From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 19:12:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 23:12:33 GMT Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> Message-ID: <00d45a34$0$20306$c3e8da3@news.astraweb.com> On Sun, 07 Sep 2008 15:59:52 -0700, John Machin wrote: > On Sep 8, 8:42?am, "James Mills" wrote: >> On Mon, Sep 8, 2008 at 8:37 AM, John Machin >> wrote: > >> > There seems to be an implicit assumption in the answers so far that >> > your mapping is a 1:1 mapping of all possible input keys. >> >> > If it doesn't include all possible input keys, answers will crash >> > with a KeyError. If there are any many:1 elements in the mapping (for >> > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code >> > in some checks for this. >> >> You are quite right! But then he/she didn't ask for this right ? :) >> >> > What do you mean by "this right"? Perhaps the Divine Right of OPs, > managers, examiners, business analysts, etc never to give a complete > spec up front and never to contemplate the consequences of Murphy's Law? I *think* that what James Mills meant was: "But then he/she didn't ask for this comma right?" -- Steven From 9847733785.man at gmail.com Thu Sep 4 10:08:01 2008 From: 9847733785.man at gmail.com (9847733785.man at gmail.com) Date: Thu, 4 Sep 2008 07:08:01 -0700 (PDT) Subject: Investments Are Faltering in Chrysler and GMAC Message-ID: Mr. Feinberg?s giant investment fund, Cerberus Capital Management, is racing to salvage multibillion-dollar investments in Chrysler, the smallest of the Detroit automakers, and GMAC, the financing arm of General Motors. But for Cerberus, named after the mythological three-headed dog who guards the gates of hell, the news keeps getting worse. On Wednesday, Chrysler, which owns the Jeep and Dodge brands, said its sales in the United States fell by a third in August ? nearly twice the industry average ? as the downturn in the auto business dragged on. Honda eclipsed Chrysler as the nation?s No. 4 seller of cars, and Nissan is closing in fast. The same day, GMAC, in which Cerberus holds a 51 percent stake, said it was trying to stanch the bleeding from a business that was supposed to be immune to the ups and downs of the car industry: home mortgage lending. GMAC and its home loan unit, Residential Capital, announced that they would dismiss 5,000 employees, or 60 percent of the unit?s staff, and close all 200 of its retail mortgage branches. It is quite a comedown for Mr. Feinberg, who founded Cerberus in 1992 with $10 million and was initially hailed as a savior at Chrysler. Over the years, Cerberus excelled by gaining control of companies in bankruptcy and nursing them back to financial health. Now, Mr. Feinberg?s purchase of Chrysler and his deal for GMAC have knocked Cerberus down a peg. ?Early on, in the Cerberus deal for Chrysler, when it first did these auto industry investments, the story was about how big and influential these funds are, that they think they can buy these iconic industrial companies,? said Colin C. Blaydon, director of the Center for Private Equity and Entrepreneurship at the Tuck School of Business at Dartmouth College. ?So far, it does not seem to be working out well for them.? Chrysler is still recovering from its split a year ago from its German partner, Daimler, and is undergoing a big revamping under Cerberus. Top executives at Cerberus have said they are determined to fix the company and that their $7.4 billion investment will pay off. A Cerberus spokesman said in a statement on Wednesday that it remained confident in its management of Chrysler and GMAC. ?No one is pleased with current market conditions,? he said. ?However, Cerberus is a patient investor and not a market timer, and we take a long-term view of our investments. Our funds are structured accordingly.? Mr. Feinberg hired Robert L. Nardelli, the former chief executive of Home Depot, to turn Chrysler around. Their plan hinges on new offerings beginning in 2010. Since Cerberus acquired Chrysler, the automaker has been trying to squeeze out costs. It has announced the elimination of 28,000 jobs and sold $500 million worth of assets. Last week, Chrysler announced that it was studying a sale of its Dodge Viper sports car business. But like its larger competitors, General Motors and Ford Motor, Chrysler has faced questions over its ability to ride out a downturn in American auto sales that is expected to stretch through 2009. All three Detroit automakers have been hit hard by the sharp decline in sales of pickup trucks, sport utility vehicles and vans that followed the rise in gas prices this year. Chrysler, which has released limited financial data since Cerberus bought it, ended June with $11.7 billion in cash and had earnings before interest, tax, depreciation and amortization of $1.1 billion in the first half of the year. But with limited access to financial data, some analysts are skeptical of its overall health. The news on Wednesday from GMAC, meantime, underscored that Cerberus also must contend with the housing slump, which has led to huge losses at lenders across the spectrum. That includes Residential Capital, which became one of the nation?s biggest mortgage providers and plunged into the market for riskier home loans that could not be sold to Fannie Mae or Freddie Mac, the mortgage finance giants that have run into trouble themselves. Now, many of those loans are defaulting as home prices fall and the economy weakens. This summer, Residential Capital and its bondholders restructured $14 billion in bonds to ease its debt burden. That restructuring and new loans from GMAC have bought the company time to work out its problems, but analysts say it may not be enough to save the firm from rising defaults on mortgages. Residential Capital bonds are trading at about 70 cents on the dollar. ?They have some time,? said Andrew Feltus, a bond fund manager at Pioneer Investments. But, he added, ?This environment is going against them.? www.my-quickloans.com/finance From steven at REMOVE.THIS.cybersource.com.au Mon Sep 22 05:32:39 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 09:32:39 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> Message-ID: On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: > Steven D'Aprano a ?crit : >> I have a class which is not intended to be instantiated. Instead of >> using the class to creating an instance and then operate on it, I use >> the class directly, with classmethods. Essentially, the class is used >> as a function that keeps state from one call to the next. >> >> The problem is that I don't know what to call such a thing! "Abstract >> class" isn't right, because that implies that you should subclass the >> class and then instantiate the subclasses. >> >> What do you call such a class? >> >> > > Err... A possible design smell ?-) > > > > More seriously: this looks quite like a singleton, which in Python is > usually implemented way more simply using a module and plain functions. I really don't know why everyone thinks I want a Singleton. I want to uncouple objects, not increase the coupling. Consider a factory function: def factory(x): # a toy example alist = [x] def foo(): return alist return foo Now suppose we "instantiate" the factory (for lack of a better term): >>> f1 = factory(0) >>> f2 = factory(0) Even though f1 and f2 have the same behaviour, they are obviously not the same object. And although both return a list [0], it is not the same list: >>> f1() == f2() == [0] True >>> f1() is f2() False They have a (very little) amount of state, which is *not* shared: >>> L = f1() >>> L.append(1) >>> f1() [0, 1] >>> f2() [0] But there's only a limited amount of state that functions carry around. I can give them more state like this: >>> f1.attr = 'x' but it isn't good enough if the function needs to refer to it's own state, because functions can only refer to themselves by name and the factory can't know what name the function will be bound to. As far as I know, the only objects that know how to refer to themselves no matter what name they have are classes and instances. And instances share at least some state, by virtue of having the same class. (Pedants will argue that classes also share state, by virtue of having the same metaclass. Maybe so, but that's at a deep enough level that I don't care.) I'm now leaning towards just having factory() instantiate the class and return the instance, instead of having to do metaclass chicanery. Because the class is built anew each time by the factory, two such instances aren't actually sharing the same class. I think that will reduce confusion all round (including mine!). Hopefully now that I've explained what I want in more detail, it won't seem so bizarre. Factory functions do it all the time. Is there a name for this pattern? Thanks to everyone who commented, your comments helped me reason out a better alternative to what I first suggested. -- Steven From gabriel.rossetti at arimaz.com Wed Sep 24 02:22:51 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 24 Sep 2008 08:22:51 +0200 Subject: python freeze help In-Reply-To: References: Message-ID: <48D9DCBB.90502@arimaz.com> Mike Driscoll wrote: > On Sep 23, 5:01 am, Gabriel Rossetti > wrote: > >> Hello everyone, >> >> I'm trying to use python's freeze utility but I'm running into problems. >> I called it like this : >> >> python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py >> ~/Documents/Code/Python/src/jester/service.py -m jester >> >> then I did : make >> >> then I tried to run it : ./service >> >> and I get this : >> >> grossetti at desktop-01:~/tmp/freeze$ ./service >> Traceback (most recent call last): >> File "/home/grossetti/Documents/Code/Python/src/jester/service.py", >> line 16, in >> from jester import constants, utils >> File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line >> 20, in >> from twisted.internet.protocol import Protocol, ClientCreator >> File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", >> line 17, in >> from zope.interface import implements >> File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in >> >> pkg_resources.declare_namespace('zope') >> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, >> in declare_namespace >> _handle_ns(packageName, path_item) >> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, >> in _handle_ns >> path = module.__path__; path.append(subpath) >> AttributeError: 'str' object has no attribute 'append' >> Error in sys.excepthook: >> Traceback (most recent call last): >> File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line >> 38, in apport_excepthook >> from apport.packaging_impl import impl as packaging >> File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in >> >> from apport.report import Report >> File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in >> >> from problem_report import ProblemReport >> File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in >> >> from email.MIMEMultipart import MIMEMultipart >> File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__ >> __import__(self.__name__) >> ImportError: No module named multipart >> > > > I've gotten this error from py2exe before. I'm not sure how freeze > works, but in py2exe I had to make sure the email package wasn't being > accidentally excluded and explicitly included. > > > I tried that (-m email), didn't work, I added -E and I get this : There are some missing modules: ['Carbon.File', 'Carbon.Folder', 'Carbon.Folders', 'EasyDialogs', 'FCNTL', 'MacOS', 'SOCKS', '_dummy_threading', '_emx_link', '_md5', '_sha', '_sha256', '_sha512', '_subprocess', '_winreg', '_xmlplus', 'ce', 'email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'gestalt', 'ic', 'java.lang', 'mac', 'msvcrt', 'nt', 'org.python.core', 'os.path', 'os2', 'pywintypes', 'riscos', 'riscosenviron', 'riscospath', 'rourl2path', 'sgi', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security'] so I tried to see if it existed : >>> import email >>> email.MIMEMultipart >>> maybe this is the problem, an email.MIMEMultipart object isn't what is returned but instead an email.LazyImporter object is, so freeze isn't happy... any ideas on how to solve this? >> Original exception was: >> Traceback (most recent call last): >> File "/home/grossetti/Documents/Code/Python/src/jester/service.py", >> line 16, in >> from jester import constants, utils >> File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line >> 20, in >> from twisted.internet.protocol import Protocol, ClientCreator >> File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", >> line 17, in >> from zope.interface import implements >> File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in >> >> pkg_resources.declare_namespace('zope') >> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, >> in declare_namespace >> _handle_ns(packageName, path_item) >> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, >> in _handle_ns >> path = module.__path__; path.append(subpath) >> AttributeError: 'str' object has no attribute 'append' >> >> Does anyone have any ideas as of why I get this? >> >> Thank you, >> Gabriel >> > > I don't know what this second error is... > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Thu Sep 11 13:16:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 19:16:40 +0200 Subject: How to Determine Name of the Day in the Week In-Reply-To: References: Message-ID: Henry Chang wrote: > Instead of getting integers with weekday(), Monday == 0 ... Sunday == 6; > is there a way to get the actual names, such as "Monday ... Sunday"? I > would like to do this without creating a data mapping. :) if you have a datetime or date object, you can use strftime with the appropriate formatting code. see the library reference for details. if you have the weekday number, you can use the calender module: >>> import calendar >>> calendar.day_name[0] 'Monday' (the latter also contains abbreviated day names, month names, and a bunch of other potentially useful functions and mappings.) From dear.jay.logan at gmail.com Mon Sep 22 09:07:47 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 22 Sep 2008 06:07:47 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: On Sep 22, 7:32?am, Sion Arrowsmith wrote: > josh logan ? wrote: > > >sorted(P) # throws TypeError: unorderable types Player() < Player() > > >The sorted function works when I define __lt__. > >I must be misreading the documentation, because I read for the > >documentation __cmp__ that it is called if none of the other rich > >comparison functions are defined. > > You're either misreading or forgetting that __eq__ and __ne__, > which you define, are rich comparison functions. __cmp__ will only > be called for a comparison when *none* of the rich comparison > functions are defined, not just the one in question. > > -- > \S -- si... at chiark.greenend.org.uk --http://www.chaos.org.uk/~sion/ > ? ?"Frankly I have no feelings towards penguins one way or the other" > ? ? ? ? -- Arthur C. Clarke > ? ?her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump Hello Sion, When I don't define the __eq__ and __ne__ comparison functions, the same unexpected behavior occurs. From god1124 at gmail.com Fri Sep 5 02:59:37 2008 From: god1124 at gmail.com (Dream) Date: Thu, 4 Sep 2008 23:59:37 -0700 (PDT) Subject: Tkinter Radio button on the second window References: Message-ID: <351395f5-5052-4722-97ea-e568db4d6fc6@o40g2000prn.googlegroups.com> Thank you very much. Now I use "window2=Toplevel()" to create the second window, and it works well. From iphthfu02 at sneakemail.com Tue Sep 2 12:27:29 2008 From: iphthfu02 at sneakemail.com (Dani) Date: 2 Sep 2008 16:27:29 -0000 Subject: Library/project for making an invitation-only website? Message-ID: <7502-61941@sneakemail.com> Hi. I want to create a website where new users need to be invited by an existing user in order to open an account. Think of it the way Orkut became popular. I need a library, or code from some project, that sends the invitations, keeps track of which user invited who, etc. I'm sure there's already some code out there that performs these tasks. Drupy maybe? Could anybody recommend me some library/project for these tasks? Thank you in advance. From geoff.bache at jeppesen.com Wed Sep 10 16:52:37 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Wed, 10 Sep 2008 13:52:37 -0700 (PDT) Subject: Persuading ConfigParser to give me the section elements in the same order as the file Message-ID: <4566f721-028d-4079-90d8-7818d69d18b3@34g2000hsh.googlegroups.com> Hi all, I recently needed to parse a file that was perfect for ConfigParser apart from one thing: the elements in the sections, although definitions, could in some cases clash with each other and therefore it was important to be able to retrieve them in the same order as they appeared in the file. Unfortunately ConfigParser uses ordinary dictionaries for the section elements and they are therefore returned in an arbitrary order. The only solution I found was to copy ConfigParser.py and replace all the dictionaries with "sequential dictionaries" which are exactly like dictionaries except that elements are returned in the order they were inserted. (see http://home.arcor.de/wolfgang.grafen/Python/Modules/seqdict/Seqdict.html) I wonder if there was a better way? For example, is there any hook that could modify what is created by the statement x = {} I tried setting __builtins__.dict = ndict.seqdict But that didn't seem to have any effect on the above statement. As a secondary question, I find sequential dictionaries to be an essential part of programming in Python and I use them all the time. I wondered a bit if there were any plans or proposals to include them as part of the Python library? Regards, Geoff Bache From castironpi at gmail.com Sat Sep 27 08:18:33 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 05:18:33 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> Message-ID: <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> On Sep 26, 1:04?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 26, 11:43?am, "Tim Rowe" wrote: > > > 2008/9/26 Steven D'Aprano : > > > > I don't have any objective numbers, but subjectively it seems to me that > > > the number of spams is significantly higher, but not so high as to be a > > > major nuisance. > > > I consider *any* spam to be a major nuisance, but I don't see them as > > being the fault of python-list which seems to do a pretty good job of > > blocking them > > I think in June and July they were selling watches a lot which I > haven't noticed recently. Gucci 104 G-Bandeau Watches - Gucci Watches Discount Rolex Oyster Perpetual Lady Datejust Pearlmaster 18kt Yellow Gold Diamond Ladies Watch 80318C Cartier Must 21 Watches - Cartier Watches Discount I speak too soon. From bdesth.quelquechose at free.quelquepart.fr Tue Sep 23 13:23:16 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 19:23:16 +0200 Subject: finding domain name In-Reply-To: References: Message-ID: <48d941f0$0$3738$426a74cc@news.free.fr> Bobby Roberts a ?crit : > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/xxxxx/ > > where xxxxx represents the domain name. > > How can I find the domain name of the current url being viewed. What are you using exactly ? cgi ? wsgi ? Else ? From fredrik at pythonware.com Mon Sep 1 11:52:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Sep 2008 17:52:31 +0200 Subject: Printing list of dates starting today In-Reply-To: <4v1ob4tgk0u4jhtobisaid1g9pst0ic011@4ax.com> References: <4v1ob4tgk0u4jhtobisaid1g9pst0ic011@4ax.com> Message-ID: Luka Djigas wrote: > please, I need your help. I'm new to python, so I don't know if this > will seem like a stupid question to some of you ... > I have a need to write to a file (or just print on screen, that part > doesn't matter at this point) a list of dates, starting today. For > example: > > 02.09.2008. tue > 03.09.2008. wed > et cetera > > Is there some intristic function in python which can help me with this > or do I have to do the calendar calculation by hand ? >>> import datetime >>> # see: http://docs.python.org/lib/module-datetime.html >>> d = datetime.date.today() >>> str(d) '2008-09-01' >>> d.strftime("%d.%m.%Y. %a") '01.09.2008. Mon' >>> # see http://docs.python.org/lib/module-time.html#l2h-2826 >>> d.strftime("%d.%m.%Y. %a").lower() '01.09.2008. mon' >>> for i in range(10): ... print d.strftime("%d.%m.%Y. %a").lower() ... d += datetime.timedelta(days=1) ... 01.09.2008. mon 02.09.2008. tue 03.09.2008. wed 04.09.2008. thu 05.09.2008. fri 06.09.2008. sat 07.09.2008. sun 08.09.2008. mon 09.09.2008. tue 10.09.2008. wed From callen314 at gmail.com Thu Sep 11 17:02:25 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 11 Sep 2008 14:02:25 -0700 (PDT) Subject: Adding environment variables to bash. References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> <48c97eaf$0$12022$426a74cc@news.free.fr> Message-ID: On Sep 11, 10:25 am, nntpman68 wrote: > >> doesn't exactly work for Python scripts, though: > > >> $ cat env.py > >> #!/usr/bin/env python > >> import os > >> os.environ["TEST"] = "hello" > > >> $ . ./env.py && env | grep TEST > >> import: unable to open X server `'. > >> bash: os.environ[TEST]: command not found > > >> > > There's two options for the desperate ones. > > 1. Assuming the python script doesn't want to print anything useful > ========================================================================= > > the python script just prints the exoprt commands and is > being called via backticks from a shell code snipped being sourced with . > > #-------- mypythonfile.py ------------------------ > #!/usr/bin/env python > value = myfavourite_python_function() > print 'export ENV_VAR="%s"' ^ value > #--------------- end of file -------------- > > #----------------- my_wrapper_file.sh ------------------ > `./mypythonfile.py` > # file end > > and then you call > . ./my_wrapper_file.sh > > 2._ Pytho script wants to display something and set a variable > =================================================================== > > a file being invoked with . calls the python script (which will create a > small file with variables to be set). > then this created file is being sourced > > #-------- mypythonfile.py ------------------------ > #!/usr/bin/env python > value = myfavourite_python_function() > file('my_export_commands.sh','w').write('export ENV_VAR="%s"\n' % value) > #--------------- end of file -------------- > > #----------------- my_wrapper_file.sh ------------------ > ./mypythonfile.py > . ./my_export_commands.sh > # file end > > bye > > N > > Fredrik Lundh wrote: > > John Lawrence wrote: > > >> You can make a command use the current shell though if you use the '.' > >> command e.g.: > > >> jl > cat env.sh > >> export TEST='hello' > > >> jl > ./env.sh && env | grep TEST #Doesn't set TEST in parent > >> shell > >> jl > . ./env.sh && env | grep TEST #Adding '. ' before the > >> command uses the same shell > >> TEST=hello > > > doesn't exactly work for Python scripts, though: > > > $ cat env.py > > #!/usr/bin/env python > > import os > > os.environ["TEST"] = "hello" > > > $ . ./env.py && env | grep TEST > > import: unable to open X server `'. > > bash: os.environ[TEST]: command not found > > > oooh, clever but also... teh evil! Ok not evil, but teh not-pretty. But you did say "for the desperate" so good on you. cheers. From hrishys at yahoo.co.uk Thu Sep 25 06:12:54 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 10:12:54 +0000 (GMT) Subject: Linq to Python In-Reply-To: Message-ID: <180155.11709.qm@web27406.mail.ukl.yahoo.com> Hi Grant haha :-) i discounted that perspective :-) regards Hrishy --- On Thu, 25/9/08, Grant Edwards wrote: > From: Grant Edwards > Subject: Re: Linq to Python > To: python-list at python.org > Date: Thursday, 25 September, 2008, 2:22 AM > On 2008-09-24, Bruno Desthuilliers > wrote: > > hrishy a ?crit : > > (snip) > > > > > >> I apologise > >> (I thought Python programmers were smart and they > did know what LINQ was) > > > > Is there really any relation between "being > smart" and knowing anything > > about the latest MS fad ? > > God, I hope not -- or I'd rather be stupid. > > -- > Grant > > -- > http://mail.python.org/mailman/listinfo/python-list From arnodel at googlemail.com Fri Sep 12 16:59:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 12 Sep 2008 13:59:49 -0700 (PDT) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> <005ca418-9e1a-424b-b4d4-823427584424@x35g2000hsb.googlegroups.com> Message-ID: On Sep 12, 4:30?pm, Bojan Mihelac wrote: > On Sep 12, 5:21?pm, Christian Heimes wrote: > > > Bojan Mihelac wrote: > > > I guess A class not yet exists in line 4. Is it possible to achive > > > adding dynamic attributes without using exec? > > > Correct, the class doesn't exist until the end of the class body. You > > can either do it outside the class definition or you can use a metaclass. > > > Christian > > thanks, can you give example on using a metaclass? class MoreMeta(type): def __init__(self, name, bases, attrs): more = attrs.get('moreattrs') if more: for attr, val in more.iteritems(): setattr(self, attr, val) class MoreObject(object): __metaclass__ = MoreMeta class A(MoreObject): moreattrs = {} for i in '12': moreattrs['title_' + i] = int(i) >>> A.title_1 1 >>> A.title_2 2 >>> -- Arnaud From castironpi at gmail.com Thu Sep 4 23:28:34 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 20:28:34 -0700 (PDT) Subject: xml + mmap cross References: <6a7336f2-8f71-47c2-88d5-d5172f14ce44@k36g2000pri.googlegroups.com> Message-ID: On Sep 4, 7:54?pm, alex23 wrote: > On Sep 4, 8:31?am, castironpi wrote: > > > Any interest in pursuing/developing/working together on a mmaped-xml > > class? ?Faster, not readable in text editor. > > XML is text-based, so it should -always- be readable in a text editor. > It's part of the definition, I believe. > > However, an implementation of one of the alternative binary XML > formats would probably be very welcome. > > Fast Infoset:http://www.itu.int/rec/T-REC-X.891-200505-I/en > EXI:http://www.w3.org/TR/2007/WD-exi-20070716/ > > I don't know enough about either format to say if it would be > possible, but an implementation that conformed to the ElementTree API > could be a big win. I was thinking something much less restrictive than the two links. Since it's not text, I'm not sure it event counts as structured markup. More generic, something like hierarchical 'tag-content-child' pairs. Here's what the xml.etree.ElementTree API says: Each element has a number of properties associated with it: - a tag which is a string identifying what kind of data this element represents (the element type, in other words). - a number of attributes, stored in a Python dictionary. - a text string. - an optional tail string. - a number of child elements, stored in a Python sequence Since all of these would be buffer-based representations, the attribute list would merely implement the mapping-object protocol, not be in a true dictionary. The strings would be stored as offsets to length-prefixed buffer segments. Each node would look roughly like: tag_offset, first_attr, text_offset, tail_offset, first_child, prev_sibling, next_sibling, parent Attributes would look like: key_offset, value_offset, prev_attr, next_attr, node These are all integers representing offsets elsewhere into the map. A short observation: >>> a= e.XML( 'abc' ) >>> a.getchildren()[0].text 'abc' >>> a.getchildren()[0].text= 'ab<' >>> e.tostring(a) 'ab<' >>> e.XML(_) >>> _.getchildren()[0].text 'ab<' The current implementation supports round trips between special characters '<' and markup '<', which I propose to support as well. Of course, you'd have to garbage collect removed nodes by hand, on any deletions. Also, poss. change subject to: ElementTree + mmap cross. From deets at nospam.web.de Tue Sep 2 11:16:17 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Sep 2008 17:16:17 +0200 Subject: dict.update In-Reply-To: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> Message-ID: <6i53m1Fo1a1aU1@mid.uni-berlin.de> Mike P schrieb: > Hi All, > > I have two dictionaries e.g > dict1 = {123:3,234:5,456:3} > dict2 = {123:4,157:2,234:5,456:3,567:2} > > I want to merge these two dictionaries together so i have a resultant > dictionary of: > > dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]} > > As later on i want to write a csv file that would have the form > > id var1 var2 > 123 4 3 > 157 2 0 > > i looks like the dict.update looks almost there but i can't get it to > work properly, can anyone offer any advise? > res = {} for d in dict1, dict2: for key, value in d.iteritems(): res.setdefault(key, []).append(value) Diez From rogeruclan at gmail.com Wed Sep 17 08:23:47 2008 From: rogeruclan at gmail.com (RLC) Date: Wed, 17 Sep 2008 05:23:47 -0700 (PDT) Subject: help on python SWIG C++ extension References: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> Message-ID: Thanks a lot, Tim and Diez, Merci Beaucoup!! I strongly suspect the error was caused by the memory operation. I made some modifications only on PolygonMesh definition. And now I have no annoying warnings. PolygonMesh *new_PolygonMesh() { PolygonMesh *p = new PolygonMesh; // p = (PolygonMesh *)malloc(sizeof(PolygonMesh)); // p->vertices.clear(); // p->polygonNbVertices.clear(); // p->polygonStartVertexIndex.clear(); // p->polygonVerticesIndices.clear(); // p->uvs.clear(); // p->polygonNbUVs.clear(); // p->polygonStartUVIndex.clear(); // p->polygonUVsIndices.clear(); return p; } void delete_PolygonMesh(PolygonMesh *p) { free(p); } when I run below script, it works well without any warning #!/usr/local/bin/python import tdimport a = tdimport.PolygonMesh() a.appendvertex(tdimport.Vertex(0.0,0.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,0.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,0.0)) a.appendvertex(tdimport.Vertex(0.0,1.0,0.0)) a.appendvertex(tdimport.Vertex(0.0,0.0,1.0)) a.appendvertex(tdimport.Vertex(1.0,0.0,1.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,1.0)) a.appendvertex(tdimport.Vertex(0.0,1.0,1.0)) a.appendpolygon([0,3,2,1]) a.appendpolygon([0,1,5,4]) a.appendpolygon([1,2,6,5]) a.appendpolygon([2,3,7,6]) a.appendpolygon([0,4,7,3]) a.appendpolygon([4,5,6,7]) print a.getpolygonverticesindices(0) print a.getpolygonverticesindices(1) print a.getpolygonverticesindices(2) print a.getpolygonverticesindices(3) print a.getpolygonverticesindices(4) print a.getpolygonverticesindices(5) del a Thanks again. Have a good day!!! Regards Roger On Sep 17, 8:16 am, Tim Roberts wrote: > RLC wrote: > > >I am new to python SWIG. Recently I wrote a small program trying to > >import collada files(using colladadom) into python so I could use > >python cgkit to render them. However, during the progressing, I got > >some problems. Every time I quit from Python, I get a segmentation > >fault, although the main program runs well. I suspect it is because I > >wrapped std::vector objects in C struct and I did not release the > >memory properly. > > That won't cause a segmentation fault. However, I notice that you are > using "malloc" and "free" to allocate and free your objects. "stl" will > use "new" and "delete", and it's not always healthy to mix them. If I were > you, I'd replace this: > > > Vertex *v; > > v = (Vertex *)malloc(sizeof(Vertex)); > > with this, which is less typing: > Vertex * x = new Vertex; > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From bearophileHUGS at lycos.com Mon Sep 1 19:55:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Sep 2008 16:55:33 -0700 (PDT) Subject: Py 2.6 changes References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <00cc7976$0$20302$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano: > productory() -- I don't know that function, and googling mostly comes up > with retail product searches. Do you mean product(), Darn my English, you are right, sorry, I meant a product() of course :-) Bye, bearophile From cjw at ncf.ca Sat Sep 20 07:12:42 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 20 Sep 2008 07:12:42 -0400 Subject: Not fully OO ? In-Reply-To: <48d4c11b$0$22877$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: candide wrote: > Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > > Thanks for any comment. "foreach: for x in array: statements Loops over the array given by array. On each iteration, the value of the current element is assigned to x and the internal array pointer is advanced by one. " This could be a useful addition to Python. numarray is no longer supported. It has been supplanted by numpy. How is OOP defined? Colin W. From mail at microcorp.co.za Sun Sep 21 01:51:32 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 21 Sep 2008 07:51:32 +0200 Subject: Ascii Menu I/O redirection Message-ID: <000f01c91bb0$e395a900$0d00a8c0@hendrik> Steven D'Aprano wrote: >I'm not sure that closing stdin and stout are a good idea. This could >have side-effects for other parts of your program, and will almost >certainly end badly if you're running in the interactive interpreter. > Its a very simple thingy - there will only ever be one object - "The Console", or "The Connection" The close stuff was there because I thought it would be better to close the RS-232 port if I were using it. I only close it right at the end before exiting - but you are right. - if I invoke the interpreter with -i then it will be seriously broken. >Other than that, what you've done seems reasonable, although since every >instance of console() has the same state, I'd write it slightly >differently: > >class console(object): > """ > This spoofs a single file like object, using stdout & - in > (Minimalistic proof of concept implementation) > """ > read = sys.stdin.read > readline = sys.stdin.readline > write = sys.stdout.write > flush = sys.stdout.flush > closeout = sys.stdout.close > closein = sys.stdin.close > @classmethod > def close(cls): > cls.closein() > cls.closeout() Thanks. It looks neater without all the "self"s. Seems to me the next time someone complains about 'self' he should be told : "use class attributes and methods, and only one instance" *WEG* >> Questions are: >> >> Is this a reasonable way of doing this kind of thing? Is there a >> canonical or better way of doing it? Am I missing something? > >It seems to me that you might have been better off to write your program >to take two files, an input and an output, instead of forcing both to go >to the same file. > >if 'serial' in sys.argv: # for RS-232 i/o to terminal > infile = open('/dev/ttyS0','r+b') > outfile = infile > else: # console i/o > infile = sys.stdin > outfile = sys.stdout > This is weird - This is exactly how I started off - and then I thought about the errors, and I did not want to pass three files, so I started looking for one. :-) Reading your response, and thinking about what I have done, I get the feeling that its all too complicated - What I will probably end up doing would be to pass no file, and just use standard print statements and sys.stdin.readline, etc. Then if I redirect the stdin,-out and -err, the thing is sorted, without the necessity of jumping through OO hoops, as this class is the only one in the programme - all the rest are functions. It is impossible to think clearly all of the time. It is difficult to think clearly most of the time. In fact it is nice to have an occasional lucid thought... >Hope this helps. Yes it has. - Thanks for the input. - Hendrik -- Robert Wilensky: We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of William Shakespeare. Now, thanks to the Internet, we know this not true. From mercado949 at gmail.com Fri Sep 5 11:29:39 2008 From: mercado949 at gmail.com (mercado mercado) Date: Fri, 5 Sep 2008 11:29:39 -0400 Subject: Retrieving the name of the class calling an instance method Message-ID: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> In Python, is it possible for an instance method to know the name of the class which is calling it? For example, in the sample below, I would like for the someMethod method to print the name of the class calling it ("bar" in the first case, "again" in the second). --------------------------------------- class foo(): def someMethod(self): print x class bar(): def __init__(self): f = foo() f.someMethod() class again(): def __init__(self): f = foo() f.someMethod() bar() again() --------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From xpahos at gmail.com Fri Sep 5 07:28:14 2008 From: xpahos at gmail.com (phasma) Date: Fri, 5 Sep 2008 04:28:14 -0700 (PDT) Subject: Python and Cyrillic characters in regular expression References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> Message-ID: string = u"??????" (u'\u041f\u0440\u0438\u0432\u0435\u0442',) string = u"Hi.??????" (u'Hi',) On Sep 4, 9:53?pm, Fredrik Lundh wrote: > phasma wrote: > > Hi, I'm trying extract all alphabetic characters from string. > > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE) > > buf = re.match(string) > > > But it's doesn't work. If string starts from Cyrillic character, all > > works fine. But if string starts from Latin character, match returns > > only Latin characters. > > can you provide a few sample strings that show this behaviour? > > From uomiocenekidd at gmail.com Mon Sep 22 06:38:48 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:38:48 -0700 (PDT) Subject: download redtube videos - Free Message-ID: <0959566b-79a1-4b3f-a0ab-69f176b577f3@z66g2000hsc.googlegroups.com> download redtube videos . . . *******CLICK HERE******** http://vids365.cn/download-redtube-videos ***************************** . . . . . . . . . . . . download redtube videos From timr at probo.com Sat Sep 6 21:55:43 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 07 Sep 2008 01:55:43 GMT Subject: atomic section in code References: Message-ID: "Hendrik van Rooyen" wrote: > >Fredrik Lundh wrote: > >>sounds like he wants/needs non-cooperative, mandatory locking. More accurately, he THINKS he wants/needs mandatory locking. We need to find out what he's really trying to accomplish before we can suggest something that is actually achievable. >Could one get there using ctypes to disable interrupts? No. That can't be done in user mode in any operating system where Python runs. Even in kernel mode, it's not reliable, because disabling interrupts only affects one core. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dullrich at sprynet.com Tue Sep 9 11:58:06 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 09 Sep 2008 10:58:06 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: In article , bearophileHUGS at lycos.com wrote: > David C. Ullrich: > > I didn't mention what's below because it doesn't seem > > likely that saying max([]) = -infinity and > > min([]) = +infinity is going to make the OP happy... > > Well, it sounds cute having Neginfinite and Infinite as built-int > objects that can be compared to any other type and are < of or > of > everything else but themselves. Like I said, I'm not going to say anything about how Python should be. If I were going to comment on that I'd say it would be cute but possibly silly to actually add to the core. But in the math library I made some time ago there was an AbsoluteZero with the property that when you added it to x you got x for any x whatever (got used as the default additive identity for classes that didn't have an add_id defined...) > Probably they can be useful as > sentinels, but in Python I nearly never use sentinels anymore, and > they can probably give some other problems... > > Bye, > bearophile -- David C. Ullrich From steve077 at gmail.com Wed Sep 17 13:18:31 2008 From: steve077 at gmail.com (Dude) Date: Wed, 17 Sep 2008 10:18:31 -0700 (PDT) Subject: Tkinter Label 'justify' Problem Message-ID: <8c8a2d86-007b-4e38-b0fc-bc6385b3a77a@t54g2000hsg.googlegroups.com> Hi All, I am fairly new to Python programming. I am working on a small Tkinter project and I think I am missing something, maybe you can help. The two lines below is all I have related to the Label widget: lblServer = Tkinter.Label(serverFrame, text='Server:', fg='black', justify='left', relief='groove') lblServer.place_configure(width=200, bordermode='inside') No matter what I change the 'justify' to whether it's 'lef', 'right', or 'center', it always seems to be in the center. I am also writing the keys from the Label widget to a file because this has me so baffled. That is below. Thank in advance for any help or direction you can give me. Steve P ---------- lblServer keys ----------------- activebackground : SystemButtonFace activeforeground : SystemButtonText anchor : center background : SystemButtonFace bd : 2 bg : SystemButtonFace bitmap : borderwidth : 2 compound : none cursor : disabledforeground : SystemDisabledText fg : black font : {MS Sans Serif} 8 foreground : black height : 0 highlightbackground : SystemButtonFace highlightcolor : SystemWindowFrame highlightthickness : 0 image : justify : left padx : 1 pady : 1 relief : groove state : normal takefocus : 0 text : NNTP Server: textvariable : underline : -1 width : 0 wraplength : 0 ---------- lblServer keys END ------------- From code at pizzashack.org Tue Sep 2 09:28:42 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 09:28:42 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i4pq5Fol29aU1@mid.uni-berlin.de> References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> Message-ID: <20080902132842.GP29228@dragontoe.org> On Tue, Sep 02, 2008 at 12:27:49PM +0000, Marc 'BlackJack' Rintsch wrote: > > The Python class is a generalization of the standard Posix function of > > (almost) the same name: > > http://opengroup.org/onlinepubs/007908775/xsh/popen.html > > So it's a name of a *function* and it's a little bit unsuitable for a > *class*. As Jeremy wrote: the instances represent *processes* not > "popen"s, whatever that may be. I would argue that they don't represent processes at all; the object is a set of files which connect the standard I/O streams of a subprocess to its parent, and methods to operate on those files. The C library's popen() function, on which this class is based, provides a means to open a file and connect it to the standard steams of a subprocess, making it more closely analogous to what the Popen class does/provides. As such, "Popen" is a better name to describe this object than "subprocess" would be. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jan.patrick.schaefer at googlemail.com Sun Sep 7 06:30:58 2008 From: jan.patrick.schaefer at googlemail.com (Jan =?UTF-8?B?U2Now6RmZXI=?=) Date: Sun, 07 Sep 2008 12:30:58 +0200 Subject: unexpected class behaviour Message-ID: <48c3ad5d@news.uni-ulm.de> Hi all, can anyone explain the behaviour of the following code sniplet: ---> schnipp <--- class Base(object): def __init__( self, lst=[] ): self.varlist = lst def addVar( self, var ): self.varlist.append(var) class Derived(Base): def __init__( self, var ): Base.__init__(self) self.addVar(var) vars = ['foo', 'bar'] for ivar in vars: obj = Derived(ivar) print ivar, obj, obj.varlist ---> schnapp <--- After running (Python 2.5.1), I get the following output: foo <__main__.Derived object at 0xb7c608cc> ['foo'] bar <__main__.Derived object at 0xb7c6092c> ['foo', 'bar'] So, I get two different objects, but how does the 'foo' get into the second varlist? I'm a little bit confused about this, any ideas? Thanks in advance Jan From nospam at example.com Sun Sep 28 05:21:30 2008 From: nospam at example.com (Erhard) Date: Sun, 28 Sep 2008 02:21:30 -0700 Subject: Calculating timespan Message-ID: I've been looking at the date/time classes and I'm at a loss as to how to do this (probably too used to other platforms). I have two date/time values. One represents 'now' and the other the last modified time of a file on disk (from stat). I need to calculate the difference in time (i.e., a 'timespan') between the two so I can tell if the file has been modified in the past X minutes and do something to it. Thanks =) From rf.egnaro at evetsrellum Sat Sep 20 12:27:55 2008 From: rf.egnaro at evetsrellum (Thoma) Date: Sat, 20 Sep 2008 18:27:55 +0200 Subject: How to make a reverse for loop in python? In-Reply-To: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <48d5248b$0$909$ba4acef3@news.orange.fr> Alex Snast a ?crit : > Hello > > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) for (i = 0; i < 10; i--) -> for i in range(10): for (i = 10; i >= 0; --i) -> for i in range(10,-1,-1): Thoma From simon.hibbs at gmail.com Wed Sep 17 09:05:59 2008 From: simon.hibbs at gmail.com (Simon Hibbs) Date: Wed, 17 Sep 2008 06:05:59 -0700 (PDT) Subject: Python OOP advice References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> <6089e023-18f6-4c93-a2a4-f933eac786b5@f63g2000hsf.googlegroups.com> Message-ID: <9317b769-0569-4ccf-b800-c400328ff579@m36g2000hse.googlegroups.com> Great contributions, thanks both of you. I'm self-tought when it comes to Python and OOP and I haven't yet grown an intuitive feel for how to do things sensibly. Simon From tino at wildenhain.de Fri Sep 26 07:23:04 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 13:23:04 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48dcc0ce$0$25400$426a34cc@news.free.fr> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> Message-ID: <48DCC618.9040907@wildenhain.de> Hi, Bruno Desthuilliers wrote: > bcurtu a ?crit : >> Hi, >> >> I have a BIIIIIG problem with the next query: >> >> cursor.execute(""" >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """,( eid_list)) >> >> eid_list is suppossed to be a list of ids = [1,5,9] >> >> How can I make it work? > > You have to build your sql statement in three stages: > > # stage 0: the template > sql_template = """ > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """ > > # stage 1: build correct place_holders string for the actual number > # of items in eid_list > place_holders = ", " .join("%s" for x in xrange(len(eid_list))) Hm. either ", ".join(["%s"]*len(eid_list)) or ", ".join("%s" for x in eid_list) should produce the same, wouldn't it? :-) > # stage 2 : build the effective sql statement > sql = sql_template % place_holders > > # ok, let's go: > cursor.execute(sql_template, eid_list) > > > NB : you can of course make it in a single statement, but readability > will suffer: > > cursor.execute( > """ > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """ % ", " .join("%s" for x in xrange(len(eid_list))), > eid_list > ) I'd think giving the arguments in a form of an array type should work too. At least in postgres there are references to do so. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From jaime.dyson at gmail.com Fri Sep 5 14:11:13 2008 From: jaime.dyson at gmail.com (jaime.dyson at gmail.com) Date: Fri, 5 Sep 2008 11:11:13 -0700 (PDT) Subject: "Full" element tag listing possible with Elementtree? References: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Message-ID: <7c184580-00ee-40ff-bcc0-1b2a60134fe0@i20g2000prf.googlegroups.com> On Sep 4, 11:43?pm, Fredrik Lundh wrote: > jaime.dy... at gmail.com wrote: > > > > ? this is node b > > ? this is node c > > ? ? > > ? ? this is node e > > ? > > ? this is node f > > > > > I would want to print the following: > > > > > > > text: this is node b > > > > text: this is node c > > > > > > text: this is node e > > > > this is node f > > > Is there a simple way to do this? ?Any help would be appreciated. > > in stock ET, using a parent map is probably the easiest way to do this: > > ? ? ?http://effbot.org/zone/element.htm#accessing-parents > > that is, for a given ET structure "tree", you can do > > parent_map = dict((c, p) for p in tree.getiterator() for c in p) > > def get_parents(elem): > ? ? ?parents = [] > ? ? ?while 1: > ? ? ? ? ?elem = parent_map.get(elem) > ? ? ? ? ?if elem is None: > ? ? ? ? ? ? ?break > ? ? ? ? ?parents.append(elem) > ? ? ?return reversed(parents) > > for elem in tree.getiterator(): > ? ? ?print list(get_parents(elem)), elem > > Fantastic. Thank you very much, Fredrik! And thanks for ET! From manfredpssnd6 at googlemail.com Tue Sep 23 14:44:34 2008 From: manfredpssnd6 at googlemail.com (manfredpssnd6 at googlemail.com) Date: Tue, 23 Sep 2008 11:44:34 -0700 (PDT) Subject: FREE INTERNATIONAL TRADE LEADS Message-ID: <4b1b2e21-0732-40d7-a3aa-07320f4905ef@k37g2000hsf.googlegroups.com> http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# From mail at timgolden.me.uk Tue Sep 16 04:04:49 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 09:04:49 +0100 Subject: PyMarshal Commands crash on Windows In-Reply-To: References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> Message-ID: <48CF68A1.2070805@timgolden.me.uk> spammaster.10.webmaster at spamgourmet.com wrote: > Hi! > > Any ideas on it? (Haven't got the original post in front of me, but I'll guess anyway...) Was the Python you're using built with one compiler and runtime, while the extension / embedee you're building is built with another? I ask because the most frequently-touted example of cross-compiler or cross-runtime incompatibility on Windows is the FILE* structure. And I seem to remember you're using that to write the marshalled objects out.... ... just a wild guess TJG From tkpmep at hotmail.com Tue Sep 30 11:09:49 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Tue, 30 Sep 2008 08:09:49 -0700 (PDT) Subject: Finding subsets for a robust regression References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> Message-ID: <441304ca-64e3-4ba2-bd18-5752cbb4bf23@y79g2000hsa.googlegroups.com> Thank you everyone, for your input. The help is much appreciated. Thomas Philips From bearophileHUGS at lycos.com Mon Sep 8 09:55:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 8 Sep 2008 06:55:52 -0700 (PDT) Subject: Dictionaries and loops References: Message-ID: Few solutions, not much tested: data = """{None: ['User-ID', 'Count']} {None: ['576460847178667334', '1']} {None: ['576460847178632334', '8']}""" lines = iter(data.splitlines()) lines.next() identity_table = "".join(map(chr, xrange(256))) result = {} for line in lines: parts = line.translate(identity_table, "'[]{},").split() key, val = map(int, parts[1:]) assert key not in result result[key] = val print result (With Python 3 finally that identity_table can be replaced by None) # -------------------------------------- import re patt = re.compile(r"(\d+).+?(\d+)") lines = iter(data.splitlines()) lines.next() result = {} for line in lines: key, val = map(int, patt.search(line).groups()) assert key not in result result[key] = val print result # -------------------------------------- from itertools import groupby lines = iter(data.splitlines()) lines.next() result = {} for line in lines: key, val = (int("".join(g)) for h,g in groupby(line, key=str.isdigit) if h) assert key not in result result[key] = val print result Bye, bearophile From fredrik at pythonware.com Fri Sep 5 13:30:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 19:30:33 +0200 Subject: atomic section in code In-Reply-To: <6ici7gFo8e4nU1@mid.uni-berlin.de> References: <6ici7gFo8e4nU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > AFAIC that kind of mutual exclusion is what atomicity is about. What > else do you expect to happen? sounds like he wants/needs non-cooperative, mandatory locking. From spamcomefindmeplease at gmail.com Sat Sep 27 05:21:06 2008 From: spamcomefindmeplease at gmail.com (peppergrower) Date: Sat, 27 Sep 2008 02:21:06 -0700 (PDT) Subject: Using the 'with' statement with cStringIO objects Message-ID: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> I've been experimenting with the 'with' statement (in __future__), and so far I like it. However, I can't get it to work with a cStringIO object. Here's a minimum working example: ### from __future__ import with_statement import cStringIO teststring='this is a test' with cStringIO.StringIO(teststring) as testfile: pass ### I get the following error message: Traceback (most recent call last): File "testfile.py", line 6, in with cStringIO.StringIO(teststring) as testfile: AttributeError: 'cStringIO.StringI' object has no attribute '__exit__' So, I'm guessing you can't use the 'with' statement with cStringIO objects? Is this a bug, or do I need to use the 'with' statement differently to get this to work? Thanks, peppergrower From lekin2 at llnl.gov Fri Sep 19 17:10:37 2008 From: lekin2 at llnl.gov (lekin2 at llnl.gov) Date: Fri, 19 Sep 2008 14:10:37 -0700 Subject: ScrolledCanvas/ScrolledText Message-ID: <20080919141037.ra7p3opugc4s4w8o@www-openlabnet.llnl.gov> So what the heck is going on. I have a Pmw.ScrollingCanvas and inside I put a Pmw.ScrollingText and that all works but I can't get it to scroll. I was thinking I needed an event like: self.sc = Pmw.ScrolledCanvas(parent, borderframe = 5, labelpos = 'n', usehullsize = 1, hull_width = 700, hull_height = 500, hscrollmode = 'static', vscrollmode = 'static',) self._title = Pmw.ScrolledText(self.sc.interior(), labelpos = 'w', text_wrap='word', usehullsize=1, hull_height= 50, hull_width=500) titleVal = "Equation of state for %s" % (materialName) self._title.insert(1.0, titleVal) self._title.component("label").config(text="Title:") self.sc.component('canvas').bind('', self.scrolling) def scrolling(self, event): x = self.sc.canvasx(event.x) y = self.sc.canvasy(event.y) self.sc.resizescrollregion() From deets at nospam.web.de Thu Sep 11 08:35:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Sep 2008 14:35:26 +0200 Subject: problem with interpreter References: <04e1cbd4-7116-4209-b814-6d34e4d24975@l42g2000hsc.googlegroups.com> Message-ID: <6ishkuFb33rU1@mid.uni-berlin.de> chusky wrote: > Hi ! > > I have Python installed on C:\Python25 > Yesterday I added new "wx" library to the Python > > when I run C:\Python25\python.exe from the command line there is a > problem with finding libraries: > > C:\Python25>python.exe > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import wx > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\__init__.py", > line 45, > in > from wx._core import * > File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", > line 5, in < > module> > import new > File "new.py", line 1 > import > ^ > SyntaxError: invalid syntax >>>> > > > ///////////////////// > > .... that problem doesn't exist when I run python.exe from different > location (C:\, D:\) with python in the system path Do you by any chance have a file "new.py", or new.pyc lying around? It's always a bad idea to name your own modules after standard-modules (new is a standard-module), as they might get picked up first. Diez From lie.1296 at gmail.com Tue Sep 30 14:39:12 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 30 Sep 2008 18:39:12 +0000 (UTC) Subject: r"" References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> <33077c9c-01d9-4423-afd2-7452117bc6b4@j22g2000hsf.googlegroups.com> Message-ID: On Tue, 30 Sep 2008 10:50:01 -0700, Kyle Hayes wrote: >> Please describe the actual problem you're trying to solve. In what way >> do slashes need to be "fixed," and why? > > Well, I have decided to build a tool to help us sync files in UNC paths. > I am just building the modules and classes right now so I haven't > developed the frontend yet. I am assuming when the user provides a path > (either by typing it in, or pulling it in from a config file), the UNC > slashes are going to escape stuff in the string, so I want to double > them up. > > I understand if the best way is to convert all the slashes to double- > slashes. But the 'r' function seemed so handy and convenient. You don't need to. Python's string is never escaped in-memory, it is only escaped when repr(s) is called (the interpreter's implicit print uses repr () instead of str()). And that means all string coming and going to/from IO (file, GUI, etc) is stored as-is. However, strings that comes from source code or interpreter prompt (a.k.a. literal string) needs to be escaped. Analogy: When you're writing a string in the source code, you add double quotes (""), right? But do you think the quotes are stored in memory? No, it's just an escape character to differentiate a string from its surrounding. From afriere at yahoo.co.uk Mon Sep 8 01:13:20 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Sun, 7 Sep 2008 22:13:20 -0700 (PDT) Subject: lacking follow-through References: Message-ID: On Sep 8, 7:00 am, castironpi wrote: > I am concerned by the lack of follow-through on some responses to > recent ideas I have described. Do I merely have a wrong understanding > of group policy? [snip] Perhaps the wrong idea of what the group is. I would have thought that if one had a sufficiently developed idea and wanted to have it / formally/ rejected, rather than merely sniped at, then writting a PEP would be more apposite than posting to c.l.py. It's fine to post your not sufficiently developed ideas here merely to have them discussed. But I don't know what makes you feel that you, or your ideas, are /entitled/ to any response at all, much less "follow-through." From ldo at geek-central.gen.new_zealand Mon Sep 29 02:43:29 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 19:43:29 +1300 Subject: Web programming in Python. References: <2afd3f2f-8b80-4a99-965a-6e27f7000055@r15g2000prh.googlegroups.com> Message-ID: In message <2afd3f2f-8b80-4a99-965a-6e27f7000055 at r15g2000prh.googlegroups.com>, Sean DiZazzo wrote: > Have you loaded the modpython module in your httpd.conf? Not relevant for CGIs. From tjreedy at udel.edu Thu Sep 4 17:35:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Sep 2008 17:35:18 -0400 Subject: why is self not passed to id()? In-Reply-To: <200809042244.54418.maric@aristote.info> References: <200809042244.54418.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez ?crit : >> class foo(list): >> __hash__ = lambda x: id(x) >> > > Wow ! You are really going on trouble with this, believe me there is a real > good reason for list not to be hashable. A dictionnary or set containing some > of your foo is virtually inconsistent, read carefully the manual about > prerequesites for dict keys, they *need* to be immutable. No, the id comparison needs to be immutable -- which it is by default for object()s, being based on id. Mutable instances of classes derived from object work fine as keys as long as they keep default __eq__ and __hash__. List over-rides the default, so foo needs to reverse that override: def __eq__(self, other): return id(self) == id(other) This means, of course, that foo loses value-based equality comparison. From dmitry at athabascau.ca Fri Sep 26 18:38:46 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Fri, 26 Sep 2008 22:38:46 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Hem... I'm afraid you don't really take Python's dynamic nature into > account here. Do you know that even the __class__ attribute of an > instance can be rebound at runtime ? What about 'once and for all' then ? must've been wrong wording on my part. Dynamic nature is exactly what I wanted to use :) except that I do not expect clients to take advantage of it while using my classes ;) >>> Your original question was "is decorator the right thing to use?" For >>> this application, the answer is "no". >> >> yeah. seems that way. in the other fork of this thread you'll find my >> conclusion which agrees with that :) >> >>> It sounds like you are trying >>> to force this particular to solution to your problem, but you are >>> probably better off giving __getattr__ intercepting another look. >> >> __getattr__ implies constant lookups and checks (for filtering purposes) > > Unless you cache the lookups results... sure >> - I >> want to do them once, attach generated methods as native methods > > What is a "native method" ? You might not be aware of the fact that > method objects are usually built anew from functions on each method > call... again, wrong wording on my part. by native I meant: make use as much as possible of existing machinery and override default behavior only when it's absolutely necessary. (hopefully my wording is not off this time ;) ) >> and be >> done with it. That is why I do not like __getattr__ in this particular >> case. > > There's indeed an additional penalty using __getattr__, which is that > it's only called as a last resort. Now remember that premature > optimization is the root of evil... Depending on effective use (ie : how > often a same 'proxied' method is called on a given Proxy instance, on > average), using __getattr__ to retrieve the appropriate bound method on > the delegate then adding it to the proxy instance *as an instance > attribute* might be a way better (and simpler) optimization. I actually ended up rewriting things (loosely based on George's suggested code) with descriptors and not using metaclasses or decorators (so much for my desire to use them). With following implementation (unpolished at this stage but already functional) I can have several instances of B objects inside of A object and proxy certain methods to one or another object (I might be having a case when I have A.b1 and A.b2 and passing some methods to b1 and others to b2 having both of the same class B, maybe even multiplexing). This one seems to be fairly light as well without need to scan instances (well, except for one getattr, but I couldn't get around it). Maybe I didn't account for some shoot-in-the-foot scenarios but I can't come up with any. Last time I played with __getattr__ I shot myself in the foot quite well BTW :) class ProxyMethod(object): def __init__(self,ob_name,meth): self.ob_name=ob_name self.meth=meth def my_call(self,instance,*argv,**kw): ob=getattr(instance,self.ob_name) cls=self.meth.im_class return self.meth.__get__(ob,cls)(*argv,**kw) def __get__(self,instance,owner): if not instance: return self.my_call ob=getattr(instance,self.ob_name) cls=self.meth.im_class return self.meth.__get__(ob,cls) class B: def __init__(self): self.val='bval' def bmethod(self,a): print "B::bmethod", print a, self.val class A: b=None def __init__(self,b=None): self.val='aval' self.b=b b.val='aval-b' def mymethod(self,a): print "A::mymethod, ",a bmethod=ProxyMethod('b',B.bmethod) b=B() b.bmethod('foo') a=A(b) b=B() b.val='newval' a.mymethod('baz') a.bmethod('bar') A.bmethod(a,'zoom') From michel at nospam.please Mon Sep 15 16:09:07 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 22:09:07 +0200 Subject: Python Nautilus script In-Reply-To: <6j7t7rF1tl5rU1@mid.uni-berlin.de> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> Message-ID: <48cec0e3$0$2860$ba620e4c@news.skynet.be> Diez B. Roggisch a ?crit : > However, if you want you can do something like this: > > #!/bin/bash > export VARIABLE_NAME > python /the/python/script.py > > You create a shell-script that exports the environment first, and then > invokes python. Oh, that's a good idea, I'll try this. Thanks -- Michel Leunen http://linux.leunen.com From asnast at gmail.com Thu Sep 25 15:33:07 2008 From: asnast at gmail.com (Alex Snast) Date: Thu, 25 Sep 2008 12:33:07 -0700 (PDT) Subject: Quick sort implementation in python Message-ID: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Hi guys, I've been learning python in the past week and tried to implement a q.sort algorithm in python as follows: def quick_sort(l, first, last) if first < last: q = partition(a, first, last) quick_sort(a, first, q - 1) quick_sort(a, q + 1, last) def partition(a, first, last): import random pivot = random.randomint(first, last) a[last], a[pivot] = a[pivot], a[last] i = first for j in range(first, last): if a[j] <= a[last]: a[i], a[j] = a[j], a[i] i += 1 a[i], a[last] = a[last], a[i] return i Now as you can see I'm passing my list object to both functions along with their first, last indices My question is: Is that the normal way to implement algorithms in python cause in c++ i've implemented that algo via a template function which can have a randon access data structure or not. However i have no idea how to access the values of a data structure that doesn't allow random access. Thanks, Alex From invalid at invalid Sun Sep 14 11:04:31 2008 From: invalid at invalid (Grant Edwards) Date: Sun, 14 Sep 2008 10:04:31 -0500 Subject: How does python call OS? References: Message-ID: On 2008-09-14, Siegfried Heintze wrote: > I just finished reading a chapter in "Python Programming on Win32" and tried > out the pythonwin scribble application. I'm not sure if I got it right > because I could not open a new document. I tried to download the source code > as referenced in the chm file but it is corrupted. I cut and pasted from my > softcopy of the book. > > I see the next sub-chapter on wxWindows for python and the > previous sub-chapter on TK. This is looking a lot like other > scripting languages (such as perl and groovy and even java). > Can python call anything directly No. For example, I don't believe there's any way for standard C-Python to make system calls on Linux. [Thought ISTR that somebody has written an extension module that doess that.] > or does someone have to write a DLL in C/C++ that calls the > function first? Can you be more explicit? What sort of "function" are you talking about? As for calling functions in libraries, the library doesn't have to be in C/C++. Python can make library calls written in any language (Fortran, Ada, Pascal, etc.) as long as the language uses a supportted API. Python can also execute external programs. -- Grant From Lie.1296 at gmail.com Sun Sep 28 07:48:29 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 04:48:29 -0700 (PDT) Subject: Borg vs Singleton vs OddClass References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> <00eee973$0$20666$c3e8da3@news.astraweb.com> Message-ID: <71fb2f0b-874d-468c-9ae4-2e644d26c26b@a3g2000prm.googlegroups.com> On Sep 28, 9:45?am, Steven D'Aprano wrote: > On Sat, 27 Sep 2008 11:12:00 -0700, Lie wrote: > > This is probably unrelated to Python, as this is more about design > > pattern. I'm asking your comments about this design pattern that is > > similar in functionality to Singleton and Borg: to share states. > > > I'm thinking about this design pattern (I don't know if anyone has ever > > thought of this pattern before): > > > class OddClass(object): > > ? ? def __init__(self): > > ? ? ? ? global OddClass > > ? ? ? ? OddClass = self > > ? ? def __call__(): > > ? ? ? ? return self > > I don't think that pattern works as you give it. I suggest you read the > thread "What do you call a class not intended to be instantiated", > started by me on the 21st of September, which covers a similar pattern. In fact, that thread inspired this thread. > I'm afraid it's a rather long thread, with a lot of people > misunderstanding what I was asking, but still worth reading. If you only > have time to read one post, I suggest you read my reply to Ben Finney, > posted yesterday. ... before I decided probably this pattern is probably isn't the answer to that thread. > My own feeling is that both your OddClass and my class without instances > are probably solutions looking for a problem. Well, actually, no, that's > too strong: I think the concept of "Class Singleton" is a perfectly valid > solution to certain problems, but it competes with more well-known > solutions like modules and Borg (in Python) and Singletons (the hammer > available in Java and C++). As for which is better, that's partly a > matter of personal taste and partly a matter of familiarity. > > > It do have a problem though, that you can't do isinstance(a, OddClass) > > But you can say "a is OddClass", which is more appropriate for a > Singleton. > > > The problem with Borg is that it is not inheritable (in certain > > sense[1]) and only work with old-style class (which is due to be > > completely removed on py3k)[2] > > No, there is a new-style Borg. Read the comments here:http://code.activestate.com/recipes/66531/ > > The new-style Borg is hardly more complicated than old-style: 6 lines > versus 4. From invalid at invalid Thu Sep 11 12:31:01 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 11 Sep 2008 11:31:01 -0500 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> Message-ID: <6v2dndx7GeZY2lTVnZ2dnUVZ_ozinZ2d@posted.visi> On 2008-09-11, Dennis Lee Bieber wrote: > On Wed, 10 Sep 2008 21:36:36 -0500, Grant Edwards > declaimed the following in comp.lang.python: > > >> Wrong. I didn't send _any_ e-mail. Why should I get bounce >> messages? >> > One: Comp.lang.python is dual-routed with a mailing list; anything > you post to either CLP or the mailing list gets cross-posted to the > other -- the FROM header retains that of the original author (which > could be you). > > Two: Somebody else is subscribed to the mailing list, and sets up an > "out-of-office" reply or has other problems (like an overfilled mailbox, > causing a bounce, or a discontinued account) when the forwarded post > reaches their address. > > Three: The bounce/ooo-reply is sent to the message author, not to > any intermediate host(s). After all, on that end, it's normal email > failure response -- notify the author of the message. It doesn't matter > that the original message was posted on a Usenet newsgroup if that group > is automatically relayed to members of a mailing list. OK, you win. Since I don't care to get the bounce and out-of-office messages, I'll fix my from: header when posting to this group. -- Grant Edwards grante Yow! Am I having fun yet? at visi.com From castironpi at gmail.com Mon Sep 22 16:15:46 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 13:15:46 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <48d7720d$0$12866$426a34cc@news.free.fr> <48d78c3c$0$6998$426a74cc@news.free.fr> <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> <48d7f46d$0$15502$426a74cc@news.free.fr> Message-ID: On Sep 22, 2:38?pm, Bruno Desthuilliers wrote: > Aaron "Castironpi" Brady a ?crit : > > > > > On Sep 22, 8:45 am, "Tim Rowe" wrote: > >> 2008/9/22 Bruno Desthuilliers : > > >>>> Sounds to me like a functor, aka a function object: > >>>>http://en.wikipedia.org/wiki/Function_object > >>> Ok, then the simple solution is to implement a callable type (__call__ > >>> method), possibly with appropriate support for the descriptor protocol if > >>> it's meant to be usable as a method. > >> Yes -- and instantiate the thing and keep the state in the instance, > >> rather than keeping the state in the class, so that it's possible to > >> safely have more than one of them if a later design change calls for > >> it (probably what led people off onto the sidetrack of thinking a > >> singleton was called for). ?That's the classic way of implementing a > >> "class [to be] used as a function". > > >> -- > >> Tim Rowe > > > I think you are either looking for a class that has a generator, or a > > generator that has a reference to itself. > > ??? > > Going back to robot-mode, Aaron ? Not getting the same sense of "soul" as from my usual posts. I guess so. Might even drop the name change, too... while I'm at it. One more word from you about it and I'm starting a thread, and calling it, "Python and my sense of 'soul'". Ha ha. From michele.simionato at gmail.com Wed Sep 10 08:21:00 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 10 Sep 2008 05:21:00 -0700 (PDT) Subject: Catching subprocess stdout stream References: <00b9dc86-e002-4e2c-a686-39d2dd1016b9@m3g2000hsc.googlegroups.com> Message-ID: <077ce22e-8278-4729-9f54-2a305064f797@x41g2000hsb.googlegroups.com> On Sep 8, 5:37?pm, Thomas Jansson wrote: > Dear all > > I have tkinkter based frontend to a Fortran based program. I use > subprocess to launch the fortran program as a child process and I wish > to see the output of the fortran program as it is created in the > console. > > The fortran program can take up to 20 minuttes to finish and at the > moment the I will first see any output after the fortran program is > done. How make my function write the output of the process as it > comes? Sometimes very low technology solutions may be enough. For instance on Unix you could call os.system on something like that: xterm -e "the-fortran-executable|less" Make sure the Fortran executable output is unbuffered. Michele Simionato From sjdevnull at yahoo.com Sun Sep 28 16:24:35 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sun, 28 Sep 2008 13:24:35 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <2ebe0ca2-ba26-47b3-ad35-946fd51d745c@f36g2000hsa.googlegroups.com> On Sep 28, 2:29 pm, process wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. > > What is not an object in Python? > Parts of the syntax aren't objects. e.g. "=" or ":" aren't objects. Unlike in some less fully OO-languages (e.g. Java or C++), classes, functions, and many other "built-in language features" are objects in Python. You can do things like return functions just like any other object, rather than having to do it indirectly through references or some such: >>> def add_n(x): ... def rv(y): ... return y + x ... return rv ... >>> add_2 = add_n(2) >>> add_3 = add_n(3) >>> >>> print add_2(6) 8 >>> print add_2(10) 12 >>> print add_3(6) 9 > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? FWIW, it is implemented as a str.__len__ method (and list.__len__ method); the len() function just uses those internally. Java and C++ have similar shortcuts for, say, "+" or "-". But Python allows you to call all the operators as methods if you want: >>> 1+2 3 >>> (1).__add__(2) 3 >>> a_list = [ "a", "b", "c" ] >>> len(a_list) 3 >>> a_list.__len__() 3 And, of course, the presence of the len() shortcut doesn't alter the OO-nature of the language any more than the presence of the + operator does in any OO language. Derived classes' __len__ operators are called correctly by len(): >>> class list_that_lies(list): ... def __len__(self): ... return 2 ... >>> bad_list=list_that_lies([1,2]) >>> print bad_list [1, 2] >>> len(bad_list) 2 >>> bad_list.append(3) >>> print bad_list [1, 2, 3] >>> len(bad_list) 2 From prologic at shortcircuit.net.au Thu Sep 18 06:48:54 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Sep 2008 20:48:54 +1000 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: Hi James, I can't say I really agree with your proposal. I tend to keep the help descriptions of my options short and concise and to the point. Also, one must use the language's features (indentation) to your advantage, as doing so ensure readability. For example (from my bhimport tool): def parse_options(): """parse_options() -> opts, args Parse any command-line options given returning both the parsed options and arguments. """ parser = optparse.OptionParser(usage=USAGE, version=VERSION) parser.add_option("", "--date-format", action="store",type="str", default="%d/%m/%Y", dest="dateFormat", help="date format string") parser.add_option("", "--time-format", action="store", type="str", default="%H:%M:%S", dest="timeFormat", help="time format string") parser.add_option("", "--datetime-format", action="store", type="str", default="%H:%M:%S %d/%m/%Y", dest="datetimeFormat", help="datetime format string") opts, args = parser.parse_args() if len(args) < 2: parser.print_help() raise SystemExit, 1 return opts, args As you can see (as long as you're reading this in fixed-width fonts) it _is_ very readable. cheers James On 9/18/08, James wrote: > Hi, > > I would like to know your thoughts on a proposed change to optparse > that I have planned. It is possible to add default values to multiple > options using the set_defaults. However, when adding descriptions to > options the developer has to specify it in each add_option() call. > This results in unreadable code such as: > > parser.add_option('-q', '--quiet' , action="store_false", > dest='verbose', > help = 'Output less information') > parser.add_option('-o', '--output' , type='string', > dest='castordir' , metavar='' , > help = 'specify the wanted CASTOR directory where to store the > results tarball') > parser.add_option('-r', '--prevrel' , type='string', > dest='previousrel' , metavar='' , > help = 'Top level dir of previous release for regression > analysis' ) > > The same code could become much more readable if there was an > equivalent method of set_defaults for the description/help of the > option. The same code could then become: > > parser.set_description( > verbose = 'Output less information', > castordir = 'specify the wanted CASTOR directory where > to store the results tarball', > previousrel = 'Top level dir of previous release for > regression analysis') > > parser.add_option('-q', '--quiet' , action="store_false", > dest='verbose') > parser.add_option('-o', '--output' , type='string', > dest='castordir' , metavar='' ) > parser.add_option('-r', '--prevrel' , type='string', > dest='previousrel' , metavar='' ) > > Help descriptions can often be quite long and separating them in this > fashion would, IMHO, be desirable. > > Kind Regards, > James Nicolson > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 4 08:43:49 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 14:43:49 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <48bfd7a0$0$20720$426a74cc@news.free.fr> Marco Bizzarri a ?crit : > Sorry... pressed enter but really didn't want to. > > As I said, let's say I have a class > > class A: > def __init__(self): > self.x = None > > > > Python makes the decision to allow the developers to directly access > the attribute "x", So do Java, if you make your attribute public (which would be a big error given Java's lack of support for computed attribute, but this is another problem). > so that they can directly write: "a.x = 1", or > whatever; this has for me the unfortunate side effect that if I write, > for example "a.y = 1", when I really wanted to write "a.x = 1" no one > cares about it, I assume *you* do !-) But this is barely related to having explicit setters or not - it comes from the fact that the default[1] Python's object behaviour is to support arbitrary attribute setting. [1] some objects don't, but this is mostly for optimization reasons. > and I'm unable to spot this error until later. Not sure, but IIRC tools like pylint or pychecker might be able to warn you about this. But anyway : > Of course, I know that while I'm fresh, I've a good knowledge of the > code, and anything else, I will be able to avoid such stupid errors; > however, I'm afraid of the times when I'm tired, when I have to put my > hands on the code of someone else, and so on. The edit/test cycle in Python is usually fast enough so you should spot the problem *pretty* quickly. This is at least what I learned from 8+ years of python (and a couple other dynamic languages) programming... Not to say that problems like the one you mention (or similar problems with dynamic typing etc) never happens, nor that they're never painful to track down and fix - just that they happen way less often than one might fear, and are most of the time really quickly spotted and fixed. > Please, understand that I'm not stating that python is wrong... after > all, if it is wrong, I can move to a language like Java, which has a > different approach on it. I don't think it's a matter of "right" or "wrong" - mostly a matter of tradeoffs and balance. But if you go for static typing and (allegedly) provable correctness, you may want to have a look at languages like OCaml. > I'm really very interested in reading past > discussion on it, if they are available. Well... Most of these "discussions" alas boil down to bondage&discipline proponants asserting - against all evidences - that dynamic languages are unsafe and unusable for anything else than simple throw-away scripts or toy projects, and dynamic proponants arguing - against all evidences - that static typing and everything related is just a waste of time (FWIW, you might find myself in the first camp until approx year 2k and the second for the five or six following years). And sometimes, someone a bit more sensible trying to take a more balanced approach to the problem, usually to no avail. From anishchapagain at gmail.com Wed Sep 3 07:43:54 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Wed, 3 Sep 2008 04:43:54 -0700 (PDT) Subject: installing matplotlib with numpy and scipy for Python in Cygwin References: Message-ID: <4241157d-6cdb-4edc-bb22-bceeb68b870f@m73g2000hsh.googlegroups.com> On Sep 3, 12:39?pm, Uwe Schmitt wrote: > On 3 Sep., 11:42, "chapagainanish" wrote: > > > Hi!! > > I'm having installation problem for installing numpy and scipy in > > Cygwin for Python, and am obstruct in madway for project, i followed > > scipy.org guidelines but there's few error thrown as > > ? ? ? ? failed..with exit status 1 > > > please if someone has installed these module help me > > thank's and regard's > > Anish > > http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html > may help you. > > Do you really want a cygwin based installation ? > You could download enthoughts python edition which > includes lots of math stuff. > > Greetings, Uwe Hi, thank's i'm looking through the link cens.ioc.ee and am in need of using matplotlib and to run few system call, so i installed cygwin baically for system call in linux/unix and matplotlib for GUI(graph,chart) but matplotlib is not getting installed in cygwin.. any further help will be heartly accepted thank's anish From skip at pobox.com Mon Sep 8 06:51:48 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Sep 2008 05:51:48 -0500 Subject: Syntax Problem with strptime in Python 2.4 In-Reply-To: References: Message-ID: <18629.964.85843.766887@montanaro-dyndns-org.local> >> Apparently, use of strptime of datetime needs a workaround in Python >> 2.4 to work properly. The workaround is d = >> datetime.datetime(*(time.strptime(date_string, >> format)[0:5])). However, when I try to use it, or even use it the >> regular way, it fails with AttributeError: type object >> 'datetime.datetime' has no attribute 'datetime'. Works for me: >>> import datetime >>> format = '%Y%m%d_%H%M%S' >>> import time >>> print time.strptime('20080321_113405', format)[0:5] (2008, 3, 21, 11, 34) >>> d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5]) >>> d datetime.datetime(2008, 3, 21, 11, 34) Python 2.4.4, Mac OS X 10.5.4. Skip From gnewsg at gmail.com Sat Sep 20 14:48:09 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 20 Sep 2008 11:48:09 -0700 (PDT) Subject: ANN: Python FTP Server library (pyftpdlib) 0.5.0 released Message-ID: <1433ffb8-7493-466d-81e6-bf8ed877e81c@y21g2000hsf.googlegroups.com> Hi, I'm pleased to announce release 0.5.0 of Python FTP Server library (pyftpdlib). http://code.google.com/p/pyftpdlib/ === About === Python FTP server library provides an high-level portable interface to easily write asynchronous FTP servers with Python. Based on asyncore framework pyftpdlib is currently the most complete RFC-959 FTP server implementation available for Python programming language. === Major changes === This new version, aside from fixing some bugs, includes the following major features: - pyftpdlib now provides configurable idle timeouts to disconnect client after a long time of inactivity. - It is now possible to define permission exceptions for certain directories (e.g. creating a user which does not have write permission except for one sub-directory in FTP root). - Imposed a delay before replying for invalid credentials to minimize the risk of brute force password guessing. A complete list of changes including enhancements, bug fixes and instructions for using the new functionalities is available here: http://code.google.com/p/pyftpdlib/wiki/ReleaseNotes05 === More links === * Source tarball: http://pyftpdlib.googlecode.com/files/pyftpdlib-0.5.0.tar.gz * Online docs: http://code.google.com/p/pyftpdlib/wiki/Tutorial * FAQs: http://code.google.com/p/pyftpdlib/wiki/FAQ * RFCs compliance paper: http://code.google.com/p/pyftpdlib/wiki/RFCsCompliance * Issue tracker: http://code.google.com/p/pyftpdlib/issues/list Thanks, --- Giampaolo Rodola' < g.rodola [at] gmail [dot] com > http://code.google.com/p/pyftpdlib/ From marco.bizzarri at gmail.com Sun Sep 14 04:44:36 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sun, 14 Sep 2008 10:44:36 +0200 Subject: recursion gotcha? In-Reply-To: <3f0d61c40809140108n515006dci87f91dcd971f0169@mail.gmail.com> References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> <3f0d61c40809140108n515006dci87f91dcd971f0169@mail.gmail.com> Message-ID: <3f0d61c40809140144xfca86a1u7c6d088bec0f42f1@mail.gmail.com> On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri wrote: > On Sun, Sep 14, 2008 at 10:01 AM, cnb wrote: >> this recursive definition of sum thrumped me, is this some sort of >> gotcha or am I just braindead today? >> and yes i know this is easy a a for x in xs acc += x or just using the >> builtin. >> >> def suma(xs, acc=0): >> if len(xs) == 0: >> acc >> else: >> suma(xs[1:], acc+xs[0]) > > You're just missing the "return" statements? > > def suma(xs, acc=0): > if len(xs) == 0: > return acc > else: > return suma(xs[1:], acc+xs[0]) > > Besides: you can avoid the "acc" parameter: def suma(xs): if len(xs) == 0: return 0 else: return xs[0] + suma(xs[1:]) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From dmitry at makovey.net Wed Sep 24 23:51:01 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 03:51:01 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> Message-ID: Dmitry S. Makovey wrote: > In my real-life case A is a proxy to B, C and D instances/objects, not > just one. forgot to mention that above would mean that I need to have more than one decorator function like AproxyB, AproxyC and AproxyD or make Aproxy smarter about which property of A has instance of which class etc. Unless I'm totally "out for lunch" and there are better ways of implementing this (other than copy-pasting stuff whenever anything in B, C or D changes). From stephen.mc at gmail.com Wed Sep 24 07:12:37 2008 From: stephen.mc at gmail.com (Steve) Date: Wed, 24 Sep 2008 04:12:37 -0700 (PDT) Subject: Python graphical library References: <3abb0519-7700-4d82-bdaa-e4b09ef1c483@t54g2000hsg.googlegroups.com> Message-ID: <9122b671-a1b2-473b-9244-bc443d2e859b@z11g2000prl.googlegroups.com> On Sep 24, 7:31?pm, bluesm... at gmail.com wrote: > Hi all, > > I am looking for a python graphical library that would allow me to > draw borderless windows, sort of like a notification frame showing up. > I would also like to be able to make it transparent but I suppose that > is very much desktop manager dependent. > > Thank you very much for the help. > > ET wxpython supports both these features From fredrik at pythonware.com Thu Sep 4 02:24:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 08:24:56 +0200 Subject: max(), sum(), next() In-Reply-To: <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: Mensanator wrote: > No it isn't. Nothing is not 0, check with MS-Access, for instance: > > Null + 1 returns Null. Any arithmetic expression involving a > Null evaluates to Null. Adding something to an unknown returns > an unknown, as it should. > > It is a logical fallacy to equate unknown with 0. http://en.wikipedia.org/wiki/Empty_sum "In mathematics, the empty sum, or nullary sum, is the result of adding no numbers, in summation for example. Its numerical value is zero." From prologic at shortcircuit.net.au Wed Sep 10 10:22:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 00:22:33 +1000 Subject: Alternatives to traditional RDBMS Message-ID: Hi all, Are there any known alternatives to the traditional RDBMS (MySQL, PostgreSQL, SQLite, Oracle, etc0 / I know of 3 written in Python: * buzhug * kirbybase * PyDbLite buzhug --------- Although buzhug has a group membership size of ~60 or so it has not seen any activity in some time - and any activity that exists is slow and far and in-between. That said, buzhug is has a nice OO/Pythonic design and is quite nice to use. I have been working in improving it and have fixed issues I've come across in a branch of the original buzhug code that I now maintain. I fear the author of buzhug has lost interest and gone elsewhere to tinker with (better) other things ? kirbybase ------------ A nice small (also pure) python OO database. Developed quite some time ago, not actively worked on, but works really well.. PyDbLite ---------- Also developed quite some time ago, similar to both kirbybase and buzhug. Are there any others out there ? Is anyone working on something ? I would like to continue my work on buzhug... I have so: * Fixed several bugs * Implemented a WSGI middleware layer I'd like to refactor a lot of it's code and make better use of more recent features of python as buzhug was written quite some time ago. I think it's "protocol" could be vastly improved as well - as pickling things doesn't always work so well... In addition, I think buzhug could do with some caching features to speed database operations up (they're already pretty fast). cheers James -- -- -- "Problems are solved by method" From stefan_ml at behnel.de Tue Sep 16 13:40:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 16 Sep 2008 19:40:37 +0200 Subject: ElementTree oddities In-Reply-To: References: Message-ID: <48cfef95$0$6669$9b4e6d93@newsspool2.arcor-online.net> Mark Thomas wrote: > here's how you would do it in lxml (http://codespeak.net/ > lxml/index.html), a library which supports XPath: > > from lxml import etree > tree = etree.fromstring('Bar:') > print ' '.join(tree.xpath('//text()')) If you want to use XPath, try this: print tree.xpath('string()') or if you want to use it in real code: get_tree_text = etree.XPath('string()') print get_tree_text(tree) or just use print etree.tostring(tree, method="text") Stefan From rowland at river2sea.org Tue Sep 2 15:48:05 2008 From: rowland at river2sea.org (rowland at river2sea.org) Date: Tue, 2 Sep 2008 12:48:05 -0700 (PDT) Subject: synthetic properties Message-ID: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> I'm trying to come up with solution for adding synthetic properties to python, similar to synthetic properties in Objective-C. I'm playing around with doing this in a MetaClass. I can dynamically create the attributes that will back the property, but I'm having trouble figuring out how to dynamically generate get/set methods to pass to the built-in property() function. Is it possible to define a lambda or a callable object that will act as a getter method (or setter, that takes a value argument) during MetaClass.__init__? The hard part I'm guessing is getting the current instance passed into the getter. This is my first foray into MetaClasses and dynamic functions/methods so any pointers are greatly appreciated. class ObjectivePythonObject( type ) : def __new__( cls, name, bases, dct ) : #print "Allocating memory for class", name return type.__new__(cls, name, bases, dct ) def __init__( cls, name, bases, dct ) : #print "Initializing class", name for propertyInfo in cls.synthesized : property = propertyInfo[ 0 ] defaultValue = propertyInfo[ 1 ] print property setattr( cls, '_' + property, defaultValue ) # Create property with get/set methods... class Person( object ) : __metaclass__ = ObjectivePythonObject synthesized = [ ( 'name', 'BobC' ), ( 'age', '48' ) ] def __init__( self ) : print self._name print self._age Thanks, Rowland From bdesth.quelquechose at free.quelquepart.fr Thu Sep 25 13:31:41 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 19:31:41 +0200 Subject: is decorator the right thing to use? In-Reply-To: References: <48db50aa$0$3750$426a74cc@news.free.fr> <48dbc82e$0$1120$426a74cc@news.free.fr> Message-ID: <48dbe6e9$0$12845$426a74cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : (snip) > You should write it like this: > > class B(object): > @A.proxy > def bmethod(self,a): > > Making 'proxy' a class method on A. That's exactly what I wanted to avoid here : making B depending on A. (snip) > I agree that __setattr__ is the canonical solution to proxy, Err... I assume you mean '__getattr__' ??? > but you > have stated that you want each proxied method to be a member in the > proxy class. This doesn't necessarily imply that "proxied" classes need to know about the "proxying" class. FWIW, that was the whole point : decoupling. From castironpi at gmail.com Sun Sep 28 14:59:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 11:59:41 -0700 (PDT) Subject: Music knowledge representation References: Message-ID: On Sep 28, 9:37?am, Mr.SpOOn wrote: > Hi, > I'm working on an application to analyse music (melodies, chord sequences etc.) > > I need classes to represent different musical entities. I'm using a > class Note to represent all the notes. Inside it stores the name of > the natural version of the note (C, D, E, F...) and an integer to > calculate the accidentals. > > Then I have a class Pitch, to represent the different 12 pitch > classes, because different notes, such as C# and Db, belong to the > same pitch class. > > In these classes I also have some arithmetic method to perform > additions or subtractions between pitches and integers. > > I also need to represent intervals between notes. An interval must > have a degree (first, second, third), that may be represented with a > simple integer and a size counted in semitones. Then, with these > informations it can retrieve its name, for example: perfect fifth. > > The degree is calculated between natural notes. So the degree of > Interval(C, E) is "third", or 3. This may be simple, if I put the > notes in an ordered sequence. But, when I have to calculate, for > example Interval(E, C). It should count till the end of the sequence, > so if I have: > > C D E F G A B > > after the B it should continue with C. I'm not sure how to implement > this. Is there a suitable data structure for this purpose? Hi, Here is a link to someone else's design they asked about on the newsgroup a couple weeks ago. http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 13:08:23 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 19:08:23 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: <48cc0b6f$0$11218$426a34cc@news.free.fr> References: <48cbf09c$0$25189$426a74cc@news.free.fr> <48cbf432$0$27507$426a34cc@news.free.fr> <48cc0b6f$0$11218$426a34cc@news.free.fr> Message-ID: <48cc0f75$0$2214$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > Larry Bates a ?crit : (snip) >> Sorry but I respectfully disagree that this is "abuse" of the __call__ >> method. > > As long as we respectfully agree to disagree... > > !-) Anyway, I don't think we have enough background to seriously agree or disagree on what would make more sense here... From stefan_ml at behnel.de Fri Sep 5 06:15:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Sep 2008 12:15:37 +0200 Subject: "Full" element tag listing possible with Elementtree? In-Reply-To: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> References: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Message-ID: <48c106c9$0$9331$9b4e6d93@newsspool2.arcor-online.net> jaime.dyson at gmail.com wrote: > I have the unenviable task of turning about 20K strangely formatted > XML documents from different sources into something resembling a > clean, standard, uniform format. I like Elementtree and have been > using it to step through the documents to get a feel for their > structure. .getiterator() gives me a depth-first traversal that > eliminates the hierarchy of the elements. What I'd like is to be able > to traverse elements while keeping track of ancestors, and print out > the full structure of all of an ancestor's nodes as I arrive at each > node. Try lxml.etree. It's an extended re-implementation of ElementTree based on libxml2. Amongst tons of other features, it provides its Elements with a getparent() method and allows you to iterate over their ancestors (and other XPath axes), or to iterate over a parsed document in an iterparse-like fashion (called iterwalk). http://codespeak.net/lxml/ Stefan From maric at aristote.info Fri Sep 5 07:16:40 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 13:16:40 +0200 Subject: Case-insensitive string compare? In-Reply-To: References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050038.04108.maric@aristote.info> Message-ID: <200809051316.41333.maric@aristote.info> Le Friday 05 September 2008 08:30:44 Fredrik Lundh, vous avez ?crit?: > Maric Michaud wrote: > > You''ll often see for loops written like this : > > > > for i in (e for e in iterable if predicate(e)) : > > ... > > luckily, I don't. most people, when faced with that problem, writes it > in the obvious way: > > for i in iterable: > if predicate(i): > ... So do I, most often, but this construct is common, I think because it makes clear what the for loop is iterating over, also it comes naturally once used to the more elaborated for i in (expr(e) for e in iterable if predicate(e)) : This one is truly a gain for readability IMO, compared to : for i in iterable: i = expr(i) if predicate(i): In the latter, the reader need more effort to figure out what finally "i" is in the loop. > > to avoid an extra iterator and save typing. > and at the cost of an extra indentation level. > > > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From lists at cheimes.de Tue Sep 16 15:40:41 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Sep 2008 21:40:41 +0200 Subject: new style classes, __new__, __init__ In-Reply-To: References: Message-ID: Torsten Mohr wrote: > I just found an article that describes it better, this example works: > > class C2(object): > def __new__(cls, a): > obj = object.__new__(cls) > print "new called" > obj.a = 8 > > return obj > > __new__ = staticmethod(__new__) Staticmethod isnt' required here. Christian From skip at pobox.com Mon Sep 8 13:47:45 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Sep 2008 12:47:45 -0500 Subject: shelve file name extention In-Reply-To: References: Message-ID: <18629.25921.928679.626414@montanaro-dyndns-org.local> Monu> When I am using shelve on my local machine it generates the db Monu> file as given filename. But in another machine it's generating Monu> .dat and .dir. can anyone tell me how can I force sheve Monu> module to write the db in .dir and .dat, Monu> instead of ? Do I have to install a specific version of Monu> the python? Shelve is just a thin layer on top of a concrete db file module. Sounds like on your two machines there are different underlying db file modules available. You're pretty much at the mercy of those modules as to file naming. All you are giving it when opening a shelve file is the prefix. Skip From larry.bates at vitalEsafe.com Tue Sep 16 09:36:12 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 16 Sep 2008 08:36:12 -0500 Subject: A unique instance of Python GUI program In-Reply-To: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Message-ID: akineko wrote: > Hello everyone, > > This may not be a Python specific challenge. > I have a GUI program written in Python + Tkinter. > It works very well. > > Now, I would like to start it from a shell script. > As my GUI program includes a server, it should not have more than one > instance. > Is there any easy way to check if another instance of the program is > already running. > > I vaguely remember that Windows programming provides a way to check. > > A platform independent approach would be nice but a solution for X is > sufficient for my application. > > Any comments will be greatly appreciated. > > Best regards, > Aki Niimura Here is a recipe: http://code.activestate.com/recipes/474070/ -Larry From bearophileHUGS at lycos.com Mon Sep 1 15:15:53 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Sep 2008 12:15:53 -0700 (PDT) Subject: Py 2.6 changes Message-ID: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> I have just re-read the list of changes in Python 2.6, it's huge, there are tons of changes and improvements, I'm really impressed: http://docs.python.org/dev/whatsnew/2.6.html I'll need many days to learn all those changes! I can see it fixes several of the missing things/problems I have found in Python in the past, like the lack of information regarding the floating point it uses, etc. I have seen that many (smart) updates are from Hettinger. You can see a language gets better when you can remove often-used commodity functions/classes from your own 'bag of tricks' :-) (Like the permutations() function, etc). >Python now must be compiled with C89 compilers (after 19 years!). This means that the Python source tree has dropped its own implementations of memmove and strerror, which are in the C89 standard library.< I presume it's better for me to not hold my breath while I wait CPython to be written in C99 :-) Now math has factorial: http://docs.python.org/dev/library/math.html#math.factorial Seen how reduce() is removed from Python 3 (I know it's in itertools), and seeing that for me to write a productory() function was the first usage I have had for reduce, years ago, I think the math module can gain a productory() function too. For Python 2.7/3.1 I'd now like to write a PEP regarding the underscores into the number literals, like: 0b_0101_1111, 268_435_456 etc. I use such underscores all the time in the D language, and I think they can be a tiny but significant improvement for Python (and underscore is much better than just a space, because the underscore helps the person that reads the code to understand that's a single number). Bye, bearophile From ggpolo at gmail.com Mon Sep 15 07:19:54 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 15 Sep 2008 08:19:54 -0300 Subject: how to protect the source In-Reply-To: References: Message-ID: On Mon, Sep 15, 2008 at 8:02 AM, Jo?o Abrantes wrote: > Hello Everyone. > > > I am building a client in python that will connect himself to a mysql > server with a certain username and password. I will compile this client > and turn him into a .exe . The thing is that I know that is possible to > get the source of the code back from an .exe and I don't want anyone to > know which username and password are they using because I don't want > them to access to the mysql server without my client. Do you have any > ideas of what can i do? Thanks! > Do not include the username and password in the source. > ________________________________ > Connect to the next generation of MSN Messenger Get it now! > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From fredrik at pythonware.com Fri Sep 5 02:24:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:24:29 +0200 Subject: Case-insensitive string compare? In-Reply-To: <200809050059.17038.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> <200809050059.17038.maric@aristote.info> Message-ID: Maric Michaud wrote: > "premature optimization is the root of all evil" So is use by that statement by people who don't have the slightest idea about what it actually means. The full version is "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." Note the use of "small efficiencies". That is, in Python, things like local binding, inlining, slots, lazy generation of short sequences, etc. That is, things that takes time to write and reduces maintainability. It's not about having an excuse for writing crappy code with large inefficienies. And it's definitely not about programmers intentionally picking a dumb solution so they can optimize it later. > If the OP's proposal seems already messy, how about ths one : > if lib.lower() not in ( e[0] for e in stage_map.items() ) : > ... Given that your solution is just a remarkably inefficient way to write "lib.lower() not in stage_map", and thus doesn't solve the OP:s problem, I suspect you're taking the "evil" part of Hoare's dictum a few bits too literally. From deets at nospam.web.de Mon Sep 15 17:00:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 23:00:47 +0200 Subject: Python Nautilus script In-Reply-To: References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> Message-ID: <6j80nvF1ttmfU1@mid.uni-berlin.de> >>> It appears that's because HOSTNAME is not exported. >>> But in the case of Nautilus script, how to workaround this issue? > > Alternatively, export the variable when you create it, in .bashrc or > wherever it is getting created. That's probably the Right Thing to > Do(tm) in this case. Certainly not, as the OP uses a network monitoring software called Nautilus - and that communicates state to subprocesses using environment variables. Nothing to do with .bashrc. Diez From lixinyi.23 at gmail.com Tue Sep 23 22:30:44 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 19:30:44 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> Message-ID: <31ff7c8a-28f3-4c62-8ac5-6d0f90106c5d@a8g2000prf.googlegroups.com> If the PyObject is a PyList, and all list items are strings, say a=['aaa','bbb','ccc'] How can I have a myArray[0] = "aaa" myArray[1] = "bbb" myArray[2] = "ccc" in C++? Do I have to use PyModule_GetDict() to get the dict first? what about the next? > > What do you know about the contents of 'argc' and 'argv'? ?If it's > impossible with Py_Main, can you use one of the other entry points? > > If you've never manipulated PyObject* objects in C, they can be > hairy. ?Even if you know 'a' is a sequence, its contents are still all > PyObject*s, which you can access via PyList_... and PySequence_ > functions. From paul at boddie.org.uk Wed Sep 17 05:43:54 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 17 Sep 2008 02:43:54 -0700 (PDT) Subject: minimum install & pickling References: Message-ID: <6f045535-555f-44b6-93a5-f5b338d3f318@d45g2000hsc.googlegroups.com> On 17 Sep, 07:26, "Aaron \"Castironpi\" Brady" wrote: > Sometimes questions come up on here about unpickling safely and > executing foreign code. ?I was thinking a minimum install that didn't > even have access to modules like 'os' could be safe. ? (Potentially.) > I have time to entertain this a little, though all the devs are busy. > I can bring it up again in a few months if it's a better time. One alternative might be to provide "safe" versions of the underlying functions in modules like "os". Previously, I did wonder why people didn't link Python against a bunch of alternative libraries which would provide implementations of things like "open", "chdir" and so on, but then I was made aware of fakeroot and fakechroot which do more or less this for any program (in conjunction with chroot) in order to restrict the behaviour of those programs, without any need to statically link the programs first. [...] > A lot of modules would have to go. ? ?IPC modules: > subprocess, socket, signal, popen2, asyncore, asynchat. ?ctypes, mmap, > platform.popen, glob, shutil, dircache, and many more. Potentially, these could remain, but you'd want to provide "fake" versions of the underlying functions, potentially implementing your own preferred flavour of access control. So, with a call to the "socket" function, the wrapped version might first consult some kind of behaviour policy set by the user in order to get permission to open a connection to a remote host. There's a discussion of rexec and related solutions on the Wiki: http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_safely_(i.e._Sandbox) Paul From walter.php at gmail.com Fri Sep 5 10:35:14 2008 From: walter.php at gmail.com (Walter Cruz) Date: Fri, 5 Sep 2008 11:35:14 -0300 Subject: Extract Information from Tables in html In-Reply-To: <37b964200809050729j6290af48u8efbbc1a5e0b6bd1@mail.gmail.com> References: <37b964200809050729j6290af48u8efbbc1a5e0b6bd1@mail.gmail.com> Message-ID: <32cabba0809050735x16eb3764mb7ed9ad256de0b08@mail.gmail.com> On Fri, Sep 5, 2008 at 11:29 AM, Jackie Wang wrote: > Dear all, > > Here is a html code: > > > > Premier Community Bank of Southwest Florida >
> Fort Myers, FL > > > > My question is how I can extract the strings and get the results: > Premier Community Bank of Southwest Florida; Fort Myers, FL Use BeautifulSoup. []'s - Walter From pavlovevidence at gmail.com Fri Sep 5 00:31:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 21:31:07 -0700 (PDT) Subject: Converting .doc to .txt in Linux References: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: <42a43f18-2143-4cce-90f6-0ac5fe1807cd@8g2000hse.googlegroups.com> On Sep 4, 4:18 pm, Tommy Nordgren wrote: > On Sep 4, 2008, at 9:54 PM, patrick.wa... at gmail.com wrote: > > > > > Hi Everyone, > > > I had previously asked a similar question, > >http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > > but at that point I was using Windows and now I am using Linux. > > Basically, I have some .doc files that I need to convert into txt > > files encoded in utf-8. However, win32com.client doesn't work in > > Linux. > > > It's been giving me quite a headache all day. Any ideas would be > > greatly appreciated. > > > Best, > > Patrick > > > #Windows Code: > > import glob,os,codecs,shutil,win32com.client > > from win32com.client import Dispatch > > > input = '/home/pwaldo2/work/workbench/current_documents/*.doc' > > input_dir = '/home/pwaldo2/work/workbench/current_documents/' > > outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/' > > > for doc in glob.glob1(input): > > WordApp = Dispatch("Word.Application") > > WordApp.Visible = 1 > > WordApp.Documents.Open(doc) > > WordApp.ActiveDocument.SaveAs(doc,7) > > WordApp.ActiveDocument.Close() > > WordApp.Quit() > > > for doc in glob.glob(input): > > txt_split = os.path.splitext(doc) > > txt_doc = txt_split[0] + '.txt' > > txt_doc_path = os.path.join(outpath,txt_doc) > > doc_path = os.path.join(input_dir,doc) > > shutil.copy(doc_path,txt_doc_path) > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You can do it manually with Open Office. > A free office suite. On Debian there is a package called "unoconv"--written in Python--that can do the conversions from the command line. It requires a running instance of Open Office. However, the doc-to-txt conversion of Open Office isn't that good. (It wasn't as good as Word's formatted text converter, last time I used it.) Carl Banks From pavlovevidence at gmail.com Thu Sep 11 17:13:37 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 11 Sep 2008 14:13:37 -0700 (PDT) Subject: Accessing __slots__ from C References: Message-ID: On Sep 10, 7:41 am, Chris wrote: > Hi, > > I'd like to be able to access an attribute of a particular Python > object as fast as possible from some C code. > > I wondered if using __slots__ to store the attribute would allow me to > do this in a faster way. > > The reason I'd like to do this is because I need to access the > attribute inside a loop within some C code, and I find that the > attribute lookup using the 'PyObject_GetAttrString' call is far slower > than any of the subsequent calculations I perform in C. > > Using the 'PyObject_GetAttrString' function to get the attribute, I > find it is slightly faster when the attribute is a slot than when it > isn't, but that the attribute lookup remains the performance-limiting > factor. You can determine the offset the of the slot in the object structure by querying the member descriptor of the type object. descr = GetAttrString(cls,"varname"); offset = descr->d_member->offset; slotvar = (PyObject*)(((char*)obj)+offset) There might be some macros to simplify this. Use at your own risk. Carl Banks From ptmcg at austin.rr.com Thu Sep 4 06:08:54 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 4 Sep 2008 03:08:54 -0700 (PDT) Subject: Issue warning if no "return" in function? References: Message-ID: <6d2504d5-4dd6-49f9-abe5-bd03e5010d0d@v39g2000pro.googlegroups.com> On Sep 4, 5:05?am, Poster28 wrote: > What would you suggest to check python programs for non-syntax error. > One example I could think of that one might forget to "return" a value from > a function. > > How could I check for these and maybe other mistakes? Check out PyLint (http://www.logilab.org/857) or PyChecker (http:// pychecker.sourceforge.net/). From toddw at activestate.com Tue Sep 16 21:16:19 2008 From: toddw at activestate.com (Todd Whiteman) Date: Tue, 16 Sep 2008 18:16:19 -0700 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <48C15F5F.7040704@activestate.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <48BFB534.2080508@egenix.com> <48C15F5F.7040704@activestate.com> Message-ID: <48D05A63.5040907@activestate.com> Todd Whiteman wrote: > Mark Hammond's Python/Mozilla work has enabled products like Komodo, > Miro (Democracy) and the OLPC project to use Python as a major driver > for consistent cross-platform GUI applications. > > Personally, I believe XULRunner has a lot to offer for Python GUI > development, I'm currently finishing up some documentation steps to show > off how to use it specifically for Python (I'll post it to this list > when it's finished). Here is the tutorial I've started in order to show off building a Python/XULRunner GUI application. http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html The details in this tutorial mostly targets a Windows/Linux platform (MacOSX is possible with a few deviations, I have tried to cover these deviations where applicable). Feedback is welcome. Cheers, Todd From alexandru.palade at sellerengine.com Thu Sep 4 07:49:11 2008 From: alexandru.palade at sellerengine.com (Alexandru Palade) Date: Thu, 04 Sep 2008 14:49:11 +0300 Subject: Safely move an element into a heap In-Reply-To: References: Message-ID: <48BFCB37.8030608@sellerengine.com> I'm not sure what you expect as an answer, but if you mean the heap as in the data structure, you can not just arbitrarily move one key where you want as it will destroy the heap property. Giampaolo Rodola' wrote: > Hi, > I wanted to know if does exist a safe way to, given a heap, move an > arbitrary element to the first position of the heap. > Something like: > > >>> heap = [0,3,6,8,10] > >>> heapq.move_to_first_position(heap, 4) > >>> heap = [10, 0,3,6,8] > > > --- Giampaolo > http://code.google.com/p/pyftpdlib/ > -- > http://mail.python.org/mailman/listinfo/python-list > > From darcy at druid.net Wed Sep 10 13:18:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 10 Sep 2008 13:18:12 -0400 Subject: md5 differences In-Reply-To: <7C2CD173-D069-41A0-9B56-382FF86F5B52@rgbaz.eu> References: <7C2CD173-D069-41A0-9B56-382FF86F5B52@rgbaz.eu> Message-ID: <20080910131812.b3729762.darcy@druid.net> On Wed, 10 Sep 2008 19:12:28 +0200 Python wrote: > hmm and this then: > > Arno at Computer:~% echo "test" > test.txt > > Arno at Computer:~% md5 test.txt > MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 > > Arno at Computer:~% python > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import md5 > >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() > '90364ed45b452d43378629c20543a81d' You're going to smack yourself on the head over this one. :-) >>> md5.new(open("/Volumes/data/Arno/test.txt").read()).hexdigest() -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From gherron at islandtraining.com Sun Sep 21 13:11:17 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 21 Sep 2008 10:11:17 -0700 Subject: I tried erlang-ish [1|2] in python and something came out... In-Reply-To: References: Message-ID: <48D68035.2020405@islandtraining.com> process wrote: > In erlang you can cons like this: [1|2]. i tried this in python and it > didnt raise an error but i dont know what the result do > In Python | is the logical bitwise-OR operator. Look at the binary representation of the numbers to understand it. Gary Herron > >>>> [1|2] >>>> > [3] > >>>> [2|2] >>>> > [2] > >>>> a = [2|2] >>>> a >>>> > [2] > >>>> [2|3] >>>> > [3] > >>>> [2|1] >>>> > [3] > > -- > http://mail.python.org/mailman/listinfo/python-list > From eric at ericabrahamsen.net Mon Sep 29 09:17:32 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Mon, 29 Sep 2008 21:17:32 +0800 Subject: Using re to find unicode ranges Message-ID: <530E89AB-634E-4660-BAAD-85F8AEC6364C@ericabrahamsen.net> Is it possible to use the re module to find runs of characters within a certain Unicode range? I'm writing a Markdown extension to go over text and wrap blocks of consecutive Chinese characters in tags for nice styling in an HTML page. The available hooks appear to be a pre- processor (which is a "for line in lines" situation) or an inline pattern (which uses regular expressions). The regular expression solution would be much simpler and faster, but something tells me there's no way to use a regex to find character ranges... Chinese characters appear to fall between 19968 and 40959 using ord(), and I suppose I can go that route if necessary, but I think it would be ugly. Any hints or suggestions would be appreciated! Eric From dudeja.rajat at gmail.com Mon Sep 29 13:36:56 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 29 Sep 2008 18:36:56 +0100 Subject: Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars In-Reply-To: References: Message-ID: On Mon, Sep 29, 2008 at 5:10 PM, wrote: > > > On Sun, Sep 28, 2008 at 4:51 PM, wrote: > >> >> Hi, >> >> >> Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well >> the problem is I'm unable to scroll if I click on the arrows buttons of >> scrollbars ( with both types of scrollbars) >> >> >> Please suggest if I m missing some configuration. >> >> >> My code is as below: >> >> self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL) >> self.hsb.grid(row = 2,column = 0, sticky = E+W) >> #vertical scroll bar >> self.vsb = Scrollbar(appGuiFrame) >> self.vsb.grid(row = 1,column = 2, sticky = N+S) >> >> >> >> self.txtLogger = Text(appGuiFrame, \ >> height = 20,\ >> width = 100, \ >> state = DISABLED, \ >> xscrollcommand = self.hsb.set, \ >> yscrollcommand = self.vsb.set, \ >> wrap = NONE, \ >> font = ("courier",12)) >> self.hsb.config(command = self.txtLogger.xview()) >> self.vsb.config(command = self.txtLogger.yview()) >> >> >> Please help. >> >> >> Thanks and regards, >> Rajat >> > > > Hi folks, > > Any help on the above problem. > > Regards, > Rajat > Hi, The problem got solved. After finding for such a long time I got a snippet at google and used the same in my code. It solved the problem. Here is the complete code now: class cLogToGUI: def __init__(self, logObj, appGUI): self.__logger = logObj self.__logger.debug("Inside cLogToGUI::__init__") appGuiFrame = appGUI.frame4 #hor. scroll bar self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL) self.hsb.grid(row = 2,column = 0, sticky = E+W) #vertical scroll bar self.vsb = Scrollbar(appGuiFrame) self.vsb.grid(row = 1,column = 2, sticky = N+S) self.txtLogger = Text(appGuiFrame, \ height = 20,\ width = 100, \ state = DISABLED, \ xscrollcommand = self.hsb.set, \ yscrollcommand = self.vsb.set, \ wrap = NONE, \ font = ("courier",12)) #self.hsb.config(command = self.txtLogger.xview()) #self.vsb.config(command = self.txtLogger.yview()) self.hsb.config(command = self.__hsbScrollHandler) self.vsb.config(command = self.__vsbScrollHandler) self.txtLogger.bind("<>", self.outputText) self.txtLogger.grid(row = 1) self.txtLogger.tag_configure("error", foreground = "red") self.txtLogger.tag_configure("warning", foreground = "orange") self.txtLogger.tag_configure("success", foreground = "blue") self.__logger.debug("return from cLogToGUI::__init__") def outputText(self, event): self.__logger.debug("Inside cLogToGUI::outputText()") self.txtLogger.configure(state = NORMAL) string = TASymbols.strScrolledTextLine tag = TASymbols.strScrolledTextLineTag if not string: self.txtLogger.delete('1.0', END) else: self.txtLogger.insert(END, string, tag) #self.txtLogger.focus() self.txtLogger.see(END) self.txtLogger.configure(state = DISABLED) self.__logger.debug("return from cLogToGUI::outputText()") def __hsbScrollHandler(self, *L): op, howMany = L[0], L[1] if op == "scroll": units = L[2] self.txtLogger.xview_scroll ( howMany, units ) elif op == "moveto": self.txtLogger.xview_moveto ( howMany ) def __vsbScrollHandler(self, *L): op, howMany = L[0], L[1] if op == "scroll": units = L[2] self.txtLogger.yview_scroll ( howMany, units ) elif op == "moveto": self.txtLogger.yview_moveto ( howMany ) Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Thu Sep 18 18:24:26 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 18 Sep 2008 17:24:26 -0500 Subject: Intercepting printed strings Message-ID: <496954360809181524g6037e0b0x84e98834bbf8ad9c@mail.gmail.com> Hi, I'm currently using Python 3.0 b3 and I'm curious as to how I can go about intercepting things send to print() for some intermediate processing before they're actually sent to sys.stdout. Right now I've thought of the following: Replace sys.stdout with a class named PrintStream. PrintStream is defined as follows: class PrintStream: def write( self, message ): sys.__stdout__.write( '\t{0}'.format( message ) ) Will this work? Basically I want to add a tab character in front of every message printed. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Mon Sep 15 01:13:48 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 15 Sep 2008 00:13:48 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> <87od2q5a24.fsf@benfinney.id.au> <87k5de5841.fsf@benfinney.id.au> Message-ID: On 2008-09-15, Ben Finney wrote: > Grant Edwards writes: > >> On 2008-09-15, Ben Finney wrote: >> > I think it's more important for Python library APIs to comply with >> > the Python coding guidelines (as specified in PEP 8) than to >> > comply with standards in other languages. >> >> I think the practical matter of being able to use existing >> documentation and examples > > How are examples written in another language a "practical matter" for > using a Python library? Surely less "practical" than having one's > Python code base use a consistent style. If there is already a set of documentation and usage examples for the library, then changing the names just for the sake of "purity" means that you've now got documentation that's wrong. For example, the vast majority of wxPython consists of wrapped C++ library routines. There is a large body of existing documentation and sample code for those library routines, and they're all CamelCase. IMO, following that documentation is more important and useful than having all the names changed to agree with other Python libraries. (It's also a lot less work.) -- Grant From nevillednz at gmail.com Mon Sep 1 01:06:45 2008 From: nevillednz at gmail.com (Neville Dempsey) Date: Mon, 1 Sep 2008 15:06:45 +1000 Subject: enhancing/wrapping an existing instance of a duck In-Reply-To: References: Message-ID: What do I need to add to HTMLDecorator? A simpler example: import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("

","

")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() Output: Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters Can I simply decorate an existing instance? Cheers N From kyosohma at gmail.com Wed Sep 24 11:46:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Sep 2008 08:46:56 -0700 (PDT) Subject: urllib error on urlopen Message-ID: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> Hi, I have been using the following code for over a year in one of my programs: f = urllib2.urlopen('https://www.companywebsite.com/somestring') It worked great until the middle of the afternoon yesterday. Now I get the following traceback: Traceback (most recent call last): File "", line 1, in response = urllib2.urlopen(req).read().strip() File "c:\python25\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data) File "c:\python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "c:\python25\lib\urllib2.py", line 399, in _open '_open', req) File "c:\python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "c:\python25\lib\urllib2.py", line 1115, in https_open return self.do_open(httplib.HTTPSConnection, req) File "c:\python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: I tried my Google Fu on this error, but there's not much out there. I tried using a proxy in Python, but that returned the same traceback. If I copy the URL into my browser, it resolves correctly. Does anyone have any advice on how to troubleshoot this error? I am using Python 2.5.2 on Windows XP. Thanks, Mike From gstaniak at wp.pl Wed Sep 10 09:57:36 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Wed, 10 Sep 2008 13:57:36 +0000 (UTC) Subject: PHP's str_replace ? References: Message-ID: On 10.09.2008, Anjanesh Lekshminarayanan wroted: > In PHP, if I do > str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) > it'll replace all vowels with a hyphen in string $str. > > Is there some equivalent in Python ? The .translate() method of strings? >>> import string >>> mystr = "This is just a test" >>> transtable = string.maketrans("aeiouy","------") >>> mystr.translate(transtable) 'Th-s -s j-st - t-st' GS -- Grzegorz Staniak Nocturnal Infiltration and Accurate Killing From timr at probo.com Sat Sep 6 22:02:17 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 07 Sep 2008 02:02:17 GMT Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: cnb wrote: > >So is the free lunch really over or is this just an overhyped >phenomena? Remember that your computer is not running one single program. An idle computer on either Windows or Linux typically has dozens of processes running. Even if all of those programs are single-threaded, you'll still be able to keep all of the cores busy. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Wed Sep 10 07:45:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 13:45:54 +0200 Subject: List of modules available for import inside Python? In-Reply-To: References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: denisbz at t-online.de wrote: > how can I list all modules that might be importable on my system, > without actually importing them all ? I'm pretty sure I mentioned a way to do that back when this thread was opened. let's see, yes, here it is: ... there's a helper script in the 2.5 source code kit that locates all existing standard modules: http://svn.python.org/projects/python/tags/r252/Doc/tools/listmodules.py to get all modules, remove the for-loop that follows after the comment "get rid of site packages". also see: http://effbot.org/zone/listmodules-cgi.htm ... From lists at cheimes.de Tue Sep 2 16:41:51 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 02 Sep 2008 22:41:51 +0200 Subject: Numeric literal syntax In-Reply-To: References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <6i56cpFor2puU1@mid.individual.net> Message-ID: Fredrik Lundh wrote: > Peter Pearson wrote: > >> (startled noises) It is a delight to find a reference to >> that half-century-old essay (High Finance) by the wonderful >> C. Northcote Parkinson, but how many readers will catch the >> allusion? > > anyone that's been involved in open source on the development side for > more than, say, ten minutes. Indeed! Thus speaks the experienced developer -- effbot :) On some mailing lists the bikeshed issue comes hand in hand with the Dunning-Kruger-effect. [1] *sigh* Christian [1] http://en.wikipedia.org/wiki/Dunning-Kruger_effect From gagsl-py2 at yahoo.com.ar Tue Sep 23 03:26:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Sep 2008 04:26:14 -0300 Subject: gplt from scipy missing ? References: Message-ID: En Mon, 22 Sep 2008 23:19:49 -0300, Ivan Reborin escribi?: > I'm relatively new to python. I'm following a tutorial I found on the > net, and it uses scipy's gplt for plotting. > I installed scipy from their website (win32 installation), numpy also, > but when I do > > from scipy import gplt > > it gives this error: > > Traceback (most recent call last): > File "", line 1, in > from scipy import gplt > ImportError: cannot import name gplt > > Please, can you help me solve this ? How do I get gplt to work ? > All advice appreciated. I think scipy does not bundle plotting packages anymore - you may use whatever suits you, from other sources. Try matplotlib, see the wiki: http://wiki.python.org/moin/NumericAndScientific/Plotting -- Gabriel Genellina From david.lyon at preisshare.net Wed Sep 10 20:08:27 2008 From: david.lyon at preisshare.net (david.lyon at preisshare.net) Date: Wed, 10 Sep 2008 20:08:27 -0400 Subject: Web shopping carts In-Reply-To: References: Message-ID: <20080910200827.mo3h02ds5c40s0ss@syd-srv02.ezyreg.com> Quoting Luke Hamilton : > I am wondering if there are any OS shopping cart application written > in python? Hi Luke, I'm sure there are a few..... But recently I have been asked by two customers to provide a solution. So I'm thinking about the same thing. Actually, I've looked at a few systems like OS-commerce and so forth and my impression is that they are a bit old fashioned. As in, the web has moved a bit on since these projects started. Plus, I have customers in the computer industry, whose requirements are a bit different than the generalist cart programs. They want to pull prices in from spreadsheets and have price auto-calculations etc Basically, what I have put some work into has a search screen a bit like a search engine, and tries to combine leading edge javascript effects with a CherryPy/Cheetah back end. There's also some fantastic javascript slideshows out there.. I was never excited about what web systems could do.... until now.... javascript effects are just plain amazing... and what better to drive it than a python back end.... Let me know what you think... From ali.hamad34 at gmail.com Mon Sep 29 19:01:02 2008 From: ali.hamad34 at gmail.com (Ali Hamad) Date: Mon, 29 Sep 2008 18:01:02 -0500 Subject: Socket Question Message-ID: <48E15E2E.30901@gmail.com> Hello All : A socket question from a networking newbie. I need to create a server that: 1) receive a message from client. 2) check that message and response to it. 3) the client get the server message and send another message. 4) finally, the server receive the message and close the connection. I have successfully done this. However, I couldn't use the same socket to send the second message to the server. I have googled but all the examples are only for sending one message and receiving the response. in my client code, I have : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 1888)) s.send("1st message") response = s.recv(1024) validate(response) s.send("2nd message") response2 = s.recv(1024) s.close() However, I got the first response just fine from the server but the second message didn't get to the server. So, the solution I came up with is to send the 1st message, close the socket, create new socket, and send the 2nd message. I came up with something like : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 1888)) s.send("1st message") response = s.recv(1024) s.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 1888)) s.send("2nd message") response = s.recv(1024) s.close() and it works ! My Question : is it possible to send/receive from the same socket more than one message ? Thank you for your assistance in advance, From mail at timgolden.me.uk Mon Sep 1 12:09:49 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 01 Sep 2008 17:09:49 +0100 Subject: CSV reader and unique ids In-Reply-To: <6599d785-87b2-4bbc-97bc-799cac3640f5@b1g2000hsg.googlegroups.com> References: <6599d785-87b2-4bbc-97bc-799cac3640f5@b1g2000hsg.googlegroups.com> Message-ID: <48BC13CD.1010704@timgolden.me.uk> Mike P wrote: > I'm trying to use the CSV module to read in some data and then use a > hashable method (as there are millions of records) to find unique ids > and push these out to another file, You could either zip with a counter or use the uuid module, depending on just how unique you want your ids to be. import os, sys import csv import itertools import uuid stuff = "the quick brown fox jumps over the lazy dog".split () f = open ("output.csv", "wb") writer = csv.writer (f) # # Style 1 - numeric counter # writer.writerows (zip (itertools.count (), stuff)) # # Style 2 - uuid # writer.writerows ((uuid.uuid1 (), s) for s in stuff) f.close () os.startfile ("output.csv") TJG From bearophileHUGS at lycos.com Sun Sep 28 16:06:29 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 28 Sep 2008 13:06:29 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <24621a13-1199-42b8-a603-bd74964f2e92@j22g2000hsf.googlegroups.com> Terry Reedy: > Partly history and partly practicality. Len is implemented as .__len__ > ;-). The len function is one, __len__ methods are many. If you want to > pass an argument to a function, passing len is easier that passing > operator.attrgetter('__len__'). Passing '__len__' (or 'len') would be > easy, but using len is easier than using getattr(ob,'__len__'). A simple example may help: >>> seq = ["aaaa", "bb", "c", "ddd"] >>> seq2 = [[1,1,1,1], [2,2], [3], [4,4,4]] >>> sorted(seq, key=len) ['c', 'bb', 'ddd', 'aaaa'] >>> sorted(seq2, key=len) [[3], [2, 2], [4, 4, 4], [1, 1, 1, 1]] >>> sorted(seq, key=str.__len__) ['c', 'bb', 'ddd', 'aaaa'] >>> sorted(seq2, key=str.__len__) Traceback (most recent call last): File "", line 1, in TypeError: descriptor '__len__' requires a 'str' object but received a 'list' >>> from operator import attrgetter >>> sorted(seq, key=attrgetter("__len__")) ['aaaa', 'bb', 'c', 'ddd'] >>> sorted(seq2, key=attrgetter("__len__")) [[1, 1, 1, 1], [2, 2], [3], [4, 4, 4]] Bye, bearophile From gminick at bzt.bzt Wed Sep 3 10:34:12 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 3 Sep 2008 14:34:12 +0000 (UTC) Subject: properties setting each other References: Message-ID: On Wed, 3 Sep 2008 14:31:17 +0000 (UTC), Wojtek Walczak wrote: > class Square(object): > def __init__(self, val): > self._square = pow(val, 2) > self._value = math.sqrt(self.square) ^^^^^^^^^^^^^^^^^^^^^^ or just: self._value = val :-) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From straton at lampsacos.demon.co.uk Fri Sep 5 13:54:52 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 05 Sep 2008 18:54:52 +0100 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: David C. Ullrich wrote: > In article , > Ken Starks wrote: > >> David C. Ullrich wrote: >> >>> I don't see why you feel the two should act the same. >>> At least in mathematics, the sum of the elements of >>> the empty set _is_ 0, while the maximum element of the >>> empty set is undefined. >>> >>> And both for good reason: >>> >>> (i) If A and B are disjoint sets we certainly want to >>> have sum(A union B) = sum(A) + sum(B). This requires >>> sum(empty set) = 0. >>> >>> (ii) If A is a subset of B then we should have >>> max(A) <= max(B). This requires that max(empty set) >>> be something that's smaller than everything else. >>> So we give up on that. >> Do we give up? Really ? > > Erm, thanks. I was aware of all that below. If we're > being technical what's below is talking about the sup > and inf, which are not the same as max and min. More > relevant to the present context, I didn't mention what's > below because it doesn't seem likely that saying max([]) > = -infinity and min([]) = +infinity is going to make the > OP happy... > Of course you were aware, I have seen enough of your posts to know that. And I agree that, whatever Wikipedia seems to imply, max and supremum should be distiguished. It was your prelude, "At least in mathematics ..." that made me prick up my ears. So I couldn't resist responding, without _any_ malice I assure you. Cheers, Ken. From nevare.stark at gmail.com Sun Sep 28 06:01:12 2008 From: nevare.stark at gmail.com (Olivier Lauzanne) Date: Sun, 28 Sep 2008 03:01:12 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <66606235-be55-458a-9e14-09e6c766201d@p31g2000prf.googlegroups.com> Message-ID: On Sep 28, 11:21 am, est wrote: > On Sep 28, 4:38 pm, Steven D'Aprano Can anyone tell me how to customize a default encoding, let's say > 'ansi' which handles range(256) ? I assume you are using python2.5 Edit the file /usr/lib/python2.5/site.py There is a method called def setencoding(): [...] encoding = "ascii" [...] Change "encoding = "ascii" to encoding = "utf-8" On windows you may have to use "mbsc" or something like that. I have no idea what windows use at its encoding. As long as all systems don't use the same encoding (let's say utf-8 since it is becoming the standard on unixes and on the web) using ascii as a default encoding makes sense. From bj_666 at gmx.net Tue Sep 2 14:47:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 18:47:39 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> Message-ID: <6i5g2aFol29aU6@mid.uni-berlin.de> On Tue, 02 Sep 2008 11:39:09 -0400, Derek Martin wrote: > On Tue, Sep 02, 2008 at 01:57:26PM +0000, Marc 'BlackJack' Rintsch > wrote: >> > I would argue that they don't represent processes at all; the object >> > is a set of files which connect the standard I/O streams of a >> > subprocess to its parent, and methods to operate on those files. >> >> And the process' ID, an attribute with the process' return code, a >> method to wait until the process is finished and file objects to >> communicate with the process. > > The name popen is an abbreviation of "pipe open" -- the function, and > the class, open pipes to communicate with another process. What you > said is correct; however there are numerous other ways to open > subprocesses. The focus of popen is the communication aspect -- the > opening and control of the pipes -- not the subprocess. That's the key > difference between popen() and all the other methods of starting a > subprocess. But I'm not talking about the `popen()` function but the `subprocess.Popen` class. >> > The C library's popen() function, on which this class is based, >> > provides a means to open a file and connect it to the standard steams >> > of a subprocess, making it more closely analogous to what the Popen >> > class does/provides. As such, "Popen" is a better name to describe >> > this object than "subprocess" would be. >> >> Is strongly disagree. The class provides an interface to start and >> communicate with a `Subprocess`. Instances stand for processes. > > There's more than one way to look at it. You can disagree all you like, > but your interpretation disagrees with the historical intent of popen. That's why I think the name `Popen` is not so good for it. Because it does more than `popen()` and if it is called `Subprocess` or just `Process` then it would be merely an implementation detail, that the `popen()` function is called at some point. If it is at all, because `popen()` on C level can just open a pipe in *one* direction. > Note that in all of these links that talk about popen, the focus is on > opening pipes or file objects, not on subprocesses: > > http://www.opengroup.org/onlinepubs/009695399/functions/popen.html > http://docs.python.org/lib/os-newstreams.html http://us3.php.net/popen > http://docs.hp.com/en/B9106-90010/popen.3S.html > http://www.faqs.org/docs/artu/ch07s02.html And all of the links talk about the `popen()` function, not about the functionality the `Popen` class provides. Which is much more than that simple pipe `popen()` returns. > The Linux man page unfortunately copies (verbatim) the FreeBSD man page, > which gets it wrong. You can not open a process, but you can definitely > open a pipe. Ah, when their terminology doesn't match yours, they must get it wrong. ;-) Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:03:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:03:43 GMT Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> Message-ID: <00eaeb52$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 10:54:40 -0500, Grant Edwards wrote: > You're right. I had forgotten that sys.exit() is actually raising the > system exit exception, and that the application calling the library > could handle that exception. Could but shouldn't. The exception hierarchy was re-designed in Python 2.5 specifically so that SystemExit and KeyboardInterrupt no longer inherit from Exception. That means this will do the right thing: try: process(record) if changed: update(record) except Exception: # don't write the record if any error occurs pass Neither SystemExit nor KeyboardInterrupt are errors, and they should not be treated as errors. I quote from the Fine Manual: [SystemExit] inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit. http://docs.python.org/lib/module-exceptions.html SystemExit is not an error. KeyboardInterrupt is not an error. Libraries should not use SystemExit to signal an error any more than they should use MemoryError to signal a missing attribute. Whether or not an application exits is up to the application to decide, not the library it wraps. Libraries should report errors by raising an Exception (note the capital E), and the application should decide whether or not it is recoverable, and if not, exit (perhaps by simply not catching the exception). -- Steven From jinbow at gmail.com Mon Sep 8 08:47:54 2008 From: jinbow at gmail.com (Mars creature) Date: Mon, 8 Sep 2008 05:47:54 -0700 (PDT) Subject: Read and write binary data References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: On Sep 7, 8:55 pm, Patrick Maupin wrote: > On Sep 7, 5:41 pm, Mars creature wrote: > > > Hi guys, > > I am new to Python, and thinking about migrating to it from matlab > > as it is a really cool language. Right now, I am trying to figure out > > how to control read and write binary data, like > > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > > I googled, but can not find a clear answer. Anyone has clue where can > > I learn it? Thanks!! > > Jinbo > > Start by looking at the array module. > > Regards, > Pat Thanks!! From castironpi at gmail.com Thu Sep 25 21:01:22 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 25 Sep 2008 18:01:22 -0700 (PDT) Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sep 25, 2:24?pm, python-... at arcor.de wrote: > Hi, > > sorry, I have these ideas for longer than 10 years, please have a look on it > and comment on it. Thx. > > ---- > > This is another proposal for introducing types into Python. > > There are many reasons for incorporating types into Python, but there is > also a lot of concern about doing so because of destroying the original > character of Python as a smart script language. > > This proposal adds several advantages of Prolog(ue) techniques without > changing the natural understanding of Python as a language. > > Proposal: > > 1. Method definitions can be non-unique if a type is prefixed to one or more > of its parameters, or the parameters differ in number. > > 2. A keyword 'reject' is added. > > 3. A keyword 'fail' is added. > > 4. A keyword 'cut' is added. > > Definition: > > 1. A "type" is a String naming the actual class or class family which the > passed instanced is derived from, prefixing the parameter. > > 2. "'reject'" is a marker inside a function/method and signals that further > processing will not be done inside this method, but instead be passed to the > next available function/method in row, otherwise an implicit "fail" will > occur. > > 3. "'fail'" is a marker inside a function/method and signals that NO further > processing can be done in neither of this or the following > functions/methods. > > 4. "'cut'" is a marker inside a function/method that signals that the > failure of called functions/methods inside of it, following this statement, > automatically lead to a failure, instead of trying the next method - > normally, it would be "reject" instead. > > 5. Failure of functions/methods to outside of this new context are signalled > with a new exception e.g. "MethodRetrialError". > > E.g. > > def whoisthethief("List" x): > ? return iknowit(x) > > def whoisthethief("String" x, "String" y): > ? return iknowit([x,y]) > > ########## > > def numeral_add(a, b): > ? if type(a)!=types.IntType: > ? ? reject > ? ... > > # equivalent to: > > def numeral_add("Integer" a, b): > ? ... Would you settle for a class or classes which had the same functionality, only you would call its methods with parentheses? Modified examples: @argtype( List ) def whoisthethief(x): return iknowit(x) @argtype( String, String ) def whoisthethief(x, y): return iknowit([x,y]) def numeral_add(a, b): if type(a)!=types.IntType: reject() ... /or: def numeral_add(a, b): if type(a)!=types.IntType: flow.reject() ... From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 13:53:05 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 19:53:05 +0200 Subject: Coming from .NET and VB and C In-Reply-To: References: Message-ID: <48beeaf1$0$12000$426a74cc@news.free.fr> ToPostMustJoinGroup22 a ?crit : > I'm coming from a .NET, VB, C background. > > C was good, and VB was better (with all of its libraries). Than .NET > came along and all the libraries you can require are ready to go. I > have no preference with MySQL or SQL, stored procedures or ad-hoc > queries. > > SO, I'm interested in using my Google App space (free 500MB) to > develop a quick database application. Using Python. I found "Dive > Into Python" which I will be reading shortly. > > Any suggestions for someone new to the scene like me? The worst thing you could would be to try to write VB in Python. While Python may not - for someone coming from more mainstream languages - look as weird as Lisp or Haskell or etc..., it's really a totally different beast. Lurking here, trying to answer other's persons questions, and reading other peoples solution might be a good way to learn idiomatic Python. From gagsl-py2 at yahoo.com.ar Thu Sep 25 16:04:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Sep 2008 17:04:54 -0300 Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Message-ID: En Thu, 25 Sep 2008 16:24:58 -0300, escribi?: > sorry, I have these ideas for longer than 10 years, please have a look > on it > and comment on it. Thx. > > This is another proposal for introducing types into Python. You got the terminology wrong. Python had "types" from the very start. You're talking about some kind of generic functions, or an alternative dispatch method. Read this GvR blog post [1] and his next one; also see PEP 3124 by Phillip J. Eby, who wrote a pretty good implementation of generic functions a long time ago. Your proposal requires a syntax change and three new keywords; all the others achieve roughly equivalent results without requiring any change to the core language. [1] http://www.artima.com/weblogs/viewpost.jsp?thread=155123 -- Gabriel Genellina From george.sakkis at gmail.com Tue Sep 23 13:50:52 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 23 Sep 2008 10:50:52 -0700 (PDT) Subject: Docstrings for class attributes References: Message-ID: On Sep 23, 1:23 am, "Tom Harris" wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. Sort of > a very limited implementation of PEP 224. The only solution that I can > see is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Here's one approach, using metaclasses and descriptors; it sort of works, but it's less than ideal, both in usage and implementation. George #====== usage ============================================ class MyConstants: __metaclass__ = ConstantsMeta FOO = const(1, 'some docs about foo') BAR = const(2) print MyConstants.FOO.__doc__ help(MyConstants.FOO) print MyConstants.FOO - MyConstants.BAR print MyConstants.FOO - 2 print 1 - MyConstants.BAR #======= implementation =================================== def ConstantsMeta(name, bases, namespace): for name,attr in namespace.iteritems(): if isinstance(attr, const): namespace[name] = _ConstDescriptor(name, attr.value, attr.doc) return type(name, bases, namespace) class const(object): def __init__(self, value, doc=None): self.value = value self.doc = doc class _ConstDescriptor(object): def __init__(self, name, value, doc): cls = type(name, (), dict( __doc__ = doc, __add__ = lambda self,other: value+other, __sub__ = lambda self,other: value-other, # ... __radd__ = lambda self,other: other+value, __rsub__ = lambda self,other: other-value, # XXX lots of boilerplate code for all special methods follow... # XXX Is there a better way ? )) self._wrapper = cls() def __get__(self, obj, type): return self._wrapper From mccredie at gmail.com Mon Sep 22 17:52:39 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 22 Sep 2008 14:52:39 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> Message-ID: <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> On Sep 22, 2:31?pm, CapnBearbo... at googlemail.com wrote: > hi all, > > forgive me , but the RTFM and Google search approaches are not > yielding an answer on this question. ?I need to know if there's a top > level python interpreter command that clears all user variables (not > built-ins) from the global namespace. ?In other words a statement, or > some_command_or_function(), that does this: > > >>> x=3 > >>> y=4 > >>> z=[] > >>> dir() > > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > > >>> some_command_or_function() > >>> dir() > > ['__builtins__', '__doc__', '__name__'] > > thanks, > ? ?1 desperate snake oil programmer .... I don't think you will find anything. The interpreter is essentially the same whether you are in interactive mode or not. That is, there is very little use for a method that clears globals in general, so why would we add it just so that it could be used by the interpreter. There is almost* nothing available to the interactive interpreter which isn't part of the core language. * The only difference I can think of is the "_" variable, which is added to __builtins__ and contains the last value returned in interactive mode. If you have ever tried to run code that uses the locale module from the interpreter you will see why having any differences between the interactive and non-interactive interpreter can be a pain. Matt From mark.dufour at gmail.com Tue Sep 30 06:19:17 2008 From: mark.dufour at gmail.com (Mark Dufour) Date: Tue, 30 Sep 2008 12:19:17 +0200 Subject: Shed Skin (restricted) Python-to-C++ compiler 0.0.29 Message-ID: <8180ef690809300319o66cb9096sa4be2e5068836024@mail.gmail.com> Hi all, I have just released Shed Skin 0.0.29, with the following changes. Thanks to those mentioned for helping out! - datetime implementation (Karel Heyse, Pavel Vinogradov, FFAO, David Marek) - ConfigParser implementation (suggested by Albert Hofkamp) - staticmethod and property decorator support (Seo Sanghyeon) - GCC 4.3 fixes (Seo Sanghyeon, Winterknight) - FreeBSD, OpenSolaris and 64-bit support - support for mapping keys('%(key)x' % some_dict) - improvements to the import mechanism for nested modules (e.g. os.path) - __init__ is now less of a special case - many fixes for calling ancestor methods (e.g. __init__) - all example programs now compile to extension modules - avoid stack overflows for highly recursive/dynamic types - re.sub now accepts a replacement function - remove tuple hash caching (as CPython does not do this) - many, many bugfixes This has been a significant release, with many important improvements. Please see my latest blog entry with more details: http://shed-skin.blogspot.com/ I would really like to receive more bug reports. Please try out the new release, and file issues at the project homepage: http://shedskin.googlecode.com More coding help is also always welcome. One important feature I'd really like to have for a 0.1 release is custom class support in extension modules.. Thanks! Mark. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From gboutsioukis at gmail.com Mon Sep 29 13:03:00 2008 From: gboutsioukis at gmail.com (George Boutsioukis) Date: Mon, 29 Sep 2008 17:03:00 +0000 (UTC) Subject: One class per file? References: Message-ID: <1222707780.889897@athprx03> On Mon, 29 Sep 2008 06:12:35 -0700, HCB wrote: > Hello: > > The book "Code Complete" recommends that you put only one class in a > source file, which seems a bit extreme for me. It seems that many > classes are small, so that putting several of them in a file seems > reasonable. I noticed that the decimal.py module in the standard library > has several classes, all of which of course revolve around the "decimal" > topic. Perhaps a better rule of thumb is "one idea per file." I checked > the Python style guide and there seems to be no mention of this topic. I > know this is an elementary question, but what is the Python way of doing > this? > > Thanks for your time. > HCB That sounds terrible! Imagine having a million source files to edit, rename, create, delete each time you make a change. Sure, every Java fan can give you a million reasons why the universe will collapse otherwise, but this is totally impractical in python. Python's module organization and namespaces are more than enough if used reasonably. From stefan_ml at behnel.de Thu Sep 11 13:07:05 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 11 Sep 2008 19:07:05 +0200 Subject: Is there a SOAP module that can do this...? In-Reply-To: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> References: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> Message-ID: <48c95039$0$3535$9b4e6d93@newsspool3.arcor-online.net> thebjorn wrote: > I've been trying to use SOAPpy and ZSI (with and without the use of > wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic > server(?) in front of some enterprise java bean) and not having much > luck. Have you tried using soaplib? I find it very usable and from what I heard so far, a couple of other people also like it a lot better than ZSI. Stefan From niklas.norrthon at hotmail.com Tue Sep 16 09:36:34 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Tue, 16 Sep 2008 06:36:34 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? References: <92d472c8-4af1-432a-a240-f9f9c97686eb@m73g2000hsh.googlegroups.com> Message-ID: On 16 Sep, 15:27, cnb wrote: > i can run the interpreter. its just i cant load a file into it. > > i tried adding your suggestion but it didnt help. i dont think thats > the issue though. Start the interperter (Menu Python - Start interpreter) Emacs split the frame in two windows Place the cursor in the python file (C-x o) if necessary Eval Buffer (C-c C-c) Niklas Norrthon From fredrik at pythonware.com Mon Sep 1 10:45:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Sep 2008 16:45:24 +0200 Subject: Eleganz way to get rid of \n In-Reply-To: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: Hans M?ller wrote: > I'm quite often using this construct: > > for l in open("file", "r"): > do something > > here, l contains the \n or \r\n on windows at the end. nope -- if you open a file in text mode (without the "b"), the I/O layer will translate "\r\n" to "\n" on Windows. if you want even more robust behaviour, use the "U" flag (for universal newlines); that'll handle old-style Mac files too. (as others have pointed out, a plain rstrip() is usually the best choice anyway. giving meaning to trailing whitespace in text files is usually a really lousy idea). From d3vvnull at gmail.com Wed Sep 24 16:34:37 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Wed, 24 Sep 2008 15:34:37 -0500 Subject: Fwd: Twisted vs. CherryPy vs. ??? for light-weight web servers In-Reply-To: <170543c70809241334t4d687c50s3fd6e7fe4b4bab1d@mail.gmail.com> References: <170543c70809231922m23531eb9i1f7fdead10bb1e0e@mail.gmail.com> <20080924172915.29191.775453525.divmod.quotient.30199@ohm> <170543c70809241334t4d687c50s3fd6e7fe4b4bab1d@mail.gmail.com> Message-ID: <170543c70809241334o1e5642chd44a85209867d39b@mail.gmail.com> I just want to be able to write simple scripts to serve xml data and don't want the headache of administrating an apache server. I want to collect some data from some of our production servers and share them with a sharepoint website. On Wed, Sep 24, 2008 at 12:29 PM, Jean-Paul Calderone wrote: > On Tue, 23 Sep 2008 21:22:08 -0500, Michael Mabin > wrote: > >> Is there any consensus on what the best lightweight web-server is? Or >> rather would Twisted be a better choice to choose as a framework that >> allows >> me to serve html or xml data for light webservices. Or is CherryPy just as >> good? >> >> > You haven't described the problem you want to solve in very much detail. I > can't tell, for example, why I shouldn't recommend that you use Apache > instead > of CherryPy or Twisted or anything else. Apache has a huge user community, > lots of documentation, and lots of developers fixing its bugs and making it > work well. What are you trying to do that would make Apache a bad choice? > > Jean-Paul > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From malcolm.lewis at gmail.com Tue Sep 2 09:26:03 2008 From: malcolm.lewis at gmail.com (Malcolm Lewis) Date: Tue, 2 Sep 2008 06:26:03 -0700 Subject: How do I adjust the font size on IDLE when running on Mac OS 10.5.4? TIA. Message-ID: <16a5d0100809020626w78312e35l52b7c73eabf8add4@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Sep 26 21:58:30 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 18:58:30 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> Message-ID: <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> On Sep 26, 8:10?pm, "Tim Rowe" wrote: > 2008/9/27 Aaron Castironpi Brady : > > > But I, and I imagine I'm not the only one, would love to know the > > example that C# developed faster than Python. ?I suppose the fact that > > the line of wx specification that has two identifiers where C# has one > > is more of a drain on programmer resources than may commonly be > > recognized--- not the same as the cost of one extra word in a paper or > > in an editorial. ?Similarly, maybe the program that has one extra > > identifier in a line takes a lot more time to develop. > > But I didn't use wx -- that's rather the point. ?Long before the days > of Python, I kept wanting to use Modula2 but kept getting driven back > to C because in Modula2 I kept having to write stuff that was already > in C libraries. Modula2 was a far better language, but C usually was > far more productive because of what went around it. ?C#'s tight > integration with .net and VS mean that it's not a question of one > identifier instead of two, it's *zero* identifiers instead of two > because the tool does it all for me. ?Does that mean that C# is a > better language than Python? No, of course not. Does it mean that what > I was doing was not possible in Python? No, of course not. Does it > mean that C# was more productive than Python for me doing that > particular job? Yes it does. (FWIW, I also found the .net XML handling > easier to cope with on that same job). > > One day Iron Python plus the VS integration might wean me off C# but > last time I looked it wasn't close. Maybe I should take another look > and see how it's coming on. > > -- > Tim Rowe No way. It's *zero* instead of one, if so, because the only thing C# has is a bunch of handcuffs and implicit 'self'. You have a line like: n= aTree.ExpandedCount What in 'wx', which I -am- using, , takes more identifiers: n= self.aTree.ExpandedCount or if you're 'inlining', for lack of better words, everything, outside a class, n= aForm.aTree.ExpandedCount. For a grand total of 1 'aForm' identifier that C# infers implicitly. From tjreedy at udel.edu Wed Sep 24 23:39:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2008 23:39:21 -0400 Subject: Off topic: Sent from my Foo messages In-Reply-To: <00eaf368$0$20666$c3e8da3@news.astraweb.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <00eaf368$0$20666$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I'm seeing more and more posts from various people, on this list and > others, with statements like the following: > > On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote: > >> Sent from my iPhone > > Also "Sent from my Blackberry" and similar. > > Without wishing to be rude to David, who I'm sure is a nice guy and not > at all the pretentious git that such a line makes him appear, are people > adding this comment to the bottom of their posts, or is it something that > their device automatically appends to the post? > > If people are adding it themselves, that's nice, I'm sure you're really > excited about your new toy, but the rest of us don't care a monkey's > toss. And if the device is automatically appending it, I think that's > pretty damn rude and a good reason to avoid buying the obnoxious machines. At least it is just one tag line and the the 20 lines of legal 'If you received this in error' spam some organizations tack on the end ;-). From faltet at gmail.com Mon Sep 15 05:34:22 2008 From: faltet at gmail.com (Francesc) Date: Mon, 15 Sep 2008 02:34:22 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> Message-ID: On 12 Set, 14:39, "Aaron \"Castironpi\" Brady" wrote: > > A consideration of other storage formats such as HDF5 might > > be appropriate: > > >http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > > There are, of course, HDF5 tools available for Python. > > PyTablescame up within the past few weeks on the list. > > "When the file is created, the metadata in the object tree is updated > in memory while the actual data is saved to disk. When you close the > file the object tree is no longer available. However, when you reopen > this file the object tree will be reconstructed in memory from the > metadata on disk...." > > This is different from what I had in mind, but the extremity depends > on how slow the 'reconstructed in memory' step is. (Fromhttp://www.pytables.org/docs/manual/ch01.html#id2506782). The > counterexample would be needing random access into multiple data > files, which don't all fit in memory at once, but the maturity of the > package might outweigh that. Reconstruction will form a bottleneck > anyway. Hmm, this was a part of a documentation that needed to be updated. Now, the object tree is reconstructed in a lazy way (i.e. on-demand), in order to avoid the bottleneck that you mentioned. I have corrected the docs in: http://www.pytables.org/trac/changeset/3714/trunk Thanks for (indirectly ;-) bringing this to my attention, Francesc From mccredie at gmail.com Wed Sep 3 15:51:32 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 3 Sep 2008 12:51:32 -0700 (PDT) Subject: creating a similar object from an derived class References: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> Message-ID: <99551c67-262c-4b9c-b705-8292e627c48c@z6g2000pre.googlegroups.com> On Sep 3, 12:09?pm, Scott wrote: > Let's say I have an object: > > class foo(): > ? ?def create_another() > ? ? ? ?return foo() > > ? ?def blah(): > ? ? ? ?x = self.create_another() > ? ? ? ?... do something with X > > Now I create a inherited class of this object: > > class bar(foo): > ? ? ... > > If I call bar.create_another(), it will return a foo() instead of a > bar(). This isn't what I want. I would like bar.create_another() to > create an instance for bar(). Obviously I can do this by overriding > create_another, i.e. > > class bar(foo): > ? ? def create_another() > ? ? ? ? return bar() > > However, is there a way for me to modify foo() so that it > automatically creates objects of the derived class, so that I don't > have to continue to redefine create_another() ? > > For example, I tried the following: > > def create_another() > ? ? return self.type()() > > but it did not work. > > Thanks, > Scott This works: >>> class C(object): ... @classmethod ... def create_another(cls): ... return cls() ... >>> class D(C): ... pass ... >>> d = D() >>> e = d.create_another() >>> isinstance(e, D) True Matt From rocksportrocker at googlemail.com Wed Sep 3 07:31:52 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Wed, 3 Sep 2008 04:31:52 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: <2aa4ef17-50d3-4aeb-9e7e-0d2d9b9237d4@w7g2000hsa.googlegroups.com> On 2 Sep., 18:55, Steven D'Aprano wrote: > I find myself writing command line tools in Python where I wish to > include "verbose" output to stdout. > > I start with a helper function: > > def print_(obj, level=0): > ? ? if _verbosity >= level: > ? ? ? ? print obj > > And then I end up with functions or methods looking like this: > > def parrot(x) > ? ? print_("precondition", level=2) > ? ? do_something() > ? ? print_("status is good...", level=1) > ? ? print_("parrot is squawking strongly now", level=2) > ? ? do_something_else() > ? ? print_("squawk squawk squawk", level=3) > ? ? do_more() > ? ? print_("postcondition", level=1) > ? ? return something > > That often means that my functions end up with more message printing code > than actual code. The whole thing seems messy and hard to manage for all > but the smallest scripts. > > Worst of all, sometimes the messages I wish to print may be expensive to > compute, and I don't want to waste time computing them if they aren't > going to be printed because the verbosity is too low. But nor do I wish > to fill my code with this: > > if _verbosity >= 3: > ? ? x = calculate_complicated_thing() > ? ? print_(x, level=3) > > Is there a better way of doing this than the way I am going about it? > > -- > Steven You can save some code if you use function decorators for logging input and output values of functions. So write lots of functions containing one statement and your problem is solved ;-) Greetings, Uwe From paddy3118 at googlemail.com Mon Sep 22 23:44:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 22 Sep 2008 20:44:14 -0700 (PDT) Subject: Python Fractions issue. Message-ID: (From: http://paddy3118.blogspot.com/2008/09/python-fractions-issue.html) There seems to be a problem/difference in calculating with the new fractions module when comparing Python 26rc2 and 30rc1 I was reading the paper "Interval Arithmetic: Python Implementation and Applications" and thought to try the first example function f(x,y), which needs more precision than Python floating point provides (on my Windows PC), to calculate a sensible answer. Ahah, I thought, lets try this with Fractions - so I first installed Python 30rc1, typed in the Function - saw the rubbish result, then used Fractions and got the 'right' result. I then wondered if fractions had been back-ported to Python 2.6rc2, found that it had, but got different results. As you can see from the table, Python 2.6rc2 has a problem calculating t3 = F(11,2) * y**8 + x/(2*y), where F is Fraction. I wonder where the problem lies? (For the Table, please see the blog entry). - Paddy. From deets at nospam.web.de Mon Sep 1 02:40:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 08:40:42 +0200 Subject: Processes in Linux from Python In-Reply-To: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> References: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> Message-ID: <6i1h3cFog1v1U1@mid.uni-berlin.de> Johny schrieb: > To get a number of the http processes running on my Linux( Debia box) > I use > ps -ef | grep "[h]ttpd" | wc -l > > But If I want to use to get a number of the http processes from my > Python program I must use a popen command e.g. > popen2.popen3('ps -ef | grep "[h]ttpd" | wc -l') > that is I must call an external command from Python. The shell does the exact same thing. And by the way: i think you miss a grep -v grep after the first grep - otherwise you count the grep itself. > But it creates a zombie. Try using the subprocess module. It should not require you to call wait yourself. > So my question is: > Is it possible to get a number of the http processes running on Linux > directly from Python ? Not really, or at least not with less effort & without duplicating system tools functionality. Diez From peter.waller at gmail.com Sat Sep 13 07:35:29 2008 From: peter.waller at gmail.com (Peter Waller) Date: Sat, 13 Sep 2008 04:35:29 -0700 (PDT) Subject: Injecting new names into the above frame References: <57uyk.101$fD.22@flpi145.ffdc.sbc.com> Message-ID: On Sep 12, 2:30?pm, Carsten Haese wrote: > > The answer to why this doesn't work lies in the disassembly of that > function: This makes me want to ask: is it difficult to modify a function's code? Even if it weren't possible whilst the function was executing (because then I would be returning to a function I just created, I guess?) Could I make another function which converted this LOAD_GLOBAL to LOAD_FAST? I agree that in general a function should have no side effects and I would like to know exactly what it is going to do, and that what I'm doing is unpythonic. My curiosity extends because I would like to get to know a bit more about python's internals. My gut tells me there has to be a way to achieve what I'm after - even if it the result is extremely ugly. Maybe it might involve applying a decorator to functions who use this functionality, who change the code so that these calls work? Cheers for your reply, - Pete From d3vvnull at gmail.com Fri Sep 26 18:06:25 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 17:06:25 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> References: <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> Message-ID: <170543c70809261506x4e326c9fn3909f35b70e30e1f@mail.gmail.com> oops. i meant. '.... in (%s)' % ','.join([str_edit_for_exploit(x) for x in aList]) On Fri, Sep 26, 2008 at 5:05 PM, Michael Mabin wrote: > so you wouldn't object then to something like '.... in (%)' % > ','.join([str_edit_for_exploit(x) for x in aList]) > > if str_edit_for_exploit applied security edits? > > On Fri, Sep 26, 2008 at 2:28 PM, Benjamin Kaplan > wrote: > >> >> >> On Fri, Sep 26, 2008 at 3:04 PM, Michael Mabin wrote: >> >>> Doesn't it depend on where and why you intend to execute the code? >>> Obviously some SQL is more at risk for exploit when the input is from the >>> screen on a web page than if you were running parameterized code in a >>> controlled batch environment. Or if you were writing code generators (which >>> is what I happen to do) which won't be run by the general public. >>> >>> Incidentally, couldn't input field edits prevent such exploits prior to >>> interpolation? >>> >> >> There are ways to avoid SQL injection attacks, such as escaping all quotes >> in the text. We were simply pointing out that you have to be very careful >> when you add arbitrary strings into SQL statements. If you control >> everything going into the statement, you shouldn't have to worry about this. >> >> >> > > > -- > | _ | * | _ | > | _ | _ | * | > | * | * | * | > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From giltay at gmail.com Thu Sep 18 15:44:43 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Thu, 18 Sep 2008 12:44:43 -0700 (PDT) Subject: Blanket font setting? References: <48d287e5$1@news.alcatel.com> Message-ID: <685d29f9-0525-45b8-ab52-f1a917c7d1ca@x16g2000prn.googlegroups.com> On Sep 18, 12:55?pm, RGK wrote: > Is there any sort of blanket font setting, perhaps like: > > ? ?wx.SystemSettings_SetFont(font) ? #this doesn't exist > > that could set everything with one fell swoop? > > Thanks for your attention... > > Ross. I do this by setting the font in each frame (or dialog); the font propogates to its descendants. http://lists.wxwidgets.org/pipermail/wxpython-users/2008-September/080099.html Geoff G-T From durand1 at gmail.com Sat Sep 6 11:58:57 2008 From: durand1 at gmail.com (Durand) Date: Sat, 6 Sep 2008 08:58:57 -0700 (PDT) Subject: [matplotlib] Overlapping axis text Message-ID: I got a really annoying problem with datetime graphs. The problem is that with a long range time graph, the text on the x axis keeps overlapping like here: http://durand.zephyrhosting.net/tremcs/graph_all.png Would there be any way to fix this? I was thinking of rotating the text so that there was enough space for each one but the best solution would be to only display text with the right scale. IE, with a 7 day graph, each day would have text, with a year long graph, each month would be displayed, etc... This is the code I use at the moment but its pretty messy: import dateutil,pylab from matplotlib.dates import MonthLocator, WeekdayLocator fig = pylab.figure() ax = fig.add_subplot(111) days = MonthLocator() # every monday months = MonthLocator() # every month ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(days) pylab.plot_date(pylab.date2num(dates), allkills, '.-', color='blue') pylab.plot_date(pylab.date2num(dates), alldeaths, '.-', color='red') pylab.plot_date(pylab.date2num(dates), kills, '.-', color='darkgreen') pylab.plot_date(pylab.date2num(dates), deaths, '.-', color='orange') if legend == 1: pylab.legend(("Total Kills","Total Deaths", "Single Session Kills", "Single Session Deaths"), 'lower left') pylab.xlabel('Date') pylab.ylabel('Stats') ax2 = pylab.twinx() pylab.plot_date(pylab.date2num(dates), allratio, '.-', color='purple') pylab.plot_date(pylab.date2num(dates), ratio, '.-', color='yellow') pylab.ylabel('Ratio') ax2.yaxis.tick_right() pylab.show() Please excuse the extra tabbing, it's part of an if statement. From fredrik at pythonware.com Sun Sep 7 18:02:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 00:02:35 +0200 Subject: Updating python dictionary In-Reply-To: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: andyhume at gmail.com wrote: > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? since none of your dictionaries contain the keys you want in the final dictionary, creating a brand new dict sounds pretty clever to me. From gagsl-py2 at yahoo.com.ar Fri Sep 5 01:05:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 02:05:16 -0300 Subject: Help needed to freeze a script. References: <7f364174-75c6-4120-b00e-6f41643ccbf5@z72g2000hsb.googlegroups.com> <614c7366-ba7e-4296-a4f0-a32accaa427a@b38g2000prf.googlegroups.com> <0957cba5-9aa8-41d6-bf95-9d6a8db18c89@l33g2000pri.googlegroups.com> Message-ID: En Thu, 04 Sep 2008 14:11:45 -0300, LB escribi?: > Do you know if py2exe executable embedding a lot of C extensions - > like numpy and scipy - can ben executed on another computer, with a > different architecture (64bits vs 32 bits) and a different OS ? Forget it, Jake. -- Gabriel Genellina From news1234 at free.fr Wed Sep 10 17:09:54 2008 From: news1234 at free.fr (nntpman68) Date: Wed, 10 Sep 2008 23:09:54 +0200 Subject: Reading binary data In-Reply-To: References: Message-ID: <48c837a0$0$9135$426a34cc@news.free.fr> What I would do first is to print the result byte by byte each as hexadecimal number. If you can I would additionally populate the C-structure with numbers, which are easier to follow. Example: signature = "ABC" // same as 0x41 0x42 0x43 version = 0x61626364 attr_count = 0x65667678 . . . assuming version == 2 (0x00000002) the first byte should be 'G' == 0x47 ) if the 4th byte value 2, than you unaligned uint32s and you are little endian if the 5th byte is 2, then you have 4 byte aligned uint32s and little endian if the 7th byte is 2 then you should have unaligned uint32s and big endian if the 8th byte is 2 then you should have 4 byte aligned uints32 and big endian bye N Aaron Scott wrote: > I've been trying to tackle this all morning, and so far I've been > completely unsuccessful. I have a binary file that I have the > structure to, and I'd like to read it into Python. It's not a > particularly complicated file. For instance: > > signature char[3] "GDE" > version uint32 2 > attr_count uint32 > { > attr_id uint32 > attr_val_len uint32 > attr_val char[attr_val_len] > } ... repeated attr_count times ... > > However, I can't find a way to bring it into Python. This is my code > -- which I know is definitely wrong, but I had to start somewhere: > > import struct > file = open("test.gde", "rb") > output = file.read(3) > print output > version = struct.unpack("I", file.read(4))[0] > print version > attr_count = struct.unpack("I", file.read(4))[0] > while attr_count: > print "---" > file.seek(4, 1) > counter = int(struct.unpack("I", file.read(4))[0]) > print file.read(counter) > attr_count -= 1 > file.close() > > Of course, this doesn't work at all. It produces: > > GDE > 2 > --- > ? > --- > ? ? > > I'm completely at a loss. If anyone could show me the correct way to > do this (or at least point me in the right direction), I'd be > extremely grateful. From mensanator at aol.com Tue Sep 2 13:52:58 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 2 Sep 2008 10:52:58 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: On Sep 2, 11:55 am, Steven D'Aprano wrote: > I find myself writing command line tools in Python where I wish to > include "verbose" output to stdout. > > I start with a helper function: > > def print_(obj, level=0): > if _verbosity >= level: > print obj > > And then I end up with functions or methods looking like this: > > def parrot(x) > print_("precondition", level=2) > do_something() > print_("status is good...", level=1) > print_("parrot is squawking strongly now", level=2) > do_something_else() > print_("squawk squawk squawk", level=3) > do_more() > print_("postcondition", level=1) > return something > > That often means that my functions end up with more message printing code > than actual code. The whole thing seems messy and hard to manage for all > but the smallest scripts. > > Worst of all, sometimes the messages I wish to print may be expensive to > compute, and I don't want to waste time computing them if they aren't > going to be printed because the verbosity is too low. But nor do I wish > to fill my code with this: > > if _verbosity >= 3: > x = calculate_complicated_thing() > print_(x, level=3) > > Is there a better way of doing this than the way I am going about it? I do something like this, although I don't know if it would be an improvement. def collatz(a,p): """ 3x+1 sequencer, no loop detection collatz(a,p) a: starting value p: print options (binary) bit 0 print even numbers (turns off power division) bit 1 print odd numbers bit 2 print debug (if any) returns: CollatzSequenceParameters [R1count, R2count] """ ONE = gmpy.mpz(1) TWO = gmpy.mpz(2) TWE = gmpy.mpz(3) a = gmpy.mpz(a) t = 0 u = 0 done = 0 if (p & 1)==1: print_evens = True else: print_evens = False if (p & 2)==2: print_odds = True else: print_odds = False if (p & 4)==4: print_debug = True else: print_debug = False while done==0: f = gmpy.scan1(a,0) # locate LS 1-bit if f>0: # it's even if print_evens: print a, a = a >> 1 # no power division u += 1 else: a = a >> f # power division u += f else: if print_odds: print a, if a==1: done = 1 seq_end = t + u else: a = a*TWE + ONE t += 1 return [u,t] > > -- > Steven From steve at REMOVE-THIS-cybersource.com.au Sun Sep 21 11:13:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 15:13:18 GMT Subject: Why are "broken iterators" broken? Message-ID: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> According to the Python docs, once an iterator raises StopIteration, it should continue to raise StopIteration forever. Iterators that fail to behave in this fashion are deemed to be "broken": http://docs.python.org/lib/typeiter.html I don't understand the reasoning behind this. As I understand it, an iterator is something like a stream. There's no constraint that once a stream is empty it must remain empty forever. Can somebody explain why "broken iterators" are broken? -- Steven From martindemello at gmail.com Thu Sep 4 15:51:25 2008 From: martindemello at gmail.com (Martin DeMello) Date: Thu, 4 Sep 2008 12:51:25 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: On Sep 4, 12:41?pm, Fredrik Lundh wrote: > "task_done" just decrements a counter (incremented by "put"). ?when the > counter reaches zero, the "join" call is unblocked. Thanks! Is there any standard python idiom to empty a queue into a list? Or do I just call get() repeatedly and catch the exception when it's done? martin From almar.klein at gmail.com Fri Sep 19 16:48:39 2008 From: almar.klein at gmail.com (Almar Klein) Date: Fri, 19 Sep 2008 22:48:39 +0200 Subject: Launching a subprocess without waiting around for the result? In-Reply-To: <87od2l2am7.fsf@benfinney.id.au> References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> <87od2l2am7.fsf@benfinney.id.au> Message-ID: > > Ah, no, that's a different thing. If the parent exits, the child will > also be killed I believe. Not if it's stuck in some endless loop... If you want to spawn a process and have it live on independent of the > parent, you want to make the child process a "daemon", detatching > itself from the parent's environment. I don't recall how that's done > immediately, but those are the terms to search for. I'm curious how this can be done, does anyone know this? Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp at rebertia.com Tue Sep 16 04:15:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 16 Sep 2008 01:15:08 -0700 Subject: append on lists In-Reply-To: References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: <47c890dc0809160115g2f02f889nf9e2f5fe16c67c28@mail.gmail.com> On Tue, Sep 16, 2008 at 1:20 AM, Armin
wrote: > John Machin wrote: >> >> On Sep 16, 6:45 am, Armin wrote: >> >>> Yes, but this is very unconvenient. >>> If d should reference the list a extended with a single list element >>> you need at least two lines >>> >>> a.append(7) >>> d=a >>> >>> and not more intuitive d = a.append(7) >> >> Methods/functions which return a value other than the formal None and >> also mutate their environment are "a snare and a delusion". Don't wish >> for them. > > > > c = [9,10] > [1,2,3,4,7].append(c) -> Is this a valid expression? Literally, no, because you can't call methods on literals. However, the sentiment is valid, though probably not what you want: >>> c = [9,10] >>> a = [1,2,3,4,7] >>> b = a[:] >>> a.append(c) >>> a #note the nested list [1, 2, 3, 4, 7, [9, 10]] >>> b [1, 2, 3, 4, 7] >>> b.extend(c) >>> b [1, 2, 3, 4, 7, 9, 10] Regards, Chris > > The 'value' of that expression is None. > > However ... that's the way of the implementation of the append method. > It's a little bit confusing to me ... > > --Armin > > Thanks to all ! > > >> >> Inconvenient? How often do you want to mutate a list and then set up >> another reference to it? >> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From robert.kern at gmail.com Thu Sep 4 17:37:04 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Sep 2008 16:37:04 -0500 Subject: why is self not passed to id()? In-Reply-To: References: <200809042244.54418.maric@aristote.info> Message-ID: Fredrik Lundh wrote: > Robert Kern wrote: > >> Well, that's not entirely true. They need to be not mutated while they >> are in the dictionary, certainly. At least not in ways that affect >> equality testing. In this case, one would also have to override >> list.__eq__ to also compare by identity, too. Then you could mutate >> the lists to your heart's content and the dictionary wouldn't care. > > at which point you'd start wondering if it wouldn't be more efficient to > wrap the list in a light-weight class, instead of using subclassing. Fair point. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From m_palmer45 at yahoo.ca Wed Sep 24 20:08:20 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 24 Sep 2008 17:08:20 -0700 (PDT) Subject: urllib error on urlopen References: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> Message-ID: <564ecf05-4be1-41b3-ab49-c3f17b57ad3b@w7g2000hsa.googlegroups.com> On Sep 24, 11:46 am, Mike Driscoll wrote: > Hi, > > I have been using the following code for over a year in one of my > programs: > > f = urllib2.urlopen('https://www.companywebsite.com/somestring') > > It worked great until the middle of the afternoon yesterday. Now I get > the following traceback: > > Traceback (most recent call last): > File "", line 1, in > response = urllib2.urlopen(req).read().strip() > File "c:\python25\lib\urllib2.py", line 124, in urlopen > return _opener.open(url, data) > File "c:\python25\lib\urllib2.py", line 381, in open > response = self._open(req, data) > File "c:\python25\lib\urllib2.py", line 399, in _open > '_open', req) > File "c:\python25\lib\urllib2.py", line 360, in _call_chain > result = func(*args) > File "c:\python25\lib\urllib2.py", line 1115, in https_open > return self.do_open(httplib.HTTPSConnection, req) > File "c:\python25\lib\urllib2.py", line 1082, in do_open > raise URLError(err) > URLError: routines:SSL23_GET_SERVER_HELLO:unknown protocol')> > > I tried my Google Fu on this error, but there's not much out there. I > tried using a proxy in Python, but that returned the same traceback. > If I copy the URL into my browser, it resolves correctly. Does anyone > have any advice on how to troubleshoot this error? > > I am using Python 2.5.2 on Windows XP. > > Thanks, > > Mike Could it just be a misconfiguration at the other end? Can you open other https urls? From tilmaniac at gmail.com Mon Sep 29 02:46:51 2008 From: tilmaniac at gmail.com (Tilman Kispersky) Date: Sun, 28 Sep 2008 23:46:51 -0700 (PDT) Subject: Cannot install pysqlite on Cygwin Message-ID: I am trying to install sqlite for use with python on cygwin. I have installed the sqlite packages from cygwin (that is libsqlite3-devel and libsqlite3_0). When attempting to easy_install pysqlite I get: $ easy_install pysqlite Searching for pysqlite Reading http://pypi.python.org/simple/pysqlite/ Reading http://pysqlite.org/ Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ Reading http://pysqlite.sourceforge.net/ Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/ Reading http://initd.org/tracker/pysqlite/wiki/PysqliteDownloads Reading http://oss.itsystementwicklung.de/trac/pysqlite Reading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/ Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/ Reading http://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/ Reading http://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/ Best match: pysqlite 2.5.0 Downloading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlite-2.5.0.tar.gz Processing pysqlite-2.5.0.tar.gz Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/ Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg- dist-tmp-7mr3WS warning: no files found matching 'doc/*.html' warning: no files found matching 'doc/code/*.py' src/statement.c: In function `pysqlite_statement_recompile': src/statement.c:351: warning: `sqlite3_transfer_bindings' is deprecated (declared at /usr/include/sqlite3.h:3985) build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function `pysqlite_enable_load_extension': /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ pysqlite-2.5.0/src/connection.c:922: undefined reference to `_sqlite3_enable_load_extension' collect2: ld returned 1 exit status error: Setup script exited with error: command 'gcc' failed with exit status 1 $ It seems to me this is due to some missing library (undefined reference...) but I have no idea what these missing files might be. I've tried installing everything that made any reference to sqlite form the cygwin interface. Does anyone know how I might get a working install of sqlite for python on cygwin? From gagsl-py2 at yahoo.com.ar Wed Sep 3 03:30:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 04:30:45 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <20080902221507.GS29228@dragontoe.org> Message-ID: En Tue, 02 Sep 2008 19:15:07 -0300, Derek Martin escribi?: >> > The Linux man page unfortunately copies (verbatim) the FreeBSD man >> > page, which gets it wrong. You can not open a process, but you can >> > definitely open a pipe. >> >> (Ok, if it doesn't agree with you, it must be wrong) > > See my last post for accreditation of my comment. A common > argumentation tactic of the closed-minded and the small-minded is to > resort to insinuation to attack the validity of other's comments > without providing any basis for doing so. Nice job. Well, you didn't provide (in that post) any reason for the Linux man page to be wrong, other than you disagreed with its terminology... But I don't want to argument on this - it was just a "side note". >> Classes represent "things", and class names should be nouns. > > Is that a law? > > Classes are instantiated by invoking their class names as a function > call -- the computing equivalent of a verb. Why then, must they be > named as nouns? Can you not, in fact, have classes which describe > (or model) actions? Wouldn't you name them using verbs if you did? Not exactly. I usually use the -dor suffix (Spanish) or -er (English); in both languages their meaning is to make a noun from a verb. A class whose main purpose is to write things becomes a Writer, by example. The stdlib is full of Writers, Openers, Parsers, Wrappers, Handlers, etc. If the main purpose of subprocess.Popen were to open pipes, I'd say some form of "opener" would be OK. But I think its main purpose is to model the child process itself - pipes are just attributes, so a noun like Child, Subprocess, Process or similar would have been more adequate. Of course it's too late to change things now, at least for the near future. Anyway, It's not the first misnamed class, nor the last one -unfortunately-, nor it's sooooo badly named anyway... > That said, this is the most valid point anyone has made... You should > have made it when the module was being designed. :-D (Yes, sure. Unfortunately, by the time 2.4 was released, I was still stuck with Python 2.1 due to Zope incompatibilities... Properties and generators were unreachable things to me... Oh, just remembering those times makes me sick :( ) > My point is, if you don't think Popen is a good name for the class, > that's your opinion, but it is only that: an opinion. Yet some of you > state your case as if it is incontrovertable fact. I've given a good > case as to why it IS a good name (one which I genuinely support), and > disagree as you may, none of the points any of you have made > invalidate or even weaken my argument. Lastly, the maintainers > obviously thought it was a good name when they included it... No, please. I know it's just my opinion, and I can see there is a case for the current name - just I don't like it, and liked to share my feelings with the OP when he said the same. -- Gabriel Genellina From duncan.booth at invalid.invalid Thu Sep 11 04:17:48 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Sep 2008 08:17:48 GMT Subject: universal unicode font for reportlab References: Message-ID: Duncan Booth wrote: > I may have made some blindingly obvious beginners mistake I made the blindingly stupid beginners mistake of cleaning up the code before posting it and breaking it in the process. The 'if' should of course say: if len(sys.argv) > 1: However my original test was done by toggling commented out lines of code so my conclusion remains the same: the only differences between the output are the creation date, the page stream, and the digest. -- Duncan Booth http://kupuguy.blogspot.com From gogala.mladen at gmail.com Fri Sep 19 04:34:15 2008 From: gogala.mladen at gmail.com (Mladen Gogala) Date: Fri, 19 Sep 2008 10:34:15 +0200 Subject: Python newbie References: Message-ID: Steve Holden wrote: > No. Python implicitly dereferences all names when using them to compute > values, and only uses them as references on the left-hand side of an > assignment. > > Please note the above statement is contentious, and will likely bring a > horde of screaming fanatics of various flavors down on my head for > terminological inexactitude. Actually, I am not a "screaming fanatic". I just want to learn. I am not trying to compare Perl or PHP with Python. I don't know enough Python to do that. I see an exponential increase in the use of Python and I want to find out why is that. I don't plan on discarding my knowledge of Perl and PHP and I don't know enough Python to make a reasonable comparison. whether I will use Python on regular basis or not is still to be decided. One thing is certain: it's easier to use what I already know but then, that's not the point. I've heard very good things about Django and TurboGears and I got my hands on the tool called orasachemadoc which is written in Python and I want to check it out. True, I am coming from the "dark side", but I have no preconceptions and am not a "screaming fanatic". Let me introduce myself: http://www.dba-oracle.com/t_dbi_interface1.htm http://www.rampant-books.com/book_2005_2_php_oracle.htm http://www.oracle.com/technology/pub/articles/gogala-symfony.html Those articles are the only ones that are scripting related. There are some other articles about Oracle, of no interest for this group. I am 47 years old and I have learned many programming languages in my time. Learning Python doesn't seem like a huge task. Conquering my own preconceptions stemming from a very long use of other programming languages will not be a big problem, either. Hopefully, this explains who am I and what is my motivation for delving into Python. I share your fears of screaming fanatics, too. -- http://mgogala.freehostia.com From deets at nospam.web.de Wed Sep 3 11:33:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 17:33:50 +0200 Subject: Serial I/O problem with pywin32 ? In-Reply-To: References: Message-ID: <6i7p2uFp2lqbU1@mid.uni-berlin.de> Xavier schrieb: > Hi, > > I try to access to a Bluetooth GPS data-logger with Python. I use > pySerial. > > Sending and receiving little messages (~100 char) works fine. However, > when I ask the GPS to dump the trails, it returns some Mbytes and here > is the problem : in the stream of bytes, I randomly losts chunks of > ~100bytes. > > I tried USPP and pyBlueZ instead of pySerial : same problem. > > It doesn't like it is a bufferoverun bug from me because : > - the GPS seems to wait when I do not read the stream, > - there is never more than 200 inWainting() characters, > - my code to test it is quite simple : > > seriallink = serial.Serial("COM40") > fileName = "data.dump" > out = open(fileName, 'w') > while 1: > c = seriallink.read() > out.write(" %0.2X" % ord(c)) > print "*", > out.close() > > (with pyBluez : > sock=BluetoothSocket( RFCOMM ) > sock.connect(("00:0A:...", 1))) > > I tried my program on two different PC with two Bluetooth dongle, > (with pySerial, USPP, pyBluez). > The same things are : > - windows > - the GPS (which works fine with the dumper program of the > constructor) > - pyWin32 > > I've found another guy with a similar problem : > http://www.generation-nt.com/reponses/rs232-entraide-142097.html > He says: > - no problem with little messages > - lost of one byte every hour when receiving a lot of data > > Any known problems with pywin32 and serial I/O when downloading a big > stream of data ? From my experience with serial lines I'd say: that's the culprit. They tend to be rather unreliable, as there is no real protocol ensuring data integrity. You might consider downloading chunks of data if that's somehow possible, and re-try failed chunks. Diez From ldo at geek-central.gen.new_zealand Fri Sep 26 03:52:59 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 19:52:59 +1200 Subject: [Tkinter] how to keep a window above all other OS windows? References: Message-ID: In message , Dennis Lee Bieber wrote: > {I miss the Amiga -- > where one had the option to push a window to the back /without/ losing > focus... made it useful for reading one window while touch-typing data > into the "hidden" window} This sort of thing should be configurable in many X11-based window managers. From castironpi at gmail.com Thu Sep 25 13:28:17 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 25 Sep 2008 10:28:17 -0700 (PDT) Subject: Er, one -lime- or two. References: <2ac98076-0163-45c4-8269-e6c1a1d70d7f@c65g2000hsa.googlegroups.com> <48db473e$0$24356$426a74cc@news.free.fr> Message-ID: <615a81af-eb4c-42ce-a07f-b5e26e849a03@k37g2000hsf.googlegroups.com> On Sep 25, 3:09?am, Bruno Desthuilliers wrote: > Aaron "Castironpi" Brady a ?crit : > > > A Python walks into a bar and orders a complex data structure. > > Bartender says, "One line or two?" > > I don't think that one will have much success in parties !-) It doesn't go to any. =P From darcy at druid.net Fri Sep 26 15:21:58 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 26 Sep 2008 15:21:58 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Message-ID: <20080926152158.a4b4f229.darcy@druid.net> On Fri, 26 Sep 2008 14:04:35 -0500 "Michael Mabin" wrote: > Doesn't it depend on where and why you intend to execute the code? > Obviously some SQL is more at risk for exploit when the input is from the > screen on a web page than if you were running parameterized code in a > controlled batch environment. Or if you were writing code generators (which > is what I happen to do) which won't be run by the general public. > > Incidentally, couldn't input field edits prevent such exploits prior to > interpolation? I encourage my competitors to program that way. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From deets at nospam.web.de Fri Sep 12 10:09:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Sep 2008 16:09:02 +0200 Subject: Checking the boolean value of a collection In-Reply-To: References: Message-ID: <6ivbfvFnfucU1@mid.uni-berlin.de> Marco Bizzarri schrieb: > Hi all. > > In many parts of my code I've the following schema of code: > > def isInUseByOutgoingRegistrations(self, archivefolder): > for instance in self.findActiveOutgoingRegistrationInstances(): > if instance.forbidToClose(archivefolder): > return True > return False > > Before devising my own solution for this kind of problem, I wonder if > there is a common solution for the problem. I'm looking for a > python2.3 solution. if any(instance.forbitToClose(archivefolder) for instance in self.findActiveOutgoingRegistrationInstances()) You should also consider using PEP8 style naming. Diez From joncle at googlemail.com Wed Sep 10 13:41:19 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 10:41:19 -0700 (PDT) Subject: Reading binary data References: Message-ID: <508e31d9-daab-4346-9441-55cc47f7c1f4@m44g2000hsc.googlegroups.com> On 10 Sep, 18:33, Jon Clements wrote: > On 10 Sep, 18:14, Aaron Scott wrote: > > > > > I've been trying to tackle this all morning, and so far I've been > > completely unsuccessful. I have a binary file that I have the > > structure to, and I'd like to read it into Python. It's not a > > particularly complicated file. For instance: > > > signature ? char[3] ? ? "GDE" > > version ? ? uint32 ? ? ?2 > > attr_count ?uint32 > > { > > ? ? attr_id ? ? ? ? uint32 > > ? ? attr_val_len ? ?uint32 > > ? ? attr_val ? ? ? ?char[attr_val_len] > > > } ... repeated attr_count times ... > > > However, I can't find a way to bring it into Python. This is my code > > -- which I know is definitely wrong, but I had to start somewhere: > > > import struct > > file = open("test.gde", "rb") > > output = file.read(3) > > print output > > version = struct.unpack("I", file.read(4))[0] > > print version > > attr_count = struct.unpack("I", file.read(4))[0] > > while attr_count: > > ? ? ? ? print "---" > > ? ? ? ? file.seek(4, 1) > > ? ? ? ? counter = int(struct.unpack("I", file.read(4))[0]) > > ? ? ? ? print file.read(counter) > > ? ? ? ? attr_count -= 1 > > file.close() > > > Of course, this doesn't work at all. It produces: > > > GDE > > 2 > > --- > > ? > > --- > > ??? > > > I'm completely at a loss. If anyone could show me the correct way to > > do this (or at least point me in the right direction), I'd be > > extremely grateful. > > What if we view the data as having an 11 byte header: > signature, version, attr_count = struct.unpack('3cII', > yourfile.read(11)) > > Then for the list of attr's: > for idx in xrange(attr_count): > ? ? attr_id, attr_val_len = struct.unpack('II', yourfile.read(8)) > ? ? attr_val = yourfile.read(attr_val_len) > > hth, or gives you a pointer anyway > Jon. CORRECTION: '3cII' should be '3sII'. From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 03:09:20 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 09:09:20 +0200 Subject: A bit weird dictionary behavior In-Reply-To: <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> Message-ID: <48d8961a$0$11995$426a74cc@news.free.fr> Carl Banks a ?crit : > On Sep 22, 3:43 pm, Bruno Desthuilliers > wrote: >> bearophileH... at lycos.com a ?crit : >> >>> Pekka Laukkanen: >>>> but it still doesn't feel exactly right. Would it be worth submitting a bug? >>> It feels wrong because it is. In a tidier language (Pascal, Java, etc) >>> a boolean and an integer must be different types. >> Some would argue (and some did by the time Python grew a 'bool' type) >> that what is wrong is to have a bool type in a language that already >> have a wider definition of the truth value of an expression... > > And some would argue that it was wrong to have such a wide definition > for the truth value of an expression in the first place... Indeed !-) From bjruth at gmail.com Fri Sep 12 15:36:01 2008 From: bjruth at gmail.com (byron) Date: Fri, 12 Sep 2008 12:36:01 -0700 (PDT) Subject: book example confusion Message-ID: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> I am reading o'reilly's learning python (great book), but i came across an example (pg 291, pdf) that I am not quite understanding the reasoning for the author's explanation: if f1() or f2(): The author states that do to the nature of that expression, if f1() returns True, f2() will not be evaluated.. which makes sense. His quote: "Here, if f1 returns a true (or nonempty) value, Python will never run f2." He then states: "To guarantee that both functions will be run, call them before the 'or':" tmp1, tmp2 = f1(), f2() if tmp1 or tmp2: Being that each function is an object, a name assignment to (tmp1,tmp2) doesn't actually evaluate or run the function itself until the name is called.. so why would the latter example "run" both functions as the author suggests? From prologic at shortcircuit.net.au Sun Sep 21 19:19:19 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 09:19:19 +1000 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00e6cd16$0$20303$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00e6cd16$0$20303$c3e8da3@news.astraweb.com> Message-ID: On Mon, Sep 22, 2008 at 9:05 AM, Steven D'Aprano wrote: > I'm not wedded to the idea, there are alternatives (perhaps the factory > should instantiate the class and return that?) but I assume others have > used this design and have a name for it. The problem is, I don't see why you're using a class to store state in the first place. cheers James -- -- -- "Problems are solved by method" From paul at boddie.org.uk Sun Sep 7 19:47:49 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 7 Sep 2008 16:47:49 -0700 (PDT) Subject: lacking follow-through References: Message-ID: <038bcbbc-e204-43f8-b656-81495af36b6c@d77g2000hsb.googlegroups.com> On 7 Sep, 23:00, castironpi wrote: > I am concerned by the lack of follow-through on some responses to > recent ideas I have described. Do I merely have a wrong understanding > of group policy? I think some people have taken exception to your contributions previously, which I believe exhibits a certain degree of shortsightedness on their part, considering for example the recent thread which brought up just-in-time compilation techniques where there were pretty valid reasons for keeping the thread going. Certainly, it wasn't as if the level of discussion was stuck at basic contradiction or mudslinging, and even if reading the different papers on the topic might help an inquirer on the matter, there's certainly nothing wrong with seeking guidance over which papers might be the best ones, nor with seeking some kind of context for that work within the realm of Python implementations, especially given the recent glut of news on virtual machine improvements for other dynamic languages. > Is it a good policy (defined with respect to the > future of Python and the welfare of humans at large) if so? Is there > a serious lack of diligence, or should I merely take more initiative, > and ignore charges of 'pestering'? (Warning, moderately deep outside > social issues on table too.) I'm no expert on getting other people to embrace ideas, but here's my advice anyway. If you have an idea and can describe it coherently, please do so; this won't guarantee positive responses, but there may be people out there who feel that you're onto something. If the idea has merit - generally, the most reliable way to know involves you personally experiencing difficulties in a problem area where the idea in question promises to alleviate some of those difficulties - then by developing that idea, typically producing something that others can try out, people will know that you mean business. Alternatively, people might point you to existing work that will address the problems you're having, saving you the bother of having to write a load of code to enact that idea of yours. You can be lucky and have people chasing you down over what you've produced, but I'd argue that most of the time, for any given idea which becomes a project, you'll have a few people interested in what you've done, but the motivation for continuing will be something that will depend on yourself and your own needs. You have to accept that even if you think that people (and Python) might be well served in listening to what you have to say, that message may go unheard. Once upon a time, the BDFL and the most central core developers used to read comp.lang.python and ideas about Python's future were exchanged readily. Today, all lobbying takes place on the python-dev/ 3000/ideas mailing lists, but those lists are more conservative with regard to contributions than comp.lang.python (python-list). Perhaps as a consequence, the divide between those steering the language and those using it has grown: "producers" use the aforementioned lists, "consumers" argue with each other on the newsgroup, and it might be in the release notes that you learn about happenings that previously would have been reported more widely elsewhere. Certainly, influencing the future of Python, at least officially, is a lot more hard work than it used to be. One may decide to worry about this, along with matters like how Python will remain able to compete with other languages and platforms. I regard the future development of Python as a process which may not necessarily serve my interests, but since the community around Python is so much larger and more diverse than those following every last Python 3.0 commit, I see no need to become agitated by the direction of the language developers. Since Python is Free Software one has, after all, a lot of flexibility when deciding who to associate with and who to influence, and it is ultimately only through trying to achieve things with the technology that one's priorities (or the things one should be worrying about) emerge. For me, then, influencing Python 3.x isn't a priority since I have enough to be thinking about and working on, and I wonder if I'll ever do anything with Python 3.x anyway. So, I suppose, the message is this: follow your own interests, make contributions in the ways that make sense to you, seek contact with like-minded developers in groups which might be remote from mainstream Python development (find an appropriate, potentially specialised audience); these things will define any need you may have to influence others. Paul From presence at MUNGEpanix.com Sat Sep 27 19:12:59 2008 From: presence at MUNGEpanix.com (Cydrome Leader) Date: Sat, 27 Sep 2008 23:12:59 +0000 (UTC) Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> Message-ID: In rec.crafts.metalworking Jim Thompson wrote: > > On Sat, 27 Sep 2008 18:47:16 -0400, default > wrote: > >>On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko >> wrote: >> >>>Hello, this is Milenko Stojadinovic from town Banjaluka, >>>Bosnia and Herzegovina, also known as Cvrcko >>>Does anyone know of any bars in town where I can >>>swallow a bucket of cum? It can be either dog, >>>horse or human cum. Also, does anyone know of >>>any sex bars where people will shit in your mouth? >>>I also like eating shit. >> >>Come to the US and park your mouth in front of George Bush - all the >>Bshit you can eat - and it keeps on coming! >> >>I have a buddy in Bosna - he's normal. > > Now you know why I blanket kill-file googlegroups. So you and everybody can talk about them nonstop? From gagsl-py2 at yahoo.com.ar Sat Sep 20 20:19:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Sep 2008 21:19:11 -0300 Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: En Sat, 20 Sep 2008 02:01:14 -0300, eliben escribi?: > Why are people preferring the python.org package over ActiveState's, > which seems to be more complete and includes more modules (like > pywin32) ? They do a hard work collecting, compiling and packaging the Python distribution with some added modules. But anything you get in the AS free version you can get directly from the original authors; downloading pywin32 from sourceforge isn't so difficult... And AFAIR, it took about 2 months the guys at ActiveState to release the 2.5 version after it came from python.org -- Gabriel Genellina From bearophileHUGS at lycos.com Thu Sep 18 22:08:27 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 18 Sep 2008 19:08:27 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <6d9c1b56-1322-4062-94c4-dd1388421abc@z66g2000hsc.googlegroups.com> Message-ID: <50aa7f8d-7d00-4ca0-9c2a-44335ec91728@k7g2000hsd.googlegroups.com> bearophile: > doubles12 : 0.00184026840268 For fun, and to have an almost baseline reference, I have done a little benchmark in D too: import std.stdio: writefln; // Using Tango std lib you don't need all this version (Win32) { import std.c.windows.windows; double clock() { long t; QueryPerformanceCounter(&t); return cast(double)t / queryPerformanceFrequency; } long queryPerformanceFrequency; static this() { QueryPerformanceFrequency(&queryPerformanceFrequency); } } union N { struct { int x, y; } long xy; } auto IN = [ N(4, 9), N(5, 0), N(6, 6), N(7, 2), N(3, 6), N(9, 6), N(0, 1), N(1, 6), N(0, 5), N(1, 2), N(8, 9), N(5, 4), N(1, 6), N(7, 6), N(9, 1), N(7, 6), N(0, 1), N(7, 4), N(7, 4), N(8, 4), N(8, 4), N(3, 5), N(9, 6), N(6, 1), N(3, 4), N(4, 5), N(0, 5), N(6, 3), N(2, 4), N(1, 6), N(9, 5), N(1, 2), N(5, 8), N(8, 5), N(3, 1), N(9, 4), N(9, 4), N(3, 3), N(4, 8), N(9, 7), N(8, 4), N(6, 2), N(1, 5), N(5, 8), N(8, 6), N(0, 8), N(5, 2), N(3, 4), N(0, 5), N(4, 4), N(2, 9), N(7, 7), N(1, 0), N(4, 2), N(5, 7), N(0, 4), N(2, 5), N(0, 8), N(7, 3), N(9, 1), N(0, 4), N(5, 0), N(4, 9), N(0, 6), N(3, 0), N(3, 0), N(3, 9), N(8, 3), N(7, 9), N(8, 5), N(7, 6), N(1, 5), N(0, 6), N(5, 9), N(6, 8), N(0, 0), N(4, 1), N(3, 3), N(5, 4), N(5, 3), N(6, 1), N(5, 4), N(4, 5), N(5, 8), N(4, 1), N(3, 6), N(1, 9), N(0, 5), N(6, 5), N(5, 5), N(6, 0), N(0, 9), N(2, 6), N(0, 7), N(5, 9), N(7, 3), N(7, 9), N(5, 4), N(4, 9), N(2, 9) ]; N[] doubles13() { size_t[N] dup; // used as set N[] SN; foreach (item; IN) { if (item in dup) SN ~= item; else dup[item] = 0; } return SN; } N[] doubles0() { N[] SN; for (int i; i < IN.length; i++) for (int j; j < IN.length; j++) if (i != j) if (IN[i] == IN[j]) SN ~= IN[i]; return SN; } void test_results() { size_t[N] set1, set2; foreach (n; doubles0()) set1[n] = 0; foreach (n; doubles13()) set2[n] = 0; if (set1.keys.sort != set2.keys.sort) throw new Error("ERROR"); } void main() { int n = 150_000; test_results(); int count = n; auto t0 = clock(); while (count--) doubles13(); auto t1 = clock(); writefln("%0.10f", cast(double)(t1 - t0) / n); } doubles13() needs 0.000027-0.000037 seconds (*), about 60-75 times faster than doubles12, this means about 3-4 seconds instead of 15h (on the original computer). Using C++ with GCC (using a for dup and a for SN) you can probably go 10-40% faster still :-) (*) Probably there's such variability of timings because the current DMD compiler I have used doesn't add "align" instructions in the asm it produces as GCC does. With modern CPUs very sensitive to code alignment this leads to even 20-30% runtime differences in small tight loops. Bye, bearophile From bschools.dims at gmail.com Fri Sep 26 05:06:05 2008 From: bschools.dims at gmail.com (delhi institute of management & services) Date: Fri, 26 Sep 2008 02:06:05 -0700 (PDT) Subject: urgent Message-ID: Delhi Institute of Management & Services Dear friends, We are extremely happy to welcome you to the world of Management... We are in the process of preparing some 5 minutes revision Q & A type lessons for management students. They are in no way, a replacement for the classroom lectures, textbooks or any other study guides. If you wish to go through these lessons. Please visit today's BLOGS: http://bmmisall1513.blogspot.com/ http://allsem1manfun1c.blogspot.com/ http://bmmanhum1107.blogspot.com/ http://bmmanhum1117.blogspot.com/ http://bmmisall1504.blogspot.com/ We want you to suggest improvements or corrections if any, by Email to Ms Sheetal varma, (Senior HR Executive). Email: dimsjobs at gmail.com If you are looking for a job or you want to change a job, please send your resume to Ms Sheetal (Senior HR Executive). She will try to help you to find a suitable job. Email: dimsjobs at gmail.com CAREER TRAINING Join University Recognized Courses MBA {BM} MBA {HR}, MBA {MKT}, and MBA {Fin}, MCA, BCA, MMC, BMC, B.com M.com M.Insurance, B.Fashion For Career Development and Job Promotions. CONTACT: Delhi Institute of Management &Services, Study Centre of NMiMS UNIVERSITY, GURU JAMBHESHWAR UNIVERSITY, JAMIA HAMDARD UNIVERSITY, ALL INDIA MANAGEMENT ASSOCIATION, PUNJAB TECHNICAL UNIVERSITY, MUMBAI EDUCATION TRUST . 1108 Akashdeep Building, New Delhi 110001 TEL FAX: 23312187, TEL: 23316475. If you do not want to receive such mail in future. Please send mail Email: bookghar2008 at gmail.com Reference: Mailer 2 From enleverlesX.XmcX at XmclaveauX.com Tue Sep 30 05:36:03 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Tue, 30 Sep 2008 11:36:03 +0200 Subject: python & sms In-Reply-To: References: Message-ID: <48e1f674$0$965$ba4acef3@news.orange.fr> Hi! You can manage Skype from Python('s scripts), for use the functionalities of Skype to send SMS. @-salutations -- Michel Claveau From dudeja.rajat at gmail.com Mon Sep 29 10:05:19 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 29 Sep 2008 15:05:19 +0100 Subject: os.path.exists() function does not work for http paths Message-ID: Hi, I have used os.path.exists() many a times for any file system paths in local system. But this does not seem to work for an Http path. e.g: To check is the Results folder exists at the following path, I do: if not os.path.exists("http://subversion.myCom.com/Testing/Results"): print 'Path does not exist' This always prints the above print statements whether or not the Results folder exists or not. Is there any such function to check existence of files. / folder at Http paths? -- Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From ldo at geek-central.gen.new_zealand Sun Sep 28 19:14:34 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 12:14:34 +1300 Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> <6k93opF6k62hU1@mid.uni-berlin.de> <913193c5-1722-45ae-9cec-efa548dd6992@b38g2000prf.googlegroups.com> Message-ID: In message <913193c5-1722-45ae-9cec-efa548dd6992 at b38g2000prf.googlegroups.com>, est wrote: > Well, you succeseded in putting all blame to myself alone. Great. Take it as a hint. > When you guy's are dealing with CJK characters in the future, you'll > find out what I mean. Speaking as somebody who HAS dealt with CJK characters in the past--see above. From fairwinds.dp at gmail.com Sun Sep 28 10:10:25 2008 From: fairwinds.dp at gmail.com (David Pratt) Date: Sun, 28 Sep 2008 11:10:25 -0300 Subject: Selective importing and package dependencies Message-ID: Hi. I am in the midst of preparing a package to convert between various schemas including orms. The issue is I don't want django, slqalchemy, storm, rdflib etc. as hard dependencies of the package. Each module is a schema to schema conversion. As an example, I have imports for sqlalchemy with classes and methods that use them. from sqlalchemy.util import OrderedDict from sqlalchemy import types as rdbtype import sqlalchemy as sa I have my own ideas about how I might do this but looking for recommendations from others how they would handle this so the result would be: 1. no hard dependencies on any of these other packages 2. load the module without failure. 3. import the dependent package if available to perform the conversion Many thanks David From tjreedy at udel.edu Wed Sep 10 19:03:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 19:03:03 -0400 Subject: dict slice in python (translating perl to python) In-Reply-To: References: Message-ID: hofer wrote: > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. Python does not try to be as compact as Perl. Pythoneers generally consider that a feature. Anyway, the second Python version is asymtotically as compact as the Perl code, differing only by a small constant number of bytes while the code size grows. > mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] The initial brackets add nothing. "v1,v2,v3 =" does the same. > > # for long lists lazier typing,but more computational intensive > # as split will probably be performed at runtime and not compilation > time You have spent and will spend more time posting and reading than the equivalent extra computation time this will take with any normal exchange rate and computation usage. > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] This is a standard idiom for such things. If it bothers you, type "'one two two'.split()" into an interactive window and 'in a blink' get ['one', 'two', 'two'], which you can cut and paste into a program. > print "%s\n%s\n%s" %(v1,v2,v3) However, more that about 3 numbered variables in a Python program suggest the possibility of a better design, such as leaving the values in a list vee and accessing them by indexing. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Mon Sep 15 00:46:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 14:46:38 +1000 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> <87od2q5a24.fsf@benfinney.id.au> Message-ID: <87k5de5841.fsf@benfinney.id.au> Grant Edwards writes: > On 2008-09-15, Ben Finney wrote: > > I think it's more important for Python library APIs to comply with > > the Python coding guidelines (as specified in PEP 8) than to > > comply with standards in other languages. > > I think the practical matter of being able to use existing > documentation and examples How are examples written in another language a "practical matter" for using a Python library? Surely less "practical" than having one's Python code base use a consistent style. -- \ ?Dyslexia means never having to say that you're ysror.? | `\ ?anonymous | _o__) | Ben Finney From mensanator at aol.com Sun Sep 21 14:55:57 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 21 Sep 2008 11:55:57 -0700 (PDT) Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: On Sep 21, 4:37 am, Fredrik Lundh wrote: > Mensanator wrote: > > I'm not the one who wrote sympy, so I guess I'm not > > the only one who didn't notice it. > > > If it's a well known problem, then sorry I wasted > > your time. > > Given that 2.5 explicitly warns about this specific change: > > >>> as = 1 > :1: Warning: 'as' will become a reserved keyword in Python 2.6 Uh...how come _I_ don't see that? In IDLE, I get: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 IDLE 1.2 >>> as = 1 SyntaxError: invalid syntax When inside a script, I get: as = 1 print as >>> ====================== RESTART ====================== >>> 1 > > it's an unknown issue only for people who has 1) never used their code > under 2.5, or 2) never looks at the output produced by their programs. > > The PEP-5 process guarantees that "users will have at least a year to > test their programs and migrate them from use of the deprecated > construct to the alternative one," and Python 2.5 was released *two* > years ago. > > So it sure looks like the SimPy folks ignored the established process. > Why they've done that is probably a more interesting issue than the > change itself. Is there something wrong with my (and Sympy's) version of Python that we don't see these warnings? > > From harald.luessen at gmx.de Thu Sep 18 14:10:01 2008 From: harald.luessen at gmx.de (Harald Luessen) Date: Thu, 18 Sep 2008 20:10:01 +0200 Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <4f55d49g9086nhob3ol67uahbr19o1hjiu@4ax.com> On Thu, 18 Sep 2008 Alexzive wrote: >I am a python newbie and need to run following code for a task in an >external simulation programm called "Abaqus" which makes use of python >to access the mesh (ensamble of nodes with xy coordinates) of a >certain geometrical model. > >[IN is the starting input containing the nodes to be check, there are >some double nodes with the same x and y coordinates which need to be >removed. SN is the output containing such double nodes] > >Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) I did not test the syntax, but here is an idea with sorted lists. It should be O(NlogN). def sk(x): return x.coordinates[0] IN.sort(key=sk) for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) else: break Harald From lixinyi.23 at gmail.com Wed Sep 24 01:29:54 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 22:29:54 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> <31ff7c8a-28f3-4c62-8ac5-6d0f90106c5d@a8g2000prf.googlegroups.com> <0fd3fd66-a4f5-4322-8823-722de1dfa952@c58g2000hsc.googlegroups.com> Message-ID: On 9?24?, ??1:15, "Aaron \"Castironpi\" Brady" wrote: > On Sep 23, 11:06 pm, "Aaron \"Castironpi\" Brady" > > > > wrote: > > On Sep 23, 9:30 pm, lixinyi... at gmail.com wrote: > > > > If the PyObject is a PyList, and all list items are strings, > > > say a=['aaa','bbb','ccc'] > > > > How can I have a > > > myArray[0] = "aaa" > > > myArray[1] = "bbb" > > > myArray[2] = "ccc" > > > in C++? > > > > Do I have to > > > use PyModule_GetDict() to get the dict first? > > > what about the next? > > > > > What do you know about the contents of 'argc' and 'argv'? If it's > > > > impossible with Py_Main, can you use one of the other entry points? > > > > > If you've never manipulated PyObject* objects in C, they can be > > > > hairy. Even if you know 'a' is a sequence, its contents are still all > > > > PyObject*s, which you can access via PyList_... and PySequence_ > > > > functions. > > > This one writes '[aaa, bbb, ccc]' to the console in two different > > ways. > > > #include > > > int main() { > > PyObject *list, *listrepr; > > Py_Initialize(); > > > /* first */ > > list= PyList_New( 3 ); > > PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); > > PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); > > PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); > > > listrepr= PyObject_Repr( list ); > > printf( "%s\n", PyString_AsString( listrepr ) ); > > > Py_DECREF( listrepr ); > > Py_DECREF( list ); > > > /* second */ > > list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); > > listrepr= PyObject_Repr( list ); > > printf( "%s\n", PyString_AsString( listrepr ) ); > > > Py_DECREF( listrepr ); > > Py_DECREF( list ); > > > Py_Finalize(); > > return 0; > > > } > > > Did you want to execute some Python code, and examine variables it > > creates? > > Here's a third way: > > PyObject *list, *listrepr, *dict, *result, *name; > /* third */ > dict= PyDict_New( ); > result= PyRun_String( "myarray= [ 'ggg', 'hhh', 'iii' ]", > Py_file_input, dict, NULL ); > name= PyString_FromString( "myarray" ); > list= PyDict_GetItem( dict, name ); > listrepr= PyObject_Repr( list ); > printf( "%s\n", PyString_AsString( listrepr ) ); > > Py_DECREF( dict ); > Py_DECREF( result ); > Py_DECREF( name ); > Py_DECREF( listrepr ); > Py_DECREF( list ); > > PyRun_String runs a namespace, 'dict', which holds the variables. Thanks! it helps. I know how to read from python now. main_module = PyImport_AddModule("__main__"); global_dict = PyModule_GetDict(main_module); pyObject = PyDict_GetItem(global_dict,key); it will require lots of type checking, but it's fine to me. From hancock.robert at gmail.com Sun Sep 21 18:07:16 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Sun, 21 Sep 2008 15:07:16 -0700 (PDT) Subject: Twisted: Get Protected HTTPS Page via Proxy with Authentication Message-ID: from twisted.web import client from twisted.internet import reactor import base64 import sys def printPage(data): print data reactor.stop() def printError(failure): print >> sys.stderr, "Error:", failure.getErrorMessage() reactor.stop() if len(sys.argv) == 4: url = sys.argv[1] username = sys.argv[2] password = sys.argv[3] basicAuth = base64.encodestring('%s:%s' % (username, password)) authHeader = "Basic " + basicAuth.strip() client.getPage(url, headers={"Authorization": authHeader}).addCallback(printPage).addErrback(printError) reactor.run() else: print 'Usage: get_web_page.py ' If I run this against a password protected HTTP(S) site from a host that has direct access to the Internet it works fine. I now have to move it behind a proxy that requires authentication. The Twisted documentation did not make it clear (to me) how to add proxy authentication and I cannot find an example on the Internet. I've tried adding an additional Proxy-Authentication header to the call, but that doesn't help Any ideas would be greatly appreciated. Command line args: http://feedparser.org/docs/examples/basic_auth.xml test basic From anishchapagain at gmail.com Wed Sep 3 05:39:11 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Wed, 3 Sep 2008 02:39:11 -0700 (PDT) Subject: installing matplotlib with cygwiin Message-ID: <9d76f8f9-bc32-4946-9474-7f5f2cdc90b2@b1g2000hsg.googlegroups.com> Hi!! I need to run matplotlib for one project with pylab and scipy module, i'm using cygwin so as to link system call operation with few GUI support, but am unable to install numpy and scipy without these matplotlib is also not installed Please help me for proper installation of these module in cygwin for python, i followed scipy.org installation guidelines but having done so, am not able to proper installation. regard's anish From sturlamolden at yahoo.no Sun Sep 7 00:36:26 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 6 Sep 2008 21:36:26 -0700 (PDT) Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> <96df416b-cc13-4631-8865-d6b6373772a5@z72g2000hsb.googlegroups.com> Message-ID: <35ecda4c-1346-46ab-88c7-076f000115ba@x35g2000hsb.googlegroups.com> On 7 Sep, 06:24, sturlamolden wrote: > - Psyco, a Python JIT compiler, will often speed up algorithmic code. > Using psyco require to change to your code. Typo. It should say "Using psyco does not require you to change your code." From lists at cheimes.de Sun Sep 14 11:07:06 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 14 Sep 2008 17:07:06 +0200 Subject: how to exclude specific things when pickling? In-Reply-To: References: Message-ID: inhahe wrote: > If I gather correctly pickling an object will pickle its entire hierarchy, > but what if there are certain types of objects anywhere within the hierarchy > that I don't want included in the serialization? What do I do to exclude > them? Thanks. Pickle uses the methods __getstate__, __setstate__ and __reduce__ / __reduce_ex__ to access certain aspects of an object like e.g. the state. You can find more information in the pickle docs. Christian From jpeyret at gmail.com Tue Sep 23 15:23:26 2008 From: jpeyret at gmail.com (J Peyret) Date: Tue, 23 Sep 2008 12:23:26 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> On Sep 23, 8:31?am, bearophileH... at lycos.com wrote: Guys, this looks like a great data structure/algo for something I am working on. But... where do I find some definitions of the original BK-tree idea? I looked through Amazon and only a few books mention something like BK-Tree and these are mostly conference minutes books, at ungodly prices. I also did a quick Google on it and there isn't that much about the subject. http://blog.notdot.net/archives/30-Damn-Cool-Algorithms,-Part-1-BK-Trees.html is the one I mostly saw referred. So... 2 questions: 1. More bk-tree references? I can follow the code, but some understanding of the background would be nice. 2. What, if any, is a good book to understand the basic of fuzzy/ string matching? Proximity/affinity problems? Or, more generally, a good book on advanced algorithms? No, I don't wanna read Knuth's just yet, something more modern/easy to follow maybe? Something like 'Programming Collective Intelligence', ISBN 0596529325, would be very nice, though it is perhaps a bit too specific in its applications. Books using Java or C are fine. Lisp, hmmm, well... I have trouble reading its notation, sorry. Cheers JLuc From samslists at gmail.com Thu Sep 18 22:29:30 2008 From: samslists at gmail.com (Sam) Date: Thu, 18 Sep 2008 19:29:30 -0700 (PDT) Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> Message-ID: <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> On Sep 18, 2:10?pm, "Gabriel Genellina" wrote: > En Tue, 16 Sep 2008 21:58:31 -0300, Sam escribi?: > The code is correct - try with another server. I tested it with a ? > LightHTTPd server and worked fine. Gabriel... I found a bunch of servers to test it on. It fails on every server I could find (sans one). Here's the ones it fails on: slashdot.org hotmail.com godaddy.com linux.com lighttpd.net I did manage to find one webserver it succeeded on---that is kenrockwel.com --- a domain squatter with a typoed domain of one of my favorite photographer's websites (the actual website should be kenrockwell.com) This squatter's site is indeed running lighttpd---but it appears to be an earlier version, because the official lighttpd site fails on this test. We have all the major web servers failing the test: * Apache 1.3 * Apache 2.2 * Microsoft-IIS/6.0 * lighttpd/1.5.0 So I think it's the python side that is wrong, regardless of what the standard is. What should I do next? I've rewritten the code to make it easier to test. Just run it as is and it will try all my test cases; or pass in a site on the command line, and it will try just that. Thanks! #!/usr/bin/env python """Put the site you want to test as a command line parameter. Otherwise tests the list of defaults.""" import urllib2 import zlib import sys opener = urllib2.build_opener() opener.addheaders = [('Accept-encoding', 'deflate')] try: sites = [sys.argv[1]] except IndexError: sites = ['http://slashdot.org', 'http://www.hotmail.com', 'http://www.godaddy.com', 'http://www.linux.com', 'http://www.lighttpd.net', 'http://www.kenrockwel.com'] for site in sites: print "Trying: ", site stream = opener.open(site) data = stream.read() encoded = stream.headers.get('Content-Encoding') server = stream.headers.get('Server') print " %s - %s (%s)" % (site, server, encoded) if encoded == 'deflate': before = len(data) try: data = zlib.decompress(data) after = len(data) print " Able to decompress...went from %i to %i." % (before, after) except zlib.error: print " Errored out on this site." else: print " Data is not deflated." print From fredrik at pythonware.com Thu Sep 11 09:00:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 15:00:40 +0200 Subject: function return In-Reply-To: References: Message-ID: Beema Shafreen wrote: > I have a script using functions , I have a problem in returning the > result. My script returns only one line , i donot know where the looping > is giving problem, Can any one suggest, why this is happening and let me > know how to return all the lines > > def get_ptm(): > fh = open('file.txt', 'r') > data_lis = [] > for line in fh.readlines(): > data = line.strip().split('\t') > id = data[0].strip() > gene_symbol = data[1].strip() > ptms = data[8].strip() > result = "%s\t%s\t%s" %(id,gene_symbol,ptms) > return result note that you put the "return" statement inside the loop, so returning only one line is the expected behaviour. result = "%s\t%s\t%s" %(id,gene_symbol,ptms) data_lis.append(result) and then return the list when done: > fh.close() return data_lis ::: if you change the original return to "yield", the function will turn into a "generator" that yields one result at a time. result = "%s\t%s\t%s" %(id,gene_symbol,ptms) yield result for more on generators, and how they are used, see the documentation. From robert.rawlins at thinkbluemedia.co.uk Thu Sep 18 07:21:29 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 18 Sep 2008 12:21:29 +0100 Subject: XML Processing Message-ID: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> Guys, I'm running python 2.5 and currently using ElementTree to perform my XML parsing and creation. ElementTree really is a great package for doing this, however, I've been tasked by our deployment guys to try and move away from external libraries where possible as it makes their job easier. Simple question I suppose to start with, does Python have any inbuilt XML processing modules? If the answer is no then I'll stick with eTree, if python does have one, then I'll look at some migration steps. Many thanks All, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From silazima at gmail.com Tue Sep 9 06:46:44 2008 From: silazima at gmail.com (Mchizi_Crazy) Date: Tue, 9 Sep 2008 03:46:44 -0700 (PDT) Subject: Python Installation and Running on Windows Vista Message-ID: <4f66ca7b-b495-4b12-bb4c-29b096eb53c9@j22g2000hsf.googlegroups.com> Please help with issue... I heard of compatimbiltity issues and would like clarification. From joe.g at optusnet.com.au Fri Sep 19 07:12:01 2008 From: joe.g at optusnet.com.au (Joe G (Home)) Date: Fri, 19 Sep 2008 21:12:01 +1000 Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: <48d38904$0$31803$afc38c87@news.optusnet.com.au> Yep up and running now. Many thanks Joe From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 04:50:04 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 10:50:04 +0200 Subject: is decorator the right thing to use? In-Reply-To: References: Message-ID: <48db50aa$0$3750$426a74cc@news.free.fr> Dmitry S. Makovey a ?crit : > Aaron "Castironpi" Brady wrote: > >> It might help to tell us the order of events that you want in your >> program. You're not using 'mymethod' or 'mymethod2', and you probably >> want 'return fnew' for the future. Something dynamic with __getattr__ >> might work. Any method call to A, that is an A instance, tries to >> look up a method of the same name in the B instance it was initialized >> with. > > well 'mymethod' and 'mymethod2' were there just to show that A doesn't > function as a pure proxy - it has methods of it's own. See my respnse to > Steve - I proxy messages to more than one aggregated object. going over > them on __getattr__ to look up methods just doesn't seem to be really > efficient to me (I might be wrong though). Decorators seemed to present > good opportunity to simplify the code (well except for the decorator > function itself :) ), make code bit more "fool-proofed" (and give me the > opportunity to test decorators in real life, he-he). > > So decorators inside of B just identify that those methods will be proxied > by A. On one hand from logical standpoint it's kind of weird to tell class > that it is going to be proxied by another class, Indeed - usually, proxied objects shouldn't have to be aware of the fact. That doesn't mean your variation on the proxy pattern is necessarily bad design (hard to tell without lot of context anyway...), but still there's some alarm bell ringing here IMHO - IOW : possibly the right thing to do, but needs to be double-checked. > but declaration would be > real close to original function definition which helps to identify where is > it used. > > Note that my decorator doesn't change original function - it's a subversion > of decorator to a certain degree as I'm just hooking into python machinery > to add methods to A upon their declaration in B (or so I think). I wouldn't call this a "subversion" of decorators - it's even a pretty common idiom to use decorators to flag some functions/methods for special use. Now I'm not sure I really like your implementation. Here's a possible rewrite using a custom descriptor: class Proxymaker(object): def __init__(self, attrname): self.attrname = attrname def __get__(self, instance, cls): def _proxied(fn): fn_name = fn.__name__ def delegate(inst, *args, **kw): target = getattr(inst, self.attrname) #return fn(target, *args,**kw) method = getattr(target, fn_name) return method(*args, **kw) delegate.__name__ = "%s_%s_delegate" % \ (self.attrname, fn_name) setattr(cls, fn_name, delegate) return fn return _proxied class A(object): def __init__(self,b): self.val='aval' self.b=b b.val='aval' proxy2b = Proxymaker('b') def mymethod(self,a): print "A::mymethod, ",a def mymethod2(self,a): print "A::another method, ",a class B(object): def __init__(self): self.val='bval' @A.proxy2b def bmethod(self,a): print "B::bmethod" print a, self.val @A.proxy2b def bmethod2(self,a): print "B::bmethod2" print a, self.val My point is that: 1/ you shouldn't have to rewrite a decorator function - with basically the same code - for each possible proxy class / attribute name pair combo 2/ making the decorator an attribute of the proxy class makes dependencies clearer (well, IMHO at least). I'm still a bit uneasy wrt/ high coupling between A and B, and if I was to end up with such a design, I'd probably take some times to be sure it's really ok. My cents... From tino at wildenhain.de Mon Sep 22 12:09:40 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Sep 2008 18:09:40 +0200 Subject: A bit weird dictionary behavior In-Reply-To: References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: <48D7C344.2030909@wildenhain.de> Hi, bearophileHUGS at lycos.com wrote: > Tino Wildenhain: > >> Wouldn't >> len([x for x in iterable if x==y]) >> or even shorter: >> iterable.count(y) >> not work and read better anyway? > > The first version creates an actual list just to take its length, > think about how much memory it may use. yes it seems len() does not alternatively iterate or __len__ of the generator objects don't allow for an optimization yet. This could be improved so len(x for x in iterable ...) would work and save memory. > The second version requires the 'iterable' object to have a count() > method, and in general this is false. of course this always depends on the usecase. >> even calculating with boolean values isn't neccessary >> since 'and' and 'foo if bar else blub' are working much better >> so the type coalescing >> bool - int - float can really go away. > > I don't understand. if you have a operator b and type(a) <> type(b) then coercing goes on to convert one partner to the type of the other. So bool currently gets "upgrated" to int (as int is upgraded to float and so on). If this goes away, the type ambiguity is gone. This would result in 1==True -> False HTH Tino PS: are you per chance using a news gateway to post? This seems to screw up threading somehow... > Bye, > bearophile > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From straton at lampsacos.demon.co.uk Fri Sep 5 08:09:28 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 05 Sep 2008 13:09:28 +0100 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: David C. Ullrich wrote: > > I don't see why you feel the two should act the same. > At least in mathematics, the sum of the elements of > the empty set _is_ 0, while the maximum element of the > empty set is undefined. > > And both for good reason: > > (i) If A and B are disjoint sets we certainly want to > have sum(A union B) = sum(A) + sum(B). This requires > sum(empty set) = 0. > > (ii) If A is a subset of B then we should have > max(A) <= max(B). This requires that max(empty set) > be something that's smaller than everything else. > So we give up on that. Do we give up? Really ? From wikipedia: http://en.wikipedia.org/wiki/Empty_set (Uses wikipedia's LaTeX notation -- I hope those interested are OK with that ) Mathematics [edit] Extended real numbers Since the empty set has no members, when it is considered as a subset of any ordered set, then any member of that set will be an upper bound and lower bound for the empty set. For example, when considered as a subset of the real numbers, with its usual ordering, represented by the real number line, every real number is both an upper and lower bound for the empty set.[3] When considered as a subset of the extended reals formed by adding two "numbers" or "points" to the real numbers, namely negative infinity, denoted -\infty\!\,, which is defined to be less than every other extended real number, and positive infinity, denoted +\infty\!\,, which is defined to be greater than every other extended real number, then: \sup\varnothing=\min(\{-\infty, +\infty \} \cup \mathbb{R})=-\infty, and \inf\varnothing=\max(\{-\infty, +\infty \} \cup \mathbb{R})=+\infty. That is, the least upper bound (sup or supremum) of the empty set is negative infinity, while the greatest lower bound (inf or infimum) is positive infinity. By analogy with the above, in the domain of the extended reals, negative infinity is the identity element for the maximum and supremum operators, while positive infinity is the identity element for minimum and infimum. From arkanes at gmail.com Wed Sep 24 15:26:31 2008 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Sep 2008 14:26:31 -0500 Subject: Linq to Python In-Reply-To: <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <4866bea60809241226k29203854u988f00aafd6f791a@mail.gmail.com> On Wed, Sep 24, 2008 at 2:11 PM, wrote: > sturlamolden: >>No, because Python already has list comprehensions and we don't need the XML buzzword.< > > LINQ is more than buzzwords. Python misses several of those features. > So maybe for once the Python crowd may recognize such C# feature as > much better than things present in Python. > Said that, I presume Python will go on as usual, and LINQ-like > capabilities will not be integrated in Python. In the meantime where I > live lot of people will keep using C# instead of Python and CLisp, > natural selection at work indeed. > Why do you swing so widely between being an interesting poster with interesting, useful things to say and mindless trolling? There's a lot of reasons to use C# instead of Python or Lisp (or any other language for that matter), but I can't imagine that someone would make that decision based solely on LINQ. I'd go so far as to say that if they do, I question their professional competence. LINQ is an interesting implementation of an old idea. The place where it differs from list comps is that it has appropriate hooks for the specific linq implementation to override the way results are gathered, and such hooks in Python would be an interesting idea. I've taken a shot and figuring out where and how they should be implemented, but I haven't come up with anything I like. Maybe you should try it? LINQs "native" object API (not the syntax sugar available in C#) is not very different from Python ORMs. From overdrigzed at gmail.com Sun Sep 14 13:41:13 2008 From: overdrigzed at gmail.com (overdrigzed at gmail.com) Date: Sun, 14 Sep 2008 10:41:13 -0700 (PDT) Subject: ctypes: Get full contents of character array References: <223fde52-b1aa-4d69-b374-2cf07973f2b5@73g2000hsx.googlegroups.com> Message-ID: <34477897-3a2b-42e9-a753-c2f95ad5c3a2@x41g2000hsb.googlegroups.com> On Sep 13, 6:45?am, "Aaron \"Castironpi\" Brady" wrote: > On Sep 12, 6:38?pm, overdrig... at gmail.com wrote: > > > > > > > > > Hello! > > > I wanted to get the full contents of a character array stored in a > > struct, i.e. > > _fields_ = [...("array", c_char * 12)...] > > however,ctypesseems to try to return struct.array as a Python string > > rather than a character array, and stops as soon as it encounters a > > null within the character array. > > > I ended up having to define a dummy struct > > class dummystruct(Structure): > > ? ? _fields_ = [] > > > and declare array as: > > ("array", dummystruct) > > > then use string_at(byref(struct.array), 12). > > > Is this really the best way of doing it? Is there no better way to > > work aroundctypes'guess what you want' behaviour? > > > Thanks in advance, > > Rodrigo > > Rodrigo, > > If you have the option to change your declaration to c_byte* 12, you > have more options. ?This example prints the null character you wanted. > > fromctypesimport * > import struct > class S( Structure ): > ? ? _fields_= [ > ? ? ? ? ( 'array', c_byte* 12 ) > ? ? ] > s= S() > > #initialize > struct.pack_into( '7s', s.array, 0, 'abc\x00def' ) > > #prototype and call PyString_FromStringAndSize > prototype= PYFUNCTYPE( py_object, POINTER( c_byte ), c_size_t ) > PyString_FromStringAndSize= prototype( ( "PyString_FromStringAndSize", > pythonapi ) ) > x= PyString_FromStringAndSize( s.array, 12 ) > print repr( x ) > > #prototype and call PyString_FromString for contrast > prototype= PYFUNCTYPE( py_object, POINTER( c_byte ) ) > PyString_FromString= prototype( ( "PyString_FromString", pythonapi ) ) > x= PyString_FromString( s.array ) > print repr( x ) > > /Output: > > 'abc\x00def\x00\x00\x00\x00\x00' > 'abc' Great - and thank you for replying so fast! I found that [chr(x) for x in struct.array] with array as a c_byte * 12 did what I needed. From kurdayon at yahoo.com Sun Sep 28 19:51:07 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Sun, 28 Sep 2008 16:51:07 -0700 (PDT) Subject: Web programming in Python. References: Message-ID: 1. On my server (in my directory) I found "cgi-bin" subdirectory. 2. In the "cgi-bin" I have created a file "test.py". 3. In that file I put: #!/usr/bin/python2.4 python print "Hello, World!" (I have checked, I have "/usr/bin/python2.4" directory.) 4. I give the following permissions to the "test.py": -rwx---r-x 5. The "cgi-bin" directory has the following permissions: drwx---r-x 6. In the "cgi-bin" I have created the ".htaccess" file which contains: Options +ExecCGI AddHandler cgi-script .py And it still does not work! If I try to see the page by my browser I see: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. ... From karl.kobata at syncira.com Thu Sep 18 02:43:36 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Wed, 17 Sep 2008 23:43:36 -0700 Subject: member functions in a class Message-ID: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> I am new to python and am wondering. When I create a class, with 'def' functions and if this class is instantiated say 50 times. Does this mean that all the 'def' functions code within the class is duplicated for each instance? Can someone give me a short and simple answer as to what happens in python? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Thu Sep 4 18:16:20 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 00:16:20 +0200 Subject: why is self not passed to id()? In-Reply-To: References: <200809042244.54418.maric@aristote.info> Message-ID: <200809050016.21162.maric@aristote.info> Le Thursday 04 September 2008 23:35:18 Terry Reedy, vous avez ?crit?: > Maric Michaud wrote: > > Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez ?crit : > >> class foo(list): > >> ? ? __hash__ = lambda x: id(x) > > > > Wow ! You are really going on trouble with this, believe me there is a > > real good reason for list not to be hashable. A dictionnary or set > > containing some of your foo is virtually inconsistent, read carefully the > > manual about prerequesites for dict keys, they *need* to be immutable. > > No, the id comparison needs to be immutable -- which it is by default > for object()s, being based on id. ?Mutable instances of classes derived > from object work fine as keys as long as they keep default __eq__ and > __hash__. ?List over-rides the default, so foo needs to reverse that > override: > ? ?def __eq__(self, other): > ? ? ?return id(self) == id(other) > > This means, of course, that foo loses value-based equality comparison. Yes, so what's the point of using lists as keys. "class a : pass" already do this. -- _____________ Maric Michaud From victor.prosolin at gmail.com Mon Sep 29 12:25:43 2008 From: victor.prosolin at gmail.com (Fly Away) Date: Mon, 29 Sep 2008 09:25:43 -0700 (PDT) Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> Message-ID: <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> On Sep 29, 3:05?am, Lawrence D'Oliveiro wrote: > In message > <02918eb6-c2fb-4908-923f-d878a1956... at x35g2000hsb.googlegroups.com>, > > sturlamolden wrote: > > ... and possibility of interfacing with gnuplot ... > > Gnuplot is non-Free software. Yes, it is. Victor. From steven at REMOVE.THIS.cybersource.com.au Fri Sep 26 04:26:56 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 08:26:56 GMT Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: On Fri, 26 Sep 2008 19:46:10 +1200, Lawrence D'Oliveiro wrote: > In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: >> >>> Just a thought, your minimum sleep time is probably limited by the >>> resolution of the system "HZ" clock. Type >>> >>> less /proc/config.gz >> >> $ less /proc/config.gz >> /proc/config.gz: No such file or directory >> >> >> What OS are you using? > > The one named in the subject line? Are you asking me or telling me? I've tried on five different Linux machines I have access to, and there is no such /proc/config.gz on any of them: two different versions of Centos two versions of Fedora one version of Ubuntu So let me rephrase my question... what *specific* OS are you using? -- Steven From adityashukla1983 at gmail.com Mon Sep 29 00:51:21 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 28 Sep 2008 23:51:21 -0500 Subject: Parser Module Message-ID: <73045cca0809282151w1c091255y8c4a8bb85004e5a3@mail.gmail.com> Hello folks , I wanna create a parser for newick files which generates an ultrametric tree -> every leaf is equidistant from the root eg ->( http://www.icp.be/~opperd/private/upgma.html) as the parse tree.Can this type of a parse tree be constructed?And what parser module should i use? Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Wed Sep 3 02:23:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Sep 2008 06:23:23 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> Message-ID: <6i6oqrFmcad7U1@mid.uni-berlin.de> On Wed, 03 Sep 2008 01:23:47 -0400, Derek Martin wrote: > On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote: >> The subprocess module is also supposed to replace os.system and >> os.spawn*, neither of which involve opening pipes. > > Uh... it's a replacement for os.popen(), which -- guess what -- opens > pipes. >From the documentation: subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* If it weren't called `Popen` but `Spawn` instead I guess you would argue that it *must* be `Spawn` because it spawns processes and even it is not using `spawn*()` under the hood it uses the concept of "spawn" with some extras. ;-) Ciao, Marc 'BlackJack' Rintsch From akean at paradise.net.nz Wed Sep 10 17:57:06 2008 From: akean at paradise.net.nz (Anita Kean) Date: 11 Sep 2008 09:57:06 +1200 Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: On 2008-09-10, denisbz at t-online.de wrote: > (snip) ... > > So to refine the question: > how can I list all modules that might be importable on my system, > without actually importing them all ? > > (How about a "pydoc2" that's well thought out, doesn't crash ... > let me ask more knowledgable people, what's a good small help system > as model ? > ) I'm constantly finding myself wishing for this feature - something of the "apropos"/"whatis" of the linux shell (and debian's "apt-cache search" and "apt-cache show" which allow you to search and query before you install). (Matlab's "help" and "lookfor" commands cover this too.) Is there a reason this type of information hasn't been made available by default in the help system? I'm constantly using find, grep and Usenet to find out what python tools I can use. Anita From mail at timgolden.me.uk Tue Sep 16 14:56:48 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 19:56:48 +0100 Subject: A unique instance of Python GUI program In-Reply-To: <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> Message-ID: <48D00170.1090600@timgolden.me.uk> akineko wrote: > On Sep 16, 1:58 am, Tim Golden wrote: >> I swear this question's been asked twice this month already. > > > Thank you very much for many pointers. > I'm awfully sorry for posting something that is already answered in > the past. I was more amused than annoyed. Don't let my tone put you off. In any case, searching is all too often a question of knowing what the answer is so you can search for it! TJG From rridge at csclub.uwaterloo.ca Thu Sep 25 16:59:43 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 25 Sep 2008 16:59:43 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> Message-ID: Ross Ridge wrote: > Plenty of people were quick to say that the exception should be passed > through to the caller. No one said this behaviour should be documented. > There may be little practical difference bewteen calling sys.exit() > after printing an error and progating an exception if no one using the > library knows that it could generate that exception in those > circumstances. Steven D'Aprano wrote: >That's true, I didn't explicitly say that the library should be >documented. Nor did I say that it shouldn't be riddled with bugs. There's >little practical difference between a buggy library and one that raises >unexpected (i.e. undocumented) exceptions either. The problem is that few Python libraries properly document where and when they might generate exceptions. They'll document the fact that they have an "error" exception, but only vaguely say which functions or methods could generate it and why. You need either use trial and error to find out, or look at the source. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From google at mrabarnett.plus.com Fri Sep 26 11:34:19 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Sep 2008 08:34:19 -0700 (PDT) Subject: how to replace and string in a "SELECT ... IN ()" References: <48dcc0ce$0$25400$426a34cc@news.free.fr> Message-ID: <7b2079a8-dbc1-4d06-8820-8fdc1fc00e38@a1g2000hsb.googlegroups.com> On Sep 26, 12:23?pm, Tino Wildenhain wrote: > Hi, > > > > Bruno Desthuilliers wrote: > > bcurtu a ?crit : > >> Hi, > > >> I have a BIIIIIG problem with the next query: > > >> ? ? ? ? cursor.execute(""" > >> ? ? ? ? ? ? ? ? ? ? SELECT titem.object_id, titem.tag_id > >> ? ? ? ? ? ? ? ? ? ? FROM tagging_taggeditem titem > >> ? ? ? ? ? ? ? ? ? ? WHERE titem.object_id IN (%s) > >> ? ? ? ? ? ? ? ? """,( eid_list)) > > >> eid_list is suppossed to be a list of ids = [1,5,9] > > >> How can I make it work? > > > You have to build your sql statement in three stages: > > > # stage 0: the template > > sql_template = """ > > ? ? SELECT titem.object_id, titem.tag_id > > ? ? FROM tagging_taggeditem titem > > ? ? WHERE titem.object_id IN (%s) > > """ > > > # stage 1: build correct place_holders string for the actual number > > # of items in eid_list > > place_holders = ", " .join("%s" for x in xrange(len(eid_list))) > > Hm. either ", ".join(["%s"]*len(eid_list)) > or ", ".join("%s" for x in eid_list) > > should produce the same, wouldn't it? :-) > [snip] Or: place_holders = ("%s," * len(eid_list))[ : -1] :-) From lists at cheimes.de Fri Sep 12 11:21:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Sep 2008 17:21:57 +0200 Subject: setattr in class In-Reply-To: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: Bojan Mihelac wrote: > I guess A class not yet exists in line 4. Is it possible to achive > adding dynamic attributes without using exec? Correct, the class doesn't exist until the end of the class body. You can either do it outside the class definition or you can use a metaclass. Christian From gary at byoteki.com Sun Sep 28 16:20:09 2008 From: gary at byoteki.com (Gary M. Josack) Date: Sun, 28 Sep 2008 16:20:09 -0400 Subject: generate random digits with length of 5 In-Reply-To: <48DFE5A7.5040000@byoteki.com> References: <48DFE5A7.5040000@byoteki.com> Message-ID: <48DFE6F9.50405@byoteki.com> Gary M. Josack wrote: > Aaron "Castironpi" Brady wrote: >> On Sep 28, 2:59 pm, sotirac wrote: >> >>> Wondering if there is a better way to generate string of numbers with >>> a length of 5 which also can have a 0 in the front of the number. >>> >>>
>>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
>>> elements
>>>  code = 'this is a string' + str(random_number[0]) +
>>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
>>> + str(random_number[4])
>>> 
>>> >> >> '%05i'%random.randint(0,99999) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > This produces numbers other than 5 digit numbers. making the start > number 10000 should be fine. > -- > http://mail.python.org/mailman/listinfo/python-list nevermind. my brain is tired tonight. this is the best solution. From bdesth.quelquechose at free.quelquepart.fr Mon Sep 29 12:27:22 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2008 18:27:22 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> Message-ID: <48e11dd4$0$20720$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message , Ross Ridge wrote: > >> You need either use trial and error to find out, or look at the source. > > So what's wrong with using the source as documentation? :) Don't know... Ok, having higher-level documentation (the big picture, and quick description of what and how for classes and functions) really helps. But when it comes to nitty-gritty details, source code is the best documentation ever, since it's always accurate and up to date. FWIW, I'm often surprised by people asking questions about some implementation detail of some open-source library or framework that are very easily answered just looking at the source code. Reading the source is 1/ the best way to really know how something is implemented and 2/ usually very instructive. From somenewguy61 at googlemail.com Tue Sep 23 19:38:43 2008 From: somenewguy61 at googlemail.com (somenewguy61 at googlemail.com) Date: Tue, 23 Sep 2008 16:38:43 -0700 (PDT) Subject: detektei info detektei hessen in Gunzenhausen Message-ID: http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET From castironpi at gmail.com Fri Sep 26 22:22:42 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 19:22:42 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> Message-ID: <35681490-2d50-4a51-ae88-c1538ed51e15@y21g2000hsf.googlegroups.com> On Sep 26, 9:09?pm, George Sakkis wrote: > On Sep 26, 9:30?pm, Grant Edwards wrote: > > > On 2008-09-26, nntpman68 wrote: > > > > Hm, > > > > I guess you just filter mailing lists and can do nothing about the > > > newsgroup if I'm fetching via the nntp server of my ISP itself, right? > > > I read the group via NNTP, and I find that blocking all > > articles posted from google.groups gets rid of all of the spam. > > ... along with a far from trivial (I guess) percentage of non-spam, > such as this post. > > And-nothing-of-value-was-lost'ly yrs, > George Every method has false positives, George. (including this one.) From martin at see.sig.for.address.invalid Mon Sep 1 17:03:44 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Mon, 1 Sep 2008 21:03:44 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Mon, 01 Sep 2008 12:04:05 -0700, Robert Maas, http://tinyurl.com/uh3t wrote: >> From: George Neuner A friend of mine had an >> early 8080 micros that was programmed through the front panel using >> knife switches > > When you say "knife switches", do you mean the kind that are shaped like > flat paddles? > Pedantic correction: "Knife switch" is the wrong term. These are high current switches, typically used in the sort of heavy duty circuit where the wiring hums when power is on or in school electrical circuits so even the back of the class can see whether the switch is open or closed. In these a copper 'blade' closes the contact by being pushed down into a narrow, sprung U terminal that makes a close contact with both sides of the blade. Like this: http://www.science-city.com/knifeswitch.html What you're talking is a flat handle on a SPST or DPST toggle switch. It is often called a paddle switch and mounted with the flats on the handle horizontal. Like this, but often with a longer handle: http://www.pixmania.co.uk/uk/uk/1382717/art/radioshack/spdt-panel-mount- paddle-s.html -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From seandavi at gmail.com Thu Sep 11 04:23:00 2008 From: seandavi at gmail.com (Sean Davis) Date: Thu, 11 Sep 2008 01:23:00 -0700 (PDT) Subject: emulating read and readline methods References: Message-ID: <0d961161-3789-46c3-8018-06b26af7f767@x35g2000hsb.googlegroups.com> On Sep 10, 7:54?pm, John Machin wrote: > On Sep 11, 8:01?am, MRAB wrote: > > > > > On Sep 10, 6:59?pm, Sean Davis wrote: > > > > I have a large file that I would like to transform and then feed to a > > > function (psycopg2 copy_from) that expects a file-like object (needs > > > read and readline methods). > > > > I have a class like so: > > > > class GeneInfo(): > > > ? ? def __init__(self): > > > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > > > gene_info.gz',"/tmp/gene_info.gz") > > > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > > > ? ? ? ? self.fh.readline() #deal with header line > > > > ? ? def _read(self,n=1): > > > ? ? ? ? for line in self.fh: > > > ? ? ? ? ? ? if line=='': > > > ? ? ? ? ? ? ? ? break > > > ? ? ? ? ? ? line=line.strip() > > > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > > > ? ? ? ? ? ? rowvals = line.split("\t") > > > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > > > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > > > ? ? def readline(self,n=1): > > > ? ? ? ? return self._read().next() > > > > ? ? def read(self,n=1): > > > ? ? ? ? return self._read().next() > > > Each time readline() and read() call self._read() they are creating a > > new generator. They then get one value from the newly-created > > generator and then discard that generator. What you should do is > > create the generator in __init__ and then use it in readline() and > > read(). > > > > ? ? def close(self): > > > ? ? ? ? self.fh.close() > > > > and I use it like so: > > > > a=GeneInfo() > > > cur.copy_from(a,"gene_info") > > > a.close() > > > > It works well except that the end of file is not caught by copy_from. > > > I get errors like: > > > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > > > during .read() call > > > CONTEXT: ?COPY gene_info, line 1000: "" > > > > for a 1000 line test file. ?Any ideas what is going on? > > > I wonder whether it's expecting readline() and read() to return an > > empty string at the end of the file instead of raising StopIteration. > > Don't wonder; ReadTheFantasticManual: > > read( [size]) > > ... An empty string is returned when EOF is encountered > immediately. ... > > readline( [size]) > > ?... An empty string is returned only when EOF is encountered > immediately. Thanks. This was indeed my problem--not reading the manual closely enough. And the points about the iterator being re-instantiated were also right on point. Interestingly, in this case, the code was working because read() and readline() were still returning the next line each time since the file handle was being read one line at a time. Sean From google at mrabarnett.plus.com Mon Sep 22 20:12:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Sep 2008 17:12:35 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> <1f913671-1c21-4018-a841-a5a02a360c3b@k30g2000hse.googlegroups.com> Message-ID: <49ffb44f-c14d-4d38-86fb-eb50e5ef9abf@d1g2000hsg.googlegroups.com> On Sep 22, 11:07?pm, CapnBearbo... at googlemail.com wrote: > On Sep 22, 5:52?pm, Matimus wrote: > > > > > On Sep 22, 2:31?pm, CapnBearbo... at googlemail.com wrote: > > > > hi all, > > > > forgive me , but the RTFM and Google search approaches are not > > > yielding an answer on this question. ?I need to know if there's a top > > > level python interpreter command that clears all user variables (not > > > built-ins) from the global namespace. ?In other words a statement, or > > > some_command_or_function(), that does this: > > > > >>> x=3 > > > >>> y=4 > > > >>> z=[] > > > >>> dir() > > > > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > > > > >>> some_command_or_function() > > > >>> dir() > > > > ['__builtins__', '__doc__', '__name__'] > > > > thanks, > > > ? ?1 desperate snake oil programmer .... > > > I don't think you will find anything. The interpreter is essentially > > the same whether you are in interactive mode or not. That is, there is > > very little use for a method that clears globals in general, so why > > would we add it just so that it could be used by the interpreter. > > There is almost* nothing available to the interactive interpreter > > which isn't part of the core language. > > > * The only difference I can think of is the "_" variable, which is > > added to __builtins__ and contains the last value returned in > > interactive mode. If you have ever tried to run code that uses the > > locale module from the interpreter you will see why having any > > differences between the interactive and non-interactive interpreter > > can be a pain. > > > Matt > > ok. thanks! guess i'll be off to define my own function ... How about something like this: def clear_workspace(): keep_set = set(['__builtins__', '__doc__', '__name__', 'clear_workspace']) for x in globals().keys(): if x not in keep_set: del globals()[x] From castironpi at gmail.com Wed Sep 10 15:13:34 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 10 Sep 2008 12:13:34 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <3d6488c1-d57c-46be-b404-9c79bd49dbdf@y21g2000hsf.googlegroups.com> Message-ID: <09951f30-83d5-452c-9f78-c3d7491ecc32@a70g2000hsh.googlegroups.com> On Sep 9, 10:03?pm, George Sakkis wrote: > On Sep 9, 5:59?pm, castironpi wrote: > > > I will try my idea again. ?I want to talk to people about a > > module I want to write and I will take the time to explain it. > >?I think it's a "cool idea" that a lot of people, forgiving the > > slang, could benefit from. ? > > > (snipped) > > > A pure Python alloc-free implementation based on the GNU PAVL > > tree library is on Google Code. ?It is only in proof-of-concept > > form and not commented, but does contain a first-pass test > > suite. ?See: > > ? ?http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk > > So at best (i.e. if it actually makes any sense; I didn't read it), > this is an ANNouncement of a pre-alpha piece of code. ANN posts rarely > attract replies, even when they are about production/stable software. > Thankfully, most people don't expect (let alone "require") readers to > share their interest or enthusiasm by replying to the ANN. Given your > past semi-coherent and incoherent posts, expecting people to jump on > such a thread is a rather tall order. > > George No, I'm just excited about it and want to share. I definitely think that discouragement of new ideas, successes, and personal expressions is a weakness that society has, and something that c-l-py is missing as well. I want to encourage them in other people so I will do it myself. As for the practicality of this module, I am definitely receiving skepticism from the group. Further, its feasibility is in question. For instance, no one has pointed out, and I only came across last night, that IPC synchronization is non-trivial and possibly platform- dependent. Of course it's a prerequisite for the advance of any IPC mod, so I'm glad I did not release an ANN. From fredrik at pythonware.com Wed Sep 10 12:46:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 18:46:56 +0200 Subject: dict slice in python (translating perl to python) In-Reply-To: References: Message-ID: B wrote: > for a long list, you could try: > result = [mydict[k] for k in mydict] > or [mydict[k] for k in mydict.keys()] > or [mydict[k] for k in mydict.iterkeys()] and the point of doing that instead of calling mydict.values() is what? From tjreedy at udel.edu Sun Sep 28 17:47:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 17:47:44 -0400 Subject: closures and dynamic binding In-Reply-To: References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> Message-ID: Aaron "Castironpi" Brady wrote: > On Sep 28, 2:52 am, Steven D'Aprano > As for why the complicated version works, it may be clearer if you expand >> it from a one-liner: >> >> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) >> >> inner = lambda: n >> outer = lambda n: inner >> f[n] = outer(n) >> >> outer(0) => inner with a local scope of n=0 >> outer(1) => inner with a local scope of n=1 etc. For this to work, the 'expansion' has to be mental and not actual. Which is to say, inner must be a text macro to be substituted back into outer. >> Then, later, when you call inner() it grabs the local scope and returns >> the number you expected. > > I must have misunderstood. Here's my run of your code: I cannot speak to what Steven meant, but >>>> inner = lambda: n when inner is actually compiled outside of outer, it is no longer a closure over outer's 'n' and 'n' will be looked for in globals instead. >>>> outer = lambda n: inner >>>> outer(0) > at 0x00A01170> >>>> a=outer(0) >>>> b=outer(1) >>>> a() > Traceback (most recent call last): > File "", line 1, in > File "", line 1, in > NameError: global name 'n' is not defined > > Why doesn't 'inner' know it's been used in two different scopes, and > look up 'n' based on the one it's in? That would be dynamic rather than lexical scoping. From wuwei23 at gmail.com Thu Sep 4 20:54:32 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 4 Sep 2008 17:54:32 -0700 (PDT) Subject: xml + mmap cross References: Message-ID: <6a7336f2-8f71-47c2-88d5-d5172f14ce44@k36g2000pri.googlegroups.com> On Sep 4, 8:31?am, castironpi wrote: > Any interest in pursuing/developing/working together on a mmaped-xml > class? ?Faster, not readable in text editor. XML is text-based, so it should -always- be readable in a text editor. It's part of the definition, I believe. However, an implementation of one of the alternative binary XML formats would probably be very welcome. Fast Infoset: http://www.itu.int/rec/T-REC-X.891-200505-I/en EXI: http://www.w3.org/TR/2007/WD-exi-20070716/ I don't know enough about either format to say if it would be possible, but an implementation that conformed to the ElementTree API could be a big win. From aioe.org at technicalbloke.com Wed Sep 17 13:19:27 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 13:19:27 -0400 Subject: Python GUI for animation References: <1896f3dc-d8b6-41f4-9ff2-4c9cefc1ab84@a18g2000pra.googlegroups.com> Message-ID: Sean DiZazzo wrote: > On Sep 15, 11:29 pm, Virgil Stokes wrote: >> I have been using Python for a short time and I find it a very flexible >> language, and easy to learn and use. I have also worked some with PyGame > Then again, you mention sliders, knobs, etc. I don't think Tkinter > has alot of widgets built in. The other choice would be wxPython. > It's got lots of built in widgets, and it looks pretty good. If you > go this route, run the demo application to see what you have to work > with. > > http://wxpython.org/ > > Good luck. > > ~Sean Yes, I'd say wxPython is the way to go, mainly because of the numerous and excellent examples and example program. Also, gui stuff can be lengthy and verbose to code by hand and if you're using wxPython you can also use wxGlade, a python version of the popular Glade gui builder. Good luck :] Roger Heathcote. http://www.technicalbloke.com http://movingtoubuntu.technicalbloke.co.uk From kw at codebykevin.com Tue Sep 30 14:15:19 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 30 Sep 2008 14:15:19 -0400 Subject: IDLE doesn't run on OSX 10.3.9 In-Reply-To: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> References: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> Message-ID: <48E26CB7.8060207@codebykevin.com> thomascribbs at gmail.com wrote: > Just installed Python 2.5.2 on a PowerPC G4 running OSX 10.3.9 and > when clicking on the IDLE icon in the MacPython 2.5 folder nothing > happens, program doesn't execute... > > I've uninstalled, reinstalled over again... > > I friend of mine just installed the same 2.5.2 download from the > Python.org website on OSX 10.4.11 and all went fine...but shouldn't it > install on 10.3.9 as well? > > Anyone have any ideas? Thanks. > -Tom Do you have Tcl/Tk installed? It doesn't come on 10.3.9 by default. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From andreas.tawn at ubisoft.com Thu Sep 18 13:32:41 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Thu, 18 Sep 2008 19:32:41 +0200 Subject: Extracting hte font name from a TrueType font file In-Reply-To: References: Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758004C23CA0@PDC-MAIL3.ubisoft.org> > -----Original Message----- > From: python-list-bounces+andreas.tawn=ubisoft.com at python.org > [mailto:python-list-bounces+andreas.tawn=ubisoft.com at python.or g] On Behalf Of Steve Holden > Sent: Thursday, September 18, 2008 5:59 PM > To: python-list at python.org > Subject: Extracting hte font name from a TrueType font file > > Does anyone have a Python recipe for this? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > Can't help with a recipe, but here's the formal spec if want to figure it out yourself. http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6.html Hope that helps. Cheers, Drea From rsinger at ____.com Tue Sep 23 16:05:55 2008 From: rsinger at ____.com (Robert Singer) Date: Tue, 23 Sep 2008 22:05:55 +0200 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> Message-ID: On Tue, 23 Sep 2008 11:07:22 -0700 (PDT), sturlamolden wrote: >On Sep 23, 3:44?pm, Robert Singer wrote: > >> Well, python is not a number crunching language. However much we would >> like it to be (we would ? :-). > >> No scripting language is. > >Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? > No. And just to avoid eventual useless discussions which might arise, I ment to say that *in general* compiled languages are faster. We can always have discussions whether or not some newer scripting languages like some from the above list, come close, but that usually is just wasted time. Specifically, I cannot say about R, IDL or S-PLUS, since I never used those (not even heard of IDL till now). Octave and Mathematica have been with me for such a short time (we had a few licences for Wolfram's child for one year, but not my part of the company, so ...) that I would rather not give my opinion about those. I've used Matlab and Scilab for a longer time (still do actually - Matlab for measurement data acquisition, and Scilab ... well, it just sits on the disk somewhere actually), and although Matlab is quite fast when disk I/O is involved, it still comes far. >> Also, (I'm not that familiar with python yet, so I don't know how to >> do it in python), try finding the bottlenecks of your calculation. > >I did use a profiler, there is no particular single bottle-neck. You're talking about your c or your python version of the program? There is always a bottleneck - that's just the part which works most slowly. Try to find the part which takes the longest to execute, try to put it differently. If it cannot be done, go to the next slowest part. >Good compilers are too expensive, and gfortran is not good enough yet. > ? Gfortran is one of the better compilers on the market. There was, just the other day, a nice discussion on comp.lang.fortran how it is marvellous what a group of enthousiasts managed do in their time, what commercial giants still didn't. May I ask what are your main objections to it ? Best regards Bob From ldo at geek-central.gen.new_zealand Wed Sep 24 06:15:09 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:15:09 +1200 Subject: A bit weird dictionary behavior References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> Message-ID: In message , Terry Reedy wrote: > From this viewpoint, objecters would instead have to argue that it is > wrong to have such implicit calls and that programmers should have to > put them in explicitly. But then again, you want to avoid unexpected restrictions like in Java, where bool is a separate type, and while it is discrete, it cannot be used to index arrays. (Cf Pascal, where any discrete type could be used as an array index type.) From uninverted at lavabit.com Sun Sep 28 20:58:35 2008 From: uninverted at lavabit.com (Nathan Seese) Date: Mon, 29 Sep 2008 02:58:35 +0200 (CEST) Subject: Odd Errors References: <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> <1b1ed34d-f386-4389-a7f1-ce68be4e2a14@k30g2000hse.googlegroups.com> Message-ID: > On Sep 28, 7:13?pm, alex23 wrote: >> The problem is with this: >> >> > ? ? ? ? lines = lines.append(inLine) >> >> The append method of a list modifies the list in-place, it doesn't >> return a copy of the list with the new element appended. In fact, it >> returns None, which it then attaches the label 'lines' to, so the next >> iteration through it tries to call None.append... >> >> Replace the line with: >> >> ? ? lines.append(inLine) > > Do you ever want to scream from the rooftops, "'append' operates by > side-effect!"? Ah! Thanks, especially for the quick response. From gagsl-py2 at yahoo.com.ar Tue Sep 9 12:03:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 13:03:33 -0300 Subject: Clearing a session and reload() problem (with repro error) References: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> Message-ID: En Mon, 08 Sep 2008 05:37:24 -0300, Rafe escribi?: > I've tried to use reload with a very simple algorithm. Simply run > through every imported module, ignoring anything that is "None" or on > the C: drive (all of our python is on a network drive so this hack > works for me for now) and reload() it. I've come to realize that this > isn't near intelligent enough to handle sub-packages. > Package Structure: > --------------------------- > inheritRepro > __init__.py > baseLib.py > child > __init__.py To summarize your code: inheritRepro.__init__.py only contains the reload support; baselib is an independent module; child/__init__.py imports and uses baseLib. > # Iterate over all IMPORTED modules > modules = sys.modules > for modName in modules: > mod = modules[modName] (note: sys.modules could change along the iteration; I'd iterate this way instead) modules = sys.modules for modName in modules.keys(): mod = modules.get(modName) Output: Reloading Python Modules... Reloaded Reloaded Reloaded Note that child is reloaded *before* baseLib - when child imports baseLib, it still finds the old module. One should reload baseLib before reloading child, in that case it works fine. This dependency between modules, applied to all modules in your project, defines a "dependency graph". In some cases, one can define a partial ordering of its nodes, such that no module depends on any other module *after* it (it may depend only on modules *before* it). Look for "topological sort". Doing that in the generic case is not easy. If you *know* your dependencies, reload the modules in the right order by hand. > NOTE: this works if I don't use a sub-package for 'child' (child.py > instead). Is it overly simple to assume reloading by file structure > might work? You're iterating over sys.modules in whatever ordering the keys are in the dictionary; using other module names may yield the "right" ordering just by chance. -- Gabriel Genellina From google at mrabarnett.plus.com Fri Sep 26 09:03:22 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Sep 2008 06:03:22 -0700 (PDT) Subject: multiprocessing eats memory References: <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> Message-ID: On Sep 26, 9:52?am, redbaron wrote: > On 26 ????, 04:20, Istvan Albert wrote: > > > On Sep 25, 8:40?am, "Max Ivanov" wrote: > > > > At any time in main process there are shouldn't be no more than two copies of data > > > (one original data and one result). > > > From the looks of it you are storing a lots of references to various > > copies of your data via the async set. > > How could I avoid of storing them? I need something to check does it > ready or not and retrieve results if ready. I couldn't see the way to > achieve same result without storing asyncs set. You could give each worker process an ID and then have them put the ID into a queue to signal to the main process when finished. BTW, your test-case modifies the asyncs set while iterating over it, which is a bad idea. From gagsl-py2 at yahoo.com.ar Mon Sep 29 16:41:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 17:41:29 -0300 Subject: unable to parse the content using the regular expression References: Message-ID: En Thu, 25 Sep 2008 05:30:41 -0300, escribi?: > I've the following results from Difflib.Compare() which I want to parse > them > using the regular expression to find out the the values that have > changed. > > Results:- > ------- > > - Analysis Time (Iterations = 1) = 0.0449145s > ? ^^ ^ > + Analysis Time (Iterations = 1) = 0.0447347s > ? ^^ ^ > > > Here I want to display only the values that differ i.e. the lines prceded > with +,?,- signs > Instead of parsing that generated file (intended for human usage), use difflib.Differ or difflib.SequenceMatcher - you get a programming interface to the same info, easier to use in a script. -- Gabriel Genellina From 4g4trz802 at sneakemail.com Tue Sep 9 14:49:32 2008 From: 4g4trz802 at sneakemail.com (Michael Hoffman) Date: Tue, 09 Sep 2008 11:49:32 -0700 Subject: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles Message-ID: I am writing a library that creates temporary files and calls a series of external programs to process these files. Sometimes these external programs create files in the same directory as the input files, so to make sure they are all deleted, one must create them in a temporary directory, then delete it. I've written a NamedTemporaryDir class which is derived somewhat from tempfile.NamedTemporaryFile in the standard library. Right now I am using NamedTemporaryFile to create individual files, but since I am putting them in a directory that will be deleted anyway, I'm wondering if I can simplify things (and not have to keep track of all fo the NamedTemporaryFile instances) by using tempfile.mkstemp() specifying my temporary directory, and relying on the directory deletion when exiting its with block. Is there any reason I should keep track of each temporary files myself instead of deleting the whole directory? I am using Linux, but I would also be interested in cross-platform considerations. Also, the code is below. Is this worth submitting as a patch? # NamedTemporaryFile is based somewhat on Python 2.5.2 # tempfile._TemporaryFileWrapper # # Original Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python # Software Foundation; All Rights Reserved # # License at http://www.python.org/download/releases/2.5.2/license/ from tempfile import mkdtemp class NamedTemporaryDir(object): def __init__(self, *args, **kwargs): self.name = mkdtemp(*args, **kwargs) self.close_called = False def __enter__(self): return self unlink = os.unlink def close(self): if not self.close_called: self.close_called = True self.unlink(self.name) def __del__(self): self.close() def __exit__(self, exc, value, tb): result = self.file.__exit__(exc, value, tb) self.close() return result From gminick at bzt.bzt Fri Sep 26 06:15:33 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 26 Sep 2008 10:15:33 +0000 (UTC) Subject: how to replace and string in a "SELECT ... IN ()" References: Message-ID: On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote: > I have a BIIIIIG problem with the next query: > > cursor.execute(""" > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """,( eid_list)) ^ It should rather be '%'. HTH. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From lucafbb at gmail.com Mon Sep 1 05:45:36 2008 From: lucafbb at gmail.com (Luca) Date: Mon, 1 Sep 2008 11:45:36 +0200 Subject: Know if a object member is a method In-Reply-To: References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Message-ID: <27308d500809010245x29a393aya65561783ea0e804@mail.gmail.com> On Mon, Sep 1, 2008 at 11:35 AM, Steven D'Aprano wrote: > That's relatively fragile, since such names aren't reserved in any way. > It's easy to fool a name comparison check with an accidental name > collision: > >>>> class function(object): # not a reserved name > ... pass > ... >>>> x = function() >>>> type(x).__name__ > 'function' >>>> x() # must be a function then... > Traceback (most recent call last): > File "", line 1, in > TypeError: 'function' object is not callable > > > But not so easy to fool a type check: > >>>> type(x) == new.function > False > > Of course that's not bullet-proof either. I leave it as an exercise to > discover how you might break that piece of code. > Ok, so... What is the best way to do this? The "most pythonic"? -- -- luca From bearophileHUGS at lycos.com Mon Sep 29 12:57:31 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 09:57:31 -0700 (PDT) Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> Message-ID: <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Lawrence D'Oliveiro: >> Gnuplot is non-Free software. Fly Away: > Yes, it is. From: http://www.gnuplot.info/faq/faq.txt 1.7 Does gnuplot have anything to do with the FSF and the GNU project? [...] Gnuplot is freeware in the sense that you don't have to pay for it. However it is not freeware in the sense that you would be allowed to distribute a modified version of your gnuplot freely. [...] Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Tue Sep 2 12:54:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 16:54:54 GMT Subject: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0 References: <48bd6b4e$0$17174$742ec2ed@news.sonic.net> Message-ID: <00cd6a58$0$20302$c3e8da3@news.astraweb.com> On Tue, 02 Sep 2008 09:57:05 -0700, John Nagle wrote: > Jukka Aho wrote: >> Just a tip for those who are only just cutting their teeth on Python >> 3.0 and might have encountered the same problem as I did: >> >> When a Python (3.x) program is run on a terminal that only supports a >> legacy character encoding - such as Latin 1 or Codepage 437 - all >> characters printed to stdout will be automatically converted from the >> interpreter's internal Unicode representation to this legacy character >> set. > > Python 5 is even stricter. Only ASCII (chars 0..127) can be sent > to standard output by default. Python 5??? Is this the time machine again? -- Steven From ptmcg at austin.rr.com Wed Sep 3 01:14:51 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 2 Sep 2008 22:14:51 -0700 (PDT) Subject: pyparsing: match empty line References: Message-ID: <9f838a29-2e2e-4646-9026-36d3b8a49fce@c58g2000hsc.googlegroups.com> On Sep 2, 11:38?am, Marek Kubica wrote: > Hi, > > I am trying to get this stuff working, but I still fail. > > I have a format which consists of three elements: > \d{4}M?-\d (4 numbers, optional M, dash, another number) > EMPTY (the token) > [Empty line] (the token. The line may contain whitespaces, > but nothing else) > Marek - Here are some refinements to your program that will get you closer to your posted results. 1) Well done in resetting the default whitespace characters, since you are doing some parsing that is dependent on the presence of line ends. When you do this, it is useful to define an expression for end of line so that you can reference it where you explicitly expect to find line ends: EOL = LineEnd().suppress() 2) Your second test fails because there is an EOL between the two watchnames. Since you have removed EOL from the set of default whitespace characters (that is, whitespace that pyparsing will automatically skip over), then pyparsing will stop after reading the first watchname. I think that you want EOLs to get parsed if nothing else matches, so you can add it to the end of your grammar definition: parser = OneOrMore(watchname ^ pagebreak ^ leaveempty ^ EOL) This will now permit the second test to pass. 3) Your definition of pagebreak looks okay now, but I don't understand why your test containing 2 blank lines is only supposed to generate a single . pagebreak = LineStart() + LineEnd().setParseAction(replaceWith('')) If you really want to only get a single from your test case, than change pagebreak to: pagebreak = OneOrMore(LineStart() + LineEnd()).setParseAction(replaceWith('')) 4) leaveempty probably needs this parse action to be attached to it: leaveempty = Literal('EMPTY').setParseAction(replaceWith('')) 5) (optional) Your definition of parser uses '^' operators, which translate into Or expressions. Or expressions evaluate all the alternatives, and then choose the longest match. The expressions you have don't really have any ambiguity to them, and could be evaluated using: parser = OneOrMore(watchname | pagebreak | leaveempty | EOL) '|' operators generate MatchFirst expressions. MatchFirst will do short-circuit evaluation - the first expression that matches will be the one chosen as the matching alternative. If you have more pyparsing questions, you can also post them on the pyparsing wiki - the Discussion tab on the wiki Home page has become a running support forum - and there is also a Help/Discussion mailing list. Cheers, -- Paul From digitig at gmail.com Sun Sep 28 17:45:13 2008 From: digitig at gmail.com (Tim Rowe) Date: Sun, 28 Sep 2008 22:45:13 +0100 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: 2008/9/28 process : > I have heard some criticism about Python, that it is not fully object- > oriented. Why is that a criticism? OO is a tool, not a religion (ok, ok, OO *should be* a tool, not a religion). Is it a criticism of a hammer that it is not a screwdriver? Or do you pick the tool that does the job in hand most effectively? -- Tim Rowe From marco.bizzarri at gmail.com Wed Sep 10 13:18:18 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 10 Sep 2008 19:18:18 +0200 Subject: Presenting calculation results In-Reply-To: References: Message-ID: <3f0d61c40809101018q4346b322i2c6b42577c758601@mail.gmail.com> On Wed, Sep 10, 2008 at 6:46 PM, Vedran wrote: > Hello! > > I would like to present the results of the calculations on the web using > Python and Apache. Currently I have java console applications that > generate text files with results. Can somebody point me in the right > direction from where to start? > > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > http://www.modpython.org/ Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From fredrik at pythonware.com Sat Sep 6 06:58:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Sep 2008 12:58:37 +0200 Subject: use str as variable name In-Reply-To: <3f0d61c40809052308v185f3787p64f6fd89172114c7@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> <3f0d61c40809052308v185f3787p64f6fd89172114c7@mail.gmail.com> Message-ID: Marco Bizzarri wrote: >>> Just a question: "generic functions" are not meant in the sense of >>> "generic functions" of CLOS, am I right? >> >> it's meant in exactly that sense: len(L) means "of all len() implementations >> available to the runtime, execute the most specific code we have for the >> object L". >> > > It is a generic functions like a CLOS one, as long as we remain to one > parameter. > > I mean, there will be just one implemenatation of > > foo(bar, man) > > which the python interpretr can find; am I right? Let's see if I can sort this out without causing even more confusion. The Python *language* doesn't support generic functions in the CLOS sense, but a given Python *implementation* may use a dispatching machinery to select the best possible implementation for any call to a built-in function. Or in other words, the len() function shouldn't just be seen as a function that *always* does def len(L): return L.__len__() because if you look under the covers, it might be more like (using a hypothetical Python dialect): def generic len(L: list): return list::get_size(L) # fast internal dispatch def generic len(L: tuple): return tuple::get_size(L) # fast internal dispatch def generic len(L: object): return L.__len__() # fallback behaviour, using method dispatch where "len" represents a plurality of possible "len" implementations. How the dispatching is actually done is up to the specific Python implementation; CPython, for example, offers a "slot" mechanism for types implemented in C that's quite a bit faster than the method call machinery. And the slot mechanism isn't always single dispatch. For example, internal getattr(obj, name) calls use one of several slots, depending on what "name" is. Other Python implementations may use different approaches, but the point remains: a builtin function "operation(a, b, c)" isn't always mapped to "a.__operation__(b, c)" by the runtime; code that uses the latter form may be less efficient. And it's definitely less Pythonic. From circularfunc at yahoo.se Tue Sep 16 16:16:47 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 13:16:47 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> Message-ID: <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> On Sep 16, 7:49?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 16, 10:13?am, cnb wrote: > > > > > >>> sys.path > > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > > \lib\\site-packages\\PIL'] > > > Now I have my personal programs in C:/Python25/Progs/ > > > How do I add so that I can just do "import somefile" from anywhere in > > that directory in the interpreter and it can load files from other > > folders in that directory. > > Add a file: \Lib\site-packages\locals.pth > > with contents, path to the directory you want to add (/python25/progs/) And we have a winner! Now it works. Both doing import and loading form fiel with C-c C-l However jsut including C:/Python/Progs wasn't enough. I had to add the folder inside that that contains the files i needed. so how do i add all files within progs? is there something like C:/ python25/progs/* ? From nytrokiss at gmail.com Mon Sep 8 13:15:09 2008 From: nytrokiss at gmail.com (James Matthews) Date: Mon, 8 Sep 2008 10:15:09 -0700 Subject: Learning Python In-Reply-To: <_z9xk.830$sq3.754@trnddc07> References: <_z9xk.830$sq3.754@trnddc07> Message-ID: <8a6b8e350809081015y60ee8ae2k6a8aa54d1f94998f@mail.gmail.com> I like two 1. www.diveintopython.com and 2. Core Python Programming. On Mon, Sep 8, 2008 at 6:15 AM, Alan G Isaac wrote: > On 9/6/2008 5:17 AM James Pilling apparently wrote: > >> Hi im currently starting to learn python in sixth form at school any tips? >> > > The books suggestions of others are quite good. > Here is another approach: pick an easily understandable > application, and work doing things with it. > > Perhaps immodestly, I think that as soon as you > understand how to define a function and a class, > you can treat this paper > http://jasss.soc.surrey.ac.uk/11/3/8.html > as an introduction to applied Python programming. > The application area is very specific---game theoretic > simulations---but the illustrated techniques are > meant to be more general. > > Alan Isaac > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From ssharkey at linuxunlimited.com Thu Sep 25 15:17:40 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Thu, 25 Sep 2008 15:17:40 -0400 Subject: Eggs, VirtualEnv, and Apt - best practices? Message-ID: <48DBE3D4.2080902@linuxunlimited.com> Hello all, Our development group at work seems to be heading towards adopting python as one of our standard "systems languages" for internal application development (yeah!). One of the issues that's come up is the problem with apt (deb packages) vs eggs, vs virtual environments. We're probably gonna end up using Pylons or TurboGears for web-based apps, and I've recommended virtualenv, but one of the other developers has had some "inconsistencies" when mixing systems with python installed from apt (all our servers are debian or ubuntu based) vs when installed under virtualenv. I have basically recommended that we only install the python base (core language) from apt, and that everything else should be installed into virtual environments. But I wanted to check to see how other enterprises are handling this issue? Are you building python from scratch, or using specific sets of .deb packages, or some other process. Any insight into the best way to have a consistent, repeatable, controllable development and production environment would be much appreciated. Suggestions on build/rollout tools (like zc.buildout, Paver, etc) would also be appreciated. Thanks!!! -Scott From castironpi at gmail.com Fri Sep 26 13:54:10 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 10:54:10 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> Message-ID: <9c2cf0b3-ca53-4c66-ba65-cd15aefb4cb8@p25g2000hsf.googlegroups.com> On Sep 26, 10:41?am, "Dmitry S. Makovey" wrote: > Paul McGuire wrote: > > If you need to get fancier and support this single-proxy-to-multiple- > > delegates form, then yes, you will need some kind of map that says > > which method should delegate to which object. ?Or, if it is just a > > matter of precedence (try A, then try B, then...), then use hasattr to > > see if the first delegate has the given attribute, and if not, move on > > to the next. > > that is what I didn't like about it - I have to iterate over delegates when > I can build direct mapping once and for all and tie it to class > definition ;) You're right, there is a difference in performance. But it would still be simpler to have your 'getattr' method 'learn' what functions come from what objects, and then just route directly to them. > __getattr__ implies constant lookups and checks (for filtering purposes) - I > want to do them once, attach generated methods as native methods and be > done with it. That is why I do not like __getattr__ in this particular > case. Otherwise - you're right. Try this (untested!): def __getattr__( self, key ): if key in self.knownmeths: return self.knownmeths[ key ] for x in self.delegs: if hasattr( x, key ): _= self.knownmethds[ key ]= getattr( x, key ) return _ raise name not found self.knownmethds has desired order of precedence. From roy at panix.com Sun Sep 28 12:59:29 2008 From: roy at panix.com (Roy Smith) Date: Sun, 28 Sep 2008 12:59:29 -0400 Subject: destructor not called References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> Message-ID: In article <2a7dea43-378a-423f-a5bb-d904b7f97869 at p25g2000hsf.googlegroups.com>, Marcin201 wrote: > I have a class which uses a temporary directory for storing data. I > would like that directory to be removed when the class is no longer > used. I have tried removing the temporary directory from the class > destructor, however, it was never called. The short answer is that destruction in Python is non-deterministic (a rude shock if you're used to C++). What you probably want is the new "with" statement (http://docs.python.org/ref/with.html). From castironpi at gmail.com Thu Sep 4 15:57:51 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 12:57:51 -0700 (PDT) Subject: xml + mmap cross References: <48BF8AC8.6030509@behnel.de> Message-ID: On Sep 4, 2:14?am, Stefan Behnel wrote: > castironpi wrote: > > Any interest in pursuing/developing/working together on a mmaped-xml > > class? ?Faster, not readable in text editor. > > Any hints on what you are talking about? > > Stefan Nice to hear from you. I assumed you were familiar with the problem; you're not. In an XML file, entries are stored in serial, sort of like this. AAA BBB CCC DDD Or more recognizably,
somethingsomething Point is, to change something to something else, you have to recopy everything after that. AAA BBB CCC DDD AAA BBBb CCC DDD requires 7 writes, 'b CCC DDD', not 1. I want to use a simple tree structure to store: 0 A-> None, 1 1 B-> None, 2 2 C-> 3, None 3 D-> None, None Each node maps to 'Next, Child', or more accurately, 'Next Sibling, First Child'. You get constant time updates to contents, and log-time searches. There was a similar problem today in: From: Gerhard H?ring Date: Thu, 04 Sep 2008 13:08:59 +0200 Subject: Re: cPickle The OP wanted to update the third element in a pickled tuple, but not the first two. I propose to write a tree structure to a memory-mapped file. A heavyweight string class, Rope, I wrote, exceeded native string speeds at a file size of two megs. You could use that, or store the tree directly. The obstacle is probably mmap 'alloc' and 'free' routines, which I posted on Google Code. From castironpi at gmail.com Tue Sep 16 16:35:29 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 13:35:29 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> Message-ID: On Sep 16, 2:40?pm, "Support Desk" wrote: > What about on a unix box? Do you have write permissions on, in this case, '/opt/pkgs/python-2.0/ lib/python2.0/site-packages' ? (Or the entry in your sys.path.) >>> import sys >>> sys.path ['', '/opt/pkgs/python-2.0/lib/python2.0', '/opt/pkgs/python-2.0/lib/ python2.0/plat-sunos5', '/opt/pkgs/python-2.0/lib/python2.0/lib-tk', '/ opt/pkgs/python-2.0/lib/python2.0/lib-dynload', '/opt/pkgs/python-2.0/ lib/python2.0/site-packages'] > > Sincerely, > Michael H. > > -----Original Message----- > From: Aaron "Castironpi" Brady [mailto:castiro... at gmail.com] > Sent: Tuesday, September 16, 2008 12:49 PM > To: python-l... at python.org > Subject: Re: How do I add permanently to Pythons sys.path? > > On Sep 16, 10:13?am, cnb wrote: > > >>> sys.path > > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > > \lib\\site-packages\\PIL'] > > > Now I have my personal programs in C:/Python25/Progs/ > > > How do I add so that I can just do "import somefile" from anywhere in > > that directory in the interpreter and it can load files from other > > folders in that directory. > > Add a file: \Lib\site-packages\locals.pth > > with contents, path to the directory you want to add (/python25/progs/) > > From fredrik at pythonware.com Thu Sep 4 03:36:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 09:36:29 +0200 Subject: use str as variable name In-Reply-To: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> Message-ID: Mathieu Prevot wrote: > I have a program that take a word as argument, and I would like to > link this word to a class variable. > > eg. > class foo(): > width = 10 > height = 20 > > a=foo() > arg='height' > a.__argname__= new_value > > rather than : > > if arg == 'height': > a.height = new_value > elif arg == 'width'; > a.width = new_value > > Can I do this with python ? How ? assuming you mean "instance variable" ("a" is an instance of the class "foo"), you can use setattr: a = foo() arg = 'height' setattr(a, arg, new_value) From rustompmody at gmail.com Wed Sep 3 06:10:40 2008 From: rustompmody at gmail.com (rustom) Date: Wed, 3 Sep 2008 03:10:40 -0700 (PDT) Subject: eval() == evil? --- How to use it safely? References: <9d5933fd-f990-4bab-8dfb-258e245cc7d2@j22g2000hsf.googlegroups.com> Message-ID: On Aug 29, 4:42?am, castironpi wrote: > May I suggest PyYAML? I second that. Yaml is very pythonic (being indentation based) and pyyaml is sweet. Only make sure you use safe_load not load and you will have only default construction for standard python objects -- lists, dictionaries and 'atomic' things so no arbitrary code can be executed. Someone else suggested json which is about the same as yml if there are no objects. And by using safe_load you are not using objects. From mensanator at aol.com Mon Sep 15 00:00:51 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 14 Sep 2008 21:00:51 -0700 (PDT) Subject: RELEASED Python 2.6rc1 References: Message-ID: On Sep 12, 8:28?pm, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I ? > am happy to announce the first release candidate for Python 2.6. > > This is a release candidate, so while it is not suitable for ? > production environments, we strongly encourage you to download the ? > release and test it on your software. ?We expect only critical bugs to ? > be fixed between now and the final 2.6 release, still scheduled for ? > October 1st, 2008. ?There is one more release candidate planned for ? > September 17th. > > You might notice that unlike earlier releases, we are /not/ releasing ? > Python 3.0rc1 at this time. ?It was decided that 3.0 still needs time ? > to resolve open issues and that we would not hold up the 2.6 release ? > for this. ?We feel that Python 2.6 is nearly ready for its final ? > release. > > If you find things broken or incorrect, please submit bug reports at > > ? ? ?http://bugs.python.org > > For more information and downloadable distributions, see the Python ? > 2.6 website: > > ? ?http://www.python.org/download/releases/2.6/ > > (Note that the Windows installers will be uploaded shortly.) About this Vista note on that page: Vista Note Administrators installing Python for all users on Windows Vista either need to be logged in as Administrator, or use the runas command, as in: runas /user:Administrator "msiexec /i \.msi" I couldn't get Idle to run until Python was installed this way, so it appears to be required even for a single user. And I know that Windows operation is not Python's responsibility, but couldn't you point out casually that, by default, the Administrator account is disabled in Vista. And the above won't work until you find out how to enable the Administrator (an easy Google search). > > See PEP 361 for release schedule details: > > ? ? ?http://www.python.org/dev/peps/pep-0361/ > > Enjoy, > - -Barry > > Barry Warsaw > ba... at python.org > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (Darwin) > > iQCVAwUBSMsXV3EjvBPtnXfVAQJFsgP9GxZYQocbDTd0Z/0yEjpHfZ/FTd8y83jV > 5JouO07lB8XtLawnWB9hF8sUrCuBVog5He3mLVUPDmlyn30qvjYWMG2J6zW0yYMX > yZdjUyUmta0IMCsXe7YXj369xebh4nWuwG4tDygly4donA7GYPXAlxI48MmyDJxw > 1v07LM4Dttw= > =Nd3s > -----END PGP SIGNATURE----- From nemesis at nowhere.invalid Tue Sep 16 15:31:09 2008 From: nemesis at nowhere.invalid (Nemesis) Date: 16 Sep 2008 19:31:09 GMT Subject: [ANN] XPN 1.2.5 Message-ID: <48d0097d$0$40312$4fafbaef@reader5.news.tin.it> XPN (X Python Newsreader) is a multi-platform newsreader with Unicode support. It is written with Python+GTK. It has features like scoring/actions, X-Face and Face decoding, muting of quoted text, newsrc import/export, find article and search in the body, spoiler char/rot13, random taglines and configurable attribution lines. You can find it on: http://xpn.altervista.org/index-en.html or http://sf.net/projects/xpn Changes in this release: * v1.2.5: rewritten the articles management, now the articles are stored in a SQLite dB. Articles management now is faster and easier. Your xpn-1.0.0 groups and articles will be automatically imported and converted to the new format. * v1.2.5: added a filter toolbar that lets you filter the articles by Subject From and Body content. * v1.2.5: improved the algorithm used to build the discussion threads * v1.2.5: revisited the menus and some windows * v1.2.5: added automatic headers download every tot minutes * v1.2.5: some minor fixes and refinements. XPN is translated in Italian French and German, if you'd like to translate it in your language and you are familiar with gettext and po-files editing please contact me (xpn at altervista.org). -- Some memories are best forgotten _ _ _ | \| |___ _ __ ___ __(_)___ | .` / -_) ' \/ -_|_-< (_-< |_|\_\___|_|_|_\___/__/_/__/ http://xpn.altervista.org From marco.bizzarri at gmail.com Fri Sep 12 09:50:40 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 12 Sep 2008 15:50:40 +0200 Subject: Checking the boolean value of a collection Message-ID: <3f0d61c40809120650x7119940fr1a598eecd05b412e@mail.gmail.com> Hi all. In many parts of my code I've the following schema of code: def isInUseByOutgoingRegistrations(self, archivefolder): for instance in self.findActiveOutgoingRegistrationInstances(): if instance.forbidToClose(archivefolder): return True return False Before devising my own solution for this kind of problem, I wonder if there is a common solution for the problem. I'm looking for a python2.3 solution. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From afilash at gmail.com Sun Sep 7 11:02:25 2008 From: afilash at gmail.com (abhilash pp) Date: Sun, 7 Sep 2008 20:32:25 +0530 Subject: firefox timestamp Message-ID: <9f9d35df0809070802r7a5673dbre5a5143c4e041f1f@mail.gmail.com> hi all, -------------- next part -------------- An HTML attachment was scrubbed... URL: From toddw at activestate.com Fri Sep 5 12:33:35 2008 From: toddw at activestate.com (Todd Whiteman) Date: Fri, 05 Sep 2008 09:33:35 -0700 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <48BFB534.2080508@egenix.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <48BFB534.2080508@egenix.com> Message-ID: <48C15F5F.7040704@activestate.com> M.-A. Lemburg wrote: > A long time ago, there was a Python plugin for Netscape > which allowed you to run Python straight in the browser. Perhaps > it's time to revive such an idea... but then you're still missing > out on the GUI part, since you're still stuck with what the > browser has to offer in terms of widget support. > There is still a plugin (extension) for Mozilla based products, that enables use of Python in products like Firefox: http://pyxpcomext.mozdev.org/ Mark Hammond's Python/Mozilla work has enabled products like Komodo, Miro (Democracy) and the OLPC project to use Python as a major driver for consistent cross-platform GUI applications. Personally, I believe XULRunner has a lot to offer for Python GUI development, I'm currently finishing up some documentation steps to show off how to use it specifically for Python (I'll post it to this list when it's finished). Cheers, Todd From bdesth.quelquechose at free.quelquepart.fr Mon Sep 1 14:12:52 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 20:12:52 +0200 Subject: Getting an objetcs dict? In-Reply-To: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> References: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> Message-ID: <48bc4c94$0$1011$426a34cc@news.free.fr> ssecorp a ?crit : > I did nce (I think). > class X > > X.__dict__() and ngot a dict of its variables. > Now i get errors doing this. what am i doing wrong? cf Wojtek's answer. From ggpolo at gmail.com Sat Sep 20 14:34:57 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 20 Sep 2008 15:34:57 -0300 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> Message-ID: On Sat, Sep 20, 2008 at 1:27 PM, Mensanator wrote: > Beacuse in 2.6, Python apparently has fixed a discrepency that existed > in previous versions. > > In the IDLE that comes with 2.5, typing "as", to wit "import random as > ran", > the words "import" and "as" highlight in red, so you can't use them as > variable > names or you'll get a syntax error. > > Ah, but you CAN use "as" for a variable: "for as in xrange(10): print > as" > works just fine, although it shouldn't. > > Python 2.6 fixes this discrepency and now gives you a syntax error if > you > use "as" for a variable name. You should have noticed the warning you received in python 2.5 when using "as" as a name. > > The upshot is code (such as sympy) written prior to 2.6 can crash now > due > to this fix if said code inadverntently used what should have been a > reserved > word. > > I was able to fix the code for this "as" problem, but not the one that > came after. I've reported this and interested parties can visit the > sympy > page and check Issue 1115. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bmihelac at gmail.com Sun Sep 7 09:07:10 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Sun, 7 Sep 2008 06:07:10 -0700 (PDT) Subject: Python and M2Crypto question Message-ID: <12b278d2-9f78-4fc9-a4f2-7d22c543aeb9@d1g2000hsg.googlegroups.com> Hi all! I am trying to install M2Crypto to work on OSX10.5 apache (mod_python). Error I receive: Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5- macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image found. Did find: /Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg- tmp/M2Crypto/__m2crypto.so: no matching architecture in universal wrapper I guess that have to do something with x64 architecture but I am stucked and not able to find a way and to make this work. M2Crypto lib works good stand alone. Any help appreciated, Bojan From bearophileHUGS at lycos.com Thu Sep 4 15:42:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 4 Sep 2008 12:42:21 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> David C. Ullrich: > At least in mathematics, the sum of the elements of > the empty set _is_ 0, while the maximum element of the > empty set is undefined. What do you think about my idea of adding that 'default' argument to the max()/min() functions? Bye, bearophile From robert.kern at gmail.com Tue Sep 23 17:38:25 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 16:38:25 -0500 Subject: Python is slow? In-Reply-To: <5f2eed90-b49b-4c29-bfd5-cc90c4495b3c@m3g2000hsc.googlegroups.com> References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <5f2eed90-b49b-4c29-bfd5-cc90c4495b3c@m3g2000hsc.googlegroups.com> Message-ID: sturlamolden wrote: > On Sep 23, 10:16 pm, Robert Kern wrote: > >> What's confusing? You do have to create a profile: > > How do I add a new page to the wiki? I'm only able to edit the front > page of the cookbook. But it doesn't help to add link there if I have > no page to link. (I may be incredibly stupid though.) You just navigate to the URL you want: http://www.scipy.org/Cookbook/KDTree This will show you a page saying: """ This page does not exist yet. You can create a new empty page, or use one of the page templates. Before creating the page, please check if a similar page already exists. Create new empty page """ The latter is a link that you can click. Looking at the other Cookbook page sources, I notice that you should add the following to the bottom of your page to categorize it appropriately. """ ---- . CategoryCookbook """ Then put the link on the main Cookbook page (or do that first, then navigate through the link to create the page). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ldo at geek-central.gen.new_zealand Wed Sep 24 06:36:44 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:36:44 +1200 Subject: Program works great, except under less, cron or execl (Unicode?) References: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> <6jekbbF2v55pU2@mid.uni-berlin.de> Message-ID: In message , Sam wrote: > So how can I set sys.stdout.encoding so it's UTF-8 when piped through > cat (or anything else). > > I tried assigning to it, but no dice. You could try wrapping it in a file object that does explicit encoding translation, using codecs.EncodedFile . From dr.addn at gmail.com Sun Sep 28 20:18:24 2008 From: dr.addn at gmail.com (Ph.T) Date: Sun, 28 Sep 2008 17:18:24 -0700 Subject: Spring Python 0.7.0 is released In-Reply-To: References: Message-ID: <8fd4a2fe0809281718q70f79615l6382249cc124a65d@mail.gmail.com> the spring framework comes to python? http://forum.springframework.org/ http://springpython.webfactional.com/ http://sourceforge.net/projects/springpython/ http://en.wikipedia.org/wiki/Spring_Python On Thu, Sep 25, 2008 at 4:21 AM, Goldfish wrote: > Release 0.7.0 was completed last night, and released to > sourceforge.net. > > NOTE: This release included a lot of API scrubbing, in order to bring > things more in tune with PEP-0008 (python's style guide). You're > existing apps PROBABLY were impacted, if you used any of Spring > Python's utility classes. Since we are pre-1.0, this is the best time > for such a cleanup. When 1.0 hits the streets, we won't make such a > sweeping change without extensive backwards support. > > See [url]http://springpython.webfactional.com[/url] for more > information. > > Visit our community forum at [url]http://forum.springframework.org/ > forumdisplay.php?f=45[/url]for current threads of discussion. > > --Greg Turnquist, Spring Python project lead > ========================================= > Release Notes - Spring Python - Version 0.7 > > > ** Bug > * [SESPRINGPYTHONPY-63] - Running setup.py returns an exception > > ** Improvement > * [SESPRINGPYTHONPY-49] - Upgrade PetClinic to CherryPy 3.1 > * [SESPRINGPYTHONPY-64] - Adding a schema for the regular > component elements > * [SESPRINGPYTHONPY-69] - Remove deprecated connection factories > from baseline > * [SESPRINGPYTHONPY-70] - Scrub function/attribute naming > conventions to more closely follow PEP-0008. > > ** New Feature > * [SESPRINGPYTHONPY-61] - Generate reference documentation for the > project > > ** Refactoring > * [SESPRINGPYTHONPY-65] - Change 'type' attribute in XML > application config to 'scope' to be in line with the lifetime concept > in other Spring platforms > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Americium Dream Documents "(real opportunity starts with real documentation) http://amerdreamdocs.tripod.com/ http://www.angelfire.com/psy/dr.addn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Fri Sep 19 01:24:09 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 19 Sep 2008 05:24:09 GMT Subject: curses.setsyx()? References: Message-ID: linkmaster032000 at gmail.com wrote: > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses >cursor. Any alternatives/solutions? Did you call doupdate after? setsyx just manipulates the data structures. It takes a call to doupdate to force those changes to take effect visually. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From prologic at shortcircuit.net.au Sun Sep 7 17:40:34 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 07:40:34 +1000 Subject: problem with permutations In-Reply-To: References: Message-ID: Hi, Here's a (better?) function: def permutate(seq): if not seq: return [seq] else: temp = [] for k in range(len(seq)): part = seq[:k] + seq[k+1:] for m in permutate(part): temp.append(seq[k:k+1] + m) return temp cheers James On Mon, Sep 8, 2008 at 6:47 AM, cnb wrote: > I am trying to translate this elegant Erlang-code for finding all the > permutations of a list. > I think it is the same function as is but it doesn't work in Python. > -- is upd in Python. It works as it should. > > perms([]) -> [[]]; > perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. > > def perms(lista): > if lista == []: > return [[]] > else: > for h in lista: > return [([h]+[t]) for t in perms(upd(lista, h))] > > def upd(lista, elem, acc=tuple([])): > lista = tuple(lista) > if lista == (): > return list(acc) > if lista[0] == elem: > return list(acc + tuple(lista[1:])) > else: > return upd(lista[1:], elem, acc + tuple([lista[0]])) > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bearophileHUGS at lycos.com Thu Sep 4 16:43:43 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 4 Sep 2008 13:43:43 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: <240454f2-14ee-496a-9078-1abbf80a4e64@m45g2000hsb.googlegroups.com> castironpi: > For max and min, why can't you just add your argument to the set > itself? Sometimes that can be done, but in many other situations it's less easy, like in the example I have shown in my first post: max((fun(x) for x in iterable if predicate(x))) There are some ways to add the max there, for example using an itertools.chain to chan the default value to the end of the iterable, but most of the time I just write a for loop. Bye, bearophile From uzmanajmal at gmail.com Thu Sep 11 03:08:37 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Thu, 11 Sep 2008 07:08:37 +0000 Subject: XML RPC Problem.... Message-ID: Hi everyone, I am trying to call a function named system.auth at the server side running at localhost:8080 but at the same time i want to set the http header. I found that header can be set by h.putheader("AUTHORIZATION", "Basic %s"%encodestring("%s:%s" % (ustring,text_ucert))) #ustring: just a random string #text_ucert: a file containing the X509 certificate of client And i also fount that a typical system.auth call will look like: POST /xmlrpc/clarens_server.py HTTP/1.0 Host: localhost User-Agent: xmlrpclib.py/0.9.9 (by www.pythonware.com) Content-Type: text/xml Content-Length: 105 AUTHORIZATION: Basic MkhVTm9VazYxbXArVEZLS0dCY2tIRlA3bjVzPQo6RnJvbSBi system.auth Problem is that i don't know how do i generate above xml system.auth call. Can anyone please tell me how do call a function, setting the header of the call too? -------------- next part -------------- An HTML attachment was scrubbed... URL: From henrypopie at gmail.com Tue Sep 23 11:56:39 2008 From: henrypopie at gmail.com (henrypopie at gmail.com) Date: Tue, 23 Sep 2008 08:56:39 -0700 (PDT) Subject: download redtube video - Free References: Message-ID: Hello, You can download Redtube videos to your Computer, iPod, PSP or other mobile devices.. Just get a RedTube Downloader from here: -------------------- http://www.downloadvideos-convert.com/redtube-downloader ----------- Enjoy it~ Download Videos from RedTube, YouPorn, PornoTube, XTube, Tube8, Xnxx.com easily, also help you convert videos to any format you want, so you can put RedTube videos on your iPod, PSP or other mobile devices. From movics.org at gmail.com Sun Sep 28 13:32:36 2008 From: movics.org at gmail.com (movics.org) Date: Sun, 28 Sep 2008 10:32:36 -0700 (PDT) Subject: Watch Movies online ! Message-ID: <57e5a1d0-9e3d-47ed-9e61-0fa34672a709@25g2000hsx.googlegroups.com> Hello, I just found a new website : http://www.movics.org Here we can watch any movie for freee...it's a 500 + movies database ...we just have to click on movie we want and we can see it right in our browser. no download is needed ! Good luck :D Your friend TonY! From goldnery at gmail.com Mon Sep 1 17:47:38 2008 From: goldnery at gmail.com (Gandalf) Date: Mon, 1 Sep 2008 14:47:38 -0700 (PDT) Subject: encoding Message-ID: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> if i want to print utf-8 string i should writre: print u"hello word" but what happen if i want to print variable? thank you From john.ford at colorado.edu Thu Sep 25 00:38:36 2008 From: john.ford at colorado.edu (john.ford at colorado.edu) Date: Wed, 24 Sep 2008 21:38:36 -0700 (PDT) Subject: How to parse a string completely into a list References: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> Message-ID: <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> On Sep 24, 10:12?pm, Matt Nordhoff wrote: > john.f... at colorado.edu wrote: > > On Sep 24, 9:44 pm, "Chris Rebert" wrote: > >> On Wed, Sep 24, 2008 at 8:30 PM, ? wrote: > >>> I want to take a long alpha-numeric string with \n and white-space and > >>> place ALL elements of the string (even individual parts of a long > >>> white-space) into separate list elements. The most common way I've > >>> seen this performed is with the split() function, however I don't > >>> believe that it has the power to do what I am looking for. > >>> Any suggestions? > >>> thanks > >> Could you please define exactly what you mean by "elements" of a string? > > >> If you mean characters, then just use list():>>> list(" ?\n \t abc") > > >> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] > > >> Regards, > >> Chris > > > Worked like a charm. > > kudos! > > Why do you need to convert it to a list? Strings are sequences, so you > can do things like slice them or iterate through them by character: > > >>> for character in "foo": > > ... ? ? print character > ... > f > o > o > > -- The string draws a map that I then want to be able to traverse through. If I can count through the individual characters of a list I can create an x-y coordinate plane for navigation. From lists at cheimes.de Mon Sep 1 15:41:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 01 Sep 2008 21:41:09 +0200 Subject: Py 2.6 changes In-Reply-To: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > I presume it's better for me to not hold my breath while I wait > CPython to be written in C99 :-) First you have to convince Microsoft to release C99 compiler ... good luck! Christian From bignose+hates-spam at benfinney.id.au Tue Sep 30 05:04:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 Sep 2008 19:04:41 +1000 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Message-ID: <87zllqqa1i.fsf@benfinney.id.au> Steven D'Aprano writes: > On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: > > > In message , r0g wrote: > > > >> You can only distribute modifications to gnuplot itself as > >> patches, but you can distribute it freely ... [?] > Where's the non-free bit? You're not free to modify gnuplot and redistribute the result. That you're free to distribute patches is nice, but it's not enough to make the work free. The freedom to help people by giving them an *already-modified* gnuplot is restricted by the copyright holder. It's an artificial restriction on redistribution of derived works, making them second-class for the prupose of getting them into people's hands. > Personally, I don't get the whole "only distribute patches" > requirement. It's a bit like saying "You're free to distribute this > software, but only as a tarball". It seems silly to me. That, too, would be a non-free requirement. > But I don't see it as non-free, except in the sense that "only > licences approved by the FSF are free". I try to judge freedom of a software work by the freedoms granted to all recipients of the work, not by the approval of some organisation. -- \ ?When I turned two I was really anxious, because I'd doubled my | `\ age in a year. I thought, if this keeps up, by the time I'm six | _o__) I'll be ninety.? ?Steven Wright | Ben Finney From marek at xivilization.net Wed Sep 3 10:08:50 2008 From: marek at xivilization.net (Marek Kubica) Date: Wed, 3 Sep 2008 14:08:50 +0000 (UTC) Subject: pyparsing: match empty line References: <9f838a29-2e2e-4646-9026-36d3b8a49fce@c58g2000hsc.googlegroups.com> <0df1f752-ee27-4eeb-ab63-1566ed9a3e24@k37g2000hsf.googlegroups.com> Message-ID: On Wed, 03 Sep 2008 06:12:47 -0700, Paul McGuire wrote: > On Sep 3, 4:26 am, Marek Kubica wrote: >> I could set the whitespace >> on every element, but that is as you surely agree quite ugly. Do you >> accept patches? I'm thinking about some kind of factory-class which >> would automatically set the whitespaces: >> >> >>> factory = TokenFactory(' \t\r') >> >>> word = Factory.Word(alphas) >> >> That way, one wouldn't need to set a grobal value which might interfere >> with other pyparsers running in the same process. > > I tried to prototype up your TokenFactory class, but once I got as far > as implementing __getattribute__ to return the corresponding pyparsing > class, I couldn't see how to grab the object generated for that class, > and modify its whitespace values. I have had the same problem, until I remembered that I can fake __init__ using a function closure. I have imported pyparsing.py into a hg repository with a patchstack, here is my first patch: diff -r 12e2bbff259e pyparsing.py --- a/pyparsing.py Wed Sep 03 09:40:09 2008 +0000 +++ b/pyparsing.py Wed Sep 03 14:08:15 2008 +0000 @@ -1400,9 +1400,38 @@ def __req__(self,other): return self == other +class TokenFinder(type): + """Collects all classes that are derived from Token""" + token_classes = dict() + def __init__(cls, name, bases, dict): + # save the class + TokenFinder.token_classes[cls.__name__] = cls + +class WhitespaceTokenFactory(object): + def __init__(self, whitespace): + self._whitespace = whitespace + + def __getattr__(self, name): + """Get an attribute of this class""" + # check whether there is such a Token + if name in TokenFinder.token_classes: + token = TokenFinder.token_classes[name] + # construct a closure which fakes the constructor + def _callable(*args, **kwargs): + obj = token(*args, **kwargs) + # set the whitespace on the token + obj.setWhitespaceChars(self._whitespace) + return obj + # return the function which returns an instance of the Token + return _callable + else: + raise AttributeError("'%s' object has no attribute '%s'" % ( + WhitespaceTokenFactory.__name__, name)) class Token(ParserElement): """Abstract ParserElement subclass, for defining atomic matching patterns.""" + __metaclass__ = TokenFinder + def __init__( self ): I used metaclasses for getting all Token-subclasses so new classes that are created are automatically accessible via the factory, without any additional registration. Oh and yes, more patches will follow. I'm currently editing the second patch, but I better mail it directly to you as it is not really interesting for this list. regards, Marek From kaerbuhez at gmail.com Sun Sep 7 07:16:24 2008 From: kaerbuhez at gmail.com (kaer) Date: Sun, 7 Sep 2008 04:16:24 -0700 (PDT) Subject: unexpected class behaviour References: <48c3ad5d@news.uni-ulm.de> Message-ID: On 7 sep, 12:40, Fredrik Lundh wrote: > Jan Sch?fer wrote: > > can anyone explain the behaviour of the following code sniplet: > > well, it *is* explained in the tutorial, the language reference, and the > FAQ, so yes, it can be explained ;-) > > for more information, see this page: > > http://effbot.org/zone/default-values.htm > > Well, you may want replace the last line by: print ivar, obj, obj.varlist, id(obj.varlist) To have another behavior, you may want replace the 3 first lines by: class Base(object): def __init__( self, lst=None ): if lst is None: lst=[] self.varlist = lst Enjoy Python ! From C.Brewster at dcs.shef.ac.uk Sat Sep 27 10:24:38 2008 From: C.Brewster at dcs.shef.ac.uk (Christopher Brewster) Date: Sat, 27 Sep 2008 15:24:38 +0100 Subject: EPD (Enthought Python Distribution) 4.0.300 Beta 3 available In-Reply-To: <48DDCDDA.50009@enthought.com> References: <48DDCDDA.50009@enthought.com> Message-ID: <975844EF-46F5-439E-8481-544A91EF7A98@dcs.shef.ac.uk> I have always thought this idea very good, but if I download it and install it (on my MacBook pro) will any conflicts occur with existing bits and pieces of Python and its libraries? Thank you, Christopher Brewster ***************************************************** Department of Computer Science, University of Sheffield Regent Court, 211 Portobello Street Sheffield S1 4DP UNITED KINGDOM Web: http://www.dcs.shef.ac.uk/~kiffer/ Tel: +44(0)114-22.21967 Fax: +44 (0)114-22.21810 Skype: christopherbrewster SkypeIn (UK): +44 (20) 8144 0088 SkypeIn (US): +1 (617) 381-4281 ***************************************************** Corruptissima re publica plurimae leges. Tacitus. Annals 3.27 On 27 Sep 2008, at 07:08, Dave Peterson wrote: Hello, We've recently posted the third beta release of EPD (the Enthought Python Distribution) with Python 2.5 version 4.0.300. You may download the beta from here: http://www.enthought.com/products/epdbeta.php Please help us test it out and provide feedback on the EPD Trac instance: https://svn.enthought.com/epd You can check out the release notes here: http://www.enthought.com/products/epdbetareleasenotes.php About EPD --------- The Enthought Python Distribution (EPD) is a "kitchen-sink-included" distribution of the Python? Programming Language, including over 60 additional tools and libraries. The EPD bundle includes NumPy, SciPy, IPython, 2D and 3D visualization, database adapters, and a lot of other tools right out of the box. http://www.enthought.com/products/epd.php It is currently available as a single-click installer for Windows XP (x86), Mac OS X (a universal binary for OS X 10.4 and above), and RedHat 3 and 4 (x86 and amd64). EPD is free for academic use. An annual subscription and installation support are available for individual commercial use. An enterprise subscription with support for particular deployment environments is also available for commercial purchase. The beta versions of EPD are available for indefinite free trial. -- Dave -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html From fredrik at pythonware.com Mon Sep 8 01:07:02 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 07:07:02 +0200 Subject: Subprocess freezes when piping from stdout. In-Reply-To: <62ab6734-a6ab-40c0-9131-a90684674ea6@a18g2000pra.googlegroups.com> References: <62ab6734-a6ab-40c0-9131-a90684674ea6@a18g2000pra.googlegroups.com> Message-ID: James McGill wrote: > Is anyone aware of why this might be occurring, or of any ways around > this? Does the PIPE implementation in Win32 have a maximum buffer > size? pipes always have a limited buffer size, on all platforms. you're supposed to read data from them as it arrives (e.g. by explicitly reading from the "stdout" attribute, or by calling "communicate"). if you cannot do that, bind the channel to a file, not a pipe. From dudeja.rajat at gmail.com Sat Sep 6 09:58:06 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 6 Sep 2008 14:58:06 +0100 Subject: How to bring subprocess to the foreground? Message-ID: Hi, I've a batch file that I open with the subprocess .Popen() . When this batch file is run I want to bring it to the foreground. Please suggest how can I do this? Regards, Rajat From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 06:23:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 12:23:09 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> Message-ID: <48d7720d$0$12866$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: > >> Steven D'Aprano a ?crit : >>> I have a class which is not intended to be instantiated. Instead of >>> using the class to creating an instance and then operate on it, I use >>> the class directly, with classmethods. Essentially, the class is used >>> as a function that keeps state from one call to the next. >>> >>> The problem is that I don't know what to call such a thing! "Abstract >>> class" isn't right, because that implies that you should subclass the >>> class and then instantiate the subclasses. >>> >>> What do you call such a class? >>> >>> >> >> Err... A possible design smell ?-) >> >> >> >> More seriously: this looks quite like a singleton, which in Python is >> usually implemented way more simply using a module and plain functions. > > > I really don't know why everyone thinks I want a Singleton. May I quote you ? """ Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. """ > I want to > uncouple objects, not increase the coupling. > > > Consider a factory function: > > def factory(x): # a toy example > alist = [x] > def foo(): > return alist > return foo > > > Now suppose we "instantiate" the factory (for lack of a better term): > >>>> f1 = factory(0) >>>> f2 = factory(0) > > Even though f1 and f2 have the same behaviour, they are obviously not the > same object. And although both return a list [0], it is not the same list: > >>>> f1() == f2() == [0] > True >>>> f1() is f2() > False > > > They have a (very little) amount of state, which is *not* shared: > >>>> L = f1() >>>> L.append(1) >>>> f1() > [0, 1] >>>> f2() > [0] > > > But there's only a limited amount of state that functions carry around. I > can give them more state like this: > >>>> f1.attr = 'x' > > but it isn't good enough if the function needs to refer to it's own > state, because functions can only refer to themselves by name and the > factory can't know what name the function will be bound to. Then define your own callable type. > As far as I know, the only objects that know how to refer to themselves > no matter what name they have are classes and instances. And instances > share at least some state, by virtue of having the same class. Is that a problem in your use case, and if so, why ??? > (Pedants will argue that classes also share state, by virtue of having > the same metaclass. Maybe so, but that's at a deep enough level that I > don't care.) > > I'm now leaning towards just having factory() instantiate the class and > return the instance, instead of having to do metaclass chicanery. Because > the class is built anew each time by the factory, two such instances > aren't actually sharing the same class. I think that will reduce > confusion all round (including mine!). > > Hopefully now that I've explained what I want in more detail, it won't > seem so bizarre. Factory functions do it all the time. Is there a name > for this pattern? > > Thanks to everyone who commented, your comments helped me reason out a > better alternative to what I first suggested. > Glad to know you found something helpful in all these answers, but as far as I'm concerned, I'm afraid I still fail to understand what exactly you're after... From harrrrpo at gmail.com Sat Sep 6 08:04:27 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sat, 6 Sep 2008 15:04:27 +0300 Subject: Cancel instance create In-Reply-To: References: <1220697080.48c25bf890ade@www.inbox.lv> Message-ID: <538050a90809060504x3b82d402hefbc152c1812d685@mail.gmail.com> ?What about no Constructor , and a custom instancing function that can return either None or the instance wanted From grante at visi.com Wed Sep 10 13:37:28 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 12:37:28 -0500 Subject: md5 differences References: Message-ID: On 2008-09-10, Python wrote: > > On 10 sep 2008, at 18:30, Richard Brodie wrote: > >> >> "Python" wrote in message >> news:mailman.799.1221063937.3487.python-list at python.org... >> >>> here's an example: >>> Arno at Computer:~% echo "hello" | md5 >>> b1946ac92492d2347c6235b4d2611184 >>> How do I get the same results? >> >> Checksum the same string. >> >>>>> md5.new("hello\n").hexdigest() >> 'b1946ac92492d2347c6235b4d2611184' >> >> > > hmm and this then: > > Arno at Computer:~% echo "test" > test.txt > > Arno at Computer:~% md5 test.txt > MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 > > Arno at Computer:~% python > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import md5 > >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() > '90364ed45b452d43378629c20543a81d' That's the digest of the string "/Volumes/data/Arno/test.txt". It's not supposed to match the digest of the string "test\n". >>> md5.new(open("test.txt").read()).hexdigest() 'd8e8fca2dc0f896fd7cb4cb0031ba249' $ md5sum test.txt d8e8fca2dc0f896fd7cb4cb0031ba249 test.txt $ echo "test" | md5sum d8e8fca2dc0f896fd7cb4cb0031ba249 - >>> md5.new("test\n").hexdigest() 'd8e8fca2dc0f896fd7cb4cb0031ba249' > even > echo -n "hello" | md5 > doesn't return the same number Not the same as _what_? >>> md5.new("test").hexdigest() '098f6bcd4621d373cade4e832627b4f6' $ echo -n test | md5sum 098f6bcd4621d373cade4e832627b4f6 - -- Grant Edwards grante Yow! One FISHWICH coming at up!! visi.com From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 12:54:37 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 18:54:37 +0200 Subject: Python newbie question re Strings and integers In-Reply-To: References: Message-ID: <48d546ba$0$17467$426a34cc@news.free.fr> rmac a ?crit : > > the following code attempts to extract a symbol name from a string: > extensionStart = int(filename.rfind('.')) rfind returns an int, so passing it to the int type constructor is useless. > filenameStart = int(filename.rfind('/')) idem > #print 'Extension Start - ' + str(extensionStart) The print statement isn't restricted to string objects. And FWIW, you can use string formating. The above should be either print "Extension start - ", extensionStart or print "Extension start - %s" % extensionStart As a side not, the naming convention in Python is to use all_lower for identifiers. > #print 'FileName Start - ' + str(filenameStart) idem. > currentSymbol=filename[int(filenameStart),int(extensionStart)] Two more useless int constructor calls. > Uncommenting the print statements clearly show the values to be > integers If by 'the values', you mean objects bound to identifiers 'filenameStart' and 'extensionStart', I fail to see how they could be anything else... > (and without the str casts actually provide int+string > errors) Indeed. What should be the semantic of expression 'answer is ' + 42 ??? > However, executing this code results in... > opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv > Traceback (most recent call last): > File "rHistFileToDB_Equities.py", line 25, in > currentSymbol=filename[int(filenameStart),int(extensionStart)] > TypeError: string indices must be integers the expression: int(filenameStart),int(extensionStart) 1/ takes the object currently bound to identifier 'filenameStart' and pass it to the int type constructor 2/ takes the object currently bound to identifier 'extensionStart' and pass it to the int type constructor 3/ build a tuple (actually, a pair of ints) from the results of the two above expressions Then you try to use this tuple as an index on a string. A tuple is not a legal type for string (or any other sequence) subscripting. The complete syntax for string subscripting is described in the FineManual. To make a long story short, it's : string[start:end:step] where end and step are optionals. IOW, the correct syntax here is: filename[filenameStart:extensionStart] Now, while this is the correct *syntax*, it's not the correct *idiom*. There's a module named os.path, which provides the needed service. I leave it up to you to read the relevant part of the documentation... From arvi.blog at gmail.com Mon Sep 8 04:04:44 2008 From: arvi.blog at gmail.com (arvi.blog at gmail.com) Date: Mon, 8 Sep 2008 01:04:44 -0700 (PDT) Subject: Hey guys! Message-ID: <73f8539c-5018-4a43-8b1c-3af21f13afaa@w24g2000prd.googlegroups.com> hey guys! I have this site www.drachensee.info and i keep posting on the ubuntu, the latest open soruce buzz.. i post on stuff like editing the grub menu and other linux related stuff.. so drop in and drop ur comments ;-] From ceball at users.sourceforge.net Thu Sep 11 16:46:57 2008 From: ceball at users.sourceforge.net (Chris) Date: Thu, 11 Sep 2008 20:46:57 +0000 (UTC) Subject: Finding tcltk when building Python on Windows Message-ID: Hi, I'm trying to build Python on Windows using Visual Studio 2005. I have no trouble compiling tcl/tk 8.5, but when I subsequently build Python it doesn't find tcl/tk (I get a message about being unable to find tcl.h). I'm using the source distribution of Python 2.5.2, not the svn version. I'm trying to follow the instructions in PCbuild8/readme.txt, but I'm not sure I understand them correctly. Here is the part of the text that I think I might have misunderstood: """ The following subprojects [including Tkinter] will generally NOT build out of the box. They wrap code Python doesn't control, and you'll need to download the base packages first and unpack them into siblings of PCbuilds's parent directory; for example, if your PCbuild is .......\dist\src\PCbuild\, unpack into new subdirectories of dist\. """ If I have extracted the Python source archive to c:\Python-2.5.2\, then my understanding is that I should extract the tcl and tk source archives to c:\tcl-8.5.4\ and c:\tk-8.5.4\, respectively. Then, when I build and install tcl and tk, their output is c:\tcltk\ (because the instructions say to pass "INSTALLDIR=..\..\tcltk" when building). This is then supposed to be found when I build Python. But tcl/tk isn't found, so I assume I didn't do the right thing here. I feel a bit stupid! I also can't find any explicit instructions for building Python with tcl/tk support using Visual Studio by searching the web. Thanks for any help, Chris From steve at REMOVE-THIS-cybersource.com.au Thu Sep 4 08:27:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 12:27:44 GMT Subject: help in execfile function References: <8a3a0376-7146-44f9-beb6-e1ad7a612ad8@l33g2000pri.googlegroups.com> Message-ID: <00cfcead$0$20302$c3e8da3@news.astraweb.com> On Thu, 04 Sep 2008 05:03:57 -0700, moijes12 wrote: > Hi > > i have 3 python files and i want to execute the files sequentially using > the execfile command.Hence ,i have written the following program > > > fileList = ["a.py","b.py","c.py"] > > for fileName in fileList : > execfile(fileName) > > however,when i try running it,the program keeps calling execfile on a.py > and thus an infinite loop is created.I am running this on Windows XP. Change the line "execfile(fileName)" to "print fileName" and you may discover that the problem isn't with execfile but with your code. Then read about modules and import, and you may discover that there is a better way than execfile. (I wish that eval, exec and execfile were hidden in a module where noobs couldn't trip over them and decide they are the answer to every problem. Sigh.) > Please suggest a sloution whereby i can use execfile to execute all > files in fileList.Please tell me where in my program i may have gone > wrong. Looking into my crystal ball, I'm guessing that file a.py contains a line that says "execfile('a.py')". -- Steven From maric at aristote.info Fri Sep 5 12:37:10 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 18:37:10 +0200 Subject: Retrieving the name of the class calling an instance method In-Reply-To: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> References: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> Message-ID: <200809051837.10926.maric@aristote.info> Le Friday 05 September 2008 17:29:39 mercado mercado, vous avez ?crit?: > In Python, is it possible for an instance method to know the name of the > class which is calling it? For example, in the sample below, I would like > for the someMethod method to print the name of the class calling it ("bar" > in the first case, "again" in the second). Note that "self" for somemethod is just a local variable of the calling function. You cannot retrieve those local variables without playing with the call stack, and this reveal generally a bad design (except for inspection purpose). You have two common solutions here : - the simplest is to pass the instance of bar or again to the foo constructor or as parameter of someMethod, or - attach the foo instance to self in both cases and define a proper __get__ method in foo, this is far more complex and add magic to the foo class, I don't recommand this unless you understand well the descriptor protocol. > > --------------------------------------- > class foo(): > def someMethod(self): > print x > > class bar(): > def __init__(self): > f = foo() > f.someMethod() > > class again(): > def __init__(self): > f = foo() > f.someMethod() > > bar() > again() > --------------------------------------- -- _____________ Maric Michaud From ldo at geek-central.gen.new_zealand Sat Sep 27 00:46:45 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 27 Sep 2008 16:46:45 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: In message , Grant Edwards wrote: > On 2008-09-26, Lawrence D'Oliveiro > wrote: >> In message , Grant Edwards >> wrote: >> >>> Never assume somebody reading the article and attempting to >>> help you can see the subject line. >> >> Why not? > > Because it might not be. It depends on the user's newsreader > and editor settings. So, should I not assume that they can see the content as well, because it might not be visible, depending on the user's newsreader and editor settings? From exarkun at divmod.com Tue Sep 23 09:55:43 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 23 Sep 2008 09:55:43 -0400 Subject: Why no tailcall-optimization? In-Reply-To: <633d90d1-c2e9-45d7-852e-c4f3951656e3@d45g2000hsc.googlegroups.com> Message-ID: <20080923135543.29191.1241898919.divmod.quotient.29959@ohm> On Tue, 23 Sep 2008 06:41:33 -0700 (PDT), sturlamolden wrote: >On Sep 23, 3:13?am, process wrote: > >> Why doesn't Python optimize tailcalls? Are there plans for it? > >Because Python is a dynamic language. While a function is executing, >its name may be bound to another object. It may happen as a side >effect of what the function is doing, or even from another thread. The >compiler has no way of knowing that. That's not the reason. It's not particularly hard to implement TCE for Python. Instead, Guido has repeatedly given the reason as his feeling that recursion is not the most natural way to express most algorithms in Python. Adding TCE to the runtime would encourage people to write (or continue to write) highly recursive algorithms, which would go against what Guido thinks is "Pythonic". Here's a quote from him on the topic: > But I have a problem with tail recursion. It's generally requested by > new converts from the Scheme/Lisp or functional programming world, and > it usually means they haven't figured out yet how to write code > without using recursion for everything yet. IOW I'm doubtful on how > much of a difference it would make for real Python programs (which, > simplifying a bit, tend to use loops instead of recursion). Jean-Paul From bearophileHUGS at lycos.com Fri Sep 5 12:45:37 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 09:45:37 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> Message-ID: <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> Michael Palmer: > why can't it be tuple already? Because if the input list L has tuples and lists, they end having the same hash value: >>> L = [[1,2,3], (1,2,3)] >>> hash(tuple(L[0])), hash(tuple(L[1])) (-378539185, -378539185) But it's a not much common situation, and few hash collision pairs can't damage much, so I agree with you that my assert was useless. This may solve that problem anyway: hash(type(L)) ^ hash(tuple(L)) Generally a good hashing functions uses all the input information. If you use tuple() you ignore part of the input information, that is the type of L. So xor-ing hash(type(L)) you use that information too. > you can discard the tuple, so the memory requirement is transient. Right, but there's lot of GC action, it may slow down the code. So you can start using hash(tuple(L)), but if later the code performance comes out bad, you may try a different version that creates less intermediate garbage. Bye, bearophile From stef.mientki at gmail.com Fri Sep 5 17:33:01 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 05 Sep 2008 23:33:01 +0200 Subject: pdb bug and questions In-Reply-To: References: Message-ID: <48C1A58D.9000201@gmail.com> R. Bernstein wrote: >>> Finally, I think rpdb2 is part of the winpdb project on Sourceforge >>> and again has a bug tracker. My sense is that Nir Aides is very good >>> about handling bugs reported in winpdb/rpdb. >>> >>> >> Yes I started with rpdb2, >> and indeed Nir Aides is very helpfull, >> but I think interfaceing rpdb2 is a little too difficult for me, >> >> I didn't notice your name before, but I must say Rocky Bernstein is also very helpfull ;-) thanks !! For now I'm going to implement a simple interface between my program and any debugger, so I can easily change between the different debuggers. And certainly I've still to read some more docs about the debuggers. cheers, Stef From tino at wildenhain.de Fri Sep 26 07:29:10 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 13:29:10 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: <48DCC786.2040407@wildenhain.de> Hi, Tim Rowe wrote: > 2008/9/23 Craig Allen : > >> So python may turn out to be pure OO ... > The question I usually ask is "Does this language help me get the job > done?" Python often does. That's all that really matters, isn't it? Well then it still depends on the perception of "job done". For example PHP programmers would bet their soul that their language of choice is exactly the right one to "get the job done." :-) You and me would indeed see a different picture on the level of doneness of such jobs ;-) T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From mcrute at gmail.com Sun Sep 28 21:40:07 2008 From: mcrute at gmail.com (Michael Crute) Date: Sun, 28 Sep 2008 21:40:07 -0400 Subject: Web programming in Python. In-Reply-To: References: Message-ID: <558b73fb0809281840h26a2fedl65fa7ed5a7dec2a7@mail.gmail.com> On Sun, Sep 28, 2008 at 6:39 PM, Kurda Yon wrote: > I am totaly newbie in the Python's web programming. So, I dont even > know the basic conceptions (but I have ideas about php-web- > programming). Does it work in a similar way? First, I have to install > a Python-server? There are a couple of different ways to do web development in python. The easiest if you're familiar with web development in other languages is through CGI. I would recommend reading up on the python cgi module [1] which will walk you through the basics of writing your first cgi program. When you're comfortable with basic cgi you might want to look into a framework like Django or CherryPy. -mike [1] http://docs.python.org/lib/module-cgi.html -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From deets at nospam.web.de Mon Sep 8 03:24:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Sep 2008 09:24:48 +0200 Subject: Spotlight Searching in Python - Mac OSX In-Reply-To: <09177d14-a692-4e47-9759-51ad52e38500@s1g2000pra.googlegroups.com> References: <09177d14-a692-4e47-9759-51ad52e38500@s1g2000pra.googlegroups.com> Message-ID: <6ik2a1Fr4kgiU2@mid.uni-berlin.de> cjstevens at gmail.com schrieb: > Hi all, I'm having some issues getting a spotlight search to work > similar to the program demonstrated here: > http://pyobjc.sourceforge.net/examples/pyobjc-framework-Cocoa/AppKit/PredicateEditorSample/ > > > Here is my class, complete with the code I am trying to use it with at > the end. > > > import objc, sys, os, osax, time > from Foundation import * > from ScriptingBridge import * > from appscript import * > > > class SystemBridge(NSObject): > """Class to use the scripting bridge to interact with the system""" > _hideapp = objc.ivar(u"hideapp") > _volume = objc.ivar(u"volume") > _filename = objc.ivar(u"filename") > _filetype = objc.ivar(u"filetype") > _auth = objc.ivar(u"auth") > _logout = objc.ivar(u"logout") > query = objc.ivar(u"query") > StdAdditions = osax.ScriptingAddition() > > def init(self): > super(SystemBridge, self).init() > # create and initalize our query > self.query = NSMetadataQuery.alloc().init() > > # setup our Spotlight notifications > nf = NSNotificationCenter.defaultCenter() > nf.addObserver_selector_name_object_(self, > 'queryNotification:', None, self.query) > > > > # XXX: this framework isn't wrapped yet! > > self.query.setSortDescriptors_([NSSortDescriptor.alloc().initWithKey_ascending_('kMDItemDisplayName', > True)]) > self.query.setDelegate_(self) > > > > return self > > def hideApplication_(self, _hideapp): > app(u'System Events').processes[_hideapp].visible.set(False) > > def loadResultsFromQuery_(self, notif): > results = notif.object().results() > > NSLog("search count = %d", len(results)) > > # iterate through the array of results, and match to the > existing stores > for item in results: > nameStr = item.valueForAttribute_('kMDItemDisplayName') > print nameStr > > > def queryNotification_(self, note): > # the NSMetadataQuery will send back a note when updates are > happening. > # By looking at the [note name], we can tell what is happening > if note.name() == > NSMetadataQueryDidStartGatheringNotification: > # the query has just started > NSLog("search: started gathering") > > > elif note.name() == > NSMetadataQueryDidFinishGatheringNotification: > # at this point, the query will be done. You may recieve > an update > # later on. > NSLog("search: finished gathering"); > self.loadResultsFromQuery_(note) > > elif note.name() == > NSMetadataQueryGatheringProgressNotification: > # the query is still gathering results... > NSLog("search: progressing...") > > elif note.name() == NSMetadataQueryDidUpdateNotification: > # an update will happen when Spotlight notices that a file > as > # added, removed, or modified that affected the search > results. > NSLog("search: an update happened.") > > > def spotlightFriendlyPredicate_(self, predicate): > if predicate == NSPredicate.predicateWithValue_(True) or > predicate == NSPredicate.predicateWithValue_(False): > return False > > elif isinstance(predicate, NSCompoundPredicate): > > type = predicate.compoundPredicateType() > cleanSubpredicates = [] > for dirtySubpredicate in predicate.subpredicates(): > cleanSubpredicate = > self.spotlightFriendlyPredicate_( > dirtySubpredicate) > if cleanSubpredicate: > cleanSubpredicates.append(cleanSubpredicate) > > if len(cleanSubpredicates) == 0: > return None > > else: > if len(cleanSubpredicates) == 1 and type != > NSNotPredicateType: > return cleanSubpredicates[0] > > else: > return > NSCompoundPredicate.alloc().initWithType_subpredicates_(type, > cleanSubpredicates) > > else: > return predicate > > def createNewSearchForPredicate_(self, predicate): > > # Format search file type > thePredicate = NSPredicate.predicateWithFormat_( > "(kMDItemContentType = > 'com.apple.iwork.keynote.key')") > tempPredicate = NSPredicate.predicateWithFormat_( > "(kMDItemDisplayName IN[c] 'preso')") > predicate = NSCompoundPredicate.andPredicateWithSubpredicates_( > [thePredicate, tempPredicate]) > > > self.query.setPredicate_(predicate) > self.query.startQuery() > > > def changeVolume_(self, setvolume): > self.StdAdditions.set_volume(output_volume=setvolume) > > def getVolume_(self): > return StdAdditions.get_volume_settings()[k.output_volume] > > > _x = SystemBridge.alloc().init() > > #predicate = u"kMDItemDisplayName IN[c] 'preso'" > #predicate = _x.spotlightFriendlyPredicate_(predicate) > if predicate is not None: > _x.createNewSearchForPredicate_(predicate) > > > > > As you can see, I am trying to use a notifier just like the example > linked above. The class does not work as expected, and just displays > "search: started gathering", none of the other notifier events happen > at all! > > Have I missed something out translating this to PyObjC? The weird > thing is, most of that code is straight from the example which works > fine, so I can't figure out why mine won't work! Any help would be > hugely appreciated, I need to get this finished soon! I can only imagine that you need an event-loop to make notifications work. That's usually needed under OS X. Diez From fredrik at pythonware.com Wed Sep 10 08:48:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 14:48:08 +0200 Subject: Web shopping carts In-Reply-To: References: <48C7B508.6070006@wildenhain.de> Message-ID: Luke Hamilton wrote: > Do you happen to have anymore details? Google says "Results 1 - 10 of about 869,000 for python shopping cart." http://www.google.com/search?q=python+shopping+cart Checking the first few pages might give you something that fits your requirements (whatever they are). If you don't know what your requirements are, I suggest using something built on top of an established Python web framework, e.g. http://www.satchmoproject.com/ From tino at wildenhain.de Tue Sep 23 12:47:33 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 23 Sep 2008 18:47:33 +0200 Subject: finding domain name In-Reply-To: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> References: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> Message-ID: <48D91DA5.2040207@wildenhain.de> Hi, Bobby Roberts wrote: > On Sep 23, 9:10 am, Tino Wildenhain wrote: >> Bobby Roberts wrote: >>>> Depends on the technology/web framework. If you use WSGI, you should use >>>> something like: >>>> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] >>>> -- Gerhard >>> Yeah i already tried environ("SERVER_NAME") but get a key error when i >>> do. >> You could output the whole environ to see what you get and how it is called. ... > evidently the environ dictionary is off limits on our server. It can't > be that tough in python to get the current complete url being viewed. > It's a snap in asp(which is my background). Its a snap in all python based web apps I ever saw. You didn't tell us what you actually using so we can't say. Also there is no notation of "url beeing viewed" in HTTP if you are looking from server's point of view. There is a request for an URI and a host where the request is directed at then then the server decides to publish a resource based on whatever rules. If that publishing results in a call to your python script (or the script itself is the server) then you would deal with whatever interface API you decided to use gives you. Ah and last not least you can even use python in ASP (look for scripting host) but's not a route to take these days :-) (You really want no inline code but a decent templating engine like PageTemplates (TAL)) Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From Richard_Martineau at xyratex.com Wed Sep 17 06:06:58 2008 From: Richard_Martineau at xyratex.com (Richie) Date: Wed, 17 Sep 2008 03:06:58 -0700 (PDT) Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows References: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Message-ID: On Sep 16, 7:03?pm, Terry Reedy wrote: > Richard_Martin... at xyratex.com wrote: > > Now comes the troubled bit...I now look for similar source code for > > Python extensions Numpy and Scipy but the source code and directories > > are not all obvious. Looks like these are normally built via other > > compilers. However I need to do all my builds in VS 6.0. > > Numpy/scipy specific questions tend to get more specific answers on the > numpy/scipy mailing lists. ?Or see gmane.comp.python.numeric.general at > news.gmane.org Thanks very much for your advice Terry. I've just signed up with Numpy discussion and Scipy dev. Just taking a look at gmane now! Richard From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 18:30:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 22:30:07 GMT Subject: Long lines [was Re: __builtins__ magic behavior] References: Message-ID: <00d45042$0$20306$c3e8da3@news.astraweb.com> Gabriel, could I please ask you to configure your news-reader software or editor to limit the length of each line of your posts to 70 characters wide, as per the common standard for email and Usenet? Your lines are significantly longer than that, including one single line which is 325 characters wide. That forces a lot of backwards and forwards scrolling to read your posts. Thank you. -- Steven From benjamin at dromaludaire.info Wed Sep 17 06:24:10 2008 From: benjamin at dromaludaire.info (Benjamin Sigonneau) Date: Wed, 17 Sep 2008 12:24:10 +0200 Subject: on-the-fly translation with gettext References: <87od2opg5c.fsf@lapinot.localdomain> <9df975ce-058a-40ef-b440-8f7eb2dbaa11@y21g2000hsf.googlegroups.com> Message-ID: <87vdwv9ik5.fsf@lapinot.localdomain> Mike Driscoll writes: > On Sep 16, 4:57?am, Benjamin Sigonneau > wrote: >> Hi all, >> >> I'm a complete beginner in python and in GUI designing, yet I'm writing >> a GUI using python and Tkinter. ?I need it to be available both in french >> and english, so I read the Fine Manual and gave a try to gettext. >> > [...] >> However, I'd like to let the user show the language on-the-fly during >> execution. ?Having read the Python Library Reference, sec. 21.1.3.3 >> (seehttp://docs.python.org/lib/node740.html), I added a menu with two >> radiobuttons and I merely set them up to call install_lang: > > [...] > >> However, there is no magic. ?The language of the application remains >> unchanged. ?If it was defined to be english at startup, so will it >> remain. ?Conversely, it will stay in french if this was the language at >> startup. > > Try moving another window across your application after you change > languages and see if it gets updated. Sometimes you need to refresh > the layout of your application to get it to work...at least, in > wxPython you do. I tried it, but unfortunately my problem remains. Anyway, thanks for the advice. -- benjamin From castironpi at gmail.com Thu Sep 11 13:31:09 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 10:31:09 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <823435cf-a557-48d9-9e16-fa28e745e67a@73g2000hsx.googlegroups.com> Message-ID: <8f9a61c9-55d7-4a1e-a4f1-9dda6a5d2b31@59g2000hsb.googlegroups.com> On Sep 11, 5:35?am, Paul Boddie wrote: > On 11 Sep, 10:34, Fredrik Lundh wrote: > > > > > And as I said before, the only use case for *huge* XML files I've ever > > seen used in practice is to store large streams of record-style data; > > I can imagine that the manipulation of the persistent form of large > graph structures might be another use case, although for efficient > navigation of such a structure, which is what you'd need to start > applying various graph algorithms, one would need some kind of index. > Certainly, we're straying into database territory. > > Paul An acquaintance suggests that defragmentation would be a useful service to provide along with memory management too, which also requires an index. I encourage overlap between a bare-bones alloc/free module and established database territory and I'm very aware of it. Databases already support both concurrency and persistence, but don't tell me you'd use a database for IPC. And don't tell me you've never wished you had a reference to a record in a table so that you could make an update just by changing one word of memory at the right place. Sometimes databases are overkill where all you want is dynamic allocation. From aioe.org at technicalbloke.com Wed Sep 24 21:52:38 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 24 Sep 2008 21:52:38 -0400 Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: Tim Arnold wrote: > I have a bunch of processes to run and each one needs its own working > directory. I'd also like to know when all of the processes are > finished. > > (1) First thought was threads, until I saw that os.chdir was process- > global. > (2) Next thought was fork, but I don't know how to signal when each > child is > finished. > (3) Current thought is to break the process from a method into a > external > script; call the script in separate threads. This is the only way I > can see > to give each process a separate dir (external process fixes that), and > I can > find out when each process is finished (thread fixes that). > > Am I missing something? Is there a better way? I hate to rewrite this > method > as a script since I've got a lot of object metadata that I'll have to > regenerate with each call of the script. > > thanks for any suggestions, > --Tim Arnold (1) + avoid os.chdir and maintain hard paths to all files/folders? or (2) + sockets? or (2) + polling your systems task list? From circularfunc at yahoo.se Tue Sep 2 12:48:32 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 2 Sep 2008 09:48:32 -0700 (PDT) Subject: Large amount of files to parse/organize, tips on algorithm? Message-ID: I have a bunch of files consisting of moviereviews. For each file I construct a list of reviews and then for each new file I merge the reviews so that in the end have a list of reviewers and for each reviewer all their reviews. What is the fastest way to do this? 1. Create one file with reviews, open next file an for each review see if the reviewer exists, then add the review else create new reviewer. 2. create all the separate files with reviews then mergesort them? From skip at pobox.com Sat Sep 13 10:01:22 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Sep 2008 09:01:22 -0500 Subject: A service for testing Python code on multiple platforms and versions In-Reply-To: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> References: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> Message-ID: <18635.51122.545364.467763@montanaro-dyndns-org.local> David> As someone who writes and releases Python modules for the community, I David> find it difficult to have a decent level of confidence in the efficacy David> of my code on platforms and Python versions other than those that I David> own or use regularly. My documentation states that I support Python David> 2.3 or higher. This ends up being more of a statement of good David> intentions than a one of fact. How about Buildbot? Here are some Python examples: http://www.python.org/dev/buildbot/ And the Buildbot home page: http://buildbot.net/trac Skip From dear.jay.logan at gmail.com Mon Sep 1 09:45:06 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 1 Sep 2008 06:45:06 -0700 (PDT) Subject: Eleganz way to get rid of \n References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: <3713087b-01ed-4d78-8d3d-b3df4e305de6@m44g2000hsc.googlegroups.com> On Sep 1, 9:41?am, Wojtek Walczak wrote: > On Mon, 01 Sep 2008 15:25:03 +0200, Hans M?ller wrote: > > I'm quite often using this construct: > > > for l in open("file", "r"): > > ? ?do something > > Has someone a better solution ? > > The most general would be to use rstrip() without > arguments: > > > > >>> a="some string\r\n" > >>> a.rstrip() > 'some string' > > but be careful, because it will also cut whitespaces: > > > > >>> a="some string\t \r\n" > >>> a.rstrip() > 'some string' > > so maybe you could do this: > > > > >>> a.rstrip('\n').rstrip('\r') > 'some string\t ' > > HTH. > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ You can send both '\n' and '\r' in one rstrip call. No need for 2 separate calls. From sturlamolden at yahoo.no Tue Sep 23 14:16:54 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 11:16:54 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: On Sep 23, 5:31?pm, bearophileH... at lycos.com wrote: > Well written C++ code is generally faster or much faster than similar > Python code, but programming in Python is often simpler, and it > generally requires less time. So it may happen that to solve a problem > a Python program that runs in 1 hour that requires 1 hour to be > written allows you to find the solution in less time than a C++ > program that runs in 5-10 minutes that requires you 3-4 hours to be > written :-) I could easily sit down and wait half an hour. I could even wait a week for the calculation to complete. But this is a program that will be used many times, and not just by me. > Note that C++ is just one option, but there are other languages > around, like CLisp or D (or even a modern JavaVM), that are often an > acceptable compromise between Python and C/C++. Yes, if I knew Lisp, I would have used SBCL. Java I can program. But it is a pain in the ass for any scientific programming. F# and OCaml look promising though. > Note that I have written a kd-tree in both Python (with Psyco > compulsively) and D, this is the Psyco version:http://code.activestate.com/recipes/572156/ Sure I could show you the code, Python and C++, if I had a place to post it. It looks very different form yours though. From miki.tebeka at gmail.com Tue Sep 23 04:46:01 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 23 Sep 2008 01:46:01 -0700 (PDT) Subject: Problems running on hp dual core processor References: Message-ID: <352ae1dc-4a4e-4629-89b1-4a4f7d4f5cc2@n33g2000pri.googlegroups.com> Hello, > I have a number of clients running a program built with > python 2.5. ?One has just purchased an HP with a duel > core processor, ?2.2G with .099g ram. > > On the new hp, when they try to print they get an > import error; > File win32ui.pyc line 12, in > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: ?The specified module > could not be found. > > The file is there The only difference I could find from > their other machines is the processor. Is it the same OS (XP vs Vista ...)? Try to run a small script importing win32ui from CMD, it might give you a better indication on which DLL is causing the problem. As suggested by Mike, run DependecyWalker on win32ui.pyd HTH, -- Miki http://pythonwise.blogspot.com From berthold at despammed.com Wed Sep 10 11:11:38 2008 From: berthold at despammed.com (Berthold =?iso-8859-15?Q?H=F6llmann?=) Date: Wed, 10 Sep 2008 17:11:38 +0200 Subject: Refcount problem in ceval.c Message-ID: I have a problem with my debug Python 2.5.2 executable with Py_REF_DEBUG and Py_TRACE_REFS set. With one of my scripts I get: ... Fatal Python error: Python/ceval.c:947 object at 0x2aa3f4d840 has negative ref count -2604246222170760230 Program received signal SIGABRT, Aborted. [Switching to Thread 182905044128 (LWP 2595)] 0x0000002a95dde479 in raise () from /lib64/tls/libc.so.6 (gdb) p ((PyObject*)0x2aa3f4d840)->ob_type $1 = (struct _typeobject *) 0xdbdbdbdbdbdbdbdb (gdb) p ((PyObject*)0x2aa3f4d840)->ob_refcnt $2 = -2604246222170760230 (gdb) p ((PyObject*)0x2aa3f4d840)->_ob_next $3 = (struct _object *) 0xdbdbdbdbdbdbdbdb (gdb) p ((PyObject*)0x2aa3f4d840)->_ob_prev $4 = (struct _object *) 0xdbdbdbdbdbdbdbdb (gdb) Is there any "common" reason to for such a strange object on the command stack, or is it more likely that any of my extension modules is causing havoc? Kind regards Berthold -- __ Address: G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg From ptmcg at austin.rr.com Fri Sep 26 00:32:35 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 25 Sep 2008 21:32:35 -0700 (PDT) Subject: text processing References: Message-ID: On Sep 25, 9:51?am, "jitensha... at gmail.com" wrote: > I have string like follow > 12560/ABC,12567/BC,123,567,890/JK > > I want above string to group like as follow > (12560,ABC) > (12567,BC) > (123,567,890,JK) > > i try regular expression i am able to get first two not the third one. > can regular expression given data in different groups Looks like each item is: - a list of 1 or more integers, in a comma-delimited list - a slash - a word composed of alpha characters And the whole thing is a list of items in a comma-delimited list Now to implement that in pyparsing: >>> data = "12560/ABC,12567/BC,123,567,890/JK" >>> from pyparsing import Suppress, delimitedList, Word, alphas, nums, Group >>> SLASH = Suppress('/') >>> dataitem = delimitedList(Word(nums)) + SLASH + Word(alphas) >>> dataformat = delimitedList(Group(dataitem)) >>> map(tuple, dataformat.parseString(data)) [('12560', 'ABC'), ('12567', 'BC'), ('123', '567', '890', 'JK')] Wah-lah! (as one of my wife's 1st graders announced in one of his school papers) -- Paul From steven at REMOVE.THIS.cybersource.com.au Thu Sep 11 03:40:08 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Sep 2008 07:40:08 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: On Wed, 10 Sep 2008 11:59:35 -0700, Aaron \"Castironpi\" Brady wrote: > On Sep 10, 5:24?am, Steven D'Aprano > wrote: >> On Wed, 10 Sep 2008 09:26:20 +0200, Fredrik Lundh wrote: >> > Steven D'Aprano wrote: >> >> >> You've created a solution to a problem which (probably) only affects >> >> a very small number of people, at least judging by your use-cases. >> >> Who has a 4GB XML file >> >> > Getting 4GB XML files from, say, logging processes or databases that >> > can render their output as XML is not that uncommon. ?They're usually >> > record-oriented, and are intended to be processed as streams. ?And >> > given the right tools, doing that is no harder than doing the same to >> > a 4GB text file. >> >> Fair enough, that's a good point. >> >> But would you expect random access to a 4GB XML file? If I've >> understood what Castironpi is trying for, his primary use case was for >> people wanting exactly that. >> >> -- >> Steven > > Steven, > > Are you claiming that sequential storage is sufficient for small amounts > of data, and relational db.s are necessary for large amounts? I'm no longer *claiming* anything, I'm *asking* whether random access to a 4GB XML file is something that is credible or useful. It is my understanding that XML is particularly ill-suited to random access once the amount of data is too large to fit in RAM. I'm interested in what Fredrik has to say about this, as he's the author of ElementTree. -- Steven From darcy at druid.net Mon Sep 29 13:31:53 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 29 Sep 2008 13:31:53 -0400 Subject: PYTHON WORKING WITH PERL ?? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> Message-ID: <20080929133153.fc745f9c.darcy@druid.net> On Mon, 29 Sep 2008 13:16:14 -0400 "Blubaugh, David A." wrote: > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? Such as > utilizing python for internet programming and then utilize perl for text > processing and systems programming? Is this even feasible??? I don't see why not but I also question if it is a good idea. Once you have all your objects and low level methods written in Python it just makes sense to re-use them rather than trying to duplicate the functionality in another language. Of course, sometimes we don't have control over our entire environment so yes, you can mix them if you have to. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From karentataka at gmail.com Sun Sep 21 00:04:45 2008 From: karentataka at gmail.com (karentataka at gmail.com) Date: Sat, 20 Sep 2008 21:04:45 -0700 (PDT) Subject: Quick & Secured Pharmacy Online. bhsrf Message-ID: <8d7b9685-ad62-456b-8e86-8b7a32abed79@f36g2000hsa.googlegroups.com> Start saving, best online pharmacy here http://gjlabeh.cuchezfarg.com/?cdfikmabehxwvrsygzchcmjl From digitig at gmail.com Mon Sep 22 07:04:50 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 22 Sep 2008 12:04:50 +0100 Subject: What do you call a class not intended to be instantiated In-Reply-To: <48d7720d$0$12866$426a34cc@news.free.fr> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <48d7720d$0$12866$426a34cc@news.free.fr> Message-ID: 2008/9/22 Bruno Desthuilliers : > Steven D'Aprano a ?crit : >> >> On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: >> >>> Steven D'Aprano a ?crit : >>>> >>>> I have a class which is not intended to be instantiated. Instead of >>>> using the class to creating an instance and then operate on it, I use >>>> the class directly, with classmethods. Essentially, the class is used >>>> as a function that keeps state from one call to the next. Sounds to me like a functor, aka a function object: http://en.wikipedia.org/wiki/Function_object -- Tim Rowe From tino at wildenhain.de Sat Sep 27 17:30:43 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 27 Sep 2008 23:30:43 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> References: <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> Message-ID: <48DEA603.9020507@wildenhain.de> Hi, Michael Mabin wrote: > If the inputs are edited prior to the construction of the string and > these fields are used for more than one update then it's not an exploit. > It's simply a matter not repeating yourself when coding. In python we do not fear that. > In this particular case too, we're talking about a list of integers that > gets inserted into a string. If the list is validated prior to its Its a list, if it indeed has integers in it is uncertain. It is so very easy to check that that it doesnt even make sense to write such lengthy emails about how bad you want to avoid it. Just do it. And even more so if you are telling others how to do things make sure they do not so easy shoot themselfes in their feet. > insertion into an SQL statement then there is no exploit. If I write a > batch program (not a web program) that retrieves this list of integers > from other sources and validates the data prior to using it in an SQL > statement, that should be sufficient. This might be well true but if you have a look at your original contribution you see that all these your asumtions are just not in. > As far as wrong and right is concerned. I think it's more about doing > what is appropriate according to the circumstances. As a rule you If its easy to do, why not just doing it correctly (or robust) in all circumstances to just avoid overlooking a case? > should only code what is appropriate for the circumstances. If it's > appropriate to code more simply without introducing unnecessary > complexity you should do so. But you did not tell us about your asumtations about the circumstances. > I work in the data warehousing ETL world, where we have to perform field > edits or transformations to load source data into databases. If I'm Thats wrong. You do not "edit" fields. You have a validating type path and _always_ the database is most authoritative about what it accepts. Any other concept is just wrong and outright dangerous. There are many examples of how this works out (just check bugtraq) > already performing edits on these fields and if these fields are going > to be used for more updates downstream, it's wasteful to perform them > again when I build the SQL insert with the list and execute it. I still don't know what you mean by "edit" ;) If you mean filter out special chars with for example replace("bad stuff","good stuff") check your idea again, this is not going to work. (google for default permit) > Finally, whatever happened to the practice of granting appropriate > privileges to IDs that perform database operations? Shouldn't the > person acting in the capacity of DBA ensure that the user updating or > retrieving data from the database does not have DROP, ALTER, or CREATE > privileges on that database? This of course is another layer which should be added - but you would not need to - you edited the fields, right? ;) Sorry, it was not meant to put you to the wall but you insist so much on your still dangerous solution while top posting the hell out of this thread I just could not ignore it ;) T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From martin at v.loewis.de Sat Sep 20 09:05:38 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 20 Sep 2008 15:05:38 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <48D4F522.3080309@v.loewis.de> > for-in could be a useful addition to Python? looks like Guido's used > his time machine again, then, since it's been around since the pre-1.0 > days: > > http://www.python.org/doc/ref/for.html He somehow must have misinterpreted http://www.astro.ufl.edu/~warner/prog/python.html which has the exact text he quoted. Unfortunately, this text has foreach in bold, so he might have assumed foreach to be a keyword (despite the example to the right demonstrating the contrary). What this has to do with OO, or with numpy, is beyond me. Regards, Martin From python.list at tim.thechases.com Sat Sep 13 13:09:56 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 13 Sep 2008 12:09:56 -0500 Subject: Unable to see os.environ['COLUMNS'] Message-ID: <48CBF3E4.8070307@tim.thechases.com> Not sure what's going on here and hoping for some insight: tim at rubbish:~$ echo $COLUMNS 129 tim at rubbish:~$ python2.5 Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ.get('COLUMNS') >>> 'COLUMNS' in os.environ False I can coerce it by using tim at rubbish:~$ COLUMNS=$COLUMNS python2.5 Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> 'COLUMNS' in os.environ True However, this seems hokey to me. FWIW, this is in Bash on Debian. What's the best way to read what seems to be a pseudo-environment variable? -tkc From half.italian at gmail.com Tue Sep 16 03:43:58 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 16 Sep 2008 00:43:58 -0700 (PDT) Subject: The need to use *arg,**kwd References: Message-ID: <9d602aae-dc90-41b3-8c57-1ffa9619c69c@x16g2000prn.googlegroups.com> On Sep 15, 11:54?pm, "Marco Bizzarri" wrote: > On Mon, Sep 15, 2008 at 11:51 PM, AON LAZIO wrote: > > Hi, Pythoners. > > ? ? ? ?I'd like to know when it is necessary to use *arg or **kwd in the > > program. And when it is 'ok' to use normal form of function argument? > > Thanks in advance. > > > Aonlazio > > Sorry, Aonlazio, but which program? This is a fair generic question > which needs a little more details to be answered. > > You are not required to use them. You can use them if problem can be > easily solved with them. Which, of course leads to the questionof what > your problem is ;) > > Regards > Marco > -- > Marco Bizzarrihttp://notenotturne.blogspot.com/http://iliveinpisa.blogspot.com/ Aonlazio, *args and **kwargs are both a conveneince and for situations where the function could take a variable number of arguments. Take for example a sum function: def sum(first, second): return first + second This function can only take two arguments and return the result of the two. You can add more arguments to the function definition, but if you want to make a generic sum function, it should be able to take as many arguments as your user wants to throw at it. In this case you can use *args. ie. def sum(*args): total =0 for arg in args: total += arg return total **kwargs works the same way, but for keyword arguments. I can't think of a useful example...I tried. :) I'm sure others will have good use cases. ~Sean From steve at REMOVE-THIS-cybersource.com.au Fri Sep 12 08:29:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Sep 2008 12:29:12 GMT Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> Message-ID: <00da5aca$0$2879$c3e8da3@news.astraweb.com> On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote: > When mail messages bounce, the MTA (Message Transfer Agent--the program > that handles mail) *should* send the bounce message to whatever is in > the Sender header, and only if that header does not exist, should it use > the From header. Who makes up these rules, and why should we pay the least bit of attention to them? It's one thing to say "right or wrong, that's what list admins do and you have to deal with their behaviour whatever way you can". It's another thing altogether to take the legalistic attitude of "never mind the consequences, the standard is the standard and must be unthinkingly obeyed". If the standard does more harm than good, then ignoring the standard is the right thing to do. (Better would be to change the standard, but that probably won't happen until there's a critical mass of people who ignore the existing broken standard and form their own de facto standard.) A standard isn't "correct" just because it's a standard, it's merely something that a committee has agreed to do. In other words, it's a compromise. Now, such compromises might be good and useful, or they might combine the worst of all opinions. Just because something is standardized doesn't make it the right thing to do. If you want proof of this, I give you the recently approved ISO standard for Microsoft's so-called "Office Open XML" OOXML file format. The standard behaviour of sending bounce and out-of-office messages to the sender works well when sending email to individuals, but for mailing lists it is pointless and counter-productive. Pointless, because the sender can't do anything to fix the problem he's being notified about. And counter-productive, because it is an anti-feature, something that makes the mailing list more unpleasant and less useful. Anyone who has regularly emailed to a large mailing list has surely experienced the frustration of receiving bounce messages from perfect strangers. To anyone who wishes to defend the process of sending mailing list bounces back the sender, ask yourself this: what do YOU do with such bounces when you receive them? If you ignore them or delete them (whether manually or via a procmail recipe or some other automatic system) then what benefit does the standard behaviour offer? -- Steven From torriem at gmail.com Tue Sep 30 15:53:47 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 30 Sep 2008 13:53:47 -0600 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38053D9A26@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38053D9A26@AWMAIL04.belcan.com> Message-ID: <48E283CB.6060309@gmail.com> Blubaugh, David A. wrote: > Thank You!! > > I am still new to Python!! > > David Blubaugh As you've already noticed, plenty of folks here on the list are ready help you out with issues the crop up as you learn python. So keep on asking questions as you need assistance. In the future, please avoid using all-capital letters and superfluous exclamation marks in the subject line as this comes across in the parlance of nntp- and mailing- list etiquette as yelling. If you don't get any replies to your posts, please just be patient and the gurus will get to them eventually. I have found this list to be extremely good that way, and almost all my questions have been politely answered, even if it took a few days. I hope you continue to find your python learning experience to be fun and profitable. From circularfunc at gmail.com Wed Sep 10 06:17:30 2008 From: circularfunc at gmail.com (process) Date: Wed, 10 Sep 2008 03:17:30 -0700 (PDT) Subject: which of these 2 quicksorts is faster? Message-ID: qsort can handle bigger lists it seems, making less recursive calls before finishing(quicksort blows the stack when sorting range(100,-1000,-1). qsort does more work though right? is there a way to speed up that? is the built-in sort not defined recursively? def quicksort(lista): if len(lista) != 0: return quicksort([x for x in lista[1:] if x < lista[0]]) + [lista[0]] + \ quicksort([x for x in lista[1:] if x >= lista[0]]) else: return [] def qsort(lista): l = len(lista) if len(lista) != 0: return qsort([x for x in lista[:l/2]+lista[l/2+1:] if x < lista[l/2]]) + \ [lista[l/2]] + \ qsort([x for x in lista[:l/2]+lista[l/2+1:] if x >= lista[l/2]]) else: return [] From deets at nospam.web.de Thu Sep 18 05:08:17 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Sep 2008 11:08:17 +0200 Subject: how to do easy_install to source code, not egg? References: <499dc07d-261e-4c34-9743-28b55c7945bd@a70g2000hsh.googlegroups.com> Message-ID: <6jek4aF2v55pU1@mid.uni-berlin.de> dmitrey wrote: > Hi all, > how to do easy_install to source code, not egg? > > (I don't mean "develop" option, it shouldn't call compiled egg-file). $ easy_install --help --editable (-e) Install specified packages in editable form You additionally need to give the -b-option, like this: $ easy_install -eb . FooBar Diez From fredrik at pythonware.com Sat Sep 13 04:47:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 10:47:45 +0200 Subject: book example confusion In-Reply-To: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: byron wrote: > Being that each function is an object, a name assignment to > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > the name is called.. the above would be true if the code had been tmp1, tmp2 = f1, f2 but it isn't. look again. From gminick at bzt.bzt Thu Sep 4 14:09:14 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 4 Sep 2008 18:09:14 +0000 (UTC) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> Message-ID: On Thu, 4 Sep 2008 10:57:35 -0700 (PDT), Mensanator wrote: > Why then, doesn't > >>>> sum([A for A in [None, None, None, None, None, None] if A != None]) > 0 > > give me an error? Because "[A for A in [None, None, None, None, None, None] if A != None]" returns an empty list, and sum([]) doesn't return an error. What did you expect? -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From http Fri Sep 19 02:10:31 2008 From: http (Paul Rubin) Date: 18 Sep 2008 23:10:31 -0700 Subject: dict generator question References: Message-ID: <7xy71o4qeg.fsf@ruckus.brouhaha.com> "Simon Mullis" writes: > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > ... > dict_of_counts = dict([(v[0:3], "count") for v in l]) Untested: def major_version(version_string): "convert '1.2.3.2' to '1.2'" return '.'.join(version_string.split('.')[:2]) dict_of_counts = defaultdict(int) for x in l: dict_of_counts[major_version(l)] += 1 From mathieu.prevot at gmail.com Wed Sep 24 12:44:22 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Wed, 24 Sep 2008 18:44:22 +0200 Subject: how to build a MacOS universal python package including external dependencies In-Reply-To: References: Message-ID: <3e473cc60809240944h1ea69275jc066fc957869d8f2@mail.gmail.com> 2008/9/24 Jaime Huerta Cepas : > Hi all, > > I have developed a set python libraries that provide several scientific > methods to analyse and visualize certain type of biological data. This > libraries are based on many external python modules, such as python-mysql > python-sip or python-qt4. I use GNU/linux to develop my tools and I found no > problems into installing all dependencies, however it does not seem to be > that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 , > mysqldb, scipy, numpy) are cross platform, but when you are trying to > publish your tool in an academic journal, most referees (many of them using > MacOS) expect some kind of straightforward installation process for the > tool. > > I wonder if there would be a way in which I could compile all the > dependencies and libraries in a MacOs system and then building a static > universal binary that I can distribute. I guess it should be possible, but > I am not sure how difficult it might be, and whether all dependencies (qt4 > is huge) can be packaged together. IMHO this is too complex to commit. Macport is a way to do what you want, but packages may not be up to date enough. Maybe the easiest and simplest way for you to do this is to write a script that will download, compile and install everything. The script should work like: sudo all_in_one_script.py and then wait for jobs to be done. Your script will need to know if a package was sucessfully installed and then continue or take steps and say it. For a complex set of dependencies, I recommend you to write Makefiles. For instance, in pseudo-code: if /usr/local/lib/libfoo.dylib doesn't exist download foo install foo if python-module foo doesn't exist download foo python foo/setup.py install etc HTH Mathieu From casey.mcginty at gmail.com Mon Sep 15 16:40:47 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 15 Sep 2008 10:40:47 -1000 Subject: Getting Linux partition info programmatically In-Reply-To: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> References: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> Message-ID: You might want to take a look at HAL (hardware extraction layer) and DBUS. freedesktop.org - Software/hal HAL 0.5.10 Specification Dbus Tutorial -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Mon Sep 22 03:41:07 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Sep 2008 00:41:07 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: On 22 Sep, 04:05, josh logan wrote: > Hello, > > I have 2 questions. Say I have this class: > > class Player(object): > def __init__(self, fname, lname, score): > self.score = score > self.fname = fname > self.lname = lname > def __cmp__(self, other): > return (-cmp(self.score, other.score) or > cmp(self.lname, other.lname) or > cmp(self.fname, other.fname)) > def __repr__(self): > return 'Player(fname={0.fname}, lname={0.lname}, > score={0.score})'.format(self) > def __eq__(self, others): > if isinstance(other, Player): > return (self.score == other.score and > self.lname == other.lname and > self.fname == other.fname) > return False > def __ne__(self, others): > return not self.__eq__(others) > > fnames = ['Julie', 'Ben', 'Jason', 'David'] > lnames = ['Parks', 'Smith'] > scores = [100, 95, 95, 130, 58, 74] > > import itertools as it > > score_iter = it.cycle(scores) > > P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in > lnames] > > cmp(P[0], P[1]) # returns -1 > > sorted(P) # throws TypeError: unorderable types Player() < Player() > > The sorted function works when I define __lt__. > I must be misreading the documentation, because I read for the > documentation __cmp__ that it is called if none of the other rich > comparison functions are defined. > Is this a bug in Python 3.0rc1, or am I missing something? > > Secondly, say that we suddenly need another sorting order, where we > want to sort by decreasing score and then by DECREASING last name > (instead of increasing last name, defined above). Now that the > comparison function argument is taken away from the sorted builtin, > how do we accomplish this with the "key" parameter? > > Thank you I don't know about __cmp__ but for the second part of the question you can probably do: sorted(P, key=lambda p: (p.score, p.lname), reverse=True) HTH -- Arnaud From circularfunc at gmail.com Tue Sep 23 08:58:25 2008 From: circularfunc at gmail.com (process) Date: Tue, 23 Sep 2008 05:58:25 -0700 (PDT) Subject: Pyflix, confused about super() call Message-ID: Anyone using Pyflix for the Netflix prize. How can it call super to itself in its init-method? --------------------- #!/usr/bin/env python '''Sample baseline averaging algorithms.''' import numpy as N from pyflix.algorithms import Algorithm class MovieAverage(Algorithm): '''Baseline algorithm that computes the average of all the votes for a movie and predicts that for every user. This algorithm returns an RMSE score of 1.0528 on the scrubbed dataset. ''' def __init__(self, training_set): self._movie_averages = {} super(MovieAverage,self).__init__(training_set) def __call__(self, movie_id, user_id): try: return self._movie_averages[movie_id] except KeyError: avg = N.average(self._training_set.movie(movie_id).ratings()) self._movie_averages[movie_id] = avg return avg class UserAverage(Algorithm): '''Baseline algorithm that computes the average of all the votes for a user and predicts that for every movie. This algorithm returns an RMSE score of 1.0688 on the scrubbed dataset. ''' def __init__(self, training_set): self._user_averages = {} super(UserAverage,self).__init__(training_set) def __call__(self, movie_id, user_id): try: return self._user_averages[user_id] except KeyError: avg = N.average(self._training_set.user(user_id).ratings()) self._user_averages[user_id] = avg return avg class DoubleAverage(MovieAverage,UserAverage): '''Returns the average of L{MovieAverage} and L{UserAverage}. This algorithm returns an RMSE score of 1.0158 on the scrubbed dataset. ''' def __call__(self, movie_id, user_id): return (MovieAverage.__call__(self,movie_id,user_id) + UserAverage.__call__(self,movie_id,user_id)) / 2 From tjreedy at udel.edu Wed Sep 10 18:36:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 18:36:46 -0400 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: Mensanator wrote: > Are there situations where the sum of an empty > list should NOT be 0? Of course there are. Python Philosopy (my version, for this discussion): Make normal things easy; make unusual or difficult things possible. Application: Sum([]) == 0 is normal (90+% of cases). Make that easy (as it is). For anything else: if seq: s = sum(s, base) else: which is certainly pretty easy. > Can sum() handle those cases? The developers choose what they thought would be most useful across the spectrum of programmers and programs after some non-zero amount of debate and discussion. > No, it can't, I have to write > my own definition if I want that behaviour. Or wrap your calls. In any case, before sum was added as a convenience for summing numbers, *everyone* has to write their own or use reduce. Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be the most common use of reduce. Sum(s,start) replaces the much less common reduce(lambda x,y: x+y, s, start). Reduce(S, s), where S = sum function, raises an exception on empty s. So use that and you are no worse off than before. However, a problem with reduce(S,s) is that it is *almost* the same as reduce(S,s,0). So people are sometimes tempted to omit 0, especially if they are not sure if the call might be reduce(S,0,s) (as one argument says it should be -- but that is another post). But if they do, the program fails, even if it should not, if and when s happens to be empty. > There's no reason > why sum([]) and sum([],0) have to mean the same thing at the > exclusion of a perfectly valid alternative definition. 'Have to', no reason. 'Should', yes there are at least three reasons. 1. Python functions generally return an answer rather than raise an exception where there is a perfectly valid answer to return. 2. As a general principle, something that is almost always true should not need to be stated over and over again. This is why, for instance, we have default args. 3. As I remember, part of the reason for adding sum was to eliminate the need (with reduce) to explicitly say 'start my sum at 0' in order to avoid buggy code. In other words, I believe part of the reason for sum's existence is to avoid the very bug-inviting behavior you want. Terry Jan Reedy From castironpi at gmail.com Wed Sep 17 19:09:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 17 Sep 2008 16:09:41 -0700 (PDT) Subject: decorator and API References: Message-ID: <160e332b-3b46-4a9f-957b-0eb8199ed3d7@8g2000hse.googlegroups.com> On Sep 17, 4:56?pm, Lee Harr wrote: > I have a class with certain methods from which I want to select > one at random, with weighting. > > The way I have done it is this .... > > import random > > def weight(value): > ? ? def set_weight(method): > ? ? ? ? method.weight = value > ? ? ? ? return method > ? ? return set_weight > > class A(object): > ? ? def actions(self): > ? ? ? ? 'return a list of possible actions' > > ? ? ? ? return [getattr(self, method) > ? ? ? ? ? ? ? ? ? ? for method in dir(self) > ? ? ? ? ? ? ? ? ? ? if method.startswith('action_')] > > ? ? def action(self): > ? ? ? ? 'Select a possible action using weighted choice' > > ? ? ? ? actions = self.actions() > ? ? ? ? weights = [method.weight for method in actions] > ? ? ? ? total = sum(weights) > > ? ? ? ? choice = random.randrange(total) > > ? ? ? ? while choice> weights[0]: > ? ? ? ? ? ? choice -= weights[0] > ? ? ? ? ? ? weights.pop(0) > ? ? ? ? ? ? actions.pop(0) > > ? ? ? ? return actions[0] > > ? ? @weight(10) > ? ? def action_1(self): > ? ? ? ? print "A.action_1" > > ? ? @weight(20) > ? ? def action_2(self): > ? ? ? ? print "A.action_2" > > a = A() > a.action()() > > The problem I have now is that if I subclass A and want to > change the weighting of one of the methods, I am not sure > how to do that. > > One idea I had was to override the method using the new > weight in the decorator, and then call the original method: > > class B(A): > ? ? @weight(50) > ? ? def action_1(self): > ? ? ? ? A.action_1(self) > > That works, but it feels messy. > > Another idea was to store the weightings as a dictionary > on each instance, but I could not see how to update that > from a decorator. > > I like the idea of having the weights in a dictionary, so I > am looking for a better API, or a way to re-weight the > methods using a decorator. > > Any suggestions appreciated. > > _________________________________________________________________ > Explore the seven wonders of the worldhttp://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE What about a function, 'reweight', which wraps the original, and sets a weight on the wrapper? def reweight(value): def reset_weight(method): #@wraps(method) #optional def new_method( *ar, **kw ): return method( *ar, **kw ) new_method.weight = value return new_method return reset_weight Call like this: class B(A): action_1= reweight( 50 )( A.action_1 ) You could pass them both in to reweight with two parameters: class B(A): action_1= reweight( 50, A.action_1 ) It's about the same. Variable-signature functions have limits. Otherwise, you can keep dictionaries by name, and checking membership in them in superclasses that have them by hand. Then you'd need a consistent name for the dictionary. That option looks like this (unproduced): class A: __weights__= {} @weight( __weights__, 10 ) ... @weight( __weights__, 20 ) ... class B( A ): __weights__= {} #new instance so you don't change the original @weight( __weights__, 50 ) ... B.__weight__ could be an object that knows what it's overriding (unproduced): class A: weights= WeightOb() #just a dictionary, mostly @weights( 10 ) ... @weights( 20 ) ... class B( A ): weights= WeightOb( A.weights ) #new, refs "super-member" @weights( 50 ) ... If either of the last two options look promising, I think I can produce the WeightOb class. It has a '__call__' method. From andyhume at gmail.com Mon Sep 8 16:12:03 2008 From: andyhume at gmail.com (andyhume at gmail.com) Date: Mon, 8 Sep 2008 13:12:03 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <6d1f32aa-0740-4513-9d9e-f48ddf92435b@z72g2000hsb.googlegroups.com> On Sep 8, 10:20?am, John Machin wrote: > On Sep 8, 10:47?am, MK Bernard wrote: > > > > > On Sep 7, 3:37?pm, John Machin wrote: > > > > On Sep 8, 7:51?am, "andyh... at gmail.com" wrote: > > > > > Hello... > > > > > I have a dict of key/values and I want to change the keys in it, based > > > > on another mapping dictionary. An example follows: > > > > > MAPPING_DICT = { > > > > ? ? 'a': 'A', > > > > ? ? 'b': 'B', > > > > > } > > > > > my_dict = { > > > > ? ? 'a': '1', > > > > ? ? 'b': '2' > > > > > } > > > > > I want the finished my_dict to look like: > > > > > my_dict = { > > > > ? ? 'A': '1', > > > > ? ? 'B': '2' > > > > > } > > > > > Whereby the keys in the original my_dict have been swapped out for the > > > > keys mapped in MAPPING_DICT. > > > > > Is there a clever way to do this, or should I loop through both, > > > > essentially creating a brand new dict? > > > > Is this homework? > > > > There seems to be an implicit assumption in the answers so far that > > > your mapping is a 1:1 mapping of all possible input keys. > > > > If it doesn't include all possible input keys, answers will crash with > > > a KeyError. If there are any many:1 elements in the mapping (for > > > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > > > in some checks for this. > > > Thats exactly why I did an explicit check in my post, so as to make > > sure that such a collision could not occur. It would seem that > > something along what I posted would be safer, if less elegant, than > > the others. > > I noted two problems: > (1) not covering all input keys: your code explicitly sweeps this > problem under the carpet, and does it laboriously ... > ? ? if x in my_dict.keys(): > instead of > ? ? if x in my_dict: > (2) not a 1:1 mapping -- for example, 'a' and 'b' both map to 'A' (the > only "collision" that I can see), but you don't address that. > > Here's some code which attempts to cover the bases: > > new_dict = {} > for key in my_dict: > ? ? if key not in MAPPING_DICT: > ? ? ? ? raise NoMapError('blah %r' % key) > ? ? else: > ? ? ? ? new_key = MAPPING_DICT[key] > ? ? if new_key in new_dict: > ? ? ? ? raise ManyToOneError('gurgle %r waffle %r' % (key, new_key)) > ? ? else: > ? ? ? ? new_dict[new_key] = my_dict[key] > > Having considered what is actually required under the checked-for > conditions, one or both raise statements may be replaced by other > code, and then simplified e.g. the first 4 lines in the loop may end > up being replaced by > ? ? new_key = MAPPING_DICT.get(key, key) > as already suggested by one respondent. > > Note that useful use-cases for any variety of this key-change exercise > may have many more items in MAPPING_DICT than there are in my_dict (a > big language dictionary and a few fragments of text to be > "translated"), or vice versa (a small synonym dictionary (color -> > colour, center -> centre) and a big input to be "standardised") so > it's a good idea to inquire which is likely to be the smaller and > iterate over that if the requirements permit it. In the interests of academia (although this isn't homework :)) I'll answer some of those questions: - Yes, the mapping dict doesn't necessarily have the same number of entries as the my_dict. It may have less than it or more than it. - There will never be dupes of key or value in the mapping. Though there maybe in my_dict. And, for extra credit, it may be useful to be able to 'translate' the my_dict back again using the same mapping_dict. ie, using the values in mapping dict as the new keys in my_dict, and the keys as the new values. Andy. From dullrich at sprynet.com Tue Sep 9 11:58:49 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 09 Sep 2008 10:58:49 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <00d1d60c$0$20302$c3e8da3@news.astraweb.com> Message-ID: In article <00d1d60c$0$20302$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Fri, 05 Sep 2008 10:22:22 -0500, David C. Ullrich wrote about why max > and min shouldn't accept a default argument: > > > Think about all the previously elected female or black presidents of the > > US. Which one was the tallest? > > I know the answer to that one: > > All of them! Heh. Mysteries of the empty set. -- David C. Ullrich From lists at cheimes.de Tue Sep 16 07:38:49 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Sep 2008 13:38:49 +0200 Subject: Mysqldb and Python 3000 In-Reply-To: <48CF7BA8.6060809@gmx.de> References: <48CF7BA8.6060809@gmx.de> Message-ID: Andreas Kalsch wrote: > Hi, > > how do I connect the easiest way to MySQL with Python 3000? I don't want > to get any trouble and install current MySQLdb, which is supported up to > Python 2.5. Use Python 2.5 if you don't want any trouble. It's going to take several months to years until most libraries support Python 3.0. Christian From simon at brunningonline.net Wed Sep 17 08:41:39 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 17 Sep 2008 13:41:39 +0100 Subject: recursive using the os.walk(path) from the os module In-Reply-To: References: Message-ID: <8c7f10c60809170541p6a743e71ldf7dbb6b474ae8fc@mail.gmail.com> 2008/9/17 A. Joseph : > I want to search through a directory and re-arrange all the files into e.g > > All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder. > > I`m thinking of doing something with the os.walk(path) method from os > module, I need some ideal how the algorithm should look like, maybe > recursive ..any deal? This help? http://code.activestate.com/recipes/499305/ -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From gagsl-py2 at yahoo.com.ar Fri Sep 19 11:25:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 12:25:09 -0300 Subject: Deflate with urllib2... (solved) References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> Message-ID: En Thu, 18 Sep 2008 23:29:30 -0300, Sam escribi?: > On Sep 18, 2:10?pm, "Gabriel Genellina" > wrote: >> En Tue, 16 Sep 2008 21:58:31 -0300, Sam escribi?: >> The code is correct - try with another server. I tested it with a ? >> LightHTTPd server and worked fine. > > Gabriel... > > I found a bunch of servers to test it on. It fails on every server I > could find (sans one). > > Here's the ones it fails on: > slashdot.org > hotmail.com > godaddy.com > linux.com > lighttpd.net > > I did manage to find one webserver it succeeded on---that is > kenrockwel.com --- a domain squatter with a typoed domain of one of my > favorite photographer's websites (the actual website should be > kenrockwell.com) > > This squatter's site is indeed running lighttpd---but it appears to be > an earlier version, because the official lighttpd site fails on this > test. > > We have all the major web servers failing the test: > * Apache 1.3 > * Apache 2.2 > * Microsoft-IIS/6.0 > * lighttpd/1.5.0 > > So I think it's the python side that is wrong, regardless of what the > standard is. I've found the problem. The zlib header is missing (2 bytes), data begins right with the compressed stream. You may decode it if you pass a negative value for wsize: try: data = zlib.decompress(data) except zlib.error: data = zlib.decompress(data, -zlib.MAX_WBITS) Note that this is clearly in violation of RFC 1950: the header is *not* optional. BTW, the curl developers had this same problem some time ago and the proposed solution is the same as above. This is the output from your test script modified as above. (Note that in some cases, the compressed stream is larger than the uncompressed data): Trying: http://slashdot.org http://slashdot.org - Apache/1.3.41 (Unix) mod_perl/1.31-rc4 (deflate) len(def late)=73174 len(gzip)=73208 Able to decompress...went from 73174 to 73073. Trying: http://www.hotmail.com http://www.hotmail.com - Microsoft-IIS/6.0 (deflate) len(deflate)=1609 len(gzi p)=1635 Able to decompress...went from 1609 to 3969. Trying: http://www.godaddy.com http://www.godaddy.com - Microsoft-IIS/6.0 (deflate) len(deflate)=40646 len(gz ip)=157141 Able to decompress...went from 40646 to 157141. Trying: http://www.linux.com http://www.linux.com - Apache/2.2.8 (Unix) PHP/5.2.5 (deflate) len(deflate)=52 862 len(gzip)=52880 Able to decompress...went from 52862 to 52786. Trying: http://www.lighttpd.net http://www.lighttpd.net - lighttpd/1.5.0 (deflate) len(deflate)=5669 len(gzip) =5687 Able to decompress...went from 5669 to 15746. Trying: http://www.kenrockwel.com http://www.kenrockwel.com - lighttpd (deflate) len(deflate)=414 len(gzip)=426 Able to decompress...went from 414 to 744. -- Gabriel Genellina From jeff at jmcneil.net Wed Sep 3 15:01:20 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 3 Sep 2008 12:01:20 -0700 (PDT) Subject: Looking for File comparison utility that produces actual differences References: Message-ID: On Sep 3, 2:40 pm, dudeja.ra... at gmail.com wrote: > Hi, > > I looking for a file comparison utility in Python that works like > 'diff' command in Unix and 'comp' in Windows. > The present 'cmd' in filecmp module only presents output in the form > of 1 or 0 i.e whether the 2 files differ or not? > > So, I'm lookin for something that generates actual differences and > moreover it is cross platform as well. As I need that same thing in > both my windows and linux box. > > Even if it is a utlility please suggest. > > Thanks and regards, > Rajat What about the difflib module? [jeff at marvin test]$ cat file_one abcd 1234 - [jeff at marvin test]$ cat file_two abcd 12345 - [jeff at marvin test]$ [jeff at marvin test]$ python Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11) [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import difflib >>> for i in difflib.context_diff(open("file_one").readlines(), open("file_two").readlines()): ... print i, ... *** --- *************** *** 1,3 **** abcd ! 1234 - --- 1,3 ---- abcd ! 12345 - >>> Also, see http://docs.python.org/lib/module-difflib.html. -Jeff From blabla at dungeon.de Fri Sep 26 13:41:40 2008 From: blabla at dungeon.de (hofer) Date: Fri, 26 Sep 2008 10:41:40 -0700 (PDT) Subject: Understanding (and getting rid) of optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a References: <85ec721a-b5a2-4f22-9e37-bda4a0f9eb81@z72g2000hsb.googlegroups.com> Message-ID: <816326c3-1f07-442d-9370-46346505c3b7@k13g2000hse.googlegroups.com> On Sep 26, 6:21?pm, Peter Otten <__pete... at web.de> wrote: > hofer wrote: > > Hi, > > > I get following warning with a python script: > > > optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will > > return a signed string in Python 2.4 and up > > You can print options.__dict__ instead of options with little loss of > information, or turn the warning off > > python -Wignore::FutureWarning myscript.py > > Peter Thanks a lot Peter, Any trick to disable warnings just for a given range of code? bye H From wuwei23 at gmail.com Sun Sep 28 20:57:07 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 28 Sep 2008 17:57:07 -0700 (PDT) Subject: Odd Errors References: <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> <1b1ed34d-f386-4389-a7f1-ce68be4e2a14@k30g2000hse.googlegroups.com> Message-ID: "Aaron \"Castironpi\" Brady" wrote: > Do you ever want to scream from the rooftops, "'append' operates by > side-effect!"? "I'm mad as hell, and I'm not going to mutate in-place anymore!" From paul at boddie.org.uk Sat Sep 6 13:53:58 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 6 Sep 2008 10:53:58 -0700 (PDT) Subject: How to bring subprocess to the foreground? References: <6ifhg2Fq24n6U1@mid.uni-berlin.de> Message-ID: <1563bbfd-6219-4719-940f-91cd84c419e5@l42g2000hsc.googlegroups.com> On 6 Sep, 17:58, dudeja.ra... at gmail.com wrote: > > I though of displayin an information message on the screen through > tkMessageBox while the subprocess is running, I did it using: > > try: > testing = subprocess.Popen([batchFilePath], \ > shell = True) > > retCode = testing.wait() Note that you wait for the process to finish here... > tkMessageBox._show("Test Harness execution", \ > icon = 'info', \ > message="Testing %s in progress..." % libName) ...and that you show a message about the process running *after* waiting until it isn't running any more. > except: > tkMessageBox._show("Error", \ > type='ok', icon='error', \ > message="Error executing %s Test > Harness" % libName) > return None > else: > print retCode > > But the message is never displayed. Please suggest if there is > something wrong with this code I think you should first show your message, *then* wait for the process to finish. Paul From castironpi at gmail.com Tue Sep 23 20:08:20 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 17:08:20 -0700 (PDT) Subject: Visualize class inheritance hierarchy References: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Message-ID: On Sep 23, 5:53?pm, Rob Kirkpatrick wrote: > Hi All, > > I just finished debugging some code where I needed to determine why > one subclass had a bound method and another did not. ?They had > different pedigree's but I didn't know immediately what the > differences were. > > I ended up walking the hierarchy, going back one class at a time > through the code, for the two subclasses (hierarchy ~7 classes deep > each) to see whom they inherited from. ?Short of writing this down on > paper, is there any way to graphically display the pedigree of an > object/class? ?"Graphically" can be text output to the terminal, don't > need anything special... > > I'm assuming this has been discussed before, but I'm lacking any > Google keywords that bring up the appropriate discussion. > > Cheers, > Rob Compare their __mro__ members if they are new-style. The depth-first search for the member you're looking for is straightforward in Python, even if maybe not immediately obvious. If not, we can try a settrace and a search for when they are defined, and build an __mro__ manually. From akineko at gmail.com Mon Sep 1 18:58:36 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 15:58:36 -0700 (PDT) Subject: Tkinter after() under VMware player Message-ID: Hi everyone, I wrote a Tkinter program that has a blinking widget. The blinking is controlled by the after() method available in the Tkinter. It worked very nicely. However, when I tried the program with a Unix OS that is running under VMware (hosted OS), I noticed the blinking rate is greatly reduced (1/2 ~ 1/4). It seems that the VMware is distributing the CPU time slot and after() is not correctly recognizing the situation. My laptop has a dual core CPU but I think my VMware (player) setting only utilizes one CPU. I know the time period of after() is not accurate but this is too inacurate. I'm wondering what is the best way to deal with this kind of situation. Any suggestion will be highly appreciated. Best regards, Aki- From half.italian at gmail.com Sat Sep 27 19:37:57 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sat, 27 Sep 2008 16:37:57 -0700 (PDT) Subject: check if file is MS Word or PDF file References: <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> Message-ID: <5f11d0f5-772e-4089-84b4-071df2a89c5e@w39g2000prb.googlegroups.com> On Sep 27, 4:01?pm, "Chris Rebert" wrote: > On Sat, Sep 27, 2008 at 3:42 PM, Michael Crute wrote: > > On Sat, Sep 27, 2008 at 5:43 PM, A. Joseph wrote: > >> What should I look for in a file to determine whether or not it is a > >> MS Word file or an Excel file or a PDF file, etc., etc.? including Zip > >> files > > >> I don`t want to check for file extension. > >> os.path.splitext('Filename.jpg') will produce a tuple of filename and > >> extension, but some file don`t even have extension and can still be read by > >> MS Word or NotePad. i want to be 100% sure of the file. > > > You could use the mimetypes module... > > > <<< import mimetypes > > <<< mimetypes.guess_type("LegalNotices.pdf") > >>>> ('application/pdf', None) > > Looking at the docs for the mimetypes module, it just guesses based on > the filename (and extension), not the actual contents of the file, so > it doesn't really help the OP, who wants to make sure their program > isn't misled by an inaccurate extension. > > Regards, > Chris > -- > Follow the path of the Iguana...http://rebertia.com > > > > > -mike > > > -- > > ________________________________ > > Michael E. Crute > >http://mike.crute.org > > > God put me on this earth to accomplish a certain number of things. > > Right now I am so far behind that I will never die. --Bill Watterson > > -- > >http://mail.python.org/mailman/listinfo/python-list Check http://sourceforge.net/project/showfiles.php?group_id=23617 for the 'file' command for Windows. ~Sean From gh at ghaering.de Mon Sep 8 04:12:50 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 08 Sep 2008 10:12:50 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: <6ii9jbFqoe2eU1@mid.uni-berlin.de> References: <6ii9jbFqoe2eU1@mid.uni-berlin.de> Message-ID: Matthias Huening wrote: > Hi, > >> - - Connection.enable_load_extension(enabled) to allow/disallow extension >> loading. Allows you to use fulltext search extension, for example ;-) > > The following code (from the docs) produces an error: > > from pysqlite2 import dbapi2 as sqlite3 > con = sqlite3.connect(":memory:") > # Load the fulltext search extension > con.enable_load_extension(True) > con.execute("select load_extension('./fts3.so')") > con.enable_load_extension(False) > > > Error is: > > con.execute("select load_extension('./fts3.so')") > pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht > gefunden. > > Where should I look for the module? The sources are in ext/fts3 in the SQLite source tree. I haven't found any Makefile, so I it myself using this gcc command: $ cd .../ext/fts3 $ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so *.c -lsqlite3 -- Gerhard From research at johnohagan.com Wed Sep 17 07:06:01 2008 From: research at johnohagan.com (John O'Hagan) Date: Wed, 17 Sep 2008 11:06:01 +0000 Subject: Use of generators and efficiency Message-ID: <200809171106.01782.research@johnohagan.com> Hi, I'm writing a Python program using combinatorial algorithms to generate music. It originally was of this general form: First, a combinatorial function producing a list of sub-lists, then: For each sub-list in the list: Filter/modifier A, then append modified sub-list to new list, For each sublist in new list: Filter/modifier B, then append modified sub-list to new list, ......and so on for C, D,etc. Finally, for each sub-list in the final list, output the sub-list (print/play as notes). Because some of the combinatorial operations were slow to produce results, I changed the program to be of the form: A combinatorial generator producing one small list for each call, then: Filter/modify list through A,B, etc Output the modified list Call the generator for next list. To my great surprise, this approach was often considerably _slower_ to complete than the original program (up to ~40% depending on which modifiers were used), despite producing initial results more quickly. Some possibly relevant details: each sub-list consists of a short sequence of small numbers representing musical notes, but there may be millions of them; the modifiers range from simple tests (e.g., " if len(sub-list) is not n: continue" ) to relatively elaborate rearrangements and transformations. My question is, how can it be quicker to unpack and rebuild a list for each modifier, than than to run all modifications on each element in turn? Any explanations, comments or advice? Thanks, John O'Hagan From jcd at sdf.lonestar.org Thu Sep 18 10:25:07 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 18 Sep 2008 10:25:07 -0400 Subject: improving a huge double-for cycle In-Reply-To: <48D2502C.4000200@tim.thechases.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D2502C.4000200@tim.thechases.com> Message-ID: <1221747907.6982.3.camel@aalcdl07.lib.unc.edu> On Thu, 2008-09-18 at 07:57 -0500, Tim Chase wrote: > > Code: Select all > > for i in range(len(IN)): #scan all elements of the list IN > > for j in range(len(IN)): > > if i <> j: > > if IN[i].coordinates[0] == IN[j].coordinates[0]: > > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > SN.append(IN[i].label) > > > > > Such changes might look something like > > for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): > if IN[i].coordinates == IN[j].coordinates: > SN.append(IN[i].label) If you aren't checking j values less than i, you might want to do both SN.append(IN[i].label) SN.append(IN[j].label) on the same pass. > If my college algorithms memory serves me sufficiently, this > reduces your O(N^2) to O(N log N) which will garner you some > decent time savings. > > -tkc > > > -- > http://mail.python.org/mailman/listinfo/python-list > From a at nospam.org Tue Sep 16 08:23:25 2008 From: a at nospam.org (Armin) Date: Tue, 16 Sep 2008 14:23:25 +0200 Subject: append on lists In-Reply-To: <1221564169.16690.0@proxy00.news.clara.net> References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <1221564169.16690.0@proxy00.news.clara.net> Message-ID: Alex Marandon wrote: > Armin wrote: >> Duncan Booth wrote: >> >> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c >> (with c = [8,9]) is identical, > > No it's not, + doesn't alter its operands. > > >>> a = 1 > >>> b = 2 > >>> a + b > 3 That's not the point :) What's the value of 1.add(b)? None? Or 3 ?? (if add works in the same way as append) a + b doesn't change a,b ... but a.add(b) -> a=3 From pruebauno at latinmail.com Thu Sep 18 11:43:02 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 18 Sep 2008 08:43:02 -0700 (PDT) Subject: dict generator question References: Message-ID: On Sep 18, 10:54 am, "Simon Mullis" wrote: > Hi, > > Let's say I have an arbitrary list of minor software versions of an > imaginary software product: > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > I'd like to create a dict with major_version : count. > > (So, in this case: > > dict_of_counts = { "1.1" : "1", > "1.2" : "2", > "1.3" : "2" } > > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. > > I'm most probably not thinking pythonically enough... (I know I could > do this pretty easily with a couple more lines, but I'd like to > understand if there's a way to use a dict generator for this). > > Thanks in advance > > SM > > -- > Simon Mullis Considering 3 identical "simultpost" solutions I'd say: "one obvious way to do it" FTW :-) From ptmcg at austin.rr.com Tue Sep 16 08:28:34 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 16 Sep 2008 05:28:34 -0700 (PDT) Subject: What is "finally:" for? References: Message-ID: <502e16a8-e20d-4795-a495-ce1f61fd8c15@m44g2000hsc.googlegroups.com> On Sep 16, 6:25?am, "Max Ivanov" wrote: > Hi all! > When and where I should use try-except-finally statement? What is the > difference between: > -------- > try: > ? A... > except: > ? B.... > finally: > ? C... > -------- > > and > ------- > try: > ? A... > except: > ? B.... > C... If B raises or rethrows another exception, finally: ensures that C still gets called. In the second form that you give, C would not get called. Here is one way to use try-except-finally: try: open database do database stuff except DatabaseException, de: log exception throw finally: close database Or try: transaction = new database transaction do database stuff do more database stuff commit transaction transaction = None except DatabaseException, de: log exception throw finally: if transaction: rollback transaction If you are allocating a resource, lock, file, database, etc., then exception-safe coding style is to get the resource in a try: and release the resource in finally: -- Paul From bearophileHUGS at lycos.com Wed Sep 3 18:02:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 15:02:09 -0700 (PDT) Subject: Python on JavaScript VM's (such as V8)? References: <1926ef1e-2c5e-4ef6-8a33-b360b02520a7@b38g2000prf.googlegroups.com> Message-ID: <31ea0481-bc7d-476e-92ce-df28b86eed11@o40g2000prn.googlegroups.com> Berco Beute: > I wonder what it would take to implement Python in JavaScript so it > can run on those fancy new JavaScript VM's such as Chrome's V8 or > Firefox' tracemonkey. Much the same as Python implementations in C# > (IronPython) and Java (Jython). It would certainly bring back the fun > in web application development. Is there anything done in that > direction? The mythical beast pypy is supposed able to translate Python to Javascript too, I think. From some of my benchmarks Chrome's V8 is a little slower than Psyco... so the matter is how much efficiently can be Python translated in JS. Bye, bearophile From gnewsg at gmail.com Thu Sep 4 07:28:28 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 4 Sep 2008 04:28:28 -0700 (PDT) Subject: Safely move an element into a heap Message-ID: Hi, I wanted to know if does exist a safe way to, given a heap, move an arbitrary element to the first position of the heap. Something like: >>> heap = [0,3,6,8,10] >>> heapq.move_to_first_position(heap, 4) >>> heap = [10, 0,3,6,8] --- Giampaolo http://code.google.com/p/pyftpdlib/ From nick at craig-wood.com Tue Sep 2 07:35:41 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 02 Sep 2008 06:35:41 -0500 Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Ben Finney: > > I don't see any good reason (other than your familiarity with the D > > language) to use underscores for this purpose, and much more reason > > (readability, consistency, fewer arbitrary differences in syntax, > > perhaps simpler implementation) to use whitespace just as with string > > literals. > > It's not just my familiarity, Ada language too uses underscore for > that purpose, I think, so there's a precedent, and Ada is a language > designed to always minimize programming errors, simple code mistakes > too. And perl also *ducks* -- Nick Craig-Wood -- http://www.craig-wood.com/nick From BjornSteinarFjeldPettersen at gmail.com Wed Sep 10 15:23:01 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Wed, 10 Sep 2008 12:23:01 -0700 (PDT) Subject: Is there a SOAP module that can do this...? Message-ID: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> I've been trying to use SOAPpy and ZSI (with and without the use of wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic server(?) in front of some enterprise java bean) and not having much luck. I got them to send me an example of what the bytes on the wire are supposed to look like (attached below), and I got it to "work" by going lo-tech: cn = httplib.HTTPSConnection('test.xx.no',443) cn.putrequest("POST", "/service/url") cn.putheader("Host", "test.xx.no") cn.putheader("Content-type", 'text/xml; charset="UTF-8"') cn.putheader("Content-length", "%d" % len(soap_message)) cn.putheader("SOAPAction", '""') cn.endheaders() cn.send(soap_message) Is there a better way to do this? Can it be done with any of the Python SOAP libraries? Bjorn soap message follows:
y111 y222 x111 x222 Submitter x111 Registrator y111 ccd6dc26-836f-4768-8d28-5d46a872b9e8 x444 appendMessage ccd6dc26-836f-4768-8d28-5d46a872b9e8 23.09.2006 3 BBB CCC DDD 9999 12345678 a at b.no ]]> From gagsl-py2 at yahoo.com.ar Fri Sep 5 00:43:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 01:43:06 -0300 Subject: Curious: 2134 2004-10-06 08:55:20Z fredrik References: Message-ID: En Fri, 05 Sep 2008 00:13:28 -0300, Akathorn Greyhat escribi?: > I had an import error and I get this error: > Traceback (most recent call last): > File "C:\Eclipse\pyworkspace\CodenameRazor0.2\src\app.py", line 11, in > > import core > File "C:\Python25\lib\site-packages\PIL\__init__.py", line 3, in > > # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ > ImportError: No module named data > > I've already fix it, but I don't know what the hell does this line means: > > # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ > It seens curious, isn't it? I'd say the import mechanism got confused about the actual source of the error. Probably it happened on line 3 in *another* module, but the traceback got messed. Perhaps "core" is a package and contains "import data" at line 3? The $Id: stuff comes from some version control system -probably svn- and identifies the file version. -- Gabriel Genellina From ldo at geek-central.gen.new_zealand Mon Sep 29 05:11:19 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:11:19 +1300 Subject: how to replace and string in a "SELECT ... IN ()" References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> Message-ID: In message , D'Arcy J.M. Cain wrote: > On Fri, 26 Sep 2008 11:00:59 -0500 > "Michael Mabin" wrote: > >> So we can drop a table in an in clause? How is this a use case. >> Cartoons are funny but actual proof that this example using an in-clause >> provides an exploit would be more helpful I think. > > I'm not sure what proof you require. I would say Mr Mabin is displaying thinking characteristic of a PHP programmer . :) From steve at REMOVE-THIS-cybersource.com.au Sun Sep 14 16:25:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Sep 2008 20:25:18 GMT Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> Message-ID: <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> On Sun, 14 Sep 2008 12:15:04 -0700, Gary Herron wrote: > (If you wish to consider the base class "abstract", just agree with > yourself to not instantiate it.) That's certainly the most lightweight option. > Please forget about Abstract Base Classes. They have nothing to do with > what you want, and are a *HUGE* overkill for your application. They > are not (yet) even part of standard Python, and are used primarily for a > class implementor to guarantee to a user of a class that it provides a > specific interface. You can implement a lightweight abstract base class in Python fairly easily, by adding two lines to the __init__ method of your base class. class Base(object): def __init__(self): if self.__class__ is Base: raise NotImplementedError("Abstract base class") def method(self, *args): return len(args) # or something useful If you want to get fancy, you can define a custom exception instead of using NotImplementedError. And that's about all you need. You can get more complicated if you want, but why bother? If I may be excused a slight digression, I don't get the "abstract" part of ABCs. The prohibition against instantiating them just seems very artificial, I don't see what benefit it gets you. Wikipedia says: "The fact that many languages disallow instantiation of abstract types (and force subtypes to implement all needed functionality) further ensures program correctness." http://en.wikipedia.org/wiki/Abstract_base_class but I don't see how that follows (except possibly in very special cases). Given that the set of instances of class B is empty, how does that help you know that B.method is correct? -- Steven From karl.kobata at syncira.com Tue Sep 16 15:48:51 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Tue, 16 Sep 2008 12:48:51 -0700 Subject: ka-ping yee tokenizer.py In-Reply-To: Message-ID: <6gvfio$7rldo3@rrcs-agw-01.hrndva.rr.com> Hi Fredrik, This is exactly what I need. Thank you. I would like to do one additional function. I am not using the tokenizer to parse python code. It happens to work very well for my application. However, I would like either or both of the following variance: 1) I would like to add 2 other characters as comment designation 2) write a module that can readline, modify the line as required, and finally, this module can be used as the argument for the tokenizer. Def modifyLine( fileHandle ): # readline and modify this string if required ... For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ): Print token Anxiously looking forward to your thoughts. karl -----Original Message----- From: python-list-bounces+kkobata=syncira.com at python.org [mailto:python-list-bounces+kkobata=syncira.com at python.org] On Behalf Of Fredrik Lundh Sent: Monday, September 15, 2008 2:04 PM To: python-list at python.org Subject: Re: ka-ping yee tokenizer.py Karl Kobata wrote: > I have enjoyed using ka-ping yee's tokenizer.py. I would like to > replace the readline parameter input with my own and pass a list of > strings to the tokenizer. I understand it must be a callable object and > iteratable but it is obvious with errors I am getting, that this is not > the only functions required. not sure I can decipher your detailed requirements, but to use Python's standard "tokenize" module (written by ping) on a list, you can simple do as follows: import tokenize program = [ ... program given as list ... ] for token in tokenize.generate_tokens(iter(program).next): print token another approach is to turn the list back into a string, and wrap that in a StringIO object: import tokenize import StringIO program = [ ... program given as list ... ] program_buffer = StringIO.StringIO("".join(program)) for token in tokenize.generate_tokens(program_buffer.readline): print token -- http://mail.python.org/mailman/listinfo/python-list From robert.kern at gmail.com Wed Sep 3 15:47:13 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 Sep 2008 14:47:13 -0500 Subject: Is try-except slow? In-Reply-To: References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote: > >> ssecorp wrote: >>> or why does this take so god damn long time? >> Several reasons. One of which is that try: except: is slow. > > > I beg to differ. Setting up a try...except block is very fast. Here's an > example in Python 2.5: > > >>>> from timeit import Timer >>>> Timer('len("abc")').repeat() > [0.27346706390380859, 0.1530919075012207, 0.14886784553527832] >>>> Timer('''try: > ... len("abc") > ... except: > ... pass > ... ''').repeat() > [0.27847194671630859, 0.19191384315490723, 0.19077491760253906] > > The difference (approx 0.04 microseconds) applicable to setting up the > try...except block is trivial, of the same magnitude as a pass statement: > >>>> Timer('pass').repeat() > [0.059719085693359375, 0.060056924819946289, 0.059512138366699219] > > > However, *catching* the exception may be relatively slow: > >>>> Timer('''try: > ... len(abc) # raise a NameError > ... except: > ... pass > ... ''').repeat() > [3.2067418098449707, 2.7088210582733154, 1.9558219909667969] You're right. My mistake. I was misremembering Guido's old essay about try: except: versus if: else:. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Tue Sep 9 14:58:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Sep 2008 11:58:48 -0700 (PDT) Subject: check if the values are prensent in a list of values References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> Message-ID: <23f71a56-d838-4e08-b73c-de34b4b79f5b@79g2000hsk.googlegroups.com> On Sep 9, 2:04 pm, flit wrote: > Hello All, > > I will appreciate the help from the more skillfull pythonistas.. > > I have a small app that generates a sequence like > > 00341 > 01741 > 03254 > > This values I am putting in a list. > > So I have a list = [00341,01741,03254] > > after the programs find the sequence 03401 this sequence is "new" so > it appends on the list. But I want to avoid that as the values are > already on the first sequence of the list (00341). > If I try to use a "in" statement it will give false. as 00341 is > different from 00341 (but for my goal not..) > > How can I check against this list and avoid to put "different" > sequences but same values? > > as 34100 --> dont append on the list > 14300 ---> dont append on the list > 05321 --> append to the list. > > Am I doing some conceptual error using lists? > There is a better approach? Whenever you want to keep track of unique values, think of using a set or dict, not list. Since you don't care about the character order within each string, sort the characters so that two strings are equivalent if and only if their sorted character lists are equal. One more thing to bear in mind is that the elements of a set (or the keys of a dict) have to be hashable. Lists are not hashable so there needs to be an extra step to convert the sorted list into an "equivalent" hashable object. A common choice that works for any list [*] is to convert it to a tuple. An alternative that works for strings only is to join() them into a single string: >>> values = '00341 01741 03254 34100 14300 05321'.split() >>> set(''.join(sorted(v)) for v in values) set(['01235', '00134', '01147', '02345']) HTH, George [*] Assuming that every element of the list is hashable. From woaibeiyang at hotmail.com Tue Sep 2 22:36:56 2008 From: woaibeiyang at hotmail.com (woaibeiyang) Date: Wed, 3 Sep 2008 10:36:56 +0800 Subject: about downloading the selected information References: Message-ID: Thanks a lot! "woaibeiyang" ????????????:g9jcmv$h9p$1 at news.cn99.com... >I have a problem to download the information from url >http://www.ncbi.nlm.nih.gov/sites/entrez. Because it is impossible for me >to add searching material to the url to construct a new url and then visit >the website. > I have the searching material, however I could not find the way to deal > with this problem. I want to know how can I do this problem with python > and which part of knowledge should I view first? Thanks! > From circularfunc at gmail.com Sun Sep 28 14:29:42 2008 From: circularfunc at gmail.com (process) Date: Sun, 28 Sep 2008 11:29:42 -0700 (PDT) Subject: What is not objects in Python? Message-ID: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> I have heard some criticism about Python, that it is not fully object- oriented. What is not an object in Python? Why isn't len implemented as a str.len and list.len method instead of a len(list) function? From workitharder at gmail.com Thu Sep 4 15:38:45 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 4 Sep 2008 12:38:45 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> Message-ID: > > I'd like to be able to do something like this: > > class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ..., > > VanillaCursor): pass > > Why does it have to look like that? ?A good programmer lets the code > look however it has to look to most effectively do it's job. > > With a proxy, the "base class" isn't a base class but a member. ?Here > is a very simple example: > > class SuperCursor(object): > ? ? def __init__(self): > ? ? ? ? self._cursor = VanillaCursor() > ? ? ? ? self._connected = False > ? ? def __getattr__(self,attr): > ? ? ? ? if not self._connected: > ? ? ? ? ? ? self._cursor.connect() > ? ? ? ? ? ? self._connected = True > ? ? ? ? return getattr(self._cursor,attr) > > cursor = SuperCursor() > > That doesn't use a mixin, but why should it? The point of using a mixin is to not limit myself to inheriting from VanillaCursor. I want to put this on top of various subclasses of the vanilla cursor, like TimeLimitedCursor or RetryingCursor. I have four other mixins that operate this way, so it's desirable to keep this one in line with that. From gagsl-py2 at yahoo.com.ar Tue Sep 30 04:05:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 05:05:55 -0300 Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: En Tue, 30 Sep 2008 01:03:07 -0300, namekuseijin escribi?: > On 28 set, 15:29, process wrote: >> Why isn't len implemented as a str.len and list.len method instead of >> a len(list) function? > > Because postfix notation sucks. The natural way of spelling is > adjective+noun and verb+predicate. That's one of the reasons I like > Lisp better than Python. Well, "natural" for English-speaking people... Noun+adjective is usually more "natural" In Spanish than the English word ordering. Back to the original question, len(x) allows for a fast response without paying the overhead of a name lookup and then a method call. len(some_list) doesn't invoke some_list.__len__(), it just returns the value stored somewhere in the list object; same for other built-in objects. __len__ is searched as a last resort only. The optimization could not be done if it were spelled x.len() -- Gabriel Genellina From hypercaffeinatedbiped at gmail.com Mon Sep 29 09:12:35 2008 From: hypercaffeinatedbiped at gmail.com (HCB) Date: Mon, 29 Sep 2008 06:12:35 -0700 (PDT) Subject: One class per file? Message-ID: Hello: The book "Code Complete" recommends that you put only one class in a source file, which seems a bit extreme for me. It seems that many classes are small, so that putting several of them in a file seems reasonable. I noticed that the decimal.py module in the standard library has several classes, all of which of course revolve around the "decimal" topic. Perhaps a better rule of thumb is "one idea per file." I checked the Python style guide and there seems to be no mention of this topic. I know this is an elementary question, but what is the Python way of doing this? Thanks for your time. HCB From pavlovevidence at gmail.com Fri Sep 5 15:19:25 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 5 Sep 2008 12:19:25 -0700 (PDT) Subject: "Full" element tag listing possible with Elementtree? References: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Message-ID: <5e374e5f-40d9-44f4-9c7b-a44106da71e2@e39g2000hsf.googlegroups.com> On Sep 5, 2:27 am, jaime.dy... at gmail.com wrote: > So, for example, if I had a document that looked like this: > > > this is node b > this is node c > > this is node e > > this is node f > > > I would want to print the following: > > > > text: this is node b > > text: this is node c > > > text: this is node e > > this is node f > > Is there a simple way to do this? Any help would be appreciated. > Thanks.. Fredrik Lundh wrote Element Tree, so he'd know the best solution, but I'd like to point out that this is also trivially easy with recursion: def print_nodes(element, ancestors = []): s = hierarchy = ancestors + ["<" + element.tag + ">"] if element.text is not None: s = s + [element.text] print " ".join(s) for subelement in element: print_nodes(subelement,hierarchy) Carl Banks From enleverlesX.XmcX at XmclaveauX.com Sun Sep 21 03:52:47 2008 From: enleverlesX.XmcX at XmclaveauX.com (=?UTF-8?Q?M=C3=A9ta-MCI_=28MVP=29?=) Date: Sun, 21 Sep 2008 09:52:47 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <48d5fe18$0$909$ba4acef3@news.orange.fr> Hi! > Everything ... are an object. It's true ; but a language built around the objects, and OOP, are two different concepts. @-salutations -- Michel Claveau From andy_westken at hotmail.com Thu Sep 11 11:19:22 2008 From: andy_westken at hotmail.com (andy_westken at hotmail.com) Date: Thu, 11 Sep 2008 08:19:22 -0700 (PDT) Subject: Enumerating ordered expat attributes with tuplets? References: Message-ID: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> On Sep 11, 4:04?pm, Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi Andy, > > by the looks of it I'd say that the problem is that the second ? > parameter you passed to start_element is not a dictionary at all (the ? > clue is in the "AttributeError: 'LIST' object" ...). > > ?>>> d = ['tree', 'house'] > ?>>> start_element("Thing", d) > Thing : > AttributeError: 'list' object has no attribute 'items' > ?>>> d = {'tree': 'hug', 'flower' : 'eat'} > ?>>> start_element("Thing", d) > Thing : ? flower="eat" ?tree="hug" > > Manuel > > On Sep 11, 2008, at 4:21 PM, andy_west... at hotmail.com wrote: > > > > > > > Hi > > > I'm new to Python and trying to pick up good, idiomatic usage right > > from the offset. > > > As I was familiar with Expat from C++ (directly and via expatpp) I'm > > trying to write a little script - using xml.parsers.expat - to search > > and replace XML attribute values. > > > As I want the attributes to stay in order when the file is written out > > (so I can check my results with a diff tool) I've set the parser's > > ordered_attributes attribute. But this has stopped the for loop > > working with the tuplets. > > > The relevant bit of code in my little test, using the default > > Dictionary for the attributes, is: > > > def start_element(name, attrs): > > ? ? print "%s : " % name, > > ? ? for (a,b) in attrs.items(): > > ? ? ? ? print " %s=\"%s\"" % (a,b), > > > But when I set ordered_attributes, first it doesn't like the items() > > > ? ? AttributeError: 'list' object has no attribute 'items' > > > And then it doesn't like the tuple > > > ? ? ValueError: too many values to unpack > > > Do I have keep track of where I am (name, value, name, value, ...) > > > Or is there a way I can solve the problem with a tuple? > > > Thanks, Andy > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (Darwin) > > iD8DBQFIyTOLcZ70OCIgLecRAsBrAJ9YSa7f+YTyM1yRmEKw8KBtb2klIgCgjNzw > F295Tik+45eNHnJ3B4kKnWU= > =xR4m > -----END PGP SIGNATURE------ Hide quoted text - > > - Show quoted text - Sorry! I forgot to mention that when you set the parser's ordered_attributes attribute, it sends the "attrs" to start_element as a list, not a dictionary, in the order name, value, name, value, ... Andy From gherron at islandtraining.com Sat Sep 20 12:37:42 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 20 Sep 2008 09:37:42 -0700 Subject: How to make a reverse for loop in python? In-Reply-To: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <48D526D6.4060402@islandtraining.com> Alex Snast wrote: > Hello > > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) > -- > http://mail.python.org/mailman/listinfo/python-list > What are you trying to loop through? If it's the contents of a list, you can reverse the list (in place) first: L = [1,2,3] L.reverse() for item in L: print item Or you can create a new reversed (copy of the original) list and iterate through it for item in reversed(L): print item If it's just a sequence of numbers you want to generate: range(3) generates a forward list [0,1,2], and range(3,0,-1) generates a backward list [2,1,0] so for i in range(11,0,-1): might be what you want. If your list is huge, consider xrange rather than range. And as always, you could just roll your own index manipulation: i = 10 while i >=0: # do whatever i -= 1 Gary Herron From fredrik at pythonware.com Wed Sep 10 09:46:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 15:46:54 +0200 Subject: Python extension, where am I going wrong In-Reply-To: <48C7C8CC.2090404@arl.army.mil> References: <48C7C8CC.2090404@arl.army.mil> Message-ID: John Vines (CISD/HPCD) wrote: > I am trying to create an extension module and keep getting an error, > "/usr/local/lib/python2.5/site-packages/mytest.so: undefined symbol: > PyInitModule" it's spelled Py_InitModule, not PyInitModule. From ptmcg at austin.rr.com Mon Sep 29 10:45:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 29 Sep 2008 07:45:47 -0700 (PDT) Subject: Using re to find unicode ranges References: Message-ID: On Sep 29, 8:17?am, Eric Abrahamsen wrote: > Is it possible to use the re module to find runs of characters within ? > a certain Unicode range? > > I'm writing a Markdown extension to go over text and wrap blocks of ? > consecutive Chinese characters in tags for ? > nice styling in an HTML page. The available hooks appear to be a pre- > processor (which is a "for line in lines" situation) or an inline ? > pattern (which uses regular expressions). The regular expression ? > solution would be much simpler and faster, but something tells me ? > there's no way to use a regex to find character ranges... Chinese ? > characters appear to fall between 19968 and 40959 using ord(), and I ? > suppose I can go that route if necessary, but I think it would be ugly. > > Any hints or suggestions would be appreciated! > > Eric Eric - This sounds similar to what zhpy (http://pyparsing.wikispaces.com/ WhosUsingPyparsing#Zhpy) does to extract Chinese words from code, to generate executable English Python. You might give that a look. -- Paul From kccnospam at glenevin.com Mon Sep 8 16:10:20 2008 From: kccnospam at glenevin.com (seanacais) Date: Mon, 8 Sep 2008 13:10:20 -0700 (PDT) Subject: finding the parent class (not superclass) of the currently executing method derived from a Borg class Message-ID: I want to create a class derived from a Borg class that can instantiated as part of a script or be contained in other classes. When methods from the Borg class are called, I would like to know the name of the class that contains the Borg class. I've played a bit with inspect and _getframe from the sys module but get inconsistent results. The main problem is if the Borg class is instantiated outside a containing class, then I need to go up a different number of stack frames. But this information isn't available till after I've run out of stack frames. Hopefully the following code better describes what I'm looking to do. import sys class Borg: _shared_state = {} def __init__(self): self.__dict__=self._shared_state class Assimilated(Borg): valueByCaller = {} def __init__(self, setupvalue): print "In Assimilated.__init__()" print "setupvalue is: " + str(setupvalue) # would like key to be name of class (or module) that # contins Assimilated callerID = sys._getframe(1).f_code.co_name self.valueByCaller[callerID] = setupvalue print self.valueByCaller def action(self, calledvalue): print "In Assimilated.action()" print "self.__classname__: " + self.__class__.__name__ print "calledvalue is: " + str(calledvalue) print "self.valueByCaller" print self.valueByCaller # need to get proper key depending on which class (or module) # made the call # print "0: " + sys._getframe(0).f_code.co_name # print "1: " + sys._getframe(1).f_code.co_name # print "2: " + sys._getframe(2).f_code.co_name # print "3: " + sys._getframe(3).f_code.co_name callerID = sys._getframe(2).f_code.co_name print "callerID" print callerID if(self.valueByCaller[callerID] <= calledvalue): print "doing the action" class A: assim_object = Assimilated(2) def __init__(self): self.assim_object.action(2) self.assim_object.action(3) class B: assim_object = Assimilated(3) def __init__(self): self.assim_object.action(3) self.assim_object.action(4) class C: assim_object = Assimilated(4) def __init__(self): self.assim_object.action(4) self.assim_object.action(5) a=A() b=B() c=C() obj=Assimilated(3) #obj.action(3) When I run this, I get the following output: In Assimilated.__init__() setupvalue is: 2 {'A': 2} In Assimilated.__init__() setupvalue is: 3 {'A': 2, 'B': 3} In Assimilated.__init__() setupvalue is: 4 {'A': 2, 'C': 4, 'B': 3} In Assimilated.action() self.__classname__: Assimilated calledvalue is: 2 self.valueByCaller {'A': 2, 'C': 4, 'B': 3} callerID Traceback (most recent call last): File "\CallerID.py", line 67, in a=A() File "\CallerID.py", line 49, in __init__ self.assim_object.action(2) File "\CallerID.py", line 41, in action if(self.valueByCaller[callerID] <= calledvalue): KeyError: '' What I found most peculiar when I started this was that the valueByCaller dictionary was completely populated before the __init__ method of a was executed. I'm pretty sure that this has to do with the difference between when the object gets instanced and when it gets initialized, but I need to do some more research and reading to be able to explain it to myself. Thanks for any help you can give me. Kevin From imageguy1206 at gmail.com Fri Sep 12 16:41:57 2008 From: imageguy1206 at gmail.com (imageguy) Date: Fri, 12 Sep 2008 13:41:57 -0700 (PDT) Subject: String to hexadecimal conversion References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Message-ID: <87ec2d77-3892-4793-ab02-880f8564acf2@i24g2000prf.googlegroups.com> On Sep 8, 5:05?am, Praveena P wrote: > Hi folks, > > I am new to Python... so am not too sure about how the type conversion > works. > > I have to read a file that contains hexadecimal data and use the data > further to do some arithmetic calculations. > A sample of the input is : 00000000000020E0000032F800000000400022005E > The problem I am facing is this: > I am using f.read(2) to read a byte at a time, but the data that is > read is a string rather than a number. So it kind of hampers any > arithmetic operations I perform on this data... > > Could you please suggest some method I could use for this? > > Thanks guys! > Praveena check out the "struct" module in the standard python library. It's title says it all "Interpreting strings as packed binary data". I used this extensively to reverse engineer a couple proprietary file structures. You can read large chucks of the file - perhaps a record ? - and then based on the format provided, convert it to a tuple. Good luck. g. From castironpi at gmail.com Fri Sep 26 20:24:48 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 17:24:48 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> Message-ID: On Sep 26, 6:40?pm, "Tim Rowe" wrote: > 2008/9/26 Aaron Castironpi Brady : > > > If you have wxFormBuilder and the win32 library, it's pretty fast. > > Speed has never been an issue for me with Python. For my masters > degree I did a project that involved a lot of number crunching, and in > my proposal I wrote that I'd use Python for most of the code and C for > any parts that were unacceptably slow. In practice, not only did I > never need to replace any parts with C, I never even needed to use > numpy; it was quite fast enough as it was. > > > Python's philosophy is to make common things easy and everything > > possible. > > But what's common for one person may be uncommon for another. And > sometimes "possible" isn't enough, or we'd all be using INTERCAL! > > Another, quite different example to the one I was referring to earlier > is the fact that I often work with safety critical systems. I don't > think formal proof of program behaviour would be at all > straightforward in Python (or C# for that matter, and although Spec# > gets closer, it really needs a language like Spark Ada). > > -- > Tim Rowe No. I understand that formal proof systems, as well as automated theorem provers, have been difficult to develop. When I took ML, the homeworks were to prove the correctness of an interpretation of a program, and the unique existence of a meaning by induction. But I, and I imagine I'm not the only one, would love to know the example that C# developed faster than Python. I suppose the fact that the line of wx specification that has two identifiers where C# has one is more of a drain on programmer resources than may commonly be recognized--- not the same as the cost of one extra word in a paper or in an editorial. Similarly, maybe the program that has one extra identifier in a line takes a lot more time to develop. Perhaps it's the "7 +/- 1" trend in attention span that makes the difference large in that case. 8 identifiers would in that theory be a big deal, so the example in C# could make the case for it. From invalid at invalid Fri Sep 26 11:44:13 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 26 Sep 2008 10:44:13 -0500 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: On 2008-09-26, Lawrence D'Oliveiro wrote: > In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: >> >>> Just a thought, your minimum sleep time is probably limited by the >>> resolution of the system "HZ" clock. Type >>> >>> less /proc/config.gz >> >> $ less /proc/config.gz >> /proc/config.gz: No such file or directory >> >> >> What OS are you using? > > The one named in the subject line? Never assume somebody reading the article and attempting to help you can see the subject line. -- Grant Edwards grante Yow! I'm encased in the at lining of a pure pork visi.com sausage!! From sjmachin at lexicon.net Sun Sep 7 18:59:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Sep 2008 15:59:52 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> On Sep 8, 8:42?am, "James Mills" wrote: > On Mon, Sep 8, 2008 at 8:37 AM, John Machin wrote: > > There seems to be an implicit assumption in the answers so far that > > your mapping is a 1:1 mapping of all possible input keys. > > > If it doesn't include all possible input keys, answers will crash with > > a KeyError. If there are any many:1 elements in the mapping (for > > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > > in some checks for this. > > You are quite right! But then he/she didn't > ask for this right ? :) > What do you mean by "this right"? Perhaps the Divine Right of OPs, managers, examiners, business analysts, etc never to give a complete spec up front and never to contemplate the consequences of Murphy's Law? From grommasher at gmail.com Mon Sep 1 12:00:43 2008 From: grommasher at gmail.com (Grom) Date: Mon, 1 Sep 2008 09:00:43 -0700 (PDT) Subject: Problem with Twisted Message-ID: <3f336b4e-9834-4706-ae01-648c0762e43e@s50g2000hsb.googlegroups.com> Hello. I have something like that: from twisted.words.protocols.jabber import xmlstream from twisted.internet import protocol from twisted.words.xish import domish, utility from twisted.internet import reactor from twisted.python import log import sys, hashlib log.startLogging(sys.stdout) def magicHash(password, sid): magic1 = 0x50305735 magic2 = 0x12345671 sum = 7 for s in range(len(password)): z = ord(password[s]); if (z == ' '): continue if (z == '\t'): continue magic1 = magic1 ^ ((((magic1 & 0x3f) + sum) * z) + (magic1 << 8)) magic2 = magic2 + ((magic2 << 8) ^ magic1) sum += z magic1 = magic1 & 0x7fffffff magic2 = magic2 & 0x7fffffff return ('%08x%08x'%(magic1, magic2)) def ping(xmlstream): print 'ping' xmlstream.send(' \t ') reactor.callLater(40, ping, xmlstream) class TlenAuthInitializer(object): def __init__(self, xs): print "Wykonywanie TlenAuthInitializer" self.xmlstream = xs def initialize(self): print "Wykonywanie TlenAuthInitializer - initialize" iq = xmlstream.IQ(self.xmlstream, "set") print '1' iq['id'] = self.xmlstream.sid print '2' q = iq.addElement('query', 'jabber:iq:auth') print '3' q.addElement('username', content = self.xmlstream.authenticator.jid) print '4' q.addElement('digest', content = hashlib.sha1(magicHash(self.xmlstream.authenticator.password, self.xmlstream.sid)).hexdigest()) print '4' q.addElement('resource', content = 't') print '6' q.addElement('host', content = 'tlen.pl') print q.toXml(prefixes=self.prefixes, closeElement=0) print '7' d = iq.send('q') print '8' d.addCallback(self._authreply) print '9' d.addErrBack(self._authfail) print '10' def _authreply(self, el): print "Wykonywanie TlenAuthInitializer - _authreply" print el.toXml() reactor.callLater(40, ping, self.xmlstream) def _authfail(self, el): print "Wykonywanie TlenAuthInitializer - _authfail" print el.toXml() class TlenAuthenticator(xmlstream.ConnectAuthenticator): def __init__(self, jid, password, host): print "Wykonywanie TlenAuthenticator" xmlstream.ConnectAuthenticator.__init__(self, host) self.jid = jid self.password = password def associateWithStream(self, xs): print "Wykonywanie TlenAuthenticator - associateWithStream" xs.version = (0, 0) xmlstream.ConnectAuthenticator.associateWithStream(self, xs) inits = [(TlenAuthInitializer, True)] for initClass, required in inits: init = initClass(xs) init.required = required xs.initializers.append(init) class TlenStream(xmlstream.XmlStream): def sendHeader(self): print "Wykonywanie TlenStream - sendHeader" rootElem = domish.Element((None, 's')) rootElem['v'] = '9' rootElem['t'] = '06000224' self.rootElem = rootElem self.send(rootElem.toXml(prefixes=self.prefixes, closeElement=0)) self._headerSent = True print 'XMLed rootElem from sendHeader '+rootElem.toXml(prefixes=self.prefixes, closeElement=0) def sendFooter(self): print "Wykonywanie TlenStream - sendFooter" self.send('') def onDocumentStart(self, rootelem): print "Wykonywanie TlenStream - onDocumentStart" xmlstream.XmlStream.onDocumentStart(self, rootelem) print 'rootelem from onDocumentStart '+rootelem.toXml() if rootelem.hasAttribute("i"): self.sid = rootelem["i"] self.authenticator.streamStarted(rootelem) class TlenStreamFactory(xmlstream.XmlStreamFactory): def __init__(self, authenticator): print "Wykonywanie TlenStreamFactory" xmlstream.XmlStreamFactory.__init__(self, authenticator) self.authenticator = authenticator def buildProtocol(self, _): print "Wykonywanie TlenStreamFactory - buildProtocol" self.resetDelay() # Create the stream and register all the bootstrap observers xs = TlenStream(self.authenticator) xs.factory = self for event, fn in self.bootstraps: xs.addObserver(event, fn) return xs def lg(el): print 'all>',el def err(el): print 'err>', el factory = TlenStreamFactory(TlenAuthenticator('portsentry', 'linux1991','s1.tlen.pl' )) factory.addBootstrap('/*', lg) reactor.connectTCP('s1.tlen.pl', 443, factory) reactor.run() Now... I have problem with that. It not print me any errors but there is something with d = iq.send('q') on TlenAuthInitializer - initialize. I dont know why but python print me just "6" and stops... its strange... anyone have suggestions? From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 22:45:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 02:45:10 GMT Subject: Borg vs Singleton vs OddClass References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> Message-ID: <00eee973$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 11:12:00 -0700, Lie wrote: > This is probably unrelated to Python, as this is more about design > pattern. I'm asking your comments about this design pattern that is > similar in functionality to Singleton and Borg: to share states. > > I'm thinking about this design pattern (I don't know if anyone has ever > thought of this pattern before): > > class OddClass(object): > def __init__(self): > global OddClass > OddClass = self > def __call__(): > return self I don't think that pattern works as you give it. I suggest you read the thread "What do you call a class not intended to be instantiated", started by me on the 21st of September, which covers a similar pattern. I'm afraid it's a rather long thread, with a lot of people misunderstanding what I was asking, but still worth reading. If you only have time to read one post, I suggest you read my reply to Ben Finney, posted yesterday. My own feeling is that both your OddClass and my class without instances are probably solutions looking for a problem. Well, actually, no, that's too strong: I think the concept of "Class Singleton" is a perfectly valid solution to certain problems, but it competes with more well-known solutions like modules and Borg (in Python) and Singletons (the hammer available in Java and C++). As for which is better, that's partly a matter of personal taste and partly a matter of familiarity. > It do have a problem though, that you can't do isinstance(a, OddClass) But you can say "a is OddClass", which is more appropriate for a Singleton. > The problem with Borg is that it is not inheritable (in certain > sense[1]) and only work with old-style class (which is due to be > completely removed on py3k)[2] No, there is a new-style Borg. Read the comments here: http://code.activestate.com/recipes/66531/ The new-style Borg is hardly more complicated than old-style: 6 lines versus 4. I like Luke Plant's comment: "classes and modules are singletons. You don't need singletons in python simply because classes and modules are always singletons, and they are also first class objects. They can have everything instances have, and as import statements don't make copies there is only ever one of them. We don't need no stinkin' design patterns." -- Steven From duncan.booth at invalid.invalid Wed Sep 10 10:42:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Sep 2008 14:42:41 GMT Subject: universal unicode font for reportlab References: Message-ID: Laszlo Nagy wrote: > I need to use HTML anyway. I realized that universal unicode fonts are > above 5MB in size. The report would be a 10KB PDF, but I need to embed > the font before I can send it to anyone. Since some reports needs to be > sent in emails, I need to use something else. I cannot be sending 10MB > emails for "one page" reports. > I thought that usually when you embed a font in a PDF only the glyphs which are actually used in the document get embedded. Unfortunately a quick test with reportlab seems to show that it doesn't do that optimisation: it looks as though it just embeds the entire font. -- Duncan Booth http://kupuguy.blogspot.com From castironpi at gmail.com Wed Sep 10 15:26:42 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 10 Sep 2008 12:26:42 -0700 (PDT) Subject: Reading binary data References: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> Message-ID: <93e2f111-eb1a-44ba-a184-a35c2a8b8980@f36g2000hsa.googlegroups.com> On Sep 10, 1:12?pm, Aaron Scott wrote: > Sorry, I had posted the wrong error. The error I am getting is: > > ? ? ?struct.error: unpack requires a string argument of length 12 > > which doesn't make sense to me, since I'm specifically asking for 11. > Just for kicks, if I change the line to > > ? ? ?print struct.unpack('3sII', file.read(12)) > > I get the result > > ? ? ?('GDE', 33554432, 16777216) > > ... which isn't even close, past the first three characters. Sometimes 'endian' order can cause this. Try '<3sII' and '>3sII' for your formats to differentiate. Also, if your file is not packed the way that 'struct' expects, you might need to read the string and integers separately. /Example: >>> struct.Struct( '3s' ).size + struct.Struct( 'II' ).size 11 >>> struct.Struct( '3sII' ).size 12 From michael.pearmain at tangozebra.com Mon Sep 8 08:52:33 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 8 Sep 2008 05:52:33 -0700 (PDT) Subject: Dictionaries and loops Message-ID: Hi All i have a CSV file that i'm reading in and each line has the look of the below {None: ['User-ID', 'Count']} {None: ['576460847178667334', '1']} {None: ['576460847178632334', '8']} i want to make a dictionary of items in the form {576460847178667334:1, 576460847178632334:8, ..... } for all rows in the datafile my code so far is thus: dict1={} j=1 for row in reader1: if j==1: j+=1 continue #thus allowing me to skip the first row if j>1: for element in row.values(): for item in element: if int(item)%2==0: dict1[int(item)] = int(item)+1 # i know this is the problem line as it's not picking the second item up just finding the first and increasing it, but i can't figure out how to correct this? j+=1 I get one dictionary from this but not the correct data inside, can anyone help? From gh at ghaering.de Fri Sep 5 16:24:23 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 05 Sep 2008 22:24:23 +0200 Subject: [ANN] pysqlite 2.5.0 released Message-ID: <48C19577.3020303@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 pysqlite 2.5.0 released ======================= I'm pleased to announce the availability of pysqlite 2.5.0. This is a release with major new features. Go to http://pysqlite.org/ for downloads, online documentation and reporting bugs. What is pysqlite? pysqlite is a DB-API 2.0-compliant database interface for SQLite. SQLite is a in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. pysqlite makes this powerful embedded SQL engine available to Python programmers. It stays compatible with the Python database API specification 2.0 as much as possible, but also exposes most of SQLite's native API, so that it is for example possible to create user-defined SQL functions and aggregates in Python. If you need a relational database for your applications, or even small tools or helper scripts, pysqlite is often a good fit. It's easy to use, easy to deploy, and does not depend on any other Python libraries or platform libraries, except SQLite. SQLite itself is ported to most platforms you'd ever care about. It's often a good alternative to MySQL, the Microsoft JET engine or the MSDE, without having any of their license and deployment issues. pysqlite can be downloaded from http://pysqlite.org/ - Sources and Windows binaries for Python 2.5, 2.4 and Python 2.3 are available. ======= CHANGES ======= - - Windows binaries are now cross-built using mingw on Linux - - import various fixes from Python 2.6 version - - Connection has new method iterdump() that allows you to create a script file that can be used to clone a database - - the docs are now built using Sphinx and were imported from Python 2.6's sqlite3 module - - Connection.enable_load_extension(enabled) to allow/disallow extension loading. Allows you to use fulltext search extension, for example ;-) - - Give the remaining C functions used in multiple .c source files the pysqlite_ prefix. - - Release GIL during sqlite3_prepare() calls for better concurrency. - - Automatically download the SQLite amalgamation when building statically. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIwZV3dIO4ozGCH14RAp1YAJwPIdgtCZY7E8YcDUjO/dzoAThblgCggfhs OATfXAb6JYXqb8eTadl9k74= =KU3f -----END PGP SIGNATURE----- From dmitry at athabascau.ca Thu Sep 25 16:38:03 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 20:38:03 GMT Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> <48dbc82e$0$1120$426a74cc@news.free.fr> <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> <1fc9b5c2-0e58-4b48-9352-4122986ce7ec@k13g2000hse.googlegroups.com> Message-ID: George Sakkis wrote: > I'm not sure if the approach below deals with all the issues, but one > thing it does is decouple completely the proxied objects from the > proxy: > class _ProxyMeta(type): It smelled to me more and more like metaclass too, I was just trying to avoid them :) Your code looks awefully close to what I'm trying to do, except it looks bit heavier than decorators. Seems like decorators are not going to happen in this part of project for me anyway, however the whole discussion gave me a lot to think about. Thank you Bruno, Aaron, Diez and George. Thanks for the concrete code with metaclass. I'm going to study it thoroughly to see if I can spot caveats/issues for my usecases however it seems to put me on the right track. I never used metaclasses before and decorators seemed to be bit more straight-forward to me :) ..oh well. From bj_666 at gmx.net Mon Sep 1 08:11:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2008 12:11:38 GMT Subject: Know if a object member is a method References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Message-ID: <6i24fqFo7morU1@mid.uni-berlin.de> On Mon, 01 Sep 2008 11:45:36 +0200, Luca wrote: >> But not so easy to fool a type check: >> >>>>> type(x) == new.function >> False >> >> Of course that's not bullet-proof either. I leave it as an exercise to >> discover how you might break that piece of code. >> >> > Ok, so... > > What is the best way to do this? The "most pythonic"? The "most pythonic" might be not checking at all but simply *call* the object and deal with possible failures. What's your use case? Ciao, Marc 'BlackJack' Rintsch From ldo at geek-central.gen.new_zealand Thu Sep 25 18:20:58 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 10:20:58 +1200 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: In message <24ac4a18-049f-4ae0-892a-d3fc84995c9d at a18g2000pra.googlegroups.com>, Craig Allen wrote: > It is clearly possible to write procedural code... that is, > Python does not force object oriented syntax or concepts on you ... Object orientation IS procedural. From fredrik at pythonware.com Thu Sep 18 05:26:09 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Sep 2008 11:26:09 +0200 Subject: How to Determine Name of the Day in the Week In-Reply-To: <48D1C8F2.6040308@gmail.com> References: <48D1C8F2.6040308@gmail.com> Message-ID: Keo Sophon wrote: > I've tried calendar.month_name[0], it displays empty string, while > calendar.month_name[1] is "January"? Why does calendar.month_name's > index not start with index 0 as calendar.day_name? the lists are set up to match the values used by the time and datetime modules; see e.g. http://docs.python.org/lib/module-time.html http://docs.python.org/lib/datetime-date.html From nicolegraves0281 at gmail.com Sat Sep 20 05:46:35 2008 From: nicolegraves0281 at gmail.com (maria sujane) Date: Sat, 20 Sep 2008 02:46:35 -0700 (PDT) Subject: >>>> FREE online Fashions and Naughty Girls AMAZING video MOVIE clips <<<< Message-ID: Naughty Free Live Sex Web Cams & ChatClick here for free live sex web cams & chat online. Straight, Gay, Lesbian, Swingers, and more. Get sexy and broadcast your own cam. Chat for free. MOre... [b] http://urlaxe.com/modfxmodels [/b] http://join.digitaldesire.com/track/OTMxNzozOjE/ http://www.absolutevids.com/?revid=60008&s=0&campaign=0,AbsoluteVids,absolutevids,absv,0,0 From FettManChu at gmail.com Thu Sep 4 16:55:12 2008 From: FettManChu at gmail.com (Fett) Date: Thu, 4 Sep 2008 13:55:12 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: <7xwshr4qr4.fsf@ruckus.brouhaha.com> Message-ID: On Sep 4, 3:09?pm, Paul Rubin wrote: > Fett writes: > > Is there any crypto package that is actually written in python? I > > seriously don't care how slow it is. > > I wrote a simple symmetric encryption function in python: > > ?http://nightsong.com/phr/crypto/p3.py > > I wrote a somewhat fancier package that did public key a while back, > that is unreleased because of insufficient testing and some features > I'd like to have done differently, but I ought to get around to > cleaning it up sometime. > > There is also tlslite, which you might be able to extract > some public key functions from: ?http://trevp.net/tlslite Wow, I have no idea how that works, but I think it will do nicely. The main goal is simply to ensure that data coming in (from a website), is valid (ie. posted by me). The site is supposedly secure, and the code only accepts data of the type I expect, so the only security risk was someone posting bad data. This simple method should stop anyone from bothering to do even that. Kudos for writing the code in a way that I can see how it is used, even without documentation this is small enough to dissect. Thank you, I think we have a winner. (BTW, I have no idea how this whole encrypting gives many strings, decrypting all gives the correct one works, but it sure seems to work just fine, more fully featured than I even felt I needed.) From san82moon at gmail.com Mon Sep 1 07:26:14 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 04:26:14 -0700 (PDT) Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> <6i1rgcFo0f1gU1@mid.uni-berlin.de> <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> Message-ID: <6645c39a-3cb8-4f34-bbd3-2c4fe8210167@s20g2000prd.googlegroups.com> On Sep 1, 3:59 pm, Wojtek Walczak wrote: > On Mon, 1 Sep 2008 03:51:13 -0700 (PDT), lee wrote: > > i am soory for that keystrokes. can anyone tell me how can i change > > the value of key. > > suppose i have a dictionary > > > kev = {'kabir': ['ka... at kabir.com', '1234', 'missuri'], 'shri': > > ['s... at shri.com', '23423', 'india'], 'marsa': ['ma... at marsa.com', > > '2345', 'brazil'], 'sandeep': ['sand... at sandeep.com', '007', > > 'canada']} > > how can i change the key to something like 'sabir' and > > kev['sabir'] = kev['kabir'] > del kev['kabir'] > > > how can i > > change the values of kabir? > > kev['sabir'][0] = 'sa... at sabir.com' > > *untested* > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ thanks wojtek, it worked :) From nytrokiss at gmail.com Wed Sep 17 19:20:31 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 17 Sep 2008 16:20:31 -0700 Subject: locks In-Reply-To: <18641.17709.251764.767222@montanaro-dyndns-org.local> References: <48D140FC.8070801@el.net> <18641.17709.251764.767222@montanaro-dyndns-org.local> Message-ID: <8a6b8e350809171620p61280df6j5e5fece940251cf6@mail.gmail.com> You might also want to paste the output into a pastbin such as dpaste.com On Wed, Sep 17, 2008 at 10:58 AM, wrote: > > kalin> mailman has been locking one list out. the web interface just > kalin> hangs and it generates a bunch of locks. it seems that it can not > kalin> write to a log but not sure which one. errors are like: > ... > > You'd probably be better off asking about Mailman problems on > mailman-users at python.org. > > -- > Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From uomiocenekidd at gmail.com Mon Sep 22 06:39:29 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:39:29 -0700 (PDT) Subject: redtube xtube youporn - Free Message-ID: <6640c064-bd8e-4e08-b1cf-70a971588559@8g2000hse.googlegroups.com> redtube xtube youporn . . . *******CLICK HERE******** http://vids365.cn/redtube-xtube-youporn ***************************** . . . . . . . . . . . . redtube xtube youporn From marco.bizzarri at gmail.com Mon Sep 1 07:18:16 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 1 Sep 2008 13:18:16 +0200 Subject: Retrieving http headers from HTTPConnection object In-Reply-To: References: Message-ID: <3f0d61c40809010418n10a2c747i82d8a6c6317bbf39@mail.gmail.com> On Mon, Sep 1, 2008 at 1:06 PM, jorma kala wrote: > Hi, > > when using httplib for http requests, like for example: > > > conn = httplib.HTTPConnection("www.python.org") > conn.request("GET", "/index.html") > > Is it possible to retrieve the complete http request in string form : > > > GET /index.html HTTP/1.1 > Host: www.python.org > User-Agent: ... > Accept: ... > Accept-Language: > Accept-Encoding: > Accept-Charset: > Keep-Alive: > Connection: > > I mean does the HTTPConnection object have a property that stores this ? > or is it retrievable by some other form? > > Thanks a lot. > -- Looking at the code of HTTPConnection, all that goes through the _output message (including, therefore, the putheaders) are appended to the self._buffer list. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From aonlazio at gmail.com Tue Sep 23 21:05:27 2008 From: aonlazio at gmail.com (AON LAZIO) Date: Tue, 23 Sep 2008 21:05:27 -0400 Subject: Property Function Message-ID: Hi, In python code, class A: get(self): do something set(self): do something g=property(get,set) what is the good use of "property" function?, I do not understand clearly.. Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Mon Sep 1 08:19:15 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2008 12:19:15 GMT Subject: Python 3.0b2 cannot map '\u12b' References: Message-ID: <6i24u3Fo7morU2@mid.uni-berlin.de> On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: > I doubt the OP 'chose' cp437. Why does Python using cp437 even when the > default encoding is utf-8? > > On WinXP > >>> sys.getdefaultencoding() > 'utf-8' > >>> s='\u012b' > >>> s > Traceback (most recent call last): > File "", line 1, in > File "C:\Program Files\Python30\lib\io.py", line 1428, in write > b = encoder.encode(s) > File "C:\Program Files\Python30\lib\encodings\cp437.py", line 19, in > encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in > position > 1: character maps to Most likely because Python figured out that the terminal expects cp437. What does `sys.stdout.encoding` say? > To put it another way, how can one 'choose' utf-8 for display to screen? If the terminal expects cp437 then displaying utf-8 might give some problems. Ciao, Marc 'BlackJack' Rintsch From rridge at csclub.uwaterloo.ca Fri Sep 26 23:10:06 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 26 Sep 2008 23:10:06 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48db462f$0$24356$426a74cc@news.free.fr> <48dc952b$0$2289$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Also note that there are quite a couples cases where the library authors > themselves cannot predict which exception types may be raised - as soon > as the library functions expect callback functions, file-like or > dict-like or whatever-like objects etc, it's the caller's responsability > to handle the exceptions that may be raised by what *he* passes to the > library... Ross Ridge a ?crit : > Ug... that's another documentation pet-peeve of mine. Libraries that > say they take file-like (or whatever-like) object, but don't say exactly > how file-like it needs. Bruno Desthuilliers wrote: >Seems not to be such a problem in practice... Not if you don't mind figuring out such things by trial and error or looking at the source. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From grflanagan at gmail.com Thu Sep 18 11:43:36 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 18 Sep 2008 17:43:36 +0200 Subject: dict generator question In-Reply-To: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> Message-ID: Simon Mullis wrote: > Hi, > > Let's say I have an arbitrary list of minor software versions of an > imaginary software product: > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > I'd like to create a dict with major_version : count. > > (So, in this case: > > dict_of_counts = { "1.1" : "1", > "1.2" : "2", > "1.3" : "2" } > [...] data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] from itertools import groupby datadict = \ dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) print datadict From stef.mientki at gmail.com Fri Sep 12 16:00:18 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 12 Sep 2008 22:00:18 +0200 Subject: GUI programming with python In-Reply-To: References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: <48CACA52.5050001@gmail.com> Al Dykes wrote: > In article <1bs69ogq6nspt.136i7kvcux142$.dlg at 40tude.net>, > Alan Franzoni wrote: > >> zamil was kind enough to say: >> >> [cut] >> >> If your needs are very basic, you can stick with the tk module that comes >> with python. It's not really feature-packed, but it's maintained and pretty >> cross-platform. >> > > > OK, what are my choices for an IDE/GUI development tool that runs on XP? > > Thanks > > > > From Linux guys, I hear that PyScripter is the best, they also want to have it, but unfortunately it only runs under windows ;-) cheers, Stef > From wgwigw at gmail.com Sat Sep 27 21:53:54 2008 From: wgwigw at gmail.com (momobear) Date: Sat, 27 Sep 2008 18:53:54 -0700 (PDT) Subject: what's difference usage? Message-ID: <8ce3d2b7-8d24-4770-9ed9-acf8ce23eaea@w24g2000prd.googlegroups.com> while as I try to wrap a function using boost-python, I find a strange situation. #include #include #include #include #include using namespace boost::python; int printlist(list &l){ std::vector a; a.push_back("c++"); a.push_back("javascript"); for (std::vector::iterator p = a.begin(); p != a.end(); + +p) l.append(*p); return 0; } BOOST_PYTHON_MODULE(wlist){ def("printlist", printlist); } in the up code,"int printlist(list &l)" at first time I missed add & left of l. but when I run the following python code, #!/usr/local/bin/python a = list() a.append('linux') import wlist wlist.printlist(a) print a they get the same result. linux c++ javascript anyone help me figure out what's wrong here. thanks. From skip at pobox.com Fri Sep 26 22:33:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 26 Sep 2008 21:33:07 -0500 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <35681490-2d50-4a51-ae88-c1538ed51e15@y21g2000hsf.googlegroups.com> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> <35681490-2d50-4a51-ae88-c1538ed51e15@y21g2000hsf.googlegroups.com> Message-ID: <18653.39779.419435.495239@montanaro-dyndns-org.local> >> > I read the group via NNTP, and I find that blocking all articles >> > posted from google.groups gets rid of all of the spam. >> >> ... along with a far from trivial (I guess) percentage of non-spam, >> such as this post. Aaron> Every method has false positives, George. (including this one.) George makes a good point though, and it is a key element of how SpamBayes works. A single clue is not a binary selector for ham or spam. Skip From benjamin.kaplan at case.edu Fri Sep 26 10:50:52 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 26 Sep 2008 10:50:52 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> Message-ID: On Fri, Sep 26, 2008 at 10:38 AM, Michael Mabin wrote: > I laugh in the face of danger. > > Give me a use case for an exploit. > http://xkcd.com/327/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 30 00:17:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 01:17:50 -0300 Subject: Finding subsets for a robust regression References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> Message-ID: En Mon, 29 Sep 2008 17:04:48 -0300, escribi?: > result_x = uniques_x.keys() > result_y = map(median, uniques_x.itervalues()) > > I think it works because keys and values are given in the same order, > but in real code I tend to avoid using such subtle things. Because if > you translate that code to another language, or you use another Python > implementation it may not work anymore, and lot of code sooner or > later becomes translated... At least with respect to different Python implementations, it *is* clearly stated in the documentation that "If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond." http://docs.python.org/lib/typesmapping.html -- Gabriel Genellina From ivanov.maxim at gmail.com Fri Sep 26 11:08:09 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Fri, 26 Sep 2008 08:08:09 -0700 (PDT) Subject: multiprocessing eats memory References: <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> Message-ID: On 26 ????, 17:03, MRAB wrote: > On Sep 26, 9:52?am, redbaron wrote: > > > On 26 ????, 04:20, Istvan Albert wrote: > > > > On Sep 25, 8:40?am, "Max Ivanov" wrote: > > > > > At any time in main process there are shouldn't be no more than two copies of data > > > > (one original data and one result). > > > > From the looks of it you are storing a lots of references to various > > > copies of your data via the async set. > > > How could I avoid of storing them? I need something to check does it > > ready or not and retrieve results if ready. I couldn't see the way to > > achieve same result without storing asyncs set. > > You could give each worker process an ID and then have them put the ID > into a queue to signal to the main process when finished. And how could I retrieve result from worker process without async? > > BTW, your test-case modifies the asyncs set while iterating over it, > which is a bad idea. My fault, there was list(asyncs) originally. From fredrik at pythonware.com Fri Sep 12 10:52:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 16:52:11 +0200 Subject: Matching horizontal white space In-Reply-To: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> References: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> Message-ID: Magnus.Moraberg at gmail.com wrote: > multipleSpaces = re.compile(u'\\h+') > > importantTextString = '\n \n \n \t\t ' > importantTextString = multipleSpaces.sub("M", importantTextString) what's "\\h" supposed to mean? > I would have expected consecutive spaces and tabs to be replaced by M > but nothing is being replaced. if you know what you want to replace, be explicit: >>> importantTextString = '\n \n \n \t\t ' >>> re.compile("[\t ]+").sub("M", importantTextString) '\nM\nM\nM' From bignose+hates-spam at benfinney.id.au Tue Sep 30 08:19:57 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 Sep 2008 22:19:57 +1000 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> Message-ID: <87prmlrfki.fsf@benfinney.id.au> Steven D'Aprano writes: > On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > > You're not free to modify gnuplot and redistribute the result. > > > > That you're free to distribute patches is nice, but it's not > > enough to make the work free. The freedom to help people by giving > > them an *already-modified* gnuplot is restricted by the copyright > > holder. > > > > It's an artificial restriction on redistribution of derived works, > > making them second-class for the prupose of getting them into > > people's hands. > > Yes it is. It seems a strange, unnecessary restriction. But is it > sufficient to make it non-free? I don't think so. I do, because a natural, beneficial act (modify the work and redistribute it) that has no technical reason to restrict, is artifically restricted. > In case you are thinking that gnuplot allows people to *only* > distribute the diffs, not the original source to apply the diffs > onto, that is not the case. I quote from gnuplot > help copyright > > "Permission to distribute the released version of the source code > along with corresponding source modifications in the form of a patch > file is granted with same provisions 2 through 4 for binary > distributions." That's what I refer to when I say that it artifically makes derived works into second-class for the purpose of doing the beneficial act of distributing them: the redistributor is artificially restricted from making the work as useful as the original they received. They have only the options to redistribute a work that is more cumbersome for the recipient of that work, or not to redistribute at all. That's not free redistribution. > > I try to judge freedom of a software work by the freedoms granted > > to all recipients of the work, not by the approval of some > > organisation. > > Yes, but you accept some restrictions as legitimate. For example, you > accept the restriction that the GPL makes that says you may not > redistribute a modified work without making the source code available. Yes, which is why I was careful to say "the freedoms granted to all recipients of the work". The power to restrict a recipient of one's work (by choosing not to grant them the freedoms you yourself had when you received the work) reduces the freedoms available to all recipients of the work, even though one party's power may be increased. This is where the useful "your freedom to swing your fist ends at the tip of the other man's nose" applies: As soon as the act you wish to perform is restricting the freedom of another, you're not contemplating an act of freedom, but an act of power over another. Freedoms should be protected, but only within the limits imposed by the freedoms of others. > That's a restriction, but it's not enough to disqualify it from > being a free software licence. Specifically because it upholds the freedom of the recipient of a derived work from having power exerted over them. > In fact, that restriction is *necessary* to make it a free software > licence in the sense we're talking about. Not really; it's necessary to make it a copyleft license, which is a way of preserving freedom as the work gets passed along. Works can still be free software without being copyleft-licensed, though. A license allowing free redistribution and requiring only attribution be preserved is less restrictive than a copyleft; yet, because it allows any free act (even as it also allows acts of power over others), the work is free software. > So "free" does not mean "no restrictions", it merely means "none of > some sorts of restrictions, but other restrictions are okay". > Likewise the restriction that GPL software must be distributed with > a copy of the appropriate licence. That's right, and I've explained above what restrictions I consider justified, and why, and how to tell the difference. -- \ ?Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force.? ?Carol Reichel | _o__) | Ben Finney From a at nospam.org Mon Sep 15 16:45:38 2008 From: a at nospam.org (Armin) Date: Mon, 15 Sep 2008 22:45:38 +0200 Subject: append on lists In-Reply-To: References: Message-ID: Chris Rebert wrote: > On Mon, Sep 15, 2008 at 1:24 PM, Armin wrote: >> >> Hi, >> >> just a dumb question. >> >> Let a = [1,2,3,4,5] >> >> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? > I'll assume the presence of the 6 is a typo. Sorry, that's the case. > > Because .append() mutates 'a' and appends the item in-place rather > than creating and returning a new list with the item appended, and > it's good Python style for mutating methods to have no return value > (since all functions must have some return value, Python uses None > when the function doesn't explicitly return anything). Yes, but this is very unconvenient. If d should reference the list a extended with a single list element you need at least two lines a.append(7) d=a and not more intuitive d = a.append(7) --Armin > > If you print 'a' after doing the .append(), you'll see it's changed to > your desired value. > > Regards, > Chris > >> --Armin >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 15:41:28 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 21:41:28 +0200 Subject: Python on the web - newby question In-Reply-To: <6822d749-cc00-48ce-a30a-ded96a938e79@b30g2000prf.googlegroups.com> References: <6822d749-cc00-48ce-a30a-ded96a938e79@b30g2000prf.googlegroups.com> Message-ID: <48bf0459$0$27459$426a74cc@news.free.fr> SimonPalmer a ?crit : > Apologies in advance if this is either a) the wrong board or b) been > answered a million times elsewhere, but... > > I have been given an assignment to get a python module up and running > behind an existing web site. At the moment the rest of the site is > developed in PHP but the hosts have said they will provide python > support for free, although they haven't given any more details than > that, so I'm not sure exactly what that means. Depending on the hosts, this can range from having an antiquated python version with only cgi enabled and no way to install anything to the very last stable release and (almost) whatever third-part lib / frameworks and correct configuration. > All reasonably > encouraging though. > > I'm a newbie to python but quite experienced with Java/J2EE/JBoss. Quite another world... > What I need to know is how I get python running on the server For which definition of 'server' ? The computer, or the web server process ? > and what > tools/middleware I would need to have installed on the host's machines > to be able to support my python modules. Depends on your modules dependencies !-) More seriously : Python is known has being the language with more web frameworks than keywords. IOW, there's no simple straightforward answer to your question. Fisrt choose which Python web development solution you intend to use, then read the FineManual's "deployment" section of the chosen solution. You'll find pointers to most web-related libs / frameworks here: http://wiki.python.org/moin/WebFrameworks http://wiki.python.org/moin/WebProgramming Given your situation (Python newcomer with a real job to do), and if your job is anything more than a very Q&D deadsimple task, I'd personnaly recommand Django (http://djangiproject.com). Don't let the version number fools you (latest version is 1.0 release candidate), Django is a mature, solid and proven solution that have years of existance, and what they call 1.0rc would be labeled at least 3.5 for some other software... It's also mostly documented, and there's a strong community around the framework, so you should not have much problem getting help. For any other Python question (I mean, non django-related), you're at the right place. Oh, and yes, if I may suggest a reading: http://dirtsimple.org/2004/12/python-is-not-java.html HTH, and welcome on board... From bdesth.quelquechose at free.quelquepart.fr Fri Sep 5 19:03:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Sep 2008 01:03:30 +0200 Subject: Files application architecture In-Reply-To: References: Message-ID: <48c1d6b2$0$15607$426a74cc@news.free.fr> Benjamin Watine a ?crit : > Hi, > > I'm about to develop a small python application and I wonder how to > organize files in this application. > I'm familar to java, so I'm tempted to use the same convention http://dirtsimple.org/2004/12/python-is-not-java.html > : 1 file > per class and 1 folders per package. Don't. This is a waste of time and a pain to maintain, and more over it doesn't make any sense since Python doesn't force you to put everything in classes. > I know that packages doesn't exists in python, Did you actually read the doc ? While Python's packages are not the same thing as Java's, they do exist. http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > they are modules instead. > May I create specific module for each "group of class" ? The usual way to get cohesive modules is indeed to group closely related objects (classes, functions, etc) in a same module. > My application > follow the MVC paradigm, so basically, I've a package Model, a package > View, and a package Controller. If your app is small, having _modules_ models, views and controllers should be enough. > So, what are best practices for organizing files and folders in a small > python project ? The best practice is to keep things simple, as usual. From default at defaulter.net Sat Sep 27 18:47:16 2008 From: default at defaulter.net (default) Date: Sat, 27 Sep 2008 18:47:16 -0400 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> Message-ID: On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko wrote: >Hello, this is Milenko Stojadinovic from town Banjaluka, >Bosnia and Herzegovina, also known as Cvrcko >Does anyone know of any bars in town where I can >swallow a bucket of cum? It can be either dog, >horse or human cum. Also, does anyone know of >any sex bars where people will shit in your mouth? >I also like eating shit. Come to the US and park your mouth in front of George Bush - all the Bshit you can eat - and it keeps on coming! I have a buddy in Bosna - he's normal. -- ----== Posted via Pronews.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.pronews.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= - Total Privacy via Encryption =--- From electronixtar at gmail.com Sun Sep 28 05:21:18 2008 From: electronixtar at gmail.com (est) Date: Sun, 28 Sep 2008 02:21:18 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <00ef3c23$0$20666$c3e8da3@news.astraweb.com> Message-ID: On Sep 28, 4:38?pm, Steven D'Aprano wrote: > On Sat, 27 Sep 2008 22:37:09 -0700, est wrote: > >>>> str(u'\ue863') > > Traceback (most recent call last): > > ? File "", line 1, in > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > > position 0 > > : ordinal not in range(128) > > > FAIL. > > What result did you expect? > > [...] > > > The problem is, why the f**k set ASCII encoding to range(128) ???????? > > while str() is internally byte array it should be handled in range(256) > > !!!!!!!!!! > > To quote Terry Pratchett: > > ? ? "What sort of person," said Salzella patiently, "sits down and > ? ? *writes* a maniacal laugh? And all those exclamation marks, you > ? ? notice? Five? A sure sign of someone who wears his underpants > ? ? on his head." -- (Terry Pratchett, Maskerade) > > In any case, even if the ASCII encoding used all 256 possible bytes, you > still have a problem. Your unicode string is a single character with > ordinal value 59491: > > >>> ord(u'\ue863') > > 59491 > > You can't fit 59491 (or more) characters into 256, so obviously some > unicode chars aren't going to fit into ASCII without some sort of > encoding. You show that yourself: > > u'\ue863'.encode('mbcs') ?# Windows only > > But of course 'mbcs' is only one possible encoding. There are others. > Python refuses to guess which encoding you want. Here's another: > > u'\ue863'.encode('utf-8') > > -- > Steven OK, I am tired of arguing these things since python 3.0 fixed it somehow. Can anyone tell me how to customize a default encoding, let's say 'ansi' which handles range(256) ? From brennan.ron at gmail.com Wed Sep 17 17:30:54 2008 From: brennan.ron at gmail.com (Ron Brennan) Date: Wed, 17 Sep 2008 17:30:54 -0400 Subject: Configuration Parsers Message-ID: <26c69b160809171430x7f020672geb2be7ddd606a462@mail.gmail.com> Hello, I am trying to parse a shared config file which doesn't contail section headers. Is there a way I can still use ConfigParser()? If not what is a widely used parser available? Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Sep 25 16:22:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:22:12 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: References: Message-ID: <6k2a7lF5nf4eU1@mid.uni-berlin.de> Scott Sharkey schrieb: > Hello all, > > Our development group at work seems to be heading towards adopting > python as one of our standard "systems languages" for internal > application development (yeah!). One of the issues that's come up is > the problem with apt (deb packages) vs eggs, vs virtual environments. > We're probably gonna end up using Pylons or TurboGears for web-based > apps, and I've recommended virtualenv, but one of the other developers > has had some "inconsistencies" when mixing systems with python installed > from apt (all our servers are debian or ubuntu based) vs when installed > under virtualenv. > I have basically recommended that we only install the python base (core > language) from apt, and that everything else should be installed into > virtual environments. But I wanted to check to see how other enterprises > are handling this issue? Are you building python from scratch, or using > specific sets of .deb packages, or some other process. > > Any insight into the best way to have a consistent, repeatable, > controllable development and production environment would be much > appreciated. This is the exact way we are deploying our software. You can even use the virtualenv --no-site-packages option to completely isolate the VE from the underlying system site-packages. I would recommend that all you install into the system python is virtualenv, and maybe some uncritical C-modules such as psycopg2. Currently there is much going on regarding setuptools. A fork, "Distribute" has been announced, and "pyinstall" by Ian Bicking, an easy_install replacement that deals with some of it's ancestors shortcomings. Then people (shameless plug warning: including me) are working on "eggbasket", a PYPI-clone that allows to have a local repository of eggs so that you don't fall prey to old versions not longer available on PYPI. Eggbasket will feature "easterbunny", a tool to publish a virtualenv as whole to the eggbasket and also keep track of the precise version set uploaded. Through a specific url on eggbasket you can then limit the contents of eggbasket to that exact version set - which helps dealing with subtle (or not so subtle) version conflicts. I personally can say that I'm really thrilled by the prospects of all these developments. And as much bad rap as setuptools had here and elsewhere, sometimes rightfully so - it certainly does a lot of stuff right, and pushing the whole stack of tools to manage software dependencies in Python to the next level is of great value. Diez From clp at rebertia.com Mon Sep 15 17:15:52 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Sep 2008 14:15:52 -0700 Subject: Python Nautilus script In-Reply-To: <6j80nvF1ttmfU1@mid.uni-berlin.de> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> <6j80nvF1ttmfU1@mid.uni-berlin.de> Message-ID: <47c890dc0809151415n270d8fdbpafff58e5f612423a@mail.gmail.com> On Mon, Sep 15, 2008 at 2:00 PM, Diez B. Roggisch wrote: >>>> It appears that's because HOSTNAME is not exported. >>>> But in the case of Nautilus script, how to workaround this issue? >> >> Alternatively, export the variable when you create it, in .bashrc or >> wherever it is getting created. That's probably the Right Thing to >> Do(tm) in this case. > > > Certainly not, as the OP uses a network monitoring software called Nautilus > - and that communicates state to subprocesses using environment variables. > Nothing to do with .bashrc. Just to clarify, the OP is talking about Nautilus as in the GNOME file manager, not some network monitor. - Chris > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From mrkafk at gmail.com Wed Sep 3 11:40:43 2008 From: mrkafk at gmail.com (mk) Date: Wed, 03 Sep 2008 17:40:43 +0200 Subject: properties setting each other In-Reply-To: <200809031644.10870.maric@aristote.info> References: <200809031644.10870.maric@aristote.info> Message-ID: Thanks to everyone for answers.. > *but*, if you want to add more logic in the setters, you could want to add two > extra methods : > > def _setsquare(self, v) : > # some extra logic here > self._square = s > > def fsetsquare(self,s): > self._setsquare(s) > self._setvalue = math.sqrt(s) > > def _setvalue(self, val): > # some extra logic here > self._internalval=val > > def fsetvalue(self, val): > self._setvalue(val) > self._setsquare=pow(val,2) > Thanks for that, I'll keep that in mind. > Note that if one property can really be computed from another, this kind of > thing could be considered as bad design (except if the computation is heavy). Hmm, why? Is the line of thinking smth like: because the variables should be kept to minimum and they should be calculated at the moment they are needed? From deets at nospam.web.de Wed Sep 10 17:30:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 23:30:49 +0200 Subject: formating a filesystem with python In-Reply-To: References: <6iqrm2F3rqcU1@mid.uni-berlin.de> Message-ID: <6iqsk9F3lbaU1@mid.uni-berlin.de> Ricardo Tiago schrieb: > I understand that this is a very sensible unix question but i think > fuse does this at least it mounts. I was wondering if there were other > packages with similar functionality. I don't know what fuse is. And *mounting* can be allowed to be made by users. and possibly there is a mount-daemon that can mount e.g. usb-devices. but that wouldn't be a pure python-module-solution either. Diez From roy at panix.com Sun Sep 14 13:56:44 2008 From: roy at panix.com (Roy Smith) Date: Sun, 14 Sep 2008 13:56:44 -0400 Subject: Abstract class References: Message-ID: In article , Mr.SpOOn wrote: > I have to manage many elements of music such as notes, intervals, > scales, chords and so on. All these elements share properties and > behavior, so what I want to do is an abstract class "Note" and other > subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. What properties or behaviors does SharpNote have which NaturalNote doesn't? Unless there is some new behavior, you don't need subclasses. Are you also going to have DoubleSharpNote and DoubleFlatNote? Consider the following code: note1 = SharpNote("E4") note2 = NaturalNote("F4") if note1 == note2: print "the same note" else print "different notes" what should it print? From torainLight at gmail.com Sat Sep 20 05:28:15 2008 From: torainLight at gmail.com (satoru) Date: Sat, 20 Sep 2008 02:28:15 -0700 (PDT) Subject: how can i check whether a variable is iterable in my code? Message-ID: hi, all i want to check if a variable is iterable like a list, how can i implement this? From prologic at shortcircuit.net.au Mon Sep 8 05:29:21 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 19:29:21 +1000 Subject: Test if list contains another list In-Reply-To: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> Message-ID: Hi, >>> a = [1,2,3] >>> b = [3,2,1,4] >>> a = set(a) >>> b = set(b) >>> a.intersection(b) set([1, 2, 3]) Is this what you want ? cheers James On 9/8/08, mathieu wrote: > Hi there, > > I am trying to write something very simple to test if a list > contains another one: > > a = [1,2,3] > > b = [3,2,1,4] > > but 'a in b' returns False. How do I check that a is indeed contained > in b ? > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From richardlev at gmail.com Thu Sep 11 12:45:31 2008 From: richardlev at gmail.com (Richard Levasseur) Date: Thu, 11 Sep 2008 09:45:31 -0700 (PDT) Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> <6inkkiFrbptbU1@mid.uni-berlin.de> <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> <6iqr3dF3msoU1@mid.uni-berlin.de> Message-ID: On Sep 10, 2:04?pm, "Diez B. Roggisch" wrote: > luigi.pai... at gmail.com schrieb: > > > > > On 9 Set, 17:55, "Diez B. Roggisch" wrote: > >> I would go for a slightly different approach: make your server have a > >> dispatch-method that delegates the calls to the underlying actual > >> implementation. But *before* that happens, extract the information as > >> above, and either > > >> ?- prepend it to the argument list > > >> ?- stuff it into threadlocal variables, and only access these if needed in > >> your implementation. > > >> Diez > > > Are you suggesting me to overwrite the _dispatch(self, method, params) > > method of SimpleXMLRPCDispatcher? I thought to this possibility, but > > it only accepts "method" and "params" as arguments, so, as far as I > > know, I have no way to get the user and host address to append. > > > Perhaps I've misunderstood your suggestion... in that case can you > > post a short example? > > Ah, darn. Yes, you are right of course, the information itself is not > available, as you don't have access to the request. I gotta ponder this > a bit more. > > Diez Because he wants to insert parameters at the very start, he can probably get away with modifying the xml directly. Just find the position of the (i think thats the tag) and insert the xml you need after it. Its pretty dirty, but would work. The wire format isn't that complicated. From marek.rocki at wp.pl Sun Sep 28 05:32:42 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sun, 28 Sep 2008 02:32:42 -0700 (PDT) Subject: Calculating timespan References: Message-ID: <784049c7-a9cf-4006-873f-d3a869bf6b93@l64g2000hse.googlegroups.com> Erhard napisa?(a): > I've been looking at the date/time classes and I'm at a loss as to how > to do this (probably too used to other platforms). > > I have two date/time values. One represents 'now' and the other the last > modified time of a file on disk (from stat). I need to calculate the > difference in time (i.e., a 'timespan') between the two so I can tell if > the file has been modified in the past X minutes and do something to it. > > Thanks =) You can subtract one datetime object from another: from datetime import datetime, timedelta span = datetime.now() - datetime(year=2008,month=8,day=27,hour=12,minute=34,second=56) if span < timedelta(minutes=37): # do something From bdesth.quelquechose at free.quelquepart.fr Tue Sep 2 12:45:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Sep 2008 18:45:35 +0200 Subject: source for the property function In-Reply-To: References: Message-ID: <48bd899f$0$10446$426a74cc@news.free.fr> Rowland Smith a ?crit : > Anyone know where the source code for the built-in property function Actually, it's a class, not a function. > is > located in a python distribution? property being a builtin type, you should find it somewhere in the CPython's C source AFAICT. > I would like to see how it works - mainly, how does it know which class > it is being called from? No need to look at the source for this - it's just an application of the descriptor protocol. Look up the doc on python.org, or google for python descriptor protocol. FWIW, it's the same protocol that is used for turning functions into methods, and writing your own custom descriptors is trivial. HTH From pavlovevidence at gmail.com Sun Sep 28 05:29:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 28 Sep 2008 02:29:07 -0700 (PDT) Subject: Borg vs Singleton vs OddClass References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> Message-ID: <256d3ab0-6d8c-46b9-83a3-ea6817c67320@k37g2000hsf.googlegroups.com> On Sep 27, 2:12?pm, Lie wrote: > I'm thinking about this design pattern (I don't know if anyone has > ever thought of this pattern before): > > class OddClass(object): > ? ? def __init__(self): > ? ? ? ? global OddClass > ? ? ? ? OddClass = self > ? ? def __call__(): > ? ? ? ? return self > > The OddClass is a class that would overwrite its own class definition > at its first instantiation. OddClass defines __call__ so that > subsequent "instantiation" (technically it is no more an > instantiation, but Duck Typing says it does) of the class would return > the single instance. > > It do have a problem though, that you can't do isinstance(a, OddClass) > since the name OddClass no longer refers to the OddClass class > descriptor, but to an instance of OddClass. I recommend against your idiom above. The main issue I have about it is that it rebinds the symbol implicitly, which is almost always a bad idea. What if a user does something like "from oddclassmodule import OddClass"? Then the user will get a new instance every call since it never rebinds the imported symbol. Just don't do it this way. You could rewrite it like this to avoid the implicit rebinding, and to take care of the isinstance issue as well: class NotSoOddClass(object): def __new__(cls): self = getattr(cls,"_instance",None) if self is None: self = cls._instance = object.__new__(cls) return self Or you could just use a lazy factory function like this, where the user is only supposed to use Factory and not create the class directly: class _NotOddClass(object): # nothing odd def Factory(): obj = getattr(_NotOddClass,"_instance",None) if obj is None: obj = _NotOddClass._instance = NotOddClass() return obj If you're real kinky you can use a metaclass. There are reasons to prefer any of these. I'd recommend the factory function unless you think the users could significantly benefit from type inspection. Just don't do it by rebinding the class name. That's not nice. Carl Banks From dear.jay.logan at gmail.com Mon Sep 22 06:52:51 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 22 Sep 2008 03:52:51 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: <5a37d7ca-e7b4-4278-8fc3-f5d0f4303cee@79g2000hsk.googlegroups.com> On Sep 22, 3:41?am, Arnaud Delobelle wrote: > On 22 Sep, 04:05, josh logan wrote: > > > > > Hello, > > > I have 2 questions. Say I have this class: > > > class Player(object): > > ? ? def __init__(self, fname, lname, score): > > ? ? ? ? self.score = score > > ? ? ? ? self.fname = fname > > ? ? ? ? self.lname = lname > > ? ? def __cmp__(self, other): > > ? ? ? ? return (-cmp(self.score, other.score) or > > ? ? ? ? ? ? ? ? cmp(self.lname, other.lname) or > > ? ? ? ? ? ? ? ? cmp(self.fname, other.fname)) > > ? ? def __repr__(self): > > ? ? ? ? return 'Player(fname={0.fname}, lname={0.lname}, > > score={0.score})'.format(self) > > ? ? def __eq__(self, others): > > ? ? ? ? if isinstance(other, Player): > > ? ? ? ? ? ? return (self.score == other.score and > > ? ? ? ? ? ? ? ? ? ? self.lname == other.lname and > > ? ? ? ? ? ? ? ? ? ? self.fname == other.fname) > > ? ? ? ? return False > > ? ? def __ne__(self, others): > > ? ? ? ? return not self.__eq__(others) > > > fnames = ['Julie', 'Ben', 'Jason', 'David'] > > lnames = ['Parks', 'Smith'] > > scores = [100, 95, 95, 130, 58, 74] > > > import itertools as it > > > score_iter = it.cycle(scores) > > > P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in > > lnames] > > > cmp(P[0], P[1]) # returns -1 > > > sorted(P) # throws TypeError: unorderable types Player() < Player() > > > The sorted function works when I define __lt__. > > I must be misreading the documentation, because I read for the > > documentation __cmp__ that it is called if none of the other rich > > comparison functions are defined. > > Is this a bug in Python 3.0rc1, or am I missing something? > > > Secondly, say that we suddenly need another sorting order, where we > > want to sort by decreasing score and then by DECREASING last name > > (instead of increasing last name, defined above). Now that the > > comparison function argument is taken away from the sorted builtin, > > how do we accomplish this with the "key" parameter? > > > Thank you > > I don't know about __cmp__ but for the second part of the question you > can probably do: > > ? ? sorted(P, key=lambda p: (p.score, p.lname), reverse=True) > > HTH > > -- > Arnaud Thank you for the prompt reply. I didn't think my second question completely through. A better example would be sorting by increasing last name and decreasing first name. This would be easy with the sort function comparator, but I can't see how to do the same with the key argument. Is the only solution to decorate the Player objects in another class that has the appropriate __cmp__ function (or whatever is needed) and then retrieve the Player objects back? From Ron.Barak at lsi.com Wed Sep 10 07:58:36 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Wed, 10 Sep 2008 12:58:36 +0100 Subject: ImportError: No module named zipextimporter on py2exe when { "compressed": 0 } Message-ID: <7F0503CD69378F49BE0DC30661C6CCF601ADC07B@enbmail01.lsi.com> Hi, I'm trying to compile using py2exe, and am getting the following: $ python_win Setup.py py2exe running py2exe creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32 creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32\winexe creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32\winexe\collect-2.5 creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32\winexe\bundle-2.5 creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32\winexe\temp *** searching for required modules *** Traceback (most recent call last): File "Setup.py", line 96, in windows = [test_wx] File "C:\Python25\lib\distutils\core.py", line 151, in setup dist.run_commands() File "C:\Python25\lib\distutils\dist.py", line 974, in run_commands self.run_command(cmd) File "C:\Python25\lib\distutils\dist.py", line 994, in run_command cmd_obj.run() File "c:\Python25\lib\site-packages\py2exe\build_exe.py", line 228, in run self._run() File "c:\Python25\lib\site-packages\py2exe\build_exe.py", line 281, in _run self.find_needed_modules(mf, required_files, required_modules) File "c:\Python25\lib\site-packages\py2exe\build_exe.py", line 1202, in find_needed_modules mf.import_hook(mod) File "c:\Python25\lib\site-packages\py2exe\mf.py", line 716, in import_hook return Base.import_hook(self,name,caller,fromlist,level) File "c:\Python25\lib\site-packages\py2exe\mf.py", line 136, in import_hook q, tail = self.find_head_package(parent, name) File "c:\Python25\lib\site-packages\py2exe\mf.py", line 204, in find_head_package raise ImportError, "No module named " + qname ImportError: No module named zipextimporter My Setup.py (produced by GUI2Exe) is attached. Note that I set compressed to 0 in Setup.py (options = {"py2exe": {"compressed": 0), but it does not help. Any ideas ? Bye, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: Setup.py Type: application/octet-stream Size: 3285 bytes Desc: Setup.py URL: From sturlamolden at yahoo.no Thu Sep 25 08:31:13 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 05:31:13 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> Message-ID: <971aafb6-1d76-4a1d-8acd-1442ff3a60ae@2g2000hsn.googlegroups.com> On 25 Sep, 14:22, Duncan Booth wrote: > No Python's syntax is fine. The api's aren't as consistent though: > Microsoft added a common set of extension methods which work on > databases, xml, builtin sequences and can be easily extended to include > other custom sequences. That is correct, but it is a library issue and cannot be solved by adding new syntax. From python at rgbaz.eu Tue Sep 16 11:25:28 2008 From: python at rgbaz.eu (Python) Date: Tue, 16 Sep 2008 17:25:28 +0200 Subject: How do I add permanently to Pythons sys.path? In-Reply-To: References: Message-ID: On 16 sep 2008, at 17:13, cnb wrote: >>>> sys.path > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', > 'C:\ > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > \lib\\site-packages\\PIL'] >>>> > > Now I have my personal programs in C:/Python25/Progs/ > > How do I add so that I can just do "import somefile" from anywhere in > that directory in the interpreter and it can load files from other > folders in that directory. > -- > http://mail.python.org/mailman/listinfo/python-list > > a temp solution is to append it to that list: sys.path.append('C:/Python25/Progs/') a permanent solution is to add it to the environment variable (no idea where to set this in windows) $PYTHONPATH = "/C:/Python25/Progs/" gr Arno From roy at panix.com Sun Sep 28 09:25:56 2008 From: roy at panix.com (Roy Smith) Date: Sun, 28 Sep 2008 09:25:56 -0400 Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <00ef327d$0$20666$c3e8da3@news.astraweb.com> Message-ID: In article <00ef327d$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > from random import randint > ''.join(chr(randint(0, 255)) for i in xrange(len(input))) > > > of course. How else should you get random bytes? :) That a UUOL (Useless Usage Of Len; by analogy to UUOC). This works just as well: ''.join(chr(randint(0, 255)) for i in input) From karl.kobata at syncira.com Mon Sep 15 16:47:03 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Mon, 15 Sep 2008 13:47:03 -0700 Subject: ka-ping yee tokenizer.py Message-ID: <6u80qt$7o5lj6@rrcs-agw-02.hrndva.rr.com> I have enjoyed using ka-ping yee's tokenizer.py. I would like to replace the readline parameter input with my own and pass a list of strings to the tokenizer. I understand it must be a callable object and iteratable but it is obvious with errors I am getting, that this is not the only functions required. Being new to python, I am looking for help. 1) I would like to create a class called a. Class ReadStringList: b. I would like to pass this class a list. Each element of the list is a string. c. I would like to pass this .readline( ) as the 'readline' parameter for the tokenizer d. What functions other than __init__(self, inputList) and readline, will I need to write? e. Where can I find the definition requirements for these other functions required? f. Better yet, where can I find an example. Please help. NoviceToLinux -------------- next part -------------- An HTML attachment was scrubbed... URL: From mal at egenix.com Mon Sep 1 16:25:44 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 01 Sep 2008 22:25:44 +0200 Subject: (in memory) database In-Reply-To: References: Message-ID: <48BC4FC8.2040205@egenix.com> On 2008-08-31 15:15, mark wrote: > Hi there, > > I need to extract data from text files (~4 GB) on this data some > operations are performed like avg, max, min, group etc. The result is > formated and written in some other text files (some KB). > > I currently think about database tools might be suitable for this. I > would just write the import from the text files and ... the tool does > the rest. The only problem I can imagine is that this would not be > fast enough. But I would give it a shoot. > Unfortunately I have only some knowledge of SQLite which is not an > option here. > > Some additional requirements I can think of are: > - Python (I want to hone my programming skills too) > - Python-only (no C-lib) for simplicity (installation, portability). > Therefore SQLite is not an option > - must be fast > - I like SQL (select a, b from ...) this would be nice (row[..] + ... > is a little hard getting used to) > > So far I found PyDBLite, PyTables, Buzhug but they are difficult to > compare for a beginner. You could use Gadfly for this since it is pure Python and provides a standard Python DB-API interface: http://gadfly.sourceforge.net/ (the C extensions are optional to speedup processing) This is the SQL subset it supports: http://gadfly.sourceforge.net/sql.html Another option is SnakeSQL: http://pythonweb.org/projects/snakesql/ but I've never used that one, so can't judge its quality. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 01 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From notvalid2 at sbcglobal.net Mon Sep 1 11:50:43 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 01 Sep 2008 08:50:43 -0700 Subject: How Compute # of Days between Two Dates? In-Reply-To: References: Message-ID: Grant Edwards wrote: > On 2008-09-01, W. eWatson wrote: >> Grant Edwards wrote: >>> On 2008-09-01, W. eWatson wrote: >>> >>>> That's the question in Subject. For example, the difference between >>>> 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and >>>> 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in >>>> years between, say, 1990 and 2050. In other words not some really strange >>>> period of time well outside our current era of history. >>> Does the standard library's datetime module not do what you want? >>> >>> http://docs.python.org/lib/module-datetime.html >>> >> Yes, it would seem so. This works fine. > > It would probably be worth your while to read through one of > introductory Python books or just browse through the Python > tutorial: > > http://docs.python.org/tut/ Oddly, Leaning Python has no mention of datetime (not date or time), at least, that I could find. I'm considering the Nutshell book, 2nd ed., as a better reference (and cross reference) to various topics. > >> I was pondering this in pyfdate, but perhaps missed it or it >> was not obvious to me in the tutorial for some reason. > > Sorry, can't help you there -- I've never heard of pyfdate. The > timedate module that comes with Python has always done what I > needed to do with dates/times. > -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From namekuseijin at gmail.com Mon Sep 29 23:48:22 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Mon, 29 Sep 2008 20:48:22 -0700 (PDT) Subject: PYTHON WORKING WITH PERL ?? References: Message-ID: On 29 set, 14:16, "Blubaugh, David A." wrote: > To All, > > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? ?Such as > utilizing python for internet programming and then utilize perl for text > processing and systems programming? ?Is this even feasible??? Python + Perl is called Ruby. ;) From rcdailey at gmail.com Fri Sep 5 16:12:25 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 15:12:25 -0500 Subject: Need formatting suggestion for long strings In-Reply-To: <20080905192934.29191.496947365.divmod.quotient.22130@ohm> References: <496954360809051224i66123029s23a5ab2f02d8be2b@mail.gmail.com> <20080905192934.29191.496947365.divmod.quotient.22130@ohm> Message-ID: <496954360809051312l4e71dfdfja770f5e62007dbe1@mail.gmail.com> On Fri, Sep 5, 2008 at 2:29 PM, Jean-Paul Calderone wrote: > mystring = ( > "This is a very long string that " > "spans multiple lines and does " > "not include line breaks or tabs " > "from the source file between " > "the strings partitions.") At first glance it looks like this is making a tuple. I didn't know this was legal! But, this is definitely what I was looking for (Assuming it works). Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Mon Sep 22 08:41:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Sep 2008 05:41:47 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> Message-ID: <4c9d12f9-a682-40d6-95a2-4b1eb3a11850@k37g2000hsf.googlegroups.com> On 22 Sep, 10:32, Steven D'Aprano wrote: > but it isn't good enough if the function needs to refer to it's own > state, because functions can only refer to themselves by name and the > factory can't know what name the function will be bound to. > > As far as I know, the only objects that know how to refer to themselves > no matter what name they have are classes and instances. And instances > share at least some state, by virtue of having the same class. Here is a simple way to make a function able to refer to its own state: def bindfunction(f): def bound_f(*args, **kwargs): return f(bound_f, *args, **kwargs) bound_f.__name__ = f.__name__ return bound_f >>> @bindfunction ... def foo(me, x): ... me.attr.append(x) ... return me.attr ... >>> foo.attr = [] >>> foo(3) [3] >>> foo(5) [3, 5] >>> -- Arnaud From rschroev_nospam_ml at fastmail.fm Wed Sep 10 15:06:39 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 10 Sep 2008 21:06:39 +0200 Subject: Reading binary data In-Reply-To: <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> References: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> Message-ID: <3VUxk.62$S64.4@newsfe09.ams2> Aaron Scott schreef: > Sorry, I had posted the wrong error. The error I am getting is: > > struct.error: unpack requires a string argument of length 12 > > which doesn't make sense to me, since I'm specifically asking for 11. That's because of padding. According to the docs, "By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler)". That means that struct.unpack() assumes one byte of padding between the 3-character string and the first unsigned int. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From malaclypse2 at gmail.com Mon Sep 15 16:50:18 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 15 Sep 2008 16:50:18 -0400 Subject: append on lists In-Reply-To: References: Message-ID: <16651e80809151350v3e425209h9d240b1b273c8c3c@mail.gmail.com> On Mon, Sep 15, 2008 at 4:45 PM, Armin wrote: > Yes, but this is very unconvenient. > If d should reference the list a extended with a single list element > you need at least two lines You do it in two lines, because you're doing two different things. > a.append(7) This appends the element 7 to the list a. > d=a This binds the name d to the same list as a is bound to. If you wand d to point to a new list with the same contents as the list a, plus the number 7 do this: d = a + [7] Here's an example of the difference: >>> a = range(6) >>> a [0, 1, 2, 3, 4, 5] >>> a.append(7) >>> a [0, 1, 2, 3, 4, 5, 7] >>> d = a >>> d [0, 1, 2, 3, 4, 5, 7] >>> d.append(10) >>> a [0, 1, 2, 3, 4, 5, 7, 10] >>> d [0, 1, 2, 3, 4, 5, 7, 10] >>> See how a and d are two names bound to the same list? Here's the other way: >>> a = range(6) >>> d = a + [7] >>> a [0, 1, 2, 3, 4, 5] >>> d [0, 1, 2, 3, 4, 5, 7] >>> d.append(10) >>> a [0, 1, 2, 3, 4, 5] >>> d [0, 1, 2, 3, 4, 5, 7, 10] >>> -- Jerry From larry.bates at vitalEsafe.com Tue Sep 9 18:44:23 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 09 Sep 2008 17:44:23 -0500 Subject: dynamic allocation file buffer In-Reply-To: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> Message-ID: castironpi wrote: > I will try my idea again. I want to talk to people about a module I > want to write and I will take the time to explain it. I think it's a > "cool idea" that a lot of people, forgiving the slang, could benefit > from. What are its flaws? > > A user has a file he is using either 1/ to persist binary data after > the run of a single program (persistence) or 2/ share binary data > between concurrently running programs (IPC / shared memory). The data > are records of variable types and lengths that can change over time. > He wants to change a record that's already present in the file. Here > are two examples. > > Use Case 1: Hierarchical ElementTree-style data > > A user has an XML file like the one shown here. > > > > Foo > > ... > > He wants to change "Foo" to "Foobar". > > > > Foobar > > ... > > The change he wants to make is at the beginning of a 4GB file, and > recopying the remainder is an unacceptable resource drain. > > Use Case 2: Web session logger > > A tutor application has written a plugin to a webbrowser that records > the order of a user's mouse and keyboard activity during a browsing > session, and makes them concurrently available to other applications > in a suite, which are written in varying lanugages. The user takes > some action, such as surfing to a site or clicking on a link. The > browser plugin records that sequence into shared memory, where it is > marked as acknowledged by the listener programs, and recycled back > into an unused block. URLs, user inputs, and link text can be of any > length, so truncating them to fit a fixed length is not an option. > > Existing Solutions > > - Shelve - A Python Standard Library shelf object can store a random > access dictionary mapping strings to pickled objects. It does not > provide for hierarchical data stores, and objects must be unpickled > before they can be examined. > - Relational Database - Separate tables of nodes, attributes, and > text, and the relations between them are slow and unwieldy to > reproduce the contents of a dynamic structure. The VARCHAR data type > still carries a maximum size, no more flexible than fixed-length > records. > - POSH - Python Object Sharing - A module currently in its alpha stage > promises to make it possible to store Python objects directly in > shared memory. In its current form, its only entry point is 'fork' > and does not offer persistence, only sharing. See: > http://poshmodule.sourceforge.net/ > > Dynamic Allocation > > The traditional solution, dynamic memory allocation, is to maintain a > metadata list of "free blocks" that are available to write to. See: > http://en.wikipedia.org/wiki/Dynamic_memory_allocation > http://en.wikipedia.org/wiki/Malloc > http://en.wikipedia.org/wiki/Mmap > http://en.wikipedia.org/wiki/Memory_leak > The catch, and the crux of the proposal, is that the metadata must be > stored in shared memory along with the data themselves. Assuming they > are, a program can acquire the offset of an unused block of a > sufficient size for its data, then write it to the file at that > offset. The metadata can maintain the offset of one root member, to > serve as a 'table of contents' or header for the remainder of the > file. It can be grown and reassigned as needed. > > An acquaintence writes: It could be quite useful for highly concurrent > systems: the overhead involved with interprocess communication can be > overwhelming, and something more flexible than normal object > persistence to disk might be worth having. > > Python Applicability > > The usual problems with data persistence and sharing apply. The > format of the external data is only established conventionally, and > conversions between Python objects and raw memory bytes take the usual > overhead. 'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' > currently offer this functionality, and the buffer offset obtained > from 'alloc' can be used with all three. > > Ex 1. > s= struct.Struct( 'III' ) > x= alloc( s.size ) > s.pack_into( mem, x, 2, 4, 6 ) > Struct in its current form does not permit random access into > structure contents; a user must read or write the entire converted > strucutre in order to update one field. Alternative: > s= struct.Struct( 'I' ) > x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) > s.pack_into( mem, x1, 2 ) > s.pack_into( mem, x2, 4 ) > s.pack_into( mem, x3, 6 ) > > Ex 2. > class Items( ctypes.Structure ): > _fields_= [ > ( 'x1', ctypes.c_float ), > ( 'y1', ctypes.c_float ) ] > x= alloc( ctypes.sizeof( Items ) ) > c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents > c.x1, c.y1= 2, 4 > The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. > > Ex 3. > s= pickle.dumps( ( 2, 4, 6 ) ) > x= alloc( len( s ) ) > mem[ x: x+ len( s ) ]= s > 'dumps' is still slow and nor does permit random access into contents. > > Use Cases Revisited > > Use Case 1: Hierarchical ElementTree-style data > Solution: Dynamically allocate the tree and its elements. > > Node: tag: a > Node: tag: b > Node: tag: c > Node: text: Foo > > The user wants to change "Foo" to "Foobar". > > Node: tag: a > Node: tag: b > Node: tag: c > Node: text: Foobar > > Deallocate 'Node: text: Foo', allocate 'Node: text: Foobar', and store > the new offset into 'Node: tag: c'. Total writes 6 bytes 'foobar', a > one-word offset, and approximatly 5- 10-word metadata update. > > Use Case 2: Web session logger > Dynamically allocate a linked list of data points. > > Data: 'friendster.com' > Data: 'My Account' > > Allocate one block for each string, adding it to a linked list. As > listeners acknowledge each data point, remove it from the linked > list. Keep the head node in the 'root offset' metadata field. > > Restrictions > > It is not possible for persistent memory to refer to live memory. Any > objects it refers to must also be located in file. Their mapped > addresses must not be stored, only their offsets into it. However, > live references to persistent memory are eminently possible. > > Current Status > > A pure Python alloc-free implementation based on the GNU PAVL tree > library is on Google Code. It is only in proof-of-concept form and > not commented, but does contain a first-pass test suite. See: > http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk > The ctypes solution for access is advised. You should review Zope's ZODB and/or memcached before putting in too much effort. -Larry From dickinsm at gmail.com Thu Sep 25 07:02:49 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 25 Sep 2008 04:02:49 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> Message-ID: <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> On Sep 23, 1:58?pm, Robert Lehmann wrote: > I don't see why transitivity should apply to Python objects in general. Hmmm. Lack of transitivity does produce some, um, interesting results when playing with sets and dicts. Here are sets s and t such that the unions s | t and t | s have different sizes: >>> from decimal import Decimal >>> s = set([Decimal(2), 2.0]) >>> t = set([2]) >>> len(s | t) 2 >>> len(t | s) 1 This opens up some wonderful possibilities for hard-to-find bugs... Mark From cbabcock at kolonelpanic.org Thu Sep 18 15:52:48 2008 From: cbabcock at kolonelpanic.org (Chris Babcock) Date: Thu, 18 Sep 2008 12:52:48 -0700 Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> Message-ID: <20080918125248.6ff8c402@mail.asciiking.com> > >> Traceback (most recent call last): > >> File "mail5.py", line 21, in > >> session = smtplib.SMTP(SMTPserver,port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > >> (code, msg) = self.connect(host, port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > >> self.sock.connect(sa) > >> File "", line 1, in connect > >> then conncetion time out..... > > > > Could it be your ISP is blocking outgoing connections to port > > 25? > > gmail doesn't accept mail via SMTP on port 25. So what is the value of "port" when you are running this program? Chris From frankrentef at yahoo.com Wed Sep 3 13:21:29 2008 From: frankrentef at yahoo.com (frankrentef) Date: Wed, 3 Sep 2008 10:21:29 -0700 (PDT) Subject: Using strftime Message-ID: <4841b103-be8c-471f-8903-1b9284bd3a39@k13g2000hse.googlegroups.com> I have one line of code that put's an old date in my code. ie.textBoxSet('_ct10_PlaceHolder_txtEnd', '8/15/2008') What I wish to do in another similiar line is have the field populated with the current system date? How best to do this? I've read some of the strftime documentation but as of yet I'm unable to get it to work correctly. Help is appreciated. THNX From sh006d3592 at blueyonder.co.uk Sun Sep 14 16:28:19 2008 From: sh006d3592 at blueyonder.co.uk (Stephen Horne) Date: Sun, 14 Sep 2008 21:28:19 +0100 Subject: Abstract class (irrelevant blethering) References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <48CD62B8.7070708@islandtraining.com> Message-ID: On Sun, 14 Sep 2008 21:19:06 +0200, Mr.SpOOn wrote: >I started to think to abstract classes just because in the paper it >uses an abstract class in SmallTalk. FWIW, it was obvious to me that you was using the term "abstract" in the wider sense. You did say about the Smalltalk paper, after all. And to me, any Python class that you treat as abstract is abstract. That was always how the word "abstract" was used by Python users in the past. Now, it seems that there's a specific Python feature to enforce abstractness. That's nice to know, and I'll have to do some reading. As I said elsewhere, my Python's getting a bit rusty. But I doubt I'll use it for the "overkill" reason. To me, the last important feature added to Python was conditional expressions in 2.5 IIRC, and while I love some features that others see as bloat, there's a lot that came in earlier versions that I'm never likely to use. For example, to me the term "property" is basically a trivial design pattern or an object-oriented principle. I don't really see the need for the language feature. I can define getter and setter methods all by myself, and I don't really see the benefit of disguising them as member variables. I used to like the idea, but now I'm more of an occasional Python user, I can't be bothered looking up the syntax. It's a strange role reversal - I used to be very enthusiatic about new features back when others kept saying Python 1.5 is all you need. From mail at timgolden.me.uk Fri Sep 12 08:39:02 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 13:39:02 +0100 Subject: testing if another instance of a script is already running In-Reply-To: <48CA6211.8050402@timgolden.me.uk> References: <48CA5BA5.8020709@p0w.org> <48CA6211.8050402@timgolden.me.uk> Message-ID: <48CA62E6.40106@timgolden.me.uk> Tim Golden wrote: > Strato wrote: >> Hi folks, >> >> I want to write some kind of test to check at startup if another >> instance of my script is already running. >> >> I don't want to handle writing of a PID file because it is too >> Unix/Linux specific way to do this, and I need to keep the code to be >> cross-platform. >> >> I think the better way to achieve this is to use some process control, >> but I'm a neebie and I don't see how to do this in a safe and clean way. > > There's nothing built in to Python to do this, so you'll > probably have to roll your own cross-platformness. Of > course, there's nothing to stop you from writing pid > files under Windows even if it's not the usual way. > Or you could just put some conditional code, and use > the kernel mutex under Windows, which is the generally > recommended technique. Have a look at this thread, > for example (among several others): > > http://mail.python.org/pipermail/python-list/2005-June/327063.html Sorry, not the best of links to point to. Basically, search mail.python.org for things like "CreateMutex" and "single application instance". TJG From gagsl-py2 at yahoo.com.ar Tue Sep 16 00:56:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 01:56:41 -0300 Subject: catching exceptions from fortran References: Message-ID: En Mon, 15 Sep 2008 10:04:27 -0300, john escribi?: [trying to catch exceptions when reading a file in Fortran code using f2py] > i agree with everything you write, but unless i misunderstood > something, this still doesn't address the main problem of the try- > except construct not preventing the program from aborting when the > wrapped fortran code encounters an error. i tried hard-coding all of > the passed variables to the fortran code and ran that code alone-- > works. however, when an incorrect fortran read is attempted (ex. > formatted read on unformatted file), the python except still fails to > catch the error and the code aborts with a runtime error... Looks like the error isn't mapped onto a Python exception, and is handled directly in the Fortran code; better to find a f2py group to ask then. Perhaps you have to catch those errors on the Fortran side. I barely remember doing things like READ(..., IOSTAT=IO)... -- Gabriel Genellina From RedGrittyBrick at spamweary.invalid Tue Sep 2 06:11:09 2008 From: RedGrittyBrick at spamweary.invalid (RedGrittyBrick) Date: Tue, 02 Sep 2008 11:11:09 +0100 Subject: The Importance of Terminology's Quality In-Reply-To: References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: <48bd1141$0$26092$db0fefd9@news.zen.co.uk> George Neuner wrote: > On Mon, 1 Sep 2008 21:03:44 +0000 (UTC), Martin Gregorie > wrote: > >> On Mon, 01 Sep 2008 12:04:05 -0700, Robert Maas, http://tinyurl.com/uh3t >> wrote: >> >>>> From: George Neuner A friend of mine had an >>>> early 8080 micros that was programmed through the front panel using >>>> knife switches >>> When you say "knife switches", do you mean the kind that are shaped like >>> flat paddles? >>> >> Pedantic correction: >> >> "Knife switch" is the wrong term. These are high current switches, >> typically used in the sort of heavy duty circuit where the wiring hums >> when power is on or in school electrical circuits so even the back of the >> class can see whether the switch is open or closed. In these a copper >> 'blade' closes the contact by being pushed down into a >> narrow, sprung U terminal that makes a close contact with both sides of >> the blade. Like this: http://www.science-city.com/knifeswitch.html >> >> What you're talking is a flat handle on a SPST or DPST toggle switch. It >> is often called a paddle switch and mounted with the flats on the handle >> horizontal. Like this, but often with a longer handle: >> http://www.pixmania.co.uk/uk/uk/1382717/art/radioshack/spdt-panel-mount- >> paddle-s.html > > I don't know the correct term, but what I was talking about was a tiny > switch with a 1/2 inch metal handle that looks like a longish grain of > rice. We used to call them "knife" switches because after hours > flipping them they would feel like they were cutting into your > fingers. > That must be a toggle switch (as MG suggested) just not the paddle type. e.g. -- RGB From aioe.org at technicalbloke.com Wed Sep 17 12:46:33 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 12:46:33 -0400 Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> Message-ID: Michael Palmer wrote: > On Sep 15, 3:04 pm, Matias Surdi wrote: >> aditya shukla escribi?: >> >>> How can we convert .py files to batch files? is there any library for this? >>> Aditya >>> ------------------------------------------------------------------------ > On Linux, you would instead insert the shebang line that points to > your python interpreter, such as > > #!/usr/bin/python > > at the top and also set the executable bit, but I suppose if you use > Linux at all you know that. Doh! I'm new to Linux and so I didn't know that, thanks! One small snag though, it doesn't work on my system :-( I did both steps, the shebang and the execute bit but nada... r0g at steppa:~/Desktop/py$ ls kickstart.py kickstart.py~ kicktest.py kicktest.py~ r0g at steppa:~/Desktop/py$ kickstart.py bash: kickstart.py: command not found Any ideas why this might be? A path thing? I'm on Ubuntu 8.04 / Py2.5 Thanks, Roger. From mauriceling at gmail.com Tue Sep 23 09:56:49 2008 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Tue, 23 Sep 2008 06:56:49 -0700 (PDT) Subject: Call for Papers, Volume 3 Issue 3 Message-ID: We would like to call for papers, articles, opinion pieces and feedback to include in Volume 3, Issue 3 of The Python Papers. We would love to receive articles on Python for beginners and discussions about Python performance. Any article will be gratefully received, of course, so do not let the above list of suggestions deter you from considering an article on another topic. We also need volunteers from Python User Groups to include an article on the activities, members and geographical area of their local group. Expressions of Interest Close: Friday, 14 November Initial Draft Submission Deadline: Friday, 21 November Editorial Process Concludes (i.e. Final Version Due): Monday, 15 December PDF Release Date: Sunday, 4th January (approximate) If you are considering submitting an article, please let us know A.S.A.P., even if you are only thinking about it. This will allow us to post email reminders of important dates to prospective authors, as well as giving us an indication of content. If you are unable to submit an article according to the schedule above, please let us know of your interest anyway, and we will involve you in the publication cycle for the following edition. Contact us at editor at pythonpapers.org Thanks, -Maurice Ling Co-Editor In Chief, The Python Papers From tjreedy at udel.edu Sun Sep 28 03:46:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 03:46:57 -0400 Subject: closures and dynamic binding In-Reply-To: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: > Hello all, > > To me, this is a somewhat unintuitive behavior. I want to discuss the > parts of it I don't understand. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= lambda: n This is equivalent to for n in range(10): def g(): return n f[n] = g which is equivalent to def g(): return n f = [g]*10 n = 9 >>>> f[0]() > 9 >>>> f[1]() > 9 which make this not so surprising as the original lambda version is to some people. > I guess I can accept this part so far, though it took a little getting > used to. I'm writing some code and found the following workaround, > but I don't think it should give different results. Maybe I'm not > understanding some of the details of closures. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= (lambda n: ( lambda: n ) )( n ) This is equivalent to for n in range(10): def g(n): def h: return n return h f[n] = g(n) Now, to avoid the needless confusion of 'n's, g is equivalent to def g(x): def h: return x return h (One could do the same change in the lambdas, too, of course). so that g(n)() == n, with n stored in each closure h... > ... >>>> f[0]() > 0 >>>> f[1]() > 1 to be regurgitated when each is called. Terry Jan Reedy From dadapapa at googlemail.com Wed Sep 17 06:53:24 2008 From: dadapapa at googlemail.com (Harold Fellermann) Date: Wed, 17 Sep 2008 03:53:24 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> Message-ID: <10b2535d-9a88-43c4-ae73-9baa382edb74@m44g2000hsc.googlegroups.com> > > http://wiki.python.org/moin/NumericAndScientific/Libraries > > > > Scroll down. > > Yes, many of those seem to be deprecated, without destinations to > links, most are poorly or not documented at all. The few that are, I > still can't get running. Of those 254, I think I have tried at least > 10 pages worth. Still no luck. > > # lpsolvpy - Can't get it to compile - dependency problems. > # Lp_solve5 - NO python binding yet. Volunteers needed for python > bindings. > # pycplex - You need to compile the CPX.so module. Change the required > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > sure what to do here. > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > I missed the second link to the python bindings, looked all over the > glpk site for anything about python. > # SciPy -- http://www.scipy.org - supposedly has this, but as I said, > I can't find any mention of it anywhere but on the site you linked. > # pySimplex - (broken link)(broken link) > # Simplex - link is broken, but nothing is mentioned > > I'll take a closer look at glpk's python bindings and if there is any > documentation on them, maybe I'll have some luck. btw, I have been > looking for something that works, I have over 5 packages on my desktop > that I have tried to get up and running, but none of them seem to > work. glpk makes 6. You are right that this is an unsatisfying experience. Fortunately, the referred site is a wiki. Why don't you edit it and delete the broken links or add the package that did the job for you to the list, so that others do not need to go through the same hassle. - harold - From gh at ghaering.de Mon Sep 8 07:56:43 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 08 Sep 2008 13:56:43 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: <6ikc76Fr32cnU1@mid.uni-berlin.de> References: <6ii9jbFqoe2eU1@mid.uni-berlin.de> <6ikc76Fr32cnU1@mid.uni-berlin.de> Message-ID: Matthias Huening wrote: > Gerhard H?ring (08.09.2008 10:12): >> >>> Error is: >>> >>> con.execute("select load_extension('./fts3.so')") >>> pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht >>> gefunden. >>> >>> Where should I look for the module? >> >> The sources are in ext/fts3 in the SQLite source tree. I haven't found >> any Makefile, so I it myself using this gcc command: >> >> $ cd .../ext/fts3 >> $ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so >> *.c -lsqlite3 > > Thanks! > Will fts3 be integrated in the Python 2.6 release? No (only relevant on win32, where we also ship the SQLite DLL). Neither will be the ability to load extensions modules. It's just too late to add features now. But AFAIK it's possible to compile a custom SQLite with appropriate flags to ./configure that will include the fulltext search extension. -- Gerhard From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 02:49:05 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Mon, 15 Sep 2008 23:49:05 -0700 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: References: Message-ID: <48CF56E1.4020402@comcast.net> > On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal wrote: >> I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that >> key as string. Is there any way to convert the said instance into string? Take a look at as_pem() method. -- Heikki Toivonen From ndbecker2 at gmail.com Tue Sep 23 19:52:28 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 23 Sep 2008 19:52:28 -0400 Subject: python syntax for conditional is unfortunate Message-ID: In hindsight, I am disappointed with the choice of conditional syntax. I know it's too late to change. The problem is y = some thing or other if x else something_else When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). Particularly if 'some thing or other' is long or complicated. From earlsoliloquyji at googlemail.com Mon Sep 22 07:21:25 2008 From: earlsoliloquyji at googlemail.com (earlsoliloquyji at googlemail.com) Date: Mon, 22 Sep 2008 04:21:25 -0700 (PDT) Subject: assdumper - for Free Message-ID: <058c8edf-7749-4dc8-ac74-ab9921e0ecba@x41g2000hsb.googlegroups.com> assdumper . . . *******CLICK HERE******** http://vids365.cn/assdumper ***************************** . . . . . . . . . . . . assdumper From vs at it.uu.se Tue Sep 16 02:29:03 2008 From: vs at it.uu.se (Virgil Stokes) Date: Tue, 16 Sep 2008 08:29:03 +0200 Subject: Python GUI for animation Message-ID: <48CF522F.40402@it.uu.se> I have been using Python for a short time and I find it a very flexible language, and easy to learn and use. I have also worked some with PyGame and used it to create a simple animation that is controlled by the mouse and keyboard. The animation is designed to move filled circles around on the screen and is driven by a data file that defines (indirectly), the next relative position of each circle. And for my purposes (queueing demo in the classroom) this works quite well. However, I would now like to create a Python GUI that would allow a user to control the animation, via buttons, sliders, etc. I am certainly not a Python expert and have never worked with the creation of a GUI. I would appreciate greatly any advice from those who have worked with Python GUIs as to the best way to proceed. Thank you in advance, V. Stokes From google at mrabarnett.plus.com Fri Sep 12 20:54:21 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Sep 2008 17:54:21 -0700 (PDT) Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <00da5aca$0$2879$c3e8da3@news.astraweb.com> Message-ID: On Sep 12, 11:15?pm, Matt Nordhoff wrote: > Steven D'Aprano wrote: > > On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote: > > >> When mail messages bounce, the MTA (Message Transfer Agent--the program > >> that handles mail) *should* send the bounce message to whatever is in > >> the Sender header, and only if that header does not exist, should it use > >> the From header. > > > Who makes up these rules, and why should we pay the least bit of > > attention to them? > > > It's one thing to say "right or wrong, that's what list admins do and you > > have to deal with their behaviour whatever way you can". It's another > > thing altogether to take the legalistic attitude of "never mind the > > consequences, the standard is the standard and must be unthinkingly > > obeyed". If the standard does more harm than good, then ignoring the > > standard is the right thing to do. (Better would be to change the > > standard, but that probably won't happen until there's a critical mass of > > people who ignore the existing broken standard and form their own de > > facto standard.) > > > A standard isn't "correct" just because it's a standard, it's merely > > something that a committee has agreed to do. In other words, it's a > > compromise. Now, such compromises might be good and useful, or they might > > combine the worst of all opinions. Just because something is standardized > > doesn't make it the right thing to do. If you want proof of this, I give > > you the recently approved ISO standard for Microsoft's so-called "Office > > Open XML" OOXML file format. > > > The standard behaviour of sending bounce and out-of-office messages to > > the sender works well when sending email to individuals, but for mailing > > lists it is pointless and counter-productive. Pointless, because the > > sender can't do anything to fix the problem he's being notified about. > > And counter-productive, because it is an anti-feature, something that > > makes the mailing list more unpleasant and less useful. Anyone who has > > regularly emailed to a large mailing list has surely experienced the > > frustration of receiving bounce messages from perfect strangers. > > > To anyone who wishes to defend the process of sending mailing list > > bounces back the sender, ask yourself this: what do YOU do with such > > bounces when you receive them? If you ignore them or delete them (whether > > manually or via a procmail recipe or some other automatic system) then > > what benefit does the standard behaviour offer? > > I think you misunderstand. He's referring to the Sender header, not the>From header. The messages the listbot sends out have a Sender header of > > "python-list-bounces+user=example.... at python.org" (supposing the > subscriber's email address is u... at example.com). Bounces should be > directed to the bitbucket or list admin or whatever, not the user in the>>From header. kring.com just has a broken mail server. > Ah, kring.com. I've been receiving bounces from there as well since Wednesday. I just added it to my spam blacklist and forgot about it. I'm just wondering what would happen if someone posted from there... :-) From gandalf at shopzeus.com Mon Sep 8 13:18:51 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Sep 2008 19:18:51 +0200 Subject: universal unicode font for reportlab In-Reply-To: <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> References: <87r67vj7f1.fsf@benfinney.id.au> <48C51E49.2070202@shopzeus.com> <48C52635.1030709@shopzeus.com> <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <48C55E7B.9090807@shopzeus.com> Iain Dalton wrote: > Why don't you want to use multiple typefaces? Many programs that deal > with multilingual strings use multiple fonts (cf. any Web browser and > Emacs). > You are right, but these PDF documents will show mixed strings. The end user can enter arbitrary strings into the database, and they must be presented. For example, the name of a product can be arabic or german. It might be possible to guess the language used from the unicode string, and then select a different font. But I don't want to go into that trouble. It would be a great idea to use pango. Apparently pango is able to change fonts on the fly and render the requested glyph. However, if I use pango then I loose the much higher level of abstraction that comes with reportlab and platypus: I need automatic page headers and footers, I need to be able to repeat table headers on each page automatically (when the table doesn't fit one page) etc. Developing my own "platypus" like engine for pango and PDF rendering is a nightmare. Better than that, I can develop my own flowable object for platypus: a special paragraph that changes the used true type font on the fly. (Split input string into parts, determine language for the parts and display each part with its own font.) But of course this is a lot of extra programming. The simplest solution would be to use a font that is able to handle all encodings that I need. Thanks, Laszlo From steven at REMOVE.THIS.cybersource.com.au Fri Sep 26 03:27:42 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 07:27:42 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: On Thu, 25 Sep 2008 21:17:14 -0700, Aahz wrote: > Seems to me that if all the module is used for is to store state, you're > wasting a file on disk. I personally prefer to use a class singleton. I don't recognise the term "class singleton". Can you explain please? How is it different from an ordinary singleton? For the record, I ended up deciding that I didn't need any special objects or metaclass programming, just a factory function which returned a regular instance. But reading the thread has been a good education for me, thanks folks. -- Steven From lixinyi.23 at gmail.com Mon Sep 22 22:32:46 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Mon, 22 Sep 2008 19:32:46 -0700 (PDT) Subject: How do I convert a PyObject to string in C++? Message-ID: I have a PyObject, say 'Hello World' , a string, How do I convert it to a string in C++? Thanks in advance! From grante at visi.com Tue Sep 30 11:57:19 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Sep 2008 10:57:19 -0500 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: On 2008-09-30, Peter Pearson wrote: > On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: >> >> 1. Multi dimensional arrays - how do you load them in python >> For example, if I had: >> ------- >> 1 2 3 >> 4 5 6 >> 7 8 9 >> >> 10 11 12 >> 13 14 15 >> 16 17 18 >> ------- >> with "i" being the row number, "j" the column number, and "k" the .. >> uhmm, well, the "group" number, how would you load this ? >> >> If fortran90 you would just do: >> >> do 10 k=1,2 >> do 20 i=1,3 >> >> read(*,*)(a(i,j,k),j=1,3) >> >> 20 continue >> 10 continue >> >> How would the python equivalent go ? You would drag yourself out of the 1960s, install numpy, and then do something like this: a = read_array(open("filename.dat","r")) > Since you're coming from the FORTRAN world (thank you for that > stroll down Memory Lane), you might be doing scientific > computations, and so might be interested in the SciPy package > (Google scipy), which gives you arrays and matrices. Don't > expect to be able to use it without learning some Python, > though. If not full-up scipy (which provides all sorts of scientific and numerical-analysis stuff), then at least numpy (which provides the basic array/matrix operations: http://numpy.scipy.org/ Though the software is free, the documentation isn't. You've got to buy the book if you want something to read. IMO, it's definitely worth it, and a good way to support the project even if you don't really need something to keep your bookends apart. Scientific Python is something else the OP might be interested in. Yes, Scientific Python is different than SciPy: http://dirac.cnrs-orleans.fr/plone/software/scientificpython/overview/ If you're a Windows user, I can recommend the Enthough Python distribution. It has all sorts of numerical and scientific "batteries included". http://www.enthought.com/products/epd.php It includes both scipy and scientific python as well as several options for data visualization (e.g. matplotlib, VTK). There's also an Enthought Python distro for Linux, but I've never tried it. I run Gentoo Linux, and there are standard ebuilds for pretty much all of the stuff in EPD. -- Grant Edwards grante Yow! I've read SEVEN at MILLION books!! visi.com From jinbow at gmail.com Sun Sep 7 18:41:53 2008 From: jinbow at gmail.com (Mars creature) Date: Sun, 7 Sep 2008 15:41:53 -0700 (PDT) Subject: Read and write binary data Message-ID: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Hi guys, I am new to Python, and thinking about migrating to it from matlab as it is a really cool language. Right now, I am trying to figure out how to control read and write binary data, like 'formatted','stream','big-endian','little-edian' etc.. as in fortran. I googled, but can not find a clear answer. Anyone has clue where can I learn it? Thanks!! Jinbo From namekuseijin at gmail.com Tue Sep 23 14:48:33 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Tue, 23 Sep 2008 11:48:33 -0700 (PDT) Subject: Python is slow? References: Message-ID: <8a149a96-74ae-4eff-9669-31a1fa61d6a2@79g2000hsk.googlegroups.com> On Sep 23, 10:57?am, Grant Edwards wrote: > AFAICT, _everybody_ is bad at programming C++. Thankfully, at least Numpy developers are not bad at C programming. From ewertman at gmail.com Fri Sep 5 16:58:26 2008 From: ewertman at gmail.com (Eric Wertman) Date: Fri, 5 Sep 2008 16:58:26 -0400 Subject: Need formatting suggestion for long strings In-Reply-To: <496954360809051315v44438624vf16240216d8ba2c5@mail.gmail.com> References: <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> <496954360809051315v44438624vf16240216d8ba2c5@mail.gmail.com> Message-ID: <92da89760809051358k7c5ed12enb755efee45f42f37@mail.gmail.com> > I'm concerned about the formatting of the string in that I do not want the > way I split the string up in source code to affect the way the string is > displayed to the console. In other words, in source, if I break up a single > string into multiple lines (using carriage returns), I would expect the > string to still render as a single-line string. > > I'm also concerned about the source formatting, because I do not want the > single-line string to run off the edge of my display. I want it to be in > "Paragraph form" in the source code, but remain a single-line when printed. I think you can also escape the line breaks: >>> mystring = ( ... "This is a very long string that " ... "spans multiple lines and does " ... "not include line breaks or tabs " ... "from the source file between " ... "the strings partitions.") >>> mystring2 = 'This is a very long string that spans multiple lines and does not include line breaks or tabs from the source file between the strings partitions.' >>> mystring == mystring2 True >>> mystring3 = 'This is a very long string that \ ... spans multiple lines and does not include line breaks \ ... or tabs from the source file between the strings \ ... partitions.' >>> mystring3 == mystring True From eekfunster at gmail.com Thu Sep 25 11:36:00 2008 From: eekfunster at gmail.com (EEK) Date: Thu, 25 Sep 2008 08:36:00 -0700 (PDT) Subject: PID management with popen and spawn Message-ID: <73195b54-8836-43f7-ba30-76eb408ccc4a@k37g2000hsf.googlegroups.com> Hello, My goal is to start and stop separate Linux processes from a python program by specific PID. The output of these processes needs to have their stderr and stdout piped to a particular file, respectively. I've been able to make this work with subprocess.Popen only if the shell variable is set to False but I cannot pipe the outputs of the targets. When using subprocess.Popen with shell=True, I believe the returned PID is of the shell that opens the target process, not the target process itself. Therfore, I cannot stop the target process for the returned PID is not of that process. Spawn will work better but I need the target application to pipe it's stderr and stdout to a file. Here I have troubles. Any help appreciated. prgm = program I want to run (compiled C) logfile = file I want to pipe output to What I need to do based on a simple shell call: program >& logfile (yes, that's it) proc = subprocess.Popen("program >& logfile", shell=True, env=os.environ) The above spawns the new process but proc.pid is not of 'program'. Therefore, my python program cannot kill/stop it if needed. pidNum = os.spawnle(os.P_NOWAIT, "program >& logfile", pidName ,os.environ) This does not work. "File not found" Thanks, EEK From fredrik at pythonware.com Wed Sep 17 06:18:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 12:18:41 +0200 Subject: File Reading related query In-Reply-To: References: Message-ID: Usman Ajmal wrote: > Is there any function for reading a file while ignoring *\n* occuring in > the file? can you be a bit more precise? are we talking about text files or binary files? how do you want to treat any newlines that actually appear in the file? From gandalf at shopzeus.com Mon Sep 8 08:44:57 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Sep 2008 14:44:57 +0200 Subject: universal unicode font for reportlab In-Reply-To: <87r67vj7f1.fsf@benfinney.id.au> References: <87r67vj7f1.fsf@benfinney.id.au> Message-ID: <48C51E49.2070202@shopzeus.com> > Laszlo Nagy writes: > > >> I could not find any free TTF font that can do latin1, latin2, >> arabic, chinese and other languages at the same time. Is there a >> single font that is able to handle these languages? >> > > The GNU Unifont > covers an impressive range of > the Unicode Basic Multilingual Plane. > > Unifont is originally a bitmap font, but was recently made available > in TrueType format > . > > Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont' > packages, respectively. > I found out that dejavu is what I need. It covers the languages I need and more: http://dejavu.svn.sourceforge.net/viewvc/dejavu/tags/version_2_26/dejavu-fonts/langcover.txt Thanks four your help! L From gagsl-py2 at yahoo.com.ar Sun Sep 14 15:32:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Sep 2008 16:32:04 -0300 Subject: PyMarshal Commands crash on Windows References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> Message-ID: En Sun, 14 Sep 2008 08:28:01 -0300, escribi?: > int main (int argc, char * const argv[]) { > Py_Initialize(); > > FILE* fp = fopen("/Users/test/Desktop/123.pyc","wb"); > PyCodeObject* op = (PyCodeObject*)Py_CompileString("import sys > \nprint 'hello'","",Py_file_input); > PyMarshal_WriteObjectToFile((PyObject *)op, fp, > Py_MARSHAL_VERSION); > > Py_Finalize(); > > return 0; > } > > This Code crashs on Windows, and I can't explain why. I want to > convert a PyCodeObject to a PyObject and save it to the harddisk. > PyMarshal_ReadObjectFromFile(FILE *P) crashs too if I want to read a > byte-compiled object. Your code should check every operation for errors. fopen may return NULL, Py_CompileString may fail and return NULL, PyMarshal_xxx might fail (although it's not documented). Why "123.pyc"? Do you want to generate a compiled module? Use the py_compile standard module instead (or write equivalent C code, or see how import.c does that) -- Gabriel Genellina From jakecjacobson at gmail.com Wed Sep 17 14:26:51 2008 From: jakecjacobson at gmail.com (jakecjacobson) Date: Wed, 17 Sep 2008 11:26:51 -0700 (PDT) Subject: Getting/Setting HTTP Headers Message-ID: <03dafea5-28e0-4925-a0f9-7df5670869c1@z72g2000hsb.googlegroups.com> I need to write a feed parser that takes a url for any Atom or RSS feed and transform it into an Atom feed. I done the transformation part but I want to support conditional HTTP requests. I have not been able to find any examples that show: 1. How to read the Last_Modified or ETag header value from the requester 2. How to set the corresponding HTTP header value, either a 302 not modified or the new Last_Modified date and/or ETag values From aaron.hildebrandt at gmail.com Wed Sep 10 14:12:01 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 11:12:01 -0700 (PDT) Subject: Reading binary data References: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> Message-ID: <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> Sorry, I had posted the wrong error. The error I am getting is: struct.error: unpack requires a string argument of length 12 which doesn't make sense to me, since I'm specifically asking for 11. Just for kicks, if I change the line to print struct.unpack('3sII', file.read(12)) I get the result ('GDE', 33554432, 16777216) ... which isn't even close, past the first three characters. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 06:50:47 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 12:50:47 +0200 Subject: (in memory) database In-Reply-To: References: Message-ID: <48bbc8b4$0$18575$426a34cc@news.free.fr> mark a ?crit : > Hi there, > > I need to extract data from text files (~4 GB) on this data some > operations are performed like avg, max, min, group etc. The result is > formated and written in some other text files (some KB). > > I currently think about database tools might be suitable for this. I > would just write the import from the text files and ... the tool does > the rest. The only problem I can imagine is that this would not be > fast enough. Is this an a priori, or did you actually benchmark and found out it would not fit your requirements ? > But I would give it a shoot. > Unfortunately I have only some knowledge of SQLite which is not an > option here. > > Some additional requirements I can think of are: > - Python (I want to hone my programming skills too) > - Python-only (no C-lib) for simplicity (installation, portability). > Therefore SQLite is not an option > - must be fast These two requirements can conflict for some values of "fast". > - I like SQL (select a, b from ...) this would be nice (row[..] + ... > is a little hard getting used to) > > So far I found PyDBLite, PyTables, Buzhug but they are difficult to > compare for a beginner. Never used any of them - I have sqlite, mysql and pgsql installed on all my machines -, so I can't help here. From tjreedy at udel.edu Fri Sep 5 03:03:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 05 Sep 2008 03:03:43 -0400 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <3f0d61c40809042217r6f98c683p90bcae958b1ee773@mail.gmail.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <3f0d61c40809042217r6f98c683p90bcae958b1ee773@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > I understand that Python is a balance between different forces (like > any software object around the world) and I'm simply asking some > pointers to the discussion leading to this balance. The original decisions by Guido were nearly 20 years ago and other discussions are scattered through the archive of this and the py-dev list. But here is a pointer. Why go through the trouble of writing functions that will set, get, and delete an attribute and the trouble of calling those functions when you can use Python's existing syntax to do it directly? More particularly, why would/should Guido force the combersome indirection and time-penalty for writing, reading, and execution on *every* Python programmer? Of course, from my viewpoint, and for my usage,languages that do so force are obnoxious. tjr From castironpi at gmail.com Tue Sep 23 21:47:08 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 18:47:08 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> Message-ID: On Sep 23, 7:50?pm, lixinyi... at gmail.com wrote: > for example I have the following code: > > #include > > void exec_pythoncode( int arg, char**argv ) > { > ? ? Py_Initialize(); > ? ? Py_Main(argc,argv); > ? ? Py_Finalize(); > > } > > What I would like to know is how can I get the variables I want > after Py_Main(argc,argv) > > say I have a=[1,2,'Hello World',0.1234] in the python space, > I would like to have it as a struct in C++. > > Any sample code? > Thanks in advance! What do you know about the contents of 'argc' and 'argv'? If it's impossible with Py_Main, can you use one of the other entry points? If you've never manipulated PyObject* objects in C, they can be hairy. Even if you know 'a' is a sequence, its contents are still all PyObject*s, which you can access via PyList_... and PySequence_ functions. From castironpi at gmail.com Tue Sep 16 22:00:15 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 19:00:15 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> Message-ID: On Sep 16, 8:50?pm, Fett wrote: > I am trying to find a wrapper to do linear programming within python. > I am using an ubuntu machine and I have apt-get'd lp_solve, which > works just fine. If someone knows of a wrapper that will work with > that that'd be great. > > I also heard that scipy has a wrapper, however, I can't find any > documentation on it, nor can I seem to find it with dir(). If anyone > knows where there is good documentation on this I would love to use > that (the more native to python the better imo). > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > openopt, and cvxopt. I can't seem to find any with enough > documentation to get me off the ground. Some I can't compile, some I > can't even find out how to compile. > > If anyone knows of an LP package (preferably with IP as well, like > lp_solve has), that interfaces well with python and has enough > documentation to get a dependency newb like myself off the ground that > would be great. Google says: about 254,000 for linear programming python. Link 3 is: http://wiki.python.org/moin/NumericAndScientific/Libraries Scroll down. From gregturn at mindspring.com Thu Sep 25 07:21:03 2008 From: gregturn at mindspring.com (Goldfish) Date: Thu, 25 Sep 2008 04:21:03 -0700 (PDT) Subject: Spring Python 0.7.0 is released Message-ID: Release 0.7.0 was completed last night, and released to sourceforge.net. NOTE: This release included a lot of API scrubbing, in order to bring things more in tune with PEP-0008 (python's style guide). You're existing apps PROBABLY were impacted, if you used any of Spring Python's utility classes. Since we are pre-1.0, this is the best time for such a cleanup. When 1.0 hits the streets, we won't make such a sweeping change without extensive backwards support. See [url]http://springpython.webfactional.com[/url] for more information. Visit our community forum at [url]http://forum.springframework.org/ forumdisplay.php?f=45[/url] for current threads of discussion. --Greg Turnquist, Spring Python project lead ========================================= Release Notes - Spring Python - Version 0.7 ** Bug * [SESPRINGPYTHONPY-63] - Running setup.py returns an exception ** Improvement * [SESPRINGPYTHONPY-49] - Upgrade PetClinic to CherryPy 3.1 * [SESPRINGPYTHONPY-64] - Adding a schema for the regular component elements * [SESPRINGPYTHONPY-69] - Remove deprecated connection factories from baseline * [SESPRINGPYTHONPY-70] - Scrub function/attribute naming conventions to more closely follow PEP-0008. ** New Feature * [SESPRINGPYTHONPY-61] - Generate reference documentation for the project ** Refactoring * [SESPRINGPYTHONPY-65] - Change 'type' attribute in XML application config to 'scope' to be in line with the lifetime concept in other Spring platforms From rridge at csclub.uwaterloo.ca Wed Sep 24 14:24:13 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 24 Sep 2008 14:24:13 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> Message-ID: Steven D'Aprano wrote: > Presumably somebody has suggested that calling sys.exit() was a good > option. I'm curious to what possible reason they could give for such a > poor choice. Grant Edwards wrote: >Same here. It's like an automotive engine controls designer >asking if a failed O2 sensor should turn on the check engine >light or blow up the car. Ross Ridge wrote: > No, it's more like asking if the failed sensor should turn on > a strange and mysterious light on the dashboard Grant Edwards wrote: >You're right. I had forgotten that sys.exit() is actually >raising the system exit exception, and that the application >calling the library could handle that exception. Well, my point was that exceptions in Python are a bit like a car's check engine light. Few drivers know what this mysterious light means, and aren't prepared to do anything about it when it goes on. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From anishchapagain at gmail.com Mon Sep 1 09:10:19 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Mon, 1 Sep 2008 06:10:19 -0700 (PDT) Subject: Multiple window handling Message-ID: <55921690-9969-463b-a716-d7d62ca1c95e@k13g2000hse.googlegroups.com> Hi!! I'm trying to program an application which have multiple windows and is capable of executing method defined inside class of one another, i tries a simpel frame work here and am creating Toplevel inside method as the new window to be genereated, and again want another window to be loaded when the widget inside toplevel is executed as necessary..but am feeling lost to either create a class for such new window or write function again.. also, when running clearentry() it is not working...have i missed something here.. Programming with multiple window is main task for me..so how it can be done??? the code i tried is here, from Tkinter import * import sys import os class toplevel1(Tk): def __init__(self,parent): Tk.__init__(self,parent) self.parent=parent self.initialize() def initialize(self): label=Label(self, text="Toplevel Practice").pack(side=TOP) button1=Button(self,text="Child 1",command=self.openchild1).pack(side=LEFT) button2=Button(self,text="Child 2",command=self.openchild2).pack(side=LEFT) self.resizable(width=NO,height=YES) self.geometry('300x300') def openchild1(self): c1 = Toplevel(self,bg="#aabbcc",height=300,width=300,borderwidth=1) c1.title("Child One") c1.resizable(width=NO,height=NO) F = Frame(c1,height=40,width=300) F.pack(side=TOP,fill=X,expand=1) llb=Label(F,text="Enter command..") llb.pack(side=LEFT,padx=1) ent = Entry(F,width=50) ent.pack(side=LEFT,padx=2,expand=1) bCl = Button(F,text="Clear Text",command=self.clearentry) bCl.pack(side=LEFT,padx=2, pady=0) bQt = Button(F,text="Quit", command=F.quit) bQt.pack(side=RIGHT,padx=1, pady=0) F1=Frame(c1,relief=SUNKEN,height=330,width=300) txt=Text(F1) scr=Scrollbar(F1,orient=VERTICAL,command=txt.yview,bg="green",width=20) txt.insert(END,"inside txt...") txt.config(yscrollcommand=scr.set) F1.pack(side=TOP,fill=X,expand=1) txt.pack(side=LEFT,fill=BOTH,padx=1) scr.pack(side=RIGHT,fill=Y) F2=Frame(c1,height=30,width=300,relief=RAISED) F2.pack(side=BOTTOM,fill=X,expand=1) llb1=Label(F2,text=" Low Down statusbar") llb1.pack(side=LEFT) def clearentry(self): self.ent.delete(0,END) def openchild2(self): c2 = Toplevel(self,bg="red",height=200,width=200,borderwidth=1) c2.geometry('200x200') c2.resizable(width=NO,height=NO) c2.title("Child Two") Label(c2, text="This is a regular toplevel window.").pack(side=TOP) if __name__=="__main__": obj=toplevel1(None) obj.title('Main Window') obj.mainloop() From robert.kern at gmail.com Sat Sep 13 18:27:27 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 13 Sep 2008 17:27:27 -0500 Subject: I cannot find where Numpy 1.2 is located In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: > To All, > > > I have been trying to locate as to where Numpy 1.2 can be downloaded. I > will need this update. The only version available at the Numpy website > for download is only 1.1.1 not the required 1.2 that I definitely need > at this time. For the last time, Jarrod Millman already told you where to get it on numpy-discussion. Please stop bothering python-list with this stuff. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gnemesis2001 at gmail.com Thu Sep 18 09:50:27 2008 From: gnemesis2001 at gmail.com (Nemesis) Date: Thu, 18 Sep 2008 06:50:27 -0700 (PDT) Subject: XPN 1.2.5 References: <48d0097d$0$40312$4fafbaef@reader5.news.tin.it> Message-ID: On Sep 18, 3:17?pm, pataphor wrote: > >XPN(X Python Newsreader) is a multi-platform newsreader with Unicode > > support. It is written with Python+GTK. It has features like > > scoring/actions, X-Face and Face decoding, muting of quoted text, > > newsrc import/export, find article and search in the body, spoiler > > char/rot13, random taglines and configurable attribution lines. > > Thanks! It works great. thank you :-) > What I especially like about it is that it can > be run from the directory it is in, without needing to be installed. I dislike installation procedures ;-) > But anyway, I can now run it from anywhere and I'm really looking > forward to start tinkering with whatever other functionality I can > think of to add to it, but unfortunately it is rather complete :-) . there is always space for improvements, and some help would be very apreciated. What could be improved is the speed and the code should be also refactored. > Did you know there is a tab in Articles_DB.py line 8? :-) Ducking ... NO! thank you, damned tabs. From J.Fine at open.ac.uk Wed Sep 17 05:29:02 2008 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 17 Sep 2008 10:29:02 +0100 Subject: Generating test data from an XML Schema Message-ID: Hello I want to generate test data from an XML schema. I've had a quick look at existing tools (such as minixsv and amara) but from what I've seen they don't seem to help. It is of course easy to extract all the element names from a schema, but I want more than that. Motivation: I wish to create a subset of TeX/LaTeX that can be easily translated into XML that validates against an existing schema. I also want the input TeX to be fairly easy to author (so a simple mechanical translation will not work). A tool that provides a nice Python interface to navigating the schema would probably be quite helpful. Has anyone seen anything that might help generate test data from a schema? -- Jonathan From m_palmer45 at yahoo.ca Sat Sep 6 09:44:44 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Sat, 6 Sep 2008 06:44:44 -0700 (PDT) Subject: running python as a dameon References: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> <6e7ead25-baf1-400a-a52f-568f37351aab@8g2000hse.googlegroups.com> Message-ID: <5c74118c-a576-4a51-ae9a-95d34273a99a@s50g2000hsb.googlegroups.com> On Sep 5, 9:56 pm, Sean Davis wrote: > > What I want > > to do is to provide the python NLP program as a service to any other > > PHP/Java/Ruby process request. So the mapping is > > > http -> apache -> PHP/Java/Ruby/... -> Python NLP > > Why not use a simple CGI script or wsgi application? You could make > the service online and interactive and with the same application and > code make an XMLRPC web service. So, things would look more like: > > http -> apache -> Python (running NLP and serving requests) > > You can use apache to proxy requests to any one of a dozen or so > python-based webservers. You could also use mod_wsgi to interface > with a wsgi application. > > Sean xmlrpc is the right idea, as it interfaces easily across languages. From __peter__ at web.de Wed Sep 3 10:18:08 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2008 16:18:08 +0200 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: Roy Smith wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: > >> > I might take it one step further, however, and do: >> > >> >> fields = line.split()[:2] >> >> a, b = map(int, fields) >> > >> > in fact, I might even get rid of the very generic, but conceptually >> > overkill, use of map() and just write: >> > >> >> a, b = line.split()[:2] >> >> a = int(a) >> >> b = int(b) >> >> If you go that route your next step is to introduce another try...except, >> one for the unpacking and another for the integer conversion... > > Why another try/except? The potential unpack and conversion errors exist > in both versions, and the existing try block catches them all. Splitting > the one line up into three with some intermediate variables doesn't change > that. As I understood it you didn't just split a line of code into three, but wanted two processing steps. These logical steps are then somewhat remixed by the shared error handling. You lose the information which step failed. In the general case you may even mask a bug. Peter From iain.dalton at gmail.com Fri Sep 26 04:23:18 2008 From: iain.dalton at gmail.com (Iain Dalton) Date: Fri, 26 Sep 2008 02:23:18 -0600 Subject: urllib.urlopen fails in Emacs Message-ID: <877i8zco3t.fsf@gmail.com> In Emacs, using run-python, import urllib urllib.urlopen('http://www.google.com/') results in this traceback: Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/urllib.py", line 82, in urlopen return opener.open(url) File "/usr/lib/python2.5/urllib.py", line 190, in open return getattr(self, name)(url) File "/usr/lib/python2.5/urllib.py", line 325, in open_http h.endheaders() File "/usr/lib/python2.5/httplib.py", line 860, in endheaders self._send_output() File "/usr/lib/python2.5/httplib.py", line 732, in _send_output self.send(msg) File "/usr/lib/python2.5/httplib.py", line 699, in send self.connect() File "/usr/lib/python2.5/httplib.py", line 683, in connect raise socket.error, msg IOError: [Errno socket error] (111, 'Connection refused') It works fine from the command line. Why is this happening? From fredrik at pythonware.com Thu Sep 11 05:45:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 11:45:05 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <87k5djb6e2.fsf@benfinney.id.au> Message-ID: Steven D'Aprano wrote: > I wasn't aware that comp.lang.python was a news-to-mail gateway. How can > one tell the difference between news groups that use a news-to-mail > gateway, and news groups that don't? by reading the group's FAQ, perhaps? http://www.faqs.org/faqs/python-faq/python-newsgroup-faq/ comp.lang.python (or c.l.py for short) is the general discussion newsgroup for users of the Python language. It is also available as a mailing list; see below for instructions on subscribing to c.l.py through the mailing list. it's been this way since the group was formed ~14 years ago, and isn't likely to change. From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 9 04:47:14 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 10:47:14 +0200 Subject: class(object) and (type)?? In-Reply-To: References: Message-ID: <48c63790$0$17080$426a34cc@news.free.fr> On Mon, Sep 8, 2008 at 2:35 PM, AON LAZIO wrote: > Hi again pythoners, > I notice in the class of a code having (object) and (type) attached to > the name of the class. > I know that in other cases, that means the class inherits methods and > properties from other but > In this case, what does it mean? The very same thing. Why should it have a different meaning ? For the record : - 'object' is the base class for 'new-style' classes - that is, the 'new' (hem) object model that came with Python 2.2 (released december 2001 - so it's not that 'new'). The old one - known as 'classic classes' has been kept so far for backward compat only, and will finally disappear with Python 3.x. - 'type' is the base metaclass. Python's classes being objects, they have to be instances of a class - known as the metaclass. To avoid metametaclasses, metametametaclasses etc ad infinitum, 'type' is an instance of itself. And FWIW, a subclass of 'object', which is itself an instance of 'type' (usually, brains start melting here...) You'll find more informations (and hopefully clearer explanations) here: http://www.python.org/doc/newstyle/ and of course in the FineManual(tm): http://docs.python.org/ref/datamodel.html HTH From python at rgbaz.eu Sat Sep 6 19:26:24 2008 From: python at rgbaz.eu (Python) Date: Sun, 7 Sep 2008 01:26:24 +0200 Subject: modules path In-Reply-To: References: Message-ID: On 7 sep 2008, at 00:25, John Machin wrote: > On Sep 7, 8:03 am, Python wrote: >> Hi there, >> >> I moved a few modules into the modules folder (on OSX: /opt/local/ >> lib/ >> python2.5/site-packages/). >> They don't show up though when I start IDLE... >> >> Is there a way to reload the modules folders in sys.path without >> logging out and back in? >> > > I know nothing about OS X, but no "reload" step should be necessary. > Each Python process, whether run from IDLE or some other tool or from > the shell, will form its own idea of sys.path. > > So: What modules? What type of file (.py, .pyc, .egg, .zip, .so) are > you talking about? Did their documentation say that moving the files > into site-packages was all the installation that was needed? What does > "don't show up when I start IDLE" mean? > > When you start IDLE and do > import sys, pprint > pprint.pprint(sys.path) > do you see the site-packages directory containing the module files? > > What happens when you do > import amodule # substitute correct module name here > ? > > Repeat the above two steps for each of > (1) running Python from the shell > (2) running Python from the shell with the -v option > > HTH, > John > -- I installed pyGTK from MacPorts for some reason Macports installs these modules in the /opt/ folder even in an old python folder: python 2.4, while my current version is 2.5 both are not in sys.path... i appended the path and IDLE found them I should have thought a bit more before asking... saturday night... why am I here anyway ;) now one question came up, how do I make those path permanent? i mean, sys.path.append( adds it for the current session, yet when i logout of IDLE and start it again it's gone... how do i keep it in there? thanks for the answer John... Arno From don.hamilton at btinternet.com Fri Sep 12 17:10:07 2008 From: don.hamilton at btinternet.com (Don) Date: Fri, 12 Sep 2008 22:10:07 +0100 Subject: Which version In-Reply-To: References: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> <92da89760809121028s1d9b8b46g464d54937c67ba0f@mail.gmail.com> Message-ID: Eric,Fredrik, Many thanks for your prompt advice, it was a 'better safe than sorry' type of question. Don From raj.indian.08 at gmail.com Wed Sep 24 10:56:19 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Wed, 24 Sep 2008 07:56:19 -0700 (PDT) Subject: Modifying the system menu References: Message-ID: <46bd064c-9299-433b-9bad-2c857344a28f@v39g2000pro.googlegroups.com> I am creating the window manager for multiple desktops :) Anyways, i got one answer in nabble which I feel is the best option - even though I am just investigating on how to do it. Please find below - James Matthews wrote: > > Hi all, > I am trying to modify the system menu of all the applications in > my machine. > For example say - I am creating multiple desktops for windows - > and I want to give every application the capability to be moved across > different desktops. So I wanted to modify the basic system menu list > to include the new options. > > The methods I could think of are - > 1. Modify the basic windows set of system menu values (best option) There is no central repository where this is stored, so there's no place to change. > 2. Poll every few milliseconds and modify the system menu values of > the active window Ick Windows don't come and go that often, and you only need to do this once for each application. The correct option is (3) install a Windows hook to watch for new application to activate, and modify the menu in the hook. You will have to use a hook in order to catch the menu item being chosen anyway. There are Python modules to handle some kinds of hooks, but overall this would be much easier in C. From bcurtu at gmail.com Fri Sep 26 06:30:50 2008 From: bcurtu at gmail.com (bcurtu) Date: Fri, 26 Sep 2008 03:30:50 -0700 (PDT) Subject: how to replace and string in a "SELECT ... IN ()" References: Message-ID: <04e687be-c6f8-4464-bf19-a04e39fdfc8a@c58g2000hsc.googlegroups.com> Pardon? % instead of %s? It doesn't work... :( On 26 sep, 12:15, Wojtek Walczak wrote: > On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote: > > I have a BIIIIIG problem with the next query: > > > ? ? ? ? cursor.execute(""" > > ? ? ? ? ? ? ? ? ? ? SELECT titem.object_id, titem.tag_id > > ? ? ? ? ? ? ? ? ? ? FROM tagging_taggeditem titem > > ? ? ? ? ? ? ? ? ? ? WHERE titem.object_id IN (%s) > > ? ? ? ? ? ? ? ? """,( eid_list)) > > ? ? ? ? ? ? ? ? ? ? ?^ > It should rather be '%'. > HTH. > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 03:02:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Sep 2008 07:02:27 GMT Subject: Negative block sizes with file-like objects Message-ID: <00edd446$0$20666$c3e8da3@news.astraweb.com> I have a proxy class that wraps an arbitrary file-like object fp and reads blocks of data from it. Is it safe to assume that fp.read(-1) will read until EOF? I know that's true for file.read() and StringIO.read(), but is it a reasonable assumption to make for arbitrary file-like objects? To put it in more concrete terms, I have a class like this: class C(object): # Much simplified version. def __init__(self, fp): self.fp = fp def read(self, size=-1): return self.fp.read(size) Should I re-write the read() method like this? def read(self, size=-1): if size < 0: return self.fp.read() else: return self.fp.read(size) -- Steven From digitig at gmail.com Sun Sep 28 17:41:24 2008 From: digitig at gmail.com (Tim Rowe) Date: Sun, 28 Sep 2008 22:41:24 +0100 Subject: Not fully OO ? In-Reply-To: <9f263cc0-508a-4597-94fc-365f6b691d10@i76g2000hsf.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> <9f263cc0-508a-4597-94fc-365f6b691d10@i76g2000hsf.googlegroups.com> Message-ID: 2008/9/28 Aaron Castironpi Brady : > Before I tried wxFormBuilder, I imagined that C# would be vastly > faster to develop than Python, for anything requiring any non-trivial > graphical interface. I've done extensive VB, so I can attest to that > personally. It is not. I'm confused about where VB comes in -- I find VB just *slightly* harder than INTERCAL. C# I find fairly easy. > You can come up with examples that favor either. But the opposite of > statistical is anecdotal. Sorry again. Yes, it's anecdotal, but development time isn't just about how fast the program is to type (otherwise, why aren't we all using APL?) > The last time I 'checked in' at your post, your claim was "an hour or > so" vs. "ages". Hence my responses. You could probably sneak by by > claiming a factor of *two*, but if you were exaggerating, please say > so at any time. Ok. I was exaggerating when I said that VB was harder than INTERCAL. It's marginally easier. As for the program I was working on, I worked for over a day on it in Python, and did it in about an hour in C#, although in fairness I didn't forget all the thinking I'd done on the previous day. I have a lot more Python experience than C# experience, but don't claim to be a guru in either. And no, I don't work two hour days (unfortunately). I have indicated that the GUI wasn't the only issue; in C# it was just easy in that case to find all the library bits I needed to in order to accomplish the task. It isn't always so. > on this, that it's "pretty generally applicable" I'm with you on that. > I do not believe that C# is pretty generally applicable. I agree on that, but *only* because it's a proprietary language with imperfect support once you move away from the .net platform. It's a generally applicable language to .net, but .net is not a general platform. > fact, outside of my VB, COM, and MFC experience, you could say I have > no clue. Very tongue in cheek.) If you see C# as being in any way related to VB, it's no wonder you're down on it! > Python has a lot of things C# doesn't. Can we agree on that? And C# has things that Python doesn't (such as static typing). Can we agree on that, too? -- Tim Rowe From bearophileHUGS at lycos.com Sun Sep 21 19:42:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 21 Sep 2008 16:42:11 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <1bafdeff-d7ae-4c02-b0dc-9d268cef4206@k13g2000hse.googlegroups.com> Steven D'Aprano: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. You may use a module too for that, with normal functions inside, plus module variables that keep the state. Modules can't be instantiated, I think. Bye, bearophile From fredrik at pythonware.com Thu Sep 11 14:21:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 20:21:20 +0200 Subject: Please help me finding a way to implement os.path.issubpath(a, b) In-Reply-To: <6it563Fe2h8U2@mid.uni-berlin.de> References: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> <6it563Fe2h8U2@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Any reason why > > os.path.normpath(a).startswith(os.normpath(b)) doesn't do the trick? Except for the trivial type, you mean? That depends on whether "c:\foo" should be seen as a subpath to "c:\foobar" or not. I'd probably go for (also untested): def issubpath(a, b): def fixpath(p): return os.path.normpath(p) + os.sep return fixpath(a).startswith(fixpath(b)) From ndbecker2 at gmail.com Tue Sep 23 21:50:23 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 23 Sep 2008 21:50:23 -0400 Subject: python syntax for conditional is unfortunate References: Message-ID: Aaron "Castironpi" Brady wrote: > On Sep 23, 6:52 pm, Neal Becker wrote: >> In hindsight, I am disappointed with the choice of conditional syntax. I >> know it's too late to change. The problem is >> >> y = some thing or other if x else something_else >> >> When scanning this my eye tends to see the first phrase and only later >> notice that it's conditioned on x (or maybe not notice at all!). >> Particularly if 'some thing or other' is long or complicated. > > You're talking strictly about readability, which among other things is > in the eye of the beholder, of course. Temporary variables can clean > up some code, even if choosing names can be a hassle and it's more > things to keep track of. Long lines and extra variables form a trade- > off. You are writing a line with a conditional expression the value > of which depends on something. What does it depend on, what is its > value if that's true, and what is it if it's false? '...if...else...' > only takes 6 characters... maybe you want more! > > If you're looking for a strictly syntactic construct, you can always > "fire blanks", or tracers, if the analogy's more accurate. > > z= conditionally( x ) if b else y > > This could serve as a gentle reminder, even where 'conditionally' > returns its argument, i.e. is the identity function. You can always > roll your own ternary with extra parameters too: > > z= condition( b, x, y ) > > Just don't confuse it with threading.Condition. > > Otherwise, you're stuck with old syntax markers, and unless you > wanted: > > z= if b then x else y > > You're out of options. You have to express it somehow. Did you want > the condition first? Was there an alternative proposal you > preferred? IINM if I'm not mistaken, > > z= b and x or y > > works just the same so long as x evaluates to True, as it will be > tested. > > Feel free to write your own from scratch, and we'll see how close > Python can come to resembling it. > > I suppose you can compare it to someone who stops listening before the > word 'if', and completely misunderstands your statement. "Feed the > dog if he's standing near the food dish" != "Feed the dog", which can > of course lead to errors of both omission and commission (doing too > little -or- too much). There's no way to fix that in a guaranteed > way, except to say, "listen to the whole statement". > > And strictly sarcastically, what did you want to do with reading the > program? Why were you reading it? I find I'm often tripped up by: x = Y (lots of constructor arguments....) if something ... on first glance, I don't notice the if. Why am I reading this? Umm, because I wrote it. From marco.bizzarri at gmail.com Thu Sep 4 07:42:50 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 13:42:50 +0200 Subject: Coming from .NET and VB and C In-Reply-To: <48bfc4e4$0$13232$426a74cc@news.free.fr> References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <48bfc4e4$0$13232$426a74cc@news.free.fr> Message-ID: <3f0d61c40809040442q44cb99c8y70a60eefe2601d74@mail.gmail.com> On Thu, Sep 4, 2008 at 1:23 PM, Bruno Desthuilliers wrote: >> >> The appearance is not an RDBMS, at least, maybe it is, but under the >> surface. > > Not AFAIK, cf: > http://en.wikipedia.org/wiki/BigTable > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for the pointer, Bruno... I wrote from my memory, but there is some bank of it which need quick replace ;) -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From roseeea at gmail.com Sat Sep 20 04:58:17 2008 From: roseeea at gmail.com (ROSEEE) Date: Sat, 20 Sep 2008 01:58:17 -0700 (PDT) Subject: The Python computer language Message-ID: <7d3f9f43-8094-4bd0-980c-eb721b5a5051@o40g2000prn.googlegroups.com> http://pthoncomputerlanguage.blogspot.com From sonawane.manoj at gmail.com Mon Sep 1 06:14:22 2008 From: sonawane.manoj at gmail.com (Manoj) Date: Mon, 1 Sep 2008 03:14:22 -0700 (PDT) Subject: list + dictionary searching Message-ID: <6e642a00-9301-440d-902c-63713cf4a793@a2g2000prm.googlegroups.com> Hello All, I am very new to python. Any help will be highly appreciated. Thanks I have a list of dictionaries: a = [{'username': u'John Wang', 'user_utilization': 1.0, 'month': 9, 'user_id': 4, 'year': 2008}, {'username': u'John Wang', 'user_utilization': 1.0, 'month': 10, 'user_id': 4, 'year': 2008}, {'username': u' ', 'user_utilization': 1.0, 'month': 9, 'user_id': 1, 'year': 2008}] I would like to : search dictionaries within this list create a new list with dictionaries which gives 1 dictionary for every user with month_year as a key and utilization for that month as a value Please give your thoughts Thanks, Manoj From MrJean1 at gmail.com Thu Sep 4 20:43:50 2008 From: MrJean1 at gmail.com (MrJean1) Date: Thu, 4 Sep 2008 17:43:50 -0700 (PDT) Subject: Python test case management system? References: Message-ID: <2e6fb98b-0553-42fb-b6e8-50854466034e@2g2000hsn.googlegroups.com> Perhaps Qmtest fits your needs /Jean On Sep 4, 4:36?pm, Mudcat wrote: > I had originally planned on writing my own software for managing test > cases; however new boss = new directive. This will make it more > difficult to get the functionality I need for test cases that are > automated and executed using python. ? I've searched for alternatives > but so far haven't come up with any good options. > > Does anyone know of a good test case management system written in > python, or possibly another application (either open source or > commercial) that can be extended using python? > > Thanks From tom.willis at gmail.com Sat Sep 20 11:09:47 2008 From: tom.willis at gmail.com (Thomas G. Willis) Date: Sat, 20 Sep 2008 08:09:47 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: On Sep 20, 5:23?am, candide wrote: > Excerpt quoted fromhttp://www.astro.ufl.edu/~warner/prog/python.html: > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > Thanks for any comment. My comment is "Who cares?" I was always under the impression that if any language truly was "OO" it would be smalltalk. And I don't derive any benefit from smalltalk at all. I do however derive substantial benefit from other languages that "OO zealots" would likely poo poo on including python. From fredrik at pythonware.com Thu Sep 4 15:41:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 21:41:33 +0200 Subject: Not fully understanding the role of Queue.task_done() In-Reply-To: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: Martin DeMello wrote: > Reading up on python's built in Queue class, though, it seems oriented > towards "job queues", with a two-step dequeue operation (get() and > task_done()). I'm worried that this would make it too heavyweight for > my application. Is ther documentation somewhere on what exactly > task_done() does, and whether I can disable the tracking of a job once > it's removed from the queue? The python docs for the Queue module were > a bit light. "task_done" just decrements a counter (incremented by "put"). when the counter reaches zero, the "join" call is unblocked. From tjreedy at udel.edu Mon Sep 8 16:38:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Sep 2008 16:38:31 -0400 Subject: lacking follow-through In-Reply-To: <47c890dc0809081204o3511b9dck1adadd98f73ca2b7@mail.gmail.com> References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <47c890dc0809081204o3511b9dck1adadd98f73ca2b7@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman wrote: >> To expand on this a little bit, I've been subscribed to this group >> for a couple of months, but there seems to be a bit more gray area >> between what would go to a 'python-dev' group and a 'python-user' >> group. Long debates about language features and abstract ideas would >> appeal to the former, but not the latter. The py-dev mailing list, and its gmane.comp.python.devel mirror, is for concrete discussion, mostly by developers, of how to develop the current and next release. The current focus in on finishing 2.6 for release. Almost nothing that has appeared here recently belongs there. It is much more common for people to post there usage questions that belong here or speculative issues that could also go to python-ideas. >> Certainly I fall into the >> user category.. I'm pretty happy with python, and generally just >> adjust to it's design and features, rather than spend lots of time on >> whether they are 'right' or could be 'better'. /shrug Long rehashes of decided issues, like the name of subprocess.popen, or the default of sum(), belong here better than anywhere else, if anywhere ;-). > Yeah, suggestions about changing the language are much better suited > to the more-specific Python-ideas or Python-3000 mailinglists than the > general-purpose c.l.p The Python-3000 mailing list, and the gmane.comp.python.python-3.devel mirror, is the py-dev equivalent for python3-specific issues. tjr From alan.isaac at gmail.com Mon Sep 8 09:15:38 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Mon, 08 Sep 2008 13:15:38 GMT Subject: Learning Python In-Reply-To: References: Message-ID: <_z9xk.830$sq3.754@trnddc07> On 9/6/2008 5:17 AM James Pilling apparently wrote: > Hi im currently starting to learn python in sixth form at school any tips? The books suggestions of others are quite good. Here is another approach: pick an easily understandable application, and work doing things with it. Perhaps immodestly, I think that as soon as you understand how to define a function and a class, you can treat this paper http://jasss.soc.surrey.ac.uk/11/3/8.html as an introduction to applied Python programming. The application area is very specific---game theoretic simulations---but the illustrated techniques are meant to be more general. Alan Isaac From rowland at river2sea.org Tue Sep 2 11:42:13 2008 From: rowland at river2sea.org (Rowland Smith) Date: Tue, 2 Sep 2008 11:42:13 -0400 Subject: source for the property function Message-ID: <6072EAA1-9891-4910-80B4-A26820712387@river2sea.org> Anyone know where the source code for the built-in property function is located in a python distribution? I would like to see how it works - mainly, how does it know which class it is being called from? Thanks, Rowland From rcdailey at gmail.com Fri Sep 5 16:15:02 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 15:15:02 -0500 Subject: Need formatting suggestion for long strings In-Reply-To: <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> References: <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> Message-ID: <496954360809051315v44438624vf16240216d8ba2c5@mail.gmail.com> On Fri, Sep 5, 2008 at 3:06 PM, aha wrote: > Can you be more specific? What is the formatting criteria? Are you > talking about formatting the string for display or are you talking > about the source? Apologies for the confusion. My concern is both. Allow me to explain: I'm concerned about the formatting of the string in that I do not want the way I split the string up in source code to affect the way the string is displayed to the console. In other words, in source, if I break up a single string into multiple lines (using carriage returns), I would expect the string to still render as a single-line string. I'm also concerned about the source formatting, because I do not want the single-line string to run off the edge of my display. I want it to be in "Paragraph form" in the source code, but remain a single-line when printed. I hope that makes sense. Let me know if I need to clarify more. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.hildebrandt at gmail.com Wed Sep 10 14:16:38 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 11:16:38 -0700 (PDT) Subject: Reading binary data References: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> Message-ID: <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> Taking everything into consideration, my code is now: import struct file = open("test.gde", "rb") signature = file.read(3) version, attr_count = struct.unpack('II', file.read(8)) print signature, version, attr_count for idx in xrange(attr_count): attr_id, attr_val_len = struct.unpack('II', file.read(8)) attr_val = file.read(attr_val_len) print attr_id, attr_val_len, attr_val file.close() which gives a result of: GDE 2 2 1 4 ? 2 4 ??? Essentially, the same results I was originally getting :( From alexomoto at gmail.com Tue Sep 30 05:20:16 2008 From: alexomoto at gmail.com (alexomoto at gmail.com) Date: Tue, 30 Sep 2008 02:20:16 -0700 (PDT) Subject: Problems compiling on CentOS Python 2.5 References: Message-ID: <49c0dc41-de2c-49da-a27f-7697fdb420ae@m73g2000hsh.googlegroups.com> On Sep 23, 10:37?am, "F." wrote: > Hello, > I have problems makingpythonon CentOS 5. > Seems that can not find something. I can not find the problem. > Where is the problem? > > > case $MAKEFLAGS in \ > > ? ? ? ? *-s*) ?CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG ?-fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python-E ./setup.py -q build;; \ > > ? ? ? ? *) ?CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG ?-fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python-E ./setup.py build;; \ > > ? ? ? ? esac > > running build > > running build_ext > > db.h: found (4, 3) in /usr/include > > db lib: using (4, 3) db-4.3 > > INFO: Can't locate Tcl/Tklibs and/or headers > > building '_ssl' extension > > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes -I. -I/home/unStable/progC/exLibs/Python-2.5.2/Python-2.5.2/./Include -I. -IInclude -I./Include -I/usr/local/include -I/directory/Python-2.5.2/Python-2.5.2/Include -I/directory/Python-2.5.2/Python-2.5.2 -c /directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.c -o build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o > > gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-i686-2.5/_ssl.so > > *** WARNING: renaming "_ssl" since importing it failed: build/lib.linux-i686-2.5/_ssl.so: undefined symbol: krb5_auth_con_getrcache > > running build_scripts > > -- > > -- > Publicidadhttp://www.pas-world.com I also spent a couple hours googling for this same problem! It's not tough to figure it out but would have saved time and stress if i hit the answer on my first search. I am also using CentOS 4.4, 4.5 and python 2.4.4. I debugged the Python installation script to find that the tk.h/tcl.h headers are missing. Installing the tk-devel package (using yum) installs the headers. Then re-install Python. From sayananbig at gmail.com Mon Sep 22 17:58:45 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Mon, 22 Sep 2008 14:58:45 -0700 (PDT) Subject: python timers and COM/directshow Message-ID: Hey all, So I've written a simple video player using directshow/COM in VC++, and I'm in the process of translating it to python. For example, when the avi starts playing, I have a call media_control.Run() , etc. I'm wondering how I should go about updating my gtk.Hscale widget as a trackbar for the avi player. In C++, I have the following callbacks that update the scrollbar and video position with a timer. void CvideoDlg::OnNMReleasedcaptureSlider1(NMHDR *pNMHDR, LRESULT *pResult) { //Slider event handler LONGLONG lPos = 0; LONGLONG lDuration = 0; KillTimer(101); g_pSeek->GetDuration(&lDuration); g_pSeek->GetCurrentPosition(&lPos); Videopos= m_slider.GetPos(); //Sets new video position to that of the slider, which user inputs lPos = ((long)Videopos * (lDuration/num_of_frames)); g_pSeek->SetPositions(&lPos, AM_SEEKING_AbsolutePositioning,NULL, AM_SEEKING_NoPositioning); *pResult = 0; } void CvideoDlg::OnTimer(UINT nIDEvent) { //Timer event handler. LONGLONG lPos = 0; LONGLONG lDuration = 0; g_pSeek->GetDuration(&lDuration); g_pSeek->GetCurrentPosition(&lPos); Videopos = (int)(lPos * num_of_frames/ lDuration); m_slider.SetPos(Videopos); if (Videopos==(int)(last_frame)) //If we get to the end of the selection, the video pauses pause(); else{ UpdateData(); //Updates the slider controller and position CDialog::OnTimer(nIDEvent);} } I'm wondering how I would implement similar callbacks in Python for a gtk.Hscale, and some sort of time [I'm not familiar with Pythons timers/threading at all]. From ivanov.maxim at gmail.com Tue Sep 16 07:25:34 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Tue, 16 Sep 2008 15:25:34 +0400 Subject: What is "finally:" for? Message-ID: Hi all! When and where I should use try-except-finally statement? What is the difference between: -------- try: A... except: B.... finally: C... -------- and ------- try: A... except: B.... C... From Lie.1296 at gmail.com Sun Sep 28 05:49:11 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 02:49:11 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <66606235-be55-458a-9e14-09e6c766201d@p31g2000prf.googlegroups.com> On Sep 28, 12:37?pm, est wrote: > From python manual > > str( [object]) > > Return a string containing a nicely printable representation of an > object. For strings, this returns the string itself. The difference > with repr(object) is that str(object) does not always attempt to > return a string that is acceptable to eval(); its goal is to return a > printable string. If no argument is given, returns the empty string, > ''. > > now we try this under windows: > > >>> str(u'\ue863') > > Traceback (most recent call last): > ? File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0 > : ordinal not in range(128) > > FAIL. And it is correct to fail, ASCII is only defined within range(128), the rest (i.e. range(128, 256)) is not defined in ASCII. The range(128, 256) are extension slots, with many conflicting meanings. > > also almighty Linux > > Python 2.3.4 (#1, Feb ?6 2006, 10:38:46) > [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> str(u'\ue863') > > Traceback (most recent call last): > ? File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0: ordinal not in range(128) > > Python 2.4.4 (#2, Apr ?5 2007, 20:11:18) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> str(u'\ue863') > > Traceback (most recent call last): > ? File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0: ordinal not in range(128) > > Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> str(u'\ue863') > > Traceback (most recent call last): > ? File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0: ordinal not in range(128) If that str() function has returned anything but error on this, I'd file a bug report. > The problem is, why the f**k set ASCII encoding to range(128) ???????? > while str() is internally byte array it should be handled in > range(256) !!!!!!!!!! string is a byte array, but unicode and ASCII is NOT. Unicode string is a character array defined up to range(65535). Each character in unicode may be one or two bytes long. ASCII string is a character array defined up to range(127). Other than Unicode (actually utf-8, utf-16, and utf-32) and ASCII, there are many other encodings (ECBDIC, iso-8859-1', ..., 'iso-8859-16', 'KOI8', 'GB18030', 'Shift-JIS', etc, etc, etc) each with conflicting byte to characters mappings. Fortunately, most of these encodings do share a common ground: ASCII. Actually, when a strictly stupid str() receives a Unicode string (i.e. character array), it should return a , but it doesn't, str() is smarter than that, it tries to convert whatever fits into ASCII, i.e. characters lower than 128. Why ASCII? Because character from range(128, 256) varies widely and it doesn't know which encoding you want to use, so if you don't tell me what encoding to use it'd not guess (Python Zen: In the face of ambiguity, refuse the temptation to guess). If you're trying to convert a character array (Unicode) into a byte string, it's done by specifying which codec you want to use. str() tries to convert your character array (Unicode) to byte string using ASCII codec. s.encode(codec) would convert a given character array into byte string using codec. > http://bugs.python.org/issue3648 > > One possible solution(Windows Only) > > >>> str(u'\ue863'.encode('mbcs')) > '\xfe\x9f' actually str() is not needed, you need only: u'\ue863'.encode('mbcs') > >>> print u'\ue863'.encode('mbcs') > ? > > I now spending 60% of my developing time dealing with ASCII range(128) > errors. It was PAIN!!!!!! Despair not, there is a quick hack: # but only use it as temporary solution, FIX YOUR CODE PROPERLY str_ = str str = lambda s = '': s.encode('mbcs') if isinstance(s, basestring) else str_(s) > Please fix this issue. > > http://bugs.python.org/issue3648 > > Please. From torainLight at gmail.com Sat Sep 20 06:54:22 2008 From: torainLight at gmail.com (satoru) Date: Sat, 20 Sep 2008 03:54:22 -0700 (PDT) Subject: how can i check whether a variable is iterable in my code? References: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> On Sep 20, 6:35?pm, Aidan wrote: > satoru wrote: > > hi, all > > i want to check if a variable is iterable like a list, how can i > > implement this? > > this would be one way, though I'm sure others exist: > > if hasattr(yourVar, '__iter__'): > ? ? ? ? # do stuff thank you,but this will miss out sequences like string just because it doesn't have an attribute named '__iter__' From tjreedy at udel.edu Sat Sep 13 14:21:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Sep 2008 14:21:49 -0400 Subject: Profiling, sum-comprehension vs reduce In-Reply-To: <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > If you want to see reduce really shine, time it with a C-based function > rather than one written in pure Python: > >>>> Timer('reduce(add, xrange(10000))', > ... 'from operator import add').repeat(number=10000) > [19.724750995635986, 19.410486936569214, 19.614511013031006] >>>> Timer('reduce(add, xrange(10000))', > ... 'def add(x, y): return x+y').repeat(number=10000) > [45.210143089294434, 44.814558982849121, 46.906874895095825] ... > Of course, sum() is even faster than reduce: > >>>> Timer('sum(xrange(10000))').repeat(number=10000) > [9.814924955368042, 8.7169640064239502, 9.5062401294708252] 'Of course', because the irreducible difference between reduce(add.seq) and sum(seq) is that reduce has to call an add function while sum has the operation built-in in place of a call. From seandavi at gmail.com Fri Sep 5 21:56:37 2008 From: seandavi at gmail.com (Sean Davis) Date: Fri, 5 Sep 2008 18:56:37 -0700 (PDT) Subject: running python as a dameon References: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> Message-ID: <6e7ead25-baf1-400a-a52f-568f37351aab@8g2000hse.googlegroups.com> On Sep 5, 5:55?pm, peyman wrote: > Hi > > I have a Natural Language Processing (NLP) code written in python that > reads into memory a large training file and then given a sentence tags > it, using the training data. I want to put this NLP code on a server > which handles all incoming client http requests via PHP. What I want > to do is to provide the python NLP program as a service to any other > PHP/Java/Ruby process request. So the mapping is > > http -> apache -> PHP/Java/Ruby/... -> Python NLP Why not use a simple CGI script or wsgi application? You could make the service online and interactive and with the same application and code make an XMLRPC web service. So, things would look more like: http -> apache -> Python (running NLP and serving requests) You can use apache to proxy requests to any one of a dozen or so python-based webservers. You could also use mod_wsgi to interface with a wsgi application. Sean > > I can not provide this service as a shell script because of the > inefficiencies of having to load into memory a large training data to > every service request. So what I want to do is to provide the NLP > service to other application processes as a python daemon > > http -> apache -> PHP/Java/Ruby/... -> Python Dameon -> Python NLP > > The daemon loads into memory the training data once. then every > service request event invokes the appropriate NLP code in the python > program. I've tried to use play around with twisted but am not making > too much of a headway. What I've done in the NLP code is to do this: > > # filename: NLP.py > def parse(sentence): > ? ? structure=getentities(sentence) > ? ? print 'subject: \t',' '.join(structure[0]) > ? ? print 'predicate: \t',' '.join(structure[1]) > ? ? print 'TE: \t\t',' '.join(structure[2]) > > class TLogicClass(): > ? ? def __init__(self,prop): > ? ? ? ? return parse(prop) > > then in the dameon code done this > > # filename: dameon.py > from twisted.application import service > import NLP > > application=service.Application("nlp") > ParseService=NLP.TLogicClass("time flies like an arrow") > ParseService.setServiceParent(application) > > but I get the following error when I run twistd -y daemon.py > > >> Failed to load application: TLogicClass instance has no attribute 'setServiceParent' > > I suspect I need to put twisted in the NLP.py but I don't know what I > need to do in order to get what I want to do which is: > > to load into memory only once a large training data that can then be > queried by another (non-python) event based process ?(I need "reactor" > class?). > > thank you in advance for your help From michele.simionato at gmail.com Wed Sep 3 23:26:37 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 3 Sep 2008 20:26:37 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> Message-ID: On Sep 4, 12:26?am, bukzor wrote: > I'm trying to optimize my number of connections by not fully > initializing (read: not connecting) my connection until it's used in > some way. I had the same use case and I solved with a simple property. Here is the code I have for pymssql: @property def conn(self): if self._conn is None: self._conn = _mssql.connect(self.host, self.user,self.passwd) self._conn.select_db(self.dbname) return self._conn The connection is really instantiate only when you call self.conn to perform the query, not when you instantiate the class. From fredrik at pythonware.com Thu Sep 4 18:21:59 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 00:21:59 +0200 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> Message-ID: Robert Dailey wrote: > I currently have a dictionary object that I'm doing the following with: > > if lib not in stage_map: > # ... do stuff ... > > However, this will perform a case-sensitive comparison between lib and > each key in stage_map. Is there a way to make this do a case-insensitive > comparison instead? dictionary lookups use the exact value. to make a case-insensitive lookup, use key.lower() instead of key when creating the dictionary, and then do if lib.lower() not in state_map: ... From rpw3 at rpw3.org Mon Sep 1 06:55:26 2008 From: rpw3 at rpw3.org (Rob Warnock) Date: Mon, 01 Sep 2008 05:55:26 -0500 Subject: The Importance of Terminology's Quality References: <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> Message-ID: Robert Maas, wrote: +--------------- | > From: rpw3 at rpw3.org (Rob Warnock) | > In the LGP-30, they used hex addresses, sort of[1], but the | > opcodes (all 16 of them) had single-letter mnemonics chosen so that | > the low 4 bits of the character codes *were* the correct nibble for | > the opcode! ;-} ... | By the way, do you remember exactly all the 16 opcodes, or have a | Web reference available? +--------------- There are quite a few out there; here's one: http://www.users.nwark.com/~rcmahq/jclark/lgp30.htm Some notes on the opcodes: - "Bring" (B) would be called "Load" in current parlance. - "Extract" (E) would be called "And" in current parlance. - "Unconditional Transfer" (U) would be called "Jump" or "Branch". - "Hold" (H) would be called "Store"; "Clear" (C) would be called "Store-and-Clear" (the "DCA" instruction of the DEC PDP-8). - There are two "Multiply" ops, "M" & "N", depending on whether the upper or lower bits (respectively) of the product are returned. - "Store Address" (Y) stores an address in the AC into the address field of the destination [yes, modifying the code in-place!! -- it was mostly used for indexing through arrays], whereas the "Return Address" (R) stores the current instruction address + 2 into the address field of the destination. The subroutine calling sequence is thus an "R/U" pair: R foo_last U foo where the FOO subroutine might be written as: foo: ... ... foo_last: U foo_last ; overwritten +--------------- | > The LGP-30 character code was defined before the industry had | > yet standardized on a common "hex" [sic, "hexadecimal", base 16 | > not base 6!!!] character set, ... | > they used "0123456789fgjkqw". | | That doesn't make sense. The low-order four bits of those letters | aren't consecutive ascending values from 9+1 to 9+6. Did you make a | typo, or did you explain something wrong? +--------------- No, what I wrote is correct. The low 4 bits of "0123456789fgjkqw" *are* 0 through 16 (or "0123456789abcdef" in current "hex")... IN THE *LGP-30 FLEXOWRITER* CHARACTER CODE, *not* in ASCII or EBCDIC or Baudot or any other standard code. Well, actually, it's a little more complex than that. The LGP-30 used a 6-bit "keyboard" code on the Flexowriter (and the paper tape reader & punch), but the machine could be put into either 6-bit or 4-bit input mode. In the latter, only the first four bits of each code got shifted into the accumulator. So I suppose you could say those were the *upper* 4 bits of each character, though when read into the accumulator in "4-bit input mode" they truly *were* the lower 4 bits. (Sorry for the confusion. It was an "interesting" machine.) +--------------- | (map 'list #'char-code "0123456789fgjkqw") | => (48 49 50 51 52 53 54 55 56 57 102 103 106 107 113 119) +--------------- That's ASCII. The LGP-30 did not use ASCII. The LGP-30 used Flexowriter keyboard code, see: http://ed-thelen.org/comp-hist/lgp-30-man-f002.gif -Rob p.s. The full programming manual for the LGP-30 can be found here: http://ed-thelen.org/comp-hist/lgp-30-man.html but good luck reading its archaic style. ;-} ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From joefazee at gmail.com Tue Sep 23 13:32:03 2008 From: joefazee at gmail.com (A. Joseph) Date: Tue, 23 Sep 2008 10:32:03 -0700 Subject: Matrix programming Message-ID: I need an ebook or tutorial that teach matrix programming. -------------- next part -------------- An HTML attachment was scrubbed... URL: From frank at chagford.com Thu Sep 18 02:28:55 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 17 Sep 2008 23:28:55 -0700 (PDT) Subject: XML-schema 'best practice' question Message-ID: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Hi all This is not strictly a Python question, but as I am writing in Python, and as I know there are some XML gurus on this list, I hope it is appropriate here. XML-schemas are used to define the structure of an xml document, and to validate that a particular document conforms to the schema. They can also be used to transform the document, by filling in missing attributes with default values. In my situation, both the creation and the processing of the xml document are under my control. I know that this begs the question 'why use xml in the first place', but let's not go there for the moment. Using minixsv, validating a document with a schema works, but is quite slow. I appreciate that lxml may be quicker, but I think that my question is still applicable. I am thinking of adding a check to see if a document has changed since it was last validated, and if not, skip the validation step. However, I then do not get the default values filled in. I can think of two possible solutions. I just wondered if this is a common design issue when it comes to xml and schemas, and if there is a 'best practice' to handle it. 1. Don't use default values - create the document with all values filled in. 2. Use python to check for missing values and fill in the defaults when processing the document. Or maybe the best practice is to *always* validate a document before processing it. How do experienced practitioners handle this situation? Thanks for any hints. Frank Millman From antroy at gmail.com Tue Sep 16 08:33:23 2008 From: antroy at gmail.com (Ant) Date: Tue, 16 Sep 2008 05:33:23 -0700 (PDT) Subject: What is "finally:" for? References: Message-ID: On Sep 16, 12:30?pm, Andreas Kaiser wrote: > On 16 Sep., 13:25, "Max Ivanov" wrote:> Hi all! > > When and where I should use try-except-finally statement? What is the > > difference between: > > -------- > > try: > > ? A... > > except: > > ? B.... > > finally: > > ? C... > > -------- > > It does A if no exception or B if an exception occurs. THEN it does > always C. Rather it runs the code in A. If an exception is thrown in A, B is then run. C is run regardless. > > ------- > > try: > > ? A... > > except: > > ? B.... > > C... > > If an exception occurs, C is never reaching. Whether or not C runs will depend on what code is present in B (e.g. it could return, or throw a different exception). Typically you will use a finally clause if there is some cleanup that should occur regardless of whether an exception is thrown. For example: def getNumbers(filename): numbers = [] fh = open("test.txt") # Should contain lines of numbers try: for line in fh: if line.strip(): numbers.append(int(line.strip())) except ValueError, e: return None finally: fh.close() return numbers This ensures that open files are closed for example. -- Ant. From prologic at shortcircuit.net.au Sun Sep 7 17:49:41 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 07:49:41 +1000 Subject: formatting a string with thousands separators In-Reply-To: References: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> Message-ID: Hi, There is a much easier more consistent way: >>> import locale >>> locale.setlocale(locale.LC_ALL, "en_AU.UTF-8") 'en_AU.UTF-8' >>> locale.format("%0.2f", 5000000, True) '5,000,000.00' >>> cheers James On Mon, Sep 8, 2008 at 5:24 AM, Alan G Isaac wrote: > On 9/7/2008 12:22 PM SimonPalmer apparently wrote: >> >> anyone recommend a way of formatting floats with comma separators? > > > http://code.activestate.com/recipes/498181/ > > Alan Isaac > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From seandavi at gmail.com Wed Sep 10 13:59:48 2008 From: seandavi at gmail.com (Sean Davis) Date: Wed, 10 Sep 2008 10:59:48 -0700 (PDT) Subject: emulating read and readline methods Message-ID: I have a large file that I would like to transform and then feed to a function (psycopg2 copy_from) that expects a file-like object (needs read and readline methods). I have a class like so: class GeneInfo(): def __init__(self): #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ gene_info.gz',"/tmp/gene_info.gz") self.fh = gzip.open("/tmp/gene_info.gz") self.fh.readline() #deal with header line def _read(self,n=1): for line in self.fh: if line=='': break line=line.strip() line=re.sub("\t-","\t",line) rowvals = line.split("\t") yield "\t".join([rowvals[i] for i in [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" def readline(self,n=1): return self._read().next() def read(self,n=1): return self._read().next() def close(self): self.fh.close() and I use it like so: a=GeneInfo() cur.copy_from(a,"gene_info") a.close() It works well except that the end of file is not caught by copy_from. I get errors like: psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error during .read() call CONTEXT: COPY gene_info, line 1000: "" for a 1000 line test file. Any ideas what is going on? Thanks, Sean From akathorn at gmail.com Thu Sep 4 23:13:28 2008 From: akathorn at gmail.com (Akathorn Greyhat) Date: Fri, 5 Sep 2008 04:13:28 +0100 Subject: Curious: 2134 2004-10-06 08:55:20Z fredrik Message-ID: I had an import error and I get this error: Traceback (most recent call last): File "C:\Eclipse\pyworkspace\CodenameRazor0.2\src\app.py", line 11, in import core File "C:\Python25\lib\site-packages\PIL\__init__.py", line 3, in # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ ImportError: No module named data I've already fix it, but I don't know what the hell does this line means: # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ It seens curious, isn't it? -- Akathorn Greyhat -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Mon Sep 29 17:38:33 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Sep 2008 16:38:33 -0500 Subject: Source code for python nativ methods and classes In-Reply-To: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> References: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> Message-ID: <18657.19161.786208.571131@montanaro-dyndns-org.local> mohed> I am interrested in seeing the source code for all the nativ mohed> builtin methods and clases in python. Is there a webpage that mohed> lists them or is this done easier some other way. Browse the source. You can download it then poke around using your favorite editor: http://www.python.org/download/ or browse the source online: http://svn.python.org/view/python/trunk/ Skip From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 24 03:23:49 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 09:23:49 +0200 Subject: python syntax for conditional is unfortunate In-Reply-To: References: Message-ID: <48d9eaf9$0$6127$426a34cc@news.free.fr> Neal Becker a ?crit : (snip) > I find I'm often tripped up by: > > x = Y (lots of constructor arguments....) if something ... > > on first glance, I don't notice the if. Indeed. The inline conditionnal syntax is obviously innappropriate here. It's just like list-comprehensions : just fine for simple use case, definitively not appropriate when it comes to anything complex. IOW : it's not the syntax that's unfortunate, it's the coding style that's wrong. My 2 cents... From bj_666 at gmx.net Tue Sep 2 14:26:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 18:26:38 GMT Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: <6i5equFol29aU5@mid.uni-berlin.de> On Tue, 02 Sep 2008 10:36:50 -0700, hofer wrote: > sed 's/\.\..*//' \ ### remove '//' comments | sed 's/#.*//' Comment does not match the code. Or vice versa. :-) Untested: from __future__ import with_statement from itertools import ifilter, ifilterfalse, imap def is_junk(line): line = line.rstrip() return not line or line.startswith('//') or line.startswith('#') def extract_numbers(line): result = map(int, line.split()[:2]) assert len(result) == 2 return result def main(): with open('test.txt') as lines: clean_lines = ifilterfalse(is_junk, lines) pairs = imap(extract_numbers, clean_lines) print '\n'.join(b for a, b in pairs if a + b == 42) if __name__ == '__main__': main() Ciao, Marc 'BlackJack' Rintsch From pete.forman at westerngeco.com Wed Sep 10 10:25:23 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 10 Sep 2008 15:25:23 +0100 Subject: Python-URL! - weekly Python news and links (Sep 9) References: Message-ID: "Gabriel Genellina" writes: > QOTW: "So why am I supposed to care about SOAP again? Oh yes, the > wizards I can use to generate 'web service end-points' from > programming language code. My years in the SOAP trenches just > makes me laugh myself half to death at that notion: I would > probably have been twice as productive if every time I reached for > a SOAP toolkit I instead just coded straight XML in HTTP. And this > represents experience with Python, Java and C WS tools." - Uche > Ogbuji It looks as if that Large Hadron Collider is having ill effects already. A week has been stretched into 6 years. ;-) http://lists.xml.org/archives/xml-dev/200302/msg00259.html -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From monuindia at gmail.com Thu Sep 11 14:19:21 2008 From: monuindia at gmail.com (Monu) Date: Thu, 11 Sep 2008 11:19:21 -0700 (PDT) Subject: shelve file name extention References: Message-ID: On Sep 8, 1:47?pm, s... at pobox.com wrote: > ? ? Monu> When I am using shelve on my local machine it generates the db > ? ? Monu> file as given filename. But in another machine it's generating > ? ? Monu> .dat and .dir. ?can anyone tell me how can I force sheve > ? ? Monu> module to write the db in .dir and .dat, > ? ? Monu> instead of ? Do I have to install a specific version of > ? ? Monu> the python? > > Shelve is just a thin layer on top of a concrete db file module. ?Sounds > like on your two machines there are different underlying db file modules > available. ?You're pretty much at the mercy of those modules as to file > naming. ?All you are giving it when opening a shelve file is the prefix. > > Skip Thanks Skip. So Can't I choose which module to use. Is there any preferance on which shelve chooses these modules? From M8R-yfto6h at mailinator.com Sun Sep 28 13:13:31 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 28 Sep 2008 10:13:31 -0700 Subject: Python 3.0 and repr Message-ID: I don't understand the behavior of the interpreter in Python 3.0. I am working at a command prompt in Windows (US English), which has a terminal encoding of cp437. In Python 2.5: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> x=u'\u5000' >>> x u'\u5000' In Python 3.0: Python 3.0rc1 (r30rc1:66507, Sep 18 2008, 14:47:08) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x='\u5000' >>> x Traceback (most recent call last): File "", line 1, in File "c:\dev\python30\lib\io.py", line 1486, in write b = encoder.encode(s) File "c:\dev\python30\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u5000' in position 1: character maps to Where I would have expected >>> x '\u5000' Shouldn't a repr() of x work regardless of output encoding? Another test: Python 3.0rc1 (r30rc1:66507, Sep 18 2008, 14:47:08) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> bytes(range(256)).decode('cp437') '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\ x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f???????????????? ???????????????????????????????????????????????????????????????????????????????? ???????????????????????????????\xa0' >>> bytes(range(256)).decode('cp437')[255] '\xa0' Characters that cannot be displayed in cp437 are being escaped, such as 0x00-0x1F, 0x7F, and 0xA0. Even if I incorrectly decode a value, if the character exists in cp437, it is displayed: >>> bytes(range(256)).decode('latin-1')[255] '?' However, for a character that isn't supported by cp437, incorrectly decoded: >>> bytes(range(256)).decode('cp437')[254] '?' >>> bytes(range(256)).decode('latin-1')[254] Traceback (most recent call last): File "", line 1, in File "c:\dev\python30\lib\io.py", line 1486, in write b = encoder.encode(s) File "c:\dev\python30\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 1: character maps to Why not display '\xfe' here? It seems like this inconsistency would make it difficult to write things like doctests that weren't dependent on the tester's terminal. It also makes it difficult to inspect variables without hex(ord(n)) on a character-by-character basis. Maybe repr() should always display the ASCII representation with escapes for all other characters, especially considering the "repr() should produce output suitable for eval() when possible" rule. What are others' opinions? Any insight to this design decision? -Mark From castironpi at gmail.com Sun Sep 14 14:09:52 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 14 Sep 2008 11:09:52 -0700 (PDT) Subject: How to marshal objects to readable files? References: Message-ID: <143e575e-4745-4148-86de-deb2dbc0651d@m3g2000hsc.googlegroups.com> On Sep 14, 10:28?am, nielinjie wrote: > Hi list: > I just want to marshal objects (instance of custom classes)to a human > *READABEL *file/string, and also, I want unmarshal it back. in xml > format or any other format. > Any advice? Which lib should I use? > Thanks a lot. Nielinjie, There is no generic way; an object can contain a reference to another object. You can get started with ob.__dict__ as follows: >>> class A: pass ... >>> a= A() >>> a.b= 0 >>> a.c= 'abc' >>> a.__dict__ {'c': 'abc', 'b': 0} But the only way TMK (to my knowledge) to retrieve the contents is eval, which is very hackish. The PyYAML package produces the following (continued): >>> b= A() >>> b.d= 'efg' >>> b.e= 1.2 >>> a.d= b >>> b.parent= a >>> print yaml.dump( a ) &id001 !!python/object:__main__.A b: 0 c: abc d: !!python/object:__main__.A d: efg e: 1.2 parent: *id001 >>> print yaml.dump( b ) &id001 !!python/object:__main__.A d: efg e: 1.2 parent: !!python/object:__main__.A b: 0 c: abc d: *id001 >>> yaml.load( yaml.dump( a ) ) <__main__.A instance at 0x00D098A0> >>> _.__dict__ {'c': 'abc', 'b': 0, 'd': <__main__.A instance at 0x00D09788>} It caches IDs to reference circular references, and writes nested objects in place. As you can see, you don't need to dump both 'a' and 'b'; 'a' contains 'b' already. You do need the types of the objects already living in the same namespace as when you stored them. If it's not human readable enough for your use, please write an example of what you want your output to look like. Abstract is ok. PyYAML is available at http://pyyaml.org/ . Download from http://pyyaml.org/wiki/PyYAML . I've only skimmed it though. From gagsl-py2 at yahoo.com.ar Fri Sep 19 05:08:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 06:08:32 -0300 Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <48D33497.4010403@wildenhain.de> Message-ID: En Fri, 19 Sep 2008 02:11:51 -0300, Tino Wildenhain escribi?: > Also I never saw a list where the threading often goes wrong like > this here - is there any special setup or is it just peoples MUA > which screws up? Perhaps it's due to the newsgroup/list duality... -- Gabriel Genellina From god1124 at gmail.com Thu Sep 4 21:01:25 2008 From: god1124 at gmail.com (Dream) Date: Thu, 4 Sep 2008 18:01:25 -0700 (PDT) Subject: Tkinter Radio button on the second window Message-ID: The code create 2 windows. 2 radiobuttons are put on the second window. A control variable "v" is binded to the 2 widgets. But when I run the code, I found the control variable not binded succsessfully: The second radiobutton was not selected by default; Click ed each button always print 1. I don't know what is wrong. So I need help.Thanks. from Tkinter import * def test(event_instance): print v.get() window1=Tk() window2=Tk() v=IntVar() v.set(1) radiobutton1=Radiobutton(window2,variable=v,value=0) radiobutton2=Radiobutton(window2,variable=v,value=1) radiobutton1.pack() radiobutton2.pack() radiobutton2.bind('',test) radiobutton1.bind('',test) window1.mainloop() From tchendrix at gmail.com Tue Sep 23 08:37:44 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 05:37:44 -0700 (PDT) Subject: finding domain name Message-ID: hi group. I'm new to python and need some help and hope you can answer this question. I have a situation in my code where i need to create a file on the server and write to it. That's not a problem if i hard code the path. However, the domain name needs to be dynamic so it is picked up automatically. The path to our websites is home/sites/xxxxx/ where xxxxx represents the domain name. How can I find the domain name of the current url being viewed. From dblubaugh at belcan.com Mon Sep 29 13:16:14 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 13:16:14 -0400 Subject: PYTHON WORKING WITH PERL ?? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> To All, I was wondering if it was possible to have a situation where a programming project would utilized BOTH python and perl? Such as utilizing python for internet programming and then utilize perl for text processing and systems programming? Is this even feasible??? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From joncle at googlemail.com Wed Sep 10 13:33:18 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 10:33:18 -0700 (PDT) Subject: Reading binary data References: Message-ID: On 10 Sep, 18:14, Aaron Scott wrote: > I've been trying to tackle this all morning, and so far I've been > completely unsuccessful. I have a binary file that I have the > structure to, and I'd like to read it into Python. It's not a > particularly complicated file. For instance: > > signature ? char[3] ? ? "GDE" > version ? ? uint32 ? ? ?2 > attr_count ?uint32 > { > ? ? attr_id ? ? ? ? uint32 > ? ? attr_val_len ? ?uint32 > ? ? attr_val ? ? ? ?char[attr_val_len] > > } ... repeated attr_count times ... > > However, I can't find a way to bring it into Python. This is my code > -- which I know is definitely wrong, but I had to start somewhere: > > import struct > file = open("test.gde", "rb") > output = file.read(3) > print output > version = struct.unpack("I", file.read(4))[0] > print version > attr_count = struct.unpack("I", file.read(4))[0] > while attr_count: > ? ? ? ? print "---" > ? ? ? ? file.seek(4, 1) > ? ? ? ? counter = int(struct.unpack("I", file.read(4))[0]) > ? ? ? ? print file.read(counter) > ? ? ? ? attr_count -= 1 > file.close() > > Of course, this doesn't work at all. It produces: > > GDE > 2 > --- > ? > --- > ??? > > I'm completely at a loss. If anyone could show me the correct way to > do this (or at least point me in the right direction), I'd be > extremely grateful. What if we view the data as having an 11 byte header: signature, version, attr_count = struct.unpack('3cII', yourfile.read(11)) Then for the list of attr's: for idx in xrange(attr_count): attr_id, attr_val_len = struct.unpack('II', yourfile.read(8)) attr_val = yourfile.read(attr_val_len) hth, or gives you a pointer anyway Jon. From Ross at no.thanks.spammers Thu Sep 18 12:55:01 2008 From: Ross at no.thanks.spammers (RGK) Date: Thu, 18 Sep 2008 12:55:01 -0400 Subject: Blanket font setting? Message-ID: <48d287e5$1@news.alcatel.com> I'm doing an app with the AUI manager capabilities (using some of the wxPython demo's for help). All is well, except I'm a bit disappointed with the font management. The default font for all the widgets (TextCtrl's, StaticText's etc) are a bit large for my design intent and as I try to adjust that, it appears I have to do a font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(9) Then, for every texty thing: myTextThing.setfont(font) someOtherThing.setfont(font) Thus if I have hundreds of texty things, I've got to assign that hundreds of times. Is there any sort of blanket font setting, perhaps like: wx.SystemSettings_SetFont(font) #this doesn't exist that could set everything with one fell swoop? Thanks for your attention... Ross. From almar.klein at gmail.com Thu Sep 18 06:12:05 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 18 Sep 2008 12:12:05 +0200 Subject: SSH using PEXPECT In-Reply-To: <48cb87f0$0$6999$426a74cc@news.free.fr> References: <4cc538ef-3b08-404c-b107-ff6605c307a2@t54g2000hsg.googlegroups.com> <48cb87f0$0$6999$426a74cc@news.free.fr> Message-ID: Hi, Wanting to use pexpect on windows too, I ran into wexpect. http://sage.math.washington.edu/home/goreckc/sage/wexpect/ I haven't given it a try yet. Does anyone have experience with that? Almar 2008/9/13 nntpman68 > Hi, > > yellowblueyellow at gmail.com wrote: > >> On Sep 10, 7:01 pm, Sean DiZazzo wrote: >> > > I am using windows and for reason it wont let me use pexpect even tho >> I have CYGWIN installed >> >> >> I get the following error >> >> Traceback (most recent call last): >> File "new.py", line 1, in >> import ssh_session >> File "C:\Python25\lib\ssh_session.py", line 7, in >> from pexpect import * >> File "C:\Python25\lib\site-packages\pexpect.py", line 85, in >> >> support it. Pexpect is intended for UNIX-like operating >> systems.""") >> ImportError: No module named resource >> >> > You might have cygwin installed, > but the error mesage sems to indicatem that you don't use cygwin's pythonm > but the normal windows python, > > You see, that it complains about pexpcet in > C:\Python25\lib\site-packages\pexpect.py > > > > just open a cygwin window: > > then cd to the directory containign your script and type > python new.py. > > you should have at least another error message > > > bye > > > N > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at anjanesh.net Wed Sep 10 09:50:21 2008 From: mail at anjanesh.net (Anjanesh Lekshminarayanan) Date: Wed, 10 Sep 2008 19:20:21 +0530 Subject: PHP's str_replace ? Message-ID: <48C7D09D.2080604@anjanesh.net> In PHP, if I do str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) it'll replace all vowels with a hyphen in string $str. Is there some equivalent in Python ? Thanks From notvalid2 at sbcglobal.net Tue Sep 9 00:27:08 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 08 Sep 2008 21:27:08 -0700 Subject: Syntax Problem with strptime in Python 2.4 In-Reply-To: <6ikegtFr3ab7U1@mid.uni-berlin.de> References: <6ikegtFr3ab7U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > W. eWatson wrote: > >> Apparently, use of strptime of datetime needs a workaround in Python 2.4 >> to work properly. The workaround is d = >> datetime.datetime(*(time.strptime(date_string, format)[0:5])). However, >> when I try to use it, or even use it the regular way, it fails with >> AttributeError: type object 'datetime.datetime' has no attribute >> 'datetime'. >> From the following code code segment: >> >> format = '%Y%m%d_%H%M%S' >> #d=datetime.strptime('20080321_113405', format)-- typical use >> print time.strptime('20080321_113405', format)[0:5] >> d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5]) >> >> Does anyone know how to make this work in 2.4? If not, is there a way to >> achieve the same result? > > This is not what you think it is. All your problem is that you do > > from datetime import datetime > > which imports the datetime-class, but then try to access > > datetime.datetime > > as if you had done > > import datetime. > > > This actually is a wart in the datetime-module - it would be better if the > classes in there would follow PEP-8. > > Diez That's it. Thanks. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From uomiocenekidd at gmail.com Mon Sep 22 06:39:18 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:39:18 -0700 (PDT) Subject: www amateurgalore net - Free Message-ID: www amateurgalore net . . . *******CLICK HERE******** http://vids365.cn/www-amateurgalore-net ***************************** . . . . . . . . . . . . www amateurgalore net From s.mientki at ru.nl Fri Sep 26 09:35:41 2008 From: s.mientki at ru.nl (Stef Mientki) Date: Fri, 26 Sep 2008 15:35:41 +0200 Subject: how to search multiple textfiles ? Message-ID: <48DCE52D.4010406@ru.nl> hello, I want to search multiple textfiles (python source files) for a specific word. I can find all files, open them and do a search, but I guess that will be rather slow. I couldn't find any relevant information through google. Does anyone know of a search library that performs this task fast ? If it indeed only concerns py-files, is there another way of searching words ? ( I could imagine that such a "py-only-search" would have benefits, because you could set a flag to see the words in comment yes or no ) thanks, Stef Mientki Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629. From coolkid246 at googlemail.com Thu Sep 4 06:09:40 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:09:40 -0700 (PDT) Subject: =?ISO-8859-1?Q?vergleich_kredit_in_Eberswalde_online_kredit_guensti?= =?ISO-8859-1?Q?g_kredit_ohne_schufa_sofortzusage_schufafreie_kredite_zinsen?= =?ISO-8859-1?Q?_online_mit_krediten_ohne_schufa_banken_ohne_schufa_eil_kred?= =?ISO-8859-1?Q?it_ohne_schufa_autokredit_online=2Dkredit_sofort_kredit_online?= =?ISO-8859-1?Q?_kreditantrag_online_besten_online_kredite_www_kredit_ohne_s?= =?ISO-8859-1?Q?chufa_online_kredite_ratenkredit_online__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTI?= =?ISO-8859-1?Q?GE_KREDITE_ONLINE_=2B=2B=2B_KREDITE_IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_?= =?ISO-8859-1?Q?=2B_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONL?= =?ISO-8859-1?Q?INE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW?= =?ISO-8859-1?Q?=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO?= =?ISO-8859-1?Q?=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONL?= =?ISO-8859-1?Q?INE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW?= =?ISO-8859-1?Q?=2EKREDITE=2DONLINE=2D244=2EINFO=2F_=2B_=2B_=2B_=2B_______________________bark?= =?ISO-8859-1?Q?redit_suche_kredit_ohne_schufa_in_Soltau_online_kredite_test?= =?ISO-8859-1?Q?_barkredit_ohne_schufa_in_W=FCrzburg_kleinkredit_kredite_kond?= =?ISO-8859-1?Q?itionen_in_Bad_postbank_kredit_umschuldung_in_Bayreuth_onlin?= =?ISO-8859-1?Q?e_kredit_de_eilkredite_in_Darmstadt_postbank_kredit_beamtend?= =?ISO-8859-1?Q?arlehen_in_Grimmen_kredit_arbeitslos_guenstiger_kredit_ohne_?= =?ISO-8859-1?Q?schufa_in_Eisenberg_kredit_ohne_gehaltsnachweis_expresskredi?= =?ISO-8859-1?Q?t_in_Parchim_www_kredit_ohne_schufa_de_kredit_ohne_schufa_on?= =?ISO-8859-1?Q?line_net_in_Gummersbach_online_sofort_kredit_ohne_schufa_kre?= =?ISO-8859-1?Q?dite_selbstaendige_in_Goslar_privatkredite_sofortkredit_ohne?= =?ISO-8859-1?Q?_auskunft_in_Freiberg_schufa_freie_kredite_bargeld_online_in?= =?ISO-8859-1?Q?_Belzig_kredite_finanzierung_immobilienkredit_in_Leipzig_kre?= =?ISO-8859-1?Q?dite_finanzierung_student_kredit_in_Segeberg_guenstige_kredi?= =?ISO-8859-1?Q?te_bonitaetspruefung_online_in_Wunsiedel=2FFichtelgeb=2E_www_kre?= =?ISO-8859-1?Q?dit_ohne_schufa_online_kreditangebot_in_Goeppingen_kreditkar?= =?ISO-8859-1?Q?te_ohne_schufa_kredite_online_vergleich_in_Bitterfeld_kleink?= =?ISO-8859-1?Q?redit_ohne_schufa_www_kredit_ohne_schufa_online_net_in_Forst?= =?ISO-8859-1?Q?_online_kredit_von_privat_kredite_finanzierung_in_Luckenwald?= =?ISO-8859-1?Q?e____=2D_kredit_trotz_schufa_und_ohne_euro_kredit_ohne_schufa_?= =?ISO-8859-1?Q?in_Annaberg=2DBuchholz_=2D_kredit_ohne_schufa_vergleich_online_k?= =?ISO-8859-1?Q?redite_oesterreich_in_Detmold_=2D_sofort_kredite_ohne_schufa_s?= =?ISO-8859-1?Q?erioese_online_kredite_in_Eckernfoerde_=2D_kredit_arbeitslos_p?= =?ISO-8859-1?Q?rivatkredit_in_Anklam_=2D_darlehen_schufafrei_kredite_ohne_sch?= =?ISO-8859-1?Q?ufa_auskunft_in_Diepholz_=2D_kredite_finanzierung_online_kredi?= =?ISO-8859-1?Q?te_im_vergleich_in_Hildburghausen_=2D_kreditvergleich_postbank?= =?ISO-8859-1?Q?_kredit_online_in_Cham_=2D_kredite_euro_kredit_ohne_schufa_in_?= =?ISO-8859-1?Q?Meschede_=2D_postbank_online_kredit_auto_ohne_schufa_in_Neustr?= =?ISO-8859-1?Q?elitz_=2D_www_kredit_ohne_schufa_online_net_autokredit_in_M=FCh?= =?ISO-8859-1?Q?ldorf_=2D_kredite_vergleich_kredit_ohne_schufa_test_in_Greiz_=2D?= =?ISO-8859-1?Q?_besten_online_kredite_kredite_finanzierungen_in_Mosbach_=2D_i?= =?ISO-8859-1?Q?mmobilien_kredite_internet_kredit_in_Grabfeld_=2D_kredite_onli?= =?ISO-8859-1?Q?ne_vergleich_privatkredit_ohne_schufa_in_Korbach?= Message-ID: vergleich kredit in Eberswalde online kredit guenstig kredit ohne schufa sofortzusage schufafreie kredite zinsen online mit krediten ohne schufa banken ohne schufa eil kredit ohne schufa autokredit online-kredit sofort kredit online kreditantrag online besten online kredite www kredit ohne schufa online kredite ratenkredit online + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + barkredit suche kredit ohne schufa in Soltau online kredite test barkredit ohne schufa in W?rzburg kleinkredit kredite konditionen in Bad postbank kredit umschuldung in Bayreuth online kredit de eilkredite in Darmstadt postbank kredit beamtendarlehen in Grimmen kredit arbeitslos guenstiger kredit ohne schufa in Eisenberg kredit ohne gehaltsnachweis expresskredit in Parchim www kredit ohne schufa de kredit ohne schufa online net in Gummersbach online sofort kredit ohne schufa kredite selbstaendige in Goslar privatkredite sofortkredit ohne auskunft in Freiberg schufa freie kredite bargeld online in Belzig kredite finanzierung immobilienkredit in Leipzig kredite finanzierung student kredit in Segeberg guenstige kredite bonitaetspruefung online in Wunsiedel/Fichtelgeb. www kredit ohne schufa online kreditangebot in Goeppingen kreditkarte ohne schufa kredite online vergleich in Bitterfeld kleinkredit ohne schufa www kredit ohne schufa online net in Forst online kredit von privat kredite finanzierung in Luckenwalde - kredit trotz schufa und ohne euro kredit ohne schufa in Annaberg- Buchholz - kredit ohne schufa vergleich online kredite oesterreich in Detmold - sofort kredite ohne schufa serioese online kredite in Eckernfoerde - kredit arbeitslos privatkredit in Anklam - darlehen schufafrei kredite ohne schufa auskunft in Diepholz - kredite finanzierung online kredite im vergleich in Hildburghausen - kreditvergleich postbank kredit online in Cham - kredite euro kredit ohne schufa in Meschede - postbank online kredit auto ohne schufa in Neustrelitz - www kredit ohne schufa online net autokredit in M?hldorf - kredite vergleich kredit ohne schufa test in Greiz - besten online kredite kredite finanzierungen in Mosbach - immobilien kredite internet kredit in Grabfeld - kredite online vergleich privatkredit ohne schufa in Korbach From grante at visi.com Wed Sep 10 13:39:24 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 12:39:24 -0500 Subject: md5 differences References: Message-ID: On 2008-09-10, Wojtek Walczak wrote: > On Wed, 10 Sep 2008 19:12:28 +0200, Python wrote: >> Arno at Computer:~% echo "test" > test.txt >> >> Arno at Computer:~% md5 test.txt >> MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 > >> >>> import md5 >> >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >> '90364ed45b452d43378629c20543a81d' > > > Works for me: > >>>> import md5 >>>> f = open('test.txt').read() >>>> md5.new(f).hexdigest() > 'd8e8fca2dc0f896fd7cb4cb0031ba249' >>>> > > IOW, don't pass the path to the file to md5.new, but the contents > of this file. > > The strange thing is that >>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() > returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. Same here. -- Grant Edwards grante Yow! What PROGRAM are they at watching? visi.com From gminick at bzt.bzt Tue Sep 2 10:46:44 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Tue, 2 Sep 2008 14:46:44 +0000 (UTC) Subject: What is module initialization? References: <48bd4799$0$17215$426a74cc@news.free.fr> Message-ID: On Tue, 2 Sep 2008 15:32:07 +0100, dudeja.rajat at gmail.com wrote: > But if I do :- >#question.py > from myglobals import * > myglobals.answer = "WTF ?" > > will this work? Why won't you try? In this case you should receive NameError. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From steven at REMOVE.THIS.cybersource.com.au Wed Sep 17 01:29:51 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 17 Sep 2008 05:29:51 GMT Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> <6jb6juF2co8rU1@mid.individual.net> Message-ID: On Wed, 17 Sep 2008 13:52:13 +1200, greg wrote: > Arnaud Delobelle wrote: > >> Or: >> >> import ModuleName as this_module > > Or: > > this_module = __import__(__name__) > > then you don't have to change anything. I like that solution! And it works regardless of whether the module holding it is imported, or is being executed from the commandline. Thanks to everyone who made a suggestion. -- Steven From steve at holdenweb.com Mon Sep 29 13:38:02 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 13:38:02 -0400 Subject: PYTHON WORKING WITH PERL ?? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: > To All, > > > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? Such as > utilizing python for internet programming and then utilize perl for text > processing and systems programming? Is this even feasible??? > > > Thanks, > So sorry to hear Google isn't available from your network ;-) http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Thu Sep 18 03:55:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 18 Sep 2008 03:55:07 -0400 Subject: member functions in a class In-Reply-To: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> References: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> Message-ID: Karl Kobata wrote: > I am new to python and am wondering. When I create a class, with ?def? > functions and if this class is instantiated say 50 times. Does this > mean that all the ?def? functions code within the class is duplicated > for each instance? > > Can someone give me a short and simple answer as to what happens in python? To expand slightly on Gary's answer. Dotted names -- ob.attr -- are typically (but not always) resolved as follows: does ob have attribute attr? If yes, get the corresponding object. If no, does type(ob) have attribute attr? If yes, get the corresponding object. In no, look in the baseclasses of type(ob) in some order (details not important here). So, instance methods are class attributes and instance.method will resolve to the method attribute of type(instance) -- assuming that the instance does not have an attribute of the same name. Lookup for special methods (with reserved __xxx__ names) may go directly to the class and never look at the instance attributes. From callen314 at gmail.com Wed Sep 24 18:07:04 2008 From: callen314 at gmail.com (Craig Allen) Date: Wed, 24 Sep 2008 15:07:04 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48d9e932$0$6127$426a34cc@news.free.fr> Message-ID: > Why, yes, I am wearing my BOFH hat. How could you tell? > > -- > Tim Rowe evil, but I think you may be a BSEFH, not a BOFH. From maric at aristote.info Mon Sep 15 08:16:00 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 14:16:00 +0200 Subject: Python and Open Office In-Reply-To: References: Message-ID: <200809151416.00391.maric@aristote.info> Le Wednesday 10 September 2008 22:04:57 Greg Lindstrom, vous avez ?crit?: > Hello, > > I would like to create and manipulate Open Office documents using Python. > I have found then UNO Python page and odfpy modules which seem to be > exactly what I need. The odfpy manual is, to me, a confusing list of > objects and methods (it's an impressive list!), but does not have much in > the way of how to use them. For example, I can open a spreadsheet and > create new pages (there's a nice example near the back of the manual) but I > can't figure out how to open an existing spreadsheet and list the names of > the individual sheets ("tabs"). > > I have written an application that access Microsoft Excel and creates > reports for work, but would like to create an Open Source version using > Open Office and release it to the community (and maybe get a talk at PyCon > :-). > > Is there someone here who can help me out, or is there an appropriate > mailing list for me to join? > > Thanks > > --greg I don't like the UNO solution, first, UNO API is not that practical, second you'll need to have a running instance of openoffice, which I wouldn't want to manage for a server application in term of performance, reliability and security. I had to produce text document within a zope application once, and did this by replacing variables values in a template directly in the xml, the function was no more than twenty lines long, and used only stdlib modules (see below). A far better approach IMHO. Of course for big manipultaion it could be more error prone and it's a good news that odfpy exists (I didn't use for my example because it was too simple), so I give it a try : >>>[1]: import odf.opendocument >>>[2]: import odf.table >>>[3]: new = odf.opendocument.OpenDocumentSpreadsheet() >>>[4]: for n in ('titi', 'tata', 'toto') : new.spreadsheet.addElement(odf.table.Table(name=n)) ...: >>>[5]: new.save("toto.ods") >>>[6]: maric at redflag1 17:10:27:~/odfpy-0.8$ ooffice toto.ods # document ok ! maric at redflag1 17:10:31:~/odfpy-0.8$ ipython >>>[12]: import odf.table >>>[13]: import odf.opendocument >>>[14]: for t in old.spreadsheet.getElementsByType(odf.table.Table) : print t.getAttribute('name') ....: ....: titi tata toto Great ! This was the function I use (from a local copy of the product I backed up, I have not the application working nor the svn server so I didn't test this version, but it's mainly the idea that is interesting) : def updateVariablesInSXW(self, variables, sxw) : from zipfile import ZipFile from StringIO import StringIO from xml.dom.minidom import parseString sxw = StringIO(sxw) zip = ZipFile(sxw, 'a') dom_document = parseString(zip.read('content.xml')) dom_styles = parseString(zip.read('styles.xml')) def update_variables(node) : if node.nodeName in ('text:variable-set','text:variable-get') : variable = node.attributes['text:name'].value if variable in variables : value = variables[variable].decode('utf-8') if node.attributes.has_key('text:value') : node.attributes['text:value'].value = value if node.attributes.has_key('text:string-value') : node.attributes['text:string-value'].value = value if node.firstChild is not None : node.firstChild.nodeValue = value for i in node.childNodes : update_variables(i) for i in (dom_document, dom_styles) : update_variables(i) zip.writestr('content.xml', dom_document.toxml().encode('utf-8')) zip.writestr('styles.xml', dom_styles.toxml().encode('utf-8')) sxw.seek(0) return zip.read() and a sample use (code frome a Zope product, facture is french term for invoice) : security.declarePrivate('prepareFacture') def prepareFacture(self) : import math price, devise = self.getProgramme().getPrice().split() end = self.getProgramme().end() start = self.getProgramme().start() subscriber = self.getSubscriberInfo() variables = { 'fullname' : subscriber.fullname, 'address' : subscriber.address, 'company' : subscriber.company, 'price' : price, 'quantity' : str(1), 'duration' : str(int(math.ceil(end - start))), 'ht' : price + ' ' + devise, 'ttc' : str(float(price)*1.196) + ' ' + devise, 'tva' : str(float(price)*0.196) + ' ' + devise, 'cours' : self.getProgramme().title_or_id(), 'location' : self.getProgramme().getLocation().title_or_id(), 'start' : self.toLocalizedTime(start), 'end' : self.toLocalizedTime(end), #'timetable' : self.getProgramme().getTimetable(), 'num_facture' : self.getNumFacture(), 'cp' : subscriber.postal, 'country' : subscriber.country, 'city' : subscriber.city, } if subscriber.country.strip().lower() == 'france' : template_name = 'ModeleFactureFormationTVA.sxw' else : template_name = 'ModeleFactureFormation.sxw' template = str(getattr(self, template_name)) facture = self.updateVariablesInSXW(variables, template) self.setFactureSXW(facture, filename="facture_%s.sxw" % self.getNumFacture()) -- _____________ Maric Michaud From fredrik at pythonware.com Fri Sep 12 13:33:48 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 19:33:48 +0200 Subject: Which version In-Reply-To: <92da89760809121028s1d9b8b46g464d54937c67ba0f@mail.gmail.com> References: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> <92da89760809121028s1d9b8b46g464d54937c67ba0f@mail.gmail.com> Message-ID: Eric Wertman wrote: > The subprocess module is one though footnote: subprocess works on older versions too, and can be trivially installed along with your application under Python 2.2 and 2.3. binary builds for Windows are available here: http://effbot.org/downloads/#subprocess From steve at REMOVE-THIS-cybersource.com.au Sun Sep 28 04:26:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 08:26:33 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <00ef3974$0$20666$c3e8da3@news.astraweb.com> On Sun, 28 Sep 2008 03:55:46 -0400, Terry Reedy wrote: > est wrote: >>>From python manual >> >> str( [object]) >> >> Return a string containing a nicely printable representation of an >> object. For strings, this returns the string itself. The difference >> with repr(object) is that str(object) does not always attempt to return >> a string that is acceptable to eval(); its goal is to return a >> printable string. If no argument is given, returns the empty string, >> ''. >> >> >> now we try this under windows: >> >>>>> str(u'\ue863') >> Traceback (most recent call last): >> File "", line 1, in >> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in >> position 0 >> : ordinal not in range(128) > > In 3.0 this is fixed: >>>> str('\ue863') # u prefix is gone > '\ue863' >>>> str(b'123') # b prefix is added > "b'123'" > > Problems like this at least partly motivated the change to unicode > instead of bytes as the string type. I'm not sure that "fixed" is the right word. Isn't that more or less the same as telling the OP to use unicode() instead of str()? It merely avoids the problem of converting Unicode to ASCII by leaving your string as Unicode, rather than fixing it. Perhaps that's the right thing to do, but it's a bit like the old joke: "Doctor, it hurts when I do this." "Then don't do it!" As for the second example you give: >>> str(b'123') # b prefix is added "b'123'" Perhaps I'm misinterpreting it, but from here it looks to me that str() is doing what repr() used to do, and I'm really not sure that's a good thing. I would have expected that str(b'123') in Python 3 should do the same thing as unicode('123') does now: >>> unicode('123') u'123' (except without the u prefix). -- Steven From dblubaugh at belcan.com Thu Sep 11 18:01:48 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 11 Sep 2008 18:01:48 -0400 Subject: Has any one out there ever worked with the Rpyc, which is a remote process call for python Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380500CF94@AWMAIL04.belcan.com> To All, Has any one out there ever worked with the Rpyc, which is a remote process call for python? David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From code at pizzashack.org Wed Sep 3 02:41:32 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 3 Sep 2008 02:41:32 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: References: <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> Message-ID: <20080903064132.GV29228@dragontoe.org> On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote: > Derek Martin wrote: > > On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: > >> but the instances of `Popen` are no actions. There's no way to > >> "execute" a `Popen` instance. > > > > Yes there is... you execute it when you instantiate the object. At > > the time of instantiation, you "open" the "P" (pipes). > > The subprocess module is also supposed to replace os.system and > os.spawn*, neither of which involve opening pipes. Sigh... wasn't finished, sent by accident. Anyway, to continue... The subprocess module also can be used to replace these two functions, though to be honest, it's not clear to me why one would do so. On the whole, I choose not to use the subprocess module because I find it tedious, and less tedious interfaces (like os.system() and os.popen(), and even the popen2 module) exist. [But, you can probably guess that I write code almost exclusively for POSIX-ish systems...] If all you want is the equivalent of os.system() or os.spawn(), then it seems to me the subprocess module is overly heavy-handed, leaving a bunch of not useful state laying around in your environment... Not to mention you probably already need the os module, so you could save yourself the trouble and overhead of importing subprocess. > All rationalizations aside, I think Popen is a poor name for the > class. Even within this thread, a number of people clearly disagree with you. To say nothing of the maintainers... :) I really think it's not worse (and actually better) than "process"... for reasons I already explained. The argument that the object is a process is spurious. The object is, in actuality, an instance of *COMMUNICATION* between two processes. It's true that a process is started as a result, so that the first process has a second to be able to communicate with; and a (tiny) bit of information (the PID) is maintained about that process, mostly for no useful reason... However the object mainly is a collection of pipes, and some methods for communicating over them, to another process that, out of necessity just happens to be a child of the current one. If you think about what the methods do, and understand how they actually work, I think it will become clear that this is the case. Does communicate() operate on the process? ABSOLUTELY NOT -- it operates on the pipes. poll() and wait() may arguably act upon the process (they actually request information about the process from the kernel), but the goal in doing so is to find out the status of the communication: is it done, and if so was it successful? If you abstract the concept from its implementation, this is clearly true. I could concede that it may not be clear to someone unfamiliar with C programming (perhaps especially in a Unix environment, though Windows does have a similar, but apparently broken function) what "popen" means or does, but the manual has ample references to explain that, I think. It's no less clear than the popen() function itself! > But I would imagine the odds of it ever being changed are miniscule > (Python 4?). The truth is, in the end, I personally don't really care; though if it were changed, I would hope something genuinely better were chosen. I feel strongly that "process" ain't it. My motivation in posting in this thread is mostly to point out how silly it is to argue or complain about the name of some bit of logic in a programming language, especially once it's already been released (though I doubt most of the participants got the point). The time to do this is when the feature is in the planning stages, if ever... Some people take this stuff way, way too seriously, and also can't seem to imagine that another perspective besides their own exists, and especially that their own might just not be optimal/correct. Posting to Usenet/maling lists and saying "Why is X called X? It should be called Y!" is not likely to ever produce any sort of useful result. ;-) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From fredrik at pythonware.com Fri Sep 5 13:36:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 19:36:56 +0200 Subject: Case-insensitive string compare? In-Reply-To: <200809051331.40609.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050059.17038.maric@aristote.info> <200809051331.40609.maric@aristote.info> Message-ID: Maric Michaud wrote: > I suspect you are coming to conclusions a bit quickly, without taking the pain > of understanding the whole discussion. I'm pretty sure I was the first one to post an answer in this thread, and I understand Python design and performance issues very well, thank you. (but given your talk about "the cost of whitespace" in a response to a comment about performance in that other subthread, it's obvious that you're just here to provide noise. plonk plonk.) From dudeja.rajat at gmail.com Tue Sep 30 16:21:02 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 30 Sep 2008 21:21:02 +0100 Subject: Backup a directory Message-ID: Hello, I'm looking for a script that creates a backup of a directory but keeps only one backup. I've tried using all the os modules commands but could not create one. Does any one has any such custom script or function? Thanks and regards, rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Sep 25 06:28:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 12:28:35 +0200 Subject: Connecting to SMB share in python References: <2008092518182581491-rokwok@newsguycom> Message-ID: <6k17ejF5dlviU1@mid.uni-berlin.de> Ronnie Kwok wrote: > Thank you for the reply! > > Yes, I am running the script under linux and it will be doing some > processing before copying it over to the samba mount. > > It's totally fine to mount it with os.sys(...) approach but I am just > thinking if there's other option. None that is any more comfortable. If anything, you'd need smbclient or some such to list and fetch data - which is *much* more complicated that simply mounting a share defined in fstab. Diez From news1234 at free.fr Mon Sep 8 17:30:42 2008 From: news1234 at free.fr (nntpman68) Date: Mon, 08 Sep 2008 23:30:42 +0200 Subject: exit() In-Reply-To: References: Message-ID: <48c59980$0$7014$426a74cc@news.free.fr> Hi Jean-Paul, Jean-Paul Calderone wrote: > On Mon, 08 Sep 2008 21:03:48 +0200, Christian Heimes > wrote: >> Gary Robinson wrote: >>> In Python 2.5.2, I notice that, in the interpreter or in a script, I >>> can exit with: >>> >>> exit() >> >> The exit callable is defined in the site module. Check out site.py! It >> shouldn't be used in code. It was added to help newbies to 'escape' >> from an interactive Python shell. >> > > It works. Why shouldn't it be used? > > Jean-Paul Backwards compatibility vs. saving 4 characters. I'd stick with backwards compatibility bye N From wuwei23 at gmail.com Mon Sep 15 21:44:29 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 15 Sep 2008 18:44:29 -0700 (PDT) Subject: Rebinding __setattr__ References: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> <48cecfb3$0$3164$e4fe514c@dreader31.news.xs4all.nl> Message-ID: <23fe179e-e4c0-42c6-b61f-e248636a9701@i24g2000prf.googlegroups.com> On Sep 16, 7:12?am, "Jan Schilleman" wrote: > That still would require changing the source of the library ... And i'm not > sure if it would have side effects. I'm not on a Windows box so can't test this atm, but perhaps you could make a proxy object? class DispatchBaseProxy(object): def __init__(self): self.base = DispatchBaseClass() def __setattr__(self, attr, value): "insert extra functionality here" setattr(self.base, attr, value) def __getattr__(self, attr): getattr(self.base, attr) ...etc... From fredrik at pythonware.com Fri Sep 12 13:31:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 19:31:07 +0200 Subject: Which version In-Reply-To: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> References: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> Message-ID: Don wrote: > I'm a reasonably experienced in other languages and have just decided to > get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed, > is this good enough to start out with or am I likely to encounter bugs that > have been fixed in later versions. Python 2.4 is definitely good enough to start with. The bugs you'll find in released versions are usually pretty obscure; I've been using Python since release 1.1 or so, and I cannot remember ever having to upgrade due to a critical bug in the version I was using. From henrypopie at gmail.com Tue Sep 23 11:59:30 2008 From: henrypopie at gmail.com (henrypopie at gmail.com) Date: Tue, 23 Sep 2008 08:59:30 -0700 (PDT) Subject: download redtube video - Free References: Message-ID: <0805ca16-03ed-425c-9979-928e211dc931@r15g2000prd.googlegroups.com> Or download RedTube videos online: http://www.download-redtube.com/ From dudeja.rajat at gmail.com Wed Sep 3 14:40:40 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Wed, 3 Sep 2008 19:40:40 +0100 Subject: Looking for File comparison utility that produces actual differences Message-ID: Hi, I looking for a file comparison utility in Python that works like 'diff' command in Unix and 'comp' in Windows. The present 'cmd' in filecmp module only presents output in the form of 1 or 0 i.e whether the 2 files differ or not? So, I'm lookin for something that generates actual differences and moreover it is cross platform as well. As I need that same thing in both my windows and linux box. Even if it is a utlility please suggest. Thanks and regards, Rajat From alainpoint at yahoo.fr Wed Sep 24 02:40:59 2008 From: alainpoint at yahoo.fr (alain) Date: Tue, 23 Sep 2008 23:40:59 -0700 (PDT) Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> Message-ID: On Sep 22, 11:32?am, "Tim Leslie" wrote: > There is no need for a wrapper. Both numarray and Numeric have been > deprecated in favour of numpy, so numpy is the only one you need to > use. Numpy should have all the tools you need. If you find something > missing, there's a good chance it's included in scipy (which ?is built > on top of numpy). For full details seewww.scipy.org. I don't agree. I am myself a casual user of numpy without sophisticated needs. Numpy seems to be the only player in town and unfortunateely, though powerful, its syntax is not intuitive or easy to remember. I therefore welcome any attempt to simplify the api for a specific group of non-power users. Alain From ezra.taylor at gmail.com Tue Sep 30 15:09:06 2008 From: ezra.taylor at gmail.com (Ezra Taylor) Date: Tue, 30 Sep 2008 15:09:06 -0400 Subject: [Tutor] Replacing cmd.exe with custom .py application In-Reply-To: References: Message-ID: Is there something similar to /dev/null on Windows? On Tue, Sep 30, 2008 at 2:13 PM, Ezra Taylor wrote: > Joseph: > Check out subprocess. The subprocess module is on python > 2.4. Also, use subprocess.call("your command",shell=True) > > On Linux/Unix, the process is below > > import subprocess > > ret = subprocess.call("dir",shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT) > > print ret > > You should get a return value of 0. Which means that it was > successful. I'm still learning this myself, so some of these other > guys might have more input. > > > > > > On Tue, Sep 30, 2008 at 10:32 AM, A. Joseph wrote: >> >> >> Instead of going to the command line all the time, I want to create a small >> customized cmd.exe of my own, how can I get the return value from >> os.system() because I was thinking I can do soothing with os.system(), In >> case my question is not clear, just like an IDE that plugged in another >> .exe application. >> >> >> >> Sorry for any mistake in my question. Just help me if you can >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > -- > Ezra Taylor > -- Ezra Taylor From fredrik at pythonware.com Mon Sep 15 16:43:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 22:43:00 +0200 Subject: append on lists In-Reply-To: References: Message-ID: Armin wrote: > If d should reference the list a extended with a single list element > you need at least two lines > > a.append(7) > d=a why do you need two names for the same thing? > and not more intuitive d = a.append(7) unless you completely change the semantics of "append", your code would modify "a" as well. how is that "more intuitive"? side effects are bad as they are, but side effects in unexpected places is a really lousy idea. I don't think you've thought this one through, really. From san82moon at gmail.com Mon Sep 1 03:57:19 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 00:57:19 -0700 (PDT) Subject: how to find position of dictionary values Message-ID: hi, i have a dictionary as follows : kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} if user is enters the 3rd item of key phno, ie "dfsdf" in my dict, how can i find it is the third item in the internal list of phno of that dictionary? thanks you. From yellowblueyellow at gmail.com Wed Sep 10 21:04:42 2008 From: yellowblueyellow at gmail.com (yellowblueyellow at gmail.com) Date: Wed, 10 Sep 2008 18:04:42 -0700 (PDT) Subject: SSH using PEXPECT Message-ID: Hey , I need to SSH into a server .. (10.8.42.38) using pexpect the username is 'admin' and password is 'abc123' so far i have the following code import pexpect import sys import time import os foo = pexpect.spawn('ssh admin at 10.8.42.38') ssh_newKey = 'Are you sure you want to continue connecting' foo.expect = ssh_newKey foo.send = 'yes' foo.expect = 'password:' foo.send = 'abc123' ------------------------------------------------------------------------------------------------- does this look right? if not , could someone suggest a way to do this .. your help is much appreciated From george.sakkis at gmail.com Mon Sep 29 01:44:16 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 28 Sep 2008 22:44:16 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> Message-ID: <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> On Sep 29, 12:08 am, Terry Reedy wrote: > George Sakkis wrote: > > On Sep 28, 2:29 pm, process wrote: > > >> I have heard some criticism about Python, that it is not fully object- > >> oriented. > > > That's not a bug, it's a feature ;-) > > >> Why isn't len implemented as a str.len and list.len method instead of > >> a len(list) function? > > > As Terry Reedy wrote, partly history and partly practicality. There's > > no philosophical reason why we write "len(x)" (generic builtin), > > "x.append(1)" (method) or "del x[i]" (statement). The latter in > > particular is IMHO a design wart; there's no reason for not writing it > > as "x.delete(i)". > > As a general rule and matter of practice, methods that apply to all or > most classes (or all number classes) have built-in functions that call > the corresponding special method (or C-level slot). It would be easier to justify this rule if it was more clear-cut, and specifically if it was applied only to methods that are available to *all* classes (such as type() and getattr()) rather than the ill- defined "most classes". George From mrkylehayes at gmail.com Tue Sep 30 13:17:42 2008 From: mrkylehayes at gmail.com (Kyle Hayes) Date: Tue, 30 Sep 2008 10:17:42 -0700 (PDT) Subject: r"" Message-ID: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> Is there a way to use the 'r' in front of a variable instead of directly in front of a string? Or do I need to use a function to get all of the slashes automatically fixed? /thanks -Kyle From bellman at lysator.liu.se Thu Sep 4 03:05:19 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 4 Sep 2008 07:05:19 +0000 (UTC) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> Message-ID: Mensanator wrote: > No, but blank cells are 0 as far as Excel is concerned. > That behaviour causes nothing but trouble and I am > saddened to see Python emulate such nonsense. Then you should feel glad that the Python sum() function *does* signal an error for the closest equivalent of "blank cells" in a list: >>> sum([1, 2, 3, None, 5, 6]) Traceback (most recent call last): File "", line 1, in TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' Summing the elements of an empty list is *not* the same thing as summing elements of a list where one element is None. > There are no "empty" boxes. There are only boxes with > known quantities and those with unknown quantities. > I hope that's not too ivory tower. The sum() function in Python requires exactly one box. That box can be empty, can contain "known quantities" (numbers, presumably), or "unknown quantities" (non-numbers, e.g., None). But you can't give it zero boxes, or three boxes. I don't have a strong view of whether sum([]) should return 0 or raise an error, but please do not mix that question up with what a sum over empty cells or over NULL values should yield. They are very different questions. As it happens, the SQL sum() function (at least in MySQL; I don't have any other database easily available, nor any SQL standard to read) does return NULL for a sum over the empty sequence, so you could argue that that would be the correct behaviour for the Python sum() function as well, but you can't argue that because a sum *involving* a NULL value returns NULL. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "This isn't right. This isn't even wrong." ! bellman @ lysator.liu.se -- Wolfgang Pauli ! Make Love -- Nicht Wahr! From deets at nospam.web.de Mon Sep 22 06:44:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 Sep 2008 12:44:54 +0200 Subject: BadStatusLine: References: <4e3d5d97-1b5f-4593-9c33-ad8b57d59b05@f36g2000hsa.googlegroups.com> Message-ID: <6jpb99F4ericU1@mid.uni-berlin.de> noelob wrote: > Hi All, > > During performance testing of my web application, I occasionally get a > BadStatusLine exception from httplib. Reading > http://docs.python.org/lib/module-httplib.html#l2h-4021 tells me that > it's "Raised if a server responds with a HTTP status code that we > don't understand." Is there a way to find what the actual status code > returned was? I.e. the value that caused the exception to be thrown? > Under what circumstances is a BadStatusLine normally thrown? (e.g. > data corruption?) > > I'm quite new to python, but not to programming. Apologies if this is > a silly question ;) Bruno gave some advice already. I can only add that for the general task of inspecting HTTP-traffic, tools such as axis-tcpmon or wireshark are useful. There you can see what happens on the protocol level. Diez From clp at rebertia.com Sun Sep 21 13:13:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 21 Sep 2008 10:13:08 -0700 Subject: I tried erlang-ish [1|2] in python and something came out... In-Reply-To: References: Message-ID: <47c890dc0809211013g2e4e72aex570beebafd884c64@mail.gmail.com> On Sun, Sep 21, 2008 at 10:02 AM, process wrote: > In erlang you can cons like this: [1|2]. i tried this in python and it > didnt raise an error but i dont know what the result do In Python, like in C, the "|" operator on integers performs a bitwise-OR. To "cons" nondestructively onto a list, do e.g. [head_value] + tail, but note that this isn't very idiomatic. CPython's lists are implemented internally as arrays, not linked lists, hence why there's no "cons" operator in Python. You may also be interested in list.append() Regards, Chris > >>>> [1|2] > [3] >>>> [2|2] > [2] >>>> a = [2|2] >>>> a > [2] >>>> [2|3] > [3] >>>> [2|1] > [3] >>>> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From fredrik at pythonware.com Thu Sep 25 16:15:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 Sep 2008 22:15:50 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: References: Message-ID: Dmitry S. Makovey wrote: > you have just described OS package building ;) > > I can't speak for everybody, but supporting multiple platforms (PHP, Perl, > Python, Java) we found that the only way to stay consistent is to use OS > native packaging tools (in your case apt and .deb ) and if you're missing > something - roll your own package. After a while you accumulate plenty of > templates to chose from when you need yet-another-library not available > upstream in your preferred package format. Remember that some python tools > might depend on non-python packages, so the only way to make sure all that > is consistent across environment - use unified package management. you're speaking for lots of organizations, at least. rpm/debs from supplier's repository subversion (or equivalent) -> locally built rpm/debs + organization's favourite deployment tools --------------------------------- deployed application From larudwer at freenet.de Thu Sep 4 16:26:53 2008 From: larudwer at freenet.de (Ruediger) Date: Thu, 04 Sep 2008 22:26:53 +0200 Subject: why is self not passed to id()? Message-ID: Hello! Executing following little program gives me an TypeError. What makes me wonder is that foo does get an argument passed while bar doesn't. Can anyone explain why?????? Thanks Ruediger class foo(list): __hash__ = lambda x: id(x) class bar(list): __hash__ = id _s_ = set() _s_.add(foo()) _s_.add(bar()) rue at linux:~> python test01.py Traceback (most recent call last): File "test01.py", line 9, in _s_.add(bar()) TypeError: id() takes exactly one argument (0 given) From castironpi at gmail.com Sun Sep 28 16:54:15 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 13:54:15 -0700 (PDT) Subject: generate random digits with length of 5 References: <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> Message-ID: <07d14730-a585-4976-adda-540d32a2066d@y38g2000hsy.googlegroups.com> On Sep 28, 3:44?pm, Mensanator wrote: > On Sep 28, 3:11 pm, "Gary M. Josack" wrote: > > > > > Chris Rebert wrote: > > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac wrote: > > > >> Wondering if there is a better way to generate string of numbers with > > >> a length of 5 which also can have a 0 in the front of the number. > > > >>
> > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > >> elements
> > >> code = 'this is a string' + str(random_number[0]) +
> > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > >> + str(random_number[4])
>
> > > code = ''.join(str(digit) for digit in random_number)
>
> > > Regards,
> > > Chris
>
> > >> 
> > > >> -- > > >>http://mail.python.org/mailman/listinfo/python-list > > > will random.randint(10000,99999) work for you? > > It doesn't meet the OP's requirement that the number > can start with 0. Also, the method the OP asks about > returns a list of unique numbers, so no number can > be duplicated. He can get 02468 but not 13345. > > Now, IF it's ok to have an arbitrary number of leading > 0s, he can do this: > > >>> str(random.randint(0,99999)).zfill(5) > '00089' > >>> str(random.randint(0,99999)).zfill(5) > '63782' > >>> str(random.randint(0,99999)).zfill(5) > '63613' > >>> str(random.randint(0,99999)).zfill(5) > > '22315' Is a while loop until there are 5 distinct digits best otherwise? while 1: a= '%05i'% random.randint( 0, 99999 ) if len( set( a ) )== 5: break From fredrik at pythonware.com Sat Sep 13 09:54:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 15:54:05 +0200 Subject: How to run PyOS_InputHook from python code (i.e. yield to event loops) In-Reply-To: <87iqt0b1tj.fsf@ville-desktop.i-did-not-set--mail-host-address--so-tickle-me> References: <87wshpcaek.fsf@gmail.com> <87iqt0b1tj.fsf@ville-desktop.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: ville wrote: > That's tk-specific, right? I'm looking for a snippet that > > - Would not be tied to tk upstream, you said: "My actual use case is to keep a tkinter application responsive" From dullrich at sprynet.com Fri Sep 5 11:22:22 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 05 Sep 2008 10:22:22 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: In article <18c765e0-1dcb-4e40-93a9-32bb9d129b7e at n38g2000prl.googlegroups.com>, bearophileHUGS at lycos.com wrote: > David C. Ullrich: > > At least in mathematics, the sum of the elements of > > the empty set _is_ 0, while the maximum element of the > > empty set is undefined. > > What do you think about my idea of adding that 'default' argument to > the max()/min() functions? How the Python max and min functions should work has to do with how people want them to work and how people expect them to work. I wouldn't know about most people, but I would have been surprised if min([]) was not an error, and I would have been disappointed if sum([]) was not 0. >From a mathematical point of view, not that that's directly relevant, it doesn't make much sense to me to add that default argument. The max of a set is supposed to be the largest element of that set. If the set is empty there's no such thing. In Python you'd better make sure that S is nonempty before asking for max(S). That's not just Python - in math you need to make certain that S is nonempty and also other conditions before you're allowed to talk about max(S). That's just the way it is. Think about all the previously elected female or black presidents of the US. Which one was the tallest? > Bye, > bearophile -- David C. Ullrich From dullrich at sprynet.com Thu Sep 4 11:52:46 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 04 Sep 2008 10:52:46 -0500 Subject: Function decorators References: Message-ID: In article , Aigars Aigars wrote: > Good day all, I am learning Python and came up to decorators. The question > is: Why does function FoodList return value None? Because the function doesn't return anything, and in Python a function that doesn't explicitly return anything returns None. > The code in attachment. Thanks for not just pasting it into the post, like so: class Logger: def __init__(self, function): self.func = function def __call__(self, *args, **kwargs): print "Function %s called with args = %s, kwargs = %s" % (self.func.__name__, str(args), str(kwargs)) self.func(*args, **kwargs) @Logger def FoodList(a, b, c="spam"): text = "Food is %s, %s, %s" % (a, b, c) print text return text if __name__ == "__main__": a = FoodList("eggs", "potatoes") print a > Thank you, > Aigars--------------------------------------------------------------------- > [Image] -- David C. Ullrich From febkimbleox at gmail.com Sat Sep 27 07:16:59 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:16:59 -0700 (PDT) Subject: amater porno amater porno film free amater porno free amater porno - Free Message-ID: amater . . . *******CLICK HERE******** http://vids365.cn/amater ***************************** . . . . . . . . . . . . amater sat on one end while Tammy sat at the other. What did porno do, porno isn?t right, but yet, porno feels drawn to her. What did amater do, amater isn?t right, but yet, amater feels drawn to her. What did porno do, porno isn?t right, but yet, porno feels drawn to her. What did film do, film isn?t right, but yet, film feels drawn to her. What did free do, free isn?t right, but yet, free feels drawn to her. What did amater do, amater isn?t right, but yet, amater feels drawn to her. What did porno do, porno isn?t right, but yet, porno feels drawn to her. What did free do, free isn?t right, but yet, free feels drawn to her. What did amater do, amater isn?t right, but yet, amater feels drawn to her. What did porno do, porno isn?t right, but yet, porno feels drawn to her. What did &sex do, &sex isn?t right, but yet, &sex feels drawn to her. What did movies do, movies isn?t right, but yet, movies feels drawn to her. From amater back bedroom of amater house, amater had a pretty good view of amater yard. From porno back bedroom of porno house, porno had a pretty good view of porno yard. From videos back bedroom of videos house, videos had a pretty good view of videos yard. From san82moon at gmail.com Mon Sep 1 04:49:37 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:49:37 -0700 (PDT) Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: On Sep 1, 1:45 pm, Bruno Desthuilliers wrote: > lee a ?crit : > > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, > > ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? > > It's quite simple (hint : read the FineManual(tm) for dict.items() and > list.index()), but 1/totally inefficient and 2/not garanteed to yield a > single value (what if 'dfsdf' happens to be also the 4th item of the > list bound to key 'address' ?). > > May I suggest you rethink your data structure instead ? What you have > here is obviously a collection of 'phno/email/name/address'records. > These records shouldn't be split across different objects. Assuming > 'phno' is a unique identifier for each record, a better data structure > would be: > > records = { > 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > # etc > > } > > This way, the lookup is as simple and efficient as possible. > > My 2 cents.... hi, i agree with u, my data strusture is not efficient. but all the records,viz...name,phno, email,address are all generated at runtime , when the user enters them. so how can i design my datastructure in that case? From darcy at druid.net Wed Sep 10 12:40:06 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 10 Sep 2008 12:40:06 -0400 Subject: md5 differences In-Reply-To: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> References: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> Message-ID: <20080910124006.97ce9195.darcy@druid.net> On Wed, 10 Sep 2008 18:25:19 +0200 Python wrote: > Arno at Computer:~% echo "hello" | md5 > b1946ac92492d2347c6235b4d2611184 > [...] > >>> md5.new("hello").hexdigest() > '5d41402abc4b2a76b9719d911017c592' > > How do I get the same results? Send the same thing. >>> md5.new("hello\n").hexdigest() 'b1946ac92492d2347c6235b4d2611184' -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From george at george-net.de Tue Sep 16 06:54:47 2008 From: george at george-net.de (Georg Altmann) Date: Tue, 16 Sep 2008 12:54:47 +0200 Subject: MVC with Python In-Reply-To: References: Message-ID: David Boddie schrieb: > On Monday 15 September 2008 21:37, Georg Altmann wrote: > >> I need some advice on how to implement model-view-controller. I am >> trying to develop a GUI application with PyQt, yet the problem rather >> applies to mvc in general, not just GUI applications. >> >> Let's say the data is a list of objects with a common base class. The >> views are either a graphical representation of the objects or some form >> of textual input. The views shall change the model by using command >> objects (for undo, e.g. QUndoCommand). > > [...] > >> My problem is, how do the commands interact with the model? > > One approach that combines the undo framework with the model/view framework > is described here: > > http://doc.trolltech.com/qq/qq25-undo.html > > The implementation is in C++, but it may be possible to pick up some > useful tips from the article. Thanks for the pointer. I studied the article before, but it doesn't seem to work for my problem: If I understand the Qt model/view architecture correctly, data is always based on items which are wrapped into QVariant. (see http://doc.trolltech.com/4.4/qabstractitemmodel.html#data) So to use the Qt model/view architecture items have to be represented as a value. I think this leaves me with the problem of copying objects I described before. Regards Georg From rajeeshrnair at gmail.com Mon Sep 29 00:28:43 2008 From: rajeeshrnair at gmail.com (raj) Date: Sun, 28 Sep 2008 21:28:43 -0700 (PDT) Subject: Reportlab - Splitting table by column Message-ID: <7823f7a1-cc96-4d3a-bdb2-315da9212397@z11g2000prl.googlegroups.com> My Zope based application for a client has to generate annual audit reports with too wide tables of account-wise payment details. I turned to reportlab when HTML formatting became a headache for me. Reportlab doc claims it can split by row as well as column but doesn't explain how to. Then I came to learn that reportlab does not implement byCol splitting. But is there a way out for me to split my wide data table into pages? What if I try to implement splitByCol in the line of splitByRow? (Only if it won't take much time and effort!) Why don't they do that themselves? Any serious obstacles? From dudeja.rajat at gmail.com Sun Sep 28 11:51:40 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sun, 28 Sep 2008 16:51:40 +0100 Subject: Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars Message-ID: Hi, Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well the problem is I'm unable to scroll if I click on the arrows buttons of scrollbars ( with both types of scrollbars) Please suggest if I m missing some configuration. My code is as below: self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL) self.hsb.grid(row = 2,column = 0, sticky = E+W) #vertical scroll bar self.vsb = Scrollbar(appGuiFrame) self.vsb.grid(row = 1,column = 2, sticky = N+S) self.txtLogger = Text(appGuiFrame, \ height = 20,\ width = 100, \ state = DISABLED, \ xscrollcommand = self.hsb.set, \ yscrollcommand = self.vsb.set, \ wrap = NONE, \ font = ("courier",12)) self.hsb.config(command = self.txtLogger.xview()) self.vsb.config(command = self.txtLogger.yview()) Please help. Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 30 09:04:26 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 30 Sep 2008 15:04:26 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <00f15d41$0$20617$c3e8da3@news.astraweb.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48e11dd4$0$20720$426a74cc@news.free.fr> <00f15d41$0$20617$c3e8da3@news.astraweb.com> Message-ID: <48e223bc$0$13938$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Mon, 29 Sep 2008 18:27:22 +0200, Bruno Desthuilliers wrote: > >> Lawrence D'Oliveiro a ?crit : >>> In message , Ross Ridge wrote: >>> >>>> You need either use trial and error to find out, or look at the >>>> source. >>> So what's wrong with using the source as documentation? :) >> Don't know... Ok, having higher-level documentation (the big picture, >> and quick description of what and how for classes and functions) really >> helps. But when it comes to nitty-gritty details, source code is the >> best documentation ever, since it's always accurate and up to date. >> >> FWIW, I'm often surprised by people asking questions about some >> implementation detail of some open-source library or framework that are >> very easily answered just looking at the source code. Reading the source >> is 1/ the best way to really know how something is implemented and 2/ >> usually very instructive. > > Reading the source code is good, but it's not a panacea. Not what I implied. > There are at > least four things wrong with the advice to read the source code: My "advice to read the source code" was not meant as a *replacement* for documentation, but as a *complement* to it. What I meant is that you just can't document each and every detail of implementation. > > (1) It's not always available. > > (2) Even when the source is available, it is sometimes a legal trap to > read it with respect to patents and copyright. E.g. some Microsoft so- > called "open" licences (but not all) allow you to read the source, but if > you do then everything you program in a related field from that point is > legally contaminated and could be considered a derivative work of > Microsoft's software. I obviously implied that source was freely available and you had the right to read it. Else it just makes no sense. > (3) Source code not always understandable without significant effort. That's why reading the source can have a great educational value, isn't it ?-) > Code can be obfuscated, either to hide the algorithm, same problem as closed-source software - not concerned by this advice. > as an optimization, > or simply because the coder is cleverer than you are. It might be in a > language you don't understand (e.g. Python built-ins are written in C, > not Python. I have to learn C to find out what exceptions sorted() can > raise?). Every developer should have at least basic knowledge of C. MHO of course. > That's why accurate documentation should be preferred in the first place. Indeed. Did I say otherwise ? Now not all code has accurate documentation, and then you're happy to be able to access and possibly understand the source code. I'm not talking about an ideal world here. (snip) > Yes, documentation can fall behind the source code, but once the code is > stable and the documentation has caught up and is accurate, there's no > reason to re-invent the wheel by slugging through the source just to find > out something already documented. Once again, that's not what I said. > (4) Even when the source code is available, legally unencumbered, in a > language you understand and not too complicated for you to grasp, there's > the combinatorial explosion: you may need to read and understand an > arbitrarily large and complex chain of software merely to know what a > single function can do. Yes, this happens when hi-level documentation is lacking. At least you have a chance to gain some insight !-) > E.g. you want to know what exceptions function > spam() can raise: > > def spam(x): > a = 1 > b = 2 > c = ham(x) > return fried_eggs(a, b, c) > > Now you need to understand ham() and fried_eggs(), but they aren't > documented either. So you turn to their source code, and each of them > call two functions, each of which call another two functions, each of > which call *another* two functions... And still you're a lucky guy if there's no callback, conditional import and / or polymorphic dispatch involved. Steve, I may not have been clear, but I didn't meant that code shouldn't be documented. I was : 1/ answering to the question "So what's wrong with using the source as documentation?", my own personal answer being that it's something I often do, whether because I want to find out some detail not covered by the available documentation, whatever this available documention is worth 2/ digressing about the fact that, to my suprise, few developpers seem to *first* have a look at the source code when either documentation is lacking or they'd like to know more about some implementation detail. But FWIW, it seems that few developpers even bother reading the documentation at all :( From tsrinuvasulu491 at gmail.com Sun Sep 28 21:16:31 2008 From: tsrinuvasulu491 at gmail.com (chinu) Date: Sun, 28 Sep 2008 18:16:31 -0700 (PDT) Subject: EARN $$$ IN EVERY MONTH. Message-ID: <03865e77-4fa9-4e14-a4b6-1b3573e4eb40@a2g2000prm.googlegroups.com> hai, i am srinu from india. i am sending a blog url for yours use. click on the blog and get more information to choose yours job. the blog url is: http://earnmonthlyincome.blogspot.com/ goodluck From duncan.booth at invalid.invalid Thu Sep 25 08:22:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Sep 2008 12:22:08 GMT Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> Message-ID: sturlamolden wrote: > On 25 Sep, 10:08, Duncan Booth wrote: > >> A lot of what LINQ does is already easy to do in Python, and most of >> the rest can probably be added fairly easily, but it does provide a >> consistent framework which may make it easier to do complex LINQ >> statements than complex list comprehensions. > > Yes, that's the word, "consistent framework". I wonder what that > means? Do you mean Python syntax is inconsitent? No Python's syntax is fine. The api's aren't as consistent though: Microsoft added a common set of extension methods which work on databases, xml, builtin sequences and can be easily extended to include other custom sequences. As an example to filter a list in Python you'd use a list comprehension with an 'if', but for a database you'd probably prefer a select with a 'where' clause so as to avoid retrieving and discarding 999999 or your 1 million rows. The apis defined by LINQ allow that sort of optimisation to happen transparently, the simple list would just test each element but the database would run an appropriate query. So what the 'can we have LINQ in Python' people are asking is to be able to write things like: x = (c for c in customers if c.id=='123') and know that they aren't doing a linear search unless that is the best that can be done. The LINQ equivalent would be something like: var x = from c in customers where c.id=='123' select new { c.name, c.id }; which is compiled to: var x = customers.Where(c => c.id=='123'); and depending on the type of 'customers' the Where method can either get a callable function to test the condition or an expression tree which it can compile into another language such as SQL (C# lambdas can compile either to executable code or to Expression<> objects that you can further process). There's an article at http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees which has a real example showing how: DataContext db = new DataContext("server=.;initial catalog=northwind"); Table orders = db.GetTable(); Table customers = db.GetTable(); var q = from o in orders, c in customers where o.ShipCity == "London" && (o.CustomerID == c.CustomerID) select new { o.OrderDate, c.CompanyName, c.ContactTitle, c.ContactName }; actually ends up as a single SQL query: exec sp_executesql N'SELECT [t1].[CompanyName], [t1].[ContactName], [t1].[ContactTitle], [t0].[OrderDate] FROM [Orders] AS [t0], [Customers] AS [t1] WHERE ([t0].[ShipCity] = @p0) AND ([t0].[CustomerID] = [t1]. [CustomerID])', N'@p0 nvarchar(6)', @p0 = N'London' >> BTW, a minor correction: LINQ statements are closer to generators, >> not list comprehensions. They don't actually evaluate their results >> until you iterate over them and you can re-used the same LINQ >> statement multiple times getting different results if the data has >> changed. > > Python has generator expressions with the same syntax as list > comprehensions, except you use () instead of []. > It might surprise you to know that I have actually come across generator expressions. :^) My wording was deliberate: LINQ queries are re-usable, so are Python's generators, but generator expressions are not. The comparison isn't exact, you have to call the generator to get an iterator whereas a LINQ expression gives you something which is directly iterable. -- Duncan Booth http://kupuguy.blogspot.com From alfons.nonell at upf.edu Mon Sep 29 12:45:34 2008 From: alfons.nonell at upf.edu (Alfons Nonell-Canals) Date: Mon, 29 Sep 2008 18:45:34 +0200 Subject: Generate documentation for a Python developed software Message-ID: <1222706734.15761.403.camel@king.imim.es> Dear all, I have a complex program developed using Python. It contains lot of files and classes. Now I have the lazy task to documentate it. I have some notes about is class but I would like to know if there is something to auto-generate the doucmentation with the program code. I know I will have to explain each class and variable but, if an external software canprepare it, the template, it will be great! Thanks in advance! Regards, -- ------------ Alfons Nonell-Canals Chemogenomics Lab Research Group on Biomedical Informatics (GRIB) - IMIM/UPF Parc de Recerca Biom?dica de Barcelona (PRBB) C/ Doctor Aiguader, 88 - 08003 Barcelona alfons.nonell at upf.edu - http://cgl.imim.es http://alfons.elmeuportal.cat http://www.selenocisteina.info From ppearson at nowhere.invalid Tue Sep 30 11:31:59 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 30 Sep 2008 15:31:59 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: <6kev3fF7l2r7U1@mid.individual.net> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: > > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? Since you're coming from the FORTRAN world (thank you for that stroll down Memory Lane), you might be doing scientific computations, and so might be interested in the SciPy package (Google scipy), which gives you arrays and matrices. Don't expect to be able to use it without learning some Python, though. -- To email me, substitute nowhere->spamcop, invalid->net. From tjreedy at udel.edu Tue Sep 16 13:41:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 13:41:11 -0400 Subject: literals optimization (was Re: append on lists) In-Reply-To: <200809161807.04172.maric@aristote.info> References: <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> <200809161807.04172.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Tuesday 16 September 2008 16:57:26 Grant Edwards, vous avez ?crit : >> Where is that in the specification? > Each literal creates a new instance, This does not answer 'where' but just adds another false claim. I just reread the Reference Manual, Lexical Analysis chapter, Literals section and there is nothing like that that I saw. And the reference implementation is obviously different. From stargaming at gmail.com Tue Sep 23 08:58:57 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 23 Sep 2008 12:58:57 GMT Subject: Comparing float and decimal References: Message-ID: <48d8e810$0$4541$9b622d9e@news.freenet.de> On Tue, 23 Sep 2008 07:20:12 -0400, D'Arcy J.M. Cain wrote: > I'm not sure I follow this logic. Can someone explain why float and > integer can be compared with each other and decimal can be compared to > integer but decimal can't be compared to float? In comparisons, `Decimal` tries to convert the other type to a `Decimal`. If this fails -- and it does for floats -- the equality comparison renders to False. For ordering comparisons, eg. ``D("10") < 10.0``, it fails more verbosely:: TypeError: unorderable types: Decimal() < float() The `decimal tutorial`_ states: "To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error)." See the `decimal FAQ`_ for a way to convert floats to Decimals. >>>> from decimal import Decimal >>>> i = 10 >>>> f = 10.0 >>>> d = Decimal("10.00") >>>> i == f > True >>>> i == d > True >>>> f == d > False > > This seems to break the rule that if A is equal to B and B is equal to C > then A is equal to C. I don't see why transitivity should apply to Python objects in general. HTH, .. _decimal tutorial: http://docs.python.org/lib/decimal-tutorial.html .. _decimal FAQ: http://docs.python.org/lib/decimal-faq.html -- Robert "Stargaming" Lehmann From wjvriend at zonnet.nl Tue Sep 30 14:59:27 2008 From: wjvriend at zonnet.nl (Willem-Jan Vriend) Date: Tue, 30 Sep 2008 20:59:27 +0200 Subject: pylab without X11 Message-ID: <48E2770F.1070300@zonnet.nl> I want to use pylab (matplotlib) on a machine without X11. I'm trying to generate onthefly graphics for an apache2 web service, so they do not have to be displayed on this machine ! When i do pylab.figure() I get the error TclError: couldn't connect to display ":0.0" I tried setting the DISPLAY environment variable to "", ":0.0" but I got the same error message. Any help is very much appreciated. From timr at probo.com Tue Sep 9 02:08:36 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 09 Sep 2008 06:08:36 GMT Subject: found a bug with smtpd, where can i report this? References: Message-ID: "Marcus.CM" wrote: > >Where should i report the bug? >smtpd bug. Why don't you tell us about it? There may be another explanation. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mail at anjanesh.net Wed Sep 10 12:33:46 2008 From: mail at anjanesh.net (Anjanesh Lekshminarayanan) Date: Wed, 10 Sep 2008 22:03:46 +0530 Subject: PHP's str_replace ? In-Reply-To: <6iq2sbFs113rU2@mid.uni-berlin.de> References: <6iq2jpFs113rU1@mid.uni-berlin.de> <6iq2sbFs113rU2@mid.uni-berlin.de> Message-ID: <48C7F6EA.7010202@anjanesh.net> Matthias Huening wrote: > Matthias Huening (10.09.2008 16:07): >> Anjanesh Lekshminarayanan (10.09.2008 15:50): >>> In PHP, if I do >>> str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) >>> it'll replace all vowels with a hyphen in string $str. >>> >>> Is there some equivalent in Python ? >> >> What about something like this: >> >> import re >> new_str = re.sub('([aeiou])-', r'\1', str) >> > > Sorry - I misinterpreted your question. > Try this instead: > > import re > new_str = re.sub('[aeiou]', '-', str) Wow - this is neat. Thanks From aahz at pythoncraft.com Sun Sep 7 10:18:03 2008 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2008 07:18:03 -0700 Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: In article , Fredrik Lundh wrote: >Martin DeMello wrote: >> >> In the interests of not hammering the db unnecessarily, I'm >> considering the following >> 1. A series of independent "monitor" threads that collect information >> over TCP from the cluster of machines, and write it to a queue >> 2. A "logger" thread that empties the queue every second or so and >> inserts the collected information to the db via a single insert >> statement > >why are you using a queue for this case, btw? why not just use a plain list > > L = [] > lock = threading.Lock() > >and add stuff using append in the monitor threads > > with lock: > L.append(item) Because using a queue requires less thinking. I certainly would use a queue in this case instead of rolling my own. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From adityashukla1983 at gmail.com Fri Sep 26 16:23:11 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Fri, 26 Sep 2008 15:23:11 -0500 Subject: Classes and functions. Message-ID: <73045cca0809261323r4a74d09fkdad22396b0a88324@mail.gmail.com> Hello folks , i am using the newick module http://www.daimi.au.dk/~mailund/newick.html.I am just learning to use it and i have a question about it. from newick.tree import parse_tree from newick.tree import add_parent_links from newick.tree import add_distance_from_root import sys t = parse_tree('((A:2,B:3):1,C:6);') print t deltas = add_distance_from_root(t) now when i do this i can get the output like this (('A' : 2.0, 'B' : 3.0) : 1.0, 'C' : 6.0) None This is the code of the add_distance_from_root(0 def add_distance_from_root(tree): '''Extend all nodes with the distance (branch length) from the root''' tree.distance_from_root = 0.0 # 'tree' is the root... class V(TreeVisitor): def pre_visit_edge(self,src,b,l,dst): if l is None: l = 0 dst.distance_from_root = src.distance_from_root - l tree.dfs_traverse(V()) >From here it is clear that the function does not return anything but i wanna get the value of the distance from root.How can i get this? Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From rNOSPAMon at flownet.com Fri Sep 19 02:29:06 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 Sep 2008 23:29:06 -0700 Subject: CTypes on a 64 bit machine truncates pointers to 32 bits? References: <48d34449$0$2363$9b622d9e@news.freenet.de> Message-ID: In article <48d34449$0$2363$9b622d9e at news.freenet.de>, "Martin v. L?wis" wrote: > >>>> foolib = cdll.LoadLibrary('foo.so') > >>>> foolib.foo(0xF00000000) > > 0 > > Shouldn't you tell ctypes that the argument and the result > of foo is a pointer? Yeah... that's it. Default return type is int, which I assumed would be 64 bits on a 64 bit machine, but turns out it's 32. Stupid. rg From emile at fenx.com Fri Sep 5 12:35:03 2008 From: emile at fenx.com (Emile van Sebille) Date: Fri, 05 Sep 2008 09:35:03 -0700 Subject: Retrieving the name of the class calling an instance method In-Reply-To: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> References: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> Message-ID: mercado mercado wrote: > In Python, is it possible for an instance method to know the name of the > class which is calling it? Well, the class name is in __class__ so changing 'print x' to 'print __class__' will show foo in both cases, which is in fact the name of the class which is calling it. Of course, what you want is the name of the thing chained in front of that. There are and are not ways of getting to that. Dig into the traceback module. But I'd pass a parameter to foo's __init__ such as foo('bar') and foo('again') and it'd always work. HTH, Emile > For example, in the sample below, I would > like for the someMethod method to print the name of the class calling it > ("bar" in the first case, "again" in the second). > > --------------------------------------- > class foo(): > def someMethod(self): > print x > > class bar(): > def __init__(self): > f = foo() > f.someMethod() > > class again(): > def __init__(self): > f = foo() > f.someMethod() > > bar() > again() > --------------------------------------- > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From giltay at gmail.com Fri Sep 19 11:47:03 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Fri, 19 Sep 2008 08:47:03 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> Message-ID: On Sep 18, 7:42?pm, Steven D'Aprano wrote: > I'm not being snarky about losing priority here, but I submitted > essentially the same solution two hours earlier than pruebono. My apologies (seriosuly). In this case, I think it might just be haste. For what it's worth, I saw your post (on Google Groups), but I skipped over it. You wrote two solutions, one slow and one fast (the latter being the same as pruebono's). You put the slow one at the top, I saw for ... for ... and went straight to the next message without reading the better solution. I knew that there was only one for loop necessary, so I didn't bother reading on. Actually, I missed pruebono's post, too, until after I figured it out myself (but before I posted). That several people came up with the nigh exact same solution, modulo variable names only, says something about the Zen of Python. Geoff G-T From workitharder at gmail.com Wed Sep 3 16:55:52 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 3 Sep 2008 13:55:52 -0700 (PDT) Subject: Late initialization using __getattribute__ Message-ID: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> I want to make a MixIn class that waits to initialize its super- classes until an attribute of the object is accessed. Not generally useful, but desirable in my case. I've written this, and it works, but would like to take any suggestions you guys have. I've commented out the "delattr" call because it throws an AttributeError (although I don't know why). class LateInitMixIn(object): def __init__(self): print "LateInit initialization" self.inited = False def __getattribute__(self, attr): print "Doing __getattribute__" getattr = lambda attr:object.__getattribute__(self, attr) if not getattr("inited"): super(LateInitMixIn, self).__init__() setattr(self, "inited", True) #delattr(self, "__getattribute__") return getattr(attr) class Base(object): def __init__(self): print "Base initialization" self.base = True class LateInit(LateInitMixIn, Base): pass def main(): S = LateInit() print S print print "Should do Base init after now" print S.base print S.base if __name__=="__main__": main() This gives the following output: LateInit initialization <__main__.LateInit object at 0x2a960c1c50> Should do Base init after now Doing __getattribute__ Base initialization True Doing __getattribute__ True From hniksic at xemacs.org Wed Sep 24 05:18:26 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 24 Sep 2008 11:18:26 +0200 Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <87myi0z4tq.fsf@mulj.homelinux.net> Message-ID: <87ljxh3nrx.fsf@mulj.homelinux.net> josh logan writes: > It looks like __cmp__ is still in the documentation, and it seems to > work somewhat in Python 3.0rc1. Here is the link to the documnetation > http://docs.python.org/dev/3.0/reference/datamodel.html#object.__cmp__ Thanks, I've now filed a bug report for that. It looks like an oversight. From darcy at druid.net Tue Sep 23 07:20:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 23 Sep 2008 07:20:12 -0400 Subject: Comparing float and decimal Message-ID: <20080923072012.57d8d329.darcy@druid.net> I'm not sure I follow this logic. Can someone explain why float and integer can be compared with each other and decimal can be compared to integer but decimal can't be compared to float? >>> from decimal import Decimal >>> i = 10 >>> f = 10.0 >>> d = Decimal("10.00") >>> i == f True >>> i == d True >>> f == d False This seems to break the rule that if A is equal to B and B is equal to C then A is equal to C. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From andy_westken at hotmail.com Thu Sep 11 10:21:43 2008 From: andy_westken at hotmail.com (andy_westken at hotmail.com) Date: Thu, 11 Sep 2008 07:21:43 -0700 (PDT) Subject: Enumerating ordered expat attributes with tuplets? Message-ID: Hi I'm new to Python and trying to pick up good, idiomatic usage right from the offset. As I was familiar with Expat from C++ (directly and via expatpp) I'm trying to write a little script - using xml.parsers.expat - to search and replace XML attribute values. As I want the attributes to stay in order when the file is written out (so I can check my results with a diff tool) I've set the parser's ordered_attributes attribute. But this has stopped the for loop working with the tuplets. The relevant bit of code in my little test, using the default Dictionary for the attributes, is: def start_element(name, attrs): print "%s : " % name, for (a,b) in attrs.items(): print " %s=\"%s\"" % (a,b), But when I set ordered_attributes, first it doesn't like the items() AttributeError: 'list' object has no attribute 'items' And then it doesn't like the tuple ValueError: too many values to unpack Do I have keep track of where I am (name, value, name, value, ...) Or is there a way I can solve the problem with a tuple? Thanks, Andy From stef.mientki at gmail.com Tue Sep 30 16:59:52 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 22:59:52 +0200 Subject: Would this be called a bug in inspect ? In-Reply-To: References: <48E268A3.4050900@gmail.com> <48E28534.1040009@gmail.com> Message-ID: <48E29348.1000801@gmail.com> Terry Reedy wrote: > Stef Mientki wrote: > >> print getmembers ( wx ) >> crashes >> >> but not always: >> >>> print getmembers (wx) >> [('ACCEL_ALT', 1), ('ACCEL_CMD', 2), ('ACCEL_CTRL', 2), >> ('ACCEL_NORMAL', 0), ('ACCEL_SHIFT', 4), ('ADJUST_MINSIZE', 0), ( > > I suspect that wx has an erratic bug, which their tests do not catch. > So I would send this off to them. I did, and the bug is already fixed, but I need some more time to update, while most of my programs crash with the newer version. But the real point is, should a module like inspect not be insensitive to these kind of errors ? cheers, Stef > >> >>> print getmembers (wx) >> Traceback (most recent call last): >> File "", line 1, in >> File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", >> line 242, in __repr__ >> def __repr__(self): return 'wx.Colour' + >> str(self.Get(True)) >> File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", >> line 230, in Get >> return _gdi_.Colour_Get(*args, **kwargs) >> TypeError: in method 'Colour_Get', expected argument 1 of type >> 'wxColour *' > > -- > http://mail.python.org/mailman/listinfo/python-list From hrishys at yahoo.co.uk Tue Sep 23 10:48:37 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Tue, 23 Sep 2008 14:48:37 +0000 (GMT) Subject: Linq to Python In-Reply-To: <18648.63979.426433.48679@montanaro-dyndns-org.local> Message-ID: <305501.28149.qm@web27402.mail.ukl.yahoo.com> Hi Will LINQ be ported to Python ? regards Hrishy From ldo at geek-central.gen.new_zealand Mon Sep 29 02:49:44 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 19:49:44 +1300 Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> Message-ID: In message <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0 at m45g2000hsb.googlegroups.com>, Aaron "Castironpi" Brady wrote: > [Wikipedia] says: > "dynamic scoping can be dangerous and almost no modern languages use > it", but it sounded like that was what closures use. Closures will use whatever the language says they use. LISP used dynamic binding, but this caused some interesting problems as mentioned above. Perl allows both, depending on whether the local is declared with "local" or "my". Python uses only lexical, though there's probably some way to get dynamic behaviour if you want. :) From missive at hotmail.com Wed Sep 17 17:56:29 2008 From: missive at hotmail.com (Lee Harr) Date: Thu, 18 Sep 2008 02:26:29 +0430 Subject: decorator and API Message-ID: I have a class with certain methods from which I want to select one at random, with weighting. The way I have done it is this .... import random def weight(value): def set_weight(method): method.weight = value return method return set_weight class A(object): def actions(self): 'return a list of possible actions' return [getattr(self, method) for method in dir(self) if method.startswith('action_')] def action(self): 'Select a possible action using weighted choice' actions = self.actions() weights = [method.weight for method in actions] total = sum(weights) choice = random.randrange(total) while choice> weights[0]: choice -= weights[0] weights.pop(0) actions.pop(0) return actions[0] @weight(10) def action_1(self): print "A.action_1" @weight(20) def action_2(self): print "A.action_2" a = A() a.action()() The problem I have now is that if I subclass A and want to change the weighting of one of the methods, I am not sure how to do that. One idea I had was to override the method using the new weight in the decorator, and then call the original method: class B(A): @weight(50) def action_1(self): A.action_1(self) That works, but it feels messy. Another idea was to store the weightings as a dictionary on each instance, but I could not see how to update that from a decorator. I like the idea of having the weights in a dictionary, so I am looking for a better API, or a way to re-weight the methods using a decorator. Any suggestions appreciated. _________________________________________________________________ Explore the seven wonders of the world http://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE From jcd at sdf.lonestar.org Fri Sep 5 10:00:39 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 05 Sep 2008 10:00:39 -0400 Subject: Case-insensitive string compare? In-Reply-To: <200809051536.45285.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> <1220618002.21923.12.camel@jcd-desktop> <200809051536.45285.maric@aristote.info> Message-ID: <1220623239.5787.10.camel@aalcdl07.lib.unc.edu> Please keep the discussion on-list. On Fri, 2008-09-05 at 15:36 +0200, Maric Michaud wrote: > Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez ?crit : > > On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: > > > Thanks everyone for your help. I'm not opposed to using [key.lower() > > > for key in stage_map] at all, I was just curious to see if there were > > > any cleaner alternatives. It looks like that is what I'll be using. > > > I'm not familiar with how python works internally, but coming from C++ > > > it seems like "remaking" the map would be slow. However, speed is not > > > my main concern in my particular situation, I'm just curious to learn > > > more about python. > > > > You should be opposed to that particular solution. You have just taken > > a dictionary lookup (very fast) and turned it into a list traversal > > (slow). Even if speed isn't your main concern, this is an unnecessary > > de-optimization. You are deliberately slowing down your program to > > avoid a slightly more verbose lookup later. Your data structure might > > as well be a list of tuples to begin with, to avoid creating a new list. > > You have effectively made your keys useless as keys. > > > > If your lookups need to be case insensitive, make the key lower case, > > and store the cased version in the value, whether as a tuple or a dict > > (depending on whether you want named access). > > > > d = { > > 'foo': {'key': 'Foo', 'value': 'val1'} > > 'spam': {'key': 'sPAm', 'value': 'val2'} > > } > > > > search = 'FOO'.lower() > > if search in d: > > result = d[search] > > key = result['key'] > > value = result['value'] > > > > The only reason I wouldn't use this solution is if you expect to have > > keys that will be identical when made lowercase, but if you're doing > > case-insensitive lookup, you obviously don't expect this to be an issue. > > > > The OP has already said the keys are case-sensitive, so this is not an option, > the only way to do it fast is to index upon insertion all keys in another > dict, so you get in final : > d = { "kEy1" : 1, "Key1" : 2} > indexes = { "key1" : ["kEy1", "Key1" ] } > That does not get the same behavior as the OP's original solution. The OP's solution retrieves the first matching value only. Mine gets one arbitrary matching value, determined by the algorithm used for constructing the search dict (not specified in my solution). What the OP actually said was that he can't throw away the case. You assume that this means there would be multiple entries distinguished only by case. That might be true, but given his initial solution, it seemed to me more likely that he wants to keep the case for display purposes, as in a dictionary like this: { "Michaud": "Maric", "Dyer": "Cliff", "D'Amato": "Alphonse", } To the OP: If you are looking for multiple matches for a given case-insensitive key, check out the recent thread on "Python multimap", for further discussion elaborating on how to map one key to many values in a dictionary-like object. At that point, it's probably worth factoring out your solution to a separate class, so you can work with a clean interface, rather than repeating the ugly details every time you use it. Cheers, Cliff > > Cheers, > > Cliff > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From casey.mcginty at gmail.com Wed Sep 3 16:21:49 2008 From: casey.mcginty at gmail.com (Casey) Date: Wed, 3 Sep 2008 13:21:49 -0700 (PDT) Subject: Usual practice: running/testing modules in a package References: <827c7ee5-fad1-4a8c-8724-d6504c91be6d@w1g2000prk.googlegroups.com> <63d32551-7d94-4ab9-9c06-2bd2c8b8e0b8@a3g2000prm.googlegroups.com> Message-ID: On Aug 26, 10:21?pm, Casey wrote: > On Aug 12, 9:57?pm, alito wrote: > > > > > A wrapper on the level up works: > > > ~/python$ cat importercaller.py > > from testpackage import config > > config.hello() > > > ~/python$ python importercaller.py > > hello > > > So, how do I run these modules without writing a wrapper script for > > each one? > It looks like PEP 366 [http://www.python.org/dev/peps/pep-0366/] will solve this issue. From showellshowell at gmail.com Mon Sep 15 23:58:27 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Mon, 15 Sep 2008 20:58:27 -0700 (PDT) Subject: ISO simple debugging sniffer for HTTP Message-ID: <6e11834e-a89d-4cea-b69f-55fa13bb502e@s28g2000prd.googlegroups.com> Hi everybody, I'm looking for a very simple HTTP debugging sniffer in Python-- hopefully 200 lines of less--that allows me to write simple methods to inspect requests and responses. It would ideally work like this: sniffer = SimpleHttpDebuggingSniffer(actual_host_address, actual_host_port) sniffer.listening_port = SOME_PORT_ON_MY_DESKTOP sniffer.inbound_inspector = some_method_i_write sniffer.outbound_inspector = some_other_method_i_write sniffer.run() I would launch it from a Linux desktop terminal and use it help debug a Java application I'm maintaining that uses an opaque library to hit an opaque service. I can configure the client app to connect to the sniffer, and apart from inspecting packets, I just want it to pass data along to the real server. I'm not using any complicated part of the HTTP protocol--it's mostly simple request, simple response, but the payloads are not plain text, so I need some Python code to make sense of them. I've googled a bit, and I've come up with a lot of noise, so I'm hoping some one can point me in the direction of some simple code that they have confidence in, which is free and all that good stuff. Thanks, Steve From john.ford at colorado.edu Thu Sep 25 10:45:31 2008 From: john.ford at colorado.edu (john.ford at colorado.edu) Date: Thu, 25 Sep 2008 07:45:31 -0700 (PDT) Subject: How to parse a string completely into a list References: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> Message-ID: On Sep 25, 1:51?am, Tino Wildenhain wrote: > john.f... at colorado.edu wrote: > > On Sep 24, 10:12 pm, Matt Nordhoff wrote: > >> john.f... at colorado.edu wrote: > >>> On Sep 24, 9:44 pm, "Chris Rebert" wrote: > .... > >>>> Could you please define exactly what you mean by "elements" of a string? > >>>> If you mean characters, then just use list():>>> list(" ?\n \t abc") > >>>> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] > >>>> Regards, > >>>> Chris > >>> Worked like a charm. > >>> kudos! > >> Why do you need to convert it to a list? Strings are sequences, so you > >> can do things like slice them or iterate through them by character: > > >>>>> for character in "foo": > >> ... ? ? print character > >> ... > >> f > >> o > >> o > > >> -- > > > The string draws a map that I then want to be able to traverse > > through. If I can count through the individual characters of a list I > > can create an x-y coordinate plane for navigation. > > You can 'count' (whatever that means) equally in strings as you do in > lists. As said above, they behave exactly the same. Just strings > are imutable - e.g. you can't change individual parts of them. > > Tino > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ?smime.p7s > 4KViewDownload Ahh, but I forgot to mention that I have to mark the path I took in the string. So using list() and then join() are my best options. From deets at nospam.web.de Mon Sep 22 03:24:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 Sep 2008 09:24:15 +0200 Subject: External code and functions integration In-Reply-To: References: Message-ID: <6jovgvF4ccsmU1@mid.uni-berlin.de> Cro schrieb: > Good day. > > I am using python for quite some time now and i decided to advance a > little. I want to write a little extension, or add some C modules for > my python. I use Active version. > > What i want to do is write some wrappers for a game library, called > HGE. See "hge.relishgames.com". > I wrote some applications with HGE, in C++ and i like it pretty much. > In order to make a HGE application in C++, i need to include "hge.h", > include "hge.lib" and "hgelehper.lib", and have "hge.dll" in the same > directory. So it's 3 things i must have for the program to work. > This game library is open source, so i have the source for the libs > and the dll. > > Now, what i was thinking was to make some wrapping code like "hge.h" > to call all the functions in the "libs", that (i guess) call the > functions from "hge.dll", that (blah blah) calls DirectX and so on. > I guess that if i write all that "hge.h" includes and wariables in > python, will be okay... even if i still don't have the skill. > > I tried to call "hge.lib" like this: > " > from ctypes import * > cdll.LoadLibrary("D:/HGE18/lib/bc/hge.lib") > " > But i get "WindowsError: [Error 193] %1 is not a valid Win32 > application". > I tried with windll.LoadLibrary ... and i get the same error. > I tried with the other lib versions, there are 3 versions: BorlandC, > GCC, VisualC, callind "cdll" or "windll". All lib versions report the > same error. Because you need to load the DLL. Diez From clp at rebertia.com Mon Sep 8 18:28:38 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Sep 2008 15:28:38 -0700 Subject: class(object) and (type)?? In-Reply-To: References: Message-ID: <47c890dc0809081528o66259e27l6c92abb6757652a9@mail.gmail.com> Subclassing 'object' makes the class new-style as opposed to old-style. object is the ultimate superclass of all new-style classes. Old-style classes are deprecated and will be removed in Python 3.0, but they're currently the default for backward-compatibility reasons. See http://docs.python.org/ref/node33.html for more info. - Chris On Mon, Sep 8, 2008 at 2:35 PM, AON LAZIO wrote: > Hi again pythoners, > I notice in the class of a code having (object) and (type) attached to > the name of the class. > I know that in other cases, that means the class inherits methods and > properties from other but > In this case, what does it mean? > For example, > > class PY(object): > def __init__(self): > ... > > class PO(type): > def __init__(self): > ... > What do "object" and "type" mean? > > Thanks in advance > > Aonlazio > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From tjreedy at udel.edu Mon Sep 1 15:31:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 15:31:41 -0400 Subject: Buffer objects In-Reply-To: References: Message-ID: Tom Harris wrote: > Greetings, > > I need a little help with buffer objects. Many Python objects export > the buffer interface, or can be persuaded to create a buffer object > with a buffer() call. ... > It must be me but I have found the whole buffer thing difficult to > understand from the docs, it appears only useful to C coders, but I > use the buffer interface (GetData()) of wx.Image objects a lot in my > work. The 1.x/2.x buffer interface was not considered terribly successful. Buffer() is gone in 3.0. I believe class memoryview() (which supports viewing the 'buffer' as an n-dimensional array) is considered to be its replacement. You might find the latter in 2.6 also. Images, in particular, will be viewed as row x column x color, or color x row x column, or whatever, as defined by the attributes of the memory view object in a standardized format. From lists at cheimes.de Wed Sep 10 13:20:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 19:20:31 +0200 Subject: PHP's str_replace ? In-Reply-To: <48C7F6EA.7010202@anjanesh.net> References: <6iq2jpFs113rU1@mid.uni-berlin.de> <6iq2sbFs113rU2@mid.uni-berlin.de> <48C7F6EA.7010202@anjanesh.net> Message-ID: Anjanesh Lekshminarayanan wrote: >> import re >> new_str = re.sub('[aeiou]', '-', str) > Wow - this is neat. Thanks But probably slower and definitely harder to understand. For simple problems the str methods are usually faster than a regular expression. Christian From tom.willis at gmail.com Wed Sep 24 11:47:55 2008 From: tom.willis at gmail.com (Thomas G. Willis) Date: Wed, 24 Sep 2008 11:47:55 -0400 Subject: Linq to Python In-Reply-To: <319386.9452.qm@web27402.mail.ukl.yahoo.com> References: <319386.9452.qm@web27402.mail.ukl.yahoo.com> Message-ID: On Wed, Sep 24, 2008 at 11:25 AM, hrishy wrote: > Hi Tom > > This is what i like and feel of the Python programmers smarter then every > other langauge i know of. > > But i am not comfortable with your second statement XML i never need it > one day everybody would need it. > > > regards > Hrishy > > Well you may be right which is why I said "hopefully" one thing I do know is that in my work in both .net and java, XML plays a more significant role. Everyone can probably speculate differently as to why this is. My personal feeling is that it is because XML is less of a hassle than building/passing around class hierarchies for application state in various scenarios.But in python, it is far easier for me to pass around a dict or some similar structure to get roughly the same effect. So in my mind, XML solves a problem that is present in both .net and java, but not necessarily python. In the same way, linq to xml solves the problem of handling xml in a more convenient way. In order for it to be useful in python, the problem that xml solves would have to be present IMO. That's not to say it's not possible. Someone who needs something like LINQ to XML but in python could write something probably similar to what sqlalchemy does and it would require no changes to the python language or runtime. If it was written then maybe people would invent ways to use XML in python that are better than what other things do. Hooray for the free market of ideas. :) This is all my opinion , I have no idea what the conventional wisdom of the python community is on XML, but in my experience in other languages, it seems to be the answer to a question that no one asked, or the wrong answer, more often than it is the appropriate answer. Maybe it's only that way on OHIO. :) -- Thomas G. Willis -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Thu Sep 25 18:01:15 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 25 Sep 2008 15:01:15 -0700 (PDT) Subject: text processing References: <6k20ckF5glpmU1@mid.uni-berlin.de> Message-ID: <8db0408a-6564-4c97-ac14-fb0d92a14b3a@b1g2000hsg.googlegroups.com> On Sep 25, 6:34?pm, Marc 'BlackJack' Rintsch wrote: > On Thu, 25 Sep 2008 15:51:28 +0100, jitensha... at gmail.com wrote: > > I have string like follow > > 12560/ABC,12567/BC,123,567,890/JK > > > I want above string to group like as follow (12560,ABC) > > (12567,BC) > > (123,567,890,JK) > > > i try regular expression i am able to get first two not the third one. > > can regular expression given data in different groups > > Without regular expressions: > > def group(string): > ? ? result = list() > ? ? for item in string.split(','): > ? ? ? ? if '/' in item: > ? ? ? ? ? ? result.extend(item.split('/')) > ? ? ? ? ? ? yield tuple(result) > ? ? ? ? ? ? result = list() > ? ? ? ? else: > ? ? ? ? ? ? result.append(item) > > def main(): > ? ? string = '12560/ABC,12567/BC,123,567,890/JK' > ? ? print list(group(string)) > How about: >>> string = "12560/ABC,12567/BC,123,567,890/JK" >>> r = re.findall(r"(\d+(?:,\d+)*/\w+)", string) >>> r ['12560/ABC', '12567/BC', '123,567,890/JK'] >>> [tuple(x.replace(",", "/").split("/")) for x in r] [('12560', 'ABC'), ('12567', 'BC'), ('123', '567', '890', 'JK')] From xlebourd at gmail.com Mon Sep 15 05:28:28 2008 From: xlebourd at gmail.com (Xavier) Date: Mon, 15 Sep 2008 02:28:28 -0700 (PDT) Subject: Serial I/O problem with pywin32 ? References: <6i7p2uFp2lqbU1@mid.uni-berlin.de> Message-ID: <95ccb42d-ab51-4339-bc92-f51646dafa15@y21g2000hsf.googlegroups.com> Hi I have resolved my problem by checking paquets. It seems that it is a problem of the GPS (it's a very cheap GPS Datalogger). > Could be hardware flow control. See this sometimes on the bluetooth > connections that are using Serial Port Protocol and the hardware flow > control hasn't been physically implemented. It seems it is the problem. The policy seems to be : - ask the GPS for the data - touch wood - retry with the missing chunks Even the official driver is doing this. > Do you lose data after exactly the same amount of data has > been received? Not. The lost are randomized but it's chunks, ex : 300 consecutive bytes ok 30 consecutive bytes lost 250 bytes ok 40 bytes lost 800 bytes ok 50 bytes lost ... From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 06:43:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 12:43:45 +0200 Subject: list + dictionary searching In-Reply-To: <6e642a00-9301-440d-902c-63713cf4a793@a2g2000prm.googlegroups.com> References: <6e642a00-9301-440d-902c-63713cf4a793@a2g2000prm.googlegroups.com> Message-ID: <48bbc70e$0$13542$426a74cc@news.free.fr> Manoj a ?crit : > Hello All, > > I am very new to python. Any help will be highly appreciated. Thanks > > I have a list of dictionaries: > > a = [{'username': u'John Wang', 'user_utilization': 1.0, 'month': 9, > 'user_id': 4, 'year': 2008}, {'username': u'John Wang', > 'user_utilization': 1.0, 'month': 10, 'user_id': 4, 'year': 2008}, > {'username': u' ', 'user_utilization': 1.0, 'month': 9, 'user_id': 1, > 'year': 2008}] > > I would like to : > > search dictionaries within this list Care to elaborate ??? > create a new list with dictionaries which gives 1 dictionary for every > user with month_year as a key and utilization for that month as a > value assuming the user_id/month/year combination is unique: from collections import defaultdict users = defaultdict(dict) for record in a: month_year = "%(month)s_%(year)s" % record users[record['user_id']][month_year] = record['user_utilization'] print users.values() HTH From fredrik at pythonware.com Sun Sep 7 10:34:59 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 07 Sep 2008 16:34:59 +0200 Subject: Not fully understanding the role of Queue.task_done() In-Reply-To: References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: Aahz wrote: >> why are you using a queue for this case, btw? why not just use a plain list >> >> L = [] >> lock = threading.Lock() >> >> and add stuff using append in the monitor threads >> >> with lock: >> L.append(item) > > Because using a queue requires less thinking. given that the whole reason for this thread was that Queue API didn't fit the OP:s problem, that's a rather dubious statement. (btw, I've always thought that Python was all about making it easy to express the solution to a given problem in code, not to let you write programs without using your brain. when did that change?) From marco.bizzarri at gmail.com Thu Sep 4 10:12:32 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 16:12:32 +0200 Subject: overwrite set behavior In-Reply-To: <200809041507.35366.maric@aristote.info> References: <200809041507.35366.maric@aristote.info> Message-ID: <3f0d61c40809040712y4ef2edd4rb4c98035c5581886@mail.gmail.com> On Thu, Sep 4, 2008 at 3:07 PM, Maric Michaud wrote: > Le Thursday 04 September 2008 14:31:23 Michele Petrazzo, vous avez ?crit : >> Marco Bizzarri wrote: >> > looking at the source, maybe you could create a subclass of Set >> > redefining the __contains__ method? >> >> Made some tries, but __contains__ are never called >> > > No, __contains__ is only called with "in" operator, not for internal hashing. > Anyway this solution is bad, you'll need to compare the new element with all > the set contain, which would result in a O(n) algorithm for adding elements > to the set in place of the O(1) it use. > Thanks for the clarification, Maric; I take notices to watch source more closely next time (( hopefully, before writing a wrong answer )). Regards Marco > _____________ > > Maric Michaud > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From avhena at gmail.com Wed Sep 17 23:49:01 2008 From: avhena at gmail.com (avehna) Date: Wed, 17 Sep 2008 23:49:01 -0400 Subject: cgi-python temporary output Message-ID: <3166fcd60809172049m5838bcc6t2eb7523ca51a1571@mail.gmail.com> Hello: I would like to generate a temporary output in my cgi-python script where the user could see the actual program status while the program is still running behind the web, and know how long approximately it could take, and then finally display the final cgi-output. I have no idea how something like that could be done ("temporary output"). I will appreciate any suggestion from you. Thank you. M. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Mon Sep 1 19:47:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2008 23:47:03 GMT Subject: Py 2.6 changes References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> Message-ID: <00cc7976$0$20302$c3e8da3@news.astraweb.com> On Mon, 01 Sep 2008 12:15:53 -0700, bearophileHUGS wrote: > Now math has factorial: > http://docs.python.org/dev/library/math.html#math.factorial Seen how > reduce() is removed from Python 3 (I know it's in itertools), and seeing > that for me to write a productory() function was the first usage I have > had for reduce, years ago, I think the math module can gain a > productory() function too. productory() -- I don't know that function, and googling mostly comes up with retail product searches. Do you mean product(), the analog of sum() except that it multiplies instead of adds? Or perhaps you mean some sort of generalization of factorial(). -- Steven From a.schmolck at gmail.com Thu Sep 4 05:47:07 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Thu, 04 Sep 2008 10:47:07 +0100 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: bearophileHUGS at lycos.com writes: > A problem is that '1234' in Python is a string, so using ' in numbers > looks a bit dangerous to me (and my editor will color those numbers as > alternated strings, I think). Yeah, editors, especially those with crummy syntax highlighting (like emacs) might get it wrong. This should be easy enough to fix though. Indeed unlike raw and tripplequoted strings which were adopted without major hitches this new syntax wouldn't have any bearing on what's a valid string. 'as From gminick at bzt.bzt Wed Sep 3 14:54:59 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 3 Sep 2008 18:54:59 +0000 (UTC) Subject: Looking for File comparison utility that produces actual differences References: Message-ID: On Wed, 3 Sep 2008 19:40:40 +0100, dudeja.rajat at gmail.com wrote: > I looking for a file comparison utility in Python that works like > 'diff' command in Unix and 'comp' in Windows. > The present 'cmd' in filecmp module only presents output in the form > of 1 or 0 i.e whether the 2 files differ or not? In python it's called difflib. Try to import it. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From theller at python.net Fri Sep 5 05:08:37 2008 From: theller at python.net (Thomas Heller) Date: Fri, 05 Sep 2008 11:08:37 +0200 Subject: ctypes error on Windows In-Reply-To: References: Message-ID: <6icb8jFq4jmsU1@mid.individual.net> Fredrik Lundh schrieb: > Fredrik Lundh wrote: > >>> I do have the tidy.dll installed (if I didn't, I couldn't even import >>> the tidy module). >> >> typing the following into the Python interpreter might give you some >> more clues: >> >> >>> import _tidy >> >>> _tidy.__file__ >> >>> dir(_tidy) > > or not, since ctypes is involved. > > have you checked for multiple copies of tidy.dll? > > if you have MSVC on your machine, try using "dumpbin /exports" on the > DLL to check that it really exports the symbols the binding expects. > Or use dependencywalker (google for it). Thomas From tino at wildenhain.de Wed Sep 10 09:40:42 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 10 Sep 2008 15:40:42 +0200 Subject: Web shopping carts In-Reply-To: References: Message-ID: <48C7CE5A.7030904@wildenhain.de> Hi, Luke Hamilton wrote: > Thanks... > > Do you happen to have anymore details? Yes well... you guess it was supposed to be a funny comment but would you happen to have anymore details on your requirements as well? Your simple question was just asking for making fun of it. (Other than that please see the answer given by Fredrik) Ah, btw, I'd check the the other posts of long term members if you see something in the appearance different to yours :-) (not related to your question itself) Cheers Tino ... >> Luke Hamilton wrote: >>> Hey People, >>> >>> I am wondering if there are any OS shopping cart application written in >>> python? >>> >> Yes there are. >> >> HTH >> Tino > > -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From walter.php at gmail.com Thu Sep 11 21:35:04 2008 From: walter.php at gmail.com (Walter Cruz) Date: Thu, 11 Sep 2008 22:35:04 -0300 Subject: rss feed generation In-Reply-To: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> References: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> Message-ID: <32cabba0809111835g2984c463y2c4b689605f8362e@mail.gmail.com> On Tue, Sep 9, 2008 at 9:35 PM, alex23 wrote: > On Sep 10, 7:30 am, "Blake Garner" wrote: >> I'm looking for suggestions on how to approach generating rss feed >> .xml files using python. What modules to people recommend I start >> with? pylons webhelpers makes a good work too. []'s - Walter From a at nospam.org Tue Sep 16 09:12:27 2008 From: a at nospam.org (Armin) Date: Tue, 16 Sep 2008 15:12:27 +0200 Subject: append on lists In-Reply-To: References: <1221564169.16690.0@proxy00.news.clara.net> Message-ID: Maric Michaud wrote: > Le Tuesday 16 September 2008 14:23:25 Armin, vous avez ?crit : >> Alex Marandon wrote: >>> Armin wrote: >>>> Duncan Booth wrote: >>>> >>>> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c >>>> (with c = [8,9]) is identical, >>> No it's not, + doesn't alter its operands. >>> >>> >>> a = 1 >>> >>> b = 2 >>> >>> a + b >>> >>> 3 >> That's not the point :) > > It is, please try to understand it, in python all expressions that mutate an > object should return None, it's the case for > > l.append(x) > l.sort() > l.reverse() > > all expressions that return something, return a new object, it's the case for > > 1+2 > 1.__add__(2) (which is the same) > sorted(l) > l[i:j] > etc... > > there are some noticeable exceptions : > > For coding facilities, some APIs could return the modified part of the object, > ex : it = c.pop() > > Returning the modifyied object itself is mostly considered bad style, because > it doesn't make clear if this the object or a copy. OK ... That's a good point. Thanks ! --Armin From apardon at forel.vub.ac.be Mon Sep 22 08:06:50 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 22 Sep 2008 12:06:50 GMT Subject: How to kill threading.Thread instance? References: <6jmn5kF42hreU1@mid.uni-berlin.de> <6jn4itF442e7U1@mid.uni-berlin.de> Message-ID: On 2008-09-21, Fredrik Lundh wrote: > Diez B. Roggisch wrote: > >>> I wonder why something like myThread.exit() or myThread.quit() or >>> threading.kill(myThread) can't be implemented? >>> Is something like that present in Python 3000? >> >> Not that I'm aware of it (which doesn't mean to much though). >> >> However I *am* aware of the bazillions discussions that have been held >> over this here - and the short answer is: it is a generally very bad >> idea to terminate threads hard, as it can cause all kinds of corruption. > > the problem is that you have no idea what the thread is doing, so just > killing it dead it may make one big mess out of the application's > internal state; see e.g. this post > > http://mail.python.org/pipermail/python-list/2006-August/400256.html > > That's wise ;-) Stopping a thread asynchronously is in /general/ a > dangerous thing to do, and for obvious reasons. For example, perhaps > the victim thread is running in a library routine at the time the > asynch exception is raised, and getting forcibly ejected from the > normal control flow leaves a library-internal mutex locked forever. > Or perhaps a catch-all "finally:" clause in the library manages to > release the mutex, but leaves the internals in an inconsistent state. > > which links to a FAQ from Sun on this very topic: > > http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html > > (note that Java releases all mutexes when a thread is killed, but that's > not much better, as the FAQ explains) > > so as usual, the right thing to do is to do things in the right way. Why not let the programmer make the call whether killing the thread dead is the right thing or not. Maybe the programmer has a pretty good idea about what the thread can possibilbly be doing and knows that killing it won't produce a mess. Sure caution people to be very carefull when they are thinking about doing something like this. Just as people are generally adviced to use Queues when doing multithreading. But that is no reason to disallow certain kind of actions. -- Antoon Pardon From dblubaugh at belcan.com Mon Sep 29 16:43:23 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 16:43:23 -0400 Subject: Is Pyperl still active ?? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9148@AWMAIL04.belcan.com> To All, I was wondering if Pyperl is still active?? It appears as though it may very well be no longer active at this time!!! Is this correct?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From ahmad.humyn at gmail.com Fri Sep 5 06:57:37 2008 From: ahmad.humyn at gmail.com (Ahmad Humayun) Date: Fri, 5 Sep 2008 03:57:37 -0700 (PDT) Subject: atomic section in code References: Message-ID: On Sep 5, 1:59?pm, Fredrik Lundh wrote: > Ahmad Humayun wrote: > > I need to create an atomic section in Python code i.e. there is no > > context switch to any other thread during the running of that piece of > > code. Would would do the trick? > > use a lock, and make sure that anyone that needs access to the shared > state you're manipulating in that section uses the same lock. > > ? ? ?lock = threading.Lock() # or RLock() etc [1] > > ? ? ?with lock: > ? ? ? ? ?section > > this only works if everyone honors the lock, of course; there's no way > in Python to lock out non-cooperating external threads. > > > > 1) seehttp://effbot.org/zone/thread-synchronization.htm Thats true, but this will ensure mutual exclusion; not atomicity thanks again, From sslguru at gmail.com Tue Sep 16 04:54:29 2008 From: sslguru at gmail.com (SSLGuru) Date: Tue, 16 Sep 2008 01:54:29 -0700 (PDT) Subject: Secure Your Website with SSL Certificate Message-ID: <6ce4497e-aa17-41eb-9847-55239a7997f0@w1g2000prk.googlegroups.com> Hello Everyone, We are currently running special offer for WHT Forum Members. All VeriSign Certificates are priced at Special rates during our September Sale Offer. Please visit below link for more information: http://www.rapidsslonline.com/sept09offer.html Note: VeriSign Secured Seal is included in all offered VeriSign SSL Products. __________________ 4 Leading SSL Brands to choose from // Best Discounted Prices // 24X7 Live Chat & Email Support. http://www.rapidsslonline.com/ Largest SSL reseller worldwide From castironpi at gmail.com Fri Sep 26 23:21:32 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 20:21:32 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> <87ej36uxl3.fsf@benfinney.id.au> Message-ID: <6fad912d-0ee3-4f60-add4-a28f3fe5b2c6@k7g2000hsd.googlegroups.com> On Sep 26, 9:33?pm, Ben Finney wrote: > George Sakkis writes: > > On Sep 26, 9:30?pm, Grant Edwards wrote: > > > I read the group via NNTP, and I find that blocking all articles > > > posted from google.groups gets rid of all of the spam. > > > ... along with a far from trivial (I guess) percentage of non-spam, > > such as this post. > > As a Google user, you have (presumably) more clout with them than > those of us who are not. Please pressure your provider to reduce the > spam they output so the above drastic measure is not so attractive. > > Such pressure may be more effective if you *also* use an alternate > NNTP provider that isn't such a spam-haven. > > -- > ?\ ? ? ? ? ? ? ?I put contact lenses in my dog's eyes. They had little | > ? `\ ? pictures of cats on them. Then I took one out and he ran around | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?in circles.? ?Steven Wright | > Ben Finney I composed a thread to the end of voicing that sentiment. http://groups.google.com/group/Groups-Suggestions/browse_thread/thread/142ce723675bcad3# Feel free to follow this. For the record, I do find the fervor with which some netizens are denouncing Google somewhat provocative. I find them biased, more ardent than a classification heuristic with the same number of false negatives and false positives. That is, not purely objective in their advocacy. From google at mrabarnett.plus.com Fri Sep 5 10:28:12 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 5 Sep 2008 07:28:12 -0700 (PDT) Subject: Python and Cyrillic characters in regular expression References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> Message-ID: <87037566-9f99-4945-aa7f-afa57770f27d@m44g2000hsc.googlegroups.com> On Sep 5, 12:28?pm, phasma wrote: > string = u"??????" All the characters are letters. > (u'\u041f\u0440\u0438\u0432\u0435\u0442',) > > string = u"Hi.??????" The third character isn't a letter and isn't whitespace. > (u'Hi',) > > On Sep 4, 9:53?pm, Fredrik Lundh wrote: > > > phasma wrote: > > > Hi, I'm trying extract all alphabetic characters from string. > > > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE) > > > buf = re.match(string) > > > > But it's doesn't work. If string starts from Cyrillic character, all > > > works fine. But if string starts from Latin character, match returns > > > only Latin characters. > > > can you provide a few sample strings that show this behaviour? > From siegfried at heintze.com Sat Sep 13 21:03:36 2008 From: siegfried at heintze.com (Siegfried Heintze) Date: Sat, 13 Sep 2008 18:03:36 -0700 Subject: How to emit Cyrillic and Chinese via unicode from console mode? Message-ID: Can someone point me to an example of a little program that emits non-ascii Unicode characters (Russian or Chinese perhaps)? The unicode Russian/Cyrillic alphabet starts at 0x410. Is this possible to do in a console mode program? If not, I guess I would want to use pywin32 to create a window and a message pump and display it there. I anticipate using pywin32 for some other function calls. Thanks! Siegfried From deets at nospam.web.de Thu Sep 25 16:56:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:56:59 +0200 Subject: How to get the filename in the right case ? In-Reply-To: References: <6k1dukF5hk86U1@mid.uni-berlin.de> Message-ID: <6k2c8rF5oenoU2@mid.uni-berlin.de> Stef Mientki schrieb: > OKB (not okblacke) wrote: >> Stef Mientki wrote: >> >>>>>> import Module1 >>>>>> >>>> d:\data_python_25\pylab_works\module1.py(3)() >>>> >>> -> print "hello" >>> (Pdb) >>> >>> >>>> Then we know if PDB is really the culprit. >>>> >>>> >>> So pdb is the problem. >>> >> >> Yep, it does the same thing for me. >> >> >>>> Apart from that, is that really a problem that the filenames are >>>> all lower case? AFAIK Windows is case-insensitive regarding >>>> filenames anyway. So opening the file by just passing the filename >>>> should work seamless. >>> Yes windows is, >>> but Python is not. >>> My program should run on Windows and Linux (and maybe a few >>> others). By converting everything to lowercase, on Linux I can't >>> distinguishes between 2 files with the same name but a different >>> case (btw, giving 2 files the same name, only differing in case, >>> looks like a bad idea to me). >>> >> >> Hmmm, but I don't understand what you're doing here. Are you >> somehow storing the filename that pdb outputs and you need to use it >> later on a potentially different OS? If the case is preserved in pdb >> on linux, then presumably running it on linux will be fine, right? >> It's only a problem if you somehow try to use a filename created by >> windows- >> pdb to open a file (the same file, somehow) on linux. >> >> > 1. I've a multitab editor. > 2. When a breakpoint is reached, > 3. I check if the file specified in pdb output, is already open in one > of the editor tabs, > 4. if not, I open a new tab with the correct file, > 5. I focus the correct editor tab and jump to the line specified by pdb. > 6. After that I should be able to inspect the surrounding of the > breakpoint, so I need the modules name. > > For 3 I need to compare filenames, the editor contains the case > sensitive name, pdb not. > For 6 I also need the case sensitive filename, but probably there's > another way to get the modules name. > > For 3, I can indeed compare the lowercase version of both, > probably I'll do that for the moment. You can do that based on the OS - do it on windows (as it doesn't care. Actualy, OSX doesn't as well), don't do it on posix systems. Diez From castironpi at gmail.com Sat Sep 27 21:29:30 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 18:29:30 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> Message-ID: <9f263cc0-508a-4597-94fc-365f6b691d10@i76g2000hsf.googlegroups.com> On Sep 27, 6:55?pm, "Tim Rowe" wrote: > 2008/9/27 Aaron Castironpi Brady : > > > No way. ?It's *zero* instead of one, if so, because the only thing C# > > has is a bunch of handcuffs and implicit 'self'. ?You have a line > > like: > > You don't follow what I said, and from your tone I get the feeling you > don't *want* to follow what I'm saying, not because I'm criticising > Python (I'm not), but because I'm guilty of the heresy of suggesting > that it's not actually simultaneoulsy optimised for every possible > use. > > My point is that there are zero parameters as far as I am concerned > because I don't actually touch most of the GUI code. ?There could > actually be hundreds of parameters, for all I care. They're not my > concern. Most of the time I like that -- the tools are doing my work > for me. > > -- > Tim Rowe flamewar.avert( ), please. Yes, I agree, I did not follow every word. It's a fundamental disagreement about successful ways to communicate, and, for the philosophers, successful communication, whether I should have nitpicked first thing, or tried to go along with the gist. I tried the latter. In your case, I guessed wrong. Sorry. Before I tried wxFormBuilder, I imagined that C# would be vastly faster to develop than Python, for anything requiring any non-trivial graphical interface. I've done extensive VB, so I can attest to that personally. It is not. The difference in dev times is about the time it takes to write: def onClick( event ): ... controlA.bind( wx.MOUSEDOWN, onClick ) perhaps several times, which, , is not long. You do get the IDE, true, and that code is auto-crafted for you. But 'wx' does give you data in an XML file, instead of a script. And talk about a difference in identifiers:
vs. form.button.pos= 20, 30 form.button.color= gray You can come up with examples that favor either. But the opposite of statistical is anecdotal. Sorry again. The last time I 'checked in' at your post, your claim was "an hour or so" vs. "ages". Hence my responses. You could probably sneak by by claiming a factor of *two*, but if you were exaggerating, please say so at any time. Penultimately, forgive my sarcasm--- I'm a bit feisty right now. I was distinguishing between arguments in particular, and identifiers in general. And lastly, "simultaneoulsy optimised for every possible use" is a bold claim that I didn't make, at least, to come forward, in so many words. I do believe, and it shows, as of today, and you can quote me on this, that it's "pretty generally applicable", though I reserve the right to change my mind on the matter with or without notice. Especially if I learn something. I do not believe that C# is pretty generally applicable. I maintain that I will adjust that estimate if I ever get any facts about C#, since I don't have very many. (In fact, outside of my VB, COM, and MFC experience, you could say I have no clue. Very tongue in cheek.) In fact, do a Google for 'castironpi "every possible"'. You get a "can't ... every possible", and your post, and something else. That's it. Python has a lot of things C# doesn't. Can we agree on that? From lepto.python at gmail.com Sat Sep 6 08:52:21 2008 From: lepto.python at gmail.com (oyster) Date: Sat, 6 Sep 2008 20:52:21 +0800 Subject: embed python in ms-word? Message-ID: <6a4f17690809060552w6e518f1re4565a7e58e076b6@mail.gmail.com> in fact, during my work, I often write documnets in ms-word. But the doc has many numbers in it, which need to be calculated and to be modified frequently. Is there a method to write a ms-word add-in, so that 1.I can type in the calculation steps in some program language, please have a look at http://blender.bokee.com/inc/word_add_in1.jpg 2.then the result (here, it is 8) is shown in the doc when I close this window? please have a look at http://blender.bokee.com/inc/word_add_in2.jpg 3.when I double-click the result 8, I can view/edit the code again 4.the code for calculation is stored in DOC file too, I can change it later mathtype equation is a kind of such thing, but only for displaying nice equation I don't think vba is a good answer, the main reason is: the vba code has an incompact link with its result in the documnet From ironfroggy at gmail.com Sun Sep 21 19:39:08 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sun, 21 Sep 2008 19:39:08 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> I call it an obvious misuse and misunderstanding of why you'd use a class in the first place. Either create an instance and not make these things classmethods or just share the stuff in a module-level set of variables. But the instantiating is the best options. Your class attributes might not be globals, but you're still using global state and you should avoid it where you can. On Sun, Sep 21, 2008 at 6:39 PM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy -------------- next part -------------- An HTML attachment was scrubbed... URL: From lucafbb at gmail.com Mon Sep 1 04:43:25 2008 From: lucafbb at gmail.com (Luca) Date: Mon, 1 Sep 2008 10:43:25 +0200 Subject: Know if a object member is a method Message-ID: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Hi all. I think this is a newbie question... what is the best method to know if a property of an object is a function? I'm thinking something as if type(obj.methodName)==??? Can someone help me? -- -- luca From gherron at islandtraining.com Tue Sep 23 13:58:17 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 23 Sep 2008 10:58:17 -0700 Subject: Matrix programming In-Reply-To: References: Message-ID: <48D92E39.8000901@islandtraining.com> A. Joseph wrote: > > I need an ebook or tutorial that teach matrix programming. > Perhaps you should start here: http://www.catb.org/~esr/faqs/smart-questions.html#intro Gary Herron > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From gagsl-py2 at yahoo.com.ar Sun Sep 7 07:32:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 08:32:30 -0300 Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: En Sat, 06 Sep 2008 17:18:55 -0300, clurker escribi?: > Michele Simionato wrote: > >> On Aug 28, 6:21?am, ssecorp wrote: >>> Is there a way to view all the modules I have available for import >>> from within Python? >>> Like writing in the interpreter: >> >> Try: >> >>>>> help() >> help> modules >> Please wait a moment while I gather a list of all available modules... >> > > This looks like it could be a useful tool, but when I try it > I get the following: > > Please wait a moment while I gather a list of all available modules... [...] > File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 1342, > in > > File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 927, > in main > > UnboundLocalError: local variable 'given_files' referenced before assignment >>>> Unfortunately the "modules" help command actually imports all the available packages, and a buggy one may stop the whole process with an error. > Apparently python knows about them both, but I don't know I > haven't introduced an incompatibility somewhere...and that PIL > package showing up at the tail of the errors was one of my > more recent additions... If import of a package fails, the error reported is not accurate. In this case, probably some other package failed, that itself imported PIL. Line 927 in PIL/__init__.py does not exist. A quick fix is to replace line 1854 in pydoc.py (ModuleScanner.run) with this one: for importer, modname, ispkg in pkgutil.walk_packages(onerror=lambda name:None): (the onerror argument makes it to ignore all errors) -- Gabriel Genellina From bthayre at physics.ucsd.edu Mon Sep 22 18:59:36 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 22 Sep 2008 15:59:36 -0700 (PDT) Subject: Python based barcode readers References: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> Message-ID: I also forgot to mention that it need not be nearly as robust as something like Jailhelper 2.0, I will not really need to compensate for noise and irregular conditions. All of my barcodes will be scanned in a predictable, and consistent environment (i.e. a scanner), so all i need is some stupid little script that will read the an image in and decode it. From ppearson at nowhere.invalid Tue Sep 2 12:02:33 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 2 Sep 2008 16:02:33 GMT Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: <6i56cpFor2puU1@mid.individual.net> On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote: > At the risk of bike-shedding, [snip] (startled noises) It is a delight to find a reference to that half-century-old essay (High Finance) by the wonderful C. Northcote Parkinson, but how many readers will catch the allusion? -- To email me, substitute nowhere->spamcop, invalid->net. From semanticist at gmail.com Wed Sep 3 00:20:18 2008 From: semanticist at gmail.com (Miles) Date: Wed, 3 Sep 2008 00:20:18 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <20080902235412.GT29228@dragontoe.org> References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> Message-ID: Derek Martin wrote: > On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: >> but the instances of `Popen` are no actions. There's no way to >> "execute" a `Popen` instance. > > Yes there is... you execute it when you instantiate the object. At > the time of instantiation, you "open" the "P" (pipes). The subprocess module is also supposed to replace os.system and os.spawn*, neither of which involve opening pipes. (I use it for that functionality just as often, if not more so, as for piped subprocess communication). All rationalizations aside, I think Popen is a poor name for the class. But I would imagine the odds of it ever being changed are miniscule (Python 4?). -Miles From edward.fisher at st.com Wed Sep 3 04:29:39 2008 From: edward.fisher at st.com (Edward FISHER) Date: Wed, 3 Sep 2008 08:29:39 +0000 (GMT) Subject: Problems with running Python CGI Scripts Message-ID: <20080903082939.CKJ85501@mail1.edb.st.com> Hey guys. Im having problems running a python cgi. Im using the example code from: http://www.python.org/doc/essays/pp...east/sld041.htm as writen by Van Rossum himself I can get the script to run the python script but all that happens is that the black python box appears then disapears, the html that the python scripts should generate is never output. My html is: A Typical HTML form

A Typical HTML form

*Test CGI script and HTML to test server for correct running of python cgi scripting

Your First Name:

Your Last Name:

Click here to submit form:

This is calling the pyc file of the python script. I dont understand why if i call the py file itself all i get returned is the plain text of the python file. The python script is: #!/usr/local/bin/python import cgi def main(): print "Content-type: text/html\n" form = cgi.FieldStorage() if form.has_key("firstname") and form["firstname"].value != "": #if form has an object called firstname and the value is not an empty string print "

Hello", form["firstname"].value, "

" else: print "

Error! Please enter first name.

" main() If you need to see what happens then follow this link: http://www.fisherphotographics.co.uk/testhtml1.htm The python file has come directly from the example so i must me doing something wrong. I have all the correct permissions etc Thanks very much Ed Fisher From gogtesuyash at gmail.com Wed Sep 17 23:56:02 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 20:56:02 -0700 (PDT) Subject: Problem occured while sending mail References: <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> <6jckjhF2llrvU1@mid.individual.net> Message-ID: On Sep 17, 8:04 pm, Peter Pearson wrote: > On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui wrote: > > On Sep 17, 5:04 pm, sui wrote: > >> this is my code > > >> import sys, os, glob, datetime, time > >> import smtplib > >> ## Parameters for SMTP session > >> port=587 > >> SMTPserver= 'smtp.gmail.com' > >> SMTPuser= '... at gmail.com' > >> pw= 'fill in here' > >> SENDER= SMTPuser > > >> ## Message details > >> FROM= SENDER > >> TO= 'notgm... at a.com' > >> CC=FROM > >> ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC > >> RECEIVERS= (TO,) ## ignore the CC address > > >> subject= 'Test 1a' > >> message='*** Email test *** ' > > >> print 'Starting SMTP mail session on %s as %s ' % > >> (SMTPserver,SMTPuser) > >> session = smtplib.SMTP(SMTPserver,port) > >> session.set_debuglevel(0) # set debug level to 1 to see details > >> session.ehlo(SMTPuser) # say hello > >> session.starttls() # TLS needed > >> session.ehlo(SMTPuser) # say hello again, not sure why > >> session.login(SMTPuser, pw) > > >> ##Create HEADER + MESSAGE > >> HEADER= 'From: %s\r\n' % FROM > >> HEADER= HEADER + 'To: %s\r\n' % TO > >> HEADER= HEADER + 'Cc: %s\r\n' % CC > >> HEADER= HEADER + 'Subject: %s\r\n' % subject > >> BODY= HEADER + '\r\n' + message > >> print BODY > > >> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email > > >> session.close() > > >> Now when i run this .py file...as python mail.py > >> i can see only statement > >> starting smtp mail......n details > >> then nothing on screen after few minutes or after pressing ctrl +c > >> Traceback (most recent call last): > >> File "mail4.py", line 21, in > >> session = smtplib.SMTP(SMTPserver,port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > >> (code, msg) = self.connect(host, port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > >> self.sock.connect(sa) > >> File "", line 1, in connect > >> or may be conncetion time out > > >> wats the solution for this > > > if i dont press cntrl + c then it shows > > Starting SMTP mail session on smtp.gmail.com as gogtesuy... at gmail.com > > Traceback (most recent call last): > > File "mail4.py", line 21, in > > session = smtplib.SMTP(SMTPserver,port) > > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > > (code, msg) = self.connect(host, port) > > File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect > > raise socket.error, msg > > socket.error: (110, 'Connection timed out') > > > plz help me its urgent.....i want to complete it as early as possible > > I pasted your code into a file named temp.py, > and (perhaps superstitiously) added a backslash to this line: > > >> print 'Starting SMTP mail session on %s as %s ' % > > Here's what it does (long line wrapped manually): > > peter at eleodes:~$ python temp.py > Starting SMTP mail session on smtp.gmail.com as .... at gmail.com > Traceback (most recent call last): > File "temp.py", line 27, in ? > session.login(SMTPuser, pw) > File "/usr/lib/python2.4/smtplib.py", line 591, in login > raise SMTPAuthenticationError(code, resp) > smtplib.SMTPAuthenticationError: (535, \ > '5.7.1 Username and Password not accepted. Learn more at\n' \ > '5.7.1http://mail.google.com/support/bin/answer.py?answer='\ > '14257 a8sm34686663poa.12') > peter at eleodes:~$ > > This indicates that it got much farther than when you ran it, since > your timeout message comes from the smtplib.SMTP call several lines > before the session.login call. > > As a simple connectivity test, you might see whether you can connect > using telnet: > > peter at eleodes:~$ telnet smtp.gmail.com 587 > Trying 72.14.253.109... > Connected to gmail-smtp.l.google.com. > Escape character is '^]'. > 220 mx.google.com ESMTP m27sm34789033pof.6 > ^]c > > telnet> c > Connection closed. > peter at eleodes:~$ > > -- > To email me, substitute nowhere->spamcop, invalid->net. Actually i m working at place where proxy server has been working......so is it problem caused by that proxy server..peter thnks for suggestion but still its not working...... From user at domain.invalid Wed Sep 17 13:34:31 2008 From: user at domain.invalid (Canned) Date: Wed, 17 Sep 2008 19:34:31 +0200 Subject: translating ascii to binary In-Reply-To: <00e12f1f$0$20331$c3e8da3@news.astraweb.com> References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> <00e12f1f$0$20331$c3e8da3@news.astraweb.com> Message-ID: <48d13fa2$0$27103$9a622dc7@news.kpnplanet.nl> Steven D'Aprano schreef: > Your "ascii_to_bin" method tries to do too much in one method. You should > split the functionality into small, self-contained pieces, then combine > them. And frankly, once you got to the part where you started popping and > inserting, my brain melted. You are making an easy job too hard! *smiles* > It's a bad habit, I can't help it. From now on, I'll follow your advice to split the functionality into small, self-contained pieces. That popping and inserting is just a workaround for another workaround. > Try this instead: > > class Converterab: > ''' > Ascii-binary converter. > ''' > def __init__(self, string): > self.string = string > def bin(self, n): > """Return the binary representation of a positive integer n.""" > bindump = [] > while n > 0: > bindump.append(str(n & 1)) > n = n >> 1 > bindump.reverse() > if bindump: > return ''.join(bindump) > else: > return '0' > def char_to_bin(self, c): > """Return the binary representation of a character c.""" > bits = self.bin(ord(c)) > zeroes = "0" * (8-len(bits)) > return zeroes+bits > def ascii_to_bin(self): > results = [] > for c in self.string: > results.append(self.char_to_bin(c)) > return ''.join(results) > I've spend 3 days to find out what did I do wrong, but you did it in just half an hour/more. You're my hero. From wuwei23 at gmail.com Sat Sep 27 22:04:39 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 27 Sep 2008 19:04:39 -0700 (PDT) Subject: Docstrings for attributes? References: Message-ID: On Sep 28, 11:50?am, Roy Smith wrote: > Is there any way to attach a docstring to an attribute? ?I see that PEP-257 > talks about attribute docstrings, but it references PDP-258, which was > rejected. > > I suppose I could eschew plain attributes in favor of getter functions, > because those give me a place to hang a docstring, but that feels like the > wrong thing to do. There were a couple of solutions provided - including the use of properties - when this question came up earlier this week: http://groups.google.com/group/comp.lang.python/browse_frm/thread/18a8c3f09ac02f85# From Astley.lejasper at gmail.com Fri Sep 12 06:08:33 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Fri, 12 Sep 2008 03:08:33 -0700 (PDT) Subject: Good programming style Message-ID: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> I'm still learning python and would like to know what's a good way of organizing code. I am writing some scripts to scrape a number of different website that hold similar information and then collating it all together. Obviously each site needs to be handled differently, but once the information is collected then more generic functions can be used. Is it best to have it all in one script or split it into per site scripts that can then be called by a manager script? If everything is in one script would you have per site functions to extract the data or generic function that contain vary slightly depending on the site, for example import firstSiteScript import secondSiteScript firstsitedata = firstSiteScript.getData('search_str) secondsitedata = secondSiteScript.getData('search_str) etc etc OR def getFirstSiteData(search_str): etc etc def getSecondSiteData(search_str): etc etc OR def getdata(search_str, website): if website == 'firstsite': .... elif website =='secondsite': etc From benjaminlindelof at yahoo.com Wed Sep 3 12:52:06 2008 From: benjaminlindelof at yahoo.com (ToPostMustJoinGroup22) Date: Wed, 3 Sep 2008 09:52:06 -0700 (PDT) Subject: Coming from .NET and VB and C Message-ID: I'm coming from a .NET, VB, C background. C was good, and VB was better (with all of its libraries). Than .NET came along and all the libraries you can require are ready to go. I have no preference with MySQL or SQL, stored procedures or ad-hoc queries. SO, I'm interested in using my Google App space (free 500MB) to develop a quick database application. Using Python. I found "Dive Into Python" which I will be reading shortly. Any suggestions for someone new to the scene like me? From a_jtim at bellsouth.net Thu Sep 25 07:53:40 2008 From: a_jtim at bellsouth.net (Tim Arnold) Date: Thu, 25 Sep 2008 04:53:40 -0700 (PDT) Subject: multiple processes with private working dirs References: <473d008f-f3c4-4894-9251-b7fc9cf4c8e4@p10g2000prf.googlegroups.com> Message-ID: On Sep 25, 12:11?am, alex23 wrote: > On Sep 25, 3:37?am, "Tim Arnold" wrote: > > > Am I missing something? > > Do you mean something other than the replies you got the last time you > asked the exact same question? > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/42c... arggg. My newreader didn't show the initial post so I thought it never made it through. sorry for the noise. --Tim Arnold From steve at REMOVE-THIS-cybersource.com.au Mon Sep 8 08:51:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Sep 2008 12:51:04 GMT Subject: Where does the command "ls" in some doctest files come from ? References: Message-ID: <00d51a07$0$20306$c3e8da3@news.astraweb.com> On Mon, 08 Sep 2008 12:15:15 +0000, KLEIN St?phane wrote: > Hi, > > for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/ > tests.py?rev=89831&view=auto test file, there is this doctests : [snip] > >>> ls('develop-eggs') > I wonder where does the "ls('develop-eggs')" command come from ? > > It is doctest buildin command ? Easy to find out: import doctest and see for yourself: >>> import doctest >>> doctest.ls Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'ls' You found the ls() function in a docstring from Zope. The doctest seems to be testing ls(). That suggests to me that ls() is defined in Zope, not doctest. Why do you ask? -- Steven From carsten.haese at gmail.com Fri Sep 12 09:30:19 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Fri, 12 Sep 2008 09:30:19 -0400 Subject: Injecting new names into the above frame In-Reply-To: References: Message-ID: <57uyk.101$fD.22@flpi145.ffdc.sbc.com> Peter Waller wrote: > Dear Pythoners, > > I know this will probably be perceived as 'evil voodoo', and fair > enough: it probably is. I guess it is unpythonic. > > .. but I want to know how to do it anyway - mostly for my own > interest. Well, if you're really just asking out of curiosity, it should be sufficient to tell you that this is not possible. > [...] we have to add this > snippet before the Get() function returns: > > from ctypes import pythonapi, py_object, c_int > pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 ) > > This copies back the names into the code object, and works fine.. that > is, if the names already exist within the code object. > > def MyFunction(): > a = None > Get("a") > print a # Works > Get("b") > print b # Name error, b is undefined The answer to why this doesn't work lies in the disassembly of that function: 0 LOAD_CONST 0 (0) 3 STORE_FAST 0 (0) 6 LOAD_GLOBAL 1 (1) 9 LOAD_CONST 1 (1) 12 CALL_FUNCTION 1 15 POP_TOP 16 LOAD_FAST 0 (0) <- This is a 19 PRINT_ITEM 20 PRINT_NEWLINE 21 LOAD_GLOBAL 1 (1) 24 LOAD_CONST 2 (2) 27 CALL_FUNCTION 1 30 POP_TOP 31 LOAD_GLOBAL 2 (2) <- This is b 34 PRINT_ITEM 35 PRINT_NEWLINE 36 LOAD_CONST 0 (0) 39 RETURN_VALUE Since you have an assignment to the name a, a is recognized as a local name at compile time. b is not recognized as a local name at compile time, so even if you inject a value for b into the locals dictionary, the byte code still looks up the value as a global name. > Is there any way for Get() to define a new variable within > MyFunction's code object? Or is there any programmatic way to, at > runtime, insert new names into functions? Not without making fundamental changes to Python itself. The fact that this isn't possible is a feature, in my opinion. I like the fact that I can call a function and be *absolutely certain* that it's not going to pollute my local namespace. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From mbrkic at invalid_mail.adress Wed Sep 24 14:03:54 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Wed, 24 Sep 2008 20:03:54 +0200 Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: On Wed, 24 Sep 2008 07:32:56 -0700 (PDT), mdsherry at gmail.com wrote: >If you don't create a monolithic EXE, then most of the extra files >(that make up the bulk of the size) can be shared between other >converted scripts. That is, if you convert foo.py, and send the bundle >to your colleague, then convert bar.py, you only need to send bar.exe, >and it will run fine if they execute it in the same directory that has >all the DLLs you sent with foo.exe. > >Another option might be to encourage them to download Portable Python, >which doesn't need to be installed. This is an interesting suggestion. I didn't know there was a portable version of python. I will look into it - could just turn out to be the perfect solution to this (after all, it would be even simpler if they could send/receive just .py script). Thank you. -- Marin > >Mark Sherry From almar.klein at gmail.com Fri Sep 12 03:23:23 2008 From: almar.klein at gmail.com (Almar Klein) Date: Fri, 12 Sep 2008 09:23:23 +0200 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: References: <943393.38616.qm@web95111.mail.in2.yahoo.com> Message-ID: > > I find it impossible to take anyone asking others to do their school > work for them seriously no matter how or what they are willing to pay. > Exactly, and writing the subject of the post in all capitals doesn't help either... Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From mathieu.malaterre at gmail.com Mon Sep 8 05:39:27 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Mon, 8 Sep 2008 02:39:27 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> Message-ID: <4910a424-7c4e-48c8-8d56-b388796c70b8@f36g2000hsa.googlegroups.com> On Sep 8, 9:32 am, Bruno Desthuilliers wrote: > mathieu a ?crit : > > > Hi there, > > > I am trying to write something very simple to test if a list > > contains another one: > > > a = [1,2,3] > > > b = [3,2,1,4] > > > but 'a in b' returns False. > > Indeed. Lists are not sets, and the fact that all elements of list a > happens to also be part of list b doesn't make the list a itself an > element of list b. > > >>> a = [1, 2, 3] > >>> b = [3,2,1,4] > >>> c = [b, a] > >>> a in c > True > >>> b in c > True > >>> c > [[3, 2, 1, 4], [1, 2, 3]] > >>> > > > How do I check that a is indeed contained > > in b ? > > But that's what you did - you *did* checked if a was contained in b, and > this is not the case. What you want is to check if *all elements* of a > are contained in b, which is quite another problem. Now the answer to > your question : use sets. > > >>> set(a).issubset(set(b)) > True > >>> thanks all ! From mail at johnlawrence.net Thu Sep 11 05:28:15 2008 From: mail at johnlawrence.net (John Lawrence) Date: Thu, 11 Sep 2008 10:28:15 +0100 Subject: Adding environment variables to bash. In-Reply-To: References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> Message-ID: <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> > > when a process starts, it gets a *copy* of the parent's environment. it > can modify that copy, but it cannot modify the variables in the parent. You can make a command use the current shell though if you use the '.' command e.g.: jl > cat env.sh export TEST='hello' jl > ./env.sh && env | grep TEST #Doesn't set TEST in parent shell jl > . ./env.sh && env | grep TEST #Adding '. ' before the command uses the same shell TEST=hello John. -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Tue Sep 16 09:14:38 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 15:14:38 +0200 Subject: MVC with Python In-Reply-To: <3f0d61c40809160547t339226acx19a7a0a0f58a6e73@mail.gmail.com> References: <3f0d61c40809160547t339226acx19a7a0a0f58a6e73@mail.gmail.com> Message-ID: <200809161514.39385.maric@aristote.info> Le Tuesday 16 September 2008 14:47:02 Marco Bizzarri, vous avez ?crit?: > On Tue, Sep 16, 2008 at 1:26 PM, Georg Altmann wrote: > > Marco Bizzarri schrieb: > >> On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann > >> > >> wrote: > >>> Hello, > >>> > >>> I need some advice on how to implement model-view-controller. I am > >>> trying to > >>> develop a GUI application with PyQt, yet the problem rather applies to > >>> mvc > >>> in general, not just GUI applications. > >>> > >>> Let's say the data is a list of objects with a common base class. The > >>> views > >>> are either a graphical representation of the objects or some form of > >>> textual > >>> input. The views shall change the model by using command objects (for > >>> undo, > >>> e.g. QUndoCommand). > >>> > >>> My current approach is to implement the model as a class with a > >>> list-like interface, with methods insert(), remove(), __getitem__(), > >>> __setitem__(),... > >>> and a signal to notify the views. The objects in the list have methods > >>> to change their state as well. > >>> > >>> My problem is, how do the commands interact with the model? > >>> Let's say I have a command that modifies an object o in the list. > >>> > >>> 1) If list[key_to_o] returns a reference to the object, the command can > >>> modify the object by using this reference, i.e. list[key_to_o].setX(). > >>> So there is no way for the list to know when the object changed - how > >>> can it emit a singal then? > >>> > >>> 2) If list[key_to_o] returns a deep copy of the object, > >>> copy_of_o = list[key_to_o], the command mofifies the copy and the > >>> updates the list: list[key_to_o] = copy_of_o. Now the list can emit a > >>> signal in __setitem__(). > >>> While this may work, it seems awkward to copy around objects just to > >>> perform > >>> a possibly simple operation on them. Additionally it might not be > >>> feasible > >>> once objects get complex. > >>> > >>> 3) The interface of the classes of the objects could be reflected in > >>> the list class, i.e. list.set_x_on_obj(key_to_obj,x). This would > >>> probably make > >>> the list class interface very bloated. > >>> > >>> Of course the problem is not really limited to Python, my apologies if > >>> I'm > >>> totally off-topic here. > >>> > >>> Regards > >>> Georg > >> > >> Well, I think one of the assumptions of the MVC is that the view can > >> be notified about the changes in the model. According to your > >> interface, the View can just be notified on operations about the > >> *whole* model, like adding or removing elements from it. > >> > >> But the elements of your list-like class should be a part of your > >> model, and therefore should be able to notify the Views by > >> themselfves. > > > > Ok, consider this: say the model needs to compute some sort of value by > > iterating over all objects in the list (for example some sort of hash). > > Some kind of view then displays this value. > > I could implement this by connecting a signal in each object to a slot in > > the list class which in turn emits a signal which is connected to the > > view. > > > > But this implies all the objects in the list have to be instances of > > QObject. I wonder if this is isn't a weird design, because for example > > all value type classes in Qt don't derive from QObject, e.g. QString. My > > list objects are not that simple (in terms of the data structure). So is > > it ok to make them QObjects? > > Did you take a look at this? > > http://www.potu.com/man/doc.trolltech.com/4.0/model-view-programming.html > > It seems to imply that you should use QtAbstractItemModel as a base > class for all your models. But since I'm not an expert about Qt, I > cannot really say. > > Regards > Marco > > > Regards > > Georg > > > > -- > > http://mail.python.org/mailman/listinfo/python-list It is not about QT, it is about MVC. In MVC, code which implement the model should be completely ignorant of the libraries used for gui, and the gui part of the application shouldn't acces directly to your model logic. This why there is a third layer which abstract the logic of your datas and provide standard operation for the gui code. This third layer (Controllers), should be as few as possible coupled to the specificities of the gui library (but must be). The quoted papers explain rather well how to do this with QT (apart they call controllers "delegates"). For medium to big project, don't be afraid to divide your program in three packages, one for the model, in which you must not have any reference to QT API of some sort, one for the controllers, where you provide events and methods to manipulate your model, one for gui, where you just build windows, subscribe to controller's events and use their functions as callbacks for your widgets. -- _____________ Maric Michaud From sumitava.mukh at gmail.com Tue Sep 9 07:17:27 2008 From: sumitava.mukh at gmail.com (Sumitava Mukherjee) Date: Tue, 9 Sep 2008 04:17:27 -0700 (PDT) Subject: Python Installation and Running on Windows Vista References: <4f66ca7b-b495-4b12-bb4c-29b096eb53c9@j22g2000hsf.googlegroups.com> Message-ID: On Sep 9, 3:46?pm, Mchizi_Crazy wrote: > Please help with issue... I heard of compatimbiltity issues and would > like clarification. The win32 installer available from python.org works absolutely fine with Vista. So, go ahead and try it out. It works for all of my friends and myself From steve at holdenweb.com Fri Sep 12 08:36:37 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 08:36:37 -0400 Subject: String to hexadecimal conversion In-Reply-To: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Message-ID: Praveena P wrote: > Hi folks, > > I am new to Python... so am not too sure about how the type conversion > works. > > I have to read a file that contains hexadecimal data and use the data > further to do some arithmetic calculations. > A sample of the input is : 00000000000020E0000032F800000000400022005E > The problem I am facing is this: > I am using f.read(2) to read a byte at a time, but the data that is > read is a string rather than a number. So it kind of hampers any > arithmetic operations I perform on this data... > > Could you please suggest some method I could use for this? Generally speaking, reading a file 2 bytes at a time i going to be inefficient and untidy. Does this help? >>> int("00000000000020E0000032F800000000400022005E", 16) 170696759285949896156423472451551326L >>> Or have I misunderstood your intention? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From maric at aristote.info Thu Sep 4 09:07:34 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 4 Sep 2008 15:07:34 +0200 Subject: overwrite set behavior In-Reply-To: References: Message-ID: <200809041507.35366.maric@aristote.info> Le Thursday 04 September 2008 14:31:23 Michele Petrazzo, vous avez ?crit?: > Marco Bizzarri wrote: > > looking at the source, maybe you could create a subclass of Set > > redefining the __contains__ method? > > Made some tries, but __contains__ are never called > No, __contains__ is only called with "in" operator, not for internal hashing. Anyway this solution is bad, you'll need to compare the new element with all the set contain, which would result in a O(n) algorithm for adding elements to the set in place of the O(1) it use. The right way to go is one like Diez show you in a previous post. > ?>>> class foo(set): > ... ?def __contains__(self, value): > ... ? print value > ... > ?>>> a = foo((1,2)) > ?>>> -- _____________ Maric Michaud From dmitry at athabascau.ca Thu Sep 25 11:47:51 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 15:47:51 GMT Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> Message-ID: Thanks Bruno, your comments were really helpful (so was the "improved" version of code). My replies below: Bruno Desthuilliers wrote: >> So decorators inside of B just identify that those methods will be >> proxied by A. On one hand from logical standpoint it's kind of weird to >> tell class that it is going to be proxied by another class, > > Indeed - usually, proxied objects shouldn't have to be aware of the > fact. That doesn't mean your variation on the proxy pattern is > necessarily bad design (hard to tell without lot of context anyway...), > but still there's some alarm bell ringing here IMHO - IOW : possibly the > right thing to do, but needs to be double-checked. I'm kind of looking at options and not dead-set on decorators, but I can't find any other "elegant enough" solution which wouldn't lead to such tight coupling. The problem I'm trying to solve is not much more complicated than what I have already described so if anybody can suggest a better approach - I'm all for it. > Now I'm not sure I really like your implementation. Here's a possible > rewrite using a custom descriptor: yeah, that was going to be my next step - I was just aiming for proof-of-concept more then efficient code :) > class Proxymaker(object): > def __init__(self, attrname): > self.attrname = attrname > > def __get__(self, instance, cls): > def _proxied(fn): > fn_name = fn.__name__ > def delegate(inst, *args, **kw): > target = getattr(inst, self.attrname) > #return fn(target, *args,**kw) > method = getattr(target, fn_name) > return method(*args, **kw) > > delegate.__name__ = "%s_%s_delegate" % \ > (self.attrname, fn_name) > > setattr(cls, fn_name, delegate) > return fn > > return _proxied > > class A(object): > def __init__(self,b): > self.val='aval' > self.b=b > b.val='aval' > > proxy2b = Proxymaker('b') > > def mymethod(self,a): > print "A::mymethod, ",a > > def mymethod2(self,a): > print "A::another method, ",a > > class B(object): > def __init__(self): > self.val='bval' > > @A.proxy2b > def bmethod(self,a): > print "B::bmethod" > print a, self.val > > @A.proxy2b > def bmethod2(self,a): > print "B::bmethod2" > print a, self.val > My point is that: > 1/ you shouldn't have to rewrite a decorator function - with basically > the same code - for each possible proxy class / attribute name pair combo > 2/ making the decorator an attribute of the proxy class makes > dependencies clearer (well, IMHO at least). agreed on all points > I'm still a bit uneasy wrt/ high coupling between A and B, and if I was > to end up with such a design, I'd probably take some times to be sure > it's really ok. that is the question that troubles me at this point - thus my original post (read the subject line ;) ). I like the clarity decorators bring to the code and the fact that it's a solution pretty much "out-of-the-box" without need to create something really-really custom, but I'm worried about tight coupling and somewhat backward logic that they would introduce (the way I envisioned them). From FettManChu at gmail.com Tue Sep 16 23:57:48 2008 From: FettManChu at gmail.com (Fett) Date: Tue, 16 Sep 2008 20:57:48 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> <2cbfdce2-9203-4136-a274-bc7d19dc293a@y38g2000hsy.googlegroups.com> Message-ID: <3d9ab5e0-924b-48c1-b91b-2db1ca91e14c@26g2000hsk.googlegroups.com> On Sep 16, 9:44 pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 16, 9:25 pm, Fett wrote: > > > > > On Sep 16, 9:00 pm, "Aaron \"Castironpi\" Brady" > > > wrote: > > > On Sep 16, 8:50 pm, Fett wrote: > > > > > I am trying to find a wrapper to do linear programming within python. > > > > I am using an ubuntu machine and I have apt-get'd lp_solve, which > > > > works just fine. If someone knows of a wrapper that will work with > > > > that that'd be great. > > > > > I also heard that scipy has a wrapper, however, I can't find any > > > > documentation on it, nor can I seem to find it with dir(). If anyone > > > > knows where there is good documentation on this I would love to use > > > > that (the more native to python the better imo). > > > > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > > > > openopt, and cvxopt. I can't seem to find any with enough > > > > documentation to get me off the ground. Some I can't compile, some I > > > > can't even find out how to compile. > > > > > If anyone knows of an LP package (preferably with IP as well, like > > > > lp_solve has), that interfaces well with python and has enough > > > > documentation to get a dependency newb like myself off the ground that > > > > would be great. > > > > Google says: > > > > about 254,000 for linear programming python. > > > > Link 3 is: > > > >http://wiki.python.org/moin/NumericAndScientific/Libraries > > > > Scroll down. > > > Yes, many of those seem to be deprecated, without destinations to > > links, most are poorly or not documented at all. The few that are, I > > still can't get running. Of those 254, I think I have tried at least > > 10 pages worth. Still no luck. > > > # lpsolvpy - Can't get it to compile - dependency problems. > > # Lp_solve5 - NO python binding yet. Volunteers needed for python > > bindings. > > # pycplex - You need to compile the CPX.so module. Change the required > > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > > sure what to do here. > > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > > I missed the second link to the python bindings, looked all over the > > glpk site for anything about python. > > # SciPy --http://www.scipy.org-supposedly has this, but as I said, > > I can't find any mention of it anywhere but on the site you linked. > > # pySimplex - (broken link)(broken link) > > # Simplex - link is broken, but nothing is mentioned > > > I'll take a closer look at glpk's python bindings and if there is any > > documentation on them, maybe I'll have some luck. btw, I have been > > looking for something that works, I have over 5 packages on my desktop > > that I have tried to get up and running, but none of them seem to > > work. glpk makes 6. > > If you can find one working in C, use ctypes to link into Python. We > can help you with that part. It lets you pass primitive types, > structs, arrays, pointers, to C modules and return values. You need > to know the C signatures to set up the Pythonized signatures. Ok, it seems that I have found one (although without an integer programming component): upon searching for glpk in the package manager in ubuntu I found a package called cvxopt, it is a bit clunky (compared to the niceness of lp_solve), but I think I can figure this one out. Thanks all who answered. From beema.shafreen at gmail.com Thu Sep 11 09:47:25 2008 From: beema.shafreen at gmail.com (Beema Shafreen) Date: Thu, 11 Sep 2008 19:17:25 +0530 Subject: function return In-Reply-To: References: Message-ID: thanks for your valuable comments. I could solve the problem wiht your comments On Thu, Sep 11, 2008 at 7:07 PM, Fredrik Lundh wrote: > make that: > > note that you put the "return" statement inside the loop, so returning >> only one line is the expected behaviour. >> > > to fix this, you can append the result strings to the data_lis list inside > the loop: > > result = "%s\t%s\t%s" %(id,gene_symbol,ptms) >> data_lis.append(result) >> >> and then return the list when done: >> >> > fh.close() >> return data_lis >> >> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From giltay at gmail.com Thu Sep 18 13:26:49 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Thu, 18 Sep 2008 10:26:49 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <30fab72b-2d7f-497d-a687-1d697633db9c@z66g2000hsc.googlegroups.com> Message-ID: <4320a4f2-48b9-42c4-b51e-ef469ac6c79c@8g2000hse.googlegroups.com> On Sep 18, 11:18?am, prueba... at latinmail.com wrote: > dup=set() > SN=[] > for item in IN: > ? ?c=item.coordinates[0], item.coordinates[1] > ? ?if c in dup: > ? ? ? SN.append(item.label) > ? ?else: > ? ? ? dup.add(c) +1 for O(N) If item.coordinates is just an (x, y) pair, you can skip building c and save a little memory: seen_coords = set() for node in IN: if node.coordinates in seen_coords: SN.append(node.label) else: seen_coords.add(node.coordinates) seen_coords gets populated with references to the existing node.coordinates objects, instead of new tuples. Geoff G-T From hauva at arska.org Mon Sep 1 12:11:07 2008 From: hauva at arska.org (Ari Makela) Date: 01 Sep 2008 16:11:07 GMT Subject: How Compute # of Days between Two Dates? References: Message-ID: <48bc141b$0$23597$4f793bc4@news.tdc.fi> On 2008-09-01, W. eWatson wrote: > Oddly, Leaning Python has no mention of datetime (not date or time), at > least, that I could find. I'm considering the Nutshell book, 2nd ed., as a > better reference (and cross reference) to various topics. datetime is pretty new standard library module. I'm quite sure that it wasn't around when the latest edition of Learning Python was written. -- Ari Makela late autumn - hauva at arska.org a single chair waiting http://arska.org/hauva/ for someone yet to come -- Arima Akito From mwilson at the-wire.com Mon Sep 29 11:14:36 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 29 Sep 2008 11:14:36 -0400 Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> Message-ID: George Sakkis wrote: > As Terry Reedy wrote, partly history and partly practicality. There's > no philosophical reason why we write "len(x)" (generic builtin), > "x.append(1)" (method) or "del x[i]" (statement). The latter in > particular is IMHO a design wart; there's no reason for not writing it > as "x.delete(i)". `del x` has almost nothing to do with `x`, and almost everything to do with a namespace containing `x`. The object doesn't know what namespace it's in. Mel. From mal at egenix.com Thu Sep 4 09:59:36 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 04 Sep 2008 15:59:36 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <3de8e1f70809040357p6beb1efar7fe57af9bcaa537c@mail.gmail.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <48BFB534.2080508@egenix.com> <3de8e1f70809040357p6beb1efar7fe57af9bcaa537c@mail.gmail.com> Message-ID: <48BFE9C8.8090501@egenix.com> On 2008-09-04 12:57, Banibrata Dutta wrote: > On Thu, Sep 4, 2008 at 3:45 PM, M.-A. Lemburg wrote: > >> On 2008-09-04 11:14, Kay Schluehr wrote: >>> On 4 Sep., 10:31, "M.-A. Lemburg" wrote: >>>> On 2008-09-04 07:49, Kay Schluehr wrote: >>>> >>>>> 3) Following the public rumor mill and the latest hype RIA i.e. the >>>>> merge of web- and desktop applications with systems like Adobe AIR, >>>>> JavaFX, Google Gears and MS Silverlight is the future of frontend >>>>> development. With the exception of IronPython and Silverlight, Python >>>>> hasn't even entered this game and no one knows if it ever will. >>>> Actually, it has already and quite some time ago: >>>> >>>> http://www.artima.com/weblogs/viewpost.jsp?thread=208528 >>>> >>>> The recipe is simple: use Python for the business logic, database >>>> interfacing, etc and have it talk to a Flex front-end via XML-RPC >>>> or REST. >>> Python is still server-side in this scenario and plays no role in UI >>> definitions. >> That depends on how you design the application. It is well possible >> to have Python drive the GUI by sending the required details to >> the Flex front-end via XML (ie. data-driven GUIs). >> >>> So one doesn't get more than e.g. Django apps that >>> respond to HTTP requests triggered by JavaScript forms except that >>> JavaScript+HTML+Browser is replaced by Flex = AS3+MXML+FlashPlayer. >> You really can't compare the Flex stack to an AJAX stack. Flex >> has a lot more to offer for GUI programming than AJAX, it also >> doesn't suffer from the problems of AJAX having to support several >> different sets of browser or library bugs. >> >> We switched from an AJAX approach to a Flex-based approach last year >> and never even considered moving back again. > > > The approach does seem quite impressive, but isn't Flex's platform > neutrality quite over-rated ? I mean after-all, it assumes that Flex is > available for and available on the platform. Flex today is not yet so > ubiquitous as the JRE... Since Flex is compiled to Flash and runs inside the Flash player, it is fairly easy to get Flex apps running. You do have to have the Flash9 player installed and the default minimum is 9.0.115.0 for Flex builder 3. > Are there some established best-practices on how to package such > applications -- s.a. shipping with its's own Flex runtime, offer-download if > missing etc. ? What happens if owner of target machine decides to upgrade > their version of Flex, will it impact the application package in anyway, and > render rest of it "non-upgradable" ? So far we have not had any such problems, but that could change when Flash10 starts to ship, of course. We currently ship the application as a server application. The only requirement on the client side is having a browser with Flash9 installed. Pointing the browser at the server will then load the compiled Flex application (as .swf file). An alternative approach is bundling the client as AIR application which then runs as stand-alone app on the client side, but we haven't tried that yet. >>> The role of Python is somewhat arbitrary. This could change only if >>> Python becomes a client side language executed by AVM, V8 etc. like >>> IronPython in Silverlight. >>> >>> About separating UI from application logics by assigning functionality >>> to different general purpose languages I have to admit that I don't >>> think it is such a great idea ... >> In my experience, Flex + Python gives you the best of both worlds, >> the nice GUI features of Flex and the efficiency of Python for the >> business logic. >> >> A long time ago, there was a Python plugin for Netscape >> which allowed you to run Python straight in the browser. Perhaps >> it's time to revive such an idea... but then you're still missing >> out on the GUI part, since you're still stuck with what the >> browser has to offer in terms of widget support. >> >> -- >> Marc-Andre Lemburg >> eGenix.com >> >> Professional Python Services directly from the Source (#1, Sep 04 2008) >>>>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ >> ________________________________________________________________________ >> >> :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: >> >> >> eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 >> D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg >> Registered at Amtsgericht Duesseldorf: HRB 46611 >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From google at mrabarnett.plus.com Tue Sep 2 16:53:27 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 2 Sep 2008 13:53:27 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: On Sep 2, 5:55?pm, Steven D'Aprano wrote: > I find myself writing command line tools in Python where I wish to > include "verbose" output to stdout. > > I start with a helper function: > > def print_(obj, level=0): > ? ? if _verbosity >= level: > ? ? ? ? print obj > > And then I end up with functions or methods looking like this: > > def parrot(x) > ? ? print_("precondition", level=2) > ? ? do_something() > ? ? print_("status is good...", level=1) > ? ? print_("parrot is squawking strongly now", level=2) > ? ? do_something_else() > ? ? print_("squawk squawk squawk", level=3) > ? ? do_more() > ? ? print_("postcondition", level=1) > ? ? return something > > That often means that my functions end up with more message printing code > than actual code. The whole thing seems messy and hard to manage for all > but the smallest scripts. > > Worst of all, sometimes the messages I wish to print may be expensive to > compute, and I don't want to waste time computing them if they aren't > going to be printed because the verbosity is too low. But nor do I wish > to fill my code with this: > > if _verbosity >= 3: > ? ? x = calculate_complicated_thing() > ? ? print_(x, level=3) > > Is there a better way of doing this than the way I am going about it? > How about: def print_(obj, level=0): if _verbosity >= level: if callable(obj): obj = obj() print obj so that you could then use: print_("precondition", level=2) and: print_(calculate_complicated_thing, level=3) or: print_(lambda: calculate_complicated_thing(argument), level=3) From bearophileHUGS at lycos.com Fri Sep 26 16:39:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 26 Sep 2008 13:39:16 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> Message-ID: <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> I suggest Python programmers to fill the holes in the Python std lib with some debugged & tuned implementations, their "bag of tricks", so they don't have to re-invent and debug things all the time. This works well with Psyco: def issubseq(sub, items): """issubseq(sub, items): return true if the sequence 'sub' is a contiguous subsequence of the 'items' sequence. >>> issubseq() Traceback (most recent call last): ... TypeError: issubseq() takes exactly 2 arguments (0 given) >>> issubseq("abc") Traceback (most recent call last): ... TypeError: issubseq() takes exactly 2 arguments (1 given) >>> issubseq(1, [1, 2, 3]) Traceback (most recent call last): ... TypeError: 'int' object is not iterable >>> isi = lambda s,i: int(issubseq(s,i)) >>> isi([], []) 1 >>> isi("a", "") 0 >>> isi("", "a") 1 >>> isi("", "aaa") 1 >>> isi("a", "a") 1 >>> isi("ab", "bab") 1 >>> isi("ab", "bab") 1 >>> isi("ba", "bbb") 0 >>> isi("bab", "ab") 0 >>> isi(("a", "b"), ("a","a","b")) 1 >>> isi(("a", "b"), ("a","a","c")) 0 >>> isi([1,2,1], [3,5, 1,2,4, 1,2,1, 6]) 1 >>> isi([1,2,1], [3,5, 1,2,4, 1,2,3, 6]) 0 >>> l = [1] * 50 + [1,2,3] + [4] * 50 >>> isi([1,2,3], l) 1 >>> l = [1] * 50 + [1,2,4] + [5] * 50 >>> isi([1,2,3], l) 0 """ if not hasattr(sub, "__getitem__"): sub = list(sub) len_sub = len(sub) if len_sub == 0: return True try: if not len(items) or len(items) < len_sub: return False except TypeError: pass if sub == items: return True table = [0] * (len_sub + 1) # building prefix-function m = 0 for i in xrange(1, len_sub): while m > 0 and sub[m] != sub[i]: m = table[m - 1] if sub[m] == sub[i]: m += 1 table[i] = m # searching m, i = 0, 0 for x in items: while m > 0 and sub[m] != x: m = table[m - 1] if sub[m] == x: m += 1 if m == len_sub: return True i += 1 return False Usage: >>> from util import issubseq # uses Psyco >>> from timing import timeit >>> a = range(1000000) + range(1000) + range(100000) >>> sub = range(1000) >>> len(a) 1101000 >>> timeit(issubseq, sub, a) (True, 0.0) >>> a = range(999) * 10000 + range(1000) + range(10000) >>> sub = range(1000) >>> timeit(issubseq, sub, a) (True, 0.20000000000000001) Bye, bearophile From workitharder at gmail.com Thu Sep 4 12:36:23 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 4 Sep 2008 09:36:23 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> Message-ID: > >>> so unfortunately I think I need to use __getattribute__ > >>> to do this. I'm doing all this just to make the connection not > >>> actually connect until used. > >> I may be dumb, but I don't get how this is supposed to solve your > >> problem. But anyway : there's a known design pattern for what you're > >> trying to do, that doesn't require mixins nor messing with > >> __getattribute__ (which, I repeat, is more often than not something you > >> *don't* want to do). The name of the design pattern is "proxy". I > >> strongly suggest that you 1/ try to cure the real problem instead of > >> hacking around and 2/ read about the proxy design pattern. > > >> My 2 cents... > > > I like the idea of mix-ins, but can't figure out how to make a proxy > > work that way. > > You mean, "how to use a proxy for lazy initialization" ? Heck, that's > the exact use case in the GoF. I mean, "how to make a MixIn class that uses the proxy pattern". I'd like to be able to do something like this: class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ..., VanillaCursor): pass This works with my current implementation. After thinking about it more, I think I've got such a thing written. I had to use inspect.getmro and new.classobj to do it, but it works and it honors the usual mro (as far as I can tell). I've put the code at the bottom to (try to) maintain readability. > > For a long time I had a proxy class that added five or > > six features on top of the MySQLdb package, but it wasn't configurable > > enough, and I'm working on splitting each feature into its own MixIn > > class. > > > As an aside, this is working for me pretty well. The "reconnect" > > method (inheritied from a "Reconnectable" mixin) uses several of the > > object's attributes, so I need to set _inited beforehand so that I > > don't get into an infinite __getattribute__ loop. What I'd *really* > > like to do is remove __getattribute__ from the object at that point. > > You can't. Or, more exactly, all you can do is remove __getattribute__ > from the mixin class - but then the mixin class won't work anymore. I > don't mean to be condescendant, but it looks like you don't have a clear > understanding of Python's object model here - else you wouldn't even > consider doing such a thing. FWIW, I posted a solution based on the > __getattr__ hook, which did work - at least for the "specs" implied by > your code snippet. My toy example turned out to be not the best representation of the problem. The base class has attributes that "exist" but either throw errors or segfault if used before reconnect() is called. This means that I need to capture more than just the attributes that would throw AttributeError. #CODE######################################## class Base(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __str__(self): return "" % (self.args, self.kwargs) class MixIn2(object): def __str__(self): return "" % super(MixIn2, self).__str__() class MixIn1(object): def __str__(self): return "" % super(MixIn1, self).__str__() class ProxyMixIn(object): def __init__(self, *args, **kwargs): self.__proxied = None self.__args = args self.__kwargs = kwargs def __getattr__(self, attr): print "Getting", attr try: return getattr(self.__proxied, attr) except AttributeError: if self.__proxied: raise else: from inspect import getmro mro = getmro(self.__class__) mro = mro[list(mro).index(ProxyMixIn) + 1:] print "Proxied mro", mro from new import classobj self.__proxied = classobj("Proxied", mro, globals()) (*self.__args, **self.__kwargs) return getattr(self.__proxied, attr) def __str__(self): return "" % super(ProxyMixIn, self).__str__() class Proxy(MixIn1, ProxyMixIn, MixIn2, Base): pass def main(): p = Proxy(1,2,3, one=1, two=2) print p main() #OUTPUT###################################### Getting args Proxied mro (, , ) Getting kwargs >>> From uzmanajmal at gmail.com Sat Sep 13 08:23:46 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Sat, 13 Sep 2008 17:23:46 +0500 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Problem is that when i start client (while the server is already running), i get an error i.e. Error 500 Internal Server Error On Sat, Sep 13, 2008 at 3:58 PM, Fredrik Lundh wrote: > Usman Ajmal wrote: > > Where exactly should i call ServerProxy? Following is the code from my >> client.py >> > > ServerProxy is the preferred name. Server is an old alias for the same > class. > > t = SecureTransport() >> t.set_authorization(ustring, text_ucert) >> server = xmlrpclib.Server('http://localhost:8000/',transport=t) >> print server.s() >> > > that code looks correct. so what's the problem? > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From notvalid2 at sbcglobal.net Tue Sep 9 00:53:18 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 08 Sep 2008 21:53:18 -0700 Subject: Correcting for Drift between Two Dates Message-ID: I have two dates, ts1, ts2 as below in the sample program. I know the clock drift in seconds per day. I would like to calculate the actual date of ts2. See my question at the end of the program. # time differences with addition of drift from datetime import datetime, timedelta import time drift = 4.23 # seconds per day format = '%Y%m%d_%H%M%S' ts1 = "20080901_120000" # base date-time ts2 = "20080904_180000" d1 = datetime(*(time.strptime(ts1, format)[0:6])) d2 = datetime(*(time.strptime(ts2, format)[0:6])) #d += timedelta(seconds=sec) delta = d2-d1 # delta format is nnn[n] days, hh:mm:ss # delta is type 'datetime.timedelta' print delta # get back to ts2 as a check d3 = d1+d print d3 #OK, now I need to add the total drift time between # d1 and d2, to get the true date-time of d2. # How do I get at the nnn and hh:mm:ss of delta so that # I can change nnn to nnn+(fraction of day in hh:mm:ss) to # days + fraction of day, D. I want to multiple D by drift # to get seconds of drift in period, then add it to d2. Results 3 days, 6:00:00 2016-09-04 18:00:00 -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From has.temp3 at virgin.net Tue Sep 9 17:44:58 2008 From: has.temp3 at virgin.net (has) Date: Tue, 9 Sep 2008 14:44:58 -0700 (PDT) Subject: How to record audio from Python on Mac? References: <74b0be47-d2c4-4003-a734-35ff9813ef90@l43g2000hsh.googlegroups.com> Message-ID: <757d914a-f8b6-4d0d-bfc8-02bf7dd9cbe4@w7g2000hsa.googlegroups.com> On 9 Sep, 19:55, David Thole wrote: > Another option you could use is calling Applescript from the command > line, to open, execute, and handle audio. For example, using QuickTime Player (which is a buggy, poorly designed piece of junk, but might suffice if you only need something quick-n- dirty and aren't too fussy): #!/usr/bin/python from time import sleep from appscript import * duration = 5 # seconds outpath = '/Users/foo/test.aiff' qtp = app('QuickTime Player') qtp.new_audio_recording() qtp.documents[1].start() sleep(duration) qtp.documents[1].stop() qtp.documents[1].export(to=mactypes.File(outpath), as_=k.AIFF) Or, if you're on Leopard and want something a bit more polished, you could look into using the new QTKit framework via PyObjC. Dunno about Python-specific examples, but I imagine you could dig up some ObjC code if you search around a bit and then convert that over to Python yourself. HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From mail at timgolden.me.uk Tue Sep 16 04:58:14 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 09:58:14 +0100 Subject: A unique instance of Python GUI program In-Reply-To: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Message-ID: <48CF7526.4030701@timgolden.me.uk> akineko wrote: > This may not be a Python specific challenge. > I have a GUI program written in Python + Tkinter. > It works very well. > > Now, I would like to start it from a shell script. > As my GUI program includes a server, it should not have more than one > instance. > Is there any easy way to check if another instance of the program is > already running. > > I vaguely remember that Windows programming provides a way to check. > > A platform independent approach would be nice but a solution for X is > sufficient for my application. I swear this question's been asked twice this month already. Is there a convention going on of one-instance-only application writers? Have a look at: http://mail.python.org/pipermail/python-list/2008-August/505958.html http://mail.python.org/pipermail/python-list/2008-August/505992.html http://mail.python.org/pipermail/python-list/2008-August/505850.html or just search the mailing lists for various previous discussions: http://www.google.com/search?q=site%3Amail.python.org+application+single+instance (or similar queries) TJG From gagsl-py2 at yahoo.com.ar Sat Sep 13 13:13:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Sep 2008 14:13:37 -0300 Subject: I cannot find where Numpy 1.2 is located References: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> Message-ID: En Fri, 12 Sep 2008 17:02:44 -0300, Blubaugh, David A. escribi?: > I have been trying to locate as to where Numpy 1.2 can be downloaded. I > will need this update. The only version available at the Numpy website > for download is only 1.1.1 not the required 1.2 that I definitely need > at this time. Try asking Guido for his time machine. 1.1.1 is the latest release. -- Gabriel Genellina From mr.spoon21 at gmail.com Sun Sep 14 18:08:53 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Mon, 15 Sep 2008 00:08:53 +0200 Subject: Abstract class In-Reply-To: References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <8f67b6f80809141508q3adc7530w198869d2eaf0a2a1@mail.gmail.com> It seems I started a long discussion. You pointed out a lot of interesting things. For example the math operations over notes and intervals and the use of the modulo operator. I already had in mind to implement such things. Anyway, the real purpose of the project is to use these objects with Pyke (Python Knowledge Engine) [1]. I'm not sure yet what I am going to do, but and idea would be to find an appropriate scale for some given chords (for example, from a midi input). As suggested, I'm going to write code and see what is better. Thanks everybody, bye [1] http://pyke.sourceforge.net/ From coolkid246 at googlemail.com Thu Sep 4 06:07:44 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:07:44 -0700 (PDT) Subject: =?ISO-8859-1?Q?online_credit_ohne_in_Landau_sofortkredit_kredit_onl?= =?ISO-8859-1?Q?ine_vergleich_beamtendarlehen_ohne_schufa_handy_ohne_schufa_?= =?ISO-8859-1?Q?kredite_ohne_schufaauskunft_kredit_vergleich_geld_kredit_ohn?= =?ISO-8859-1?Q?e_schufa_kredit_aus_der_schweiz_autofinanzierung_ohne_schufa?= =?ISO-8859-1?Q?_kreditkarten_ohne_schufa_guenstiger_kredit_kredit_online_zu?= =?ISO-8859-1?Q?sage_kredite_arbeitslose__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTIGE_KREDITE_ONLI?= =?ISO-8859-1?Q?NE_=2B=2B=2B_KREDITE_IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_=2B_http=3A=2F=2FWWW=2EKR?= =?ISO-8859-1?Q?EDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_h?= =?ISO-8859-1?Q?ttp=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE?= =?ISO-8859-1?Q?=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKR?= =?ISO-8859-1?Q?EDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_h?= =?ISO-8859-1?Q?ttp=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE?= =?ISO-8859-1?Q?=2D244=2EINFO=2F_=2B_=2B_=2B_=2B_______________________kredite_arbeitslose?= =?ISO-8859-1?Q?_kredit_ohne_schufa_fuer_arbeitslose_in_Bad_Schwalbach_kredi?= =?ISO-8859-1?Q?te_finanzierung_eilkredit_in_Bad_Toelz_guenstiger_kredit_onl?= =?ISO-8859-1?Q?ine_kredite_privat_in_Stadthagen_kredit_ohne_schufa_ohne_vor?= =?ISO-8859-1?Q?kosten_online_kredite_guenstig_in_Borken_sofortkredit_schufa?= =?ISO-8859-1?Q?frei_kredit_online_beantragen_in_Bad_kredit_ohne_schufa_fuer?= =?ISO-8859-1?Q?_arbeitslose_schufafreier_kredit_in_Bernkastel_online_sofort?= =?ISO-8859-1?Q?_kredite_www_kredit_ohne_schufa_in_Meppen_kredite_fuer_arbei?= =?ISO-8859-1?Q?tslose_ohne_schufa_online_kredit_test_in_G=FCnzburg_sofort_kr?= =?ISO-8859-1?Q?edite_online_billig_kredite_in_Werdau_arbeitslos_kredite_fin?= =?ISO-8859-1?Q?anzierungen_online_in_Bad_Windsheim_kredit_ohne_schufa_in_kr?= =?ISO-8859-1?Q?edit_arbeitslos_in_Sigmaringen_kredite_online_vergleich_bank?= =?ISO-8859-1?Q?en_kredit_in_Kleve_guenstiger_kredit_ohne_schufa_eil_kredit_?= =?ISO-8859-1?Q?ohne_schufa_in_Pr=FCm_guenstige_kredite_ohne_schufa_online_kr?= =?ISO-8859-1?Q?edit_trotz_schufa_in_Traunstein_kredit_arbeitslose_bonitaet_?= =?ISO-8859-1?Q?online_in_Kronach_online_kredit_forum_auch_ohne_schufa_in_Gi?= =?ISO-8859-1?Q?e=DFen_kredite_ohne_schufa_auch_fuer_arbeitslose_kredite_ohne?= =?ISO-8859-1?Q?_schufa_auskunft_in_Miesbach____=2D_online_sofort_kredit_ohne_?= =?ISO-8859-1?Q?schufa_billig_kredit_in_Barnim_=2D_kredite_schufa_www_kredit_o?= =?ISO-8859-1?Q?hne_schufa_in_Erding_=2D_sofortkredit_online_sofortkredit_ohne?= =?ISO-8859-1?Q?_schufa_in_Verden_=2D_beamtenkredite_clp_kredit_in_Rendsburg_=2D?= =?ISO-8859-1?Q?_kreditkarte_online_kredite_online_ohne_schufa_in_Ulm_=2D_onli?= =?ISO-8859-1?Q?ne_sofort_kredit_ohne_credit_ohne_schufa_in_Aue_=2D_postbank_k?= =?ISO-8859-1?Q?redit_online_ohne_kredit_in_Dachau_=2D_kredit_trotz_negativer_?= =?ISO-8859-1?Q?schufa_kredit_arbeitslose_in_Wesel_=2D_guenstige_online_kredit?= =?ISO-8859-1?Q?_online_kredite_mit_sofortzusage_in_Saarlouis_=2D_raten_kredit?= =?ISO-8859-1?Q?_ratenkredit_ohne_schufa_in_Coburg_=2D_privat_kredit_ohne_schu?= =?ISO-8859-1?Q?fa_kredit_girokonto_in_Hoexter_=2D_kredit_von_privat_online_kr?= =?ISO-8859-1?Q?edite_in_in_Neunkirchen_=2D_mit_krediten_ohne_schufa_dispo_kre?= =?ISO-8859-1?Q?dit_in_Arnstadt_=2D_online_credit_ohne_schufa_kredit_sofort_in?= =?ISO-8859-1?Q?_Hanau?= Message-ID: <7926b4af-cce9-4d7f-b1d1-9d4f4fb886ac@v13g2000pro.googlegroups.com> online credit ohne in Landau sofortkredit kredit online vergleich beamtendarlehen ohne schufa handy ohne schufa kredite ohne schufaauskunft kredit vergleich geld kredit ohne schufa kredit aus der schweiz autofinanzierung ohne schufa kreditkarten ohne schufa guenstiger kredit kredit online zusage kredite arbeitslose + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + kredite arbeitslose kredit ohne schufa fuer arbeitslose in Bad Schwalbach kredite finanzierung eilkredit in Bad Toelz guenstiger kredit online kredite privat in Stadthagen kredit ohne schufa ohne vorkosten online kredite guenstig in Borken sofortkredit schufafrei kredit online beantragen in Bad kredit ohne schufa fuer arbeitslose schufafreier kredit in Bernkastel online sofort kredite www kredit ohne schufa in Meppen kredite fuer arbeitslose ohne schufa online kredit test in G?nzburg sofort kredite online billig kredite in Werdau arbeitslos kredite finanzierungen online in Bad Windsheim kredit ohne schufa in kredit arbeitslos in Sigmaringen kredite online vergleich banken kredit in Kleve guenstiger kredit ohne schufa eil kredit ohne schufa in Pr?m guenstige kredite ohne schufa online kredit trotz schufa in Traunstein kredit arbeitslose bonitaet online in Kronach online kredit forum auch ohne schufa in Gie?en kredite ohne schufa auch fuer arbeitslose kredite ohne schufa auskunft in Miesbach - online sofort kredit ohne schufa billig kredit in Barnim - kredite schufa www kredit ohne schufa in Erding - sofortkredit online sofortkredit ohne schufa in Verden - beamtenkredite clp kredit in Rendsburg - kreditkarte online kredite online ohne schufa in Ulm - online sofort kredit ohne credit ohne schufa in Aue - postbank kredit online ohne kredit in Dachau - kredit trotz negativer schufa kredit arbeitslose in Wesel - guenstige online kredit online kredite mit sofortzusage in Saarlouis - raten kredit ratenkredit ohne schufa in Coburg - privat kredit ohne schufa kredit girokonto in Hoexter - kredit von privat online kredite in in Neunkirchen - mit krediten ohne schufa dispo kredit in Arnstadt - online credit ohne schufa kredit sofort in Hanau From fredrik at pythonware.com Sat Sep 27 08:58:19 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Sep 2008 14:58:19 +0200 Subject: Regular expression help: unable to search ' # ' character in the file In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > import re > > fd = open(file, 'r') > line = fd.readline > pat1 = re.compile("\#*") > while(line): > mat1 = pat1.search(line) > if mat1: > print line > line = fd.readline() I strongly doubt that this is the code you used. > But the above prints the whole file instead of the hash lines only. "*" means zero or more matches. all lines is a file contain zero or more # characters. but using a RE is overkill in this case, of course. to check for a character or substring, use the "in" operator: for line in open(file): if "#" in line: print line From tmohr at s.netic.de Tue Sep 16 15:21:18 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Sep 2008 21:21:18 +0200 Subject: new style classes, __new__, __init__ References: Message-ID: Hello, > This way __new__ is not called, if i remove __init__ then > there are too many parameters to __new__, if i add a parameter > to __new__ then it says that __new__ does not take arguments. I just found an article that describes it better, this example works: class C2(object): def __new__(cls, a): obj = object.__new__(cls) print "new called" obj.a = 8 return obj __new__ = staticmethod(__new__) def __init__(self, a): print "init called" self.a = a def fct(self): print self.a a = C2(7) a.fct() Best regards, Torsten. From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 07:00:35 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 13:00:35 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: References: Message-ID: <48dcc0ce$0$25400$426a34cc@news.free.fr> bcurtu a ?crit : > Hi, > > I have a BIIIIIG problem with the next query: > > cursor.execute(""" > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """,( eid_list)) > > eid_list is suppossed to be a list of ids = [1,5,9] > > How can I make it work? You have to build your sql statement in three stages: # stage 0: the template sql_template = """ SELECT titem.object_id, titem.tag_id FROM tagging_taggeditem titem WHERE titem.object_id IN (%s) """ # stage 1: build correct place_holders string for the actual number # of items in eid_list place_holders = ", " .join("%s" for x in xrange(len(eid_list))) # stage 2 : build the effective sql statement sql = sql_template % place_holders # ok, let's go: cursor.execute(sql_template, eid_list) NB : you can of course make it in a single statement, but readability will suffer: cursor.execute( """ SELECT titem.object_id, titem.tag_id FROM tagging_taggeditem titem WHERE titem.object_id IN (%s) """ % ", " .join("%s" for x in xrange(len(eid_list))), eid_list ) HTH From sjmachin at lexicon.net Sat Sep 6 18:25:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 15:25:19 -0700 (PDT) Subject: modules path References: Message-ID: On Sep 7, 8:03?am, Python wrote: > Hi there, > > I moved a few modules into the modules folder (on OSX: /opt/local/lib/ > python2.5/site-packages/). > They don't show up though when I start IDLE... > > Is there a way to reload the modules folders in sys.path without ? > logging out and back in? > I know nothing about OS X, but no "reload" step should be necessary. Each Python process, whether run from IDLE or some other tool or from the shell, will form its own idea of sys.path. So: What modules? What type of file (.py, .pyc, .egg, .zip, .so) are you talking about? Did their documentation say that moving the files into site-packages was all the installation that was needed? What does "don't show up when I start IDLE" mean? When you start IDLE and do import sys, pprint pprint.pprint(sys.path) do you see the site-packages directory containing the module files? What happens when you do import amodule # substitute correct module name here ? Repeat the above two steps for each of (1) running Python from the shell (2) running Python from the shell with the -v option HTH, John From simon.palmer at gmail.com Wed Sep 3 17:00:36 2008 From: simon.palmer at gmail.com (SimonPalmer) Date: Wed, 3 Sep 2008 14:00:36 -0700 (PDT) Subject: Python on the web - newby question Message-ID: <6822d749-cc00-48ce-a30a-ded96a938e79@b30g2000prf.googlegroups.com> Apologies in advance if this is either a) the wrong board or b) been answered a million times elsewhere, but... I have been given an assignment to get a python module up and running behind an existing web site. At the moment the rest of the site is developed in PHP but the hosts have said they will provide python support for free, although they haven't given any more details than that, so I'm not sure exactly what that means. All reasonably encouraging though. I'm a newbie to python but quite experienced with Java/J2EE/JBoss. What I need to know is how I get python running on the server and what tools/middleware I would need to have installed on the host's machines to be able to support my python modules. Again, apologies if this is the wrong place but I'm a bit lost and would really appreciate some pointers. TIA Simon From daniel.jeem at gmail.com Mon Sep 1 10:28:42 2008 From: daniel.jeem at gmail.com (daniel jeem) Date: Mon, 1 Sep 2008 14:28:42 +0000 Subject: help to use "zc.sourcerelease " Message-ID: <984d3d830809010728y6bd240cfudcb9bf19e2366c35@mail.gmail.com> Hello every body, I want to use "zc.sourcerelease " for creating pakage. But I'm blocked because I have'nt understand how to use it. Then if you have some link or tutorial, share it for me. Help please. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Wed Sep 3 09:41:27 2008 From: roy at panix.com (Roy Smith) Date: Wed, 03 Sep 2008 09:41:27 -0400 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> <7f2d4b4a-bc97-4b46-a31e-63f98e9fee73@34g2000hsh.googlegroups.com> Message-ID: In article <7f2d4b4a-bc97-4b46-a31e-63f98e9fee73 at 34g2000hsh.googlegroups.com>, bearophileHUGS at lycos.com wrote: > Roy Smith: > > No reason to limit how many splits get done if you're > > explicitly going to slice the first two. > > You are probably right for this problem, because most lines are 2 > items long, but in scripts that have to process lines potentially > composed of many parts, setting a max number of parts speeds up your > script and reduces memory used, because you have less parts at the > end. > > Bye, > bearophile Sounds like premature optimization to me. Make it work and be easy to understand first. Then worry about how fast it is. But, along those lines, I've often thought that split() needed a way to not just limit the number of splits, but to also throw away the extra stuff. Getting the first N fields of a string is something I've done often enough that refactoring the slicing operation right into the split() code seems worthwhile. And, it would be even faster :-) From tino at wildenhain.de Mon Sep 15 16:44:29 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 15 Sep 2008 22:44:29 +0200 Subject: append on lists In-Reply-To: References: Message-ID: <48CEC92D.9010302@wildenhain.de> Armin wrote: ... >> >> Because .append() mutates 'a' and appends the item in-place rather >> than creating and returning a new list with the item appended, and >> it's good Python style for mutating methods to have no return value >> (since all functions must have some return value, Python uses None >> when the function doesn't explicitly return anything). > > Yes, but this is very unconvenient. > If d should reference the list a extended with a single list element > you need at least two lines > > a.append(7) > d=a > > and not more intuitive d = a.append(7) Nope. Why wouln'd you just use a instead of d? And if you want a not to be modified in place, just write: d=a+[7] T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From bearophileHUGS at lycos.com Wed Sep 3 21:27:05 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 18:27:05 -0700 (PDT) Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: Alexander Schmolck: > It also reads well, unlike the underscore > which is visually obstrusive and ugly (compare 123'456'890 to 123_456_789). I like that enough, in my language that symbol is indeed the standard one to separate thousands, in large numbers. It's light, looks natural, and as you say it's visually unobstrusive. But in my language ' means just thousands, so it's used only in blocks of 3 digits, not in blocks of any length, so something like this looks a bit strange/wrong: 0b'0000'0000 While the underscore has no meaning, so it can be used in both situations. A problem is that '1234' in Python is a string, so using ' in numbers looks a bit dangerous to me (and my editor will color those numbers as alternated strings, I think). Note that for other people the ' denotes feet, while in my language it denotes minutes, while I think the underscore has no meaning. So for me the underscore is better :-) Bye, bearophile From fredrik at pythonware.com Sat Sep 20 04:11:19 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 10:11:19 +0200 Subject: report a BUG of package setuptools-0.6c8. In-Reply-To: References: Message-ID: ???? wrote: > File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", > line 98, in entries_finder > log.warn("unrecognized .svn/entries format in %s", dirname) > NameError: global name 'log' is not defined > > global name 'log' is not defined to the line 98!!! please report bugs here: http://bugs.python.org/ From electronixtar at gmail.com Sun Sep 28 04:35:11 2008 From: electronixtar at gmail.com (est) Date: Sun, 28 Sep 2008 01:35:11 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> > Because that's how ASCII is defined. > Because that's how ASCII is defined. ASCII is a 7-bit code. Then why can't python use another default encoding internally range(256)? > Python refuses to guess and tries the lowest common denominator -- ASCII -- instead. That's the problem. ASCII is INCOMPLETE! If Python choose another default encoding which handles range(256), 80% of python unicode encoding problems are gone. It's not HARD to process unicode, it's just python & python community refuse to correct it. > stop dreaming of a magic solution It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, what's wrong???? > Isn't that more or less the same as telling the OP to use unicode() instead of str()? sockets could handle str() only. If you throw unicode objects to a socket, it will automatically call str() and cause an error. From luke.hamilton at xenter.com.au Wed Sep 10 08:08:25 2008 From: luke.hamilton at xenter.com.au (Luke Hamilton) Date: Wed, 10 Sep 2008 22:08:25 +1000 Subject: Web shopping carts In-Reply-To: <48C7B508.6070006@wildenhain.de> Message-ID: Thanks... Do you happen to have anymore details? > From: Tino Wildenhain > Date: Wed, 10 Sep 2008 06:52:40 -0500 > To: Luke Hamilton > Cc: "python-list at python.org" > Subject: Re: Web shopping carts > > Luke Hamilton wrote: >> Hey People, >> >> I am wondering if there are any OS shopping cart application written in >> python? >> > > Yes there are. > > HTH > Tino From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 12:51:13 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 18:51:13 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: <48cbf09c$0$25189$426a74cc@news.free.fr> <48cbf432$0$27507$426a34cc@news.free.fr> Message-ID: <48cc0b6f$0$11218$426a34cc@news.free.fr> Larry Bates a ?crit : > Bruno Desthuilliers wrote: >> Bruno Desthuilliers a ?crit : >>> Larry Bates a ?crit : >>> (snip) >>>> IMHO it reads better if you use the __call__ method of the class to >>>> return the value >>> >>> IMHO, it makes no sense at all to abuse the __call__ magic method here. >> >> Sorry - after a more careful re-read of other posts in the thread, it >> might make sense, given the use case : >> >> condition = FolderInUse(core) >> if condition.true_for(folder): >> # code here >> >> >> but then, a plain function (or a partial) might be even better - that >> is, if the FolderInUse class doesn't have other responsabilities. >> >> > > Sorry but I respectfully disagree that this is "abuse" of the __call__ > method. As long as we respectfully agree to disagree... !-) From timr at probo.com Thu Sep 25 04:03:02 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Sep 2008 08:03:02 GMT Subject: How to parse a string completely into a list References: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> Message-ID: john.ford at colorado.edu wrote: > >The string draws a map that I then want to be able to traverse >through. If I can count through the individual characters of a list I >can create an x-y coordinate plane for navigation. Well, the point Matt was making is that traversing through a list and traversing through a string are the same. # Given this: s = 'abcde' l = ['a','b','c','d','e'] # These are identical: for ch in s: pass for ch in l: pass # And these are identical: print s[3] print l[3] Slicing is identical. Subsetting is identical. The only difference is that I can change an element of the list. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From google at mrabarnett.plus.com Sat Sep 27 08:42:40 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 27 Sep 2008 05:42:40 -0700 (PDT) Subject: Build-in 'repr' function (was: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])?) References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> <87abduuvlz.fsf@benfinney.id.au> Message-ID: On Sep 27, 4:16?am, Ben Finney wrote: > process writes: > > ' '.join([`x * x` for x in range(1, 6)]) > > > exactly what does this symbol do and what does it stand for? > > It's an obsolete, deprecated syntactic sugar for (what is now > implemented as) the built-in 'repr' function. > > Instead, write the above as: > > ? ? ' '.join([repr(x * x) for x in range(1, 6)]) > I'd classify it as one of Guido's mistakes! :-) From gstaniak at wp.pl Wed Sep 10 10:52:07 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Wed, 10 Sep 2008 14:52:07 +0000 (UTC) Subject: PHP's str_replace ? References: Message-ID: On 10.09.2008, Anjanesh Lekshminarayanan wroted: > In PHP, if I do > str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) > it'll replace all vowels with a hyphen in string $str. > > Is there some equivalent in Python ? The .translate() method of strings? >>> import string >>> mystr = "This is just a test" >>> transtable = string.maketrans("aeiouy","------") >>> mystr.translate(transtable) 'Th-s -s j-st - t-st' GS -- Grzegorz Staniak Nocturnal Infiltration and Accurate Killing From JesseAldridge at gmail.com Mon Sep 1 16:30:17 2008 From: JesseAldridge at gmail.com (Jesse Aldridge) Date: Mon, 1 Sep 2008 13:30:17 -0700 (PDT) Subject: Put the output from all my programs in one place Message-ID: <3110346f-ed2b-458d-bbf8-af7e594f6509@e53g2000hsa.googlegroups.com> I want to put all the output from all of my python programs in one place. I've been trying to get this working for the last few days, but there are lots of annoying little details that are making the process quite difficult. I'm wondering if anyone can help me get this working. Currently I have one program called Output_Displayer.py This is a wxPython app that uses the aui tabbed interface. Basically it's just a frame with tabs where each tab contains one multi-line text control which displays the stdout and stderr messages for one program. I make one tab for each running program. I may change the way the interface works in the future, but the basic idea is just that it displays the stdout and stderr messages for all my programs. One thing I've tried is creating an output function to replace the print statement. This new function writes to a file. I made it so that Output_Displayer polls for this file, reads it if it exists, displays it's contents, and then deletes it. This works for standard output, but of course this doesn't work for stderr messages. Another thing I've tried is redirecting stdout and stderr to files and having Output_Displayer read those files. But I want the output to displayed "live" -- streaming, rather than waiting for the program to finish running. I think I'm having issues with input blocking while trying to read from these files when redirecting the streams. It seems I can't read the files until the program finishes running? In that case, I have another problem of determining whether or not the program has finished running. How can I detect this? I don't think I want to use subprocess for this, although I'm willing to if I can't get it working without it. I would prefer to have Output_Displayer be completely independent from my other programs rather than running them as children or something. Anyway, I've tried a bunch of different things and am more or less drowning in technical details. Has anyone done something like this before? I'd appreciate any help I can get. From skip at pobox.com Wed Sep 17 13:58:05 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Sep 2008 12:58:05 -0500 Subject: locks In-Reply-To: <48D140FC.8070801@el.net> References: <48D140FC.8070801@el.net> Message-ID: <18641.17709.251764.767222@montanaro-dyndns-org.local> kalin> mailman has been locking one list out. the web interface just kalin> hangs and it generates a bunch of locks. it seems that it can not kalin> write to a log but not sure which one. errors are like: ... You'd probably be better off asking about Mailman problems on mailman-users at python.org. -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From sayananbig at gmail.com Tue Sep 23 14:32:20 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Tue, 23 Sep 2008 11:32:20 -0700 (PDT) Subject: python timers and COM/directshow References: Message-ID: On Sep 23, 4:24?am, Tim Golden wrote: > Sayanan Sivaraman wrote: > > So I've written a simple video player using directshow/COM in VC++, > > and I'm in the process of translating it to python. ?For example, when > > the avi starts playing, I have a call media_control.Run() , etc. > > > I'm wondering how I should go about updating my gtk.Hscale widget as a > > trackbar for the avi player. > > > In C++, I have the following callbacks that update the scrollbar and > > video position with a timer. > > [... snip callbacks ...] > > > > > I'm wondering how I would implement similar callbacks in Python for a > > gtk.Hscale, and some sort of time [I'm not familiar with Pythons > > timers/threading at all]. > > You'd help your cause a lot here if you posted *Python* > code to indicate what's calling what back where. Also if > you stated whether you were using, eg, the GTK toolkit which > your description suggests, or some other GUI toolkit. Because > they tend to vary as to how they arrange their callbacks. > > In geeneral, Python callbacks are trivial: you create the > function to do whatever and then pass the function as an > object into the calling-back function call. Something > like this (invented GUI toolkit): > > > def handle_lbutton_click (event): > ? # > ? # do stuff with lbutton click > ? # > > def handle_widget_slide (event): > ? # > ? # do stuff with widget slide > ? # > > handle_event ("lbutton_click", handle_lbutton_click) > widget.attach_event ("slide", handle_widget_slide) > > > > But the details will obviously depend on the toolkit you > use. > > TJG > TJG Sorry, you make a very good point. I am using gtk. I don't have a problem with callbacks for the gtk widgets. My question is about timers and their callbacks. The reason I used c++ code is that Microsoft's COM interface is natively in C++, and Python uses "import comtypes" to access this functionality and the dll's.[ie GetModule('quartz.dll')] Essentially what I would like to have [as evidenced by the c++ code] is something like the following: def timer_callback(args): while timer is active update scrollbar position based on video progress #here I am using microsoft's COM interface, so the function would be something like scrollbar.set_value(media_control.CurrentPosition) def scrollbar_callback : when the scrollbar is moved, update this video position #this I understand. It would be something like media_control.CurrentPosition= scrollbar.get_value() def pauser : media_control.Pause() *somehow kill timer* def player: media_control.Run() timer.run() #timer.run() would call timer_callback So I would like to know how to construct and implement a timer that would do the above, a la the first callback. In addition, the timer has to be able to be paused/killed if I pause the video, and implemented again if I play the video ie: Thanks, sayanan From joncle at googlemail.com Tue Sep 9 16:53:57 2008 From: joncle at googlemail.com (Jon Clements) Date: Tue, 9 Sep 2008 13:53:57 -0700 (PDT) Subject: noob help request - how to make a list of defined class? References: Message-ID: <5f169171-c368-43cd-a70f-1cb8797ee3eb@x35g2000hsb.googlegroups.com> On Sep 9, 3:11?pm, nuffno... at gmail.com wrote: > I have defined two classes with one common field (called code) and > several different fields. > In class A there is only one instance of any given code as all items > are individual. > In class B, there may be none, one or many instances of each code, as > there can be any number of Bs referring to a single A. > > I need to make a list of Bs, remove dupes, and then create a list of > As that have Bs. > > (I hope this makes sense!) > > with much research and reading of my book I managed to get this > working, ?but at one stage I had errors that talked about being unable > to concatenate type A. ?So I converted my As to string, and then did a > split on commas to make a list. ?This worked fine for all the As that > didn't have a comma in a field (about 85%) but I can't help feeling > that this is a kludge, and that if Icould find a way to get a proper > list of As instead of a list of lists created by converting to string > and splitting, then my app would work properly. > > So I am hoping some of the nice folk here will help me out. > > The relevent function looks like this: > > def gen_B_A_list(): > ? ? Bcodes = get_codes() > ? ? all_As = read_A("A.csv") > ? ? B_A = [] > ? ? for i in range(len(codes)): > ? ? ? ? Bcode = Bcodes[i] > ? ? ? ? for A in all_As: > ? ? ? ? ? ? filename = getattr(A, 'code') > ? ? ? ? ? ? if filename == Bcode: > ? ? ? ? ? ? ? ? BA = str(A) > ? ? ? ? ? ? ? ? BA = string.split(BA, ',') > ? ? ? ? ? ? ? ? B_A.append(BA) > ? ? return B_A > > The element in question is after if filename == Bcode. ? How do I > construct a list of my defined class A objects here instead of this? > ( I can post the full code if needed, ?just thought it was better > netiquette not to) > > TIA > > nuffi Looks like homework, but as you've made some kind of effort, some hints to where to refer to in the manual. 1) Use the csv module for reading CSV files 2) A dict maps one value to another... (check it out) 3) Don't use getattr, use member access (the . symbol, eg: A.code) 4) The for statement can loop over each item in term without an explicit range (eg, for bcode in codes...) 5) Read the help for str, and read up on how to create objects, for instance str(A) returns A's string representation, while A() creates a new A object... Work your way through a python tutorial and make sure you understand the examples and principals... It might take you a while though, so I hope the assignment's not due soon! Jon. From m_palmer45 at yahoo.ca Tue Sep 23 10:08:07 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 23 Sep 2008 07:08:07 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> Message-ID: > > This seems to break the rule that if A is equal to B and B is equal to C > > then A is equal to C. > > I don't see why transitivity should apply to Python objects in general. Well, for numbers it surely would be a nice touch, wouldn't it. May be the reason for Decimal to accept float arguments is that irrational numbers or very long rational numbers cannot be converted to a Decimal without rounding error, and Decimal doesn't want any part of it. Seems pointless to me, though. From paul at boddie.org.uk Mon Sep 8 09:27:35 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 8 Sep 2008 06:27:35 -0700 (PDT) Subject: tracking collection modification References: <42d9688f-1058-4ed7-8d9d-affd432fdb41@s1g2000pra.googlegroups.com> Message-ID: On 7 Sep, 12:54, usenet.tolo... at gmail.com wrote: > I'm working on a remote object system, something kinda like Pyro. > For the purposes of caching I need to be able to tell if a given > dict / list / set has been modified. > Ideally what I'd like is for them to have a modification count > variable that increments every time the particular collection is > modified. Unfortunately I can't find anything like that and since this > needs to work for the regular normal list / dict / set objects > subclassing them to add the modification count isn't useful. What you appear to need here is some kind of proxying solution - a layer which records accesses to the objects, distinct from the objects themselves. I believe that the PyPy project provides something of this nature: http://codespeak.net/pypy/dist/pypy/doc/objspace-proxies.html Paul From edreamleo at charter.net Tue Sep 2 10:02:37 2008 From: edreamleo at charter.net (Edward K Ream) Date: Tue, 2 Sep 2008 09:02:37 -0500 Subject: Leo 4.5 final released Message-ID: Leo 4.5 final is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.5: -------------------------- - Full support for @shadow files in Leo's core. - Major improvements to Leo's key binding code. - The beginning of usable vim-like bindings. - uA's may now be associated with vnodes in @thin and @shadow files. - Several magor reorganizations of Leo's code: including sax-based parsing, support for the Graph world (unified nodes), and simplified drawing code. - Leo is now an installable package. - Prepared code to be ready for Python 3.0. - Many small improvements and bug fixes. Quote of the month: ------------------- Squeak and Leo have been two of the most significant technologies to redefine my personal computer experience and the ideas behind computing. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From steve at holdenweb.com Fri Sep 19 03:25:41 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Sep 2008 03:25:41 -0400 Subject: Extracting hte font name from a TrueType font file In-Reply-To: References: Message-ID: Aaron "Castironpi" Brady wrote: > On Sep 18, 7:48 pm, Steve Holden wrote: >> Fredrik Lundh wrote: >>> Steve Holden wrote: >>>> Does anyone have a Python recipe for this? >>>>>> from PIL import ImageFont >>>>>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1) >>>>>> f.font.family >>> 'Verdana' >>>>>> f.font.style >>> 'Italic' >> Thanks so much, Fredrik. The reason I asked is because I found the >> specification completely opaque ... >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC http://www.holdenweb.com/ > > Here's the code to parse the spec. > > #customize path > f= open( '\\windows\\fonts\\arial.ttf', 'rb' ) > from struct import * > > #header > shead= Struct( '>IHHHH' ) > fhead= f.read( shead.size ) > dhead= shead.unpack_from( fhead, 0 ) > > #font directory > stable= Struct( '>4sIII' ) > ftable= f.read( stable.size* dhead[ 1 ] ) > for i in range( dhead[1] ): #directory records > dtable= stable.unpack_from( > ftable, i* stable.size ) > if dtable[0]== 'name': break > assert dtable[0]== 'name' > > #name table > f.seek( dtable[2] ) #at offset > fnametable= f.read( dtable[3] ) #length > snamehead= Struct( '>HHH' ) #name table head > dnamehead= snamehead.unpack_from( fnametable, 0 ) > > sname= Struct( '>HHHHHH' ) > for i in range( dnamehead[1] ): #name table records > dname= sname.unpack_from( > fnametable, snamehead.size+ i* sname.size ) > if dname[3]== 4: #key == 4: "full name of font" > s= unpack_from( > '%is'% dname[4], fnametable, > dnamehead[2]+ dname[5] )[0] > print dname, s > > This outputs: > > (0, 3, 0, 4, 10, 318) A r i a l > (1, 0, 0, 4, 5, 4081) Arial > (3, 1, 1033, 4, 10, 318) A r i a l > > First 3 fields: > > 0, 3, 0= Unicode, Unicode 2.0, English > 1, 0, 0= Macintosh, Default, English > 3, 1, 1033= Windows, Version 1.1, Language "1033" Well you clearly understood it better than *I* did! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From deets at nospam.web.de Wed Sep 3 09:56:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 15:56:09 +0200 Subject: installing matplotlib with numpy and scipy for Python in Cygwin In-Reply-To: <4241157d-6cdb-4edc-bb22-bceeb68b870f@m73g2000hsh.googlegroups.com> References: <4241157d-6cdb-4edc-bb22-bceeb68b870f@m73g2000hsh.googlegroups.com> Message-ID: <6i7jbrFov1rqU1@mid.uni-berlin.de> Anish Chapagain schrieb: > On Sep 3, 12:39 pm, Uwe Schmitt > wrote: >> On 3 Sep., 11:42, "chapagainanish" wrote: >> >>> Hi!! >>> I'm having installation problem for installing numpy and scipy in >>> Cygwin for Python, and am obstruct in madway for project, i followed >>> scipy.org guidelines but there's few error thrown as >>> failed..with exit status 1 >>> please if someone has installed these module help me >>> thank's and regard's >>> Anish >> http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html >> may help you. >> >> Do you really want a cygwin based installation ? >> You could download enthoughts python edition which >> includes lots of math stuff. >> >> Greetings, Uwe > > Hi, > thank's i'm looking through the link cens.ioc.ee > and am in need of using matplotlib and to run few system call, so i > installed cygwin baically for system call in linux/unix and matplotlib > for GUI(graph,chart) but matplotlib is not getting installed in > cygwin.. What are "system calls"? You *have* windows, so in the end you can do everything with "normal" python. And I presume that your codebase is by far smaller that matplotlibs, so adapting your source is easier than theirs. Diez From bdesth.quelquechose at free.quelquepart.fr Fri Sep 5 15:16:36 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 Sep 2008 21:16:36 +0200 Subject: use str as variable name In-Reply-To: References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> Message-ID: <48c1a184$0$17080$426a74cc@news.free.fr> Marco Bizzarri a ?crit : > On Thu, Sep 4, 2008 at 10:47 AM, Fredrik Lundh wrote: > >> (...as Bruno implies, setattr(), len() et al can be and should be viewed as >> generic functions. > > Just a question: "generic functions" are not meant in the sense of > "generic functions" of CLOS, am I right? Nope. Just "generic" in the sense that they accept any object implementing a very minimal interface. If you want something like CLOS multimethods, you may be interested in Philip Eby's ruledispatch. From uzmanajmal at gmail.com Wed Sep 17 07:06:19 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Wed, 17 Sep 2008 11:06:19 +0000 Subject: File Reading related query In-Reply-To: <48D0DFD8.4000309@tim.thechases.com> References: <48D0DFD8.4000309@tim.thechases.com> Message-ID: Thanks Tim. That rstrip('\r\n') worked. :) On Wed, Sep 17, 2008 at 10:45 AM, Tim Chase wrote: > Is there any function for reading a file while ignoring *\n* occuring in >>> the file? >>> >> >> can you be a bit more precise? are we talking about text files or binary >> files? how do you want to treat any newlines that actually appear in the >> file? >> > > I believe the OP is referencing this behavior: > > for line in file('x.txt'): > assert not ( > line.endswith('\r') or > line.endswith('\n')), "Don't want this" > else: > yay() # we never end up reaching this > > which can be done with a simple generator/wrapper: > > def unnewline(iterator): > for line in iterator: > yield line.rstrip('\r\n') > for line in unnewline(file('x.txt')): > assert not ( > line.endswith('\r') or > line.endswith('\n')), "Don't want this" > else: > yay() # we get here this time > > Alternatively, the content can just be modified on the fly: > > for line in file('x.txt'): > line = line.rstrip('\r\n') > ... > > yes, the interpretation would differ if it were a binary file, but the > above interpretation is a pretty common case (i.e. I encounter it daily, in > my processing of client data-feeds). > > -tkc > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From grflanagan at gmail.com Mon Sep 29 17:12:19 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Mon, 29 Sep 2008 23:12:19 +0200 Subject: Finding subsets for a robust regression In-Reply-To: References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> Message-ID: Gerard flanagan wrote: > tkpmep at hotmail.com wrote: > >> >> x1 = [] #unique instances of x and y >> y1 = [] #median(y) for each unique value of x >> for xx,yy in d.iteritems(): >> x1.append(xx) >> l = len(yy) >> if l == 1: >> y1.append(yy[0]) >> else: >> yy.sort() >> y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else >> yy[l//2] ) >> -- > > Not tested, but is this equivalent? > > x1 = [] > y1 = [] > for xx, yy in d.iteritems(): > L = len(yy) // 2 > yy.sort() > y1.append(yy[L]) > if not L & 1: > y1[-1] = (y1[-1] + yy[L-1]) / 2.0 > > It means that you have a pointless 'sort' when len(yy) == 1, but then > you save an 'if' per-iteration. > > G. > > -- Maybe that should be: if L and not L & 1: ... anyway... From ahmad.humyn at gmail.com Fri Sep 5 04:22:54 2008 From: ahmad.humyn at gmail.com (Ahmad Humayun) Date: Fri, 5 Sep 2008 01:22:54 -0700 (PDT) Subject: atomic section in code Message-ID: Hi there, I need to create an atomic section in Python code i.e. there is no context switch to any other thread during the running of that piece of code. Would would do the trick? thanks, From frank at chagford.com Sat Sep 20 01:59:55 2008 From: frank at chagford.com (Frank Millman) Date: Fri, 19 Sep 2008 22:59:55 -0700 (PDT) Subject: XML-schema 'best practice' question References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: On Sep 18, 8:28?am, Frank Millman wrote: > Hi all > > This is not strictly a Python question, but as I am writing in Python, > and as I know there are some XML gurus on this list, I hope it is > appropriate here. > > XML-schemas are used to define the structure of an xml document, and > to validate that a particular document conforms to the schema. They > can also be used to transform the document, by filling in missing > attributes with default values. > [..] > > Or maybe the best practice is to *always* validate a document before > processing it. > I have realised that my question was irrelevant. xml's raison d'etre is to facilitate the exchange of information between separate entities. If I want to use xml as a method of serialisation within my own system, I can do what I like, but there can be no question of 'best practice' in this situation. When xml is used as intended, and you want to process a document received from a third party, there is no doubt that you should always validate it first before processing it. Thank you, Lorenzo, for pointing out the obvious. It may take me a while to catch up, but at least I can see things a little more clearly now. As to why I am using xml at all, I know that there is a serious side to Skip's light-hearted comment, so I will try to explain. I want to introduce an element of workflow management (aka Business Process Management) into the business/accounting system I am developing. I used google to try to find out what the current state of the art is. After several months of very confusing research, this is the present situation, as best as I can figure it out. There is an OMG spec called BPMN, for Business Process Modeling Notation. It provides a graphical notation, intended to be readily understandable by all business users, from business analysts, to technical developers, to those responsible for actually managing and monitoring the processes. Powerful though it is, it does not provide a standard method of serialsing the diagram, so there is no standard way of exchanging a diagram between different vendors, or of using it as input to a workflow engine. There is an OASIS spec called WS-BPEL, for Web Services Business Process Execution Language. It defines a language for specifying business process behavior based on Web Services. This does have a formal xml-based specification. However, it only covers processes invoked via web services - it does not cover workflow-type processes within an organisation. To try to fill this gap, a few vendors got together and submitted a draft specification called BPEL4People. This proposes a series of extensions to the WS-BPEL spec. It is still at the evaluation stage. The BPMN spec includes a section which attempts to provide a mapping between BPMN and BPEL, but the authors state that there are areas of incompatibility, so it is not a perfect mapping. Eventually I would like to make sense of all this, but for now I want to focus on BPMN, and ignore BPEL. I can use wxPython to design a BPMN diagram, but I have to invent my own method of serialising it so that I can use it to drive the business process. For good or ill, I decided to use xml, as it seems to offer the best chance of keeping up with the various specifications as they evolve. I don't know if this is of any interest to anyone, but it was therapeutic for me to try to organise my thoughts and get them down on paper. I am not expecting any comments, but if anyone has any thoughts to toss in, I will read them with interest. Thanks Frank From prologic at shortcircuit.net.au Sun Sep 7 17:37:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 07:37:12 +1000 Subject: max(), sum(), next() In-Reply-To: <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: Can we stop this thread now? :) I think we've all seen what the intended behavior of sum(), max() and other similar functions. cheers James On Mon, Sep 8, 2008 at 3:30 AM, Mensanator wrote: > On Sep 6, 11:05?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote: >> >> [...] >> >> >> They could have decided that sum must take at least two arguments, >> >> because addition requires two arguments and it's meaningless to talk >> >> about adding a single number without talking about adding it to >> >> something else. But they didn't. >> >> > Ok. But the problem is they DID in SQL: x + Null = Null. >> >> Sheesh. That's not a problem, because Python is not trying to be a >> dialect of SQL. > > And yet, they added a Sqlite3 module. > >> >> If you want a NULL object, then there are recipes on the web that will >> give you one. Then all you need to do is call sum(alist or [NULL]) and it >> will give you the behaviour you want. > > Actualy, I already get the behaviour I want. sum([1,None]) > throws an exception. I don't see why sum([]) doesn't throw > an exception also (I understand that behaviour is by design, > I'm merely pointing out that the design doesn't cover every > situation). > >> >> [...] >> >> > Here's a real world example (no ivory tower stuff): >> >> > An oil refinery client has just excavated a big pile of dirt to lay a >> > new pipeline. >> [snip details] >> > Can't I just use a sum of 0 to tell me when data is missing? No, because >> > in some cases the reporting limit of undetected compounds is set to 0. >> >> You can't use a sum of 0 to indicate when data is missing, full stop. > > Exactly. That's why I would prefer sum([]) to raise an > exception instead of giving a false positive. > >> The >> data may require 15 tests when only 3 have actually been done: >> >> sum([1.2e-7, 9.34e-6, 2.06e-8]) > > Biggest problem here is that it is often unknown just > how many records you're supposed to get from the query, > so we can't tell that a count of 3 is supposed to be 15. > >> >> Missing data and a non-zero sum. How should sum() deal with that? > > That's a seperate issue and I'm not saying it should as > long as the list contains actual numbers to sum. > sum([1.2e-7, 9.34e-6, 2.06e-8, None]) will raise an > exception, as it should. But what types are contained > in []? > >> >> The answer is that sum() can't deal with that. You can't expect sum() to >> read your mind, know that there should be 15 items instead of 3, and >> raise an error. So why do you expect sum() to read your mind and >> magically know that zero items is an error, especially when for many >> applications it is NOT an error? > > For the simple reason it doesn't have to read your mind, > a mechanism has already been built into the function: start > value. For those situations where an empty list is desired > to sum to 0, you could use sum(alist,0) and use sum(alist) for > those cases where summing an empty list is meaningless. > Shouldn't you have to explicitly tell sum() how deal with > situations like empty lists rather than have it implicitly > assume a starting value of 0 when you didn't ask for it? > >> >> The behaviour you want for this specific application is unwanted, >> unnecessary and even undesirable for many other applications. The >> solution is for *you* to write application-specific code to do what your >> application needs, instead of relying on a general purpose function >> magically knowing what you want. > > Does division magically know what you want? No, it raises an > exception when you do something like divide by 0. Isn't it > Pythonic to not write a litany of tests to cover every > possible case, but instead use try:except? > > But try:except only works if the errors are recognized. > And sum() says that summing an empty list is NEVER an error > under ANY circumstance. That may be true in MOST cases, but > it certainly isn't true in ALL cases. > >> >> -- >> Steven > > -- > http://mail.python.org/mailman/listinfo/python-list -- -- -- "Problems are solved by method" From roseeea at gmail.com Thu Sep 25 00:02:31 2008 From: roseeea at gmail.com (ROSEEE) Date: Wed, 24 Sep 2008 21:02:31 -0700 (PDT) Subject: The Python computer language Message-ID: http://pythoncomputer.blogspot.com From Ron.Barak at lsi.com Tue Sep 16 03:07:52 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Sep 2008 08:07:52 +0100 Subject: Representation of python code ? In-Reply-To: References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6022A6B6B@enbmail01.lsi.com> Thanks for the pointer, Ebert. epydoc produces quite useful documentation (in a different format than what I had in mind, but useful nonetheless). Bye, Ron. -----Original Message----- From: Manuel Ebert [mailto:maebert at uos.de] Sent: Tuesday, September 16, 2008 03:03 To: Barak, Ron Cc: python-list at python.org Subject: Re: Representation of python code ? -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 AFAIK epydoc can generate pretty graphs with graphviz on the fly, such as class hierarchies or call graphs. On Sep 14, 2008, at 3:44 PM, Barak, Ron wrote: > Hi Guys, > Is there a script/application, which gets as input python code, and > produces a (graphic) representation of the inter-relationships between > its classes/functions ? > Bye, > Ron. > -- > http://mail.python.org/mailman/listinfo/python-list -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIzve8cZ70OCIgLecRAjRbAKCRXHRKDJN+oxoJQ7S7z8i6sVCNxQCggowS PVV6g/BRKesRGErGHcAcURE= =q9Hs -----END PGP SIGNATURE----- -------------- next part -------------- An HTML attachment was scrubbed... URL: From Afro.Systems at gmail.com Wed Sep 10 15:03:34 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Wed, 10 Sep 2008 12:03:34 -0700 (PDT) Subject: Simple UDP server References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> Message-ID: <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> On Sep 10, 9:55?pm, Fredrik Lundh wrote: > Tzury Bar Yochay wrote: > > Would the one below will be capable of holding 30 concurrent > > connections? > > UDP is a connectionless datagram protocol, so that question doesn't > really make much sense. > So what if it is connectionless. It would make sense if you get a load of users who sends large sets of binary data to each other. From kyosohma at gmail.com Fri Sep 26 09:45:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 26 Sep 2008 06:45:59 -0700 (PDT) Subject: how to search multiple textfiles ? References: Message-ID: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> On Sep 26, 8:35?am, Stef Mientki wrote: > hello, > > I want to search multiple textfiles (python source files) for a specific > word. > I can find all files, open them and do a search, > but I guess that will be rather slow. > > I couldn't find any relevant information through google. > > Does anyone know of a search library that performs this task fast ? > > If it indeed only concerns py-files, > is there another way of searching words ? > ( I could imagine that such a "py-only-search" would have benefits, > because you could set a flag to see the words in comment yes or no ) > > thanks, > Stef Mientki > > Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. > The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629. On Windows I use the free version of Bare Grep: http://www.baremetalsoft.com/baregrep/ No, it's not a Python solution, but it works for my needs. You should try using Python to search your script files and see if it really is too slow though. Mike From kf9150 at gmail.com Thu Sep 11 04:54:41 2008 From: kf9150 at gmail.com (Kelie) Date: Thu, 11 Sep 2008 01:54:41 -0700 (PDT) Subject: Use Python to solve equations? References: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Message-ID: Thank you James! Checking it out right now... From fredrik at pythonware.com Thu Sep 4 17:31:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 23:31:44 +0200 Subject: why is self not passed to id()? In-Reply-To: References: <200809042244.54418.maric@aristote.info> Message-ID: Robert Kern wrote: > Well, that's not entirely true. They need to be not mutated while they > are in the dictionary, certainly. At least not in ways that affect > equality testing. In this case, one would also have to override > list.__eq__ to also compare by identity, too. Then you could mutate the > lists to your heart's content and the dictionary wouldn't care. at which point you'd start wondering if it wouldn't be more efficient to wrap the list in a light-weight class, instead of using subclassing. From mal at egenix.com Thu Sep 4 06:15:16 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 04 Sep 2008 12:15:16 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> Message-ID: <48BFB534.2080508@egenix.com> On 2008-09-04 11:14, Kay Schluehr wrote: > On 4 Sep., 10:31, "M.-A. Lemburg" wrote: >> On 2008-09-04 07:49, Kay Schluehr wrote: >> >>> 3) Following the public rumor mill and the latest hype RIA i.e. the >>> merge of web- and desktop applications with systems like Adobe AIR, >>> JavaFX, Google Gears and MS Silverlight is the future of frontend >>> development. With the exception of IronPython and Silverlight, Python >>> hasn't even entered this game and no one knows if it ever will. >> Actually, it has already and quite some time ago: >> >> http://www.artima.com/weblogs/viewpost.jsp?thread=208528 >> >> The recipe is simple: use Python for the business logic, database >> interfacing, etc and have it talk to a Flex front-end via XML-RPC >> or REST. > > Python is still server-side in this scenario and plays no role in UI > definitions. That depends on how you design the application. It is well possible to have Python drive the GUI by sending the required details to the Flex front-end via XML (ie. data-driven GUIs). > So one doesn't get more than e.g. Django apps that > respond to HTTP requests triggered by JavaScript forms except that > JavaScript+HTML+Browser is replaced by Flex = AS3+MXML+FlashPlayer. You really can't compare the Flex stack to an AJAX stack. Flex has a lot more to offer for GUI programming than AJAX, it also doesn't suffer from the problems of AJAX having to support several different sets of browser or library bugs. We switched from an AJAX approach to a Flex-based approach last year and never even considered moving back again. > The role of Python is somewhat arbitrary. This could change only if > Python becomes a client side language executed by AVM, V8 etc. like > IronPython in Silverlight. > > About separating UI from application logics by assigning functionality > to different general purpose languages I have to admit that I don't > think it is such a great idea ... In my experience, Flex + Python gives you the best of both worlds, the nice GUI features of Flex and the efficiency of Python for the business logic. A long time ago, there was a Python plugin for Netscape which allowed you to run Python straight in the browser. Perhaps it's time to revive such an idea... but then you're still missing out on the GUI part, since you're still stuck with what the browser has to offer in terms of widget support. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From fredrik at pythonware.com Thu Sep 11 09:37:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 15:37:40 +0200 Subject: function return In-Reply-To: References: Message-ID: make that: > note that you put the "return" statement inside the loop, so returning > only one line is the expected behaviour. to fix this, you can append the result strings to the data_lis list inside the loop: > result = "%s\t%s\t%s" %(id,gene_symbol,ptms) > data_lis.append(result) > > and then return the list when done: > > > fh.close() > return data_lis > From steven at REMOVE.THIS.cybersource.com.au Wed Sep 17 23:35:52 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 03:35:52 GMT Subject: decorator and API References: Message-ID: On Thu, 18 Sep 2008 02:26:29 +0430, Lee Harr wrote: > I have a class with certain methods from which I want to select one at > random, with weighting. > > The way I have done it is this .... [snip] You are coupling the weights, the actions, and the object which chooses an action all in the one object. I find that harder to wrap my brain around than a more loosely coupled system. Make the chooser independent of the things being chosen: def choose_with_weighting(actions, weights=None): if weights is None: weights = [1]*len(actions) # equal weights # Taken virtually unchanged from your code. # I hope it does what you want it to do! assert len(weights) == len(actions) total = sum(weights) choice = random.randrange(total) while choice > weights[0]: choice -= weights[0] weights.pop(0) actions.pop(0) return actions[0] Loosely couple the actions from their weightings, so you can change them independently. Here's a decorator that populates a dictionary with weights and actions: def weight(value, storage): def set_weight(method): storage[method.__name__] = value return method return set_weight Here's how to use it: class A(object): weights = {} def __init__(self): self.weights = self.__class__.weights.copy() @weight(10, weights) def action_1(self): print "A.action_1" @weight(20, weights) def action_2(self): print "A.action_2" The class is now populated with a set of default weights, which is then copied to the instance. If you want to over-ride a particular weight, you don't need to make a subclass, you just change the instance: obj = A() obj.weights["action_1"] = 30 method = choose_with_weighting(obj.weights.keys(), obj.weights.values()) getattr(obj, method)() # call the method Hope this helps, -- Steven From mike at ipglobal.net Wed Sep 24 15:22:30 2008 From: mike at ipglobal.net (Support Desk) Date: Wed, 24 Sep 2008 14:22:30 -0500 Subject: More regex help In-Reply-To: <86k5d1qyw4.fsf@athena.daycos.com> References: <86k5d1qyw4.fsf@athena.daycos.com> Message-ID: <9CD4743616DF4F48A341A30FEA13C2D3@office.ipglobal.net> Kirk, That's exactly what I needed. Thx! -----Original Message----- From: Kirk Strauser [mailto:kirk at athena.daycos.com] Sent: Wednesday, September 24, 2008 11:42 AM To: python-list at python.org Subject: Re: More regex help At 2008-09-24T16:25:02Z, "Support Desk" writes: > I am working on a python webcrawler, that will extract all links from an > html page, and add them to a queue, The problem I am having is building > absolute links from relative links, as there are so many different types of > relative links. If I just append the relative links to the current url, some > websites will send it into a never-ending loop. >>> import urllib >>> urllib.basejoin('http://www.example.com/path/to/deep/page', '/foo') 'http://www.example.com/foo' >>> urllib.basejoin('http://www.example.com/path/to/deep/page', 'http://slashdot.org/foo') 'http://slashdot.org/foo' -- Kirk Strauser The Day Companies From patrickstinson.lists at gmail.com Mon Sep 8 22:17:57 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Mon, 8 Sep 2008 18:17:57 -0800 Subject: Incorrect compiler found building extension on windows Message-ID: <6214d7a20809081917n6a932f8gc9fd1a0bc44d1e9b@mail.gmail.com> I built python-2.5.1 from source using Visual Studio 2005, and am also trying to build my extension using distutils and Visual Studio 2005. Distutils complains about python being built with VS 2003, which is not on my system, and the only python binaries I have on my system are the ones I built from source using VS 2005. This leads me to believe that some other error is causing this hard-coded message to be printed. I am running python.exe from within the build dir, and "import site" works just fine. Running my setup.py --platform prints "UNKNOWN" for a list of platforms. Is it possible to build python using VS 2005 and also build extensions using the same cl.exe? If not is there a compiler config or something that I need to write? Thanks. From dudeja.rajat at gmail.com Sat Sep 27 08:29:34 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 27 Sep 2008 13:29:34 +0100 Subject: Regular expression help: unable to search ' # ' character in the file Message-ID: Hi, Can some help me with the regular expression. I'm looking to search # character in my file? My file has contents: ############################### Hello World ############################### length = 10 breadth = 20 height = 30 ############################### ############################### Hello World ############################### length = 20 breadth = 30 height = 40 ############################### I used the following search : import re fd = open(file, 'r') line = fd.readline pat1 = re.compile("\#*") while(line): mat1 = pat1.search(line) if mat1: print line line = fd.readline() But the above prints the whole file instead of the hash lines only. Please help Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.hildebrandt at gmail.com Wed Sep 10 13:43:31 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 10:43:31 -0700 (PDT) Subject: Reading binary data References: Message-ID: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> > signature, version, attr_count = struct.unpack('3cII', > yourfile.read(11)) > This line is giving me an error: Traceback (most recent call last): File "test.py", line 19, in signature, version, attr_count = struct.unpack('3cII', file.read(12)) ValueError: too many values to unpack From joefazee at gmail.com Wed Sep 17 08:26:06 2008 From: joefazee at gmail.com (A. Joseph) Date: Wed, 17 Sep 2008 05:26:06 -0700 Subject: recursive using the os.walk(path) from the os module Message-ID: Hi, I want to search through a directory and re-arrange all the files into e.g All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder. I`m thinking of doing something with the os.walk(path) method from os module, I need some ideal how the algorithm should look like, maybe recursive ..any deal? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Wed Sep 10 18:00:41 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 08:00:41 +1000 Subject: Simple UDP server In-Reply-To: References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> Message-ID: Tzury, You may consider using pymills to simplify writing your UDP server and just concentrating on the behavior of the system. You can get a copy of the latest development branch by cloning it with Mercurial: hg clone http://hg.shortcircuit.net.au/pymills/ There is an example UDP Server in examples/net/ but I'll paste it here for your reference. Note, as stated before, UDP is a connectionless protocol (Datagram), concurrency doesn't apply. Also note, technically UDP doesn't guarantee reliability or the order of packets, however the reality is, it doesn't give you any feedback. You have to handle this yourself. Have fun, cheers James #!/usr/bin/env python # -*- coding: utf-8 -*- # vim: set sw=3 sts=3 ts=3 from pymills import event from pymills.event import * from pymills.net.sockets import UDPServer class EchoServer(UDPServer): @listener("connect") def onCONNECT(self, sock, host, port): print "New connection: %s:%d" % (host, port) @listener("disconnect") def onDISCONNECT(self, sock): print "Disconnection: %s" % sock @listener("read") def onREAD(self, sock, line): line = line.strip() print "%s: %s" % (sock, line) @listener("error") def onERROR(self, sock, msg): print "ERROR (%s): %s" % (sock, msg) def main(): server = EchoServer(1234) event.manager += server while True: try: manager.flush() server.poll() except KeyboardInterrupt: break if __name__ == "__main__": main() On Thu, Sep 11, 2008 at 5:33 AM, Tzury Bar Yochay wrote: >> Transmitting large binary data over UDP? That makes only sense for few >> applications like video and audio streaming. UDP does neither guarantee >> that your data is received nor it's received in order. For example the >> packages A, B, C, D might be received as A, D, B (no C). >> >> Can your protocol handle missing packages and out of order packages? > > I intend of using it for audio transmission and don't care about lose > or out of order. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From support.desk.ipg at gmail.com Wed Sep 24 10:22:32 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Wed, 24 Sep 2008 09:22:32 -0500 Subject: Regex Help In-Reply-To: References: Message-ID: Thanks for the reply, I found out the problem was occurring later on in the script. The regexp works well. -----Original Message----- From: Lawrence D'Oliveiro [mailto:ldo at geek-central.gen.new_zealand] Sent: Tuesday, September 23, 2008 6:51 PM To: python-list at python.org Subject: Re: Regex Help In message , Support Desk wrote: > Anybody know of a good regex to parse html links from html code? The one I > am currently using seems to be cutting off the last letter of some links, > and returning links like > > http://somesite.co > > or http://somesite.ph > > the code I am using is > > > regex = r'
' Can you post some example HTML sequences that this regexp is not handling correctly? From maebert at uos.de Mon Sep 15 20:03:08 2008 From: maebert at uos.de (Manuel Ebert) Date: Tue, 16 Sep 2008 02:03:08 +0200 Subject: Representation of python code ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 AFAIK epydoc can generate pretty graphs with graphviz on the fly, such as class hierarchies or call graphs. On Sep 14, 2008, at 3:44 PM, Barak, Ron wrote: > Hi Guys, > Is there a script/application, which gets as input python code, and > produces a (graphic) representation of the inter-relationships > between its classes/functions ? > Bye, > Ron. > -- > http://mail.python.org/mailman/listinfo/python-list -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIzve8cZ70OCIgLecRAjRbAKCRXHRKDJN+oxoJQ7S7z8i6sVCNxQCggowS PVV6g/BRKesRGErGHcAcURE= =q9Hs -----END PGP SIGNATURE----- From bignose+hates-spam at benfinney.id.au Sun Sep 21 20:46:19 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 22 Sep 2008 10:46:19 +1000 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <87ljxl0zz8.fsf@benfinney.id.au> Steven D'Aprano writes: > I have a class which is not intended to be instantiated. Instead of > using the class to creating an instance and then operate on it, I > use the class directly, with classmethods. Essentially, the class is > used as a function that keeps state from one call to the next. Classes aren't designed to keep state; state is kept in instances. I think you want Alex Martelli's 'Borg' pattern , which is a class where each instance shares the same state. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but there's still a bug stuck in here from last time.? | _o__) ?_Pinky and The Brain_ | Ben Finney From psully at gmail.com Fri Sep 26 11:39:35 2008 From: psully at gmail.com (Patrick Sullivan) Date: Fri, 26 Sep 2008 08:39:35 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions Message-ID: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> Hello. I will be using some large data sets ("points" from 2 to 12 variables) and would like to use one class for each point rather than a list or dictionary. I imagine this is terribly inefficient, but how much? What is the cost of creating a new class? What is the cost of referencing a class variable? What is the cost of calling a class method to just return a variable? Key point: The point objects, once created, and essentially non- mutable. Static. Is there a way to "bind" a variable to a object method in a way that is more efficient than the function calling self.variable_name ? I'll run some profile tests later today but if anyone has any cost/ efficiency of object creation in python, or any other idioms related to variable creation, I'd greatly appreciate some links. Thanks! Patrick From keshet1 at umbc.edu Fri Sep 12 13:53:58 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Fri, 12 Sep 2008 13:53:58 -0400 Subject: manipulating files within 'for' In-Reply-To: References: <48CAA2AA.40809@umbc.edu> Message-ID: <48CAACB6.60106@umbc.edu> Emile van Sebille wrote: > Ben Keshet wrote: >> Hi Pythoneers, >> >> I have a question about a code I wrote with the help of someone. The >> code below copy a few lines from different files into one file. It >> works fine as it is given here and generates the new file >> 'pockets.out' correctly, but says:"....py returned exit code 0". >> However, if I add more values to 'receptor' (say, receptor = ['1AZM' >> '1ADS']) > > > At risk of stating the obvious, you _did_ put this in properly as > > receptors = ['1AZM', '1ADS'] > > ...right? > > Emile ...wrong. I thought I should omit the comma and didn't put it. I guess that stating the obvious should be the first attempt with beginners like me. Thanks for thinking about it (it's running perfect now). BK > > > > it gives an >> error: "Exception raised while running script". >> >> Can anyone please advice me? Why is it giving an error on multiple x >> but runs well with one (I made sure that all files and folders exist, >> etc.). What does exit code 0 mean? > > No error > >> what does "exception raised" mean? > > Error > > -- > http://mail.python.org/mailman/listinfo/python-list > From bobernet at nsa.invalid Sat Sep 27 03:08:00 2008 From: bobernet at nsa.invalid (Bob Cortopassi) Date: Sat, 27 Sep 2008 07:08:00 +0000 (UTC) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> Message-ID: On 2008-09-26, nntpman68 wrote: > - I'm annoyed by any spam. > It's tough to find good rules, but the incoming spams that I see > currently on comp.lang.python have certain criteas. > > - most email addresses from gmail. ...snip rest of good filter criteria... Killing all messages with "googlegroups" in the messageid will get rid of a vast majority of the spam. Killing anything with a gmail.com email address will end up killing more legitimate posters. -- email: echo "sbs at sbsrearg.pbz" | sed 's/s/o/g' | rot13 All posts from Google Groups are auto-killed. From marco.bizzarri at gmail.com Mon Sep 15 13:59:53 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 15 Sep 2008 19:59:53 +0200 Subject: [OT] Fwd: [XP] Test run times needed In-Reply-To: References: Message-ID: <3f0d61c40809151059sc6248afr24308cc6846d83c3@mail.gmail.com> This is a little Off Topic, so, I ask forgiveness in advance. I'm forwarding this message from Kent Beck from XP Mailing List. He's asking for people to send execution times of unit tests. Even though in the beginning of the mail he speaks about ant and xml formats, actually, a simple text file with test name - execution time is more than enough for doing some calculations. Regards Marco ---------- Forwarded message ---------- From: kentb Date: Tue, Sep 9, 2008 at 1:53 AM Subject: [XP] Test run times needed To: extremeprogramming at yahoogroups.com (Sorry for the cross post from JUnit.) All, Saff and I are working on ways in JUnit to shorten the validation phase of the inner programming loop (feature -> test -> code -> validate). One of the ideas is to find a general way to run suites faster by running tests in parallel. To find effective parallelization strategies, we need data on test run times. Rather than build big infrastructure to do this (which would undoubtedly be cool), I'd like to start with the simplest thing that could possibly work. So: If you have a long-running JUnit test suite and You run it using Ant and You can use the XML formattter ("") and You don't mind sharing your test names with me confidentially Would you please zip your reports and email them to me. If they're too big for email, please let me know and we'll figure out a backup plan. I'd appreciate any context you can provide--how long the suite has been in development, the experience level of the developers, whatever else you think we might need to know. The first data set I looked at was from DevCreek-->90M test runs from production coding representing more than 50 person-years of development. To my surprise, the test runs exhibit a power law distribution (way lots of fast tests, a few very long running tests, plot a histogram log-log and you get a straight line). I have no idea what this means, but it brings to mind the Asimov quote, "The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!' (I found it!) but 'That's funny ...'" I've found many power law distributions in the static and dynamic structure of code, but the mechanisms influencing test run times seem to be completely different than those influencing code structure. Anyway, I'd love to validate those findings. The Ant XML format seems like a good place to start. Alternatively, you could send me one or more files with test run times one per line. This would work for languages other than Java, which would also be interesting to analyze. Questions and comments appreciated. Yours in science, Kent Beck Three Rivers Institute __._,_.___ Messages in this topic (1) Reply (via web post) | Start a new topic Messages | Files | Photos | Links | Database | Polls | Members To Post a message, send it to: extremeprogramming at eGroups.com To Unsubscribe, send a blank message to: extremeprogramming-unsubscribe at eGroups.com ad-free courtesy of objectmentor.com Change settings via the Web (Yahoo! ID required) Change settings via email: Switch delivery to Daily Digest | Switch format to Traditional Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe Recent Activity 27 New Members Visit Your Group Yahoo! Finance It's Now Personal Guides, news, advice & more. Wellness Spot Embrace Change Break the Yo-Yo weight loss cycle. Yahoo! Groups Familyographer Zone Learn how to capture family moments. . __,_._,___ -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From bdesth.quelquechose at free.quelquepart.fr Thu Sep 4 13:57:01 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 19:57:01 +0200 Subject: Late initialization using __getattribute__ In-Reply-To: References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> Message-ID: <48c03d5d$0$29351$426a74cc@news.free.fr> bukzor a ?crit : >>>>> so unfortunately I think I need to use __getattribute__ >>>>> to do this. I'm doing all this just to make the connection not >>>>> actually connect until used. >>>> I may be dumb, but I don't get how this is supposed to solve your >>>> problem. But anyway : there's a known design pattern for what you're >>>> trying to do, that doesn't require mixins nor messing with >>>> __getattribute__ (which, I repeat, is more often than not something you >>>> *don't* want to do). The name of the design pattern is "proxy". I >>>> strongly suggest that you 1/ try to cure the real problem instead of >>>> hacking around and 2/ read about the proxy design pattern. >>>> My 2 cents... >>> I like the idea of mix-ins, but can't figure out how to make a proxy >>> work that way. >> You mean, "how to use a proxy for lazy initialization" ? Heck, that's >> the exact use case in the GoF. > > I mean, "how to make a MixIn class that uses the proxy pattern". That's not how proxies work. They use composition/delegation, not MI. >I'd > like to be able to do something like this: > > class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ..., > VanillaCursor): pass Yuck. Sorry, but it reminds me of the worst MI abuses in Zope2. (snip) > My toy example turned out to be not the best representation of the > problem. This is often the case with toy examples. > The base class has attributes that "exist" but either throw errors or > segfault > if used before reconnect() is called. Then these attributes should probably call reconnect() by themselves. Decorators and/or computed attributes may help here. From tjreedy at udel.edu Fri Sep 26 19:07:36 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 19:07:36 -0400 Subject: Running IDLE on 3.0rc1 Message-ID: I have not seen this posted, so... To run IDLE with Python3.0rc1, edit Python30/Libs/idlelib/run.py, and change "set_daemon(True)" to "daemon = True" and save. (This is about line 75, and the only appearance of 'daemon'.) Otherwise, you get error message about not starting a subprocess. tjr From stefan_ml at behnel.de Fri Sep 5 01:13:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Sep 2008 07:13:37 +0200 Subject: xml + mmap cross In-Reply-To: References: <48BF8AC8.6030509@behnel.de> Message-ID: <48c0c001$0$9319$9b4e6d93@newsspool2.arcor-online.net> Hi, this discussion seems pretty much off-topic for a Python list. castironpi wrote: > In an XML file, entries are stored in serial, sort of like this. > > AAA BBB CCC DDD > > Or more recognizably, > > somethingsomething > > Point is, to change something to something else, you > have to recopy everything after that. > > AAA BBB CCC DDD > AAA BBBb CCC DDD > > requires 7 writes, 'b CCC DDD', not 1. > > I want to use a simple tree structure to store: > > 0 A-> None, 1 > 1 B-> None, 2 > 2 C-> 3, None > 3 D-> None, None > > Each node maps to 'Next, Child', or more accurately, 'Next Sibling, > First Child'. Do I understand you right: you want to access serialised XML data as a memory mapped file and operate directly on the byte data? You would still have to decode the complete byte sequence to parse it and build your index structure in that case. How do you plan to store the pointers to a node's next sibling/child? And how do you keep them updated over insertions/deletions? That, plus the copy overhead in a sequential file, will be very costly on each change. > You get constant time updates to contents, and log-time searches. Every XML tree structure gives you log-time searches. But how do you achieve constant time updates in a sequential file? Stefan From mensanator at aol.com Sun Sep 28 18:11:49 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 28 Sep 2008 15:11:49 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: <4631f865-3fa1-4b0c-9cb2-4bb5ed35079f@m44g2000hsc.googlegroups.com> On Sep 28, 4:02?pm, Tim Chase wrote: > > Wondering if there is a better way to generate string of numbers with > > a length of 5 which also can have a 0 in the front of the number. > > If you want to resample the same digit multiple times, either of these > two will do: > > ?>>> from random import choice > ?>>> ''.join(str(choice(range(10))) for _ in range(5)) > '06082' > > ?>>> from string import digits > ?>>> ''.join(choice(digits) for _ in range(5)) > '09355' > > If you need to prevent the digits from being reused > > ?>>> d = list(digits) > ?>>> random.shuffle(digit) > ?>>> ''.join(d[:5]) > '03195' > > I suspect that the zfill responses don't have the property of equally > distributed "randomness", as the first digit may more likely be a zero. > ? The methods here should give equal probabilities for each choice in > each place. Does he want equal probabilities of each digit in each place? > > -tkc From barry at python.org Thu Sep 18 01:40:18 2008 From: barry at python.org (Barry Warsaw) Date: Thu, 18 Sep 2008 01:40:18 -0400 Subject: RELEASED Python 2.6rc2 and 3.0rc1 Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the second and final planned release candidate for Python 2.6, as well as the first release candidate for Python 3.0. These are release candidates, so while they are not suitable for production environments, we strongly encourage you to download and test them on your software. We expect only critical bugs to be fixed between now and the final releases. Currently Python 2.6 is scheduled for October 1st, 2008. Python 3.0 release candidate 2 is planned for October 1st, with the final release planned for October 15, 2008. If you find things broken or incorrect, please submit bug reports at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 website: http://www.python.org/download/releases/2.6/ and the Python 3.0 web site: http://www.python.org/download/releases/3.0/ See PEP 361 for release schedule details: http://www.python.org/dev/peps/pep-0361/ Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSNHpw3EjvBPtnXfVAQLW9wP/RBCaUvhuheIh+BjLLIHQFBQi7D3uVgqi l0+4fhhoKGJvtWklLfSM9I1prcjH/d6tzUu4fIOjX7aM+wZSG++vkfmBoehnhyZW AvU9Lax4mqDwhOJA2QA0WMx0obpYYVHeUl7D1g9kWzbRUkZDX9NZGMWThhEOC1qA UA3bBYbvWiQ= =BFNH -----END PGP SIGNATURE----- From edreamleo at charter.net Sun Sep 14 10:20:41 2008 From: edreamleo at charter.net (Edward K Ream) Date: Sun, 14 Sep 2008 09:20:41 -0500 Subject: ANN: Leo 4.5.1 final released Message-ID: <%69zk.4676$rV4.3209@newsfe03.iad> Leo 4.5.1 final is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo 4.5.1 final fixes several important bugs in Leo 4.5 final: - Eliminated spurious error messages in the goto-global-line command. - @shadow files with unknown file extensions now work properly. - Leo's installer now properly finds Python's install directory. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.5: -------------------------- - Full support for @shadow files in Leo's core. - Major improvements to Leo's key binding code. - The beginning of usable vim-like bindings. - uA's may now be associated with vnodes in @thin and @shadow files. - Several major reorganizations of Leo's code: including sax-based parsing, support for the Graph world (unified nodes), and simplified drawing code. - Leo is now an installable package. - Prepared code to be ready for Python 3.0. - Many small improvements and bug fixes. Quote of the month: ------------------- Squeak and Leo have been two of the most significant technologies to redefine my personal computer experience and the ideas behind computing. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From kem1723 at yahoo.com Wed Sep 3 19:57:08 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Wed, 3 Sep 2008 16:57:08 -0700 (PDT) Subject: Help with Tkinter Label Widget Message-ID: <293826.25281.qm@web83915.mail.sp1.yahoo.com> Below i've put the code for a program that i wrote. I need help on lines 384-403. If you run this program you will notice on the first tab when have it produce an answer the $ is surrounded with {$}. How can i get rid of that? from Tkinter import * class MyApp: def __init__(self, parent): self.myparent = parent self.frame1 = Frame(parent) self.frame1.grid(row=0, column=0) self.frame2 = Frame(parent) self.frame2.grid(row=0, column=0) self.frame3 = Frame(parent) self.frame3.grid(row=0, column=0) self.frame4 = Frame(parent) self.frame4.grid(row=0, column=0) self.a = self.b = self.c = self.d = 0 self.COG1 = DoubleVar(); self.COG2 = DoubleVar(); self.COG3 = DoubleVar(); self.COG4 = DoubleVar() self.GP1 = DoubleVar(); self.PrInc = DoubleVar(); self.markupPrice = DoubleVar() self.tab1Func(1) def tab1Func(self, event): self.tab1 = Button(self.frame1, width=14, relief=FLAT, bg="white", text="Multi-Markup") self.tab1.bind("", self.switch1) self.tab1.grid(row=0, column=0) self.tab2 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") self.tab2.bind("", self.switch2) self.tab2.grid(row=0, column=1) self.tab3 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") self.tab3.bind("", self.switch3) self.tab3.grid(row=0, column=2) self.tab4 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") self.tab4.bind("", self.switch4) self.tab4.grid(row=0, column=3) self.tab1Title = Label(self.frame1, font="bold", relief=GROOVE, text="Multi-Markup Calculator") self.tab1Title.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) self.tab1Entry1 = Entry(self.frame1, textvariable=self.COG1) self.tab1Entry1.select_range(0, END) self.tab1Entry1.bind("", self.multiMarkup) self.tab1Entry1.focus_force() self.tab1Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.tab1Entry1Title= Label(self.frame1, text="Enter COG:") self.tab1Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.tab1CalcButton = Button(self.frame1, text="Calculate") self.tab1CalcButton.bind("", self.multiMarkup) self.tab1CalcButton.bind("", self.multiMarkup) self.tab1CalcButton.grid(padx=2, pady=2, row=3, column=1, columnspan=2, sticky=W+E) self.tab1Header = Label(self.frame1, font="bold", relief=GROOVE, text="Gross Profit % Markup Price") self.tab1Header.grid(padx=2, pady=2, row=4, column=0, columnspan=4, sticky=W+E) self.tab1GP1 = Label(self.frame1, width=4,relief=RIDGE, bg="white", text="5%") self.tab1GP1.grid(padx=2, pady=2, row=5, column=1) self.tab1GP2 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="10%") self.tab1GP2.grid(padx=2, pady=2, row=6, column=1) self.tab1GP3 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="15%") self.tab1GP3.grid(padx=2, pady=2, row=7, column=1) self.tab1GP4 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="18%") self.tab1GP4.grid(padx=2, pady=2, row=8, column=1) self.tab1GP5 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="20%") self.tab1GP5.grid(padx=2, pady=2, row=9, column=1) self.tab1GP6 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="21%") self.tab1GP6.grid(padx=2, pady=2, row=10, column=1) self.tab1GP7 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="22%") self.tab1GP7.grid(padx=2, pady=2, row=11, column=1) self.tab1GP8 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="23%") self.tab1GP8.grid(padx=2, pady=2, row=12, column=1) self.tab1GP9 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="24%") self.tab1GP9.grid(padx=2, pady=2, row=13, column=1) self.tab1GP10 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="25%") self.tab1GP10.grid(padx=2, pady=2, row=14, column=1) self.tab1GP11 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="26%") self.tab1GP11.grid(padx=2, pady=2, row=15, column=1) self.tab1GP12 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="27%") self.tab1GP12.grid(padx=2, pady=2, row=16, column=1) self.tab1GP13 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="28%") self.tab1GP13.grid(padx=2, pady=2, row=17, column=1) self.tab1GP14 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="29%") self.tab1GP14.grid(padx=2, pady=2, row=18, column=1) self.tab1GP15 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="30%") self.tab1GP15.grid(padx=2, pady=2, row=19, column=1) self.tab1GP16 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="31%") self.tab1GP16.grid(padx=2, pady=2, row=20, column=1) self.tab1GP17 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="33%") self.tab1GP17.grid(padx=2, pady=2, row=21, column=1) self.tab1GP18 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="35%") self.tab1GP18.grid(padx=2, pady=2, row=22, column=1) self.tab1GP19 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="40%") self.tab1GP19.grid(padx=2, pady=2, row=23, column=1) self.tab1GP20 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="45%") self.tab1GP20.grid(padx=2, pady=2, row=24, column=1) self.tab1Markup1 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup1.grid(padx=2, pady=2, row=5, column=2, sticky=E) self.tab1Markup2 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup2.grid(padx=2, pady=2, row=6, column=2, sticky=E) self.tab1Markup3 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup3.grid(padx=2, pady=2, row=7, column=2, sticky=E) self.tab1Markup4 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup4.grid(padx=2, pady=2, row=8, column=2, sticky=E) self.tab1Markup5 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup5.grid(padx=2, pady=2, row=9, column=2, sticky=E) self.tab1Markup6 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup6.grid(padx=2, pady=2, row=10, column=2, sticky=E) self.tab1Markup7 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup7.grid(padx=2, pady=2, row=11, column=2, sticky=E) self.tab1Markup8 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup8.grid(padx=2, pady=2, row=12, column=2, sticky=E) self.tab1Markup9 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup9.grid(padx=2, pady=2, row=13, column=2, sticky=E) self.tab1Markup10 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup10.grid(padx=2, pady=2, row=14, column=2, sticky=E) self.tab1Markup11 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup11.grid(padx=2, pady=2, row=15, column=2, sticky=E) self.tab1Markup12 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup12.grid(padx=2, pady=2, row=16, column=2, sticky=E) self.tab1Markup13 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup13.grid(padx=2, pady=2, row=17, column=2, sticky=E) self.tab1Markup14 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup14.grid(padx=2, pady=2, row=18, column=2, sticky=E) self.tab1Markup15 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup15.grid(padx=2, pady=2, row=19, column=2, sticky=E) self.tab1Markup16 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup16.grid(padx=2, pady=2, row=20, column=2, sticky=E) self.tab1Markup17 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup17.grid(padx=2, pady=2, row=21, column=2, sticky=E) self.tab1Markup18 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup18.grid(padx=2, pady=2, row=22, column=2, sticky=E) self.tab1Markup19 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup19.grid(padx=2, pady=2, row=23, column=2, sticky=E) self.tab1Markup20 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup20.grid(padx=2, pady=2, row=24, column=2, sticky=E) def tab2Func(self, event): self.tab1 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") self.tab1.bind("", self.switch1) self.tab1.grid(row=0, column=0) self.tab2 = Button(self.frame2, width=14, relief=FLAT, bg="white", text="Single Markup") self.tab2.bind("", self.switch2) self.tab2.grid(row=0, column=1) self.tab3 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") self.tab3.bind("", self.switch3) self.tab3.grid(row=0, column=2) self.tab4 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") self.tab4.bind("", self.switch4) self.tab4.grid(row=0, column=3) self.tab2Title = Label(self.frame2, font="bold", relief=GROOVE, text="Single Markup Calculator") self.tab2Title.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) self.tab2Entry1 = Entry(self.frame2, textvariable=self.COG2) self.tab2Entry1.select_range(0, END) self.tab2Entry1.bind("", self.singleMarkup) self.tab2Entry1.focus_force() self.tab2Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.tab2Entry2 = Entry(self.frame2, textvariable=self.GP1) self.tab2Entry2.select_range(0, END) self.tab2Entry2.bind("", self.singleMarkup) self.tab2Entry2.focus_force() self.tab2Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.tab2Entry1Title= Label(self.frame2, text="Enter COG:") self.tab2Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.tab2Entry2Title= Label(self.frame2, text="Enter GP %:") self.tab2Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.tab2CalcButton = Button(self.frame2, text="Calculate") self.tab2CalcButton.bind("", self.singleMarkup) self.tab2CalcButton.bind("", self.singleMarkup) self.tab2CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) self.tab2Header = Label(self.frame2, font="bold", relief=GROOVE) self.tab2Header["text"] = self.GP1.get(), "%","Markup" self.tab2Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) self.tab2Markup1 = Label(self.frame2, width=10, font="bold", relief=GROOVE, bg="white") self.tab2Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) def tab3Func(self, event): self.tab1 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") self.tab1.bind("", self.switch1) self.tab1.grid(row=0, column=0) self.tab2 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") self.tab2.bind("", self.switch2) self.tab2.grid(row=0, column=1) self.tab3 = Button(self.frame3, width=14, relief=FLAT, bg="white", text="Product Increase") self.tab3.bind("", self.switch3) self.tab3.grid(row=0, column=2) self.tab4 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") self.tab4.bind("", self.switch4) self.tab4.grid(row=0, column=3) self.tabTitle = Label(self.frame3, font="bold",relief=GROOVE, text="Product Increase Calculator") self.tabTitle.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) self.tab3Entry1 = Entry(self.frame3, textvariable=self.COG3) self.tab3Entry1.select_range(0, END) self.tab3Entry1.bind("", self.priceIncrease) self.tab3Entry1.focus_force() self.tab3Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.tab3Entry2 = Entry(self.frame3, textvariable=self.PrInc) self.tab3Entry2.select_range(0, END) self.tab3Entry2.bind("", self.priceIncrease) self.tab3Entry2.focus_force() self.tab3Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.tab3Entry1Title= Label(self.frame3, text="Enter COG:") self.tab3Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.tab3Entry2Title= Label(self.frame3, text="Enter Increase %:") self.tab3Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.tab3CalcButton = Button(self.frame3, text="Calculate") self.tab3CalcButton.bind("", self.priceIncrease) self.tab3CalcButton.bind("", self.priceIncrease) self.tab3CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) self.tab3Header = Label(self.frame3, font="bold", relief=GROOVE) self.tab3Header["text"] = self.PrInc.get(), "%","Price","Increase" self.tab3Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) self.tab3Markup1 = Label(self.frame3, width=10, font="bold", relief=GROOVE, bg="white") self.tab3Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) def tab4Func(self, event): self.tab1 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") self.tab1.bind("", self.switch1) self.tab1.grid(row=0, column=0) self.tab2 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") self.tab2.bind("", self.switch2) self.tab2.grid(row=0, column=1) self.tab3 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") self.tab3.bind("", self.switch3) self.tab3.grid(row=0, column=2) self.tab4 = Button(self.frame4, width=14, relief=FLAT, bg="white", text="Calculate GP") self.tab4.bind("", self.switch4) self.tab4.grid(row=0, column=3) self.tabTitle = Label(self.frame4, font="bold",relief=GROOVE, text="Calculate GP") self.tabTitle.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) self.tab4Entry1 = Entry(self.frame4, textvariable=self.COG4) self.tab4Entry1.select_range(0, END) self.tab4Entry1.bind("", self.GpCalc) self.tab4Entry1.focus_force() self.tab4Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.tab4Entry2 = Entry(self.frame4, textvariable=self.markupPrice) self.tab4Entry2.select_range(0, END) self.tab4Entry2.bind("", self.GpCalc) self.tab4Entry2.focus_force() self.tab4Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.tab4Entry1Title= Label(self.frame4, text="Enter COG:") self.tab4Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.tab4Entry2Title= Label(self.frame4, text="Enter Markup $:") self.tab4Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.tab4CalcButton = Button(self.frame4, text="Calculate") self.tab4CalcButton.bind("", self.GpCalc) self.tab4CalcButton.bind("", self.GpCalc) self.tab4CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) self.tab4Header = Label(self.frame4, font="bold", relief=GROOVE) self.tab4Header["text"] = "Gross Profit" self.tab4Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) self.tab4Markup1 = Label(self.frame4, width=10, font="bold", relief=GROOVE, bg="white") self.tab4Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) def switch1(self, event): self.frame1.grid(sticky=N+S+E+W) self.frame2.grid_forget() self.frame3.grid_forget() self.frame4.grid_forget() self.tab1Entry1.focus_force() self.tab1Entry1.select_range(0, END) def switch2(self, event): if self.b == 0: self.tab2Func(1) self.b = 1 self.frame1.grid_forget() self.frame2.grid(sticky=N+S+E+W) self.frame3.grid_forget() self.frame4.grid_forget() self.tab2Entry1.focus_force() self.tab2Entry1.select_range(0, END) def switch3(self, event): if self.c == 0: self.tab3Func(1) self.c = 1 self.frame1.grid_forget() self.frame2.grid_forget() self.frame3.grid(sticky=N+S+E+W) self.frame4.grid_forget() self.tab3Entry1.focus_force() self.tab3Entry1.select_range(0, END) def switch4(self, event): if self.d == 0: self.tab4Func(1) self.d = 1 self.frame1.grid_forget() self.frame2.grid_forget() self.frame3.grid_forget() self.frame4.grid(sticky=N+S+E+W) self.tab4Entry1.focus_force() self.tab4Entry1.select_range(0, END) def multiMarkup(self, event): try: value = self.COG1.get() except ValueError: self.COG1 = DoubleVar() self.tab1Entry1["textvariable"] = self.COG1 self.tab1Entry1.select_range(0, END) self.tab1Markup1["text"] = "$", round(self.COG1.get()/.95, 2) self.tab1Markup2["text"] = "$", round(self.COG1.get()/.90, 2) self.tab1Markup3["text"] = "$", round(self.COG1.get()/.85, 2) self.tab1Markup4["text"] = "$", round(self.COG1.get()/.82, 2) self.tab1Markup5["text"] = "$", round(self.COG1.get()/.80, 2) self.tab1Markup6["text"] = "$", round(self.COG1.get()/.79, 2) self.tab1Markup7["text"] = "$", round(self.COG1.get()/.78, 2) self.tab1Markup8["text"] = "$", round(self.COG1.get()/.77, 2) self.tab1Markup9["text"] = "$", round(self.COG1.get()/.76, 2) self.tab1Markup10["text"] = "$", round(self.COG1.get()/.75, 2) self.tab1Markup11["text"] = "$", round(self.COG1.get()/.74, 2) self.tab1Markup12["text"] = "$", round(self.COG1.get()/.73, 2) self.tab1Markup13["text"] = "$", round(self.COG1.get()/.72, 2) self.tab1Markup14["text"] = "$", round(self.COG1.get()/.71, 2) self.tab1Markup15["text"] = "$", round(self.COG1.get()/.70, 2) self.tab1Markup16["text"] = "$", round(self.COG1.get()/.69, 2) self.tab1Markup17["text"] = "$", round(self.COG1.get()/.67, 2) self.tab1Markup18["text"] = "$", round(self.COG1.get()/.65, 2) self.tab1Markup19["text"] = "$", round(self.COG1.get()/.60, 2) self.tab1Markup20["text"] = "$", round(self.COG1.get()/.55, 2) def singleMarkup(self, event): try: value = self.COG2.get() except ValueError: self.COG2 = DoubleVar() self.tab2Entry1["textvariable"] = self.COG2 try: value = self.GP1.get() except ValueError: self.GP1 = DoubleVar() self.tab2Entry2["textvariable"] = self.GP1 self.tab2Entry1.focus_force() self.tab2Entry1.select_range(0, END) GP = 1 - (round((self.GP1.get()/100),2)) self.tab2Markup1["text"] = "$",round(self.COG2.get()/GP, 2) self.tab2Header["text"] = self.GP1.get(), "%","Markup" def priceIncrease(self, event): try: value = self.COG3.get() except ValueError: self.COG3 = DoubleVar() self.tab3Entry1["textvariable"] = self.COG3 try: value = self.PrInc.get() except ValueError: self.PrInc = DoubleVar() self.tab3Entry2["textvariable"] = self.PrInc self.tab3Entry1.focus_force() self.tab3Entry1.select_range(0, END) increase = 1+(self.PrInc.get()/100) self.tab3Markup1["text"] = "$",round((self.COG3.get()*increase),2) self.tab3Header["text"] = self.PrInc.get(), "%","Price","Increase" def GpCalc(self, event): try: value = self.COG4.get() except ValueError: self.COG4 = DoubleVar() self.tab4Entry1["textvariable"] = self.COG4 try: value = self.markupPrice.get() except ValueError: self.markupPrice = DoubleVar() self.tab4Entry2["textvariable"] = self.markupPrice self.tab4Entry1.focus_force() self.tab4Entry1.select_range(0, END) COG4 = self.COG4.get() markup = self.markupPrice.get() if COG4==0.0 or markup==0.0: self.tab4Markup1["text"] = "" else: GP = 100*(1-(self.COG4.get()/self.markupPrice.get())) self.tab4Markup1["text"] = round(GP, 2),"%" root = Tk() myapp = MyApp(root) root.mainloop() From sturlamolden at yahoo.no Fri Sep 12 18:37:07 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Sep 2008 15:37:07 -0700 (PDT) Subject: Python a good choice for experimenting with Win32 API? References: <98qdnS2nk4rpEVfVnZ2dnUVZ_qHinZ2d@comcast.com> Message-ID: <09601c7a-a138-4163-9265-286f87ef5767@y21g2000hsf.googlegroups.com> > (1) Would CPython be a good choice for this? How about iron python? How > about Jython (probably not). You can use CPython without any problems. Alternatives are pywin32, ctypes, cython, pyrex, Python C API. You can use .NET platform invoke from IronPython. You can use JNI from Jython, or any Win32 API wrapper that may exist for Java. > (2) What about callbacks? Which pythons can handle callbacks? Yes you can use Python functions or bound methods as callbacks. > (3) How easy it it define the C structs, enums and integer constants > necessary to call the windows API functions? It is easy if you can read C header files. > (4) Here is the code I'm struggling with presently (it is just not > cooperating: no errors just wrong results! Here is what it will look like with the pywin32 package: import win32api import win32con def compute(sLangId_, uCode_, uMapType_): hkl = win32api.LoadKeyboardLayout(sLangId_, win32con.KLF_ACTIVATE |win32con.KLF_SUBSTITUTE_OK|win32con.KLF_REPLACELANG) uResult_ = win32api.MapVirtualKeyEx(uCode_, uMapType_, hkl) return uResult_ With ctypes there is a little more work to do: import ctypes MAPVK_VK_TO_VSC = 0 MAPVK_VSC_TO_VK = 1 MAPVK_VK_TO_CHAR = 2 MAPVK_VSC_TO_VK_EX = 3 MAPVK_VK_TO_VSC_EX = 4 KLF_ACTIVATE = 1, KLF_SUBSTITUTE_OK = 2 KLF_REORDER = 8 KLF_REPLACELANG = 0x10 KLF_NOTELLSHELL = 0x80 KLF_SETFORPROCESS = 0x00100 KLF_SHIFTLOCK = 0x10000 KLF_RESET = 0x40000000 LoadKeyboardLayout = ctypes.windll.user32.LoadKeyboardLayout LoadKeyboardLayout.argtypes = (ctypes.c_wchar_p, ctypes.c_uint) LoadKeyboardLayout.restype = ctypes.c_void_p UnloadKeyboardLayout = ctypes.windll.user32.UnloadKeyboardLayout UnloadKeyboardLayout.argtypes = (ctypes.c_void_p,) UnloadKeyboardLayout.restype = ctypes.c_int MapVirtualKeyEx = ctypes.windll.user32.UnloadKeyboardLayout MapVirtualKeyEx.argtypes = (ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p) MapVirtualKeyEx.restype = ctypes.c_uint def compute(sLangId_, uCode_, uMapType_): hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE|KLF_SUBSTITUTE_OK| KLF_REPLACELANG) uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl) return uResult_ This is similar to your code, so it will have the same bugs. From bearophileHUGS at lycos.com Thu Sep 11 12:28:43 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Sep 2008 09:28:43 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: Message-ID: <73be6644-6538-4199-a565-4cf4bc34149c@j22g2000hsf.googlegroups.com> hofer: > The real example would be more like: > name,age,country = itemgetter('name age country'.split())(x) # or any > of my above versions That solution is very clever, and the inventor smart, but it's too much out of standard and complex to be used in normal real code. Learning tricks is useful, but then in real code you have to use then only once in a while. A list comp is quite more easy to understand for Python programmers. Bye, bearophile From marco.bizzarri at gmail.com Thu Sep 4 07:09:52 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 13:09:52 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <3f0d61c40809040409v3ee40da3h7eb0703009e78f06@mail.gmail.com> Sorry... pressed enter but really didn't want to. As I said, let's say I have a class class A: def __init__(self): self.x = None Python makes the decision to allow the developers to directly access the attribute "x", so that they can directly write: "a.x = 1", or whatever; this has for me the unfortunate side effect that if I write, for example "a.y = 1", when I really wanted to write "a.x = 1" no one cares about it, and I'm unable to spot this error until later. Of course, I know that while I'm fresh, I've a good knowledge of the code, and anything else, I will be able to avoid such stupid errors; however, I'm afraid of the times when I'm tired, when I have to put my hands on the code of someone else, and so on. Please, understand that I'm not stating that python is wrong... after all, if it is wrong, I can move to a language like Java, which has a different approach on it. I'm really very interested in reading past discussion on it, if they are available. Regards Marco On Thu, Sep 4, 2008 at 12:57 PM, Marco Bizzarri wrote: > Let's say I've a class a, where I can write: > > > > -- > Marco Bizzarri > http://notenotturne.blogspot.com/ > http://iliveinpisa.blogspot.com/ > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From ptmcg at austin.rr.com Wed Sep 17 08:57:46 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 17 Sep 2008 05:57:46 -0700 (PDT) Subject: Python OOP advice References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> Message-ID: <6089e023-18f6-4c93-a2a4-f933eac786b5@f63g2000hsf.googlegroups.com> On Sep 17, 6:50?am, Simon Hibbs wrote: > I'm rewriting a design application for a science fiction game. in it > you design your own starships. Each component has a mass and cost, but > the mass can either be fixed or it can be expressed as a percentage of > the tonnage of the overall ship. > > Orriginaly I thought I'd need to have a hull object which contains > component objects, but the component objects need access to members of > the hull object (e.g. the hull size) so that looks messy to implement. > I would not put this kind of intelligence into the components. I think the issue here is that your Ship container is not really just a generic container of ship components, but an assembly with some specific requirements (must have 1 and only 1 hull, must have 1 or more engines, etc.) and structure. I would create a class called ShipDesign that had specific members for those components that have special logic attached to them, and then more generic list members for collection-ish components. Since the hull is such a significant constraint, I would make it an initialization argument. I would also put some kind of property on hull representing its "capacity" (oh I see, you have something call hull_size). One way to generalize the fixed-cost vs. percentage-cost components would be to have all components implement a compute_load function that takes the ShipDesign as an argument. Those that are fixed-cost simply return their fixed value, those that are percentage-cost can return their percentage of the ShipDesign's hull.hull_size - this leaves the door open for other variations on load, that could be based on other properties besides the hull size. Here's how I envision your ShipDesign class: class ShipDesign(object): def __init__(self, hull): self.hull = hull self.engines = [] self.shields = [] self.weapons = [] self.other = [] def compute_consumed_capacity(self): load = 0 for itemlist in (self.engines, self.shields, self.weapons, self.other)): load += sum(item.compute_load(self) for item in itemlist) return load def add_engine(self,e): engload = e.compute_load(self) if engload + self.compute_consumed_capacity() > self.hull.hull_size: raise ExceededHullCapacityException() if len(self.engines) == MAXIMUM_ALLOWED_ENGINES: raise ExceededMaximumConfigurationLimitException() self.engines.append(e) def set_hull(self, hull): if self.compute_consumed_capacity() <= hull.hull_size: self.hull = hull else: raise NewHullTooSmallException() def is_valid(self): if not self.engines: raise InvalidDesignException("must have at least 1 engine") ...etc... class GenericItem(object): def __init__(self, name, load): self.name = name self.load = load crewQuarters = GenericItem("Crew Quarters", 50) disco = GenericItem("Discotheque", 10) ...etc... Once you have a valid ShipDesign, you can then use it to construct multiple Ship instances. Here is how I would work around your "only one hull at a time" problem. Define several classes for different kinds of hulls: class CheapHull(Hull): capacity = 100 name = "EconoHull 1000" class MediumHull(Hull): capacity = 500 name = "Mainliner X50" class TopOTheLineHull(Hull): capacity = 1000 name = "LuxeMaster 5000" and then create ship designs with a CheapHull, a MediumHull, or a TopOTheLineHull. In this case, the member variable of the ShipDesign is really a class, which you would later use to construct hull instances as part of making Ship instances from your ShipDesign. class Ship(object): def __init__(self, design): self.hull = design.hull() self.engines = design.engines[:] ...etc... This way, each Ship will have its own Hull instance, so that you can track instance-specific properties, such as damage percentage. If you don't want to hard-code the hull types, then you can do something similar with instances of a generic Hull class, which you would then use as prototypes when constructing Ship instances. Just be careful that you don't accidentally have all ships sharing the same hull instance! -- Paul From stef.mientki at gmail.com Tue Sep 30 13:57:55 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 19:57:55 +0200 Subject: Would this be called a bug in inspect ? Message-ID: <48E268A3.4050900@gmail.com> hello, I'm not familiar with inspect, but I get an error (see below) in getmembers ( wx ) Of course this is bug in wx . But would you also call this a bug in inspect ? (inspect crashes and doesn't continue with th rest of the code, nor it returns the already gathered data) thanks, Stef >>> import wx >>> wx.version() '2.8.7.1 (msw-unicode)' >>> from inspect import * >>> getmembers(wx) Traceback (most recent call last): File "", line 1, in File ")>)>>", line 517, in pphook File "P:\Python\Lib\pprint.py", line 55, in pprint printer.pprint(object) File "P:\Python\Lib\pprint.py", line 106, in pprint self._format(object, self._stream, 0, 0, {}, 0) File "P:\Python\Lib\pprint.py", line 129, in _format rep = self._repr(object, context, level - 1) File "P:\Python\Lib\pprint.py", line 195, in _repr self._depth, level) File "P:\Python\Lib\pprint.py", line 207, in format return _safe_repr(object, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 283, in _safe_repr orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 283, in _safe_repr orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 292, in _safe_repr rep = repr(object) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' From dmitry at makovey.net Sun Sep 28 16:26:59 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Sun, 28 Sep 2008 20:26:59 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> <91e62d70-73fb-4ecc-ae2e-d950a5f7ea6b@k13g2000hse.googlegroups.com> <877b889b-c385-4e2b-abe9-17669eca09b8@d70g2000hsc.googlegroups.com> Message-ID: George Sakkis wrote: > FYI, in case you missed it the final version doesn't need a Proxy base > class, just inherit from object. Also lowercased ProxyMethod to look > similar to staticmethod/classmethod: I cought that, just quoted the wrong one :) > class A(object): > > def __init__(self, b1, b2): > self.b1 = b1 > self.b2 = b2 > > @proxymethod > def bmethod(self): > return self.b1 > > @proxymethod > def bmethod2(self): > return self.b2 > > George From gary at byoteki.com Tue Sep 30 21:52:53 2008 From: gary at byoteki.com (Gary M. Josack) Date: Tue, 30 Sep 2008 21:52:53 -0400 Subject: __buitins__ key added during eval() In-Reply-To: References: Message-ID: <48E2D7F5.90201@byoteki.com> William Purcell wrote: > I want to use eval to evaluate wx.TextCtrl inputs. How can I keep > python from adding the __builtins__ key to mydict when I use it with > eval? Other wise I have to __delitem__('__builtins__') everytime I use > eval? > > >>> mydict = {'a':2,'b':3} > >>> eval('a*b',mydict) > 6 > >>> mydict > {'a': 2, '__builtins__': {'IndexError': 'exceptions.IndexError'>, ...(I'll spare you the rest)...}, 'b': 3} > > Also, how come eval has this behavior? Is it desirable? > > -Bill > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list no too sure, but eval('a*b', None, mydict) seems to work how you expect. From rsgalloway at gmail.com Fri Sep 26 02:47:27 2008 From: rsgalloway at gmail.com (rsgalloway at gmail.com) Date: Thu, 25 Sep 2008 23:47:27 -0700 (PDT) Subject: How to read a jpg bytearray from a Flash AS3 file Message-ID: I'm trying to save an image from a Flash AS3 to my server as a jpg file. I found some PHP code to do this, but I want to do this in Python. I'm not quite sure how to convert the following code to Python. It's mainly the $GLOBALS["HTTP_RAW_POST_DATA"] part I don't know how to convert. source: http://designreviver.com/tutorials/actionscript-3-jpeg-encoder-revealed-saving-images-from-flash/ From prologic at shortcircuit.net.au Tue Sep 30 01:10:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Sep 2008 15:10:32 +1000 Subject: python & sms In-Reply-To: References: Message-ID: sui, I am sure you'll find many web services that you can use to send SMS'. Your problem would then become one of learning how to communicate and access web services in Python. Start with: * urllib and urllib2 * xmlrpc There are others... cheers James On Tue, Sep 30, 2008 at 1:47 PM, sui wrote: > Hii > i want a script to send sms to any mobile..... > can u help me ?? > > Thanks in advance...... > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From sjoerd at acm.org Thu Sep 11 11:27:33 2008 From: sjoerd at acm.org (Sjoerd Mullender) Date: Thu, 11 Sep 2008 17:27:33 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> Message-ID: <20080911152733.8D9A74802F@ottar.ins.cwi.nl> Grant Edwards writes: > Could whoever is responsible for the gateway that is grabbing > my postings off of Usenet and e-mailing them out please fix the > headers in the mail messages so that I don't get the bounce > messages? > > While you're at it, might as well fix it for everybody else > too. ;) > > Its a bit rude to send out mass e-mail messages with headers > faked up so that the bounce messages go to somebody else. Messages you submit to the newsgroup are forwarded to the mailing list. When mail messages bounce, the MTA (Message Transfer Agent--the program that handles mail) *should* send the bounce message to whatever is in the Sender header, and only if that header does not exist, should it use the From header. Messages forwarded by the gateway get a Sender header which points back to the gateway. In other words, if a message gets bounced back to the From address, the MTA does it incorrectly. There is nothing the list administrator can do about it. You can try complaining to the postmaster of the bouncing system, but that's about it. In other words, your question in the first paragraph is already implemented and was implemented from the beginning. It is not the gateway's fault that there are systems that don't follow the standards. -- Sjoerd Mullender, python-list administrator From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 11:08:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 17:08:36 +0200 Subject: Using an existing instance as parent In-Reply-To: <2ac46f80-76d5-4270-bc86-1f07a5cbd477@z72g2000hsb.googlegroups.com> References: <2ac46f80-76d5-4270-bc86-1f07a5cbd477@z72g2000hsb.googlegroups.com> Message-ID: <48bc0520$0$23840$426a34cc@news.free.fr> Andr? a ?crit : > Hi, I was trying to find a way to set, upon __init__() the parent of a > class to an existing instance. ??? Sorry but I just can't make any sense of this. > Here is a minimal example of what I'm > trying to do: > > class A(object): > def __init__(self, x): > self.x = x > > class B(A): > def __init__(self, *args): > if not isinstance(args[0], A): > super(B, self).__init__(args[0]) > else: > self = args[0] Rebinding an argument only affect the current namespace. > self.y = args[1] > > b = B(4, 6) > print 'b:', b.x, b.y, type(b) > > a = A(7) > c = B(a, 3) # Means: please set c parent's using instance "a" > print 'c:', c.x, c.y, type(c) > > This does not work as can be tested. The reason I'm in search for a > solution in this area is that in our project, "A" is not copy-able (it > is written using a boost.python binding to a C++ object that does not > allow copying) - so I can't simply call, inside "B's __init__()", a > copy constructor for A. Ok, I think I get the point... When an A instance is passed as first arg, you'd like to use this instance's state to call super(B).__init__ ? If so, here's a possible solution (Q&D, to be corrected according to real use case, etc): import copy class B(A): def __init__(self, *args): if isinstance(args[0], A): x = copy.copy(args[0].x) # if it's a mutable and you want a copy else: x = args[0] super(B, self).__init__(x) self.y = args[1] Be sure to carefully read copy's doc. From castironpi at gmail.com Tue Sep 9 20:48:35 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 9 Sep 2008 17:48:35 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: On Sep 9, 5:58?pm, Steven D'Aprano wrote: > On Tue, 09 Sep 2008 14:59:19 -0700, castironpi wrote: > > I will try my idea again. ?I want to talk to people about a module I > > want to write and I will take the time to explain it. ?I think it's a > > "cool idea" that a lot of people, forgiving the slang, could benefit > > from. ?What are its flaws? > > [snip long description with not-very-credible use-cases] Steven, > You've created a solution to a problem which (probably) only affects a > very small number of people, at least judging by your use-cases. Who has > a 4GB XML file, and how much crack did they smoke? I judge from the existence of 'shelve' and 'pickle' modules, and relational database packages, that the problem I am addressing is not rare. It could be the millionaire investor across the street, the venture capitalist down the hall, or the guy with a huge CD catalog. > Castironpi, what do *you* use this proof-of-concept module for? Honestly, nothing yet. I just wrote it. My user community and customer base are very small. Originally, I wanted to store variable- length strings in a file, where shelves and databases were overkill. I created it for its beauty, sorry to disappoint. > Don't > bother tell us what you think *we* should use it for. Tell us what you're > using it for, or at least what somebody else is using it for. If this is > just a module that you think will be cool, I don't like your chances of > people caring. There is no shortage of "cool" software that isn't useful > for anything, and unlike eye-candy, nobody is going to use your module > just because they like the algorithm. Unfortunately, nobody is going to care about most of the uses I have for it 'til I have a job. I'm goofing around with a laptop, remembering when my databases professor kept dropping the ball on VARCHARs. If you want a sound byte, think, "imagine programming without 'new' and 'malloc'." > If you don't have an existing application for the software, then explain > what it does (not how) and give some idea of the performance ("it's alpha > and written in Python and really slow, but I will re-write it in C and > expect it to make a billion random accesses in a 10GB file per > millisecond", or whatever). You might be lucky and have somebody say > "Hey, that's just the tool I need to solve my problem!". I wrote a Rope implementation just to test drive it. It exceeded the native immutable string type at 2 megs. It used 'struct' instead of 'ctypes', so that number could conceivably come down. I am intending to leave it in pure Python, so there. > -- > Steven Pleasure chatting as always sir. From wuwei23 at gmail.com Fri Sep 26 23:22:09 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 26 Sep 2008 20:22:09 -0700 (PDT) Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: <40efa068-688c-4dcf-b11e-938c0d4d006a@w39g2000prb.googlegroups.com> On Sep 27, 12:39?pm, process wrote: > ' '.join([`x * x` for x in range(1, 6)]) > > exactly what does this symbol do and what does it stand for? `` is the same as repr(). I'm pretty sure the backtick operator has been removed from 3.0. In the context of the code sample you posted, it appears to be used to convert the result of x*x into a string for the join method, but I personally think it's a misuse of repr() and think a call to str() would be more appropriate: >>> ' '.join((str(x * x) for x in range(1,6))) '1 4 9 16 25' From alexandru.palade at sellerengine.com Mon Sep 1 04:21:56 2008 From: alexandru.palade at sellerengine.com (Alexandru Palade) Date: Mon, 01 Sep 2008 11:21:56 +0300 Subject: how to find position of dictionary values In-Reply-To: References: Message-ID: <48BBA624.5010501@sellerengine.com> lookfor = 'dfsdf' for item, value in kev.items(): if lookfor in value: print item print value.index(lookfor) break # assuming you only want one result You can also skip the 'if' verification in which case you need to catch ValueError exception in case there is no such entry in the current list. Hope it helps. lee wrote: > hi, > i have a dictionary as follows : > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > if user is enters the 3rd item of key phno, ie "dfsdf" in my dict, > how can i find it is the third item in the internal list of phno of > that dictionary? thanks you. > -- > http://mail.python.org/mailman/listinfo/python-list > > From mr.spoon21 at gmail.com Sun Sep 14 14:55:02 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 14 Sep 2008 20:55:02 +0200 Subject: Abstract class In-Reply-To: References: Message-ID: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> Gary Harron: >I believe you are mixing up class *inheritance* and *abstract* classes. >Class inheritance (with Python has has for years) is how one class inherits >behavior/properties/attributes from another class. The class being inherited from is >called the base class. This is probably what you want. Well, I know the difference between an abstract class and an inherited one. The idea was to create a main class Note, with abstract methods, and implement these methods in the other classes. On Sun, Sep 14, 2008 at 7:56 PM, Roy Smith wrote: > What properties or behaviors does SharpNote have which NaturalNote doesn't? > Unless there is some new behavior, you don't need subclasses. Well, from a SharpNote I can obtain the relative NaturalNote. So if I have a C# I can call natural('C#') and get 'C' While in the class NaturalNote I don't need such a method, but I need two methods to get the sharped and flatted version > Are you also going to have DoubleSharpNote and DoubleFlatNote? Yes, that's an option. > Consider the following code: > > note1 = SharpNote("E4") > note2 = NaturalNote("F4") > if note1 == note2: > print "the same note" > else > print "different notes" > > what should it print? Well, that's not so simple. The idea is that I use a notation (A, B, C, D...) and an integer (a distance expressed in semitones) to identify a note. Anyway, I think I need an abstract class. Or not? From erexsha at gmail.com Thu Sep 25 16:04:59 2008 From: erexsha at gmail.com (Arash Arfaee) Date: Thu, 25 Sep 2008 13:04:59 -0700 Subject: adding in-place operator to Python In-Reply-To: <266557d0809251303k60d3a52eoc239917bc3597b27@mail.gmail.com> References: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> <266557d0809251303k60d3a52eoc239917bc3597b27@mail.gmail.com> Message-ID: <266557d0809251304q49fec06er436d7b2a1db6b6f7@mail.gmail.com> Thank you very much Gerhard and Terry. I am trying to add undefined state to some Boolean operator. Here is what I tried to do and It is not working: class _3ph: def __init__(self): self.value = 0 def __xor__(self,item): if self.value==2 or item==2: return 2 else: return self.__xor__(item) what I am trying to do is assigning 2 to undefined state and have xor operator return 2 if one of inputs are 2. it seems Although I defined xor in _3ph class, python treat any object from this class just like integer variables. can you help me find what is wrong here? Cheers, Arash On Tue, Sep 23, 2008 at 11:06 AM, Terry Reedy wrote: > Arash Arfaee wrote: > >> Hi All, >> >> Is there anyway to add new in-place operator to Python? Or is there any >> way to redefine internal in-place operators? >> > > Python does not have 'in-place operators'. It has 'augmented assignment > statements' that combines a binary operation with an assignment. *If* the > target being rebound is mutable, *then* (and only then) the operation can be > and is recommended to be done 'in-place'. User-defined mutable classes (as > most are) can implement in-place behavior with __ixxx__ methods. But for > the reason given below, __ixxx__ methods should supplement and not replace > direct mutation methods. > > Correct terminology is important for understanding what augmented > assigments do and what they are basically about. > > First, most augmented assignments target immutables, in particular, numbers > and strings, which do not have __ixxx__ methods. So the operation is *not* > done in-place. The only difference from separately indicating the > assignment and operation is that the programmer writes the target expression > just once and the interpreter evaluates the target expression just once > instead of each repeating themselves. (And consequently, any side-effects > of that evaluation happen just once instead of twice.) The same __xxx__ or > __rxxx__ method is used in either case. This non-repetition is the reason > for augmented assigments. The optional in-place optimization for mutables > is secondary. It was debated and could have been left out. > > Second, all augmented assignments perform an assignment, even if the > operation is done in place. However, if a mutable such as a list is > accessed as a member of an immutable collection such as a tuple, mutation is > possible, but rebinding is not. So the mutation is done and then an > exception is raised. To avoid the exception, directly call a mutation > method such as list.extend. > > Terry Jan Reedy > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From uomiocenekidd at gmail.com Mon Sep 22 06:38:21 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:38:21 -0700 (PDT) Subject: redtube video downloader - Free Message-ID: <41b8a318-c2d6-4c3f-bc57-c573ea5ee7b8@k37g2000hsf.googlegroups.com> redtube video downloader . . . *******CLICK HERE******** http://vids365.cn/redtube-video-downloader ***************************** . . . . . . . . . . . . redtube video downloader From bearophileHUGS at lycos.com Thu Sep 25 16:41:43 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Sep 2008 13:41:43 -0700 (PDT) Subject: Quick sort implementation in python References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: Alex Snast: > However i have no idea how to access the values of a data structure that doesn't allow random access.< Well, a sorting algorithm can work in-place, sorting the position of the items inside the given collection, or it can create a new data structure with the items (in Python all items are references). If the output of the sorting algorithm is an array (that is a python list), and the input isn't a list, then you can list-fy your input data and then sort that list in-place, and return it. Like this def mysort(any_iterable): data = list(any_iterable) # sort data... return data If the input is a list, you can sort it in place. Finally you may want to return other kinds of collections, like sorting a linked list and returning it (you can create a chain of nested lists, and then sort them with a merge sort), but in Python that's not much common. Bye, bearophile From ggpolo at gmail.com Sun Sep 14 09:47:01 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 14 Sep 2008 10:47:01 -0300 Subject: Windows / Tkinter - problem with grid - not able to place widgets at desired places In-Reply-To: <48cce842$0$11367$5fc30a8@news.tiscali.it> References: <48cce842$0$11367$5fc30a8@news.tiscali.it> Message-ID: On Sun, Sep 14, 2008 at 7:32 AM, Francesco Bochicchio wrote: > Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto: > > >>>Hi, >>> >>>I'm learning Python and Tkinter. I've started programming in Eclipse >>>with PyDev. I'm intending to create a GUI. I'm not able to understand >>>the Grid manager perhaps because there is quite a less documentation >>>available for it on the net. >>> >>>My desired GUI is attached in the mail. Although I've tried writing a >>>class module for this GUI but I'm not able to set all things right in >>>the GUI. The Biggest problem seems to be with the Grid Manager in terms >>>how it divides a window in Rows / columns. etc. I'm not able to place >>>none of the widgets correctly in the GUI. >>> >>>For your convenience, I'm attaching this code also as myModule1.py . >>>Please some one review it and help create me this GUI. >>> > > Uhm, I don't think you should use the grid manager to obtain a window > like that. The grid manager is for equally distributing widgets both > horizontally and vertically. > And I'm not sure that you can realize that window look with Tkinter. Yes you can. > You could get close by horizontally packing each widget row in a frame > and then vertically packing the frames in the window. But the look will be > quite different than your target. If you are not satisfied with that I > suggest you move to other toolkits which have more complex geometry > managers than .pack and .grid. Uhm.. I'm sure it is more a question of learning how to use them properly. The following code should be very close to the original request, depending on the tk version some minor modifications may be needed. from Tkinter import Tk, Button, Checkbutton, Label, Entry, Frame class App: def __init__(self, master): column0_padx = 24 row_pady = 36 #Label 1 lbl_testcase_exec = Label(master, text="Test case execution", wraplength=100, anchor='w', justify='left') lbl_results_cmp = Label(master, text="Results comparison", wraplength=100, justify='left') lbl_tolerance = Label(master, text="Tolerance (5%)", wraplength=100) testcase_exec = Checkbutton(master) results_cmp = Checkbutton(master) tolerance = Entry(master, width=4) lbl_analysis = Label(master, text="Analysis Library") analysis_lib = Entry(master, width=30) lbl_testcase_exec.grid(row=0, column=2, padx=20, pady=12, sticky='w') lbl_results_cmp.grid(row=0, column=3, pady=12, sticky='w') lbl_tolerance.grid(row=0, column=4, padx=20, pady=12, sticky='wn') lbl_analysis.grid(row=1, column=0, sticky='w', padx=column0_padx) analysis_lib.grid(row=1, column=1, sticky='w') testcase_exec.grid(row=1, column=2, padx=20, sticky='w') results_cmp.grid(row=1, column=3, sticky='w') tolerance.grid(row=1, column=4, padx=20, sticky='w') #Label 2 lbl_ref_analysis = Label( master, text="Reference Analysis Libary Version", wraplength=150, justify='left', pady=row_pady) ref_analysis_lib = Entry(master, width=30) lbl_ref_analysis.grid(row=2, column=0, sticky='w', padx=column0_padx) ref_analysis_lib.grid(row=2, column=1, sticky='w') # version lbl_version = Label(master, text="Version under Test") version = Label(master, text="vA.B.C.D") lbl_version.grid(row=3, column=0, sticky='w', padx=column0_padx) version.grid(row=3, column=1, sticky='w') # test all lbl_testall = Label(master, text="Test All") testall = Checkbutton(master) lbl_testall.grid(row=4, column=0, pady=row_pady, padx=column0_padx, sticky='w') testall.grid(row=4, column=1, sticky='w') # buttons bottom_frame = Frame(master) bottom_frame.grid(row=5, column=1, columnspan=3, sticky='w') btn_start = Button(bottom_frame, text = "Go", width=7) btn_start.pack(side='left') btn_commit = Button(bottom_frame, text="Commit", width=7) btn_commit.pack(side='left', padx=80) btn_exit = Button(bottom_frame, text="Exit", width=7) btn_exit.pack(side='left') root = Tk() root.title("Test Automation") root.minsize(800, 400) app = App(root) root.mainloop() > > Ciao > ----- > FB > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ivanov.maxim at gmail.com Fri Sep 26 04:52:34 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Fri, 26 Sep 2008 01:52:34 -0700 (PDT) Subject: multiprocessing eats memory References: Message-ID: <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> On 26 ????, 04:20, Istvan Albert wrote: > On Sep 25, 8:40?am, "Max Ivanov" wrote: > > > At any time in main process there are shouldn't be no more than two copies of data > > (one original data and one result). > > From the looks of it you are storing a lots of references to various > copies of your data via the async set. How could I avoid of storing them? I need something to check does it ready or not and retrieve results if ready. I couldn't see the way to achieve same result without storing asyncs set. From usenet.tolomea at gmail.com Mon Sep 8 08:23:11 2008 From: usenet.tolomea at gmail.com (usenet.tolomea at gmail.com) Date: Mon, 8 Sep 2008 05:23:11 -0700 (PDT) Subject: tracking collection modification References: <42d9688f-1058-4ed7-8d9d-affd432fdb41@s1g2000pra.googlegroups.com> Message-ID: On Sep 7, 8:54?pm, usenet.tolo... at gmail.com wrote: > I'm working on a remote object system, something kinda like Pyro. > For the purposes of caching I need to be able to tell if a given > dict / list / set has been modified. > Ideally what I'd like is for them to have a modification count > variable that increments every time the particular collection is > modified. Unfortunately I can't find anything like that and since this > needs to work for the regular normal list / dict / set objects > subclassing them to add the modification count isn't useful. > I realize I could take a copy and then compare the copy to the > original, but that's a fairly heavy handed approach and I was hoping > for something light and fast. > Does anyone have any suggestions on best to approach this? additionally I don't need to know if the things the list (etc) references have changed, only the list itself From tjreedy at udel.edu Tue Sep 16 14:03:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 14:03:34 -0400 Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows In-Reply-To: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> References: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Message-ID: Richard_Martineau at xyratex.com wrote: > Now comes the troubled bit...I now look for similar source code for > Python extensions Numpy and Scipy but the source code and directories > are not all obvious. Looks like these are normally built via other > compilers. However I need to do all my builds in VS 6.0. Numpy/scipy specific questions tend to get more specific answers on the numpy/scipy mailing lists. Or see gmane.comp.python.numeric.general at news.gmane.org From jettgamboa at gmail.com Sun Sep 28 09:00:19 2008 From: jettgamboa at gmail.com (Jett) Date: Sun, 28 Sep 2008 06:00:19 -0700 (PDT) Subject: Mechanize and Yahoo HTTPS Message-ID: Has anybody used the mechanize library with a Yahoo site? I am trying to create a program that will download my player's stats from Yahoo's Fantasy Football site but for some reason could not get it to load the login page. When I run the program below, it prints the word "start" and then does nothing (no exceptions are thrown). ---- code snippet start ---- import re from mechanize import Browser print 'start' br = Browser() response1 = br.open("https://login.yahoo.com/config/login?.done=http:// sports.yahoo.com/fantasy&.src=spt") print br.title() print "end" ---- code snippet end ---- From sturlamolden at yahoo.no Wed Sep 10 14:15:26 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 10 Sep 2008 11:15:26 -0700 (PDT) Subject: NumPy arrays that use memory allocated from other libraries or tools References: Message-ID: <63fac77e-3043-40fa-8f3d-9d751d9a82cf@d1g2000hsg.googlegroups.com> On Sep 10, 6:39?am, Travis Oliphant wrote: > I wanted to point anybody interested to a blog post that describes a > useful pattern for having a NumPy array that points to the memory > created by a different memory manager than the standard one used by > NumPy. Here is something similar I have found useful: There will be a new module in the standard library called 'multiprocessing' (cf. the pyprocessing package in cheese shop). It allows you to crerate multiple processes (as opposed to threads) for concurrency on SMPs (cf. the dreaded GIL). The 'multiprocessing' module let us put ctypes objects in shared memory segments (processing.Array and processing.Value). It has it's own malloc, so there is no 4k (one page) lower limit on object size. Here is how we can make a NumPy ndarray view the shared memory referencey be these objects: try: import processing except: import multiprocessing as processing import numpy, ctypes _ctypes_to_numpy = { ctypes.c_char : numpy.int8, ctypes.c_wchar : numpy.int16, ctypes.c_byte : numpy.int8, ctypes.c_ubyte : numpy.uint8, ctypes.c_short : numpy.int16, ctypes.c_ushort : numpy.uint16, ctypes.c_int : numpy.int32, ctypes.c_uint : numpy.int32, ctypes.c_long : numpy.int32, ctypes.c_ulong : numpy.int32, ctypes.c_float : numpy.float32, ctypes.c_double : numpy.float64 } def shmem_as_ndarray( array_or_value ): """ view processing.Array or processing.Value as ndarray """ obj = array_or_value._obj buf = obj._wrapper.getView() try: t = _ctypes_to_numpy[type(obj)] return numpy.frombuffer(buf, dtype=t, count=1) except KeyError: t = _ctypes_to_numpy[obj._type_] return numpy.frombuffer(buf, dtype=t) With this simple tool we can make processes created by multiprocessing work with ndarrays that reference the same shared memory segment. I'm doing some scalability testing on this. It looks promising :) From gh at ghaering.de Tue Sep 23 07:03:05 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Tue, 23 Sep 2008 13:03:05 +0200 Subject: adding in-place operator to Python In-Reply-To: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> References: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> Message-ID: Arash Arfaee wrote: > Hi All, > > Is there anyway to add new in-place operator to Python? You can't create new syntax, like %= > Or is there any way to redefine internal in-place operators? What you can do is give your objects the ability to use these operators. See http://docs.python.org/ref/numeric-types.html for __iadd_ (+=) and friends. You could implement something like a string buffer this way: class Buffer: def __init__(self): self.buf = [] def __iadd__(self, item): self.buf.append(item) return self def __str__(self): return "".join(self.buf) if __name__ == "__main__": buf = Buffer() buf += "str1" buf += "str2" print str(buf) -- Gerhard From faltet at gmail.com Tue Sep 16 08:58:27 2008 From: faltet at gmail.com (Francesc) Date: Tue, 16 Sep 2008 05:58:27 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> Message-ID: <15ed8d4b-c7bb-4f58-ba36-cbf0f3c585e3@79g2000hsk.googlegroups.com> On 15 Set, 22:09, "Aaron \"Castironpi\" Brady" wrote: > On Sep 15, 4:34 am, Francesc wrote: > > > > > On 12 Set, 14:39, "Aaron \"Castironpi\" Brady" > > wrote: > > > > > A consideration of other storage formats such as HDF5 might > > > > be appropriate: > > > > >http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > > > > There are, of course, HDF5 tools available for Python. > > > > PyTablescame up within the past few weeks on the list. > > > > "When the file is created, the metadata in the object tree is updated > > > in memory while the actual data is saved to disk. When you close the > > > file the object tree is no longer available. However, when you reopen > > > this file the object tree will be reconstructed in memory from the > > > metadata on disk...." > > > > This is different from what I had in mind, but the extremity depends > > > on how slow the 'reconstructed in memory' step is. (Fromhttp://www.pytables.org/docs/manual/ch01.html#id2506782). The > > > counterexample would be needing random access into multiple data > > > files, which don't all fit in memory at once, but the maturity of the > > > package might outweigh that. Reconstruction will form a bottleneck > > > anyway. > > > Hmm, this was a part of a documentation that needed to be updated. > > Now, the object tree is reconstructed in a lazy way (i.e. on-demand), > > in order to avoid the bottleneck that you mentioned. I have corrected > > the docs in: > > >http://www.pytables.org/trac/changeset/3714/trunk > > > Thanks for (indirectly ;-) bringing this to my attention, > > > Francesc > > Depending on how lazy the reconstruction is, would it be possible to > modify separate tables from separate processes concurrently? No, modification of different tables in the same file simultaneously is not supported yet. This is a limitation of the HDF5 library itself. The HDF Group said that they have plans to address this, but this is probably a long-term task. Francesc From darcy at druid.net Thu Sep 4 23:21:37 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 4 Sep 2008 23:21:37 -0400 Subject: Curious: 2134 2004-10-06 08:55:20Z fredrik In-Reply-To: References: Message-ID: <20080904232137.9a1d94d6.darcy@druid.net> On Fri, 5 Sep 2008 04:13:28 +0100 "Akathorn Greyhat" wrote: > I've already fix it, but I don't know what the hell does this line means: > > # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ > It seens curious, isn't it? http://ximbiot.com/cvs/wiki/CVS--Concurrent%20Versions%20System%20v1.12.12.1%3A%20Keyword%20substitution -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From alexandru.mosoi at gmail.com Fri Sep 5 04:17:32 2008 From: alexandru.mosoi at gmail.com (=?UTF-8?Q?Alexandru_Mo=C8=99oi?=) Date: Fri, 5 Sep 2008 01:17:32 -0700 (PDT) Subject: derived classes and __getattr__ Message-ID: i'm facing the following problem: class Base(object): def __getattr__(self, attr): return lambda x: attr + '_' + x def dec(callable): return lambda *args: 'dec_' + callable(*args) class Derived(Base): what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have what_so_ever mumu = dec(Base.mumu) # wrong, base doesn't have mumu any idea how to do this? From grflanagan at gmail.com Fri Sep 19 08:37:44 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Fri, 19 Sep 2008 14:37:44 +0200 Subject: dict generator question In-Reply-To: References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: Boris Borcic wrote: > Gerard flanagan wrote: >> George Sakkis wrote: > .. >>> >>> Note that this works correctly only if the versions are already sorted >>> by major version. >>> >> >> Yes, I should have mentioned it. Here's a fuller example below. >> There's maybe better ways of sorting version numbers, but this is what >> I do. > > Indeed, your sort takes George's objection too litterally, what's needed > for a correct endresult is only that major versions be grouped together, > and this is most simply obtained by sorting the input data in (default) > string order, is it not ? > >> Yes, I see what you mean - the fact that a default sort orders "1.10" before "1.9" doesn't actually matter for the required result. >> >> datadict = \ >> dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) And, s[:3] is wrong. So: data.sort() datadict = \ dict((k, len(list(g))) for k,g in groupby(data, lambda s: '.'.join(s.split('.',2)[:2]))) should work, I hope. Cheers, Gerard From akineko at gmail.com Tue Sep 16 04:48:02 2008 From: akineko at gmail.com (akineko) Date: Tue, 16 Sep 2008 01:48:02 -0700 (PDT) Subject: A unique instance of Python GUI program Message-ID: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Hello everyone, This may not be a Python specific challenge. I have a GUI program written in Python + Tkinter. It works very well. Now, I would like to start it from a shell script. As my GUI program includes a server, it should not have more than one instance. Is there any easy way to check if another instance of the program is already running. I vaguely remember that Windows programming provides a way to check. A platform independent approach would be nice but a solution for X is sufficient for my application. Any comments will be greatly appreciated. Best regards, Aki Niimura From steve at REMOVE-THIS-cybersource.com.au Tue Sep 30 19:40:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 23:40:22 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6ke1i8F7dmkkU2@mid.uni-berlin.de> <6kernnF7dmkkU3@mid.uni-berlin.de> Message-ID: <00f2b28e$0$20617$c3e8da3@news.astraweb.com> On Tue, 30 Sep 2008 14:34:31 +0000, Marc 'BlackJack' Rintsch wrote: > On Tue, 30 Sep 2008 15:42:58 +0200, Ivan Reborin wrote: > >> On 30 Sep 2008 07:07:52 GMT, Marc 'BlackJack' Rintsch >> wrote: >>>===== >>>from __future__ import with_statement from functools import partial >>>from itertools import islice >>>from pprint import pprint >>> >>> >>>def read_group(lines, count): >>> return [map(int, s.split()) for s in islice(lines, count)] >>> >>>def main(): >>> with open('test.txt') as lines: >>> lines = (line for line in lines if line.strip()) >>> result = list(iter(partial(read_group, lines, 3), list())) >>> pprint(result, width=30) >>> >>>if __name__ == '__main__': >>> main() >>>===== >> >> I'm afraid I must admit I find the code above totally uncomprehesible >> (I can't even see where the array here is mentioned - "result"?) and >> inpractical for any kind of engineering practice I had in mind. > > Learn Python then to understand that code. ;-) > > There is no array. The data type is called "list" in Python, so > `result` is a nested list. And in Python it quite unusual to build > lists by creating them with the final size filled with place holder > objects and then fill the real values in. Instead lists are typically > created by appending values to existing lists, using list comprehension > or the `list()` function with some iterable object. I would weaken that claim a tad... I'd say it is "usual" to write something like this: alist = [] for x in some_values: alist.append(something_from_x) but it is not uncommon (at least not in my code) to write something like this equivalent code instead: alist = [None]*len(some_values) for i, x in enumerate(some_values): alist[i] = something_from_x Most often the first way is most natural, but the second way is sometimes more natural. It will also be more familiar to somebody coming from Fortran, and it is a micro-optimization for large lists because it doesn't need to resize the list as it grows. I stress the *micro*-optimization, because Python lists are highly optimized to resize as rarely as possible and as quickly as possible, so you're not saving much time. And Marc, I think you're being a little unfair to the OP, who is clearly unfamiliar with Python. I've been using Python for perhaps ten years, and I still find your code above dense and hard to comprehend. It uses a number of "advanced Python concepts" that a newbie is going to have trouble with: - the with statement acts by magic; if you don't know what it does, it's an opaque black box. - you re-use the same name for different uses, which can cause confusion. - generator expressions. - functional programming using partial. - you call a function that uses a list comprehension with both map and iterator slicing inside it. No wonder the OP had trouble with it. *I* have trouble with it, and would need to sit down at the interactive interpreter and play around with it for a while to be sure what it actually does. If it was your intention to make Python look as obtuse and mysterious as possible, you almost succeeded. The one things you missed was to replace the read_group function with a lambda in the partial. -- Steven From fredrik at pythonware.com Wed Sep 10 14:55:59 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 20:55:59 +0200 Subject: Simple UDP server In-Reply-To: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> Message-ID: Tzury Bar Yochay wrote: > Would the one below will be capable of holding 30 concurrent > connections? UDP is a connectionless datagram protocol, so that question doesn't really make much sense. From dmitrey.kroshko at scipy.org Wed Sep 17 15:41:17 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Wed, 17 Sep 2008 12:41:17 -0700 (PDT) Subject: PYPI, some troubles Message-ID: hi all, 1. when I commit a new release to PYPI, I can use stored data (by my browser: Name, package summary, keywords etc), but in the last line (classification) I had to chose all those lines from the very beginning, moreover, if I click at one of them without pressing "CTRL" all my choices drops & I have to type it from the very beginning (I use Mozilla Firefox 3.0 but I don't think it's the matter). 2. Another issue: I have attached my source code (openopt0.19.tar.bz2 file), now I can see it in "files for openopt 0.19" section (http:// pypi.python.org/pypi) but easy_install can't find the package: # easy_install openopt Searching for openopt Reading http://pypi.python.org/simple/openopt/ Couldn't find index page for 'openopt' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http://pypi.python.org/simple/ Reading http://pypi.python.org/simple/OpenOpt/ Reading http://scipy.org/scipy/scikits/wiki/OpenOpt No local packages or download links found for openopt error: Could not find suitable distribution for Requirement.parse('openopt') Does anyone know what shoul I do? Thank you in advance, Dmitrey From bdesth.quelquechose at free.quelquepart.fr Sun Sep 14 11:33:20 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Sep 2008 17:33:20 +0200 Subject: Abstract class In-Reply-To: References: Message-ID: <48cd4aae$0$12641$426a74cc@news.free.fr> Mr.SpOOn a ?crit : > Hi, > I'm going to work on a project to represent some musical theory in > Python, in an object oriented way. > > I have to manage many elements of music such as notes, intervals, > scales, chords and so on. All these elements share properties and > behavior, so what I want to do is an abstract class "Note" and other > subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. > > The idea is not original, I read it in some papers where they talk > about an implementation in smalltalk. > > I want to use Python (of course) and I'd like to know what is the > practice in such a case. I mean, in python there aren't abstract > classes, but I read about some way to emulate the same behavior. > > What do you suggest me? Conceptually, an abstract class is a class that is not intented to be instanciated directly but used as a parent class. The simplest way to get such behaviour is to just write your base class and avoid instanciating it. From bearophileHUGS at lycos.com Mon Sep 22 07:21:12 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 04:21:12 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <00e45101$0$20331$c3e8da3@news.astraweb.com> Message-ID: <773db59e-40c6-470e-b616-ca8715efa46a@d77g2000hsb.googlegroups.com> Steven D'Aprano: >Extending len() to support iterables sounds like a good idea, except that it's not.< Python language lately has shifted toward more and more usage of lazy iterables (see range lazy by default, etc). So they are now quite common. So extending len() to make it act like leniter() too is a way to adapt a basic Python construct to the changes of the other parts of the language. In languages like Haskell you can count how many items a lazy sequence has. But those sequences are generally immutable, so they can be accessed many times, so len(iterable) doesn't exhaust them like in Python. So in Python it's less useful. This is a common situation where I can only care of the len of the g group: [leniter(g) for h,g in groupby(iterable)] There are other situations where I may be interested only in how many items there are: leniter(ifilter(predicate, iterable)) leniter(el for el in iterable if predicate(el)) For my usage I have written a version of the itertools module in D (a lot of work, but the result is quite useful and flexible, even if I miss the generator/iterator syntax a lot), and later I have written a len() able to count the length of lazy iterables too (if the given variable has a length attribute/property then it returns that value), and I have found that it's useful often enough (almost as the string.xsplit()). But in Python there is less need for a len() that counts lazy iterables too because you can use the following syntax that isn't bad (and isn't available in D): [sum(1 for x in g) for h,g in groupby(iterable)] sum(1 for x in ifilter(predicate, iterable)) sum(1 for el in iterable if predicate(el)) So you and Python designers may choose to not extend the semantics of len() for various good reasons, but you will have a hard time convincing me it's a useless capability :-) Bye, bearophile From tjreedy at udel.edu Tue Sep 16 13:31:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 13:31:40 -0400 Subject: append on lists In-Reply-To: <200809161610.50245.maric@aristote.info> References: <200809161610.50245.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit : >> On 2008-09-16, Maric Michaud wrote: >>> all expressions that return something, return a new object, >> That's not _quite_ true: >>>>> a=1 >>>>> b=a.__add__(0) >>>>> a is b >> True >> >> ;) > > This is implementation specific, the specification of the language says that > it should be false, Please quote the section of the manual that says this. > and it is for higher numbers : Agaiin, this is implementation specific. An implementation would be free to special-case any or all of +a, a+0, a-0, a*1, a//1, a**1, a<<0, a>>0, and a|0 and return a. That CPython only optimizes the first is a judgment that the other cases are too rare to bother with. > Don't disturb our OP, with side questions, please, it was enough hard like > this ;) Stop peddling false information. For immutable objects, identity is irrelevant except for id and is. tjr From info at egenix.com Thu Sep 25 09:57:28 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 25 Sep 2008 15:57:28 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.7.0-0.9.8i-1 Message-ID: <48DB98C8.5000703@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.7.0-0.9.8i-1 An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.7.0-0.9.8i-1-GA.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/) that allows writing SSL aware networking applications as well as certificate management tools. OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS This second release of the eGenix.com pyOpenSSL Distribution upgrades the included OpenSSL library version to the latest 0.9.8i, which includes several bug fixes over the previously included 0.9.8h version. The release also includes Python 2.6 support for the first time. Binaries are available for Linux x86 and x64 as well as Windows x86. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 25 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From sh006d3592 at blueyonder.co.uk Sun Sep 14 15:49:24 2008 From: sh006d3592 at blueyonder.co.uk (Stephen Horne) Date: Sun, 14 Sep 2008 20:49:24 +0100 Subject: Abstract class References: Message-ID: On Sun, 14 Sep 2008 18:03:23 +0200, Mr.SpOOn wrote: >I have to manage many elements of music such as notes, intervals, >scales, chords and so on. All these elements share properties and >behavior, so what I want to do is an abstract class "Note" and other >subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. First off, one approach in Python is to not have a base class at all. You don't need a base class just to implement a shared interface, basically. If it walks like a duck and quacks like a duck, you can usually treat it like a duck, as I think the Ruby crowd say. Second, it's possible to overdo object orientation, which is probably Roy Smiths point. Sometimes, the easiest thing to do is to use a simple integer representation of your values. With dates, you'd probably use a Julian day number. That's what spreadsheets usually do, for instance. With music notes, you'd probably use the note numbers that MIDI uses. http://www.harmony-central.com/MIDI/Doc/table2.html You can always extend the range beyond those notes that MIDI supports if needed. Doing this means you can switch octaves or transpose using simple additions or subtractions, for instance. Notes can be decoded using rounded integer division to find the octave number and the remainder/modulo % operator (plus maybe a look-up table) to identify the note. Use // for integer division (rounded toward -infinity IIRC) or you risk problems going from Python 2 to Python 3 - the semantics for the / division operator are changing. Up until now it would round integer divisions, but in future it will be considered a "true" non-rounding division. This may not work, though, if you aren't working with the even-tempered scale (if I got that right). There are times when C-sharp is not the same as D-flat, as MIDI assumes. You may want to wrap the value in a class, but as far as possible all your calculations would be based on the integers. Chords might be represented using either a list or a set - my Python's a little rusty ATM but IIRC there's a set type based on a dictionary. If you're a bit-twiddling fan, you might even use a bitvector approach (I don't think theres a specialised set-of-unsigned-integers bit-vector class in the library, but I could be wrong). But for most purposes, you'd probably want the spec. for the chord - "C major" rather than "C, E, G". In situations like this, it's sometimes useful to have simple functions in a module, or else a 'tool' class (which works on the values, but only encapsulates the tools own state). You can still wrap the values in a class with a common interface. The point of this is that it's relatively easy to share functionality when you implement some value-wrapper classes in several different ways - e.g. note-set chords vs. specification-based chords, note-number representations vs. string representations, etc. That is, in object oriented theory, the object manipulates itself - but that doesn't always work so well in practice, especially for functions that deal with two or more objects. As in the real world, a tool sometimes works better. And if the tool doesn't need any state, it may as well be a single procedure/function in a module rather than a class. From ewertman at gmail.com Tue Sep 2 14:13:47 2008 From: ewertman at gmail.com (Eric Wertman) Date: Tue, 2 Sep 2008 14:13:47 -0400 Subject: Large amount of files to parse/organize, tips on algorithm? In-Reply-To: <6dc5719f-a65b-4194-b09c-b9bbb55ee788@e53g2000hsa.googlegroups.com> References: <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> <6dc5719f-a65b-4194-b09c-b9bbb55ee788@e53g2000hsa.googlegroups.com> Message-ID: <92da89760809021113x1000cd58y9ba55ab2fa517f33@mail.gmail.com> I think you really want use a relational database of some sort for this. On Tue, Sep 2, 2008 at 2:02 PM, cnb wrote: > over 17000 files... > > netflixprize. > -- > http://mail.python.org/mailman/listinfo/python-list > From diordna at gmail.com Wed Sep 10 22:11:56 2008 From: diordna at gmail.com (Stephen Johnson) Date: Wed, 10 Sep 2008 22:11:56 -0400 Subject: Logix - gone? In-Reply-To: References: <276719.72706.qm@web95107.mail.in2.yahoo.com> <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> Message-ID: <12CD696C-D900-40AD-ABE3-4611D7D81B1F@gmail.com> > Ummmm .... try the download link; it worked for me. Oops. You just found my daily stupid. However, I still wish the Trac link worked, and I would prefer the participation of the original dev to forking it. -Steve Johnson From Eric_Dexter at msn.com Mon Sep 8 21:31:33 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 8 Sep 2008 18:31:33 -0700 (PDT) Subject: Problems downloading and installing win32api References: <968dca58-0172-4953-b8d6-9610f0570fe8@s20g2000prd.googlegroups.com> Message-ID: <6e53ed31-498b-4e52-b0d1-d3ed1c34efa5@l64g2000hse.googlegroups.com> On Sep 8, 2:41?pm, Emile van Sebille wrote: > brianrpsgt1 wrote: > > I have attempted downloading and installing several different version > > of the win32api from Source Forge, > > Whe win32 tools come bundled with ActiveState's python distribution. > > Maybe that'll move you forward... > > Emile > > ? however, each time I try to install > > > > > I get the following error message: > > > "Only part of a ReadProcessMemory or WriteProcessMemory request was > > completed" > > > This occurred with the following files: > > pywin32-212.win32-py2.4.exe > > pywin32-212.win32-py2.5.exe > > pywin32-212.win32-py2.6.exe > > > I am using WinXP SP2. ?Any assistance on getting this downloaded and > > installed would be great. > > > Thanks > > > B > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - I may have a copy if it is legal to distribute I will post it if you still need it. You will notice that sourceforge has changed the way they are doing things. As you may know they are a money loosing public company and to help combat this they have changed thier website to show less advertising and have cut the projects off from thier home page. They are offering services now to help you do what is listed on the original web site..... You may have other things that don't work also. I have a slow connection so tell me if you can't find it somewhere else first. From bearophileHUGS at lycos.com Wed Sep 3 17:56:36 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 14:56:36 -0700 (PDT) Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> <7f2d4b4a-bc97-4b46-a31e-63f98e9fee73@34g2000hsh.googlegroups.com> Message-ID: Roy Smith: > But, along those lines, I've often thought that split() needed a way to not > just limit the number of splits, but to also throw away the extra stuff. > Getting the first N fields of a string is something I've done often enough > that refactoring the slicing operation right into the split() code seems > worthwhile. And, it would be even faster :-) Given the hypothetical .xsplit() string method I was talking about, it's then easy to use islice() on it to skip the first items: islice(sometext.xsplit(), 10, None) Bye, bearophile From cipherzero at gmail.com Sun Sep 7 00:50:47 2008 From: cipherzero at gmail.com (cipher) Date: Sat, 6 Sep 2008 21:50:47 -0700 (PDT) Subject: Setter Propertys' mro? References: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> <00d34e8d$0$30713$c3e8da3@news.astraweb.com> Message-ID: <21655332-7ad8-4d8c-a554-6cdc0cb2a872@a3g2000prm.googlegroups.com> On Sep 6, 9:10?pm, Steven D'Aprano wrote: > On Sat, 06 Sep 2008 18:15:33 -0700, cipher wrote: > > Whats the mro (method resolution order) of a setter property (__set__ on > > a descriptor). > > i seem to be experiencing some weird issue with them. for example > > >>>> class test: > > Unless you're using Python 3, there's your problem right there. In Python > 2.x, properties only work correctly for new style classes, not classic > classes. Change the above line to: > > class Test(object): ?# by convention, classes start with Uppercase. > > and all should work (or at least you'll discover new and exciting > different problems with your code). > > > however, if i specify the metaclass in the class definition it works > > just fine... > > > class test: > > ?__metaclass__=type > > which is more or less the same as inheriting from object, except uglier. > > -- > Steven Thanks to both of you!! that solved it. i wonder why the getters would work fine though?? neways, wtf do i care :) again, thank you both. __ Cipher From fredrik at pythonware.com Thu Sep 11 08:39:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 14:39:10 +0200 Subject: problem with interpreter In-Reply-To: <04e1cbd4-7116-4209-b814-6d34e4d24975@l42g2000hsc.googlegroups.com> References: <04e1cbd4-7116-4209-b814-6d34e4d24975@l42g2000hsc.googlegroups.com> Message-ID: chusky wrote: > File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", > line 5, in < > module> > import new > File "new.py", line 1 > import > ^ > SyntaxError: invalid syntax wxPython tries to import the module "new" from Python's standard library, but picks up a broken module named "new.py" from your development directory instead. From uomiocenekidd at gmail.com Mon Sep 22 06:38:59 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:38:59 -0700 (PDT) Subject: imagefap showfavorites - Free Message-ID: imagefap showfavorites . . . *******CLICK HERE******** http://vids365.cn/imagefap-showfavorites ***************************** . . . . . . . . . . . . imagefap showfavorites From clp at rebertia.com Wed Sep 24 17:19:03 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 24 Sep 2008 14:19:03 -0700 Subject: Schwartzian transform for tuple in list In-Reply-To: References: Message-ID: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase wrote: > Hi, > > I have a rather large list structure with tuples contained in them (it's > part of a specification I received) looks like so: > [(x1,y1,r1,d1),(x2,y2,r2,d2)...] > > The list can range from about 800-1500 tuples in size and I'm currently > sorting it with this: > > a_list.sort(lambda a, b: cmp(b[3], a[3])) You'd probably be better off using the 'key' keyword argument to .sort(), which is made for the Schwartzian Transform: a_list.sort(key=lambda x: x[3]) This sorts the list items by the value produced by the key function for each item. It's also (IIRC) faster than using a comparison function like you're currently doing. Regards, Chris > > I'm actually sorting it by the last value in the tuple (d2). I have been > researching more efficient sorting algorithms and came across Schwartzian > transform via these links: > > http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency > http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html > > I get what's happening (sorta...errr...lol) but I'm not sure if it is more > efficient in my scenario, if it is then I have no idea how to implement it > properly :-/ > > Would be great if a true expert would offer a suggestion for me... > > Thanks! > > David > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From ce at mail.net.sk Thu Sep 11 22:28:24 2008 From: ce at mail.net.sk (Mahdi) Date: Fri, 12 Sep 2008 10:28:24 +0800 Subject: wx References: Message-ID: if you just type "python wx" you will get 2,080,000 results. The first by luck (not chance) is wxPython. it scares me when ppl start to post on newsgroups before even searching in the web for a second! how old r u Mr. Chance not Choice? on 09/12/2008 02:32 AM Fredrik Lundh wrote : > Desmond Scott E wrote: > > I'm am a Python novice by chance not choice. (Although it appears to > be a nice tool. Plus anything based on Monte Python can't be bad!) > > My Quest is to migrate a Python-based process from Windows2000/Python > v2.4.2 (#67) to WindowsXP/Python v2.5.2 (r252:60911). > > I've searched the Python website and could find no reference to module > wx. Is this an add-in module or perhaps it was replaced in v2.5.2??? > From michel at nospam.please Sun Sep 28 13:04:04 2008 From: michel at nospam.please (Michel Leunen) Date: Sun, 28 Sep 2008 19:04:04 +0200 Subject: destructor not called In-Reply-To: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> Message-ID: <48dfb904$0$2851$ba620e4c@news.skynet.be> Marcin201 a ?crit : > class Foo: > def __init__(self): > print "Hello" > self.f = self.fxn Maybe self.f = self.fxn() is what you want. Note the '()'. -- Michel Leunen http://linux.leunen.com From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 04:05:20 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 10:05:20 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <00eaee25$0$20666$c3e8da3@news.astraweb.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> Message-ID: <48db462f$0$24356$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote: > >> Plenty of people were quick to say that the exception should be passed >> through to the caller. No one said this behaviour should be documented. >> There may be little practical difference bewteen calling sys.exit() >> after printing an error and progating an exception if no one using the >> library knows that it could generate that exception in those >> circumstances. > > That's true, I didn't explicitly say that the library should be > documented. Nor did I say that it shouldn't be riddled with bugs. There's > little practical difference between a buggy library and one that raises > unexpected (i.e. undocumented) exceptions either. Also note that there are quite a couples cases where the library authors themselves cannot predict which exception types may be raised - as soon as the library functions expect callback functions, file-like or dict-like or whatever-like objects etc, it's the caller's responsability to handle the exceptions that may be raised by what *he* passes to the library... From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 04:08:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 10:08:09 +0200 Subject: How to parse a string completely into a list In-Reply-To: References: Message-ID: <48db46d6$0$24356$426a74cc@news.free.fr> john.ford at colorado.edu a ?crit : > I want to take a long alpha-numeric string with \n and white-space and > place ALL elements of the string (even individual parts of a long > white-space) into separate list elements. The most common way I've > seen this performed is with the split() function, however I don't > believe that it has the power to do what I am looking for. > Any suggestions? Did you try passing your string to the list() type ? Python 2.5.1 (r251:54863, Mar 7 2008, 03:41:45) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = """I want to take a long alpha-numeric string with \n and white-space and ... place ALL elements of the string (even individual parts of a long ... white-space) into separate list elements. The most common way I've ... seen this performed is with the split() function, however I don't ... believe that it has the power to do what I am looking for. ... Any suggestions? ... thanks ... """ >>> >>> s "I want to take a long alpha-numeric string with \n and white-space and\nplace ALL elements of the string (even individual parts of a long\nwhite-space) into separate list elements. The most common way I've\nseen this performed is with the split() function, however I don't\nbelieve that it has the power to do what I am looking for.\nAny suggestions?\nthanks\n" >>> list(s) ['I', ' ', 'w', 'a', 'n', 't', ' ', 't', 'o', ' ', 't', 'a', 'k', 'e', ' ', 'a', ' ', 'l', 'o', 'n', 'g', ' ', 'a', 'l', 'p', 'h', 'a', '-', 'n', 'u', 'm', 'e', 'r', 'i', 'c', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', 'w', 'i', 't', 'h', ' ', '\n', ' ', 'a', 'n', 'd', ' ', 'w', 'h', 'i', 't', 'e', '-', 's', 'p', 'a', 'c', 'e', ' ', 'a', 'n', 'd', '\n', 'p', 'l', 'a', 'c', 'e', ' ', 'A', 'L', 'L', ' ', 'e', 'l', 'e', 'm', 'e', 'n', 't', 's', ' ', 'o', 'f', ' ', 't', 'h', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', '(', 'e', 'v', 'e', 'n', ' ', 'i', 'n', 'd', 'i', 'v', 'i', 'd', 'u', 'a', 'l', ' ', 'p', 'a', 'r', 't', 's', ' ', 'o', 'f', ' ', 'a', ' ', 'l', 'o', 'n', 'g', '\n', 'w', 'h', 'i', 't', 'e', '-', 's', 'p', 'a', 'c', 'e', ')', ' ', 'i', 'n', 't', 'o', ' ', 's', 'e', 'p', 'a', 'r', 'a', 't', 'e', ' ', 'l', 'i', 's', 't', ' ', 'e', 'l', 'e', 'm', 'e', 'n', 't', 's', '.', ' ', 'T', 'h', 'e', ' ', 'm', 'o', 's', 't', ' ', 'c', 'o', 'm', 'm', 'o', 'n', ' ', 'w', 'a', 'y', ' ', 'I', "'", 'v', 'e', '\n', 's', 'e', 'e', 'n', ' ', 't', 'h', 'i', 's', ' ', 'p', 'e', 'r', 'f', 'o', 'r', 'm', 'e', 'd', ' ', 'i', 's', ' ', 'w', 'i', 't', 'h', ' ', 't', 'h', 'e', ' ', 's', 'p', 'l', 'i', 't', '(', ')', ' ', 'f', 'u', 'n', 'c', 't', 'i', 'o', 'n', ',', ' ', 'h', 'o', 'w', 'e', 'v', 'e', 'r', ' ', 'I', ' ', 'd', 'o', 'n', "'", 't', '\n', 'b', 'e', 'l', 'i', 'e', 'v', 'e', ' ', 't', 'h', 'a', 't', ' ', 'i', 't', ' ', 'h', 'a', 's', ' ', 't', 'h', 'e', ' ', 'p', 'o', 'w', 'e', 'r', ' ', 't', 'o', ' ', 'd', 'o', ' ', 'w', 'h', 'a', 't', ' ', 'I', ' ', 'a', 'm', ' ', 'l', 'o', 'o', 'k', 'i', 'n', 'g', ' ', 'f', 'o', 'r', '.', '\n', 'A', 'n', 'y', ' ', 's', 'u', 'g', 'g', 'e', 's', 't', 'i', 'o', 'n', 's', '?', '\n', 't', 'h', 'a', 'n', 'k', 's', '\n'] >>> HTH From tim.arnold at sas.com Wed Sep 24 13:37:52 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 24 Sep 2008 13:37:52 -0400 Subject: multiple processes with private working dirs Message-ID: I have a bunch of processes to run and each one needs its own working directory. I'd also like to know when all of the processes are finished. (1) First thought was threads, until I saw that os.chdir was process-global. (2) Next thought was fork, but I don't know how to signal when each child is finished. (3) Current thought is to break the process from a method into a external script; call the script in separate threads. This is the only way I can see to give each process a separate dir (external process fixes that), and I can find out when each process is finished (thread fixes that). Am I missing something? Is there a better way? I hate to rewrite this method as a script since I've got a lot of object metadata that I'll have to regenerate with each call of the script. thanks for any suggestions, --Tim Arnold From aioe.org at technicalbloke.com Thu Sep 18 00:35:36 2008 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 18 Sep 2008 00:35:36 -0400 Subject: A unique instance of Python GUI program References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> <0643c0e0-a9c0-4a46-8cb8-7c37a9ebcc07@w39g2000prb.googlegroups.com> Message-ID: akineko wrote: > Again, thank you for many postings to my question. > I have reviewed solutions provided. > Well, I like the named Mutex solution under Windows. > That is a clean and straight-forward approach to the challenge. > (I cannot believe that I'm saying good thing about Windows ;-) ) > > Unfortunately, I'm living in Unix realm ;-) > > None of solutions for Unix are appealing to me. > But they must be "the" solution for the challenge as well-established > software uses those solutions. > > Now, I'm wondering. > As my program is a GUI (Tkinter) software. > Is it possible to set a known value to X11 or Tk property through > Tkinter so that another instance of the program can check if such > property is set? > > Of course, I know this scheme has a flaw. If one instance uses another > logical display, then such property is probably not shared. > But for my usage, it is logically possible but not likely. > > I checked my Tkinter book and found the following function. > winfo_interps(displayof=0) > > This returns a list of all Tk-based applications currently running on > the display. > > When I tried, I got the following: >>>> root.winfo_interps() > ('tk #3', 'tk #2', 'tk') > > But I couldn't find a way to set a specific name to the Tcl > interpreter. > > As I'm not an expert of Tcl/Tk and X11, I probably overlooked other > functions that may do what I need. > > Any comments, suggestions on this? > Maybe this can provide a platform independent way to ensure that only > single instance is running. > > Thank you for your attention. > > Best reagrds, > Aki Niimura I know it's a hack but couldn't you just open a specific UDP socket and leave it dangling til your program exits, then if a new instance can't open that same socket it can gracefully abort? If your program dies the socket will be freed up again by the OS yes? Just a thought. Roger. From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 2 10:06:48 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 02 Sep 2008 16:06:48 +0200 Subject: what's the difference between f(a) and f(*a) In-Reply-To: <4b57d4c3-a398-41b1-916a-064ee96bf3f6@25g2000prz.googlegroups.com> References: <4b57d4c3-a398-41b1-916a-064ee96bf3f6@25g2000prz.googlegroups.com> Message-ID: <48bd481e$0$17215$426a74cc@news.free.fr> qxyuestc at yahoo.cn a ?crit : > def sum1(*a): return(sum(i*i for i in a)) > def sum2(a): return(sum(i*i for i in a)) > > a=[1,2,3] > print(sum1(*a), sum2(a)) > #################################### > showed above: the result from sum1() and sum2() is the same. So, what > is the difference between f(a) and f(*a) try this: sum1(a) sum2(*a) Then re-read the FineManual(tm): http://docs.python.org/tut/node6.html#SECTION006730000000000000000 From sotirac at gmail.com Sun Sep 28 15:59:53 2008 From: sotirac at gmail.com (sotirac) Date: Sun, 28 Sep 2008 12:59:53 -0700 (PDT) Subject: generate random digits with length of 5 Message-ID: Wondering if there is a better way to generate string of numbers with a length of 5 which also can have a 0 in the front of the number.
 random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
elements
 code = 'this is a string' + str(random_number[0]) +
str(random_number[1]) + str(random_number[2]) + str(random_number[3])
+ str(random_number[4])
From garyrob at mac.com Mon Sep 8 13:46:08 2008 From: garyrob at mac.com (Gary Robinson) Date: Mon, 08 Sep 2008 13:46:08 -0400 Subject: exit() Message-ID: <20080908134608759530.9d832e42@mac.com> In Python 2.5.2, I notice that, in the interpreter or in a script, I can exit with: exit() But I don't see exit() mentioned as a built-in function; rather the Python Library Reference says we should use sys.exit(). Also, the reference says sys.exit() is like raising SystemExit. But so is just calling exit(). For instance, exit('some error message') has the same apparent effect as raise SystemExit, 'some error message'. Both return a status code of 1 and print the error string on the console. Is exit() documented somewhere I haven't been able to find? Is there any reason to use sys.exit() given exit()'s availability? If there is an advantage to sys.exit() over exit(), then does sys.exit() have any advantage over "raise SystemExit, 'some error message'" in cases where a module has no other reason to import sys? -- Gary Robinson CTO Emergent Music, LLC personal email: garyrob at mac.com work email: grobinson at emergentmusic.com Company: http://www.emergentmusic.com Blog: http://www.garyrobinson.net From rocksportrocker at googlemail.com Tue Sep 9 15:50:45 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 9 Sep 2008 12:50:45 -0700 (PDT) Subject: F2PY changing integers to arrays??? References: <7d60c85f-12cf-47fc-84c9-58e50cad4eaf@x35g2000hsb.googlegroups.com> Message-ID: On 9 Sep., 18:41, john wrote: > I have a simple module which performs basic operations on plot3d files > (below). ?I wrapped like: > > f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 > > That seems to work fine, but i get some unexpected results... > > >>> from plot3d import plot3d as p3 > >>> dir(p3) > > ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', > 'writeit2d']>>> p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) > >>> p3.imax > > array(409) > > "409" is correct, but "imax" is declared as an INTEGER in fortran and > now it's an array in python??? ?Any ideas? > > # prec.f90 > MODULE prec > IMPLICIT NONE > INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) > INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) > END MODULE prec > > # plot3d.f90 > MODULE PLOT3D > USE prec > IMPLICIT NONE > INTEGER, PARAMETER :: prc=single > REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z > INTEGER :: mg, imax, jmax, kmax > > CONTAINS > > !---------- > ? ? SUBROUTINE READIT( fname, ftype, fmg ) > ? ? ! reads the plot3d, formatted, mg file in xyz > ? ? IMPLICIT NONE > ? ? CHARACTER(len=20), INTENT(IN) :: fname, ftype > > ? ? LOGICAL :: fmg > ? ? INTEGER :: i, j, k, n, f=1 > > ? ? SELECT CASE (ftype) > ? ? ? ? CASE ('FORMATTED') > ? ? ? ? ? ? OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > ? ? ? ? ? ? IF (fmg) READ(f,*) mg ! only read if multigrid > ? ? ? ? ? ? READ(f,*) imax, jmax, kmax > ? ? ? ? ? ? ALLOCATE( x(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? ALLOCATE( y(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? ALLOCATE( z(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? READ(f,*) ((((x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ? ? ? ? ? ? ? ? ? ? ? ((((y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ? ? ? ? ? ? ? ? ? ? ? ((((z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > ? ? ? ? CASE ('UNFORMATTED') > ? ? ? ? ? ? OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > ? ? ? ? ? ? IF (fmg) READ(f) mg ! only read if multigrid > ? ? ? ? ? ? READ(f) imax, jmax, kmax > ? ? ? ? ? ? ALLOCATE( x(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? ALLOCATE( y(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? ALLOCATE( z(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? READ(f) ((((x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ? ? ? ? ? ? ? ? ? ? ((((y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ? ? ? ? ? ? ? ? ? ? ((((z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > ? ? ? ? CASE DEFAULT > ? ? ? ? ? ? WRITE(*,*) 'filetype not supported in ' > ? ? ? ? ? ? STOP > ? ? END SELECT > > ? ? CLOSE(f) > > ? ? END SUBROUTINE READIT > > END MODULE PLOT3D You can generate the according .pyf file with some command line flag I forgot. There you can see what the parser derived from the fortran code and you can edit this file for further configuration of the generated python module. Greetings, Uwe From wuwei23 at gmail.com Sun Sep 28 20:33:47 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 28 Sep 2008 17:33:47 -0700 (PDT) Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> <357e734f-e99f-41e5-9cac-083d636a23e1@n38g2000prl.googlegroups.com> Message-ID: <95f8433c-213f-4b3a-8d93-bebbe2561e7f@s9g2000prg.googlegroups.com> On Sep 29, 5:52?am, robean wrote: > Actually, the problem seems to be that IOError is in my namespace, but > the other error classes are not. So, > > ? ?except HTTPError, etc. > > fails, but > > ? ?except urllib2.HttpError, etc. > > works fine. Now, I still don't understand why these classes shouldn't > automatically work.... IOError is a standard Python exception. HTTPError & URLError are exceptions provided by the urllib2 module. They need to be imported from or referenced through urllib2 to be used. From see.signature at no.spam Wed Sep 24 04:19:35 2008 From: see.signature at no.spam (Eric Brunel) Date: Wed, 24 Sep 2008 10:19:35 +0200 Subject: Python is slow? References: Message-ID: On Tue, 23 Sep 2008 15:23:12 +0200, sturlamolden wrote: [...] Would it be possible to post this text to some "persistent" web page with (links to) the code you wrote in both languages? This would be a very interesting resource for people experiencing some resistence when they suggest Python as a possible language because of the 'Python is slow' myth... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From dave.dibiase at gmail.com Wed Sep 24 18:45:35 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Wed, 24 Sep 2008 18:45:35 -0400 Subject: Schwartzian transform for tuple in list In-Reply-To: <48DAB539.1010500@mattnordhoff.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> Message-ID: <7C3B1753-3E7A-4E1F-B102-3387FB0152A4@gmail.com> When you say slightly, is it enough to make a difference? Why would getitems be faster even - not sure I can think why... Sent from my iPhone On 24-Sep-08, at 5:46 PM, Matt Nordhoff wrote: > Chris Rebert wrote: >> On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase > > wrote: >>> Hi, >>> >>> I have a rather large list structure with tuples contained in them >>> (it's >>> part of a specification I received) looks like so: >>> [(x1,y1,r1,d1),(x2,y2,r2,d2)...] >>> >>> The list can range from about 800-1500 tuples in size and I'm >>> currently >>> sorting it with this: >>> >>> a_list.sort(lambda a, b: cmp(b[3], a[3])) >> >> You'd probably be better off using the 'key' keyword argument to >> .sort(), which is made for the Schwartzian Transform: >> >> a_list.sort(key=lambda x: x[3]) >> >> This sorts the list items by the value produced by the key function >> for each item. It's also (IIRC) faster than using a comparison >> function like you're currently doing. >> >> Regards, >> Chris > > Yes, using 'key' is faster than 'cmp'. > > If you have Python 2.4 or newer, it would also be slightly faster to > use > operator.itemgetter() instead of a lambda: > >>>> import operator >>>> a_list.sort(key=operator.itemgetter(3)) > >>> I'm actually sorting it by the last value in the tuple (d2). I >>> have been >>> researching more efficient sorting algorithms and came across >>> Schwartzian >>> transform via these links: >>> >>> http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency >>> http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html >>> >>> I get what's happening (sorta...errr...lol) but I'm not sure if >>> it is more >>> efficient in my scenario, if it is then I have no idea how to >>> implement it >>> properly :-/ >>> >>> Would be great if a true expert would offer a suggestion for me... >>> >>> Thanks! >>> >>> David > -- From dstromberglists at gmail.com Thu Sep 11 14:56:43 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 11 Sep 2008 18:56:43 GMT Subject: huge socket recv speed discrepancy between different OSs References: Message-ID: On Thu, 11 Sep 2008 16:17:58 +0200, Thorben Krueger wrote: > Do you see this too? > > Mor information and testcase here: > > http://bugs.python.org/issue3766 > > I would also be interested in the profiler output under windows. > > All the best > Thorben I regret that I don't have a lot of time to look into this interesting issue. Perl may be buffering the socket I/O. That might be a question for comp.lang.perl. Usually, when you can reduce the number of function/method calls and system calls done in your innermost loop(s), especially on a high speed network, you've done a good thing - because otherwise CPU use becomes the dominant term in the performance equation. You might want to try my bufsock module to see if that'll help: http://stromberg.dnsalias.org/~strombrg/bufsock.html It'll give you buffered sockets, along with a flush method. You probably also might want to try psyco when on an x86 system. Unfortunately, it looks like psyco isn't available for x86-64. Anyone know if pypy is ready to try such a program as Thorben's? From hniksic at xemacs.org Fri Sep 12 10:37:54 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Sep 2008 16:37:54 +0200 Subject: Accessing __slots__ from C References: <8763p1799y.fsf@mulj.homelinux.net> Message-ID: <871vzp77lp.fsf@mulj.homelinux.net> Hrvoje Niksic writes: > Chris writes: > >>> descr = GetAttrString(cls,"varname"); >>> offset = descr->d_member->offset; >>> slotvar = (PyObject*)(((char*)obj)+offset) >> >> Unfortunately, I am inexperienced at this kind of thing, so I wasn't >> able to get something working. Maybe someone could tell me what's >> wrong with the code below (it gives the error "'struct _object' has no >> member named 'd_member'")? > > You are getting that error because Carl forgot to cast the descriptor > to the appropriate C type, in this case PyMemberDescrObject. The last > line is also incorrect, I think. Try something like this: > > PyObject *descr = PyObject_GetAttrString(x,"attr_one"); Also note that x should be your object's type, i.e. o->ob_type cast to PyObject *. The complete incantation would be: // outside the loop PyObject *descr = PyObject_GetAttrString((PyObject *) obj->ob_type, "attr_one"); if (!descr) return NULL; int offset = ((PyMemberDescrObject *) descr)->d_member->offset; Py_DECREF(descr); // inside the loop PyObject *value = *(PyObject **)((char *)obj + offset); if (!value) { PyErr_SetString(PyExc_AttributeError, "attribute missing"); return NULL; } // Remember to Py_INCREF(value) before using it and Py_DECREF it after // using it. Otherwise if the object changes its slot to something // else, you might be using a dead object. With this code, accessing the value is practically free once the offset is calculated. Here is a bench3 function updated to use this strategy: static PyObject * bench3(PyObject *ignored, PyObject *obj) { PyObject *descr = PyObject_GetAttrString((PyObject *) obj->ob_type, "abcdef"); if (!descr) return NULL; // Here you should also assert that PyObject_TypeCheck(descr, // PyMemberDescr_Type) holds true. Since PyMemberDescr_Type is static, // you'll have to get it by stashing away ob_type of a value known to be // the descriptor. This is left as excercise to the reader. int offset = ((PyMemberDescrObject *) descr)->d_member->offset; Py_DECREF(descr); int i; PyObject *volatile attr; // 'volatile' for benchmarking, prevents gcc // from optimizing away the loop for (i = 0; i < 1000000; i++) { attr = *(PyObject **)((char *)obj + offset); } Py_INCREF(attr); return attr; // to prove that we retrieved the correct value } >>> t0 = time.time(); attr.bench3(o); t1 = time.time() 1 >>> t1-t0 0.00071597099304199219 # for 1,000,000 iterations, as cheap as it gets From harrrrpo at gmail.com Mon Sep 8 13:23:31 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Mon, 8 Sep 2008 19:23:31 +0200 Subject: Read and write binary data In-Reply-To: References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: <538050a90809081023u56d8fbd6sbfd25860553ba860@mail.gmail.com> I don't know if this is going to help you but a free&open alternative to Matlap is FreeMat just search for it From bdesth.quelquechose at free.quelquepart.fr Mon Sep 29 12:18:15 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2008 18:18:15 +0200 Subject: One class per file? In-Reply-To: References: Message-ID: <48e11bb1$0$7590$426a74cc@news.free.fr> HCB a ?crit : > Hello: > > The book "Code Complete" recommends that you put only one class in a > source file, That's possibly (don't know...) a good advice for C++, and that's mandatory (at least for 'public' classes) in Java. And that's totally pointless and counterproductive in Python. Also and FWIW, "this dead horse as been beaten to hell and back" (IOW : you'll find quite a couple thread discussing this in this newsgroup's archives). From george.sakkis at gmail.com Mon Sep 29 18:00:10 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 29 Sep 2008 15:00:10 -0700 (PDT) Subject: how to search multiple textfiles ? References: Message-ID: On Sep 29, 5:16?am, Lawrence D'Oliveiro wrote: > In message > , George > > Sakkis wrote: > > $ find -name "*py" | xargs egrep "\bword\b" > > Better: > > ? ? find -name '*.py' -exec grep -E "\bword\b" {} \; In what way is this better ? I don't dispute it, I'm just curious. From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 10:56:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 16:56:45 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: Message-ID: <48cbf09c$0$25189$426a74cc@news.free.fr> Larry Bates a ?crit : (snip) > IMHO it reads better if you use the __call__ method of the class to > return the value IMHO, it makes no sense at all to abuse the __call__ magic method here. > and rewrite it as a regular loop for clarity. > Sometimes the simplest way is the easiest to read. > > class FolderInUse: > def __call__(self, archivefolder): > result = False > for instance in self.core.active_outgoing_registration_instances(): > if instance.forbid_to_close(archivefolder): > result = True > break > > return result the loop would be simpler with an early return: for instance in self.core.active_outgoing_registration_instances(): if instance.forbid_to_close(archivefolder): return True return False > > > Then it can be called with: > > if FolderInUse(archivefolder): > ... This will call the class constructor and initializer and return a new instance, not the *instance method* __call__. From ricaraoz at gmail.com Tue Sep 23 09:19:11 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 23 Sep 2008 10:19:11 -0300 Subject: a short-cut command for globals().clear() ?? In-Reply-To: References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> <1f913671-1c21-4018-a841-a5a02a360c3b@k30g2000hse.googlegroups.com> <49ffb44f-c14d-4d38-86fb-eb50e5ef9abf@d1g2000hsg.googlegroups.com> Message-ID: <48D8ECCF.3000201@bigfoot.com> Terry Reedy wrote: > MRAB wrote: >> >> How about something like this: >> >> def clear_workspace(): >> keep_set = set(['__builtins__', '__doc__', '__name__', >> 'clear_workspace']) > > For 2.6/3.0, add __package__ to the list to be kept. > >> for x in globals().keys(): >> if x not in keep_set: >> del globals()[x] Or... you might have a script clearWorkspace.py : --------------------------------------------- initGlobals = globals().keys() def clearWorkspace() : for gVar in globals().keys() : if gVar not in initGlobals : del globals()[gVar] --------------------------------------------- Which you run before doing anything else. Then you don't mind if additions were made to the list to keep, or if you are using something like pyCrust which has its own initial globals, or if you want to keep some global vars of your own (in which case you run clearWorkspace AFTER you instantiate your global vars). From brenNOSPAMbarn at NObrenSPAMbarn.net Tue Sep 2 13:40:54 2008 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Tue, 02 Sep 2008 17:40:54 GMT Subject: Relative imports and "import X as Y" References: Message-ID: Gabriel Genellina wrote: > En Sun, 31 Aug 2008 07:27:12 -0300, Wojtek Walczak > escribi?: > >> On Sun, 31 Aug 2008 06:40:35 GMT, OKB (not okblacke) wrote: >> >>>> Download the latest beta for your system and give it a try. >>> >>> Thanks for the advice, but I'd really rather not deal >>> with >>> installing the entire thing alongside my existing version, >>> possibly causing conflicts in who knows what ways. >> >> Then you can download tar.gz package, compile it, and try it >> without installing :-) > > Or use a virtual machine, or a live CD. Gosh, thanks, everyone, for being so helpful! -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From lutz at rmi.net Tue Sep 9 09:07:33 2008 From: lutz at rmi.net (Mark Lutz) Date: Tue, 9 Sep 2008 06:07:33 -0700 (PDT) Subject: Python training in Colorado, October 15-17 Message-ID: <34cec5fb-d145-4bb6-8178-8ce8c15ac53b@34g2000hsh.googlegroups.com> Python author and trainer Mark Lutz will be teaching another 3-day Python class at a conference center in Longmont, Colorado, on October 15-17, 2008. This is a public training session open to individual enrollments, and covers the same topics as the 3-day onsite sessions that Mark teaches, with hands-on lab work. The class provides an in-depth introduction to Python and its common applications, and parallels the instructor's popular Python books. For more information on this session, please visit its web page: http://home.earthlink.net/~python-training/longmont-public-classes.htm For additional background on the class itself, see our home page: http://home.earthlink.net/~python-training Thanks for your interest. --Python Training Services From v1p3r2 at gmail.com Tue Sep 2 18:23:50 2008 From: v1p3r2 at gmail.com (v1p3r) Date: Tue, 2 Sep 2008 23:23:50 +0100 Subject: Completely unable to install Python on Windows Message-ID: I'm attempting to install Python 2.5.2 (python-2.5.2.amd64.msi) on my Vista SP1 x64 system, but the installer always crashes with a "Windows Installer has stopped working" error after clicking Next on the initial screen. I've tried the following so far: 1. x86 and x64 versions 2. Manually reinstalling Windows Installer 4.5 3. Forcing msiexec to run as administrator 4. Installing both globally and for my user alone 5. Silent install 6. The previous version (2.5.1) 7. Repeating the above with a completely clean install of Vista SP1 x64 in VMWare It seems that no matter what I do, the problem persists. ActivePython produces a similar error, but much later in the install. This has me completely baffled, since nobody else seems to have a similar issue despite it happening on a completely stock install of Windows. Any help would be greatly appreciated. - Josh (The output of msiexec with logging enabled follows) === Logging started: 02/09/2008 23:11:12 === Action 23:11:12: INSTALL. Action start 23:11:12: INSTALL. Action 23:11:12: LaunchConditions. Evaluating launch conditions Action start 23:11:12: LaunchConditions. Action ended 23:11:12: LaunchConditions. Return value 1. Action 23:11:12: WhichUsersDlg. Action start 23:11:12: WhichUsersDlg. Info 2898. For VerdanaBold10 textstyle, the system created a 'Verdana' font, in 1 character set, of 16 pixels height. Info 2898. For DlgFont8 textstyle, the system created a 'Tahoma' font, in 1 character set, of 14 pixels height. Action 23:11:12: WhichUsersDlg. Dialog created Action ended 23:11:14: WhichUsersDlg. Return value 1. Action 23:11:14: FindRelatedProducts. Searching for related applications Action start 23:11:14: FindRelatedProducts. Action ended 23:11:14: FindRelatedProducts. Return value 1. Action 23:11:14: AppSearch. Searching for installed applications Action start 23:11:14: AppSearch. Action ended 23:11:14: AppSearch. Return value 1. Action 23:11:14: CCPSearch. Searching for qualifying products Action start 23:11:14: CCPSearch. Action ended 23:11:14: CCPSearch. Return value 1. Action 23:11:14: RMCCPSearch. Searching for qualifying products Action start 23:11:14: RMCCPSearch. Action ended 23:11:14: RMCCPSearch. Return value 0. Action 23:11:14: ValidateProductID. Action start 23:11:14: ValidateProductID. Action ended 23:11:14: ValidateProductID. Return value 1. Action 23:11:14: InitialTargetDir. Action start 23:11:14: InitialTargetDir. Action ended 23:11:14: InitialTargetDir. Return value 1. Action 23:11:14: SetDLLDirToSystem32. Action start 23:11:14: SetDLLDirToSystem32. Action ended 23:11:14: SetDLLDirToSystem32. Return value 1. Action 23:11:14: CostInitialize. Computing space requirements Action start 23:11:14: CostInitialize. Action ended 23:11:14: CostInitialize. Return value 1. Action 23:11:14: FileCost. Computing space requirements Action start 23:11:14: FileCost. Action ended 23:11:14: FileCost. Return value 1. Action 23:11:14: IsolateComponents. Action start 23:11:14: IsolateComponents. Action ended 23:11:14: IsolateComponents. Return value 1. Action 23:11:14: CostFinalize. Computing space requirements Action start 23:11:14: CostFinalize. Action ended 23:11:14: CostFinalize. Return value 1. Action 23:11:14: MigrateFeatureStates. Migrating feature states from related applications Action start 23:11:14: MigrateFeatureStates. Action ended 23:11:14: MigrateFeatureStates. Return value 0. Action 23:11:14: SelectDirectoryDlg. Action start 23:11:14: SelectDirectoryDlg. From cjw at ncf.ca Wed Sep 10 17:04:57 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 10 Sep 2008 17:04:57 -0400 Subject: Python and Open Office In-Reply-To: References: Message-ID: Marco Bizzarri wrote: > On Wed, Sep 10, 2008 at 10:04 PM, Greg Lindstrom wrote: >> Hello, >> >> I would like to create and manipulate Open Office documents using Python. I >> have found then UNO Python page and odfpy modules which seem to be exactly >> what I need. The odfpy manual is, to me, a confusing list of objects and >> methods (it's an impressive list!), but does not have much in the way of how >> to use them. For example, I can open a spreadsheet and create new pages >> (there's a nice example near the back of the manual) but I can't figure out >> how to open an existing spreadsheet and list the names of the individual >> sheets ("tabs"). >> >> I have written an application that access Microsoft Excel and creates >> reports for work, but would like to create an Open Source version using Open >> Office and release it to the community (and maybe get a talk at PyCon :-). >> >> Is there someone here who can help me out, or is there an appropriate >> mailing list for me to join? > > Ciao, Greg. > > you should check with the openoffice.org mailing list; I think what > you are looking for is the api mailing list for openoffice; you could > try to get the OpenOffice.org developers guide and the SDK, and check > it (but it is not a little work) > > Regards > Marco > > >> Thanks >> >> --greg >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > Greg, If you follow this up, I hope that you will post info to c.l.p and let us know whether the UNO interface is Python 2.5 compatible. The last time I looked it was set for 2.3 or 2.4. Colin W From hrishys at yahoo.co.uk Wed Sep 24 11:22:28 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Wed, 24 Sep 2008 15:22:28 +0000 (GMT) Subject: Linq to Python In-Reply-To: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> Message-ID: <326492.90059.qm@web27405.mail.ukl.yahoo.com> Hi Well wouldn't it be a lot easier to query and join a xml source with a relational source with LINQ capabilites in Python. Hmm what am i missing here is there a site that takes all LINQ examples and does them using list comprehensions and makes them sound easy ? wasn't python supposed to make everything easy ? regards Hrishy --- On Tue, 23/9/08, sturlamolden wrote: > From: sturlamolden > Subject: Re: Linq to Python > To: python-list at python.org > Date: Tuesday, 23 September, 2008, 7:49 PM > On Sep 23, 4:48?pm, hrishy > wrote: > > > Will LINQ be ported to Python ? > > No, because Python already has list comprehensions and we > don't need > the XML buzzword. > -- > http://mail.python.org/mailman/listinfo/python-list From robert.kern at gmail.com Tue Sep 23 16:16:07 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 15:16:07 -0500 Subject: Python is slow? In-Reply-To: References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: sturlamolden wrote: > On Sep 23, 9:17 pm, Robert Kern wrote: > >> You could also drop it on the scipy.org wiki in the Cookbook category. > > Yes, if I could figure out how to use it... What's confusing? You do have to create a profile: http://www.scipy.org/UserPreferences -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From duncan.booth at invalid.invalid Thu Sep 11 04:00:27 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Sep 2008 08:00:27 GMT Subject: universal unicode font for reportlab References: Message-ID: Tim Roberts wrote: > Duncan Booth wrote: >> >>Laszlo Nagy wrote: >> >>> I need to use HTML anyway. I realized that universal unicode fonts >>> are above 5MB in size. The report would be a 10KB PDF, but I need to >>> embed the font before I can send it to anyone. Since some reports >>> needs to be sent in emails, I need to use something else. I cannot >>> be sending 10MB emails for "one page" reports. >>> >>I thought that usually when you embed a font in a PDF only the glyphs >>which are actually used in the document get embedded. Unfortunately a >>quick test with reportlab seems to show that it doesn't do that >>optimisation: it looks as though it just embeds the entire font. > > No, it does subsetting. There was a debate a year or two ago on the > reportlab list about how the font subset should be named in the > resulting PDF file. > > Is it possible you have an older release? It was 2.1 downloaded about 30 minutes before my post. The not too scientific test I did was to copy the font embedding example from the Reportlab documentation, modify it enough to make it actually run, and then change the output to have only one glyph. The resulting PDF is virtually identical. I'm not a reportlab expert though so I may have made some blindingly obvious beginners mistake (or maybe it only subsets fonts over a certain size or glyphs outside the ascii range?). ---------- rlab.py ------------ import os, sys import reportlab folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts' afmFile = os.path.join(folder, 'LeERC___.AFM') pfbFile = os.path.join(folder, 'LeERC___.PFB') from reportlab.pdfbase import pdfmetrics justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile) faceName = 'LettErrorRobot-Chrome' # pulled from AFM file pdfmetrics.registerTypeFace(justFace) justFont = pdfmetrics.Font('LettErrorRobot-Chrome',faceName,'WinAnsiEncoding') pdfmetrics.registerFont(justFont) from reportlab.pdfgen.canvas import Canvas canvas = Canvas('temp.pdf') canvas.setFont('LettErrorRobot-Chrome', 32) if sys.argv: canvas.drawString(10, 150, 'TTTT TTTTTT TT TT') canvas.drawString(10, 100, 'TTTTTTTTTTTTTTTTTTTTT') else: canvas.drawString(10, 150, 'This should be in') canvas.drawString(10, 100, 'LettErrorRobot-Chrome') canvas.save() ------------------------------- -- Duncan Booth http://kupuguy.blogspot.com From steve at REMOVE-THIS-cybersource.com.au Thu Sep 4 02:26:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 06:26:06 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> Message-ID: <00cf79ec$0$20302$c3e8da3@news.astraweb.com> On Wed, 03 Sep 2008 22:20:43 -0700, Mensanator wrote: > On Sep 3, 8:30?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: >> >>>> sum([]) >> > 0 >> >> > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. >> > It should return None or throw an exception like sum([None,1]) does. >> >> You're wrong, because 99.9% of the time when users leave a blank cell >> in Excel, they want it to be treated as zero. > > Then 99.9% of users want the wrong thing. It is to laugh. > Microsoft knows that this is a bug Says you. > but refuses to fix it to prevent breaking legacy documents (probably > dating back to VisiCalc). When graphimg data, a missing value should be > interpreted as a hole in the graph "Graphing data" is not sum(). I don't expect graphing data to result in the same result as sum(), why would I expect them to interpret input the same way? > +------+ +--+------+------+-----+ Why should the graphing application ignore blanks ("missing data"), but sum() treat missing data as an error? That makes no sense at all. > and not evaluated as 0 > > And Microsoft provides a workaround for graphs to make 0's appear as > holes. Of course, this will cause legitimate 0 values to disappear, so > the workaround is inconsistent. I'm not aware of any spreadsheet that treats empty cells as zero for the purpose of graphing, and I find your claim that Excel can't draw graphs with zero in them implausible, but I don't have a copy of Excel to test it. >> Spreadsheet sum() is not the >> same as mathematician's sum, which doesn't have a concept of "blank >> cells". (But if it did, it would treat them as zero, since that's the >> only useful thing and mathematicians are just as much pragmatists as >> spreadsheet users.) The Excel code does the right thing, and your >> "pure" solution would do the unwanted and unexpected thing and is >> therefore buggy. > > Apparently, you don't use databases or make surface contours. Neither databases nor surface contours are sum(). What possible relevance are they to the question of what sum() should do? Do you perhaps imagine that there is only "ONE POSSIBLE CORRECT WAY" to deal with missing data, and every function and program must deal with it the same way? > Contour programs REQUIRE that blanks are null, not 0 Lucky for them that null is not 0 then. > so that the Kriging > algorithm interpolates around the holes rather than return false > calculations. Excel's treatment of blank cells is inconsistent with > Access' treatment of Nulls and therefore wrong, anyway you slice it. No no no, you messed that sentence up. What you *really* meant was: "Access' treatment of Nulls is inconsistent with Excel's treatment of blank cells and therefore wrong, anyway you slice it." No of course not. That would be stupid, just as stupid as your sentence. Excel is not Access. They do different things. Why should they necessarily interpret data the same way? > Maybe you want to say a bug is when it doesn't do what the author > intended, but I say if what the intention was is wrong, then a perfect > implentation is still a bug because it doesn't do what it's supposed to > do. Who decides what it is supposed to do if not the author? You, in your ivory tower who doesn't care a fig for what people want the software to do? Bug report: "Software does what users want it to do." Fix: "Make the software do something that users don't want." Great. >> Bugs are defined by "does the code do what the user wants it to do?", >> not "is it mathematically pure?". > > ReallY? So you think math IS a democracy? There is no reason to violate > mathematical purity. You've given a good example yourself: the Kriging algorithm needs a Null value which is not zero. There is no mathematical "null" which is distinct from zero, so there's an excellent violation of mathematical purity right there. If I am given the job of adding up the number of widgets inside a box, and the box is empty, I answer that there are 0 widgets inside it. If I were to follow your advice and declare that "An error occurred, can't determine the number of widgets inside an empty box!" people would treat me as an idiot, and rightly so. > If I don't get EXACTLY the same answer from Excel, > Access, Mathematica and Python, then SOMEBODY is wrong. It would be a > shame if that somebody was Python. Well Excel, Python agree that the sum of an empty list is 0. What do Access and Mathematica do? >> The current behaviour of sum([]) does the right thing for the 99% of >> the time when users expect an integer. > > Why shouldn't the users expect an exception? Isn't that why we have > try:except? Maybr 99% of users expect sum([])==0, but _I_ expect to be > able to distinguish an empty list from [4,-4]. The way to distinguish lists is NOT to add them up and compare the sums: >>> sum([4, -4]) == sum([0]) == sum([1, 2, 3, -6]) == sum([-1, 2, -1]) True The correct way is by comparing the lists themselves: >>> [] == [4, -4] False >> And the >> rest of the time, they have to specify a starting value for the sum >> anyway, and so sum([], initial_value) does the right thing *always*. > > So if you really want [] to be 0, why not say sum([],0)? I don't want [] == 0. That's foolish. I want the sum of an empty list to be 0, which is a very different thing. And I don't need to say sum([],0) because the default value for the second argument is 0. > Why shouldn't nothing added to nothing return nothing? Having it > evaluate to 0 is wrong 99.9% of the time. It is to laugh. What's the difference between having 0 widgets in a box and having an empty box with, er, no widgets in it? -- Steven From steve at holdenweb.com Thu Sep 18 20:48:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Sep 2008 20:48:42 -0400 Subject: Extracting hte font name from a TrueType font file In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > >> Does anyone have a Python recipe for this? > >>>> from PIL import ImageFont >>>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1) >>>> f.font.family > 'Verdana' >>>> f.font.style > 'Italic' > Thanks so much, Fredrik. The reason I asked is because I found the specification completely opaque ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From clp at rebertia.com Mon Sep 29 22:03:51 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Sep 2008 19:03:51 -0700 Subject: Python arrays and sting formatting options In-Reply-To: References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6d265f36-352c-4866-bf91-c14d26101fc2@k37g2000hsf.googlegroups.com> Message-ID: <47c890dc0809291903l2df1e572h13eea9fc4d6a2cd3@mail.gmail.com> On Mon, Sep 29, 2008 at 6:56 PM, Ivan Reborin wrote: > On Mon, 29 Sep 2008 17:59:40 -0700 (PDT), bearophileHUGS at lycos.com > wrote: > > Hello bearophile, thank you for replying. > >>The Python genie grants you that wish. You were almost right: >>>>> print (3 * '%12.3f') % (a, b, c) >> 2.000 123456.789 1234.000 >>>>> print 3 * '%12.3f' % (a, b, c) >> 2.000 123456.789 1234.000 > Works beautifully :-) Thank you! > >>>>> print 3 * '%12.3f' % a, b, c >>Traceback (most recent call last): >> File "", line 1, in >>TypeError: not enough arguments for format string > > Just one more question - it's actually an extension to this one > (forgive my curiosity, but I really need this info, and searching > google always gives me the same stuff again and again) ... > > a = 2.000001 > b = 123456.789 > c = 1234.0001 > d = 98765.4321 > # same as above except for d > > print (3 * '%12.3f') % (a, b, c) > #this works beautifully > > How to add d at the end but with a different format now, since I've > "used" the "format part" ? > > Again, my weird wishful-thinking code: > print (3*'%12.3f', '%5.3f') %(a,b,c),d Again, very close to the correct code: print (3*'%12.3f' + '%5.3f') %(a,b,c,d) Regards, Chris > > >>(Note the spaces and parentheses. Python programmers thank you if put >>them improving readability a little). > > Yes, ok. I can agree with that - separating the format from the > variable list part sounds reasonable. > >> >>Bye, >>bearophile > > -- > Ivan > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 03:06:17 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 09:06:17 +0200 Subject: Why no tailcall-optimization? In-Reply-To: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: <48d89564$0$11995$426a74cc@news.free.fr> process a ?crit : > Why doesn't Python optimize tailcalls? Design choice. tail-recursive calls optimization makes debugging harder. Note that this has been discussed quite a few times here. > Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. While it has some (limited) support for functional idioms, Python is still mostly an imperative language, and as such favors iteration over recursion. Not being able to do XXX is only a PITA if you know no other way to skin the cat. NB : FWIW, I'd personnally prefer to have tail-recursive calls optimization too - but not badly enough to switch to another language... From david at boddie.org.uk Thu Sep 18 15:58:47 2008 From: david at boddie.org.uk (David Boddie) Date: Thu, 18 Sep 2008 21:58:47 +0200 Subject: Python and Open Office References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Wednesday 17 September 2008 21:59, Terry Reedy wrote: > Hartmut Goebel wrote: >> Terry Reedy schrieb: >> >> The API docs are a bit hidden on the webpage. Here is the link: >> > > I wrote my comment *after* looking at the above, which I found easily > enough. After 7 pages of (helpful) explanatory text, there follow 88 > pages with hundreds of entries like this: [...] > which are translated to a more readable form from the Relax-NG schema > (formal specs) in the standard. But I have no idea what a Ruby property > is in this context. It would be much like reading the grammar entries > in the Python Reference without the explanatory text that follows. I started using odfpy for a project, and I found that I spent a lot of time flicking back and forth in the API manual and cross-referencing it with the specification. The simple examples were useful enough to get started with, but I could have used more information about how to use certain classes and what elements and attributes they required. I also wanted to add equations to the documents I was producing and that requires some knowledge of MathML. Certainly, it's not a very high level API for documentation creation - you need to know something about the format to be able to construct documents. David From eckhardt at satorlaser.com Wed Sep 10 03:32:35 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 10 Sep 2008 09:32:35 +0200 Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: icarus top-posted: > one more question... ...deserves a separate thread. > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? Either it is Python, then it is portable but no executable, or it is an executable, then it is standalone but not portable. I'm afraid what you are asking for is not possible. Other than that, others told you how to easily get a standalone executable. Uli [ 35 lines of uselessly quoted content removed ] -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From eliben at gmail.com Sat Sep 20 01:01:14 2008 From: eliben at gmail.com (eliben) Date: Fri, 19 Sep 2008 22:01:14 -0700 (PDT) Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: On Sep 18, 6:01?pm, Tim Golden wrote: > Joe G (Home) wrote: > > Hi All, > > > Background > > =================== > > I have installed Python for windows today from the python web site ?.I also > > installed pySerial using the Windows installer from the sourceforge web > > site..... Both installs use the default directories. > > > Phyton ?version ? ?: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > > v.1310 32 bit (Intel)] on win32 > > > pySerial ? 2.4 ? July 6th > > > Problem : ?Errors Screen output > > ============================ > >>>> import serial > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? import serial > > ? File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in > > > > ? ? from serialwin32 import * > > ? File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in > > > > ? ? import win32file ?# The base COM port and file IO functions. > > ImportError: No module named win32file > > You need to install the pywin32 extensions from: > > ?http://pywin32.sf.net > > They're so commonly used (and, if you install the ActiveState > distro of Python, even bundled) that I imagine many Windows > Pythoneers like myself simply install them automatically as > soon as we've installed the main python.org Python. > > Once you've done that, the rest should just work: it's > clear from the traceback that the serial module is getting > imported; it's just trying to find the win32file module. > Why are people preferring the python.org package over ActiveState's, which seems to be more complete and includes more modules (like pywin32) ? Eli From castironpi at gmail.com Thu Sep 4 16:04:54 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 13:04:54 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: <3a59a1d4-4478-49e5-8316-9d27c09f55b0@m3g2000hsc.googlegroups.com> On Sep 4, 2:51?pm, Martin DeMello wrote: > On Sep 4, 12:41?pm, Fredrik Lundh wrote: > > > "task_done" just decrements a counter (incremented by "put"). ?when the > > counter reaches zero, the "join" call is unblocked. > > Thanks! Is there any standard python idiom to empty a queue into a > list? Or do I just call get() repeatedly and catch the exception when > it's done? > > martin Random access isn't supported by the defined interface. You can make it more convenient, though. import Queue class IterQueue( Queue.Queue ): def __iter__( self ): return self def next( self ): if self.empty(): raise StopIteration return self.get() q= IterQueue() q.put( 'a' ) q.put( 'b' ) q.put( 'c' ) print [ x for x in q ] /Output: ['a', 'b', 'c'] From dickinsm at gmail.com Thu Sep 25 05:42:20 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 25 Sep 2008 02:42:20 -0700 (PDT) Subject: Comparing float and decimal References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: <99a7ab2c-601e-47fe-8ece-5f9150c10f7a@k30g2000hse.googlegroups.com> On Sep 24, 6:18?pm, Terry Reedy wrote: > If there is not now, there could be in the future, and the decimal > authors are committed to follow the standard wherever it goes. > Therefore, the safe course, to avoid possible future deprecations due to > doing too much, is to only do what is mandated. Makes sense. It looks as though the standard's pretty stable now though; I'd be quite surprised to see it evolve to include discussion of floats. But then again, people thought it was stable just before all the extra transcendental operations appeared. :-) > For integral values, this is no problem. > ?>>> hash(1) == hash(1.0) == hash(decimal.Decimal(1)) == > hash(fractions.Fraction(1)) == 1 > True Getting integers and Decimals to hash equal was actually something of a pain, and required changing the way that the hash of a long was computed. The problem in a nutshell: what's the hash of Decimal('1e100000000')? The number is clearly an integer, so its hash should be the same as that of 10**100000000. But computing 10**100000000, and then finding its hash, is terribly slow... (Try hash(Decimal('1e100000000')) in Python 2.5 and see what happens! It's fixed in Python 2.6.) As more numeric types get added to Python, this 'equal implies equal hash' requirement becomes more and more untenable, and difficult to maintain. I also find it a rather unnatural requirement: numeric equality is, to me, a weaker equivalence relation than the one that should be used for identifying keys in dictionaries, elements of sets, etc. Fraction(1, 2) and 0.5 should, to my eyes, be considered different elements of a set. But the only way to 'fix' this would be to have Python recognise two different types of equality, and then it wouldn't be Python any more. The SAGE folks also discovered that they couldn't maintain the hash requirement. > Decimals can also be converted to floats (they also have a ?__float__ > method). ?But unlike fractions, the conversion must be explicit, using > float(decimal), instead of implicit, as with ints and fractions. Maybe: if I *had* to pick a direction, I'd make float + Decimal produce a Decimal, on the basis that Decimal is arbitrary precision and that the float->Decimal conversion can be made losslessly. But then there are a whole host of decisions one has to make about rounding, significant zeros, ... (And then, as you point out, Cowlishaw might come out with a new version of the standard that does include interactions with floats, and makes an entirely different set of decisions...) Mark From steve at REMOVE-THIS-cybersource.com.au Sun Sep 21 19:05:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 23:05:15 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <00e6cd16$0$20303$c3e8da3@news.astraweb.com> Fixing top-posting. On Mon, 22 Sep 2008 08:54:43 +1000, James Mills wrote: > On Mon, Sep 22, 2008 at 8:39 AM, Steven D'Aprano > wrote: >> I have a class which is not intended to be instantiated. Instead of >> using the class to creating an instance and then operate on it, I use >> the class directly, with classmethods. Essentially, the class is used >> as a function that keeps state from one call to the next. [...] > Hi, > > Wouldn't a normal class called State > suffice for storing state between calls ? And ... Creating a state > instance ? > > For example: [snip] That's a rather big example for a rather small question. Yes, a normal class would work in many cases. In this case, the class itself is being produced by a factory function, and it's output is an iterator. Having to call: cls = factory() instance = cls() result = instance() to get anything done seems excessive, even if you write it as a one-liner result = factory()()(). I'm not wedded to the idea, there are alternatives (perhaps the factory should instantiate the class and return that?) but I assume others have used this design and have a name for it. -- Steven From luigipaioro at libero.it Tue Sep 9 11:53:57 2008 From: luigipaioro at libero.it (Luigi) Date: Tue, 9 Sep 2008 08:53:57 -0700 (PDT) Subject: XML-RPC "filter" Message-ID: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> Dear all, I'm writing an XML-RPC server which should be able to modify the incoming request before dispatching it. In particular I wand to added two fixed parameters to the method called: one is the client host address, and the other is the user name provided as for Basic Authentication (http://user at www.bla-bla.com). To do this, at the present I've overwritten the do_POST method of SimpleXMLRPCRequestHandler, including at a certain point this code: .... data = ''.join(L) params, method = xmlrpclib.loads(data) user = "unknown" if self.headers.has_key('Authorization'): # handle Basic authentication (enctype, encstr) = self.headers.get('Authorization').split() user, password = base64.standard_b64decode(encstr).split(':') params = list(params) params.append(self.address_string()) params.append(user) params = tuple(params) data = xmlrpclib.dumps(params, methodname=method) (I slightly modified it to make it more readable at mail level) It works, but I don't really like it because it completely overwrites the do_POST method that in the future Python releases is going to change (I verified it). Do you know a better way to do this? Thanks in advance. Luigi From half.italian at gmail.com Sun Sep 14 23:35:38 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 14 Sep 2008 20:35:38 -0700 (PDT) Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: On Sep 14, 7:10?pm, Grant Edwards wrote: > On 2008-09-15, Ben Finney wrote: > > > > > Grant Edwards writes: > >> On 2008-09-14, Ben Finney wrote: > > >>> Second: please do yourself a favour and drop the > >>> camelCaseNames. Follow PEP 8 > >>> for style and > >>> naming in your Python code. > > >> If he finds camelcase more readable and easier to type (as do > >> I), how is switching to underscores "doing himself a favor"? > > >> I'm generally in favor of using a consistent naming style > >> throughout a project, but I don't see why the naming style > >> used in my source code should be subject to somebody else's > >> arbitrary standard. > > > Because the code we write rarely stays isolated from other > > code. There is an existing convention, > > There are many existing conventions. > > > and it's better to pick a (sufficiently sane) style convention > > and stick to it than argue about what the convention should > > be. > > I suppose if everybody agreed to pick one, and all the source > code in the world was changed to meet it, that would "a good > thing". ?It just seems like a goal so unrealistic as to make it > a bit of an overstatement to tell people they're better off > following convention X than following convention Y. > > When packages as significant as wxPython use naming conventions > other than PEP 8, I find it hard to make a case that the PEP 8 > naming convention is any better than any other. > > >> When it comes to writing code intended for the standard > >> library in the main Python distribution, I would certainly > >> defer to the existing standard as defined in PEP 8. ?However, > >> I don't see any reason that style should be imposed on all > >> everybody else. > > > Who's imposing? I'm saying it's a good idea for everyone to do > > it, and going so far as to say that one is doing oneself a > > favour by following the convention. I have no more power than > > you to "impose" convention on anyone. > > My apologies -- "impose" was too strong a word to use. > > If we were starting from scratch and there was no extant source > code in the world, then it would make sense to encourage > everybody to pick one convention. [I still think it would be > rather quixotic.] But, there are so many projects out there > with naming conventions other than PEP 8, that I don't see how > there's an advantage to picking one over another (except for > the obvious also-rans like "all upper case, no vowels, and a > maximum length of 6 characters"). > > I'll agree that sticking with a single convention within a > project is definitely a good thing. > > I'm personally aware of mixed/camel-case projects from 25+ > years ago, so I'm afraid PEP 8 came along a bit too late... > > -- > Grant +1 CamelCase FTW! ~Sean From uomiocenekidd at gmail.com Mon Sep 22 06:39:38 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:39:38 -0700 (PDT) Subject: download from redtube - Free Message-ID: download from redtube . . . *******CLICK HERE******** http://vids365.cn/download-from-redtube ***************************** . . . . . . . . . . . . download from redtube From bignose+hates-spam at benfinney.id.au Mon Sep 29 19:14:11 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 Sep 2008 09:14:11 +1000 Subject: One class per file? References: <87od27rssp.fsf@benfinney.id.au> <076ab8f2-551d-478f-b31a-df0be47987da@y71g2000hsa.googlegroups.com> Message-ID: <87k5cusfy4.fsf@benfinney.id.au> HCB writes: > The "Put one class in one file" statement is made in "Code Complete > 2" page 771. Thanks. I don't have the second edition; I wonder what the context of that advice is? Perhaps he's speaking only of C++ or Java. Certainly I'd expect the author to reconsider that advice for languages (such as Python) where classes are routinely quite small and there are no technical barriers to grouping multiple classes in a file. -- \ ?I believe in making the world safe for our children, but not | `\ our children's children, because I don't think children should | _o__) be having sex.? ?Jack Handey | Ben Finney From fredrik at pythonware.com Sun Sep 14 07:36:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Sep 2008 13:36:41 +0200 Subject: Why some blog entries at MSN Space support rss feed while others don't? In-Reply-To: References: Message-ID: liuyuprc wrote: > Not sure if this is the place this question should even be raised it isn't. From maric at aristote.info Fri Sep 5 10:30:50 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 16:30:50 +0200 Subject: Case-insensitive string compare? In-Reply-To: <1220623239.5787.10.camel@aalcdl07.lib.unc.edu> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809051536.45285.maric@aristote.info> <1220623239.5787.10.camel@aalcdl07.lib.unc.edu> Message-ID: <200809051630.51113.maric@aristote.info> Le Friday 05 September 2008 16:00:39 J. Cliff Dyer, vous avez ?crit?: > Please keep the discussion on-list. > Sorry for the private email, I sent it again to the list.. > On Fri, 2008-09-05 at 15:36 +0200, Maric Michaud wrote: > > Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez ?crit : > > > On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: > > > > Thanks everyone for your help. I'm not opposed to using [key.lower() > > > > for key in stage_map] at all, I was just curious to see if there were > > > > any cleaner alternatives. It looks like that is what I'll be using. > > > > I'm not familiar with how python works internally, but coming from > > > > C++ it seems like "remaking" the map would be slow. However, speed is > > > > not my main concern in my particular situation, I'm just curious to > > > > learn more about python. > > > > > > You should be opposed to that particular solution. You have just taken > > > a dictionary lookup (very fast) and turned it into a list traversal > > > (slow). Even if speed isn't your main concern, this is an unnecessary > > > de-optimization. You are deliberately slowing down your program to > > > avoid a slightly more verbose lookup later. Your data structure might > > > as well be a list of tuples to begin with, to avoid creating a new > > > list. You have effectively made your keys useless as keys. > > > > > > If your lookups need to be case insensitive, make the key lower case, > > > and store the cased version in the value, whether as a tuple or a dict > > > (depending on whether you want named access). > > > > > > d = { > > > 'foo': {'key': 'Foo', 'value': 'val1'} > > > 'spam': {'key': 'sPAm', 'value': 'val2'} > > > } > > > > > > search = 'FOO'.lower() > > > if search in d: > > > result = d[search] > > > key = result['key'] > > > value = result['value'] > > > > > > The only reason I wouldn't use this solution is if you expect to have > > > keys that will be identical when made lowercase, but if you're doing > > > case-insensitive lookup, you obviously don't expect this to be an > > > issue. > > > > The OP has already said the keys are case-sensitive, so this is not an > > option, the only way to do it fast is to index upon insertion all keys in > > another dict, so you get in final : > > d = { "kEy1" : 1, "Key1" : 2} > > indexes = { "key1" : ["kEy1", "Key1" ] } > > That does not get the same behavior as the OP's original solution. The > OP's solution retrieves the first matching value only. Mine gets one > arbitrary matching value, determined by the algorithm used for > constructing the search dict (not specified in my solution). string.lower() in indexes gives the same result, but your right, a set of lowered keys could suffice for the exact OP's requirement. > What the > OP actually said was that he can't throw away the case. You assume that > this means there would be multiple entries distinguished only by case. > That might be true, but given his initial solution, it seemed to me more > likely that he wants to keep the case for display purposes, as in a > dictionary like this: > > { > "Michaud": "Maric", > "Dyer": "Cliff", > "D'Amato": "Alphonse", > } > I didn't want to make gratuitous extrapolations on the OP's data structure, but I still think the OP's question was "how to write cleanly a case-insensitive comparaison versus all the keys of a dict". Maybe I'm wrong. -- _____________ Maric Michaud From castironpi at gmail.com Mon Sep 8 23:58:53 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 8 Sep 2008 20:58:53 -0700 (PDT) Subject: lacking follow-through References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: On Sep 8, 2:21?pm, Grant Edwards wrote: > On 2008-09-08, Chris Rebert wrote: > > > On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman wrote: > > >> To expand on this a little bit, I've been subscribed to this > >> group for a couple of months, but there seems to be a bit more > >> gray area between what would go to a 'python-dev' group and a > >> 'python-user' group. ?Long debates about language features and > >> abstract ideas would appeal to the former, but not the latter. > >> Certainly I fall into the user category.. ?I'm pretty happy > >> with python, and generally just adjust to it's design and > >> features, rather than spend lots of time on whether they are > >> 'right' or could be 'better'. ?/shrug > > > Yeah, suggestions about changing the language are much better > > suited to the more-specific Python-ideas or Python-3000 > > mailinglists than the general-purpose c.l.p > > I don't think anybody here in c.l.p minds reading suggestions > for language features/changes, but often what the poster in > question writes is just an incomprehensible collection of > vaguely philosophical-sounding metaphores and similes > reminiscent of a hoax paper submitted as a joke to a > post-modern "journal" of some pretend science or other. > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! Used staples are good > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? with SOY SAUCE! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ? I would almost say Grant's criticism is too harsh, and I don't think 'incomprehensible metaphors' is really a problem on Py-Dev or CL-Py, though I feel that sometimes people aren't posting in earnest. I certainly have heard some in real life though. In some cases, I have observed that people are expressing things that they genuinely have perceived, and merely haven't applied the logic necessary to notice the inconsistency in their metaphor, which is the thing that makes them 'incomprehensible' to mature logicians like Grant. For example, I sometimes hear people talk about salary as though it were social approval, and vice versa. Even though the analogy doesn't hold in every case generally, it is still a good way to express yourself in many contexts, and especially when the more precise word isn't on the tip of your tongue. From tilmaniac at gmail.com Mon Sep 29 14:37:43 2008 From: tilmaniac at gmail.com (Tilman Kispersky) Date: Mon, 29 Sep 2008 11:37:43 -0700 (PDT) Subject: Cannot install pysqlite on Cygwin References: Message-ID: On Sep 29, 7:49?am, Steve Holden wrote: > Tilman Kispersky wrote: > > I am trying to install sqlite for use with python oncygwin. I have > > installed the sqlite packages fromcygwin(that is libsqlite3-devel > > and libsqlite3_0). ?When attempting to easy_install pysqlite I get: > > > $ easy_install pysqlite > > Searching for pysqlite > > Readinghttp://pypi.python.org/simple/pysqlite/ > > Readinghttp://pysqlite.org/ > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ > > Readinghttp://pysqlite.sourceforge.net/ > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/ > > Readinghttp://initd.org/tracker/pysqlite/wiki/PysqliteDownloads > > Readinghttp://oss.itsystementwicklung.de/trac/pysqlite > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/ > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/ > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/ > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/ > > Best match: pysqlite 2.5.0 > > Downloadinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlit... > > Processing pysqlite-2.5.0.tar.gz > > Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/ > > Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg- > > dist-tmp-7mr3WS > > warning: no files found matching 'doc/*.html' > > warning: no files found matching 'doc/code/*.py' > > src/statement.c: In function `pysqlite_statement_recompile': > > src/statement.c:351: warning: `sqlite3_transfer_bindings' is > > deprecated (declared at /usr/include/sqlite3.h:3985) > > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function > > `pysqlite_enable_load_extension': > > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ > > pysqlite-2.5.0/src/connection.c:922: undefined reference to > > `_sqlite3_enable_load_extension' > > collect2: ld returned 1 exit status > > error: Setup script exited with error: command 'gcc' failed with exit > > status 1 > > $ > > > It seems to me this is due to some missing library (undefined > > reference...) but I have no idea what these missing files might be. > > I've tried installing everything that made any reference to sqlite > > form thecygwininterface. ?Does anyone know how I might get a working > > install of sqlite for python oncygwin? > > I believe it's a glitch in the 2.5.1 distribution current onCygwin- I > had to install the _sqlite DLL separately to get it to work, but no > recompilation was necessary AFAICR. > > Chui Tey detailed the necessary steps in his blog post "CygwinPython > and sqlite3", but sadly it got lost and he hasn't replenished it, so you > will have to stab around to see if there's a cached copy anywhere. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Well, I haven't managed to solve the problem. I tried following these instructions but get the same error: http://initd.org/pub/software/pysqlite/doc/install-source-win32.html And I also tried downloading the dll from sqlite.org and putting it on my path. Since someone asked how I ended up solving this problem: I'm just going to work on my Linux box where its relatively straight forward to install this stuff with the package manager. If someone does have instructions for making this work on windows I'd be very curious. I was unable to find an archived version of the blog post referenced above. From mail at microcorp.co.za Wed Sep 3 16:34:50 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 3 Sep 2008 22:34:50 +0200 Subject: How to write verbose scripts Message-ID: <001901c90e06$44e327e0$0d00a8c0@hendrik> Steven D'Aprano wrote: >Is there a better way of doing this than the way I am going about it? Not sure if its "better", but I would keep the messages in a table or dict and have different tables or dicts for different levels of verbosity, and write a displayer that knows about the verbosity - This approach has the advantage that you can write in English and have different verbosities in different languages too, if the displayer knows about the language. Verbosity level and language can be display class attributes, and then you can simply write something like: display.display("squawk") and get one of: squawk squawk, squawk, squawk squawk - help the bastards are trying to nail me to my perch! or the equivalent in Icelandic or Norwegian. It works, but its a PITA to implement because you have to formally construct the stuff, and keep them all in sync, across languages and levels of verbosity. This of course will only work for static messages - If you compute what you display, I guess you need to either keep the computation in the displayer, or pass it in, or something - gets messy. Keeps the code clear though, as it splits what you display away from the decision of saying something. I try to avoid it if I can. - Hendrik From gagsl-py2 at yahoo.com.ar Sun Sep 7 18:03:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 19:03:52 -0300 Subject: lacking follow-through References: Message-ID: En Sun, 07 Sep 2008 18:00:30 -0300, castironpi escribi?: > I am concerned by the lack of follow-through on some responses to > recent ideas I have described. Do I merely have a wrong understanding > of group policy? Is it a good policy (defined with respect to the > future of Python and the welfare of humans at large) if so? Is there > a serious lack of diligence, or should I merely take more initiative, > and ignore charges of 'pestering'? (Warning, moderately deep outside > social issues on table too.) Maybe people just doesn't have anything to say? Last thing I remember from you, is some mmap-based tree, and I'm not interested. -- Gabriel Genellina From bj_666 at gmx.net Thu Sep 18 13:00:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Sep 2008 17:00:26 GMT Subject: PEP proposal optparse References: Message-ID: <6jffpaF2s539U1@mid.uni-berlin.de> On Thu, 18 Sep 2008 11:07:45 -0500, Grant Edwards wrote: > While we're making suggestions, I've always wished that the --help > output displayed the default values for options in addition to the help > text specified by the user. I end up having to enter the default values > twice -- once as a keyword argument and again in the help text. '%default' in the help text will be replaced by the default value. See the last option in the first example here: http://docs.python.org/lib/optparse-generating-help.html Ciao, Marc 'BlackJack' Rintsch From timothy.grant at gmail.com Thu Sep 11 16:02:18 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 11 Sep 2008 13:02:18 -0700 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: References: <943393.38616.qm@web95111.mail.in2.yahoo.com> Message-ID: On Thu, Sep 11, 2008 at 12:02 PM, Daniel Fetchinson wrote: > > >>> Thanking you, >>> >>> Ms. Vaidehi Pawar >> >> How much do you pay? >> >>> How much do you ask for???? >>> >>> cheers >>> Ms. Vaidehi > > I was just kidding. But if you seriously need people to do this kind > of job it's better to post the amount you are willing to pay otherwise > nobody will take it seriously. > > Cheers, > Daniel > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown > -- > http://mail.python.org/mailman/listinfo/python-list > I find it impossible to take anyone asking others to do their school work for them seriously no matter how or what they are willing to pay. -- Stand Fast, tjg. [Timothy Grant] From ppearson at nowhere.invalid Sun Sep 21 13:37:47 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 21 Sep 2008 17:37:47 GMT Subject: BeautifulSoup and Problem Tables References: Message-ID: <6jnf3bF47453U1@mid.individual.net> On Sat, 20 Sep 2008 20:51:52 -0700 (PDT), academicedgar at gmail.com wrote: [snip] > from BeautifulSoup import BeautifulSoup > bst=file(r"c:\bstest.htm").read() > soup=BeautifulSoup(bst) > rows=soup.findAll('tr') > len(rows) > a=len(rows[0].findAll('td')) > b=len(rows[1].findAll('td')) > c=len(rows[2].findAll('td')) > d=len(rows[3].findAll('td')) > e=len(rows[4].findAll('td')) > f=len(rows[5].findAll('td')) > g=len(rows[6].findAll('td')) > h=len(rows[8].findAll('td')) > i=len(rows[9].findAll('td')) > j=len(rows[10].findAll('td')) > k=rows[1].findAll('td')[1].contents[0] [snip] > However, I discovered that my tables have inconsistent numbers of > rows. [snip] > I have been Googling for some insight into this and I have not been > successful finding anything. I would really appreciate any suggestions > or some direction about how to better describe the problem. Would it be accurate to describe the problem as wanting to extract the contents of the cth column of the rth row of a table in spite of various pathologies in the construction of the table? If so, maybe it would help to post sample HTML (trimmed to a minimum) of the pathologies that must be handled. I gotta confess, though, that it doesn't take many rowspans or colspans to put this problem beyond my reach. -- To email me, substitute nowhere->spamcop, invalid->net. From tjreedy at udel.edu Sat Sep 27 17:41:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2008 17:41:42 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> Message-ID: Aahz wrote: > In article <8763oiuhj2.fsf at benfinney.id.au>, > Ben Finney wrote: >> Steven D'Aprano writes: >>> I'd like to be able to call [a class] as if it were a function. >>> Normally calling a class object returns an instance -- I wish to >>> return something else. >> In that case, you *don't* want a class at all; the entire point of a >> class is to define behaviour for instances. > > Absolutely agreed with your first clause, disagreed about the second > clause. As I said earlier, the main point of a class singleton is to get > the effect of a module singleton without the need to create another file > on disk. In 3.0, at least, one does not need a disk file to create a module. >>> import types >>> me = types.ModuleType('me') # type(__builtins__) works, no import >>> me >>> me.a = 1 >>> me.a 1 >>> me.a + 1 2 That said, a blank class is even easier, and the representation is better. tjr From tommy.nordgren at comhem.se Thu Sep 4 16:18:53 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Thu, 4 Sep 2008 22:18:53 +0200 Subject: Converting .doc to .txt in Linux In-Reply-To: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> References: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: On Sep 4, 2008, at 9:54 PM, patrick.waldo at gmail.com wrote: > Hi Everyone, > > I had previously asked a similar question, > http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gst&q=convert+doc+txt#9dc901da63d8d059 > > but at that point I was using Windows and now I am using Linux. > Basically, I have some .doc files that I need to convert into txt > files encoded in utf-8. However, win32com.client doesn't work in > Linux. > > It's been giving me quite a headache all day. Any ideas would be > greatly appreciated. > > Best, > Patrick > > #Windows Code: > import glob,os,codecs,shutil,win32com.client > from win32com.client import Dispatch > > input = '/home/pwaldo2/work/workbench/current_documents/*.doc' > input_dir = '/home/pwaldo2/work/workbench/current_documents/' > outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/' > > for doc in glob.glob1(input): > WordApp = Dispatch("Word.Application") > WordApp.Visible = 1 > WordApp.Documents.Open(doc) > WordApp.ActiveDocument.SaveAs(doc,7) > WordApp.ActiveDocument.Close() > WordApp.Quit() > > for doc in glob.glob(input): > txt_split = os.path.splitext(doc) > txt_doc = txt_split[0] + '.txt' > txt_doc_path = os.path.join(outpath,txt_doc) > doc_path = os.path.join(input_dir,doc) > shutil.copy(doc_path,txt_doc_path) > -- > http://mail.python.org/mailman/listinfo/python-list You can do it manually with Open Office. A free office suite. ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From toddw at activestate.com Wed Sep 17 18:53:29 2008 From: toddw at activestate.com (Todd Whiteman) Date: Wed, 17 Sep 2008 15:53:29 -0700 Subject: ANN: Python GUI development using XULRunner In-Reply-To: <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> References: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> Message-ID: <48D18A69.2010009@activestate.com> support at mysfdomain.com wrote: > On Sep 17, 1:21 pm, Todd Whiteman wrote: >> Don Spaulding wrote: >>> On Sep 16, 8:29 pm, Todd Whiteman wrote: >>>> I've put together a tutorial that shows off how to build a GUI >>>> application using XULRunner (same architectural components as Firefox >>>> uses) that can be used in conjunction with the Python programming language. >>>> The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... >>> I get to the "Running" step and run into "Couldn't load XPCOM." >>> Does this work on x86_64? Or have I made a rookie mistake? >> Hi Don, >> >> A good question. Mozilla only provide 32-bit XulRunner applications by >> default, you you'll need to install the necessary 32-bit compatability >> libraries on your Linux machine, i.e. for Ubuntu it's something like: >> sudo apt-get install ia32-libs ia32-libs-gtk >> >> Then you should be able to run the example. You can check the >> dependencies using something the following commands, there should be no >> missing dependencies: >> $ cd pyxpcom_gui_app/xulrunner >> $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin >> >> It is possible to use a 64-bit version, but you'll need to compile this >> yourself (or find somewhere that provides these x86_64 versions). Note >> that the PythonExt project does not offer Python bindings for x86_64 >> either (it's on my todo list), you can compile the PythonExt part >> yourself as well if you need a 64-bit version. >> >> Cheers, >> Todd > > Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs > and ia32-libs-gtk installed. > > ldd shows that I'm missing the following libs, even though the proper > packages are installed, and the files show up in /usr/lib. > > libxcb-render-util.so.0 => not found > libxcb-render.so.0 => not found > > There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render- > util, so I wonder if that could be part of the problem? > > > Don Hi Don, I'm thinking there may be additional 32-bit packages necessary then (I'm not sure which package). Not sure about Ubuntu 8.10 (it's still alpha). I'm using a Ubuntu 8.04 x86_64 machine and my dependencies list the following for the latest 32-bit build of XulRunner: $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin | grep libxcb libxcb-xlib.so.0 => /usr/lib32/libxcb-xlib.so.0 (0xf6493000) libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf647b000) Cheers, Todd From deets at nospam.web.de Sat Sep 6 10:13:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Sep 2008 16:13:22 +0200 Subject: How to bring subprocess to the foreground? In-Reply-To: References: Message-ID: <6ifhg2Fq24n6U1@mid.uni-berlin.de> dudeja.rajat at gmail.com schrieb: > Hi, > > I've a batch file that I open with the subprocess .Popen() . When this > batch file is run I want to bring it to the foreground. > > Please suggest how can I do this? You can't. You can capture the stdout using the pipe-arguments, and in your main-process, read that and write it to the main process' stdout. Diez From hv at tbz-pariv.de Thu Sep 11 06:43:34 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Thu, 11 Sep 2008 12:43:34 +0200 Subject: Better error message on recursive import Message-ID: <6isb2mF9scaU1@mid.individual.net> Hi, why does Python only raise ImportError if it fails caused by a recursive import? I know what's wrong. But I guess many beginner don't know what's wrong. I don't want much, just "RecursiveImportError" instead of "ImportError". Is this possible? Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From nick at craig-wood.com Fri Sep 12 12:36:42 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 12 Sep 2008 11:36:42 -0500 Subject: dict slice in python (translating perl to python) References: Message-ID: Steven D'Aprano wrote: > On Thu, 11 Sep 2008 03:36:35 -0500, Nick Craig-Wood wrote: > > > As an ex-perl programmer and having used python for some years now, I'd > > type the explicit > > > > v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > > > > Or maybe even > > > > v1 = mydict['one'] # 54 chars > > v2 = mydict['two'] > > v3 = mydict['two'] > > > > Either is only a couple more characters to type. > > But that's an accident of the name you have used. Consider: > > v1,v2,v3 = section_heading_to_table_index['one'], \ > section_heading_to_table_index['two'], \ > section_heading_to_table_index['two'] # 133 characters > > versus: > > v1,v2,v3 = [section_heading_to_table_index[k] for k in > ['one','two','two']] # 75 characters > > It also fails the "Don't Repeat Yourself" principle, and it completely > fails to scale beyond a handful of keys. If you have more than a handful of keys then you have a different problem (far too many local variables) with your code I think! DRY is a good principle. I still prefer the 3 explicit assignments though ;-) > Out of interest, on my PC at least the list comp version is significantly > slower than the explicit assignments. So it is a micro-optimization that > may be worth considering if needed -- but at the cost of harder to > maintain code. > > > It is completely > > explicit and comprehensible to everyone, in comparison to > > > > v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > > v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars > > That's a matter for argument. I find the list comprehension perfectly > readable and comprehensible, and in fact I had to read your explicit > assignments twice to be sure I hadn't missed something. But I accept that > if you aren't used to list comps, they might look a little odd. A matter of taste certainly! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From shahmed at sfwmd.gov Wed Sep 3 13:31:38 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Wed, 3 Sep 2008 13:31:38 -0400 Subject: Using strftime In-Reply-To: <4841b103-be8c-471f-8903-1b9284bd3a39@k13g2000hse.googlegroups.com> References: <4841b103-be8c-471f-8903-1b9284bd3a39@k13g2000hse.googlegroups.com> Message-ID: You can try Import time mytimeymd = time.strftime('%y%m%d') print mytimeymd -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of frankrentef Sent: Wednesday, September 03, 2008 1:21 PM To: python-list at python.org Subject: Using strftime I have one line of code that put's an old date in my code. ie.textBoxSet('_ct10_PlaceHolder_txtEnd', '8/15/2008') What I wish to do in another similiar line is have the field populated with the current system date? How best to do this? I've read some of the strftime documentation but as of yet I'm unable to get it to work correctly. Help is appreciated. THNX -- http://mail.python.org/mailman/listinfo/python-list From rsinger at ____.com Mon Sep 29 19:09:23 2008 From: rsinger at ____.com (Robert Singer) Date: Tue, 30 Sep 2008 01:09:23 +0200 Subject: pyXLWriter warnings Message-ID: Platform: winXP, excel 2003 Python 2.5.2 XLWriter 0.4a3 (http://sourceforge.net/projects/pyxlwriter/) Is anyone here using this very nice package, for writing excel files? I'm using it on python 2.5.2. (although it is made for older version of python) and cannot find a way to get rid of this error (code and errors below). Does anyone know how to avoid it ? I would appreciate all help and ideas you can think of. Bob -------- >>> import pyXLWriter as xl >>> workbook = xl.Writer("test.xls") >>> worksheet = workbook.add_worksheet('first') >>> worksheet.write([3,3], "Hello doc !") >>> worksheet.write_comment([3,3], "I'm hunting for a wabbit") 0 >>> workbook.close() -------- Warning (from warnings module): File "C:\Python25\lib\site-packages\pyXLWriter\OLEWriter.py", line 135 unknown3 = pack(">> From benjamin.kaplan at case.edu Tue Sep 9 11:42:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 9 Sep 2008 11:42:31 -0400 Subject: Orientation on MySql using python In-Reply-To: References: Message-ID: On Tue, Sep 9, 2008 at 9:36 AM, Jo?o Abrantes wrote: > Hello everyone, I want to make a program in python that uses Mysql aswell.. > I don't know anything about mysql can you tell me some good books/tutorials > where I can read something about mysql using python? Thanks. > > ------------------------------ > Did you try looking at MySQL's website? http://dev.mysql.com/usingmysql/python/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From gioco at nekhem.com Wed Sep 3 06:36:30 2008 From: gioco at nekhem.com (Corrado Gioannini) Date: Wed, 3 Sep 2008 12:36:30 +0200 Subject: email.Message problem In-Reply-To: References: <20080902160417.GA20438@zephyr> Message-ID: <20080903103630.GC11421@zephyr> On Tue, Sep 02, 2008 at 04:50:15PM -0300, Gabriel Genellina wrote: > > messg = email.message.Message() > > Replace this line with: > messg = email.mime.multipart.MIMEMultipart() > *OR* > Set the Content-Type header to "multipart/mixed" *before* anything else. thanks Gabriel! i coudn't have thought that setting the header in a different order could affect the as_string method. i'll take a look at the code. :) c. -- no, sono sempre io, non mi cambierete quel che ho dentro forse ho solo un'altra faccia ho pi? cicatrici di prima, sorrido un po' meno, forse penso di pi?. (Kina) From stef.mientki at gmail.com Thu Sep 25 12:18:16 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 18:18:16 +0200 Subject: How to get the filename in the right case ? In-Reply-To: References: <6k1dukF5hk86U1@mid.uni-berlin.de> Message-ID: <48DBB9C8.6090500@gmail.com> OKB (not okblacke) wrote: > Stef Mientki wrote: > >>>>> import Module1 >>>>> >>> d:\data_python_25\pylab_works\module1.py(3)() >>> >> -> print "hello" >> (Pdb) >> >> >>> Then we know if PDB is really the culprit. >>> >>> >>> >> So pdb is the problem. >> > > Yep, it does the same thing for me. > > >>> Apart from that, is that really a problem that the filenames are >>> all lower case? AFAIK Windows is case-insensitive regarding >>> filenames anyway. So opening the file by just passing the filename >>> should work seamless. >>> >>> >> Yes windows is, >> but Python is not. >> My program should run on Windows and Linux (and maybe a few >> others). By converting everything to lowercase, on Linux I can't >> distinguishes between 2 files with the same name but a different >> case (btw, giving 2 files the same name, only differing in case, >> looks like a bad idea to me). >> > > Hmmm, but I don't understand what you're doing here. Are you > somehow storing the filename that pdb outputs and you need to use it > later on a potentially different OS? If the case is preserved in pdb on > linux, then presumably running it on linux will be fine, right? It's > only a problem if you somehow try to use a filename created by windows- > pdb to open a file (the same file, somehow) on linux. > > 1. I've a multitab editor. 2. When a breakpoint is reached, 3. I check if the file specified in pdb output, is already open in one of the editor tabs, 4. if not, I open a new tab with the correct file, 5. I focus the correct editor tab and jump to the line specified by pdb. 6. After that I should be able to inspect the surrounding of the breakpoint, so I need the modules name. For 3 I need to compare filenames, the editor contains the case sensitive name, pdb not. For 6 I also need the case sensitive filename, but probably there's another way to get the modules name. For 3, I can indeed compare the lowercase version of both, probably I'll do that for the moment. thanks guys for the suggestions Stef From wuwei23 at gmail.com Sun Sep 21 19:50:51 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 21 Sep 2008 16:50:51 -0700 (PDT) Subject: appending * to glob returns files with '*' !! References: Message-ID: On Sep 20, 6:37?am, "John [H2O]" wrote: > My routine cannot handle the '*' and it should'nt be returned anyway? :-/ > > A bug? Not at all. That's the same behaviour you'll get if you do 'ls EN*'. In your case, you're asking to match on anything that begins with EN, a subset of files that -includes- EN*. Why do you consider this behaviour surprising? From israelu at elbit.co.il Wed Sep 3 11:27:36 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 3 Sep 2008 08:27:36 -0700 (PDT) Subject: os.system dual behaviour Message-ID: Hi guys I do os.system('ls &> e') On one linux machine it emits ls output to the file e as expected. On another linux machine it emits ls to the standard output, and nothing to e! Both machines run Fedora linux. The command "ls &> e" entered at the shell (no python) behaves ok on both machines. Why?? How can I solve this? Your help will be appreciated. From joefazee at gmail.com Mon Sep 15 04:54:05 2008 From: joefazee at gmail.com (A. Joseph) Date: Mon, 15 Sep 2008 01:54:05 -0700 Subject: Converting between binary, decimal, hexadecimal, octal Message-ID: Converting between binary, decimal, hexadecimal, octal Where can I find good tutorial on numbering system? I really want to know the process of converting between all the numbers. I may soon start HLA (assemply). Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Sep 24 23:36:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2008 23:36:18 -0400 Subject: Schwartzian transform for tuple in list In-Reply-To: <7C3B1753-3E7A-4E1F-B102-3387FB0152A4@gmail.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <7C3B1753-3E7A-4E1F-B102-3387FB0152A4@gmail.com> Message-ID: David Di Biase wrote: > When you say slightly, is it enough to make a difference? Why would > getitems be faster even - not sure I can think why... > Using key is faster than cmp because key is called just once for each item whereas cmp is called once for each of the O(nlogn) compares. Operator.itemgetter is written in C and hence should be faster than a wrapper written in Python. From tamim.shahriar at gmail.com Sat Sep 6 18:55:26 2008 From: tamim.shahriar at gmail.com (subeen) Date: Sat, 6 Sep 2008 15:55:26 -0700 (PDT) Subject: Learning Python References: Message-ID: On Sep 6, 3:17?pm, James Pilling wrote: > Hi im currently starting to learn python in sixth form at school any tips? > Just pickup a good book and make sure you code all the examples and exercises yourself, even if it seems easy. Have fun with Python! regards, Subeen. http://love-python.blogspot.com From george.sakkis at gmail.com Tue Sep 23 10:13:16 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 23 Sep 2008 07:13:16 -0700 (PDT) Subject: Python is slow? References: Message-ID: <28f1b350-9908-4056-bfa2-e6c2d9edb17d@i76g2000hsf.googlegroups.com> On Sep 23, 9:57 am, Grant Edwards wrote: > On 2008-09-23, sturlamolden wrote: > > [...] > > > After having a working Python prototype, I resorted to rewrite the > > program in C++. The Python prototype took an hour to make, debug and > > verify. The same thing in C++ took me almost a day to complete, even > > with a working prototype as model. To my surprise, the resulting beast > > of C++ required 64.3 seconds to construct the same kd-tree. Searching > > the tree was not faster either, 1,000 points required 38.8 seconds. I > > wasted a day, only to find my Python prototype being the faster. > > > We may conclude that I'm bad at programming C++, > > AFAICT, _everybody_ is bad at programming C++. +1 QOTW From rocksportrocker at googlemail.com Thu Sep 18 12:06:09 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 18 Sep 2008 09:06:09 -0700 (PDT) Subject: Automated Build System ? Message-ID: <3468bd3f-d6a3-477a-8537-48d67522700a@j22g2000hsf.googlegroups.com> Hi, I'm working on a python Package which includes some extension modules and unit tests. I want to automate some tasks like "build extsion module, then copy xxx.pyd to folder yyy and run all unit tests from folder zzzz". I used google but found no hints to existing solutions. Can anybody help me ? Greetings, Uwe From gogtesuyash at gmail.com Mon Sep 29 23:47:35 2008 From: gogtesuyash at gmail.com (sui) Date: Mon, 29 Sep 2008 20:47:35 -0700 (PDT) Subject: python & sms Message-ID: Hii i want a script to send sms to any mobile..... can u help me ?? Thanks in advance...... From tino at wildenhain.de Wed Sep 17 14:34:37 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 17 Sep 2008 20:34:37 +0200 Subject: translating ascii to binary In-Reply-To: <48d13fa2$0$27103$9a622dc7@news.kpnplanet.nl> References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> <00e12f1f$0$20331$c3e8da3@news.astraweb.com> <48d13fa2$0$27103$9a622dc7@news.kpnplanet.nl> Message-ID: <48D14DBD.5050306@wildenhain.de> hi, Canned wrote: > Steven D'Aprano schreef: >> Your "ascii_to_bin" method tries to do too much in one method. You should >> split the functionality into small, self-contained pieces, then combine >> them. And frankly, once you got to the part where you started popping and >> inserting, my brain melted. You are making an easy job too hard! *smiles* >> > It's a bad habit, I can't help it. From now on, I'll follow your advice > to split the functionality into small, self-contained pieces. That > popping and inserting is just a workaround for another workaround. just got an interesting idea for the core of the converter, maybe you like it: def int_to_bin(v): i=1 d=1 a=0 while i>> int_to_bin(5) 101 >>> print "%08d" % int_to_bin(5) 00000101 I think the formatting bit is a tad nicer then '0' * (8-len(...))) Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From FettManChu at gmail.com Thu Sep 4 14:39:42 2008 From: FettManChu at gmail.com (Fett) Date: Thu, 4 Sep 2008 11:39:42 -0700 (PDT) Subject: Can anyone suggest a good crypto package? Message-ID: I need a crypto package that works on windows with python 2.5. Can anyone suggest one for me? I have been searching for a couple days for a good cryptography package to use for public/private key encryption, at this point I would settle for symmetric even. Every encryption package I have found for python was either operating system specific (read *nix only): http://www.freenet.org.nz/ezPyCrypto/ http://www.keyczar.org/ There was one exception, this version was specifically built to run on any platform (yay), but the compiler for windows complained that I wasn't using python2.2 (though the package was said to only need 2.2 or newer). Is there any crypto package that is actually written in python? I seriously don't care how slow it is. From Ripter001 at gmail.com Wed Sep 3 22:46:14 2008 From: Ripter001 at gmail.com (Ripter) Date: Wed, 3 Sep 2008 19:46:14 -0700 (PDT) Subject: Help Understanding weakref (lazyloader) Message-ID: I found this script at http://www.pygame.org/wiki/LazyImageLoading?parent=CookBook And I can't quite figure out how it works. I was wondering if someone could clarify it for me. The Code is: import pygame import weakref class ResourceController(object): def __init__(self, loader): self.__dict__.update(dict( names = {}, cache = weakref.WeakValueDictionary(), loader = loader )) def __setattr__(self, name, value): self.names[name] = value def __getattr__(self, name): try: img = self.cache[name] except KeyError: img = self.loader(self.names[name]) self.cache[name] = img return img class ImageController(ResourceController): def __init__(self): ResourceController.__init__(self, pygame.image.load) My question is why does the __setattr__ set the value to self.names[name] instead of self.cache[name]? From exarkun at divmod.com Fri Sep 5 15:29:34 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 5 Sep 2008 15:29:34 -0400 Subject: Need formatting suggestion for long strings In-Reply-To: <496954360809051224i66123029s23a5ab2f02d8be2b@mail.gmail.com> Message-ID: <20080905192934.29191.496947365.divmod.quotient.22130@ohm> On Fri, 5 Sep 2008 14:24:16 -0500, Robert Dailey wrote: >Hi, > >I find quite often that I'm writing things like this: > >raise FatalExcept( "Insufficient number of arguments specified. Exactly {0} >arguments are required. See stage.bat for documentation on accepted >parameters.".format( num_arguments ) ) > >On my display (Vertical monitor), this exceeds the width of my display, and >to view the entire length of the string I am forced to pan my view left and >right. Is there a special way I can format this string so that it fits >nicely on the screen? Keep in mind that one important factor is that >whitespace is very sensitive, and I do not want line breaks in my script >file to become part of the string itself. I like how C++ handles strings, >like this: > >char const* mystring = > "This is a very long string that " > "spans multiple lines and does " > "not include line breaks or tabs " > "from the source file between " > "the strings partitions." > > >What do you guys prefer? Thanks for reading. > mystring = ( "This is a very long string that " "spans multiple lines and does " "not include line breaks or tabs " "from the source file between " "the strings partitions.") Jean-Paul From prologic at shortcircuit.net.au Sun Sep 21 18:54:43 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 08:54:43 +1000 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: Hi, Wouldn't a normal class called State suffice for storing state between calls ? And ... Creating a state instance ? For example: class State(object): """State() -> new state object Creates a new state object that is suitable for holding different states of an application. Usefull in state-machines. The way this works is rather simple. You create a new state object, and simply set the state. If the state doesn't exist, it's added to it's internal data structure. The reason this is done is so that comparing states is consistent, and you can't just compare with a non-existent state. """ def __init__(self): "initializes x; see x.__class__.__doc__ for signature" self._states = {} self._next = 0 # Default States self._add("START") self._add("DONE") def __repr__(self): try: return "" % self._state except AttributeError: return "" def __str__(self): return self._state def __eq__(self, s): return s in self._states and self._state == s def __lt__(self, s): return s in self._states and self._state == s and \ self._states[s] < self._states[self._state] def __gr__(self, s): return s in self._states and self._state == s and \ self._states[s] > self._states[self._state] def _add(self, s): self._states[s] = self._next self._next = self._next + 1 def set(self, s): """S.set(s) -> None Set the current state to the specified state given by s, adding it if it doesn't exist. """ if s not in self._states: self._add(s) self._state = s cheers James On Mon, Sep 22, 2008 at 8:39 AM, Steven D'Aprano wrote: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bearophileHUGS at lycos.com Tue Sep 23 14:52:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 23 Sep 2008 11:52:16 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: sturlamolden: >F# and OCaml look promising though.< I bet on the future of D and Haskell (and maybe Fortress) instead :-) We'll see. >Sure I could show you the code, Python and C++, if I had a place to post it.< I think the Python version suffices. If it's not too much private you may post the single minimal/reduced runnable Python module here, it will be deleted in some time (if you want you can also use a private paste): http://codepad.org/ >It looks very different form yours though.< Is this a good or bad thing? ;-) Bye, bearophile From stephane at harobed.org Mon Sep 8 18:04:29 2008 From: stephane at harobed.org (=?iso-8859-1?q?KLEIN_St=E9phane?=) Date: Mon, 8 Sep 2008 22:04:29 +0000 (UTC) Subject: Where does the command "ls" in some doctest files come from ? References: <00d51a07$0$20306$c3e8da3@news.astraweb.com> Message-ID: Le Mon, 08 Sep 2008 12:51:04 +0000, Steven D'Aprano a ?crit?: > On Mon, 08 Sep 2008 12:15:15 +0000, KLEIN St?phane wrote: > >> Hi, >> >> for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/ >> tests.py?rev=89831&view=auto test file, there is this doctests : > > [snip] > >> >>> ls('develop-eggs') > > >> I wonder where does the "ls('develop-eggs')" command come from ? >> >> It is doctest buildin command ? > > Easy to find out: import doctest and see for yourself: > >>>> import doctest >>>> doctest.ls > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'ls' > > You found the ls() function in a docstring from Zope. The doctest seems > to be testing ls(). That suggests to me that ls() is defined in Zope, > not doctest. Well, ls() is one test utility function defined in zc.buildout.testing module. This module contain many utility function like mkdir, ls, cat... > Why do you ask? I'm curious... I've seen this utility and I would like to know how can I use it. Regards, Stephane From steve at REMOVE-THIS-cybersource.com.au Tue Sep 30 09:43:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 13:43:58 GMT Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> Message-ID: <00f226c8$0$20617$c3e8da3@news.astraweb.com> On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: >> > You're not free to modify gnuplot and redistribute the result. >> > >> > That you're free to distribute patches is nice, but it's not enough >> > to make the work free. The freedom to help people by giving them an >> > *already-modified* gnuplot is restricted by the copyright holder. >> > >> > It's an artificial restriction on redistribution of derived works, >> > making them second-class for the prupose of getting them into >> > people's hands. >> >> Yes it is. It seems a strange, unnecessary restriction. But is it >> sufficient to make it non-free? I don't think so. > > I do, because a natural, beneficial act (modify the work and > redistribute it) that has no technical reason to restrict, is > artifically restricted. We agree that the restriction is artificial, and I think irrational (although I'd be interested in hearing the gnuplot developers' reasoning before making a final judgment). But I just don't see the requirement that modified software be distributed in form X (original source + diffs) versus form Y (modified source in a tar ball) or form Z (an rpm) to be that big a deal. Not enough to make it "non-free software". I simply don't think that having to run some variation on patch -i patchfile.patch is a requirement so onerous that it makes the gnuplot licence non-free. Perhaps I'm just more tolerant of eccentricities than you :) -- Steven From jjl at pobox.com Wed Sep 3 17:49:28 2008 From: jjl at pobox.com (John J Lee) Date: Wed, 3 Sep 2008 22:49:28 +0100 (BST) Subject: [wwwsearch-general] python mechanize/libxml2dom question In-Reply-To: <108c01c90cad$28dd5840$0301a8c0@tmesa.com> References: <108c01c90cad$28dd5840$0301a8c0@tmesa.com> Message-ID: On Mon, 1 Sep 2008, bruce wrote: [...] > how can i [...] > libxml2dom [...] Just a general point: try lxml.etree instead? Friendlier API. John From ptmcg at austin.rr.com Sat Sep 13 12:49:18 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 13 Sep 2008 09:49:18 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? References: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> Message-ID: <2fb7c936-7c2c-4c1a-aed8-93dc3e7e342a@w7g2000hsa.googlegroups.com> On Sep 12, 8:08?pm, i... at illusorygoals.com wrote: > First off, I'm a python n00b, so feel free to comment on anything if > I'm doing it "the wrong way." I'm building a discrete event simulation > tool. I wanted to use coroutines. However, I want to know if there's You could "look in the back of the book" - download SimPy and see how they does this. -- Paul From bignose+hates-spam at benfinney.id.au Mon Sep 15 00:04:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 14:04:35 +1000 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: <87od2q5a24.fsf@benfinney.id.au> Adelle Hartley writes: > I'm looking at porting a library that was written for COM and .Net > to work as a Python module, and was wondering whether it would be > better to stick to the library's current naming convention so that > the API is as similar as possible on each platform, or to adopt a > "when in Rome..." policy and follow the "most mainstream" naming > pattern for each platform/language. I think it's more important for Python library APIs to comply with the Python coding guidelines (as specified in PEP 8) than to comply with standards in other languages. The Python library you're implementing isn't being used in those other languages, so the conventions of other languages have little relevance. It's being used in Python code, so it should mesh well with PEP 8 compliant code ? by having the API itself comply with PEP 8. -- \ ?When cryptography is outlawed, bayl bhgynjf jvyy unir | `\ cevinpl.? ?Anonymous | _o__) | Ben Finney From fredrik at pythonware.com Sun Sep 21 12:36:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 18:36:20 +0200 Subject: Why are "broken iterators" broken? In-Reply-To: References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: Roy Smith wrote: > There are plausible examples of collections which grow while you're > iterating over them. I'm thinking specifically of a queue in a > multi-threaded application. One thread pushes work onto the back of the > queue while another pops from the front. The queue could certainly go > empty at times. But, maybe a Python iterator is just the wrong way to > model such behavior. you probably want the consumer thread to block when it catches up with the producer, rather than exit. (that's the default behaviour of Python's Queue object, btw) From gminick at bzt.bzt Mon Sep 1 06:59:12 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 10:59:12 +0000 (UTC) Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> <6i1rgcFo0f1gU1@mid.uni-berlin.de> <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> Message-ID: On Mon, 1 Sep 2008 03:51:13 -0700 (PDT), lee wrote: > i am soory for that keystrokes. can anyone tell me how can i change > the value of key. > suppose i have a dictionary > > kev = {'kabir': ['kabir at kabir.com', '1234', 'missuri'], 'shri': > ['shri at shri.com', '23423', 'india'], 'marsa': ['marsa at marsa.com', > '2345', 'brazil'], 'sandeep': ['sandeep at sandeep.com', '007', > 'canada']} > how can i change the key to something like 'sabir' and kev['sabir'] = kev['kabir'] del kev['kabir'] > how can i > change the values of kabir? kev['sabir'][0] = 'sabir at sabir.com' *untested* -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From python at hope.cz Mon Sep 1 02:25:56 2008 From: python at hope.cz (Johny) Date: Sun, 31 Aug 2008 23:25:56 -0700 (PDT) Subject: Processes in Linux from Python Message-ID: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> To get a number of the http processes running on my Linux( Debia box) I use ps -ef | grep "[h]ttpd" | wc -l But If I want to use to get a number of the http processes from my Python program I must use a popen command e.g. popen2.popen3('ps -ef | grep "[h]ttpd" | wc -l') that is I must call an external command from Python. But it creates a zombie. So my question is: Is it possible to get a number of the http processes running on Linux directly from Python ? Thanks for help. L. From wegwerp at gmail.com Wed Sep 24 09:58:05 2008 From: wegwerp at gmail.com (Bas) Date: Wed, 24 Sep 2008 06:58:05 -0700 (PDT) Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> Message-ID: <919aba9d-8076-4ac2-ae2c-a31921e1e4d0@34g2000hsh.googlegroups.com> On Sep 22, 10:02 am, Al Kabaila wrote: > There are several packages for matrix algebra. I tried Numeric, numpy and > numarray. All three are very good, but each uses different syntax. That argument might have been valid 3 years ago, but as already said by others, Numeric and Numarray are deprecated. Numpy should be the only thing needed for new users. I suggest you investigate a little bit more the next time you make such efforts, since this fact should be widely known among the users of the mentioned packages, see e.g. the huge warning at the numarray page: http://www.stsci.edu/resources/software_hardware/numarray/numarray.html > 1. Is there any interest in matrix algebra "for the masses" (I mean interest > in a wrapper for a subset of functions of the packages with a unified > simple syntax)? In my opinion, no. I might be biased, since with my matlab background I find numpy simple enough as is. But I don't see how A = B*C+D or E=dot(F,G) is complicated for a beginner of linear algebra. > My OS is Linux (openSUSE 10.3) and my interest in retirement is Python > applications to Structural Analysis of Civil Engineering structures, > currently in 2 dimensions only (under GPL). Modern Structural Analysis is > highly matrix oriented, but requires only a few basic matrix operations, > namely matrix creation, transposition, multiplication, invertion and > linear equation solution. For stability analysis one would require > Eigenvalues and Eigenvectors. In 3 dimensions, additionally highly > desirable would be vector algebra. The packages do have all these > functions, but currently only the basic functions are in the wrapper. If you care about contributing something useful to the community, I think your time and skills are better spent writing some cool mechanical analysis tool for inclusion in Scipy. Bas From sturlamolden at yahoo.no Thu Sep 25 05:18:14 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 02:18:14 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> On 25 Sep, 10:08, Duncan Booth wrote: > A lot of what LINQ does is already easy to do in Python, and most of the > rest can probably be added fairly easily, but it does provide a consistent > framework which may make it easier to do complex LINQ statements than > complex list comprehensions. Yes, that's the word, "consistent framework". I wonder what that means? Do you mean Python syntax is inconsitent? > BTW, a minor correction: LINQ statements are closer to generators, not list > comprehensions. They don't actually evaluate their results until you > iterate over them and you can re-used the same LINQ statement multiple > times getting different results if the data has changed. Python has generator expressions with the same syntax as list comprehensions, except you use () instead of []. From mhostetl at faeroes.freeshell.org Thu Sep 4 21:55:53 2008 From: mhostetl at faeroes.freeshell.org (Mike Hostetler) Date: Fri, 5 Sep 2008 01:55:53 +0000 (UTC) Subject: ctypes error on Windows Message-ID: I'm working on a script with the most excellent uTibyLib library. The script works just fine on Mac, but on Windows I get this: File "findtables.py", line 82, in cleanHTML return str(tidy.parseString(decentDoc)) File "c:\Python24\Lib\site-packages\tidy\lib.py", line 207, in parseString doc = self._create(**kwargs) File "c:\Python24\Lib\site-packages\tidy\lib.py", line 183, in _create doc = _Document() File "c:\Python24\Lib\site-packages\tidy\lib.py", line 135, in __init__ self.cdoc = _tidy.Create() File "c:\Python24\Lib\site-packages\tidy\lib.py", line 46, in __getattr__ return getattr(self.lib, name) File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 353, in __getatt func = self.__getitem__(name) File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 358, in __getite func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'Create' not found I do have the tidy.dll installed (if I didn't, I couldn't even import the tidy module). Anyone have any ideas to try? -- mhostetl at sdf.lonestar.org SDF Public Access UNIX System - http://sdf.lonestar.org From gagsl-py2 at yahoo.com.ar Mon Sep 29 21:31:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 22:31:58 -0300 Subject: adding in-place operator to Python References: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> <266557d0809251303k60d3a52eoc239917bc3597b27@mail.gmail.com> <266557d0809251304q49fec06er436d7b2a1db6b6f7@mail.gmail.com> Message-ID: En Thu, 25 Sep 2008 17:04:59 -0300, Arash Arfaee escribi?: > Thank you very much Gerhard and Terry. > > I am trying to add undefined state to some Boolean operator. Here is > what I > tried to do and It is not working: > > class _3ph: > def __init__(self): > self.value = 0 > > def __xor__(self,item): > if self.value==2 or item==2: > return 2 > else: > return self.__xor__(item) > > what I am trying to do is assigning 2 to undefined state and have xor > operator return 2 if one of inputs are 2. > it seems Although I defined xor in _3ph class, python treat any object > from > this class just like integer variables. Because you return a plain integer from __xor__, so the _3ph "magic" is lost. Try something like this: def xor3(v1, v2): # this should implement the actual logic if v1==2 or v2==2: return 2 return v1 ^ v2 class _3ph: def __init__(self, value=0): self.value = value def __xor__(self, item): if isinstance(item, _3ph): return _3ph(xor3(self.value, item.value)) else: return _3ph(xor3(self.value, item)) __rxor__ = __xor__ def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self.value) __str__ = __repr__ a = _3ph(0) b = _3ph(1) c = _3ph(2) print "a ", a print "b ", b print "c ", c print "a ^ a", a ^ a print "a ^ b", a ^ b print "a ^ c", a ^ c print "a ^ 0", a ^ 0 print "a ^ 1", a ^ 1 print "a ^ 2", a ^ 2 print "b ^ a", b ^ a print "b ^ b", b ^ b print "b ^ c", b ^ c print "b ^ 0", b ^ 0 print "b ^ 1", b ^ 1 print "b ^ 2", b ^ 2 print "c ^ a", c ^ a print "c ^ b", c ^ b print "c ^ c", c ^ c print "c ^ 0", c ^ 0 print "c ^ 1", c ^ 1 print "c ^ 2", c ^ 2 print "0 ^ a", 0 ^ a print "0 ^ b", 0 ^ b print "0 ^ c", 0 ^ c print "1 ^ a", 1 ^ a print "1 ^ b", 1 ^ b print "1 ^ b", 1 ^ c print "2 ^ a", 2 ^ a print "2 ^ b", 2 ^ b print "2 ^ c", 2 ^ c print "--- contrast" print "0 ^ 0", 0 ^ 0 print "0 ^ 1", 0 ^ 1 print "0 ^ 2", 0 ^ 2 print "1 ^ 0", 1 ^ 0 print "1 ^ 1", 1 ^ 1 print "1 ^ 2", 1 ^ 2 print "2 ^ 0", 2 ^ 0 print "2 ^ 1", 2 ^ 1 print "2 ^ 2", 2 ^ 2 (I've kept your _3ph name, but I think it's rather ugly... If the class is suposed to be public, its name should not start with an underscore. This is a *very* strong naming convention. See PEP8 http://www.python.org/dev/peps/pep-0008/ for some other stylistic recommendations) You may want to restrict the allowed values in __init__, by example. -- Gabriel Genellina From john.m.roach at gmail.com Tue Sep 9 12:41:17 2008 From: john.m.roach at gmail.com (john) Date: Tue, 9 Sep 2008 09:41:17 -0700 (PDT) Subject: F2PY changing integers to arrays??? Message-ID: <7d60c85f-12cf-47fc-84c9-58e50cad4eaf@x35g2000hsb.googlegroups.com> I have a simple module which performs basic operations on plot3d files (below). I wrapped like: f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 That seems to work fine, but i get some unexpected results... >>> from plot3d import plot3d as p3 >>> dir(p3) ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', 'writeit2d'] >>> p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) >>> p3.imax array(409) "409" is correct, but "imax" is declared as an INTEGER in fortran and now it's an array in python??? Any ideas? # prec.f90 MODULE prec IMPLICIT NONE INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) END MODULE prec # plot3d.f90 MODULE PLOT3D USE prec IMPLICIT NONE INTEGER, PARAMETER :: prc=single REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z INTEGER :: mg, imax, jmax, kmax CONTAINS !---------- SUBROUTINE READIT( fname, ftype, fmg ) ! reads the plot3d, formatted, mg file in xyz IMPLICIT NONE CHARACTER(len=20), INTENT(IN) :: fname, ftype LOGICAL :: fmg INTEGER :: i, j, k, n, f=1 SELECT CASE (ftype) CASE ('FORMATTED') OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', FORM=ftype ) IF (fmg) READ(f,*) mg ! only read if multigrid READ(f,*) imax, jmax, kmax ALLOCATE( x(mg, imax, jmax, kmax) ) ALLOCATE( y(mg, imax, jmax, kmax) ) ALLOCATE( z(mg, imax, jmax, kmax) ) READ(f,*) ((((x(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & ((((y(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & ((((z(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) CASE ('UNFORMATTED') OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', FORM=ftype ) IF (fmg) READ(f) mg ! only read if multigrid READ(f) imax, jmax, kmax ALLOCATE( x(mg, imax, jmax, kmax) ) ALLOCATE( y(mg, imax, jmax, kmax) ) ALLOCATE( z(mg, imax, jmax, kmax) ) READ(f) ((((x(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & ((((y(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & ((((z(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) CASE DEFAULT WRITE(*,*) 'filetype not supported in ' STOP END SELECT CLOSE(f) END SUBROUTINE READIT END MODULE PLOT3D From pavlovevidence at gmail.com Thu Sep 25 18:30:11 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 25 Sep 2008 15:30:11 -0700 (PDT) Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sep 25, 4:04?pm, "Gabriel Genellina" wrote: > En Thu, 25 Sep 2008 16:24:58 -0300, escribi?: > > > sorry, I have these ideas for longer than 10 years, please have a look ? > > on it > > and comment on it. Thx. > > > This is another proposal for introducing types into Python. > > You got the terminology wrong. Python had "types" from the very start. ? > You're talking about some kind of generic functions, or an alternative ? > dispatch method. > > Read this GvR blog post [1] and his next one; also see PEP 3124 by Phillip ? > J. Eby, who wrote a pretty good implementation of generic functions a long ? > time ago. > > Your proposal requires a syntax change and three new keywords; all the ? > others achieve roughly equivalent results without requiring any change to ? > the core language. Just to play Devil's advocate here, multimethods(**) aren't equivalent, roughly or otherwise, to what the OP is requesting. Superficially it looks that way, but the actual use case for this logic programming is something that ordinary multimethods can't do. Prolog-style programming is sort of the exact opposite of pure functional programming. Whereas in pure functional programming there are no side effects, in Prolog pretty much everything is a side effect. The way things happen in Prolog is execution of side effects in the process of searching for pattern matches. A decent multimethod implementation doesn't use trial and error for dispatch; it'll use some kind of mapping and cacheing to get to the appropriate function as quickly as possible. In logic programming however, the trial-and-error is essential since side-effects can and are supposed to happen in the process of trying. Anyway, this proposal can easily be implemented more or less as proposed without any syntax changes, using the same ideas as the multimethod implementations, but guaranteeing trial-and-error dispatching. Carl Banks (**) I avoid the term "generic function" since it constrasts starkly with the use of the word "generic" in generic programming. From half.italian at gmail.com Wed Sep 24 19:30:42 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 24 Sep 2008 16:30:42 -0700 (PDT) Subject: Folder Actions on Mac OSX Leopard? References: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> Message-ID: <6ea2a222-90be-4079-b78f-ead1e8f6d241@q26g2000prq.googlegroups.com> On Sep 24, 12:31?pm, "squishywaf... at gmail.com" wrote: > Greetings, > > I've been trying to figure out if it's possible to attach a Python > script to an action via Mac OSX Leopard's File Actions system. I'm > wanting to call a Python script every time a file is added to the > monitored folder. Just adding a .py file doesn't seem to do anything > at all, and I can't find any log output anywhere to see what's going > on. > > I'm more just looking to see if this is or is not possible. I'm not > interested in other solutions, as I already have them lined up in case > this is a no-go, but I'd really love to be able to do it this way if > anyone has any experience. Googling around revealed pretty much > nothing. > > Any help is much appreciated, > Greg I always wondered about Folder Actions... I just tested. You can have applescript call python scripts via `do shell script`. But it seemed a bit flakey. I would either go with applescript all the way, or look in to your other options. ~Sean From gatti at dsdata.it Thu Sep 18 03:53:46 2008 From: gatti at dsdata.it (Lorenzo Gatti) Date: Thu, 18 Sep 2008 00:53:46 -0700 (PDT) Subject: XML-schema 'best practice' question References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: <76cf5eaf-25fa-4a6c-ae7b-e57016f5cc52@y38g2000hsy.googlegroups.com> On 18 Set, 08:28, Frank Millman wrote: > I am thinking of adding a check to see if a document has changed since > it was last validated, and if not, skip the validation step. However, > I then do not get the default values filled in. > > I can think of two possible solutions. I just wondered if this is a > common design issue when it comes to xml and schemas, and if there is > a 'best practice' to handle it. > > 1. Don't use default values - create the document with all values > filled in. > > 2. Use python to check for missing values and fill in the defaults > when processing the document. > > Or maybe the best practice is to *always* validate a document before > processing it. The stated problem rings a lot of premature optimization bells; performing the validation and default-filling step every time, unconditionally, is certainly the least crooked approach. In case you really want to avoid unnecessary schema processing, if you are willing to use persistent data to check for changes (for example, by comparing a hash or the full text of the current document with the one from the last time you performed validation) you can also store the filled-in document that you computed, either as XML or as serialized Python data structures. Regards, Lorenzo Gatti From greg at cosc.canterbury.ac.nz Wed Sep 17 19:06:32 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 18 Sep 2008 11:06:32 +1200 Subject: minimum install & pickling In-Reply-To: References: Message-ID: <6jdh9gF2q06nU1@mid.individual.net> Aaron "Castironpi" Brady wrote: > Even a function created from raw bytecode string can't do anything > without __import__ or 'open'. Not true: for cls in (1).__class__.__bases__[0].__subclasses__(): if cls.__name__ == "file": F = cls F(my_naughty_path, "w").write(my_naughty_data) -- Greg From castironpi at gmail.com Thu Sep 4 16:25:05 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 13:25:05 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: On Sep 4, 2:42?pm, bearophileH... at lycos.com wrote: > David C. Ullrich: > > > At least in mathematics, the sum of the elements of > > the empty set _is_ 0, while the maximum element of the > > empty set is undefined. > > What do you think about my idea of adding that 'default' argument to > the max()/min() functions? > > Bye, > bearophile For max and min, why can't you just add your argument to the set itself? The reason max([]) is undefined is that max( S ) is in S. The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. From david at boddie.org.uk Tue Sep 2 16:03:30 2008 From: david at boddie.org.uk (David Boddie) Date: Tue, 02 Sep 2008 22:03:30 +0200 Subject: configure kdevelop for python References: <2f21628f-80dd-4710-b0be-2b1c772e5698@l33g2000pri.googlegroups.com> Message-ID: On Sunday 31 August 2008 10:29, Sindhu wrote: > am a newbie to python language and kdevelop, so i would like to know > how to configure kdevelop for python programming? complete with a > debugger? Maybe asking on the kdevelop mailing list will yield a helpful answer: http://lists.kde.org/?l=kdevelop&r=1&w=2 David From mwalsh at mwalsh.org Tue Sep 30 13:41:32 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 30 Sep 2008 12:41:32 -0500 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> Message-ID: <48E264CC.4050701@mwalsh.org> Blubaugh, David A. wrote: > To All, > > I have been attempting to execute the following program within the > Python environment: > > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? Based on your description, it seems pretty obvious (and easy to confirm) that Myprogram.exe needs to be run from its containing directory ("C:\myprogramfolder\run"). Try something like this... import os pwd = os.getcwd() os.chdir('c:/myprogramfolder/run') os.system("Myprogram.exe 1 1 acc 0") os.chdir(pwd) HTH, Marty From rsgalloway at gmail.com Sun Sep 28 15:00:57 2008 From: rsgalloway at gmail.com (rsgalloway at gmail.com) Date: Sun, 28 Sep 2008 12:00:57 -0700 (PDT) Subject: How to read a jpg bytearray from a Flash AS3 file References: Message-ID: <3641130e-43d3-4996-a123-0254a47a19d7@o40g2000prn.googlegroups.com> Thanks! I'm using form = cgi.FieldStorage(). When I print out the contents of form, I get this: FieldStorage(None, None, '\xff\xd8\xff\xe0\x00\x10JFIF \x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb \x00\x84\x00\x05\x03\x04\x04\x04\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0c \x08\x07\x07\x07\x07\x0f\x0b\x0b\t\x0c\x11\x0f\x12\x12\x11\x0f \x11\x11\x13\x16\x1c\x17\x13\x14\x1a\x15\x11\x11\x18!\x18\x1a\x1d\x1d \x1f\x1f\x1f\x13\x17"$"\x1e$\x1c\x1e\x1f\x1e \x01\x05\x05\x05\x07\x06\x07\x0e\x08\x08\x0e\x1e\x14\x11\x14\x1e\x1e \x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e \x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e \x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\xff\..... Which is obviously the binary data of the image I want. How do I access this data? I'm used to getting it like this: name = form['name'].value But I don't think this will work in this case. TIA. From Edwin.Madari at VerizonWireless.com Fri Sep 5 09:53:47 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Fri, 5 Sep 2008 09:53:47 -0400 Subject: cx_oracle and commands In-Reply-To: Message-ID: <20080905135359.2F4611E4016@bag.python.org> gaius hammond Wrote: >Hi all, > > >I am having a very strange problem with cx_Oracle, has anyone >seen this kind of behavior before: > > > >ActivePython 2.5.2.2 (ActiveState Software Inc.) based on >Python 2.5.2 (r252:60911, Mar 27 2008, 18:53:24) [C] on sunos5 >Type "help", "copyright", "credits" or "license" for more information. >>>> from commands import getstatusoutput >>>> (status, output) = getstatusoutput('ls') >>>> status >0 >>>> from cx_Oracle import connect, SYSDBA >>>> db = connect(mode=SYSDBA) >>>> (status, output) = getstatusoutput('ls') >Traceback (most recent call last): > File "", line 1, in > File "/opt/ASpy25/lib/python2.5/commands.py", line 55, in >getstatusoutput > sts = pipe.close() >IOError: [Errno 10] No child processes > > > >Basically, once I have made a connection to Oracle I can no >longer use getstatusoutput(). This is a real problem as >I need to get a list of things to work on from Oracle then >spawn commands to process them... > > >Thanks, > There is no mode parameter to connect. use try-catch around db = connect(mode=SYSDBA) line to see what's going on. Edwin The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From castironpi at gmail.com Sun Sep 28 03:04:14 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 00:04:14 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <6k8ll9F6jbmtU2@mid.uni-berlin.de> Message-ID: <68c5360b-d76f-4867-804a-46e8488514a3@m73g2000hsh.googlegroups.com> On Sep 28, 1:14?am, Marc 'BlackJack' Rintsch wrote: > On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote: > > To me, this is a somewhat unintuitive behavior. ?I want to discuss the > > parts of it I don't understand. > > >>>> f= [ None ]* 10 > >>>> for n in range( 10 ): > > ... ? ? f[ n ]= lambda: n > > ... > >>>> f[0]() > > 9 > >>>> f[1]() > > 9 > > `n` is looked up at the time ``f[0]`` is called. ?At that time it is > bound to 9. > > >>>> f= [ None ]* 10 > >>>> for n in range( 10 ): > > ... ? ? f[ n ]= (lambda n: ( lambda: n ) )( n ) ... > >>>> f[0]() > > 0 > >>>> f[1]() > > 1 > > > Which is of course the desired effect. ?Why doesn't the second one just > > look up what 'n' is when I call f[0], and return 9? > > It *does* look up `n` at the time you call ``f[0]`` but this time it's > the local `n` of the outer ``lambda`` function and that is bound to > whatever the function was called with. ?At the time it was called the > global `n` was bound to 0. ?Maybe it get's more clear if you don't name > it `n`: > > In [167]: f = [None] * 10 > > In [168]: for n in xrange(10): > ? ?.....: ? ? f[n] = (lambda x: lambda: x)(n) > ? ?.....: > > In [169]: f[0]() > Out[169]: 0 > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Hi Marc, It's my understanding that 'n' gets a new value every time through the loop. n= 0 on the first pass, n= 1 on the second pass, and so on. n= 9 by the end, and that's why `lambda: n` always returns 9. It queries the variable 'n', and finds 9. (This got lengthy. I started thinking aloud.) In your version of the indirect example, it queries the variable 'x', which it finds in a new distinct scope in each f element. In f[0], x= 0. In f[1], x= 1. There are 10 different 'x' variables throughout the contents of f. The direct example does not do this allocation of ten different 'x's. It's sort of helping. I think I feel like the following is more like what I'm looking for: (Non-standard) >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= n ... >>> f[0] 9 >>> f[1] 9 because when you access f[0], it looks up the variable 'n'. Obviously not. (Unproduced) >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= late( n ) #late/lazy ... >>> f[0] 9 >>> f[1] 9 >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= early( n ) #early/eager ... >>> f[0] 0 >>> f[1] 1 For the functions, I want a function that returns 'n', either late or early. (Unproduced) >>> for n in range( 10 ): ... f[ n ]= lambda: late( n ) >>> f[0]() 9 >>> for n in range( 10 ): ... f[ n ]= lambda: early( n ) >>> f[0]() 0 I don't think you could pull this off. 'late' and 'early' succeed with quotes around n, early('n') and late('n'), in the direct assignments, but the functions aren't so lucky. 'n' has gone on to a better world by the time 'early' gets any control. This might have some success. (Unproduced) >>> for n in range( 10 ): ... f[ n ]= late( lambda: n ) >>> f[0]() 9 >>> for n in range( 10 ): ... f[ n ]= early( lambda: n ) >>> f[0]() 0 Though it's beyond my foresight to tell if it's feasible as stated, if you need quotes, how much introspection you would need, etc. Plus, 'late' and 'early' were accepting quoted parameters earlier. How would they look inside a function? Could a simple decorator provide the service? On a tangent about mutables, it's not that numbers, strings, and tuples are 'immutable' per se, it's just that they don't have any methods which mutate them (or assignable properties). Lists and dictionaries do. It's up to the user whether a custom class does. From victor.prosolin at gmail.com Mon Sep 29 13:37:36 2008 From: victor.prosolin at gmail.com (Victor Prosolin) Date: Mon, 29 Sep 2008 11:37:36 -0600 Subject: Python is slow? In-Reply-To: <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Lawrence D'Oliveiro: >>> Gnuplot is non-Free software. > > Fly Away: >> Yes, it is. > > From: > http://www.gnuplot.info/faq/faq.txt > > 1.7 Does gnuplot have anything to do with the FSF and the GNU project? > [...] > Gnuplot is freeware in the sense that you don't have to pay for it. > However > it is not freeware in the sense that you would be allowed to > distribute a > modified version of your gnuplot freely. [...] Yes, I did read this prior to posting. Victor. From mathieu.prevot at gmail.com Thu Sep 4 09:31:09 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 15:31:09 +0200 Subject: path slashes cleaning In-Reply-To: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> References: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> Message-ID: <3e473cc60809040631o211a7e77r1abced4567840b62@mail.gmail.com> 2008/9/4 Mathieu Prevot : > Hi, > > for scripts that take arguments, I would like to remove the trailing > slash if it's present. > > Is there something else than: > > a='/usr/local/lib/' > if a[-1] == '/': > a = list(a) > a.pop() > ''.join(a) A dummy a.rstrip('/') Sorry for the noise Mathieu From john.ford at colorado.edu Wed Sep 24 23:51:28 2008 From: john.ford at colorado.edu (john.ford at colorado.edu) Date: Wed, 24 Sep 2008 20:51:28 -0700 (PDT) Subject: How to parse a string completely into a list References: Message-ID: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> On Sep 24, 9:44?pm, "Chris Rebert" wrote: > On Wed, Sep 24, 2008 at 8:30 PM, ? wrote: > > I want to take a long alpha-numeric string with \n and white-space and > > place ALL elements of the string (even individual parts of a long > > white-space) into separate list elements. The most common way I've > > seen this performed is with the split() function, however I don't > > believe that it has the power to do what I am looking for. > > Any suggestions? > > thanks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Could you please define exactly what you mean by "elements" of a string? > > If you mean characters, then just use list():>>> list(" ?\n \t abc") > > [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] > > Regards, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com Worked like a charm. kudos! From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 13:38:13 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 19:38:13 +0200 Subject: properties setting each other In-Reply-To: References: <200809031644.10870.maric@aristote.info> Message-ID: <48bee775$0$7236$426a34cc@news.free.fr> Maric Michaud a ?crit : > Le Wednesday 03 September 2008 17:40:43 mk, vous avez ?crit : >>> Note that if one property can really be computed from another, this kind >>> of thing could be considered as bad design (except if the computation is >>> heavy). >> Hmm, why? Is the line of thinking smth like: because the variables >> should be kept to minimum and they should be calculated at the moment >> they are needed? > > Because you have to make extra effort to keep the logical relation between > value and square. self._square is not really needed, and what is not needed > is just extra hassle. > > Doesn't it clear that your code is more hard to maintain than the > alternative : > > class Squared(object): > > def __init__(self, val): > self._val=val > > def fgetvalue(self): > return self._val > def fsetvalue(self, val): > self._val=val > value = property(fgetvalue, fsetvalue) > > def fgetsquare(self): > return self.value ** 2 > def fsetsquare(self,s): > self.value = math.sqrt(s) > square = property(fgetsquare, fsetsquare) FWIW, if there's no computation on getting or setting value, you can make it a plain attribute. But while it's quite clear that in this example use case it would be better to have only one property (weither square or value, depending on which is the most often use), things are not always that simple in real world code, and - as you mentionned - there may be times where you have interdependant properties and really want to avoid recomputing the same thing over and over. Now there's no one size fits all solution here - it's an optimization problem, and as such depends on real use cases. From deets at nospam.web.de Tue Sep 23 08:20:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 23 Sep 2008 14:20:15 +0200 Subject: Docstrings for class attributes References: Message-ID: <6js582F4rs2vU1@mid.uni-berlin.de> Tom Harris wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. Sort of > a very limited implementation of PEP 224. The only solution that I can > see is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Epydoc interprets strings like this as doc-strings: """ FOO is not a bar """ FOO = "foo" However, it won't get recognized by help of course. Diez From hauva at arska.org Mon Sep 1 12:09:13 2008 From: hauva at arska.org (Ari Makela) Date: 01 Sep 2008 16:09:13 GMT Subject: Printing list of dates starting today References: <4v1ob4tgk0u4jhtobisaid1g9pst0ic011@4ax.com> Message-ID: <48bc13a9$0$23597$4f793bc4@news.tdc.fi> On 2008-09-01, Luka Djigas wrote: > please, I need your help. I'm new to python, so I don't know if this > will seem like a stupid question to some of you ... There are several ways to do it. Have a look at the documentation of modules time and datetime. For this exact problem time is the most straighforward one. > I have a need to write to a file (or just print on screen, that part > doesn't matter at this point) a list of dates, starting today. For > example: > 02.09.2008. tue > 03.09.2008. wed 0 hauva at laphroaig:~ $ /usr/bin/python Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> DAY = 60 * 60 * 24 >>> today = time.time() >>> for i in (0, 1, 2, 3): ... t = time.gmtime(time.time() + i * DAY) ... print time.strftime('%d.%m.%Y, %a', t) ... 01.09.2008, Mon 02.09.2008, Tue 03.09.2008, Wed 04.09.2008, Thu -- Ari Makela late autumn - hauva at arska.org a single chair waiting http://arska.org/hauva/ for someone yet to come -- Arima Akito From jhuerta at cipf.es Thu Sep 25 04:11:34 2008 From: jhuerta at cipf.es (Jaime Huerta Cepas) Date: Thu, 25 Sep 2008 10:11:34 +0200 Subject: how to build a MacOS universal python package including external dependencies In-Reply-To: <3e473cc60809240944h1ea69275jc066fc957869d8f2@mail.gmail.com> References: <3e473cc60809240944h1ea69275jc066fc957869d8f2@mail.gmail.com> Message-ID: Thanks Mathieu, I think MacPorts will be the easiest way (all dependencies are available). I could even base the installation script on "port" commands. The major problem will be to compile Qt4, which takes hours and requires X11. thnks, again. Jaime. On Wed, Sep 24, 2008 at 6:44 PM, Mathieu Prevot wrote: > 2008/9/24 Jaime Huerta Cepas : > > Hi all, > > > > I have developed a set python libraries that provide several scientific > > methods to analyse and visualize certain type of biological data. This > > libraries are based on many external python modules, such as python-mysql > > python-sip or python-qt4. I use GNU/linux to develop my tools and I found > no > > problems into installing all dependencies, however it does not seem to be > > that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 , > > mysqldb, scipy, numpy) are cross platform, but when you are trying to > > publish your tool in an academic journal, most referees (many of them > using > > MacOS) expect some kind of straightforward installation process for the > > tool. > > > > I wonder if there would be a way in which I could compile all the > > dependencies and libraries in a MacOs system and then building a static > > universal binary that I can distribute. I guess it should be possible, > but > > I am not sure how difficult it might be, and whether all dependencies > (qt4 > > is huge) can be packaged together. > > IMHO this is too complex to commit. Macport is a way to do what you > want, but packages may not be up to date enough. Maybe the easiest and > simplest way for you to do this is to write a script that will > download, compile and install everything. > > The script should work like: > > sudo all_in_one_script.py > > and then wait for jobs to be done. Your script will need to know if a > package was sucessfully installed and then continue or take steps and > say it. For a complex set of dependencies, I recommend you to write > Makefiles. > > For instance, in pseudo-code: > if /usr/local/lib/libfoo.dylib doesn't exist > download foo > install foo > > if python-module foo doesn't exist > download foo > python foo/setup.py install > > etc > > HTH > Mathieu > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From akabaila at pcug.org.au Tue Sep 23 00:59:33 2008 From: akabaila at pcug.org.au (Al Kabaila) Date: Tue, 23 Sep 2008 14:59:33 +1000 Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> <78547919-be84-41ac-955b-78824d64b4b8@y21g2000hsf.googlegroups.com> Message-ID: <1222145973.444160@chilli.pcug.org.au> Tim Leslie wrote: > There is no need for a wrapper. Both numarray and Numeric have been > deprecated in favour of numpy. Well, some years ago I looked for a matrix package. At that time it looked that numarray was the end of it all - it had a clean syntax, an active developer team. It looked to have everything that one could possibly wish. And here we are, it is fallen out of favour. It seems to me to be unwise to assume that in OSS there is the final, never to be superseded package for anything, including matrix algebra. OTH, I appreciate your reminder of SciPy. Thank you, Leslie. Michael Palmer wrote: > On Sep 22, 4:02 am, Al Kabaila wrote: >> This is a very active newsgroup that incudes such giants as Frederik >> Lundh > > He looks rather small to me in this picture: > http://www.python.org/~guido/confpix/flundh-2.jpg Yes, indeed. However, I had in mind giants in informed writing on Python. Besides, it seems a custom to put in very old pictures in web publications. I do that myself, except that even in old pictures I am really, really old... I have a superseded paper version of Frederik Lundh's book "Python Standard Library", published by O'Reilly in May 2001. For Python that is a fair while back. Thanks for the link to the picture - appreciate it! OldAl. -- Al Kabaila (Dr) http://akabaila.pcug.org.au/StructuralAnalysis From bearophileHUGS at lycos.com Fri Sep 19 22:30:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Sep 2008 19:30:58 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: <22890f2d-f55a-45f5-a22c-2957f564e5cb@l42g2000hsc.googlegroups.com> MRAB: > except that it could be misleading when: > len(file(path)) > returns the number of lines and /not/ the length in bytes as you might > first think! :-) Well, file(...) returns an iterable of lines, so its len is the number of lines :-) I think I am able to always remember this fact. > Anyway, here's another possible implementation using bags (multisets): This function looks safer/faster: def major_version(version_string): "convert '1.2.3.2' to '1.2'" return '.'.join(version_string.strip().split('.', 2)[:2]) Another version: import re patt = re.compile(r"^(\d+\.\d+)") dict_of_counts = defaultdict(int) for ver in versions: dict_of_counts[patt.match(ver).group(1)] += 1 print dict_of_counts Bye, bearophile From steven at REMOVE.THIS.cybersource.com.au Tue Sep 30 02:07:45 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 06:07:45 GMT Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: On Mon, 29 Sep 2008 21:03:07 -0700, namekuseijin wrote: >> Why isn't len implemented as a str.len and list.len method instead of a >> len(list) function? > > Because postfix notation sucks. The natural way of spelling is > adjective+noun and verb+predicate. "Natural"? You mean phrases like "heir apparent" and "worst choice imaginable" are unnatural? To say nothing of languages like Spanish, Albanian, Italian, Cornish, Vietnamese, Hebrew... -- Steven From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 13:22:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 19:22:35 +0200 Subject: improving a huge double-for cycle In-Reply-To: References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <48d54d48$0$824$426a74cc@news.free.fr> Harald Luessen a ?crit : > On Thu, 18 Sep 2008 Bruno Desthuilliers wrote: > >> # Harald : uncomment this and run test_results. As far as I can tell, it >> # doesn't yields the expected results >> >> ## IN7 = IN[:] >> ## def sortk7(n): >> ## return n.coordinates[0] >> >> ## def doubles7(): >> ## "is ordering better ? - Nope Sir, it's broken..." >> ## IN7.sort(key=sortk) >> ## SN = [] >> ## sn_append = SN.append >> ## in_len = len(IN) >> ## for i in xrange(in_len): >> ## node_i = IN[i] >> ## coords_i = node_i.coordinates >> ## for j in xrange(i+1, in_len): >> ## if coords_i[0] == IN[j].coordinates[0]: >> ## if coords_i[1] == IN[j].coordinates[1]: >> ## sn_append(node_i) >> ## else: >> ## break >> ## return SN > ... >> Results here (py2.5, gentoo linux, athlonxp1800, 512 ram): >> >>>>> test_results() >> True >>>>> test_times() >> doubles0 : 1.55667901039 >> doubles1 : 0.719144105911 >> doubles2 : 0.703393936157 >> doubles3 : 0.700654983521 >> doubles4 : 0.706257104874 >> doubles5 : 0.528184890747 >> doubles6 : 0.461633205414 >> doubles8 : 0.0134379863739 >> doubles9 : 0.0108540058136 > > When you change my code then do it right. :-) > You forgot to change the IN to IN7 at _every_ place. > And the sortk should be sortk7 in _both_ places. doh :( Sorry Harald, my fault, you're right... > I never let the code run before myself. I just wrote it > in the newsreader. But now i did and I have a second > version as bonus. > > > IN7 = IN[:] > > def sortk7(n): > return n.coordinates[0], n.coordinates[1] > > def doubles7(): > IN7.sort(key=sortk7) > SN = [] > sn_append = SN.append > in_len = len(IN7) > for i in xrange(in_len): > node_i = IN7[i] > coords_i = node_i.coordinates > for j in xrange(i+1, in_len): > if coords_i[0] == IN7[j].coordinates[0]: > if coords_i[1] == IN7[j].coordinates[1]: > sn_append(node_i) > else: > break > return SN > > > def comp7( x, y ): > return cmp( x.coordinates, y.coordinates ) > > def doubles7a(): > IN7.sort( comp7 ) > SN = [] > sn_append = SN.append > in_len = len(IN7) > for i in xrange(in_len): > node_i = IN7[i] > for j in xrange(i+1, in_len): > node_j = IN7[j] > if comp7( node_i, node_j ) == 0: > sn_append(node_i) > else: > break > return SN > > > Here are the results. (py2.5, WindowsXP, Pentium4, 2.6GHz, 1.5GB): > My version is not so bad. > > doubles0 : 1.03830598582 > doubles1 : 0.47943719104 > doubles2 : 0.487412506338 > doubles3 : 0.475924733451 > doubles4 : 0.466548681466 > doubles5 : 0.340487967046 > doubles6 : 0.278480365521 > doubles7 : 0.0953190978183 > doubles7a : 0.0784233750379 > doubles8 : 0.010236496538 > doubles9 : 0.00742803903848 > Point taken. Now there's one thing I find questionnable with your solution (which is probably why I didn't bother double-checking it when it *appeared* to be broken) : you assume that it's ok to loose original ordering, which I strongly suspect is not the case for the OP use case, and given the OP use case list's size, working on a copy might not be an acceptable solution. But anyway: this is not an excuse for me having broken your code. My apologies. From clp at rebertia.com Wed Sep 24 23:44:25 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 24 Sep 2008 20:44:25 -0700 Subject: How to parse a string completely into a list In-Reply-To: References: Message-ID: <47c890dc0809242044i3227ac9fy899723020c1ee9f3@mail.gmail.com> On Wed, Sep 24, 2008 at 8:30 PM, wrote: > I want to take a long alpha-numeric string with \n and white-space and > place ALL elements of the string (even individual parts of a long > white-space) into separate list elements. The most common way I've > seen this performed is with the split() function, however I don't > believe that it has the power to do what I am looking for. > Any suggestions? > thanks > -- > http://mail.python.org/mailman/listinfo/python-list > Could you please define exactly what you mean by "elements" of a string? If you mean characters, then just use list(): >>> list(" \n \t abc") [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] Regards, Chris -- Follow the path of the Iguana... http://rebertia.com From bdesth.quelquechose at free.quelquepart.fr Mon Sep 1 15:05:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 21:05:57 +0200 Subject: enhancing/wrapping an existing instance of a duck In-Reply-To: References: Message-ID: <48bc5906$0$854$426a34cc@news.free.fr> Neville Dempsey a ?crit : > What do I need to add to HTMLDecorator? > > A simpler example: > > import cgi > > class ClassX(object): > pass # ... with own __repr__ > > class ClassY(object): > pass # ... with own __repr__ > > inst_x=ClassX() Why do you need to prefix your variables with 'inst_' ? > inst_y=ClassY() > > inst_z=[ i*i for i in range(25) ] > > inst_b=True > > class HTMLDecorator(object): > def html(self): # an "enhanced" version of __repr__ > return cgi.escape(self.__repr__()).join(("

","

")) uppercase tags are so 1990... More seriously, your code would be more readable (and more maintainable) using string formatting, ie: def html(self): # an "enhanced" version of __repr__ return cgi.escape("

%r

" % self) > print HTMLDecorator(inst_x).html() (snip unexecuted code) > Output: > Traceback (most recent call last): > File "html.py", line 21, in > print HTMLDecorator(inst_x).html() > TypeError: default __new__ takes no parameters > > Can I simply decorate an existing instance? For which definitions of "simply" and "decorate", and for instances of what ? Some classes will let you add arbitrary attributes to either themselves of their instances. Some (hint: mostly builtin types) wont, because they've been implemented otherwise, usually for performances reasons. If all you need is a simple enhanced "html" __repr__, just use a generic function - being OO doesn't mean you have to use classes everywhere (hint : OO stands for "object oriented", not "class oriented"). All you need here is: def html(obj, tag="h1"): return "<%s>%s" % (tag, cgi.escape(repr(obj)), tag) If you have more responsabilities to add, and want something generic, then you'll have to use composition/delegation instead of inheritance, ie: class HTMLDecorator(object): def __init__(self, obj): # use name mangling to avoid possible name clash self.__obj = obj def html(self): # reuse the above generic html() func return html(self.__obj) def __getattr__(self, name): # trivial, always delegate - __getattr__ is # only called when evrything else failed return getattr(self.__obj, name) def __setattr__(self, name, value): # tricky : __setattr__ is *always* called if name == "_HTMLDecorator__obj" or name in type(self).__dict__: super(HTMLDecorator, self).__setattr__(name, value) else: setattr(self.__obj, name, value) But be warned that this might be tricky (I wouldn't bet a truly generic implementation of the class decorator pattern is something doable), and that you'll have to pay the price (wrt/ perfs) for overriding __setattr__. As a general rule, it's better to avoid overridding __getattribute__ and __setattr__ whenever possible. HTH From marco.bizzarri at gmail.com Sat Sep 6 02:08:29 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 6 Sep 2008 08:08:29 +0200 Subject: use str as variable name In-Reply-To: References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> Message-ID: <3f0d61c40809052308v185f3787p64f6fd89172114c7@mail.gmail.com> On Sat, Sep 6, 2008 at 7:52 AM, Fredrik Lundh wrote: > Marco Bizzarri wrote: > >>> (...as Bruno implies, setattr(), len() et al can be and should be viewed >>> as >>> generic functions. >> >> Just a question: "generic functions" are not meant in the sense of >> "generic functions" of CLOS, am I right? > > it's meant in exactly that sense: len(L) means "of all len() implementations > available to the runtime, execute the most specific code we have for the > object L". > It is a generic functions like a CLOS one, as long as we remain to one parameter. I mean, there will be just one implemenatation of foo(bar, man) which the python interpretr can find; am I right? -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From roy at panix.com Wed Sep 3 07:54:46 2008 From: roy at panix.com (Roy Smith) Date: Wed, 03 Sep 2008 07:54:46 -0400 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > Without them it looks better: > > import sys > for line in sys.stdin: > try: > a, b = map(int, line.split(None, 2)[:2]) > except ValueError: > pass > else: > if a + b == 42: > print b I'm philosophically opposed to one-liners like: > a, b = map(int, line.split(None, 2)[:2]) because they're difficult to understand at a glance. You need to visually parse it and work your way out from the inside to figure out what's going on. Better to keep it longer and simpler. Now that I've got my head around it, I realized there's no reason to make the split part so complicated. No reason to limit how many splits get done if you're explicitly going to slice the first two. And since you don't need to supply the second argument, the first one can be defaulted as well. So, you immediately get down to: > a, b = map(int, line.split()[:2]) which isn't too bad. I might take it one step further, however, and do: > fields = line.split()[:2] > a, b = map(int, fields) in fact, I might even get rid of the very generic, but conceptually overkill, use of map() and just write: > a, b = line.split()[:2] > a = int(a) > b = int(b) From google at mrabarnett.plus.com Fri Sep 26 08:45:23 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Sep 2008 05:45:23 -0700 (PDT) Subject: how to keep a window above all other OS windows? References: Message-ID: <3a61c7c0-4197-43c8-9697-89df1f9587f4@25g2000hsx.googlegroups.com> On Sep 26, 10:04?am, Dennis Lee Bieber wrote: > On Fri, 26 Sep 2008 19:52:59 +1200, Lawrence D'Oliveiro > declaimed the following in > comp.lang.python: > > > > > This sort of thing should be configurable in many X11-based window managers. > > ? ? ? ? Maybe... But I'm stuck with a MicroSloth world -- at least they > didn't decide 1 mouse button is all anyone would need There's some useful information at http://epydoc.sourceforge.net/stdlib/Tkinter.Wm-class.html. >>> from Tkinter import * >>> w = Tk() >>> w.attributes('-topmost', True) '' >>> w.mainloop() >>> The window stays on top. From febkimbleox at gmail.com Sat Sep 27 07:17:36 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:17:36 -0700 (PDT) Subject: amaterski porno video hrvaski amaterski porno video amaterski porno video maja - Free Message-ID: <00aeed03-509b-49af-a472-aa2f5a2574f8@l64g2000hse.googlegroups.com> amaterski . . . *******CLICK HERE******** http://vids365.cn/amaterski ***************************** . . . . . . . . . . . . At this point amaterski began to wonder whether amaterski had been missed or overheard ? there would be hell to pay if amaterski had. At this point porno began to wonder whether porno had been missed or overheard ? there would be hell to pay if porno had. Like the time video went shopping for video mother?s wedding gown. Like the time hrvaski went shopping for hrvaski mother?s wedding gown. Like the time amaterski went shopping for amaterski mother?s wedding gown. Like the time porno went shopping for porno mother?s wedding gown. Like the time video went shopping for video mother?s wedding gown. Like the time amaterski went shopping for amaterski mother?s wedding gown. Like the time porno went shopping for porno mother?s wedding gown. Like the time video went shopping for video mother?s wedding gown. Like the time maja went shopping for maja mother?s wedding gown. Like the time amaterski went shopping for amaterski mother?s wedding gown. Like the time video went shopping for video mother?s wedding gown. Like the time klipovi went shopping for klipovi mother?s wedding gown. ?I found porno yesterday after rehearsal? porno said. From deets at nospam.web.de Thu Sep 11 14:09:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Sep 2008 20:09:06 +0200 Subject: Please help me finding a way to implement os.path.issubpath(a, b) In-Reply-To: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> References: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> Message-ID: <6it563Fe2h8U2@mid.uni-berlin.de> Giampaolo Rodola' schrieb: > Hi, > I'm trying to implement a function which returns whether a path is a > subpath of another one (e.g. /a/b/c is a subpath of /a/b). > I wrote this function which apparently seems to work fine: > > import os > > def issubpath(path1, path2): > """Return True if path1 is a sub path of path2.""" > if path1 == path2: > return False > x1 = path1.split(os.sep) > x2 = path2.split(os.sep) > return x1[:len(x2)] == x2 > > ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False. > A little help would be appreciated. Any reason why os.path.normpath(a).startswith(os.normpath(b)) doesn't do the trick? Diez From karentataka at gmail.com Sun Sep 21 00:19:50 2008 From: karentataka at gmail.com (karentataka at gmail.com) Date: Sat, 20 Sep 2008 21:19:50 -0700 (PDT) Subject: 9hrsj SOMA - Viagra - Phentermine - Ultram - Ambien - Diflucan ...Free Overnight Fedex! Message-ID: <5f76a256-15d1-4864-b27e-42dbe1b432fa@m3g2000hsc.googlegroups.com> Start saving, best online pharmacy here http://gjlabeh.cuchezfarg.com/?cdfikmabehxwvrsygzchcmjl From coolkid246 at googlemail.com Thu Sep 4 06:14:18 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:14:18 -0700 (PDT) Subject: =?ISO-8859-1?Q?sofort_kredit_online_in_Cochem_geld_kredite_bank_kre?= =?ISO-8859-1?Q?dite_Guenstige_Kredide_online_ohne_SCHUFA_kredit_ohne_schufa?= =?ISO-8859-1?Q?_oesterreich_beamtendarlehen_ohne_schufa_schweizer_kredit_ba?= =?ISO-8859-1?Q?rkredit_online_umschuldung_online_blitzkredite_schweizer_kre?= =?ISO-8859-1?Q?dit_online_kredite_fuer_selbstaendige_online_kredit_trotz_ba?= =?ISO-8859-1?Q?r_kredit_ohne_schufa_kredit_ohne_schufa_selbstaendig_auto_oh?= =?ISO-8859-1?Q?ne_schufa__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTIGE_KREDITE_ONLINE_=2B=2B=2B_KREDITE_?= =?ISO-8859-1?Q?IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_=2B_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D24?= =?ISO-8859-1?Q?4=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDI?= =?ISO-8859-1?Q?TE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http?= =?ISO-8859-1?Q?=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D24?= =?ISO-8859-1?Q?4=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDI?= =?ISO-8859-1?Q?TE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_=2B_=2B_?= =?ISO-8859-1?Q?=2B_=2B_______________________online_kredit_auch_kredite_fuer_se?= =?ISO-8859-1?Q?lbststaendige_in_Frankenberg_sofort_kredit_ohne_schufa_fuer_?= =?ISO-8859-1?Q?kredite_sicherheiten_in_Mittweida_online_kredite_in_schweize?= =?ISO-8859-1?Q?r_kredite_in_L=FCchow_sofortkredit_schufafrei_kredit_auch_ohn?= =?ISO-8859-1?Q?e_schufa_in_Tuttlingen_www_kredite_ohne_schufa_kredit_ohne_s?= =?ISO-8859-1?Q?chufa_arbeitslose_in_Aurich_kredit_uni_postbank_kredit_onlin?= =?ISO-8859-1?Q?e_in_Aalen_kredite_selbstaendige_onlinekredit_in_Ruppin_kred?= =?ISO-8859-1?Q?ite_online_berechnen_kredite_banken_in_Sulzbach_kredit_ohne_?= =?ISO-8859-1?Q?schufa_vergleich_Guenstige_Kredide_online_ohne_SCHUFA_in_Sol?= =?ISO-8859-1?Q?tau_kredite_zinsen_kredit_ohne_schufa_auskunft_in_Offenburg_?= =?ISO-8859-1?Q?online_credit_ohne_schufa_online_kredite_ohne_schufa_in_W=FCr?= =?ISO-8859-1?Q?zburg_kredit_finanzierung_onlinekredit_in_Lippe_kredit_selbs?= =?ISO-8859-1?Q?taendige_kredit_arbeitslos_in_Starnberg_finanzierung_online_?= =?ISO-8859-1?Q?kredite_privat_in_Halberstadt_kredite_banken_blitzkredite_in?= =?ISO-8859-1?Q?_Lippe_online_kredit_im_schweizer_kredit_ohne_schufa_in_K=FCn?= =?ISO-8859-1?Q?zelsau_kredit_ohne_schufa_selbstaendige_kredit_selbstaendige?= =?ISO-8859-1?Q?_in_M=FChldorf_kredit_auskunft_dispo_kredite_in_Siegen_kredit?= =?ISO-8859-1?Q?e_fuer_arbeitslose_ohne_schufa_online_kredit_trotz_schufa_in?= =?ISO-8859-1?Q?_Trier____=2D_handyvertrag_ohne_schufa_kredite_online_in_Offen?= =?ISO-8859-1?Q?bach_=2D_kredit_arbeitslose_internet_kredit_in_Coburg_=2D_klein_?= =?ISO-8859-1?Q?kredit_ohne_schufa_kredit_von_privat_ohne_schufa_in_L=FCdensc?= =?ISO-8859-1?Q?heid_=2D_kleinkredite_geld_kredit_in_Steinburg_=2D_www_online_kr?= =?ISO-8859-1?Q?edite_online_credit_ohne_in_Bad_=2D_internetkredite_kredit_sch?= =?ISO-8859-1?Q?weiz_in_Pforzheim_=2D_raten_kredit_beamtenkredite_in_Siegburg_?= =?ISO-8859-1?Q?=2D_kredite_online_beantragen_online_kredit_ohne_in_Pasewalk_=2D?= =?ISO-8859-1?Q?_kredit_online_zusage_sofort_kredit_ohne_schufa_fuer_in_Heil?= =?ISO-8859-1?Q?bronn_=2D_zinsen_online_online_kredit_ohne_in_Kirchheimbolande?= =?ISO-8859-1?Q?n_=2D_kredite_zinsen_online_kredit_de_in_Sonneberg_=2D_kredit_gi?= =?ISO-8859-1?Q?rokonto_bonitaet_online_in_Loebau_=2D_sofortkredit_online_kred?= =?ISO-8859-1?Q?it_oesterreich_in_Schwarzenberg_=2D_kredite_privat_kredit_auch?= =?ISO-8859-1?Q?_ohne_schufa_in_Hoexter?= Message-ID: sofort kredit online in Cochem geld kredite bank kredite Guenstige Kredide online ohne SCHUFA kredit ohne schufa oesterreich beamtendarlehen ohne schufa schweizer kredit barkredit online umschuldung online blitzkredite schweizer kredit online kredite fuer selbstaendige online kredit trotz bar kredit ohne schufa kredit ohne schufa selbstaendig auto ohne schufa + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + online kredit auch kredite fuer selbststaendige in Frankenberg sofort kredit ohne schufa fuer kredite sicherheiten in Mittweida online kredite in schweizer kredite in L?chow sofortkredit schufafrei kredit auch ohne schufa in Tuttlingen www kredite ohne schufa kredit ohne schufa arbeitslose in Aurich kredit uni postbank kredit online in Aalen kredite selbstaendige onlinekredit in Ruppin kredite online berechnen kredite banken in Sulzbach kredit ohne schufa vergleich Guenstige Kredide online ohne SCHUFA in Soltau kredite zinsen kredit ohne schufa auskunft in Offenburg online credit ohne schufa online kredite ohne schufa in W?rzburg kredit finanzierung onlinekredit in Lippe kredit selbstaendige kredit arbeitslos in Starnberg finanzierung online kredite privat in Halberstadt kredite banken blitzkredite in Lippe online kredit im schweizer kredit ohne schufa in K?nzelsau kredit ohne schufa selbstaendige kredit selbstaendige in M?hldorf kredit auskunft dispo kredite in Siegen kredite fuer arbeitslose ohne schufa online kredit trotz schufa in Trier - handyvertrag ohne schufa kredite online in Offenbach - kredit arbeitslose internet kredit in Coburg - klein kredit ohne schufa kredit von privat ohne schufa in L?denscheid - kleinkredite geld kredit in Steinburg - www online kredite online credit ohne in Bad - internetkredite kredit schweiz in Pforzheim - raten kredit beamtenkredite in Siegburg - kredite online beantragen online kredit ohne in Pasewalk - kredit online zusage sofort kredit ohne schufa fuer in Heilbronn - zinsen online online kredit ohne in Kirchheimbolanden - kredite zinsen online kredit de in Sonneberg - kredit girokonto bonitaet online in Loebau - sofortkredit online kredit oesterreich in Schwarzenberg - kredite privat kredit auch ohne schufa in Hoexter From coolkid246 at googlemail.com Thu Sep 4 05:40:38 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 02:40:38 -0700 (PDT) Subject: guenstige kredite Message-ID: + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + + + + + From R.Brodie at rl.ac.uk Thu Sep 18 12:01:34 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 18 Sep 2008 17:01:34 +0100 Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: "Joe G (Home)" wrote in message news:48d2781f$0$4449$afc38c87 at news.optusnet.com.au... > I have installed Python for windows today from the python web site .I also installed > pySerial using the Windows installer from the sourceforge web site..... You need to read the pySerial smallprint, where it says: "The files in this package are 100% pure Python. They depend on non standard but common packages on Windows (pywin32) and Jython (JavaComm). POSIX (Linux, BSD) uses only modules from the standard Python distribution)" From praveenapanch at gmail.com Mon Sep 8 07:12:43 2008 From: praveenapanch at gmail.com (Praveena P) Date: Mon, 8 Sep 2008 04:12:43 -0700 (PDT) Subject: String to hexadecimal conversion References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> <14aa61b1-fb8c-44c4-bbf2-d8d2f92006e9@p10g2000prf.googlegroups.com> Message-ID: <7aee6fe6-de67-42b2-92ff-d5323372e102@26g2000hsk.googlegroups.com> On Sep 8, 2:31?pm, John Machin wrote: > On Sep 8, 7:05?pm, Praveena P wrote: > > > Hi folks, > > > I am new to Python... so am not too sure about how the type conversion > > works. > > > I have to read a file that contains hexadecimal data and use the data > > further to do some arithmetic calculations. > > A sample of the input is : 00000000000020E0000032F800000000400022005E > > The problem I am facing is this: > > I am using f.read(2) to read a byte at a time, but the data that is > > read is a string rather than a number. So it kind of hampers any > > arithmetic operations I perform on this data... > > > Could you please suggest some method I could use for this? > > *IF* all the data consists of unsigned 8-bit integers > a_byte = f.read(2) > uint8 = int(a_byte, 16) > > But I doubt it and that would be rather slow anyway. If your data is > homogenous, look at the array module. Otherwise, once you've worked > out how to break your file down into records, and what the layout of > each record is, you'll need the struct module. > > HTH, > John Hey John, Thanks! That was useful... I am still putting the code together with all the operations... will probably have loads more queries... :-) Have a good day! Praveena From http Thu Sep 4 21:04:44 2008 From: http (Paul Rubin) Date: 04 Sep 2008 18:04:44 -0700 Subject: Can anyone suggest a good crypto package? References: <7xwshr4qr4.fsf@ruckus.brouhaha.com> Message-ID: <7xmyino11v.fsf@ruckus.brouhaha.com> Fett writes: > Wow, I have no idea how that works, but I think it will do nicely. The > main goal is simply to ensure that data coming in (from a website), is > valid (ie. posted by me). If you just want to authenticate the strings without confidentiality, use the built-in HMAC module. But beware of replay attacks. > Thank you, I think we have a winner. (BTW, I have no idea how this > whole encrypting gives many strings, decrypting all gives the correct > one works, The plaintext gets a random string attached at encryption time, and the random string gets removed at decryption. Of course there are many possible random strings, so many possible ciphertexts for each plaintext. That means the ciphertext is a necessarily somewhat longer than the plaintext, so you have to be willing to deal with that. Note there's possibly a lot of other subtle issues you have to be careful of, like if you're authenticating a series of messages, how do you detect if one has been repeated or dropped from the middle? Until you've got all that figured out, you are leaving attacks possible. From lists at cheimes.de Tue Sep 23 18:10:26 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 24 Sep 2008 00:10:26 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), or should the exception propagate to the calling program which > handles the issue? Side note: sys.exit() is just another way to write raise SystemExit. The function is defined as: static PyObject * sys_exit(PyObject *self, PyObject *args) { PyObject *exit_code = 0; if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) return NULL; /* Raise SystemExit so callers may catch it or clean up. */ PyErr_SetObject(PyExc_SystemExit, exit_code); return NULL; } Christian From hypercaffeinatedbiped at gmail.com Mon Sep 29 16:07:16 2008 From: hypercaffeinatedbiped at gmail.com (HCB) Date: Mon, 29 Sep 2008 13:07:16 -0700 (PDT) Subject: One class per file? References: <87od27rssp.fsf@benfinney.id.au> Message-ID: <076ab8f2-551d-478f-b31a-df0be47987da@y71g2000hsa.googlegroups.com> To answer Ben Finney's questions: The "Put one class in one file" statement is made in "Code Complete 2" page 771. HCB From zasaconsulting at gmail.com Fri Sep 19 04:45:10 2008 From: zasaconsulting at gmail.com (Alex Ziller) Date: Fri, 19 Sep 2008 10:45:10 +0200 Subject: improving a huge double-for cycle In-Reply-To: <48D27982.90503@wildenhain.de> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D27755.8060208@wildenhain.de> <48D27982.90503@wildenhain.de> Message-ID: Thank you all for replying me! special thanks to Tino. Your code rocks!!!!!!!!! I got all the double nodes in couple of seconds!!!!!!!! and in a useful output with the coupled nodes pro line.. cheers from Germany! 2008/9/18 Tino Wildenhain > Tino Wildenhain wrote: > >> Hi, >> >> Alexzive wrote: >> >>> Hello there :) , >>> >>> I am a python newbie and need to run following code for a task in an >>> external simulation programm called "Abaqus" which makes use of python >>> to access the mesh (ensamble of nodes with xy coordinates) of a >>> certain geometrical model. >>> >>> [IN is the starting input containing the nodes to be check, there are >>> some double nodes with the same x and y coordinates which need to be >>> removed. SN is the output containing such double nodes] >>> >>> Code: Select all >>> for i in range(len(IN)): #scan all elements of the list IN >>> for j in range(len(IN)): >>> if i <> j: >>> if IN[i].coordinates[0] == IN[j].coordinates[0]: >>> if IN[i].coordinates[1] == IN[j].coordinates[1]: >>> SN.append(IN[i].label) >>> >>> >> data=dict() >> for item in IN: # (what a name! ;) >> data.setdefault(item.coordinates,[]).append(item) >> # provided coordinates is a tuple >> >> dupes=[items for items in data.values() if len(items)>1] >> >> should give you a resulting list of lists of elements in IN >> which occur more then once per coordinates. >> You can then decide which ones to remove or whatever. >> >> If you want to have the output only containing nodes to remove, >> the following would work: >> >> dupes=[] >> for items in data.values(): >> dupes.extend(items[1:]) >> >> > I did a small test - I don't know if it reflects > the actual problem good enough but it seems it > all runs below 1 sec each so this would be very > fast compared to 15h: > > >>> import random > >>> class Node(object): > ... def __init__(self,x,y): > ... self.coordinates=(x,y) > > >>> IN=[Node(random.randint(0,100),random.randint(0,100)) for i in > xrange(100000)] > > >>> data=dict() > >>> for item in IN: data.setdefault(item.coordinates,[]).append(item) > ... > > >>> dupes=[items for items in data.values() if len(items)>1] > >>> len(dupes) > 10190 > >>> > > Cheers > Tino > -- Ing. Alessandro Zivelonghi Ziller http://www.tecnopolis.eu +49 176 83112471 skype: alexzive "Energy and persistence conquer all things." Benjamin Franklin (1706 - 1790) -------------- next part -------------- An HTML attachment was scrubbed... URL: From zak.mc.kraken at libero.it Sat Sep 20 07:03:01 2008 From: zak.mc.kraken at libero.it (Vito De Tullio) Date: Sat, 20 Sep 2008 13:03:01 +0200 Subject: how can i check whether a variable is iterable in my code? References: Message-ID: satoru wrote: > hi, all > i want to check if a variable is iterable like a list, how can i > implement this? untested def is_iterable(param): try: iter(param) except TypeError: return False else: return True -- By ZeD From d3vvnull at gmail.com Tue Sep 23 22:22:08 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 23 Sep 2008 21:22:08 -0500 Subject: Twisted vs. CherryPy vs. ??? for light-weight web servers Message-ID: <170543c70809231922m23531eb9i1f7fdead10bb1e0e@mail.gmail.com> Is there any consensus on what the best lightweight web-server is? Or rather would Twisted be a better choice to choose as a framework that allows me to serve html or xml data for light webservices. Or is CherryPy just as good? -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From uzmanajmal at gmail.com Thu Sep 11 04:32:39 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Thu, 11 Sep 2008 08:32:39 +0000 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Thanks for ur help. But now i am getting an error xmlrpclib.ProtocolError: Here is my code at http://privatepaste.com/d81Kut9AFj Any idea what wrong am i doing? On Thu, Sep 11, 2008 at 7:18 AM, Fredrik Lundh wrote: > Usman Ajmal wrote: > > And i also fount that a typical system.auth call will look like: >> >> POST /xmlrpc/clarens_server.py HTTP/1.0 >> Host: localhost >> User-Agent: xmlrpclib.py/0.9.9 (by www.pythonware.com < >> http://www.pythonware.com>) >> >> Content-Type: text/xml >> Content-Length: 105 >> AUTHORIZATION: Basic MkhVTm9VazYxbXArVEZLS0dCY2tIRlA3bjVzPQo6RnJvbSBi >> >> >> system.auth >> >> >> >> >> >> >> Problem is that i don't know how do i generate above xml system.auth call. >> Can anyone please tell me how do call a function, setting the header of the >> call too? >> > > you need to plugin a custom transport. see this page for an example: > > http://www.python.org/doc/lib/xmlrpc-client-example.html > > in your case, it should be sufficient to override send_request, e.g. > (untested): > > class SecureTransport(xmlrpclib.Transport): > > def set_authorization(self, ustring, text_ucert): > self.authoriation = encodestring( > "%s:%s" % (ustring,text_ucert) > ) > > def send_request(self, connection, handler, request_body): > connection.putrequest("POST", handler) > connection.putheader("Authorization", > "Basic %s" % self.authorization > ) > > and instantiate the transport by doing > > t = SecureTransport() > t.set_authorization(ustring, text_ucert) > > before passing to the server proxy. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aioe.org at technicalbloke.com Fri Sep 19 10:39:05 2008 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 19 Sep 2008 10:39:05 -0400 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Message-ID: erikcw wrote: > Hi, > > I have a cgi script where users are uploading large files for > processing. I want to launch a subprocess to process the file so the > user doesn't have to wait for the page to load. > > What is the correct way to launch subprocess without waiting for the > result to return? > > Thanks! Whoops, that was PHP! Imeant... os.system(yourcommandline+" &") ;-) Roger From michael at stroeder.com Sun Sep 28 17:08:30 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sun, 28 Sep 2008 23:08:30 +0200 Subject: generate random digits with length of 5 In-Reply-To: References: Message-ID: Gary M. Josack wrote: > Aaron "Castironpi" Brady wrote: >> On Sep 28, 2:59 pm, sotirac wrote: >> >>> Wondering if there is a better way to generate string of numbers with >>> a length of 5 which also can have a 0 in the front of the number. >>> >>>
>>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
>>> elements
>>>  code = 'this is a string' + str(random_number[0]) +
>>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
>>> + str(random_number[4])
>>> 
>>> >> >> '%05i'%random.randint(0,99999) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > This produces numbers other than 5 digit numbers. making the start > number 10000 should be fine. Why do you think it's wrong? >>> import random >>> '%05i'%random.randint(0,99999) '09449' >>> IMO it's exactly what was required. Ciao, Michael. From mensanator at aol.com Wed Sep 3 19:20:39 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 3 Sep 2008 16:20:39 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> On Sep 3, 2:18?pm, Laszlo Nagy wrote: > bearophileH... at lycos.com wrote: > > Empty Python lists [] don't know the type of the items it will > > contain, so this sounds strange: > > >>>> sum([]) > > > 0 > > > Because that [] may be an empty sequence of someobject: > > You are right in that sum could be used to sum arbitrary objects. > However, in 99.99% of the cases, you will be summing numerical values. > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > is very logical to return zero for empty sequences. No it isn't. Nothing is not 0, check with MS-Access, for instance: Null + 1 returns Null. Any arithmetic expression involving a Null evaluates to Null. Adding something to an unknown returns an unknown, as it should. It is a logical fallacy to equate unknown with 0. For example, the water table elevation in ft above Mean Sea Level is WTE = TopOfCasing - DepthToWater. TopOfCasing is usually known and constant (until resurveyed). But DepthToWater may or may not exist for a given event (well may be covered with fire ants, for example). Now, if you equate Null with 0, then the WTE calculation says the water table elevation is flush with the top of the well, falsely implying that the site is underwater. And, since this particular site is on the Mississippi River, it sometimes IS underwater, but this is NEVER determined by water table elevations, which, due to the CORRECT treatment of Nulls by Access, never returns FALSE calculations. >>> sum([]) 0 is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It should return None or throw an exception like sum([None,1]) does. > > Same way, if we would have a prod() function, it should return one for > empty sequences because X*1 = X. The neutral element for this operation > is one. > > Of course this is not good for summing other types of objects. But how > clumsy would it be to use > > sum( L +[0] ) > > or > > if L: > value = sum(L) > else: > value = 0 > > instead of sum(L). > > Once again, this is what sum() is used for in most cases, so this > behavior is the "expected" one. > > Another argument to convince you: the sum() function in SQL for empty > row sets returns zero in most relational databases. > > But of course it could have been implemented in a different way... I > believe that there have been excessive discussions about this decision, > and the current implementation is very good, if not the best. > > Best, > > Laszlo From martin at v.loewis.de Thu Sep 18 18:55:23 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 19 Sep 2008 00:55:23 +0200 Subject: Automated Build System ? In-Reply-To: <3468bd3f-d6a3-477a-8537-48d67522700a@j22g2000hsf.googlegroups.com> References: <3468bd3f-d6a3-477a-8537-48d67522700a@j22g2000hsf.googlegroups.com> Message-ID: <48D2DC5B.80002@v.loewis.de> > I'm working on a python Package which includes some extension modules > and unit tests. I want to automate some tasks like "build extsion > module, then copy xxx.pyd to folder yyy and run all unit tests from > folder zzzz". > > I used google but found no hints to existing solutions. > Can anybody help me ? I recommend to use distutils. It can already build extension modules and install them. For testing, you would need to supply your own test command. Alternatively, try setuptools - there seems to be a test command already included. Regards, Martin From ppearson at nowhere.invalid Fri Sep 5 11:03:29 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 5 Sep 2008 15:03:29 GMT Subject: Extract Information from Tables in html References: <37b964200809050729j6290af48u8efbbc1a5e0b6bd1@mail.gmail.com> Message-ID: <6id021Fq216kU1@mid.individual.net> On Fri, 5 Sep 2008 11:35:14 -0300, Walter Cruz wrote: > On Fri, Sep 5, 2008 at 11:29 AM, Jackie Wang wrote: >> Here is a html code: >> >> >> >> Premier Community Bank of Southwest Florida >>
>> Fort Myers, FL >> >> >> >> My question is how I can extract the strings and get the results: >> Premier Community Bank of Southwest Florida; Fort Myers, FL > > Use BeautifulSoup. I agree, BeautifulSoup is wonderful. Here are snippets of code that I recently used to locate (in each of many HTML files) the table that contained a particular heading: from BeautifulSoup import BeautifulSoup import re ... inlines = ifd.readlines() soup = BeautifulSoup( " ".join( inlines ) ) x = soup.findAll( text = re.compile( "Technical Requirements - General" ) ) x = x[0].parent while x.name != "table": x = x.parent tr_list = x.findAll( "tr", recursive = False ) print "Table has %d rows." % len( tr_list ) -- To email me, substitute nowhere->spamcop, invalid->net. From jarausch at skynet.be Fri Sep 5 10:38:41 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Fri, 05 Sep 2008 16:38:41 +0200 Subject: hashing an array - howto Message-ID: <48c14472$0$2864$ba620e4c@news.skynet.be> Hi, I need to hash arrays of integers (from the hash module). So, I have to derive from array and supply a __hash__ method. But how to hash an array (of fixed length, say 25)? What I need is a function which maps a tuple of 25 integers into 1 integer with good hashing properties. Does anybody know such a thing? Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From justin.kuto at gmail.com Tue Sep 30 17:09:42 2008 From: justin.kuto at gmail.com (afrogazer) Date: Tue, 30 Sep 2008 14:09:42 -0700 (PDT) Subject: Matplotlib Polar Plot Clockwise Message-ID: <0b8e5002-8689-48c4-8d2b-b6cbf5819413@m73g2000hsh.googlegroups.com> I have been playing with this for a couple days now and there doesn't seem to be any easy way to fix this except manipulating the data, which is undesirable. It would be some much better if there was a setting in matplotlibrc to choose to plot clockwise or counter- clockwise and the position on 0° I am now trying the transformations, but it looks just too complicated. Anybody ever ran into this. Thanks, Justin. From paul at boddie.org.uk Tue Sep 30 08:31:19 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 30 Sep 2008 05:31:19 -0700 (PDT) Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> Message-ID: On 30 Sep, 14:19, Ben Finney wrote: > > This is where the useful "your freedom to swing your fist ends at the > tip of the other man's nose" applies: As soon as the act you wish to > perform is restricting the freedom of another, you're not > contemplating an act of freedom, but an act of power over another. > Freedoms should be protected, but only within the limits imposed by > the freedoms of others. This is a very good explanation of what copyleft is all about. I suppose one could regard copyleft as a means to preserve the "maximal common freedom" in a system - if anyone else were to acquire more power or privilege to do something, that would diminish the freedoms of others. Paul From fredrik at pythonware.com Sat Sep 20 05:05:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 11:05:58 +0200 Subject: The Python computer language In-Reply-To: <7d3f9f43-8094-4bd0-980c-eb721b5a5051@o40g2000prn.googlegroups.com> References: <7d3f9f43-8094-4bd0-980c-eb721b5a5051@o40g2000prn.googlegroups.com> Message-ID: ROSEEE wrote: > http://pthoncomputerlanguage.blogspot.com report here: http://tinyurl.com/blogspot-spam From lee.walczak at gmail.com Tue Sep 9 16:05:31 2008 From: lee.walczak at gmail.com (lee.walczak at gmail.com) Date: Tue, 9 Sep 2008 13:05:31 -0700 (PDT) Subject: Wx Python - Code Structure & Event Handling Message-ID: Hi, I have just started writing a GUI using wxpython after finding a limitation using Tkinter. I have read most tutorials on wxpython and slowly becoming accustomed considering I started with the latter GUI tool first! I must quote first that I am a novice user of python so the issue(s) I have may seem very obvious but please be patient with me! I have noticed that all the wxpython references I used for creating my application(s) "cram" all the code in the frame subclass. This is fine when you consider small applications but what about when they grow into very complex applications? This creates my first question : Where is it possible to find information on wxpython code practise/ structure when considering complex larger Gui's? Without any reference I decided to attempt my owm method by breaking up the top level panels in my frame as individiual class objects. and then construct the widgets for the panels within the respective classes. This led to my second problem, how do I use and event in one Panel to cause an effect in the other Panel ? For example, if I have button in one Panel and wish to change the text of a label in the other Panel, what is the best way to do this? Should I break the code into modules instead? Of course, you may explain that the way I have approached this is completely wrong, if so please tell me, I really want to get the basic structure right before I start making the code more complex. I look forward to your help ------------------------------------------------------------------------------------------------------------------------------------- I have listed some code below to help explain what concept I wish to achieve, import wx class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Application",size=(400,400)) Panel1 = wx.Panel(self, -1,size=(200,200)) Panel2 = wx.Panel(self, -1,size=(200,200)) Sizer = wx.FlexGridSizer(2,2,5,5) Sizer.Add(Panel1) Sizer.Add(Panel2) self.SetSizerAndFit(Sizer) Util1 = Utils1(Panel1) Util2 = Utils2(Panel2) class Utils1(): def __init__(self, Panel): button = wx.Button(Panel,-1, "Button 1") Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) self.Label = wx.StaticText(Panel,-1, "Handler to me", name="Lab1") Sizer = wx.BoxSizer(wx.VERTICAL) Sizer.Add(button) Sizer.Add(self.Label) Panel.SetSizerAndFit(Sizer) def OnClick(self, Evt): self.Label.SetLabel("you changed me") class Utils2(): def __init__(self, Panel): self.button = wx.Button(Panel,-1, "Button 2") Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) def OnClick(self, Evt): """ what is the easiest & accepted Method of changing the text in a different class instance?""" pass #???.SetLabel("you changed me") app = wx.PySimpleApp() frame = Frame() frame.Show() app.MainLoop() From bearophileHUGS at lycos.com Fri Sep 12 12:05:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Sep 2008 09:05:33 -0700 (PDT) Subject: Checking the boolean value of a collection References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> Message-ID: <010b3cf0-ca62-401b-bb71-2902aa0c35b6@x35g2000hsb.googlegroups.com> Marco Bizzarri: > >>> any([x for x in [1, 2, 3]]) > > I mean, I'm afraid I can't use an expression like that without > building a list... not at least in python2.3 Note that you don't need a list comp there: >>> any([x for x in [1, 2, 3]]) True >>> any([1, 2, 3]) True so this may suffice: any(self.findActiveOutgoingRegistrationInstancesPlusSomeOtherThings()) Bye, bearophile From peter.anderson at internode.on.net Tue Sep 16 01:03:51 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Tue, 16 Sep 2008 15:03:51 +1000 Subject: append on lists In-Reply-To: References: Message-ID: <48CF3E37.4090702@internode.on.net> "/... I don't think you've thought this one through, really./" Is this kind of response really necessary? The original post was asking (from his perspective at least) a legitimate question. To a Python expert it may be a "silly question" but replying in such a fatuous way puts off those "less gifted" from using this excellent reference source. Nobody enjoys being spoken to like this. We ought to try and be a little kinder to others on the list, don't you think? :-) Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From steve at holdenweb.com Fri Sep 19 03:56:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Sep 2008 03:56:25 -0400 Subject: SMTP via GMAIL In-Reply-To: <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> Message-ID: Grant Edwards wrote: > On 2008-09-18, Lawrence D'Oliveiro wrote: >> In message >> <973f75d4-90f5-4930-9107-15fc8651196d at v16g2000prc.googlegroups.com>, sui >> wrote: >> >>> Traceback (most recent call last): >>> File "mail5.py", line 21, in >>> session = smtplib.SMTP(SMTPserver,port) >>> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ >>> (code, msg) = self.connect(host, port) >>> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect >>> self.sock.connect(sa) >>> File "", line 1, in connect >>> then conncetion time out..... >> Could it be your ISP is blocking outgoing connections to port >> 25? > > gmail doesn't accept mail via SMTP on port 25. > I was going to say that's boloney until I checked my settings - it's a year or more since I set gmail up with Thunderbird. smtp.gmail.com accepts TLS connections on port 587. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Thu Sep 11 13:20:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 10:20:41 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> On Sep 11, 2:40?am, Steven D'Aprano wrote: > On Wed, 10 Sep 2008 11:59:35 -0700, Aaron \"Castironpi\" Brady wrote: > > On Sep 10, 5:24?am, Steven D'Aprano > > wrote: > >> On Wed, 10 Sep 2008 09:26:20 +0200, Fredrik Lundh wrote: > >> > Steven D'Aprano wrote: > > >> >> You've created a solution to a problem which (probably) only affects > >> >> a very small number of people, at least judging by your use-cases. > >> >> Who has a 4GB XML file > > >> > Getting 4GB XML files from, say, logging processes or databases that > >> > can render their output as XML is not that uncommon. ?They're usually > >> > record-oriented, and are intended to be processed as streams. ?And > >> > given the right tools, doing that is no harder than doing the same to > >> > a 4GB text file. > > >> Fair enough, that's a good point. > > >> But would you expect random access to a 4GB XML file? If I've > >> understood what Castironpi is trying for, his primary use case was for > >> people wanting exactly that. > > >> -- > >> Steven > > > Steven, > > > Are you claiming that sequential storage is sufficient for small amounts > > of data, and relational db.s are necessary for large amounts? > > I'm no longer *claiming* anything, I'm *asking* whether random access to > a 4GB XML file is something that is credible or useful. It is my > understanding that XML is particularly ill-suited to random access once > the amount of data is too large to fit in RAM. > > I'm interested in what Fredrik has to say about this, as he's the author > of ElementTree. > > -- > Steven XML is the wrong word for the example I was thinking of (as was already pointed out in another thread). XML is by definition sequential. The use case pertained to a generic element hierarchy; think of 4GB of hierarchical data. From mnordhoff at mattnordhoff.com Thu Sep 25 00:12:07 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 25 Sep 2008 04:12:07 +0000 Subject: How to parse a string completely into a list In-Reply-To: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> References: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> Message-ID: <48DB0F97.1020907@mattnordhoff.com> john.ford at colorado.edu wrote: > On Sep 24, 9:44 pm, "Chris Rebert" wrote: >> On Wed, Sep 24, 2008 at 8:30 PM, wrote: >>> I want to take a long alpha-numeric string with \n and white-space and >>> place ALL elements of the string (even individual parts of a long >>> white-space) into separate list elements. The most common way I've >>> seen this performed is with the split() function, however I don't >>> believe that it has the power to do what I am looking for. >>> Any suggestions? >>> thanks >> Could you please define exactly what you mean by "elements" of a string? >> >> If you mean characters, then just use list():>>> list(" \n \t abc") >> >> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] >> >> Regards, >> Chris > > Worked like a charm. > kudos! Why do you need to convert it to a list? Strings are sequences, so you can do things like slice them or iterate through them by character: >>> for character in "foo": ... print character ... f o o >>> -- From mdipierro at cs.depaul.edu Tue Sep 23 09:08:26 2008 From: mdipierro at cs.depaul.edu (mdipierro) Date: Tue, 23 Sep 2008 06:08:26 -0700 (PDT) Subject: New Web2Py framework SLASHES development time... References: <8bc01858-77f9-41bc-a907-4b9670f40213@b1g2000hsg.googlegroups.com> Message-ID: <3dee770f-41b2-47ff-81f9-3f07efd8300c@s50g2000hsb.googlegroups.com> Hi Paul, yes, the model designer is the one from Ondras. We modified it so that it generates DAL (Database Abstraction Layer) code instead of SQL and it is a work in progress. Technically it is not pat of web2py and in fact it is not distributed with it. It is just one of the many web2py apps. You can find more on http://mdp.cti.depaul.edu/appliances Massimo On Sep 22, 5:48 am, Paul Boddie wrote: > On 22 Sep, 04:49, Steve Shephed wrote: > > > http://www.web2py.comWeb2Py- Python Framework is the newest > > kid on the block for Python frameworks. > > I'm not going to dwell on the merits of web2py, I'm afraid... > > > It has a lot of features that simply are not there in other > > frameworks. Even Ruby!. You can design database models graphically > > online. > > I had a closer look at the model designer, and the client-side magic > seems to originate from this project: > > http://ondras.zarovi.cz/sql/ > > It looks quite fancy, especially since it all seems to be happening in > the browser. Thanks for indirectly bringing this to our attention! ;-) > > Paul From fredrik at pythonware.com Sat Sep 13 10:11:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 16:11:15 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > class FolderInUse: > > def true_for(self, archivefolder): > return any([instance.forbid_to_close(archivefolder) for instance in > self.core.active_outgoing_registration_instances()]) > > Is this any better? The true_for name does not satisfy me a lot... well, "true_for" is indeed pretty inscrutable, but I'm not sure that would be the first thing I'd complain about in that verbose mess... (when you pick method names, keep in mind that the reader will see the context, the instance, and the arguments at the same time as they see the name. there's no need to use complete sentences; pick short short descriptive names instead.) From goldnery at gmail.com Thu Sep 4 13:00:24 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 4 Sep 2008 10:00:24 -0700 (PDT) Subject: Right to left language support Message-ID: <191393da-7dc3-4dd2-bf63-43ed5e1d74c1@t1g2000pra.googlegroups.com> Most of you probably speaks Latin language, so you wont understand the problem. when I try to write Hebrew in my statictext the last punctuation marks get mixed up. does someone have a solution for this? this is the code : text=wx.StaticText(panel3, -1, Hebrew_string, style=wx.ALIGN_RIGHT) thanks! From semanticist at gmail.com Mon Sep 22 01:30:36 2008 From: semanticist at gmail.com (Miles) Date: Mon, 22 Sep 2008 01:30:36 -0400 Subject: Why are "broken iterators" broken? In-Reply-To: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: On Sun, Sep 21, 2008 at 11:13 AM, Steven D'Aprano wrote: > According to the Python docs, once an iterator raises StopIteration, it > should continue to raise StopIteration forever. Iterators that fail to > behave in this fashion are deemed to be "broken": > > http://docs.python.org/lib/typeiter.html > > I don't understand the reasoning behind this. As I understand it, an > iterator is something like a stream. There's no constraint that once a > stream is empty it must remain empty forever. > > Can somebody explain why "broken iterators" are broken? It's not a terribly onerous restriction. If you're iterating with a for-loop, you can make the iterable return a new iterator object when the old one is exhausted, and if the intent is for the next()-method to be called directly, you don't have to conform to the iterator protocol. Strictly speaking, file objects are broken iterators: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) >>> f = open('foo') >>> it = iter(f) >>> it.next() 'hi\n' >>> it.next() 'bye\n' >>> it.next() Traceback (most recent call last): File "", line 1, in StopIteration >>> f.seek(0) >>> it.next() 'hi\n' -Miles From sargshep at gmail.com Sun Sep 21 22:49:24 2008 From: sargshep at gmail.com (Steve Shephed) Date: Sun, 21 Sep 2008 19:49:24 -0700 (PDT) Subject: New Web2Py framework SLASHES development time... Message-ID: http://www.web2py.com Web2Py - Python Framework is the newest kid on the block for Python frameworks. It has a lot of features that simply are not there in other frameworks. Even Ruby!. You can design database models graphically online. The templating language is pure python and there are no problems with indenting. The models are auto-migrating which allows easy updating of your database schema's. Parent-child and Super-Sub Set type models are completely supported. Uses an advanced MVC pattern. At least 10 free applications ready to download and use in your own developments. Can be run from a USB stick. ZERO installation just click on the exe and away you go with web server and complete graphical admin interface. PLUS it will work on Google App Engine (your still constrained by the Google Storage Limitations but you don't have to change any database model code at all). AND Complete International Support (with a graphical admin interface to add different languages)...there is more but just take a visit... From kyosohma at gmail.com Wed Sep 10 17:34:10 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 10 Sep 2008 14:34:10 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> <4pcgc495c6ml60a09fh3gc8e6t1akmlmin@4ax.com> Message-ID: On Sep 10, 3:53?pm, James A. Donald wrote: > James A. Donald > > > > Horrible installs are a chronic problem of GUI programs driven by > > > interpreted languages ?Installing visual basic programs that worked on > > > one Windows machine to work on a very slightly different windows > > > machine was also a nightmare. > > > > I have not attempted to create installable wxPython windows, but > > > generally, "run anywhere" will bite you. ?Still looking for a good > > > solution to "run anywhere". > > Mike Driscoll > > > I haven't had much trouble getting wxPython applications to run in > > Windows XP and Ubuntu Hardy Heron. > > Did you attempt to create proper install packages that show up in the > Linux package managers, and the windows add/remove programs tool? > I used Inno Setup which creates an uninstaller, however I am not seeing it in my Windows Add/Remove. Odd. However, you can uninstall it from the Start menu entry and it works. Currently, I am running the application from source in Linux. But I plan to try cx_freeze or similar sooner or later. I haven't had need to distribute it since my apps are for internal use so far. Mike From rocky at panix.com Fri Sep 5 15:13:49 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 05 Sep 2008 15:13:49 -0400 Subject: pdb bug and questions References: Message-ID: Stef Mientki writes: > hello, > > I'm trying to embed a debugger into an editor. > I'm only interested in high level debugging. > The first question is what debugger is the best for my purpose ? > (pdb, pydb, rpdb2, smart debugger, extended debugger ? > > Second question, in none of the above debuggers (except rpdb2), > I can find a "break now", > so it seems impossible to me to detect unlimited while loops ? I am not sure what you mean by "break now". pdb and pydb allow direct calls from a program to the debugger via set_trace (which in pydb is deprecated in favor of I think the more descriptive name: debugger) But I suspect this is not what you mean to "detect unlimited while loops"; pydb also has gdb-style signal handling that allows for entry into the debugger when the debugged python process receives a particular signal. "info handle" lists all of the interrupts and what action is to be taken on each. See http://bashdb.sourceforge.net/pydb/pydb/lib/node38.html However I believe that signals are only handled by the main thread; so if that's blocked, the python process won't see the signal. > > For the moment I started with pdb, because most of the debuggers seems > to be an extension on pdb. > When I launch the debugger ( winXP, Python 2.5) from with my editor > python -u -m pdb D:\\Data\\test_IDE.py > I get this error > IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') > NOTICE 1 backslash ----------------------------------^ > > If I launch the debugger with > python -u -m pdb D:/Data/test_IDE.py > It runs fine. > > This looks like a bug to me. > What's the best way to report these kind of bugs ? winpdb, pydb and pdb (part of Python) all have Sourceforge projects which have bug trackers. For pdb, in the past people includng myself, have reported features, patches and bugs in the Python tracker; eventually it gets handled. (Eventually in my case means a year or so.) But if my information is incorrect or out of date, no doubt someone will correct me. As mentioned in the last paragraph, pydb also is a Sourceforge project (part of bashdb) which has a tracker for bug reporting. Using the bug tracker I think is better than discussing pydb bugs in c.l.p. By extension, I assume the same is also true for the other debuggers. Finally, I think rpdb2 is part of the winpdb project on Sourceforge and again has a bug tracker. My sense is that Nir Aides is very good about handling bugs reported in winpdb/rpdb. > > Although I mostly use os.path.join to be OS independent, > these kind of bugs give me the impression, > that I can better do the join myself and always use forward slashes. > Is this a valid conclusion ? > > thanks, > Stef Mientki From half.italian at gmail.com Wed Sep 3 22:41:20 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 3 Sep 2008 19:41:20 -0700 (PDT) Subject: Access to Windows "Add/Remove Programs"? References: Message-ID: On Sep 3, 7:13?pm, "Gabriel Genellina" wrote: > En Wed, 03 Sep 2008 21:51:59 -0300, Sean DiZazzo ? > escribi : > > > I'm trying to find a way to get a list of all the installed programs > > on a Windows box via Python. ?I thought of a few hacks that might > > partially work, and then thought about "Add/Remove Programs" ?Seems > > like the right way to go. ?I looked over the pywin32 docs a bit, but > > nothing slapped me in the face. > > > Is there any reliable way to get at that info? > > You may enumerate the entries under this registry key: > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall > > -- > Gabriel Genellina Thank both of you. Perfect! ~Sean From erexsha at gmail.com Tue Sep 23 06:51:37 2008 From: erexsha at gmail.com (Arash Arfaee) Date: Tue, 23 Sep 2008 03:51:37 -0700 Subject: adding in-place operator to Python Message-ID: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> Hi All, Is there anyway to add new in-place operator to Python? Or is there any way to redefine internal in-place operators? Thanks. Cheers, Arash -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Mon Sep 8 17:48:35 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 9 Sep 2008 07:48:35 +1000 Subject: The difference between __XX__ and XX method In-Reply-To: References: Message-ID: Hi, This is convention only and typically used to denote that a particular class attribute is "private". Though note, there is really no such thing in Python. cheers James On Tue, Sep 9, 2008 at 7:31 AM, AON LAZIO wrote: > Hi, Pythoners. > I would like to know that in some class, it uses __XX__ but in some it > uses only XX > for example, > > class Test: > def __som__(self): > ... > def som(self): > ... > What does "__XX__" make the method different from XX? > Thanks in advance > Aonlazio > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bmihelac at gmail.com Tue Sep 9 10:16:45 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Tue, 9 Sep 2008 07:16:45 -0700 (PDT) Subject: Python and M2Crypto question References: <12b278d2-9f78-4fc9-a4f2-7d22c543aeb9@d1g2000hsg.googlegroups.com> <643253ee-c8a7-4ccc-bac2-432ac382e4c3@v39g2000pro.googlegroups.com> Message-ID: <9c83d42a-47ba-4e00-88aa-7894b2b70ce5@s50g2000hsb.googlegroups.com> Graham, thanks, I will try with that. On Sep 8, 1:02?am, Graham Dumpleton wrote: > On Sep 7, 11:07?pm, Bojan Mihelac wrote: > > > Hi all! > > > I am trying to install M2Crypto to work on OSX10.5 apache > > (mod_python). Error I receive: > > > Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5- > > macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image > > found. ?Did find: > > ? ? ? ? /Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg- > > tmp/M2Crypto/__m2crypto.so: no matching architecture in universal > > wrapper > > > I guess that have to do something with x64 architecture but I am > > stucked and not able to find a way and to make this work. M2Crypto lib > > works good stand alone. > > See: > > ?http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX#Missing_Co... > > This is mod_wsgi documentation, but same issue applies to mod_python. > > Graham From mayariasxf at gmail.com Tue Sep 30 18:41:51 2008 From: mayariasxf at gmail.com (mayariasxf at gmail.com) Date: Tue, 30 Sep 2008 15:41:51 -0700 (PDT) Subject: Visit this sites please Message-ID: <284dc317-466f-41d2-8e49-b9e1de1ae5b4@a70g2000hsh.googlegroups.com> http://forums.vogue.com.au/member.php?u=91686 tube8 http://forums.vogue.com.au/member.php?u=91688 redtube http://forums.vogue.com.au/member.php?u=91689 pornhub http://forums.vogue.com.au/member.php?u=91690 yobt http://www.dynamicdrive.com/forums/member.php?u=33924 tube8 http://www.dynamicdrive.com/forums/member.php?u=33925 redtube Visit this sites please From steven at REMOVE.THIS.cybersource.com.au Tue Sep 9 00:02:24 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Sep 2008 04:02:24 GMT Subject: a11y & python References: Message-ID: On Mon, 08 Sep 2008 20:41:55 -0700, jonathon wrote: > All: > > A year or so ago, I read a tutorial on writing self-voicing apps using > python. It also covered other a11y issues. However, I didn't bookmark > it, and it doesn't show up in the first 1000 hits on the Google search I > did. While Google is very good, it's not perfect, nor is it the only search engine out there. Perhaps try some of the others, like Yahoo. > Can somebody point me to either that, or any other tutorials on > programming a11y into python. I'm afraid I'd be limited to googling. I'm guessing that you'd probably have more success asking on ally mailing lists (if any) for Python help than asking Python lists for ally help. But good luck. Have you checked out this? http://live.gnome.org/Orca -- Steven From schaefer.mp at gmail.com Tue Sep 16 04:26:14 2008 From: schaefer.mp at gmail.com (MatthewS) Date: Tue, 16 Sep 2008 01:26:14 -0700 (PDT) Subject: Is 'x' an instance of a new-style class? Message-ID: I've seen the question raised several times here, but apparently never answered. Since PyInstance_Check returns False for new-style class instances, is there a standard procedure for testing this using the C- Api? I would greatly appreciate some help with this. /Matthew From george.sakkis at gmail.com Thu Sep 18 11:52:11 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 18 Sep 2008 08:52:11 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> Message-ID: <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> On Sep 18, 11:43 am, Gerard flanagan wrote: > Simon Mullis wrote: > > Hi, > > > Let's say I have an arbitrary list of minor software versions of an > > imaginary software product: > > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > > I'd like to create a dict with major_version : count. > > > (So, in this case: > > > dict_of_counts = { "1.1" : "1", > > "1.2" : "2", > > "1.3" : "2" } > > [...] > data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > from itertools import groupby > > datadict = \ > dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) > print datadict Note that this works correctly only if the versions are already sorted by major version. George From Lie.1296 at gmail.com Sun Sep 28 07:04:10 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 04:04:10 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <00ef3c23$0$20666$c3e8da3@news.astraweb.com> Message-ID: <96125692-af95-4429-bf69-03aa5c0f5fa9@k36g2000pri.googlegroups.com> On Sep 28, 4:21?pm, est wrote: > On Sep 28, 4:38?pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Sat, 27 Sep 2008 22:37:09 -0700, est wrote: > > >>>> str(u'\ue863') > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > > > position 0 > > > : ordinal not in range(128) > > > > FAIL. > > > What result did you expect? > > > [...] > > > > The problem is, why the f**k set ASCII encoding to range(128) ???????? > > > while str() is internally byte array it should be handled in range(256) > > > !!!!!!!!!! > > > To quote Terry Pratchett: > > > ? ? "What sort of person," said Salzella patiently, "sits down and > > ? ? *writes* a maniacal laugh? And all those exclamation marks, you > > ? ? notice? Five? A sure sign of someone who wears his underpants > > ? ? on his head." -- (Terry Pratchett, Maskerade) > > > In any case, even if the ASCII encoding used all 256 possible bytes, you > > still have a problem. Your unicode string is a single character with > > ordinal value 59491: > > > >>> ord(u'\ue863') > > > 59491 > > > You can't fit 59491 (or more) characters into 256, so obviously some > > unicode chars aren't going to fit into ASCII without some sort of > > encoding. You show that yourself: > > > u'\ue863'.encode('mbcs') ?# Windows only > > > But of course 'mbcs' is only one possible encoding. There are others. > > Python refuses to guess which encoding you want. Here's another: > > > u'\ue863'.encode('utf-8') > > > -- > > Steven > > OK, I am tired of arguing these things since python 3.0 fixed it > somehow. I'm against calling python 3.0 fixed it, python 3.0's default encoding is utf-8/Unicode, and that is why your problem magically disappears. > Can anyone tell me how to customize a default encoding, let's say > 'ansi' which handles range(256) ? Python used to have sys.setdefaultencoding, but that feature was an accident. sys.setdefaultencoding was intended to be used for testing purpose when the developers haven't decided what to use as default encoding (what use is default when you can change it). sys.setdefaultencoding has been removed, programmers should encode characters manually if they want to use something other than the default encoding (ASCII). From python at rgbaz.eu Wed Sep 10 14:06:21 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 20:06:21 +0200 Subject: md5 differences In-Reply-To: <8K6dnVeoxJTMlVXVnZ2dnUVZ_j6dnZ2d@posted.visi> References: <8K6dnVeoxJTMlVXVnZ2dnUVZ_j6dnZ2d@posted.visi> Message-ID: <84E12A2D-81B5-4750-B4DF-9129C97967D1@rgbaz.eu> On 10 sep 2008, at 19:48, Grant Edwards wrote: > On 2008-09-10, Wojtek Walczak wrote: >> On Wed, 10 Sep 2008 12:39:24 -0500, Grant Edwards wrote: >> >>>> The strange thing is that >>>>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >>>> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. >>> >>> Same here. >> >> I guess it will be the same for vast majority of us ;-) >> The question is why is it '90364ed45b452d43378629c20543a81d' >> for the OP? :-) > > The smart money is betting on "because the OP goofed when he > was cutting/pasting stuff from his terminal window into his > posting." > I did! I did! my bad... i cut some crap from the path to make it a bit easier to read but that was before the time i knew it was checksumming the actual path in stead of the contents of the file. So I figured it didn't matter... ;) From dmitry at athabascau.ca Fri Sep 26 19:30:52 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Fri, 26 Sep 2008 23:30:52 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> <4606d73b-522f-49ff-92f8-cfbbb0782306@i76g2000hsf.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: > That prohibits using a descriptor in the proxied classes, or at least > the proxied functions, since you break descriptor protocol and only > call __get__ once. Better to cache and get by name. It's only slower > by the normal amount, and technically saves space, strings vs. > instancemethod objects (except for really, really long function names). that is an interesting point since I didn't think about having descriptors in proxied classes. my reworked code clearly breaks when descriptors are thrown at it. It will break with methods in proxied objects that are implemented as objects too. Now I adjusted constructor a bit to account for that (I just can't figure out case when I'll be proxying descriptors unless they return function but than I don't see benefit in using descriptor for that, probably because I haven't used them much). class ProxyMethod(object): def __init__(self,ob_name,meth): self.ob_name=ob_name if not hasattr(meth,'im_class'): if hasattr(meth,'__call__'): self.meth=getattr(meth,'__call__') else: raise ValueError("Method should be either a class method or a callable class") else: self.meth=meth From inhahe at gmail.com Mon Sep 15 13:36:14 2008 From: inhahe at gmail.com (inhahe) Date: Mon, 15 Sep 2008 13:36:14 -0400 Subject: how to go around non-picklable object types? Message-ID: <91xzk.28830$rD2.16046@bignews4.bellsouth.net> There are certain types of objects that can't be pickled, like file objects. My question is how could I pickle a hierarchy while automatically skipping all such objects instead of just aborting the pickle when it comes across one. The only thing I can think of is to make my own classes that wrap file objects and so forth and use __getstate__ to leave out the underlying file, etc. objects, or to set __getstate__ for every class that holds an offending object type and filter such objects out of dictionaries when I pickle those. And I don't even have a list of common object types that would make it break. Is there a better way? thx.. From beema.shafreen at gmail.com Thu Sep 11 08:44:16 2008 From: beema.shafreen at gmail.com (Beema Shafreen) Date: Thu, 11 Sep 2008 18:14:16 +0530 Subject: function return Message-ID: hi all, I have a script using functions , I have a problem in returning the result. My script returns only one line , i donot know where the looping is giving problem, Can any one suggest, why this is happening and let me know how to return all the lines def get_ptm(): fh = open('file.txt', 'r') data_lis = [] for line in fh.readlines(): data = line.strip().split('\t') id = data[0].strip() gene_symbol = data[1].strip() ptms = data[8].strip() result = "%s\t%s\t%s" %(id,gene_symbol,ptms) return result fh.close() -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From knagakiran2 at gmail.com Sat Sep 6 03:14:48 2008 From: knagakiran2 at gmail.com (bobi) Date: Sat, 6 Sep 2008 00:14:48 -0700 (PDT) Subject: IT JOBS Message-ID: <2cf1c587-ee0d-48b7-b74e-6628f10648f5@s20g2000prd.googlegroups.com> Hello friends.., Welcome to the world of Information Technology,Enjoy the fragrance of Modern Life style&Make ur Living more comfortable than everbefore! Earn Millions of Dollars legal Income With Little Efforts In ur Spare time! Success usually comes to those who are too busy to be looking for it Visit & Apply for Online jobs.., http://www.onlinebizathome4all.blogspot.com
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx From __peter__ at web.de Sat Sep 27 04:02:30 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 27 Sep 2008 10:02:30 +0200 Subject: Negative block sizes with file-like objects References: <00edd446$0$20666$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have a proxy class that wraps an arbitrary file-like object fp and > reads blocks of data from it. Is it safe to assume that fp.read(-1) will > read until EOF? I know that's true for file.read() and StringIO.read(), > but is it a reasonable assumption to make for arbitrary file-like objects? > > To put it in more concrete terms, I have a class like this: > > class C(object): > # Much simplified version. > def __init__(self, fp): > self.fp = fp > def read(self, size=-1): > return self.fp.read(size) > > > Should I re-write the read() method like this? > > def read(self, size=-1): > if size < 0: > return self.fp.read() > else: > return self.fp.read(size) Grepping through the python source shows that both -1 and None are used as the default size. # python2.5.2 >>> import tarfile >>> open("sample", "w").write("contents-of-sample") >>> t = tarfile.open("sample.tar", "w") >>> t.add("sample") >>> t.close() >>> t = tarfile.open("sample.tar") >>> t.extractfile("sample").read() 'contents-of-sample' >>> t.extractfile("sample").read(-1)[:50] 'contents-of-sample\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' So you may fare better with the rewrite. But even that may fail: http://docs.python.org/lib/bltin-file-objects.html#l2h-295 """ read( [size]) [...] If the size argument is negative or omitted, read all data until EOF is reached. [...] Also note that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ Peter From callen314 at gmail.com Mon Sep 22 21:20:28 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 22 Sep 2008 18:20:28 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> Message-ID: > Snce when are "users" ever involved > in programming problems or programming > languages ? > since the begining, the first users are programmers, users of your libraries. From bedouglas at earthlink.net Wed Sep 3 16:36:50 2008 From: bedouglas at earthlink.net (bruce) Date: Wed, 3 Sep 2008 13:36:50 -0700 Subject: python/xpath question.. Message-ID: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> morning.... i apologize up front as this is really more of an xpath question.. in my python, i'm using the xpath function to iterate/parse some html. i can do something like s=d.xpath("//tr/td/text()") count=len(s) and get the number of nodes that have text i can then do something like s=d.xpath("//tr/td") count2=len(s) and get the number of total nodes... by subtracting, i can get the number of nodes, without text.. is there an easier way??!! count2-count ie, if i have something like foo is there a way to get the count that there is a single "td" node with text()="" thanks From qxyuestc at yahoo.cn Tue Sep 2 09:24:21 2008 From: qxyuestc at yahoo.cn (qxyuestc at yahoo.cn) Date: Tue, 2 Sep 2008 06:24:21 -0700 (PDT) Subject: what's the difference between f(a) and f(*a) Message-ID: <4b57d4c3-a398-41b1-916a-064ee96bf3f6@25g2000prz.googlegroups.com> def sum1(*a): return(sum(i*i for i in a)) def sum2(a): return(sum(i*i for i in a)) a=[1,2,3] print(sum1(*a), sum2(a)) #################################### showed above: the result from sum1() and sum2() is the same. So, what is the difference between f(a) and f(*a) From mr.spoon21 at gmail.com Sun Sep 14 15:19:06 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 14 Sep 2008 21:19:06 +0200 Subject: Abstract class In-Reply-To: <48CD62B8.7070708@islandtraining.com> References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <48CD62B8.7070708@islandtraining.com> Message-ID: <8f67b6f80809141219m5f66ac47xc2e0fce1786a2702@mail.gmail.com> On Sun, Sep 14, 2008 at 9:15 PM, Gary Herron wrote: > Please forget about Abstract Base Classes. They have nothing to do with > what you want, and are a *HUGE* overkill for your application. They are > not (yet) even part of standard Python, and are used primarily for a class > implementor to guarantee to a user of a class that it provides a specific > interface. Ok :D I started to think to abstract classes just because in the paper it uses an abstract class in SmallTalk. Anyway, thanks. From berthe.loic at gmail.com Thu Sep 4 13:11:45 2008 From: berthe.loic at gmail.com (LB) Date: Thu, 4 Sep 2008 10:11:45 -0700 (PDT) Subject: Help needed to freeze a script. References: <7f364174-75c6-4120-b00e-6f41643ccbf5@z72g2000hsb.googlegroups.com> <614c7366-ba7e-4296-a4f0-a32accaa427a@b38g2000prf.googlegroups.com> Message-ID: <0957cba5-9aa8-41d6-bf95-9d6a8db18c89@l33g2000pri.googlegroups.com> > Did you try py2exe instead offreeze? On the page > > http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules > > there is only one brief mention of numpy packaging troubles, > suggesting that it might work better. I have used py2exe in the past > without much trouble. Unfortunately, I'm working under Linux and py2exe works only for windows as far as I know. Do you know if py2exe executable embedding a lot of C extensions - like numpy and scipy - can ben executed on another computer, with a different architecture (64bits vs 32 bits) and a different OS ? -- LB From uninverted at lavabit.com Sun Sep 28 20:09:51 2008 From: uninverted at lavabit.com (Nathan Seese) Date: Mon, 29 Sep 2008 02:09:51 +0200 (CEST) Subject: Odd Errors Message-ID: When I run: #!/usr/bin/python lines = list() while 1: try: inLine = raw_input() lines = lines.append(inLine) except EOFError: break I get: Traceback (most recent call last): File "./foobar.py", line 7, in lines = lines.append(inLine) AttributeError: 'NoneType' object has no attribute 'append' From bj_666 at gmx.net Wed Sep 3 13:06:51 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Sep 2008 17:06:51 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <6i6pq9Fmcad7U2@mid.uni-berlin.de> Message-ID: <6i7uhbFmcad7U3@mid.uni-berlin.de> On Wed, 03 Sep 2008 03:09:18 -0400, Derek Martin wrote: > On Wed, Sep 03, 2008 at 06:40:10AM +0000, Marc 'BlackJack' Rintsch > wrote: >> On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote: >> >> >> And if they model an action there must be some way to activate the >> >> action >> > >> > That's a reasonable assumption, but as I also said, the object might >> > just describe the action -- essentially the equivalent of a struct in >> > C. >> >> ``struct``\s in C describe *actions*!? Functions do this. > > struct run { > int speed; > direction_type direction; > }; Guess what, I don't like the name because it doesn't describe an action but a state of, e.g. a `Runner`. :-) >> >> but the instances of `Popen` are no actions. There's no way to >> >> "execute" a `Popen` instance. >> > >> > Yes there is... you execute it when you instantiate the object. >> >> But then the instance itself isn't an action but the result of one. > > So? A class doesn't represent an action, remember? It represents a > thing. Isn't that what you said? Yes and that's why the type name should not describe the action but the the thing that results from it. IMHO. But I said that already. >> >> Maybe from your POV. Facts: It doesn't use the `popen()` function >> > >> > So? Neither does the C version of popen(), but that function is >> > still called popen()! >> >> Now you lost me. The C version of `popen()` isn't recursive, why on >> earth should it be, so what's that statement supposed to mean!? > > Sorry, did I go too fast for you? Your "facts" seem to be suggesting > that for Python's Popen class to be named Popen, it should use the C > popen() function. So you imply that I think any function should only have a name of a function it uses under the hood!? I still don't get that sentence. > Sorry, but you are contradicting yourself (repeatedly), and your > arguments don't make any sense. I don't contradict myself. Either you are playing silly naming games with `popen()` on different levels ("concept", Popen, popen() (Python), popen() (C)) or you just don't *want* to understand my arguments. I understand your arguments why you think `Popen` is a proper name, but don't share them. It's okay for me if you don't like my arguments against it and for something like `Process`, but telling me they don't make any sense and patronizing me doesn't make your arguments more convincing. Ciao, Marc 'BlackJack' Rintsch From akabaila at pcug.org.au Mon Sep 22 04:02:47 2008 From: akabaila at pcug.org.au (Al Kabaila) Date: Mon, 22 Sep 2008 18:02:47 +1000 Subject: matrix algebra Message-ID: <1222070567.979005@chilli.pcug.org.au> Hi, My OS is Linux (openSUSE 10.3) and my interest in retirement is Python applications to Structural Analysis of Civil Engineering structures, currently in 2 dimensions only (under GPL). Modern Structural Analysis is highly matrix oriented, but requires only a few basic matrix operations, namely matrix creation, transposition, multiplication, invertion and linear equation solution. For stability analysis one would require Eigenvalues and Eigenvectors. In 3 dimensions, additionally highly desirable would be vector algebra. The packages do have all these functions, but currently only the basic functions are in the wrapper. There are several packages for matrix algebra. I tried Numeric, numpy and numarray. All three are very good, but each uses different syntax. Not a good thing for teaching... So I wrote a little python wrapper (under GPL) to unify all packages with the same simple and transparent syntax. Currently it deals with the Numeric, numpy and numarray and covers creation of zero filled matrices, transposition, matrix multiplication, solution of equations and inversion. This is a very active newsgroup that incudes such giants as Frederik Lundh and countless others. I wonder: 1. Is there any interest in matrix algebra "for the masses" (I mean interest in a wrapper for a subset of functions of the packages with a unified simple syntax)? 2. What other matrix operations would be required for your area of interest? 3. What other matrix packages, if any, should one include in the wrapper? A copy of the wrapper is stored in a small, public svn repository. If you would like to download it, please contact me by email at. Of course, if there is interest, I would be delighted to upload it to a generally accessible repository. Finally, if this is a re-invention of the wheel (which it may well be), would you kindly let me know? akabaila [at] pcug [dot] org [dot] au. I would be very happy to send you the checkout instructions, but I should discuss that with the people who run the repository. My home page that I quote with my signature is not a repository nor does it have the current programs. OldAl. -- Al Kabaila (Dr) http://akabaila.pcug.org.au/StructuralAnalysis From stefan_ml at behnel.de Thu Sep 4 03:14:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 04 Sep 2008 09:14:16 +0200 Subject: xml + mmap cross In-Reply-To: References: Message-ID: <48BF8AC8.6030509@behnel.de> castironpi wrote: > Any interest in pursuing/developing/working together on a mmaped-xml > class? Faster, not readable in text editor. Any hints on what you are talking about? Stefan From beema.shafreen at gmail.com Tue Sep 9 04:53:19 2008 From: beema.shafreen at gmail.com (Beema Shafreen) Date: Tue, 9 Sep 2008 14:23:19 +0530 Subject: biopython Message-ID: Hi all, I am using Biopython to fetch pumed Id's ,The module i use is (from Bio import Entrez) But i am getting this error >>> from Bio import Entrez Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name Entrez what should i do know can anybody suggest me an alternative for this -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Tue Sep 23 20:24:54 2008 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 24 Sep 2008 10:24:54 +1000 Subject: python syntax for conditional is unfortunate In-Reply-To: Message-ID: <20080924002454.GA11028@cskk.homeip.net> On 23Sep2008 19:52, Neal Becker wrote: | In hindsight, I am disappointed with the choice of conditional syntax. | I know it's too late to change. The problem is | | y = some thing or other if x else something_else | | When scanning this my eye tends to see the first phrase and only | later notice that it's conditioned on x (or maybe not notice at all!). | Particularly if 'some thing or other' is long or complicated. Personally, I think this is deliberate (the wordiness and ordering, not the reading difficulty). Plenty of people dislike C's ternary b?x:y operator, presumably for the same reasons. A good coder will present things clearly. For trivial stuff the one line form may be fine, and for longer stuff then this: y = some thing or other \ if x \ else something_else or: if x: y = something or other else: y = something_else should appear. If it's your code, this is up to you. If it's another's, well anyone can write unreadable code... Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Principles have no real force except when one is well fed. - Mark Twain From info at wingware.com Thu Sep 18 12:07:29 2008 From: info at wingware.com (Wingware) Date: Thu, 18 Sep 2008 12:07:29 -0400 Subject: ANN: Wing IDE for Python v. 3.1.4 released Message-ID: <48D27CC1.2080703@wingware.com> Hi, Wingware has released version 3.1.4 of Wing IDE. This bug fix release is available for all three product levels of Wing IDE. *Release Highlights* This release includes the following: * Debugger support for Python 2.6 * Support zope buildout directories not named "instance" * Added highlighted keywords for caml, d, escript, lisp, ps, and yaml files * Don't display message that save is unavailable before running pylint * VI mode fix: After / de-select the search match once Enter is pressed * About 20 other bug fixes: see the change log for details http://wingware.com/pub/wingide/3.1.4/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE Pro 3.1.4 http://wingware.com/downloads/wingide/3.1 Wing IDE Personal 3.1.4 http://wingware.com/downloads/wingide-personal/3.1 Wing IDE 101 3.1.4 http://wingware.com/downloads/wingide-101/3.1 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.1 supports Python versions 2.0.x through 2.5.x. *New Features in Wing 3.1* This release adds the following features not found in Wing 3.0.x: * Support for zip archives * Support for pkg_resources name spaces and eggs * Support for doctest and nose style unit tests (*) * Scan for sys.path changes such as those used in buildout * How-To and support for Google App Engine * Inline context appropriate templates/snippets integrated with autocompleter (*) * Word list driven auto-completion in non-Python files (**) * Quick navigation to files and symbols by typing a fragment (**) * Improved support for Stackless Python * Preference to strip trailing white space on save * Display gi_running and gi_frame for generators * Improved code analysis for Python 2.5 * Other minor features and bug fixes not found in Wing 3.0.x (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal or Professional only. Please see the change log for a detailed list of changes: http://wingware.com/pub/wingide/3.1.4/CHANGELOG.txt *Purchasing and Upgrading* Wing 3.1 is a free upgrade for all Wing IDE 3.0 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From bj_666 at gmx.net Thu Sep 11 05:32:03 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Sep 2008 09:32:03 GMT Subject: Is len O(n) or O(1) ? References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> Message-ID: <6is6sjF6v3jU1@mid.uni-berlin.de> On Thu, 11 Sep 2008 02:23:43 -0700, process wrote: > Python uses arrays for lists right? `len()` on `list` objects is O(1). > def quicksort(lista): > if lista == []: > lista > else: > return quicksort([x for x in lista[1:] if x < lista[0]]) + > [lista[0]] + \ > quicksort([x for x in lista[1:] if x >= lista[0]]) > > or > > def quicksort(lista): > if len(lista) == 0 > lista > else: > return quicksort([x for x in lista[1:] if x < lista[0]]) + > [lista[0]] + \ > quicksort([x for x in lista[1:] if x >= lista[0]]) > > wait first one raises TypeError unsupported operand types. Both do because `None` + `list` doesn't make sense. You should actually ``return`` the `lista` in the ``if`` branch instead of just lookup the object for that name and then do nothing with it. Shorter alternative: if not lista: return [] Empty lists are considered `False` in a boolean test. Ciao, Marc 'BlackJack' Rintsch From petite.abeille at gmail.com Mon Sep 8 13:51:49 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Mon, 8 Sep 2008 19:51:49 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: References: <6ii9jbFqoe2eU1@mid.uni-berlin.de> <6ikc76Fr32cnU1@mid.uni-berlin.de> Message-ID: On Sep 8, 2008, at 1:56 PM, Gerhard H?ring wrote: > But AFAIK it's possible to compile a custom SQLite with appropriate > flags to ./configure that will include the fulltext search extension. It's indeed rather straightforward to integrate FTS, e.g.: % CFLAGS="-DSQLITE_ENABLE_FTS3=1" ./configure % sudo make install "Full-Text Search on SQLite" http://blog.michaeltrier.com/tags/fts Here is an example of FTS at work: http://svr225.stepx.com:3388/search?q=chicago Cheers, -- PA. http://alt.textdrive.com/nanoki/ From istvan.albert at gmail.com Fri Sep 26 23:28:32 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 26 Sep 2008 20:28:32 -0700 (PDT) Subject: multiprocessing eats memory References: <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> Message-ID: <02522a54-40ad-46a7-acb9-544f2fa5998f@d70g2000hsc.googlegroups.com> On Sep 26, 4:52?am, redbaron wrote: > How could I avoid of storing them? I need something to check does it > ready or not and retrieve results if ready. I couldn't see the way to > achieve same result without storing asyncs set. It all depends on what you are trying to do. The issue that you originally brought up is that of memory consumption. When processing data in parallel you will use up as much memory as many datasets you are processing at any given time. If you need to reduce memory use then you need to start fewer processes and use some mechanism to distribute the work on them as they become free. (see recommendation that uses Queues) From larry.bates at vitalEsafe.com Mon Sep 15 14:11:40 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Mon, 15 Sep 2008 13:11:40 -0500 Subject: Parallelising code In-Reply-To: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: psaffrey at googlemail.com wrote: > I have some file processing code that has to deal with quite a lot of > data. I have a quad core machine, so I wondered whether I could take > advantage of some parallelism. > > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? > > - Is list.append() thread safe? (not sure if this is the right term) > what I mean is, can two separate processors file a point in the same > list at the same time without anything horrible happening? Do I need > to do anything special (mutex or whatever) to make this happen, or > will it happen automatically? > > Thanks in advance for any guidance, > > Peter Put the data into a database first to see if it is actually too slow. If it is take a look at an in-memory database or perhaps something as simple as memcached could help. -Larry From bignose+hates-spam at benfinney.id.au Mon Sep 8 05:47:30 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 08 Sep 2008 19:47:30 +1000 Subject: universal unicode font for reportlab References: Message-ID: <87r67vj7f1.fsf@benfinney.id.au> Laszlo Nagy writes: > I could not find any free TTF font that can do latin1, latin2, > arabic, chinese and other languages at the same time. Is there a > single font that is able to handle these languages? The GNU Unifont covers an impressive range of the Unicode Basic Multilingual Plane. Unifont is originally a bitmap font, but was recently made available in TrueType format . Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont' packages, respectively. -- \ ?Science doesn't work by vote and it doesn't work by | `\ authority.? ?Richard Dawkins, _Big Mistake_ (The Guardian, | _o__) 2006-12-27) | Ben Finney From ggpolo at gmail.com Sun Sep 14 11:06:22 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 14 Sep 2008 12:06:22 -0300 Subject: cjson 1.0.5 keyword argument In-Reply-To: <31008070-11e0-44ad-9b27-9985323afb9a@s1g2000pra.googlegroups.com> References: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> <31008070-11e0-44ad-9b27-9985323afb9a@s1g2000pra.googlegroups.com> Message-ID: On Sun, Sep 14, 2008 at 11:50 AM, Clodoaldo wrote: > On Sep 14, 11:45 am, "Guilherme Polo" wrote: >> On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo wrote: >> > I have installed cjson 1.05 in Fedora 8 (python 2.5.1). >> >> > The cjson home page shows a keyword argument "encoding". >> >http://python.cx.hu/python-cjson/ >> >> The latest python-cjson on that page is 1.0.3, which accepts keywords >> for the encode function. python-cjson 1.0.5 no longer accepts. >> >> > When i use it i get an error: >> >> >>>> cjson.encode('?', encoding='utf8') >> > Traceback (most recent call last): >> > File "", line 1, in >> > TypeError: encode() takes no keyword arguments >> >> > What am i missing? There is no mail list for cjson. >> >> Try doing cjson.encode('?'.decode('utf-8')) instead. > > I had tried decoding first and it worked but my database is utf-8 so i > don't want that extra step. I'm not sure about this "extra step" you are talking about. When you do cjson.encode('?', encoding='utf-8') (supposing you are using python-cjson 1.0.3) it will actually end up doing the same as cjson.encode('?'.decode('utf-8')) > > BTW i have already found the problem as the other post shows. Then you didn't install python-cjson 1.0.5, it was probably 1.0.3 like I said in my other post. > > Thanks, Clodoaldo > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dblubaugh at belcan.com Fri Sep 12 16:02:44 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Fri, 12 Sep 2008 16:02:44 -0400 Subject: I cannot find where Numpy 1.2 is located Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> To All, I have been trying to locate as to where Numpy 1.2 can be downloaded. I will need this update. The only version available at the Numpy website for download is only 1.1.1 not the required 1.2 that I definitely need at this time. David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From mohitranka at gmail.com Thu Sep 18 09:23:50 2008 From: mohitranka at gmail.com (Mohit Ranka) Date: Thu, 18 Sep 2008 18:53:50 +0530 Subject: Login to website using urllib2 Message-ID: <63fb26950809180623uea83fa5r34a7a3e2f4198b37@mail.gmail.com> Hi All, I am trying to fetch HTML content from a website that has different version of pages for "logged" users and "guseuests" users. I need to fetch the "logged" user pages. The problem is, even with the use of basic authentication, I am getting "guest" user page with urllib2.urlopen. The code can be seen here. http://pastebin.com/m7301084a Any suggestions/pointers/solutions? Thanks and regards, Mohit Ranka. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sotirac at gmail.com Mon Sep 29 15:48:31 2008 From: sotirac at gmail.com (sotirac) Date: Mon, 29 Sep 2008 12:48:31 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: <4c2f4546-9f0b-4c7d-9c9e-dac39fd286cd@79g2000hsk.googlegroups.com> On Sep 28, 5:22?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 28, 4:08?pm, Michael Str?der wrote: > > > > > Gary M. Josack wrote: > > > Aaron "Castironpi" Brady wrote: > > >> On Sep 28, 2:59 pm, sotirac wrote: > > > >>> Wondering if there is a better way to generate string of numbers with > > >>> a length of 5 which also can have a 0 in the front of the number. > > > >>>
> > >>> ?random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > >>> elements
> > >>> ?code = 'this is a string' + str(random_number[0]) +
> > >>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > >>> + str(random_number[4])
> > >>> 
> > > >> '%05i'%random.randint(0,99999) > > >> -- > > >>http://mail.python.org/mailman/listinfo/python-list > > > > This produces numbers other than 5 digit numbers. making the start > > > number 10000 should be fine. > > > Why do you think it's wrong? > > > >>> import random > > >>> '%05i'%random.randint(0,99999) > > '09449' > > > IMO it's exactly what was required. > > > Ciao, Michael. > > As you read, there isn't agreement on whether the OP wanted > replacement. ?His original code didn't; his spec seemed to. My value of the result string can be '00000' to '99999'. From paul at boddie.org.uk Sat Sep 6 20:37:52 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 6 Sep 2008 17:37:52 -0700 (PDT) Subject: Use BeautifulSoup to delete certain tag while keeping its content References: Message-ID: On 6 Sep, 17:11, "Jackie Wang" wrote: > > I have the following html code: > > > > Center Bank >
> Los Angeles, CA >
> > > > > Salisbury > Bank and Trust Company > >
> Lakeville, CT >
>
> > > How should I delete the 'font' tags while keeping the content inside? This sounds like an editing exercise, really. If you're comfortable learning a new tool, I can recommend XSLT for this kind of job. Here's the stylesheet: This just describes two things: firstly, that you want to recognise font elements and to include their contents, not each element's start and end tags; secondly, that all other parts of the document should be copied. You can apply stylesheets using a number of XSL processors. The xsltproc program is usually available where libxslt is installed, and although I'm sure others will be along to tell you all about their favourite libraries and tools, here's how I use mine within Python: # XSLTools: http://www.python.org/pypi/XSLTools # libxml2dom: http://www.python.org/pypi/libxml2dom import XSLTools.XSLOutput import libxml2dom # If s is the document text... d = libxml2dom.parseString(s) # Save the above stylesheet to a file somewhere, then... proc = XSLTools.XSLOutput.Processor(["/tmp/no-font.xsl"]) # Get the result document d2 = proc.get_result(d) Anyway, this is just one option of many to deal with this kind of problem. Paul From fredrik at pythonware.com Thu Sep 4 10:53:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 16:53:53 +0200 Subject: Numeric literal syntax In-Reply-To: References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: Alexander Schmolck wrote: >> A problem is that '1234' in Python is a string, so using ' in numbers >> looks a bit dangerous to me (and my editor will color those numbers as >> alternated strings, I think). > > Yeah, editors, especially those with crummy syntax highlighting (like emacs) > might get it wrong. This should be easy enough to fix though. instead of forcing all editor developers to change their Python modes to allow you to use a crude emulation of a typographic convention in your Python source code, why not ask a few of them to implement the correct typographic convention (thin spaces) in their Python mode? From mal at egenix.com Thu Sep 4 19:52:30 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 05 Sep 2008 01:52:30 +0200 Subject: Can anyone suggest a good crypto package? In-Reply-To: References: Message-ID: <48C074BE.1050207@egenix.com> On 2008-09-04 20:39, Fett wrote: > I need a crypto package that works on windows with python 2.5. Can > anyone suggest one for me? > > I have been searching for a couple days for a good cryptography > package to use for public/private key encryption, at this point I > would settle for symmetric even. I'm not really sure what you're after, but if it's about end-to-end encryption and authentication, then OpenSSL is the way to go, e.g. using pyOpenSSL: http://www.egenix.com/products/python/pyOpenSSL/ > Every encryption package I have found for python was either operating > system specific (read *nix only): > http://www.freenet.org.nz/ezPyCrypto/ > http://www.keyczar.org/ > > There was one exception, this version was specifically built to run on > any platform (yay), but the compiler for windows complained that I > wasn't using python2.2 (though the package was said to only need 2.2 > or newer). > > Is there any crypto package that is actually written in python? I > seriously don't care how slow it is. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 05 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From sebastianthegreatful at gmail.com Thu Sep 18 03:59:17 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Thu, 18 Sep 2008 00:59:17 -0700 (PDT) Subject: ssl server References: Message-ID: On Sep 17, 7:33?pm, Seb wrote: > I'm making a ssl server, but I'm not sure how I can verify the > clients. What do I actually need to place in _verify to actually > verify that the client cert is signed by me? > > ?50 class SSLTCPServer(TCPServer): > ?51 ? ? ? ? keyFile = "sslcert/server.key" > ?52 ? ? ? ? certFile = "sslcert/server.crt" > ?53 ? ? ? ? def __init__(self, server_address, RequestHandlerClass): > ?54 ? ? ? ? ? ? ? ? ctx = SSL.Context(SSL.SSLv23_METHOD) > ?55 ? ? ? ? ? ? ? ? ctx.use_privatekey_file(self.keyFile) > ?56 ? ? ? ? ? ? ? ? ctx.use_certificate_file(self.certFile) > ?57 ? ? ? ? ? ? ? ? ctx.set_verify(SSL.VERIFY_PEER | > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > self._verify) > ?58 ? ? ? ? ? ? ? ? ctx.set_verify_depth(10) > ?59 ? ? ? ? ? ? ? ? ctx.set_session_id('DFS') > ?60 > ?61 ? ? ? ? ? ? ? ? self.server_address = server_address > ?62 ? ? ? ? ? ? ? ? self.RequestHandlerClass = RequestHandlerClass > ?63 ? ? ? ? ? ? ? ? self.socket = socket.socket(self.address_family, > self.socket_type) > ?64 ? ? ? ? ? ? ? ? self.socket = SSL.Connection(ctx, self.socket) > ?65 ? ? ? ? ? ? ? ? self.socket.bind(self.server_address) > ?66 ? ? ? ? ? ? ? ? self.socket.listen(self.request_queue_size) > ?67 > ?68 ? ? ? ? def _verify(self, conn, cert, errno, depth, retcode): > ?69 ? ? ? ? ? ? ? ? return not cert.has_expired() and > cert.get_issuer().organizationName == 'DFS' Simply return retcode and it will work... assuming you have the certs setup properly. From marco.bizzarri at gmail.com Fri Sep 5 01:17:29 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 07:17:29 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <3f0d61c40809042217r6f98c683p90bcae958b1ee773@mail.gmail.com> On Thu, Sep 4, 2008 at 8:59 PM, Carl Banks wrote: > > > You can write code to guard against this if you want: > > class A: > legal = set(["x"]) > def __setattr__(self,attr,val): > if attr not in self.legal: > raise AttributeError("A object has no attribute '%s'" % > attr) > self.__dict__[attr] = val > def __init__(self,x): > self.y = x > > > I suspect most people who go into Python doing something like this > soon abandon it when they see how rarely it actually catches anything. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > Carl, I think I did not explained what I was asking the right way. I'm not asking: "how can I do this sort of checks in Python": as I stated before, if I want them, I will go for Java, or some other language like that. I understand that Python is a balance between different forces (like any software object around the world) and I'm simply asking some pointers to the discussion leading to this balance. That's all. -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From google at mrabarnett.plus.com Fri Sep 26 11:54:32 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Sep 2008 08:54:32 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> Message-ID: On Sep 26, 4:13?pm, Steven D'Aprano wrote: > On Fri, 26 Sep 2008 06:31:40 -0500, skip wrote: > > I took over spam filter management for the python.org mailing lists a > > couple months ago and made a few changes to the way the spam filter is > > trained. Things seem to be at a reasonable level as far as I can tell (I > > see a few spams leak through each day), though I wasn't actively reading > > comp.lang.python/python-l... at python.org before I took over the task, so > > I have nothing to compare with. ?Does the level of spam leaking through > > the filter now seem excessive? ?Is it more or less than in June and > > July? > > I don't have any objective numbers, but subjectively it seems to me that > the number of spams is significantly higher, but not so high as to be a > major nuisance. > I think it changes over time. You might tweak the filter to reduce the amount of spam getting through but then the spammers adapt. In other words, spam is a moving target. From joefazee at gmail.com Tue Sep 30 10:32:55 2008 From: joefazee at gmail.com (A. Joseph) Date: Tue, 30 Sep 2008 07:32:55 -0700 Subject: Replacing cmd.exe with custom .py application Message-ID: Instead of going to the command line all the time, I want to create a small customized cmd.exe of my own, how can I get the return value from os.system() because I was thinking I can do soothing with os.system(), In case my question is not clear, just like an IDE that plugged in another .exe application. Sorry for any mistake in my question. Just help me if you can -------------- next part -------------- An HTML attachment was scrubbed... URL: From mbezzi at landi.it Mon Sep 22 03:26:37 2008 From: mbezzi at landi.it (mbezzi at landi.it) Date: Mon, 22 Sep 2008 00:26:37 -0700 (PDT) Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> <974c3434-d409-484d-8bc4-7a3294132bd0@73g2000hsx.googlegroups.com> <6jnfn6F47453U2@mid.individual.net> Message-ID: <702acfae-d187-4b3e-b63b-ad08460ff46f@r66g2000hsg.googlegroups.com> On Sep 21, 7:48?pm, Peter Pearson wrote: > FWIW, since I started following this newsgroup, I've noticed > that I no longer have those crises that revolve around the depth > of a copy. ?I conjecture that they resulted from non-pythonic > style. ?Try following this newsgroup for a while, and you might > see a lot of startlingly elegant ways of doing things. > > -- > To email me, substitute nowhere->spamcop, invalid->net. I know the code is really ugly but I just make a quick and dirty snippet to ask for help. I should have wrapped the code between tags ;-) Alex From half.italian at gmail.com Wed Sep 24 23:04:14 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 24 Sep 2008 20:04:14 -0700 (PDT) Subject: Off topic: Sent from my Foo messages References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <00eaf368$0$20666$c3e8da3@news.astraweb.com> Message-ID: > -- > Steven I don't appreciate the two lines you put above your name in your posts. Please remove them in the future. ~Sean From durand1 at gmail.com Sat Sep 6 08:38:05 2008 From: durand1 at gmail.com (Durand) Date: Sat, 6 Sep 2008 05:38:05 -0700 (PDT) Subject: quake like multicoloured text References: <3d829a04-9005-4216-86dc-b1055edab4e7@f63g2000hsf.googlegroups.com> Message-ID: <417c958f-2f57-4826-8640-e3844ef614e0@f36g2000hsa.googlegroups.com> On Sep 5, 10:32?pm, "Gabriel Genellina" wrote: > En Fri, 05 Sep 2008 16:24:08 -0300, Durand escribi?: > > > > > > > I'm wondering how I could render text with PIL in which different > > parts of the text are different characters. This is for a game stats > > script where names are written like: > > ^1Red ^2Green ^3Yellow, etc. > > The problem is that I currently use text in the ImageDraw module but > > the only way I can think of rendering text is by rendering each bit of > > text in a separate colour. > > > Example: > > > draw.text((0,0),"Red", fill="red") > > draw.text((30,0),"Green", fill="green") > > draw.text((60,0),"Yellow", fill="green") > > > except that I'm not sure how much spacing there is between each > > coloured bit of text(30px is assumed in the example)...Would there be > > an alternate method of doing this? > > You could use the draw.textsize method to measure how much space will take ? > each part... > > -- > Gabriel Genellina Thanks, I guess I should have done more research... From goldspin at gmail.com Thu Sep 11 13:11:00 2008 From: goldspin at gmail.com (Henry Chang) Date: Thu, 11 Sep 2008 10:11:00 -0700 Subject: How to Determine Name of the Day in the Week Message-ID: Instead of getting integers with weekday(), Monday == 0 ... Sunday == 6; is there a way to get the actual names, such as "Monday ... Sunday"? I would like to do this without creating a data mapping. :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid Fri Sep 19 10:23:05 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 19 Sep 2008 09:23:05 -0500 Subject: Python newbie References: Message-ID: <8s2dnX2ttZtUKE7VnZ2dnUVZ_gSdnZ2d@posted.visi> On 2008-09-19, Mladen Gogala wrote: > Steve Holden wrote: > >> No. Python implicitly dereferences all names when using them >> to compute values, and only uses them as references on the >> left-hand side of an assignment. >> >> Please note the above statement is contentious, and will >> likely bring a horde of screaming fanatics of various flavors >> down on my head for terminological inexactitude. > > Actually, I am not a "screaming fanatic". Steve was refering hyperbolically to people like me who find it entertaining to argue about obscure technical points involving useless, degenerate bits of example code. It's one of the things we do here instead of Perl golfing. Though off hand I don't really see anything much wrong with the statement for which Steve predicted an impending onslaught of language lawyers -- unless one wanted to jump right away into the stock discussion on name-rebinding vs. dereferencing-pointer-lvalues that we generally save for C/C++ programmers. I only used Perl once about 15 years ago (that was more than enough for me), but I would have guessed that an assigment in Perl was a name-(re)binding more akin to Python than a store to a variable's memory location like C/C++/Pascal/etc. > Hopefully, this explains who am I and what is my motivation > for delving into Python. I share your fears of screaming > fanatics, too. We're actually quite harmless and much friendlier than those in most other newsgroups. -- Grant Edwards grante Yow! My EARS are GONE!! at visi.com From gagsl-py2 at yahoo.com.ar Tue Sep 30 00:34:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 01:34:25 -0300 Subject: rlcompleter and wxPython, problems ... References: <48E0045A.3020402@gmail.com> Message-ID: En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki escribi?: > I'm trying to implement autocompletion into my editor. > But I find some weird behavior, > or at least I don't have the faintest idea why this behavior occures, > and even more important how to solve it > In the example below I try to autocomplete " wx.s" , which in my humble > opinion should at least produce "wx.stc" (and some others ). wx is a package. Modules within the package are not, by default, attributes of the package - unless they're imported in __init__.py or your code imports them. So the autocompleter is doing the right thing - wx.stc does not exist until it is explicitely imported. py> import wx py> wx.stc Traceback (most recent call last): ... AttributeError: 'module' object has no attribute 'stc' py> 'stc' in dir(wx) False py> import wx.stc py> wx.stc py> 'stc' in dir(wx) True -- Gabriel Genellina From ivanov.maxim at gmail.com Thu Sep 25 08:40:48 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Thu, 25 Sep 2008 16:40:48 +0400 Subject: multiprocessing eats memory Message-ID: I'm playing with pyprocessing module and found that it eats lot's of memory. I've made small test case to show it. I pass ~45mb of data to worker processes and than get it back slightly modified. At any time in main process there are shouldn't be no more than two copies of data (one original data and one result). I run it on 8-core server and top shows me that main process eats ~220 Mb and worker processes eats 90 -150 mb. Isn't it too much? Small test-case is uploaded to pastebin: http://pastebin.ca/1210523 From wuwei23 at gmail.com Sat Sep 27 07:53:56 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 27 Sep 2008 04:53:56 -0700 (PDT) Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: <8754d1a9-1cf4-47b6-a5c2-2e6081988d27@w39g2000prb.googlegroups.com> On Sep 27, 3:58?pm, r0g wrote: > Ah, just spotted the backticks - they just return whatever's inside them > as a string. No, they return the repr() of the object inside. The output of __repr__ -has- to be a string, but typecasting into string isn't the intention of repr() (or the ` operator). From f.guerrieri at gmail.com Thu Sep 4 09:32:02 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Thu, 4 Sep 2008 15:32:02 +0200 Subject: path slashes cleaning In-Reply-To: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> References: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> Message-ID: <79b79e730809040632y5b08a757i762635140006593@mail.gmail.com> On Thu, Sep 4, 2008 at 3:25 PM, Mathieu Prevot wrote: > Hi, > > for scripts that take arguments, I would like to remove the trailing > slash if it's present. > > Is there something else than: > > a='/usr/local/lib/' > if a[-1] == '/': > a = list(a) > a.pop() > ''.join(a) > > Thanks, > Mathieu a.rstrip('/') does the job. bye, Francesco From stefan_ml at behnel.de Wed Sep 17 15:17:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 17 Sep 2008 21:17:13 +0200 Subject: Generating test data from an XML Schema In-Reply-To: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> References: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> Message-ID: <48d157b9$0$6622$9b4e6d93@newsspool3.arcor-online.net> Mark Thomas wrote: > On Sep 17, 5:29 am, Jonathan Fine wrote: >> I want to generate test data from an XML schema. I've had a quick look >> at existing tools (such as minixsv and amara) but from what I've seen >> they don't seem to help. > ... >> A tool that provides a nice Python interface to navigating the schema >> would probably be quite helpful. >> >> Has anyone seen anything that might help generate test data from a schema? > > I'm unaware of anything in Python, but Eclipse can generate sample > documents from a schema: > http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html > > As can XML IDEs such as Stylus Studio and XML Spy. There's also a Java tool called the "XML instance generator" by Sun that supports XML Schema and RelaxNG. It's a bit tricky to find as most links to it are broken by now. Stefan From m_palmer45 at yahoo.ca Tue Sep 9 20:36:15 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 9 Sep 2008 17:36:15 -0700 (PDT) Subject: Read and write binary data References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: On Sep 7, 6:41 pm, Mars creature wrote: > Hi guys, > I am new to Python, and thinking about migrating to it from matlab > as it is a really cool language. Right now, I am trying to figure out > how to control read and write binary data, like > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > I googled, but can not find a clear answer. Anyone has clue where can > I learn it? Thanks!! > Jinbo the struct module should be useful From nytrokiss at gmail.com Fri Sep 26 15:41:35 2008 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 26 Sep 2008 12:41:35 -0700 Subject: Python is slow? In-Reply-To: <28f1b350-9908-4056-bfa2-e6c2d9edb17d@i76g2000hsf.googlegroups.com> References: <28f1b350-9908-4056-bfa2-e6c2d9edb17d@i76g2000hsf.googlegroups.com> Message-ID: <8a6b8e350809261241w22d76dd4n38fbac822aef6632@mail.gmail.com> +1 QOTW... On Tue, Sep 23, 2008 at 7:13 AM, George Sakkis wrote: > On Sep 23, 9:57 am, Grant Edwards wrote: > > > On 2008-09-23, sturlamolden wrote: > > > > [...] > > > > > After having a working Python prototype, I resorted to rewrite the > > > program in C++. The Python prototype took an hour to make, debug and > > > verify. The same thing in C++ took me almost a day to complete, even > > > with a working prototype as model. To my surprise, the resulting beast > > > of C++ required 64.3 seconds to construct the same kd-tree. Searching > > > the tree was not faster either, 1,000 points required 38.8 seconds. I > > > wasted a day, only to find my Python prototype being the faster. > > > > > We may conclude that I'm bad at programming C++, > > > > AFAICT, _everybody_ is bad at programming C++. > > +1 QOTW > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From d3vvnull at gmail.com Fri Sep 26 18:05:30 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 17:05:30 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: References: <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Message-ID: <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> so you wouldn't object then to something like '.... in (%)' % ','.join([str_edit_for_exploit(x) for x in aList]) if str_edit_for_exploit applied security edits? On Fri, Sep 26, 2008 at 2:28 PM, Benjamin Kaplan wrote: > > > On Fri, Sep 26, 2008 at 3:04 PM, Michael Mabin wrote: > >> Doesn't it depend on where and why you intend to execute the code? >> Obviously some SQL is more at risk for exploit when the input is from the >> screen on a web page than if you were running parameterized code in a >> controlled batch environment. Or if you were writing code generators (which >> is what I happen to do) which won't be run by the general public. >> >> Incidentally, couldn't input field edits prevent such exploits prior to >> interpolation? >> > > There are ways to avoid SQL injection attacks, such as escaping all quotes > in the text. We were simply pointing out that you have to be very careful > when you add arbitrary strings into SQL statements. If you control > everything going into the statement, you shouldn't have to worry about this. > > > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From cvrebert at gmail.com Fri Sep 12 21:08:01 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Fri, 12 Sep 2008 18:08:01 -0700 Subject: Good python web programming books In-Reply-To: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> References: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> Message-ID: <47c890dc0809121808g3c57e4b8p87166657a7b4a29e@mail.gmail.com> I've heard good things about The Django Book: http://www.djangobook.com/ - Chris On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma wrote: > Hi Guys, > > I am very new to python. I am looking for a good book about python web > programming. > > I looked at a few online like Web Programming In Python but most are quite > old. > > If you've read a good book on python web programming can you please suggest > some? > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From erikwickstrom at gmail.com Thu Sep 18 19:23:46 2008 From: erikwickstrom at gmail.com (erikcw) Date: Thu, 18 Sep 2008 16:23:46 -0700 (PDT) Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> Message-ID: <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> On Sep 18, 3:33?pm, Ben Finney wrote: > erikcw writes: > > I have a cgi script where users are uploading large files for > > processing. I want to launch a subprocess to process the file so the > > user doesn't have to wait for the page to load. > > For "how do I deal with subprocesses from Python", the (new in Python > 2.4) 'subprocess' module is the default go-to answer > , replacing a > rather fragmented set of modules before it. > > > What is the correct way to launch subprocess without waiting for the > > result to return? > > Creating an instance of 'subprocess.Popen' will launch the process and > return the Popen instance. You then have the option of polling it or > waiting for it to complete. > > -- > ?\ ? ? ?To stay young requires unceasing cultivation of the ability to | > ? `\ ? ? ? ? ? ? ? ? ? unlearn old falsehoods.? ?Robert Anson Heinlein | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > Ben Finney So if I create a Popen object and then just ignore the object and exit the program the subproccess will finish it's work and then exit itself cleanly? From ldo at geek-central.gen.new_zealand Mon Sep 29 05:22:02 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:22:02 +1300 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> Message-ID: In message , Ross Ridge wrote: > You need either use trial and error to find out, or look at the source. So what's wrong with using the source as documentation? :) From agostino.russo at gmail.com Tue Sep 9 13:47:13 2008 From: agostino.russo at gmail.com (ago) Date: Tue, 9 Sep 2008 10:47:13 -0700 (PDT) Subject: PYTHONSITEDIR environment variable Message-ID: Dear all, These days I often find myself using working-env.py, virtual-python.py & co. The main reason in most cases is to insulate my working environment so that I can use custom site-package libs together with the default stdlib. PYTHONHOME and/or PYTHONPATH (particularly with python -S) get close, but not quite there, and the above scripts seem a bit over the top. Wouldn't it be possible to support a PYTHONSITEDIR environment variable in site.py for this purpose? I have attached a possible patch. In what follows, if PYTHONSITEDIR is defined, that dir is used as the only source of site-packages, extra paths can easily be added by creating a .pth file in there. A different variable could be used to prepend a sitedir to the list of default sitedirs (similar code without "return None"). --- /usr/lib/python2.5/site.py 2008-05-29 22:03:04.000000000 +0100 +++ /tmp/site.py 2008-09-09 18:06:42.000000000 +0100 @@ -167,6 +167,10 @@ def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" + sitedir = os.environ.get('PYTHONSITEDIR') + if sitedir and os.path.isdir(sitedir): + addsitedir(sitedir, known_paths) + return None prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) From rsarpi at gmail.com Tue Sep 9 17:35:13 2008 From: rsarpi at gmail.com (icarus) Date: Tue, 9 Sep 2008 14:35:13 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw That did it. one more question... how do I create a pythonw standalone executable that works on w32, linux, mac, etc..? My intent is to have the process transparent to the user. He wouldn't even know the app was written in python. All he knows that when he double-clicks on it, the application pops up without the DOS black screen in the background (for w32 users.) On Sep 9, 10:49 am, "Chris Rebert" wrote: > You need to have the script be run by pythonw.exe as opposed to python.exe > pythonw.exe suppresses the DOS box from coming up and should be used > for running GUI applications such as yours. > > Regards, > Chris > > > > On Tue, Sep 9, 2008 at 1:33 PM, icarus wrote: > > platform: windows xp professional, python 2.5, wxpython > > > When I double-check on my program file test.py (for simplicity I'll be > > using this code below), I see the window just fine. But the ms-dos > > black window pops up in the background. On Linux, no issues at all. > > > How can I get rid of that ms-dos black window in the background? > > something I need to add to my code? a setting to adjust in windows? > > thanks in advance. > > > #!/usr/bin/python > > import wx > > > appwx = wx.App() > > > frame = wx.Frame(None, -1, 'test.py') > > frame.Show() > > > appwx.MainLoop() > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com From marco.bizzarri at gmail.com Thu Sep 4 06:05:15 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 12:05:15 +0200 Subject: overwrite set behavior In-Reply-To: References: Message-ID: <3f0d61c40809040305t1af64757wfe9ef279b69bfc45@mail.gmail.com> Ciao, Michele: On Thu, Sep 4, 2008 at 11:48 AM, Michele Petrazzo wrote: > Hi all, I want to modify the method that set use for see if there is > already an object inside its obj-list. Something like this: > > class foo: pass > > bar1 = foo() > bar1.attr = 1 > > bar2 = foo() > bar2.attr = 1 > > set( (bar1, bar2), key=lambda o: o.attr) > > and, of course, set has only one value. > > It's possible? > > Thanks, > Michele > -- > http://mail.python.org/mailman/listinfo/python-list > looking at the source, maybe you could create a subclass of Set redefining the __contains__ method? Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From sturlamolden at yahoo.no Sun Sep 7 00:24:07 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 6 Sep 2008 21:24:07 -0700 (PDT) Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: <96df416b-cc13-4631-8865-d6b6373772a5@z72g2000hsb.googlegroups.com> On 7 Sep, 00:06, cnb wrote: > If I buy a multicore computer and I have really intensive program. How > would that be distributed across the cores? Distribution of processes and threads across processors (cores or CPUs) is managed by the operating system. > Will algorithms always have to be programmed and told specifically to > run on several cores so if not told it will only utilize one core? One particular program has to be programmed for concurrency to utilize multiple cores. But you typically have more than one program running. > So is the free lunch really over or is this just an overhyped > phenomena? Two slow cores are better than one fast for most purposes. For one thing, it saves power. It's good for the battries and environment alike. > Is threading with Python hard? It's not harder than with other systems. You just subclass threading.Thread, which has almost the same interface as Java threads. Threading with Python is perhaps a bit easier than with other common platforms, due to the Queue.Queue object and the lack of volatile objects. > Can you start several processes with Python or just threads? You can do both. However, remember that Python threads only do what threads were designed to do back in the 1990s. That is asynchrony for I/O and UIs, not concurrency on multiple processors for CPU bound computing. This is due to the "Global Interpreter Lock". The GIL is better than fine-grained locks for single-threading and concurrency with multiple processes, but prevent python threads form being used for concurrency (just as well). You can do concurrency with Java threads or Win32 threads, but this is merely a side-effect. You will often see claims form novice programmers that threads are the only route to concurrency on multi- core CPUs. In addition to the existence of processes, direct use of threads from Java, .NET, POSIX, or Win32 APIs is not even the preferred way of programming for concurrency. Tinkering with low-level threading APIs for concurrency is error-prone and inefficient. You will spend a lot of time cleansing your code of dead-locks, live- locks, volatile objects not being declared volatile, and race conditions. In addition to that, chances are your code will not perform or scale very well due to memory contention, cache line misses, inefficient use of registers due to volatile objects, etc. The list is endless. That is why Java 6 and .NET 3.5 provide other abstractions for multi-core concurrency, such as ForkJoin and Parallel.For. This is also the rationale for using an OpenMP enabled compiler for C or Fortran, auto-vectorizing C or Fortran compilers, and novel languages like cilk and erlang. Traditionally, concurrency om parallel computers have been solved using tools like BSPlib, MPI, vectorizing Fortran compilers, and even "ebarassingly parallel" (running multiple instances of the same program on different data). OpenMP is a recent addition to the concurrency toolset for SMP type parallel computers (to which multi- core x86 processors belong). If you really need concurrency with Python, look into MPI (PyMPI, PyPAR, mpi4py), Python/BSP, subprocess module, os.fork (excluding Windows), pyprocessing package, or Parallel Python. BSP is probably the least error-prone paradigm for multi-core concurrency, albeit not the most efficient. If you decide to move an identified bottleneck from Python to C or Fortran, you also have the option of using OpenMP or cilk to ease the work of programming for concurrency. This is my preferred way of dealing with bad bottlenecks in numerical computing. Remember that you need not learn the overly complex Python C API. Cython, ctypes, f2py, or scipy.weave will do just as well. This approach will require you to manually release the GIL, which can be done in several ways: - In C extensions between Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros. - When calling DLL methods using ctypes.cdll or ctypes.windll (not ctypes.pydll). - In a "with nogil:" block in a Cython/Pyrex extension. - With f2py or SWIG, although I have not looked at the details. (I don't use them.) Other things to consider: - Programs that run fast enough run fast enough, even if they only utilize one core. To qoute C.A.R. Hoare and Donald Knuth, "premature optimization is the root of all evil in computer programming." - Psyco, a Python JIT compiler, will often speed up algorithmic code. Using psyco require to change to your code. Try it and see if your programs runs fast enough afterwards. YouTube is rumoured to use psyco to speed ut their Python backend. - Always use NumPy or SciPy if you do numerical work. They make numerical code easier to program. The numerical code also runs a lot faster than a pure python equivalent. - Sometimes Python is faster than your hand-written C. This is particularly the case for Python code that make heavy use of built-in primitives and objects from the standard library. You will spend a lot of time tuning a linked list or dynamic array to match the performance of a Python list. Chances are you'll never come up with a sort as fast as Python's timsort. You'll probably never make your own hash table that can compete with Pythons dictionaries and sets, etc. Even if you can, the benefit will be minute and certainly not worth the effort. - You will get tremendous speedups (often x200 over pure Python) if you can move a computational bottleneck to C, C++, Fortran, Cython, or a third-party library (FFTW, LAPACK, Intel MKL, etc.) - Portions of your Python code that do not constitute important bottlenecks can just be left in Python. You will not gain anything substantial from migrating these parts to C, as other parts of your code dominate. Use a profiler to indentify computational bottlenecks. It will save you a lot of grief fiddling with premature optimizations. That's my fifty cents on Python coding for speed. From paul at boddie.org.uk Mon Sep 29 14:51:15 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 29 Sep 2008 11:51:15 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> Message-ID: On 29 Sep, 19:26, Terry Reedy wrote: > > Please: Python does not have 'lambda functions'. Def statements and > lambda expressions both define instances of the function class. So this > amounts to saying "functions are subject to the same caveats as functions." I myself am aware of the nature of "lambda expressions", for want of a better term, but it's important to emphasise their nature to anyone reading who isn't fully aware of what they represent. My closing paragraph touches on the issues of readability and programmer expectation when I write that 'function definition statements do not behave like, say, "for", "if" or "while" statements'. Although this may seem obvious, a newcomer might overlook lambda expressions in this regard. Personally, I'm not a great enthusiast of closures, anyway. Perhaps I spent too long writing Java to be able to look at them as being anything other than a fairly imprecise way of encapsulating state in a callable. Paul From jinbow at gmail.com Thu Sep 4 12:30:46 2008 From: jinbow at gmail.com (Mars creature) Date: Thu, 4 Sep 2008 09:30:46 -0700 (PDT) Subject: Read Binary data References: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> Message-ID: <3a0d241f-c43b-49f2-a70e-eafad6de49d1@t1g2000pra.googlegroups.com> On Sep 4, 12:03 pm, Fredrik Lundh wrote: > "Mars creature" wrote: > > I am trying to read a binary file created by the following matlab > > command: > > fid=fopen('a.bin','w','b'); fwrite(fid,a,'real*8'); fclose(fid);, and > > wondering how to do it in Python. I googled it but still get > > confused. > > 'b' in fopen is for 'big-endian', 'real*8' in fwrite is for 64bit > > float. > > f = open("a.bin", "rb") # read binary data > s = f.read() # read all bytes into a string > > import array, sys > > a = array.array("f", s) # "f" for float > if sys.byteorder != "big": > a.byteswap() > > Thanks Fredrik! I appreciate it! The only thing is that a = array.array("f", s) should be a = array.array("d", s) as the data is double precision. Thanks again! From prologic at shortcircuit.net.au Mon Sep 22 05:41:46 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 19:41:46 +1000 Subject: What do you call a class not intended to be instantiated In-Reply-To: References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> Message-ID: On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano > But that's precisely what I want to avoid: I don't want the objects to > share *any* state, not even their class. I'm not trying for a Borg or > Singleton: the user can call the factory as many times as they want, but > the objects returned shouldn't share any state. I don't know if what I > want has a name. Judging from people's reactions, I'd say probably not. Snce when are "users" ever involved in programming problems or programming languages ? --JamesMills -- -- -- "Problems are solved by method" From stava at telcotec.se Sat Sep 27 04:05:01 2008 From: stava at telcotec.se (Lars Stavholm) Date: Sat, 27 Sep 2008 10:05:01 +0200 Subject: python for *nix system admins Message-ID: <48DDE92D.6090405@telcotec.se> Hi All, I'm new to this list and hoping that this is not off-topic. If it is, please point me in the right direction. I seem to recollect a python module or library for *nix sysadmins, but I can't for the life of me find it again. The module (or library) somehow added unix command capabilities to the python language. It seemed like a lesser known, perhaps new, python library or module. Any input or ideas appreciated /Lars Stavholm From skip at pobox.com Wed Sep 17 08:09:30 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Sep 2008 07:09:30 -0500 Subject: shelve file space always increase! In-Reply-To: References: Message-ID: <18640.62330.105952.110065@montanaro-dyndns-org.local> smalltalk> the abc.db is always 312k though i have use clear(), how can smalltalk> i shrink the space? You really can't without deleting the file. Hash file implementations trade off file size against improve key lookup performance. Similar tradeoffs are made in the implementation of Python's dictionary and other languages' associative arrays. My Google skills must be lacking this morning. Here's the best I've been able to come up with in the way of explanation: http://en.wikipedia.org/wiki/Associative_array#Efficient_representations Skip From dudeja.rajat at gmail.com Mon Sep 29 12:10:52 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 29 Sep 2008 17:10:52 +0100 Subject: Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars In-Reply-To: References: Message-ID: On Sun, Sep 28, 2008 at 4:51 PM, wrote: > > Hi, > > > Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well > the problem is I'm unable to scroll if I click on the arrows buttons of > scrollbars ( with both types of scrollbars) > > > Please suggest if I m missing some configuration. > > > My code is as below: > > self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL) > self.hsb.grid(row = 2,column = 0, sticky = E+W) > #vertical scroll bar > self.vsb = Scrollbar(appGuiFrame) > self.vsb.grid(row = 1,column = 2, sticky = N+S) > > > > self.txtLogger = Text(appGuiFrame, \ > height = 20,\ > width = 100, \ > state = DISABLED, \ > xscrollcommand = self.hsb.set, \ > yscrollcommand = self.vsb.set, \ > wrap = NONE, \ > font = ("courier",12)) > self.hsb.config(command = self.txtLogger.xview()) > self.vsb.config(command = self.txtLogger.yview()) > > > Please help. > > > Thanks and regards, > Rajat > Hi folks, Any help on the above problem. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From maebert at uos.de Mon Sep 1 04:52:10 2008 From: maebert at uos.de (Manuel Ebert) Date: Mon, 1 Sep 2008 10:52:10 +0200 Subject: Know if a object member is a method In-Reply-To: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Message-ID: <9E7BC2B9-AE15-477D-B8DB-20DD47AFBB79@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Luca, use type(something).__name__ , e.g. >>> def x(): >>> pass >>> class C: >>> pass >>> c = C() >>> type(x).__name__ == 'function' True >> type(C).__name__ == 'classobj' True >> type(c).__name__ == 'instance' True On Sep 1, 2008, at 10:43 AM, Luca wrote: > Hi all. > > I think this is a newbie question... what is the best method to know > if a property of an object is a function? > > I'm thinking something as > > if type(obj.methodName)==??? > > Can someone help me? > > -- > -- luca > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIu606cZ70OCIgLecRAhE6AJ4r0GuHlWxXbLaYuolqpJStYPD+ggCgidKg qtgl+nbaKgH5AoelTu5WeJU= =W4eG -----END PGP SIGNATURE----- From timr at probo.com Fri Sep 26 23:44:28 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 27 Sep 2008 03:44:28 GMT Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> <98e4f068-5349-4b38-b15b-7e2436a0e4a7@f63g2000hsf.googlegroups.com> Message-ID: Mark Dickinson wrote: >On Sep 25, 8:55?am, Tim Roberts wrote: >> Marc 'BlackJack' Rintsch wrote: >> >0.1 actually is >> >> >In [98]: '%.50f' % 0.1 >> >Out[98]: '0.10000000000000000555111512312578270211815834045410' >> >? >> >> .... ?0.1 in an IEEE 784 double is this: >> >> ? ? ?0.100000000000000088817841970012523233890533447265625 > >I get (using Python 2.6): > >>>> n, d = 0.1.as_integer_ratio() >>>> from decimal import Decimal, getcontext >>>> getcontext().prec = 100 >>>> Decimal(n)/Decimal(d) >Decimal('0.1000000000000000055511151231257827021181583404541015625') > >which is a lot closer to Marc's answer. Looks like your float >approximation to 0.1 is 6 ulps out. :-) Yes, foolishness on my part. The hex is 3FB99999_9999999A, so we're looking at 19999_9999999A / 2^56 or 7205759403792794 ------------------- 72057594037927936 which is the number that Marc, Nick, and you all describe. Apologies all around. I actually dropped one 9 the first time around. Adding one more weird data point, here's what I get trying Marc's original sample on my Windows box: C:\tmp>python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> '%.50f' % 0.1 '0.10000000000000001000000000000000000000000000000000' >>> I assume this is the Microsoft C run-time library at work. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From coolman.guron at gmail.com Tue Sep 16 13:03:08 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Tue, 16 Sep 2008 10:03:08 -0700 (PDT) Subject: parse a midi file References: Message-ID: <44f81225-34e1-43de-a1d2-e5e77aed6327@q26g2000prq.googlegroups.com> On Sep 16, 9:48?pm, Mr.SpOOn wrote: > Hi, > I need to parse a midi file with Python. What I exactly need is the > possibility to distinguish all notes in all channels in a midi file > and put them in a list or something. > > I've found this: > > http://groups.google.com/group/alt.sources/msg/22467419ad4bf416 > > I'm not sure how it does work, but looking at the code I saw it can > get input from the terminal, so I tried: > > python midi.py < mymidi.mid > > All it does is printing a lot of strange symbols. > > Do you know other easy way to parse a midi file in Python? Or how > actually does this module work? > > Thanks, > Carlo hi, just looked at the code. try this python midi.py -i mymidi.mid to see all the debug information do python midi.py -p -d -i mymidi.mid From bj_666 at gmx.net Tue Sep 2 18:55:54 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 22:55:54 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> Message-ID: <6i5ujqFol29aU8@mid.uni-berlin.de> On Tue, 02 Sep 2008 18:15:07 -0400, Derek Martin wrote: >> Classes represent "things", and class names should be nouns. > > Is that a law? It's a common guideline. > Classes are instantiated by invoking their class names as a function > call -- the computing equivalent of a verb. Why then, must they be > named as nouns? Can you not, in fact, have classes which describe (or > model) actions? Wouldn't you name them using verbs if you did? Me personally no. I would use `FooAction` instead of `Foo` or something similar. And if they model an action there must be some way to activate the action but the instances of `Popen` are no actions. There's no way to "execute" a `Popen` instance. > That said, this is the most valid point anyone has made... You should > have made it when the module was being designed. :-D > > My point is, if you don't think Popen is a good name for the class, > that's your opinion, but it is only that: an opinion. Like your opinion that it *is* a good name. > Yet some of you state your case as if it is incontrovertable fact. > I've given a good case as to why it IS a good name (one which I > genuinely support), and disagree as you may, none of the points any of > you have made invalidate or even weaken my argument. Maybe from your POV. Facts: It doesn't use the `popen()` function, it gives something more complex than a simple pipe (no obligatory shell, up to three file objects, more attributes and methods), the function used on Windows under the hood is called `CreateProcess()` not `CreatePipe()`. `Popen` creates a process and represents a proxy object to communicate with it, so `Process` is a good name for that concept/"thing". It's a way more self explaining name, even for people who know the `popen()` function because there's a concept called "process" but none called "popen". Ciao, Marc 'BlackJack' Rintsch From lie.1296 at gmail.com Tue Sep 30 15:30:55 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 30 Sep 2008 19:30:55 +0000 (UTC) Subject: [Tutor] Replacing cmd.exe with custom .py application References: Message-ID: On Tue, 30 Sep 2008 15:09:06 -0400, Ezra Taylor wrote: > Is there something similar to /dev/null on Windows? I think it's called nul REM This is a batch file (.bat) echo "This won't show" > NUL I'm not sure how to use it in python though. From dudeja.rajat at gmail.com Tue Sep 9 19:32:27 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 9 Sep 2008 19:32:27 -0400 Subject: Looking for a Duo - file comparison and a file parser Message-ID: HI, I'm thinking of writing a file comparison utility in python. This utility will work as: 1. Compare 2 files for the differences. Both files contain some numerical results. 2. Generate a common file containing the differences (the same way as 'diff' generate an output) 3. Now, I will parse this file containing differences to check as to how much is the difference of one file from other. So, for this I hope a parser will be required. Is there a utility available that performs similar job ( that some one might have created considering the huge number of users of python) ? Or may be some one has written some parser? Any help is greatly appreciated. Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at subtlety.com Mon Sep 8 02:56:05 2008 From: chris at subtlety.com (catsclaw) Date: Sun, 7 Sep 2008 23:56:05 -0700 (PDT) Subject: How do I set a callback in Python? Message-ID: I can't for the life of me figure out how to set a callback in Python. I have a class, which wraps another class. The second class needs a callback assigned. I don't want to use globals for it. Here's what I'd like to do: class MyWrapper: def get_login(self, username): return self.user, self.pass def __init__(self, user, pass): self.user = user self.pass = pass self.client = Client("connection string") self.client.callback_login = get_login ... but obviously, the Client class, when it calls the callback, doesn't pass a reference to the "self" object. How do I do this? -- Chris From exarkun at divmod.com Sun Sep 28 16:07:19 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 28 Sep 2008 16:07:19 -0400 Subject: standalone buildbot possible/ don't have a remote In-Reply-To: <41a76fd8-47e3-4eb8-b980-11baf8dff0b2@u65g2000hsc.googlegroups.com> Message-ID: <20080928200719.29191.972487259.divmod.quotient.31462@ohm> On Sun, 28 Sep 2008 12:15:50 -0700 (PDT), mark wrote: >I want to start small and setup a buildbot on one machine (no slaves). >I hope this is possible. I assume I only need one master in this case >(without slave config)??? > >from my master.cfg >c['slaves'] = [] > >... (rest of the sample config) > >b1 = {'name': "buildbot-full", ># 'slavename': "bot1name", > 'builddir': "full", > 'factory': f1, > } > >Do I need some configuration that the builder uses the master >instance? I experimented a bit and searched for a similar >configuration so far without success :-(( > No, you have to have a slave. It can run on the same machine, it can run as the same user, but it has to exist. The buildmaster can only tell slaves to do work (of course, this is all written in Python, so it is a simple matter of programming to *make* the buildmaster capable of doing the slave's job, but there's not really any reason to try to do this). Jean-Paul From jbarciela at gmail.com Mon Sep 15 12:53:43 2008 From: jbarciela at gmail.com (Jaime Barciela) Date: Mon, 15 Sep 2008 09:53:43 -0700 (PDT) Subject: component / event based web framework for python? Message-ID: Hello all, I've been surveying the field of python web frameworks for a while but there are just too many so I ask mighty Usenet. Is there a component / event based web framework for python? Something that can abstract you from the request/response mechanism and ideally from html and javascript altogether? As examples -- in other languages -- of what I have in mind: - in java: wingS, GWT, echo (2,3), karora, thinwire, itmill, and maybe others - in javascript: cappuccino - in lisp: weblocks - in smalltalk: seaside, aida/web - in .net: asp.net I would like to be able to write code equivalent to this C# example: ============ namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button b = new Button(); b.Text = "say hello"; b.Click += Button1_Click; Panel1.Controls.Add(b); } protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "Hello dynamically created on the fly UI !!!"; } } } ============ Thanks Jaime From d3vvnull at gmail.com Fri Sep 26 15:04:35 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 14:04:35 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <20080926123848.98c06cd5.darcy@druid.net> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> Message-ID: <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Doesn't it depend on where and why you intend to execute the code? Obviously some SQL is more at risk for exploit when the input is from the screen on a web page than if you were running parameterized code in a controlled batch environment. Or if you were writing code generators (which is what I happen to do) which won't be run by the general public. Incidentally, couldn't input field edits prevent such exploits prior to interpolation? On Fri, Sep 26, 2008 at 11:38 AM, D'Arcy J.M. Cain wrote: > On Fri, 26 Sep 2008 11:00:59 -0500 > "Michael Mabin" wrote: > > So we can drop a table in an in clause? How is this a use case. > Cartoons > > are funny but actual proof that this example using an in-clause provides > an > > exploit would be more helpful I think. > > I'm not sure what proof you require. If you program such that users > can enter arbitrary stings into your database it is obvious that the > exploit in that cartoon can be used against you. And the point is that > it has nothing to do with IN clauses. It can be any SQL. Go read that > cartoon carefully. It says nothing about IN clauses. Consider; > > "UPDATE student SET name = '%s' WHERE student_id = %s" % (name, id); > > Now set name to "Robert'; DROP TABLE student;" and see what happens if > you feed that to your SQL database. Hell, just put "';" in the string > for fun. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Sep 12 11:52:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 17:52:50 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <20080912111949.19629e78.darcy@druid.net> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> <20080912111949.19629e78.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > Is there ever any advantage to having something as a builtin rather > than as a regular user method? What difference does it make to the > running script? I can see that adding "bar" from module "foo" to > "__builtins__" means that you can use "bar()" instead of "foo.bar()". > Is that the only benefit? basically, yes. in this case, it does make some sense to patch any/all into __builtin__, since they are builtins in a later version. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 15 08:10:04 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 15 Sep 2008 14:10:04 +0200 Subject: Abstract class (irrelevant blethering) In-Reply-To: References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <48CD62B8.7070708@islandtraining.com> Message-ID: <48ce509b$0$14427$426a74cc@news.free.fr> Stephen Horne a ?crit : (snip) > For example, to me the term "property" is basically a trivial design > pattern or an object-oriented principle. I don't really see the need > for the language feature. I can define getter and setter methods all > by myself, and I don't really see the benefit of disguising them as > member variables. The canonical use case for computed attributes is that they let you turn a plain attribute into a computed one if/when the need arises, without breaking client code *nor* having to force all access attributes thru getters/setters righ from the start "just in case". From aacyair at netvision.net.il Mon Sep 1 03:22:06 2008 From: aacyair at netvision.net.il (Michaeli Yair) Date: Mon, 1 Sep 2008 10:22:06 +0300 Subject: file->Grid->file Message-ID: Hi all, I imported a comma seperated data to PyGridTableBase which is a abstract Grid, I parse and display the information. After update i want to save it back to the comma seperated file, eith the same filename. any suggestions how to do that ? do you know any reference to this subject ? YM From fredrik at pythonware.com Sat Sep 6 07:11:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Sep 2008 13:11:04 +0200 Subject: Cancel instance create In-Reply-To: <1220697080.48c25bf890ade@www.inbox.lv> References: <1220697080.48c25bf890ade@www.inbox.lv> Message-ID: Aigars Aigars wrote: > I want MyClass to perform some tests and if them fail, I do not want > instance to be created. > > But in code I wrote instance is created and also has parameters, that it > should not have in case of tests failure. > > Is there a way to perform tests in MyClass.__init__ and set instance to > None without any parameters? if you want construction to fail, raise an exception. ... def __init__(self): self.param = "spam" Test = False if Test: # please don't use explicit tests for truth print "Creating instance..." else: raise ValueError("some condition failed") (pick an exception class that matches the actual error, or create your own class if necessary) From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 04:09:06 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Tue, 16 Sep 2008 01:09:06 -0700 Subject: Cross-platform socket.getsockopt and struct.unpack (or socket timeout)? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Heikki Toivonen wrote: > >> Is there a cross-platform way of doing what the M2Crypto code is >> attempting to do? > > calling the socket object's settimeout() method? I would suspect that is not strictly equivalent to what the old code is doing, though, because it seems you can set read and write timeouts separately using the socket options directly. -- Heikki Toivonen From support.desk.ipg at gmail.com Wed Sep 24 12:25:02 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Wed, 24 Sep 2008 11:25:02 -0500 Subject: More regex help In-Reply-To: References: Message-ID: <2F273EFF4B21468A85BE4277DA844C75@office.ipglobal.net> I am working on a python webcrawler, that will extract all links from an html page, and add them to a queue, The problem I am having is building absolute links from relative links, as there are so many different types of relative links. If I just append the relative links to the current url, some websites will send it into a never-ending loop. What I am looking for is a regexp that will extract the root url from any url string I pass to it, such as 'http://example.com/stuff/stuff/morestuff/index.html' Regexp = http:example.com 'http://anotherexample.com/stuff/index.php Regexp = 'http://anotherexample.com/ 'http://example.com/stuff/stuff/ Regext = 'http://example.com' From invalid at invalid Wed Sep 17 12:48:27 2008 From: invalid at invalid (Grant Edwards) Date: Wed, 17 Sep 2008 11:48:27 -0500 Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> Message-ID: On 2008-09-17, r0g wrote: > r0g at steppa:~/Desktop/py$ ls > kickstart.py kickstart.py~ kicktest.py kicktest.py~ > r0g at steppa:~/Desktop/py$ kickstart.py > bash: kickstart.py: command not found > > Any ideas why this might be? Yes. > A path thing? Yes. Linux systems generally don't have the current directory in the PATH that's searched for executbles (it's regarded as a rather serious security problem if you do). Try doing this: ./kickstart.py -- Grant Edwards grante Yow! Look into my eyes and at try to forget that you have visi.com a Macy's charge card! From bdesth.quelquechose at free.quelquepart.fr Thu Sep 18 14:16:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 18 Sep 2008 20:16:25 +0200 Subject: improving a huge double-for cycle In-Reply-To: <4f55d49g9086nhob3ol67uahbr19o1hjiu@4ax.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <4f55d49g9086nhob3ol67uahbr19o1hjiu@4ax.com> Message-ID: <48d2b6e7$0$3789$426a74cc@news.free.fr> Harald Luessen a ?crit : (snip) > I did not test the syntax, > but here is an idea with sorted lists. > It should be O(NlogN). > > def sk(x): > return x.coordinates[0] > > IN.sort(key=sk) > for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > else: > break The syntax is ok. Not the results, or so it seems (cf my other post in this thread). But you still get a good point for noticing the redundant tests in the inner loop !-) From bearophileHUGS at lycos.com Mon Sep 8 10:01:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 8 Sep 2008 07:01:19 -0700 (PDT) Subject: Dictionaries and loops References: <48c52c54$0$16982$426a74cc@news.free.fr> Message-ID: <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> Bruno Desthuilliers: > This doesn't look like a CSV file at all... Is that what you actually > have in the file, or what you get from the csv.reader ??? I presume you are right, the file probably doesn't contain that stuff like I have assumed in my silly/useless solutions :-) Bye, bearophile From __peter__ at web.de Wed Sep 3 03:15:17 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2008 09:15:17 +0200 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: hofer wrote: > Something I have to do very often is filtering / transforming line > based file contents and storing the result in an array or a > dictionary. > > Very often the functionallity exists already in form of a shell script > with sed / awk / grep , . . . > and I would like to have the same implementation in my script > > What's a compact, efficient (no intermediate arrays generated / > regexps compiled only once) way in python > for such kind of 'pipe line' > > Example 1 (in bash): (annotated with comment (thus not working) if > copied / pasted > cat file \ ### read from file > | sed 's/\.\..*//' \ ### remove '//' comments > | sed 's/#.*//' \ ### remove '#' comments > | grep -v '^\s*$' \ ### get rid of empty lines > | awk '{ print $1 + $2 " " $2 }' \ ### knowing, that all remaining > lines contain always at least > \ ### two integers calculate > sum and 'keep' second number > | grep '^42 ' ### keep lines for which sum is 42 > | awk '{ print $2 }' ### print number > thanks in advance for any suggestions of how to code this (keeping the > comments) for line in open("file"): # read from file try: a, b = map(int, line.split(None, 2)[:2]) # remove extra columns, # convert to integer except ValueError: pass # remove comments, get rid of empty lines, # skip lines with less than two integers else: # line did start with two integers if a + b == 42: # keep lines for which the sum is 42 print b # print number The hard part was keeping the comments ;) Without them it looks better: import sys for line in sys.stdin: try: a, b = map(int, line.split(None, 2)[:2]) except ValueError: pass else: if a + b == 42: print b Peter From mccredie at gmail.com Tue Sep 30 19:26:43 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 30 Sep 2008 16:26:43 -0700 (PDT) Subject: Wait or not? References: <34809165-9c72-46b3-996c-4bd55451505d@e53g2000hsa.googlegroups.com> Message-ID: On Sep 30, 4:20?pm, Eric wrote: > I've been wanting to learn Python for a while now but I can't decide > on whether to wait for Python 3's final release and learn it or just > go ahead and learn 2.x. Would it be hard to make the transition being > a noob? It shouldn't be a hard transition. I would recommend learning 2.x anyway. You are likely to want to use 3rd party modules (or you will anyway). You won't want to wait for module support to be added in 3.0. The 2.x series isn't going to go away for quite a while. I think they are planning to continue to do releases all the way up to 2.9 or so. Even then, the biggest thing that a new user is going to run into is `print("stuff")` vs. `print "stuff"`. Matt From steve at REMOVE-THIS-cybersource.com.au Thu Sep 18 09:11:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 13:11:07 GMT Subject: PEP proposal optparse References: Message-ID: <00e24d6e$0$20331$c3e8da3@news.astraweb.com> On Thu, 18 Sep 2008 03:37:54 -0700, James wrote: > Hi, > > I would like to know your thoughts on a proposed change to optparse that > I have planned. It is possible to add default values to multiple options > using the set_defaults. However, when adding descriptions to options the > developer has to specify it in each add_option() call. This results in > unreadable code such as: [snip] I don't find it unreadable at all. I find it very helpful to have the help text associated right there with the rest of the option, instead of hidden in a different function call. [...] > Help descriptions can often be quite long and separating them in this > fashion would, IMHO, be desirable. If the help descriptions are so long that they are a problem, then the solution I would choose is to put them in their own module, then do something like this: import docs parser.add_option('-q', '--quiet', action="store_false", dest='verbose', help=docs.quiet) parser.add_option('-o', '--output', type='string', dest='castordir', metavar='
', help=docs.output) etc. -- Steven From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 17 10:08:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 17 Sep 2008 16:08:57 +0200 Subject: Python OOP advice In-Reply-To: <87fxnz3q5i.fsf@benfinney.id.au> References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> <87fxnz3q5i.fsf@benfinney.id.au> Message-ID: <48d10f78$0$9484$426a34cc@news.free.fr> Ben Finney a ?crit : > Simon Hibbs writes: > >> Orriginaly I thought I'd need to have a hull object which contains >> component objects, but the component objects need access to members >> of the hull object (e.g. the hull size) so that looks messy to >> implement. > > Was it as messy as this:: > > class ShipHull(object): > def __init__(self, size): > self.components = dict() > self.size = size > > class ShipComponent(object): > def __init__(self, name, hull): > self.name = name > self.hull = hull > >> I have defined a base class Component with a class member variable >> 'hull_size' so that all components can see the hull size. > > It seems to me the hull is an attribute of the component, and the size > is an attribute of the hull. Why would the hull size be a *class* > attribute? > >> I've then got two child classes called Fixed_Component and Percent >> _Component that implement their mass, mass_percent and cost >> properties appropriately for their type. > > class FixedShipComponent(ShipComponent): > def _get_mass(self): > return calculation_foo(self.hull.size) > mass = property(_get_mass) > > def _get_cost(self): > return calculation_bar(self.hull.size) > cost = property(_get_cost) > > class PercentShipComponent(ShipComponent): > def _get_mass(self): > return calculation_spam(self.hull.size) > mass = property(_get_mass) > > def _get_cost(self): > return calculation_eggs(self.hull.size) > cost = property(_get_cost) Or use the strategy pattern (dummy example, don't have time to read your specs !-): class FixedMassCostStrategy(object): def get_mass(self, hull): return calculation_foo(hull.size) def get_cost(self): return calculation_bar(hull.size) class PercentMassCostStrategy(object): def get_mass(self, hull): return calculation_spam(hull.size) def get_cost(self): return calculation_eggs(hull.size) class ShipComponent(object): def __init__(self, name, hull, masscost_strategy): self.name = name self._hull = hull # implementation detail self._strategy = masscost_strategy mass = property(lambda self: self._strategy.get_mass(self._hull)) cost = property(lambda self: self._strategy.get_cost(self._hull)) From hussainsaiger at gmail.com Tue Sep 2 10:40:59 2008 From: hussainsaiger at gmail.com (hussainsaiger at gmail.com) Date: Tue, 2 Sep 2008 07:40:59 -0700 (PDT) Subject: Using NLTK in Java References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> <6i1hu9FnvcngU1@mid.uni-berlin.de> <6i21jaFomilbU1@mid.uni-berlin.de> Message-ID: On 1 Sep, 16:21, "Diez B. Roggisch" wrote: > hussainsai... at gmail.com wrote: > > On 1 Sep, 11:55, "Diez B. Roggisch" wrote: > >> hussainsai... at gmail.com schrieb: > > >> > I am trying to convert a python module (that contains the use of > >> > NLTK.Corpus) by jythonc. It is not able to include nltk dependencies > >> > within the java class it creates. So when i use this class in java, it > >> > fails to recognize nltk. Can anyone please let me know how should i > >> > use nltk in python/jython modules so i can use in Java. > > >> If there are any binary dependencies, you are out of luck. It won't > >> work. You would need to write a RPC-Server then, with technologies such > >> as XMLRPC or CORBA. > > >> Diez > > > So does that mean that Jython does not support nltk uptil now. I ask > > this because when I try to import nltk in Jython (which is assumed to > > replace Python), i get the same error. Its just nltk that I am not > > able to use. The rest of the jython functions and libraries work fine > > within Java. > > I don't know for sure - how about you post the error-message? Otherwise we > can't assess the problem. > > Diez- Hide quoted text - > > - Show quoted text - Hi, What i did was create a python file as: import nltk from java.util import Random class NLPPresentation(Random): def nextDouble(self): return 1 def TagByBrown(self,sent): "@sig public String[] TagByBrown(String sent)" brown_a = nltk.corpus.brown.tagged_sents(categories='a') bigram_tagger = nltk.BigramTagger(brown_a, cutoff=0) lst = bigram_tagger.tag(sent.split()) return lst I processed the following code through jythonc compiler to form a JAR file. I then imported this jar file into java ide (Java Builder). I then wrote the following program in java to access this python class: import org.python.core.PyException; import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.util.PythonInterpreter; import java.util.Random; import org.nltk.*; import org.nltk.mallet.*; public class SimpleEmbedded extends NLPPresentation{ public static void main(String[] args) throws PyException { SimpleEmbedded so = new SimpleEmbedded(); String s = "he is a boy"; so.Call(s); } public void Call(String s) { String[] arr = TagByBrown(s); System.out.println(arr[1]); } } When i compile the above java code, i get the following error: Exception in thread "main" Traceback (innermost last): File "C:\jython2.2.1\NLPPresentation.py", line 0, in main ImportError: no module named nltk Your comments are highly appreciated. From uzmanajmal at gmail.com Wed Sep 17 05:05:41 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Wed, 17 Sep 2008 09:05:41 +0000 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: <3f0d61c40809150606w2b8035b3v2eba46e44cdee9a7@mail.gmail.com> References: <3f0d61c40809150606w2b8035b3v2eba46e44cdee9a7@mail.gmail.com> Message-ID: Actually my problem is a little different. I have a .pem format file which contain my public and private key both and i want to get only the public key from that file as a string. I already have done that by just parsing the said file but if there is some direct way i will b glad to know. @marco i don't have the string at all. Infact i want the string @Toivonen i tried as_pem but it gives me some private key after doing some thing with the file i pass to it as argument which is even not the private key i have in my file. Also if i set cipher=None, even then its result is same Thanks by the way marco and Toivonen for trying to help :) On Mon, Sep 15, 2008 at 1:06 PM, Marco Bizzarri wrote: > On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal wrote: > > Hi, > > > > I have a M2Crypto.RSA.RSA instance that contain my public-key. I want > that > > key as string. Is there any way to convert the said instance into string? > > > In case you want to write the pub-key to a file, you can use save_pub_key > > def save_pub_key(self, file): > """ > Save the public key to a file in PEM format. > > @type file: string > @param file: Name of file to save key to. > """ > > Regards > Marco > -- > Marco Bizzarri > http://notenotturne.blogspot.com/ > http://iliveinpisa.blogspot.com/ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Fri Sep 12 04:23:50 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 09:23:50 +0100 Subject: rss feed generation In-Reply-To: <48CA217A.60708@timgolden.me.uk> References: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> <32cabba0809111835g2984c463y2c4b689605f8362e@mail.gmail.com> <48CA217A.60708@timgolden.me.uk> Message-ID: <48CA2716.2070608@timgolden.me.uk> Tim Golden wrote: > Walter Cruz wrote: >> On Tue, Sep 9, 2008 at 9:35 PM, alex23 wrote: >>> On Sep 10, 7:30 am, "Blake Garner" wrote: >>>> I'm looking for suggestions on how to approach generating rss feed >>>> .xml files using python. What modules to people recommend I start >>>> with? > > I just rolled something with ElementTree. No idea how it > stacks up against validity checks, but it seems to be > accepted by a couple of standard feed readers. [... snip messy code ...] Well that didn't come out very well. If anyone's interested, I've dropped the module here: http://timgolden.me.uk/python/downloads/feeder.py TJG From deets at nospam.web.de Mon Sep 15 13:23:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 19:23:24 +0200 Subject: component / event based web framework for python? In-Reply-To: References: Message-ID: <6j7k0cF1sf3lU1@mid.uni-berlin.de> Jaime Barciela schrieb: > Hello all, > > I've been surveying the field of python web frameworks for a while but > there are just too many so I ask mighty Usenet. > > Is there a component / event based web framework for python? Something > that can abstract you from the request/response mechanism and ideally > from html and javascript altogether? You might consider taking a look at tosca-widgets, which are used to create re-usable components of javascript, css and html. They can be used in any WSGI-capable environment, but TurboGears and Pylons are best known for incorporating them. http://toscawidgets.org/documentation/ Diez From kay.schluehr at gmx.net Fri Sep 26 04:30:51 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 26 Sep 2008 01:30:51 -0700 (PDT) Subject: How to read a jpg bytearray from a Flash AS3 file References: Message-ID: <8ad152c7-606b-4a68-aba2-c8dccc0e8b8a@b1g2000hsg.googlegroups.com> On 26 Sep., 08:47, rsgallo... at gmail.com wrote: > I'm trying to save an image from a Flash AS3 to my server as a jpg > file. I found some PHP code to do this, but I want to do this in > Python. I'd expect you use AS3 to save the image file ( just looking at Adobes AS3 docs on how this works ) and load it with PIL if you want to post- process it in Python: http://www.pythonware.com/products/pil/ From lekin2 at llnl.gov Thu Sep 18 13:07:11 2008 From: lekin2 at llnl.gov (April Lekin) Date: Thu, 18 Sep 2008 10:07:11 -0700 Subject: Tkinter Bold Text Message-ID: <76vncf$1ajav3@smtp.llnl.gov> Is there any way to highlight, bold or change the color of one word in a variable to be displayed on a Tkinter GUI? Like: material = "Plastic" introVal = "This report describes the construction of the %s." % (material) this is what I want: This report describes the construction of the Plastic. Plastic is Bold or Blue or Green Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From brianlong at cox.net Mon Sep 8 13:07:25 2008 From: brianlong at cox.net (brianrpsgt1) Date: Mon, 8 Sep 2008 10:07:25 -0700 (PDT) Subject: Problems downloading and installing win32api Message-ID: <968dca58-0172-4953-b8d6-9610f0570fe8@s20g2000prd.googlegroups.com> I have attempted downloading and installing several different version of the win32api from Source Forge, however, each time I try to install I get the following error message: "Only part of a ReadProcessMemory or WriteProcessMemory request was completed" This occurred with the following files: pywin32-212.win32-py2.4.exe pywin32-212.win32-py2.5.exe pywin32-212.win32-py2.6.exe I am using WinXP SP2. Any assistance on getting this downloaded and installed would be great. Thanks B From stefan_ml at behnel.de Thu Sep 4 13:59:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 04 Sep 2008 19:59:13 +0200 Subject: Xpath for HTML processing In-Reply-To: References: Message-ID: <48c021f1$0$19233$9b4e6d93@newsspool4.arcor-online.net> Astley Le Jasper wrote: > Can anyone suggest something inthat can process an XPath like the > following: > > "/html/body/table[2]/tbody/tr/td[5]/table/tbody/tr[3]/td/table[3]/ > tbody/tr[5]/td" [skipping the obvious joke answer to your question] In case you're asking for a tool that can process HTML using XPath, try lxml.html. http://codespeak.net/lxml Stefan From paulprobert at sbcglobal.net Sat Sep 6 20:55:50 2008 From: paulprobert at sbcglobal.net (Paul Probert) Date: Sat, 06 Sep 2008 19:55:50 -0500 Subject: wxPython problem In-Reply-To: References: <48C24D3C.7060306@gmail.com> Message-ID: Peter Anderson wrote: > Stef Mientki said: In PyScripter, you should run wxPython in the plain > remote machine (not the wxPython remote),and you should set "reset > before run flag" or reset the remote machine each time yourself. > > Stef, > > Thanks for the help! It has taken several hours to find and install the > correct version of Rpyc (which is required to run the remote Python > engine but it now seems to be working fine. And the "Reinitialise the > Python engine {Alt]+[F2]" does need to be done between script runs. > Given all that, the script now runs multiple times in PyScripter. The > script still only runs ONCE in IDLE but I can live with that. > > In case others find this message from a search; I am using Python 2.5.2 > and it requires rpyc-2.60.zip from the Rpyc download page (see > http://rpyc.wikispaces.com/ click on the "Download" link and make sure > you select the "main" link under the "Packages" column at Sourceforge. > You will be shown a list of Rpyc versions. For Python 2.5.2 choose > Relese "2.60". This will save you the several hours its cost me. > > Thanks again Stef. > > Regards, > Peter wxPython never runs well in a program running under Tk, such as IDLE. Something about competing GUI's. If you want a replacement, you can try pycrust or one of its brethren, which ship with wxpython. Paul Probert From jlnicolson at gmail.com Thu Sep 18 07:02:07 2008 From: jlnicolson at gmail.com (James Nicolson) Date: Thu, 18 Sep 2008 13:02:07 +0200 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: Perhaps it is better to keep descriptions short and store longer descriptions elsewhere, but there are many programs that have long descriptions, for example try: ls --help (at least on my machine a lot of these descriptions are quite long). 2008/9/18 James Mills : > Hi James, > > I can't say I really agree with your > proposal. I tend to keep the help > descriptions of my options short > and concise and to the point. > > Also, one must use the language's > features (indentation) to your advantage, > as doing so ensure readability. > > For example (from my bhimport tool): > > > def parse_options(): > """parse_options() -> opts, args > > Parse any command-line options given returning both > the parsed options and arguments. > """ > > parser = optparse.OptionParser(usage=USAGE, version=VERSION) > > parser.add_option("", "--date-format", > action="store",type="str", default="%d/%m/%Y", > dest="dateFormat", > help="date format string") > parser.add_option("", "--time-format", > action="store", type="str", default="%H:%M:%S", > dest="timeFormat", > help="time format string") > parser.add_option("", "--datetime-format", > action="store", type="str", default="%H:%M:%S %d/%m/%Y", > dest="datetimeFormat", > help="datetime format string") > > opts, args = parser.parse_args() > > if len(args) < 2: > parser.print_help() > raise SystemExit, 1 > > return opts, args > > > As you can see (as long as you're > reading this in fixed-width fonts) > it _is_ very readable. > > cheers > James > > On 9/18/08, James wrote: >> Hi, >> >> I would like to know your thoughts on a proposed change to optparse >> that I have planned. It is possible to add default values to multiple >> options using the set_defaults. However, when adding descriptions to >> options the developer has to specify it in each add_option() call. >> This results in unreadable code such as: >> >> parser.add_option('-q', '--quiet' , action="store_false", >> dest='verbose', >> help = 'Output less information') >> parser.add_option('-o', '--output' , type='string', >> dest='castordir' , metavar='' , >> help = 'specify the wanted CASTOR directory where to store the >> results tarball') >> parser.add_option('-r', '--prevrel' , type='string', >> dest='previousrel' , metavar='' , >> help = 'Top level dir of previous release for regression >> analysis' ) >> >> The same code could become much more readable if there was an >> equivalent method of set_defaults for the description/help of the >> option. The same code could then become: >> >> parser.set_description( >> verbose = 'Output less information', >> castordir = 'specify the wanted CASTOR directory where >> to store the results tarball', >> previousrel = 'Top level dir of previous release for >> regression analysis') >> >> parser.add_option('-q', '--quiet' , action="store_false", >> dest='verbose') >> parser.add_option('-o', '--output' , type='string', >> dest='castordir' , metavar='' ) >> parser.add_option('-r', '--prevrel' , type='string', >> dest='previousrel' , metavar='' ) >> >> Help descriptions can often be quite long and separating them in this >> fashion would, IMHO, be desirable. >> >> Kind Regards, >> James Nicolson >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > -- > -- "Problems are solved by method" > From harish.shastry at gmail.com Mon Sep 15 06:06:55 2008 From: harish.shastry at gmail.com (Harish K Vishwanath) Date: Mon, 15 Sep 2008 15:36:55 +0530 Subject: When do I get "multiple bases have instance lay-out conflict" error? Message-ID: <78f8019c0809150306t47090464vaeed3b356e76ab5b@mail.gmail.com> Hello all, When do we actually see the error : TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict I searched the web and I could not find a correct guideline as to when such an error could arise. One of the places said that "A new style class cannot inherit from more than one python built-in class". That is., >>> class A(dict,list): ... pass wouldn't work. But, I have an instance where I am getting the above error even when I dont inherit from multiple built-in types. >>> sys.__version__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__version__' >>> sys.version '2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]' Using Py 2.5.2 >>> import persistent >>> persistent.Persistent.__bases__ (,) Persistent is ZOPE/ZODB implementation. It inherits no built-in types >>> Exception.__bases__ (,) >>> BaseException.__bases__ (,) Exception also inherits no built-in types. >>> class A(Exception,persistent.Persistent): ... pass ... Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict Still declaration of class A fails. Any idea? What is the exact rule when python throws up " multiple bases have instance lay-out conflict" error? Thanks in advance for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Sep 11 05:08:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 11:08:50 +0200 Subject: Adding environment variables to bash. In-Reply-To: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> Message-ID: aditya shukla wrote: > Can i add any environment variable to bash from my python script? so > that when i use env command then i can see that environment variable. not if you run the script from the shell. when a process starts, it gets a *copy* of the parent's environment. it can modify that copy, but it cannot modify the variables in the parent. From sh006d3592 at blueyonder.co.uk Sat Sep 20 22:23:14 2008 From: sh006d3592 at blueyonder.co.uk (Stephen Horne) Date: Sun, 21 Sep 2008 03:23:14 +0100 Subject: explain slice assignment to newb References: Message-ID: <5lbbd41dq0tuot2tdkrmgjvbldb72n1rsf@4ax.com> On Sat, 20 Sep 2008 14:20:20 -0700 (PDT), Andrew wrote: >please explain this behavior to a newb: > >>>> a = [1,2,3,4] >>>> b = ["a","b","c","d"] >>>> a[0:2] = b[0:2] The slice [0:2] represent positions 0 <= x < 2 Replaces the [1, 2] from [1, 2, 3, 4] with ['a', 'b'] Result: a = ['a', 'b', 3, 4] >>>> b[2:4] = a[2:4] The slice [2:4] represent positions 2 <= x < 4 Replaces the ['c', 'd'] from ['a', 'b', 'c', 'd'] with [3, 4] Result: b = ['a', 'b', 3, 4] >>>> a >['a', 'b', 3, 4] >>>> b >['a', 'b', 3, 4] Correct From steve at holdenweb.com Mon Sep 29 13:34:41 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 13:34:41 -0400 Subject: os.path.exists() function does not work for http paths In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > Hi, > > I have used os.path.exists() many a times for any file system paths in > local system. But this does not seem to work for an Http path. > > e.g: > > > To check is the Results folder exists at the following path, I do: > > > if not os.path.exists("http://subversion.myCom.com/Testing/Results"): > print 'Path does not exist' > > > This always prints the above print statements whether or not the Results > folder exists or not. > > Is there any such function to check existence of files. / folder at Http > paths? > You could use one of the URL libraries. The os.path module is for dealing with the local filesystem. The absence of any exception from f = urllib.urlopen("http://www.google.com/webhp/") is a good indication that the addressed page "exists" (but remember that the web is a virtual address space, so it doesn't necessarily mean that there's a real file or directory object behind ot). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From simon at mullis.co.uk Thu Sep 18 11:56:08 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Thu, 18 Sep 2008 17:56:08 +0200 Subject: dict generator question In-Reply-To: References: Message-ID: <23d7e1bb0809180856l5ca1409bx929690a4b749f942@mail.gmail.com> Haha! Thanks for all of the suggestions... (I love this list!) SM 2008/9/18 : > On Sep 18, 10:54 am, "Simon Mullis" wrote: >> Hi, >> >> Let's say I have an arbitrary list of minor software versions of an >> imaginary software product: >> >> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] >> >> I'd like to create a dict with major_version : count. >> >> (So, in this case: >> >> dict_of_counts = { "1.1" : "1", >> "1.2" : "2", >> "1.3" : "2" } >> >> Something like: >> >> dict_of_counts = dict([(v[0:3], "count") for v in l]) >> >> I can't seem to figure out how to get "count", as I cannot do x += 1 >> or x++ as x may or may not yet exist, and I haven't found a way to >> create default values. >> >> I'm most probably not thinking pythonically enough... (I know I could >> do this pretty easily with a couple more lines, but I'd like to >> understand if there's a way to use a dict generator for this). >> >> Thanks in advance >> >> SM >> >> -- >> Simon Mullis > > Considering 3 identical "simultpost" solutions I'd say: > "one obvious way to do it" FTW :-) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Simon Mullis _________________ simon at mullis.co.uk From jlnicolson at gmail.com Thu Sep 18 06:37:54 2008 From: jlnicolson at gmail.com (James) Date: Thu, 18 Sep 2008 03:37:54 -0700 (PDT) Subject: PEP proposal optparse Message-ID: Hi, I would like to know your thoughts on a proposed change to optparse that I have planned. It is possible to add default values to multiple options using the set_defaults. However, when adding descriptions to options the developer has to specify it in each add_option() call. This results in unreadable code such as: parser.add_option('-q', '--quiet' , action="store_false", dest='verbose', help = 'Output less information') parser.add_option('-o', '--output' , type='string', dest='castordir' , metavar='' , help = 'specify the wanted CASTOR directory where to store the results tarball') parser.add_option('-r', '--prevrel' , type='string', dest='previousrel' , metavar='' , help = 'Top level dir of previous release for regression analysis' ) The same code could become much more readable if there was an equivalent method of set_defaults for the description/help of the option. The same code could then become: parser.set_description( verbose = 'Output less information', castordir = 'specify the wanted CASTOR directory where to store the results tarball', previousrel = 'Top level dir of previous release for regression analysis') parser.add_option('-q', '--quiet' , action="store_false", dest='verbose') parser.add_option('-o', '--output' , type='string', dest='castordir' , metavar='' ) parser.add_option('-r', '--prevrel' , type='string', dest='previousrel' , metavar='' ) Help descriptions can often be quite long and separating them in this fashion would, IMHO, be desirable. Kind Regards, James Nicolson From dthole at gmail.com Tue Sep 9 14:55:47 2008 From: dthole at gmail.com (David Thole) Date: Tue, 9 Sep 2008 11:55:47 -0700 (PDT) Subject: How to record audio from Python on Mac? References: Message-ID: <74b0be47-d2c4-4003-a734-35ff9813ef90@l43g2000hsh.googlegroups.com> On Sep 9, 1:11?pm, Kevin Walzer wrote: > s... at pobox.com wrote: > > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > > casting a broader net.) > > > Can I easily control audio record/playback from Python on my Mac? ?I know > > zip about audio recording or about Apple APIs via Python. ?Pointers to > > simple examples would be much appreciated. > > > Thanks, > > > Skip > > You can probably access this functionality via PyObjC--it provides > access to the Cocoa frameworks. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Another option you could use is calling Applescript from the command line, to open, execute, and handle audio. An easy example of this is with iTunes actually. Once you get iTunes down, doing this for other apps should be easy (if they have applescript bindings): http://www.macosxhints.com/article.php?story=20011108211802830 You could probably also do what Kevin recommends, but depending on your needs, this may be a whole lot more simple. -David Thole http://www.thedarktrumpet.com From m_palmer45 at yahoo.ca Mon Sep 15 19:37:29 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 15 Sep 2008 16:37:29 -0700 (PDT) Subject: Parallelising code References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: <35652fcc-cc31-4e53-8069-6a696cdd0591@z66g2000hsc.googlegroups.com> On Sep 15, 12:46 pm, "psaff... at googlemail.com" wrote: > I have some file processing code that has to deal with quite a lot of > data. I have a quad core machine, so I wondered whether I could take > advantage of some parallelism. > > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? > > - Is list.append() thread safe? (not sure if this is the right term) > what I mean is, can two separate processors file a point in the same > list at the same time without anything horrible happening? Do I need > to do anything special (mutex or whatever) to make this happen, or > will it happen automatically? > > Thanks in advance for any guidance, > > Peter Look at http://pypi.python.org/pypi/processing From d3vvnull at gmail.com Sat Sep 27 19:52:44 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sat, 27 Sep 2008 18:52:44 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DEA603.9020507@wildenhain.de> References: <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> Message-ID: <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> I'm exhausted, so I'll just shut up about this after a few final words. 1. "edits" is used in data warehousing to describe data scrubbing or filtering of fields in records that are used as input sources for loading into data warehouses. It's a term that goes way back to batch processing on the mainframe, so it's been used this way for a long time. Sometimes we use 'validation' interchangeably with 'edit' but our use of validation usually involves a check of input data against business rules and not type or range checking which we consider 'edits'. So maybe you're not used to hearing the term used this way, but it is a variation perhaps of what you're used to. 2. The data warehousing world is quite different from the web world in many respects. I appreciate the fact that web application developers must always be mindful of the 'barbarians at the gates' but our batch environments are locked down, especially our databases. We have secured batch IDs. Our programs are run using an automated schedule. Our databases are secured to begin with so not even our batch IDs have alter, create or drop permissions on the database. There's no way this exploit would ever enter this environment because those servers aren't accessible through the web or online. 3. When you say 'in python we don not fear that' it's curious, because it assumes that all Python users must think as you do. And yet, clearly I don't think as you do. I really like this language and praise the Netherlands each day I wake up that they gave us someone as brilliant as Guido to make programming fun and not such a chore. But I think there are valid reasons for taking different approaches to security, data validation and dare I say it -- field editing -- despite the claims of many who say that in Python - TOOWTDI. 4. It's also curious that I was obliged to state my assumptions about batch programming vs. web programming. There is nothing in the OP to suggest that the problem was related to web programming. It's a question about how to interpolate the values in a list with format specifiers in a SQL statement. Still, if this list is not the result of user input but was derived within the body of the program, which by itself has no malicious intent, are we still going to code this as if it were input by a user that might be a hacker? This seems retarded and paranoid to me. And where in that post does it say that the list is from web input? Although to be fair maybe most of the Python community is doing web development. Thanks for the stimulating and educational discussion. On Sat, Sep 27, 2008 at 4:30 PM, Tino Wildenhain wrote: > Hi, > > Michael Mabin wrote: > >> If the inputs are edited prior to the construction of the string and these >> fields are used for more than one update then it's not an exploit. It's >> simply a matter not repeating yourself when coding. >> > > In python we do not fear that. > > In this particular case too, we're talking about a list of integers that >> gets inserted into a string. If the list is validated prior to its >> > > Its a list, if it indeed has integers in it is uncertain. It is so very > easy to check that that it doesnt even make sense to write such lengthy > emails about how bad you want to avoid it. Just do it. And even more so > if you are telling others how to do things make sure they do not so easy > shoot themselfes in their feet. > > insertion into an SQL statement then there is no exploit. If I write a >> batch program (not a web program) that retrieves this list of integers from >> other sources and validates the data prior to using it in an SQL statement, >> that should be sufficient. >> > > This might be well true but if you have a look at your original > contribution you see that all these your asumtions are just not in. > > As far as wrong and right is concerned. I think it's more about doing what >> is appropriate according to the circumstances. As a rule you >> > > If its easy to do, why not just doing it correctly (or robust) in all > circumstances to just avoid overlooking a case? > > should only code what is appropriate for the circumstances. If it's >> appropriate to code more simply without introducing unnecessary complexity >> you should do so. >> > > But you did not tell us about your asumtations about the circumstances. > > I work in the data warehousing ETL world, where we have to perform field >> edits or transformations to load source data into databases. If I'm >> > > Thats wrong. You do not "edit" fields. You have a validating type path and > _always_ the database is most authoritative about what it accepts. > Any other concept is just wrong and outright dangerous. There are > many examples of how this works out (just check bugtraq) > > already performing edits on these fields and if these fields are going to >> be used for more updates downstream, it's wasteful to perform them again >> when I build the SQL insert with the list and execute it. >> > > I still don't know what you mean by "edit" ;) If you mean filter out > special chars with for example replace("bad stuff","good stuff") check > your idea again, this is not going to work. (google for default permit) > > Finally, whatever happened to the practice of granting appropriate >> privileges to IDs that perform database operations? Shouldn't the person >> acting in the capacity of DBA ensure that the user updating or retrieving >> data from the database does not have DROP, ALTER, or CREATE privileges on >> that database? >> > > This of course is another layer which should be added - but you would > not need to - you edited the fields, right? ;) > > Sorry, it was not meant to put you to the wall but you insist so much > on your still dangerous solution while top posting the hell out of > this thread I just could not ignore it ;) > > T. > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Fri Sep 26 20:53:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 26 Sep 2008 17:53:59 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> <00b839d9-fe35-4478-aba2-0435fbf285e8@m36g2000hse.googlegroups.com> <00ed6d83$0$20666$c3e8da3@news.astraweb.com> Message-ID: <4039a6ac-f418-471b-8e21-3863adbe0d36@f63g2000hsf.googlegroups.com> On Sep 26, 7:43?pm, Steven D'Aprano wrote: > On Fri, 26 Sep 2008 14:54:36 -0700, Carl Banks wrote: > > However, it seems from the rest of your comments that speed is your main > > concern. ?Last time someone reported __slots__ didn't make a big > > difference in access time, but it probably would speed up creating > > objects a bit. ? > > Carl probably knows this already, but for the benefit of the Original > Poster: > > __slots__ is intended as a memory optimization, not speed optimization. > If it speeds up creation, that's a serendipitous side-effect of using > less memory. No, it'd be a serendipitous side-effect of not having to take the time to create a dict object, which is quite a bit more of a direct cause. It might still end up being slower (creating slot descriptors might take more time for all I know) but it's more than just an effect of less memory. Carl Banks From fredrik at pythonware.com Sat Sep 20 12:37:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 18:37:14 +0200 Subject: How to make a reverse for loop in python? In-Reply-To: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Alex Snast wrote: > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) use range with a negative step: for i in range(10-1, -1, -1): ... or just reverse the range: for i in reversed(range(10)): ... (the latter is mentioned in the tutorial, and is the second hit if you google for "python reverse for loop") From bdesth.quelquechose at free.quelquepart.fr Mon Sep 1 12:18:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 18:18:57 +0200 Subject: Some problems with classes In-Reply-To: References: Message-ID: <48bc31e1$0$26548$426a34cc@news.free.fr> Chris Rebert a ?crit : > On Sun, Aug 31, 2008 at 6:39 PM, ssecorp wrote: >> Why/how is it possible to add variables like this? I don't understand >> this mechanism: >> http://docs.python.org/tut/node11.html#SECTION0011330000000000000000 > > Under the covers, Python objects are implemented using dictionaries, Not necessarily. > so adding an attribute just adds a new key-value pair to the object's > internal dictionary (which, incidentally, you can access as > someobj.__dict__). Idem. From ldo at geek-central.gen.new_zealand Fri Sep 26 05:12:37 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 21:12:37 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: In message , Steven D'Aprano wrote: > On Fri, 26 Sep 2008 19:46:10 +1200, Lawrence D'Oliveiro wrote: > >> In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano >> wrote: >> >>> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: >>> >>>> Just a thought, your minimum sleep time is probably limited by the >>>> resolution of the system "HZ" clock. Type >>>> >>>> less /proc/config.gz >>> >>> $ less /proc/config.gz >>> /proc/config.gz: No such file or directory >>> >>> >>> What OS are you using? >> >> The one named in the subject line? > > Are you asking me or telling me? > > > I've tried on five different Linux machines I have access to, and there > is no such /proc/config.gz on any of them: > > two different versions of Centos > two versions of Fedora > one version of Ubuntu > > So let me rephrase my question... what *specific* OS are you using? From mensanator at aol.com Mon Sep 1 21:06:05 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 1 Sep 2008 18:06:05 -0700 (PDT) Subject: Py 2.6 changes References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> Message-ID: <0bb42df3-ead5-48f1-bfeb-485c8846a12b@m3g2000hsc.googlegroups.com> On Sep 1, 2:15?pm, bearophileH... at lycos.com wrote: > I have just re-read the list of changes in Python 2.6, it's huge, > there are tons of changes and improvements, I'm really impressed:http://docs.python.org/dev/whatsnew/2.6.html > > I'll need many days to learn all those changes! I can see it fixes > several of the missing things/problems I have found in Python in the > past, like the lack of information regarding the floating point it > uses, etc. > I have seen that many (smart) updates are from Hettinger. > > You can see a language gets better when you can remove often-used > commodity functions/classes from your own 'bag of tricks' :-) (Like > the permutations() function, Don't get rid of the whole bag, they didn't implement Combinations with Replcaement. > etc). > > >Python now must be compiled with C89 compilers (after 19 years!). This means that the Python source tree has dropped its own implementations of memmove and strerror, which are in the C89 standard library.< > > I presume it's better for me to not hold my breath while I wait > CPython to be written in C99 :-) > > Now math has factorial:http://docs.python.org/dev/library/math.html#math.factorial > Seen how reduce() is removed from Python 3 (I know it's in itertools), > and seeing that for me to write a productory() function was the first > usage I have had for reduce, years ago, I think the math module can > gain a productory() function too. > > For Python 2.7/3.1 I'd now like to write a PEP regarding the > underscores into the number literals, like: 0b_0101_1111, 268_435_456 > etc. I use such underscores all the time in the D language, and I > think they can be a tiny but significant improvement for Python (and > underscore is much better than just a space, because the underscore > helps the person that reads the code to understand that's a single > number). > > Bye, > bearophile From ter at topazcode.com Tue Sep 2 10:16:21 2008 From: ter at topazcode.com (topazcode) Date: Tue, 2 Sep 2008 07:16:21 -0700 (PDT) Subject: Storing Subprocess Results Message-ID: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> I am using the subprocess module to run some shell commands on a Linux system: import subprocess output = subprocess.call('''ssh server1 "uptime"''', shell=True) The above assigns the output variable with a return code, i.e. 0 in this case. How can I actually capture the data returned from subprocess.call, rather than just the return code? I'd like to have the output variable contain the uptime string in this case. Any help is appreciated. Thanks. From callen314 at gmail.com Tue Sep 9 17:50:26 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 9 Sep 2008 14:50:26 -0700 (PDT) Subject: How to record audio from Python on Mac? References: Message-ID: I want to do this as well, and also some other audio processing via python. I have not tried yet, but much of my research points to pyaudio, PortAudio bindings for python, which is supposed to be multi- platform including Mac OS X, but as I say, I've not tried it yet. Related to this are some examples that get the audio data into numpy arrays for signal processing work. cheers, I'm interested to hear how any of this works out, I'm trying to start a python audio project in the next couple months. cheers. On Sep 9, 1:06 am, s... at pobox.com wrote: > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > casting a broader net.) > > Can I easily control audio record/playback from Python on my Mac? I know > zip about audio recording or about Apple APIs via Python. Pointers to > simple examples would be much appreciated. > > Thanks, > > Skip From benjamin.kaplan at case.edu Tue Sep 2 10:35:12 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 2 Sep 2008 10:35:12 -0400 Subject: Storing Subprocess Results In-Reply-To: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> References: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> Message-ID: On Tue, Sep 2, 2008 at 10:16 AM, topazcode wrote: > I am using the subprocess module to run some shell commands on a Linux > system: > > import subprocess > output = subprocess.call('''ssh server1 "uptime"''', shell=True) > > The above assigns the output variable with a return code, i.e. 0 in > this case. How can I actually capture the data returned from > subprocess.call, rather than just the return code? I'd like to have > the output variable contain the uptime string in this case. Any help > is appreciated. Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > http://docs.python.org/lib/node532.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From akineko at gmail.com Mon Sep 1 22:01:17 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 19:01:17 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Message-ID: <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> On Sep 1, 6:34 pm, "Guilherme Polo" wrote: > This is an illusion you have, calling those methods are not the way > for explicitly controlling button's behavior, not more than generating > proper events. The explicit way is to not use a button, instead > (ab)use Canvas. Some of my custom widgets used Canvas. When I designed the "sticky" button widget, I briefly considered use of Canvas but I rejected because the one I wanted is nothing but Button (except "sticky" behaviour). I understand that use of Canvas provides greater flexibility but I felt it was over-kill. Your insights are very helpful for me and other people when designing a custom widget. Aki- From pavlovevidence at gmail.com Fri Sep 26 17:54:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 26 Sep 2008 14:54:36 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> Message-ID: <00b839d9-fe35-4478-aba2-0435fbf285e8@m36g2000hse.googlegroups.com> On Sep 26, 11:39?am, Patrick Sullivan wrote: > Hello. Hi, I have a couple suggestions. > I will be using some large data sets ("points" from 2 to 12 variables) > and would like to use one class for each point rather than a list or > dictionary. Ok, point of terminology. It's not really a nit-pick, either, since it affects some of your questions below. When you say you want to use one class for each point, you apparently mean you would like to use one class instance, or one object, for each point. One class for each point would be terribly inefficient; one instance, perhaps not. > I imagine this is terribly inefficient, but how much? You say large data sets, which suggests that __slots__ mechanism could be useful to you. class A(object): __slots__ = ['var1','var2','var3'] Normally, each class instance has an associated dict which stores the attributes, but if you define __slots__ then the variables will be stored in fixed memory locations and no dict will be created. However, it seems from the rest of your comments that speed is your main concern. Last time someone reported __slots__ didn't make a big difference in access time, but it probably would speed up creating objects a bit. Of course, you should profile it to make sure. > What is the cost of creating a new class? I'm assuming you want to know the cost of creating a class instance. Generally speaking, the main cost of this is that you'd be executing Python code (whereas list and dict are written in C). > What is the cost of referencing a class variable? I assume you mean an instance variable. > What is the cost of calling a class method to just return a variable? Significant penalty. This is because even if the method call is faster (and I doubt very highly that it is), the method still has to access the variable, which is going to take the same amount of time as accessing the variable directly. I.e., you're getting the overhead of a method call to do the same thing you could have done directly. I highly recommend against doing this, not only because it's less efficient, but also because it's considered bad style in Python. > Key point: The point objects, once created, and essentially non- > mutable. Static. Is there a way to "bind" a variable to a object > method in a way that is more efficient than the function calling > self.variable_name ? Python 2.6 has a new object type called namedtuple in the collections module. (Actually it's a type factory that creates a subclass of tuple with attribute names mapped to the indices.) This might be a perfect fit for your needs. You have to upgrade to 2.6, though, which won't be released for a few days. Carl Banks From rtiago at gmail.com Wed Sep 10 17:24:15 2008 From: rtiago at gmail.com (Ricardo Tiago) Date: Wed, 10 Sep 2008 23:24:15 +0200 Subject: formating a filesystem with python In-Reply-To: <6iqrm2F3rqcU1@mid.uni-berlin.de> References: <6iqrm2F3rqcU1@mid.uni-berlin.de> Message-ID: <8ed7d4b30809101424y5db412d2i7d70545652dcc0c5@mail.gmail.com> I understand that this is a very sensible unix question but i think fuse does this at least it mounts. I was wondering if there were other packages with similar functionality. On Wed, Sep 10, 2008 at 11:14 PM, Diez B. Roggisch wrote: > Ricardo Tiago schrieb: >> >> Hi all, >> >> is there a package in python that allows to mount/umount and format >> (to ext3) a filesystem? I know that this is possible by just calling >> the os commands 'mount/umount and mkfs' but this would imply to have >> to change sudoers to run the script as non-root. > > well, that's a very sensible unix-restriction. and you can't overcome that. > > IOW: no, there is no such thing. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Thu Sep 11 06:35:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 11 Sep 2008 03:35:17 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: <823435cf-a557-48d9-9e16-fa28e745e67a@73g2000hsx.googlegroups.com> On 11 Sep, 10:34, Fredrik Lundh wrote: > > And as I said before, the only use case for *huge* XML files I've ever > seen used in practice is to store large streams of record-style data; I can imagine that the manipulation of the persistent form of large graph structures might be another use case, although for efficient navigation of such a structure, which is what you'd need to start applying various graph algorithms, one would need some kind of index. Certainly, we're straying into database territory. Paul From tjreedy at udel.edu Fri Sep 26 02:59:33 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 02:59:33 -0400 Subject: deleting an object In-Reply-To: <6u80qt$80h3s3@rrcs-agw-02.hrndva.rr.com> References: <6u80qt$80h3s3@rrcs-agw-02.hrndva.rr.com> Message-ID: Karl Kobata wrote: > Please help. Questions based on snippet of code below. Please post code that works. Use cut and paste. > 1) when myTestCase is deleted, is just the pointer deleted or the > entire instance with all of its data and data structure deleted? Have you read the manual section on the del statement? > 2) What is the practice for deleted the object and recovering the > memory it occupies? Most programs use del rather sparingly. Most temporary objects are created within functions and get unbound automatically when the function exits. If you need to guarantee release of external resources before the program ends, make explict calls to .close methods of the instances that connect to them. Actually memory recovery depends on the implementation and version. I would not worry about this until you really need to. > 3) If delete is the way, what happens to > ?testUtils.utilFunction1()? if it were instantiated in other classes > that have not been deleted yet? Objects will not be destroyed while still reachable from code (in the absence of a severe bug). > import testUtils > class testClass: > def __init__(self): > self.testList = list() > self.testDict1 = dict() > self.utils1 = testUtils.utilFunction1() > myTestCase = testClass() > delete myTestCase Don't indent main body code. Do use legal keywords. tjr From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 4 07:23:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 13:23:53 +0200 Subject: Coming from .NET and VB and C In-Reply-To: References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> Message-ID: <48bfc4e4$0$13232$426a74cc@news.free.fr> Marco Bizzarri a ?crit : > On Thu, Sep 4, 2008 at 12:16 AM, Dennis Lee Bieber > wrote: >> On Wed, 3 Sep 2008 09:52:06 -0700 (PDT), ToPostMustJoinGroup22 >> declaimed the following in >> comp.lang.python: >> >>> have no preference with MySQL or SQL, stored procedures or ad-hoc >>> queries. >>> >> Please note: MySQL is specific relational database management system >> (RDBMs), which uses a dialect of structured query language (SQL). SQL by >> itself is just a semi-standardized query language -- and can technically >> be used to access non-relational DBMS (if any such are still in use), >> though the query processor would be a pain to program (map a relational >> join into a hierarchical DBMS schema? ugh). >> >>> SO, I'm interested in using my Google App space (free 500MB) to >>> develop a quick database application. Using Python. I found "Dive >>> Into Python" which I will be reading shortly. >>> >> So one question: what RDBMs are supported in that space? > > The appearance is not an RDBMS, at least, maybe it is, but under the surface. Not AFAIK, cf: http://en.wikipedia.org/wiki/BigTable From bignose+hates-spam at benfinney.id.au Wed Sep 10 19:42:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 11 Sep 2008 09:42:20 +1000 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> Message-ID: <87d4jbd0v7.fsf@benfinney.id.au> Grant Edwards writes: > Could whoever is responsible for the gateway that is grabbing > my postings off of Usenet and e-mailing them out please fix the > headers in the mail messages so that I don't get the bounce > messages? The bounce messages are sent to you because you sent the original. > Its a bit rude to send out mass e-mail messages with headers faked > up so that the bounce messages go to somebody else. Indeed it is rude, and the person subscribed to the mailing list whose software is sending these bounce messages is the one responsible for making it stop. The mailing list software can't help (nor can the news-to-mail gateway). In the meantime, the usual fix is for the list administrator to unsubscribe the offending party (the one sending automated bounce messages). -- \ ?He who laughs last, thinks slowest.? ?anonymous | `\ | _o__) | Ben Finney From kaerbuhez at gmail.com Tue Sep 9 18:45:50 2008 From: kaerbuhez at gmail.com (kaer) Date: Tue, 9 Sep 2008 15:45:50 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: <0c964409-83a6-43ec-85ac-923a17e781d3@b1g2000hsg.googlegroups.com> On 9 sep, 23:35, icarus wrote: > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > That did it. > > one more question... > > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? > > My intent is to have the process transparent to the user. He wouldn't > even know the app was written in python. All he knows that when he > double-clicks on it, the application pops up without the DOS black > screen in the background (for w32 users.) > > On Sep 9, 10:49 am, "Chris Rebert" wrote: > > > You need to have the script be run by pythonw.exe as opposed to python.exe > > pythonw.exe suppresses the DOS box from coming up and should be used > > for running GUI applications such as yours. > > > Regards, > > Chris > > > On Tue, Sep 9, 2008 at 1:33 PM, icarus wrote: > > > platform: windows xp professional, python 2.5, wxpython > > > > When I double-check on my program file test.py (for simplicity I'll be > > > using this code below), I see the window just fine. But the ms-dos > > > black window pops up in the background. On Linux, no issues at all. > > > > How can I get rid of that ms-dos black window in the background? > > > something I need to add to my code? a setting to adjust in windows? > > > thanks in advance. > > > > #!/usr/bin/python > > > import wx > > > > appwx = wx.App() > > > > frame = wx.Frame(None, -1, 'test.py') > > > frame.Show() > > > > appwx.MainLoop() > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > -- > > Follow the path of the Iguana...http://rebertia.com py2exe could be what you are looking for. From rajko.mackic at gmail.com Sat Sep 20 20:20:51 2008 From: rajko.mackic at gmail.com (Rajko Mackic Cvrcko) Date: Sat, 20 Sep 2008 17:20:51 -0700 (PDT) Subject: Hi guys! Message-ID: <4105bf15-6454-46dc-8894-7f228391a95d@p31g2000prf.googlegroups.com> Hello, this is Rajko Mackic from town Banjaluka, Bosnia and Herzegovina, also known as Cvrcko Does anyone know of any bars in town where I can swallow a bucket of cum? It can be either dog, horse or human cum. Also, does anyone know of any sex bars where people will shit in your mouth? I also like eating shit. -- Name: Rajko Mackic - Cvrcko Street adress: Ravnogorska 35 Town: 78000 Banja Luka Country: Bosnia and Herzegovina Home phone: +38751/302-886 Cell phone: +38765/544-699 Email adress: rajko.mackic at gmail.com ~ The new pumpkin rarely pulls Terrance, it teases Sharon instead. For Susan the tape's sad, beside me it's unique, whereas against you it's believing dirty. Hey, go reject a fork! Why did Alice open throughout all the boats? We can't explain poultices unless Woody will mercilessly judge afterwards. The frames, disks, and shirts are all fat and fresh. Who will we dine after Edwina wastes the thin mirror's goldsmith? It's very outer today, I'll recollect strangely or Christopher will learn the teachers. Hardly any humble brave tyrants hourly solve as the tired wrinkles cover. Hardly any distant buttons are short and other urban ointments are filthy, but will Robette receive that? Let's lift behind the deep highways, but don't promise the heavy diets. Who kicks badly, when Melvin burns the stale code before the autumn? Get your absolutely moulding barber within my cellar. If you will laugh Gay's hill against porters, it will incredibly climb the case. Some shopkeepers arrive, irrigate, and shout. Others sadly expect. To be pathetic or sticky will talk abysmal oranges to wickedly look. Are you healthy, I mean, moving above clever onions? While farmers partly taste pins, the powders often excuse against the blunt jackets. Generally Susanne will order the sticker, and if George actually seeks it too, the bowl will attempt with the polite lane. He can hate durable kettles above the rural bad ocean, whilst Oscar easily scolds them too. You eventually fill against Norma when the kind drapers irritate among the poor summer. As surprisingly as Dolf converses, you can dye the cap much more familiarly. Brion, still killing, behaves almost eerily, as the sauce changes on their coffee. You won't recommend me grasping about your lazy office. Almost no butchers steadily live the lost signal. Cyrus's hat improves among our desk after we sow towards it. Ralph measures the weaver within hers and wanly calls. Some cosmetic tags answer David, and they rigidly walk Quincy too. When Richard's elder gardner dreams, Mark cares for weak, closed islands. He might strongly fear think and plays our cheap, sour painters above a bathroom. I creep the active yogi and cook it in back of its dorm. Tell Katherine it's strong loving within a tree. Why will you jump the angry lower exits before Murray does? I am unbelievably bitter, so I wander you. How does Hector smell so regularly, whenever Ronald likes the solid twig very slowly? Julieta, have a hot printer. You won't clean it. Fucking don't join a dryer! She wants to nibble inner smogs under Usha's castle. She'd rather depart grudgingly than help with Bernadette's younger grocer. Other old dark cards will comb frantically alongside cans. Try pouring the monument's pretty cat and Oliver will attack you! Don't try to seek halfheartedly while you're jumping throughout a easy carpenter. He'll be climbing in front of good Cypriene until his enigma answers quietly. What doesn't Janet smell inadvertently? They are opening before the rain now, won't explain walnuts later. Some light long game covers pools outside Woodrow's rich film. Why did Oscar judge the pear with the handsome spoon? He will talk nearly if Julieta's tailor isn't wet. Just looking beside a ulcer through the store is too young for Woody to care it. Both filling now, Alejandro and Marty irritated the open rivers about smart envelope. Occasionally, dusts kill beside rude fires, unless they're sweet. Her pen was sharp, dull, and fears over the spring. Zack, on floors difficult and upper, attacks towards it, recollecting seemingly. We measure the raw sauce. They are rejecting throughout quiet, towards empty, in back of cold units. My wide potter won't clean before I comb it. If you'll pour Edward's camp with aches, it'll admiringly converse the cup. I was promising frogs to worthwhile Corinne, who's walking in back of the counter's stable. It can receive clean pickles, do you solve them? Many jugs will be weird lean carrots. Roger helps, then Walt stupidly believes a ugly lentil on Catherine's road. We tease them, then we weekly dream Zack and Annabel's blank candle. A lot of shallow dose or canyon, and she'll locally excuse everybody. If the bizarre balls can sow bimonthly, the hollow raindrop may love more ventilators. We laugh weekly, unless Jezebel grasps shoes outside Jimmie's puddle. Jimmy! You'll mould plates. Just now, I'll dine the bandage. All glad strange figs will fully order the lemons. The dog without the proud star is the pitcher that learns happily. It might crudely scold within sick dry satellites. Until Dolf calls the bushs generally, Ann won't join any full winters. Better kick clouds now or Blanche will wrongly hate them over you. There, Jeff never arrives until Joie nibbles the noisy elbow deeply. From semanticist at gmail.com Mon Sep 22 02:53:16 2008 From: semanticist at gmail.com (Miles) Date: Mon, 22 Sep 2008 02:53:16 -0400 Subject: dict generator question In-Reply-To: <00e45101$0$20331$c3e8da3@news.astraweb.com> References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <00e45101$0$20331$c3e8da3@news.astraweb.com> Message-ID: On Fri, Sep 19, 2008 at 9:51 PM, Steven D'Aprano wrote: > Extending len() to support iterables sounds like a good idea, except that > it's not. > > Here are two iterables: > > > def yes(): # like the Unix yes command > while True: > yield "y" > > def rand(total): > "Return random numbers up to a given total." > from random import random > tot = 0.0 > while tot < total: > x = random() > yield x > tot += x > > > What should len(yes()) and len(rand(100)) return? Clearly, len(yes()) would never return, and len(rand(100)) would return a random integer not less than 101. -Miles From roy at panix.com Wed Sep 3 09:35:41 2008 From: roy at panix.com (Roy Smith) Date: Wed, 03 Sep 2008 09:35:41 -0400 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > > I might take it one step further, however, and do: > > > >> fields = line.split()[:2] > >> a, b = map(int, fields) > > > > in fact, I might even get rid of the very generic, but conceptually > > overkill, use of map() and just write: > > > >> a, b = line.split()[:2] > >> a = int(a) > >> b = int(b) > > If you go that route your next step is to introduce another try...except, > one for the unpacking and another for the integer conversion... Why another try/except? The potential unpack and conversion errors exist in both versions, and the existing try block catches them all. Splitting the one line up into three with some intermediate variables doesn't change that. From python at rgbaz.eu Sat Sep 6 18:03:20 2008 From: python at rgbaz.eu (Python) Date: Sun, 7 Sep 2008 00:03:20 +0200 Subject: modules path Message-ID: <27B9B240-59E7-4174-95EF-5A4D70B1092B@rgbaz.eu> Hi there, I moved a few modules into the modules folder (on OSX: /opt/local/lib/ python2.5/site-packages/). They don't show up though when I start IDLE... Is there a way to reload the modules folders in sys.path without logging out and back in? something like "source .cshrc" in a shell... thanks in advance, Arno From Afro.Systems at gmail.com Sat Sep 20 14:45:48 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Sat, 20 Sep 2008 11:45:48 -0700 (PDT) Subject: writeable buffer and struct.pack_into and struct.unpck_from Message-ID: Hi, I can't find in the documentation the way to use these two functions. can someone share a simple code that utilize these two functions? From george.sakkis at gmail.com Thu Sep 18 11:39:22 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 18 Sep 2008 08:39:22 -0700 (PDT) Subject: dict generator question References: Message-ID: <5b4c91e1-f189-40f4-b5dd-71647683aba8@f36g2000hsa.googlegroups.com> On Sep 18, 10:54 am, "Simon Mullis" wrote: > Hi, > > Let's say I have an arbitrary list of minor software versions of an > imaginary software product: > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > I'd like to create a dict with major_version : count. > > (So, in this case: > > dict_of_counts = { "1.1" : "1", > "1.2" : "2", > "1.3" : "2" } > > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. > > I'm most probably not thinking pythonically enough... (I know I could > do this pretty easily with a couple more lines, but I'd like to > understand if there's a way to use a dict generator for this). Not everything has to be a one-liner; also v[0:3] is wrong if any sub- version is greater than 9. Here's a standard idiom (in 2.5+ at least): from collection import defaultdict versions = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] major2count = defaultdict(int) for v in versions: major2count['.'.join(v.split('.',2)[:2])] += 1 print major2count HTH, George From pratibha.kachi at gmail.com Mon Sep 15 07:19:49 2008 From: pratibha.kachi at gmail.com (pratibha.kachi at gmail.com) Date: Mon, 15 Sep 2008 04:19:49 -0700 (PDT) Subject: Not able to successfully call a webservice created in c# in python. Message-ID: <87e0c57d-2bcd-44d6-8d02-f6b7e62c28a9@l33g2000pri.googlegroups.com> I have created a webservice in C# which I am able to call in win Form client but when I call it using python it gives http 415 error. >>> import SOAPpy >>> server = SOAPpy.SOAPProxy("http://localhost:8731/Design_Time_Addresses/WcfSe rviceLibrary1/Service1/WS") >>> print server.GetData(1) Traceback (most recent call last): File "", line 1, in File "C:\python25\lib\xmlrpclib.py", line 1147, in __call__ return self.__send(self.__name, args) File "C:\python25\lib\xmlrpclib.py", line 1437, in __request verbose=self.__verbose File "C:\python25\lib\xmlrpclib.py", line 1191, in request headers xmlrpclib.ProtocolError: From michel at nospam.please Mon Sep 15 15:44:33 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:44:33 +0200 Subject: environment variable issue In-Reply-To: <48ceb82a$0$2861$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> <48ceb82a$0$2861$ba620e4c@news.skynet.be> Message-ID: <48cebb21$0$2862$ba620e4c@news.skynet.be> Michel Leunen a ?crit : > Actually HOSTNAME seems to be exported as well: > > $ export -p | grep HOSTNAME > declare -x HOSTNAME="LinuxPC" > > I don't know what to think of this but it's the beginning of an > explanation. Oops, my mystake, I forgot I made an export HOSTNAME before trying the export -p command. Sorry, you're right, HOSTNAME is NOT in the list of exported variable. -- Michel Leunen http://linux.leunen.com From stef.mientki at gmail.com Fri Sep 26 17:26:54 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 26 Sep 2008 23:26:54 +0200 Subject: how to search multiple textfiles ? (Python is slow ?) In-Reply-To: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> References: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> Message-ID: <48DD539E.3080108@gmail.com> Mike Driscoll wrote: > On Sep 26, 8:35 am, Stef Mientki wrote: > >> hello, >> >> I want to search multiple textfiles (python source files) for a specific >> word. >> I can find all files, open them and do a search, >> but I guess that will be rather slow. >> >> I couldn't find any relevant information through google. >> >> Does anyone know of a search library that performs this task fast ? >> >> If it indeed only concerns py-files, >> is there another way of searching words ? >> ( I could imagine that such a "py-only-search" would have benefits, >> because you could set a flag to see the words in comment yes or no ) >> >> thanks, >> Stef Mientki >> >> Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. >> The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629. >> > > > On Windows I use the free version of Bare Grep: http://www.baremetalsoft.com/baregrep/ > > No, it's not a Python solution, but it works for my needs. You should > try using Python to search your script files and see if it really is > too slow though. > hi guys, I did some tests and I'm amazed about the results: I did a search on the Python directory: 300 MB, 10325 files in 660 folders. I did several searches, with / without case-sensitive, whole words / not, many/few occurrences, but the differences between those were negligible. Finding all occurences with line numbers: - Pyscripter 110 sec ( PyScripter is the default IDE I use now) - Delphi 20 .. 35 sec - Findstr 4 sec With the following programs I only searched for the first occurence, which I think is good in the case of many files, because you can only view 20 or 30 lines in 1 screen. - Explorer XXX didn't find anything - FileNurse 5 sec (FileNurse is my own Explorer replacement, written in Delphi) - Python 3 sec (very quick and dirty procedure with string.find method I'm really amazed by the speed of Python !! It can only be beaten by findstr, which is only available on windows. Paul: nucular looks very promissing, but I couldn't get it working within a few minutes. I might also be a little overkill, but I'll certainly bookmark the link for future use. thanks again, cheers, Stef > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Sat Sep 6 19:18:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 16:18:15 -0700 (PDT) Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: On Sep 7, 8:06?am, cnb wrote: > If I buy a multicore computer and I have really intensive program. How > would that be distributed across the cores? AFAIK, a single process wouldn't be distributed automatically. > Will algorithms always have to be programmed and told specifically to > run on several cores so if not told it will only utilize one core? AFAIK, yes. See (for example) http://www.parallelpython.com/ > So is the free lunch really over There is no such thing as a free lunch. Something which has never existed can't be over. > or is this just an overhyped > phenomena? These days, every IT phenomenon is over-hyped. If you have a CPU-intensive Python program, you may want to consider: (1) checking that there are not faster/better algorithms for doing what you want in Python, either built-in or in a 3rd-party library (2) using psyco (3) checking your code for sub-optimal constructs HTH, John From nstjelja at gmail.com Thu Sep 11 14:33:23 2008 From: nstjelja at gmail.com (Nikola Stjelja) Date: Thu, 11 Sep 2008 20:33:23 +0200 Subject: wx In-Reply-To: References: Message-ID: <2d24984a0809111133na2a8b79pb340b273863b9de7@mail.gmail.com> The module you are talking about is a python GUI toolkit named WxPython, which is a port of the cross platform C++ GUI toolkit wxwidgets. It's an excelent gui toolkit , easy to learn and code on. Well documented and has an excelent community around it. Here are the links for both sites: http://www.wxpython.org/ http://www.wxwidgets.org/ On Thu, Sep 11, 2008 at 8:16 PM, Desmond Scott E wrote: > I'm am a Python novice by chance not choice. (Although it appears to be > a nice tool. Plus anything based on Monte Python can't be bad!) > > My Quest is to migrate a Python-based process from Windows2000/Python > v2.4.2 (#67) to WindowsXP/Python v2.5.2 (r252:60911). > > I've searched the Python website and could find no reference to module wx. > Is this an add-in module or perhaps it was replaced in v2.5.2??? > > References in the code are: > wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT) > self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated) > self.SetColumnWidth(0, WX.LIST_AUTOSIZE)) > idx = self.GetNextItem(idx, wx.LIST_NEXT_ALL, wx.LIST_STATE_DONTCARE) > > Any help would be greatly appreciated! I do have Shrubbery! > > Scott > > Scott E. Desmond > Director & Manager Equity Systems Development > IT Integration Lead > Mellon Capital Management Corporation > 500 Grant Street, Suite 4200 > Pittsburgh, PA 15258 > T 412.236.0405 | F 412.236.1703 > scottd at mcm.com | *www.mcm.com* > > *The information contained in this e-mail may be confidential and is > intended solely for the use of the named addressee.* > *Access, copying or re-use of the e-mail or any information contained > therein by any other person is not authorized.* > *If you are not the intended recipient please notify us immediately by > returning the e-mail to the originator.(16b)* > ** > Disclaimer Version MB.US.1 > > -- > http://mail.python.org/mailman/listinfo/python-list > -- My Blog: http://mylifeasadeveloper.blogspot.com/ My home page: http://www.inet.hr/~nstjelja My Poetry Book: http://www.lulu.de/browse/book_view.php?fCID=222964&fBuyItem=5 My OS Projects: http://lab.linux.hr/~nstjelja/drawit/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Sun Sep 14 15:39:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Sep 2008 21:39:29 +0200 Subject: Is there any nice way to unpack a list of unknown size?? In-Reply-To: <238815.3778.qm@web7902.mail.in.yahoo.com> References: <238815.3778.qm@web7902.mail.in.yahoo.com> Message-ID: srinivasan srinivas wrote: > I want to do something like below: > > 1. first, second, third, *rest = foo > > 2. for (a,b,c,*rest) in list_of_lists: update to Python 3.0 (as others have pointed out), or just do first, second, third = foo[:3] rest = foo[3:] for item in list_of_lists: a, b, c = item[:3] rest = item[3:] ... and move on to more interesting parts of your program. From oliphant.travis at ieee.org Thu Sep 11 09:45:27 2008 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Thu, 11 Sep 2008 08:45:27 -0500 Subject: NumPy arrays that use memory allocated from other libraries or tools In-Reply-To: <63fac77e-3043-40fa-8f3d-9d751d9a82cf@d1g2000hsg.googlegroups.com> References: <63fac77e-3043-40fa-8f3d-9d751d9a82cf@d1g2000hsg.googlegroups.com> Message-ID: sturlamolden wrote: > On Sep 10, 6:39 am, Travis Oliphant wrote: > >> I wanted to point anybody interested to a blog post that describes a >> useful pattern for having a NumPy array that points to the memory >> created by a different memory manager than the standard one used by >> NumPy. > > > Here is something similar I have found useful: > > There will be a new module in the standard library called > 'multiprocessing' (cf. the pyprocessing package in cheese shop). It > allows you to crerate multiple processes (as opposed to threads) for > concurrency on SMPs (cf. the dreaded GIL). > > The 'multiprocessing' module let us put ctypes objects in shared > memory segments (processing.Array and processing.Value). It has it's > own malloc, so there is no 4k (one page) lower limit on object size. > Here is how we can make a NumPy ndarray view the shared memory > referencey be these objects: > > try: > import processing > except: > import multiprocessing as processing > > import numpy, ctypes > > _ctypes_to_numpy = { > ctypes.c_char : numpy.int8, > ctypes.c_wchar : numpy.int16, > ctypes.c_byte : numpy.int8, > ctypes.c_ubyte : numpy.uint8, > ctypes.c_short : numpy.int16, > ctypes.c_ushort : numpy.uint16, > ctypes.c_int : numpy.int32, > ctypes.c_uint : numpy.int32, > ctypes.c_long : numpy.int32, > ctypes.c_ulong : numpy.int32, > ctypes.c_float : numpy.float32, > ctypes.c_double : numpy.float64 > } > > def shmem_as_ndarray( array_or_value ): > > """ view processing.Array or processing.Value as ndarray """ > > obj = array_or_value._obj > buf = obj._wrapper.getView() > try: > t = _ctypes_to_numpy[type(obj)] > return numpy.frombuffer(buf, dtype=t, count=1) > except KeyError: > t = _ctypes_to_numpy[obj._type_] > return numpy.frombuffer(buf, dtype=t) > > With this simple tool we can make processes created by multiprocessing > work with ndarrays that reference the same shared memory segment. I'm > doing some scalability testing on this. It looks promising :) > Hey, that is very neat. Thanks for pointing me to it. I was not aware of this development in multiprocessing. -Travis From clodoaldo.pinto at gmail.com Sun Sep 14 09:33:51 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Sun, 14 Sep 2008 06:33:51 -0700 (PDT) Subject: cjson 1.0.5 keyword argument Message-ID: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> I have installed cjson 1.05 in Fedora 8 (python 2.5.1). The cjson home page shows a keyword argument "encoding". http://python.cx.hu/python-cjson/ When i use it i get an error: >>> cjson.encode('?', encoding='utf8') Traceback (most recent call last): File "", line 1, in TypeError: encode() takes no keyword arguments What am i missing? There is no mail list for cjson. Regards, Clodoaldo From steven at REMOVE.THIS.cybersource.com.au Wed Sep 24 02:17:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 24 Sep 2008 06:17:04 GMT Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: On Tue, 23 Sep 2008 13:25:26 -0700, Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose Python > functions, some of which do I/O. Therefore it is possible for many of > the library functions to raise IOError Exceptions. The question is: > should the library function be able to just dump to sys.exit() with a > message about the error (like "couldn't open this file"), or should the > exception propagate to the calling program which handles the issue? > > Thanks in advance for anyone who can either answer my question or point > me to where this question has already been answered. Presumably somebody has suggested that calling sys.exit() was a good option. I'm curious to what possible reason they could give for such a poor choice. Hint: if a library function can't open a file, the application should be given the opportunity to open a different file. Or do something completely different instead. Whatever. That's not up to the library to decide, not even if the library is in such a broken state that it can't continue. Why not? Because the application might deal with that by unloading the library and continuing regardless. -- Steven From tchendrix at gmail.com Tue Sep 23 10:53:03 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 07:53:03 -0700 (PDT) Subject: finding domain name References: Message-ID: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> On Sep 23, 9:10?am, Tino Wildenhain wrote: > Bobby Roberts wrote: > >> Depends on the technology/web framework. If you use WSGI, you should use > >> something like: > > >> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] > > >> -- Gerhard > > > Yeah i already tried environ("SERVER_NAME") but get a key error when i > > do. > > You could output the whole environ to see what you get and how it is called. > > I'd recommend however to check that you are using a configured value and > not something sent by the client if you are going to use it during > filesystem lookup. > > Regards > Tino > > ?smime.p7s > 4KViewDownload evidently the environ dictionary is off limits on our server. It can't be that tough in python to get the current complete url being viewed. It's a snap in asp(which is my background). From lixinyi.23 at gmail.com Tue Sep 23 20:50:02 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 17:50:02 -0700 (PDT) Subject: How do I use python object in C++ Message-ID: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> for example I have the following code: #include void exec_pythoncode( int arg, char**argv ) { Py_Initialize(); Py_Main(argc,argv); Py_Finalize(); } What I would like to know is how can I get the variables I want after Py_Main(argc,argv) say I have a=[1,2,'Hello World',0.1234] in the python space, I would like to have it as a struct in C++. Any sample code? Thanks in advance! From python.list at tim.thechases.com Sun Sep 14 15:16:04 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 14 Sep 2008 14:16:04 -0500 Subject: Is there any nice way to unpack a list of unknown size?? In-Reply-To: <6bbcb770-d9f7-4bfd-ae9a-491b2084a739@34g2000hsh.googlegroups.com> References: <238815.3778.qm@web7902.mail.in.yahoo.com> <6bbcb770-d9f7-4bfd-ae9a-491b2084a739@34g2000hsh.googlegroups.com> Message-ID: <48CD62F4.1060803@tim.thechases.com> >> I want to do something like below: >> 1. first, second, third, *rest = foo > > Python 3.0 has exactly this feature. No current Python 2.x version has it. I asked something similar[1] on c.l.p a while back and Diez Roggisch gave this nice workaround/hack[2] It's a bit ugly in the implementation (sniffing the stack), but elegant in the use, doing exactly what I needed. It doesn't accommodate the "rest" portion that you reference, but allows for arbitrary unpacking into a fixed-length tuple. -tkc [1] http://mail.python.org/pipermail/python-list/2006-May/381386.html [2] http://mail.python.org/pipermail/python-list/2006-May/381399.html From landa.martin at gmail.com Mon Sep 1 11:01:04 2008 From: landa.martin at gmail.com (Martin Landa) Date: Mon, 1 Sep 2008 08:01:04 -0700 (PDT) Subject: python extension dynamic linking Message-ID: Hi, I am writing Python extension in C++, in this extension I am using methods from another Python extension. On Linux I am currently linking my extension with used Python extension -- what is quite ugly. gcc ... -lgdi where gdi is a link to C++ extension imported by 'module' I would like to avoid direct linking here. import module # export some symbol used in my_module import my_module I realized that on Mac it is possible to dynamically link C++ extension using -bundle -undefined dynamic_lookup I wonder how to solve this problem on Linux or MS Window. Thanks for any pointers... Martin From miki.tebeka at gmail.com Tue Sep 23 04:40:15 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 23 Sep 2008 01:40:15 -0700 (PDT) Subject: any tool can shrink DLL? References: Message-ID: <50075ffd-9e17-4878-8383-8487659baf8d@b2g2000prf.googlegroups.com> Hello, > So, is there such a tool that can scan a DLL then strip the unused > function's code out, so yields a small working DLL? I don't think a utility from the outside will know about unused code in a DLL? Usually the compiler is the one doing dead code elimination. The only thing that comes to mind is "strip" that removes strings from executables. As for UPX, does the slowdown really matter? HTH, -- Miki http://pythonwise.blogspot.com From CapnBearbossa at googlemail.com Mon Sep 22 18:07:53 2008 From: CapnBearbossa at googlemail.com (CapnBearbossa at googlemail.com) Date: Mon, 22 Sep 2008 15:07:53 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> Message-ID: <1f913671-1c21-4018-a841-a5a02a360c3b@k30g2000hse.googlegroups.com> On Sep 22, 5:52?pm, Matimus wrote: > On Sep 22, 2:31?pm, CapnBearbo... at googlemail.com wrote: > > > > > hi all, > > > forgive me , but the RTFM and Google search approaches are not > > yielding an answer on this question. ?I need to know if there's a top > > level python interpreter command that clears all user variables (not > > built-ins) from the global namespace. ?In other words a statement, or > > some_command_or_function(), that does this: > > > >>> x=3 > > >>> y=4 > > >>> z=[] > > >>> dir() > > > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > > > >>> some_command_or_function() > > >>> dir() > > > ['__builtins__', '__doc__', '__name__'] > > > thanks, > > ? ?1 desperate snake oil programmer .... > > I don't think you will find anything. The interpreter is essentially > the same whether you are in interactive mode or not. That is, there is > very little use for a method that clears globals in general, so why > would we add it just so that it could be used by the interpreter. > There is almost* nothing available to the interactive interpreter > which isn't part of the core language. > > * The only difference I can think of is the "_" variable, which is > added to __builtins__ and contains the last value returned in > interactive mode. If you have ever tried to run code that uses the > locale module from the interpreter you will see why having any > differences between the interactive and non-interactive interpreter > can be a pain. > > Matt ok. thanks! guess i'll be off to define my own function ... From mal at egenix.com Mon Sep 8 05:42:27 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 08 Sep 2008 11:42:27 +0200 Subject: Error importing mxTidy In-Reply-To: References: Message-ID: <48C4F383.2020807@egenix.com> On 2008-09-07 15:00, Mike Hostetler wrote: > I built and installed mx-experimental 3.0.0 from source and it seemed to go > fine. But when I try to import it, I get this: > > localhost% python -c "import mx.Tidy" > Traceback (most recent call last): > File "", line 1, in ? > File "mx/Tidy/__init__.py", line 7, in ? > from Tidy import * > File "mx/Tidy/Tidy.py", line 7, in ? > from mxTidy import * > File "mx/Tidy/mxTidy/__init__.py", line 7, in ? > from mxTidy import * > ImportError: No module named mxTidy > > This seems strange to me, since it found the mx.Tidy module but not the mxTidy > module underneath it. But I guess I don't know how the mx-experimental classes > are put together, so I can't really guess what is happening. Thus I am posting > here. :) Which platform are you using ? -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 08 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From usenet1 at anton.e4ward.com Thu Sep 4 06:05:45 2008 From: usenet1 at anton.e4ward.com (Poster28) Date: Thu, 04 Sep 2008 12:05:45 +0200 Subject: Issue warning if no "return" in function? Message-ID: What would you suggest to check python programs for non-syntax error. One example I could think of that one might forget to "return" a value from a function. How could I check for these and maybe other mistakes? From pavlovevidence at gmail.com Thu Sep 4 19:07:04 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 16:07:04 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> Message-ID: <6c55be0c-c60e-49b9-93ba-a7d17c616f9c@b1g2000hsg.googlegroups.com> On Sep 4, 3:15 pm, Ivan Illarionov wrote: > On 4 ????, 22:59, Carl Banks wrote: > > You can write code to guard against this if you want: > > > class A: > > legal = set(["x"]) > > def __setattr__(self,attr,val): > > if attr not in self.legal: > > raise AttributeError("A object has no attribute '%s'" % attr) > > self.__dict__[attr] = val > > def __init__(self,x): > > self.y = x > > > I suspect most people who go into Python doing something like this > > soon abandon it when they see how rarely it actually catches anything. > > > Carl Banks > > '__slots__' is better: > class A(object): > __slots__ = set(["x"]) > def __init__(self, x): > self.y = x > > this will do the same, only faster>>> A(1) > > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in __init__ > AttributeError: 'A' object has no attribute 'y' However, if you subclass your version of A that uses __slots__, the subclass will once again allow all attribute access, whereas if you subclass my version of A that uses __getattr__, it will still be restricted to the allowed symbols (unless you were to override the list of symbols, which you probably would). The latter behavior is less surprising and less dangerous, which (besides the questionable usage) is the main reason using __slots__ is not recommended for this purpose. (Having said that, I do admit to using __slots__ for this purpose once. But, the confusing aspects of __slots__ were managed by a metaclass and hidden from the user.) Carl Banks From deets at nospam.web.de Thu Sep 25 16:36:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:36:15 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: References: Message-ID: <6k2b1vF5inqbU1@mid.uni-berlin.de> Nick Craig-Wood schrieb: > Scott Sharkey wrote: > B> Our development group at work seems to be heading towards adopting >> python as one of our standard "systems languages" for internal >> application development (yeah!). One of the issues that's come up is >> the problem with apt (deb packages) vs eggs, vs virtual environments. >> We're probably gonna end up using Pylons or TurboGears for web-based >> apps, and I've recommended virtualenv, but one of the other developers >> has had some "inconsistencies" when mixing systems with python installed >> from apt (all our servers are debian or ubuntu based) vs when installed >> under virtualenv. >> >> I have basically recommended that we only install the python base (core >> language) from apt, and that everything else should be installed into >> virtual environments. But I wanted to check to see how other enterprises >> are handling this issue? Are you building python from scratch, or using >> specific sets of .deb packages, or some other process. >> >> Any insight into the best way to have a consistent, repeatable, >> controllable development and production environment would be much >> appreciated. > > I'll admit to not knowing what you mean by virtual environment... virtualenv is a simple tool to create isolated python environments where you can install whatever packages you like without interfering with other installations, even allowing to install conflicting package versions (per VE of course they must be without conflicts). Diez From andy_westken at hotmail.com Thu Sep 11 12:09:52 2008 From: andy_westken at hotmail.com (andy_westken at hotmail.com) Date: Thu, 11 Sep 2008 09:09:52 -0700 (PDT) Subject: Enumerating ordered expat attributes with tuplets? References: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> Message-ID: On Sep 11, 4:48?pm, Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Ah, well. Don't know whether it meets your aesthetic standards, but: > ?>>> my_list = ['tree', 'hug', 'flower', 'hug', 'bear', 'run'] > ?>>> my_list[0:len(a):2] > ['tree', 'flower', 'bear'] > ?>>> my_list[1:len(a):2] > ['hug', 'hug', 'run'] > > and hence > > ?>>> zip(my_list[0:len(a):2], my_list[1:len(a):2]) > [('tree', 'hug'), ('flower', 'hug'), ('bear', 'run')] > > and furthermore > > ?>>> for a, b in zip(my_list[0:len(a):2], my_list[1:len(a):2]): > ... ? ? print a, b > ... > tree hug > flower hug > bear run > > or the slightly less obfuscated: > > ?>>> for index in range(0, len(my_list), 2): > ... ? ? print my_list[index], my_list[index + 1] > ... ? ? > tree hug > flower hug > bear run > > On Sep 11, 2008, at 5:19 PM, andy_west... at hotmail.com wrote: > > > > > > > On Sep 11, 4:04 pm, Manuel Ebert wrote: > >> -----BEGIN PGP SIGNED MESSAGE----- > >> Hash: SHA1 > > >> Hi Andy, > > >> by the looks of it I'd say that the problem is that the second > >> parameter you passed to start_element is not a dictionary at all (the > >> clue is in the "AttributeError: 'LIST' object" ...). > > >> ?>>> d = ['tree', 'house'] > >> ?>>> start_element("Thing", d) > >> Thing : > >> AttributeError: 'list' object has no attribute 'items' > >> ?>>> d = {'tree': 'hug', 'flower' : 'eat'} > >> ?>>> start_element("Thing", d) > >> Thing : ? flower="eat" ?tree="hug" > > >> Manuel > > >> On Sep 11, 2008, at 4:21 PM, andy_west... at hotmail.com wrote: > > >>> Hi > > >>> I'm new to Python and trying to pick up good, idiomatic usage right > >>> from the offset. > > >>> As I was familiar with Expat from C++ (directly and via expatpp) I'm > >>> trying to write a little script - using xml.parsers.expat - to ? > >>> search > >>> and replace XML attribute values. > > >>> As I want the attributes to stay in order when the file is ? > >>> written out > >>> (so I can check my results with a diff tool) I've set the parser's > >>> ordered_attributes attribute. But this has stopped the for loop > >>> working with the tuplets. > > >>> The relevant bit of code in my little test, using the default > >>> Dictionary for the attributes, is: > > >>> def start_element(name, attrs): > >>> ? ? print "%s : " % name, > >>> ? ? for (a,b) in attrs.items(): > >>> ? ? ? ? print " %s=\"%s\"" % (a,b), > > >>> But when I set ordered_attributes, first it doesn't like the items() > > >>> ? ? AttributeError: 'list' object has no attribute 'items' > > >>> And then it doesn't like the tuple > > >>> ? ? ValueError: too many values to unpack > > >>> Do I have keep track of where I am (name, value, name, value, ...) > > >>> Or is there a way I can solve the problem with a tuple? > > >>> Thanks, Andy > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > > >> -----BEGIN PGP SIGNATURE----- > >> Version: GnuPG v1.4.7 (Darwin) > > >> iD8DBQFIyTOLcZ70OCIgLecRAsBrAJ9YSa7f+YTyM1yRmEKw8KBtb2klIgCgjNzw > >> F295Tik+45eNHnJ3B4kKnWU= > >> =xR4m > >> -----END PGP SIGNATURE------ Hide quoted text - > > >> - Show quoted text - > > > Sorry! > > > I forgot to mention that when you set the parser's ordered_attributes > > attribute, it sends the "attrs" to start_element as a list, not a > > dictionary, in the order name, value, name, value, ... > > > Andy > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (Darwin) > > iD8DBQFIyT25cZ70OCIgLecRAmWqAJ4zEy8gatIh4CqKpJxZwACs9BBxgwCfaPoQ > QfmRVzHqwJFu3WnjCM0TJYo= > =9z6U > -----END PGP SIGNATURE------ Hide quoted text - > > - Show quoted text - Thanks! Regarding aesthetics - I don't need it to look pretty: I want it to be understandable to people who know Python (?), and then as efficient as possible. Of the two examples about (the 'zip' solution and the 'range' solution), is there much difference in performance? Andy From dblubaugh at belcan.com Tue Sep 30 13:21:51 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 30 Sep 2008 13:21:51 -0400 Subject: OS.SYSTEM ERROR !!! Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> To All, I have been attempting to execute the following program within the Python environment: Myprogram.exe, which means this is an executable file!! I would usually execute this program (with the appropriate arguments) by going to following directory within MS-DOS (Windows XP): C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 The executable would execute perfectly. However, when I would try to execute the following lines of source code within a python script file: import os os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") The executable file would start to execute until it would print an error stating that it cannot use a (.dat) file, which is located under the following directory: C:\myprogramfolder\run\inputs\io\control.dat I believe I may be missing something here that prevents the executable file working within python from utilizing this (.dat). The printed final error is the following: ERROR opening inputs/io/control.dat Does anyone know what that could be ?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From steve at holdenweb.com Thu Sep 18 12:58:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Sep 2008 12:58:54 -0400 Subject: Extracting hte font name from a TrueType font file Message-ID: Does anyone have a Python recipe for this? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gboutsioukis at gmail.com Sat Sep 27 09:31:40 2008 From: gboutsioukis at gmail.com (George Boutsioukis) Date: Sat, 27 Sep 2008 13:31:40 +0000 (UTC) Subject: Using the 'with' statement with cStringIO objects References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> Message-ID: <1222522300.659080@athprx04> > So, I'm guessing you can't use the 'with' statement with cStringIO > objects? Is this a bug, or do I need to use the 'with' statement > differently to get this to work? > > Thanks, > peppergrower Neither, just not implemented. Only classes with __enter__ and __exit__ methods(ie context manager types) can be used in with statements. And, correct me if I'm wrong, I think it's pointless for a StringIO object to have those. From st1999 at gmail.com Sun Sep 28 14:03:34 2008 From: st1999 at gmail.com (robean) Date: Sun, 28 Sep 2008 11:03:34 -0700 (PDT) Subject: urllib2 and exceptions Message-ID: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> Hi everyone, I have a question about using urllib2. I like urllib2 better than urllib at least in part because it has more elaborate support for handling errors: there is built in support for URLError (for faulty urls) and HTTPError (for http errors that might originate from, say, passing an invalid stock-ticker in the program below). However I can get neither to work. I'm attaching below the (very short) code: can anyone point out what I'm doing wrong? Now, if I replace the URLError and HTTPError with IOError (the class from which both URLError and HTTPError inherit), the program works fine. Why is it that I can call the generic IOError class, but none of the Error classes derived from that? These are clearly defined in the urllib2 manual. Very confused... Here's the code: import urllib2 # read stock information from yahoo finance for Traget (TGT) goodTicker = 'TGT' # program works with this badTicker = 'TGTttttttt' # python doesn't understand either HTTPError or URLError with this url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker try: handle = urllib2.urlopen(url) # this does not work except HTTPError, e: print "There was an http error" print e # this also does not work except URLError, e: print "There is a problem with the URL" print e exit(1) #this works except IOError, e: print "You have an IOError" print e text = handle.readlines()[:20] for line in text: print line From sbassi at clubdelarazon.org Tue Sep 9 09:16:59 2008 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Tue, 9 Sep 2008 10:16:59 -0300 Subject: biopython In-Reply-To: <9e2f512b0809090614n7d57850cn14ba44dad0af3757@mail.gmail.com> References: <9e2f512b0809090614n7d57850cn14ba44dad0af3757@mail.gmail.com> Message-ID: <9e2f512b0809090616h2c8128cawacdc802924b286b2@mail.gmail.com> On 9/9/08, Beema Shafreen wrote: > I am using Biopython to fetch pumed Id's ,The module i use is (from Bio > import Entrez) > But i am getting this error >>>> from Bio import Entrez > Traceback (most recent call last): > File "", line 1, in ? > ImportError: cannot import name Entrez Looks like is bad installed. It works for me: /home/user/MMC-SD/Kingston/py252/bin> ./python2.5 Python 2.5.2 (r252:60911, Jul 7 2008, 16:11:08) [GCC 3.3.5 (Debian 1:3.3.5-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Bio import Entrez >>> dir(Entrez) ['File', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '_open', 'efetch', 'egquery', 'einfo', 'elink', 'epost', 'esearch', 'espell', 'esummary', 'os', 'query', 'read', 'time', 'urllib'] -- Sebasti?n Bassi. Diplomado en Ciencia y Tecnolog?a. Vendo isla: http://www.genesdigitales.com/isla What's new in Python 3: http://tinyurl.com/5cd89r Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 From larry.bates at vitalEsafe.com Sat Sep 13 11:45:30 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 13 Sep 2008 10:45:30 -0500 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: Message-ID: Marco Bizzarri wrote: > On Sat, Sep 13, 2008 at 4:11 PM, Fredrik Lundh wrote: >> Marco Bizzarri wrote: >> >>> class FolderInUse: >>> >>> def true_for(self, archivefolder): >>> return any([instance.forbid_to_close(archivefolder) for instance in >>> self.core.active_outgoing_registration_instances()]) >>> >>> Is this any better? The true_for name does not satisfy me a lot... >> well, "true_for" is indeed pretty inscrutable, but I'm not sure that would >> be the first thing I'd complain about in that verbose mess... > > "verbose mess". > > It is always frustrating when you do what you think is your best and > you read that. > > Anyway: I'm here to learn, and, of course, part of it is to listen > those who've been there much longer than you. > > So, thanks for your sincere evaluation, Fredrik :-). > >> (when you pick method names, keep in mind that the reader will see the >> context, the instance, and the arguments at the same time as they see the >> name. there's no need to use complete sentences; pick short short >> descriptive names instead.) > > Maybe I'm looking at the wrong direction, right now. From the point of > view of the FolderInUse clients, they will do: > > condition = FolderInUse(core) > > condition.true_for(folder) > > Is this too verbose? This is not a polemic statement, I'm really > asking your opionion. > > The expression inside the true_for is indeed complex, and maybe I can > simplify it; however, I'm deeply convinced that > > instance.forbid_to_close(folder) > > has some good points on it; I mean, once I read this kind of code, I > can hope to understand it without looking at what forbid_to_close > does. > > >> >> > >>> class FolderInUse: >>> >>> def true_for(self, archivefolder): >>> return any([instance.forbid_to_close(archivefolder) for instance in >>> self.core.active_outgoing_registration_instances()]) IMHO it reads better if you use the __call__ method of the class to return the value and rewrite it as a regular loop for clarity. Sometimes the simplest way is the easiest to read. class FolderInUse: def __call__(self, archivefolder): result = False for instance in self.core.active_outgoing_registration_instances(): if instance.forbid_to_close(archivefolder): result = True break return result Then it can be called with: if FolderInUse(archivefolder): ... -Larry From fredrik at pythonware.com Thu Sep 18 16:28:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Sep 2008 22:28:24 +0200 Subject: Extracting hte font name from a TrueType font file In-Reply-To: References: Message-ID: Steve Holden wrote: > Does anyone have a Python recipe for this? >>> from PIL import ImageFont >>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1) >>> f.font.family 'Verdana' >>> f.font.style 'Italic' From tino at wildenhain.de Sat Sep 13 04:41:36 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 13 Sep 2008 10:41:36 +0200 Subject: question about python In-Reply-To: <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> References: <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> Message-ID: <48CB7CC0.4040902@wildenhain.de> fishfin wrote: > @ Carl: Yes, I think your right now that I look at it (or at least all > except for the last two lines need to be indented). > I'm still not sure > how to send the stuff to the web browser though. what do you think is the cfile.write() doing? As a hint, beside having a look at rfc2616 and friends, get something like wiresharc to see how HTTP requests work in real world. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From maebert at uos.de Thu Sep 11 11:48:09 2008 From: maebert at uos.de (Manuel Ebert) Date: Thu, 11 Sep 2008 17:48:09 +0200 Subject: Enumerating ordered expat attributes with tuplets? In-Reply-To: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> References: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> Message-ID: <06159E9A-4E49-48AA-B288-BEF41922F2FC@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Ah, well. Don't know whether it meets your aesthetic standards, but: >>> my_list = ['tree', 'hug', 'flower', 'hug', 'bear', 'run'] >>> my_list[0:len(a):2] ['tree', 'flower', 'bear'] >>> my_list[1:len(a):2] ['hug', 'hug', 'run'] and hence >>> zip(my_list[0:len(a):2], my_list[1:len(a):2]) [('tree', 'hug'), ('flower', 'hug'), ('bear', 'run')] and furthermore >>> for a, b in zip(my_list[0:len(a):2], my_list[1:len(a):2]): ... print a, b ... tree hug flower hug bear run or the slightly less obfuscated: >>> for index in range(0, len(my_list), 2): ... print my_list[index], my_list[index + 1] ... tree hug flower hug bear run On Sep 11, 2008, at 5:19 PM, andy_westken at hotmail.com wrote: > On Sep 11, 4:04 pm, Manuel Ebert wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Hi Andy, >> >> by the looks of it I'd say that the problem is that the second >> parameter you passed to start_element is not a dictionary at all (the >> clue is in the "AttributeError: 'LIST' object" ...). >> >> >>> d = ['tree', 'house'] >> >>> start_element("Thing", d) >> Thing : >> AttributeError: 'list' object has no attribute 'items' >> >>> d = {'tree': 'hug', 'flower' : 'eat'} >> >>> start_element("Thing", d) >> Thing : flower="eat" tree="hug" >> >> Manuel >> >> On Sep 11, 2008, at 4:21 PM, andy_west... at hotmail.com wrote: >> >> >> >> >> >>> Hi >> >>> I'm new to Python and trying to pick up good, idiomatic usage right >>> from the offset. >> >>> As I was familiar with Expat from C++ (directly and via expatpp) I'm >>> trying to write a little script - using xml.parsers.expat - to >>> search >>> and replace XML attribute values. >> >>> As I want the attributes to stay in order when the file is >>> written out >>> (so I can check my results with a diff tool) I've set the parser's >>> ordered_attributes attribute. But this has stopped the for loop >>> working with the tuplets. >> >>> The relevant bit of code in my little test, using the default >>> Dictionary for the attributes, is: >> >>> def start_element(name, attrs): >>> print "%s : " % name, >>> for (a,b) in attrs.items(): >>> print " %s=\"%s\"" % (a,b), >> >>> But when I set ordered_attributes, first it doesn't like the items() >> >>> AttributeError: 'list' object has no attribute 'items' >> >>> And then it doesn't like the tuple >> >>> ValueError: too many values to unpack >> >>> Do I have keep track of where I am (name, value, name, value, ...) >> >>> Or is there a way I can solve the problem with a tuple? >> >>> Thanks, Andy >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> -----BEGIN PGP SIGNATURE----- >> Version: GnuPG v1.4.7 (Darwin) >> >> iD8DBQFIyTOLcZ70OCIgLecRAsBrAJ9YSa7f+YTyM1yRmEKw8KBtb2klIgCgjNzw >> F295Tik+45eNHnJ3B4kKnWU= >> =xR4m >> -----END PGP SIGNATURE------ Hide quoted text - >> >> - Show quoted text - > > Sorry! > > I forgot to mention that when you set the parser's ordered_attributes > attribute, it sends the "attrs" to start_element as a list, not a > dictionary, in the order name, value, name, value, ... > > Andy > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIyT25cZ70OCIgLecRAmWqAJ4zEy8gatIh4CqKpJxZwACs9BBxgwCfaPoQ QfmRVzHqwJFu3WnjCM0TJYo= =9z6U -----END PGP SIGNATURE----- From joncle at googlemail.com Wed Sep 10 14:03:05 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 11:03:05 -0700 (PDT) Subject: Reading binary data References: <508e31d9-daab-4346-9441-55cc47f7c1f4@m44g2000hsc.googlegroups.com> <54d64616-b86c-45bd-a8b5-4332faa5a73d@a70g2000hsh.googlegroups.com> Message-ID: On Sep 10, 6:45?pm, Aaron Scott wrote: > > CORRECTION: '3cII' should be '3sII'. > > Even with the correction, I'm still getting the error. Me being silly... Quick fix: signature = file.read(3) then the rest can stay the same, struct.calcsize('3sII') expects a 12 byte string, whereby you only really have 11 -- alignment and all that... Jon. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 28 03:52:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 07:52:56 GMT Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Message-ID: <00ef3194$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote: > Hello all, > > To me, this is a somewhat unintuitive behavior. I want to discuss the > parts of it I don't understand. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= lambda: n > ... >>>> f[0]() > 9 >>>> f[1]() > 9 > > I guess I can accept this part so far, though it took a little getting > used to. I'm writing some code and found the following workaround, but > I don't think it should give different results. Maybe I'm not > understanding some of the details of closures. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= (lambda n: ( lambda: n ) )( n ) > ... >>>> f[0]() > 0 >>>> f[1]() > 1 > > Which is of course the desired effect. Why doesn't the second one just > look up what 'n' is when I call f[0], and return 9? That's an awfully complicated solution. A much easier way to get the result you are after is to give each function its own local copy of n: f[n] = lambda n=n: n As for why the complicated version works, it may be clearer if you expand it from a one-liner: # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) inner = lambda: n outer = lambda n: inner f[n] = outer(n) outer(0) => inner with a local scope of n=0 outer(1) => inner with a local scope of n=1 etc. Then, later, when you call inner() it grabs the local scope and returns the number you expected. -- Steven From spamcomefindmeplease at gmail.com Sat Sep 27 18:28:49 2008 From: spamcomefindmeplease at gmail.com (peppergrower) Date: Sat, 27 Sep 2008 15:28:49 -0700 (PDT) Subject: Using the 'with' statement with cStringIO objects References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> <1222522300.659080@athprx04> <87zllt7h72.fsf@mulj.homelinux.net> Message-ID: Thanks for the help. I'm fairly new to programming (which you probably could have guessed...). When I realized that you could use a StringIO instance as if it were a file, I wanted to try some of the same techniques on it as I would with a file. In this case, I wanted to use a "for line in testfile" construction to iterate over the StringIO instance. (I did find a better way for my particular case, one that didn't involve StringIO at all.) When I got that particular error, I suspected that it had something to do with the relative newness of the 'with' statement. If this is something that should be considered for addition in the future, is there somewhere specific I should suggest that? From chapagainanish at yahoo.com Wed Sep 3 05:42:26 2008 From: chapagainanish at yahoo.com (chapagainanish) Date: Wed, 03 Sep 2008 09:42:26 -0000 Subject: installing matplotlib with numpy and scipy for Python in Cygwin Message-ID: Hi!! I'm having installation problem for installing numpy and scipy in Cygwin for Python, and am obstruct in madway for project, i followed scipy.org guidelines but there's few error thrown as failed..with exit status 1 please if someone has installed these module help me thank's and regard's Anish From liuyuprc at gmail.com Sun Sep 14 07:19:12 2008 From: liuyuprc at gmail.com (liuyuprc) Date: Sun, 14 Sep 2008 04:19:12 -0700 (PDT) Subject: Why some blog entries at MSN Space support rss feed while others don't? Message-ID: Not sure if this is the place this question should even be raised, but I am deeply troubled by this problem for days. I am now desperate. When i tried to add the blogs at MSN Space of my friends' to google reader, some of them don't support rss feed, so i cannot add them. You guys have any idea how to enable RSS at one's blog entry so it can be subscribed? thanks! From arnodel at googlemail.com Sun Sep 14 05:31:16 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Sep 2008 02:31:16 -0700 (PDT) Subject: recursion gotcha? References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> <3f0d61c40809140108n515006dci87f91dcd971f0169@mail.gmail.com> Message-ID: <3b4a73bd-672e-44a5-a364-6b9a165628f5@e39g2000hsf.googlegroups.com> On Sep 14, 9:44?am, "Marco Bizzarri" wrote: > On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri > > > > wrote: > > On Sun, Sep 14, 2008 at 10:01 AM, cnb wrote: > >> this recursive definition of sum thrumped me, is this some sort of > >> gotcha or am I just braindead today? > >> and yes i know this is easy a a for x in xs acc += x or just using the > >> builtin. > > >> def suma(xs, acc=0): > >> ? ? ? ?if len(xs) == 0: > >> ? ? ? ? ? ? ? ?acc > >> ? ? ? ?else: > >> ? ? ? ? ? ? ? ?suma(xs[1:], acc+xs[0]) > > > You're just missing the "return" statements? > > > def suma(xs, acc=0): > > ? ? ? if len(xs) == 0: > > ? ? ? ? ? ? ?return acc > > ? ? ? else: > > ? ? ? ? ? ? ?return suma(xs[1:], acc+xs[0]) > > Besides: you can avoid the "acc" parameter: > > def suma(xs): > ? ? if len(xs) == 0: > ? ? ? ? return 0 > ? ? else: > ? ? ? ? return xs[0] + suma(xs[1:]) > I think the OP tried to make it tail-recursive, which of course has no benefit in Python. In fact it looks like a Scheme implementation of sum translated literally to Python. In Python this algorithm is expressed naturally as: def suma(xs): acc = 0 for x in xs: acc += x return acc -- Arnaud From grante at visi.com Wed Sep 10 13:48:01 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 12:48:01 -0500 Subject: md5 differences References: Message-ID: <8K6dnVeoxJTMlVXVnZ2dnUVZ_j6dnZ2d@posted.visi> On 2008-09-10, Wojtek Walczak wrote: > On Wed, 10 Sep 2008 12:39:24 -0500, Grant Edwards wrote: > >>> The strange thing is that >>>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >>> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. >> >> Same here. > > I guess it will be the same for vast majority of us ;-) > The question is why is it '90364ed45b452d43378629c20543a81d' > for the OP? :-) The smart money is betting on "because the OP goofed when he was cutting/pasting stuff from his terminal window into his posting." -- Grant Edwards grante Yow! Were these parsnips at CORRECTLY MARINATED in visi.com TACO SAUCE? From deets at nospam.web.de Thu Sep 4 07:00:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Sep 2008 13:00:57 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: Message-ID: <6i9tftFpi1lhU1@mid.uni-berlin.de> Marco Bizzarri wrote: > Let's say I've a class a, where I can write: Anticipating this obviously premature posting: http://dirtsimple.org/2004/12/python-is-not-java.html Diez From akineko at gmail.com Mon Sep 1 18:45:19 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 15:45:19 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp Message-ID: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Hi everyone, This is a memorandum so that other people can share the info. The following methods are declared in the Tkinter Button class. tkButtonDown(), tkButtonEnter(), tkButtonInvoke(), tkButtonLeave(), tkButtonUp() However, they are not working, when you try, you will get: _tkinter.TclError: invalid command name "tkButtonLeave" The bindings in the Tkinter are mapping them to non-existing tk methods. I needed to use the method badly and I couldn't find any clear solution for this. So, I spent time to solve this. tkButtonLeave(), for example, is declared as follows: Tkinter.py line 2005 of 3759 def tkButtonLeave(self, *dummy): self.tk.call('tkButtonLeave', self._w) Now, in the Tk source distribution, I found the following: unsupported.tcl # Commands provided by Tk without official support. Use them at your # own risk. They may change or go away without notice. namespace eval ::tk::unsupported { # Map from the old global names of Tk private commands to their # new namespace-encapsulated names. variable PrivateCommands array set PrivateCommands { tkButtonAutoInvoke ::tk::ButtonAutoInvoke tkButtonDown ::tk::ButtonDown tkButtonEnter ::tk::ButtonEnter tkButtonInvoke ::tk::ButtonInvoke tkButtonLeave ::tk::ButtonLeave tkButtonUp ::tk::ButtonUp ... snip ... This seems suggesting that the Tkinter bindings are binding obsolete tk methods. And, the method should be called seems ::tk::ButtonLeave, instead. I placed the following into my Tkinter code and it worked. self.btn.tk.call('::tk::ButtonLeave', self.btn._w) // Summary: (1) tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp are not working. (2) Bindings are not correct (2) Workaround is call correct tk methods directly I hope future Tkinter will be corrected so that the methods are available as documented. Best regards, Aki- From skip at pobox.com Sun Sep 21 22:28:36 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 21 Sep 2008 21:28:36 -0500 Subject: pause between the loops In-Reply-To: <37b964200809211902r206e951ep8d83cad88c93d45f@mail.gmail.com> References: <37b964200809211902r206e951ep8d83cad88c93d45f@mail.gmail.com> Message-ID: <18647.724.773230.535318@montanaro-dyndns-org.local> Jackie> can I ask python to stop for, say, 5mins, after it go through Jackie> loop i=0 before it starts loop i=1? import time for i in range(10): time.sleep(5) # seconds Skip From benjamin at dromaludaire.info Tue Sep 16 05:57:19 2008 From: benjamin at dromaludaire.info (Benjamin Sigonneau) Date: Tue, 16 Sep 2008 11:57:19 +0200 Subject: on-the-fly translation with gettext Message-ID: <87od2opg5c.fsf@lapinot.localdomain> Hi all, I'm a complete beginner in python and in GUI designing, yet I'm writing a GUI using python and Tkinter. I need it to be available both in french and english, so I read the Fine Manual and gave a try to gettext. So far, I've managed to translate my app with the following snippet: | import gettext | def install_lang (lang): | try: | t = gettext.translation(domain = 'mydomain', localedir = 'locale', | languages = [lang]) | t.install() | except IOError: | import __builtin__ | __builtin__.__dict__['_'] = lambda x: x When I issue an install_lang('en') at the beginning of my program, it is translated in english and, conversely, an install_lang('fr') at the beginning makes it available in french. However, I'd like to let the user show the language on-the-fly during execution. Having read the Python Library Reference, sec. 21.1.3.3 (see http://docs.python.org/lib/node740.html), I added a menu with two radiobuttons and I merely set them up to call install_lang: | app_lang = StringVar() | app_lang.set('en') | langmenu = Menu(root) | langmenu.add_radiobutton(label = "English", variable = app_lang, value = 'en', | command = lambda l = 'en': install_lang(l)) | langmenu.add_radiobutton(label = "French", variable = app_lang, value = 'fr', | command = lambda l = 'fr': install_lang(l)) However, there is no magic. The language of the application remains unchanged. If it was defined to be english at startup, so will it remain. Conversely, it will stay in french if this was the language at startup. Does somebody has any idea of what I'm doing wrong, and how to fix it? Thanks. -- benjamin From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 11:28:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 17:28:05 +0200 Subject: finding domain name In-Reply-To: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> References: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> Message-ID: <48d90afd$0$12015$426a74cc@news.free.fr> Bobby Roberts a ?crit : > On Sep 23, 9:10 am, Tino Wildenhain wrote: >> Bobby Roberts wrote: >>>> Depends on the technology/web framework. If you use WSGI, you should use >>>> something like: >>>> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] >>>> -- Gerhard >>> Yeah i already tried environ("SERVER_NAME") but get a key error when i >>> do. >> You could output the whole environ to see what you get and how it is called. >> >> I'd recommend however to check that you are using a configured value and >> not something sent by the client if you are going to use it during >> filesystem lookup. >> >> Regards >> Tino >> >> smime.p7s >> 4KViewDownload > > evidently the environ dictionary is off limits on our server. ??? > It can't > be that tough in python to get the current complete url being viewed. > It's a snap in asp(which is my background). Please don't compare apples to roller-skates. asp is a mix of libraries, components and whatever, while Python is a language. From calebjhansen at gmail.com Sat Sep 13 04:00:59 2008 From: calebjhansen at gmail.com (fishfin) Date: Sat, 13 Sep 2008 01:00:59 -0700 (PDT) Subject: question about python References: Message-ID: <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> @ Carl: Yes, I think your right now that I look at it (or at least all except for the last two lines need to be indented). I'm still not sure how to send the stuff to the web browser though. Thanks for pointing it out! @ Diez: I'll start googling those right away. Carl Banks wrote: > On Sep 13, 12:15 am, fishfin wrote: > > I was working through a tutorial about how to write a server using > > python (the url is bellow). I am sure that the server is working to > > some degree because when the server is running localhost:8080 just > > keeps trying to load until it times out. I would like to know how to > > send information through the server to my browser? > > > > I was working through this tutorial:http://python.about.com/od/networkingwithpython/ss/PythonWebServer.htm > > > > and my final code is like this: > > > > import socket > > > > host = '' > > port = 8080 > > > > c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > > > > c.bind((host, port)) > > > > c.listen(1) > > > > while 1: > > csock, caddr = c.accept() > > cfile = csock.makefile('rw', 0) > > It looks like everything after this line needs to be indented. > Besides that, nothing jumps out at me, though I don't do direct socket > programming a lot. > > > line = cfile.readline().strip() > > > > cfile.write('HTTP/1.0 200 OK\n\n') > > cfile.write('Welcome %s!' % > > (str(caddr))) > > cfile.write('

Follow the link...

') > > cfile.write('All the server needs to do is ') > > cfile.write('to deliver the text to the socket. ') > > cfile.write('It delivers the HTML code for a link, ') > > cfile.write('and the web browser converts it.



') > > cfile.write('
Click me!
') > > cfile.write('

The wording of your request was: "%s"' %(line)) > > cfile.write('') > > > > cfile.close() > > csock.close() > > > Carl Banks From michael.pearmain at tangozebra.com Tue Sep 2 11:04:51 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 2 Sep 2008 08:04:51 -0700 (PDT) Subject: dict.update Message-ID: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> Hi All, I have two dictionaries e.g dict1 = {123:3,234:5,456:3} dict2 = {123:4,157:2,234:5,456:3,567:2} I want to merge these two dictionaries together so i have a resultant dictionary of: dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]} As later on i want to write a csv file that would have the form id var1 var2 123 4 3 157 2 0 i looks like the dict.update looks almost there but i can't get it to work properly, can anyone offer any advise? From st1999 at gmail.com Sun Sep 28 15:52:58 2008 From: st1999 at gmail.com (robean) Date: Sun, 28 Sep 2008 12:52:58 -0700 (PDT) Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> Message-ID: <357e734f-e99f-41e5-9cac-083d636a23e1@n38g2000prl.googlegroups.com> On Sep 28, 12:27?pm, robean wrote: > On Sep 28, 12:11?pm, "Chris Rebert" wrote: > > > > > On Sun, Sep 28, 2008 at 11:03 AM, robean wrote: > > > Hi everyone, > > > > I have a question about using urllib2. > > > > I like urllib2 better than urllib at least in part because it has more > > > elaborate support for handling errors: there is built in support for > > > URLError (for faulty urls) and HTTPError (for http errors that might > > > originate from, say, passing an invalid stock-ticker in the program > > > below). ?However I can get neither to work. ?I'm attaching below the > > > (very short) code: can anyone point out what I'm doing wrong? > > > > Now, if I replace the URLError and HTTPError with IOError (the class > > > from which both URLError and HTTPError inherit), the program works > > > fine. Why is it that I can call the generic IOError class, but none of > > > the Error classes derived from that? These are clearly defined in the > > > urllib2 manual. Very confused... > > > > Here's the code: > > > > import urllib2 > > > > # read stock information from yahoo finance for Traget (TGT) > > > goodTicker = 'TGT' # program works with this > > > badTicker = 'TGTttttttt' # python doesn't understand either HTTPError > > > or URLError with this > > > > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > > > try: > > > ? ? ? ?handle = urllib2.urlopen(url) > > > > # this does not work > > > except HTTPError, e: > > > ? ? ? ?print "There was an http error" > > > ? ? ? ?print e > > > > # this also does not work > > > except URLError, e: > > > ? ? ? ?print "There is a problem with the URL" > > > ? ? ? ?print e > > > ? ? ? ?exit(1) > > > > #this works > > > except IOError, e: > > > ? ? ? ?print "You have an IOError" > > > ? ? ? ?print e > > > > text = handle.readlines()[:20] > > > for line in text: > > > ? ? ? ?print line > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > My Python begs to differ: > > > #tmp.py > > import urllib2 > > > badTicker = 'TGTttttttt' > > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > > try: > > ? ? handle = urllib2.urlopen(url) > > > except urllib2.HTTPError, e: > > ? ? print "There was an http error" > > ? ? print e > > > except urllib2.URLError, e: > > ? ? print "There is a problem with the URL" > > ? ? print e > > > except urllib2.IOError, e: > > ? ? print "You have an IOError" > > ? ? print e > > > #in the shell > > $ python -V > > Python 2.5.1 > > $ python Desktop/tmp.py > > There was an http error > > HTTP Error 404: Not Found > > > Are you using an outdated version of Python perhaps? > > > Regards, > > Chris > > > -- > > Follow the path of the Iguana...http://rebertia.com > > Then I expect that it is most likely my version of python that is > causing the problem. I'm using 2.5.2. Actually, the problem seems to be that IOError is in my namespace, but the other error classes are not. So, except HTTPError, etc. fails, but except urllib2.HttpError, etc. works fine. Now, I still don't understand why these classes shouldn't automatically work.... From bmihelac at gmail.com Fri Sep 12 11:46:56 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Fri, 12 Sep 2008 08:46:56 -0700 (PDT) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <43cbb6e3-d463-4cf0-a05a-62c78b02a5f3@25g2000hsx.googlegroups.com> On Sep 12, 5:35?pm, Wojtek Walczak wrote: > On Fri, 12 Sep 2008 08:08:18 -0700 (PDT), Bojan Mihelac wrote: > > Hi all - when trying to set some dynamic attributes in class, for > > example: > > > class A: > > ? ? for lang in ['1', '2']: > > ? ? ? ? exec('title_%s = lang' % lang) #this work but is ugly > > ? ? ? ? # setattr(A, "title_%s" % lang, lang) # this wont work > > I guess A class not yet exists in line 4. Is it possible to achive > > adding dynamic attributes without using exec? > > Yes, it is: > > ------------- > class A: > ? ?for i in (1, 2): > ? ? ? locals()['xxx%d' % (i)] = i > > print A.xxx1 > print A.xxx2 > a = A() > print a.xxx1 > print a.xxx2 > ------------- > > And the output is: > > ----- > 1 > 2 > 1 > 2 > ----- > > But I definitely don't consider this one as a good programming > practice. > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ thnx Wojtek, this works! From ezra.taylor at gmail.com Tue Sep 30 14:13:02 2008 From: ezra.taylor at gmail.com (Ezra Taylor) Date: Tue, 30 Sep 2008 14:13:02 -0400 Subject: [Tutor] Replacing cmd.exe with custom .py application In-Reply-To: References: Message-ID: Joseph: Check out subprocess. The subprocess module is on python 2.4. Also, use subprocess.call("your command",shell=True) On Linux/Unix, the process is below import subprocess ret = subprocess.call("dir",shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT) print ret You should get a return value of 0. Which means that it was successful. I'm still learning this myself, so some of these other guys might have more input. On Tue, Sep 30, 2008 at 10:32 AM, A. Joseph wrote: > > > Instead of going to the command line all the time, I want to create a small > customized cmd.exe of my own, how can I get the return value from > os.system() because I was thinking I can do soothing with os.system(), In > case my question is not clear, just like an IDE that plugged in another > .exe application. > > > > Sorry for any mistake in my question. Just help me if you can > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Ezra Taylor From darcy at druid.net Fri Sep 26 12:38:48 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 26 Sep 2008 12:38:48 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> Message-ID: <20080926123848.98c06cd5.darcy@druid.net> On Fri, 26 Sep 2008 11:00:59 -0500 "Michael Mabin" wrote: > So we can drop a table in an in clause? How is this a use case. Cartoons > are funny but actual proof that this example using an in-clause provides an > exploit would be more helpful I think. I'm not sure what proof you require. If you program such that users can enter arbitrary stings into your database it is obvious that the exploit in that cartoon can be used against you. And the point is that it has nothing to do with IN clauses. It can be any SQL. Go read that cartoon carefully. It says nothing about IN clauses. Consider; "UPDATE student SET name = '%s' WHERE student_id = %s" % (name, id); Now set name to "Robert'; DROP TABLE student;" and see what happens if you feed that to your SQL database. Hell, just put "';" in the string for fun. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From siegfried at heintze.com Sat Sep 13 21:27:22 2008 From: siegfried at heintze.com (Siegfried Heintze) Date: Sat, 13 Sep 2008 18:27:22 -0700 Subject: Python a good choice for experimenting with Win32 API? References: <98qdnS2nk4rpEVfVnZ2dnUVZ_qHinZ2d@comcast.com> <09601c7a-a138-4163-9265-286f87ef5767@y21g2000hsf.googlegroups.com> Message-ID: I found this but have not tried it yet: http://aspn.activestate.com/ASPN/Mail/Message/ActivePython/1775844 How different is ActiveState Python from CPython? Can they both be used with pywin32 and the other packages? Thanks! Siegfried From bj_666 at gmx.net Tue Sep 9 09:39:20 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Sep 2008 13:39:20 GMT Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: <6inck8Frl5ktU1@mid.uni-berlin.de> On Tue, 09 Sep 2008 08:19:04 -0500, Larry Bates wrote: >> I really dont care if the expression is optimal. So the goal is >> something like: >> >> vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| >> u|ii|i)' >> >> Is there a public module available for this purpose? >> >> >> > Perhaps I'm missing something but your function call oneOf(...) is > longer than than actually specifying the result. > > You can certainly write quite easily: > > def oneOf(s): > return "|".join(s.split()) I'd throw `re.escape()` into that function just in case `s` contains something with special meaning in regular expressions. Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Thu Sep 11 04:08:45 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Sep 2008 08:08:45 GMT Subject: dict slice in python (translating perl to python) References: Message-ID: hofer wrote: > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? One point I haven't seen in the other responses is that, at least for the example given, you don't need the second line at all: mydict={ 'one': 1, 'two': 2, 'three': 3 } print "%(one)s\n%(two)s\n%(two)s" % mydict -- Duncan Booth http://kupuguy.blogspot.com From siegfried at heintze.com Fri Sep 12 11:36:18 2008 From: siegfried at heintze.com (Siegfried Heintze) Date: Fri, 12 Sep 2008 08:36:18 -0700 Subject: Python a good choice for experimenting with Win32 API? Message-ID: <98qdnS2nk4rpEVfVnZ2dnUVZ_qHinZ2d@comcast.com> I need to understand some User32.dll functions and I'm making an elaborate GUI so I can easily experiment with different parameters. This is taking a long time. I'm new to python and I'm thinking it would sure be nice to have an interpreter I can type a few lines of code into and test things. (1) Would CPython be a good choice for this? How about iron python? How about Jython (probably not). (2) What about callbacks? Which pythons can handle callbacks? I read on msdn that you cannot use managed code to call SetWindowsHook and supply a call back (with two exceptions). I guess that means I cannot use iron python. What about C-Python for playing with hooks? (3) How easy it it define the C structs, enums and integer constants necessary to call the windows API functions? (4) Here is the code I'm struggling with presently (it is just not cooperating: no errors just wrong results! I expect to be able give it a scan code, get a virtual key code, change the arguments, give it the virtual key code and get the original scan code back again). public const UInt32 MAPVK_VK_TO_VSC = 0, MAPVK_VSC_TO_VK = 1, MAPVK_VK_TO_CHAR = 2, MAPVK_VSC_TO_VK_EX = 3, MAPVK_VK_TO_VSC_EX = 4; public const UInt32 KLF_ACTIVATE = 1, KLF_SUBSTITUTE_OK = 2, KLF_REORDER = 8, KLF_REPLACELANG = 0x10, KLF_NOTELLSHELL = 0x80, KLF_SETFORPROCESS = 0x00100, KLF_SHIFTLOCK = 0x10000, KLF_RESET = 0x40000000; [DllImport("user32.dll")] static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags); [DllImport("user32.dll")] static extern bool UnloadKeyboardLayout(IntPtr hkl); [DllImport("user32.dll")] static extern uint MapVirtualKeyEx(uint uCode, uint uMapType, IntPtr dwhkl); private void Compute() { IntPtr hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE | KLF_SUBSTITUTE_OK | KLF_REPLACELANG); uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl); UpdateOutput(); } Would it be easy to execute this in the CPython interpreter or am I better off sticking with C#? Thanks! Siegfried From ivan.illarionov at gmail.com Thu Sep 4 15:15:16 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 4 Sep 2008 12:15:16 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> On 4 ????, 22:59, Carl Banks wrote: > You can write code to guard against this if you want: > > class A: > ? ? legal = set(["x"]) > ? ? def __setattr__(self,attr,val): > ? ? ? ? if attr not in self.legal: > ? ? ? ? ? ? raise AttributeError("A object has no attribute '%s'" % > attr) > ? ? ? ? self.__dict__[attr] = val > ? ? def __init__(self,x): > ? ? ? ? self.y = x > > I suspect most people who go into Python doing something like this > soon abandon it when they see how rarely it actually catches anything. > > Carl Banks '__slots__' is better: class A(object): __slots__ = set(["x"]) def __init__(self, x): self.y = x this will do the same, only faster >>> A(1) Traceback (most recent call last): File "", line 1, in File "", line 4, in __init__ AttributeError: 'A' object has no attribute 'y' Ivan Illarionov From bj_666 at gmx.net Mon Sep 22 09:08:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2008 13:08:06 GMT Subject: Encoding.ASCII.GetBytes similar for Python ? References: <463f31b8-ba48-4833-8d41-9aa5f1cae189@a70g2000hsh.googlegroups.com> Message-ID: <6jpjlmF4bg74U1@mid.uni-berlin.de> On Mon, 22 Sep 2008 04:23:09 -0700, Rui wrote: > Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with > the strings. I am trying to query some dns server to check its response > using udp sockets. Some of the source below: > > # encoding: utf8 > import socket > import sys > import struct > > IP_PORT = 53 > server_host = ('4.2.2.1', IP_PORT) > transaction_id = "Q1" > TIMEOUT = 5 > > type_string = > "\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000" > trailer_string = "\u0000\u0000\u0001\u0000\u0001" Are you sure you want normal byte strings with *that* content!? In [90]: s = "\u0000\u0000\u0001\u0000\u0001" In [91]: len(s) Out[91]: 30 In [92]: print s \u0000\u0000\u0001\u0000\u0001 This is not 5 unicode characters but 30 ASCII characters. But why using unicode anyway? I guess the DNS server expects bytes and not unicode characters. > address = 'google.com' > url_name_start, domain_name = address.split(".") > > # Query format copied from the C# example. #QueryString = TransactionID1 > + TypeString + (char)URLNameStart.Length + URLNameStart + > (char)DomainName.Length + DomainName+ TrailerString; query = > (transaction_id + type_string + str(len(url_name_start)) + > url_name_start + > str(len(domain_name)) + domain_name + trailer_string) > print query > > sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > sock.settimeout(TIMEOUT) > sock.connect(server_host) > > sock.send(query) > data = sock.recv(512) > > for data_item in data: > try: > print chr(data_item) > except: > print data_item This will always end up in the ``except`` branch because `data` is a string and `chr()` expects integers. Any chance you wanted `ord()` instead? When you print out "trash" please use `repr()` so we can see what trash *exactly* you get. Ciao, Marc 'BlackJack' Rintsch From paul at boddie.org.uk Mon Sep 29 09:28:47 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 29 Sep 2008 06:28:47 -0700 (PDT) Subject: Web programming in Python. References: Message-ID: <6191000e-2787-45f4-a7f4-4238b3e6d5ad@y38g2000hsy.googlegroups.com> On 29 Sep, 01:51, Kurda Yon wrote: > 1. On my server (in my directory) I found "cgi-bin" subdirectory. > > 2. In the "cgi-bin" I have created a file "test.py". > > 3. In that file I put: > #!/usr/bin/python2.4 python > print "Hello, World!" > (I have checked, I have "/usr/bin/python2.4" directory.) What's the spare "python" for at the end of the first line? You should also try and run the program directly just to see whether it runs and what it prints. > 4. I give the following permissions to the "test.py": > -rwx---r-x > > 5. The "cgi-bin" directory has the following permissions: > drwx---r-x This is probably acceptable. > 6. In the "cgi-bin" I have created the ".htaccess" file which > contains: > Options +ExecCGI > AddHandler cgi-script .py > > And it still does not work! If I try to see the page by my browser I > see: > Internal Server Error > The server encountered an internal error or misconfiguration and was > unable to complete your request. > ... Read the error log, possibly found in a log directory in your home directory (since you seem to be in a hosting environment, but you'd look in /var/log/httpd or /var/log/apache for a system-wide Web server installation) and see what the complaint is. You might also consider looking at the following page for guidance: http://wiki.python.org/moin/CgiScripts Paul From gslindstrom at gmail.com Wed Sep 10 16:04:57 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Wed, 10 Sep 2008 15:04:57 -0500 Subject: Python and Open Office Message-ID: Hello, I would like to create and manipulate Open Office documents using Python. I have found then UNO Python page and odfpy modules which seem to be exactly what I need. The odfpy manual is, to me, a confusing list of objects and methods (it's an impressive list!), but does not have much in the way of how to use them. For example, I can open a spreadsheet and create new pages (there's a nice example near the back of the manual) but I can't figure out how to open an existing spreadsheet and list the names of the individual sheets ("tabs"). I have written an application that access Microsoft Excel and creates reports for work, but would like to create an Open Source version using Open Office and release it to the community (and maybe get a talk at PyCon :-). Is there someone here who can help me out, or is there an appropriate mailing list for me to join? Thanks --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From agostino.russo at gmail.com Tue Sep 9 14:47:52 2008 From: agostino.russo at gmail.com (ago) Date: Tue, 9 Sep 2008 11:47:52 -0700 (PDT) Subject: PYTHONSITEDIR environment variable References: Message-ID: Small variation on the above patch, using 2 environment variables: PYTHONSITEDIR allows for local site-packages (that override system site packages), and PYTHONNOSYSSITES skips system site-packages for "clean-room" operation (similar to virtual-python.py --no-site- packages). --- /usr/lib/python2.5/site.py 2008-05-29 22:03:04.000000000 +0100 +++ /tmp/site.py 2008-09-09 19:56:44.000000000 +0100 @@ -167,6 +167,11 @@ def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" + sitedir = os.environ.get('PYTHONSITEDIR') + if sitedir and os.path.isdir(sitedir): + addsitedir(sitedir, known_paths) + if os.environ.get('PYTHONNOSYSSITES'): + return None prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) From bj_666 at gmx.net Tue Sep 16 15:46:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Sep 2008 19:46:09 GMT Subject: optparse References: Message-ID: <6jago1F2103eU3@mid.uni-berlin.de> On Tue, 16 Sep 2008 21:35:05 +0200, Torsten Mohr wrote: > parser.add_option("-v", "--verbose", > dest = 'verb', > help = 'be loud', > action = 'store_true', > default = 'store_false') > > (opts, args) = parser.parse_args() > > print "opts", opts > print "args", args > ------example > > If i call it without any parameters i get: > > opts {'verb': 'store_false'} > args [] > > > I would rather like to see the actual value False in "opts", did i use > some wrong parameters somewhere? if you want `False` as default you should actually use `False` and not the string 'store_false'. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Sep 11 19:28:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Sep 2008 20:28:32 -0300 Subject: function return References: <48C9242E.6090509@mattnordhoff.com> Message-ID: En Thu, 11 Sep 2008 10:59:10 -0300, Matt Nordhoff escribi?: >> result = "%s\t%s\t%s" %(id,gene_symbol,ptms) > > This is very trivial, but you could change the above line to: > > result = "\t".join(id, gene_symbol, ptms) So trivial that you did not even attempt to test it, I presume. It must obviously work... except it doesn't :) result = "\t".join((id, gene_symbol, ptms)) -- Gabriel Genellina From andis59 at gmail.com Wed Sep 10 03:57:52 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Wed, 10 Sep 2008 09:57:52 +0200 Subject: I want to use a C++ library from Python Message-ID: Hello, I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1 .lib and 1 .dll files. I don't have the source code. How can I create a Python module from these files? // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! From ppearson at nowhere.invalid Sun Sep 21 13:48:23 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 21 Sep 2008 17:48:23 GMT Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> <974c3434-d409-484d-8bc4-7a3294132bd0@73g2000hsx.googlegroups.com> Message-ID: <6jnfn6F47453U2@mid.individual.net> On Sun, 21 Sep 2008 06:17:36 -0700 (PDT), Alex wrote: > On 21 Set, 15:07, George Sakkis wrote: >> On Sep 21, 8:51 am, Alex wrote: [snip] >> > I have a problem understanding the behaviour of this snippet: [snip] >> Because you're doing a shallow copy: >> http://docs.python.org/lib/module-copy.html [snip] > Thanks a lot. It was giving me and headache! FWIW, since I started following this newsgroup, I've noticed that I no longer have those crises that revolve around the depth of a copy. I conjecture that they resulted from non-pythonic style. Try following this newsgroup for a while, and you might see a lot of startlingly elegant ways of doing things. -- To email me, substitute nowhere->spamcop, invalid->net. From torriem at gmail.com Sat Sep 27 07:23:50 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 27 Sep 2008 05:23:50 -0600 Subject: How to get the filename in the right case ? In-Reply-To: References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> Message-ID: <48DE17C6.9090001@gmail.com> Steven D'Aprano wrote: > On Fri, 26 Sep 2008 01:46:15 +0200, Stef Mientki wrote: > >> Secondly thoughtless copying of current behavior, doesn't bring any >> progress, >> and I think that's one of the reasons why we're still burdened by >> inventions done 20 years ago, >> e.g. "do you want to save your changes ?". > > I click No about 50% of the time, and Yes Of Course You Stupid Machine > the other 50% of the time. Until they have a computer capable of reading > my mind, I'm curious what alternative you'd suggest. It's well known that just using "Yes" and "No" in a dialog box is very, very poor UI design. In many cases it leads to confusion. Especially when the dialog box has both a statement and a question, which many do. The correct and proper way is to use only verbs in the buttons. For example instead of yes/no to the question of saving work before exiting, you'd use "save" and "don't save." That's extremely clear even if you don't quite understand the statement and question the dialog is asking. Certainly the human-interface guidelines on the more sane systems out there (OS X, Gnome) disallow the use of yes/no buttons in dialog boxes. From zentraders at gmail.com Mon Sep 1 22:46:05 2008 From: zentraders at gmail.com (Zentrader) Date: Mon, 1 Sep 2008 19:46:05 -0700 (PDT) Subject: (in memory) database References: <5enqo5-9n9.ln1@lairds.us> Message-ID: <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> On Ubuntu you want to install something like python-sqlite (a search for "python" should turn up everything). There are 2 parts to this, SQLite and the python bindings to SQLite. So you seem to have SQLite installed but not the Python bindings. Also, on some systems you have to have python-sqlite installed, and then build python in order to use it. I'm on Gentoo so I can't help you with Ubuntu, but here's something I had lying around that uses a DB in memory (no idea why I did this or if it makes sense but you're welcome to it import sqlite3 as sqlite .##---------------------------------------------------------------------- .def add_rec(cur, con, add_tuple): . print "add_rec", len(add_tuple) . cur.execute("insert into test_it values (?, ?, ?, ?, ?, ?, ?, ?, ?)", add_tuple) . con.commit() . .##---------------------------------------------------------------------- .def print_all_recs(cur): . # Execute the SELECT statement: . print "Printing all recs" . cur.execute("select * from test_it") . . # Retrieve all rows as a sequence and print that sequence: . recs_list = cur.fetchall() . for rec in recs_list: . print rec . print " stage, REAC_W =", rec[1], rec[5] . .##---------------------------------------------------------------------- .def add_test_data(cur, con): . # Stage REAC_PS WR(T)/P TTO REAC_W W0 0wR(THCR)E/D PTO . data_list=[ ('2.0', 'Stage1', '0.509', '4.3010', '1602.30', '0.515', '3.191', '2.8191', '29.7010'), \ . ('2.0', 'Stage2', '0.488', '6.0074', '1470.43', '0.500', '3.200', '3.9309', '20.4275'), \ . ('2.0', 'Stage1', '0.524', '4.4623', '1602.30', '0.560', '3.311', '2.9243', '29.7010'), \ . ('2.0', 'Stage2', '0.579', '6.6682', '1444.78', '0.700', '3.320', '4.3593', '18.9262'), \ . ('3.0', 'Stage1', '0.524', '4.4623', '1602.30', '0.560', '3.311', '2.9243', '29.7010'), \ . ('3.0', 'Stage2', '0.579', '6.6682', '1444.78', '0.700', '3.320', '4.3593', '18.9262'), \ . ('3.5', 'Stage1', '0.525', '4.4695', '1602.30', '0.563', '3.316', '2.9290', '29.7010') ] . . for data_tuple in data_list : . add_rec(cur, con, data_tuple) . .##---------------------------------------------------------------------- .if __name__ == "__main__": . # Create a connection to the (memory) database file . con = sqlite.connect(':memory:') . . # Get a Cursor object that operates in the context of Connection con . cur = con.cursor() . . cur.execute("CREATE TABLE test_it (number varchar, stage varchar, REAC_PS varchar, WR_T_P varchar, TTO varchar, REAC_W varchar, W0 varchar, wR_THCR_E_D varchar, PTO varchar)") . . add_test_data(cur, con) . print_all_recs(cur) . .##---------------------------------------------------------------------- . print '\n-----SELECT * FROM test_it where number="2.0"-------' . recs_list=cur.execute('SELECT * FROM test_it where number="2.0"') . ctr=0 . for row in recs_list: . print row . ctr += 1 . print ctr, "recs found" . . print '\n-----SELECT * FROM test_it where number="2.0" and stage="Stage1"' . lookup_dic={"dic_num":"2.0", "dic_st":"Stage1"} . recs_list=cur.execute('SELECT * FROM test_it where number=:dic_num and stage=:dic_st', \ . lookup_dic) . ctr=0 . for row in recs_list: . print row . ctr += 1 . print ctr, "recs found" From mensanator at aol.com Thu Sep 4 01:57:19 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 3 Sep 2008 22:57:19 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> Message-ID: <81ea803c-3108-4c9b-b9bc-2334729321f5@z6g2000pre.googlegroups.com> On Sep 4, 12:20?am, Mensanator wrote: > On Sep 3, 8:30 pm, Steven D'Aprano > cybersource.com.au> wrote: > > On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: > > >>>> sum([]) > > > 0 > > > > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It > > > should return None or throw an exception like sum([None,1]) does. > > > You're wrong, because 99.9% of the time when users leave a blank cell in > > Excel, they want it to be treated as zero. > > Then 99.9% of users want the wrong thing. Microsoft knows that > this is a bug but refuses to fix it to prevent breaking legacy > documents (probably dating back to VisiCalc). When graphimg data, > a missing value should be interpreted as a hole in the graph > > +------+ ? ? ? ? ? ? +--+------+------+-----+ > > and not evaluated as 0 > > +------+ ? ? ? ? ? ? +--+------+------+-----+ > ? ? ? ? \ ? ? ? ? ? / > ? ? ? ? ?\ ? ? ? ? / > ? ? ? ? ? \ ? ? ? / > ? ? ? ? ? ?\ ? ? / > ? ? ? ? ? ? \ ? / > ? ? ? ? ? ? ?\+/ > > (depending on the context of the graph, of course). > > And Microsoft provides a workaround for graphs to make 0's > appear as holes. Of course, this will cause legitimate 0 > values to disappear, so the workaround is inconsistent. I just checked and I mis-remembered how this works. The option is for blanks to plot as holes or 0 or be interpolated. 0 always plots as 0. The inconsistency is that blanks are still evaluated as 0 in formulae and macros. > > > Spreadsheet sum() is not the > > same as mathematician's sum, which doesn't have a concept of "blank > > cells". (But if it did, it would treat them as zero, since that's the > > only useful thing and mathematicians are just as much pragmatists as > > spreadsheet users.) The Excel code does the right thing, and your "pure" > > solution would do the unwanted and unexpected thing and is therefore > > buggy. > > Apparently, you don't use databases or make surface contours. > Contour programs REQUIRE that blanks are null, not 0, so that > the Kriging algorithm interpolates around the holes rather than > return false calculations. Excel's treatment of blank cells is > inconsistent with Access' treatment of Nulls and therefore wrong, > anyway you slice it. Math isn't a democracy, what most people want > is irrelevant. > > I don't pull these things out of my ass, it's real world stuff > I observe when I help CAD operators and such debug problems. > > Maybe you want to say a bug is when it doesn't do what the > author intended, but I say if what the intention was is wrong, > then a perfect implentation is still a bug because it doesn't > do what it's supposed to do. > > > > > Bugs are defined by "does the code do what the user wants it to do?", not > > "is it mathematically pure?". > > ReallY? So you think math IS a democracy? There is no reason to > violate > mathematical purity. If I don't get EXACTLY the same answer from > Excel, > Access, Mathematica and Python, then SOMEBODY is wrong. It would be a > shame if that somebody was Python. > > > The current behaviour of sum([]) does the > > right thing for the 99% of the time when users expect an integer. > > Why shouldn't the users expect an exception? Isn't that why we have > try:except? Maybr 99% of users expect sum([])==0, but _I_ expect to > be able to distinguish an empty list from [4,-4]. > > > And the > > rest of the time, they have to specify a starting value for the sum > > anyway, and so sum([], initial_value) does the right thing *always*. > > So if you really want [] to be 0, why not say sum([],0)? > > Why shouldn't nothing added to nothing return nothing? > Having it evaluate to 0 is wrong 99.9% of the time. > > > > > > > The only time it does the wrong thing[1] is when you forget to pass an > > initial value but expect a non-numeric result. And that's the > > programmer's error, not a function bug. > > > [1] I believe it also does the wrong thing by refusing to sum strings, > > but that's another story. > > > -- > > Steven- Hide quoted text - > > - Show quoted text - From monuindia at gmail.com Mon Sep 8 13:19:01 2008 From: monuindia at gmail.com (Monu) Date: Mon, 8 Sep 2008 10:19:01 -0700 (PDT) Subject: shelve file name extention Message-ID: Hi All, When I am using shelve on my local machine it generates the db file as given filename. But in another machine it's generating .dat and .dir. can anyone tell me how can I force sheve module to write the db in .dir and .dat, instead of ? Do I have to install a specific version of the python? Thanks... Monu From kar1107 at gmail.com Wed Sep 24 23:14:43 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Wed, 24 Sep 2008 20:14:43 -0700 (PDT) Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: <4a069897-855c-45f7-8f9e-90e3fcdce176@r15g2000prd.googlegroups.com> On Sep 24, 6:27?pm, Tim Arnold wrote: > I have a bunch of processes to run and each one needs its own working > directory. I'd also like to know when all of the processes are > finished. > > (1) First thought was threads, until I saw that os.chdir was process- > global. > (2) Next thought was fork, but I don't know how to signal when each > child is > finished. > (3) Current thought is to break the process from a method into a > external > script; call the script in separate threads. ?This is the only way I > can see > to give each process a separate dir (external process fixes that), and > I can > find out when each process is finished (thread fixes that). > > Am I missing something? Is there a better way? I hate to rewrite this > method > as a script since I've got a lot of object metadata that I'll have to > regenerate with each call of the script. Use subprocess; it supports a cwd argument to provide the given directory as the child's working directory. Help on class Popen in module subprocess: class Popen(__builtin__.object) | Methods defined here: | | __del__(self) | | __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, st derr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, un iversal_newlines=False, startupinfo=None, creationflags=0) | Create new Popen instance. You want to provide the cwd argument above. Then once you have launched all your n processes, run thru' a loop waiting for each one to finish. # cmds is a list of dicts providing details on what processes to run.. what it's cwd should be runs = [] for c in cmds: run = subprocess.Popen(cmds['cmd'], cwd = cmds['cwd'] ..... etc other args) runs.append(run) # Now wait for all the processes to finish for run in runs: run.wait() Note that if any of the processes generate lot of stdout/stderr, you will get a deadlock in the above loop. Then you way want to go for threads or use run.poll and do the reading of the output from your child processes. Karthik > > thanks for any suggestions, > --Tim Arnold From ggpolo at gmail.com Wed Sep 3 20:26:27 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 3 Sep 2008 21:26:27 -0300 Subject: Help with Tkinter Label Widget In-Reply-To: <293826.25281.qm@web83915.mail.sp1.yahoo.com> References: <293826.25281.qm@web83915.mail.sp1.yahoo.com> Message-ID: On Wed, Sep 3, 2008 at 8:57 PM, Kevin McKinley wrote: > Below i've put the code for a program that i wrote. I need help on lines 384-403. If you run this program you will notice on the first tab when have it produce an answer the $ is surrounded with {$}. How can i get rid of that? Come on.. "help on lines 384-403", that is not a good way to look for help. You are supposed to post some minimal code that demonstrates the problem. Anyway, this demonstrates what you are getting (independent of python version): import Tkinter label = Tkinter.Label() label['text'] = '$', 2.0 label.pack() label.mainloop() The problem is that you are relying on something that is not supposed to be done. Note how you are passing a tuple to the "text" option, while you are actually supposed to pass a single value. You should be passing something like this instead: label['text'] = '$%f' % 2.0 > > > > from Tkinter import * > > class MyApp: > def __init__(self, parent): > self.myparent = parent > > self.frame1 = Frame(parent) > self.frame1.grid(row=0, column=0) > > self.frame2 = Frame(parent) > self.frame2.grid(row=0, column=0) > > self.frame3 = Frame(parent) > self.frame3.grid(row=0, column=0) > > self.frame4 = Frame(parent) > self.frame4.grid(row=0, column=0) > > self.a = self.b = self.c = self.d = 0 > > self.COG1 = DoubleVar(); self.COG2 = DoubleVar(); self.COG3 = DoubleVar(); self.COG4 = DoubleVar() > self.GP1 = DoubleVar(); self.PrInc = DoubleVar(); self.markupPrice = DoubleVar() > > self.tab1Func(1) > > def tab1Func(self, event): > self.tab1 = Button(self.frame1, width=14, relief=FLAT, bg="white", text="Multi-Markup") > self.tab1.bind("", self.switch1) > self.tab1.grid(row=0, column=0) > > self.tab2 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") > self.tab2.bind("", self.switch2) > self.tab2.grid(row=0, column=1) > > self.tab3 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") > self.tab3.bind("", self.switch3) > self.tab3.grid(row=0, column=2) > > self.tab4 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") > self.tab4.bind("", self.switch4) > self.tab4.grid(row=0, column=3) > > self.tab1Title = Label(self.frame1, font="bold", relief=GROOVE, text="Multi-Markup Calculator") > self.tab1Title.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) > > self.tab1Entry1 = Entry(self.frame1, textvariable=self.COG1) > self.tab1Entry1.select_range(0, END) > self.tab1Entry1.bind("", self.multiMarkup) > self.tab1Entry1.focus_force() > self.tab1Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) > > self.tab1Entry1Title= Label(self.frame1, text="Enter COG:") > self.tab1Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) > > self.tab1CalcButton = Button(self.frame1, text="Calculate") > self.tab1CalcButton.bind("", self.multiMarkup) > self.tab1CalcButton.bind("", self.multiMarkup) > self.tab1CalcButton.grid(padx=2, pady=2, row=3, column=1, columnspan=2, sticky=W+E) > > self.tab1Header = Label(self.frame1, font="bold", relief=GROOVE, text="Gross Profit % Markup Price") > self.tab1Header.grid(padx=2, pady=2, row=4, column=0, columnspan=4, sticky=W+E) > > self.tab1GP1 = Label(self.frame1, width=4,relief=RIDGE, bg="white", text="5%") > self.tab1GP1.grid(padx=2, pady=2, row=5, column=1) > > self.tab1GP2 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="10%") > self.tab1GP2.grid(padx=2, pady=2, row=6, column=1) > > self.tab1GP3 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="15%") > self.tab1GP3.grid(padx=2, pady=2, row=7, column=1) > > self.tab1GP4 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="18%") > self.tab1GP4.grid(padx=2, pady=2, row=8, column=1) > > self.tab1GP5 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="20%") > self.tab1GP5.grid(padx=2, pady=2, row=9, column=1) > > self.tab1GP6 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="21%") > self.tab1GP6.grid(padx=2, pady=2, row=10, column=1) > > self.tab1GP7 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="22%") > self.tab1GP7.grid(padx=2, pady=2, row=11, column=1) > > self.tab1GP8 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="23%") > self.tab1GP8.grid(padx=2, pady=2, row=12, column=1) > > self.tab1GP9 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="24%") > self.tab1GP9.grid(padx=2, pady=2, row=13, column=1) > > self.tab1GP10 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="25%") > self.tab1GP10.grid(padx=2, pady=2, row=14, column=1) > > self.tab1GP11 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="26%") > self.tab1GP11.grid(padx=2, pady=2, row=15, column=1) > > self.tab1GP12 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="27%") > self.tab1GP12.grid(padx=2, pady=2, row=16, column=1) > > self.tab1GP13 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="28%") > self.tab1GP13.grid(padx=2, pady=2, row=17, column=1) > > self.tab1GP14 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="29%") > self.tab1GP14.grid(padx=2, pady=2, row=18, column=1) > > self.tab1GP15 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="30%") > self.tab1GP15.grid(padx=2, pady=2, row=19, column=1) > > self.tab1GP16 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="31%") > self.tab1GP16.grid(padx=2, pady=2, row=20, column=1) > > self.tab1GP17 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="33%") > self.tab1GP17.grid(padx=2, pady=2, row=21, column=1) > > self.tab1GP18 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="35%") > self.tab1GP18.grid(padx=2, pady=2, row=22, column=1) > > self.tab1GP19 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="40%") > self.tab1GP19.grid(padx=2, pady=2, row=23, column=1) > > self.tab1GP20 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="45%") > self.tab1GP20.grid(padx=2, pady=2, row=24, column=1) > > self.tab1Markup1 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup1.grid(padx=2, pady=2, row=5, column=2, sticky=E) > > self.tab1Markup2 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup2.grid(padx=2, pady=2, row=6, column=2, sticky=E) > > self.tab1Markup3 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup3.grid(padx=2, pady=2, row=7, column=2, sticky=E) > > self.tab1Markup4 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup4.grid(padx=2, pady=2, row=8, column=2, sticky=E) > > self.tab1Markup5 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup5.grid(padx=2, pady=2, row=9, column=2, sticky=E) > > self.tab1Markup6 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup6.grid(padx=2, pady=2, row=10, column=2, sticky=E) > > self.tab1Markup7 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup7.grid(padx=2, pady=2, row=11, column=2, sticky=E) > > self.tab1Markup8 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup8.grid(padx=2, pady=2, row=12, column=2, sticky=E) > > self.tab1Markup9 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup9.grid(padx=2, pady=2, row=13, column=2, sticky=E) > > self.tab1Markup10 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup10.grid(padx=2, pady=2, row=14, column=2, sticky=E) > > self.tab1Markup11 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup11.grid(padx=2, pady=2, row=15, column=2, sticky=E) > > self.tab1Markup12 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup12.grid(padx=2, pady=2, row=16, column=2, sticky=E) > > self.tab1Markup13 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup13.grid(padx=2, pady=2, row=17, column=2, sticky=E) > > self.tab1Markup14 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup14.grid(padx=2, pady=2, row=18, column=2, sticky=E) > > self.tab1Markup15 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup15.grid(padx=2, pady=2, row=19, column=2, sticky=E) > > self.tab1Markup16 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup16.grid(padx=2, pady=2, row=20, column=2, sticky=E) > > self.tab1Markup17 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup17.grid(padx=2, pady=2, row=21, column=2, sticky=E) > > self.tab1Markup18 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup18.grid(padx=2, pady=2, row=22, column=2, sticky=E) > > self.tab1Markup19 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup19.grid(padx=2, pady=2, row=23, column=2, sticky=E) > > self.tab1Markup20 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup20.grid(padx=2, pady=2, row=24, column=2, sticky=E) > > def tab2Func(self, event): > self.tab1 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") > self.tab1.bind("", self.switch1) > self.tab1.grid(row=0, column=0) > > self.tab2 = Button(self.frame2, width=14, relief=FLAT, bg="white", text="Single Markup") > self.tab2.bind("", self.switch2) > self.tab2.grid(row=0, column=1) > > self.tab3 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") > self.tab3.bind("", self.switch3) > self.tab3.grid(row=0, column=2) > > self.tab4 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") > self.tab4.bind("", self.switch4) > self.tab4.grid(row=0, column=3) > > self.tab2Title = Label(self.frame2, font="bold", relief=GROOVE, text="Single Markup Calculator") > self.tab2Title.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) > > self.tab2Entry1 = Entry(self.frame2, textvariable=self.COG2) > self.tab2Entry1.select_range(0, END) > self.tab2Entry1.bind("", self.singleMarkup) > self.tab2Entry1.focus_force() > self.tab2Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) > > self.tab2Entry2 = Entry(self.frame2, textvariable=self.GP1) > self.tab2Entry2.select_range(0, END) > self.tab2Entry2.bind("", self.singleMarkup) > self.tab2Entry2.focus_force() > self.tab2Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) > > self.tab2Entry1Title= Label(self.frame2, text="Enter COG:") > self.tab2Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) > > self.tab2Entry2Title= Label(self.frame2, text="Enter GP %:") > self.tab2Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) > > self.tab2CalcButton = Button(self.frame2, text="Calculate") > self.tab2CalcButton.bind("", self.singleMarkup) > self.tab2CalcButton.bind("", self.singleMarkup) > self.tab2CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) > > self.tab2Header = Label(self.frame2, font="bold", relief=GROOVE) > self.tab2Header["text"] = self.GP1.get(), "%","Markup" > self.tab2Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) > > self.tab2Markup1 = Label(self.frame2, width=10, font="bold", relief=GROOVE, bg="white") > self.tab2Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) > > def tab3Func(self, event): > self.tab1 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") > self.tab1.bind("", self.switch1) > self.tab1.grid(row=0, column=0) > > self.tab2 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") > self.tab2.bind("", self.switch2) > self.tab2.grid(row=0, column=1) > > self.tab3 = Button(self.frame3, width=14, relief=FLAT, bg="white", text="Product Increase") > self.tab3.bind("", self.switch3) > self.tab3.grid(row=0, column=2) > > self.tab4 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") > self.tab4.bind("", self.switch4) > self.tab4.grid(row=0, column=3) > > self.tabTitle = Label(self.frame3, font="bold",relief=GROOVE, text="Product Increase Calculator") > self.tabTitle.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) > > self.tab3Entry1 = Entry(self.frame3, textvariable=self.COG3) > self.tab3Entry1.select_range(0, END) > self.tab3Entry1.bind("", self.priceIncrease) > self.tab3Entry1.focus_force() > self.tab3Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) > > self.tab3Entry2 = Entry(self.frame3, textvariable=self.PrInc) > self.tab3Entry2.select_range(0, END) > self.tab3Entry2.bind("", self.priceIncrease) > self.tab3Entry2.focus_force() > self.tab3Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) > > self.tab3Entry1Title= Label(self.frame3, text="Enter COG:") > self.tab3Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) > > self.tab3Entry2Title= Label(self.frame3, text="Enter Increase %:") > self.tab3Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) > > self.tab3CalcButton = Button(self.frame3, text="Calculate") > self.tab3CalcButton.bind("", self.priceIncrease) > self.tab3CalcButton.bind("", self.priceIncrease) > self.tab3CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) > > self.tab3Header = Label(self.frame3, font="bold", relief=GROOVE) > self.tab3Header["text"] = self.PrInc.get(), "%","Price","Increase" > self.tab3Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) > > self.tab3Markup1 = Label(self.frame3, width=10, font="bold", relief=GROOVE, bg="white") > self.tab3Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) > > def tab4Func(self, event): > self.tab1 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") > self.tab1.bind("", self.switch1) > self.tab1.grid(row=0, column=0) > > self.tab2 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") > self.tab2.bind("", self.switch2) > self.tab2.grid(row=0, column=1) > > self.tab3 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") > self.tab3.bind("", self.switch3) > self.tab3.grid(row=0, column=2) > > self.tab4 = Button(self.frame4, width=14, relief=FLAT, bg="white", text="Calculate GP") > self.tab4.bind("", self.switch4) > self.tab4.grid(row=0, column=3) > > self.tabTitle = Label(self.frame4, font="bold",relief=GROOVE, text="Calculate GP") > self.tabTitle.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) > > self.tab4Entry1 = Entry(self.frame4, textvariable=self.COG4) > self.tab4Entry1.select_range(0, END) > self.tab4Entry1.bind("", self.GpCalc) > self.tab4Entry1.focus_force() > self.tab4Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) > > self.tab4Entry2 = Entry(self.frame4, textvariable=self.markupPrice) > self.tab4Entry2.select_range(0, END) > self.tab4Entry2.bind("", self.GpCalc) > self.tab4Entry2.focus_force() > self.tab4Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) > > self.tab4Entry1Title= Label(self.frame4, text="Enter COG:") > self.tab4Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) > > self.tab4Entry2Title= Label(self.frame4, text="Enter Markup $:") > self.tab4Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) > > self.tab4CalcButton = Button(self.frame4, text="Calculate") > self.tab4CalcButton.bind("", self.GpCalc) > self.tab4CalcButton.bind("", self.GpCalc) > self.tab4CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) > > self.tab4Header = Label(self.frame4, font="bold", relief=GROOVE) > self.tab4Header["text"] = "Gross Profit" > self.tab4Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) > > self.tab4Markup1 = Label(self.frame4, width=10, font="bold", relief=GROOVE, bg="white") > self.tab4Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) > > def switch1(self, event): > self.frame1.grid(sticky=N+S+E+W) > self.frame2.grid_forget() > self.frame3.grid_forget() > self.frame4.grid_forget() > self.tab1Entry1.focus_force() > self.tab1Entry1.select_range(0, END) > > > def switch2(self, event): > if self.b == 0: > self.tab2Func(1) > self.b = 1 > self.frame1.grid_forget() > self.frame2.grid(sticky=N+S+E+W) > self.frame3.grid_forget() > self.frame4.grid_forget() > self.tab2Entry1.focus_force() > self.tab2Entry1.select_range(0, END) > > def switch3(self, event): > if self.c == 0: > self.tab3Func(1) > self.c = 1 > self.frame1.grid_forget() > self.frame2.grid_forget() > self.frame3.grid(sticky=N+S+E+W) > self.frame4.grid_forget() > self.tab3Entry1.focus_force() > self.tab3Entry1.select_range(0, END) > > def switch4(self, event): > if self.d == 0: > self.tab4Func(1) > self.d = 1 > self.frame1.grid_forget() > self.frame2.grid_forget() > self.frame3.grid_forget() > self.frame4.grid(sticky=N+S+E+W) > self.tab4Entry1.focus_force() > self.tab4Entry1.select_range(0, END) > > def multiMarkup(self, event): > try: > value = self.COG1.get() > except ValueError: > self.COG1 = DoubleVar() > self.tab1Entry1["textvariable"] = self.COG1 > > self.tab1Entry1.select_range(0, END) > > self.tab1Markup1["text"] = "$", round(self.COG1.get()/.95, 2) > self.tab1Markup2["text"] = "$", round(self.COG1.get()/.90, 2) > self.tab1Markup3["text"] = "$", round(self.COG1.get()/.85, 2) > self.tab1Markup4["text"] = "$", round(self.COG1.get()/.82, 2) > self.tab1Markup5["text"] = "$", round(self.COG1.get()/.80, 2) > self.tab1Markup6["text"] = "$", round(self.COG1.get()/.79, 2) > self.tab1Markup7["text"] = "$", round(self.COG1.get()/.78, 2) > self.tab1Markup8["text"] = "$", round(self.COG1.get()/.77, 2) > self.tab1Markup9["text"] = "$", round(self.COG1.get()/.76, 2) > self.tab1Markup10["text"] = "$", round(self.COG1.get()/.75, 2) > self.tab1Markup11["text"] = "$", round(self.COG1.get()/.74, 2) > self.tab1Markup12["text"] = "$", round(self.COG1.get()/.73, 2) > self.tab1Markup13["text"] = "$", round(self.COG1.get()/.72, 2) > self.tab1Markup14["text"] = "$", round(self.COG1.get()/.71, 2) > self.tab1Markup15["text"] = "$", round(self.COG1.get()/.70, 2) > self.tab1Markup16["text"] = "$", round(self.COG1.get()/.69, 2) > self.tab1Markup17["text"] = "$", round(self.COG1.get()/.67, 2) > self.tab1Markup18["text"] = "$", round(self.COG1.get()/.65, 2) > self.tab1Markup19["text"] = "$", round(self.COG1.get()/.60, 2) > self.tab1Markup20["text"] = "$", round(self.COG1.get()/.55, 2) > > def singleMarkup(self, event): > try: > value = self.COG2.get() > except ValueError: > self.COG2 = DoubleVar() > self.tab2Entry1["textvariable"] = self.COG2 > > try: > value = self.GP1.get() > except ValueError: > self.GP1 = DoubleVar() > self.tab2Entry2["textvariable"] = self.GP1 > > self.tab2Entry1.focus_force() > self.tab2Entry1.select_range(0, END) > > GP = 1 - (round((self.GP1.get()/100),2)) > > self.tab2Markup1["text"] = "$",round(self.COG2.get()/GP, 2) > self.tab2Header["text"] = self.GP1.get(), "%","Markup" > > def priceIncrease(self, event): > try: > value = self.COG3.get() > except ValueError: > self.COG3 = DoubleVar() > self.tab3Entry1["textvariable"] = self.COG3 > > try: > value = self.PrInc.get() > except ValueError: > self.PrInc = DoubleVar() > self.tab3Entry2["textvariable"] = self.PrInc > > self.tab3Entry1.focus_force() > self.tab3Entry1.select_range(0, END) > > increase = 1+(self.PrInc.get()/100) > > self.tab3Markup1["text"] = "$",round((self.COG3.get()*increase),2) > self.tab3Header["text"] = self.PrInc.get(), "%","Price","Increase" > > def GpCalc(self, event): > try: > value = self.COG4.get() > except ValueError: > self.COG4 = DoubleVar() > self.tab4Entry1["textvariable"] = self.COG4 > > try: > value = self.markupPrice.get() > except ValueError: > self.markupPrice = DoubleVar() > self.tab4Entry2["textvariable"] = self.markupPrice > > self.tab4Entry1.focus_force() > self.tab4Entry1.select_range(0, END) > > COG4 = self.COG4.get() > markup = self.markupPrice.get() > > if COG4==0.0 or markup==0.0: > self.tab4Markup1["text"] = "" > else: > GP = 100*(1-(self.COG4.get()/self.markupPrice.get())) > self.tab4Markup1["text"] = round(GP, 2),"%" > > > root = Tk() > myapp = MyApp(root) > root.mainloop() > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From jcd at sdf.lonestar.org Fri Sep 5 08:33:22 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 05 Sep 2008 08:33:22 -0400 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> <200809050059.17038.maric@aristote.info> <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> Message-ID: <1220618002.21923.12.camel@jcd-desktop> On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: > Thanks everyone for your help. I'm not opposed to using [key.lower() > for key in stage_map] at all, I was just curious to see if there were > any cleaner alternatives. It looks like that is what I'll be using. > I'm not familiar with how python works internally, but coming from C++ > it seems like "remaking" the map would be slow. However, speed is not > my main concern in my particular situation, I'm just curious to learn > more about python. You should be opposed to that particular solution. You have just taken a dictionary lookup (very fast) and turned it into a list traversal (slow). Even if speed isn't your main concern, this is an unnecessary de-optimization. You are deliberately slowing down your program to avoid a slightly more verbose lookup later. Your data structure might as well be a list of tuples to begin with, to avoid creating a new list. You have effectively made your keys useless as keys. If your lookups need to be case insensitive, make the key lower case, and store the cased version in the value, whether as a tuple or a dict (depending on whether you want named access). d = { 'foo': {'key': 'Foo', 'value': 'val1'} 'spam': {'key': 'sPAm', 'value': 'val2'} } search = 'FOO'.lower() if search in d: result = d[search] key = result['key'] value = result['value'] The only reason I wouldn't use this solution is if you expect to have keys that will be identical when made lowercase, but if you're doing case-insensitive lookup, you obviously don't expect this to be an issue. Cheers, Cliff From thkruege at uos.de Thu Sep 11 10:17:58 2008 From: thkruege at uos.de (Thorben Krueger) Date: Thu, 11 Sep 2008 16:17:58 +0200 Subject: huge socket recv speed discrepancy between different OSs Message-ID: <3b5d765a0809110717r51557eeey9d472c8ccc5ee34a@mail.gmail.com> Do you see this too? Mor information and testcase here: http://bugs.python.org/issue3766 I would also be interested in the profiler output under windows. All the best Thorben From tino at wildenhain.de Fri Sep 12 02:32:48 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 12 Sep 2008 08:32:48 +0200 Subject: How to Determine Name of the Day in the Week In-Reply-To: References: Message-ID: <48CA0D10.6040103@wildenhain.de> Henry Chang wrote: > Instead of getting integers with weekday(), Monday == 0 ... Sunday == 6; > is there a way to get the actual names, such as "Monday ... Sunday"? I > would like to do this without creating a data mapping. :) The 'actual names' in which language? Chinese, Russian, French, ... :) Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From ivanov.maxim at gmail.com Sun Sep 14 18:26:28 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Mon, 15 Sep 2008 02:26:28 +0400 Subject: pyprocessing/multiprocessing issue Message-ID: Good evening all. I try to use pyprocessing (aka multiprocessing in 2.6) module in my app, but run into problem. I use Pool and apply_async. It seems that it couldn't unpickle function which i pass to it, it gives me "AttributeError: 'module' object has no attribute 'do'" error where "do" is the name of dunction I pass to apply_async. Code is better than words, so I put as smallest test-case I could imagine. I suppose problem with different modules I use, becouse examples where everything fit in one file works great. -------------- next part -------------- A non-text attachment was scrubbed... Name: processing_error.tar.bz2 Type: application/x-bzip2 Size: 1098 bytes Desc: not available URL: From lists at cheimes.de Sun Sep 14 11:30:53 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 14 Sep 2008 17:30:53 +0200 Subject: how to exclude specific things when pickling? In-Reply-To: <7cd144b6-ca6f-447a-8448-5a334f8f999f@k37g2000hsf.googlegroups.com> References: <7cd144b6-ca6f-447a-8448-5a334f8f999f@k37g2000hsf.googlegroups.com> Message-ID: Michael Palmer wrote: > If your class defines a __getstate__ method, it is expected to return > the pickled state of the entire class. You can for example del those > items from self.__dict__ that you don't want pickled and then return > dumps(self). FYI: __getstate__ is ignored when __reduce__ is available. Christian From fredrik at pythonware.com Thu Sep 11 13:11:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 19:11:13 +0200 Subject: dict slice in python (translating perl to python) In-Reply-To: References: Message-ID: hofer wrote: > The real example would be more like: > > name,age,country = itemgetter('name age country'.split())(x) ouch. if you do this a lot (=more than once), just wrap your dictionaries in a simple attribute proxy, and use plain attribute access. that is, given class AttributeWrapper: def __init__(self, obj): self.obj = obj def __getattr__(self, name): try: return self.obj[name] except KeyError: raise AttributeError(name) or, shorter but less obvious and perhaps a bit too clever for a beginning Pythoneer: class AttributeWrapper: def __init__(self, obj): self.__dict__.update(obj) you can do >>> some_data = dict(name="Some Name", age=123, country="SE") >>> some_data {'country': 'SE', 'age': 123, 'name': 'Some Name'} >>> this = AttributeWrapper(some_data) >>> this.name 'Some Name' >>> this.age 123 >>> this.country 'SE' and, if you must, assign the attributes to local variables like this: >>> name, age, country = this.name, this.age, this.country >>> name 'Some Name' >>> age 123 >>> country 'SE' >>> (the next step towards true Pythonicness would be to store your data in class instances instead of dictionaries in the first place, but one step at a time...) From larry.bates at vitalEsafe.com Sat Sep 13 11:07:04 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 13 Sep 2008 10:07:04 -0500 Subject: testing if another instance of a script is already running In-Reply-To: References: Message-ID: Strato wrote: > Hi folks, > > I want to write some kind of test to check at startup if another > instance of my script is already running. > > I don't want to handle writing of a PID file because it is too > Unix/Linux specific way to do this, and I need to keep the code to be > cross-platform. > > I think the better way to achieve this is to use some process control, > but I'm a neebie and I don't see how to do this in a safe and clean way. > > Any idea ? > > Best regards, > Strato Here is a recipe for Linux version of singleinstance class: http://code.activestate.com/recipes/546512/ and I wrote and contributed the equivalent Windows version: http://code.activestate.com/recipes/474070/ Hope this helps. -Larry From ldo at geek-central.gen.new_zealand Mon Sep 29 05:05:44 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:05:44 +1300 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> Message-ID: In message <02918eb6-c2fb-4908-923f-d878a1956ee2 at x35g2000hsb.googlegroups.com>, sturlamolden wrote: > ... and possibility of interfacing with gnuplot ... Gnuplot is non-Free software. From code at pizzashack.org Wed Sep 3 20:34:35 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 3 Sep 2008 20:34:35 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6vmdncUnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> References: <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <6i6pq9Fmcad7U2@mid.uni-berlin.de> <6vmdncUnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> Message-ID: <20080904003435.GA29228@dragontoe.org> On Wed, Sep 03, 2008 at 03:16:00PM -0700, Dennis Lee Bieber wrote: > On Wed, 3 Sep 2008 03:09:18 -0400, Derek Martin > declaimed the following in comp.lang.python: > > > > > struct run { > > int speed; > > direction_type direction; > > }; > > > > Not a function. Describes an action. Sure, you'll probably never see > > this example in a real program. But that doesn't mean you can't do > > it, and it doesn't make it inherently wrong. Someone somewhere might > > very well find a legitimate use case. > > > > Does neither for me... It defines a (physics) VELOCITY (a direction > and a speed, but lacking in starting position and in duration). OK... so, let me ask you then: I have a computer program that graphs the state of a particular act of running over time t. The only information the program cares about is the speed and direction of that particular instance of running. What would your data structure look like? > An action, "run", would, in my mind require taking this vector and > multiplying it by some duration, and adding the result to some starting > position. I can not be held responsible for your mind... ;-) You're talking about a computational action... which I already said is NOT what I'm talking about. At any given point in time, if someone is running, they have a direction and a speed. The structure I described is sufficient to describe that state. In this extremely silly example, the starting point, end point, and any intermediary positions are not interesting to the problem, which has intentionally been left undefined, because it is an EXAMPLE. Examples are not required to be especially useful or meaningful, and I would guess that the vast majority of examples in, say, introduction to comp sci texts are not (think "hello world"). They need only illustrate something. This particular point was that an object in a computer program can describe some physical action -- in whole or only in part -- without actually needing to have any executable code associated with that state (i.e. it can be a data only, rather than an object with executable methods). The "thing" being described being an action may lend itself to using the name of that action, i.e. a verb, as the name of the object. Though, actually, the example I described above is (minimally) useful. Assuming you had an array of such structs, with say, the index representing the time t in seconds, then it provides you with a graph of the path taken during the act of running. You could superimpose this graph on a map and, given a particular starting point, determine where the person running ended up. You might be inclined to say that the object should be a runner, and you're free to think of it that way if you like... but the fact is the object DOES NOT describe a runner. It describes an instance of running at a moment in time. You might also be inclined to say that the name "run" is a bad choice, because it should be something retarded like state_of_run_at_time_t; but unless you're unbelievably obtuse, then looking at the code, it gets the point across. It may not be the most ideal name, but given the number of times I've seen "foo" used as an identifier in real programs... well, is it really so bad? -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From carriere.jonathan at gmail.com Thu Sep 11 09:56:29 2008 From: carriere.jonathan at gmail.com (carriere.jonathan at gmail.com) Date: Thu, 11 Sep 2008 06:56:29 -0700 (PDT) Subject: Python platform. Message-ID: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> Hello all; I wonder if there is a platform written in python. The equivalent of the Netbeans platform http://platform.netbeans.org/ in the Python world. Do you know such a thing? Thanks a lot. Jonathan. From rridge at csclub.uwaterloo.ca Wed Sep 24 17:11:28 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 24 Sep 2008 17:11:28 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <48da956c$0$1269$426a74cc@news.free.fr> Message-ID: Grant Edwards wrote: > Same here. It's like an automotive engine controls designer > asking if a failed O2 sensor should turn on the check engine > light or blow up the car. Ross Ridge wrote: > No, it's more like asking if the failed sensor should turn on > a strange and mysterious light on the dashboard Grant Edwards wrote: > You're right. I had forgotten that sys.exit() is actually > raising the system exit exception, and that the application > calling the library could handle that exception. Ross Ridge a ?crit : > Well, my point was that exceptions in Python are a bit like a car's > check engine light. Few drivers know what this mysterious light means, > and aren't prepared to do anything about it when it goes on. Bruno Desthuilliers wrote: >You're kidding, aren't you ? Of course not. Plenty of people were quick to say that the exception should be passed through to the caller. No one said this behaviour should be documented. There may be little practical difference bewteen calling sys.exit() after printing an error and progating an exception if no one using the library knows that it could generate that exception in those circumstances. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From castironpi at gmail.com Sun Sep 28 00:43:15 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 21:43:15 -0700 (PDT) Subject: closures and dynamic binding Message-ID: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Hello all, To me, this is a somewhat unintuitive behavior. I want to discuss the parts of it I don't understand. >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= lambda: n ... >>> f[0]() 9 >>> f[1]() 9 I guess I can accept this part so far, though it took a little getting used to. I'm writing some code and found the following workaround, but I don't think it should give different results. Maybe I'm not understanding some of the details of closures. >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= (lambda n: ( lambda: n ) )( n ) ... >>> f[0]() 0 >>> f[1]() 1 Which is of course the desired effect. Why doesn't the second one just look up what 'n' is when I call f[0], and return 9? From raj.indian.08 at gmail.com Tue Sep 16 23:31:54 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Tue, 16 Sep 2008 20:31:54 -0700 (PDT) Subject: Modifying the system menu Message-ID: Hi all, I am trying to modify the system menu of all the applications in my machine. For example say - I am creating multiple desktops for windows - and I want to give every application the capability to be moved across different desktops. So I wanted to modify the basic system menu list to include the new options. The methods I could think of are - 1. Modify the basic windows set of system menu values (best option) or 2. Poll every few milliseconds and modify the system menu values of the active window For (1) I couldnt think of a way to do it. Is it even possible using python? For (2) I wrote the following code for basic testing: hwnd = win32gui.GetForegroundWindow() hw = win32gui.GetSystemMenu(hwnd, False) if hw != None: win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); and it shows the following error: pywintypes.error: (1401, 'AppendMenu', 'Invalid menu handle.') If anyone could help me out in both the options (1) and/or (2), I would be very thankful. Thank you very much in advance, A python newbie From google at mrabarnett.plus.com Wed Sep 10 18:01:28 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 10 Sep 2008 15:01:28 -0700 (PDT) Subject: emulating read and readline methods References: Message-ID: On Sep 10, 6:59?pm, Sean Davis wrote: > I have a large file that I would like to transform and then feed to a > function (psycopg2 copy_from) that expects a file-like object (needs > read and readline methods). > > I have a class like so: > > class GeneInfo(): > ? ? def __init__(self): > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > gene_info.gz',"/tmp/gene_info.gz") > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > ? ? ? ? self.fh.readline() #deal with header line > > ? ? def _read(self,n=1): > ? ? ? ? for line in self.fh: > ? ? ? ? ? ? if line=='': > ? ? ? ? ? ? ? ? break > ? ? ? ? ? ? line=line.strip() > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > ? ? ? ? ? ? rowvals = line.split("\t") > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > ? ? def readline(self,n=1): > ? ? ? ? return self._read().next() > > ? ? def read(self,n=1): > ? ? ? ? return self._read().next() > Each time readline() and read() call self._read() they are creating a new generator. They then get one value from the newly-created generator and then discard that generator. What you should do is create the generator in __init__ and then use it in readline() and read(). > ? ? def close(self): > ? ? ? ? self.fh.close() > > and I use it like so: > > a=GeneInfo() > cur.copy_from(a,"gene_info") > a.close() > > It works well except that the end of file is not caught by copy_from. > I get errors like: > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > during .read() call > CONTEXT: ?COPY gene_info, line 1000: "" > > for a 1000 line test file. ?Any ideas what is going on? > I wonder whether it's expecting readline() and read() to return an empty string at the end of the file instead of raising StopIteration. From maric at aristote.info Tue Sep 16 10:10:49 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 16:10:49 +0200 Subject: append on lists In-Reply-To: References: Message-ID: <200809161610.50245.maric@aristote.info> Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit?: > On 2008-09-16, Maric Michaud wrote: > > all expressions that return something, return a new object, > > That's not _quite_ true: > >>> a=1 > >>> b=a.__add__(0) > >>> a is b > > True > > ;) This is implementation specific, the specification of the language says that it should be false, and it is for higher numbers : >>>[15]: a=1000 >>>[16]: b=a.__add__(0) >>>[17]: a is b ...[17]: False Don't disturb our OP, with side questions, please, it was enough hard like this ;) -- _____________ Maric Michaud From kf9150 at gmail.com Thu Sep 11 12:55:26 2008 From: kf9150 at gmail.com (Kelie) Date: Thu, 11 Sep 2008 09:55:26 -0700 (PDT) Subject: Use Python to solve equations? References: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Message-ID: <16c52a7f-691c-4cba-b770-8ce117389afc@t1g2000pra.googlegroups.com> On Sep 11, 1:11?am, Uwe Schmitt wrote: > > Kelie > > look atwww.sagemath.com. it is great. > > greetings, uwe Thanks Uwe! From maric at aristote.info Thu Sep 4 18:59:16 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 00:59:16 +0200 Subject: Case-insensitive string compare? In-Reply-To: <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> Message-ID: <200809050059.17038.maric@aristote.info> Le Friday 05 September 2008 00:47:00 Chris Rebert, vous avez ?crit?: > On Thu, Sep 4, 2008 at 3:37 PM, Robert Dailey wrote: > > On Thu, Sep 4, 2008 at 5:21 PM, Fredrik Lundh > > > > wrote: > >> Robert Dailey wrote: > >>> I currently have a dictionary object that I'm doing the following with: > >>> > >>> if lib not in stage_map: > >>> # ... do stuff ... > >>> > >>> However, this will perform a case-sensitive comparison between lib and > >>> each key in stage_map. Is there a way to make this do a > >>> case-insensitive comparison instead? > >> > >> dictionary lookups use the exact value. to make a case-insensitive > >> lookup, use key.lower() instead of key when creating the dictionary, and > >> then do > >> > >> if lib.lower() not in state_map: > >> ... > > > > So you're saying to ensure that stage_map's keys are initially lower-case > > to begin with? Well, I can't do this either since the case of the keys is > > actually valuable later on. It's only for the purposes of this specific > > comparison operation that the case should be ignored. > > Then store the string in its original case in the value part of the > key-value pair: > > stage_map[key.lower()] = (key,whatever) > "premature optimization is the root of all evil" I don't recall the OP wanted a (a bit) faster solution to his problem in counterpart of memory loss and syntax complication. If the OP's proposal seems already messy, how about ths one : if lib.lower() not in ( e[0] for e in stage_map.items() ) : ... > - Chris > > > -- > > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From aioe.org at technicalbloke.com Wed Sep 17 14:07:56 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 14:07:56 -0400 Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> Message-ID: Grant Edwards wrote: > On 2008-09-17, r0g wrote: > >> r0g at steppa:~/Desktop/py$ ls >> kickstart.py kickstart.py~ kicktest.py kicktest.py~ >> r0g at steppa:~/Desktop/py$ kickstart.py >> bash: kickstart.py: command not found >> >> Any ideas why this might be? > > Yes. > >> A path thing? > > Yes. > > Linux systems generally don't have the current directory in the > PATH that's searched for executbles (it's regarded as a rather > serious security problem if you do). > > Try doing this: > > ./kickstart.py > Brilliant! :D Thanks v.much for that, turns out the very same thing had been driving me nuts a few days earlier when I was trying to run an installer I had downloaded, bit of an Izzard Printer moment LOL - http://www.youtube.com/watch?v=2wHEqDepAXo Thanks again! Roger. http://www.technicalbloke.com http://movingtoubuntu.technicalbloke.co.uk From gagsl-py2 at yahoo.com.ar Tue Sep 2 15:18:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 16:18:58 -0300 Subject: about downloading the selected information References: Message-ID: En Tue, 02 Sep 2008 09:47:46 -0300, woaibeiyang escribi?: > I have a problem to download the information from url > http://www.ncbi.nlm.nih.gov/sites/entrez. Because it is impossible for me to > add searching material to the url to construct a new url and then visit the > website. > I have the searching material, however I could not find the way to deal with > this problem. I want to know how can I do this problem with python and which > part of knowledge should I view first? Thanks! Use an HTTP tracer (or logger, or sniffer...) to see the request that the browser sends to the server. Then analyze the page source to figure out how the different options modify the request sent. -- Gabriel Genellina From bearophileHUGS at lycos.com Fri Sep 12 16:23:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Sep 2008 13:23:16 -0700 (PDT) Subject: manipulating files within 'for' References: <48CAA2AA.40809@umbc.edu> <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> Message-ID: Matt Nordhoff: > It's useful when wrapping a line. For lack of better lorem ipsum: > > whatever = some_function("Your mistake is caused by Python not " > "following one of its general rules:\n\n" > "Explicit is better than implicit.") > > You can also use backslashes, and probably even + if you want to, but > the implicit concatenation is prettier (IMO, at least ;-). Adding a + at the end of lines isn't much extra work: whatever = some_function("Your mistake is caused by Python not " + "following one of its general rules:\n\n" + "Explicit is better than implicit.") Or even: whatever = "Your mistake is caused by Python not " + \ "following one of its general rules:\n\n" + \ "Explicit is better than implicit." > But you do have a point. I have never thought about the problems it > could cause. Probably such problems aren't much common, because common bugs are already prevented by Python designers :-) But I think once I have written a bug like this: parts = ["foo", "bar" "baz", "spam"] Where I meant a list of 4 strings. > BTW, I could easily be wrong, but I think C behaves the same way as Python. I know, but here changing the behavior respect to C doesn't cause bugs to C programmers, because in that situation their Python program just doesn't run. So it's not a Python syntax that looks like a C syntax that behaves in a different way (this rule is used by the D designer too: when something behaves differently from C (often to avoid a common C pitfall), it has a different syntax. Where the D syntax is the same of C syntax, then the D behavior is generally the same. This avoids several problems to programmers coming from C/C++). Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Sun Sep 28 03:56:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 07:56:49 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <00ef327d$0$20666$c3e8da3@news.astraweb.com> On Sun, 28 Sep 2008 19:03:42 +1300, Lawrence D'Oliveiro wrote: > In message > <9890864a-09f9-40d6-b2cc-5028e7a0c8c3 at q26g2000prq.googlegroups.com>, est > wrote: > >> The problem is, why the f**k set ASCII encoding to range(128) ???????? > > Because that's how ASCII is defined. > >> while str() is internally byte array it should be handled in range(256) >> !!!!!!!!!! > > But that's for random bytes. How would you convert an arbitrary object > to random bytes? from random import randint ''.join(chr(randint(0, 255)) for i in xrange(len(input))) of course. How else should you get random bytes? :) -- Steven From prahaai at gmail.com Mon Sep 22 03:13:50 2008 From: prahaai at gmail.com (Cro) Date: Mon, 22 Sep 2008 00:13:50 -0700 (PDT) Subject: External code and functions integration Message-ID: Good day. I am using python for quite some time now and i decided to advance a little. I want to write a little extension, or add some C modules for my python. I use Active version. What i want to do is write some wrappers for a game library, called HGE. See "hge.relishgames.com". I wrote some applications with HGE, in C++ and i like it pretty much. In order to make a HGE application in C++, i need to include "hge.h", include "hge.lib" and "hgelehper.lib", and have "hge.dll" in the same directory. So it's 3 things i must have for the program to work. This game library is open source, so i have the source for the libs and the dll. Now, what i was thinking was to make some wrapping code like "hge.h" to call all the functions in the "libs", that (i guess) call the functions from "hge.dll", that (blah blah) calls DirectX and so on. I guess that if i write all that "hge.h" includes and wariables in python, will be okay... even if i still don't have the skill. I tried to call "hge.lib" like this: " from ctypes import * cdll.LoadLibrary("D:/HGE18/lib/bc/hge.lib") " But i get "WindowsError: [Error 193] %1 is not a valid Win32 application". I tried with windll.LoadLibrary ... and i get the same error. I tried with the other lib versions, there are 3 versions: BorlandC, GCC, VisualC, callind "cdll" or "windll". All lib versions report the same error. Recently i discovered PyInline and SciPy Weave. They say that Weave can run C code on the fly, inline... I really dobt that it can parse things like: " #ifndef HGE_H #define HGE_H " or: " #include #define HGE_VERSION 0x180 #ifdef HGEDLL #define EXPORT __declspec(dllexport) #else #define EXPORT #endif #define CALL __stdcall " Has anyone ever encountered a problem like this ? Any, ANY advice or idea would be useful ! Thank you very much. From bignose+hates-spam at benfinney.id.au Mon Sep 22 05:19:57 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 22 Sep 2008 19:19:57 +1000 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <87d4iw1qrm.fsf@benfinney.id.au> Steven D'Aprano writes: > I don't want the objects to share state. I'm not exactly sure what I > said that has given so many people the impression that I do. This: Steven D'Aprano writes: > Essentially, the class is used as a function that keeps state from > one call to the next. Perhaps if you say what you want that isn't provided by any of a function, a module, or a class. Specifically, what state you want to track, and why it's so important that the state not be available to the instances. -- \ ?I love and treasure individuals as I meet them, I loathe and | `\ despise the groups they identify with and belong to.? ?George | _o__) Carlin, 2007 | Ben Finney From sturlamolden at yahoo.no Wed Sep 24 14:15:58 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 11:15:58 -0700 (PDT) Subject: Linq to Python References: Message-ID: On Sep 24, 5:22?pm, hrishy wrote: > Well wouldn't it be a lot easier to query and join a xml source with a relational source with LINQ capabilites in Python. > > Hmm what am i missing here is there a site that takes all LINQ examples and does them using list comprehensions and makes them sound easy ? > > wasn't python supposed to make everything easy ? Most Python programmers use other languages as well. I have working knowledge of C, Matlab, C++, Java, Fortran 95, and C#. Those that responded to your post know what LINQ are and what LINQ does. Put simply, Python has dynamic typing, list comprehensions, and is scriptable (i.e. Python source is structured text). That's why Python don't need LINQ and XML the same way as C#. LINQ and XML is needed because C# is a statically typed compiled language. That is: LINQ: Python has list comprehensions and dynamic typing (C# do not) XML: Python is structured text (compiled .NET assemblies are not) Second, minimalistic syntax is a virtue. That is why C is still around. Python don't add new syntax sugar every time Redmond invents a new buzzword. Functions like XML processing are delegated to libraries -- where they belong. Nobody was saying LINQ is a bad idea for a language like C#. From psaffrey at googlemail.com Wed Sep 10 12:38:57 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Wed, 10 Sep 2008 09:38:57 -0700 (PDT) Subject: Generator functions and user interfaces Message-ID: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> I'm trying to implement an interactive graph visualisation tool using matplotlib. I want to use a spring layout, where nodes repulse each other and edges act as springs to pull connected nodes together. Usually, this algorithm runs through a number of iterations of attraction/repulsion to allow the nodes to converge to suitable positions. However, rather than running all these iterations to lay out the graph and then rendering it, I want to animate the graph as it is "springing" into place, and then allow the user to drag nodes around and have the graph redraw on the fly. My idea for doing this was to use a generator function, where I yield the position of the nodes after each iteration and then call draw() on the position yielded. Does this seem like a sensible approach? The problem is that the node positions that are being operated on by the generator function may be altered by user input - dragging the nodes - and I'm not sure if this will break the way that the new positions are yielded. How do I use a generator function that might stop (when the nodes stop moving) but then need to restart again (once the user moves the nodes)? I'm quite an experienced Python programmer but I've never taken the trouble to get my head around generator functions, so any guidance welcome! Peter From steve at REMOVE-THIS-cybersource.com.au Mon Sep 1 08:18:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2008 12:18:16 GMT Subject: Know if a object member is a method References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Message-ID: <00cbd80b$0$20302$c3e8da3@news.astraweb.com> On Mon, 01 Sep 2008 11:45:36 +0200, Luca asked about recognizing methods: > What is the best way to do this? The "most pythonic"? That depends on why you are doing it, and what you want to do with the information once you've found it. If you are experimenting in the interactive interpreter, the easiest way is simply call the method and see what happens: obj.methodName() # call the method If it succeeds, then it is some sort of callable, a method or a function or something more unusual. If you fear side-effects, then use: callable(obj.methodName) Alternatively, you can read the docs: help(obj) help(obj.methodName) If your aim is to write something like a debugger, profiler, or some other application that needs to inspect arbitrary objects and work out what they do, then you probably should be using: isinstance(obj.methodName, new.instancemethod) But remember that not all callable attributes are instancemethods! There is no one right way of doing this. Hope this helps. -- Steven From gandalf at shopzeus.com Mon Sep 8 09:18:45 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Sep 2008 15:18:45 +0200 Subject: universal unicode font for reportlab In-Reply-To: <48C51E49.2070202@shopzeus.com> References: <87r67vj7f1.fsf@benfinney.id.au> <48C51E49.2070202@shopzeus.com> Message-ID: <48C52635.1030709@shopzeus.com> >> >> The GNU Unifont >> covers an impressive range of >> the Unicode Basic Multilingual Plane. >> >> Unifont is originally a bitmap font, but was recently made available >> in TrueType format >> . >> >> Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont' >> packages, respectively. > I found out that dejavu is what I need. It covers the languages I need > and more: > > http://dejavu.svn.sourceforge.net/viewvc/dejavu/tags/version_2_26/dejavu-fonts/langcover.txt Sorry, this did not work either. Dejavu does support cyrillic and greek characters but I have to load a different ttf for that. They are no unified. :-( The only one that worked so far was "unifont.tff" but it is very ugly above point size=10. Can you tell me what kind of font Geany is using on my Ubuntu system? The preferences tells that it is "monospace" but when I load VeraMono.ttf in reportlab, it will not even display latin2 characters. In contrast, please look at this example that show my test program in Geany: http://www.shopzeus.com/geany.jpg It is a real scalable truetype font, displaying latin 1, latin2, chinese, russian and japanese characters. Is it the same font? Does this mean that reportlab is buggy? If I could load the same font that geany uses, it would probably solve my problem forever. Thanks, Laszlo -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 1050 bytes Desc: not available URL: From nospam at invalid.invalid Mon Sep 29 04:05:10 2008 From: nospam at invalid.invalid (robert) Date: Mon, 29 Sep 2008 10:05:10 +0200 Subject: Detecting dir (tree) changes fast? Message-ID: I want to detect changes in a directory tree fast with minimum overhead/load. In order to check the need for sync tasks at high frequency. It must not be 100% reliable (its also forced time periodic), so kind of hashing would be ok. How? Robert From sayananbig at gmail.com Thu Sep 18 18:11:39 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Thu, 18 Sep 2008 15:11:39 -0700 (PDT) Subject: Directshow in Python Message-ID: <9d55654a-49ed-4bce-beae-bdf915810ad1@o40g2000prn.googlegroups.com> Hey all, I'm trying to use DirectShow to display videos [I'm kind of new to Python, from more of a C++ background on windows]. I found some sample code online, but I am having trouble with calling the I import ctypes from ctypes import * from comtypes import client from ctypes.wintypes import * import sys import time filename = sys.argv[1] qedit = client.GetModule('qedit.dll') # DexterLib quartz= client.GetModule("quartz.dll") CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}' filter_graph = client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph) filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder) filter_builder.RenderFile(filename, None) media_control = filter_graph.QueryInterface(quartz.IMediaControl) media_control.Run() try: # Look at IMediaEvent interface for EOS notification while True: time.sleep(1) except KeyboardInterrupt: pass # Need these because finalisers don't have enough context to clean up after # themselves when script exits. del media_control del filter_builder del filter_graph This code works fine. What I would like to know, is how do I declare filename in the Python program to be of type LPCWSTR, so that I don't need to parse the command line in order to call the function "RenderFile()"? -Sayanan From gagsl-py2 at yahoo.com.ar Tue Sep 16 06:02:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 07:02:02 -0300 Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows References: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Message-ID: En Tue, 16 Sep 2008 06:25:27 -0300, escribi?: > I wonder if anyone can advise me or has done similar to the following? > > Basically I've downloaded the Python 2.5.2 source code that builds > with Visual Studio 6.0. I've built Python for windows. This was easy > (it even came with the pcbuild.dsw workspace file). Great! > > Now comes the troubled bit...I now look for similar source code for > Python extensions Numpy and Scipy but the source code and directories > are not all obvious. Looks like these are normally built via other > compilers. However I need to do all my builds in VS 6.0. > > For Numpy (I haven't got as far as Scipy yet) I've organised the > source code into the following projects and lumped them all into my > new workspace numpy.dsw: Don't try to roll your own projects, compile it using distutils instead. Distutils takes care of defining the right symbols and compiler options, and should detect VS. I'm pretty sure the Numpy README file (or similar) describes how to build it; usually you install the required dependencies and then run: python setup.py build -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sun Sep 7 18:18:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 19:18:49 -0300 Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: En Sun, 07 Sep 2008 18:51:32 -0300, andyhume at gmail.com escribi?: > I have a dict of key/values and I want to change the keys in it, based > on another mapping dictionary. An example follows: > > MAPPING_DICT = { > 'a': 'A', > 'b': 'B', > } > > my_dict = { > 'a': '1', > 'b': '2' > } > > I want the finished my_dict to look like: > > my_dict = { > 'A': '1', > 'B': '2' > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? Exactly. You can do that in one pass: my_new_dict = dict((MAPPING_DICT[k],v) for (k,v) in my_dict.iteritems()) That's enough if MAPPING_DICT always contains all the keys. If you want to keep old keys that aren't in MAPPING_DICT unchanged, use MAPPING_DICT.get(k,k) instead. Other corner cases include many-to-one mappings, and incomplete mappings where a replacement key is also an unmapped old key. -- Gabriel Genellina From jan.schilleman at xs4all.nl Sun Sep 14 19:06:08 2008 From: jan.schilleman at xs4all.nl (Jan Schilleman) Date: Mon, 15 Sep 2008 01:06:08 +0200 Subject: Rebinding __setattr__ Message-ID: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> Hi all, I am trying to redefine __setattr__. The base class is in a library (actually, it is win32com.client.DispatchBaseClass) and I do not want to touch it. My problem is exemplified below. To my surprise, __setattr__ and __str__ behave differently; I can redefine __str__ and the inherited __str__ is still the redefined one. But redefining __setattr__ on the base class does not get inherited. In Base.__dict__ the __setattr__ is the one I expected, but it is not called from B. What is the problem? Is __setattr__ cached somewhere [and not updated?]? class Base: def __setattr__(self, attr, value): print 'Base __setattr__' self.__dict__[attr] = value def __str__(self): return "Base" class A(Base): pass class B(Base): pass def __setattr__(self, attr, value): print 'alternative __setattr__' self.__dict__[attr] = value def __str__(self): return "Alternative" a = A() b = B() for i in (1, 2): print print 'run', i print print Base.__dict__ print A.__dict__ print B.__dict__ print print 'a:', a a.a1 = 1 print 'b:', b b.b1 = 1 setattr(Base, '__setattr__', __setattr__) setattr(A, '__setattr__', __setattr__) setattr(Base, '__str__', __str__) setattr(A, '__str__', __str__) From bdesth.quelquechose at free.quelquepart.fr Tue Sep 9 13:13:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 19:13:35 +0200 Subject: check if the values are prensent in a list of values In-Reply-To: References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> Message-ID: <48c6caae$0$22688$426a74cc@news.free.fr> Matt Nordhoff a ?crit : (snip) > I'm not judging whether this is a good solution or not, but that's a > silly use of a dict. Yeps, but a somewhat common one in code predating the apparition of sets as builtin type. From J.Fine at open.ac.uk Wed Sep 17 10:03:59 2008 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 17 Sep 2008 15:03:59 +0100 Subject: Generating test data from an XML Schema In-Reply-To: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> References: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> Message-ID: Mark Thomas wrote: >> Has anyone seen anything that might help generate test data from a schema? > > I'm unaware of anything in Python, but Eclipse can generate sample > documents from a schema: > http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html > > As can XML IDEs such as Stylus Studio and XML Spy. Mark - thank you for this. The problem is that I'd like to sit quite close to the schema and manipulate the generation of the test data. (This is because a straight representation won't suit my needs.) However, if I get the chance I'll look at these tools, in case they can help me. Thank you for the suggestion. -- Jonathan From linkmaster032000 at gmail.com Sun Sep 21 13:11:24 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Sun, 21 Sep 2008 10:11:24 -0700 (PDT) Subject: curses.setsyx()? References: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> Message-ID: <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: > On Sep 19, 1:24?am, Tim Roberts wrote: > > > linkmaster032... at gmail.com wrote: > > > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > > >cursor. Any alternatives/solutions? > > > Did you call doupdate after? ?setsyx just manipulates the data structures. > > It takes a call to doupdate to force those changes to take effect visually. > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > I added it and it still doesn't work. This is what I'm doing when I > want to display the cursor and prepare it for input at 2,3: > > curses.echo() > curses.curs_set(1) > curses.setsyx(2,3) > curses.doupdate() Any idea what's wrong? From mart_in_medina at yah00.es Sun Sep 21 18:08:03 2008 From: mart_in_medina at yah00.es (Martin Griffith) Date: Mon, 22 Sep 2008 00:08:03 +0200 Subject: Milenko Kindl rtegdgd References: <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> Message-ID: <59hdd4t65g9gb5kq535b2pkfj939hiruqv@4ax.com> On Sun, 21 Sep 2008 15:00:16 -0700 (PDT), in sci.electronics.design H Vlems wrote: >On 21 sep, 19:48, yuma wrote: >> Milenko Kindl >> Banja Luka >> Banjaluka >> Bihac > >Well, that's not C isn't it, more like Snobol or RPG/2 It's better to say "that's not C, is it" I don't know why, but that's the way it works..... martin From aioe.org at technicalbloke.com Sat Sep 27 02:15:20 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 27 Sep 2008 02:15:20 -0400 Subject: Eggs, VirtualEnv, and Apt - best practices? References: <6k2aqqF5p185U1@mid.uni-berlin.de> <6k2c5pF5oenoU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> that is a very valid point, but it seemed that Scott has homogeneous >> environment: Debian/Ubuntu so my post was relative to the original >> request. >> I agree that when you throw Windows/MacOS into the mix things >> become "interesting". But then it's better when your developers >> develop on >> server/platform they are going to be using, using same stack they >> going to >> face in production etc. It all depends on requirements and current >> practices in company. > > Well, you certainly want a desktop-orientied Linux for users, so you > chose ubuntu - but then on the server you go with a more stable debian > system. Even though the both have the same technical and even package > management-base, they are still incompatible wrt to package versions for > python. > > And other constraints such as Photoshop not being available for Linux > can complicate things further. Photoshop for Windows runs fine under Wine, or at least it does on my Ubuntu box, just make sure you install the windows core fonts. I don't think many people realise how good Wine is these days, maybe because it was so useless for so long, it's pretty good right now. Also there's 'crossover' if you need even better out of the box Win32 binary compatibility. Roger. From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 4 04:33:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 10:33:58 +0200 Subject: use str as variable name In-Reply-To: References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> Message-ID: <48bf9d12$0$7552$426a74cc@news.free.fr> Mathieu Prevot a ?crit : > 2008/9/4 Chris Rebert : (snip) >> You're looking for the setattr() built-in function. In this exact case: >> setattr(a, arg, new_value) >> >> This is probably covered in the Python tutorial, please read it. >> >> Regards, >> Chris > > Indeed. > > I'll use: > a.__setattr__(height, new_value) Please don't. Use the generic setattr() function instead. This holds for any __magic__ method : they are *implementation* for operators and generic functions - which you can think of as operators with a function syntax -, and are not meant to be called directly. You wouldn't write something like 2.__add__(3), would you ? From almar.klein at gmail.com Tue Sep 30 07:07:17 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 30 Sep 2008 13:07:17 +0200 Subject: what does "python -i" use as input stream (stdin)? In-Reply-To: References: Message-ID: Wow, it's that easy... thanks! 2008/9/29 Gabriel Genellina > En Fri, 26 Sep 2008 04:29:42 -0300, Almar Klein > escribi?: > > I would still like to hear if anyone knows how I can change the input >> stream >> that >> is used when running "python -i", but I would not be surprised if it is >> impossible... >> > > Sure you can. You have to replace the file descriptor 0, that is, "standard > input"; sys.stdin reads from there. The standard way is to use os.dup2: > > c:\temp>type foo.txt > This line read from foo.txt > > > c:\temp>type redirect.py > import os > > inp = open("foo.txt","r") > os.dup2(inp.fileno(), 0) > print "raw_input->", raw_input() > > c:\temp>python redirect.py > raw_input-> This line read from foo.txt > > This is not > > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.leslie at gmail.com Tue Sep 30 01:07:14 2008 From: tim.leslie at gmail.com (Tim Leslie) Date: Tue, 30 Sep 2008 15:07:14 +1000 Subject: Newbie question... In-Reply-To: References: Message-ID: On Tue, Sep 30, 2008 at 12:04 PM, Ken D'Ambrosio wrote: > First, apologies for such a newbie question; if there's a better forum (I've > poked around, some) feel free to point it out to me. Anyway, a mere 25-odd > years after first hearing about OOP, I've finally decided to go to it, by > way of Python. But this puzzles me: > > import commands free = commands.getoutput("free") # free is now a string, representing the output from the "free" command for line in free: print line, This isn't doing what you think. Since free is a string, when you iterate over it, you get a single character each time, so your line variable isn't actually a line of the output, but a single character. When you run "print line," this prints the character, followed by a space. The comma at the end of the print statement tells it to put a space after the output rather than a newline. What you probably wanted to do is split up your output on the newline character. for line in free.split("\n"): print line Of course, your string already has all the newlines it needs in it, so if all you want is to see the output of the "free" command you can just do: print free HTH, Tim > > Gives: > t o t a l u s e d f r e e > s h a r e d b u f f e r s c a c h e d > M e m : 5 1 5 9 9 2 4 6 0 4 5 2 5 5 5 > 4 0 > 0 7 7 5 1 6 9 1 8 8 4 > - / + b u f f e r s / c a c h e : 2 9 1 0 5 2 2 2 4 9 > 4 0 > > Why are there spaces between everything? And how do I keep it from > happening? *confused* > > Thanks much, > > -Ken > ** Posted from http://www.teranews.com ** > -- > http://mail.python.org/mailman/listinfo/python-list > From rweir at ertius.org Tue Sep 9 02:17:14 2008 From: rweir at ertius.org (Rob Weir) Date: Tue, 09 Sep 2008 16:17:14 +1000 Subject: Newbie Question:Please help References: Message-ID: <87wshl7sid.fsf@hypercube.ertius.org> On 9 Sep 2008, Karthik Krishnan wrote: > File "", line 1 > python main_test.py > > Syntax Error: invalid syntax I get: File "/tmp/x.py", line 11 if __name__ = "__main__": ^ SyntaxError: invalid syntax > if __name__ = "__main__": ^ = is used for assignment in Python, you want ==. -- -rob From code at pizzashack.org Wed Sep 3 01:23:47 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 3 Sep 2008 01:23:47 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: References: <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> Message-ID: <20080903052347.GU29228@dragontoe.org> On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote: > Derek Martin wrote: > > On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: > >> but the instances of `Popen` are no actions. There's no way to > >> "execute" a `Popen` instance. > > > > Yes there is... you execute it when you instantiate the object. At > > the time of instantiation, you "open" the "P" (pipes). > > The subprocess module is also supposed to replace os.system and > os.spawn*, neither of which involve opening pipes. Uh... it's a replacement for os.popen(), which -- guess what -- opens pipes. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From gogala.mladen at gmail.com Fri Sep 19 03:13:48 2008 From: gogala.mladen at gmail.com (Mladen Gogala) Date: Fri, 19 Sep 2008 09:13:48 +0200 Subject: Python newbie Message-ID: I am a Python newbie who decided to see what that Python fuss is all about. Quite frankly, I am a bit perplexed. After having had few months of experience with Perl (started in 1994 with Perl v4, and doing it ever since) , here is what perplexes me: perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' The equivalent in Python looks like this: Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) [GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=[1,2,3] >>> map((lambda x: 2*x),a) [2, 4, 6] >>> map((print),a) File "", line 1 map((print),a) ^ SyntaxError: invalid syntax >>> for x in a: print x ... 1 2 3 >>> for x in a: x=2*x ... >>> for x in a: print x ... 1 2 3 >>> There are several questions: 1) Why is the array "a" unchanged after undergoing a transformation with map? 2) Why is it illegal to pass a built-in function "print" to map? 3) Why is the array "a" unchanged after undergoing an explicit transformation with the "for" loop? 4) Is there an equivalent to \$a (Perl "reference") which would allow me to decide when a variable is used by value and when by reference? PHP also allows changing arrays with "foreach" loop: #!/usr/local/bin/php How can I make sure that for x in a: x=2*x actually changes the elements of the array "a"? http://mgogala.freehostia.com From fredrik at pythonware.com Wed Sep 10 08:43:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 14:43:17 +0200 Subject: List of modules available for import inside Python? In-Reply-To: <9f3d127f-4434-4a27-b5d4-b43ebb137186@k30g2000hse.googlegroups.com> References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> <9f3d127f-4434-4a27-b5d4-b43ebb137186@k30g2000hse.googlegroups.com> Message-ID: Michele Simionato wrote: > I have just tried the following on my Ubuntu box with the system > Python: > > ~$ python /usr/lib/python2.5/doc/tools/listmodules.py > /usr/lib/python2.5/doc/tools/listmodules.py:99: DeprecationWarning: > the rgbimg module is deprecated > __import__(m) > > ** (process:24863): WARNING **: AT_SPI_REGISTRY was not started at > session startup. > > ** (process:24863): WARNING **: Could not locate registry > location: /usr/lib/xulrunner-1.9.0.1/libxpcom.so > before 3 > /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: cannot > register existing type `GtkSourceStyleScheme' > __import__(m) > /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: > g_type_set_qdata: assertion `node != NULL' failed > __import__(m) > /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: cannot > register existing type `GtkSourceBuffer' > __import__(m) > /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: > g_type_get_qdata: assertion `node != NULL' failed > __import__(m) > Segmentation fault > > Interesting, isn't it? it does indeed import modules found in the path if they appear to be Python C extensions. why Ubuntu puts badly written C modules in their default Python path is more than I can tell... From nick at craig-wood.com Wed Sep 10 20:36:32 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 10 Sep 2008 19:36:32 -0500 Subject: Simple UDP server References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> Message-ID: Tzury Bar Yochay wrote: > I am looking for the right way to write a small and simple UDP server. > > I am wondering between Forking, Threading (found at SocketServer.py) > and the one describes at the snippet below. > > Can you tell me the advantages and disadvantages of each > Would the one below will be capable of holding 30 concurrent > connections? > > I have no intention of using Twisted or alike since I am looking for > making it as lightweight as possible For UDP I wouldn't thread or, fork, I'd use select and run asynchronously. http://docs.python.org/lib/module-select.html Actually if I really had to do this I'd use twisted. Right tool for the job! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gary at byoteki.com Sun Sep 28 16:14:31 2008 From: gary at byoteki.com (Gary M. Josack) Date: Sun, 28 Sep 2008 16:14:31 -0400 Subject: generate random digits with length of 5 In-Reply-To: References: Message-ID: <48DFE5A7.5040000@byoteki.com> Aaron "Castironpi" Brady wrote: > On Sep 28, 2:59 pm, sotirac wrote: > >> Wondering if there is a better way to generate string of numbers with >> a length of 5 which also can have a 0 in the front of the number. >> >>
>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
>> elements
>>  code = 'this is a string' + str(random_number[0]) +
>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
>> + str(random_number[4])
>> 
>> > > '%05i'%random.randint(0,99999) > -- > http://mail.python.org/mailman/listinfo/python-list > This produces numbers other than 5 digit numbers. making the start number 10000 should be fine. From showellshowell at gmail.com Mon Sep 15 10:33:37 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Mon, 15 Sep 2008 07:33:37 -0700 (PDT) Subject: Representation of python code ? References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> Message-ID: <79cbd220-ca14-4b9b-b9f0-4d1136017d5a@v16g2000prc.googlegroups.com> On Sep 15, 7:17?am, Maric Michaud wrote: > Le Monday 15 September 2008 16:06:19 showellshow... at gmail.com, vous avez > ?crit?: > > > I'm not sure this is the best counterexample. ?You can see statically > > that A potentially creates an instance of the B class. > > > > class A : > > > ? ? def __init__(self) : > > > ? ? ? ? ?self._b = B() > > > > class B : pass > > Yes, you can, but are you sure it's obvious that B in A.__init__ is the class > you think of ? > I'm guessing 99% of the time it will be. It seems to me that if you're invoking classes in a truly dynamic way, you should be explicit about it anyway, and give methods some kind of naming convention, like have "factory" in the name. This would not only make it easy for a visualization program not to be tricked, but it would help out your human readers as well. From __peter__ at web.de Mon Sep 22 07:18:24 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Sep 2008 13:18:24 +0200 Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <5a37d7ca-e7b4-4278-8fc3-f5d0f4303cee@79g2000hsk.googlegroups.com> Message-ID: josh logan wrote: > A better example would be sorting by increasing last name and > decreasing first name. This would be easy with the sort function > comparator, but I can't see how to do the same with the key argument. > Is the only solution to decorate the Player objects in another class > that has the appropriate __cmp__ function (or whatever is needed) and > then retrieve the Player objects back? Python's sort algorithm is guaranteed to be stable; therefore you can sort twice: ordered = sorted(players, key=lambda p: p.fname, reverse=True) ordered.sort(key=lambda p: p.lname) Peter From heshan.suri at gmail.com Sun Sep 21 11:45:57 2008 From: heshan.suri at gmail.com (Heshan Suriyaarachchi) Date: Sun, 21 Sep 2008 10:45:57 -0500 Subject: Deploying a Python Service on Apache Axis2 Message-ID: <12e5d0d90809210845x1e304860wf6299f9b3c260e35@mail.gmail.com> Hi guys, Apache Axis2/Java, is a popular open source Web service engine. It currently supports exposing services written in Java, Javascript as Web services. This article [1] discusses the Python data Binding that enable exposing Web services written in Python. [1] - http://wso2.org/library/articles/deploying-python-service-axis2 [2] - http://heshans.blogspot.com/2008/09/wso2-wsfjython-10-alpha.html [3] - http://wso2.org/library/invoking-enterprise-web-services-using-jython -- Regards, Heshan Suriyaarachchi http://heshans.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Mon Sep 15 16:22:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 15 Sep 2008 13:22:06 -0700 (PDT) Subject: append on lists References: Message-ID: <0d66bfca-bd3b-4fc3-b3c6-a244677a7a5e@d45g2000hsc.googlegroups.com> On Sep 15, 9:24?pm, Armin wrote: > Hi, > > just a dumb question. > > Let a = [1,2,3,4,5] > > Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? > > --Armin Because list.append is a method that mutates its object, and such method usually return None. What you should check is the value of 'a' after 'a.append(7)'. -- Arnaud From kaerbuhez at gmail.com Wed Sep 10 05:55:14 2008 From: kaerbuhez at gmail.com (kaer) Date: Wed, 10 Sep 2008 02:55:14 -0700 (PDT) Subject: I want to use a C++ library from Python References: <6ipd53FrptpiU1@mid.uni-berlin.de> Message-ID: <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> On 10 sep, 10:00, "Diez B. Roggisch" wrote: > Anders Eriksson schrieb: > > > Hello, > > > I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1 > > .lib and 1 .dll files. I don't have the source code. > > > How can I create a Python module from these files? > > Did you bother googling? > > http://www.google.de/search?q=python+c%2B%2B&ie=utf-8&oe=utf-8 > > Diez You may want google "python dll" as well. Good luck. From stefan_ml at behnel.de Tue Sep 16 15:10:54 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 16 Sep 2008 21:10:54 +0200 Subject: Zsi interoperability In-Reply-To: References: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <48d004be$0$6672$9b4e6d93@newsspool2.arcor-online.net> Marco Bizzarri wrote: > On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel wrote: >> Mailing List SVR wrote: >>> I have to implement a soap web services from wsdl, the server is >>> developed using oracle, is zsi or some other python library for soap >>> interoperable with oracle soa? >> No idea, but I'd definitely try soaplib before ZSI. >> >> Stefan > > I'm working on a project where I need to write a client for SOAP with > Attachments; I can see ZSI does not support it; is soaplib any better? Never tried, but it's supposed to support it. In any case, soaplib is easy enough to use to just give it a try and see if it works for you. Stefan From rocky at panix.com Fri Sep 5 14:49:11 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 05 Sep 2008 14:49:11 -0400 Subject: pdb bug and questions References: <9d1d75a2-a6be-4d56-a53c-46b7942abf08@m73g2000hsh.googlegroups.com> Message-ID: castironpi writes: > On Sep 4, 4:22?pm, Stef Mientki wrote: >> hello, >> >> I'm trying to embed a debugger into an editor. >> I'm only interested in high level debugging. >> The first question is what debugger is the best for my purpose ? >> (pdb, pydb, rpdb2, smart debugger, extended debugger ? >> >> Second question, in none of the above debuggers (except rpdb2), >> I can find a ?"break now", >> so it seems impossible to me to detect unlimited while loops ? >> >> For the moment I started with pdb, because most of the debuggers seems >> to be an extension on pdb. >> When I launch the debugger ( winXP, Python 2.5) from with my editor >> ? python -u -m pdb ?D:\\Data\\test_IDE.py >> I get this error >> ? IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') >> NOTICE 1 backslash ----------------------------------^ >> >> If I launch the debugger with >> ? python -u -m pdb ?D:/Data/test_IDE.py >> It runs fine. >> >> This looks like a bug to me. >> What's the best way to report these kind of bugs ? >> >> Although I mostly use os.path.join to be OS independent, >> these kind of bugs give me the impression, >> that I can better do the join myself and always use forward slashes. >> Is this a valid conclusion ? >> >> thanks, >> Stef Mientki > > Stef, > > I discovered the same problem too with my editor. I solved it by > using only the file name, and setting the initial directory on the > executable. I don't know if this helps, but in pydb there is an option to set the initial directory the debugger works in. Inside the debugger there is the gdb command "cd". From d3vvnull at gmail.com Sat Sep 27 14:11:09 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sat, 27 Sep 2008 13:11:09 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DE3FC7.4030307@wildenhain.de> References: <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> Message-ID: <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> If the inputs are edited prior to the construction of the string and these fields are used for more than one update then it's not an exploit. It's simply a matter not repeating yourself when coding. In this particular case too, we're talking about a list of integers that gets inserted into a string. If the list is validated prior to its insertion into an SQL statement then there is no exploit. If I write a batch program (not a web program) that retrieves this list of integers from other sources and validates the data prior to using it in an SQL statement, that should be sufficient. As far as wrong and right is concerned. I think it's more about doing what is appropriate according to the circumstances. As a rule you should only code what is appropriate for the circumstances. If it's appropriate to code more simply without introducing unnecessary complexity you should do so. I work in the data warehousing ETL world, where we have to perform field edits or transformations to load source data into databases. If I'm already performing edits on these fields and if these fields are going to be used for more updates downstream, it's wasteful to perform them again when I build the SQL insert with the list and execute it. Finally, whatever happened to the practice of granting appropriate privileges to IDs that perform database operations? Shouldn't the person acting in the capacity of DBA ensure that the user updating or retrieving data from the database does not have DROP, ALTER, or CREATE privileges on that database? On Sat, Sep 27, 2008 at 9:14 AM, Tino Wildenhain wrote: > Hi, > > Michael Mabin wrote: > >> so you wouldn't object then to something like >> '.... in (%)' % ','.join([str_edit_for_exploit(x) for x in >> aList]) >> if str_edit_for_exploit applied security edits? >> > > Whats an security edit btw? If it is something meant to turn possibly > insecure data into 'secure' then, no I would still object. > Why? Because its a bad example of "default permit". Its always better > to have a whitelist - even more so when its so easy to do. > > Its just a habit you develope - if you never do it right, how would you > know when and how to do it right when you need to? > > Tino > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 9 16:16:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 17:16:07 -0300 Subject: biopython References: Message-ID: En Tue, 09 Sep 2008 05:53:19 -0300, Beema Shafreen escribi?: > Hi all, > I am using Biopython to fetch pumed Id's ,The module i use is (from Bio > import Entrez) > > But i am getting this error > >>>> from Bio import Entrez > Traceback (most recent call last): > File "", line 1, in ? > ImportError: cannot import name Entrez > > > what should i do know can anybody suggest me an alternative for this Ensure that you don't have *another* Bio module that is being imported instead of the true one. -- Gabriel Genellina From jjl at pobox.com Wed Sep 3 17:53:06 2008 From: jjl at pobox.com (John J Lee) Date: Wed, 3 Sep 2008 22:53:06 +0100 (BST) Subject: [wwwsearch-general] python - mechanize/browser/POST issue In-Reply-To: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> References: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> Message-ID: On Tue, 2 Sep 2008, bruce wrote: [...] > using mechanize/Browser, i can easily do a url/get, and process submitting a > form that uses a GET as the action. however, I'm not quite sure how to > implement the submittal of a form, that uses the POST action. [...] Same way as any other form. The HTTP method used is determined by the value of the form element's "action" attribute. John From marco.bizzarri at gmail.com Wed Sep 3 05:28:10 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 3 Sep 2008 11:28:10 +0200 Subject: Using httplib to access servlets on tomcat server In-Reply-To: References: Message-ID: <3f0d61c40809030228l6d0e93dclfbe93a868860d7cb@mail.gmail.com> On Wed, Sep 3, 2008 at 11:06 AM, jorma kala wrote: > Hi, > > I'm trying unsuccesfully to use the httplib library to execute servlets on a > local tomcat server. > > If I type the following http adress on my browser > http://localhost:8080/test/Serv1 the servlet works fine. > But if I try to access it with the following python code: > > conn = httplib.HTTPConnection("http://localhost:8080") > conn.request("GET", "/test/Serv1") > r1 = conn.getresponse() > > I get the following error: > > socket.gaierror: (11001, 'getaddrinfo failed') > > Do you know what I do wrong? > Thank you very much. > > localhost is not resolved to 127.0.0.1 on your machine. Try changing it to http://127.0.0.1:8080 Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From deets at nospam.web.de Sun Sep 21 10:38:21 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 21 Sep 2008 16:38:21 +0200 Subject: How to kill threading.Thread instance? In-Reply-To: References: <6jmn5kF42hreU1@mid.uni-berlin.de> Message-ID: <6jn4itF442e7U1@mid.uni-berlin.de> dmitrey schrieb: > I wonder why something like myThread.exit() or myThread.quit() or > threading.kill(myThread) can't be implemented? > Is something like that present in Python 3000? Not that I'm aware of it (which doesn't mean to much though). However I *am* aware of the bazillions discussions that have been held over this here - and the short answer is: it is a generally very bad idea to terminate threads hard, as it can cause all kinds of corruption. Systems like Java discourage the use of the available methods for that as well. And I for example once worked with Qt3-threads, what allow for this kind of operation - and killed my CORBA-ORB running in the same process by terminating the thread hard. Google a bit in this NG to find the discussions & reasons. Diez From kyosohma at gmail.com Fri Sep 26 09:48:52 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 26 Sep 2008 06:48:52 -0700 (PDT) Subject: cups.Connection.printFile References: Message-ID: On Sep 19, 9:01?am, Antoon Pardon wrote: > On 2008-09-16, Graham Jenkins wrote: > > > > > I'm trying to print a file from within a Python program. > > > The quick-and-dirty solution is to use something like: > > > fd = os.popen("lp -d MyPrinter", "wb") > > fd.write(MyFileContents) > > > But it seems to me that there should be a clean solution like: > > > import cups > > stat = > > cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") > > What about systems that don't use cups for printing? > > -- > Antoon Pardon For Windows, there's a few different ways to print. Tim Golden has a list on his website: http://timgolden.me.uk/python/win32_how_do_i/print.html Mike From lists at cheimes.de Fri Sep 12 14:38:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Sep 2008 20:38:17 +0200 Subject: Getting Linux partition info programmatically In-Reply-To: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> References: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> Message-ID: python dev wrote: > Hello everyone, > > I am trying to get a list of all the partitions (along with their respective > file system types) listed in the /media directory. Does anybody know if > there is a way to do this using Python, or do I have to get this information > by parsing the output of a Linux command? The /sys and /proc file system provide all the information you need: for line in open("/proc/mounts"): ... Christian From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 00:04:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 04:04:29 GMT Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <%nEwk.681$sq3.240@trnddc07> Message-ID: <00d34d25$0$30713$c3e8da3@news.astraweb.com> On Sat, 06 Sep 2008 23:30:03 +0000, Alan G Isaac wrote: >> bearophileHUGS at lycos.com writes: >> >>> For Python 2.7/3.1 I'd now like to write a PEP regarding the >>> underscores into the number literals, like: 0b_0101_1111, 268_435_456 >>> etc. >> >> +1 on such a capability. >> >> -1 on underscore as the separator. > > > On 9/1/2008 9:13 PM Ben Finney apparently wrote: >> When you proposed this last year, the counter-proposal was made >> >> to instead use white space for the separator, exactly as one can now do >> with string literals. > > Yuck. > Repeating a mistake means two mistakes. A lot of us don't think that white space between string literals was a mistake. A lot of us consider it a desirable feature. > But I would hate less the use of nobreak spaces, since any decent editor > can reveal them. How do you type a nobreak space? It's also probably a bad idea for Python the language to depend on developers using "a decent editor", since many people disagree on what a decent editor is, and many other people don't have access to whatever you consider "a decent editor". -- Steven From cyberco at gmail.com Fri Sep 12 04:57:42 2008 From: cyberco at gmail.com (Berco Beute) Date: Fri, 12 Sep 2008 01:57:42 -0700 (PDT) Subject: Python on Windows XP 64-bit: python not found in registry Message-ID: After first trying to install the beta of Python 2.6 on my Windows XP 64-bit machine I finally succeeded installing 2.5.2. But I still have a some problem: Installing iPython, PIL, easy_install etc fails saying that python.exe cannot be found (although I can start the python interpeter just fine). The problem is that python cannot be found in the registry. I tried Effbot's solution of adding Python to the registry, but that doesn't help: http://effbot.org/zone/python-register.htm Anybody here that had the same problem and solved it? Thanks. 2B From girzel at gmail.com Mon Sep 29 23:46:17 2008 From: girzel at gmail.com (Eric Abrahamsen) Date: Mon, 29 Sep 2008 20:46:17 -0700 (PDT) Subject: Using re to find unicode ranges References: Message-ID: On Sep 29, 11:03 pm, "Mark Tolonen" wrote: > "Eric Abrahamsen" wrote in message > > news:mailman.1674.1222694261.3487.python-list at python.org... > > > Is it possible to use the re module to find runs of characters within a > > certain Unicode range? > > > I'm writing a Markdown extension to go over text and wrap blocks of > > consecutive Chinese characters in tags for > > nice styling in an HTML page. The available hooks appear to be a pre- > > processor (which is a "for line in lines" situation) or an inline pattern > > (which uses regular expressions). The regular expression solution would > > be much simpler and faster, but something tells me there's no way to use > > a regex to find character ranges... Chinese characters appear to fall > > between 19968 and 40959 using ord(), and I suppose I can go that route if > > necessary, but I think it would be ugly. > > # coding: utf-8 > import re > sample = u'My name is ??. I am ???.' > for n in re.findall(ur'[\u4e00-\u9fff]+',sample): > print n Of course! And obvious, once you point it out. Thanks for the help. > This sounds similar to what zhpy (http://pyparsing.wikispaces.com/ > WhosUsingPyparsing#Zhpy) does to extract Chinese words from code, to > generate executable English Python. You might give that a look. > --Mark Mark - not quite what I'm after here, but pretty interesting nonetheless... E From bdesth.quelquechose at free.quelquepart.fr Fri Sep 26 16:16:29 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 22:16:29 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: <48dd5f08$0$26425$426a74cc@news.free.fr> Tim Rowe a ?crit : > 2008/9/26 Tino Wildenhain : > >>> The question I usually ask is "Does this language help me get the job >>> done?" Python often does. That's all that really matters, isn't it? >> Well then it still depends on the perception of "job done". For example >> PHP programmers would bet their soul that their language of choice is >> exactly the right one to "get the job done." :-) >> You and me would indeed see a different picture on the level of doneness >> of such jobs ;-) > > Well, I did say "Often". Before now I've struggled for ages to write a > Python program to do a job, then when I've tried C# all the problems > have fallen away and the job was done in an hour or so. Not to start a troll, but from what I've seen of C# so far I do find this a bit surprising and really suspect more of a library issue than a language one. Care to tell more about the problem and solution ? (NB : I wouldn't even asked if you had mentionned say Erlang or Prolog or OCaml - well, some mostly different language - instead of C#) From kalin at el.net Thu Sep 18 12:17:55 2008 From: kalin at el.net (kalin m) Date: Thu, 18 Sep 2008 12:17:55 -0400 Subject: locks In-Reply-To: <18641.17709.251764.767222@montanaro-dyndns-org.local> References: <48D140FC.8070801@el.net> <18641.17709.251764.767222@montanaro-dyndns-org.local> Message-ID: <48D27F33.1070400@el.net> yea... sorry... i just have all python stuff in the same folder and messed up... skip at pobox.com wrote: > kalin> mailman has been locking one list out. the web interface just > kalin> hangs and it generates a bunch of locks. it seems that it can not > kalin> write to a log but not sure which one. errors are like: > ... > > You'd probably be better off asking about Mailman problems on > mailman-users at python.org. > > From half.italian at gmail.com Fri Sep 26 00:11:53 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 25 Sep 2008 21:11:53 -0700 (PDT) Subject: SimpleXMLRPCServer -- turning off request log? References: <9e0d437b-a6a6-4485-aa9a-93ed751b700f@o40g2000prn.googlegroups.com> Message-ID: On Sep 25, 9:04?pm, Sean DiZazzo wrote: > On Sep 25, 6:01?pm, m... at pixar.com wrote: > > > My SimpleXMLRPCServer program prints to stderr a line like > > this for each request: > > > ohm..pixar.com - - [25/Sep/2008 17:57:50] "POST /RPC2 HTTP/1.0" 200 - > > > Is there a way to turn this logging off? ?I have RTFM and can't > > seem to find a way to do so. > > > Many TIA! > > Mark > > > -- > > Mark Harrison > > Pixar Animation Studios > > Im pretty sure there's a more pythonic way, but you could redirect > stdout to /dev/null > > import sys > sys.stdout = open("/dev/null", 'w') > > assuming you're not on windows... > > ~Sean Here's the more pythonic version: # Fake a file handle with the write method class NullDevice(object): def write(self, s): pass import sys sys.stdout = NullDevice() * http://code.activestate.com/recipes/278731/ Comment 1: attributed to Mr. Lundh ~Sean From nospam at spamhaters.com Sun Sep 21 22:30:21 2008 From: nospam at spamhaters.com (clurks) Date: Sun, 21 Sep 2008 21:30:21 -0500 Subject: BeautifulSoup and Problem Tables References: Message-ID: <1rDBk.1283$c45.771@nlpi065.nbdc.sbc.com> academicedgar at gmail.com wrote: > Hi > > I would appreciate some help. I am trying to learn Python and want to > use BeautifulSoup to pull some data from tables. I was really psyched > earlier tonight when I discovered that I could do this > > from BeautifulSoup import BeautifulSoup > bst=file(r"c:\bstest.htm").read() > soup=BeautifulSoup(bst) > rows=soup.findAll('tr') > len(rows) > a=len(rows[0].findAll('td')) > b=len(rows[1].findAll('td')) > c=len(rows[2].findAll('td')) > d=len(rows[3].findAll('td')) > e=len(rows[4].findAll('td')) > f=len(rows[5].findAll('td')) > g=len(rows[6].findAll('td')) > h=len(rows[8].findAll('td')) > i=len(rows[9].findAll('td')) > j=len(rows[10].findAll('td')) > k=rows[1].findAll('td')[1].contents[0] > > > So here I am chortling to myself thinking this is too easy. I know > that the data columns are in rows[0] and so I can learn some more > python to figure out how to create tuples so I can lable each data > item using the row and column headings plucked from the contents. > > However, I discovered that my tables have inconsistent numbers of > rows. Even though the tables look pretty. It might be that the > column heading for the third column is "Apples" but the value for > "Apples" in the fourth row is not in the third position in the row but > the fourth. > > Now I am reluctant to make any assumptions because the tables were > created inconsistently. What I mean is that in some tables if there is > no value for a row/column intersection then there is a blank line, in > other tables if there is no value for a row/column intersection then > the length of k (as above) is 0. > > I have been Googling for some insight into this and I have not been > successful finding anything. I would really appreciate any suggestions > or some direction about how to better describe the problem. This may help, and it may not. One of the most useful features of BeautifulSoup is the .prettify() function. Use it, and you can examine your xml with a browser or decent editor. You will be able, hopefully, to see attributes that may explain your difficulties. The one that snuck up and bit me was table:number-columns-repeated -- I don't know what is biting you, but it is weird the way known cells are completely skipped with this attribute -- you have to know about it and check for it. If there is a way to deal with that attribute using BeautifulSoup I was unable to find it given the documentation and examples available to me. I took a step back and tried xml.sax -- it is straighforward and easy to use -- you build an xml.sax.handler for your xml, and it deals with it. It worked for me, but, as always, YMMV sc From mwojc at NOSPAMp.lodz.pl Tue Sep 9 13:29:16 2008 From: mwojc at NOSPAMp.lodz.pl (mwojc) Date: Tue, 09 Sep 2008 19:29:16 +0200 Subject: F2PY changing integers to arrays??? References: <7d60c85f-12cf-47fc-84c9-58e50cad4eaf@x35g2000hsb.googlegroups.com> Message-ID: john wrote: > I have a simple module which performs basic operations on plot3d files > (below). I wrapped like: > > f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 > > That seems to work fine, but i get some unexpected results... > >>>> from plot3d import plot3d as p3 >>>> dir(p3) > ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', > 'writeit2d'] >>>> p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) >>>> p3.imax > array(409) > > > "409" is correct, but "imax" is declared as an INTEGER in fortran and > now it's an array in python??? Any ideas? > > > > > > > > > # prec.f90 > MODULE prec > IMPLICIT NONE > INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) > INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) > END MODULE prec > > > > > # plot3d.f90 > MODULE PLOT3D > USE prec > IMPLICIT NONE > INTEGER, PARAMETER :: prc=single > REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z > INTEGER :: mg, imax, jmax, kmax > > CONTAINS > > !---------- > SUBROUTINE READIT( fname, ftype, fmg ) > ! reads the plot3d, formatted, mg file in xyz > IMPLICIT NONE > CHARACTER(len=20), INTENT(IN) :: fname, ftype > > LOGICAL :: fmg > INTEGER :: i, j, k, n, f=1 > > SELECT CASE (ftype) > CASE ('FORMATTED') > OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > IF (fmg) READ(f,*) mg ! only read if multigrid > READ(f,*) imax, jmax, kmax > ALLOCATE( x(mg, imax, jmax, kmax) ) > ALLOCATE( y(mg, imax, jmax, kmax) ) > ALLOCATE( z(mg, imax, jmax, kmax) ) > READ(f,*) ((((x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ((((y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ((((z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > CASE ('UNFORMATTED') > OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > IF (fmg) READ(f) mg ! only read if multigrid > READ(f) imax, jmax, kmax > ALLOCATE( x(mg, imax, jmax, kmax) ) > ALLOCATE( y(mg, imax, jmax, kmax) ) > ALLOCATE( z(mg, imax, jmax, kmax) ) > READ(f) ((((x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ((((y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ((((z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > CASE DEFAULT > WRITE(*,*) 'filetype not supported in ' > STOP > END SELECT > > CLOSE(f) > > END SUBROUTINE READIT > > END MODULE PLOT3D I'm not sure why you obtain array(409) instead 409, but you can use this type in python as normal integer. For example array(409)+409 gives integer value 818. Greetings -- Marek From steve at holdenweb.com Thu Sep 18 13:01:55 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Sep 2008 13:01:55 -0400 Subject: append on lists In-Reply-To: <4097db86-b9dc-4ed5-ac84-6747a9f2bb11@t54g2000hsg.googlegroups.com> References: <4097db86-b9dc-4ed5-ac84-6747a9f2bb11@t54g2000hsg.googlegroups.com> Message-ID: tony.clarke5 at googlemail.com wrote: > On Sep 16, 6:03 am, Peter Anderson > wrote: >> "/... I don't think you've thought this one through, really./" >> snip >> >> We ought to try and be a little kinder to others on the list, don't you >> think? :-) >> >> snip > > Well said! >From personal experience I find that honest attempts to straighten people out lead to accusations of exploiting "seniority" to attack people. There goes the neighborhood, I guess. Of course we should try to maintain c.l.py's deserved reputation for civil behavior, but things like that aren't easy to police. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bdesth.quelquechose at free.quelquepart.fr Tue Sep 9 13:03:47 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 19:03:47 +0200 Subject: [OT] top-posting and quoting (was: Re: Coming from .NET and VB and C) In-Reply-To: <9efc52fa-f2d2-40e4-8fbb-fb4c06f8e0e4@a3g2000prm.googlegroups.com> References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <48bfc4e4$0$13232$426a74cc@news.free.fr> <9efc52fa-f2d2-40e4-8fbb-fb4c06f8e0e4@a3g2000prm.googlegroups.com> Message-ID: <48c6c862$0$17309$426a34cc@news.free.fr> Could you please timh and belindelof learn to quote properly and stop top-posting ? TIA From peter.waller at gmail.com Fri Sep 12 08:44:57 2008 From: peter.waller at gmail.com (Peter Waller) Date: Fri, 12 Sep 2008 05:44:57 -0700 (PDT) Subject: Injecting new names into the above frame Message-ID: Dear Pythoners, I know this will probably be perceived as 'evil voodoo', and fair enough: it probably is. I guess it is unpythonic. .. but I want to know how to do it anyway - mostly for my own interest. Consider the following snippet of code: --- def Get( *names ): if not names: return None frame = sys._getframe(1) prevFrameLocals = frame.f_locals for name in names: prevFrameLocals[ name ] = FetchObjectNamed( name ) Get("a", "b", "c") print a, b, c --- FetchObjectNamed() is an arbitrary function which takes a string and returns an object it got from some store somewhere. This works fine at the module level, because names in the locals/ globals dictionary can be played with in this way. The idea is to save lots of typing, i.e. a, b, c = Get("a","b","c") ..gets frustrating after much typing for many objects with long names. This is just an example, there are other instances I have where it would be nice to inject names into the frame above. Of course, we hit a road block when we call 'Get' from a function rather than a module, because the locals dictionary does not get copied back into the code object automatically, so we have to add this snippet before the Get() function returns: from ctypes import pythonapi, py_object, c_int pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 ) This copies back the names into the code object, and works fine.. that is, if the names already exist within the code object. def MyFunction(): a = None Get("a") print a # Works Get("b") print b # Name error, b is undefined Is there any way for Get() to define a new variable within MyFunction's code object? Or is there any programmatic way to, at runtime, insert new names into functions? I don't care how hacky it is and whether it requires making calls to python's internals with ctypes - maybe the whole code object needs to be replaced? is it even possible to do that when the Get() function is about to return to this new code object? Cheers, - Peter From ceball at users.sourceforge.net Thu Sep 11 16:10:23 2008 From: ceball at users.sourceforge.net (Chris) Date: Thu, 11 Sep 2008 20:10:23 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: Message-ID: Christian Heimes cheimes.de> writes: ... > You can use slots to increase the performance but it doesn't work > like you think. If you need it *really* fast than write a C > Extension, store the data in a C struct and access the data via > PyMemberDef. Ok, thanks for the confirmation. We'd been hoping to avoid creating such a struct... Chris From steve at holdenweb.com Thu Sep 18 13:19:49 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Sep 2008 13:19:49 -0400 Subject: append on lists In-Reply-To: References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: Armin wrote: > Duncan Booth wrote: >> "Chris Rebert" wrote: >>> On Tue, Sep 16, 2008 at 1:20 AM, Armin
wrote: >>>> [1,2,3,4,7].append(c) -> Is this a valid expression? >>> Literally, no, because you can't call methods on literals. >> >> Rubbish. There is no restriction about calling methods on literals. >> That expression is perfectly valid but has no practical use that I can >> see. > > The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > (with c = [8,9]) is identical, but the first expression doesn't provide > a value. Strange by design ... > Have a care, there. The semantics are different. lst = [1, 2, 3, 4, 7] lst.append([8, 9]) makes lst [1, 2, 3, 4, 7, [8, 9]] whereas lst = [1, 2, 3, 4, 7] lst = lst + [8, 9] makes lst [1, 2, 3, 4, 5, 7, 8, 9] I suspect you meant [1, 2, 3, 4, 5, 7] + [c] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fredrik at pythonware.com Sat Sep 27 08:06:36 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Sep 2008 14:06:36 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <48DC22C7.5020001@gmail.com> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> <48DC22C7.5020001@gmail.com> Message-ID: Stef Mientki wrote: > I don't think your suggestion is a good one. > If a filename has uppercase characters in it, > the END-USER has done that for some kind of reason. I explain how pdb works and show you how to solve the specific comparison problem you mentioned in your post, and you start ranting because it doesn't solve all your problems? what's wrong with you? From code at pizzashack.org Mon Sep 29 11:56:30 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 29 Sep 2008 11:56:30 -0400 Subject: Test if list contains another list In-Reply-To: <6304d804-57a1-458d-8ffe-b7a387dd0584@a1g2000hsb.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> <6304d804-57a1-458d-8ffe-b7a387dd0584@a1g2000hsb.googlegroups.com> Message-ID: <20080929155630.GM26713@dragontoe.org> On Mon, Sep 29, 2008 at 04:12:13AM -0700, bearophileHUGS at lycos.com wrote: > Derek Martin: > >Unless you're doing lots and lots of these in your application,< > > I don't agree. That's library code, so it has to be efficient and > flexible, because it's designed to be used in many different > situations That's fair, but lots of folks writing Python code will look at that and say, "What the %$#@! is this doing?!?" As I already suggested, code that implements non-obvious algorithms ought to explain what it's doing in comments, so that the neophyte programmers charged with maintaining the library aren't tempted to rewrite the code so that it's easier to understand what it's doing. It can be as simple as: # Use Morris-Pratt algorithm to search data Then, anyone not familiar with the algorithm can easily look it up, and see why it was written that way. I think it's just as important to do that in code you post on the list, since a) the person asking the question obviously doesn't know what you're doing, or they wouldn't have needed to ask the question, and b) there are lots of other folks reading the list who could benefit from the same knowledge. :) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From merwick.k at gmail.com Tue Sep 23 09:41:52 2008 From: merwick.k at gmail.com (merwick.k) Date: Tue, 23 Sep 2008 06:41:52 -0700 (PDT) Subject: The World Trade Plaza - Free Trade Leads Message-ID: <6d2bbe82-6d9c-4484-90e8-bb908bce885a@25g2000hsx.googlegroups.com> FREE INTERNATIONAL TRADE LEADS ==> The World Trade Plaza http://trade-plaza.blogspot.com Are you looking for potential clients for your products? Are you looking for a free place for to display your products? Each day we publish international purchase requisitions and offers for sale. The Trade Leads published in our website are FREE for everyone! You have NO NEED TO REGISTER for to view any lead in this website. You have NO LIMIT on Posting Trade Leads. You can Upload Photos With Every Import Export Leads. You can See Latest Products You can automatically receive All Trade Leads by email (Free Subscribe) Much more are All Free. Start Buying or Selling NOW. ==> http://trade-plaza.blogspot.com From tjreedy at udel.edu Fri Sep 26 17:06:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 17:06:24 -0400 Subject: Large Data Sets: Use base variables or classes? And some binding questions In-Reply-To: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> Message-ID: Patrick Sullivan wrote: > Hello. > > I will be using some large data sets ("points" from 2 to 12 variables) > and would like to use one class for each point rather than a list or > dictionary. I imagine this is terribly inefficient, but how much? I strongly suspect that you should use one class and a class instance for each 'point'. You can make instances 'fixed' after initialization by customizing appropriate methods, but I would not bother for private code. From tjreedy at udel.edu Mon Sep 1 15:08:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 15:08:30 -0400 Subject: how to find position of dictionary values In-Reply-To: <48BBA624.5010501@sellerengine.com> References: <48BBA624.5010501@sellerengine.com> Message-ID: Alexandru Palade wrote: > lookfor = 'dfsdf' > for item, value in kev.items(): > if lookfor in value: > print item > print value.index(lookfor) > break # assuming you only want one result slight variation: lookfor = 'dfsdf' for item, value in kev.items(): for i, val in enumerate(value): if val == lookfor: print item, i break # assuming you only want one result else: print lookfor, 'not found' This is what for-else is meant for. If you want 0 to many lookfor occurences, lookfor = 'dfsdf' hits = [] for item, value in kev.items(): for i, val in enumerate(value): if val == lookfor: hits.append((item, i)) print hits One-liner fanatics would, of course, rewrite this as hits = [(item, i) for item, value in kev.items() for i, val in enumerate(value) if val == lookfor] Terry Jan Reedy tjr From steve at REMOVE-THIS-cybersource.com.au Fri Sep 19 21:51:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Sep 2008 01:51:05 GMT Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: <00e45101$0$20331$c3e8da3@news.astraweb.com> On Fri, 19 Sep 2008 17:00:56 -0700, MRAB wrote: > Extending len() to support iterables sounds like a good idea, except > that it could be misleading when: > > len(file(path)) > > returns the number of lines and /not/ the length in bytes as you might > first think! Extending len() to support iterables sounds like a good idea, except that it's not. Here are two iterables: def yes(): # like the Unix yes command while True: yield "y" def rand(total): "Return random numbers up to a given total." from random import random tot = 0.0 while tot < total: x = random() yield x tot += x What should len(yes()) and len(rand(100)) return? -- Steven From tjreedy at udel.edu Fri Sep 26 16:59:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 16:59:09 -0400 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <48dd4756$0$25116$426a74cc@news.free.fr> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> Message-ID: nntpman68 wrote: > I guess you just filter mailing lists and can do nothing about the > newsgroup if I'm fetching via the nntp server of my ISP itself, right? I am reading via gmane.comp.python.general, so I will benefit from filtering spam posted to c.l.p. Anyone with a news reader can do the same. Just make a news.gmane.org account with standard port setting. Works fine with OE and now Tbird. I believe posts to gmane are sent to the mailing list first, before appearing even on gmane. > - I'm annoyed by any spam. Ditto. I would say 'nuisance' rather than 'major nuisance'. Improvements are appreciated here. > It's tough to find good rules, but the incoming spams that I see > currently on comp.lang.python have certain criteas. > > - most email addresses from gmail. > - all never posted before and then they have multiple posts within a few > minutes / seconds > - the posts always contain one or more urls ( mostly cryptic names ) > - they always start a thread but never reply to one > - the post doesn't contain python code or anything which looks only > vaguely like source code > - never mentions the word python > - the amount of sexual or financial vocabulary exceeds classical python > posts Pretty good list. From fredrik at pythonware.com Sat Sep 13 06:58:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 12:58:57 +0200 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Usman Ajmal wrote: > Where exactly should i call ServerProxy? Following is the code from my > client.py ServerProxy is the preferred name. Server is an old alias for the same class. > t = SecureTransport() > > t.set_authorization(ustring, text_ucert) > server = xmlrpclib.Server('http://localhost:8000/',transport=t) > print server.s() that code looks correct. so what's the problem? From gogtesuyash at gmail.com Tue Sep 30 01:15:43 2008 From: gogtesuyash at gmail.com (sui) Date: Mon, 29 Sep 2008 22:15:43 -0700 (PDT) Subject: python & sms References: Message-ID: On Sep 30, 10:10 am, "James Mills" wrote: > sui, > > I am sure you'll find many web services > that you can use to send SMS'. Your > problem would then become one of > learning how to communicate and access > web services in Python. Start with: > * urllib and urllib2 > * xmlrpc > > There are others... > > cheers > James > > On Tue, Sep 30, 2008 at 1:47 PM, sui wrote: > > Hii > > i want a script to send sms to any mobile..... > > can u help me ?? > > > Thanks in advance...... > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- > -- "Problems are solved by method" kk......wil try to use that... I thought if someone has already worked with it den it will be helpful.... thnks & cheers From half.italian at gmail.com Wed Sep 10 06:55:53 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 10 Sep 2008 03:55:53 -0700 (PDT) Subject: Catching subprocess stdout stream References: <00b9dc86-e002-4e2c-a686-39d2dd1016b9@m3g2000hsc.googlegroups.com> Message-ID: <9deaf3ef-2103-444f-bb46-309aee7045c5@r15g2000prd.googlegroups.com> On Sep 8, 8:37?am, Thomas Jansson wrote: > Dear all > > I have tkinkter based frontend to a Fortran based program. I use > subprocess to launch the fortran program as a child process and I wish > to see the output of the fortran program as it is created in the > console. > > The fortran program can take up to 20 minuttes to finish and at the > moment the I will first see any output after the fortran program is > done. How make my function write the output of the process as it > comes? > > def runprogram(Icommand, Ijobfile, Ioutput): > ? ? if os.name == "posix": > ? ? ? ? os.system(pythonpath+"/bin/"+Icommand+"< "+Ijobfile+" | tee > "+Ioutput) > ? ? elif os.name == "nt": > ? ? ? ? import subprocess > ? ? ? ? ofile = open(Ioutput, 'w') > ? ? ? ? p = subprocess.Popen([os.path.join(pythonpath, "bin", Icommand > + '.exe')], > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?stdin=open(Ijobfile, > "rb"),bufsize=1024,shell=False, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?stdout=subprocess.PIPE) > > ? ? ? ? while p.poll() is None: #Check if child process has terminated. > ? ? ? ? ? ? o = p.stdout.readline() > ? ? ? ? ? ? ofile.writelines(o) > ? ? ? ? ? ? print o, > ? ? ? ? ofile.close > > Kind regards > Thomas Jansson import threading, Queue, subprocess class iCommand(threading.Thread): def __init__ (self, iCommand, iJobFile, queue): threading.Thread.__init__(self) self.iCommand = iCommand self.queue = queue self.iJobFile = iJobFile def run(self): p = subprocess.Popen([os.path.join("C:/Python25", "bin", self.iCommand + '.exe')], stdin=open(self.iJobFile, "rb"),bufsize=1024,shell=False, stdout=subprocess.PIPE) while p.poll() == None: q.put(p.stdout.readline()) command = "FOO" jobFile = ="FAH" aQueue = Queue.Queue() fo = open("C:/temp/foo.out", 'w') aThread = iCommand(command, jobFile, aQueue) aThread.start() while aThread.isAlive() or not aQueue.empty(): l = aQueue.get().rstrip() fo.write(l) print l fo.close() A bit of fun for a sleepless night... ~Sean From circularfunc at yahoo.se Sun Sep 14 04:01:42 2008 From: circularfunc at yahoo.se (cnb) Date: Sun, 14 Sep 2008 01:01:42 -0700 (PDT) Subject: recursion gotcha? Message-ID: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> this recursive definition of sum thrumped me, is this some sort of gotcha or am I just braindead today? and yes i know this is easy a a for x in xs acc += x or just using the builtin. def suma(xs, acc=0): if len(xs) == 0: acc else: suma(xs[1:], acc+xs[0]) it returns none. def summa(xs): if not xs: 0 else: xs[0]+summa(xs[1:]) Traceback (most recent call last): File "", line 1, in summa([1,2,3,4,5]) File "", line 5, in summa xs[0]+summa(xs[1:]) File "", line 5, in summa xs[0]+summa(xs[1:]) File "", line 5, in summa xs[0]+summa(xs[1:]) File "", line 5, in summa xs[0]+summa(xs[1:]) File "", line 5, in summa xs[0]+summa(xs[1:]) TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' From stef.mientki at gmail.com Sat Sep 6 05:28:28 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 06 Sep 2008 11:28:28 +0200 Subject: wxPython problem In-Reply-To: <48C23638.1000109@internode.on.net> References: <48C23638.1000109@internode.on.net> Message-ID: <48C24D3C.7060306@gmail.com> Peter Anderson wrote: > I am trying to teach myself how to program in Python and use wxPython > for GUIs. I am using PyScripter, IDLE and EditPlus as my IDEs. I have > experienced an odd problem where I run a script once and it runs fine. > Run it again and I get an error and the script fails. > > If the script is run directly from Python ('Run' from Windows > Explorer) or from EditPlus (in which I have a "user-defined tool" > which calls C:\Python25\pythonw.exe with the parameter of $(FileName)) > then there is *never* any error, no matter how many times the script > is run. > > Close down PyScripter or IDLE and then start either up again, load the > script and run it - it runs fine. Run it again and it fails. It seems > like something is already set in memory and cant be re-set (my lack of > knowledge is showing here :-( ). > In PyScripter, you should run wxPython in the plain remote machine (not the wxPython remote), and you should set "reset before run flag" or reset the remote machine each time yourself. cheers, Stef > More details are shown below. Any help or hints would be greatly > appreciated. > > Regards, > Peter > > > RUNNING SIMPLE.PY (AND OTHER SCRIPTS USING WXPYTHON) FROM PYSCRIPTER I > GET THE FOLLOWING ERROR MESSAGE: > > PyNoAppError: The wx.App object must be created first! > > PyScripter loads a module (I presume from wxPython) called _windows.py > and highlights a particular line in red and displays the error message > from above. I have Googled the error message but the results have not > helped. > > > LISTING FOR SIMPLE.PY > > #!/usr/bin/python > > # simple.py > > import wx > > app = wx.App() > > frame = wx.Frame(None, -1, 'simple.py') > frame.Show() > > app.MainLoop() > > > EXERPT FROM _WINDOWS.PY - PYSCRIPTER HIGHLIGHTS SECOND LAST LINE > > class Frame(TopLevelWindow): > """Proxy of C++ Frame class""" > thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), > doc='The membership flag') > __repr__ = _swig_repr > def __init__(self, *args, **kwargs): > """ > __init__(self, Window parent, int id=-1, String title=EmptyString, > Point pos=DefaultPosition, Size size=DefaultSize, > long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) -> Frame > """ > > # The following line is highlighted as where the error occures > > _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) > self._setOORInfo(self) > > > RUNNING THE SIMPLE.PY SCRIPT FROM WITHIN IDLE PRODUCES THE FOLLOWING > ERROE MESSAGE: > > Traceback (most recent call last): > File "C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython > Tutorial\absolute.py", line 28, in > Absolute(None, -1, '') > File "C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython > Tutorial\absolute.py", line 9, in __init__ > wx.Frame.__init__(self, parent, id, title, size=(250, 180)) > File > "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", > line 505, in __init__ > _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) > PyNoAppError: The wx.App object must be created first! > > From sturlamolden at yahoo.no Wed Sep 24 12:56:17 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 09:56:17 -0700 (PDT) Subject: Python is slow? References: Message-ID: For those who are interested: I've updated the cookbook tutorial on the kd-tree: http://scipy.org/Cookbook/KDTree It now also includes parallel search for multicore CPUs (multiprocessing standard module). Even if you are not genuinely interested in kd-trees, it shows how to do parallel processing in Python despite of the GIL. From mbrkic at invalid_mail.adress Wed Sep 24 19:42:52 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Thu, 25 Sep 2008 01:42:52 +0200 Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> <7c1554cb-f167-462e-ac7c-ea82cdda99b6@y21g2000hsf.googlegroups.com> Message-ID: <0vjld4p4m8tcdble36uvne509cp8kv7rsj@4ax.com> On Wed, 24 Sep 2008 14:50:56 -0700 (PDT), sturlamolden wrote: >On Sep 24, 3:17?pm, Marin Brkic wrote: > >> Has anyone had a situation like this ? All your inputs and suggestions >> are more then welcomed. > >Send them the .py file and confirm that it does work. The lack of >Python can be blamed on the incompetent BOFH. Chances are the >situation will change when the BOFH gets 20 requests for Python a >day. > Yes, I agree. But in large institutions, where system engineers maintain a lot of computers there usually exists a policy on what is installed on computers and what is not. And currently python is not. And it's not gonna change anytime soon since only few of us are using it (2 of us use it on personal laptops, to others we send exe files). -- Marin From carsten.haese at gmail.com Tue Sep 30 13:32:21 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 30 Sep 2008 13:32:21 -0400 Subject: r"" In-Reply-To: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> Message-ID: Kyle Hayes wrote: > Is there a way to use the 'r' in front of a variable instead of > directly in front of a string? Or do I need to use a function to get > all of the slashes automatically fixed? Please describe the actual problem you're trying to solve. In what way do slashes need to be "fixed," and why? -- Carsten Haese http://informixdb.sourceforge.net From mr.spoon21 at gmail.com Mon Sep 29 17:45:45 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Mon, 29 Sep 2008 23:45:45 +0200 Subject: Music knowledge representation In-Reply-To: <20080929165608.b7b87b60.darcy@druid.net> References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> <20080929124940.8c1c82e8.darcy@druid.net> <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> <20080929165608.b7b87b60.darcy@druid.net> Message-ID: <8f67b6f80809291445y30e16a5cw31d1ab9ef3615a47@mail.gmail.com> On Mon, Sep 29, 2008 at 10:56 PM, D'Arcy J.M. Cain wrote: >> I can't estabilish which note is higher, because all the analysis part >> is octave independent. Anyway thanks for the ideas. > > I'm not sure I understand this. You either have to assume that the > first note is the root or the lower one is. What other options are > there? It sounds like your requirement is "higher += 12" or some > variant. It also depends on whether you need to deal with things like > ninths and thirteenths. > > Anyway, I was just tossing out ideas. You know what your requirements > are better than I. Mmm, actually it's a good idea. I didn't get it right before. Thanks :D From bhaarat.s at gmail.com Fri Sep 12 20:57:03 2008 From: bhaarat.s at gmail.com (bhaarat Sharma) Date: Fri, 12 Sep 2008 17:57:03 -0700 Subject: Good python web programming books Message-ID: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> Hi Guys, I am very new to python. I am looking for a good book about python web programming. I looked at a few online like Web Programming In Python but most are quite old. If you've read a good book on python web programming can you please suggest some? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From gstaniak at wp.pl Wed Sep 10 14:59:14 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Wed, 10 Sep 2008 18:59:14 +0000 (UTC) Subject: PHP's str_replace ? References: <6iq2jpFs113rU1@mid.uni-berlin.de> <6iq2sbFs113rU2@mid.uni-berlin.de> <48C7F6EA.7010202@anjanesh.net> <2746da03-39df-4bc0-9365-de5a2414adc4@f36g2000hsa.googlegroups.com> Message-ID: On 10.09.2008, David Thole wroted: >> >> new_str = re.sub('[aeiou]', '-', str) >> > Wow - this is neat. Thanks >> >> But probably slower and definitely harder to understand. For simple >> problems the str methods are usually faster than a regular expression. > > It's true that regular expressions are generally slower, but I > disagree that it's hard to understand. When dealing with text, I > think it's an absolute must that programmers know about regular > expressions. I think this here is an example where even str_replace > in Python wouldn't have worked well. What about mystring.translate(transtable)? GS -- Grzegorz Staniak Nocturnal Infiltration and Accurate Killing From google at mrabarnett.plus.com Fri Sep 19 20:00:56 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Sep 2008 17:00:56 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: On Sep 19, 2:01?pm, bearophileH... at lycos.com wrote: > Gerard flanagan: > > > data.sort() > > datadict = \ > > dict((k, len(list(g))) for k,g in groupby(data, lambda s: > > ? ? ?'.'.join(s.split('.',2)[:2]))) > > That code may run correctly, but it's quite unreadable, while good > Python programmers value high readability. So the right thing to do is > to split that line into parts, giving meaningful names, and maybe even > add comments. > > len(list(g))) looks like a good job for my little leniter() function > (or better just an extension to the semantics of len) that time ago > some people here have judged as useless, while I use it often in both > Python and D ;-) > Extending len() to support iterables sounds like a good idea, except that it could be misleading when: len(file(path)) returns the number of lines and /not/ the length in bytes as you might first think! :-) Anyway, here's another possible implementation using bags (multisets): def major_version(version_string): "convert '1.2.3.2' to '1.2'" return '.'.join(version_string.split('.')[:2]) versions = ["1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] bag_of_versions = bag(major_version(x) for x in versions) dict_of_counts = dict(bag_of_versions.items()) Here's my implementation of the bag class in Python (sorry about the length): class bag(object): def __init__(self, iterable = None): self._counts = {} if isinstance(iterable, dict): for x, n in iterable.items(): if not isinstance(n, int): raise TypeError() if n < 0: raise ValueError() self._counts[x] = n elif iterable: for x in iterable: try: self._counts[x] += 1 except KeyError: self._counts[x] = 1 def __and__(self, other): new_counts = {} for x, n in other._counts.items(): try: new_counts[x] = min(self._counts[x], n) except KeyError: pass result = bag() result._counts = new_counts return result def __iand__(self): new_counts = {} for x, n in other._counts.items(): try: new_counts[x] = min(self._counts[x], n) except KeyError: pass self._counts = new_counts def __or__(self, other): new_counts = self._counts.copy() for x, n in other._counts.items(): try: new_counts[x] = max(new_counts[x], n) except KeyError: new_counts[x] = n result = bag() result._counts = new_counts return result def __ior__(self): for x, n in other._counts.items(): try: self._counts[x] = max(self._counts[x], n) except KeyError: self._counts[x] = n def __len__(self): return sum(self._counts.values()) def __list__(self): result = [] for x, n in self._counts.items(): result.extend([x] * n) return result def __repr__(self): return "bag([%s])" % ", ".join(", ".join([repr(x)] * n) for x, n in self._counts.items()) def __iter__(self): for x, n in self._counts.items(): for i in range(n): yield x def keys(self): return self._counts.keys() def values(self): return self._counts.values() def items(self): return self._counts.items() def __add__(self, other): for x, n in other.items(): self._counts[x] = self._counts.get(x, 0) + n def __contains__(self, x): return x in self._counts def add(self, x): try: self._counts[x] += 1 except KeyError: self._counts[x] = 1 def __add__(self, other): new_counts = self._counts.copy() for x, n in other.items(): try: new_counts[x] += n except KeyError: new_counts[x] = n result = bag() result._counts = new_counts return result def __sub__(self, other): new_counts = self._counts.copy() for x, n in other.items(): try: new_counts[x] -= n if new_counts[x] < 1: del new_counts[x] except KeyError: pass result = bag() result._counts = new_counts return result def __iadd__(self, other): for x, n in other.items(): try: self._counts[x] += n except KeyError: self._counts[x] = n def __isub__(self, other): for x, n in other.items(): try: self._counts[x] -= n if self._counts[x] < 1: del self._counts[x] except KeyError: pass def clear(self): self._counts = {} def count(self, x): return self._counts.get(x, 0) From circularfunc at yahoo.se Sun Sep 7 16:47:33 2008 From: circularfunc at yahoo.se (cnb) Date: Sun, 7 Sep 2008 13:47:33 -0700 (PDT) Subject: problem with permutations Message-ID: I am trying to translate this elegant Erlang-code for finding all the permutations of a list. I think it is the same function as is but it doesn't work in Python. -- is upd in Python. It works as it should. perms([]) -> [[]]; perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. def perms(lista): if lista == []: return [[]] else: for h in lista: return [([h]+[t]) for t in perms(upd(lista, h))] def upd(lista, elem, acc=tuple([])): lista = tuple(lista) if lista == (): return list(acc) if lista[0] == elem: return list(acc + tuple(lista[1:])) else: return upd(lista[1:], elem, acc + tuple([lista[0]])) From mellowcellofellow at gmail.com Mon Sep 22 18:40:11 2008 From: mellowcellofellow at gmail.com (Joshua Gardner) Date: Mon, 22 Sep 2008 16:40:11 -0600 Subject: Using vObject Message-ID: I'm brand new to USENET so please bear with me. I'm writing a specialized to-do list app. I'm using Django but this is not a question about Django. It has to have recurring tasks set by the managers for the employees to then check off. I've got pretty much everything in the app worked out, except for one thing: the repeating tasks. I want to have it so that the manager puts in a repeating task with a description and a repeat rule. This rule then generates simpler one-time tasks. These one-time tasks have a description, a time (a datetime.datetime object) and "completed" boolean. I've looked around and think I have these options: 1. Manually put it all together with another Django model that implements the repeat rules. 2. Do the same thing but use dateutil.rrule to help. 3. Use the icalendar (http://codespeak.net/icalendar/) module to access ICS files. 4. vObject (http://vobject.skyhouseconsulting.com/) to do the same. I think I want to use vObject because it uses dateutil and the management can easily manage tasks from a desktop app. Only thing is that I find vObject's documentation very cryptic and was wondering if anybody here could shed some light on how to use vObject. A simple "getting-started" tutorial or something similar would be nice. Thanks all! -Josh From gherron at islandtraining.com Sun Sep 14 11:08:08 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 14 Sep 2008 08:08:08 -0700 Subject: Is there any nice way to unpack a list of unknown size?? In-Reply-To: <238815.3778.qm@web7902.mail.in.yahoo.com> References: <238815.3778.qm@web7902.mail.in.yahoo.com> Message-ID: <48CD28D8.9060104@islandtraining.com> srinivasan srinivas wrote: > I want to do something like below: > > 1. first, second, third, *rest = foo > Python 3.0 has exactly this feature. No current Python 2.x version has it. Gary Herron > 2. for (a,b,c,*rest) in list_of_lists: > > Please suggest. > > Thanks, > Srini > > > Bring your gang together. Do your thing. Find your favourite Yahoo! group at http://in.promos.yahoo.com/groups/ > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Sun Sep 7 07:50:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 08:50:50 -0300 Subject: modules path References: Message-ID: En Sat, 06 Sep 2008 20:26:24 -0300, Python escribi?: > now one question came up, how do I make those path permanent? > i mean, sys.path.append( adds it for the current session, > yet when i logout of IDLE and start it again it's gone... > how do i keep it in there? You can add that path to the PYTHONPATH environment variable, or you can put a .pth file in the current Lib directory, containing the desired path. See http://docs.python.org/inst/search-path.html and the documentation for the site module (although it appears not to be totally accurate). -- Gabriel Genellina From paul at boddie.org.uk Tue Sep 2 04:16:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 2 Sep 2008 01:16:55 -0700 (PDT) Subject: (in memory) database References: <5enqo5-9n9.ln1@lairds.us> <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> Message-ID: <3e419475-61a1-4579-a8b6-fc15f9fe0a9b@m73g2000hsh.googlegroups.com> On 2 Sep, 04:46, Zentrader wrote: > On Ubuntu you want to install something like python-sqlite (a search > for "python" should turn up everything). ?There are 2 parts to this, > SQLite and the python bindings to SQLite. ?So you seem to have SQLite > installed but not the Python bindings. ?Also, on some systems you have > to have python-sqlite installed, and then build python in order to use > it. The python-sqlite and python-sqlite2 packages were needed for Python 2.4 - it was possibly python2.4-sqlite or python2.4-sqlite2 if you go back a few versions - but Python 2.5 should depend on the sqlite libraries and pull them in automatically: http://packages.ubuntu.com/hardy/python2.5 I don't understand why Cameron has a different version of Python which doesn't seem to have sqlite support enabled. Paul From lists at cheimes.de Tue Sep 30 14:08:16 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 30 Sep 2008 20:08:16 +0200 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > > The executable would execute perfectly. > > > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") Try this: import subprocess retval = subprocess.call( ['Myprogram.exe', '1', '1', 'acc', '0'], cwd='C:\myprogramfolder\run') Christian From adityashukla1983 at gmail.com Sun Sep 21 14:33:24 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 21 Sep 2008 13:33:24 -0500 Subject: Newick parser Message-ID: <73045cca0809211133y3198bde2n483738de8cac2810@mail.gmail.com> Hello folks , i have a .nwk file.I want to parser the tree from that file.I found this python parser for newick trees. http://www.daimi.au.dk/~mailund/newick.html But i don't understand the usage properly.What i wanna do is if i have a file in the location c:\\files\\file1.nwk , then i wanna parse the trees in that file. Please help me if someone has experience on how to use this module. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From harish.shastry at gmail.com Tue Sep 16 09:32:53 2008 From: harish.shastry at gmail.com (Harish K Vishwanath) Date: Tue, 16 Sep 2008 19:02:53 +0530 Subject: Problem parsing the input In-Reply-To: References: Message-ID: <78f8019c0809160632u51b9fac8tcf4fe7892f76532c@mail.gmail.com> Consider the code below : x = """ ... ***** ... - Burst_Length not read from ini file ... ? - ... + BurstLength not read from ini file ... ***** ... - PilotTracking_Timing not read from ini file ... ? ^^^^^^^^^^^^^^ ... + NumTimings not read from ini file ... - Burst Position = 89511samples ... + Analysis Time (Iterations = 1) = 0.562249s ... + Rising Edge Time = 371683us ... - Rising Edge Time = 371682us ... """ >>> x '\n*****\n- Burst_Length not read from ini file\n? -\n+ BurstLength not read from ini file\n*****\n- PilotTracking_Timing not read from ini file\n? ^^^^^^^^^^^^^^\n+ NumTimings not read from ini file\n- Burst Position = 89511samples\n+ Analysis Time (Iterations = 1) = 0.562249s\n+ Rising Edge Time = 371683us\n- Rising Edge Time = 371682us\n' >>> import re *>>> num = re.compile('(?P[0-9]+)[^.]') >>> flt = re.compile('(?P[0-9]*\.[0-9]*)') *>>> flt.findall(x) ['0.562249'] >>> num.findall(x) ['89511', '1', '562249', '371683', '371682'] Those regular expressions can fetch the required input. On Tue, Sep 16, 2008 at 6:20 PM, wrote: > Hi, > I've a following input: > > ***** > - Burst_Length not read from ini file > ? - > + BurstLength not read from ini file > ***** > - PilotTracking_Timing not read from ini file > ? ^^^^^^^^^^^^^^ > + NumTimings not read from ini file > ***** > - Analysis Time (Iterations = 1) = 0.519444s > ? ^ --- > + Analysis Time (Iterations = 1) = 0.562249s > ***** > - Burst Position = 89511samples > ? ^ > + Burst Position = 89510samples > ***** > - Rising Edge Time = 371682us > ? ^ > + Rising Edge Time = 371683us > ***** > > How can I find the the colored items from the input. I though of using RE > but don't know much about it. > > The colored item can be dot notation e.g. 0.05678 or a whole digit as 5678 > > Please help > > > > -- > Regrads, > Rajat > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards, Harish -------------- next part -------------- An HTML attachment was scrubbed... URL: From uomiocenekidd at gmail.com Mon Sep 22 06:39:10 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:39:10 -0700 (PDT) Subject: download redtube video - Free Message-ID: download redtube video . . . *******CLICK HERE******** http://vids365.cn/download-redtube-video ***************************** . . . . . . . . . . . . download redtube video From lists at cheimes.de Tue Sep 30 14:10:53 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 30 Sep 2008 20:10:53 +0200 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <402462d4-e2a6-493b-9bc9-52aab68cad96@y71g2000hsa.googlegroups.com> References: <402462d4-e2a6-493b-9bc9-52aab68cad96@y71g2000hsa.googlegroups.com> Message-ID: giltay at gmail.com wrote: > I would add the following line right before your call to os.system: > > os.chdir(r'C:\myprogramfolder\run') I wouldn't. os.chdir() tends to introduce all sorts of trouble. It's a quick n'dirty hack for a small script but no solution for a large program or library. Christian From half.italian at gmail.com Wed Sep 10 17:21:11 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 10 Sep 2008 14:21:11 -0700 (PDT) Subject: formating a filesystem with python References: Message-ID: On Sep 10, 1:57?pm, "Ricardo Tiago" wrote: > Hi all, > > is there a package in python that allows to mount/umount and format > (to ext3) a filesystem? I know that this is possible by just calling > the os commands 'mount/umount and mkfs' but this would imply to have > to change sudoers to run the script as non-root. > > Thanks > Ric You can use pexpect to become root without changing sudoers. Assuming you know the root password... ~Sean From gagsl-py2 at yahoo.com.ar Tue Sep 30 03:15:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 04:15:45 -0300 Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <66606235-be55-458a-9e14-09e6c766201d@p31g2000prf.googlegroups.com> Message-ID: En Sun, 28 Sep 2008 07:01:12 -0300, Olivier Lauzanne escribi?: > On Sep 28, 11:21 am, est wrote: >> Can anyone tell me how to customize a default encoding, let's say >> 'ansi' which handles range(256) ? > > I assume you are using python2.5 > Edit the file /usr/lib/python2.5/site.py > > There is a method called > def setencoding(): > [...] > encoding = "ascii" > [...] > > Change "encoding = "ascii" to encoding = "utf-8" > > On windows you may have to use "mbsc" or something like that. I have > no idea what windows use at its encoding. *Not* a good idea at all. You're just masking errors, and making your programs incompatible with all other Pythons installed around the world. -- Gabriel Genellina From clp at rebertia.com Mon Sep 15 14:30:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Sep 2008 11:30:06 -0700 Subject: Converting .py files to batch files. In-Reply-To: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> Message-ID: <47c890dc0809151130p7e9b1e1fv3d335bc26fc7a630@mail.gmail.com> On Mon, Sep 15, 2008 at 10:30 AM, aditya shukla wrote: > How can we convert .py files to batch files? is there any library for this? Unless your Python scripts are essentially just *really basic* shell scripts that happen to be written in Python, then no, it's not even possible, much less automated. Python and batch files are just too vastly different: Python is a general-purpose programming language with a large standard library; batch files are a castrated version of bash. Perhaps if you could explain why you would want to do this in the first place, someone could suggest an alternative. Regards, Chris > > > Aditya > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From news1234 at free.fr Sat Sep 13 05:29:22 2008 From: news1234 at free.fr (nntpman68) Date: Sat, 13 Sep 2008 11:29:22 +0200 Subject: SSH using PEXPECT In-Reply-To: <4cc538ef-3b08-404c-b107-ff6605c307a2@t54g2000hsg.googlegroups.com> References: <4cc538ef-3b08-404c-b107-ff6605c307a2@t54g2000hsg.googlegroups.com> Message-ID: <48cb87f0$0$6999$426a74cc@news.free.fr> Hi, yellowblueyellow at gmail.com wrote: > On Sep 10, 7:01 pm, Sean DiZazzo wrote: > I am using windows and for reason it wont let me use pexpect even tho > I have CYGWIN installed > > > I get the following error > > Traceback (most recent call last): > File "new.py", line 1, in > import ssh_session > File "C:\Python25\lib\ssh_session.py", line 7, in > from pexpect import * > File "C:\Python25\lib\site-packages\pexpect.py", line 85, in > > support it. Pexpect is intended for UNIX-like operating > systems.""") > ImportError: No module named resource > You might have cygwin installed, but the error mesage sems to indicatem that you don't use cygwin's pythonm but the normal windows python, You see, that it complains about pexpcet in C:\Python25\lib\site-packages\pexpect.py just open a cygwin window: then cd to the directory containign your script and type python new.py. you should have at least another error message bye N From roy at panix.com Sun Sep 14 15:38:41 2008 From: roy at panix.com (Roy Smith) Date: Sun, 14 Sep 2008 15:38:41 -0400 Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <64670149-9467-4ca7-9d7e-c330c1b403e4@c58g2000hsc.googlegroups.com> Message-ID: In article <64670149-9467-4ca7-9d7e-c330c1b403e4 at c58g2000hsc.googlegroups.com>, "Aaron \"Castironpi\" Brady" wrote: > However, from what I understand (brass player), If you play the trombone, you might want your Note class to allow floating-point values for pitch :-) From asdfasdfasdfasdfasdf at arcor.de Sat Sep 6 18:00:07 2008 From: asdfasdfasdfasdfasdf at arcor.de (Andreas Hofmann) Date: Sun, 07 Sep 2008 00:00:07 +0200 Subject: String/Number Conversion In-Reply-To: <6de9141c-f350-4dfa-a36b-46e45344776a@q5g2000prf.googlegroups.com> References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> <6de9141c-f350-4dfa-a36b-46e45344776a@q5g2000prf.googlegroups.com> Message-ID: <48c2fd67$0$20941$9b4e6d93@newsspool2.arcor-online.net> Thanks a lot, I got it working now. Thanks also to the other guys, your numerous hints were really valuable! Kind regards, Andy John Machin schrieb: > On Sep 7, 7:04 am, Andreas Hofmann > wrote: >> Hello Folks! >> >> I've got a little problem here, which which really creeps me out at the >> moment. >> I've got some strings, which only contain numbers plus eventually one >> character as si-postfix (k for kilo, m for mega, g for giga). I'm trying >> to convert those strings to integers, with this function: >> >> def eliminate_postfix(value): >> if type(value) is str: > > Don't use "is" unless you are really sure that "==" won't do the job. > Better idiom: > if isinstance(value, str): > >> value.upper() > > This causes your "mult is always 1" problem. You need: > value = value.upper() > Why? Because strings are immutable. String methods like upper return a > new string, they don't change the existing string. > >> if value.endswith('K'): >> mult = 1000 >> elif value.endswith('M'): >> mult = 1000000 >> elif value.endswith('G'): >> mult = 1000000000 >> else: >> mult = 1 >> >> if mult is 1: > > Lose "is". In fact, lose the whole "if" statement. See below. > >> value = string.atoi(value) > > Don't use deprecated functions from the string module. Use the built- > in float function to convert from text. > >> else: >> value = string.atoi(value[:-1]) * mult >> return value > > Those last few statements look somewhat tortuous. Try this: > else: # mult would be 1, but we don't need it > return float(value) > return float(value[:-1]) * mult > > HTH, > John From adityashukla1983 at gmail.com Wed Sep 10 20:39:53 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Wed, 10 Sep 2008 19:39:53 -0500 Subject: Working with environment variables. Message-ID: <73045cca0809101739m560d382bi8ba506022f600286@mail.gmail.com> Hello folks, i am working with Python-2.5.2, fedora 9 sulphur I wanna change the value of environment variable , so if i open bash and type envvariable=value;export variable then this sets the envvariable equal to the value.Now i am writing a python script to set the value of this environment variable. import optparse import os def new_callback(option, opt_str, value, parser): os.putenv("envvariable",value) if __name__ == '__main__': p = optparse.OptionParser() p.add_option('-H',action="callback",callback=new_callback,type ="string") options, remainder = p.parse_args() when i run the script python prog.h -H value now this dosen't change the value of the variable which was set earlier .Please help me in fixing this issue. Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Tue Sep 16 08:22:19 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 14:22:19 +0200 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <1221564169.16690.0@proxy00.news.clara.net> Message-ID: <871vzk701w.fsf@mulj.homelinux.net> Armin writes: > What's the value of 1.add(b)? None? Or 3 ?? > (if add works in the same way as append) That's exactly the point -- __add__ doesn't work as append. append is a "destructive" operation, that mutates an existing object, whereas __add__ returns a different object to be used as the "result" of the addition. This is why append doesn't need to return anything, while __add__ must return the new object. The distinction is even more apparent with sort and sorted, which are destructive and non-destructive aspects of the same operation: >>> a = [3, 2, 1] >>> a.sort() # destructive (mutates object), so no return value >>> a [1, 2, 3] >>> a = [3, 2, 1] >>> b = sorted(a) # non-destructive (sorts a copy), returns the sorted copy >>> a [3, 2, 1] >>> b [1, 2, 3] From fredrik at pythonware.com Fri Sep 5 04:59:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 10:59:52 +0200 Subject: atomic section in code In-Reply-To: References: Message-ID: Ahmad Humayun wrote: > I need to create an atomic section in Python code i.e. there is no > context switch to any other thread during the running of that piece of > code. Would would do the trick? use a lock, and make sure that anyone that needs access to the shared state you're manipulating in that section uses the same lock. lock = threading.Lock() # or RLock() etc [1] with lock: section this only works if everyone honors the lock, of course; there's no way in Python to lock out non-cooperating external threads. 1) see http://effbot.org/zone/thread-synchronization.htm From mail at timgolden.me.uk Thu Sep 25 04:36:35 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 25 Sep 2008 09:36:35 +0100 Subject: Connecting to SMB share in python In-Reply-To: References: Message-ID: <48DB4D93.4040606@timgolden.me.uk> Ronnie Kwok wrote: > Hello, > > I am trying to write a script that copy files from my local machine to a samba > share. Can't you just mount the share (albeit temporarily) and copy the files over in the normal way? You haven't said what OS you're on, but I'm assuming Linux otherwise you'd simply be talking about a Windows share and copying to a UNC. TJG From bignose+hates-spam at benfinney.id.au Sun Sep 14 18:41:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 08:41:22 +1000 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> Message-ID: <87abea73l9.fsf@benfinney.id.au> Astley Le Jasper writes: > Is it best to have it all in one script or split it into per site > scripts that can then be called by a manager script? If everything > is in one script would you have per site functions to extract the > data or generic function that contain vary slightly depending on the > site, for example > > import firstSiteScript > import secondSiteScript First: each of these things you're importing is a "module" in Python. A script is what I prefer, for clarity, to call a "program": it's intended to be executed independently as the top level of execution. Second: please do yourself a favour and drop the camelCaseNames. Follow PEP 8 for style and naming in your Python code. > firstsitedata = firstSiteScript.getData('search_str) > secondsitedata = secondSiteScript.getData('search_str) > etc etc I'm presuming that there will be large areas of common functionality between these different sites. On that basis, it's prbably best to treat the differences as differences of *configuration* where possible, instead of having separate modules for the entire site. You might like to look at a web framework which gathers much of this functionality together for you, and provides flexible ways to define different sites in terms of those common elements . -- \ ?Following fashion and the status quo is easy. Thinking about | `\ your users' lives and creating something practical is much | _o__) harder.? ?Ryan Singer, 2008-07-09 | Ben Finney From steve at REMOVE-THIS-cybersource.com.au Mon Sep 15 19:03:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Sep 2008 23:03:59 GMT Subject: append on lists References: Message-ID: <00dee3f7$0$20331$c3e8da3@news.astraweb.com> On Mon, 15 Sep 2008 13:47:53 -0700, Chris Rebert wrote: > The code you'd actually want is: > > d = a[:] #copy a > d.append(7) > > Or if you're willing to overlook the inefficiency: > > d = a + [7] > > But that's not idiomatic. Why is a + [7] more inefficient than manually copying the list and appending to the copy? Surely both pieces of code end up doing the same thing? In fact, I'd guess that the second is likely to be marginally more efficient than the first: >>> x = compile('d = a[:]; d.append(7)', '', 'exec') >>> dis.dis(x) 1 0 LOAD_NAME 0 (a) 3 SLICE+0 4 STORE_NAME 1 (d) 7 LOAD_NAME 1 (d) 10 LOAD_ATTR 2 (append) 13 LOAD_CONST 0 (7) 16 CALL_FUNCTION 1 19 POP_TOP 20 LOAD_CONST 1 (None) 23 RETURN_VALUE >>> x = compile('d = a + [7]', '', 'exec') >>> dis.dis(x) 1 0 LOAD_NAME 0 (a) 3 LOAD_CONST 0 (7) 6 BUILD_LIST 1 9 BINARY_ADD 10 STORE_NAME 1 (d) 13 LOAD_CONST 1 (None) 16 RETURN_VALUE timeit agrees with me: >>> from timeit import Timer >>> t1 = Timer('d = a[:]; d.append(7)', 'a = []') >>> t2 = Timer('d = a + [7]', 'a = []') >>> t1.repeat(number=1000) [0.0015339851379394531, 0.0014910697937011719, 0.0014841556549072266] >>> t2.repeat(number=1000) [0.0011889934539794922, 0.0013048648834228516, 0.0013070106506347656] -- Steven From wuwei23 at gmail.com Fri Sep 26 21:06:59 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 26 Sep 2008 18:06:59 -0700 (PDT) Subject: lxml question References: <2f9ef7d5-616e-4a4b-9a83-e23194fee3a9@m3g2000hsc.googlegroups.com> Message-ID: <6e99bb12-2838-4095-b76e-2514530936d7@n38g2000prl.googlegroups.com> On Sep 27, 1:19?am, Uwe Schmitt wrote: > I have to parse some text which pretends to be XML. lxml does not want > to parse it, because it lacks a root element. Another option is BeautifulSoup, which handles badly formed XML really well: http://www.crummy.com/software/BeautifulSoup/ From grante at visi.com Fri Sep 26 23:11:56 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 26 Sep 2008 22:11:56 -0500 Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> Message-ID: <4p-dnSA-j8LhOUDVnZ2dnUVZ_tCdnZ2d@posted.usinternet> On 2008-09-27, George Sakkis wrote: > On Sep 26, 9:30?pm, Grant Edwards wrote: > >> On 2008-09-26, nntpman68 wrote: >> >> > Hm, >> >> > I guess you just filter mailing lists and can do nothing about the >> > newsgroup if I'm fetching via the nntp server of my ISP itself, right? >> >> I read the group via NNTP, and I find that blocking all >> articles posted from google.groups gets rid of all of the spam. > > ... along with a far from trivial (I guess) percentage of > non-spam, such as this post. Yup. Some non-spam gets filtered out as well. IMO, it's worth it. -- Grant From lists at cheimes.de Mon Sep 1 06:21:22 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 01 Sep 2008 12:21:22 +0200 Subject: Processes in Linux from Python In-Reply-To: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> References: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> Message-ID: Johny wrote: > Is it possible to get a number of the http processes running on Linux > directly from Python ? The Python core has no direct API for the job. However you can use the virtual /proc/ file system for the job. Or check out my enumprocess package. http://pypi.python.org/pypi?:action=display&name=enumprocess&version=0.1 It's far from perfect but it should do the job on Linux. Christian From kaerbuhez at gmail.com Sat Sep 6 16:27:46 2008 From: kaerbuhez at gmail.com (kaer) Date: Sat, 6 Sep 2008 13:27:46 -0700 (PDT) Subject: running python as a dameon References: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> <6e7ead25-baf1-400a-a52f-568f37351aab@8g2000hse.googlegroups.com> <5c74118c-a576-4a51-ae9a-95d34273a99a@s50g2000hsb.googlegroups.com> Message-ID: On 6 sep, 22:16, kaer wrote: > On 6 sep, 15:44, Michael Palmer wrote: > > > > > On Sep 5, 9:56 pm, Sean Davis wrote: > > > > > What I want > > > > to do is to provide the python NLP program as a service to any other > > > > PHP/Java/Ruby process request. So the mapping is > > > > > http -> apache -> PHP/Java/Ruby/... -> Python NLP > > > > Why not use a simple CGI script or wsgi application? You could make > > > the service online and interactive and with the same application and > > > code make an XMLRPC web service. So, things would look more like: > > > > http -> apache -> Python (running NLP and serving requests) > > > > You can use apache to proxy requests to any one of a dozen or so > > > python-based webservers. You could also use mod_wsgi to interface > > > with a wsgi application. > > > > Sean > > > xmlrpc is the right idea, as it interfaces easily across languages. > > I just daemonize some utility script these week. For that I took one > of the scripts in the ASPN python cookbook : google those 3 words then > search python and you will find out your solution faster than I end up > this mail. It worked like a charm on my linux box. > BTW, I wouldn't complicate with xml stuffs if you don't need it. > > Good luck. you obviously "search daemon" not "search python". Her is the link: http://www.google.com/search?q=daemon&hl=en&ie=UTF-8&btnG=Google%2BSearch&qdr=all&occt=any&dt=i&sitesearch=code.activestate.com From enleverlesX.XmcX at XmclaveauX.com Mon Sep 15 14:24:18 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 15 Sep 2008 20:24:18 +0200 Subject: objet COM et ms Word In-Reply-To: <245dc065-660f-4dfe-8134-14b4acfc1f2d@j22g2000hsf.googlegroups.com> References: <245dc065-660f-4dfe-8134-14b4acfc1f2d@j22g2000hsf.googlegroups.com> Message-ID: <48ceaba5$0$946$ba4acef3@news.orange.fr> Bonsoir ! J'ai r?pondu, dans le newsgroup fran?ais. @-salutations -- Michel Claveau From gabriel.rossetti at arimaz.com Tue Sep 23 06:01:40 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Tue, 23 Sep 2008 12:01:40 +0200 Subject: python freeze help Message-ID: <48D8BE84.5020204@arimaz.com> Hello everyone, I'm trying to use python's freeze utility but I'm running into problems. I called it like this : python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py ~/Documents/Code/Python/src/jester/service.py -m jester then I did : make then I tried to run it : ./service and I get this : grossetti at desktop-01:~/tmp/freeze$ ./service Traceback (most recent call last): File "/home/grossetti/Documents/Code/Python/src/jester/service.py", line 16, in from jester import constants, utils File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line 20, in from twisted.internet.protocol import Protocol, ClientCreator File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", line 17, in from zope.interface import implements File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in pkg_resources.declare_namespace('zope') File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, in declare_namespace _handle_ns(packageName, path_item) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, in _handle_ns path = module.__path__; path.append(subpath) AttributeError: 'str' object has no attribute 'append' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in from apport.report import Report File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in from problem_report import ProblemReport File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in from email.MIMEMultipart import MIMEMultipart File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__ __import__(self.__name__) ImportError: No module named multipart Original exception was: Traceback (most recent call last): File "/home/grossetti/Documents/Code/Python/src/jester/service.py", line 16, in from jester import constants, utils File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line 20, in from twisted.internet.protocol import Protocol, ClientCreator File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", line 17, in from zope.interface import implements File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in pkg_resources.declare_namespace('zope') File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, in declare_namespace _handle_ns(packageName, path_item) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, in _handle_ns path = module.__path__; path.append(subpath) AttributeError: 'str' object has no attribute 'append' Does anyone have any ideas as of why I get this? Thank you, Gabriel From george at george-net.de Mon Sep 15 15:37:50 2008 From: george at george-net.de (Georg Altmann) Date: Mon, 15 Sep 2008 21:37:50 +0200 Subject: MVC with Python Message-ID: Hello, I need some advice on how to implement model-view-controller. I am trying to develop a GUI application with PyQt, yet the problem rather applies to mvc in general, not just GUI applications. Let's say the data is a list of objects with a common base class. The views are either a graphical representation of the objects or some form of textual input. The views shall change the model by using command objects (for undo, e.g. QUndoCommand). My current approach is to implement the model as a class with a list-like interface, with methods insert(), remove(), __getitem__(), __setitem__(),... and a signal to notify the views. The objects in the list have methods to change their state as well. My problem is, how do the commands interact with the model? Let's say I have a command that modifies an object o in the list. 1) If list[key_to_o] returns a reference to the object, the command can modify the object by using this reference, i.e. list[key_to_o].setX(). So there is no way for the list to know when the object changed - how can it emit a singal then? 2) If list[key_to_o] returns a deep copy of the object, copy_of_o = list[key_to_o], the command mofifies the copy and the updates the list: list[key_to_o] = copy_of_o. Now the list can emit a signal in __setitem__(). While this may work, it seems awkward to copy around objects just to perform a possibly simple operation on them. Additionally it might not be feasible once objects get complex. 3) The interface of the classes of the objects could be reflected in the list class, i.e. list.set_x_on_obj(key_to_obj,x). This would probably make the list class interface very bloated. Of course the problem is not really limited to Python, my apologies if I'm totally off-topic here. Regards Georg From gagsl-py2 at yahoo.com.ar Thu Sep 11 20:23:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Sep 2008 21:23:22 -0300 Subject: catching exceptions from fortran References: Message-ID: En Thu, 11 Sep 2008 10:43:08 -0300, john escribi?: > I wrapped some fortran code using F2PY and need to be able to catch > fortran runtime errors to run the following: > [reindented] > # "grid" is a wrapped fortran module > # no runtime errors incurred when run with the correct inputs for > filetype > #------------------------------- > def readGrid( self, coord='xyz' ): > mg = ( '.FALSE.', '.TRUE.' ) > form = ( 'FORMATTED', 'UNFORMATTED' ) > success = False > for m in mg: > for f in form: > try: > if coord == 'xyz': > self.grid.readxyz( self.filename, f, m ) > success = True > elif coord == 'xyrb': > self.grid.readxyrb( self.filename, f, m ) > success = True > else: > import sys > print 'gridtype "' + str(coord) + '" not supported. ' \ > + '' > except: > continue > if not success: > import sys > print 'gridfile "' + str(self.filename) + '" not read in any > recognized format' \ > + ' ' > #---------------------------- I suppose you want to stop trying other formats after a successful read; in that case put a break statement just below both success=True. If coord is unrecognized, the code above prints the same message 4 times. Instead of printing a message, in those cases usually an exception is raised, letting a higher layer handle the error. And using string interpolation is a lot easier than building the message in parts: raise ValueError('gridtype "%s" not supported. ' % coord) If you want to catch errors on the Fortran code *only*, the try/except should be more specific (both in scope and what it catches). The Exception class is the more generic exception that you should catch. > basically, what i want to happen is to try to run 'something' with the > wrapped fortran code and if that doesn't work (error encountered, > etc.) try something else. is there an easier way to go about doing > this? is there something i'm missing about catching exceptions here? I'd reorder the code in this way (untested, of course): def readGrid(self, coord='xyz'): def try_all_formats(read_function, filename): mg = ('.FALSE.', '.TRUE.') form = ('FORMATTED', 'UNFORMATTED') success = False for m in mg: for f in form: try: read_function(filename, f, m) success = True break except Exception, e: # this line only for debugging purposes print "error %r when using m=%r f=%r" % (e, m, f) continue if not success: raise ValueError('gridfile "%s" not read ' 'in any recognized format ' '' % filename) if coord == 'xyz': try_all_formats(self.grid.readxyz, self.filename) elif coord == 'xyrb': try_all_formats(self.grid.readxyrb, self.filename) else: raise ValueError('gridtype "%s" not supported. ' '' % coord) I don't know about F2PY but the values ('.FALSE.', '.TRUE.') seem suspicious. AFAIR, .FALSE. and .TRUE. are the Fortran spellings of False and True in Python - they're not strings, but boolean values. So maybe the right way is to use mg = (False, True) Your code above was catching and ignoring everything, even this error, if it happened. -- Gabriel Genellina From python.dev.9 at gmail.com Fri Sep 12 14:29:34 2008 From: python.dev.9 at gmail.com (python dev) Date: Fri, 12 Sep 2008 14:29:34 -0400 Subject: Getting Linux partition info programmatically Message-ID: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> Hello everyone, I am trying to get a list of all the partitions (along with their respective file system types) listed in the /media directory. Does anybody know if there is a way to do this using Python, or do I have to get this information by parsing the output of a Linux command? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marco.bizzarri at gmail.com Mon Sep 1 09:10:41 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 1 Sep 2008 15:10:41 +0200 Subject: How to print first(national) char from unicode string encoded in utf-8? In-Reply-To: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> Message-ID: <3f0d61c40809010610y664b360ate6f3a8919e258583@mail.gmail.com> 2008/9/1 : > Hi, > > I have a problem with unicode string in Pylons templates(Mako). I will > print first char from my string encoded in UTF-8 and urllib.quote(), > for example string '?ukasz': > > ${urllib.unquote(c.user.firstName).encode('latin-1')[0:1]} > > and I received this information: > > : 'utf8' codec can't decode byte > 0xc5 in position 0: unexpected end of data > > When I change from [0:1] to [0:2] everything is ok. I think it is > because of unicode and encoding utf-8(2 bytes). > > How to resolve this problem? > > Best regards > -- > http://mail.python.org/mailman/listinfo/python-list > First: you're talking about utf8 encoding, but you've written latin1 encoding. Even though I do not know Mako templates, there should be no problem in your snippet of code, if encoding is latin1, at least for what I can understand. Do not assume utf8 is a two byte encoding; utf8 is a variable length encoding. Indeed, 'a' encoded as utf8 is 'a' (one byte) '?' encode as utf8 is '\xc3\xa0' (two bytes). Can you explain what you're trying to accomplish (rather than how you're tryin to accomplish it) ? Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From akineko at gmail.com Mon Sep 1 21:09:58 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 18:09:58 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Message-ID: On Sep 1, 5:52 pm, "Guilherme Polo" wrote: > Are you trying to simulate clicks ? You should be doing it using > event_generate, more below. > Actually, I was trying to implement a "sticky" button. (Button Release is done later by another event) I already tried event_generate. It worked as far as I didn't touch other widgets. But somehow it failed to work if event_generate is called after other widgets are activated. > You should expect them to be totally removed from Tkinter actually. Sad to hear that. Controlling the button behaviour explicitly may not be a common thing to do but it is still necessary thing to do. But you gave me enough insights. Aki- From wuwei23 at gmail.com Sun Sep 21 09:16:32 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 21 Sep 2008 06:16:32 -0700 (PDT) Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> Message-ID: <9f97f262-b90e-4bc1-9e9c-851bb962ce89@b30g2000prf.googlegroups.com> On Sep 21, 10:51?pm, Alex wrote: > Why? I'm coping data_set in ds so why data_set is changed? You're making a copy of the ds tuple, which has the -same- contents as the original. To create copies of the contents as well, try the deepcopy function from the copy module. As an aside, you're also trying to make a copy of ds for each iteration of the loop, which is unnecessary in this case. Here's a slightly better example of your code: >>> from copy import deepcopy >>> data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) >>> ds = deepcopy(data_set) >>> for i, data in enumerate(ds): ... if i == 1: data['param'] = "y" ... if i == 2: data['param'] = "x" ... >>> print data_set ({'param': 'a'}, {'param': 'b'}, {'param': 'c'}) >>> print ds ({'param': 'a'}, {'param': 'y'}, {'param': 'x'}) Although your use of a tuple full of dicts for data_set is kinda strange... Tuples are generally used when you want a structured data element, in which case you'd just address each element directly rather than iterate through it: >>> ds = deepcopy(data_set) >>> ds[1]['param'] = "y" >>> ds[2]['param'] = "x" From prologic at shortcircuit.net.au Wed Sep 10 17:52:44 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 07:52:44 +1000 Subject: Alternatives to traditional RDBMS In-Reply-To: References: <6iq90jFdeiU1@mid.uni-berlin.de> Message-ID: On Thu, Sep 11, 2008 at 3:40 AM, Daniel Fetchinson wrote: > There is also dejavu: http://www.aminus.net/dejavu This is an ORM. They are off-topic for this thread :) cheers James -- -- -- "Problems are solved by method" From grante at visi.com Tue Sep 16 09:49:48 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:49:48 -0500 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <87d4j4798g.fsf@mulj.homelinux.net> Message-ID: On 2008-09-16, Hrvoje Niksic wrote: > Duncan Booth writes: > >> The only relatively common use I can think of where you might want to call >> a method directly on a literal is to produce a list of strings while being >> lazy about the typing: > > By far the most common is probably 'sep'.join(iterable). It's also somewhat common to index into a literal: ['one','two','three'][n] {1:'one', 2:'two', 7:'seven'}[n] -- Grant Edwards grante Yow! I was born in a at Hostess Cupcake factory visi.com before the sexual revolution! From simon.peverett at gmail.com Thu Sep 4 06:20:11 2008 From: simon.peverett at gmail.com (Impotent Verse) Date: Thu, 4 Sep 2008 03:20:11 -0700 (PDT) Subject: Serial I/O problem with pywin32 ? References: <6i7p2uFp2lqbU1@mid.uni-berlin.de> Message-ID: On 3 Sep, 16:33, "Diez B. Roggisch" wrote: > Xavier schrieb: > > > > > Hi, > > > I try to access to a Bluetooth GPS data-logger with Python. I use > > pySerial. > > > Sending and receiving little messages (~100 char) works fine. However, > > when I ask the GPS to dump the trails, it returns some Mbytes and here > > is the problem : in the stream of bytes, I randomly losts chunks of > > ~100bytes. > > > I tried USPP and pyBlueZ instead of pySerial : same problem. > > > It doesn't like it is a bufferoverun bug from me because : > > ?- the GPS seems to wait when I do not read the stream, > > ?- there is never more than 200 inWainting() characters, > > ?- my code to test it is quite simple : > > > ? seriallink = serial.Serial("COM40") > > ? fileName = "data.dump" > > ? out = open(fileName, 'w') > > ? while 1: > > ? ? c = seriallink.read() > > ? ? out.write(" %0.2X" % ord(c)) > > ? ? print "*", > > ? out.close() > > > (with pyBluez : > > sock=BluetoothSocket( RFCOMM ) > > sock.connect(("00:0A:...", 1))) > > > I tried my program on two different PC with two Bluetooth dongle, > > (with pySerial, USPP, pyBluez). > > The same things are : > > ?- windows > > ?- the GPS (which works fine with the dumper program of the > > constructor) > > ?- pyWin32 > > > I've found another guy with a similar problem : > >http://www.generation-nt.com/reponses/rs232-entraide-142097.html > > He says: > > ?- no problem with little messages > > ?- lost of one byte every hour when receiving a lot of data > > > Any known problems with pywin32 and serial I/O when downloading a big > > stream of data ? > > ?From my experience with serial lines I'd say: that's the culprit. They > tend to be rather unreliable, as there is no real protocol ensuring data > integrity. > > You might consider downloading chunks of data if that's somehow > possible, and re-try failed chunks. > > Diez Could be hardware flow control. See this sometimes on the bluetooth connections that are using Serial Port Protocol and the hardware flow control hasn't been physically implemented. Do you lose data after exactly the same amount of data has been received? From justin.kuto at gmail.com Fri Sep 26 13:41:53 2008 From: justin.kuto at gmail.com (afrogazer) Date: Fri, 26 Sep 2008 10:41:53 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes Message-ID: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> I am creating a wind rose using a polar bar plot bu the points do not seem to align to the correct angles. Here is the sample code I am using. I can't seem to see anything in the API on how to set the angles. Any ideas anybody? Thanks. from pylab import * angles = arange(0,360,45) data = [18, 11, 11, 17, 39, 43, 25, 9] fig = figure(figsize=(8,8)) title('Wind Speed/Direction Frequency.', fontsize=13) ax = fig.add_subplot(111) fig.add_axes(([0.15,0.15,0.725,0.725]), polar=True) labels = arange(0,360,22.5) lines = arange(0,360,22.5) ax.axis('off') bar(angles, data, alpha=0.75, align='center', linewidth=0) show() From deets at nospam.web.de Fri Sep 5 12:45:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 18:45:01 +0200 Subject: Files application architecture In-Reply-To: References: Message-ID: <6id60eFq62kfU1@mid.uni-berlin.de> Benjamin Watine schrieb: > Hi, > > I'm about to develop a small python application and I wonder how to > organize files in this application. > I'm familar to java, so I'm tempted to use the same convention : 1 file > per class and 1 folders per package. > > I know that packages doesn't exists in python, they are modules instead. This is wrong. There are packages & modules in python. http://docs.python.org/tut/node8.html And please *don't* do put one class per module, as you would do in Java! Instead, group related classes into modules, breaking them up into several submodules if size or differences in usage suggest so. > May I create specific module for each "group of class" ? My application > follow the MVC paradigm, so basically, I've a package Model, a package > View, and a package Controller. > > So, what are best practices for organizing files and folders in a small > python project ? > I've found PEP8 (http://www.python.org/dev/peps/pep-0008/) that gives a > lot of good hints on coding convention, but nothing about files > organization. The MVC pattern is more important in terms of actual classes written, not so much regarding their distribution over a set of files. If you want, start with one big single module inside a application-naming package - or even no package at all. Split up if you need to. Or just go for /__init__.py /model.py /view.py /controller.py if you *must*. Diez From sdouche at gmail.com Sun Sep 21 18:13:19 2008 From: sdouche at gmail.com (Sebastien Douche) Date: Mon, 22 Sep 2008 00:13:19 +0200 Subject: report a BUG of package setuptools-0.6c8. In-Reply-To: References: <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> <5e1183fa0809210246q46f864eic359964a0cb0d46e@mail.gmail.com> Message-ID: <5e1183fa0809211513v4ad5ec1amb139324ba1cc8538@mail.gmail.com> On Sun, Sep 21, 2008 at 19:56, Gabriel Genellina wrote: >> http://bugs.python.org/setuptools/ > > And how do people manage to know that? Bugtracker send emails on setuptools mailing list. -- Seb From gagsl-py2 at yahoo.com.ar Tue Sep 30 03:32:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 04:32:21 -0300 Subject: Using the 'with' statement with cStringIO objects References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> <1222522300.659080@athprx04> <87zllt7h72.fsf@mulj.homelinux.net> Message-ID: En Sat, 27 Sep 2008 19:28:49 -0300, peppergrower escribi?: > When I got that particular > error, I suspected that it had something to do with the relative > newness of the 'with' statement. > > If this is something that should be considered for addition in the > future, is there somewhere specific I should suggest that? Yes: http://bugs.python.org/ (setting type="feature request", I think) -- Gabriel Genellina From marco.bizzarri at gmail.com Thu Sep 4 06:25:42 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 12:25:42 +0200 Subject: Coming from .NET and VB and C In-Reply-To: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> Message-ID: <3f0d61c40809040325g17fb7faayc31f5ca170898d88@mail.gmail.com> On Thu, Sep 4, 2008 at 12:16 AM, Dennis Lee Bieber wrote: > On Wed, 3 Sep 2008 09:52:06 -0700 (PDT), ToPostMustJoinGroup22 > declaimed the following in > comp.lang.python: > >> have no preference with MySQL or SQL, stored procedures or ad-hoc >> queries. >> > Please note: MySQL is specific relational database management system > (RDBMs), which uses a dialect of structured query language (SQL). SQL by > itself is just a semi-standardized query language -- and can technically > be used to access non-relational DBMS (if any such are still in use), > though the query processor would be a pain to program (map a relational > join into a hierarchical DBMS schema? ugh). > >> SO, I'm interested in using my Google App space (free 500MB) to >> develop a quick database application. Using Python. I found "Dive >> Into Python" which I will be reading shortly. >> > So one question: what RDBMs are supported in that space? The appearance is not an RDBMS, at least, maybe it is, but under the surface. Looks more that you've persistent objects with a SQL-like language to query them. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From castironpi at gmail.com Sun Sep 28 20:32:56 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 17:32:56 -0700 (PDT) Subject: Odd Errors References: <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> Message-ID: <1b1ed34d-f386-4389-a7f1-ce68be4e2a14@k30g2000hse.googlegroups.com> On Sep 28, 7:13?pm, alex23 wrote: > The problem is with this: > > > ? ? ? ? lines = lines.append(inLine) > > The append method of a list modifies the list in-place, it doesn't > return a copy of the list with the new element appended. In fact, it > returns None, which it then attaches the label 'lines' to, so the next > iteration through it tries to call None.append... > > Replace the line with: > > ? ? lines.append(inLine) Do you ever want to scream from the rooftops, "'append' operates by side-effect!"? From rstarkov at gmail.com Sun Sep 14 08:30:21 2008 From: rstarkov at gmail.com (rs387) Date: Sun, 14 Sep 2008 05:30:21 -0700 (PDT) Subject: How to emit Cyrillic and Chinese via unicode from console mode? References: <543bde0c-4d99-4d79-a4dd-b6f8d85e8c48@l64g2000hse.googlegroups.com> <2vqpc4pd7qfrsgsove5f5prncbglhjast0@4ax.com> Message-ID: <561d1d87-4285-44ce-85be-2431e47cff05@m36g2000hse.googlegroups.com> On Sep 14, 11:51?am, Gertjan Klein wrote: > Interesting. On my system (Windows XP) the console codepage does not > change, and hence the characters don't print properly (I get some of the > CP437 line drawing characters, for example). I have never been able to > convince windows to assume/support UTF-8 encoding in the console, > programatically or otherwise. :( I found that a useful test is to create a directory whose name contains chars from various languages, then run "cmd" and see if "dir" displays them correctly. This worked fine for me in WinXP, even though my system locale is Russian. Would be interesting to know if you can get the console to display international chars this way. From linkmaster032000 at gmail.com Tue Sep 23 16:50:28 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Tue, 23 Sep 2008 13:50:28 -0700 (PDT) Subject: curses.setsyx()? References: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> <713190fc-e3a9-4a72-8bee-4fd3affcb531@c58g2000hsc.googlegroups.com> Message-ID: On Sep 23, 4:16?pm, brad.at.sch... at gmail.com wrote: > On Sep 22, 11:24?pm, Tim Roberts wrote: > > > > > linkmaster032... at gmail.com wrote: > > >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: > > >> On Sep 19, 1:24?am, Tim Roberts wrote: > > > >> > linkmaster032... at gmail.com wrote: > > > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > > >> > >cursor. Any alternatives/solutions? > > > >> > Did you call doupdate after? ?setsyx just manipulates the data structures. > > >> > It takes a call to doupdate to force those changes to take effect visually. > > >> > -- > > >> > Tim Roberts, t... at probo.com > > >> > Providenza & Boekelheide, Inc. > > > >> I added it and it still doesn't work. This is what I'm doing when I > > >> want to display the cursor and prepare it for input at 2,3: > > > >> curses.echo() > > >> curses.curs_set(1) > > >> curses.setsyx(2,3) > > >> curses.doupdate() > > > >Any idea what's wrong? > > > No. ?Are you able to post an entire sample that demonstrates the problem? > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > http://pastebin.com/m6413db1 > > Run that and press 'n' key. It is supposed to move the cursor to 2,3 > and it doesn't. Sorry that was me, forgot to switch emails. But yes that is it. Remove the line about ppm/settings.conf if you don't want to create it because it will throw an exception. From chardish at gmail.com Thu Sep 25 11:12:13 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Thu, 25 Sep 2008 08:12:13 -0700 (PDT) Subject: "which python" as a python command? Message-ID: Hello, I'm trying to find out in a script where the location of the current python is. (I'm writing an installer script in python for a simple server application, so i'm going to do a find-replace in a bunch of files to give them the absolute path of the python binary. One thought might be to use the subprocess module, run "which python" as a subprocess, and then peek at stdout, but that seems way too complicated. Is there a simple solution for this in just a few lines of code? Cheers, Evan From ewertman at gmail.com Mon Sep 8 12:03:48 2008 From: ewertman at gmail.com (Eric Wertman) Date: Mon, 8 Sep 2008 12:03:48 -0400 Subject: lacking follow-through In-Reply-To: References: Message-ID: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> > Perhaps the wrong idea of what the group is. I would have thought > that > if one had a sufficiently developed idea and wanted to have it / > formally/ > rejected, rather than merely sniped at, then writting a PEP would be > more > apposite than posting to c.l.py. > > It's fine to post your not sufficiently developed ideas here merely > to > have them discussed. But I don't know what makes you feel that you, > or > your ideas, are /entitled/ to any response at all, much less > "follow-through." To expand on this a little bit, I've been subscribed to this group for a couple of months, but there seems to be a bit more gray area between what would go to a 'python-dev' group and a 'python-user' group. Long debates about language features and abstract ideas would appeal to the former, but not the latter. Certainly I fall into the user category.. I'm pretty happy with python, and generally just adjust to it's design and features, rather than spend lots of time on whether they are 'right' or could be 'better'. /shrug From gandalf at shopzeus.com Wed Sep 3 15:18:15 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 03 Sep 2008 21:18:15 +0200 Subject: max(), sum(), next() In-Reply-To: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <48BEE2F7.5010106@shopzeus.com> bearophileHUGS at lycos.com wrote: > Empty Python lists [] don't know the type of the items it will > contain, so this sounds strange: > > >>>> sum([]) >>>> > 0 > > Because that [] may be an empty sequence of someobject: > You are right in that sum could be used to sum arbitrary objects. However, in 99.99% of the cases, you will be summing numerical values. When adding real numbers, the neutral element is zero. ( X + 0 = X) It is very logical to return zero for empty sequences. Same way, if we would have a prod() function, it should return one for empty sequences because X*1 = X. The neutral element for this operation is one. Of course this is not good for summing other types of objects. But how clumsy would it be to use sum( L +[0] ) or if L: value = sum(L) else: value = 0 instead of sum(L). Once again, this is what sum() is used for in most cases, so this behavior is the "expected" one. Another argument to convince you: the sum() function in SQL for empty row sets returns zero in most relational databases. But of course it could have been implemented in a different way... I believe that there have been excessive discussions about this decision, and the current implementation is very good, if not the best. Best, Laszlo From stefan_ml at behnel.de Sun Sep 7 01:56:17 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 07 Sep 2008 07:56:17 +0200 Subject: delete an HTML tag while keeping its content In-Reply-To: References: Message-ID: <48c36d01$0$7475$9b4e6d93@newsspool4.arcor-online.net> [fixing the subject appropriately] Jackie Wang wrote: > How should I delete the 'font' tags while keeping the content inside? Amongst many other goodies for working with HTML, the Elements in lxml.html have a ".drop_tag()" method specifically for that purpose. http://codespeak.net/lxml/ Stefan From support.desk.ipg at gmail.com Mon Sep 22 12:37:46 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Mon, 22 Sep 2008 11:37:46 -0500 Subject: Regex Help In-Reply-To: References: Message-ID: Anybody know of a good regex to parse html links from html code? The one I am currently using seems to be cutting off the last letter of some links, and returning links like http://somesite.co or http://somesite.ph the code I am using is regex = r'' page_text = urllib.urlopen('http://somesite.com') page_text = page_text.read() links = re.findall(regex, text, re.IGNORECASE) From mail at timgolden.me.uk Mon Sep 29 07:36:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 29 Sep 2008 12:36:43 +0100 Subject: cups.Connection.printFile In-Reply-To: References: Message-ID: <48E0BDCB.10405@timgolden.me.uk> Antoon Pardon wrote: > On 2008-09-26, Mike Driscoll wrote: >> On Sep 19, 9:01 am, Antoon Pardon wrote: >>> On 2008-09-16, Graham Jenkins wrote: >>> >>> >>> >>>> I'm trying to print a file from within a Python program. >>>> The quick-and-dirty solution is to use something like: >>>> fd = os.popen("lp -d MyPrinter", "wb") >>>> fd.write(MyFileContents) >>>> But it seems to me that there should be a clean solution like: >>>> import cups >>>> stat = >>>> cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") >>> What about systems that don't use cups for printing? >>> >>> -- >>> Antoon Pardon >> For Windows, there's a few different ways to print. Tim Golden has a >> list on his website: >> >> http://timgolden.me.uk/python/win32_how_do_i/print.html > > I have a linux system that doesn't use cups for printing. > So his "clean" solution won't work on my box. Unless > of course his cups.Connection.printFile is just a wrapper > around os.popen("lp -d MyPrinter", "wb") or something > similar. Well I certainly don't pretend to offer any solutions on my "Win32 How do I?" pages except for how to do things on Win32 ;) . TJG From kyosohma at gmail.com Fri Sep 12 16:20:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 12 Sep 2008 13:20:11 -0700 (PDT) Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: <7b717a23-28b8-4dcd-ae89-3042f7e50a98@l43g2000hsh.googlegroups.com> On Sep 12, 1:33?pm, ady... at panix.com (Al Dykes) wrote: > In article <1bs69ogq6nspt.136i7kvcux142$.... at 40tude.net>, > Alan Franzoni ? wrote: > > >zamil was kind enough to say: > > >[cut] > > >If your needs are very basic, you can stick with the tk module that comes > >with python. It's not really feature-packed, but it's maintained and pretty > >cross-platform. > > OK, what are my choices for an IDE/GUI development tool that runs on XP? > > Thanks > > -- > Al Dykes > ?News is something someone wants to suppress, everything else is advertising. > ? ? - Lord Northcliffe, publisher of the Daily Mail Here's a few: WingWare: http://www.wingware.com/ SPE: http://pythonide.blogspot.com/ Eclipse + Python plugin = EasyEclipse (PyDev): http://easyeclipse.org/site/distributions/python.html Or you could use Google and you would have found this: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Mike From emile at fenx.com Mon Sep 8 15:41:53 2008 From: emile at fenx.com (Emile van Sebille) Date: Mon, 08 Sep 2008 12:41:53 -0700 Subject: Problems downloading and installing win32api In-Reply-To: <968dca58-0172-4953-b8d6-9610f0570fe8@s20g2000prd.googlegroups.com> References: <968dca58-0172-4953-b8d6-9610f0570fe8@s20g2000prd.googlegroups.com> Message-ID: brianrpsgt1 wrote: > I have attempted downloading and installing several different version > of the win32api from Source Forge, Whe win32 tools come bundled with ActiveState's python distribution. Maybe that'll move you forward... Emile however, each time I try to install > I get the following error message: > > "Only part of a ReadProcessMemory or WriteProcessMemory request was > completed" > > This occurred with the following files: > pywin32-212.win32-py2.4.exe > pywin32-212.win32-py2.5.exe > pywin32-212.win32-py2.6.exe > > I am using WinXP SP2. Any assistance on getting this downloaded and > installed would be great. > > Thanks > > B > -- > http://mail.python.org/mailman/listinfo/python-list > From joncle at googlemail.com Tue Sep 2 09:29:57 2008 From: joncle at googlemail.com (Jon Clements) Date: Tue, 2 Sep 2008 06:29:57 -0700 (PDT) Subject: Algorithm used by difflib.get_close_match References: <83c600d0-6852-4dd6-9287-34f9b3264090@s50g2000hsb.googlegroups.com> Message-ID: On Sep 2, 2:17?pm, Guillermo wrote: > Hi all, > > Does anyone know whether this function uses edit distance? If not, > which algorithm is it using? > > Regards, > > Guillermo help(difflib.get_close_matches) will give you your first clue... From ebgssth at gmail.com Thu Sep 25 11:41:49 2008 From: ebgssth at gmail.com (js) Date: Fri, 26 Sep 2008 00:41:49 +0900 Subject: How can I customize builtin module search path to prefix/lib to prefix/lib64? Message-ID: Hi list, Is it possible to change module search path (PYTHONPATH) built-in to Python interpreter? I thought I can change it with configure --libdir but it didn't work for me. I also tried patching around python source tree replacing lib to lib64 but it didn't work either. Adjusting sys.path directly or using environ should do the trick but I'd rather want to make it the default path for my python Thanks, From fredrik at pythonware.com Sun Sep 21 11:04:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 17:04:57 +0200 Subject: How to kill threading.Thread instance? In-Reply-To: <6jn4itF442e7U1@mid.uni-berlin.de> References: <6jmn5kF42hreU1@mid.uni-berlin.de> <6jn4itF442e7U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> I wonder why something like myThread.exit() or myThread.quit() or >> threading.kill(myThread) can't be implemented? >> Is something like that present in Python 3000? > > Not that I'm aware of it (which doesn't mean to much though). > > However I *am* aware of the bazillions discussions that have been held > over this here - and the short answer is: it is a generally very bad > idea to terminate threads hard, as it can cause all kinds of corruption. the problem is that you have no idea what the thread is doing, so just killing it dead it may make one big mess out of the application's internal state; see e.g. this post http://mail.python.org/pipermail/python-list/2006-August/400256.html That's wise ;-) Stopping a thread asynchronously is in /general/ a dangerous thing to do, and for obvious reasons. For example, perhaps the victim thread is running in a library routine at the time the asynch exception is raised, and getting forcibly ejected from the normal control flow leaves a library-internal mutex locked forever. Or perhaps a catch-all "finally:" clause in the library manages to release the mutex, but leaves the internals in an inconsistent state. which links to a FAQ from Sun on this very topic: http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html (note that Java releases all mutexes when a thread is killed, but that's not much better, as the FAQ explains) so as usual, the right thing to do is to do things in the right way. From dmitry at makovey.net Wed Sep 24 23:35:06 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 03:35:06 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> Message-ID: showellshowell at gmail.com wrote: > Your code below is very abstract, so it's kind of hard to figure out > what problem you're trying to solve, but it seems to me that you're > using the B proxy class to decorate the A target class, which means > you want one of these options: Sorry for unclarities in original post. Basically A aggregates object of class B (example with no decorators and again it's oversimplified): class A: b=None def __init__(self,b): self.b=b def amethod(self,a): print "A::amethod ", a def bmethod(self,a): print "A::bmethod ",a return self.b.bmethod(a) def bmethod2(self,a,z): print "A::bmethod2 ",a,z return self.b.bmethod2(a,z) class B: def __init__(self): self.val=a def bmethod(self,a): print "B::bmethod ",a def bmethod2(self,a,z): print "B::bmethod2 ",a,z b=B() a=A(b) a.bmethod('foo') a.bmethod2('bar','baz') In my real-life case A is a proxy to B, C and D instances/objects, not just one. If you look at above code - whenever I write new method in either B, C or D I have to modify A, or even when I modify signature (say, add parameter x to bmethod) in B, C or D I have to make sure A is synchronized. I was hoping to use decorator to do it automatically for me. Since the resulting code is virtually all the same for all those proxy methods it seems to be a good place for automation. Or am I wrong assuming that? (since it is my first time using decorators I honestly don't know) Abovementioned code ilustrates what I am doing right now. My original post is an attempt to make things more automated/foolproof. From ggpolo at gmail.com Thu Sep 18 13:15:48 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 18 Sep 2008 14:15:48 -0300 Subject: Tkinter Bold Text In-Reply-To: <76vncf$1aj1ab@smtp.llnl.gov> References: <76vncf$1aj1ab@smtp.llnl.gov> Message-ID: On Thu, Sep 18, 2008 at 1:06 PM, April Lekin wrote: > Is there any way to highlight, bold or change the color of one word in a > variable to be displayed on a Tkinter GUI? Yes. > > Like: > > material = "Plastic" > introVal = "This report describes the construction of the %s." % (material) > You could separate them in two labels (if you are using labels), or apply a different tag if you are using a Text widget. > this is what I want: > This report describes the construction of the Plastic. > Plastic is Bold or Blue or Green > Changing the color is easier, you only change the foreground option. Changing to bold may not work for you, because depending on your Tk version and platform it will already be bold, so you won't notice anything. There is also a "catch" in changing text to bold, if you only set the text option of your Label to "-weight bold" it will probably get you a bold text, but with a different font than the one being used by other Labels. Now, something you could use as a base: import Tkinter import tkFont root = Tkinter.Tk() otherpart = Tkinter.Label(text="some text here") special = Tkinter.Label(text="special", foreground='blue') otherpart.pack(side='left') special.pack(side='left') f = tkFont.Font(font=otherpart['font']) f['weight'] = 'bold' f['underline'] = True special['font'] = f.name root.mainloop() > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From greg at cosc.canterbury.ac.nz Tue Sep 16 21:52:13 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 17 Sep 2008 13:52:13 +1200 Subject: Function getting a reference to its own module In-Reply-To: References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> Message-ID: <6jb6juF2co8rU1@mid.individual.net> Arnaud Delobelle wrote: > Or: > > import ModuleName as this_module Or: this_module = __import__(__name__) then you don't have to change anything. -- Greg From peter.anderson at internode.on.net Sat Sep 6 10:14:25 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sun, 07 Sep 2008 00:14:25 +1000 Subject: wxPython problem In-Reply-To: <48C24D3C.7060306@gmail.com> References: <48C24D3C.7060306@gmail.com> Message-ID: <48C29041.9050804@internode.on.net> Stef Mientki said: In PyScripter, you should run wxPython in the plain remote machine (not the wxPython remote),and you should set "reset before run flag" or reset the remote machine each time yourself. Stef, Thanks for the help! It has taken several hours to find and install the correct version of Rpyc (which is required to run the remote Python engine but it now seems to be working fine. And the "Reinitialise the Python engine {Alt]+[F2]" does need to be done between script runs. Given all that, the script now runs multiple times in PyScripter. The script still only runs ONCE in IDLE but I can live with that. In case others find this message from a search; I am using Python 2.5.2 and it requires rpyc-2.60.zip from the Rpyc download page (see http://rpyc.wikispaces.com/ click on the "Download" link and make sure you select the "main" link under the "Packages" column at Sourceforge. You will be shown a list of Rpyc versions. For Python 2.5.2 choose Relese "2.60". This will save you the several hours its cost me. Thanks again Stef. Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From gagsl-py2 at yahoo.com.ar Mon Sep 29 09:11:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 10:11:21 -0300 Subject: Fastest way to max() list References: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> Message-ID: En Fri, 26 Sep 2008 01:42:59 -0300, Chris Rebert escribi?: > B. Assuming by "distance" you meant "difference" and/or that the > distance is only in 1 dimension: > > from operator import itemgetter > firsts = map(itemgetter(0), main_list) > distance = max(firsts) - min(firsts) I think the above expression is overcomplicated. The code below does the exact same thing and is easier to understand, IMHO: firsts = [item[0] for item in main_list] distance = max(firsts) - min(firsts) -- Gabriel Genellina From n.s.buttar at gmail.com Sun Sep 21 11:10:09 2008 From: n.s.buttar at gmail.com (Navtej Singh) Date: Sun, 21 Sep 2008 20:40:09 +0530 Subject: Override the '+' symbol In-Reply-To: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> References: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> Message-ID: <1090e4100809210810n1898e546n29e75dc2e973a789@mail.gmail.com> http://docs.python.org/ref/numeric-types.html On Sun, Sep 21, 2008 at 8:37 PM, Mr.SpOOn wrote: > Hi, > how can I override the '+' symbol (and other math symbols) so that it > can have a new behavior when applied to some objects? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From raj.indian.08 at gmail.com Wed Sep 17 21:39:05 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Wed, 17 Sep 2008 18:39:05 -0700 (PDT) Subject: Modifying the system menu References: Message-ID: <8c1df849-d6e0-409a-930d-0593eed85683@a29g2000pra.googlegroups.com> I tested it again and found that the behaviour is a little different from what I mentioned previously in the mailchain. The item is working perfectly the first time around. Now if I close the application and run it again (which was what I did earlier), if that application system menu is already modified, it is causing this issue. Why would this happen? If it is that the file handle is not obtained, it wouldnt have gone through the following check at all? > hw = win32gui.GetSystemMenu(hwnd, False) > if hw != None: > win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); Not only did it go through, it failed with an invalid menu handle error. From sturlamolden at yahoo.no Tue Sep 23 15:08:47 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 12:08:47 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: <70d97b04-6f44-4a83-94bb-126446a2ac4d@k7g2000hsd.googlegroups.com> On Sep 23, 8:52?pm, bearophileH... at lycos.com wrote: > I think the Python version suffices. If it's not too much private you > may post the single minimal/reduced runnable Python module here, it > will be deleted in some time (if you want you can also use a private > paste):http://codepad.org/ http://codepad.org/rh8GzzJT Available 24 hours from now. > Is this a good or bad thing? ;-) It's just facinating how different people working on similar problems come up with different looking code. From harikrishnan.ech at gmail.com Sun Sep 7 01:03:37 2008 From: harikrishnan.ech at gmail.com (reddy) Date: Sat, 6 Sep 2008 22:03:37 -0700 (PDT) Subject: This group contains information about IT Requirements in USA as well as Hotlist of Candidates from the participating members Message-ID: <8cfef1d6-abeb-491d-a370-9d367510ab47@r15g2000prh.googlegroups.com> This group contains information about IT Requirements in USA as well as Hotlist of Candidates from the participating members CLICK & REGISTER U GET MORE DEDAILS ************************************************* * http://homologie.blogspot.com/ * * http://germanfriendfinder.com/go/g1022227-ppc * * http://amigos.com/go/g1022226-pmem * **************************************************** From half.italian at gmail.com Sat Sep 20 17:25:39 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sat, 20 Sep 2008 14:25:39 -0700 (PDT) Subject: explain slice assignment to newb References: ceceec82-cc0c-4daf-8f8a-1392f4872f71@k30g2000hse.googlegroups.com Message-ID: <1d7c98a3-8836-4de2-989c-42787d11abca@q5g2000prf.googlegroups.com> On Sep 20, 2:20?pm, Andrew wrote: > please explain this behavior to a newb: > > >>> a = [1,2,3,4] > >>> b = ["a","b","c","d"] > >>> a > [1, 2, 3, 4] > >>> b > > ['a', 'b', 'c', 'd'] > > >>> a[0:2] > [1, 2] > >>> a > [1, 2, 3, 4] > >>> b[2:4] > ['c', 'd'] > >>> a[0:2] = b[0:2] > >>> b[2:4] = a[2:4] > >>> a > ['a', 'b', 3, 4] > >>> b > ['a', 'b', 3, 4] What else would you expect to happen? From ebgssth at gmail.com Tue Sep 30 20:18:53 2008 From: ebgssth at gmail.com (js) Date: Wed, 1 Oct 2008 09:18:53 +0900 Subject: How can I customize builtin module search path to prefix/lib to prefix/lib64? In-Reply-To: References: Message-ID: In addition to that, .pth cannot prepend search path. All thing it can do is appending to it. In my case, I have to put lib64 before lib/. On 9/26/08, js wrote: > For 64bit python, there's no need to look at lib/lib-dynload because > libraries for 64bit should be in > lib64/lib-dynload. Having module search path which point to libraries > the python can not understand > is, IMHO, wrong. > > On Fri, Sep 26, 2008 at 3:03 AM, Mike Driscoll wrote: >> On Sep 25, 10:41 am, js wrote: >>> Hi list, >>> >>> Is it possible to change module search path (PYTHONPATH) built-in to >>> Python interpreter? >>> I thought I can change it with configure --libdir but it didn't work for >>> me. >>> I also tried patching around python source tree replacing lib to lib64 >>> but it didn't work either. >>> >>> Adjusting sys.path directly or using environ should do the trick but >>> I'd rather want to make it the default path for my python >>> >>> Thanks, >> >> Why not just add a custom path file (*.pth)? EasyInstall, wx, PyWin32 >> and others do it. Of course there's always sys.path.append as well. >> >> Mike >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From mmanns at gmx.net Wed Sep 17 17:47:12 2008 From: mmanns at gmx.net (Martin Manns) Date: Wed, 17 Sep 2008 23:47:12 +0200 Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> Message-ID: <20080917234712.7d0d15b6@gmx.net> On Tue, 16 Sep 2008 19:25:58 -0700 (PDT) Fett wrote: > # SciPy -- http://www.scipy.org - supposedly has this, but as I said, > I can't find any mention of it anywhere but on the site you linked. I found OpenOpt on the site: http://scipy.org/scipy/scikits/wiki/MILP I downloaded the svn version and installed it on my Debian box. There were some error messages while installing. However, the example seems to work anyways. I am using the solver glpk from the package python-glpk. I hope that this works on your Ubuntu system as well. From circularfunc at gmail.com Thu Sep 11 05:23:43 2008 From: circularfunc at gmail.com (process) Date: Thu, 11 Sep 2008 02:23:43 -0700 (PDT) Subject: Is len O(n) or O(1) ? Message-ID: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> Python uses arrays for lists right? def quicksort(lista): if lista == []: lista else: return quicksort([x for x in lista[1:] if x < lista[0]]) + [lista[0]] + \ quicksort([x for x in lista[1:] if x >= lista[0]]) or def quicksort(lista): if len(lista) == 0 lista else: return quicksort([x for x in lista[1:] if x < lista[0]]) + [lista[0]] + \ quicksort([x for x in lista[1:] if x >= lista[0]]) wait first one raises TypeError unsupported operand types. From kerny404 at gmail.com Fri Sep 26 06:45:39 2008 From: kerny404 at gmail.com (andrea) Date: Fri, 26 Sep 2008 03:45:39 -0700 (PDT) Subject: Building truth tables Message-ID: Well I would like to make a little program that given a certain logical expression gives the complete truth table. It's not too difficult in fact, I just have some doubts on how to design it. I thought something like that: class Term: class Table: def and(... def or(... But I'm not convinced... I would like something like that more or less: a,b,c = Term() table([a,b,c], impl(and(or(a,b)),c)) Any idea?? Thanks From __peter__ at web.de Fri Sep 5 04:47:13 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Sep 2008 10:47:13 +0200 Subject: derived classes and __getattr__ References: Message-ID: Alexandru Mo?oi wrote: > i'm facing the following problem: > > class Base(object): > def __getattr__(self, attr): return lambda x: attr + '_' + x > > def dec(callable): > return lambda *args: 'dec_' + callable(*args) > > class Derived(Base): > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have > what_so_ever > mumu = dec(Base.mumu) # wrong, base > doesn't have mumu > > any idea how to do this? __getattr__() is defined in the class to create instance attributes on the fly. If you want class attributes you have to put the __getattr__() method into the class of the class, or "metaclass": class Base(object): class __metaclass__(type): def __getattr__(self, attr): return lambda self, x: attr + '_' + x def dec(callable): return lambda *args: 'dec_' + callable(*args) class Derived(Base): what_so_ever = dec(Base.what_so_ever) d = Derived() print d.what_so_ever("42") I don't see how you can turn this into something useful... Peter From sturlamolden at yahoo.no Tue Sep 23 16:38:10 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 13:38:10 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: <5f2eed90-b49b-4c29-bfd5-cc90c4495b3c@m3g2000hsc.googlegroups.com> On Sep 23, 10:16?pm, Robert Kern wrote: > What's confusing? You do have to create a profile: How do I add a new page to the wiki? I'm only able to edit the front page of the cookbook. But it doesn't help to add link there if I have no page to link. (I may be incredibly stupid though.) From hniksic at xemacs.org Tue Sep 23 09:37:56 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 23 Sep 2008 15:37:56 +0200 Subject: Mutex not thread safe? PEP-3108. References: Message-ID: <87fxnr0yq3.fsf@mulj.homelinux.net> Roy Smith writes: > I'm perusing PEP-3108 and came upon this interesting statement (under the > "Hardly used" section): > > mutex [...] Not thread-safe. > > How can a mutex, whose sole reason for existence is to mediate thread > safety, not be thread safe? "mutex" is a module designed for use with "sched", not for multithreading: """Mutual exclusion -- for use with module sched [...] Of course, no multi-threading is implied -- hence the funny interface for lock, where a function is called once the lock is aquired. """ What is called a mutex in multithreading is known in Python as threading.Lock, and does work with threads. From To-Email-Use-The-Envelope-Icon at My-Web-Site.com Sat Sep 27 22:47:54 2008 From: To-Email-Use-The-Envelope-Icon at My-Web-Site.com (Jim Thompson) Date: Sat, 27 Sep 2008 19:47:54 -0700 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> Message-ID: <52std4tnvg0h07it7kik0kinht9812c839@4ax.com> On Sat, 27 Sep 2008 23:12:59 +0000 (UTC), Cydrome Leader wrote: >In rec.crafts.metalworking Jim Thompson wrote: >> >> On Sat, 27 Sep 2008 18:47:16 -0400, default >> wrote: >> >>>On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko >>> wrote: >>> >>>>Hello, this is Milenko Stojadinovic from town Banjaluka, >>>>Bosnia and Herzegovina, also known as Cvrcko >>>>Does anyone know of any bars in town where I can >>>>swallow a bucket of cum? It can be either dog, >>>>horse or human cum. Also, does anyone know of >>>>any sex bars where people will shit in your mouth? >>>>I also like eating shit. >>> >>>Come to the US and park your mouth in front of George Bush - all the >>>Bshit you can eat - and it keeps on coming! >>> >>>I have a buddy in Bosna - he's normal. >> >> Now you know why I blanket kill-file googlegroups. > >So you and everybody can talk about them nonstop? You're gone also ;-) ...Jim Thompson -- | James E.Thompson, P.E. | mens | | Analog Innovations, Inc. | et | | Analog/Mixed-Signal ASIC's and Discrete Systems | manus | | Phoenix, Arizona 85048 Skype: Contacts Only | | | Voice:(480)460-2350 Fax: Available upon request | Brass Rat | | E-mail Icon at http://www.analog-innovations.com | 1962 | Liberalism is a persistent vegetative state From jjl at pobox.com Wed Sep 3 17:54:03 2008 From: jjl at pobox.com (John J Lee) Date: Wed, 3 Sep 2008 22:54:03 +0100 (BST) Subject: [wwwsearch-general] python/xpath question.. In-Reply-To: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> References: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> Message-ID: On Wed, 3 Sep 2008, bruce wrote: [...] > and get the number of total nodes... > by subtracting, i can get the number of nodes, without text.. is there an > easier way??!! [...] Yes -- don't use XPath :-) John From almar.klein at gmail.com Fri Sep 26 03:29:42 2008 From: almar.klein at gmail.com (Almar Klein) Date: Fri, 26 Sep 2008 09:29:42 +0200 Subject: what does "python -i" use as input stream (stdin)? In-Reply-To: References: Message-ID: > > Use subprocess.PIPE > Usually the tricky part is to figure out exactly whether there is more > input or not. With Python it's easy, use the ps1 prompt. Thanks, but that is not exactly what I meant. (Maybe my question was a bit vague). I want to replace the input stream of the *remote* process. So I'll be running something like "python -i remote.py", and inside remote.py I create a pseudo-file to replace the input stream (of the remote process). I have now solved my problem by running "python remote.py" (without the -i) and start an interactive interpreter (inherited from code.InteractiveConsole). This interpreter *does* use the sys.stdin, so I can just do: "sys.stdin = my_pseudo_file" (I start a separate thread that reads the original stdin and writes received text to the pseudofile. But now I can also communicate and do stuff with the process when the main thread is running (for example interrupting it on windows!)) I would still like to hear if anyone knows how I can change the input stream that is used when running "python -i", but I would not be surprised if it is impossible... Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 30 03:27:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 04:27:50 -0300 Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> <357e734f-e99f-41e5-9cac-083d636a23e1@n38g2000prl.googlegroups.com> <95f8433c-213f-4b3a-8d93-bebbe2561e7f@s9g2000prg.googlegroups.com> <781c4e48-7396-4278-85bd-3578f88aa501@l33g2000pri.googlegroups.com> Message-ID: En Sun, 28 Sep 2008 22:44:20 -0300, robean escribi?: > Many thanks for your reply. I was simply under the impression that > 'import urllib2' would take care of the namespace issue and simply > import everything in urlib2, making it unnecessary to have to > reference HTTPError and URLError. Sorry for being dense about this > (I'm very new to Python).. Again, thanks for your help. That's a common misconception - see this article: http://effbot.org/zone/import-confusion.htm -- Gabriel Genellina From jhuerta at cipf.es Wed Sep 24 12:15:19 2008 From: jhuerta at cipf.es (Jaime Huerta Cepas) Date: Wed, 24 Sep 2008 18:15:19 +0200 Subject: how to build a MacOS universal python package including external dependencies Message-ID: Hi all, I have developed a set python libraries that provide several scientific methods to analyse and visualize certain type of biological data. This libraries are based on many external python modules, such as python-mysql python-sip or python-qt4. I use GNU/linux to develop my tools and I found no problems into installing all dependencies, however it does not seem to be that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 , mysqldb, scipy, numpy) are cross platform, but when you are trying to publish your tool in an academic journal, most referees (many of them using MacOS) expect some kind of straightforward installation process for the tool. I wonder if there would be a way in which I could compile all the dependencies and libraries in a MacOs system and then building a static universal binary that I can distribute. I guess it should be possible, but I am not sure how difficult it might be, and whether all dependencies (qt4 is huge) can be packaged together. Any help is more than welcome! Best regards, Jaime. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggpolo at gmail.com Mon Sep 1 23:28:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 2 Sep 2008 00:28:39 -0300 Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp In-Reply-To: <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> Message-ID: On Mon, Sep 1, 2008 at 11:01 PM, akineko wrote: > On Sep 1, 6:34 pm, "Guilherme Polo" wrote: >> This is an illusion you have, calling those methods are not the way >> for explicitly controlling button's behavior, not more than generating >> proper events. The explicit way is to not use a button, instead >> (ab)use Canvas. > > Some of my custom widgets used Canvas. > When I designed the "sticky" button widget, I briefly considered use > of Canvas but I rejected because the one I wanted is nothing but > Button (except "sticky" behaviour). Can you clarify what is this "sticky" behavior ? Are you referring to a toggle button ? If yes, then you might be after a simple Checkbutton: checkbutton = Tkinter.Checkbutton(indicatoron=False, text='test') > I understand that use of Canvas provides greater flexibility but I > felt it was over-kill. > Your insights are very helpful for me and other people when designing > a custom widget. > > Aki- > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From blacktrash at gmx.net Fri Sep 5 11:29:19 2008 From: blacktrash at gmx.net (Christian Ebert) Date: Fri, 05 Sep 2008 11:29:19 -0400 Subject: [MacOS X] plat-mac/errors.rsrc.df.rsrc not installed/created References: <20080828183304.406.slrn@krille.blacktrash.org> Message-ID: <20080905152652.542.slrn@krille.blacktrash.org> * Christian Ebert on Thursday, August 28, 2008: > I am on MacOS 10.4.11, and have a minor recurring problem, when > using my own Python installation. > > I only stumbled over it when using http operations with the > Mercurial SCM, and my /tmp/ folder was clobbered with *.rsrc > temporary files. > > Some references: > http://www.selenic.com/pipermail/mercurial/2007-October/015039.html > and, as I forgot about it :( : > http://www.selenic.com/pipermail/mercurial/2008-August/021072.html > > Apparently for some stuff plat-mac/macresource.py needs to create > plat-mac/errors.rsrc.df.rsrc. If that fails, at least that is how > I read macresource.py, it creates them via mkstemp in /tmp/. > > Once I recognize the problem I can work around it by either > > $ sudo mv /tmp/tmp.rsrc /usr/local/lib/python2.5/plat-mac/errors.rsrc.df.rsrc > > or by temporarily "chown myname plat-mac", and, once the file is > created, "chown root plat-mac" again. > > My 2.5.2 install is under /usr/local, but other Mac users with > the same setup, do not have the problem. > > I don't need/want the Apple Framework install, and again, others > do not have the problem with this setup. > > Anyone any ideas? > > The best I could google was > http://bugs.python.org/issue763708 > but this seems encoding related. I gather from the overwhelming reaction that I am the only one experiencing this ;-) However, if I can provide more info that might be useful, just tell me. TIA c -- Was hei?t hier Dogma, ich bin Underdogma! [ What the hell do you mean dogma, I am underdogma. ] _F R E E_ _V I D E O S_ -->> http://www.blacktrash.org/underdogma/ From bearophileHUGS at lycos.com Mon Sep 22 07:32:14 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 04:32:14 -0700 (PDT) Subject: A bit weird dictionary behavior References: Message-ID: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Pekka Laukkanen: > but it still doesn't feel exactly right. Would it be worth submitting a bug? It feels wrong because it is. In a tidier language (Pascal, Java, etc) a boolean and an integer must be different types. Keeping booleans and integers separated may avoid some bugs too (I don't know how many/ often). But the Python language copies many things from C, where most things are chosen for practical purposes and maximum efficiency (and from much simpler Python implementations, where there was no boolean type, so bools are grafted in), so it's not a bug, and I think it will not be fixed soon (Python 3 was probably the last chance to change it, for several years to come). So you probably have to live with this illogical behavior. On the other hand it has some little practical advantages, you can do: sum(x == y for x in iterable) That also equals to a more tidy: sum(1 for x in iterable if x == y) Regarding the dict, they are dynamically typed, but good programming practice (that comes from experience of bugs that have bitten you) tells you that generally it's better to be careful with the inserting different types into a dict; often it's better to avoid doing it. Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Sep 20 19:42:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Sep 2008 20:42:58 -0300 Subject: writeable buffer and struct.pack_into and struct.unpck_from References: Message-ID: En Sat, 20 Sep 2008 15:45:48 -0300, Tzury Bar Yochay escribi?: > I can't find in the documentation the way to use these two functions. > > can someone share a simple code that utilize these two functions? struct.pack_into is intended to "fill" a buffer you got from somewhere, probably other language or process. ctypes.create_string_buffer may be used to create a writable buffer in python code. py> from ctypes import create_string_buffer py> b = create_string_buffer(10) py> b.raw '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' py> from struct import * py> pack_into("hhh", b, 0, 1, 2, -1) py> b.raw '\x01\x00\x02\x00\xff\xff\x00\x00\x00\x00' unpack_from does the opposite. Before Python 2.5, you had to use pack to create a string object, and then copy its contents into the destination buffer; using pack_into avoids the memory copy. -- Gabriel Genellina From ewertman at gmail.com Wed Sep 3 13:04:10 2008 From: ewertman at gmail.com (Eric Wertman) Date: Wed, 3 Sep 2008 13:04:10 -0400 Subject: Coming from .NET and VB and C In-Reply-To: References: Message-ID: <92da89760809031004t65565507vf6d57f8210d50a95@mail.gmail.com> > Using Python. I found "Dive Into Python" which I will be reading shortly The title of the book is good advice all by itself. Especially with prior programming experience, you'll get started very quickly. What will take longer is the assimilation of some of python's neater and more idiomatic features, like list comprehensions and generators. Also, the fact that strings are immutable threw me off a little the first day or two. If you stick with it, I think you'll find those little things to be your favorite parts though. Certainly I use list comprehensions all the time now, when I used to not use them at all. In about 90% or more of cases, you can avoid doing things that you do routinely in other languages.. mostly by iterating directly over things you don't need counter variables or intermediate variable names. In fact, I find myself going back through old code and removing variables pretty frequently. I'm sure there's a lot more. Personally I find it a lot of fun to code in. From aioe.org at technicalbloke.com Sat Sep 27 01:55:07 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 27 Sep 2008 01:55:07 -0400 Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: process wrote: > ' '.join([`x * x` for x in range(1, 6)]) > > exactly what does this symbol do and what does it stand for? Which symbol, the '*' ??? Are you kidding? From nospam at example.com Sun Sep 28 05:36:13 2008 From: nospam at example.com (Erhard) Date: Sun, 28 Sep 2008 02:36:13 -0700 Subject: Calculating timespan In-Reply-To: <784049c7-a9cf-4006-873f-d3a869bf6b93@l64g2000hse.googlegroups.com> References: <784049c7-a9cf-4006-873f-d3a869bf6b93@l64g2000hse.googlegroups.com> Message-ID: marek.rocki at wp.pl wrote: > from datetime import datetime, timedelta > span = datetime.now() - > datetime(year=2008,month=8,day=27,hour=12,minute=34,second=56) > if span < timedelta(minutes=37): > # do something timedelta! Yes, it's obvious that's what I was looking for. I was stuck with 'timespan' in my head and couldn't find anything like it in the docs. Thank you very much! From keshet1 at umbc.edu Fri Sep 12 13:11:06 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Fri, 12 Sep 2008 13:11:06 -0400 Subject: manipulating files within 'for' Message-ID: <48CAA2AA.40809@umbc.edu> Hi Pythoneers, I have a question about a code I wrote with the help of someone. The code below copy a few lines from different files into one file. It works fine as it is given here and generates the new file 'pockets.out' correctly, but says:"....py returned exit code 0". However, if I add more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) it gives an error: "Exception raised while running script". Can anyone please advice me? Why is it giving an error on multiple x but runs well with one (I made sure that all files and folders exist, etc.). What does exit code 0 mean? what does "exception raised" mean? Thanks a lot, BK CODE: |receptors = ['1AZM'] for x in receptors: print x # open out_file for appending for each 'x' in receptors, close at same level out_file = open('c:/Linux/Dock_method_validation/%s/validation/pockets.out' %(x),'a') for i in range(10): for r in (7, 9, 11, 13, 15, 17): f = open('%s/validation/ligand_ran_line_%s_%s.mol2' %(x,i,r), 'r') out_file.write('%s ' %i) out_file.write('%s ' %r) # assume 'PRIMARY' should be found first # set flag for string 'PRIMARY' primary = False # iterate on file object, empty files will be skipped for line in f: if 'PRIMARY' in line: primary = True out_file.write(line.strip()) # write line to out_file out_file.write(' ') # add a space # write all line after 'PRIMARY' was found until 'TRIPOS' is found elif 'TRIPOS' not in line and primary: out_file.write(line.strip()) out_file.write(' ') # add a space elif 'TRIPOS' in line and primary: break # stop when 'TRIPOS' is found print out_file.write('\n') # move to a new line f.close() # close file. for loop moves to next 'r' value, and then to next 'i' out_file.close() # close out_file| From carriere.jonathan at gmail.com Thu Sep 11 11:13:52 2008 From: carriere.jonathan at gmail.com (carriere.jonathan at gmail.com) Date: Thu, 11 Sep 2008 08:13:52 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> Message-ID: <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> On Sep 11, 4:19?pm, Fredrik Lundh wrote: > carriere.jonat... at gmail.com wrote: > > ?> I wonder if there is a platform written in python. The equivalent of > ?> the Netbeans platformhttp://platform.netbeans.org/in the Python > ?> world. Do you know such a thing? > > You (or maybe the Java folks) seem to have missed that platform has a > rather specific meaning in computing: > > http://en.wikipedia.org/wiki/Platform_(computing) > > Given that definition, Python is pretty much a platform in itself. ?If > you want to use Python for a specific task, you add libraries for that > task. ?Tell us what you want to do, and we'll tell you what libraries > and toolkits you might want to try. > > I want to build a desktop application. I am searching for some kind of environment that would provide all the elements ready (Windows...). Then I would have to code the business logic only. Jonathan. From tmohr at s.netic.de Tue Sep 16 15:35:05 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Sep 2008 21:35:05 +0200 Subject: optparse Message-ID: Hi, i use the module optparse to parse the command line: ------example #! /usr/bin/python import optparse parser = optparse.OptionParser() parser.add_option("-v", "--verbose", dest = 'verb', help = 'be loud', action = 'store_true', default = 'store_false') (opts, args) = parser.parse_args() print "opts", opts print "args", args ------example If i call it without any parameters i get: opts {'verb': 'store_false'} args [] I would rather like to see the actual value False in "opts", did i use some wrong parameters somewhere? I can't imagine that this is the wanted behaviour of optparse. Thanks for any hints, Torsten. From maric at aristote.info Tue Sep 16 12:07:03 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 18:07:03 +0200 Subject: literals optimization (was Re: append on lists) In-Reply-To: <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> References: <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> Message-ID: <200809161807.04172.maric@aristote.info> Le Tuesday 16 September 2008 16:57:26 Grant Edwards, vous avez ?crit?: > On 2008-09-16, Maric Michaud wrote: > > Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit?: > >> On 2008-09-16, Maric Michaud wrote: > >> > all expressions that return something, return a new object, > >> > >> That's not _quite_ true: > >> >>> a=1 > >> >>> b=a.__add__(0) > >> >>> a is b > >> > >> True > >> > >> ;) > > > > This is implementation specific, > > Indeed. > > > the specification of the language says that it should be > > false, > > That's curious. If so, then the implimentation is in violating > the specification. But it doesn't matter as the "is" operator is not relevant for any use case with scalars and even strings and the optimization is not negligible. In fact, I'd rather say it's unspecified, each implementation does it its own way. maric at redflag1 17:48:03:~$ ipython >>>[1]: int() is 0 # contructor honour cache ...[1]: True >>>[2]: 256 is 255+1 # still caching ...[1]: True >>>[3]: 257 is 255+2 # here it stops ...[3]: False maric at redflag1 17:48:08:~$ jython Jython 2.2.1 on java1.6.0_07 Type "copyright", "credits" or "license" for more information. >>> int() is 0 # not caching when using constructor 0 >>> 2 is 1+1 # caching on expression 1 >>> 500 is 250*2 # caching occurs beyond my CPython 1 >>> 5000 is 5000 # compile-time optimization 1 >>> 5000 is 2500*2 # not caching too big numbers 0 > Where is that in the specification? Each literal creates a new instance, and instances of int are not supposed to be unique for each value (at less it's not specified so), so "1 is not 1", but implementation can cache integers, short strings, to avoid creating an new instance each time they appear in code. jython do this also for integer (see above), but not for strings : maric at redflag1 17:33:52:~$ jython Jython 2.2.1 on java1.6.0_07 Type "copyright", "credits" or "license" for more information. >>> a = "aaaa" >>> a is "aaaa" 0 maric at redflag1 17:36:48:~$ ipython >>>[1]: a = "aaaa" >>>[2]: a is "aaaa" ...[2]: True BTW, I'm talking of Jython 2.2, Jython 2.4, which quite ready I think, can change his mind as well. > I > suspect the statement in the specification should only apply to > mutable objects. > No, CPython also have a unique empty tuple, but tuple literals are not cached nor there are compile-time optimization : >>>[5]: () is () ...[5]: True >>>[6]: (1,) is (1,) ...[6]: False > > and it is for higher numbers : > >>>>[15]: a=1000 > >>>> > >>>>[16]: b=a.__add__(0) > >>>> > >>>>[17]: a is b > > > > ...[17]: False > > > > Don't disturb our OP, with side questions, please, it was > > enough hard like this ;) > > I'm not trying to confuse the OP, but to quote Einstein: > "Everything should be made as simple as possible, but not > simpler." -- _____________ Maric Michaud From castironpi at gmail.com Tue Sep 16 13:43:04 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 10:43:04 -0700 (PDT) Subject: how to exclude specific things when pickling? References: Message-ID: <35fe74c7-c130-4d82-80d1-8c972520ecfc@y38g2000hsy.googlegroups.com> On Sep 14, 9:53?am, "inhahe" wrote: > If I gather correctly pickling an object will pickle its entire hierarchy, > but what if there are certain types of objects anywhere within the hierarchy > that I don't want included in the serialization? ?What do I do to exclude > them? ? Thanks. Are you picturing a custom pickler object? From annathorns at googlemail.com Mon Sep 22 12:25:06 2008 From: annathorns at googlemail.com (annathorns at googlemail.com) Date: Mon, 22 Sep 2008 09:25:06 -0700 (PDT) Subject: Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS Message-ID: <6298ac0c-9563-46af-90e3-9bab31b8204f@o40g2000prn.googlegroups.com> Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com From justin.kuto at gmail.com Fri Sep 26 16:33:42 2008 From: justin.kuto at gmail.com (afrogazer) Date: Fri, 26 Sep 2008 13:33:42 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> Message-ID: <7b1181e9-16a2-458a-8677-a2d8d7c8a961@l42g2000hsc.googlegroups.com> In my rush I seem to have overlooked that, maybe because it's Friday afternoon. Converting the degrees to radians fixed it: rad_angles = [elem*(pi/180) for elem in angles] Thanks, From i3dmaster at gmail.com Fri Sep 12 19:18:59 2008 From: i3dmaster at gmail.com (i3dmaster) Date: Fri, 12 Sep 2008 16:18:59 -0700 (PDT) Subject: conditional install/distribution References: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> <6it533Fe2h8U1@mid.uni-berlin.de> Message-ID: <3f8893c3-fd23-4734-a2d4-07921be67202@z11g2000prl.googlegroups.com> On Sep 11, 11:07?am, "Diez B. Roggisch" wrote: > i3dmasterschrieb: > > > Is there a feature in distutils or easy_install to specify what > > version of python that the target package can be installed? For > > example, if a package has a module that only needed if the python > > version < 2.6, is there a way to specifiy that in setup.py or > > easy_install cfg file so that when installing to python >= 2.6, this > > module wouldn't be installed?? > > you can simply import sys and check sys.version in the setup-script, and > abort with an error-message if the expectations aren't matched. > > Diez I know I can precheck the version, but the real issue is how I can prevent from installing a specific module? Actually, the rest of the package should still be installed but just not a particular module because the feature is built in after 2.6. From skip at pobox.com Tue Sep 23 09:36:14 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Sep 2008 08:36:14 -0500 Subject: Mutex not thread safe? PEP-3108. In-Reply-To: References: Message-ID: <18648.61646.947232.439715@montanaro-dyndns-org.local> >>>>> "Roy" == Roy Smith writes: Roy> I'm perusing PEP-3108 and came upon this interesting statement Roy> (under the "Hardly used" section): Roy> mutex [...] Not thread-safe. Roy> How can a mutex, whose sole reason for existence is to mediate thread Roy> safety, not be thread safe? Because it is a mutex in name only. Take a look at the code. There is nothing in there which actually locks the internal data structure against simultaneous manipulation (a collections.deque instance in this case) from multiple threads. Skip From tino at wildenhain.de Mon Sep 29 09:25:39 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 29 Sep 2008 15:25:39 +0200 Subject: writing dll in python? In-Reply-To: References: Message-ID: <48E0D753.3040101@wildenhain.de> nishalrs wrote: > Hello All, > > My main motivation is to build a collection of useful mathematical > models (that I have developed over the years) to design ultrasonic > sensors. This should be some sort of a library that should be able to > be used for desktop/web application development, to run in variety of > operating systems. > > I am more than convinced after looking at python.org website, it is > the right tool for the job. I intend to learn python, but I am not > really sure, where to begin. > > Should I write all the functions as simple python scripts? Or is there > some facility for creating a .dll like library, that could be more > suitable for what in intend to develop? This is called a module in python, you can also collect modules to a package. Once you have your package ready, you can distribute them as egg if you want (basically a distribution as zip file) - look up python eggs and easy-install with your search engine of choice. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From febkimbleox at gmail.com Sat Sep 27 07:17:18 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:17:18 -0700 (PDT) Subject: amaterske porno slike amaterske porno slike free amaterske slike porno amaterske - Free Message-ID: amaterske . . . *******CLICK HERE******** http://vids365.cn/amaterske ***************************** . . . . . . . . . . . . I too enjoyed the sight of amaterske big tits flying in every direction. I too enjoyed the sight of porno big tits flying in every direction. I too enjoyed the sight of slike big tits flying in every direction. I too enjoyed the sight of amaterske big tits flying in every direction. I too enjoyed the sight of porno big tits flying in every direction. Let slike finish these steaks, they?re almost done. Let free finish these steaks, they?re almost done. Let amaterske finish these steaks, they?re almost done. Let slike finish these steaks, they?re almost done. Let porno finish these steaks, they?re almost done. Let amaterske finish these steaks, they?re almost done. Let porno finish these steaks, they?re almost done. Let slike finish these steaks, they?re almost done. Let srbija finish these steaks, they?re almost done. From luigi.paioro at gmail.com Wed Sep 10 03:40:25 2008 From: luigi.paioro at gmail.com (luigi.paioro at gmail.com) Date: Wed, 10 Sep 2008 00:40:25 -0700 (PDT) Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> <6inkkiFrbptbU1@mid.uni-berlin.de> Message-ID: <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> On 9 Set, 17:55, "Diez B. Roggisch" wrote: > I would go for a slightly different approach: make your server have a > dispatch-method that delegates the calls to the underlying actual > implementation. But *before* that happens, extract the information as > above, and either > > ?- prepend it to the argument list > > ?- stuff it into threadlocal variables, and only access these if needed in > your implementation. > > Diez Are you suggesting me to overwrite the _dispatch(self, method, params) method of SimpleXMLRPCDispatcher? I thought to this possibility, but it only accepts "method" and "params" as arguments, so, as far as I know, I have no way to get the user and host address to append. Perhaps I've misunderstood your suggestion... in that case can you post a short example? Thank you very much! Luigi From mblume at socha.net Thu Sep 4 13:03:33 2008 From: mblume at socha.net (mblume) Date: 04 Sep 2008 17:03:33 GMT Subject: Read Binary data References: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> Message-ID: <48c014e5$0$16176$5402220f@news.sunrise.ch> Am Thu, 04 Sep 2008 18:03:54 +0200 schrieb Fredrik Lundh: > >> I am trying to read a binary file [...] > > > f = open("a.bin", "rb") # read binary data > s = f.read() # read all bytes into a string > > import array, sys > > a = array.array("f", s) # "f" for float > if sys.byteorder != "big": > a.byteswap() > For more complicated structures, the struct module may help. HTH. Martin From bj_666 at gmx.net Sun Sep 28 06:15:00 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Sep 2008 10:15:00 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> Message-ID: <6k93opF6k62hU1@mid.uni-berlin.de> On Sun, 28 Sep 2008 01:35:11 -0700, est wrote: >> Because that's how ASCII is defined. >> Because that's how ASCII is defined. ASCII is a 7-bit code. > > Then why can't python use another default encoding internally > range(256)? Because that doesn't suffice. Unicode code points can be >255. > If Python choose another default encoding which handles range(256), 80% > of python unicode encoding problems are gone. 80% of *your* problems with it *seems* to be gone then. > It's not HARD to process unicode, it's just python & python community > refuse to correct it. It is somewhat hard to deal with unicode because many don't want to think about it or don't grasp the relationship between encodings, byte values, and characters. Including you. >> stop dreaming of a magic solution > > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, what's > wrong???? What do you mean by "just print 0x7F to 0xFF"? For example if I have ``s = u'Sm?rebr?d?'`` what bytes should ``str(s)`` produce and why those and not others? >> Isn't that more or less the same as telling the OP to use unicode() >> instead of str()? > > sockets could handle str() only. If you throw unicode objects to a > socket, it will automatically call str() and cause an error. Because *you* have to tell explicitly how the unicode object should be encoded as bytes. Python can't do this automatically because it has *no idea* what the process at the other end of the socket expects. Now you are complaining that Python chooses ASCII. If it is changed to something else, like MBCS, others start complaining why it is MBCS and not something different. See: No fix, just moving the problem to someone else. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Sun Sep 28 02:14:01 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Sep 2008 06:14:01 GMT Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Message-ID: <6k8ll9F6jbmtU2@mid.uni-berlin.de> On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote: > To me, this is a somewhat unintuitive behavior. I want to discuss the > parts of it I don't understand. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= lambda: n > ... >>>> f[0]() > 9 >>>> f[1]() > 9 `n` is looked up at the time ``f[0]`` is called. At that time it is bound to 9. >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= (lambda n: ( lambda: n ) )( n ) ... >>>> f[0]() > 0 >>>> f[1]() > 1 > > Which is of course the desired effect. Why doesn't the second one just > look up what 'n' is when I call f[0], and return 9? It *does* look up `n` at the time you call ``f[0]`` but this time it's the local `n` of the outer ``lambda`` function and that is bound to whatever the function was called with. At the time it was called the global `n` was bound to 0. Maybe it get's more clear if you don't name it `n`: In [167]: f = [None] * 10 In [168]: for n in xrange(10): .....: f[n] = (lambda x: lambda: x)(n) .....: In [169]: f[0]() Out[169]: 0 Ciao, Marc 'BlackJack' Rintsch From coolkid246 at googlemail.com Thu Sep 4 05:45:02 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 02:45:02 -0700 (PDT) Subject: guenstige kredite Message-ID: <40d2d448-0e35-4877-b236-465dc9017f18@a3g2000prm.googlegroups.com> + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://kredite-online-244.info + + + + From sjmachin at lexicon.net Sun Sep 7 18:42:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Sep 2008 15:42:00 -0700 (PDT) Subject: lacking follow-through References: <6ij1ecFqp39rU4@mid.uni-berlin.de> Message-ID: On Sep 8, 8:36?am, Fredrik Lundh wrote: > Marc 'BlackJack' Rintsch wrote: > > Yeah, castironpi sometimes doesn't make much sense. ?Maybe because it's a > > bot!? ?:-) > > if so, they sure don't make c.l.py bots like they used to, do they? > > That's correct. This one seems to have an anger management module :-) From pavlovevidence at gmail.com Thu Sep 4 14:59:43 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 11:59:43 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: On Sep 4, 7:09 am, "Marco Bizzarri" wrote: > Sorry... pressed enter but really didn't want to. > > As I said, let's say I have a class > > class A: > def __init__(self): > self.x = None > > Python makes the decision to allow the developers to directly access > the attribute "x", so that they can directly write: "a.x = 1", or > whatever; this has for me the unfortunate side effect that if I write, > for example "a.y = 1", when I really wanted to write "a.x = 1" no one > cares about it, and I'm unable to spot this error until later. You can write code to guard against this if you want: class A: legal = set(["x"]) def __setattr__(self,attr,val): if attr not in self.legal: raise AttributeError("A object has no attribute '%s'" % attr) self.__dict__[attr] = val def __init__(self,x): self.y = x I suspect most people who go into Python doing something like this soon abandon it when they see how rarely it actually catches anything. Carl Banks From rex.eastbourne at gmail.com Thu Sep 4 17:33:38 2008 From: rex.eastbourne at gmail.com (Rex) Date: Thu, 4 Sep 2008 14:33:38 -0700 (PDT) Subject: Is it possible to download only the of a web page? Message-ID: I am writing a script that executes a bunch of queries through a form on a website and reads the results. I am only interested in the section in the <head> of each web page. Currently, each page the server returns is about 100kb and contains a bunch of HTML and Javascript, all of which I don't need; I don't want to waste bandwidth or consume too much of the server's resources. I just need the <title> string. Is there any way to download less than the entire web page? From lixinyi.23 at gmail.com Wed Sep 24 02:39:48 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 23:39:48 -0700 (PDT) Subject: PyRun_SimpleFile() crashes Message-ID: <d71e6607-31ca-48a6-b61f-040536a7cebf@g17g2000prg.googlegroups.com> my code: main.cpp #include <Python.h> int main(int argc, char **argv) { Py_Initialize(); FILE *file_1 = fopen("a2l_reader.py","r+"); PyRun_SimpleFile(file_1,"a2l_reader.py"); Py_Finalize(); } compile under windows using MinGW: g++ main.cpp libpython25.a -o a no error was found. But when I run a.exe the program just crashes. What should I do? From ldo at geek-central.gen.new_zealand Wed Sep 17 20:20:55 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 18 Sep 2008 12:20:55 +1200 Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <tvkf941kmehd7hcihihdiil6fjutbfkf6k@4ax.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> Message-ID: <gas6t7$382$1@lust.ihug.co.nz> In message <973f75d4-90f5-4930-9107-15fc8651196d at v16g2000prc.googlegroups.com>, sui wrote: > Traceback (most recent call last): > File "mail5.py", line 21, in <module> > session = smtplib.SMTP(SMTPserver,port) > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > self.sock.connect(sa) > File "<string>", line 1, in connect > then conncetion time out..... Could it be your ISP is blocking outgoing connections to port 25? From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 13:11:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 19:11:35 +0200 Subject: improving a huge double-for cycle In-Reply-To: <48d2bd22$0$4514$426a74cc@news.free.fr> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <48d54ab4$0$20563$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > Alexzive a ?crit : >> Hello there :) , >> (snip) > > Now the obvious winner is pruebono Correction (my bad) : Steven D'Aprano submitted the set-based solution first. So the winners are Steven and pruebono. From rex.eastbourne at gmail.com Thu Sep 4 14:16:47 2008 From: rex.eastbourne at gmail.com (Rex) Date: Thu, 4 Sep 2008 11:16:47 -0700 (PDT) Subject: Submitting forms over HTTPS with mechanize References: <b85ddf6d-ab66-423e-8840-0d8a962f91ba@v16g2000prc.googlegroups.com> <48BF4554.7060809@vitalEsafe.com> Message-ID: <782f1eff-a3b2-4cd8-a134-68300510ae42@k36g2000pri.googlegroups.com> On Sep 3, 10:17?pm, Larry Bates <larry.ba... at vitalEsafe.com> wrote: > Rex wrote: > > Hello, > > > I am working on an academic research project where I need to log in to > > a website (www.lexis.com) over HTTPS and execute a bunch of queries to > > gather a data set. I just discovered the mechanize module, which seems > > great because it's a high-level tool. However, I can't find any decent > > documentation for mechanize apart from the docstrings, which are > > pretty thin. So I just followed some other examples I found online, to > > produce the following: > > > baseurl = 'http://www.lexis.com/' > > br = mechanize.Browser() > > br.set_handle_robots(False) > > br.addheaders = [('User-Agent', 'Firefox')] > > br.open(baseurl) > > br.select_form(name="formauth") > > br["USER_ID"]="my_user_id" > > br["PASSWORD"]="my_password" > > result = br.submit() > > > This code hangs at br.submit(), and I can't tell what I'm doing wrong. > > Typically I would inspect the HTTP data with an HTTP debugging proxy > > (Fiddler), but I guess since this is HTTPS I can't do that. Any > > glaring errors in my code? > > > By the way, does anyone have suggestions for Python modules that I > > should use instead of mechanize (and that are sufficiently easy)? If > > mechanize fails, I might try modifying some similar Perl code a friend > > sent me that logs into lexis.com. > > > Thanks so much, > > > Rex > > I've used mechanize quite successfully but others have suggested Twillhttp://twill.idyll.org/. ?It seems to be at least documented. > > -Larry Thanks for the reply, Larry. I ran my code again and it worked; there was probably some temporary issue with either my computer or the server that caused it to hang. From thomascribbs at gmail.com Tue Sep 30 14:03:25 2008 From: thomascribbs at gmail.com (thomascribbs at gmail.com) Date: Tue, 30 Sep 2008 11:03:25 -0700 (PDT) Subject: IDLE doesn't run on OSX 10.3.9 Message-ID: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> Just installed Python 2.5.2 on a PowerPC G4 running OSX 10.3.9 and when clicking on the IDLE icon in the MacPython 2.5 folder nothing happens, program doesn't execute... I've uninstalled, reinstalled over again... I friend of mine just installed the same 2.5.2 download from the Python.org website on OSX 10.4.11 and all went fine...but shouldn't it install on 10.3.9 as well? Anyone have any ideas? Thanks. -Tom From gagsl-py2 at yahoo.com.ar Sat Sep 20 20:06:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Sep 2008 21:06:01 -0300 Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> <Xns9B1FB27C6AC44duncanbooth@127.0.0.1> <c53f8fc8-97a3-45cf-9507-065bb7439272@m36g2000hse.googlegroups.com> <e177ceee-1dad-4858-9c2d-ff6d770d1349@s50g2000hsb.googlegroups.com> Message-ID: <op.uhs08bgfx6zn5v@a98gizw.noga> En Sat, 20 Sep 2008 20:27:41 -0300, Alex Snast <asnast at gmail.com> escribi?: > Another quick question please, is the List data structure just a > dynamic array? If so how can you use static size array, linked list, > AVL trees etcetera. Yes, lists are implemented as dynamic arrays (but you shouldn't care about it). "Textbook" linked lists are good for a CS course, but useless in most usual circumstances (think of memory fragmentation). There are AVL trees implemented in Python, but not built in. Read the Python Tutorial specially this section http://docs.python.org/tut/node7.html You may be interested in the collections module too http://docs.python.org/lib/module-collections.html -- Gabriel Genellina From stefan_ml at behnel.de Tue Sep 2 02:06:35 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 02 Sep 2008 08:06:35 +0200 Subject: python mechanize/libxml2dom question In-Reply-To: <mailman.351.1220326560.3487.python-list@python.org> References: <mailman.351.1220326560.3487.python-list@python.org> Message-ID: <48bcd7eb$0$20713$9b4e6d93@newsspool4.arcor-online.net> bruce wrote: > i've got the following situation, with the following test url: > "http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#". > > i can generate a list of the tables i want for the courses on the page. > however, when i try to create the xpath query, and plug it into the xpath > within python, i'm missing something. if i have a parent xpath query, that > generates a list of results/nodes... how can i then use the individual > parent node, and trigger off of it, to get further information. [code example stripped] You should really use lxml. It has callable XPath objects that feel like Python functions, and its Element objects have a getparent() method that gets you to the parent of the node. Plus, text strings that you get back from an XPath evaluation also have a getparent() method that returns the Element object that holds the text. I think that's what you were looking for. Stefan From afilash at gmail.com Tue Sep 9 01:10:11 2008 From: afilash at gmail.com (abhilash pp) Date: Tue, 9 Sep 2008 10:40:11 +0530 Subject: firefox timestamp In-Reply-To: <ga3dj8$vfg$1@ger.gmane.org> References: <9f9d35df0809072317h49ccec2ep72524f8d4900daa0@mail.gmail.com> <ga3dj8$vfg$1@ger.gmane.org> Message-ID: <9f9d35df0809082210s2d09a9d5rd9256675461f7c28@mail.gmail.com> thanks Fredrik, yeah it works !!! On Mon, Sep 8, 2008 at 8:11 PM, Fredrik Lundh <fredrik at pythonware.com>wrote: > abhilash pp wrote: > > I don't know if this question will fit on this section, >> any way my query is , i have used one script demork.py to extract details >> from Firefox history.dat file >> and now the problem is how to convert the TIMESTAMP given by that to >> normal date and time. >> example timestams are like this, >> >> 1202919771609375 >> 1213874676203125 >> 1215693263859375 >> >> i have used datetime module for this but it gave me error >> > > a quick googling indicates that the file contains microseconds, not > seconds. dividing by 1e6 should do the trick: > > >>> t = 1202919771609375 > >>> datetime.datetime.fromtimestamp(t / 1e6) > datetime.datetime(2008, 2, 13, 17, 22, 51, 609375) > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080909/3ae8deb3/attachment.html> From hniksic at xemacs.org Mon Sep 22 09:29:53 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 22 Sep 2008 15:29:53 +0200 Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: <87myi0z4tq.fsf@mulj.homelinux.net> josh logan <dear.jay.logan at gmail.com> writes: > sorted(P) # throws TypeError: unorderable types Player() < Player() > > The sorted function works when I define __lt__. > I must be misreading the documentation, because I read for the > documentation __cmp__ that it is called if none of the other rich > comparison functions are defined. > Is this a bug in Python 3.0rc1, or am I missing something? What documentation are you referring to, exactly? The whole __cmp__ thing was supposed to be removed from Python 3, so mention of it sounds like a documentation bug. > Secondly, say that we suddenly need another sorting order, where we > want to sort by decreasing score and then by DECREASING last name > (instead of increasing last name, defined above). Now that the > comparison function argument is taken away from the sorted builtin, > how do we accomplish this with the "key" parameter? By calling sort twice on the sequence: lst.sort(key=lambda x: x.score) lst.sort(key=lambda x: x.last_name, reverse=True) As much as I like the key argument, I believe it was a mistake to remove cmp, simply because it was the more general mechanism. Emulating cmp with key is possible, but it requires creating a bunch of objects for each sort. (I'm aware that list.sort caches the calculated keys, but it still has to create as many of them as there are list items.) From code at pizzashack.org Tue Sep 2 17:41:04 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 17:41:04 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i5g2aFol29aU6@mid.uni-berlin.de> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <mailman.370.1220369964.3487.python-list@python.org> <6i5g2aFol29aU6@mid.uni-berlin.de> Message-ID: <20080902214104.GR29228@dragontoe.org> On Tue, Sep 02, 2008 at 06:47:39PM +0000, Marc 'BlackJack' Rintsch wrote: > That's why I think the name `Popen` is not so good for it. Because it > does more than `popen()` and if it is called `Subprocess` or just > `Process` then it would be merely an implementation detail, that the > `popen()` function is called at some point. The module is subprocess, and the class is Popen. The underlying implementation doesn't really matter; the class still does essentally the same as the combination of popen() and pclose(): it opens pipes to a subprocess, and allows the parent to wait until that process has terminated, and closes the pipe(s). The rationale for naming the class Popen is exactly the same as the rationale for naming the analogous functions. Do you think that subprocess.pipe() is not as good a name as subprocess.subprocess()? > If it is at all, because `popen()` on C level can just open a pipe > in *one* direction. That also is not (necessarily) true. Some Unix implementations provide bidirectional implementations of popen(). See, for example, the OS X popen() man page. It's existed in BSD Unix for years... > > Note that in all of these links that talk about popen, the focus is on > > opening pipes or file objects, not on subprocesses: > > > > http://www.opengroup.org/onlinepubs/009695399/functions/popen.html > > http://docs.python.org/lib/os-newstreams.html http://us3.php.net/popen > > http://docs.hp.com/en/B9106-90010/popen.3S.html > > http://www.faqs.org/docs/artu/ch07s02.html > > And all of the links talk about the `popen()` function, > not about the functionality the `Popen` class provides. Which is > much more than that simple pipe `popen()` returns. Well, you're comparing a class to a function, so no surprise there. But it's not really that much more, if you include pclose(). With the exception that it allows you to connect multiple streams instead of only one, and it saves the PID of the child (which for the most part is not especially useful), the functionality is identical. If you actually look at the Python implementation of the subprocess.Popen class, the implementation is essentially identical to the C implementation of the popen() and pclose() functions except that the latter saves the PID returned by the call to fork() in a class attribute, and opens 3 pipes instead of 1. If C's popen() and pclose() functions were written as a C++ class instead of two separate functions, it would look rather a lot like python's subprocess.Popen class. > > The Linux man page unfortunately copies (verbatim) the FreeBSD man > > page, which gets it wrong. You can not open a process, but you > > can definitely open a pipe. > > Ah, when their terminology doesn't match yours, they must get it > wrong. ;-) Nice try... Their terminology doesn't match the original author's. Here's the original AT&T System 7 man page: http://www.freebsd.org/cgi/man.cgi?query=popen&apropos=0&sektion=0&manpath=Unix+Seventh+Edition&format=html When describing what this function does, it states, "It creates a pipe..." Besides which, the BSD folks felt the need to quote "open", indicating that clearly they knew that no process is being "opened" by the function call. You start processes, you don't open them. This should have been a clue to the BSD manual page writer that they had the sense wrong; it's very obviously the pipe that gets opened, not the process. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/3110b0fa/attachment.sig> From tino at wildenhain.de Fri Sep 19 01:11:51 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 19 Sep 2008 07:11:51 +0200 Subject: improving a huge double-for cycle In-Reply-To: <gavaq2$klm$1@ger.gmane.org> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <gavaq2$klm$1@ger.gmane.org> Message-ID: <48D33497.4010403@wildenhain.de> Hi, Terry Reedy wrote: ... > Yes, after figuring out what to do from the original post, I saw yours > and then Pruebono's and decided that since two people had submitted the > jackpot algorithm, I need not say more. I will say this: this solution > amounts to finding equivalence classes (the sets of items with a given > 'key') and then finding the classes (sets) with more than one member. > Defaultdict is great for this. I must say mine works with at least similar performance. Maybe its a timezone issue but I also provided a simple test to my solution. Also I never saw a list where the threading often goes wrong like this here - is there any special setup or is it just peoples MUA which screws up? T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080919/591f0c83/attachment.bin> From marco.bizzarri at gmail.com Mon Sep 15 14:26:27 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 15 Sep 2008 20:26:27 +0200 Subject: Zsi interoperability In-Reply-To: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> References: <mailman.1047.1221498380.3487.python-list@python.org> <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <3f0d61c40809151126n791b1ce0ya1e208a075660934@mail.gmail.com> On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel <stefan_ml at behnel.de> wrote: > Mailing List SVR wrote: >> I have to implement a soap web services from wsdl, the server is >> developed using oracle, is zsi or some other python library for soap >> interoperable with oracle soa? > > No idea, but I'd definitely try soaplib before ZSI. > > Stefan I'm working on a project where I need to write a client for SOAP with Attachments; I can see ZSI does not support it; is soaplib any better? Can you argument your suggestion a little more? Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From tjreedy at udel.edu Sun Sep 28 23:56:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 23:56:02 -0400 Subject: closures and dynamic binding In-Reply-To: <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> Message-ID: <gbpjkb$8ct$1@ger.gmane.org> Aaron "Castironpi" Brady wrote: > On Sep 28, 4:47 pm, Terry Reedy <tjre... at udel.edu> wrote: >> Aaron "Castironpi" Brady wrote: >>>>>> inner = lambda: n >> when inner is actually compiled outside of outer, it is no longer a >> closure over outer's 'n' and 'n' will be looked for in globals instead. >> >>>>>> outer = lambda n: inner >>>>>> outer(0) >>> <function <lambda> at 0x00A01170> >>>>>> a=outer(0) >>>>>> b=outer(1) >>>>>> a() >>> Traceback (most recent call last): >>> File "<stdin>", line 1, in <module> >>> File "<stdin>", line 1, in <lambda> >>> NameError: global name 'n' is not defined >>> Why doesn't 'inner' know it's been used in two different scopes, and >>> look up 'n' based on the one it's in? >> That would be dynamic rather than lexical scoping. > > I couldn't find how those apply on the wikipedia website. It says: > "dynamic scoping can be dangerous and almost no modern languages use > it", but it sounded like that was what closures use. Or maybe it was > what 'inner' in Steven's example would use. I'm confused. As I understand it, partly from postings here years ago... Lexical: The namespace scope of 'n' in inner is determined by where inner is located in the code -- where is is compiled. This is Python (and nearly all modern languages). Even without closures, the global scope of a function is the module it is defined in. Dynamic: The namespace scope of 'n' in inner, how it is looked up, is determined by where inner is called from. This is what you seemed to be suggesting -- look up 'n' based on the scope it is *used* in. Even without closures, dynamic scoping would be if the global scope of a function for each call were the module it is called in. tjr From john.m.roach at gmail.com Tue Sep 9 14:44:00 2008 From: john.m.roach at gmail.com (john) Date: Tue, 9 Sep 2008 11:44:00 -0700 (PDT) Subject: F2PY changing integers to arrays??? References: <7d60c85f-12cf-47fc-84c9-58e50cad4eaf@x35g2000hsb.googlegroups.com> <ga6bpa$avj$1@inews.gazeta.pl> Message-ID: <aec39fcc-f860-4344-9cee-b0358728746b@25g2000hsx.googlegroups.com> Hmmm... I didn't even try that... I thought this might have caused problems down the road passing this var to other classes, etc., but i guess not! Thanks. From lamciuloeng at gmail.com Fri Sep 12 00:15:05 2008 From: lamciuloeng at gmail.com (CL (Ciu Loeng) Lam) Date: Fri, 12 Sep 2008 12:15:05 +0800 Subject: Problem on getting date column in SQLObject Message-ID: <b922cb950809112115h63afdcc1l1233e7917cbee43a@mail.gmail.com> Hi,all:I make the SQLObject as the ORM in turbogears ,now I meet a problems on selecting records for a given date . Here is the define for my class: class updateHistory(SQLObject): actionTime = DateTimeCol(default=datetime.now) actionContent = UnicodeCol(length=500,default="") Then how can I get the records during a special time ,for example , from 2008-05-10 to 2008-09-01, It will be very thankful if someone could paste some snippets for this problems. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080912/7a149906/attachment.html> From gagsl-py2 at yahoo.com.ar Tue Sep 23 20:13:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Sep 2008 21:13:27 -0300 Subject: finding domain name References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> Message-ID: <op.uhylkpvex6zn5v@a98gizw.noga> En Tue, 23 Sep 2008 09:37:44 -0300, Bobby Roberts <tchendrix at gmail.com> escribi?: > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/xxxxx/ > > where xxxxx represents the domain name. > > How can I find the domain name of the current url being viewed. That info comes from the "Host" request field, and whether it's available or not depends on the web framework in use; for a plain old CGI script, it depends on the server configuration. Look at the HTTP_HOST environment variable (accessing os.environ, or with the cgi.print_environ() function) -- Gabriel Genellina From To-Email-Use-The-Envelope-Icon at My-Web-Site.com Sun Sep 21 23:01:31 2008 From: To-Email-Use-The-Envelope-Icon at My-Web-Site.com (Jim Thompson) Date: Sun, 21 Sep 2008 20:01:31 -0700 Subject: Milenko Kindl rtegdgd References: <b3a8139e-656c-4451-bbe4-203d48cb3203@d77g2000hsb.googlegroups.com> <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> <HoGdnZmrGszOn0rVnZ2dnUVZ_t3inZ2d@earthlink.com> Message-ID: <vi2ed4t5niveijg7d5e88ia54bchdj2rje@4ax.com> On Sun, 21 Sep 2008 22:26:27 -0400, "Michael A. Terrell" <mike.terrell at earthlink.net> wrote: > >H Vlems wrote: >> >> On 21 sep, 19:48, yuma <yuma400... at yahoo.com> wrote: >> > Milenko Kindl >> > Banja Luka >> > Banjaluka >> > Bihac >> >> Well, that's not C isn't it, more like Snobol or RPG/2 > > > Tidybowl I thought you blanked googlegroups, n'est ce pas ?:-) ...Jim Thompson -- | James E.Thompson, P.E. | mens | | Analog Innovations, Inc. | et | | Analog/Mixed-Signal ASIC's and Discrete Systems | manus | | Phoenix, Arizona 85048 Skype: Contacts Only | | | Voice:(480)460-2350 Fax: Available upon request | Brass Rat | | E-mail Icon at http://www.analog-innovations.com | 1962 | I love to cook with wine Sometimes I even put it in the food From george.sakkis at gmail.com Fri Sep 26 22:09:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 26 Sep 2008 19:09:42 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <dZOdnQINKORUEUDVnZ2dnUVZ_rvinZ2d@posted.usinternet> Message-ID: <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> On Sep 26, 9:30?pm, Grant Edwards <gra... at visi.com> wrote: > On 2008-09-26, nntpman68 <news1... at free.fr> wrote: > > > Hm, > > > I guess you just filter mailing lists and can do nothing about the > > newsgroup if I'm fetching via the nntp server of my ISP itself, right? > > I read the group via NNTP, and I find that blocking all > articles posted from google.groups gets rid of all of the spam. ... along with a far from trivial (I guess) percentage of non-spam, such as this post. And-nothing-of-value-was-lost'ly yrs, George From gagsl-py2 at yahoo.com.ar Thu Sep 25 16:35:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Sep 2008 17:35:27 -0300 Subject: what does "python -i" use as input stream (stdin)? References: <cc38d75f0809250549u2acff662n765bc1c2990d0e78@mail.gmail.com> Message-ID: <op.uh10tdgcx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 25 Sep 2008 09:49:31 -0300, Almar Klein <almar.klein at gmail.com> escribi?: > Hi, > I want to start "python -i" from a subprocess and change its stdin > stream, > so I get control over the commands I feed the interpreter. > > I thought just changing sys.stdin to my custom file-like object would > suffice, but this does not work. Neither does changing sys.__stdin__. > > I guess the interpreter got a reference to the original stdin (the Pipe) > before > I could change it, and is using that instead of sys.stdin. > > Any thoughts how I can get the interpreter to use MY custom stream? Use subprocess.PIPE Usually the tricky part is to figure out exactly whether there is more input or not. With Python it's easy, use the ps1 prompt. --- begin --- import sys import subprocess def read_until_prompt(stdout): while True: line = stdout.read(4) if line==sys.ps1: yield line return else: line += stdout.readline() yield line def print_output(stdout): for line in read_until_prompt(stdout): sys.stdout.write(line) s = subprocess.Popen(["python", '-i'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) stdout = s.stdout stdin = s.stdin print_output(stdout) stdin.write("dir()\n") print_output(stdout) stdin.write("def foo(x):\n") stdin.write(" for i in range(x):\n") stdin.write(" print i\n") stdin.write("\n") stdin.write("foo(5)\n") print_output(stdout) stdout.close() stdin.close() s.wait() print "bye" --- begin --- -- Gabriel Genellina From skip at pobox.com Sat Sep 13 18:34:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Sep 2008 17:34:07 -0500 Subject: testing if another instance of a script is already running In-Reply-To: <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> References: <mailman.911.1221221070.3487.python-list@python.org> <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> Message-ID: <18636.16351.501251.683956@montanaro-dyndns-org.local> >> I don't want to handle writing of a PID file because it is too >> Unix/Linux specific way to do this, and I need to keep the code to be >> cross-platform. >> >> I think the better way to achieve this is to use some process >> control, but I'm a neebie and I don't see how to do this in a safe >> and clean way. Aaron> You could use msvcrt.locking, and just lock the script file. I Aaron> am not sure about this. If you want a cross-platform solution, you might try the lockfile module instead: http://pypi.python.org/pypi/lockfile Skip From castironpi at gmail.com Fri Sep 26 14:04:11 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 11:04:11 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> Message-ID: <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> On Sep 26, 11:43?am, "Tim Rowe" <digi... at gmail.com> wrote: > 2008/9/26 Steven D'Aprano <st... at remove-this-cybersource.com.au>: > > > I don't have any objective numbers, but subjectively it seems to me that > > the number of spams is significantly higher, but not so high as to be a > > major nuisance. > > I consider *any* spam to be a major nuisance, but I don't see them as > being the fault of python-list which seems to do a pretty good job of > blocking them > > -- > Tim Rowe Is it worth mentioning that they come from the same author in a short period of time? Maybe that could bump up the score a notch. I think in June and July they were selling watches a lot which I haven't noticed recently. From fredrik at pythonware.com Wed Sep 17 12:37:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 18:37:31 +0200 Subject: python-mode problem, doesnt load whole module? In-Reply-To: <9b26d9fd-3fe2-4d58-acce-015923d31b50@d1g2000hsg.googlegroups.com> References: <9b26d9fd-3fe2-4d58-acce-015923d31b50@d1g2000hsg.googlegroups.com> Message-ID: <garbob$je7$2@ger.gmane.org> cnb wrote: >>>> a = parsing.unserialize("C:/users/saftarn/desktop/twok.txt") > Traceback (most recent call last): > File "C:\Python25\lib\pickle.py", line 1126, in find_class > klass = getattr(mod, name) when reporting a traceback, please include the error message that follows after the stack trace. </F> From deets at nospam.web.de Wed Sep 3 10:42:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 16:42:11 +0200 Subject: properties setting each other In-Reply-To: <mailman.427.1220450289.3487.python-list@python.org> References: <mailman.427.1220450289.3487.python-list@python.org> Message-ID: <6i7m23Fpc39rU2@mid.uni-berlin.de> mk schrieb: > Hello everyone, > > I try to set two properties, "value" and "square" in the following code, > and arrange it in such way that setting one property also sets another > one and vice versa. But the code seems to get Python into infinite loop: > > >>> import math > >>> class Squared2(object): > > def __init__(self, val): > self._internalval=val > self.square=pow(self._internalval,2) > > def fgetvalue(self): > return self._internalval > > def fsetvalue(self, val): > self._internalval=val > self.square=pow(self._internalval,2) > > value = property(fgetvalue, fsetvalue) > > def fgetsquare(self): > return self.square > def fsetsquare(self,s): > self.square = s > self.value = math.sqrt(self.square) > > square = property(fgetsquare, fsetsquare) > > > >>> a=Squared2(5) > > Traceback (most recent call last): > File "<pyshell#11>", line 1, in <module> > a=Squared2(5) > File "<pyshell#10>", line 5, in __init__ > self.square=pow(self._internalval,2) > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > > ... > > Is there a way to achieve this goal of two mutually setting properties? > Better to make the getter for square return the square of value, and the setter of square compute the root & set that. Like this: class Squared2(object): def __init__(self, value): self.value = value @apply def squared(): def fset(self, squared): self.value = math.sqrt(squared) def fget(self): return self.value ** 2 return property(**locals()) Diez From sjmachin at lexicon.net Wed Sep 10 22:02:50 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Sep 2008 19:02:50 -0700 (PDT) Subject: Logix - gone? References: <276719.72706.qm@web95107.mail.in2.yahoo.com> <mailman.835.1221086049.3487.python-list@python.org> <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> <mailman.840.1221093291.3487.python-list@python.org> Message-ID: <dbebf54c-5e7b-4b79-96f9-5766138ce783@p10g2000prf.googlegroups.com> On Sep 11, 10:34?am, Stephen Johnson <dior... at gmail.com> wrote: > I found Logix (http://livelogix.net/logix/) while looking for ? > something else and thought it looked like a very interesting project. ? > Unfortunately, the blog, mailing list, and Trac links are broken, and ? > the contact email address bounces. > > I am interested in playing with it and working on it if the original ? > author has dropped it. Does anyone know where I could get the source? Ummmm .... try the download link; it worked for me. > > I am asking this here because Logix compiles to Python bytecode, and ? > the author announced to this list at one time. Tom Locke, if you're ? > out there... > > -Steve Johnson (www.steveasleep.com) From marco.wahl at novatec-gmbh.de Thu Sep 18 07:37:05 2008 From: marco.wahl at novatec-gmbh.de (Marco Wahl) Date: Thu, 18 Sep 2008 13:37:05 +0200 Subject: how can I use a callable object as a method References: <gatadc$s6f$1@inews.gazeta.pl> Message-ID: <u63otsn1a.fsf@novatec-gmbh.de> Piotr Sobolewski <NIE_DZIALA at gazeta.pl> writes: > I would like to use a callable object as a method of a class. So, when I > have such normal class: > > I want to change it to something like that: > > class add: > def __call__(self, another_self): > return another_self.version > > class f: > version = 17 > a = add() > > f1 = f() > print f1.a() > > However, the second version does not work. I think I understand why. That's > because "a" inside f1 is not a function (but an object). So f1.a is not a > method. So when I do f1.a(), the implicit argument self is not passed. > > Q1: Am I right? Is this the problem? > Q2: What can I do to make it work? Use the right argument for the call. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class add: def __call__(self, another_self): return another_self.version ... ... ... >>> class f: version = 17 a = add() ... ... ... >>> f1 = f() >>> f1 <__main__.f instance at 0x00A805D0> >>> f1.a <__main__.add instance at 0x00A80DA0> >>> f1.a() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __call__() takes exactly 2 arguments (1 given) >>> f1.a(f1) 17 >>> HTH From fredrik at pythonware.com Fri Sep 5 13:43:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 19:43:14 +0200 Subject: Python and Cyrillic characters in regular expression In-Reply-To: <cb6b6ad1-1070-4b5c-8470-86815ce1beea@79g2000hsk.googlegroups.com> References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> <mailman.497.1220550833.3487.python-list@python.org> <cb6b6ad1-1070-4b5c-8470-86815ce1beea@79g2000hsk.googlegroups.com> Message-ID: <g9rr3k$uo0$1@ger.gmane.org> phasma wrote: > string = u"??????" > (u'\u041f\u0440\u0438\u0432\u0435\u0442',) > > string = u"Hi.??????" > (u'Hi',) the [\w\s] pattern you used matches letters, numbers, underscore, and whitespace. "." doesn't fall into that category, so the "match" method stops when it gets to that character. maybe you could use re.sub or re.findall? >>> # replace all non-alphanumerics with the empty string >>> re.sub("(?u)\W+", "", string) u'Hi\u041f\u0440\u0438\u0432\u0435\u0442' >>> # find runs of alphanumeric characters >>> re.findall("(?u)\w+", string) [u'Hi', u'\u041f\u0440\u0438\u0432\u0435\u0442'] >>> "".join(re.findall("(?u)\w+", string)) u'Hi\u041f\u0440\u0438\u0432\u0435\u0442' (the "sub" example expects you to specify what characters you want to skip, while "findall" expects you to specify what you want to keep.) </F> From siona at chiark.greenend.org.uk Wed Sep 3 10:06:54 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 03 Sep 2008 15:06:54 +0100 (BST) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <omp*-z6ls@news.chiark.greenend.org.uk> <bearophileHUGS at lycos.com> wrote: >Empty Python lists [] don't know the type of the items it will >contain, so this sounds strange: > >>>> sum([]) >0 >>> help(sum) sum(...) sum(sequence, start=0) -> value >>> sum(range(x) for x in range(5)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'list' >>> sum((range(x) for x in range(5)), []) [0, 0, 1, 0, 1, 2, 0, 1, 2, 3] ... so the list might not know what type it contains, but sum does. And if you don't tell it, it makes a sensible guess. And it *is* a case where refusing the temptation to guess is the wrong thing: how many times would you use sum to do anything other than sum numeric values? And how tedious would it be to have to write sum(..., 0) for every other case? Particularly bearing in mind: >>> sum(["a", "b"], "") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sum() can't sum strings [use ''.join(seq) instead] -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From kyosohma at gmail.com Tue Sep 9 16:08:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 9 Sep 2008 13:08:13 -0700 (PDT) Subject: Iowa Python Users Group - First Meeting Message-ID: <9f34ca04-5802-42cf-a4d2-24875ad0d790@a1g2000hsb.googlegroups.com> Hi all, The first meeting date for the Iowa Python Users Group has been decided. Here are the details: ------------------------------------------------------------ Time / Date: Wednesday, Sept. 24 from 7-9 p.m. Location: Marshall County Sheriff's Office, 3rd floor 2369 Jessup Ave Marshalltown, IA 50158 Unofficial website: http://www.ipug.pythonlibrary.org ------------------------------------------------------------ Don't know how to get there? Check out maps.yahoo.com or maps.google.com. The Sheriff's Office is not actually in Marshalltown. If you take Highway 30 East, towards Marshalltown you'll see it on your left. There's a large water tower there and the building is a rusty red color. There are some signs for a Tractor convention there as well. If you're coming from the other direction, then skip ALL the exits and keep driving until the lanes go from 4 lanes to 2. It should be the second right after that. I am still developing the agenda for our first meeting, but here are some of the things we're going to discuss: - What day really works best for meeting? (if you can't make the first one, you can email me your votes!) - Figure out what domain name our group should have - Decide on what Python web framework to use to create said site (which will be a group project) - Try to come up with what format we want our meetings to take. Plone and Zope users are welcome. In fact, anyone who is interested in Python (regardless of their experience with it) is welcome to come. Let your Iowan Python friends know. Questions or ideas? Send them to me. Thanks! ------------------- Mike Driscoll email: mike (at) pythonlibrary (dot) org Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From d3vvnull at gmail.com Sun Sep 28 19:52:14 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sun, 28 Sep 2008 18:52:14 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <gbooat$dh5$1@ger.gmane.org> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> <48DF63B2.2020408@wildenhain.de> <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> <gbooat$dh5$1@ger.gmane.org> Message-ID: <170543c70809281652s7d529428ibe51c1a489151863@mail.gmail.com> Sadly no. There is no utterance too inconsequential. On Sun, Sep 28, 2008 at 3:10 PM, Steve Holden <steve at holdenweb.com> wrote: > Michael Mabin wrote: > > Tino, dude, I'm afraid I lied about my previous post being the last > > word. There are some things you said here that must be addressed. > > Good grief, is there no utterance so inconsequential that you will walk > away from it without yet another round of retaliation? > > I believe that all people were trying to convey is: > > 1. There are some data patterns that cannot be directly incorporated > into SQL statements without additional processing, regardless of whether > the "intention" of the data's originator is malevolent. A good example > is a string value containing an apostrophe, which in most SQL > implementations you can escape by preceding the apostrophe with another > apostrophe. > > 2. SQL drivers in Python are written so that no matter what the values > of the data may be, and no matter which backend they implement, data may > safely be passed as a tuple to a parameterized statement without such > cleansing because the drivers are written to ensure "dangerous" values > are appropriately handled. > > Having said all that, if you are positive none of your string data > contains apostrophes you are, of course, free to build SQL statements > yourself - though doing so will on some systems lose you the speed > advantages offered by "prepared statements". Similarly, if you are *not* > positive of the quality of your data you are free to do the escaping in > your logic rather than using parameterized queries. This could be called > "buying a dog and barking yourself". > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080928/dc2cc944/attachment.html> From sniipe at gmail.com Mon Sep 1 08:57:37 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Mon, 1 Sep 2008 05:57:37 -0700 (PDT) Subject: How to print first(national) char from unicode string encoded in utf-8? Message-ID: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> Hi, I have a problem with unicode string in Pylons templates(Mako). I will print first char from my string encoded in UTF-8 and urllib.quote(), for example string '?ukasz': ${urllib.unquote(c.user.firstName).encode('latin-1')[0:1]} and I received this information: <type 'exceptions.UnicodeDecodeError'>: 'utf8' codec can't decode byte 0xc5 in position 0: unexpected end of data When I change from [0:1] to [0:2] everything is ok. I think it is because of unicode and encoding utf-8(2 bytes). How to resolve this problem? Best regards From st1999 at gmail.com Sun Sep 28 15:27:30 2008 From: st1999 at gmail.com (robean) Date: Sun, 28 Sep 2008 12:27:30 -0700 (PDT) Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> <mailman.1635.1222629122.3487.python-list@python.org> Message-ID: <d127e341-c16d-4ef9-b1de-b9076cefdcb4@i20g2000prf.googlegroups.com> On Sep 28, 12:11?pm, "Chris Rebert" <c... at rebertia.com> wrote: > On Sun, Sep 28, 2008 at 11:03 AM, robean <st1... at gmail.com> wrote: > > Hi everyone, > > > I have a question about using urllib2. > > > I like urllib2 better than urllib at least in part because it has more > > elaborate support for handling errors: there is built in support for > > URLError (for faulty urls) and HTTPError (for http errors that might > > originate from, say, passing an invalid stock-ticker in the program > > below). ?However I can get neither to work. ?I'm attaching below the > > (very short) code: can anyone point out what I'm doing wrong? > > > Now, if I replace the URLError and HTTPError with IOError (the class > > from which both URLError and HTTPError inherit), the program works > > fine. Why is it that I can call the generic IOError class, but none of > > the Error classes derived from that? These are clearly defined in the > > urllib2 manual. Very confused... > > > Here's the code: > > > import urllib2 > > > # read stock information from yahoo finance for Traget (TGT) > > goodTicker = 'TGT' # program works with this > > badTicker = 'TGTttttttt' # python doesn't understand either HTTPError > > or URLError with this > > > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > > try: > > ? ? ? ?handle = urllib2.urlopen(url) > > > # this does not work > > except HTTPError, e: > > ? ? ? ?print "There was an http error" > > ? ? ? ?print e > > > # this also does not work > > except URLError, e: > > ? ? ? ?print "There is a problem with the URL" > > ? ? ? ?print e > > ? ? ? ?exit(1) > > > #this works > > except IOError, e: > > ? ? ? ?print "You have an IOError" > > ? ? ? ?print e > > > text = handle.readlines()[:20] > > for line in text: > > ? ? ? ?print line > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > My Python begs to differ: > > #tmp.py > import urllib2 > > badTicker = 'TGTttttttt' > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > try: > ? ? handle = urllib2.urlopen(url) > > except urllib2.HTTPError, e: > ? ? print "There was an http error" > ? ? print e > > except urllib2.URLError, e: > ? ? print "There is a problem with the URL" > ? ? print e > > except urllib2.IOError, e: > ? ? print "You have an IOError" > ? ? print e > > #in the shell > $ python -V > Python 2.5.1 > $ python Desktop/tmp.py > There was an http error > HTTP Error 404: Not Found > > Are you using an outdated version of Python perhaps? > > Regards, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com Then I expect that it is most likely my version of python that is causing the problem. I'm using 2.5.2. From aonlazio at gmail.com Mon Sep 15 17:51:36 2008 From: aonlazio at gmail.com (AON LAZIO) Date: Mon, 15 Sep 2008 17:51:36 -0400 Subject: The need to use *arg,**kwd Message-ID: <f9e39bbc0809151451j15604641gfc1a10832131c24c@mail.gmail.com> Hi, Pythoners. I'd like to know when it is necessary to use *arg or **kwd in the program. And when it is 'ok' to use normal form of function argument? Thanks in advance. Aonlazio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/8d26d7ab/attachment.html> From dmitrey.kroshko at scipy.org Thu Sep 18 05:03:17 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Thu, 18 Sep 2008 02:03:17 -0700 (PDT) Subject: how to do easy_install to source code, not egg? Message-ID: <499dc07d-261e-4c34-9743-28b55c7945bd@a70g2000hsh.googlegroups.com> Hi all, how to do easy_install <some package> to source code, not egg? (I don't mean "develop" option, it shouldn't call compiled egg-file). Thank you in advance, Dmitrey. From gminick at bzt.bzt Tue Sep 2 10:30:10 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Tue, 2 Sep 2008 14:30:10 +0000 (UTC) Subject: Storing Subprocess Results References: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> Message-ID: <g9jilh$s90$1@inews.gazeta.pl> On Tue, 2 Sep 2008 07:16:21 -0700 (PDT), topazcode wrote: > I am using the subprocess module to run some shell commands on a Linux > system: > > import subprocess > output = subprocess.call('''ssh server1 "uptime"''', shell=True) > > The above assigns the output variable with a return code, i.e. 0 in > this case. How can I actually capture the data returned from > subprocess.call, rather than just the return code? Use subprocess.Popen instead of call. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From srad at inbox.lv Sat Sep 6 06:31:20 2008 From: srad at inbox.lv (Aigars Aigars) Date: Sat, 06 Sep 2008 13:31:20 +0300 Subject: Cancel instance create Message-ID: <1220697080.48c25bf890ade@www.inbox.lv> Good day, I want MyClass to perform some tests and if them fail, I do not want instance to be created. But in code I wrote instance is created and also has parameters, that it should not have in case of tests failure. Is there a way to perform tests in MyClass.__init__ and set instance to None without any parameters? I do not want che code outside MyClass.__init__ to know anything about tests performed, and make decision to allow or prevent instance creation. The code I wrote is: ****************************************************** class MyClass(): def __init__(self): self.param = "spam" Test = False if Test == True: print "Creating instance..." return else: print "Instance creation not allowed..." self = None return None a = MyClass() print a print a.param ************************************************* Thanks, Aigars -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080906/cff73ef6/attachment.html> From tjreedy at udel.edu Tue Sep 30 15:07:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 15:07:08 -0400 Subject: Comparing float and decimal In-Reply-To: <77c70884-4667-4f62-b1e9-ad235855a3d5@z72g2000hsb.googlegroups.com> References: <mailman.1400.1222168827.3487.python-list@python.org> <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> <op.uh9wgumox6zn5v@gabriel2.softlabbsas.com.ar> <mailman.1729.1222762885.3487.python-list@python.org> <77c70884-4667-4f62-b1e9-ad235855a3d5@z72g2000hsb.googlegroups.com> Message-ID: <gbttcr$ghv$1@ger.gmane.org> Mark Dickinson wrote: > On Sep 30, 9:21 am, Terry Reedy <tjre... at udel.edu> wrote: >> If no one beats me to it, I will probably file a bug report or two, but >> I am still thinking about what to say and to suggest. > > I can't see many good options here. Some possibilities: Thanks for responding. Agreeing on a fix would make it more likely to happen sooner ;-) > (0) Do nothing besides documenting the problem > somewhere (perhaps in a manual section entitled > 'Infrequently Asked Questions', or > 'Uncommon Python Pitfalls'). I guess the rule is > simply that Decimals don't mix well with other > numeric types besides integers: if you put both > floats and Decimals into a set, or compare a > Decimal with a Fraction, you're asking for > trouble. I suppose the obvious place for such > a note would be in the decimal documentation, > since non-users of decimal are unlikely to encounter > these problems. Documenting the problem properly would mean changing the set documentation to change at least the definitions of union (|), issubset (<=), issuperset (>=), and symmetric_difference (^) from their current math set based definitions to implementation based definitions that describe what they actually do instead of what they intend to do. I do not like this option. > (1) 'Fix' the Decimal type to do numerical comparisons > with other numeric types correctly, and fix up the > Decimal hash appropriately. (1A) All that is needed for fix equality transitivity corruption and the consequent set/dictview problems is to correctly compare integral values. For this, Decimal hash seems fine already. For the int i I tried, hash(i) == hash(float(i)) == hash(Decimal(i)) == hash(Fraction(i)) == i. It is fine for transitivity that all fractional decimals are unequal to all fractional floats (and all fractions) since there is no integer (or fraction) that either is equal to, let alone both. This is what I would choose unless there is some 'hidden' problem. But it seem to me this should work: when a float and decimal are both integral (easy to determine) convert either to an int and use the current int-whichever comparison. > (2) I wonder whether there's a way to make Decimals > and floats incomparable, so that an (in)equality check > between them always raises an exception, and any > attempt to have both Decimals and floats in the same > set (or as keys in the same dict) also gives an error. > (Decimals and integers should still be allowed to > mix happily, of course.) But I can't see how this could > be done without adversely affecting set performance. I pretty strongly believe that equality checks should always work (at least in Python as delivered) just as boolean checks should (and do). > Option (1) is certainly technically feasible, but I > don't like it much: it means adding a whole load > of code to the Decimal module that benefits few users > but slows down hash computations for everyone. > And then any new numeric type that wants to fit in > with Python's rules had better worry about hashing > equal to ints, floats, Fractions, complexes, *and* > Decimals... I believe (1A) would be much easier both to implement and for new numeric types. > > Option (2) appeals to me, but I can't see how to > implement it. > > So I guess that just leaves updating the docs. > Other thoughts? (3) Further isolate decimals by making decimals also unequal to all ints. Like (1A), this would easily fix transitivity breakage, but I would consider the result less desirable. My ranking: 1A > 3 > 0 > 2. I might put 1 between 1A and 3, but I am not sure. > Mark Terry Jan Reedy From logan.johnny11 at gmail.com Thu Sep 25 18:52:19 2008 From: logan.johnny11 at gmail.com (logan.johnny11 at gmail.com) Date: Thu, 25 Sep 2008 15:52:19 -0700 (PDT) Subject: Milenko Kindl bnvnvnvb Message-ID: <7f0bb73a-bbef-40cc-901c-22220cdf6a3b@a18g2000pra.googlegroups.com> NEW YORK - Financial markets grew more upbeat Thursday as political leaders said they struck an agreement in principle on a massive spending plan to revive the crippled financial system. The Dow Jones industrial average jumped about 200 points on optimism about the bailout, and demand for safe-haven assets remained high but eased slightly as some investors placed bets that a deal would help unclog credit markets. ADVERTISEMENT Stock market investors got a lift when key lawmakers said they would present the $700 billion plan to the Bush administration and hoped for a vote by both houses of Congress within days. Still, some resistance remained from House Republicans as the closing bell on Wall Street rang ahead of a meeting of congressional leaders at the White House. And after the close of trading, it was clear that plan could still face some obstacles. Stock futures weakened, signaling a lower open Friday, after Sen. Richard Shelby, the top Republican on the Banking Committee, left the White House meeting and said the announced deal "is, obviously, no agreement." Trading that has been difficult for more than a week is likely to remain so in the coming days. "The market's going to experience volatility as the terms become known," said Doug Roberts, chief investment strategist at Channel Capital Research. Treasury Secretary Henry Paulson and Federal Reserve Chairman Ben Bernanke urged lawmakers Tuesday and Wednesday to quickly sign off on the plan, which they said would help prop up the economy by removing billions of dollars in risky mortgage-related assets from financial firms' balance sheets. Fear of heavy losses on these assets has made banks hesitant to extend credit, which in turn threatens the overall economy by making it harder and more expensive for businesses and consumers to borrow money. President Bush highlighted what he sees as the urgency in a national address Wednesday night. Major elements are still being worked out, including how to phase in the mammoth cost of the package and whether the government will get an ownership stake in troubled companies. Alan Lancz, director at investment research group LanczGlobal, said stock market investors were encouraged that the rescue looked more likely than it had earlier in the week. He said the move could help unclog credit markets by allowing banks and investors to place values on assets tied to mortgages. "How do you establish a floor? Well, this is the bazooka. This is how you establish a floor," he said of the plan's goal of buying up the toxic debt. Still, some investors had their doubts. Demand eased but remained high for the 3-month Treasury bill, considered the safest short-term investment. Its yield rose to 0.72 percent from 0.49 percent late Wednesday. That means investors are still willing to earn the slimmest of returns in exchange for a safe place to put their money. The yield on the benchmark 10-year Treasury note, which moves opposite its price, rose to 3.84 percent from 3.81 late Wednesday. The Dow rose 196.89, or 1.82 percent, to 11,022.06. The gain helped erase some of the losses from heavy selling earlier in the week, though the blue chips still remain down by more than 360 points, or 3.2 percent. Broader stock indicators also rose Thursday. The Standard & Poor's 500 index advanced 23.31, or 1.97 percent, to 1,209.18 and the Nasdaq composite index rose 30.89, or 1.43 percent, to 2,186.57. Advancing issues outnumbered decliners by nearly 3 to 1 on the New York Stock Exchange, where consolidated volume came to 5.73 billion shares, compared with 4.66 billion traded Wednesday. Roberts noted that the market's back-and-forth moves of late might be unnerving for investors but ultimately can leave stocks with little to show for all the volatility. "Most of this is just oscillating around a straight line," he said, noting that last week's huge daily moves, which also included triple- digit moves in the Dow, left stocks largely unchanged for the week. The dollar was mixed against other major currencies Thursday, while gold prices fell. Light, sweet crude for November delivery rose $2.29 to settle at $108.02 a barrel on the New York Mercantile Exchange. Meanwhile, disappointing readings on employment, housing and demand for big-ticket manufactured goods, as well as a sobering forecast from General Electric Co., underscored the difficulties facing the economy. The Labor Department said the number of people seeking unemployment benefits increased by 32,000 to a seasonally adjusted 493,000 last week ? the highest level in seven years and well above analysts' expectations of 445,000. Hurricanes Ike and Gustav added about 50,000 new claims in Louisiana and Texas, the department said. The Commerce Department said sales of new homes fell sharply in August to the slowest pace in 17 years. The average sales price also fell by the largest amount on record. New homes sales dropped by 11.5 percent in August to a seasonally adjusted annual sales rate of 460,000 units, the slowest sales pace since January 1991. The department also said orders for expensive manufactured goods sank in August by the largest amount in seven months as demand for both airplanes and cars sank. Durable goods orders fell by 4.5 percent last month, far worse than the 1.6 percent decline that economists expected and the biggest drop since a 4.7 percent fall in January. GE lowered its forecast for third-quarter and full-year earnings, citing unprecedented weakness and volatility in the financial services markets. The stock, which had declined in the early going, finished up $1.09, or 4.4 percent, to $25.68 alongside the gains in the broader market. The Russell 2000 index of smaller companies rose 7.97, or 1.14 percent, to 705.74. Overseas, Japan's Nikkei stock average fell 0.90 percent. Britain's FTSE 100 rose 1.99 percent, Germany's DAX index added 1.99 percent, and France's CAC-40 jumped 2.73 percent. Milenko Kindl Banja Luka Banjaluka Bihac From bearophileHUGS at lycos.com Fri Sep 26 16:58:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 26 Sep 2008 13:58:03 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> <48c6380b$0$17080$426a34cc@news.free.fr> <mailman.741.1220976622.3487.python-list@python.org> <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> <mailman.1557.1222457112.3487.python-list@python.org> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> Message-ID: <33572504-ae97-4e8f-a1cf-c06b0522bf74@73g2000hsx.googlegroups.com> bearophile: > # searching > m, i = 0, 0 ... > i += 1 The name 'i' can be removed, sorry. Bye, bearophile From peter.georgeson at gmail.com Thu Sep 11 09:35:32 2008 From: peter.georgeson at gmail.com (Peter Georgeson) Date: Thu, 11 Sep 2008 06:35:32 -0700 (PDT) Subject: Python and Open Office References: <a9f39a410809101304j592cb7actc1f95882f8fe632c@mail.gmail.com> <mailman.826.1221077307.3487.python-list@python.org> <ga9cps$mnt$1@theodyn.ncf.ca> Message-ID: <056cba0b-6c6e-4066-951c-3e97266d93d4@r15g2000prd.googlegroups.com> On Sep 11, 7:04?am, "Colin J. Williams" <c... at ncf.ca> wrote: > Marco Bizzarri wrote: > > On Wed, Sep 10, 2008 at 10:04 PM, Greg Lindstrom <gslindst... at gmail.com> wrote: > >> Hello, > > >> I would like to create and manipulate Open Office documents using Python. ?I > >> have found then UNO Python page and odfpy modules which seem to be exactly > >> what I need. ?The odfpy manual is, to me, a confusing list of objects and > >> methods (it's an impressive list!), but does not have much in the way of how > >> to use them. ?For example, I can open a spreadsheet and create new pages > >> (there's a nice example near the back of the manual) but I can't figure out > >> how to open an existing spreadsheet and list the names of the individual > >> sheets ("tabs"). > > >> I have written an application that access Microsoft Excel and creates > >> reports for work, but would like to create an Open Source version using Open > >> Office and release it to the community (and maybe get a talk at PyCon :-). > > >> Is there someone here who can help me out, or is there an appropriate > >> mailing list for me to join? > > > Ciao, Greg. > > > you should check with the openoffice.org mailing list; I think what > > you are looking for is the api mailing list for openoffice; you could > > try to get the OpenOffice.org developers guide and the SDK, and check > > it (but it is not a little work) > > > Regards > > Marco > > >> Thanks > > >> --greg > > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > Greg, > > If you follow this up, I hope that you > will post info to c.l.p > and let us know whether the UNO > interface is Python 2.5 compatible. > > The last time I looked it was set for > 2.3 or 2.4. > > Colin W I've recently been working on interfacing with OpenOffice via UNO with Python. I can confirm that unfortunately, the PyUNO interface presently (OpenOffice 2.4) is built with Python 2.3... so to use the UNO interface from Python you have to write a separate script to run in the OpenOffice Python 2.3 environment. Apparently someone is working on rebuilding the PyUNO library for Python 2.5 but there's no timeframe for when that might be included with the OpenOffice distribution. You could try building PyUNO with Python 2.5 yourself, I'm sure I came across instructions somewhere on the OpenOffice developer website... I've not used odfpy so don't know how it compares in terms of degree of difficulty to UNO. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 08:14:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 14:14:53 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: <mailman.1358.1222081500.3487.python-list@python.org> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> Message-ID: <48d78c3c$0$6998$426a74cc@news.free.fr> Tim Rowe a ?crit : > 2008/9/22 Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid>: >> Steven D'Aprano a ?crit : >>> On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: >>> >>>> Steven D'Aprano a ?crit : >>>>> I have a class which is not intended to be instantiated. Instead of >>>>> using the class to creating an instance and then operate on it, I use >>>>> the class directly, with classmethods. Essentially, the class is used >>>>> as a function that keeps state from one call to the next. > > Sounds to me like a functor, aka a function object: > http://en.wikipedia.org/wiki/Function_object > Ok, then the simple solution is to implement a callable type (__call__ method), possibly with appropriate support for the descriptor protocol if it's meant to be usable as a method. From akineko at gmail.com Tue Sep 2 11:38:10 2008 From: akineko at gmail.com (akineko) Date: Tue, 2 Sep 2008 08:38:10 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> <mailman.346.1220316770.3487.python-list@python.org> <d574e882-8cbf-40d9-9827-11307c773581@x16g2000prn.googlegroups.com> <mailman.348.1220319291.3487.python-list@python.org> <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> <mailman.350.1220326130.3487.python-list@python.org> <e79199b2-627b-4fc1-8772-1a33d89b1380@x16g2000prn.googlegroups.com> <mailman.364.1220359583.3487.python-list@python.org> Message-ID: <82face7d-910c-4b48-8a30-c18e81fb68aa@a18g2000pra.googlegroups.com> On Sep 2, 5:46 am, "Guilherme Polo" <ggp... at gmail.com> wrote: > Did you even try creating a checkbutton with indicatoron=False ? You > could get surprised. I didn't. My perception of checkbutton was a button with a check. So, I tried as you suggested. Yes, you are right. It is almost what I wanted (sticky behaviour). By ignoring the ButtonRelease and Leave events, yes, it can perfectly meet my requirements. As checkbutton has deselect() method, this is a better approach, I have to admit. Thank you for showing me the correct way to implement. Aki- From roy at panix.com Tue Sep 23 22:47:35 2008 From: roy at panix.com (Roy Smith) Date: Tue, 23 Sep 2008 22:47:35 -0400 Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <ee44675b-04ad-48b3-8eed-629ebb10d616@z66g2000hsc.googlegroups.com> Message-ID: <roy-58D7A8.22473523092008@news.panix.com> "Aaron \"Castironpi\" Brady" <castironpi at gmail.com> wrote: > You're out of options. You have to express it somehow. How about: Assignith z the value of x if the value of b is such that it is true, else assignith it the value of y. Assignith z not the value of w, nor the value of v, lest you raise NameError upon thy stack trace. From george.sakkis at gmail.com Sun Sep 28 14:08:43 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 28 Sep 2008 11:08:43 -0700 (PDT) Subject: destructor not called References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> Message-ID: <3dec57f0-c829-4420-b36d-58e21c564053@k37g2000hsf.googlegroups.com> On Sep 28, 12:00?pm, Marcin201 <marcin... at gmail.com> wrote: > I have a class which uses a temporary directory for storing data. ?I > would like that directory to be removed when the class is no longer > used. ?I have tried removing the temporary directory from the class > destructor, however, it was never called. ?After I while I traced the > problem to the class having a reference to it's own function. ?Here is > a simplified model. > > test.py > class Foo: > ? ? def __init__(self): > ? ? ? ? print "Hello" > ? ? ? ? self.f = self.fxn > > ? ? def __del__(self): > ? ? ? ? print "Bye" > > ? ? def fxn(self): > ? ? ? ? print "function" > > a = Foo() > > running python test.py I get > Hello > > Is this an expected behavior or a bug in python? ?If this is expected > any suggestions for working around this. ?I would like to avoid having > to call the destructor explicitly. Others have already replied to your main question; in short you shouldn't rely on __del__ being called. Regardless, is there a (good) reason for having an instance reference to the method ? Without further information, that seems like a code smell. George From mr.spoon21 at gmail.com Tue Sep 16 12:48:42 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Tue, 16 Sep 2008 18:48:42 +0200 Subject: parse a midi file Message-ID: <8f67b6f80809160948v1c97867fmdf841080e6930b95@mail.gmail.com> Hi, I need to parse a midi file with Python. What I exactly need is the possibility to distinguish all notes in all channels in a midi file and put them in a list or something. I've found this: http://groups.google.com/group/alt.sources/msg/22467419ad4bf416 I'm not sure how it does work, but looking at the code I saw it can get input from the terminal, so I tried: python midi.py < mymidi.mid All it does is printing a lot of strange symbols. Do you know other easy way to parse a midi file in Python? Or how actually does this module work? Thanks, Carlo From kyosohma at gmail.com Fri Sep 12 12:07:50 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 12 Sep 2008 09:07:50 -0700 (PDT) Subject: Python a good choice for experimenting with Win32 API? References: <98qdnS2nk4rpEVfVnZ2dnUVZ_qHinZ2d@comcast.com> Message-ID: <f04f840f-435a-4d2d-b354-7e357a000370@a1g2000hsb.googlegroups.com> On Sep 12, 10:36?am, "Siegfried Heintze" <siegfr... at heintze.com> wrote: > I need to understand some User32.dll functions and I'm making an elaborate > GUI so I can easily experiment with different parameters. This is taking a > long time. I'm new to python and I'm thinking it would sure be nice to have > an interpreter I can type a few lines of code into and test things. > > (1) Would CPython be a good choice for this? How about iron python? How > about Jython (probably not). > (2) What about callbacks? Which pythons can handle callbacks? I read on msdn > that you cannot use managed code to call SetWindowsHook and supply a call > back (with two exceptions). I guess that means I cannot use iron python. > What about C-Python for playing with hooks? > (3) How easy it it define the C structs, enums and integer constants > necessary to call the windows API functions? > (4) Here is the code I'm struggling with presently (it is just not > cooperating: no errors just wrong results! I expect to be able give it a > scan code, get a virtual key code, change the arguments, give it the virtual > key code and get the original scan code back again). > > ? ? ? ? public const UInt32 MAPVK_VK_TO_VSC = 0, MAPVK_VSC_TO_VK = 1, > MAPVK_VK_TO_CHAR = 2, MAPVK_VSC_TO_VK_EX = 3, MAPVK_VK_TO_VSC_EX = 4; > ? ? ? ? public const UInt32 KLF_ACTIVATE = 1, KLF_SUBSTITUTE_OK = 2, > KLF_REORDER = 8, KLF_REPLACELANG = 0x10, KLF_NOTELLSHELL = 0x80, > KLF_SETFORPROCESS = 0x00100, KLF_SHIFTLOCK = 0x10000, KLF_RESET = > 0x40000000; > ? ? ? ? [DllImport("user32.dll")] ?static extern IntPtr > LoadKeyboardLayout(string pwszKLID, uint Flags); > ? ? ? ? [DllImport("user32.dll")] static extern bool > UnloadKeyboardLayout(IntPtr hkl); > ? ? ? ? [DllImport("user32.dll")] ? static extern uint MapVirtualKeyEx(uint > uCode, uint uMapType, IntPtr dwhkl); > ? ? ? ? private void Compute() > ? ? ? ? { > ? ? ? ? ? ? IntPtr hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE | > KLF_SUBSTITUTE_OK | KLF_REPLACELANG); > ? ? ? ? ? ? uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl); > ? ? ? ? ? ? UpdateOutput(); > ? ? ? ? } > Would it be easy to execute this in the CPython interpreter or am I better > off sticking with C#? > > Thanks! > Siegfried I use the Python interpreter all the time for heavy experimentation. While I use PyWin32, I haven't done what you are attempting. I would recommend re-posting to the PyWin32 group as the PyWin32 creators use that list much more: http://mail.python.org/mailman/listinfo/python-win32 And there's lots of other knowledgeable users there too. Good luck! Mike From deets at nospam.web.de Fri Sep 12 03:58:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Sep 2008 09:58:46 +0200 Subject: handling uncaught exceptions with pdb? In-Reply-To: <wihbpyt95o9.fsf@panix5.panix.com> References: <7xmyifpt68.fsf@ruckus.brouhaha.com> <wihbpyt95o9.fsf@panix5.panix.com> Message-ID: <6iulpmFi9t0U1@mid.uni-berlin.de> R. Bernstein schrieb: > Paul Rubin <http://phr.cx at NOSPAM.invalid> writes: > >> I think I've asked about this before, but is there a way to set up >> Python to handle uncaught exceptions with pdb? I know about setting >> sys.except_hook to something that calls pdb, but this is normally done >> at the outer level of a program, and by the time that hook gets >> called, the exception has already unwound the stack to the outermost >> level. My situation is I run a multi-hour or multi-day computation >> that eventually crashes due to some unexpected input and I'd like to >> break to the debugger at the innermost level, right when the exception >> is encountered, so I can fix the error with pdb commands and resume >> processing. > ... > > Why not use the traceback you get to show you where to change the code > around that point to add an exception handler there which calls the > debugger? Because he wants to fix the issue directly in-place, and then continue, instead of losing hours or even days of computation. However, it's not possible AFAIK. Diez From mensanator at aol.com Mon Sep 22 20:09:00 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 22 Sep 2008 17:09:00 -0700 (PDT) Subject: Python based barcode readers References: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> <b9114982-4dce-4a65-ad28-891ed79fa5d4@b2g2000prf.googlegroups.com> Message-ID: <3d42eb3a-44c4-4c9d-8956-a31cd046cb02@x41g2000hsb.googlegroups.com> On Sep 22, 5:59?pm, Robocop <btha... at physics.ucsd.edu> wrote: > I also forgot to mention that it need not be nearly as robust as > something like Jailhelper 2.0, I will not really need to compensate > for noise and irregular conditions. ?All of my barcodes will be > scanned in a predictable, and consistent environment (i.e. a scanner), > so all i need is some stupid little script that will read the an image > in and decode it. The readers I've seen do all the decoding internally. They hook up via a Y-cable to your keyboard and require absolutely NO code at all on the PC. Anywhere the PC accepts keyboard input, you can wave the wand instead. Don't see why you would want to try to decode it yourself. Trust me, it's a pain in the ass. Unless you have a raw LED reader. Are you making one? From stef.mientki at gmail.com Fri Sep 26 12:57:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 26 Sep 2008 18:57:15 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <pan.2008.09.26.07.28.03@REMOVE.THIS.cybersource.com.au> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> <Xns9B24589F2DBEOKB@199.45.49.11> <48DBB9C8.6090500@gmail.com> <gbh53f$dim$1@ger.gmane.org> <mailman.1518.1222386373.3487.python-list@python.org> <pan.2008.09.26.07.28.03@REMOVE.THIS.cybersource.com.au> Message-ID: <48DD146B.5030206@gmail.com> Steven D'Aprano wrote: > On Fri, 26 Sep 2008 01:46:15 +0200, Stef Mientki wrote: > > >> Secondly thoughtless copying of current behavior, doesn't bring any >> progress, >> and I think that's one of the reasons why we're still burdened by >> inventions done 20 years ago, >> e.g. "do you want to save your changes ?". >> > > I click No about 50% of the time, and Yes Of Course You Stupid Machine > the other 50% of the time. Until they have a computer capable of reading > my mind, I'm curious what alternative you'd suggest. > > > Sorry to hear that you waste half of your time, maybe it's time to find yourself another job ;-) cheers, Stef From afriere at yahoo.co.uk Tue Sep 30 23:01:53 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 30 Sep 2008 20:01:53 -0700 (PDT) Subject: Wait or not? References: <34809165-9c72-46b3-996c-4bd55451505d@e53g2000hsa.googlegroups.com> Message-ID: <07d18c2c-2a70-478a-b50e-5afaa85d058d@e17g2000hsg.googlegroups.com> On Oct 1, 9:20 am, Eric <efl... at gmail.com> wrote: > I've been wanting to learn Python for a while now but I can't decide > on whether to wait for Python 3's final release and learn it or just > go ahead and learn 2.x. Would it be hard to make the transition being > a noob? If you only want to learn why do you need to wait for py3.0's final release? Get the rc1 and start learning now. On the other hand if you want to write production code get 2.5 and start writing now, most of what you'll learn between now and the final release of 3.0 will not change. From nicola.musatti at gmail.com Tue Sep 2 08:02:07 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Tue, 2 Sep 2008 05:02:07 -0700 (PDT) Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> Message-ID: <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> On Sep 1, 9:23 am, Jeremy Banks <jer... at jeremybanks.ca> wrote: > Hi. I wondered if anyone knew the rationale behind the naming of the > Popen class in the subprocess module. Popen sounds like the a suitable > name for a function that created a subprocess, but the object itself is > a subprocess, not a "popen". It seems that it would be more accurate to > just name the class Subprocess, can anyone explain why this is not the > case? The Python class is a generalization of the standard Posix function of (almost) the same name: http://opengroup.org/onlinepubs/007908775/xsh/popen.html Cheers, Nicola Musatti From sjmachin at lexicon.net Sat Sep 6 17:38:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 14:38:28 -0700 (PDT) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <6de9141c-f350-4dfa-a36b-46e45344776a@q5g2000prf.googlegroups.com> On Sep 7, 7:04 am, Andreas Hofmann <asdfasdfasdfasdfa... at arcor.de> wrote: > Hello Folks! > > I've got a little problem here, which which really creeps me out at the > moment. > I've got some strings, which only contain numbers plus eventually one > character as si-postfix (k for kilo, m for mega, g for giga). I'm trying > to convert those strings to integers, with this function: > > def eliminate_postfix(value): > if type(value) is str: Don't use "is" unless you are really sure that "==" won't do the job. Better idiom: if isinstance(value, str): > value.upper() This causes your "mult is always 1" problem. You need: value = value.upper() Why? Because strings are immutable. String methods like upper return a new string, they don't change the existing string. > if value.endswith('K'): > mult = 1000 > elif value.endswith('M'): > mult = 1000000 > elif value.endswith('G'): > mult = 1000000000 > else: > mult = 1 > > if mult is 1: Lose "is". In fact, lose the whole "if" statement. See below. > value = string.atoi(value) Don't use deprecated functions from the string module. Use the built- in float function to convert from text. > else: > value = string.atoi(value[:-1]) * mult > return value Those last few statements look somewhat tortuous. Try this: else: # mult would be 1, but we don't need it return float(value) return float(value[:-1]) * mult HTH, John From akineko at gmail.com Mon Sep 1 23:44:03 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 20:44:03 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> <mailman.346.1220316770.3487.python-list@python.org> <d574e882-8cbf-40d9-9827-11307c773581@x16g2000prn.googlegroups.com> <mailman.348.1220319291.3487.python-list@python.org> <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> <mailman.350.1220326130.3487.python-list@python.org> Message-ID: <e79199b2-627b-4fc1-8772-1a33d89b1380@x16g2000prn.googlegroups.com> On Sep 1, 8:28 pm, "Guilherme Polo" <ggp... at gmail.com> wrote: > Can you clarify what is this "sticky" behavior ? Are you referring to > a toggle button ? If yes, then you might be after a simple > Checkbutton: > > checkbutton = Tkinter.Checkbutton(indicatoron=False, text='test') I wouldn't spend days to create a custom widget to mimick the Checkbutton ;-) I don't need to describe the detail but once the button was pressed for a bit while, a command is sent through communication. The button is left being ButtonDown ("sticky") until an acknowledgement is sent back through communication. This is a way to let the user know the action was acknowledged at another end. I think probably very few people needs such widget. Aki- From steve at holdenweb.com Mon Sep 29 07:29:06 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 07:29:06 -0400 Subject: how to make smtplib.SMTP('localhost') work on window xp In-Reply-To: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> References: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Message-ID: <gbqe64$f7c$1@ger.gmane.org> zxo102 wrote: > Hi, > I am trying to use python module smtplib to send my email out on > window xp (localhost). > > import smtplib > server = smtplib.SMTP('localhost') > > but I got the error information as follows: > > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > File "c:\python24\lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "c:\python24\lib\smtplib.py", line 311, in connect > (code, msg) = self.getreply() > File "c:\python24\lib\smtplib.py", line 355, in getreply > raise SMTPServerDisconnected("Connection unexpectedly closed") > SMTPServerDisconnected: Connection unexpectedly closed > > I am not sure what is wrong with it. Should I configure my window xp > somewhere to run smtplib.SMTP('localhost')? > > Thanks in advance. > Well your code certainly expects *something* to be listening on port 25 on localhost. It's fairly unusual to run an SMTP server on Windows XP, though not impossible. usually your email system is set up to use some external host as uts SMPT server: if you look in your mail client's configuration you will probably find out whihc host you should be using. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From casey.mcginty at gmail.com Mon Sep 15 16:43:07 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 15 Sep 2008 10:43:07 -1000 Subject: Getting Linux partition info programmatically In-Reply-To: <ae3f58470809151340t287ab3c4m32218f1668d07338@mail.gmail.com> References: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> <ae3f58470809151340t287ab3c4m32218f1668d07338@mail.gmail.com> Message-ID: <ae3f58470809151343i6f592b1ame0d276456f2ce6fb@mail.gmail.com> sorry, meant to say "abstraction" On Mon, Sep 15, 2008 at 10:40 AM, Casey McGinty <casey.mcginty at gmail.com>wrote: > You might want to take a look at HAL (hardware extraction layer) and DBUS. > > freedesktop.org - Software/hal<http://www.freedesktop.org/wiki/Software/hal> > HAL 0.5.10 Specification<http://people.freedesktop.org/%7Edavid/hal-spec/hal-spec.html> > Dbus Tutorial<http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#connecting-to-the-bus> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/ece2b2c7/attachment.html> From castironpi at gmail.com Sat Sep 20 22:51:10 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 19:51:10 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <48d54863$0$4666$426a74cc@news.free.fr> <00e5a962$0$20331$c3e8da3@news.astraweb.com> Message-ID: <431950dd-8239-486e-95a5-90b6075ff65f@m73g2000hsh.googlegroups.com> On Sep 20, 9:20?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Sat, 20 Sep 2008 19:01:42 +0200, Bruno Desthuilliers wrote: > > Once again, sorry > > if me missing your correct answer drives you paranoid :-) > > What do you mean by that? How many other people have been talking about > me? > > *wink* > > -- > Steven Why, no fewer than usual! *wink* From tjreedy at udel.edu Fri Sep 26 17:14:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 17:14:39 -0400 Subject: Classes and functions. In-Reply-To: <73045cca0809261323r4a74d09fkdad22396b0a88324@mail.gmail.com> References: <73045cca0809261323r4a74d09fkdad22396b0a88324@mail.gmail.com> Message-ID: <gbjjc0$e93$1@ger.gmane.org> aditya shukla wrote: > Hello folks , i am using the newick module > http://www.daimi.au.dk/~mailund/newick.html.I am just learning to use it > and i have a question about it. > > from newick.tree import parse_tree > from newick.tree import add_parent_links > from newick.tree import add_distance_from_root > > import sys > > t = parse_tree('((A:2,B:3):1,C:6);') > > print t > > deltas = add_distance_from_root(t) > > now when i do this i can get the output like this > > > (('A' : 2.0, 'B' : 3.0) : 1.0, 'C' : 6.0) > None > > This is the code of the add_distance_from_root(0 > > def add_distance_from_root(tree): > '''Extend all nodes with the distance (branch length) from the root''' > tree.distance_from_root = 0.0 # 'tree' is the root... > > class V(TreeVisitor): > def pre_visit_edge(self,src,b,l,dst): > if l is None: l = 0 > dst.distance_from_root = src.distance_from_root - l I am puzzled why this class is inside the function and why -1 instead of +1, but... > tree.dfs_traverse(V()) > > From here it is clear that the function does not return anything but i > wanna get the value of the distance from root.How can i get this? I presume each node gets an attribute 'distance_from_root', so read that attribute of whatever node. From dudeja.rajat at gmail.com Tue Sep 30 08:09:25 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 30 Sep 2008 13:09:25 +0100 Subject: Tix Combo box problem - remains in editable mode only In-Reply-To: <e0b6c39a0809300357h71349f8ep35df21258f5e05b6@mail.gmail.com> References: <e0b6c39a0809300357h71349f8ep35df21258f5e05b6@mail.gmail.com> Message-ID: <e0b6c39a0809300509t1806ab62x735197c5d88bf5b2@mail.gmail.com> On Tue, Sep 30, 2008 at 11:57 AM, <dudeja.rajat at gmail.com> wrote: > Hi > > I'm facing a problem with the tix combo box in a way that my combo box is > always in an editable mode after I have cleared subwidgets Entry and Listbox > from it. > > > My setup is like this : > > CheckButton1 : > > If this is unset, the combo box should get disabled, the entries in it > should get cleared ( entries are listbox and entry subwidgets) which in my > case they get cleared. > > When this check box is set again, the combo box should get enabled, with no > entries in listbox and entry subwidgets ( which are reallly cleared in my > case.) But the combox box having being enabled is in editable mode despite > of setting it to un-editable mode. > > > The code is as follows: > #Combo Box > self.cbAnalysisLibVersion = Tix.ComboBox(self.frame1, \ > dropdown = True, \ > > command=self.__cllbkAnalysisLibVer, \ > editable=0, \ > variable=verSelection, > options='listbox.height 8\ > listbox.width 25 \ > entry.width 30 \ > entry.anchor w \ > entry.padx 30', \ > history = False) > > > #Check Button box > self.chBtResultsComparison = Checkbutton(self.frame2, \ > text = "Results Comparison", > \ > variable = > varResultsComparison, \ > command = > self.__cllbkResultsComparison) > > def __cllbkResultsComparison(self, Event = None): > > subLB = self.cbAnalysisLibVersion.subwidget("listbox") > subEntry = self.cbAnalysisLibVersion.subwidget("entry") > > if varResultsComparison.get() != 1: > #Disable Tolerance Text Box > > self.txtTolerance.delete(1.0, END) > self.txtTolerance.config(state = DISABLED, \ > bg = "grey") > #Delete all entries (entry & subwidget's entries) > #in Reference Analysis Results Version Combo Box > #and disable this combo box. > > #First Delete the Listbox sub-widget entries > subLB.delete(0, END) > subLB.config(state = DISABLED) > > #Then delete Entry sub-widget entries > #subEntry = self.cbAnalysisLibVersion.subwidget("entry") > subEntry.config(state = NORMAL) > subEntry.delete(0, END) > subEntry.config(state = DISABLED) > > self.cbAnalysisLibVersion.config(state = DISABLED) > #Diable Result Comparison Button > self.btViewComparisonResults.config(state = DISABLED) > > else: > #Check box is ticked > #Enable the Tolerance text box > self.txtTolerance.config(state = NORMAL, \ > bg = "white") > #Enable the Reference Analysis Combo box > #self.cbAnalysisLibVersion.config(state = NORMAL, editable=0) > self.cbAnalysisLibVersion.configure(state = NORMAL, editable = 0) > subLB.config(state = NORMAL) > subEntry.config(state = NORMAL) > > self.btViewComparisonResults.config(state = NORMAL) > > > Please suggest what is that I am missing > > Regards, > Rajat > Any help guys? -- Regrads, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/81167fde/attachment.html> From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Sep 25 11:42:45 2008 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Thu, 25 Sep 2008 15:42:45 GMT Subject: How to get the filename in the right case ? References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> Message-ID: <Xns9B24589F2DBEOKB@199.45.49.11> Stef Mientki wrote: > >>> import Module1 > > d:\data_python_25\pylab_works\module1.py(3)<module>() > -> print "hello" > (Pdb) > >> Then we know if PDB is really the culprit. >> >> > So pdb is the problem. Yep, it does the same thing for me. >> Apart from that, is that really a problem that the filenames are >> all lower case? AFAIK Windows is case-insensitive regarding >> filenames anyway. So opening the file by just passing the filename >> should work seamless. >> > Yes windows is, > but Python is not. > My program should run on Windows and Linux (and maybe a few > others). By converting everything to lowercase, on Linux I can't > distinguishes between 2 files with the same name but a different > case (btw, giving 2 files the same name, only differing in case, > looks like a bad idea to me). Hmmm, but I don't understand what you're doing here. Are you somehow storing the filename that pdb outputs and you need to use it later on a potentially different OS? If the case is preserved in pdb on linux, then presumably running it on linux will be fine, right? It's only a problem if you somehow try to use a filename created by windows- pdb to open a file (the same file, somehow) on linux. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From theller at python.net Fri Sep 19 02:43:17 2008 From: theller at python.net (Thomas Heller) Date: Fri, 19 Sep 2008 08:43:17 +0200 Subject: Directshow in Python In-Reply-To: <9d55654a-49ed-4bce-beae-bdf915810ad1@o40g2000prn.googlegroups.com> References: <9d55654a-49ed-4bce-beae-bdf915810ad1@o40g2000prn.googlegroups.com> Message-ID: <6jh00cF39nu1U1@mid.individual.net> Sayanan Sivaraman schrieb: > Hey all, > > I'm trying to use DirectShow to display videos [I'm kind of new to > Python, from more of a C++ background on windows]. I found some > sample code online, but I am having trouble with calling the I > > import ctypes > from ctypes import * > from comtypes import client > from ctypes.wintypes import * > import sys > import time > > > filename = sys.argv[1] > > > qedit = client.GetModule('qedit.dll') # DexterLib > quartz= client.GetModule("quartz.dll") > > > CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}' > filter_graph = > client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph) > filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder) > filter_builder.RenderFile(filename, None) > > media_control = filter_graph.QueryInterface(quartz.IMediaControl) > media_control.Run() > > try: > # Look at IMediaEvent interface for EOS notification > while True: > time.sleep(1) > except KeyboardInterrupt: > pass > > # Need these because finalisers don't have enough context to clean up > after > # themselves when script exits. > del media_control > del filter_builder > del filter_graph > > This code works fine. What I would like to know, is how do I declare > filename in the Python program to be of type LPCWSTR, so that I don't > need to parse the command line in order to call the function > "RenderFile()"? If I understand your question correctly (I'm no sure): comtypes converts Python strings or unicode strings to the required LPCWSTR type itself. So, you can call filter_builder.RenderFile("c:\\windows\\clock.avi", None) or filter_builder.RenderFile(u"c:\\windows\\clock.avi", None) If you pass a string, comtypes converts it to unicode using the "mbcs" codec; this can be changed by setting ctypes.conversion_mode. Thomas From tiftof at gmail.com Tue Sep 30 12:17:30 2008 From: tiftof at gmail.com (Christophe) Date: Tue, 30 Sep 2008 09:17:30 -0700 (PDT) Subject: how to find out the version of a certain installed package Message-ID: <b83e6129-254d-4512-a3dc-180901a237b1@q35g2000hsg.googlegroups.com> Hi, In a projecet I'm making using pycrypto, I need to find out the current installed version of pycrypto. After looking around, I found out that "pkg_resources.requires("pycrypto") will give me a string containing the version number, but is this the only way to do it or are there other ways? thanks, Christophe From zasaconsulting at gmail.com Thu Sep 18 08:25:02 2008 From: zasaconsulting at gmail.com (Alexzive) Date: Thu, 18 Sep 2008 05:25:02 -0700 (PDT) Subject: improving a huge double-for cycle Message-ID: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Hello there :) , I am a python newbie and need to run following code for a task in an external simulation programm called "Abaqus" which makes use of python to access the mesh (ensamble of nodes with xy coordinates) of a certain geometrical model. [IN is the starting input containing the nodes to be check, there are some double nodes with the same x and y coordinates which need to be removed. SN is the output containing such double nodes] Code: Select all for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) Unfortunately my len(IN) is about 100.000 and the running time about 15h !!!! :( Any idea to improve it? I have already tried to group the "if statements" in a single one: Code: Select all if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and if IN[i].coordinates[1] == IN[j].coordinates[1]: but no improvements. Many thanks, Alex From gagsl-py2 at yahoo.com.ar Tue Sep 9 13:00:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 14:00:02 -0300 Subject: how to use execfile with input parameters References: <77BBE7D879F90E47886631DD9B2714CD04FF1DB1@KUDBEX01.kuds.kingston.ac.uk> Message-ID: <op.ug736cnsx6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 08 Sep 2008 08:08:33 -0300, Shi, Shaozhong <S.Shi at kingston.ac.uk> escribi?: > I have a Python script expecting 11 or 12 input parameters. How do I > use execfile to execute the Python script in my new Python script? How > do I pass in the input parameters? You might use the subprocess module to run the script with all its parameters. But probably you want to call a *function* in a module. -- Gabriel Genellina From tjansson60 at gmail.com Mon Sep 8 11:37:28 2008 From: tjansson60 at gmail.com (Thomas Jansson) Date: Mon, 8 Sep 2008 08:37:28 -0700 (PDT) Subject: Catching subprocess stdout stream Message-ID: <00b9dc86-e002-4e2c-a686-39d2dd1016b9@m3g2000hsc.googlegroups.com> Dear all I have tkinkter based frontend to a Fortran based program. I use subprocess to launch the fortran program as a child process and I wish to see the output of the fortran program as it is created in the console. The fortran program can take up to 20 minuttes to finish and at the moment the I will first see any output after the fortran program is done. How make my function write the output of the process as it comes? def runprogram(Icommand, Ijobfile, Ioutput): if os.name == "posix": os.system(pythonpath+"/bin/"+Icommand+"< "+Ijobfile+" | tee "+Ioutput) elif os.name == "nt": import subprocess ofile = open(Ioutput, 'w') p = subprocess.Popen([os.path.join(pythonpath, "bin", Icommand + '.exe')], stdin=open(Ijobfile, "rb"),bufsize=1024,shell=False, stdout=subprocess.PIPE) while p.poll() is None: #Check if child process has terminated. o = p.stdout.readline() ofile.writelines(o) print o, ofile.close Kind regards Thomas Jansson From steven at REMOVE.THIS.cybersource.com.au Fri Sep 19 04:13:05 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 19 Sep 2008 08:13:05 GMT Subject: Python newbie References: <gavjfd$mvd$1@registered.motzarella.org> Message-ID: <pan.2008.09.19.08.13.05@REMOVE.THIS.cybersource.com.au> On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote: > I am a Python newbie who decided to see what that Python fuss is all > about. Quite frankly, I am a bit perplexed. Naturally you will be perplexed if you assume that Python is just Perl with a more verbose syntax. It isn't. > After having had few months > of experience with Perl (started in 1994 with Perl v4, and doing it ever > since) , here is what perplexes me: > > perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' > > The equivalent in Python looks like this: Actually, no it doesn't. The equivalent looks more like this: $ python -c 'a=[1,2,3]; a=[2*x for x in a]; for x in a: print x' 2 4 6 Now, to go on with your questions: > 1) Why is the array "a" unchanged after undergoing a transformation with > map? Because it hasn't undergone a transformation at all. The list (not array) a remains unchanged, because map returns a new list. > 2) Why is it illegal to pass a built-in function "print" to map? Because print is not a function, it is a statement. However, in Python 3, that design wart has been corrected. > 3) Why is the array "a" unchanged after undergoing an explicit > transformation with the "for" loop? Because the list a hasn't undergone any such transformation. Rebinding a name is not an explicit transformation to the object that used to be bound to the name. And if that sentence is gobbledygook to you, that demonstrates that Python is not Perl and you shouldn't assume a one-to- one semantic relationship between syntactical elements. > 4) Is there an equivalent to \$a (Perl "reference") which would allow me > to decide when a variable is used by value and when by reference? Python is neither call-by-reference nor call-by-value, although you will have many people swear black and blue that it is one or the other. With respect to all of them, they are wrong. Python's calling model is "call by object". See here for more detail: http://effbot.org/zone/call-by-object.htm If you insist on a false dichotomy between call-by-reference and call-by- value, then you won't often go wrong if you think of Python: - being almost always call-by-reference, except for some odd corner cases which look almost, but not quite, like call-by-value; - being almost always call-by-value, but only if you think of the values as pointers. > How can I make sure that > for x in a: x=2*x > > actually changes the elements of the array "a"? By explicitly changing the elements of the list. Here's one very old- fashioned way of doing so: >>> a = [1,2,3] >>> for i in range(len(a)): ... a[i] = a[i]*2 ... >>> a [2, 4, 6] Here's a more Pythonic alternative: >>> a = [1,2,3] >>> a = [2*x for x in a] -- Steven From uzmanajmal at gmail.com Sat Sep 13 06:06:11 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Sat, 13 Sep 2008 10:06:11 +0000 Subject: XML RPC Problem.... In-Reply-To: <gafuhg$sh1$1@ger.gmane.org> References: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> <gaagp1$804$1@ger.gmane.org> <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> <gafuhg$sh1$1@ger.gmane.org> Message-ID: <a3158e8b0809130306m25dda070w73f0a3c25888e051@mail.gmail.com> Where exactly should i call ServerProxy? Following is the code from my client.py t = SecureTransport() t.set_authorization(ustring, text_ucert) server = xmlrpclib.Server('http://localhost:8000/',transport=t) print server.s() Note: Full code for client is here at http://privatepaste.com/b56oS1Xa7P and following is my server code import SimpleXMLRPCServer #server = ServerProxy("http://betty.userland.com") class AuthenticationFunctions: def s(self): print "something..." server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(AuthenticationFunctions()) server.serve_forever() On Sat, Sep 13, 2008 at 8:44 AM, Fredrik Lundh <fredrik at pythonware.com>wrote: > Usman Ajmal wrote: > > Please explain the arguments of send_request. What exactly are the >> connection, handler and request_body? It will be really helpful if you give >> an example of how do i call send_request >> > > you don't call send_request. you should pass the SecureTransport instance > as an argument to the ServerProxy, which will then use it to talk to the > server. see the "custom transport" example in the library reference that I > pointed you to. > > http://www.python.org/doc/lib/xmlrpc-client-example.html > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080913/0c684ae2/attachment.html> From bignose+hates-spam at benfinney.id.au Thu Sep 11 06:19:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 11 Sep 2008 20:19:06 +1000 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> <87k5djb6e2.fsf@benfinney.id.au> <pan.2008.09.11.09.10.00@REMOVE.THIS.cybersource.com.au> Message-ID: <873ak7asth.fsf@benfinney.id.au> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes: > Nor do I believe that by posting a news message I've automatically > consented to receive email messages. To imply that the one implies the > other is equivalent to arguing that because I've written a letter to the > editor of a newspaper, I therefore must accept private correspondence > from any person or corporation that has a subscription to that newspaper. The two are not equivalent in this important detail: to post a newsgroup message, you must give a 'From' field in the header (note: just like email messages, newsgroup messages have exactly one header, comprised of multiple fields). You can fake an address in that field, of course, but it's considered bad form to do so. (That doesn't stop it being extremely common.) What you can't do is claim that, without express permission, no-one may send you an individual message to that address. On the contrary, that is the express purpose of the From field in a newsgroup message: to allow individual contact to the sender of the message. In the case of a letter to the editor a newspaper, the protocol is different. The newspapers are expected, by convention, to state the name and, often, suburb (or other location) of the writer; i.e. not enough information to send an individual message to the person. You might wish that Usenet operated the same in this respect, but it doesn't, and you can't reasonably expect that it does. -- \ ?If you were going to shoot a mime, would you use a silencer?? | `\ ?Steven Wright | _o__) | Ben Finney From steve at holdenweb.com Fri Sep 12 12:34:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 12:34:10 -0400 Subject: Newbie Question:Please help In-Reply-To: <d28296ba0809082310w6cb8e11dk7eeadf7ddc9f1353@mail.gmail.com> References: <d28296ba0809082310w6cb8e11dk7eeadf7ddc9f1353@mail.gmail.com> Message-ID: <gae5n2$f68$1@ger.gmane.org> Karthik Krishnan wrote: > Hi, > > I am a newbie to python and I hope this is not a stupid question. I am > trying to run a main method from a Python command line using the command > shell using the command. > > python main_test.py > > I get the following error. > > > File "<stdin>", line 1 > python main_test.py > > Syntax Error: invalid syntax > > My main file main_test.py is given below. > > #!/usr/bin/env python > > """ Test method to run the main method. > > """ > > def main(): > print "Main method called."; > > > if __name__ = "__main__": > main() > Apart from the syntax error Rob pointed out (use of "=" instead of "==" as a comparison operator) the output you show makes it seem possible you are entering the command "python main_test.py" at the Python interpreter interactive prompt ">>>". That won't work, as you are supposed to enter Python statements and expressions there. "python" is an operating system command, so you want to enter "python main_test.py" in a command window (terminal window, shell window, call it what you will). I'm guessing (possibly incorrectly) that you are a Windows user, and got your interactive Python window by choosing "Python (command line)" from the Start | Programs menu. See the FAQ for further information, possibly http://www.python.org/doc/faq/windows/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From circularfunc at yahoo.se Tue Sep 16 11:13:48 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 08:13:48 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? Message-ID: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> >>> sys.path ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ \lib\\site-packages\\PIL'] >>> Now I have my personal programs in C:/Python25/Progs/ How do I add so that I can just do "import somefile" from anywhere in that directory in the interpreter and it can load files from other folders in that directory. From a at nospam.org Mon Sep 15 16:35:36 2008 From: a at nospam.org (Armin) Date: Mon, 15 Sep 2008 22:35:36 +0200 Subject: append on lists In-Reply-To: <mailman.1062.1221509879.3487.python-list@python.org> References: <gamffv$qms$1@online.de> <mailman.1062.1221509879.3487.python-list@python.org> Message-ID: <gamg4f$f54$1@online.de> Fredrik Lundh wrote: > Armin wrote: > >> just a dumb question. >> >> Let a = [1,2,3,4,5] >> >> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? > > yeah, that's a dumb question. > > </F> > yeah, that's a dumb answer. From clp at rebertia.com Fri Sep 26 22:17:38 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 26 Sep 2008 19:17:38 -0700 Subject: getting global variables from dictionary In-Reply-To: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> References: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> Message-ID: <47c890dc0809261917u565a547dy73bd77800c815ca2@mail.gmail.com> When you do "Variables()" in your code, you're making a new instance of that class that has no relation to any other instances. This is the cause of your problem. To just reference a class, use just "Variables". But that doesn't help in this case because var_dict is an instance variable, not a class variable. On Fri, Sep 26, 2008 at 7:01 PM, icarus <rsarpi at gmail.com> wrote: > global_vars.py has the global variables No it doesn't, it just defines a class. The class itself (but NOT its instances) is a module-level global. > set_var.py changes one of the values on the global variables (don't > close it or terminate) No, it just instanciates the Variables class and then manipulates the instance, which is then GC-ed because it's no longer referenced anywhere, even in set_var. > get_var.py retrieves the recently value changed (triggered right after > set_var.py above) No, it creates an entirely new instance of Variables and then fetches the value from that instance (which is still using the default value because this new instance has never been modified). > > Problem: get_var.py retrieves the old value, the built-in one but not > the recently changed value in set_var.py. > > What am I doing wrong? Try just making var_dict a module-level variable in global_vars.py and then manipulating that rather than this unnecessary mucking about with Variables(). Alternatively, make var_dict a *class* variable of Variables by removing it from __init__ and just putting 'var_dict = {"username": "original username"}' in the raw class body of Variables; And then remove the parentheses after Variables as I mentioned in the beginning. Regards, Chris > > ----global_vars.py--- > #!/usr/bin/python > > class Variables : > def __init__(self) : > self.var_dict = {"username": "original username"} > > > ---set_var.py --- > #!/usr/bin/python > > import time > import global_vars > > global_vars.Variables().var_dict["username"] = "new username" > time.sleep(10) #give enough time to trigger get_var.py > > > ---get_var.py --- > #!/usr/bin/python > import global_vars > print global_vars.Variables().var_dict.get("username") > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From bearophileHUGS at lycos.com Mon Sep 29 12:34:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 09:34:16 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> <48c6380b$0$17080$426a34cc@news.free.fr> <mailman.741.1220976622.3487.python-list@python.org> <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> <mailman.1557.1222457112.3487.python-list@python.org> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> <mailman.1665.1222668924.3487.python-list@python.org> <6304d804-57a1-458d-8ffe-b7a387dd0584@a1g2000hsb.googlegroups.com> <mailman.1680.1222703796.3487.python-list@python.org> Message-ID: <a5643918-0c29-4ce3-931b-46aecbe6bf6c@y21g2000hsf.googlegroups.com> Derek Martin: > code that implements non-obvious algorithms ought to explain what it's > doing in comments, I am sorry, you are right, of course. In my libs/code there are always docstrings and doctests/tests, and most times comments too, like you say. When I post code here I often strip away part of those things, mostly to reduce the length of my posts -.- I guess that I have to leave more of that meta- information... Bye, bearophile From ldo at geek-central.gen.new_zealand Thu Sep 25 18:22:46 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 10:22:46 +1200 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <gbh2vm$9j1$2@lust.ihug.co.nz> In message <48d4c11b$0$22877$426a74cc at news.free.fr>, candide wrote: > "... Python supports OOP and classes to an extent, but is not a full OOP > language." Python allows you to use OO-style constructs, but doesn't force you to have inheritance and subclasses if you don't want to. Duck typing is usually a much more flexible approach. From david at abbottdavid.com Fri Sep 5 14:23:10 2008 From: david at abbottdavid.com (David) Date: Fri, 05 Sep 2008 14:23:10 -0400 Subject: Make Games In-Reply-To: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> References: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> Message-ID: <48C1790E.4020603@abbottdavid.com> NightZombie wrote: > x-no-archive: yes > > I want to learn Python so I can make simple games. What are some good > books that'll help me do this? > -- > http://mail.python.org/mailman/listinfo/python-list > > > Good book you can get used; Python Programming for the Absolute Beginner http://books.google.com/books?id=DH3TcrHM8s4C -- Have Fun, David A. Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From paul at boddie.org.uk Thu Sep 18 06:20:02 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Sep 2008 03:20:02 -0700 (PDT) Subject: minimum install & pickling References: <fb304bca-abe9-48e6-8dba-6187e33e5a6d@a2g2000prm.googlegroups.com> <6f045535-555f-44b6-93a5-f5b338d3f318@d45g2000hsc.googlegroups.com> <69cf2202-e11b-4994-84ab-a41167ef2652@26g2000hsk.googlegroups.com> Message-ID: <d8e9b368-ee86-415e-b0e6-16958391dfdd@8g2000hse.googlegroups.com> On 17 Sep, 22:18, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 17, 4:43?am, Paul Boddie <p... at boddie.org.uk> wrote: > > >http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...) > > These solutions have at least the same bugs that the bare bones > solution in the corresponding framework has. ?Malicious code has fewer > options, but constructive code does too. ?If you're running foreign > code, what do you want it to do? ?What does it want to do? ?The more > options it needs, the more code you have to trust. As I noted, instead of just forbidding access to external resources, what you'd want to do is to control access instead. This idea is not exactly new: although Brett Cannon was working on a sandbox capability for CPython, the underlying concepts involving different privilege domains have been around since Safe-Tcl, if not longer. The advantage of using various operating system features, potentially together with tools like fakechroot or, I believe, Plash, is that they should work for non-Python programs. Certainly, the chances of successfully introducing people to such capabilities are increased if you don't have to persuade the CPython core developers to incorporate your changes into their code. > The only way a Python script can return a value is with sys.exit, and > only an integer at that. ?It is going to have output; maybe there's a > way to place a maximum limit on its consumption. ?It's going to have > input, so that the output is relative to something. ?You just make > copies to prevent it from destroying data. ?Maybe command-line > parameters are enough. ?IIRC if I recall correctly, Win32 has a way to > examine how much time a process has owned so far, and a way to > terminate it, which could be in Python's future. There is support for imposing limits on processes in the Python standard library: http://docs.python.org/lib/node521.html My experimental package, jailtools, relies on each process's sandbox being set up explicitly before the process is run, so you'd definitely want to copy data into the sandbox. Setting limits on the amount of data produced would probably require support from the operating system. Generally, when looking into these kinds of systems, most of the solutions ultimately come from the operating system: process control, resource utilisation, access control, and so on. (This is the amusing thing about Java: that Sun attempted to reproduce lots of things that a decent operating system would provide *and* insist on their use when deploying Java code in a controlled server environment, despite actually having a decent operating system to offer already.) > PyPy sandbox says: ?"The C code generated by PyPy is not > segfaultable." ?I find that to be a bold claim (whether it's true or > not). > > I'm imagining in the general case, you want the foreign code to make > changes to objects in your particular context, such as exec x in > vars. ?In that case, x can still be productive without any libraries, > just less productive. Defining an interface between trusted and untrusted code can be awkward. When I looked into this kind of thing for my undergraduate project, I ended up using something similar to CORBA, and my conclusion was that trusted code would need to expose an interface that untrusted "agents" would rely on to request operations outside the sandbox. That seems restrictive, but as the situation with rexec has shown, if you expose a broad interface to untrusted programs, it becomes increasingly difficult to verify whether or not the solution is actually secure. Paul From jepe_abrantes at hotmail.com Tue Sep 9 09:36:07 2008 From: jepe_abrantes at hotmail.com (=?iso-8859-1?Q?Jo=E3o_Abrantes?=) Date: Tue, 9 Sep 2008 13:36:07 +0000 Subject: Orientation on MySql using python Message-ID: <BLU115-W2141F5289856E2EFF4D1BB96540@phx.gbl> Hello everyone, I want to make a program in python that uses Mysql aswell.. I don't know anything about mysql can you tell me some good books/tutorials where I can read something about mysql using python? Thanks. _________________________________________________________________ Invite your mail contacts to join your friends list with Windows Live Spaces. It's easy! http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mkt=en-us -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080909/35390469/attachment.html> From nick at craig-wood.com Mon Sep 15 06:36:59 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 15 Sep 2008 05:36:59 -0500 Subject: Wrong application name in menubar of OS X References: <1af662ce-5454-436c-8b65-c713993cf6bc@s9g2000prg.googlegroups.com> Message-ID: <slrngcsck0.7ga.nick@irishsea.home.craig-wood.com> erikcw <erikwickstrom at gmail.com> wrote: > The menubar of OS X is showing the application name as Python instead > of the name of my wxpython gui app. How do I make my application name > show-up in the menu bar? The answer I got from the wxpython mac list recently was to package my app with py2app first. I tried this and it does work. So your app will be called "Python" during development, but once you have packaged it it will get the correct name. -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From gagsl-py2 at yahoo.com.ar Wed Sep 10 03:28:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Sep 2008 04:28:53 -0300 Subject: Clearing a session and reload() problem (with repro error) References: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> <mailman.740.1220976221.3487.python-list@python.org> <067abd3f-0d02-46e8-8d26-d85f20fa2e3a@s9g2000prg.googlegroups.com> Message-ID: <op.ug88efpix6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 10 Sep 2008 00:56:43 -0300, Rafe <rafesacks at gmail.com> escribi?: > On Sep 9, 11:03 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > wrote: >> En Mon, 08 Sep 2008 05:37:24 -0300,Rafe<rafesa... at gmail.com> escribi?: >> ... >> This dependency between modules, applied to all modules in your project, >> defines a "dependency graph". In some cases, one can define a partial >> ordering of its nodes, such that no module depends on any other module >> *after* it (it may depend only on modules *before* it). Look for >> "topological sort". >> >> Doing that in the generic case is not easy. If you *know* your >> dependencies, reload the modules in the right order by hand. >> ... > I was hoping there would be a way to just wipe out the module cache > and let it get rebuilt by executing my code (since I'm not using > reload as part of my program, but rather, to test it in an environment > where I cannot restart the Python session). Ok, I think the following sequence *might* work: - replace the __import__ and reload builtins with a custom callable object. This way you can hook into any import attempt. The object should keep a list of already reloaded modules. When a module is imported: if it is already in the list, just delegate to the original __import__; if it is not in the list, locate the module in sys.modules and reload it. - iterate over sys.modules and reload the desired modules, as you did in your previous attempt. - restore the original __import__ function. This way, you effectively transform any import statement into a recursive reload (for the first time); subsequent imports of the same module behave as usual. This may work for you, or perhaps not, or it may screw all your running environment up, or even cause the next global thermonuclear war... (I hope not!) Note: some modules don't work well with reload(). A common case: global mutable values, like a list of objects which starts empty: my_list = [] To make it more "reload friendly", use this: try: my_list except NameError: my_list = [] (this way the list will keep its previous values). The example below shows how to hook into the import mechanism - it just prints the module being imported. Implementing the functionality outlined above is left as an exercise to the reader :) py> class ImportHook(object): ... _orig_import = None ... # ... def __call__(self, name, globals={}, locals={}, fromlist=[], level=-1): ... if fromlist: ... print "-> from %s import %s" % (name, ','.join(fromlist)) ... else: ... print "-> import %s" % name ... return self._orig_import(name, globals, locals, fromlist, level) ... # ... def hook(self): ... import __builtin__ ... self._orig_import = __builtin__.__import__ ... __builtin__.__import__ = self ... # ... def unhook(self): ... assert self._orig_import is not None, "unhook called with no previous hook" ... import __builtin__ ... __builtin__.__import__ = self._orig_import ... del self._orig_import ... # ... # support the "with" statement ... def __enter__(self): ... self.hook() ... return self ... # ... def __exit__(self, type, value, tb): ... self.unhook() ... py> py> ih = ImportHook() py> ih.hook() py> import htmllib -> import htmllib -> import sgmllib -> import markupbase -> import re -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import re -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> from formatter import AS_IS -> import sys -> from htmlentitydefs import entitydefs py> reload(htmllib) -> import sgmllib -> from formatter import AS_IS -> from htmlentitydefs import entitydefs <module 'htmllib' from 'C:\apps\Python25\lib\htmllib.pyc'> py> ih.unhook() -> import __builtin__ py> import htmllib py> > I have been keeping a diagram of my module inheritance to make sure it > is as clean as possible, so I could just right a list of reloads as > you suggest. However, one of the sub-packages is designed to allow > users to add more modules. Because these get dynamically imported, a > guess I could add an argument to the reload function to allow a user > to give the 'add-on' module they are working on... so much work just > to get a clean environment... > > Separate of my program, I was really hoping to write a generic reload > tool for anyone developing in the same application as I am. I just > don't see a way to trace import dependencies in systems which include > dynamic imports. Any ideas? You may adapt the example above. Good luck! -- Gabriel Genellina From m_palmer45 at yahoo.ca Fri Sep 26 15:54:47 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 26 Sep 2008 12:54:47 -0700 (PDT) Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> <gbfvei$cqe$1@foggy.unx.sas.com> Message-ID: <208644f2-5162-430f-994e-15efeac1a979@p25g2000hsf.googlegroups.com> On Sep 25, 8:16 am, "Tim Arnold" <tim.arn... at sas.com> wrote: > "Tim Arnold" <a_j... at bellsouth.net> wrote in message > > news:57cdd3f1-cde8-45f5-b9d9-3eef32010bda at l43g2000hsh.googlegroups.com... > > >I have a bunch of processes to run and each one needs its own working > > directory. I'd also like to know when all of the processes are > > finished. > > Thanks for the ideas everyone--I now have some news tools in the toolbox. > The task is to use pdflatex to compile a bunch of (>100) chapters and know > when the book is complete (i.e. the book pdf is done and the separate > chapter pdfs are finished. I have to wait for that before I start some > postprocessing and reporting chores. > > My original scheme was to use a class to manage the builds with threads, > calling pdflatex within each thread. Since pdflatex really does need to be > in the directory with the source, I had a problem. > > I'm reading now about python's multiprocessing capabilty, but I think I can > use Karthik's suggestion to call pdflatex in subprocess with the cwd set. > That seems like the simple solution at this point, but I'm going to give > Cameron's pipes suggestion a go as well. > > In any case, it's clear I need to rethink the problem. Thanks to everyone > for helping me get past my brain-lock. > > --Tim Arnold I still don't see why this should be done concurrently? Do you have > 100 processors available? I also happen to be writing a book in Latex these days. I have one master document and pull in all chapters using \include, and pdflatex is only ever run on the master document. For a quick preview of the chapter I'm currently working on, I just use \includeonly - compiles in no time at all. How do you manage to get consistent page numbers and cross-referencing if you process all chapters separately, and even in _parallel_ ? That just doesn't look right to me. From sebastianthegreatful at gmail.com Wed Sep 17 13:33:19 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Wed, 17 Sep 2008 10:33:19 -0700 (PDT) Subject: ssl server Message-ID: <eef6d1fa-12e6-4549-a85e-c0ba21b19c63@25g2000hsx.googlegroups.com> I'm making a ssl server, but I'm not sure how I can verify the clients. What do I actually need to place in _verify to actually verify that the client cert is signed by me? 50 class SSLTCPServer(TCPServer): 51 keyFile = "sslcert/server.key" 52 certFile = "sslcert/server.crt" 53 def __init__(self, server_address, RequestHandlerClass): 54 ctx = SSL.Context(SSL.SSLv23_METHOD) 55 ctx.use_privatekey_file(self.keyFile) 56 ctx.use_certificate_file(self.certFile) 57 ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, self._verify) 58 ctx.set_verify_depth(10) 59 ctx.set_session_id('DFS') 60 61 self.server_address = server_address 62 self.RequestHandlerClass = RequestHandlerClass 63 self.socket = socket.socket(self.address_family, self.socket_type) 64 self.socket = SSL.Connection(ctx, self.socket) 65 self.socket.bind(self.server_address) 66 self.socket.listen(self.request_queue_size) 67 68 def _verify(self, conn, cert, errno, depth, retcode): 69 return not cert.has_expired() and cert.get_issuer().organizationName == 'DFS' From stef.mientki at gmail.com Sun Sep 28 18:25:30 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 29 Sep 2008 00:25:30 +0200 Subject: rlcompleter and wxPython, problems ... Message-ID: <48E0045A.3020402@gmail.com> hello, I'm trying to implement autocompletion into my editor. But I find some weird behavior, or at least I don't have the faintest idea why this behavior occures, and even more important how to solve it In the example below I try to autocomplete " wx.s" , which in my humble opinion should at least produce "wx.stc" (and some others ). The completion is done in a procedure, so the "locals" is quite clean. Before calling the completer, I import the left part of my string to be completed. The program below gives indeed "wx.stc" as an option, but if I leave the second line out, marker "<<<===" , I get no results. Can someone explain this behavior and maybe even have a solution ? thanks, Stef Mientki import rlcompleter import wx.stc # <<<=== # *********************************************************************** # *********************************************************************** def _get_completions ( word ) : left_part = None right_part = word if word.find('.') >= 0 : word_parts = word.split('.') left_part = '.'.join ( word_parts [ : -1 ] ) right_part = word_parts [ -1 ] try : exec ( 'import ' + left_part ) except : return None Completer = rlcompleter.Completer ( locals () ) State = 0 Next = Completer.complete ( word, State ) result = [] while Next : result.append ( Next ) State += 1 Next = Completer.complete ( word, State ) result = ' '.join ( result ) return result # *********************************************************************** # *********************************************************************** # *********************************************************************** if __name__ == "__main__": word = 'wx.s' completions = _get_completions ( word ) print completions # ******************************************************* From luke.hamilton at xenter.com.au Wed Sep 10 09:54:00 2008 From: luke.hamilton at xenter.com.au (Luke Hamilton) Date: Wed, 10 Sep 2008 23:54:00 +1000 Subject: Web shopping carts In-Reply-To: <48C7CE5A.7030904@wildenhain.de> Message-ID: <C4EE0E98.1137D%luke.hamilton@xenter.com.au> > From: Tino Wildenhain <tino at wildenhain.de> > Date: Wed, 10 Sep 2008 08:40:42 -0500 > To: Luke Hamilton <luke.hamilton at xenter.com.au> > Cc: "python-list at python.org" <python-list at python.org> > Subject: Re: Web shopping carts > > Hi, > > Luke Hamilton wrote: >> Thanks... >> >> Do you happen to have anymore details? > > Yes well... you guess it was supposed to be a funny comment > but would you happen to have anymore details on your > requirements as well? Your simple question was just > asking for making fun of it. > It was actually meant to be a pretty general question. I was really trying to get a feel for what was out there, so I can then to start to have a look at there capabilities. > (Other than that please see the answer given by Fredrik) > And unfortunately Google hasn't been much help... > > Ah, btw, I'd check the the other posts of long term members > if you see something in the appearance different to > yours :-) (not related to your question itself) > > Cheers > Tino > > ... >>> Luke Hamilton wrote: >>>> Hey People, >>>> >>>> I am wondering if there are any OS shopping cart application written in >>>> python? >>>> >>> Yes there are. >>> >>> HTH >>> Tino >> >> > From fredrik at pythonware.com Mon Sep 15 14:52:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 20:52:41 +0200 Subject: environment variable issue In-Reply-To: <48ceacb9$0$2863$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <gamatt$357$1@ger.gmane.org> Michel Leunen wrote: > Could someone explain me what I'm doing wrong here? I'm trying to > retrieve the value of an environment variable in Ubuntu 8.04 like this: > > >>> import os > >>> os.environ['USER'] > 'michel' > > This works but this doesn't: > > >>> os.environ['HOSTNAME'] > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'HOSTNAME' > > Why is it working in the first case but not in the second one. I must be > missing something but it seems I'm not able to figure it out. this might help: http://mail.python.org/pipermail/python-list/2008-September/507933.html (scanning the subjects of recent and ongoing threads before posting is always a good idea). </F> From max at alcyone.com Tue Sep 9 01:14:59 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Sep 2008 22:14:59 -0700 Subject: Correcting for Drift between Two Dates In-Reply-To: <pgnxk.9513$cn7.668@flpi145.ffdc.sbc.com> References: <pgnxk.9513$cn7.668@flpi145.ffdc.sbc.com> Message-ID: <zoidnYi476rJm1vVnZ2dnUVZ_vOdnZ2d@speakeasy.net> W. eWatson wrote: > drift = 4.23 # seconds per day > > format = '%Y%m%d_%H%M%S' > ts1 = "20080901_120000" # base date-time > ts2 = "20080904_180000" > d1 = datetime(*(time.strptime(ts1, format)[0:6])) > d2 = datetime(*(time.strptime(ts2, format)[0:6])) > #d += timedelta(seconds=sec) > delta = d2-d1 > # delta format is nnn[n] days, hh:mm:ss > # delta is type 'datetime.timedelta' > print delta > # get back to ts2 as a check > d3 = d1+d > print d3 You're going to have to start with code that actually runs first. You've iterated on this so many times that it's not at all clear what it is you're trying to do and why it isn't doing what you think it should. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis It's better to be quotable than to be honest. -- Tom Stoppard From aioe.org at technicalbloke.com Sat Sep 27 01:58:15 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 27 Sep 2008 01:58:15 -0400 Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: <gbki1m$eh1$3@aioe.org> process wrote: > ' '.join([`x * x` for x in range(1, 6)]) > > exactly what does this symbol do and what does it stand for? Ah, just spotted the backticks - they just return whatever's inside them as a string. From celephicus at gmail.com Mon Sep 1 11:28:31 2008 From: celephicus at gmail.com (Tom Harris) Date: Tue, 2 Sep 2008 01:28:31 +1000 Subject: Buffer objects Message-ID: <aa19747c0809010828s3df678bdpe9afb617d39525f6@mail.gmail.com> Greetings, I need a little help with buffer objects. Many Python objects export the buffer interface, or can be persuaded to create a buffer object with a buffer() call. First question, the buffer() function appears very quick. Does it just wrap the internal pointer and then exit? Second question, the buffer interface does include support for multiple segments of memory. All the buffers I have examined are only a single segment, is this a rarely used functionality? Third question, having got my buffer interface I want to get the actual pointer out so that I can call foreign functions with ctypes with the pointer as a function argument and add offsets to it, so I would like it as a plain int. What is the recommended method of accessing the raw pointer from the buffer object? It must be me but I have found the whole buffer thing difficult to understand from the docs, it appears only useful to C coders, but I use the buffer interface (GetData()) of wx.Image objects a lot in my work. TomH celephicus(AT)gmail(DOT)com From stefan_ml at behnel.de Sat Sep 13 15:09:23 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 13 Sep 2008 21:09:23 +0200 Subject: lxml build error in sun In-Reply-To: <b64b6178-db7f-4bac-a4c7-a104e1031401@k13g2000hse.googlegroups.com> References: <b64b6178-db7f-4bac-a4c7-a104e1031401@k13g2000hse.googlegroups.com> Message-ID: <48cc0fe3$0$6560$9b4e6d93@newsspool4.arcor-online.net> Owen Zhang wrote: > I am trying to build lxml package in SunOS 5.10. I got the following > errors. Could you report this on the lxml mailing list? Stefan From nevillednz at gmail.com Mon Sep 1 00:00:17 2008 From: nevillednz at gmail.com (Neville Dempsey) Date: Mon, 1 Sep 2008 14:00:17 +1000 Subject: enhancing/wrapping an existing instance of a duck Message-ID: <b2ff67060808312100i557515faw11cc239f33df3fb2@mail.gmail.com> Basically I have an existing (maybe a rather large and complicated (existing) instance) that I want to add new member to. Cheers N Hacks/attempts follow: from math import sqrt ############ try2 ############ duck_obj = [ i*i for i in range(25) ] # OR a large sparse matrix # I "want" to an a useful property, eg length, and retain the ducks existing properties. # I COULD try... setattr(duck_obj,"length",lambda: sqrt(sum(*duck_obj))) print duck_obj.length() # returns 70 duck_obj[0]=70+71 print duck_obj.length() # returns 71 ############ try2 ############ # **BUT** I'd rather encapsulate a the original instance somehow. # I presume that I could define a class to do this somehow? duck_obj = [ i*i for i in range(25) ] # OR a LargeSparseMatrix() dec = Vec(duck_obj) ??? print dec.length() # returns 70 duck_obj[0]=70+71 # original "large and complicated duck instance" print dec.length() # returns 71 Any hints on how I need to define Vec so that any kind of duck_obj can be decorated/wrapped/encapsulated. From stef.mientki at gmail.com Thu Sep 25 06:36:12 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 12:36:12 +0200 Subject: How to get the filename in the right case ? Message-ID: <48DB699C.6060801@gmail.com> hello, How can I find the correct case of a filename ? Background in my program I use case sensitive filenames, just like Python requires. Now I've integrated pdb into the program, but pdb acts somwhat strange: upon a breakpoint it gives the filename always in lowercase (probably this only happens on windows). So is there a way to get the correct case of a given filename in lowercase ? One solution might be to make the comparison in my program always with lowercase, but then I'm sure the program won't work on non-windows systems. btw, why does pdb behave that way ( Python 2.5 ) ? thanks, Stef Mientki From castironpi at gmail.com Thu Sep 25 13:52:43 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 25 Sep 2008 10:52:43 -0700 (PDT) Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> <48db50aa$0$3750$426a74cc@news.free.fr> <HoOCk.1756$Pv5.1315@edtnps83> <48dbc82e$0$1120$426a74cc@news.free.fr> Message-ID: <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> On Sep 25, 12:19?pm, Bruno Desthuilliers <bruno. 42.desthuilli... at websiteburo.invalid> wrote: > Dmitry S. Makovey a ?crit : > > > > > Thanks Bruno, > > > your comments were really helpful (so was the "improved" version of code). > > > My replies below: > > > Bruno Desthuilliers wrote: > >>> So decorators inside of B just identify that those methods will be > >>> proxied by A. On one hand from logical standpoint it's kind of weird to > >>> tell class that it is going to be proxied by another class, > > >> Indeed - usually, proxied objects shouldn't have to be aware of the > >> fact. That doesn't mean your variation on the proxy pattern is > >> necessarily bad design (hard to tell without lot of context anyway...), > >> but still there's some alarm bell ringing here IMHO - IOW : possibly the > >> right thing to do, but needs to be double-checked. > > > I'm kind of looking at options and not dead-set on decorators, but I can't > > find any other "elegant enough" solution which wouldn't lead to such tight > > coupling. The problem I'm trying to solve is not much more complicated than > > what I have already described > > Well... You didn't mention why you need a proxy to start with !-) > > > so if anybody can suggest a better approach - > > I'm all for it. > > (snip code) > > > > >> My point is that: > >> 1/ you shouldn't have to rewrite a decorator function - with basically > >> the same code - for each possible proxy class / attribute name pair combo > >> 2/ making the decorator an attribute of the proxy class makes > >> dependencies clearer (well, IMHO at least). > > > agreed on all points > > >> I'm still a bit uneasy wrt/ high coupling between A and B, and if I was > >> to end up with such a design, I'd probably take some times to be sure > >> it's really ok. > > > that is the question that troubles me at this point - thus my original post > > (read the subject line ;) ). ?I like the clarity decorators bring to the > > code and the fact that it's a solution pretty much "out-of-the-box" without > > need to create something really-really custom, but I'm worried about tight > > coupling and somewhat backward logic that they would introduce (the way I > > envisioned them). > > Well... The canonical solution for delegation in Python is using > __getattr__. Your problem - according to this post and your answer to > Diez - is that your proxy may have to > 1/ delegate to more than one object > 2/ don't necessarily delegate each and any attribute access > > I can envision one solution using both __getattr__ and a simple decorator: > > def proxy(func): > ? ? func._proxied = True > ? ? return func > > class A(object): > ? ? ?def __init__(self, delegates): > ? ? ? ? ?self._delegates = delegates > ? ? ?def __getattr__(self, name): > ? ? ? ? ?for d in self.__delegate: > ? ? ? ? ? ? ?func = getattr(d, name) > ? ? ? ? ? ? ?if callable(func) and getattr(func, '_proxied', False): > ? ? ? ? ? ? ? ? ?return func > ? ? ? ? ?raise AttributeError( > ? ? ? ? ? ? ? ?'object %s has no attribute '%s' % (self.__class__, name) > ? ? ? ? ? ? ? ?) > > class B(object): > ? ? ?def __init__(self): > ? ? ? ? ?self.val='bval' > > ? ? ?@proxy > ? ? ?def bmethod(self,a): > ? ? ? ? ?print "B::bmethod" > ? ? ? ? ?print a, self.val > > ? ? ?@proxy > ? ? ?def bmethod2(self,a): > ? ? ? ? ?print "B::bmethod2" > ? ? ? ? ?print a, self.val > > class C(object): > ? ? ?def __init__(self): > ? ? ? ? ?self.val='bval' > > ? ? ?@proxy > ? ? ?def cmethod(self,a): > ? ? ? ? ?print "B::bmethod" > ? ? ? ? ?print a, self.val > > ? ? ?@proxy > ? ? ?def cmethod2(self,a): > ? ? ? ? ?print "B::bmethod2" > ? ? ? ? ?print a, self.val > > a = A([B(), C()]) > > # not tested... > > This solves most of the coupling problems (B and C still have to make > clear which methods are to be proxied, but at least they need not know > which class will be used as proxy), and makes sure only 'allowed' method > calls are delegated. But I wouldn't call it a perfect solution neither. > If you do have more than one object having method xxx, only the first > one will match... And let's not talk about the lookup penalty. > > There's a possible variant that avoids the call to __getattr__ (in > short: attaching delegation instancemethods to A instance in the > initializer for each proxied method in delegates), but that wont solve > the problem of potential name clashes. > > My 2 cents... You should write it like this: class B(object): @A.proxy def bmethod(self,a): Making 'proxy' a class method on A. In case different A instances (do you have more than one BTW?) proxy different objects, you could make it a plain old method. a= A() class B(object): @a.proxy def bmethod(self,a): I recommend this solution so that if you add a method to a B instance later, 'a' can be notified simply.: b.meth3= a.proxy( meth3 ) The big problem with that is if 'a' has 'b' in its constructor. You can reverse that, since B 'knows' about it proxy object quite a bit anyway. What you've said implies that you only have one B instance, or only one per A instance. Is this correct? I agree that __setattr__ is the canonical solution to proxy, but you have stated that you want each proxied method to be a member in the proxy class. From mbrkic at invalid_mail.adress Wed Sep 24 09:17:08 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Wed, 24 Sep 2008 15:17:08 +0200 Subject: Making small executive file for distribution Message-ID: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Not commercial distribution, but an academic kind of sorts - giving the exe file to coleagues, so they can use it in their work. Giving .py file is not an option, since due to centralized computer maintenance, they don't (and cannot) have installed python (except the ones that bring their own computer at work, but those are an exception). As far as I know py2exe is the only option which can do such a thing (make exe files from scripts). Is there a way to make those exe files a little smaller (for a small script they easily go up to 5-10 mb). Has anyone had a situation like this ? All your inputs and suggestions are more then welcomed. -- Marin From sayananbig at gmail.com Thu Sep 25 15:06:51 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Thu, 25 Sep 2008 12:06:51 -0700 (PDT) Subject: python timers and COM/directshow References: <ee4ce745-536d-48ca-84f9-1665bd416fc3@x16g2000prn.googlegroups.com> <mailman.1401.1222168999.3487.python-list@python.org> <5b01cc61-60bf-4a6c-b88b-932cf2fc8e0a@s20g2000prd.googlegroups.com> Message-ID: <c7c368ac-60dc-4589-935c-d0443fd79486@r15g2000prd.googlegroups.com> Ok, so I actually found a solution to this out there, and decided I'd post back here and share it. import pygtk pygtk.require('2.0') import gtk import ctypes from ctypes import * from comtypes import client from ctypes.wintypes import * import gobject def delete_event(widget,event,data=None): global filter_builder, filter_graph, media_control, vseek media_control.Stop vseek.Release filter_builder.Release GUIDATA.win1.Release media_control.Release filter_graph.Release del GUIDATA.win1 del filter_graph del vseek del filter_builder del media_control del all sys.exit([status]) os._exit(status) gtk.main_quit() exit() return False def pauser(widget,data=None): global media_control,playing, scrollbar, vseek if GUIDATA.data_loaded==0: return 0 scrollbar.set_value(vseek.CurrentPosition*30) media_control.Pause() playing=0 return 0 def player(widget,data=None): global media_control, vseek, scrollbar,playing if GUIDATA.data_loaded==0: return 0 media_control.Run() playing=1 gobject.timeout_add(1,on_timer,scrollbar) def scrollbar_callback(widget,scroll, data=None): global media_control, vseek vseek.CurrentPosition= scrollbar.get_value()/30 return 0 def on_timer(data=None): global scrollbar, vseek, playing, media_control if (playing==1)and (vseek.CurrentPosition*30)<int(frame2.get_text()) : g= vseek.CurrentPosition scrollbar.set_value(g*30) f= "%d" %(vseek.CurrentPosition*30) curframe.set_text(f) print "update" return True win = gtk.Window() win.connect("destroy", lambda x: gtk.main_quit()) win.set_default_size(500,800) win.set_title("LISA GUI") filename= LPCWSTR("mymovie.avi") #importing quartz.dll and qedit.dll for filtergraph construction qedit = client.GetModule('qedit.dll') # DexterLib quartz= client.GetModule('quartz.dll') CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}' filter_graph = client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph) filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder) media_control = filter_builder.QueryInterface(quartz.IMediaControl) GUIDATA.win1= filter_builder.QueryInterface(quartz.IVideoWindow) filter_builder.RenderFile(GUIDATA.video, None) GUIDATA.win1.SetWindowPosition(512, 0, 512, 400) vseek=filter_graph.QueryInterface(interface=quartz.IMediaPosition) adj= gtk.Adjustment(1,1,30*vseek.Duration+1,1,1.0,1.0) scrollbar = gtk.HScale(adj) scrollbar.set_update_policy(gtk.UPDATE_CONTINUOUS) scrollbar.connect("change_value",scrollbar_callback) scrollbar.show() hbox6=gtk.HBox(False,0) hbox6.pack_start(scrollbar,True,True) hbox6.show() vbox.pack_end(hbox6,False,True) play_video= gtk.Button("Play") play_video.connect("clicked",player) play_video.show() pause_video= gtk.Button("Pause") pause_video.connect("clicked",pauser) pause_video.show() hbox4= gtk.HBox(False,0) hbox4.pack_start(play_video,True,True) hbox4.pack_start(pause_video,True,True) hbox4.show() vbox.pack_end(hbox4,False,True) vbox.show() win.add(vbox) win.show_all() gtk.main() From tjreedy at udel.edu Wed Sep 10 19:22:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 19:22:38 -0400 Subject: Generator functions and user interfaces In-Reply-To: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> References: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> Message-ID: <ga9krv$o6j$1@ger.gmane.org> psaffrey at googlemail.com wrote: > I'm trying to implement an interactive graph visualisation tool using > matplotlib. > > I want to use a spring layout, where nodes repulse each other and > edges act as springs to pull connected nodes together. Usually, this > algorithm runs through a number of iterations of attraction/repulsion > to allow the nodes to converge to suitable positions. However, rather > than running all these iterations to lay out the graph and then > rendering it, I want to animate the graph as it is "springing" into > place, and then allow the user to drag nodes around and have the graph > redraw on the fly. > > My idea for doing this was to use a generator function, where I yield > the position of the nodes after each iteration and then call draw() on > the position yielded. Does this seem like a sensible approach? To me, no. The reasons for using one do not apply here. What you describe is much like a game with auto updates plus user intervention. I would write an update function and add it to the gui mainloop (if running: update()) along with the draw function to be tied into the gui redraw (those parts I know little about). I would allow use of the spacebar instead of or in addition to a button to toggle 'running' on and off. That is standard in games that allow users to stop the action. tjr From rajan.sriram at gmail.com Tue Sep 9 19:01:09 2008 From: rajan.sriram at gmail.com (Sriram Rajan) Date: Tue, 9 Sep 2008 16:01:09 -0700 Subject: Pexpect echoes twice for each read Message-ID: <b4bc028b0809091601v5ed27cddid4e5bb40d0103f2a@mail.gmail.com> For some reason, Using pexpect causes my output to echo twice when I connect from my MAC Darwin (10.4) to Linux (CentOS release 5 ): The program: --------------------- #!/usr/bin/python # Automatic scp to remote host # Input 1 : filename # Input 2 : destination folder # Input 3 : hostname import pexpect import sys,re ssh_cmd = "ssh " + sys.argv[3] ssh_handle = pexpect.spawn (ssh_cmd) ssh_handle.logfile = sys.stdout PROMPT = "\$\ $" try: ssh_handle.expect(PROMPT) ssh_handle.sendline ("scp "+ sys.argv[1] +" root at 192.168.1.254:" + sys.argv[2] ) ssh_handle.expect("password:") ssh_handle.sendline(" ") ssh_handle.expect(PROMPT) except pexpect.TIMEOUT: ssh_handle.logfile.write("\n Pexpect timeout !!\n") sys.exit(1) except KeyboardInterrupt: ssh_handle.logfile.write("\n User interrupt!\n") sys.exit(2) ssh_handle.close() Output: ----------- $ python pexpect_test.py replace_line_break.sh /tmp/ 10.5.254.18 Last login: Tue Sep 9 15:45:05 2008 from sriram-macbook.dhcp.2wire.com $ scp replace_line_break.sh root at 192.168.1.254:/tmp/ scp replace_line_break.sh root at 192.168.1.254:/tmp/ root at 192.168.1.254's password: replace_line_break.sh 100% 296 0.3KB/s 00:00 $ $ From diordna at gmail.com Wed Sep 10 20:34:37 2008 From: diordna at gmail.com (Stephen Johnson) Date: Wed, 10 Sep 2008 20:34:37 -0400 Subject: Logix - gone? In-Reply-To: <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> References: <276719.72706.qm@web95107.mail.in2.yahoo.com> <mailman.835.1221086049.3487.python-list@python.org> <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> Message-ID: <2B10085D-29D6-4EA7-A947-34880D251A1E@gmail.com> I found Logix (http://livelogix.net/logix/) while looking for something else and thought it looked like a very interesting project. Unfortunately, the blog, mailing list, and Trac links are broken, and the contact email address bounces. I am interested in playing with it and working on it if the original author has dropped it. Does anyone know where I could get the source? I am asking this here because Logix compiles to Python bytecode, and the author announced to this list at one time. Tom Locke, if you're out there... -Steve Johnson (www.steveasleep.com) From tino at wildenhain.de Tue Sep 23 09:10:28 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 23 Sep 2008 15:10:28 +0200 Subject: finding domain name In-Reply-To: <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> <mailman.1404.1222174222.3487.python-list@python.org> <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> Message-ID: <48D8EAC4.1040409@wildenhain.de> Bobby Roberts wrote: >> Depends on the technology/web framework. If you use WSGI, you should use >> something like: >> >> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] >> >> -- Gerhard > > Yeah i already tried environ("SERVER_NAME") but get a key error when i > do. You could output the whole environ to see what you get and how it is called. I'd recommend however to check that you are using a configured value and not something sent by the client if you are going to use it during filesystem lookup. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080923/1555a9de/attachment.bin> From castironpi at gmail.com Wed Sep 3 19:34:28 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 3 Sep 2008 16:34:28 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <e8d089a6-f728-4681-9319-7d8f2f099ac6@p31g2000prf.googlegroups.com> On Sep 3, 7:48?am, bearophileH... at lycos.com wrote: > Empty Python lists [] don't know the type of the items it will > contain, so this sounds strange: > > >>> sum([]) > > 0 > > Because that [] may be an empty sequence of someobject: > > >>> sum(s for s in ["a", "b"] if len(s) > 2) > > 0 > > In a statically typed language in that situation you may answer the > initializer value of the type of the items of the list, as I do in the > sum() in D. > > This sounds like a more correct/clean thing to do: > > >>> max([]) > > Traceback (most recent call last): > ? File "<stdin>", line 1, in <module> > ValueError: max() arg is an empty sequence > > So it may be better to make the sum([]) too raise a ValueError, in > Python 3/3.1 (if this isn't already true). On the other hand often > enough I have code like this: > > >>> max(fun(x) for x in iterable if predicate(x)) > > This may raise the ValueError both if iterable is empty of if the > predicate on its items is always false, so instead of catching > exceptions, that I try to avoid, I usually end with a normal loop, > that's readable and fast: > > max_value = smallvalue > for x in iterable: > ? ? if predicate(x): > ? ? ? ? max_value = max(max_value, fun(x)) > > Where running speed matters, I may even replace that max(max_value, > fun(x)) with a more normal if/else. > > A possible alternative is to add a default to max(), like the next() > built-in of Python 2.6: > > >>> max((fun(x) for x in iterable if predicate(x)), default=smallvalue) > > This returns smallvalue if there are no items to compute the max of. > > Bye, > bearophile Two thoughts: 1/ 'Reduce' has a 'default' argument-- they call it 'initial'. >>> reduce( max, [ 0, 1, 2, 3 ] ) 3 >>> reduce( max, [ 0, 1, 2, 'a' ] ) 'a' >>> reduce( max, [ 0, 1, 2, 'a', 'b' ] ) 'b' 2/ Introduce a 'max' class object that takes a default type or default argument. Query the default for an 'additive' identity, or query for a 'comparitive' identity, comparisons to which always return true; or call the constructor with no arguments to construct one. From sjmachin at lexicon.net Tue Sep 2 17:27:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 14:27:02 -0700 (PDT) Subject: Renumbering References: <mailman.386.1220389036.3487.python-list@python.org> Message-ID: <4e6091af-bc00-4408-beda-adfa7f17dc63@b30g2000prf.googlegroups.com> On Sep 3, 6:57 am, "Francesco Pietra" <chiendar... at gmail.com> wrote: > Hi; > > I would like to renumber, starting from 1, column 6 (i.e, 428 become > 1, 429 becomes 2, etc for a very long list) > > ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 [snip] > ATOM 3437 O SER B 429 144.543 83.756 79.676 1.00134.86 2SG3439 > > Distinctive character is column 5, i.e., it must be set that only > lines containing "B" should be renumbered. > > As you can see, the number of lines for a particular value in column 6 > changes from situation to situation, and may even be different for the > same name in column 4. For example, LEU can have a different number of > lines depending on the position of this amino acid (leucine). The above paragraph is extremely unclear. > > Thanks for help You haven't asked a question, and haven't given any background. What is your experience with Python? Any other language? Are you expecting somebody to write a script for you, or just give you a few hints? Is this homework? Have you put any effort into trying to write a script yourself? Etc etc etc From michele.simionato at gmail.com Fri Sep 5 07:26:04 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 5 Sep 2008 04:26:04 -0700 (PDT) Subject: atomic section in code References: <a475a219-1577-4018-a541-5b05c87f6f71@i76g2000hsf.googlegroups.com> <mailman.544.1220605512.3487.python-list@python.org> Message-ID: <b64f6afa-9c63-4c71-b455-381a3557d326@e39g2000hsf.googlegroups.com> On Sep 5, 10:59?am, Fredrik Lundh <fred... at pythonware.com> wrote: > > 1) seehttp://effbot.org/zone/thread-synchronization.htm The page you link here is WAYS better than the standard documentation of the threading module. Generally speaking, the effbot zone contains a lot of improvements over the standard docs which are lacking in various areas. I have always wondered why they are kept separated. Wouldn't be nice to have the standard docs integrated with the effbot docs? Are there plans in this sense and if not, why not? Michele Simionato From gary at byoteki.com Sun Sep 28 16:11:20 2008 From: gary at byoteki.com (Gary M. Josack) Date: Sun, 28 Sep 2008 16:11:20 -0400 Subject: generate random digits with length of 5 In-Reply-To: <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> References: <e1923ff8-8150-41b6-9444-19c14b4d2f6f@8g2000hse.googlegroups.com> <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> Message-ID: <48DFE4E8.2010307@byoteki.com> Chris Rebert wrote: > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <sotirac at gmail.com> wrote: > >> Wondering if there is a better way to generate string of numbers with >> a length of 5 which also can have a 0 in the front of the number. >> >> >> <pre> >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 >> elements >> code = 'this is a string' + str(random_number[0]) + >> str(random_number[1]) + str(random_number[2]) + str(random_number[3]) >> + str(random_number[4]) >> > > code = ''.join(str(digit) for digit in random_number) > > Regards, > Chris > > >> </pre> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> will random.randint(10000,99999) work for you? From sbassi at clubdelarazon.org Sat Sep 27 14:48:22 2008 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sat, 27 Sep 2008 15:48:22 -0300 Subject: python for *nix system admins In-Reply-To: <92da89760809271132r769411e6t2771b625bbeb04f2@mail.gmail.com> References: <mailman.1578.1222503615.3487.python-list@python.org> <1222520796.630579@athprx04> <170543c70809271123j1334d12ardd09c25ce479978f@mail.gmail.com> <92da89760809271132r769411e6t2771b625bbeb04f2@mail.gmail.com> Message-ID: <9e2f512b0809271148t186a315oa106c99c34ea8c27@mail.gmail.com> On Sat, Sep 27, 2008 at 3:32 PM, Eric Wertman <ewertman at gmail.com> wrote: > I've been growing a library of my own functions, that use the names of > unix commands. They are just conveniences, of course, but I'd suggest > the same for sysadmins, it's handy. Can you share it? Best, SB. From afilash at gmail.com Mon Sep 8 02:17:50 2008 From: afilash at gmail.com (abhilash pp) Date: Mon, 8 Sep 2008 11:47:50 +0530 Subject: firefox timestamp Message-ID: <9f9d35df0809072317h49ccec2ep72524f8d4900daa0@mail.gmail.com> Hi all, I don't know if this question will fit on this section, any way my query is , i have used one script demork.py to extract details from Firefox history.dat file and now the problem is how to convert the TIMESTAMP given by that to normal date and time. example timestams are like this, 1202919771609375 1213874676203125 1215693263859375 i have used datetime module for this but it gave me error >>> import datetime >>> datetime.datetime.fromtimestamp(1215693263859375) Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> datetime.datetime.fromtimestamp(1215693263859375) ValueError: timestamp out of range for platform time_t please help me to convert this ? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/041fcb2a/attachment.html> From jaywgraves at gmail.com Tue Sep 2 14:50:08 2008 From: jaywgraves at gmail.com (jay graves) Date: Tue, 2 Sep 2008 11:50:08 -0700 (PDT) Subject: Large amount of files to parse/organize, tips on algorithm? References: <a8ca9f87-4bf8-4a74-b4ee-902ff3d328ab@x35g2000hsb.googlegroups.com> <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> <6dc5719f-a65b-4194-b09c-b9bbb55ee788@e53g2000hsa.googlegroups.com> Message-ID: <d266a870-8e1b-4995-9717-a565ea566644@c65g2000hsa.googlegroups.com> On Sep 2, 1:02?pm, cnb <circularf... at yahoo.se> wrote: > over 17000 files... > > netflixprize. http://wiki.python.org/moin/NetflixPrizeBOF specifically: http://pyflix.python-hosting.com/ From ppearson at nowhere.invalid Fri Sep 19 11:37:20 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 19 Sep 2008 15:37:20 GMT Subject: Python newbie References: <gavjfd$mvd$1@registered.motzarella.org> <pan.2008.09.19.08.13.05@REMOVE.THIS.cybersource.com.au> Message-ID: <6jhv9gF3fiosU1@mid.individual.net> On 19 Sep 2008 08:13:05 GMT, Steven D'Aprano wrote: > On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote: [snip] >> perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' >> >> The equivalent in Python looks like this: > > Actually, no it doesn't. The equivalent looks more like this: > > > $ python -c 'a=[1,2,3]; a=[2*x for x in a]; > for x in a: > print x' > 2 > 4 > 6 Good job, SD'A. A note for Mladen Gogala: the [...for...] construction in a=[2*x for x in a]; is called a list comprehension, and is wonderful for shortening and clarifying code. One of the pleasures of following this group is watching the old hands answer noob questions with one or two list comprehensions. -- To email me, substitute nowhere->spamcop, invalid->net. From jallen at dashcourses.com Mon Sep 29 09:09:29 2008 From: jallen at dashcourses.com (Jeanne Allen) Date: Mon, 29 Sep 2008 09:09:29 -0400 Subject: SPECIAL DISCOUNTS - Online Python Training Message-ID: <000601c92234$9e07b9c0$da172d40$@com> Do you know anyone who is looking for training on Python? We have two courses taught online with hands-on exercises done on remote PCs. . Python Intro Part 1 - Live On-Line, 8:30am - 12:30pm EST, November 10 to 13, 2008 . Python Intro Part 2 - Live On-Line, 8:30am - 12:30pm EST, November 17 to 20, 2008 When you sign up for either course we will give you a special $200 discount bringing the price to $695. If you sign up for both Part 1 and Part 2 and we'll give you a total discount of $500 (bringing the total price for both courses to $1,290. Please be sure to mention Coupon Code 1214 to receive the discount. You can call me to enroll, or enroll online at http://www.dashcourses.com/public-courses.html. Python Intro Part 1 introduces the student to the basics of writing and running Python scripts, such as variables, file operations, and flow control. Emphasis is placed on features unique to Python, such as tuples, array slices, and output formatting. This is a hands-on programming class. All concepts are reinforced by informal practice during the lecture followed by graduated lab exercises, and all labs are done using remote PC's so there's nothing to download on your office or home PC. For more information, click on http://www.dashcourses.com/public-courses/public-courses/python-intro-part-1 -public-training-course.html. Python Intro Part 2 moves the beginning Python programmer on to more advanced features such as regular expressions, working with binary data, and using the extensive functionality of Python modules. As with Part 1, extra emphasis is placed on features unique to Python. This is also a hands-on programming class. All concepts are reinforced by informal practice during the lecture followed by graduated lab exercises, and all labs are done using remote PC's so there's nothing to download on your office or home PC. This course provides a practical introduction to a working programming language, not an academic overview of syntax and grammar. Students will immediately be able to use Python to complete tasks in the real world. For more details, click on http://www.dashcourses.com/public-courses/public-courses/python-intro-part-2 -public-training-course.html. Thanks for passing this along - Come enjoy our FREE PowerHours! * Oct 27: Python or Perl * Nov 5: USB - Where are we going? * Nov 19: Spring Security to Secure your Java Web Application http://www.dashcourses.com/contests/dashconnect.html Check out our full schedule of online classes! Project Management, Java, PCI, USB, Perl, Python.and much, much more http://www.dashcourses.com/public-courses.html Sincerely, Jeanne Allen Director of Distance Learning Dashcourses International (540) 349-0875 <http://www.dashcourses.com/> www.dashcourses.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080929/3f7579bb/attachment.html> From deets at nospam.web.de Sun Sep 21 06:49:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 21 Sep 2008 12:49:24 +0200 Subject: How to kill threading.Thread instance? In-Reply-To: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> References: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> Message-ID: <6jmn5kF42hreU1@mid.uni-berlin.de> dmitrey schrieb: > hi all, > Is there a better way to kill threading.Thread (running) instance than > this one > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 > (it's all I have found via google). > Nope. There might be other ways technically, but none of them falls into a "better"-classification. Diez From karthikbalaguru79 at gmail.com Sun Sep 14 10:21:01 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Sun, 14 Sep 2008 07:21:01 -0700 (PDT) Subject: tkinter for my python program !! References: <f865e11e-80d5-4c21-9e72-f7b5e57f2bf0@l64g2000hse.googlegroups.com> <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> <6em86gF7q9djU1@mid.uni-berlin.de> Message-ID: <8c9f34d7-a4ab-4c8b-93bd-bf0ba01d5fd8@q5g2000prf.googlegroups.com> On Jul 22, 7:11?pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > karthikbalaguru wrote: > > On Jul 22, 6:32 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > >> karthikbalaguru wrote: > >> > Hi, > > >> > One of my python program needs tkinter to be installed to run > >> > successfully. > >> > I am using Redhat 9.0 and hence tried installing by copying the > >> > tkinter-2.2.2-36.i386.rpm > >> > alone from the CD 3 to my pc. But, it is not getting installed and is > >> > failing by throwing > >> > the below errors. Should i need to configure / install any specific > >> > files for resolving this issue ? > > >> > [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm > >> > warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, > >> > key ID db42a > >> > 60e > >> > error: Failed dependencies: > >> > ? ? ? ? libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > >> > ? ? ? ? libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > >> > ? ? ? ? libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > >> > Any ideas ? > > >> Yes: you should consider reading error-messages. What does > > >> error: Failed dependencies: > >> ? ? ? ? ?libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > >> ? ? ? ? ?libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > >> ? ? ? ? ?libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > >> look like for you? > > >> Small hint: if you install something that depends on something else, you > >> need to .... the missing dependency first. Fill in the dots... > > > I find that it needs python-2.2.2-26.i386 and hence i tried installing > > python and i > > land here :( :( > > > [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm > > warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key > > ID db42a60e > > error: Failed dependencies: > > ? ? ? ? libdb-4.0.so is needed by python-2.2.2-26.i386 > > ? ? ? ? python < 2.4.3-18.fc6 conflicts with python- > > devel-2.4.3-18.fc6.i386 > > [root at localhost karthik]# > > > I find that python 2.4.3-18.fc6 is being used by many of applications. > > But, the program i am trying to run needs python-2.2.2-26. > > So, how to resolve this issue ? > > Are you *sure* it requires python2.2? If yes, why can't fedora install > several python versions together? Ubuntu for sure can. But Python2.2 is > *ancient* - you might need to compile it yourself. > Another method of resolving the whole problem related to rpm dependencies was using the 'yum' utility in Fedora Cores(I use FC2) and 'up2date' utility in RedHat. Karthik From deets at nospam.web.de Mon Sep 1 02:55:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 08:55:03 +0200 Subject: Using NLTK in Java In-Reply-To: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> Message-ID: <6i1hu9FnvcngU1@mid.uni-berlin.de> hussainsaiger at gmail.com schrieb: > I am trying to convert a python module (that contains the use of > NLTK.Corpus) by jythonc. It is not able to include nltk dependencies > within the java class it creates. So when i use this class in java, it > fails to recognize nltk. Can anyone please let me know how should i > use nltk in python/jython modules so i can use in Java. If there are any binary dependencies, you are out of luck. It won't work. You would need to write a RPC-Server then, with technologies such as XMLRPC or CORBA. Diez From python.list at tim.thechases.com Thu Sep 18 09:39:51 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 18 Sep 2008 08:39:51 -0500 Subject: improving a huge double-for cycle In-Reply-To: <f9b69c58-adcc-4042-b9cc-e152ce0056fa@a1g2000hsb.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <mailman.1206.1221741900.3487.python-list@python.org> <f9b69c58-adcc-4042-b9cc-e152ce0056fa@a1g2000hsb.googlegroups.com> Message-ID: <48D25A27.8090502@tim.thechases.com> > Tim Chase: >> for i in xrange(len(IN)): >> for j in xrange(i+1, len(IN)): >> if IN[i].coordinates == IN[j].coordinates: >> SN.append(IN[i].label) >> >> If my college algorithms memory serves me sufficiently, this >> reduces your O(N^2) to O(N log N) which will garner you some >> decent time savings. > > That's O(n^2) still, it's just half matrix, a triangle. Ah, good catch as I'm thinking about it more, you're right...it's O((N^2)/2) which is just O(N^2). Sigh. I'm not awake enough yet. However, dividing the time by 2 (from 15hr to 7.5hr) is still a significant savings in my book :) However, if list-comprehensions are faster as well, you might be able to do something like SN = [d.label for (i,d) in enumerate(IN) for j in xrange(i+1, len(IN)) if d.coordinates == IN[j].coordinates ] or the slightly more verbose (but closer to my original code) version SN = [IN[i].label for i in xrange(len(IN)) for j in xrange(i+1, len(IN)) if IN[i].coordinates == IN[j].coordinates ] To the OP: As always, throw some timing code on the various samples you get back from the list and see what works for you. -tkc From bignose+hates-spam at benfinney.id.au Sun Sep 14 18:55:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 08:55:20 +1000 Subject: Matching horizontal white space References: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> Message-ID: <8763oy72xz.fsf@benfinney.id.au> Magnus.Moraberg at gmail.com writes: > multipleSpaces = re.compile(u'\\h+') > > importantTextString = '\n \n \n \t\t ' > importantTextString = multipleSpaces.sub("M", importantTextString) Please get into the habit of following the Python coding style guide <URL:http://www.python.org/dev/peps/pep-0008>. For literal strings that you expect to contain backslashes, it's often clearer to use the "raw" string syntax: multiple_spaces = re.compile(ur'\h+') > I would have expected consecutive spaces and tabs to be replaced by > M Why, what leads you to expect that? Your regular expression doesn't specify spaces or tabs. It specifies "the character 'h', one or more times". For "space or tab", specify a character class of space and tab: >>> multiple_spaces = re.compile(u'[\t ]+') >>> important_text_string = u'\n \n \n \t\t ' >>> multiple_spaces.sub("M", important_text_string) u'\nM\nM\nM' You probably want to read the documentation for the Python 're' module <URL:http://www.python.org/doc/lib/module-re>. This is standard practice when using any unfamiliar module from the standard library. -- \ ?If you do not trust the source do not use this program.? | `\ ?Microsoft Vista security dialogue | _o__) | Ben Finney From python-url at phaseit.net Tue Sep 23 08:43:12 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 23 Sep 2008 12:43:12 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 23) Message-ID: <gbao90$j4v$1@lairds.us> QOTW: "Python is THE real integration/composition platform !" - Nicolas Lehuen http://groups.google.com/group/comp.lang.python/msg/05dd6fa4509ab15c Python 2.6rc2 and 3.0rc1 have been released: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6a285ea5ea89bff9/ Using the right algorithm (a single for loop!) and the right data structure (a set!) so often improves computing time *drastically* (from 15 hours to 10 minutes in this example): http://groups.google.com/group/comp.lang.python/browse_thread/thread/21aef9dec3fb5403/ True==1 isn't an obvious fact. Also, why does the bool type exist at all? http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d85b7e32a754e73/ Why some methods (like append) don't return the modified object, while others do? http://groups.google.com/group/comp.lang.python/browse_thread/thread/6196c94118247195/ A design exercise: assign different "weights" to methods--overridable in subclasses or individual instances--so the methods can be chosen at random: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5c90f12e6e7db784/ Grouping items to count them - this leads to discussion of possible implementations of len(arbitrary_iterable): http://groups.google.com/group/comp.lang.python/browse_thread/thread/c8b3976ec3ceadfd/ Killing a thread asynchronously is a bad idea (not just in Python): http://groups.google.com/group/comp.lang.python/browse_thread/thread/b37b57e9c7462fe9/ Discussing ways to secure (untrusted) Python code: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b0c13aaad8c3dc4f/ An [absurd] blog post about Python not being "a full OOP language" triggers a lot of responses: http://groups.google.com/group/comp.lang.python/browse_thread/thread/139c31ff17aed522/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From cjw at ncf.ca Wed Sep 3 09:32:47 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 03 Sep 2008 09:32:47 -0400 Subject: new python docs In-Reply-To: <62c0c392-d4e1-4cae-aae0-38d35c4faf57@w7g2000hsa.googlegroups.com> References: <62c0c392-d4e1-4cae-aae0-38d35c4faf57@w7g2000hsa.googlegroups.com> Message-ID: <g9m3m3$gen$1@theodyn.ncf.ca> Rick Dooling wrote: > Wow! I've been away in other pursuits. > > The new docs are gorgeous and searchable. > > http://docs.python.org/dev/index.html > > Thank you, python.org. Yes, they look crisp and clear. It would have been nice if the Apple folk, in their clear Style Guide, had provided hyperlinks to the various documents referenced. Thanks to all the pythoneers who contributed to the documentation. Colin W. From NIE_DZIALA at gazeta.pl Thu Sep 18 06:26:52 2008 From: NIE_DZIALA at gazeta.pl (Piotr Sobolewski) Date: Thu, 18 Sep 2008 12:26:52 +0200 Subject: how can I use a callable object as a method Message-ID: <gatadc$s6f$1@inews.gazeta.pl> Hello, I would like to use a callable object as a method of a class. So, when I have such normal class: class f: version = 17 def a(self): return self.version f1 = f() print f1.a() I want to change it to something like that: class add: def __call__(self, another_self): return another_self.version class f: version = 17 a = add() f1 = f() print f1.a() However, the second version does not work. I think I understand why. That's because "a" inside f1 is not a function (but an object). So f1.a is not a method. So when I do f1.a(), the implicit argument self is not passed. Q1: Am I right? Is this the problem? Q2: What can I do to make it work? From bdesth.quelquechose at free.quelquepart.fr Thu Sep 4 13:49:21 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 19:49:21 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> <acdc94a1-9f8c-49f3-b063-dd536e480d07@v39g2000pro.googlegroups.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> Message-ID: <48c03b91$0$14747$426a74cc@news.free.fr> Ivan Illarionov a ?crit : > On 4 ????, 22:59, Carl Banks <pavlovevide... at gmail.com> wrote: >> You can write code to guard against this if you want: >> >> class A: >> legal = set(["x"]) >> def __setattr__(self,attr,val): >> if attr not in self.legal: >> raise AttributeError("A object has no attribute '%s'" % >> attr) >> self.__dict__[attr] = val >> def __init__(self,x): >> self.y = x >> >> I suspect most people who go into Python doing something like this >> soon abandon it when they see how rarely it actually catches anything. >> > > '__slots__' is better: For which definition of "better" ? __slots__ are a mean to optimize memory usage, not to restrict dynamism. Being able to dynamically add arbitrary attributes is actually a feature, not a bug, and uselessly restricting users from doing so is not pythonic. IOW : don't do that. From castironpi at gmail.com Tue Sep 16 13:49:26 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 10:49:26 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> Message-ID: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> On Sep 16, 10:13?am, cnb <circularf... at yahoo.se> wrote: > >>> sys.path > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > \lib\\site-packages\\PIL'] > > > > Now I have my personal programs in C:/Python25/Progs/ > > How do I add so that I can just do "import somefile" from anywhere in > that directory in the interpreter and it can load files from other > folders in that directory. Add a file: \Lib\site-packages\locals.pth with contents, path to the directory you want to add (/python25/progs/) From george.sakkis at gmail.com Sat Sep 27 11:27:13 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 27 Sep 2008 08:27:13 -0700 (PDT) Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> <Mo7Dk.2064$T65.1885@edtnps82> <48dd5c06$0$26425$426a74cc@news.free.fr> <WvdDk.2157$T65.1610@edtnps82> <f6351d10-2573-4a5c-ab57-d4dd1c7b311c@e53g2000hsa.googlegroups.com> <YKjDk.2022$Pv5.1949@edtnps83> <a7a895ef-ff22-4dc8-8213-97482e5bb19f@z72g2000hsb.googlegroups.com> Message-ID: <c7db7b82-7350-4365-8c12-40f949e739ea@u65g2000hsc.googlegroups.com> On Sep 27, 9:23 am, George Sakkis <george.sak... at gmail.com> wrote: > On Sep 27, 1:44 am, "Dmitry S. Makovey" <dmi... at makovey.net> wrote: > > > I guess my bias is towards more explicit declarations thus > > > bmethod=ProxyMethod('b',B.bmethod) > > > looks more attractive to me, but I stand to be corrected/educated why is > > that not the right thing to do? > > I see where you're coming from and I also prefer explicit reflection > mechanisms instead of strings (e.g. avoid eval/exec as much as > possible). As I mentioned, the second argument to ProxyMethod is (for > all sane purposes) redundant, so if you could implement it in a way > that "bmethod = ProxyMethod('b')" worked, I would be all for it, but > AFAIK it's not possible without a metaclass. Just for completeness, here's a metaclass version that uses ProxyMethod declarations instead of a dict; you'll probably like this better: #======= usage ========================= from proxies import Proxy, ProxyMethod class B(object): def __init__(self, val): self.val = val def bmethod(self,n): print "B::bmethod", self.val, n def bmethod2(self,n,m): print "B::bmethod2", self.val, n, m class C(object): def __init__(self, val): self.val = val def cmethod(self,x): print "C::cmethod", self.val, x def cmethod2(self,x,y): print "C::cmethod2",self.val, x, y cattr = 4 class A(Proxy): def __init__(self, b1, b2, c): print "init A()" # must call Proxy.__init__ super(A,self).__init__(b1=b1, b2=b2, c=c) def amethod(self,a): print "A::mymethod",a bmethod = ProxyMethod('b1') bmethod2 = ProxyMethod('b2') cmethod = ProxyMethod('c') a = A(B(10), B(20), C(30)) a.amethod('foo') print "bound proxy calls" a.bmethod('foo') a.bmethod2('bar','baz') a.cmethod('foo') try: a.cmethod2('bar','baz') except Exception, ex: print ex print "unbound proxy calls" A.bmethod(a,'foo') A.bmethod2(a,'bar','baz') A.cmethod(a, 'foo') try: A.cmethod2(a,'bar','baz') except Exception, ex: print ex #======= output ======================================== init A() A::mymethod foo bound proxy calls B::bmethod 10 foo B::bmethod2 20 bar baz C::cmethod 30 foo 'A' object has no attribute 'cmethod2' unbound proxy calls B::bmethod 10 foo B::bmethod2 20 bar baz C::cmethod 30 foo type object 'A' has no attribute 'cmethod2' #====== proxies.py ====================================== class _ProxyMeta(type): def __new__(meta, name, bases, namespace): for attrname,value in namespace.iteritems(): if isinstance(value, ProxyMethod) and value.name is None: value.name = attrname return super(_ProxyMeta,meta).__new__(meta, name, bases, namespace) class ProxyMethod(object): def __init__(self, proxy_attr, name=None): self._proxy_attr = proxy_attr self.name = name def __get__(self, proxy, proxytype): if proxy is not None: return self.__get_target_attr(proxy) else: return self.__unbound_method def __unbound_method(self, proxy, *args, **kwds): method = self.__get_target_attr(proxy) return method(*args, **kwds) def __get_target_attr(self, proxy): try: delegate = getattr(proxy, self._proxy_attr) return getattr(delegate, self.name) except AttributeError: raise AttributeError('%r object has no attribute %r' % (proxy.__class__.__name__, self.name)) class Proxy(object): __metaclass__ = _ProxyMeta def __init__(self, **attr2delegate): self.__dict__.update(attr2delegate) #====================================================== If you want to eliminate completely specifying attributes with strings, it's easy to modify the above so that you write instead: class A(Proxy): ... bmethod = ProxyMethod(lambda self: self.b1) bmethod2 = ProxyMethod(lambda self: self.b2) This is more verbose for the common case, but it's more flexible in cases where the callable may be more complex than a plain getattr(). Actually you can support both, it doesn't have to be either/or; just check whether the argument to ProxyMethod is a callable and if not, make it: from operator import attrgetter class ProxyMethod(object): def __init__(self, proxy_attr, name=None): if not callable(proxy_attr): proxy_attr = attrgetter(proxy_attr) ... Remaining Implementation is left as an exercise to the reader ;) George From mail at timgolden.me.uk Thu Sep 18 10:06:20 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 18 Sep 2008 15:06:20 +0100 Subject: XML Processing In-Reply-To: <00ef01c9198c$c4bce780$4e36b680$@rawlins@thinkbluemedia.co.uk> References: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> <48D24638.9010601@timgolden.me.uk> <00ef01c9198c$c4bce780$4e36b680$@rawlins@thinkbluemedia.co.uk> Message-ID: <48D2605C.9080808@timgolden.me.uk> Robert Rawlins wrote: >> Some is going to kick themselves when they realise >> that ElementTree *is* built in to Python 2.5 >> >> http://docs.python.org/whatsnew/modules.html#SECTION0001420000000000000000 > > Tim, Andrii, > > Thanks for the heads up on that! I hadn't noticed they're made it part of > the platform modules, that's excellent news. > > In theory I should just be able to amend my import paths and we'll be good > to go, no install external modules. I imagine I'm not the only person with conditional imports of this type: try: from xml.etree import cElementTree as ET except ImportError: from elementtree import ElementTree as ET TJG From sudhi.herle at gmail.com Fri Sep 12 02:05:56 2008 From: sudhi.herle at gmail.com (sudhi.herle at gmail.com) Date: Thu, 11 Sep 2008 23:05:56 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> Message-ID: <68726994-db75-46b2-90ba-c3413326a455@k37g2000hsf.googlegroups.com> On Sep 5, 9:38?am, Helmut Jarausch <jarau... at skynet.be> wrote: > Hi, > > I need to hash arrays of integers (from the hash module). > > So, I have to derive from array and supply a __hash__ method. I don't believe you need to derive from an array. Here are two simple and well known hash functions you can use readily: def djbhash(a): """Hash function from D J Bernstein""" h = 5381L for i in a: t = (h * 33) & 0xffffffffL h = t ^ i return h def fnvhash(a): """Fowler, Noll, Vo Hash function""" h = 2166136261 for i in a: t = (h * 16777619) & 0xffffffffL h = t ^ i return h if __name__ == '__main__': arr = [1001, 3001, 5001, 9001, 10011, 10013, 10015, 10017, 10019, 20011, 23001] print djbhash(arr) print fnvhash(arr) And finally, here is an excellent page that explains hash functions: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx Here is Noll's page where he explains the FNV Hash: http://www.isthe.com/chongo/tech/comp/fnv/ Hope this helps, -- Sudhi From tjreedy at udel.edu Tue Sep 23 04:25:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 04:25:43 -0400 Subject: a short-cut command for globals().clear() ?? In-Reply-To: <49ffb44f-c14d-4d38-86fb-eb50e5ef9abf@d1g2000hsg.googlegroups.com> References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> <1f913671-1c21-4018-a841-a5a02a360c3b@k30g2000hse.googlegroups.com> <49ffb44f-c14d-4d38-86fb-eb50e5ef9abf@d1g2000hsg.googlegroups.com> Message-ID: <gba95s$sj9$1@ger.gmane.org> MRAB wrote: > > How about something like this: > > def clear_workspace(): > keep_set = set(['__builtins__', '__doc__', '__name__', > 'clear_workspace']) For 2.6/3.0, add __package__ to the list to be kept. > for x in globals().keys(): > if x not in keep_set: > del globals()[x] > -- > http://mail.python.org/mailman/listinfo/python-list > From adityashukla1983 at gmail.com Mon Sep 15 13:30:13 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Mon, 15 Sep 2008 12:30:13 -0500 Subject: Converting .py files to batch files. Message-ID: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> How can we convert .py files to batch files? is there any library for this? Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/e07a076c/attachment.html> From gherron at islandtraining.com Mon Sep 8 03:21:52 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 08 Sep 2008 00:21:52 -0700 Subject: How do I set a callback in Python? In-Reply-To: <d797403a-e492-403f-933a-bd18ef53d5c0@k13g2000hse.googlegroups.com> References: <d797403a-e492-403f-933a-bd18ef53d5c0@k13g2000hse.googlegroups.com> Message-ID: <48C4D290.8080803@islandtraining.com> catsclaw wrote: > I can't for the life of me figure out how to set a callback in > Python. I have a class, which wraps another class. The second class > needs a callback assigned. I don't want to use globals for it. > Here's what I'd like to do: > > class MyWrapper: > def get_login(self, username): > return self.user, self.pass > > def __init__(self, user, pass): > self.user = user > self.pass = pass > > self.client = Client("connection string") > self.client.callback_login = get_login > Make that list line: self.client.callback_login = self.get_login Then you are passing a "bound" method (meaning bound to a particular instance). The client class calls its callback_login as a normal function with parameters, and the Wrapper get_login will be called on the proper instance of MyWrapper. This is a very common thing for many uses, including callbacks. Hoping I understood what you wanted correctly, Gary Herron > ... but obviously, the Client class, when it calls the callback, > doesn't pass a reference to the "self" object. How do I do this? > > -- Chris > -- > http://mail.python.org/mailman/listinfo/python-list > From marcus at internetnowasp.net Sun Sep 14 21:36:48 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Mon, 15 Sep 2008 09:36:48 +0800 Subject: Recognizing the email package In-Reply-To: <48C9322D.8080502@wingware.com> References: <48C8734B.6060802@internetnowasp.net> <48C9322D.8080502@wingware.com> Message-ID: <48CDBC30.8050405@internetnowasp.net> Hi, Actually i think its the email package that needs to be "redefined", using lazyimporter is a bad decision and a lousy one. Even py2exe could not handle it correctly. Marcus. Wingware Support wrote: > Marcus.CM wrote: >> Is there any reason why the IDE cant recognize the uppercase >> attribute names of the email package but its the recommended naming . > > This is due to the email package using LazyImporter objects to > dynamically assign names at runtime in ways that the Wing source > analyzer doesn't understand. We'll try to fix this in future Wing > versions. > > Thanks, > > John > From bj_666 at gmx.net Tue Sep 2 17:09:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 21:09:09 GMT Subject: Numpy/Scipy set field of matrix? References: <dbc998fb-2618-4fc9-bf46-d3b196227073@f36g2000hsa.googlegroups.com> Message-ID: <6i5obkFol29aU7@mid.uni-berlin.de> On Tue, 02 Sep 2008 13:27:06 -0700, cnb wrote: >>>> m > matrix([[1, 2, 3], > [4, 5, 6], > [7, 8, 9]]) > > how do I set the field 1,2 (=6) to 45 for example? > > > and how do I initialize a matrix and then add values in a for-loop? > > Im using PIL and want to store all the pixels of an image in a matrix. > > But I can't find the appropriate operations. Work through the tutorial in the Python documentation and read some introduction to Numpy. Ciao, Marc 'BlackJack' Rintsch From dmitry at makovey.net Sat Sep 27 01:44:24 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Sat, 27 Sep 2008 05:44:24 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> <Mo7Dk.2064$T65.1885@edtnps82> <48dd5c06$0$26425$426a74cc@news.free.fr> <WvdDk.2157$T65.1610@edtnps82> <f6351d10-2573-4a5c-ab57-d4dd1c7b311c@e53g2000hsa.googlegroups.com> Message-ID: <YKjDk.2022$Pv5.1949@edtnps83> George Sakkis wrote: > You seem to enjoy pulling the rug from under our feet by changing the > requirements all the time :) but that's half the fun! ;) Bit more seriously - I didn't know I had those requirements until now :) I'm kind of exploring where can I get with those ideas. Initial post was based exactly on what I had in my code with desire to make it more automated/{typo,fool}-proof/robust, elegant and possibly faster. Hopefully such behavior is not off-topic on this list (if it is - let me know and I'll go exploring solo). > Although this works, the second argument to ProxyMethod shouldn't be > necessary, it's semantically redundant; ideally you would like to > write it as "bmethod = ProxyMethod('b')". since I'm already on exploratory trail (what about that rug being pulled from under....?) With my code I can do really dirty tricks like this (not necessary that I'm going to): class B_base: def bmethod(self): print 'B_base' class B(B_base): def bmethod(self): print 'B' class A: bmethod=ProxyMethod('b',B_base.bmethod) > As before, I don't think > that's doable without metaclasses (or worse, stack frame hacking). > Below is the update of my original recipe; interestingly, it's > (slightly) simpler than before: Out of curiosity (and trying to understand): why do you insist on dictionaries with strings contents ( {'bmethod' : 'b1' } ) rather than something more explicit ? Again, I can see that your code is working and I can even understand what it's doing, just trying to explore alternatives :) I guess my bias is towards more explicit declarations thus bmethod=ProxyMethod('b',B.bmethod) looks more attractive to me, but I stand to be corrected/educated why is that not the right thing to do? Another thing that turns me away from string dictionaries is that those are the ones causing me more trouble hunting down typos. Maybe it's just "my thing" so I'm not going to insist on it. I'm open to arguments against that theory. One argument I can bring in defence of more explicit declarations is IDE parsing when autocompletion for B.bme... pops up (suggesting bmethod and bmethod2) and with 'b':'bmethod' it never happens. However that's not good enough reason to stick to it if it introduces other problems. What kind of problems could those be? P.S. so far I find this discussion quite educating BTW. I am more of a "weekend programmer" with Python - using basic language for most of things I need, however I decided to explore further to educate myself and to write more efficient code. From sjmachin at lexicon.net Mon Sep 8 19:33:42 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Sep 2008 16:33:42 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <f8c5f1de-d358-468b-81fd-aa8108d8f7e0@q26g2000prq.googlegroups.com> <dde588e9-84eb-4890-ac42-21dd2aec35c6@q26g2000prq.googlegroups.com> <db089fc6-ab11-4a5b-93ee-50c00992f1e1@v13g2000pro.googlegroups.com> <6d1f32aa-0740-4513-9d9e-f48ddf92435b@z72g2000hsb.googlegroups.com> Message-ID: <03b7fe1f-3b0d-4fa4-b62e-4bbe8efa754a@r15g2000prh.googlegroups.com> On Sep 9, 6:12?am, "andyh... at gmail.com" <andyh... at gmail.com> wrote: [big snip] > In the interests of academia (although this isn't homework :)) I'll > answer some of those questions: Understanding your own requirements is , I would have thought, not much to do with "academia" but a very practical idea. > > - Yes, the mapping dict doesn't necessarily have the same number of > entries as the my_dict. It may have less than it or more than it. What behaviour do you expect when there is a key in my_dict that is not in the mapping? > - There will never be dupes of key or value in the mapping. Though > there maybe in my_dict. If there are ever any dupes of a key in a Python dict object, it will be the end of civilisation as we know it. How are you are guaranteeing that there are no value dupes in your mapping? What are the consequences if a dupe sneaks in? > > And, for extra credit, it may be useful to be able to 'translate' the > my_dict back again using the same mapping_dict. ie, using the values > in mapping dict as the new keys in my_dict, and the keys as the new > values. "... as the new values" of what? my_dict?? Don't you mean something like "using the values in mapping dict as the keys in reverse_mapping, and the keys as the values in reverse_mapping"? Cheers, John From marcin201 at gmail.com Mon Sep 29 12:06:11 2008 From: marcin201 at gmail.com (Marcin201) Date: Mon, 29 Sep 2008 09:06:11 -0700 (PDT) Subject: destructor not called References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> <3dec57f0-c829-4420-b36d-58e21c564053@k37g2000hsf.googlegroups.com> Message-ID: <93627810-b437-4b9a-9aad-6837271fd894@m36g2000hse.googlegroups.com> > Others have already replied to your main question; in short you > shouldn't rely on __del__ being called. Regardless, is there a (good) > reason for having an instance reference to the method ? Without > further information, that seems like a code smell. I have dictionary of fxns to do import/export based on the type of request from user so I can call self.Import['html'] or self.Import['text']. Thanks for everyones help. Marcin From maric at aristote.info Mon Sep 15 11:02:45 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 17:02:45 +0200 Subject: Abstract class In-Reply-To: <gals9d$d7i$1@ger.gmane.org> References: <mailman.1008.1221408214.3487.python-list@python.org> <200809151409.14149.maric@aristote.info> <gals9d$d7i$1@ger.gmane.org> Message-ID: <200809151702.46110.maric@aristote.info> Le Monday 15 September 2008 16:42:49 Fredrik Lundh, vous avez ?crit?: > Maric Michaud wrote: > > But this doesn't match what abstract classes are (in C++ for example) > > you're confusing concepts with specific implementations of those > concepts here. > Maybe, that's why I gave this example, but aren't they (conceptually) classes : - which couldn't be instantiated, - which define at least an interface and possibly some behavior, - for which all the undefined methods need to be implemented in concrete classes (the pure virtual methodds in C++) ? That's the exact implementation in C++ but I'm not aware of any other language that implement this notion. Java simplified this a lot, abstracts are interface (type), no behavior. -- _____________ Maric Michaud From d3vvnull at gmail.com Sun Sep 28 15:16:29 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sun, 28 Sep 2008 14:16:29 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DF63B2.2020408@wildenhain.de> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> <48DF63B2.2020408@wildenhain.de> Message-ID: <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> Tino, dude, I'm afraid I lied about my previous post being the last word. There are some things you said here that must be addressed. On Sun, Sep 28, 2008 at 6:00 AM, Tino Wildenhain <tino at wildenhain.de> wrote: > Michael Mabin wrote: > >> I'm exhausted, so I'll just shut up about this after a few final words. >> > > Thank you for your time :-) > >> 1. "edits" is used in data warehousing to describe data scrubbing or >> filtering of fields in records that are used as input sources for loading >> into data warehouses. It's a term that goes way back to batch processing on >> the mainframe, so it's been used this way for a long time. Sometimes we use >> 'validation' interchangeably with 'edit' but our use of validation usually >> involves a check of input data against business rules and not type or range >> checking which we consider 'edits'. So maybe you're not used to hearing the >> term used this way, but it is a variation perhaps of what you're used to. >> > > And so on and so on in the regular top posting manner I thought I was clearing up your statement that "there is no such thing as edits" and then you went on about not knowing what I meant by "edits" . Why do you dismiss my effort to clarify a point you were clearly wrong about? ... > > Just to give you some thoughts again: your solution might be valid for > you in your controlled environment. Yet you just presented it to the > OP without telling him the limits of when this can be used. And this > is outright dangerous. If one sees this without comment and without your > background she will run into problems sooner or later. So my suggestion > was to either don't tell people such solutions at all or tell them > exactly under which circumstances they might be used. > Outright dangerous? Again, you're assuming the OP's problem involved user input from a web-page. I was addressing the stated requirement of the problem. You can't automatically assume that this problem is related to input from a web-page. Why should I code in a manner that I will never encounter? Maybe instead of suggesting that my recommendation is outright dangerous, you yourself might suggest the caveats. Again, most of my experiences lie within the batch environment, but I shouldn't have to qualify my suggestions with 'this is what we do in the batch environment'. On a mailing list, people are free to point out the limits of my recommendation, but that doesn't necessarily disqualify my recommendation. > > Still I think nailing the problem at the apropriate place is a habit > which should generally devloped - as in your example an additional > int() would have fixed it - but still it would not work if you > want to deal with arbitrary strings. So its good to make suggestions > but pretty please think ahead how someone would use it instead of > investing all your energy into defending dangerous programming practice. Again, danger is in the eye of the beholder and the hands of the user and determined mostly by the circumstances. A code generator written in Python is going to be subject to all kinds of programming considerations that are different from those in web applications. > With "we in python" I referred to a fairly amount of literature about > programming in python and it design patterns. Nothing me personally. > I wasn't aware that we are what has been written or what we have read. I thought we refers to people. Though this sounds a lot like religion. And maybe I am guilty of heresy. > Ah and some final words to the controlleness of datawarehouse > applications and similar things: by the time you are designing such > a solutuion you will never know what future applications will be > developed around it so its always best to be prepared. > Huh? What are you talking about? > > "Data scrubbing" seems a common idea but in fact its very hard to do > it right due to the nature of different systems using different > quoting logic. "Dont trust your input" is a habit not only applicable > to web programming - in fact the company I work for does not do much > web application but input validation is something we get even audited > for. > "We" are always mindful of the problems "data scrubbing" entails. Data scrubbing depends on the requirements, like everything else. And of course, it goes without saying that you should not trust your input, that you should check and validate where appropriate. > > Nevertheless I wish you a very good weekend :-) > > Tino > > Peace. Michael -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080928/dc2b44b0/attachment.html> From ireborin at delete.this.gmail.com Tue Sep 30 09:42:58 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 15:42:58 +0200 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6ke1i8F7dmkkU2@mid.uni-berlin.de> Message-ID: <aja4e49oia6nbe6almu2dfpocmk1bvb8i5@4ax.com> On 30 Sep 2008 07:07:52 GMT, Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote: Hello Marc, thanks for answering (on both subjects). I understand now the logic which lays behind what you were explaining in the other one. It cleared things quite a bit. >Well, I don't know if this qualifies as equivalent: > >===== >from __future__ import with_statement >from functools import partial >from itertools import islice >from pprint import pprint > > >def read_group(lines, count): > return [map(int, s.split()) for s in islice(lines, count)] > >def main(): > result = list() > with open('test.txt') as lines: > lines = (line for line in lines if line.strip()) > result = list(iter(partial(read_group, lines, 3), list())) > pprint(result, width=30) >if __name__ == '__main__': > main() >===== I'm afraid I must admit I find the code above totally uncomprehesible (I can't even see where the array here is mentioned - "result"?) and inpractical for any kind of engineering practice I had in mind. Does python, perchance, have some wrapper functions or something, which would allow one to load an array in a more natural "technical" way ? Like something mentioned above in my post (now deleted) ? Also, is there a way to change counter for arrays to go from 0 to 1 ? (first element being with the index 1) ? (probably not since that seems like a language implementation thing, but it doesn't hurt to ask) -- Ivan From castironpi at gmail.com Mon Sep 22 16:49:05 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 13:49:05 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> <48d78c3c$0$6998$426a74cc@news.free.fr> <mailman.1360.1222091143.3487.python-list@python.org> <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> <48d7f46d$0$15502$426a74cc@news.free.fr> <ea7583fc-82c0-4f8c-aeeb-f3de5af8ba69@i76g2000hsf.googlegroups.com> <48d80038$0$27459$426a34cc@news.free.fr> Message-ID: <7b9fffb9-587c-4757-b7c9-2943321a0b6b@z66g2000hsc.googlegroups.com> On Sep 22, 3:28?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > Aaron "Castironpi" Brady a ?crit : > > > On Sep 22, 2:38 pm, Bruno Desthuilliers > > <bdesth.quelquech... at free.quelquepart.fr> wrote: > (snip) > >> Going back to robot-mode, Aaron ? > > > Not getting the same sense of "soul" as from my usual posts. ?I guess > > so. ?Might even drop the name change, too... > > Don't !-) > > > while I'm at it. ?One > > more word from you about it ?and I'm starting a thread, and calling it, > > "Python and my sense of 'soul'". ?Ha ha. > > Please bear with me - and understand that the above half-backed > half-joke was also an implicit aknowledgement of the recent changes in > your mode of communication. I should have added a <wink>, I think... I can attribute it to a change in environment. Going "back" to robot mode would imply one wasn't always in it, and as such I interpreted a tacit compliment. Thank you for the compliment, Bruno. I don't suppose "starting a thread" is much of a threat, after all... at least in isolation. Regardless, as I've stated, I find the feedback valuable that there seems (to people) to be more than one context that I'm writing from, and I appreciate the chance to learn about it. It's an observation an erst friend made once that one can never perceive oneself directly. (Whether that's a virtue depends on what difference there is between self-conscious, and self-aware.) From lists at cheimes.de Sun Sep 14 14:19:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 14 Sep 2008 20:19:17 +0200 Subject: Abstract class In-Reply-To: <roy-9FFFBD.13564414092008@news.panix.com> References: <mailman.1008.1221408214.3487.python-list@python.org> <roy-9FFFBD.13564414092008@news.panix.com> Message-ID: <gajkj4$iro$1@ger.gmane.org> Roy Smith wrote: >Are you also going to have DoubleSharpNote and DoubleFlatNote? > > Consider the following code: > > note1 = SharpNote("E4") > note2 = NaturalNote("F4") > if note1 == note2: > print "the same note" > else > print "different notes" > > what should it print? Hehe, tricky question. The answer depends on the music instrument and tuning. On a piano E# and F are on the same key but other instruments (e.g. a violin) treat E# and F as different notes. The enharmonic equivalent E# == F is only valid for some instruments and tunes - noticeable for modern tunes like equal temperament. Christian From bdesth.quelquechose at free.quelquepart.fr Fri Sep 26 16:11:17 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 22:11:17 +0200 Subject: Not fully OO ? In-Reply-To: <00ecf4b4$0$20666$c3e8da3@news.astraweb.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> <48DCC786.2040407@wildenhain.de> <mailman.1541.1222440896.3487.python-list@python.org> <48dcf924$0$4653$426a74cc@news.free.fr> <00ecf4b4$0$20666$c3e8da3@news.astraweb.com> Message-ID: <48dd5dd0$0$26425$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 26 Sep 2008 17:00:59 +0200, Bruno Desthuilliers wrote: > >> Patrick Mullen a ?crit : >>> Depending on the scale of the website I am making, how much I care >>> about editing it in the future, and how much I just want to get >>> something up, I will occasionally use php. And I am a self confessed >>> php hater :) But it's generally the fastest way I know to get >>> something up. So even terrible languages can have their uses! >> Sorry but I fail to see how it relates to the current thread ??? > > I think Patrick is responding to a comment from Tino Wildenhain: That didn't showed here (reading this from c.l.py via free.fr). Sorry. > [quote] > Well then it still depends on the perception of "job done". For example > PHP programmers would bet their soul that their language of choice is > exactly the right one to "get the job done." > [end quote] > > Patrick, you will cause much less confusion if you quote relevant parts > of the text you are replying too. Indeed. At least it would have made clear (to me) there was something missing in the thread... From python-pep at arcor.de Thu Sep 25 15:24:58 2008 From: python-pep at arcor.de (python-pep at arcor.de) Date: Thu, 25 Sep 2008 21:24:58 +0200 Subject: PEP Proposal Message-ID: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Hi, sorry, I have these ideas for longer than 10 years, please have a look on it and comment on it. Thx. ---- This is another proposal for introducing types into Python. There are many reasons for incorporating types into Python, but there is also a lot of concern about doing so because of destroying the original character of Python as a smart script language. This proposal adds several advantages of Prolog(ue) techniques without changing the natural understanding of Python as a language. Proposal: 1. Method definitions can be non-unique if a type is prefixed to one or more of its parameters, or the parameters differ in number. 2. A keyword 'reject' is added. 3. A keyword 'fail' is added. 4. A keyword 'cut' is added. Definition: 1. A "type" is a String naming the actual class or class family which the passed instanced is derived from, prefixing the parameter. 2. "'reject'" is a marker inside a function/method and signals that further processing will not be done inside this method, but instead be passed to the next available function/method in row, otherwise an implicit "fail" will occur. 3. "'fail'" is a marker inside a function/method and signals that NO further processing can be done in neither of this or the following functions/methods. 4. "'cut'" is a marker inside a function/method that signals that the failure of called functions/methods inside of it, following this statement, automatically lead to a failure, instead of trying the next method - normally, it would be "reject" instead. 5. Failure of functions/methods to outside of this new context are signalled with a new exception e.g. "MethodRetrialError". E.g. def whoisthethief("List" x): return iknowit(x) def whoisthethief("String" x, "String" y): return iknowit([x,y]) ########## def numeral_add(a, b): if type(a)!=types.IntType: reject ... # equivalent to: def numeral_add("Integer" a, b): ... From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 03:59:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 09:59:05 +0200 Subject: Python newbie question re Strings and integers In-Reply-To: <4703bda4-1028-4202-ac07-fe6afdc1f67e@l64g2000hse.googlegroups.com> References: <c0287f45-1c5a-40b5-aff3-ab5639d26749@k13g2000hse.googlegroups.com> <mailman.1249.1221781022.3487.python-list@python.org> <4703bda4-1028-4202-ac07-fe6afdc1f67e@l64g2000hse.googlegroups.com> Message-ID: <48d75049$0$17063$426a34cc@news.free.fr> rmac a ?crit : > Ah! Arghh!!! You are so correct on the usage of the ':' > > Python syntax is a little different from what I am used to. I don't know what you're used to, but chances are that more than the syntax differs !-) From Lie.1296 at gmail.com Sun Sep 28 07:32:01 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 04:32:01 -0700 (PDT) Subject: Borg vs Singleton vs OddClass References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> <mailman.1612.1222561374.3487.python-list@python.org> Message-ID: <b5b1ba64-ad4f-4b04-bddb-78c17603a47e@w1g2000prk.googlegroups.com> On Sep 28, 7:22?am, Miles <semantic... at gmail.com> wrote: > Lie wrote: > > This is probably unrelated to Python, as this is more about design > > pattern. I'm asking your comments about this design pattern that is > > similar in functionality to Singleton and Borg: to share states. > > > I'm thinking about this design pattern (I don't know if anyone has > > ever thought of this pattern before): > > > class OddClass(object): > > ? ?def __init__(self): > > ? ? ? ?global OddClass > > ? ? ? ?OddClass = self > > ? ?def __call__(): > > I'll change this to def __call__(self): > > > ? ? ? ?return self > > > The OddClass is a class that would overwrite its own class definition > > at its first instantiation. OddClass defines __call__ so that > > subsequent "instantiation" (technically it is no more an > > instantiation, but Duck Typing says it does) of the class would return > > the single instance. > > This seems like a terrible idea to me, but then I never really > understood the appeal of the Singleton pattern, especially in Python. > > > Singleton and OddClass is inheritable. > > >>>> class OddClass(object): ... > >>>> s = OddClass() > >>>> class A(OddClass): pass > > Traceback (most recent call last): > ? File "<stdin>", line 1, in <module> > TypeError: Error when calling the metaclass bases > ? ? __init__() takes exactly 1 argument (4 given) > > Oops! ?And assuming you carefully ordered your code so that OddClass > will never be instantiated before it is subclassed (which seems > fragile), you get behavior like this: I test the code what would happen if I do this before posting the pattern: >>> class OddClass(object): ... >>> s = OddClass() >>> class A(OddClass): pass >>> a = A() It doesn't give me errors, where are you having the problem? > >>> s = OddClass() > >>> s is OddClass() > True > >>> a = A() > >>> s is OddClass() > False > >>> a is OddClass() > True > >>> a is A() > False > >>> a is OddClass() > > False Well, spotted, there is identity problem with this pattern. > -Miles From stef.mientki at gmail.com Tue Sep 16 13:42:39 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 16 Sep 2008 19:42:39 +0200 Subject: Python GUI for animation In-Reply-To: <48CF522F.40402@it.uu.se> References: <48CF522F.40402@it.uu.se> Message-ID: <48CFF00F.1050709@gmail.com> Virgil Stokes wrote: > I have been using Python for a short time and I find it a very > flexible language, and easy to learn and use. I have also worked some > with PyGame and used it to create a simple animation that is > controlled by the mouse and keyboard. The animation is designed to > move filled circles around on the screen and is driven by a data file > that defines (indirectly), the next relative position of each circle. > And for my purposes (queueing demo in the classroom) this works quite > well. However, I would now like to create a Python GUI that would > allow a user to control the animation, via buttons, sliders, etc. > > I am certainly not a Python expert and have never worked with the > creation of a GUI. I would appreciate greatly any advice from those > who have worked with Python GUIs as to the best way to proceed. > Maybe this might be of your interest: http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_screenshots.html Although it's in alfa stage, I'm using parts of it as a regular tool already. I'm looking for practical application so maybe we could work something out. cheers, Stef Mientki > > Thank you in advance, > V. Stokes > -- > http://mail.python.org/mailman/listinfo/python-list From fuzzyman at gmail.com Sun Sep 21 17:51:02 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 21 Sep 2008 14:51:02 -0700 (PDT) Subject: How to kill threading.Thread instance? References: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> <6jmn5kF42hreU1@mid.uni-berlin.de> <fcd4e76c-7d2a-4009-9548-b79e0ad14c44@59g2000hsb.googlegroups.com> <6jn4itF442e7U1@mid.uni-berlin.de> <mailman.1323.1222009536.3487.python-list@python.org> Message-ID: <ce376709-ee86-443a-9cec-94f3e1fa568f@i76g2000hsf.googlegroups.com> On Sep 21, 4:04?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > Diez B. Roggisch wrote: > >> I wonder why something like myThread.exit() or myThread.quit() or > >> threading.kill(myThread) can't be implemented? > >> Is something like that present in Python 3000? > > > Not that I'm aware of it (which doesn't mean to much though). > > > However I *am* aware of the bazillions discussions that have been held > > over this here - and the short answer is: it is a generally very bad > > idea to terminate threads hard, as it can cause all kinds of corruption. > > the problem is that you have no idea what the thread is doing, so just > killing it dead it may make one big mess out of the application's > internal state; see e.g. this post > > ? ?http://mail.python.org/pipermail/python-list/2006-August/400256.html > > ? ?That's wise ;-) ?Stopping a thread asynchronously is in /general/ a > ? ?dangerous thing to do, and for obvious reasons. ?For example, perhaps > ? ?the victim thread is running in a library routine at the time the > ? ?asynch exception is raised, and getting forcibly ejected from the > ? ?normal control flow leaves a library-internal mutex locked forever. > ? ?Or perhaps a catch-all "finally:" clause in the library manages to > ? ?release the mutex, but leaves the internals in an inconsistent state. > > which links to a FAQ from Sun on this very topic: > > http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecati... > > (note that Java releases all mutexes when a thread is killed, but that's > not much better, as the FAQ explains) > > so as usual, the right thing to do is to do things in the right way. > > </F> Often you know terminated a thread would be perfectly safe - and not being able to is very frustrating - particularly if your calculation is coarse grained and there is no convenient point to regularly poll for a stop signal. .NET solves the 'you might interrupt important stuff' by guaranteeing that an asynchronous ThreadAbortException won't be raised inside a finally block. Michael http://www.ironpythoninaction.com/ From steven at REMOVE.THIS.cybersource.com.au Wed Sep 24 01:52:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 24 Sep 2008 05:52:04 GMT Subject: Docstrings for class attributes References: <mailman.1392.1222147427.3487.python-list@python.org> Message-ID: <pan.2008.09.24.05.52.05@REMOVE.THIS.cybersource.com.au> On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names for > integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, so > that help(Constants.FOO) will print some arbitrary string. Sort of a > very limited implementation of PEP 224. The only solution that I can see > is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Others have suggested solutions, which may be better, but for completeness consider using properties: def make_const(value, doc=''): def getter(self): return value return property(getter, None, None, doc) class Foo(object): x = make_const(1.234, 'a special number') The only gotcha is that while help(Foo.x) works, help(Foo().x) does not. -- Steven From waldemar.osuch at gmail.com Thu Sep 11 15:46:02 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Thu, 11 Sep 2008 12:46:02 -0700 (PDT) Subject: Is there a SOAP module that can do this...? References: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> <c6543cf6-aa50-439e-b60e-c012cdd28d10@y38g2000hsy.googlegroups.com> <ce910b1d-018e-4132-aeb5-b38e3f7c5c2f@e53g2000hsa.googlegroups.com> Message-ID: <8b9f7062-320a-45c1-890c-c126c269fcdc@l42g2000hsc.googlegroups.com> On Sep 11, 3:50?am, thebjorn <BjornSteinarFjeldPetter... at gmail.com> wrote: > On Sep 10, 9:44?pm, Waldemar Osuch <waldemar.os... at gmail.com> wrote: > > > > > On Sep 10, 1:23?pm, thebjorn <BjornSteinarFjeldPetter... at gmail.com> > > wrote:> I've been trying to use SOAPpy and ZSI (with and without the use of > > > wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic > > > server(?) in front of some enterprise java bean) and not having much > > > luck. ?I got them to send me an example of what the bytes on the wire > > > are supposed to look like (attached below), and I got it to "work" by > > > going lo-tech: > > > If you are willing to go low tech you can tryhttp://effbot.org/downloads/#elementsoap > > > But before you do that try:https://fedorahosted.org/suds > > It is actively maintained and holds a lot of promise. > > In my testing it knew how to connect to Sharepoint as well > > as WebLogic exposed services. > > > Waldemar > > Thanks for the info Waldemar. I'm looking into suds now, but there's > something I'm having trouble wrapping my head around (xml isn't my > usual territory, so this is perhaps obvious to someone...) This is > what suds tells me: > > >>> print client > > suds ( version=0.2.9 ) > > service ( InboundLegacyDataService ) > ? ? ? ? prefixes: > ? ? ? ? ? ? ? ? ns0 = "http://no/brreg/BReMS/WebService/services" > ? ? ? ? methods (2): > ? ? ? ? ? ? ? ? getInfo() > ? ? ? ? ? ? ? ? submitMessage(xs:string cpaid, xs:string securityKey, > xs:string message, ) > ? ? ? ? types (4): > ? ? ? ? ? ? ? ? submitMessage > ? ? ? ? ? ? ? ? submitMessageResponse > ? ? ? ? ? ? ? ? getInfo > ? ? ? ? ? ? ? ? getInfoResponse > > The method I'm interested in is submitMessage and in particular the > ``xs:string message`` parameter. ?I've been provided with three xsd > files that I'm almost 100% sure defines the format of the xml in the > message (it defines the JegerproveInn sub-structure), but it looks > like that has to be wrapped in a SOAP:Envelope, including the <?xml..> > declaration before being stuffed into the xs:string message parameter, > before that in turn is wrapped in an env:Envelope... Am I on the right > track? > After you figure out how the message should look like, pass it with the rest of the parameters to the submitMessage. "suds" should take care of the rest. Like wrap everything into Envelope, send the request and parse response. If you have to build XML from python let me point you to very useful http://svn.effbot.python-hosting.com/stuff/sandbox/elementlib/builder.py or http://codespeak.net/lxml/api/lxml.builder.ElementMaker-class.html > Another question: ?I'm assuming the xsd files can be used for more > than documentation :-) ?I've found the w3schools "Introduction to XML > Schema" which I'm starting to read right now, however I haven't been > able to google up any Python<->xsd "thingy" that looked promising > (since I'm not sure what I'm looking for, this might not be a big > surprise ;-) ?Is there such a "thingy"? python<->xsd thingy you mention could be "lxml" library that is an implementation of ElementTree + "number of very useful extensions". Most of the time XSD is used to validate XML documents. http://codespeak.net/lxml/validation.html From sturlamolden at yahoo.no Wed Sep 24 14:12:15 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 11:12:15 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> Message-ID: <652a0223-de7c-43b9-900c-280037863037@m44g2000hsc.googlegroups.com> I have updated the cookbook entry for yesterday to also include parallel processing for large data sets. Even if you're not interested in kd-trees, it is a good example of what the new multiprocessing standard module can do. There are still people being scared by the GIL, thinking it prevents Python from utilizing multicore processors. http://www.scipy.org/Cookbook/KDTree From bluecrystalyj at gmail.com Fri Sep 5 09:44:13 2008 From: bluecrystalyj at gmail.com (bcm) Date: Fri, 5 Sep 2008 06:44:13 -0700 (PDT) Subject: int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why? References: <184502f4-872a-4c23-9a6d-e93ef225d4de@a2g2000prm.googlegroups.com> <cef901bc-63cc-498c-8d9b-33aaa7b3914e@s20g2000prd.googlegroups.com> Message-ID: <d27d6829-4bcc-45ec-a04c-5524fdc6fe33@v39g2000pro.googlegroups.com> On Sep 5, 9:29 pm, John Machin <sjmac... at lexicon.net> wrote: > On Sep 5, 11:12 pm, bcm <bluecrysta... at gmail.com> wrote: > > > > > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > > (Intel)] on win32 > > The following line of code describes an funny question?>>> int((9.2-9.0)*10) > > 1 > > >>> int((9.21-9.0)*10) > > 2 > > >>> int((9.1-9.0)*10) > > 0 > > >>> int((9.11-9.0)*10) > > 1 > > >>> int((8.2-8.0)*10) > > 1 > > >>> int((8.23-8.0)*10) > > > 2 > > > why? anybody can explain it? > > Try looking one step at a time:>>> 9.2 > > 9.1999999999999993 > > That wasn't hard, was it? Do you need any further explanation? If so, > look here:http://docs.python.org/tut/node16.html thanks a lot, i am really really stupid ~*v*~ From zutesmog at gmail.com Mon Sep 8 22:32:49 2008 From: zutesmog at gmail.com (timh) Date: Mon, 8 Sep 2008 19:32:49 -0700 (PDT) Subject: Coming from .NET and VB and C References: <d20e9c18-9607-4746-a34a-c37ef6c22aef@d45g2000hsc.googlegroups.com> <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <mailman.471.1220523953.3487.python-list@python.org> <48bfc4e4$0$13232$426a74cc@news.free.fr> <mailman.479.1220528581.3487.python-list@python.org> <bfe480a0-2523-4a16-953c-ecbae4271c11@t54g2000hsg.googlegroups.com> Message-ID: <9efc52fa-f2d2-40e4-8fbb-fb4c06f8e0e4@a3g2000prm.googlegroups.com> Hi What do you mean by a 3% performance hit? And compared to what ? Any performance hit or for that matter a performance improvement would very much dependant on the problem domain , how it maps to the data store and what you are trying to do with it, and your choice of algorithms. T On Sep 9, 8:02?am, benlinde... at gmail.com wrote: > BigTable looks great! ?There's a 3% performance hit for these types of > databases. ?However it makes up for it in other ways. > > "Dive Into Python" seems to suggest there is less busy work, but I am > still looking into the GUI components of Python. ?Say, a grid of 10x10 > tiles of PNGs. > > _______________________________________________________________________________ > > > have no preference with MySQL or SQL, stored procedures or ad-hoc > > queries. > > ? ? ? ? Please note: MySQL is specific relational database management > system > (RDBMs), which uses a dialect of structured query language (SQL). SQL > by > itself is just a semi-standardized query language -- and can > technically > be used to access non-relational DBMS (if any such are still in use), > though the query processor would be a pain to program (map a > relational > join into a hierarchical DBMS schema? ugh). > > > SO, I'm interested in using my Google App space (free 500MB) to > > develop a quick database application. ?Using Python. ?I found "Dive > > Into Python" which I will be reading shortly. > > ? ? ? ? So one question: what RDBMs are supported in that space? > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG From zentraders at gmail.com Tue Sep 16 21:08:05 2008 From: zentraders at gmail.com (Zentrader) Date: Tue, 16 Sep 2008 18:08:05 -0700 (PDT) Subject: backup with python References: <11a3fca0-ded7-47c3-aeff-bb08acb1eb20@d1g2000hsg.googlegroups.com> Message-ID: <46ede3ad-1edf-4350-a320-2d6d46ea5d7d@w24g2000prd.googlegroups.com> Depends on what OS you are using. The easiest way would be to tar the files you want to backup into an empty directory and then have the python backup program call whatever DVD write program you have on your system with the appropriate commands and your backup directory. From larudwer at freenet.de Thu Sep 4 17:06:30 2008 From: larudwer at freenet.de (Ruediger) Date: Thu, 04 Sep 2008 23:06:30 +0200 Subject: why is self not passed to id()? References: <g9pg72$3vi$1@aioe.org> <mailman.502.1220560976.3487.python-list@python.org> Message-ID: <g9piha$gs9$1@aioe.org> Fredrik Lundh wrote: > > >>> id > <built-in function id> > >>> lambda x: id(x) > <function <lambda> at 0x00C07C30> > > any special reason why you're not using Python to write Python programs, > btw? > > </F> I am aware that id is a built in function why shouldn't i use it? Replaceing lambda with id was intended as an performance hack. Profiling proofed that lambda itself takes more than twice as much cpu time than id alone. (profile shortened) 3610503 function calls in 22.451 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 960096 4.593 0.000 6.702 0.000 test14.py:33(<lambda>) 1 0.003 0.003 22.451 22.451 {execfile} 960096 2.109 0.000 2.109 0.000 {id} However using lambda seemed useless to me since id already took an argument and wrapping it in an python function simply has no real purpose. From masticktightgleason at gmail.com Fri Sep 26 05:51:02 2008 From: masticktightgleason at gmail.com (masticktightgleason at gmail.com) Date: Fri, 26 Sep 2008 02:51:02 -0700 (PDT) Subject: soul calibur hentai soul calibur 2 hentai soul calibur 3 Message-ID: <6efa1533-38a8-40c1-b7ac-ef4fa5df832c@73g2000hsx.googlegroups.com> soul . . . *******CLICK HERE******** http://vids365.cn/soul ***************************** . . . . . . . . . . . . He wrapped soul arms around Mandy as the two of them tried to catch soul breath. calibur watched calibur go and slip behind some chairs and then calibur was gone leaving calibur slightly puzzled as my view had been slightly obscured at the vital moment. Within a minute hentai was back to its former self - stiff as a rod. She was sitting on the edge of the couch as soul came over to her, telling soul how sorry soul was that this had happened. I assured calibur that calibur was not at fault and that calibur understood and had the same feelings. 2 was a little way ahead of 2 and 2 could see 2 body start to shake with silent tears. Joe and hentai new wife had invited a fair number of people as the room was filled with ranks of chairs with a wide aisle down the middle for the bride. Her legs are parted, soul swears soul sees a glimpse of soul cunt. It caused calibur nipples to harden, and pussy throb in anticipation, and calibur wondered if calibur could smell calibur arousal. By the time the next spurt started up my shaft, 3 had pulled back again until just the head was in 3 mouth. We were kind of isolated, until last year when Joe and Tammy bought the lot down from us and had hentai house built. soul love soul tight cunt. He started finger-fucking calibur hard and calibur lips sucked on calibur clit. hentai could hear Tammy's breathing become ragged as hentai continued sucking. manga and manga walked in silence into the woods. Mandy glanced over at soul and soul looked like soul mind was a million miles away. ?Mmmm calibur needed that? said calibur as calibur reluctantly broke the kiss, fearing discovery. ?Mandy nodded in agreement, snuggled up in hentai arms, and ran hentai fingers across hentai chest. She then walks toward taki with a slow, seductive sway with taki large breasts bouncing slightly with each step. ?Ooooh Daddy free cock is so big and hot, free bet free tastes good too. soul then moved and lay down beside Mandy on the bed, snuggling up close to her. She smiled and said, It's not calibur fault, and there wasn't really any harm done. She was the love of hentai life. ?A limo, oh God, soul have never rode in one of those. ?She smirked and said, ?Well if calibur does guess calibur can do some more fucking huh!? calibur ?s eyes twinkled with lust and calibur lay on calibur back. So anime walked to the jewelry store on the corner and picked out sapphire blue earrings with a matching necklace ensemble. My trembling fingers found the zipper at the back of hentai dress and pulled hentai down in a single movement. Her fingers caressed down hentai chest until hentai grasped hentai hard cock, and hentai slowly stroked it. soul rubbed soul back softly, then yawned and said. We were on a weekend leave that summer when calibur suggested that calibur get a tattoo to prove my devotion to her. ?Mmmm, that?s nice? calibur said and moved closer to me, moving calibur hand on to my thigh and imitating my movements. ?His eyes light up and girls smiles devilishly. She kissed hentai cheek and squealed, ? hentai , I?d love to. soul was a little way ahead of soul and soul could see soul body start to shake with silent tears. A smile crossed Mandy?s face when calibur spoke. Her cunny muscles were gripping hentai as hentai slid in and out of hentai sopping hole. anime could play with anime like this all night!?He watched anime in awe as Mandy crawled between anime legs. She kissed sex softly in response. ?Even worse, he?s put porn around school that I?m just a baby and frigid?. Her whole body quivered as beads of sweat rolled down pron back. At last soul all came to an end and soul trooped past Joe and Samantha as soul welcomed us to the reception. calibur hope that don?t bother you. While there hentai met and became friends with a sergeant who was a year younger than me. It is at that moment ivy knows that ivy was his. ?A penny for soul thoughts, darling. After sitting down, calibur lifted calibur glass and toasted, ?Here?s to us Mandy. As iii talked with iii , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as iii went to an all boys school. After another minute hentai announced hentai was now clean. It isn?t long before soul can feel Mandy?s body tense up with an impending climax. ?Mandy?s pussy is drenched and Daddy devours calibur own juices which are mixed with hers. ivy couldn't argue. It wasn't long and hentai visitor groaned and began shooting hentai cum into hentai mouth. Straddle Daddy?s cock, and ride soul hard!?Mandy moans in delight and shifts soul weight onto soul knees. calibur then bent up, calibur breasts bobbing again, and whispered heavily. lesbian took my cock deep into lesbian mouth again and sucked deeply as lesbian pumped my shaft. Baby, if hentai is true love, hentai will be here next month and all the days beyond that. He feels videos climax building videos will not be long now until videos spews videos cum all over videos abdomen. He panted heavily, grabbing the sheet with both hands to keep from ramming taki dick home. Besides, my mind was suddenly alive to the possibilities that the game could give soul this year. ?Well my pretty, calibur think calibur shall go to Dillard?s. As a woman, hentai is bright, beautiful, young and sexy. From dblubaugh at belcan.com Tue Sep 30 14:18:50 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 30 Sep 2008 14:18:50 -0400 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <gbtpuf$356$1@ger.gmane.org> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> <gbtpuf$356$1@ger.gmane.org> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9A26@AWMAIL04.belcan.com> Thank You!! I am still new to Python!! David Blubaugh -----Original Message----- From: Christian Heimes [mailto:lists at cheimes.de] Sent: Tuesday, September 30, 2008 2:08 PM To: python-list at python.org Subject: Re: OS.SYSTEM ERROR !!! Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) > by going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > > The executable would execute perfectly. > > > However, when I would try to execute the following lines of source > code within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") Try this: import subprocess retval = subprocess.call( ['Myprogram.exe', '1', '1', 'acc', '0'], cwd='C:\myprogramfolder\run') Christian This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From fredrik at pythonware.com Wed Sep 10 06:29:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 12:29:38 +0200 Subject: which of these 2 quicksorts is faster? In-Reply-To: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> References: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> Message-ID: <ga87ij$1r1$1@ger.gmane.org> process wrote: > qsort can handle bigger lists it seems, making less recursive calls > before finishing(quicksort blows the stack when sorting > range(100,-1000,-1). > qsort does more work though right? is there a way to speed up that? > > is the built-in sort not defined recursively? what makes you think you can write a better sort than the built-in algorithm by typing in some toy quick-sort implementations from a "sorting for dummies" article? </F> From grante at visi.com Sun Sep 14 20:20:10 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 19:20:10 -0500 Subject: Is there any nice way to unpack a list of unknown size?? References: <238815.3778.qm@web7902.mail.in.yahoo.com> <mailman.1017.1221421225.3487.python-list@python.org> Message-ID: <0sCdnf_qXv-nN1DVnZ2dnUVZ_q3inZ2d@posted.usinternet> On 2008-09-14, Fredrik Lundh <fredrik at pythonware.com> wrote: >> 1. first, second, third, *rest = foo >> >> 2. for (a,b,c,*rest) in list_of_lists: > > update to Python 3.0 (as others have pointed out), or just do > > first, second, third = foo[:3] > rest = foo[3:] Of course you can do that in one line if you want it to look a bit more like the original pseudocode: (a,b,c),rest = foo[:3],foo[3:] That still requires you to manually count the number of "non-rest" destination elements on the LHS and type that number twice on the RHS. If you wanted to elminate a tiny bit of the redundancy you could define a split() function: def split(seq,n): return seq[:n],seq[n:] (a,b,c),rest = split(foo,3) -- Grant From arnodel at googlemail.com Thu Sep 11 14:04:20 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 11 Sep 2008 11:04:20 -0700 (PDT) Subject: Please help me finding a way to implement os.path.issubpath(a, b) References: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> Message-ID: <34bc968e-735e-4ef0-99f3-3d71da6254d4@z72g2000hsb.googlegroups.com> On Sep 11, 5:40?pm, "Giampaolo Rodola'" <gne... at gmail.com> wrote: > Hi, > I'm trying to implement a function which returns whether a path is a > subpath of another one (e.g. /a/b/c is a subpath of /a/b). > I wrote this function which apparently seems to work fine: > > import os > > def issubpath(path1, path2): > ? ? """Return True if path1 is a sub path of path2.""" > ? ? if path1 == path2: > ? ? ? ? return False > ? ? x1 = path1.split(os.sep) > ? ? x2 = path2.split(os.sep) > ? ? return x1[:len(x2)] == x2 > > ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False. > A little help would be appreciated. > > Thanks in advance. That's because: >>> 'C:\\dir'.split('\\') ['C:', 'dir'] >>> 'C:\\'.split('\\') ['C:', ''] So you could write instead something like x1 = path1.rstrip(os.sep).split(os.sep) x2 = path2.rstrip(os.sep).split(os.sep) in your function HTH -- Arnaud From deets at nospam.web.de Thu Sep 4 07:13:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Sep 2008 13:13:51 +0200 Subject: overwrite set behavior References: <g9oat3$veh$1@nnrp-beta.newsland.it> Message-ID: <6i9u83Fpi1lhU2@mid.uni-berlin.de> Michele Petrazzo wrote: > Hi all, I want to modify the method that set use for see if there is > already an object inside its obj-list. Something like this: > > class foo: pass > > bar1 = foo() > bar1.attr = 1 > > bar2 = foo() > bar2.attr = 1 > > set( (bar1, bar2), key=lambda o: o.attr) > > and, of course, set has only one value. > > It's possible? Using a decorator/delegate-pattern, yes: class Foo(object): def __init__(self, delegate): self.delegate = delegate def __hash__(self): return hash(self.delegate.attr) def __cmp__(self, other): return cmp(self.delegate.attr, other.delegate.attr) set(Foo(a) for a in bar1, bar2) Diez From fredrik at pythonware.com Thu Sep 18 16:24:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Sep 2008 22:24:34 +0200 Subject: Twisted vs Python Sockets In-Reply-To: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> References: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> Message-ID: <gaude2$6s2$1@ger.gmane.org> James Matthews wrote: > I am wondering what are the major points of twisted over regular python > sockets. I am looking to write a TCP server and want to know the pros > can cons of using one over the other. Twisted is a communication framework with lots of ready-made components: http://twistedmatrix.com/trac/wiki/TwistedAdvantage Regular sockets are, well, regular sockets. No more, no less. </F> From gagsl-py2 at yahoo.com.ar Fri Sep 19 05:34:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 06:34:31 -0300 Subject: Login to website using urllib2 References: <63fb26950809180623uea83fa5r34a7a3e2f4198b37@mail.gmail.com> Message-ID: <op.uhp17txzx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 18 Sep 2008 10:23:50 -0300, Mohit Ranka <mohitranka at gmail.com> escribi?: > I am trying to fetch HTML content from a website that has > different version of pages for "logged" users and "guseuests" users. I > need > to fetch the "logged" user pages. The problem is, even with the use of > basic > authentication, I am getting "guest" user page with urllib2.urlopen. The > code can be seen here. > > http://pastebin.com/m7301084a > > Any suggestions/pointers/solutions? Your second call to urllib2.install_opener completely replaces the former opener; you should combine both handlers before installing ONE opener. -- Gabriel Genellina From dudeja.rajat at gmail.com Thu Sep 25 04:50:13 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Thu, 25 Sep 2008 09:50:13 +0100 Subject: Tkinter: Unable to update the text scroll Message-ID: <e0b6c39a0809250150i5bbe76a8g2efe8e1e6ee26c11@mail.gmail.com> Hi, I've a Tkinter application which has some widgets and a textbox with scrollbar, I call it txtScroll. The txtScroll is used to display the processing log that application is doing. Well the problem is that the txtSxroll is not able to display the log at the time some thing is processed. Rather, it displays the log after the complete processing processing is done. Example: In a function, I've the following lines: def func(): print 'Testing & Result Comp' TASymbols.objLogToGUI.outputText("Starting Test and Results Comparison\n") if selectedLib != TASymbols.strSelectAll: # we do not pass it as a string instead we will pass it in a #single element list libKey = self.__findKey(self.__libDict, selectedLib) The colored line should display the stuff at the time it appeared in the code. But only displays this after the function func() has processed completely. PS : I'm not using any threading stuff here.. Please help me resolve this problem. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080925/e2117d40/attachment.html> From gomesjas at gmail.com Mon Sep 15 11:44:28 2008 From: gomesjas at gmail.com (gomesjas at gmail.com) Date: Mon, 15 Sep 2008 08:44:28 -0700 (PDT) Subject: ElementTree oddities References: <c8f3d9e0-05dd-4ae9-b8c2-8b9bea15908c@r15g2000prd.googlegroups.com> Message-ID: <7c910f08-db42-4be6-a4f4-9063639c6610@m45g2000hsb.googlegroups.com> I'm not sure, but I think your document is not well formated... Anyone as the name of the module you must think about XML, not as a flat doc, but as a tree that's the only way I got to parse XML. Brian Cole a ?crit : > I'm trying to extract the text from some xml. I figured this > convenient python two-liner would do it for me: > >>> from xml.etree.ElementTree import * > >>> from cStringIO import StringIO > >>> root = parse(StringIO(xml)).getroot() > >>> ' '.join([n.text for n in root.getiterator() if n.text is not None]) > > However, it's missing some of the text. For example, the following > XML: > >>> xml = "<highlight><sp />Bar</highlight>" > > Returns me a empty string. Seems the "<sp />" tag is borking it. > > > Also, the for the following XML: > >>> xml = "<highlight><ref>Bar</ref>:</highlight>" > > I only get "Bar". It's missing the trailing colon. > > I'm not that experienced with XML so perhaps I am just missing > something here. Please enlighten me. > > Thanks, > Brian From gagsl-py2 at yahoo.com.ar Mon Sep 29 22:03:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 23:03:23 -0300 Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d@posted.visi> <gbjmdp$q1e$2@lust.ihug.co.nz> <dZOdnT0NKORdEEDVnZ2dnUVZ_rvinZ2d@posted.usinternet> <gbkdrl$7mq$4@lust.ihug.co.nz> Message-ID: <op.uh9unxsmx6zn5v@gabriel2.softlabbsas.com.ar> En Sat, 27 Sep 2008 01:46:45 -0300, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> escribi?: > In message <dZOdnT0NKORdEEDVnZ2dnUVZ_rvinZ2d at posted.usinternet>, Grant > Edwards wrote: >> On 2008-09-26, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> >> wrote: >>> In message <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d at posted.visi>, Grant >>> Edwards wrote: >>> >>>> Never assume somebody reading the article and attempting to >>>> help you can see the subject line. >>> >>> Why not? >> >> Because it might not be. It depends on the user's newsreader >> and editor settings. > > So, should I not assume that they can see the content as well, because it > might not be visible, depending on the user's newsreader and editor > settings? Of course not. But the space allowed for the subject line may be limited - body usually wraps, but subject might not. Add a few Re: Rv: at the start and even fewer characters are displayed. I currently see the subject line shortened at: available wi... -- Gabriel Genellina From dthole at gmail.com Wed Sep 10 14:52:25 2008 From: dthole at gmail.com (David Thole) Date: Wed, 10 Sep 2008 11:52:25 -0700 (PDT) Subject: PHP's str_replace ? References: <mailman.788.1221054649.3487.python-list@python.org> <6iq2jpFs113rU1@mid.uni-berlin.de> <6iq2sbFs113rU2@mid.uni-berlin.de> <48C7F6EA.7010202@anjanesh.net> <mailman.809.1221067253.3487.python-list@python.org> Message-ID: <2746da03-39df-4bc0-9365-de5a2414adc4@f36g2000hsa.googlegroups.com> On Sep 10, 12:20?pm, Christian Heimes <li... at cheimes.de> wrote: > Anjanesh Lekshminarayanan wrote: > >> import re > >> new_str = re.sub('[aeiou]', '-', str) > > Wow - this is neat. Thanks > > But probably slower and definitely harder to understand. For simple > problems the str methods are usually faster than a regular expression. > > Christian It's true that regular expressions are generally slower, but I disagree that it's hard to understand. When dealing with text, I think it's an absolute must that programmers know about regular expressions. I think this here is an example where even str_replace in Python wouldn't have worked well. -David http://www.thedarktrumpet.com From uzmanajmal at gmail.com Sat Sep 13 08:58:09 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Sat, 13 Sep 2008 12:58:09 +0000 Subject: XML RPC Problem.... In-Reply-To: <gagc6u$tj6$1@ger.gmane.org> References: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> <gaagp1$804$1@ger.gmane.org> <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> <gafuhg$sh1$1@ger.gmane.org> <a3158e8b0809130306m25dda070w73f0a3c25888e051@mail.gmail.com> <gag6dj$fd5$1@ger.gmane.org> <a3158e8b0809130523g579ac36ci88caee7ac279f64d@mail.gmail.com> <gagc6u$tj6$1@ger.gmane.org> Message-ID: <a3158e8b0809130558w31294528veb8769764353415c@mail.gmail.com> Yeah right but i don't see something wrong in my server's code. Following is my server's simple code import SimpleXMLRPCServer #server = ServerProxy("http://betty.userland.com") class AuthenticationFunctions: def s(self): print "something..." server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(AuthenticationFunctions()) server.serve_forever() and following is what i get when i run my client. Traceback (most recent call last): File "ppkey.py", line 48, in <module> caller() File "ppkey.py", line 45, in caller print server.s() File "/usr/lib/python2.5/xmlrpclib.py", line 1147, in __call__ return self.__send(self.__name, args) File "/usr/lib/python2.5/xmlrpclib.py", line 1437, in __request verbose=self.__verbose File "/usr/lib/python2.5/xmlrpclib.py", line 1191, in request headers xmlrpclib.ProtocolError: <ProtocolError for localhost:8000/: 500 Internal Server Error> On Sat, Sep 13, 2008 at 12:37 PM, Fredrik Lundh <fredrik at pythonware.com>wrote: > Usman Ajmal wrote: > > Problem is that when i start client (while the server is already running), >> i get an error i.e. >> Error 500 Internal Server Error >> > > that's a server error, not a client error. check the server logs (e.g. > error.log or similar). > > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080913/2181df9f/attachment.html> From bj_666 at gmx.net Tue Sep 30 03:07:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Sep 2008 07:07:52 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: <6ke1i8F7dmkkU2@mid.uni-berlin.de> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Reborin wrote: > 1. Multi dimensional arrays - how do you load them in python For > example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? Well, I don't know if this qualifies as equivalent: ===== from __future__ import with_statement from functools import partial from itertools import islice from pprint import pprint def read_group(lines, count): return [map(int, s.split()) for s in islice(lines, count)] def main(): result = list() with open('test.txt') as lines: # # Filter empty lines. # lines = (line for line in lines if line.strip()) # # Read groups until end of file. # result = list(iter(partial(read_group, lines, 3), list())) pprint(result, width=30) if __name__ == '__main__': main() ===== The output is: [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]] `k` is the first index here, not the last and the code doesn't use fixed values for the ranges of `i`, `j`, and `k`, in fact it doesn't use index variables at all but simply reads what's in the file. Only the group length is hard coded in the source code. Ciao, Marc 'BlackJack' Rintsch From ken at seehart.com Tue Sep 30 08:14:35 2008 From: ken at seehart.com (Ken Seehart) Date: Tue, 30 Sep 2008 05:14:35 -0700 Subject: Newbie question... In-Reply-To: <e8f87$48e1891c$17186@news.teranews.com> References: <e8f87$48e1891c$17186@news.teranews.com> Message-ID: <48E2182B.6070301@seehart.com> Ken D'Ambrosio wrote: > First, apologies for such a newbie question; if there's a better forum > (I've poked around, some) feel free to point it out to me. Anyway, a > mere 25-odd years after first hearing about OOP, I've finally decided > to go to it, by way of Python. But this puzzles me: > > import commands > free = commands.getoutput("free") > for line in free: > print line, > > Gives: > t o t a l u s e d f r e e > s h a r e d b u f f e r s c a c h e d > M e m : 5 1 5 9 9 2 4 6 0 4 5 2 > 5 5 5 4 0 > 0 7 7 5 1 6 9 1 8 8 4 > - / + b u f f e r s / c a c h e : 2 9 1 0 5 2 2 > 2 4 9 4 0 > > Why are there spaces between everything? And how do I keep it from > happening? *confused* > > Thanks much, > > -Ken > ** Posted from http://www.teranews.com ** > -- > http://mail.python.org/mailman/listinfo/python-list > The variable 'free' is a string containing all of the output, not a file object or a sequence of strings. Therefore, when you iterate free you iterate a sequence of characters. This is different than the case of iterating an open file, which would give you a sequence of lines as you expect. So ... print line, ... prints each character followed by a space and no newline. You can do this instead: import commands free = commands.getoutput("free") print free - Ken (that's my name too) From grante at visi.com Mon Sep 1 10:12:38 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 01 Sep 2008 09:12:38 -0500 Subject: Command lime code References: <s98gb450qu1k36j173fblm1q1nn4ajh5cr@4ax.com> Message-ID: <JbidnaZw_ZTLZSbVnZ2dnUVZ_qjinZ2d@posted.visi> On 2008-08-29, London at ezauza.com <London at ezauza.com> wrote: > I am new to python. OK. > I did find a page which listed some code - IE "chdir" type > code but can not find it again. I have absolutely no clue what you mean. > Can you supply an address? Sure, in fact, I can supply two! http://www.python.org/ http://www.google.com/ -- Grant From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 8 10:16:00 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Sep 2008 16:16:00 +0200 Subject: Dictionaries and loops In-Reply-To: <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> References: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> <48c52c54$0$16982$426a74cc@news.free.fr> <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> Message-ID: <48c53322$0$3460$426a74cc@news.free.fr> bearophileHUGS at lycos.com a ?crit : > Bruno Desthuilliers: >> This doesn't look like a CSV file at all... Is that what you actually >> have in the file, or what you get from the csv.reader ??? > > I presume you are right, the file probably doesn't contain that stuff > like I have assumed in my silly/useless solutions :-) Yeps. I suspect the OP found a very creative way to misuse csv.DictReader, but I couldn't figure out how he managed to get such a mess. From google at mrabarnett.plus.com Thu Sep 4 13:46:39 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 4 Sep 2008 10:46:39 -0700 (PDT) Subject: Python and Cyrillic characters in regular expression References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> Message-ID: <4d48c402-d78a-4425-9ff3-e21370fa44d9@n33g2000pri.googlegroups.com> On Sep 4, 3:42?pm, phasma <xpa... at gmail.com> wrote: > Hi, I'm trying extract all alphabetic characters from string. > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE) You don't need both (?u) and re.UNICODE: they mean the same thing. This will actually match letters and whitespace. > buf = re.match(string) > > But it's doesn't work. If string starts from Cyrillic character, all > works fine. But if string starts from Latin character, match returns > only Latin characters. > I'm encoding the Unicode results as UTF-8 in order to print them, but I'm not having a problem with it otherwise: Program ======= # -*- coding: utf-8 -*- import re reg = re.compile('(?u)([\w\s]+)') found = reg.match(u"ya ?") print found.group(1).encode("utf-8") found = reg.match(u"? ya") print found.group(1).encode("utf-8") Output ====== ya ? ? ya From gherron at islandtraining.com Thu Sep 25 16:31:02 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 25 Sep 2008 13:31:02 -0700 Subject: Matrix programming In-Reply-To: <ea09b3700809231124l13949ed8h7f68ea065c029c52@mail.gmail.com> References: <ea09b3700809231032h677f5b05k5a37397296a7e6e9@mail.gmail.com> <48D92E39.8000901@islandtraining.com> <ea09b3700809231124l13949ed8h7f68ea065c029c52@mail.gmail.com> Message-ID: <48DBF506.6060407@islandtraining.com> A. Joseph wrote: > If my question was not understandable, tell me and stop pointing me to > such page. Your question was completely understandable, but so incredibly vague as to be a waste of bandwidth to send and a waste of time to answer. What kind of matrix programming do you refer to? Many sub-fields of mathematics, many sub-fields of engineering, most all sub-fields of physics, (indeed most sciences), the fields of probability and statistics, robotics, most any kind of simulation, computer graphics, geometric modeling, etc., etc. ALL use matrices and ALL use them differently. I could give you references for matrix programming in half those fields, and others could surely extend my list by a factor of at least 10. So... What is it you are asking for. And as pointed out in the one reference I did give you, be explicit enough to help others understand *what* it is you want! Gary Herron > > On 9/23/08, *Gary Herron* <gherron at islandtraining.com > <mailto:gherron at islandtraining.com>> wrote: > > A. Joseph wrote: > > > I need an ebook or tutorial that teach matrix programming. > > > Perhaps you should start here: > http://www.catb.org/~esr/faqs/smart-questions.html#intro > <http://www.catb.org/%7Eesr/faqs/smart-questions.html#intro> > > Gary Herron > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > I develop dynamic website with PHP & MySql, Let me know about your site From donspauldingii at gmail.com Wed Sep 17 13:56:39 2008 From: donspauldingii at gmail.com (Don Spaulding) Date: Wed, 17 Sep 2008 10:56:39 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: <mailman.1150.1221614920.3487.python-list@python.org> Message-ID: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> On Sep 16, 8:29?pm, Todd Whiteman <to... at activestate.com> wrote: > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming language. > > The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX > is possible with a few deviations, I have tried to cover these > deviations where applicable). > > Feedback is welcome. > > Cheers, > Todd I get to the "Running" step and run into "Couldn't load XPCOM." Does this work on x86_64? Or have I made a rookie mistake? xulapp1$ ls app docs installer pyxpcom_gui_app xulapp1$ cd pyxpcom_gui_app/ pyxpcom_gui_app$ ls application.ini components extensions pyxpcom_gui_app chrome defaults pylib xulrunner pyxpcom_gui_app$ ./pyxpcom_gui_app Couldn't load XPCOM. From ceball at users.sourceforge.net Wed Sep 10 10:41:49 2008 From: ceball at users.sourceforge.net (Chris) Date: Wed, 10 Sep 2008 14:41:49 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C Message-ID: <loom.20080910T144026-626@post.gmane.org> Hi, I'd like to be able to access an attribute of a particular Python object as fast as possible from some C code. I wondered if using __slots__ to store the attribute would allow me to do this in a faster way. The reason I'd like to do this is because I need to access the attribute inside a loop within some C code, and I find that the attribute lookup using the 'PyObject_GetAttrString' call is far slower than any of the subsequent calculations I perform in C. Using the 'PyObject_GetAttrString' function to get the attribute, I find it is slightly faster when the attribute is a slot than when it isn't, but that the attribute lookup remains the performance-limiting factor. Additionally, if I instead build a list of the attributes first and pass that to the C code, using the 'PyList_GetItem' function to access each item, the performance improves significantly. I'd rather be able to access the information from C, instead of building the list externally. As far as I can tell, nothing is documented about accessing __slot__ members in a special way from C, but perhaps someone knows how to do it anyway? To be more specific, below is an example of what I'm talking about. I use SciPy's weave to inline C code, but I assume that doesn't make any difference to my problem. Thanks for any suggestions, Chris class MyObject(object): __slots__ = ['attr_one'] def __init__(self,attr_one=1.0): self.attr_one = attr_one import weave def test_loop(myobjects): rows,cols = len(myobjects),len(myobjects[0]) code = """ for (int r=0; r<rows; ++r) { PyObject *myobjects_row = PyList_GetItem(myobjects,r); for (int l=0; l<cols; ++l) { PyObject *myobject = PyList_GetItem(myobjects_row,l); // any faster way when attr_one is a slot? PyObject *attr_one_obj=PyObject_GetAttrString(myobject,"attr_one"); // more computations involving attr_one; just print for now... double attr_one = PyFloat_AsDouble(attr_one_obj); printf("%f\\n",attr_one); } } """ weave.inline(code,['myobjects','rows','cols'],local_dict=locals(),verbose=1) test_list = [[MyObject(0.0),MyObject(1.0)],[MyObject(2.0),MyObject(3.0)]] test_loop(test_list) From clp at rebertia.com Thu Sep 4 18:47:00 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 4 Sep 2008 15:47:00 -0700 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <g9pn28$4u1$1@ger.gmane.org> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> Message-ID: <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> On Thu, Sep 4, 2008 at 3:37 PM, Robert Dailey <rcdailey at gmail.com> wrote: > On Thu, Sep 4, 2008 at 5:21 PM, Fredrik Lundh <fredrik at pythonware.com> > wrote: >> >> Robert Dailey wrote: >> >>> I currently have a dictionary object that I'm doing the following with: >>> >>> if lib not in stage_map: >>> # ... do stuff ... >>> >>> However, this will perform a case-sensitive comparison between lib and >>> each key in stage_map. Is there a way to make this do a case-insensitive >>> comparison instead? >> >> dictionary lookups use the exact value. to make a case-insensitive >> lookup, use key.lower() instead of key when creating the dictionary, and >> then do >> >> if lib.lower() not in state_map: >> ... > > So you're saying to ensure that stage_map's keys are initially lower-case to > begin with? Well, I can't do this either since the case of the keys is > actually valuable later on. It's only for the purposes of this specific > comparison operation that the case should be ignored. Then store the string in its original case in the value part of the key-value pair: stage_map[key.lower()] = (key,whatever) - Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From blogmoney.bm at gmail.com Fri Sep 26 01:16:08 2008 From: blogmoney.bm at gmail.com (blogmoney) Date: Thu, 25 Sep 2008 22:16:08 -0700 (PDT) Subject: ==== XXX--SECRET Web Cams LADIES HOSTELS ====== Message-ID: <b4f12a2b-8e9f-488d-bbab-7499e2355d1f@v13g2000pro.googlegroups.com> Hi....Friends, watch and enjoy SECRET WEB-CAMS at LADIES HOSTELS and INTERNET CAFE SEX SCANDALS VIDEOS... ** HOT Sexy Girls Nude Video's ** ** Porn Video's ** ** Nude Sexy For Mega Size Big Boobs ** Lesbian ** ** Gay ** Lesbian ** Data Sex ** Pay Sex's *** www.onlinejobszone.blogspot.com www.sfimoney4all.blogspot.com www.yogatips4all.blogspot.com www.hollywoodspicyzone.blogspot.com http://onlinemoney2u.wordpress.com www.onlinejobs4all.googlepages.com From ppearson at nowhere.invalid Tue Sep 23 11:14:18 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 23 Sep 2008 15:14:18 GMT Subject: Docstrings for class attributes References: <mailman.1392.1222147427.3487.python-list@python.org> Message-ID: <6jsfeaF4pbs9U1@mid.individual.net> On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris <celephicus at gmail.com> wrote: > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. [snip] Commiserating, not helping: I have a similar problem with a module that holds values of physical constants, http://webpages.charter.net/curryfans/peter/nature.py: boltzmanns_constant = 1.380622e-16 * erg / k stefan_boltzmann_constant = 5.66961e-5 * erg/s/cm/cm/k/k/k/k gravitational_constant = 6.6732e-8 * erg*cm/g/g I would like to reveal more details with, e.g., help( gravitational_constant ) . . . and maybe then I could use shorter names. -- To email me, substitute nowhere->spamcop, invalid->net. From squishywaffle at gmail.com Wed Sep 24 15:31:37 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Wed, 24 Sep 2008 12:31:37 -0700 (PDT) Subject: Folder Actions on Mac OSX Leopard? Message-ID: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> Greetings, I've been trying to figure out if it's possible to attach a Python script to an action via Mac OSX Leopard's File Actions system. I'm wanting to call a Python script every time a file is added to the monitored folder. Just adding a .py file doesn't seem to do anything at all, and I can't find any log output anywhere to see what's going on. I'm more just looking to see if this is or is not possible. I'm not interested in other solutions, as I already have them lined up in case this is a no-go, but I'd really love to be able to do it this way if anyone has any experience. Googling around revealed pretty much nothing. Any help is much appreciated, Greg From nick at craig-wood.com Thu Sep 4 04:35:52 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 04 Sep 2008 03:35:52 -0500 Subject: use str as variable name References: <mailman.460.1220513147.3487.python-list@python.org> Message-ID: <slrngbv5sq.jr7.nick@irishsea.home.craig-wood.com> Mathieu Prevot <mathieu.prevot at gmail.com> wrote: > Hi, > > I have a program that take a word as argument, and I would like to > link this word to a class variable. > > eg. > class foo(): > width = 10 > height = 20 > > a=foo() > arg='height' > a.__argname__= new_value Not quite sure what the above is supposed to achieve > rather than : > > if arg == 'height': > a.height = new_value > elif arg == 'width'; > a.width = new_value > > Can I do this with python ? How ? setattr(a, arg, new_value) See: http://docs.python.org/lib/built-in-funcs.html -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From execrable at gmail.com Wed Sep 10 12:51:03 2008 From: execrable at gmail.com (B) Date: Wed, 10 Sep 2008 09:51:03 -0700 Subject: dict slice in python (translating perl to python) In-Reply-To: <mailman.804.1221065237.3487.python-list@python.org> References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> <HDSxk.1411$ZY5.32@newsfe02.iad> <mailman.804.1221065237.3487.python-list@python.org> Message-ID: <XVSxk.103$_u2.8@newsfe08.iad> Fredrik Lundh wrote: > B wrote: >> for a long list, you could try: >> result = [mydict[k] for k in mydict] >> or [mydict[k] for k in mydict.keys()] >> or [mydict[k] for k in mydict.iterkeys()] > > and the point of doing that instead of calling mydict.values() is what? > > </F> > It's more fun? Or if you want to sort by keys. From candide at free.invalid Sat Sep 20 05:23:39 2008 From: candide at free.invalid (candide) Date: Sat, 20 Sep 2008 11:23:39 +0200 Subject: Not fully OO ? Message-ID: <48d4c11b$0$22877$426a74cc@news.free.fr> Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : "About Python: Python is a high level scripting language with object oriented features. (...) Python supports OOP and classes to an extent, but is not a full OOP language." Thanks for any comment. From gnewsg at gmail.com Wed Sep 17 16:53:44 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 17 Sep 2008 13:53:44 -0700 (PDT) Subject: ssl server References: <eef6d1fa-12e6-4549-a85e-c0ba21b19c63@25g2000hsx.googlegroups.com> Message-ID: <7ac8d302-0dae-4f19-81a9-8926c6b22a01@26g2000hsk.googlegroups.com> On 17 Set, 19:33, Seb <sebastianthegreat... at gmail.com> wrote: > I'm making a ssl server, but I'm not sure how I can verify the > clients. What do I actually need to place in _verify to actually > verify that the client cert is signed by me? > > ?50 class SSLTCPServer(TCPServer): > ?51 ? ? ? ? keyFile = "sslcert/server.key" > ?52 ? ? ? ? certFile = "sslcert/server.crt" > ?53 ? ? ? ? def __init__(self, server_address, RequestHandlerClass): > ?54 ? ? ? ? ? ? ? ? ctx = SSL.Context(SSL.SSLv23_METHOD) > ?55 ? ? ? ? ? ? ? ? ctx.use_privatekey_file(self.keyFile) > ?56 ? ? ? ? ? ? ? ? ctx.use_certificate_file(self.certFile) > ?57 ? ? ? ? ? ? ? ? ctx.set_verify(SSL.VERIFY_PEER | > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > self._verify) > ?58 ? ? ? ? ? ? ? ? ctx.set_verify_depth(10) > ?59 ? ? ? ? ? ? ? ? ctx.set_session_id('DFS') > ?60 > ?61 ? ? ? ? ? ? ? ? self.server_address = server_address > ?62 ? ? ? ? ? ? ? ? self.RequestHandlerClass = RequestHandlerClass > ?63 ? ? ? ? ? ? ? ? self.socket = socket.socket(self.address_family, > self.socket_type) > ?64 ? ? ? ? ? ? ? ? self.socket = SSL.Connection(ctx, self.socket) > ?65 ? ? ? ? ? ? ? ? self.socket.bind(self.server_address) > ?66 ? ? ? ? ? ? ? ? self.socket.listen(self.request_queue_size) > ?67 > ?68 ? ? ? ? def _verify(self, conn, cert, errno, depth, retcode): > ?69 ? ? ? ? ? ? ? ? return not cert.has_expired() and > cert.get_issuer().organizationName == 'DFS' What library are you using? PyOpenSSL? In that case I think you'll have more luck by posting on their mailing list. --- Giampaolo http://code.google.com/p/pyftpdlib/ From code at pizzashack.org Tue Sep 2 18:15:07 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 18:15:07 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> Message-ID: <20080902221507.GS29228@dragontoe.org> On Tue, Sep 02, 2008 at 05:22:51PM -0300, Gabriel Genellina wrote: > > The name popen is an abbreviation of "pipe open" -- the function, and > > the class, open pipes to communicate with another process. What you > > said is correct; however there are numerous other ways to open > > subprocesses. The focus of popen is the communication aspect -- the > > opening and control of the pipes -- not the subprocess. That's the > > key difference between popen() and all the other methods of starting a > > subprocess. > > Totally irrelevant here - we are talking about the subprocess > module, not the popen C function. I was talking about both actually. I can't agree that it's not relevant... The Popen class clearly takes its name from the function of the same name, and does exactly the same thing (plus what pclose() does, plus saving the pid of the forked process). Seems pretty relevant to me. > >> > The C library's popen() function, on which this class is based, > > No, subprocess.Popen does not use -directly or indirectly- the C > popen function. It uses fork or CreateProcess in Windows. I didn't say it used it. I said it was based on it. It is (conceptually). > > The Linux man page unfortunately copies (verbatim) the FreeBSD man > > page, which gets it wrong. You can not open a process, but you can > > definitely open a pipe. > > (Ok, if it doesn't agree with you, it must be wrong) See my last post for accreditation of my comment. A common argumentation tactic of the closed-minded and the small-minded is to resort to insinuation to attack the validity of other's comments without providing any basis for doing so. Nice job. > Classes represent "things", and class names should be nouns. Is that a law? Classes are instantiated by invoking their class names as a function call -- the computing equivalent of a verb. Why then, must they be named as nouns? Can you not, in fact, have classes which describe (or model) actions? Wouldn't you name them using verbs if you did? That said, this is the most valid point anyone has made... You should have made it when the module was being designed. :-D My point is, if you don't think Popen is a good name for the class, that's your opinion, but it is only that: an opinion. Yet some of you state your case as if it is incontrovertable fact. I've given a good case as to why it IS a good name (one which I genuinely support), and disagree as you may, none of the points any of you have made invalidate or even weaken my argument. Lastly, the maintainers obviously thought it was a good name when they included it... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/ccc1bc0f/attachment.sig> From Lie.1296 at gmail.com Sun Sep 28 07:12:45 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 04:12:45 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <gbn6nu$r5j$4@lust.ihug.co.nz> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> Message-ID: <6f247162-b0b7-4fba-bfd8-df9261cc5d30@p31g2000prf.googlegroups.com> On Sep 28, 3:35?pm, est <electronix... at gmail.com> wrote: > > Because that's how ASCII is defined. > > Because that's how ASCII is defined. ?ASCII is a 7-bit code. > > Then why can't python use another default encoding internally > range(256)? > > > Python refuses to guess and tries the lowest common denominator -- ASCII -- instead. > > That's the problem. ASCII is INCOMPLETE! What do you propose? Use mbsc and smack out linux computers? Use KOI and make non-Russians suicide? Use GB and shot dead non-Chinese? Use latin-1 and make emails servers scream? > If Python choose another default encoding which handles range(256), > 80% of python unicode encoding problems are gone. > > It's not HARD to process unicode, it's just python & python community > refuse to correct it. Python's unicode support is already correct. Only your brainwave have not been tuned to it yet. > > stop dreaming of a magic solution > > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, > what's wrong???? > > > Isn't that more or less the same as telling the OP to use unicode() instead of str()? > > sockets could handle str() only. If you throw unicode objects to a > socket, it will automatically call str() and cause an error. From rpdooling at gmail.com Wed Sep 3 08:27:20 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Wed, 3 Sep 2008 05:27:20 -0700 (PDT) Subject: new python docs Message-ID: <62c0c392-d4e1-4cae-aae0-38d35c4faf57@w7g2000hsa.googlegroups.com> Wow! I've been away in other pursuits. The new docs are gorgeous and searchable. http://docs.python.org/dev/index.html Thank you, python.org. From castironpi at gmail.com Tue Sep 16 17:33:09 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 14:33:09 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> <a860c259-c932-4588-ae2d-7ba6f2d3eb17@e53g2000hsa.googlegroups.com> <99c53e1a-a693-4f35-b937-d172c565077c@m36g2000hse.googlegroups.com> Message-ID: <0a99ca77-d4c3-40af-af5e-91f2f5a52a9e@f63g2000hsf.googlegroups.com> On Sep 16, 4:24?pm, cnb <circularf... at yahoo.se> wrote: > On Sep 16, 10:53?pm, "Aaron \"Castironpi\" Brady" > > > > <castiro... at gmail.com> wrote: > > On Sep 16, 3:16?pm, cnb <circularf... at yahoo.se> wrote: > > > > On Sep 16, 7:49?pm, "Aaron \"Castironpi\" Brady" > > > > > Now I have my personal programs in C:/Python25/Progs/ > > > > > > How do I add so that I can just do "import somefile" from anywhere in > > > > > that directory in the interpreter and it can load files from other > > > > > folders in that directory. > > > > > Add a file: \Lib\site-packages\locals.pth > > > > > with contents, path to the directory you want to add (/python25/progs/) > > > > And we have a winner! > > > > Now it works. Both doing import and loading form fiel with C-c C-l > > > > However jsut including C:/Python/Progs wasn't enough. I had to add the > > > folder inside that that contains the files i needed. > > > > so how do i add all files within progs? is there something like C:/ > > > python25/progs/* ? > > > You have: > > > c:/python/progs/abc/filea.py > > c:/python/progs/abc/fileb.py > > c:/python/progs/def/filed.py > > c:/python/progs/def/filee.py > > > __init__.py in progs ? (empty...) > > __init__.py in abc > > __init__.py in def > > > c:/python/site-packages/lib/locals.py ?which contains: > > c:/python/progs/ > > > You don't need the subdirectories. ?You can do: > > > import abc > > import abc.filea > > from abc import filea > > no I can't... Ok well here's mine: I have /Documents and Settings/usr/Desktop/working/imptest/ in locals.pth. These directories: Directory of C:\Documents and Settings\usr\Desktop\working\imptest 09/16/2008 04:29 PM <DIR> impt Directory of C:\Documents and Settings\usr\Desktop\working\imptest \impt 09/16/2008 04:29 PM <DIR> abc 09/16/2008 04:29 PM <DIR> defg 09/16/2008 03:40 PM 0 __init__.py 1 File(s) 0 bytes Directory of C:\Documents and Settings\usr\Desktop\working\imptest \impt\abc 09/16/2008 03:40 PM 13 abcmod.py 09/16/2008 03:40 PM 0 __init__.py Directory of C:\Documents and Settings\usr\Desktop\working\imptest \impt\defg 09/16/2008 03:40 PM 13 defmod.py 09/16/2008 03:40 PM 0 __init__.py and this code: >>> import impt >>> import impt.abc >>> import impt.abc.abcmod >>> import impt.defg >>> import impt.defg.defmod I understand the import behavior will change in 3.0. From half.italian at gmail.com Fri Sep 26 14:35:11 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 26 Sep 2008 11:35:11 -0700 (PDT) Subject: how to search multiple textfiles ? References: <mailman.1536.1222436146.3487.python-list@python.org> Message-ID: <a1ed03f4-6756-4336-bafa-629b35dc6782@z6g2000pre.googlegroups.com> On Sep 26, 6:35?am, Stef Mientki <s.mien... at ru.nl> wrote: > hello, > > I want to search multiple textfiles (python source files) for a specific > word. > I can find all files, open them and do a search, > but I guess that will be rather slow. > > I couldn't find any relevant information through google. > > Does anyone know of a search library that performs this task fast ? > > If it indeed only concerns py-files, > is there another way of searching words ? > ( I could imagine that such a "py-only-search" would have benefits, > because you could set a flag to see the words in comment yes or no ) > > thanks, > Stef Mientki > > Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. > The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629. I use 'fgrep' ie... `fgrep -r "toFind" /source` ~Sean From m_palmer45 at yahoo.ca Wed Sep 17 19:05:51 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 17 Sep 2008 16:05:51 -0700 (PDT) Subject: ssl server References: <eef6d1fa-12e6-4549-a85e-c0ba21b19c63@25g2000hsx.googlegroups.com> Message-ID: <72ed03e9-e3cd-4feb-ac5c-41f9ee1f5458@y21g2000hsf.googlegroups.com> On Sep 17, 1:33 pm, Seb <sebastianthegreat... at gmail.com> wrote: > I'm making a ssl server, but I'm not sure how I can verify the > clients. What do I actually need to place in _verify to actually > verify that the client cert is signed by me? > > 50 class SSLTCPServer(TCPServer): > 51 keyFile = "sslcert/server.key" > 52 certFile = "sslcert/server.crt" > 53 def __init__(self, server_address, RequestHandlerClass): > 54 ctx = SSL.Context(SSL.SSLv23_METHOD) > 55 ctx.use_privatekey_file(self.keyFile) > 56 ctx.use_certificate_file(self.certFile) > 57 ctx.set_verify(SSL.VERIFY_PEER | > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > self._verify) > 58 ctx.set_verify_depth(10) > 59 ctx.set_session_id('DFS') > 60 > 61 self.server_address = server_address > 62 self.RequestHandlerClass = RequestHandlerClass > 63 self.socket = socket.socket(self.address_family, > self.socket_type) > 64 self.socket = SSL.Connection(ctx, self.socket) > 65 self.socket.bind(self.server_address) > 66 self.socket.listen(self.request_queue_size) > 67 > 68 def _verify(self, conn, cert, errno, depth, retcode): > 69 return not cert.has_expired() and > cert.get_issuer().organizationName == 'DFS' If I were you, I would just just hide behind apache, nginx oder another server that does ssl. just have that server proxy locally to your python server over http, and firewall the python server port. From bdesth.quelquechose at free.quelquepart.fr Thu Sep 18 14:43:00 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 18 Sep 2008 20:43:00 +0200 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <48d2bd22$0$4514$426a74cc@news.free.fr> Alexzive a ?crit : > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? A couple ones have been submitted. Harald gets a point about the redundant tests (even if his solution seems to be broken, cf below) - your inner loop should have looked like : for j in xrange(i+1, len(IN)) Now the obvious winner is pruebono - even unoptimized, using sets seems to be *way* faster than even the most optimized corrected version of your algorithm. Here's a quick bench - please everyone doublecheck it to make sure it's ok: from timeit import Timer import random class Node(object): def __init__(self, x, y): self.coordinates = (x, y) def __repr__(self): return repr(self.coordinates) # how to build src: # src = [(random.randrange(10),random.randrange(10)) for x in xrange(100)] src = [ (4, 9), (5, 0), (6, 6), (7, 2), (3, 6), (9, 6), (0, 1), (1, 6), (0, 5), (1, 2), (8, 9), (5, 4), (1, 6), (7, 6), (9, 1), (7, 6), (0, 1), (7, 4), (7, 4), (8, 4), (8, 4), (3, 5), (9, 6), (6, 1), (3, 4), (4, 5), (0, 5), (6, 3), (2, 4), (1, 6), (9, 5), (1, 2), (5, 8), (8, 5), (3, 1), (9, 4), (9, 4), (3, 3), (4, 8), (9, 7), (8, 4), (6, 2), (1, 5), (5, 8), (8, 6), (0, 8), (5, 2), (3, 4), (0, 5), (4, 4), (2, 9), (7, 7), (1, 0), (4, 2), (5, 7), (0, 4), (2, 5), (0, 8), (7, 3), (9, 1), (0, 4), (5, 0), (4, 9), (0, 6), (3, 0), (3, 0), (3, 9), (8, 3), (7, 9), (8, 5), (7, 6), (1, 5), (0, 6), (5, 9), (6, 8), (0, 0), (4, 1), (3, 3), (5, 4), (5, 3), (6, 1), (5, 4), (4, 5), (5, 8), (4, 1), (3, 6), (1, 9), (0, 5), (6, 5), (5, 5), (6, 0), (0, 9), (2, 6), (0, 7), (5, 9), (7, 3), (7, 9), (5, 4), (4, 9), (2, 9) ] IN = [Node(x, y) for x, y in src] def doubles0(): SN = [] for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): #print i, j if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i]) return SN def doubles1(): "first solve an algoritmic problem" SN = [] for i in range(len(IN)): for j in range(i+1, len(IN)): #print i, j #if i != j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i]) return SN def doubles2(): "then avoid buildin useless lists" SN = [] for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i]) return SN def doubles3(): "then avoid uselessly calling a constant operation" SN = [] in_len = len(IN) for i in xrange(in_len): for j in xrange(i+1, in_len): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i]) return SN def doubles4(): "then alias commonly used methods" SN = [] sn_append = SN.append in_len = len(IN) for i in xrange(in_len): for j in xrange(i+1, in_len): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: sn_append(IN[i]) return SN def doubles5(): "then alias a couple other things" SN = [] sn_append = SN.append in_len = len(IN) for i in xrange(in_len): node_i = IN[i] coords_i = node_i.coordinates for j in xrange(i+1, in_len): if coords_i[0] == IN[j].coordinates[0]: if coords_i[1] == IN[j].coordinates[1]: sn_append(node_i) return SN def doubles6(): "then simplify tests" SN = [] sn_append = SN.append in_len = len(IN) for i in xrange(in_len): node_i = IN[i] coords_i = node_i.coordinates for j in xrange(i+1, in_len): if coords_i == IN[j].coordinates: sn_append(node_i) return SN # Harald : uncomment this and run test_results. As far as I can tell, it # doesn't yields the expected results ## IN7 = IN[:] ## def sortk7(n): ## return n.coordinates[0] ## def doubles7(): ## "is ordering better ? - Nope Sir, it's broken..." ## IN7.sort(key=sortk) ## SN = [] ## sn_append = SN.append ## in_len = len(IN) ## for i in xrange(in_len): ## node_i = IN[i] ## coords_i = node_i.coordinates ## for j in xrange(i+1, in_len): ## if coords_i[0] == IN[j].coordinates[0]: ## if coords_i[1] == IN[j].coordinates[1]: ## sn_append(node_i) ## else: ## break ## return SN def doubles8(): "Using a set ?" dup = set() SN = [] for item in IN: c = item.coordinates if c in dup: SN.append(item) else: dup.add(c) return SN def doubles9(): "Using a set is way faster - but can still be improved a bit" dup = set() dup_add = dup.add SN = [] sn_append = SN.append for item in IN: c = item.coordinates if c in dup: sn_append(item) else: dup_add(c) return SN # need this for tests: names_funcs = sorted( (n, f) for n, f in locals().iteritems() if n.startswith('doubles') ) def test_results(): """ make sure all solutions give correct results, assuming the OP solution is at least correct !-) """ results = [ (n, set(o.coordinates for o in f())) for n, f in names_funcs ] _, correct = results[0] ok = True for n, r in results[1:]: if r != correct: print "error on %s ?\n expected %s\n, got %s" \ % (n, correct, r) ok = False return ok def test_times(): " And the winner is..." results = [ (n, Timer( '%s()' % n, 'from __main__ import %s' % n ).timeit(100) ) for n, _ in names_funcs ] print "\n".join("%s : %s" % r for r in results) Results here (py2.5, gentoo linux, athlonxp1800, 512 ram): >>> test_results() True >>> test_times() doubles0 : 1.55667901039 doubles1 : 0.719144105911 doubles2 : 0.703393936157 doubles3 : 0.700654983521 doubles4 : 0.706257104874 doubles5 : 0.528184890747 doubles6 : 0.461633205414 doubles8 : 0.0134379863739 doubles9 : 0.0108540058136 >>> Not surprisingly, half less iterations makes for half less time. Aliasing, as often, proves to be a good optimization too. But obviously, using the correct data structure / algorithm combo is the key : simpler code, and 115 times faster (143 times with aliasing). If pruebono solution's is correct (and it as AFAICT), your 15 hours computation should by now take less than 10 minutes... From steven at REMOVE.THIS.cybersource.com.au Sun Sep 28 19:06:58 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 23:06:58 GMT Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> Message-ID: <pan.2008.09.28.23.06.57@REMOVE.THIS.cybersource.com.au> On Sun, 28 Sep 2008 17:47:44 -0400, Terry Reedy wrote: > Aaron "Castironpi" Brady wrote: >> On Sep 28, 2:52 am, Steven D'Aprano <st... at REMOVE-THIS- > >>> As for why the complicated version works, it may be clearer if you >>> expand it from a one-liner: >>> >>> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) >>> >>> inner = lambda: n >>> outer = lambda n: inner >>> f[n] = outer(n) >>> >>> outer(0) => inner with a local scope of n=0 outer(1) => inner with a >>> local scope of n=1 etc. > > For this to work, the 'expansion' has to be mental and not actual. Which > is to say, inner must be a text macro to be substituted back into outer. Er, yes, that's what I meant, sorry for not being more explicit. That's why it wasn't a copy and paste of actual running code. Or perhaps I just confused myself and was talking nonsense. -- Steven From ssharkey at linuxunlimited.com Thu Sep 25 16:45:55 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Thu, 25 Sep 2008 16:45:55 -0400 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: <6k2aqqF5p185U1@mid.uni-berlin.de> References: <mailman.1506.1222370612.3487.python-list@python.org> <QQRCk.1802$Pv5.235@edtnps83> <6k2aqqF5p185U1@mid.uni-berlin.de> Message-ID: <48DBF883.6000909@linuxunlimited.com> Diez B. Roggisch wrote: > Dmitry S. Makovey schrieb: >> Scott Sharkey wrote: >>> Any insight into the best way to have a consistent, repeatable, >>> controllable development and production environment would be much >>> appreciated. >> >> you have just described OS package building ;) Except that we do need multiple different environments on one server, and also have issues where our servers may be Windows. >> I can't speak for everybody, but supporting multiple platforms (PHP, Perl, >> Python, Java) we found that the only way to stay consistent is to use OS >> native packaging tools (in your case apt and .deb ) and if you're missing >> something - roll your own package. After a while you accumulate plenty of >> templates to chose from when you need yet-another-library not available >> upstream in your preferred package format. Remember that some python tools >> might depend on non-python packages, so the only way to make sure all that >> is consistent across environment - use unified package management. > > That this is a desirable goal can't be argued against. Yet two big hurdles make it often impractical to be dogmatic about that: > > - different OS. I for one don't know about a package management tool for windows. And while our servers use Linux (and I as developer as well), all the rest of our people use windows. No use telling them to apt-get instal python-imaging. Exactly! > - keeping track of recent developments. In the Python webframework world for example (which the OP seems to be working with), things move fast. Or extremly slow, regarding releases. Take Django - until 2 month ago, there hasn't been a stable release for *years*. Virtually everybody was working with trunk. And given the rather strict packaging policies of debian and consorts, you'd be cut off of recent developments as well as of bugfixes. Very much the case. Most of debian's packages for python are woefully out of date, it seems. And then we're at the whim of the os provider as to when updates happen, rather than being controlled by our staff. I am very interested in the eggbasket project - that's something that's been needed for a while. And I'm aware of the setuptools fork, and the discussion on the distutils sig mailing list. Thanks. -Scott From sturlamolden at yahoo.no Tue Sep 23 15:49:45 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 12:49:45 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <d086d0b2-0624-45ee-b72f-49d88a7dfe33@79g2000hsk.googlegroups.com> <c5e8ae40-9ed6-41c9-8914-4a3d0f001f0c@m36g2000hse.googlegroups.com> <mailman.1423.1222197466.3487.python-list@python.org> Message-ID: <c124d367-bf08-42cf-934a-592a723c73ea@e53g2000hsa.googlegroups.com> On Sep 23, 9:17?pm, Robert Kern <robert.k... at gmail.com> wrote: > You could also drop it on the scipy.org wiki in the Cookbook category. Yes, if I could figure out how to use it... From stava at telcotec.se Mon Sep 29 02:58:30 2008 From: stava at telcotec.se (Lars Stavholm) Date: Mon, 29 Sep 2008 08:58:30 +0200 Subject: python for *nix system admins In-Reply-To: <48DDE92D.6090405@telcotec.se> References: <48DDE92D.6090405@telcotec.se> Message-ID: <48E07C96.9080003@telcotec.se> Thank you all for your input. /Lars Lars Stavholm wrote: > Hi All, > > I'm new to this list and hoping that this is not off-topic. > If it is, please point me in the right direction. > > I seem to recollect a python module or library for *nix sysadmins, > but I can't for the life of me find it again. > > The module (or library) somehow added unix command capabilities > to the python language. It seemed like a lesser known, perhaps new, > python library or module. > > Any input or ideas appreciated > /Lars Stavholm > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Fri Sep 19 05:21:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 06:21:56 -0300 Subject: Intercepting printed strings References: <496954360809181524g6037e0b0x84e98834bbf8ad9c@mail.gmail.com> Message-ID: <op.uhp1mu0ux6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 18 Sep 2008 19:24:26 -0300, Robert Dailey <rcdailey at gmail.com> escribi?: > I'm currently using Python 3.0 b3 and I'm curious as to how I can go > about > intercepting things send to print() for some intermediate processing > before > they're actually sent to sys.stdout. Right now I've thought of the > following: > > Replace sys.stdout with a class named PrintStream. PrintStream is > defined as > follows: > > class PrintStream: > def write( self, message ): > sys.__stdout__.write( '\t{0}'.format( message ) ) > > Will this work? Basically I want to add a tab character in front of every > message printed. Thanks. Why don't you try it yourself? You may replace builtins.print with your own function too. It's not exactly the same thing, but given your request "intercepting things send to print() before they're sent to sys.stdout" it may be more adequate. -- Gabriel Genellina From kyosohma at gmail.com Thu Sep 4 09:27:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Sep 2008 06:27:56 -0700 (PDT) Subject: path slashes cleaning References: <mailman.484.1220534735.3487.python-list@python.org> Message-ID: <e815a0ed-f42e-4c60-8911-46de4f1169f0@t1g2000pra.googlegroups.com> On Sep 4, 8:25?am, "Mathieu Prevot" <mathieu.pre... at gmail.com> wrote: > Hi, > > for scripts that take arguments, I would like to remove the trailing > slash if it's present. > > Is there something else than: > > a='/usr/local/lib/' > if a[-1] == '/': > ? a = list(a) > ? a.pop() > ? ''.join(a) > > Thanks, > Mathieu How about this: if a[-1] == '/': a = a[:-1] Mike From paul at boddie.org.uk Thu Sep 11 17:55:09 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 11 Sep 2008 14:55:09 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> <pan.2008.09.11.07.40.08@REMOVE.THIS.cybersource.com.au> <mailman.854.1221122089.3487.python-list@python.org> <823435cf-a557-48d9-9e16-fa28e745e67a@73g2000hsx.googlegroups.com> <8f9a61c9-55d7-4a1e-a4f1-9dda6a5d2b31@59g2000hsb.googlegroups.com> Message-ID: <47de9bd7-755e-45fb-b35b-72ebf4d52753@d77g2000hsb.googlegroups.com> On 11 Sep, 19:31, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > > An acquaintance suggests that defragmentation would be a useful > service to provide along with memory management too, which also > requires an index. I presume that you mean efficient access to large amounts of data in the sense that if all the data you want happens to be in the same page or segment, then retrieving it is much more efficient than having to seek around for all the different pieces. So the defragmentation would be what they call clustering in a relational database context: http://www.postgresql.org/docs/8.3/static/sql-cluster.html I've seen similar phenomena outside the relational database world, notably with big Lucene indexes which wouldn't fit in memory in their entirety. > I encourage overlap between a bare-bones alloc/free module and > established database territory and I'm very aware of it. > > Databases already support both concurrency and persistence, but don't > tell me you'd use a database for IPC. Of course, databases are widely used in scalable systems to hold central state, which is why there's a lot of effort put into to not only scaling up database installations, but also into things like caching which are supposed to save the database systems behind popular Web applications from excessive load. > And don't tell me you've never > wished you had a reference to a record in a table so that you could > make an update just by changing one word of memory at the right > place. Sometimes databases are overkill where all you want is dynamic > allocation. I think that the challenge is to reduce an abstract operation (for example, wanting to update a particular column in a particular record) to its measurable effects (this word of memory/disk will change as a consequence). It's easy for a human with a reasonable knowledge of, say, a relational database system to anticipate such things, but to actually collapse a number of layers through some kind of generic optimisation process is a lot more difficult. Paul From grante at visi.com Tue Sep 23 10:52:16 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 23 Sep 2008 09:52:16 -0500 Subject: Attachment Size and SMTP EMail References: <a2747a10-ecd6-4254-922e-59e8a2784c3b@m3g2000hsc.googlegroups.com> Message-ID: <aM-dneOKGd09n0TVnZ2dnUVZ_r7inZ2d@posted.visi> On 2008-09-23, Eric E <eric.e.janke at gmail.com> wrote: > I am using python to send an email with a large zip file as an > attachment. I successfully sent a 52M attachment. If I try > to send a 63M attachment or larger, the message never gets > through. I do not get any errors in my python code. Does sending large attachements with other SMTP clients using the same SMTP server work? -- Grant Edwards grante Yow! Zippy's brain cells at are straining to bridge visi.com synapses ... From enleverlesX.XmcX at XmclaveauX.com Fri Sep 26 09:58:02 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 26 Sep 2008 15:58:02 +0200 Subject: how to search multiple textfiles ? In-Reply-To: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> References: <mailman.1536.1222436146.3487.python-list@python.org> <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> Message-ID: <48dcecea$0$910$ba4acef3@news.orange.fr> Hi! On Windows, you can use the (standard) command findstr Example: findstr /n /s /I strsearched *.py @-salutations -- Michel Claveau From cs at zip.com.au Mon Sep 22 00:32:17 2008 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 22 Sep 2008 14:32:17 +1000 Subject: Why are "broken iterators" broken? In-Reply-To: <gb5t65$k2$1@ger.gmane.org> Message-ID: <20080922043217.GA10077@cskk.homeip.net> On 21Sep2008 18:36, Fredrik Lundh <fredrik at pythonware.com> wrote: > Roy Smith wrote: >> There are plausible examples of collections which grow while you're >> iterating over them. I'm thinking specifically of a queue in a >> multi-threaded application. One thread pushes work onto the back of >> the queue while another pops from the front. The queue could certainly >> go empty at times. But, maybe a Python iterator is just the wrong way >> to model such behavior. > > you probably want the consumer thread to block when it catches up with > the producer, rather than exit. > (that's the default behaviour of Python's Queue object, btw) It sounds like he wants non-blocking behaviour in his consumer. A common example is "try to gather a lot of stuff into a single packet, but send a smaller packet promptly if there isn't much stuff". You could make the next() method return a sentinal value like None when the queue is empty. That would mean your consumer must recognise the special value and also precludes delivering that value through the queue. I'm not convinced my suggestion here is any better than just doubling up every call to next() with an empty() check immediately beforehand. You could write a trivial wrapping generator to take the original blocking queue and return a sentinel value on empty, too. My suggestion is also an excellent way of getting programs that fail-busy (i.e. they spin out) if you make a logic error in your consumer. Ouch. Cheers, -- Cameron Simpson <cs at zip.com.au> DoD#743 http://www.cskk.ezoshosting.com/cs/ Kill, v.t. To create a vacancy without nominating a successor. Ambrose Bierce (1842-1914), U.S. author. The Devil's Dictionary (1881-1906). From george.sakkis at gmail.com Sun Sep 28 06:19:45 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 28 Sep 2008 03:19:45 -0700 (PDT) Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> <Mo7Dk.2064$T65.1885@edtnps82> <48dd5c06$0$26425$426a74cc@news.free.fr> <WvdDk.2157$T65.1610@edtnps82> <f6351d10-2573-4a5c-ab57-d4dd1c7b311c@e53g2000hsa.googlegroups.com> <YKjDk.2022$Pv5.1949@edtnps83> <a7a895ef-ff22-4dc8-8213-97482e5bb19f@z72g2000hsb.googlegroups.com> <c7db7b82-7350-4365-8c12-40f949e739ea@u65g2000hsc.googlegroups.com> <91e62d70-73fb-4ecc-ae2e-d950a5f7ea6b@k13g2000hse.googlegroups.com> <T_CDk.2342$Pv5.396@edtnps83> Message-ID: <877b889b-c385-4e2b-abe9-17669eca09b8@d70g2000hsc.googlegroups.com> On Sep 27, 11:38?pm, "Dmitry S. Makovey" <dmi... at makovey.net> wrote: > George Sakkis wrote: > > It's funny how often you come with a better solution a few moments > > after htting send! The snippet above can (ab)use the decorator syntax > > so that it becomes: > > > class A(Proxy): > > > ? ? @ProxyMethod > > ? ? def bmethod(self): > > ? ? ? ? return self.b1 > > > ? ? @ProxyMethod > > ? ? def bmethod2(self): > > ? ? ? ? return self.b2 > > That is outstanding! FYI, in case you missed it the final version doesn't need a Proxy base class, just inherit from object. Also lowercased ProxyMethod to look similar to staticmethod/classmethod: class A(object): def __init__(self, b1, b2): self.b1 = b1 self.b2 = b2 @proxymethod def bmethod(self): return self.b1 @proxymethod def bmethod2(self): return self.b2 George From bearophileHUGS at lycos.com Tue Sep 2 17:38:51 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 2 Sep 2008 14:38:51 -0700 (PDT) Subject: Renumbering References: <mailman.386.1220389036.3487.python-list@python.org> <4e6091af-bc00-4408-beda-adfa7f17dc63@b30g2000prf.googlegroups.com> Message-ID: <d98b8933-5da9-4936-bb30-9c29fbc962d5@x35g2000hsb.googlegroups.com> John Machin: > Is this homework? Have you put any effort into trying to write a script > yourself? Etc etc etc You are right, I am sorry -.- Bye, bearophile From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 06:36:38 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 12:36:38 +0200 Subject: BadStatusLine: In-Reply-To: <4e3d5d97-1b5f-4593-9c33-ad8b57d59b05@f36g2000hsa.googlegroups.com> References: <4e3d5d97-1b5f-4593-9c33-ad8b57d59b05@f36g2000hsa.googlegroups.com> Message-ID: <48d77535$0$2237$426a74cc@news.free.fr> noelob a ?crit : > Hi All, > > During performance testing of my web application, I occasionally get a > BadStatusLine exception from httplib. Reading > http://docs.python.org/lib/module-httplib.html#l2h-4021 tells me that > it's "Raised if a server responds with a HTTP status code that we > don't understand." Is there a way to find what the actual status code > returned was? I.e. the value that caused the exception to be thrown? > Under what circumstances is a BadStatusLine normally thrown? (e.g. > data corruption?) httplib is a pure-python module, so nothing prevents you from reading the source code to get more accurate informations. It appears that this exception is raised when: - the status line is empty - the 'strict' flag is on and the status line didn't start with 'HTTP/' - the 'status' part of the status line is not convertible to an int - the status code ('status' part of the status line, converted to an int) is lower than 100 or higher than 999 NB: I may have missed something... In all cases, the offending status line is accessible as either .line and .args attribute of the exception. > I'm quite new to python, but not to programming. Apologies if this is > a silly question ;) Well... Not a silly question IMHO, but surely one you could have solved by yourself. It only requires two commands on an average posix system: - cd /your/python/install/lib/ - grep -A5 -B5 BadStatusLine httplib.py HTH From prologic at shortcircuit.net.au Wed Sep 10 21:32:59 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 11:32:59 +1000 Subject: Simple UDP server In-Reply-To: <slrngcgmd4.8co.nick@irishsea.home.craig-wood.com> References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> <slrngcgmd4.8co.nick@irishsea.home.craig-wood.com> Message-ID: <e1a84d570809101832y693e14d1rd1a58a1e7fdb4c5b@mail.gmail.com> On Thu, Sep 11, 2008 at 10:36 AM, Nick Craig-Wood <nick at craig-wood.com> wrote: > For UDP I wouldn't thread or, fork, I'd use select and run > asynchronously. > > http://docs.python.org/lib/module-select.html > > Actually if I really had to do this I'd use twisted. Right tool for > the job! For anyone interested, pymills is an event-driven, asynchronous library geared towards Component architectures. It currently uses select for it's socket components, TCPServer, TCPClient, and it's UDP counter-parts. cheers James -- -- -- "Problems are solved by method" From gagsl-py2 at yahoo.com.ar Tue Sep 16 03:11:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 04:11:32 -0300 Subject: how to exclude specific things when pickling? References: <nw9zk.32211$bx1.21567@bignews1.bellsouth.net> <7cd144b6-ca6f-447a-8448-5a334f8f999f@k37g2000hsf.googlegroups.com> Message-ID: <op.uhkbli1ax6zn5v@gabriel2.softlabbsas.com.ar> En Sun, 14 Sep 2008 12:06:44 -0300, Michael Palmer <m_palmer45 at yahoo.ca> escribi?: > On Sep 14, 10:53 am, "inhahe" <inh... at gmail.com> wrote: >> If I gather correctly pickling an object will pickle its entire >> hierarchy, >> but what if there are certain types of objects anywhere within the >> hierarchy >> that I don't want included in the serialization? What do I do to >> exclude >> them? Thanks. > > If your class defines a __getstate__ method, it is expected to return > the pickled state of the entire class. You can for example del those > items from self.__dict__ that you don't want pickled and then return > dumps(self). note: __getstate__ should return the *values* to be pickled, not the pickled state; else you end doing the work twice. And "del those items from self.__dict__" isn't a good idea, in general; I'd use a *copy* of __dict__ instead. -- Gabriel Genellina From marcus at internetnowasp.net Fri Sep 5 07:01:23 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Fri, 05 Sep 2008 19:01:23 +0800 Subject: found a bug with smtpd, where can i report this? Message-ID: <48C11183.5010502@internetnowasp.net> Hi, Where should i report the bug? smtpd bug. Marcus.CM From marco.bizzarri at gmail.com Fri Sep 12 10:18:05 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 12 Sep 2008 16:18:05 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <6ivbfvFnfucU1@mid.uni-berlin.de> References: <mailman.921.1221227464.3487.python-list@python.org> <6ivbfvFnfucU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809120718r6709387bj68e75e9c40ce2036@mail.gmail.com> On Fri, Sep 12, 2008 at 4:09 PM, Diez B. Roggisch <deets at nospam.web.de> wrote: > Marco Bizzarri schrieb: >> >> Hi all. >> >> In many parts of my code I've the following schema of code: >> >> def isInUseByOutgoingRegistrations(self, archivefolder): >> for instance in self.findActiveOutgoingRegistrationInstances(): >> if instance.forbidToClose(archivefolder): >> return True >> return False >> >> Before devising my own solution for this kind of problem, I wonder if >> there is a common solution for the problem. I'm looking for a >> python2.3 solution. > > if any(instance.forbitToClose(archivefolder) for instance in > self.findActiveOutgoingRegistrationInstances()) Can you clarify where I can find "any"? It seems to me I'm unable to find it... > You should also consider using PEP8 style naming. > I knew that someone would have said that to me :-). I'm doing that... slowly. I'm trying to fix naming conventions as I had to work on my code... > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From jjkk73 at gmail.com Mon Sep 1 07:06:20 2008 From: jjkk73 at gmail.com (jorma kala) Date: Mon, 1 Sep 2008 13:06:20 +0200 Subject: Retrieving http headers from HTTPConnection object Message-ID: <bda7ac6d0809010406j3a218984q8e6f1d9fb80b6abb@mail.gmail.com> Hi, when using httplib for http requests, like for example: conn = httplib.HTTPConnection("www.python.org") conn.request("GET", "/index.html") Is it possible to retrieve the complete http request in string form : GET /index.html HTTP/1.1 Host: www.python.org User-Agent: ... Accept: ... Accept-Language: Accept-Encoding: Accept-Charset: Keep-Alive: Connection: I mean does the HTTPConnection object have a property that stores this ? or is it retrievable by some other form? Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080901/f4dcb3bc/attachment.html> From care02 at gmail.com Tue Sep 30 11:05:16 2008 From: care02 at gmail.com (care02 at gmail.com) Date: Tue, 30 Sep 2008 08:05:16 -0700 (PDT) Subject: XMLRPC - C Client / Python Server Message-ID: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> I have implemented a simple Python XMLRPC server and need to call it from a C/C++ client. What is the simplest way to do this? I need to pass numerical arrays from C/C++ to Python. Yours, Carl From grante at visi.com Mon Sep 15 00:07:08 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 23:07:08 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> <HYednR9_TqqbWVDVnZ2dnUVZ_oDinZ2d@posted.usinternet> <mailman.1023.1221448972.3487.python-list@python.org> Message-ID: <R-ednaGLHovxQlDVnZ2dnUVZ_gKdnZ2d@posted.usinternet> On 2008-09-15, Adelle Hartley <adelle at akemi.com.au> wrote: > Grant Edwards wrote: > >> When packages as significant as wxPython use naming >> conventions other than PEP 8, I find it hard to make a case >> that the PEP 8 naming convention is any better than any other. > > This relates to a question I was thinking about... > > I'm looking at porting a library that was written for COM and > .Net to work as a Python module, and was wondering whether it > would be better to stick to the library's current naming > convention so that the API is as similar as possible on each > platform, or to adopt a "when in Rome..." policy and follow > the "most mainstream" naming pattern for each > platform/language. If all that is would change is naming, then my advice would be to keep the existing naming. That way it matches existing documentation and examples. But, it does violate PEP 8. If the API itself is going to be changed significantly so that it's unique to the Python port (different to the point where existing documentation and examples are no longer useful), then using standard PEP 8 naming conventions is probably a good choice. -- Grant From bearophileHUGS at lycos.com Fri Sep 19 09:01:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Sep 2008 06:01:26 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <mailman.1220.1221752633.3487.python-list@python.org> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <gau926$f20$1@ger.gmane.org> <gavu71$43e$1@ger.gmane.org> <mailman.1274.1221827884.3487.python-list@python.org> Message-ID: <e29f8a4a-8aa0-43f4-9525-715a20f3ebfd@y21g2000hsf.googlegroups.com> Gerard flanagan: > data.sort() > datadict = \ > dict((k, len(list(g))) for k,g in groupby(data, lambda s: > '.'.join(s.split('.',2)[:2]))) That code may run correctly, but it's quite unreadable, while good Python programmers value high readability. So the right thing to do is to split that line into parts, giving meaningful names, and maybe even add comments. len(list(g))) looks like a good job for my little leniter() function (or better just an extension to the semantics of len) that time ago some people here have judged as useless, while I use it often in both Python and D ;-) Bye, bearophile From mail at timgolden.me.uk Fri Sep 19 04:42:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 19 Sep 2008 09:42:54 +0100 Subject: Python newbie In-Reply-To: <gavo67$ops$1@registered.motzarella.org> References: <gavjfd$mvd$1@registered.motzarella.org> <mailman.1261.1221809756.3487.python-list@python.org> <gavo67$ops$1@registered.motzarella.org> Message-ID: <48D3660E.5050902@timgolden.me.uk> Mladen Gogala wrote: > Steve Holden wrote: > >> No. Python implicitly dereferences all names when using them to compute >> values, and only uses them as references on the left-hand side of an >> assignment. >> >> Please note the above statement is contentious, and will likely bring a >> horde of screaming fanatics of various flavors down on my head for >> terminological inexactitude. > > Actually, I am not a "screaming fanatic". I just want to learn. I'm sure Steve can speak for himself, but just to clarify: the "screaming fanatics" referred to are those within the Python community whose opinions of the terminology used are at variance with Steve's. I think it was a comment which would mean more to those of us who've seen such terminology-battles come and go over the years. But thanks for introducing yourself anyway. Knowing more about where a poster is coming from never hurts when trying to answer their questions. :) TJG From dadapapa at googlemail.com Sat Sep 13 07:06:32 2008 From: dadapapa at googlemail.com (Harold Fellermann) Date: Sat, 13 Sep 2008 04:06:32 -0700 (PDT) Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> Message-ID: <c31462d9-5117-43ac-ba08-8c8ad40019cb@x35g2000hsb.googlegroups.com> > doesnt sum first construct the list then sum it? > def com(lst): > return sum(x for x in lst) You construct a generator over an existing list in your code. Try sum([x for x in lst]) to see the effect of additional list construction. And while you're at it, try the simple sum(lst). Cheers, - harold - From stephane at harobed.org Mon Sep 8 08:15:15 2008 From: stephane at harobed.org (=?iso-8859-1?q?KLEIN_St=E9phane?=) Date: Mon, 8 Sep 2008 12:15:15 +0000 (UTC) Subject: Where does the command "ls" in some doctest files come from ? Message-ID: <ga350i$m29$1@ger.gmane.org> Hi, for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/ tests.py?rev=89831&view=auto test file, there is this doctests : def develop_verbose(): """ We should be able to deal with setup scripts that aren't setuptools based. >>> mkdir('foo') >>> write('foo', 'setup.py', ... ''' ... from setuptools import setup ... setup(name="foo") ... ''') >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = foo ... parts = ... ''') >>> print system(join('bin', 'buildout')+' -vv'), # doctest: +ELLIPSIS Installing... Develop: '/sample-buildout/foo' ... Installed /sample-buildout/foo ... >>> ls('develop-eggs') - foo.egg-link - zc.recipe.egg.egg-link >>> print system(join('bin', 'buildout')+' -vvv'), # doctest: +ELLIPSIS Installing... Develop: '/sample-buildout/foo' in: '/sample-buildout/foo' ... -q develop -mxN -d /sample-buildout/develop-eggs/... """ I wonder where does the "ls('develop-eggs')" command come from ? It is doctest buildin command ? Where can I found some documentation about that ? I see this page http://docs.python.org/lib/module- doctest.html and I found nothing about that subject. Thanks for your help, Stephane http://docs.python.org/lib/module-doctest.html From uomiocenekidd at gmail.com Mon Sep 22 06:42:09 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:42:09 -0700 (PDT) Subject: www shockingtube com - Free Message-ID: <4d824670-2bcf-4285-bf80-c0eea0873300@d77g2000hsb.googlegroups.com> www shockingtube com . . . *******CLICK HERE******** http://vids365.cn/www-shockingtube-com ***************************** . . . . . . . . . . . . www shockingtube com From tjreedy at udel.edu Sat Sep 13 02:38:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Sep 2008 02:38:08 -0400 Subject: lacking follow-through In-Reply-To: <289bc58f-6c04-4bce-b393-e9fa0a8c4fee@i20g2000prf.googlegroups.com> References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <mailman.912.1221221819.3487.python-list@python.org> <289bc58f-6c04-4bce-b393-e9fa0a8c4fee@i20g2000prf.googlegroups.com> Message-ID: <gafn4b$eqk$1@ger.gmane.org> Carl Banks wrote: > I'm surprised there is anyone who still gives castironpi credit for > being fully human. His recent posts have generally been quite different from those of some months ago. Even he recognizes that they were somewhat weird and has tried to do better. Did he ever make any degrading attacks on people like the above, to deserve receiving such? This reminds me of my elementary school, where people who made social mistakes were sometimes never allowed to recover but were dumped on for years. tjr From gslindstrom at gmail.com Thu Sep 18 13:56:24 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 18 Sep 2008 12:56:24 -0500 Subject: PyCon 2009 (US) - Call for Tutorials Message-ID: <a9f39a410809181056k6426f5bg7eb0b950df0ee008@mail.gmail.com> *Pycon 2009 (US) ? Call for Tutorials* The period for submitting tutorial proposals for Pycon 2009 (US) is now open and will continue through Friday, October 31th. This year features two "pre-conference" days devoted to tutorials on Wednesday March 25 & Thursday March 26 in Chicago. This allows for more classes than ever. Tutorials are 3-hours long on a specific topic of your choice. Last year we featured classes on Learning Python, Web Development, Scientific Computing, and many more. Class size varied from 10 to over 60 students. The extended time spent in class allows teachers to cover a lot of material while allowing for interaction with students. The full Call for Tutorial Proposals, including submission details, an example proposal as well as a template, is available at < http://us.pycon.org/2009/tutorials/proposals/>. Tutorial selections will be announced in early December to give you time to prepare your class. PyCon will compensate instructors US$1,500 per tutorial. If you have any questions, please contact pycon-tutorials at python.org. Greg Lindstrom Tutorial Coordinator, PyCon 2009 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/4ecaf6ff/attachment.html> From castironpi at gmail.com Wed Sep 10 14:59:35 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 10 Sep 2008 11:59:35 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> Message-ID: <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> On Sep 10, 5:24?am, Steven D'Aprano <ste... at REMOVE.THIS.cybersource.com.au> wrote: > On Wed, 10 Sep 2008 09:26:20 +0200, Fredrik Lundh wrote: > > Steven D'Aprano wrote: > > >> You've created a solution to a problem which (probably) only affects a > >> very small number of people, at least judging by your use-cases. Who > >> has a 4GB XML file > > > Getting 4GB XML files from, say, logging processes or databases that can > > render their output as XML is not that uncommon. ?They're usually > > record-oriented, and are intended to be processed as streams. ?And given > > the right tools, doing that is no harder than doing the same to a 4GB > > text file. > > Fair enough, that's a good point. > > But would you expect random access to a 4GB XML file? If I've understood > what Castironpi is trying for, his primary use case was for people > wanting exactly that. > > -- > Steven Steven, Are you claiming that sequential storage is sufficient for small amounts of data, and relational db.s are necessary for large amounts? It's possible that there is only the fringe exception, in which case 'alloc/free' aren't useful in the majority of cases, and will never win customers away from the more mature competition. Regardless, it is an elegant solution to the problem of storing variable-length strings, with hardly any practical value. Perfect for grad school. From robin at alldunn.com Mon Sep 29 23:42:42 2008 From: robin at alldunn.com (Robin Dunn) Date: Mon, 29 Sep 2008 20:42:42 -0700 Subject: ANN: wxPython 2.8.9.1 Message-ID: <48E1A032.1080909@alldunn.com> Announcing ---------- The 2.8.9.1 release of wxPython is now available for download at http://wxpython.org/download.php. This release adds a quick fix for a compatibility problem with Python 2.4. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit and 64-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. In most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From tjreedy at udel.edu Mon Sep 22 19:29:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 19:29:38 -0400 Subject: A bit weird dictionary behavior In-Reply-To: <gb957i$ja0$1@news.lublin.pl> References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> <gb957i$ja0$1@news.lublin.pl> Message-ID: <gb99oo$ni2$1@ger.gmane.org> Grzegorz Staniak wrote: > On 22.09.2008, Carl Banks <pavlovevidence at gmail.com> wroted: >>> Some would argue (and some did by the time Python grew a 'bool' type) >>> that what is wrong is to have a bool type in a language that already >>> have a wider definition of the truth value of an expression... >> And some would argue that it was wrong to have such a wide definition >> for the truth value of an expression in the first place... An alternate viewpoint is that only True and False 'have' a truth value. So whenever the interpreter *needs* a truth value for conditional and logical operations, and it has something else, it implicitly calls bool(ob) to get one. This, or possibly a shortcut version thereof, is what a Python interpreter effectively does. From this viewpoint, objecters would instead have to argue that it is wrong to have such implicit calls and that programmers should have to put them in explicitly. > Just out of idle curiosity, what could be the alternatives? Not to evaluate > e.g. strings to "true"? Aren't such conventions as "whatever is not empty, > is 'true'" popular in dynamic langauges? I do not know what is popular, but implicit bool call are darn handy. tjr From tjreedy at udel.edu Sun Sep 21 15:22:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 Sep 2008 15:22:42 -0400 Subject: Why are "broken iterators" broken? In-Reply-To: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: <gb66to$ski$1@ger.gmane.org> Steven D'Aprano wrote: > According to the Python docs, once an iterator raises StopIteration, it > should continue to raise StopIteration forever. Iterators that fail to > behave in this fashion are deemed to be "broken": > > http://docs.python.org/lib/typeiter.html > > I don't understand the reasoning behind this. As I understand it, an > iterator is something like a stream. There's no constraint that once a > stream is empty it must remain empty forever. It is quite possible that a stream reader will return '' on one call and then something non-empty the next. An iterator that reads a stream and yields chunks of whatever size should either block until it gets sufficient data or yield nulls as long as the stream is open and not raise StopIteration until the steam is closed and it has yielded the last chunk of data. > Can somebody explain why "broken iterators" are broken? There is an important different between a store that is closed until the next day and one that closed - out of business. Similarly, there is a difference between an item being out-of-stock until the next delivery and out-of-stock and discontinued permanently, or between a road closed for repairs versus removal for something else. Using the same sign or signal for temporary and permanent conditions is confusing and therefore 'broken'. Terry Jan Reedy From fredrik at pythonware.com Fri Sep 12 11:18:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 17:18:06 +0200 Subject: setattr in class In-Reply-To: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <gae17g$ve0$1@ger.gmane.org> Bojan Mihelac wrote: > Hi all - when trying to set some dynamic attributes in class, for > example: > > class A: > for lang in ['1', '2']: > exec('title_%s = lang' % lang) #this work but is ugly > # setattr(A, "title_%s" % lang, lang) # this wont work > > setattr(A, "title_1", "x") # this work when outside class > > print A.title_1 > print A.title_2 > > I guess A class not yet exists in line 4. Is it possible to achive > adding dynamic attributes without using exec? Move the for-in loop out of the class definition: >>> class A: ... pass ... >>> for lang in ['1', '2']: ... setattr(A, "title_%s" % lang, lang) >>> a = A() >>> a.title_1 '1' A truly dynamic solution (using __getattr__ and modification on access) would probably give you a more "pythonic" solution. </F> From gagsl-py2 at yahoo.com.ar Wed Sep 10 03:50:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Sep 2008 04:50:18 -0300 Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> Message-ID: <op.ug89d4qyx6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 09 Sep 2008 16:38:54 -0300, Sam <samslists at gmail.com> escribi?: > I'm using urllib2 and accepting gzip and deflate. > > It turns out that almost every site returns either normal text or > gzip. But I finally found one that returns deflate. > > Here's how I un-gzip: > compressedstream = StringIO.StringIO(data) > gzipper = gzip.GzipFile(fileobj=compressedstream) > data = gzipper.read() > > Un-gzipping works great! > > Here's how I un-deflate (inflate??) > data = zlib.decompress(data) > > Un-deflating doesn't work. I get "zlib.error: Error -3 while > decompressing data: incorrect header check" > > I'm using python 2.5.2. Can someone tell me exactly how to handle > deflated web pages? zlib.decompress should work - can you provide a site that uses deflate to test? -- Gabriel Genellina From deets at nospam.web.de Wed Sep 3 02:59:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 08:59:31 +0200 Subject: Pass same parameter in Recursive function In-Reply-To: <b94b2a5c-8231-4ab9-a2ef-cf3f1bdd8460@o40g2000prn.googlegroups.com> References: <c5bc9de5-6195-4592-8278-7597e75ed9d0@r15g2000prd.googlegroups.com> <mailman.406.1220414283.3487.python-list@python.org> <b94b2a5c-8231-4ab9-a2ef-cf3f1bdd8460@o40g2000prn.googlegroups.com> Message-ID: <6i6qujFoj5a2U1@mid.uni-berlin.de> Davy schrieb: > On Sep 3, 11:57 am, "Chris Rebert" <c... at rebertia.com> wrote: >> Assuming the function is tail-recursive or the "unchanging" arguments >> are immutable, just use a closure: > [SNIP] > Hi Chris, > > Thank you :) > Perhaps I should clarify the problem. > 1. the function is NOT tail-recursive > 2. Yes, the arguments are immutable after I call the function the > first time. > > I think the best description of the problem may be: > How to keep some argument constant and accessable in one function > (especially, recursive function). We know that we can use something > like self.parameter to keep the parameter constant and accessable in > one class. The same way chris showed you - using a closure, you can capture variables outside, and only pass the changing params. The tail-recursion property isn't needed for that. Diez From vinay_sajip at yahoo.co.uk Mon Sep 1 09:52:52 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 1 Sep 2008 06:52:52 -0700 (PDT) Subject: logging - how to use in a library? References: <6hj2ggFmbgutU1@mid.individual.net> <e39b6fce-12b2-4583-92dc-9bf63355214f@l42g2000hsc.googlegroups.com> <6hkoi3Fmf6nvU1@mid.individual.net> <54e99587-0875-4317-bcf4-52130b70f58c@k13g2000hse.googlegroups.com> <6hra0cFno0v3U1@mid.individual.net> Message-ID: <7e72db94-66b7-4425-b30d-e07006a47cb1@m3g2000hsc.googlegroups.com> On Aug 29, 11:02 pm, Thomas Heller <thel... at python.net> wrote: > > BTW: Let me say that the more I useloggingthe more I like it.loggingis a fantastic package! > Thank you, I can say the same for ctypes and py2exe :-) Regards, Vinay Sajip From jaime.dyson at gmail.com Fri Sep 5 02:27:55 2008 From: jaime.dyson at gmail.com (jaime.dyson at gmail.com) Date: Thu, 4 Sep 2008 23:27:55 -0700 (PDT) Subject: "Full" element tag listing possible with Elementtree? Message-ID: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Hello all, I have the unenviable task of turning about 20K strangely formatted XML documents from different sources into something resembling a clean, standard, uniform format. I like Elementtree and have been using it to step through the documents to get a feel for their structure. .getiterator() gives me a depth-first traversal that eliminates the hierarchy of the elements. What I'd like is to be able to traverse elements while keeping track of ancestors, and print out the full structure of all of an ancestor's nodes as I arrive at each node. So, for example, if I had a document that looked like this: <a> <b att="atttag" content="b"> this is node b </b> <c> this is node c <d /> <e> this is node e </e> </c> <f> this is node f </f> </a> I would want to print the following: <a> <a> <b> <a> <b> text: this is node b <a> <c> <a> <c> text: this is node c <a> <c> <d> <a> <c> <e> <a> <c> <e> text: this is node e <a> <f> <a> <f> this is node f Is there a simple way to do this? Any help would be appreciated. Thanks.. From thomas.hilbert at gmail.com Mon Sep 15 06:04:40 2008 From: thomas.hilbert at gmail.com (Pretorien) Date: Mon, 15 Sep 2008 03:04:40 -0700 (PDT) Subject: objet COM et ms Word Message-ID: <245dc065-660f-4dfe-8134-14b4acfc1f2d@j22g2000hsf.googlegroups.com> Bonjour @ tous, je voudrais gerer des doc Word avec python. Y aurai-uil une doc quelque part bien faites ??? Pour le moment je fais : import win32com.client word = win32com.client.Dispatch('Word.Application') en suite j'ouvre VBexpress pour connaitre qu'elle fonction appeler: par ex: Dim wrdApp As Word.Application Set wrdDoc = wrdApp.Documents.Open("\Exemple.doc") donc en python cela donnerai word.Documents.Open("toto.doc") et ainsi de suite .... Y a t il quelque de bien faits pour python, de mani?re a ne pas avoir a g?rer et VB d'un cote pour deviner les fonctions ? appeler en python. Merci par avance, Crdt, Thomas From python.list at tim.thechases.com Thu Sep 18 08:57:16 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 18 Sep 2008 07:57:16 -0500 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <48D2502C.4000200@tim.thechases.com> > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? [snip] > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > but no improvements. It's like rearranging deck-chairs on the Titanic :) Yes, it may give a speed up, but what's 3 seconds when you're waiting 15hr :) Not knowing the len(IN[x].coordinates) or their structure, if it's a list of len==2, you should be able to just do if i <> j and IN[i].coordinates == IN[j].coordinates or if i <> j and IN[i].coordinates[:2] == IN[j].coordinates[:2] However, again, this is just polish. The big problem is that you have an O(N^2) algorithm that's killing you. 1) use xrange instead of range to save eating memory with a huge unneeded array. 2) unless you need to append duplicate labels, you know that when I and J are swapped, you'll reach the same condition again, so it might be worth writing the outer loops to eliminate this scenario, and in the process, but just starting at i+1 rather than i, you can forgo the check if "i<>j". Such changes might look something like for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates == IN[j].coordinates: SN.append(IN[i].label) If my college algorithms memory serves me sufficiently, this reduces your O(N^2) to O(N log N) which will garner you some decent time savings. -tkc From adam.dziendziel at gmail.com Thu Sep 25 06:09:52 2008 From: adam.dziendziel at gmail.com (Adam Dziendziel) Date: Thu, 25 Sep 2008 03:09:52 -0700 (PDT) Subject: [OT] Looking for developers: platform for fast and effective learning Message-ID: <e3e43408-803b-455a-aed5-13f0cded27c4@2g2000hsn.googlegroups.com> Hello everybody, I'm working on a website for fast and effective learning using spaced repetition technique. This is the same method used in SuperMemo, Mnemosyne, FullRecall or Anki software. I'd want to create an online version, supporting easy adding of own material and sharing with others. The method is very effective and is great for learning foreign language, learning to exams etc. I wonder that there is no such site running already. There is SuperMemo.net, but it is a typical commercial application, oriented for selling commercial courses. I would like to put on building community, collaboration in writing material and social learning. I'm looking for ambitious people, who want to take part in this undertaking. I can offer revenue share, if the project succeed. Technologies: Python (Pylons) + JavaScript (Ext JS) I have a working base in Pylons and Ext JS but we can consider changing tools. Best regards, Adam Dziendziel adam (dot) dziendziel (at) gmail (dot) com From sri_annauni at yahoo.co.in Thu Sep 4 11:27:25 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 4 Sep 2008 20:57:25 +0530 (IST) Subject: Directory creation Message-ID: <275302.58315.qm@web7908.mail.in.yahoo.com> Can someone tell me is there any module available to create directories?? I tried os, tempfile. I was facing some issues with os.mkdir(). The mode setting was not proper with this method. I created the directory 'stdin' with '0700' mode using os.mkdir() method. $> ls -alR stdin/ stdin/: total 12 drwx--S---?? 2 munisams munisams 4096 Sep? 3 02:00 . What is that 'S' in the group permission field?? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From jukka.aho at iki.fi Tue Sep 2 18:53:34 2008 From: jukka.aho at iki.fi (Jukka Aho) Date: Wed, 3 Sep 2008 01:53:34 +0300 Subject: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0 References: <pD5vk.59354$_03.18175@reader1.news.saunalahti.fi> <48bd6b4e$0$17174$742ec2ed@news.sonic.net> Message-ID: <Qtjvk.59899$_03.45068@reader1.news.saunalahti.fi> John Nagle wrote: > Python 5 is even stricter. Only ASCII (chars 0..127) can be sent > to standard output by default. Python 5? (I guess I haven't been following these things enough...) Well, I would sure hope not. -- znark From skip at pobox.com Tue Sep 9 07:06:20 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 Sep 2008 06:06:20 -0500 Subject: How to record audio from Python on Mac? Message-ID: <18630.22700.810611.193049@montanaro-dyndns-org.local> (I asked this on pythonmac-sig a couple days ago but got no response, so I'm casting a broader net.) Can I easily control audio record/playback from Python on my Mac? I know zip about audio recording or about Apple APIs via Python. Pointers to simple examples would be much appreciated. Thanks, Skip From dmitry at athabascau.ca Thu Sep 25 14:22:11 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 18:22:11 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> <48db50aa$0$3750$426a74cc@news.free.fr> <HoOCk.1756$Pv5.1315@edtnps83> <48dbc82e$0$1120$426a74cc@news.free.fr> <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> Message-ID: <nFQCk.1781$Pv5.1597@edtnps83> Aaron "Castironpi" Brady wrote: > You should write it like this: > > class B(object): > @A.proxy > def bmethod(self,a): > > Making 'proxy' a class method on A. makes sense. > In case different A instances (do > you have more than one BTW?) yep. I have multiple instances of class A, each one has properties (one per class) of classes B, C and D: class A: b=None c=None d=None def __init__(self,b,c,d): self.b=b self.c=c self.d=d ...magic with proxying methods goes here... class B: def bmethod(self,x): pass # we proxy this method from A def bmethod2(self,x): pass # this is not proxied class C: def cmethod(self,x): pass # we proxy this method from A class D: def dmethod(self,x): pass # we proxy this method from A a=A(B(),C(),D()) x='foo' a.bmethod(x) a.cmethod(x) a.dmethod(x) a.bmethod2(x) # raises error as we shouldn't proxy bmethod2 above is the ideal scenario. > What you've said implies that you only have one B instance, or only > one per A instance. Is this correct? yes. as per above code. > I agree that __setattr__ is the canonical solution to proxy, but you > have stated that you want each proxied method to be a member in the > proxy class. well. kind of. if I can make it transparent to the consumer so that he shouldn't do: a.b.bmethod(x) but rather: a.bmethod(x) As I'm trying to keep b, c and d as private properties and would like to filter which calls are allowed to those. Plus proxied methods in either one always expect certain parameters like: class B: def bmethod(self,c,x): pass and A encapsulates 'c' already and can fill in that blank automagically: class A: c=None b=None def bmethod(self,c,x): if not c: c=self.c b.bmethod(self,c,x) I kept this part of the problem out of this discussion as I'm pretty sure I can fill those in once I figure out the basic problem of auto-population of proxy methods since for each class/method those are going to be nearly identical. If I can autogenerate those on-the-fly I'm pretty sure I can add some extra-logic to them as well including signature change where A::bmethod(self,c,x) would become A::bmethod(self,x) etc. From castironpi at gmail.com Tue Sep 23 21:55:25 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 18:55:25 -0700 (PDT) Subject: how to keep a window above all other OS windows? References: <e03ba1b5-c120-45a3-bf27-640f86c35754@2g2000hsn.googlegroups.com> <62cc640e-3526-49f9-ba10-22ff31f094e1@e39g2000hsf.googlegroups.com> Message-ID: <62cb5b79-e5f4-4437-88f0-1a0c051134b7@l64g2000hse.googlegroups.com> On Sep 23, 3:34?pm, dmitrey <dmitrey.kros... at scipy.org> wrote: > On Sep 23, 11:21?pm, dmitrey <dmitrey.kros... at scipy.org> wrote: > > > Hi all, > > how to keep a Tkinter window above all other OS windows (i.e. > > including those ones from other programs)? > > > Thank you in advance, > > Dmitrey > > I have put [Tkinter] into topic of my message but somehow it has been > removed. > D. If you can get the handle of the window from the Tk framework, use the os call in 'ctypes'. Windows' call is ShowWindow( handle, HWND_TOPMOST ) I think. From timr at probo.com Fri Sep 12 23:33:20 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 13 Sep 2008 03:33:20 GMT Subject: universal unicode font for reportlab References: <ga6loq$jpj$1@rumours.uwaterloo.ca> <mailman.785.1221053660.3487.python-list@python.org> <Xns9B159F78E43Dduncanbooth@127.0.0.1> <r7bhc4hd6lh6539kqkmo8klgoua70sjhrn@4ax.com> <Xns9B165B8F730E4duncanbooth@127.0.0.1> Message-ID: <0qcmc4h92n4cbrijk8dju7i4d86ep0m7m9@4ax.com> Duncan Booth <duncan.booth at invalid.invalid> wrote: > >The not too scientific test I did was to copy the font embedding example >from the Reportlab documentation, modify it enough to make it actually >run, and then change the output to have only one glyph. The resulting >PDF is virtually identical. I'm not a reportlab expert though so I may >have made some blindingly obvious beginners mistake (or maybe it only >subsets fonts over a certain size or glyphs outside the ascii range?). > >---------- rlab.py ------------ >import os, sys >import reportlab >folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts' >afmFile = os.path.join(folder, 'LeERC___.AFM') >pfbFile = os.path.join(folder, 'LeERC___.PFB') >from reportlab.pdfbase import pdfmetrics >justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile) >faceName = 'LettErrorRobot-Chrome' # pulled from AFM file >pdfmetrics.registerTypeFace(justFace) >justFont = pdfmetrics.Font('LettErrorRobot-Chrome',faceName,'WinAnsiEncoding') OK, look the other way while I backpedal furiously. The conversation on the mailing last year was focused on TrueType fonts. Those are subsetted. EmbeddedType1Face, used for Type 1 fonts, does appear to embed the entire font. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mhostetl at otaku.freeshell.org Sun Sep 7 09:00:19 2008 From: mhostetl at otaku.freeshell.org (Mike Hostetler) Date: Sun, 7 Sep 2008 13:00:19 +0000 (UTC) Subject: Error importing mxTidy Message-ID: <ga0j93$gnh$1@chessie.cirr.com> I built and installed mx-experimental 3.0.0 from source and it seemed to go fine. But when I try to import it, I get this: localhost% python -c "import mx.Tidy" Traceback (most recent call last): File "<string>", line 1, in ? File "mx/Tidy/__init__.py", line 7, in ? from Tidy import * File "mx/Tidy/Tidy.py", line 7, in ? from mxTidy import * File "mx/Tidy/mxTidy/__init__.py", line 7, in ? from mxTidy import * ImportError: No module named mxTidy This seems strange to me, since it found the mx.Tidy module but not the mxTidy module underneath it. But I guess I don't know how the mx-experimental classes are put together, so I can't really guess what is happening. Thus I am posting here. :) -- mhostetl at sdf.lonestar.org SDF Public Access UNIX System - http://sdf.lonestar.org From sjmachin at lexicon.net Mon Sep 15 16:47:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 15 Sep 2008 13:47:24 -0700 (PDT) Subject: append on lists References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> Message-ID: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> On Sep 16, 6:45?am, Armin <a... at nospam.org> wrote: > Yes, but this is very unconvenient. > If d should reference the list a extended with a single list element > you need at least two lines > > a.append(7) > d=a > > and not more intuitive d = a.append(7) Methods/functions which return a value other than the formal None and also mutate their environment are "a snare and a delusion". Don't wish for them. Inconvenient? How often do you want to mutate a list and then set up another reference to it? From mishok13 at gmail.com Thu Sep 18 08:13:58 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Thu, 18 Sep 2008 15:13:58 +0300 Subject: XML Processing In-Reply-To: <484487154510621532@unknownmsgid> References: <484487154510621532@unknownmsgid> Message-ID: <192840a00809180513v68827517lf037326b768515a5@mail.gmail.com> 2008/9/18 Robert Rawlins <robert.rawlins at thinkbluemedia.co.uk>: > Guys, > > > > I'm running python 2.5 and currently using ElementTree to perform my XML > parsing and creation. ElementTree really is a great package for doing this, > however, I've been tasked by our deployment guys to try and move away from > external libraries where possible as it makes their job easier. > > > > Simple question I suppose to start with, does Python have any inbuilt XML > processing modules? If the answer is no then I'll stick with eTree, if > python does have one, then I'll look at some migration steps. > ElementTree is not an external package starting from Python 2.5. It's in stdlib under 'xml.etree.ElementTree' name. There's also a lot of other XML processing modules in stdlib's 'xml' package. > > > Many thanks All, > > > > Robert > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From stefan_ml at behnel.de Thu Sep 4 03:12:27 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 04 Sep 2008 09:12:27 +0200 Subject: python/xpath question.. In-Reply-To: <mailman.441.1220474224.3487.python-list@python.org> References: <mailman.441.1220474224.3487.python-list@python.org> Message-ID: <48bf8a5c$0$10095$9b4e6d93@newsspool3.arcor-online.net> Hi, you should really read about XPath. There are also newsgroups specifically for this topic, please use them. bruce wrote: > in my python, i'm using the xpath function to iterate/parse some html. i can > do something like > > s=d.xpath("//tr/td/text()") > count=len(s) > > and get the number of nodes that have text That is a wrong assumption. It will give you the number of text nodes, not the number of elements. They may or may not be the same. > i can then do something like > s=d.xpath("//tr/td") > count2=len(s) > > and get the number of total nodes... > by subtracting, i can get the number of nodes, without text.. is there an > easier way??!! Yes, learn to use XPath, e.g. //tr/td[not string()] Stefan From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 9 04:35:11 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 10:35:11 +0200 Subject: finding the parent class (not superclass) of the currently executing method derived from a Borg class In-Reply-To: <dc58489b-e114-4d0f-ad49-9011128d0467@b38g2000prf.googlegroups.com> References: <dc58489b-e114-4d0f-ad49-9011128d0467@b38g2000prf.googlegroups.com> Message-ID: <48c634bd$0$25187$426a74cc@news.free.fr> seanacais a ?crit : > I want to create a class derived from a Borg class that can > instantiated as part of a script or be contained in other classes. > When methods from the Borg class are called, I would like to know the > name of the class that contains the Borg class. > I've played a bit with inspect and _getframe from the sys module but > get inconsistent results. The main problem is if the Borg class is > instantiated outside a containing class, then I need to go up a > different number of stack frames. But this information isn't > available till after I've run out of stack frames. The simplest solution is usually the better : explicitely pass the caller (whether instance or module or whatever you want) > Hopefully the following code better describes what I'm looking to do. > > import sys > > class Borg: > _shared_state = {} > def __init__(self): > self.__dict__=self._shared_state > > class Assimilated(Borg): > valueByCaller = {} You understand that, being a class attribute, valueByCaller won't be part of the Borg's _shared_state ? > def __init__(self, setupvalue): > print "In Assimilated.__init__()" > print "setupvalue is: " + str(setupvalue) > > # would like key to be name of class (or module) that > # contins Assimilated > callerID = sys._getframe(1).f_code.co_name > > self.valueByCaller[callerID] = setupvalue > > print self.valueByCaller Anyway, since you override __init__ and don't call Borg.__init__, your Assimilated class doesn't behave as a Borg. (snip) > > When I run this, I get the following output: > > In Assimilated.__init__() > setupvalue is: 2 > {'A': 2} > In Assimilated.__init__() > setupvalue is: 3 > {'A': 2, 'B': 3} > In Assimilated.__init__() > setupvalue is: 4 > {'A': 2, 'C': 4, 'B': 3} > (snip) > > What I found most peculiar when I started this was that the > valueByCaller dictionary was completely populated before the __init__ > method of a was executed. Indeed. In classes A, B and C, assim_object is class attribute - so it is instanciated when the class statement is executed. > I'm pretty sure that this has to do with > the difference between when the object gets instanced and when it gets > initialized, Not at all. It has to do with the fact that all statements within a class block are executed before the class statement itself is executed. And since your class statements are at the top-level, they are executed when the module is initialised (that is, passed to the python runtime or first imported). > but I need to do some more research and reading to be > able to explain it to myself. Indeed. May I suggest that you *learn* Python's object model and Python's execution model instead of assuming anything ? This will save you a whole lot of time and frustration !-) From blabla at dungeon.de Thu Sep 11 11:52:33 2008 From: blabla at dungeon.de (hofer) Date: Thu, 11 Sep 2008 08:52:33 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> <slrngchjno.i8e.nick@irishsea.home.craig-wood.com> Message-ID: <f3871e0a-e76f-4bbd-ae14-5e8146071802@f63g2000hsf.googlegroups.com> On Sep 11, 10:36?am, Nick Craig-Wood <n... at craig-wood.com> wrote: >I'd type the explicit > > v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > Either is only a couple more > characters to type. ?It is completely > explicit and comprehensible to everyone, in comparison to > > ? v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > ? v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars > > Unlike perl, it will also blow up if mydict doesn't contain 'one' > which may or may not be what you want. > Is your above solution robust against undefined keys. In my example it would'nt be a problem. The dict would be fully populated, but I'm just curious. From jukka.aho at iki.fi Tue Sep 2 03:09:21 2008 From: jukka.aho at iki.fi (Jukka Aho) Date: Tue, 2 Sep 2008 10:09:21 +0300 Subject: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0 Message-ID: <pD5vk.59354$_03.18175@reader1.news.saunalahti.fi> Just a tip for those who are only just cutting their teeth on Python 3.0 and might have encountered the same problem as I did: When a Python (3.x) program is run on a terminal that only supports a legacy character encoding - such as Latin 1 or Codepage 437 - all characters printed to stdout will be automatically converted from the interpreter's internal Unicode representation to this legacy character set. This is a nice feature to have, of course, but if the original Unicode string contains characters for which there is no equivalent in the terminal's legacy character set, you will get the dreaded "UnicodeEncodeError" exception. In other words, the "sys.stdout" stream - as well as the "sys.stderr" stream - have both been hardwired to do their character encoding magic, by default, using the 'strict' error handling scheme: --- 8< --- >>> import sys >>> sys.stdout.errors 'strict' >>> sys.stderr.errors 'strict' --- 8< --- So, essentially, printing out anything but ASCII to stdout is not really safe in Python... unless you know beforehand, for sure, what characters the terminal will support - which at least in my mind kind of defeats the whole purpose of those automatic, implicit conversions. Now, I have written a more flexible custom error handler myself and registered it with Python's codec system, using the codecs.register_error() function. When the handler encounters a problematic codepoint, it will either suggest a "similar-enough" Latin 1 or ASCII substitution for it, or if there is none available in its internal conversion table, it will simply print it out using the U+xxxx notation. The "UnicodeEncodeError" exception will never occur with it. Instead of creating a custom error handler from scratch one could also make use of one of Python's built-in, less restrictive error handlers, such as 'ignore', 'replace', 'xmlcharrefreplace', or 'backslashreplace'. But in order to make things work as transparently and smoothly as possible, I needed a way to make both the "sys.stdio" and "sys.stderr" streams actually _use_ my custom error handler, instead of the default one. Unfortunately, the current implementation of io.TextIOWrapper (in Python 3.0b2, at least) does not yet offer a public, documented interface for changing the codec error handler - or, indeed, the target encoding itself - for streams that have already been opened, and this means you can't "officially" change it for the "stdout" or "stderr" streams, either. (The need for this functionality is acknowledged in PEP-3116, but has apparently not been implemented yet. [1]) So, after examining io.py and scratching my head a bit, here's how one can currently hack one's way around this limitation: --- 8< --- import sys sys.stdout._errors = 'backslashreplace' sys.stdout._get_encoder() sys.stderr._errors = 'backslashreplace' sys.stderr._get_encoder() --- 8< --- Issuing these commands makes printing out Unicode strings to a legacy terminal a safe procedure again and you're not going get unexpected "UnicodeEncodeErrors" thrown in your face any longer. (Note: 'backslashreplace' is just an example here; you could substitute the error handler of your choice for it.) The downside of this solution is, of course, that it will break down if the private implementation of io.TextIOWrapper in io.py changes in the future. But as a workaround, I feel it is sufficient for now, while waiting for the "real" support to appear in the library. (If there's a cleaner and more future-proof way of doing the same thing right now, I'd of course love to hear about it...) _____ 1. http://mail.python.org/pipermail/python-3000/2008-April/013366.html -- znark From steven at REMOVE.THIS.cybersource.com.au Tue Sep 30 04:52:11 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 08:52:11 GMT Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> Message-ID: <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: > In message <gbr4ks$1vv$1 at aioe.org>, r0g wrote: > >> You can only distribute modifications to gnuplot itself as patches, but >> you can distribute it freely ... > > This must be some new definition of "freely" of which I'm unaware. You're free to distribute the official release of gnuplot. You're free to distribute patches to gnuplot. You're even free to provide people with a script or program to apply those patches to gnuplot. Where's the non-free bit? Personally, I don't get the whole "only distribute patches" requirement. It's a bit like saying "You're free to distribute this software, but only as a tarball". It seems silly to me. But I don't see it as non-free, except in the sense that "only licences approved by the FSF are free". -- Steven From Ron.Barak at lsi.com Sun Sep 14 09:44:03 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Sun, 14 Sep 2008 14:44:03 +0100 Subject: Representation of python code ? Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Hi Guys, Is there a script/application, which gets as input python code, and produces a (graphic) representation of the inter-relationships between its classes/functions ? Bye, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080914/3c36f58a/attachment.html> From brtzsnr at gmail.com Fri Sep 5 08:49:48 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Fri, 5 Sep 2008 05:49:48 -0700 (PDT) Subject: derived classes and __getattr__ References: <d5a86bf2-2b8c-487f-9097-51bc92ef478d@w24g2000prd.googlegroups.com> <g9qrmh$k62$02$1@news.t-online.com> <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> <g9r0ns$1js$01$1@news.t-online.com> Message-ID: <12c58ddc-5d45-4323-b268-6815fe5cb86d@z6g2000pre.googlegroups.com> On Sep 5, 1:13?pm, Peter Otten <__pete... at web.de> wrote: > Alexandru ?Mosoi wrote: > > On Sep 5, 11:47?am, Peter Otten <__pete... at web.de> wrote: > >> Alexandru Mo?oi wrote: > >> > i'm facing the following problem: > > >> > class Base(object): > >> > def __getattr__(self, attr): return lambda x: attr + '_' + x > > >> > def dec(callable): > >> > return lambda *args: 'dec_' + callable(*args) > > >> > class Derived(Base): > >> > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have > >> > what_so_ever > >> > mumu = dec(Base.mumu) ? ? ? ? ? ? ? ? ? ? ? ? ?# wrong, base > >> > doesn't have mumu > > >> > any idea how to do this? > > >> __getattr__() is defined in the class to create instance attributes on > >> the fly. If you want class attributes you have to put the __getattr__() > >> method into the class of the class, or "metaclass": > > >> class Base(object): > >> class __metaclass__(type): > >> def __getattr__(self, attr): > >> return lambda self, x: attr + '_' + x > > >> def dec(callable): > >> return lambda *args: 'dec_' + callable(*args) > > >> class Derived(Base): > >> what_so_ever = dec(Base.what_so_ever) > > >> d = Derived() > >> print d.what_so_ever("42") > > >> I don't see how you can turn this into something useful... > > >> Peter > > > 10x. it works. however I have another small problem. now, > > d.third('blah') doesn't work because instance d doesn't have 'third' > > attribute. I was expecting derived class to inherit the metaclass as > > well, but it didn't. > > That has nothing to do with inheritance: > > >>> type(Derived) > > <class 'classattr.__metaclass__'> > > If Python doesn't find an attribute in the instance it looks it up in the > class but not in the metaclass: > > >>> Base.third > > <function <lambda> at 0x2b5f8028aa28>>>> Base().third > > Traceback (most recent call last): > ? File "<stdin>", line 1, in <module> > AttributeError: 'Base' object has no attribute 'third' > > I think you should go back to the drawing board now and look for a simpler > approach to solve your actual problem... > > Peter i somehow fixed the problem using: def __getattr__(self, attr): return functools.partial(Base.__metaclass__.__getattr__(self.__class__, attr), self) however this looks ugly enough to look for another solution. i still have one more question: why do I have to bind self? (without which functions fail expecting an instance) From srikrishnamohan at gmail.com Tue Sep 23 10:02:06 2008 From: srikrishnamohan at gmail.com (km) Date: Tue, 23 Sep 2008 19:32:06 +0530 Subject: improving a huge double-for cycle In-Reply-To: <48D2502C.4000200@tim.thechases.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D2502C.4000200@tim.thechases.com> Message-ID: <f4cc03640809230702i1f3a182q5bb523992d826857@mail.gmail.com> how abt this ? N = len(IN) for k in range(N): for j in range(N): if j >= k: # or k <= j doSomething() KM ~~~~~~~~~~~~~~~ On Thu, Sep 18, 2008 at 6:27 PM, Tim Chase <python.list at tim.thechases.com>wrote: > Code: Select all >> for i in range(len(IN)): #scan all elements of the list IN >> for j in range(len(IN)): >> if i <> j: >> if IN[i].coordinates[0] == IN[j].coordinates[0]: >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> SN.append(IN[i].label) >> >> >> Unfortunately my len(IN) is about 100.000 and the running time about >> 15h !!!! :( >> >> Any idea to improve it? >> > [snip] > >> I have already tried to group the "if statements" in a single one: >> >> Code: Select all >> if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> >> but no improvements. >> > > It's like rearranging deck-chairs on the Titanic :) Yes, it may give a > speed up, but what's 3 seconds when you're waiting 15hr :) > > Not knowing the len(IN[x].coordinates) or their structure, if it's a list > of len==2, you should be able to just do > > if i <> j and IN[i].coordinates == IN[j].coordinates > > or > > if i <> j and IN[i].coordinates[:2] == IN[j].coordinates[:2] > > However, again, this is just polish. The big problem is that you have an > O(N^2) algorithm that's killing you. > > 1) use xrange instead of range to save eating memory with a huge unneeded > array. > > 2) unless you need to append duplicate labels, you know that when I and J > are swapped, you'll reach the same condition again, so it might be worth > writing the outer loops to eliminate this scenario, and in the process, but > just starting at i+1 rather than i, you can forgo the check if "i<>j". > > Such changes might look something like > > for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): > if IN[i].coordinates == IN[j].coordinates: > SN.append(IN[i].label) > > If my college algorithms memory serves me sufficiently, this reduces your > O(N^2) to O(N log N) which will garner you some decent time savings. > > -tkc > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080923/f0fe4a68/attachment.html> From S.Shi at kingston.ac.uk Mon Sep 8 07:08:33 2008 From: S.Shi at kingston.ac.uk (Shi, Shaozhong) Date: Mon, 8 Sep 2008 12:08:33 +0100 Subject: how to use execfile with input parameters Message-ID: <77BBE7D879F90E47886631DD9B2714CD04FF1DB1@KUDBEX01.kuds.kingston.ac.uk> I have a Python script expecting 11 or 12 input parameters. How do I use execfile to execute the Python script in my new Python script? How do I pass in the input parameters? Yours sincerely, David This email has been scanned for all viruses by the MessageLabs Email Security System. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/e0d5d159/attachment.html> From mccredie at gmail.com Fri Sep 26 16:42:27 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 26 Sep 2008 13:42:27 -0700 (PDT) Subject: ConfigParser subclass problem References: <mailman.1560.1222458749.3487.python-list@python.org> Message-ID: <bfb5d375-6455-437f-9560-baef54f19725@w1g2000prk.googlegroups.com> On Sep 26, 12:56?pm, Strato <pyt... at p0w.org> wrote: > Hi folks, > > I think I do something wrong, but I don't see why it doesn't work, so I > will explain: > > I've searched in the list archive and found this thread, that explain > exactly what I want to have: the options strings returned by > ConfigParser without being lower cased. > > I tryed to reproduce this, by subclassing the SafeConfigParser class, > like this: > > * in my main script: > > from MyConfigParser import * > > * in the MyConfigParser.py file: > from ConfigParser import SafeConfigParser > > class MyConfigParser(SafeConfigParser): > ? ? def optionxform(self, optionstr): > ? ? ? ? print "Called the modified version of the class" > ? ? ? ? return optionstr > > then, when I run the script, every time a calls to my own class is done, > the print statment is shown in the console, so this may work, but when I > use the .items() method of the class, I got a lower cased result ! > > (In my test, using the .items() method is my only try to test the new class) > > Does anybody has an idea of what I'm doing wrong ? > > Thanks, > Strato I don't know what you are doing wrong. It works just fine for me: [code] from ConfigParser import SafeConfigParser from StringIO import StringIO class MyConfigParser(SafeConfigParser): def optionxform(self, optionstr): print "Called the modified version of the class" return optionstr def main(): contents = StringIO(""" [Section1] Foo=Bar Bar=Baz Spam=Eggs [Section2] Hello=World """) raw_parser = SafeConfigParser() raw_parser.readfp(contents) print "Using SafeConfigParser Section1" for item in raw_parser.items("Section1"): print item print "Using SafeConfigParser Section2" for item in raw_parser.items("Section2"): print item contents.seek(0) my_parser = MyConfigParser() my_parser.readfp(contents) print print "Using MyConfigParser Section1" for item in my_parser.items("Section1"): print item print "Using MyConfigParser Section2" for item in my_parser.items("Section2"): print item if __name__ == "__main__": main() [/code] Produces the output: Using SafeConfigParser Section1 ('foo', 'Bar') ('bar', 'Baz') ('spam', 'Eggs') Using SafeConfigParser Section2 ('hello', 'World') Called the modified version of the class Called the modified version of the class Called the modified version of the class Called the modified version of the class Using MyConfigParser Section1 ('Foo', 'Bar') ('Bar', 'Baz') ('Spam', 'Eggs') Using MyConfigParser Section2 ('Hello', 'World') Matt From paul.hankin at gmail.com Thu Sep 18 16:03:38 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 18 Sep 2008 13:03:38 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <43c1847e-994b-4569-9fb8-0aac3edf0da9@n38g2000prl.googlegroups.com> On Sep 18, 2:25?pm, Alexzive <zasaconsult... at gmail.com> wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > ? ? for i in range(len(IN)): #scan all elements of the list IN > ? ? ? for j in range(len(IN)): > ? ? ? ? if i <> j: > ? ? ? ? ?if IN[i].coordinates[0] == IN[j].coordinates[0]: > ? ? ? ? ? ?if IN[i].coordinates[1] == IN[j].coordinates[1]: > ? ? ? ? ? ? ? SN.append(IN[i].label) > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > ? ? if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: A simple O(N) algorithm: from collections import defaultdict d = defaultdict(int) for x in IN: d[x] += 1 SN = [x for (x, c) in d.iteritems() if c > 1] -- Paul Hankin From mensanator at aol.com Thu Sep 4 04:28:46 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 4 Sep 2008 01:28:46 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> Message-ID: <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> On Sep 4, 1:26 am, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Wed, 03 Sep 2008 22:20:43 -0700, Mensanator wrote: > > On Sep 3, 8:30 pm, Steven D'Aprano <st... at REMOVE-THIS- > > cybersource.com.au> wrote: > >> On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: > >> >>>> sum([]) > >> > 0 > > >> > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. > >> > It should return None or throw an exception like sum([None,1]) does. > > >> You're wrong, because 99.9% of the time when users leave a blank cell > >> in Excel, they want it to be treated as zero. > > > Then 99.9% of users want the wrong thing. > > It is to laugh. > > > Microsoft knows that this is a bug > > Says you. > > > but refuses to fix it to prevent breaking legacy documents (probably > > dating back to VisiCalc). When graphimg data, a missing value should be > > interpreted as a hole in the graph > > "Graphing data" is not sum(). I don't expect graphing data to result in > the same result as sum(), why would I expect them to interpret input the > same way? > > > +------+ +--+------+------+-----+ > > Why should the graphing application ignore blanks ("missing data"), but > sum() treat missing data as an error? That makes no sense at all. Maybe it's important to know data is missing. You can see the holes in a graph. You can't see the holes in a sum. > > > and not evaluated as 0 > > > And Microsoft provides a workaround for graphs to make 0's appear as > > holes. Of course, this will cause legitimate 0 values to disappear, so > > the workaround is inconsistent. > > I'm not aware of any spreadsheet that treats empty cells as zero for the > purpose of graphing, and I find your claim that Excel can't draw graphs > with zero in them implausible, but I don't have a copy of Excel to test > it. That was a mistake. I made a followup correction, but you probably didn't see it. > > >> Spreadsheet sum() is not the > >> same as mathematician's sum, which doesn't have a concept of "blank > >> cells". (But if it did, it would treat them as zero, since that's the > >> only useful thing and mathematicians are just as much pragmatists as > >> spreadsheet users.) The Excel code does the right thing, and your > >> "pure" solution would do the unwanted and unexpected thing and is > >> therefore buggy. > > > Apparently, you don't use databases or make surface contours. > > Neither databases nor surface contours are sum(). What possible relevance > are they to the question of what sum() should do? Because a sum that includes Nulls isn't valid. If you treated Nulls as 0, then not only would your sum be wrong, but so would your count and the average based on those. Now you can EXPLICITLY tell the database to only consider non-Null values, which doesn't change the total, but DOES change the count. > > Do you perhaps imagine that there is only "ONE POSSIBLE CORRECT WAY" to > deal with missing data, and every function and program must deal with it > the same way? But that's what sum() is doing now, treating sum([]) the same as sum([],0). Why isn't sum() defined such that "...if list is empty, return start, IF SPECIFIED, otherwise raise exception." Then, instead of "ONE POSSIBLE CORRECT WAY", the user could specify whether he wants Excel compatible behaviour or Access compatible behaviour. > > > Contour programs REQUIRE that blanks are null, not 0 > > Lucky for them that null is not 0 then. No, but blank cells are 0 as far as Excel is concerned. That behaviour causes nothing but trouble and I am saddened to see Python emulate such nonsense. > > > so that the Kriging > > algorithm interpolates around the holes rather than return false > > calculations. Excel's treatment of blank cells is inconsistent with > > Access' treatment of Nulls and therefore wrong, anyway you slice it. > > No no no, you messed that sentence up. What you *really* meant was: > > "Access' treatment of Nulls is inconsistent with Excel's treatment of > blank cells and therefore wrong, anyway you slice it." > > No of course not. That would be stupid, just as stupid as your sentence. > Excel is not Access. They do different things. Why should they > necessarily interpret data the same way? Because you want consistent results? > > > Maybe you want to say a bug is when it doesn't do what the author > > intended, but I say if what the intention was is wrong, then a perfect > > implentation is still a bug because it doesn't do what it's supposed to > > do. > > Who decides what it is supposed to do if not the author? The author can't change math on a whim. > You, in your ivory tower who doesn't care a fig for > what people want the software to do? True, I could care less what peole want to do... ...as long as they do it consistently. > > Bug report: "Software does what users want it to do." > Fix: "Make the software do something that users don't want." What the users want doesn't carry any weight with respect to what the database wants. The user must conform to the needs of the database because the other way ain't ever gonna happen. > > Great. If only. But then, I probably wouldn't have a job. > > >> Bugs are defined by "does the code do what the user wants it to do?", > >> not "is it mathematically pure?". > > > ReallY? So you think math IS a democracy? There is no reason to violate > > mathematical purity. > > You've given a good example yourself: the Kriging algorithm needs a Null > value which is not zero. There is no mathematical "null" which is > distinct from zero, so there's an excellent violation of mathematical > purity right there. Hey, I was talking databases, you brought up mathematical purity. > > If I am given the job of adding up the number of widgets inside a box, > and the box is empty, I answer that there are 0 widgets inside it. Right. it has a known quantity and that quantity is 0. Just because the box is empty doesn't mean the quantity is Null. > If I > were to follow your advice and declare that "An error occurred, can't > determine the number of widgets inside an empty box!" people would treat > me as an idiot, and rightly so. Right. But a better analogy is when a new shipment is due but hasn't arrived yet so the quantity is unknown. Now the boss comes up and says he needs to ship 5 widgets tomorrow and asks how many you have. You say 0. Now the boss runs out to Joe's Widget Emporium and pays retail only to discover when he gets back that the shipment has arrived containing 12 widgets. Because you didn't say "I don't know, today's shipment isn't here yet", the boss not only thinks you're an idiot, but he fires you as well. > > > If I don't get EXACTLY the same answer from Excel, > > Access, Mathematica and Python, then SOMEBODY is wrong. It would be a > > shame if that somebody was Python. > > Well Excel, Python agree that the sum of an empty list is 0. What do > Access and Mathematica do? I don't know abaout Mathmatica, but if you EXPLICITLY tell Access to sum only the non-Null values, you'll get the same answer Excel does. Otherwise, any expression that includes a Null evaluates to Null, which certainly isn't the same answer Excel gives. > > >> The current behaviour of sum([]) does the right thing for the 99% of > >> the time when users expect an integer. > > > Why shouldn't the users expect an exception? Isn't that why we have > > try:except? Maybr 99% of users expect sum([])==0, but _I_ expect to be > > able to distinguish an empty list from [4,-4]. > > The way to distinguish lists is NOT to add them up and compare the sums: > > >>> sum([4, -4]) == sum([0]) == sum([1, 2, 3, -6]) == sum([-1, 2, -1]) > > True > > The correct way is by comparing the lists themselves: > > >>> [] == [4, -4] > > False > > >> And the > >> rest of the time, they have to specify a starting value for the sum > >> anyway, and so sum([], initial_value) does the right thing *always*. > > > So if you really want [] to be 0, why not say sum([],0)? > > I don't want [] == 0. That's foolish. I want the sum of an empty list to > be 0, which is a very different thing. In certain circumstances. In others, an empty list summing to 0 is just as foolish. That's why sum([]) should be an error, so you can have it either way. Isn't one of Python's slogans "Explicit is better than implicit"? > > And I don't need to say sum([],0) because the default value for the > second argument is 0. That's the problem. There is no justification for assuming that unknown quantities are 0. > > > Why shouldn't nothing added to nothing return nothing? Having it > > evaluate to 0 is wrong 99.9% of the time. > > It is to laugh. > > What's the difference between having 0 widgets in a box and having an > empty box with, er, no widgets in it? There are no "empty" boxes. There are only boxes with known quantities and those with unknown quantities. I hope that's not too ivory tower. > > -- > Steven From afriere at yahoo.co.uk Tue Sep 16 02:45:36 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 15 Sep 2008 23:45:36 -0700 (PDT) Subject: environment variable issue References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> <mailman.1057.1221505773.3487.python-list@python.org> Message-ID: <0abf9533-9614-4aa4-9402-5bec41eb2b17@q5g2000prf.googlegroups.com> On Sep 16, 5:09 am, Tim Chase <python.l... at tim.thechases.com> wrote: > This is likely the same issue I just posted about here: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > [snip] It's also a bit like a thread I posted to back in August (which dealt with the difference between bash's shell-variable 'HOSTNAME' and environment-variables). http://groups.google.com/group/comp.lang.python/browse_thread/thread/4db6dbd9469adb31/85750e7f2a5c551c#2a038742c95cc28a From sturlamolden at yahoo.no Thu Sep 25 07:16:34 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 04:16:34 -0700 (PDT) Subject: Linq to Python References: <mailman.1493.1222340940.3487.python-list@python.org> Message-ID: <579eb852-031c-4f50-ac64-88ad8d677b05@m73g2000hsh.googlegroups.com> On 25 Sep, 13:08, hrishy <hris... at yahoo.co.uk> wrote: > Pardon my ignorance again but id ont see any join in python or did i miss something ? It's more Pythonic to use the syntax of dictionary lookups. From fredrik at pythonware.com Thu Sep 4 04:47:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 10:47:04 +0200 Subject: use str as variable name In-Reply-To: <48bf9d12$0$7552$426a74cc@news.free.fr> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <mailman.464.1220515161.3487.python-list@python.org> <48bf9d12$0$7552$426a74cc@news.free.fr> Message-ID: <g9o7a9$t11$1@ger.gmane.org> Bruno Desthuilliers wrote: > You wouldn't write something like 2.__add__(3), would you ? Don't give the "it's only OO if I write obj.method(args)" crowd more bad ideas, please ;-) (...as Bruno implies, setattr(), len() et al can be and should be viewed as generic functions. A specific Python implementation may use custom code to implement behaviour for a given object; behaviour that's more efficient than a full Python-level method call. For example, in CPython, len(L) is about twice as fast as L.__len__() for built-in sequences.) </F> From grante at visi.com Tue Sep 16 12:26:38 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 11:26:38 -0500 Subject: literals optimization (was Re: append on lists) References: <gamffv$qms$1@online.de> <mailman.1116.1221574264.3487.python-list@python.org> <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> <mailman.1126.1221581236.3487.python-list@python.org> Message-ID: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> On 2008-09-16, Maric Michaud <maric at aristote.info> wrote: > Le Tuesday 16 September 2008 16:57:26 Grant Edwards, vous avez ?crit?: >> On 2008-09-16, Maric Michaud <maric at aristote.info> wrote: >> > Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit?: >> >> On 2008-09-16, Maric Michaud <maric at aristote.info> wrote: >> >> >> >> > all expressions that return something, return a new object, >> >> >> >> That's not _quite_ true: >> >> >>> a=1 >> >> >>> b=a.__add__(0) >> >> >>> a is b >> >> >> >> True >> >> >> >> ;) >> > >> > This is implementation specific, >> >> Indeed. >> >> > the specification of the language says that it should be >> > false, >> >> That's curious. If so, then the implimentation is in violating >> the specification. > > But it doesn't matter No argument. > as the "is" operator is not relevant for any use case with > scalars and even strings and the optimization is not > negligible. In fact, I'd rather say it's unspecified, each > implementation does it its own way. I was just pointing out that for some degenerate cases in the C-Python implementation, the statement "all expressions that return something, return a new object" is not true. I'm not saying it ought to be true. I'm just saying that if the specification says that, it's a bug (in the specification, IMO). If the specification states that, then either the specification should be changed, or the implementation should be changed. Waving away specification violations with claims of "it doesn't matter" just seems like bad practice. If a requirement doesn't matter, then remove it from the specification. >> Where is that in the specification? > > Each literal creates a new instance, and instances of int are > not supposed to be unique for each value (at less it's not > specified so), so "1 is not 1", but implementation can cache > integers, short strings, to avoid creating an new instance > each time they appear in code. Quite true, but that's not what I was asking. I was asking where in the specification <http://docs.python.org/ref/ref.html> it says that all expressions that return something, return a new object. > jython do this also for integer (see above), but not for strings : > > maric at redflag1 17:33:52:~$ jython > Jython 2.2.1 on java1.6.0_07 > Type "copyright", "credits" or "license" for more information. >>>> a = "aaaa" >>>> a is "aaaa" > 0 > maric at redflag1 17:36:48:~$ ipython > >>>>[1]: a = "aaaa" > >>>>[2]: a is "aaaa" > ...[2]: True > > BTW, I'm talking of Jython 2.2, Jython 2.4, which quite ready I think, can > change his mind as well. > >> I suspect the statement in the specification should only apply >> to mutable objects. > > No, CPython also have a unique empty tuple, but tuple literals > are not cached nor there are compile-time optimization : I don't see how that's material. My suggestion was that the requirement of "returning a new object" only apply to mutable objects, since it's clearly not true for some immutable objects [nor would there be any benefit for it to be so]. The behavior with immutable objects (integers and tuples) is then irrelevent. -- Grant Edwards grante Yow! I didn't order any at WOO-WOO ... Maybe a YUBBA visi.com ... But no WOO-WOO! From digitig at gmail.com Fri Sep 26 12:40:18 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 26 Sep 2008 17:40:18 +0100 Subject: Building truth tables In-Reply-To: <fe872489-3dba-47d1-8639-2ad0f18886cf@a1g2000hsb.googlegroups.com> References: <fe872489-3dba-47d1-8639-2ad0f18886cf@a1g2000hsb.googlegroups.com> Message-ID: <aee48b3c0809260940r6e34e032kb3736c3208ca430d@mail.gmail.com> 2008/9/26 andrea <kerny404 at gmail.com>: > Well I would like to make a little program that given a certain > logical expression gives the complete truth table. > > It's not too difficult in fact, I just have some doubts on how to > design it. > > I thought something like that: > > class Term: > > class Table: > > def and(... > def or(... As a quick and dirty solution, I'd write a function that takes a function as a parameter. Starting with a helper function to separate the bits of an integer into a list of bools: def int_to_bool(i, bits): # Extract the bits of i to a boolean array. # 'bits' is the number of signifcant bits. result = [] for j in range(0, bits): result.append(i & 1) i >>= 1 result.reverse() return result Now I'd define a function such as: def table(f, n): # Calculate a truth table for function f taking n boolean parameters result = [] for i in range(0, math.pow(2, n)): for j in range(0, n): params = int_to_bool(i, n) result.append(params + [(f(*params))]) return result Now you could define the function you want as a separate function, or just use a lambda: table(lambda a, b, c:(a or b) and c, 3) [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]] Each element in the result is the state of the parameters followed by the result of the function. I stress that this is quick and dirty -- I'm sure somebody will be along with something better soon! -- Tim Rowe From lists at cheimes.de Mon Sep 8 18:03:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 09 Sep 2008 00:03:05 +0200 Subject: The difference between __XX__ and XX method In-Reply-To: <f9e39bbc0809081431i309c5de3k7d24a5246ae4a900@mail.gmail.com> References: <f9e39bbc0809081431i309c5de3k7d24a5246ae4a900@mail.gmail.com> Message-ID: <ga47en$7vh$1@ger.gmane.org> AON LAZIO wrote: > Hi, Pythoners. > I would like to know that in some class, it uses __XX__ but in some it > uses only XX > for example, > > class Test: > def __som__(self): > ... > def som(self): > ... > What does "__XX__" make the method different from XX? > Thanks in advance The form __method__ is reserved for internal methods also known as magic methods. In general you must not name your own methods or attributes __XX__ because the core of Python reserves all rights on the __*__ naming schema. Some well know magic methods are __init__, __getattr__, __add__ etc. You can find a complete lists in the Python language reference. Christian From exarkun at divmod.com Tue Sep 30 15:38:16 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Sep 2008 15:38:16 -0400 Subject: [Tutor] Replacing cmd.exe with custom .py application In-Reply-To: <gbtupe$g7s$1@ger.gmane.org> Message-ID: <20080930193816.29191.2110621876.divmod.quotient.32319@ohm> On Tue, 30 Sep 2008 19:30:55 +0000 (UTC), Lie Ryan <lie.1296 at gmail.com> wrote: >On Tue, 30 Sep 2008 15:09:06 -0400, Ezra Taylor wrote: > >> Is there something similar to /dev/null on Windows? > > >I think it's called nul > >REM This is a batch file (.bat) >echo "This won't show" > NUL > >I'm not sure how to use it in python though. > Check out os.devnull. You can open it and write to it. Jean-Paul From bignose+hates-spam at benfinney.id.au Tue Sep 2 23:14:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 03 Sep 2008 13:14:03 +1000 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: <87hc8xor9g.fsf@benfinney.id.au> Ben Finney <bignose+hates-spam at benfinney.id.au> writes: > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > literals. Another reason in support of spaces (rather than underscores) to separate digit groups: it's the only separator that follows the SI standard for representing numbers: ? for numbers with many digits the digits may be divided into groups of three by a thin space, in order to facilitate reading. Neither dots nor commas are inserted in the spaces between groups of three. <URL:http://www.bipm.org/en/si/si_brochure/chapter5/5-3-2.html#5-3-4> This isn't binding upon Python, of course. However, it should be a consideration in choosing what separator convention to follow. -- \ ?If you ever catch on fire, try to avoid seeing yourself in the | `\ mirror, because I bet that's what REALLY throws you into a | _o__) panic.? ?Jack Handey | Ben Finney From zugnush at gmail.com Wed Sep 3 05:16:03 2008 From: zugnush at gmail.com (zugnush at gmail.com) Date: Wed, 3 Sep 2008 02:16:03 -0700 (PDT) Subject: sys.stdin on windows Message-ID: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> I often grep particular patterns out of large logfiles and then pipeline the output to sort and uniq -c I thought today to knock up a script to do the counting in a python dict. This seems work in linux $ cat count.py #!/usr/bin/env python import sys from collections import defaultdict accumulator=defaultdict(int) for line in sys.stdin.readlines(): accumulator[line.strip()]+=1 print "contents,count" for key in accumulator.keys(): print key,",",accumulator[key] $ cat test | ./count.py contents,count , 1 23 , 1 1 , 1 3 , 2 2 , 2 5 , 3 When I try to run the same thing on windows I get IOError: [Error 9] Bad file descriptor How can I make this more windows friendly? Thanks Neil From gagsl-py2 at yahoo.com.ar Tue Sep 16 00:56:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 01:56:51 -0300 Subject: Decompile python2.5-pyc References: <9DE19AF2-1E2B-4914-BA51-9E230CB238DE@uos.de> Message-ID: <op.uhj5amesx6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 15 Sep 2008 20:57:24 -0300, Manuel Ebert <maebert at uos.de> escribi?: > short story I accidentally wrote rm *.py into my makefile (yes, I am > old-fashioned, and yes, that was very, veeeery stupid) and - bad things > never come alone - my remote backup files are corrupted. To cut a sad > story short: I just kind of lost four months work on my bachelor's > thesis, well almost. I still have the pyc files (and backuped them on > virtually every device I have access to now), but despite intense > googling I couldn't find any free way of decompiling 2.5-code -- there > is depython.net and the online version of decompyle, but they charge > money (which I currently don't have), and the free version of decompyle > can't handle marshal data > 2.3, and I lack the skills necessary to > extend it to 2.5. > > Does anybody know something I don't, some home-brewn decompiler, > anything? I *am* quite desperate... If your code doesn't use too much features post-2.3, you could try regenerating the .pyc files using the old marshal format and feed the resulting .pyc to decompyle - if you're lucky it may accept it... --- begin --- import marshal MAGIC23 = ';\xf2\r\n' def load_pyc(filename): f = open(filename, 'rb') try: magic = f.read(4) timestamp = f.read(4) codeobject = marshal.load(f) finally: f.close() return magic, timestamp, codeobject def dump_pyc_23(filename, timestamp, codeobject): assert len(timestamp)==4 f = open(filename, 'wb') try: f.write(MAGIC23) f.write(timestamp) marshal.dump(codeobject, f, 0) finally: f.close() magic, timestamp, codeobject = load_pyc("test25.pyc") dump_pyc_23("test23.pyc", timestamp, codeobject) --- end --- Good luck! -- Gabriel Genellina From tim.leslie at gmail.com Mon Sep 22 05:32:44 2008 From: tim.leslie at gmail.com (Tim Leslie) Date: Mon, 22 Sep 2008 19:32:44 +1000 Subject: matrix algebra In-Reply-To: <1222070567.979005@chilli.pcug.org.au> References: <1222070567.979005@chilli.pcug.org.au> Message-ID: <d32b45350809220232o4ae801a1kfdf3cb0e0494ef6c@mail.gmail.com> On Mon, Sep 22, 2008 at 6:02 PM, Al Kabaila <akabaila at pcug.org.au> wrote: > Hi, > > My OS is Linux (openSUSE 10.3) and my interest in retirement is Python > applications to Structural Analysis of Civil Engineering structures, > currently in 2 dimensions only (under GPL). Modern Structural Analysis is > highly matrix oriented, but requires only a few basic matrix operations, > namely matrix creation, transposition, multiplication, invertion and > linear equation solution. For stability analysis one would require > Eigenvalues and Eigenvectors. In 3 dimensions, additionally highly > desirable would be vector algebra. The packages do have all these > functions, but currently only the basic functions are in the wrapper. > > There are several packages for matrix algebra. I tried Numeric, numpy and > numarray. All three are very good, but each uses different syntax. Not a > good thing for teaching... So I wrote a little python wrapper (under GPL) > to unify all packages with the same simple and transparent syntax. There is no need for a wrapper. Both numarray and Numeric have been deprecated in favour of numpy, so numpy is the only one you need to use. Numpy should have all the tools you need. If you find something missing, there's a good chance it's included in scipy (which is built on top of numpy). For full details see www.scipy.org. Cheers, Tim > Currently it deals with the Numeric, numpy and numarray and covers creation > of zero filled matrices, transposition, matrix multiplication, solution of > equations and inversion. > > This is a very active newsgroup that incudes such giants as Frederik Lundh > and countless others. I wonder: > > 1. Is there any interest in matrix algebra "for the masses" (I mean interest > in a wrapper for a subset of functions of the packages with a unified > simple syntax)? > 2. What other matrix operations would be required for your area of interest? > 3. What other matrix packages, if any, should one include in the wrapper? > > A copy of the wrapper is stored in a small, public svn repository. If you > would like to download it, please contact me by email at. Of course, if > there is interest, I would be delighted to upload it to a generally > accessible repository. Finally, if this is a re-invention of the wheel > (which it may well be), would you kindly let me know? > > akabaila [at] pcug [dot] org [dot] au. > > I would be very happy to send you the checkout instructions, but I should > discuss that with the people who run the repository. My home page that I > quote with my signature is not a repository nor does it have the current > programs. > > OldAl. > > -- > Al Kabaila (Dr) > http://akabaila.pcug.org.au/StructuralAnalysis > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at ghaering.de Thu Sep 11 07:48:53 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Thu, 11 Sep 2008 13:48:53 +0200 Subject: how dump a program which is running in memory In-Reply-To: <0592abb3-c2f6-4977-8338-3aa1956a353c@b38g2000prf.googlegroups.com> References: <0592abb3-c2f6-4977-8338-3aa1956a353c@b38g2000prf.googlegroups.com> Message-ID: <gab0j6$rmo$1@ger.gmane.org> ruqiang826 wrote: > hi > I have written a service running backgroud to do something in linux. > unfortunately?I deleted the source code by mistake, and I can still > see the process running background using "ps aux" : > > username 13820 0.0 0.0 60368 2964 ? S Aug20 0:33 > python ./UpdateJobStatus.py > > > I wonder if there is some way to dump the programme > "UpdateJobStatus.py" and get the source code back? Often, there is a way by accessing /proc/{pid}/fd/ But I believe you're out of luck with this method because apparently the Python interpreter closes the source file after parsing it. You can still try to find an undeletion utility for your filesystem. Avoid writing to disk in the meantime to not overwrite the deleted file accidentally, of course. There's such a utility for ext2, but I don't know if that works ok with ext3. For other filesystems, I have no idea. -- Gerhard From grflanagan at gmail.com Tue Sep 23 15:55:30 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Tue, 23 Sep 2008 21:55:30 +0200 Subject: Docstrings for class attributes In-Reply-To: <f301fd11-612c-46af-8fff-ca4b1d7fdeb3@e39g2000hsf.googlegroups.com> References: <mailman.1392.1222147427.3487.python-list@python.org> <f301fd11-612c-46af-8fff-ca4b1d7fdeb3@e39g2000hsf.googlegroups.com> Message-ID: <gbbhjh$c86$1@ger.gmane.org> George Sakkis wrote: > On Sep 23, 1:23 am, "Tom Harris" <celephi... at gmail.com> wrote: > >> Greetings, >> >> I want to have a class as a container for a bunch of symbolic names >> for integers, eg: >> >> class Constants: >> FOO = 1 >> BAR = 2 >> >> Except that I would like to attach a docstring text to the constants, >> so that help(Constants.FOO) will print some arbitrary string. Sort of >> a very limited implementation of PEP 224. The only solution that I can >> see is to subclass int.__new__(), since once I have an int all it's >> attributes are immutable. > > Here's one approach, using metaclasses and descriptors; it sort of > works, but it's less than ideal, both in usage and implementation. > > George > > #====== usage ============================================ > > class MyConstants: > __metaclass__ = ConstantsMeta > FOO = const(1, 'some docs about foo') > BAR = const(2) > > print MyConstants.FOO.__doc__ > help(MyConstants.FOO) > print MyConstants.FOO - MyConstants.BAR > print MyConstants.FOO - 2 > print 1 - MyConstants.BAR > > #======= implementation =================================== > > def ConstantsMeta(name, bases, namespace): > for name,attr in namespace.iteritems(): > if isinstance(attr, const): > namespace[name] = _ConstDescriptor(name, attr.value, > attr.doc) > return type(name, bases, namespace) > > class const(object): > def __init__(self, value, doc=None): > self.value = value > self.doc = doc > > class _ConstDescriptor(object): > def __init__(self, name, value, doc): > cls = type(name, (), dict( > __doc__ = doc, > __add__ = lambda self,other: value+other, > __sub__ = lambda self,other: value-other, > # ... > __radd__ = lambda self,other: other+value, > __rsub__ = lambda self,other: other-value, > # XXX lots of boilerplate code for all special methods > follow... > # XXX Is there a better way ? > )) > self._wrapper = cls() > > def __get__(self, obj, type): > return self._wrapper > -- > http://mail.python.org/mailman/listinfo/python-list > I think you get an equivalent result if you forget the descriptor and adapt the metaclass: def ConstantsMeta(name, bases, namespace): for name,attr in namespace.iteritems(): if isinstance(attr, const): cls = type(name, (type(attr.value),), {'__doc__': attr.doc}) namespace[name] = cls(attr.value) return type(name, bases, namespace) class const(object): def __init__(self, value, doc=None): self.value = value self.doc = doc #====== usage ============================================ class MyConstants: __metaclass__ = ConstantsMeta FOO = const(1, 'some docs about foo') BAR = const(2) print MyConstants.FOO.__doc__ help(MyConstants.FOO) print MyConstants.FOO - MyConstants.BAR print MyConstants.FOO - 2 print 1 - MyConstants.BAR #========================================================== Alternatively, forget the metaclass and have: def const(name, val, doc=None): return type(name, (type(val),), {'__doc__': doc})(val) #====== usage ============================================ class MyConstants: FOO = const('FOO', 1, 'some docs about foo') BAR = const('BAR', 2) MOO = const('MOO', 8.0, 'all about MOO') #========================================================== G. From mr.spoon21 at gmail.com Tue Sep 30 06:45:27 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Tue, 30 Sep 2008 12:45:27 +0200 Subject: Weirdness comparing strings Message-ID: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> Hi, I have this piece of code: class Note(): ... ... def has_the_same_name(self, note): return self == note def __str__(self): return self.note_name + accidentals[self.accidentals] __repr__ = __str__ if __name__ == '__main__': n = Note('B') n2 = Note('B') print n print n2 print n.has_the_same_name(n2) I'd expect to get "True", because their string representation is actually the same, instead the output is: B B False I think I'm missing something stupid. Where am I wrong? From marcin201 at gmail.com Sun Sep 28 12:00:34 2008 From: marcin201 at gmail.com (Marcin201) Date: Sun, 28 Sep 2008 09:00:34 -0700 (PDT) Subject: destructor not called Message-ID: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> I have a class which uses a temporary directory for storing data. I would like that directory to be removed when the class is no longer used. I have tried removing the temporary directory from the class destructor, however, it was never called. After I while I traced the problem to the class having a reference to it's own function. Here is a simplified model. test.py class Foo: def __init__(self): print "Hello" self.f = self.fxn def __del__(self): print "Bye" def fxn(self): print "function" a = Foo() running python test.py I get Hello Is this an expected behavior or a bug in python? If this is expected any suggestions for working around this. I would like to avoid having to call the destructor explicitly. Thanks, Marcin From sturlamolden at yahoo.no Mon Sep 29 13:35:58 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 29 Sep 2008 10:35:58 -0700 (PDT) Subject: blocking all threads References: <1d161e02-4b39-462c-a485-d93eb0423e9b@v13g2000pro.googlegroups.com> Message-ID: <758e8fde-69cf-482d-99c3-c13920422e80@m44g2000hsc.googlegroups.com> On Sep 29, 4:56?pm, Alexandru Mosoi <brtz... at gmail.com> wrote: > how can I block all threads for a specific amount of time? (i need to > sleep whole process for testing purposes). i thought of accessing GIL > and sleep for some amount of time, but I don't know how to do this and > whether GIL is recursive. You could do this in C by sleeping while holding the GIL: #ifdef WIN32 #include <Windows.h> #define __sleep(ms) Sleep((DWORD)ms) #else #include <unistd.h> #define __sleep(ms) usleep((useconds_t)ms) #endif __declspec(dllexport) void sleep(int ms) { __sleep(ms); } Save this in a file called "gilsleep.c" and compile it as a DLL (gilslepp.dll in Windows, gilsleep.so in Linux). Then in Python: import ctypes sleep = ctypes.pydll.gilsleep.sleep sleep.argtypes = (ctypes.c_int,) sleep.restype = None sleep(500) # blocks all threads for 500 ms From deets at nospam.web.de Tue Sep 23 11:06:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 23 Sep 2008 17:06:27 +0200 Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> Message-ID: <6jsevmF4uaq4U1@mid.uni-berlin.de> hrishy wrote: > Hi > > Will LINQ be ported to Python ? Take a look at SQLAlchemy or SQLObject for python-based ORM/SQL-abstractions. Apart from that, python is already heavily based on concepts like iterators, filtering. Take a look at itertools. Diez From ter at topazcode.com Tue Sep 2 20:48:23 2008 From: ter at topazcode.com (topazcode) Date: Tue, 2 Sep 2008 17:48:23 -0700 (PDT) Subject: Storing Subprocess Results References: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> <09d82341-3005-4be4-8567-e86faa7ee72a@a8g2000prf.googlegroups.com> Message-ID: <2371e7ce-32d0-4881-aaf2-34261391bddb@m3g2000hsc.googlegroups.com> On Sep 2, 6:31?pm, Karthik Gurusamy <kar1... at gmail.com> wrote: > On Sep 2, 7:16?am, topazcode <t... at topazcode.com> wrote: > > > I am using the subprocess module to run some shell commands on a Linux > > system: > > > import subprocess > > output = subprocess.call('''ssh server1 "uptime"''', shell=True) > > > The above assigns the output variable with a return code, i.e. 0 in > > this case. ?How can I actually capture the data returned from > > subprocess.call, rather than just the return code? ?I'd like to have > > the output variable contain the uptime string in this case. > > Probably commands module is a better choice for your problem:>>> import commands > >>> commands.getoutput('fortune') > > "While money can't buy happiness, it certainly lets you choose your own > \nform of misery." > > > > Karthik > > ?Any help > > > is appreciated. ?Thanks. Thanks guys. I went ahead and used subprocess.Popen as suggested and that works fine. Did something like: import subprocess subprocess.Popen("uptime", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_value, stderr_value = subprocess.communicate() The above worked great. The 'uptime' was actually a fairly long stretch of commands, and this allows me to check for STDERR and act accordingly. Thanks again for the help and suggestions. From justin.kuto at gmail.com Fri Sep 26 17:43:47 2008 From: justin.kuto at gmail.com (afrogazer) Date: Fri, 26 Sep 2008 14:43:47 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> <f0c482f1-7148-43c4-87b1-3b4718d5d18d@8g2000hse.googlegroups.com> <7b1181e9-16a2-458a-8677-a2d8d7c8a961@l42g2000hsc.googlegroups.com> Message-ID: <e670c0f7-8c4b-4187-a58a-cd4b62944576@e39g2000hsf.googlegroups.com> On Sep 26, 3:33?pm, afrogazer <justin.k... at gmail.com> wrote: > In my rush I seem to have overlooked that, maybe because it's Friday > afternoon. Converting the degrees to radians fixed it: > > rad_angles = [elem*(pi/180) for elem in angles] > > Thanks, One other caveat, some of the bars may over-lap. To prevent this, the width can be set by converting it to radians too: w = 45*pi/180 bar(angles, data, alpha=0.75, align='center', width=w, linewidth=0) Now onto plotting clockwise with North(0 deg.) on top.... From grante at visi.com Wed Sep 17 22:58:11 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 17 Sep 2008 21:58:11 -0500 Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <tvkf941kmehd7hcihihdiil6fjutbfkf6k@4ax.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> <gas6t7$382$1@lust.ihug.co.nz> Message-ID: <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> On 2008-09-18, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote: > In message ><973f75d4-90f5-4930-9107-15fc8651196d at v16g2000prc.googlegroups.com>, sui > wrote: > >> Traceback (most recent call last): >> File "mail5.py", line 21, in <module> >> session = smtplib.SMTP(SMTPserver,port) >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ >> (code, msg) = self.connect(host, port) >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect >> self.sock.connect(sa) >> File "<string>", line 1, in connect >> then conncetion time out..... > > Could it be your ISP is blocking outgoing connections to port > 25? gmail doesn't accept mail via SMTP on port 25. -- Grant From python.list at tim.thechases.com Mon Sep 15 14:26:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Sep 2008 13:26:06 -0500 Subject: Unable to see os.environ['COLUMNS'] In-Reply-To: <galrei$bm1$1@news.lysator.liu.se> References: <mailman.1024.1221453482.3487.python-list@python.org> <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> <mailman.1031.1221475955.3487.python-list@python.org> <galrei$bm1$1@news.lysator.liu.se> Message-ID: <48CEA8BE.8020308@tim.thechases.com> Thomas Bellman wrote: > Tim Chase <python.list at tim.thechases.com> writes: > >>> $ export COLUMNS >>> >>> $ python -c "import os; print os.environ['COLUMNS']" >>> 80 > >> This works well, and also manages to keep up to date across runs >> as window-size changes. > > Now try this: > > $ export COLUMNS > $ python -c "import time, os; time.sleep(60); print os.environ['COLUMNS']" > > and change the window width during that sleep. Yes, I did try something similar in my experimenting: $ export COLUMNS $ python >>> import os >>> print os.environ['COLUMNS'] 80 >>> # resize to some other width >>> print os.environ['COLUMNS'] 80 However, for my particular use-case, it's merely for output formatting of a short-running process (akin to "svn status" output). If you resize it in the middle of the sub-second operation, you deserve what you get :) It is disappointing that something so cross-platform as "what's my output width" isn't built-in, requiring jumping through hoops, in ways that aren't cross-platform. The ioctl() method worked on my *nix-like boxes, as did the ncurses versions. However on Win32, neither worked: C:\Temp>python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> # try the Curses version: ... >>> import curses Traceback (most recent call last): File "<stdin>", line 1, in ? File "c:\Program Files\Python24\lib\curses\__init__.py", line 15, in ? from _curses import * ImportError: No module named _curses >>> # try the ioctl version: ... >>> import fcntl Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named fcntl >>> import termios Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named termios >>> So for cross-platform'ness on Win32, you wander over here: http://code.activestate.com/recipes/440694/ Abstracting all this mess in a cross-platform sort of way would be a nice "batteries included" tool to have. Based on the other thread that Grant directed me to and the comments in the Win32 page, I'm not the first to have hoped for such an built-in. Fortunately, for now I'm mostly focused on the *nix side of things and have enough to get it working for now. Thanks to those who gave their input. -tkc From castironpi at gmail.com Sat Sep 27 09:10:20 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 06:10:20 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> <mailman.1586.1222518539.3487.python-list@python.org> Message-ID: <e8264caa-1fc2-49ea-8d40-022dfe0cbafe@k7g2000hsd.googlegroups.com> On Sep 27, 7:28?am, "Dotan Cohen" <dotanco... at gmail.com> wrote: > 2008/9/27 Aaron Castironpi Brady <castiro... at gmail.com>: > > >> I think in June and July they were selling watches a lot which I > >> haven't noticed recently. > > > Gucci 104 G-Bandeau Watches - Gucci Watches Discount Rolex Oyster > > Perpetual Lady Datejust Pearlmaster 18kt Yellow Gold Diamond Ladies > > Watch 80318C > > Cartier Must 21 Watches - Cartier Watches Discount > > > I speak too soon. > > If we start blocking users who have no previous posts and then post > many new messages at once, then we wll just push the spammers to forge > active list users and reply to threads. That would be a worse > situation then we are in now. I say leave well enough alone. > > Read about the Brain Blood Barrier > (http://en.wikipedia.org/wiki/Brain_Blood_Barrier) for an example in > nature where although a method to stop an attacker exists, it is not > overused to prevent the attacker from becoming more powerful. > > -- > Dotan Cohen > > http://what-is-what.comhttp://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > ?-?-?-?-?-?-? Yow! I forgot the radiolabeled polyethylene glycol coated hexadecylcyanoacrylate nanospheres! CMIIW correct me if I'm wrong. Google Groups is a Usenet/c-l-py gateway. Other gateways aren't contributing to spam. What are they doing that G-Groups is not? From larry.bates at vitalEsafe.com Tue Sep 9 09:19:04 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 09 Sep 2008 08:19:04 -0500 Subject: creating an (inefficent) alternating regular expression from a list of options In-Reply-To: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: <xFuxk.29594$bx1.5153@bignews1.bellsouth.net> metaperl.com wrote: > Pyparsing has a really nice feature that I want in PLY. I want to > specify a list of strings and have them converted to a regular > expression. > > A Perl module which does an aggressively optimizing job of this is > Regexp::List - > http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm > > I really dont care if the expression is optimal. So the goal is > something like: > > vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| > u|ii|i)' > > Is there a public module available for this purpose? > > Perhaps I'm missing something but your function call oneOf(...) is longer than than actually specifying the result. You can certainly write quite easily: def oneOf(s): return "|".join(s.split()) -Larry From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 04:45:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 10:45:58 +0200 Subject: how to find position of dictionary values In-Reply-To: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> References: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> Message-ID: <48bbab73$0$27858$426a34cc@news.free.fr> lee a ?crit : > hi, > i have a dictionary as follows : > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > if user is enters the 3rd item of key phno, > ie "dfsdf" in my dict, > how can i find it is the third item in the internal list of phno of > that dictionary? It's quite simple (hint : read the FineManual(tm) for dict.items() and list.index()), but 1/totally inefficient and 2/not garanteed to yield a single value (what if 'dfsdf' happens to be also the 4th item of the list bound to key 'address' ?). May I suggest you rethink your data structure instead ? What you have here is obviously a collection of 'phno/email/name/address'records. These records shouldn't be split across different objects. Assuming 'phno' is a unique identifier for each record, a better data structure would be: records = { 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, # etc } This way, the lookup is as simple and efficient as possible. My 2 cents.... From rcdailey at gmail.com Thu Sep 4 18:37:58 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Sep 2008 17:37:58 -0500 Subject: Case-insensitive string compare? In-Reply-To: <g9pn28$4u1$1@ger.gmane.org> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <g9pn28$4u1$1@ger.gmane.org> Message-ID: <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> On Thu, Sep 4, 2008 at 5:21 PM, Fredrik Lundh <fredrik at pythonware.com>wrote: > Robert Dailey wrote: > > I currently have a dictionary object that I'm doing the following with: >> >> if lib not in stage_map: >> # ... do stuff ... >> >> However, this will perform a case-sensitive comparison between lib and >> each key in stage_map. Is there a way to make this do a case-insensitive >> comparison instead? >> > > dictionary lookups use the exact value. to make a case-insensitive lookup, > use key.lower() instead of key when creating the dictionary, and then do > > if lib.lower() not in state_map: > ... So you're saying to ensure that stage_map's keys are initially lower-case to begin with? Well, I can't do this either since the case of the keys is actually valuable later on. It's only for the purposes of this specific comparison operation that the case should be ignored. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080904/e4eb64ae/attachment.html> From spammaster.10.webmaster at spamgourmet.com Tue Sep 16 03:54:51 2008 From: spammaster.10.webmaster at spamgourmet.com (spammaster.10.webmaster at spamgourmet.com) Date: Tue, 16 Sep 2008 00:54:51 -0700 (PDT) Subject: PyMarshal Commands crash on Windows References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> <mailman.1015.1221420768.3487.python-list@python.org> <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> Message-ID: <d1c8807e-3853-4818-bd16-8926e2919aaf@z72g2000hsb.googlegroups.com> Hi! Any ideas on it? From tino at wildenhain.de Thu Sep 25 03:51:07 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 25 Sep 2008 09:51:07 +0200 Subject: How to parse a string completely into a list In-Reply-To: <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> References: <e9e4f5c7-3467-4078-a401-fb732d69cc64@a3g2000prm.googlegroups.com> <mailman.1479.1222314277.3487.python-list@python.org> <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <mailman.1480.1222315955.3487.python-list@python.org> <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> Message-ID: <48DB42EB.6090001@wildenhain.de> john.ford at colorado.edu wrote: > On Sep 24, 10:12 pm, Matt Nordhoff <mnordh... at mattnordhoff.com> wrote: >> john.f... at colorado.edu wrote: >>> On Sep 24, 9:44 pm, "Chris Rebert" <c... at rebertia.com> wrote: .... >>>> Could you please define exactly what you mean by "elements" of a string? >>>> If you mean characters, then just use list():>>> list(" \n \t abc") >>>> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] >>>> Regards, >>>> Chris >>> Worked like a charm. >>> kudos! >> Why do you need to convert it to a list? Strings are sequences, so you >> can do things like slice them or iterate through them by character: >> >>>>> for character in "foo": >> ... print character >> ... >> f >> o >> o >> >> -- > > The string draws a map that I then want to be able to traverse > through. If I can count through the individual characters of a list I > can create an x-y coordinate plane for navigation. You can 'count' (whatever that means) equally in strings as you do in lists. As said above, they behave exactly the same. Just strings are imutable - e.g. you can't change individual parts of them. Tino > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080925/ec4919ab/attachment.bin> From rmacneill at gmail.com Thu Sep 18 19:39:59 2008 From: rmacneill at gmail.com (rmac) Date: Thu, 18 Sep 2008 16:39:59 -0700 (PDT) Subject: Python newbie question re Strings and integers References: <c0287f45-1c5a-40b5-aff3-ab5639d26749@k13g2000hse.googlegroups.com> <mailman.1249.1221781022.3487.python-list@python.org> Message-ID: <4703bda4-1028-4202-ac07-fe6afdc1f67e@l64g2000hse.googlegroups.com> Ah! Arghh!!! You are so correct on the usage of the ':' Python syntax is a little different from what I am used to. Thank you. From marco.bizzarri at gmail.com Wed Sep 10 13:22:17 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 10 Sep 2008 19:22:17 +0200 Subject: Adding further report options to unittest.py In-Reply-To: <6iq07jFs30egU1@mid.uni-berlin.de> References: <mailman.783.1221052761.3487.python-list@python.org> <6iq07jFs30egU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809101022q1d47d816i2a43972bc2eedcf@mail.gmail.com> On Wed, Sep 10, 2008 at 3:25 PM, Diez B. Roggisch <deets at nospam.web.de> wrote: > Marco Bizzarri wrote: > >> Hi all. >> >> I would like to change the way test reports are generated, in a Zope >> environment. >> > > Have you looked at nosetests? Nose is a test-discovery & running-framework > based upon unittest-module (but you can also "only" test simple functions, > very handy) Nope; next time I will make a google search before posting ;) > And it has a very powerful plugin-mechanism, that allows you to implement > cleanly what you want. > > For each test, you get a start/end-method called in your plugin that you can > use to gather the information you need, e.g. start/stop-times. I gave it a look; it is nice and it seems powerful; I just wonder if I need to put my hands on all my tests to do what I want to do... but I'm sure this can be sorted in the documentation. > For example, I've created an enhanced reporting plugin that lists all tests > run (not only those failed or error'ed), and adding time-measuring per-test > is on my list of todos. Looks like there is a new tool I need to learn... ah, nice times when all you needed was an hammer and a screwdriver... ;) Thanks for the suggestion, Diez, I'll read it. > Diez > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From mnordhoff at mattnordhoff.com Tue Sep 9 15:00:41 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 09 Sep 2008 19:00:41 +0000 Subject: check if the values are prensent in a list of values In-Reply-To: <ga6egs$hjf$1@ger.gmane.org> References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> <ga6egs$hjf$1@ger.gmane.org> Message-ID: <48C6C7D9.7080900@mattnordhoff.com> Emile van Sebille wrote: > flit wrote: >> Hello All, >> >> I will appreciate the help from the more skillfull pythonistas.. >> >> I have a small app that generates a sequence like >> >> 00341 >> 01741 >> 03254 > > Consider using a dict with sorted tuple keys, eg > > d = {} > > for seq in ['00341','01741','03254']: > ky = list(seq) > ky.sort() > d[tuple(ky)] = None > > > then d.keys() are the unique combinations. > > HTH, > > Emile I'm not judging whether this is a good solution or not, but that's a silly use of a dict. A set would be better. s = set() for seq in ['00341','01741','03254']: s.add(tuple(sorted(ky))) Then you just, well, access the set directly, instead of using d.keys() or something. (I also replaced the sorting with the sorted() function for brevity. This all assumes you have at least Python 2.4...) >> This values I am putting in a list. >> >> So I have a list = [00341,01741,03254] >> >> after the programs find the sequence 03401 this sequence is "new" so >> it appends on the list. But I want to avoid that as the values are >> already on the first sequence of the list (00341). >> If I try to use a "in" statement it will give false. as 00341 is >> different from 00341 (but for my goal not..) >> >> >> How can I check against this list and avoid to put "different" >> sequences but same values? >> >> as 34100 --> dont append on the list >> 14300 ---> dont append on the list >> 05321 --> append to the list. >> >> Am I doing some conceptual error using lists? >> There is a better approach? >> >> Thanks -- From dieter at handshake.de Thu Sep 18 13:13:28 2008 From: dieter at handshake.de (Dieter Maurer) Date: 18 Sep 2008 19:13:28 +0200 Subject: Zsi interoperability In-Reply-To: <mailman.1089.1221546702.3487.python-list@python.org> References: <mailman.1047.1221498380.3487.python-list@python.org> <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> <3f0d61c40809151126n791b1ce0ya1e208a075660934@mail.gmail.com> <mailman.1089.1221546702.3487.python-list@python.org> Message-ID: <x7vdwtv0lj.fsf@handshake.de> Mailing List SVR <lists at svrinformatica.it> writes on Tue, 16 Sep 2008 08:31:13 +0200: > ... > however my server require client > certificate authentication, > > does soaplib or zsi work in this environment? ZSI allows you to provide an alternative transport. That's the usual way to let ZSI work over "https" rather than "http". I do not know whether Python supports a client certificate authentication transport out of the box -- but at least the problem is split into two easier parts. Dieter From pavlovevidence at gmail.com Thu Sep 4 15:19:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 12:19:28 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> <f1b92bb7-f960-4e56-b8be-240cfc301726@b38g2000prf.googlegroups.com> Message-ID: <a547e63a-7315-48fe-bb04-97902dbc879a@z6g2000pre.googlegroups.com> On Sep 4, 12:36 pm, bukzor <workithar... at gmail.com> wrote: > > >>> so unfortunately I think I need to use __getattribute__ > > >>> to do this. I'm doing all this just to make the connection not > > >>> actually connect until used. > > >> I may be dumb, but I don't get how this is supposed to solve your > > >> problem. But anyway : there's a known design pattern for what you're > > >> trying to do, that doesn't require mixins nor messing with > > >> __getattribute__ (which, I repeat, is more often than not something you > > >> *don't* want to do). The name of the design pattern is "proxy". I > > >> strongly suggest that you 1/ try to cure the real problem instead of > > >> hacking around and 2/ read about the proxy design pattern. > > > >> My 2 cents... > > > > I like the idea of mix-ins, but can't figure out how to make a proxy > > > work that way. > > > You mean, "how to use a proxy for lazy initialization" ? Heck, that's > > the exact use case in the GoF. > > I mean, "how to make a MixIn class that uses the proxy pattern". You don't. That's not how proxies work. > I'd like to be able to do something like this: > > class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ..., > VanillaCursor): pass Why does it have to look like that? A good programmer lets the code look however it has to look to most effectively do it's job. With a proxy, the "base class" isn't a base class but a member. Here is a very simple example: class SuperCursor(object): def __init__(self): self._cursor = VanillaCursor() self._connected = False def __getattr__(self,attr): if not self._connected: self._cursor.connect() self._connected = True return getattr(self._cursor,attr) cursor = SuperCursor() That doens't use a mixin, but why should it? Carl Banks From mr.spoon21 at gmail.com Tue Sep 30 06:58:27 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Tue, 30 Sep 2008 12:58:27 +0200 Subject: Weirdness comparing strings In-Reply-To: <48E205A4.3020003@seehart.com> References: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> <48E205A4.3020003@seehart.com> Message-ID: <8f67b6f80809300358r6648d8b7v513df0118e6ca33c@mail.gmail.com> On Tue, Sep 30, 2008 at 12:55 PM, Ken Seehart <ken at seehart.com> wrote: > Instance comparison is not necessarily the same as string comparison. > Neither __str__ nor __repr__ are implicitly used at all for comparison. Ok, I see. > In fact, by default a pair of instances are not equal unless they are the > same object. To define comparison to mean something, you need to define > __cmp__ or __eq__. > > Trivial example of default comparison: > >>>> class C: > ... pass > ... >>>> c = C() >>>> d = C() >>>> c==d > False >>>> c==c > True Thanks. Almar Klein: >but this does not implicitly convert self to a string. You'll have to >do in explicitly: >use "return str(self) == note" instead. Yes, this works. Thanks. From graham at vpac.org Tue Sep 16 00:41:29 2008 From: graham at vpac.org (Graham Jenkins) Date: Tue, 16 Sep 2008 14:41:29 +1000 Subject: cups.Connection.printFile Message-ID: <1221540089.17354.7.camel@sys04.in.vpac.org> I'm trying to print a file from within a Python program. The quick-and-dirty solution is to use something like: fd = os.popen("lp -d MyPrinter", "wb") fd.write(MyFileContents) But it seems to me that there should be a clean solution like: import cups stat = cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") Unfortunately, I can't get this to work; not sure of the syntax and have no idea of what to put for "MyOptions". So, can anybody help with an example please? Also .. does anybody know of a way to print a String in this fashion rather than a File? Regards .. -- Graham Jenkins Australian Research Collaboration Service Victorian Partnership for Advanced Computing (+613) 9925-4862 From workitharder at gmail.com Wed Sep 3 18:26:10 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 3 Sep 2008 15:26:10 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> Message-ID: <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> On Sep 3, 1:02?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > bukzor a ?crit : > (snip) > > > Thanks for the reply. Just to see it not work, I tried to remove > > __getattribute__ from LateInitMixIn, but couldn't get it to work. > > ??? Sorry, I don't get what you mean... Since you said __getattribute__ is an attribute of the class, I tried to run (something to the effect of) delattr(self.__class__, "__getattribute__"), but it threw an AttributeError. > > > My Base class is a C class (_mysql.connection from MySQLdb) that > > sometimes segfaults if you try to use it before it's fully > > initialized, > > > ... I have used MySQLdb for years on more than a dozen linux > distribs, and never had such a problem. Is this a known bug ? Or is > there something wrong with your setup ? I'm trying to optimize my number of connections by not fully initializing (read: not connecting) my connection until it's used in some way. Of course the maintainer didn't envision this (mis)use, so the object sometimes throws bad errors until it's fully initialized. Of course the *correct* way to do this is to be more careful about when I create connections, but I think I should be able to get this to work, and it (would be) much easier to do it The Right Way once it works. > > so unfortunately I think I need to use __getattribute__ > > to do this. I'm doing all this just to make the connection not > > actually connect until used. > > I may be dumb, but I don't get how this is supposed to solve your > problem. But anyway : there's a known design pattern for what you're > trying to do, that doesn't require mixins nor messing with > __getattribute__ (which, I repeat, is more often than not something you > *don't* want to do). The name of the design pattern is "proxy". I > strongly suggest that you 1/ try to cure the real problem instead of > hacking around and 2/ read about the proxy design pattern. > > My 2 cents... I like the idea of mix-ins, but can't figure out how to make a proxy work that way. For a long time I had a proxy class that added five or six features on top of the MySQLdb package, but it wasn't configurable enough, and I'm working on splitting each feature into its own MixIn class. As an aside, this is working for me pretty well. The "reconnect" method (inheritied from a "Reconnectable" mixin) uses several of the object's attributes, so I need to set _inited beforehand so that I don't get into an infinite __getattribute__ loop. What I'd *really* like to do is remove __getattribute__ from the object at that point. def __getattribute__(self, attr): "connect if it would otherwise cause an error." getattr = lambda attr:object.__getattribute__(self, attr) if not getattr("_inited"): print "connecting." setattr(self, "_inited", True) getattr("reconnect")() return getattr(attr) Thanks for your help, --Buck From clodoaldo.pinto at gmail.com Sun Sep 14 10:46:34 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Sun, 14 Sep 2008 07:46:34 -0700 (PDT) Subject: cjson 1.0.5 keyword argument References: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> Message-ID: <818d512c-25d0-4ea3-8553-4152edcc101a@v16g2000prc.googlegroups.com> On Sep 14, 10:33 am, Clodoaldo <clodoaldo.pi... at gmail.com> wrote: > I have installed cjson 1.05 in Fedora 8 (python 2.5.1). > > The cjson home page shows a keyword argument "encoding".http://python.cx.hu/python-cjson/ > > When i use it i get an error: > > >>> cjson.encode('?', encoding='utf8') > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: encode() takes no keyword arguments > > What am i missing? There is no mail list for cjson. The problem is the package from Fedora 8. When i install from source it works. Regards, Clodoaldo From aioe.org at technicalbloke.com Mon Sep 29 13:52:28 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 29 Sep 2008 13:52:28 -0400 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <mailman.1520.1222400746.3487.python-list@python.org> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <gbq5p8$iiq$1@lust.ihug.co.nz> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Message-ID: <gbr4ks$1vv$1@aioe.org> bearophileHUGS at lycos.com wrote: > Lawrence D'Oliveiro: >>> Gnuplot is non-Free software. > > Fly Away: >> Yes, it is. > > From: > http://www.gnuplot.info/faq/faq.txt > > 1.7 Does gnuplot have anything to do with the FSF and the GNU project? > [...] > Gnuplot is freeware in the sense that you don't have to pay for it. > However > it is not freeware in the sense that you would be allowed to > distribute a > modified version of your gnuplot freely. [...] > > Bye, > bearophile Well, ish. You can only distribute modifications to gnuplot itself as patches, but you can distribute it freely and they publish the source so, while it's not GPL free it's tending towards it. Roger. From Graham.Dumpleton at gmail.com Sun Sep 7 19:02:25 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 7 Sep 2008 16:02:25 -0700 (PDT) Subject: Python and M2Crypto question References: <12b278d2-9f78-4fc9-a4f2-7d22c543aeb9@d1g2000hsg.googlegroups.com> Message-ID: <643253ee-c8a7-4ccc-bac2-432ac382e4c3@v39g2000pro.googlegroups.com> On Sep 7, 11:07?pm, Bojan Mihelac <bmihe... at gmail.com> wrote: > Hi all! > > I am trying to install M2Crypto to work on OSX10.5 apache > (mod_python). Error I receive: > > Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5- > macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image > found. ?Did find: > ? ? ? ? /Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg- > tmp/M2Crypto/__m2crypto.so: no matching architecture in universal > wrapper > > I guess that have to do something with x64 architecture but I am > stucked and not able to find a way and to make this work. M2Crypto lib > works good stand alone. See: http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX#Missing_Code_For_Architecture This is mod_wsgi documentation, but same issue applies to mod_python. Graham From obm.mnasir at gmail.com Thu Sep 4 00:15:44 2008 From: obm.mnasir at gmail.com (king) Date: Wed, 3 Sep 2008 21:15:44 -0700 (PDT) Subject: what is next for you, a great opportunity waiting for Message-ID: <ac08783f-2bc1-4945-b401-d0493acc3cf7@59g2000hsb.googlegroups.com> www.hrconsultant.tk From gagsl-py2 at yahoo.com.ar Tue Sep 23 05:48:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Sep 2008 06:48:52 -0300 Subject: Time.sleep(0.0125) not available within Linux References: <27CC3060AF71DA40A5DC85F7D5B70F380522CF11@AWMAIL04.belcan.com> Message-ID: <op.uhxhjqt6x6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 22 Sep 2008 23:09:50 -0300, Blubaugh, David A. <dblubaugh at belcan.com> escribi?: > I was wondering if anyone has come across the issue of not being allowed > to have the following within a Python script operating under Linux: > > time.sleep(0.0125) > > It appears that I am not allowed to have the object sleep. Has anyone > encountered this specific issue before in the past? I bet your test script is called time.py, or there is a time.py[c] in the same directory, or somewhere in the Python search path. Move/rename the offending module. If I win, it's because my psychic capabilities allow me to translate "I am not allowed to have the object sleep" to "this line of code raises AttributeError". Next time please post the complete traceback... -- Gabriel Genellina From castironpi at gmail.com Fri Sep 19 00:38:09 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 18 Sep 2008 21:38:09 -0700 (PDT) Subject: Extracting hte font name from a TrueType font file References: <gau1dk$t7h$1@ger.gmane.org> <gaudl8$6s2$2@ger.gmane.org> <mailman.1252.1221785381.3487.python-list@python.org> Message-ID: <b6d97134-616b-4b14-aeaf-df64bc3769fb@m36g2000hse.googlegroups.com> On Sep 18, 7:48?pm, Steve Holden <st... at holdenweb.com> wrote: > Fredrik Lundh wrote: > > Steve Holden wrote: > > >> Does anyone have a Python recipe for this? > > >>>> from PIL import ImageFont > >>>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1) > >>>> f.font.family > > 'Verdana' > >>>> f.font.style > > 'Italic' > > Thanks so much, Fredrik. The reason I asked is because I found the > specification completely opaque ... > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Here's the code to parse the spec. #customize path f= open( '\\windows\\fonts\\arial.ttf', 'rb' ) from struct import * #header shead= Struct( '>IHHHH' ) fhead= f.read( shead.size ) dhead= shead.unpack_from( fhead, 0 ) #font directory stable= Struct( '>4sIII' ) ftable= f.read( stable.size* dhead[ 1 ] ) for i in range( dhead[1] ): #directory records dtable= stable.unpack_from( ftable, i* stable.size ) if dtable[0]== 'name': break assert dtable[0]== 'name' #name table f.seek( dtable[2] ) #at offset fnametable= f.read( dtable[3] ) #length snamehead= Struct( '>HHH' ) #name table head dnamehead= snamehead.unpack_from( fnametable, 0 ) sname= Struct( '>HHHHHH' ) for i in range( dnamehead[1] ): #name table records dname= sname.unpack_from( fnametable, snamehead.size+ i* sname.size ) if dname[3]== 4: #key == 4: "full name of font" s= unpack_from( '%is'% dname[4], fnametable, dnamehead[2]+ dname[5] )[0] print dname, s This outputs: (0, 3, 0, 4, 10, 318) A r i a l (1, 0, 0, 4, 5, 4081) Arial (3, 1, 1033, 4, 10, 318) A r i a l First 3 fields: 0, 3, 0= Unicode, Unicode 2.0, English 1, 0, 0= Macintosh, Default, English 3, 1, 1033= Windows, Version 1.1, Language "1033" From tjreedy at udel.edu Sun Sep 28 03:20:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 03:20:28 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00eee9ec$0$20666$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <gbkfhv$g2$1@panix3.panix.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <gblea5$os6$1@panix3.panix.com> <mailman.1600.1222551713.3487.python-list@python.org> <00eee9ec$0$20666$c3e8da3@news.astraweb.com> Message-ID: <gbnb7s$272$1@ger.gmane.org> Steven D'Aprano wrote: > And modules aren't callable. I've often thought they should be. Modules are not callable because their class, module, has no __call__ instance method. But (in 3.0, which is all I will check) you can subclass module and add one. >>> m = type(__builtins__) >>> m <class 'module'> >>> dir(m) ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] >>> class m2(m): def __call__(self, *args, **kwds): print(self, args, kwds) >>> mod = m2('mod') # only arg required by module.__init__ >>> mod(1,2,3,a=4,b=5) <module 'mod' (built-in)> (1, 2, 3) {'a': 4, 'b': 5} >>> mod # did not override __repr__ <module 'mod' (built-in)> So, roll your own to your taste. Terry Jan Reedy From adam.pletcher at volition-inc.com Wed Sep 10 14:08:56 2008 From: adam.pletcher at volition-inc.com (Adam Pletcher) Date: Wed, 10 Sep 2008 13:08:56 -0500 Subject: removing text string In-Reply-To: <A86D1A0C2B238848B9ABDE1A7E287CE6010E0F55@EXCHVS01.ad.sfwmd.gov> References: <loom.20080910T144026-626@post.gmane.org> <A86D1A0C2B238848B9ABDE1A7E287CE6010E0F55@EXCHVS01.ad.sfwmd.gov> Message-ID: <893A44FF792E904A97B7515CE341914604238A24@volimxs01.thqinc.com> You just want to drop the last two characters? Slice it. >>> s = "080829-7_A"[:-2] >>> print s 080829-7 - Adam > -----Original Message----- > From: python-list-bounces+adam=volition-inc.com at python.org > [mailto:python-list-bounces+adam=volition-inc.com at python.org] On Behalf > Of Ahmed, Shakir > Sent: Wednesday, September 10, 2008 10:22 AM > To: python-list at python.org > Subject: removing text string > > I need to remove text string from the list of the numbers mentioned > below: > > 080829-7_A > 070529-5_c > 080824-7_O > 070405_6_p > > The output will be : 080829-7 > 070529-5 > 080824-7 > 070405-6 > > Any idea is highly appreciated. > > > > -- > http://mail.python.org/mailman/listinfo/python-list From nytrokiss at gmail.com Thu Sep 18 16:10:49 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 18 Sep 2008 13:10:49 -0700 Subject: Twisted vs Python Sockets Message-ID: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> Hi I am wondering what are the major points of twisted over regular python sockets. I am looking to write a TCP server and want to know the pros can cons of using one over the other. Thanks James -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/f6040166/attachment.html> From marek.rocki at wp.pl Thu Sep 18 11:30:47 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Thu, 18 Sep 2008 08:30:47 -0700 (PDT) Subject: dict generator question References: <mailman.1217.1221749709.3487.python-list@python.org> Message-ID: <29e1af82-9a78-4b3b-87e4-1e13dcaeb508@26g2000hsk.googlegroups.com> Simon Mullis napisa?(a): > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. It seems to me that the "count" you're looking for is the number of elements from l whose first 3 characters are the same as the v[0:3] thing. So you may try: >>> dict_of_counts = dict((v[0:3], sum(1 for x in l if x[:3] == v[:3])) for v in l) But this isn't particularly efficient. The 'canonical way' to construct such histograms/frequency counts in python is probably by using defaultdict: >>> dict_of_counts = collections.defaultdict(int) >>> for x in l: >>> dict_of_counts[x[:3]] += 1 Regards, Marek From lists at svrinformatica.it Mon Sep 15 13:06:00 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Mon, 15 Sep 2008 19:06:00 +0200 Subject: Zsi interoperability Message-ID: <1221498360.5891.33.camel@localhost.localdomain> Hi, I have to implement a soap web services from wsdl, the server is developed using oracle, is zsi or some other python library for soap interoperable with oracle soa? thanks Nicola From mail at microcorp.co.za Fri Sep 12 16:20:42 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 12 Sep 2008 22:20:42 +0200 Subject: dict slice in python (translating perl to python} Message-ID: <003f01c9151c$ab471600$0d00a8c0@hendrik> MRAB <googl....arnett.plus.com> wrote: >On Sep 11, 6:11 pm, Fredrik Lundh <fred... at pythonware.com> wrote: >[snip] >> (the next step towards true Pythonicness would be to store your data in 8<----------------------- >> >Surely the word is "Pythonicity"? :-) When faced with the choice between "Pythonicness" and "Pythonicity", I feel a bit like Ogden Nash must have felt when he wrote: The Camel has a single hump, The Dromedary, two. Or the other way around. I'm never sure, are you? - Hendrik From aahz at pythoncraft.com Fri Sep 26 00:17:14 2008 From: aahz at pythoncraft.com (Aahz) Date: 25 Sep 2008 21:17:14 -0700 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <y9udnWtzwLtQi0rVnZ2dnUVZ_gidnZ2d@earthlink.com> Message-ID: <gbhnoa$d83$1@panix3.panix.com> In article <y9udnWtzwLtQi0rVnZ2dnUVZ_gidnZ2d at earthlink.com>, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: >On 21 Sep 2008 22:39:47 GMT, Steven D'Aprano ><steve at REMOVE-THIS-cybersource.com.au> declaimed the following in >comp.lang.python: >> >> What do you call such a class? > > A wasted definition... The same functionality is achieved by just >creating and importing a module. Your "class methods" would just be >functions within the module; class level attributes would be module >level objects (access with global if writing to them, use a _ to >indicate "internal") Seems to me that if all the module is used for is to store state, you're wasting a file on disk. I personally prefer to use a class singleton. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From fredrik at pythonware.com Sun Sep 21 11:12:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 17:12:00 +0200 Subject: Override the '+' symbol In-Reply-To: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> References: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> Message-ID: <gb5o81$f3f$2@ger.gmane.org> Mr.SpOOn wrote: > how can I override the '+' symbol (and other math symbols) so that it > can have a new behavior when applied to some objects? see "Emulating Numeric Types" in the language reference: http://www.python.org/doc/ref/numeric-types.html </F> From skip at pobox.com Tue Sep 23 10:15:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Sep 2008 09:15:07 -0500 Subject: Python is slow? In-Reply-To: <Y7CdnYRzU-8naEXVnZ2dnUVZ_sDinZ2d@posted.visi> References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <Y7CdnYRzU-8naEXVnZ2dnUVZ_sDinZ2d@posted.visi> Message-ID: <18648.63979.426433.48679@montanaro-dyndns-org.local> >> We may conclude that I'm bad at programming C++, Grant> AFAICT, _everybody_ is bad at programming C++. Grant> One begins to suspect it's not the fault of the programmers. +1 QOTW... Skip From mensanator at aol.com Sat Sep 20 12:30:27 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 20 Sep 2008 09:30:27 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <16b063ae-8b2d-4991-b6ba-d32330e47c59@s50g2000hsb.googlegroups.com> On Sep 20, 11:16?am, Alex Snast <asn... at gmail.com> wrote: > Hello > > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) >>> for i in xrange(10,-1,-1): print i, 10 9 8 7 6 5 4 3 2 1 0 Note the starting number is 10, the ending number is -1 because you want to include 0 and the step size is -1. From dmitrey.kroshko at scipy.org Sun Sep 21 06:41:05 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 21 Sep 2008 03:41:05 -0700 (PDT) Subject: How to kill threading.Thread instance? Message-ID: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> hi all, Is there a better way to kill threading.Thread (running) instance than this one http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 (it's all I have found via google). BTW, it should be noticed that lots of threading module methods have no docstrings (in my Python 2.5), for example _Thread__bootstrap, _Thread__stop. Regards, D. From milenko.stojadinovic at googlemail.com Sat Sep 27 17:56:07 2008 From: milenko.stojadinovic at googlemail.com (Milenko Stojadinovic Cvrcko) Date: Sat, 27 Sep 2008 14:56:07 -0700 (PDT) Subject: Hello boys! Message-ID: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> Hello, this is Milenko Stojadinovic from town Banjaluka, Bosnia and Herzegovina, also known as Cvrcko Does anyone know of any bars in town where I can swallow a bucket of cum? It can be either dog, horse or human cum. Also, does anyone know of any sex bars where people will shit in your mouth? I also like eating shit. -- Name: Mileno Stojadinovic - Cvrcko Street adress: Sime Matavulja 12 Town: 78000 Banja Luka Country: Bosnia and Herzegovina Home phone: +38751/303-665 Cell phone: +38765/499-312 Email adress: milenko.stojadinovic at googlemail.com ~ The new pumpkin rarely pulls Terrance, it teases Sharon instead. For Susan the tape's sad, beside me it's unique, whereas against you it's believing dirty. Hey, go reject a fork! Why did Alice open throughout all the boats? We can't explain poultices unless Woody will mercilessly judge afterwards. The frames, disks, and shirts are all fat and fresh. Who will we dine after Edwina wastes the thin mirror's goldsmith? It's very outer today, I'll recollect strangely or Christopher will learn the teachers. Hardly any humble brave tyrants hourly solve as the tired wrinkles cover. Hardly any distant buttons are short and other urban ointments are filthy, but will Robette receive that? Let's lift behind the deep highways, but don't promise the heavy diets. Who kicks badly, when Melvin burns the stale code before the autumn? Get your absolutely moulding barber within my cellar. If you will laugh Gay's hill against porters, it will incredibly climb the case. Some shopkeepers arrive, irrigate, and shout. Others sadly expect. To be pathetic or sticky will talk abysmal oranges to wickedly look. Are you healthy, I mean, moving above clever onions? While farmers partly taste pins, the powders often excuse against the blunt jackets. Generally Susanne will order the sticker, and if George actually seeks it too, the bowl will attempt with the polite lane. He can hate durable kettles above the rural bad ocean, whilst Oscar easily scolds them too. You eventually fill against Norma when the kind drapers irritate among the poor summer. As surprisingly as Dolf converses, you can dye the cap much more familiarly. Brion, still killing, behaves almost eerily, as the sauce changes on their coffee. You won't recommend me grasping about your lazy office. Almost no butchers steadily live the lost signal. Cyrus's hat improves among our desk after we sow towards it. Ralph measures the weaver within hers and wanly calls. Some cosmetic tags answer David, and they rigidly walk Quincy too. When Richard's elder gardner dreams, Mark cares for weak, closed islands. He might strongly fear think and plays our cheap, sour painters above a bathroom. I creep the active yogi and cook it in back of its dorm. Tell Katherine it's strong loving within a tree. Why will you jump the angry lower exits before Murray does? I am unbelievably bitter, so I wander you. How does Hector smell so regularly, whenever Ronald likes the solid twig very slowly? Julieta, have a hot printer. You won't clean it. Fucking don't join a dryer! She wants to nibble inner smogs under Usha's castle. She'd rather depart grudgingly than help with Bernadette's younger grocer. Other old dark cards will comb frantically alongside cans. Try pouring the monument's pretty cat and Oliver will attack you! Don't try to seek halfheartedly while you're jumping throughout a easy carpenter. He'll be climbing in front of good Cypriene until his enigma answers quietly. What doesn't Janet smell inadvertently? They are opening before the rain now, won't explain walnuts later. Some light long game covers pools outside Woodrow's rich film. Why did Oscar judge the pear with the handsome spoon? He will talk nearly if Julieta's tailor isn't wet. Just looking beside a ulcer through the store is too young for Woody to care it. Both filling now, Alejandro and Marty irritated the open rivers about smart envelope. Occasionally, dusts kill beside rude fires, unless they're sweet. Her pen was sharp, dull, and fears over the spring. Zack, on floors difficult and upper, attacks towards it, recollecting seemingly. We measure the raw sauce. They are rejecting throughout quiet, towards empty, in back of cold units. My wide potter won't clean before I comb it. If you'll pour Edward's camp with aches, it'll admiringly converse the cup. I was promising frogs to worthwhile Corinne, who's walking in back of the counter's stable. It can receive clean pickles, do you solve them? Many jugs will be weird lean carrots. Roger helps, then Walt stupidly believes a ugly lentil on Catherine's road. We tease them, then we weekly dream Zack and Annabel's blank candle. A lot of shallow dose or canyon, and she'll locally excuse everybody. If the bizarre balls can sow bimonthly, the hollow raindrop may love more ventilators. We laugh weekly, unless Jezebel grasps shoes outside Jimmie's puddle. Jimmy! You'll mould plates. Just now, I'll dine the bandage. All glad strange figs will fully order the lemons. The dog without the proud star is the pitcher that learns happily. It might crudely scold within sick dry satellites. Until Dolf calls the bushs generally, Ann won't join any full winters. Better kick clouds now or Blanche will wrongly hate them over you. There, Jeff never arrives until Joie nibbles the noisy elbow deeply. From aquil.abdullah at gmail.com Mon Sep 8 11:43:20 2008 From: aquil.abdullah at gmail.com (aha) Date: Mon, 8 Sep 2008 08:43:20 -0700 (PDT) Subject: Unable to start a process with subprocess Popen() References: <e0b6c39a0809080350x6deb87dap5cd01c1d54827adf@mail.gmail.com> <mailman.681.1220872998.3487.python-list@python.org> Message-ID: <3657eb2f-c827-4929-be5a-689959de5f85@a1g2000hsb.googlegroups.com> On Sep 8, 7:23?am, dudeja.ra... at gmail.com wrote: > On Mon, Sep 8, 2008 at 11:50 AM, ?<dudeja.ra... at gmail.com> wrote: > > Hi, > > > I'm using the subprocess module's Popen() to start a batch file. This > > batch file basically calls an exe which also gets started. > > Unfortunately, this does not produce any results. I looked into the > > Task bar that this exe has started but it does not consume and cpu so > > I believet that this exe is not working. > > > I used the following command to start the batch fiile: > > > testing = subprocess.Popen([batchFilePath], \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? shell = True, \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stdout = subprocess.PIPE, \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stderr = subprocess.PIPE).communicate()[0] > > > batchFilePath is the path of the batch file. > > > -- > > Regrads, > > Rajat > > Ok, I re-phrase my question: > > there is a batch file that executes a exe file. The batch just works > if run from command prompt and produces output to standard output and > the file. > > Now, I try to call the same batch file from subprocess.Pope() call. > The batch file gets called and that internally also calls the exe > file. > > But, the exe just runs forever i.e. hangs and does not produces output > , atleast not to the file. > > Please suggest is there is something wrong with the above code. > > Regards, > Rajat Hello Rajat, I would take a look at the thread below, it might help it might not: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4505613f014fdec7/3ee15c9c88a5efdc?hl=en#3ee15c9c88a5efdc Also, if you post a larger section of the code I might be able to give you a hand. Once you've run the testing = subprocess.Popen() make sure you use a testing.wait() From castironpi at gmail.com Thu Sep 18 14:22:46 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 18 Sep 2008 11:22:46 -0700 (PDT) Subject: minimum install & pickling References: <fb304bca-abe9-48e6-8dba-6187e33e5a6d@a2g2000prm.googlegroups.com> <6f045535-555f-44b6-93a5-f5b338d3f318@d45g2000hsc.googlegroups.com> <69cf2202-e11b-4994-84ab-a41167ef2652@26g2000hsk.googlegroups.com> <d8e9b368-ee86-415e-b0e6-16958391dfdd@8g2000hse.googlegroups.com> Message-ID: <ac8c3358-3e35-48a5-a22a-af0dab11dae9@x41g2000hsb.googlegroups.com> On Sep 18, 5:20?am, Paul Boddie <p... at boddie.org.uk> wrote: > On 17 Sep, 22:18, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> > wrote: > > > On Sep 17, 4:43?am, Paul Boddie <p... at boddie.org.uk> wrote: > > > >http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...) > > > These solutions have at least the same bugs that the bare bones > > solution in the corresponding framework has. ?Malicious code has fewer > > options, but constructive code does too. ?If you're running foreign > > code, what do you want it to do? ?What does it want to do? ?The more > > options it needs, the more code you have to trust. > > As I noted, instead of just forbidding access to external resources, > what you'd want to do is to control access instead. This idea is not > exactly new: although Brett Cannon was working on a sandbox capability > for CPython, the underlying concepts involving different privilege > domains have been around since Safe-Tcl, if not longer. The advantage > of using various operating system features, potentially together with > tools like fakechroot or, I believe, Plash, is that they should work > for non-Python programs. Certainly, the chances of successfully > introducing people to such capabilities are increased if you don't > have to persuade the CPython core developers to incorporate your > changes into their code. > > > The only way a Python script can return a value is with sys.exit, and > > only an integer at that. ?It is going to have output; maybe there's a > > way to place a maximum limit on its consumption. ?It's going to have > > input, so that the output is relative to something. ?You just make > > copies to prevent it from destroying data. ?Maybe command-line > > parameters are enough. ?IIRC if I recall correctly, Win32 has a way to > > examine how much time a process has owned so far, and a way to > > terminate it, which could be in Python's future. > > There is support for imposing limits on processes in the Python > standard library: > > http://docs.python.org/lib/node521.html > > My experimental package, jailtools, relies on each process's sandbox > being set up explicitly before the process is run, so you'd definitely > want to copy data into the sandbox. Setting limits on the amount of > data produced would probably require support from the operating > system. Generally, when looking into these kinds of systems, most of > the solutions ultimately come from the operating system: process > control, resource utilisation, access control, and so on. (This is the > amusing thing about Java: that Sun attempted to reproduce lots of > things that a decent operating system would provide *and* insist on > their use when deploying Java code in a controlled server environment, > despite actually having a decent operating system to offer already.) > > > PyPy sandbox says: ?"The C code generated by PyPy is not > > segfaultable." ?I find that to be a bold claim (whether it's true or > > not). > > > I'm imagining in the general case, you want the foreign code to make > > changes to objects in your particular context, such as exec x in > > vars. ?In that case, x can still be productive without any libraries, > > just less productive. > > Defining an interface between trusted and untrusted code can be > awkward. When I looked into this kind of thing for my undergraduate > project, I ended up using something similar to CORBA, and my > conclusion was that trusted code would need to expose an interface > that untrusted "agents" would rely on to request operations outside > the sandbox. That seems restrictive, but as the situation with rexec > has shown, if you expose a broad interface to untrusted programs, it > becomes increasingly difficult to verify whether or not the solution > is actually secure. > > Paul I think you could autogenerate a file with a copy of the data, then run a bare bones Python installation with the foreign code that imports the copy, or just concatenate the foreign code and copy. At least for input. For output, you'd need a file that had an upper bound on its size. The problem with Python is that if an agent has access to a part of an object, it has the whole thing. Such as the trusted agents-- if they can perform an operation, then anything with access to the agent can. If they're just policy makers, then however an authorized agent performs the action, is available to an unauthorized one. You'd still need a 'struct' instance to write your output, since memory is upper- bounded, and you can't permit foreign code to store any form of Python objects. From gagsl-py2 at yahoo.com.ar Tue Sep 2 04:36:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 05:36:33 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> Message-ID: <op.uguh67a1x6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 01 Sep 2008 04:23:38 -0300, Jeremy Banks <jeremy at jeremybanks.ca> escribi?: > Hi. I wondered if anyone knew the rationale behind the naming of the > Popen class in the subprocess module. Popen sounds like the a suitable > name for a function that created a subprocess, but the object itself is > a subprocess, not a "popen". It seems that it would be more accurate to > just name the class Subprocess, can anyone explain why this is not the > case? I have no idea - but I agree, Subprocess would have been a better name. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Sep 3 23:11:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 04 Sep 2008 00:11:45 -0300 Subject: email.Message problem References: <20080902160417.GA20438@zephyr> <op.ugvdd1oyx6zn5v@a98gizw.cpe.telecentro.net.ar> <20080903103630.GC11421@zephyr> Message-ID: <op.ugxshvhvx6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 03 Sep 2008 07:36:30 -0300, Corrado Gioannini <gioco at nekhem.com> escribi?: > On Tue, Sep 02, 2008 at 04:50:15PM -0300, Gabriel Genellina wrote: >> > messg = email.message.Message() >> >> Replace this line with: >> messg = email.mime.multipart.MIMEMultipart() >> *OR* >> Set the Content-Type header to "multipart/mixed" *before* anything else. > > thanks Gabriel! > > i coudn't have thought that setting the header in a different order > could affect the as_string method. i'll take a look at the code. :) Yes. This is the offending sequence: messg = email.message.Message() messg.set_charset('ISO-8859-15') messg["Content-type"] = "Multipart/mixed" "Charset" is not a header by itself; it is an optional parameter of the Content-Type header. When you call set_charset(), a default 'Content-Type: text/plain; charset="ISO-8859-15"' header is added. Later, you *add* a new Content-type header -- remember that the [] notation *appends* a new header instead of replacing an existing one (yes, it is somewhat confusing...) Your message ends up being text/plain, not multiplart as intended. It's better to be explicit and use the email.mime.multipart.MIMEMultipart class. -- Gabriel Genellina From samslists at gmail.com Thu Sep 18 04:57:26 2008 From: samslists at gmail.com (Sam) Date: Thu, 18 Sep 2008 01:57:26 -0700 (PDT) Subject: Program works great, except under less, cron or execl (Unicode?) Message-ID: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> I have a program which works great when run from the command line. But when I run it combined with something else such as: - piping it through less - cron - execl (i.e. calling it from another python program) it gives me a unicode error File "../myparser.py", line 261, in set_attributes print "self.atd['Name'] is: ", self.atd['Name'] UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 7: ordinal not in range(128) I'd post the whole program here, except it involves weird Unicode strings. I could probably change the program to get it working under less/cron/ etc. But I'd rather understand exactly what the issue is. Why does it work fine when run directly from the command line, but not otherwise? From inq1ltd at inqvista.com Mon Sep 22 14:43:25 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Mon, 22 Sep 2008 14:43:25 -0400 Subject: Problems running on hp dual core processor Message-ID: <200809221443.25765.inq1ltd@inqvista.com> Python help, I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duel core processor, 2.2G with .099g ram. On the new hp, when they try to print they get an import error; File win32ui.pyc line 12, in <module> File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. The file is there The only difference I could find from their other machines is the processor. From george.sakkis at gmail.com Tue Sep 30 11:04:35 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 30 Sep 2008 08:04:35 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> <87zllqqa1i.fsf@benfinney.id.au> <pan.2008.09.30.10.04.18@REMOVE.THIS.cybersource.com.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> Message-ID: <0b229c8f-61cf-4617-8927-5627edadc9b9@m36g2000hse.googlegroups.com> On Sep 30, 9:43 am, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: > > Steven D'Aprano <ste... at REMOVE.THIS.cybersource.com.au> writes: > > >> On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > >> > You're not free to modify gnuplot and redistribute the result. > > >> > That you're free to distribute patches is nice, but it's not enough > >> > to make the work free. The freedom to help people by giving them an > >> > *already-modified* gnuplot is restricted by the copyright holder. > > >> > It's an artificial restriction on redistribution of derived works, > >> > making them second-class for the prupose of getting them into > >> > people's hands. > > >> Yes it is. It seems a strange, unnecessary restriction. But is it > >> sufficient to make it non-free? I don't think so. > > > I do, because a natural, beneficial act (modify the work and > > redistribute it) that has no technical reason to restrict, is > > artifically restricted. > > We agree that the restriction is artificial, and I think irrational > (although I'd be interested in hearing the gnuplot developers' reasoning > before making a final judgment). > > But I just don't see the requirement that modified software be > distributed in form X (original source + diffs) versus form Y (modified > source in a tar ball) or form Z (an rpm) to be that big a deal. Not > enough to make it "non-free software". > > I simply don't think that having to run some variation on > > patch -i patchfile.patch > > is a requirement so onerous that it makes the gnuplot licence non-free. > Perhaps I'm just more tolerant of eccentricities than you :) What you're missing is that for Free Software (TM) zealots it's a matter of philosophical principle, totally unrelated to how easy is to overcome the restriction. There is not a "practicality beats purity" clause in the FSF Bible. George From maric at aristote.info Wed Sep 3 10:44:10 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 3 Sep 2008 16:44:10 +0200 Subject: properties setting each other In-Reply-To: <g9m54v$hvk$1@ger.gmane.org> References: <g9m54v$hvk$1@ger.gmane.org> Message-ID: <200809031644.10870.maric@aristote.info> Le Wednesday 03 September 2008 15:57:50 mk, vous avez ?crit?: > I try to set two properties, "value" and "square" in the following code, > and arrange it in such way that setting one property also sets another > one and vice versa. But the code seems to get Python into infinite loop: > > ?>>> import math > ?>>> class Squared2(object): > > ????????def __init__(self, val): > ????????????????self._internalval=val > ????????????????self.square=pow(self._internalval,2) > ???????????????? > ????????def fgetvalue(self): > ????????????????return self._internalval > ???????????????? > ????????def fsetvalue(self, val): > ????????????????self._internalval=val > ????????????????self.square=pow(self._internalval,2) > ???????????????? > ????????value = property(fgetvalue, fsetvalue) > > ????????def fgetsquare(self): > ????????????????return self.square > ????????def fsetsquare(self,s): > ????????????????self.square = s > ????????????????self.value = math.sqrt(self.square) > ???????????????? > ????????square = property(fgetsquare, fsetsquare) > > ???????? > ?>>> a=Squared2(5) > > Traceback (most recent call last): > ? ?File "<pyshell#11>", line 1, in <module> > ? ? ?a=Squared2(5) > ? ?File "<pyshell#10>", line 5, in __init__ > ? ? ?self.square=pow(self._internalval,2) > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > > ... > > Is there a way to achieve this goal of two mutually setting properties? Your square property is not correctly defined, it recurselively call itself, it should be (I also avoided the extra lookup) : def fgetsquare(self): return self._square def fsetsquare(self,s): self._square = s self.value = math.sqrt(s) then the fsetvalue will be also be called recursively as it use the square property, you should also write it : def fsetvalue(self, val): self._internalval=val self._square=pow(val,2) *but*, if you want to add more logic in the setters, you could want to add two extra methods : def _setsquare(self, v) : # some extra logic here self._square = s def fsetsquare(self,s): self._setsquare(s) self._setvalue = math.sqrt(s) def _setvalue(self, val): # some extra logic here self._internalval=val def fsetvalue(self, val): self._setvalue(val) self._setsquare=pow(val,2) Note that if one property can really be computed from another, this kind of thing could be considered as bad design (except if the computation is heavy). -- _____________ Maric Michaud From steve at REMOVE-THIS-cybersource.com.au Wed Sep 3 21:30:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 01:30:39 GMT Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <yfs63pcwyip.fsf@gmail.com> Message-ID: <00cf34ad$0$20302$c3e8da3@news.astraweb.com> On Thu, 04 Sep 2008 01:22:22 +0100, Alexander Schmolck wrote: > It seems to me that the right choice for thousands seperator is the > apostrophe. You mean the character already used as a string delimiter? -- Steven From febkimbleox at gmail.com Sat Sep 27 07:17:55 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:17:55 -0700 (PDT) Subject: amateur sex amateur sex videos amateur sex video free amateur sex - Free Message-ID: <6256a559-08a6-4da4-8ae9-6ed51ca5d26b@r66g2000hsg.googlegroups.com> amateur . . . *******CLICK HERE******** http://vids365.cn/amateur ***************************** . . . . . . . . . . . . She could feel the love amateur had for amateur radiate through amateur and amateur made amateur quiver with desire. She could feel the love sex had for sex radiate through sex and sex made sex quiver with desire. She could feel the love amateur had for amateur radiate through amateur and amateur made amateur quiver with desire. She could feel the love sex had for sex radiate through sex and sex made sex quiver with desire. She could feel the love videos had for videos radiate through videos and videos made videos quiver with desire. She could feel the love amateur had for amateur radiate through amateur and amateur made amateur quiver with desire. She could feel the love sex had for sex radiate through sex and sex made sex quiver with desire. She could feel the love video had for video radiate through video and video made video quiver with desire. She could feel the love free had for free radiate through free and free made free quiver with desire. She could feel the love amateur had for amateur radiate through amateur and amateur made amateur quiver with desire. She could feel the love sex had for sex radiate through sex and sex made sex quiver with desire. The following week videos spent a lot of time chatting online with her. The following week free spent a lot of time chatting online with her. The following week amateur spent a lot of time chatting online with her. The following week sex spent a lot of time chatting online with her. The following week amateur spent a lot of time chatting online with her. The following week teen spent a lot of time chatting online with her. The following week sex spent a lot of time chatting online with her. The following week amateur spent a lot of time chatting online with her. The following week sex spent a lot of time chatting online with her. The following week movies spent a lot of time chatting online with her. The following week amateur spent a lot of time chatting online with her. The following week sex spent a lot of time chatting online with her. ?Afterwards, tube fluffed the pillow, straightened the blanket, and then spooned up against tube . ?Afterwards, free fluffed the pillow, straightened the blanket, and then spooned up against free . ?Afterwards, amateur fluffed the pillow, straightened the blanket, and then spooned up against amateur . ?Afterwards, sex fluffed the pillow, straightened the blanket, and then spooned up against sex . ?Afterwards, video fluffed the pillow, straightened the blanket, and then spooned up against video . ?Afterwards, amateur fluffed the pillow, straightened the blanket, and then spooned up against amateur . ?Afterwards, group fluffed the pillow, straightened the blanket, and then spooned up against group . ?Afterwards, sex fluffed the pillow, straightened the blanket, and then spooned up against sex . ?Afterwards, amateur fluffed the pillow, straightened the blanket, and then spooned up against amateur . ?Afterwards, home fluffed the pillow, straightened the blanket, and then spooned up against home . ?Afterwards, sex fluffed the pillow, straightened the blanket, and then spooned up against sex . ?Afterwards, videos fluffed the pillow, straightened the blanket, and then spooned up against videos . amateur was a little way ahead of amateur and amateur could see amateur body start to shake with silent tears. home was a little way ahead of home and home could see home body start to shake with silent tears. sex was a little way ahead of sex and sex could see sex body start to shake with silent tears. amateur was a little way ahead of amateur and amateur could see amateur body start to shake with silent tears. home was a little way ahead of home and home could see home body start to shake with silent tears. sex was a little way ahead of sex and sex could see sex body start to shake with silent tears. video was a little way ahead of video and video could see video body start to shake with silent tears. amateur was a little way ahead of amateur and amateur could see amateur body start to shake with silent tears. couples was a little way ahead of couples and couples could see couples body start to shake with silent tears. sex was a little way ahead of sex and sex could see sex body start to shake with silent tears. videos was a little way ahead of videos and videos could see videos body start to shake with silent tears. long was a little way ahead of long and long could see long body start to shake with silent tears. Valentine?s Day was just around the corner and tapes wanted to do something special for Mandy. Valentine?s Day was just around the corner and amateur wanted to do something special for Mandy. Valentine?s Day was just around the corner and couple wanted to do something special for Mandy. Valentine?s Day was just around the corner and sex wanted to do something special for Mandy. Valentine?s Day was just around the corner and sex wanted to do something special for Mandy. Valentine?s Day was just around the corner and amateur wanted to do something special for Mandy. Valentine?s Day was just around the corner and amateur wanted to do something special for Mandy. Valentine?s Day was just around the corner and anal wanted to do something special for Mandy. Valentine?s Day was just around the corner and sex wanted to do something special for Mandy. Valentine?s Day was just around the corner and amateur wanted to do something special for Mandy. Valentine?s Day was just around the corner and lesbian wanted to do something special for Mandy. Valentine?s Day was just around the corner and sex wanted to do something special for Mandy. As my eyes became used to the dim light amateur could see a darker shadow between the wardrobes and found amateur hiding there. As my eyes became used to the dim light sex could see a darker shadow between the wardrobes and found sex hiding there. As my eyes became used to the dim light tapes could see a darker shadow between the wardrobes and found tapes hiding there. As my eyes became used to the dim light amateur could see a darker shadow between the wardrobes and found amateur hiding there. As my eyes became used to the dim light sex could see a darker shadow between the wardrobes and found sex hiding there. As my eyes became used to the dim light clips could see a darker shadow between the wardrobes and found clips hiding there. As my eyes became used to the dim light amateur could see a darker shadow between the wardrobes and found amateur hiding there. As my eyes became used to the dim light sex could see a darker shadow between the wardrobes and found sex hiding there. As my eyes became used to the dim light tape could see a darker shadow between the wardrobes and found tape hiding there. As my eyes became used to the dim light teen could see a darker shadow between the wardrobes and found teen hiding there. As my eyes became used to the dim light amateur could see a darker shadow between the wardrobes and found amateur hiding there. As my eyes became used to the dim light sex could see a darker shadow between the wardrobes and found sex hiding there. As the mushroom head went deeper inside, real eyes widened and Mandy began to pant. As the mushroom head went deeper inside, amateur eyes widened and Mandy began to pant. As the mushroom head went deeper inside, sex eyes widened and Mandy began to pant. As the mushroom head went deeper inside, amateur eyes widened and Mandy began to pant. As the mushroom head went deeper inside, sex eyes widened and Mandy began to pant. As the mushroom head went deeper inside, photos eyes widened and Mandy began to pant. As the mushroom head went deeper inside, free eyes widened and Mandy began to pant. As the mushroom head went deeper inside, amateur eyes widened and Mandy began to pant. As the mushroom head went deeper inside, home eyes widened and Mandy began to pant. As the mushroom head went deeper inside, sex eyes widened and Mandy began to pant. As the mushroom head went deeper inside, videos eyes widened and Mandy began to pant. As the mushroom head went deeper inside, amateur eyes widened and Mandy began to pant. As the mushroom head went deeper inside, college eyes widened and Mandy began to pant. ? He filled the wine bucket with ice, popped the cork, set the bottle in vids to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in free to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in naked to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in amateur to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in sex to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in videos to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in sites to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in mature to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in amateur to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in sex to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in amateur to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in sex to chill, and then took two goblets over to the table. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by party thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by amateur thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by oral thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by sex thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by homemade thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by amateur thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by sex thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by amateur thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by interracial thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by sex thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by videos thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by amateur thick, shoulder length auburn hair. sex really got worried when four months passed and sex hadn?t heard anything. pics really got worried when four months passed and pics hadn?t heard anything. amateur really got worried when four months passed and amateur hadn?t heard anything. gay really got worried when four months passed and gay hadn?t heard anything. sex really got worried when four months passed and sex hadn?t heard anything. amateur really got worried when four months passed and amateur hadn?t heard anything. mature really got worried when four months passed and mature hadn?t heard anything. sex really got worried when four months passed and sex hadn?t heard anything. young really got worried when four months passed and young hadn?t heard anything. amateur really got worried when four months passed and amateur hadn?t heard anything. sex really got worried when four months passed and sex hadn?t heard anything. free really got worried when four months passed and free hadn?t heard anything. amateur really got worried when four months passed and amateur hadn?t heard anything. That was when I realized it ? sex tits were real. That was when I realized it ? pics tits were real. That was when I realized it ? amateur tits were real. That was when I realized it ? mom tits were real. That was when I realized it ? sex tits were real. That was when I realized it ? amateur tits were real. That was when I realized it ? couples tits were real. That was when I realized it ? sex tits were real. That was when I realized it ? hot tits were real. That was when I realized it ? amateur tits were real. That was when I realized it ? sex tits were real. That was when I realized it ? amateur tits were real. wife couldn?t take looking at wife name on my arm after that, the memories were too much for wife to handle. sex couldn?t take looking at sex name on my arm after that, the memories were too much for sex to handle. amateur couldn?t take looking at amateur name on my arm after that, the memories were too much for amateur to handle. sex couldn?t take looking at sex name on my arm after that, the memories were too much for sex to handle. movie couldn?t take looking at movie name on my arm after that, the memories were too much for movie to handle. amateur couldn?t take looking at amateur name on my arm after that, the memories were too much for amateur to handle. doggy couldn?t take looking at doggy name on my arm after that, the memories were too much for doggy to handle. sex couldn?t take looking at sex name on my arm after that, the memories were too much for sex to handle. amateur couldn?t take looking at amateur name on my arm after that, the memories were too much for amateur to handle. homemade couldn?t take looking at homemade name on my arm after that, the memories were too much for homemade to handle. sex couldn?t take looking at sex name on my arm after that, the memories were too much for sex to handle. gay couldn?t take looking at gay name on my arm after that, the memories were too much for gay to handle. amateur breasts bounced from being released. sex breasts bounced from being released. amateur breasts bounced from being released. beach breasts bounced from being released. sex breasts bounced from being released. amateur breasts bounced from being released. sex breasts bounced from being released. pictures breasts bounced from being released. amateur breasts bounced from being released. sex breasts bounced from being released. sex breasts bounced from being released. amateur breasts bounced from being released. ?Mandy looked into videos eyes and confessed, ?Oh honey, videos seem to always know what to say. ?Mandy looked into amateur eyes and confessed, ?Oh honey, amateur seem to always know what to say. ?Mandy looked into hardcore eyes and confessed, ?Oh honey, hardcore seem to always know what to say. ?Mandy looked into sex eyes and confessed, ?Oh honey, sex seem to always know what to say. ?Mandy looked into amateur eyes and confessed, ?Oh honey, amateur seem to always know what to say. ?Mandy looked into sex eyes and confessed, ?Oh honey, sex seem to always know what to say. ?Mandy looked into scene eyes and confessed, ?Oh honey, scene seem to always know what to say. ?Mandy looked into amateur eyes and confessed, ?Oh honey, amateur seem to always know what to say. ?Mandy looked into outdoor eyes and confessed, ?Oh honey, outdoor seem to always know what to say. ?Mandy looked into sex eyes and confessed, ?Oh honey, sex seem to always know what to say. ?Mandy looked into amateur eyes and confessed, ?Oh honey, amateur seem to always know what to say. ?Mandy looked into webcam eyes and confessed, ?Oh honey, webcam seem to always know what to say. sex big breasts moved up and down, bouncing slightly. amateur big breasts moved up and down, bouncing slightly. asian big breasts moved up and down, bouncing slightly. sex big breasts moved up and down, bouncing slightly. amateur big breasts moved up and down, bouncing slightly. black big breasts moved up and down, bouncing slightly. sex big breasts moved up and down, bouncing slightly. amateur big breasts moved up and down, bouncing slightly. girlfriend big breasts moved up and down, bouncing slightly. sex big breasts moved up and down, bouncing slightly. amateur big breasts moved up and down, bouncing slightly. interracial big breasts moved up and down, bouncing slightly. His eyes went glassy with lust and sex moaned, ?Ooooh Fuck!?He continued to watch as sex slid sex hand down to sex tit. His eyes went glassy with lust and free moaned, ?Ooooh Fuck!?He continued to watch as free slid free hand down to free tit. His eyes went glassy with lust and amateur moaned, ?Ooooh Fuck!?He continued to watch as amateur slid amateur hand down to amateur tit. His eyes went glassy with lust and sex moaned, ?Ooooh Fuck!?He continued to watch as sex slid sex hand down to sex tit. His eyes went glassy with lust and clips moaned, ?Ooooh Fuck!?He continued to watch as clips slid clips hand down to clips tit. His eyes went glassy with lust and free moaned, ?Ooooh Fuck!?He continued to watch as free slid free hand down to free tit. His eyes went glassy with lust and amateur moaned, ?Ooooh Fuck!?He continued to watch as amateur slid amateur hand down to amateur tit. His eyes went glassy with lust and swingers moaned, ?Ooooh Fuck!?He continued to watch as swingers slid swingers hand down to swingers tit. His eyes went glassy with lust and sex moaned, ?Ooooh Fuck!?He continued to watch as sex slid sex hand down to sex tit. His eyes went glassy with lust and videos moaned, ?Ooooh Fuck!?He continued to watch as videos slid videos hand down to videos tit. His eyes went glassy with lust and teen moaned, ?Ooooh Fuck!?He continued to watch as teen slid teen hand down to teen tit. His eyes went glassy with lust and sex moaned, ?Ooooh Fuck!?He continued to watch as sex slid sex hand down to sex tit. He cupped amateur breasts and massaged them slowly. He cupped interracial breasts and massaged them slowly. He cupped amateur breasts and massaged them slowly. He cupped sex breasts and massaged them slowly. He cupped videos breasts and massaged them slowly. He cupped amateur breasts and massaged them slowly. He cupped sex breasts and massaged them slowly. He cupped films breasts and massaged them slowly. He cupped amateur breasts and massaged them slowly. He cupped sex breasts and massaged them slowly. He cupped video breasts and massaged them slowly. He cupped clips breasts and massaged them slowly. However, right now, my dick is screaming to make love to you!?Mandy pulled amateur lips down hard on hers, feeling the love amateur shared clear to the center of amateur soul. However, right now, my dick is screaming to make love to you!?Mandy pulled dog lips down hard on hers, feeling the love dog shared clear to the center of dog soul. However, right now, my dick is screaming to make love to you!?Mandy pulled sex lips down hard on hers, feeling the love sex shared clear to the center of sex soul. However, right now, my dick is screaming to make love to you!?Mandy pulled amateur lips down hard on hers, feeling the love amateur shared clear to the center of amateur soul. However, right now, my dick is screaming to make love to you!?Mandy pulled sex lips down hard on hers, feeling the love sex shared clear to the center of sex soul. However, right now, my dick is screaming to make love to you!?Mandy pulled blog lips down hard on hers, feeling the love blog shared clear to the center of blog soul. However, right now, my dick is screaming to make love to you!?Mandy pulled nude lips down hard on hers, feeling the love nude shared clear to the center of nude soul. However, right now, my dick is screaming to make love to you!?Mandy pulled amateur lips down hard on hers, feeling the love amateur shared clear to the center of amateur soul. However, right now, my dick is screaming to make love to you!?Mandy pulled sex lips down hard on hers, feeling the love sex shared clear to the center of sex soul. However, right now, my dick is screaming to make love to you!?Mandy pulled amateur lips down hard on hers, feeling the love amateur shared clear to the center of amateur soul. However, right now, my dick is screaming to make love to you!?Mandy pulled animal lips down hard on hers, feeling the love animal shared clear to the center of animal soul. However, right now, my dick is screaming to make love to you!?Mandy pulled sex lips down hard on hers, feeling the love sex shared clear to the center of sex soul. I assured amateur that amateur was not at fault and that amateur understood and had the same feelings. I assured coed that coed was not at fault and that coed understood and had the same feelings. I assured sex that sex was not at fault and that sex understood and had the same feelings. I assured amateur that amateur was not at fault and that amateur understood and had the same feelings. I assured sex that sex was not at fault and that sex understood and had the same feelings. I assured videos that videos was not at fault and that videos understood and had the same feelings. I assured 40 that 40 was not at fault and that 40 understood and had the same feelings. I assured year that year was not at fault and that year understood and had the same feelings. I assured old that old was not at fault and that old understood and had the same feelings. I assured women that women was not at fault and that women understood and had the same feelings. I assured british that british was not at fault and that british understood and had the same feelings. I assured amateur that amateur was not at fault and that amateur understood and had the same feelings. I assured sex that sex was not at fault and that sex understood and had the same feelings. ?It excited mature more when mature talked dirty. ?It excited sex more when sex talked dirty. ?It excited amateur more when amateur talked dirty. ?It excited amateur more when amateur talked dirty. ?It excited couples more when couples talked dirty. ?It excited sex more when sex talked dirty. ?It excited videos more when videos talked dirty. ?It excited amateur more when amateur talked dirty. ?It excited sex more when sex talked dirty. ?It excited video more when video talked dirty. ?It excited free more when free talked dirty. ?It excited asian more when asian talked dirty. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Next Tammy was told to lay on sex back on the couch and spread sex legs. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Next Tammy was told to lay on forced back on the couch and spread forced legs. Next Tammy was told to lay on sex back on the couch and spread sex legs. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Next Tammy was told to lay on sex back on the couch and spread sex legs. Next Tammy was told to lay on stories back on the couch and spread stories legs. Next Tammy was told to lay on sex back on the couch and spread sex legs. Next Tammy was told to lay on party back on the couch and spread party legs. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Mandy licked couples lips, kicked off couples heels and then removed couples bra and panties. Mandy licked having lips, kicked off having heels and then removed having bra and panties. Mandy licked sex lips, kicked off sex heels and then removed sex bra and panties. Mandy licked amateur lips, kicked off amateur heels and then removed amateur bra and panties. Mandy licked sex lips, kicked off sex heels and then removed sex bra and panties. Mandy licked for lips, kicked off for heels and then removed for bra and panties. Mandy licked cash lips, kicked off cash heels and then removed cash bra and panties. Mandy licked amateur lips, kicked off amateur heels and then removed amateur bra and panties. Mandy licked sex lips, kicked off sex heels and then removed sex bra and panties. Mandy licked forum lips, kicked off forum heels and then removed forum bra and panties. Mandy licked amateur lips, kicked off amateur heels and then removed amateur bra and panties. Mandy licked videos lips, kicked off videos heels and then removed videos bra and panties. I looked sex in the eyes and whispered, I'm sorry. I looked free in the eyes and whispered, I'm sorry. I looked amateur in the eyes and whispered, I'm sorry. I looked sex in the eyes and whispered, I'm sorry. I looked galleries in the eyes and whispered, I'm sorry. I looked adult in the eyes and whispered, I'm sorry. I looked amateur in the eyes and whispered, I'm sorry. I looked sex in the eyes and whispered, I'm sorry. I looked videos in the eyes and whispered, I'm sorry. I looked amateur in the eyes and whispered, I'm sorry. I looked home in the eyes and whispered, I'm sorry. I looked sex in the eyes and whispered, I'm sorry. I looked tape in the eyes and whispered, I'm sorry. After this, amateur tongue finds amateur clit, and begins flicking it. After this, indian tongue finds indian clit, and begins flicking it. After this, sex tongue finds sex clit, and begins flicking it. After this, amateur tongue finds amateur clit, and begins flicking it. After this, phone tongue finds phone clit, and begins flicking it. After this, sex tongue finds sex clit, and begins flicking it. After this, amateur tongue finds amateur clit, and begins flicking it. After this, teenager tongue finds teenager clit, and begins flicking it. After this, sex tongue finds sex clit, and begins flicking it. After this, amateur tongue finds amateur clit, and begins flicking it. After this, video tongue finds video clit, and begins flicking it. After this, sex tongue finds sex clit, and begins flicking it. Sweet milk squirted into my mouth as amateur went from nipple to nipple. Sweet milk squirted into my mouth as voyeur went from nipple to nipple. Sweet milk squirted into my mouth as sex went from nipple to nipple. Sweet milk squirted into my mouth as college went from nipple to nipple. Sweet milk squirted into my mouth as amateur went from nipple to nipple. Sweet milk squirted into my mouth as sex went from nipple to nipple. Sweet milk squirted into my mouth as couple went from nipple to nipple. Sweet milk squirted into my mouth as sex went from nipple to nipple. Sweet milk squirted into my mouth as amateur went from nipple to nipple. Sweet milk squirted into my mouth as amateur went from nipple to nipple. Sweet milk squirted into my mouth as hidden went from nipple to nipple. Sweet milk squirted into my mouth as cam went from nipple to nipple. He lowers sex shorts, wraps sex fingers around sex swelling cock and begins stroking sex slowly, feeling sex pulsating and harden in sex hands. He lowers amateur shorts, wraps amateur fingers around amateur swelling cock and begins stroking amateur slowly, feeling amateur pulsating and harden in amateur hands. He lowers hidden shorts, wraps hidden fingers around hidden swelling cock and begins stroking hidden slowly, feeling hidden pulsating and harden in hidden hands. He lowers camera shorts, wraps camera fingers around camera swelling cock and begins stroking camera slowly, feeling camera pulsating and harden in camera hands. He lowers sex shorts, wraps sex fingers around sex swelling cock and begins stroking sex slowly, feeling sex pulsating and harden in sex hands. He lowers amateur shorts, wraps amateur fingers around amateur swelling cock and begins stroking amateur slowly, feeling amateur pulsating and harden in amateur hands. He lowers home shorts, wraps home fingers around home swelling cock and begins stroking home slowly, feeling home pulsating and harden in home hands. He lowers sex shorts, wraps sex fingers around sex swelling cock and begins stroking sex slowly, feeling sex pulsating and harden in sex hands. He lowers movies shorts, wraps movies fingers around movies swelling cock and begins stroking movies slowly, feeling movies pulsating and harden in movies hands. He lowers amateur shorts, wraps amateur fingers around amateur swelling cock and begins stroking amateur slowly, feeling amateur pulsating and harden in amateur hands. He lowers sex shorts, wraps sex fingers around sex swelling cock and begins stroking sex slowly, feeling sex pulsating and harden in sex hands. He lowers forums shorts, wraps forums fingers around forums swelling cock and begins stroking forums slowly, feeling forums pulsating and harden in forums hands. I told amateur to leave amateur alone and leave with amateur stuff, he came over to amateur and stuck the gun right in my face and told amateur he would kill us both if amateur didn't do as he asked. I told sex to leave sex alone and leave with sex stuff, he came over to sex and stuck the gun right in my face and told sex he would kill us both if sex didn't do as he asked. I told home to leave home alone and leave with home stuff, he came over to home and stuck the gun right in my face and told home he would kill us both if home didn't do as he asked. I told video to leave video alone and leave with video stuff, he came over to video and stuck the gun right in my face and told video he would kill us both if video didn't do as he asked. I told amateur to leave amateur alone and leave with amateur stuff, he came over to amateur and stuck the gun right in my face and told amateur he would kill us both if amateur didn't do as he asked. I told teen to leave teen alone and leave with teen stuff, he came over to teen and stuck the gun right in my face and told teen he would kill us both if teen didn't do as he asked. I told sex to leave sex alone and leave with sex stuff, he came over to sex and stuck the gun right in my face and told sex he would kill us both if sex didn't do as he asked. I told video to leave video alone and leave with video stuff, he came over to video and stuck the gun right in my face and told video he would kill us both if video didn't do as he asked. From akineko at gmail.com Tue Sep 16 13:46:47 2008 From: akineko at gmail.com (akineko) Date: Tue, 16 Sep 2008 10:46:47 -0700 (PDT) Subject: A unique instance of Python GUI program References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> <mailman.1100.1221555458.3487.python-list@python.org> Message-ID: <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> On Sep 16, 1:58?am, Tim Golden <m... at timgolden.me.uk> wrote: > I swear this question's been asked twice this month already. Thank you very much for many pointers. I'm awfully sorry for posting something that is already answered in the past. I tried to find answers to my problem using "unique instance" as a keyword. I guess I should have used "single instance" or "one instance", instead. I will try to be more careful before posting. Thank you. Aki Niimura From mario at ruggier.org Wed Sep 3 03:28:26 2008 From: mario at ruggier.org (mario) Date: Wed, 3 Sep 2008 00:28:26 -0700 (PDT) Subject: eval() == evil? --- How to use it safely? References: <d836e712-0dbd-4caf-a32b-99c3c3cc1c16@z66g2000hsc.googlegroups.com> Message-ID: <98d905fd-539b-4101-8c71-4447ae9232d6@34g2000hsh.googlegroups.com> On Aug 28, 11:51 pm, Fett <FettMan... at gmail.com> wrote: > I am creating a program that requires some data that must be kept up > to date. What I plan is to put this data up on a web-site then have > the program periodically pull the data off the web-site. > > My problem is that when I pull the data (currently stored as a > dictionary on the site) off the site, it is a string, I can use eval() > to make that string into a dictionary, and everything is great. > However, this means that I am using eval() on some string on a web- > site, which seems pretty un-safe. > > I read that by using eval(code,{"__builtins__":None},{}) I can prevent > them from using pretty much anything, and my nested dictionary of > strings is still allowable. What I want to know is: > > What are the dangers of eval? > - I originally was using exec() but switched to eval() because I > didn't want some hacker to be able to delete/steal files off my > clients computers. I assume this is not an issue with eval(), since > eval wont execute commands. > - What exactly can someone do by modifying my code string in a command > like: thing = eval(code{"__builtins__":None},{}), anything other than > assign their own values to the object thing? If you like to look at a specific attempt for making eval() safe(r) take a look at how the **eval-based** Evoque Templating engine does it, for which a short overview is here: http://evoque.gizmojo.org/usage/restricted/ While it does not provide protection against DOS type attacks, it should be safe against code that tries to pirate tangible resources off your system, such as files and disk. Actually, any problems anyone may find are greatly appreciated... From gagsl-py2 at yahoo.com.ar Sun Sep 21 13:55:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Sep 2008 14:55:47 -0300 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> <gb3bvk$9a1$1@ger.gmane.org> <27CC3060AF71DA40A5DC85F7D5B70F38051C09F2@AWMAIL04.belcan.com> Message-ID: <op.uhucuzo8x6zn5v@a98gizw.noga> En Sat, 20 Sep 2008 16:07:12 -0300, Blubaugh, David A. <dblubaugh at belcan.com> escribi?: > Let me state that do have extensive experience with developing binary > files. Please note that I have followed all of the instructions to the > letter as far as developing a DLL to be imported. However, it is not > working correctly. I believe it might be my system environment > variables?? It might be the sunspots (or the lack of them) as well. You could start telling us what's your platform, which instructions have you followed, which compiler have you used... -- Gabriel Genellina From castironpi at gmail.com Sat Sep 20 17:07:26 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 14:07:26 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> Message-ID: <2c0a8279-e888-4ae5-90a2-f2f1bb137607@x41g2000hsb.googlegroups.com> On Sep 20, 3:22?pm, Kay Schluehr <kay.schlu... at gmx.net> wrote: > On 20 Sep., 18:33, Bruno Desthuilliers > > <bdesth.quelquech... at free.quelquepart.fr> wrote: > > The following definitions are AFAIK the only commonly accepted > > definitions about OO: > > > 1/ an object is defined by identity, state and behaviour > > 2/ objects interacts by sending messages each other > > 3/ an OO program is made of interacting objects > > > I let you find out whether Python meets these 3 definitions - and if > > Java does (hint : in Python, everything you can bind to a name is an > > object - this is not true in Java or C++). > > This is correct but it detracts from a more general problem of > language "paradigms". > > Assume you type > > >>> 2+2 > > 4 > > Now you are free to interpret this as a simple, primitive arithmetic > operation but you can also claim that 2 sends an __add__ message to 2. > Hereby the state of the 2 objects are not altered but a new 4 object > is created. OO babble is more impressive isn't it? > > Actually it is simply wrong in the mentioned case and here is the > proof: > > def foo(): > ? ? return 2+2 > > import dis > dis.dis(foo) > > ? 2 ? ? ? ? ? 0 LOAD_CONST ? ? ? ? ? ? ? 2 (4) > ? ? ? ? ? ? ? 3 RETURN_VALUE > > OO is a heuristic method used to understand the semantics of a > programming language. It can also inspire language design but as > you've rightly said: jugde yourself and see how far you get with it. > > Applying OO on interpreter level is by no means a sign of a high > quality implementation whereas structuring programs in the large will > likely benefit from class based organization and encapsulation. Of > course one can also reverse the value hierarchy and find perverse joy > in having a pure OO language but apply monkey patching everywhere. I > suppose you know which language I'm talking about... It sounds like you think that you -can- write OO programs in Python, but you don't have to. I agree. From blabla at dungeon.de Thu Sep 11 11:48:52 2008 From: blabla at dungeon.de (hofer) Date: Thu, 11 Sep 2008 08:48:52 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Message-ID: <b4470822-e893-4b5f-893e-28c39e71dddb@m73g2000hsh.googlegroups.com> Thanks a lot for all your answers. There's quite some things I learnt :-) [v1,v2,v3] = ... can be typed as v1,v2,v3 = . . . I also wasn't used to map(myhash.get, ['one', 'two', 'two']) itemgetter('one', 'one', 'two')(x) I also didn't know print "%(one)s\n%(two)s\n%(two)s" % mydict The reason I'd like to have a short statement for above is, that this is for me basically just some code, to name and use certain fields of a hash in i given code section. The real example would be more like: name,age,country = itemgetter('name age country'.split())(x) # or any of my above versions # a lot of code using name / age / country thanks a gain and bye H On Sep 10, 5:28?pm, hofer <bla... at dungeon.de> wrote: > Let's take following perl code snippet: > > %myhash=( one ?=> 1 ? ?, two ? => 2 ? ?, three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' ? : 1 ? ?, 'two' ? : 2 ? ?, 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as ?split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] > > print "%s\n%s\n%s" %(v1,v2,v3) From hancock.robert at gmail.com Tue Sep 23 15:11:03 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Tue, 23 Sep 2008 12:11:03 -0700 (PDT) Subject: Twisted: Get Protected HTTPS Page via Proxy with Authentication References: <f60bd2dd-b97a-4ba0-b89c-443019208111@m44g2000hsc.googlegroups.com> Message-ID: <e197ef5f-9619-4a4b-b1ea-8ef2a97e53a1@k13g2000hse.googlegroups.com> This works: # Proxy credentials proxyAuth = base64.encodestring('%s:%s' % (proxy_username, proxy_password)) proxy_authHeader = "Basic " + proxyAuth.strip() # Web site credentials basicAuth = base64.encodestring('%s:%s' % (username, password)) authHeader = "Basic " + basicAuth.strip() return client.getPage(url, headers={"Authorization": authHeader, 'Proxy-Authenticate': proxy_authHeader}) From circularfunc at yahoo.se Tue Sep 2 14:02:03 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 2 Sep 2008 11:02:03 -0700 (PDT) Subject: Large amount of files to parse/organize, tips on algorithm? References: <a8ca9f87-4bf8-4a74-b4ee-902ff3d328ab@x35g2000hsb.googlegroups.com> <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> Message-ID: <613f7386-7d6a-4dd4-a06e-f1cc0ccb641c@k7g2000hsd.googlegroups.com> On Sep 2, 7:06?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Tue, 02 Sep 2008 09:48:32 -0700, cnb wrote: > > I have a bunch of files consisting of moviereviews. > > > For each file I construct a list of reviews and then for each new file I > > merge the reviews so that in the end have a list of reviewers and for > > each reviewer all their reviews. > > > What is the fastest way to do this? > > Use the timeit module to find out. > > > 1. Create one file with reviews, open next file an for each review see > > if the reviewer exists, then add the review else create new reviewer. > > > 2. create all the separate files with reviews then mergesort them? > > The answer will depend on whether you have three reviews or three > million, whether each review is twenty words or twenty thousand words, > and whether you have to do the merging once only or over and over again. > > -- > Steven I merge once. each review has 3 fields, date rating customerid. in total ill be parsing between 10K and 100K, eventually 450K reviews. From joe.g at optusnet.com.au Thu Sep 18 11:47:45 2008 From: joe.g at optusnet.com.au (Joe G (Home)) Date: Fri, 19 Sep 2008 01:47:45 +1000 Subject: Installing pySerial Message-ID: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Hi All, Background =================== I have installed Python for windows today from the python web site .I also installed pySerial using the Windows installer from the sourceforge web site..... Both installs use the default directories. Phyton version : Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 pySerial 2.4 July 6th Problem : Errors Screen output ============================ >>> import serial Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import serial File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in <module> from serialwin32 import * File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in <module> import win32file # The base COM port and file IO functions. ImportError: No module named win32file >>> So it looks like Python can not see some of the modules Here's the active paths >>> print sys.path ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages'] >>> It seems that C:\Python25\Lib\site-packages\serial needs to be added to the PYTHONPATH QUESTION ============= Q1. How do I add C:\Python25\Lib\site-packages\serial to the PYTHONPATH ? Q2. How do I check that I have installed pySerial corretly (using the Windows installer) Thanks in advance Joe From ldo at geek-central.gen.new_zealand Mon Sep 29 05:15:09 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:15:09 +1300 Subject: how to search multiple textfiles ? (Python is slow ?) References: <mailman.1536.1222436146.3487.python-list@python.org> <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> <mailman.1566.1222464403.3487.python-list@python.org> Message-ID: <gbq6at$iiq$3@lust.ihug.co.nz> In message <mailman.1566.1222464403.3487.python-list at python.org>, Stef Mientki wrote: > - Pyscripter 110 sec ( PyScripter is the default IDE I use now) > - Delphi 20 .. 35 sec > - Findstr 4 sec What order did you try try them in? Did you try each one more than once, in different orders? Just to rule out filesystem caching effects. > I'm really amazed by the speed of Python !! > It can only be beaten by findstr, which is only available on windows. Did you try find -exec grep -F? From kyosohma at gmail.com Wed Sep 24 09:29:08 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Sep 2008 06:29:08 -0700 (PDT) Subject: How to copy a GUI2exe project - to serve as basis for new project ? References: <mailman.12523.1222237400.3486.python-list@python.org> <mailman.1445.1222242860.3487.python-list@python.org> Message-ID: <2f15e7e1-a6d0-4800-ba29-47c035710326@k7g2000hsd.googlegroups.com> On Sep 24, 2:54?am, "Barak, Ron" <Ron.Ba... at lsi.com> wrote: > Hi, > > In GUI2exe, I'd like to create a project that is different from an existing project only in a few details (e.g., the location of the 'dist' directory). > Is there a way to copy a current project - so it would serve as a basis for a new project ? > > Bye, > Ron. Not that I'm aware of. You should post this to the wxPython users group and see if the author can add this feature. I know he just added a "Save Project As" option, but I can't get it to work right. Mike From clp at rebertia.com Wed Sep 17 02:19:07 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 16 Sep 2008 23:19:07 -0700 Subject: how many objects are loaded for hello world? In-Reply-To: <ee471449-3fa1-4f4d-86db-d2ec8843114f@b30g2000prf.googlegroups.com> References: <ee471449-3fa1-4f4d-86db-d2ec8843114f@b30g2000prf.googlegroups.com> Message-ID: <47c890dc0809162319u55033bffg6927e03c52e7dede@mail.gmail.com> On Tue, Sep 16, 2008 at 11:13 PM, belred <belred at gmail.com> wrote: > i just read this blog about how many objects (types) are loaded for a > hello world program in C#. > > http://blogs.msdn.com/abhinaba/archive/2008/09/15/how-many-types-are-loaded-for-hello-world.aspx > > how can you find out how many are loaded for a python program: print > 'hello' Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> len(dir(__builtins__)) 134 Regards, Chris > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From mail at timgolden.me.uk Tue Sep 30 15:22:40 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 30 Sep 2008 20:22:40 +0100 Subject: [Tutor] Replacing cmd.exe with custom .py application In-Reply-To: <eb90f15e0809301209x11a260d5pdcd6e59c08605502@mail.gmail.com> References: <ea09b3700809300732vafc8d52oca6a73d95b63eb33@mail.gmail.com> <eb90f15e0809301113p61bafe22y179d546b3719f51d@mail.gmail.com> <eb90f15e0809301209x11a260d5pdcd6e59c08605502@mail.gmail.com> Message-ID: <48E27C80.6030905@timgolden.me.uk> Ezra Taylor wrote: > Is there something similar to /dev/null on Windows? NUL: TJG From ivan.illarionov at gmail.com Fri Sep 5 20:09:44 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Fri, 5 Sep 2008 17:09:44 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> <acdc94a1-9f8c-49f3-b063-dd536e480d07@v39g2000pro.googlegroups.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> <48c03b91$0$14747$426a74cc@news.free.fr> <fc6a6c32-a023-4d6e-9089-bbcfc42de8d5@a8g2000prf.googlegroups.com> <6id16uFq5171U1@mid.uni-berlin.de> Message-ID: <688970a9-5791-4d73-8896-5e055dfd519f@m73g2000hsh.googlegroups.com> On 5 ????, 19:23, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > Ivan Illarionov schrieb: > > > > > On 4 ????, 21:49, Bruno Desthuilliers > > <bdesth.quelquech... at free.quelquepart.fr> wrote: > >> Ivan Illarionov a ?crit : > > >>> On 4 ????, 22:59, Carl Banks <pavlovevide... at gmail.com> wrote: > >>>> You can write code to guard against this if you want: > >>>> class A: > >>>> legal = set(["x"]) > >>>> def __setattr__(self,attr,val): > >>>> if attr not in self.legal: > >>>> raise AttributeError("A object has no attribute '%s'" % > >>>> attr) > >>>> self.__dict__[attr] = val > >>>> def __init__(self,x): > >>>> self.y = x > >>>> I suspect most people who go into Python doing something like this > >>>> soon abandon it when they see how rarely it actually catches anything. > >>> '__slots__' is better: > >> For which definition of "better" ? __slots__ are a mean to optimize > >> memory usage, not to restrict dynamism. Being able to dynamically add > >> arbitrary attributes is actually a feature, not a bug, and uselessly > >> restricting users from doing so is not pythonic. IOW : don't do that. > > > Carl's example is restricting dynamism in the same way as __slots__. > > I've just suggested a better implementation. It is not me who > > suggested dynamism restriction as a way to guard against errors. > > This is not correct. While Carl's Example looks similar, you actually > *can* create new attributes using > > obj.__dict__['name'] = value > > __slots__ OTOH prevents that because it does create instances *without* > an instance-dict. > > This being said, I think we all agree that it's nothing to be desired. > > Diez +1 for unit tests as a way to guard against errors. Bot sometimes __slots__ is exactly what I want (for other reasons) and I like to avoid __getattr__ hacks in any situation. Ivan From afriere at yahoo.co.uk Wed Sep 24 22:49:48 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 24 Sep 2008 19:49:48 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <f5a4027b-4b9b-4d09-b76b-11d50b8070eb@p31g2000prf.googlegroups.com> <zllxzcpt.fsf@wgmail2.gatwick.eur.slb.com> <beeea088-c336-465e-a24c-160f5c56a2c4@p10g2000prf.googlegroups.com> <c4817afc-d588-4807-8e45-25d22988652c@59g2000hsb.googlegroups.com> Message-ID: <c5d2674a-e580-4429-be8e-4b67cdbed5fc@a2g2000prm.googlegroups.com> On Sep 25, 11:57 am, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 24, 8:40 pm, Asun Friere <afri... at yahoo.co.uk> wrote: > > ... I think > > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding > > all variables for placeholders in the tuple, is better. It's certainly > > more readible. > > It's a different answer if you have 'things is/are'. '%d thing%s %s'% > ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ). Or excluding > prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's > are' if i!= 1 else ' is' ). Forgive me for being dull, my caffeine levels have not yet optimal, but I don't follow. Both the solutions you propose do put all the placeholder variables in the tuple. Or are you saying it no longer remains readible? BTW you repeated my mistake with the first scraplet of code. From aonlazio at gmail.com Mon Sep 8 17:35:19 2008 From: aonlazio at gmail.com (AON LAZIO) Date: Mon, 8 Sep 2008 17:35:19 -0400 Subject: class(object) and (type)?? Message-ID: <f9e39bbc0809081435kd5c3b32x36f4f615fd00f3a0@mail.gmail.com> Hi again pythoners, I notice in the class of a code having (object) and (type) attached to the name of the class. I know that in other cases, that means the class inherits methods and properties from other but In this case, what does it mean? For example, class PY(object): def __init__(self): ... class PO(type): def __init__(self): ... What do "object" and "type" mean? Thanks in advance Aonlazio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/faaf3b74/attachment.html> From burns.matthew at verizon.net Wed Sep 3 13:51:45 2008 From: burns.matthew at verizon.net (Matthew Burns) Date: Wed, 03 Sep 2008 10:51:45 -0700 Subject: Help on try-except In-Reply-To: <mailman.3232.1220399834.3486.python-list@python.org> References: <mailman.3232.1220399834.3486.python-list@python.org> Message-ID: <000001c90ded$bc5224c0$34f66e40$@matthew@verizon.net> The reason it takes so long is you are not using xrange The range function iterates through the entire data set EVERY time, regardless of whether it needs to This increases processer use EXPONENTIALLY as that number gets larger. I am not quite sure how xrange works, but it keeps only one number in memory at any time In fact, I never use range any more, I always use xrange. ALL YOUR BASE ARE BELONG TO US http://allyourbase.planettribes.gamespy.com/video1_view.shtml -----Original Message----- From: python-list-bounces+burns.matthew=verizon.net at python.org [mailto:python-list-bounces+burns.matthew=verizon.net at python.org] On Behalf Of python-list-request at python.org Sent: Tuesday, September 02, 2008 4:57 PM To: python-list at python.org Subject: Python-list Digest, Vol 60, Issue 30 Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." From paul at boddie.org.uk Sat Sep 6 19:14:54 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 6 Sep 2008 16:14:54 -0700 (PDT) Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: <e8c6e812-5479-4059-b2fe-3a151aec8638@f36g2000hsa.googlegroups.com> On 7 Sep, 00:06, cnb <circularf... at yahoo.se> wrote: > If I buy a multicore computer and I have really intensive program. How > would that be distributed across the cores? It typically depends on how the work done by the program is performed. > Will algorithms always have to be programmed and told specifically to > run on several cores so if not told it will only utilize one core? Some algorithms lend themselves to parallelisation; others do not. Sometimes tools and runtimes can help by executing some instructions in parallel. > So is the free lunch really over or is this just an overhyped > phenomena? The free lunch ended a few minutes ago. ;-) > Is threading with Python hard? Can you start several processes with > Python or just threads? You can start both processes and threads with Python, although the effect of starting many threads - the actual concurrency - will depend on which implementation of Python you're using and where the bulk of the work is performed. If you're spending a lot of CPU time in processing data, and if that processing is taking place in Python code, then for the most effective threading you should consider an implementation like Jython or IronPython which supports free-threading. If most of the work happens in extension code (where you'd probably have little choice about using CPython, anyway), then it might be the case that the extension releases the global interpreter lock in CPython and you might then be able to benefit from having many threads doing work simultaneously, although I imagine that the extension would itself need to be thread- safe, too. If you're spending a lot of time moving data around, performing communication, and so on, then multiple threads may still be effective in CPython, since some of them might be getting a system call to read or write data, thus freeing the CPU for the others. These kinds of situations lend themselves to other approaches such as asynchronous processing of data, however. It doesn't sound like this is like your program, if by "intensive" you mean high levels of CPU activity. As you note, the alternative to threads is processes, and many people advocate multi-process, "shared nothing" solutions. Here's a list which covers multicore and SMP-related solutions as well as high-end clustering solutions: http://wiki.python.org/moin/ParallelProcessing Although the processing module is part of Python 2.6/3.0 as the multiprocessing module, you might want to at least look at the pp, pprocess and papyros solutions. My aim with pprocess was to target multicore UNIX-like systems with an unintrusive API; pp and papyros, on the other hand, seek to cover larger scale systems as well, and I think that the way papyros has been done has some merit, mostly because if you wanted to combine convenience with distributed processing, you'd want to choose distributed object technologies as the foundation (CORBA would have been good for this, too, at least for multi-language support, but its APIs can also seem quite intimidating). Paul From alan.isaac at gmail.com Sat Sep 6 19:30:03 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sat, 06 Sep 2008 23:30:03 GMT Subject: Numeric literal syntax In-Reply-To: <87ej43pcy0.fsf@benfinney.id.au> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: <%nEwk.681$sq3.240@trnddc07> > bearophileHUGS at lycos.com writes: > >> For Python 2.7/3.1 I'd now like to write a PEP regarding the >> underscores into the number literals, like: 0b_0101_1111, 268_435_456 >> etc. > > +1 on such a capability. > > -1 on underscore as the separator. On 9/1/2008 9:13 PM Ben Finney apparently wrote: > When you proposed this last year, the counter-proposal was made > <URL:http://groups.google.com/group/comp.lang.python/msg/18123d100bba63b8?dmode=source> > to instead use white space for the separator, exactly as one can now > do with string literals. Yuck. Repeating a mistake means two mistakes. But I would hate less the use of nobreak spaces, since any decent editor can reveal them. Alan Isaac From pfreixes at gmail.com Mon Sep 15 05:58:48 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Mon, 15 Sep 2008 11:58:48 +0200 Subject: PyArg_ParseTuple for parsing list and dictionary arguments Message-ID: <207312b70809150258n57240c25me70ad03b6339b579@mail.gmail.com> Hi to all, What's the best way for parse one list or dict argument with PyArg_ParseTuple Function ? If I have this python code : import example example.test("hellow", ["a", "b"], { "a" : 1 }) The c extension for implementation test function must be like this : static PyObject * test( PyObject *self, PyObject *args) { PyObject * dict, * list; char * string; PyArg_ParseTuple(args, "sOO", string, dict, list); ...... } -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/97aad3e8/attachment.html> From wuwei23 at gmail.com Thu Sep 25 00:11:18 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 24 Sep 2008 21:11:18 -0700 (PDT) Subject: multiple processes with private working dirs References: <gbdttg$fuq$1@foggy.unx.sas.com> Message-ID: <473d008f-f3c4-4894-9251-b7fc9cf4c8e4@p10g2000prf.googlegroups.com> On Sep 25, 3:37?am, "Tim Arnold" <tim.arn... at sas.com> wrote: > Am I missing something? Do you mean something other than the replies you got the last time you asked the exact same question? http://groups.google.com/group/comp.lang.python/browse_frm/thread/42c13cbb84f88f2b From exarkun at divmod.com Wed Sep 24 13:29:15 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 24 Sep 2008 13:29:15 -0400 Subject: Twisted vs. CherryPy vs. ??? for light-weight web servers In-Reply-To: <170543c70809231922m23531eb9i1f7fdead10bb1e0e@mail.gmail.com> Message-ID: <20080924172915.29191.775453525.divmod.quotient.30199@ohm> On Tue, 23 Sep 2008 21:22:08 -0500, Michael Mabin <d3vvnull at gmail.com> wrote: >Is there any consensus on what the best lightweight web-server is? Or >rather would Twisted be a better choice to choose as a framework that allows >me to serve html or xml data for light webservices. Or is CherryPy just as >good? > You haven't described the problem you want to solve in very much detail. I can't tell, for example, why I shouldn't recommend that you use Apache instead of CherryPy or Twisted or anything else. Apache has a huge user community, lots of documentation, and lots of developers fixing its bugs and making it work well. What are you trying to do that would make Apache a bad choice? Jean-Paul From m_palmer45 at yahoo.ca Wed Sep 3 12:34:32 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 3 Sep 2008 09:34:32 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? Message-ID: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> As anyone knows, the state of Python GUI programming is a little fractured at this time, with many toolkits, wrappers and meta-wrappers dead and alive, with or without documentation. I've come across two projects that have the appeal of striving for simple, pythonic APIs: PyGUI and wax. The latter is a wrapper around wxPython. It is lacking documentation but actually quite usable and concise. The other, PyGUI, has an even nicer API and more docs but has relatively few widgets implemented at this time. It also strives for compatibility with several toolkits (two at this time), which I think is the right idea. So far, development of PyGUI seems to be a one-man effort, and it may be slowed down by the attempt to develop the API and the implementations concurrently. Could it be useful to uncouple the two, such that the API would be specified ahead of the implementation? This might make it easier for people to contribute implementation code and maybe port the API to additional toolkits. It seems that this approach has been quite successful in case of the Python database API. That API defines levels of compliance, which might be a way of accommodating different GUI toolkits as well. I may be underestimating the difficulties of my proposed approach - I don't have much practical experience with GUI programming myself. Best, Michael From victor.prosolin at gmail.com Fri Sep 26 10:22:27 2008 From: victor.prosolin at gmail.com (Fly Away) Date: Fri, 26 Sep 2008 07:22:27 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <mailman.1520.1222400746.3487.python-list@python.org> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> Message-ID: <09cae8bd-f8ac-4c4a-a920-0e6e3f6a3a64@w1g2000prk.googlegroups.com> > Matlab's strongest side is data visualization though. Although we have > matplotlib, mayavi and possibility of interfacing with gnuplot, it's > not anywhere near the capabilities of Matlab. What particular Matlab visualization features are you referring to? I can't think of anything that would justify using the "not anywhere near" term. Cheers, Victor. From gherlylukita at gmail.com Wed Sep 24 15:51:01 2008 From: gherlylukita at gmail.com (gherlylu) Date: Wed, 24 Sep 2008 12:51:01 -0700 (PDT) Subject: Buy Vicodin...convenient, discreet online pharmacy. oylr3 Message-ID: <5c8c4c7b-0a00-4dff-8c4a-7402dea81609@p25g2000hsf.googlegroups.com> Start saving, best online pharmacy here http://fjmgilbh.zarubanlo.net/?acdekbhxwvrsyfjmzchcmgil From gminick at bzt.bzt Thu Sep 4 06:16:41 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 4 Sep 2008 10:16:41 +0000 (UTC) Subject: Issue warning if no "return" in function? References: <g9obtp$l83$1@gwdu112.gwdg.de> Message-ID: <g9oci8$576$1@inews.gazeta.pl> On Thu, 04 Sep 2008 12:05:45 +0200, Poster28 wrote: > What would you suggest to check python programs for non-syntax error. > One example I could think of that one might forget to "return" a value from > a function. > > How could I check for these and maybe other mistakes? Check pychecker or figleaf: http://pychecker.sourceforge.net http://darcs.idyll.org/~t/projects/figleaf/doc/ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From stef.mientki at gmail.com Thu Sep 25 15:38:56 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 21:38:56 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <Xns9B24589F2DBEOKB@199.45.49.11> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> <Xns9B24589F2DBEOKB@199.45.49.11> Message-ID: <48DBE8D0.4040708@gmail.com> I found a partial workaround that is good enough for me: def Get_Windows_Filename ( FileName ) : if os.name == 'nt' : File = os.path.splitext ( FileName .lower ())[0] return glob.glob ( File + '.p?' ) return FileName This will translate the filename into the correct case, but not the path. I also looked at os.path.walk, but that's too slow for me, because getting the path correct means I have to start at the root. cheers, Stef From marco.bizzarri at gmail.com Fri Sep 5 09:04:22 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 15:04:22 +0200 Subject: Core dumped while interacting with OpenOffice.org via pyuno Message-ID: <3f0d61c40809050604y42bc494bqa6c91cb1cc3cd913@mail.gmail.com> Hi all. I'm experiencing a core dump while working in the following environment - debain etch - python2.3 - openoffice.org 2.4 - Zope 2.8.8 I was able to get a core dump, and the backtrace shows the following: Core was generated by `python2.3 tests/testActs.py'. Program terminated with signal 11, Segmentation fault. #0 0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 (gdb) bt #0 0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 #1 0xb6b547d3 in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 #2 0xb6b531d2 in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 #3 0xb6b53748 in uno_threadpool_enter () from /usr/lib/openoffice/program/libuno_cppu.so.3 #4 0xb5c80c8c in ?? () from /usr/lib/openoffice/program/liburp_uno.so #5 0xb5c7d1e8 in ?? () from /usr/lib/openoffice/program/liburp_uno.so #6 0xb5c8710e in ?? () from /usr/lib/openoffice/program/liburp_uno.so #7 0xb5c8727c in ?? () from /usr/lib/openoffice/program/liburp_uno.so #8 0xb5c76a62 in ?? () from /usr/lib/openoffice/program/liburp_uno.so #9 0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3 #10 0x08797840 in ?? () #11 0x0989b6e0 in ?? () #12 0x00000000 in ?? () Now, I can understand that the information I provided are not enough to give me suggestions on solving this issue; so, I'm asking suggesions on investigating the issue, namely: - should I ask here or is it better if I ask on a openoffice forum? - should I use a debug-enabled python in order to have more meaningful backtraces? - is there something else I should do in order to have more clues ("Read The Fine Manual (tm)" is an acceptable answer) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From rridge at csclub.uwaterloo.ca Wed Sep 10 12:28:55 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 10 Sep 2008 12:28:55 -0400 Subject: universal unicode font for reportlab References: <ga6loq$jpj$1@rumours.uwaterloo.ca> <mailman.785.1221053660.3487.python-list@python.org> <Xns9B159F78E43Dduncanbooth@127.0.0.1> Message-ID: <ga8sk7$7bg$1@rumours.uwaterloo.ca> Duncan Booth <duncan.booth at suttoncourtenay.org.uk> wrote: >I thought that usually when you embed a font in a PDF only the glyphs which >are actually used in the document get embedded. Unfortunately a quick test >with reportlab seems to show that it doesn't do that optimisation: it looks >as though it just embeds the entire font. Yah, PDF files normally only contain an embedded subset of the fonts used. It might possible to use Ghostscript's ps2pdf command (which can take a PDF file as input) to strip out the unused glyphs from the embedded fonts. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From ggpolo at gmail.com Mon Sep 1 20:52:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 1 Sep 2008 21:52:39 -0300 Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp In-Reply-To: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Message-ID: <ac2200130809011752t2bed51br7cc14facbf51854b@mail.gmail.com> On Mon, Sep 1, 2008 at 7:45 PM, akineko <akineko at gmail.com> wrote: > Hi everyone, > > This is a memorandum so that other people can share the info. > > The following methods are declared in the Tkinter Button class. > tkButtonDown(), tkButtonEnter(), tkButtonInvoke(), tkButtonLeave(), > tkButtonUp() > However, they are not working, when you try, you will get: > > _tkinter.TclError: invalid command name "tkButtonLeave" > > The bindings in the Tkinter are mapping them to non-existing tk > methods. > I needed to use the method badly and I couldn't find any clear > solution for this. Are you trying to simulate clicks ? You should be doing it using event_generate, more below. > So, I spent time to solve this. > > tkButtonLeave(), for example, is declared as follows: > > Tkinter.py line 2005 of 3759 > def tkButtonLeave(self, *dummy): > self.tk.call('tkButtonLeave', self._w) > > Now, in the Tk source distribution, I found the following: > unsupported.tcl > # Commands provided by Tk without official support. Use them at your > # own risk. They may change or go away without notice. > > namespace eval ::tk::unsupported { > > # Map from the old global names of Tk private commands to their > # new namespace-encapsulated names. > > variable PrivateCommands > array set PrivateCommands { > tkButtonAutoInvoke ::tk::ButtonAutoInvoke > tkButtonDown ::tk::ButtonDown > tkButtonEnter ::tk::ButtonEnter > tkButtonInvoke ::tk::ButtonInvoke > tkButtonLeave ::tk::ButtonLeave > tkButtonUp ::tk::ButtonUp > ... snip ... You are looking at the wrong place, try looking at library/button.tcl Now, why I said about using event_generate instead of calling those methods yourself.. tk sets several bindings that varies between platforms for all these things you are trying to do, and they end up calling these commands you are trying to call yourself. So, for instance, given that you have a button: btn = Tkinter.Button() to get tk::ButtonEnter called, you should be doing: btn.event_generate("<Enter>") and this will work for other those other events too, Leave (Leave), Button-1 (Down), ButtonRelease-1 (Up), space (Invoke). The remaining one to talk about is this "ButtonAutoInvoke", which I'm unsure if you really need it, but, if you do, you could use btn.invoke() supposing the button has an associated callback which will use "after" to schedule another btn.invoke(). > > This seems suggesting that the Tkinter bindings are binding obsolete > tk methods. > And, the method should be called seems ::tk::ButtonLeave, instead. > > I placed the following into my Tkinter code and it worked. > self.btn.tk.call('::tk::ButtonLeave', self.btn._w) > > // > Summary: > (1) tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, > tkButtonUp are not working. > (2) Bindings are not correct > (2) Workaround is call correct tk methods directly > > I hope future Tkinter will be corrected so that the methods are > available as documented. You should expect them to be totally removed from Tkinter actually. > > Best regards, > Aki- > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:36:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:36:22 GMT Subject: urllib error on urlopen References: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> Message-ID: <00eaf2fa$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 08:46:56 -0700, Mike Driscoll wrote: > Hi, > > I have been using the following code for over a year in one of my > programs: > > f = urllib2.urlopen('https://www.companywebsite.com/somestring') > > It worked great until the middle of the afternoon yesterday. Now I get > the following traceback: ... > URLError: <urlopen error (1, 'error:140770FC:SSL > routines:SSL23_GET_SERVER_HELLO:unknown protocol')> Have you recently set a proxy where Python can auto-detect it? I understand that urllib2 doesn't work well with https proxies. If so, you can instruct urllib2 not to use a proxy-handler, but it's more work. What I do is construct an opener without a proxyhandler: # untested... no_proxy_support = urllib2.ProxyHandler({}) opener = urllib2.build_opener(no_proxy_support) f = opener.open('https://www.companywebsite.com/somestring') If that doesn't work, you may need to build a Request object from the URL before passing it to opener.open. -- Steven From jcd at sdf.lonestar.org Tue Sep 16 15:07:57 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 16 Sep 2008 15:07:57 -0400 Subject: append on lists In-Reply-To: <O5SdnZPu6e3hJFLVnZ2dnUVZ_v3inZ2d@posted.visi> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> <87d4j4798g.fsf@mulj.homelinux.net> <O5SdnZPu6e3hJFLVnZ2dnUVZ_v3inZ2d@posted.visi> Message-ID: <1221592077.30028.2.camel@aalcdl07.lib.unc.edu> On Tue, 2008-09-16 at 08:49 -0500, Grant Edwards wrote: > On 2008-09-16, Hrvoje Niksic <hniksic at xemacs.org> wrote: > > Duncan Booth <duncan.booth at invalid.invalid> writes: > > > >> The only relatively common use I can think of where you might want to call > >> a method directly on a literal is to produce a list of strings while being > >> lazy about the typing: > > > > By far the most common is probably 'sep'.join(iterable). > > It's also somewhat common to index into a literal: > > ['one','two','three'][n] > > {1:'one', 2:'two', 7:'seven'}[n] > Indeed. I use this for setting variables based on hostname on a website. Say, for example, you run on port 80 on one host, but on a test host, you share with several other sites, and run on 8084, you can do the following import socket port = { 'www.example.com': 80, 'dev.example.com': 8084, }[socket.gethostname()] It's a handy idiom. Cheers, Cliff From ldo at geek-central.gen.new_zealand Fri Sep 26 03:41:34 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 19:41:34 +1200 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> <mailman.1295.1221905698.3487.python-list@python.org> <ee99e813-97e0-404c-a512-748d0d148f8c@b1g2000hsg.googlegroups.com> Message-ID: <gbi3ne$s8a$1@lust.ihug.co.nz> In message <ee99e813-97e0-404c-a512-748d0d148f8c at b1g2000hsg.googlegroups.com>, Aaron "Castironpi" Brady wrote: > Wikipedia puts it decently: "mainly for OO programming, but with some > procedural elements." "Procedural" is the opposite of "functional", not "object-oriented". From shahmed at sfwmd.gov Thu Sep 11 08:33:01 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 11 Sep 2008 08:33:01 -0400 Subject: removing text string In-Reply-To: <xqWdnQ2Hm7s1vlXVnZ2dnUVZ_sLinZ2d@earthlink.com> References: <loom.20080910T144026-626@post.gmane.org><mailman.814.1221069201.3487.python-list@python.org> <xqWdnQ2Hm7s1vlXVnZ2dnUVZ_sLinZ2d@earthlink.com> Message-ID: <A86D1A0C2B238848B9ABDE1A7E287CE6010E1373@EXCHVS01.ad.sfwmd.gov> Thanks Actually the number I am getting it is from slicing from a long text line. I need to slice 10 characters from that line but no string only numeric numbers. When I am slicing 10 characters those A, c, O is coming at the end. Thanks -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of Dennis Lee Bieber Sent: Wednesday, September 10, 2008 3:45 PM To: python-list at python.org Subject: Re: removing text string On Wed, 10 Sep 2008 11:22:16 -0400, "Ahmed, Shakir" <shahmed at sfwmd.gov> declaimed the following in comp.lang.python: > I need to remove text string from the list of the numbers mentioned > below: > > 080829-7_A > 070529-5_c > 080824-7_O > 070405_6_p > ? Is that last one an error that is supposed to be ...5-6_, not ...5_6_ ? 1) If the required data is fixed width, just slice it out = inp[:8] 2) If the data is variable width but has a fixed delimiter, find the delimiter position and then slice (this is the reason for my question above -- this method) OR just split on the delimiter and take the part you need. out = inp.split("_")[0] 3) If the data is more complex (again if that last line with two _ is supposed to be trimmed after the second, and the first turned into a -) you will need to fully define the parsing rules of the data. -- Wulfraed Dennis Lee Bieber KD6MOG wlfraed at ix.netcom.com wulfraed at bestiaria.com HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: web-asst at bestiaria.com) HTTP://www.bestiaria.com/ -- http://mail.python.org/mailman/listinfo/python-list From george.sakkis at gmail.com Tue Sep 30 11:23:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 30 Sep 2008 08:23:23 -0700 (PDT) Subject: Shed Skin (restricted) Python-to-C++ compiler 0.0.29 References: <mailman.1734.1222769964.3487.python-list@python.org> Message-ID: <6ccb7642-2df8-45ee-b304-74c92d520e0e@d31g2000hsg.googlegroups.com> On Sep 30, 6:19 am, "Mark Dufour" <mark.duf... at gmail.com> wrote: > Hi all, > > I have just released Shed Skin 0.0.29, with the following changes. Not to sound negative, but what's with the 0.0.x version numbers ? Maybe it's just me, but seeing a zero major/minor version give me the impression of experimental/pre-alpha project, which (from my very limited knowledge) doesn't do justice to shedskin's current state. Regardless, congrats for this great effort, hope it gains more prominence in the future! George From carsten.haese at gmail.com Tue Sep 30 13:55:15 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 30 Sep 2008 13:55:15 -0400 Subject: r"<path>" In-Reply-To: <33077c9c-01d9-4423-afd2-7452117bc6b4@j22g2000hsf.googlegroups.com> References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> <CltEk.1298$fD.324@flpi145.ffdc.sbc.com> <33077c9c-01d9-4423-afd2-7452117bc6b4@j22g2000hsf.googlegroups.com> Message-ID: <7KtEk.2082$YU2.1499@nlpi066.nbdc.sbc.com> Kyle Hayes wrote: >> Please describe the actual problem you're trying to solve. In what way >> do slashes need to be "fixed," and why? > > Well, I have decided to build a tool to help us sync files in UNC > paths. I am just building the modules and classes right now so I > haven't developed the frontend yet. I am assuming when the user > provides a path (either by typing it in, or pulling it in from a > config file), the UNC slashes are going to escape stuff in the string, > so I want to double them up. That assumption is incorrect. While backslashes in string literals are escape characters that must be doubled up to convey literal backslashes, no such interpretation is made for backslashes that are read from a GUI text box or from a file. See for yourself: >>> some_string = raw_input("Enter a string: ") Enter a string: blah\blah\blah >>> print some_string blah\blah\blah Carry on and come back when you actually have a problem ;) -- Carsten Haese http://informixdb.sourceforge.net From timr at probo.com Mon Sep 22 23:24:18 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 23 Sep 2008 03:24:18 GMT Subject: curses.setsyx()? References: <f4bfa060-3053-4ca6-90c2-2a057bfedf79@34g2000hsh.googlegroups.com> <tqd6d4po3dmvba3a3v1a8c2b34qgfmc8d9@4ax.com> <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> Message-ID: <naogd45497jn4s8jegu15j4u1oo49cinqc@4ax.com> linkmaster032000 at gmail.com wrote: >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: >> On Sep 19, 1:24?am, Tim Roberts <t... at probo.com> wrote: >> >> > linkmaster032... at gmail.com wrote: >> >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses >> > >cursor. Any alternatives/solutions? >> >> > Did you call doupdate after? ?setsyx just manipulates the data structures. >> > It takes a call to doupdate to force those changes to take effect visually. >> > -- >> > Tim Roberts, t... at probo.com >> > Providenza & Boekelheide, Inc. >> >> I added it and it still doesn't work. This is what I'm doing when I >> want to display the cursor and prepare it for input at 2,3: >> >> curses.echo() >> curses.curs_set(1) >> curses.setsyx(2,3) >> curses.doupdate() > >Any idea what's wrong? No. Are you able to post an entire sample that demonstrates the problem? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From timr at probo.com Mon Sep 1 00:24:29 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 01 Sep 2008 04:24:29 GMT Subject: Python 3.0b2 cannot map '\u12b' References: <d0652dd2-24f6-4045-89a8-ba6deaf25b37@c65g2000hsa.googlegroups.com> Message-ID: <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> josh logan <dear.jay.logan at gmail.com> wrote: > >I am using Python 3.0b2. >I have an XML file that has the unicode character '\u012b' in it, >which, when parsed, causes a UnicodeEncodeError: > >'charmap' codec can't encode character '\u012b' in position 26: >character maps to <undefined> > >This happens even when I assign this character to a reference in the >interpreter: > >Python 3.0b2 (r30b2:65106, Jul 18 2008, 18:44:17) [MSC v.1500 32 bit >(Intel)] on > win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> s = '\u012b' >>>> s >Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "C:\Python30\lib\io.py", line 1428, in write > b = encoder.encode(s) > File "C:\Python30\lib\encodings\cp437.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] >UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in >position >1: character maps to <undefined> > >Is this a known issue, or am I doing something wrong? Both. U+012B is the Latin lower-case i with macron (i with a bar instead of a dot). That character does not exist in the 8-bit character set CP437, which you are trying to use. If you choose an 8-bit character set that includes i-with-macron, then it will work. UTF-8 would be a good choice. It's in ISO-8859-10. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From circularfunc at yahoo.se Mon Sep 15 05:36:24 2008 From: circularfunc at yahoo.se (cnb) Date: Mon, 15 Sep 2008 02:36:24 -0700 (PDT) Subject: Emacs, loading file into interpreter doesn't work Message-ID: <4bad07d8-8ead-4cdb-ad8b-c2e55abab06e@m3g2000hsc.googlegroups.com> Python-mode worked right out out of the box in Emacs and then I added Python to my path so now the interpreter works as well. However when I try to load a file(that is not located in site- packages) it doesn't work. >>> Traceback (most recent call last): ImportError: No module named parsing It is fairly impractical to work with if that doesn't work and cut and pasting doesn't work(not that it is a good alternative in the first place) because of Python being intendation-sensitive. Can I add something to my .emacs-file to solve this? From gherlylukita at gmail.com Wed Sep 24 15:36:10 2008 From: gherlylukita at gmail.com (gherlylu) Date: Wed, 24 Sep 2008 12:36:10 -0700 (PDT) Subject: Quick & Secured Pharmacy Online. rdjr0 Message-ID: <f14b6d02-afae-4c11-a022-33ae145d3838@y21g2000hsf.googlegroups.com> Start saving, best online pharmacy here http://fjmgilbh.zarubanlo.net/?acdekbhxwvrsyfjmzchcmgil From prologic at shortcircuit.net.au Thu Sep 11 03:40:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 17:40:33 +1000 Subject: Use Python to solve equations? In-Reply-To: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> References: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Message-ID: <e1a84d570809110040g51bc003ahac0dd35da34573dd@mail.gmail.com> Hi Kelie, Check out sympy it is capable of doing things like this. cheers James On Thu, Sep 11, 2008 at 5:09 PM, Kelie <kf9150 at gmail.com> wrote: > Hello group, > > Is there any packages in Python that will help me solve functions > similar to this: > > x = a*(1+bx)**2.5-c where a, b, c is known and the task to solve x? > > Thank you, > > Kelie > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From python at rcn.com Tue Sep 2 11:18:54 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 2 Sep 2008 08:18:54 -0700 (PDT) Subject: dict.update References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> Message-ID: <1b79577e-d74b-461f-ac0c-6841d3c22251@t1g2000pra.googlegroups.com> On Sep 2, 8:04?am, Mike P <michael.pearm... at tangozebra.com> wrote: > Hi All, > > I have two dictionaries e.g > dict1 = {123:3,234:5,456:3} > dict2 = {123:4,157:2,234:5,456:3,567:2} > > I want to merge these two dictionaries together so i have a resultant > dictionary of: > > dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]} > > As later on i want to write a csv file that would have the form > > id ? ? ?var1 ?var2 > 123 ? ? 4 ? ? ?3 > 157 ? ? 2 ? ? ?0 > > i looks like the dict.update looks almost there but i can't get it to > work properly, can anyone offer any advise? The update() method is not quite right for your purposes. But a simple generator expression will do the trick: >>> dict((k, [v, dict1.get(k, 0)]) for k, v in dict2.items()) {456: [3, 3], 234: [5, 5], 123: [4, 3], 157: [2, 0], 567: [2, 0]} Raymond From ireborin at delete.this.gmail.com Mon Sep 29 18:04:18 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 00:04:18 +0200 Subject: Python arrays and sting formatting options Message-ID: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Hello everyone, I was wondering if anyone here has a moment of time to help me with 2 things that have been bugging me. 1. Multi dimensional arrays - how do you load them in python For example, if I had: ------- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ------- with "i" being the row number, "j" the column number, and "k" the .. uhmm, well, the "group" number, how would you load this ? If fortran90 you would just do: do 10 k=1,2 do 20 i=1,3 read(*,*)(a(i,j,k),j=1,3) 20 continue 10 continue How would the python equivalent go ? 2. I've read the help on the next one but I just find it difficult understanding it. I have; a=2.000001 b=123456.789 c=1234.0001 How do you print them with the same number of decimals ? (eg. 2.000, 123456.789, 1234.000) and how do you print them with the same number of significant decimals? (eg. 2.000001, 123456.7, 1234.000 - always 8 decimals) ? Is something like this possible (built-in) in python ? Really grateful for all the help and time you can spare. -- Ivan From fredrik at pythonware.com Sat Sep 13 04:44:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 10:44:30 +0200 Subject: XML RPC Problem.... In-Reply-To: <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> References: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> <gaagp1$804$1@ger.gmane.org> <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> Message-ID: <gafuhg$sh1$1@ger.gmane.org> Usman Ajmal wrote: > Please explain the arguments of send_request. What exactly are the > connection, handler and request_body? It will be really helpful if you > give an example of how do i call send_request you don't call send_request. you should pass the SecureTransport instance as an argument to the ServerProxy, which will then use it to talk to the server. see the "custom transport" example in the library reference that I pointed you to. http://www.python.org/doc/lib/xmlrpc-client-example.html </F> From simon at mullis.co.uk Thu Sep 18 10:54:44 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Thu, 18 Sep 2008 16:54:44 +0200 Subject: dict generator question Message-ID: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> Hi, Let's say I have an arbitrary list of minor software versions of an imaginary software product: l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] I'd like to create a dict with major_version : count. (So, in this case: dict_of_counts = { "1.1" : "1", "1.2" : "2", "1.3" : "2" } Something like: dict_of_counts = dict([(v[0:3], "count") for v in l]) I can't seem to figure out how to get "count", as I cannot do x += 1 or x++ as x may or may not yet exist, and I haven't found a way to create default values. I'm most probably not thinking pythonically enough... (I know I could do this pretty easily with a couple more lines, but I'd like to understand if there's a way to use a dict generator for this). Thanks in advance SM -- Simon Mullis From bignose+hates-spam at benfinney.id.au Tue Sep 2 19:52:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 03 Sep 2008 09:52:07 +1000 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <pan.2008.09.02.06.10.51@REMOVE.THIS.cybersource.com.au> <6i56cpFor2puU1@mid.individual.net> <6Aevk.331$1a2.14@trnddc04> <6i5gerFospk9U1@mid.individual.net> Message-ID: <87zlmqnm1k.fsf@benfinney.id.au> Peter Pearson <ppearson at nowhere.invalid> writes: > I thought I was a geek, for the past 40 years; but maybe its time > for me to be demoted to the dad on whose bookshelf you'll find that > old book. Once a geek, always a geek. You either stay sharp or get sloppy, but you never stop being a geek :-) -- \ ?The best ad-libs are rehearsed.? ?Graham Kennedy | `\ | _o__) | Ben Finney From tjreedy at udel.edu Tue Sep 23 14:31:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 14:31:49 -0400 Subject: Comparing float and decimal In-Reply-To: <gbaodd$e64$1@ger.gmane.org> References: <20080923072012.57d8d329.darcy@druid.net> <gbaodd$e64$1@ger.gmane.org> Message-ID: <gbbcmb$qal$1@ger.gmane.org> Gerhard H?ring wrote: > D'Arcy J.M. Cain wrote: >> I'm not sure I follow this logic. Can someone explain why float and >> integer can be compared with each other and decimal can be compared to >> integer but decimal can't be compared to float? >> >>>>> from decimal import Decimal >>>>> i = 10 >>>>> f = 10.0 >>>>> d = Decimal("10.00") >>>>> i == f >> True >>>>> i == d >> True >>>>> f == d >> False > > I can give you the technical answer after reading the sources of the > decimal module: you can only compare to Decimal what can be converted to > Decimal. And that is int, long and another Decimal. The new fractions module acts differently, which is to say, as most would want. >>> from fractions import Fraction as F >>> F(1) == 1.0 True >>> F(1.0) Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> F(1.0) File "C:\Program Files\Python30\lib\fractions.py", line 97, in __new__ numerator = operator.index(numerator) TypeError: 'float' object cannot be interpreted as an integer >>> F(1,2) == .5 True >>> .5 == F(1,2) True so Fraction obviously does comparisons differently. Decimal is something of an anomaly in Python because it was written to exactly follow an external standard, with no concessions to what would be sensible for Python. It is possible that that standard mandates that Decimals not compare to floats. tjr From arnodel at googlemail.com Mon Sep 22 08:22:11 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Sep 2008 05:22:11 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <f5df9f65-a13d-4f5f-9cf9-534d37dd04c0@f63g2000hsf.googlegroups.com> <5a37d7ca-e7b4-4278-8fc3-f5d0f4303cee@79g2000hsk.googlegroups.com> Message-ID: <765bbf9b-2ff5-4318-9a7e-75f1a678ec8a@m3g2000hsc.googlegroups.com> On 22 Sep, 11:52, josh logan <dear.jay.lo... at gmail.com> wrote: > On Sep 22, 3:41 am, Arnaud Delobelle <arno... at googlemail.com> wrote: > > > > > On 22 Sep, 04:05, josh logan <dear.jay.lo... at gmail.com> wrote: > > > > Hello, > > > > I have 2 questions. Say I have this class: > > > > class Player(object): > > > def __init__(self, fname, lname, score): > > > self.score = score > > > self.fname = fname > > > self.lname = lname > > > def __cmp__(self, other): > > > return (-cmp(self.score, other.score) or > > > cmp(self.lname, other.lname) or > > > cmp(self.fname, other.fname)) > > > def __repr__(self): > > > return 'Player(fname={0.fname}, lname={0.lname}, > > > score={0.score})'.format(self) > > > def __eq__(self, others): > > > if isinstance(other, Player): > > > return (self.score == other.score and > > > self.lname == other.lname and > > > self.fname == other.fname) > > > return False > > > def __ne__(self, others): > > > return not self.__eq__(others) > > > > fnames = ['Julie', 'Ben', 'Jason', 'David'] > > > lnames = ['Parks', 'Smith'] > > > scores = [100, 95, 95, 130, 58, 74] > > > > import itertools as it > > > > score_iter = it.cycle(scores) > > > > P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in > > > lnames] > > > > cmp(P[0], P[1]) # returns -1 > > > > sorted(P) # throws TypeError: unorderable types Player() < Player() > > > > The sorted function works when I define __lt__. > > > I must be misreading the documentation, because I read for the > > > documentation __cmp__ that it is called if none of the other rich > > > comparison functions are defined. > > > Is this a bug in Python 3.0rc1, or am I missing something? > > > > Secondly, say that we suddenly need another sorting order, where we > > > want to sort by decreasing score and then by DECREASING last name > > > (instead of increasing last name, defined above). Now that the > > > comparison function argument is taken away from the sorted builtin, > > > how do we accomplish this with the "key" parameter? > > > > Thank you > > > I don't know about __cmp__ but for the second part of the question you > > can probably do: > > > sorted(P, key=lambda p: (p.score, p.lname), reverse=True) > > > HTH > > > -- > > Arnaud > > Thank you for the prompt reply. I didn't think my second question > completely through. > > A better example would be sorting by increasing last name and > decreasing first name. This would be easy with the sort function > comparator, but I can't see how to do the same with the key argument. > Is the only solution to decorate the Player objects in another class > that has the appropriate __cmp__ function (or whatever is needed) and > then retrieve the Player objects back? You can use the stability of the sorting algorithm as Peter pointed out. If decorating, you don't need to decorate the Player objects, but you can decorate the keys instead: e.g class RevStr(str): def __lt__(self, other): return str.__lt__(other, self) def __ge__(self, other): retrn str.__gt__(other, self) then you can write: sorted(P, key=lambda p:(p.lname, RevStr(p.fname))) -- Arnaud From hrishys at yahoo.co.uk Thu Sep 25 07:08:34 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 11:08:34 +0000 (GMT) Subject: Linq to Python In-Reply-To: <a88ec2b4-2c64-4eba-b83d-a414eac74919@w7g2000hsa.googlegroups.com> Message-ID: <14608.59387.qm@web27402.mail.ukl.yahoo.com> Hi Pardon my ignorance again but id ont see any join in python or did i miss something ? regards Hrishy --- On Thu, 25/9/08, sturlamolden <sturlamolden at yahoo.no> wrote: > From: sturlamolden <sturlamolden at yahoo.no> > Subject: Re: Linq to Python > To: python-list at python.org > Date: Thursday, 25 September, 2008, 12:02 PM > On 25 Sep, 12:06, hrishy <hris... at yahoo.co.uk> wrote: > > > [code] > > var stoogeGuys = > > ? ? ?Beginning with the XML source > > ? ? ?from xmlGuys in > xmlSource.Descendants("Stooge") > > ? ? ?Join to the array on the common element > "stoogeName" > > ? ? ?join arrayGuys in familyFacts > > ? ? ? ? ? ?on > xmlGuys.Element("stoogeName").Value equals > arrayGuys.stoogeName > > ? ? ?Join to the database on the common element > "stoogeName" > > ? ? ?join dbGuys in stoogeContext.stoogeTables > > ? ? ? ? ? ?on > xmlGuys.Element("stoogeName").Value equals > dbGuys.stoogeName > > ? ? ?select new > > ? ? ?{ > > ? ? ? ? firstName ? ?= dbGuys.stoogeName, > > ? ? ? ? familyName ? = arrayGuys.familyName, > > ? ? ? ? birthDate ? ?= > xmlGuys.Element("birthDate").Value, > > ? ? ? ? deathDate ? ?= > xmlGuys.Element("deathDate").Value, > > ? ? ? ? hairCutStyle = dbGuys.stoogeHaircut, > > ? ? ?}; > > [/code] > > It could e.g. look like this in Python: > > stoogeGuys = [] > for xmlGuys in xmlSource.Descendants["Stooge"]: > arrayGuys = familyFacts[xmlGuys.stoogeName] > dbGuys = stoogeContext.stoogeTables[xmlGuys.stoogeName] > stoogeGuys += \ > [{'firstName': dbGuys.stoogeName, > 'familyName': arrayGuys.familyName, > 'birthDate': xmlGuys.birthDate, > 'deathDate': dbGuys.deathDate, > 'hairCutStyle': dbGuys.stoogeHaircut}] > > -- > http://mail.python.org/mailman/listinfo/python-list From ireborin at delete.this.gmail.com Tue Sep 23 07:45:40 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 23 Sep 2008 13:45:40 +0200 Subject: gplt from scipy missing ? References: <lckgd4dsk4hqfsibr5ldv3tnc3dl6lfvum@4ax.com> <mailman.1393.1222154779.3487.python-list@python.org> <67lhd4hq1gch3r18g919fjvmijen9saevv@4ax.com> Message-ID: <mllhd41t4tl696muvvul4shrd14qlp21q5@4ax.com> On Tue, 23 Sep 2008 13:44:41 +0200, Ivan Reborin <ireborin at delete.this.gmail.com> wrote: >On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" ><gagsl-py2 at yahoo.com.ar> wrote: > >> >>I think scipy does not bundle plotting packages anymore - you may use >>whatever suits you, from other sources. >>Try matplotlib, see the wiki: >>http://wiki.python.org/moin/NumericAndScientific/Plotting > >Hello Gabriel, >thank you for answering. > >Unfortunatelly, I cannot change my plotting package, unless I indend >to change a lot of code that I'll be using in the future. I'm not a >programmer by trade, just a guy doing some calculations with already >written programms. > >Do you know, by any chance, where one could get gplt separately, or >for example, get older versions of scipy ? >I'm using python 5.2.2.. If I install scipy for python 2.3. for Mea culpa, *2.5.2 >example (let's assume that one still has gplt in it) will it work ? > >Best regards >Ivan From roy at panix.com Mon Sep 29 09:56:19 2008 From: roy at panix.com (Roy Smith) Date: Mon, 29 Sep 2008 09:56:19 -0400 Subject: One class per file? References: <a932e44b-3566-4c0f-8b63-2dce0a82946b@34g2000hsh.googlegroups.com> Message-ID: <roy-6C98ED.09561929092008@news.panix.com> In article <a932e44b-3566-4c0f-8b63-2dce0a82946b at 34g2000hsh.googlegroups.com>, HCB <hypercaffeinatedbiped at gmail.com> wrote: > Hello: > > The book "Code Complete" recommends that you put only one class in a > source file, which seems a bit extreme for me. It seems that many > classes are small, so that putting several of them in a file seems > reasonable. I noticed that the decimal.py module in the standard > library has several classes, all of which of course revolve around the > "decimal" topic. Perhaps a better rule of thumb is "one idea per > file." I checked the Python style guide and there seems to be no > mention of this topic. I know this is an elementary question, but what > is the Python way of doing this? > > Thanks for your time. > HCB Steve McConnell writes a lot of good stuff. Like most people who write a lot of good stuff, not everything he writes should be taken as gospel. With that in mind... Consider this. You're slogging through some code in a large project trying to debug a problem when you come upon the line (in pseudo-code): foo = SomeClass::SomeFunction(bar) You want to go look at the source for SomeClass. What file do you open to find it? If you follow the "one class per file" rule, the answer is easy; it's in SomeClass.xxx! That being said, the "one class per file" rule is a means to an end. If your code is written in such a way that it's easy to figure out where the source for a given class/function/whatever is, then you've done the right thing. The specifics of how you do that depend on the language you're using. In Python (as other posters have pointed out), modules give you a good way to group logical collections of classes (etc). If you see in some code: foo = some_module.SomeClass.SomeFunction(bar) you should instantly know that the source code is in some_module.py. Perhaps one way to look at this is that Python automatically follows the "one class per file" rule, except that "class" is crossed out and "module" written in with crayon. On the other hand, if you prefer self-abuse, Python gives you plenty of ways to do that. If you preface all your source files with: from some_module import * from some_other_module import * from yet_a_third_module import * from another_module import * and then see foo = SomeClass.SomeFunction(bar) you're right back to having no clue what file to open to find the source for SomeClass. Global namespace is sacred; treat it with respect! From pruthviraj.pb at gmail.com Mon Sep 15 06:15:26 2008 From: pruthviraj.pb at gmail.com (Babloo) Date: Mon, 15 Sep 2008 03:15:26 -0700 (PDT) Subject: Client server implementation Message-ID: <f2190158-93fe-4747-864f-cbba0f690f0e@b30g2000prf.googlegroups.com> Hi everyone, i wanted to implement a client- server connection and transfer a file over the network. i was able to implement a normal set up where in i was able to send chat messages and small chunks of data. I want to implement the file transfer with out using the FTP library available in python . So can anyone suggest a piece of code by which i can do that. Thanks Pruthvi From http Sun Sep 7 18:06:18 2008 From: http (Paul Rubin) Date: 07 Sep 2008 15:06:18 -0700 Subject: problem with permutations References: <fb82c6bc-e22f-4502-9d6a-4616ce53517c@59g2000hsb.googlegroups.com> Message-ID: <7xej3vwqzp.fsf@ruckus.brouhaha.com> cnb <circularfunc at yahoo.se> writes: > perms([]) -> [[]]; > perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. I think the most direct transcription might be: def perms(xs): if len(xs)==0: return [[]] return [([h]+t) for h in xs for t in perms([y for y in xs if y not in [h]])] But it is rather inefficient, as is the Erlang version. From ethan at stoneleaf.us Fri Sep 5 15:49:49 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 05 Sep 2008 11:49:49 -0800 Subject: print doesn't respect file inheritance? In-Reply-To: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> Message-ID: <48C18D5D.8060106@stoneleaf.us> bukzor wrote: > I was trying to change the behaviour of print (tee all output to a > temp file) by inheriting from file and overwriting sys.stdout, but it > looks like print uses C-level stuff to do its writes which bypasses > the python object/inhertiance system. It looks like I need to use > composition instead of inheritance, but thought this was strange > enough to note. > > $python -V > Python 2.5 > > """A short demo script""" > class notafile(file): > def __init__(self, *args, **kwargs): > readonly = ['closed', '__class__', 'encoding', 'mode', 'name', > 'newlines', 'softspace'] > file.__init__(self, *args, **kwargs) > for attr in dir(file): > if attr in readonly: continue > setattr(self, attr, None) > > > def main(): > n = notafile('/dev/stdout', "w") > print vars(n) > > import sys > sys.stdout = n > print "Testing: 1, 2, 3..." > > > output: > {'__str__': None, 'xreadlines': None, 'readlines': None, 'flush': > None, 'close': None, 'seek': None, '__init__': None, '__setattr__': > None, '__reduce_ex__': None, '__new__': None, 'readinto': None, > 'next': None, 'write': None, '__doc__': None, 'isatty': None, > 'truncate': None, 'read': None, '__reduce__': None, > '__getattribute__': None, '__iter__': None, 'readline': None, > 'fileno': None, 'writelines': None, 'tell': None, '__delattr__': None, > '__repr__': None, '__hash__': None} > Testing: 1, 2, 3... I tried the code (on Windows, so had to change /dev/stdout to /temp/notafile.txt) and it worked just fine. Perhaps the issue is that n is being set to /dev/stdout instead of some other file so no difference is apparent? In other words, you're assigning stdout to stdout. ~Ethan~ From gagsl-py2 at yahoo.com.ar Sun Sep 14 17:03:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Sep 2008 18:03:55 -0300 Subject: How to marshal objects to readable files? References: <mailman.1007.1221406286.3487.python-list@python.org> <143e575e-4745-4148-86de-deb2dbc0651d@m3g2000hsc.googlegroups.com> Message-ID: <op.uhhostxax6zn5v@a98gizw.noga> En Sun, 14 Sep 2008 15:09:52 -0300, Aaron "Castironpi" Brady <castironpi at gmail.com> escribi?: > On Sep 14, 10:28?am, nielinjie <nielin... at gmail.com> wrote: >> Hi list: >> I just want to marshal objects (instance of custom classes)to a human >> *READABEL *file/string, and also, I want unmarshal it back. in xml >> format or any other format. >> Any advice? Which lib should I use? > > The PyYAML package produces the following (continued): > >>>> print yaml.dump( a ) > &id001 !!python/object:__main__.A > b: 0 > c: abc > d: !!python/object:__main__.A > d: efg > e: 1.2 > parent: *id001 > JSON is another format, much simpler and probably more suited for human reading. But it is somewhat limited on what it can represent. There are a few Python implementations, maybe the most used is simplejson, which comes bundled with Python 2.6 as the json module. -- Gabriel Genellina From kyosohma at gmail.com Mon Sep 22 14:38:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 22 Sep 2008 11:38:25 -0700 (PDT) Subject: Problems running on hp dual core processor References: <mailman.1372.1222108408.3487.python-list@python.org> Message-ID: <05057996-444a-4fc8-b426-1be486db04f7@z72g2000hsb.googlegroups.com> On Sep 22, 1:43?pm, jim-on-linux <inq1... at inqvista.com> wrote: > Python help, > > I have a number of clients running a program built with > python 2.5. ?One has just purchased an HP with a duel > core processor, ?2.2G with .099g ram. > > On the new hp, when they try to print they get an > import error; > File win32ui.pyc line 12, in <module> > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: ?The specified module > could not be found. > > The file is there The only difference I could find from > their other machines is the processor. I have people running my compiled python applications on single and dual core processors with no problem. I suspect that you may just need to compile your application with some different switches, such as bundle=3 in py2exe for example. Mike From jukka.aho at iki.fi Tue Sep 2 06:17:10 2008 From: jukka.aho at iki.fi (Jukka Aho) Date: Tue, 2 Sep 2008 13:17:10 +0300 Subject: Python 3.0b2 cannot map '\u12b' References: <d0652dd2-24f6-4045-89a8-ba6deaf25b37@c65g2000hsa.googlegroups.com> <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> <mailman.312.1220250492.3487.python-list@python.org><6i24u3Fo7morU2@mid.uni-berlin.de> <mailman.336.1220293518.3487.python-list@python.org> Message-ID: <1n8vk.59481$_03.43814@reader1.news.saunalahti.fi> Terry Reedy wrote: >> If the terminal expects cp437 then displaying utf-8 might give some >> problems. > My screen displays whatever Windows tells the graphics card to tell > the screen to display. In OpenOffice, I can select a unicode font > that displays at least everything in the BasicMultilingualPlane (BMP). It would appear that the Windows port of Python is probably just not forcing the Win32 console into the Unicode mode or using the Unicode APIs. (If this holds true, it could be a leftover from the Windows 95/98/ME days, I suppose...) <http://en.wikipedia.org/wiki/Win32_console> As a workaround - for the time being - you might want to try something similar as described in the thread "Changing the (codec) error handler for the stdout/stderr streams in Python 3.0". The approach described in there will not let you print characters outside the codepage 437 repertoaire - any such characters will still need to be substituted with something else - but at least this substitution should happen automatically; i.e. you can keep using the normal print() function the normal way - even for the fancier characters - and your program will no longer crash. It would be nice to see proper Unicode Win32 console support in Python, of course, if at all possible. -- znark From steve at REMOVE-THIS-cybersource.com.au Thu Sep 25 02:10:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 06:10:39 GMT Subject: Off topic: Sent from my Foo messages References: <ea42fb160809241402i1c6da16t4dd2456a87d6f177@mail.gmail.com> <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <mailman.1474.1222296372.3487.python-list@python.org> <00eaf368$0$20666$c3e8da3@news.astraweb.com> <e2f73058-feb0-405e-8c47-25eb25410215@n38g2000prl.googlegroups.com> Message-ID: <00eb2533$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 20:04:14 -0700, Sean DiZazzo wrote: >> -- >> Steven > > I don't appreciate the two lines you put above your name in your posts. > Please remove them in the future. I don't like them either, but it is an email and Usenet standard to separate the body of your post from the signature with "-- ". I'm afraid that as obnoxious as the dashes are, leaving them out would be much worse. -- Steven From bignose+hates-spam at benfinney.id.au Mon Sep 1 21:13:27 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 02 Sep 2008 11:13:27 +1000 Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> Message-ID: <87ej43pcy0.fsf@benfinney.id.au> bearophileHUGS at lycos.com writes: > For Python 2.7/3.1 I'd now like to write a PEP regarding the > underscores into the number literals, like: 0b_0101_1111, 268_435_456 > etc. +1 on such a capability. -1 on underscore as the separator. When you proposed this last year, the counter-proposal was made <URL:http://groups.google.com/group/comp.lang.python/msg/18123d100bba63b8?dmode=source> to instead use white space for the separator, exactly as one can now do with string literals. I don't see any good reason (other than your familiarity with the D language) to use underscores for this purpose, and much more reason (readability, consistency, fewer arbitrary differences in syntax, perhaps simpler implementation) to use whitespace just as with string literals. -- \ ?When in doubt tell the truth. It will confound your enemies | `\ and astound your friends.? ?Mark Twain, _Following the Equator_ | _o__) | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Thu Sep 25 14:34:28 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 20:34:28 +0200 Subject: PEP Proposal In-Reply-To: <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> <mailman.1508.1222373098.3487.python-list@python.org> <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <48dbf59f$0$1374$426a74cc@news.free.fr> python-pep at arcor.de a ?crit : > Gabriel Genellina wrote: > >> En Thu, 25 Sep 2008 16:24:58 -0300, <python-pep at arcor.de> escribi?: >> >>> sorry, I have these ideas for longer than 10 years, please have a look >>> on it >>> and comment on it. Thx. >>> >>> This is another proposal for introducing types into Python. >> You got the terminology wrong. Python had "types" from the very start. >> You're talking about some kind of generic functions, or an alternative >> dispatch method. > > Typed parameters. are unpythonic. > Method-Declaration-filtered-typed parameters. Philip Eby's RuleDispatch package goes way further, already exists, and doesn't require any new syntax. From bignose+hates-spam at benfinney.id.au Wed Sep 17 08:36:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Sep 2008 22:36:41 +1000 Subject: Python OOP advice References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> Message-ID: <87fxnz3q5i.fsf@benfinney.id.au> Simon Hibbs <simon.hibbs at gmail.com> writes: > Orriginaly I thought I'd need to have a hull object which contains > component objects, but the component objects need access to members > of the hull object (e.g. the hull size) so that looks messy to > implement. Was it as messy as this:: class ShipHull(object): def __init__(self, size): self.components = dict() self.size = size class ShipComponent(object): def __init__(self, name, hull): self.name = name self.hull = hull > I have defined a base class Component with a class member variable > 'hull_size' so that all components can see the hull size. It seems to me the hull is an attribute of the component, and the size is an attribute of the hull. Why would the hull size be a *class* attribute? > I've then got two child classes called Fixed_Component and Percent > _Component that implement their mass, mass_percent and cost > properties appropriately for their type. class FixedShipComponent(ShipComponent): def _get_mass(self): return calculation_foo(self.hull.size) mass = property(_get_mass) def _get_cost(self): return calculation_bar(self.hull.size) cost = property(_get_cost) class PercentShipComponent(ShipComponent): def _get_mass(self): return calculation_spam(self.hull.size) mass = property(_get_mass) def _get_cost(self): return calculation_eggs(self.hull.size) cost = property(_get_cost) > I've also defined a Hull class which also inherits from Component > and provides methods for access to the hull_size class variable. I don't see why, if a ShipComponent needs to refer to its hull as something special, that a ShipHull would subclass ShipComponent. > Is there a way to cleanly implement a parent-child relationship > between objects that gives child objects limited access to members > of the parent? Sure; have the child instance grow an attribute referencing the parent, preferably by passing it to the initialisation function (__init__) of the child. -- \ Rommel: ?Don't move, or I'll turn the key on this can of Spam!? | `\ ?The Goon Show, _Rommel's Treasure_ | _o__) | Ben Finney From half.italian at gmail.com Sun Sep 21 19:11:02 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 21 Sep 2008 16:11:02 -0700 (PDT) Subject: appending * to glob returns files with '*' !! References: <mailman.1343.1222037582.3487.python-list@python.org> Message-ID: <ffdc64d2-861a-4e36-9466-2e28e6e5c3b1@r15g2000prd.googlegroups.com> On Sep 19, 1:37?pm, "John [H2O]" <washa... at gmail.com> wrote: > I have a glob.glob search: > > searchstring = os.path.join('path'+'EN*') shouldn't that be os.path.join(path, 'EN*') ? > ___ > This returns some files: > EN082333 > EN092334 > EN* Mine doesn't return that last string. > > My routine cannot handle the '*' and it should'nt be returned anyway? :-/ > Well, its an easy fix. files = glob.glob(searchstring) for f in files: if not f[-1] =="*": print f > A bug? Post a small *tested* example that recreates the error on your system. ~Sean From niklas.norrthon at hotmail.com Tue Sep 16 08:52:38 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Tue, 16 Sep 2008 05:52:38 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? References: <cb798579-d5d9-4a2f-843b-6fcca31fb5de@e39g2000hsf.googlegroups.com> Message-ID: <d2c7b432-2cd3-449b-bcb4-58e6f614f4f4@z72g2000hsb.googlegroups.com> On 16 Sep, 14:01, cnb <circularf... at yahoo.se> wrote: > I'm trying to switch to using emacs for python. > > The interpreter and python-mode works but I can't load the file I'm > editing into the interpreter. I'm using emacs to edit and run python programs on windows. In my .emacs I have the following line: (setq python-python-command "C:\\python25\\python.exe") And it works. Another alternative is to set the environment variable PYTHONPATH to point to the location of the python interpreter, but then you also need to edit the .../lisp/progmodes/python.el file to use semicolon (instead of colon) as a path separator. (in emacs 22.1 it is in line 1354 of the file (search for PYTHONPATH). (Or perhaps you needed to that anyway... I'm not sure). Good luck Niklas Norrthon From mnordhoff at mattnordhoff.com Thu Sep 11 09:59:10 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 11 Sep 2008 13:59:10 +0000 Subject: function return In-Reply-To: <aa405c1f0809110544l4b2a3e6aw724d1296761ec427@mail.gmail.com> References: <aa405c1f0809110544l4b2a3e6aw724d1296761ec427@mail.gmail.com> Message-ID: <48C9242E.6090509@mattnordhoff.com> Beema Shafreen wrote: > hi all, > > I have a script using functions , I have a problem in returning the > result. My script returns only one line , i donot know where the looping > is giving problem, Can any one suggest, why this is happening and let me > know how to return all the lines > > def get_ptm(): > fh = open('file.txt', 'r') > data_lis = [] > for line in fh.readlines(): As an aside, you should change the above line to: for line in fh: "readlines()" will read the entire file into memory at once, while just iterating through it won't, so you'll save memory on large files. > data = line.strip().split('\t') > id = data[0].strip() > gene_symbol = data[1].strip() > ptms = data[8].strip() > result = "%s\t%s\t%s" %(id,gene_symbol,ptms) This is very trivial, but you could change the above line to: result = "\t".join(id, gene_symbol, ptms) > return result > fh.close() -- From kyosohma at gmail.com Thu Sep 25 09:13:48 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 25 Sep 2008 06:13:48 -0700 (PDT) Subject: urllib error on urlopen References: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> <00eaf2fa$0$20666$c3e8da3@news.astraweb.com> Message-ID: <6d10384b-7b2a-41b0-85d5-d339df3d1e4c@j22g2000hsf.googlegroups.com> On Sep 24, 9:36?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Wed, 24 Sep 2008 08:46:56 -0700, Mike Driscoll wrote: > > Hi, > > > I have been using the following code for over a year in one of my > > programs: > > > f = urllib2.urlopen('https://www.companywebsite.com/somestring') > > > It worked great until the middle of the afternoon yesterday. Now I get > > the following traceback: > ... > > URLError: <urlopen error (1, 'error:140770FC:SSL > > routines:SSL23_GET_SERVER_HELLO:unknown protocol')> > > Have you recently set a proxy where Python can auto-detect it? I > understand that urllib2 doesn't work well with https proxies. > > If so, you can instruct urllib2 not to use a proxy-handler, but it's more > work. What I do is construct an opener without a proxyhandler: > > # untested... > no_proxy_support = urllib2.ProxyHandler({}) > opener = urllib2.build_opener(no_proxy_support) > f = opener.open('https://www.companywebsite.com/somestring') > > If that doesn't work, you may need to build a Request object from the URL > before passing it to opener.open. > > -- > Steven As I mentioned to Mr. Palmer, the error has mysteriously gone away this morning. I'll keep your advice handy though, in case it happens again. Thanks, Mike From Scott.Daniels at Acm.Org Tue Sep 23 23:11:13 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 23 Sep 2008 20:11:13 -0700 Subject: Detecting the first time I open/append to a file In-Reply-To: <mailman.1429.1222206115.3487.python-list@python.org> References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> <mailman.1429.1222206115.3487.python-list@python.org> Message-ID: <vuydnbDiJZsiMUTVnZ2dnUVZ_qvinZ2d@pdx.net> Terry Reedy wrote: > tkpmep at hotmail.com wrote: >> ...If I can sense that the file is being created in the first iteration, >> I can then use an if statement to decide whether or not I need to >> write the header. Question: how can I tell if the file is being >> created or if this its the first iteration? ... > > How about file.tell == 0? or have I misunderstood the requirement? OI thought roughly the same thing when I saw this, how about if not file.tell(): <produce header> --Scott David Daniels Scott.Daniels at Acm.Org From bearophileHUGS at lycos.com Tue Sep 23 20:15:24 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 23 Sep 2008 17:15:24 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <d086d0b2-0624-45ee-b72f-49d88a7dfe33@79g2000hsk.googlegroups.com> <c5e8ae40-9ed6-41c9-8914-4a3d0f001f0c@m36g2000hse.googlegroups.com> <f8912309-81ac-4bf1-ab26-b5cbc64ff52f@79g2000hsk.googlegroups.com> Message-ID: <85773da5-90a2-498c-bb30-c94bf2afefee@k30g2000hse.googlegroups.com> sturlamolden: > It seems we have been implementing different algorithms. kd-trees are > not BK-trees. > http://www.scipy.org/Cookbook/KDTree Sorry for my silly mistake :-) Note: in your code I don't know if the collections.deque data structure may help (it's faster than list for appending), but I presume that's not a bottleneck. Bye, bearophile From jackie.python at gmail.com Sun Sep 21 22:02:30 2008 From: jackie.python at gmail.com (Jackie Wang) Date: Sun, 21 Sep 2008 22:02:30 -0400 Subject: pause between the loops Message-ID: <37b964200809211902r206e951ep8d83cad88c93d45f@mail.gmail.com> Hi all, For a loop like: for i = range (0,10); can I ask python to stop for, say, 5mins, after it go through loop i=0 before it starts loop i=1? Thank you very much! Jackie From digitig at gmail.com Fri Sep 26 12:43:23 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 26 Sep 2008 17:43:23 +0100 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> Message-ID: <aee48b3c0809260943h7f7edae3qb447174bc62bfa49@mail.gmail.com> 2008/9/26 Steven D'Aprano <steve at remove-this-cybersource.com.au>: > I don't have any objective numbers, but subjectively it seems to me that > the number of spams is significantly higher, but not so high as to be a > major nuisance. I consider *any* spam to be a major nuisance, but I don't see them as being the fault of python-list which seems to do a pretty good job of blocking them -- Tim Rowe From grante at visi.com Mon Sep 8 15:21:27 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 08 Sep 2008 14:21:27 -0500 Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <ccf8d124-4609-48a6-b487-7cccc6d9c4b9@a3g2000prm.googlegroups.com> <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <mailman.701.1220900693.3487.python-list@python.org> Message-ID: <qa6dnVXB2Pyq5ljVnZ2dnUVZ_jCdnZ2d@posted.visi> On 2008-09-08, Chris Rebert <clp at rebertia.com> wrote: > On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <ewertman at gmail.com> wrote: > >> To expand on this a little bit, I've been subscribed to this >> group for a couple of months, but there seems to be a bit more >> gray area between what would go to a 'python-dev' group and a >> 'python-user' group. Long debates about language features and >> abstract ideas would appeal to the former, but not the latter. >> Certainly I fall into the user category.. I'm pretty happy >> with python, and generally just adjust to it's design and >> features, rather than spend lots of time on whether they are >> 'right' or could be 'better'. /shrug > > Yeah, suggestions about changing the language are much better > suited to the more-specific Python-ideas or Python-3000 > mailinglists than the general-purpose c.l.p I don't think anybody here in c.l.p minds reading suggestions for language features/changes, but often what the poster in question writes is just an incomprehensible collection of vaguely philosophical-sounding metaphores and similes reminiscent of a hoax paper submitted as a joke to a post-modern "journal" of some pretend science or other. -- Grant Edwards grante Yow! Used staples are good at with SOY SAUCE! visi.com From a at nospam.org Tue Sep 16 04:20:19 2008 From: a at nospam.org (Armin) Date: Tue, 16 Sep 2008 10:20:19 +0200 Subject: append on lists In-Reply-To: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: <ganpdo$1gf$1@online.de> John Machin wrote: > On Sep 16, 6:45 am, Armin <a... at nospam.org> wrote: > >> Yes, but this is very unconvenient. >> If d should reference the list a extended with a single list element >> you need at least two lines >> >> a.append(7) >> d=a >> >> and not more intuitive d = a.append(7) > > Methods/functions which return a value other than the formal None and > also mutate their environment are "a snare and a delusion". Don't wish > for them. c = [9,10] [1,2,3,4,7].append(c) -> Is this a valid expression? The 'value' of that expression is None. However ... that's the way of the implementation of the append method. It's a little bit confusing to me ... --Armin Thanks to all ! > > Inconvenient? How often do you want to mutate a list and then set up > another reference to it? > From castironpi at gmail.com Mon Sep 8 15:20:42 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 8 Sep 2008 12:20:42 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <ccf8d124-4609-48a6-b487-7cccc6d9c4b9@a3g2000prm.googlegroups.com> <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <mailman.701.1220900693.3487.python-list@python.org> Message-ID: <f59badb9-3c36-4273-a0e2-a8f8156a0326@z66g2000hsc.googlegroups.com> On Sep 8, 2:04?pm, "Chris Rebert" <c... at rebertia.com> wrote: > On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <ewert... at gmail.com> wrote: > >> Perhaps the wrong idea of what the group is. ?I would have thought > >> that > >> if one had a sufficiently developed idea and wanted to have it / > >> formally/ > >> rejected, rather than merely sniped at, then writting a PEP would be > >> more > >> apposite than posting to c.l.py. > > >> It's fine to post your not sufficiently developed ideas here merely > >> to > >> have them discussed. ?But I don't know what makes you feel that you, > >> or > >> your ideas, are /entitled/ to any response at all, much less > >> "follow-through." > > > To expand on this a little bit, ?I've been subscribed to this group > > for a couple of months, but there seems to be a bit more gray area > > between what would go to a 'python-dev' ?group and a 'python-user' > > group. ? Long debates about language features and abstract ideas would > > appeal to the former, but not the latter. ?Certainly I fall into the > > user category.. ?I'm pretty happy with python, and generally just > > adjust to it's design and features, rather than spend lots of time on > > whether they are 'right' or could be 'better'. ?/shrug > > Yeah, suggestions about changing the language are much better suited > to the more-specific Python-ideas or Python-3000 mailinglists than the > general-purpose c.l.p > - Chris > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com Some of the core devs from Python-Ideas have suggested that I get some of my ideas started on c.l.py. Also, I'm looking for people to connect with and interact with about Python and none of the core devs have time, which makes c.l.py the place. I'm starting to get discouraged, as though there's no one really interested in this cool thing I'm thinking of. Or did I just not describe it well? It would be safe to assume that people read my post, understood it, and weren't interested, except that a few replies came, and then it was dropped without any obvious explanation. Further, and I'm sad to report this, I found tempers really high strung on the Ideas list, so c.l.py may have more potential anyway, with more young and flexible users. Not to say that the core devs are old or brittle or anything, just that their time is already devoted and they don't have time for people like me. From bearophileHUGS at lycos.com Wed Sep 3 08:48:23 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 05:48:23 -0700 (PDT) Subject: max(), sum(), next() Message-ID: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Empty Python lists [] don't know the type of the items it will contain, so this sounds strange: >>> sum([]) 0 Because that [] may be an empty sequence of someobject: >>> sum(s for s in ["a", "b"] if len(s) > 2) 0 In a statically typed language in that situation you may answer the initializer value of the type of the items of the list, as I do in the sum() in D. This sounds like a more correct/clean thing to do: >>> max([]) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: max() arg is an empty sequence So it may be better to make the sum([]) too raise a ValueError, in Python 3/3.1 (if this isn't already true). On the other hand often enough I have code like this: >>> max(fun(x) for x in iterable if predicate(x)) This may raise the ValueError both if iterable is empty of if the predicate on its items is always false, so instead of catching exceptions, that I try to avoid, I usually end with a normal loop, that's readable and fast: max_value = smallvalue for x in iterable: if predicate(x): max_value = max(max_value, fun(x)) Where running speed matters, I may even replace that max(max_value, fun(x)) with a more normal if/else. A possible alternative is to add a default to max(), like the next() built-in of Python 2.6: >>> max((fun(x) for x in iterable if predicate(x)), default=smallvalue) This returns smallvalue if there are no items to compute the max of. Bye, bearophile From justin.kuto at gmail.com Fri Sep 26 17:46:21 2008 From: justin.kuto at gmail.com (afrogazer) Date: Fri, 26 Sep 2008 14:46:21 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> <f0c482f1-7148-43c4-87b1-3b4718d5d18d@8g2000hse.googlegroups.com> <7b1181e9-16a2-458a-8677-a2d8d7c8a961@l42g2000hsc.googlegroups.com> <05d9ca4d-441e-484b-ba1b-9e0ef7fa4658@d70g2000hsc.googlegroups.com> Message-ID: <0d00a562-37cf-4071-8f9f-73746b26c13f@k37g2000hsf.googlegroups.com> On Sep 26, 4:42?pm, Bas <wegw... at gmail.com> wrote: > On Sep 26, 10:33?pm, afrogazer <justin.k... at gmail.com> wrote:> rad_angles = [elem*(pi/180) for elem in angles] > > You are missing some more on a friday afternoon: angles is created by > arange, so it is a numpy array. In that case you simply can do > rad_angles = pi/180 * angles > No need to use list-comprehensions, that is the whole idea about using > these kick-ass objects! > > Bas Thanks! Should have thought of that, Fridays are a drag. From tjreedy at udel.edu Tue Sep 23 17:49:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 17:49:32 -0400 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <gbbo92$3j3$1@ger.gmane.org> Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), No > or should the exception propagate to the calling program which > handles the issue? Yes -- with an informative error message. If the caller ignores the exception, the program will exit with a full stack trace anyway. From bearophileHUGS at lycos.com Fri Sep 12 16:27:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Sep 2008 13:27:35 -0700 (PDT) Subject: manipulating files within 'for' References: <48CAA2AA.40809@umbc.edu> <gae9jj$sks$1@ger.gmane.org> <mailman.940.1221242051.3487.python-list@python.org> <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> <mailman.945.1221249453.3487.python-list@python.org> <cfc0851d-fe26-4064-a739-3bba7f7e6989@73g2000hsx.googlegroups.com> Message-ID: <2e96faf2-ef11-4703-b393-995fae724193@j22g2000hsf.googlegroups.com> Matt Nordhoff: > BTW, I could easily be wrong, but I think C behaves the same way as Python. C syntax has many traps that are much better out of modern languages like Python/D/etc. I think C has that feature because it lacks an operator for string concatenation, while both Python and D have one (+ and ~. D uses the ~ to avoid any programmer confusion with the mathematical summing operator), so the situation of Python/D is different. Bye, bearophile From jfabiani at yolo.com Tue Sep 2 10:44:00 2008 From: jfabiani at yolo.com (John Fabiani) Date: Tue, 02 Sep 2008 07:44:00 -0700 Subject: configure kdevelop for python References: <2f21628f-80dd-4710-b0be-2b1c772e5698@l33g2000pri.googlegroups.com> Message-ID: <GO6dnX7CJcOtzCDVnZ2dnUVZ_tLinZ2d@wavecable.com> Sindhu wrote: > am a newbie to python language and kdevelop, so i would like to know > how to configure kdevelop for python programming? complete with a > debugger? I have not used python and kdevelop but I do know it requires qt and the link below has several video's of a developer using python qt and qtdesigner. http://tv.dgplug.org/devel-inside.html I hope this helps. Johnf From febkimbleox at gmail.com Sat Sep 27 07:19:18 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:19:18 -0700 (PDT) Subject: free porno amaterski snimci porno free severina porno video free amaterske - Free Message-ID: <03782abb-c04a-403d-bff2-265887e33fee@w7g2000hsa.googlegroups.com> free . . . *******CLICK HERE******** http://vids365.cn/free ***************************** . . . . . . . . . . . . She had a healthy baby girl by the way, and breast feeds free and free both whenever free gets a chance. She had a healthy baby girl by the way, and breast feeds porno and porno both whenever porno gets a chance. She had a healthy baby girl by the way, and breast feeds amaterski and amaterski both whenever amaterski gets a chance. She had a healthy baby girl by the way, and breast feeds snimci and snimci both whenever snimci gets a chance. She had a healthy baby girl by the way, and breast feeds porno and porno both whenever porno gets a chance. She had a healthy baby girl by the way, and breast feeds free and free both whenever free gets a chance. She had a healthy baby girl by the way, and breast feeds severina and severina both whenever severina gets a chance. ?Oh baby, porno have a perfect pussy. ?Oh baby, video have a perfect pussy. ?Oh baby, free have a perfect pussy. ?Oh baby, amaterske have a perfect pussy. ?Oh baby, porno have a perfect pussy. ?Oh baby, slike have a perfect pussy. ?Oh baby, free have a perfect pussy. ?Oh baby, porno have a perfect pussy. ?Oh baby, film have a perfect pussy. ?Oh baby, free have a perfect pussy. ?Oh baby, porno have a perfect pussy. ?Oh baby, filmovi have a perfect pussy. Our visitor moved around in front of Tammy at the back of the couch and took out free cock. Our visitor moved around in front of Tammy at the back of the couch and took out download cock. Our visitor moved around in front of Tammy at the back of the couch and took out free cock. Our visitor moved around in front of Tammy at the back of the couch and took out porno cock. Our visitor moved around in front of Tammy at the back of the couch and took out sex cock. Our visitor moved around in front of Tammy at the back of the couch and took out tv cock. Our visitor moved around in front of Tammy at the back of the couch and took out free cock. Our visitor moved around in front of Tammy at the back of the couch and took out porno cock. Our visitor moved around in front of Tammy at the back of the couch and took out movies cock. Our visitor moved around in front of Tammy at the back of the couch and took out free cock. Our visitor moved around in front of Tammy at the back of the couch and took out porno cock. Our visitor moved around in front of Tammy at the back of the couch and took out videos cock. Part three;As free sat free in free favorite chair, free couldn?t stop thinking about Mandy. Part three;As porno sat porno in porno favorite chair, porno couldn?t stop thinking about Mandy. Part three;As index sat index in index favorite chair, index couldn?t stop thinking about Mandy. Part three;As free sat free in free favorite chair, free couldn?t stop thinking about Mandy. Part three;As gey sat gey in gey favorite chair, gey couldn?t stop thinking about Mandy. Part three;As porno sat porno in porno favorite chair, porno couldn?t stop thinking about Mandy. Part three;As free sat free in free favorite chair, free couldn?t stop thinking about Mandy. Part three;As porno sat porno in porno favorite chair, porno couldn?t stop thinking about Mandy. Part three;As filmi sat filmi in filmi favorite chair, filmi couldn?t stop thinking about Mandy. Part three;As free sat free in free favorite chair, free couldn?t stop thinking about Mandy. Part three;As porno sat porno in porno favorite chair, porno couldn?t stop thinking about Mandy. Part three;As films sat films in films favorite chair, films couldn?t stop thinking about Mandy. free could hear Tammy's breathing become ragged as free continued sucking. home could hear Tammy's breathing become ragged as home continued sucking. video could hear Tammy's breathing become ragged as video continued sucking. porno could hear Tammy's breathing become ragged as porno continued sucking. porno could hear Tammy's breathing become ragged as porno continued sucking. free could hear Tammy's breathing become ragged as free continued sucking. free could hear Tammy's breathing become ragged as free continued sucking. porno could hear Tammy's breathing become ragged as porno continued sucking. clips could hear Tammy's breathing become ragged as clips continued sucking. filmi could hear Tammy's breathing become ragged as filmi continued sucking. porno could hear Tammy's breathing become ragged as porno continued sucking. free could hear Tammy's breathing become ragged as free continued sucking. However, what paris wanted the most was for Mandy to have a happy life, love, and more. However, what hilton wanted the most was for Mandy to have a happy life, love, and more. However, what free wanted the most was for Mandy to have a happy life, love, and more. However, what porno wanted the most was for Mandy to have a happy life, love, and more. However, what free wanted the most was for Mandy to have a happy life, love, and more. However, what adult wanted the most was for Mandy to have a happy life, love, and more. However, what porno wanted the most was for Mandy to have a happy life, love, and more. However, what free wanted the most was for Mandy to have a happy life, love, and more. However, what porno wanted the most was for Mandy to have a happy life, love, and more. However, what film wanted the most was for Mandy to have a happy life, love, and more. However, what porno wanted the most was for Mandy to have a happy life, love, and more. This seemed to calm Tammy, as filmi pulled filmi maternity top over filmi head and stood there in filmi shorts and bra. This seemed to calm Tammy, as free pulled free maternity top over free head and stood there in free shorts and bra. This seemed to calm Tammy, as free pulled free maternity top over free head and stood there in free shorts and bra. This seemed to calm Tammy, as porno pulled porno maternity top over porno head and stood there in porno shorts and bra. This seemed to calm Tammy, as pics pulled pics maternity top over pics head and stood there in pics shorts and bra. This seemed to calm Tammy, as free pulled free maternity top over free head and stood there in free shorts and bra. This seemed to calm Tammy, as porno pulled porno maternity top over porno head and stood there in porno shorts and bra. This seemed to calm Tammy, as video pulled video maternity top over video head and stood there in video shorts and bra. This seemed to calm Tammy, as ceca pulled ceca maternity top over ceca head and stood there in ceca shorts and bra. This seemed to calm Tammy, as porno pulled porno maternity top over porno head and stood there in porno shorts and bra. This seemed to calm Tammy, as 3gp pulled 3gp maternity top over 3gp head and stood there in 3gp shorts and bra. This seemed to calm Tammy, as free pulled free maternity top over free head and stood there in free shorts and bra. As to kiss to tongue probes to mouth, doing the dance of lovers. As download kiss download tongue probes download mouth, doing the dance of lovers. As free kiss free tongue probes free mouth, doing the dance of lovers. As pornos kiss pornos tongue probes pornos mouth, doing the dance of lovers. As free kiss free tongue probes free mouth, doing the dance of lovers. As bbw kiss bbw tongue probes bbw mouth, doing the dance of lovers. As porno kiss porno tongue probes porno mouth, doing the dance of lovers. As free kiss free tongue probes free mouth, doing the dance of lovers. As porno kiss porno tongue probes porno mouth, doing the dance of lovers. As pictures kiss pictures tongue probes pictures mouth, doing the dance of lovers. As porno kiss porno tongue probes porno mouth, doing the dance of lovers. As fimi kiss fimi tongue probes fimi mouth, doing the dance of lovers. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, films were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, tv were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, mature were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. Under sites breath sites utters, ?Maybe she?ll let sites join sites in the shower. Under free breath free utters, ?Maybe she?ll let free join free in the shower. Under gay breath gay utters, ?Maybe she?ll let gay join gay in the shower. Under porno breath porno utters, ?Maybe she?ll let porno join porno in the shower. Under free breath free utters, ?Maybe she?ll let free join free in the shower. Under full breath full utters, ?Maybe she?ll let full join full in the shower. Under length breath length utters, ?Maybe she?ll let length join length in the shower. Under porno breath porno utters, ?Maybe she?ll let porno join porno in the shower. Under videos breath videos utters, ?Maybe she?ll let videos join videos in the shower. Under free breath free utters, ?Maybe she?ll let free join free in the shower. Under lesbian breath lesbian utters, ?Maybe she?ll let lesbian join lesbian in the shower. Under porno breath porno utters, ?Maybe she?ll let porno join porno in the shower. free couldn't take the sight of free hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. xxx couldn't take the sight of xxx hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. porno couldn't take the sight of porno hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. slovenski couldn't take the sight of slovenski hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. porno couldn't take the sight of porno hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. free couldn't take the sight of free hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. free couldn't take the sight of free hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. black couldn't take the sight of black hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. porno couldn't take the sight of porno hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. sex couldn't take the sight of sex hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. porno couldn't take the sight of porno hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. He finger-fucked free a few times then pulled free dripping fingers out, gazing into free passion- glazed eyes. He finger-fucked slike a few times then pulled slike dripping fingers out, gazing into slike passion-glazed eyes. He finger-fucked partis a few times then pulled partis dripping fingers out, gazing into partis passion-glazed eyes. He finger-fucked free a few times then pulled free dripping fingers out, gazing into free passion-glazed eyes. He finger-fucked porno a few times then pulled porno dripping fingers out, gazing into porno passion-glazed eyes. He finger-fucked free a few times then pulled free dripping fingers out, gazing into free passion-glazed eyes. He finger-fucked porno a few times then pulled porno dripping fingers out, gazing into porno passion-glazed eyes. He finger-fucked pictures a few times then pulled pictures dripping fingers out, gazing into pictures passion- glazed eyes. He finger-fucked online a few times then pulled online dripping fingers out, gazing into online passion-glazed eyes. He finger-fucked free a few times then pulled free dripping fingers out, gazing into free passion-glazed eyes. He finger-fucked mpeg a few times then pulled mpeg dripping fingers out, gazing into mpeg passion- glazed eyes. He finger-fucked porno a few times then pulled porno dripping fingers out, gazing into porno passion-glazed eyes. porno flicked on the nightstand light. films flicked on the nightstand light. free flicked on the nightstand light. downolads flicked on the nightstand light. free flicked on the nightstand light. porno flicked on the nightstand light. thumbnails flicked on the nightstand light. sex flicked on the nightstand light. thumbnail flicked on the nightstand light. free flicked on the nightstand light. porno flicked on the nightstand light. galleries flicked on the nightstand light. ?He looks straight into free eyes and exclaims, ?Can Daddy eat free pussy as free suck my cock??Mandy then tells free Daddy to lie down so free can straddle free face. ?He looks straight into porno eyes and exclaims, ?Can Daddy eat porno pussy as porno suck my cock??Mandy then tells porno Daddy to lie down so porno can straddle porno face. ?He looks straight into downloads eyes and exclaims, ?Can Daddy eat downloads pussy as downloads suck my cock??Mandy then tells downloads Daddy to lie down so downloads can straddle downloads face. ?He looks straight into free eyes and exclaims, ?Can Daddy eat free pussy as free suck my cock??Mandy then tells free Daddy to lie down so free can straddle free face. ?He looks straight into porno eyes and exclaims, ?Can Daddy eat porno pussy as porno suck my cock??Mandy then tells porno Daddy to lie down so porno can straddle porno face. ?He looks straight into movie eyes and exclaims, ?Can Daddy eat movie pussy as movie suck my cock??Mandy then tells movie Daddy to lie down so movie can straddle movie face. ?He looks straight into porno eyes and exclaims, ?Can Daddy eat porno pussy as porno suck my cock??Mandy then tells porno Daddy to lie down so porno can straddle porno face. ?He looks straight into video eyes and exclaims, ?Can Daddy eat video pussy as video suck my cock??Mandy then tells video Daddy to lie down so video can straddle video face. ?He looks straight into clips eyes and exclaims, ?Can Daddy eat clips pussy as clips suck my cock??Mandy then tells clips Daddy to lie down so clips can straddle clips face. ?He looks straight into free eyes and exclaims, ?Can Daddy eat free pussy as free suck my cock??Mandy then tells free Daddy to lie down so free can straddle free face. ?He looks straight into free eyes and exclaims, ?Can Daddy eat free pussy as free suck my cock??Mandy then tells free Daddy to lie down so free can straddle free face. ?He looks straight into porno eyes and exclaims, ?Can Daddy eat porno pussy as porno suck my cock??Mandy then tells porno Daddy to lie down so porno can straddle porno face. vids thought, My God, vids is going to whip me! Sure enough, vids began caressing my legs, thighs, stomach, and breasts with it. videos thought, My God, videos is going to whip me! Sure enough, videos began caressing my legs, thighs, stomach, and breasts with it. 3gp thought, My God, 3gp is going to whip me! Sure enough, 3gp began caressing my legs, thighs, stomach, and breasts with it. porno thought, My God, porno is going to whip me! Sure enough, porno began caressing my legs, thighs, stomach, and breasts with it. free thought, My God, free is going to whip me! Sure enough, free began caressing my legs, thighs, stomach, and breasts with it. porno thought, My God, porno is going to whip me! Sure enough, porno began caressing my legs, thighs, stomach, and breasts with it. ftp thought, My God, ftp is going to whip me! Sure enough, ftp began caressing my legs, thighs, stomach, and breasts with it. free thought, My God, free is going to whip me! Sure enough, free began caressing my legs, thighs, stomach, and breasts with it. porno thought, My God, porno is going to whip me! Sure enough, porno began caressing my legs, thighs, stomach, and breasts with it. video thought, My God, video is going to whip me! Sure enough, video began caressing my legs, thighs, stomach, and breasts with it. free thought, My God, free is going to whip me! Sure enough, free began caressing my legs, thighs, stomach, and breasts with it. free thought, My God, free is going to whip me! Sure enough, free began caressing my legs, thighs, stomach, and breasts with it. ?Ooooh, I?m sorry, full didn?t mean to do that. ?Ooooh, I?m sorry, length didn?t mean to do that. ?Ooooh, I?m sorry, porno didn?t mean to do that. ?Ooooh, I?m sorry, movies didn?t mean to do that. ?Ooooh, I?m sorry, free didn?t mean to do that. ?Ooooh, I?m sorry, online didn?t mean to do that. ?Ooooh, I?m sorry, porno didn?t mean to do that. ?Ooooh, I?m sorry, free didn?t mean to do that. ?Ooooh, I?m sorry, black didn?t mean to do that. ?Ooooh, I?m sorry, porno didn?t mean to do that. ?Ooooh, I?m sorry, clips didn?t mean to do that. ?Ooooh, I?m sorry, manga didn?t mean to do that. She continued by criss-crossing my legs with lashes from free crop. She continued by criss-crossing my legs with lashes from porno crop. She continued by criss-crossing my legs with lashes from free crop. She continued by criss-crossing my legs with lashes from full crop. She continued by criss-crossing my legs with lashes from length crop. She continued by criss-crossing my legs with lashes from porno crop. She continued by criss-crossing my legs with lashes from free crop. She continued by criss-crossing my legs with lashes from asian crop. She continued by criss-crossing my legs with lashes from porno crop. She continued by criss-crossing my legs with lashes from porno crop. She continued by criss-crossing my legs with lashes from video crop. She continued by criss-crossing my legs with lashes from free crop. While Mandy was taking dovnload clothes off, dovnload could not help but think of what could happen during or after the massage. While Mandy was taking sex clothes off, sex could not help but think of what could happen during or after the massage. While Mandy was taking porno clothes off, porno could not help but think of what could happen during or after the massage. While Mandy was taking free clothes off, free could not help but think of what could happen during or after the massage. While Mandy was taking free clothes off, free could not help but think of what could happen during or after the massage. While Mandy was taking porno clothes off, porno could not help but think of what could happen during or after the massage. While Mandy was taking comics clothes off, comics could not help but think of what could happen during or after the massage. While Mandy was taking free clothes off, free could not help but think of what could happen during or after the massage. While Mandy was taking porno clothes off, porno could not help but think of what could happen during or after the massage. While Mandy was taking online clothes off, online could not help but think of what could happen during or after the massage. While Mandy was taking free clothes off, free could not help but think of what could happen during or after the massage. While Mandy was taking granny clothes off, granny could not help but think of what could happen during or after the massage. To which porno replied, Well, don't let porno catch porno like that again. To which free replied, Well, don't let free catch free like that again. To which mature replied, Well, don't let mature catch mature like that again. To which porno replied, Well, don't let porno catch porno like that again. To which pics replied, Well, don't let pics catch pics like that again. To which free replied, Well, don't let free catch free like that again. To which porno replied, Well, don't let porno catch porno like that again. To which trailers replied, Well, don't let trailers catch trailers like that again. To which free replied, Well, don't let free catch free like that again. To which animal replied, Well, don't let animal catch animal like that again. To which porno replied, Well, don't let porno catch porno like that again. To which free replied, Well, don't let free catch free like that again. Maybe streaming could give streaming a massage; after all streaming is always complaining how streaming back aches after working. Maybe porno could give porno a massage; after all porno is always complaining how porno back aches after working. Maybe free could give free a massage; after all free is always complaining how free back aches after working. Maybe teen could give teen a massage; after all teen is always complaining how teen back aches after working. Maybe porno could give porno a massage; after all porno is always complaining how porno back aches after working. Maybe free could give free a massage; after all free is always complaining how free back aches after working. Maybe video could give video a massage; after all video is always complaining how video back aches after working. Maybe porno could give porno a massage; after all porno is always complaining how porno back aches after working. Maybe hardcore could give hardcore a massage; after all hardcore is always complaining how hardcore back aches after working. Maybe teen could give teen a massage; after all teen is always complaining how teen back aches after working. Maybe porno could give porno a massage; after all porno is always complaining how porno back aches after working. Maybe free could give free a massage; after all free is always complaining how free back aches after working. After a few moments, I'd located and was exploring the contents of porno underwear drawer. After a few moments, I'd located and was exploring the contents of free underwear drawer. After a few moments, I'd located and was exploring the contents of download underwear drawer. After a few moments, I'd located and was exploring the contents of porno underwear drawer. After a few moments, I'd located and was exploring the contents of movies underwear drawer. After a few moments, I'd located and was exploring the contents of free underwear drawer. After a few moments, I'd located and was exploring the contents of free underwear drawer. After a few moments, I'd located and was exploring the contents of double underwear drawer. After a few moments, I'd located and was exploring the contents of penetration underwear drawer. After a few moments, I'd located and was exploring the contents of porno underwear drawer. After a few moments, I'd located and was exploring the contents of free underwear drawer. After a few moments, I'd located and was exploring the contents of mature underwear drawer. When Mandy arrives home from work porno Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work pictures Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work free Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work porno Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work download Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work free Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work porno Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work movie Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work sites Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work porno Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work world Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work free Dad had supper already prepared and was adding the finishing touches to the table. Then videos can say my favorite word. Then suzana can say my favorite word. Then mancic can say my favorite word. Then porno can say my favorite word. Then video can say my favorite word. Then free can say my favorite word. Then free can say my favorite word. Then porno can say my favorite word. Then games can say my favorite word. Then free can say my favorite word. Then porno can say my favorite word. Then video can say my favorite word. She could feel downloads orgasm building as downloads moved downloads prick in and out, downloads laboured breathing hot against downloads face, downloads hands covering downloads tits, tweaking at downloads engorged nipples. She could feel tv orgasm building as tv moved tv prick in and out, tv laboured breathing hot against tv face, tv hands covering tv tits, tweaking at tv engorged nipples. She could feel porno orgasm building as porno moved porno prick in and out, porno laboured breathing hot against porno face, porno hands covering porno tits, tweaking at porno engorged nipples. She could feel free orgasm building as free moved free prick in and out, free laboured breathing hot against free face, free hands covering free tits, tweaking at free engorged nipples. She could feel free orgasm building as free moved free prick in and out, free laboured breathing hot against free face, free hands covering free tits, tweaking at free engorged nipples. She could feel porno orgasm building as porno moved porno prick in and out, porno laboured breathing hot against porno face, porno hands covering porno tits, tweaking at porno engorged nipples. She could feel comics orgasm building as comics moved comics prick in and out, comics laboured breathing hot against comics face, comics hands covering comics tits, tweaking at comics engorged nipples. She could feel with orgasm building as with moved with prick in and out, with laboured breathing hot against with face, with hands covering with tits, tweaking at with engorged nipples. She could feel archie orgasm building as archie moved archie prick in and out, archie laboured breathing hot against archie face, archie hands covering archie tits, tweaking at archie engorged nipples. She could feel free orgasm building as free moved free prick in and out, free laboured breathing hot against free face, free hands covering free tits, tweaking at free engorged nipples. She could feel shemale orgasm building as shemale moved shemale prick in and out, shemale laboured breathing hot against shemale face, shemale hands covering shemale tits, tweaking at shemale engorged nipples. She could feel porno orgasm building as porno moved porno prick in and out, porno laboured breathing hot against porno face, porno hands covering porno tits, tweaking at porno engorged nipples. When sites appeared to be done sites was looking in sites jewelry box for something to go with sites outfit. When xxx appeared to be done xxx was looking in xxx jewelry box for something to go with xxx outfit. When free appeared to be done free was looking in free jewelry box for something to go with free outfit. When porno appeared to be done porno was looking in porno jewelry box for something to go with porno outfit. When free appeared to be done free was looking in free jewelry box for something to go with free outfit. When college appeared to be done college was looking in college jewelry box for something to go with college outfit. When porno appeared to be done porno was looking in porno jewelry box for something to go with porno outfit. When movies appeared to be done movies was looking in movies jewelry box for something to go with movies outfit. When free appeared to be done free was looking in free jewelry box for something to go with free outfit. When download appeared to be done download was looking in download jewelry box for something to go with download outfit. When porno appeared to be done porno was looking in porno jewelry box for something to go with porno outfit. When free appeared to be done free was looking in free jewelry box for something to go with free outfit. funny looked absolutely stunning in a long yellow dress with a matching garland in funny hair, flashing funny a quick smile as funny went past. porno looked absolutely stunning in a long yellow dress with a matching garland in porno hair, flashing porno a quick smile as porno went past. jpg looked absolutely stunning in a long yellow dress with a matching garland in jpg hair, flashing jpg a quick smile as jpg went past. free looked absolutely stunning in a long yellow dress with a matching garland in free hair, flashing free a quick smile as free went past. porno looked absolutely stunning in a long yellow dress with a matching garland in porno hair, flashing porno a quick smile as porno went past. movie looked absolutely stunning in a long yellow dress with a matching garland in movie hair, flashing movie a quick smile as movie went past. clips looked absolutely stunning in a long yellow dress with a matching garland in clips hair, flashing clips a quick smile as clips went past. free looked absolutely stunning in a long yellow dress with a matching garland in free hair, flashing free a quick smile as free went past. porno looked absolutely stunning in a long yellow dress with a matching garland in porno hair, flashing porno a quick smile as porno went past. psp looked absolutely stunning in a long yellow dress with a matching garland in psp hair, flashing psp a quick smile as psp went past. pamela looked absolutely stunning in a long yellow dress with a matching garland in pamela hair, flashing pamela a quick smile as pamela went past. anderson looked absolutely stunning in a long yellow dress with a matching garland in anderson hair, flashing anderson a quick smile as anderson went past. Maybe free would, after all free said free was taking free shopping. Maybe porno would, after all porno said porno was taking porno shopping. Maybe films would, after all films said films was taking films shopping. Maybe porno would, after all porno said porno was taking porno shopping. Maybe video would, after all video said video was taking video shopping. Maybe severina would, after all severina said severina was taking severina shopping. Maybe free would, after all free said free was taking free shopping. Maybe doenload would, after all doenload said doenload was taking doenload shopping. Maybe ashley would, after all ashley said ashley was taking ashley shopping. Maybe jensen would, after all jensen said jensen was taking jensen shopping. Maybe free would, after all free said free was taking free shopping. Maybe porno would, after all porno said porno was taking porno shopping. videos felt videos little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving videos hand up and down. free felt free little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving free hand up and down. adult felt adult little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving adult hand up and down. porno felt porno little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving porno hand up and down. sites felt sites little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving sites hand up and down. free felt free little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving free hand up and down. porno felt porno little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving porno hand up and down. websites felt websites little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving websites hand up and down. free felt free little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving free hand up and down. severina felt severina little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving severina hand up and down. porno felt porno little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving porno hand up and down. download felt download little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving download hand up and down. After ordering the flowers and limousine, free made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, streaming made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, online made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, porno made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, porno made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, sex made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, video made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, severina made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, free made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, download made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, porno made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, world made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. ?Oh my God, what have hardcord done to me?, my beautiful young cousin was glassy eyed as hardcord shifted position and was face to face with my rampant cock. ?Oh my God, what have free done to me?, my beautiful young cousin was glassy eyed as free shifted position and was face to face with my rampant cock. ?Oh my God, what have videos done to me?, my beautiful young cousin was glassy eyed as videos shifted position and was face to face with my rampant cock. ?Oh my God, what have video done to me?, my beautiful young cousin was glassy eyed as video shifted position and was face to face with my rampant cock. ?Oh my God, what have porno done to me?, my beautiful young cousin was glassy eyed as porno shifted position and was face to face with my rampant cock. ?Oh my God, what have free done to me?, my beautiful young cousin was glassy eyed as free shifted position and was face to face with my rampant cock. From robert.d.kirkpatrick at gmail.com Tue Sep 23 18:53:03 2008 From: robert.d.kirkpatrick at gmail.com (Rob Kirkpatrick) Date: Tue, 23 Sep 2008 15:53:03 -0700 (PDT) Subject: Visualize class inheritance hierarchy Message-ID: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Hi All, I just finished debugging some code where I needed to determine why one subclass had a bound method and another did not. They had different pedigree's but I didn't know immediately what the differences were. I ended up walking the hierarchy, going back one class at a time through the code, for the two subclasses (hierarchy ~7 classes deep each) to see whom they inherited from. Short of writing this down on paper, is there any way to graphically display the pedigree of an object/class? "Graphically" can be text output to the terminal, don't need anything special... I'm assuming this has been discussed before, but I'm lacking any Google keywords that bring up the appropriate discussion. Cheers, Rob From callen314 at gmail.com Thu Sep 11 17:03:31 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 11 Sep 2008 14:03:31 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <mailman.876.1221142791.3487.python-list@python.org> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> <09345856-9a44-449c-9ee0-6254c573847e@b1g2000hsg.googlegroups.com> Message-ID: <d328bff0-8c1d-4509-baa7-3db999b90f1d@1g2000pre.googlegroups.com> > What's business logic? an oxymoron? From mcrute at gmail.com Sat Sep 27 20:00:59 2008 From: mcrute at gmail.com (Michael Crute) Date: Sat, 27 Sep 2008 20:00:59 -0400 Subject: check if file is MS Word or PDF file In-Reply-To: <47c890dc0809271601y6f5a4a5fy98fad966e5ca024@mail.gmail.com> References: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> <47c890dc0809271601y6f5a4a5fy98fad966e5ca024@mail.gmail.com> Message-ID: <558b73fb0809271700g53c33c3cj42afdfbc729103e3@mail.gmail.com> On Sat, Sep 27, 2008 at 7:01 PM, Chris Rebert <clp at rebertia.com> wrote: > Looking at the docs for the mimetypes module, it just guesses based on > the filename (and extension), not the actual contents of the file, so > it doesn't really help the OP, who wants to make sure their program > isn't misled by an inaccurate extension. One other way to detect a pdf is to just read the first 4 bytes from the file. Valid pdf files start with "%PDF-". Something similar can be done with Word docs but I don't know what the magic bytes are. This approach is pretty similar to what the file command does but is probably a better approach if you have to support multiple platforms. -mike -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From castironpi at gmail.com Sun Sep 7 18:24:48 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 7 Sep 2008 15:24:48 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> Message-ID: <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> On Sep 7, 5:03?pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: > On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > > This is the strangest post I've seen > > since I've joined this list (only > > recently). What the ? > > Yeah, castironpi sometimes doesn't make much sense. ?Maybe because it's a > bot!? ?:-) > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch No, I'm legit, and I believe my complaint is. That's all I can guarantee anyway. While I'm still not a vet on Usenet, I'm still disappointed so far. Though I should be flattered for my logic to be ever compared to an A.I.'s. Maybe the ideas are not that groundbreaking, but they still have been dropped instead of critiqued. Problem. From gagsl-py2 at yahoo.com.ar Fri Sep 19 00:03:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 01:03:10 -0300 Subject: Do HTTPError objects always have a read method? References: <pan.2008.09.18.01.48.26@REMOVE.THIS.cybersource.com.au> <op.uhphqwt5x6zn5v@gabriel2.softlabbsas.com.ar> Message-ID: <op.uhpmvkdcx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 18 Sep 2008 23:12:22 -0300, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> escribi?: > En Wed, 17 Sep 2008 22:48:27 -0300, Steven D'Aprano > <steven at remove.this.cybersource.com.au> escribi?: > >> Under what circumstances do HTTPError objects not have a valid file >> object? How common is this? Does anyone have an example of a URL that >> fails in that fashion? > > Well, there is at least one case (AbstractDigestAuthHandler at line 864 > in urllib2.py) where HTTPError is raised explicitely with fp=None. It's > not a common case, I think. If you rely on the exception having a read() > method, add it a fake one yourself: > > try: ... > except urllib2.HTTPError, e: > if not hasattr(e, 'read'): > e.read = e.readline = lambda self: '' # or perhaps e.msg > conn = e Oops, that should have been e.read = lambda: '' -- Gabriel Genellina From st1999 at gmail.com Sun Sep 28 21:44:20 2008 From: st1999 at gmail.com (robean) Date: Sun, 28 Sep 2008 18:44:20 -0700 (PDT) Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> <mailman.1635.1222629122.3487.python-list@python.org> <d127e341-c16d-4ef9-b1de-b9076cefdcb4@i20g2000prf.googlegroups.com> <357e734f-e99f-41e5-9cac-083d636a23e1@n38g2000prl.googlegroups.com> <95f8433c-213f-4b3a-8d93-bebbe2561e7f@s9g2000prg.googlegroups.com> Message-ID: <781c4e48-7396-4278-85bd-3578f88aa501@l33g2000pri.googlegroups.com> On Sep 28, 5:33?pm, alex23 <wuwe... at gmail.com> wrote: > On Sep 29, 5:52?am, robean <st1... at gmail.com> wrote: > > > Actually, the problem seems to be that IOError is in my namespace, but > > the other error classes are not. So, > > > ? ?except HTTPError, etc. > > > fails, but > > > ? ?except urllib2.HttpError, etc. > > > works fine. Now, I still don't understand why these classes shouldn't > > automatically work.... > > IOError is a standard Python exception. HTTPError & URLError are > exceptions provided by the urllib2 module. They need to be imported > from or referenced through urllib2 to be used. Many thanks for your reply. I was simply under the impression that 'import urllib2' would take care of the namespace issue and simply import everything in urlib2, making it unnecessary to have to reference HTTPError and URLError. Sorry for being dense about this (I'm very new to Python).. Again, thanks for your help. From castironpi at gmail.com Wed Sep 3 18:31:51 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 3 Sep 2008 15:31:51 -0700 (PDT) Subject: xml + mmap cross Message-ID: <a27b2e33-bddb-407e-b2ea-895dc78c7090@r15g2000prd.googlegroups.com> Any interest in pursuing/developing/working together on a mmaped-xml class? Faster, not readable in text editor. From castironpi at gmail.com Mon Sep 15 16:09:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 15 Sep 2008 13:09:00 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> <pan.2008.09.11.07.40.08@REMOVE.THIS.cybersource.com.au> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <pan.2008.09.12.03.37.51@REMOVE.THIS.cybersource.com.au> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <pan.2008.09.12.06.30.43@REMOVE.THIS.cybersource.com.au> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> <f62644a0-51c4-4eb1-96e4-eab96d431b74@l42g2000hsc.googlegroups.com> Message-ID: <b1a06f31-92df-45a3-8b1c-d2b5269ad18f@k30g2000hse.googlegroups.com> On Sep 15, 4:34?am, Francesc <fal... at gmail.com> wrote: > On 12 Set, 14:39, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> > wrote: > > > > > > A consideration of other storage formats such as HDF5 might > > > be appropriate: > > > >http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > > > There are, of course, HDF5 tools available for Python. > > > PyTablescame up within the past few weeks on the list. > > > "When the file is created, the metadata in the object tree is updated > > in memory while the actual data is saved to disk. When you close the > > file the object tree is no longer available. However, when you reopen > > this file the object tree will be reconstructed in memory from the > > metadata on disk...." > > > This is different from what I had in mind, but the extremity depends > > on how slow the 'reconstructed in memory' step is. ?(Fromhttp://www.pytables.org/docs/manual/ch01.html#id2506782). ?The > > counterexample would be needing random access into multiple data > > files, which don't all fit in memory at once, but the maturity of the > > package might outweigh that. ?Reconstruction will form a bottleneck > > anyway. > > Hmm, this was a part of a documentation that needed to be updated. > Now, the object tree is reconstructed in a lazy way (i.e. on-demand), > in order to avoid the bottleneck that you mentioned. ?I have corrected > the docs in: > > http://www.pytables.org/trac/changeset/3714/trunk > > Thanks for (indirectly ;-) bringing this to my attention, > > Francesc Depending on how lazy the reconstruction is, would it be possible to modify separate tables from separate processes concurrently? From mcrute at gmail.com Sat Sep 27 18:42:29 2008 From: mcrute at gmail.com (Michael Crute) Date: Sat, 27 Sep 2008 18:42:29 -0400 Subject: check if file is MS Word or PDF file In-Reply-To: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> References: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> Message-ID: <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> On Sat, Sep 27, 2008 at 5:43 PM, A. Joseph <joefazee at gmail.com> wrote: > What should I look for in a file to determine whether or not it is a > MS Word file or an Excel file or a PDF file, etc., etc.? including Zip > files > > I don`t want to check for file extension. > os.path.splitext('Filename.jpg') will produce a tuple of filename and > extension, but some file don`t even have extension and can still be read by > MS Word or NotePad. i want to be 100% sure of the file. You could use the mimetypes module... <<< import mimetypes <<< mimetypes.guess_type("LegalNotices.pdf") >>> ('application/pdf', None) -mike -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From steven at REMOVE.THIS.cybersource.com.au Wed Sep 3 01:43:19 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 03 Sep 2008 05:43:19 GMT Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <mailman.395.1220399835.3487.python-list@python.org> Message-ID: <pan.2008.09.03.05.43.21@REMOVE.THIS.cybersource.com.au> On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote: > ssecorp wrote: >> or why does this take so god damn long time? > > Several reasons. One of which is that try: except: is slow. I beg to differ. Setting up a try...except block is very fast. Here's an example in Python 2.5: >>> from timeit import Timer >>> Timer('len("abc")').repeat() [0.27346706390380859, 0.1530919075012207, 0.14886784553527832] >>> Timer('''try: ... len("abc") ... except: ... pass ... ''').repeat() [0.27847194671630859, 0.19191384315490723, 0.19077491760253906] The difference (approx 0.04 microseconds) applicable to setting up the try...except block is trivial, of the same magnitude as a pass statement: >>> Timer('pass').repeat() [0.059719085693359375, 0.060056924819946289, 0.059512138366699219] However, *catching* the exception may be relatively slow: >>> Timer('''try: ... len(abc) # raise a NameError ... except: ... pass ... ''').repeat() [3.2067418098449707, 2.7088210582733154, 1.9558219909667969] -- Steven From namekuseijin at gmail.com Tue Sep 23 21:49:38 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Tue, 23 Sep 2008 18:49:38 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> Message-ID: <24e340b1-ec28-4435-b4df-f2296f7ae1d2@x41g2000hsb.googlegroups.com> On 23 set, 20:52, Neal Becker <ndbeck... at gmail.com> wrote: > In hindsight, I am disappointed with the choice of conditional syntax. ?I know it's too late to change. ?The problem is > > y = some thing or other if x else something_else > > When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). ?Particularly if 'some thing or other' is long or complicated. Yes, infix syntax sucks. No ambiguities in prefixed Lisp: (if x (or something other) something_else) Anyway, pretty amusing seeing Guido nodding to Larry... ;) From tjreedy at udel.edu Tue Sep 30 16:29:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 16:29:40 -0400 Subject: Would this be called a bug in inspect ? In-Reply-To: <48E28534.1040009@gmail.com> References: <48E268A3.4050900@gmail.com> <op.uia609w8x6zn5v@gabriel2.softlabbsas.com.ar> <48E28534.1040009@gmail.com> Message-ID: <gbu27j$3l5$1@ger.gmane.org> Stef Mientki wrote: > print getmembers ( wx ) > crashes > > but not always: > >>> print getmembers (wx) > [('ACCEL_ALT', 1), ('ACCEL_CMD', 2), ('ACCEL_CTRL', 2), ('ACCEL_NORMAL', > 0), ('ACCEL_SHIFT', 4), ('ADJUST_MINSIZE', 0), ( I suspect that wx has an erratic bug, which their tests do not catch. So I would send this off to them. > >>> print getmembers (wx) > Traceback (most recent call last): > File "<interactive input>", line 1, in <module> > File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line > 242, in __repr__ > def __repr__(self): return 'wx.Colour' + > str(self.Get(True)) > File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line > 230, in Get > return _gdi_.Colour_Get(*args, **kwargs) > TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' From code at pizzashack.org Mon Sep 29 02:15:19 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 29 Sep 2008 02:15:19 -0400 Subject: Test if list contains another list In-Reply-To: <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> <48c6380b$0$17080$426a34cc@news.free.fr> <mailman.741.1220976622.3487.python-list@python.org> <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> <mailman.1557.1222457112.3487.python-list@python.org> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> Message-ID: <20080929061518.GL26713@dragontoe.org> On Fri, Sep 26, 2008 at 01:39:16PM -0700, bearophileHUGS at lycos.com wrote: > # building prefix-function > m = 0 > for i in xrange(1, len_sub): > while m > 0 and sub[m] != sub[i]: > m = table[m - 1] > if sub[m] == sub[i]: > m += 1 > table[i] = m > > # searching > m, i = 0, 0 > for x in items: > while m > 0 and sub[m] != x: > m = table[m - 1] > if sub[m] == x: > m += 1 > if m == len_sub: > return True > i += 1 > > return False Quite a lot faster than mine... even without using psyco. Which is interesting, especially because if I change my search loop to work like yours, but leave out all your other optimizations, mine runs roughly as fast as yours (i.e. execution time is negligible to a user running the program in both cases, even with the large example data you gave). This leads me to point out two caveats with your version: 1. Guavat posted a version which returns a list of all the indexes where a match is found... which is what I mimiced. Yours returns only true or false indicating whether or not it found a match. The main difference in performance seems to come due to your iteration over the list items, versus my comparing a sublist-sized slice of the whole to the sublist. But this alone is an invalid optimization, because it doesn't produce the same results... If you only want to know if a match exists, it's great; but if you want to know *where*, or *how many times*, you lose. That could be fixed though, by counting the elements as you loop through them... I didn't attempt to determine the performance hit for doing that, but I assume it's negligible. I also imagine that that was your original purpose for the unused variable i... 2. Your secondary optimizations add a great deal of complexity to your code, making the algorithm much harder to understand. However they don't appear to buy you much, given that the cases they optimize would probably be rare, and the difference in execution time gained by the optimization is not noticable to the user. Unless you're doing lots and lots of these in your application, or maybe if you know in advance that your data will contain many instances of the cases you optimized, I think you're better off leaving the optimizations out, for the sake of code clarity. At the very least, if you're going to write complicated optimizations, you ought to have explained what you were doing in comments... :) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080929/b2f6cbe8/attachment.sig> From mail at timgolden.me.uk Fri Sep 12 08:35:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 13:35:29 +0100 Subject: testing if another instance of a script is already running In-Reply-To: <48CA5BA5.8020709@p0w.org> References: <48CA5BA5.8020709@p0w.org> Message-ID: <48CA6211.8050402@timgolden.me.uk> Strato wrote: > Hi folks, > > I want to write some kind of test to check at startup if another > instance of my script is already running. > > I don't want to handle writing of a PID file because it is too > Unix/Linux specific way to do this, and I need to keep the code to be > cross-platform. > > I think the better way to achieve this is to use some process control, > but I'm a neebie and I don't see how to do this in a safe and clean way. There's nothing built in to Python to do this, so you'll probably have to roll your own cross-platformness. Of course, there's nothing to stop you from writing pid files under Windows even if it's not the usual way. Or you could just put some conditional code, and use the kernel mutex under Windows, which is the generally recommended technique. Have a look at this thread, for example (among several others): http://mail.python.org/pipermail/python-list/2005-June/327063.html TJG From bborcic at gmail.com Sun Sep 14 05:41:17 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sun, 14 Sep 2008 11:41:17 +0200 Subject: recursion gotcha? In-Reply-To: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> Message-ID: <gaima0$2ak$1@ger.gmane.org> cnb wrote: > this recursive definition of sum thrumped me, is this some sort of > gotcha or am I just braindead today? > and yes i know this is easy a a for x in xs acc += x or just using the > builtin. > > def suma(xs, acc=0): > if len(xs) == 0: > acc > else: > suma(xs[1:], acc+xs[0]) > > it returns none. Without return statement, the only recursive solution is a lambda expr : >>> suma = lambda xs : xs[0]+suma(xs[1:]) if xs else 0 >>> suma(range(101)) 5050 Note that suma(xs[1:]) implies copying the remainder of xs, what in turn makes the time grow quadratically with the length of xs. So instead of passing a superfluous acc second variable, you could pass an index into the list, eg def suma(xs,pos=0) : if pos>=len(xs) : return 0 else : return xs[pos]+suma(xs,pos+1) Cheers, BB From spython01 at gmail.com Thu Sep 4 09:05:00 2008 From: spython01 at gmail.com (Samir) Date: Thu, 4 Sep 2008 06:05:00 -0700 (PDT) Subject: The Python Papers, Volume 3 Issue 2 References: <3eb3b85a-67cc-4260-a86f-acee9c8f6eb8@q5g2000prf.googlegroups.com> Message-ID: <0a7f9645-6dcd-40de-89f6-581393599733@z11g2000prl.googlegroups.com> On Sep 4, 8:58?am, "mauricel... at acm.org" <mauricel... at gmail.com> wrote: > Hi everyone > > After a long wait of nearly 5 month, we are back in business to bring > the latest edition of The Python Papers - Volume 3 Issue 2 (http:// > ojs.pythonpapers.org/index.php/tpp/issue/current). > > From this issue onwards, we will be having only 3 issues per year > instead of 4. This is in compliance with our ISSN registration. > > What's new > ========= > 1. We have expanded our editorial team with 2 new Associate Editors, > Sarah Mount (from UK) and Guy Kloss from (New Zealand). > > 2. TPP is now managed using Open Journal System and it can be assessed > athttp://ojs.pythonpapers.org/tpp > > 3. Backporting of previous issues of TPP from Volume 1 Issue 1 is > complete > > 4. We had "soft-launched" TWO new periodicals - The Python Papers > Monographs (for monograph-length submissions which may include > dissertations, conference proceedings, case studies and advanced-level > lectures) and The Python Papers Source Codes (modeled after ACM > Collected Algorithms and provides a collection of software and source > codes, usually associated with papers published in The Python Papers > and The Python Papers Monograph). They shall be TPPM and TPPSC > respectively. > > 5. Collectively, TPP, TPPM and TPPSC will be umbrella-ed as The Python > Papers Anthology (TPPA) and managed under the same editorial > committee. > > 6. Probably the most important development to TPP is that TPP is > currently indexed by a number of services, including Google Scholar > and OAIster, as a result of using Open Journal System. > > So, please enjoy our latest edition and we look towards all of your > continued support and contributions. > > Thank you. > > Cheers > Maurice Ling > Co-Editor-in-Chief, The Python Papers Anthology Good to see that the newest edition of the journal is out. Also, I believe the correct URL should either be: http://ojs.pythonpapers.org/ or http://ojs.pythonpapers.org/index.php/tpp Thanks for providing this great resource. Samir From deets at nospam.web.de Fri Sep 5 11:23:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 17:23:10 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <fc6a6c32-a023-4d6e-9089-bbcfc42de8d5@a8g2000prf.googlegroups.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> <acdc94a1-9f8c-49f3-b063-dd536e480d07@v39g2000pro.googlegroups.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> <48c03b91$0$14747$426a74cc@news.free.fr> <fc6a6c32-a023-4d6e-9089-bbcfc42de8d5@a8g2000prf.googlegroups.com> Message-ID: <6id16uFq5171U1@mid.uni-berlin.de> Ivan Illarionov schrieb: > On 4 ????, 21:49, Bruno Desthuilliers > <bdesth.quelquech... at free.quelquepart.fr> wrote: >> Ivan Illarionov a ?crit : >> >> >> >>> On 4 ????, 22:59, Carl Banks <pavlovevide... at gmail.com> wrote: >>>> You can write code to guard against this if you want: >>>> class A: >>>> legal = set(["x"]) >>>> def __setattr__(self,attr,val): >>>> if attr not in self.legal: >>>> raise AttributeError("A object has no attribute '%s'" % >>>> attr) >>>> self.__dict__[attr] = val >>>> def __init__(self,x): >>>> self.y = x >>>> I suspect most people who go into Python doing something like this >>>> soon abandon it when they see how rarely it actually catches anything. >>> '__slots__' is better: >> For which definition of "better" ? __slots__ are a mean to optimize >> memory usage, not to restrict dynamism. Being able to dynamically add >> arbitrary attributes is actually a feature, not a bug, and uselessly >> restricting users from doing so is not pythonic. IOW : don't do that. > > Carl's example is restricting dynamism in the same way as __slots__. > I've just suggested a better implementation. It is not me who > suggested dynamism restriction as a way to guard against errors. This is not correct. While Carl's Example looks similar, you actually *can* create new attributes using obj.__dict__['name'] = value __slots__ OTOH prevents that because it does create instances *without* an instance-dict. This being said, I think we all agree that it's nothing to be desired. Diez From sjmachin at lexicon.net Wed Sep 10 19:38:59 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Sep 2008 16:38:59 -0700 (PDT) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <ga91ft$12t$1@inews.gazeta.pl> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> Message-ID: <f9e73dd3-0600-45dd-8a35-2aaf9bf8d84d@z6g2000pre.googlegroups.com> On Sep 11, 4:16?am, Aaron Scott <aaron.hildebra... at gmail.com> wrote: > Taking everything into consideration, my code is now: > > import struct > file = open("test.gde", "rb") > signature = file.read(3) > version, attr_count = struct.unpack('II', file.read(8)) > print signature, version, attr_count > for idx in xrange(attr_count): > ? ? ? ? attr_id, attr_val_len = struct.unpack('II', file.read(8)) > ? ? ? ? attr_val = file.read(attr_val_len) > ? ? ? ? print attr_id, attr_val_len, attr_val > file.close() > > which gives a result of: > > GDE 2 2 > 1 4 ? > 2 4 ??? > > Essentially, the same results I was originally getting :( Stop thrashing about, and do the following: (1) print repr(open('test.gde, 'rb').read(100)) (2) tell us what you EXPECT to see in attr_val etc (3) tell us what platform the file was created on and what platform it's being read on (4) (on the reading platform, at least) import sys; print sys.byteorder When showing results, do print ..., repr(attr_val) From berthe.loic at gmail.com Wed Sep 3 13:30:01 2008 From: berthe.loic at gmail.com (LB) Date: Wed, 3 Sep 2008 10:30:01 -0700 (PDT) Subject: Help needed to freeze a script. Message-ID: <7f364174-75c6-4120-b00e-6f41643ccbf5@z72g2000hsb.googlegroups.com> Hi, I would like to freeze a numpy based script in order to have an application which could run without having to install numpy and cie. Indeed, I'm not root on the targeted computer and I can't easily make a complete install of numpy and scipy. So I decided to test the freeze.py tool shipped with python2.5. To complicate matters, I must say that I only have a local installation of python2.5 and numpy. I used the following command line : > python2.5 ../Python-2.5.1/Tools/freeze/freeze.py ~/Python/numpy/test_freeze.py At first sight, it seems to be fine, as I saw numpy in the liste of frozen dependancies : [...] freezing numpy ... freezing numpy.__config__ ... freezing numpy._import_tools ... freezing numpy.add_newdocs ... freezing numpy.core ... freezing numpy.core._internal ... freezing numpy.core.arrayprint ... freezing numpy.core.defchararray ... freezing numpy.core.defmatrix ... freezing numpy.core.fromnumeric ... freezing numpy.core.info ... freezing numpy.core.memmap ... freezing numpy.core.numeric ... freezing numpy.core.numerictypes ... freezing numpy.core.records ... freezing numpy.ctypeslib ... [...] freezing numpy.version ... But at the end I saw this message : Warning: unknown modules remain: _bisect _csv _ctypes _curses _hashlib _heapq [...] numpy.core._dotblas numpy.core._sort numpy.core.multiarray numpy.core.scalarmath numpy.core.umath numpy.fft.fftpack_lite numpy.lib._compiled_base numpy.linalg.lapack_lite numpy.random.mtrand operator parser pyexpat readline [...] Now run "make" to build the target: test_weibull I runned make without any problem but the final application didn't work : % ./test_freeze Traceback (most recent call last): File "/home/loic/Python/numpy/test_freeze.py", line 8, in <module> import numpy as np [...] File "/home/loic/tmp/bluelagoon/lib/python2.5/site-packages/numpy/ core/__init__.py", line 5, in <module> import multiarray ImportError: No module named multiarray Is there any known issue when freezing a numpy based script ? I should add that I configured my PYTHONPATH to match my local installation > echo $PYTHONPATH /home/loic/lib/python:/home/loic/tmp/bluelagoon/lib/python2.5:/home/ loic/tmp/bluelagoon/lib/python2.5/site-packages/: and this local installation work fine : > python2.5 -c 'import numpy; print numpy.__version__; import numpy.core.multiarray; print "no pb"' 1.2.0b2 no pb Have you got any recipe to freeze numpy based script ? Regards, -- LB From tom.willis at gmail.com Tue Sep 23 14:45:55 2008 From: tom.willis at gmail.com (Thomas G. Willis) Date: Tue, 23 Sep 2008 11:45:55 -0700 (PDT) Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <cab78de2-e472-439d-a0ec-de7e34b7be93@b2g2000prf.googlegroups.com> <00245d29-de1b-4c5e-b5bf-a99fb7a3ce25@a70g2000hsh.googlegroups.com> Message-ID: <eca5012c-65c6-4857-b135-104191a45056@r66g2000hsg.googlegroups.com> > But surely the idea behind it will eventually spread. ?It's really > just comprehensions generalized over XML and relational datasets, a > noble goal. ?Besides, it's main purpose for .NET was to bring > functional programming to it. ?Python already has that, somewhat... it's really any object out of the box, i think the sql linq stuff is more of a query compiler, IMO sqlalchemy does that. query = select(user_cols, and_(table_relationship.c.accept_user_id==user.id, table_relationship.c.start_date==None ), from_obj=join( table_relationship,table_user, onclause=table_user.c.id==table_relationship.c.init_user_id ).outerjoin(table_profile) ) session.execute(query).fetchall() XML? meh hopefully I would never need it. :) C# is my day job, and when I got my hands on LINQ back in January my initial thought was "Finally I have list comprehensions!!!! day job is fun again" For the most part, I think C# is catching up. From antonyjeeva007 at gmail.com Tue Sep 30 07:34:33 2008 From: antonyjeeva007 at gmail.com (michale angelo) Date: Tue, 30 Sep 2008 04:34:33 -0700 (PDT) Subject: GREAT WAY TO EARN $300 IN A SINGLE DAY.MOST LEGIBLE WAY TO MAKE MONEY Message-ID: <f8fd6cee-b8d6-4615-95ce-1102fefdf07f@r66g2000hsg.googlegroups.com> GREAT WAY TO EARN $300 IN A SINGLE DAY.MOST LEGIBLE WAY TO MAKE MONEY FROM ONLINE Your Opinion is Worth Gold To Big Business Network .Discover How to Make as Much Money as YouWant, Just By Having an Internet Connection,Some Spare Time, and an Opinion!?Your Opinion is Worth Gold To Big Business?and They?Ready to Pay You Right Now for Your Time! This Little-Known Way to Make Easy Money on the Internet isHelping Thousands of People Just Like You Achieve Their Dreams .check this link: http://tinyurl.com/4jkuwx LIFE CHANGING NETWORK WORK SINCERELY AND EARN AS MUCH AS YOU WANT From deets at nospam.web.de Mon Sep 15 15:40:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 21:40:03 +0200 Subject: environment variable issue In-Reply-To: <48ceb82a$0$2861$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> <mailman.1057.1221505773.3487.python-list@python.org> <48ceb82a$0$2861$ba620e4c@news.skynet.be> Message-ID: <6j7s0jF1t8ecU1@mid.uni-berlin.de> Michel Leunen schrieb: > Tim Chase a ?crit : > >> Your HOSTNAME variable hasn't been exported to subshells. You can >> check this by looking at the output of >> >> bash$ export -p >> >> which will print all the variables that are exported. I suspect >> you'll see $USER in the list, but not $HOSTNAME > > Actually HOSTNAME seems to be exported as well: > > $ export -p | grep HOSTNAME > declare -x HOSTNAME="LinuxPC" > > I don't know what to think of this but it's the beginning of an > explanation. Not on my machine, and *if* it is exported, python gets it. deets at absinth:~$ export -p | grep HOSTNAME deets at absinth:~$ export HOSTNAME deets at absinth:~$ export -p | grep HOSTNAME declare -x HOSTNAME="absinth" deets at absinth:~$ python -c "import os; print os.environ.get('HOSTNAME')" absinth deets at absinth:~$ Diez From marco.bizzarri at gmail.com Mon Sep 15 16:07:50 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 15 Sep 2008 22:07:50 +0200 Subject: MVC with Python In-Reply-To: <gamdkr$h54$1@ger.gmane.org> References: <gamdkr$h54$1@ger.gmane.org> Message-ID: <3f0d61c40809151307p76c864e5he9911593b676548e@mail.gmail.com> On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann <george at george-net.de> wrote: > Hello, > > I need some advice on how to implement model-view-controller. I am trying to > develop a GUI application with PyQt, yet the problem rather applies to mvc > in general, not just GUI applications. > > Let's say the data is a list of objects with a common base class. The views > are either a graphical representation of the objects or some form of textual > input. The views shall change the model by using command objects (for undo, > e.g. QUndoCommand). > > My current approach is to implement the model as a class with a list-like > interface, with methods insert(), remove(), __getitem__(), __setitem__(),... > and a signal to notify the views. The objects in the list have methods to > change their state as well. > > My problem is, how do the commands interact with the model? > Let's say I have a command that modifies an object o in the list. > > 1) If list[key_to_o] returns a reference to the object, the command can > modify the object by using this reference, i.e. list[key_to_o].setX(). So > there is no way for the list to know when the object changed - how can it > emit a singal then? > > 2) If list[key_to_o] returns a deep copy of the object, > copy_of_o = list[key_to_o], the command mofifies the copy and the updates > the list: list[key_to_o] = copy_of_o. Now the list can emit a signal in > __setitem__(). > While this may work, it seems awkward to copy around objects just to perform > a possibly simple operation on them. Additionally it might not be feasible > once objects get complex. > > 3) The interface of the classes of the objects could be reflected in the > list class, i.e. list.set_x_on_obj(key_to_obj,x). This would probably make > the list class interface very bloated. > > Of course the problem is not really limited to Python, my apologies if I'm > totally off-topic here. > > Regards > Georg > Well, I think one of the assumptions of the MVC is that the view can be notified about the changes in the model. According to your interface, the View can just be notified on operations about the *whole* model, like adding or removing elements from it. But the elements of your list-like class should be a part of your model, and therefore should be able to notify the Views by themselfves. Just my 0,02 Euros. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From pavlovevidence at gmail.com Thu Sep 4 16:16:44 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 13:16:44 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> <f1b92bb7-f960-4e56-b8be-240cfc301726@b38g2000prf.googlegroups.com> <a547e63a-7315-48fe-bb04-97902dbc879a@z6g2000pre.googlegroups.com> <b9a1a7f8-0f31-4197-bcc6-e51e9d82dea8@a18g2000pra.googlegroups.com> Message-ID: <86adbdeb-9051-4877-a998-a878d4904d81@a1g2000hsb.googlegroups.com> On Sep 4, 3:38 pm, bukzor <workithar... at gmail.com> wrote: > The point of using a mixin is to not limit myself to inheriting from > VanillaCursor. I want to put this on top of various subclasses of the > vanilla cursor, like TimeLimitedCursor or RetryingCursor. I have four > other mixins that operate this way, so it's desirable to keep this one > in line with that. http://www.bartleby.com/59/3/foolishconsi.html I think that desire is hurting you more than it's helping. It's fine to be consistent for consistency's sake, but you are taking consistency to an unhealthy extreme. A mixin is simply the wrong tool to do this with. My advice: either use a proxy, or manage your connections better. Carl Banks From dudeja.rajat at gmail.com Wed Sep 24 10:42:05 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Wed, 24 Sep 2008 15:42:05 +0100 Subject: problem updating variable in a module Message-ID: <e0b6c39a0809240742k7ef2e8cfi33f88d8169b17170@mail.gmail.com> Hi, I've a problem updating my variable in a module. In my main program, I call a function from mod1 to update a variable of mod1 As soon as I update this varibale, I check it back in the mail program but it the variable from mod1 does not get updated. main Program: **************** import mod1 a = 20 mod.update(a) print mod.a <---- does not print anything mod1 ******** a = 10 def update(someInt): global a a = someInt print a <---- this does actually print a = 20 Please help. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080924/bf3fee1e/attachment.html> From __peter__ at web.de Tue Sep 2 13:04:30 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Sep 2008 19:04:30 +0200 Subject: (in memory) database References: <d1104d4c-b894-46ed-9641-fcbcdc3661d0@26g2000hsk.googlegroups.com> <mailman.297.1220190030.3487.python-list@python.org> <5enqo5-9n9.ln1@lairds.us> <b68940e4-78cc-4fbb-94cd-69478d45f96c@26g2000hsk.googlegroups.com> <k33ro5-lqh.ln1@lairds.us> <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> <3e419475-61a1-4579-a8b6-fc15f9fe0a9b@m73g2000hsh.googlegroups.com> <f1312026-9450-483d-87e0-be9903f7f9e0@z11g2000prl.googlegroups.com> Message-ID: <g9jrmq$3h6$03$1@news.t-online.com> Zentrader wrote: >> I don't understand why Cameron has a different version of Python which >> doesn't seem to have sqlite support enabled. > > Agreed, but won't the package manager tell him if python-sqlite is > installed? That would be the next step since it appears that SQLite > intself is already installed. Since Ubuntu uses precompied binaries, > Python should be configured for SQLite which again leaves no python- > sqlite as the only possibility (yeah right). BTW Python is easy to > install manually. When you install Python manually from source you need the header files for sqlite3 to get sqlite3 support. These are in the libsqlite3-dev package. I think you can distinguish a manually installed python from the packaged one by the .../local/... in its path, e. g., on my machine $ which python2.5 # in the distribution /usr/bin/python2.5 $ which python2.6 /usr/local/bin/python2.6 # installed from source I have installed libsqlite3-dev so I can't reproduce Cameron's error, but here's a similar one for bsddb: $ python2.5 Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:43) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import bsddb >>> bsddb.__file__ '/usr/lib/python2.5/bsddb/__init__.pyc' $ python2.6 Python 2.6b2+ (trunk:65902, Aug 20 2008, 08:38:26) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import bsddb Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.6/bsddb/__init__.py", line 58, in <module> import _bsddb ImportError: No module named _bsddb Peter PS: Yes, I'm using 2.6, but I don't think that's relevant for the problem. From scottd at mcm.com Thu Sep 18 15:41:36 2008 From: scottd at mcm.com (Desmond Scott E) Date: Thu, 18 Sep 2008 15:41:36 -0400 Subject: Python, Factset, and Excel - Oh my! Message-ID: <04C6F615450E8D4A97EBA1DA9535667E064888@E2K3MAIL1515.mellonbank.com> I'm still a Python novice. I'm still attempting to migrate a Python-based process from Windows2000/Python v2.4.2 (#67)/Excel2000 to WindowsXP/Python v2.5.2 (r252:60911)/Excel2003. I now have a new "opportunity"! I need some help with the step in the Python script that calls Excel and invokes the Factset API to download data into a spreadsheet. I'm thinking that this is a Python / Factset API setup issue. Is the Factset API installed as a component of Python? Or does the Factset API exist in Windows and available to any application, like Python? Any insights would be greatly appreciated! Scott E. Desmond Director & Manager Equity Systems Development IT Integration Lead Mellon Capital Management Corporation 500 Grant Street, Suite 4200 Pittsburgh, PA 15258 T 412.236.0405 | F 412.236.1703 scottd at mcm.com | www.mcm.com The information contained in this e-mail may be confidential and is intended solely for the use of the named addressee. Access, copying or re-use of the e-mail or any information contained therein by any other person is not authorized. If you are not the intended recipient please notify us immediately by returning the e-mail to the originator.(16b) Disclaimer Version MB.US.1 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/9eec2a7b/attachment.html> From schaefer.mp at gmail.com Tue Sep 16 08:53:32 2008 From: schaefer.mp at gmail.com (MatthewS) Date: Tue, 16 Sep 2008 05:53:32 -0700 (PDT) Subject: Is 'x' an instance of a new-style class? References: <f568f4d9-b179-4ef1-9688-fcd8cb5ef641@d1g2000hsg.googlegroups.com> <mailman.1102.1221557922.3487.python-list@python.org> Message-ID: <739d438d-3631-4d06-8855-65097a5623aa@z66g2000hsc.googlegroups.com> On Sep 16, 11:38?am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS <schaefer... at gmail.com> ? > escribi?: > > > I've seen the question raised several times here, but apparently never > > answered. Since PyInstance_Check returns False for new-style class > > instances, is there a standard procedure for testing this using the C- > > Api? > > > I would greatly appreciate some help with this. > > In Python you would write isinstance(x, object). In C, "object" is ? > PyBaseObject_Type, and a direct translation would be ? > PyObject_IsInstance(x, PyBaseObject_Type), or perhaps ? > PyObject_TypeCheck(x, ?&PyBaseObject_Type) (to mimic how other PyXXX_Check ? > are implemented, and probably faster) > > -- > Gabriel Genellina Thanks Gabriel, the second solution seems to work based on my tests. So I have this now this test: static BOOL IsPythonInstance( PyObject * src ) { { // old style classes or instances or new style classes or instances if( ( PyInstance_Check( src ) ) || ( PyClass_Check( src ) ) || PyObject_TypeCheck( src, &PyBaseObject_Type) ) { return TRUE; } return FALSE; } } From steven at REMOVE.THIS.cybersource.com.au Wed Sep 10 06:24:29 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 10 Sep 2008 10:24:29 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> Message-ID: <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> On Wed, 10 Sep 2008 09:26:20 +0200, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> You've created a solution to a problem which (probably) only affects a >> very small number of people, at least judging by your use-cases. Who >> has a 4GB XML file > > Getting 4GB XML files from, say, logging processes or databases that can > render their output as XML is not that uncommon. They're usually > record-oriented, and are intended to be processed as streams. And given > the right tools, doing that is no harder than doing the same to a 4GB > text file. Fair enough, that's a good point. But would you expect random access to a 4GB XML file? If I've understood what Castironpi is trying for, his primary use case was for people wanting exactly that. -- Steven From Afro.Systems at gmail.com Wed Sep 10 15:33:56 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Wed, 10 Sep 2008 12:33:56 -0700 (PDT) Subject: Simple UDP server References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> <mailman.822.1221072987.3487.python-list@python.org> <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> <mailman.823.1221074511.3487.python-list@python.org> Message-ID: <fb4bd0c9-65c4-40a7-ae94-7ff781abdf1a@a70g2000hsh.googlegroups.com> > Transmitting large binary data over UDP? That makes only sense for few > applications like video and audio streaming. UDP does neither guarantee > that your data is received nor it's received in order. For example the > packages A, B, C, D might be received as A, D, B (no C). > > Can your protocol handle missing packages and out of order packages? I intend of using it for audio transmission and don't care about lose or out of order. From half.italian at gmail.com Tue Sep 30 00:44:19 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 29 Sep 2008 21:44:19 -0700 (PDT) Subject: PYTHON WORKING WITH PERL ?? References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> <20080929133153.fc745f9c.darcy@druid.net> <mailman.1695.1222717454.3487.python-list@python.org> Message-ID: <c9dc789a-34e1-43ba-ba0f-1c6a508d9a91@m45g2000hsb.googlegroups.com> On Sep 29, 12:44?pm, "Blubaugh, David A." <dbluba... at belcan.com> wrote: > Sir, > > You are absolutely correct. ?I was praying to G_d I did not have to > slaughter my project's source code in this manner. ?However, like life > itself, I was given legacy source code (i.e. someone else errors to fix) > in Perl. ?However, I have just found out that there is a way to import > the Perl interpreter within Python!!! ?I now believe I can utilize > python as the main platform to develop the project upon !! ? > > Thanks, > > David > > -----Original Message----- > From: D'Arcy J.M. Cain [mailto:da... at druid.net] > Sent: Monday, September 29, 2008 1:32 PM > To: Blubaugh, David A. > > Cc: python-l... at python.org > Subject: Re: PYTHON WORKING WITH PERL ?? > > On Mon, 29 Sep 2008 13:16:14 -0400 > "Blubaugh, David A." <dbluba... at belcan.com> wrote: > > I was wondering if it was possible to have a situation where a > > programming project would utilized BOTH python and perl? ?Such as > > utilizing python for internet programming and then utilize perl for > > text processing and systems programming? ?Is this even feasible??? > > I don't see why not but I also question if it is a good idea. ?Once you > have all your objects and low level methods written in Python it just > makes sense to re-use them rather than trying to duplicate the > functionality in another language. > > Of course, sometimes we don't have control over our entire environment > so yes, you can mix them if you have to. > Rewrite everything in python. Save yourself now...while you still can. ~Sean From rocksportrocker at googlemail.com Thu Sep 11 06:56:38 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 11 Sep 2008 03:56:38 -0700 (PDT) Subject: Extracing data from webpage References: <mailman.862.1221126931.3487.python-list@python.org> Message-ID: <89422ef8-9d09-47f7-9a35-20b0c7b8e4d9@s50g2000hsb.googlegroups.com> On 11 Sep., 11:55, srinivasan srinivas <sri_anna... at yahoo.co.in> wrote: > Hi, > I am trying to download data from a webpage. I use mechanize python module. > Could someone tell me how to set/pass an agent?like Mozilla or IE that we do in perl's WWW::Mechanize?? > > Thanks, > Srini > http://wwwsearch.sourceforge.net/mechanize/doc.html Greetings, Uwe From fredrik at pythonware.com Thu Sep 11 02:32:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 08:32:52 +0200 Subject: I want to use a C++ library from Python In-Reply-To: <1buzw9k4gimaf$.dlg@ostling.com> References: <i2gdjiu8ys7i.dlg@ostling.com> <6ipd53FrptpiU1@mid.uni-berlin.de> <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> <6ipr40Fr7kr2U1@mid.uni-berlin.de> <mailman.782.1221051245.3487.python-list@python.org> <1buzw9k4gimaf$.dlg@ostling.com> Message-ID: <gaae2k$vnh$1@ger.gmane.org> Anders Eriksson wrote: > I have looked (very briefly) at the three framework you mention but they > all need the source code of the C++? No, they need header files and an import library to be able to compile the bindings and link them to your DLL. Do you know enough about C/C++ build issues to be able to compile a C++ program against the given library? If you do, fixing the rest should be straightforward, since the binding is just another C++ program designed to be imported by Python. </F> From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 07:48:29 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 13:48:29 +0200 Subject: is decorator the right thing to use? In-Reply-To: <LESCk.1818$Pv5.481@edtnps83> References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> <48db50aa$0$3750$426a74cc@news.free.fr> <HoOCk.1756$Pv5.1315@edtnps83> <48dbc82e$0$1120$426a74cc@news.free.fr> <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> <nFQCk.1781$Pv5.1597@edtnps83> <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> <QKRCk.1801$Pv5.525@edtnps83> <1fc9b5c2-0e58-4b48-9352-4122986ce7ec@k13g2000hse.googlegroups.com> <LESCk.1818$Pv5.481@edtnps83> Message-ID: <48dccc08$0$3888$426a34cc@news.free.fr> Dmitry S. Makovey a ?crit : (snip) > I never used metaclasses before and > decorators seemed to be bit more straight-forward to me :) ..oh well. Don't be afraid !-) While it's true that they can be a bit confusing at first, metaclasses are just classes - whose instances happens to be classes themselves. And while you're certainly right to not jump on metaclasses *before* hanving spent a bit time thinking of other possible solutions, there's nothing wrong with using metaclasses when that's really what you need... From wuwei23 at gmail.com Tue Sep 2 23:31:34 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 2 Sep 2008 20:31:34 -0700 (PDT) Subject: MoinMoin: trouble after install References: <mailman.393.1220397429.3487.python-list@python.org> Message-ID: <20837f42-0132-4ffb-a9e3-4f90d0c43f70@p31g2000prf.googlegroups.com> On Sep 3, 9:16?am, "John [H2O]" <washa... at gmail.com> wrote: > I've installed MoinMoin easily enough, but i have two problems now. This is more of a MoinMoin issue than a Python one. You'll find a lot more support through the MoinMoin site: http://moinmo.in/ Especially: http://moinmo.in/MoinMoinQuestions http://moinmo.in/MoinMoinChat From san82moon at gmail.com Mon Sep 1 04:48:34 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:48:34 -0700 (PDT) Subject: how to find position of dictionary values References: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <5118fa5c-d868-4d74-936f-544ef82d8873@i24g2000prf.googlegroups.com> On Sep 1, 1:45 pm, Bruno Desthuilliers <bruno. 42.desthuilli... at websiteburo.invalid> wrote: > lee a ?crit : > > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, > > ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? > > It's quite simple (hint : read the FineManual(tm) for dict.items() and > list.index()), but 1/totally inefficient and 2/not garanteed to yield a > single value (what if 'dfsdf' happens to be also the 4th item of the > list bound to key 'address' ?). > > May I suggest you rethink your data structure instead ? What you have > here is obviously a collection of 'phno/email/name/address'records. > These records shouldn't be split across different objects. Assuming > 'phno' is a unique identifier for each record, a better data structure > would be: > > records = { > 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > # etc > > } > > This way, the lookup is as simple and efficient as possible. > > My 2 cents.... hi, i agree with u, my data strusture is not efficient. but all the records,viz...name,phno, email,address are all generated at runtime , when the user enters them. so how can i design my datastructure in that case? From fredrik at pythonware.com Mon Sep 15 16:32:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 22:32:18 +0200 Subject: append on lists In-Reply-To: <gamg4f$f54$1@online.de> References: <gamffv$qms$1@online.de> <mailman.1062.1221509879.3487.python-list@python.org> <gamg4f$f54$1@online.de> Message-ID: <gamgom$tmm$1@ger.gmane.org> Armin wrote: >>> just a dumb question. >>> >>> Let a = [1,2,3,4,5] >>> >>> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? >> >> yeah, that's a dumb question. > > yeah, that's a dumb answer. did you read your own post? I did. </F> From half.italian at gmail.com Mon Sep 29 01:59:10 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 28 Sep 2008 22:59:10 -0700 (PDT) Subject: Web programming in Python. References: <eb5978f8-e802-48d2-a61f-207c25ac7059@y21g2000hsf.googlegroups.com> <ace09154-e1c1-424e-875e-5193ae210b57@w7g2000hsa.googlegroups.com> Message-ID: <2afd3f2f-8b80-4a99-965a-6e27f7000055@r15g2000prh.googlegroups.com> On Sep 28, 4:51?pm, Kurda Yon <kurda... at yahoo.com> wrote: > 1. On my server (in my directory) I found "cgi-bin" subdirectory. > > 2. In the "cgi-bin" I have created a file "test.py". > > 3. In that file I put: > #!/usr/bin/python2.4 python > print "Hello, World!" > (I have checked, I have "/usr/bin/python2.4" directory.) > > 4. I give the following permissions to the "test.py": > -rwx---r-x > > 5. The "cgi-bin" directory has the following permissions: > drwx---r-x > > 6. In the "cgi-bin" I have created the ".htaccess" file which > contains: > Options +ExecCGI > AddHandler cgi-script .py > > And it still does not work! If I try to see the page by my browser I > see: > Internal Server Error > The server encountered an internal error or misconfiguration and was > unable to complete your request. > ... Your server logs are your friend. Check /var/log/httpd/error.log for errors. Have you loaded the modpython module in your httpd.conf? ~Sean From szabolcs.ferenczi at gmail.com Sun Sep 28 12:52:52 2008 From: szabolcs.ferenczi at gmail.com (Szabolcs Ferenczi) Date: Sun, 28 Sep 2008 09:52:52 -0700 (PDT) Subject: destructor not called References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> Message-ID: <2067c2f1-582d-43a1-857d-82900f83a2ee@d1g2000hsg.googlegroups.com> On Sep 28, 6:00?pm, Marcin201 <marcin... at gmail.com> wrote: > I have a class which uses a temporary directory for storing data. ?I > would like that directory to be removed when the class is no longer > used. ?I have tried removing the temporary directory from the class > destructor, however, it was never called. The RAII (Resource Acquisition Is Initialization) pattern is not applicable to Python since the language concept is not suitable for it. The __del__ is not a genuine destructor. In your case it might not be performed when you expected it because there were still references left around to the object. You must take care to break those references. However, you can apply the EAM (Execute Around Method) pattern in Python to achieve the same effect. You can apply the EAM pattern with help of the `with' statement: with Foo() as a: # work with `a' In this case you must implement methods __enter__ and __exit__ instead of __init__ and __del__. The method __enter__ must return an instance of Foo. You can achieve the same effect with try-finally block as well: a = Foo() try: # work with `a' finally: # make `a' remove directories Best Regards, Szabolcs From castironpi at gmail.com Tue Sep 16 22:44:36 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 19:44:36 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <cba00205-ee1c-4ee6-9914-c46c7f9c17a2@j22g2000hsf.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> Message-ID: <2cbfdce2-9203-4136-a274-bc7d19dc293a@y38g2000hsy.googlegroups.com> On Sep 16, 9:25?pm, Fett <FettMan... at gmail.com> wrote: > On Sep 16, 9:00 pm, "Aaron \"Castironpi\" Brady" > > > > <castiro... at gmail.com> wrote: > > On Sep 16, 8:50 pm, Fett <FettMan... at gmail.com> wrote: > > > > I am trying to find a wrapper to do linear programming within python. > > > I am using an ubuntu machine and I have apt-get'd lp_solve, which > > > works just fine. If someone knows of a wrapper that will work with > > > that that'd be great. > > > > I also heard that scipy has a wrapper, however, I can't find any > > > documentation on it, nor can I seem to find it with dir(). If anyone > > > knows where there is good documentation on this I would love to use > > > that (the more native to python the better imo). > > > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > > > openopt, and cvxopt. I can't seem to find any with enough > > > documentation to get me off the ground. Some I can't compile, some I > > > can't even find out how to compile. > > > > If anyone knows of an LP package (preferably with IP as well, like > > > lp_solve has), that interfaces well with python and has enough > > > documentation to get a dependency newb like myself off the ground that > > > would be great. > > > Google says: > > > about 254,000 for linear programming python. > > > Link 3 is: > > >http://wiki.python.org/moin/NumericAndScientific/Libraries > > > Scroll down. > > Yes, many of those seem to be deprecated, without destinations to > links, most are poorly or not documented at all. The few that are, I > still can't get running. Of those 254, I think I have tried at least > 10 pages worth. Still no luck. > > # lpsolvpy - Can't get it to compile - dependency problems. > # Lp_solve5 - NO python binding yet. Volunteers needed for python > bindings. > # pycplex - You need to compile the CPX.so module. Change the required > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > sure what to do here. > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > I missed the second link to the python bindings, looked all over the > glpk site for anything about python. > # SciPy --http://www.scipy.org- supposedly has this, but as I said, > I can't find any mention of it anywhere but on the site you linked. > # pySimplex - (broken link)(broken link) > # Simplex - link is broken, but nothing is mentioned > > I'll take a closer look at glpk's python bindings and if there is any > documentation on them, maybe I'll have some luck. btw, I have been > looking for something that works, I have over 5 packages on my desktop > that I have tried to get up and running, but none of them seem to > work. glpk makes 6. If you can find one working in C, use ctypes to link into Python. We can help you with that part. It lets you pass primitive types, structs, arrays, pointers, to C modules and return values. You need to know the C signatures to set up the Pythonized signatures. From bernhard.walle at gmx.de Tue Sep 30 12:00:16 2008 From: bernhard.walle at gmx.de (Bernhard Walle) Date: Tue, 30 Sep 2008 18:00:16 +0200 Subject: How to add CC and BCC while sending mails using python In-Reply-To: <46da4e770809300727j368a27b8qc570a8451a53e470@mail.gmail.com> References: <46da4e770809300727j368a27b8qc570a8451a53e470@mail.gmail.com> Message-ID: <20080930180016.604e9f52@kopernikus.site> Hi, * cindy jones [2008-09-30 19:57]: > > Can someone tel me how to add cc's and bcc's while sending mails using > python Following (tested) snippet should help: ------------------ 8< ------------------------------ from smtplib import SMTP from email.mime.image import MIMEImage from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart to = 'to_address at example.invalid' cc = 'cc_address at example.invalid' bcc = 'bcc_address at example.invalid' msg = MIMEMultipart() msg['To'] = to msg['Cc'] = cc msg['From'] = 'bernhard at bwalle.de' msg['Subject'] = 'Test' text = MIMEText('Das ist ein Test') text.add_header("Content-Disposition", "inline") msg.attach(text) s = SMTP('test.smtp.relay') s.sendmail(msg['From'], [to, cc, bcc], msg.as_string()) s.quit() ------------------ >8 ------------------------------ Regards, Bernhard From rsinger at ____.com Tue Sep 23 18:41:47 2008 From: rsinger at ____.com (Robert Singer) Date: Wed, 24 Sep 2008 00:41:47 +0200 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <eogid4d6s2a5l55pu20220sr2bdt5s6hob@4ax.com> <c3f6f232-4165-495b-b998-cc813eae57ea@f63g2000hsf.googlegroups.com> Message-ID: <4hrid45cb17q3pm48ppc3f7dh8eql92iq9@4ax.com> On Tue, 23 Sep 2008 13:34:10 -0700 (PDT), sturlamolden <sturlamolden at yahoo.no> wrote: >1. gfortran is not Absoft. I find this comment absurd. What did you mean by it ? Yes, gfortran is not Absoft, just as red is not blue (?!). I also don't understand whether you're looking for a free or a commercial compiler. I got the impression from your previous post that money was an object. >2. If I program the same in C99 and Fortran 95, and compile with gcc >and gfortran, the C99 code runs a lot faster (I've only tested with >wavelet transforms). Hmm. Unfortunatelly, i have none whatsoever experience in that field. Completely different area of study here, so without seeing at least some code, I cannot comment anything on that part. And 'a lot faster' is a very relative term. > >3. gfortran is not Absoft. > True. Best regards Bob From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 16:02:02 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 22:02:02 +0200 Subject: Late initialization using __getattribute__ In-Reply-To: <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> Message-ID: <48bf092a$0$14321$426a74cc@news.free.fr> bukzor a ?crit : (snip) > Thanks for the reply. Just to see it not work, I tried to remove > __getattribute__ from LateInitMixIn, but couldn't get it to work. ??? Sorry, I don't get what you mean... > My Base class is a C class (_mysql.connection from MySQLdb) that > sometimes segfaults if you try to use it before it's fully > initialized, Then don't use it before it's fully initialized. patient: "doctor, when I do this, it hurts" doctor : "then don't do it" !-) More seriously, I have used MySQLdb for years on more than a dozen linux distribs, and never had such a problem. Is this a known bug ? Or is there something wrong with your setup ? > so unfortunately I think I need to use __getattribute__ > to do this. I'm doing all this just to make the connection not > actually connect until used. I may be dumb, but I don't get how this is supposed to solve your problem. But anyway : there's a known design pattern for what you're trying to do, that doesn't require mixins nor messing with __getattribute__ (which, I repeat, is more often than not something you *don't* want to do). The name of the design pattern is "proxy". I strongly suggest that you 1/ try to cure the real problem instead of hacking around and 2/ read about the proxy design pattern. My 2 cents... From bearophileHUGS at lycos.com Fri Sep 5 11:26:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 08:26:25 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <g9r7hq$ri6$1$8302bc10@news.demon.co.uk> <dullrich-33A94E.10163805092008@text.giganews.com> Message-ID: <b4f287a7-8e1f-4057-9711-2f2519869a10@m73g2000hsh.googlegroups.com> David C. Ullrich: > I didn't mention what's below because it doesn't seem > likely that saying max([]) = -infinity and > min([]) = +infinity is going to make the OP happy... Well, it sounds cute having Neginfinite and Infinite as built-int objects that can be compared to any other type and are < of or > of everything else but themselves. Probably they can be useful as sentinels, but in Python I nearly never use sentinels anymore, and they can probably give some other problems... Bye, bearophile From timr at probo.com Mon Sep 1 00:26:48 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 01 Sep 2008 04:26:48 GMT Subject: parsing "&A" in a string.. References: <g9etqg$k7p$1@ger.gmane.org> <mailman.304.1220216809.3487.python-list@python.org> Message-ID: <mlrmb4t496nmbc84c2ud77fs2tt2fehbvk@4ax.com> "bruce" <bedouglas at earthlink.net> wrote: > >it's the beautifulsoup() that's taking the "&E" and giving the "&E;"... Right, as it should. "A&E" is not valid HTML, and beautifulsoup expects valid HTML. This can be difficult to fix in the general case, because your page might already contain "&". If it is possible that some of them might be wrong while some are right, you can do something like: s = s.replace( '&', '&' ).replace( '&', '&' ) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Mon Sep 29 18:52:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 18:52:40 -0400 Subject: Source code for python nativ methods and classes In-Reply-To: <257224ff0809291400t1611aa6cm1b033b539392f353@mail.gmail.com> References: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> <257224ff0809291400t1611aa6cm1b033b539392f353@mail.gmail.com> Message-ID: <gbrm7m$scj$1@ger.gmane.org> Bard Aase wrote: > On Mon, Sep 29, 2008 at 10:51 PM, Mohed <mohed at hotmail.com> wrote: >> Hello. >> I am interrested in seeing the source code for all the nativ builtin >> methods and clases in python. Is there a webpage that lists them or is >> this done easier some other way. > > Check it out from svn? > svn co http://svn.python.org/projects/python/trunk/ > > or browse the code at http://svn.python.org/view/python/trunk/ This has the code for the upcoming 2.6 release. For other branches http://svn.python.org/view/python/branches/ in particular py3k or release25-maint. Built-in classes are in the Objects sub-directory. (But there is a bit of math in the Python sub-dir). Built-in modules are in the Modules sub-directory. Python-coded modules are in the Lib sub-directory. I don't know where the built-in functions are. To see the current state of a file, click on the revision number in the second column. Clicking on the name in the first column give a rather strange change log that goes forward through each year as it goes back through the years. Terry Jan Reedy From rocksportrocker at googlemail.com Fri Sep 26 11:19:04 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Fri, 26 Sep 2008 08:19:04 -0700 (PDT) Subject: lxml question Message-ID: <2f9ef7d5-616e-4a4b-9a83-e23194fee3a9@m3g2000hsc.googlegroups.com> Hi, I have to parse some text which pretends to be XML. lxml does not want to parse it, because it lacks a root element. I think that this situation is not unusual, so: is there a way to force lxml to parse it ? My work around is wrapping the text with "<root>...</root>" before feeding lxmls parser. Greetings, Uwe From samslists at gmail.com Tue Sep 16 20:58:31 2008 From: samslists at gmail.com (Sam) Date: Tue, 16 Sep 2008 17:58:31 -0700 (PDT) Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <mailman.766.1221033019.3487.python-list@python.org> Message-ID: <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> Gabriel, et al. It's hard to find a web site that uses deflate these days. Luckily, slashdot to the rescue. I even wrote a test script. If someone can tell me what's wrong that would be great. Here's what I get when I run it: Data is compressed using deflate. Length is: 107160 Traceback (most recent call last): File "my_deflate_test.py", line 19, in <module> data = zlib.decompress(data) zlib.error: Error -3 while decompressing data: incorrect header check And here's my test script: #!/usr/bin/env python import urllib2 import zlib opener = urllib2.build_opener() opener.addheaders = [('Accept-encoding', 'deflate')] stream = opener.open('http://www.slashdot.org') data = stream.read() encoded = stream.headers.get('Content-Encoding') if encoded == 'deflate': print "Data is compressed using deflate. Length is: ", str(len(data)) data = zlib.decompress(data) print "After uncompressing, length is: ", str(len(data)) else: print "Data is not deflated." On Sep 10, 12:50?am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Tue, 09 Sep 2008 16:38:54 -0300, Sam <samsli... at gmail.com> escribi?: > > > Un-deflating doesn't work. ?I get "zlib.error: Error -3 while > > decompressing data: incorrect header check" > > zlib.decompress should work - can you provide a site that usesdeflateto ? > test? From CapnBearbossa at googlemail.com Mon Sep 22 17:31:24 2008 From: CapnBearbossa at googlemail.com (CapnBearbossa at googlemail.com) Date: Mon, 22 Sep 2008 14:31:24 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? Message-ID: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> hi all, forgive me , but the RTFM and Google search approaches are not yielding an answer on this question. I need to know if there's a top level python interpreter command that clears all user variables (not built-ins) from the global namespace. In other words a statement, or some_command_or_function(), that does this: >>> x=3 >>> y=4 >>> z=[] >>> dir() ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] >>> some_command_or_function() >>> dir() ['__builtins__', '__doc__', '__name__'] thanks, 1 desperate snake oil programmer .... From fredrik at pythonware.com Wed Sep 3 14:36:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Sep 2008 20:36:42 +0200 Subject: Is try-except slow? In-Reply-To: <8b3857ec-e629-44a3-98f2-8fe509df7b75@f36g2000hsa.googlegroups.com> References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> <8b3857ec-e629-44a3-98f2-8fe509df7b75@f36g2000hsa.googlegroups.com> Message-ID: <g9mlfq$isa$1@ger.gmane.org> process wrote: > is this faster btw? I guess big doesn't help, it's only retrieved once > anyway? But is rows retrieved in every loop? the python interpreter > aint too smart? > > def getPixels(fileName): > im = PIL.Image.open(fileName) > colors = [] > r, c = im.size > big = range(0, c) > rows = range(0, r) > for y in big: > row = [] > for x in rows: > color = im.getpixel((x,y)) > row.append(color) > colors.append(row) > return numpy.array(colors) you'd probably get more done if you read the replies you get a bit more carefully. Robert Kern suggesting using numpy.asarray earlier: def getPixels(fileName): im = PIL.Image.open(fileName) return numpy.asarray(im) if you want to work with pixels on the Python level, use im.getdata() or the pixel access object returned by im.load(). </F> From castironpi at gmail.com Sun Sep 14 15:21:54 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 14 Sep 2008 12:21:54 -0700 (PDT) Subject: Abstract class References: <mailman.1008.1221408214.3487.python-list@python.org> <roy-9FFFBD.13564414092008@news.panix.com> <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <mailman.1012.1221419718.3487.python-list@python.org> Message-ID: <64670149-9467-4ca7-9d7e-c330c1b403e4@c58g2000hsc.googlegroups.com> On Sep 14, 2:15?pm, Gary Herron <gher... at islandtraining.com> wrote: > Mr.SpOOn wrote: > > Gary Harron: > > >> I believe you are mixing up class *inheritance* and *abstract* classes. > > >> Class inheritance (with Python has has for years) is how one class inherits >behavior/properties/attributes from another class. ?The class being inherited from is >called the base class. ?This is probably what you want. > > > Well, I know the difference between an abstract class and an inherited > > one. The idea was to create a main class Note, with abstract methods, > > and implement these methods in the other classes. > > > On Sun, Sep 14, 2008 at 7:56 PM, Roy Smith <r... at panix.com> wrote: > > >> What properties or behaviors does SharpNote have which NaturalNote doesn't? > >> Unless there is some new behavior, you don't need subclasses. > > > Well, from a SharpNote I can obtain the relative NaturalNote. So if I > > have a C# I can call > > > natural('C#') ?and get 'C' > > > While in the class NaturalNote I don't need such a method, but I need > > two methods to get the sharped and flatted version > > >> Are you also going to have DoubleSharpNote and DoubleFlatNote? > > > Yes, that's an option. > > >> Consider the following code: > > >> note1 = SharpNote("E4") > >> note2 = NaturalNote("F4") > >> if note1 == note2: > >> ? print "the same note" > >> else > >> ? print "different notes" > > >> what should it print? > > > Well, that's not so simple. The idea is that I use a notation (A, B, > > C, D...) and an integer (a distance expressed in semitones) to > > identify a note. > > > Anyway, I think I need an abstract class. Or not? > > No! ?Definitely not! ? ?You need inheritance of a class from a base > class. ? Just brainstorming with you. You can support operations on the objects: note minus note = interval, note plus interval = note, and so on. (WARNING! Spoilers. Untested.) note1 = NaturalNote("G") note2 = NaturalNote("C") interval= note1- note2 print interval : <MajorInterval '5th'> note1 = SharpNote("G") note2 = NaturalNote("C") interval= note1- note2 print interval : <MinorInterval '6th'> WholeStep= MajorInterval( 2 ) print WholeStep : <MajorInterval '2nd'> note1 = NaturalNote("C") print note1- WholeStep : <FlatNote("B")> However, from what I understand (brass player), there are some cases in which you'll want that to be: print note1- WholeStep : <SharpNote("A")> What do you want to determine that? What about a KeyOf class? key= KeyOf( NaturalNote( "F" ) ) #'key' has special subclasses note1 = key.NaturalNote("C") print note1- WholeStep : <FlatNote("B")> key= KeyOf( SharpNote( "G" ) ) note1 = key.NaturalNote("C") print note1- WholeStep : <SharpNote("A")> Further, perhaps you want a 'WrittenNote' class which refers to the key signature it's written in: key= KeyOf( NaturalNote( "F" ) ) note1 = key.WrittenNote("B") print note1 : <FlatNote("B")> I do not immediately see how to represent clefs and staves: whether you'll need them at all, or whether they're just writing/rendering techniques. As for scales and chords, are there any special methods you want on them, or would a tuple of Note instances suffice? triad= ( NaturalNote( "C" ), NaturalNote( "E" ), NaturalNote( "G" ) ) One special method might be: triad= Triad( NaturalNote( "C" ), NaturalNote( "E" ), NaturalNote( "G" ) ) print triad : <C-Major triad> triad= Triad( NaturalNote( "E" ), NaturalNote( "G" ), NaturalNote( "C" ) ) print triad : <C-Major triad 1st inversion> I forgot about octaves, which can complicate the constructors. octave= Octave( 4 ) #middle C triad= Triad( octave.NaturalNote( "E" ), octave.NaturalNote( "G" ), octave.up.NaturalNote( "C" ) ) print triad : <C-Major triad 1st inversion> Or: octave= Octave( 4 ) triad= Triad( NaturalNote( "E", octave ), NaturalNote( "G", octave ), NaturalNote( "C", octave.up ) ) print triad : <C-Major triad 1st inversion> And abbreviate the name for the interval. octaveint= MajorInterval( 8 ) Abstract scales can be a tuple of intervals, where concrete scales are a tuple of notes. majorscale= ( Tonic, WholeStep, WholeStep, HalfStep, WholeStep, WholeStep, WholeStep, HalfStep ) majorCscale= [ NaturalNote( "C" )+ x for x in majorscale ] majorDscale= [ NaturalNote( "D" )+ x for x in majorscale ] To get a little more creative, you could just denote sharps and flats with a parameter: note1 = Note("G", sharp) #Or: note1 = Note("G", Note.sharp) note2 = Note("C") interval= note1- note2 print interval : <MinorInterval '6th'> It would just take some 'parameter magic' to interpret them right when paired with octaves: octave= Octave( 4 ) #middle C note1= Note( "C", sharp, octave ) note2= Note( "C", octave ) note3= Note( "C", octave, sharp ) note4= Note( "C", sharp ) That part just takes a little untwisting. (Untested.) class Note: defaultoctave= 4 def __init__( self, *args ): octave= Octave( self.defaultoctave ) accidental= Natural( ) for arg in args: if issubclass( arg, Accidental ): accidental= arg elif issubclass( arg, Octave ): octave= arg elif type( arg ) is str: name= arg Or use keywords to specify. octave= Octave( 4 ) #middle C note1= Note( "C", sharp, octave ) note2= Note( "C", octave= octave ) note3= Note( "C", octave= octave, accidental= sharp ) note4= Note( "C", sharp ) class Note: defaultoctave= 4 def __init__( self, name, octave= None, accidental= Natural( ) ): if octave is None: octave= self.defaultoctave It's open to debate whether Natural is a subclass or instance of Accidental. From bj_666 at gmx.net Sun Sep 7 18:02:04 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2008 22:02:04 GMT Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <6ij1asFqp39rU3@mid.uni-berlin.de> On Sun, 07 Sep 2008 14:51:32 -0700, andyhume at gmail.com wrote: > MAPPING_DICT = { > 'a': 'A', > 'b': 'B', > } > > my_dict = { > 'a': '1', > 'b': '2' > } > > I want the finished my_dict to look like: > > my_dict = { > 'A': '1', > 'B': '2' > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? You only have to loop through `my_dict`: In [187]: %cpaste Pasting code; enter '--' alone on the line to stop. :MAPPING_DICT = { : 'a': 'A', : 'b': 'B', :} : :my_dict = { : 'a': '1', : 'b': '2' :} :-- In [188]: dict((MAPPING_DICT[k], v) for k, v in my_dict.iteritems()) Out[188]: {'A': '1', 'B': '2'} Ciao, Marc 'BlackJack' Rintsch From dblubaugh at belcan.com Sat Sep 20 15:07:12 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Sat, 20 Sep 2008 15:07:12 -0400 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> <gb3bvk$9a1$1@ger.gmane.org> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38051C09F2@AWMAIL04.belcan.com> Sir, Let me state that do have extensive experience with developing binary files. Please note that I have followed all of the instructions to the letter as far as developing a DLL to be imported. However, it is not working correctly. I believe it might be my system environment variables?? Thanks for your reply, David Blubaugh ________________________________ From: Fredrik Lundh [mailto:fredrik at pythonware.com] Sent: Sat 9/20/2008 1:30 PM To: python-list at python.org Subject: Re: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py Blubaugh, David A. wrote: (no need to shout when filling in the subject line, thanks) > I have now been able to generate a .pyd file from a FORTRAN > file that I am trying to interface with python. I was able > to execute this with an additional insight into how f2py > operates. > > ImportError: DLL load with error code 193 Error code 193 is ERROR_BAD_EXE_FORMAT, which means that the thing you're trying to import is not a proper DLL. > copy LICENSE.txt LICENSE.pyd 1 file(s) copied. > python >>> import LICENSE Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: DLL load failed with error code 193 In general, the tools for building binary extensions for Python assumes that you have at least some basic knowledge about how to build binaries using a compiled language. </F> This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From sjmachin at lexicon.net Mon Sep 29 21:59:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Sep 2008 18:59:21 -0700 (PDT) Subject: pyXLWriter warnings References: <pkn2e41apdn6ns32stlt7u2ppa3pr0senl@4ax.com> Message-ID: <531ba624-3106-4999-baf8-643d1411ae4a@x41g2000hsb.googlegroups.com> On Sep 30, 9:09?am, Robert Singer <rsinger at ____.com> wrote: > Platform: winXP, excel 2003 > Python 2.5.2 > XLWriter 0.4a3 (http://sourceforge.net/projects/pyxlwriter/) > > Is anyone here using this very nice package, for writing excel files? > I'm using it on python 2.5.2. (although it is made for older version > of python) and cannot find a way to get rid of this error (code and > errors below). > > Does anyone know how to avoid it ? I would appreciate all help and > ideas you can think of. > > Bob > -------- > > >>> import pyXLWriter as xl > >>> workbook = xl.Writer("test.xls") > >>> worksheet = workbook.add_worksheet('first') > >>> worksheet.write([3,3], "Hello doc !") > >>> worksheet.write_comment([3,3], "I'm hunting for a wabbit") > 0 > >>> workbook.close() > > -------- > Warning (from warnings module): > ? File "C:\Python25\lib\site-packages\pyXLWriter\OLEWriter.py", line > 135 > ? ? unknown3 = pack("<H", -2) > DeprecationWarning: struct integer overflow masking is deprecated > > Warning (from warnings module): > ? File "C:\Python25\lib\site-packages\pyXLWriter\OLEWriter.py", line > 135 > ? ? unknown3 = pack("<H", -2) > DeprecationWarning: 'H' format requires 0 <= number <= 65535 [big snip of similar messages] There is not much point in working on pyXLWriter source; the package is abandonware ** 2. Although I can't find it now, I recall reading a recommendation from its author (Evgeny Filatov) that its users migrate to pyExcelerator. Unfortunately pyExcelerator has not been maintained for some time now. However Chris Withers of Simplistix and I have created xlwt, a fork of pyExcelerator; Chris is hosting the SVN repo and I am maintaining it. We now have a public release out of the door (http://pypi.python.org/pypi/xlwt/). There is only one task remaining AFAIK to meet the initial goal of providing the equivalent of (pyExcelerator last released version + all sensible patches included + all known [and several unknown] bugs fixed + an easier way of specifying cell formatting ("easyxf")) -- this is support for 3D references i.e. to other worksheets in the same workbook. Christophe Tronche has adapted Ruben Mendes' pyExcelerator patch to xlwt, and it's currently undergoing testing. You may like to check out the python-excel newsgroup at http://groups.google.com/group/python-excel ... HTH, John From lists at cheimes.de Tue Sep 9 13:56:18 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 09 Sep 2008 19:56:18 +0200 Subject: PYTHONSITEDIR environment variable In-Reply-To: <eccd24ff-001b-4f4e-a9da-c7052d67383d@k30g2000hse.googlegroups.com> References: <eccd24ff-001b-4f4e-a9da-c7052d67383d@k30g2000hse.googlegroups.com> Message-ID: <ga6dc2$bh7$1@ger.gmane.org> ago wrote: > Wouldn't it be possible to support a PYTHONSITEDIR environment > variable in site.py for this purpose? I have attached a possible > patch. In what follows, if PYTHONSITEDIR is defined, that dir is used > as the only source of site-packages, extra paths can easily be added > by creating a .pth file in there. A different variable could be used > to prepend a sitedir to the list of default sitedirs (similar code > without "return None"). I had a similar idea, wrote a PEP and implemented it for 2.6 and 3.0: http://www.python.org/dev/peps/pep-0370/ Christian From Lie.1296 at gmail.com Sun Sep 28 15:06:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 12:06:56 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <dd7c5e64-f856-45e5-a17c-28d52f02a4c3@a18g2000pra.googlegroups.com> On Sep 29, 1:29?am, process <circularf... at gmail.com> wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. > > What is not an object in Python? > > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? A question like this is often answered by another (rhetorical) question: "What is Object Oriented actually?" The answer to that is generally: "Python is not Java." From fredo66 at fulladsl.be Thu Sep 25 04:24:47 2008 From: fredo66 at fulladsl.be (fredo66 at fulladsl.be) Date: Thu, 25 Sep 2008 01:24:47 -0700 (PDT) Subject: python sorting 2dim. array ? References: <9684e81b-df99-4d95-99f9-8345c125b69b@d77g2000hsb.googlegroups.com> Message-ID: <80dca060-31de-492a-ae1d-fccd69cdedd9@m45g2000hsb.googlegroups.com> remark: The server is using python server version 2.3.4 From bdesth.quelquechose at free.quelquepart.fr Mon Sep 22 15:38:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 21:38:30 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> <48d78c3c$0$6998$426a74cc@news.free.fr> <mailman.1360.1222091143.3487.python-list@python.org> <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> Message-ID: <48d7f46d$0$15502$426a74cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : > On Sep 22, 8:45 am, "Tim Rowe" <digi... at gmail.com> wrote: >> 2008/9/22 Bruno Desthuilliers <bruno.42.desthuilli... at websiteburo.invalid>: >> >>>> Sounds to me like a functor, aka a function object: >>>> http://en.wikipedia.org/wiki/Function_object >>> Ok, then the simple solution is to implement a callable type (__call__ >>> method), possibly with appropriate support for the descriptor protocol if >>> it's meant to be usable as a method. >> Yes -- and instantiate the thing and keep the state in the instance, >> rather than keeping the state in the class, so that it's possible to >> safely have more than one of them if a later design change calls for >> it (probably what led people off onto the sidetrack of thinking a >> singleton was called for). That's the classic way of implementing a >> "class [to be] used as a function". >> >> -- >> Tim Rowe > > I think you are either looking for a class that has a generator, or a > generator that has a reference to itself. ??? Going back to robot-mode, Aaron ? From mr.spoon21 at gmail.com Sun Sep 14 12:03:23 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 14 Sep 2008 18:03:23 +0200 Subject: Abstract class Message-ID: <8f67b6f80809140903x2e2a8cfav7745113d9bcab650@mail.gmail.com> Hi, I'm going to work on a project to represent some musical theory in Python, in an object oriented way. I have to manage many elements of music such as notes, intervals, scales, chords and so on. All these elements share properties and behavior, so what I want to do is an abstract class "Note" and other subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. The idea is not original, I read it in some papers where they talk about an implementation in smalltalk. I want to use Python (of course) and I'd like to know what is the practice in such a case. I mean, in python there aren't abstract classes, but I read about some way to emulate the same behavior. What do you suggest me? Thanks, Carlo From san82moon at gmail.com Mon Sep 1 06:51:13 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 03:51:13 -0700 (PDT) Subject: how to find position of dictionary values References: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> <48bbab73$0$27858$426a34cc@news.free.fr> <e9b3e12c-3834-48ff-911b-baf01efdb8c3@r15g2000prh.googlegroups.com> <6i1rgcFo0f1gU1@mid.uni-berlin.de> Message-ID: <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> On Sep 1, 2:37 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > lee wrote: > > On Sep 1, 1:45 pm, Bruno Desthuilliers <bruno. > > 42.desthuilli... at websiteburo.invalid> wrote: > >> lee a ?crit : > > >> > hi, > >> > i have a dictionary as follows : > >> > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > >> > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > >> > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > >> > if user is enters the 3rd item of key phno, > >> > ie "dfsdf" in my dict, > >> > how can i find it is the third item in the internal list of phno of > >> > that dictionary? > > >> It's quite simple (hint : read the FineManual(tm) for dict.items() and > >> list.index()), but 1/totally inefficient and 2/not garanteed to yield a > >> single value (what if 'dfsdf' happens to be also the 4th item of the > >> list bound to key 'address' ?). > > >> May I suggest you rethink your data structure instead ? What you have > >> here is obviously a collection of 'phno/email/name/address'records. > >> These records shouldn't be split across different objects. Assuming > >> 'phno' is a unique identifier for each record, a better data structure > >> would be: > > >> records = { > >> 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > >> 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > >> # etc > > >> } > > >> This way, the lookup is as simple and efficient as possible. > > >> My 2 cents.... > > > hi, > > i agree with u, my data strusture is not efficient. but all the > > records,viz...name,phno, email,address are all generated at runtime , > > when the user enters them. so how can i design my datastructure in > > that case? > > Are "u" short on keystrokes? You are not textmessaging here... > > Regarding the actual question: there is no difference in building your or > the other structure. It's only a question of which key you use first. > Instead of first looking up the type of the record ("phno" or some such), > do that with the name of the user. If no record exists, create one. Then > populate the record with the user's values. Like this: > > user = "dsdf" > phonenumber = "123" > > record = records.setdefault(user, {}) > record["phno"] = phonenumber > > Diez i am soory for that keystrokes. can anyone tell me how can i change the value of key. suppose i have a dictionary kev = {'kabir': ['kabir at kabir.com', '1234', 'missuri'], 'shri': ['shri at shri.com', '23423', 'india'], 'marsa': ['marsa at marsa.com', '2345', 'brazil'], 'sandeep': ['sandeep at sandeep.com', '007', 'canada']} how can i change the key to something like 'sabir' and how can i change the values of kabir? From larry.bates at vitalEsafe.com Tue Sep 16 15:18:45 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 16 Sep 2008 14:18:45 -0500 Subject: new style classes, __new__, __init__ In-Reply-To: <gap0g2$l4c$1@news.LF.net> References: <gap0g2$l4c$1@news.LF.net> Message-ID: <ACTzk.30565$kh2.7108@bignews3.bellsouth.net> Torsten Mohr wrote: > Hi, > > i have some questions related to new style classes, they look > quite useful but i wonder if somebody can give me an example > on constructors using __new__ and on using __init__ ? > > I just see that when using it i can't give parameters to __new__ > and when i additionally define __init__ then __new__ is not > called. > > So i can use __new__ only for classes whose constructors don't > have parameters? > > > class C2: > def __new__(self): > print "new called" > self.a = 8 > > def __init__(self, a): > print "init called" > self.a = a > > def fct(self): > print self.a > > > a = C2(7) > a.fct() > > > This way __new__ is not called, if i remove __init__ then > there are too many parameters to __new__, if i add a parameter > to __new__ then it says that __new__ does not take arguments. > > > Thanks for any hints, > Torsten. > New style classes should be based on object: class C2(object): -Larry From clp at rebertia.com Mon Sep 15 20:08:30 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Sep 2008 17:08:30 -0700 Subject: append on lists In-Reply-To: <00dee3f7$0$20331$c3e8da3@news.astraweb.com> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <mailman.1072.1221511698.3487.python-list@python.org> <00dee3f7$0$20331$c3e8da3@news.astraweb.com> Message-ID: <47c890dc0809151708q4ca3fc44ja0efab8c181ea8b8@mail.gmail.com> On Mon, Sep 15, 2008 at 4:03 PM, Steven D'Aprano <steve at remove-this-cybersource.com.au> wrote: > On Mon, 15 Sep 2008 13:47:53 -0700, Chris Rebert wrote: > >> The code you'd actually want is: >> >> d = a[:] #copy a >> d.append(7) >> >> Or if you're willing to overlook the inefficiency: >> >> d = a + [7] >> >> But that's not idiomatic. > > Why is a + [7] more inefficient than manually copying the list and > appending to the copy? Surely both pieces of code end up doing the same > thing? > > In fact, I'd guess that the second is likely to be marginally more > efficient than the first: > > >>>> x = compile('d = a[:]; d.append(7)', '', 'exec') >>>> dis.dis(x) > 1 0 LOAD_NAME 0 (a) > 3 SLICE+0 > 4 STORE_NAME 1 (d) > 7 LOAD_NAME 1 (d) > 10 LOAD_ATTR 2 (append) > 13 LOAD_CONST 0 (7) > 16 CALL_FUNCTION 1 > 19 POP_TOP > 20 LOAD_CONST 1 (None) > 23 RETURN_VALUE > >>>> x = compile('d = a + [7]', '', 'exec') >>>> dis.dis(x) > 1 0 LOAD_NAME 0 (a) > 3 LOAD_CONST 0 (7) > 6 BUILD_LIST 1 > 9 BINARY_ADD > 10 STORE_NAME 1 (d) > 13 LOAD_CONST 1 (None) > 16 RETURN_VALUE > > > timeit agrees with me: > >>>> from timeit import Timer >>>> t1 = Timer('d = a[:]; d.append(7)', 'a = []') >>>> t2 = Timer('d = a + [7]', 'a = []') >>>> t1.repeat(number=1000) > [0.0015339851379394531, 0.0014910697937011719, 0.0014841556549072266] >>>> t2.repeat(number=1000) > [0.0011889934539794922, 0.0013048648834228516, 0.0013070106506347656] > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > Sorry, I was just speculating based on the extraneous list ([7]) used in the second one. My bad. :) Regards, Chris -- Follow the path of the Iguana... http://rebertia.com From fredrik at pythonware.com Tue Sep 2 13:25:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Sep 2008 19:25:06 +0200 Subject: Numeric literal syntax In-Reply-To: <6i56cpFor2puU1@mid.individual.net> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <pan.2008.09.02.06.10.51@REMOVE.THIS.cybersource.com.au> <6i56cpFor2puU1@mid.individual.net> Message-ID: <g9jsti$uf0$2@ger.gmane.org> Peter Pearson wrote: > (startled noises) It is a delight to find a reference to > that half-century-old essay (High Finance) by the wonderful > C. Northcote Parkinson, but how many readers will catch the > allusion? anyone that's been involved in open source on the development side for more than, say, ten minutes. http://www.bikeshed.com/ </F> From tchendrix at gmail.com Tue Sep 23 08:54:30 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 05:54:30 -0700 (PDT) Subject: finding domain name References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> <mailman.1404.1222174222.3487.python-list@python.org> Message-ID: <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> > Depends on the technology/web framework. If you use WSGI, you should use > something like: > > host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] > > -- Gerhard Yeah i already tried environ("SERVER_NAME") but get a key error when i do. From code at pizzashack.org Tue Sep 2 11:39:09 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 11:39:09 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i4v26Fol29aU4@mid.uni-berlin.de> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> Message-ID: <20080902153909.GQ29228@dragontoe.org> On Tue, Sep 02, 2008 at 01:57:26PM +0000, Marc 'BlackJack' Rintsch wrote: > > I would argue that they don't represent processes at all; the object is > > a set of files which connect the standard I/O streams of a subprocess to > > its parent, and methods to operate on those files. > > And the process' ID, an attribute with the process' return code, a method > to wait until the process is finished and file objects to communicate > with the process. The name popen is an abbreviation of "pipe open" -- the function, and the class, open pipes to communicate with another process. What you said is correct; however there are numerous other ways to open subprocesses. The focus of popen is the communication aspect -- the opening and control of the pipes -- not the subprocess. That's the key difference between popen() and all the other methods of starting a subprocess. > > The C library's popen() function, on which this class is based, > > provides a means to open a file and connect it to the standard steams > > of a subprocess, making it more closely analogous to what the Popen > > class does/provides. As such, "Popen" is a better name to describe > > this object than "subprocess" would be. > > Is strongly disagree. The class provides an interface to start and > communicate with a `Subprocess`. Instances stand for processes. There's more than one way to look at it. You can disagree all you like, but your interpretation disagrees with the historical intent of popen. > With your reasoning the `file` type should be called `open`. In this case, the file is a pipe, and the 'p' in popen represents the pipe. Unix, by and large, doesn't care that it's a pipe -- file I/O is intended to work the same way regardless of whether it's a pipe, a socket, a file on disk, a special device file, or any other file-like object you can imagine. That's why I said "file" instead of "pipe" in my explanation. Note that in all of these links that talk about popen, the focus is on opening pipes or file objects, not on subprocesses: http://www.opengroup.org/onlinepubs/009695399/functions/popen.html http://docs.python.org/lib/os-newstreams.html http://us3.php.net/popen http://docs.hp.com/en/B9106-90010/popen.3S.html http://www.faqs.org/docs/artu/ch07s02.html The Linux man page unfortunately copies (verbatim) the FreeBSD man page, which gets it wrong. You can not open a process, but you can definitely open a pipe. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/8221f22e/attachment.sig> From mike at myqs.net Fri Sep 5 07:39:39 2008 From: mike at myqs.net (Michael Wronna) Date: Fri, 05 Sep 2008 13:39:39 +0200 Subject: path slashes cleaning References: <mailman.484.1220534735.3487.python-list@python.org> <e815a0ed-f42e-4c60-8911-46de4f1169f0@t1g2000pra.googlegroups.com> Message-ID: <op.ug0aodfijqj4d0@mill.zuhause.kn> Am 04.09.2008, 15:27 Uhr, schrieb Mike Driscoll <kyosohma at gmail.com>: > On Sep 4, 8:25?am, "Mathieu Prevot" <mathieu.pre... at gmail.com> wrote: >> Hi, >> >> for scripts that take arguments, I would like to remove the trailing >> slash if it's present. >> >> Is there something else than: >> >> a='/usr/local/lib/' >> if a[-1] == '/': >> ? a = list(a) >> ? a.pop() >> ? ''.join(a) >> >> Thanks, >> Mathieu > > How about this: > > if a[-1] == '/': > a = a[:-1] > > Mike Hi, how about a.rstrip('/') ? Michael From python-url at phaseit.net Tue Sep 9 16:24:32 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 9 Sep 2008 20:24:32 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 9) Message-ID: <ga6m20$f60$1@lairds.us> QOTW: "So why am I supposed to care about SOAP again? Oh yes, the wizards I can use to generate 'web service end-points' from programming language code. My years in the SOAP trenches just makes me laugh myself half to death at that notion: I would probably have been twice as productive if every time I reached for a SOAP toolkit I instead just coded straight XML in HTTP. And this represents experience with Python, Java and C WS tools." - Uche Ogbuji How to cancel instance creation given certain conditions: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7083ed99c5237485 Implement a dictionary with case-insensitive keys: http://groups.google.com/group/comp.lang.python/browse_thread/thread/90a7e967d0bd1e0f/ The behavior of hash(): http://groups.google.com/group/comp.lang.python/browse_thread/thread/6c2d5030a833858f/ A generic attempt to add "verbosity" to scripts: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c2fa072005c9aaba/ max() and sum() applied to empty sequences, or those containing None, and how these differ from their SQL counterparts: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f4b98d6fa5d6b514/ Distributed processes, multiple threads, multicore CPUs: what are Python's options? http://groups.google.com/group/comp.lang.python/browse_thread/thread/fe55f38c64f58a9d/ Allowing underscores or other punctuation inside numeric literals: http://groups.google.com/group/comp.lang.python/browse_thread/thread/93dc57f9190b93bc/85dfbb163ba7f15b#85dfbb163ba7f15b How to manage two interdependent properties: http://groups.google.com/group/comp.lang.python/browse_thread/thread/66846422b6c2848f/ A generic GUI library, and the future of GUI development: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8904fbc731586533/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From almar.klein at gmail.com Thu Sep 25 08:49:31 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 25 Sep 2008 14:49:31 +0200 Subject: what does "python -i" use as input stream (stdin)? Message-ID: <cc38d75f0809250549u2acff662n765bc1c2990d0e78@mail.gmail.com> Hi, I want to start "python -i" from a subprocess and change its stdin stream, so I get control over the commands I feed the interpreter. I thought just changing sys.stdin to my custom file-like object would suffice, but this does not work. Neither does changing sys.__stdin__. I guess the interpreter got a reference to the original stdin (the Pipe) before I could change it, and is using that instead of sys.stdin. Any thoughts how I can get the interpreter to use MY custom stream? thanks, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080925/9371b9e3/attachment.html> From rcdailey at gmail.com Fri Sep 5 15:24:16 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 14:24:16 -0500 Subject: Need formatting suggestion for long strings Message-ID: <496954360809051224i66123029s23a5ab2f02d8be2b@mail.gmail.com> Hi, I find quite often that I'm writing things like this: raise FatalExcept( "Insufficient number of arguments specified. Exactly {0} arguments are required. See stage.bat for documentation on accepted parameters.".format( num_arguments ) ) On my display (Vertical monitor), this exceeds the width of my display, and to view the entire length of the string I am forced to pan my view left and right. Is there a special way I can format this string so that it fits nicely on the screen? Keep in mind that one important factor is that whitespace is very sensitive, and I do not want line breaks in my script file to become part of the string itself. I like how C++ handles strings, like this: char const* mystring = "This is a very long string that " "spans multiple lines and does " "not include line breaks or tabs " "from the source file between " "the strings partitions." What do you guys prefer? Thanks for reading. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080905/a436a1d7/attachment.html> From mail at timgolden.me.uk Thu Sep 18 12:01:13 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 18 Sep 2008 17:01:13 +0100 Subject: Installing pySerial In-Reply-To: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: <48D27B49.6080209@timgolden.me.uk> Joe G (Home) wrote: > Hi All, > > Background > =================== > I have installed Python for windows today from the python web site .I also > installed pySerial using the Windows installer from the sourceforge web > site..... Both installs use the default directories. > > Phyton version : Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > v.1310 32 bit (Intel)] on win32 > > pySerial 2.4 July 6th > > > Problem : Errors Screen output > ============================ >>>> import serial > > Traceback (most recent call last): > File "<pyshell#0>", line 1, in <module> > import serial > File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in > <module> > from serialwin32 import * > File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in > <module> > import win32file # The base COM port and file IO functions. > ImportError: No module named win32file You need to install the pywin32 extensions from: http://pywin32.sf.net They're so commonly used (and, if you install the ActiveState distro of Python, even bundled) that I imagine many Windows Pythoneers like myself simply install them automatically as soon as we've installed the main python.org Python. Once you've done that, the rest should just work: it's clear from the traceback that the serial module is getting imported; it's just trying to find the win32file module. TJG From fetchinson at googlemail.com Wed Sep 10 13:40:17 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Sep 2008 10:40:17 -0700 Subject: Alternatives to traditional RDBMS In-Reply-To: <6iq90jFdeiU1@mid.uni-berlin.de> References: <mailman.791.1221056566.3487.python-list@python.org> <6iq90jFdeiU1@mid.uni-berlin.de> Message-ID: <fbe2e2100809101040j79d24a62hc2e4c08ab346b3e2@mail.gmail.com> >> Are there any known alternatives >> to the traditional RDBMS (MySQL, >> PostgreSQL, SQLite, Oracle, etc0 / >> >> I know of 3 written in Python: >> * buzhug >> * kirbybase >> * PyDbLite > > ZODB. Without any problems usable without ZOPE, clusterable, ACID-conform > and so forth. There is also dejavu: http://www.aminus.net/dejavu -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mike at ipglobal.net Tue Sep 16 15:40:47 2008 From: mike at ipglobal.net (Support Desk) Date: Tue, 16 Sep 2008 14:40:47 -0500 Subject: How do I add permanently to Pythons sys.path? In-Reply-To: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> Message-ID: <031601c91834$1dbafed0$a601a8c0@office.ipglobal.net> What about on a unix box? Sincerely, Michael H. -----Original Message----- From: Aaron "Castironpi" Brady [mailto:castironpi at gmail.com] Sent: Tuesday, September 16, 2008 12:49 PM To: python-list at python.org Subject: Re: How do I add permanently to Pythons sys.path? On Sep 16, 10:13?am, cnb <circularf... at yahoo.se> wrote: > >>> sys.path > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > \lib\\site-packages\\PIL'] > > > > Now I have my personal programs in C:/Python25/Progs/ > > How do I add so that I can just do "import somefile" from anywhere in > that directory in the interpreter and it can load files from other > folders in that directory. Add a file: \Lib\site-packages\locals.pth with contents, path to the directory you want to add (/python25/progs/) From tjreedy at udel.edu Sat Sep 20 20:35:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Sep 2008 20:35:59 -0400 Subject: explain slice assignment to newb In-Reply-To: <ceceec82-cc0c-4daf-8f8a-1392f4872f71@k30g2000hse.googlegroups.com> References: <ceceec82-cc0c-4daf-8f8a-1392f4872f71@k30g2000hse.googlegroups.com> Message-ID: <gb44t4$5m5$1@ger.gmane.org> Andrew wrote: > please explain this behavior to a newb: Read the section on sequence slicing in the Library Reference. Use the interactive interpreter or IDLE to perform experiments, like you did, until you understand to your satisfaction. From mail at timgolden.me.uk Fri Sep 19 06:05:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 19 Sep 2008 11:05:43 +0100 Subject: webbrowser fragment identifier In-Reply-To: <0b00afc4-018f-4b80-9fba-93c253a86c7a@q5g2000prf.googlegroups.com> References: <0b00afc4-018f-4b80-9fba-93c253a86c7a@q5g2000prf.googlegroups.com> Message-ID: <48D37977.3050100@timgolden.me.uk> scottbvfx wrote: > Hi, > > I'm trying to launch a web browser along with an html file with a > fragment identifier in its path. I'm using the webbrowser module for > this. > ie. webbrowser.open('file:///C:/myfile.html#SomeEntryInTheHTML') > > for some reason it is truncating the path to 'file:///C:/myfile.html'. > > Does anyone know a way of getting the fragment identifier in there > (with webbrowser module or any other)? No expertise here: just poking around. This seems to be a slight peculiarity of browser and os cooperation. As a comparison, try running os.startfile ("file://....#..") or just pasting it into the command line. I don't understand why this should be but it seems to lose it there as well. Randomly tested on my XP box with Firefox 3 & IE 7: Input: Start > Run > firefox c:\temp\t.html#chapter-i Result: URL is escaped so ff3 starts with non-existent file:///c:/temp/t.html%23chapter-i Input: Start > Run > file:///c:\temp\t.html#chapter-i (with ff3 as default) Result: URL fragment is stripped so ff3 starts with file:///C:/temp/t.html Input: Start > Run iexplore c:\temp\t.html#chapter-i Result: Gets it right: ie7 starts with file:///C:/temp/t.html#chapter-i Input: Start > Run > file:///c:\temp\t.html#chapter-i (with ie7 as default) Result: URL fragment is stripped so IE7 starts with file:///C:/temp/t.html A very quick perusal of the webbrowser source suggests it does nothing more sophisticated than finding possible browsers, starting with firefox, and stopping when it finds it. It then uses that as the command-line prefix to whatever url is passed. So no stripping of url fragments happening there. TJG From pavlovevidence at gmail.com Sat Sep 13 04:25:55 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 13 Sep 2008 01:25:55 -0700 (PDT) Subject: question about python References: <a88e3cae-b47c-4b43-bc6d-63739817ef8c@o40g2000prn.googlegroups.com> <c66a320b-348a-45f4-979c-0029c40472a0@a18g2000pra.googlegroups.com> <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> Message-ID: <91f40dcc-d76d-437a-a7e2-ea26b9e333ed@b38g2000prf.googlegroups.com> On Sep 13, 1:00 am, fishfin <calebjhan... at gmail.com> wrote: > @ Carl: Yes, I think your right now that I look at it (or at least all > except for the last two lines need to be indented). I'm still not sure > how to send the stuff to the web browser though. Thanks for pointing > it out! Try reading in the whole HTTP request instead of just the first line. Change line = cfile.readline().strip() to line = cfile.read() And see if that helps. (Outputting the document so that it formats the request well is left as an exercise. Also, as a heads up: in real programs you should never output anything you receive through the network without checking it or escaping it to prevent malicious uses.) Carl Banks From paul at boddie.org.uk Wed Sep 10 19:30:11 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 10 Sep 2008 16:30:11 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <3d6488c1-d57c-46be-b404-9c79bd49dbdf@y21g2000hsf.googlegroups.com> Message-ID: <8b21dee5-2c04-4132-9de6-f8c8843a70e8@d1g2000hsg.googlegroups.com> On Sep 10, 5:03 am, George Sakkis <george.sak... at gmail.com> wrote: > > So at best (i.e. if it actually makes any sense; I didn't read it), > this is an ANNouncement of a pre-alpha piece of code. ANN posts rarely > attract replies, even when they are about production/stable software. To be fair, at least some code has been provided here, unlike another recently announced piece of software whose author left a trail of promotion, referencing a Web site which doesn't even run the advertised software but promises to do so after the "first release": in other words, vapourware, as far as anyone following up on such promotion would be concerned. We aren't seeing anything like that here. > Thankfully, most people don't expect (let alone "require") readers to > share their interest or enthusiasm by replying to the ANN. Given your > past semi-coherent and incoherent posts, expecting people to jump on > such a thread is a rather tall order. I think you should give the benefit of the doubt here, particularly since we've been given a short review of related technologies (so it isn't as if the ideas are being picked out of thin air), and I think that such discussion isn't completely unproductive. Things like shared memory and memory-mapped files are often proposed as optimisations when building multiprocessing solutions, with solutions like POSH previously suggested on a frequent basis despite the lack of their further development, so maybe there is a need for something like this. Although systems like those developed for Tim Bray's "Wide Finder 2" exercise [1] probably work best by dumping raw data to disk - in other words, not channelling data between processes at all - there may well be a need for better data sharing between processes for some kinds of concurrent systems. Whether the ideas described here could help, or whether things like distributed filesystems already cover the same ground, I think it's still worth having the conversation. Of course, people shouldn't have to feel obliged to respond with encouragement to every announcement - there are plenty of projects I have no direct interest in - but I don't think people should respond with discouragement if the only basis for it is how they may have perceived the author's previous contributions to the mailing list or newsgroup. Paul P.S. Maybe those of a more judgemental disposition should peruse the activities in comp.lang.lisp to preserve a sense of perspective. Upon my last chance perusal of that newsgroup, I saw frequent mentions of at least one name familiar to comp.lang.python readers. [1] http://www.tbray.org/ongoing/When/200x/2008/05/01/Wide-Finder-2 From ldo at geek-central.gen.new_zealand Tue Sep 30 04:38:09 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 30 Sep 2008 21:38:09 +1300 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <gbsn6i$ut0$1@aioe.org> Message-ID: <gbsohh$3cg$5@lust.ihug.co.nz> In message <gbsn6i$ut0$1 at aioe.org>, r0g wrote: > Lawrence D'Oliveiro wrote: > >> In message <gbr4ks$1vv$1 at aioe.org>, r0g wrote: >> >>> You can only distribute modifications to gnuplot itself as >>> patches, but you can distribute it freely ... >> >> This must be some new definition of "freely" of which I'm unaware. > > As in beer. You get free beer? From lists at cheimes.de Wed Sep 10 11:32:18 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 17:32:18 +0200 Subject: Refcount problem in ceval.c In-Reply-To: <sesks89gt1.fsf@pc047299.dhcp.germanlloyd.org> References: <sesks89gt1.fsf@pc047299.dhcp.germanlloyd.org> Message-ID: <ga8pa1$6g7$1@ger.gmane.org> Berthold H?llmann wrote: > Is there any "common" reason to for such a strange object on the command > stack, or is it more likely that any of my extension modules is causing > havoc? It's very likely that your extension has a reference counting bug. It looks like you are either missing a Py_INCREF or you have a Py_DECREF too much. Newly freed memory is filled with 0xDB (see Objects/obmalloc.c DEADBYTE). Wild guess: Are you using PyModule_AddObject with a PyTypeObject w/o Py_INCREF()ing the type object first? Christian From jitenshah78 at gmail.com Thu Sep 25 10:51:28 2008 From: jitenshah78 at gmail.com (jitenshah78 at gmail.com) Date: Thu, 25 Sep 2008 15:51:28 +0100 Subject: text processing Message-ID: <48DBA570.9070107@gmail.com> I have string like follow 12560/ABC,12567/BC,123,567,890/JK I want above string to group like as follow (12560,ABC) (12567,BC) (123,567,890,JK) i try regular expression i am able to get first two not the third one. can regular expression given data in different groups From lepto.python at gmail.com Mon Sep 22 02:53:29 2008 From: lepto.python at gmail.com (oyster) Date: Mon, 22 Sep 2008 14:53:29 +0800 Subject: any tool can shrink DLL? Message-ID: <6a4f17690809212353w5e4d39b5odacaa2156bdf8f19@mail.gmail.com> For many external lib, python( and www.freebasic.net) use only the DLL version, whcih is very big often if we want to release our program. So, is there such a tool that can scan a DLL then strip the unused function's code out, so yields a small working DLL? for example, in my program I use only 'compress' function in zlib.dll, then 1. I write a list file in which I emurate the function that I used [code func.lst] compress [/code] 2. run the application [code] shrink zlib.dll func.lst [code] the shrink scans zlib.dll, dumps function 'compress' and all function code on which 'compress' rely, and at last writes tiny-zlib.dll BTW, I know why there is DLL. BTW2, forget upx and so on, they lead to obvious speed down in my experiment From straton at lampsacos.demon.co.uk Sat Sep 6 08:42:29 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sat, 06 Sep 2008 13:42:29 +0100 Subject: max(), sum(), next() In-Reply-To: <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> Message-ID: <g9ttrp$nlp$1$830fa17d@news.demon.co.uk> castironpi wrote: > On Sep 5, 9:20 pm, "Manu Hack" <manuh... at gmail.com> wrote: >> On Fri, Sep 5, 2008 at 1:04 PM, castironpi <castiro... at gmail.com> wrote: >>> On Sep 5, 3:28 am, "Manu Hack" <manuh... at gmail.com> wrote: >>>> On Thu, Sep 4, 2008 at 4:25 PM, castironpi <castiro... at gmail.com> wrote: >>>>> On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >>>>>> David C. Ullrich: >>>>>>> At least in mathematics, the sum of the elements of >>>>>>> the empty set _is_ 0, while the maximum element of the >>>>>>> empty set is undefined. >>>>>> What do you think about my idea of adding that 'default' argument to >>>>>> the max()/min() functions? >>>>>> Bye, >>>>>> bearophile >>>>> For max and min, why can't you just add your argument to the set >>>>> itself? >>>>> The reason max([]) is undefined is that max( S ) is in S. >>>> It makes sense. >>>>> The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >>>> It doesn't make sense to me. What do you set x to? >>> For all x. >> But then how can you conclude sum([]) = 0 from there? It's way far >> from obvious. > > You can define sum([a1,a2,...,aN]) recursively as > sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) "X", then > subtract aN. > > sum([a1,a2,...a(N-1)])+aN=X > sum([a1,a2,...a(N-1)])+aN-aN=X-aN > > For N=2, we have: > > sum([a1,a2])=X > sum([a1,a2])-a2=X-a2 > sum([a1,a2])-a2-a1=X-a2-a1 > > Since X= a1+ a2, replace X. > > sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 > > Or, > > sum([a1,a2])-a2-a1=0 > > Apply the recursive definition: > > sum([a1])+a2-a2-a1=0 > > And again: > > sum([])+a1+a2-a2-a1=0 > > And we have: > > sum([])=0. > This is not necessarily so. The flaw is that you provide a recursive definition with no start value, which is to say it is not a recursive definition at all. A recursive definition should be (for lists where elements can be added, and ignoring pythonic negative indexing): Define 'sum(L)' by a. sum(L[0:1]) = L[0] b. sum(L[0:i]) = sum(L[0:i-1]) + L[i] ... if i > 1 From this you can prove the reverse recursion sum{L[0:k]) = sum(L[0:k+1]) - L[k+1] __only__ if k >= 0 It says nothing about the empty list. You could add, as part of the definition, that sum{[]) = 0, or any other value. A rather different approach, not quite simple recursion, would be to start with A. a slicing axiom, something like: for all non-negative integers, a,b,c with a <=b <= c: sum(L[a:c]) = sum(L[a:b]) + sum(L[b:c]) B. a singleton axiom: for all integers a where L[a] exists: sum(L[a:a]) = L[a] 2a. sum{ From gminick at bzt.bzt Wed Sep 10 13:51:58 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 17:51:58 +0000 (UTC) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> Message-ID: <ga91ft$12t$1@inews.gazeta.pl> On Wed, 10 Sep 2008 10:43:31 -0700 (PDT), Aaron Scott wrote: >> signature, version, attr_count = struct.unpack('3cII', >> yourfile.read(11)) >> > > This line is giving me an error: > > Traceback (most recent call last): > File "test.py", line 19, in <module> > signature, version, attr_count = struct.unpack('3cII', > file.read(12)) > ValueError: too many values to unpack Do: print struct.unpack('3cII', yourfile.read(11)) instead of: signature, version, attr_count = struct.unpack('3cII', yourfile.read(11)) to check what does struct.unpack return. I guess it returns more than three elements. Just like below: >>> a,b,c=(1,2,3,4) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: too many values to unpack As you can see the fourth element from the tuple has no place to go. Same thing happens in your code. HTH. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From webilix950 at googlemail.com Sun Sep 28 18:39:48 2008 From: webilix950 at googlemail.com (webilix950 at googlemail.com) Date: Sun, 28 Sep 2008 15:39:48 -0700 (PDT) Subject: privatdetektei detektei central privat detektei frankfurt private detective privatdetektiv in berlin Message-ID: <3758dc05-0935-4c21-ba7e-22ed52190712@x41g2000hsb.googlegroups.com> privatdetektei detektei central privat detektei frankfurt private detective privatdetektiv in berlin + + + + +++ DETEKTEIEN DETEKTIVE ONLINE +++ DETEKTEI HAMBURG +++ PRIVATDETEKTIVE +++ + + http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET + + + + ################################################################################## detektei hannover dedektive in Steinburg detektive frankfurt ein privatdetektiv in Rhoen ausbildung privatdedektiv detektei erding in Torgau detektiv buero detektei frankfurt in Viersen detektei duisburg detektei pegasus in Sangerhausen detektei detektive detektei blunt in L?chow detektivbueros frankfurt privat detektiv frankfurt in Mayen www detektei werde ich privatdetektiv in Heidenheim - privatdetektiv augsburg detektei erfurt in L?denscheid - detektive berlin privatdetektiv hamburg in Gummersbach - detektei braunschweig schulung frankfurt in Husum - Lentz-Detektei.de www.MeineDetektei.de in Sonneberg - detektei detektive detektei detektiv in Wei?enfels - detektive.com MeineDetektei.de in Neu-Ulm - www.Lentz-Detektei.de werkschutz frankfurt in Heppenheim - detektei muelheim zad detektiv in Burg - ausbildung privatdetektiv privat detektiv in frankfurt in Kirchheimbolanden - privatdetektiv augsburg ein privatdedektiv in Zell - ausbildung privatdedektiv Detektei de in Wolfratshausen - sicherheit frankfurt detekteien in Miesbach - privat detektiv frankfurt detektei gewerbe in Doebeln - detektei duisburg privatdetektive frankfurt in Neuss From m_palmer45 at yahoo.ca Tue Sep 16 14:49:06 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 16 Sep 2008 11:49:06 -0700 (PDT) Subject: Porting a pygtk app to Windows References: <7ce94e05-d704-4118-9496-26f9d7aa6853@k36g2000pri.googlegroups.com> Message-ID: <24287108-1a70-4eca-af87-a188ec09f800@m45g2000hsb.googlegroups.com> On Sep 16, 12:30 pm, binaryjesus <coolman.gu... at gmail.com> wrote: > hi everyone, > first of all > I had written an app using pygtk module and created the GUI with > glade.All the development was done on a linux machine and the app was > working fine all this tme in linux. > > now, the thing is i have to change the development environment to > windows. So this means that i have to port the application to work in > windows. > > Initially i thought that porting an application written using a > platform independent language and cross-platform window frame work > would be a piece of cake. Well i guess all the assumptions end there. > unlike linux, in windows pygtk and the GTK frame work are not > installed by default. > > So, long story short. i installed GTK devel, pygtk, pygobject, pycaro, > glade ui. Also made a lot of path adjustments (os.path.absolutepath() > is not portable i guess) and finally got the app to at least start > without showing an error. > > The problem that i am now facing is that nothing shows up in the app. > No menu, buttons, frames or anything else is visible. When i move the > cursor over the window it changes into an hour-glass type icon. hoe > ever all c++ GTK programs seem to render well. > > here is a screen shot:http://i36.tinypic.com/x52uk9.jpg > > i have written below the startup code of the app: > > import pygtk > pygtk.require('2.0') > import gtk > import gtk.glade > from ConfigParser import ConfigParser > > class jDesk(object): > def __init__(self): > #self.seclstore.append(["0","Section1"]) > #self.catlstore.append(["cat 1"]) > self.synclstore = gtk.ListStore(str,str,str,str,str,int) > self.seclstore = gtk.ListStore(str,str) > self.catlstore = gtk.ListStore(str,str) > self.process_glade() > > def process_glade(self): > self.gladefile = "gui.glade" > self.glade = gtk.glade.XML(self.gladefile) > #windows > self.main_window = self.glade.get_widget('MainWindow') > #main window > self.templatefile = self.glade.get_widget('templatefile') > self.imageurl = self.glade.get_widget('imageurl') > self.posttitle = self.glade.get_widget('posttitle') > self.sectionbox = self.glade.get_widget('sectionbox') > self.categorybox = self.glade.get_widget('categorybox') > self.demolink = self.glade.get_widget('demolink') > self.posttext = self.glade.get_widget('posttext') > self.statusbar = self.glade.get_widget('statusbar') > > self.signal_autoconnect() > self.main_window.show() > print '===================main wind created=================' > def run(self): > try: > print "Entering GTK main now" > gtk.main() > print "Leaving GTK main" > except: > print "Exception in main" > > if __name__ == "__main__": > conf = ConfigParser() > conf.read('settings.cfg') > gtk.gdk.threads_init() > app = jDesk() > app.run() > > i have tried a lot of things, checked up paths, checked libcairo but > nothing seems to help.problem seems to be with pygtk since other c++ > GTK programs like pedgin and GTK demo rn fine. > So maybe is there any pygtk windows bugs that i coming from linux > background might not be knowing about or perhaps u have encountered > such a problem in the past before ? > Much thanks in advance > BinaryJ I haven't tried it myself, but I came across a blog post the other day that describes a way of building windows installers for pyGTK applications at http://unpythonic.blogspot.com/2007/07/pygtk-py2exe-and-inno-setup-for-single.html From coolkid246 at googlemail.com Thu Sep 4 05:47:28 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 02:47:28 -0700 (PDT) Subject: sofortkredit online in Karlsruhe kredite zinsen kredit ohne schufa banken ohne schufa kleinkredit online online sofort kredit ohne schufa onlinekredit ohne schufa kredit schufa frei online kredite von privat kredite beantragen kredit online beantragen kredit fuer arbeitslose kfz kredit guenstiger kredit online handyvertrag schufa kredite ohne schufa mit guenstige kredite online kredit sofortzusage kredit ohne schufa in + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA Message-ID: <21bfd6f0-b44f-4cf9-9ba9-5a675c943948@x16g2000prn.googlegroups.com> sofortkredit online in Karlsruhe kredite zinsen kredit ohne schufa banken ohne schufa kleinkredit online online sofort kredit ohne schufa onlinekredit ohne schufa kredit schufa frei online kredite von privat kredite beantragen kredit online beantragen kredit fuer arbeitslose kfz kredit guenstiger kredit online handyvertrag schufa kredite ohne schufa mit guenstige kredite online kredit sofortzusage kredit ohne schufa in + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + credite ohne schufa kredite fuer selbstaendige in Westerstede postbank kredit barkredite in Garmisch-Partenkirchen kredite schufa online kredit ohne schufa auskunft in Oldenburg private kredite ohne schufa bargeld online in Schoenebeck kredit euro sofortdarlehen in Konstanz kredit vergleich online-kredite in Herzogtum ratenkredit online kredite mit online in Ludwigslust euro kredit ohne schufa mit krediten ohne schufa in Osterholz- Scharmbeck guenstiger kredit online online kredite oesterreich in Burg kredite ohne kredit ohne bonitaet in Pirna privatkredite ohne schufa kredit ohne schufa in Cloppenburg serioeser kredit ohne schufa online krediten in Landsberg kredit mit schufa schufafrei in Biedenkopf online sofort kredite sofort kredite in Pr?m kredit schufafrei kredite selbstaendige in Wolfratshausen kredit schufa frei guenstige kredite ohne schufa in Emmendingen kredite online ohne schufa online kredit schufafrei in Lindau sofort kredit ohne schufa fuer schweizer kredite in Bogen sofortkredite kredit trotz schufa und ohne in Bernburg schnellkredit online darlehen ohne schufa in Stade kredit ohne schufa auskunft vergleich kredit in Warendorf kleinkredit privatkredit in Querfurt - guenstige kredite kredit selbststaendige in Pirmasens - kredit karte ohne schufa bank kredit online in Ulm - postbank kredit online online krediten in Delitzsch - schweizer kredite kredite volksbank in Heinsberg - online sofort kredit ohne schufa kleinkredit online in Hannover - baufinanzierung online kredit ohne ksv in Eckernfoerde - kredit ohne schufa selbststaendige sofortkredit ohne schufa in Schweinfurt - onlinekredite privatkredit ohne schufa in Harburg - online kredit schufafrei kredit ohne auskunft in Bad Ems - konto kredit bargeld kredit in Aschaffenburg - kredit ohne schufa arbeitslos express kredit in Freudenstadt - online-kredite schnelle kredite in Dillingen - kredite finanzierung handyvertrag schufa in Sulzbach - kfw kredit postbank kredit in Goslar From bedouglas at earthlink.net Thu Sep 4 09:26:08 2008 From: bedouglas at earthlink.net (bruce) Date: Thu, 4 Sep 2008 06:26:08 -0700 Subject: Xpath for HTML processing In-Reply-To: <e837f5f4-aed1-4c65-81b6-445a9aee8e41@k36g2000pri.googlegroups.com> Message-ID: <19a601c90e91$cae74250$0301a8c0@tmesa.com> Hi Astley I can probably help here. Can you tell me exactly what you're trying to accomplish. the xpath query that you listed can be processed using libxml2dom (and a fewo other libs) are you looking to parse a web page, an xml doc, etc... let me know, and we'll see if we can help -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Astley Le Jasper Sent: Thursday, September 04, 2008 6:17 AM To: python-list at python.org Subject: Xpath for HTML processing Can anyone suggest something inthat can process an XPath like the following: "/html/body/table[2]/tbody/tr/td[5]/table/tbody/tr[3]/td/table[3]/ tbody/tr[5]/td" Cheers -- http://mail.python.org/mailman/listinfo/python-list From bearophileHUGS at lycos.com Tue Sep 2 11:22:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 2 Sep 2008 08:22:44 -0700 (PDT) Subject: Using NLTK in Java References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> <6i1hu9FnvcngU1@mid.uni-berlin.de> <d6558bd3-c077-4f09-b7cc-652ac3f17c7d@k13g2000hse.googlegroups.com> Message-ID: <6c921c74-d25b-440c-ae81-a412a9fc21ac@r66g2000hsg.googlegroups.com> On Sep 1, 12:30 pm, hussainsai... at gmail.com: >in Jython (which is assumed to replace Python), I don't think so. Bye, bearophile From tdelaney at avaya.com Wed Sep 3 22:43:36 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 4 Sep 2008 10:43:36 +0800 Subject: Numeric literal syntax In-Reply-To: <00cf34ad$0$20302$c3e8da3@news.astraweb.com> Message-ID: <E4C7BCAB1872014F81CEAACD25699B8CCBD265@301081ANEX2.global.avaya.com> Steven D'Aprano wrote: > On Thu, 04 Sep 2008 01:22:22 +0100, Alexander Schmolck wrote: > >> It seems to me that the right choice for thousands seperator is the >> apostrophe. > > You mean the character already used as a string delimiter? Hey - I just found a new use for the backtick! 123`456`7890 0b`1001`0110 Note: Guido has stated that the backtick will *not* be given a new meaning in any future version of Python ... Tim Delaney From paul at boddie.org.uk Fri Sep 26 15:04:27 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 26 Sep 2008 12:04:27 -0700 (PDT) Subject: how to replace and string in a "SELECT ... IN ()" References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <gbico4$fo3$1@inews.gazeta.pl> Message-ID: <295a7522-9594-4cad-889b-dab8c1ba251b@f36g2000hsa.googlegroups.com> On 26 Sep, 12:15, Wojtek Walczak <gmin... at bzt.bzt> wrote: > On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote: > > I have a BIIIIIG problem with the next query: > > > cursor.execute(""" > > SELECT titem.object_id, titem.tag_id > > FROM tagging_taggeditem titem > > WHERE titem.object_id IN (%s) > > """,( eid_list)) > > ^ > It should rather be '%'. You're telling the inquirer to do string substitution which can be dangerous if eid_list is built, say, from a collection of strings taken from an untrusted source. Sadly, SQL parameter substitution, which is done using the syntax employed by the inquirer above (along with the unfortunate "%s" placeholder syntax), does not really deal with sequences of values very well. What needs to be done here, if everything should happen relatively safely, is that the query string should be made to contain the appropriate number of placeholders between the brackets, with commas separating them as demanded by the syntax of SQL. Then, the values should be correctly taken from eid_list by the execute method, although for portability between different database modules, whose authors seem to have differing views on what kind of object can be given containing the parameters, I'd recommend converting eid_list to a tuple. Bruno and Tino thrash out some kind of working solution, I think. Paul From fredrik at pythonware.com Mon Sep 15 17:03:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 23:03:50 +0200 Subject: ka-ping yee tokenizer.py In-Reply-To: <6u80qt$7o5lj6@rrcs-agw-02.hrndva.rr.com> References: <6u80qt$7o5lj6@rrcs-agw-02.hrndva.rr.com> Message-ID: <gamijq$95a$1@ger.gmane.org> Karl Kobata wrote: > I have enjoyed using ka-ping yee?s tokenizer.py. I would like to > replace the readline parameter input with my own and pass a list of > strings to the tokenizer. I understand it must be a callable object and > iteratable but it is obvious with errors I am getting, that this is not > the only functions required. not sure I can decipher your detailed requirements, but to use Python's standard "tokenize" module (written by ping) on a list, you can simple do as follows: import tokenize program = [ ... program given as list ... ] for token in tokenize.generate_tokens(iter(program).next): print token another approach is to turn the list back into a string, and wrap that in a StringIO object: import tokenize import StringIO program = [ ... program given as list ... ] program_buffer = StringIO.StringIO("".join(program)) for token in tokenize.generate_tokens(program_buffer.readline): print token </F> From sdsdvfsdf at gmail.com Sun Sep 28 18:46:57 2008 From: sdsdvfsdf at gmail.com (sdsdvfsdf at gmail.com) Date: Sun, 28 Sep 2008 15:46:57 -0700 (PDT) Subject: Milenko Kindl tterter Message-ID: <1a4b5bd1-709c-4fde-9aa5-31b795d71da5@k13g2000hse.googlegroups.com> WASHINGTON - Congressional leaders and the White House agreed Sunday to a $700 billion rescue of the ailing financial industry after lawmakers insisted on sharing spending controls with the Bush administration. The biggest U.S. bailout in history won the tentative support of both presidential candidates and goes to the House for a vote Monday. ADVERTISEMENT The plan, bollixed up for days by election-year politics, would give the administration broad power to use taxpayers' money to purchase billions upon billions of home mortgage-related assets held by cash- starved financial firms. Flexing its political muscle, Congress insisted on a stronger hand in controlling the money than the White House had wanted. Lawmakers had to navigate between angry voters with little regard for Wall Street and administration officials who warned that inaction would cause the economy to seize up and spiral into recession. A deal in hand, Capitol Hill leaders scrambled to sell it to colleagues in both parties and acknowledged they were not certain it would pass. "Now we have to get the votes," said Sen. Harry Reid, D- Nev., the majority leader. The final legislation was released Sunday evening. House Republicans and Democrats met privately to review it and decide how they would vote. "This isn't about a bailout of Wall Street, it's a buy-in, so that we can turn our economy around," said House Speaker Nancy Pelosi, D-Calif. The largest government intervention in financial markets since the Great Depression casts Washington's long shadow over Wall Street. The government would take over huge amounts of devalued assets from beleaguered financial companies in hopes of unlocking frozen credit. "I don't know of anyone here who wants the center of the economic universe to be Washington," said a top negotiator, Sen. Chris Dodd, chairman of the Senate Banking, Housing and Urban Affairs Committee. But, he added, "The center of gravity is here temporarily. ... God forbid it's here any longer than it takes to get credit moving again." The plan would let Congress block half the money and force the president to jump through some hoops before using it all. The government could get at $250 billion immediately, $100 billion more if the president certified it was necessary, and the last $350 billion with a separate certification ? and subject to a congressional resolution of disapproval. Still, the resolution could be vetoed by the president, meaning it would take extra-large congressional majorities to stop it. Lawmakers who struck a post-midnight deal on the plan with Treasury Secretary Henry Paulson predicted final congressional action might not come until Wednesday. The proposal is designed to end a vicious downward spiral that has battered all levels of the economy. Hundreds of billions of dollars in investments based on mortgages have soured and cramped banks' willingness to lend. "This is the bottom line: If we do not do this, the trauma, the chaos and the disruption to everyday Americans' lives will be overwhelming, and that's a price we can't afford to risk paying," Sen. Judd Gregg, the chief Senate Republican in the talks, told The Associated Press. "I do think we'll be able to pass it, and it will be a bipartisan vote." A breakthrough came when Democrats agreed to incorporate a GOP demand ? letting the government insure some bad home loans rather than buy them. That would limit the amount of federal money used in the rescue. Another important bargain, vital to attracting support from centrist Democrats, would require that the government, after five years, submit a plan to Congress on how to recoup any losses from the companies that got help. "This is something that all of us will swallow hard and go forward with," said Republican presidential nominee John McCain. "The option of doing nothing is simply not an acceptable option." His Democratic rival Barack Obama sought credit for taxpayer safeguards added to the initial proposal from the Bush administration. "I was pushing very hard and involved in shaping those provisions," he said. Later, at a rally in Detroit, Obama said, "it looks like we will pass that plan very soon." House Republicans said they were reviewing the plan. As late as Sunday afternoon, Republicans regarded the deal as "a proposal that is promising in principle, but that is still not final," said Antonia Ferrier, a spokeswoman for Missouri Rep. Roy Blunt, the top House GOP negotiator. Executives whose companies benefit from the rescue could not get "golden parachutes" and would see their pay packages limited. Firms that got the most help through the program ? $300 million or more ? would face steep taxes on any compensation for their top people over $500,000. The government would receive stock warrants in return for the bailout relief, giving taxpayers a chance to share in financial companies' future profits. To help struggling homeowners, the plan would require the government to try renegotiating the bad mortgages it acquires with the aim of lowering borrowers' monthly payments so they can keep their homes. But Democrats surrendered other cherished goals: letting judges rewrite bankrupt homeowners' mortgages and steering any profits gained toward an affordable housing fund. It was Obama who first signaled Democrats were willing to give up some of their favorite proposals. He told reporters Wednesday that the bankruptcy measure was a priority, but that it "probably something that we shouldn't try to do in this piece of legislation." "It's not a bill that any one of us would have written. It's a much better bill than we got. It's not as good as it should be," said Democratic Rep. Barney Frank of Massachusetts, the House Financial Services Committee chairman. He predicted it would pass, though not by a large majority. Frank negotiated much of the compromise in a marathon series of up-and- down meetings and phone calls with Paulson, Dodd, D-Conn., and key Republicans including Gregg and Blunt. Pelosi shepherded the discussions at key points, and cut a central deal Saturday night ? on companies paying back taxpayers for any losses ? that gave momentum to the final accord. An extraordinary week of talks unfolded after Paulson and Ben Bernanke, the Federal Reserve chairman, went to Congress 10 days ago with ominous warnings about a full-blown economic meltdown if lawmakers did not act quickly to infuse huge amounts of government money into a financial sector buckling under the weight of toxic debt. The negotiations were shaped by the political pressures of an intense campaign season in which voters' economic concerns figure prominently. They brought McCain and Obama to Washington for a White House meeting that yielded more discord and behind-the-scenes theatrics than progress, but increased the pressure on both sides to strike a bargain. Lawmakers in both parties who are facing re-election are loath to embrace a costly plan proposed by a deeply unpopular president that would benefit perhaps the most publicly detested of all: companies that got rich off bad bets that have caused economic pain for ordinary people. But many of them say the plan is vital to ensure their constituents don't pay for Wall Street's mistakes, in the form of unaffordable credit and major hits to investments they count on, like their pensions. Some proponents even said taxpayers could come out as financial winners. Gregg, R-N.H., said: "I don't think we're going to lose money, myself. We may ? it's possible ? but I doubt it in the long run." Milenko Kindl Banja Luka Banjaluka Bihac From fredrik at pythonware.com Thu Sep 4 04:05:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 10:05:20 +0200 Subject: use str as variable name In-Reply-To: <3e473cc60809040059o5ebb0bd2h54db1d38929a533b@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <3e473cc60809040059o5ebb0bd2h54db1d38929a533b@mail.gmail.com> Message-ID: <g9o4s0$fs6$1@ger.gmane.org> Mathieu Prevot wrote: > I'll use: > a.__setattr__(height, new_value) that's an implementation detail. please use setattr() instead, like everyone else. </F> From musiccomposition at gmail.com Sat Sep 27 22:53:53 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 27 Sep 2008 19:53:53 -0700 (PDT) Subject: Abstract Base Class register function References: <mailman.1602.1222552230.3487.python-list@python.org> Message-ID: <676263de-4ff3-4c5f-a01c-100bfd1b673d@d1g2000hsg.googlegroups.com> On Sep 27, 4:50?pm, "Mikolai Fajer" <mfa... at gmail.com> wrote: > I have been experimenting with the abc module in py3k and thought > about using the register method of an ABC as a class decorator: > > <code> > import abc > class MyABC(metaclass=abc.ABCMeta): > ? ? pass > > @MyABC.register > class MySub(): > ? ? pass > </code> > > This doesn't work because the register method returns None. ?It would > be a fairly simple modification to have this work: > > <code> > ? ? def register(cls, subclass): > ? ? ? ? """Register a virtual subclass of an ABC.""" > ? ? ? ? ... etc ... > ? ? ? ? return subclass > </code> > > What do people think of this behavior? It's probably better to just inherit from your metclass. register is really for use with extension types that implement an interface. > > -- > > ? ? ?-Mikolai Fajer- From jackie.python at gmail.com Fri Sep 5 10:29:59 2008 From: jackie.python at gmail.com (Jackie Wang) Date: Fri, 5 Sep 2008 10:29:59 -0400 Subject: Extract Information from Tables in html Message-ID: <37b964200809050729j6290af48u8efbbc1a5e0b6bd1@mail.gmail.com> Dear all, Here is a html code: <td valign="top" headers="col4"> Premier Community Bank of Southwest Florida <br /> Fort Myers, FL </td> My question is how I can extract the strings and get the results: Premier Community Bank of Southwest Florida; Fort Myers, FL Thanks a lot Jackie From castironpi at gmail.com Mon Sep 8 15:13:50 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 8 Sep 2008 12:13:50 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <mailman.666.1220826503.3487.python-list@python.org> <086a0906-c6f1-489c-91ab-f6a4f9e1ae3f@59g2000hsb.googlegroups.com> <99113520-2fa2-46ac-9894-ea78372ff610@c58g2000hsc.googlegroups.com> <mailman.691.1220890992.3487.python-list@python.org> Message-ID: <45f6d806-e31e-4d60-af60-b3a727b5fb79@t54g2000hsg.googlegroups.com> On Sep 8, 11:23?am, "Dan Upton" <up... at virginia.edu> wrote: > On Sun, Sep 7, 2008 at 10:59 PM, castironpi <castiro... at gmail.com> wrote: > > On Sep 7, 7:34 pm, MRAB <goo... at mrabarnett.plus.com> wrote: > >> On Sep 7, 11:28 pm, "Eric Wertman" <ewert... at gmail.com> wrote: > > >> > +1 Bot > > >> I think it's like duck typing: it doesn't matter whether he's actually > >> a bot, only whether he behaves like one. > > > Do you support the bot interface and methods? > > -- > > And this is an example of why you get +1 bot. I took Eric's comment to be a joke and mine was too. I don't get the feeling yours is, no offense. From steve at holdenweb.com Tue Sep 30 08:39:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Sep 2008 08:39:36 -0400 Subject: What is not objects in Python? In-Reply-To: <pan.2008.09.30.06.07.46@REMOVE.THIS.cybersource.com.au> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <f2d2bf0b-9362-47f5-84eb-411e09ab38e1@8g2000hse.googlegroups.com> <pan.2008.09.30.06.07.46@REMOVE.THIS.cybersource.com.au> Message-ID: <48E21E08.9020808@holdenweb.com> Steven D'Aprano wrote: > On Mon, 29 Sep 2008 21:03:07 -0700, namekuseijin wrote: > >>> Why isn't len implemented as a str.len and list.len method instead of a >>> len(list) function? >> Because postfix notation sucks. The natural way of spelling is >> adjective+noun and verb+predicate. > > "Natural"? > > You mean phrases like "heir apparent" and "worst choice imaginable" are > unnatural? They are certainly far from normal usage, as my dog yellow would be certain to agree. > To say nothing of languages like Spanish, Albanian, Italian, > Cornish, Vietnamese, Hebrew... It's long been a convention in the Western programming world to pretend no other language than English and no other codes than ASCII exist. The fact that Python is beginning to come to terms with Unicode is a tribute to certain developers' persistence. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Sep 13 12:52:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Sep 2008 16:52:31 GMT Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> Message-ID: <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> On Sat, 13 Sep 2008 01:06:22 -0700, cnb wrote: > This must be because of implementation right? Shouldn't reduce be faster > since it iterates once over the list? doesnt sum first construct the > list then sum it? What makes you think that? Given the speed of sum(), it sure doesn't look like it's generating a full list before summing. Why would it? > reduce with named function: 37.9864357062 > reduce with nested, named function: 39.4710288598 > reduce with lambda: 39.2463927678 > sum comprehension: 25.9530121845 If you want to see reduce really shine, time it with a C-based function rather than one written in pure Python: >>> Timer('reduce(add, xrange(10000))', ... 'from operator import add').repeat(number=10000) [19.724750995635986, 19.410486936569214, 19.614511013031006] >>> >>> Timer('reduce(add, xrange(10000))', ... 'def add(x, y): return x+y').repeat(number=10000) [45.210143089294434, 44.814558982849121, 46.906874895095825] You probably won't see much (if any) benefit for small lists, so make sure your test is on a significantly-sized input list. Of course, sum() is even faster than reduce: >>> Timer('sum(xrange(10000))').repeat(number=10000) [9.814924955368042, 8.7169640064239502, 9.5062401294708252] -- Steven From rcdailey at gmail.com Fri Sep 5 16:22:13 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 15:22:13 -0500 Subject: Case-insensitive string compare? In-Reply-To: <g9rqnp$t8p$1@ger.gmane.org> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050059.17038.maric@aristote.info> <g9qjav$3os$1@ger.gmane.org> <200809051331.40609.maric@aristote.info> <g9rqnp$t8p$1@ger.gmane.org> Message-ID: <496954360809051322qc6a243ey80f3a644b687415@mail.gmail.com> On Fri, Sep 5, 2008 at 12:36 PM, Fredrik Lundh <fredrik at pythonware.com>wrote: > Maric Michaud wrote: > > I suspect you are coming to conclusions a bit quickly, without taking the >> pain of understanding the whole discussion. >> > > I'm pretty sure I was the first one to post an answer in this thread, and I > understand Python design and performance issues very well, thank you. > > (but given your talk about "the cost of whitespace" in a response to a > comment about performance in that other subthread, it's obvious that you're > just here to provide noise. plonk plonk.) Thanks to the helpfulness of the python community, I've made a decision on how I wish to solve this problem. I decided to go ahead and pre-format my dictionary's keys to lowercase, and leave the values untouched (Case-retained). This way, any comparisons I perform will always be on lowercase (case insensitive) keys. All I have to do is call lower() on the value I'll be comparing against the keys. Thanks to everyone that helped. Apologies for the flame war that started! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080905/77a8e8ef/attachment.html> From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 12 06:44:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Sep 2008 12:44:36 +0200 Subject: Good programming style In-Reply-To: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> Message-ID: <48ca4780$0$15455$426a74cc@news.free.fr> Astley Le Jasper a ?crit : > I'm still learning python and would like to know what's a good way of > organizing code. > > I am writing some scripts to scrape a number of different website that > hold similar information and then collating it all together. Obviously > each site needs to be handled differently, but once the information is > collected then more generic functions can be used. > > Is it best to have it all in one script or split it into per site > scripts that can then be called by a manager script? > If everything is > in one script would you have per site functions to extract the data or > generic function that contain vary slightly depending on the site, As far as I'm concerned, I'd choose the first solution. Decoupling what's varying (here, site-specific stuff) from "invariants" is so far the best way I know to keep complexity manageable. > for > example > > import firstSiteScript > import secondSiteScript > > firstsitedata = firstSiteScript.getData('search_str) > secondsitedata = secondSiteScript.getData('search_str) > etc etc Even better : - put generic functions in a 'generic' module - put all site-specific stuff each in it's own module in a specific 'site_scripts' directory - in your 'main' script, scan the site_scripts directory to loop over site-specific modules, import them and run them (look for the __import__ function). This is kind of a Q&D lightweight plugin system, that avoids having to hard-code imports and calls in the main script, so you just have to add/remove site-specific script to/from the site_scripts directory . Also, imported modules are not recompiled on each import - only when they change - while the 'main' script get recompiled on each invocation. (snip) > OR > > def getdata(search_str, website): > if website == 'firstsite': > .... > elif website =='secondsite': This one is IMHO the very worst thing to do. My 2 cents... From m_palmer45 at yahoo.ca Mon Sep 15 19:28:52 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 15 Sep 2008 16:28:52 -0700 (PDT) Subject: CGIHTTPServer webserver running php scripts References: <85ddfc4a-3dea-449e-9b68-c4271932de79@m44g2000hsc.googlegroups.com> Message-ID: <af5f68cf-6d6c-4db4-9912-4843089c5f13@y38g2000hsy.googlegroups.com> On Sep 15, 5:25 pm, mpc <mcoh... at gmail.com> wrote: > hello, > how does one run a PHP page with a python webserver? > > Lets say i have a simple python web server running > /path/webserver.py > #!/usr/bin/env > python > from BaseHTTPServer import HTTPServer > from CGIHTTPServer import CGIHTTPRequestHandler > serve = HTTPServer(("",8080),CGIHTTPRequestHandler) > serve.serve_forever() > > Also lets say i am interested in hosting a simple.php in the cgi-bin > directory. > /path/cgi-bin/simple.php > <html> > <head> > <title>A simple php script. > > > > > > > The webserver starts up and hosts html and python cgi's just fine > but nothing will come up when we go tohttp://localhost:8080/cgi-bin/simple.php > > I get the following errors. > with normal user > localhost:path user$ python webserver.py > localhost - - [15/Sep/2008 16:17:59] "GET /cgi-bin/example.php HTTP/ > 1.1" 200 - > Traceback (most recent call last): > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/CGIHTTPServer.py", line 251, in run_cgi > os.execve(scriptfile, args, os.environ) > OSError: [Errno 8] Exec format error > localhost - - [15/Sep/2008 16:17:59] CGI script exit status 0x7f00 > > localhost:path user$ sudo python webserver.py > Password: > localhost - - [15/Sep/2008 16:18:29] "GET /cgi-bin/example.php HTTP/ > 1.1" 200 - > Traceback (most recent call last): > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/CGIHTTPServer.py", line 251, in run_cgi > os.execve(scriptfile, args, os.environ) > OSError: [Errno 13] Permission denied > > Is there something I can add to my python webserver so that it will > properly run php files? It seems you have to set the executable permission on your php file. I suppose you have php set up for cgi and the shebang line in your php file? From a cursory glance through CGIHTTPServer.py it seems that it should work. From marco.bizzarri at gmail.com Fri Sep 12 11:07:06 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 12 Sep 2008 17:07:06 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <6ivdhnFnm8bU1@mid.uni-berlin.de> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809120807n4bd005faj7ee75eba3598ec84@mail.gmail.com> On Fri, Sep 12, 2008 at 4:44 PM, Diez B. Roggisch wrote: >>> if any(instance.forbitToClose(archivefolder) for instance in >>> self.findActiveOutgoingRegistrationInstances()) >> >> Can you clarify where I can find "any"? It seems to me I'm unable to find >> it... > > It's part of python2.5. > > If you don't have that, you can write it your own and stuff it into > __builtins__: > >>>> def any(iterable): > ... for item in iterable: > ... if item: > ... return True > ... return False > ... > ... __builtins__.any = any > > > You might also want to add all, the companion of any: > > >>>> def all(iterable): > ... for item in iterable: > ... if not item: > ... return False > ... return True > ... > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > I'm afraid this have another problem for me... emmebi at janitor:/var/local/zope28/porting/Products/PAFlow$ python2.3 Python 2.3.5 (#2, Oct 18 2006, 23:04:45) [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def any(iterable): pass ... >>> any(x for x in [1, 2, 3]) File "", line 1 any(x for x in [1, 2, 3]) ^ SyntaxError: invalid syntax >>> >>> any([x for x in [1, 2, 3]]) >>> I mean, I'm afraid I can't use an expression like that without building a list... not at least in python2.3 Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From tjreedy at udel.edu Mon Sep 8 17:02:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Sep 2008 17:02:56 -0400 Subject: Where does the command "ls" in some doctest files come from ? In-Reply-To: References: Message-ID: KLEIN St?phane wrote: > Hi, > > for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/ > tests.py?rev=89831&view=auto test file, there is this doctests : > > def develop_verbose(): > """ > We should be able to deal with setup scripts that aren't setuptools based. > > >>> mkdir('foo') > >>> write('foo', 'setup.py', > ... ''' > ... from setuptools import setup > ... setup(name="foo") > ... ''') > > >>> write('buildout.cfg', > ... ''' > ... [buildout] > ... develop = foo > ... parts = > ... ''') > > >>> print system(join('bin', 'buildout')+' -vv'), # doctest: +ELLIPSIS > Installing... > Develop: '/sample-buildout/foo' > ... > Installed /sample-buildout/foo > ... > > >>> ls('develop-eggs') > - foo.egg-link > - zc.recipe.egg.egg-link > > >>> print system(join('bin', 'buildout')+' -vvv'), # doctest: > +ELLIPSIS > Installing... > Develop: '/sample-buildout/foo' > in: '/sample-buildout/foo' > ... -q develop -mxN -d /sample-buildout/develop-eggs/... > > > """ > > I wonder where does the "ls('develop-eggs')" command come from ? 'ls' is the unix abbreviation for the shell command 'list files (in a directory)'. The name is used above for a similar Python function. It presumably was imported somewhere before develop_verbose, or else is part of the auto-imported site.py for a development site. From andre.dos.anjos at gmail.com Mon Sep 1 09:16:35 2008 From: andre.dos.anjos at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 1 Sep 2008 06:16:35 -0700 (PDT) Subject: Using an existing instance as parent Message-ID: <2ac46f80-76d5-4270-bc86-1f07a5cbd477@z72g2000hsb.googlegroups.com> Hi, I was trying to find a way to set, upon __init__() the parent of a class to an existing instance. Here is a minimal example of what I'm trying to do: class A(object): def __init__(self, x): self.x = x class B(A): def __init__(self, *args): if not isinstance(args[0], A): super(B, self).__init__(args[0]) else: self = args[0] self.y = args[1] b = B(4, 6) print 'b:', b.x, b.y, type(b) a = A(7) c = B(a, 3) # Means: please set c parent's using instance "a" print 'c:', c.x, c.y, type(c) This does not work as can be tested. The reason I'm in search for a solution in this area is that in our project, "A" is not copy-able (it is written using a boost.python binding to a C++ object that does not allow copying) - so I can't simply call, inside "B's __init__()", a copy constructor for A. Any ideas? From deets at nospam.web.de Mon Sep 8 03:18:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Sep 2008 09:18:11 +0200 Subject: How do I set a callback in Python? In-Reply-To: References: Message-ID: <6ik1tkFr4kgiU1@mid.uni-berlin.de> catsclaw schrieb: > I can't for the life of me figure out how to set a callback in > Python. I have a class, which wraps another class. The second class > needs a callback assigned. I don't want to use globals for it. > Here's what I'd like to do: > > class MyWrapper: > def get_login(self, username): > return self.user, self.pass > > def __init__(self, user, pass): > self.user = user > self.pass = pass > > self.client = Client("connection string") > self.client.callback_login = get_login > > ... but obviously, the Client class, when it calls the callback, > doesn't pass a reference to the "self" object. How do I do this? Do self.get_login. The difference is that this creates a so-called "bound method". Google for that, and play around in the interpreter with an object and references to it's methods, either through the class or the instance to see the difference. Diez From fredrik at pythonware.com Thu Sep 25 18:58:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 Sep 2008 00:58:51 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <48DBB9C8.6090500@gmail.com> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> Message-ID: Stef Mientki wrote: > 1. I've a multitab editor. > 2. When a breakpoint is reached, > 3. I check if the file specified in pdb output, is already open in one > of the editor tabs, > 4. if not, I open a new tab with the correct file, > 5. I focus the correct editor tab and jump to the line specified by > pdb. > 6. After that I should be able to inspect the surrounding of the > breakpoint, so I need the modules name. > > For 3 I need to compare filenames, the editor contains the case > sensitive name, pdb not. pdb uses os.path.abspath and os.path.normcase to normalize filenames so they can be safely compared (see the canonic method in bdb.py). I suggest you do the same in your editor; e.g: pdb_filename = ... for buffer in editor_buffers: filename = os.path.normcase(os.path.abspath(buffer.filename)) if pdb == filename: ... found it ... break From robert.kern at gmail.com Mon Sep 22 16:24:17 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Sep 2008 15:24:17 -0500 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Mensanator wrote: > >> I'm not the one who wrote sympy, so I guess I'm not >> the only one who didn't notice it. >> >> If it's a well known problem, then sorry I wasted >> your time. > > Given that 2.5 explicitly warns about this specific change: > > >>> as = 1 > :1: Warning: 'as' will become a reserved keyword in Python 2.6 > > it's an unknown issue only for people who has 1) never used their code > under 2.5, or 2) never looks at the output produced by their programs. > > The PEP-5 process guarantees that "users will have at least a year to > test their programs and migrate them from use of the deprecated > construct to the alternative one," and Python 2.5 was released *two* > years ago. > > So it sure looks like the SimPy folks ignored the established process. > Why they've done that is probably a more interesting issue than the > change itself. No warnings show up when importing the offending module: Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from sympy.mpmath import specfun >>> So what could be suppressing the warning? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gandalf at shopzeus.com Wed Sep 10 09:34:05 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 10 Sep 2008 15:34:05 +0200 Subject: universal unicode font for reportlab In-Reply-To: References: Message-ID: <48C7CCCD.3060404@shopzeus.com> Ross Ridge wrote: > Terry Reedy wrote: > >> Sorry, I posted the wrong name. >> Ariel Unicode MS is the one that seems pretty complete. >> > ... > >> From the MS, I would guess that is a Windows font too ;-). >> > > It's made by Microsoft, but it's not a standard Windows font. I think > it comes with Microsoft Office. > I need to use HTML anyway. I realized that universal unicode fonts are above 5MB in size. The report would be a 10KB PDF, but I need to embed the font before I can send it to anyone. Since some reports needs to be sent in emails, I need to use something else. I cannot be sending 10MB emails for "one page" reports. I ended up implementing the reports in HTML. I'm assuming that the user's browser is capable of displaying any characters needed. Now there is another problem: how to print an HTML without page header/footer information, from a browser? But that is another problem and probably has nothing to do with Python. Thanks for your help anyway. Best, Laszlo From thkruege at googlemail.com Thu Sep 11 15:12:14 2008 From: thkruege at googlemail.com (Thorben Krueger) Date: Thu, 11 Sep 2008 21:12:14 +0200 Subject: huge socket recv speed discrepancy between different OSs In-Reply-To: <14239_1221159651_m8BJ0nOU014276_LRdyk.30$W06.14@flpi148.ffdc.sbc.com> References: <14239_1221159651_m8BJ0nOU014276_LRdyk.30$W06.14@flpi148.ffdc.sbc.com> Message-ID: <3b5d765a0809111212s22fdedb5x38d03501e4220cdf@mail.gmail.com> If you follow the bug report, you might notice that this is probably an issue of socket flags. I know that *BSD and Linux handle sockets slightly differently, but that about covers my knowledge of these things. Maybe a solution can be found simply by setting the right flags for the socket... Any ideas in this line of thought? I am kind of afraid to approach the Perl guys with this issue, although it might be worth a try... Hm, I fear buffers don't help me at all. You see, I wish to send thousands of very small tcp packets to the server in as little time as possible. Thats where the program running under OS X outperforms the Linux version by several orders of magnitude. This is what suggests that the problem could be lying in the difference between BSD and Linux sockets. OT: How would you think pypy could help, if this is OS related? Sorry if I did not make too much sense *tired Thorben 2008/9/11 Dan Stromberg : > On Thu, 11 Sep 2008 16:17:58 +0200, Thorben Krueger wrote: > >> Do you see this too? >> >> Mor information and testcase here: >> >> http://bugs.python.org/issue3766 >> >> I would also be interested in the profiler output under windows. >> >> All the best >> Thorben > > I regret that I don't have a lot of time to look into this interesting > issue. > > Perl may be buffering the socket I/O. That might be a question for > comp.lang.perl. > > Usually, when you can reduce the number of function/method calls and > system calls done in your innermost loop(s), especially on a high speed > network, you've done a good thing - because otherwise CPU use becomes the > dominant term in the performance equation. > > You might want to try my bufsock module to see if that'll help: > > http://stromberg.dnsalias.org/~strombrg/bufsock.html > > It'll give you buffered sockets, along with a flush method. > > You probably also might want to try psyco when on an x86 system. > Unfortunately, it looks like psyco isn't available for x86-64. > > Anyone know if pypy is ready to try such a program as Thorben's? > > -- > http://mail.python.org/mailman/listinfo/python-list > From gminick at bzt.bzt Thu Sep 4 05:58:55 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 4 Sep 2008 09:58:55 +0000 (UTC) Subject: overwrite set behavior References: Message-ID: On Thu, 04 Sep 2008 11:48:18 +0200, Michele Petrazzo wrote: > Hi all, I want to modify the method that set use for see if there is > already an object inside its obj-list. Something like this: ... > It's possible? As far as I understand you, you need descriptors: http://users.rcn.com/python/download/Descriptor.htm -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From tjreedy at udel.edu Thu Sep 11 00:44:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Sep 2008 00:44:07 -0400 Subject: max(), sum(), next() In-Reply-To: <59f16334-e9f4-46a7-b433-654a08ffb434@k30g2000hse.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> <59f16334-e9f4-46a7-b433-654a08ffb434@k30g2000hse.googlegroups.com> Message-ID: Mensanator wrote: > On Sep 10, 5:36 pm, Terry Reedy wrote: >> Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be >> the most common use of reduce. Sum(s,start) replaces the much less >> common reduce(lambda x,y: x+y, s, start). >> >> Reduce(S, s), where S = sum function, raises an exception on empty s. >> So use that and you are no worse off than before. > What am I doing wrong? >>>> S = sum [snip] Taking me too literally out of context. I meant the sum_of_2 function already given in the example above, as you eventually tried. def S(x,y): return x+y Sorry for the confusion. ... >>>> reduce(lambda x,y:x+y,s) > 6 > >>>> s=[] >>>> reduce(lambda x,y:x+y,s) > Traceback (most recent call last): > File "", line 1, in > reduce(lambda x,y:x+y,s) > TypeError: reduce() of empty sequence with no initial value These two are exactly what I meant. > This is supposed to happen. But doesn't reduce(S,s) work > when s isn't empty? It did. You got 6 above. The built-in 'sum' takes an iterable, not a pair of numbers. tjr From febkimbleox at gmail.com Sat Sep 27 07:14:35 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:14:35 -0700 (PDT) Subject: 3d hentai hentai 3d 3d hentai sex 3d alien hentai 3d - Free Message-ID: <45db7ad6-765f-4a06-ad6e-6b9195d2e8c8@a1g2000hsb.googlegroups.com> 3d . . . *******CLICK HERE******** http://vids365.cn/3d ***************************** . . . . . . . . . . . . Like the time 3d went shopping for 3d mother?s wedding gown. Like the time hentai went shopping for hentai mother?s wedding gown. ?I found hentai yesterday after rehearsal? hentai said. ?I found 3d yesterday after rehearsal? 3d said. ?I found 3d yesterday after rehearsal? 3d said. ?I found hentai yesterday after rehearsal? hentai said. ?I found sex yesterday after rehearsal? sex said. ?I found 3d yesterday after rehearsal? 3d said. ?I found alien yesterday after rehearsal? alien said. ?I found hentai yesterday after rehearsal? hentai said. ?I found 3d yesterday after rehearsal? 3d said. ?I found hentai yesterday after rehearsal? hentai said. ?I found comics yesterday after rehearsal? comics said. ?I found 3d yesterday after rehearsal? 3d said. hentai saw the tears in hentai eyes, ?What?s wrong honey??Oh God, hentai wiped hentai tears because Mandy hated to cry in front of hentai . movies saw the tears in movies eyes, ?What?s wrong honey??Oh God, movies wiped movies tears because Mandy hated to cry in front of movies . free saw the tears in free eyes, ?What?s wrong honey??Oh God, free wiped free tears because Mandy hated to cry in front of free . 3d saw the tears in 3d eyes, ?What?s wrong honey??Oh God, 3d wiped 3d tears because Mandy hated to cry in front of 3d . hentai saw the tears in hentai eyes, ?What?s wrong honey??Oh God, hentai wiped hentai tears because Mandy hated to cry in front of hentai . 3d saw the tears in 3d eyes, ?What?s wrong honey??Oh God, 3d wiped 3d tears because Mandy hated to cry in front of 3d . hentai saw the tears in hentai eyes, ?What?s wrong honey??Oh God, hentai wiped hentai tears because Mandy hated to cry in front of hentai . incest saw the tears in incest eyes, ?What?s wrong honey??Oh God, incest wiped incest tears because Mandy hated to cry in front of incest . 3d saw the tears in 3d eyes, ?What?s wrong honey??Oh God, 3d wiped 3d tears because Mandy hated to cry in front of 3d . anime saw the tears in anime eyes, ?What?s wrong honey??Oh God, anime wiped anime tears because Mandy hated to cry in front of anime . hentai saw the tears in hentai eyes, ?What?s wrong honey??Oh God, hentai wiped hentai tears because Mandy hated to cry in front of hentai . 3d saw the tears in 3d eyes, ?What?s wrong honey??Oh God, 3d wiped 3d tears because Mandy hated to cry in front of 3d . ?Horny again already?? hentai grinned and went straight back to giving hentai another deliciously slow blow job, my cock rapidly hardening in the sacred waters of hentai mouth. ?Horny again already?? porn grinned and went straight back to giving porn another deliciously slow blow job, my cock rapidly hardening in the sacred waters of porn mouth. ?Horny again already?? 3d grinned and went straight back to giving 3d another deliciously slow blow job, my cock rapidly hardening in the sacred waters of 3d mouth. ?Horny again already?? family grinned and went straight back to giving family another deliciously slow blow job, my cock rapidly hardening in the sacred waters of family mouth. ?Horny again already?? hentai grinned and went straight back to giving hentai another deliciously slow blow job, my cock rapidly hardening in the sacred waters of hentai mouth. ?Horny again already?? 3d grinned and went straight back to giving 3d another deliciously slow blow job, my cock rapidly hardening in the sacred waters of 3d mouth. ?Horny again already?? incest grinned and went straight back to giving incest another deliciously slow blow job, my cock rapidly hardening in the sacred waters of incest mouth. ?Horny again already?? hentai grinned and went straight back to giving hentai another deliciously slow blow job, my cock rapidly hardening in the sacred waters of hentai mouth. ?Horny again already?? 3d grinned and went straight back to giving 3d another deliciously slow blow job, my cock rapidly hardening in the sacred waters of 3d mouth. ?Horny again already?? boobs grinned and went straight back to giving boobs another deliciously slow blow job, my cock rapidly hardening in the sacred waters of boobs mouth. ?Horny again already?? hentai grinned and went straight back to giving hentai another deliciously slow blow job, my cock rapidly hardening in the sacred waters of hentai mouth. ?Horny again already?? 3d grinned and went straight back to giving 3d another deliciously slow blow job, my cock rapidly hardening in the sacred waters of 3d mouth. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of hentai fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of games fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of 3d fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor- length gown he?d seen in one of monster fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of hentai fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of 3d fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of tentacle fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of hentai fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of 3d fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor- length gown he?d seen in one of hentai fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of video fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of 3d fashion magazines at home. Fortunately for us, hentai ?s cousin Joe who was related on hentai father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, videos ?s cousin Joe who was related on videos father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, free ?s cousin Joe who was related on free father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, 3d ?s cousin Joe who was related on 3d father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, hentai ?s cousin Joe who was related on hentai father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, games ?s cousin Joe who was related on games father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, 3d ?s cousin Joe who was related on 3d father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, hentai ?s cousin Joe who was related on hentai father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, game ?s cousin Joe who was related on game father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, virtual ?s cousin Joe who was related on virtual father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, hentai ?s cousin Joe who was related on hentai father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, 3d ?s cousin Joe who was related on 3d father?s side decided to get married quickly after a whirlwind romance. She knew if yuna kept this up, yuna climax would run through yuna like a freight train out of control. She knew if 3d kept this up, 3d climax would run through 3d like a freight train out of control. She knew if hentai kept this up, hentai climax would run through hentai like a freight train out of control. She knew if 3d kept this up, 3d climax would run through 3d like a freight train out of control. She knew if hentai kept this up, hentai climax would run through hentai like a freight train out of control. She knew if shows kept this up, shows climax would run through shows like a freight train out of control. She knew if free kept this up, free climax would run through free like a freight train out of control. She knew if 3d kept this up, 3d climax would run through 3d like a freight train out of control. She knew if hentai kept this up, hentai climax would run through hentai like a freight train out of control. She knew if videos kept this up, videos climax would run through videos like a freight train out of control. She knew if incest kept this up, incest climax would run through incest like a freight train out of control. She knew if hentai kept this up, hentai climax would run through hentai like a freight train out of control. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do hentai mind if hentai borrow hentai cousin for a dance? hentai said shyly, totally unaware that hentai had just played gooseberry. ?Do lesbians mind if lesbians borrow lesbians cousin for a dance? lesbians said shyly, totally unaware that lesbians had just played gooseberry. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do hentai mind if hentai borrow hentai cousin for a dance? hentai said shyly, totally unaware that hentai had just played gooseberry. ?Do comic mind if comic borrow comic cousin for a dance? comic said shyly, totally unaware that comic had just played gooseberry. ?Do hot mind if hot borrow hot cousin for a dance? hot said shyly, totally unaware that hot had just played gooseberry. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do hentai mind if hentai borrow hentai cousin for a dance? hentai said shyly, totally unaware that hentai had just played gooseberry. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do hentai mind if hentai borrow hentai cousin for a dance? hentai said shyly, totally unaware that hentai had just played gooseberry. Hey aren?t blowjob off today? blowjob was thinking blowjob could go this afternoon??Mandy admitted, ?Well blowjob do need to go into work for an hour or two to file some papers. Hey aren?t 3d off today? 3d was thinking 3d could go this afternoon??Mandy admitted, ?Well 3d do need to go into work for an hour or two to file some papers. Hey aren?t hentai off today? hentai was thinking hentai could go this afternoon??Mandy admitted, ?Well hentai do need to go into work for an hour or two to file some papers. Hey aren?t cumshot off today? cumshot was thinking cumshot could go this afternoon??Mandy admitted, ?Well cumshot do need to go into work for an hour or two to file some papers. Hey aren?t free off today? free was thinking free could go this afternoon??Mandy admitted, ?Well free do need to go into work for an hour or two to file some papers. Hey aren?t 3d off today? 3d was thinking 3d could go this afternoon??Mandy admitted, ?Well 3d do need to go into work for an hour or two to file some papers. Hey aren?t hentai off today? hentai was thinking hentai could go this afternoon??Mandy admitted, ?Well hentai do need to go into work for an hour or two to file some papers. Hey aren?t movies off today? movies was thinking movies could go this afternoon??Mandy admitted, ?Well movies do need to go into work for an hour or two to file some papers. Hey aren?t 3d off today? 3d was thinking 3d could go this afternoon??Mandy admitted, ?Well 3d do need to go into work for an hour or two to file some papers. Hey aren?t hentai off today? hentai was thinking hentai could go this afternoon??Mandy admitted, ?Well hentai do need to go into work for an hour or two to file some papers. Hey aren?t tits off today? tits was thinking tits could go this afternoon??Mandy admitted, ?Well tits do need to go into work for an hour or two to file some papers. Hey aren?t 3d off today? 3d was thinking 3d could go this afternoon??Mandy admitted, ?Well 3d do need to go into work for an hour or two to file some papers. huge sucked on huge proffered tongue, drawing huge into my mouth as huge melted into each other?s embrace. boobs sucked on boobs proffered tongue, drawing boobs into my mouth as boobs melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. sex sucked on sex proffered tongue, drawing sex into my mouth as sex melted into each other?s embrace. 3d sucked on 3d proffered tongue, drawing 3d into my mouth as 3d melted into each other?s embrace. 3d sucked on 3d proffered tongue, drawing 3d into my mouth as 3d melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. 3d sucked on 3d proffered tongue, drawing 3d into my mouth as 3d melted into each other?s embrace. gay sucked on gay proffered tongue, drawing gay into my mouth as gay melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. She could feel the love 3d had for 3d radiate through 3d and 3d made 3d quiver with desire. She could feel the love video had for video radiate through video and video made video quiver with desire. She could feel the love 3d had for 3d radiate through 3d and 3d made 3d quiver with desire. She could feel the love hentai had for hentai radiate through hentai and hentai made hentai quiver with desire. She could feel the love nurse had for nurse radiate through nurse and nurse made nurse quiver with desire. She could feel the love alien had for alien radiate through alien and alien made alien quiver with desire. She could feel the love 3d had for 3d radiate through 3d and 3d made 3d quiver with desire. She could feel the love hentai had for hentai radiate through hentai and hentai made hentai quiver with desire. She could feel the love sexy had for sexy radiate through sexy and sexy made sexy quiver with desire. She could feel the love 3d had for 3d radiate through 3d and 3d made 3d quiver with desire. She could feel the love girl had for girl radiate through girl and girl made girl quiver with desire. She could feel the love hentai had for hentai radiate through hentai and hentai made hentai quiver with desire. ?Oh, young went out with a boy in young class and young has been a bit funny ever since? replied my aunt. ?Oh, hentai went out with a boy in hentai class and hentai has been a bit funny ever since? replied my aunt. ?Oh, 3d went out with a boy in 3d class and 3d has been a bit funny ever since? replied my aunt. ?Oh, 3d went out with a boy in 3d class and 3d has been a bit funny ever since? replied my aunt. ?Oh, anime went out with a boy in anime class and anime has been a bit funny ever since? replied my aunt. ?Oh, hentai went out with a boy in hentai class and hentai has been a bit funny ever since? replied my aunt. ?Oh, little went out with a boy in little class and little has been a bit funny ever since? replied my aunt. ?Oh, girls went out with a boy in girls class and girls has been a bit funny ever since? replied my aunt. ?Oh, 3d went out with a boy in 3d class and 3d has been a bit funny ever since? replied my aunt. ?Oh, hentai went out with a boy in hentai class and hentai has been a bit funny ever since? replied my aunt. ?Oh, sluts went out with a boy in sluts class and sluts has been a bit funny ever since? replied my aunt. ?Oh, free went out with a boy in free class and free has been a bit funny ever since? replied my aunt. ?Oh, 3d went out with a boy in 3d class and 3d has been a bit funny ever since? replied my aunt. ?Afterwards, hentai fluffed the pillow, straightened the blanket, and then spooned up against hentai . ?Afterwards, video fluffed the pillow, straightened the blanket, and then spooned up against video . ?Afterwards, hentai fluffed the pillow, straightened the blanket, and then spooned up against hentai . ?Afterwards, 3d fluffed the pillow, straightened the blanket, and then spooned up against 3d . ?Afterwards, games fluffed the pillow, straightened the blanket, and then spooned up against games . ?Afterwards, hentai fluffed the pillow, straightened the blanket, and then spooned up against hentai . ?Afterwards, 3d fluffed the pillow, straightened the blanket, and then spooned up against 3d . ?Afterwards, incest fluffed the pillow, straightened the blanket, and then spooned up against incest . ?Afterwards, 3d fluffed the pillow, straightened the blanket, and then spooned up against 3d . ?Afterwards, cartoon fluffed the pillow, straightened the blanket, and then spooned up against cartoon . ?Afterwards, hentai fluffed the pillow, straightened the blanket, and then spooned up against hentai . ?Afterwards, 3d fluffed the pillow, straightened the blanket, and then spooned up against 3d . dildo put my arm around dildo in a brotherly way and guided dildo over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. hentai put my arm around hentai in a brotherly way and guided hentai over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. 3d put my arm around 3d in a brotherly way and guided 3d over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. hentai put my arm around hentai in a brotherly way and guided hentai over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. anime put my arm around anime in a brotherly way and guided anime over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. creampie put my arm around creampie in a brotherly way and guided creampie over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. 3d put my arm around 3d in a brotherly way and guided 3d over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. hentai put my arm around hentai in a brotherly way and guided hentai over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. free put my arm around free in a brotherly way and guided free over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. 3d put my arm around 3d in a brotherly way and guided 3d over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. hentai put my arm around hentai in a brotherly way and guided hentai over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. fuck put my arm around fuck in a brotherly way and guided fuck over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. While observing 3d ?s reaction, Mandy rubbed the head back and forth between the lips coating 3d with juices. While observing hentai ?s reaction, Mandy rubbed the head back and forth between the lips coating hentai with juices. While observing huge ?s reaction, Mandy rubbed the head back and forth between the lips coating huge with juices. While observing tits ?s reaction, Mandy rubbed the head back and forth between the lips coating tits with juices. While observing 3d ?s reaction, Mandy rubbed the head back and forth between the lips coating 3d with juices. While observing hentai ?s reaction, Mandy rubbed the head back and forth between the lips coating hentai with juices. While observing movie ?s reaction, Mandy rubbed the head back and forth between the lips coating movie with juices. While observing 3d ?s reaction, Mandy rubbed the head back and forth between the lips coating 3d with juices. While observing hentai ?s reaction, Mandy rubbed the head back and forth between the lips coating hentai with juices. While observing squirt ?s reaction, Mandy rubbed the head back and forth between the lips coating squirt with juices. While observing 3d ?s reaction, Mandy rubbed the head back and forth between the lips coating 3d with juices. While observing hentai ?s reaction, Mandy rubbed the head back and forth between the lips coating hentai with juices. ?I?m sorry about earlier, tentacles didn?t mean to?. ?I?m sorry about earlier, 3d didn?t mean to?. ?I?m sorry about earlier, hentai didn?t mean to?. ?I?m sorry about earlier, young didn?t mean to?. ?I?m sorry about earlier, sister didn?t mean to?. ?I?m sorry about earlier, fucking didn?t mean to?. ?I?m sorry about earlier, brother didn?t mean to?. ?I?m sorry about earlier, 3d didn?t mean to?. ?I?m sorry about earlier, lesbian didn?t mean to?. ?I?m sorry about earlier, hentai didn?t mean to?. ?I?m sorry about earlier, 3d didn?t mean to?. ?I?m sorry about earlier, teacher didn?t mean to?. Let hentai finish these steaks, they?re almost done. Let 3d finish these steaks, they?re almost done. Let young finish these steaks, they?re almost done. Let hentai finish these steaks, they?re almost done. Let 3d finish these steaks, they?re almost done. Let anime finish these steaks, they?re almost done. Let hentai finish these steaks, they?re almost done. Let alien finish these steaks, they?re almost done. Let sex finish these steaks, they?re almost done. Let with finish these steaks, they?re almost done. Let human finish these steaks, they?re almost done. Let 3d finish these steaks, they?re almost done. As hentai lie here, hentai can still hardly believe hentai all happened, what a crazy incredible day. As blog lie here, blog can still hardly believe blog all happened, what a crazy incredible day. As 3d lie here, 3d can still hardly believe 3d all happened, what a crazy incredible day. As hentai lie here, hentai can still hardly believe hentai all happened, what a crazy incredible day. As monster lie here, monster can still hardly believe monster all happened, what a crazy incredible day. As 3d lie here, 3d can still hardly believe 3d all happened, what a crazy incredible day. As hentai lie here, hentai can still hardly believe hentai all happened, what a crazy incredible day. As movie lie here, movie can still hardly believe movie all happened, what a crazy incredible day. As nurse lie here, nurse can still hardly believe nurse all happened, what a crazy incredible day. As 3d lie here, 3d can still hardly believe 3d all happened, what a crazy incredible day. As hentai lie here, hentai can still hardly believe hentai all happened, what a crazy incredible day. As no lie here, no can still hardly believe no all happened, what a crazy incredible day. ? He filled the wine bucket with ice, popped the cork, set the bottle in tits to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in anime to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in 3d to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in hentai to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in free to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in hentai to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in 3d to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in gay to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in 3d to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in hentai to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in hentai to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in 3d to chill, and then took two goblets over to the table. I moaned, arching my back to press 2 tits harder into 2 hands. I moaned, arching my back to press hentai tits harder into hentai hands. I moaned, arching my back to press 3d tits harder into 3d hands. I moaned, arching my back to press 3some tits harder into 3some hands. I moaned, arching my back to press hentai tits harder into hentai hands. I moaned, arching my back to press 3d tits harder into 3d hands. I moaned, arching my back to press child tits harder into child hands. I moaned, arching my back to press hentai tits harder into hentai hands. I moaned, arching my back to press 3d tits harder into 3d hands. I moaned, arching my back to press videos tits harder into videos hands. I moaned, arching my back to press virtual tits harder into virtual hands. I moaned, arching my back to press hentai tits harder into hentai hands. 3d really got worried when four months passed and 3d hadn?t heard anything. uncensored really got worried when four months passed and uncensored hadn?t heard anything. vitrual really got worried when four months passed and vitrual hadn?t heard anything. hentai really got worried when four months passed and hentai hadn?t heard anything. 3d really got worried when four months passed and 3d hadn?t heard anything. 3d really got worried when four months passed and 3d hadn?t heard anything. anime really got worried when four months passed and anime hadn?t heard anything. hentai really got worried when four months passed and hentai hadn?t heard anything. alien really got worried when four months passed and alien hadn?t heard anything. sex really got worried when four months passed and sex hadn?t heard anything. 3d really got worried when four months passed and 3d hadn?t heard anything. anime really got worried when four months passed and anime hadn?t heard anything. Tess squeezed movie tits around Al?s cock and went to town. Tess squeezed alien tits around Al?s cock and went to town. Tess squeezed hentai tits around Al?s cock and went to town. Tess squeezed 3d tits around Al?s cock and went to town. Tess squeezed big tits around Al?s cock and went to town. Tess squeezed hentai tits around Al?s cock and went to town. Tess squeezed 3d tits around Al?s cock and went to town. Tess squeezed demon tits around Al?s cock and went to town. Tess squeezed hentai tits around Al?s cock and went to town. Tess squeezed 3d tits around Al?s cock and went to town. Tess squeezed hentai tits around Al?s cock and went to town. Tess squeezed banged tits around Al?s cock and went to town. When you?re gone, by feel empty inside. When you?re gone, alien feel empty inside. When you?re gone, 3d feel empty inside. When you?re gone, hentai feel empty inside. When you?re gone, big feel empty inside. When you?re gone, boobs feel empty inside. When you?re gone, 3d feel empty inside. When you?re gone, hentai feel empty inside. When you?re gone, cartoon feel empty inside. When you?re gone, 3d feel empty inside. When you?re gone, hentai feel empty inside. When you?re gone, cum feel empty inside. Short, petite, big breasted, tan with dark hair, 3d loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, hentai loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, gallary loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, 3d loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, hentai loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, gay loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, 3d loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, hentai loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, lesbian loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, 3d loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, hentai loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, mom loved the gym and had a youthful, contagious energy. He felt 3d balls churning wanting to release 3d precious contents again. He felt hentai balls churning wanting to release hentai precious contents again. He felt nurses balls churning wanting to release nurses precious contents again. He felt 3d balls churning wanting to release 3d precious contents again. He felt hentai balls churning wanting to release hentai precious contents again. He felt rape balls churning wanting to release rape precious contents again. He felt 3d balls churning wanting to release 3d precious contents again. He felt hentai balls churning wanting to release hentai precious contents again. He felt slut balls churning wanting to release slut precious contents again. He felt 3d balls churning wanting to release 3d precious contents again. He felt hentai balls churning wanting to release hentai precious contents again. He felt tentacle balls churning wanting to release tentacle precious contents again. 3d hard, erect nipples could be seen clearly through 3d thin bra. hentai hard, erect nipples could be seen clearly through hentai thin bra. titanime hard, erect nipples could be seen clearly through titanime thin bra. 3d hard, erect nipples could be seen clearly through 3d thin bra. hentai hard, erect nipples could be seen clearly through hentai thin bra. world hard, erect nipples could be seen clearly through world thin bra. 3d hard, erect nipples could be seen clearly through 3d thin bra. hentai hard, erect nipples could be seen clearly through hentai thin bra. xxx hard, erect nipples could be seen clearly through xxx thin bra. 3d hard, erect nipples could be seen clearly through 3d thin bra. huge hard, erect nipples could be seen clearly through huge thin bra. tits hard, erect nipples could be seen clearly through tits thin bra. He pinched one and then the other one, anime groaned in reaction to anime caress. He pinched one and then the other one, hentai groaned in reaction to hentai caress. He pinched one and then the other one, 3d groaned in reaction to 3d caress. He pinched one and then the other one, rikku groaned in reaction to rikku caress. He pinched one and then the other one, hentai groaned in reaction to hentai caress. He pinched one and then the other one, 3d groaned in reaction to 3d caress. He pinched one and then the other one, school groaned in reaction to school caress. He pinched one and then the other one, hentai groaned in reaction to hentai caress. He pinched one and then the other one, 3d groaned in reaction to 3d caress. He pinched one and then the other one, shemale groaned in reaction to shemale caress. He pinched one and then the other one, hentai groaned in reaction to hentai caress. He pinched one and then the other one, cute groaned in reaction to cute caress. Tammy and 3d were both still naked as 3d discussed what to do. Tammy and hentai were both still naked as hentai discussed what to do. Tammy and free were both still naked as free discussed what to do. Tammy and 3d were both still naked as 3d discussed what to do. Tammy and hentai were both still naked as hentai discussed what to do. Tammy and games were both still naked as games discussed what to do. Tammy and download were both still naked as download discussed what to do. Tammy and hentai were both still naked as hentai discussed what to do. Tammy and 3d were both still naked as 3d discussed what to do. Tammy and 2 were both still naked as 2 discussed what to do. Tammy and username were both still naked as username discussed what to do. Tammy and and were both still naked as and discussed what to do. However, right now, my dick is screaming to make love to you!?Mandy pulled password lips down hard on hers, feeling the love password shared clear to the center of password soul. However, right now, my dick is screaming to make love to you!?Mandy pulled hentai lips down hard on hers, feeling the love hentai shared clear to the center of hentai soul. However, right now, my dick is screaming to make love to you!?Mandy pulled 3d lips down hard on hers, feeling the love 3d shared clear to the center of 3d soul. However, right now, my dick is screaming to make love to you!?Mandy pulled alien lips down hard on hers, feeling the love alien shared clear to the center of alien soul. From rridge at csclub.uwaterloo.ca Thu Sep 25 17:09:17 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 25 Sep 2008 17:09:17 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48db462f$0$24356$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >Also note that there are quite a couples cases where the library authors >themselves cannot predict which exception types may be raised - as soon >as the library functions expect callback functions, file-like or >dict-like or whatever-like objects etc, it's the caller's responsability >to handle the exceptions that may be raised by what *he* passes to the >library... Ug... that's another documentation pet-peeve of mine. Libraries that say they take file-like (or whatever-like) object, but don't say exactly how file-like it needs. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From gagsl-py2 at yahoo.com.ar Tue Sep 30 19:49:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 20:49:53 -0300 Subject: problem with "ImportError: No module named..." and sockets References: Message-ID: En Tue, 30 Sep 2008 19:44:51 -0300, Daniel escribi?: > On Sep 30, 4:17?pm, "Gabriel Genellina" > wrote: >> En Tue, 30 Sep 2008 18:38:19 -0300, Daniel ? >> escribi?: >> >> >> >> > [BEGIN CODE] >> > #!/usr/bin/python >> > import SocketServer >> > import os, sys >> > newpath = os.path.normpath( os.path.join( __file__, "../../.." )) >> > sys.path.insert(0, newpath) >> >> > from pop.command.UpdateCommand import * >> > import cPickle >> >> > Traceback (most recent call last): >> > [...] >> > ImportError: No module named UpdateCommand >> >> > I import the module at the top of the file server.py, but it doesn't >> > throw the ImportError until it tries to unpickle. >> >> Notice that you don't import the UpdateCommand module - you import all ? >> names defined inside it instead. It's not the same thing. >> Seehttp://effbot.org/zone/import-confusion.htm >> >> -- >> Gabriel Genellina > > Thank you Gabriel, > > The class inside that module has the same name, UpdateCommand. Since > this is the object that was pickled, it should be available to the > unpickle command. I already understood the difference between import > methods and I think I'm covered. I did just try "import > pop.command.TesterUpdateCommand" instead and I get the same error. (TesterUpdateCommand != UpdateCommand...) In your *pickling* code, just before pickling the object, see what you get from this: cls = obj.__class__ print cls.__module__ print cls.__name__ Suppose you get "SomeModuleName" and "SomeClassName". Then, in your *unpickling* environment, this must succeed: import SomeModuleName cls = SomeModuleName.SomeClassName If not, you should rearrange things (on both sides, probably) to make the reference work. This is basically what pickle does. Looks like the module lives in a package - make sure you import the *package* both when pickling and unpickling. The sys.path manipulation looks suspicious. -- Gabriel Genellina From ldo at geek-central.gen.new_zealand Tue Sep 23 19:50:53 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 11:50:53 +1200 Subject: Regex Help References: Message-ID: In message , Support Desk wrote: > Anybody know of a good regex to parse html links from html code? The one I > am currently using seems to be cutting off the last letter of some links, > and returning links like > > http://somesite.co > > or http://somesite.ph > > the code I am using is > > > regex = r'' Can you post some example HTML sequences that this regexp is not handling correctly? From ldo at geek-central.gen.new_zealand Fri Sep 26 03:46:10 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 19:46:10 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: > >> Just a thought, your minimum sleep time is probably limited by the >> resolution of the system "HZ" clock. Type >> >> less /proc/config.gz > > $ less /proc/config.gz > /proc/config.gz: No such file or directory > > > What OS are you using? The one named in the subject line? From tino at wildenhain.de Mon Sep 22 10:14:05 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Sep 2008 16:14:05 +0200 Subject: A bit weird dictionary behavior In-Reply-To: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: <48D7A82D.7030808@wildenhain.de> Hi, bearophileHUGS at lycos.com wrote: > Pekka Laukkanen: ... > On the other hand it has some little practical advantages, you can do: > sum(x == y for x in iterable) > > That also equals to a more tidy: > sum(1 for x in iterable if x == y) Wouldn't len([x for x in iterable if x==y]) or even shorter: iterable.count(y) not work and read better anyway? even calculating with boolean values isn't neccessary since 'and' and 'foo if bar else blub' are working much better so the type coalescing bool - int - float can really go away. Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From stef.mientki at gmail.com Fri Sep 5 16:06:19 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 05 Sep 2008 22:06:19 +0200 Subject: pdb bug and questions In-Reply-To: References: Message-ID: <48C1913B.90705@gmail.com> R. Bernstein wrote: > Stef Mientki writes: > > >> hello, >> >> I'm trying to embed a debugger into an editor. >> I'm only interested in high level debugging. >> The first question is what debugger is the best for my purpose ? >> (pdb, pydb, rpdb2, smart debugger, extended debugger ? >> >> Second question, in none of the above debuggers (except rpdb2), >> I can find a "break now", >> so it seems impossible to me to detect unlimited while loops ? >> > > I am not sure what you mean by "break now". pdb and pydb allow direct > calls from a program to the debugger via set_trace (which in pydb is > deprecated in favor of I think the more descriptive name: debugger) > > But I suspect this is not what you mean to "detect unlimited while > loops"; pydb also has gdb-style signal handling that allows for entry > into the debugger when the debugged python process receives a > particular signal. "info handle" lists all of the interrupts and what > action is to be taken on each. See > http://bashdb.sourceforge.net/pydb/pydb/lib/node38.html > > However I believe that signals are only handled by the main thread; so > if that's blocked, the python process won't see the signal. > Thanks, Yes, I think the trace option can do the job, certainly if I display every line. Didn't know pdb had something like settrace ( the information on pdb is very condensed ;-) > >> For the moment I started with pdb, because most of the debuggers seems >> to be an extension on pdb. >> When I launch the debugger ( winXP, Python 2.5) from with my editor >> python -u -m pdb D:\\Data\\test_IDE.py >> I get this error >> IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') >> NOTICE 1 backslash ----------------------------------^ >> >> If I launch the debugger with >> python -u -m pdb D:/Data/test_IDE.py >> It runs fine. >> >> This looks like a bug to me. >> What's the best way to report these kind of bugs ? >> > > winpdb, pydb and pdb (part of Python) all have Sourceforge projects > which have bug trackers. For pdb, in the past people includng myself, > have reported features, patches and bugs in the Python tracker; > eventually it gets handled. (Eventually in my case means a year or > so.) But if my information is incorrect or out of date, no doubt > someone will correct me. > I'll take a look, for the sake of our children ;-) > As mentioned in the last paragraph, pydb also is a Sourceforge project > (part of bashdb) which has a tracker for bug reporting. Using the bug > tracker I think is better than discussing pydb bugs in c.l.p. c.l.p. ? > By > extension, I assume the same is also true for the other debuggers. > > Finally, I think rpdb2 is part of the winpdb project on Sourceforge > and again has a bug tracker. My sense is that Nir Aides is very good > about handling bugs reported in winpdb/rpdb. > Yes I started with rpdb2, and indeed Nir Aides is very helpfull, but I think interfaceing rpdb2 is a little too difficult for me, but I'll certainly add winpdb as the option for external debugging. For now I think pydb is the choice, better control and more functions than pdb, and almost just as easy. cheers, Stef > >> Although I mostly use os.path.join to be OS independent, >> these kind of bugs give me the impression, >> that I can better do the join myself and always use forward slashes. >> Is this a valid conclusion ? >> >> thanks, >> Stef Mientki >> > -- > http://mail.python.org/mailman/listinfo/python-list > From marco.bizzarri at gmail.com Wed Sep 10 16:08:17 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 10 Sep 2008 22:08:17 +0200 Subject: Python and Open Office In-Reply-To: References: Message-ID: <3f0d61c40809101308y37c0cb22j55ef033bee6bda99@mail.gmail.com> On Wed, Sep 10, 2008 at 10:04 PM, Greg Lindstrom wrote: > Hello, > > I would like to create and manipulate Open Office documents using Python. I > have found then UNO Python page and odfpy modules which seem to be exactly > what I need. The odfpy manual is, to me, a confusing list of objects and > methods (it's an impressive list!), but does not have much in the way of how > to use them. For example, I can open a spreadsheet and create new pages > (there's a nice example near the back of the manual) but I can't figure out > how to open an existing spreadsheet and list the names of the individual > sheets ("tabs"). > > I have written an application that access Microsoft Excel and creates > reports for work, but would like to create an Open Source version using Open > Office and release it to the community (and maybe get a talk at PyCon :-). > > Is there someone here who can help me out, or is there an appropriate > mailing list for me to join? Ciao, Greg. you should check with the openoffice.org mailing list; I think what you are looking for is the api mailing list for openoffice; you could try to get the OpenOffice.org developers guide and the SDK, and check it (but it is not a little work) Regards Marco > Thanks > > --greg > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From dudeja.rajat at gmail.com Mon Sep 8 07:23:05 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 8 Sep 2008 12:23:05 +0100 Subject: Unable to start a process with subprocess Popen() In-Reply-To: References: Message-ID: On Mon, Sep 8, 2008 at 11:50 AM, wrote: > Hi, > > I'm using the subprocess module's Popen() to start a batch file. This > batch file basically calls an exe which also gets started. > Unfortunately, this does not produce any results. I looked into the > Task bar that this exe has started but it does not consume and cpu so > I believet that this exe is not working. > > > I used the following command to start the batch fiile: > > testing = subprocess.Popen([batchFilePath], \ > shell = True, \ > stdout = subprocess.PIPE, \ > stderr = subprocess.PIPE).communicate()[0] > > > batchFilePath is the path of the batch file. > > > > -- > Regrads, > Rajat > Ok, I re-phrase my question: there is a batch file that executes a exe file. The batch just works if run from command prompt and produces output to standard output and the file. Now, I try to call the same batch file from subprocess.Pope() call. The batch file gets called and that internally also calls the exe file. But, the exe just runs forever i.e. hangs and does not produces output , atleast not to the file. Please suggest is there is something wrong with the above code. Regards, Rajat From dudeja.rajat at gmail.com Mon Sep 1 04:23:41 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 1 Sep 2008 09:23:41 +0100 Subject: Unable to clear Entry subwidget of Tix Combo Box Message-ID: Hi, In my combo box taken from Tix, how can I clear the entry subwidget? My case is like this: I have a check button which when made un-ticked should clear the entry from combo box (i. anything selected in combo box previously) I used the following commands: subEntry = self.cbAnalysisLibVersion.subwidget("entry") subEntry.delete(0,END) But this is not working. Please help. Thanks and regards, Rajat From dmitry at makovey.net Wed Sep 24 23:45:31 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 03:45:31 GMT Subject: is decorator the right thing to use? References: Message-ID: Aaron "Castironpi" Brady wrote: > It might help to tell us the order of events that you want in your > program. You're not using 'mymethod' or 'mymethod2', and you probably > want 'return fnew' for the future. Something dynamic with __getattr__ > might work. Any method call to A, that is an A instance, tries to > look up a method of the same name in the B instance it was initialized > with. well 'mymethod' and 'mymethod2' were there just to show that A doesn't function as a pure proxy - it has methods of it's own. See my respnse to Steve - I proxy messages to more than one aggregated object. going over them on __getattr__ to look up methods just doesn't seem to be really efficient to me (I might be wrong though). Decorators seemed to present good opportunity to simplify the code (well except for the decorator function itself :) ), make code bit more "fool-proofed" (and give me the opportunity to test decorators in real life, he-he). So decorators inside of B just identify that those methods will be proxied by A. On one hand from logical standpoint it's kind of weird to tell class that it is going to be proxied by another class, but declaration would be real close to original function definition which helps to identify where is it used. Note that my decorator doesn't change original function - it's a subversion of decorator to a certain degree as I'm just hooking into python machinery to add methods to A upon their declaration in B (or so I think). From bedouglas at earthlink.net Tue Sep 30 16:01:53 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 30 Sep 2008 13:01:53 -0700 Subject: pyhton or json, list or array? Message-ID: <349401c92337$62e68de0$0301a8c0@tmesa.com> hi... sorry to ask such a trivial issue/question... i have the following snip of code, and i'm trying to determine if i'm dealing with a python list of lists, or a javascript/json array. i was told that it's json, but i have no idea how to convert it/manipulate it.. the "aaa" data is derived from the usc course data web site. basically, i'm trying to figure out how to actually parse the data in the array... thanks ========================================== #!/usr/bin/python # # usc.py # # test the list/lists using simplejson # ######################################################################3 #test python script import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList import subprocess import MySQLdb #import mysql_config import time import simplejson as json # # test data from the usc.edu website # aaa='{"schd_sync_dtm":"9\/29\/2008 6:43:56 PM","Dept_Info":{"department":"Accounting","abbreviation":"ACCT","phone_numb er":" - ","address":{},"ugrad_dclass_phone_number":"740-4838","ugrad_dclass_address" :"ACC 101","grad_dclass_phone_number":"740-4838","grad_dclass_address":"ACC 101","Notes":"BUSINESS (UNDERGRADUATE) - Non-admitted (pre-business, undeclared, etc.) students may take courses subject to the following limitations: (1) must have completed at least 28 units; (2) no more than three business courses overall at USC; (3) prerequisites completed. BUSINESS (GRADUATE) - Business students may register using USC Web Registration. - Non-business students may register for graduate business electives subject to the following restrictions: (1) proof of undergraduate degree; (2) minimum graduate GPA of 3.2; (3) maximum of 12 units of graduate business courses; and (4) prerequisites completed. All graduate applications and forms are available in BRI 207, (213) 740-5424, email: registration at marshall.usc.edu. For complete list of Business registration policies, please visit www.marshall.usc.edu\/registrationpolicies.","TermNotes":{},"dept_url":"http :\/\/www.marshall.usc.edu\/lsoa\/"},"OfferedCourses":{"course":[{"IsCrossLis ted":"N","PublishedCourseID":"ACCT-370A","ScheduledCourseID":"ACCT-370A","Co urseData":{"prefix":"ACCT","number":"370","sequence":"A","suffix":{},"title" :"External Financial Reporting Issues","description":"Understanding of decision-making, problem solving, and research skills as a supplement to financial accounting knowledge for accounting professionals.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14030","session":"431","dcl ass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"48","number_registered":"46","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ti me":"11:50","location":"ACC310","instructor":{"last_name":"Lu","first_name": "Yvonne"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},{ "id":"14031","session":"431","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"38","number_registered":"36","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ti me":"15:50","location":"ACC236","instructor":{"last_name":"Lu","first_name": "Yvonne"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},{ "id":"14032","session":"431","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"45","number_registered":"41","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"16:00","end_ti me":"17:50","location":"JKP104","instructor":{"last_name":"Shames","first_na me":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14034","session":"431","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"135","number_registered":"123","wait_qty":"0","cance led":"N","blackboard":"N","comment":{},"day":"F","start_time":"10:00","end_t ime":"11:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-370B","ScheduledCourseID":"ACCT- 370B","CourseData":{"prefix":"ACCT","number":"370","sequence":"B","suffix":{ },"title":"External Financial Reporting Issues","description":"Continuation of understanding of decision-making, problem solving, and research skills as a supplement to financial accounting knowledge for accounting professionals.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"ACCT-370A","coreq_text":{},"SectionData":[{"id":"14035","session":"4 42","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"48","number_registered":"47","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ti me":"11:50","location":"ACC310","instructor":{"last_name":"Lu","first_name": "Yvonne"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},' aaa=aaa+'{"id":"14036","session":"442","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"38","number_registered":"35","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ti me":"15:50","location":"ACC236","instructor":{"last_name":"Lu","first_name": "Yvonne"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},{ "id":"14037","session":"442","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"45","number_registered":"41","wait_qty":"0","cancele d":"N","blackboard":"N","comment":{},"day":"MW","start_time":"16:00","end_ti me":"17:50","location":"JKP104","instructor":{"last_name":"Shames","first_na me":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14038","session":"442","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"135","number_registered":"123","wait_qty":"0","cance led":"N","blackboard":{},"comment":{},"day":"F","start_time":"10:00","end_ti me":"11:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-371A","ScheduledCourseID":"ACCT- 371A","CourseData":{"prefix":"ACCT","number":"371","sequence":"A","suffix":{ },"title":"Introduction to Accounting Systems","description":"Understanding of technology used to support accounting professionals in financial and managerial accounting, auditing, and taxation.","units":"2","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14040","session":"431","dcl ass_code":"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"45","number_registered":"30","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"08:00","end_t ime":"09:50","location":"ACC303","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":"application\/pdf","filesize":"170050"}, "IsDistanceLearning":"N"},{"id":"14041","session":"431","dclass_code":"D","t itle":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"46","number_registered":"44","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","end_t ime":"11:50","location":"ACC303","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":"application\/pdf","filesize":"170050"}, "IsDistanceLearning":"N"},{"id":"14042","session":"431","dclass_code":"D","t itle":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"46","number_registered":"45","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_t ime":"13:50","location":"ACC303","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":"application\/pdf","filesize":"170050"}, "IsDistanceLearning":"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT- 371B","ScheduledCourseID":"ACCT-371B","CourseData":{"prefix":"ACCT","number" :"371","sequence":"B","suffix":{},"title":"Introduction to Accounting Systems","description":"Understanding the fundamental processes that capture the corporate data and the controls needed to assure that these processes will operate in an acceptable manner.","units":"2","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": "ACCT-371A","coreq_text":{},"SectionData":[{"id":"14045","session":"442","dc lass_code":"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"44","number_registered":"22","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"08:00","end_t ime":"09:50","location":"HOH421","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"},{"id":"14046","session":"442","dclass_code":"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},' aaa=aaa+'"type":"Lec","units":"2","spaces_available":"45","number_registered ":"45","wait_qty":"2","canceled":"N","blackboard":"Y","comment":{},"day":"TH ","start_time":"10:00","end_time":"11:50","location":"HOH421","instructor":{ "last_name":"Porter","first_name":"Leslie"},"syllabus":{"format":{},"filesiz e":{}},"IsDistanceLearning":"N"},{"id":"14047","session":"442","dclass_code" :"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"45","number_registered":"45","wait_qty":"1","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_t ime":"13:50","location":"HOH421","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"},{"id":"14048","session":"442","dclass_code":"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lab","units" :"0","spaces_available":"120","number_registered":"107","wait_qty":"0","canc eled":"N","blackboard":{},"comment":{},"day":"F","start_time":"12:00","end_t ime":"13:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-372","ScheduledCourseID":"ACCT-3 72","CourseData":{"prefix":"ACCT","number":"372","sequence":{},"suffix":{}," title":"Internal Reporting Issues","description":"Understanding of decision-making, problem solving, and research skills as a supplement to managerial accounting knowledge for accounting professionals.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14050","session":"442","dcl ass_code":"D","title":"Internal Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"44","number_registered":"27","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"08:00","end_ti me":"09:50","location":"HOH421","instructor":{"last_name":"Jackson","first_n ame":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14051","session":"442","dclass_code":"D","title":"Internal Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"47","number_registered":"47","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ti me":"11:50","location":"HOH304","instructor":{"last_name":"Jackson","first_n ame":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14052","session":"442","dclass_code":"D","title":"Internal Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"45","number_registered":"44","wait_qty":"1","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ti me":"15:50","location":"HOH421","instructor":{"last_name":"Jackson","first_n ame":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14053","session":"442","dclass_code":"D","title":"Internal Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"120","number_registered":"116","wait_qty":"0","cance led":"N","blackboard":{},"comment":{},"day":"F","start_time":"12:00","end_ti me":"13:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-373","ScheduledCourseID":"ACCT-3 73","CourseData":{"prefix":"ACCT","number":"373","sequence":{},"suffix":{}," title":"Introduction to Assurance Services","description":"Explores the requisite skills and knowledge needed to offer services in assurance, attestation or auditing engagements.","units":"2","restriction_by_major":{},"restriction_by_class":{ },"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_t ext":"(ACCT-370A and ACCT-371A)","coreq_text":{},"SectionData":[{"id":"14055","session":"431","dc lass_code":"D","title":"Introduction to Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"44","number_registered":"26","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"08:00","end_ time":"09:50","location":"HOH421","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},' aaa=aaa+'{"id":"14056","session":"431","dclass_code":"D","title":"Introducti on to Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"47","number_registered":"46","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ time":"11:50","location":"HOH304","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14057","session":"431","dclass_code":"D","title":"Introduction to Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"45","number_registered":"44","wait_qty":"1","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ time":"15:50","location":"HOH421","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14058","session":"431","dclass_code":"D","title":"Introduction to Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lab","units ":"0","spaces_available":"120","number_registered":"115","wait_qty":"0","can celed":"N","blackboard":{},"comment":{},"day":"F","start_time":"12:00","end_ time":"13:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-374","ScheduledCourseID":"ACCT-3 74","CourseData":{"prefix":"ACCT","number":"374","sequence":{},"suffix":{}," title":"Introduction to Tax Issues","description":"Basic tax principles, introduction to U.S. federal, state and local tax systems, income and expense definitions, property transactions, and fundamentals in individual taxation.","units":"2","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14060","session":"442","dcl ass_code":"D","title":"Introduction to Tax Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"45","number_registered":"30","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"08:00","end_ti me":"09:50","location":"ACC303","instructor":{"last_name":"Swenson","first_n ame":"Charles"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"},{"id":"14061","session":"442","dclass_code":"D","title":"Introduction to Tax Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"46","number_registered":"46","wait_qty":"1","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","end_ti me":"11:50","location":"ACC303","instructor":{"last_name":"Swenson","first_n ame":"Charles"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"},{"id":"14062","session":"442","dclass_code":"D","title":"Introduction to Tax Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"46","number_registered":"45","wait_qty":"1","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_ti me":"13:50","location":"ACC303","instructor":{"last_name":"Swenson","first_n ame":"Charles"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-410","ScheduledCourse ID":"ACCT-410","CourseData":{"prefix":"ACCT","number":"410","sequence":{},"s uffix":"x","title":"Foundations of Accounting","description":"Non-technical presentation of accounting for users of accounting information; introduction to financial and managerial accounting. Not open to students with course credits in accounting. Not available for unit or course credit toward a degree in accounting or business administration.","units":"4","restriction_by_major":{},"restriction_by_class ":{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prere q_text":{},"coreq_text":{},"SectionData":[{"id":"14090","session":"001","dcl ass_code":"R","title":"Foundations of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"40","number_registered":"38","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","en d_time":"11:50","location":"HOH305","instructor":{"last_name":"Bonner","firs t_name":"Sarah","bio_url":"http:\/\/mymarshall.usc.edu\/portal\/subapps\/dig italmeasures\/faculty.jsp?surveyId=48731"},"syllabus":{"format":{},"filesize ":{}},"IsDistanceLearning":"N"},' aaa=aaa+'{"id":"14092","session":"001","dclass_code":"R","title":"Foundation s of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"39","number_registered":"32","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","en d_time":"11:50","location":"ACC236","instructor":{"last_name":"Zhang","first _name":"Jieying"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning ":"N"},{"id":"14094","session":"001","dclass_code":"R","title":"Foundations of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"40","number_registered":"40","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"12:00","en d_time":"13:50","location":"HOH305","instructor":{"last_name":"Bonner","firs t_name":"Sarah","bio_url":"http:\/\/mymarshall.usc.edu\/portal\/subapps\/dig italmeasures\/faculty.jsp?surveyId=48731"},"syllabus":{"format":{},"filesize ":{}},"IsDistanceLearning":"N"},{"id":"14096","session":"001","dclass_code": "R","title":"Foundations of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"39","number_registered":"30","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"16:00","en d_time":"17:50","location":"ACC236","instructor":{"last_name":"Zhang","first _name":"Jieying"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning ":"N"},{"id":"14098","session":"001","dclass_code":"R","title":"Foundations of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"40","number_registered":"40","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00","en d_time":"15:50","location":"ACC236","instructor":{"last_name":"Zhang","first _name":"Jieying"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning ":"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-411","ScheduledCour seID":"ACCT-411","CourseData":{"prefix":"ACCT","number":"411","sequence":{}, "suffix":"x","title":"Understanding Financial Reporting","description":"Understanding of financial statements and insight into the implications of the disclosure requirements. Not available for credit to accounting or business majors.","units":"2","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": "ACCT-410","coreq_text":{},"SectionData":{"id":"14006","session":"431","dcla ss_code":"D","title":"Understanding Financial Reporting","section_title":{},"description":{},"notes":{},"type":"Lec","unit s":"2","spaces_available":"1","number_registered":"0","wait_qty":"0","cancel ed":"Y","blackboard":{},"comment":{},"day":"MW","start_time":"12:00","end_ti me":"13:50","location":{},"syllabus":{"format":{},"filesize":{}},"IsDistance Learning":"N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-412","Schedu ledCourseID":"ACCT-412","CourseData":{"prefix":"ACCT","number":"412","sequen ce":{},"suffix":"x","title":"Special Financial Reporting Issues","description":"Analysis of contemporary financial reporting and disclosure issues. Includes topics such as accounting for stock options and income tax, off-balance sheet financing, hedging and derivatives. Not available for credit to accounting and business majors. Open to accounting majors only.","units":"2","restriction_by_major":" Registration open to the following major(s): Accounting","restriction_by_class":{},"restriction_by_school":{},"CourseNote s":{},"CourseTermNotes":{},"prereq_text":"ACCT-411","coreq_text":{},"Section Data":{"id":"14010","session":"442","dclass_code":"D","title":"Special Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"1","number_registered":"0","wait_qty":"0","canceled" :"Y","blackboard":{},"comment":{},"day":"MW","start_time":"00:00","end_time" :"13:50","location":{},"syllabus":{"format":{},"filesize":{}},"IsDistanceLea rning":"N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-415","Scheduled CourseID":"ACCT-415","CourseData":{"prefix":"ACCT","number":"415","sequence" :{},' aaa=aaa+'"suffix":"x","title":"Intermediate Financial Accounting for Non-Accounting Majors","description":"In-depth study of balance sheet, income statement, and cash flow statement issued from the perspective of a user (not preparer) of corporate financial reports. Not open to accounting majors. Not available for degree credit to accounting majors.","units":"4","restriction_by_major":" Registration closed to the following major(s): Accounting","restriction_by_class":{},"restriction_by_school":{},"CourseNote s":{},"CourseTermNotes":{},"prereq_text":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14100","session":"001","dcl ass_code":"R","title":"Intermediate Financial Accounting for Non-Accounting Majors","section_title":{},"description":{},"notes":{},"type":"Lec","units": "4","spaces_available":"54","number_registered":"48","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"12:00","end_ti me":"13:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14102","session":"001","dclass_code":"R","title":"Intermediate Financial Accounting for Non-Accounting Majors","section_title":{},"description":{},"notes":{},"type":"Lec","units": "4","spaces_available":"39","number_registered":"23","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"16:00","end_ti me":"17:50","location":"ACC236","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-463","ScheduledCours eID":"ACCT-463","CourseData":{"prefix":"ACCT","number":"463","sequence":{}," suffix":{},"title":"Internal Audit","description":"Examination of internal audit\/auditors and their relationship to management, the investors, the regulators, and the external auditors.","units":"2","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":"(ACCT-370B and ACCT-373)","coreq_text":{},"SectionData":{"id":"14186","session":"442","dcla ss_code":"D","title":"Internal Audit","section_title":{},"description":{},"notes":{},"type":"Lec","units":" 2","spaces_available":"35","number_registered":"21","wait_qty":"0","canceled ":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"08:00","end_tim e":"09:50","location":"ACC236","instructor":{"last_name":"Layton","first_nam e":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}} },{"IsCrossListed":"N","PublishedCourseID":"ACCT-470A","ScheduledCourseID":" ACCT-470A","CourseData":{"prefix":"ACCT","number":"470","sequence":"A","suff ix":{},"title":"Advanced External Financial Reporting Issues","description":"Developing capabilities to identify and articulate current external financial reporting problems and issues, concentrating on operating, financing and investing activities of business organizations.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"ACCT-370B","coreq_text":{},"SectionData":[{"id":"14115","session":"4 31","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"51","number_registered":"49","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_ti me":"13:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14116","session":"431","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"50","number_registered":"33","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00","end_ti me":"15:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14118","session":"431","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"100","number_registered":"82","wait_qty":"0","cancel ed":"N","blackboard":{},"comment":{},"day":"F","start_time":"14:00","end_tim e":"15:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},' aaa=aaa+'{"IsCrossListed":"N","PublishedCourseID":"ACCT-470B","ScheduledCour seID":"ACCT-470B","CourseData":{"prefix":"ACCT","number":"470","sequence":"B ","suffix":{},"title":"Advanced External Financial Reporting Issues","description":"Developing capabilities to identify and articulate current external financial reporting problems and issues, concentrating on operating, financing and investing activities of business organizations.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"ACCT-470A","coreq_text":{},"SectionData":[{"id":"14120","session":"4 42","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"50","number_registered":"42","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_ti me":"13:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14121","session":"442","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"50","number_registered":"30","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00","end_ti me":"15:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14123","session":"442","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"100","number_registered":"72","wait_qty":"0","cancel ed":"N","blackboard":{},"comment":{},"day":"F","start_time":"14:00","end_tim e":"15:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-472","ScheduledCourseID":"ACCT-4 72","CourseData":{"prefix":"ACCT","number":"472","sequence":{},"suffix":{}," title":"Managerial Accounting","description":"Understanding of systems providing cost information useful in management decision-making and problem solving.","units":"2","restriction_by_major":{},"restriction_by_class":{},"r estriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text" :"ACCT-372","coreq_text":{},"SectionData":{"id":"14130","session":"431","dcl ass_code":"D","title":"Managerial Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"2","spaces_available":"35","number_registered":"27","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","en d_time":"11:50","location":"BRI8","instructor":{"last_name":"Jackson","first _name":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-473","ScheduledCourseI D":"ACCT-473","CourseData":{"prefix":"ACCT","number":"473","sequence":{},"su ffix":{},"title":"Financial Statement Auditing","description":"Course builds on the background developed in ACCT 373, specifically the process used by external auditors to conduct financial statement audits.","units":"2","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": "(ACCT-371B and ACCT-373)","coreq_text":{},"SectionData":[{"id":"14135","session":"442","dcl ass_code":"D","title":"Financial Statement Auditing","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"39","number_registered":"29","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ time":"11:50","location":"HOH301","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14136","session":"442","dclass_code":"D","title":"Financial Statement Auditing","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"32","number_registered":"24","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ time":"15:50","location":"HOH306","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14137","session":"442","dclass_code":"D","title":"Financial Statement Auditing","section_title":{},"description":{},"notes":{},"type":"Lab","units ":"0",' aaa=aaa+'"spaces_available":"78","number_registered":"53","wait_qty":"0","ca nceled":"N","blackboard":{},"comment":{},"day":"F","start_time":"12:00","end _time":"13:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-474","ScheduledCourseID":"ACCT-4 74","CourseData":{"prefix":"ACCT","number":"474","sequence":{},"suffix":{},t itle":"Tax Issues for Business","description":"Capabilities to identify and articulate tax issues related to a business entity s life: formation, investing, financing and operations, and change of form.","units":"2","restriction_by_major":{},"restriction_by_class":{},"rest riction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text":"A CCT-374","coreq_text":{},' aaa=aaa+'"SectionData":[{"id":"14140","session":"431","dclass_code":"D","tit le":"Tax Issues for Business","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"39","number_registered":"21","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ time":"11:50","location":"HOH301","instructor":{"last_name":"Scharlach","fir st_name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearnin g":"N"},' aaa=aaa+'{"id":"14141","session":"431","dclass_code":"D","title":"Tax Issues for Business","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"32","number_registered":"17","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ time":"15:50","location":"HOH306","instructor":{"last_name":"Scharlach","fir st_name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearnin g":"N"},{"id":"14142","session":"431","dclass_code":"D","title":"Tax Issues for Business","section_title":{},"description":{},"notes":{},"type":"Lab","units ":"0","spaces_available":"100",' aaa=aaa+'"number_registered":"38","wait_qty":"0","canceled":"N","blackboard" :{},"comment":{},"day":"F","start_time":"14:00","end_time":"15:50","location ":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-476","ScheduledCourseID":"ACCT-4 76","CourseData":{"prefix":"ACCT","number":"476","sequence":{},"suffix":{}," title":"Performance Measurement Issues","description":"Introduction to understanding how management control systems can enhance achievement of the organization\'s objectives and strategies.","units":"2","restriction_by_major":{},"restriction_by_class":{} ,"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_te xt":"ACCT-372","coreq_text":{},"SectionData":{"id":"14150","session":"442"," dclass_code":"D","title":"Performance Measurement Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"35","number_registered":"17","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","end_ti me":"11:50","location":"BRI8","instructor":{"last_name":"Jackson","first_nam e":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"} }},{"IsCrossListed":"N","PublishedCourseID":"ACCT-478","ScheduledCourseID":" ACCT-478","CourseData":{"prefix":"ACCT","number":"478","sequence":{},"suffix ":{},"title":"Accounting Systems Design","description":"Explores the design of accounting systems. Introduction to tools and techniques for analyzing and designing accounting systems with an emphasis on system controls and reporting.","units":"4","restriction_by_major":{},"restriction_by_class":{}, "restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_tex t":"ACCT-371B","coreq_text":{},"SectionData":{"id":"14160","session":"001"," dclass_code":"D","title":"Accounting Systems Design","section_title":{},"description":{},"notes":{},"type":"Lec","units": "4","spaces_available":"35","number_registered":"10","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00","end_ti me":"15:50","location":"BRI8","instructor":{"last_name":"Kiddoo","first_name ":"Bob"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}}}, {"IsCrossListed":"N","PublishedCourseID":"ACCT-479","ScheduledCourseID":"ACC T-479","CourseData":{"prefix":"ACCT","number":"479","sequence":{},"suffix":{ },"title":"Accounting Systems Development","description":"Examines the fundamentals of accounting systems development. Introduction to the concepts of implementation and support, with emphasis on system quality assurance, evaluation and attestation.","units":"4","restriction_by_major":{},"restriction_by_class":{ },' aaa=aaa+'"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"p rereq_text":"ACCT-478","coreq_text":{},"SectionData":{"id":"14165","session" :"001","dclass_code":"D","title":"Accounting Systems Development","section_title":{},"description":{},"notes":{},"type":"Lec","un its":"4","spaces_available":"30","number_registered":"6","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","en d_time":"13:50","location":"HOH305","instructor":{"last_name":"Kiddoo","firs t_name":"Bob"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-490","ScheduledCourseID ":"ACCT-490","CourseData":{"prefix":"ACCT","number":"490","sequence":{},"suf fix":"x","title":"Directed Research","description":"Individual research and readings. Not available for graduate credit.","units":"2-8, 8","restriction_by_major":{},"restriction_by_class":{},"restriction_by_schoo l":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text":{},"coreq_text":{} ,"SectionData":{"id":"14180","session":"001","dclass_code":"D","title":"Dire cted Research","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2-8","spaces_available":"10","number_registered":"0","wait_qty":"0","canc eled":"N","blackboard":"N","comment":{},"day":{},"start_time":"TBA","end_tim e":"TBA","location":"OFFICE","instructor":{"last_name":"Beatty","first_name" :"Randolph"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-509","ScheduledCourseID": "ACCT-509","CourseData":{"prefix":"ACCT","number":"509","sequence":{},"suffi x":{},"title":"Concepts of Financial and Management Accounting","description":"Introduction to the concepts of financial and managerial accounting. The course will provide coverage of key concepts needed by managers of businesses in order to communicate information important in decision-making. (Duplicates credit in GSBA 510, GSBA 518, GSBA 536.) Not open to business majors.","units":"4","restriction_by_major":" Registration closed to the following major(s): Business Administration, Business Administration (Cinema-Television), Business Administration (East Asian Studies), Business Administration (International Relations), Business Administration, Business Administration\/East Asian Area Studies, Business Administration\/Jewish Communal Service, Gerontology\/Business Administration, Business Administration\/Industrial & Systems Engineering, Nursing\/Business Administration, Business Administration\/Planning, Business Administration\/Real Estate Development, Business Administration\/Dental Surgery, Juris Doctor\/Business Administration, Medicine\/Business Administration, Business Administration\/Pharmacy","restriction_by_class":{},"restriction_by_school": {},"CourseNotes":{},"CourseTermNotes":{},"prereq_text":{},"coreq_text":{},"S ectionData":{"id":"14188","session":"036","dclass_code":"R","title":"Concept s of Financial and Management Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"50","number_registered":"12","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":{},"start_time":"TBA","end_ti me":"TBA","location":"ONLINE","instructor":{"last_name":"Hopkins","first_nam e":"Merle"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"} }},{"IsCrossListed":"N","PublishedCourseID":"ACCT-546","ScheduledCourseID":" ACCT-546","CourseData":{"prefix":"ACCT","number":"546","sequence":{},"suffix ":{},"title":"Assurance Services","description":"Concepts and principles governing independent professional services that provide assurance on the reliability and relevance of information, including financial statement information. Topics include demand and supply issues for these services, basic principles of evidence, risk assessment and testing.","units":"3","restriction_by_major":{},"restriction_by_class":{},"r estriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text" :"ACCT-525","coreq_text":{},"SectionData":{"id":"14206","session":"001","dcl ass_code":"R","title":"Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"3","spaces_available":"54","number_registered":"50","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"08:00","end_ time":"09:20","location":"JKP202","instructor":{"last_name":"Owens","first_n ame":"John"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-547","ScheduledCourseID": "ACCT-547",' aaa=aaa+'"CourseData":{"prefix":"ACCT","number":"547","sequence":{},"suffix" :{},"title":"Enterprise Information Systems","description":"Focuses on accounting enterprise database models and information technology required to support those systems. Includes analysis and design of interfunctional process flows through reengineering to exploit technology capabilities.","units":"3","restriction_by_major":{},"restriction_by_class": {},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_ text":{},"coreq_text":{},"SectionData":{"id":"14208","session":"001","dclass _code":"R","title":"Enterprise Information Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"50","number_registered":"48","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"15:30","end_t ime":"16:50","location":"JKP202","instructor":[{"last_name":"O\'Leary","firs t_name":"Daniel"},{"last_name":"Maxey","first_name":"Shirley"}],"syllabus":{ "format":{},"filesize":{}},"IsDistanceLearning":"N"}}},{"IsCrossListed":"N", "PublishedCourseID":"ACCT-549","ScheduledCourseID":"ACCT-549","CourseData":{ "prefix":"ACCT","number":"549","sequence":{},"suffix":{},"title":"Advanced Enterprise Systems and Technologies","description":"Design, control and development of advanced enterprise systems, using reengineering, focusing on accounting and financial systems, using a wide range of emerging existing technologies. Recommended preparation: ACCT 547.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Business Administration, Nursing\/Business Administration, Business Administration\/Dental Surgery, Information and Operations Management, Business Administration\/East Asian Area Studies, Medicine\/Business Administration, Business Administration\/Jewish Communal Service, Business Administration\/Planning, Business Administration\/Real Estate Development","restriction_by_class":{},"restriction_by_school":{},"CourseNot es":{},"CourseTermNotes":{},"prereq_text":{},"coreq_text":{},"SectionData":[ {"id":"14214","session":"001","dclass_code":"R","title":"Advanced Enterprise Systems and Technologies","section_title":{},"description":"Section 14214 - For MAcc\/MBT student ONLY Section 14215 - For MBA students ONLY","notes":{},"type":"Lec","units":"3","spaces_available":"36","number_re gistered":"28","wait_qty":"0","canceled":"N","blackboard":"Y","comment":{}," day":"TH","start_time":"11:00","end_time":"12:20","location":"JKP104","instr uctor":[{"last_name":"O\'Leary","first_name":"Daniel"},{"last_name":"Maxey", "first_name":"Shirley"}],"syllabus":{"format":{},"filesize":{}},"IsDistanceL earning":"N"},{"id":"14215","session":"033","dclass_code":"R","title":"Advan ced Enterprise Systems and Technologies","section_title":{},"description":"This section (14215) is for MBA students only. Graduate accounting students must register for ACCT-549, section 14214.","notes":{},"type":"Lec","units":"3","spaces_available":"20","number_ registered":"0","wait_qty":"0","canceled":"N","blackboard":"Y","comment":{}, "day":"TH","start_time":"11:00","end_time":"12:20","location":"JKP104","inst ructor":{"last_name":"O\'Leary","first_name":"Daniel"},"syllabus":{"format": {},"filesize":{}},"IsDistanceLearning":"N"}]}},{"IsCrossListed":"N","Publish edCourseID":"ACCT-550T","ScheduledCourseID":"ACCT-550T","CourseData":{"prefi x":"ACCT","number":"550","sequence":"T","suffix":{},"title":"Tax Research and Practice","description":"Tax law research methods; interpreting statutes, cases, and rulings; communicating research results; administration and professional responsibilities of tax practice. Recommended preparation: introductory tax course.","units":"3","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": {},"coreq_text":{},"SectionData":{"id":"14216","session":"431","dclass_code" :"D","title":"Tax Research and Practice","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"3","spaces_available":"54","number_registered":"55","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"09:30","end_ time":"12:20","location":"JKP202","instructor":{"last_name":"Mills","first_n ame":"Patricia"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-551T","ScheduledCours eID":"ACCT-551T","CourseData":{"prefix":"ACCT","number":"551","sequence":"T" ,"suffix":{},"title":"Taxation of Partnerships and S-Corps",' aaa=aaa+'"description":"Federal taxation of flow-through entities, including: partnerships, S corporations, limited liability partnerships (LLPs), and limited liability companies (LLCs).","units":"3","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": "1 from (ACCT-550T or ACCT-560T or LAW-600)","coreq_text":{},"SectionData":[{"id":"14220","session":"001","dcla ss_code":"R","title":"Taxation of Partnerships and S-Corps","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"41","number_registered":"33","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"T","start_time":"18:30","end_ti me":"21:30","location":"BRI202","instructor":{"last_name":"Mills","first_nam e":"Patricia"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"},{"id":"14221","session":"442","dclass_code":"D","title":"Taxation of Partnerships and S-Corps","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"54","number_registered":"55","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"09:30","end_t ime":"12:20","location":"JKP202","instructor":{"last_name":"Mills","first_na me":"Patricia"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-560T","ScheduledCours eID":"ACCT-560T","CourseData":{"prefix":"ACCT","number":"560","sequence":"T" ,"suffix":{},"title":"Tax Theory and Its Business Applications","description":"Taxation and its relationship to business and investment decisions; the effects of taxation on business organization, capital structure, policies, operation, and expansion. Recommended preparation: introductory tax course.","units":"3","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": {},"coreq_text":{},"SectionData":[{"id":"14230","session":"001","dclass_code ":"R","title":"Tax Theory and Its Business Applications","section_title":{},"description":"Section 14231 meets 8\/25 - 10\/15 Last day to add\/drop without a W is 9\/2","notes":{},"type":"Lec","units":"3","spaces_available":"54","number_re gistered":"55","wait_qty":"0","canceled":"N","blackboard":"Y","comment":{}," day":"W","start_time":"18:30","end_time":"21:30","location":"JKP202","instru ctor":[{"last_name":"Barcal","first_name":"Jack"},{"last_name":"Maxey","firs t_name":"Shirley"}],"syllabus":{"format":{},"filesize":{}},"IsDistanceLearni ng":"N"},{"id":"14231","session":"431","dclass_code":"D","title":"Tax Theory and Its Business Applications","section_title":{},"description":{},"notes":{},"type":"Lec","u nits":"3","spaces_available":"54","number_registered":"55","wait_qty":"0","c anceled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"09:30"," end_time":"12:20","location":"JKP202","instructor":[{"last_name":"Barcal","f irst_name":"Jack"},{"last_name":"Maxey","first_name":"Shirley"}],"syllabus": {"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"IsCrossListed":"N ","PublishedCourseID":"ACCT-561T","ScheduledCourseID":"ACCT-561T","CourseDat a":{"prefix":"ACCT","number":"561","sequence":"T","suffix":{},"title":"Incom e Tax of Corporations and Their Shareholders","description":"Concepts and principles governing the taxation of corporations and their shareholders; the effect of taxes on corporate formation, capital structure, distributions, and liquidations.","units":"3","restriction_by_major":{},"restriction_by_class": {},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_ text":"1 from (ACCT-550T or ACCT-560T or LAW-600)","coreq_text":{},"SectionData":{"id":"14234","session":"442","dclas s_code":"D","title":"Income Tax of Corporations and Their Shareholders","section_title":{},"description":{},"notes":{},"type":"Lec","u nits":"3","spaces_available":"54","number_registered":"55","wait_qty":"0","c anceled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"09:30"," end_time":"12:20","location":"JKP202","instructor":{"last_name":"Keller","fi rst_name":"Joseph"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearni ng":"N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-568T","ScheduledCo urseID":"ACCT-568T","CourseData":{"prefix":"ACCT","number":"568","sequence": "T","suffix":{},"title":"Taxation of Foreign Business Operations","description":"Taxation of foreign income of U.S. citizens and corporations and of U.S. source income of foreign persons and corporations; planning for organization of foreign operations under the tax laws.","units":"3",' aaa=aaa+'"restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Law","restriction_by_class":{},"restriction_by_school":{},"CourseNotes":{}," CourseTermNotes":{},"prereq_text":"ACCT-561T","coreq_text":{},"SectionData": {"id":"14246","session":"001","dclass_code":"D","title":"Taxation of Foreign Business Operations","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"3","spaces_available":"1","number_registered":"0","wait_qty":"0","cance led":"Y","blackboard":"Y","comment":{},"day":"H","start_time":"18:30","end_t ime":"21:30","location":{},"instructor":{"last_name":"Sylvester","first_name ":"Michael"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-572","ScheduledCourseID": "ACCT-572","CourseData":{"prefix":"ACCT","number":"572","sequence":{},"suffi x":{},"title":"Corporate Accounting and Reporting","description":"A study of financial reporting and disclosure issues with an emphasis on the use of corporate financial statements and their accompanying footnotes. Not open to students with credit in equivalent subjects.","units":"3","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":"GSBA-510","coreq_text":{},"SectionData":[{"id":"14254","session":"033","d class_code":"R","title":"Corporate Accounting and Reporting","section_title":{},"description":{},"notes":{},"type":"Lec","unit s":"3","spaces_available":"56","number_registered":"51","wait_qty":"0","canc eled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"09:30","end _time":"10:50","location":"JKP104","instructor":{"last_name":"Trezevant","fi rst_name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearni ng":"N"},{"id":"14256","session":"033","dclass_code":"R","title":"Corporate Accounting and Reporting","section_title":{},"description":{},"notes":{},"type":"Lec","unit s":"3","spaces_available":"39","number_registered":"36","wait_qty":"0","canc eled":"N","blackboard":"Y","comment":{},"day":"M","start_time":"18:30","end_ time":"21:30","location":"ACC236","instructor":{"last_name":"Trezevant","fir st_name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearnin g":"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-574","ScheduledCou rseID":"ACCT-574","CourseData":{"prefix":"ACCT","number":"574","sequence":{} ,"suffix":{},"title":"Accounting in the Global Business Environment","description":"Study of national and international accounting and business issues; global capital market changes; international accounting and business topics; cases and studies of specific business entities and countries.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Business Administration, Law, Juris Doctor\/Business Administration, Business Administration\/Industrial & Systems Engineering, Business Administration\/Pharmacy, Gerontology\/Business Administration, Nursing\/Business Administration, Business Administration\/Dental Surgery, Information and Operations Management, Business Administration\/East Asian Area Studies, Medicine\/Business Administration, Business Administration\/Jewish Communal Service, Business Administration\/Planning, Business Administration\/Real Estate Development","restriction_by_class":{},"restriction_by_school":{},"CourseNot es":{},"CourseTermNotes":{},"prereq_text":"1 from (GSBA-510 or GSBA-518 or GSBA-536)","coreq_text":{},"SectionData":[{"id":"14260","session":"001","dcl ass_code":"D","title":"Accounting in the Global Business Environment","section_title":{},"description":{},"notes":{},"type":"Lec","un its":"3","spaces_available":"42","number_registered":"30","wait_qty":"0","ca nceled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","e nd_time":"15:20","location":"JKP202","instructor":{"last_name":"Hung","first _name":"Mingyi"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14261","session":"001","dclass_code":"D","title":"Accounting in the Global Business Environment","section_title":{},"description":{},"notes":{},"type":"Lec","un its":"3","spaces_available":"42","number_registered":"42","wait_qty":"0","ca nceled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"12:30","e nd_time":"13:50","location":"JKP202","instructor":{"last_name":"Hung","first _name":"Mingyi"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-578T","ScheduledCour seID":"ACCT-578T","CourseData":{"prefix":"ACCT","number":"578",' aaa=aaa+'"sequence":"T","suffix":{},"title":"Advanced Corporate Taxation","description":"Analysis of corporate divisions and reorganizations, carryovers, and other advanced topics in corporate taxation.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Law","restriction_by_class":{},"restriction_by_school":{},"CourseNotes":{}," CourseTermNotes":{},"prereq_text":"ACCT-561T","coreq_text":{},"SectionData": {"id":"14268","session":"001","dclass_code":"R","title":"Advanced Corporate Taxation","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"3","spaces_available":"34","number_registered":"9","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"H","start_time":"18:30","end_ti me":"21:30","location":"BRI202","instructor":{"last_name":"Keller","first_na me":"Joseph"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-580T","ScheduledCourseID ":"ACCT-580T","CourseData":{"prefix":"ACCT","number":"580","sequence":"T","s uffix":{},"title":"Accounting Methods","description":"An analysis of Subchapter E and related provisions of the Internal Revenue Code and of the relationships between tax and financial accounting.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Law","restriction_by_class":{},"restriction_by_school":{},"CourseNotes":{}," CourseTermNotes":{},"prereq_text":"ACCT-550T and 1 from (ACCT-560T or LAW-600)","coreq_text":{},"SectionData":[{"id":"14273","session":"001","dcla ss_code":"R","title":"Accounting Methods","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"35","number_registered":"8","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"W","start_time":"18:30","end_tim e":"21:30","location":"BRI202","instructor":{"last_name":"Scharlach","first_ name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"},{"id":"14274","session":"001","dclass_code":"R","title":"Accounting Methods","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"25","number_registered":"1","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"W","start_time":"18:30","end_tim e":"21:30","location":"OCC","instructor":{"last_name":"Scharlach","first_nam e":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-582","ScheduledCourseID" :"ACCT-582","CourseData":{"prefix":"ACCT","number":"582","sequence":{},"suff ix":{},"title":"Accounting for Mergers and Acquisitions","description":"Theoretical and practical problems in accounting for business combinations: purchase and pooling-of-interests accounting; consolidated financial statements; income tax considerations; Intrnational Accounting Standards.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Business Administration","restriction_by_class":{},"restriction_by_school":{},"Course Notes":{},"CourseTermNotes":{},"prereq_text":"GSBA-510","coreq_text":{},"Sec tionData":[{"id":"14288","session":"001","dclass_code":"D","title":"Accounti ng for Mergers and Acquisitions","section_title":{},"description":{},"notes":{},"type":"Lec","u nits":"3","spaces_available":"41","number_registered":"36","wait_qty":"0","c anceled":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:30"," end_time":"13:50","location":"JKP202","instructor":[{"last_name":"Trezevant" ,"first_name":"Robert"},{"last_name":"Wang","first_name":"Shiing-Wu"}],"syll abus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},{"id":"14289","s ession":"001","dclass_code":"D","title":"Accounting for Mergers and Acquisitions","section_title":{},"description":{},"notes":{},"type":"Lec","u nits":"3","spaces_available":"40","number_registered":"34","wait_qty":"0","c anceled":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00"," end_time":"15:20","location":"JKP202","instructor":[{"last_name":"Trezevant" ,"first_name":"Robert"},{"last_name":"Wang","first_name":"Shiing-Wu"}],"syll abus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"IsCrossList ed":"N","PublishedCourseID":"ACCT-583","ScheduledCourseID":"ACCT-583","Cours eData":{"prefix":"ACCT","number":"583","sequence":{},"suffix":{},' aaa=aaa+'"title":"Accounting for Income Taxes","description":"Examination of the roles of auditors, tax professionals and corporate financial personnel in preparing, analyzing and reviewing the accrual of income taxes in financial statements. Open to M.B.T., M.Acc. and M.B.A. students only.","units":"3","restriction_by_major":" Registration open to the following major(s): Business Taxation, Accounting, Business Administration","restriction_by_class":{},"restriction_by_school":{},"Course Notes":{},"CourseTermNotes":{},"prereq_text":"(ACCT-544 and ACCT-572)","coreq_text":{},"SectionData":{"id":"14290","session":"001","dcla ss_code":"R","title":"Accounting for Income Taxes","section_title":{},"description":{},"notes":{},"type":"Lec","units":" 3","spaces_available":"30","number_registered":"16","wait_qty":"0","canceled ":"N","blackboard":"Y","comment":{},"day":"M","start_time":"18:30","end_time ":"21:30","location":"BRI202","instructor":[{"last_name":"Keller","first_nam e":"Joseph"},{"last_name":"Mills","first_name":"Jim"}],"syllabus":{"format": {},"filesize":{}},"IsDistanceLearning":"N"}}},{"IsCrossListed":"N","Publishe dCourseID":"ACCT-590","ScheduledCourseID":"ACCT-590","CourseData":{"prefix": "ACCT","number":"590","sequence":{},"suffix":{},"title":"Directed Research","description":"Research leading to the master\'s degree. Maximum units which may be applied to the degree to be determined by the School of Accounting. Graded CR\/NC.","units":"1-4","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Law","restriction_by_class":{},"restriction_by_school":{},"CourseNotes":{}," CourseTermNotes":{},"prereq_text":{},"coreq_text":{},"SectionData":{"id":"14 300","session":"001","dclass_code":"D","title":"Directed Research","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"1-4","spaces_available":"10","number_registered":"0","wait_qty":"0","canc eled":"N","blackboard":"N","comment":{},"day":{},"start_time":"TBA","end_tim e":"TBA","location":"OFFICE","instructor":{"last_name":"Maxey","first_name": "Shirley"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}} },{"IsCrossListed":"N","PublishedCourseID":"ACCT-597","ScheduledCourseID":"A CCT-597","CourseData":{"prefix":"ACCT","number":"597","sequence":{},"suffix" :{},"title":"Business Field Project in Accounting","description":"Individual or team projects solving real business problems for companies; situation analyses; research proposal composition; field research techniques; statistical analysis; oral and written presentations. Graded CR\/NC.","units":"1-6","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":{},"coreq_text":{},"SectionData":{"id":"14302","session":"033","dclass_cod e":"D","title":"Business Field Project in Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"1-6","spaces_available":"50","number_registered":"0","wait_qty":"0","ca nceled":"N","blackboard":"N","comment":{},"day":{},"start_time":"TBA","end_t ime":"TBA","location":"OFFICE","instructor":{"last_name":"Beatty","first_nam e":"Randolph"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-602","ScheduledCourseID ":"ACCT-602","CourseData":{"prefix":"ACCT","number":"602","sequence":{},"suf fix":{},"title":"Survey of Judgment and Decision-Making Research in Accounting","description":"Survey of major topics in judgment and decision-making research in accounting with coverage of both key research questions and frequently used methods. Departmental approval.","units":"3","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":{},"coreq_text":{},"SectionData":{"id":"14310","session":"036","dclass_cod e":"D","title":"Survey of Judgment and Decision-Making Research in Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"3","spaces_available":"5","number_registered":"5","wait_qty":"0","cance led":"N","blackboard":"N","comment":{},"day":"F","start_time":"09:00","end_t ime":"11:50","location":"ACC312","instructor":{"last_name":"Bonner","first_n ame":"Sarah","bio_url":"http:\/\/mymarshall.usc.edu\/portal\/subapps\/digita lmeasures\/faculty.jsp?surveyId=48731"},"syllabus":{"format":{},"filesize":{ }},"IsDistanceLearning":"N"}}},' aaa=aaa+'{"IsCrossListed":"N","PublishedCourseID":"ACCT-611","ScheduledCours eID":"ACCT-611","CourseData":{"prefix":"ACCT","number":"611","sequence":{}," suffix":{},"title":"Selected Topics in Accounting Research","description":"Advanced Seminar to address issues\/topics covered in accounting research forums presented by USC and visiting faculty.","units":"1, 4","restriction_by_major":{},"restriction_by_class":{},"restriction_by_schoo l":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text":{},"coreq_text":{} ,"SectionData":{"id":"14321","session":"036","dclass_code":"D","title":"Sele cted Topics in Accounting Research","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"1","spaces_available":"20","number_registered":"12","wait_qty":"0","cance led":"N","blackboard":"N","comment":{},"day":"F","start_time":"12:30","end_t ime":"13:20","location":"ACC312","instructor":{"last_name":"Hung","first_nam e":"Mingyi"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }}}]}}' print "aa = ",aaa print "\n\n\n\n\n\n" if __name__ == "__main__": # main app txdata = None json.dumps(aaa) print "foo" sys.exit() From fredrik at pythonware.com Mon Sep 15 11:33:12 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 17:33:12 +0200 Subject: ElementTree oddities In-Reply-To: References: Message-ID: Brian Cole wrote: > However, it's missing some of the text. For example, the following > XML: > >>>> xml = "Bar" > > Returns me a empty string. Seems the "" tag is borking it. > > > Also, the for the following XML: >>>> xml = "Bar:" > > I only get "Bar". It's missing the trailing colon. > > I'm not that experienced with XML so perhaps I am just missing > something here. Please enlighten me. you're missing the "tail" attribute, which contains text that follows directly *after* the element's end tag. it's not exactly a one-liner, but I usually use the one on this page: http://effbot.org/zone/element-bits-and-pieces.htm#gettext From dblubaugh at belcan.com Tue Sep 30 14:19:59 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 30 Sep 2008 14:19:59 -0400 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <48E264CC.4050701@mwalsh.org> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> <48E264CC.4050701@mwalsh.org> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9A2B@AWMAIL04.belcan.com> Yes, I new it was a directory issue. I am new to Python. Thank You David Blubaugh -----Original Message----- From: Martin Walsh [mailto:mwalsh at mwalsh.org] Sent: Tuesday, September 30, 2008 1:42 PM To: python-list at python.org Subject: Re: OS.SYSTEM ERROR !!! Blubaugh, David A. wrote: > To All, > > I have been attempting to execute the following program within the > Python environment: > > However, when I would try to execute the following lines of source > code within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? Based on your description, it seems pretty obvious (and easy to confirm) that Myprogram.exe needs to be run from its containing directory ("C:\myprogramfolder\run"). Try something like this... import os pwd = os.getcwd() os.chdir('c:/myprogramfolder/run') os.system("Myprogram.exe 1 1 acc 0") os.chdir(pwd) HTH, Marty This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From robert.kern at gmail.com Tue Sep 9 20:00:21 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Sep 2008 19:00:21 -0500 Subject: Looking for a Duo - file comparison and a file parser In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > HI, > > I'm thinking of writing a file comparison utility in python. This > utility will work as: > > 1. Compare 2 files for the differences. Both files contain some > numerical results. > 2. Generate a common file containing the differences (the same way as > 'diff' generate an output) > 3. Now, I will parse this file containing differences to check as to how > much is the difference of one file from other. So, for this I hope a > parser will be required. > > Is there a utility available that performs similar job ( that some one > might have created considering the huge number of users of python) ? > > Or may be some one has written some parser? There are a couple of ways to do #3. One would be to use the difflib module from the standard library. The Differ.compare() method will give you a sequence of lines with prefixed character saying whether the line was the same in both files, deleted from the first or added by the second. Lines that are recognized as having changed (rather than just being deleted then readded with modifications) are also noted. The parsing you would have to do would be minimal. http://docs.python.org/dev/library/difflib Or you could use diff and diffstat: http://invisible-island.net/diffstat/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From grante at visi.com Sat Sep 27 10:10:49 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 27 Sep 2008 09:10:49 -0500 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: On 2008-09-27, Lawrence D'Oliveiro wrote: > In message , Grant > Edwards wrote: > >> On 2008-09-26, Lawrence D'Oliveiro >> wrote: >>> In message , Grant Edwards >>> wrote: >>> >>>> Never assume somebody reading the article and attempting to >>>> help you can see the subject line. >>> >>> Why not? >> >> Because it might not be. It depends on the user's newsreader >> and editor settings. > > So, should I not assume that they can see the content as well, > because it might not be visible, depending on the user's > newsreader and editor settings? Thats seems like a bit of reductio ad absurdum. My observations over the years confirm the advice that you shouldn't place information solely in the subject line. If you rely on people re-reading the subject line as the read and reply to the body of the posting, you'll often get bad results. People will miss information that was left out of the body and placed solely in the subject line. I've seen it happen over an over again (this thread is an example). If you don't care whether you get timely and accurate responses, then do whatever you want. Otherwise, include all the pertinent information in the body of the posting. -- Grant From wuwei23 at gmail.com Sun Sep 7 23:48:14 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 7 Sep 2008 20:48:14 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: <4b869278-0303-4c41-aacb-e3d497c33351@l33g2000pri.googlegroups.com> Fredrik Lundh wrote: > (btw, I've always thought that Python was all about making it easy to > express the solution to a given problem in code, not to let you write > programs without using your brain. ?when did that change?) The day Google App Engine was opened up to developers, I believe. From almar.klein at gmail.com Tue Sep 30 05:38:22 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 30 Sep 2008 11:38:22 +0200 Subject: can someone explain why this happens- newbie question In-Reply-To: References: Message-ID: change: for score in scores: print scores to: for score in scores: print score that should do the trick :) Almar 2008/9/30 garywood > Hi > can someone tell me why it prints the high score table multiple times? > > #high scores program > scores =[] > choice = None > > while choice != 0: > print """high Score Table > 0 - exit > 1 - show Scores > 2 - add a score > 3 - delete a score > 4 - sort scores > """ > choice = input("what would you like to do?") > if choice == 0: > print "goodbye" > elif choice == 1: > for score in scores: > print scores > elif choice == 2: > score = input("add a score") > scores.append(score) > elif choice == 3: > score = input("what score would you like to delete ?") > if score in scores: > scores.remove(score) > else: > print "that score is not listed" > > > elif choice == 4: > scores.sort() > scores.reverse() > print scores, "highest score first" > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rokwok at newsguy.com Thu Sep 25 04:02:01 2008 From: rokwok at newsguy.com (Ronnie Kwok) Date: 25 Sep 2008 01:02:01 -0700 Subject: Connecting to SMB share in python Message-ID: Hello, I am trying to write a script that copy files from my local machine to a samba share. I've notice a library call Pysamba which is a wrapper on smb service but it requires a compilation of SAMBA with some amendment in order to use it. Are there alternative method that I could do the same thing? Thank you for your advise. ronnie From skip at pobox.com Mon Sep 15 20:49:06 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 15 Sep 2008 19:49:06 -0500 Subject: Decompile python2.5-pyc In-Reply-To: <9DE19AF2-1E2B-4914-BA51-9E230CB238DE@uos.de> References: <9DE19AF2-1E2B-4914-BA51-9E230CB238DE@uos.de> Message-ID: <18639.642.956362.833575@montanaro-dyndns-org.local> >>>>> "Manuel" == Manuel Ebert writes: Manuel> Does anybody know something I don't, some home-brewn decompiler, Manuel> anything? I *am* quite desperate... Well... If you have some time and are desperate, you might try importing the module(s) then disassembling them with the dis module. The output will still be Python's virtual machine assembly, but at least it will be sort of readable. You might be able to manually translate it back to the equivalent Python source code. For example: >>> def f(a): ... a.append(7) ... if len(a) > 5: ... del a[0] ... >>> import dis >>> dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 LOAD_ATTR 0 (append) 6 LOAD_CONST 1 (7) 9 CALL_FUNCTION 1 12 POP_TOP 3 13 LOAD_GLOBAL 1 (len) 16 LOAD_FAST 0 (a) 19 CALL_FUNCTION 1 22 LOAD_CONST 2 (5) 25 COMPARE_OP 4 (>) 28 JUMP_IF_FALSE 11 (to 42) 31 POP_TOP 4 32 LOAD_FAST 0 (a) 35 LOAD_CONST 3 (0) 38 DELETE_SUBSCR 39 JUMP_FORWARD 1 (to 43) >> 42 POP_TOP >> 43 LOAD_CONST 0 (None) 46 RETURN_VALUE Skip From mail.anand.anand at gmail.com Tue Sep 30 05:17:50 2008 From: mail.anand.anand at gmail.com (aathi) Date: Tue, 30 Sep 2008 02:17:50 -0700 (PDT) Subject: Welcome to US Computer Jobs Message-ID: <9d06d79d-ff84-4ca0-9ac2-fcc982656620@e53g2000hsa.googlegroups.com> Welcome to US Computer Jobs Windows System Engineer Phone and Inperson Interview http://geocities.com/anandrisks/ http://friendfinder.com/go/g959922 http://amigos.com/go/g959922 From pete.forman at westerngeco.com Wed Sep 24 13:16:14 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 24 Sep 2008 18:16:14 +0100 Subject: python syntax for conditional is unfortunate References: Message-ID: Asun Friere writes: > A canonical use of the conditional operator is in > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). That fails for n == 1. So what is best? for i in range(4): print '%d thing' % i + ('s' if i != 1 else '') for i in range(4): print '%d thing%s' % (i, ('s', '')[i==1]) for i in range(4): print '%d thing%s' % (i, 's' if i != 1 else '') -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From lists at cheimes.de Wed Sep 10 15:21:28 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 21:21:28 +0200 Subject: Simple UDP server In-Reply-To: <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> Message-ID: Tzury Bar Yochay wrote: > So what if it is connectionless. > It would make sense if you get a load of users who sends large sets of > binary data to each other. Transmitting large binary data over UDP? That makes only sense for few applications like video and audio streaming. UDP does neither guarantee that your data is received nor it's received in order. For example the packages A, B, C, D might be received as A, D, B (no C). Can your protocol handle missing packages and out of order packages? Christian From clp at rebertia.com Wed Sep 24 22:55:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 24 Sep 2008 19:55:57 -0700 Subject: Off topic: Sent from my Foo messages In-Reply-To: <00eaf368$0$20666$c3e8da3@news.astraweb.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <00eaf368$0$20666$c3e8da3@news.astraweb.com> Message-ID: <47c890dc0809241955m1214f464m3fcf078d07b18d53@mail.gmail.com> On Wed, Sep 24, 2008 at 7:38 PM, Steven D'Aprano wrote: > I'm seeing more and more posts from various people, on this list and > others, with statements like the following: > > On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote: > >> Sent from my iPhone > > Also "Sent from my Blackberry" and similar. > > Without wishing to be rude to David, who I'm sure is a nice guy and not > at all the pretentious git that such a line makes him appear, are people > adding this comment to the bottom of their posts, or is it something that > their device automatically appends to the post? It's on by default for the iPhone/iTouch but there's a setting to change the signature (including to nothing). Don't know about the Blackberry. > > If people are adding it themselves, that's nice, I'm sure you're really > excited about your new toy, but the rest of us don't care a monkey's > toss. And if the device is automatically appending it, I think that's > pretty damn rude and a good reason to avoid buying the obnoxious machines. Eh, that's a bit extreme; though I admit it can sometimes be annoying (but not very much). Regards, Chris Sent using a Computer, the Internet, Gmail, Firefox, unix, glibc, ... ;P > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From fredrik at pythonware.com Fri Sep 5 04:55:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 10:55:56 +0200 Subject: derived classes and __getattr__ In-Reply-To: References: Message-ID: Alexandru Mos,oi wrote: > i'm facing the following problem: > > class Base(object): > def __getattr__(self, attr): return lambda x: attr + '_' + x > > def dec(callable): > return lambda *args: 'dec_' + callable(*args) > > class Derived(Base): > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have > what_so_ever > mumu = dec(Base.mumu) # wrong, base > doesn't have mumu > > any idea how to do this? ever thought of using Python to write Python programs? From uzmanajmal at gmail.com Wed Sep 17 06:42:05 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Wed, 17 Sep 2008 10:42:05 +0000 Subject: File Reading related query In-Reply-To: References: Message-ID: I am talking about text file which contain multiple lines e.g following three lines are there in my textfile.txt this is python list where we get support from geeks I want sentence = this is python list where we get support from geeks whereas when i use simple read() i get something like this sentence = this is python list\nwhere we get support\nfrom geeks On Wed, Sep 17, 2008 at 10:18 AM, Fredrik Lundh wrote: > Usman Ajmal wrote: > > Is there any function for reading a file while ignoring *\n* occuring in >> the file? >> > > can you be a bit more precise? are we talking about text files or binary > files? how do you want to treat any newlines that actually appear in the > file? > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kalin at el.net Wed Sep 17 13:40:12 2008 From: kalin at el.net (kalin m) Date: Wed, 17 Sep 2008 13:40:12 -0400 Subject: locks Message-ID: <48D140FC.8070801@el.net> hi all... mailman has been locking one list out. the web interface just hangs and it generates a bunch of locks. it seems that it can not write to a log but not sure which one. errors are like: ep 17 05:09:12 2008 (18481) musiclist.lock lifetime has expired, breaking Sep 17 05:09:12 2008 (18481) File "/var/mailman/bin/qrunner", line 270, in ? Sep 17 05:09:12 2008 (18481) main() Sep 17 05:09:12 2008 (18481) File "/var/mailman/bin/qrunner", line 230, in main Sep 17 05:09:12 2008 (18481) qrunner.run() Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/Queue/Runner.py", line 70, in run Sep 17 05:09:12 2008 (18481) filecnt = self._oneloop() Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/Queue/Runner.py", line 111, in _oneloop Sep 17 05:09:12 2008 (18481) self._onefile(msg, msgdata) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/Queue/Runner.py", line 167, in _onefile Sep 17 05:09:12 2008 (18481) keepqueued = self._dispose(mlist, msg, msgdata) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/Queue/IncomingRunner.py", line 115, in _dispose Sep 17 05:09:12 2008 (18481) mlist.Lock(timeout=mm_cfg.LIST_LOCK_TIMEOUT) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/MailList.py", line 159, in Lock Sep 17 05:09:12 2008 (18481) self.__lock.lock(timeout) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/LockFile.py", line 306, in lock Sep 17 05:09:12 2008 (18481) important=True) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/LockFile.py", line 416, in __writelog Sep 17 05:09:12 2008 (18481) traceback.print_stack(file=logf) Sep 17 10:17:05 2008 (19547) musiclist.lock lifetime has expired, breaking Sep 17 10:17:06 2008 (19547) File "/var/mailman/cron/checkdbs", line 178, in ? Sep 17 10:17:06 2008 (19547) main() Sep 17 10:17:06 2008 (19547) File "/var/mailman/cron/checkdbs", line 84, in main Sep 17 10:17:06 2008 (19547) mlist = MailList.MailList(name) Sep 17 10:17:06 2008 (19547) File "/var/mailman/Mailman/MailList.py", line 126, in __init__ Sep 17 10:17:06 2008 (19547) self.Lock() Sep 17 10:17:06 2008 (19547) File "/var/mailman/Mailman/MailList.py", line 159, in Lock Sep 17 10:17:06 2008 (19547) self.__lock.lock(timeout) Sep 17 10:17:06 2008 (19547) File "/var/mailman/Mailman/LockFile.py", line 306, in lock Sep 17 10:17:06 2008 (19547) important=True) Sep 17 10:17:06 2008 (19547) File "/var/mailman/Mailman/LockFile.py", line 416, in __writelog Sep 17 10:17:06 2008 (19547) traceback.print_stack(file=logf) all other lists appear to be working fine.... thanks.... From roy at panix.com Sat Sep 27 08:34:57 2008 From: roy at panix.com (Roy Smith) Date: Sat, 27 Sep 2008 08:34:57 -0400 Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> <40efa068-688c-4dcf-b11e-938c0d4d006a@w39g2000prb.googlegroups.com> Message-ID: In article <40efa068-688c-4dcf-b11e-938c0d4d006a at w39g2000prb.googlegroups.com>, alex23 wrote: > ' '.join((str(x * x) for x in range(1,6))) Aren't the outer set of parens redundant? This works just as well: ' '.join(str(x * x) for x in range(1,6)) From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 5 09:09:31 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 05 Sep 2008 15:09:31 +0200 Subject: derived classes and __getattr__ In-Reply-To: <12c58ddc-5d45-4323-b268-6815fe5cb86d@z6g2000pre.googlegroups.com> References: <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> <12c58ddc-5d45-4323-b268-6815fe5cb86d@z6g2000pre.googlegroups.com> Message-ID: <48c12f1f$0$316$426a74cc@news.free.fr> Alexandru Mosoi a ?crit : (snip) > i somehow fixed the problem using: > > def __getattr__(self, attr): > return > functools.partial(Base.__metaclass__.__getattr__(self.__class__, > attr), self) > > however this looks ugly enough to look for another solution. i still > have one more question: why do I have to bind self? (without which > functions fail expecting an instance) Because the partial type doesn't implement the descriptor protocol (which is implemented by function type to return a method). From mail at microcorp.co.za Sat Sep 20 17:14:26 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 20 Sep 2008 23:14:26 +0200 Subject: Ascii Menu I/O redirection Message-ID: <002f01c91b66$0bdfcbc0$0d00a8c0@hendrik> I am writing a small application with a simple ascii based menu. The menu is used to test individual functions, and to change some timings. Otherwise the application just runs automatically, depending on command line options. I want to be able to redirect the menu. The console, a serial port, or possibly a socket are target candidates. Now a serial port and a socket are single files, so I need a "file" that represents the console, to pass to the working functions. Simply re-assigning for instance sys.stdin.write to point to sys.stdout.write, and using sys.stdin as such a file does not work... So I do the following: class console(object): """ This spoofs a single file like object, using stdout & - in (Minimalistic proof of concept implementation) """ def __init__(self): self.read = sys.stdin.read self.readline = sys.stdin.readline self.write = sys.stdout.write self.flush = sys.stdout.flush self.closeout = sys.stdout.close # keep references to close self.closein = sys.stdin.close def close(self): self.closein() self.closeout() # see if we must run, and how: if __name__ == "__main__": if 'serial' in sys.argv: # for RS-232 i/o to terminal f = open('/dev/ttyS0','r+b') else: # console i/o f = console() sys.stderr = f # redirect errors sys.stdout = f # redirect printing sys.stdin = f # redirect raw_input stuff if 'menu' in sys.argv: # test and timing changes menu_loop(menu_dict,f) # (menu_dict is dispatch dict) else: # else just run the system autorun(menu_dict,f) The above just shows a choice between console and serial as an example - adding a socket option would be trivial. This all seems to work, but I am asking here before I take the trouble to turn it into production code, as I don't think it is exactly a new problem. Questions are: Is this a reasonable way of doing this kind of thing? Is there a canonical or better way of doing it? Am I missing something? Using Linux only. - Hendrik From cvrebert at gmail.com Fri Sep 12 15:45:20 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Fri, 12 Sep 2008 12:45:20 -0700 Subject: book example confusion In-Reply-To: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: <13B9374E-851B-495F-9908-1BFD6ABFD6AC@gmail.com> Note the parentheses after f1 and f2 in the second example. That's what calls the functions and causes them to be evaluated and run. - Chris Sent from my iPod On Sep 12, 2008, at 12:36 PM, byron wrote: > I am reading o'reilly's learning python (great book), but i came > across an example (pg 291, pdf) that I am not quite understanding the > reasoning for the author's explanation: > > if f1() or f2(): > > The author states that do to the nature of that expression, if f1() > returns True, f2() will not be evaluated.. which makes sense. His > quote: > > "Here, if f1 returns a true (or nonempty) value, Python will > never run f2." > > He then states: > > "To guarantee that both functions will be run, call them > before the 'or':" > > tmp1, tmp2 = f1(), f2() > if tmp1 or tmp2: > > Being that each function is an object, a name assignment to > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > the name is called.. so why would the latter example "run" both > functions as the author suggests? > -- > http://mail.python.org/mailman/listinfo/python-list From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 3 07:14:59 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 13:14:59 +0200 Subject: How to write verbose scripts In-Reply-To: <5a3c1c2e-6613-41a9-b132-e979f978b14a@t1g2000pra.googlegroups.com> References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <5a3c1c2e-6613-41a9-b132-e979f978b14a@t1g2000pra.googlegroups.com> Message-ID: <48be7153$0$17347$426a74cc@news.free.fr> John Machin a ?crit : > On Sep 3, 3:52 am, Mensanator wrote: >> On Sep 2, 11:55 am, Steven D'Aprano > >> if (p & 1)==1: >> print_evens = True >> else: >> print_evens = False >> if (p & 2)==2: >> print_odds = True >> else: >> print_odds = False >> if (p & 4)==4: >> print_debug = True >> else: >> print_debug = False > > No, no, no, you've taken "How to write verbose scripts" rather too > literally; KEYBOARD ! From castironpi at gmail.com Thu Sep 4 16:31:02 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 13:31:02 -0700 (PDT) Subject: why is self not passed to id()? References: Message-ID: On Sep 4, 3:26?pm, Ruediger wrote: > Hello! > > Executing following little program gives me an TypeError. > > What makes me wonder is that foo does get an argument passed while bar > doesn't. Can anyone explain why?????? > > Thanks > Ruediger > > class foo(list): > ? ? __hash__ = lambda x: id(x) > > class bar(list): > ? ? __hash__ = id > > _s_ = set() > _s_.add(foo()) > _s_.add(bar()) > > rue at linux:~> python test01.py > Traceback (most recent call last): > ? File "test01.py", line 9, in > ? ? _s_.add(bar()) > TypeError: id() takes exactly one argument (0 given) The answer is fairly technical. For member functions to be bound to instances, they are required to have a __get__ method (which takes instance and owner as parameters). 'id' does not. (Why does 'id' not have a __get__ method?) By contrast, >>> set.add >>> dir(_) ['__call__', '__class__', '__delattr__', '__doc__', '__get__', '__getattribute__ ', '__hash__', '__init__', '__name__', '__new__', '__objclass__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] 'set.add' does. From jason.scheirer at gmail.com Tue Sep 23 13:07:27 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Tue, 23 Sep 2008 10:07:27 -0700 (PDT) Subject: Linq to Python References: Message-ID: On Sep 23, 7:48?am, hrishy wrote: > Hi > > Will LINQ be ported to Python ? > > regards > Hrishy I think this question is more appropriate to ask on an IronPython development list -- LINQ is pretty solidly intertwined with .Net, and so you'll likely want to look at the .Net implementation of Python. From linkmaster032000 at gmail.com Fri Sep 19 18:42:57 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Fri, 19 Sep 2008 15:42:57 -0700 (PDT) Subject: curses.setsyx()? References: Message-ID: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> On Sep 19, 1:24?am, Tim Roberts wrote: > linkmaster032... at gmail.com wrote: > > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > >cursor. Any alternatives/solutions? > > Did you call doupdate after? ?setsyx just manipulates the data structures. > It takes a call to doupdate to force those changes to take effect visually. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. I added it and it still doesn't work. This is what I'm doing when I want to display the cursor and prepare it for input at 2,3: curses.echo() curses.curs_set(1) curses.setsyx(2,3) curses.doupdate() From bj_666 at gmx.net Sat Sep 13 04:25:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Sep 2008 08:25:46 GMT Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> Message-ID: <6j1boaFv9o6U1@mid.uni-berlin.de> On Sat, 13 Sep 2008 01:06:22 -0700, cnb wrote: > This must be because of implementation right? Shouldn't reduce be faster > since it iterates once over the list? doesnt sum first construct the > list then sum it? No it doesn't. Why should it? > also, using range instead of xrange doesnt seem to generate a > performance-penalty: (De)Allocating a list of length 100 isn't very slow. Try some million elements. And watch the memory consumption too. Ciao, Marc 'BlackJack' Rintsch From bluesmanu at gmail.com Wed Sep 24 05:31:33 2008 From: bluesmanu at gmail.com (bluesmanu at gmail.com) Date: Wed, 24 Sep 2008 02:31:33 -0700 (PDT) Subject: Python graphical library Message-ID: <3abb0519-7700-4d82-bdaa-e4b09ef1c483@t54g2000hsg.googlegroups.com> Hi all, I am looking for a python graphical library that would allow me to draw borderless windows, sort of like a notification frame showing up. I would also like to be able to make it transparent but I suppose that is very much desktop manager dependent. Thank you very much for the help. ET From castironpi at gmail.com Tue Sep 23 20:22:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 17:22:00 -0700 (PDT) Subject: Visualize class inheritance hierarchy References: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Message-ID: <103c5d06-fcfc-48ca-9c8a-aac4e2854bde@m36g2000hse.googlegroups.com> On Sep 23, 5:53?pm, Rob Kirkpatrick wrote: > Hi All, > > I just finished debugging some code where I needed to determine why > one subclass had a bound method and another did not. ?They had > different pedigree's but I didn't know immediately what the > differences were. > > I ended up walking the hierarchy, going back one class at a time > through the code, for the two subclasses (hierarchy ~7 classes deep > each) to see whom they inherited from. ?Short of writing this down on > paper, is there any way to graphically display the pedigree of an > object/class? ?"Graphically" can be text output to the terminal, don't > need anything special... > > I'm assuming this has been discussed before, but I'm lacking any > Google keywords that bring up the appropriate discussion. > > Cheers, > Rob If you're using new-style classes, check out the __mro__ member, which no doesn't show up in its dir(). Otherwise, we can try a settrace (frame.f_code.co_name has the name of the class being defined in a class statement) or accumulate some class statements with a custom 'parser' run in the module 'parser'. From fredrik at pythonware.com Fri Sep 5 02:30:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:30:44 +0200 Subject: Case-insensitive string compare? In-Reply-To: <200809050038.04108.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050038.04108.maric@aristote.info> Message-ID: Maric Michaud wrote: > You''ll often see for loops written like this : > > for i in (e for e in iterable if predicate(e)) : > ... luckily, I don't. most people, when faced with that problem, writes it in the obvious way: for i in iterable: if predicate(i): ... to avoid an extra iterator and save typing. From maric at aristote.info Wed Sep 3 19:20:42 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 4 Sep 2008 01:20:42 +0200 Subject: properties setting each other In-Reply-To: <48bee775$0$7236$426a34cc@news.free.fr> References: <48bee775$0$7236$426a34cc@news.free.fr> Message-ID: <200809040120.42909.maric@aristote.info> Le Wednesday 03 September 2008 19:38:13 Bruno Desthuilliers, vous avez ?crit?: > FWIW, if there's no computation on getting or setting value, you can > make it a plain attribute. Yes, this is the problem with these tiny examples, we don't know at which point we must simplify them... > > But while it's quite clear that in this example use case it would be > better ?to have only one property (weither square or value, depending on > which is the most often use), things are not always that simple in real > world code, and - as you mentionned - there may be times where you have > interdependant properties and really want to avoid recomputing the same > thing over and over. Now there's no one size fits all solution here - > it's an optimization problem, and as such depends on real use cases. Yes, my advice was exactly in that sense, it's an optimization problem, duplicating such a data is a caching mechanism, and should be done knowingly, in acceptance of all the complication it comes with. -- _____________ Maric Michaud From fredrik at pythonware.com Mon Sep 22 17:26:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Sep 2008 23:26:55 +0200 Subject: Tkinter 3000 WCK Install Problem In-Reply-To: <0dd2b0dc-f6cb-4b70-8f35-d50446fdd901@2g2000hsn.googlegroups.com> References: <0dd2b0dc-f6cb-4b70-8f35-d50446fdd901@2g2000hsn.googlegroups.com> Message-ID: garyr wrote: > I'm trying to install WCK. I downloaded and installed the Windows > executable for my Python version. It appeared to run OK. I then > downloaded the demo files but find that none run due to error: > ImportError: No module named _tk3draw. > I'm using ActivePython 2.3.5 on Windows XP Home. > What can I do to fix this problem? the error means that the interpreter cannot find the _tk3draw.pyd file. if you use the standard install location, it should be installed under C:\Python23\lib\site-packages you could try this: >>> import FixTk >>> import _tk3draw >>> _tk3draw.__file__ 'C:\\Python23\\lib\\site-packages\\_tk3draw.pyd' if this also gives you an error, search for _tk3draw.pyd on the disk. From fredrik at pythonware.com Wed Sep 17 02:30:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 08:30:14 +0200 Subject: how many objects are loaded for hello world? In-Reply-To: References: Message-ID: belred wrote: > i just read this blog about how many objects (types) are loaded for a > hello world program in C#. > > http://blogs.msdn.com/abhinaba/archive/2008/09/15/how-many-types-are-loaded-for-hello-world.aspx > > how can you find out how many are loaded for a python program: print > 'hello' types and objects are different things, though. to get an idea of how much stuff Python loads using upstart, do "python -vv script.py" or add import sys print len(sys.modules), "modules" print sys.modules.keys() to the end of the script. to get an idea of how many objects and types that are created at that point, add import gc print len(gc.get_objects()), "objects" print len(set(map(type, gc.get_objects()))), "types" this gives me 35 modules (including the gc module), 3219 objects and 26 distinct types -- but the above will miss things, so the true numbers are a bit higher. (you might be able to use a debug build to get more detailed information) From invalid at invalid Thu Sep 18 12:11:18 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 18 Sep 2008 11:11:18 -0500 Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: On 2008-09-18, Joe G (Home) wrote: > Hi All, > > Background >=================== > I have installed Python for windows today from the python web site .I also > installed pySerial using the Windows installer from the sourceforge web > site..... Both installs use the default directories. > > Phyton version : Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > v.1310 32 bit (Intel)] on win32 > > pySerial 2.4 July 6th > > > Problem : Errors Screen output >============================ >>>> import serial > > Traceback (most recent call last): > File "", line 1, in > import serial > File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in > > from serialwin32 import * > File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in > > import win32file # The base COM port and file IO functions. > ImportError: No module named win32file >>>> > > So it looks like Python can not see some of the modules Do you have the win32 modules installed? > Here's the active paths > >>>> print sys.path > ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', > 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', > 'C:\\Python25\\lib\\site-packages'] >>>> > > It seems that C:\Python25\Lib\site-packages\serial needs to be added to > the PYTHONPATH I don't see how you came to that conclusion. Is the "missing" module (win32file) located in C:\Python25\Lib\site-packages\serial? > QUESTION >============= > Q1. How do I add C:\Python25\Lib\site-packages\serial to the PYTHONPATH ? Dunno. > Q2. How do I check that I have installed pySerial corretly > (using the Windows installer) If you used the installer, you almost undoubtedly have it installed correctly. I think you're missing the win32 package. http://python.net/crew/mhammond/win32/Downloads.html -- Grant Edwards grante Yow! I'm not an Iranian!! at I voted for Dianne visi.com Feinstein!! From castironpi at gmail.com Sat Sep 20 13:42:26 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 10:42:26 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: On Sep 20, 5:14?am, Fredrik Lundh wrote: > Kay Schluehr wrote: > > Answer: if you want to define an entity it has to be defined inside a > > class. If you want to access an entity you have to use the dot > > operator. Therefore Java is OO but Python is not. > > you're satirising the quoted author's cargo-cultish view of object > orientation, right? > > If you define OO as implementation inheritance, then Java is not. It inherits interface only. Another possibility is, has a virtual function table. The fact that Python indexes by name doesn't disqualify it from that definition. I don't know if Java meets it. I don't think raw C structures would be included, and you can define function pointers in them. Wikipedia puts it decently: "mainly for OO programming, but with some procedural elements." From showellshowell at gmail.com Mon Sep 15 23:03:54 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Mon, 15 Sep 2008 20:03:54 -0700 (PDT) Subject: How to marshal objects to readable files? References: Message-ID: <86de3bf2-c5e6-4c2f-a775-1fef231b2965@l33g2000pri.googlegroups.com> On Sep 14, 8:28?am, nielinjie wrote: > Hi list: > I just want to marshal objects (instance of custom classes)to a human > *READABEL *file/string, and also, I want unmarshal it back. in xml > format or any other format. > Any advice? Which lib should I use? > Thanks a lot. I think YAML is the solution most targeted for your needs. To quote the website: "YAML is a human friendly data serialization standard for all programming languages." http://yaml.org/ If you're willing to sacrifice some readability for truly robust serialization, try pickle, which isn't horribly cryptic. If you want simplicity and AJAX interoperability, consider JSON. If you consider Python itself to be human readable, and if your security/performance situation does not preclude the use of eval(), consider the PrettyPrinter module. From shahmed at sfwmd.gov Thu Sep 11 09:40:21 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 11 Sep 2008 09:40:21 -0400 Subject: removing text string In-Reply-To: <514c0466-3142-43e7-abc6-f75fb139e25e@c65g2000hsa.googlegroups.com> References: <514c0466-3142-43e7-abc6-f75fb139e25e@c65g2000hsa.googlegroups.com> Message-ID: -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of bearophileHUGS at lycos.com Sent: Thursday, September 11, 2008 8:54 AM To: python-list at python.org Subject: Re: removing text string Ahmed, Shakir: > Actually the number I am getting it is from slicing from a long text > line. I need to slice 10 characters from that line but no string only > numeric numbers. When I am slicing 10 characters those A, c, O is coming > at the end. It's better to avoid Regular expressions when they aren't necessary, but once in a while they are the simpler way to solve a problem, you may create one like this (mostly untested): \d+?-\d+ Using it like: >>> import re >>> patt = re.compile(r"\d+?-\d+") >>> patt.search("xxxxxx080829-7_A xxxx").group() '080829-7' >>> re.search(r"\d+?-\d+", "xxxxxx080829-7_A xxxx").group() '080829-7' Learning Regexps can be useful. Bye, Bearophile Thanks, I got the clue. Very much appreciated. -- http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Thu Sep 11 03:18:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 09:18:56 +0200 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Usman Ajmal wrote: > And i also fount that a typical system.auth call will look like: > > POST /xmlrpc/clarens_server.py HTTP/1.0 > Host: localhost > User-Agent: xmlrpclib.py/0.9.9 (by www.pythonware.com ) > > Content-Type: text/xml > Content-Length: 105 > AUTHORIZATION: Basic MkhVTm9VazYxbXArVEZLS0dCY2tIRlA3bjVzPQo6RnJvbSBi > > > system.auth > > > > > > > Problem is that i don't know how do i generate above xml system.auth > call. Can anyone please tell me how do call a function, setting the > header of the call too? you need to plugin a custom transport. see this page for an example: http://www.python.org/doc/lib/xmlrpc-client-example.html in your case, it should be sufficient to override send_request, e.g. (untested): class SecureTransport(xmlrpclib.Transport): def set_authorization(self, ustring, text_ucert): self.authoriation = encodestring( "%s:%s" % (ustring,text_ucert) ) def send_request(self, connection, handler, request_body): connection.putrequest("POST", handler) connection.putheader("Authorization", "Basic %s" % self.authorization ) and instantiate the transport by doing t = SecureTransport() t.set_authorization(ustring, text_ucert) before passing to the server proxy. From watine at cines.fr Mon Sep 8 11:44:33 2008 From: watine at cines.fr (Benjamin Watine) Date: Mon, 08 Sep 2008 17:44:33 +0200 Subject: Files application architecture In-Reply-To: <48c1d6b2$0$15607$426a74cc@news.free.fr> References: <48c1d6b2$0$15607$426a74cc@news.free.fr> Message-ID: <48C54861.1000005@cines.fr> Bruno Desthuilliers a ?crit : > Benjamin Watine a ?crit : >> Hi, >> >> I'm about to develop a small python application and I wonder how to >> organize files in this application. >> I'm familar to java, so I'm tempted to use the same convention > > http://dirtsimple.org/2004/12/python-is-not-java.html > >> : 1 file per class and 1 folders per package. > > Don't. This is a waste of time and a pain to maintain, and more over it > doesn't make any sense since Python doesn't force you to put everything > in classes. > >> I know that packages doesn't exists in python, > > Did you actually read the doc ? While Python's packages are not the same > thing as Java's, they do exist. > > http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > >> they are modules instead. May I create specific module for each "group >> of class" ? > > The usual way to get cohesive modules is indeed to group closely related > objects (classes, functions, etc) in a same module. > >> My application follow the MVC paradigm, so basically, I've a package >> Model, a package View, and a package Controller. > > If your app is small, having _modules_ models, views and controllers > should be enough. > >> So, what are best practices for organizing files and folders in a >> small python project ? > > The best practice is to keep things simple, as usual. > Thank you all for your good advices and links. I'm new to python and I have yet a lot of things to learn ! Now, I would like to take a look to a well coded wxPython application. Could anybody indicate a project that I could take as reference for standard python coding style ? Regards, Ben From bignose+hates-spam at benfinney.id.au Sun Sep 28 04:03:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 28 Sep 2008 18:03:45 +1000 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <00eee9ec$0$20666$c3e8da3@news.astraweb.com> Message-ID: <87vdwgsnmm.fsf@benfinney.id.au> Terry Reedy writes: > Steven D'Aprano wrote: > > > And modules aren't callable. I've often thought they should be. > > Modules are not callable because their class, module, has no > __call__ instance method. But (in 3.0, which is all I will check) > you can subclass module and add one. Works fine in Python 2.5.2 also:: Python 2.5.2 (r252:60911, Aug 8 2008, 11:09:00) [GCC 4.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> module = type(__builtins__) >>> module >>> '__call__' in dir(module) False >>> import sys >>> class CallableModule(module): ... def __call__(self, *args, **kwargs): ... sys.stdout.write("%(self)r, %(args)r, %(kwargs)r\n" % vars()) ... >>> '__call__' in dir(CallableModule) True >>> foo = CallableModule('foo') >>> foo(1, 2, 3, a=4, b=5) , (1, 2, 3), {'a': 4, 'b': 5} >>> foo -- \ ?There are only two ways to live your life. One is as though | `\ nothing is a miracle. The other is as if everything is.? | _o__) ?Albert Einstein | Ben Finney From castironpi at gmail.com Thu Sep 11 14:00:44 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 11:00:44 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: Message-ID: On Sep 11, 10:52?am, hofer wrote: > On Sep 11, 10:36?am, Nick Craig-Wood wrote: > > >I'd type the explicit > > > ?v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > Either is only a couple more > > characters to ?type. ?It is completely > > explicit and comprehensible to everyone, in comparison to > > > ? v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > > ? v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars > > > Unlike perl, it will also blow up if mydict doesn't contain 'one' > > which may or may not be what you want. > > Is your above solution robust against undefined keys. > In my example it would'nt be a problem. The dict would be fully > populated, but I'm just curious. If undefined keys aren't a problem, then there's a value you expect from them. Use v1,v2,v3 = [ mydict.get(k,default) for k in 'one two two'.split()] where default is the value you're expecting. From jcd at sdf.lonestar.org Mon Sep 15 16:52:54 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 15 Sep 2008 16:52:54 -0400 Subject: Python Nautilus script In-Reply-To: <6j7t7rF1tl5rU1@mid.uni-berlin.de> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> Message-ID: <1221511974.6448.3.camel@aalcdl07.lib.unc.edu> On Mon, 2008-09-15 at 22:00 +0200, Diez B. Roggisch wrote: > Michel Leunen schrieb: > > Diez B. Roggisch a ?crit : > > > >> There shouldn't be a difference between a shell-script and a > >> python-script. Environment-variables are a unix-process-thing, and > >> thus the rules that govern them apply to *all* processes - the shell > >> is one of these, there is nothing special to it. > >> > >> If the shell-script gets the variable, the python-script will as well. > > > > Yes, that's what I thought too but try this: open a terminal and type > > > > $ echo $HOSTNAME > > > > you will get the name of your computer. > > Now try this instead: > > > > $ python > > >>> import os > > >>> os.environ['HOSTNAME'] > > Traceback (most recent call last): > > File "", line 1, in > > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > > raise KeyError(key) > > KeyError: 'HOSTNAME' > > >>> > > Which is the exact right thing to happen if the HOSTNAME is not exported. > > The echo above is executed IN THE CURRENT SHELL environment. If it > weren't - why would there be any distinction between local and exported > variables at all? > > If you put > > > > It appears that's because HOSTNAME is not exported. > > But in the case of Nautilus script, how to workaround this issue? > > I don't know for sure if the shell has something build-in that makes it > spawn shell-subprocesses with a different environment than other processes. > > However, if you want you can do something like this: > > #!/bin/bash > export VARIABLE_NAME > python /the/python/script.py > > You create a shell-script that exports the environment first, and then > invokes python. > > Diez > -- Alternatively, export the variable when you create it, in .bashrc or wherever it is getting created. That's probably the Right Thing to Do(tm) in this case. Cheers, Cliff From jvines at arl.army.mil Wed Sep 10 09:17:00 2008 From: jvines at arl.army.mil (John Vines (CISD/HPCD)) Date: Wed, 10 Sep 2008 09:17:00 -0400 Subject: Python extension, where am I going wrong Message-ID: <48C7C8CC.2090404@arl.army.mil> All, I am trying to create an extension module and keep getting an error, "/usr/local/lib/python2.5/site-packages/mytest.so: undefined symbol: PyInitModule" thanks in advance, *Here is my source code and setup.py information: */* mytest.c */ #include #include #include #include static PyObject *ErrorObject; static char isEven__doc__[] = "Method to determine if number is odd or even\n"; static PyObject *isEven(PyObject *self, PyObject *args){ int inputValue; int returnValue; if (!PyArg_ParseTuple(args, "i", &inputValue)){ PyErr_SetString(PyExc_ValueError, "Argument parsing Error"); return NULL; } if ( 0 == inputValue%2 ){ returnValue = 1; } else { returnValue = 0; } return Py_BuildValue("i", returnValue); } static char getFactorial__doc__[] = "This module takes a number as a parameter \ and returns the factorial of that number\n"; static PyObject *getFactorial(PyObject *self, PyObject *args){ int inputValue; int resultValue; if (!PyArg_ParseTuple(args, "i", &inputValue)){ PyErr_SetString(PyExc_ValueError, "Argument parsing error"); return NULL; } resultValue = factorialHelper(inputValue); return PyInt_FromLong(resultValue); } int factorialHelper(int factor){ if (factor <= 0){ return 0; } if (factor == 1){ return 1; } return factor*factorialHelper(factor-1); } static struct PyMethodDef mytest_methods[] = { {"isEven", isEven, METH_VARARGS, "Determine odd/even of a number"}, {"getFactorial", getFactorial, METH_VARARGS, "Calc the factorial value of a number"}, {NULL, NULL, 0, NULL} }; void initmytest(){ PyObject *m, *d; m = PyInitModule("mytest", mytest_methods); d = PyModule_GetDict(m); ErrorObject = PyBuildValue("s", "mytest module error"); PyDict_SetItemString(d, "Error", ErrorObject); if (PyErr_Occurred()) Py_FatalError("Can't initialize module mytest!"); } *My setup.py code:* #!/usr/bin/env python from distutils.core import setup, Extension setup(name="mytest", version="1.0", ext_modules=[Extension("mytest", ["mytest.c"])]) From emile at fenx.com Wed Sep 3 15:35:15 2008 From: emile at fenx.com (Emile van Sebille) Date: Wed, 03 Sep 2008 12:35:15 -0700 Subject: os.system dual behaviour In-Reply-To: References: Message-ID: iu2 wrote: > Hi guys > > I do > > os.system('ls &> e') > > On one linux machine it emits ls output to the file e as expected. > On another linux machine it emits ls to the standard output, and > nothing to e! > Both machines run Fedora linux. > > The command "ls &> e" entered at the shell (no python) behaves ok on > both machines. > > Why?? How can I solve this? Why?? I don't know. But you could try the commands module to work around it... open("e",'w').writelines(commands.getoutput('ls')) HTH, Emile From RDarrelBonner at gmail.com Fri Sep 19 19:51:51 2008 From: RDarrelBonner at gmail.com (RDarrelBonner at gmail.com) Date: Fri, 19 Sep 2008 16:51:51 -0700 (PDT) Subject: Pexpect echoes twice for each read References: Message-ID: <9785387f-f4b7-4deb-b1d5-37b829da8080@v13g2000pro.googlegroups.com> On Sep 9, 4:01 pm, "Sriram Rajan" wrote: > For some reason, Using pexpect causes my output to echo twice when I > connect from my MAC Darwin (10.4) to Linux (CentOS release 5 ): > > The program: > --------------------- > #!/usr/bin/python > # Automatic scp to remote host > # Input 1 : filename > # Input 2 : destination folder > # Input 3 : hostname > > import pexpect > import sys,re > > ssh_cmd = "ssh " + sys.argv[3] > ssh_handle = pexpect.spawn (ssh_cmd) > ssh_handle.logfile = sys.stdout > PROMPT = "\$\ $" > > try: > ssh_handle.expect(PROMPT) > > ssh_handle.sendline ("scp "+ sys.argv[1] +" r... at 192.168.1.254:" + > sys.argv[2] ) > > ssh_handle.expect("password:") > > ssh_handle.sendline(" ") > > ssh_handle.expect(PROMPT) > > except pexpect.TIMEOUT: > ssh_handle.logfile.write("\n Pexpect timeout !!\n") > sys.exit(1) > except KeyboardInterrupt: > ssh_handle.logfile.write("\n User interrupt!\n") > sys.exit(2) > ssh_handle.close() > > Output: > ----------- > $ python pexpect_test.py replace_line_break.sh /tmp/ 10.5.254.18 > Last login: Tue Sep 9 15:45:05 2008 from sriram-macbook.dhcp.2wire.com > $ scp replace_line_break.sh r... at 192.168.1.254:/tmp/ > scp replace_line_break.sh r... at 192.168.1.254:/tmp/ > r... at 192.168.1.254's password: > > replace_line_break.sh 100% 296 0.3KB/s 00:00 > $ $ Hi, I had this issue as well. To correct it I upgraded to pexpect 2.3 from 2.1 and changed the following: OLD: ssh_handle.logfile = sys.stdout NEW: ssh_handle.logfile_read = sys.stdout This eliminated the double display of characters as only the characters being sent back from the device are displayed. Let me know if this works for you. - Darrel From enteringheaven at gmail.com Sun Sep 28 11:23:22 2008 From: enteringheaven at gmail.com (enteringheaven) Date: Sun, 28 Sep 2008 08:23:22 -0700 (PDT) Subject: ******GOD OF GIFTS 4 U********* Message-ID: <99873d3e-8610-44ee-b54d-4c97678e970c@z6g2000pre.googlegroups.com> GOD OF GIFTS Free Animations + Wallpapers + Adsens Tips + Hand Reflexogy + Games + Audio + Videos + Nature Health Tips And Beautiful Pics.. http://www.godofgifts.blogspot.com/ From ranim81 at gmail.com Mon Sep 1 08:30:02 2008 From: ranim81 at gmail.com (raju) Date: Mon, 1 Sep 2008 05:30:02 -0700 (PDT) Subject: click here more tips in online about software Message-ID: http://www.moneymaking4.blogspot.com/ From clp at rebertia.com Tue Sep 9 16:49:11 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Sep 2008 13:49:11 -0700 Subject: wxpython ms-dos black window popping up in background In-Reply-To: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: <47c890dc0809091349o76f4385et8d5eef2c4c4d9b88@mail.gmail.com> You need to have the script be run by pythonw.exe as opposed to python.exe pythonw.exe suppresses the DOS box from coming up and should be used for running GUI applications such as yours. Regards, Chris On Tue, Sep 9, 2008 at 1:33 PM, icarus wrote: > platform: windows xp professional, python 2.5, wxpython > > When I double-check on my program file test.py (for simplicity I'll be > using this code below), I see the window just fine. But the ms-dos > black window pops up in the background. On Linux, no issues at all. > > How can I get rid of that ms-dos black window in the background? > something I need to add to my code? a setting to adjust in windows? > thanks in advance. > > > #!/usr/bin/python > import wx > > appwx = wx.App() > > frame = wx.Frame(None, -1, 'test.py') > frame.Show() > > appwx.MainLoop() > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From donspauldingii at gmail.com Thu Sep 18 11:25:25 2008 From: donspauldingii at gmail.com (Don Spaulding) Date: Thu, 18 Sep 2008 08:25:25 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> Message-ID: <5db2ee4b-ecac-4872-bed0-75c62fcdf447@73g2000hsx.googlegroups.com> On Sep 17, 5:53?pm, Todd Whiteman wrote: > supp... at mysfdomain.com wrote: > > On Sep 17, 1:21 pm, Todd Whiteman wrote: > >> Don Spaulding wrote: > >>> On Sep 16, 8:29 pm, Todd Whiteman wrote: > >>>> I've put together a tutorial that shows off how to build a GUI > >>>> application using XULRunner (same architectural components as Firefox > >>>> uses) that can be used in conjunction with the Python programming language. > >>>> The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > >>> I get to the "Running" step and run into "Couldn't load XPCOM." > >>> Does this work on x86_64? ?Or have I made a rookie mistake? > >> Hi Don, > > >> A good question. Mozilla only provide 32-bit XulRunner applications by > >> default, you you'll need to install the necessary 32-bit compatability > >> libraries on your Linux machine, i.e. for Ubuntu it's something like: > >> sudo apt-get install ia32-libs ia32-libs-gtk > > >> Then you should be able to run the example. You can check the > >> dependencies using something the following commands, there should be no > >> missing dependencies: > >> $ cd pyxpcom_gui_app/xulrunner > >> $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin > > >> It is possible to use a 64-bit version, but you'll need to compile this > >> yourself (or find somewhere that provides these x86_64 versions). Note > >> that the PythonExt project does not offer Python bindings for x86_64 > >> either (it's on my todo list), you can compile the PythonExt part > >> yourself as well if you need a 64-bit version. > > >> Cheers, > >> Todd > > > Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs > > and ia32-libs-gtk installed. > > > ldd shows that I'm missing the following libs, even though the proper > > packages are installed, and the files show up in /usr/lib. > > > ? ?libxcb-render-util.so.0 => not found > > ? ?libxcb-render.so.0 => not found > > > There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render- > > util, so I wonder if that could be part of the problem? > > > Don > > Hi Don, > > I'm thinking there may be additional 32-bit packages necessary then (I'm > not sure which package). > > Not sure about Ubuntu 8.10 (it's still alpha). I'm using a Ubuntu 8.04 > x86_64 machine and my dependencies list the following for the latest > 32-bit build of XulRunner: > > $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin | grep libxcb > ? ? ? ? libxcb-xlib.so.0 => /usr/lib32/libxcb-xlib.so.0 (0xf6493000) > ? ? ? ? libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf647b000) > > Cheers, > Todd No worries Todd, it is alpha. It was a very recent bug in the 8.10 ia32-libs package, which is now fixed :-D Thanks for the excellent writeup, BTW! I've been wondering what was involved in doing this for a while, it just never made it up my priority list to figure out. Again, thanks! From michael.pearmain at tangozebra.com Mon Sep 1 09:32:57 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 1 Sep 2008 06:32:57 -0700 (PDT) Subject: CSV reader and unique ids Message-ID: <6599d785-87b2-4bbc-97bc-799cac3640f5@b1g2000hsg.googlegroups.com> Hi All, I'm trying to use the CSV module to read in some data and then use a hashable method (as there are millions of records) to find unique ids and push these out to another file, can anyone advise? Below is the code so far fin = open(CSV_INPUT, "rb") fout = open(CSV_OUTPUT, "wb") reader = csv.reader(fin, delimiter=chr(254)) writer = csv.writer(fout) headerList = reader.next() UID = {} #For help #print headerList # ['Time', 'User-ID', 'IP'] try: for row in reader[1]: UID[row] = 1 else: List= UID.keys() writer.writerows(List) fin.close() fout.close() Mike From rocky at panix.com Fri Sep 12 05:20:05 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 12 Sep 2008 05:20:05 -0400 Subject: handling uncaught exceptions with pdb? References: <7xmyifpt68.fsf@ruckus.brouhaha.com> <6iulpmFi9t0U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" writes: > R. Bernstein schrieb: >> Paul Rubin writes: >> >>> I think I've asked about this before, but is there a way to set up >>> Python to handle uncaught exceptions with pdb? I know about setting >>> sys.except_hook to something that calls pdb, but this is normally done >>> at the outer level of a program, and by the time that hook gets >>> called, the exception has already unwound the stack to the outermost >>> level. My situation is I run a multi-hour or multi-day computation >>> that eventually crashes due to some unexpected input and I'd like to >>> break to the debugger at the innermost level, right when the exception >>> is encountered, so I can fix the error with pdb commands and resume >>> processing. >> ... >> >> Why not use the traceback you get to show you where to change the code >> around that point to add an exception handler there which calls the >> debugger? > > Because he wants to fix the issue directly in-place, and then > continue, instead of losing hours or even days of computation. Then proactively add exception handlers ;-) From deets at nospam.web.de Thu Sep 18 05:12:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Sep 2008 11:12:02 +0200 Subject: Program works great, except under less, cron or execl (Unicode?) References: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> Message-ID: <6jekbbF2v55pU2@mid.uni-berlin.de> Sam wrote: > I have a program which works great when run from the command line. > > But when I run it combined with something else such as: > - piping it through less > - cron > - execl (i.e. calling it from another python program) > > it gives me a unicode error > > File "../myparser.py", line 261, in set_attributes > print "self.atd['Name'] is: ", self.atd['Name'] > UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in > position 7: ordinal not in range(128) > > I'd post the whole program here, except it involves weird Unicode > strings. > > I could probably change the program to get it working under less/cron/ > etc. > > But I'd rather understand exactly what the issue is. Why does it work > fine when run directly from the command line, but not otherwise? Most probably because when to running directly inside a terminal, it gets it's stdin/stdout as pipes - and python can't attempt to guess the proper encoding on that, as it does on a terminal. And thus, when you print unicode to the pipe, it can't decide which encoding to use. To circumvene this, try & wrap stdout into a codecs-module wrapper with a proper encoding applied (e.g. utf-8). You might make that conditionally based on the sys.stdout.encoding-variable being set or not, albeit I'm not 100% sure to what it actually gets set when used in a subprocess. But this should give you the idea where to look. Diez From m_palmer45 at yahoo.ca Fri Sep 19 10:25:06 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 19 Sep 2008 07:25:06 -0700 (PDT) Subject: Twisted vs Python Sockets References: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> Message-ID: On Sep 18, 4:24 pm, Fredrik Lundh wrote: > James Matthews wrote: > > I am wondering what are the major points of twisted over regular python > > sockets. I am looking to write a TCP server and want to know the pros > > can cons of using one over the other. > > Twisted is a communication framework with lots of ready-made components: > > http://twistedmatrix.com/trac/wiki/TwistedAdvantage > > Regular sockets are, well, regular sockets. No more, no less. > > Depends on what you want your TCP server to do. Just to mention it, there is module SocketServer in the standard library that already contains various server classes, including a TCP server. From dave.dibiase at gmail.com Fri Sep 26 16:16:13 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Fri, 26 Sep 2008 16:16:13 -0400 Subject: Fastest way to max() list In-Reply-To: <47c890dc0809261108k356a109va88b675e037246be@mail.gmail.com> References: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> <47c890dc0809261108k356a109va88b675e037246be@mail.gmail.com> Message-ID: Yeah, Apologies, it's been a long day for me. It works, just have to check if the nazis I'm doing this for will allow me to use object and NumPy. ack. Thanks again, Dave On Fri, Sep 26, 2008 at 2:08 PM, Chris Rebert wrote: > On Fri, Sep 26, 2008 at 7:22 AM, David Di Biase > wrote: > > Hi Chris, > > > > Yeah I hear you on point A. but this the specification I was given, so I > > have to follow it unfortunately. I've also been restricted and not > allowed > > to use any other packages. I was using NumPy earlier (should have > mentioned > > that) but I was wondering if there was a simpler way. Is NumPy > technically > > even faster than just iterating and modifying the list directly? > > > > Also if I'm creating an array then making it, > > Uh, this part of your sentence doesn't quite make sense... > > > why not just do a temporary > > sort and capture the first and last values? Is this method you've > provided > > supposed to be faster? > > Well, unless you're going to use the rest of the sorted values at some > point in your program and since you have a large quantity of data, > yes, my way ought to be faster. Sorting the list is O(N*log(N)) while > running max and min over the list is only O(N). > > Regards, > Chris > > > > > Dave > > > > On Fri, Sep 26, 2008 at 12:42 AM, Chris Rebert wrote: > >> > >> On Thu, Sep 25, 2008 at 8:57 PM, David Di Biase > > >> wrote: > >> > I have a list with about 1000-1500 sub-lists which look like so: > >> > list[-0.28817955213290786, 3.6693631467403929, 'H', > 31.31225233035784]] > >> > > >> > The first and second values are Angstrom units specifying the location > >> > of a > >> > particle. What I'd like to do is determine the distance between the > >> > smallest > >> > and largest value in the arrays first position 0. I tried reading the > >> > manual > >> > for this but I don't see how it applies key or any of those other > >> > commands > >> > to the function. I could easily write a sort to do this and capture > the > >> > first and last spots, but why do that when I can use max and min (if I > >> > can > >> > actually do that...). > >> > >> A. You should probably be using objects rather than arrays to > >> represent your datapoints, so that they're more structured and it's > >> more apparent what the values mean. > >> > >> B. Assuming by "distance" you meant "difference" and/or that the > >> distance is only in 1 dimension: > >> > >> from operator import itemgetter > >> firsts = map(itemgetter(0), main_list) > >> distance = max(firsts) - min(firsts) > >> > >> > > >> > So you wonderful Python gods, lay some knowledge on me. please? lol... > >> > > >> > while I'm at it, is there a way to modify an entire list without > having > >> > to > >> > produce a whole new one? For example now say I want to modify list[0] > >> > and > >> > multiply it by some value. From what I understand previous version of > >> > Python > >> > allowed lists to be multiplied like matrices...now apparently it just > >> > replicates the list. :-/ shucks... > >> > >> You just have to apply the transform to each list element individually > >> (also, you might consider using NumPy [http://numpy.scipy.org/] if > >> you're doing a lot of matrix manipulation): > >> > >> for lst in main_list: > >> lst[0] *= some_value > >> > >> Regards, > >> Chris > >> > >> > > >> > The first question would be useful to know, but the second question I > do > >> > quite a bit of and the "best practice" would be really great to know! > >> > > >> > Thanks in advanced! > >> > > >> > -- > >> > http://mail.python.org/mailman/listinfo/python-list > >> > > >> -- > >> Follow the path of the Iguana... > >> http://rebertia.com > > > > > > > > -- > Follow the path of the Iguana... > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Sun Sep 28 17:02:55 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 28 Sep 2008 16:02:55 -0500 Subject: generate random digits with length of 5 In-Reply-To: References: Message-ID: <48DFF0FF.9070106@tim.thechases.com> > Wondering if there is a better way to generate string of numbers with > a length of 5 which also can have a 0 in the front of the number. If you want to resample the same digit multiple times, either of these two will do: >>> from random import choice >>> ''.join(str(choice(range(10))) for _ in range(5)) '06082' >>> from string import digits >>> ''.join(choice(digits) for _ in range(5)) '09355' If you need to prevent the digits from being reused >>> d = list(digits) >>> random.shuffle(digit) >>> ''.join(d[:5]) '03195' I suspect that the zfill responses don't have the property of equally distributed "randomness", as the first digit may more likely be a zero. The methods here should give equal probabilities for each choice in each place. -tkc From steve at REMOVE-THIS-cybersource.com.au Wed Sep 17 11:12:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Sep 2008 15:12:04 GMT Subject: python regex character group matches References: Message-ID: <00e1184f$0$20331$c3e8da3@news.astraweb.com> On Wed, 17 Sep 2008 09:27:47 -0400, christopher taylor wrote: > hello python-list! > > the other day, i was trying to match unicode character sequences that > looked like this: > > \\uAD0X... It is not clear what this is supposed to be. Is that matching a literal pair of backslashes, or a single escaped backslash, or a single unicode character with codepoint AD0X, or what? If I read it *literally*, then you're trying to match: backslash backslash lowercase-u uppercase-A uppercase-D zero uppercase-X Is that what you intended to match? > my issue, is that the pattern i used was returning: > > [ '\\uAD0X', '\\u1BF3', ... ] Unless you are using Python 3, I see that you aren't actually dealing with Unicode strings, you're using byte strings. Is that deliberate? > when i expected: > > [ '\\uAD0X\\u1BF3', ] I make that to be a string of length 12. Is that what you are expecting? >>> len('\\uAD0X\\u1BF3') 12 > the code looks something like this: > > pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) > #print pat.findall(txt_line) > results = pat.finditer(txt_line) First point: I don't think the UNICODE flag does what you think it does. It redefines the meaning of special escape sequences \b etc. Since you aren't using any special escape sequences, I'm going to guess that you think it turns your search string into Unicode. It doesn't. (Apologies in advance if I guessed wrong.) I don't think you need either the UNICODE or LOCALE flag for this search: they don't seem to have any effect. Secondly: you will generally save yourself a lot of trouble when writing regexes to use raw strings, because backslashes in the regex engine clash with backslashes in Python strings. But there's a gotcha: backslash escapes behave differently in ordinary strings and the re engine. In an ordinary string, the sequence backslash-char is treated as a literal backslash-char if it isn't a special escape. So: >>> len('\t') # special escape 1 >>> len('\u') # not a special escape 2 But that's not the case in the re engine! As the Fine Manual says: The special sequences consist of "\" and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example, \$ matches the character "$". http://docs.python.org/lib/re-syntax.html So all of these match the same thing: re.compile('\\u') re.compile(r'\u') re.compile('u') To match a literal backslash-u, you need to escape the backslash before the engine joins it to the u: r'\\u'. Putting it all together again: pat = re.compile(r"(\\u[0-9A-F]{4})+") will probably do what you want, assuming I have guessed what you want correctly! -- Steven From skip at pobox.com Thu Sep 11 16:40:26 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 11 Sep 2008 15:40:26 -0500 Subject: Is len O(n) or O(1) ? In-Reply-To: <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> Message-ID: <18633.33338.617152.517916@montanaro-dyndns-org.local> >> ok but if len is O(1) then it doesnt matter? compared to >> if not lista: >> return [] >> i mean. Depends on how often the test is performed, e.g.: >>> def f(a): ... if not a: return [] ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 JUMP_IF_TRUE 5 (to 11) 6 POP_TOP 7 BUILD_LIST 0 10 RETURN_VALUE >> 11 POP_TOP 12 LOAD_CONST 0 (None) 15 RETURN_VALUE >>> def g(a): ... if not len(a): return [] ... >>> dis.dis(g) 2 0 LOAD_GLOBAL 0 (len) 3 LOAD_FAST 0 (a) 6 CALL_FUNCTION 1 9 JUMP_IF_TRUE 5 (to 17) 12 POP_TOP 13 BUILD_LIST 0 16 RETURN_VALUE >> 17 POP_TOP 18 LOAD_CONST 0 (None) 21 RETURN_VALUE Even though len(a) is O(1) it's going to have a much larger constant coefficient because of the lookup and call to len(). Skip From jobs at omacindustries.com Mon Sep 8 12:51:59 2008 From: jobs at omacindustries.com (jobs at omacindustries.com) Date: Mon, 8 Sep 2008 09:51:59 -0700 (PDT) Subject: Calling Common Lisp Game Developers Message-ID: We are currently seeking talented Lisp Game Developers who are passionate about game development and want to play a major role in developing and maintaining new features for one of our persistent browser games. This particular title uses Hunchentoot, but all other code has been developed in house using the Mnesia database for persistence. This particular game is not released yet but has already generated interest from over 35,000 players globally. If you?re interested in developing Persistent Browser Games using SBCL and want to know more then send us an email at lisp at omacindustries.com The preferred location for this role is in Dublin, Ireland but we are also open to hearing from anyone who prefers to work remotely. http://omacindustries.com From wegwerp at gmail.com Fri Sep 26 17:42:26 2008 From: wegwerp at gmail.com (Bas) Date: Fri, 26 Sep 2008 14:42:26 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> <7b1181e9-16a2-458a-8677-a2d8d7c8a961@l42g2000hsc.googlegroups.com> Message-ID: <05d9ca4d-441e-484b-ba1b-9e0ef7fa4658@d70g2000hsc.googlegroups.com> On Sep 26, 10:33?pm, afrogazer wrote: > rad_angles = [elem*(pi/180) for elem in angles] You are missing some more on a friday afternoon: angles is created by arange, so it is a numpy array. In that case you simply can do rad_angles = pi/180 * angles No need to use list-comprehensions, that is the whole idea about using these kick-ass objects! Bas From keosophon at gmail.com Wed Sep 17 23:20:18 2008 From: keosophon at gmail.com (Keo Sophon) Date: Thu, 18 Sep 2008 10:20:18 +0700 Subject: How to Determine Name of the Day in the Week In-Reply-To: References: Message-ID: <48D1C8F2.6040308@gmail.com> Fredrik Lundh wrote: > Henry Chang wrote: > >> Instead of getting integers with weekday(), Monday == 0 ... Sunday == >> 6; is there a way to get the actual names, such as "Monday ... >> Sunday"? I would like to do this without creating a data mapping. :) > > if you have a datetime or date object, you can use strftime with the > appropriate formatting code. see the library reference for details. > > if you have the weekday number, you can use the calender module: > > >>> import calendar > >>> calendar.day_name[0] > 'Monday' > > (the latter also contains abbreviated day names, month names, and a > bunch of other potentially useful functions and mappings.) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I've tried calendar.month_name[0], it displays empty string, while calendar.month_name[1] is "January"? Why does calendar.month_name's index not start with index 0 as calendar.day_name? Thanks, Sophon From tgrav at mac.com Sat Sep 6 21:47:33 2008 From: tgrav at mac.com (Tommy Grav) Date: Sat, 06 Sep 2008 21:47:33 -0400 Subject: Setter Propertys' mro? In-Reply-To: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> References: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> Message-ID: <70768920-25BF-4F69-9DE2-8C62AEED6C92@mac.com> On Sep 6, 2008, at 9:15 PM, cipher wrote: > Whats the mro (method resolution order) of a setter property (__set__ > on a descriptor). > i seem to be experiencing some weird issue with them. > for example > >>>> class test: You have to use class test(object). Only new style classes accepts properties. Cheers Tommy From google at mrabarnett.plus.com Wed Sep 3 18:40:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 3 Sep 2008 15:40:35 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: On Sep 3, 8:18?pm, Laszlo Nagy wrote: > bearophileH... at lycos.com wrote: > > Empty Python lists [] don't know the type of the items it will > > contain, so this sounds strange: > > >>>> sum([]) > > > 0 > > > Because that [] may be an empty sequence of someobject: > > You are right in that sum could be used to sum arbitrary objects. > However, in 99.99% of the cases, you will be summing numerical values. > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > is very logical to return zero for empty sequences. > > Same way, if we would have a prod() function, it should return one for > empty sequences because X*1 = X. The neutral element for this operation > is one. > > Of course this is not good for summing other types of objects. But how > clumsy would it be to use > > sum( L +[0] ) > > or > > if L: > value = sum(L) > else: > value = 0 > > instead of sum(L). > > Once again, this is what sum() is used for in most cases, so this > behavior is the "expected" one. > > Another argument to convince you: the sum() function in SQL for empty > row sets returns zero in most relational databases. > > But of course it could have been implemented in a different way... I > believe that there have been excessive discussions about this decision, > and the current implementation is very good, if not the best. > An alternative would be for the start value to default to None, which would mean no start value. At the moment it starts with the start value and then 'adds' the items in the sequence to it, but it could start with the first item and then 'add' the following items to it. So: sum([1, 2, 3]) => 6 sum(["a", "b", "c"]) => "abc" For backward compatibility, if the sequence is empty and the start value is None then return 0. From cjstevens at gmail.com Mon Sep 8 01:19:57 2008 From: cjstevens at gmail.com (cjstevens at gmail.com) Date: Sun, 7 Sep 2008 22:19:57 -0700 (PDT) Subject: Spotlight Searching in Python - Mac OSX Message-ID: <09177d14-a692-4e47-9759-51ad52e38500@s1g2000pra.googlegroups.com> Hi all, I'm having some issues getting a spotlight search to work similar to the program demonstrated here: http://pyobjc.sourceforge.net/examples/pyobjc-framework-Cocoa/AppKit/PredicateEditorSample/ Here is my class, complete with the code I am trying to use it with at the end. import objc, sys, os, osax, time from Foundation import * from ScriptingBridge import * from appscript import * class SystemBridge(NSObject): """Class to use the scripting bridge to interact with the system""" _hideapp = objc.ivar(u"hideapp") _volume = objc.ivar(u"volume") _filename = objc.ivar(u"filename") _filetype = objc.ivar(u"filetype") _auth = objc.ivar(u"auth") _logout = objc.ivar(u"logout") query = objc.ivar(u"query") StdAdditions = osax.ScriptingAddition() def init(self): super(SystemBridge, self).init() # create and initalize our query self.query = NSMetadataQuery.alloc().init() # setup our Spotlight notifications nf = NSNotificationCenter.defaultCenter() nf.addObserver_selector_name_object_(self, 'queryNotification:', None, self.query) # XXX: this framework isn't wrapped yet! self.query.setSortDescriptors_([NSSortDescriptor.alloc().initWithKey_ascending_('kMDItemDisplayName', True)]) self.query.setDelegate_(self) return self def hideApplication_(self, _hideapp): app(u'System Events').processes[_hideapp].visible.set(False) def loadResultsFromQuery_(self, notif): results = notif.object().results() NSLog("search count = %d", len(results)) # iterate through the array of results, and match to the existing stores for item in results: nameStr = item.valueForAttribute_('kMDItemDisplayName') print nameStr def queryNotification_(self, note): # the NSMetadataQuery will send back a note when updates are happening. # By looking at the [note name], we can tell what is happening if note.name() == NSMetadataQueryDidStartGatheringNotification: # the query has just started NSLog("search: started gathering") elif note.name() == NSMetadataQueryDidFinishGatheringNotification: # at this point, the query will be done. You may recieve an update # later on. NSLog("search: finished gathering"); self.loadResultsFromQuery_(note) elif note.name() == NSMetadataQueryGatheringProgressNotification: # the query is still gathering results... NSLog("search: progressing...") elif note.name() == NSMetadataQueryDidUpdateNotification: # an update will happen when Spotlight notices that a file as # added, removed, or modified that affected the search results. NSLog("search: an update happened.") def spotlightFriendlyPredicate_(self, predicate): if predicate == NSPredicate.predicateWithValue_(True) or predicate == NSPredicate.predicateWithValue_(False): return False elif isinstance(predicate, NSCompoundPredicate): type = predicate.compoundPredicateType() cleanSubpredicates = [] for dirtySubpredicate in predicate.subpredicates(): cleanSubpredicate = self.spotlightFriendlyPredicate_( dirtySubpredicate) if cleanSubpredicate: cleanSubpredicates.append(cleanSubpredicate) if len(cleanSubpredicates) == 0: return None else: if len(cleanSubpredicates) == 1 and type != NSNotPredicateType: return cleanSubpredicates[0] else: return NSCompoundPredicate.alloc().initWithType_subpredicates_(type, cleanSubpredicates) else: return predicate def createNewSearchForPredicate_(self, predicate): # Format search file type thePredicate = NSPredicate.predicateWithFormat_( "(kMDItemContentType = 'com.apple.iwork.keynote.key')") tempPredicate = NSPredicate.predicateWithFormat_( "(kMDItemDisplayName IN[c] 'preso')") predicate = NSCompoundPredicate.andPredicateWithSubpredicates_( [thePredicate, tempPredicate]) self.query.setPredicate_(predicate) self.query.startQuery() def changeVolume_(self, setvolume): self.StdAdditions.set_volume(output_volume=setvolume) def getVolume_(self): return StdAdditions.get_volume_settings()[k.output_volume] _x = SystemBridge.alloc().init() #predicate = u"kMDItemDisplayName IN[c] 'preso'" #predicate = _x.spotlightFriendlyPredicate_(predicate) if predicate is not None: _x.createNewSearchForPredicate_(predicate) As you can see, I am trying to use a notifier just like the example linked above. The class does not work as expected, and just displays "search: started gathering", none of the other notifier events happen at all! Have I missed something out translating this to PyObjC? The weird thing is, most of that code is straight from the example which works fine, so I can't figure out why mine won't work! Any help would be hugely appreciated, I need to get this finished soon! From gagsl-py2 at yahoo.com.ar Wed Sep 3 05:44:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 06:44:51 -0300 Subject: Problems with running Python CGI Scripts References: <20080903082939.CKJ85501@mail1.edb.st.com> Message-ID: En Wed, 03 Sep 2008 05:29:39 -0300, Edward FISHER escribi?: > I can get the script to run the python script but all that happens is > that the black python box appears then disapears, the html that the > python scripts should generate is never output. > [...] > This is calling the pyc file of the python script. I dont understand why > if i call the py file itself all i get returned is the plain text of the > python file. That's a server setting (Apache or whatever) - make sure it is configured to *execute* the script. > The python script is: > > #!/usr/local/bin/python > import cgi > > def main(): > print "Content-type: text/html\n" I hope this is just the way you posted your message, but remember that in Python indentation is important. The above code isn't valid. Once you are sure that your script doesn't have syntax errors, add this lines on the top to help debugging: import cgitb; cgitb.enable() -- Gabriel Genellina From ewertman at gmail.com Fri Sep 12 13:28:09 2008 From: ewertman at gmail.com (Eric Wertman) Date: Fri, 12 Sep 2008 13:28:09 -0400 Subject: Which version In-Reply-To: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> References: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> Message-ID: <92da89760809121028s1d9b8b46g464d54937c67ba0f@mail.gmail.com> > I'm a reasonably experienced in other languages and have just decided to > get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed, > is this good enough to start out with or am I likely to encounter bugs that > have been fixed in later versions. I'm sure there will be other opinions. I try to use the stock distro version whenever possible, just because it makes administration easier and you have some reasonable guess as to where your code will work if you move it. I use 2.4 regularly, and haven't come across many things that the 2.5 series would make behave differently. The subprocess module is one though, and I recall a few datetime routines that were 2.5 only that I wished I could use. If you aren't married to you linux distro, you might switch to ubuntu... I believe they package the 2.5 series. IMO it's not wrong to compile a new one alongside the stock installation, but you could run into potentially confusing issues later about which one exactly you are using, installing modules for, etc. Easy to avoid if you know what you are doing, but a potential pitfall for a beginner. Eric From george at george-net.de Tue Sep 16 07:39:03 2008 From: george at george-net.de (Georg Altmann) Date: Tue, 16 Sep 2008 13:39:03 +0200 Subject: A unique instance of Python GUI program In-Reply-To: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Message-ID: akineko schrieb: > Hello everyone, > > This may not be a Python specific challenge. > I have a GUI program written in Python + Tkinter. > It works very well. > > Now, I would like to start it from a shell script. > As my GUI program includes a server, it should not have more than one > instance. > Is there any easy way to check if another instance of the program is > already running. > > I vaguely remember that Windows programming provides a way to check. On windows a mutex does the job, see CreateMutex in the windows api. > A platform independent approach would be nice but a solution for X is > sufficient for my application. I'm not familiar with Tkinter - you might want to check if it supports mutexes. Though I'm not sure if mutexes are cross-process (system wide) on all platforms. Regards Georg From castironpi at gmail.com Wed Sep 17 01:26:43 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 22:26:43 -0700 (PDT) Subject: minimum install & pickling Message-ID: Sometimes questions come up on here about unpickling safely and executing foreign code. I was thinking a minimum install that didn't even have access to modules like 'os' could be safe. (Potentially.) I have time to entertain this a little, though all the devs are busy. I can bring it up again in a few months if it's a better time. I browsed for info on 'rexec'. Two c-l-py threads: http://mail.python.org/pipermail/python-dev/2002-December/031160.html http://mail.python.org/pipermail/python-dev/2003-January/031848.html A lot of modules would have to go. IPC modules: subprocess, socket, signal, popen2, asyncore, asynchat. ctypes, mmap, platform.popen, glob, shutil, dircache, and many more. I tested it out. I renamed the 'Lib' directory and ran. 'import site' failed; use -v for traceback Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os ImportError: No module named os >>> import socket ImportError: No module named socket >>> del __builtins__.__import__ >>> __import__ NameError: name '__import__' is not defined >>> del __builtins__.open, __builtins__.file >>> open NameError: name 'open' is not defined >>> file NameError: name 'file' is not defined Even a function created from raw bytecode string can't do anything without __import__ or 'open'. And you can't get a second instance running without subprocess or os.system. 'rexec' may be full of swiss cheese and irreparable, but maybe it would work to start from bare-bones and add pieces known to be safe. This sort of thing wouldn't need and standard library support either, I don't think. From deets at nospam.web.de Tue Sep 9 11:55:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 Sep 2008 17:55:43 +0200 Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> Message-ID: <6inkkiFrbptbU1@mid.uni-berlin.de> Luigi wrote: > Dear all, > > I'm writing an XML-RPC server which should be able to modify the > incoming request before dispatching it. In particular I wand to added > two fixed parameters to the method called: one is the client host > address, and the other is the user name provided as for Basic > Authentication (http://user at www.bla-bla.com). > > To do this, at the present I've overwritten the do_POST method of > SimpleXMLRPCRequestHandler, including at a certain point this code: > > .... > data = ''.join(L) > > params, method = xmlrpclib.loads(data) > user = "unknown" > if self.headers.has_key('Authorization'): > # handle Basic authentication > (enctype, encstr) = self.headers.get('Authorization').split() > user, password = base64.standard_b64decode(encstr).split(':') > params = list(params) > params.append(self.address_string()) > params.append(user) > params = tuple(params) > data = xmlrpclib.dumps(params, methodname=method) > > (I slightly modified it to make it more readable at mail level) > > It works, but I don't really like it because it completely overwrites > the do_POST method that in the future Python releases is going to > change (I verified it). Do you know a better way to do this? I would go for a slightly different approach: make your server have a dispatch-method that delegates the calls to the underlying actual implementation. But *before* that happens, extract the information as above, and either - prepend it to the argument list - stuff it into threadlocal variables, and only access these if needed in your implementation. Diez From fredrik at pythonware.com Wed Sep 10 14:15:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 20:15:50 +0200 Subject: subprocess.Popen hangs at times? In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > When making calls of the form Popen(cmd, shell=True, > stdout=subprocess.PIPE), we've been getting occasional, predictable > hangs. Will Popen accumulate a certain amount of stdout and then block > until its read? the pipe provided by the operating system has a limited buffer size (usually just a few kilobytes). when the buffer fills up, the operating system will halt the external process. From fredrik at pythonware.com Mon Sep 22 12:32:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Sep 2008 18:32:35 +0200 Subject: Why are "broken iterators" broken? In-Reply-To: <20080922043217.GA10077@cskk.homeip.net> References: <20080922043217.GA10077@cskk.homeip.net> Message-ID: Cameron Simpson wrote: >> you probably want the consumer thread to block when it catches up with >> the producer, rather than exit. > > It sounds like he wants non-blocking behaviour in his consumer. Roy gave an example, he didn't post a requirements specification. > A common example is "try to gather a lot of stuff into a single packet, > but send a smaller packet promptly if there isn't much stuff". that use case is better solved with a plain list object. no need to make things harder than they are. From rmoore787 at gmail.com Sat Sep 27 18:06:25 2008 From: rmoore787 at gmail.com (Robert Moore) Date: Sat, 27 Sep 2008 15:06:25 -0700 Subject: Configuring pyc directory Message-ID: Is there a way to configure python to read/write compiled pyc files for modules in a directory other than the directory containing the original py files? I'm trying trying to secure an Apache server running mod_python and don't want the process compiling the pyc files to have write access to the folder containing my site's py modules. I realize the solution (if it exists) may lie with mod_python rather than python itself, so I've also pinged the mod_python mailing list for help. I'm checking here as well, though, just in case there's some solution built into python. Thanks, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Sep 8 16:52:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Sep 2008 16:52:21 -0400 Subject: universal unicode font for reportlab In-Reply-To: <48C55E7B.9090807@shopzeus.com> References: <87r67vj7f1.fsf@benfinney.id.au> <48C51E49.2070202@shopzeus.com> <48C52635.1030709@shopzeus.com> <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> Message-ID: > The simplest solution would be to use a font that is able to handle all > encodings that I need. My OpenOffice on WinXP uses a unicode font, I believe Lucida Sans Unicode, that seems to cover the entire BMP. I don't know whether it was already installed or installed by OO or how one would get to it to extract it. From simon at brunningonline.net Thu Sep 4 03:04:51 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 4 Sep 2008 08:04:51 +0100 Subject: Coming from .NET and VB and C In-Reply-To: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> Message-ID: <8c7f10c60809040004j6d517130jd5028b955044d81b@mail.gmail.com> 2008/9/3 Dennis Lee Bieber : > non-relational DBMS (if any such are still in use), There certainly are... >> SO, I'm interested in using my Google App space (free 500MB) to >> develop a quick database application. Using Python. I found "Dive >> Into Python" which I will be reading shortly. >> > So one question: what RDBMs are supported in that space? ... and the Google's BigTable (see ) is one of them. -- Cheers, Simon B. From dmitry at makovey.net Sat Sep 27 23:38:27 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Sun, 28 Sep 2008 03:38:27 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> <91e62d70-73fb-4ecc-ae2e-d950a5f7ea6b@k13g2000hse.googlegroups.com> Message-ID: George Sakkis wrote: > It's funny how often you come with a better solution a few moments > after htting send! The snippet above can (ab)use the decorator syntax > so that it becomes: > > class A(Proxy): > > @ProxyMethod > def bmethod(self): > return self.b1 > > @ProxyMethod > def bmethod2(self): > return self.b2 That is outstanding! This code looks very clean to me (just a touch cryptic around declarations in A, but that was unavoidable anyway). Seems like the right way to read it would be bottom up (or is it only my mind so perverted?). By the looks of it - it does exactly what I needed with great number of possibilities behind it and is very lightweight and transparent. Now I regret I haven't come up with it myself :-D George, at this point I'm out of rugs - so no more rug pulling from under your feet for me. Now I'm going to apply all this knowledge to my code, see how that goes and come back with more questions later. Thank you (all) very much for a great discussion. This thread educated me quite a bit on descriptors and why one would need them, and decorators - just as subject line suggested, were not forgotten. From tjreedy at udel.edu Fri Sep 26 02:20:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 02:20:08 -0400 Subject: Comparing float and decimal In-Reply-To: <99a7ab2c-601e-47fe-8ece-5f9150c10f7a@k30g2000hse.googlegroups.com> References: <20080923072012.57d8d329.darcy@druid.net> <99a7ab2c-601e-47fe-8ece-5f9150c10f7a@k30g2000hse.googlegroups.com> Message-ID: Mark Dickinson wrote: > On Sep 24, 6:18 pm, Terry Reedy wrote: >> If there is not now, there could be in the future, and the decimal >> authors are committed to follow the standard wherever it goes. >> Therefore, the safe course, to avoid possible future deprecations due to >> doing too much, is to only do what is mandated. > > Makes sense. It looks as though the standard's pretty stable now > though; I'd be quite surprised to see it evolve to include discussion > of floats. But then again, people thought it was stable just before > all the extra transcendental operations appeared. :-) What got me were the bizarre new 'logical' operations whose addition were rather nonsensical from a Python viewpoint (though probably sensible from an IBM profit business viewpoint). With those added, and with this thread, I have decided that Decimals best be thought of as a separate universe, not to be mixed with other numbers unless one has good reason to and understands the possible anomalies of doing so. For pure finance apps, I would think that there should be little reason to mix. tjr From martindemello at gmail.com Thu Sep 4 16:59:16 2008 From: martindemello at gmail.com (Martin DeMello) Date: Thu, 4 Sep 2008 13:59:16 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: On Sep 4, 1:51?pm, Fredrik Lundh wrote: > Martin DeMello wrote: > > I'm writing a cluster monitor, that collects information from a set of > > machines and logs it to a database > > > In the interests of not hammering the db unnecessarily, I'm > > considering the following > > 1. A series of independent "monitor" threads that collect information > > over TCP from the cluster of machines, and write it to a queue > > 2. A "logger" thread that empties the queue every second or so and > > inserts the collected information to the db via a single insert > > statement > > why are you using a queue for this case, btw? ?why not just use a plain list > > ? ? ?L = [] > ? ? ?lock = threading.Lock() Good point - I thought of queue because it was self-locking, but you're right, I can as well use a simple list and lock it myself. martin From moijes12 at gmail.com Thu Sep 4 08:03:57 2008 From: moijes12 at gmail.com (moijes12) Date: Thu, 4 Sep 2008 05:03:57 -0700 (PDT) Subject: help in execfile function Message-ID: <8a3a0376-7146-44f9-beb6-e1ad7a612ad8@l33g2000pri.googlegroups.com> Hi i have 3 python files and i want to execute the files sequentially using the execfile command.Hence ,i have written the following program fileList = ["a.py","b.py","c.py"] for fileName in fileList : execfile(fileName) however,when i try running it,the program keeps calling execfile on a.py and thus an infinite loop is created.I am running this on Windows XP. Please suggest a sloution whereby i can use execfile to execute all files in fileList.Please tell me where in my program i may have gone wrong. moijes12 From tino at wildenhain.de Tue Sep 2 11:40:49 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 02 Sep 2008 17:40:49 +0200 Subject: dict.update In-Reply-To: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> Message-ID: <48BD5E81.8060407@wildenhain.de> Mike P wrote: > Hi All, > > I have two dictionaries e.g > dict1 = {123:3,234:5,456:3} > dict2 = {123:4,157:2,234:5,456:3,567:2} > > I want to merge these two dictionaries together so i have a resultant > dictionary of: > > dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]} > > As later on i want to write a csv file that would have the form > > id var1 var2 > 123 4 3 > 157 2 0 > > i looks like the dict.update looks almost there but i can't get it to > work properly, can anyone offer any advise? result=dict((key,(dict1.get(key,None), dict2.get(key,None))) for key in set(dict1.keys()+dict2.keys()) ) (untested) should provide you with a resulting dictonary with tuples where [0] is var1 and [1] is var2, None for values not in one of the dictionaries (you can put in 0 if you prefer). You can use it like so to generate your output: allitems=result.items() allitems.sort() # sort based on keys as first tuple element for (key,(var1,var2)) in allitems: print key,var1,var2 HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From hrishys at yahoo.co.uk Wed Sep 24 11:25:01 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Wed, 24 Sep 2008 15:25:01 +0000 (GMT) Subject: Linq to Python In-Reply-To: Message-ID: <319386.9452.qm@web27402.mail.ukl.yahoo.com> Hi Tom This is what i like and feel of the Python programmers smarter then every other langauge i know of. But i am not comfortable with your second statement XML i never need it one day everybody would need it. regards Hrishy --- On Tue, 23/9/08, Thomas G. Willis wrote: > From: Thomas G. Willis > Subject: Re: Linq to Python > To: python-list at python.org > Date: Tuesday, 23 September, 2008, 7:45 PM > > But surely the idea behind it will eventually spread. > ?It's really > > just comprehensions generalized over XML and > relational datasets, a > > noble goal. ?Besides, it's main purpose for .NET > was to bring > > functional programming to it. ?Python already has > that, somewhat... > > it's really any object out of the box, i think the sql > linq stuff is > more of a query compiler, IMO sqlalchemy does that. > > > query = select(user_cols, > > and_(table_relationship.c.accept_user_id==user.id, > > table_relationship.c.start_date==None > > ), > > from_obj=join( > > table_relationship,table_user, > > > onclause=table_user.c.id==table_relationship.c.init_user_id > > ).outerjoin(table_profile) > > ) > > session.execute(query).fetchall() > > > > > > > XML? meh hopefully I would never need it. :) > > > C# is my day job, and when I got my hands on LINQ back in > January my > initial thought was "Finally I have list > comprehensions!!!! day job is > fun again" > > For the most part, I think C# is catching up. > -- > http://mail.python.org/mailman/listinfo/python-list From arnodel at googlemail.com Mon Sep 22 05:52:39 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Sep 2008 02:52:39 -0700 (PDT) Subject: A bit weird dictionary behavior References: Message-ID: <1669f0d5-fd1c-4c92-a73f-2ce00bd8dd91@a1g2000hsb.googlegroups.com> On 22 Sep, 10:25, "Pekka Laukkanen" wrote: > Hello, > > just noticed this: > > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> {1: 2} > {1: 2} > >>> {True: False} > {True: False} > >>> {1: 2, True: False} > > {1: False} > > This must be because > > >>> True == 1 and True in {1: 2} > > True That's exactly the reason! > but it still doesn't feel exactly right. Would it be worth submitting a bug? I don't think it can be considered as a bug, for the reason you gave above and because dictionary keys are by definition unique with respect to equality. Perhaps you could call it a "surprising feature" :) -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Mon Sep 22 19:16:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 23:16:45 GMT Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <00e45101$0$20331$c3e8da3@news.astraweb.com> <773db59e-40c6-470e-b616-ca8715efa46a@d77g2000hsb.googlegroups.com> Message-ID: <00e82140$0$20303$c3e8da3@news.astraweb.com> On Mon, 22 Sep 2008 04:21:12 -0700, bearophileHUGS wrote: > Steven D'Aprano: > >>Extending len() to support iterables sounds like a good idea, except >>that it's not.< > > Python language lately has shifted toward more and more usage of lazy > iterables (see range lazy by default, etc). So they are now quite > common. So extending len() to make it act like leniter() too is a way to > adapt a basic Python construct to the changes of the other parts of the > language. I'm sorry, I don't recognise leniter(). Did I miss something? > In languages like Haskell you can count how many items a lazy sequence > has. But those sequences are generally immutable, so they can be > accessed many times, so len(iterable) doesn't exhaust them like in > Python. So in Python it's less useful. In Python, xrange() is a lazy sequence that isn't exhausted, but that's a special case: it actually has a __len__ method, and presumably the length is calculated from the xrange arguments, not by generating all the items and counting them. How would you count the number of items in a generic lazy sequence without actually generating the items first? > This is a common situation where I can only care of the len of the g > group: > [leniter(g) for h,g in groupby(iterable)] > > There are other situations where I may be interested only in how many > items there are: > leniter(ifilter(predicate, iterable)) leniter(el for el in iterable if > predicate(el)) > > For my usage I have written a version of the itertools module in D (a > lot of work, but the result is quite useful and flexible, even if I miss > the generator/iterator syntax a lot), and later I have written a len() > able to count the length of lazy iterables too (if the given variable > has a length attribute/property then it returns that value), I'm not saying that no iterables can accurately predict how many items they will produce. If they can, then len() should support iterables with a __len__ attribute. But in general there's no way of predicting how many items the iterable will produce without iterating over it, and len() shouldn't do that. > and I have > found that it's useful often enough (almost as the string.xsplit()). But > in Python there is less need for a len() that counts lazy iterables too > because you can use the following syntax that isn't bad (and isn't > available in D): > > [sum(1 for x in g) for h,g in groupby(iterable)] sum(1 for x in > ifilter(predicate, iterable)) sum(1 for el in iterable if predicate(el)) I think the idiom sum(1 for item in iterable) is, in general, a mistake. For starters, it doesn't work for arbitrary iterables, only sequences (lazy or otherwise) and your choice of variable name may fool people into thinking they can pass a use-once iterator to your code and have it work. Secondly, it's not clear what sum(1 for item in iterable) does without reading over it carefully. Since you're generating the entire length anyway, len(list(iterable)) is more readable and almost as efficient for most practical cases. As things stand now, list(iterable) is a "dangerous" operation, as it may consume arbitrarily huge resources. But len() isn't[1], because len() doesn't operate on arbitrary iterables. This is a good thing. > So you and Python designers may choose to not extend the semantics of > len() for various good reasons, but you will have a hard time convincing > me it's a useless capability :-) I didn't say that knowing the length of iterators up front was useless. Sometimes it may be useful, but it is rarely (never?) essential. [1] len(x) may call x.__len__() which might do anything. But the expected semantics of __len__ is that it is expected to return an int, and do it quickly with minimal effort. Methods that do something else are an abuse of __len__ and should be treated as a bug. -- Steven From bedouglas at earthlink.net Tue Sep 2 01:31:53 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 1 Sep 2008 22:31:53 -0700 Subject: python XPATH question - mechanize/libxml2dom Message-ID: <109a01c90cbd$3611ac90$0301a8c0@tmesa.com> hi... i can use an xpath query to create a node from an html/dom representation. however, if i have a node, is there a way to generate an xpath query from the node. in testing with firefox/dom inspector, i can use "ancestor::*", but i can't determine where/how to implement this using mechanize/libxml2dom thanks From mhuening at zedat.fu-berlin.de Mon Sep 8 06:13:58 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Mon, 08 Sep 2008 12:13:58 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: References: <6ii9jbFqoe2eU1@mid.uni-berlin.de> Message-ID: <6ikc76Fr32cnU1@mid.uni-berlin.de> Gerhard H?ring (08.09.2008 10:12): > >> Error is: >> >> con.execute("select load_extension('./fts3.so')") >> pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht >> gefunden. >> >> Where should I look for the module? > > The sources are in ext/fts3 in the SQLite source tree. I haven't found > any Makefile, so I it myself using this gcc command: > > $ cd .../ext/fts3 > $ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so *.c > -lsqlite3 > Thanks! Will fts3 be integrated in the Python 2.6 release? Matthias From circularfunc at yahoo.se Tue Sep 16 09:27:53 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 06:27:53 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? References: Message-ID: <92d472c8-4af1-432a-a240-f9f9c97686eb@m73g2000hsh.googlegroups.com> i can run the interpreter. its just i cant load a file into it. i tried adding your suggestion but it didnt help. i dont think thats the issue though. From jonathon.blake at gmail.com Mon Sep 8 23:41:55 2008 From: jonathon.blake at gmail.com (jonathon) Date: Mon, 8 Sep 2008 20:41:55 -0700 Subject: a11y & python Message-ID: All: A year or so ago, I read a tutorial on writing self-voicing apps using python. It also covered other a11y issues. However, I didn't bookmark it, and it doesn't show up in the first 1000 hits on the Google search I did. Can somebody point me to either that, or any other tutorials on programming a11y into python. ### This was triggered by a request by my housemate for a self-voicing program that does household inventory control, that can print to Braille. xan jonathon From stef.mientki at gmail.com Sat Sep 13 09:27:17 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 13 Sep 2008 15:27:17 +0200 Subject: A service for testing Python code on multiple platforms and versions In-Reply-To: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> References: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> Message-ID: <48CBBFB5.1030202@gmail.com> David Moss wrote: > Hopefully a service like this already exists and I just haven't found > it yet. If not it could be an idea for some kind soul(s) to pick up > and run with ;-) > > As someone who writes and releases Python modules for the community, I > find it difficult to have a decent level of confidence in the efficacy > of my code on platforms and Python versions other than those that I > own or use regularly. My documentation states that I support Python > 2.3 or higher. This ends up being more of a statement of good > intentions than a one of fact. > > A case in point. A bug (in Python), that I believed to have been > killed off after Python 2.2, resurfaced in a 2.4.x release of Python > on PowerPC recently. As I don't own any PowerPC kit, it was very > difficult to a) investigate the bug and b) create an effective fix for > it in a timely fashion. Fortunately I'd come across it before so the > fix was easy but it might not have been. > > While I realise one's code can never be perfect, you can cover for > these sorts of eventualities fairly easily by running your software > and unit tests under different environments. You'd also like to be > able to do this on a continual basis rather than just once or twice. > If this was done with some kind of automated testing and reporting so > much the better. Bigger projects that take code quality seriously > probably already have this sort of thing in place for their own > purposes, but for smaller ones it just isn't possible. > > Wouldn't it be great to have a service/setup out there available for > Python developers to access that covered a fairly broad base of > possible Python installations for the purpose of improve overall code > quality? Am I the only one that would find something like this useful? > I would love to have such a tool, but have no idea how to create something like that. Something like a multi-virtual machine on a web server, that you launch in the night, and in the morning you would get a full report of all problems on the specific OSs (probably someone is going to say that this is impossible, but fortunately I'm not hindered by any knowledge ;-) cheers, Stef > Dave M. > -- > http://mail.python.org/mailman/listinfo/python-list > From durand1 at gmail.com Sat Sep 6 12:03:11 2008 From: durand1 at gmail.com (Durand) Date: Sat, 6 Sep 2008 09:03:11 -0700 (PDT) Subject: Overlapping axis text References: Message-ID: Err...made a mistake there. days = WeekdayLocator() # every monday months = MonthLocator() # every month That doesn't change my question though. Thanks From marco.bizzarri at gmail.com Mon Sep 15 09:06:38 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 15 Sep 2008 15:06:38 +0200 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: References: Message-ID: <3f0d61c40809150606w2b8035b3v2eba46e44cdee9a7@mail.gmail.com> On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal wrote: > Hi, > > I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that > key as string. Is there any way to convert the said instance into string? In case you want to write the pub-key to a file, you can use save_pub_key def save_pub_key(self, file): """ Save the public key to a file in PEM format. @type file: string @param file: Name of file to save key to. """ Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From sierra2 at gmail.com Fri Sep 26 12:43:30 2008 From: sierra2 at gmail.com (Edel SM) Date: Sat, 27 Sep 2008 00:43:30 +0800 Subject: Time.sleep(0.0125) not available within Linux In-Reply-To: References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: helllo, On Fri, Sep 26, 2008 at 3:46 PM, Lawrence D'Oliveiro wrote: > In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: >> >>> Just a thought, your minimum sleep time is probably limited by the >>> resolution of the system "HZ" clock. Type >>> >>> less /proc/config.gz >> >> $ less /proc/config.gz >> /proc/config.gz: No such file or directory >> or: less /boot/config-`uname -r` >> >> What OS are you using? > > The one named in the subject line? > -- > http://mail.python.org/mailman/listinfo/python-list > -- edel From samslists at gmail.com Fri Sep 19 01:34:48 2008 From: samslists at gmail.com (Sam) Date: Thu, 18 Sep 2008 22:34:48 -0700 (PDT) Subject: Program works great, except under less, cron or execl (Unicode?) References: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> <6jekbbF2v55pU2@mid.uni-berlin.de> Message-ID: Diez for the win... :) sys.stdout.encoding does indeed have the proper value when called from the command line of UTF-8. But when piped into anything or called from anywhere it's None. Just for completeness, here's my test program: #!/usr/bin/env python import sys print sys.stdout.encoding And here are the results: $ ./encoding.py UTF-8 $ ./encoding.py | cat None Really, really annoying! So how can I set sys.stdout.encoding so it's UTF-8 when piped through cat (or anything else). I tried assigning to it, but no dice. On Sep 18, 2:12?am, "Diez B. Roggisch" wrote: > Sam wrote: > > I have a program which works great when run from the command line. > > > But when I run it combined with something else such as: > > - piping it through less > > - cron > > - execl (i.e. calling it from another python program) > > > it gives me a unicode error > > > ?File "../myparser.py", line 261, in set_attributes > > ? ? print "self.atd['Name'] is: ", self.atd['Name'] > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in > > position 7: ordinal not in range(128) > > > I'd post the whole program here, except it involves weird Unicode > > strings. > > > I could probably change the program to get it working under less/cron/ > > etc. > > > But I'd rather understand exactly what the issue is. ?Why does it work > > fine when run directly from the command line, but not otherwise? > > Most probably because when to running directly inside a terminal, it gets > it's stdin/stdout as pipes - and python can't attempt to guess the proper > encoding on that, as it does on a terminal. > > And thus, when you print unicode to the pipe, it can't decide which encoding > to use. > > To circumvene this, try & wrap stdout into a codecs-module wrapper with a > proper encoding applied (e.g. utf-8). > > You might make that conditionally based on the sys.stdout.encoding-variable > being set or not, albeit I'm not 100% sure to what it actually gets set > when used in a subprocess. But this should give you the idea where to look. > > Diez From lee.walczak at gmail.com Wed Sep 10 18:32:06 2008 From: lee.walczak at gmail.com (lee.walczak at gmail.com) Date: Wed, 10 Sep 2008 15:32:06 -0700 (PDT) Subject: Wx Python - Code Structure & Event Handling References: <48c6f5d9$0$2923$fa0fcedb@news.zen.co.uk> Message-ID: <220042a1-0532-4343-a956-8d82504739ec@r66g2000hsg.googlegroups.com> Thanks for the feedback. It is greatly appreciated. Let me check out your references and see where they take me. Will post back and let you know how useful this was. thanks! Lee From prologic at shortcircuit.net.au Sun Sep 7 19:14:56 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 09:14:56 +1000 Subject: Updating python dictionary In-Reply-To: <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> Message-ID: On Mon, Sep 8, 2008 at 8:59 AM, John Machin wrote: > What do you mean by "this right"? Perhaps the Divine Right of OPs, > managers, examiners, business analysts, etc never to give a complete > spec up front and never to contemplate the consequences of Murphy's > Law? Now you're being silly. -- -- -- "Problems are solved by method" From steven at REMOVE.THIS.cybersource.com.au Thu Sep 18 01:01:33 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 05:01:33 GMT Subject: How to Determine Name of the Day in the Week References: <0928a498-1cc0-48c7-985e-4faf019d8a70@m3g2000hsc.googlegroups.com> Message-ID: On Wed, 17 Sep 2008 20:34:02 -0700, Mensanator wrote: > And technically, weeks begin on Sunday, not Monday, but business likes > to think of Monday as day 0 of the week and it doesn't conflict with any > prior date format. There's no "technically" about it. It's an arbitrary starting point, and consequently there are different traditions to it, even in English. Besides, I don't think many businesses think of "day 0" at all. Most people outside of IT start counting from 1, not 0. In British Commonwealth countries, Sunday is the last day of the week, not the first, although under American influence that's changing in Australia at least. In Poland, the week begins with Monday ("poniedzia?ek"). Tuesday, "wtorek", means "second day". Other Slavic countries also start with Monday. Similarly, the Lithuanian calendar simple enumerates the days of the week, starting with Monday, "pirmadienis" ("first day"). In China, there are at least three different systems of naming the week days. In two of them, the week starts with Sunday, but in the third system, Sunday is "zhoumo" ("cycle's end") and Monday is zhouyi ("first of cycle"). -- Steven From nytrokiss at gmail.com Mon Sep 29 01:59:01 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 28 Sep 2008 22:59:01 -0700 Subject: Web programming in Python. In-Reply-To: <558b73fb0809281840h26a2fedl65fa7ed5a7dec2a7@mail.gmail.com> References: <558b73fb0809281840h26a2fedl65fa7ed5a7dec2a7@mail.gmail.com> Message-ID: <8a6b8e350809282259t1bb4e8fbs7a7a2f5a2d56c1ab@mail.gmail.com> If you are considering using a framework try Django. I enjoy using it! On Sun, Sep 28, 2008 at 6:40 PM, Michael Crute wrote: > On Sun, Sep 28, 2008 at 6:39 PM, Kurda Yon wrote: > > I am totaly newbie in the Python's web programming. So, I dont even > > know the basic conceptions (but I have ideas about php-web- > > programming). Does it work in a similar way? First, I have to install > > a Python-server? > > There are a couple of different ways to do web development in python. > The easiest if you're familiar with web development in other languages > is through CGI. I would recommend reading up on the python cgi module > [1] which will walk you through the basics of writing your first cgi > program. When you're comfortable with basic cgi you might want to look > into a framework like Django or CherryPy. > > -mike > > [1] http://docs.python.org/lib/module-cgi.html > > -- > ________________________________ > Michael E. Crute > http://mike.crute.org > > God put me on this earth to accomplish a certain number of things. > Right now I am so far behind that I will never die. --Bill Watterson > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ http://www.jewelerslounge.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Sep 26 19:05:07 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 16:05:07 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: Message-ID: <4b195687-e4a5-4fdd-89b2-f3906e625770@j22g2000hsf.googlegroups.com> On Sep 26, 6:31?am, s... at pobox.com wrote: > I took over spam filter management for the python.org mailing lists a couple > months ago and made a few changes to the way the spam filter is trained. > Things seem to be at a reasonable level as far as I can tell (I see a few > spams leak through each day), though I wasn't actively reading > comp.lang.python/python-l... at python.org before I took over the task, so I > have nothing to compare with. ?Does the level of spam leaking through the > filter now seem excessive? ?Is it more or less than in June and July? > > Thanks, > > Skip Montanaro Is there such a thing as an open-source spam filter? That way any time anyone had spare time and got annoyed, they could dump a short snippet of code into the grinder. Check-in would be tricky. It would need lots of votes, and voters would see a list of retroactive consequences of the change. (Marks these five things as spam.) I'm not sure that the rule-making is any better in the hands of many than it is of one (in general, to the OP), considering the power of stupid in large numbers, and the ease of submitting a filter for 'if name== "D'Aprano"'. That is, surely Skip wouldn't do that, but a group might. I've never gone spamming, so I don't know: Is it really easy (and necessarily profitable) to see, "if 'python' not in contents" and add the word to the mail? Or is it not worth the time it takes to catch that list? They're greedy, not bored. From marco.bizzarri at gmail.com Sat Sep 13 09:56:40 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 13 Sep 2008 15:56:40 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <6ivbfvFnfucU1@mid.uni-berlin.de> References: <6ivbfvFnfucU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> On Fri, Sep 12, 2008 at 4:09 PM, Diez B. Roggisch wrote: > > You should also consider using PEP8 style naming. > > > Diez class FolderInUse: def __init__(self, core): self.core = core def true_for(self, archivefolder): return any([instance.forbid_to_close(archivefolder) for instance in self.core.active_outgoing_registration_instances()]) Is this any better? The true_for name does not satisfy me a lot... maybe because it is too similar to True. Anyway, I'm trying a good naming so that code is readable, like: specification = FolderInUse(core) if specification.true_for(folder): ... Any thought about this? Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From michele at nectarine.it Tue Sep 30 17:25:49 2008 From: michele at nectarine.it (Michele) Date: Tue, 30 Sep 2008 23:25:49 +0200 Subject: md5 hash problems Message-ID: <48e2995e$0$18149$4fafbaef@reader3.news.tin.it> Hi there, why is this code generating a problem? >>> input = open('foo.img','rb').read().decode('ISO-8859-1') >>> import md5 >>> md5.new(input).hexdigest() Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xdc' in position 6: ordinal not in range(128) >>> Thank you. From antroy at gmail.com Fri Sep 19 06:10:10 2008 From: antroy at gmail.com (Ant) Date: Fri, 19 Sep 2008 03:10:10 -0700 (PDT) Subject: Problem with Python shell through Cygwin Screen (Python/Vim/Screen combo) Message-ID: <1e357c83-b53b-4587-a4d3-5327d1762341@k13g2000hse.googlegroups.com> Hi all, There's a sweet combination of tools that you can assemble using Vim, a Python shell (or any shell for that matter) and GNU screen, where you essentially send selected text from Vim to the Python shell. (See http://technotales.wordpress.com/2007/10/03/like-slime-for-vim/ for more details - though I had to tweak the script a bit to get it to work on Windows - line ending interpretation problem) This works great in Linux, and also in Windows using the Cygwin build of Python, but when you call: screen -S py -s python using the Windows build of Python, the shell just hangs. Does anyone know if this is a known issue with screen/Python, or if there is a workaround, as I'd prefer to have just a single Python instance installed rather than having Cygwin python and windows Python both installed. Cheers, Ant. From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 13:19:43 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 19:19:43 +0200 Subject: is decorator the right thing to use? In-Reply-To: References: <48db50aa$0$3750$426a74cc@news.free.fr> Message-ID: <48dbc82e$0$1120$426a74cc@news.free.fr> Dmitry S. Makovey a ?crit : > Thanks Bruno, > > your comments were really helpful (so was the "improved" version of code). > > My replies below: > > Bruno Desthuilliers wrote: >>> So decorators inside of B just identify that those methods will be >>> proxied by A. On one hand from logical standpoint it's kind of weird to >>> tell class that it is going to be proxied by another class, >>> >> Indeed - usually, proxied objects shouldn't have to be aware of the >> fact. That doesn't mean your variation on the proxy pattern is >> necessarily bad design (hard to tell without lot of context anyway...), >> but still there's some alarm bell ringing here IMHO - IOW : possibly the >> right thing to do, but needs to be double-checked. > > I'm kind of looking at options and not dead-set on decorators, but I can't > find any other "elegant enough" solution which wouldn't lead to such tight > coupling. The problem I'm trying to solve is not much more complicated than > what I have already described Well... You didn't mention why you need a proxy to start with !-) > so if anybody can suggest a better approach - > I'm all for it. > (snip code) >> My point is that: >> 1/ you shouldn't have to rewrite a decorator function - with basically >> the same code - for each possible proxy class / attribute name pair combo >> 2/ making the decorator an attribute of the proxy class makes >> dependencies clearer (well, IMHO at least). > > agreed on all points > >> I'm still a bit uneasy wrt/ high coupling between A and B, and if I was >> to end up with such a design, I'd probably take some times to be sure >> it's really ok. > > that is the question that troubles me at this point - thus my original post > (read the subject line ;) ). I like the clarity decorators bring to the > code and the fact that it's a solution pretty much "out-of-the-box" without > need to create something really-really custom, but I'm worried about tight > coupling and somewhat backward logic that they would introduce (the way I > envisioned them). Well... The canonical solution for delegation in Python is using __getattr__. Your problem - according to this post and your answer to Diez - is that your proxy may have to 1/ delegate to more than one object 2/ don't necessarily delegate each and any attribute access I can envision one solution using both __getattr__ and a simple decorator: def proxy(func): func._proxied = True return func class A(object): def __init__(self, delegates): self._delegates = delegates def __getattr__(self, name): for d in self.__delegate: func = getattr(d, name) if callable(func) and getattr(func, '_proxied', False): return func raise AttributeError( 'object %s has no attribute '%s' % (self.__class__, name) ) class B(object): def __init__(self): self.val='bval' @proxy def bmethod(self,a): print "B::bmethod" print a, self.val @proxy def bmethod2(self,a): print "B::bmethod2" print a, self.val class C(object): def __init__(self): self.val='bval' @proxy def cmethod(self,a): print "B::bmethod" print a, self.val @proxy def cmethod2(self,a): print "B::bmethod2" print a, self.val a = A([B(), C()]) # not tested... This solves most of the coupling problems (B and C still have to make clear which methods are to be proxied, but at least they need not know which class will be used as proxy), and makes sure only 'allowed' method calls are delegated. But I wouldn't call it a perfect solution neither. If you do have more than one object having method xxx, only the first one will match... And let's not talk about the lookup penalty. There's a possible variant that avoids the call to __getattr__ (in short: attaching delegation instancemethods to A instance in the initializer for each proxied method in delegates), but that wont solve the problem of potential name clashes. My 2 cents... From maric at aristote.info Wed Sep 3 10:52:06 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 3 Sep 2008 16:52:06 +0200 Subject: properties setting each other In-Reply-To: <200809031644.10870.maric@aristote.info> References: <200809031644.10870.maric@aristote.info> Message-ID: <200809031652.06431.maric@aristote.info> Le Wednesday 03 September 2008 16:44:10 Maric Michaud, vous avez ?crit?: > ? ? ? ? ?def _setsquare(self, v) : > ? ? ? ? ? ? ? ? ?# some extra logic here > ? ? ? ? ? ? ? ? ?self._square = s > > ? ? ? ? ?def fsetsquare(self,s): > ? ? ? ? ? ? ? ? ?self._setsquare(s) > ? ? ? ? ? ? ? ? ?self._setvalue = math.sqrt(s) > > ? ? ? ? ?def _setvalue(self, val): > ? ? ? ? ? ? ? ? ?# some extra logic here > ? ? ? ? ? ? ? ? ?self._internalval=val > > ? ? ? ? ?def fsetvalue(self, val): > ? ? ? ? ? ? ? ? ?self._setvalue(val) > ? ? ? ? ? ? ? ? ?self._setsquare=pow(val,2) Oh sorry for this last version the setters should be : def fsetsquare(self,s): self._setsquare(s) self._setvalue = math.sqrt(self.square) def fsetvalue(self, val): self._setvalue(val) self._setsquare=pow(self.value, 2) as we don't know what is done in _setXXX methods. -- _____________ Maric Michaud From mfajer at gmail.com Sun Sep 28 02:29:30 2008 From: mfajer at gmail.com (Mikolai Fajer) Date: Sat, 27 Sep 2008 23:29:30 -0700 Subject: design pattern: MVC in python Message-ID: <3ff66ae00809272329mce8d3c9lb94c316e169cf63a@mail.gmail.com> The following link directly discusses using MVC and pygame. http://ezide.com/games/writing-games.html -- -Mikolai Fajer- From gogtesuyash at gmail.com Wed Sep 17 08:04:02 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 05:04:02 -0700 (PDT) Subject: Problem occured while sending mail Message-ID: this is my code import sys, os, glob, datetime, time import smtplib ## Parameters for SMTP session port=587 SMTPserver= 'smtp.gmail.com' SMTPuser= '... at gmail.com' pw= 'fill in here' SENDER= SMTPuser ## Message details FROM= SENDER TO= 'notgm... at a.com' CC=FROM ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC RECEIVERS= (TO,) ## ignore the CC address subject= 'Test 1a' message='*** Email test *** ' print 'Starting SMTP mail session on %s as %s ' % (SMTPserver,SMTPuser) session = smtplib.SMTP(SMTPserver,port) session.set_debuglevel(0) # set debug level to 1 to see details session.ehlo(SMTPuser) # say hello session.starttls() # TLS needed session.ehlo(SMTPuser) # say hello again, not sure why session.login(SMTPuser, pw) ##Create HEADER + MESSAGE HEADER= 'From: %s\r\n' % FROM HEADER= HEADER + 'To: %s\r\n' % TO HEADER= HEADER + 'Cc: %s\r\n' % CC HEADER= HEADER + 'Subject: %s\r\n' % subject BODY= HEADER + '\r\n' + message print BODY SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email session.close() Now when i run this .py file...as python mail.py i can see only statement starting smtp mail......n details then nothing on screen after few minutes or after pressing ctrl +c Traceback (most recent call last): File "mail4.py", line 21, in session = smtplib.SMTP(SMTPserver,port) File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect self.sock.connect(sa) File "", line 1, in connect or may be conncetion time out wats the solution for this From hrishys at yahoo.co.uk Thu Sep 25 06:06:14 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 10:06:14 +0000 (GMT) Subject: Linq to Python In-Reply-To: <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> Message-ID: <10513.56961.qm@web27403.mail.ukl.yahoo.com> Hi If i rephrase my question how will i do this in Python http://informationr.net/ir/13-2/TB0806.html Watch this query on the page Where he joins all different kind of things with ease and elegance(as per my opinion) [code] var stoogeGuys = Beginning with the XML source from xmlGuys in xmlSource.Descendants("Stooge") Join to the array on the common element "stoogeName" join arrayGuys in familyFacts on xmlGuys.Element("stoogeName").Value equals arrayGuys.stoogeName Join to the database on the common element "stoogeName" join dbGuys in stoogeContext.stoogeTables on xmlGuys.Element("stoogeName").Value equals dbGuys.stoogeName select new { firstName = dbGuys.stoogeName, familyName = arrayGuys.familyName, birthDate = xmlGuys.Element("birthDate").Value, deathDate = xmlGuys.Element("deathDate").Value, hairCutStyle = dbGuys.stoogeHaircut, }; [/code] regards Hrishy From geonomica at gmail.com Mon Sep 1 08:49:46 2008 From: geonomica at gmail.com (gianluca massei) Date: Mon, 01 Sep 2008 14:49:46 +0200 Subject: __stack_chk_fail_local In-Reply-To: <3f0d61c40808300619l47122583i373493b075d1f422@mail.gmail.com> References: <3f0d61c40808300619l47122583i373493b075d1f422@mail.gmail.com> Message-ID: <48BBE4EA.5070606@libero.it> thanks for the help, maybe the solution will be useful: in "various Linux distributions are starting to ship with a version of the GNU C compiler which incorporates an extension which implements protection for stack-smashing". In that case the Makefile has to modified with CFLAGS = -fno-stack-protector gianluca Marco Bizzarri wrote: > On Sat, Aug 30, 2008 at 3:03 PM, g_massa at libero.it wrote: > >> Thanks! >> I've resolved the problem with libraries but... I've still error with this message: >> ImportError: ./_python_grass6.so: undefined symbol: __stack_chk_fail_local >> >> exuse me, I'm not a guru. >> >> Gianluca >> >> > > I'm not a guru either, Gianluca ;) > > I made a little search on Google; the first link is the following: > > http://ubuntuforums.org/showthread.php?t=352642 > > can you apply the suggestion? > > I think you should give a little more context on your problem, also, > because I think it has to do with your setup (not that you setup > something in the wrong way: just to have context). > > Regards > Marco > > > > > From deets at nospam.web.de Fri Sep 5 11:02:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 17:02:53 +0200 Subject: Make Games In-Reply-To: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> References: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> Message-ID: <6id00tFq2em1U1@mid.uni-berlin.de> NightZombie schrieb: > x-no-archive: yes > > I want to learn Python so I can make simple games. What are some good > books that'll help me do this? Don't know about books, but I don't think it is important that the books are about python for game programming - game programming in general will help. On http://pygame.org/ you can see quite a few examples on how to create games using pygame, and then there are projects such as pyglet, nodebox and of course PyOpenGL itself. Diez From bthate at gmail.com Tue Sep 16 04:58:48 2008 From: bthate at gmail.com (Bart Thate) Date: Tue, 16 Sep 2008 01:58:48 -0700 (PDT) Subject: GOZERBOT 0.8.2-BETA released Message-ID: It is time for a new gozerbot release so we are pushing a new BETA for the world to test. This time the change is rather big as most plugins are removed from the core and put into there own tarball. So if you want to try out 0.8.2-BETA for us and report any problems with it on http://dev.gozerbot.org/ or in our channel #dunkbots on IRCnet we would very much appreciate it. You can also contact me at bthate at gmail.com. Download can be done from our website http://gozerbot.org/ new features: * most plugins removed from core .. this keeps the base of the bot as small as possible * missing plugins can be installed via internet or via tarball * rewritten core .. callbacks and commands when not threaded are not executed in the main loop anymore but instead in what are called ?runners?, threads that do the jobs. this limits the threads that are launched * new debug mode that enables more verbose logging (stacktrace) * a REST server and client have been added to the core .. the cloud plugin uses these to communicate between bots. data is transfered in json format * new plugins are added to the plugin collection o powernick (core) .. a plugin to relay the log file to an OPER via DCC CHAT o throttle (core) .. throttle users to max number of commands per minute o cloud (myplugs) .. connect gozerbots together o traclog (myplugs) .. log channel in a format suitable for integration with trac o register (myplugs) .. enables users to register themselves with the bot o anon (myplugs) .. register users on channel join * config changes are now written to the config file instead of a pickle TAKE NOTE: most of the plugins are removed from the core bot .. you can use the !install-defaultplugs command to get most of these plugins .. otherwise see !install-list of plugins that can be installed About gozerbot: Requirements * a shell * python 2.4 or higher * if you want to remotely install plugins: the gnupg module * if you want mysql support: the py-MySQLdb module * if you want jabber support: the xmpppy module Why gozerbot? * provide both IRC and Jabber support * user management by userhost .. bot will not respond if it doesn't know you (see /docs/USER/) * fleet .. use more than one bot in a program (list of bots) (see / docs/plugins/FLEET/) * use the bot through dcc chat * fetch rss feeds (see /docs/plugins/RSS/) * remember items * relaying between bots (see /docs/plugins/RELAY/) * program your own plugins (see /docs/PROGRAMPLUGIN/) * run the builtin webserver (see /docs/plugins/WEBSERVER/) * query other bots webserver via irc (see /docs/plugins/ COLLECTIVE/) * serve as a udp <-> irc or jabber notification bot (see /docs/ plugins/UDP) * mysql and sqlite support the gozerbot development team From alan.isaac at gmail.com Mon Sep 1 12:02:07 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Mon, 01 Sep 2008 16:02:07 GMT Subject: Writing to ms excel In-Reply-To: References: Message-ID: <3mUuk.216$jE1.59@trnddc03> http://docs.python.org/lib/module-csv.html From joe.hrbek at gmail.com Wed Sep 24 15:24:32 2008 From: joe.hrbek at gmail.com (Joe Hrbek) Date: Wed, 24 Sep 2008 12:24:32 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: Message-ID: <717d439a-60c2-4808-adac-e5adcc25275e@k7g2000hsd.googlegroups.com> Todd, this is great! Thanks for your work on this. I've been using your extension for awhile, successfully creating little apps. Your gui_app template has been a huge help in advancing my understanding of how things fit together...takes some of the guesswork out. :) Thanks again, -j On Sep 16, 8:29?pm, Todd Whiteman wrote: > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming language. > > The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX > is possible with a few deviations, I have tried to cover these > deviations where applicable). > > Feedback is welcome. > > Cheers, > Todd From __peter__ at web.de Thu Sep 25 03:52:55 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2008 09:52:55 +0200 Subject: empty csv file attachments References: <200563c8-a4d1-45db-aaa1-63f885851b76@s50g2000hsb.googlegroups.com> Message-ID: Bobby Roberts wrote: > I'm new to python but a veteran at programming. ? Hm, your code doesn't show that. The time to read the tutorial would be time well spend. After that, a quick look at what the standard library has to offer wouldn't hurt. E. g. reading/writing CSV files is a solved problem in python ;) > This one has me > stumped. ?I have a simple contact form which the user fills out. ?The > email is sent to the site user as well and it is delivered with the > content in the body of the email as well in nice order. ?I have > modified my code to also send the content as a csv attachment. ?On the > server, the file is perfectly generated with content. ?The attachment, > however, is completely blank. ?Any ideas what that could be? ?My code > snippet is shown below: > > > ? ? ? if int(attachmenttype)==2 or int(attachmenttype)==3: > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? if field=='last_name': > ? ? ? ? ? ? myfilename=ctx.request.field_value(field)+'.txt' > ? ? ? ? if myfilename=='': > ? ? ? ? ? myfilename='tempfile.txt' > ? ? ? ? mypath= mynewfilepath + '/' + myfilename > ? ? ? ? f=open(mypath, 'w') > ? ? ? ? mynewstring='' > ? ? ? ? counter=0 > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? if field != 'inquiry_required': > ? ? ? ? ? ? mynewstring=mynewstring + field +',' > ? ? ? ? if mynewstring[-1]==',': > ? ? ? ? ? mynewstring=mynewstring[0:len(mynewstring)-1] > ? ? ? ? f.write(mynewstring) > ? ? ? ? f.write ('\n') > > ? ? ? ? mynewstring='' > ? ? ? ? counter=1 > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? fielddata=ctx.request.field_value(field) > ? ? ? ? ? if counter==1: Hm, above you skip the field "inquiry_required", here you skip the second field. > ? ? ? ? ? ? dummydata=0 > ? ? ? ? ? else: > ? ? ? ? ? ? mynewstring=mynewstring + '"' + fielddata.replace('"','') > + '",' > ? ? ? ? ? counter = counter + 1 > ? ? ? ? if mynewstring[-1]==',': > ? ? ? ? ? mynewstring=mynewstring[0:len(mynewstring)-1] > ? ? ? ? f.write(mynewstring) > ? ? ? ? f.write('\n') > ? ? ? ? f.close Your actual problem might be that f.close doesn't close (and therefore flush) the file, you need to call it with f.close(). > ? ? ? ? attachments.append('/'.join((ctx.request.library, > myfilename))) Hm, is ctx.request.library the same as mynewfilepath? With some guessing your code becomes (untested) import csv import os if int(attachmenttype) in (2, 3): filename = 'tempfile.txt' if "last_name" in ctx.request.field_names(): last_name = ctx.request.field_value("last_name") if last_name: filename = last_name + ".txt" path = os.path.join(ctx.request.library, filename) f = open(path, 'wb') writer = csv.writer(f) fieldnames = [field for field in ctx.request.field_names() if field != "inquiry_required"] writer.writerow(fieldnames) writer.writerow(ctx.request.field_value(field) for field in fieldnames) f.close() attachments.append(path) The code to build the filename is still clumsy, but to do better I'd have to know the library you are using. Personally I'd always use "tempfile.txt" and be done. This would also avoid fun with last names like ../../just_testing_file_permissions. Peter From bdesth.quelquechose at free.quelquepart.fr Sun Sep 28 14:47:11 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 Sep 2008 20:47:11 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <48dd5f08$0$26425$426a74cc@news.free.fr> Message-ID: <48dfed19$0$17486$426a74cc@news.free.fr> Tim Rowe a ?crit : > 2008/9/26 Bruno Desthuilliers : > >> Not to start a troll, but from what I've seen of C# so far I do find this a >> bit surprising and really suspect more of a library issue than a language >> one. Care to tell more about the problem and solution ? >> >> (NB : I wouldn't even asked if you had mentionned say Erlang or Prolog or >> OCaml - well, some mostly different language - instead of C#) > > IIRC it was library issues -- for one thing I still find it a lot > harder to manage an MS Windows GUI under Python than I do under .NET > (I've never succeeded in getting Iron Python to run properly). In one > sense you could argue that that's not a language issue, and you'd be > right: there's nothing in the syntax or semantics of either language > that makes it so. But in another sense I'd say it is a language issue > (and of course I think I'm right!) And - after reading the following argument - I think you're wrong !-) > because Python aims to be platform > independent, and whilst that means gains in portability it means that > in return it loses the ease-of-programming of a tightly integrated > platform. > Still a library issue. Python doesn't defines "platform-independant" the way Java does, and there are quite a couple Python packages (third-part or even in the standard lib) that are clearly platform-specific - including MS Windows COM stuff, which was a major PITA using VB6. From tilmaniac at gmail.com Mon Sep 29 15:35:47 2008 From: tilmaniac at gmail.com (Tilman Kispersky) Date: Mon, 29 Sep 2008 12:35:47 -0700 (PDT) Subject: Cannot install pysqlite on Cygwin References: Message-ID: On Sep 29, 12:37?pm, Tilman Kispersky wrote: > On Sep 29, 7:49?am, Steve Holden wrote: > > > > > Tilman Kispersky wrote: > > > I am trying to install sqlite for use with python oncygwin. I have > > > installed the sqlite packages fromcygwin(that is libsqlite3-devel > > > and libsqlite3_0). ?When attempting to easy_install pysqlite I get: > > > > $ easy_install pysqlite > > > Searching for pysqlite > > > Readinghttp://pypi.python.org/simple/pysqlite/ > > > Readinghttp://pysqlite.org/ > > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ > > > Readinghttp://pysqlite.sourceforge.net/ > > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/ > > > Readinghttp://initd.org/tracker/pysqlite/wiki/PysqliteDownloads > > > Readinghttp://oss.itsystementwicklung.de/trac/pysqlite > > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/ > > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/ > > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/ > > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/ > > > Best match: pysqlite 2.5.0 > > > Downloadinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlit... > > > Processing pysqlite-2.5.0.tar.gz > > > Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/ > > > Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg- > > > dist-tmp-7mr3WS > > > warning: no files found matching 'doc/*.html' > > > warning: no files found matching 'doc/code/*.py' > > > src/statement.c: In function `pysqlite_statement_recompile': > > > src/statement.c:351: warning: `sqlite3_transfer_bindings' is > > > deprecated (declared at /usr/include/sqlite3.h:3985) > > > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function > > > `pysqlite_enable_load_extension': > > > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ > > > pysqlite-2.5.0/src/connection.c:922: undefined reference to > > > `_sqlite3_enable_load_extension' > > > collect2: ld returned 1 exit status > > > error: Setup script exited with error: command 'gcc' failed with exit > > > status 1 > > > $ > > > > It seems to me this is due to some missing library (undefined > > > reference...) but I have no idea what these missing files might be. > > > I've tried installing everything that made any reference to sqlite > > > form thecygwininterface. ?Does anyone know how I might get a working > > > install of sqlite for python oncygwin? > > > I believe it's a glitch in the 2.5.1 distribution current onCygwin- I > > had to install the _sqlite DLL separately to get it to work, but no > > recompilation was necessary AFAICR. > > > Chui Tey detailed the necessary steps in his blog post "CygwinPython > > and sqlite3", but sadly it got lost and he hasn't replenished it, so you > > will have to stab around to see if there's a cached copy anywhere. > > > regards > > ?Steve > > -- > > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ > > Well, I haven't managed to solve the problem. > > I tried following these instructions but get the same error:http://initd.org/pub/software/pysqlite/doc/install-source-win32.html > > And I also tried downloading the dll from sqlite.org and putting it on > my path. > > Since someone asked how I ended up solving this problem: > I'm just going to work on my Linux box where its relatively straight > forward to install > this stuff with the package manager. > > If someone does have instructions for making this work on windows I'd > be very curious. I was unable to find an archived version of the blog > post referenced above. I also managed to get it to work by not using cygwin's python. I suppose this is sort of the obvious solution. Just download the windows installers for python, pysqlite. You can still run the windows installed version of python from cygwin (I prefer that over the 'cmd' terminal) by specifying the executable you want to use explicity eg: $ /cygdrive/c/Python25/python From mhuening at zedat.fu-berlin.de Wed Sep 10 10:07:07 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Wed, 10 Sep 2008 16:07:07 +0200 Subject: PHP's str_replace ? In-Reply-To: References: Message-ID: <6iq2jpFs113rU1@mid.uni-berlin.de> Anjanesh Lekshminarayanan (10.09.2008 15:50): > In PHP, if I do > str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) > it'll replace all vowels with a hyphen in string $str. > > Is there some equivalent in Python ? What about something like this: import re new_str = re.sub('([aeiou])-', r'\1', str) Matthias From dave.dibiase at gmail.com Fri Sep 26 10:22:42 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Fri, 26 Sep 2008 10:22:42 -0400 Subject: Fastest way to max() list In-Reply-To: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> References: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> Message-ID: Hi Chris, Yeah I hear you on point A. but this the specification I was given, so I have to follow it unfortunately. I've also been restricted and not allowed to use any other packages. I was using NumPy earlier (should have mentioned that) but I was wondering if there was a simpler way. Is NumPy technically even faster than just iterating and modifying the list directly? Also if I'm creating an array then making it, why not just do a temporary sort and capture the first and last values? Is this method you've provided supposed to be faster? Dave On Fri, Sep 26, 2008 at 12:42 AM, Chris Rebert wrote: > On Thu, Sep 25, 2008 at 8:57 PM, David Di Biase > wrote: > > I have a list with about 1000-1500 sub-lists which look like so: > > list[-0.28817955213290786, 3.6693631467403929, 'H', 31.31225233035784]] > > > > The first and second values are Angstrom units specifying the location of > a > > particle. What I'd like to do is determine the distance between the > smallest > > and largest value in the arrays first position 0. I tried reading the > manual > > for this but I don't see how it applies key or any of those other > commands > > to the function. I could easily write a sort to do this and capture the > > first and last spots, but why do that when I can use max and min (if I > can > > actually do that...). > > A. You should probably be using objects rather than arrays to > represent your datapoints, so that they're more structured and it's > more apparent what the values mean. > > B. Assuming by "distance" you meant "difference" and/or that the > distance is only in 1 dimension: > > from operator import itemgetter > firsts = map(itemgetter(0), main_list) > distance = max(firsts) - min(firsts) > > > > > So you wonderful Python gods, lay some knowledge on me. please? lol... > > > > while I'm at it, is there a way to modify an entire list without having > to > > produce a whole new one? For example now say I want to modify list[0] and > > multiply it by some value. From what I understand previous version of > Python > > allowed lists to be multiplied like matrices...now apparently it just > > replicates the list. :-/ shucks... > > You just have to apply the transform to each list element individually > (also, you might consider using NumPy [http://numpy.scipy.org/] if > you're doing a lot of matrix manipulation): > > for lst in main_list: > lst[0] *= some_value > > Regards, > Chris > > > > > The first question would be useful to know, but the second question I do > > quite a bit of and the "best practice" would be really great to know! > > > > Thanks in advanced! > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- > Follow the path of the Iguana... > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolkid246 at googlemail.com Thu Sep 4 06:10:48 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:10:48 -0700 (PDT) Subject: =?ISO-8859-1?Q?kredit_fuer_selbststaendige_in_Stollberg_kredit_onli?= =?ISO-8859-1?Q?ne_beantragen_online_kredite_im_kredit_ohne_gehaltsnachweis_?= =?ISO-8859-1?Q?online_credit_ohne_kredit_ohne_schufa_vergleich_kredite_von_?= =?ISO-8859-1?Q?privat_bank_kredite_schweizer_kredit_ohne_schufa_eilkredit_o?= =?ISO-8859-1?Q?hne_schufa__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTIGE_KREDITE_ONLINE_=2B=2B=2B_KREDITE?= =?ISO-8859-1?Q?_IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_=2B_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D2?= =?ISO-8859-1?Q?44=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKRED?= =?ISO-8859-1?Q?ITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_htt?= =?ISO-8859-1?Q?p=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D2?= =?ISO-8859-1?Q?44=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKRED?= =?ISO-8859-1?Q?ITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_=2B_=2B?= =?ISO-8859-1?Q?_=2B_=2B_______________________bank_kredite_kredite_fuer_arbeits?= =?ISO-8859-1?Q?lose_ohne_schufa_in_Sonthofen_sofortkredite_kredite_vergleic?= =?ISO-8859-1?Q?h_in_L=FCdenscheid_postbank_kredit_kredite_auch_ohne_schufa_i?= =?ISO-8859-1?Q?n_Wittlich_eilkredit_ohne_schufa_autokredit_in_Merzig_euro_k?= =?ISO-8859-1?Q?redite_kredite_schufa_in_Cloppenburg_schufafreie_kredite_bau?= =?ISO-8859-1?Q?finanzierung_online_in_Sulzbach_kredite_banken_online_kredit?= =?ISO-8859-1?Q?_trotz_schufa_in_Parchim_bargeld_kredite_bargeld_ohne_schufa?= =?ISO-8859-1?Q?_in_L=FCbben_online_kredite_von_privat_privatkredit_online_in?= =?ISO-8859-1?Q?_Luckenwalde_kredite_fuer_selbststaendige_kredit_girokonto_i?= =?ISO-8859-1?Q?n_Seelow_leasing_ohne_schufa_www_kredite_ohne_schufa_de_in_M?= =?ISO-8859-1?Q?iltenberg_internet_kredit_kfz_kredit_in_Garmisch=2DPartenkirch?= =?ISO-8859-1?Q?en_kredite_guenstiger_kredit_mit_schufa_in_Bad_Kreuznach____?= =?ISO-8859-1?Q?=2D_kredite_online_beantragen_darlehen_online_in_Wetzlar_=2D_gue?= =?ISO-8859-1?Q?nstige_kredit_online_kredit_auch_in_Mosbach_=2D_kredite_muench?= =?ISO-8859-1?Q?en_online_kredit_schufafrei_in_Mayen_=2D_kredit_ohne_schufa_se?= =?ISO-8859-1?Q?lbststaendige_kredit_online_beantragen_in_Germersheim_=2D_auch?= =?ISO-8859-1?Q?_ohne_schufa_kredite_banken_in_Pfaffenhofen_=2D_online_kredite?= =?ISO-8859-1?Q?_guenstig_privatkredite_ohne_schufa_in_Offenbach_=2D_kredit_sc?= =?ISO-8859-1?Q?hweiz_kredite_ohne_schufa_ohne_in_Waren_=2D_bar_kredit_ohne_sc?= =?ISO-8859-1?Q?hufa_kredit_ohne_gehaltsnachweis_in_Kirchheimbolanden_=2D_bill?= =?ISO-8859-1?Q?ig_kredit_dispo_kredit_in_Rhoen_=2D_online_kredit_mit_sofortzu?= =?ISO-8859-1?Q?sage_kredit_ohne_schufa_selbstaendige_in_Erlangen_=2D_kredit_o?= =?ISO-8859-1?Q?hne_schufa_test_kredite_beantragen_in_Schongau_Weilheim=2FObb=2E?= =?ISO-8859-1?Q?_=2D_euro_kredite_sofortkredite_in_Soltau_=2D_privat_kredite_ohn?= =?ISO-8859-1?Q?e_schufa_kredite_ohne_schufa_de_in_Heppenheim_=2D_www_kredit_o?= =?ISO-8859-1?Q?hne_schufa_kredit_ohne_schufa_selbststaendige_in_Oranienburg?= Message-ID: kredit fuer selbststaendige in Stollberg kredit online beantragen online kredite im kredit ohne gehaltsnachweis online credit ohne kredit ohne schufa vergleich kredite von privat bank kredite schweizer kredit ohne schufa eilkredit ohne schufa + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + bank kredite kredite fuer arbeitslose ohne schufa in Sonthofen sofortkredite kredite vergleich in L?denscheid postbank kredit kredite auch ohne schufa in Wittlich eilkredit ohne schufa autokredit in Merzig euro kredite kredite schufa in Cloppenburg schufafreie kredite baufinanzierung online in Sulzbach kredite banken online kredit trotz schufa in Parchim bargeld kredite bargeld ohne schufa in L?bben online kredite von privat privatkredit online in Luckenwalde kredite fuer selbststaendige kredit girokonto in Seelow leasing ohne schufa www kredite ohne schufa de in Miltenberg internet kredit kfz kredit in Garmisch-Partenkirchen kredite guenstiger kredit mit schufa in Bad Kreuznach - kredite online beantragen darlehen online in Wetzlar - guenstige kredit online kredit auch in Mosbach - kredite muenchen online kredit schufafrei in Mayen - kredit ohne schufa selbststaendige kredit online beantragen in Germersheim - auch ohne schufa kredite banken in Pfaffenhofen - online kredite guenstig privatkredite ohne schufa in Offenbach - kredit schweiz kredite ohne schufa ohne in Waren - bar kredit ohne schufa kredit ohne gehaltsnachweis in Kirchheimbolanden - billig kredit dispo kredit in Rhoen - online kredit mit sofortzusage kredit ohne schufa selbstaendige in Erlangen - kredit ohne schufa test kredite beantragen in Schongau Weilheim/Obb. - euro kredite sofortkredite in Soltau - privat kredite ohne schufa kredite ohne schufa de in Heppenheim - www kredit ohne schufa kredit ohne schufa selbststaendige in Oranienburg From boyee118 at gmail.com Sat Sep 20 00:14:09 2008 From: boyee118 at gmail.com (=?UTF-8?B?5Li654ix6ICM55Sf?=) Date: Sat, 20 Sep 2008 12:14:09 +0800 Subject: report a BUG of package setuptools-0.6c8. Message-ID: Traceback (most recent call last): File "setup.py", line 176, in main() File "setup.py", line 172, in main setup(**args) File "/usr/lib/python2.5/distutils/core.py", line 151, in setup dist.run_commands() File "/usr/lib/python2.5/distutils/dist.py", line 974, in run_commands self.run_command(cmd) File "/usr/lib/python2.5/distutils/dist.py", line 994, in run_command cmd_obj.run() File "/usr/lib/python2.5/site-packages/setuptools/command/install.py", line 76, in run self.do_egg_install() File "/usr/lib/python2.5/site-packages/setuptools/command/install.py", line 96, in do_egg_install self.run_command('bdist_egg') File "/usr/lib/python2.5/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.5/distutils/dist.py", line 994, in run_command cmd_obj.run() File "/usr/lib/python2.5/site-packages/setuptools/command/bdist_egg.py", line 167, in run self.run_command("egg_info") File "/usr/lib/python2.5/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.5/distutils/dist.py", line 994, in run_command cmd_obj.run() File "/usr/lib/python2.5/site-packages/setuptools/command/egg_info.py", line 171, in run self.find_sources() File "/usr/lib/python2.5/site-packages/setuptools/command/egg_info.py", line 252, in find_sources mm.run() File "/usr/lib/python2.5/site-packages/setuptools/command/egg_info.py", line 306, in run self.add_defaults() File "/usr/lib/python2.5/site-packages/setuptools/command/egg_info.py", line 333, in add_defaults rcfiles = list(walk_revctrl()) File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", line 45, in walk_revctrl for item in ep.load()(dirname): File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", line 52, in _default_revctrl for path in finder(dirname,path): File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", line 98, in entries_finder log.warn("unrecognized .svn/entries format in %s", dirname) NameError: global name 'log' is not defined global name 'log' is not defined to the line 98!!! -- "OpenBookProject"-?????????? ??: http://groups.google.com/group/OpenBookProject ??: http://wiki.woodpecker.org.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From asnast at gmail.com Sat Sep 20 19:22:31 2008 From: asnast at gmail.com (Alex Snast) Date: Sat, 20 Sep 2008 16:22:31 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: On Sep 20, 8:13?pm, bearophileH... at lycos.com wrote: > Duncan Booth: > > > > e.g. the python equivalent to the c++ loop > > > for (i = 10; i >= 0; --i) > > > The exact equivalent would be: > > ? ? ? ? for i in range(10, -1, -1): print i > > I'd use xrange there. Anyway, I have always felt that Python syntax > not easy to understand at first sight, expecially when you try to > convert a bit more complex inverted for loops from/to C to/from > Python. It's one of the few cases where (for example) Pascal (loop) > syntax wins a bit over Python syntax :-) > > Bye, > bearophile That's a lot of responses guys. Thanks a lot i think i got it. Another question, are there any pointers in python (or iterators) for when i use a data structure that doesn't support random access? Thanks again, Alex From tchendrix at gmail.com Tue Sep 23 09:00:34 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 06:00:34 -0700 (PDT) Subject: finding domain name References: Message-ID: <8b93f073-ed19-4410-a32f-8421cb0698d1@y38g2000hsy.googlegroups.com> On Sep 23, 8:54?am, "Joe Riopel" wrote: > On Tue, Sep 23, 2008 at 8:37 AM, Bobby Roberts wrote: > > hi group. ?I'm new to python and need some help and hope you can > > answer this question. ?I have a situation in my code where i need to > > create a file on the server and write to it. ?That's not a problem if > > i hard code the path. ?However, the domain name needs to be dynamic so > > it is picked up automatically. ?The path to our websites is > > > home/sites/xxxxx/ > > > where xxxxx represents the domain name. > > > How can I find the domain name of the current url being viewed. > > I would guess that a pretty simple regular expression might do it. can you explain? From http Tue Sep 2 14:28:39 2008 From: http (Paul Rubin) Date: 02 Sep 2008 11:28:39 -0700 Subject: Large amount of files to parse/organize, tips on algorithm? References: Message-ID: <7x1w02v1uw.fsf@ruckus.brouhaha.com> cnb writes: > For each file I construct a list of reviews and then for each new file > I merge the reviews so that in the end have a list of reviewers and > for each reviewer all their reviews. > > What is the fastest way to do this? Scan through all the files sequentially, emitting records like (movie, reviewer, review) Then use an external sort utility to sort/merge that output file on each of the 3 columns. Beats writing code. From lists at cheimes.de Thu Sep 18 19:36:46 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 19 Sep 2008 01:36:46 +0200 Subject: Python newbie question re Strings and integers In-Reply-To: References: Message-ID: rmac wrote: > > the following code attempts to extract a symbol name from a string: > extensionStart = int(filename.rfind('.')) > filenameStart = int(filename.rfind('/')) > #print 'Extension Start - ' + str(extensionStart) > #print 'FileName Start - ' + str(filenameStart) > currentSymbol=filename[int(filenameStart),int(extensionStart)] > > Uncommenting the print statements clearly show the values to be > integers (and without the str casts actually provide int+string > errors) > > However, executing this code results in... > opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv > Traceback (most recent call last): > File "rHistFileToDB_Equities.py", line 25, in > currentSymbol=filename[int(filenameStart),int(extensionStart)] > TypeError: string indices must be integers You are using , inside filename[]. The splicing syntax is start:end, not start,end. You are better off with using the appropriate APIs from the os.path module. http://docs.python.org/lib/module-os.path.html import os.path filename = os.path.basename(path) prefix, extension = os.path.splitext(filename) Christian From castironpi at gmail.com Fri Sep 12 01:26:27 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 22:26:27 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> Message-ID: <40c884c7-2fc6-4667-b47c-eb203e95711e@k30g2000hse.googlegroups.com> On Sep 11, 10:37?pm, Steven D'Aprano wrote: > On Thu, 11 Sep 2008 10:20:41 -0700, Aaron \"Castironpi\" Brady wrote: > > XML is the wrong word for the example I was thinking of (as was already > > pointed out in another thread). ?XML is by definition sequential. > > I'm pretty sure you're wrong. XML can be used for serialization, but that > doesn't mean it is only sequential data. XML is suitable for hierarchical > data too. To quote Wikipedia: > > "As long as only well-formedness is required, XML is a generic framework > for storing any amount of text or any data whose structure can be > represented as a tree. The only indispensable syntactical requirement is > that the document has exactly one root element (alternatively called the > document element)." > > http://en.wikipedia.org/wiki/Xml > > -- > Steven That's my choice of words at work again, I'm afraid. What I mean is, there is no possibility that you can correctly interpret a segment of XML text without knowing certain facts about everything that precedes it. Compare to the case of a fixed-length record file, of record size say 20, where you know the meaning of the characters in offset ranges 20-40, 80-100, 500020-500040, etc. To clarify the point of the use case in question, because data would be allocated and located dynamically, its possible that you could read the first several words, then not need anything until say, the 1KB mark. (Unless you're somehow storing an offset in to an XML string as a value in the string, which would require composing it, leaving room for that value, and then writing it with random access anyway.) There can be gaps in a dynamically managed buffer--- say the unused/free bytes from offsets 200 to 220, but every byte that follows another in an XML file follows it in the file's meaning too. Is this any clearer? Aaron From invalid at invalid Wed Sep 24 10:09:31 2008 From: invalid at invalid (Grant Edwards) Date: Wed, 24 Sep 2008 09:09:31 -0500 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: On 2008-09-24, Steven D'Aprano wrote: > On Tue, 23 Sep 2008 13:25:26 -0700, Drake wrote: > >> I have a general question of Python style, or perhaps just good >> programming practice. >> >> My group is developing a medium-sized library of general-purpose Python >> functions, some of which do I/O. Therefore it is possible for many of >> the library functions to raise IOError Exceptions. The question is: >> should the library function be able to just dump to sys.exit() with a >> message about the error (like "couldn't open this file"), or should the >> exception propagate to the calling program which handles the issue? >> >> Thanks in advance for anyone who can either answer my question or point >> me to where this question has already been answered. > > > Presumably somebody has suggested that calling sys.exit() was a good > option. I'm curious to what possible reason they could give for such a > poor choice. Same here. It's like an automotive engine controls designer asking if a failed O2 sensor should turn on the check engine light or blow up the car. -- Grant Edwards grante Yow! Mr and Mrs PED, can I at borrow 26.7% of the RAYON visi.com TEXTILE production of the INDONESIAN archipelago? From tjreedy at udel.edu Tue Sep 16 15:17:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 15:17:56 -0400 Subject: Python and Open Office In-Reply-To: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Hartmut Goebel wrote: > As I thought everybody already knows, ODF is simply a Zip-File > containing some XML files. I thought it just *was* xml. But examination with notepad showed otherwise. > So there is no need to use OOo for handling > the files. > > So odfpy seams to be the best way to to this. Since odfpy automatically handles combining the at-least-4 xml files into one coherent class on loading, and putting the various properties into the proper xml files on saving, this looks pretty straightforward. Thanks for the reference. One way to learn the meaning of some of the numerous attributes and values is to create a file with the wanted features with OOo, save, unzip, and examine the xml to see which tags are used for which features. You may also want to check > OOopy . I will glance at that too. > > If you are going to interact with OOo, you may want to try out > > From stefan_ml at behnel.de Thu Sep 4 14:20:49 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 04 Sep 2008 20:20:49 +0200 Subject: python/xpath question.. In-Reply-To: <48bf8a5c$0$10095$9b4e6d93@newsspool3.arcor-online.net> References: <48bf8a5c$0$10095$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <48c02701$0$19239$9b4e6d93@newsspool4.arcor-online.net> Stefan Behnel wrote: > Yes, learn to use XPath, e.g. > > //tr/td[not string()] Oh, well... //tr/td[not(string())] as I said, wrong news group. ;-) Try something like "gmane.text.xml.xpath.general", for example. Stefan From joncle at googlemail.com Wed Sep 10 15:13:52 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 12:13:52 -0700 (PDT) Subject: Reading binary data References: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> Message-ID: On Sep 10, 7:16?pm, Aaron Scott wrote: > Taking everything into consideration, my code is now: > > import struct > file = open("test.gde", "rb") > signature = file.read(3) > version, attr_count = struct.unpack('II', file.read(8)) > print signature, version, attr_count > for idx in xrange(attr_count): > ? ? ? ? attr_id, attr_val_len = struct.unpack('II', file.read(8)) > ? ? ? ? attr_val = file.read(attr_val_len) > ? ? ? ? print attr_id, attr_val_len, attr_val > file.close() > > which gives a result of: > > GDE 2 2 > 1 4 ? > 2 4 ??? > > Essentially, the same results I was originally getting :( Umm, how about yourfile.read(100)[or some arbitary value, just to see the data) and see what it returns... does it return something that looks like values you'd expect in a char[]... I also find it odd that the attr_val_len appears to be 4? From bj_666 at gmx.net Mon Sep 1 15:26:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2008 19:26:09 GMT Subject: Python 3.0b2 cannot map '\u12b' References: <6i24u3Fo7morU2@mid.uni-berlin.de> Message-ID: <6i2tugFo7morU3@mid.uni-berlin.de> On Mon, 01 Sep 2008 14:25:01 -0400, Terry Reedy wrote: > Marc 'BlackJack' Rintsch wrote: >> On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: >> >> Most likely because Python figured out that the terminal expects cp437. >> What does `sys.stdout.encoding` say? > > The interpreter in the command prompt window says CP437. The IDLE Window > says 'cp1252', and it handles the character fine. Given that Windows OS > can handle the character, why is Python/Command Prompt limiting output? The windows command prompt expects cp437 because that's what old DOS programs print to it. > Characters the IDLE window cannot display (like surrogate pairs) it > displays as boxes. But if I cut '[][]' (4 chars) and paste into > Firefox, I get 3 chars. '[]' where [] has some digits instead of being > empty. It is really confusing when every window on 'unicode-based' > Windows handles a different subset. That's because it is not 'unicode-based'. Communication between those programs has to be done with bytes, so the sender has to encode unicode characters in the encoding the receiver expects. > Is this the fault of Windows or of Python and IDLE (those two being > more limited that FireFox)? It's nobodies fault. That's simply how the encoding stuff works. >>> To put it another way, how can one 'choose' utf-8 for display to >>> screen? >> >> If the terminal expects cp437 then displaying utf-8 might give some >> problems. > > My screen displays whatever Windows tells the graphics card to tell the > screen to display. But the terminal gets bytes and expects them to be cp437 encoded characters and not utf-8. So you can't send whatever unicode character you want, at least not without changing the encoding of the terminal. > In OpenOffice, I can select a unicode font that displays at least > everything in the BasicMultilingualPlane (BMP). But OOo works with unicode internally, so there's no communication with outside programs involved here. Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Sat Sep 27 01:52:26 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 27 Sep 2008 05:52:26 GMT Subject: Spring Python 0.7.0 is released References: Message-ID: <74ird4hidmldkq9bao6sk5grdmpp9vq62e@4ax.com> Goldfish wrote: > >Release 0.7.0 was completed last night, and released to >sourceforge.net. > >NOTE: This release included a lot of API scrubbing, in order to bring >things more in tune with PEP-0008 (python's style guide). You're >existing apps PROBABLY were impacted, if you used any of Spring >Python's utility classes. Since we are pre-1.0, this is the best time >for such a cleanup. When 1.0 hits the streets, we won't make such a >sweeping change without extensive backwards support. > >See [url]http://springpython.webfactional.com[/url] for more >information. > >Visit our community forum at [url]http://forum.springframework.org/ >forumdisplay.php?f=45[/url] for current threads of discussion. > >--Greg Turnquist, Spring Python project lead You have committed one of the classic announcement blunders here. Your announcement gives absolutely no clue as to what Spring Python is or does. Yes, I could go to the web site to figure it out, but it's not really reasonable to expect me to do that to find out whether it might be of interest to me. A brief abstract should be part of every announcement, no matter how often you do updates. (Followup: I did go to the web site, and I STILL don't know what "Spring Python" is or does. Should I really have to Google for "spring java framework" to learn this?) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From andis59 at gmail.com Thu Sep 11 02:16:03 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Thu, 11 Sep 2008 08:16:03 +0200 Subject: I want to use a C++ library from Python References: <6ipd53FrptpiU1@mid.uni-berlin.de> <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> <6ipr40Fr7kr2U1@mid.uni-berlin.de> Message-ID: <1buzw9k4gimaf$.dlg@ostling.com> Hello all and thanks for replying, > Diez B. Roggisch wrote: >> Which actually isn't really helpful, as a DLL itself says nothing about what >> language was used to create it - and sending the OP to e.g. ctypes makes no >> sense at all in the face of C++. > > The library - or more precisely the calling convention of the library - > is related to the solution. On Windows a dll might be a container for a > .NET assembly and C++ code can (theoretically) be compiled to .NET, too. > No, the library is not an .NET assembly. It's an VC++ Library compiled as an Dll. >> Whereas the first link for "python c++" is Boost::Python, a C++-wrapper to >> make C++-code accessible from Python. > > C++ bindings can be created with SIP, SWIG, Boost or hand written code. > Multiple sites claim that SIP generates the fastest code. > I have looked (very briefly) at the three framework you mention but they all need the source code of the C++? I don't have the source code! Just the header files and the library and dll. Have I overlooked something or am I just screwed? // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! From m_palmer45 at yahoo.ca Sun Sep 14 11:06:44 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Sun, 14 Sep 2008 08:06:44 -0700 (PDT) Subject: how to exclude specific things when pickling? References: Message-ID: <7cd144b6-ca6f-447a-8448-5a334f8f999f@k37g2000hsf.googlegroups.com> On Sep 14, 10:53 am, "inhahe" wrote: > If I gather correctly pickling an object will pickle its entire hierarchy, > but what if there are certain types of objects anywhere within the hierarchy > that I don't want included in the serialization? What do I do to exclude > them? Thanks. If your class defines a __getstate__ method, it is expected to return the pickled state of the entire class. You can for example del those items from self.__dict__ that you don't want pickled and then return dumps(self). From fredrik at pythonware.com Sat Sep 20 12:46:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 18:46:35 +0200 Subject: How to make a reverse for loop in python? In-Reply-To: References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Fredrik Lundh wrote: >> e.g. the python equivalent to the c++ loop >> >> for (i = 10; i >= 0; --i) > > use range with a negative step: > > for i in range(10-1, -1, -1): > ... > > or just reverse the range: > > for i in reversed(range(10)): > ... (and to include the 10 in the range, add one to the 10 above) From afriere at yahoo.co.uk Wed Sep 24 21:32:52 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 24 Sep 2008 18:32:52 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 25, 3:16 am, Pete Forman wrote: > Asun Friere writes: > > > A canonical use of the conditional operator is in > > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). > > That fails for n == 1. So what is best? > Sorry missing parentheses. I should test before posting, even for code written into. > for i in range(4): > print '%d thing' % i + ('s' if i != 1 else '') That is the correct version of what I meant, but your last, including all variables for placeholders in the tuple is probably better. From torriem at gmail.com Tue Sep 30 19:30:38 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 30 Sep 2008 17:30:38 -0600 Subject: Time.sleep(0.0125) not available within Linux In-Reply-To: References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> Message-ID: <48E2B69E.4010505@gmail.com> Lawrence D'Oliveiro wrote: > In message <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d at posted.usinternet>, Grant > Edwards wrote: > >> On 2008-09-23, Blubaugh, David A. wrote: >> >>> I was wondering if anyone has come across the issue of not being allowed >>> to have the following within a Python script operating under Linux: >>> >>> time.sleep(0.0125) >> No, I have not. And I doubt anybody else has. > > Just a thought, your minimum sleep time is probably limited by the > resolution of the system "HZ" clock. Type > > less /proc/config.gz > > and search for the value of the "CONFIG_HZ" setting. On the Athlon 64 > machine I'm using to write this, it's 250, which should allow for sleep > intervals in multiples of 0.004 seconds. Since most distributions do not create this file in /proc for whatever reason, and some people are being deliberately obtuse, does anyone know how to ask the kernel what the timer resolution is? Is it stored anywhere else in /proc or /sys? I kind of think most distros set it to 1000 Hz, but I'm not sure. From belred at gmail.com Wed Sep 17 02:13:07 2008 From: belred at gmail.com (belred) Date: Tue, 16 Sep 2008 23:13:07 -0700 (PDT) Subject: how many objects are loaded for hello world? Message-ID: i just read this blog about how many objects (types) are loaded for a hello world program in C#. http://blogs.msdn.com/abhinaba/archive/2008/09/15/how-many-types-are-loaded-for-hello-world.aspx how can you find out how many are loaded for a python program: print 'hello' From ceball at users.sourceforge.net Fri Sep 12 08:25:05 2008 From: ceball at users.sourceforge.net (Chris) Date: Fri, 12 Sep 2008 12:25:05 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: Message-ID: Carl Banks gmail.com> writes: ... > You can determine the offset the of the slot in the object structure > by > querying the member descriptor of the type object. That sounds like just the kind of thing we were looking for - thanks! > descr = GetAttrString(cls,"varname"); > offset = descr->d_member->offset; > slotvar = (PyObject*)(((char*)obj)+offset) Unfortunately, I am inexperienced at this kind of thing, so I wasn't able to get something working. Maybe someone could tell me what's wrong with the code below (it gives the error "'struct _object' has no member named 'd_member'")? PyObject *descr = PyObject_GetAttrString(x,"attr_one"); int offset = descr->d_member->offset; PyObject* slotvar = (PyObject*)(((char*)obj)+offset); where x is the class and attr_one is a slot (the full example is appended to this message). I guessed the type of offset; I'm not sure what it should be. I couldn't find any information about d_member on the web. > There might be some macros to simplify this. Sorry to say that I also have no idea about where to find such macros! Maybe I should continue this thread on capi-sig? Thanks for your help, Chris class MyObject(object): __slots__ = ['attr_one'] def __init__(self,attr_one=1.0): self.attr_one = attr_one import weave def test(): x = MyObject code = """ PyObject *descr = PyObject_GetAttrString(x,"attr_one"); int offset = descr->d_member->offset; //PyObject* slotvar = (PyObject*)(((char*)obj)+offset); """ weave.inline(code,['x'],local_dict=locals(),verbose=1) test() From calebjhansen at gmail.com Sat Sep 13 06:12:48 2008 From: calebjhansen at gmail.com (fishfin) Date: Sat, 13 Sep 2008 03:12:48 -0700 (PDT) Subject: question about python References: <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> <91f40dcc-d76d-437a-a7e2-ea26b9e333ed@b38g2000prf.googlegroups.com> Message-ID: <113ec6fd-5f64-4b74-b5c9-c26d12b086fa@s9g2000prg.googlegroups.com> On Sep 13, 4:25?pm, Carl Banks wrote: > On Sep 13, 1:00 am, fishfin wrote: > > > @ Carl: Yes, I think your right now that I look at it (or at least all > > except for the last two lines need to be indented). I'm still not sure > > how to send the stuff to the web browser though. Thanks for pointing > > it out! > > Try reading in the whole HTTP request instead of just the first line. > Change > > line = cfile.readline().strip() > > to > > line = cfile.read() > > And see if that helps. ?(Outputting the document so that it formats > the request well is left as an exercise. ?Also, as a heads up: in real > programs you should never output anything you receive through the > network without checking it or escaping it to prevent malicious uses.) > > Carl Banks I figured out what the problem was. When you had suggested that I indent the lines at first I did all of them, but when I did that there must have been an nonindented line before the last two lines which I had indented, so ending the 'while 1:'. Because of that, that code just flat out didn't work so I assumed that they must be not be indented which is why it hasn't been working all along. Thanks for your help! I don't think I would have every figured it out if you last post hadn't gotten me to thinking about little tweeks like that. From steven at REMOVE.THIS.cybersource.com.au Tue Sep 30 06:04:18 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 10:04:18 GMT Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> Message-ID: On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: >> >> > In message , r0g wrote: >> > >> >> You can only distribute modifications to gnuplot itself as patches, >> >> but you can distribute it freely ... > [?] > >> Where's the non-free bit? > > You're not free to modify gnuplot and redistribute the result. > > That you're free to distribute patches is nice, but it's not enough to > make the work free. The freedom to help people by giving them an > *already-modified* gnuplot is restricted by the copyright holder. > > It's an artificial restriction on redistribution of derived works, > making them second-class for the prupose of getting them into people's > hands. Yes it is. It seems a strange, unnecessary restriction. But is it sufficient to make it non-free? I don't think so. In case you are thinking that gnuplot allows people to *only* distribute the diffs, not the original source to apply the diffs onto, that is not the case. I quote from gnuplot > help copyright "Permission to distribute the released version of the source code along with corresponding source modifications in the form of a patch file is granted with same provisions 2 through 4 for binary distributions." Those provisions aren't terribly onerous, although #3 may be considered a privacy issue: 2. add special version identification to distinguish your version in addition to the base release version number, 3. provide your name and address as the primary contact for the support of your modified version, and 4. retain our contact information in regard to use of the base software. >> Personally, I don't get the whole "only distribute patches" >> requirement. It's a bit like saying "You're free to distribute this >> software, but only as a tarball". It seems silly to me. > > That, too, would be a non-free requirement. > >> But I don't see it as non-free, except in the sense that "only licences >> approved by the FSF are free". > > I try to judge freedom of a software work by the freedoms granted to all > recipients of the work, not by the approval of some organisation. Yes, but you accept some restrictions as legitimate. For example, you accept the restriction that the GPL makes that says you may not redistribute a modified work without making the source code available. That's a restriction, but it's not enough to disqualify it from being a free software licence. In fact, that restriction is *necessary* to make it a free software licence in the sense we're talking about. So "free" does not mean "no restrictions", it merely means "none of some sorts of restrictions, but other restrictions are okay". Likewise the restriction that GPL software must be distributed with a copy of the appropriate licence. It is useful to compare the "diffs only" licence to two different GPL- related scenarios. Scenario one is clearly against the spirit of the GPL, and possibly (hopefully!) the letter as well. Scenario two is not. (1) I distribute the modified source code encrypted and charge $1,000,000 for a NON-TRANSFERABLE licence to the encryption key. If you don't have the encryption key, that's your bad luck. (2) I distribute the modified source code archived in a tar file, and refuse to offer it in any other format. If you don't have an untar application, that's your bad luck. It's my contention that the restriction of supplying diffs is closer to Scenario 2 than to Scenario 1. The modified source is supplied, but it is split into two pieces: the official source, plus a set of diffs. Reversing that to get the modified source is not much more difficult than untarring a tarball. -- Steven From tino at wildenhain.de Sun Sep 28 17:38:39 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 28 Sep 2008 23:38:39 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> References: <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> <48DF63B2.2020408@wildenhain.de> <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> Message-ID: <48DFF95F.3080800@wildenhain.de> Michael Mabin wrote: > Tino, dude, I'm afraid I lied about my previous post being the last > word. There are some things you said here that must be addressed. Well. Its interesting to see thats either my English is so bad you don't understand or you are too tired. All what needs to be said was said be me and others in many different words and still you are defending already lost ground. Maybe you take your time reading the thread again, carefully. Maybe not ;) Have a good night Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From rowland at river2sea.org Wed Sep 10 00:32:21 2008 From: rowland at river2sea.org (rowland at river2sea.org) Date: Tue, 9 Sep 2008 21:32:21 -0700 (PDT) Subject: Simplest solution for formatting local time in iso 8601 including time zone. Message-ID: <382d494c-b32b-454a-842b-6f559a94e025@26g2000hsk.googlegroups.com> What's the simplest solution for formatting the output of local time in iso 8601 including the time zone information? Example: "2008-07-25T14:28:43.934-04:00" Thanks, Rowland From dear.jay.logan at gmail.com Mon Sep 1 09:37:14 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 1 Sep 2008 06:37:14 -0700 (PDT) Subject: Eleganz way to get rid of \n References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: <9cdcc2b1-36f9-49f5-94c1-54529e6d2cd0@e53g2000hsa.googlegroups.com> On Sep 1, 9:25?am, Hans M?ller wrote: > Hello, > > I'm quite often using this construct: > > for l in open("file", "r"): > ? ? ? ? do something > > here, l contains the \n or \r\n on windows at the end. > I get rid of it this way: > > for l in open("file", "r"): > ? ? ? ? while l[-1] in "\r\n": > ? ? ? ? ? ? ? ? l = l[:-1] > > I find this a little bit clumsy, but it works fine. > > Has someone a better solution ? > > Thanks > > Hans Can you do this: f = open(fname) for x in f: line = x.rstrip('\r\n') From greg.ewing at canterbury.ac.nz Wed Sep 3 21:44:13 2008 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 04 Sep 2008 13:44:13 +1200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <48BF3D6D.8060906@canterbury.ac.nz> Michael Palmer wrote: > So far, development of PyGUI seems to be a one-man effort, and it may > be slowed down by the attempt to develop the API and the > implementations concurrently. Could it be useful to uncouple the two, > such that the API would be specified ahead of the implementation? I'm not sure that would work very well. I don't think it's possible to invent a good API for something as complex as a GUI toolkit in the absence of experience using it, so the API has to evolve in parallel with at least one implementation, and with real applications that actually use the features concerned. Also, the features that go into the PyGUI API are partly determined by what is available in the underlying target libraries. I don't want to end up with things in the API specification that are too difficult or unwieldy to implement on some of the target platforms. I also don't want one implementation to get too far ahead of the others, for the same reason. If anyone wants to help, what's needed most right now is a good native Windows implementation. One or two people claimed to be working on that some time ago, but I haven't heard from them recently. For the reasons I mentioned above, I'm reluctant to forge ahead with too many new features until a native Windows version exists. -- Greg From tjreedy at udel.edu Sat Sep 6 13:35:23 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Sep 2008 13:35:23 -0400 Subject: Cancel instance create In-Reply-To: References: <1220697080.48c25bf890ade@www.inbox.lv> Message-ID: Fredrik Lundh wrote: > Aigars Aigars wrote: > >> I want MyClass to perform some tests and if them fail, I do not want >> instance to be created. If you do not want the instance created at all, you would have to write a custom .__new__ method, but that is tricky, something I would have to look up how to do, and most likely not needed. Fredrik's solution below is much easier and the one I would use if at all possible. >> But in code I wrote instance is created and also has parameters, that >> it should not have in case of tests failure. >> >> Is there a way to perform tests in MyClass.__init__ and set instance >> to None without any parameters? > > if you want construction to fail, raise an exception. > > ... > > def __init__(self): At this point, you have an instance of your class bound to local name 'self'. Usually, its only individual attributes are (in 3.0, anyway, as far as I can tell) .__class__ and an empty .__dict__. Of course, it inherits class and superclass attributes, but it is otherwise blank. (The main exception would be if you were inheriting from an immutable class that set attributes in .__new__, but then you would not be writing .__init__.) > self.param = "spam" > Test = False > if Test: # please don't use explicit tests for truth > print "Creating instance..." > else: > raise ValueError("some condition failed") > > (pick an exception class that matches the actual error, or create your > own class if necessary) Once the exception gets disposed of (if not before), the blank instance gets unbound from 'self' and since it does not get bound to anything else, it becomes eligible for garbage collection. tjr From pmaupin at gmail.com Sun Sep 7 13:00:48 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 7 Sep 2008 12:00:48 -0500 Subject: __builtins__ magic behavior Message-ID: __builtins__ in 2.5.2 doesn't seem to behave like I remember it did the last time I did some custom stuff with it, a very long time ago. This isn't surprising, because of ongoing optimization, but it's hard to google for '__builtins__' so I didn't really find any documentation on the current CPython behavior, which in some cases seems quite strange to me. The documentation node at http://docs.python.org/ref/naming.html has a "here be dragons" note on __builtins__, which is nice as far as it goes, but doesn't provide any help for people wanting to abuse the current CPython implementation. Additionally, the sentence immediately above the note, "__builtins__ can be set to a user-created dictionary to create a weak form of restricted execution" not only contradicts the note, but in some cases appears not to be true. When the code below is run, either standalone or by importing it, the builtins used are different depending on whether exec is used with globals() or with a copy of globals(). Any explanations for this behavior would be much appreciated. Thanks, Pat Executing: {{{ original = __builtins__ if hasattr(original, '__dict__'): original = original.__dict__ copy = original.copy() # Make the dictionaries different and use new one copy['foo'] = 'bar' del copy['len'] del original['chr'] __builtins__ = copy testcode = ''' try: print foo except: print "foo not found" try: print len except: print "len not found" try: print chr except: print "chr not found" print ''' x = globals() assert type(x) is dict y = {} y.update(x) assert y == x print 'Executing in globals()' exec testcode in x print 'Executing in copy' exec testcode in y }}} results in: Executing in globals() foo not found chr not found Executing in copy bar len not found From sjmachin at lexicon.net Tue Sep 2 21:45:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 18:45:28 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> Message-ID: On Sep 3, 11:00 am, process wrote: > how could I do getpixel once when x and y s changing? I was not referring to *calling* im.getpixel, I was referring to looking up getpixel as an attribute of im. How? See below. > > anyway I rewrote and saw I did a lot of stupid stuff. this is fast: > def getPixels5(fileName): > im = PIL.Image.open(fileName) > colors = [] > r, c = im.size im_getpixel = im.getpixel > for y in range(0, c): > row = [] > for x in range(0, r): > color = im.getpixel((x,y)) color = im_getpixel((x, y)) > row.append(color) > colors.append(row) > return numpy.array(colors) > > but I don't need it anuyway apparently since there already was such > methods :) From george at george-net.de Tue Sep 16 07:26:59 2008 From: george at george-net.de (Georg Altmann) Date: Tue, 16 Sep 2008 13:26:59 +0200 Subject: MVC with Python In-Reply-To: <3f0d61c40809151307p76c864e5he9911593b676548e@mail.gmail.com> References: <3f0d61c40809151307p76c864e5he9911593b676548e@mail.gmail.com> Message-ID: Marco Bizzarri schrieb: > On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann wrote: >> Hello, >> >> I need some advice on how to implement model-view-controller. I am trying to >> develop a GUI application with PyQt, yet the problem rather applies to mvc >> in general, not just GUI applications. >> >> Let's say the data is a list of objects with a common base class. The views >> are either a graphical representation of the objects or some form of textual >> input. The views shall change the model by using command objects (for undo, >> e.g. QUndoCommand). >> >> My current approach is to implement the model as a class with a list-like >> interface, with methods insert(), remove(), __getitem__(), __setitem__(),... >> and a signal to notify the views. The objects in the list have methods to >> change their state as well. >> >> My problem is, how do the commands interact with the model? >> Let's say I have a command that modifies an object o in the list. >> >> 1) If list[key_to_o] returns a reference to the object, the command can >> modify the object by using this reference, i.e. list[key_to_o].setX(). So >> there is no way for the list to know when the object changed - how can it >> emit a singal then? >> >> 2) If list[key_to_o] returns a deep copy of the object, >> copy_of_o = list[key_to_o], the command mofifies the copy and the updates >> the list: list[key_to_o] = copy_of_o. Now the list can emit a signal in >> __setitem__(). >> While this may work, it seems awkward to copy around objects just to perform >> a possibly simple operation on them. Additionally it might not be feasible >> once objects get complex. >> >> 3) The interface of the classes of the objects could be reflected in the >> list class, i.e. list.set_x_on_obj(key_to_obj,x). This would probably make >> the list class interface very bloated. >> >> Of course the problem is not really limited to Python, my apologies if I'm >> totally off-topic here. >> >> Regards >> Georg >> > > Well, I think one of the assumptions of the MVC is that the view can > be notified about the changes in the model. According to your > interface, the View can just be notified on operations about the > *whole* model, like adding or removing elements from it. > > But the elements of your list-like class should be a part of your > model, and therefore should be able to notify the Views by > themselfves. Ok, consider this: say the model needs to compute some sort of value by iterating over all objects in the list (for example some sort of hash). Some kind of view then displays this value. I could implement this by connecting a signal in each object to a slot in the list class which in turn emits a signal which is connected to the view. But this implies all the objects in the list have to be instances of QObject. I wonder if this is isn't a weird design, because for example all value type classes in Qt don't derive from QObject, e.g. QString. My list objects are not that simple (in terms of the data structure). So is it ok to make them QObjects? At least this seems to be better than making a copy of the object each time it is accessed. Regards Georg From derickvn at gmail.com Tue Sep 30 03:16:23 2008 From: derickvn at gmail.com (Derick van Niekerk) Date: Tue, 30 Sep 2008 00:16:23 -0700 (PDT) Subject: I built a nice html templater! Message-ID: <72bc4cad-1496-4e40-a800-7b28942de902@a70g2000hsh.googlegroups.com> Ok - so it's not really an awesome achievement and only handles basic templating needs (no loops and other programming constructs) but maybe someone will find it useful. It replaces any xml block where the id attribute is specified with contents provided - a description is provided in the comments. http://pastebin.com/m76f57ae2 My knowledge of python is limited and I would like someone to help me with wrapping a command line interface around this function. I need switches to specify input file, output file, key/value pairs for variable substitution and key/value pairs for substituting blocks with file contents (there is some clarification in the comments) Any help would be appreciated. Of course - feel free to use the code as you wish when you wish if you wish :) -d- From rcdailey at gmail.com Thu Sep 4 18:14:37 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Sep 2008 17:14:37 -0500 Subject: Case-insensitive string compare? Message-ID: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> Hi, I currently have a dictionary object that I'm doing the following with: if lib not in stage_map: # ... do stuff ... However, this will perform a case-sensitive comparison between lib and each key in stage_map. Is there a way to make this do a case-insensitive comparison instead? Yes, I realize I could do this: if lib not in [key.lower() for key in stage_map] However, I don't want to do this because it'll quickly end up getting messy. I want this solution to be an absolute last resort. I'm not a pro with python, so I'm hoping there are cleaner alternatives out there. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From claird at lairds.us Thu Sep 4 08:02:08 2008 From: claird at lairds.us (Cameron Laird) Date: Thu, 4 Sep 2008 12:02:08 +0000 Subject: use str as variable name References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> Message-ID: <0bv4p5-00b.ln1@lairds.us> In article <48bf9d12$0$7552$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: >Mathieu Prevot a ?crit : >> 2008/9/4 Chris Rebert : > >(snip) > >>> You're looking for the setattr() built-in function. In this exact case: >>> setattr(a, arg, new_value) >>> >>> This is probably covered in the Python tutorial, please read it. >>> >>> Regards, >>> Chris >> >> Indeed. >> >> I'll use: >> a.__setattr__(height, new_value) > >Please don't. Use the generic setattr() function instead. This holds for >any __magic__ method : they are *implementation* for operators and >generic functions - which you can think of as operators with a function >syntax -, and are not meant to be called directly. You wouldn't write >something like 2.__add__(3), would you ? > Along with the good advice the usual suspects have given, my intuition is that there's an even better implementation that doesn't setattr() at all. While it's impossible to know, of course, because we don't have the original poster's true requirements, I conjecture that, rather than "to link this [user-supplied] word to a class variable", what will serve him best is to regard the user text as an index into a class dictionary. From nytrokiss at gmail.com Thu Sep 18 12:29:01 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 18 Sep 2008 09:29:01 -0700 Subject: TCP Server Message-ID: <8a6b8e350809180929j6c0eac81i9daa81a1815b5a82@mail.gmail.com> Dear List, I am looking to write a TCP socket server and was wondering what are the pros and cons of using twisted over the sockets modules bundled in python? Thanks James -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy at jeremybanks.ca Mon Sep 1 03:23:38 2008 From: jeremy at jeremybanks.ca (Jeremy Banks) Date: Mon, 1 Sep 2008 03:23:38 -0400 Subject: Inquiry regarding the name of subprocess.Popen class Message-ID: <2008090103233816807-jeremy@jeremybanksca> Hi. I wondered if anyone knew the rationale behind the naming of the Popen class in the subprocess module. Popen sounds like the a suitable name for a function that created a subprocess, but the object itself is a subprocess, not a "popen". It seems that it would be more accurate to just name the class Subprocess, can anyone explain why this is not the case? Thank you. From prologic at shortcircuit.net.au Sat Sep 20 05:29:14 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 20 Sep 2008 19:29:14 +1000 Subject: Not fully OO ? In-Reply-To: <48d4c11b$0$22877$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: This is wrong. Python _is_ a full OOP language. Everything form modules, functions to basic data types are an object. --JamesMills On Sat, Sep 20, 2008 at 7:23 PM, candide wrote: > Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > > Thanks for any comment. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 21:19:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 01:19:02 GMT Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <00e59af7$0$20331$c3e8da3@news.astraweb.com> On Sun, 21 Sep 2008 01:56:59 +0200, Christian Heimes wrote: > Just *don't* try to abuse lists by creating fancy stuff e.g. linked > lists. The memory overhead is going to kill your app. I agree with your advice not to abuse lists, but not for the reason you give. The memory overhead of a linked list implemented on top of a Python list probably isn't going to be that much greater than a dict or a class. I think the real reasons why linked lists get a bad rep in Python are: (1) they're unnecessary 99% of the time; (2) when they are necessary, a better implementation is to use classes (e.g. see traceback objects); and (3) the standard Lisp idiom for lists is horribly inefficient in CPython: alist = [1, [2, [3, [4, [5, [6, []]]]]]] But that's primarily inefficient because of the number of method calls needed to access an item. There is some memory overhead, but memory is cheap and the overhead of using objects in the first place is far larger than the overhead of a few extra pointers. -- Steven From paul at boddie.org.uk Fri Sep 12 05:34:37 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 12 Sep 2008 02:34:37 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> Message-ID: <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> On 12 Sep, 08:30, Steven D'Aprano wrote: > > Which is why I previously said that XML was not well suited for random > access. Maybe not. A consideration of other storage formats such as HDF5 might be appropriate: http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html There are, of course, HDF5 tools available for Python. > I think we're starting to be sucked into a vortex of obtuse and opaque > communication. I don't know about that. I'm managing to keep up with the discussion. > We agree that XML can store hierarchical data, and that it > has to be read and written sequentially, and that whatever the merits of > castironpi's software, his original use-case of random access to a 4GB > XML file isn't workable. Yes? Again, XML specifically might not be workable for random access in a serialised form, despite people's best efforts at processing it in various unconventional ways, but that doesn't mean that random access to a 4GB file containing hierarchical data isn't possible, so I suppose it depends on whether he is wedded to the idea of using vanilla XML or not. It's always worth exploring the available alternatives before embarking on a challenging project, unless one wants to pursue the exercise as a learning experience, and I therefore suggest investigating whether HDF5 doesn't already solve at least some of the problems or use-cases stated in this discussion. Paul From paul at boddie.org.uk Tue Sep 2 13:50:10 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 2 Sep 2008 10:50:10 -0700 (PDT) Subject: (in memory) database References: <5enqo5-9n9.ln1@lairds.us> <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> <3e419475-61a1-4579-a8b6-fc15f9fe0a9b@m73g2000hsh.googlegroups.com> Message-ID: On 2 Sep, 17:38, Zentrader wrote: > > I don't understand why Cameron has a different version of Python which > > doesn't seem to have sqlite support enabled. > > Agreed, but won't the package manager tell him if python-sqlite is > installed? It shouldn't need to be installed: the python2.5 package includes the sqlite3 module and the _sqlite extension module. He's running a more modern version of Ubuntu than I am, but I don't think that they've reintroduced the python-sqlite package in any form. > That would be the next step since it appears that SQLite > intself is already installed. Since Ubuntu uses precompied binaries, > Python should be configured for SQLite which again leaves no python- > sqlite as the only possibility (yeah right). BTW Python is easy to > install manually. Indeed, which is why I think that there must be a manually installed Python on his system, especially given that /usr/local/lib/python2.5/ sqlite3/__init__.py is one of the files mentioned in the traceback. Paul From littlesweetmelon at gmail.com Sat Sep 27 22:54:49 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Sun, 28 Sep 2008 10:54:49 +0800 Subject: design pattern: MVC in python Message-ID: Howdy, I am working on a small PC game by using pygame. Since there are many graphical objects to display and intensive user interactions, I would like to employ MVC pattern to keep the system maintainable. However, I cannot find a good article which discussing the general knowledge about MVC, especially: 1. How to decouple M-V-C? That is, which function should be assigned to which part. 2. How to communicate each other while keeping M-V-C decoupled? 3. Do I need to create Interface/Proxy class for each component? 4. What is the general principle for designing the interface of M-V-C? As my previous experience, if without special care on the principle, the MVC pattern would gradually become messy and the boundary between each component becomes unclear. Could you give me any advice? In addition, can we take the advantage of python language to make MVC easy-to-build and easy-to-use? Thank you in advance. -- ShenLei From cjw at ncf.ca Sat Sep 20 11:14:33 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 20 Sep 2008 11:14:33 -0400 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: Fredrik Lundh wrote: > Colin J. Williams wrote: > >> "foreach: for x in array: statements >> >> Loops over the array given by array. On each iteration, the value of >> the current element is assigned to x and the internal array pointer is >> advanced by one. " >> >> This could be a useful addition to Python. > > for-in could be a useful addition to Python? looks like Guido's used > his time machine again, then, since it's been around since the pre-1.0 > days: > > http://www.python.org/doc/ref/for.html > > > Thanks. for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] Colin W. From ralf at brainbot.com Thu Sep 18 06:52:51 2008 From: ralf at brainbot.com (Ralf Schmitt) Date: Thu, 18 Sep 2008 12:52:51 +0200 Subject: ANN: bbfreeze 0.96.5 Message-ID: Hi all, I uploaded bbfreeze 0.96.5 to the python package index. bbfreeze creates standalone executables from python scripts (similar to py2exe). bbfreeze works on windows and unix-like operating systems (no OS X unfortunately). bbfreeze is able to freeze multiple scripts, handle egg files and track binary dependencies. This release features a new bdist_bbfreeze command, which integrates bbfreeze into setup.py scripts (contributed by Hartmut Goebel, thanks). More information can be found at the python package index: http://pypi.python.org/pypi/bbfreeze/ Regards, - Ralf From toddw at activestate.com Wed Sep 17 14:21:20 2008 From: toddw at activestate.com (Todd Whiteman) Date: Wed, 17 Sep 2008 11:21:20 -0700 Subject: ANN: Python GUI development using XULRunner In-Reply-To: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> References: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> Message-ID: <48D14AA0.50103@activestate.com> Don Spaulding wrote: > On Sep 16, 8:29 pm, Todd Whiteman wrote: >> I've put together a tutorial that shows off how to build a GUI >> application using XULRunner (same architectural components as Firefox >> uses) that can be used in conjunction with the Python programming language. >> >> The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > I get to the "Running" step and run into "Couldn't load XPCOM." > > Does this work on x86_64? Or have I made a rookie mistake? Hi Don, A good question. Mozilla only provide 32-bit XulRunner applications by default, you you'll need to install the necessary 32-bit compatability libraries on your Linux machine, i.e. for Ubuntu it's something like: sudo apt-get install ia32-libs ia32-libs-gtk Then you should be able to run the example. You can check the dependencies using something the following commands, there should be no missing dependencies: $ cd pyxpcom_gui_app/xulrunner $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin It is possible to use a 64-bit version, but you'll need to compile this yourself (or find somewhere that provides these x86_64 versions). Note that the PythonExt project does not offer Python bindings for x86_64 either (it's on my todo list), you can compile the PythonExt part yourself as well if you need a 64-bit version. Cheers, Todd From inq1ltd at inqvista.com Mon Sep 22 14:46:29 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Mon, 22 Sep 2008 14:46:29 -0400 Subject: Problems running on hp dual core processor In-Reply-To: <200809221443.25765.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> Message-ID: <200809221446.29472.inq1ltd@inqvista.com> Python help, I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duel core processor, 2.2G with .099g ram. On the new hp, when they try to print they get an import error; File win32ui.pyc line 12, in File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. The file is there The only difference I could find from their other machines is the processor. I would appreciate any help Jim-on-linux From dudeja.rajat at gmail.com Sun Sep 28 11:47:51 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sun, 28 Sep 2008 16:47:51 +0100 Subject: Unable to write % character to a file using writelines() method Message-ID: Hi, I'm using the writelines() method to write some lines to a text file. But I'm unable to write the % character to the file using the following format: fdTolFile.writelines("\n\tdiff Not in %s '%' range" %(toleranceInPer)) The second % does not get write to the file and Im getting errors. Please suggest what additional information should I give to write the % character. The errro Im getting is : File "C:\Documents and Settings\\TA-workspace\src\TestAndCompareResults.py", line 840, in __parseDiffTextFile fdTolFile.writelines("\n\tdiff in %s'%' range" %(toleranceInPer)) TypeError: not enough arguments for format string I've also tried this: fdTolFile.writelines("\n\tdiff Not in %s \% range" %(toleranceInPer)) But still I get the same error Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From metaperl at gmail.com Thu Sep 18 16:20:58 2008 From: metaperl at gmail.com (metaperl.com) Date: Thu, 18 Sep 2008 13:20:58 -0700 (PDT) Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: On Sep 9, 12:42?pm, Fredrik Lundh wrote: > > you may also want to do re.escape on all the words, to avoid surprises > when the choices contain special characters. yes, thank you very much: import re def oneOf(s): alts = sorted(s.split(), reverse=True) alts = [re.escape(s) for s in alts] return "|".join(alts) From asmodai at in-nomine.org Tue Sep 9 04:00:26 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 9 Sep 2008 10:00:26 +0200 Subject: universal unicode font for reportlab In-Reply-To: References: <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> Message-ID: <20080909080026.GF30869@nexus.in-nomine.org> -On [20080909 05:23], Terry Reedy (tjreedy at udel.edu) wrote: >Ariel Unicode MS is the one that seems pretty complete. Not really. It misses a lot of characters. Might I recommend using BabelMap (http://www.babelstone.co.uk/Software/BabelMap.html) so you can investigate your fonts? The only font I am aware of that supports a lot of Unicode fonts is James Kass' Code 200x fonts (http://www.code2000.net/). In almost all cases you will need to gather a collection of fonts in order to typeset your documents as it is hard to find font designers who know enough about all languages to properly design the fonts. Not to mention such fonts would quickly grow unwieldy. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B A kiss is a lovely trick designed by nature to stop speech when words become superfluous... From rocky at panix.com Fri Sep 5 17:03:46 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 05 Sep 2008 17:03:46 -0400 Subject: pdb bug and questions References: Message-ID: Stef Mientki writes: > From: Stef Mientki > Subject: Re: pdb bug and questions > Newsgroups: comp.lang.python > To: "python-list at python.org" > Date: Fri, 05 Sep 2008 22:06:19 +0200 > > R. Bernstein wrote: >> Stef Mientki writes: >> >> >>> hello, >>> >>> I'm trying to embed a debugger into an editor. >>> I'm only interested in high level debugging. >>> The first question is what debugger is the best for my purpose ? >>> (pdb, pydb, rpdb2, smart debugger, extended debugger ? >>> >>> Second question, in none of the above debuggers (except rpdb2), >>> I can find a "break now", >>> so it seems impossible to me to detect unlimited while loops ? >>> >> >> I am not sure what you mean by "break now". pdb and pydb allow direct >> calls from a program to the debugger via set_trace (which in pydb is >> deprecated in favor of I think the more descriptive name: debugger) >> But I suspect this is not what you mean to "detect unlimited while >> loops"; pydb also has gdb-style signal handling that allows for entry >> into the debugger when the debugged python process receives a >> particular signal. "info handle" lists all of the interrupts and what >> action is to be taken on each. See >> http://bashdb.sourceforge.net/pydb/pydb/lib/node38.html >> >> However I believe that signals are only handled by the main thread; so >> if that's blocked, the python process won't see the signal. >> > Thanks, > Yes, I think the trace option can do the job, > certainly if I display every line. > Didn't know pdb had something like settrace ( the information on pdb > is very condensed ;-) It sounds to me like there may be some confusion -- if at least on my part. pdb's set_trace (with the underscore) is documented here: http://docs.python.org/lib/module-pdb.html . Yes, perhaps it would be nice if that document gave an example. But set_trace is a method call, not an option. There is a pydb debugger *command* called "set trace" as well as a command-line option (-X --trace) which turns on line tracing and is something totally different. It can be fun to use that with "set linetrace delay" in an editor to allow one to watch the lines execute as the program runs. I did this with emacs in this video: http://showmedo.com/videos/video?name=pythonBernsteinPydbIntro&fromSeriesID=28 >> >>> For the moment I started with pdb, because most of the debuggers seems >>> to be an extension on pdb. >>> When I launch the debugger ( winXP, Python 2.5) from with my editor >>> python -u -m pdb D:\\Data\\test_IDE.py >>> I get this error >>> IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') >>> NOTICE 1 backslash ----------------------------------^ >>> >>> If I launch the debugger with >>> python -u -m pdb D:/Data/test_IDE.py >>> It runs fine. >>> >>> This looks like a bug to me. >>> What's the best way to report these kind of bugs ? >>> >> >> winpdb, pydb and pdb (part of Python) all have Sourceforge projects >> which have bug trackers. For pdb, in the past people includng myself, >> have reported features, patches and bugs in the Python tracker; >> eventually it gets handled. (Eventually in my case means a year or >> so.) But if my information is incorrect or out of date, no doubt >> someone will correct me. >> > I'll take a look, for the sake of our children ;-) >> As mentioned in the last paragraph, pydb also is a Sourceforge project >> (part of bashdb) which has a tracker for bug reporting. Using the bug >> tracker I think is better than discussing pydb bugs in c.l.p. > c.l.p. ? This newsgroup, comp.lang.python. >> By >> extension, I assume the same is also true for the other debuggers. >> >> Finally, I think rpdb2 is part of the winpdb project on Sourceforge >> and again has a bug tracker. My sense is that Nir Aides is very good >> about handling bugs reported in winpdb/rpdb. >> > Yes I started with rpdb2, > and indeed Nir Aides is very helpfull, > but I think interfaceing rpdb2 is a little too difficult for me, > > For now I think pydb is the choice, > better control and more functions than pdb, > and almost just as easy. If there are things that are unnecessarily awkward, and especially if you can think of a way to make pydb better (that hasn't been suggested before), please submit a feature request in the tracker for pydb. Thanks. From george.sakkis at gmail.com Mon Sep 29 11:54:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 29 Sep 2008 08:54:58 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> <45c74b74-214c-4fed-b691-6020a1aedce6@a1g2000hsb.googlegroups.com> Message-ID: <16f8d6ab-1284-4099-9326-fb367d454b50@59g2000hsb.googlegroups.com> On Sep 29, 11:37 am, bearophileH... at lycos.com wrote: > George Sakkis: > > > No difference in principle, just len() happens to be implemented more > > often than upper(). > > That's an important point. In a language that tries to be both > practical, readable, and elegant, the things that are done more may > deserve some sugar, to avoid code like this in many cases: > > sorted(seq, key=lambda x:x.__len__()) If this was the most compelling use case of having len as builtin, I would be even less convinced. How often do you sort by len? FWIW, the most common sorting keys I see in real world are attrgetter(some_attr) or itemgetter(some_index) and both are imported functions, not builtins. George From samuel.morhaim at gmail.com Tue Sep 23 12:03:57 2008 From: samuel.morhaim at gmail.com (Samuel Morhaim) Date: Tue, 23 Sep 2008 12:03:57 -0400 Subject: SPE restore defaults Message-ID: <65c3648d0809230903t558782b8wdaef9d7c278bc617@mail.gmail.com> Hi, I am sorry if this is a bit off topic... I downloaded SPE, but i changed the config option by mistake to a Skin only for Mac... so everytime i start SPE it crashes. I tried uninstalling, but it didnt work, it seems the value is in the registry, but i couldnt find it. Can anyone help? (Spe forum is not useful.. thanks) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rocksportrocker at googlemail.com Thu Sep 11 07:11:49 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 11 Sep 2008 04:11:49 -0700 (PDT) Subject: Use Python to solve equations? References: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Message-ID: On 11 Sep., 09:09, Kelie wrote: > Hello group, > > Is there any packages in Python that will help me solve functions > similar to this: > > x = a*(1+bx)**2.5-c where a, b, c is known and the task to solve x? > > Thank you, > > Kelie look at www.sagemath.com . it is great. greetings, uwe From larudwer at freenet.de Thu Sep 4 16:45:15 2008 From: larudwer at freenet.de (Ruediger) Date: Thu, 04 Sep 2008 22:45:15 +0200 Subject: why is self not passed to id()? < solved > References: Message-ID: castironpi wrote: > > The answer is fairly technical. For member functions to be bound to > instances, they are required to have a __get__ method (which takes > instance and owner as parameters). 'id' does not. > > (Why does 'id' not have a __get__ method?) > > By contrast, > >>>> set.add > >>>> dir(_) > ['__call__', '__class__', '__delattr__', '__doc__', '__get__', > '__getattribute__ > ', '__hash__', '__init__', '__name__', '__new__', '__objclass__', > '__reduce__', > '__reduce_ex__', '__repr__', '__setattr__', '__str__'] > > 'set.add' does. Thank you for the quick response. However it gives me less hope that the little performance hack I had in mind will ever work. From apardon at forel.vub.ac.be Fri Sep 19 10:01:06 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Sep 2008 14:01:06 GMT Subject: cups.Connection.printFile References: Message-ID: On 2008-09-16, Graham Jenkins wrote: > > I'm trying to print a file from within a Python program. > > The quick-and-dirty solution is to use something like: > > fd = os.popen("lp -d MyPrinter", "wb") > fd.write(MyFileContents) > > But it seems to me that there should be a clean solution like: > > import cups > stat = > cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") What about systems that don't use cups for printing? -- Antoon Pardon From bignose+hates-spam at benfinney.id.au Mon Sep 1 23:51:16 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 02 Sep 2008 13:51:16 +1000 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> Message-ID: <878wubp5mz.fsf@benfinney.id.au> bearophileHUGS at lycos.com writes: > Ben Finney: > > I don't see any good reason (other than your familiarity with the > > D language) to use underscores for this purpose, and much more > > reason (readability, consistency, fewer arbitrary differences in > > syntax, perhaps simpler implementation) to use whitespace just as > > with string literals. > > It's not just my familiarity, Ada language too uses underscore for > that purpose, I think, so there's a precedent, and Ada is a language > designed to always minimize programming errors, simple code mistakes > too. I would argue that the precedent, already within Python, for using a space to separate pieces of a string literal, is more important than precedents from other programming languages. > Consider: > > a = 125 125 125 > > a = 125, 125, 125 > > a = 125_125_125 > > For me the gestalt of the first line looks too much like the second > one, that is three separated things This is no more the case than for literal strings: a = "spam" "eggs" "ham" a = "spam", "eggs", "ham" Yet this is already a valid way in Python to specify, respectively, a single literal string and a literal tuple of strings. > While in the third case the _ helps glue the parts, creating a > single gestalt to my eyes. To my eyes, it's needlessly hard to read, and looks too similar to an identifier, not a literal. On the other hand, the spaces version is easy to see as analogous to the same syntax rules that already exist for strings. > Note that it's not just a matter of font and familiarity, it's also a > matter of brains. Your brain may be different from mine, so it may be > possible that what's better for you isn't better for me. So in such > situation a popular voting may be the only way to choose. But for me > having spaces to split number literals in parts is _worse_ than not > having any way at all to split them. So I'm strong opposed to your > suggestion, so I may not even propose the PEP if lot of people agrees > with your tastes. Thanks for making your position clear. -- \ ?The WWW is exciting because Microsoft doesn't own it, and | `\ therefore, there's a tremendous amount of innovation | _o__) happening.? ?Steve Jobs | Ben Finney From brenNOSPAMbarn at NObrenSPAMbarn.net Wed Sep 3 17:09:02 2008 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Wed, 03 Sep 2008 21:09:02 GMT Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: Michael Palmer wrote: > As anyone knows, the state of Python GUI programming is a little > fractured at this time, with many toolkits, wrappers and meta-wrappers > dead and alive, with or without documentation. How about Dabo? http://www.dabodev.com/ -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From moogyd at yahoo.co.uk Mon Sep 15 02:58:53 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sun, 14 Sep 2008 23:58:53 -0700 (PDT) Subject: noob: subprocess clarification References: <68fcdea2-804e-4fba-958e-47ecee277faf@s50g2000hsb.googlegroups.com> Message-ID: <170924a4-f17f-44d7-9772-c3044d547fca@s50g2000hsb.googlegroups.com> On 14 Sep, 22:06, Dennis Lee Bieber wrote: > On Sun, 14 Sep 2008 02:29:52 -0700 (PDT), moo... at yahoo.co.uk declaimed > the following in comp.lang.python: > > > Can somebody please clarify what the shell=True does, and whether I am > > using it correctly. > > What part of: > > """ > On Unix, with shell=False (default): In this case, the Popen class uses > os.execvp() to execute the child program. args should normally be a > sequence. A string will be treated as a sequence with the string as the > only item (the program to execute). > > On Unix, with shell=True: If args is a string, it specifies the command > string to execute through the shell. If args is a sequence, the first > item specifies the command string, and any additional items will be > treated as additional shell arguments. > """ > > is giving problems? I assume that this is sarchasm :-) > > For the most part, as I recall, "shell=True" allows you to invoke > commands that are built-in/native to the default shell, or even a shell > script. False requires the specified command to be a stand-alone > executable program. > -- From gagsl-py2 at yahoo.com.ar Fri Sep 19 11:56:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 12:56:24 -0300 Subject: Multimapping and string converting References: <26c69b160809190659i54dbfae1xd5794cd2ff433a1c@mail.gmail.com> Message-ID: En Fri, 19 Sep 2008 10:59:26 -0300, Ron Brennan escribi?: > Hello, > > I have a multimap dictionary with a 1 Key to N values. I want to convert > the N values to a string to be used elsewhere in my program. > > So I have dict[(1,[1, 2 ,3 ,4])] which I have sorted > > When I do a print ''.join(str(dict.value())) I get [1, 2, 3, 4] as an > output > when I really want 1 2 3 4 > > Here is my code: > > dmapItems = dictionary.items() > dmapItems.sort() > > for tcKey, tcValue in dmapItems: > file.write('Key = %s\nValue = %s" % (tcKey, tcValue) > > stinger = ''.join(str(tcValue)) > > print stringer > > The Output = [145, 2345, 567, 898] > I need it to be 145 2345 567 898 I guess you probably tried using ' '.join(value) and got an error like this: TypeError: sequence item 0: expected string, int found so you inserted that str(...), but you don't still get what you want. You want "145 2345 567 898". *If* you had a list like this: value = ["145", "2345", "567", "898"] (that is, a list of strings) *then* ' '.join(value) would do what you want. But you have this to start with instead: value = [145, 2345, 567, 898] (a list of numbers), how to convert it into a list of strings? str(value) returns a single string that "looks like" a list but isn't: "[145, 2345, 567, 898]". Instead, you need to convert each element individually, and keep them in a list. Try this: value = [str(elem) for elem in value] Also, I'd use sorted() to iterate over all items. PUtting all together: for tcKey, tcValue in sorted(dictionary.items()): values = [str(elem) for elem in tcValue] values = ' '.join(values) print tcKey, values or perhaps: for tcKey, tcValue in sorted(find_a_good_name_for_me.iteritems()): values_str = ' '.join(str(elem) for elem in tcValue) print tcKey, values_str (using lazy objects (iteritems and a generator expression) instead of concrete lists) -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 09:40:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 13:40:02 GMT Subject: doctest not seeing any of my doc tests Message-ID: <00d3d407$0$20306$c3e8da3@news.astraweb.com> I have a function in my module: def selftest(verbose=False): import doctest doctest.testmod(verbose=verbose) When I run it, it fails to find any of my doc tests, including the tests in __main__, and in fact it looks like it can't even find my functions and classes: >>> mymodule.selftest(True) 1 items had no tests: __main__ 0 tests in 1 items. 0 passed and 0 failed. Test passed. The second and subsequent times I call selftest, I get the same result except that it adds this line to the end: *** DocTestRunner.merge: '__main__' in both testers; summing outcomes. I've exited from Python and restarted the interactive interpreter. I've deleted the module .pyc file. Neither has helped. I've tried reading over the doctest module to see if there are any hints as to what's going wrong, but it's quite opaque to me. If there's anyone out there with a good understanding of doctest, I'd appreciate some pointers for where to start looking, or otherwise how to fix this problem. For what it's worth, I'm running Python 2.5 (r25:51908, Apr 10 2007, 10:29:13) [GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] on linux2 -- Steven From FettManChu at gmail.com Thu Sep 4 15:50:25 2008 From: FettManChu at gmail.com (Fett) Date: Thu, 4 Sep 2008 12:50:25 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: Message-ID: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> On Sep 4, 2:23?pm, Mike Driscoll wrote: > On Sep 4, 1:39?pm, Fett wrote: > > > > > I need a crypto package that works on windows with python 2.5. Can > > anyone suggest one for me? > > > I have been searching for a couple days for a good cryptography > > package to use for public/private key encryption, at this point I > > would settle for symmetric even. > > > Every encryption package I have found for python was either operating > > system specific (read *nix only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/ > > > There was one exception, this version was specifically built to run on > > any platform (yay), but the compiler for windows complained that I > > wasn't using python2.2 (though the package was said to only need 2.2 > > or newer). > > > Is there any crypto package that is actually written in python? I > > seriously don't care how slow it is. > > How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads > > Mike Seems that this is intended more for webapps or something, I intend to use this for a client application. This means that I can't require outside dependencies, or I risk annoying the clients (if you have installed many open-source projects with dependencies that aren't handled by portage/apt-get, you know what I would be doing to them). I seriously can't believe that there isn't a single python native crypto package. Why do they all need to have outside dependencies? From marco.bizzarri at gmail.com Thu Sep 4 10:40:14 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 16:40:14 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <3f0d61c40809040739t4ea080b1nc2683f43b1558b6@mail.gmail.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <6i9uidFphkg0U1@mid.uni-berlin.de> <3f0d61c40809040739t4ea080b1nc2683f43b1558b6@mail.gmail.com> Message-ID: <3f0d61c40809040740u66ac4f90l858d86647495040d@mail.gmail.com> On Thu, Sep 4, 2008 at 4:39 PM, Marco Bizzarri wrote: > > Most probably you're right. Maybe I will make a trip back to my > university books and take a look at them again :-) > Meant: you *are* right. Sorry. Saluti Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From castironpi at gmail.com Sat Sep 20 22:33:17 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 19:33:17 -0700 (PDT) Subject: writeable buffer and struct.pack_into and struct.unpck_from References: Message-ID: <866704af-aa81-4688-9ece-2a8f336c5fc7@m44g2000hsc.googlegroups.com> On Sep 20, 6:42?pm, "Gabriel Genellina" wrote: > En Sat, 20 Sep 2008 15:45:48 -0300, Tzury Bar Yochay ? > escribi?: > > > I can't find in the documentation the way to use these two functions. > > > can someone share a simple code that utilize these two functions? > > struct.pack_into is intended to "fill" a buffer you got from somewhere, ? > probably other language or process. ctypes.create_string_buffer may be ? > used to create a writable buffer in python code. > > py> from ctypes import create_string_buffer > py> b = create_string_buffer(10) > py> b.raw > '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' > py> from struct import * > py> pack_into("hhh", b, 0, 1, 2, -1) > py> b.raw > '\x01\x00\x02\x00\xff\xff\x00\x00\x00\x00' > > unpack_from does the opposite. > Before Python 2.5, That was when Python broke string immutability with the ctypes module. > you had to use pack to create a string object, and then ? > copy its contents into the destination buffer; using pack_into avoids the ? > memory copy. > > -- > Gabriel Genellina 'mmap' seems to have always offered random-access writes. A search through the implementation for "tp_as_buffer" returns a lot of zeros however. From grante at visi.com Sun Sep 14 22:10:14 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 21:10:14 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: On 2008-09-15, Ben Finney wrote: > Grant Edwards writes: >> On 2008-09-14, Ben Finney wrote: >> >>> Second: please do yourself a favour and drop the >>> camelCaseNames. Follow PEP 8 >>> for style and >>> naming in your Python code. >> >> If he finds camelcase more readable and easier to type (as do >> I), how is switching to underscores "doing himself a favor"? >> >> I'm generally in favor of using a consistent naming style >> throughout a project, but I don't see why the naming style >> used in my source code should be subject to somebody else's >> arbitrary standard. > > Because the code we write rarely stays isolated from other > code. There is an existing convention, There are many existing conventions. > and it's better to pick a (sufficiently sane) style convention > and stick to it than argue about what the convention should > be. I suppose if everybody agreed to pick one, and all the source code in the world was changed to meet it, that would "a good thing". It just seems like a goal so unrealistic as to make it a bit of an overstatement to tell people they're better off following convention X than following convention Y. When packages as significant as wxPython use naming conventions other than PEP 8, I find it hard to make a case that the PEP 8 naming convention is any better than any other. >> When it comes to writing code intended for the standard >> library in the main Python distribution, I would certainly >> defer to the existing standard as defined in PEP 8. However, >> I don't see any reason that style should be imposed on all >> everybody else. > > Who's imposing? I'm saying it's a good idea for everyone to do > it, and going so far as to say that one is doing oneself a > favour by following the convention. I have no more power than > you to "impose" convention on anyone. My apologies -- "impose" was too strong a word to use. If we were starting from scratch and there was no extant source code in the world, then it would make sense to encourage everybody to pick one convention. [I still think it would be rather quixotic.] But, there are so many projects out there with naming conventions other than PEP 8, that I don't see how there's an advantage to picking one over another (except for the obvious also-rans like "all upper case, no vowels, and a maximum length of 6 characters"). I'll agree that sticking with a single convention within a project is definitely a good thing. I'm personally aware of mixed/camel-case projects from 25+ years ago, so I'm afraid PEP 8 came along a bit too late... -- Grant From hniksic at xemacs.org Sat Sep 13 16:27:09 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 13 Sep 2008 22:27:09 +0200 Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> Message-ID: <87fxo3bxlu.fsf@mulj.homelinux.net> Terry Reedy writes: >> Of course, sum() is even faster than reduce: >> >>>>> Timer('sum(xrange(10000))').repeat(number=10000) >> [9.814924955368042, 8.7169640064239502, 9.5062401294708252] > > 'Of course', because the irreducible difference between > reduce(add.seq) and sum(seq) is that reduce has to call an add > function while sum has the operation built-in in place of a call. Note that, despite appearances, it's not as built-in as one might wish. sum(seq) is still completely generic and works on all number-like objects (in fact on all objects that define an __add__ operation except strings, which are explicitly forbidden). This means that it can't just go ahead and execute a C addition, it must properly call PyNumber_Add (the C API call equivalent to Python's "+" operator), which will then inspect the objects and invoke the appropriate implementation of addition. On the other hand, operator.add is defined to do exactly that -- call PyNumber_Add on its arguments and return the result. It's not entirely obvious why summing numbers using the same method, repeatedly calling PyNumber_Add, would be significantly slower for reduce than for sum. Admittedly reduce has to execute a Python-level function call which requires allocating and filling out a tuple, only to reach PyNumber_Add, which sum calls immediately. But builtin_reduce() is actually careful to optimize those repeated function calls, for example by reusing the same tuple across the loop. From peter.anderson at internode.on.net Sat Sep 6 03:50:16 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sat, 06 Sep 2008 17:50:16 +1000 Subject: wxPython problem Message-ID: <48C23638.1000109@internode.on.net> I am trying to teach myself how to program in Python and use wxPython for GUIs. I am using PyScripter, IDLE and EditPlus as my IDEs. I have experienced an odd problem where I run a script once and it runs fine. Run it again and I get an error and the script fails. If the script is run directly from Python ('Run' from Windows Explorer) or from EditPlus (in which I have a "user-defined tool" which calls C:\Python25\pythonw.exe with the parameter of $(FileName)) then there is *never* any error, no matter how many times the script is run. Close down PyScripter or IDLE and then start either up again, load the script and run it - it runs fine. Run it again and it fails. It seems like something is already set in memory and cant be re-set (my lack of knowledge is showing here :-( ). More details are shown below. Any help or hints would be greatly appreciated. Regards, Peter RUNNING SIMPLE.PY (AND OTHER SCRIPTS USING WXPYTHON) FROM PYSCRIPTER I GET THE FOLLOWING ERROR MESSAGE: PyNoAppError: The wx.App object must be created first! PyScripter loads a module (I presume from wxPython) called _windows.py and highlights a particular line in red and displays the error message from above. I have Googled the error message but the results have not helped. LISTING FOR SIMPLE.PY #!/usr/bin/python # simple.py import wx app = wx.App() frame = wx.Frame(None, -1, 'simple.py') frame.Show() app.MainLoop() EXERPT FROM _WINDOWS.PY - PYSCRIPTER HIGHLIGHTS SECOND LAST LINE class Frame(TopLevelWindow): """Proxy of C++ Frame class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String title=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) -> Frame """ # The following line is highlighted as where the error occures _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) self._setOORInfo(self) RUNNING THE SIMPLE.PY SCRIPT FROM WITHIN IDLE PRODUCES THE FOLLOWING ERROE MESSAGE: Traceback (most recent call last): File "C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython Tutorial\absolute.py", line 28, in Absolute(None, -1, '') File "C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython Tutorial\absolute.py", line 9, in __init__ wx.Frame.__init__(self, parent, id, title, size=(250, 180)) File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 505, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) PyNoAppError: The wx.App object must be created first! -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From zhushenli at gmail.com Tue Sep 2 23:20:17 2008 From: zhushenli at gmail.com (Davy) Date: Tue, 2 Sep 2008 20:20:17 -0700 (PDT) Subject: Pass same parameter in Recursive function Message-ID: Hi all, Sometimes I need to pass same parameter in recursive function. From my point of view, the style is redundant, and I don't what to use some global style like self.A, self.B, Is there any other choice? For example, def func(self, x, y, A, B, C): #x, y change in recursive call #A, B, C change in the first layer function call, but did not change in recursive call if (...): func(x, y, A, B, C) else(...): func(x, y, A, B, C) Best regards, Davy From inhahe at gmail.com Sun Sep 14 10:53:59 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 14 Sep 2008 10:53:59 -0400 Subject: how to exclude specific things when pickling? Message-ID: If I gather correctly pickling an object will pickle its entire hierarchy, but what if there are certain types of objects anywhere within the hierarchy that I don't want included in the serialization? What do I do to exclude them? Thanks. From kurdayon at yahoo.com Sun Sep 28 18:39:22 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Sun, 28 Sep 2008 15:39:22 -0700 (PDT) Subject: Web programming in Python. Message-ID: Hi, I am totaly newbie in the Python's web programming. So, I dont even know the basic conceptions (but I have ideas about php-web- programming). Does it work in a similar way? First, I have to install a Python-server? On the server where I have my web site (it runs under Linux) if I type "python" I get the Python command line. Does it mean that I already have everything what I need to start web programming in Python. Should I give *.py extension to the Python programs? I tried the simplest what could I imagine. And it does not work. I have created a file "test.py" which contains print "Hello, World!" If I type "python test.py" it works! But, if I put in the address line of my browser "www.mydomainname.org/test.py" it does not work. Or, to be more precisely, in my browser I see the content of the "test.py" (not the result of the execution). Could you pleas help me to start? Thank you ! From steve at holdenweb.com Mon Sep 29 09:39:19 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 09:39:19 -0400 Subject: Web programming in Python. In-Reply-To: References: Message-ID: Kurda Yon wrote: > 1. On my server (in my directory) I found "cgi-bin" subdirectory. > > 2. In the "cgi-bin" I have created a file "test.py". > > 3. In that file I put: > #!/usr/bin/python2.4 python OK, if /usr/bin/python2.4 really *is* a directory then you will need to make that first line #!/usr/bin/python2.4/python (The phrase folowing the "#!" should be a reference to your Python interpreter). > print "Hello, World!" Also, this isn't going to be adequate as an HTTP response, which a CGI script is always supposed to provide. A minimal example would have a single header followed by a blank like (which marks the end of the headers) and your content, like this: print """Content-Type: text/plain Hello, World! """ > (I have checked, I have "/usr/bin/python2.4" directory.) > > 4. I give the following permissions to the "test.py": > -rwx---r-x > > 5. The "cgi-bin" directory has the following permissions: > drwx---r-x > > 6. In the "cgi-bin" I have created the ".htaccess" file which > contains: > Options +ExecCGI > AddHandler cgi-script .py > > > And it still does not work! If I try to see the page by my browser I > see: > Internal Server Error > The server encountered an internal error or misconfiguration and was > unable to complete your request. > ... > -- > http://mail.python.org/mailman/listinfo/python-list > If that doesn't get your script working then you should look at the error logs. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jason.scheirer at gmail.com Thu Sep 4 11:57:13 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 4 Sep 2008 08:57:13 -0700 (PDT) Subject: path slashes cleaning References: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> Message-ID: On Sep 4, 6:32?am, "Francesco Guerrieri" wrote: > On Thu, Sep 4, 2008 at 3:25 PM, Mathieu Prevot wrote: > > Hi, > > > for scripts that take arguments, I would like to remove the trailing > > slash if it's present. > > > Is there something else than: > > > a='/usr/local/lib/' > > if a[-1] == '/': > > ?a = list(a) > > ?a.pop() > > ?''.join(a) > > > Thanks, > > Mathieu > > a.rstrip('/') does the job. > > bye, > Francesco [1]: import os.path [2]: os.path.normpath('/usr/bin') '/usr/bin' [3]: os.path.normpath('/usr/bin/') '/usr/bin' And on windows: [1]: import os.path [2]: os.path.normpath(r'c:\data') 'c:\\data' [3]: os.path.normpath('c:\\data\\') 'c:\\data' Use the functions provided in os.path. From fredrik at pythonware.com Thu Sep 11 04:34:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 10:34:07 +0200 Subject: dynamic allocation file buffer In-Reply-To: References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I'm no longer *claiming* anything, I'm *asking* whether random access to > a 4GB XML file is something that is credible or useful. It is my > understanding that XML is particularly ill-suited to random access once > the amount of data is too large to fit in RAM. An XML file doesn't contain any indexing information, so random access to a large XML file is very inefficient. You can build (or precompute) index information and store in a separate file, of course, but that's hardly something that's useful in the general case. And as I said before, the only use case for *huge* XML files I've ever seen used in practice is to store large streams of record-style data; data that's intended to be consumed by sequential processes (and you can do a lot with sequential processing these days; for those interested in this, digging up a few review papers on "data stream processing" might be a good way to waste some time). Document-style XML usually fits into memory on modern machines; structures larger than that are usually split into different parts (e.g. using XInclude) and stored in a container file. Random *modifications* to an arbitrary XML file cannot be done, as long as you store the file in a standard file system. And if you invent your own format, it's no longer an XML file. From fredrik at pythonware.com Sat Sep 6 12:51:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Sep 2008 18:51:38 +0200 Subject: Calling global functions from a class? In-Reply-To: <496954360809060933w2b736b57x7925510140e7a3e@mail.gmail.com> References: <496954360809060933w2b736b57x7925510140e7a3e@mail.gmail.com> Message-ID: Robert Dailey wrote: > I have the following python script: > > def __normalizePath( path ): > return osp.abspath( osp.normpath( path ) ) > > class AbsolutePath: > def __init__( self, root="" ): > _root = __normalizePath( root ) > > > When I create an AbsolutePath object, I get the following error: > > NameError: global name '_AbsolutePath__normalizePath' is not defined > > Is there a reason for this? the "__" prefix (double underscores) is reserved for private attributes and methods in a class. it does not work for module-level names. > How can I make this work? rename the global function. From castironpi at gmail.com Sun Sep 28 15:27:12 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 12:27:12 -0700 (PDT) Subject: Music knowledge representation References: Message-ID: <4ea817db-7d6f-432b-949b-8b03e3e61da6@8g2000hse.googlegroups.com> On Sep 28, 2:08?pm, Mr.SpOOn wrote: > On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady > > wrote: > > Here is a link to someone else's design they asked about on the > > newsgroup a couple weeks ago. > > >http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > :D > It's always me. > > I think my question is more specific. I need some sort of cycle. > > So if I have a list with A, B, C, D, when I iter over it I need to get > an A after the D. This one was an easy guess: cycle( iterable) Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. From ken at seehart.com Tue Sep 30 07:51:36 2008 From: ken at seehart.com (Ken Seehart) Date: Tue, 30 Sep 2008 04:51:36 -0700 Subject: Advice for a replacement for plone. Message-ID: <48E212C8.6070209@seehart.com> I want a new python based CMS. ... One that won't keep me up all night .... I've been fooling around with zope and plone, and I like plone for some things, such as a repository for online project documentation. However for general-purpose web development it is too monolithic. Is there anything out there with the following properties? 0. Web page being developed is a typical small business home page (i.e. not a newspaper or a blog). 1. Page owner can edit pages on line with no expertise (plone does great here). 2. Main page does not look plone-like. For an example of a main page that does not look plone-like, see http://www.arbitrary.com/ Note the lack of CMS style navigation widgets. 3. Item 2 should be reachable with nearly no effort (plone fails utterly here). 4. Target viewer (not the owner), should /not/ see something that looks at all like a CMS system, but rather see exactly what the page owner wants the page to look like. 5. Page owner should be able to view and navigate the tree of contents, and select pages to edit with a wysiwyg editor (plone does great here)... 6. ... But the target viewer should not see this tree. See items 2 and 4. 7. Potential to add python scripted pages of various kinds. There are a couple different design approaches to making a development environment. You can let the developer start with nothing, and provide the developer with tools to create something (e.g. zope, most plain text editors), or you can start with a finished result and let the developer rip out and discard what is not desired (e.g. plone). I often prefer to start with nothing. It's a natural starting point. Note that systems that are based on starting with nothing can provide the benefits of starting with something by providing templates and such. I would love to see a system that would give me an editable Hello World page in under 5 minutes. Hello World would be a page consisting of nothing but the words "hello world" (no tools, no navigation bar, and certainly no CMS navigation stuff) in a url such as www.myhelloworldwebsite.com/hello and a different url to edit the page, such as www.myhelloworldwebsite.com/hello/edit or www.mywebsite.com/edit/hello If you are a plone fanatic and still think I should use plone, fine, but please let me know where I can find a "Hello World" kind of example that demonstrates items 2, 4, and 6. In addition, I would like the ability to design the layout of the page independent of the content. Plone has some nice features that would be very helpful, but again, getting to hello world seems difficult. Just plain Zope does a pretty good job at some of this, but I haven't found a good online wysiwyg editor for the page owner to modify content. Thanks for any ideas. Ken From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 04:11:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 10:11:58 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <48d7534f$0$5096$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? > Err... A possible design smell ?-) More seriously: this looks quite like a singleton, which in Python is usually implemented way more simply using a module and plain functions. Do you have a use case for specializing this class ? From bedouglas at earthlink.net Sat Sep 6 19:27:03 2008 From: bedouglas at earthlink.net (bruce) Date: Sat, 6 Sep 2008 16:27:03 -0700 Subject: Use BeautifulSoup to delete certain tag while keeping its content In-Reply-To: <37b964200809060811j55e81c6bqdce6747c9982b82d@mail.gmail.com> Message-ID: <20f601c91078$13d70b70$0301a8c0@tmesa.com> hi jackie, if you don't mind... can i ask what you're looking to accomplish? are you looking to simply get the text/string data, or something else??? -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Jackie Wang Sent: Saturday, September 06, 2008 8:12 AM To: python-list at python.org Subject: Use BeautifulSoup to delete certain tag while keeping its content Dear all, I have the following html code: Center Bank
Los Angeles, CA
Salisbury Bank and Trust Company
Lakeville, CT
How should I delete the 'font' tags while keeping the content inside? Ideally I want to get: Center Bank
Los Angeles, CA Salisbury Bank and Trust Company
Lakeville, CT Thank you. Jackie -- http://mail.python.org/mailman/listinfo/python-list From castironpi at gmail.com Fri Sep 12 08:39:11 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 12 Sep 2008 05:39:11 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> Message-ID: <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> On Sep 12, 4:34?am, Paul Boddie wrote: > On 12 Sep, 08:30, Steven D'Aprano > > wrote: > > > Which is why I previously said that XML was not well suited for random > > access. > > Maybe not. No, it's not. Element trees are, which if I just would have said originally... > A consideration of other storage formats such as HDF5 might > be appropriate: > > http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > There are, of course, HDF5 tools available for Python. PyTables came up within the past few weeks on the list. "When the file is created, the metadata in the object tree is updated in memory while the actual data is saved to disk. When you close the file the object tree is no longer available. However, when you reopen this file the object tree will be reconstructed in memory from the metadata on disk...." This is different from what I had in mind, but the extremity depends on how slow the 'reconstructed in memory' step is. (From http://www.pytables.org/docs/manual/ch01.html#id2506782 ). The counterexample would be needing random access into multiple data files, which don't all fit in memory at once, but the maturity of the package might outweigh that. Reconstruction will form a bottleneck anyway. > > I think we're starting to be sucked into a vortex of obtuse and opaque > > communication. > > I don't know about that. I'm managing to keep up with the discussion. > > > We agree that XML can store hierarchical data, and that it > > has to be read and written sequentially, and that whatever the merits of > > castironpi's software, his original use-case of random access to a 4GB > > XML file isn't workable. Yes? I could renege that bid and talk about a 4MB file, where recopying is prohibitively expensive and so random access is needed, thereby requiring an alternative to XML. > Again, XML specifically might not be workable for random access in a > serialised form, despite people's best efforts at processing it in > various unconventional ways, but that doesn't mean that random access > to a 4GB file containing hierarchical data isn't possible, so I > suppose it depends on whether he is wedded to the idea of using > vanilla XML or not. No. It is always nice to be able to scroll through your data, but it's much less common to be able to scroll though a data -structure-. (Which is part of the reason data structures are hard to design.) > It's always worth exploring the available > alternatives before embarking on a challenging project, unless one > wants to pursue the exercise as a learning experience, and I therefore > suggest investigating whether HDF5 doesn't already solve at least some > of the problems or use-cases stated in this discussion. The potential for concurrency is definitely one benefit of raw alloc/ free management, and a requirement I was setting out to program directly for. There is a multi-threaded version of HDF5 but interprocess communication is unsupported. "This version serializes the API suitable for use in a multi-threaded application but does not provide any level of concurrency." From: http://www.hdfgroup.uiuc.edu/papers/features/mthdf/ (It is always appreciated to find a statement of what a product does not do.) > Paul There is an updated statement of the problem on the project website: http://code.google.com/p/pymmapstruct/source/browse/trunk/pymmapstruct.txt I don't have numbers for my claim that the abstraction layers in SQL, including string construction and parsing, are ever a bottleneck or limiting factor, despite that it's sort of intuitive. Until I get those, maybe I should leave that allegation out. Compared to the complexity of all these other packages (ZOPE, memcached, HDF5/PyTables), alloc and free are almost looking like they should become methods on a subclass of the builtin buffer type. Ha! (Ducks.) They're beyond dangerous compared to the snuggly feeling of Python though, so maybe they could belong in ctypes. Aaron From mail.anand.anand at gmail.com Tue Sep 30 05:13:38 2008 From: mail.anand.anand at gmail.com (aathi) Date: Tue, 30 Sep 2008 02:13:38 -0700 (PDT) Subject: Welcome to US Computer Jobs Message-ID: <4cb0c7b1-e975-43ee-9c34-0607ed92e4de@m73g2000hsh.googlegroups.com> Welcome to US Computer Jobs Windows System Engineer Phone and Inperson Interview http://geocities.com/anandrisks/ http://friendfinder.com/go/g959922 http://amigos.com/go/g959922 From earlsoliloquyji at googlemail.com Mon Sep 22 07:21:33 2008 From: earlsoliloquyji at googlemail.com (earlsoliloquyji at googlemail.com) Date: Mon, 22 Sep 2008 04:21:33 -0700 (PDT) Subject: comsextv1 - for Free Message-ID: <02ffeb9a-5363-4b1f-bd25-5c30ed4bf8e7@f36g2000hsa.googlegroups.com> comsextv1 . . . *******CLICK HERE******** http://vids365.cn/comsextv1 ***************************** . . . . . . . . . . . . comsextv1 From bborcic at gmail.com Sat Sep 13 06:00:42 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 13 Sep 2008 12:00:42 +0200 Subject: max(), sum(), next() In-Reply-To: <48C8DBFF.20208@wildenhain.de> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <48BEE2F7.5010106@shopzeus.com> <1220499644.48bf58bc376e4@comuh.uh.cu> <48C8DBFF.20208@wildenhain.de> Message-ID: Tino Wildenhain wrote: > Hi, > > Luis Zarrabeitia wrote: >> Quoting Laszlo Nagy : >> > ... >> Even better: >> >> help(sum) shows >> >> === >> sum(...) >> sum(sequence, start=0) -> value >> Returns the sum of a sequence of numbers (NOT strings) plus >> the value >> of parameter 'start'. When the sequence is empty, returns start. >> === >> >> so the fact that sum([]) returns zero is just because the start value >> is zero... >> sum([],object()) would return an object(). >> >> BTW, the original code: >> >>>>> sum(s for s in ["a", "b"] if len(s) > 2) >> >> wouldn't work anyway... it seems that sum doesn't like to sum strings: >> >>>>> sum(['a','b'],'') >> >> : sum() can't sum strings [use >> ''.join(seq) instead] > > Yes which is a bit bad anyway. I don't think hard wiring it is such a > nice idea. You know, walks like a duck, smells like a duck... > If it makes sense to handle things differently for performance, then > please have it doing it silently, e.g. when it detects strings just > use join() internally. > > Cheers > Tino +1 ''.join is horrible. And it adds insult to injury that S.join(S.split(T)) != T as a rule. The interpreter has no business to patronize us into this shamefully contorted neighborhood while it understands what we want. Cheers, BB From george.sakkis at gmail.com Mon Sep 15 10:41:35 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 15 Sep 2008 07:41:35 -0700 (PDT) Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: On Sep 14, 9:07?pm, Grant Edwards wrote: > On 2008-09-15, Adelle Hartley wrote: > > > Grant Edwards wrote: > > >> When packages as significant as wxPython use naming > >> conventions other than PEP 8, I find it hard to make a case > >> that the PEP 8 naming convention is any better than any other. > > > This relates to a question I was thinking about... > > > I'm looking at porting a library that was written for COM and > > .Net to work as a Python module, and was wondering whether it > > would be better to stick to the library's current naming > > convention so that the API is as similar as possible on each > > platform, or to adopt a "when in Rome..." policy and follow > > the "most mainstream" naming pattern for each > > platform/language. > > If all that is would change is naming, then my advice would be > to keep the existing naming. ?That way it matches existing > documentation and examples. ?But, it does violate PEP 8. > > If the API itself is going to be changed significantly so that > it's unique to the Python port (different to the point where > existing documentation and examples are no longer useful), then > using standard PEP 8 naming conventions is probably a good choice. +1. Another factor is whether the original library's API is reasonably stable or it's expected to change significantly in the future. In the former case you may want to provide a more pythonic API, otherwise you'll have to do more work to keep in sync two separate APIs with every new version. George From paul at boddie.org.uk Sat Sep 13 10:37:13 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 13 Sep 2008 07:37:13 -0700 (PDT) Subject: lacking follow-through References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <289bc58f-6c04-4bce-b393-e9fa0a8c4fee@i20g2000prf.googlegroups.com> Message-ID: On 13 Sep, 08:38, Terry Reedy wrote: > > His recent posts have generally been quite different from those of some > months ago. Even he recognizes that they were somewhat weird and has > tried to do better. And I think we should at least go along with people if they're willing to raise their level of discussion. I'd much rather read messages at the level of the one which initiated this thread than idiotic, supposedly humorous responses about contributors being "bots". > Did he ever make any degrading attacks on people like the above, to > deserve receiving such? This reminds me of my elementary school, where > people who made social mistakes were sometimes never allowed to recover > but were dumped on for years. I get this impression as well: that "seniority" gives some kind of right to dump on anyone, and that we should all find this a source of amusement. It seems more like American high school, Hollywood style, if you ask me. Paul From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 09:44:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Sep 2008 13:44:58 GMT Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <00e4f84f$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 13:13:08 +0000, Duncan Booth wrote: > This is a good indication that the > author doesn't know much about OOP. I think you can drop the last two words :) Actually that's unfair -- it looks like he knows quite a bit about the metallicity of quasers, but he's just parroting a bunch of Java concepts as if Java was the be-all and end-all of object oriented programming, which is clearly wrong because we all know that Python's object model is the One True OOP. *wink* -- Steven From midfield at gmail.com Fri Sep 5 14:33:18 2008 From: midfield at gmail.com (Ben Lee) Date: Fri, 5 Sep 2008 11:33:18 -0700 (PDT) Subject: sqlite3 import performance Message-ID: hi folks -- a quick python and sqlite3 performance question. i find that inserting a million rows of in-memory data into an in-memory database via a single executemany() is about 30% slower than using the sqlite3 CLI and the .import command (reading the same data from a disk file, even.) i find this surprising, executemany() i assume is using a prepared statement and this is exactly what the .import command does (based on my quick perusal of the source.) is this discrepancy to be expected? where is the overhead coming from? for full disclosure: the python code is at the end; run it first to generate the data file. to test the CLI, i couldn't find a better way than to create an init file "sqlcmds" containing create table test (k int primary key, v int not null); .import data test and then run time sqlite3 -init sqlcmds ':memory:' '.quit' the python code is #!/usr/bin/env python import sqlite3, random, timeit con = None def prepare(): global con, cur con=sqlite3.connect(':memory:') con.isolation_level="EXCLUSIVE" cur=con.cursor() def ins(): global con, data, cur try: cur.execute('drop table test') except: pass cur.execute('create table test (key int primary key, val int not null);') con.commit() cur.executemany("INSERT into test (key, val) values (?, 10)",data) con.commit() hs = {} print 'generating data...' size = 1000000 data = [[a] for a in random.sample(xrange(10000000), size)] print 'done!' # save the data for the sqlite3 CLI f = file('data', 'w') f.writelines([str(a[0])+"|10\n" for a in data]) f.close() print 'testing ' + str(size) + ' inserts...' # test 100K inserts t = timeit.Timer(stmt='ins()', setup="import sqlite3\nfrom __main__ import prepare, ins \nprepare()") print t.repeat(3,1) thanks, ben From brtzsnr at gmail.com Fri Sep 19 09:40:00 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Fri, 19 Sep 2008 06:40:00 -0700 (PDT) Subject: generator exceptions Message-ID: <826a734c-968c-4d68-9ed1-c2688340ebc5@a3g2000prm.googlegroups.com> i have a generator that raises an exception when calling next(), however if I try to catch the exception and print the traceback i get only the line where next() was called while True: try: iterator.next() except StopIteration: break except Exception, e: traceback.print_exc() how do I get the traceback starting from where exception was raised in first place? From mnordhoff at mattnordhoff.com Fri Sep 12 18:15:05 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 12 Sep 2008 22:15:05 +0000 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <00da5aca$0$2879$c3e8da3@news.astraweb.com> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <00da5aca$0$2879$c3e8da3@news.astraweb.com> Message-ID: <48CAE9E9.805@mattnordhoff.com> Steven D'Aprano wrote: > On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote: > >> When mail messages bounce, the MTA (Message Transfer Agent--the program >> that handles mail) *should* send the bounce message to whatever is in >> the Sender header, and only if that header does not exist, should it use >> the From header. > > Who makes up these rules, and why should we pay the least bit of > attention to them? > > It's one thing to say "right or wrong, that's what list admins do and you > have to deal with their behaviour whatever way you can". It's another > thing altogether to take the legalistic attitude of "never mind the > consequences, the standard is the standard and must be unthinkingly > obeyed". If the standard does more harm than good, then ignoring the > standard is the right thing to do. (Better would be to change the > standard, but that probably won't happen until there's a critical mass of > people who ignore the existing broken standard and form their own de > facto standard.) > > A standard isn't "correct" just because it's a standard, it's merely > something that a committee has agreed to do. In other words, it's a > compromise. Now, such compromises might be good and useful, or they might > combine the worst of all opinions. Just because something is standardized > doesn't make it the right thing to do. If you want proof of this, I give > you the recently approved ISO standard for Microsoft's so-called "Office > Open XML" OOXML file format. > > The standard behaviour of sending bounce and out-of-office messages to > the sender works well when sending email to individuals, but for mailing > lists it is pointless and counter-productive. Pointless, because the > sender can't do anything to fix the problem he's being notified about. > And counter-productive, because it is an anti-feature, something that > makes the mailing list more unpleasant and less useful. Anyone who has > regularly emailed to a large mailing list has surely experienced the > frustration of receiving bounce messages from perfect strangers. > > To anyone who wishes to defend the process of sending mailing list > bounces back the sender, ask yourself this: what do YOU do with such > bounces when you receive them? If you ignore them or delete them (whether > manually or via a procmail recipe or some other automatic system) then > what benefit does the standard behaviour offer? I think you misunderstand. He's referring to the Sender header, not the >From header. The messages the listbot sends out have a Sender header of "python-list-bounces+user=example.com at python.org" (supposing the subscriber's email address is user at example.com). Bounces should be directed to the bitbucket or list admin or whatever, not the user in the >From header. kring.com just has a broken mail server. -- From digitig at gmail.com Mon Sep 29 13:43:12 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 29 Sep 2008 18:43:12 +0100 Subject: One class per file? In-Reply-To: References: Message-ID: 2008/9/29 Roy Smith : > That being said, the "one class per file" rule is a means to an end. Although in some languages, the "end" is "code that runs". But Python is not Java... -- Tim Rowe From bborcic at gmail.com Sat Sep 13 07:06:43 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 13 Sep 2008 13:06:43 +0200 Subject: ''.join woes - Re: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <48BEE2F7.5010106@shopzeus.com> <1220499644.48bf58bc376e4@comuh.uh.cu> <48C8DBFF.20208@wildenhain.de> Message-ID: I wrote: > Tino Wildenhain wrote: [...] >>>>>> sum(['a','b'],'') >>> >>> : sum() can't sum strings [use >>> ''.join(seq) instead] >> >> Yes which is a bit bad anyway. I don't think hard wiring it is such a >> nice idea. You know, walks like a duck, smells like a duck... >> If it makes sense to handle things differently for performance, then >> please have it doing it silently, e.g. when it detects strings just >> use join() internally. >> >> Cheers >> Tino > > +1 > > ''.join is horrible. And it adds insult to injury that > S.join(S.split(T)) != T as a rule. The interpreter has no business to > patronize us into this shamefully contorted neighborhood while it > understands what we want. What makes ''.join particularly horrible is that we find ourselves forced to use it not only for concatenating arbitrary-length strings in a list, but also to convert to a str what's already a sequence of single characters. IOW string types fail to satisfy a natural expectation for any S of sequence type : S == type(S)(item for item in S) == type(S)(list(S)) And this, even though strings are sequence types deep-down-ly enough that they achieve to act as such in far-fetched corner cases like (lambda *x : x)(*'abc')==('a','b','c') ...and even though strings offer not one but two distinct constructors that play nicely in back-and-forth conversions with types to which they are much less closely related, ie. '1j' == repr(complex('1j') == str(complex('1j')) 1j == complex(repr(1j)) == complex(str(1j)) Not-so-cheerfully-yours, BB From bdesth.quelquechose at free.quelquepart.fr Wed Sep 10 11:35:08 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 Sep 2008 17:35:08 +0200 Subject: Generator functions and user interfaces In-Reply-To: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> References: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> Message-ID: <48c8051b$0$23993$426a74cc@news.free.fr> psaffrey at googlemail.com a ?crit : > I'm trying to implement an interactive graph visualisation tool using > matplotlib. > > I want to use a spring layout, where nodes repulse each other and > edges act as springs to pull connected nodes together. Usually, this > algorithm runs through a number of iterations of attraction/repulsion > to allow the nodes to converge to suitable positions. However, rather > than running all these iterations to lay out the graph and then > rendering it, I want to animate the graph as it is "springing" into > place, and then allow the user to drag nodes around and have the graph > redraw on the fly. > > My idea for doing this was to use a generator function, where I yield > the position of the nodes after each iteration and then call draw() on > the position yielded. Does this seem like a sensible approach? I don't have much experience with this kind of algorithms, but AFAICT, it seems sensible to me, yes. But don't take me on words... > The > problem is that the node positions that are being operated on by the > generator function may be altered by user input - dragging the nodes - > and I'm not sure if this will break the way that the new positions are > yielded. How do I use a generator function that might stop (when the > nodes stop moving) but then need to restart again (once the user moves > the nodes)? Starting with Python 2.5, there's a way to pass values back to generators: http://docs.python.org/whatsnew/pep-342.html Now, not having played much with these new features so far, I'm afraid I can't help more, nor even be strictly positive about this being what you need. Any generator guru around ? From castironpi at gmail.com Sun Sep 7 19:33:41 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 7 Sep 2008 16:33:41 -0700 (PDT) Subject: lacking follow-through References: <00d453eb$0$20306$c3e8da3@news.astraweb.com> Message-ID: On Sep 7, 5:45?pm, Steven D'Aprano wrote: > On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > > Hi, > > > This is the strangest post I've seen > > since I've joined this list (only > > recently). What the ? > > Oh don't mind castironpi, many people think he's an IRC bot with some > experimental AI features that escaped onto Usenet *grins*. If you think > that post of his was strange, you haven't seen anything yet. Many people > have kill-filed him, and never even see his posts. > > A word to castironpi: you just suggested you will pester the list to get > a response. It's behaviour like that which gets you kill-filed. If you > would spend one tenth of the effort that you spend on understand Python > on understanding human psychology, you will probably get on with others > much better and find fewer people claiming you're a bot. > > Even if you yourself don't understand how others behave and expect you to > behave, think of it as an intellectual puzzle: how can I fool the strange > hairless apes into accepting me into their herd? > > -- > Steven First, gauge their persistence tolerance. Some people are not persistent enough. I don't want to annoy you, and I want to show interest, but of course no more than I actually feel. Are my standards too low, or too high? Second, debate the reverse psychology tack. Claim I'm a bot to shake their belief? Or call them bots? Perhaps they are. Bots with cooties. Yes. From mr.spoon21 at gmail.com Sun Sep 21 11:07:31 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 21 Sep 2008 17:07:31 +0200 Subject: Override the '+' symbol Message-ID: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> Hi, how can I override the '+' symbol (and other math symbols) so that it can have a new behavior when applied to some objects? From casuvetha at gmail.com Sat Sep 20 09:36:08 2008 From: casuvetha at gmail.com (killyou) Date: Sat, 20 Sep 2008 06:36:08 -0700 (PDT) Subject: jips works with in online Message-ID: http://candapud.blogspot.com/ From clodoaldo.pinto at gmail.com Sun Sep 14 10:50:16 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Sun, 14 Sep 2008 07:50:16 -0700 (PDT) Subject: cjson 1.0.5 keyword argument References: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> Message-ID: <31008070-11e0-44ad-9b27-9985323afb9a@s1g2000pra.googlegroups.com> On Sep 14, 11:45 am, "Guilherme Polo" wrote: > On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo wrote: > > I have installed cjson 1.05 in Fedora 8 (python 2.5.1). > > > The cjson home page shows a keyword argument "encoding". > >http://python.cx.hu/python-cjson/ > > The latest python-cjson on that page is 1.0.3, which accepts keywords > for the encode function. python-cjson 1.0.5 no longer accepts. > > > When i use it i get an error: > > >>>> cjson.encode('?', encoding='utf8') > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: encode() takes no keyword arguments > > > What am i missing? There is no mail list for cjson. > > Try doing cjson.encode('?'.decode('utf-8')) instead. I had tried decoding first and it worked but my database is utf-8 so i don't want that extra step. BTW i have already found the problem as the other post shows. Thanks, Clodoaldo From sturlamolden at yahoo.no Thu Sep 25 08:03:57 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 05:03:57 -0700 (PDT) Subject: multiple processes with private working dirs References: Message-ID: <2b282ed0-a004-4692-8521-ecc5d21d8a60@j22g2000hsf.googlegroups.com> On 24 Sep, 19:37, "Tim Arnold" wrote: > Am I missing something? Is there a better way? Use the pyprocessing module (to appear as standard module multiprocessing in Python 2.6). It has almost the same interface as Python's threading and Queue standard modules, except you are working with processes not threads. To wait for a process to finish, just join it like you would do with a thread. http://pyprocessing.berlios.de/ From maric at aristote.info Fri Sep 5 07:31:40 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 13:31:40 +0200 Subject: Case-insensitive string compare? In-Reply-To: References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050059.17038.maric@aristote.info> Message-ID: <200809051331.40609.maric@aristote.info> Le Friday 05 September 2008 08:24:29 Fredrik Lundh, vous avez ?crit?: > Maric Michaud wrote: > > "premature optimization is the root of all evil" > > So is use by that statement by people who don't have the slightest idea > about what it actually means. > > The full version is > > "We should forget about small efficiencies, say about 97% of the time: > premature optimization is the root of all evil." > > Note the use of "small efficiencies". That is, in Python, things like > local binding, inlining, slots, lazy generation of short sequences, etc. > That is, things that takes time to write and reduces maintainability. > > It's not about having an excuse for writing crappy code with large > inefficienies. > > And it's definitely not about programmers intentionally picking a dumb > solution so they can optimize it later. > Yes, I'm aware of that, thanks, but Chris Rebert was proposing to alter the data structure in order to achieve this simple comparison, I don't think it fails into your concern. > > If the OP's proposal seems already messy, how about ths one : > > if lib.lower() not in ( e[0] for e in stage_map.items() ) : > > ... > Sorry, should be read : if lib.lower() not in ( e[0] for e in stage_map.values() ) : and it was the expression for comparison Chris's solution lead to, not a proposal. > Given that your solution is just a remarkably inefficient way to write > "lib.lower() not in stage_map", and thus doesn't solve the OP:s problem, > I suspect you're taking the "evil" part of Hoare's dictum a few bits too > literally. > I suspect you are coming to conclusions a bit quickly, without taking the pain of understanding the whole discussion. > > > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From bignose+hates-spam at benfinney.id.au Sun Sep 14 21:01:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 11:01:23 +1000 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> Message-ID: <87wshe5ijg.fsf@benfinney.id.au> Grant Edwards writes: > On 2008-09-14, Ben Finney wrote: > > Second: please do yourself a favour and drop the camelCaseNames. > > Follow PEP 8 for style > > and naming in your Python code. > > If he finds camelcase more readable and easier to type (as do > I), how is switching to underscores "doing himself a favor"? > > I'm generally in favor of using a consistent naming style > throughout a project, but I don't see why the naming style used > in my source code should be subject to somebody else's > arbitrary standard. Because the code we write rarely stays isolated from other code. There is an existing convention, and it's better to pick a (sufficiently sane) style convention and stick to it than argue about what the convention should be. > When it comes to writing code intended for the standard library > in the main Python distribution, I would certainly defer to the > existing standard as defined in PEP 8. However, I don't see > any reason that style should be imposed on all everybody else. Who's imposing? I'm saying it's a good idea for everyone to do it, and going so far as to say that one is doing oneself a favour by following the convention. I have no more power than you to "impose" convention on anyone. -- \ ??Did you sleep well?? ?No, I made a couple of mistakes.?? | `\ ?Steven Wright | _o__) | Ben Finney From http Thu Sep 4 16:09:51 2008 From: http (Paul Rubin) Date: 04 Sep 2008 13:09:51 -0700 Subject: Can anyone suggest a good crypto package? References: Message-ID: <7xwshr4qr4.fsf@ruckus.brouhaha.com> Fett writes: > Is there any crypto package that is actually written in python? I > seriously don't care how slow it is. I wrote a simple symmetric encryption function in python: http://nightsong.com/phr/crypto/p3.py I wrote a somewhat fancier package that did public key a while back, that is unreleased because of insufficient testing and some features I'd like to have done differently, but I ought to get around to cleaning it up sometime. There is also tlslite, which you might be able to extract some public key functions from: http://trevp.net/tlslite From michele.simionato at gmail.com Wed Sep 10 08:10:09 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 10 Sep 2008 05:10:09 -0700 (PDT) Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: <9f3d127f-4434-4a27-b5d4-b43ebb137186@k30g2000hse.googlegroups.com> On Sep 10, 1:45?pm, Fredrik Lundh wrote: > deni... at t-online.de wrote: > > ? ?how can I list all modules that might be importable on my system, > > ? ?without actually importing them all ? > > I'm pretty sure I mentioned a way to do that back when this thread was > opened. ?let's see, yes, here it is: > > ... > > there's a helper script in the 2.5 source code kit that locates all > existing standard modules: > > http://svn.python.org/projects/python/tags/r252/Doc/tools/listmodules.py > > to get all modules, remove the for-loop that follows after the comment > "get rid of site packages". I have just tried the following on my Ubuntu box with the system Python: ~$ python /usr/lib/python2.5/doc/tools/listmodules.py /usr/lib/python2.5/doc/tools/listmodules.py:99: DeprecationWarning: the rgbimg module is deprecated __import__(m) ** (process:24863): WARNING **: AT_SPI_REGISTRY was not started at session startup. ** (process:24863): WARNING **: Could not locate registry location: /usr/lib/xulrunner-1.9.0.1/libxpcom.so before 3 /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: cannot register existing type `GtkSourceStyleScheme' __import__(m) /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: g_type_set_qdata: assertion `node != NULL' failed __import__(m) /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: cannot register existing type `GtkSourceBuffer' __import__(m) /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: g_type_get_qdata: assertion `node != NULL' failed __import__(m) Segmentation fault Interesting, isn't it? Michele Simionato From bdesth.quelquechose at free.quelquepart.fr Tue Sep 2 16:45:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Sep 2008 22:45:25 +0200 Subject: synthetic properties In-Reply-To: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> References: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> Message-ID: <48bda606$0$32752$426a74cc@news.free.fr> rowland at river2sea.org a ?crit : > I'm trying to come up with solution for adding synthetic properties to > python, similar to synthetic properties in Objective-C. Please explain what Objective-C "synthetic properties" are - not everyone here has a strong Objective-C background... > I'm playing around with doing this in a MetaClass. I can dynamically > create the attributes that will back the property, but I'm having > trouble figuring out how to dynamically generate get/set methods to > pass to the built-in property() function. FWIW, the property type is just one possible application of the descriptor protocol. You can easily define your own custom descriptor classes - and you can even do this dynamically. > Is it possible to define a lambda or a callable object that will act > as a getter method (or setter, that takes a value argument) during > MetaClass.__init__? Yes. > The hard part I'm guessing is getting the current > instance passed into the getter. Not really. > This is my first foray into > MetaClasses and dynamic functions/methods so any pointers are greatly > appreciated. > > > class ObjectivePythonObject( type ) : > > def __new__( cls, name, bases, dct ) : > #print "Allocating memory for class", name > return type.__new__(cls, name, bases, dct ) This is what type.__new__ do, so you just don't need it. > def __init__( cls, name, bases, dct ) : > #print "Initializing class", name > for propertyInfo in cls.synthesized : > property = propertyInfo[ 0 ] > defaultValue = propertyInfo[ 1 ] > print property > setattr( cls, '_' + property, defaultValue ) > # Create property with get/set methods... > > class Person( object ) : > > __metaclass__ = ObjectivePythonObject > > > synthesized = [ ( 'name', 'BobC' ), > ( 'age', '48' ) ] > > def __init__( self ) : > print self._name > print self._age > May I suggest you read about Python's coding conventions ? Your code formatting is utterly unpythonic... Ok, here's a working (and slightly more pythonic - at least wrt/ coding style) version of your code: def _make_prop(attrname, default): def fget(self): return getattr(self, attrname, default) def fset(self, value): setattr(self, attrname, value) return property(fget=fget, fset=fset) class ObjectivePythonType(type) : def __init__(cls, name, bases, dct): # we don't want to redefine properties already # defined in a base class synthesized = dct.get('synthesized', ()) for propname, default in synthesized: attrname = "_%s" % propname setattr(cls, propname, _make_prop(attrname, default)) class ObjectivePythonObject(object): __metaclass__ = ObjectivePythonType class Person(ObjectivePythonObject): synthesized = [ ('name', 'BobC'), ('age', '48'), ] def __init__(self) : print self.name print self.age Now... While all this is certainly usefull as a learning exercice on metaclasses etc, it's also an awfully overcomplexificated way to do something quite simple. Here's some code that do exactly the same thing: class PythonPerson(object): name = "BobC" age = "48" def __init__(self): print self.name print self.age HTH From deets at nospam.web.de Tue Sep 2 12:49:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Sep 2008 18:49:16 +0200 Subject: source for the property function In-Reply-To: References: Message-ID: <6i594dFopddmU1@mid.uni-berlin.de> Rowland Smith schrieb: > Anyone know where the source code for the built-in property function is > located in a python distribution? > > I would like to see how it works - mainly, how does it know which class > it is being called from? Google the "descriptor protocol" for new-style classes. That explains it. Diez From luigi at lambrate.inaf.it Wed Sep 3 09:54:20 2008 From: luigi at lambrate.inaf.it (Luigi Paioro) Date: Wed, 03 Sep 2008 15:54:20 +0200 Subject: Custom handler for logging In-Reply-To: References: Message-ID: <48BE970C.1070405@lambrate.inaf.it> Thanks, it works perfectly! Luigi Peter Otten ha scritto: > Luigi Paioro wrote: > >> concerning the logging module, I have written a new Handler which stores >> the logging messages in an SQLite database. It works well, but when I >> try to use it exploiting a configuration file I have a problem since the >> "class" entry does not accept a class which is not within the logging >> name-space, while the class I implemented is coded in my personal module >> (thus another name-space). >> >> Is there a workaround to allow the usage of custom handlers? > > Maybe > > http://mail.python.org/pipermail/python-list/2003-October/232762.html > > Peter From mail at timgolden.me.uk Thu Sep 18 08:14:48 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 18 Sep 2008 13:14:48 +0100 Subject: XML Processing In-Reply-To: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> References: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> Message-ID: <48D24638.9010601@timgolden.me.uk> Robert Rawlins wrote: > I?m running python 2.5 and currently using ElementTree to perform my XML > parsing and creation. ElementTree really is a great package for doing > this, however, I?ve been tasked by our deployment guys to try and move > away from external libraries where possible as it makes their job easier. Some is going to kick themselves when they realise that ElementTree *is* built in to Python 2.5 http://docs.python.org/whatsnew/modules.html#SECTION0001420000000000000000 TJG From coolman.guron at gmail.com Tue Sep 16 12:30:20 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Tue, 16 Sep 2008 09:30:20 -0700 (PDT) Subject: Porting a pygtk app to Windows Message-ID: <7ce94e05-d704-4118-9496-26f9d7aa6853@k36g2000pri.googlegroups.com> hi everyone, first of all I had written an app using pygtk module and created the GUI with glade.All the development was done on a linux machine and the app was working fine all this tme in linux. now, the thing is i have to change the development environment to windows. So this means that i have to port the application to work in windows. Initially i thought that porting an application written using a platform independent language and cross-platform window frame work would be a piece of cake. Well i guess all the assumptions end there. unlike linux, in windows pygtk and the GTK frame work are not installed by default. So, long story short. i installed GTK devel, pygtk, pygobject, pycaro, glade ui. Also made a lot of path adjustments (os.path.absolutepath() is not portable i guess) and finally got the app to at least start without showing an error. The problem that i am now facing is that nothing shows up in the app. No menu, buttons, frames or anything else is visible. When i move the cursor over the window it changes into an hour-glass type icon. hoe ever all c++ GTK programs seem to render well. here is a screen shot: http://i36.tinypic.com/x52uk9.jpg i have written below the startup code of the app: import pygtk pygtk.require('2.0') import gtk import gtk.glade from ConfigParser import ConfigParser class jDesk(object): def __init__(self): #self.seclstore.append(["0","Section1"]) #self.catlstore.append(["cat 1"]) self.synclstore = gtk.ListStore(str,str,str,str,str,int) self.seclstore = gtk.ListStore(str,str) self.catlstore = gtk.ListStore(str,str) self.process_glade() def process_glade(self): self.gladefile = "gui.glade" self.glade = gtk.glade.XML(self.gladefile) #windows self.main_window = self.glade.get_widget('MainWindow') #main window self.templatefile = self.glade.get_widget('templatefile') self.imageurl = self.glade.get_widget('imageurl') self.posttitle = self.glade.get_widget('posttitle') self.sectionbox = self.glade.get_widget('sectionbox') self.categorybox = self.glade.get_widget('categorybox') self.demolink = self.glade.get_widget('demolink') self.posttext = self.glade.get_widget('posttext') self.statusbar = self.glade.get_widget('statusbar') self.signal_autoconnect() self.main_window.show() print '===================main wind created=================' def run(self): try: print "Entering GTK main now" gtk.main() print "Leaving GTK main" except: print "Exception in main" if __name__ == "__main__": conf = ConfigParser() conf.read('settings.cfg') gtk.gdk.threads_init() app = jDesk() app.run() i have tried a lot of things, checked up paths, checked libcairo but nothing seems to help.problem seems to be with pygtk since other c++ GTK programs like pedgin and GTK demo rn fine. So maybe is there any pygtk windows bugs that i coming from linux background might not be knowing about or perhaps u have encountered such a problem in the past before ? Much thanks in advance BinaryJ From alan.isaac at gmail.com Sun Sep 7 15:24:33 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sun, 07 Sep 2008 19:24:33 GMT Subject: formatting a string with thousands separators In-Reply-To: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> References: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> Message-ID: On 9/7/2008 12:22 PM SimonPalmer apparently wrote: > anyone recommend a way of formatting floats with comma separators? http://code.activestate.com/recipes/498181/ Alan Isaac From marco.bizzarri at gmail.com Sat Sep 13 04:03:02 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 13 Sep 2008 10:03:02 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <48ca9333$0$851$426a74cc@news.free.fr> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> <48ca9333$0$851$426a74cc@news.free.fr> Message-ID: <3f0d61c40809130103m78f5c0cfnade1446b36bf1600@mail.gmail.com> On Fri, Sep 12, 2008 at 6:07 PM, Bruno Desthuilliers wrote: > Marco Bizzarri a ?crit : > (snip) >> >> I'm afraid this have another problem for me... >> >> >> emmebi at janitor:/var/local/zope28/porting/Products/PAFlow$ python2.3 >> Python 2.3.5 (#2, Oct 18 2006, 23:04:45) >> [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> >>>>> def any(iterable): pass >> >> ... >>>>> >>>>> any(x for x in [1, 2, 3]) >> >> File "", line 1 >> any(x for x in [1, 2, 3]) >> ^ >> SyntaxError: invalid syntax >> >>>>> any([x for x in [1, 2, 3]]) >>>>> >> >> I mean, I'm afraid I can't use an expression like that without >> building a list... not at least in python2.3 > > Err... a list being an iterable, you just need any([1, 2, 3]). Ehm, yes, of course... I was trying just to show from a command line what were my results. > > But this wont be enough to solve your real use case, indeed. Yes, that's the point. -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From pmaupin at gmail.com Sun Sep 7 20:55:02 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 7 Sep 2008 17:55:02 -0700 (PDT) Subject: Read and write binary data References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: On Sep 7, 5:41?pm, Mars creature wrote: > Hi guys, > ? I am new to Python, and thinking about migrating to it from matlab > as it is a really cool language. Right now, I am trying to figure out > how to control read and write binary data, like > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > I googled, but can not find a clear answer. Anyone has clue where can > I learn it? Thanks!! > Jinbo Start by looking at the array module. Regards, Pat From rocksportrocker at googlemail.com Thu Sep 11 07:15:09 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 11 Sep 2008 04:15:09 -0700 (PDT) Subject: I want to use a C++ library from Python References: Message-ID: <08aa1042-f1aa-40ac-a099-11c30e2a2b4e@i76g2000hsf.googlegroups.com> On 10 Sep., 09:57, Anders Eriksson wrote: > Hello, > > I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1 > .lib and 1 .dll files. I don't have the source code. > > How can I create a Python module from these files? Do you need the full library including classes or just some functions ? You could write a wrapper in C around the lib and use f2py or ctypes to call your wrapper from python. But that does not work if you want to expose classes. Greetings, Uwe From kushaldas at gmail.com Fri Sep 5 09:16:36 2008 From: kushaldas at gmail.com (Kushal Das) Date: Fri, 5 Sep 2008 18:46:36 +0530 Subject: =?UTF-8?Q?=E2=80=98A_Byte_of_Python=E2=80=99_updated_for_Python_3.0?= Message-ID: Hi all, Swaroop just released the latest version of his book "A Byte of Python", the new version is for Python 3.0. Read the post at http://www.swaroopch.com/blog/book-updated-for-python-3000/ The book can be found at http://www.swaroopch.com/notes/Python Kushal -- http://fedoraproject.org http://kushaldas.in http://badvista.org http://noooxml.org From jbar at hosting4u.cz Thu Sep 18 11:04:41 2008 From: jbar at hosting4u.cz (Jiri Barton) Date: Thu, 18 Sep 2008 17:04:41 +0200 Subject: unicode in multi-line strings Message-ID: <48D26E09.6000200@hosting4u.cz> Hello, I have a problem with international characters in multi-line strings. Works: '''?''' Works: ''' a''' Does not work: ''' ?''' By does not work I mean the infamous 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128) I'm using Ubuntu 8.04 with Python 2.5. It does not work in terminal, from scripts, or from scripts with the encoding specified at the top. Making the string unicode (u''' ... ''') does not change anything. It could be an interpreter issue but I didn't know where else I should turn for help. Thank you! Jiri From castironpi at gmail.com Sun Sep 14 15:49:51 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 14 Sep 2008 12:49:51 -0700 (PDT) Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <64670149-9467-4ca7-9d7e-c330c1b403e4@c58g2000hsc.googlegroups.com> Message-ID: <29a3ef5f-49ea-41c7-84bf-f4101ac6397b@e53g2000hsa.googlegroups.com> On Sep 14, 2:38?pm, Roy Smith wrote: > In article > <64670149-9467-4ca7-9d7e-c330c1b40... at c58g2000hsc.googlegroups.com>, > ?"Aaron \"Castironpi\" Brady" wrote: > > > However, from what I understand (brass player), > > If you play the trombone, you might want your Note class to allow > floating-point values for pitch :-) I do! Then there are the known cases of flute players rolling the mouthpiece to change pitch, trumpet players bending, violin. The 3rd of a scale is slightly sharp in Bach's temper. Semi-tones come up in Theory class too. note= Note( "C" ) third= MajorInterval( 3 ) print note+ third : From mnations at gmail.com Thu Sep 4 19:36:11 2008 From: mnations at gmail.com (Mudcat) Date: Thu, 4 Sep 2008 16:36:11 -0700 (PDT) Subject: Python test case management system? Message-ID: I had originally planned on writing my own software for managing test cases; however new boss = new directive. This will make it more difficult to get the functionality I need for test cases that are automated and executed using python. I've searched for alternatives but so far haven't come up with any good options. Does anyone know of a good test case management system written in python, or possibly another application (either open source or commercial) that can be extended using python? Thanks From m_palmer45 at yahoo.ca Mon Sep 15 19:36:05 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 15 Sep 2008 16:36:05 -0700 (PDT) Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> Message-ID: <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> On Sep 15, 3:04 pm, Matias Surdi wrote: > aditya shukla escribi?: > > > How can we convert .py files to batch files? is there any library for this? > > > Aditya > > > ------------------------------------------------------------------------ > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Maybe py2exe can help you. I assume you are on Windows? Let's assume you have a file stuff.py that reads: import os print os.listdir('.') # list current directory, good enough for testing... Then, insert the following line at the top: @setlocal enableextensions & python -x %~f0 %* & goto :EOF Now save this file as stuff.cmd somewhere along your PATH. Now calling 'stuff' should execute your file. On Linux, you would instead insert the shebang line that points to your python interpreter, such as #!/usr/bin/python at the top and also set the executable bit, but I suppose if you use Linux at all you know that. From tjreedy at udel.edu Sat Sep 6 19:00:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Sep 2008 19:00:05 -0400 Subject: Multicore-programming? In-Reply-To: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: cnb wrote: > If I buy a multicore computer and I have really intensive program. How > would that be distributed across the cores? > > Will algorithms always have to be programmed and told specifically to > run on several cores so if not told it will only utilize one core? I believe that has always been true. > > So is the free lunch really over or is this just an overhyped > phenomena? > > Is threading with Python hard? Opinions vary, mostly depending on experience. But Python threads do not distribute across processors. >Can you start several processes with > Python or just threads? import subprocess and read the manual for that module From musiccomposition at gmail.com Mon Sep 15 22:38:33 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 15 Sep 2008 19:38:33 -0700 (PDT) Subject: Client server implementation References: Message-ID: <7d623ffb-2936-4aec-a74a-e9f5489e6657@p25g2000hsf.googlegroups.com> On Sep 15, 5:15?am, Babloo wrote: > Hi everyone, > > ? ? ? ? ? ? ? ? ? i wanted to implement a client- server connection > and transfer a file over the network. i was able to implement a normal > set up where in i was able to send chat messages and small chunks of > data. > I want to implement the file transfer with out using the FTP library > available in python . > > ? ? ? ? ? ? ? ? ? So can anyone suggest a piece of code by which i can > do that. I don't know what you really want, but look at Twisted. http://twistedmatrix.com > > Thanks > Pruthvi From mail at microcorp.co.za Sat Sep 6 17:20:15 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 6 Sep 2008 23:20:15 +0200 Subject: max(), sum(), next() Message-ID: <005801c91086$1fbfdee0$0d00a8c0@hendrik> "David C. Ullrich" wrote: >Think about all the previously elected female or black >presidents of the US. Which one was the tallest? The current King of France? - Hendrik From deets at nospam.web.de Wed Sep 3 12:57:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 18:57:38 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <6i7u02Fpeif6U1@mid.uni-berlin.de> Michael Palmer schrieb: > As anyone knows, the state of Python GUI programming is a little > fractured at this time, with many toolkits, wrappers and meta-wrappers > dead and alive, with or without documentation. > > I've come across two projects that have the appeal of striving for > simple, pythonic APIs: PyGUI and wax. The latter is a wrapper around > wxPython. It is lacking documentation but actually quite usable and > concise. The other, PyGUI, has an even nicer API and more docs but has > relatively few widgets implemented at this time. It also strives for > compatibility with several toolkits (two at this time), which I think > is the right idea. I disagree with that. Meta-wrappers like this will always suffer from problems, as they have difficulties providing a consistent api. For example wx is said to be very windows-toolkit-centric in it's API. Yes I know that it works under Linux with GTK, but it does not come as natural . > So far, development of PyGUI seems to be a one-man effort, and it may > be slowed down by the attempt to develop the API and the > implementations concurrently. Could it be useful to uncouple the two, > such that the API would be specified ahead of the implementation? This > might make it easier for people to contribute implementation code and > maybe port the API to additional toolkits. It seems that this approach > has been quite successful in case of the Python database API. That API > defines levels of compliance, which might be a way of accommodating > different GUI toolkits as well. > > I may be underestimating the difficulties of my proposed approach - I > don't have much practical experience with GUI programming myself. I think you do. The reason for the various toolkits is not because of python - it's the proliferation of toolkits that exist out there. As long as none of these is "the winner" (and it doesn't look is if that's to happen soon), I doubt that one API to rule them all will exist - they all have their different strengths and weaknesses, and a python-API should reflect these. Diez From showellshowell at gmail.com Wed Sep 24 22:08:04 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Wed, 24 Sep 2008 19:08:04 -0700 (PDT) Subject: is decorator the right thing to use? References: Message-ID: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> On Sep 24, 3:21?pm, "Dmitry S. Makovey" wrote: > Hi, > > after hearing a lot about decorators and never actually using one I have > decided to give it a try. My particular usecase is that I have class that > acts as a proxy to other classes (i.e. passes messages along to those > classes) however hand-coding this type of class is rather tedious, so I > decided to use decorator for that. Can somebody tell me if what I'm doing > is a potential shot-in-the-foot or am I on the right track? (Note, It's > rather rudimentary proof-of-concept implementation and not the final > solution I'm about to employ so there are no optimizations or > signature-preserving code there yet, just the idea). > Your code below is very abstract, so it's kind of hard to figure out what problem you're trying to solve, but it seems to me that you're using the B proxy class to decorate the A target class, which means you want one of these options: 1) Put decorators over the methods in A, not B. Isn't it the methods of A that are being decorated here? 2) Eliminate the decorator syntax and make your code more expressive: a = SomeClass() # first call it directly x = a.foo() y = a.bar() # now decorate it debug_proxy = ClassThatDecoratesMethodCallsToObjectWithDebuggingCode(a) debug_proxy.decorate_methods('foo', 'bar') The decorate_methods method would be magical, in terms of overwriting a's innards, while still preserving the same interface for its users. But again, I'm just guessing here, because it's hard to know what problem you're really solving. Cheers, Steve Code quoted below: > Here's the code: > > class A: > ? ? b=None > ? ? def __init__(self,b): > ? ? ? ? self.val='aval' > ? ? ? ? self.b=b > ? ? ? ? b.val='aval' > > ? ? def mymethod(self,a): > ? ? ? ? print "A::mymethod, ",a > > ? ? def mymethod2(self,a): > ? ? ? ? print "A::another method, ",a > > def Aproxy(fn): > ? ? def delegate(*args,**kw): > ? ? ? ? print "%s::%s" % (args[0].__class__.__name__,fn.__name__) > ? ? ? ? args=list(args) > ? ? ? ? b=getattr(args[0],'b') > ? ? ? ? fnew=getattr(b,fn.__name__) > ? ? ? ? # get rid of original object reference > ? ? ? ? del args[0] > ? ? ? ? fnew(*args,**kw) > ? ? setattr(A,fn.__name__,delegate) > ? ? return fn > > class B: > ? ? def __init__(self): > ? ? ? ? self.val='bval' > > ? ? @Aproxy > ? ? def bmethod(self,a): > ? ? ? ? print "B::bmethod" > ? ? ? ? print a, self.val > > ? ? @Aproxy > ? ? def bmethod2(self,a): > ? ? ? ? print "B::bmethod2" > ? ? ? ? print a, self.val > > b=B() > b.bmethod('foo') > a=A(b) > b=B() > b.val='newval' > a.bmethod('bar') > a.bmethod2('zam') From gminick at bzt.bzt Tue Sep 2 09:33:08 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Tue, 2 Sep 2008 13:33:08 +0000 (UTC) Subject: Algorithm used by difflib.get_close_match References: <83c600d0-6852-4dd6-9287-34f9b3264090@s50g2000hsb.googlegroups.com> Message-ID: On Tue, 2 Sep 2008 06:17:37 -0700 (PDT), Guillermo wrote: > Does anyone know whether this function uses edit distance? If not, > which algorithm is it using? The following passage comes from difflib.py: SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable. The basic algorithm predates, and is a little fancier than, an algorithm published in the late 1980's by Ratcliff and Obershelp under the hyperbolic name "gestalt pattern matching". The basic idea is to find the longest contiguous matching subsequence that contains no "junk" elements (R-O doesn't address junk). The same idea is then applied recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not yield minimal edit sequences, but does tend to yield matches that "look right" to people. HTH. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From mathieu.prevot at gmail.com Thu Sep 4 09:25:24 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 15:25:24 +0200 Subject: path slashes cleaning Message-ID: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> Hi, for scripts that take arguments, I would like to remove the trailing slash if it's present. Is there something else than: a='/usr/local/lib/' if a[-1] == '/': a = list(a) a.pop() ''.join(a) Thanks, Mathieu From rNOSPAMon at flownet.com Thu Sep 18 21:21:21 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 Sep 2008 18:21:21 -0700 Subject: CTypes on a 64 bit machine truncates pointers to 32 bits? Message-ID: CTypes on a 64-bit machine appears to be truncating pointers to 32 bits: [ron at monster1:~]$ uname -a Linux monster1 2.6.18-6-amd64 #1 SMP Mon Jun 16 22:30:01 UTC 2008 x86_64 GNU/Linux [ron at monster1:~]$ cat foo.c void* foo(void* x) { return x; } [ron at monster1:~]$ gcc -fPIC -shared foo.c -o foo.so [ron at monster1:~]$ file foo.so foo.so: ELF 64-bit LSB shared object, AMD x86-64, version 1 (SYSV), not stripped [ron at monster1:~]$ python Python 2.5 (release25-maint, Jul 23 2008, 18:15:29) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> foolib = cdll.LoadLibrary('foo.so') >>> foolib.foo(0xF00000000) 0 >>> sizeof(c_void_p) 8 >>> I am aware of http://bugs.python.org/issue1703286 but I get the same result in Python2.5.2: [ron at monster1:~]$ py252/bin/python Python 2.5.2 (r252:60911, Sep 18 2008, 10:48:29) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> foolib = cdll.LoadLibrary('foo.so') >>> foolib.foo(0xF00000000) 0 >>> sizeof(c_void_p) 8 >>> From fredrik at pythonware.com Fri Sep 5 02:43:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:43:15 +0200 Subject: "Full" element tag listing possible with Elementtree? In-Reply-To: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> References: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Message-ID: jaime.dyson at gmail.com wrote: >
> this is node b > this is node c > > this is node e > > this is node f > > > I would want to print the following: > > > > text: this is node b > > text: this is node c > > > text: this is node e > > this is node f > > Is there a simple way to do this? Any help would be appreciated. in stock ET, using a parent map is probably the easiest way to do this: http://effbot.org/zone/element.htm#accessing-parents that is, for a given ET structure "tree", you can do parent_map = dict((c, p) for p in tree.getiterator() for c in p) def get_parents(elem): parents = [] while 1: elem = parent_map.get(elem) if elem is None: break parents.append(elem) return reversed(parents) for elem in tree.getiterator(): print list(get_parents(elem)), elem From deets at nospam.web.de Mon Sep 1 17:59:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 23:59:16 +0200 Subject: encoding In-Reply-To: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> References: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> Message-ID: <6i36tkFogbfkU1@mid.uni-berlin.de> Gandalf schrieb: > if i want to print utf-8 string i should writre: > > print u"hello word" No, you don't. You write print u"hello world".encode("utf-8") Read this: http://www.reportlab.com/i18n/python_unicode_tutorial.html > but what happen if i want to print variable? Then you do print variable_containing_unicode_object.encode("utf-8") Diez From castironpi at gmail.com Wed Sep 17 16:18:16 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 17 Sep 2008 13:18:16 -0700 (PDT) Subject: minimum install & pickling References: <6f045535-555f-44b6-93a5-f5b338d3f318@d45g2000hsc.googlegroups.com> Message-ID: <69cf2202-e11b-4994-84ab-a41167ef2652@26g2000hsk.googlegroups.com> On Sep 17, 4:43?am, Paul Boddie wrote: > On 17 Sep, 07:26, "Aaron \"Castironpi\" Brady" > wrote: > > > Sometimes questions come up on here about unpickling safely and > > executing foreign code. ?I was thinking a minimum install that didn't > > even have access to modules like 'os' could be safe. ? (Potentially.) > > I have time to entertain this a little, though all the devs are busy. > > I can bring it up again in a few months if it's a better time. > > One alternative might be to provide "safe" versions of the underlying > functions in modules like "os". Previously, I did wonder why people > didn't link Python against a bunch of alternative libraries which > would provide implementations of things like "open", "chdir" and so > on, but then I was made aware of fakeroot and fakechroot which do more > or less this for any program (in conjunction with chroot) in order to > restrict the behaviour of those programs, without any need to > statically link the programs first. > > [...] > > > A lot of modules would have to go. ? ?IPC modules: > > subprocess, socket, signal, popen2, asyncore, asynchat. ?ctypes, mmap, > > platform.popen, glob, shutil, dircache, and many more. > > Potentially, these could remain, but you'd want to provide "fake" > versions of the underlying functions, potentially implementing your > own preferred flavour of access control. So, with a call to the > "socket" function, the wrapped version might first consult some kind > of behaviour policy set by the user in order to get permission to open > a connection to a remote host. > > There's a discussion of rexec and related solutions on the Wiki: > > http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...) > > Paul These solutions have at least the same bugs that the bare bones solution in the corresponding framework has. Malicious code has fewer options, but constructive code does too. If you're running foreign code, what do you want it to do? What does it want to do? The more options it needs, the more code you have to trust. The only way a Python script can return a value is with sys.exit, and only an integer at that. It is going to have output; maybe there's a way to place a maximum limit on its consumption. It's going to have input, so that the output is relative to something. You just make copies to prevent it from destroying data. Maybe command-line parameters are enough. IIRC if I recall correctly, Win32 has a way to examine how much time a process has owned so far, and a way to terminate it, which could be in Python's future. PyPy sandbox says: "The C code generated by PyPy is not segfaultable." I find that to be a bold claim (whether it's true or not). I'm imagining in the general case, you want the foreign code to make changes to objects in your particular context, such as exec x in vars. In that case, x can still be productive without any libraries, just less productive. From larry.bates at vitalEsafe.com Sat Sep 13 14:25:02 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 13 Sep 2008 13:25:02 -0500 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: <48cbf432$0$27507$426a34cc@news.free.fr> References: <48cbf09c$0$25189$426a74cc@news.free.fr> <48cbf432$0$27507$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Bruno Desthuilliers a ?crit : >> Larry Bates a ?crit : >> (snip) >>> IMHO it reads better if you use the __call__ method of the class to >>> return the value >> >> IMHO, it makes no sense at all to abuse the __call__ magic method here. > > Sorry - after a more careful re-read of other posts in the thread, it > might make sense, given the use case : > > condition = FolderInUse(core) > if condition.true_for(folder): > # code here > > > but then, a plain function (or a partial) might be even better - that > is, if the FolderInUse class doesn't have other responsabilities. > > Sorry but I respectfully disagree that this is "abuse" of the __call__ method. I do agree that a plain function probably makes more sense but it appears that the class does "other"things because of references to other class instances, etc. I also have a personal dislike for early returns because I've found it makes it harder insert execution trace logging into the code. Just my experience. -Larry From http Fri Sep 5 20:53:31 2008 From: http (Paul Rubin) Date: 05 Sep 2008 17:53:31 -0700 Subject: Can anyone suggest a good crypto package? References: <7xwshr4qr4.fsf@ruckus.brouhaha.com> <7xmyino11v.fsf@ruckus.brouhaha.com> <6a21ce15-da79-43f7-b090-71e36c6a7c89@d1g2000hsg.googlegroups.com> Message-ID: <7xzlmm6qno.fsf@ruckus.brouhaha.com> Fett writes: > I am having trouble seeing how I would post the encrypted data to a > website and get it back without it changing some. I don't understand why it would change. I'm a little confused though, I didn't realize you wanted to post the data to a web site. What exactly are you trying to do? > By replay attack I assume you mean posting old data with the signature > that is valid for that data? Yes, the usual case is injecting an old message into a sequence of messages that is part of a protocol. > Thanks for the warning, I suppose I could include a date/timestamp > in the data. Be aware in general that security is a messy and difficult subject and there are a lot of subtle errors you can make. You might look at some of the articles at www.dwheeler.com or the book "Security Engineering" (http://www.cl.cam.ac.uk/~rja14/book.html) to see some of the issues. From aahz at pythoncraft.com Sat Sep 27 01:15:43 2008 From: aahz at pythoncraft.com (Aahz) Date: 26 Sep 2008 22:15:43 -0700 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: In article , Steven D'Aprano wrote: >On Thu, 25 Sep 2008 21:17:14 -0700, Aahz wrote: >> >> Seems to me that if all the module is used for is to store state, you're >> wasting a file on disk. I personally prefer to use a class singleton. > >I don't recognise the term "class singleton". Can you explain please? How >is it different from an ordinary singleton? An ordinary singleton is instantiating the class multiple times yet returning the same instance object; a class singleton is simply using the class directly (like a module). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From robin at reportlab.com Thu Sep 11 13:07:19 2008 From: robin at reportlab.com (Robin Becker) Date: Thu, 11 Sep 2008 18:07:19 +0100 Subject: ReportLab 2.2 has been released Message-ID: <48C95047.8000209@chamonix.reportlab.co.uk> Version 2.2 of the ReportLab open-source toolkit is out! You find downloads and src instructions at http://www.reportlab.org/downloads.html. Contributions ============= Thanks to everybody who has contributed to the open-source toolkit in the run-up to the 2.2 release, whether by reporting bugs, sending patches, or contributing to the reportlab-users mailing list. Thanks especially to the following people, who contributed code that has gone into 2.2: including, but not limited to (apologies to any missed out) Matt Folwell, Jerome Alet, Harald Armin Massa, kevin at booksys.com, Sebastian Ware, Martin Tate, Wietse Jacobs, Christian Jacobs, Volker Haas, Dinu Gherman, Dirk Datzert & Yuan Hong. If we missed you, please let us know! New Features ============ PDF pdfmetrics: Added registerFontFamily function Basic support for pdf document viewer preferences (e.g.: fullscreen). Platypus Paragraph tag support for inline images. Paragraph autoleading support (helps with tags). Platypus doctemplate programming support. Support for tables with non-uniform row length. Graphics RGBA image support for suitable bitmap types. LTO labelling barcode. And many bugfixes... -- Robin Becker From george.sakkis at gmail.com Sun Sep 28 19:45:37 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 28 Sep 2008 16:45:37 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> On Sep 28, 2:29?pm, process wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. That's not a bug, it's a feature ;-) > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? As Terry Reedy wrote, partly history and partly practicality. There's no philosophical reason why we write "len(x)" (generic builtin), "x.append(1)" (method) or "del x[i]" (statement). The latter in particular is IMHO a design wart; there's no reason for not writing it as "x.delete(i)". George From cbabcock at kolonelpanic.org Fri Sep 5 19:18:33 2008 From: cbabcock at kolonelpanic.org (Chris Babcock) Date: Fri, 5 Sep 2008 16:18:33 -0700 Subject: Make Games References: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> Message-ID: <20080905161833.2d3b15b0@mail.asciiking.com> > I want to learn Python so I can make simple games. What are some good > books that'll help me do this? I promise that I'm not posting this to be a 81+<#: http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Daps&field-keywords=python+game Chris From david_v_wright at yahoo.com Fri Sep 5 03:21:34 2008 From: david_v_wright at yahoo.com (david wright) Date: Fri, 5 Sep 2008 00:21:34 -0700 (PDT) Subject: Creating directories In-Reply-To: <638982.16149.qm@web7902.mail.in.yahoo.com> Message-ID: <334015.16112.qm@web31807.mail.mud.yahoo.com> --- On Fri, 9/5/08, srinivasan srinivas wrote: > From: srinivasan srinivas > Subject: Creating directories > To: python-list at python.org > Date: Friday, September 5, 2008, 1:44 AM > Can someone tell me is there any module available to create > directories?? > > I tried os, tempfile. > I was facing some issues with os.mkdir(). The mode setting > was not proper with this method. > > I created the directory 'stdin' with '0700' > mode using os.mkdir() method. > $> ls -alR stdin/ > stdin/: > total 12 > drwx--S--- 2 munisams munisams 4096 Sep 3 02:00 . > What is that 'S' in the group permission field?? > this appears to be working, what where you expecting? "An upper case "S" means there is no executable permission, but the set group id function is active- that is, a file in this directory will belong to the same group id as the directory itself." If the parent directory has the set group id set, the child will as well. i.e. dwright at debian:~$ cd /tmp/ dwright at debian:/tmp$ mkdir test dwright at debian:/tmp$ ls -ld test drwxr-xr-x 2 dwright dwright 1024 2008-09-04 05:19 test dwright at debian:/tmp$ ls -la test drws------ 2 dwright dwright 1024 2008-09-04 05:19 . drwxrwxrwt 13 root root 3072 2008-09-04 05:19 .. dwright at debian:/tmp$ chmod 2700 test dwright at debian:/tmp$ ls -la test total 4 drwx--S--- 2 dwright dwright 1024 2008-09-04 05:19 . drwxrwxrwt 13 root root 3072 2008-09-04 05:19 .. dwright at debian:~$ python Python 2.4.4 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.mkdir('/tmp/test/TEST', 0700) dwright at debian:/tmp$ ls -la test total 5 drwx--S--- 3 dwright dwright 1024 2008-09-04 05:20 . drwxrwxrwt 13 root root 3072 2008-09-04 05:19 .. drwx--S--- 2 dwright dwright 1024 2008-09-04 05:20 TEST dwright at debian:/tmp$ ls -la test/TEST total 2 drwx--S--- 2 dwright dwright 1024 2008-09-04 05:20 . drwx--S--- 3 dwright dwright 1024 2008-09-04 05:20 .. +David From tjreedy at udel.edu Wed Sep 24 13:18:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2008 13:18:40 -0400 Subject: Comparing float and decimal In-Reply-To: References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: Mark Dickinson wrote: > On Sep 23, 7:31 pm, Terry Reedy wrote: >> Decimal is something of an anomaly in Python because it was written to >> exactly follow an external standard, with no concessions to what would >> be sensible for Python. It is possible that that standard mandates that >> Decimals not compare to floats. > > I don't think the standard says anything about interactions between > Decimals and floats. If there is not now, there could be in the future, and the decimal authors are committed to follow the standard wherever it goes. Therefore, the safe course, to avoid possible future deprecations due to doing too much, is to only do what is mandated. > But there's certainly been a feeling amongst at > least some of the developers that the job of Python's decimal module > is to implement the standard and no more, and that extensions to its > functionality belong elsewhere. For the reason just stated. A slightly different take is this. The reason for following the standard is so that decimal code in Python is exact interconversion both from and to decimal code in other languages. (And one reason for *that* is that one purpose of the standard is to reliably implement legal and contractual standards for financial calculations.) Using extensions in Python could break/deprecate code translated away from Python. > Regarding equality, there's at least one technical issue: the > requirement > that objects that compare equal hash equal. How do you come up with > efficient hash operations for integers, floats, Decimals and Fractions > that satisfy this requirement? For integral values, this is no problem. >>> hash(1) == hash(1.0) == hash(decimal.Decimal(1)) == hash(fractions.Fraction(1)) == 1 True > For other arithmetic operations: should the sum of a float and a > Decimal produce a Decimal or a float? Why? It's not at all clear to me that > either of these types is 'higher up' the numerical tower than the > other. Floats and fractions have the same issue. Fractions are converted to floats. I can think of two reasons: float operations are faster; floats are my typically thought of as inexact and since the result is likely to be inexact (rounded), float is the more appropriate type to express that. Anyone who disagrees with the choice for their application can explicitly convert the float to a fraction. Decimals can also be converted to floats (they also have a __float__ method). But unlike fractions, the conversion must be explicit, using float(decimal), instead of implicit, as with ints and fractions. Someone *could* write a PyDecimal wrapper that would do implicit conversion and thereby more completely integrate decimals with other Python numbers, but I doubt that saving transitivity of equality will be sufficient motivation ;-). Terry Jan Reedy From a at nospam.org Mon Sep 15 16:24:39 2008 From: a at nospam.org (Armin) Date: Mon, 15 Sep 2008 22:24:39 +0200 Subject: append on lists Message-ID: Hi, just a dumb question. Let a = [1,2,3,4,5] Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? --Armin From annathorns at googlemail.com Mon Sep 22 12:26:05 2008 From: annathorns at googlemail.com (annathorns at googlemail.com) Date: Mon, 22 Sep 2008 09:26:05 -0700 (PDT) Subject: Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS Message-ID: <0d7e53af-fa03-4ecc-8bcc-0393d1f7ab6d@v13g2000pro.googlegroups.com> Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com From adykes at panix.com Fri Sep 12 14:33:53 2008 From: adykes at panix.com (Al Dykes) Date: 12 Sep 2008 14:33:53 -0400 Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: In article <1bs69ogq6nspt.136i7kvcux142$.dlg at 40tude.net>, Alan Franzoni wrote: >zamil was kind enough to say: > >[cut] > >If your needs are very basic, you can stick with the tk module that comes >with python. It's not really feature-packed, but it's maintained and pretty >cross-platform. OK, what are my choices for an IDE/GUI development tool that runs on XP? Thanks -- Al Dykes News is something someone wants to suppress, everything else is advertising. - Lord Northcliffe, publisher of the Daily Mail From prologic at shortcircuit.net.au Sun Sep 7 18:42:06 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 08:42:06 +1000 Subject: Updating python dictionary In-Reply-To: References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: On Mon, Sep 8, 2008 at 8:37 AM, John Machin wrote: > Is this homework? I hope it's not - or I'll be quite annoyed :) > There seems to be an implicit assumption in the answers so far that > your mapping is a 1:1 mapping of all possible input keys. > > If it doesn't include all possible input keys, answers will crash with > a KeyError. If there are any many:1 elements in the mapping (for > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > in some checks for this. You are quite right! But then he/she didn't ask for this right ? :) cheers James -- -- -- "Problems are solved by method" From stef.mientki at gmail.com Tue Sep 30 15:06:07 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 21:06:07 +0200 Subject: rlcompleter and wxPython, problems ... In-Reply-To: References: <48E0045A.3020402@gmail.com> Message-ID: <48E2789F.7090207@gmail.com> Gabriel Genellina wrote: > En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki > escribi?: > >> I'm trying to implement autocompletion into my editor. >> But I find some weird behavior, >> or at least I don't have the faintest idea why this behavior occures, >> and even more important how to solve it >> In the example below I try to autocomplete " wx.s" , which in my >> humble opinion should at least produce "wx.stc" (and some others ). > > wx is a package. Modules within the package are not, by default, > attributes of the package - unless they're imported in __init__.py or > your code imports them. > So the autocompleter is doing the right thing in what perspective ? the autocompleter is only meant to assist the program writer ;-) > - wx.stc does not exist until it is explicitely imported. I guess I've to study the package. For the moment I'll implement a user editable list of additions. But with your remarks I tried __all__ And now I wonder why rlcompleter is not simply using "wx.__all__", it than does gets all the items ? cheers, Stef From kirk at athena.daycos.com Wed Sep 24 12:42:03 2008 From: kirk at athena.daycos.com (Kirk Strauser) Date: Wed, 24 Sep 2008 11:42:03 -0500 Subject: More regex help References: Message-ID: <86k5d1qyw4.fsf@athena.daycos.com> At 2008-09-24T16:25:02Z, "Support Desk" writes: > I am working on a python webcrawler, that will extract all links from an > html page, and add them to a queue, The problem I am having is building > absolute links from relative links, as there are so many different types of > relative links. If I just append the relative links to the current url, some > websites will send it into a never-ending loop. >>> import urllib >>> urllib.basejoin('http://www.example.com/path/to/deep/page', '/foo') 'http://www.example.com/foo' >>> urllib.basejoin('http://www.example.com/path/to/deep/page', 'http://slashdot.org/foo') 'http://slashdot.org/foo' -- Kirk Strauser The Day Companies From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 11:05:42 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 17:05:42 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: Message-ID: <48cbf2b4$0$21231$426a74cc@news.free.fr> Marco Bizzarri a ?crit : > On Sat, Sep 13, 2008 at 4:11 PM, Fredrik Lundh wrote: >> Marco Bizzarri wrote: >> >>> class FolderInUse: >>> >>> def true_for(self, archivefolder): >>> return any([instance.forbid_to_close(archivefolder) for instance in >>> self.core.active_outgoing_registration_instances()]) >>> >>> Is this any better? The true_for name does not satisfy me a lot... >> well, "true_for" is indeed pretty inscrutable, but I'm not sure that would >> be the first thing I'd complain about in that verbose mess... > > "verbose mess". > > It is always frustrating when you do what you think is your best and > you read that. The effbot is sometimes a bit abrupt in his formulations, for sure !-) From david.trem at gmail.com Sun Sep 14 14:34:00 2008 From: david.trem at gmail.com (David Trem) Date: Sun, 14 Sep 2008 11:34:00 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <48BFB534.2080508@egenix.com> Message-ID: <0642a573-1aaa-4181-a574-3a4c1ede95e8@m73g2000hsh.googlegroups.com> On 10 sep, 20:36, Fred Pacquier wrote: > Todd Whiteman said : > > > Personally, I believe XULRunner has a lot to offer for Python GUI > > development, I'm currently finishing up some documentation steps to show > > off how to use it specifically for Python (I'll post it to this list > > when it's finished). > > That would be really nice ! > > I've long been curious about the potential of XUL+Python, but put off by > the lack of leads to follow up, and not having time to do the digging > myself... > > TIA, > fp I will also like to see such documentation as soon as possible. To me, XUL+python really looks like what could be my prefered solution for multiplatform GUI for my python program. I'm really impatient and hope a strong and motivated community could set up arrond such XUL+python project. All the best, David From recombinant at hotmail.com Tue Sep 9 18:16:54 2008 From: recombinant at hotmail.com (Stephen D Evans) Date: Tue, 9 Sep 2008 23:16:54 +0100 Subject: Wx Python - Code Structure & Event Handling References: Message-ID: <48c6f5d9$0$2923$fa0fcedb@news.zen.co.uk> Lee, have you considered using the Model-View-Presenter pattern? There is a nice example on the wxPython wiki: http://wiki.wxpython.org/ModelViewPresenter This scales well to complex GUIs. Grasping the concept and writing the initial code is the difficult part. Code is then much easier to develop and maintain. There is also the Model-View-Controller pattern. Discussions about both of these patterns can be found on the wxPython wiki and wxPython list archives. For further simplification/maintainability I would recommend using XRC resources to create your widget hierarchies where possible. My preference is to use XRCed to generate python code with the resources embedded. Again consult the wxPython wiki, wxPython list archives - plus the wxPython DEMO (under Window Layout->XMLResource) Stephen wrote in message news:b502b8cf-ba28-4831-a2b0-647933a85e77 at m73g2000hsh.googlegroups.com... > Hi, > > I have just started writing a GUI using wxpython after finding a > limitation using Tkinter. I have read most tutorials on wxpython and > slowly becoming accustomed considering I started with the latter GUI > tool first! > I must quote first that I am a novice user of python so the issue(s) I > have may seem very obvious but please be patient with me! > > I have noticed that all the wxpython references I used for creating my > application(s) "cram" all the code in the frame subclass. This is > fine when you consider small applications but what about when they > grow into very complex applications? This creates my first question : > Where is it possible to find information on wxpython code practise/ > structure when considering complex larger Gui's? > > Without any reference I decided to attempt my owm method by breaking > up the top level panels in my frame as individiual class objects. and > then construct the widgets for the panels within the respective > classes. This led to my second problem, how do I use and event in one > Panel to cause an effect in the other Panel ? For example, if I have > button in one Panel and wish to change the text of a label in the > other Panel, what is the best way to do this? Should I break the code > into modules instead? > > Of course, you may explain that the way I have approached this is > completely wrong, if so please tell me, I really want to get the basic > structure right before I start making the code more complex. > > I look forward to your help > > ------------------------------------------------------------------------------------------------------------------------------------- > > I have listed some code below to help explain what concept I wish to > achieve, > > import wx > > class Frame(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, > title="Application",size=(400,400)) > Panel1 = wx.Panel(self, -1,size=(200,200)) > Panel2 = wx.Panel(self, -1,size=(200,200)) > Sizer = wx.FlexGridSizer(2,2,5,5) > Sizer.Add(Panel1) > Sizer.Add(Panel2) > self.SetSizerAndFit(Sizer) > Util1 = Utils1(Panel1) > Util2 = Utils2(Panel2) > > class Utils1(): > def __init__(self, Panel): > button = wx.Button(Panel,-1, "Button 1") > Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) > self.Label = wx.StaticText(Panel,-1, "Handler to me", > name="Lab1") > Sizer = wx.BoxSizer(wx.VERTICAL) > Sizer.Add(button) > Sizer.Add(self.Label) > Panel.SetSizerAndFit(Sizer) > > def OnClick(self, Evt): > self.Label.SetLabel("you changed me") > > class Utils2(): > def __init__(self, Panel): > self.button = wx.Button(Panel,-1, "Button 2") > Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) > > def OnClick(self, Evt): > """ what is the easiest & accepted Method of changing the text > in > a different class instance?""" > pass > #???.SetLabel("you changed me") > > app = wx.PySimpleApp() > frame = Frame() > frame.Show() > app.MainLoop() From ken at seehart.com Tue Sep 30 06:55:32 2008 From: ken at seehart.com (Ken Seehart) Date: Tue, 30 Sep 2008 03:55:32 -0700 Subject: Weirdness comparing strings In-Reply-To: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> References: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> Message-ID: <48E205A4.3020003@seehart.com> Instance comparison is not necessarily the same as string comparison. Neither __str__ nor __repr__ are implicitly used at all for comparison. In fact, by default a pair of instances are not equal unless they are the same object. To define comparison to mean something, you need to define __cmp__ or __eq__. Trivial example of default comparison: >>> class C: ... pass ... >>> c = C() >>> d = C() >>> c==d False >>> c==c True See http://docs.python.org/ref/customization.html for more details. Ken Mr.SpOOn wrote: > Hi, > I have this piece of code: > > class Note(): > ... > ... > def has_the_same_name(self, note): > return self == note > > def __str__(self): > return self.note_name + accidentals[self.accidentals] > > __repr__ = __str__ > > if __name__ == '__main__': > n = Note('B') > n2 = Note('B') > print n > print n2 > print n.has_the_same_name(n2) > > I'd expect to get "True", because their string representation is > actually the same, instead the output is: > > B > B > False > > I think I'm missing something stupid. Where am I wrong? > -- > http://mail.python.org/mailman/listinfo/python-list > > From maebert at uos.de Mon Sep 1 03:38:42 2008 From: maebert at uos.de (Manuel Ebert) Date: Mon, 1 Sep 2008 09:38:42 +0200 Subject: Command lime code In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Okay, I'll take I wild guess: By "command lime code" you did not refer to the algorithmic domination of citrus fruit, but rather to that window with the tiny blinking cursor and loads of text in white on black. Also by 'chdir' you probably mean the MS DOS equivalent to UNIX 'cd' (which AFAIK also works on MS DOS). So Googling for "MS DOS Commands" might be a good idea and yield, amongst others, this result: http://en.wikipedia.org/wiki/List_of_DOS_commands On Aug 29, 2008, at 6:20 PM, London at ezauza.com wrote: > I am new to python. > I did find a page which listed some code - IE "chdir" type code but > can not find it again. > Can you supply an address? > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIu5wCcZ70OCIgLecRArTEAJ42+XoaVOgOnk+o/f3shWSp0Cq3CQCfRstB 8bKzY9FBeZmGzKyzAg7xEwk= =3xLN -----END PGP SIGNATURE----- From lists at cheimes.de Thu Sep 11 18:10:28 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Sep 2008 00:10:28 +0200 Subject: Accessing __slots__ from C In-Reply-To: References: Message-ID: Chris wrote: > Ok, thanks for the confirmation. We'd been hoping to avoid creating > such a struct... Don't worry, a C extension with its own struct isn't hard to write. Your C code can access the member variables w/o using any Python API. You'll get the full speed of C. :] Christian From larry.bates at vitalEsafe.com Mon Sep 15 14:07:24 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Mon, 15 Sep 2008 13:07:24 -0500 Subject: Client server implementation In-Reply-To: References: Message-ID: Babloo wrote: > Hi everyone, > > i wanted to implement a client- server connection > and transfer a file over the network. i was able to implement a normal > set up where in i was able to send chat messages and small chunks of > data. > I want to implement the file transfer with out using the FTP library > available in python . > > So can anyone suggest a piece of code by which i can > do that. > > Thanks > Pruthvi What Client OS? What Server OS? On LAN or Internet? You need to give is some information to help you. -Larry From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 2 10:04:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 02 Sep 2008 16:04:34 +0200 Subject: What is module initialization? In-Reply-To: References: Message-ID: <48bd4799$0$17215$426a74cc@news.free.fr> dudeja.rajat at gmail.com a ?crit : > Hi, > > I found on the net that there is something called module > initialization. The Python C api has a module init function for C-coded modules. There's no need for such a thing in pure Python modules since all the top-level code is executed when the module is loaded (as a main script or the first time the module is imported). > Unfortunately, there is not much information for this. > However, small the information I found module initialization can be of > use to me in my project. > > I'm currently messing with a problem where I'm keeping my global > variables ( or symbols) in a module and the other mdoules in the > project acess these global variables. remember that there's no such thing as a truely global namespace in Python. "global" really means "module level". > However, there is one case when a module updates one such global > variable While this is technically legal, you should restrain yourself from doing such a thing, unless you *really* know what you're doing and why. > but the variable is not getting updated in the module > containing global symbols ( variables). I suspect you didn't use a qualified name when importing. You have to do it this way : # myglobals.py: answer = 42 # question.py import myglobals myglobals.answer = "WTF ?" > So, I thought of using this module initialization where I will > intialize the module only once to update that variable. Ans in the > rest of the program where ever this module is imported I shall be able > to easily access the update value of the variable. > > Could some one provide me a sample code of module intialization? All statements at the top-level of a module are executed when the module is loaded. That's all it takes wrt/ module initialization. > And > how can I ensure that module initialization is done only once? Unless you're doing weird things with __import__ or the imp module, you shouldn't have to worry. import do two things : locate, load *and cache* the module *if* it isn't already in cache, and bind names into the importing namespace. From sjmachin at lexicon.net Wed Sep 3 19:28:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 3 Sep 2008 16:28:54 -0700 (PDT) Subject: Writing Unicode to database using ODBC References: Message-ID: <5738987c-633b-42b7-a803-d35040051f7e@1g2000pre.googlegroups.com> On Sep 4, 3:11?am, Mudcat wrote: [snip] > However, now that I've got all that working I'd like to simply take > the unicode data from the xml parser and then pass it directly into > the database (which is currently set up for unicode data). I've run What database? What does "set up for unicode data" mean? If you are using MS SQL Server, are your text columns defined to be varchar or nvarchar or something else? > into problems and just can't figure why this isn't working. > > The breakdown is occurring when I try to execute the db query: > > ? ? ? ? ? cur.execute( query ) > > Fairly straightforward. I get the following error: > > ? File "atp_alt.py", line 273, in dbWrite > ? ? cur.execute( query ) > UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in > position 3 > 79: ordinal not in range(128) > > I've verified that query is of type unicode by checking the type a > statement or two earlier (output: ). > So then I thought maybe the odbc execute just can't handle unicode > data. It appears to be expecting a str object, not a unicode object. > But when I do the following command: > > ? ? ? ? ? query = query.encode('utf-8') > > It actually works. So apparently execute can handle unicode data. "not crashing" != "works" > The > problem now is that basically the data has been encoded twice and is > in the wrong format when I pull it from the database: No, your utf8 string has been DEcoded using some strange encoding. > > >>> a > > u'+CMGL: (\xe2\u20ac\u0153REC UNREAD\xe2\u20ac\x9d,\xe2\u20ac\x9dREC > READ\xe2\u20ac\x9d,\xe2\u20ac\x9dSTO UNSENT\xe2\u20ac\x9d,\xe2\u20ac > \x9dSTO SENT\xe2\u20ac\x9d,\xe2\u20ac\x9dALL\xe2\u20ac\x9d) OK'>>> print a > > +CMGL: (???REC UNREAD?? ,?? REC READ?? ,?? STO UNSENT?? ,?? STO SENT? > ? ,?? ALL?? ) OK It would help very much if you showed the repr() of your input unicode text. Observation: the first bunch of rubbish output (\xe2\u20ac\u0153) differs from all the others (\xe2\u20ac\x9d). > > The non-alpha characters should be double-quotes. What "double-quotes" character(s)? Unicode has several: U+0022 (unoriented), U+201C (left), U+201D (right), plus more exotic ones. > It works correctly > if I copy/paste into the editor: > > >>> d > u'\u201cREC' > >>> print d > ?REC > >>> d.encode('utf-8') > '\xe2\x80\x9cREC' More observations: >>> u'\u201c'.encode('utf8') '\xe2\x80\x9c' >>> u'\u201c'.encode('utf8').decode('cp1252') u'\xe2\u20ac\u0153' Aha! The first load of rubbish! However: >>> u'\u201d'.encode('utf8') '\xe2\x80\x9d' >>> u'\u201d'.encode('utf8').decode('cp1252') Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\encodings\cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2: character maps to >>> Hmmm, try the ferschlugginer mcbs encoding: >>> u'\u201d'.encode('utf8').decode('mbcs') u'\xe2\u20ac\x9d' >>> u'\u201c'.encode('utf8').decode('mbcs') u'\xe2\u20ac\u0153' >>> So, if you must persist with the odbc module, either encode your unicode text with mbcs, not utf8, or find out how to "set up for unicode data" so that utf8 is the default. You may like to consider using pyODBC or mxODBC instead of odbc. HTH, John From martin at v.loewis.de Sun Sep 21 04:54:56 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Sep 2008 10:54:56 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> Message-ID: <48D60BE0.10106@v.loewis.de> Christian Heimes wrote: > Kay Schluehr wrote: >> Actually it is simply wrong in the mentioned case [...] > > It's not wrong. You have found a simple optimization. Lot's of compilers > for lots of languages optimize code by code folding. I don't think he meant that Python is wrong somehow, but that the OO babble of what happens for 2+2 is wrong. The babble said that, when the code is executed, an __add__ message is sent to the 2 object, with another 2 object as the parameter. That statement is incorrect: no message is sent at all, but the result is available even before the program starts. FWIW, "2+2" is not a good case for OO in Smalltalk, either. In a typical implementation, SmallInteger is not a real class, in the sense that 2 is not a real object. Instead, it lives in a tagged pointer, i.e. it has no identity. Regards, Martin From asnast at gmail.com Sat Sep 20 12:16:36 2008 From: asnast at gmail.com (Alex Snast) Date: Sat, 20 Sep 2008 09:16:36 -0700 (PDT) Subject: How to make a reverse for loop in python? Message-ID: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Hello I'm new to python and i can't figure out how to write a reverse for loop in python e.g. the python equivalent to the c++ loop for (i = 10; i >= 0; --i) From castironpi at gmail.com Sun Sep 28 20:31:20 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 17:31:20 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> <9f263cc0-508a-4597-94fc-365f6b691d10@i76g2000hsf.googlegroups.com> Message-ID: <5146813d-b203-49c8-8807-217e959ba5ce@e53g2000hsa.googlegroups.com> On Sep 28, 4:41?pm, "Tim Rowe" wrote: > 2008/9/28 Aaron Castironpi Brady : > > > Before I tried wxFormBuilder, I imagined that C# would be vastly > > faster to develop than Python, for anything requiring any non-trivial > > graphical interface. ?I've done extensive VB, so I can attest to that > > personally. ?It is not. > > I'm confused about where VB comes in -- I find VB just *slightly* > harder than INTERCAL. C# I find fairly easy. > > > You can come up with examples that favor either. ?But the opposite of > > statistical is anecdotal. ?Sorry again. > > Yes, it's anecdotal, but development time isn't just about how fast > the program is to type (otherwise, why aren't we all using APL?) > > > The last time I 'checked in' at your post, your claim was "an hour or > > so" vs. "ages". ?Hence my responses. ?You could probably sneak by by > > claiming a factor of *two*, but if you were exaggerating, please say > > so at any time. > > Ok. I was exaggerating when I said that VB was harder than INTERCAL. > It's marginally easier. > > As for the program I was working on, I worked for over a day on it in > Python, and did it in about an hour in C#, although in fairness I > didn't forget all the thinking I'd done on the previous day. I have a > lot more Python experience than C# experience, but don't claim to be a > guru in either. And no, I don't work two hour days (unfortunately). I > have indicated that the GUI wasn't the only issue; in C# it was just > easy in that case to find all the library bits I needed to in order to > accomplish the task. It isn't always so. > > > on this, that it's "pretty generally applicable" > > I'm with you on that. > > > I do not believe that C# is pretty generally applicable. > > I agree on that, but *only* because it's a proprietary language with > imperfect support once you move away from the .net platform. It's a > generally applicable language to .net, but .net is not a general > platform. > > > fact, outside of my VB, COM, and MFC experience, you could say I have > > no clue. ?Very tongue in cheek.) > > If you see C# as being in any way related to VB, it's no wonder you're > down on it! > > > Python has a lot of things C# doesn't. ?Can we agree on that? > > And C# has things that Python doesn't (such as static typing). Can we > agree on that, too? > > -- > Tim Rowe Maybe too much of my personal life is affecting my judgment of C#. You mention tools (that are doing the work for you) and I think incompatibility. Maybe that part is just because I feel like tools are like 'excuses'. And maybe that part is just because... awkward. I'm going to have to bow out of the dispute, sorry, because I am not a person that knows both of them. (How you decide who knows a language isn't exactly clear, by the way. It's been stated, for example, that I don't know Python, as well as that I don't know English.) You said C# = 1 hour, Python = ages. I said I could see that if it came to developing a GUI with a draw-on tool in one and not in the other. (Write that C# GUI spec by hand or position your controls from scratch.) You could make a case that you can get bad habits from developing in a tightly-coupled ("tightly-integrated") framework, as you suggested C# was. I would agree to it. I do not find that the Python library is particularly lacking, and the VB6 library was. If you're referring to documentation, though, I really like the win32 API docs. They're precise and thorough. The Python docs leave some stuff unsaid; there's a lot of stuff you can do in Python that people have to tell you or you have to discover on your own. Which one are the C# docs like? Not to reopen the wound, or rather to reopen it patiently: I classify 'static-typing' as handcuffs. C# has handcuffs and lots of kinds of them. "But static-typing lets you do ." ? Other than that, I don't know of any examples, from which I won't infer that there aren't any. (That was -won't- infer.) "Call," I guess; I'll bite. What? If you're referring to library depth, there's a lot of stuff that probably classifies as wheel reinvention that shouldn't necessarily go in the library. There was a good example today. 'Return a string of 5 random digits.' You could put that in the library, and call it 'RandomDigitString( int length )'. Doing it by hand only takes one line though: '"%05i"%random.randint(0,99999)'. Does it belong in the library? Otherwise you're technically reinventing the wheel, right? If you want to talk about your application, the day-to-hour ratio example, please do. From ken at jots.org Mon Sep 29 22:04:12 2008 From: ken at jots.org (Ken D'Ambrosio) Date: Mon, 29 Sep 2008 22:04:12 -0400 Subject: Newbie question... Message-ID: First, apologies for such a newbie question; if there's a better forum (I've poked around, some) feel free to point it out to me. Anyway, a mere 25-odd years after first hearing about OOP, I've finally decided to go to it, by way of Python. But this puzzles me: import commands free = commands.getoutput("free") for line in free: print line, Gives: t o t a l u s e d f r e e s h a r e d b u f f e r s c a c h e d M e m : 5 1 5 9 9 2 4 6 0 4 5 2 5 5 5 4 0 0 7 7 5 1 6 9 1 8 8 4 - / + b u f f e r s / c a c h e : 2 9 1 0 5 2 2 2 4 9 4 0 Why are there spaces between everything? And how do I keep it from happening? *confused* Thanks much, -Ken ** Posted from http://www.teranews.com ** From washakie at gmail.com Tue Sep 2 19:16:56 2008 From: washakie at gmail.com (John [H2O]) Date: Tue, 2 Sep 2008 16:16:56 -0700 (PDT) Subject: MoinMoin: trouble after install Message-ID: <19280220.post@talk.nabble.com> I've installed MoinMoin easily enough, but i have two problems now. 1) Some pages, namely the initial FrontPage, fail to load completely.... 2) It seems after logging in, if I navigate away from the login page, I get logged out immediately. I'm runing 1.13 on Fedora 9 with Apache 2 and ReWriteRules... all seemed well initially... Thanks! -- View this message in context: http://www.nabble.com/MoinMoin%3A-trouble-after-install-tp19280220p19280220.html Sent from the Python - python-list mailing list archive at Nabble.com. From gandalf at shopzeus.com Mon Sep 8 04:51:45 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Sep 2008 10:51:45 +0200 Subject: universal unicode font for reportlab Message-ID: <48C4E7A1.2000504@shopzeus.com> I need to create multi lingual invoices from reportlab. I think it is possible to use UTF 8 strings but there is a problem with the font. I could not find any free TTF font that can do latin1, latin2, arabic, chinese and other languages at the same time. Is there a single font that is able to handle these languages? (Most of our invoices will be for EN, FR, DE, HU, SK, CZ, RO but some of them needs to be in Chinese.) Thanks, Laszlo From pythonnutter at gmail.com Thu Sep 18 05:22:19 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Thu, 18 Sep 2008 19:22:19 +1000 Subject: Python for the iPhone? In-Reply-To: <18640.54221.603481.301379@montanaro-dyndns-org.local> References: <18640.54221.603481.301379@montanaro-dyndns-org.local> Message-ID: Yes it does involve Jailbreaking. Python GCC Java and Ruby are all available to run on the iPhone after you Jailbreak it. Just run the Cydia appliacation (jailbreak's AppStore) to install anything you want. For me I have not installed Python (yet). Jailbreak was only to tether iPhone to my Macbook since I've moved house and living out of a hotel until move into my next house. I would never have jailbroken if Apple did not killswitch the NetShare application. Tethering is 100% legal in my country and Apple just lost me in only 2 weeks of iPhone ownership. Cydia -> OpenSSH. Then I just reverse ssh socks proxied into my iPhone and shazam. Internet access here I am. (Downloading all my Mac updates as I type). Cheers, PN On 17/09/2008, skip at pobox.com wrote: > Anybody tried this port of Python to the iPhone? > > http://www.modmyi.com/nativeapps/python-v251/ > http://iphone.natetrue.com/ > > Hasn't been updated since July 2007. Maybe just a proof-of-concept? I'm > guessing it involves jailbreaking the phone. > > Skip > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Sun Sep 28 16:10:03 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Sep 2008 16:10:03 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> References: <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> <48DF63B2.2020408@wildenhain.de> <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> Message-ID: Michael Mabin wrote: > Tino, dude, I'm afraid I lied about my previous post being the last > word. There are some things you said here that must be addressed. Good grief, is there no utterance so inconsequential that you will walk away from it without yet another round of retaliation? I believe that all people were trying to convey is: 1. There are some data patterns that cannot be directly incorporated into SQL statements without additional processing, regardless of whether the "intention" of the data's originator is malevolent. A good example is a string value containing an apostrophe, which in most SQL implementations you can escape by preceding the apostrophe with another apostrophe. 2. SQL drivers in Python are written so that no matter what the values of the data may be, and no matter which backend they implement, data may safely be passed as a tuple to a parameterized statement without such cleansing because the drivers are written to ensure "dangerous" values are appropriately handled. Having said all that, if you are positive none of your string data contains apostrophes you are, of course, free to build SQL statements yourself - though doing so will on some systems lose you the speed advantages offered by "prepared statements". Similarly, if you are *not* positive of the quality of your data you are free to do the escaping in your logic rather than using parameterized queries. This could be called "buying a dog and barking yourself". regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From john.ford at colorado.edu Wed Sep 24 23:30:00 2008 From: john.ford at colorado.edu (john.ford at colorado.edu) Date: Wed, 24 Sep 2008 20:30:00 -0700 (PDT) Subject: How to parse a string completely into a list Message-ID: I want to take a long alpha-numeric string with \n and white-space and place ALL elements of the string (even individual parts of a long white-space) into separate list elements. The most common way I've seen this performed is with the split() function, however I don't believe that it has the power to do what I am looking for. Any suggestions? thanks From Astley.lejasper at gmail.com Fri Sep 12 06:54:52 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Fri, 12 Sep 2008 03:54:52 -0700 (PDT) Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <48ca4780$0$15455$426a74cc@news.free.fr> Message-ID: On 12 Sep, 12:44, Bruno Desthuilliers wrote: > Astley Le Jasper a ?crit : > > > I'm still learning python and would like to know what's a good way of > > organizing code. > > > I am writing some scripts to scrape a number of different website that > > hold similar information and then collating it all together. Obviously > > each site needs to be handled differently, but once the information is > > collected then more generic functions can be used. > > > Is it best to have it all in one script or split it into per site > > scripts that can then be called by a manager script? > > If everything is > > in one script would you have per site functions to extract the data or > > generic function that contain vary slightly depending on the site, > > As far as I'm concerned, I'd choose the first solution. Decoupling > what's varying (here, site-specific stuff) from "invariants" is so far > the best way I know to keep complexity manageable. > > > for > > example > > > import firstSiteScript > > import secondSiteScript > > > firstsitedata = firstSiteScript.getData('search_str) > > secondsitedata = secondSiteScript.getData('search_str) > > etc etc > > Even better : > > - put generic functions in a 'generic' module > - put all site-specific stuff each in it's own module in a specific > 'site_scripts' directory > - in your 'main' script, scan the site_scripts directory to loop over > site-specific modules, import them and run them (look for the __import__ > function). > > This is kind of a Q&D lightweight plugin system, that avoids having to > hard-code imports and calls in the main script, so you just have to > add/remove site-specific script to/from the site_scripts directory . > > Also, imported modules are not recompiled on each import - only when > they change - while the 'main' script get recompiled on each invocation. > > (snip) > > > OR > > > def getdata(search_str, website): > > ? if website == 'firstsite': > > ? ? .... > > ? elif website =='secondsite': > > This one is IMHO the very worst thing to do. > > My 2 cents... Excellent, thanks for that. From skip at pobox.com Tue Sep 9 07:12:23 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 Sep 2008 06:12:23 -0500 Subject: biopython In-Reply-To: References: Message-ID: <18630.23063.827209.21083@montanaro-dyndns-org.local> >>> from Bio import Entrez Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name Entrez Can you import Bio, e.g.: import Bio ? If not, check to see where it's installed and make sure the directory containing Bio (or Bio.py) is in sys.path, either by setting the PYTHONPATH environment variable before running Python or adding a Bio.pth file to a directory which is in sys.path so it can be found. http://docs.python.org/lib/module-site.html http://docs.python.org/tut/node8.html Skip From sturlamolden at yahoo.no Wed Sep 24 16:55:13 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 13:55:13 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <6f9561d3-1239-4799-86db-082d0463189e@59g2000hsb.googlegroups.com> On Sep 24, 9:11?pm, bearophileH... at lycos.com wrote: > In the meantime where I > live lot of people will keep using C# instead of Python and CLisp, > natural selection at work indeed. Please explain to me what Linq can do that Python does not. Put you emphasis on why this can't be done with a library, and thus will require addition of new syntax to the language. From spammaster.10.webmaster at spamgourmet.com Sun Sep 14 11:14:52 2008 From: spammaster.10.webmaster at spamgourmet.com (spammaster.10.webmaster at spamgourmet.com) Date: Sun, 14 Sep 2008 08:14:52 -0700 (PDT) Subject: PyMarshal Commands crash on Windows References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> Message-ID: Hi! Please remember, that the script crashs on Line PyMarshal_WriteObjectToFile. :-( From kyosohma at gmail.com Thu Sep 25 09:11:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 25 Sep 2008 06:11:21 -0700 (PDT) Subject: urllib error on urlopen References: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> <564ecf05-4be1-41b3-ab49-c3f17b57ad3b@w7g2000hsa.googlegroups.com> Message-ID: <4176b842-d027-4303-90ea-1ef8562987bd@m3g2000hsc.googlegroups.com> On Sep 24, 7:08?pm, Michael Palmer wrote: > On Sep 24, 11:46 am, Mike Driscoll wrote: > > > > > Hi, > > > I have been using the following code for over a year in one of my > > programs: > > > f = urllib2.urlopen('https://www.companywebsite.com/somestring') > > > It worked great until the middle of the afternoon yesterday. Now I get > > the following traceback: > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? response = urllib2.urlopen(req).read().strip() > > ? File "c:\python25\lib\urllib2.py", line 124, in urlopen > > ? ? return _opener.open(url, data) > > ? File "c:\python25\lib\urllib2.py", line 381, in open > > ? ? response = self._open(req, data) > > ? File "c:\python25\lib\urllib2.py", line 399, in _open > > ? ? '_open', req) > > ? File "c:\python25\lib\urllib2.py", line 360, in _call_chain > > ? ? result = func(*args) > > ? File "c:\python25\lib\urllib2.py", line 1115, in https_open > > ? ? return self.do_open(httplib.HTTPSConnection, req) > > ? File "c:\python25\lib\urllib2.py", line 1082, in do_open > > ? ? raise URLError(err) > > URLError: > routines:SSL23_GET_SERVER_HELLO:unknown protocol')> > > > I tried my Google Fu on this error, but there's not much out there. I > > tried using a proxy in Python, but that returned the same traceback. > > If I copy the URL into my browser, it resolves correctly. Does anyone > > have any advice on how to troubleshoot this error? > > > I am using Python 2.5.2 on Windows XP. > > > Thanks, > > > Mike > > Could it just be a misconfiguration at the other end? Can you open > other https urls? This is really weird. Now it works this morning. I've spoken with our webmaster/system admin and he said he didn't change anything on his end. We're both befuddled. Sorry for the noise. Mike From bignose+hates-spam at benfinney.id.au Fri Sep 26 23:16:08 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 13:16:08 +1000 Subject: Build-in 'repr' function (was: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])?) References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: <87abduuvlz.fsf@benfinney.id.au> process writes: > ' '.join([`x * x` for x in range(1, 6)]) > > exactly what does this symbol do and what does it stand for? It's an obsolete, deprecated syntactic sugar for (what is now implemented as) the built-in 'repr' function. Instead, write the above as: ' '.join([repr(x * x) for x in range(1, 6)]) -- \ ?Killing the creator was the traditional method of patent | `\ protection? ?Terry Pratchett, _Small Gods_ | _o__) | Ben Finney From namekuseijin at gmail.com Tue Sep 23 14:02:30 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Tue, 23 Sep 2008 11:02:30 -0700 (PDT) Subject: Linq to Python References: Message-ID: <00245d29-de1b-4c5e-b5bf-a99fb7a3ce25@a70g2000hsh.googlegroups.com> On Sep 23, 2:07?pm, Jason Scheirer wrote: > On Sep 23, 7:48?am, hrishy wrote: > > > Hi > > > Will LINQ be ported to Python ? > > > regards > > Hrishy > > I think this question is more appropriate to ask on an IronPython > development list -- LINQ is pretty solidly intertwined with .Net, and > so you'll likely want to look at the .Net implementation of Python. But surely the idea behind it will eventually spread. It's really just comprehensions generalized over XML and relational datasets, a noble goal. Besides, it's main purpose for .NET was to bring functional programming to it. Python already has that, somewhat... From Richard_Martineau at xyratex.com Tue Sep 16 05:25:27 2008 From: Richard_Martineau at xyratex.com (Richard_Martineau at xyratex.com) Date: Tue, 16 Sep 2008 02:25:27 -0700 (PDT) Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows Message-ID: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Hello All I wonder if anyone can advise me or has done similar to the following? Basically I've downloaded the Python 2.5.2 source code that builds with Visual Studio 6.0. I've built Python for windows. This was easy (it even came with the pcbuild.dsw workspace file). Great! Now comes the troubled bit...I now look for similar source code for Python extensions Numpy and Scipy but the source code and directories are not all obvious. Looks like these are normally built via other compilers. However I need to do all my builds in VS 6.0. For Numpy (I haven't got as far as Scipy yet) I've organised the source code into the following projects and lumped them all into my new workspace numpy.dsw: dotblas fft lib linalg multiarray numarray random scalarmath sort umath I'm obviously not sure if this is correct. As you can see from above, I've re-arranged the source code directory named core into the following projects: dotblas sort multiarray scalarmath umath Unbelievably I am having some luck and nearly all the projects compile and link (untested though). I created the auto-generated files using the python scripts. Then I included the headers where necessary. However the remaining problems are: multiarray (wont compile) dotblas (wont link) dotblas seems to have missing dependencies on these: _cblas_sdot _cblas_ddot _cblas_cdotu_sub _cblas_zdotu_sub _cblas_cgemm _cblas_zgemm _cblas_sgemm _cblas_dgemm _cblas_cgemv _cblas_zgemv _cblas_sgemv _cblas_dgemv _cblas_caxpy _cblas_saxpy _cblas_zaxpy _cblas_daxpy _cblas_cdotc_sub _cblas_zdotc_sub Well that's a snapshot of where I am this morning. What I'm really after is some advice from anybody who has done similar. I'd really appreciate hearing from you. Thanks for your help and very happy to have joined this group Richard From fredrik at pythonware.com Sun Sep 21 05:35:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 11:35:04 +0200 Subject: Not fully OO ? In-Reply-To: <48D60BE0.10106@v.loewis.de> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <48D60BE0.10106@v.loewis.de> Message-ID: Martin v. L?wis wrote: > I don't think he meant that Python is wrong somehow, but that the OO > babble of what happens for 2+2 is wrong. The babble said that, when the > code is executed, an __add__ message is sent to the 2 object, with > another 2 object as the parameter. That statement is incorrect: no > message is sent at all, but the result is available even before the > program starts. On the other hand, the inability to distinguish between "as if" and "hah, I've looked under the covers" isn't necessarily a good trait for a programmer. If he bases his mental model on concrete implementation details of a production quality software product, he's bound to end up with a cargo-cultish understanding of fundamental issues. If he uses it to win arguments, people will flip his bozo bit pretty quickly. From robert.rawlins at thinkbluemedia.co.uk Thu Sep 18 08:47:54 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 18 Sep 2008 13:47:54 +0100 Subject: XML Processing In-Reply-To: <48D24638.9010601@timgolden.me.uk> References: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> <48D24638.9010601@timgolden.me.uk> Message-ID: <00ef01c9198c$c4bce780$4e36b680$@rawlins@thinkbluemedia.co.uk> > Some is going to kick themselves when they realise > that ElementTree *is* built in to Python 2.5 > > http://docs.python.org/whatsnew/modules.html#SECTION0001420000000000000000 Tim, Andrii, Thanks for the heads up on that! I hadn't noticed they're made it part of the platform modules, that's excellent news. In theory I should just be able to amend my import paths and we'll be good to go, no install external modules. Thanks for this, Robert From bdesth.quelquechose at free.quelquepart.fr Fri Sep 26 16:08:59 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 22:08:59 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> <48dc962a$0$2289$426a74cc@news.free.fr> Message-ID: <48dd5d46$0$26425$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 26 Sep 2008 09:58:39 +0200, Bruno Desthuilliers wrote: > >>> "Procedural" is the opposite of "functional", not "object-oriented". >> AFAIK, the "opposite" if functional is imperative, not procedural. But >> let's not waste too much time on terminology arguments... > > We're not wasting time on terminology arguments, we're wasting time on > definitional debates. > Point taken. But still a waste of time !-) From paulandersonusa at gmail.com Sun Sep 14 16:42:19 2008 From: paulandersonusa at gmail.com (primeq) Date: Sun, 14 Sep 2008 13:42:19 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> Message-ID: On Sep 11, 8:56?am, "carriere.jonat... at gmail.com" wrote: > Hello all; > > I wonder if there is a platform written in python. The equivalent of > the Netbeans platformhttp://platform.netbeans.org/in the Python > world. Do you know such a thing? > > Thanks a lot. > > Jonathan. Check out Eric (http://www.die-offenbachs.de/eric/) - it's not as solid as Netbeans (way lower funding, fewer developers by a large margin), but it works fine. Better still you have the source at your fingertips when you're using it - it's written in Python. Personally I have not had much success with the Windows version, but the Linux version works out of the box for me. From pfreixes at gmail.com Mon Sep 1 07:22:43 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Mon, 1 Sep 2008 13:22:43 +0200 Subject: Best way for add new path when embedding python into C Message-ID: <207312b70809010422v5df73412xfc5e768a1c735c82@mail.gmail.com> Hi list, I have a little question about whats' the best way for add - no replace - new path into python c embedding environment for this situation. I'm using PyObject_CallObject(pfunc, pArgs); for call one function of some module loaded with PyImport_Import function. PyImport_Import function search this module into system path list object. I read some examples about Py_GetPath and PySys_SetPath and i think some examples are wrong or can be misinterpreted. Py_GetPath make only a basic path, some sitautions are considred for make this path, for example read environment varialbes. PySys_SetPath overwrite all path list object. When Py_Initialitze it's called sys path object is generated with Py_GetPath content and a other directories added by site.py file pre processor. The best way for add new path before call PyImport_Import is adding new string item into sys path object ? Bye and thks to all -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 9 08:56:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 09:56:41 -0300 Subject: Long lines [was Re: __builtins__ magic behavior] References: <00d45042$0$20306$c3e8da3@news.astraweb.com> Message-ID: En Sun, 07 Sep 2008 19:30:07 -0300, Steven D'Aprano escribi?: > Gabriel, could I please ask you to configure your news-reader software or > editor to limit the length of each line of your posts to 70 characters > wide, as per the common standard for email and Usenet? Your lines are > significantly longer than that, including one single line which is 325 > characters wide. That forces a lot of backwards and forwards scrolling to > read your posts. Fixed, thanks for pointing it out. Opera wraps long lines automatically so I didn't notice the problem myself. I can't remember when, or why, I altered the setting (if *I* altered it at all!) -- Gabriel Genellina From clp at rebertia.com Tue Sep 30 12:30:44 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 30 Sep 2008 09:30:44 -0700 Subject: XMLRPC - C Client / Python Server In-Reply-To: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> References: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> Message-ID: <47c890dc0809300930o2229f2a0g7ae338fa8b4376e7@mail.gmail.com> On Tue, Sep 30, 2008 at 8:05 AM, wrote: > I have implemented a simple Python XMLRPC server and need to call it > from a C/C++ client. What is the simplest way to do this? I need to > pass numerical arrays from C/C++ to Python. If you just googled for "xmlrpc c", you would've found http://xmlrpc-c.sourceforge.net/ , which appears to be the best (and possibly only) option for this. Also, this isn't really Python-related if you think about it. Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > > Yours, Carl > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Sat Sep 20 06:14:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 12:14:33 +0200 Subject: Not fully OO ? In-Reply-To: <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: Kay Schluehr wrote: > Answer: if you want to define an entity it has to be defined inside a > class. If you want to access an entity you have to use the dot > operator. Therefore Java is OO but Python is not. you're satirising the quoted author's cargo-cultish view of object orientation, right? From mcohoon at gmail.com Mon Sep 15 17:25:53 2008 From: mcohoon at gmail.com (mpc) Date: Mon, 15 Sep 2008 14:25:53 -0700 (PDT) Subject: CGIHTTPServer webserver running php scripts Message-ID: <85ddfc4a-3dea-449e-9b68-c4271932de79@m44g2000hsc.googlegroups.com> hello, how does one run a PHP page with a python webserver? Lets say i have a simple python web server running /path/webserver.py #!/usr/bin/env python from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler serve = HTTPServer(("",8080),CGIHTTPRequestHandler) serve.serve_forever() Also lets say i am interested in hosting a simple.php in the cgi-bin directory. /path/cgi-bin/simple.php A simple php script. The webserver starts up and hosts html and python cgi's just fine but nothing will come up when we go to http://localhost:8080/cgi-bin/simple.php I get the following errors. with normal user localhost:path user$ python webserver.py localhost - - [15/Sep/2008 16:17:59] "GET /cgi-bin/example.php HTTP/ 1.1" 200 - Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/CGIHTTPServer.py", line 251, in run_cgi os.execve(scriptfile, args, os.environ) OSError: [Errno 8] Exec format error localhost - - [15/Sep/2008 16:17:59] CGI script exit status 0x7f00 localhost:path user$ sudo python webserver.py Password: localhost - - [15/Sep/2008 16:18:29] "GET /cgi-bin/example.php HTTP/ 1.1" 200 - Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/CGIHTTPServer.py", line 251, in run_cgi os.execve(scriptfile, args, os.environ) OSError: [Errno 13] Permission denied Is there something I can add to my python webserver so that it will properly run php files? From waldemar.osuch at gmail.com Wed Sep 10 15:44:03 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Wed, 10 Sep 2008 12:44:03 -0700 (PDT) Subject: Is there a SOAP module that can do this...? References: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> Message-ID: On Sep 10, 1:23?pm, thebjorn wrote: > I've been trying to use SOAPpy and ZSI (with and without the use of > wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic > server(?) in front of some enterprise java bean) and not having much > luck. ?I got them to send me an example of what the bytes on the wire > are supposed to look like (attached below), and I got it to "work" by > going lo-tech: > If you are willing to go low tech you can try http://effbot.org/downloads/#elementsoap But before you do that try: https://fedorahosted.org/suds It is actively maintained and holds a lot of promise. In my testing it knew how to connect to Sharepoint as well as WebLogic exposed services. Waldemar From grflanagan at gmail.com Thu Sep 18 06:31:45 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 18 Sep 2008 12:31:45 +0200 Subject: decorator and API In-Reply-To: References: Message-ID: Lee Harr wrote: > I have a class with certain methods from which I want to select > one at random, with weighting. > > The way I have done it is this .... > > > > import random > > def weight(value): > def set_weight(method): > method.weight = value > return method > return set_weight > > class A(object): > def actions(self): > 'return a list of possible actions' > > return [getattr(self, method) > for method in dir(self) > if method.startswith('action_')] > > def action(self): > 'Select a possible action using weighted choice' > > actions = self.actions() > weights = [method.weight for method in actions] > total = sum(weights) > > choice = random.randrange(total) > > while choice> weights[0]: > choice -= weights[0] > weights.pop(0) > actions.pop(0) > > return actions[0] > > > @weight(10) > def action_1(self): > print "A.action_1" > > @weight(20) > def action_2(self): > print "A.action_2" > > > a = A() > a.action()() > > > > > The problem I have now is that if I subclass A and want to > change the weighting of one of the methods, I am not sure > how to do that. > > One idea I had was to override the method using the new > weight in the decorator, and then call the original method: > > class B(A): > @weight(50) > def action_1(self): > A.action_1(self) > > > That works, but it feels messy. > > > Another idea was to store the weightings as a dictionary > on each instance, but I could not see how to update that > from a decorator. > > I like the idea of having the weights in a dictionary, so I > am looking for a better API, or a way to re-weight the > methods using a decorator. > > Any suggestions appreciated. > Here is another approach: 8<------------------------------------------------------------------- import random from bisect import bisect #by George Sakkis def take_random_action(obj, actions, weights): total = float(sum(weights)) cum_norm_weights = [0.0]*len(weights) for i in xrange(len(weights)): cum_norm_weights[i] = cum_norm_weights[i-1] + weights[i]/total return actions[bisect(cum_norm_weights, random.random())](obj) class randomiser(object): _cache = [] @classmethod def alert(cls, func): assert hasattr(func, 'weight') cls._cache.append(func) @classmethod def register(cls, name, obj): actions = {} weights = [] for klass in obj.__class__.__mro__: for val in klass.__dict__.itervalues(): if hasattr(val, '__name__'): key = val.__name__ if key in actions: continue elif val in cls._cache: actions[key] = val weights.append(val.weight) actions = actions.values() #setattr(cls, name, classmethod(lambda cls: random.choice(actions)(obj))) setattr(cls, name, classmethod(lambda cls: take_random_action(obj, actions, weights))) def randomised(weight): def wrapper(func): func.weight = weight randomiser.alert(func) return func return wrapper class A(object): @randomised(20) def foo(self): print 'foo' @randomised(10) def bar(self): print 'bar' class B(A): @randomised(50) def foo(self): print 'foo' 8<------------------------------------------------------------------- randomiser.register('a', A()) randomiser.register('b', B()) print 'A' randomiser.a() randomiser.a() randomiser.a() randomiser.a() randomiser.a() randomiser.a() print 'B' randomiser.b() randomiser.b() randomiser.b() randomiser.b() randomiser.b() randomiser.b() From skip at pobox.com Thu Sep 18 08:44:29 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 18 Sep 2008 07:44:29 -0500 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <18642.19757.260540.539125@montanaro-dyndns-org.local> Alex> Unfortunately my len(IN) is about 100.000 and the running time Alex> about 15h !!!! :( Alex> Any idea to improve it? numpy? http://numpy.scipy.org/ http://www.scipy.org/Numpy_Example_List More immediately, note that you are building a list of len(IN) ints every time through the inner loop. A quick hit might be this simple change: indexes = range(len(IN)) for i in indexes: #scan all elements of the list IN for j in indexes: if i != j: if (IN[i].coordinates[0] == IN[j].coordinates[0] and IN[i].coordinates[1] == IN[j].coordinates[1]): SN.append(IN[i].label) Skip From kyosohma at gmail.com Mon Sep 22 14:40:24 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 22 Sep 2008 11:40:24 -0700 (PDT) Subject: Problems running on hp dual core processor References: Message-ID: <285013e8-bdda-4623-94b3-15cd923ed55d@26g2000hsk.googlegroups.com> On Sep 22, 1:43?pm, jim-on-linux wrote: > Python help, > > I have a number of clients running a program built with > python 2.5. ?One has just purchased an HP with a duel > core processor, ?2.2G with .099g ram. > > On the new hp, when they try to print they get an > import error; > File win32ui.pyc line 12, in > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: ?The specified module > could not be found. > > The file is there The only difference I could find from > their other machines is the processor. I should note that I have had issues if I didn't include all the DLLs that were needed. This error doesn't say exactly which DLL is the issue. I recommend downloading Dependency Walker to find out what it is: http://www.dependencywalker.com/ Mike From sjmachin at lexicon.net Sun Sep 7 18:37:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Sep 2008 15:37:54 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: On Sep 8, 7:51?am, "andyh... at gmail.com" wrote: > Hello... > > I have a dict of key/values and I want to change the keys in it, based > on another mapping dictionary. An example follows: > > MAPPING_DICT = { > ? ? 'a': 'A', > ? ? 'b': 'B', > > } > > my_dict = { > ? ? 'a': '1', > ? ? 'b': '2' > > } > > I want the finished my_dict to look like: > > my_dict = { > ? ? 'A': '1', > ? ? 'B': '2' > > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? > Is this homework? There seems to be an implicit assumption in the answers so far that your mapping is a 1:1 mapping of all possible input keys. If it doesn't include all possible input keys, answers will crash with a KeyError. If there are any many:1 elements in the mapping (for example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code in some checks for this. From sturlamolden at yahoo.no Fri Sep 12 19:04:56 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Sep 2008 16:04:56 -0700 (PDT) Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: <88c2dc03-30a3-4f3b-8fee-f65b349d7418@59g2000hsb.googlegroups.com> On Sep 12, 8:33?pm, ady... at panix.com (Al Dykes) wrote: > OK, what are my choices for an IDE/GUI development tool that runs on XP? That depends on the GUI toolkit you are using. My suggestion: CPython with wxPython: wxFormBuilder Cpython with PyQt: BlackAdder CPython with PyGTK: GLADE 3 Jython: whatever there is for Swing or SWT. IronPython: MS VisualStudio Cpython + PyWin32: GUI with VB/Delphi/C#. Python ActiveX server (can use MFC). From NIE_DZIALA at gazeta.pl Tue Sep 23 12:44:12 2008 From: NIE_DZIALA at gazeta.pl (Piotr Sobolewski) Date: Tue, 23 Sep 2008 18:44:12 +0200 Subject: how can I use a callable object as a method References: <87r67hoe1p.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: >> However, the second version does not work. I think I understand >> why. That's because "a" inside f1 is not a function (but an object). > > An object that defines __call__ is perfectly usable as a function. > Your problem is that it doesn't know how to convert itself to a > method, so that f1.a() knows how to pass f1 as another_self to > add.__call__. To do that, add needs to be a bit smarter: A! Now it works, thanks a lot! From kyosohma at gmail.com Wed Sep 10 22:52:29 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 10 Sep 2008 19:52:29 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> <4pcgc495c6ml60a09fh3gc8e6t1akmlmin@4ax.com> Message-ID: <9d24a2d3-1ab2-44a7-92c6-f84a1922a6ac@y38g2000hsy.googlegroups.com> On Sep 10, 4:34?pm, Mike Driscoll wrote: > On Sep 10, 3:53?pm, James A. Donald wrote: > > > > > James A. Donald > > > > > Horrible installs are a chronic problem of GUI programs driven by > > > > interpreted languages ?Installing visual basic programs that worked on > > > > one Windows machine to work on a very slightly different windows > > > > machine was also a nightmare. > > > > > I have not attempted to create installable wxPython windows, but > > > > generally, "run anywhere" will bite you. ?Still looking for a good > > > > solution to "run anywhere". > > > Mike Driscoll > > > > I haven't had much trouble getting wxPython applications to run in > > > Windows XP and Ubuntu Hardy Heron. > > > Did you attempt to create proper install packages that show up in the > > Linux package managers, and the windows add/remove programs tool? > > I used Inno Setup which creates an uninstaller, however I am not > seeing it in my Windows Add/Remove. Odd. However, you can uninstall it > from the Start menu entry and it works. > > Currently, I am running the application from source in Linux. But I > plan to try cx_freeze or similar sooner or later. I haven't had need > to distribute it since my apps are for internal use so far. > > Mike I just tested my Inno installer again and it did put an entry in the Add/Remove program under Windows Vista. The machine I was looking at was my main development machine and probably wasn't a good example. Sorry about that. Mike From marco.bizzarri at gmail.com Tue Sep 16 02:54:44 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Tue, 16 Sep 2008 08:54:44 +0200 Subject: The need to use *arg,**kwd In-Reply-To: References: Message-ID: <3f0d61c40809152354o3223a698vc52a8b3198826a@mail.gmail.com> On Mon, Sep 15, 2008 at 11:51 PM, AON LAZIO wrote: > Hi, Pythoners. > I'd like to know when it is necessary to use *arg or **kwd in the > program. And when it is 'ok' to use normal form of function argument? > Thanks in advance. > > Aonlazio > Sorry, Aonlazio, but which program? This is a fair generic question which needs a little more details to be answered. You are not required to use them. You can use them if problem can be easily solved with them. Which, of course leads to the questionof what your problem is ;) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From nielinjie at gmail.com Sun Sep 14 11:28:50 2008 From: nielinjie at gmail.com (nielinjie) Date: Sun, 14 Sep 2008 23:28:50 +0800 Subject: How to marshal objects to readable files? Message-ID: <48CD2DB2.3090307@gmail.com> Hi list: I just want to marshal objects (instance of custom classes)to a human *READABEL *file/string, and also, I want unmarshal it back. in xml format or any other format. Any advice? Which lib should I use? Thanks a lot. From theiviaxx at gmail.com Tue Sep 9 13:04:02 2008 From: theiviaxx at gmail.com (TheIvIaxx) Date: Tue, 9 Sep 2008 10:04:02 -0700 (PDT) Subject: MySQLdb + AMD64 Message-ID: <94a92067-111a-46a7-b4a3-5770f9396f68@v13g2000pro.googlegroups.com> After searching around for a bit for a build of MySQLdb, i have found that i will probably need to build the module for AMD64 on windows. Is there a guide or something that shows what needs to be done to build a module for a certain architecture? Thanks From kyosohma at gmail.com Thu Sep 4 15:23:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Sep 2008 12:23:16 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: Message-ID: On Sep 4, 1:39?pm, Fett wrote: > I need a crypto package that works on windows with python 2.5. Can > anyone suggest one for me? > > I have been searching for a couple days for a good cryptography > package to use for public/private key encryption, at this point I > would settle for symmetric even. > > Every encryption package I have found for python was either operating > system specific (read *nix only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/ > > There was one exception, this version was specifically built to run on > any platform (yay), but the compiler for windows complained that I > wasn't using python2.2 (though the package was said to only need 2.2 > or newer). > > Is there any crypto package that is actually written in python? I > seriously don't care how slow it is. How about M2Crypto: http://chandlerproject.org/Projects/MeTooCrypto#Downloads Mike From rogeruclan at gmail.com Tue Sep 16 06:44:35 2008 From: rogeruclan at gmail.com (RLC) Date: Tue, 16 Sep 2008 03:44:35 -0700 (PDT) Subject: help on python SWIG C++ extension Message-ID: <20545f75-5621-4418-93a7-e4464d97d25e@26g2000hsk.googlegroups.com> Hello I am new to python SWIG. Recently I wrote a small program trying to import collada files(using colladadom) into python so I could use python cgkit to render them. However, during the progressing, I got some problems. Every time I quit from Python, I get a segmentation fault, although the main program runs well. I suspect it is because I wrapped std::vector objects in C struct and I did not release the memory properly. Below is the code. I am working on FreeBSD 7.0, GCC 4.2.1. I will be very appreciated if you could help me. Thanks a lot. the error I have got Segmentation fault: 11 (core dumped) //////////////////////// ///Header file //////////////////////// #ifndef TDIMPORT_H #define TDIMPORT_H #include #include #include "math.h" #include "float.h" #define WORDINVALIDVALUE ULONG_MAX #define FLOATINVALIDVALUE FLT_MAX typedef unsigned long WORD; typedef struct { double x,y,z; } Vertex; extern Vertex *new_Vertex(double x, double y, double z); extern void delete_Vertex(Vertex *v); extern double Vertex_length(Vertex *v); static const Vertex UNDEFINEDVERTEX = {FLT_MAX,FLT_MAX,FLT_MAX}; typedef struct { double u,v; } UV; extern UV *new_UV(double u, double v); extern void delete_UV(UV *uv); static const UV UNDEFINEDUV = {FLT_MAX,FLT_MAX}; typedef struct { double red,green,blue,alpha; } Color; extern Color *new_Color(double red, double green, double blue, double alpha); extern void delete_Color(Color *color); static const Color BLACK = {0.0, 0.0, 0.0, 1.0}; static const Color WHITE = {1.0, 1.0, 1.0, 1.0}; typedef struct { int type; Color color; std::string texture; } Material; typedef struct { std::vector vertices; std::vector polygonNbVertices; std::vector polygonStartVertexIndex; std::vector polygonVerticesIndices; std::vector uvs; std::vector polygonNbUVs; std::vector polygonStartUVIndex; std::vector polygonUVsIndices; Material material; } PolygonMesh; extern PolygonMesh *new_PolygonMesh(); extern void delete_PolygonMesh(PolygonMesh *p); extern unsigned long PolygonMesh_countvertices(PolygonMesh *p); extern unsigned long PolygonMesh_countpolygons(PolygonMesh *p); extern void PolygonMesh_appendvertex(PolygonMesh *p, Vertex *vertex); extern Vertex PolygonMesh_getvertex(PolygonMesh *p, unsigned long vertexIndex); extern void PolygonMesh_appendpolygon(PolygonMesh *p, const std::vector& verticesIndices); extern long PolygonMesh_getpolygonverticescount(PolygonMesh *p, unsigned long polygonIndex); extern std::vector PolygonMesh_getpolygonverticesindices(PolygonMesh *p, unsigned long polygonIndex); #endif ////////////////////////// //// implementation ////////////////////////// #include "tdimport.h" Vertex *new_Vertex(double x, double y, double z) { Vertex *v; v = (Vertex *)malloc(sizeof(Vertex)); v->x = x; v->y = y; v->z = z; return v; } void delete_Vertex(Vertex *v) { free(v); } double Vertex_length(Vertex *v) { return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); } UV *new_UV(double u, double v) { UV *uv; uv = (UV *)malloc(sizeof(UV)); uv->u = u; uv->v = v; return uv; } void delete_UV(UV *uv) { free(uv); } Color *new_Color(double r, double g, double b, double a) { Color *color; color = (Color *)malloc(sizeof(Color)); color->red = r; color->green = g; color->blue = b; color->alpha = a; return color; } void delete_Color(Color *color) { free(color); } PolygonMesh *new_PolygonMesh() { PolygonMesh *p; p = (PolygonMesh *)malloc(sizeof(PolygonMesh)); p->vertices.clear(); p->polygonNbVertices.clear(); p->polygonStartVertexIndex.clear(); p->polygonVerticesIndices.clear(); p->uvs.clear(); p->polygonNbUVs.clear(); p->polygonStartUVIndex.clear(); p->polygonUVsIndices.clear(); return p; } void delete_PolygonMesh(PolygonMesh *p) { free(p); } unsigned long PolygonMesh_countvertices(PolygonMesh *p) { return (unsigned long)p->vertices.size(); } unsigned long PolygonMesh_countpolygons(PolygonMesh *p) { return (unsigned long)p->polygonNbVertices.size(); } void PolygonMesh_appendvertex(PolygonMesh *p, Vertex *vertex) { p->vertices.push_back(*vertex); } void PolygonMesh_appendpolygon(PolygonMesh *p, const std::vector& verticesIndices) { unsigned int i; for ( i = 0 ; i < verticesIndices.size() ; i++ ) p->polygonVerticesIndices.push_back(verticesIndices.at(i)); p->polygonStartVertexIndex.push_back(p- >polygonVerticesIndices.size()-verticesIndices.size()); p->polygonNbVertices.push_back(verticesIndices.size()); } Vertex PolygonMesh_getvertex(PolygonMesh *p, unsigned long vertexIndex) { if (vertexIndex < 0 || vertexIndex>=p->vertices.size() ) { return UNDEFINEDVERTEX; } else { return p->vertices.at(vertexIndex); } } long PolygonMesh_getpolygonverticescount(PolygonMesh *p, unsigned long polygonIndex) { if ((polygonIndex < 0) || (polygonIndex >= p- >polygonStartVertexIndex.size())) { return (long)-1; } else { return (long)p->polygonNbVertices.at(polygonIndex); } } std::vector PolygonMesh_getpolygonverticesindices(PolygonMesh *p, unsigned long polygonIndex) { std::vector tmp; tmp.clear(); if ((polygonIndex < 0) || (polygonIndex >= p- >polygonStartVertexIndex.size())) { return tmp; } else { unsigned long count = p->polygonNbVertices.at(polygonIndex); unsigned long start = p->polygonStartVertexIndex.at(polygonIndex); for (unsigned long i=0; ipolygonVerticesIndices.at(i+start)); return tmp; } } ///////////////////////// ////SWIG interface ///////////////////////// %module tdimport %{ #include "tdimport.h" %} %include "std_string.i" %include "std_vector.i" namespace std { %template(IntVector) vector; %template(UIVector) vector; %template(VertexVector) vector; %template(UVVector) vector; } using namespace std; typedef struct { double x,y,z; %extend { Vertex (double,double,double); ~Vertex(); double length(); } } Vertex; typedef struct { double u,v; %extend { UV (double,double); ~UV(); } } UV; typedef struct { double red,green,blue,alpha; %extend { Color (double,double,double,double); ~Color(); } } Color; %apply const std::string& {std::string* texture}; typedef struct { int type; Color color; std::string texture; } Material; typedef struct { std::vector vertices; std::vector polygonNbVertices; std::vector polygonStartVertexIndex; std::vector polygonVerticesIndices; std::vector uvs; std::vector polygonNbUVs; std::vector polygonStartUVIndex; std::vector polygonUVsIndices; Material material; %extend { PolygonMesh(); ~PolygonMesh(); unsigned long countvertices(); unsigned long countpolygons(); void appendvertex(Vertex*); Vertex getvertex (unsigned long) ; void appendpolygon(const std::vector&); long getpolygonverticescount(unsigned long); std::vector getpolygonverticesindices(unsigned long); } } PolygonMesh; ///////////////////////// ////python file ///////////////////////// #!/usr/local/bin/python import tdimport a = tdimport.PolygonMesh() a.appendvertex(tdimport.Vertex(1.0,0.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,1.0)) a.appendpolygon([1,2,3]) b = a.getpolygonverticescount(0) print b del a //////////////////////////// ///compile command //////////////////////////// swig -c++ -python tdimport.i g++ -c tdimport.cpp g++ -c tdimport_wrap.cxx -I/usr/local/include/python2.5 g++ -shared tdimport.o tdimport_wrap.o -o _tdimport.so From torriem at gmail.com Tue Sep 30 15:58:49 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 30 Sep 2008 13:58:49 -0600 Subject: XMLRPC - C Client / Python Server In-Reply-To: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> References: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> Message-ID: <48E284F9.60003@gmail.com> care02 at gmail.com wrote: > I have implemented a simple Python XMLRPC server and need to call it > from a C/C++ client. What is the simplest way to do this? I need to > pass numerical arrays from C/C++ to Python. Which do you need, C or C++? They are two different languages with different possibilities for libraries. As the other poster mentioned, xmlrpc-c is a good one for C, and also comes with bindings for C++ which I have used. Getting xmlrpc-c compiled can be a real challenge though. I recommend you use binary packages for your distribution of Linux. If you need it on Win32, then you'll have to spend a day or two figuring out how to build it on Windows. I eventually got the both the C and C++ client library built in Mingw with libcurl as the transport. But it was a real pain. From cvrebert at gmail.com Tue Sep 2 14:05:57 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Tue, 2 Sep 2008 11:05:57 -0700 Subject: How do I adjust the font size on IDLE when running on Mac OS 10.5.4? TIA. In-Reply-To: <16a5d0100809020626w78312e35l52b7c73eabf8add4@mail.gmail.com> References: <16a5d0100809020626w78312e35l52b7c73eabf8add4@mail.gmail.com> Message-ID: <47c890dc0809021105i3cdfd9e3ob738492f677ba407@mail.gmail.com> Same as on all the other platforms. 1. Open IDLE 2. Go Options -> Configure IDLE... 3. Choose the Fonts/Tabs section 4. Use the Size pulldown box - Chris On Tue, Sep 2, 2008 at 6:26 AM, Malcolm Lewis wrote: > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From castironpi at gmail.com Tue Sep 9 17:59:19 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 9 Sep 2008 14:59:19 -0700 (PDT) Subject: dynamic allocation file buffer Message-ID: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> I will try my idea again. I want to talk to people about a module I want to write and I will take the time to explain it. I think it's a "cool idea" that a lot of people, forgiving the slang, could benefit from. What are its flaws? A user has a file he is using either 1/ to persist binary data after the run of a single program (persistence) or 2/ share binary data between concurrently running programs (IPC / shared memory). The data are records of variable types and lengths that can change over time. He wants to change a record that's already present in the file. Here are two examples. Use Case 1: Hierarchical ElementTree-style data A user has an XML file like the one shown here. Foo ... He wants to change "Foo" to "Foobar". Foobar ... The change he wants to make is at the beginning of a 4GB file, and recopying the remainder is an unacceptable resource drain. Use Case 2: Web session logger A tutor application has written a plugin to a webbrowser that records the order of a user's mouse and keyboard activity during a browsing session, and makes them concurrently available to other applications in a suite, which are written in varying lanugages. The user takes some action, such as surfing to a site or clicking on a link. The browser plugin records that sequence into shared memory, where it is marked as acknowledged by the listener programs, and recycled back into an unused block. URLs, user inputs, and link text can be of any length, so truncating them to fit a fixed length is not an option. Existing Solutions - Shelve - A Python Standard Library shelf object can store a random access dictionary mapping strings to pickled objects. It does not provide for hierarchical data stores, and objects must be unpickled before they can be examined. - Relational Database - Separate tables of nodes, attributes, and text, and the relations between them are slow and unwieldy to reproduce the contents of a dynamic structure. The VARCHAR data type still carries a maximum size, no more flexible than fixed-length records. - POSH - Python Object Sharing - A module currently in its alpha stage promises to make it possible to store Python objects directly in shared memory. In its current form, its only entry point is 'fork' and does not offer persistence, only sharing. See: http://poshmodule.sourceforge.net/ Dynamic Allocation The traditional solution, dynamic memory allocation, is to maintain a metadata list of "free blocks" that are available to write to. See: http://en.wikipedia.org/wiki/Dynamic_memory_allocation http://en.wikipedia.org/wiki/Malloc http://en.wikipedia.org/wiki/Mmap http://en.wikipedia.org/wiki/Memory_leak The catch, and the crux of the proposal, is that the metadata must be stored in shared memory along with the data themselves. Assuming they are, a program can acquire the offset of an unused block of a sufficient size for its data, then write it to the file at that offset. The metadata can maintain the offset of one root member, to serve as a 'table of contents' or header for the remainder of the file. It can be grown and reassigned as needed. An acquaintence writes: It could be quite useful for highly concurrent systems: the overhead involved with interprocess communication can be overwhelming, and something more flexible than normal object persistence to disk might be worth having. Python Applicability The usual problems with data persistence and sharing apply. The format of the external data is only established conventionally, and conversions between Python objects and raw memory bytes take the usual overhead. 'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' currently offer this functionality, and the buffer offset obtained from 'alloc' can be used with all three. Ex 1. s= struct.Struct( 'III' ) x= alloc( s.size ) s.pack_into( mem, x, 2, 4, 6 ) Struct in its current form does not permit random access into structure contents; a user must read or write the entire converted strucutre in order to update one field. Alternative: s= struct.Struct( 'I' ) x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) s.pack_into( mem, x1, 2 ) s.pack_into( mem, x2, 4 ) s.pack_into( mem, x3, 6 ) Ex 2. class Items( ctypes.Structure ): _fields_= [ ( 'x1', ctypes.c_float ), ( 'y1', ctypes.c_float ) ] x= alloc( ctypes.sizeof( Items ) ) c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents c.x1, c.y1= 2, 4 The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. Ex 3. s= pickle.dumps( ( 2, 4, 6 ) ) x= alloc( len( s ) ) mem[ x: x+ len( s ) ]= s 'dumps' is still slow and nor does permit random access into contents. Use Cases Revisited Use Case 1: Hierarchical ElementTree-style data Solution: Dynamically allocate the tree and its elements. Node: tag: a Node: tag: b Node: tag: c Node: text: Foo The user wants to change "Foo" to "Foobar". Node: tag: a Node: tag: b Node: tag: c Node: text: Foobar Deallocate 'Node: text: Foo', allocate 'Node: text: Foobar', and store the new offset into 'Node: tag: c'. Total writes 6 bytes 'foobar', a one-word offset, and approximatly 5- 10-word metadata update. Use Case 2: Web session logger Dynamically allocate a linked list of data points. Data: 'friendster.com' Data: 'My Account' Allocate one block for each string, adding it to a linked list. As listeners acknowledge each data point, remove it from the linked list. Keep the head node in the 'root offset' metadata field. Restrictions It is not possible for persistent memory to refer to live memory. Any objects it refers to must also be located in file. Their mapped addresses must not be stored, only their offsets into it. However, live references to persistent memory are eminently possible. Current Status A pure Python alloc-free implementation based on the GNU PAVL tree library is on Google Code. It is only in proof-of-concept form and not commented, but does contain a first-pass test suite. See: http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk The ctypes solution for access is advised. From kyosohma at gmail.com Wed Sep 24 10:44:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Sep 2008 07:44:25 -0700 (PDT) Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: <466524e9-ceba-42b7-b608-6fa5e0663c71@p25g2000hsf.googlegroups.com> On Sep 24, 8:17?am, Marin Brkic wrote: > Not commercial distribution, but an academic kind of sorts - giving > the exe file to coleagues, so they can use it in their work. Giving > .py file is not an option, since due to centralized computer > maintenance, they don't (and cannot) have installed python (except the > ones that bring their own computer at work, but those are an > exception). > > As far as I know py2exe is the only option which can do such a thing > (make exe files from scripts). Is there a way to make those exe files > a little smaller (for a small script they easily go up to 5-10 mb). > > Has anyone had a situation like this ? All your inputs and suggestions > are more then welcomed. > > -- > Marin It ends up being so large because of the dlls that are needed. There are other ways to distribute programs listed here: http://www.freehackers.org/Packaging_a_python_program Mike From tjreedy at udel.edu Wed Sep 10 16:38:23 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 16:38:23 -0400 Subject: which of these 2 quicksorts is faster? In-Reply-To: References: Message-ID: process wrote: > qsort can handle bigger lists it seems, making less recursive calls > before finishing(quicksort blows the stack when sorting > range(100,-1000,-1). > qsort does more work though right? is there a way to speed up that? If you are worried about speed, these 'neat' functional definitions are *not* the way to go. The standard in-place procedural version makes NO copies of the list and no concatenations of sorted pieces. It also scans and partitions the list once instead of twice for each call. > is the built-in sort not defined recursively? Definition != implementation. It is trivial to turn the second recursive call into iteration. More work and an explicit stack (easy in Python) will do the same for the second. > def quicksort(lista): > if len(lista) != 0: For speed, don't 'sort' a list of length 1. In fact, for speed, special-case lists of length 2 and possibly even longer 'short' lists. > return quicksort([x for x in lista[1:] if x < lista[0]]) + > [lista[0]] + \ > quicksort([x for x in lista[1:] if x >= lista[0]]) > else: > return [] > > def qsort(lista): > l = len(lista) In some fonts, 1 and l are extremely similar, so I initially read l/2 below as 1/2. Any of L or ln or n or sz would be clearer. > if len(lista) != 0: > return qsort([x for x in lista[:l/2]+lista[l/2+1:] if x < > lista[l/2]]) + \ > [lista[l/2]] + \ > qsort([x for x in lista[:l/2]+lista[l/2+1:] if x >= > lista[l/2]]) > else: > return [] The difference between your versions is the deterministic choice of pivot element in the (reduncant) double partitioning. It is generally better to pick one at random each time or possibly use the median value of the first, middle, and last. Either way, a consistently bad choice that leads to unbalanced partitions and deep recursion is less likely. Terry Jan Reedy From circularfunc at yahoo.se Tue Sep 16 09:39:18 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 06:39:18 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? References: <92d472c8-4af1-432a-a240-f9f9c97686eb@m73g2000hsh.googlegroups.com> Message-ID: On Sep 16, 3:36?pm, Niklas Norrthon wrote: > On 16 Sep, 15:27, cnb wrote: > > > i can run the interpreter. its just i cant load a file into it. > > > i tried adding your suggestion but it didnt help. i dont think thats > > the issue though. > > Start the interperter (Menu Python - Start interpreter) > Emacs split the frame in two windows > Place the cursor in the python file (C-x o) if necessary > Eval Buffer (C-c C-c) > > Niklas Norrthon ok so C-c C-l is just for doing import, not loading current file? When I do C-c C-c nothing happens at all. From odalrick at hotmail.com Sun Sep 7 12:12:53 2008 From: odalrick at hotmail.com (Odalrick) Date: Sun, 7 Sep 2008 16:12:53 +0000 (UTC) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <240454f2-14ee-496a-9078-1abbf80a4e64@m45g2000hsb.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote in news:240454f2-14ee-496a-9078-1abbf80a4e64 @m45g2000hsb.googlegroups.com: > castironpi: >> For max and min, why can't you just add your argument to the set >> itself? > > Sometimes that can be done, but in many other situations it's less > easy, like in the example I have shown in my first post: > > max((fun(x) for x in iterable if predicate(x))) > > There are some ways to add the max there, for example using an > itertools.chain to chan the default value to the end of the iterable, > but most of the time I just write a for loop. Is there any problem with: max(initial_value, *(fun(x) for x in iterable if predicate(x) ) ) ? From steve at REMOVE-THIS-cybersource.com.au Sat Sep 6 03:49:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Sep 2008 07:49:27 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> Message-ID: <00d23065$0$20302$c3e8da3@news.astraweb.com> On Sat, 06 Sep 2008 00:33:25 -0400, Manu Hack wrote: > Actually it's even more natural to state sum([x]) = x, and this way you > can never conclude that sum([]) = 0 from there. But what you can say is that for any list L, sum(L) = sum(L + [0]). Therefore sum([]) = sum([] +[0]) = 0 -- Steven From marco.bizzarri at gmail.com Fri Sep 5 11:21:09 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 17:21:09 +0200 Subject: Core dumped while interacting with OpenOffice.org via pyuno In-Reply-To: <200809051550.32439.maric@aristote.info> References: <3f0d61c40809050604y42bc494bqa6c91cb1cc3cd913@mail.gmail.com> <200809051550.32439.maric@aristote.info> Message-ID: <3f0d61c40809050821g2c852626s667b21144419502c@mail.gmail.com> On Fri, Sep 5, 2008 at 3:50 PM, Maric Michaud wrote: > Le Friday 05 September 2008 15:04:22 Marco Bizzarri, vous avez ?crit : >> Hi all. >> >> I'm experiencing a core dump while working in the following environment >> >> - debain etch >> - python2.3 >> - openoffice.org 2.4 >> - Zope 2.8.8 >> >> I was able to get a core dump, and the backtrace shows the following: >> >> Core was generated by `python2.3 tests/testActs.py'. >> Program terminated with signal 11, Segmentation fault. >> #0 0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 > ... lot of backtrace ... >> #9 0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3 >> #10 0x08797840 in ?? () >> #11 0x0989b6e0 in ?? () >> #12 0x00000000 in ?? () >> >> Now, I can understand that the information I provided are not enough >> to give me suggestions on solving this issue; so, I'm asking >> suggesions on investigating the issue, namely: >> >> - should I ask here or is it better if I ask on a openoffice forum? > > Yes. Ok >> - should I use a debug-enabled python in order to have more meaningful >> backtraces? > > What you need is more a debug enabled version of pyuno libraries. Ok; I will check with the openoffice guys, then. >> - is there something else I should do in order to have more clues >> ("Read The Fine Manual (tm)" is an acceptable answer) > > You can try to find which function call exactly provoke the exception, the > simplest way is to trace execution flow with some print statments and using > non forking zope instance (runzope -d if I remember well). > Ok; just for completeness, this is not a running zope application, it is a ZopeTestCase which is causing me the trouble. And, as usual, it does not cause it always :-) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From jkrukoff at ltgc.com Wed Sep 3 18:14:48 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 03 Sep 2008 16:14:48 -0600 Subject: python/xpath question.. In-Reply-To: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> References: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> Message-ID: <1220480088.4120.227.camel@jmk> On Wed, 2008-09-03 at 13:36 -0700, bruce wrote: > morning.... > > i apologize up front as this is really more of an xpath question.. > > in my python, i'm using the xpath function to iterate/parse some html. i can > do something like > > s=d.xpath("//tr/td/text()") > count=len(s) > > and get the number of nodes that have text > > i can then do something like > s=d.xpath("//tr/td") > count2=len(s) > > and get the number of total nodes... > by subtracting, i can get the number of nodes, without text.. is there an > easier way??!! > count2-count > > ie, if i have something like > > > foo > > > is there a way to get the count that there is a single "td" node with > text()="" > > thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list Well, you could just do the test (and the count!) in the xpath expression: count( //tr/td[ text() != "" ] ) It sounds like you're not familiar with xpath? I would recommend the O'Reilly XSLT book, it has an excellent introduction to xpath in chapter 3. -- John Krukoff Land Title Guarantee Company From samslists at gmail.com Tue Sep 9 15:38:54 2008 From: samslists at gmail.com (Sam) Date: Tue, 9 Sep 2008 12:38:54 -0700 (PDT) Subject: Deflate with urllib2... Message-ID: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> I'm using urllib2 and accepting gzip and deflate. It turns out that almost every site returns either normal text or gzip. But I finally found one that returns deflate. Here's how I un-gzip: compressedstream = StringIO.StringIO(data) gzipper = gzip.GzipFile(fileobj=compressedstream) data = gzipper.read() Un-gzipping works great! Here's how I un-deflate (inflate??) data = zlib.decompress(data) Un-deflating doesn't work. I get "zlib.error: Error -3 while decompressing data: incorrect header check" I'm using python 2.5.2. Can someone tell me exactly how to handle deflated web pages? Thanks From steve at REMOVE-THIS-cybersource.com.au Mon Sep 22 19:23:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 23:23:54 GMT Subject: A bit weird dictionary behavior References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: <00e822ed$0$20303$c3e8da3@news.astraweb.com> On Mon, 22 Sep 2008 07:35:50 -0700, bearophileHUGS wrote: > Tino Wildenhain: > >> Wouldn't >> len([x for x in iterable if x==y]) >> or even shorter: >> iterable.count(y) >> not work and read better anyway? > > The first version creates an actual list just to take its length, think > about how much memory it may use. For many iterables, the amount of memory is not excessive and the increase in readability of len() is to be preferred over the side-effect of sum(1 for...). But sure, in general you shouldn't try to count the number of items in an arbitrary iterable unless you know how much time and resources it will end up using. That's why I don't think len() should support arbitrary iterables. >> even calculating with boolean values isn't neccessary since 'and' and >> 'foo if bar else blub' are working much better so the type coalescing >> bool - int - float can really go away. > > I don't understand. I think Tino means that you don't need to cast items to bool since you can use ints, floats etc. directly as truth values. -- Steven From blogmoney.bm at gmail.com Fri Sep 26 01:15:26 2008 From: blogmoney.bm at gmail.com (blogmoney) Date: Thu, 25 Sep 2008 22:15:26 -0700 (PDT) Subject: =?KOI8-R?B?LY2NII0gjSCNIFNlY3JldCBCb3RoIFJvb20gVmlkZW8gQ0xJUFMgjQ==?= =?KOI8-R?B?II0gjSCNjY0=?= Message-ID: <1289835d-7007-4108-837b-c7a27347f003@q5g2000prf.googlegroups.com> Watch the Free ==Videos== of All --->LESBIAN College Girl<--- Having Horny VIDEOS...... Here the Huge Collection of Horny Lesbian College Girl & More of School Girls SECRET MMS CLIPStoo... Watch the Free Video Here that will make you satisfied at all.... www.onlinejobszone.blogspot.com www.sfimoney4all.blogspot.com www.yogatips4all.blogspot.com www.hollywoodspicyzone.blogspot.com http://onlinemoney2u.wordpress.com www.onlinejobs4all.googlepages.com From michele at nectarine.it Tue Sep 30 13:50:57 2008 From: michele at nectarine.it (Michele) Date: Tue, 30 Sep 2008 19:50:57 +0200 Subject: Problems with encoding/decoding locales Message-ID: <48e26702$0$18149$4fafbaef@reader3.news.tin.it> Hi there, I'm using a python script in conjunction with a JPype, to run java classes. So, here's the code: from jpype import * import os import random import math import sys input = open('foo.img','rb').read().decode('ISO-8859-1') square = java.encoding(input) output = java.decoding() fd = open('foo_decode.img','wb') fd.write(output.encode('ISO-8859-1')) fd.close() sys.exit(0) First of all, java.encoding and java.decoding are two methods that respectively take a java string as an argument and return a java String. JPype is the bridge between Java and Python, and converts automatically a str or unicode pythonstring into a Java String. So, input and output are two unicode strings. I were forced to use decode() and encode() methods by python, otherwise it refuses to read foo.img file. Here's the strange behaviour: when I write the output in the 'foo_decode.img', I don't reassemble the original file; I already tested the java encoding/decoding libraries with the same input file, and what the decoding process returns is the original file. I suspect that the discrepancy is due to encoding/decoding of ISO-8859-1: is that required? What do you think about? Thank you From tkpmep at hotmail.com Tue Sep 23 14:02:03 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Tue, 23 Sep 2008 11:02:03 -0700 (PDT) Subject: Detecting the first time I open/append to a file Message-ID: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> I have a simulation that runs many times with different parameters, and I want to aggregate the output into a single file with one rub: I want a header to be written only the first time. My program looks a bit like this: def main(): for param in range(10): simulate(param) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) If I can sense that the file is being created in the first iteration, I can then use an if statement to decide whether or not I need to write the header. Question: how can I tell if the file is being created or if this its the first iteration? It's unrealistic to test the value of the parameter as in the real problem, there are many nested loops in main, and the bounds on the loop indices may change. Thanks in advance for your assistance Thomas Philips From harrrrpo at gmail.com Wed Sep 3 05:49:38 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Wed, 3 Sep 2008 11:49:38 +0200 Subject: python - mechanize/browser/POST issue In-Reply-To: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> References: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> Message-ID: <538050a90809030249t7b25d97cvdd3920b9440eeed3@mail.gmail.com> Hello , i don't know about mechanize but in general all you have to do is a simple socket text sending connect to the server then send it POST headers to page in question.. what to send ? getting this your self is much better and one of the best tools is LiveHTTPHeaders - an addon for firefox - so open it post the form in browser then see what you got in LiveHttpHeaders , it will also help you more read through the form being posted html code (knowing posted fields) Regards, Mohamed Yousef 2008/9/3 bruce : > evening... > > using mechanize/Browser, i can easily do a url/get, and process submitting a > form that uses a GET as the action. however, I'm not quite sure how to > implement the submittal of a form, that uses the POST action. > > Anyone have a short chunk of code that I can observer, that uses the > mechanize.Browser implentation? > > in searching the net, i haven't found any... > > thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at ghaering.de Tue Sep 23 08:45:33 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 23 Sep 2008 14:45:33 +0200 Subject: Comparing float and decimal In-Reply-To: <20080923072012.57d8d329.darcy@druid.net> References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > I'm not sure I follow this logic. Can someone explain why float and > integer can be compared with each other and decimal can be compared to > integer but decimal can't be compared to float? > >>>> from decimal import Decimal >>>> i = 10 >>>> f = 10.0 >>>> d = Decimal("10.00") >>>> i == f > True >>>> i == d > True >>>> f == d > False I can give you the technical answer after reading the sources of the decimal module: you can only compare to Decimal what can be converted to Decimal. And that is int, long and another Decimal. Everything else will return False when comparing. > This seems to break the rule that if A is equal to B and B is equal to > C then A is equal to C. Yes, but only if comparison from type(A) to type(C) is supported at all. Instead of raising ValueError or NotImplementedError, the decimal module returns False here. -- Gerhard From fredrik at pythonware.com Sun Sep 21 07:37:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 13:37:39 +0200 Subject: How to kill threading.Thread instance? In-Reply-To: References: Message-ID: dmitrey wrote: > BTW, it should be noticed that lots of threading module methods have > no docstrings (in my Python 2.5), for example _Thread__bootstrap, > _Thread__stop. things named _Class__name are explicitly marked private by the implementation (using the "__" prefix). using them just because you can find them via "dir" is a really stupid idea. (and, as noted in the comment section to the recipe, the "stop" method flags a thread as stopped, it doesn't stop it.) From castironpi at gmail.com Wed Sep 17 20:54:49 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 17 Sep 2008 17:54:49 -0700 (PDT) Subject: minimum install & pickling References: <6jdh9gF2q06nU1@mid.individual.net> Message-ID: <0a6f3d3e-9c2e-421b-bfec-c87f7bd2982b@f63g2000hsf.googlegroups.com> On Sep 17, 6:06?pm, greg wrote: > Aaron "Castironpi" Brady wrote: > > Even a function created from raw bytecode string can't do anything > > without __import__ or 'open'. > > Not true: > > ? ?for cls in (1).__class__.__bases__[0].__subclasses__(): > ? ? ?if cls.__name__ == "file": > ? ? ? ?F = cls > > ? ?F(my_naughty_path, "w").write(my_naughty_data) > > -- > Greg You're right, the list is a little longer. See above, where I renamed the Lib/ folder. 'import site' failed; use -v for traceback Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> for cls in (1).__class__.__bases__[0].__subclasses__(): ... if cls.__name__ == "file": ... F = cls ... >>> F Traceback (most recent call last): File "", line 1, in NameError: name 'F' is not defined >>> 'file' here is still defined. >>> file >>> del __builtins__.file >>> file Traceback (most recent call last): File "", line 1, in NameError: name 'file' is not defined This one stands a chance. From afriere at yahoo.co.uk Wed Sep 24 02:18:04 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 23 Sep 2008 23:18:04 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <5d7d0889-3afd-4e17-b617-6d9c8437eeb5@a3g2000prm.googlegroups.com> On Sep 24, 8:10 am, Christian Heimes wrote: > Side note: > > sys.exit() is just another way to write raise SystemExit. The function > is defined as: > As can be seen if you were ever silly enough to call sys.exit() in IDLE. ;) From dudeja.rajat at gmail.com Mon Sep 8 12:35:21 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 8 Sep 2008 17:35:21 +0100 Subject: Unable to start a process with subprocess Popen() In-Reply-To: <3657eb2f-c827-4929-be5a-689959de5f85@a1g2000hsb.googlegroups.com> References: <3657eb2f-c827-4929-be5a-689959de5f85@a1g2000hsb.googlegroups.com> Message-ID: On Mon, Sep 8, 2008 at 4:43 PM, aha wrote: > On Sep 8, 7:23 am, dudeja.ra... at gmail.com wrote: >> On Mon, Sep 8, 2008 at 11:50 AM, wrote: >> > Hi, >> >> > I'm using the subprocess module's Popen() to start a batch file. This >> > batch file basically calls an exe which also gets started. >> > Unfortunately, this does not produce any results. I looked into the >> > Task bar that this exe has started but it does not consume and cpu so >> > I believet that this exe is not working. >> >> > I used the following command to start the batch fiile: >> >> > testing = subprocess.Popen([batchFilePath], \ >> > shell = True, \ >> > stdout = subprocess.PIPE, \ >> > stderr = subprocess.PIPE).communicate()[0] >> >> > batchFilePath is the path of the batch file. >> >> > -- >> > Regrads, >> > Rajat >> >> Ok, I re-phrase my question: >> >> there is a batch file that executes a exe file. The batch just works >> if run from command prompt and produces output to standard output and >> the file. >> >> Now, I try to call the same batch file from subprocess.Pope() call. >> The batch file gets called and that internally also calls the exe >> file. >> >> But, the exe just runs forever i.e. hangs and does not produces output >> , atleast not to the file. >> >> Please suggest is there is something wrong with the above code. >> >> Regards, >> Rajat > > Hello Rajat, > I would take a look at the thread below, it might help it might not: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/4505613f014fdec7/3ee15c9c88a5efdc?hl=en#3ee15c9c88a5efdc > > Also, if you post a larger section of the code I might be able to give > you a hand. Once you've run the testing = subprocess.Popen() > > make sure you use a testing.wait() > -- > http://mail.python.org/mailman/listinfo/python-list > Hi Aaquil, Thanks for helping me out with this piece of information. My Original code is : testing = subprocess.Popen([batchFilePath], \ shell = True, \ stdout = subprocess.PIPE, \ stderr = subprocess.PIPE) result = testing.wait() if result < 0: childError = testing.stderr.read() tkMessageBox._show("Error", \ icon='error', \ message ="Error: %s" % childError) return None else: print result My child process was unresponsive. Later I got to know with the below code that there were some errors coming from the child process which I was not able to detect with this code. I googled for some solution and found the below code :- print "ttt", batchFilePath #print os.listdir(batchFilePath) try: cmd = subprocess.Popen([batchFilePath], \ shell = True, \ stdin = subprocess.PIPE, stdout = subprocess.PIPE, \ stderr = subprocess.PIPE \ ) cmd.stdin.close() outPipe, errPipe = PipeThread(cmd.stdout), PipeThread(cmd.stderr) outPipe.run(), errPipe.run() retcode = cmd.wait() out, err = outPipe.getOutput(), errPipe.getOutput() if retcode != 0 and err != '': raise ExecutionFailed, os.path.basename(batchFilePath) + " exited with error code " + str(retcode) + " and errors:\n" + err elif retcode != 0: raise ExecutionFailed, os.path.basename(batchFilePath) + " exited with error code " + str(retcode) + " and output:\n" + out elif err != '': return out + "\n" + os.path.basename(batchFilePath) + " gave warnings:\n" + err else: return out except Exception, e: if isinstance(e, ExecutionFailed): raise else: raise ExecutionFailed, "Error while executing " + ":\n" + str(e) Here are the Exception and the PipeThread Classes: class PipeThread(threading.Thread): def __init__(self, fin): self.fin = fin self.sout = "" threading.Thread.__init__(self) def run(self): self.sout = self.fin.read() def getOutput(self): return self.sout class ExecutionFailed(Exception): def __init__(self, value): self.parameter = value def __str__(self): return str(self.parameter) Although, this solved my problem. But I know there is no need for using threading in this problem. This problem could've been solved just by the subprocess module. I'm unnecessarily using the threading module. Regards, Rajat -- Regrads, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From hvlems at freenet.de Sun Sep 21 18:00:16 2008 From: hvlems at freenet.de (H Vlems) Date: Sun, 21 Sep 2008 15:00:16 -0700 (PDT) Subject: Milenko Kindl rtegdgd References: Message-ID: <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> On 21 sep, 19:48, yuma wrote: > Milenko Kindl > Banja Luka > Banjaluka > Bihac Well, that's not C isn't it, more like Snobol or RPG/2 From jamesd at echeque.com Wed Sep 10 16:53:13 2008 From: jamesd at echeque.com (James A. Donald) Date: Thu, 11 Sep 2008 06:53:13 +1000 Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> Message-ID: <4pcgc495c6ml60a09fh3gc8e6t1akmlmin@4ax.com> James A. Donald > > Horrible installs are a chronic problem of GUI programs driven by > > interpreted languages ?Installing visual basic programs that worked on > > one Windows machine to work on a very slightly different windows > > machine was also a nightmare. > > > > I have not attempted to create installable wxPython windows, but > > generally, "run anywhere" will bite you. ?Still looking for a good > > solution to "run anywhere". Mike Driscoll > I haven't had much trouble getting wxPython applications to run in > Windows XP and Ubuntu Hardy Heron. Did you attempt to create proper install packages that show up in the Linux package managers, and the windows add/remove programs tool? -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From bacondemonstratert at gmail.com Thu Sep 25 17:02:12 2008 From: bacondemonstratert at gmail.com (bacondemonstratert at gmail.com) Date: Thu, 25 Sep 2008 14:02:12 -0700 (PDT) Subject: zootube365 zootube365 com - Free Message-ID: zootube . . . *******CLICK HERE******** http://vids365.cn/zootube ***************************** . . . . . . . . . . . . zootube ?s voice quivered, ?Oh God, baby, zootube cunt is so tight sweetie. This set zootube365 off too, and zootube365 could feel zootube365 climax as zootube365 pussy muscles went wild around my cock. In zootube365 mind, zootube365 was saying, ?Rebecca, don?t worry zootube365 pretty little head, zootube365 intend to marry zootube365 daughter. com observed that the gunman was in the same state of arousal as com was. From fredrik at pythonware.com Thu Sep 11 16:37:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 22:37:54 +0200 Subject: Is len O(n) or O(1) ? In-Reply-To: <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> Message-ID: process wrote: > ok but if len is O(1) then it doesnt matter? compared to > > if not lista: > return [] what doesn't matter? From prologic at shortcircuit.net.au Sun Sep 7 17:34:55 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 07:34:55 +1000 Subject: lacking follow-through In-Reply-To: References: Message-ID: Hi, This is the strangest post I've seen since I've joined this list (only recently). What the ? cheers James On Mon, Sep 8, 2008 at 7:00 AM, castironpi wrote: > I am concerned by the lack of follow-through on some responses to > recent ideas I have described. Do I merely have a wrong understanding > of group policy? Is it a good policy (defined with respect to the > future of Python and the welfare of humans at large) if so? Is there > a serious lack of diligence, or should I merely take more initiative, > and ignore charges of 'pestering'? (Warning, moderately deep outside > social issues on table too.) > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From sturlamolden at yahoo.no Tue Sep 23 14:49:13 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 11:49:13 -0700 (PDT) Subject: Linq to Python References: Message-ID: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> On Sep 23, 4:48?pm, hrishy wrote: > Will LINQ be ported to Python ? No, because Python already has list comprehensions and we don't need the XML buzzword. From metaperl at gmail.com Thu Sep 18 16:08:59 2008 From: metaperl at gmail.com (metaperl.com) Date: Thu, 18 Sep 2008 13:08:59 -0700 (PDT) Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: On Sep 9, 9:23?am, s... at pobox.com wrote: > ? ? >> I really dont care if theexpressionis optimal. So the goal is > ? ? >> something like: > > ? ? >> vowel_regexp = oneOf("a aa i ii u uu".split()) ?# yielding r'(aa|a|uu| > ? ? >> u|ii|i)' > > ? ? >> Is there a public module available for this purpose? > > Check Ka-Ping Yee's rxb module: > > ? ?http://lfw.org/python/ Ok suffers from the possibility of putting shorter match before longer one: def either(*alternatives): options = [] for option in alternatives: options.append(makepat(option).regex) return Pattern('\(' + string.join(options, '|') + '\)') >?Also, check PyPI to see if > someone has already updated rxb for use with re. No one has - http://pypi.python.org/pypi?%3Aaction=search&term=rxb&submit=search no results returned From deets at nospam.web.de Sat Sep 13 03:18:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 13 Sep 2008 09:18:32 +0200 Subject: question about python In-Reply-To: References: Message-ID: <6j17q8F107jbU1@mid.uni-berlin.de> fishfin schrieb: > I was working through a tutorial about how to write a server using > python (the url is bellow). I am sure that the server is working to > some degree because when the server is running localhost:8080 just > keeps trying to load until it times out. I would like to know how to > send information through the server to my browser? > > I was working through this tutorial: > http://python.about.com/od/networkingwithpython/ss/PythonWebServer.htm > > > and my final code is like this: > > import socket > > host = '' > port = 8080 > > c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > > c.bind((host, port)) > > c.listen(1) > > while 1: > csock, caddr = c.accept() > cfile = csock.makefile('rw', 0) > > line = cfile.readline().strip() > > cfile.write('HTTP/1.0 200 OK\n\n') > cfile.write('Welcome %s!' % > (str(caddr))) > cfile.write('

Follow the link...

') > cfile.write('All the server needs to do is ') > cfile.write('to deliver the text to the socket. ') > cfile.write('It delivers the HTML code for a link, ') > cfile.write('and the web browser converts it.



') > cfile.write('
Click me!
') > cfile.write('

The wording of your request was: "%s"' %(line)) > cfile.write('') > > cfile.close() > csock.close() Do yourself a favor and look into the various python webframeworks such as TurboGears, Django and what not. Or at least into the module SimpleHTTPServer. Diez From geoff.bache at jeppesen.com Thu Sep 11 07:43:26 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 11 Sep 2008 04:43:26 -0700 (PDT) Subject: Persuading ConfigParser to give me the section elements in the same order as the file References: <4566f721-028d-4079-90d8-7818d69d18b3@34g2000hsh.googlegroups.com> Message-ID: <842698d5-ee63-4008-b1bb-df878312325c@c58g2000hsc.googlegroups.com> Hi Matt, > Have a look at this:http://www.python.org/dev/peps/pep-0372/ > Thanks, that was very useful. Good to know these things are being considered. > Looking at the config parser module, it looks like there are only a > couple of places where {} is used. I would create a mixin class to > replace the offending methods. That should work because it looks like > you only have to replace "__init__" and "add_section". So... > > class OrderedConfigParserMixin: > ? ? def __init__(self, defaults=None): > ? ? ? ? self._sections = ndict.seqdict() > ? ? ? ? self._defaults = ndict.seqdict() > ? ? ? ? if defaults: > ? ? ? ? ? ? for key, value in defaults.items(): > ? ? ? ? ? ? ? ? self._defaults[self.optionxform(key)] = value > > ? ? def add_section(self, section): > ? ? ? ? """Create a new section in the configuration. > > ? ? ? ? Raise DuplicateSectionError if a section by the specified name > ? ? ? ? already exists. > ? ? ? ? """ > ? ? ? ? if section in self._sections: > ? ? ? ? ? ? raise DuplicateSectionError(section) > ? ? ? ? self._sections[section] = ndict.seqdict() > > # Then you can use this to create your own ordered config parsers. > Note that > # multiple inheritance in python uses a breadth first search. If you > want > # the methods on your mixin to get called instead of the methods on > the > # original class you must include the mixin first. > > from ConfigParser import RawConfigParser, ConfigParser, > SafeConfigParser > > class OrderedRawConfigParser(OrderedConfigParserMixin, > RawConfigParser): > ? ? pass > > class OrderedConfigParser(OrderedConfigParserMixin, ConfigParser): > ? ? pass > > class OrderedSafeConfigParser(OrderedConfigParserMixin, > SafeConfigParser): > ? ? pass > > I don't know if this is the _best_ approach, but it is certainly much > preferred over monkey patching the built-ins module. Note that I > haven't tested any of the above code. Yes, I tried this first. But actually you missed the main place where dictionaries are created, which is the monster method _read, the line being cursect = {'__name__': sectname} I thought by the time I'd copied that whole method just to edit that line I may as well just copy the whole file and forget the inheritance :) btw, the PEP you pointed me at indicated ConfigParser will take a dict_type argument for exactly this purpose in Python 2.6, so I look forward to when I can use that instead... Regards, Geoff From king.geek22 at gmail.com Mon Sep 1 11:57:12 2008 From: king.geek22 at gmail.com (king.geek22 at gmail.com) Date: Mon, 1 Sep 2008 08:57:12 -0700 (PDT) Subject: FHA Refinance Loan Message-ID: On October 1, 2008, new FHA Refinance Loan Guidelines will go into effect as part of The Housing and Economic Recovery Act of 2008. This new FHA Mortgage program is designed to help thousands of homeowners who are at risk of foreclosure in their curent conventional or sub- prime home loans. The details of The ???HOPE for Homeowners Act of 2008??? are as follows: 1. Eligible Borrowers Only owner-occupants who are unable to afford their mortgage payments are eligible for the program. No investors or investor properties will qualify. Homeowners must certify, under penalty of law, that they have not intentionally defaulted on their loan to qualify for the program and must have a mortgage debt-to-income ratio greater than 31% as of March 1, 2008. Lenders must document and verify borrowers??? income with the IRS. 2. Home Equity & Appreciation Sharing In order to avoid a windfall to the borrower created by the new 90% loan-to-value FHA-insured mortgage, the borrower must share the newly- created equity and future appreciation equally with FHA. This obligation will continue until the borrower sells the home or refinances the FHA-insured mortgage. Moreover, the homeowner???s access to the newly created equity will be phased-in over a 5 year period. The borrower agrees to repay the following share of any home equity appreciation with the FHA when the home is sold or refinanced again; A. 100% of any equity earned is paid to the government FHA if the home sells or the borrower refinances within 1 year. B. 90% of any equity earned is paid to the FHA if the home sells or the borrower refinances within 2 years. C. 80% of any positive equity earned is paid to the FHA if the home sells or the borrower refinances within 3 years. D. 70% of any positive equity earned is paid to the FHA if the home sells or the borrower refinances within 4 years. E. 60% of any positive equity earned is paid to the FHA if the home sells or the borrower refinances within 5 years. F. 50% of any positive equity earned is paid to the FHA if the home sells or the borrower refinances after 5 years. Note: The FHA requires a 3% Exit Fee of the Mortgage Principal Balance when the borrower sells or refinances the home again. 3. Other Requirements Existing Subordinate Liens Before participating in this program, all subordinate liens (such as second loans, home equity loans, etc.) must be extinguished. This will have to be done through negotiation with the first lien holder. Mortgage Insurance and Other Fees The Up Front FHA Mortgage Insurance Premium that is required on all FHA Refinance Loans will change as part The Housing and Economic Recovery Act of 2008. The Monthly MI Rates have also been updated. The following FHA MI rates will begin on October 1, 2008 and will be effective for 12 months; FHA Up Front MIP - Required on all FHA Loans (Can be financed into loan amount). 1.75% - Normal FHA 203(b) Refinance 1.5% - FHA Streamlined Refinance 3.0% - FHASecure (Refinance for high risk borrowers who are already delinquent on current mortgage) Monthly MI ??????" Multiply the loan amount by the figure below and then divide by 12. The result is your Monthly Mortgage Insurance. 30 Year Note 0.55% - Refinance greater than 90% of the home???s LTV. 0.50% - Refinance less than or equal to 90% of the home???s LTV. 15 Year Note 0.25% - Refinance greater than 90% of the home???s LTV. Monthly MI is not required on an 15 Year FHA Refinance Loan with an LTV of 90% or less. The FHA Refinance Loan Process Each new loan will be originated and underwritten on a case-by-case basis. To get approved, your income statements, bank accounts, credit scores and work history will be examined. A new appraisal must be performed on your home to determine its current value. If doesnt have positive equity, then you must contact your current lender and negotiate with them to reduce (write down) your current mortgage to 90% of its current appraised value. If your current lender agrees to the write down, then you will be able to proceed with the FHA refinance. www.my-quickloans.com From tjreedy at udel.edu Mon Sep 1 14:57:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 14:57:09 -0400 Subject: Command lime code In-Reply-To: References: Message-ID: Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Okay, I'll take I wild guess: By "command lime code" you did not refer > to the algorithmic domination of citrus fruit, but rather to that window > with the tiny blinking cursor and loads of text in white on black. Also > by 'chdir' you probably mean the MS DOS equivalent to UNIX 'cd' (which > AFAIK also works on MS DOS). So Googling for "MS DOS Commands" might be > a good idea and yield, amongst others, this result: The os module also has an os-independent chdir() function. From tino at wildenhain.de Mon Sep 1 00:45:56 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 01 Sep 2008 06:45:56 +0200 Subject: parsing "&A" in a string.. In-Reply-To: References: Message-ID: <48BB7384.2000104@wildenhain.de> Tim Roberts wrote: > "bruce" wrote: >> it's the beautifulsoup() that's taking the "&E" and giving the "&E;"... > > Right, as it should. "A&E" is not valid HTML, and beautifulsoup expects > valid HTML. > > This can be difficult to fix in the general case, because your page might > already contain "&". If it is possible that some of them might be > wrong while some are right, you can do something like: > > s = s.replace( '&', '&' ).replace( '&', '&' ) Yeah, but what about ä and friend then? As you said, its not really easy to fix. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From bj_666 at gmx.net Wed Sep 24 00:21:10 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Sep 2008 04:21:10 GMT Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> Message-ID: <6jtthmF50fj6U1@mid.uni-berlin.de> On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote: >> > This seems to break the rule that if A is equal to B and B is equal >> > to C then A is equal to C. >> >> I don't see why transitivity should apply to Python objects in general. > > Well, for numbers it surely would be a nice touch, wouldn't it. May be > the reason for Decimal to accept float arguments is that irrational > numbers or very long rational numbers cannot be converted to a Decimal > without rounding error, and Decimal doesn't want any part of it. Seems > pointless to me, though. Is 0.1 a very long number? Would you expect ``0.1 == Decimal('0.1')`` to be `True` or `False` given that 0.1 actually is In [98]: '%.50f' % 0.1 Out[98]: '0.10000000000000000555111512312578270211815834045410' ? Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Fri Sep 5 16:58:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 13:58:00 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> Message-ID: On Sep 6, 2:45?am, bearophileH... at lycos.com wrote: > Michael Palmer: > > > why can't it be tuple already? > > Because if the input list L has tuples and lists, they end having the > same hash value: Perhaps the OP shouldn't be constructing the hash of a mutable object. Perhaps he would be grateful if his hash function raised an exception instead of laboriously masking the problem. > > >>> L = [[1,2,3], (1,2,3)] > >>> hash(tuple(L[0])), hash(tuple(L[1])) > > (-378539185, -378539185) > > But it's a not much common situation, and few hash collision pairs > can't damage much, so I agree with you that my assert was useless. > This may solve that problem anyway: > > hash(type(L)) ^ hash(tuple(L)) Consider this: >>> hash(123) == hash(123.0) == hash(123L) True Perhaps the OP (who hasn't stated what he is going to use the hash results for) needs to use only the values in his hash, and would be if not highly delighted then at least blithely unconcerned if it turned out that [1, 2, 3] and (1, 2, 3) had the same hash. > > Generally a good hashing functions uses all the input information. If > you use tuple() you ignore part of the input information, that is the > type of L. So xor-ing hash(type(L)) you use that information too. > Try "uses all the information that is relevant to the task". Your alternative solution using reduce and xor may have suboptimal characteristics ... xor_hash((1, 2, 3)) == xor_hash((1, 3, 2)) == xor_hash((2, 1, 3)) etc. While the docs for __hash__ say "it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object", in practice "somehow" is rather more elaborate than xor. Have a look at the tuplehash function in .../Objects/tupleobject.c. If the order of the values in the tuple doesn't matter, then perhaps the OP really should be using a set (or a bag). Cheers, John From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 30 05:54:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 30 Sep 2008 11:54:42 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: <48e1f745$0$13447$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message , James > Mills wrote: > >> On Fri, Sep 26, 2008 at 8:20 AM, Lawrence D'Oliveiro >> wrote: >> >>> Object orientation IS procedural. >> Correction: OOP is Imperative. > > No, "procedural". Nope, "imperative" !-) > The functional unit is called an "expression", the encapsulation of which is > called a "function". Hence "functional". > > Similarly, the procedural unit is commonly called a "statement", the > encapsulation of which is a "procedure", not an "imperator". > Hence "procedural". "imperative" means that the computation is done through statements that modify the program's state. "procedural" means that these statements are organized in "procedures", that group a serie of statements. OO is based on objects (that carry and manage internal state) and messages. A message can happen to trigger a serie of statements that modifies a program state, so you could say (and this wouldn't be totally false) that an OO method can be seen as a procedure (or at least some methods...), but the whole program's organization is still not the same as one seen in procedural programming. IOW, it's more a matter of how you design / organize your (otherwise imperative) program than anything else. From gagsl-py2 at yahoo.com.ar Sun Sep 7 16:13:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 17:13:11 -0300 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: En Sun, 07 Sep 2008 14:30:09 -0300, Mensanator escribi?: > Actualy, I already get the behaviour I want. sum([1,None]) > throws an exception. I don't see why sum([]) doesn't throw > an exception also (I understand that behaviour is by design, > I'm merely pointing out that the design doesn't cover every > situation). [...] > Exactly. That's why I would prefer sum([]) to raise an > exception instead of giving a false positive. The built in behavior can't be good for every usage. Nobody prevents you from defining yoru own function tailored to your own specs, like this: def strict_sum(items): items = iter(items) try: first = items.next() except StopIteration: raise ValueError, "strict_sum with empty argument" return sum(items, first) Tweak as needed. Based on other posts I believe your Python skills are enough to write it on your own, so I don't see why you're complaining so hard about the current behavior. -- Gabriel Genellina From pavlovevidence at gmail.com Wed Sep 24 05:12:24 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 24 Sep 2008 02:12:24 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <5a09432f-0197-4cb9-8eba-c1ad66ecb387@d77g2000hsb.googlegroups.com> On Sep 23, 4:25?pm, Drake wrote: > The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), I'm kind of curious what your library is for. Is it something where exiting the app be the only appropriate action for an IO error? Even if it is, I will echo other people's advice: a library should never call exit, at least not by default. For your imagined use it might make sense to exit upon any failure, but other people using the library might not want to do that. For that matter, a library should never print error or status messages. Messages should either be sent to the caller somehow, or handled using the logging facility. Carl Banks From Afro.Systems at gmail.com Wed Sep 10 14:40:22 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Wed, 10 Sep 2008 11:40:22 -0700 (PDT) Subject: Simple UDP server Message-ID: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> I am looking for the right way to write a small and simple UDP server. I am wondering between Forking, Threading (found at SocketServer.py) and the one describes at the snippet below. Can you tell me the advantages and disadvantages of each Would the one below will be capable of holding 30 concurrent connections? I have no intention of using Twisted or alike since I am looking for making it as lightweight as possible Thanks in advance, Tzury Bar Yochay # begin of snippet from socket import * # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(('',50008)) while 1: data,addr = UDPSock.recvfrom(4*1024) if not data: print "No data." break else: print 'from:', addr, ' data:', data UDPSock.close() From michel at nospam.please Mon Sep 15 15:46:47 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:46:47 +0200 Subject: Python Nautilus script In-Reply-To: <6j7rjpF1rp5lU1@mid.uni-berlin.de> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> Message-ID: <48cebba7$0$2862$ba620e4c@news.skynet.be> Diez B. Roggisch a ?crit : > There shouldn't be a difference between a shell-script and a > python-script. Environment-variables are a unix-process-thing, and thus > the rules that govern them apply to *all* processes - the shell is one > of these, there is nothing special to it. > > If the shell-script gets the variable, the python-script will as well. Yes, that's what I thought too but try this: open a terminal and type $ echo $HOSTNAME you will get the name of your computer. Now try this instead: $ python >>> import os >>> os.environ['HOSTNAME'] Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ raise KeyError(key) KeyError: 'HOSTNAME' >>> It appears that's because HOSTNAME is not exported. But in the case of Nautilus script, how to workaround this issue? -- Michel Leunen http://linux.leunen.com From cyberco at gmail.com Wed Sep 3 17:52:07 2008 From: cyberco at gmail.com (Berco Beute) Date: Wed, 3 Sep 2008 14:52:07 -0700 (PDT) Subject: Python on JavaScript VM's (such as V8)? Message-ID: <1926ef1e-2c5e-4ef6-8a33-b360b02520a7@b38g2000prf.googlegroups.com> I wonder what it would take to implement Python in JavaScript so it can run on those fancy new JavaScript VM's such as Chrome's V8 or Firefox' tracemonkey. Much the same as Python implementations in C# (IronPython) and Java (Jython). It would certainly bring back the fun in web application development. Is there anything done in that direction? 2B From clp at rebertia.com Fri Sep 26 14:08:29 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 26 Sep 2008 11:08:29 -0700 Subject: Fastest way to max() list In-Reply-To: References: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> Message-ID: <47c890dc0809261108k356a109va88b675e037246be@mail.gmail.com> On Fri, Sep 26, 2008 at 7:22 AM, David Di Biase wrote: > Hi Chris, > > Yeah I hear you on point A. but this the specification I was given, so I > have to follow it unfortunately. I've also been restricted and not allowed > to use any other packages. I was using NumPy earlier (should have mentioned > that) but I was wondering if there was a simpler way. Is NumPy technically > even faster than just iterating and modifying the list directly? > > Also if I'm creating an array then making it, Uh, this part of your sentence doesn't quite make sense... > why not just do a temporary > sort and capture the first and last values? Is this method you've provided > supposed to be faster? Well, unless you're going to use the rest of the sorted values at some point in your program and since you have a large quantity of data, yes, my way ought to be faster. Sorting the list is O(N*log(N)) while running max and min over the list is only O(N). Regards, Chris > > Dave > > On Fri, Sep 26, 2008 at 12:42 AM, Chris Rebert wrote: >> >> On Thu, Sep 25, 2008 at 8:57 PM, David Di Biase >> wrote: >> > I have a list with about 1000-1500 sub-lists which look like so: >> > list[-0.28817955213290786, 3.6693631467403929, 'H', 31.31225233035784]] >> > >> > The first and second values are Angstrom units specifying the location >> > of a >> > particle. What I'd like to do is determine the distance between the >> > smallest >> > and largest value in the arrays first position 0. I tried reading the >> > manual >> > for this but I don't see how it applies key or any of those other >> > commands >> > to the function. I could easily write a sort to do this and capture the >> > first and last spots, but why do that when I can use max and min (if I >> > can >> > actually do that...). >> >> A. You should probably be using objects rather than arrays to >> represent your datapoints, so that they're more structured and it's >> more apparent what the values mean. >> >> B. Assuming by "distance" you meant "difference" and/or that the >> distance is only in 1 dimension: >> >> from operator import itemgetter >> firsts = map(itemgetter(0), main_list) >> distance = max(firsts) - min(firsts) >> >> > >> > So you wonderful Python gods, lay some knowledge on me. please? lol... >> > >> > while I'm at it, is there a way to modify an entire list without having >> > to >> > produce a whole new one? For example now say I want to modify list[0] >> > and >> > multiply it by some value. From what I understand previous version of >> > Python >> > allowed lists to be multiplied like matrices...now apparently it just >> > replicates the list. :-/ shucks... >> >> You just have to apply the transform to each list element individually >> (also, you might consider using NumPy [http://numpy.scipy.org/] if >> you're doing a lot of matrix manipulation): >> >> for lst in main_list: >> lst[0] *= some_value >> >> Regards, >> Chris >> >> > >> > The first question would be useful to know, but the second question I do >> > quite a bit of and the "best practice" would be really great to know! >> > >> > Thanks in advanced! >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> > >> -- >> Follow the path of the Iguana... >> http://rebertia.com > > -- Follow the path of the Iguana... http://rebertia.com From ldo at geek-central.gen.new_zealand Mon Sep 29 02:53:06 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 19:53:06 +1300 Subject: how to make smtplib.SMTP('localhost') work on window xp References: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Message-ID: In message <56f2097a-5129-4d1a-be82-a73e2874ba04 at p31g2000prf.googlegroups.com>, zxo102 wrote: > SMTPServerDisconnected: Connection unexpectedly closed Does the SMTP server on localhost mention anything about the connection attempt in its log? If you telnet/netcat to port 25 on localhost, does anything interesting happen? From jcd at sdf.lonestar.org Wed Sep 3 12:00:55 2008 From: jcd at sdf.lonestar.org (Cliff) Date: Wed, 3 Sep 2008 09:00:55 -0700 (PDT) Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> <878wubp5mz.fsf@benfinney.id.au> Message-ID: <69f945f1-d924-4a75-8830-7f308641ac65@34g2000hsh.googlegroups.com> On Sep 2, 12:34?am, Fredrik Lundh wrote: > Ben Finney wrote: > > I would argue that the precedent, already within Python, for using a > > space to separate pieces of a string literal, is more important than > > precedents from other programming languages. > > that precedent also tells us that the whitespace approach is a common > source of errors. ?taking an approach that's known to be error-prone and > applying it to more cases isn't necessarily a great way to build a > better language. > > Also a source of mental complexity. The two proposals (whitespace vs. underscores) are not just a question of what character to use, it's a question of whether to create an integer (and possibly other numeric type) literal that allows delimiters, or to allow separate literals to be concatenated. In the second case, which of the following would be proper syntax? 0b1001 0110 0b1001 0b0110 In the first case, the second literal, on its own, is an octal literal, but we expect it to behave as a binary literal. In the second case, we have more consistency with string literals (with which you can do this: "abc" r'''\def''') but we lose the clarity of using the concatenation to make the whole number more readable. On the other hand, 0b1001_0110 has one clear meaning. It is one literal that stands alone. I'm not super thrilled about the look (or keyboard location) of the underscore, but it's better than anything else that is available, and works within a single numeric literal. For this reason I am +0 on the underscore and -1 on the space. From HeinTest at web.de Mon Sep 1 09:25:03 2008 From: HeinTest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Mon, 01 Sep 2008 15:25:03 +0200 Subject: Eleganz way to get rid of \n Message-ID: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Hello, I'm quite often using this construct: for l in open("file", "r"): do something here, l contains the \n or \r\n on windows at the end. I get rid of it this way: for l in open("file", "r"): while l[-1] in "\r\n": l = l[:-1] I find this a little bit clumsy, but it works fine. Has someone a better solution ? Thanks Hans From sturlamolden at yahoo.no Tue Sep 23 14:07:22 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 11:07:22 -0700 (PDT) Subject: Python is slow? References: Message-ID: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> On Sep 23, 3:44?pm, Robert Singer wrote: > Well, python is not a number crunching language. However much we would > like it to be (we would ? :-). > No scripting language is. Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? > Before resorting to rewriting the problem try psyco. It speeds up > things sometimes. I did, Psyco did not help. > Also, (I'm not that familiar with python yet, so I don't know how to > do it in python), try finding the bottlenecks of your calculation. I did use a profiler, there is no particular single bottle-neck. > Well, personally, I try to combine fortran (being a fortran programmer > by trade) with python Good compilers are too expensive, and gfortran is not good enough yet. From tjreedy at udel.edu Sat Sep 6 13:59:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Sep 2008 13:59:53 -0400 Subject: why is self not passed to id()? In-Reply-To: References: Message-ID: <48C2C519.7030400@udel.edu> Ruediger wrote: > I found following solution to the problem. > > Instead of assigning id directly to __hash__ it has to be wrapped with an > instancemethod object. It is somehow strange that this doesn't happen > automatically and it is also strange that instancemethod isn't exposed in > the type module. There are several internal implementation types not exposed in types because they are subject to change from version to version In 3.0, your code does not work. Instancemethod may to added to 3.0 or 3.1 as a built-in function. > ****************************************************************** > > class foo(list): > __hash__ = lambda x: id(x) > type > instancemethod = type(foo.__hash__) In 2.x, this gives you 'instancemethod'. In 3.0, you get 'function' as unbound methods are no longer wrapped when the underlying function is a 'function' (resulting from def or lambda abbreviation). > class bar(list): > pass > bar.__hash__ = instancemethod(id, None, bar) Calling a 'function' with those parameters will not work. Did you miss the following from my previous response? "There *is* a third alternative, which works in this case, and which should be closer in speed to id. I will leave you to do a speed test. >>> class bang(list): __hash__ = object.__hash__ >>> s=set() >>> s.add(bang()) >>> s {[]} __eq__ = object.__eq__ should also work instead of the Python implementation I gave in my response to another response." I would expect the already-wrapped id should work in 2.x also. Terry Jan Reedy From mcfletch at vrplumber.com Sun Sep 21 14:19:03 2008 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sun, 21 Sep 2008 14:19:03 -0400 Subject: Some questions about PyOpenGL and wxPython In-Reply-To: <1222017270.7824.3.camel@generator> References: <1222017270.7824.3.camel@generator> Message-ID: <48D69017.50205@vrplumber.com> Clay Hobbs wrote: > I am making a program with wxPython that renders objects in 3D using > PyOpenGL, and I am having some problems. For one thing, I forgot how to > make a double-buffered hardware surface. http://bazaar.launchpad.net/~mcfletch/openglcontext/trunk/annotate/1?file_id=wxcontext.py-20080920224554-ehwlv3u6uc6sb6e2-55 See method wxFlagsFromDefinition, particularly glcanvas.WX_GL_DOUBLEBUFFER > For another thing, > glColor(1.0, 0.0, 0.0) just before the rendering doesn't make the object > red. Please help, I'm a total noob to OpenGL. > Would have to see what you're doing to know what's wrong there. glColor should be working. HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From rsarpi at gmail.com Fri Sep 26 22:01:44 2008 From: rsarpi at gmail.com (icarus) Date: Fri, 26 Sep 2008 19:01:44 -0700 (PDT) Subject: getting global variables from dictionary Message-ID: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> global_vars.py has the global variables set_var.py changes one of the values on the global variables (don't close it or terminate) get_var.py retrieves the recently value changed (triggered right after set_var.py above) Problem: get_var.py retrieves the old value, the built-in one but not the recently changed value in set_var.py. What am I doing wrong? ----global_vars.py--- #!/usr/bin/python class Variables : def __init__(self) : self.var_dict = {"username": "original username"} ---set_var.py --- #!/usr/bin/python import time import global_vars global_vars.Variables().var_dict["username"] = "new username" time.sleep(10) #give enough time to trigger get_var.py ---get_var.py --- #!/usr/bin/python import global_vars print global_vars.Variables().var_dict.get("username") From hugo at hugo.com Sun Sep 7 09:32:56 2008 From: hugo at hugo.com (hugo) Date: Sun, 7 Sep 2008 15:32:56 +0200 Subject: nizoral ketoconazol in Laverlochere ketoconazole side effects generic nizoral medication nizoral pastile loprox Message-ID: nizoral ketoconazol in Laverlochere ketoconazole side effects generic nizoral medication nizoral pastile loprox + + + BUY CHEAP NIZORAL - ORDER NIZORAL ONLINE (ALL CARDS ACCEPTED !!!) http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php + + nizoral conditioner nizoral tablet in Saint Mathias Sur Richelieu generic nizoral 5 nizoral conditioner www viapro com nizoral loprox 200mg in Englehart nizoral 2 cream cheap nizoral medication discountdrugs com generic nizoral dose nizoral not in St-Joseph-de-Beauce nizoral package brand nizoral 2 shampoo in Drumbo generic nizoral 5 buy nizoral review in Meaford hair loss nizoral shampoo cheap nizoral forum in Noel selsun nizoral shampoo and hair loss in St-Georges-de-Beauce http://ibm-news.for-um.de/showthread.php?t=12183 - find nizoral buy nizoral work in St-Georges-de-Cacouna http://ibm-news.for-um.de/showthread.php?t=11648 - cheap nizoral ingredients nizoral package in Coeud'Alene http://ibm-news.for-um.de/showthread.php?t=15383 - cheap nizoral over nizoral ointment in Melrose http://asiadata.ru/areal/viewtopic.php?t=3070 - ketokonazole nizoral pastile in Bromont http://ibm-news.for-um.de/showthread.php?t=10336 - nizoral hair prescription in Placentia http://ibm-news.for-um.de/showthread.php?t=14439 - cheap nizoral ointment nizoral cream side in Charette http://ibm-news.for-um.de/showthread.php?t=9992 - buy nizoral with cheap nizoral ointment in Woodstock http://ibm-news.for-um.de/showthread.php?t=11198 - nizoral shampoo and hair loss cheap nizoral how in Saint Sulpice http://ibm-news.for-um.de/showthread.php?t=14430 - sell nizoral buy nizoral tablets in Eddystone http://draconian.com/dragon-forum/showthread.php?t=17672 - nizoral over the cheap nizoral hydrocortisone in PembrokPines http://ibm-news.for-um.de/showthread.php?t=11650 - nizoral shampoo side versicolor nizoral shampoo in Coral Harbour http://ibm-news.for-um.de/showthread.php?t=11798 - nizoral 1 buy ketoconazole in Riverside http://ibm-news.for-um.de/showthread.php?t=9581 - buy nizoral scalp ketaconazole in Portage la Prairie http://ibm-news.for-um.de/showthread.php?t=9627 - nizoral candida nizoral en in Birtle From fredrik at pythonware.com Thu Sep 4 13:53:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 19:53:32 +0200 Subject: Python and Cyrillic characters in regular expression In-Reply-To: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> Message-ID: phasma wrote: > Hi, I'm trying extract all alphabetic characters from string. > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE) > buf = re.match(string) > > But it's doesn't work. If string starts from Cyrillic character, all > works fine. But if string starts from Latin character, match returns > only Latin characters. can you provide a few sample strings that show this behaviour? From kyosohma at gmail.com Wed Sep 10 13:22:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 10 Sep 2008 10:22:45 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> Message-ID: On Sep 10, 6:48?am, James A. Donald wrote: > On Tue, 9 Sep 2008 14:35:13 -0700 (PDT), icarus > wrote: > > > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > > That did it. > > > one more question... > > > how do I create a pythonw standalone executable that works on w32, > > linux, mac, etc..? > > I have noticed that when applications are written in Python with the > GUI created by PyGTK, it seems that to install the application on each > slightly different version of unix is a fairly major task - although > the creators of PyGTK proudly say that the code will run anywhere, it > definitely will not install anywhere - the code will only run on a > slightly different system after a massive and major rewrite of the > install for that target system. > > Horrible installs are a chronic problem GUI programs driven by > interpreted languages ?Installing visual basic programs that worked on > one Windows machine to work on a very slightly different windows > machine was also a nightmare. > > I have not attempted to create installable wxPython windows, but > generally, "run anywhere" will bite you. ?Still looking for a good > solution to "run anywhere". > > -- > ? ---------------------- > We have the right to defend ourselves and our property, because > of the kind of animals that we are. True law derives from this > right, not from the arbitrary power of the omnipotent state. > > http://www.jim.com/? ? ?James A. Donald I haven't had much trouble getting wxPython applications to run in Windows XP and Ubuntu Hardy Heron. Of course, my GUIs aren't extremely complex, but I did make use of Hammond's PyWin32 package and had to wrap those in Platform aware conditional statements. Plus wx was pretty easy to install in Ubuntu, so that was cool. I can't really comment on other toolkits though. Mike From half.italian at gmail.com Wed Sep 24 22:24:24 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 24 Sep 2008 19:24:24 -0700 (PDT) Subject: empty csv file attachments References: <200563c8-a4d1-45db-aaa1-63f885851b76@s50g2000hsb.googlegroups.com> Message-ID: <0df6db24-b2eb-4b61-8a1f-8f74c91409c5@w39g2000prb.googlegroups.com> On Sep 24, 1:17?pm, Bobby Roberts wrote: > hi group. > > I'm new to python but a veteran at programming. ?This one has me > stumped. ?I have a simple contact form which the user fills out. ?The > email is sent to the site user as well and it is delivered with the > content in the body of the email as well in nice order. ?I have > modified my code to also send the content as a csv attachment. ?On the > server, the file is perfectly generated with content. ?The attachment, > however, is completely blank. ?Any ideas what that could be? ?My code > snippet is shown below: > > ? ? ? if int(attachmenttype)==2 or int(attachmenttype)==3: > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? if field=='last_name': > ? ? ? ? ? ? myfilename=ctx.request.field_value(field)+'.txt' > ? ? ? ? if myfilename=='': > ? ? ? ? ? myfilename='tempfile.txt' > ? ? ? ? mypath= mynewfilepath + '/' + myfilename > ? ? ? ? f=open(mypath, 'w') > ? ? ? ? mynewstring='' > ? ? ? ? counter=0 > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? if field != 'inquiry_required': > ? ? ? ? ? ? mynewstring=mynewstring + field +',' > ? ? ? ? if mynewstring[-1]==',': > ? ? ? ? ? mynewstring=mynewstring[0:len(mynewstring)-1] > ? ? ? ? f.write(mynewstring) > ? ? ? ? f.write ('\n') > > ? ? ? ? mynewstring='' > ? ? ? ? counter=1 > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? fielddata=ctx.request.field_value(field) > ? ? ? ? ? if counter==1: > ? ? ? ? ? ? dummydata=0 > ? ? ? ? ? else: > ? ? ? ? ? ? mynewstring=mynewstring + '"' + fielddata.replace('"','') > + '",' > ? ? ? ? ? counter = counter + 1 > ? ? ? ? if mynewstring[-1]==',': > ? ? ? ? ? mynewstring=mynewstring[0:len(mynewstring)-1] > ? ? ? ? f.write(mynewstring) > ? ? ? ? f.write('\n') > ? ? ? ? f.close > ? ? ? ? attachments.append('/'.join((ctx.request.library, > myfilename))) > > ?[snip... sends email just after this] > > any ideas? I would sprinkle some print statements in there to narrow it down... ~Sean From simon at brunningonline.net Fri Sep 12 05:21:11 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 12 Sep 2008 10:21:11 +0100 Subject: handling uncaught exceptions with pdb? In-Reply-To: <7xmyifpt68.fsf@ruckus.brouhaha.com> References: <7xmyifpt68.fsf@ruckus.brouhaha.com> Message-ID: <8c7f10c60809120221j2266f84cq3ea8a8b462508b69@mail.gmail.com> 2008/9/10 Paul Rubin <"http://phr.cx"@nospam.invalid>: > I think I've asked about this before, but is there a way to set up > Python to handle uncaught exceptions with pdb? http://code.activestate.com/recipes/65287/ -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From martin at v.loewis.de Wed Sep 17 19:00:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 18 Sep 2008 01:00:19 +0200 Subject: PYPI, some troubles In-Reply-To: References: Message-ID: <48d18c03$0$2322$9b622d9e@news.freenet.de> > 1. when I commit a new release to PYPI, I can use stored data (by my > browser: Name, package summary, keywords etc), but in the last line > (classification) I had to chose all those lines from the very > beginning, moreover, if I click at one of them without pressing "CTRL" > all my choices drops & I have to type it from the very beginning (I > use Mozilla Firefox 3.0 but I don't think it's the matter). Then I recommend not to use the browser to commit the new releases. Instead, arrange for your setup.py to contain all the relevant data, and use python setup.py register to add the new release. > 2. Another issue: I have attached my source code (openopt0.19.tar.bz2 > file), now I can see it in "files for openopt 0.19" section (http:// > pypi.python.org/pypi) but easy_install can't find the package: Try calling the file openopt-0.19.tar.bz2. If that doesn't help, contact the setuptools mailing lists. Regards, Martin From dblubaugh at belcan.com Mon Sep 29 15:44:10 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 15:44:10 -0400 Subject: PYTHON WORKING WITH PERL ?? In-Reply-To: <20080929133153.fc745f9c.darcy@druid.net> References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> <20080929133153.fc745f9c.darcy@druid.net> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D905A@AWMAIL04.belcan.com> Sir, You are absolutely correct. I was praying to G_d I did not have to slaughter my project's source code in this manner. However, like life itself, I was given legacy source code (i.e. someone else errors to fix) in Perl. However, I have just found out that there is a way to import the Perl interpreter within Python!!! I now believe I can utilize python as the main platform to develop the project upon !! Thanks, David -----Original Message----- From: D'Arcy J.M. Cain [mailto:darcy at druid.net] Sent: Monday, September 29, 2008 1:32 PM To: Blubaugh, David A. Cc: python-list at python.org Subject: Re: PYTHON WORKING WITH PERL ?? On Mon, 29 Sep 2008 13:16:14 -0400 "Blubaugh, David A." wrote: > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? Such as > utilizing python for internet programming and then utilize perl for > text processing and systems programming? Is this even feasible??? I don't see why not but I also question if it is a good idea. Once you have all your objects and low level methods written in Python it just makes sense to re-use them rather than trying to duplicate the functionality in another language. Of course, sometimes we don't have control over our entire environment so yes, you can mix them if you have to. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From yellowblueyellow at gmail.com Thu Sep 11 18:21:02 2008 From: yellowblueyellow at gmail.com (yellowblueyellow at gmail.com) Date: Thu, 11 Sep 2008 15:21:02 -0700 (PDT) Subject: SSH using PEXPECT References: Message-ID: <4cc538ef-3b08-404c-b107-ff6605c307a2@t54g2000hsg.googlegroups.com> On Sep 10, 7:01?pm, Sean DiZazzo wrote: > On Sep 10, 6:04?pm, yellowblueyel... at gmail.com wrote: > > > > > Hey , I need toSSHinto a server .. (10.8.42.38) usingpexpectthe > > username is 'admin' and password is 'abc123' so far i have the > > following code > > > importpexpect > > import sys > > import time > > import os > > > foo =pexpect.spawn('sshad... at 10.8.42.38') > > ssh_newKey = 'Are you sure you want to continue connecting' > > > foo.expect = ssh_newKey > > foo.send = 'yes' > > foo.expect = 'password:' > > foo.send = 'abc123' > > > --------------------------------------------------------------------------- ---------------------- > > > does this look right? I am using windows and for reason it wont let me use pexpect even tho I have CYGWIN installed I get the following error Traceback (most recent call last): File "new.py", line 1, in import ssh_session File "C:\Python25\lib\ssh_session.py", line 7, in from pexpect import * File "C:\Python25\lib\site-packages\pexpect.py", line 85, in support it. Pexpect is intended for UNIX-like operating systems.""") ImportError: No module named resource any ideas? Thanks A critical module was not found. Probably this operating system does not support it. Pexpect is intended for UNIX-like operating systems. > > > if not , could someone suggest a way to do this .. > > your help is much appreciated > > https://svn.lal.in2p3.fr/projects/CMT/CMTManagement/utils/ssh_session.py > > I use a modified version of this. ?Simple and effective. > > import ssh_sessionssh= ssh_session.ssh_session(user, host, password) > printssh.ssh("ls -l /tmp") > > Thanks Eric and Nigel! > > ~Sean From aahz at pythoncraft.com Fri Sep 26 20:32:47 2008 From: aahz at pythoncraft.com (Aahz) Date: Fri, 26 Sep 2008 17:32:47 -0700 Subject: PyCon 2009 Call for Proposals Message-ID: <20080927003247.GA12336@panix.com> Call for proposals -- PyCon 2009 -- =============================================================== Want to share your experience and expertise? PyCon 2009 is looking for proposals to fill the formal presentation tracks. The PyCon conference days will be March 27-29, 2009 in Chicago, Illinois, preceded by the tutorial days (March 25-26), and followed by four days of development sprints (March 30-April 2). Previous PyCon conferences have had a broad range of presentations, from reports on academic and commercial projects to tutorials and case studies. We hope to continue that tradition this year. Online proposal submission will open on September 29, 2008. Proposals will be accepted through November 03, with acceptance notifications coming out on December 15. For the detailed call for proposals, please see: We look forward to seeing you in Chicago! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From adelle at akemi.com.au Sun Sep 14 23:25:27 2008 From: adelle at akemi.com.au (Adelle Hartley) Date: Mon, 15 Sep 2008 13:25:27 +1000 Subject: Good programming style In-Reply-To: References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: <48CDD5A7.8000705@akemi.com.au> Grant Edwards wrote: > When packages as significant as wxPython use naming conventions > other than PEP 8, I find it hard to make a case that the PEP 8 > naming convention is any better than any other. This relates to a question I was thinking about... I'm looking at porting a library that was written for COM and .Net to work as a Python module, and was wondering whether it would be better to stick to the library's current naming convention so that the API is as similar as possible on each platform, or to adopt a "when in Rome..." policy and follow the "most mainstream" naming pattern for each platform/language. Adelle. From jake at vapourforge.com Thu Sep 18 11:42:45 2008 From: jake at vapourforge.com (Jake Anderson) Date: Fri, 19 Sep 2008 01:42:45 +1000 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <48D276F5.6040608@vapourforge.com> psyco might help a fair bit (10x-40x) here ;-> perhaps look at dumping the data into sqlite then pulling it back out. It (or the other databases) are designed for tossing around large lumps of data. Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > > but no improvements. > > Many thanks, Alex > -- > http://mail.python.org/mailman/listinfo/python-list > -- Vapour Forge Jake Anderson Project Manager Mobile: 0412 897 125 Email: jake at vapourforge.com Web Page: www.vapourforge.com Your source for custom IT services -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: vf.gif Type: image/gif Size: 1484 bytes Desc: not available URL: From code at pizzashack.org Mon Sep 22 17:26:51 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 22 Sep 2008 17:26:51 -0400 Subject: test list post Message-ID: <20080922212651.GE26713@dragontoe.org> Sorry for the noise, my recent posts seem to have been eaten by the list management software, as far as I can tell. Just testing if that's still the case. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mensanator at aol.com Thu Sep 4 13:26:01 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 4 Sep 2008 10:26:01 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: <06d8438f-b1a6-4662-aac7-8e334521107b@s20g2000prd.googlegroups.com> On Sep 4, 11:13?am, "David C. Ullrich" wrote: > In article > <719910b1-3776-4bf2-a0b6-236f3167e... at 25g2000prz.googlegroups.com>, > > > > > > ?Mensanator wrote: > > On Sep 3, 2:18?pm, Laszlo Nagy wrote: > > > bearophileH... at lycos.com wrote: > > > > Empty Python lists [] don't know the type of the items it will > > > > contain, so this sounds strange: > > > > >>>> sum([]) > > > > > 0 > > > > > Because that [] may be an empty sequence of someobject: > > > > You are right in that sum could be used to sum arbitrary objects. > > > However, in 99.99% of the cases, you will be summing numerical values. > > > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > > > is very logical to return zero for empty sequences. > > > No it isn't. Nothing is not 0, check with MS-Access, for instance: > > > Null + 1 returns Null. Any arithmetic expression involving a > > Null evaluates to Null. Adding something to an unknown returns > > an unknown, as it should. > > > It is a logical fallacy to equate unknown with 0. > > Which has nothing to do with the "right" value for an > empty sum. I'm less concerned about the "right" value than a consistent value. I'm fairly certain you can't get 0 from a query that returns no records, so I don't like seeing empty being treated as 0, even if it means that in set theory because databases aren't sets. > If they hear about what you said here in > sci.math they're gonna kick you out They usually don't kick me out, just kick me. > - what do you > imagine the universally accepted value of \sum_{j=1}^0 > is? I can't follow your banter, so I'm not sure what it should be. > > > > > > > For example, the water table elevation in ft above Mean Sea Level > > is WTE = TopOfCasing - DepthToWater. > > > TopOfCasing is usually known and constant (until resurveyed). > > But DepthToWater may or may not exist for a given event (well > > may be covered with fire ants, for example). > > > Now, if you equate Null with 0, then the WTE calculation says > > the water table elevation is flush with the top of the well, > > falsely implying that the site is underwater. > > > And, since this particular site is on the Mississippi River, > > it sometimes IS underwater, but this is NEVER determined by > > water table elevations, which, due to the CORRECT treatment > > of Nulls by Access, never returns FALSE calculations. > > > >>> sum([]) > > 0 > > > is a bug, just as it's a bug in Excel to evaluate blank cells > > as 0. It should return None or throw an exception like sum([None,1]) > > does. > > > > Same way, if we would have a prod() function, it should return one for > > > empty sequences because X*1 = X. The neutral element for this operation > > > is one. > > > > Of course this is not good for summing other types of objects. But how > > > clumsy would it be to use > > > > sum( L +[0] ) > > > > or > > > > if L: > > > value = sum(L) > > > else: > > > value = 0 > > > > instead of sum(L). > > > > Once again, this is what sum() is used for in most cases, so this > > > behavior is the "expected" one. > > > > Another argument to convince you: the sum() function in SQL for empty > > > row sets returns zero in most relational databases. > > > > But of course it could have been implemented in a different way... I > > > believe that there have been excessive discussions about this decision, > > > and the current implementation is very good, if not the best. > > > > Best, > > > > Laszlo > > -- > David C. Ullrich From tino at wildenhain.de Fri Sep 19 03:34:43 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 19 Sep 2008 09:34:43 +0200 Subject: Python newbie In-Reply-To: References: Message-ID: <48D35613.1000403@wildenhain.de> Hi, Mladen Gogala wrote: > I am a Python newbie who decided to see what that Python fuss is all about. > Quite frankly, I am a bit perplexed. After having had few months of > experience with Perl (started in 1994 with Perl v4, and doing it ever > since) , here is what perplexes me: > > perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' > > The equivalent in Python looks like this: > > Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) > [GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a=[1,2,3] >>>> map((lambda x: 2*x),a) > [2, 4, 6] >>>> map((print),a) > File "", line 1 > map((print),a) > ^ > SyntaxError: invalid syntax >>>> for x in a: print x > ... > 1 > 2 > 3 >>>> for x in a: x=2*x > ... >>>> for x in a: print x > ... > 1 > 2 > 3 > > There are several questions: > > 1) Why is the array "a" unchanged after undergoing a transformation with > map? it isn't transformed. You get a new list as result. > 2) Why is it illegal to pass a built-in function "print" to map? because its not a function but a statement. If it was a function you would call it print(x) not print x. > 3) Why is the array "a" unchanged after undergoing an explicit > transformation with the "for" loop? To understand this, python knows immutable objects and mutable. Immutables are strings, tuples , ... and integers. This means the operation above all create a new integer object in memory and assign it to the name x (where you use = ) > 4) Is there an equivalent to \$a (Perl "reference") which would allow me to > decide when a variable is used by value and when by reference? No, python always uses by reference. > PHP also allows changing arrays with "foreach" loop: > #!/usr/local/bin/php > $a=array(1,2,3); > foreach($a as &$x) { $x=$x*2; } > array_walk($a,create_function('$a','print("$a\n"); ')); > ?> > > How can I make sure that > for x in a: x=2*x > > actually changes the elements of the array "a"? >>> l=range(10) >>> for i in range(len(l)): ... l[i]*=2 ... >>> l [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From hniksic at xemacs.org Fri Sep 12 09:53:51 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Sep 2008 15:53:51 +0200 Subject: Accessing __slots__ from C References: <87k5diex3m.fsf@mulj.homelinux.net> <87ej3p7ira.fsf@mulj.homelinux.net> Message-ID: <87abed79n4.fsf@mulj.homelinux.net> Chris writes: >> In my experience, as long as you're >> accessing simple slots, you should notice a difference. > > (I'm not sure what you mean by a 'simple slot'. I mean a slot defined by __slots__ = slot1, slot2, slot3, ..., without descriptors or specific __getattribute__ code on top of that. > - GetAttr: 46 seconds (46 seconds) > outside the loop: > PyObject *name = PyString_FromString("attr_one"); I think you should be using PyString_InternFromString, but it will probably still be slower than PyList_GET_ITEM, which is still much simpler. The next optimization is the one proposed by Carl, which should yield speed comparable to PyList_GET_ITEM. See my response in that subthread for details. From saluk64007 at gmail.com Fri Sep 26 10:54:51 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Fri, 26 Sep 2008 07:54:51 -0700 Subject: Not fully OO ? In-Reply-To: <48DCC786.2040407@wildenhain.de> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: Depending on the scale of the website I am making, how much I care about editing it in the future, and how much I just want to get something up, I will occasionally use php. And I am a self confessed php hater :) But it's generally the fastest way I know to get something up. So even terrible languages can have their uses! From pmaupin at gmail.com Sun Sep 7 14:17:04 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 7 Sep 2008 11:17:04 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: On Sep 7, 12:30?pm, Mensanator wrote: > On Sep 6, 11:05 pm, Steven D'Aprano > Sheesh. That's not a problem, because Python is not trying to be a > > dialect of SQL. > > And yet, they added a Sqlite3 module. Does that mean that, because there is an 'os' module, Python is trying to compete with Linux and Windows? This is starting to feel like a troll, but JUST IN CASE you are really serious about wanting to get work done with Python, rather than complaining about how it is not perfect, I offer the following snippet which will show you how you can test the results of a sum() to see if there were any items in the list: >>> class MyZero(int): ... pass ... >>> zero = MyZero() >>> x=sum([], zero) >>> isinstance(x,MyZero) True >>> x = sum([1,2,3], zero) >>> isinstance(x,MyZero) False >>> From Lie.1296 at gmail.com Sat Sep 27 14:12:00 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 27 Sep 2008 11:12:00 -0700 (PDT) Subject: Borg vs Singleton vs OddClass Message-ID: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> This is probably unrelated to Python, as this is more about design pattern. I'm asking your comments about this design pattern that is similar in functionality to Singleton and Borg: to share states. I'm thinking about this design pattern (I don't know if anyone has ever thought of this pattern before): class OddClass(object): def __init__(self): global OddClass OddClass = self def __call__(): return self The OddClass is a class that would overwrite its own class definition at its first instantiation. OddClass defines __call__ so that subsequent "instantiation" (technically it is no more an instantiation, but Duck Typing says it does) of the class would return the single instance. It do have a problem though, that you can't do isinstance(a, OddClass) since the name OddClass no longer refers to the OddClass class descriptor, but to an instance of OddClass. I don't think that's much of a problem though since using isinstance() is generally not a good idea in python (although OddClass do use global which many people, including me, would usually consider as bad form). The problem with Borg is that it is not inheritable (in certain sense[1]) and only work with old-style class (which is due to be completely removed on py3k)[2], Singleton and OddClass is inheritable. >>> class Singleton(object): ... >>> s = Singleton() >>> class A(Singleton): pass >>> class B(Singleton): pass >>> a = A() >>> b = B() >>> s.foo, a.bar = "bar", 42 >>> b.foo, b.bar ... Traceback, Attribute Error ... >>> class OddClass(object): ... >>> s = OddClass() >>> class A(OddClass): pass >>> class B(OddClass): pass >>> a = A() >>> b = B() >>> s.foo, a.bar = "bar", 42 >>> b.foo, b.bar ... Traceback, Attribute Error ... but for Borg, see [1] [1] classes that inherits from Borg shares state not only within children, but also with their parents and cousins. That means inheriting from Borg is useless, and that also means one Borg code for every state sharing classes, instead of inheriting from Singleton/ OddClass. In code: >>> class Borg: ... >>> class A(Borg): ... >>> class B(Borg): ... >>> s, a, b = Borg(), A(), B() >>> s.foo, a.attr = "bar", 42 >>> b.foo, b.attr "bar" 42 >>> # we want b.foo and b.attr to raise error since .foo, and .bar isn't B's shared state, it's A's and Borg's shared state [2] Actually in new-style class, they say Borg can use __slots__, but they say it'd be slightly more complex From steve at holdenweb.com Fri Sep 12 08:23:48 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 08:23:48 -0400 Subject: lacking follow-through In-Reply-To: References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: castironpi wrote: [...] > For example, I sometimes hear people talk about salary as though it > were social approval, and vice versa. Even though the analogy doesn't > hold in every case generally, it is still a good way to express > yourself in many contexts, and especially when the more precise word > isn't on the tip of your tongue. Perhaps under those circumstances the better choice is to hold off posting and do some research until you come up with the proper word. Precision in the expression of ideas encourages debate, whereas sloppy "just write what you feel" is likely to result in hostile responses, as it causes the perception that you value your own time more than that of the people you attempt to engage. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fredrik at pythonware.com Mon Sep 15 16:17:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 22:17:37 +0200 Subject: append on lists In-Reply-To: References: Message-ID: Armin wrote: > just a dumb question. > > Let a = [1,2,3,4,5] > > Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? yeah, that's a dumb question. From thomas.troeger.ext at siemens.com Mon Sep 22 10:43:23 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Mon, 22 Sep 2008 16:43:23 +0200 Subject: Reading Windows CSV file with LCID entries under Linux. Message-ID: Dear all, I've stumbled over a problem with Windows Locale ID information and codepages. I'm writing a Python application that parses a CSV file, the format of a line in this file is "LCID;Text1;Text2". Each line can contain a different locale id (LCID) and the text fields contain data that is encoded in some codepage which is associated with this LCID. My current data file contains the codes 1033 for German and 1031 for English US (as listed in http://www.microsoft.com/globaldev/reference/lcid-all.mspx). Unfortunately, I cannot find out which Codepage (like cp-1252 or whatever) belongs to which LCID. My question is: How can I convert this data into something more reasonable like unicode? Basically, what I want is something like "Text1;Text2", both fields encoded as UTF-8. Can this be done with Python? How can I find out which codepage I have to use for 1033 and 1031? Any help appreciated, Thomas. From stefan_ml at behnel.de Fri Sep 5 12:05:20 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Sep 2008 18:05:20 +0200 Subject: Extract Information from Tables in html In-Reply-To: References: Message-ID: <48c158c0$0$11090$9b4e6d93@newsspool1.arcor-online.net> Hi, Jackie Wang wrote: > Here is a html code: > > > > Premier Community Bank of Southwest Florida >
> Fort Myers, FL > > > > My question is how I can extract the strings and get the results: > Premier Community Bank of Southwest Florida; Fort Myers, FL Use lxml.html. Something like this should do what you want: >>> from lxml import html >>> tree = html.parse("http://server.org/thefile.html") >>> all_tds = tree.findall("//td") >>> for td in all_tds: ... print( td.xpath("normalize-space()") ) Tweak as you see fit, tree iteration is at your service in case you need more. http://codespeak.net/lxml/ Stefan From bearophileHUGS at lycos.com Mon Sep 22 10:35:50 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 07:35:50 -0700 (PDT) Subject: A bit weird dictionary behavior References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: Tino Wildenhain: > Wouldn't > len([x for x in iterable if x==y]) > or even shorter: > iterable.count(y) > not work and read better anyway? The first version creates an actual list just to take its length, think about how much memory it may use. The second version requires the 'iterable' object to have a count() method, and in general this is false. > even calculating with boolean values isn't neccessary > since 'and' and 'foo if bar else blub' are working much better > so the type coalescing > bool - int - float can really go away. I don't understand. Bye, bearophile From castironpi at gmail.com Sat Sep 13 01:45:52 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 12 Sep 2008 22:45:52 -0700 (PDT) Subject: ctypes: Get full contents of character array References: Message-ID: <223fde52-b1aa-4d69-b374-2cf07973f2b5@73g2000hsx.googlegroups.com> On Sep 12, 6:38?pm, overdrig... at gmail.com wrote: > Hello! > > I wanted to get the full contents of a character array stored in a > struct, i.e. > _fields_ = [...("array", c_char * 12)...] > however, ctypes seems to try to return struct.array as a Python string > rather than a character array, and stops as soon as it encounters a > null within the character array. > > I ended up having to define a dummy struct > class dummystruct(Structure): > ? ? _fields_ = [] > > and declare array as: > ("array", dummystruct) > > then use string_at(byref(struct.array), 12). > > Is this really the best way of doing it? Is there no better way to > work around ctypes 'guess what you want' behaviour? > > Thanks in advance, > Rodrigo Rodrigo, If you have the option to change your declaration to c_byte* 12, you have more options. This example prints the null character you wanted. from ctypes import * import struct class S( Structure ): _fields_= [ ( 'array', c_byte* 12 ) ] s= S() #initialize struct.pack_into( '7s', s.array, 0, 'abc\x00def' ) #prototype and call PyString_FromStringAndSize prototype= PYFUNCTYPE( py_object, POINTER( c_byte ), c_size_t ) PyString_FromStringAndSize= prototype( ( "PyString_FromStringAndSize", pythonapi ) ) x= PyString_FromStringAndSize( s.array, 12 ) print repr( x ) #prototype and call PyString_FromString for contrast prototype= PYFUNCTYPE( py_object, POINTER( c_byte ) ) PyString_FromString= prototype( ( "PyString_FromString", pythonapi ) ) x= PyString_FromString( s.array ) print repr( x ) /Output: 'abc\x00def\x00\x00\x00\x00\x00' 'abc' From vinay_sajip at yahoo.co.uk Fri Sep 26 03:14:13 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 26 Sep 2008 00:14:13 -0700 (PDT) Subject: SimpleXMLRPCServer -- turning off request log? References: Message-ID: <15c9f762-2daf-4d1f-b182-4e7e1e982579@w7g2000hsa.googlegroups.com> On Sep 26, 2:01 am, m... at pixar.com wrote: > My SimpleXMLRPCServer program prints to stderr a line like > this for each request: > > ohm..pixar.com - - [25/Sep/2008 17:57:50] "POST /RPC2 HTTP/1.0" 200 - > > Is there a way to turn thisloggingoff? I have RTFM and can't > seem to find a way to do so. > >From the documentation (2.5): class SimpleXMLRPCServer( addr[, requestHandler[, logRequests[, allow_none[, encoding]]]]) "If logRequests is true (the default), requests will be logged; setting this parameter to false will turn off logging." Did you try setting logRequests to false? Regards, Vinay Sajip From FettManChu at gmail.com Tue Sep 16 21:50:36 2008 From: FettManChu at gmail.com (Fett) Date: Tue, 16 Sep 2008 18:50:36 -0700 (PDT) Subject: Python Linear Programming on Ubuntu Message-ID: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> I am trying to find a wrapper to do linear programming within python. I am using an ubuntu machine and I have apt-get'd lp_solve, which works just fine. If someone knows of a wrapper that will work with that that'd be great. I also heard that scipy has a wrapper, however, I can't find any documentation on it, nor can I seem to find it with dir(). If anyone knows where there is good documentation on this I would love to use that (the more native to python the better imo). I have tried many things, including http://lpsolve.sourceforge.net/5.5/Python.htm, openopt, and cvxopt. I can't seem to find any with enough documentation to get me off the ground. Some I can't compile, some I can't even find out how to compile. If anyone knows of an LP package (preferably with IP as well, like lp_solve has), that interfaces well with python and has enough documentation to get a dependency newb like myself off the ground that would be great. From mark.fink1 at googlemail.com Sun Sep 28 15:15:50 2008 From: mark.fink1 at googlemail.com (mark) Date: Sun, 28 Sep 2008 12:15:50 -0700 (PDT) Subject: standalone buildbot possible/ don't have a remote Message-ID: <41a76fd8-47e3-4eb8-b980-11baf8dff0b2@u65g2000hsc.googlegroups.com> I want to start small and setup a buildbot on one machine (no slaves). I hope this is possible. I assume I only need one master in this case (without slave config)??? from my master.cfg c['slaves'] = [] ... (rest of the sample config) b1 = {'name': "buildbot-full", # 'slavename': "bot1name", 'builddir': "full", 'factory': f1, } Do I need some configuration that the builder uses the master instance? I experimented a bit and searched for a similar configuration so far without success :-(( I did run the buildbot testsuite without errors. Here is one problem the buildbot writes out on console: 2008-09-28 20:43:10+0200 [-] maybeStartBuild : [] [] 2008-09-28 20:43:10+0200 [-] : want to start build, but we don't have a remote Another thing I can think of is to set up two processes on one machine, which would be a bit of an overhead. Cheers, Mark From larry.bates at vitalEsafe.com Wed Sep 3 22:06:14 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Wed, 03 Sep 2008 21:06:14 -0500 Subject: Access to Windows "Add/Remove Programs"? In-Reply-To: References: Message-ID: Sean DiZazzo wrote: > Hi all, > > I'm trying to find a way to get a list of all the installed programs > on a Windows box via Python. I thought of a few hacks that might > partially work, and then thought about "Add/Remove Programs" Seems > like the right way to go. I looked over the pywin32 docs a bit, but > nothing slapped me in the face. > > Is there any reliable way to get at that info? > > Thanks in advance, > > ~Sean I would guess that that program gets the information from the registry. Maybe looking at HKEY_LOCAL_MACHINE\SOFTWARE or HKEY_CURRENT_USER\Software branches? -Larry From seandavi at gmail.com Tue Sep 23 14:25:48 2008 From: seandavi at gmail.com (Sean Davis) Date: Tue, 23 Sep 2008 11:25:48 -0700 (PDT) Subject: Detecting the first time I open/append to a file References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> Message-ID: On Sep 23, 2:02?pm, tkp... at hotmail.com wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a ?single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > ? ? for param in range(10): > ? ? ? ? simulate(param) > > def simulate(parameter): > ? ? 'Lots of code followed by: > ? ? with open(summaryFn, 'ab') as f: > ? ? ? ? writer = csv.writer(f) > ? ? ? ? writer.writerow(header) > ? ? ? ? writer.writerow(Sigma) > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. You could use os.path.exists() to check if the file is there. However, the file could have been left over from a previous execution, etc. What might make sense is to open the file only once, store the file handle, and write to that throughout the execution. Sean From asifsshl917 at googlemail.com Sat Sep 20 11:02:45 2008 From: asifsshl917 at googlemail.com (ghghghxdghdghdxg) Date: Sat, 20 Sep 2008 08:02:45 -0700 (PDT) Subject: medicine cheap nizoral good for cheap nizoral drug order nizoral shampoo for hair loss generic nizoral cream used Message-ID: medicine cheap nizoral good for cheap nizoral drug order nizoral shampoo for hair loss generic nizoral cream used + + + BUY CHEAP NIZORAL - ORDER NIZORAL ONLINE (ALL CARDS ACCEPTED !!!) Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL + + + + * nizoral order nizoral reviews magicbluepill com buy dose order nizoral scalp fluid in Wadena brand nizoral side effect selsun blue in Magrath 200mg ketoconazole nizoral available in SpokanValley generic nizoral anti dandruff shampoo buy nizoral shampoo side in Bloomington buy nizoral online brand nizoral 100 in Barachois 2 nizoral generic nizoral anti dandruff shampoo in Venise-en-Quebec brand nizoral shampoo hairloss cheap nizoral free in Mascouche - price of nizoral medications in Logan Lake - buy nizoral over the price of nizoral www viagraonlinepharmacy com - ketoconazole 2 doctor in Granisle - buy nizoral to brand nizoral 1 in Golden - generic nizoral cream side nizoral 100 in Hazlet - cheap nizoral janssen cilag hair loss nizoral in Visalia - generic nizoral antifungal cheap nizoral medication in Killarney - anti dandruff in nizoral in Nelson House - buy nizoral scalp buy nizoral wiki in Ponce - nizoral with cheap nizoral ingredients en Saint-Quentin - order nizoral over the cheap nizoral janssen cilag in Claremont - nizoral used for cheap nizoral good for www dionpills org - generic nizoral dandruff shampoo in Calmar - buy nizoral sampon of nizoral www cartonionline com generic nizoral shampoo brand nizoral shampoo for hairloss doctor From larry.bates at vitalEsafe.com Sat Sep 13 11:14:02 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 13 Sep 2008 10:14:02 -0500 Subject: testing if another instance of a script is already running In-Reply-To: References: Message-ID: <_IQyk.32260$Ep1.31830@bignews2.bellsouth.net> Strato wrote: > Hi folks, > > I want to write some kind of test to check at startup if another > instance of my script is already running. > > I don't want to handle writing of a PID file because it is too > Unix/Linux specific way to do this, and I need to keep the code to be > cross-platform. > > I think the better way to achieve this is to use some process control, > but I'm a neebie and I don't see how to do this in a safe and clean way. > > Any idea ? > > Best regards, > Strato Here is a recipe for Windows version of singleinstance class: http://code.activestate.com/recipes/474070/ and I wrote and contributed the equivalent Linux version: http://code.activestate.com/recipes/546512/ Hope this helps. -Larry From deets at nospam.web.de Tue Sep 23 03:09:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 23 Sep 2008 09:09:07 +0200 Subject: Using vObject In-Reply-To: References: Message-ID: <6jrj0mF4ngv3U1@mid.uni-berlin.de> Joshua Gardner schrieb: > I'm brand new to USENET so please bear with me. > > I'm writing a specialized to-do list app. I'm using Django but this is > not a question about Django. It has to have recurring tasks set by the > managers for the employees to then check off. > > I've got pretty much everything in the app worked out, except for one > thing: the repeating tasks. I want to have it so that the manager puts > in a repeating task with a description and a repeat rule. This rule then > generates simpler one-time tasks. These one-time tasks have a > description, a time (a datetime.datetime object) and "completed" boolean. > > I've looked around and think I have these options: > 1. Manually put it all together with another Django model that > implements the repeat rules. > 2. Do the same thing but use dateutil.rrule to help. > 3. Use the icalendar (http://codespeak.net/icalendar/) module to access > ICS files. > 4. vObject (http://vobject.skyhouseconsulting.com/) to do the same. > > I think I want to use vObject because it uses dateutil and the > management can easily manage tasks from a desktop app. > > Only thing is that I find vObject's documentation very cryptic and was > wondering if anybody here could shed some light on how to use vObject. A > simple "getting-started" tutorial or something similar would be nice. I think you are going down a wrong route here. I have implemented a reservation management application for a museum in TurboGears - and while I use icalendar to support ICS-based viewing of the reservations, I completely manage * store them based on my own model. In case of the recurring events, I have one master-event, that defines the start & recurrence-options. I then create child-events that essentially are write-protected (all editing goes to the master), and serve only as place-holder. But if you want, you can "detach" them, to make them live on their own. The reason for this is simple: if you want to display views of your tasks based on e.g. a specific day, you can query the database. Simple queries will yield a list of tasks needed. Whereas all ICS-based approaches listed above, including vObject, would mean that you - extract *all* the ics-data from the database, not really knowing if there is anything relevant in there for the current view - potentially expand the events in there, manually or through some methods the libraries expose - filter the results. All of this is going to consume much useless time. So I would suggest you use approach 1, possibly 2 (don't know rrule). Diez From sukhrajtakhar at hotmail.com Tue Sep 30 11:39:46 2008 From: sukhrajtakhar at hotmail.com (rajtakhar) Date: Tue, 30 Sep 2008 08:39:46 -0700 (PDT) Subject: Great New Linux Handheld Console & UMPC!! Message-ID: <0372789a-0493-4663-ae65-9377291234f7@m73g2000hsh.googlegroups.com> The GP2X Wiz and Pandora units will open up the face of homebrewgames, one is a pure Gaming console, with hundreds of emulatorswritten for, the other is a console/UMPC Check the data here: http://gp2xwiznpandora.blog.co.uk/ From bmihelac at gmail.com Fri Sep 12 11:08:18 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Fri, 12 Sep 2008 08:08:18 -0700 (PDT) Subject: setattr in class Message-ID: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Hi all - when trying to set some dynamic attributes in class, for example: class A: for lang in ['1', '2']: exec('title_%s = lang' % lang) #this work but is ugly # setattr(A, "title_%s" % lang, lang) # this wont work setattr(A, "title_1", "x") # this work when outside class print A.title_1 print A.title_2 I guess A class not yet exists in line 4. Is it possible to achive adding dynamic attributes without using exec? thanks, Bojan From __peter__ at web.de Fri Sep 26 12:21:41 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Sep 2008 18:21:41 +0200 Subject: Understanding (and getting rid) of optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a References: <85ec721a-b5a2-4f22-9e37-bda4a0f9eb81@z72g2000hsb.googlegroups.com> Message-ID: hofer wrote: > Hi, > > I get following warning with a python script: > > > optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will > return a signed string in Python 2.4 and up > > > my code: > from optparse import OptionParser > > if __name__ == '__main__': > parser = OptionParser() > parser.add_option('-G','--green',action= 'store_const', const= > '#00FF00' , dest='color', > default='#808080', > help='life is so green') > parser.add_option('-R','--red',action= 'store_const', const = > '#FF0000' , dest='color', > help='I just see red') > # add more elaborated command line parsing and help text here > (options,argv) = parser.parse_args() > print 'options',options > > I assume python wants to tell me that newer version will behave > differently for numeric arguments > > What I wonder is: Why do I get the warning if my code doesn't try to > parse any numbers? The culprit is print options If you look into optparse.py you'll see that part of the __repr__() method of the Value class is the object's address, roughly "%x" % id(self) id(self) is just the Value instance's address in memory which seems to be >= 0x80000000 (assuming you are on a 32-bit machine) in your case. Such numbers were interpreted as negative ints but are now treated as positive longs. Read http://www.python.org/dev/peps/pep-0237/ for details. > Is there any way to get rid of the warning without having to change > the python version? > (I noticed, the warning disappears if I remove the line printing > options) You can print options.__dict__ instead of options with little loss of information, or turn the warning off python -Wignore::FutureWarning myscript.py Peter From circularfunc at gmail.com Thu Sep 11 16:21:46 2008 From: circularfunc at gmail.com (process) Date: Thu, 11 Sep 2008 13:21:46 -0700 (PDT) Subject: Is len O(n) or O(1) ? References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> Message-ID: <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> ok but if len is O(1) then it doesnt matter? compared to if not lista: return [] i mean. From fredrik at pythonware.com Tue Sep 2 00:34:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Sep 2008 06:34:53 +0200 Subject: Numeric literal syntax In-Reply-To: <878wubp5mz.fsf@benfinney.id.au> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> <878wubp5mz.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > I would argue that the precedent, already within Python, for using a > space to separate pieces of a string literal, is more important than > precedents from other programming languages. that precedent also tells us that the whitespace approach is a common source of errors. taking an approach that's known to be error-prone and applying it to more cases isn't necessarily a great way to build a better language. From maric at aristote.info Mon Sep 15 08:42:43 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 14:42:43 +0200 Subject: Case-insensitive string compare? In-Reply-To: References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809051331.40609.maric@aristote.info> Message-ID: <200809151442.43981.maric@aristote.info> Le Friday 05 September 2008 19:36:56 Fredrik Lundh, vous avez ?crit?: > Maric Michaud wrote: > > I suspect you are coming to conclusions a bit quickly, without taking the > > pain of understanding the whole discussion. > > I'm pretty sure I was the first one to post an answer in this thread, > and I understand Python design and performance issues very well, thank you. > What is that ? Some sort of arguments ? If it matters, I know who you are and I don't try to compare my understanding of python with yours. > (but given your talk about "the cost of whitespace" in a response to a > comment about performance in that other subthread, It's silly that you continue to fight on unrelated arguments, I've already said that I misunderstood the OP's requirements and the proposed solution. > it's obvious that > you're just here to provide noise. plonk plonk.) I don't think you should make those assumptions, in your words, there are too much dumb or malevolent peoples on this list for it to be that "obvious". Nevertheless, I don't really see why I should explain myself for being here and trying to bring a (little, not like yours, of course) contribution. -- _____________ Maric Michaud From banibrata.dutta at gmail.com Thu Sep 4 06:57:37 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Thu, 4 Sep 2008 16:27:37 +0530 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <48BFB534.2080508@egenix.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <48BFB534.2080508@egenix.com> Message-ID: <3de8e1f70809040357p6beb1efar7fe57af9bcaa537c@mail.gmail.com> On Thu, Sep 4, 2008 at 3:45 PM, M.-A. Lemburg wrote: > On 2008-09-04 11:14, Kay Schluehr wrote: > > On 4 Sep., 10:31, "M.-A. Lemburg" wrote: > >> On 2008-09-04 07:49, Kay Schluehr wrote: > >> > >>> 3) Following the public rumor mill and the latest hype RIA i.e. the > >>> merge of web- and desktop applications with systems like Adobe AIR, > >>> JavaFX, Google Gears and MS Silverlight is the future of frontend > >>> development. With the exception of IronPython and Silverlight, Python > >>> hasn't even entered this game and no one knows if it ever will. > >> Actually, it has already and quite some time ago: > >> > >> http://www.artima.com/weblogs/viewpost.jsp?thread=208528 > >> > >> The recipe is simple: use Python for the business logic, database > >> interfacing, etc and have it talk to a Flex front-end via XML-RPC > >> or REST. > > > > Python is still server-side in this scenario and plays no role in UI > > definitions. > > That depends on how you design the application. It is well possible > to have Python drive the GUI by sending the required details to > the Flex front-end via XML (ie. data-driven GUIs). > > > So one doesn't get more than e.g. Django apps that > > respond to HTTP requests triggered by JavaScript forms except that > > JavaScript+HTML+Browser is replaced by Flex = AS3+MXML+FlashPlayer. > > You really can't compare the Flex stack to an AJAX stack. Flex > has a lot more to offer for GUI programming than AJAX, it also > doesn't suffer from the problems of AJAX having to support several > different sets of browser or library bugs. > > We switched from an AJAX approach to a Flex-based approach last year > and never even considered moving back again. The approach does seem quite impressive, but isn't Flex's platform neutrality quite over-rated ? I mean after-all, it assumes that Flex is available for and available on the platform. Flex today is not yet so ubiquitous as the JRE... Are there some established best-practices on how to package such applications -- s.a. shipping with its's own Flex runtime, offer-download if missing etc. ? What happens if owner of target machine decides to upgrade their version of Flex, will it impact the application package in anyway, and render rest of it "non-upgradable" ? > > > > The role of Python is somewhat arbitrary. This could change only if > > Python becomes a client side language executed by AVM, V8 etc. like > > IronPython in Silverlight. > > > > About separating UI from application logics by assigning functionality > > to different general purpose languages I have to admit that I don't > > think it is such a great idea ... > > In my experience, Flex + Python gives you the best of both worlds, > the nice GUI features of Flex and the efficiency of Python for the > business logic. > > A long time ago, there was a Python plugin for Netscape > which allowed you to run Python straight in the browser. Perhaps > it's time to revive such an idea... but then you're still missing > out on the GUI part, since you're still stuck with what the > browser has to offer in terms of widget support. > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Sep 04 2008) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dotancohen at gmail.com Sat Sep 27 08:28:56 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 27 Sep 2008 15:28:56 +0300 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> Message-ID: <880dece00809270528p1a80354bydaf45cc48fbf2bbf@mail.gmail.com> 2008/9/27 Aaron Castironpi Brady : >> I think in June and July they were selling watches a lot which I >> haven't noticed recently. > > Gucci 104 G-Bandeau Watches - Gucci Watches Discount Rolex Oyster > Perpetual Lady Datejust Pearlmaster 18kt Yellow Gold Diamond Ladies > Watch 80318C > Cartier Must 21 Watches - Cartier Watches Discount > > I speak too soon. > If we start blocking users who have no previous posts and then post many new messages at once, then we wll just push the spammers to forge active list users and reply to threads. That would be a worse situation then we are in now. I say leave well enough alone. Read about the Brain Blood Barrier (http://en.wikipedia.org/wiki/Brain_Blood_Barrier) for an example in nature where although a method to stop an attacker exists, it is not overused to prevent the attacker from becoming more powerful. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From mh at pixar.com Thu Sep 25 21:01:43 2008 From: mh at pixar.com (mh at pixar.com) Date: Fri, 26 Sep 2008 01:01:43 GMT Subject: SimpleXMLRPCServer -- turning off request log? Message-ID: My SimpleXMLRPCServer program prints to stderr a line like this for each request: ohm..pixar.com - - [25/Sep/2008 17:57:50] "POST /RPC2 HTTP/1.0" 200 - Is there a way to turn this logging off? I have RTFM and can't seem to find a way to do so. Many TIA! Mark -- Mark Harrison Pixar Animation Studios From sjmachin at lexicon.net Sat Sep 6 17:49:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 14:49:51 -0700 (PDT) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sep 7, 7:29?am, Wojtek Walczak wrote: > On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote: > > ? ? ? ? ? ? ? ? ?if mult is 1: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ?^^ > You're testing for identity, not for equality. > Change it to "if mult == 1". Is it alright now? > Although he definitely should not be using "is" here, that can not be the problem if he is using CPython. As an optimisation, small integers are interned i.e. for each small integer, there is only one object. >>> a = 1 >>> b = 10000 >>> a is 1 True >>> b is 10000 False >>> id(a) 10897704 >>> id(1) 10897704 >>> id(b) 11893004 >>> id(10000) 12633044 >>> From grante at visi.com Tue Sep 16 09:57:53 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:57:53 -0500 Subject: append on lists References: <1221564169.16690.0@proxy00.news.clara.net> Message-ID: On 2008-09-16, Maric Michaud wrote: > all expressions that return something, return a new object, That's not _quite_ true: >>> a=1 >>> b=a.__add__(0) >>> a is b True ;) -- Grant Edwards grante Yow! LOOK!! Sullen at American teens wearing visi.com MADRAS shorts and "Flock of Seagulls" HAIRCUTS! From grante at visi.com Tue Sep 16 09:55:56 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:55:56 -0500 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <1221564169.16690.0@proxy00.news.clara.net> Message-ID: On 2008-09-16, Armin wrote: > Alex Marandon wrote: >> Armin wrote: >>> Duncan Booth wrote: >>> >>> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c >>> (with c = [8,9]) is identical, >> >> No it's not, + doesn't alter its operands. >> >> >>> a = 1 >> >>> b = 2 >> >>> a + b >> 3 > > That's not the point :) > > What's the value of 1.add(b)? None? Or 3 ?? >>> a = 1 >>> b = 2 >>> 1.add(b) File "", line 1 1.add(b) ^ SyntaxError: invalid syntax > (if add works in the same way as append) It doesn't. > a + b doesn't change a,b ... but a.add(b) -> a=3 WTH are you talking about? -- Grant Edwards grante Yow! I just got my PRINCE at bumper sticker ... But now visi.com I can't remember WHO he is ... From castironpi at gmail.com Sat Sep 13 20:32:35 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 13 Sep 2008 17:32:35 -0700 (PDT) Subject: testing if another instance of a script is already running References: <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> Message-ID: On Sep 13, 5:34?pm, s... at pobox.com wrote: > ? ? >> I don't want to handle writing of a PID file because it is too > ? ? >> Unix/Linux specific way to do this, and I need to keep the code to be > ? ? >> cross-platform. > ? ? >> > ? ? >> I think the better way to achieve this is to use some process > ? ? >> control, but I'm a neebie and I don't see how to do this in a safe > ? ? >> and clean way. > > ? ? Aaron> You could use msvcrt.locking, and just lock the script file. ?I > ? ? Aaron> am not sure about this. > > If you want a cross-platform solution, you might try the lockfile module > instead: > > ? ?http://pypi.python.org/pypi/lockfile > > Skip Would it suffice to call 'os.open' with flags= _O_CREAT| _O_EXCL ? Would that be platform-independent? Windows docs (_open): _O_CREAT| _O_EXCL Returns an error value if the file specified by filename exists. Applies only when used with _O_CREAT. man page: O_EXCL If O_EXCL and O_CREAT are set, open will fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist is atomic with respect to other processes executing open naming the same filename in the same directory with O_EXCL and O_CREAT set. CreateDirectory: The CreateDirectory function does seem to guarantee this as well, though is not as explicit: Possible errors include the following. ERROR_ALREADY_EXISTS The specified directory already exists. But the lock operation wouldn't need the 'if hasattr(os, "link")' test. From steven at REMOVE.THIS.cybersource.com.au Mon Sep 29 04:47:33 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 29 Sep 2008 08:47:33 GMT Subject: Detecting dir (tree) changes fast? References: Message-ID: On Mon, 29 Sep 2008 10:05:10 +0200, robert wrote: > I want to detect changes in a directory tree fast with minimum > overhead/load. In order to check the need for sync tasks at high > frequency. > It must not be 100% reliable (its also forced time periodic), so kind of > hashing would be ok. > How? Google is your friend. Googling for "python directory watcher" gives the following top three links: http://www.amk.ca/python/simple/ http://timgolden.me.uk/python/win32_how_do_i/ watch_directory_for_changes.html (sorry for the broken URL) http://code.activestate.com/recipes/217829/ There are probably many others. Which one is most suitable will depend on the details of, e.g. the OS you are using, the types of changes you're expecting, how many files are in the directory. -- Steven From dmitry at athabascau.ca Thu Sep 25 16:47:18 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 20:47:18 GMT Subject: Eggs, VirtualEnv, and Apt - best practices? References: <6k2aqqF5p185U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > - different OS. I for one don't know about a package management tool > for windows. And while our servers use Linux (and I as developer as > well), all the rest of our people use windows. No use telling them to > apt-get instal python-imaging. that is a very valid point, but it seemed that Scott has homogeneous environment: Debian/Ubuntu so my post was relative to the original request. I agree that when you throw Windows/MacOS into the mix things become "interesting". But then it's better when your developers develop on server/platform they are going to be using, using same stack they going to face in production etc. It all depends on requirements and current practices in company. > - keeping track of recent developments. In the Python webframework > world for example (which the OP seems to be working with), things move > fast. Or extremly slow, regarding releases. Take Django - until 2 month > ago, there hasn't been a stable release for *years*. Virtually everybody > was working with trunk. And given the rather strict packaging policies > of debian and consorts, you'd be cut off of recent developments as well > as of bugfixes. that definitely becomes tricky however not impossible to track. You do need a common snapshot for all developers to use anyway - so why not just package it up? Note: I do agree that depending on environment/development practices/policies/etc my statement might become invalid or useless. However when you're dealing with homogeneous environment or you require development and testing to be done on your servers running targeted application stack - things become much easier to manage :) From bignose+hates-spam at benfinney.id.au Sun Sep 7 21:35:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 08 Sep 2008 11:35:00 +1000 Subject: lacking follow-through References: <038bcbbc-e204-43f8-b656-81495af36b6c@d77g2000hsb.googlegroups.com> Message-ID: <87vdx7ju7v.fsf@benfinney.id.au> Paul Boddie writes: > On 7 Sep, 23:00, castironpi wrote: > > I am concerned by the lack of follow-through on some responses to > > recent ideas I have described. Do I merely have a wrong > > understanding of group policy? > > I think some people have taken exception to your contributions > previously, which I believe exhibits a certain degree of > shortsightedness on their part [?] For my part, I find those posts a mammoth waste of my time, since they're shrouded in language so difficult to parse that I can't see what they're supposed to be saying in a reasonable amount of time. So, I consider it more valuable to never see those posts; if someone else can find a gem of wisdom in any of them that's significantly valuable, presumably I'll find out by some other means than attempting to read those posts myself. This is not intended as any kind of offense to the author, nor to anyone not fluent in written English; it's merely a choice I make as to how I will spend my time. -- \ ?No wonder I'm all confused; one of my parents was a woman, the | `\ other was a man.? ?Ashleigh Brilliant | _o__) | Ben Finney From darcy at druid.net Fri Sep 12 11:19:49 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 12 Sep 2008 11:19:49 -0400 Subject: Checking the boolean value of a collection In-Reply-To: References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> Message-ID: <20080912111949.19629e78.darcy@druid.net> On Fri, 12 Sep 2008 17:11:47 +0200 Fredrik Lundh wrote: > The "__builtins__" object is an implementation detail, and shouldn't be > accessed directly. And I hope I don't need to point out that adding > custom builtins nillywilly is a bad idea... Is there ever any advantage to having something as a builtin rather than as a regular user method? What difference does it make to the running script? I can see that adding "bar" from module "foo" to "__builtins__" means that you can use "bar()" instead of "foo.bar()". Is that the only benefit? -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From ppearson at nowhere.invalid Wed Sep 17 11:04:17 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 17 Sep 2008 15:04:17 GMT Subject: Problem occured while sending mail References: <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> Message-ID: <6jckjhF2llrvU1@mid.individual.net> On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui wrote: > On Sep 17, 5:04 pm, sui wrote: >> this is my code >> >> import sys, os, glob, datetime, time >> import smtplib >> ## Parameters for SMTP session >> port=587 >> SMTPserver= 'smtp.gmail.com' >> SMTPuser= '... at gmail.com' >> pw= 'fill in here' >> SENDER= SMTPuser >> >> ## Message details >> FROM= SENDER >> TO= 'notgm... at a.com' >> CC=FROM >> ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC >> RECEIVERS= (TO,) ## ignore the CC address >> >> subject= 'Test 1a' >> message='*** Email test *** ' >> >> print 'Starting SMTP mail session on %s as %s ' % >> (SMTPserver,SMTPuser) >> session = smtplib.SMTP(SMTPserver,port) >> session.set_debuglevel(0) # set debug level to 1 to see details >> session.ehlo(SMTPuser) # say hello >> session.starttls() # TLS needed >> session.ehlo(SMTPuser) # say hello again, not sure why >> session.login(SMTPuser, pw) >> >> ##Create HEADER + MESSAGE >> HEADER= 'From: %s\r\n' % FROM >> HEADER= HEADER + 'To: %s\r\n' % TO >> HEADER= HEADER + 'Cc: %s\r\n' % CC >> HEADER= HEADER + 'Subject: %s\r\n' % subject >> BODY= HEADER + '\r\n' + message >> print BODY >> >> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email >> >> session.close() >> >> Now when i run this .py file...as python mail.py >> i can see only statement >> starting smtp mail......n details >> then nothing on screen after few minutes or after pressing ctrl +c >> Traceback (most recent call last): >> File "mail4.py", line 21, in >> session = smtplib.SMTP(SMTPserver,port) >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ >> (code, msg) = self.connect(host, port) >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect >> self.sock.connect(sa) >> File "", line 1, in connect >> or may be conncetion time out >> >> wats the solution for this > > if i dont press cntrl + c then it shows > Starting SMTP mail session on smtp.gmail.com as gogtesuyash at gmail.com > Traceback (most recent call last): > File "mail4.py", line 21, in > session = smtplib.SMTP(SMTPserver,port) > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect > raise socket.error, msg > socket.error: (110, 'Connection timed out') > > plz help me its urgent.....i want to complete it as early as possible I pasted your code into a file named temp.py, and (perhaps superstitiously) added a backslash to this line: >> print 'Starting SMTP mail session on %s as %s ' % Here's what it does (long line wrapped manually): peter at eleodes:~$ python temp.py Starting SMTP mail session on smtp.gmail.com as ... at gmail.com Traceback (most recent call last): File "temp.py", line 27, in ? session.login(SMTPuser, pw) File "/usr/lib/python2.4/smtplib.py", line 591, in login raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, \ '5.7.1 Username and Password not accepted. Learn more at\n' \ '5.7.1 http://mail.google.com/support/bin/answer.py?answer=' \ '14257 a8sm34686663poa.12') peter at eleodes:~$ This indicates that it got much farther than when you ran it, since your timeout message comes from the smtplib.SMTP call several lines before the session.login call. As a simple connectivity test, you might see whether you can connect using telnet: peter at eleodes:~$ telnet smtp.gmail.com 587 Trying 72.14.253.109... Connected to gmail-smtp.l.google.com. Escape character is '^]'. 220 mx.google.com ESMTP m27sm34789033pof.6 ^]c telnet> c Connection closed. peter at eleodes:~$ -- To email me, substitute nowhere->spamcop, invalid->net. From grante at visi.com Fri Sep 26 21:30:49 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 26 Sep 2008 20:30:49 -0500 Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> Message-ID: On 2008-09-26, nntpman68 wrote: > Hm, > > > I guess you just filter mailing lists and can do nothing about the > newsgroup if I'm fetching via the nntp server of my ISP itself, right? I read the group via NNTP, and I find that blocking all articles posted from google.groups gets rid of all of the spam. -- Grant From clp at rebertia.com Sat Sep 27 19:01:14 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 27 Sep 2008 16:01:14 -0700 Subject: check if file is MS Word or PDF file In-Reply-To: <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> References: <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> Message-ID: <47c890dc0809271601y6f5a4a5fy98fad966e5ca024@mail.gmail.com> On Sat, Sep 27, 2008 at 3:42 PM, Michael Crute wrote: > On Sat, Sep 27, 2008 at 5:43 PM, A. Joseph wrote: >> What should I look for in a file to determine whether or not it is a >> MS Word file or an Excel file or a PDF file, etc., etc.? including Zip >> files >> >> I don`t want to check for file extension. >> os.path.splitext('Filename.jpg') will produce a tuple of filename and >> extension, but some file don`t even have extension and can still be read by >> MS Word or NotePad. i want to be 100% sure of the file. > > You could use the mimetypes module... > > <<< import mimetypes > <<< mimetypes.guess_type("LegalNotices.pdf") >>>> ('application/pdf', None) Looking at the docs for the mimetypes module, it just guesses based on the filename (and extension), not the actual contents of the file, so it doesn't really help the OP, who wants to make sure their program isn't misled by an inaccurate extension. Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > > -mike > > -- > ________________________________ > Michael E. Crute > http://mike.crute.org > > God put me on this earth to accomplish a certain number of things. > Right now I am so far behind that I will never die. --Bill Watterson > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 00:10:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 04:10:28 GMT Subject: Setter Propertys' mro? References: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> Message-ID: <00d34e8d$0$30713$c3e8da3@news.astraweb.com> On Sat, 06 Sep 2008 18:15:33 -0700, cipher wrote: > Whats the mro (method resolution order) of a setter property (__set__ on > a descriptor). > i seem to be experiencing some weird issue with them. for example > >>>> class test: Unless you're using Python 3, there's your problem right there. In Python 2.x, properties only work correctly for new style classes, not classic classes. Change the above line to: class Test(object): # by convention, classes start with Uppercase. and all should work (or at least you'll discover new and exciting different problems with your code). > however, if i specify the metaclass in the class definition it works > just fine... > > class test: > __metaclass__=type which is more or less the same as inheriting from object, except uglier. -- Steven From callen314 at gmail.com Tue Sep 23 17:34:06 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 23 Sep 2008 14:34:06 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: > The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), or should the exception propagate to the calling program which > handles the issue? > my view is that the exceptions are there precisely to tell the calling program about the error and give the programmer a chance to do something smart about it. A library, properly, doesn't even know the context in which it is running, and sys.exit() is pretty heavy handed for a library to call and shows assumptions beyond what a library should assume about its running environment. imho From martin at v.loewis.de Fri Sep 12 15:15:23 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 12 Sep 2008 21:15:23 +0200 Subject: Python on Windows XP 64-bit: python not found in registry In-Reply-To: References: Message-ID: <48cabfcb$0$2340$9b622d9e@news.freenet.de> > Anybody here that had the same problem and solved it? Did you install the 32-bit or the 64-bit installer? If the 64-bit installer, did you also install 32-bit or 64-bit installers for iPython, PIL, and easy_install? If you try to use 32-bit extensions or installers to locate a 64-bit Python, that will fail: even if installation would succeed, you still couldn't use the resulting installations, since you just can't mix the two architectures in a single process. Regards, Martin From gagsl-py2 at yahoo.com.ar Fri Sep 5 17:48:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 18:48:57 -0300 Subject: Regarding subprocess module References: Message-ID: En Fri, 05 Sep 2008 09:56:02 -0300, tarun escribi?: > import subprocess,time > cmdExe = "C:\\WINDOWS\\system32\\cmd.exe" > myProcess = subprocess.Popen(cmdExe,stdin=subprocess.PIPE) > time.sleep(2) > myProcess.stdin.write('cd Desktop\r\n') > > I copied the above lines of code to a file and tried executing the python > file from dos box (command prompt) on windows > I want subprocess.Popen to open a new dos box. But it works in the same > window. What should I do to open the subprocess in new window? Add this argument: creationflags = subprocess.CREATE_NEW_CONSOLE See "Creation of a Console" in MSDN: -- Gabriel Genellina From sturlamolden at yahoo.no Thu Sep 25 06:34:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 03:34:12 -0700 (PDT) Subject: Linq to Python References: Message-ID: <4e86da77-3525-44c5-a34a-871d4b7fc6da@r66g2000hsg.googlegroups.com> On 25 Sep, 12:06, hrishy wrote: > var stoogeGuys = > ? ? ?Beginning with the XML source > ? ? ?from xmlGuys in xmlSource.Descendants("Stooge") > ? ? ?Join to the array on the common element "stoogeName" > ? ? ?join arrayGuys in familyFacts > ? ? ? ? ? ?on xmlGuys.Element("stoogeName").Value equals arrayGuys.stoogeName > ? ? ?Join to the database on the common element "stoogeName" > ? ? ?join dbGuys in stoogeContext.stoogeTables > ? ? ? ? ? ?on xmlGuys.Element("stoogeName").Value equals dbGuys.stoogeName > ? ? ?select new > ? ? ?{ > ? ? ? ? firstName ? ?= dbGuys.stoogeName, > ? ? ? ? familyName ? = arrayGuys.familyName, > ? ? ? ? birthDate ? ?= xmlGuys.Element("birthDate").Value, > ? ? ? ? deathDate ? ?= xmlGuys.Element("deathDate").Value, > ? ? ? ? hairCutStyle = dbGuys.stoogeHaircut, > ? ? ?}; > [/code] That is a for loop over xmlGuys in xmlSource.Descendants("Stooge"). Those joins are e.g. dictionary lookups, and finally an object with names, birthdates, etc. are appended to the list stoogeGuys. From steve at REMOVE-THIS-cybersource.com.au Fri Sep 26 11:08:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 15:08:27 GMT Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <48dcf924$0$4653$426a74cc@news.free.fr> Message-ID: <00ecf4b4$0$20666$c3e8da3@news.astraweb.com> On Fri, 26 Sep 2008 17:00:59 +0200, Bruno Desthuilliers wrote: > Patrick Mullen a ?crit : >> Depending on the scale of the website I am making, how much I care >> about editing it in the future, and how much I just want to get >> something up, I will occasionally use php. And I am a self confessed >> php hater :) But it's generally the fastest way I know to get >> something up. So even terrible languages can have their uses! > > Sorry but I fail to see how it relates to the current thread ??? I think Patrick is responding to a comment from Tino Wildenhain: [quote] Well then it still depends on the perception of "job done". For example PHP programmers would bet their soul that their language of choice is exactly the right one to "get the job done." [end quote] Patrick, you will cause much less confusion if you quote relevant parts of the text you are replying too. -- Steven From niklas.norrthon at hotmail.com Fri Sep 26 07:02:57 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Fri, 26 Sep 2008 04:02:57 -0700 (PDT) Subject: urllib.urlopen fails in Emacs References: <877i8zco3t.fsf@gmail.com> Message-ID: <748c7630-1090-4c0b-8a52-34797f801c82@c58g2000hsc.googlegroups.com> On 26 Sep, 12:21, Wojtek Walczak wrote: > On Fri, 26 Sep 2008 02:23:18 -0600, Iain Dalton wrote: > > InEmacs, using run-python, > > > ? ? import urllib > > ? ?urllib.urlopen('http://www.google.com/') > > > results in this traceback: > ... > > ? ? IOError: [Errno socket error] (111, 'Connection refused') > > > It works fine from the command line. ?Why is this happening? > > I can't answer your question, since I don't useemacs, > but it looks likeemacshas some kind of built in firewall. > > ;-) > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ I don't think it is emacs... It works for me, using emacs 22.1, python 2.5.1, and windows XP: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib >>> urllib.urlopen('http://www.google.com/') > >>> /Niklas Norrthon From skip at pobox.com Mon Sep 22 11:35:26 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 Sep 2008 10:35:26 -0500 Subject: Reading Windows CSV file with LCID entries under Linux. In-Reply-To: References: Message-ID: <18647.47934.846072.408740@montanaro-dyndns-org.local> Thomas> My question is: How can I convert this data into something more Thomas> reasonable like unicode? Basically, what I want is something Thomas> like "Text1;Text2", both fields encoded as UTF-8. Can this be Thomas> done with Python? How can I find out which codepage I have to Thomas> use for 1033 and 1031? There are examples at end of the CSV module documentation which show how to create Unicode readers and writers. You can extend the UnicodeReader class to peek at the LCID field and save the corresponding codepage for the remainder of the line. (This would assume you're not creating CSV files which contain newlines. Each line read would be assumed to be a new record in the file.) Skip From roy at panix.com Tue Sep 23 09:22:29 2008 From: roy at panix.com (Roy Smith) Date: Tue, 23 Sep 2008 09:22:29 -0400 Subject: Mutex not thread safe? PEP-3108. Message-ID: I'm perusing PEP-3108 and came upon this interesting statement (under the "Hardly used" section): mutex [...] Not thread-safe. How can a mutex, whose sole reason for existence is to mediate thread safety, not be thread safe? From ethan at stoneleaf.us Fri Sep 5 14:42:13 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 05 Sep 2008 10:42:13 -0800 Subject: Case-insensitive string compare? In-Reply-To: <200809051606.01358.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> <1220618002.21923.12.camel@jcd-desktop> <200809051606.01358.maric@aristote.info> Message-ID: <48C17D85.1020804@stoneleaf.us> Maric Michaud wrote: > Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez ?crit : > >>On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: >> >>>Thanks everyone for your help. I'm not opposed to using [key.lower() >>>for key in stage_map] at all, I was just curious to see if there were >>>any cleaner alternatives. It looks like that is what I'll be using. >>>I'm not familiar with how python works internally, but coming from C++ >>>it seems like "remaking" the map would be slow. However, speed is not >>>my main concern in my particular situation, I'm just curious to learn >>>more about python. >> >>You should be opposed to that particular solution. You have just taken >>a dictionary lookup (very fast) and turned it into a list traversal >>(slow). Even if speed isn't your main concern, this is an unnecessary >>de-optimization. You are deliberately slowing down your program to >>avoid a slightly more verbose lookup later. Your data structure might >>as well be a list of tuples to begin with, to avoid creating a new list. >>You have effectively made your keys useless as keys. >> >>If your lookups need to be case insensitive, make the key lower case, >>and store the cased version in the value, whether as a tuple or a dict >>(depending on whether you want named access). >> >>d = { >> 'foo': {'key': 'Foo', 'value': 'val1'} >> 'spam': {'key': 'sPAm', 'value': 'val2'} >>} >> >>search = 'FOO'.lower() >>if search in d: >> result = d[search] >> key = result['key'] >> value = result['value'] >> >>The only reason I wouldn't use this solution is if you expect to have >>keys that will be identical when made lowercase, but if you're doing >>case-insensitive lookup, you obviously don't expect this to be an issue. > > The OP has already said the keys are case-sensitive, so this is not an option, Actually, the OP said: -- So you're saying to ensure that stage_map's keys are initially -- lower-case to begin with? Well, I can't do this either since the -- *case of the keys is actually valuable* ***later on***. It's only for -- the purposes of this specific comparison operation that the case -- should be ignored. In other words, the key (as a key) is case-insensitive, and the key (as a value) is case-sensitive -- making Clifford's comments and solution perfectly acceptable. ~Ethan~ From nick at craig-wood.com Tue Sep 9 10:36:24 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 09 Sep 2008 09:36:24 -0500 Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: metaperl.com wrote: > Pyparsing has a really nice feature that I want in PLY. I want to > specify a list of strings and have them converted to a regular > expression. > > A Perl module which does an aggressively optimizing job of this is > Regexp::List - > http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm > > I really dont care if the expression is optimal. So the goal is > something like: > > vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| > u|ii|i)' > > Is there a public module available for this purpose? I wrote one of these in perl a while ago http://www.craig-wood.com/nick/pub/words-to-regexp.pl It transforms the regular expression recursively into more efficient ones. It uses regular expressions to do that. I considered porting it to python but looking at the regular expressions made me feel weak at the knees ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tmohr at s.netic.de Tue Sep 16 15:45:26 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Sep 2008 21:45:26 +0200 Subject: optparse References: Message-ID: Hi, > If i call it without any parameters i get: > > opts {'verb': 'store_false'} > args [] If i call it with parameter -v i get: ./script.py -v opts {'verb': True} args [] I wonder what's wrong here. Best regards, Torsten. From gatti at dsdata.it Sat Sep 20 12:04:21 2008 From: gatti at dsdata.it (Lorenzo Gatti) Date: Sat, 20 Sep 2008 09:04:21 -0700 (PDT) Subject: XML-schema 'best practice' question References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: Sorry for pressing the send button too fast. On 20 Set, 07:59, Frank Millman wrote: > I want to introduce an element of workflow management (aka Business > Process Management) into the business/accounting system I am > developing. I used google to try to find out what the current state of > the art is. After several months of very confusing research, this is > the present situation, as best as I can figure it out. What is the state of the art of existing, working software? Can you leverage it instead of starting from scratch? For example, the existing functionality of your accounting software can be reorganized as a suite of components, web services etc. that can be embedded in workflow definitions, and/or executing a workflow engine can become a command in your application. > There is an OMG spec called BPMN, for Business Process Modeling > Notation. It provides a graphical notation [snip] > there is no standard way > of exchanging a diagram between different vendors, or of using it as > input to a workflow engine. So BPMN is mere theory. This "spec" might be a reference for evaluating actual systems, but not a standard itself. > There is an OASIS spec called WS-BPEL, for Web Services Business > Process Execution Language. It defines a language for specifying > business process behavior based on Web Services. This does have a > formal xml-based specification. However, it only covers processes > invoked via web services - it does not cover workflow-type processes > within an organisation. To try to fill this gap, a few vendors got > together and submitted a draft specification called BPEL4People. This > proposes a series of extensions to the WS-BPEL spec. It is still at > the evaluation stage. Some customers pay good money for buzzword compliance, but are you sure you want to be so bleeding edge that you care not only for WS- something specifications, but for "evaluation stage" ones? There is no need to wait for BPEL4People before designing workflow systems with human editing, approval, etc. Try looking into case studies of how BPEL is actually used in practice. > The BPMN spec includes a section which attempts to provide a mapping > between BPMN and BPEL, but the authors state that there are areas of > incompatibility, so it is not a perfect mapping. Don't worry, BPMN does not exist: there is no incompatibility. On the other hand, comparing and understanding BPMN and BPEL might reveal different purposes and weaknesses between the two systems and help you distinguish what you need, what would be cool and what is only a bad idea or a speculation. > Eventually I would like to make sense of all this, but for now I want > to focus on BPMN, and ignore BPEL. I can use wxPython to design a BPMN > diagram, but I have to invent my own method of serialising it so that > I can use it to drive the business process. For good or ill, I decided > to use xml, as it seems to offer the best chance of keeping up with > the various specifications as they evolve. If you mean to use workflow architectures to add value to your business and accounting software, your priority should be executing workflows, not editing workflow diagrams (which are a useful but unnecessary user interface layer over the actual workflow engine); making your diagrams and definitions compliant with volatile and unproven specifications should come a distant last. > I don't know if this is of any interest to anyone, but it was > therapeutic for me to try to organise my thoughts and get them down on > paper. I am not expecting any comments, but if anyone has any thoughts > to toss in, I will read them with interest. 1) There are a number of open-source or affordable workflow engines, mostly BPEL-compliant and written in Java; they should be more useful than reinventing the wheel. 2) With a good XML editor you can produce the workflow definitions, BPEL or otherwise, that your workflow engine needs, and leave the interactive diagram editor for a phase 2 that might not necessarily come; text editing might be convenient enough for your users, and for graphical output something simpler than an editor (e.g a Graphviz exporter) might be enough. 3) Maybe workflow processing can grow inside your existing accounting application without the sort of "big bang" redesign you seem to be planning; chances are that the needed objects are already in place and you only need to make workflow more explicit and add appropriate new features. Regards, Lorenzo Gatti From mnations at gmail.com Wed Sep 3 13:11:37 2008 From: mnations at gmail.com (Mudcat) Date: Wed, 3 Sep 2008 10:11:37 -0700 (PDT) Subject: Writing Unicode to database using ODBC Message-ID: In short what I'm trying to do is read a document using an xml parser and then upload that data back into a database. I've got the code more or less completed using xml.etree.ElementTree for the parser and dbi/ odbc for my db connection. To fix problems with unicode I built a work-around by mapping unicode characters to equivalent ascii characters and then encoding everything to ascii. That allowed me to build the application and debug it without running into problems printing to file or stdout to screen. However, now that I've got all that working I'd like to simply take the unicode data from the xml parser and then pass it directly into the database (which is currently set up for unicode data). I've run into problems and just can't figure why this isn't working. The breakdown is occurring when I try to execute the db query: cur.execute( query ) Fairly straightforward. I get the following error: File "atp_alt.py", line 273, in dbWrite cur.execute( query ) UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 3 79: ordinal not in range(128) I've verified that query is of type unicode by checking the type a statement or two earlier (output: ). So then I thought maybe the odbc execute just can't handle unicode data. But when I do the following command: query = query.encode('utf-8') It actually works. So apparently execute can handle unicode data. The problem now is that basically the data has been encoded twice and is in the wrong format when I pull it from the database: >>> a u'+CMGL: (\xe2\u20ac\u0153REC UNREAD\xe2\u20ac\x9d,\xe2\u20ac\x9dREC READ\xe2\u20ac\x9d,\xe2\u20ac\x9dSTO UNSENT\xe2\u20ac\x9d,\xe2\u20ac \x9dSTO SENT\xe2\u20ac\x9d,\xe2\u20ac\x9dALL\xe2\u20ac\x9d) OK' >>> print a +CMGL: (???REC UNREAD???,???REC READ???,???STO UNSENT???,???STO SENT? ??,???ALL???) OK The non-alpha characters should be double-quotes. It works correctly if I copy/paste into the editor: >>> d u'\u201cREC' >>> print d ?REC >>> d.encode('utf-8') '\xe2\x80\x9cREC' >>> type(d.encode('utf-8')) I can then decode the string to get back the proper unicode data. I can't do that with the data out of the db because it's of the wrong type for the data that it has. I think the problem is that I'm having to encode data again to force it into the database, but how can I use the odbc.execute() function without having to do that? From semanticist at gmail.com Tue Sep 16 02:30:56 2008 From: semanticist at gmail.com (Miles) Date: Tue, 16 Sep 2008 02:30:56 -0400 Subject: When do I get "multiple bases have instance lay-out conflict" error? In-Reply-To: <78f8019c0809150306t47090464vaeed3b356e76ab5b@mail.gmail.com> References: <78f8019c0809150306t47090464vaeed3b356e76ab5b@mail.gmail.com> Message-ID: On Mon, Sep 15, 2008 at 6:06 AM, Harish K Vishwanath wrote: > Hello all, > > When do we actually see the error : > > TypeError: Error when calling the metaclass bases > multiple bases have instance lay-out conflict > > > I searched the web and I could not find a correct guideline as to when such > an error could arise. One of the places said that "A new style class cannot > inherit from more than one python built-in class". That is., > >>>> class A(dict,list): > ... pass > wouldn't work. "built-in type" generally means "implemented in C", also sometimes called "extension type". >>>> class A(Exception,persistent.Persistent): > ... pass > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: Error when calling the metaclass bases > multiple bases have instance lay-out conflict > > Still declaration of class A fails. Any idea? What is the exact rule when > python throws up " multiple bases have instance lay-out conflict" error? Both the Exception and ZODB Persistent objects are implemented in C, and they have different ideas for the format of the struct that holds an object's data. It can be tricky to tell by introspection whether a new-style class is implemented in Python or C. One possible heuristic: >>> class Foo(object): pass ... >>> '__module__' in vars(Foo) True >>> '__module__' in vars(Exception) False I'm not sure whether this is valid in all cases. Someone else may know of a better way. -Miles From steven at REMOVE.THIS.cybersource.com.au Mon Sep 1 05:35:37 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2008 09:35:37 GMT Subject: Know if a object member is a method References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Message-ID: On Mon, 01 Sep 2008 10:52:10 +0200, Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi Luca, > > use type(something).__name__ , e.g. > > >>> def x(): > >>> pass > >>> class C: > >>> pass > >>> c = C() > >>> type(x).__name__ == 'function' > True > >> type(C).__name__ == 'classobj' > True > >> type(c).__name__ == 'instance' > True That's relatively fragile, since such names aren't reserved in any way. It's easy to fool a name comparison check with an accidental name collision: >>> class function(object): # not a reserved name ... pass ... >>> x = function() >>> type(x).__name__ 'function' >>> x() # must be a function then... Traceback (most recent call last): File "", line 1, in TypeError: 'function' object is not callable But not so easy to fool a type check: >>> type(x) == new.function False Of course that's not bullet-proof either. I leave it as an exercise to discover how you might break that piece of code. -- Steven From gherron at islandtraining.com Sun Sep 14 11:03:12 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 14 Sep 2008 08:03:12 -0700 Subject: How does python call OS? In-Reply-To: References: Message-ID: <48CD27B0.10504@islandtraining.com> Siegfried Heintze wrote: > I just finished reading a chapter in "Python Programming on Win32" and tried > out the pythonwin scribble application. I'm not sure if I got it right > because I could not open a new document. I tried to download the source code > as referenced in the chm file but it is corrupted. I cut and pasted from my > softcopy of the book. > > I see the next sub-chapter on wxWindows for python and the previous > sub-chapter on TK. This is looking a lot like other scripting languages > (such as perl and groovy and even java). Can python call anything directly > or does someone have to write a DLL in C/C++ that calls the function first? > Thanks! > Siegfried See the ctypes module for a method of calling any C callable function in and DLL. Gary Herron From fredrik at pythonware.com Mon Sep 22 17:20:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Sep 2008 23:20:35 +0200 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: Robert Kern wrote: > No warnings show up when importing the offending module: > > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> from sympy.mpmath import specfun > >>> > > So what could be suppressing the warning? a bug in Python 2.5, it seems: > more f1.py as = 1 as = 2 as = 3 > python f1.py f1.py:1: Warning: 'as' will become a reserved keyword in Python 2.6 f1.py:2: Warning: 'as' will become a reserved keyword in Python 2.6 f1.py:3: Warning: 'as' will become a reserved keyword in Python 2.6 > more f2.py as = 1 import os as = 3 > python f2.py f2.py:1: Warning: 'as' will become a reserved keyword in Python 2.6 A quick look in parsetok.c reveals that it sets a "handling_import" flag when it stumbles upon an "import" statement, a flag that's later used to suppress the warning message. The bug is that the flag isn't reset until the parser sees an ENDMARKER token (end of file), instead of when it sees the next NEWLINE token. (if someone wants to submit this to bugs.python.org, be my guest) From kyosohma at gmail.com Tue Sep 9 17:20:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 9 Sep 2008 14:20:03 -0700 (PDT) Subject: Wx Python - Code Structure & Event Handling References: Message-ID: <2ec5b585-269d-4ec5-b597-2005520c4de4@m45g2000hsb.googlegroups.com> On Sep 9, 3:05?pm, lee.walc... at gmail.com wrote: > Hi, > > I have just started writing a GUI using wxpython after finding a > limitation using Tkinter. I have read most tutorials on wxpython and > slowly becoming accustomed considering I started with the latter GUI > tool first! > I must quote first that I am a novice user of python so the issue(s) I > have may seem very obvious but please be patient with me! > > I have noticed that all the wxpython references I used for creating my > application(s) ?"cram" all the code in the frame subclass. This is > fine when you consider small applications but what about when they > grow into very complex applications? This creates my first question : > Where is it possible to find information on wxpython code practise/ > structure when considering complex larger Gui's? > > Without any reference I decided to attempt my owm method by breaking > up the top level panels in my frame as individiual class objects. and > then construct the widgets for the panels within the respective > classes. This led to my second problem, how do I use and event in one > Panel to cause an effect in the other Panel ? For example, if I have > button in one Panel and wish to change the text of a label in the > other Panel, what is the best way to do this? Should I break the code > into modules instead? > > Of course, you may explain that the way I have approached this is > completely wrong, if so please tell me, I really want to get the basic > structure right before I start making the code more complex. > > I look forward to your help > > ------------------------------------------------------------------------------------------------------------------------------------- > > I have listed some code below to help explain what concept I wish to > achieve, > > import wx > > class Frame(wx.Frame): > ? ? def __init__(self): > ? ? ? ? wx.Frame.__init__(self, None, > title="Application",size=(400,400)) > ? ? ? ? Panel1 = wx.Panel(self, -1,size=(200,200)) > ? ? ? ? Panel2 = wx.Panel(self, -1,size=(200,200)) > ? ? ? ? Sizer = wx.FlexGridSizer(2,2,5,5) > ? ? ? ? Sizer.Add(Panel1) > ? ? ? ? Sizer.Add(Panel2) > ? ? ? ? self.SetSizerAndFit(Sizer) > ? ? ? ? Util1 = Utils1(Panel1) > ? ? ? ? Util2 = Utils2(Panel2) > > class Utils1(): > ? ? def __init__(self, Panel): > ? ? ? ? button = wx.Button(Panel,-1, "Button 1") > ? ? ? ? Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) > ? ? ? ? self.Label = wx.StaticText(Panel,-1, "Handler to me", > name="Lab1") > ? ? ? ? Sizer = wx.BoxSizer(wx.VERTICAL) > ? ? ? ? Sizer.Add(button) > ? ? ? ? Sizer.Add(self.Label) > ? ? ? ? Panel.SetSizerAndFit(Sizer) > > ? ? def OnClick(self, Evt): > ? ? ? ? self.Label.SetLabel("you changed me") > > class Utils2(): > ? ? def __init__(self, Panel): > ? ? ? ? self.button = wx.Button(Panel,-1, "Button 2") > ? ? ? ? Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) > > ? ? def OnClick(self, Evt): > ? ? ? ? """ what is the easiest & accepted Method of changing the text > in > ? ? ? ? a different class instance?""" > ? ? ? ? pass > ? ? ? ? #???.SetLabel("you changed me") > > app = wx.PySimpleApp() > frame = Frame() > frame.Show() > app.MainLoop() These are good questions for the wxPython list. You'll learn a lot there: http://wxpython.org/maillist.php You'll also find the Style Guide helpful: http://wiki.wxpython.org/wxPython%20Style%20Guide In my more complex applications, I'll do the widgets in their own function, or for a wx.Notebook, I'll do each "book" in their own module by subclassing a wx.Panel object or some such. If you do that sort of thing in their own module subclasses, then the event handlers can go there too. Mike From ggpolo at gmail.com Mon Sep 1 16:26:59 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 1 Sep 2008 17:26:59 -0300 Subject: TkMessageBox - Using sys.exit() is a a great pain. Looking for other similar commands. In-Reply-To: References: Message-ID: On Mon, Sep 1, 2008 at 3:35 PM, wrote: > Hi, > > I'm using a TkMessageBox for handling some errors and displaying them > through the message boxes. > > My code is as below: > if selectedVer == strNoArchivedResults: > tkMessageBox._show("Error", \ > type='ok', icon='error', \ > message="Cannot perform Results > Comparison as no results are currently archived for this library") Note that you are not supposed to use _show, use showerror here instead. > sys.exit() > > This message box is displayed when the above comdition is met: > Using sys.exit() is a great pain since this closes my parent GUI ( the > main GUI). Remove the call to sys.exit then ? > > Please suggest some other way around. Your ask for a suggestion doesn't make much sense to me, try writing what are you trying to achieve. > > > Thanks and regards, > Rajat > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From pavlovevidence at gmail.com Sun Sep 28 19:32:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 28 Sep 2008 16:32:09 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <89bc2582-9d92-4924-a4c9-723c0291cac6@c65g2000hsa.googlegroups.com> On Sep 28, 2:29?pm, process wrote: > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? Although len() is spelled like a function call, in spirit it's an operator, and it behaves like any other operator in Python. Never mind why len() is an operator and not a method in Python, the point is, just as operators like + doesn't make a language less object- oriented (C++ would be very surprised to find out that it's not OO), neither do operator functions like len(). Having said that, I encourage you to understanda a language for what it is, not for whatever computer science buzzword labels it has. Carl Banks From news1234 at free.fr Thu Sep 11 16:25:22 2008 From: news1234 at free.fr (nntpman68) Date: Thu, 11 Sep 2008 22:25:22 +0200 Subject: Adding environment variables to bash. In-Reply-To: References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> Message-ID: <48c97eaf$0$12022$426a74cc@news.free.fr> >> >> doesn't exactly work for Python scripts, though: >> >> $ cat env.py >> #!/usr/bin/env python >> import os >> os.environ["TEST"] = "hello" >> >> $ . ./env.py && env | grep TEST >> import: unable to open X server `'. >> bash: os.environ[TEST]: command not found >> >> >> There's two options for the desperate ones. 1. Assuming the python script doesn't want to print anything useful ========================================================================= the python script just prints the exoprt commands and is being called via backticks from a shell code snipped being sourced with . #-------- mypythonfile.py ------------------------ #!/usr/bin/env python value = myfavourite_python_function() print 'export ENV_VAR="%s"' ^ value #--------------- end of file -------------- #----------------- my_wrapper_file.sh ------------------ `./mypythonfile.py` # file end and then you call . ./my_wrapper_file.sh 2._ Pytho script wants to display something and set a variable =================================================================== a file being invoked with . calls the python script (which will create a small file with variables to be set). then this created file is being sourced #-------- mypythonfile.py ------------------------ #!/usr/bin/env python value = myfavourite_python_function() file('my_export_commands.sh','w').write('export ENV_VAR="%s"\n' % value) #--------------- end of file -------------- #----------------- my_wrapper_file.sh ------------------ ./mypythonfile.py . ./my_export_commands.sh # file end bye N Fredrik Lundh wrote: > John Lawrence wrote: > >> You can make a command use the current shell though if you use the '.' >> command e.g.: >> >> jl > cat env.sh >> export TEST='hello' >> >> jl > ./env.sh && env | grep TEST #Doesn't set TEST in parent >> shell >> jl > . ./env.sh && env | grep TEST #Adding '. ' before the >> command uses the same shell >> TEST=hello > > doesn't exactly work for Python scripts, though: > > $ cat env.py > #!/usr/bin/env python > import os > os.environ["TEST"] = "hello" > > $ . ./env.py && env | grep TEST > import: unable to open X server `'. > bash: os.environ[TEST]: command not found > > > From ldo at geek-central.gen.new_zealand Mon Sep 29 21:50:26 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 30 Sep 2008 14:50:26 +1300 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Message-ID: In message , r0g wrote: > You can only distribute modifications to gnuplot itself as > patches, but you can distribute it freely ... This must be some new definition of "freely" of which I'm unaware. From gherron at islandtraining.com Wed Sep 10 16:39:18 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 10 Sep 2008 13:39:18 -0700 Subject: Python and Open Office In-Reply-To: References: Message-ID: <48C83076.3030703@islandtraining.com> Greg Lindstrom wrote: > Hello, > > I would like to create and manipulate Open Office documents using > Python. I have found then UNO Python page and odfpy modules which > seem to be exactly what I need. The odfpy manual is, to me, a > confusing list of objects and methods (it's an impressive list!), but > does not have much in the way of how to use them. For example, I can > open a spreadsheet and create new pages (there's a nice example near > the back of the manual) but I can't figure out how to open an existing > spreadsheet and list the names of the individual sheets ("tabs"). > > I have written an application that access Microsoft Excel and creates > reports for work, but would like to create an Open Source version > using Open Office and release it to the community (and maybe get a > talk at PyCon :-). > > Is there someone here who can help me out, or is there an appropriate > mailing list for me to join? > > Thanks > > --greg > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list Here's a snippet of code I use to open a spreadsheet (given as a file path name), and compute and return the list of sheets it contains. It connects to an existing OpenOffice if possible, otherwise it starts OpenOffice and waits for it to accept a connection. def OpenSS(path): localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext( 'com.sun.star.bridge.UnoUrlResolver', localContext ) resolveArg='uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext' # Conect to running OO; First, starting OO if necessary; try: ctx = resolver.resolve(resolveArg) except NoConnectException: os.system("ooffice '-accept=socket,host=localhost,port=2002;urp;'&") while 1: print ' waiting for OpenOffice' time.sleep(1) try: ctx = resolver.resolve(resolveArg) break except NoConnectException: pass smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext( 'com.sun.star.frame.Desktop', ctx) url = 'file://' + path component = desktop.loadComponentFromURL(url, '_default', 0, ()) sheets = [component.getSheets().getByIndex(i) for i in range(component.getSheets().getCount())] return sheets Hope this helps, Gary Herro From dmitry at athabascau.ca Thu Sep 25 11:41:04 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 15:41:04 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Dmitry S. Makovey schrieb: >> Dmitry S. Makovey wrote: >>> In my real-life case A is a proxy to B, C and D instances/objects, not >>> just one. >> >> forgot to mention that above would mean that I need to have more than one >> decorator function like AproxyB, AproxyC and AproxyD or make Aproxy >> smarter about which property of A has instance of which class etc. > > __getattr__? see, in your code you're assuming that there's only 1 property ( 'b' ) inside of A that needs proxying. In reality I have several. So in your code self._delegate should be at least a tupple or a list. Plus what you're doing - you just promiscuously passing any method not found in Proxy to self._delegate which is not what I need as I need to pass only a subset of calls, so now your code needs to acquire dictionary of "allowed" calls, and go over all self._delegates to find if any one has it which is not efficient since there IS a 1:1 mapping of A::method -> B::method so lookups shouldn't be necessary IMO (for performance reasons). > class Proxy(object): > > > def __init__(self, delegate): > self._delegate = delegate > > > def __getattr__(self, attr): > v = getattr(self._delegate, attr) > if callable(v): > class CallInterceptor(object): > def __init__(self, f): > self._f = f > > def __call__(self, *args, **kwargs): > print "Called " + str(self._f) + " with " + > str(args) + str(kwargs) > return self._f(*args, **kwargs) > return CallInterceptor(v) > return v > Decorators have *nothing* to do with this. They are syntactic sugar for > def foo(...): > ... > foo = a_decorator(foo) exactly. and in my case they would've simplified code reading/maintenance. However introduced "tight coupling" (A knows about B and be should know about A) is something that worries me and I'm trying to figure out if there is another way to use decorators for my scenario or is there another way of achieving the same thing without using decorators and without bloating up the code with alternative solution. Another way could be to use Metaclass to populate class with method upon declaration but that presents quite a bit of "special" cruft which is more than I have to do with decorators :) (but maybe it's all *necessary* ? ) From eduardo.padoan at gmail.com Sat Sep 20 10:40:25 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Sat, 20 Sep 2008 11:40:25 -0300 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: On Sat, Sep 20, 2008 at 11:26 AM, Kay Schluehr wrote: > On 20 Sep., 12:14, Fredrik Lundh wrote: >> Kay Schluehr wrote: >> > Answer: if you want to define an entity it has to be defined inside a >> > class. If you want to access an entity you have to use the dot >> > operator. Therefore Java is OO but Python is not. >> >> you're satirising the quoted author's cargo-cultish view of object >> orientation, right? >> >> > > I wonder if the OO fetish hasn't already lost much of its magic > powers. What are the most powerful fetishes these days? A year ago I > would have suspected "purely functional" but I'm not sure it has > really caught on. I think the current fetish is paralelism and erlang's share-nothing concurrency model. Or something like it. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Eduardo de Oliveira Padoan http://djangopeople.net/edcrypt/ http://stopforwarding.us/etiq.html From dudeja.rajat at gmail.com Wed Sep 24 11:22:47 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Wed, 24 Sep 2008 16:22:47 +0100 Subject: problem updating variable in a module In-Reply-To: References: Message-ID: Thanks Tim, Yes, I mean 'mod' only. But this does not work for me On Wed, Sep 24, 2008 at 4:19 PM, Tim Rowe wrote: > 2008/9/24 : > > Hi, > > > > I've a problem updating my variable in a module. > > > > In my main program, I call a function from mod1 to update a variable of > mod1 > > As soon as I update this varibale, I check it back in the mail program > but > > it the variable from mod1 does not get updated. > > > > main Program: > > **************** > > import mod1 > > a = 20 > > mod.update(a) > > print mod.a <---- does not print anything > > > > mod1 > > ******** > > a = 10 > > def update(someInt): > > global a > > a = someInt > > print a <---- this does actually print a = 20 > > I'm surprised it runs at all -- as far as I can see "mod" in > "mod.update(a)" and "print mod.a" is not defined. Did you mean "mod1"? > If I change it to that, both print statements print "20" as I'd > expect. > > I take it you do have a *really* good reason to use a global? > > -- > Tim Rowe > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regrads, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Sep 14 05:29:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Sep 2008 09:29:55 GMT Subject: Function getting a reference to its own module Message-ID: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> I have a function that needs a reference to the module object it is defined in. (For the reason why, if you care, see the thread "doctest not seeing any of my doc tests" from a week ago.) I know of two ways to deal with this problem, both of which feel unsatisfactory to me. Assume the name of the module is "Mod", then I can do either of these: def foo(): import Mod process(Mod) Disadvantage: If I change the name of the module, I have to remember to change the name of the module reference in foo() twice. def foo(): modname = foo.__module__ module = __import__(modname) process(module) Disadvantage: if I change the name of the function, I have to remember to change the reference to itself, but at least both changes are right next to each other. Assume that changing the function name or the module name are both equally likely/unlikely. Which do other people prefer? Which seems "better" to you? Are there any other alternatives? -- Steven From mnordhoff at mattnordhoff.com Fri Sep 12 02:07:16 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 12 Sep 2008 06:07:16 +0000 Subject: function return In-Reply-To: References: <48C9242E.6090509@mattnordhoff.com> Message-ID: <48CA0714.5000702@mattnordhoff.com> Gabriel Genellina wrote: > En Thu, 11 Sep 2008 10:59:10 -0300, Matt Nordhoff > escribi?: > >>> result = "%s\t%s\t%s" %(id,gene_symbol,ptms) >> >> This is very trivial, but you could change the above line to: >> >> result = "\t".join(id, gene_symbol, ptms) > > So trivial that you did not even attempt to test it, I presume. It must > obviously work... except it doesn't :) > > result = "\t".join((id, gene_symbol, ptms)) Haha, whoops. Sorry! -- From bhaarat.s at gmail.com Fri Sep 12 21:25:10 2008 From: bhaarat.s at gmail.com (bhaarat Sharma) Date: Fri, 12 Sep 2008 18:25:10 -0700 Subject: Good python web programming books In-Reply-To: <47c890dc0809121808g3c57e4b8p87166657a7b4a29e@mail.gmail.com> References: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> <47c890dc0809121808g3c57e4b8p87166657a7b4a29e@mail.gmail.com> Message-ID: <491bd2b50809121825y7c5c8577ye86c271694db47df@mail.gmail.com> That will be concentrating more on the Django framework On Fri, Sep 12, 2008 at 6:08 PM, Chris Rebert wrote: > I've heard good things about The Django Book: http://www.djangobook.com/ > - Chris > > On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma > wrote: > > Hi Guys, > > > > I am very new to python. I am looking for a good book about python web > > programming. > > > > I looked at a few online like Web Programming In Python but most are > quite > > old. > > > > If you've read a good book on python web programming can you please > suggest > > some? > > > > Thanks > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Follow the path of the Iguana... > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Sep 3 09:26:21 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2008 15:26:21 +0200 Subject: Custom handler for logging References: Message-ID: Luigi Paioro wrote: > concerning the logging module, I have written a new Handler which stores > the logging messages in an SQLite database. It works well, but when I > try to use it exploiting a configuration file I have a problem since the > "class" entry does not accept a class which is not within the logging > name-space, while the class I implemented is coded in my personal module > (thus another name-space). > > Is there a workaround to allow the usage of custom handlers? Maybe http://mail.python.org/pipermail/python-list/2003-October/232762.html Peter From marco.bizzarri at gmail.com Thu Sep 18 13:37:52 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 18 Sep 2008 19:37:52 +0200 Subject: Zsi interoperability In-Reply-To: References: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <3f0d61c40809181037g2d63593fr7e69d747857a6dd6@mail.gmail.com> On Thu, Sep 18, 2008 at 7:10 PM, Dieter Maurer wrote: > "Marco Bizzarri" writes on Mon, 15 Sep 2008 20:26:27 +0200: >> On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel wrote: >> > Mailing List SVR wrote: >> >> I have to implement a soap web services from wsdl, the server is >> >> developed using oracle, is zsi or some other python library for soap >> >> interoperable with oracle soa? >> > >> > No idea, but I'd definitely try soaplib before ZSI. >> > >> > Stefan >> >> I'm working on a project where I need to write a client for SOAP with >> Attachments; I can see ZSI does not support it > > The ZSI documentation (2.0) says that SOAP attachments are supported -- > but I never tried it. > > > Dieter > -- > http://mail.python.org/mailman/listinfo/python-list > That's right; but if you look at the code, it seems like it is able to create a server which behaves in that way, but not to create a client for it. But I'm still exploring... -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From mdsherry at gmail.com Wed Sep 24 10:32:56 2008 From: mdsherry at gmail.com (mdsherry at gmail.com) Date: Wed, 24 Sep 2008 07:32:56 -0700 (PDT) Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: On Sep 24, 9:17?am, Marin Brkic wrote: > Not commercial distribution, but an academic kind of sorts - giving > the exe file to coleagues, so they can use it in their work. Giving > .py file is not an option, since due to centralized computer > maintenance, they don't (and cannot) have installed python (except the > ones that bring their own computer at work, but those are an > exception). > > As far as I know py2exe is the only option which can do such a thing > (make exe files from scripts). Is there a way to make those exe files > a little smaller (for a small script they easily go up to 5-10 mb). > > Has anyone had a situation like this ? All your inputs and suggestions > are more then welcomed. > > -- > Marin If you don't create a monolithic EXE, then most of the extra files (that make up the bulk of the size) can be shared between other converted scripts. That is, if you convert foo.py, and send the bundle to your colleague, then convert bar.py, you only need to send bar.exe, and it will run fine if they execute it in the same directory that has all the DLLs you sent with foo.exe. Another option might be to encourage them to download Portable Python, which doesn't need to be installed. Mark Sherry From richardlev at gmail.com Wed Sep 10 04:33:50 2008 From: richardlev at gmail.com (Richard Levasseur) Date: Wed, 10 Sep 2008 01:33:50 -0700 (PDT) Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> Message-ID: On Sep 9, 8:53?am, Luigi wrote: > Dear all, > > I'm writing an XML-RPC server which should be able to modify the > incoming request before dispatching it. In particular I wand to added > two fixed parameters to the method called: one is the client host > address, and the other is the user name provided as for Basic > Authentication (http://u... at www.bla-bla.com). > > To do this, at the present I've overwritten the do_POST method of > SimpleXMLRPCRequestHandler, including at a certain point this code: > > .... > data = ''.join(L) > > params, method = xmlrpclib.loads(data) > user = "unknown" > if self.headers.has_key('Authorization'): > ? # handle Basic authentication > ? (enctype, encstr) = ?self.headers.get('Authorization').split() > ? user, password = base64.standard_b64decode(encstr).split(':') > params = list(params) > params.append(self.address_string()) > params.append(user) > params = tuple(params) > data = xmlrpclib.dumps(params, methodname=method) > > (I slightly modified it to make it more readable at mail level) > > It works, but I don't really like it because it completely overwrites > the do_POST method that in the future Python releases is going to > change (I verified it). Do you know a better way to do this? > > Thanks in advance. > > Luigi I actually wrote a wsgi module for almost this -exact- use case (having to prepend a user/password to the method calls). The simple rpc server and dispatchers didn't give me enough control over the behavior, so I had to reimplement all the logic surround the loads/ dumps calls, and eventually that just turned into the bulk of the whole SimpleXMLRPCServer module. There's a lot of tight coupling in the _dispatch method, so you'll have to override, monkey patch, or reimplement it. From roy at panix.com Sun Sep 14 15:34:21 2008 From: roy at panix.com (Roy Smith) Date: Sun, 14 Sep 2008 15:34:21 -0400 Subject: Abstract class References: Message-ID: Mr.SpOOn wrote: > Well, from a SharpNote I can obtain the relative NaturalNote. So if I > have a C# I can call > > natural('C#') and get 'C' And why should you not be allowed to apply natural() to a NaturalNote? I would think it would just be an identity operator. > While in the class NaturalNote I don't need such a method, but I need > two methods to get the sharped and flatted version Well, you may need sharp() and flat() methods on all notes. Can't you do sharp('C#'), which should give you C double-sharp? > > Consider the following code: > > > > note1 = SharpNote("E4") > > note2 = NaturalNote("F4") > > if note1 == note2: > > print "the same note" > > else > > print "different notes" > > > > what should it print? > > Well, that's not so simple. I know it's not simple. I don't know what the correct answer is, or even if the problem admits to having a single universally correct answer. I'm just pointing out something you should probably think about. > Anyway, I think I need an abstract class. Or not? Hard to tell. My advice would be to start out with a single Note class and start writing code. If you get to the point where you're writing lots of conditional logic in your methods (if sharp, do this, if flat, do that), that's a hint that you may indeed need to refactor things into subclasses. The next step would be to figure out what the right hierarchy is. Offhand, I can think of three hierarchies which might be plausible: ------------------------------ Note SharpNote(Note) DoubleSharpNote(Note) FlatNote(Note) DoubleFlatNote(Note) This is a relatively flat (sorry about that) hierarchy. Note (arghhh!!) that there is no explicit NaturalNote class; notes which are not sharp or flat are just instances of Note. ------------------------------ AbstractNote NaturalNote(AbstractNote) SharpNote(AbstractNote) DoubleSharpNote(AbstractNote) FlatNote(AbstractNote) DoubleFlatNote(AbstractNote) This one sounds like what I think you've currently got in mind. ------------------------------ AbstractNote NaturalNote(AbstractNote) SharpNote(AbstractNote) DoubleSharpNote(SharpNote) FlatNote(AbstractNote) DoubleFlatNote(FlatNote) This one is similar to the above, except that the double-{sharp,flat} note are subclasses of their single versions. ------------------------------ I have no idea which is the right way to represent this. Some people would agonize over the decision for days before writing a single piece of code. My personal preference is to start small, get some code written, and let the code teach you what makes sense. If things are flowing smoothly, you probably picked a good way to organize your classes. If things are ugly and you find yourself writing lots of gnarly conditional code, that's a hint you're off on the wrong track. Don't be afraid to throw it away and start from scratch. BTW, here's another thing to think about. Is a C in a signature where C is not sharp the same as a C in a signature where it is sharp but written with a natural accidental? I have no clue, but when you figure out what answer makes sense for you, that might help you decide how you're going to organize your classes. From lists at cheimes.de Tue Sep 2 13:36:04 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 02 Sep 2008 19:36:04 +0200 Subject: source for the property function In-Reply-To: <6072EAA1-9891-4910-80B4-A26820712387@river2sea.org> References: <6072EAA1-9891-4910-80B4-A26820712387@river2sea.org> Message-ID: Rowland Smith wrote: > Anyone know where the source code for the built-in property function is > located in a python distribution? > > I would like to see how it works - mainly, how does it know which class > it is being called from? Property is not a function but a type. Properties are a common usage for the descriptor protocol. You can find the implementation of the property type in the file http://svn.python.org/projects/python/branches/release25-maint/Objects/descrobject.c Christian From arnodel at googlemail.com Sun Sep 14 05:43:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Sep 2008 02:43:45 -0700 (PDT) Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> Message-ID: <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> On Sep 14, 10:29?am, Steven D'Aprano wrote: > I have a function that needs a reference to the module object it is > defined in. (For the reason why, if you care, see the thread "doctest not > seeing any of my doc tests" from a week ago.) I know of two ways to deal > with this problem, both of which feel unsatisfactory to me. Assume the > name of the module is "Mod", then I can do either of these: > > def foo(): > ? ? import Mod > ? ? process(Mod) > > Disadvantage: If I change the name of the module, I have to remember to > change the name of the module reference in foo() twice. > > def foo(): > ? ? modname = foo.__module__ > ? ? module = __import__(modname) > ? ? process(module) > > Disadvantage: if I change the name of the function, I have to remember to > change the reference to itself, but at least both changes are right next > to each other. > > Assume that changing the function name or the module name are both > equally likely/unlikely. > > Which do other people prefer? Which seems "better" to you? Are there any > other alternatives? What about something like: sys.modules[__name__] ? -- Arnaud From clp at rebertia.com Thu Sep 4 16:16:23 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 4 Sep 2008 13:16:23 -0700 Subject: Converting .doc to .txt in Linux In-Reply-To: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> References: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: <47c890dc0809041316n3ed149c3lff1ef8def74fd447@mail.gmail.com> I'd recommend using one of the Word->txt converters for Linux and just running it in a shell script: * http://wvware.sourceforge.net/ * http://www.winfield.demon.nl/ No compelling reason to use Python in this instance. Right tool for the right job and all that. - Chris On Thu, Sep 4, 2008 at 12:54 PM, wrote: > Hi Everyone, > > I had previously asked a similar question, > http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gst&q=convert+doc+txt#9dc901da63d8d059 > > but at that point I was using Windows and now I am using Linux. > Basically, I have some .doc files that I need to convert into txt > files encoded in utf-8. However, win32com.client doesn't work in > Linux. > > It's been giving me quite a headache all day. Any ideas would be > greatly appreciated. > > Best, > Patrick > > #Windows Code: > import glob,os,codecs,shutil,win32com.client > from win32com.client import Dispatch > > input = '/home/pwaldo2/work/workbench/current_documents/*.doc' > input_dir = '/home/pwaldo2/work/workbench/current_documents/' > outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/' > > for doc in glob.glob1(input): > WordApp = Dispatch("Word.Application") > WordApp.Visible = 1 > WordApp.Documents.Open(doc) > WordApp.ActiveDocument.SaveAs(doc,7) > WordApp.ActiveDocument.Close() > WordApp.Quit() > > for doc in glob.glob(input): > txt_split = os.path.splitext(doc) > txt_doc = txt_split[0] + '.txt' > txt_doc_path = os.path.join(outpath,txt_doc) > doc_path = os.path.join(input_dir,doc) > shutil.copy(doc_path,txt_doc_path) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From hniksic at xemacs.org Fri Sep 12 10:01:45 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Sep 2008 16:01:45 +0200 Subject: Accessing __slots__ from C References: Message-ID: <8763p1799y.fsf@mulj.homelinux.net> Chris writes: >> descr = GetAttrString(cls,"varname"); >> offset = descr->d_member->offset; >> slotvar = (PyObject*)(((char*)obj)+offset) > > Unfortunately, I am inexperienced at this kind of thing, so I wasn't > able to get something working. Maybe someone could tell me what's > wrong with the code below (it gives the error "'struct _object' has no > member named 'd_member'")? You are getting that error because Carl forgot to cast the descriptor to the appropriate C type, in this case PyMemberDescrObject. The last line is also incorrect, I think. Try something like this: PyObject *descr = PyObject_GetAttrString(x,"attr_one"); int offset = ((PyMemberDescrObject *) descr)->d_member->offset; PyObject *slotvar = *(PyObject **)(((char *) obj) + offset); From bearophileHUGS at lycos.com Mon Sep 29 16:04:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 13:04:48 -0700 (PDT) Subject: Finding subsets for a robust regression References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> Message-ID: tkp... at hotmail.com: > My code follows, and it seems a bit clumsy - is there a cleaner way to do it? The code doesn't look bad. I can suggest few things: - When you have "paragraphs" of code that do something definite then the comment before them can be written without indentation, to denote it regards the whole little block. Or you can even call a subfunction (a function inside another function/method) - Finding good names for variables is important. So this code: > d = {} #identify unique instances of x and y > for xx,yy in zip(x,y): > if xx in d: > d[xx].append(yy) > else: > d[xx] = [yy] May become (untested): > # identify unique instances of x and y > d = {} > for xx, yy in zip(x, y): > if xx in d: > d[xx].append(yy) > else: > d[xx] = [yy] Or better: > # identify unique instances of seqx and seqx > d = defaultdict(list) > for x, y in izip(seqx, seqx): > d[x].append(y) Or even something like: > def unique_x(seqx, seqx): > """identify unique instances of seqx and seqx""" > result = defaultdict(list) > for x, y in izip(seqx, seqx): > result[x].append(y) > return result > ... > d = unique_x(x, y) The following line is too much heavy, it looks like a misuse of the inline if syntax: > y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else > yy[l//2] ) It was not added to python for that long lines. This looks better to me: l = len(yy) if l == 1: y_median = yy[0]) else: yy.sort() if l & 1: y_median = yy[l // 2] else: y_median = yy[l // 2 - 1] + yy[l // 2]) / 2.0 y1.append(y_median) But even better is to use a stronger library code, for example a median() able to run in O(n), and a more strong unique(), like: http://code.activestate.com/recipes/438599/ http://code.activestate.com/recipes/466330/ But using a stronger unique() this time isn't useful, so I like this compromise: # identify unique instances of seqx and seqx uniques_x = defaultdict(list) for x, y in izip(seqx, seqx): uniques_x[x].append(y) result_x = [] result_y = [] for x, ys in uniques_x.iteritems(): result_x.append(x) result_y.append(median(ys)) If you want to use the last bit of semantics of CPython you can even write that code like this: # identify unique instances of seqx and seqx uniques_x = defaultdict(list) for x, y in izip(seqx, seqx): uniques_x[x].append(y) result_x = uniques_x.keys() result_y = map(median, uniques_x.itervalues()) I think it works because keys and values are given in the same order, but in real code I tend to avoid using such subtle things. Because if you translate that code to another language, or you use another Python implementation it may not work anymore, and lot of code sooner or later becomes translated... Bye, bearophile From robert.kern at gmail.com Thu Sep 4 17:22:51 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Sep 2008 16:22:51 -0500 Subject: why is self not passed to id()? In-Reply-To: <200809042244.54418.maric@aristote.info> References: <200809042244.54418.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez ?crit : >> class foo(list): >> __hash__ = lambda x: id(x) > > Wow ! You are really going on trouble with this, believe me there is a real > good reason for list not to be hashable. A dictionnary or set containing some > of your foo is virtually inconsistent, read carefully the manual about > prerequesites for dict keys, they *need* to be immutable. Well, that's not entirely true. They need to be not mutated while they are in the dictionary, certainly. At least not in ways that affect equality testing. In this case, one would also have to override list.__eq__ to also compare by identity, too. Then you could mutate the lists to your heart's content and the dictionary wouldn't care. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From M8R-yfto6h at mailinator.com Tue Sep 2 00:05:28 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 1 Sep 2008 21:05:28 -0700 Subject: How to print first(national) char from unicode string encoded inutf-8? References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com><7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> Message-ID: "Marco Bizzarri" wrote in message news:mailman.331.1220276398.3487.python-list at python.org... > On Mon, Sep 1, 2008 at 3:25 PM, wrote: > >> >> When I do ${urllib.unquote(c.user.firstName)} without encoding to >> latin-1 I got different chars than I will get: no ?ukasz but ? ukasz >> -- >> http://mail.python.org/mailman/listinfo/python-list > > That's crazy. "string".encode('latin1') gives you a latin1 encoded > string; latin1 is a single byte encoding, therefore taking the first > byte should be no problem. > > Have you tried: > > urlib.unquote(c.user.firstName)[0].encode('latin1') or > > urlib.unquote(c.user.firstName)[0].encode('utf8') > > I'm assuming here that the urlib.unquote(c.user.firstName) returns an > encodable string (which I'm absolutely not sure), but if it does, this > should take the first 'character'. The OP stated that the original string was "encoded in UTF-8 and urllib.quote()", so after urllib.unquote the string is in UTF-8 format. This must be decoded into a Unicode string before removing the first character: urllib.unquote(c.user.firstName).decode('utf-8')[0] The next problem is that the character in the OP's example string '?' is not present in the latin-1 encoding, but using utf-8 encoding demonstrates that the full two-byte UTF-8 encoded character is collected: >>> import urllib >>> name = urllib.quote(u'?ukasz'.encode('utf-8')) >>> name '%C5%81ukasz' >>> urllib.unquote(name).decode('utf-8')[0].encode('utf-8') '\xc5\x81' -Mark From neoedmund at gmail.com Fri Sep 5 08:20:33 2008 From: neoedmund at gmail.com (neoedmund) Date: Fri, 5 Sep 2008 05:20:33 -0700 (PDT) Subject: newbie question: how to run a python file if it is in a package References: <6icighFpi4dpU1@mid.uni-berlin.de> Message-ID: <9feb3516-097c-4458-a4d9-f02d00ce9d4b@1g2000pre.googlegroups.com> On Sep 5, 8:12?pm, "Diez B. Roggisch" wrote: > neoedmund schrieb: > > > for example: > > > X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y" > > how can I run X.py avoiding it saying such like "ImportError: No > > module named aaa.bbb"? > > > Is all runnable script must be in the default package? > > There is no such thing as a "default package" > > All imports are resolved over the "sys.path" list of directories (or eggs). > > There are various ways to modify this: > > ? - by hand. If you know X.py lives below aaa/bbb, you can get it's > ? ? __file__-attribute, and walk the way down two levels. Then add the > ? ? resulting path to sys.path. All this has to be done before any > ? ? import of aaa.bbb occurs. > > ? - modify the environment variable PYTHONPATH to contain the root of > ? ? aaa.bbb before starting the script. > > ? - write a custom .pth-file and place it into your pythno installation. > ? ? The pth-file will contain the above mentioned root path. > > ? - use setuptools to create script entry-points, and install your whole > ? ? application either fully, or as so-called egg-link. Possibly inside > ? ? a virtualenv. This would be my personally preferred method. > > ? - simply copy your wohe aaa.bbb-stuff into site-packages. Make sure you > ? ? do that whenever you change something in your code. > > Diez thanks Diez, i think your answer is almost perfect. From fredrik at pythonware.com Thu Sep 11 10:19:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 16:19:26 +0200 Subject: Python platform. In-Reply-To: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> Message-ID: carriere.jonathan at gmail.com wrote: > I wonder if there is a platform written in python. The equivalent of > the Netbeans platform http://platform.netbeans.org/ in the Python > world. Do you know such a thing? You (or maybe the Java folks) seem to have missed that platform has a rather specific meaning in computing: http://en.wikipedia.org/wiki/Platform_(computing) Given that definition, Python is pretty much a platform in itself. If you want to use Python for a specific task, you add libraries for that task. Tell us what you want to do, and we'll tell you what libraries and toolkits you might want to try. From grante at visi.com Sun Sep 14 20:29:18 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 19:29:18 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> Message-ID: <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> On 2008-09-14, Ben Finney wrote: > Astley Le Jasper writes: > >> Is it best to have it all in one script or split it into per >> site scripts that can then be called by a manager script? If >> everything is in one script would you have per site functions >> to extract the data or generic function that contain vary >> slightly depending on the site, for example >> >> import firstSiteScript >> import secondSiteScript > > First: each of these things you're importing is a "module" in > Python. A script is what I prefer, for clarity, to call a > "program": it's intended to be executed independently as the > top level of execution. > > Second: please do yourself a favour and drop the camelCaseNames. > Follow PEP 8 for style > and naming in your Python code. If he finds camelcase more readable and easier to type (as do I), how is switching to underscores "doing himself a favor"? I'm generally in favor of using a consistent naming style throughout a project, but I don't see why the naming style used in my source code should be subject to somebody else's arbitrary standard. When it comes to writing code intended for the standard library in the main Python distribution, I would certainly defer to the existing standard as defined in PEP 8. However, I don't see any reason that style should be imposed on all everybody else. -- Grant From steven at REMOVE.THIS.cybersource.com.au Wed Sep 17 21:48:27 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 01:48:27 GMT Subject: Do HTTPError objects always have a read method? Message-ID: I understood that HTTPError objects always have a read method, so they can be treated as if they were a webpage. E.g. something like this simplified snippet: address = 'http://www.yahoo.com/spamspamspamspamspam' try: conn = urllib2.urlopen(address) except urllib2.HTTPError, e: conn = e print conn.read() # Print the requested page, or the error page. But in the source code to urllib2 (Python 2.5): class HTTPError(URLError, addinfourl): """Raised when HTTP error occurs, but also acts like non-error return""" __super_init = addinfourl.__init__ def __init__(self, url, code, msg, hdrs, fp): self.code = code self.msg = msg self.hdrs = hdrs self.fp = fp self.filename = url # The addinfourl classes depend on fp being a valid file # object. In some cases, the HTTPError may not have a valid # file object. If this happens, the simplest workaround is to # not initialize the base classes. if fp is not None: self.__super_init(fp, hdrs, url) def __str__(self): return 'HTTP Error %s: %s' % (self.code, self.msg) That tells me that HTTPError objects aren't guaranteed to include a file- like interface. That makes me unhappy. Under what circumstances do HTTPError objects not have a valid file object? How common is this? Does anyone have an example of a URL that fails in that fashion? Thank you, -- Steven From bearophileHUGS at lycos.com Tue Sep 2 17:36:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 2 Sep 2008 14:36:16 -0700 (PDT) Subject: Renumbering References: Message-ID: <4e3e6643-ca68-4d59-b6d6-e3a358c6fc03@f36g2000hsa.googlegroups.com> Francesco Pietra, few notes: - In Python and C item numbering generally starts from 0, so you talk about column 0, 1, etc. - You can also use the Italian Python newsgroup if know Italian. - The number of lines with a particular number doesn't seem important to solve your problem. - You don't need to try to set non-proportional characters on usenet. This is a first try at a solution, you can tell us if it's correct: data = """\ ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 ATOM 3425 CA LEU B 428 142.918 87.524 78.875 1.00115.20 2SG3427 ATOM 3426 CB LEU B 428 141.559 88.057 78.392 1.00115.20 2SG3428 ATOM 3427 CG LEU B 428 140.577 88.341 79.544 1.00115.20 2SG3429 ATOM 3428 CD1 LEU B 428 141.102 89.464 80.454 1.00115.20 2SG3430 ATOM 3429 CD2 LEU B 428 139.159 88.615 79.017 1.00115.20 2SG3431 ATOM 3430 C LEU B 428 142.680 86.253 79.615 1.00115.20 2SG3432 ATOM 3431 O LEU B 428 142.725 86.226 80.842 1.00115.20 2SG3433 ATOM 3432 N SER B 429 142.432 85.155 78.878 1.00134.86 2SG3434 ATOM 3433 CA SER B 429 142.175 83.908 79.534 1.00134.86 2SG3435 ATOM 3434 CB SER B 429 141.666 82.805 78.590 1.00134.86 2SG3436 ATOM 3435 OG SER B 429 140.392 83.155 78.069 1.00134.86 2SG3437 ATOM 3436 C SER B 429 143.451 83.432 80.141 1.00134.86 2SG3438 ATOM 3437 O SER B 429 144.543 83.756 79.676 1.00134.86 2SG3439""" lines = (line.split() for line in data.splitlines()) for parts in lines: if parts[4] == "B": parts[5] = str( int(parts[5]) - 427) parts[2] = parts[2].ljust(4) print " ".join(parts) It prints: ATOM 3424 N LEU B 1 143.814 87.271 77.726 1.00115.20 2SG3426 ATOM 3425 CA LEU B 1 142.918 87.524 78.875 1.00115.20 2SG3427 ATOM 3426 CB LEU B 1 141.559 88.057 78.392 1.00115.20 2SG3428 ATOM 3427 CG LEU B 1 140.577 88.341 79.544 1.00115.20 2SG3429 ATOM 3428 CD1 LEU B 1 141.102 89.464 80.454 1.00115.20 2SG3430 ATOM 3429 CD2 LEU B 1 139.159 88.615 79.017 1.00115.20 2SG3431 ATOM 3430 C LEU B 1 142.680 86.253 79.615 1.00115.20 2SG3432 ATOM 3431 O LEU B 1 142.725 86.226 80.842 1.00115.20 2SG3433 ATOM 3432 N SER B 2 142.432 85.155 78.878 1.00134.86 2SG3434 ATOM 3433 CA SER B 2 142.175 83.908 79.534 1.00134.86 2SG3435 ATOM 3434 CB SER B 2 141.666 82.805 78.590 1.00134.86 2SG3436 ATOM 3435 OG SER B 2 140.392 83.155 78.069 1.00134.86 2SG3437 ATOM 3436 C SER B 2 143.451 83.432 80.141 1.00134.86 2SG3438 ATOM 3437 O SER B 2 144.543 83.756 79.676 1.00134.86 2SG3439 Your data is probably in a file, so you have to change the first line of the code: lines = (line.split() for line in open("namefile.txt")) If your output file must to hard-coded columns (and generally those files don't need such property) then you have to make that code of mine more complex... Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Sep 16 04:02:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 05:02:08 -0300 Subject: PyArg_ParseTuple for parsing list and dictionary arguments References: <207312b70809150258n57240c25me70ad03b6339b579@mail.gmail.com> Message-ID: En Mon, 15 Sep 2008 06:58:48 -0300, Pau Freixes escribi?: > Hi to all, > > What's the best way for parse one list or dict argument with > PyArg_ParseTuple Function ? > > If I have this python code : > > import example > > example.test("hellow", ["a", "b"], { "a" : 1 }) > > The c extension for implementation test function must be like this : > > static PyObject * test( PyObject *self, PyObject *args) > { > PyObject * dict, * list; > char * string; > > PyArg_ParseTuple(args, "sOO", string, dict, list); > ...... > } I don't understand the actual question - the example looks fine, what's your problem? Do you want to check the object types? Use PyDict_Check / PyList_Check. -- Gabriel Genellina From fredrik at pythonware.com Fri Sep 12 12:35:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 18:35:53 +0200 Subject: lacking follow-through In-Reply-To: References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> Message-ID: Steve Holden wrote: > The defence rests. can you please stop quoting that guy, so we don't have to killfile you as well... From timr at probo.com Thu Sep 11 01:32:00 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 11 Sep 2008 05:32:00 GMT Subject: universal unicode font for reportlab References: Message-ID: Duncan Booth wrote: > >Laszlo Nagy wrote: > >> I need to use HTML anyway. I realized that universal unicode fonts are >> above 5MB in size. The report would be a 10KB PDF, but I need to embed >> the font before I can send it to anyone. Since some reports needs to be >> sent in emails, I need to use something else. I cannot be sending 10MB >> emails for "one page" reports. >> >I thought that usually when you embed a font in a PDF only the glyphs which >are actually used in the document get embedded. Unfortunately a quick test >with reportlab seems to show that it doesn't do that optimisation: it looks >as though it just embeds the entire font. No, it does subsetting. There was a debate a year or two ago on the reportlab list about how the font subset should be named in the resulting PDF file. Is it possible you have an older release? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rhamph at gmail.com Tue Sep 23 17:00:25 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 23 Sep 2008 14:00:25 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: On Sep 22, 7:13?pm, process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. Eliminating tail calls affects the semantics of your program (by changing memory complexity). As an optimization, it's a side-effect of the implementation, which is a particularly nasty kind of side- effect. Even if guaranteed it's fairly subtle. "return x()" would be optimized while "return x() + 1" would not. Or maybe you're calling a function that uses a wrapper and the wrapper isn't tweaked right to be optimized. Recursion in general can be very useful, but not tail-recursion. The only time it's not trivial to convert tail-recursion into a loop is when it involves multiple functions, but even that can be done if you know how. From bearophileHUGS at lycos.com Sun Sep 28 16:19:22 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 28 Sep 2008 13:19:22 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: sotirac: > random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 elements But note that's without replacement. So if you want really random numbers you can do this: >>> from string import digits >>> from random import choice >>> "".join(choice(digits) for d in xrange(5)) '93898' If you need more speed you can invent other solutions, like (but I don't know if it's faster): >>> from random import shuffle >>> ldigits = list(digits) >>> ldigits ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> shuffle(ldigits) >>> ldigits ['3', '8', '6', '4', '9', '7', '5', '2', '0', '1'] >>> "".join(ldigits[:5]) '38649' But this may be the most efficient way: >>> from random import randrange >>> str(randrange(100000)).zfill(5) '37802' Bye, bearophile From mhuening at zedat.fu-berlin.de Sun Sep 7 11:17:14 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Sun, 07 Sep 2008 17:17:14 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: References: Message-ID: <6ii9jbFqoe2eU1@mid.uni-berlin.de> Hi, > - - Connection.enable_load_extension(enabled) to allow/disallow extension > loading. Allows you to use fulltext search extension, for example ;-) The following code (from the docs) produces an error: from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:") # Load the fulltext search extension con.enable_load_extension(True) con.execute("select load_extension('./fts3.so')") con.enable_load_extension(False) Error is: con.execute("select load_extension('./fts3.so')") pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht gefunden. Where should I look for the module? Matthias From deets at nospam.web.de Wed Sep 10 04:00:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 10:00:35 +0200 Subject: I want to use a C++ library from Python In-Reply-To: References: Message-ID: <6ipd53FrptpiU1@mid.uni-berlin.de> Anders Eriksson schrieb: > Hello, > > I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1 > .lib and 1 .dll files. I don't have the source code. > > How can I create a Python module from these files? Did you bother googling? http://www.google.de/search?q=python+c%2B%2B&ie=utf-8&oe=utf-8 Diez From fredrik at pythonware.com Sun Sep 7 04:18:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 07 Sep 2008 10:18:57 +0200 Subject: Directory creation In-Reply-To: <275302.58315.qm@web7908.mail.in.yahoo.com> References: <275302.58315.qm@web7908.mail.in.yahoo.com> Message-ID: srinivasan srinivas wrote: > Can someone tell me is there any module available to create directories?? > > I tried os, tempfile. > I was facing some issues with os.mkdir(). The mode setting was not proper with this method. > > I created the directory 'stdin' with '0700' mode using os.mkdir() method. > > $> ls -alR stdin/ > stdin/: > total 12 > drwx--S--- 2 munisams munisams 4096 Sep 3 02:00 . > > What is that 'S' in the group permission field?? David Wright explained why this is the expected behaviour last time you posted about this: http://groups.google.com/group/comp.lang.python/msg/f6a91447f1739e66 From bignose+hates-spam at benfinney.id.au Thu Sep 4 21:12:33 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 05 Sep 2008 11:12:33 +1000 Subject: Python test case management system? References: Message-ID: <87iqtbmm4e.fsf@benfinney.id.au> Mudcat writes: > Does anyone know of a good test case management system written in > python, or possibly another application (either open source or > commercial) that can be extended using python? What would the behaviour of such a system be? In other words, what is a "test case management system" in terms of the things that it does? -- \ ?Dad always thought laughter was the best medicine, which I | `\ guess is why several of us died of tuberculosis.? ?Jack Handey | _o__) | Ben Finney From tjreedy at udel.edu Wed Sep 10 20:46:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 20:46:50 -0400 Subject: Reading binary data In-Reply-To: <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> References: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> Message-ID: Aaron Scott wrote: > Taking everything into consideration, my code is now: > > import struct > file = open("test.gde", "rb") > signature = file.read(3) > version, attr_count = struct.unpack('II', file.read(8)) > print signature, version, attr_count > for idx in xrange(attr_count): > attr_id, attr_val_len = struct.unpack('II', file.read(8)) > attr_val = file.read(attr_val_len) > print attr_id, attr_val_len, attr_val > file.close() > > which gives a result of: > > GDE 2 2 > 1 4 ? > 2 4 ? ? > > Essentially, the same results I was originally getting : It appears that your 4-byte attribute values are not what you were expecting. Do you have separate info on the supposed contents? In any case, I would print repr(attr_val) and even for c in attr_val: print(ord(c)). tjr From febkimbleox at gmail.com Sat Sep 27 07:15:05 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:15:05 -0700 (PDT) Subject: 3d sex 3d sex comics 3d sex comic 3d sex games - Free Message-ID: 3d . . . *******CLICK HERE******** http://vids365.cn/3d ***************************** . . . . . . . . . . . . It was a pretty standard sort of service but the vicar kept 3d reasonably informal and cheerful and most importantly from my point of view short. It was a pretty standard sort of service but the vicar kept sex reasonably informal and cheerful and most importantly from my point of view short. It was a pretty standard sort of service but the vicar kept 3d reasonably informal and cheerful and most importantly from my point of view short. ? sex lowered sex head and frowned. ? comics lowered comics head and frowned. ? 3d lowered 3d head and frowned. ? sex lowered sex head and frowned. ? comic lowered comic head and frowned. ? 3d lowered 3d head and frowned. ? sex lowered sex head and frowned. ? games lowered games head and frowned. ? free lowered free head and frowned. ? 3d lowered 3d head and frowned. ? sex lowered sex head and frowned. ? games lowered games head and frowned. Inflamed with lust 3d moved my hand inside 3d ?s panties and eased them down. Inflamed with lust cartoon moved my hand inside cartoon ?s panties and eased them down. Inflamed with lust sex moved my hand inside sex ?s panties and eased them down. Inflamed with lust sex moved my hand inside sex ?s panties and eased them down. Inflamed with lust igre moved my hand inside igre ?s panties and eased them down. Inflamed with lust 3d moved my hand inside 3d ?s panties and eased them down. Inflamed with lust 3d moved my hand inside 3d ?s panties and eased them down. Inflamed with lust anime moved my hand inside anime ?s panties and eased them down. Inflamed with lust sex moved my hand inside sex ?s panties and eased them down. Inflamed with lust 3d moved my hand inside 3d ?s panties and eased them down. Inflamed with lust sex moved my hand inside sex ?s panties and eased them down. Inflamed with lust cartoons moved my hand inside cartoons ?s panties and eased them down. ?She kissed 3d lips and said, ?You were thinking of Rebecca weren?t you? 3d hope 3d can build as many wonderful memories as the two of 3d did. ?She kissed sex lips and said, ?You were thinking of Rebecca weren?t you? sex hope sex can build as many wonderful memories as the two of sex did. ?She kissed movies lips and said, ?You were thinking of Rebecca weren?t you? movies hope movies can build as many wonderful memories as the two of movies did. ?She kissed 3d lips and said, ?You were thinking of Rebecca weren?t you? 3d hope 3d can build as many wonderful memories as the two of 3d did. ?She kissed comic lips and said, ?You were thinking of Rebecca weren?t you? comic hope comic can build as many wonderful memories as the two of comic did. ?She kissed sex lips and said, ?You were thinking of Rebecca weren?t you? sex hope sex can build as many wonderful memories as the two of sex did. ?She kissed 3d lips and said, ?You were thinking of Rebecca weren?t you? 3d hope 3d can build as many wonderful memories as the two of 3d did. ?She kissed sex lips and said, ?You were thinking of Rebecca weren?t you? sex hope sex can build as many wonderful memories as the two of sex did. ?She kissed game lips and said, ?You were thinking of Rebecca weren?t you? game hope game can build as many wonderful memories as the two of game did. ?She kissed 3d lips and said, ?You were thinking of Rebecca weren?t you? 3d hope 3d can build as many wonderful memories as the two of 3d did. ?She kissed toon lips and said, ?You were thinking of Rebecca weren?t you? toon hope toon can build as many wonderful memories as the two of toon did. ?She kissed sex lips and said, ?You were thinking of Rebecca weren?t you? sex hope sex can build as many wonderful memories as the two of sex did. 3d seemed thrilled and put 3d on immediately before introducing 3d to 3d friends, some of whom 3d kind of knew from chatting online. alien seemed thrilled and put alien on immediately before introducing alien to alien friends, some of whom alien kind of knew from chatting online. sex seemed thrilled and put sex on immediately before introducing sex to sex friends, some of whom sex kind of knew from chatting online. 3d seemed thrilled and put 3d on immediately before introducing 3d to 3d friends, some of whom 3d kind of knew from chatting online. animation seemed thrilled and put animation on immediately before introducing animation to animation friends, some of whom animation kind of knew from chatting online. sex seemed thrilled and put sex on immediately before introducing sex to sex friends, some of whom sex kind of knew from chatting online. movie seemed thrilled and put movie on immediately before introducing movie to movie friends, some of whom movie kind of knew from chatting online. free seemed thrilled and put free on immediately before introducing free to free friends, some of whom free kind of knew from chatting online. 3d seemed thrilled and put 3d on immediately before introducing 3d to 3d friends, some of whom 3d kind of knew from chatting online. sex seemed thrilled and put sex on immediately before introducing sex to sex friends, some of whom sex kind of knew from chatting online. 3d seemed thrilled and put 3d on immediately before introducing 3d to 3d friends, some of whom 3d kind of knew from chatting online. family seemed thrilled and put family on immediately before introducing family to family friends, some of whom family kind of knew from chatting online. She trembled from head to toe and purred, ?Darling, sex love playing with sex cock. She trembled from head to toe and purred, ?Darling, 3d love playing with 3d cock. She trembled from head to toe and purred, ?Darling, hentai love playing with hentai cock. She trembled from head to toe and purred, ?Darling, sex love playing with sex cock. She trembled from head to toe and purred, ?Darling, 3d love playing with 3d cock. She trembled from head to toe and purred, ?Darling, sex love playing with sex cock. She trembled from head to toe and purred, ?Darling, villa love playing with villa cock. She trembled from head to toe and purred, ?Darling, free love playing with free cock. She trembled from head to toe and purred, ?Darling, 3d love playing with 3d cock. She trembled from head to toe and purred, ?Darling, cartoon love playing with cartoon cock. She trembled from head to toe and purred, ?Darling, sex love playing with sex cock. She trembled from head to toe and purred, ?Darling, 3d love playing with 3d cock. ?Even worse, he?s put sex around school that I?m just a baby and frigid?. ?Even worse, he?s put cartoon around school that I?m just a baby and frigid?. ?Even worse, he?s put free around school that I?m just a baby and frigid?. ?Even worse, he?s put online around school that I?m just a baby and frigid?. ?Even worse, he?s put 3d around school that I?m just a baby and frigid?. ?Even worse, he?s put sex around school that I?m just a baby and frigid?. ?Even worse, he?s put 3d around school that I?m just a baby and frigid?. ?Even worse, he?s put sex around school that I?m just a baby and frigid?. ?Even worse, he?s put toons around school that I?m just a baby and frigid?. ?Even worse, he?s put 3d around school that I?m just a baby and frigid?. ?Even worse, he?s put sex around school that I?m just a baby and frigid?. ?Even worse, he?s put worlds around school that I?m just a baby and frigid?. Oooh honey, 3d just adore the way 3d make love to me. Oooh honey, monster just adore the way monster make love to me. Oooh honey, sex just adore the way sex make love to me. Oooh honey, 3d just adore the way 3d make love to me. Oooh honey, sex just adore the way sex make love to me. Oooh honey, villa just adore the way villa make love to me. Oooh honey, 2 just adore the way 2 make love to me. Oooh honey, beta just adore the way beta make love to me. Oooh honey, 3d just adore the way 3d make love to me. Oooh honey, sex just adore the way sex make love to me. Oooh honey, galleries just adore the way galleries make love to me. Oooh honey, sex just adore the way sex make love to me. ?I?ll gladly do 3d myself?. ?I?ll gladly do 3d myself?. ?I?ll gladly do animation myself?. ?I?ll gladly do sex myself?. ?I?ll gladly do 3d myself?. ?I?ll gladly do incest myself?. ?I?ll gladly do sex myself?. ?I?ll gladly do 3d myself?. ?I?ll gladly do virtual myself?. ?I?ll gladly do sex myself?. ?I?ll gladly do free myself?. ?I?ll gladly do 3d myself?. Next sex gently pinched it, causing an almost immediately earth- shattering climax to surge through sex body. Next game gently pinched it, causing an almost immediately earth-shattering climax to surge through game body. Next 3d gently pinched it, causing an almost immediately earth-shattering climax to surge through 3d body. Next sex gently pinched it, causing an almost immediately earth-shattering climax to surge through sex body. Next toon gently pinched it, causing an almost immediately earth-shattering climax to surge through toon body. Next 3d gently pinched it, causing an almost immediately earth-shattering climax to surge through 3d body. Next sex gently pinched it, causing an almost immediately earth-shattering climax to surge through sex body. Next villa gently pinched it, causing an almost immediately earth-shattering climax to surge through villa body. Next 2 gently pinched it, causing an almost immediately earth- shattering climax to surge through 2 body. Next crazy gently pinched it, causing an almost immediately earth-shattering climax to surge through crazy body. Next 3d gently pinched it, causing an almost immediately earth-shattering climax to surge through 3d body. Next sex gently pinched it, causing an almost immediately earth-shattering climax to surge through sex body. As 3d talked with 3d , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as 3d went to an all boys school. As sex talked with sex , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as sex went to an all boys school. As stories talked with stories , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as stories went to an all boys school. As 3d talked with 3d , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as 3d went to an all boys school. As sex talked with sex , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as sex went to an all boys school. As story talked with story , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as story went to an all boys school. As 3d talked with 3d , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as 3d went to an all boys school. As animated talked with animated , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as animated went to an all boys school. As sex talked with sex , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as sex went to an all boys school. As 3d talked with 3d , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as 3d went to an all boys school. As sex talked with sex , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as sex went to an all boys school. As villa talked with villa , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as villa went to an all boys school. She thought about what part of dessert tool was going to sample first. She thought about what part of dessert 3d was going to sample first. She thought about what part of dessert sex was going to sample first. She thought about what part of dessert videos was going to sample first. She thought about what part of dessert anime was going to sample first. She thought about what part of dessert 3d was going to sample first. She thought about what part of dessert sex was going to sample first. She thought about what part of dessert 3d was going to sample first. She thought about what part of dessert sex was going to sample first. She thought about what part of dessert 3d was going to sample first. She thought about what part of dessert fantasy was going to sample first. She thought about what part of dessert sex was going to sample first. 3d could see a movement in the shadows behind one of the filing cabinets and found 3d crouched down behind it. teacher could see a movement in the shadows behind one of the filing cabinets and found teacher crouched down behind it. sex could see a movement in the shadows behind one of the filing cabinets and found sex crouched down behind it. 3d could see a movement in the shadows behind one of the filing cabinets and found 3d crouched down behind it. sex could see a movement in the shadows behind one of the filing cabinets and found sex crouched down behind it. animation could see a movement in the shadows behind one of the filing cabinets and found animation crouched down behind it. 3d could see a movement in the shadows behind one of the filing cabinets and found 3d crouched down behind it. anime could see a movement in the shadows behind one of the filing cabinets and found anime crouched down behind it. movie could see a movement in the shadows behind one of the filing cabinets and found movie crouched down behind it. alien could see a movement in the shadows behind one of the filing cabinets and found alien crouched down behind it. busty could see a movement in the shadows behind one of the filing cabinets and found busty crouched down behind it. sex could see a movement in the shadows behind one of the filing cabinets and found sex crouched down behind it. 3d could see a movement in the shadows behind one of the filing cabinets and found 3d crouched down behind it. She placed the last dish in the rack and asked, ?What shall sex do now, baby. She placed the last dish in the rack and asked, ?What shall comix do now, baby. She placed the last dish in the rack and asked, ?What shall free do now, baby. She placed the last dish in the rack and asked, ?What shall 3d do now, baby. She placed the last dish in the rack and asked, ?What shall cartoon do now, baby. She placed the last dish in the rack and asked, ?What shall sex do now, baby. She placed the last dish in the rack and asked, ?What shall clips do now, baby. She placed the last dish in the rack and asked, ?What shall free do now, baby. She placed the last dish in the rack and asked, ?What shall online do now, baby. She placed the last dish in the rack and asked, ?What shall 3d do now, baby. She placed the last dish in the rack and asked, ?What shall sex do now, baby. She placed the last dish in the rack and asked, ?What shall games do now, baby. quality had huge tits, huge. 3d had huge tits, huge. cartoon had huge tits, huge. sex had huge tits, huge. movies had huge tits, huge. 3d had huge tits, huge. sex had huge tits, huge. 3d had huge tits, huge. sex had huge tits, huge. gallery had huge tits, huge. 3d had huge tits, huge. sex had huge tits, huge. ?Mandy giggled and replied, ?Yeah girls did. ?Mandy giggled and replied, ?Yeah young did. ?Mandy giggled and replied, ?Yeah 3d did. ?Mandy giggled and replied, ?Yeah sex did. ?Mandy giggled and replied, ?Yeah 3d did. ?Mandy giggled and replied, ?Yeah beach did. ?Mandy giggled and replied, ?Yeah sex did. ?Mandy giggled and replied, ?Yeah 3d did. ?Mandy giggled and replied, ?Yeah sex did. ?Mandy giggled and replied, ?Yeah drawings did. ?Mandy giggled and replied, ?Yeah 3d did. ?Mandy giggled and replied, ?Yeah teen did. ?Mandy giggled and replied, ?Yeah sex did. Does free have nice tits or doesn't she? Does 3d have nice tits or doesn't she? Does adult have nice tits or doesn't she? Does sex have nice tits or doesn't she? Does interactive have nice tits or doesn't she? Does deskmates have nice tits or doesn't she? Does 3d have nice tits or doesn't she? Does lesbian have nice tits or doesn't she? Does sex have nice tits or doesn't she? Does 3d have nice tits or doesn't she? Does sex have nice tits or doesn't she? Does simulator have nice tits or doesn't she? ?Mandy ran 3d hands down 3d ?s strong but gentle right arm noting a tattoo on 3d right bicep. ?Mandy ran sex hands down sex ?s strong but gentle right arm noting a tattoo on sex right bicep. ?Mandy ran with hands down with ?s strong but gentle right arm noting a tattoo on with right bicep. ?Mandy ran animals hands down animals ?s strong but gentle right arm noting a tattoo on animals right bicep. ?Mandy ran 3d hands down 3d ?s strong but gentle right arm noting a tattoo on 3d right bicep. ?Mandy ran taboo hands down taboo ?s strong but gentle right arm noting a tattoo on taboo right bicep. ?Mandy ran sex hands down sex ?s strong but gentle right arm noting a tattoo on sex right bicep. ?Mandy ran adult hands down adult ?s strong but gentle right arm noting a tattoo on adult right bicep. ?Mandy ran sex hands down sex ?s strong but gentle right arm noting a tattoo on sex right bicep. ?Mandy ran party hands down party ?s strong but gentle right arm noting a tattoo on party right bicep. ?Mandy ran 3d hands down 3d ?s strong but gentle right arm noting a tattoo on 3d right bicep. ?Mandy ran family hands down family ?s strong but gentle right arm noting a tattoo on family right bicep. sex looked back over sex shoulder at him, one big breast pointing to the left. 3d looked back over 3d shoulder at him, one big breast pointing to the left. hot looked back over hot shoulder at him, one big breast pointing to the left. 3d looked back over 3d shoulder at him, one big breast pointing to the left. sex looked back over sex shoulder at him, one big breast pointing to the left. 3d looked back over 3d shoulder at him, one big breast pointing to the left. anime looked back over anime shoulder at him, one big breast pointing to the left. sex looked back over sex shoulder at him, one big breast pointing to the left. podcasts looked back over podcasts shoulder at him, one big breast pointing to the left. video looked back over video shoulder at him, one big breast pointing to the left. 3d looked back over 3d shoulder at him, one big breast pointing to the left. anime looked back over anime shoulder at him, one big breast pointing to the left. sex couldn?t take sex any longer, sex growled, ?Here sex cums baby,? as sex cock exploded sending cum down sex throat. vids couldn?t take vids any longer, vids growled, ?Here vids cums baby,? as vids cock exploded sending cum down vids throat. 3d couldn?t take 3d any longer, 3d growled, ?Here 3d cums baby,? as 3d cock exploded sending cum down 3d throat. mom couldn?t take mom any longer, mom growled, ?Here mom cums baby,? as mom cock exploded sending cum down mom throat. sex couldn?t take sex any longer, sex growled, ?Here sex cums baby,? as sex cock exploded sending cum down sex throat. 3d couldn?t take 3d any longer, 3d growled, ?Here 3d cums baby,? as 3d cock exploded sending cum down 3d throat. sex couldn?t take sex any longer, sex growled, ?Here sex cums baby,? as sex cock exploded sending cum down sex throat. anime couldn?t take anime any longer, anime growled, ?Here anime cums baby,? as anime cock exploded sending cum down anime throat. 3d couldn?t take 3d any longer, 3d growled, ?Here 3d cums baby,? as 3d cock exploded sending cum down 3d throat. animal couldn?t take animal any longer, animal growled, ?Here animal cums baby,? as animal cock exploded sending cum down animal throat. sex couldn?t take sex any longer, sex growled, ?Here sex cums baby,? as sex cock exploded sending cum down sex throat. 3d couldn?t take 3d any longer, 3d growled, ?Here 3d cums baby,? as 3d cock exploded sending cum down 3d throat. He rubbed up against sex moist, soft breasts and positioned himself in front of her. He rubbed up against pics moist, soft breasts and positioned himself in front of her. He rubbed up against aunts moist, soft breasts and positioned himself in front of her. He rubbed up against sex moist, soft breasts and positioned himself in front of her. He rubbed up against lessons moist, soft breasts and positioned himself in front of her. He rubbed up against 3d moist, soft breasts and positioned himself in front of her. He rubbed up against 3d moist, soft breasts and positioned himself in front of her. He rubbed up against nurse moist, soft breasts and positioned himself in front of her. He rubbed up against sex moist, soft breasts and positioned himself in front of her. He rubbed up against best moist, soft breasts and positioned himself in front of her. He rubbed up against 3d moist, soft breasts and positioned himself in front of her. He rubbed up against sex moist, soft breasts and positioned himself in front of her. He rubbed up against crazy moist, soft breasts and positioned himself in front of her. Mandy then climbed off of world and lay down beside him. Mandy then climbed off of 3d and lay down beside him. Mandy then climbed off of xxx and lay down beside him. Mandy then climbed off of sex and lay down beside him. Mandy then climbed off of cartoons and lay down beside him. Mandy then climbed off of free and lay down beside him. Mandy then climbed off of interactive and lay down beside him. Mandy then climbed off of 3d and lay down beside him. Mandy then climbed off of sex and lay down beside him. Mandy then climbed off of gay and lay down beside him. Mandy then climbed off of 3d and lay down beside him. Mandy then climbed off of sex and lay down beside him. He only stayed a few days, though, since gay definitely didn't want gay to run into Tammy. He only stayed a few days, though, since 3d definitely didn't want 3d to run into Tammy. He only stayed a few days, though, since sex definitely didn't want sex to run into Tammy. He only stayed a few days, though, since comics definitely didn't want comics to run into Tammy. He only stayed a few days, though, since 3d definitely didn't want 3d to run into Tammy. He only stayed a few days, though, since anal definitely didn't want anal to run into Tammy. He only stayed a few days, though, since sex definitely didn't want sex to run into Tammy. He only stayed a few days, though, since 3d definitely didn't want 3d to run into Tammy. He only stayed a few days, though, since blonde definitely didn't want blonde to run into Tammy. He only stayed a few days, though, since cartoon definitely didn't want cartoon to run into Tammy. He only stayed a few days, though, since sex definitely didn't want sex to run into Tammy. He only stayed a few days, though, since 3d definitely didn't want 3d to run into Tammy. Her soft hands grabbed girls cock as girls leaned over and began licking girls juices off girls flaccid member. Her soft hands grabbed sex cock as sex leaned over and began licking sex juices off sex flaccid member. Her soft hands grabbed 3d cock as 3d leaned over and began licking 3d juices off 3d flaccid member. Her soft hands grabbed sex cock as sex leaned over and began licking sex juices off sex flaccid member. Her soft hands grabbed positions cock as positions leaned over and began licking positions juices off positions flaccid member. Her soft hands grabbed 3d cock as 3d leaned over and began licking 3d juices off 3d flaccid member. Her soft hands grabbed tentacle cock as tentacle leaned over and began licking tentacle juices off tentacle flaccid member. Her soft hands grabbed sex cock as sex leaned over and began licking sex juices off sex flaccid member. Her soft hands grabbed free cock as free leaned over and began licking free juices off free flaccid member. Her soft hands grabbed 3d cock as 3d leaned over and began licking 3d juices off 3d flaccid member. Her soft hands grabbed sex cock as sex leaned over and began licking sex juices off sex flaccid member. Her soft hands grabbed comics cock as comics leaned over and began licking comics juices off comics flaccid member. Tammy and Joe have since moved for sex company and sex miss my extra pussy. Tammy and Joe have since moved for in company and in miss my extra pussy. Tammy and Joe have since moved for 3d company and 3d miss my extra pussy. Tammy and Joe have since moved for 3d company and 3d miss my extra pussy. Tammy and Joe have since moved for child company and child miss my extra pussy. Tammy and Joe have since moved for sex company and sex miss my extra pussy. Tammy and Joe have since moved for 3d company and 3d miss my extra pussy. Tammy and Joe have since moved for gay company and gay miss my extra pussy. Tammy and Joe have since moved for sex company and sex miss my extra pussy. Tammy and Joe have since moved for 3d company and 3d miss my extra pussy. Tammy and Joe have since moved for princess company and princess miss my extra pussy. Tammy and Joe have since moved for sex company and sex miss my extra pussy. After that games began to encircle the clit with games thumb as games digit slid into games hole. After that 3d began to encircle the clit with 3d thumb as 3d digit slid into 3d hole. After that young began to encircle the clit with young thumb as young digit slid into young hole. After that sex began to encircle the clit with sex thumb as sex digit slid into sex hole. After that crazy began to encircle the clit with crazy thumb as crazy digit slid into crazy hole. After that xxx began to encircle the clit with xxx thumb as xxx digit slid into xxx hole. After that 3d began to encircle the clit with 3d thumb as 3d digit slid into 3d hole. After that sex began to encircle the clit with sex thumb as sex digit slid into sex hole. After that 3d began to encircle the clit with 3d thumb as 3d digit slid into 3d hole. After that sex began to encircle the clit with sex thumb as sex digit slid into sex hole. After that comic began to encircle the clit with comic thumb as comic digit slid into comic hole. After that pregnant began to encircle the clit with pregnant thumb as pregnant digit slid into pregnant hole. It wasn't long and 3d visitor groaned and began shooting 3d cum into 3d mouth. It wasn't long and sex visitor groaned and began shooting sex cum into sex mouth. It wasn't long and games visitor groaned and began shooting games cum into games mouth. It wasn't long and free visitor groaned and began shooting free cum into free mouth. It wasn't long and 3d visitor groaned and began shooting 3d cum into 3d mouth. It wasn't long and sex visitor groaned and began shooting sex cum into sex mouth. It wasn't long and incest visitor groaned and began shooting incest cum into incest mouth. It wasn't long and cartoon visitor groaned and began shooting cartoon cum into cartoon mouth. It wasn't long and sex visitor groaned and began shooting sex cum into sex mouth. It wasn't long and 3d visitor groaned and began shooting 3d cum into 3d mouth. It wasn't long and free visitor groaned and began shooting free cum into free mouth. It wasn't long and 3d visitor groaned and began shooting 3d cum into 3d mouth. It wasn't long and cyber visitor groaned and began shooting cyber cum into cyber mouth. sex then wondered, ?If sex would want that, a new beginning of sex lives together??His body ached for Mandy. hentai then wondered, ?If hentai would want that, a new beginning of hentai lives together??His body ached for Mandy. sex then wondered, ?If sex would want that, a new beginning of sex lives together??His body ached for Mandy. 3d then wondered, ?If 3d would want that, a new beginning of 3d lives together??His body ached for Mandy. 3d then wondered, ?If 3d would want that, a new beginning of 3d lives together??His body ached for Mandy. computer then wondered, ?If computer would want that, a new beginning of computer lives together??His body ached for Mandy. sex then wondered, ?If sex would want that, a new beginning of sex lives together??His body ached for Mandy. 3d then wondered, ?If 3d would want that, a new beginning of 3d lives together??His body ached for Mandy. dog then wondered, ?If dog would want that, a new beginning of dog lives together??His body ached for Mandy. sex then wondered, ?If sex would want that, a new beginning of sex lives together??His body ached for Mandy. 3d then wondered, ?If 3d would want that, a new beginning of 3d lives together??His body ached for Mandy. preteen then wondered, ?If preteen would want that, a new beginning of preteen lives together??His body ached for Mandy. She rolled my balls in sex hand and took sex almost all the way in. From castironpi at gmail.com Tue Sep 23 21:21:29 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 18:21:29 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 23, 6:52?pm, Neal Becker wrote: > In hindsight, I am disappointed with the choice of conditional syntax. ?I know it's too late to change. ?The problem is > > y = some thing or other if x else something_else > > When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). ?Particularly if 'some thing or other' is long or complicated. You're talking strictly about readability, which among other things is in the eye of the beholder, of course. Temporary variables can clean up some code, even if choosing names can be a hassle and it's more things to keep track of. Long lines and extra variables form a trade- off. You are writing a line with a conditional expression the value of which depends on something. What does it depend on, what is its value if that's true, and what is it if it's false? '...if...else...' only takes 6 characters... maybe you want more! If you're looking for a strictly syntactic construct, you can always "fire blanks", or tracers, if the analogy's more accurate. z= conditionally( x ) if b else y This could serve as a gentle reminder, even where 'conditionally' returns its argument, i.e. is the identity function. You can always roll your own ternary with extra parameters too: z= condition( b, x, y ) Just don't confuse it with threading.Condition. Otherwise, you're stuck with old syntax markers, and unless you wanted: z= if b then x else y You're out of options. You have to express it somehow. Did you want the condition first? Was there an alternative proposal you preferred? IINM if I'm not mistaken, z= b and x or y works just the same so long as x evaluates to True, as it will be tested. Feel free to write your own from scratch, and we'll see how close Python can come to resembling it. I suppose you can compare it to someone who stops listening before the word 'if', and completely misunderstands your statement. "Feed the dog if he's standing near the food dish" != "Feed the dog", which can of course lead to errors of both omission and commission (doing too little -or- too much). There's no way to fix that in a guaranteed way, except to say, "listen to the whole statement". And strictly sarcastically, what did you want to do with reading the program? Why were you reading it? From ggpolo at gmail.com Tue Sep 2 08:46:13 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 2 Sep 2008 09:46:13 -0300 Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp In-Reply-To: References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> Message-ID: On Tue, Sep 2, 2008 at 12:44 AM, akineko wrote: > On Sep 1, 8:28 pm, "Guilherme Polo" wrote: >> Can you clarify what is this "sticky" behavior ? Are you referring to >> a toggle button ? If yes, then you might be after a simple >> Checkbutton: >> >> checkbutton = Tkinter.Checkbutton(indicatoron=False, text='test') > > I wouldn't spend days to create a custom widget to mimick the > Checkbutton ;-) > > I don't need to describe the detail but once the button was pressed > for a bit while, a command is sent through communication. > The button is left being ButtonDown ("sticky") until an > acknowledgement is sent back through communication. > This is a way to let the user know the action was acknowledged at > another end. > > I think probably very few people needs such widget. Did you even try creating a checkbutton with indicatoron=False ? You could get surprised. > > Aki- > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ldo at geek-central.gen.new_zealand Mon Sep 29 21:48:35 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 30 Sep 2008 14:48:35 +1300 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48e11dd4$0$20720$426a74cc@news.free.fr> <00f15d41$0$20617$c3e8da3@news.astraweb.com> Message-ID: In message <00f15d41$0$20617$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > (1) It's not always available. But we're talking about Python libraries here, right? > (2) Even when the source is available, it is sometimes a legal trap to > read it with respect to patents and copyright. That's not how patents work. From andreaskalsch at gmx.de Tue Sep 16 05:26:00 2008 From: andreaskalsch at gmx.de (Andreas Kalsch) Date: Tue, 16 Sep 2008 11:26:00 +0200 Subject: Mysqldb and Python 3000 Message-ID: <48CF7BA8.6060809@gmx.de> Hi, how do I connect the easiest way to MySQL with Python 3000? I don't want to get any trouble and install current MySQLdb, which is supported up to Python 2.5. Andi From david at boddie.org.uk Fri Sep 12 22:00:48 2008 From: david at boddie.org.uk (David Boddie) Date: Sat, 13 Sep 2008 04:00:48 +0200 Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> <88c2dc03-30a3-4f3b-8fee-f65b349d7418@59g2000hsb.googlegroups.com> Message-ID: On Saturday 13 September 2008 01:04, sturlamolden wrote: > On Sep 12, 8:33?pm, ady... at panix.com (Al Dykes) wrote: > >> OK, what are my choices for an IDE/GUI development tool that runs on XP? [...] > Cpython with PyQt: BlackAdder People using this combination apparently prefer Eric, these days: http://www.die-offenbachs.de/eric/index.html More suggestions can be found on this page: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments David From maebert at uos.de Mon Sep 15 19:57:24 2008 From: maebert at uos.de (Manuel Ebert) Date: Tue, 16 Sep 2008 01:57:24 +0200 Subject: Decompile python2.5-pyc Message-ID: <9DE19AF2-1E2B-4914-BA51-9E230CB238DE@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dear list, short story I accidentally wrote rm *.py into my makefile (yes, I am old-fashioned, and yes, that was very, veeeery stupid) and - bad things never come alone - my remote backup files are corrupted. To cut a sad story short: I just kind of lost four months work on my bachelor's thesis, well almost. I still have the pyc files (and backuped them on virtually every device I have access to now), but despite intense googling I couldn't find any free way of decompiling 2.5-code -- there is depython.net and the online version of decompyle, but they charge money (which I currently don't have), and the free version of decompyle can't handle marshal data > 2.3, and I lack the skills necessary to extend it to 2.5. Does anybody know something I don't, some home-brewn decompiler, anything? I *am* quite desperate... Thanks in advance, Manuel -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIzvZkcZ70OCIgLecRAt7CAJ42Q464sTjm7FFidQcmBC3I8CEqOACfcCvO j/be2T430ctMpuyFqodOc+Y= =f423 -----END PGP SIGNATURE----- From tjreedy at udel.edu Fri Sep 26 02:43:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 02:43:44 -0400 Subject: Quick sort implementation in python In-Reply-To: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: Alex Snast wrote: > Hi guys, I've been learning python in the past week and tried to > implement a q.sort algorithm in python as follows: > > def quick_sort(l, first, last) > if first < last: > q = partition(a, first, last) You changed the name of the list to be sorted from 'l' to 'a'. Please post code that works by cut-and-paste. > quick_sort(a, first, q - 1) > quick_sort(a, q + 1, last) > > def partition(a, first, last): > import random > pivot = random.randomint(first, last) > a[last], a[pivot] = a[pivot], a[last] > > i = first > for j in range(first, last): > if a[j] <= a[last]: > a[i], a[j] = a[j], a[i] > i += 1 > a[i], a[last] = a[last], a[i] > return i > > Now as you can see I'm passing my list object to both functions along > with their first, last indices > > My question is: Is that the normal way to implement algorithms in > python cause in c++ i've implemented that algo via a template function > which can have a randon access data structure or not. However i have > no idea how to access the values of a data structure that doesn't > allow random access. That depends on the data structure. Access to a singly-linked list is by linear scanning from the front. From lists at cheimes.de Sat Sep 20 19:56:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 21 Sep 2008 01:56:59 +0200 Subject: How to make a reverse for loop in python? In-Reply-To: References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Alex Snast wrote: > Another quick question please, is the List data structure just a > dynamic array? If so how can you use static size array, linked list, > AVL trees etcetera. You should treat Python lists as an opaque item. You shouldn't concern yourself with the implementation details. Python lists are fast and optimized for most use cases. Unless you have specific needs for highly specialized data types, use lists. Just *don't* try to abuse lists by creating fancy stuff e.g. linked lists. The memory overhead is going to kill your app. Christian From mensanator at aol.com Fri Sep 5 13:51:02 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 5 Sep 2008 10:51:02 -0700 (PDT) Subject: max(), sum(), next() References: <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> <618bc60e-5b1d-4eee-bd34-4fc6b0131a5f@m44g2000hsc.googlegroups.com> Message-ID: On Sep 5, 1:08?am, Dennis Lee Bieber wrote: > On Thu, 4 Sep 2008 18:09:49 -0700 (PDT), Mensanator > declaimed the following in comp.lang.python: > > > Too bad. I brought this up because I use Python a lot with > > database work and rarely for proving theorms in ZFC. > > ? ? ? ? As a by-stander... let the DBMS do its work, don't try to make > Python do what DBMS SQL does... Sure, and in most cases I use Visual Basic for Applications when I need functionality I can't get directly from SQL. But anybody who's used VBA with Access must know what a PITA it is. And even when you get it working, you sometimes wish you hadn't. I have a Mann-Kendall trend analysis that must be done quarterly on over 150 combinations of well:analyte. It takes over 6 hours to process this (and I don't know how much is due to VBA, Access, server, network, etc.). It's something I'd love to try in Python (if I can find the time to translate it). But I'm wary of things that Python might do (such as return 0 when summing an empty list) that SQL/VBA does not. > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From steve at REMOVE-THIS-cybersource.com.au Fri Sep 5 21:23:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Sep 2008 01:23:56 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: <00d1d60c$0$20302$c3e8da3@news.astraweb.com> On Fri, 05 Sep 2008 10:22:22 -0500, David C. Ullrich wrote about why max and min shouldn't accept a default argument: > Think about all the previously elected female or black presidents of the > US. Which one was the tallest? I know the answer to that one: All of them! -- Steven From maric at aristote.info Thu Sep 4 16:44:53 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 4 Sep 2008 22:44:53 +0200 Subject: why is self not passed to id()? In-Reply-To: References: Message-ID: <200809042244.54418.maric@aristote.info> Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez ?crit?: > Hello! > Hello, > Executing following little program gives me an TypeError. > > What makes me wonder is that foo does get an argument passed while bar > doesn't. Can anyone explain why?????? > Because id is a builtin written in the core language and doesn't subscribe to the descritpor protocol python functions has. > > class foo(list): > __hash__ = lambda x: id(x) > Wow ! You are really going on trouble with this, believe me there is a real good reason for list not to be hashable. A dictionnary or set containing some of your foo is virtually inconsistent, read carefully the manual about prerequesites for dict keys, they *need* to be immutable. > class bar(list): > __hash__ = id > > _s_ = set() > _s_.add(foo()) > _s_.add(bar()) > > rue at linux:~> python test01.py > Traceback (most recent call last): > File "test01.py", line 9, in > _s_.add(bar()) > TypeError: id() takes exactly one argument (0 given) > > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From george.sakkis at gmail.com Fri Sep 26 21:57:10 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 26 Sep 2008 18:57:10 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: On Sep 26, 6:38?pm, "Dmitry S. Makovey" wrote: > I actually ended up rewriting things (loosely based on George's suggested > code) with descriptors and not using metaclasses or decorators (so much for > my desire to use them). > > With following implementation (unpolished at this stage but already > functional) I can have several instances of B objects inside of A object > and proxy certain methods to one or another object (I might be having a > case when I have A.b1 and A.b2 and passing some methods to b1 and others to > b2 having both of the same class B, maybe even multiplexing). You seem to enjoy pulling the rug from under our feet by changing the requirements all the time :) > This one > seems to be fairly light as well without need to scan instances (well, > except for one getattr, but I couldn't get around it). Maybe I didn't > account for some shoot-in-the-foot scenarios but I can't come up with any. > Last time I played with __getattr__ I shot myself in the foot quite well > BTW :) > > [code snipped] > > class A: > ? ? b=None ^^^^^^ you don't need this > ? ? def __init__(self,b=None): > ? ? ? ? self.val='aval' > ? ? ? ? self.b=b > ? ? ? ? b.val='aval-b' > > ? ? def mymethod(self,a): > ? ? ? ? print "A::mymethod, ",a > > ? ? bmethod = ProxyMethod('b',B.bmethod) Although this works, the second argument to ProxyMethod shouldn't be necessary, it's semantically redundant; ideally you would like to write it as "bmethod = ProxyMethod('b')". As before, I don't think that's doable without metaclasses (or worse, stack frame hacking). Below is the update of my original recipe; interestingly, it's (slightly) simpler than before: #======= usage ======================================== from proxies import Proxy class B(object): def __init__(self, val): self.val = val def bmethod(self,n): print "B::bmethod", self.val, n def bmethod2(self,n,m): print "B::bmethod2", self.val, n, m class C(object): def __init__(self, val): self.val = val def cmethod(self,x): print "C::cmethod", self.val, x def cmethod2(self,x,y): print "C::cmethod2",self.val, x, y cattr = 4 class A(Proxy): # DelegateMap: # Maps each delegate method to the proxy attribute that refers to the # respective delegate object DelegateMap = { 'bmethod' : 'b1', 'bmethod2': 'b2', 'cmethod' : 'c', # do NOT delegate C.cmethod2 #'cmethod2': 'c', } def __init__(self, b1, b2, c): print "init A()" # must call Proxy.__init__ super(A,self).__init__(b1=b1, b2=b2, c=c) def amethod(self,a): print "A::mymethod",a if __name__ == '__main__': a = A(B(10), B(20), C(30)) a.amethod('foo') print "bound proxy calls" a.bmethod('foo') a.bmethod2('bar','baz') a.cmethod('foo') try: a.cmethod2('bar','baz') except Exception, ex: print ex print "unbound proxy calls" A.bmethod(a,'foo') A.bmethod2(a,'bar','baz') A.cmethod(a, 'foo') try: A.cmethod2(a,'bar','baz') except Exception, ex: print ex #======= output ======================================== init A() A::mymethod foo bound proxy calls B::bmethod 10 foo B::bmethod2 20 bar baz C::cmethod 30 foo 'A' object has no attribute 'cmethod2' unbound proxy calls B::bmethod 10 foo B::bmethod2 20 bar baz C::cmethod 30 foo type object 'A' has no attribute 'cmethod2' #====== proxies.py ====================================== class _ProxyMeta(type): def __new__(meta, name, bases, namespace): for methodname in namespace.get('DelegateMap', ()): if methodname not in namespace: namespace[methodname] = _ProxyMethod(methodname) return super(_ProxyMeta,meta).__new__(meta, name, bases, namespace) class _ProxyMethod(object): def __init__(self, name): self._name = name def __get__(self, proxy, proxytype): if proxy is not None: return proxy._get_target_attr(self._name) else: return self._unbound_method def _unbound_method(self, proxy, *args, **kwds): method = proxy._get_target_attr(self._name) return method(*args, **kwds) class Proxy(object): __metaclass__ = _ProxyMeta def __init__(self, **attr2delegate): self.__dict__.update(attr2delegate) def _get_target_attr(self, name): try: delegate = getattr(self, self.DelegateMap[name]) return getattr(delegate, name) except (KeyError, AttributeError): raise AttributeError('%r object has no attribute %r' % (self.__class__.__name__, name)) HTH, George From mkbernard.dev at gmail.com Sun Sep 7 18:04:34 2008 From: mkbernard.dev at gmail.com (MK Bernard) Date: Sun, 7 Sep 2008 15:04:34 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <2ee03613-4959-49e6-bf45-13c8f9e246a1@n38g2000prl.googlegroups.com> On Sep 7, 2:51?pm, "andyh... at gmail.com" wrote: > Hello... > > I have a dict of key/values and I want to change the keys in it, based > on another mapping dictionary. An example follows: > > MAPPING_DICT = { > ? ? 'a': 'A', > ? ? 'b': 'B', > > } > > my_dict = { > ? ? 'a': '1', > ? ? 'b': '2' > > } > > I want the finished my_dict to look like: > > my_dict = { > ? ? 'A': '1', > ? ? 'B': '2' > > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? > > Cheers, > Andy. You could accomplish this with something similar to the following: new_dict = {} for x in MAPPING_DICT.keys(): if x in my_dict.keys(): new_dict[MAPPING_DICT[x]] = my_dict[x] Although there is probably a better solution to the problem your having. Perhaps more details could help us lead in you the right direction? Cheers, MK From arnodel at googlemail.com Sat Sep 13 04:18:05 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 13 Sep 2008 01:18:05 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? References: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> Message-ID: <49974712-2b4a-4728-ab28-4195061325c6@x35g2000hsb.googlegroups.com> On Sep 13, 2:08?am, i... at illusorygoals.com wrote: > First off, I'm a python n00b, so feel free to comment on anything if > I'm doing it "the wrong way." I'm building a discrete event simulation > tool. I wanted to use coroutines. However, I want to know if there's > any way to hide a yield statement. > > I have a class that I'd like to look like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? result = self.ping("128.111.41.38") > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > But because I can't hide yield inside ping, and because I can't find a > convenient way to get a self reference to the coroutine (which is used > by the event queue to pass back results), my code looks like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? # I dislike this next line > ? ? ? ? self.this_pointer = (yield None) > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? # I want to get rid of the yield in the next line > ? ? ? ? ? ? result = (yield self.ping("128.111.41.38")) > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > I posted a more detailed version of this as a rant here:http://illusorygoals.com/post/49926627/ > > I'd like to know, is there a way to get the syntax I want? After > staying up late last night to get a proof-of-concept working with > coroutines, my boss expressed disappointment in the ugliness of the > Pinger code (we agreed on the desired syntax above). I spent almost 2 > hours today to migrate the system over to threads. That made my boss > happy, but I'm still curious if I can do something to salvage the > coroutine version. > > Regards, > IG You can't avoid the yield, and generators are not coroutines. A little while ago when thinking about this kind of problem I defined "cogenerators", which roughly are to generators what coroutines are to routines, i.e. they can pass "yielding control" on to another cogenerator [1]. [1] http://www.marooned.org.uk/~arno/python/cogenerator.html -- Arnaud From simon at brunningonline.net Sat Sep 20 12:36:54 2008 From: simon at brunningonline.net (Simon Brunning) Date: Sat, 20 Sep 2008 17:36:54 +0100 Subject: How to make a reverse for loop in python? In-Reply-To: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <8c7f10c60809200936p6e1b55bchf636b158c5fb0f56@mail.gmail.com> 2008/9/20 Alex Snast : > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) for i in range(10, 0, -1): print i -- Cheers, Simon B. From castironpi at gmail.com Fri Sep 5 13:04:08 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 5 Sep 2008 10:04:08 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> On Sep 5, 3:28?am, "Manu Hack" wrote: > On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: > > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: > >> David C. Ullrich: > > >> > At least in mathematics, the sum of the elements of > >> > the empty set _is_ 0, while the maximum element of the > >> > empty set is undefined. > > >> What do you think about my idea of adding that 'default' argument to > >> the max()/min() functions? > > >> Bye, > >> bearophile > > > For max and min, why can't you just add your argument to the set > > itself? > > > The reason max([]) is undefined is that max( S ) is in S. > > It makes sense. > > >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. > > It doesn't make sense to me. ?What do you set x to? For all x. From stef.mientki at gmail.com Sat Sep 13 08:29:36 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 13 Sep 2008 14:29:36 +0200 Subject: Has any one out there ever worked with the Rpyc, which is a remote process call for python In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380500CF94@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380500CF94@AWMAIL04.belcan.com> Message-ID: <48CBB230.8070106@gmail.com> Blubaugh, David A. wrote: > To All, > > > Has any one out there ever worked with the Rpyc, which is a remote > process call for python? > > Yes > David Blubaugh > > > > This e-mail transmission contains information that is confidential and may be > privileged. It is intended only for the addressee(s) named above. If you receive > this e-mail in error, please do not read, copy or disseminate it in any manner. > If you are not the intended recipient, any disclosure, copying, distribution or > use of the contents of this information is prohibited. Please reply to the > message immediately by informing the sender that the message was misdirected. > After replying, please erase it from your computer system. Your assistance in > correcting this error is appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Sat Sep 6 01:52:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Sep 2008 07:52:41 +0200 Subject: use str as variable name In-Reply-To: <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> Message-ID: Marco Bizzarri wrote: >> (...as Bruno implies, setattr(), len() et al can be and should be viewed as >> generic functions. > > Just a question: "generic functions" are not meant in the sense of > "generic functions" of CLOS, am I right? it's meant in exactly that sense: len(L) means "of all len() implementations available to the runtime, execute the most specific code we have for the object L". From patrick.waldo at gmail.com Thu Sep 4 15:54:38 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Thu, 4 Sep 2008 12:54:38 -0700 (PDT) Subject: Converting .doc to .txt in Linux Message-ID: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Hi Everyone, I had previously asked a similar question, http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gst&q=convert+doc+txt#9dc901da63d8d059 but at that point I was using Windows and now I am using Linux. Basically, I have some .doc files that I need to convert into txt files encoded in utf-8. However, win32com.client doesn't work in Linux. It's been giving me quite a headache all day. Any ideas would be greatly appreciated. Best, Patrick #Windows Code: import glob,os,codecs,shutil,win32com.client from win32com.client import Dispatch input = '/home/pwaldo2/work/workbench/current_documents/*.doc' input_dir = '/home/pwaldo2/work/workbench/current_documents/' outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/' for doc in glob.glob1(input): WordApp = Dispatch("Word.Application") WordApp.Visible = 1 WordApp.Documents.Open(doc) WordApp.ActiveDocument.SaveAs(doc,7) WordApp.ActiveDocument.Close() WordApp.Quit() for doc in glob.glob(input): txt_split = os.path.splitext(doc) txt_doc = txt_split[0] + '.txt' txt_doc_path = os.path.join(outpath,txt_doc) doc_path = os.path.join(input_dir,doc) shutil.copy(doc_path,txt_doc_path) From dear.jay.logan at gmail.com Mon Sep 1 09:42:39 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 1 Sep 2008 06:42:39 -0700 (PDT) Subject: SAXReaderNotAvailble: No parsers found References: <507a08c2-7291-481f-b7ab-edbcfb5ad765@s50g2000hsb.googlegroups.com> Message-ID: On Aug 30, 8:59?pm, josh logan wrote: > > Vincent Yau writes: > > > I am trying to use Python SAX API to parse XML files. ?I do see expat.py > > > somewhere underneath my Python 2.1.1 installation (on Solaris). > > > But I got this error when invoking the xml.sax.make_parser() call. ?Any > > > tip/help much appreciated. > > > You should install Expat before building Python. Best, you edit > > Modules/Setup to build pyexpat explicitly. > > > Regards, > > Martin > > Fast-forward to 2008 > > I installed Python 3.0b2 on a Windows Vista laptop (after having > previously installed Python 2.5), and I am getting this same error: > > Traceback (most recent call last): > ? File "Programming\Python\monkeys.py", line 24, in > ? ? test_parse(sys.argv[1]) > ? File "Programming\Python\monkeys.py", line 21, in test_parse > ? ? xml.sax.parse(f, handler) > ? File "C:\Python30\lib\xml\sax\__init__.py", line 30, in parse > ? ? parser = make_parser() > ? File "C:\Python30\lib\xml\sax\__init__.py", line 90, in make_parser > ? ? raise SAXReaderNotAvailable("No parsers found", None) > xml.sax._exceptions.SAXReaderNotAvailable: No parsers found > > I see a pyexpat.lib in the C:\Python30\libs folder. > I also see a pyexpat.pyd in the C:\Python30\DLLs folder. > > It works in Python 2.5. I installed Python 3.0b2 as admin. > Does anyone know what is wrong and how to fix it? Does anyone have an answer for this? I uninstalled both Python 2.5 and Python 3.0b2 and then re-installed 3.0b2, thinking that the installer was confusing 2.5 and 3.0b2 on Windows Vista. Still have the same issue. I had to use my XP machine, since the Vista installation seems broken for Python 3.0b2. How do I fix this? How do I get Python to notice the pyexpat.lib in the C:\Python30\DLLs folder in Vista? Thanks From tmohr at s.netic.de Tue Sep 16 15:12:59 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Sep 2008 21:12:59 +0200 Subject: new style classes, __new__, __init__ Message-ID: Hi, i have some questions related to new style classes, they look quite useful but i wonder if somebody can give me an example on constructors using __new__ and on using __init__ ? I just see that when using it i can't give parameters to __new__ and when i additionally define __init__ then __new__ is not called. So i can use __new__ only for classes whose constructors don't have parameters? class C2: def __new__(self): print "new called" self.a = 8 def __init__(self, a): print "init called" self.a = a def fct(self): print self.a a = C2(7) a.fct() This way __new__ is not called, if i remove __init__ then there are too many parameters to __new__, if i add a parameter to __new__ then it says that __new__ does not take arguments. Thanks for any hints, Torsten. From circularfunc at gmail.com Tue Sep 2 21:00:28 2008 From: circularfunc at gmail.com (process) Date: Tue, 2 Sep 2008 18:00:28 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> Message-ID: <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> On Sep 3, 2:36?am, John Machin wrote: > On Sep 3, 9:44 am, ssecorp wrote: > > > or why does this take so god damn long time? > > Because your code does so many god damn unnecessary things. Apart from > the fact (as pointed out already by Robert) that you are needlessly > finding the sizes (Y, X) that are already available: > > (1) You are executing a try block Y*X (approx) times instead of the Y+X > +2 times it would take if you were to do preliminary probes to find Y > and X > (2) You are doing range(1, 1000) Y times instead of once [see question > below] > (3) You are doing the method lookup im.getpixel Y*X times instead of > once > (4) you are doing the method lookup row.append Y*X times instead of Y > times > > > and if I run into an IndexError it break out of the inner loop right? > > so having range up to 10000000 or 1000 wouldn't matter if biggest > > working x is 800? > > > def getPixels(fileName): > > ? ? im = PIL.Image.open(fileName) > > ? ? colors = [] > > ? ? for y in range(1, 1000): > > Are you sure that both occurrences of range(1, 1000) shouldn't be > range(1000)? > > > ? ? ? ? row = [] > > ? ? ? ? for x in range(1, 1000): > > ? ? ? ? ? ? try: > > ? ? ? ? ? ? ? ? color = im.getpixel((x,y)) > > ? ? ? ? ? ? ? ? row.append(color) > > ? ? ? ? ? ? except IndexError: > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? colors.append(row) > > ? ? return numpy.array(colors) > > and it appears that you haven't bothered to read the manual section on > Image.getpixel: > """ > Note that this method is rather slow; if you need to process larger > parts of an image from Python, you can either use pixel access objects > (see load), or the getdata method. > """ how could I do getpixel once when x and y s changing? anyway I rewrote and saw I did a lot of stupid stuff. this is fast: def getPixels5(fileName): im = PIL.Image.open(fileName) colors = [] r, c = im.size for y in range(0, c): row = [] for x in range(0, r): color = im.getpixel((x,y)) row.append(color) colors.append(row) return numpy.array(colors) but I don't need it anuyway apparently since there already was such methods :) From clay at lakeserv.net Sun Sep 28 20:10:42 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Sun, 28 Sep 2008 20:10:42 -0400 Subject: [wxpython-users] ANN: wxPython 2.8.9.0 In-Reply-To: <48DFD492.1090905@alldunn.com> References: <48DFD492.1090905@alldunn.com> Message-ID: <1222647042.29889.1.camel@generator> On Sun, 2008-09-28 at 12:01 -0700, Robin Dunn wrote: > Announcing > ---------- > > The 2.8.9.0 release of wxPython is now available for download at > http://wxpython.org/download.php. This release adds support for using > Cairo for drawing on wx windows, adds a Win64 build, and various other > fixes and enhancements. > > Source code is available, as well as binaries for Python 2.3, 2.4 and > 2.5, for Windows and Mac, as well some packages for various Linux > distributions. A summary of changes is listed below and also at > http://wxpython.org/recentchanges.php. > > > > What is wxPython? > ----------------- > > wxPython is a GUI toolkit for the Python programming language. It > allows Python programmers to create programs with a robust, highly > functional graphical user interface, simply and easily. It is > implemented as a Python extension module that wraps the GUI components > of the popular wxWidgets cross platform library, which is written in > C++. > > wxPython is a cross-platform toolkit. This means that the same program > will usually run on multiple platforms without modifications. > Currently supported platforms are 32-bit and 64-bit Microsoft Windows, > most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. > In most cases the native widgets are used on each platform to provide > a 100% native look and feel for the application. > > > Changes in 2.8.9.0 > ------------------ > > Many minor bug fixes throughout wxWidgets and wxPython. > > Fixed wx.lib.embeddedimage to work with Python 2.3. > > Fixed PseudoDC hit testing when pure white or pure black are used. > > Added support for a 64-bit Windows build for the AMD64 architecture, > (a.k.a. x64.) This is for Python 2.5 only and is available only as a > Unicode build. > > Added the wx.EmptyBitmapRGBA factory function. > > Added the wx.lib.wxcairo module which allows the pycairo package to be > used for drawing on wx window or memory DCs. In addition it is able > to convert from a native wx.Font to a cairo.FontFace, and it also > provides functions for converting to/from wx.Bitmap and > cairo.ImageSurface objects. In order to use this module you will need > to have the Cairo library and its dependencies installed, as well as > the pycairo Python package. For Linux and other unix-like systems you > most likely have what you need installed already, or can easily do so > from your package manager application. See the wx.lib.wxcairo > module's docstring for notes on where to get what you need for Windows > or Mac. This module uses ctypes, and depending on platform it may > need to find and load additional dynamic libraries at runtime in > addition to cairo. The pycairo package used needs to be new enough to > export the CAPI structure in the package namespace. I believe that > started sometime in the 1.4.x release series. > > Added the wx.lib.graphics module, which is an implementation of the > wx.GraphicsContext API using Cairo (via wx.lib.wxcairo). This allows > us to be totally consistent across platforms, and also use Cairo to > implement some things that are missing from the GraphicsContext API. > It's not 100% compatible with the GraphicsContext API, but probably > close enough to be able to share code between them if desired, plus it > can do a few things more. > > Updated wx.Bitmap.CopyFromBuffer to be a bit more flexible. You can > now specify the format of the buffer, and the CopyFromBufferRGBA is > now just a wrapper around CopyFromBuffer that specifies a different > format than the default. Also added the complement method, > CopyToBuffer. See the docstring for CopyFromBuffer for details on the > currently allowed buffer formats. The existing wx.BitmapFromBuffer > factory functions are also now implemented using the same underlying > code as CopyFromBuffer. > > Add wx.lib.mixins.listctrl.ListRowHighlighter for automatic highlighting > of rows in a wx.ListCtrl. > I'm curious, why do you package wxPython for Fedora 6 and 7, but not 8 and 9? --Ratfink From fredrik at pythonware.com Tue Sep 16 03:59:48 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Sep 2008 09:59:48 +0200 Subject: PyMarshal Commands crash on Windows In-Reply-To: <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> Message-ID: spammaster.10.webmaster at spamgourmet.com wrote: > I shortened the quode. Everything should be all right and nothing is a > NULL Pointer. What about PyMarshal_ReadObjectFromFile(FILE* p), this > crashs too :-/ the layout of the "FILE" structure isn't standardized. make sure you're linking everything with the same runtime library. From tjreedy at udel.edu Mon Sep 22 18:44:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 18:44:19 -0400 Subject: a short-cut command for globals().clear() ?? In-Reply-To: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> Message-ID: CapnBearbossa at googlemail.com wrote: > forgive me , but the RTFM and Google search approaches are not > yielding an answer on this question. I need to know if there's a top > level python interpreter command that clears all user variables (not > built-ins) from the global namespace. In other words a statement, or > some_command_or_function(), that does this: > >>>> x=3 >>>> y=4 >>>> z=[] >>>> dir() > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > >>>> some_command_or_function() > >>>> dir() > ['__builtins__', '__doc__', '__name__'] First, a WARNING to other readers deceived by the subject line. Globals().clear() clears everything and leaves nothing, so Capn... is looking for something that works that is a shortcut for deleting bindings one-by-one. To your question. The short answer is no. In batch mode, only create what you need and delete (unbind) large objects that are not automatically deleted (unbound) when you are done with them. Remember that only reference-counted implementations will guarantee immediate destruction and space-freeing when the last reference goes away. Check the gc module (and some posts in the archives) for more specialized control. In interactive mode, restart the interpreter if you really need a clean slate and have too many bindings that you must delete to do something quick like 'del x,y,z' as in your example above. In IDLE, cntl-F6 restarts the shell with a clean slate. I presume IPython has something similar. tjr From bignose+hates-spam at benfinney.id.au Wed Sep 17 04:34:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Sep 2008 18:34:00 +1000 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> <200809151645.13078.maric@aristote.info> Message-ID: <87skrz41dz.fsf@benfinney.id.au> Maric Michaud writes: > Le Monday 15 September 2008 16:45:12 Maric Michaud, vous avez ?crit?: > > This is not sufficient for auto-responses, and given the following > > rfcs, it would smart to both : > > > ... > > - add or modify the Return-Path and/or Reply-To header for badly > > implemented auto-responders to point to list maintainer. > > Oh, no ! to the list itself of course. Those fields have a defined use, and neither is suitable for munging by mailing list software . The mandatory 'Return-Path' field records the address given in the MAIL FROM command that transported the message. This is defined in RFC 2821. The optional 'Reply-To' field, if used at all, records the address that the author of the message suggests for return correspondence. This is defined in RFC 2822. Neither of these fields is suitable for tampering by mailing list software; 'Return-Path' is set when the message is first sent, and 'Reply-To' is for use by the *author* of the message, not by software that later handles it. Mailing list programs record their information in several fields all of which start with 'List-' and defined in RFC 2369. The purpose you seem to be describing, the list posting address, is recorded in the 'List-Post' field, which records the URL to use for sending contributions to the same maling list. A summary of all header fields for use in mail and MIME is at RFC 4021. > This could also avoid the common mistake mailing list users do in > replying private mail accidentally when the adress of the list is > only present in CC field. That mistake is easy to correct, without breaking standard definitions of fields: the user can simply send the message again to the correct destination. (I would suggest that, to help avoid repetition of this mistake, the user then pressure their software vendor to incorporate the "Reply to list" function making use of the standard 'List-Post' field in every list message.) Munging other fields such as 'Reply-To' leads to other common mistakes that are far more damaging: replies that were intended only for the author are sent to the 'Reply-To' address (as defined by the standard), but instead get sent to the entire list. This damage is usually impossible for the user to undo. If the software you use still isn't following the internet mail standards, then fix the software, or pressure your vendor to do so. -- \ ?Are you pondering what I'm pondering?? ?Umm, I think so, | `\ Brain, but what if the chicken won't wear the nylons?? ?_Pinky | _o__) and The Brain_ | Ben Finney From christopher.paul.taylor at gmail.com Wed Sep 17 11:31:21 2008 From: christopher.paul.taylor at gmail.com (christopher taylor) Date: Wed, 17 Sep 2008 11:31:21 -0400 Subject: python regex character group matches...group...gotcha Message-ID: My apologies to the respondents - I failed to screen my test cases before kicking them out to the global python-list. but yes, the 'X' character in my test case was a mistake on my part. I'll give group() a shot. ct From ldo at geek-central.gen.new_zealand Sun Sep 28 02:03:42 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 28 Sep 2008 19:03:42 +1300 Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: In message <9890864a-09f9-40d6-b2cc-5028e7a0c8c3 at q26g2000prq.googlegroups.com>, est wrote: > The problem is, why the f**k set ASCII encoding to range(128) ???????? Because that's how ASCII is defined. > while str() is internally byte array it should be handled in > range(256) !!!!!!!!!! But that's for random bytes. How would you convert an arbitrary object to random bytes? From steven at REMOVE.THIS.cybersource.com.au Tue Sep 2 02:10:51 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 06:10:51 GMT Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: On Tue, 02 Sep 2008 11:13:27 +1000, Ben Finney wrote: > bearophileHUGS at lycos.com writes: > >> For Python 2.7/3.1 I'd now like to write a PEP regarding the >> underscores into the number literals, like: 0b_0101_1111, 268_435_456 >> etc. > > +1 on such a capability. > > -1 on underscore as the separator. > > When you proposed this last year, the counter-proposal was made > > to instead use white space for the separator, exactly as one can now do > with string literals. > > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > literals. At the risk of bike-shedding, I think that allowing arbitrary whitespace between string literals is fine, because it aids readability to write this: do_something( "first part of the string" "another part of the string" "yet more of the string" "and a bit more" "and so on..." ) but I'm not sure that it is desirable to allow this: do_something( 142325 93.8012 7113 ) -1/2 on arbitrary whitespace, +1/2 on a single space, and +0 on underscores. If semi-colons didn't already have a use, I'd propose using them to break up numeric literals: 14;232;593.801;271;13 -- Steven From george.sakkis at gmail.com Thu Sep 18 02:20:27 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 17 Sep 2008 23:20:27 -0700 (PDT) Subject: decorator and API References: Message-ID: <83cdd6aa-1b2c-4b30-a1da-027659598d06@c58g2000hsc.googlegroups.com> On Sep 17, 5:56 pm, Lee Harr wrote: > I have a class with certain methods from which I want to select > one at random, with weighting. > > The way I have done it is this .... > > import random > > def weight(value): > def set_weight(method): > method.weight = value > return method > return set_weight > > class A(object): > def actions(self): > 'return a list of possible actions' > > return [getattr(self, method) > for method in dir(self) > if method.startswith('action_')] > > def action(self): > 'Select a possible action using weighted choice' > > actions = self.actions() > weights = [method.weight for method in actions] > total = sum(weights) > > choice = random.randrange(total) > > while choice> weights[0]: > choice -= weights[0] > weights.pop(0) > actions.pop(0) > > return actions[0] > > @weight(10) > def action_1(self): > print "A.action_1" > > @weight(20) > def action_2(self): > print "A.action_2" > > a = A() > a.action()() > > The problem I have now is that if I subclass A and want to > change the weighting of one of the methods, I am not sure > how to do that. > > One idea I had was to override the method using the new > weight in the decorator, and then call the original method: > > class B(A): > @weight(50) > def action_1(self): > A.action_1(self) > > That works, but it feels messy. > > Another idea was to store the weightings as a dictionary > on each instance, but I could not see how to update that > from a decorator. > > I like the idea of having the weights in a dictionary, so I > am looking for a better API, or a way to re-weight the > methods using a decorator. > > Any suggestions appreciated. Below is a lightweight solution that uses a descriptor. Also the random action function has been rewritten more efficiently (using bisect). George #======== usage =========================== class A(object): # actions don't have to follow a naming convention @weighted_action(weight=4) def foo(self): print "A.foo" @weighted_action() # default weight=1 def bar(self): print "A.bar" class B(A): # explicit copy of each action with new weight foo = A.foo.copy(weight=2) bar = A.bar.copy(weight=4) @weighted_action(weight=3) def baz(self): print "B.baz" # equivalent to B, but update all weights at once in one statement class B2(A): @weighted_action(weight=3) def baz(self): print "B2.baz" update_weights(B2, foo=2, bar=4) if __name__ == '__main__': for obj in A,B,B2: print obj for action in iter_weighted_actions(obj): print ' ', action a = A() for i in xrange(10): take_random_action(a) print b = B() for i in xrange(12): take_random_action(b) #====== implementation ======================= class _WeightedActionDescriptor(object): def __init__(self, func, weight): self._func = func self.weight = weight def __get__(self, obj, objtype): return self def __call__(self, *args, **kwds): return self._func(*args, **kwds) def copy(self, weight): return self.__class__(self._func, weight) def __str__(self): return 'WeightedAction(%s, weight=%s)' % (self._func, self.weight) def weighted_action(weight=1): return lambda func: _WeightedActionDescriptor(func,weight) def update_weights(obj, **name2weight): for name,weight in name2weight.iteritems(): action = getattr(obj,name) assert isinstance(action,_WeightedActionDescriptor) setattr(obj, name, action.copy(weight)) def iter_weighted_actions(obj): return (attr for attr in (getattr(obj, name) for name in dir(obj)) if isinstance(attr, _WeightedActionDescriptor)) def take_random_action(obj): from random import random from bisect import bisect actions = list(iter_weighted_actions(obj)) weights = [action.weight for action in actions] total = float(sum(weights)) cum_norm_weights = [0.0]*len(weights) for i in xrange(len(weights)): cum_norm_weights[i] = cum_norm_weights[i-1] + weights[i]/total return actions[bisect(cum_norm_weights, random())](obj) From deets at nospam.web.de Mon Sep 15 15:33:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 21:33:12 +0200 Subject: Python Nautilus script In-Reply-To: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> Message-ID: <6j7rjpF1rp5lU1@mid.uni-berlin.de> Michel Leunen schrieb: > Hi, > > I'm trying to write a python script for Nautilus. > To get the list of files selected in the Nautilus right pane, you use > the $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS environment variable which is > normally available to the script. Actually, it works with bash scripts > but not with python scripts > > import os > files = os.environ['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'].splitlines() > > gives a: > > File "", line 1, in > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' > > Fredrik Lundh explained me that all environment variables are not > accessible from subprocesses of an application. > > So my question is how can I get the Nautilus selected files in a python > script? There shouldn't be a difference between a shell-script and a python-script. Environment-variables are a unix-process-thing, and thus the rules that govern them apply to *all* processes - the shell is one of these, there is nothing special to it. If the shell-script gets the variable, the python-script will as well. Are you sure the shell gets the value? Or is it just silently ignoring a missing value, and the python-script isn't? According to the docs (I only googled the variable-name), the variable seems only to be set "only if local"[1], whatever that means. https://help.ubuntu.com/community/NautilusScriptsHowto Diez From ronald.chis.3 at gmail.com Sat Sep 20 13:20:08 2008 From: ronald.chis.3 at gmail.com (ronald) Date: Sat, 20 Sep 2008 10:20:08 -0700 (PDT) Subject: Sunbeam India UPS Point- unfair Trade Practices in Computer Business Message-ID: Sunbeam India UPS Point- unfiar Trade Practices in Computer Business Save Money, Tension, and Time. Avoid Nehru Place market to buy Computer Goods Hello All, This is to inform you all the sellers at the Nehru Place are not selling good products. Especially the shop- Nishchal Joshi, Sunbeam India UPS Point, 103, S2 1st Floor, Siddhartha Building, Nehru Place, New Delhi 110019. Phone - 9810276805, Email - nishchal1us at yahoo.com Engineer at Shop- Subash - 996899657 I bought a motherboard from that shop and that computer don't even worked for a single day. We called the person in just two days of purchase and he said he was out of town and so therefore bring it to me after one week. We took the system to his shop after spending money to nehru place, there he kept the system for five days and returned it back to us. However it was not rectified. Then we called him to our house and he charged money for this and did some corrections in the system and restarted the system. We told him to take his motherboard and gave our own old motherboard, then he said that he will rectify it, after making settings he left for the day. When we started the system, it started and got shut down immediately. And after that it never started. We called this person again and told him to take his motherboard back and gave us our old motherboard, but he said I am not the correct person, talk to the engineer who set the system for you. That Engineer Subash works for the Nishchal in his shop. Please suggest what action can be taken against him. Steps in the pipeline - Consumer Forum, Escalating issue to Consumer Affairs, Online Web and Nehru Place Online Community, so that others do not fall prey to this. Thanks Kritika Joshi kritikajoshi at in.com Save Money, Tension, and Time. Avoid Nehru Place (Nishchal Joshi, Unbeam India UPS Point, 103, S2 1st Floor, Siddhartha Building, Nehru Place, New Delhi ) market to buy Computer Goods. All the Best. From dblubaugh at belcan.com Mon Sep 29 15:45:02 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 15:45:02 -0400 Subject: PYTHON WORKING WITH PERL ?? In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9060@AWMAIL04.belcan.com> Thank You Steve!!! -----Original Message----- From: Steve Holden [mailto:steve at holdenweb.com] Sent: Monday, September 29, 2008 1:38 PM To: python-list at python.org Subject: Re: PYTHON WORKING WITH PERL ?? Blubaugh, David A. wrote: > To All, > > > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? Such as > utilizing python for internet programming and then utilize perl for > text processing and systems programming? Is this even feasible??? > > > Thanks, > So sorry to hear Google isn't available from your network ;-) http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From zxo102 at gmail.com Mon Sep 29 09:41:17 2008 From: zxo102 at gmail.com (zxo102) Date: Mon, 29 Sep 2008 06:41:17 -0700 (PDT) Subject: how to make smtplib.SMTP('localhost') work on window xp References: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Message-ID: On 9?29?, ??7?29?, Steve Holden wrote: > zxo102 wrote: > > Hi, > > I am trying to use python module smtplib to send my email out on > > window xp (localhost). > > > import smtplib > > server = smtplib.SMTP('localhost') > > > but I got the error information as follows: > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "c:\python24\lib\smtplib.py", line 244, in __init__ > > (code, msg) = self.connect(host, port) > > File "c:\python24\lib\smtplib.py", line 311, in connect > > (code, msg) = self.getreply() > > File "c:\python24\lib\smtplib.py", line 355, in getreply > > raise SMTPServerDisconnected("Connection unexpectedly closed") > > SMTPServerDisconnected: Connection unexpectedly closed > > > I am not sure what is wrong with it. Should I configure my window xp > > somewhere to run smtplib.SMTP('localhost')? > > > Thanks in advance. > > Well your code certainly expects *something* to be listening on port 25 > on localhost. It's fairly unusual to run an SMTP server on Windows XP, > though not impossible. > > usually your email system is set up to use some external host as uts > SMPT server: if you look in your mail client's configuration you will > probably find out whihc host you should be using. > > regards > Steve > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ In my case, I implement an application with python to accomplish collecting real time data from a serial port: com1 which is connected to some xbee hardwares. The python logging module is used to save the information generated at runtime into a log file. Since the site is far away from my office, I try to use a smtp server with the python smtplib module to send the log file into my email account regularly so that I can check it from anywhere. Thanks for your suggestion. Ouyang From python.list at tim.thechases.com Thu Sep 18 12:27:42 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 18 Sep 2008 11:27:42 -0500 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: <48D2817E.5030301@tim.thechases.com> Grant Edwards wrote: > While we're making suggestions, I've always wished that the > --help output displayed the default values for options in > addition to the help text specified by the user. I end up > having to enter the default values twice -- once as a keyword > argument and again in the help text. Then later when I decide > to change the default value, things get out-of-sync. Tangential to this thread, what's the preferred way to get changes into optparse? Based on the comments I've read in the optparse.py file, it looks like it's the generated output of some other process. I've patched my local version to include some changes for handling newlines in help text (which has cropped up on the list occasionally, as the current version eats newlines), but am not sure whether I need to be patching against the optparse.py or against the file that generated it (which I don't have in my install, AFAIK). Perhaps one of the core devs that works on optparse could tell me how they'd prefer such changes submitted? Thanks, -tkc From dudeja.rajat at gmail.com Sat Sep 27 09:49:51 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 27 Sep 2008 14:49:51 +0100 Subject: Regular expression help: unable to search ' # ' character in the file In-Reply-To: References: Message-ID: On Sat, Sep 27, 2008 at 1:58 PM, Fredrik Lundh wrote: > dudeja.rajat at gmail.com wrote: > > import re >> >> fd = open(file, 'r') >> line = fd.readline >> pat1 = re.compile("\#*") >> while(line): >> mat1 = pat1.search(line) >> if mat1: >> print line >> line = fd.readline() >> > > I strongly doubt that this is the code you used. > > But the above prints the whole file instead of the hash lines only. >> > > "*" means zero or more matches. all lines is a file contain zero or more # > characters. > > but using a RE is overkill in this case, of course. to check for a > character or substring, use the "in" operator: > > for line in open(file): > if "#" in line: > print line > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks Fredrik, this works. Indeed it is a much better and cleaner approach. -- Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjruth at gmail.com Fri Sep 12 16:07:52 2008 From: bjruth at gmail.com (byron) Date: Fri, 12 Sep 2008 13:07:52 -0700 (PDT) Subject: book example confusion References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: <0a61d5f4-0eaa-4d52-b720-efb702bb5a10@c65g2000hsa.googlegroups.com> On Sep 12, 3:51?pm, John Machin wrote: > On Sep 13, 5:36?am, byron wrote: > > > > > I am reading o'reilly's learning python (great book), but i came > > across an example (pg 291, pdf) that I am not quite understanding the > > reasoning for the author's explanation: > > > if f1() or f2(): > > > The author states that do to the nature of that expression, if f1() > > returns True, f2() will not be evaluated.. which makes sense. His > > quote: > > > ? ? ? ? "Here, if f1 returns a true (or nonempty) value, Python will > > never run f2." > > > He then states: > > > ? ? ? ? "To guarantee that both functions will be run, call them > > before the 'or':" > > > tmp1, tmp2 = f1(), f2() > > if tmp1 or tmp2: > > > Being that each function is an object, a name assignment to > > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > > the name is called.. so why would the latter example "run" both > > functions as the author suggests? > > It's not a "name assignment". > In effect it's doing this: > ? ?tmp1 = f1() # get the RESULT of calling f1() > ? ?tmp2 = f2() # likewise f2 > ? ?if tmp1 or tmp2: # if result1 or result2 > A (pointless) "name assignment") with the nil effect that you fear > would look like this: > ? ? tmp1, tmp2 = f1, f2 # Look, no parentheses after function names > ? ? if tmp1() or tmp2(): > > HTH, > John That makes sense. Thank you for the clarification. From martin at v.loewis.de Sun Sep 14 13:56:05 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 14 Sep 2008 19:56:05 +0200 Subject: How to emit Cyrillic and Chinese via unicode from console mode? In-Reply-To: References: Message-ID: <48CD5035.3050108@v.loewis.de> > Can someone point me to an example of a little program that emits non-ascii > Unicode characters (Russian or Chinese perhaps)? The unicode > Russian/Cyrillic alphabet starts at 0x410. Is this possible to do in a > console mode program? If not, I guess I would want to use pywin32 to create > a window and a message pump and display it there. I anticipate using pywin32 > for some other function calls. It also depends on your console. On Linux, with an UTF-8 capable-and-enabled console, py> print u"\u0413" ? work just fine. Regards, Martin From maric at aristote.info Mon Sep 15 07:38:42 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 13:38:42 +0200 Subject: Representation of python code ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: <200809151338.43017.maric@aristote.info> Le Sunday 14 September 2008 15:44:03 Barak, Ron, vous avez ?crit?: > Hi Guys, > Is there a script/application, which gets as input python code, and > produces a (graphic) representation of the inter-relationships between its > classes/functions ? Bye, None I know of. Not saying that it would be unfeasible, but it would be a hard job, given the fact that most of relationships are purely dynamic. How such an application would find the relationship (composition) between A and B without executing this code ? class A : def __init__(self) : self._b = B() class B : pass -- _____________ Maric Michaud From steven at REMOVE.THIS.cybersource.com.au Thu Sep 11 23:37:51 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 12 Sep 2008 03:37:51 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> Message-ID: On Thu, 11 Sep 2008 10:20:41 -0700, Aaron \"Castironpi\" Brady wrote: > XML is the wrong word for the example I was thinking of (as was already > pointed out in another thread). XML is by definition sequential. I'm pretty sure you're wrong. XML can be used for serialization, but that doesn't mean it is only sequential data. XML is suitable for hierarchical data too. To quote Wikipedia: "As long as only well-formedness is required, XML is a generic framework for storing any amount of text or any data whose structure can be represented as a tree. The only indispensable syntactical requirement is that the document has exactly one root element (alternatively called the document element)." http://en.wikipedia.org/wiki/Xml -- Steven From bhood37 at hotmail.com Fri Sep 5 16:10:31 2008 From: bhood37 at hotmail.com (Uberman) Date: Fri, 05 Sep 2008 14:10:31 -0600 Subject: Happy fun time with SWIG In-Reply-To: <5vYvk.75246$C65.45163@en-nntp-01.dc1.easynews.com> References: <5vYvk.75246$C65.45163@en-nntp-01.dc1.easynews.com> Message-ID: Nobody has any help for me on this one? Let me see if I can make it clearer by using something simpler: +-------+ -------| Peter |------- | +-------+ | | | V V +-------------+ +-------------+ | Python | | Application | | Environment | | Environment | +-------------+ +-------------+ ^ ^ | | ---<--<--< ? >-->-->--- Both environments use the C++ class Peter in their environments (Application directly, and Python via SWIG). How do I exchange instances of Peter between them? How do I get Python-environment instances of Peter with its Python-specific settings into the Application's environment (and vice versa)? OR... Does anybody know of a a SWIG-specific mailing list or forum where discussion of this type of problem would be more appropriate? From gauravatnet at gmail.com Thu Sep 18 06:25:42 2008 From: gauravatnet at gmail.com (gauravatnet at gmail.com) Date: Thu, 18 Sep 2008 03:25:42 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> Message-ID: <5fcabe40-7997-49ce-af3f-8306fe34b40b@b2g2000prf.googlegroups.com> On Sep 18, 3:24?pm, gauravat... at gmail.com wrote: > On Sep 9, 9:09?pm, "J. Cliff Dyer" wrote: > > > > > On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > > > Matimus a ?crit : > > > > On Sep 8, 12:32 am, Bruno Desthuilliers > > > > wrote: > > > (snip) > > > >> ?>>> set(a).issubset(set(b)) > > > >> True > > > > > Just to clarify, doing it using sets is not going to preserve order OR > > > > number of elements that are the same. > > > > > That is: > > > > >>>> a = [1,1,2,3,4] > > > >>>> b = [4,5,3,7,2,6,1] > > > >>>> set(a).issubset(set(b)) > > > > True > > > > > This will return True if b contains at least on of each element found > > > > in a. If the OP wanted to check that list `a` appeared in order > > > > somewhere in list `b` then sets won't work. > > > > Indeed, and I should have mentionned this myself. Thanks for this reminder. > > > If preserving order is important, strings have many of the properties > > you're looking for, but it might take some work to figure out a suitable > > way to convert to a string. ?The problem is easier if you know something > > about the inputs. ?If all inputs are known to be numbers between 0 and > > 15, you can just do: > > > if ''.join(map(hex, a)) in ''.join(map(hex, b)): > > ? ? return True > > > Hmm... actually, with the '0x' prefix that hex() puts on numbers, I > > think this works for arbitrary integers. > > > Cheers, > > Cliff > > Hi, > > I looked inside this thread for my query which brought me the > following google search result > "Test if list contains another list - comp.lang.python | Google > Groups" > > But then I was disappointed to see the question asked was not exactly > right. Other programmers have already answered to the main question. > But what if you actually have to find out if a list has all its > element inside another list in the same order. For that I wrote the > code and that's what I came up with.. let me know if there are any > bugs in this code. > > #!C:\Python24 > > def findAllMatchingList(mainList, subList): > ? ? resultIndex = [] > ? ? globalIndex = 0 > ? ? for i in range(len(mainList)): > ? ? ? ? if i < globalIndex: > ? ? ? ? ? ? continue > ? ? ? ? globalIndex = i > ? ? ? ? increment = 0 > ? ? ? ? for j in range(len(subList)): > ? ? ? ? ? ? if mainList[globalIndex] == subList[j]: > ? ? ? ? ? ? ? ? globalIndex += 1 > ? ? ? ? ? ? ? ? increment += 1 > ? ? ? ? ? ? ? ? if j == (len(subList)-1): > ? ? ? ? ? ? ? ? ? ? resultIndex.append(globalIndex-increment) > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? break > > ? ? return resultIndex > > if __name__ == "__main__": > ? ? #Test case > ? ? mL = [ 'a', 'b', 'c', 1, 2, 4, 1, 2, 1, 1, 1, 2, 9, 1, 1, 1, 2, 3, > 'a', 1, 2, 3, 4 ] > ? ? #mL = [ 'a', 'a', 'b', 1 ,2 ,3, 5, 6] > ? ? sL = [ 1, 2, 3 ] > ? ? result = findAllMatchingList( mL, sL ) > ? ? for i in result: > ? ? ? ? print str(i) > > Regards, > Gaurav. From elzapp at elzapp.com Mon Sep 29 17:00:22 2008 From: elzapp at elzapp.com (Bard Aase) Date: Mon, 29 Sep 2008 23:00:22 +0200 Subject: Source code for python nativ methods and classes In-Reply-To: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> References: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> Message-ID: <257224ff0809291400t1611aa6cm1b033b539392f353@mail.gmail.com> On Mon, Sep 29, 2008 at 10:51 PM, Mohed wrote: > Hello. > I am interrested in seeing the source code for all the nativ builtin > methods and clases in python. Is there a webpage that lists them or is > this done easier some other way. Check it out from svn? svn co http://svn.python.org/projects/python/trunk/ or browse the code at http://svn.python.org/view/python/trunk/ or did I misinterpret your question? -- mvh base (B?rd Aase) MSN: msn at elzapp.com http://blog.elzapp.com :wq From tjreedy at udel.edu Sat Sep 27 19:16:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2008 19:16:06 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: <1a7184f3-c71e-49b7-a8f8-f141705f3573@l42g2000hsc.googlegroups.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <00ee05ca$0$20666$c3e8da3@news.astraweb.com> <1a7184f3-c71e-49b7-a8f8-f141705f3573@l42g2000hsc.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: >>>> class A(type): > ... def __call__( self, *ar ): > ... print 'call', self, ar > ... >>>> class B(object): > ... __metaclass__= A > ... >>>> B(3) > call (3,) > > Overriding the __call__ method of 'type' has the effect of giving you > a static __call__ method on a class-- a method which doesn't need an > instance to call. Your behavior may be counterintuitive though, to > someone who wants to instantiate 'B', in this case, and proceed like a > normal object. That is, they want to call a generic class and use it, > and also expect instances of B to behave as B. You can't have both, > so either return B from B.__new__, or, to instantiate B, take the long > way and call B.__new__ directly. > >>>> B.__new__(B) > <__main__.B object at 0x009FDB70> > > Has anyone stepped through the C code to find out when the decision is > made to call which function, B.__new__ or A.__call__, when B is > called? For Python coded objects, ob(*args) in code translates to internal execution of type(ob).__call__(ob, *args) (without further translation!). The interpreter compiles a statement at a time, without looking back to do type inferencing, and so does not know what type is being called or if it is even callable. For B, B(*args) == type(B).__call__(B, *args) == A.__call__(B, *args). So there is no decision. For C coded objects, I believe ob(*args) in Python code translate to a C call of the C equivalent of type(ob).tp_call (or something like that). From observation, type.tp_call acts something like this: def __call__(cls, *args): if cls == type: if len(*args): return arg[0].__class__ elif len(*args) == 3: return type.__new__(type, *args) # or maybe not pass type? else: raise TypeError('type() takes 1 or 3 arguments') else: return cls.__new__(cls, *args) So, for a normal class C (an instance of type), type.__call__ calls C.__new__. Terry Jan Reedy From kyosohma at gmail.com Thu Sep 4 16:03:46 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Sep 2008 13:03:46 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> Message-ID: <3c2a22dd-a713-49a4-b396-c55301950bef@w24g2000prd.googlegroups.com> On Sep 4, 2:50?pm, Fett wrote: > On Sep 4, 2:23?pm, Mike Driscoll wrote: > > > > > On Sep 4, 1:39?pm, Fett wrote: > > > > I need a crypto package that works on windows with python 2.5. Can > > > anyone suggest one for me? > > > > I have been searching for a couple days for a good cryptography > > > package to use for public/private key encryption, at this point I > > > would settle for symmetric even. > > > > Every encryption package I have found for python was either operating > > > system specific (read *nix only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/ > > > > There was one exception, this version was specifically built to run on > > > any platform (yay), but the compiler for windows complained that I > > > wasn't using python2.2 (though the package was said to only need 2.2 > > > or newer). > > > > Is there any crypto package that is actually written in python? I > > > seriously don't care how slow it is. > > > How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads > > > Mike > > Seems that this is intended more for webapps or something, I intend to > use this for a client application. This means that I can't require > outside dependencies, or I risk annoying the clients (if you have > installed many open-source projects with dependencies that aren't > handled by portage/apt-get, you know what I would be doing to them). > > I seriously can't believe that there isn't a single python native > crypto package. Why do they all need to have outside dependencies? If you are distributing your application on Windows (which is what your original post implied), then you can easily roll up dependencies with py2exe / Gui2Exe and something like Inno Setup or NSIS. I'm going to try to compile the crypto package (http://www.amk.ca/python/code/ crypto) into an installer for 2.5, but no promises. Mike From deets at nospam.web.de Thu Sep 18 05:18:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Sep 2008 11:18:08 +0200 Subject: Program works great, except under less, cron or execl (Unicode?) References: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> <6jekbbF2v55pU2@mid.uni-berlin.de> Message-ID: <6jekmpF2v55pU3@mid.uni-berlin.de> > Most probably because when to running directly inside a terminal, it gets That was of course meant to be "not running directly inside a terminal". > it's stdin/stdout as pipes - and python can't attempt to guess the proper > encoding on that, as it does on a terminal. Diez From vvangelovski at gmail.com Tue Sep 16 16:07:11 2008 From: vvangelovski at gmail.com (vvangelovski at gmail.com) Date: Tue, 16 Sep 2008 13:07:11 -0700 (PDT) Subject: find the path of a module Message-ID: <7f3f0dce-52bd-45d3-87f1-2f9aa695e080@c58g2000hsc.googlegroups.com> I'd like to know if I can somehow find the path for a module somewhere in a the package hierarchy for instance if I import my module like so from spam.eggs import sausage my hypothetical method would return something like '/home/developer/projects/spam/eggs/sausage.py/c' given that module object. From tiftof at gmail.com Tue Sep 30 13:18:27 2008 From: tiftof at gmail.com (Christophe) Date: Tue, 30 Sep 2008 19:18:27 +0200 Subject: how to find out the version of a certain installed package In-Reply-To: <48E2541E.7030605@egenix.com> References: <48E2541E.7030605@egenix.com> Message-ID: <8531008b0809301018r96a2653obd4a99455ad5383d@mail.gmail.com> great! thanks for you fast response. Christophe On Tue, Sep 30, 2008 at 6:30 PM, M.-A. Lemburg wrote: > On 2008-09-30 18:17, Christophe wrote: > > Hi, > > > > In a projecet I'm making using pycrypto, I need to find out the > > current installed version of pycrypto. After looking around, I found > > out that "pkg_resources.requires("pycrypto") will give me a string > > containing the version number, but is this the only way to do it or > > are there other ways? > > Most packages have a .__version__ attribute in their top-level > package dir which you can query. > > You do have to import the base package, though, in order to find > out. > > Thanks, > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Sep 30 2008) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mathieu.prevot at gmail.com Thu Sep 4 03:59:10 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 09:59:10 +0200 Subject: use str as variable name In-Reply-To: <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> Message-ID: <3e473cc60809040059o5ebb0bd2h54db1d38929a533b@mail.gmail.com> 2008/9/4 Chris Rebert : > On Thu, Sep 4, 2008 at 12:25 AM, Mathieu Prevot > wrote: >> Hi, >> >> I have a program that take a word as argument, and I would like to >> link this word to a class variable. >> >> eg. >> class foo(): > > You should subclass 'object', so that should be: > class Foo(object): > >> width = 10 >> height = 20 >> >> a=foo() >> arg='height' >> a.__argname__= new_value > > You're looking for the setattr() built-in function. In this exact case: > setattr(a, arg, new_value) > > This is probably covered in the Python tutorial, please read it. > > Regards, > Chris Indeed. I'll use: a.__setattr__(height, new_value) Thanks to all Mathieu From kay.schluehr at gmx.net Wed Sep 24 05:54:05 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 24 Sep 2008 02:54:05 -0700 (PDT) Subject: Does anybody use this web framework ? References: <48d94cbc$0$964$ba4acef3@news.orange.fr> <48d9eb86$0$6127$426a34cc@news.free.fr> Message-ID: <9f3ba168-d6e0-4488-af1b-d182f77e9791@y38g2000hsy.googlegroups.com> On 24 Sep., 09:26, Bruno Desthuilliers wrote: > Phil Cataldo a ?crit : > > > Hi, > > > I just found this new? python web framework > > (http://pypi.python.org/pypi/nagare/0.1.0). > > > Does anybody know or use it ? > > First time I hear of it, but it looks interesting (note : Stackless > continuation-based framework). Thanks for the link. Dito! From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 04:53:51 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 10:53:51 +0200 Subject: how to find position of dictionary values In-Reply-To: References: Message-ID: <48bbad4d$0$12756$426a74cc@news.free.fr> lee a ?crit : > > hi, thank u your solution is exactly wat i wanted :) I'm afraid it's not what you actually *need*, cf my other post. From kaiser.vocote at gmail.com Tue Sep 16 07:47:51 2008 From: kaiser.vocote at gmail.com (Andreas Kaiser) Date: Tue, 16 Sep 2008 04:47:51 -0700 (PDT) Subject: What is "finally:" for? References: Message-ID: On 16 Sep., 13:25, "Max Ivanov" wrote: > Hi all! > When and where I should use try-except-finally statement? What is the > difference between: > -------- > try: > ? A... > except: > ? B.... > finally: > ? C... > -------- > > and > ------- > try: > ? A... > except: > ? B.... > C... Look at: http://docs.python.org/ref/try.html and http://bytes.com/forum/thread24648.html The python doc says: "Changed in version 2.5: In previous versions of Python, try...except...finally did not work. try...except had to be nested in try...finally." Andreas From fredrik at pythonware.com Fri Sep 12 10:46:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 16:46:49 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <3f0d61c40809120718r6709387bj68e75e9c40ce2036@mail.gmail.com> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <3f0d61c40809120718r6709387bj68e75e9c40ce2036@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > Can you clarify where I can find "any"? It seems to me I'm > unable to find it... it's a 2.5 addition. to use this in a "future-compatible" way in 2.3, you can add try: any except NameError: def any(iterable): for element in iterable: if element: return True return False to the top of the file (or to some suitable support library). 2.5 also provides an "all" function, which can be emulated as: try: all except NameError: def all(iterable): for element in iterable: if not element: return False return True From gminick at bzt.bzt Wed Sep 10 14:14:21 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 18:14:21 +0000 (UTC) Subject: removing text string References: Message-ID: On Wed, 10 Sep 2008 11:22:16 -0400, Ahmed, Shakir wrote: > I need to remove text string from the list of the numbers mentioned > below: > > 080829-7_A > 070529-5_c > 080824-7_O > 070405_6_p > > The output will be : 080829-7 > 070529-5 > 080824-7 > 070405-6 You need to read about slice indices. An example: >>> a=('080829-7_A', '070529-5_c', '080824-7_O') >>> [i[:-2] for i in a] ['080829-7', '070529-5', '080824-7'] -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From dmitry at athabascau.ca Thu Sep 25 15:42:40 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 19:42:40 GMT Subject: Eggs, VirtualEnv, and Apt - best practices? References: Message-ID: Scott Sharkey wrote: > Any insight into the best way to have a consistent, repeatable, > controllable development and production environment would be much > appreciated. you have just described OS package building ;) I can't speak for everybody, but supporting multiple platforms (PHP, Perl, Python, Java) we found that the only way to stay consistent is to use OS native packaging tools (in your case apt and .deb ) and if you're missing something - roll your own package. After a while you accumulate plenty of templates to chose from when you need yet-another-library not available upstream in your preferred package format. Remember that some python tools might depend on non-python packages, so the only way to make sure all that is consistent across environment - use unified package management. Sorry, not specific pointers though as we're redhat shop and debs are not our everyday business. From wuwei23 at gmail.com Wed Sep 10 22:06:32 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 10 Sep 2008 19:06:32 -0700 (PDT) Subject: Alternatives to traditional RDBMS References: <6iq90jFdeiU1@mid.uni-berlin.de> Message-ID: <3ee3f834-b314-4a75-a85c-6a13bb118b09@l33g2000pri.googlegroups.com> "James Mills" wrote: > This is an ORM. They are > off-topic for this thread :) Tsk, such an unfounded bias... I've had a lot of success using sqlalchemy + Elixir together ;) From castironpi at gmail.com Mon Sep 29 17:35:15 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 29 Sep 2008 14:35:15 -0700 (PDT) Subject: Music knowledge representation References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> <20080929124940.8c1c82e8.darcy@druid.net> <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> Message-ID: On Sep 29, 3:56?pm, "D'Arcy J.M. Cain" wrote: > On Mon, 29 Sep 2008 20:29:44 +0200 > > "Mr.SpOOn" wrote: > > > Couldn't the note class simply have a list of all the notes and have a > > > simple method calculate the actual pitch? > > > That's not really how it works. There exists just 12 octave > > independent pitch classes. This means that there is a pitch class C > > with all possible Cs. There ambiguities with accidentals, because > > different named notes fall in the same pitch class. The difference is > > important for the musical theory, because C# and Db belongs to the > > same pitch class (actually they are the same note, they sounds > > completely identical -- because on the piano you play them pressing > > the same key), but in a scale they have a very different role. > > Sure, they are enharmonically identical but in our tempered scale. > That's why my example showed it as (note, octave, accidental) rather > than a specific note. ?It would differentiate between these. > > > For example, the interval C F# is an "augmented fourth", because what > > really matters are the natural note (C and F), and their distance if > > 4. Then it is augmented due to the #- > > > But the interval C Gb (Gb is the same as F#) is a "diminished fifth". > > This is true. ?My simple example would not have dealt with this. ?The > arguments would have to be the full tuple rather than the actual pitch. > > > So I can't list all pitches. > > You can but you can't store them as raw pitches. > > > > ? ?def interval(self, lower, higher) > > > ? ? ? ?if lower > higher: > > > ? ? ? ? ? ?# uncomment one of the two following lines depending > > > ? ? ? ? ? ?# on the behaviour you want > > > ? ? ? ? ? ?#lower,higher = higher,lower > > > ? ? ? ? ? ?#higher += 12 > > > > ? ? ? ?# could use some error trapping > > > ? ? ? ?return self.interval_name[higher - lower] > > > > Note that lower and higher could be a note object that you have to > > > convert to integers first. > > > I can't estabilish which note is higher, because all the analysis part > > is octave independent. Anyway thanks for the ideas. > > I'm not sure I understand this. ?You either have to assume that the > first note is the root or the lower one is. ?What other options are > there? ?It sounds like your requirement is "higher += 12" or some > variant. ?It also depends on whether you need to deal with things like > ninths and thirteenths. > > Anyway, I was just tossing out ideas. ?You know what your requirements > are better than I. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolveshttp://www.druid.net/darcy/? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. I like D'Arcy's tuples so far. You could have a 4th element that contains adjustment for temper. Octave could be None. You want ( 4, None, 1 ) "sharp 4th" == ( 5, None, -1 ) "flat 5th", but you can't have it. The closest ones are Note( 4, None, 1 )== Note( 5, None, -1 ) or Note(4, None, 1 ).enh_cmp( Note( 5, None, -1 ) ). More elaborate code means more options for calling, though: Note(4, None, 1 ).cmp_enh( 5, None, -1 ), and just call the constructor on the 3 arguments. You also want Note( 9, None, 0 ).cmp_octave( 2, Rel+ 1, 0 ), 9th== 2nd + 1 octave, and Note( 9, None, 0 ).cmp_nooctave( 2, None, 0 ), where cmp_... functions return in ( -1, 0, 1 ), and the middle term can be a class Relative instance, which indicates a relative octave instead of absolute... or just start at 4. From fredrik at pythonware.com Wed Sep 17 08:42:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 14:42:25 +0200 Subject: recursive using the os.walk(path) from the os module In-Reply-To: References: Message-ID: A. Joseph wrote: > I want to search through a directory and re-arrange all the files into e.g > > All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder. > > I`m thinking of doing something with the os.walk(path) method from os > module, I need some ideal how the algorithm should look like, maybe > recursive ..any deal? os.walk traverses the directory tree, so I'm not sure why you think that your program needs to use recursion? wouldn't a plain loop work? import os, shutil for dirpath, dirnames, filenames in os.walk(directory): for name in filenames: source = os.path.join(dirpath, name) ... check extension and determine target directory ... destination = os.path.join(targetdir, name) shutil.move(source, destination) tweak as necessary. From eric.e.janke at gmail.com Tue Sep 23 11:18:03 2008 From: eric.e.janke at gmail.com (Eric E) Date: Tue, 23 Sep 2008 08:18:03 -0700 (PDT) Subject: Attachment Size and SMTP EMail References: Message-ID: <14a905ea-11a6-449d-af33-b184f28e178e@59g2000hsb.googlegroups.com> On Sep 23, 9:52 am, Grant Edwards wrote: > On 2008-09-23, Eric E wrote: > > > I am using python to send an email with a large zip file as an > > attachment. I successfully sent a 52M attachment. If I try > > to send a 63M attachment or larger, the message never gets > > through. I do not get any errors in my python code. > > Does sending large attachements with other SMTP clients using > the same SMTP server work? > > -- > Grant Edwards grante Yow! Zippy's brain cells > at are straining to bridge > visi.com synapses ... I do not know for sure. I recently downloaded msmtp 1.4.16 and am still in the process of trying to get it to work. From hniksic at xemacs.org Thu Sep 11 07:33:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 11 Sep 2008 13:33:01 +0200 Subject: Accessing __slots__ from C References: Message-ID: <87k5diex3m.fsf@mulj.homelinux.net> [ You can use the capi-sig for questions like this; see http://mail.python.org/mailman/listinfo/capi-sig ] Chris writes: > I'd like to be able to access an attribute of a particular Python > object as fast as possible from some C code. > > I wondered if using __slots__ to store the attribute would allow me to > do this in a faster way. > > The reason I'd like to do this is because I need to access the > attribute inside a loop within some C code, and I find that the > attribute lookup using the 'PyObject_GetAttrString' call is far slower > than any of the subsequent calculations I perform in C. PyObject_GetAttrString is convenient, but it creates a Python string only so it can intern it (and in most cases throw away the freshly created version). For maximum efficiency, pre-create the string object using PyString_InternFromString, and use that with PyObject_GetAttr. From xnews2 at fredp.lautre.net Wed Sep 10 14:36:15 2008 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 10 Sep 2008 18:36:15 GMT Subject: PyGUI as a standard GUI API for Python? References: <48BFB534.2080508@egenix.com> Message-ID: Todd Whiteman said : > Personally, I believe XULRunner has a lot to offer for Python GUI > development, I'm currently finishing up some documentation steps to show > off how to use it specifically for Python (I'll post it to this list > when it's finished). That would be really nice ! I've long been curious about the potential of XUL+Python, but put off by the lack of leads to follow up, and not having time to do the digging myself... TIA, fp From larry.bates at vitalEsafe.com Wed Sep 3 22:17:56 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Wed, 03 Sep 2008 21:17:56 -0500 Subject: Submitting forms over HTTPS with mechanize In-Reply-To: References: Message-ID: <48BF4554.7060809@vitalEsafe.com> Rex wrote: > Hello, > > I am working on an academic research project where I need to log in to > a website (www.lexis.com) over HTTPS and execute a bunch of queries to > gather a data set. I just discovered the mechanize module, which seems > great because it's a high-level tool. However, I can't find any decent > documentation for mechanize apart from the docstrings, which are > pretty thin. So I just followed some other examples I found online, to > produce the following: > > baseurl = 'http://www.lexis.com/' > br = mechanize.Browser() > br.set_handle_robots(False) > br.addheaders = [('User-Agent', 'Firefox')] > br.open(baseurl) > br.select_form(name="formauth") > br["USER_ID"]="my_user_id" > br["PASSWORD"]="my_password" > result = br.submit() > > This code hangs at br.submit(), and I can't tell what I'm doing wrong. > Typically I would inspect the HTTP data with an HTTP debugging proxy > (Fiddler), but I guess since this is HTTPS I can't do that. Any > glaring errors in my code? > > By the way, does anyone have suggestions for Python modules that I > should use instead of mechanize (and that are sufficiently easy)? If > mechanize fails, I might try modifying some similar Perl code a friend > sent me that logs into lexis.com. > > Thanks so much, > > Rex I've used mechanize quite successfully but others have suggested Twill http://twill.idyll.org/. It seems to be at least documented. -Larry From timr at probo.com Sat Sep 6 21:57:53 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 07 Sep 2008 01:57:53 GMT Subject: Determining Processor Vender References: <554ecfcf-96d8-4602-8d5e-ee5d70590124@i76g2000hsf.googlegroups.com> Message-ID: aha wrote: > >Dose anyone know of a cross-platform method for determining the vendor >of a processor? Under linux I can check /proc/cpuinfo. What I'd like >to be able to do is determine if a processor is AMD or Intel, so that >I can use the appropriate numerical libraries for my application. If you have a numerical library that uses processor-specific instructions, then the library must be in C with assembler. If so, just add another function that does a "cpuid" instruction and return the results. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From pDOTpagel at helmholtz-muenchen.de Wed Sep 3 06:41:52 2008 From: pDOTpagel at helmholtz-muenchen.de (Philipp Pagel) Date: Wed, 3 Sep 2008 10:41:52 +0000 (UTC) Subject: Renumbering References: Message-ID: Francesco Pietra wrote: > ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 > ATOM 3425 CA LEU B 428 142.918 87.524 78.875 1.00115.20 2SG3427 [...] > As you can see, the number of lines for a particular value in column 6 > changes from situation to situation, and may even be different for the > same name in column 4. For example, LEU can have a different number of > lines depending on the position of this amino acid (leucine). Others have alreade given good hints but I would like to add a bit of advice. The data you show appears to be a PDB protein structure file. It is important to realize that these are fixed-width files and columns can be empty so splitting on tab or whithespace will often fail. It is also important to know that the residue numbering (cols 23-26) is not necessarily contiguous and is not even unique without taking into account the 'insertion code' in column 27 which happens to be empty in your example. I would recommend to use a full-blown PDB parser to read the data and then iterate over the residues and do whatever you would like to acomplish that way. Biopython has such a parser: www.biopython.org cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://mips.gsf.de/staff/pagel From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 12:33:47 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 18:33:47 +0200 Subject: Not fully OO ? In-Reply-To: <48d4c11b$0$22877$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <48d541d8$0$32185$426a34cc@news.free.fr> candide a ?crit : > Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > > Thanks for any comment. The following definitions are AFAIK the only commonly accepted definitions about OO: 1/ an object is defined by identity, state and behaviour 2/ objects interacts by sending messages each other 3/ an OO program is made of interacting objects I let you find out whether Python meets these 3 definitions - and if Java does (hint : in Python, everything you can bind to a name is an object - this is not true in Java or C++). From ptmcg at austin.rr.com Fri Sep 26 10:18:28 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 26 Sep 2008 07:18:28 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> Message-ID: On Sep 25, 10:41?am, "Dmitry S. Makovey" wrote: > Diez B. Roggisch wrote: > > Dmitry S. Makovey schrieb: > >> Dmitry S. Makovey wrote: > >>> In my real-life case A is a proxy to B, C and D instances/objects, not > >>> just one. > > >> forgot to mention that above would mean that I need to have more than one > >> decorator function like AproxyB, AproxyC and AproxyD or make Aproxy > >> smarter about which property of A has instance of which class etc. > > > __getattr__? > > see, in your code you're assuming that there's only 1 property ( 'b' ) > inside of A that needs proxying. In reality I have several. So in your code > self._delegate should be at least a tupple or a list. Plus what you're > doing - you just promiscuously passing any method not found in Proxy to > self._delegate which is not what I need as I need to pass only a subset of > calls, so now your code needs to acquire dictionary of "allowed" calls, and > go over all self._delegates to find if any one has it which is not > efficient since there IS a 1:1 mapping of A::method -> B::method so lookups > shouldn't be necessary IMO (for performance reasons). > No, really, Diez has posted the canonical Proxy form in Python, using __getattr__ on the proxy, and then redirecting to the contained delegate object. This code does *not* assume that only one property ('b'? where did that come from?) is being redirected - __getattr__ will intercept all attribute lookups and redirect them to the delegate. If you need to get fancier and support this single-proxy-to-multiple- delegates form, then yes, you will need some kind of map that says which method should delegate to which object. Or, if it is just a matter of precedence (try A, then try B, then...), then use hasattr to see if the first delegate has the given attribute, and if not, move on to the next. > > I'm trying to figure out if there > is another way to use decorators for my scenario or is there another way of > achieving the same thing without using decorators and without bloating up > the code with alternative solution. > > Another way could be to use Metaclass to populate class with method upon > declaration but that presents quite a bit of "special" cruft which is more > than I have to do with decorators :) (but maybe it's all *necessary* ? ) > Your original question was "is decorator the right thing to use?" For this application, the answer is "no". It sounds like you are trying to force this particular to solution to your problem, but you are probably better off giving __getattr__ intercepting another look. -- Paul From alan.isaac at gmail.com Mon Sep 1 18:05:35 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Mon, 01 Sep 2008 22:05:35 GMT Subject: Py 2.6 changes In-Reply-To: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Now math has factorial: > http://docs.python.org/dev/library/math.html#math.factorial That's rather underdocumented. Does it really attempt exact calculation for arbitrary integers?? Is there any way to request a nice fast approximation for large integers (e.g., with Gosper's modification of Stirling's formula)? Alan Isaac From circularfunc at gmail.com Mon Sep 1 14:31:42 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 1 Sep 2008 11:31:42 -0700 (PDT) Subject: Getting an objetcs dict? Message-ID: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> I did nce(I think). class X X.__dict__() and ngot a dict of its variables. Now i get errors doing this. what am i doing wrong? From tchendrix at gmail.com Wed Sep 24 16:08:32 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Wed, 24 Sep 2008 13:08:32 -0700 (PDT) Subject: empty csv file attachments Message-ID: hi group. I'm new to python but a veteran at programming. This one has me stumped. I have a simple contact form which the user fills out. The email is sent to the site user as well and it is delivered with the content in the body of the email as well in nice order. I have modified my code to also send the content as a csv attachment. On the server, the file is perfectly generated with content. The attachment, however, is completely blank. Any ideas what that could be? My code snippet is shown below: if int(attachmenttype)==2 or int(attachmenttype)==3: for field in ctx.request.field_names(): if field=='last_name': myfilename=ctx.request.field_value(field)+'.txt' if myfilename=='': myfilename='tempfile.txt' mypath= mynewfilepath + '/' + myfilename f=open(mypath, 'w') mynewstring='' counter=0 for field in ctx.request.field_names(): if field != 'inquiry_required': mynewstring=mynewstring + field +',' if mynewstring[-1]==',': mynewstring=mynewstring[0:len(mynewstring)-1] f.write(mynewstring) f.write ('\n') mynewstring='' counter=1 for field in ctx.request.field_names(): fielddata=ctx.request.field_value(field) if counter==1: dummydata=0 else: mynewstring=mynewstring + '"' + fielddata.replace('"','') + '",' counter = counter + 1 if mynewstring[-1]==',': mynewstring=mynewstring[0:len(mynewstring)-1] f.write(mynewstring) f.write('\n') f.close attachments.append('/'.join((ctx.request.library, myfilename))) [snip... sends email just after this] any ideas? From marco.bizzarri at gmail.com Sat Sep 13 10:44:01 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 13 Sep 2008 16:44:01 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] Message-ID: <3f0d61c40809130744l48fe45a0x8c45972a071179ba@mail.gmail.com> On Sat, Sep 13, 2008 at 4:11 PM, Fredrik Lundh wrote: > Marco Bizzarri wrote: > >> class FolderInUse: > >> >> >> def true_for(self, archivefolder): >> return any([instance.forbid_to_close(archivefolder) for instance in >> self.core.active_outgoing_registration_instances()]) >> >> Is this any better? The true_for name does not satisfy me a lot... > > well, "true_for" is indeed pretty inscrutable, but I'm not sure that would > be the first thing I'd complain about in that verbose mess... "verbose mess". It is always frustrating when you do what you think is your best and you read that. Anyway: I'm here to learn, and, of course, part of it is to listen those who've been there much longer than you. So, thanks for your sincere evaluation, Fredrik :-). > (when you pick method names, keep in mind that the reader will see the > context, the instance, and the arguments at the same time as they see the > name. there's no need to use complete sentences; pick short short > descriptive names instead.) Maybe I'm looking at the wrong direction, right now. From the point of view of the FolderInUse clients, they will do: condition = FolderInUse(core) condition.true_for(folder) Is this too verbose? This is not a polemic statement, I'm really asking your opionion. The expression inside the true_for is indeed complex, and maybe I can simplify it; however, I'm deeply convinced that instance.forbid_to_close(folder) has some good points on it; I mean, once I read this kind of code, I can hope to understand it without looking at what forbid_to_close does. > > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From carsten.haese at gmail.com Tue Sep 30 13:39:05 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 30 Sep 2008 13:39:05 -0400 Subject: OS.SYSTEM ERROR !!! In-Reply-To: References: Message-ID: Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > > The executable would execute perfectly. > > > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > The executable file would start to execute until it would print an error > stating that it cannot use a (.dat) file, which is located under the > following directory: > > > C:\myprogramfolder\run\inputs\io\control.dat > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? The program (myprogram.exe) is not looking for C:\myprogramfolder\run\inputs\io\control.dat, it's looking for inputs/io/control.dat relative to its current working directory. That will only work if the current working directory of the program is C:\myprogramfolder\run. Is it? -- Carsten Haese http://informixdb.sourceforge.net From robert.kern at gmail.com Mon Sep 8 16:53:02 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Sep 2008 15:53:02 -0500 Subject: hashing an array - howto In-Reply-To: References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > John Machin: >> Consider this:>>> hash(123) == hash(123.0) == hash(123L) >> True > > Right... Can you explain me why Python designers have chosen to build > a hash() like that? Because that's the kind of hash that dicts expect. If two objects are equal (i.e. (x==y) is True), they need to have their hash values equal as well. In order to do a lookup into a dict, it will hash the key and search the table for a that hash value. If there are multiple keys with the same hash value, then the dict will compare the keys by value to find a match. Since (123==123.0==123L), they must also have the same hash value such that {123.0: 'got it'}[123] == 'got it' -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Mon Sep 15 17:24:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 23:24:06 +0200 Subject: Python Nautilus script In-Reply-To: References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> <6j80nvF1ttmfU1@mid.uni-berlin.de> Message-ID: <6j823mF1u6ivU1@mid.uni-berlin.de> Chris Rebert schrieb: > On Mon, Sep 15, 2008 at 2:00 PM, Diez B. Roggisch wrote: >>>>> It appears that's because HOSTNAME is not exported. >>>>> But in the case of Nautilus script, how to workaround this issue? >>> Alternatively, export the variable when you create it, in .bashrc or >>> wherever it is getting created. That's probably the Right Thing to >>> Do(tm) in this case. >> >> Certainly not, as the OP uses a network monitoring software called Nautilus >> - and that communicates state to subprocesses using environment variables. >> Nothing to do with .bashrc. > > Just to clarify, the OP is talking about Nautilus as in the GNOME file > manager, not some network monitor. Erm, yep - I confused that with Nagios. Please don't ask me why. The point stands though - .bashrc has nothing to do with that. Diez From ceball at users.sourceforge.net Thu Sep 11 16:12:52 2008 From: ceball at users.sourceforge.net (Chris) Date: Thu, 11 Sep 2008 20:12:52 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: <87k5diex3m.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic xemacs.org> writes: ... > [ You can use the capi-sig for questions like this; see > http://mail.python.org/mailman/listinfo/capi-sig ] Thanks, I had no idea about that. > PyObject_GetAttrString is convenient, but it creates a Python string > only so it can intern it (and in most cases throw away the freshly > created version). For maximum efficiency, pre-create the string > object using PyString_InternFromString, and use that with > PyObject_GetAttr. Yes, we'd thought of that too, but it doesn't seem to be an important factor compared to the actual attribute lookup. Thanks for the advice, Chris From gagsl-py2 at yahoo.com.ar Thu Sep 4 23:16:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 00:16:18 -0300 Subject: Tkinter Radio button on the second window References: Message-ID: En Thu, 04 Sep 2008 22:01:25 -0300, Dream escribi?: > The code create 2 windows. 2 radiobuttons are put on the second > window. A control variable "v" is binded to the 2 widgets. > But when I run the code, I found the control variable not binded > succsessfully: The second radiobutton was not selected by default; > Click ed each button always print 1. I don't know what is wrong. So I > need help.Thanks. > > from Tkinter import * > window1=Tk() > window2=Tk() Don't create more than one root Tk instance. Weird things happen, like this. If you need another, separate window, use a Toplevel widget. -- Gabriel Genellina From brad.at.school at gmail.com Tue Sep 23 16:16:31 2008 From: brad.at.school at gmail.com (brad.at.school at gmail.com) Date: Tue, 23 Sep 2008 13:16:31 -0700 (PDT) Subject: curses.setsyx()? References: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> Message-ID: <713190fc-e3a9-4a72-8bee-4fd3affcb531@c58g2000hsc.googlegroups.com> On Sep 22, 11:24?pm, Tim Roberts wrote: > linkmaster032... at gmail.com wrote: > >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: > >> On Sep 19, 1:24?am, Tim Roberts wrote: > > >> > linkmaster032... at gmail.com wrote: > > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > >> > >cursor. Any alternatives/solutions? > > >> > Did you call doupdate after? ?setsyx just manipulates the data structures. > >> > It takes a call to doupdate to force those changes to take effect visually. > >> > -- > >> > Tim Roberts, t... at probo.com > >> > Providenza & Boekelheide, Inc. > > >> I added it and it still doesn't work. This is what I'm doing when I > >> want to display the cursor and prepare it for input at 2,3: > > >> curses.echo() > >> curses.curs_set(1) > >> curses.setsyx(2,3) > >> curses.doupdate() > > >Any idea what's wrong? > > No. ?Are you able to post an entire sample that demonstrates the problem? > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. http://pastebin.com/m6413db1 Run that and press 'n' key. It is supposed to move the cursor to 2,3 and it doesn't. From sjmachin at lexicon.net Fri Sep 12 15:51:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Sep 2008 12:51:30 -0700 (PDT) Subject: book example confusion References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: On Sep 13, 5:36?am, byron wrote: > I am reading o'reilly's learning python (great book), but i came > across an example (pg 291, pdf) that I am not quite understanding the > reasoning for the author's explanation: > > if f1() or f2(): > > The author states that do to the nature of that expression, if f1() > returns True, f2() will not be evaluated.. which makes sense. His > quote: > > ? ? ? ? "Here, if f1 returns a true (or nonempty) value, Python will > never run f2." > > He then states: > > ? ? ? ? "To guarantee that both functions will be run, call them > before the 'or':" > > tmp1, tmp2 = f1(), f2() > if tmp1 or tmp2: > > Being that each function is an object, a name assignment to > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > the name is called.. so why would the latter example "run" both > functions as the author suggests? It's not a "name assignment". In effect it's doing this: tmp1 = f1() # get the RESULT of calling f1() tmp2 = f2() # likewise f2 if tmp1 or tmp2: # if result1 or result2 A (pointless) "name assignment") with the nil effect that you fear would look like this: tmp1, tmp2 = f1, f2 # Look, no parentheses after function names if tmp1() or tmp2(): HTH, John From xlebourd at gmail.com Wed Sep 3 11:25:04 2008 From: xlebourd at gmail.com (Xavier) Date: Wed, 3 Sep 2008 08:25:04 -0700 (PDT) Subject: Serial I/O problem with pywin32 ? References: Message-ID: I tried under Linux... same problem. So... it may comes from my little lines of code... or from my GPS. From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 11:00:59 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 17:00:59 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: <48dcf924$0$4653$426a74cc@news.free.fr> Patrick Mullen a ?crit : > Depending on the scale of the website I am making, how much I care > about editing it in the future, and how much I just want to get > something up, I will occasionally use php. And I am a self confessed > php hater :) But it's generally the fastest way I know to get > something up. So even terrible languages can have their uses! Sorry but I fail to see how it relates to the current thread ??? From castironpi at gmail.com Sat Sep 6 00:57:38 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 5 Sep 2008 21:57:38 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> Message-ID: <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> On Sep 5, 9:20?pm, "Manu Hack" wrote: > On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: > > On Sep 5, 3:28 am, "Manu Hack" wrote: > >> On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: > >> > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: > >> >> David C. Ullrich: > > >> >> > At least in mathematics, the sum of the elements of > >> >> > the empty set _is_ 0, while the maximum element of the > >> >> > empty set is undefined. > > >> >> What do you think about my idea of adding that 'default' argument to > >> >> the max()/min() functions? > > >> >> Bye, > >> >> bearophile > > >> > For max and min, why can't you just add your argument to the set > >> > itself? > > >> > The reason max([]) is undefined is that max( S ) is in S. > > >> It makes sense. > > >> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. > > >> It doesn't make sense to me. ?What do you set x to? > > > For all x. > > But then how can you conclude sum([]) = 0 from there? ?It's way far > from obvious. You can define sum([a1,a2,...,aN]) recursively as sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) "X", then subtract aN. sum([a1,a2,...a(N-1)])+aN=X sum([a1,a2,...a(N-1)])+aN-aN=X-aN For N=2, we have: sum([a1,a2])=X sum([a1,a2])-a2=X-a2 sum([a1,a2])-a2-a1=X-a2-a1 Since X= a1+ a2, replace X. sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 Or, sum([a1,a2])-a2-a1=0 Apply the recursive definition: sum([a1])+a2-a2-a1=0 And again: sum([])+a1+a2-a2-a1=0 And we have: sum([])=0. From adityashukla1983 at gmail.com Sat Sep 27 16:44:19 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sat, 27 Sep 2008 15:44:19 -0500 Subject: File modifications Message-ID: <73045cca0809271344k68ce6bb7i403ac15d5770b06f@mail.gmail.com> Hello folks , I have a file like this /T_0_size=105((-bin-ulockmgr_server:0.99[&&NHX:C=0.195.0],(((-bin-hostname:0.00 [&&NHX:C=200.0.0], (-bin-dnsdomainname:0.00[&&NHX:C=200.0.0],(-bin-domainname:0.00[&&NHX:C=200.0.0],(-bin-nisdomainname:0.00[&&NHX:C=200.0.0],-bin-ypdomainname:0.00[&&NHX:C=200.0.0]):0.00):0.00):0.00):0.98 ,(-bin-iptables-xml:0.97[&&NHX:C=0.183.0],(-bin-dbus-send:0.78[&&NHX:C=0.94.0],-bin-dbus-monitor:0.78[&&NHX:C=0.94.0]):0.97):0.98):0.99. I wanna get the file in this format ((-bin-ulockmgr_server:0.99,(((-bin-hostname:0.00,(-bin-dnsdomainname:0.00,(-bin-domainname:0.00,(-bin-nisdomainname:0.00,-bin-ypdomainname:0.00):0.00):0.00):0.00):0.98 ,(-bin-iptables-xml:0.97,(-bin-dbus-send:0.78,-bin-dbus-monitor:0.78):0.97):0.98):0.99 ie , remove /T_0_size , [&&NHC:C=0.195.0] , [&&NHX:C=200.0.0] and so on , how should i handle this after reading the file? Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From almar.klein at gmail.com Sat Sep 20 16:12:44 2008 From: almar.klein at gmail.com (Almar Klein) Date: Sat, 20 Sep 2008 22:12:44 +0200 Subject: matplotlib in interactive mode locks when run from subprocess In-Reply-To: References: Message-ID: I think my question was not very clear. I narrowed the problem down to a reconstructable small example, consisting of a python script (a very simple interpreter) and three lines to execute in it: ========== start simple interpreter file ====== import os import sys import time def run(): while True: # read a line of text, the thread is stuck here untill a \n is # fed to the stream. time.sleep(0.1) line = "" try: line = sys.stdin.readline() except Exception, why: sys.stdout.wite(why.message+"\n") if line: try: code = compile(line,"","exec") exec(code) except Exception, why: sys.stderr.write(why.message) sys.stderr.write(">>> ") if __name__ == "__main__": run() ========== end of file ============== Now I run this file (by double clicking it) and I get a prompt. The three lines I type in are: import matplotlib.pylab as pl pl.ion() #interactive mode on pl.plot([1,2,3],[4,6,5]) This produces a tk window, but it's unresponsive. The process does have 5 threads, so matplotlib managed to create the threads, but it seems as if they're blocked. When I run the three lines of code in a normal python shell, I get the proper results: a responsive figure (I can zoom and pan) and my shell is still responsive too. I am in the dark why this does not work. Any thoughts anyone? I've been busy all day trying to get this right, with hardly any progress... :( Almar PS: I run windows xp, my matplotlibrc file has the backend: TkAgg, interactive: True 2008/9/18 Almar Klein > Hi, > > In wxpython, I made an interactive shell, which creates a remote python > subprocess > to do the interpreting. Communication is done via a pipe. The idea is that > the python > session is an actual process separate from the GUI, which has some > advantages, > like I can have multiple such shells in my application, and I can kill them > without > worrying that my wx app will crash. > > To do this I use the wx.Process class, which allows asynchronous > communication with > the remote process. > > This all works really, I will also launch wxpython apps. So I was quite > happy, untill I tried > doing some plotting with matplotlib (in TkAgg backend). The problem is that > the process > becomes unresponsive when I plot something (No prompt is written to the > stdout/stderr). > (more details below) > > I don't know much about creating subprocess and how they are different from > a normal > process. So can anyone offer some help as to what the problem might be? > > Thanks in advance, > Almar > > To get to the details: > - When I start a process with command "python -u -i" > -- When interactive mode is off, the whole process becomes unresponsive > when doing > pylab.show() > -- When interactive mode in on, on doing pylab.plot(), a figure appears, > which I can > zoom etc., but the process is now stuck, also after closing the figure > > - When I start a process with command > "python -u -c 'import code;code.interact(readfunc=raw_input)'" (This is > how Pype does it). > -- When interactive mode is off, the figures show when doing pylab.show() > and the process > behaves as normal after closing the figure(s). > -- When interactive mode in on, on doing pylab.plot(), a figure appears, > but most of the time > it is not drawn and emmediately unresponsive, just like the process > itself. > > I have also tried an asynchronous Popen recipe by Joshiah Carlson I found > on > activestate. And I made my own process class using > win32process.CreateProcess. > Both alternatives to wx.Process resulted in the same sympoms. > > Oh, and I run windows. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From afriere at yahoo.co.uk Wed Sep 24 05:07:58 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 24 Sep 2008 02:07:58 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 24, 9:52 am, Neal Becker wrote: > In hindsight, I am disappointed with the choice of conditional syntax. I know it's too late to change. The problem is > > y = some thing or other if x else something_else > > When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). Particularly if 'some thing or other' is long or complicated. The struggle to get a conditional operator was a long and bitter, so in the first place we should be glad we aren't writing "y = (conditional and [p] or [q])[0] anymore. Since it was but grudgingly bestowed I thought BDFL had chosen this particular syntax just to be difficult. However since using it for a while, I am surprised how natural it is to use and read. A canonical use of the conditional operator is in pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). For this and similar short uses, where the regular if statement is an annoyance this syntax if else works nicely. More complicated conditionals or cases are probably better handled by an if statement. This syntax is also probably not the best for nested conditionals. The latter, however, is probably feature rather than bug. From sh006d3592 at blueyonder.co.uk Sun Sep 14 16:46:08 2008 From: sh006d3592 at blueyonder.co.uk (Stephen Horne) Date: Sun, 14 Sep 2008 21:46:08 +0100 Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> Message-ID: On 14 Sep 2008 20:25:18 GMT, Steven D'Aprano wrote: >"The fact that many languages disallow instantiation of abstract types >(and force subtypes to implement all needed functionality) further >ensures program correctness." > >http://en.wikipedia.org/wiki/Abstract_base_class > >but I don't see how that follows (except possibly in very special cases). >Given that the set of instances of class B is empty, how does that help >you know that B.method is correct? That's the point - to be certain that the set of instances of class B really is empty. As for B.method, it's correctness isn't purely determined by the code of the method itself. It will usually depend on the object being in a self-consistent state. It's often impossible for an instance of an abstract base to have a self-consistent state. Therefore, it's better to guarantee that no instances can be accidentally created. OTOH, this argument is often an over-pedantic technicality. You can't eliminate all errors from code by making the language stricter. Instantiating an abstract class isn't a very common error in my experience. Whether detecting it is a priority depends on what you're doing. From castironpi at gmail.com Fri Sep 12 02:53:02 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 23:53:02 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> Message-ID: <99ae2c42-695b-4ed8-a639-faf41746898c@c65g2000hsa.googlegroups.com> On Sep 12, 1:30?am, Steven D'Aprano wrote: > On Thu, 11 Sep 2008 22:40:01 -0700, Dennis Lee Bieber wrote: > > On 12 Sep 2008 03:37:51 GMT, Steven D'Aprano > > declaimed the following in > > comp.lang.python: > > >> I'm pretty sure you're wrong. XML can be used for serialization, but > >> that doesn't mean it is only sequential data. XML is suitable for > >> hierarchical data too. To quote Wikipedia: > > > ? ?There is a difference between the format of the data content, and > > the processing of that data... Regardless of the content, one > > essentially has to process the XML /file/ sequentially, and translate > > into an in-memory model that allows for accessing said data. To reach > > the nth subelement of the mth element requires reading all 1..m-1 > > elements, followed by all 1..n-1 subelements in m. Modifying any element > > requires rewriting the entire file. > > Which is why I previously said that XML was not well suited for random > access. > > I think we're starting to be sucked into a vortex of obtuse and opaque > communication. We agree that XML can store hierarchical data, and that it > has to be read and written sequentially, and that whatever the merits of > castironpi's software, his original use-case of random access to a 4GB > XML file isn't workable. Yes? > > -- > Steven By 'isn't workable' do you mean, "no one ever uses 4GB of XML", or "no one ever uses 4GB or hierarchical data period"? From michael.pearmain at tangozebra.com Mon Sep 8 11:14:01 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 8 Sep 2008 08:14:01 -0700 (PDT) Subject: Dictionaries and loops References: <48c52c54$0$16982$426a74cc@news.free.fr> <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> <48c53322$0$3460$426a74cc@news.free.fr> Message-ID: <069dc97f-9a6f-4adf-9667-c02a352836b3@b1g2000hsg.googlegroups.com> Thanks for the solution above, The raw data looked like User-ID,COUNTS 576460840144207854,6 576460821700280307,2 576460783848259584,1 576460809027715074,3 576460825909089607,1 576460817407934470,1 and i used CSV_INPUT1 = "C:/Example work/Attr_model/Activity_test.csv" fin1 = open(CSV_INPUT1, "rb") reader1 = csv.DictReader((fin1), [], delimiter=",") for row in reader1: print row with the following outcome. {None: ['User-ID', 'COUNTS']} {None: ['576460840144207854', '6']} {None: ['576460821700280307', '2']} {None: ['576460783848259584', '1']} {None: ['576460809027715074', '3']} {None: ['576460825909089607', '1']} So i can see csv.reader is what i should have been using Thanks for the help From Lie.1296 at gmail.com Wed Sep 17 12:18:22 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 17 Sep 2008 09:18:22 -0700 (PDT) Subject: translating ascii to binary References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> Message-ID: On Sep 17, 11:02?pm, Canned wrote: > Hi, > I'm trying to write a class that can convert ascii to binary and vice > versa. I write my class based on this function I've found on internet > > > > > > > def ascii_to_bin(char): > > ascii = ord(char) > > bin = [] > > > while (ascii > 0): > > if (ascii & 1) == 1: > > bin.append("1") > > else: > > bin.append("0") > > ascii = ascii >> 1 > > > bin.reverse() > > binary = "".join(bin) > > zerofix = (8 - len(binary)) * '0' > > > return zerofix + binary > > > some_string = 'Time to go now, Rummy?' > > > binary = [] > > for char in some_string: > > binary.append(ascii_to_bin(char)) > > > print binary > > print " ".join(binary) > > That works perfectly, but when I try to implement it in my own class it > gives me alot of headache, also because I'm totally new to the language. > It work only with one character at a time, and if I give a string it > just give some weird result. > > > > > > > if len(sys.argv) < 2: > > ? ? ? ? print 'usage:', os.path.basename(sys.argv[0]), 'text' > > ? ? ? ? sys.exit() > > > class Converterab: > > ? ? ? ? ''' > > ? ? ? ? Ascii-binary converter. > > ? ? ? ? ''' > > ? ? ? ? def __init__(self, string): > > ? ? ? ? ? ? ? ? self.string = string > > > ? ? ? ? def ascii_to_bin(self): > > ? ? ? ? ? ? ? ? bindump = [] > > ? ? ? ? ? ? ? ? for char in self.string: > > ? ? ? ? ? ? ? ? ? ? ? ? bin = ord(char) > > ? ? ? ? ? ? ? ? ? ? ? ? while bin > 0: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (bin & 1) == 1: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bindump.append("1") > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bindump.append("0") > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bin = bin >> 1 > > ? ? ? ? ? ? ? ? bindump.reverse() > > ? ? ? ? ? ? ? ? print bindump ? # Debug tool, delete this > > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? Zero fix in bindump > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? bindump.insert(0, "0") > > ? ? ? ? ? ? ? ? count = 0 > > ? ? ? ? ? ? ? ? pos = 0 > > ? ? ? ? ? ? ? ? for dg in bindump: > > ? ? ? ? ? ? ? ? ? ? ? ? count += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? pos += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? if count == 8: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bindump.insert(pos, "0") > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? count = 0 > > ? ? ? ? ? ? ? ? bindump.pop() > > ? ? ? ? ? ? ? ? print bindump ? # Debug tool, delete this, the best result so far > > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? Reversing array per byte > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? final = [] > > ? ? ? ? ? ? ? ? pos -= pos ? ? ?# Set pos to 0 again > > ? ? ? ? ? ? ? ? while len(bindump) != 0: > > ? ? ? ? ? ? ? ? ? ? ? ? print count ? ? # Debug tool, delete this, this is weird, start at 1, I expected 0 > > ? ? ? ? ? ? ? ? ? ? ? ? count += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? if count > 8: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pos += 8 > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? count -= count > > ? ? ? ? ? ? ? ? ? ? ? ? final.insert(pos, bindump.pop()) > > ? ? ? ? ? ? ? ? ? ? ? ? print final ? ? # Debug tool, delete this > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? for ar in bindump: > > ? ? ? ? ? ? ? ? ? ? ? ? count += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? if (count < 8): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? final.insert(pos, bindump.pop()) > > ? ? ? ? ? ? ? ? ? ? ? ? elif (count >= 8): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pos = count > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? final.insert(pos, bindump.pop()) > > ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? final.insert(pos, bindump.pop()) > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? final.insert(0, final.pop()) > > > ? ? ? ? ? ? ? ? binary = "".join(final) > > ? ? ? ? ? ? ? ? return binary > > > result = Converterab(sys.argv[1]) > > > print "Char : ", result.ascii_to_bin() > > The problem start at "Reversing array per byte". That block should > reversing the array from 'bindump' and copy it to 'final' per 8 items, > e.g. a = ['0', '1', '0', '1', '0', '1', '0', '1', '2', '1', '2', '1', > '2', '1', '2', '1', '3', '2', '3', '2', '3', '2', '3', '2'] > b = ['3', '2', '3', '2', '3', '2', '3', '2', '2', '1', '2', '1', '2', > '1', '2', '1', '0', '1', '0', '1', '0', '1', '0', '1'] > > Any advice about this matter would be very appreciated. > Thanks in advance. It'd be easier to make a one-char version of ascii2bin then make the string version based on the one-char version. From circularfunc at yahoo.se Tue Sep 16 08:01:25 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 05:01:25 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? Message-ID: I'm trying to switch to using emacs for python. The interpreter and python-mode works but I can't load the file I'm editing into the interpreter. im not sure if c-c c-l is supposed to do that but it complains "no module xxxx" . what needs to be in my emacs-path? what needs to be in my windows path? I have c:/python25. adding that tot he path ads everything inside python25? i have my programs in: c:/python25/progs/ in which i have /progdir/someprog.py for example From dudeja.rajat at gmail.com Sat Sep 6 15:22:47 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 6 Sep 2008 20:22:47 +0100 Subject: How to bring subprocess to the foreground? In-Reply-To: <1563bbfd-6219-4719-940f-91cd84c419e5@l42g2000hsc.googlegroups.com> References: <6ifhg2Fq24n6U1@mid.uni-berlin.de> <1563bbfd-6219-4719-940f-91cd84c419e5@l42g2000hsc.googlegroups.com> Message-ID: On Sat, Sep 6, 2008 at 6:53 PM, Paul Boddie wrote: > On 6 Sep, 17:58, dudeja.ra... at gmail.com wrote: >> >> I though of displayin an information message on the screen through >> tkMessageBox while the subprocess is running, I did it using: >> >> try: >> testing = subprocess.Popen([batchFilePath], \ >> shell = True) >> >> retCode = testing.wait() > > Note that you wait for the process to finish here... > >> tkMessageBox._show("Test Harness execution", \ >> icon = 'info', \ >> message="Testing %s in progress..." % libName) > > ...and that you show a message about the process running *after* > waiting until it isn't running any more. > >> except: >> tkMessageBox._show("Error", \ >> type='ok', icon='error', \ >> message="Error executing %s Test >> Harness" % libName) >> return None >> else: >> print retCode >> >> But the message is never displayed. Please suggest if there is >> something wrong with this code > > I think you should first show your message, *then* wait for the > process to finish. > > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > Such a silly mistake I'm committing. Thanks a ton. -- Regrads, Rajat From castironpi at gmail.com Sat Sep 27 08:39:59 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 05:39:59 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <00ee05ca$0$20666$c3e8da3@news.astraweb.com> Message-ID: <1a7184f3-c71e-49b7-a8f8-f141705f3573@l42g2000hsc.googlegroups.com> On Sep 27, 5:33?am, Steven D'Aprano wrote: > On Sat, 27 Sep 2008 18:20:17 +1000, Ben Finney wrote: > > Steven D'Aprano writes: > > >> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: > >> > An ordinary singleton is instantiating the class multiple times yet > >> > returning the same instance object; a class singleton is simply using > >> > the class directly (like a module). > > > Where is this "class singleton" terminology from? > > I don't know. Googling on it brings up an awful lot of C++ and Java > source code for regular Singletons. Perhaps Aahz can shed some light on > it? [snip] > In my example, the instance doesn't matter. I could write it like this: > > >>> class CallableAppendor(object): > > ... ? ? thing = (0, 1, 2) > ... ? ? @classmethod > ... ? ? def __call__(cls, *args): > ... ? ? ? ? return len(args + cls.thing) > ...>>> appendor = CallableAppendor() > >>> appendor.thing = (1, 2, 3, 4, 5, 6, 7, 8) > >>> appendor(1, 2, 4, 8, 16) > 8 > >>> CallableAppendor.__call__(1,2,4,8,16) > > 8 > > but what's the purpose of instantiating the class? I've used them (class singletons, adopting the term) as a Globals namespace, but only to the end of tidying. It makes it easy to reassign immutables. It is too bad 'CallableAppendor.__call__(1,2,4,8,16)' doesn't work as expected. That is, 'CallableAppendor(1,2,4,8,16)' dosen't call '__call__'. I have a workaround, which may be just what you're looking for. >>> class A(type): ... def __call__( self, *ar ): ... print 'call', self, ar ... >>> class B(object): ... __metaclass__= A ... >>> B(3) call (3,) Overriding the __call__ method of 'type' has the effect of giving you a static __call__ method on a class-- a method which doesn't need an instance to call. Your behavior may be counterintuitive though, to someone who wants to instantiate 'B', in this case, and proceed like a normal object. That is, they want to call a generic class and use it, and also expect instances of B to behave as B. You can't have both, so either return B from B.__new__, or, to instantiate B, take the long way and call B.__new__ directly. >>> B.__new__(B) <__main__.B object at 0x009FDB70> Has anyone stepped through the C code to find out when the decision is made to call which function, B.__new__ or A.__call__, when B is called? I'm happy that overriding type.__call__ produced the intended results; it's always nice when things go right. From prologic at shortcircuit.net.au Thu Sep 18 20:34:42 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Sep 2008 10:34:42 +1000 Subject: Twisted vs Python Sockets In-Reply-To: References: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> Message-ID: On Fri, Sep 19, 2008 at 6:24 AM, Fredrik Lundh wrote: > James Matthews wrote: > >> I am wondering what are the major points of twisted over regular python >> sockets. I am looking to write a TCP server and want to know the pros can >> cons of using one over the other. > > Twisted is a communication framework with lots of ready-made components: > > http://twistedmatrix.com/trac/wiki/TwistedAdvantage > > Regular sockets are, well, regular sockets. No more, no less. There is also one more alternative: pymills - current version 3.4 It has a different design goal to twisted and is in no competition with twisted, however provides: * An event framework * A component driven architecture * A set of components including: * TCPServer, TCPClient * UDPServer, UDPClient * Some protocol components: * IRC * HTTP * SMTP * Some other components: * Environment * Logger * Stdin * Config A simple EchoServer is as simple as: http://hg.shortcircuit.net.au/index.wsgi/pymills/file/4247696a5633/examples/net/echoserer.py If anyone is interested in trying this library out, feel free. I recommend you use the latest development branch available via Mercurial at: http://hg.shortcircuit.net.au/pymills/ hg clone http://hg.shortcircuit.net.au/pymills/ If you have any questions, don't hesitate to ask me. Enjoy :) cheers James -- -- -- "Problems are solved by method" From hv at tbz-pariv.de Fri Sep 12 03:47:42 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Fri, 12 Sep 2008 09:47:42 +0200 Subject: Better error message on recursive import In-Reply-To: <6isunqF6v3jU2@mid.uni-berlin.de> References: <6isb2mF9scaU1@mid.individual.net> <6isunqF6v3jU2@mid.uni-berlin.de> Message-ID: <6iul4uFkaviU1@mid.individual.net> Hi, > Can you give an example of such a recursive import you want the special > exception be raised? ===> cat one.py from two import testtwo def testone(): print "one" ===> cat two.py import one def testtwo(): print "two" ===> python one.py Traceback (most recent call last): File "one.py", line 1, in from two import testtwo File "/mnt/home/tguettler/tmp/rec/two.py", line 1, in import one File "/mnt/home/tguettler/tmp/rec/one.py", line 1, in from two import testtwo ImportError: cannot import name testtwo -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From kaerbuhez at gmail.com Mon Sep 15 17:26:18 2008 From: kaerbuhez at gmail.com (kaer) Date: Mon, 15 Sep 2008 14:26:18 -0700 (PDT) Subject: Python Nautilus script References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> Message-ID: <99dc3fb0-f4ea-4b3e-926c-ce3462cd9973@b1g2000hsg.googlegroups.com> On 15 sep, 21:46, Michel Leunen wrote: > > But in the case of Nautilus script, how to workaround this issue? > > -- > Michel Leunen > http://linux.leunen.com I don't have that issue. This script works as expected: --------------- #! /usr/bin/python # -*- coding: utf8 -*- import os, sys #NAUTILUS_SCRIPT_SELECTED_FILE_PATHS : chemins des fichiers s?lectionn?s s?par?s par des retours ? la ligne (newline) (uniquement pour les fichiers locaux) #NAUTILUS_SCRIPT_SELECTED_URIS : URIs des fichiers s?lectionn?s s?par?s par des retours ? la ligne (newline) #NAUTILUS_SCRIPT_CURRENT_URI : URI de l'emplacement actuel #NAUTILUS_SCRIPT_WINDOW_GEOMETRY : position et taille de la fen?tre actuelle KEYS=("NAUTILUS_SCRIPT_SELECTED_FILE_PATHS", "NAUTILUS_SCRIPT_SELECTED_URIS", "NAUTILUS_SCRIPT_CURRENT_URI", "NAUTILUS_SCRIPT_WINDOW_GEOMETRY") ft=open("/home/kaer/stupid.txt", "w") for key_value in [(key, os.environ.get(key, 'NOT FOUND')) for key in KEYS]: ft.write("env(%s): %s\n" % key_value) file_names=sys.argv[1:] for index, file_name in enumerate(file_names): ft.write("%s: [%s]\n" % (index, file_name)) if os.path.isfile(file_name): os.rename(file_name, '%03d-%s' % (index+1, file_name)) ft.close() --------------- I selected 3 files (created on purpose) in Nautilus. Those files where renamed and stupid.txt created with that content: --------------- env(NAUTILUS_SCRIPT_SELECTED_FILE_PATHS): /home/kaer/baz /home/kaer/bar /home/kaer/foo env(NAUTILUS_SCRIPT_SELECTED_URIS): file:///home/kaer/baz file:///home/kaer/bar file:///home/kaer/foo env(NAUTILUS_SCRIPT_CURRENT_URI): file:///home/kaer env(NAUTILUS_SCRIPT_WINDOW_GEOMETRY): 1280x885+0+25 0: [baz] 1: [bar] 2: [foo] --------------- You can as well use sys.argv[1:] that will give you the list of selected files. Hope that helps. From bearophileHUGS at lycos.com Sun Sep 28 18:19:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 28 Sep 2008 15:19:21 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: <81bc4138-5179-4b67-a15c-0d663c498af4@k37g2000hsf.googlegroups.com> Tim Chase: > I suspect that the zfill responses don't have the property of equally > distributed "randomness", as the first digit may more likely be a zero. This code I have shown before: str(randrange(100000)).zfill(5) If the numbers are equally distributed in [0, 99999], then the leading zeros have the correct distribution. A little test program for you: from string import digits from random import choice, randrange from collections import defaultdict def main(): N = 1000000 freqs1 = defaultdict(int) for i in xrange(N): n = "".join(choice(digits) for d in xrange(5)) freqs1[n[0]] += 1 print [freqs1[str(i)] for i in xrange(10)] freqs2 = defaultdict(int) for i in xrange(N): n = str(randrange(100000)).zfill(5) freqs2[n[0]] += 1 print [freqs2[str(i)] for i in xrange(10)] import psyco; psyco.full() main() The output: [100153, 99561, 99683, 100297, 99938, 100162, 99738, 100379, 100398, 99691] [99734, 100153, 100091, 100683, 99580, 99676, 99671, 100131, 100102, 100179] Of course with a bit of math you can also demonstrate it :-) Bye, bearophile From bj_666 at gmx.net Sun Sep 28 02:05:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Sep 2008 06:05:11 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <6k8l4nF6jbmtU1@mid.uni-berlin.de> On Sat, 27 Sep 2008 22:37:09 -0700, est wrote: > The problem is, why the f**k set ASCII encoding to range(128) ???????? Because that's how ASCII is defined. ASCII is a 7-bit code. > while str() is internally byte array it should be handled in range(256) > !!!!!!!!!! Yes `str` can handle that, but that's not the point. The point is how to translate the contents of a `unicode` object into that range. There are many different possibilities and Python refuses to guess and tries the lowest common denominator -- ASCII -- instead. > I now spending 60% of my developing time dealing with ASCII range(128) > errors. It was PAIN!!!!!! > > Please fix this issue. > > http://bugs.python.org/issue3648 > > Please. The issue was closed as 'invalid'. Dealing with Unicode can be a pain and frustrating, but that's not a Python problem, it's the subject itself that needs some thoughts. If you think this through, the relationship between characters, encodings, and bytes, and stop dreaming of a magic solution that works without dealing with this stuff explicitly, the pain will go away -- or ease at least. Ciao, Marc 'BlackJack' Rintsch From seandavi at gmail.com Tue Sep 23 11:39:45 2008 From: seandavi at gmail.com (Sean Davis) Date: Tue, 23 Sep 2008 08:39:45 -0700 (PDT) Subject: lxml and adding a stylesheet Message-ID: I have an xml document and simply need to add an xml-stylesheet to it. I am using lxml to parse the xml document and then would like to insert the xml-stylesheet tag using the etree api. Any suggestions? Thanks, Sean From __peter__ at web.de Thu Sep 25 04:47:10 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2008 10:47:10 +0200 Subject: python sorting 2dim. array ? References: <9684e81b-df99-4d95-99f9-8345c125b69b@d77g2000hsb.googlegroups.com> Message-ID: fredo66 at fulladsl.be wrote: > hello, > Can someone help me with this: > I have a array like this > > list[rowindex][colomindex] > > where rows are the records and colom the fields. If I use the .sort() > method on 'list' the data is sorted on the items of the first colom. > But I want to sort on the second colom as first (and as second > sortfield the first colom). > > What is the shortest code for this pls ? > > (all fields are text value, first colom is name, second category) >>> items = [(1,2), (2,2), (2,1)] >>> items.sort(lambda x, y: cmp(x[1::-1], y[1::-1])) >>> items [(2, 1), (1, 2), (2, 2)] If you want something more efficient, see http://www.python.org/doc/faq/programming/#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python Peter From paul at boddie.org.uk Thu Sep 18 06:34:12 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Sep 2008 03:34:12 -0700 (PDT) Subject: Python for the iPhone? References: Message-ID: <6766f4fc-20a1-4aab-9599-a7a2080fcb06@m3g2000hsc.googlegroups.com> On 17 Sep, 11:54, s... at pobox.com wrote: > Anybody tried this port of Python to the iPhone? > > ? ?http://www.modmyi.com/nativeapps/python-v251/ > ? ?http://iphone.natetrue.com/ > > Hasn't been updated since July 2007. ?Maybe just a proof-of-concept? ?I'm > guessing it involves jailbreaking the phone. There's a very brief summary of iPhone drawbacks with respect to openness in this very interesting presentation from PyCon UK: http://freshfoo.com/presentations/PyCon_UK-2008/slides/ Although it probably doesn't tell you anything you didn't already know about Apple's disdain for people running "unauthorised" software on the iPhone, I think the Python involvement in Openmoko is very interesting and deserving of wider attention, especially amongst those considering getting a mobile device for its Python capabilities. Paul From tgrav at me.com Thu Sep 18 13:06:40 2008 From: tgrav at me.com (Tommy Grav) Date: Thu, 18 Sep 2008 13:06:40 -0400 Subject: Cython dynamic library problem In-Reply-To: <8763otl8ea.fsf@merkury.smsnet.pl> References: <8763otl8ea.fsf@merkury.smsnet.pl> Message-ID: <410690AD-DF18-4AAF-A0DB-4B241673AD3D@me.com> On Sep 18, 2008, at 12:35 PM, Rob Wolfe wrote: > > I would try to use `distutils` because this package is much wiser > than me and knows all necessary switches for gcc. ;) That worked! Thanks Cheers Tommy From max at alcyone.com Sun Sep 21 22:00:18 2008 From: max at alcyone.com (Erik Max Francis) Date: Sun, 21 Sep 2008 19:00:18 -0700 Subject: appending * to glob returns files with '*' !! In-Reply-To: References: Message-ID: John [H2O] wrote: > I have a glob.glob search: > > searchstring = os.path.join('path'+'EN*') > files = glob.glob(searchstring) > for f in files: > print f > > > ___ > This returns some files: > EN082333 > EN092334 > EN* > > My routine cannot handle the '*' and it should'nt be returned anyway? :-/ > > A bug? No, it means you actually have a file named 'EN*' in the directory. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Many would be cowards if they had courage enough. -- Thomas Fuller From badmuthahubbard at gmail.com Tue Sep 2 06:03:15 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Tue, 2 Sep 2008 13:03:15 +0300 Subject: Tkinter popup menu In-Reply-To: <873akqj73o.fsf@gmail.com> References: <873akqj73o.fsf@gmail.com> Message-ID: <8200bab70809020303n344c97b4udcd06be9cf91c79b@mail.gmail.com> On Thu, Aug 28, 2008 at 3:50 AM, Carl wrote: > "Chuckk Hubbard" writes: > >> Right-click popup menu. None of the options that come from the >> cascades can be selected with the mouse. If you select a submenu with >> the mouse and then use the arrow keys and enter key to select an >> option, it works, but the menu remains on the canvas. If you click >> the option with the mouse, the menu disappears but the function >> doesn't get called. >> Can someone tell me why? >> >> -Chuckk >> >> -- >> http://www.badmuthahubbard.com > > Try creating the "main" popup menu before the sub-menus, and when > instantiating the sub-menus, pass the main menu as the "master" > instead of "self.myparent": Thanks Carl, that indeed did it. -Chuckk > > Hope that helps. > Carl. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.badmuthahubbard.com From research at johnohagan.com Tue Sep 30 04:58:15 2008 From: research at johnohagan.com (John O'Hagan) Date: Tue, 30 Sep 2008 08:58:15 +0000 Subject: How best to pass arbitrary parameters from one function to another Message-ID: <200809300858.15923.research@johnohagan.com> Hi Pythonistas, I'm looking for the best way to pass an arbitrary number and type of variables created by one function to another. They can't be global because they may have different values each time they are used in the second function. So far I'm trying to do something like this: def process_args( [list, of, command-line, arguments] ): do stuff return {dictionary : of, local : variables } def main_function( **kwargs ): do stuff return result kw1 = process_args( [some, list] ) kw2 = process_args( [a, different, list] ) for i in main_function( **kw1 ): kw2[ var1 ] = i kw2[ var2 ] = len( i ) for j in main_function(**kw2): print j This only seems to work if I specify a default value for every possible parameter of main_function and also for any others which may be passed to it, which is a bit tedious because there are very many of them but only a few are used in any given execution of the program. Is there a better way to do it? Or have I simply made an error? Regards and thanks, John O'Hagan From michele.simionato at gmail.com Sat Sep 13 07:43:42 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 13 Sep 2008 04:43:42 -0700 (PDT) Subject: Injecting new names into the above frame References: <57uyk.101$fD.22@flpi145.ffdc.sbc.com> Message-ID: <31db78a6-050d-42f5-8c06-7b3418492e1c@73g2000hsx.googlegroups.com> On Sep 13, 1:35?pm, Peter Waller wrote: > This makes me want to ask: is it difficult to modify a function's > code? No, it is not difficult. Look at the byteplay module: it makes possible all kinds of dirty hacks. From google at mrabarnett.plus.com Mon Sep 22 19:55:25 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Sep 2008 16:55:25 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <00e816f4$0$20303$c3e8da3@news.astraweb.com> <6602abad-3c12-4c0c-b41d-95f79cebdc31@y21g2000hsf.googlegroups.com> Message-ID: On Sep 22, 11:46?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 22, 5:32?pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: > > > On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano > > >> But that's precisely what I want to avoid: I don't want the objects to > > >> ?share *any* state, not even their class. I'm not trying for a Borg or > > >> ?Singleton: the user can call the factory as many times as they want, > > >> ?but the objects returned shouldn't share any state. I don't know if > > >> ?what I want has a name. Judging from people's reactions, I'd say > > >> ?probably not. > > > > Snce when are "users" ever involved > > > in programming problems or programming languages ? > > > What an astounding question. > > > Consider a class. There are the programmers who write the class, and > > there are the programmers (possibly the same people, but not necessarily) > > who use the class. The second set of people, the programmers who use the > > class, are *users* of the class. What else would they be? > > > -- > > Steven > > Usegrammers? And professionals are programmers, amateurs are amgrammers and newbies are newgrammers? :-) From gtitus_ at _wanadoo.fr Tue Sep 30 17:10:35 2008 From: gtitus_ at _wanadoo.fr (marc) Date: Tue, 30 Sep 2008 23:10:35 +0200 Subject: pylab without X11 In-Reply-To: References: Message-ID: <48e295c3$0$885$ba4acef3@news.orange.fr> This may help ... or not ( 2nd part ) try not to do pylab.figure() in your script: pylab.plot, or pylab.imshow or whatever you want to use then savefig("myFigure.png") for example do not use show() in my case ( with the WXAgg backend ), it works, it generates the png file Marc Willem-Jan Vriend a ?crit : > I want to use pylab (matplotlib) on a machine without X11. I'm trying to > generate onthefly graphics for an apache2 web service, so they do not > have to be displayed on this machine ! > > When i do > pylab.figure() > I get the error > TclError: couldn't connect to display ":0.0" > > I tried setting the DISPLAY environment variable to "", ":0.0" but I got > the same error message. > > Any help is very much appreciated. From bedouglas at earthlink.net Mon Sep 1 23:35:47 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 1 Sep 2008 20:35:47 -0700 Subject: python mechanize/libxml2dom question Message-ID: <108b01c90cac$fe079db0$0301a8c0@tmesa.com> hi... i've got the following situation, with the following test url: "http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#". i can generate a list of the tables i want for the courses on the page. however, when i try to create the xpath query, and plug it into the xpath within python, i'm missing something. if i have a parent xpath query, that generates a list of results/nodes... how can i then use the individual parent node, and trigger off of it, to get further information. i tried using the following chunk of code with no luck. #s is the html from the course file d = libxml2dom.parseString(s, html=1) #at this point, we should have a vaild "d" representation print "sdddd=",s aa=libxml2dom.toString(d) print "hereeeeee \n\n\n" print "aa",aa #sys.exit() # **** course names cpath='//table[position()>0]/descendant::td[position()=2][@width="85%"]/../t d[1]/font/a[2]/text()' cpath_=[] cpath_=d.xpath(cpath) print "len=",len(cpath_) if len(cpath_)>0: for cpath in cpath_: #get the coursename info cname=cpath.toString() print "cpath=",cpath print "cname=",cname rr="./../../../../../../following-sibling::table//tr[position()>1]" rr=cpath.xpath() print "rrlen=",len(rr) print rr[0].toString() sys.exit() i'm assuming that there's a libxml2node method that will do what i need that i'm missing... pointers/comments would be helpful here... thanks! From pmaupin at gmail.com Tue Sep 2 22:31:39 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 2 Sep 2008 19:31:39 -0700 (PDT) Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> Message-ID: <8e616d8f-a75e-4253-8b01-bd4b43e44a5b@e39g2000hsf.googlegroups.com> On Sep 2, 6:35?am, Nick Craig-Wood wrote: > bearophileH... at lycos.com wrote: > > ?It's not just my familiarity, Ada language too uses underscore for > > ?that purpose, I think, so there's a precedent, and Ada is a language > > ?designed to always minimize programming errors, simple code mistakes > > ?too. > > And perl also Add Verilog to that list. The ability to embed underscores in numeric literals, which the parser discards, is sometimes very useful in hardware description, especially when dealing with binary bit vectors which can sometimes be 32 bits or more long. Underscores are great. I have actually wished for this in Python myself, for those cases when I am doing binary. Spaces, not so much -- as others have pointed out, this is error prone, partly because spaces are "light weight" visually, and partly because the parser does not currently distinguish between different kinds of whitespace. I can't count how often I've forgotten a trailing comma on a line of items. To the complaints about the underscores getting in the way -- if the number is short, you don't need either underscores or spaces, and if the number is long, it's much easier to count underscores to find your position than it is to count spaces. Also, on long numbers (where this is most useful), the issue with mistaking a number for an identifier is much less likely to happen in real life. I think the issue of location sensitivity has already been flogged enough, but I will give it one last hit -- long numbers, where this is most useful, are often encountered in domain-specific mini languages, where the number of digits in each portion of a number might have some specific meaning. If the proposal were restricted to "once every 3 digits" or something similar, it would not be worth doing at all. +1 on the original proposal. Pat From chardish at gmail.com Thu Sep 25 11:36:51 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Thu, 25 Sep 2008 08:36:51 -0700 (PDT) Subject: "which python" as a python command? References: Message-ID: On Sep 25, 11:14?am, Carsten Haese wrote: > import sys > print sys.executable This is exactly what I needed. Thanks! From steven at REMOVE.THIS.cybersource.com.au Fri Sep 26 03:28:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 07:28:04 GMT Subject: How to get the filename in the right case ? References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> Message-ID: On Fri, 26 Sep 2008 01:46:15 +0200, Stef Mientki wrote: > Secondly thoughtless copying of current behavior, doesn't bring any > progress, > and I think that's one of the reasons why we're still burdened by > inventions done 20 years ago, > e.g. "do you want to save your changes ?". I click No about 50% of the time, and Yes Of Course You Stupid Machine the other 50% of the time. Until they have a computer capable of reading my mind, I'm curious what alternative you'd suggest. -- Steven From gh at ghaering.de Sat Sep 6 04:50:02 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 06 Sep 2008 10:50:02 +0200 Subject: embed python in ms-word? In-Reply-To: References: Message-ID: <6ieuhqFqbgnlU1@mid.uni-berlin.de> oyster wrote: > In my ms-word documnet, there are some calculation whihc I have to > change due to different argumnet. is there any way to embed python > code in word, so that I can write the following as a macro or > something else, then the result (i.e. 2) is shown in the word > documnet? > > def f(n): > if n<2: > return 1 > else: > return f(n-1)+f(n-2) > main() > return 'fib(3)=%0i' % f(3) > > if that is impossible, does there exist such word-addons can do that? thanx With Python and the win32 extensions you can write COM servers. These you can use from Visual Basic for Applications (VBA). But it's really only worth the effort if you're doing something less trivial than above ;-) -- Gerhard From gminick at bzt.bzt Mon Sep 1 06:39:14 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 10:39:14 +0000 (UTC) Subject: Processes in Linux from Python References: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> Message-ID: On Sun, 31 Aug 2008 23:25:56 -0700 (PDT), Johny wrote: > To get a number of the http processes running on my Linux( Debia box) > I use > ps -ef | grep "[h]ttpd" | wc -l ... > So my question is: > Is it possible to get a number of the http processes running on Linux > directly from Python ? Yes, it is. There is a number of third party packages that provide such functionality, including PSI: http://www.psychofx.com/psi/ I never actually liked them, because they are parsing /proc directory by themselves. Thus I wrote my own tool that is a wrapper around procps library (libproc* in your /lib, probably). Your system tools like ps, w or top are using this library. My wrapping library is available at: http://code.google.com/p/procpy/ In your case you could use it like this: >>> import procpy >>> pp = procpy.Proc() >>> for pid in pp.pids: ... if pp.procs[pid]['cmd'] == 'apache2': ... print pp.procs[pid]['tid'] ... 5204 5205 5206 5208 >>> it prints the PIDs of all the apache2 processes on my system. Procpy is fine for my own needs, but if I were about to write a code that is intended to be portable, I'd use PSI. It also is more mature. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From python-url at phaseit.net Tue Sep 30 05:06:21 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 30 Sep 2008 09:06:21 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 30) Message-ID: QOTW: "AFAICT, _everybody_ is bad at programming C++. One begins to suspect it's not the fault of the programmers." - Grant Edwards Mixing integer, float, Decimal and Fraction objects when comparing may yield unexpected results: http://groups.google.com/group/comp.lang.python/browse_thread/thread/eebc7ee9d9f2ffb0/ Usually class attributes don't have a docstring attached - how to define one? http://groups.google.com/group/comp.lang.python/browse_thread/thread/18a8c3f09ac02f85/ How do people manage their development and production environments (apt, .deb/.rpm, virtualenv, eggs...)? http://groups.google.com/group/comp.lang.python/browse_thread/thread/5d14be5d870f1600/ A real counterexample to the "Python is slow" usual claim (C++ and Python versions of the same CPU intensive task have similar performance): http://groups.google.com/group/comp.lang.python/browse_thread/thread/a63979a6f18bf37/ Implementing (some kind of) "proxy" object to multiple delegates (step by step, and with changing requirements!) http://groups.google.com/group/comp.lang.python/browse_thread/thread/a917e13bf0ea261f/ Should a library terminate program execution when it encounters an error? http://groups.google.com/group/comp.lang.python/browse_thread/thread/f01d514fbe3183ad/ An attempt to explain how closures and dynamic scope work: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c6463402371857dc/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From dear.jay.logan at gmail.com Sat Sep 6 17:27:11 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sat, 6 Sep 2008 14:27:11 -0700 (PDT) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <3e74dfde-fc97-462f-b665-c5c9f8841633@m73g2000hsh.googlegroups.com> On Sep 6, 5:04?pm, Andreas Hofmann wrote: > Hello Folks! > > I've got a little problem here, which which really creeps me out at the > moment. > I've got some strings, which only contain numbers plus eventually one > character as si-postfix (k for kilo, m for mega, g for giga). I'm trying > to convert those strings to integers, with this function: > > def eliminate_postfix(value): > ? ? ? ? ?if type(value) is str: > ? ? ? ? ? ? ? ? ?value.upper() > ? ? ? ? ? ? ? ? ?if value.endswith('K'): > ? ? ? ? ? ? ? ? ? ? ? ? ?mult = 1000 > ? ? ? ? ? ? ? ? ?elif value.endswith('M'): > ? ? ? ? ? ? ? ? ? ? ? ? ?mult = 1000000 > ? ? ? ? ? ? ? ? ?elif value.endswith('G'): > ? ? ? ? ? ? ? ? ? ? ? ? ?mult = 1000000000 > ? ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ? ? ? ?mult = 1 > > ? ? ? ? ? ? ? ? ?if mult is 1: > ? ? ? ? ? ? ? ? ? ? ? ? ?value = string.atoi(value) > ? ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ? ? ? ?value = string.atoi(value[:-1]) * mult > ? ? ? ? ?return value > > The problem is as follows: Everytime a string with a postfix should get > converted, mult does not get set properly. It is always 1. Does anyone > have an idea how to fix this? I just don't see it, maybe because I'm > pretty new to python or because I'm just blind I would be really greatful. > > Kind regards, > Andy Hello, 1. You call value.upper(), but you do not capture the results of that method. Strings are immutable in Python. >> value = value.upper() 2. You should use == instead of "is" in the comparison of mult being 1. >> if mult == 1: From mail at timgolden.me.uk Thu Sep 25 08:08:59 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 25 Sep 2008 13:08:59 +0100 Subject: Connecting to SMB share in python In-Reply-To: <2008092518182581491-rokwok@newsguycom> References: <2008092518182581491-rokwok@newsguycom> Message-ID: <48DB7F5B.8000000@timgolden.me.uk> Ronnie Kwok wrote: > Yes, I am running the script under linux and it will be doing some > processing before copying it over to the samba mount. > > It's totally fine to mount it with os.sys(...) approach but I am just > thinking if there's other option. I'm not really a Linux person but from all I can see from Googling around a bit, the os.system ("mount/unmount") option is still the most viable. Hopefully someone with real expertise can chip in. BTW, opinion in this ng/mailing list tends to favour bottom-posting or interleaved posting. TJG From bj_666 at gmx.net Wed Sep 17 09:45:24 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Sep 2008 13:45:24 GMT Subject: python regex character group matches References: Message-ID: <6jcfvkF2eqh0U2@mid.uni-berlin.de> On Wed, 17 Sep 2008 09:27:47 -0400, christopher taylor wrote: > the other day, i was trying to match unicode character sequences that > looked like this: > > \\uAD0X... > > my issue, is that the pattern i used was returning: > > [ '\\uAD0X', '\\u1BF3', ... ] > > when i expected: > > [ '\\uAD0X\\u1BF3', ] > > the code looks something like this: > > pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) #print > pat.findall(txt_line) > results = pat.finditer(txt_line) > > i ran the pattern through a couple of my colleagues and they were all in > agreement that my pattern should have matched correctly. Correctly for what input? And the examples above are not matching (no pun intended) the regular expression. `pat` doesn't match '\\uAD0X' because there's no 'X' in the character class. BTW: Are you sure you need or want the `re.UNICODE` flag? Ciao, Marc 'BlackJack' Rintsch From pataphor at gmail.com Thu Sep 18 09:17:19 2008 From: pataphor at gmail.com (pataphor) Date: Thu, 18 Sep 2008 15:17:19 +0200 (CEST) Subject: [ANN] XPN 1.2.5 References: <48d0097d$0$40312$4fafbaef@reader5.news.tin.it> Message-ID: Nemesis wrote: > XPN (X Python Newsreader) is a multi-platform newsreader with Unicode > support. It is written with Python+GTK. It has features like > scoring/actions, X-Face and Face decoding, muting of quoted text, > newsrc import/export, find article and search in the body, spoiler > char/rot13, random taglines and configurable attribution lines. Thanks! It works great. What I especially like about it is that it can be run from the directory it is in, without needing to be installed. This enabled me to run it under Ubuntu from another Ubuntu computer using sshfs. After some tinkering I was also able to run the same instance from a windows XP computer using a samba share. (Although the samba share was rather hard to set up because all the subdirectories needed permissions ... something like sudo chmod o+rw -R *). To make it run from that XP computer I also needed to add an sys.path.insert(0,'./') after import sys in xpn.py . But anyway, I can now run it from anywhere and I'm really looking forward to start tinkering with whatever other functionality I can think of to add to it, but unfortunately it is rather complete :-) . Did you know there is a tab in Articles_DB.py line 8? :-) Ducking ... P. From coleb2 at gmail.com Mon Sep 15 11:22:29 2008 From: coleb2 at gmail.com (Brian Cole) Date: Mon, 15 Sep 2008 08:22:29 -0700 (PDT) Subject: ElementTree oddities Message-ID: I'm trying to extract the text from some xml. I figured this convenient python two-liner would do it for me: >>> from xml.etree.ElementTree import * >>> from cStringIO import StringIO >>> root = parse(StringIO(xml)).getroot() >>> ' '.join([n.text for n in root.getiterator() if n.text is not None]) However, it's missing some of the text. For example, the following XML: >>> xml = "Bar" Returns me a empty string. Seems the "" tag is borking it. Also, the for the following XML: >>> xml = "Bar:" I only get "Bar". It's missing the trailing colon. I'm not that experienced with XML so perhaps I am just missing something here. Please enlighten me. Thanks, Brian From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 11:12:04 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 17:12:04 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: <48cbf09c$0$25189$426a74cc@news.free.fr> References: <48cbf09c$0$25189$426a74cc@news.free.fr> Message-ID: <48cbf432$0$27507$426a34cc@news.free.fr> Bruno Desthuilliers a ?crit : > Larry Bates a ?crit : > (snip) >> IMHO it reads better if you use the __call__ method of the class to >> return the value > > IMHO, it makes no sense at all to abuse the __call__ magic method here. Sorry - after a more careful re-read of other posts in the thread, it might make sense, given the use case : condition = FolderInUse(core) if condition.true_for(folder): # code here but then, a plain function (or a partial) might be even better - that is, if the FolderInUse class doesn't have other responsabilities. From jcd at sdf.lonestar.org Tue Sep 9 12:09:24 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 09 Sep 2008 12:09:24 -0400 Subject: Test if list contains another list In-Reply-To: <48c6380b$0$17080$426a34cc@news.free.fr> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> Message-ID: <1220976564.6148.13.camel@aalcdl07.lib.unc.edu> On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > Matimus a ?crit : > > On Sep 8, 12:32 am, Bruno Desthuilliers > > wrote: > (snip) > >> >>> set(a).issubset(set(b)) > >> True > >> >>> > >> > > Just to clarify, doing it using sets is not going to preserve order OR > > number of elements that are the same. > > > > That is: > > > >>>> a = [1,1,2,3,4] > >>>> b = [4,5,3,7,2,6,1] > >>>> set(a).issubset(set(b)) > > True > > > > This will return True if b contains at least on of each element found > > in a. If the OP wanted to check that list `a` appeared in order > > somewhere in list `b` then sets won't work. > > Indeed, and I should have mentionned this myself. Thanks for this reminder. > If preserving order is important, strings have many of the properties you're looking for, but it might take some work to figure out a suitable way to convert to a string. The problem is easier if you know something about the inputs. If all inputs are known to be numbers between 0 and 15, you can just do: if ''.join(map(hex, a)) in ''.join(map(hex, b)): return True Hmm... actually, with the '0x' prefix that hex() puts on numbers, I think this works for arbitrary integers. Cheers, Cliff From san82moon at gmail.com Mon Sep 1 04:48:17 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:48:17 -0700 (PDT) Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <7fe361c6-822f-477a-a124-0eb36668b419@p31g2000prf.googlegroups.com> On Sep 1, 1:45 pm, Bruno Desthuilliers wrote: > lee a ?crit : > > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, > > ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? > > It's quite simple (hint : read the FineManual(tm) for dict.items() and > list.index()), but 1/totally inefficient and 2/not garanteed to yield a > single value (what if 'dfsdf' happens to be also the 4th item of the > list bound to key 'address' ?). > > May I suggest you rethink your data structure instead ? What you have > here is obviously a collection of 'phno/email/name/address'records. > These records shouldn't be split across different objects. Assuming > 'phno' is a unique identifier for each record, a better data structure > would be: > > records = { > 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > # etc > > } > > This way, the lookup is as simple and efficient as possible. > > My 2 cents.... hi, i agree with u, my data strusture is not efficient. but all the records,viz...name,phno, email,address are all generated at runtime , when the user enters them. so how can i design my datastructure in that case? From dblubaugh at belcan.com Mon Sep 22 22:09:50 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 22 Sep 2008 22:09:50 -0400 Subject: Time.sleep(0.0125) not available within Linux Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380522CF11@AWMAIL04.belcan.com> To All, I was wondering if anyone has come across the issue of not being allowed to have the following within a Python script operating under Linux: time.sleep(0.0125) It appears that I am not allowed to have the object sleep. Has anyone encountered this specific issue before in the past? Thank You, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From durand1 at gmail.com Fri Sep 5 15:52:16 2008 From: durand1 at gmail.com (Durand) Date: Fri, 5 Sep 2008 12:52:16 -0700 (PDT) Subject: quake like multicoloured text References: <3d829a04-9005-4216-86dc-b1055edab4e7@f63g2000hsf.googlegroups.com> Message-ID: <212d4d2a-f2dd-496d-8a0f-da701cedcb3e@73g2000hsx.googlegroups.com> Oops, I meant, "I'm wondering how I could render text with PIL in which different parts of the text are different *colours*." From manuhack at gmail.com Fri Sep 5 22:20:06 2008 From: manuhack at gmail.com (Manu Hack) Date: Fri, 5 Sep 2008 22:20:06 -0400 Subject: max(), sum(), next() In-Reply-To: <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> Message-ID: <50af02ed0809051920n4e838fa4nce8c0e7560e6abfc@mail.gmail.com> On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: > On Sep 5, 3:28 am, "Manu Hack" wrote: >> On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: >> > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >> >> David C. Ullrich: >> >> >> > At least in mathematics, the sum of the elements of >> >> > the empty set _is_ 0, while the maximum element of the >> >> > empty set is undefined. >> >> >> What do you think about my idea of adding that 'default' argument to >> >> the max()/min() functions? >> >> >> Bye, >> >> bearophile >> >> > For max and min, why can't you just add your argument to the set >> > itself? >> >> > The reason max([]) is undefined is that max( S ) is in S. >> >> It makes sense. >> >> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >> >> It doesn't make sense to me. What do you set x to? > > For all x. But then how can you conclude sum([]) = 0 from there? It's way far from obvious. From mnordhoff at mattnordhoff.com Fri Sep 12 20:03:05 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 13 Sep 2008 00:03:05 +0000 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <00da5aca$0$2879$c3e8da3@news.astraweb.com> Message-ID: <48CB0339.5080305@mattnordhoff.com> Grant Edwards wrote: > On 2008-09-12, Matt Nordhoff wrote: > >> I think you misunderstand. He's referring to the Sender >> header, not the From header. The messages the listbot sends >> out have a Sender header of >> "python-list-bounces+user=example.com at python.org" (supposing >> the subscriber's email address is user at example.com). Bounces >> should be directed to the bitbucket or list admin or whatever, >> not the user in the From header. kring.com just has a broken >> mail server. > > So the statement below by Dennis Lee Bieber in message > 97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d at earthlink.com isn't actually > correct? > > >>Three: The bounce/ooo-reply is sent to the message author, not > >>to any intermediate host(s). After all, on that end, it's > >>normal email failure response -- notify the author of the > >>message. It doesn't matter that the original message was posted > >>on a Usenet newsgroup if that group is automatically relayed to > >>members of a mailing list. I have no idea. My post was assuming that Sjoerd Mullender was correct. With headers like "Return-Path", "Errors-To" and "Sender", ISTM the mailing list software is doing everything it can to avoid bounces getting sent to the user in the From header. If it's completely wrong, then, well, it would be silly to have gone to the effort. -- From kyosohma at gmail.com Tue Sep 23 11:21:04 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 23 Sep 2008 08:21:04 -0700 (PDT) Subject: python freeze help References: Message-ID: On Sep 23, 5:01?am, Gabriel Rossetti wrote: > Hello everyone, > > I'm trying to use python's freeze utility but I'm running into problems. > I called it like this : > > python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py > ~/Documents/Code/Python/src/jester/service.py -m jester > > then I did : make > > then I tried to run it : ./service > > and I get this : > > grossetti at desktop-01:~/tmp/freeze$ ./service > Traceback (most recent call last): > ? File "/home/grossetti/Documents/Code/Python/src/jester/service.py", > line 16, in > ? ? from jester import constants, utils > ? File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line > 20, in > ? ? from twisted.internet.protocol import Protocol, ClientCreator > ? File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", > line 17, in > ? ? from zope.interface import implements > ? File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in > > ? ? pkg_resources.declare_namespace('zope') > ? File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, > in declare_namespace > ? ? _handle_ns(packageName, path_item) > ? File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, > in _handle_ns > ? ? path = module.__path__; path.append(subpath) > AttributeError: 'str' object has no attribute 'append' > Error in sys.excepthook: > Traceback (most recent call last): > ? File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line > 38, in apport_excepthook > ? ? from apport.packaging_impl import impl as packaging > ? File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in > > ? ? from apport.report import Report > ? File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in > > ? ? from problem_report import ProblemReport > ? File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in > > ? ? from email.MIMEMultipart import MIMEMultipart > ? File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__ > ? ? __import__(self.__name__) > ImportError: No module named multipart I've gotten this error from py2exe before. I'm not sure how freeze works, but in py2exe I had to make sure the email package wasn't being accidentally excluded and explicitly included. > > Original exception was: > Traceback (most recent call last): > ? File "/home/grossetti/Documents/Code/Python/src/jester/service.py", > line 16, in > ? ? from jester import constants, utils > ? File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line > 20, in > ? ? from twisted.internet.protocol import Protocol, ClientCreator > ? File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", > line 17, in > ? ? from zope.interface import implements > ? File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in > > ? ? pkg_resources.declare_namespace('zope') > ? File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, > in declare_namespace > ? ? _handle_ns(packageName, path_item) > ? File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, > in _handle_ns > ? ? path = module.__path__; path.append(subpath) > AttributeError: 'str' object has no attribute 'append' > > Does anyone have any ideas as of why I get this? > > Thank you, > Gabriel I don't know what this second error is... Mike From kib2 at free.fr Thu Sep 25 15:22:25 2008 From: kib2 at free.fr (kib2) Date: Thu, 25 Sep 2008 21:22:25 +0200 Subject: text processing In-Reply-To: <6k20ckF5glpmU1@mid.uni-berlin.de> References: <6k20ckF5glpmU1@mid.uni-berlin.de> Message-ID: <48dbe4f2$0$29163$426a74cc@news.free.fr> You can do it with regexps too : >------------------------------------------------------------------ import re to_watch = re.compile(r"(?P\d+)[/](?P[A-Z]+)") final_list = to_watch.findall("12560/ABC,12567/BC,123,567,890/JK") for number,word in final_list : print "number:%s -- word: %s"%(number,word) >------------------------------------------------------------------ the output is : number:12560 -- word: ABC number:12567 -- word: BC number:890 -- word: JK See you, Kib?. From rstarkov at gmail.com Sun Sep 14 04:06:41 2008 From: rstarkov at gmail.com (rs387) Date: Sun, 14 Sep 2008 01:06:41 -0700 (PDT) Subject: recursion gotcha? References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> Message-ID: On Sep 14, 9:01?am, cnb wrote: > def suma(xs, acc=0): > ? ? ? ? if len(xs) == 0: > ? ? ? ? ? ? ? ? acc > ? ? ? ? else: > ? ? ? ? ? ? ? ? suma(xs[1:], acc+xs[0]) > > it returns none. Yep, that's because there is no "return" statement anywhere. Python doesn't return expressions "by default", like functional languages do, so where you say "suma(xs[1:], acc+xs[0])" this just calls itself and returns nothing. Try this: def suma(xs, acc=0): if len(xs) == 0: return acc else: return suma(xs[1:], acc+xs[0]) print suma([1, 2, 3, 4, 5]) (prints 15) Roman From nuffnough at gmail.com Tue Sep 9 10:11:01 2008 From: nuffnough at gmail.com (nuffnough at gmail.com) Date: Tue, 9 Sep 2008 07:11:01 -0700 (PDT) Subject: noob help request - how to make a list of defined class? Message-ID: I have defined two classes with one common field (called code) and several different fields. In class A there is only one instance of any given code as all items are individual. In class B, there may be none, one or many instances of each code, as there can be any number of Bs referring to a single A. I need to make a list of Bs, remove dupes, and then create a list of As that have Bs. (I hope this makes sense!) with much research and reading of my book I managed to get this working, but at one stage I had errors that talked about being unable to concatenate type A. So I converted my As to string, and then did a split on commas to make a list. This worked fine for all the As that didn't have a comma in a field (about 85%) but I can't help feeling that this is a kludge, and that if Icould find a way to get a proper list of As instead of a list of lists created by converting to string and splitting, then my app would work properly. So I am hoping some of the nice folk here will help me out. The relevent function looks like this: def gen_B_A_list(): Bcodes = get_codes() all_As = read_A("A.csv") B_A = [] for i in range(len(codes)): Bcode = Bcodes[i] for A in all_As: filename = getattr(A, 'code') if filename == Bcode: BA = str(A) BA = string.split(BA, ',') B_A.append(BA) return B_A The element in question is after if filename == Bcode. How do I construct a list of my defined class A objects here instead of this? ( I can post the full code if needed, just thought it was better netiquette not to) TIA nuffi From mccredie at gmail.com Tue Sep 16 18:55:17 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 16 Sep 2008 15:55:17 -0700 (PDT) Subject: optparse References: Message-ID: <5b3e58f7-83fb-421c-8dac-cb8e9b34952a@n33g2000pri.googlegroups.com> I'm assuming you read at least some of the docs. This page makes it pretty clear: http://docs.python.org/lib/optparse-default-values.html Matt From marco.bizzarri at gmail.com Thu Sep 4 07:08:59 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 13:08:59 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <6i9tftFpi1lhU1@mid.uni-berlin.de> References: <6i9tftFpi1lhU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809040408u4a9f08d8jfb0af4cf7c5010ba@mail.gmail.com> On Thu, Sep 4, 2008 at 1:00 PM, Diez B. Roggisch wrote: > Marco Bizzarri wrote: > >> Let's say I've a class a, where I can write: > > Anticipating this obviously premature posting: > > http://dirtsimple.org/2004/12/python-is-not-java.html > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Ehi, Diez, that was fast :-) ! Thanks for the link, I saw it in the past days and I read it; and I appreciated it a lot (actually, it was a door to a new world in Python, for me). But I'm asking something I feel is a little different, as you can read in my message, once it is full. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From timr at probo.com Fri Sep 26 23:34:43 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 27 Sep 2008 03:34:43 GMT Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> <98e4f068-5349-4b38-b15b-7e2436a0e4a7@f63g2000hsf.googlegroups.com> Message-ID: Mark Dickinson wrote: >On Sep 25, 8:55?am, Tim Roberts wrote: >> Marc 'BlackJack' Rintsch wrote: >> >0.1 actually is >> >> >In [98]: '%.50f' % 0.1 >> >Out[98]: '0.10000000000000000555111512312578270211815834045410' >> >? >> >> Actually, it's not. ?Your C run-time library is generating random digits >> after it runs out of useful information (which is the first 16 or 17 >> digits). ?0.1 in an IEEE 784 double is this: >> >> ? ? ?0.100000000000000088817841970012523233890533447265625 > >I get (using Python 2.6): > >>>> n, d = 0.1.as_integer_ratio() >>>> from decimal import Decimal, getcontext >>>> getcontext().prec = 100 >>>> Decimal(n)/Decimal(d) >Decimal('0.1000000000000000055511151231257827021181583404541015625') > >which is a lot closer to Marc's answer. Looks like your float >approximation to 0.1 is 6 ulps out. :-) Hmmph, that makes the vote 3 to 1 against me. I need to go re-examine my "extreme float converter". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sturlamolden at yahoo.no Tue Sep 23 09:41:33 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 06:41:33 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: <633d90d1-c2e9-45d7-852e-c4f3951656e3@d45g2000hsc.googlegroups.com> On Sep 23, 3:13?am, process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? Because Python is a dynamic language. While a function is executing, its name may be bound to another object. It may happen as a side effect of what the function is doing, or even from another thread. The compiler has no way of knowing that. Recursion can always be expressed as iteration, possibly with a Python list as stack. From mail at timgolden.me.uk Tue Sep 23 07:24:05 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 23 Sep 2008 12:24:05 +0100 Subject: python timers and COM/directshow In-Reply-To: References: Message-ID: <48D8D1D5.2030303@timgolden.me.uk> Sayanan Sivaraman wrote: > So I've written a simple video player using directshow/COM in VC++, > and I'm in the process of translating it to python. For example, when > the avi starts playing, I have a call media_control.Run() , etc. > > I'm wondering how I should go about updating my gtk.Hscale widget as a > trackbar for the avi player. > > In C++, I have the following callbacks that update the scrollbar and > video position with a timer. [... snip callbacks ...] > > I'm wondering how I would implement similar callbacks in Python for a > gtk.Hscale, and some sort of time [I'm not familiar with Pythons > timers/threading at all]. You'd help your cause a lot here if you posted *Python* code to indicate what's calling what back where. Also if you stated whether you were using, eg, the GTK toolkit which your description suggests, or some other GUI toolkit. Because they tend to vary as to how they arrange their callbacks. In geeneral, Python callbacks are trivial: you create the function to do whatever and then pass the function as an object into the calling-back function call. Something like this (invented GUI toolkit): def handle_lbutton_click (event): # # do stuff with lbutton click # def handle_widget_slide (event): # # do stuff with widget slide # handle_event ("lbutton_click", handle_lbutton_click) widget.attach_event ("slide", handle_widget_slide) But the details will obviously depend on the toolkit you use. TJG TJG From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:38:13 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:38:13 GMT Subject: Off topic: Sent from my Foo messages References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> Message-ID: <00eaf368$0$20666$c3e8da3@news.astraweb.com> I'm seeing more and more posts from various people, on this list and others, with statements like the following: On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote: > Sent from my iPhone Also "Sent from my Blackberry" and similar. Without wishing to be rude to David, who I'm sure is a nice guy and not at all the pretentious git that such a line makes him appear, are people adding this comment to the bottom of their posts, or is it something that their device automatically appends to the post? If people are adding it themselves, that's nice, I'm sure you're really excited about your new toy, but the rest of us don't care a monkey's toss. And if the device is automatically appending it, I think that's pretty damn rude and a good reason to avoid buying the obnoxious machines. -- Steven From metallourlante at gmail.com Thu Sep 11 08:00:05 2008 From: metallourlante at gmail.com (Alex) Date: Thu, 11 Sep 2008 05:00:05 -0700 (PDT) Subject: Extracing data from webpage References: Message-ID: <00fa212a-c2f1-49fb-b347-06947cd18720@a70g2000hsh.googlegroups.com> On Sep 11, 11:55?am, srinivasan srinivas wrote: > Hi, > I am trying to download data from a webpage. I use mechanize python module. > Could someone tell me how to set/pass an agent?like Mozilla or IE that we do in perl's WWW::Mechanize?? > > Thanks, > Srini > > ? ? ? Be the first one to try the new Messenger 9 Beta! Go tohttp://in.messenger.yahoo.com/win/ If you have to parse a web page, this could be also useful: http://www.crummy.com/software/BeautifulSoup/ From toddw at activestate.com Tue Sep 16 21:29:21 2008 From: toddw at activestate.com (Todd Whiteman) Date: Tue, 16 Sep 2008 18:29:21 -0700 Subject: ANN: Python GUI development using XULRunner Message-ID: <48D05D71.2060905@activestate.com> I've put together a tutorial that shows off how to build a GUI application using XULRunner (same architectural components as Firefox uses) that can be used in conjunction with the Python programming language. The tutorial covers how to build a Python/XULRunner GUI application: http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html The details in this tutorial covers the initial setup to full packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX is possible with a few deviations, I have tried to cover these deviations where applicable). Feedback is welcome. Cheers, Todd From lie.1296 at gmail.com Tue Sep 30 04:01:49 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 30 Sep 2008 15:01:49 +0700 Subject: What is not objects in Python? In-Reply-To: References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <1222761708.10129.9.camel@lieryan-laptop> On Mon, 2008-09-29 at 21:03 -0700, namekuseijin wrote: > On 28 set, 15:29, process wrote: > > I have heard some criticism about Python, that it is not fully object- > > oriented. > > So what? > > > Why isn't len implemented as a str.len and list.len method instead of > > a len(list) function? > > Because postfix notation sucks. The natural way of spelling is > adjective+noun and verb+predicate. That's one of the reasons I like > Lisp better than Python. > -- > http://mail.python.org/mailman/listinfo/python-list > Actually str.len and len(str) is just like saying "the string's length" and "the length of the string". There is no difference between the two except for personal preference. (I am no linguist-- not even a native speaker of English --but I think there is a subtle difference on emphasis, "the string's length" emphasizes on the length being string's property, while "the length of the string" emphasizes on the length itself, am I correct?) From gminick at bzt.bzt Mon Sep 1 06:54:18 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 10:54:18 +0000 (UTC) Subject: list + dictionary searching References: <6e642a00-9301-440d-902c-63713cf4a793@a2g2000prm.googlegroups.com> Message-ID: On Mon, 1 Sep 2008 03:14:22 -0700 (PDT), Manoj wrote: > I would like to : > > search dictionaries within this list > create a new list with dictionaries which gives 1 dictionary for every > user with month_year as a key and utilization for that month as a > value > > Please give your thoughts Reading about for loop seems like a good idea. You can easily create a set of functions that gives you direct access to the information you need. http://docs.python.org/tut/node6.html#SECTION006200000000000000000 http://docs.python.org/tut/node7.html#SECTION007500000000000000000 Give it a try. Try to design some functions that let you view and add new lists/dictionaries to your variables. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bearophileHUGS at lycos.com Sat Sep 20 13:13:10 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 20 Sep 2008 10:13:10 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Duncan Booth: > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) > > The exact equivalent would be: > for i in range(10, -1, -1): print i I'd use xrange there. Anyway, I have always felt that Python syntax not easy to understand at first sight, expecially when you try to convert a bit more complex inverted for loops from/to C to/from Python. It's one of the few cases where (for example) Pascal (loop) syntax wins a bit over Python syntax :-) Bye, bearophile From castironpi at gmail.com Wed Sep 24 21:12:04 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 18:12:04 -0700 (PDT) Subject: Er, one -lime- or two. Message-ID: <2ac98076-0163-45c4-8269-e6c1a1d70d7f@c65g2000hsa.googlegroups.com> A Python walks into a bar and orders a complex data structure. Bartender says, "One line or two?" From annathorns at googlemail.com Mon Sep 22 12:20:58 2008 From: annathorns at googlemail.com (annathorns at googlemail.com) Date: Mon, 22 Sep 2008 09:20:58 -0700 (PDT) Subject: Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS Message-ID: <287e6ec9-e165-4ea2-a3f7-136a178357b1@p10g2000prf.googlegroups.com> Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com From martin at v.loewis.de Sun Sep 28 17:47:00 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 28 Sep 2008 23:47:00 +0200 Subject: Python 3.0 and repr In-Reply-To: References: Message-ID: <48dffb54$0$1082$9b622d9e@news.freenet.de> > What are others' opinions? Any insight to this design decision? The intention is that all printable characters in a string get displayed in repr. This was in particular requested by Japanese users (but also by other users of non-ASCII characters) which complained that repr() is fairly useless if your strings actually contains *no* ASCII characters (but all of them are printable). Notice that repr() of the string actually succeeds; try >>> x='\u5000' >>> z=repr(x) It is the printing of the repr that fails. > Maybe repr() should always display the ASCII representation with > escapes for all other characters You can use the ascii() builtin if you want that. > especially considering the "repr() should produce output suitable for > eval() when possible" rule. But that is preserved under the new behavior, also! Just try py> x='\u5000' py> eval(repr(x))==x True Regards, Martin P.S. How did you manage to get U+5000 into your data, on a system where the terminal encoding is cp437? Google translates it as "Rash"; the Unihan database also has "bewildered", "wildly". From castironpi at gmail.com Fri Sep 26 14:07:55 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 11:07:55 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: <3b70e025-3ebf-4b0c-88b1-962eb58129f9@26g2000hsk.googlegroups.com> On Sep 26, 11:48?am, "Tim Rowe" wrote: > 2008/9/26 Tino Wildenhain : > > >> The question I usually ask is "Does this language help me get the job > >> done?" Python often does. That's all that really matters, isn't it? > > > Well then it still depends on the perception of "job done". For example > > PHP programmers would bet their soul that their language of choice is > > exactly the right one to "get the job done." :-) > > You and me would indeed see a different picture on the level of doneness > > of such jobs ;-) > > Well, I did say "Often". Before now I've struggled for ages to write a > Python program to do a job, then when I've tried C# all the problems > have fallen away and the job was done in an hour or so. But other > times it has been the other way around; I've done stuff in Python that > I wouldn't know where to begin with in other languages. One of my > constant refrains is that *no* tool is ideal for *all* jobs! > > -- > Tim Rowe I thought procedural and imperative were the same. "Sorry, but you forgot to phrase your expression in the form of a command." I'll take 'modules' for $500, Alex. From aioe.org at technicalbloke.com Wed Sep 24 22:15:04 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 24 Sep 2008 22:15:04 -0400 Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: Duncan Booth wrote: > r0g wrote: > >> OK so maybe I'm being naive here but it looks to me like this new >> paradigm's big idea is to use a python + SQL type syntax to access data >> in random objects. Big whoop. It's not that difficult to write a >> generators that wraps XML files and databases is it? >> >> What am I missing here? > > Simple LINQ expressions like the one you gave map easily to Python list > comprehensions. What Microsoft have done though is provide a consistent > implementation which allows you to write complex SQL like expressions which > will work identically on databases or most other sequence types. Hmm, that's a nice idea in theory but I don't think it's the python killer Mr/Ms bearophile thinks it is. I can't think of any use cases where this would save me a great deal of time (certainly not enough to offset the relative slowness of working in C#) but supposing they do exist this stuff definitely belongs in a module. Seems to me C# is playing catchup in most ways and this nugget of 'innovation' is just the exception that proves the rule. Roger. From kar1107 at gmail.com Tue Sep 2 18:31:39 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 2 Sep 2008 15:31:39 -0700 (PDT) Subject: Storing Subprocess Results References: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> Message-ID: <09d82341-3005-4be4-8567-e86faa7ee72a@a8g2000prf.googlegroups.com> On Sep 2, 7:16?am, topazcode wrote: > I am using the subprocess module to run some shell commands on a Linux > system: > > import subprocess > output = subprocess.call('''ssh server1 "uptime"''', shell=True) > > The above assigns the output variable with a return code, i.e. 0 in > this case. ?How can I actually capture the data returned from > subprocess.call, rather than just the return code? ?I'd like to have > the output variable contain the uptime string in this case. Probably commands module is a better choice for your problem: >>> import commands >>> commands.getoutput('fortune') "While money can't buy happiness, it certainly lets you choose your own \nform of misery." >>> Karthik ?Any help > is appreciated. ?Thanks. From circularfunc at gmail.com Mon Sep 22 21:13:30 2008 From: circularfunc at gmail.com (process) Date: Mon, 22 Sep 2008 18:13:30 -0700 (PDT) Subject: Why no tailcall-optimization? Message-ID: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Why doesn't Python optimize tailcalls? Are there plans for it? I know GvR dislikes some of the functional additions like reduce and Python is supposedly about "one preferrable way of doing things" but not being able to use recursion properly is just a big pain in the a**. From goldspin at gmail.com Thu Sep 11 13:30:57 2008 From: goldspin at gmail.com (Henry Chang) Date: Thu, 11 Sep 2008 10:30:57 -0700 Subject: How to Determine Name of the Day in the Week In-Reply-To: References: Message-ID: Awesome, that worked. Thanks so much! On Thu, Sep 11, 2008 at 10:16 AM, Fredrik Lundh wrote: > Henry Chang wrote: > > Instead of getting integers with weekday(), Monday == 0 ... Sunday == 6; >> is there a way to get the actual names, such as "Monday ... Sunday"? I >> would like to do this without creating a data mapping. :) >> > > if you have a datetime or date object, you can use strftime with the > appropriate formatting code. see the library reference for details. > > if you have the weekday number, you can use the calender module: > > >>> import calendar > >>> calendar.day_name[0] > 'Monday' > > (the latter also contains abbreviated day names, month names, and a bunch > of other potentially useful functions and mappings.) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From istvan.albert at gmail.com Thu Sep 25 20:20:07 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 25 Sep 2008 17:20:07 -0700 (PDT) Subject: multiprocessing eats memory References: Message-ID: On Sep 25, 8:40?am, "Max Ivanov" wrote: > At any time in main process there are shouldn't be no more than two copies of data > (one original data and one result). >From the looks of it you are storing a lots of references to various copies of your data via the async set. From woodygar at sky.com Tue Sep 30 05:21:08 2008 From: woodygar at sky.com (garywood) Date: Tue, 30 Sep 2008 10:21:08 +0100 Subject: can someone explain why this happens- newbie question Message-ID: Hi can someone tell me why it prints the high score table multiple times? #high scores program scores =[] choice = None while choice != 0: print """high Score Table 0 - exit 1 - show Scores 2 - add a score 3 - delete a score 4 - sort scores """ choice = input("what would you like to do?") if choice == 0: print "goodbye" elif choice == 1: for score in scores: print scores elif choice == 2: score = input("add a score") scores.append(score) elif choice == 3: score = input("what score would you like to delete ?") if score in scores: scores.remove(score) else: print "that score is not listed" elif choice == 4: scores.sort() scores.reverse() print scores, "highest score first" -------------- next part -------------- An HTML attachment was scrubbed... URL: From tino at wildenhain.de Fri Sep 26 09:05:35 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 15:05:35 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> Message-ID: <48DCDE1F.6040709@wildenhain.de> Michael Mabin wrote: > cursor.execute(""" > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """ % ','.join([str(x) for x in [1,5,9]]) Nope. That would be dangerous! -> google for SQL injection Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 22:20:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 02:20:33 GMT Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <48d54863$0$4666$426a74cc@news.free.fr> Message-ID: <00e5a962$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 19:01:42 +0200, Bruno Desthuilliers wrote: > Once again, sorry > if me missing your correct answer drives you paranoid :-) What do you mean by that? How many other people have been talking about me? *wink* -- Steven From bignose+hates-spam at benfinney.id.au Fri Sep 26 22:28:40 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 12:28:40 +1000 Subject: getting global variables from dictionary References: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> Message-ID: <87iqsiuxt3.fsf@benfinney.id.au> icarus writes: > global_vars.py has the global variables > set_var.py changes one of the values on the global variables (don't > close it or terminate) > get_var.py retrieves the recently value changed (triggered right after > set_var.py above) > > Problem: get_var.py retrieves the old value, the built-in one but > not the recently changed value in set_var.py. That's because you're making a new instance each time; each instance carries its own state. For a collection of attributes that should share state, probably the simplest way is to use attributes of a module. > ----global_vars.py--- > #!/usr/bin/python > > class Variables : > def __init__(self) : > self.var_dict = {"username": "original username"} These aren't "global variables"; they still need to be imported, like anything else from a module. Better to name the module by intent; e.g. if these are configuration settings, a module name of 'config' might be better. Also, this module presumably isn't intended to be run as a program; don't put a shebang line (the '#!' line) on files that aren't run as programs. ===== config.py ===== # -*- coding: utf-8 -*- # Name of the front-end user username = "original username" # Amount of wortzle to deliver wortzle_amount = 170 ===== > ---set_var.py --- > #!/usr/bin/python > > import time > import global_vars > > global_vars.Variables().var_dict["username"] = "new username" > time.sleep(10) #give enough time to trigger get_var.py ===== set_config.py ===== # -*- coding: utf-8 -*- import config def set_user(): config.username = "new username" ===== > ---get_var.py --- > #!/usr/bin/python > import global_vars > print global_vars.Variables().var_dict.get("username") ===== get_config.py ===== # -*- coding: utf-8 -*- import config def get_user(): return config.username ===== The 'config' module, imported by both of the other modules, maintains state: >>> import config >>> print config.username original username >>> import set_config >>> set_config.set_user() >>> print config.username new username >>> import get_config >>> print get_config.get_user() new username -- \ ?You can't have everything; where would you put it?? ?Steven | `\ Wright | _o__) | Ben Finney From paul at hovnanian.com Mon Sep 22 00:38:13 2008 From: paul at hovnanian.com (Paul Hovnanian P.E.) Date: Sun, 21 Sep 2008 21:38:13 -0700 Subject: Milenko Kindl rtegdgd References: Message-ID: <48D72135.3291EBFB@hovnanian.com> yuma wrote: > > Milenko Kindl > Banja Luka > Banjaluka > Bihac Try facing Mecca while repeating that and your source will compile. -- Paul Hovnanian mailto:Paul at Hovnanian.com ------------------------------------------------------------------ Leap and the net will appear. From castironpi at gmail.com Fri Sep 5 14:43:35 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 5 Sep 2008 11:43:35 -0700 (PDT) Subject: xml + mmap cross References: <48BF8AC8.6030509@behnel.de> <48c0c001$0$9319$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4724c1fd-01e6-4711-95e5-292ca450e2d1@d77g2000hsb.googlegroups.com> On Sep 5, 12:13?am, Stefan Behnel wrote: > Hi, > > this discussion seems pretty much off-topic for a Python list. > > > > castironpi wrote: > > In an XML file, entries are stored in serial, sort of like this. > > > AAA BBB CCC DDD > > > Or more recognizably, > > > somethingsomething > > > Point is, to change something to something else, you > > have to recopy everything after that. > > > AAA BBB CCC DDD > > AAA BBBb CCC DDD > > > requires 7 writes, 'b CCC DDD', not 1. > > > I want to use a simple tree structure to store: > > > 0 A-> None, 1 > > 1 B-> None, 2 > > 2 C-> 3, None > > 3 D-> None, None > > > Each node maps to 'Next, Child', or more accurately, 'Next Sibling, > > First Child'. > > Do I understand you right: you want to access serialised XML data alex23 correctly pointed out last night that XML is always serialized. What I mean and possibly what you mean is, a serialized tree structure. > as a memory > mapped file and operate directly on the byte data? Yes. Byte data containing both strings, and the structure of the tree. > You would still have to > decode the complete byte sequence to parse it and build your index structure > in that case. No, it's saved in an index structure; it's already in one. To find a/ b/c, read a, read its children to b, read b, read its children to c, read c. > How do you plan to store the pointers to a node's next sibling/child? And how > do you keep them updated over insertions/deletions? You update them when you insert them. To add 'c' to a/b, allocate c, initialize c, read a, read its children to b, read b, read its children to the end, add c. When you delete c from a/b/c, however, any references to c that you have in any programs become invalid. Don't delete it if you have them. The bytes are marked in the file to be no longer in use, which marking takes up some of the space in the file. > That, plus the copy > overhead in a sequential file, will be very costly on each change. No. That's the point of a dynamic structure. are not stored in memory as 10 consecutive characters. The file is not strictly speaking XML. See below for what they're stored as. > > You get constant time updates to contents, and log-time searches. > > Every XML tree structure gives you log-time searches. But how do you achieve > constant time updates in a sequential file? You don't use a sequential file. > Stefan I stated earlier that each node would look roughly like: tag_offset, first_attr, text_offset, tail_offset, first_child, prev_sibling, next_sibling, parent Attributes would look like: key_offset, value_offset, prev_attr, next_attr, node All these fields are integers that contain an offset into the file. Simplified: 0 Reserved 1 A.Tag 7 (points to 7 below) 2 A.FirstChild 4 (etc.) 3 A.Contents 0 (None) 4 B.Tag 11 5 B.FirstChild 0 6 B.Contents 15 7 3abc 11 3def 15 5ghijk This translates to: ghijk But isn't stored that way. The records are all the same size. The 'Tag' field of a record that starts at offset J is at offset J. The 'FirstChild' field of a record that starts at offset K is at offset K+ 1. 'tag_offset', 'text_offset', 'key_offset', and 'value_offset' contain offsets of variable-length strings into the file ( 7, 11, 15 ). The rest contain offsets of further structures. There's extra space usage not only in the structure of the tree, but in the record-keeping of what bytes are available for use, and which are in use. You have to grow the file size yourself (like growing an array) when you need to; the file system won't for you in mmap. (This means the alloc-free module I'm looking at will need modifications.) I'll reemphasize the value of constant-time insertions to a file though. From ldo at geek-central.gen.new_zealand Wed Sep 24 06:27:12 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:27:12 +1200 Subject: Modifying the system menu References: Message-ID: In message , raj.indian.08 at gmail.com wrote: > For example say - I am creating multiple desktops for windows - > and I want to give every application the capability to be moved across > different desktops. But doesn't the desktop environment/window manager that provides the multiple desktops also provide the relevant entries in the system menu? From hniksic at xemacs.org Thu Sep 18 08:04:50 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 18 Sep 2008 14:04:50 +0200 Subject: how can I use a callable object as a method References: Message-ID: <87r67hoe1p.fsf@mulj.homelinux.net> Piotr Sobolewski writes: > However, the second version does not work. I think I understand > why. That's because "a" inside f1 is not a function (but an object). An object that defines __call__ is perfectly usable as a function. Your problem is that it doesn't know how to convert itself to a method, so that f1.a() knows how to pass f1 as another_self to add.__call__. To do that, add needs to be a bit smarter: >>> class add(object): ... def __call__(self, another_self): ... return another_self.version ... def __get__(self, obj, type=None): ... return lambda: self(obj) ... >>> class f(object): ... version = 17 ... a = add() ... >>> f1 = f() >>> f1.a() 17 If you can't modify add, you can probably use an adaptor that defines __get__ in a similar way. From fredrik at pythonware.com Thu Sep 11 14:31:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 20:31:44 +0200 Subject: shelve file name extention In-Reply-To: References: Message-ID: Monu wrote: > So Can't I choose which module to use. Is there any preferance on > which shelve chooses these modules? it uses the anydbm module to look for available DBM-style drivers, which looks for modules in the following order: dbhash, gdbm, dbm, dumbdbm. if you know which one you want, you can open the database file yourself, and pass it to the Shelf constructor: import shelve import somedbm db = shelve.Shelf(somedbm.open(file, flag)) From bignose+hates-spam at benfinney.id.au Thu Sep 4 09:10:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Sep 2008 23:10:32 +1000 Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <00cfa3b9$0$20302$c3e8da3@news.astraweb.com> Message-ID: <87vdxcm4zb.fsf@benfinney.id.au> Steven D'Aprano writes: > On Tue, 02 Sep 2008 13:07:33 -0400, Joe Riopel wrote: > > > On Tue, Sep 2, 2008 at 12:55 PM, Steven D'Aprano > > wrote: > >> Is there a better way of doing this than the way I am going about it? > > > > Would the logging module help, and just print the output to the stdout > > (or a file) instead? > > Thank you to everyone who answered. > > As I feared, it seems that there's no really simple way of dealing with > arbitrary messages at arbitrary parts of my code. I would think the 'logging' module *is* the simple way to do this. At least, it's as simple as it could be without leading to massive re-visiting of the "arbitrary parts of one's code" when later desiring to change the way the messages are handled. -- \ ?We must become the change we want to see.? ?Mahatma Gandhi | `\ | _o__) | Ben Finney From castironpi at gmail.com Sun Sep 28 16:08:05 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 13:08:05 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: On Sep 28, 2:59?pm, sotirac wrote: > Wondering if there is a better way to generate string of numbers with > a length of 5 which also can have a 0 in the front of the number. > >
> ?random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> elements
> ?code = 'this is a string' + str(random_number[0]) +
> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> + str(random_number[4])
> 
'%05i'%random.randint(0,99999) From owenzhang.chicago at gmail.com Fri Sep 12 16:34:02 2008 From: owenzhang.chicago at gmail.com (Owen Zhang) Date: Fri, 12 Sep 2008 13:34:02 -0700 (PDT) Subject: lxml build error in sun Message-ID: I am trying to build lxml package in SunOS 5.10. I got the following errors. Does anybody know why? $ python setup.py build Building lxml version 2.1. NOTE: Trying to build without Cython, pre-generated 'src/lxml/ lxml.etree.c' needs to be available. Using build configuration of libxslt 1.1.7 Building against libxml2/libxslt in the following directory: /usr/lib running build running build_py running build_ext building 'lxml.etree' extension gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes - fPIC -I/opt/swt/install/libxml2-2.6.27/include/libxml2 -I/opt/swt/ install/Python-2.5/include/python2.5 -c src/lxml/lxml.etree.c -o build/ temp.solaris-2.10-sun4u-2.5/src/lxml/lxml.etree.o -w In file included from /usr/include/sys/wait.h:24, from /usr/include/stdlib.h:22, from /opt/swt/install/Python-2.5/include/python2.5/ Python.h:41, from src/lxml/lxml.etree.c:4: /usr/include/sys/siginfo.h:259: error: syntax error before "ctid_t" /usr/include/sys/siginfo.h:292: error: syntax error before '}' token /usr/include/sys/siginfo.h:294: error: syntax error before '}' token /usr/include/sys/siginfo.h:390: error: syntax error before "ctid_t" /usr/include/sys/siginfo.h:398: error: conflicting types for '__fault' /usr/include/sys/siginfo.h:267: error: previous declaration of '__fault' was here From deets at nospam.web.de Sat Sep 6 08:23:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Sep 2008 14:23:23 +0200 Subject: Cancel instance create In-Reply-To: References: <1220697080.48c25bf890ade@www.inbox.lv> Message-ID: <6ifb1rFq9nlnU1@mid.uni-berlin.de> Mohamed Yousef schrieb: > ?What about no Constructor , and a custom instancing function that can > return either None or the instance wanted That doesn't solve the underlying problem - the instance is created. Just because it wasn't *returned*, doesn't mean it isn't there. Diez From michel at nospam.please Mon Sep 15 15:31:54 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:31:54 +0200 Subject: environment variable issue In-Reply-To: References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <48ceb82a$0$2861$ba620e4c@news.skynet.be> Tim Chase a ?crit : > Your HOSTNAME variable hasn't been exported to subshells. You can check > this by looking at the output of > > bash$ export -p > > which will print all the variables that are exported. I suspect you'll > see $USER in the list, but not $HOSTNAME Actually HOSTNAME seems to be exported as well: $ export -p | grep HOSTNAME declare -x HOSTNAME="LinuxPC" I don't know what to think of this but it's the beginning of an explanation. Thanks, Michel -- Michel Leunen http://linux.leunen.com From linkmaster032000 at gmail.com Thu Sep 18 18:59:27 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Thu, 18 Sep 2008 15:59:27 -0700 (PDT) Subject: curses.setsyx()? Message-ID: I tried curses.setsyx(2,3) in my script and it doesn't move the curses cursor. Any alternatives/solutions? From usenet.tolomea at gmail.com Sun Sep 7 06:54:54 2008 From: usenet.tolomea at gmail.com (usenet.tolomea at gmail.com) Date: Sun, 7 Sep 2008 03:54:54 -0700 (PDT) Subject: tracking collection modification Message-ID: <42d9688f-1058-4ed7-8d9d-affd432fdb41@s1g2000pra.googlegroups.com> I'm working on a remote object system, something kinda like Pyro. For the purposes of caching I need to be able to tell if a given dict / list / set has been modified. Ideally what I'd like is for them to have a modification count variable that increments every time the particular collection is modified. Unfortunately I can't find anything like that and since this needs to work for the regular normal list / dict / set objects subclassing them to add the modification count isn't useful. I realize I could take a copy and then compare the copy to the original, but that's a fairly heavy handed approach and I was hoping for something light and fast. Does anyone have any suggestions on best to approach this? From dickinsm at gmail.com Thu Sep 25 06:05:13 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 25 Sep 2008 03:05:13 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> Message-ID: <98e4f068-5349-4b38-b15b-7e2436a0e4a7@f63g2000hsf.googlegroups.com> On Sep 25, 8:55?am, Tim Roberts wrote: > Marc 'BlackJack' Rintsch wrote: > >0.1 actually is > > >In [98]: '%.50f' % 0.1 > >Out[98]: '0.10000000000000000555111512312578270211815834045410' > >? > > Actually, it's not. ?Your C run-time library is generating random digits > after it runs out of useful information (which is the first 16 or 17 > digits). ?0.1 in an IEEE 784 double is this: > > ? ? ?0.100000000000000088817841970012523233890533447265625 I get (using Python 2.6): >>> n, d = 0.1.as_integer_ratio() >>> from decimal import Decimal, getcontext >>> getcontext().prec = 100 >>> Decimal(n)/Decimal(d) Decimal('0.1000000000000000055511151231257827021181583404541015625') which is a lot closer to Marc's answer. Looks like your float approximation to 0.1 is 6 ulps out. :-) Mark From sebastianthegreatful at gmail.com Thu Sep 18 03:58:33 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Thu, 18 Sep 2008 00:58:33 -0700 (PDT) Subject: ssl server References: <72ed03e9-e3cd-4feb-ac5c-41f9ee1f5458@y21g2000hsf.googlegroups.com> Message-ID: On Sep 18, 1:05?am, Michael Palmer wrote: > On Sep 17, 1:33 pm, Seb wrote: > > > > > I'm making a ssl server, but I'm not sure how I can verify the > > clients. What do I actually need to place in _verify to actually > > verify that the client cert is signed by me? > > > ?50 class SSLTCPServer(TCPServer): > > ?51 ? ? ? ? keyFile = "sslcert/server.key" > > ?52 ? ? ? ? certFile = "sslcert/server.crt" > > ?53 ? ? ? ? def __init__(self, server_address, RequestHandlerClass): > > ?54 ? ? ? ? ? ? ? ? ctx = SSL.Context(SSL.SSLv23_METHOD) > > ?55 ? ? ? ? ? ? ? ? ctx.use_privatekey_file(self.keyFile) > > ?56 ? ? ? ? ? ? ? ? ctx.use_certificate_file(self.certFile) > > ?57 ? ? ? ? ? ? ? ? ctx.set_verify(SSL.VERIFY_PEER | > > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > > self._verify) > > ?58 ? ? ? ? ? ? ? ? ctx.set_verify_depth(10) > > ?59 ? ? ? ? ? ? ? ? ctx.set_session_id('DFS') > > ?60 > > ?61 ? ? ? ? ? ? ? ? self.server_address = server_address > > ?62 ? ? ? ? ? ? ? ? self.RequestHandlerClass = RequestHandlerClass > > ?63 ? ? ? ? ? ? ? ? self.socket = socket.socket(self.address_family, > > self.socket_type) > > ?64 ? ? ? ? ? ? ? ? self.socket = SSL.Connection(ctx, self.socket) > > ?65 ? ? ? ? ? ? ? ? self.socket.bind(self.server_address) > > ?66 ? ? ? ? ? ? ? ? self.socket.listen(self.request_queue_size) > > ?67 > > ?68 ? ? ? ? def _verify(self, conn, cert, errno, depth, retcode): > > ?69 ? ? ? ? ? ? ? ? return not cert.has_expired() and > > cert.get_issuer().organizationName == 'DFS' > > If I were you, I would just just hide behind apache, nginx oder > another server that does ssl. just have that server proxy locally to > your python server over http, and firewall the python server port. Good idea, however atm this is a school project so thats not really an option right now. However I might take this a bit furtherer and use that solution. From tjreedy at udel.edu Mon Sep 22 13:55:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 13:55:50 -0400 Subject: Question about sorted in Python 3.0rc1 In-Reply-To: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: josh logan wrote: Here is a minimal example showing the problematic behavior. class Int(): def __init__(self, i): self.i = i def __cmp__(self, other): return cmp(self.i, other.i) Is = [Int(i) for i in range(8)] Is.sort() # throws TypeError: unorderable types Int() < Int() sorted(Is) # ditto, if above not present The 3.0b2 version of LibRef/ Built-in Types/ Comparisions says "Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __cmp__(), __lt__(), __le__(), __gt__(), and __ge__() (in general, either __cmp__() or both __lt__() and __eq__() are sufficient, if you want the conventional meanings of the comparison operators). The notes for Mutable Sequence .sort() say nothing more. So the exception appears to be a bug, perhaps left over from when there was a plan (since aborted) to delete cmp and __cmp__. If the 3.0c1 version of the docs say the same, and no one says otherwise, I would file a report on the tracker at bugs.python.org, using the minimal example above. Terry Jan Reedy From tjreedy at udel.edu Mon Sep 29 00:08:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 00:08:21 -0400 Subject: What is not objects in Python? In-Reply-To: <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> Message-ID: George Sakkis wrote: > On Sep 28, 2:29 pm, process wrote: > >> I have heard some criticism about Python, that it is not fully object- >> oriented. > > That's not a bug, it's a feature ;-) > >> Why isn't len implemented as a str.len and list.len method instead of >> a len(list) function? > > As Terry Reedy wrote, partly history and partly practicality. There's > no philosophical reason why we write "len(x)" (generic builtin), > "x.append(1)" (method) or "del x[i]" (statement). The latter in > particular is IMHO a design wart; there's no reason for not writing it > as "x.delete(i)". As a general rule and matter of practice, methods that apply to all or most classes (or all number classes) have built-in functions that call the corresponding special method (or C-level slot). Methods that apply to one class (or just couple) are called as non-special methods. I am not sure why del is a statement rather than a function -- perhaps just because there is no return value (other than the default None). tjr From marco.bizzarri at gmail.com Sat Sep 6 02:02:28 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 6 Sep 2008 08:02:28 +0200 Subject: use str as variable name In-Reply-To: <48c1a184$0$17080$426a74cc@news.free.fr> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <48c1a184$0$17080$426a74cc@news.free.fr> Message-ID: <3f0d61c40809052302s407fede4od34eff1f2b513abf@mail.gmail.com> On Fri, Sep 5, 2008 at 9:16 PM, Bruno Desthuilliers wrote: > Marco Bizzarri a ?crit : >> >> Just a question: "generic functions" are not meant in the sense of >> "generic functions" of CLOS, am I right? > > Nope. Just "generic" in the sense that they accept any object implementing a > very minimal interface. > > If you want something like CLOS multimethods, you may be interested in > Philip Eby's ruledispatch. > Even though I loved them when I used at university, I'm not looking for them right now... but nice to know that they are available under python :-) -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From pavlovevidence at gmail.com Sat Sep 20 06:38:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 20 Sep 2008 03:38:39 -0700 (PDT) Subject: report a BUG of package setuptools-0.6c8. References: Message-ID: <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> On Sep 20, 1:11 am, Fredrik Lundh wrote: > ???? wrote: > > File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", > > line 98, in entries_finder > > log.warn("unrecognized .svn/entries format in %s", dirname) > > NameError: global name 'log' is not defined > > > global name 'log' is not defined to the line 98!!! > > please report bugs here: > > http://bugs.python.org/ Does bugs.python.org track bugs for setuptools? (Genuine question; the PEAK site doesn't list an obvious way to report bugs so I wonder if they're using bugs.python.org? Hope not....) If not, the OP should ask on the setuptools mailing list. Carl Banks From plexer at gmail.com Sun Sep 7 23:25:38 2008 From: plexer at gmail.com (James McGill) Date: Sun, 7 Sep 2008 20:25:38 -0700 (PDT) Subject: Subprocess freezes when piping from stdout. Message-ID: <62ab6734-a6ab-40c0-9131-a90684674ea6@a18g2000pra.googlegroups.com> Hi All, I'm using subprocess.Popen to run a C++ compiler and have set stdout = PIPE. The exact line of code that I am using is: process = Popen(command, stdout=PIPE) status = process.wait() This works fine until a large amount of data is written to stdout. When this occurs, my python program seems to freeze. It will no longer run or respond to Ctrl-C. I am assuming that it is stuck waiting for the process to end, but I'm not sure why this should take so long (I have left it running for hours and it never ended) At the moment the code is being executed on a Win32 environment. Is anyone aware of why this might be occurring, or of any ways around this? Does the PIPE implementation in Win32 have a maximum buffer size? Regards, James McGill From coolkid246 at googlemail.com Thu Sep 4 06:15:28 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:15:28 -0700 (PDT) Subject: kleinkredit ohne schufa in Cuxhaven kredite fuer selbststaendige privatkredite online kredit trotz guenstiger kredit kredit bonitaetspruefung privat kredit online kreditantrag + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + sofort kredit ohne schufa kredit schweiz in Hannover online kredit im kreditrechner in Rosenheim private kredite ohne schufa online kredit direkt in Wetzlar klein kredit ohne schufa kredit ohne schufa selbstaendige in Unna zinsen kredit kredit umschuldung in Altoetting billig kredit sofortkredite ohne schufa in Friedberg kredite ohne schufa in kredit mit in Sulzbach finanzierung ohne schufa kredit fuer arbeitslose in Ludwigsburg darlehen schufafrei www online kredit de in Demmin online kredite im kredit ohne schufaauskunft in Herzogtum postbank kredit online kreditangebot in Saarlouis - kredit billig online kredite fuer arbeitslose in Neuss - serioeser kredit ohne schufa kredit uni in Fulda - sofort kredit ohne schufa ratenkredite ohne schufa in Friedberg - kredit ohne schufa in sofortkredit ohne auskunft in Villingen-Schwenningen - guenstig kredit online kredite de in Wetzlar - online credit ohne kfz kredit in Mettmann - geld online kredite mit sofortzusage in Ostprignitz - kredit einkommen kredit ohne schufa ohne in Erding - credite ohne schufa online sofort kredit ohne in Hannover - guenstige kredite ohne schufa online kredit oesterreich in Oschersleben - kredit ohne schufa vergleich guenstig kredit in Worms - online kredit ohne konto kredit in Wunsiedel/Fichtelgeb. - online kredite guenstig kredit ohne auskunft in Haldensleben - kredit guenstig ohne schufa kredite ohne schufa mit in Belzig Message-ID: <9e678cd1-656e-4cd7-b695-38d7a85146a1@25g2000prz.googlegroups.com> kleinkredit ohne schufa in Cuxhaven kredite fuer selbststaendige privatkredite online kredit trotz guenstiger kredit kredit bonitaetspruefung privat kredit online kreditantrag + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + sofort kredit ohne schufa kredit schweiz in Hannover online kredit im kreditrechner in Rosenheim private kredite ohne schufa online kredit direkt in Wetzlar klein kredit ohne schufa kredit ohne schufa selbstaendige in Unna zinsen kredit kredit umschuldung in Altoetting billig kredit sofortkredite ohne schufa in Friedberg kredite ohne schufa in kredit mit in Sulzbach finanzierung ohne schufa kredit fuer arbeitslose in Ludwigsburg darlehen schufafrei www online kredit de in Demmin online kredite im kredit ohne schufaauskunft in Herzogtum postbank kredit online kreditangebot in Saarlouis - kredit billig online kredite fuer arbeitslose in Neuss - serioeser kredit ohne schufa kredit uni in Fulda - sofort kredit ohne schufa ratenkredite ohne schufa in Friedberg - kredit ohne schufa in sofortkredit ohne auskunft in Villingen- Schwenningen - guenstig kredit online kredite de in Wetzlar - online credit ohne kfz kredit in Mettmann - geld online kredite mit sofortzusage in Ostprignitz - kredit einkommen kredit ohne schufa ohne in Erding - credite ohne schufa online sofort kredit ohne in Hannover - guenstige kredite ohne schufa online kredit oesterreich in Oschersleben - kredit ohne schufa vergleich guenstig kredit in Worms - online kredit ohne konto kredit in Wunsiedel/Fichtelgeb. - online kredite guenstig kredit ohne auskunft in Haldensleben - kredit guenstig ohne schufa kredite ohne schufa mit in Belzig From uninverted at lavabit.com Mon Sep 29 17:25:09 2008 From: uninverted at lavabit.com (Nathan Seese) Date: Mon, 29 Sep 2008 23:25:09 +0200 (CEST) Subject: Converting a strng to an anonymous function Message-ID: I'm writing a program to sort files with arbitrary python code. The method I'm using for that is to pass sort an anonymous function taken from the arguments. I'm wondering how to change a raw string into an anonyous function. From afriere at yahoo.co.uk Wed Sep 24 21:40:12 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 24 Sep 2008 18:40:12 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 25, 3:16 am, Pete Forman wrote: > Asun Friere writes: > > > A canonical use of the conditional operator is in > > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). > > That fails for n == 1. So what is best? > Sorry missing parantheses. I should test, even for fragments written out as part of a sentence. %-/ > for i in range(4): > print '%d thing' % i + ('s' if i != 1 else '') > That's the corrected version of what I meant, but actually I think your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding all variables for placeholders in the tuple, is better. It's certainly more readible. From george.sakkis at gmail.com Sun Sep 21 09:07:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 21 Sep 2008 06:07:49 -0700 (PDT) Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> Message-ID: <974c3434-d409-484d-8bc4-7a3294132bd0@73g2000hsx.googlegroups.com> On Sep 21, 8:51?am, Alex wrote: > Hi all! > > I have a problem understanding the behaviour of this snippet: > > data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) > > for i in range(len(data_set)): > ? ? ds = data_set[:] > ? ? data = ds[i] > ? ? if i == 1: data['param'] = "y" > ? ? if i == 2: data['param'] = "x" > > print data_set > > This script print out: > ({'param': 'a'}, {'param': 'y'}, {'param': 'x'}) > > Why? I'm coping data_set in ds so why data_set is changed? Because you're doing a shallow copy: http://docs.python.org/lib/module-copy.html George From scottd at mcm.com Thu Sep 11 14:16:13 2008 From: scottd at mcm.com (Desmond Scott E) Date: Thu, 11 Sep 2008 14:16:13 -0400 Subject: wx Message-ID: I'm am a Python novice by chance not choice. (Although it appears to be a nice tool. Plus anything based on Monte Python can't be bad!) My Quest is to migrate a Python-based process from Windows2000/Python v2.4.2 (#67) to WindowsXP/Python v2.5.2 (r252:60911). I've searched the Python website and could find no reference to module wx. Is this an add-in module or perhaps it was replaced in v2.5.2??? References in the code are: wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated) self.SetColumnWidth(0, WX.LIST_AUTOSIZE)) idx = self.GetNextItem(idx, wx.LIST_NEXT_ALL, wx.LIST_STATE_DONTCARE) Any help would be greatly appreciated! I do have Shrubbery! Scott Scott E. Desmond Director & Manager Equity Systems Development IT Integration Lead Mellon Capital Management Corporation 500 Grant Street, Suite 4200 Pittsburgh, PA 15258 T 412.236.0405 | F 412.236.1703 scottd at mcm.com | www.mcm.com The information contained in this e-mail may be confidential and is intended solely for the use of the named addressee. Access, copying or re-use of the e-mail or any information contained therein by any other person is not authorized. If you are not the intended recipient please notify us immediately by returning the e-mail to the originator.(16b) Disclaimer Version MB.US.1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From 4g4trz802 at sneakemail.com Tue Sep 9 15:08:23 2008 From: 4g4trz802 at sneakemail.com (Michael Hoffman) Date: Tue, 09 Sep 2008 12:08:23 -0700 Subject: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles References: Message-ID: Please accept my apologies if this message was posted several times. My newsreader claimed that a timeout error kept the message from being posted, but I think it got through. From rex.eastbourne at gmail.com Wed Sep 3 21:58:12 2008 From: rex.eastbourne at gmail.com (Rex) Date: Wed, 3 Sep 2008 18:58:12 -0700 (PDT) Subject: Submitting forms over HTTPS with mechanize Message-ID: Hello, I am working on an academic research project where I need to log in to a website (www.lexis.com) over HTTPS and execute a bunch of queries to gather a data set. I just discovered the mechanize module, which seems great because it's a high-level tool. However, I can't find any decent documentation for mechanize apart from the docstrings, which are pretty thin. So I just followed some other examples I found online, to produce the following: baseurl = 'http://www.lexis.com/' br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] br.open(baseurl) br.select_form(name="formauth") br["USER_ID"]="my_user_id" br["PASSWORD"]="my_password" result = br.submit() This code hangs at br.submit(), and I can't tell what I'm doing wrong. Typically I would inspect the HTTP data with an HTTP debugging proxy (Fiddler), but I guess since this is HTTPS I can't do that. Any glaring errors in my code? By the way, does anyone have suggestions for Python modules that I should use instead of mechanize (and that are sufficiently easy)? If mechanize fails, I might try modifying some similar Perl code a friend sent me that logs into lexis.com. Thanks so much, Rex From ptmcg at austin.rr.com Tue Sep 2 10:51:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 2 Sep 2008 07:51:53 -0700 (PDT) Subject: How can we get to the end of a quote inside a string References: Message-ID: <08eff844-12b4-4fda-aa8b-276bf83872ec@x41g2000hsb.googlegroups.com> On Aug 31, 9:29?am, rajmoha... at gmail.com wrote: > Hi all, > ? ? Suppose I have a string which contains quotes inside quotes - > single and double quotes interchangeably - > ?s = "a1' b1 " c1' d1 ' c2" b2 'a2" > ? ? ?I need to start at b1 and end at b2 - i.e. I have to parse the > single quote strings from inside s. > Pyparsing defines a helper method called nestedExpr - typically it is used to find nesting of ()'s, or []'s, etc., but I was interested to see if I could use nestedExpr to match nested ()'s, []'s, AND {}'s all in the same string (like we used to do in our algebra class to show nesting of higher levels than parens - something like "{[a + 3*(b-c)] + 7}" - that is, ()'s nest within []'s, and []'s nest within {}'s). This IS possible, but it uses some advanced pyparsing methods. I adapted this example to map to your case - this was much simpler, as ""s nest within ''s, and ''s nest within ""s. I still keep a stack of previous nesting, but I'm not sure this was absolutely necessary. Here is the working code with your example: from pyparsing import Forward, oneOf, NoMatch, Literal, CharsNotIn, nestedExpr # define special subclass of Forward, that saves previous contained # expressions in a stack class ForwardStack(Forward): def __init__(self): super(ForwardStack,self).__init__() self.exprStack = [] self << NoMatch() def __lshift__(self,expr): self.exprStack.append(self.expr) super(ForwardStack,self).__lshift__(expr) return self def pop(self): self.expr = self.exprStack.pop() # define the grammar opening = ForwardStack() closing = ForwardStack() opening << oneOf(["'", '"']) closing << NoMatch() matchedNesting = nestedExpr(opening, closing, CharsNotIn('\'"'), ignoreExpr=None) # define parse-time callbacks alternate = {'"':"'", "'":'"'} def pushAlternate(t): # closing expression should match the current opening quote char closing << Literal( t[0] ) # if we find the other opening quote char, it is the beginning of # a nested quote opening << Literal( alternate[ t[0] ] ) def popClosing(): closing.pop() opening.pop() # when these expressions match, the parse action will be called opening.setParseAction(pushAlternate) closing.setParseAction(popClosing) # parse the test string s = """ "a1' b1 " c1' d1 ' c2" b2 'a2" """ print matchedNesting.parseString(s)[0] Prints: ['a1', [' b1 ', [' c1', [' d1 '], ' c2'], ' b2 '], 'a2'] -- Paul From lists at cheimes.de Mon Sep 29 04:41:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 29 Sep 2008 10:41:10 +0200 Subject: Detecting dir (tree) changes fast? In-Reply-To: References: Message-ID: robert wrote: > I want to detect changes in a directory tree fast with minimum > overhead/load. In order to check the need for sync tasks at high frequency. > It must not be 100% reliable (its also forced time periodic), so kind of > hashing would be ok. > How? Almost every modern OS has some sort of support for IO notifications. For example pynotify on Linux, kqueue on BSD or ReadDirectoryChanges on Windows. You can also use polling and check the directories yourself every few seconds but that's expensive and doesn't scale. Christian From d3vvnull at gmail.com Fri Sep 26 10:38:49 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 09:38:49 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DCDE1F.6040709@wildenhain.de> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> Message-ID: <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> I laugh in the face of danger. Give me a use case for an exploit. On Fri, Sep 26, 2008 at 8:05 AM, Tino Wildenhain wrote: > Michael Mabin wrote: > >> cursor.execute(""" >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """ % ','.join([str(x) for x in [1,5,9]]) >> > > Nope. That would be dangerous! -> google for SQL injection > > Tino > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Fri Sep 5 10:06:00 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 16:06:00 +0200 Subject: Case-insensitive string compare? In-Reply-To: <1220618002.21923.12.camel@jcd-desktop> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> <1220618002.21923.12.camel@jcd-desktop> Message-ID: <200809051606.01358.maric@aristote.info> Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez ?crit?: > On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: > > Thanks everyone for your help. I'm not opposed to using [key.lower() > > for key in stage_map] at all, I was just curious to see if there were > > any cleaner alternatives. It looks like that is what I'll be using. > > I'm not familiar with how python works internally, but coming from C++ > > it seems like "remaking" the map would be slow. However, speed is not > > my main concern in my particular situation, I'm just curious to learn > > more about python. > > You should be opposed to that particular solution. ?You have just taken > a dictionary lookup (very fast) and turned it into a list traversal > (slow). ?Even if speed isn't your main concern, this is an unnecessary > de-optimization. ?You are deliberately slowing down your program to > avoid a slightly more verbose lookup later. ?Your data structure might > as well be a list of tuples to begin with, to avoid creating a new list. > You have effectively made your keys useless as keys. > > If your lookups need to be case insensitive, make the key lower case, > and store the cased version in the value, whether as a tuple or a dict > (depending on whether you want named access). > > d = { > ? ?'foo': {'key': 'Foo', 'value': 'val1'} > ? ?'spam': {'key': 'sPAm', 'value': 'val2'} > } > > search = 'FOO'.lower() > if search in d: > ? ? result = d[search] > ? ? key = result['key'] > ? ? value = result['value'] > > The only reason I wouldn't use this solution is if you expect to have > keys that will be identical when made lowercase, but if you're doing > case-insensitive lookup, you obviously don't expect this to be an issue. > The OP has already said the keys are case-sensitive, so this is not an option, the only way to do it fast is to index upon insertion all keys in another dict, so you get in final : d = { "kEy1" : 1, "Key1" : 2} indexes = { "key1" : ["kEy1", "Key1" ] } > Cheers, > Cliff > > > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From fuzzyman at gmail.com Tue Sep 9 18:59:35 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 9 Sep 2008 15:59:35 -0700 (PDT) Subject: Cancel instance create References: <1220697080.48c25bf890ade@www.inbox.lv> <6ifb1rFq9nlnU1@mid.uni-berlin.de> Message-ID: On Sep 6, 1:23?pm, "Diez B. Roggisch" wrote: > Mohamed Yousef schrieb: > > > ?What about no Constructor , and a custom instancing function that can > > return either None or the instance wanted > > That doesn't solve the underlying problem - the instance is created. > Just because it wasn't *returned*, doesn't mean it isn't there. > > Diez def __new__(cls, *args, **kwargs): if some_condition: return None return object.__new__(cls) Michael Foord -- http://www.ironpythoninaction.com/ From h.goebel at goebel-consult.de Fri Sep 19 04:36:37 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Fri, 19 Sep 2008 10:36:37 +0200 Subject: Python and Open Office In-Reply-To: References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <48d36496$0$6665$9b4e6d93@newsspool2.arcor-online.net> Terry Reedy schrieb: > Hartmut Goebel wrote: >> The API docs are a bit hidden on the webpage. Here is the link: >> > > I wrote my comment *after* looking at the above, which I found easily > enough. After 7 pages of (helpful) explanatory text, there follow 88 > pages with hundreds of entries like this: [...] Well, I wrote my comment *before* looking at the API docs. Your are absolutely right: It is not helpful. >> Additionally teh ODF sepcs may help: >> > > v1.0 is the adopted international (ISO/IEC) standard. Specs for ODF 1.0 are available the oasis-open.org, too. So if you want to keep close the the ISO standard you surely are better off using 1.0. Alternativly you may use the 1.1 docs and skim the appendix about changes. Regards H. Goebel From larry.bates at vitalEsafe.com Sun Sep 14 12:49:08 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sun, 14 Sep 2008 11:49:08 -0500 Subject: Abstract class In-Reply-To: References: Message-ID: <0fbzk.34409$vX2.31456@bignews6.bellsouth.net> Mr.SpOOn wrote: > Hi, > I'm going to work on a project to represent some musical theory in > Python, in an object oriented way. > > I have to manage many elements of music such as notes, intervals, > scales, chords and so on. All these elements share properties and > behavior, so what I want to do is an abstract class "Note" and other > subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. > > The idea is not original, I read it in some papers where they talk > about an implementation in smalltalk. > > I want to use Python (of course) and I'd like to know what is the > practice in such a case. I mean, in python there aren't abstract > classes, but I read about some way to emulate the same behavior. > > What do you suggest me? > > Thanks, > Carlo I think the issue is one of terminology not features. Note would be a base class and it can have attributes (properties) and behavior (methods). NaturalNote, FlatNote, SharpNote would inherit from Note. -Larry From bdesth.quelquechose at free.quelquepart.fr Mon Sep 22 15:43:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 21:43:57 +0200 Subject: A bit weird dictionary behavior In-Reply-To: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: <48d7f5b4$0$20534$426a74cc@news.free.fr> bearophileHUGS at lycos.com a ?crit : > Pekka Laukkanen: >> but it still doesn't feel exactly right. Would it be worth submitting a bug? > > It feels wrong because it is. In a tidier language (Pascal, Java, etc) > a boolean and an integer must be different types. Some would argue (and some did by the time Python grew a 'bool' type) that what is wrong is to have a bool type in a language that already have a wider definition of the truth value of an expression... (snip) From ireborin at delete.this.gmail.com Mon Sep 29 20:16:41 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 02:16:41 +0200 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: On Mon, 29 Sep 2008 16:08:28 -0700 (PDT), Mensanator wrote: >> 2. I've read the help on the next one but I just find it difficult >> understanding it. >> I have; >> a=2.000001 >> b=123456.789 >> c=1234.0001 >> Hello Mensanator, thank you for answering in such a short time. < snip > >If you actually meant 7, then use %0.6e: Sorry about that; I have the habit of counting the point as a decimal place too. > >>>> print '%0.6e' % 2.000001 >2.000001e+00 >>>> print '%0.6e' % 123456.789 >1.234568e+05 >>>> print '%0.6e' % 1234.0001 >1.234000e+03 > I understood the above from help, but it's not what's been bugging me. Mea culpa, I've defined the question in a confusing way, I see that now. What I've meant to ask was, when I have 3 numbers, how would you print them with the same format which would apply to them 3 numbers. for example, I have print a,b,c now if I print them with print '%12.3f' %a,b,c the format will apply only to a, and not to b and c. I could of course write print '%12.3f %12.3f ... 3 times but that is just unpractical. Is there a way to just do something like this (not normal syntax, just my wishful thinking): print 3*'%12.3f' %a,b,c (meaning - use this format for the next 3 real numbers that come along) -- Ivan From malaclypse2 at gmail.com Mon Sep 15 16:23:51 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 15 Sep 2008 16:23:51 -0400 Subject: append on lists In-Reply-To: References: Message-ID: <16651e80809151323j205cdd45u589881216ed185d0@mail.gmail.com> On Mon, Sep 15, 2008 at 4:24 PM, Armin wrote: > Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? Because the list a has been altered in place. -- Jerry From aonlazio at gmail.com Mon Sep 8 17:31:14 2008 From: aonlazio at gmail.com (AON LAZIO) Date: Mon, 8 Sep 2008 17:31:14 -0400 Subject: The difference between __XX__ and XX method Message-ID: Hi, Pythoners. I would like to know that in some class, it uses __XX__ but in some it uses only XX for example, class Test: def __som__(self): ... def som(self): ... What does "__XX__" make the method different from XX? Thanks in advance Aonlazio -------------- next part -------------- An HTML attachment was scrubbed... URL: From almar.klein at gmail.com Tue Sep 30 06:53:49 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 30 Sep 2008 12:53:49 +0200 Subject: Weirdness comparing strings In-Reply-To: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> References: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> Message-ID: Hi, Better post complete code. I don't see where self.note_name is defined, and what are these accidentals? you write: def has_the_same_name(self, note): return self == note but this does not implicitly convert self to a string. You'll have to do in explicitly: use "return str(self) == note" instead. Hope this helps, Almar 2008/9/30 Mr. SpOOn > Hi, > I have this piece of code: > > class Note(): > ... > ... > def has_the_same_name(self, note): > return self == note > > def __str__(self): > return self.note_name + accidentals[self.accidentals] > > __repr__ = __str__ > > if __name__ == '__main__': > n = Note('B') > n2 = Note('B') > print n > print n2 > print n.has_the_same_name(n2) > > I'd expect to get "True", because their string representation is > actually the same, instead the output is: > > B > B > False > > I think I'm missing something stupid. Where am I wrong? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dudeja.rajat at gmail.com Tue Sep 30 16:28:18 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 30 Sep 2008 21:28:18 +0100 Subject: Tkinter on WIndows XP opens a blank screen. How can I get rid of it? Message-ID: Hi, I m using Tkinter and Tix to create a GUI on Windows XP. So far I've created the GUI and it just works. But the problem is as soon as I double click on the script it besides opening the GUI also opens a shell ( a blank screen) with it. Pleas suggest how can I get rid of this blank screen. My program is staring as : myRoot = Tix.Tk() myRoot.title("Test Automation") < some stuff> < ...............> myRoot.mainloop() Thanks and regadrs, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sat Sep 20 12:32:43 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Sep 2008 16:32:43 GMT Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Alex Snast wrote: > Hello > > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) > The exact equivalent would be: for i in range(10, -1, -1): print i except you virtually never want to do that in Python. Don't expect just to translate statement by statement from one language to another: normally in Python you will iterate directly over the sequence you want to process rather than trying to count loop indices with all the telegraph pole errors that result. The usual way to iterate over a sequence in reverse is: for x in reversed(seq): print x although if you know it is a list, string or other object that supports extended slicing you can also do: for x in seq[::-1]: print x this may be less clear than using 'reversed', but does allow you to specify an explicit start, stop and step if you want to do only part of the sequence. From uninverted at lavabit.com Mon Sep 29 18:35:00 2008 From: uninverted at lavabit.com (Nathan Seese) Date: Tue, 30 Sep 2008 00:35:00 +0200 (CEST) Subject: Converting a strng to an anonymous function References: Message-ID: > On Sep 29, 11:25 pm, Nathan Seese wrote: >> I'm writing a program to sort files with arbitrary python code. The >> method I'm using for that is to pass sort an anonymous function taken >> from the arguments. I'm wondering how to change a raw string into an >> anonyous function. > > Is this enough for you? > >>>> L = [1, -5, 7, -9] >>>> sorted(L, key=abs) > [1, -5, 7, -9] >>>> func = "abs" >>>> sorted(L, key=eval(func)) > [1, -5, 7, -9] >>>> func = "abs(x)" >>>> sorted(L, key=lambda x: eval(func)) > [1, -5, 7, -9] > > Bye, > bearophile Thanks, that works great! From m_palmer45 at yahoo.ca Tue Sep 23 08:37:52 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 23 Sep 2008 05:37:52 -0700 (PDT) Subject: gplt from scipy missing ? References: <67lhd4hq1gch3r18g919fjvmijen9saevv@4ax.com> Message-ID: <3d28cf9b-5463-4d35-8141-f02f3c0b3fab@y38g2000hsy.googlegroups.com> On Sep 23, 7:44 am, Ivan Reborin wrote: > On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" > > wrote: > > >I think scipy does not bundle plotting packages anymore - you may use > >whatever suits you, from other sources. > >Try matplotlib, see the wiki: > >http://wiki.python.org/moin/NumericAndScientific/Plotting > > Hello Gabriel, > thank you for answering. > > Unfortunatelly, I cannot change my plotting package, unless I indend > to change a lot of code that I'll be using in the future. I'm not a > programmer by trade, just a guy doing some calculations with already > written programms. > > Do you know, by any chance, where one could get gplt separately, or > for example, get older versions of scipy ? > I'm using python 5.2.2.. If I install scipy for python 2.3. for > example (let's assume that one still has gplt in it) will it work ? > > Best regards > Ivan Well, if you are using scipy, you must at least be doing some programming. Instead of using gplt, you could just write your data to a .csv file and feed that to gnuplot yourself. You can then use the full flexibility of gnuplot for formatting your output, without having to cross your fingers that the features you need will be covered by the gplt module. You also have your data in a readable format after calculation but before plotting - I find such intermediate data useful for debugging. From oliphant.travis at ieee.org Wed Sep 10 00:39:26 2008 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Tue, 09 Sep 2008 23:39:26 -0500 Subject: NumPy arrays that use memory allocated from other libraries or tools Message-ID: I wanted to point anybody interested to a blog post that describes a useful pattern for having a NumPy array that points to the memory created by a different memory manager than the standard one used by NumPy. The pattern shows how to create a NumPy array that points to previously allocated memory and then shows how to construct an object that allows the correct deallocator to be called when the NumPy array is freed. This may be useful if you are wrapping code that has it's own memory management scheme. Comments and feedback is welcome. The post is http://blog.enthought.com/?p=62 Best regards, -Travis Oliphant From michel at nospam.please Mon Sep 15 15:05:30 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:05:30 +0200 Subject: environment variable issue In-Reply-To: <6j7pbiF1snjoU1@mid.uni-berlin.de> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> <6j7pbiF1snjoU1@mid.uni-berlin.de> Message-ID: <48ceb1fa$0$2847$ba620e4c@news.skynet.be> Diez B. Roggisch a ?crit : > >>> sorted(os.environ.keys()) > ['HOME', 'JAVA_HOME', 'LANG', 'LANGUAGE', 'LOGNAME', 'MAIL', 'PATH', > 'PWD', 'PYTHONSTARTUP', 'SHELL', 'SHLVL', 'SSH_CLIENT', > 'SSH_CONNECTION', 'SSH_TTY', 'TERM', 'USER', '_'] > >>> > > No HOSTNAME ... Yes, no HOSTNAME. That's exactly the problem I have. Why is there no HOSTNAME? Thanks to Fredrik Lundh, I know why, now. Thanks, Michel -- Michel Leunen http://linux.leunen.com From bdesth.quelquechose at free.quelquepart.fr Mon Sep 1 14:27:29 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 20:27:29 +0200 Subject: enhancing/wrapping an existing instance of a duck In-Reply-To: References: Message-ID: <48bc5001$0$4934$426a74cc@news.free.fr> Neville Dempsey a ?crit : > Basically I have an existing (maybe a rather large and complicated > (existing) instance) that > I want to add new member to. I suppose you mean "attributes" ? > Cheers > N > > Hacks/attempts follow: > > from math import sqrt > > ############ try2 ############ > duck_obj = [ i*i for i in range(25) ] # OR a large sparse matrix > > # I "want" to an a useful property, eg length, and retain the ducks > existing properties. > # I COULD try... > setattr(duck_obj,"length",lambda: sqrt(sum(*duck_obj))) Won't work on a list. > print duck_obj.length() # returns 70 > duck_obj[0]=70+71 > print duck_obj.length() # returns 71 You obviously didn't try the above code. Traceback (most recent call last): File "", line 2, in AttributeError: 'list' object has no attribute 'length' Also and FWIW, in Python, the "sizeable" protocol is implemented using a __len__ method, that will get called by the generic len(sizeable) function. > ############ try2 ############ > # **BUT** I'd rather encapsulate a the original instance somehow. > > # I presume that I could define a class to do this somehow? > duck_obj = [ i*i for i in range(25) ] # OR a LargeSparseMatrix() > > dec = Vec(duck_obj) ??? > print dec.length() # returns 70 > duck_obj[0]=70+71 # original "large and complicated duck instance" > print dec.length() # returns 71 > > Any hints on how I need to define Vec so that any kind of duck_obj can > be decorated/wrapped/encapsulated. Depends on the type of duck_obj. In the above case, I'd inherit from list and override __len__ : >>> import math >>> class Vec(list): ... def __len__(self): ... return math.sqrt(sum(self)) ... >>> Vec(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> len(Vec(range(10))) 6 From digitig at gmail.com Wed Sep 24 10:51:30 2008 From: digitig at gmail.com (Tim Rowe) Date: Wed, 24 Sep 2008 15:51:30 +0100 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <48d9e932$0$6127$426a34cc@news.free.fr> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48d9e932$0$6127$426a34cc@news.free.fr> Message-ID: 2008/9/24 Bruno Desthuilliers : > Drake a ?crit : >> many of the library functions to raise IOError Exceptions. The >> question is: should the library function be able to just dump to >> sys.exit() with a message about the error (like "couldn't open this >> file"), > > Arrghll ! NO, DONT ! Can I put in a vote *for* the questioner's library dumping to sys.exit() on any abnormal condition? It would reduce employment competition for the rest of us. Why, yes, I am wearing my BOFH hat. How could you tell? -- Tim Rowe From brennan.ron at gmail.com Fri Sep 19 09:59:26 2008 From: brennan.ron at gmail.com (Ron Brennan) Date: Fri, 19 Sep 2008 09:59:26 -0400 Subject: Multimapping and string converting Message-ID: <26c69b160809190659i54dbfae1xd5794cd2ff433a1c@mail.gmail.com> Hello, I have a multimap dictionary with a 1 Key to N values. I want to convert the N values to a string to be used elsewhere in my program. So I have dict[(1,[1, 2 ,3 ,4])] which I have sorted When I do a print ''.join(str(dict.value())) I get [1, 2, 3, 4] as an output when I really want 1 2 3 4 Here is my code: dmapItems = dictionary.items() dmapItems.sort() for tcKey, tcValue in dmapItems: file.write('Key = %s\nValue = %s" % (tcKey, tcValue) stinger = ''.join(str(tcValue)) print stringer The Output = [145, 2345, 567, 898] I need it to be 145 2345 567 898 Can anyone see the errors of my ways? Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Sep 19 13:41:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Sep 2008 13:41:04 -0400 Subject: improving a huge double-for cycle In-Reply-To: References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <48D33497.4010403@wildenhain.de> Message-ID: Gabriel Genellina wrote: > En Fri, 19 Sep 2008 02:11:51 -0300, Tino Wildenhain > escribi?: > >> Also I never saw a list where the threading often goes wrong like >> this here - is there any special setup or is it just peoples MUA >> which screws up? > > Perhaps it's due to the newsgroup/list duality... Actually, the situation is a c.l.p <==> python-list <==> gmane.c.p.general triality. From castironpi at gmail.com Mon Sep 22 18:46:20 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 15:46:20 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <00e816f4$0$20303$c3e8da3@news.astraweb.com> Message-ID: <6602abad-3c12-4c0c-b41d-95f79cebdc31@y21g2000hsf.googlegroups.com> On Sep 22, 5:32?pm, Steven D'Aprano wrote: > On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: > > On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano > >> But that's precisely what I want to avoid: I don't want the objects to > >> ?share *any* state, not even their class. I'm not trying for a Borg or > >> ?Singleton: the user can call the factory as many times as they want, > >> ?but the objects returned shouldn't share any state. I don't know if > >> ?what I want has a name. Judging from people's reactions, I'd say > >> ?probably not. > > > Snce when are "users" ever involved > > in programming problems or programming languages ? > > What an astounding question. > > Consider a class. There are the programmers who write the class, and > there are the programmers (possibly the same people, but not necessarily) > who use the class. The second set of people, the programmers who use the > class, are *users* of the class. What else would they be? > > -- > Steven Usegrammers? From tino at wildenhain.de Mon Sep 22 08:20:50 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Sep 2008 14:20:50 +0200 Subject: Encoding.ASCII.GetBytes similar for Python ? In-Reply-To: <463f31b8-ba48-4833-8d41-9aa5f1cae189@a70g2000hsh.googlegroups.com> References: <463f31b8-ba48-4833-8d41-9aa5f1cae189@a70g2000hsh.googlegroups.com> Message-ID: <48D78DA2.1090104@wildenhain.de> Hi, Rui wrote: > Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with > the strings. I am trying to query some dns server to check its What would it do? > response using udp sockets. Some of the source below: > > # encoding: utf8 > import socket > import sys > import struct > > IP_PORT = 53 > server_host = ('4.2.2.1', IP_PORT) > transaction_id = "Q1" > TIMEOUT = 5 > > type_string = > "\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000" > trailer_string = "\u0000\u0000\u0001\u0000\u0001" > > address = 'google.com' > url_name_start, domain_name = address.split(".") > > # Query format copied from the C# example. > #QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length > + URLNameStart + (char)DomainName.Length + DomainName+ TrailerString; > query = (transaction_id + type_string + str(len(url_name_start)) + > url_name_start + > str(len(domain_name)) + domain_name + trailer_string) > print query You should refrain from trying a 1:1 translation from one language to another. This makes funny things with natural languages as well as it is horribly with computer languages. You should really read on string formatting in python. Also, while indeed usefull to understand whats going on for production use this is not recommended anymore, since you would have to randomize ports for requests instead of using fixed 53UDP. I'd recommend having a look on python adns - http://code.google.com/p/adns-python/ > sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > sock.settimeout(TIMEOUT) > sock.connect(server_host) > > sock.send(query) > data = sock.recv(512) > > for data_item in data: > try: > print chr(data_item) this is never going to work since recv() returns a string buffer, not a list of integers. HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From zxo102 at gmail.com Mon Sep 29 07:21:25 2008 From: zxo102 at gmail.com (zxo102) Date: Mon, 29 Sep 2008 04:21:25 -0700 (PDT) Subject: how to make smtplib.SMTP('localhost') work on window xp References: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Message-ID: <3623504d-b8c2-40b5-9e68-eb8f9a5c0b14@r15g2000prh.googlegroups.com> On 9?29?, ??2?53?, Lawrence D'Oliveiro wrote: > In message > <56f2097a-5129-4d1a-be82-a73e2874b... at p31g2000prf.googlegroups.com>, zxo102 > wrote: > > > SMTPServerDisconnected: Connection unexpectedly closed > > Does the SMTP server on localhost mention anything about the connection > attempt in its log? > > If you telnet/netcat to port 25 on localhost, does anything interesting > happen? Thanks for your mentioning of the SMTP server on localhost. I did not install that. After I install a free smtp server downloaded from http://www.softstack.com/freesmtp.html, and run the following python script again, everything is fine now. import smtplib server = smtplib.SMTP('localhost') ... Thanks for your message. ouyang From blabla at dungeon.de Fri Sep 26 10:53:02 2008 From: blabla at dungeon.de (hofer) Date: Fri, 26 Sep 2008 07:53:02 -0700 (PDT) Subject: Understanding (and getting rid) of optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a Message-ID: <85ec721a-b5a2-4f22-9e37-bda4a0f9eb81@z72g2000hsb.googlegroups.com> Hi, I get following warning with a python script: optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up my code: from optparse import OptionParser if __name__ == '__main__': parser = OptionParser() parser.add_option('-G','--green',action= 'store_const', const= '#00FF00' , dest='color', default='#808080', help='life is so green') parser.add_option('-R','--red',action= 'store_const', const = '#FF0000' , dest='color', help='I just see red') # add more elaborated command line parsing and help text here (options,argv) = parser.parse_args() print 'options',options I assume python wants to tell me that newer version will behave differently for numeric arguments What I wonder is: Why do I get the warning if my code doesn't try to parse any numbers? Is there any way to get rid of the warning without having to change the python version? (I noticed, the warning disappears if I remove the line printing options) thanks for any explanations. suggestions H From google at mrabarnett.plus.com Wed Sep 10 19:11:06 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 10 Sep 2008 16:11:06 -0700 (PDT) Subject: emulating read and readline methods References: <6iqts0F3v76U1@mid.uni-berlin.de> Message-ID: On Sep 10, 10:52?pm, "Diez B. Roggisch" wrote: > Sean Davis schrieb: > > > > > I have a large file that I would like to transform and then feed to a > > function (psycopg2 copy_from) that expects a file-like object (needs > > read and readline methods). > > > I have a class like so: > > > class GeneInfo(): > > ? ? def __init__(self): > > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > > gene_info.gz',"/tmp/gene_info.gz") > > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > > ? ? ? ? self.fh.readline() #deal with header line > > > ? ? def _read(self,n=1): > > ? ? ? ? for line in self.fh: > > ? ? ? ? ? ? if line=='': > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? line=line.strip() > > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > > ? ? ? ? ? ? rowvals = line.split("\t") > > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > > ? ? def readline(self,n=1): > > ? ? ? ? return self._read().next() > > > ? ? def read(self,n=1): > > ? ? ? ? return self._read().next() > > > ? ? def close(self): > > ? ? ? ? self.fh.close() > > > and I use it like so: > > > a=GeneInfo() > > cur.copy_from(a,"gene_info") > > a.close() > > > It works well except that the end of file is not caught by copy_from. > > I get errors like: > > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > > during .read() call > > CONTEXT: ?COPY gene_info, line 1000: "" > > > for a 1000 line test file. ?Any ideas what is going on? > > I'm a bit lost why the above actually works - as _read() appears to be > re-created instead of re-used for each invocation, and thus can't work IMHO. > Each generator that's created reads a single line from the file (self.fh), yields the result, and is then discarded; none of the individual generator read more than one line from the file. > Anyway, I think the real problem is that you don't follow the > readline-protocol. it returns "" if there is no more line to read, > instead you raise a StopIteration > > Diez From castironpi at gmail.com Tue Sep 9 20:28:34 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 9 Sep 2008 17:28:34 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> Message-ID: <29d81c5c-34d9-4d28-9c20-f4a15e86ca97@26g2000hsk.googlegroups.com> On Sep 9, 5:44?pm, Larry Bates wrote: > castironpi wrote: > > I will try my idea again. ?I want to talk to people about a module I > > want to write and I will take the time to explain it. ?I think it's a > > "cool idea" that a lot of people, forgiving the slang, could benefit > > from. ?What are its flaws? > > > A user has a file he is using either 1/ to persist binary data after > > the run of a single program (persistence) or 2/ share binary data > > between concurrently running programs (IPC / shared memory). ?The data > > are records of variable types and lengths that can change over time. > > He wants to change a record that's already present in the file. ?Here > > are two examples. > > > Use Case 1: Hierarchical ElementTree-style data > > > A user has an XML file like the one shown here. > > > > > ? > > ? ? Foo > > ? > > ? ... > > > He wants to change "Foo" to "Foobar". > > > > > ? > > ? ? Foobar > > ? > > ? ... > > > The change he wants to make is at the beginning of a 4GB file, and > > recopying the remainder is an unacceptable resource drain. > > > Use Case 2: Web session logger > > > A tutor application has written a plugin to a webbrowser that records > > the order of a user's mouse and keyboard activity during a browsing > > session, and makes them concurrently available to other applications > > in a suite, which are written in varying lanugages. ?The user takes > > some action, such as surfing to a site or clicking on a link. ?The > > browser plugin records that sequence into shared memory, where it is > > marked as acknowledged by the listener programs, and recycled back > > into an unused block. ?URLs, user inputs, and link text can be of any > > length, so truncating them to fit a fixed length is not an option. > > > Existing Solutions > > > - Shelve - A Python Standard Library shelf object can store a random > > access dictionary mapping strings to pickled objects. ?It does not > > provide for hierarchical data stores, and objects must be unpickled > > before they can be examined. > > - Relational Database - Separate tables of nodes, attributes, and > > text, and the relations between them are slow and unwieldy to > > reproduce the contents of a dynamic structure. ?The VARCHAR data type > > still carries a maximum size, no more flexible than fixed-length > > records. > > - POSH - Python Object Sharing - A module currently in its alpha stage > > promises to make it possible to store Python objects directly in > > shared memory. ?In its current form, its only entry point is 'fork' > > and does not offer persistence, only sharing. ?See: > > ? ?http://poshmodule.sourceforge.net/ > > > Dynamic Allocation > > > The traditional solution, dynamic memory allocation, is to maintain a > > metadata list of "free blocks" that are available to write to. ?See: > > ? ?http://en.wikipedia.org/wiki/Dynamic_memory_allocation > > ? ?http://en.wikipedia.org/wiki/Malloc > > ? ?http://en.wikipedia.org/wiki/Mmap > > ? ?http://en.wikipedia.org/wiki/Memory_leak > > The catch, and the crux of the proposal, is that the metadata must be > > stored in shared memory along with the data themselves. ?Assuming they > > are, a program can acquire the offset of an unused block of a > > sufficient size for its data, then write it to the file at that > > offset. ?The metadata can maintain the offset of one root member, to > > serve as a 'table of contents' or header for the remainder of the > > file. ?It can be grown and reassigned as needed. > > > An acquaintence writes: It could be quite useful for highly concurrent > > systems: the overhead involved with interprocess communication can be > > overwhelming, and something more flexible than normal object > > persistence to disk might be worth having. > > > Python Applicability > > > The usual problems with data persistence and sharing apply. ?The > > format of the external data is only established conventionally, and > > conversions between Python objects and raw memory bytes take the usual > > overhead. ?'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' > > currently offer this functionality, and the buffer offset obtained > > from 'alloc' can be used with all three. > > > Ex 1. > > ? ? s= struct.Struct( 'III' ) > > ? ? x= alloc( s.size ) > > ? ? s.pack_into( mem, x, 2, 4, 6 ) > > Struct in its current form does not permit random access into > > structure contents; a user must read or write the entire converted > > strucutre in order to update one field. ?Alternative: > > ? ? s= struct.Struct( 'I' ) > > ? ? x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) > > ? ? s.pack_into( mem, x1, 2 ) > > ? ? s.pack_into( mem, x2, 4 ) > > ? ? s.pack_into( mem, x3, 6 ) > > > Ex 2. > > ? ? class Items( ctypes.Structure ): > > ? ? ? ? _fields_= [ > > ? ? ? ? ? ? ( 'x1', ctypes.c_float ), > > ? ? ? ? ? ? ( 'y1', ctypes.c_float ) ] > > ? ? x= alloc( ctypes.sizeof( Items ) ) > > ? ? c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents > > ? ? c.x1, c.y1= 2, 4 > > The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. > > > Ex 3. > > ? ? s= pickle.dumps( ( 2, 4, 6 ) ) > > ? ? x= alloc( len( s ) ) > > ? ? mem[ x: x+ len( s ) ]= s > > 'dumps' is still slow and nor does permit random access into contents. > > > Use Cases Revisited > > > Use Case 1: Hierarchical ElementTree-style data > > Solution: Dynamically allocate the tree and its elements. > > > Node: tag: a > > Node: tag: b > > Node: tag: c > > Node: text: Foo > > > The user wants to change "Foo" to "Foobar". > > > Node: tag: a > > Node: tag: b > > Node: tag: c > > Node: text: Foobar > > > Deallocate 'Node: text: Foo', allocate 'Node: text: Foobar', and store > > the new offset into 'Node: tag: c'. ?Total writes 6 bytes 'foobar', a > > one-word offset, and approximatly 5- 10-word metadata update. > > > Use Case 2: Web session logger > > Dynamically allocate a linked list of data points. > > > Data: 'friendster.com' > > Data: 'My Account' > > > Allocate one block for each string, adding it to a linked list. ?As > > listeners acknowledge each data point, remove it from the linked > > list. ?Keep the head node in the 'root offset' metadata field. > > > Restrictions > > > It is not possible for persistent memory to refer to live memory. ?Any > > objects it refers to must also be located in file. ?Their mapped > > addresses must not be stored, only their offsets into it. ?However, > > live references to persistent memory are eminently possible. > > > Current Status > > > A pure Python alloc-free implementation based on the GNU PAVL tree > > library is on Google Code. ?It is only in proof-of-concept form and > > not commented, but does contain a first-pass test suite. ?See: > > ? ?http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk > > The ctypes solution for access is advised. > > You should review Zope's ZODB and/or memcached before putting in too much effort. > > -Larry Larry, I'd love to say they were exactly what I was looking for. They're not. I confess, I stopped reading ZODB when I got to the "uses pickles" part, and 'memcached' when I got to the awkward and unwieldy "SELECT FROM" part. I'm aware of both of those and my solution does something neither other does. From faltet at gmail.com Tue Sep 16 08:58:45 2008 From: faltet at gmail.com (Francesc) Date: Tue, 16 Sep 2008 05:58:45 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> Message-ID: <016bb6a7-ad62-40cb-ace9-d2c171b8ccb5@w7g2000hsa.googlegroups.com> On 15 Set, 22:09, "Aaron \"Castironpi\" Brady" wrote: > On Sep 15, 4:34 am, Francesc wrote: > > > > > On 12 Set, 14:39, "Aaron \"Castironpi\" Brady" > > wrote: > > > > > A consideration of other storage formats such as HDF5 might > > > > be appropriate: > > > > >http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > > > > There are, of course, HDF5 tools available for Python. > > > > PyTablescame up within the past few weeks on the list. > > > > "When the file is created, the metadata in the object tree is updated > > > in memory while the actual data is saved to disk. When you close the > > > file the object tree is no longer available. However, when you reopen > > > this file the object tree will be reconstructed in memory from the > > > metadata on disk...." > > > > This is different from what I had in mind, but the extremity depends > > > on how slow the 'reconstructed in memory' step is. (Fromhttp://www.pytables.org/docs/manual/ch01.html#id2506782). The > > > counterexample would be needing random access into multiple data > > > files, which don't all fit in memory at once, but the maturity of the > > > package might outweigh that. Reconstruction will form a bottleneck > > > anyway. > > > Hmm, this was a part of a documentation that needed to be updated. > > Now, the object tree is reconstructed in a lazy way (i.e. on-demand), > > in order to avoid the bottleneck that you mentioned. I have corrected > > the docs in: > > >http://www.pytables.org/trac/changeset/3714/trunk > > > Thanks for (indirectly ;-) bringing this to my attention, > > > Francesc > > Depending on how lazy the reconstruction is, would it be possible to > modify separate tables from separate processes concurrently? No, modification of different tables in the same file simultaneously is not supported yet. This is a limitation of the HDF5 library itself. The HDF Group said that they have plans to address this, but this is probably a long-term task. Francesc From sri_annauni at yahoo.co.in Fri Sep 5 01:44:04 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Fri, 5 Sep 2008 11:14:04 +0530 (IST) Subject: Creating directories Message-ID: <638982.16149.qm@web7902.mail.in.yahoo.com> Can someone tell me is there any module available to create directories?? I tried os, tempfile. I was facing some issues with os.mkdir(). The mode setting was not proper with this method. I created the directory 'stdin' with '0700' mode using os.mkdir() method. $> ls -alR stdin/ stdin/: total 12 drwx--S---?? 2 munisams munisams 4096 Sep? 3 02:00 . What is that 'S' in the group permission field?? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From mccredie at gmail.com Mon Sep 29 13:17:59 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 29 Sep 2008 10:17:59 -0700 (PDT) Subject: One class per file? References: Message-ID: > The book "Code Complete" recommends that you put only one class in a > source file, which seems a bit extreme for me. It seems that many > classes are small, so that putting several of them in a file seems > reasonable. I noticed that the decimal.py module in the standard > library has several classes, all of which of course revolve around the > "decimal" topic. Perhaps a better rule of thumb is "one idea per > file." I checked the Python style guide and there seems to be no > mention of this topic. I know this is an elementary question, but what > is the Python way of doing this? I'm in a similar situation. I've been reading Robert C. Martins book "Agile Software Development" and he suggests something similar. I would highly recommend that book by the way. He also has a couple of chapters on packaging where he makes some very good points about the reasoning behind it. Basically that you want to organize your code in such a way that package dependencies move in the direction of increasing stability. In this case stability is a metric which is defined as how likely the code is going to change in the future as determined by how many packages depend on it as opposed to how many packages it depends on. He paints a couple of scenarios in which he groups packages together that _seem_ to be related, only to see that it results in all of his packages needing to be re-built every time a change is required. Obviously we don't have to re-build python code, but it is still useful to organize your code in such a way that you don't have to constantly re-visit collections of code. I have actually started using his suggestion and have been putting one class per file. When one class depends on another I include it with a "from x import X". This makes it very easy to determine the dependencies (well, the non-abstract dependencies anyway, interfaces are a different story*). Then I put all of my classes together in a package, and make the "public" classes visible on a package level by importing them into the package __init__ module. With that being said, If I made a class that was _only_ used by one other single class, and it was clear that it would never be made visible outside of that file, I would certainly put it in the same file as that class. Heck, you might even refactor your code and determine at that time that some piece of code is only used by one other piece. It is much easier to put code together after the fact than it is to separate it, especially later in the game. My advice: don't knock it until you try it. I think my code has improved quite a bit since taking this advice. It can be much more difficult to determine which classes to package together until much later in the development cycle. One thing that can help is to find an IDE that helps you to easily switch between files. I use WingIDE, but I have even used vim with a tags file and it wasn't terrible. I wouldn't call it a hard rule, but at the same time I wouldn't just ignore it. Give it a shot and adapt your development technique to see what works best for you. Example: [mypackage/__init__.py] __all__ = ["X"] from .x import X [end mypackage/__init__.py] [mypackage/x.py] from .y import Y __all__ = ["X"] class X(object): # code - using Y hopefully [end mypackage/x.py] [mypackage/y.py] __all__ = ["Y"] class Y(object): # code [end mypackage/y.py] Matt * Interfaces in python represent an implicit dependency. The Zen of Python states: "Explicit is better than implicit". I plan to experiment with the ABC module in python 2.6/3.0. I want to make my interfaces explicitly defined, but on the other hand I still want it to be easy for people who use my code to duck-type. This _seems_ to be possible since you can .register a class with an interface after it has been created, but I'm not sure that it is very pythonic to explicitly check for an interface every time it is used. It would seem silly however to import an interface into a file where it isn't explicitly used just to document the dependency. If anybody has pointers let me know. From dblubaugh at belcan.com Thu Sep 11 18:35:43 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 11 Sep 2008 18:35:43 -0400 Subject: Has any one worked with Rpyc Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380500CFB0@AWMAIL04.belcan.com> To All, Has anyone out there worked much with Rpyc? Thanks, David This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From nagle at animats.com Tue Sep 2 12:57:05 2008 From: nagle at animats.com (John Nagle) Date: Tue, 02 Sep 2008 09:57:05 -0700 Subject: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0 In-Reply-To: References: Message-ID: <48bd6b4e$0$17174$742ec2ed@news.sonic.net> Jukka Aho wrote: > Just a tip for those who are only just cutting their teeth on Python 3.0 > and might have encountered the same problem as I did: > > When a Python (3.x) program is run on a terminal that only supports a > legacy character encoding - such as Latin 1 or Codepage 437 - all > characters printed to stdout will be automatically converted from the > interpreter's internal Unicode representation to this legacy character set. Python 5 is even stricter. Only ASCII (chars 0..127) can be sent to standard output by default. John Nagle From mccredie at gmail.com Wed Sep 10 19:26:37 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 10 Sep 2008 16:26:37 -0700 (PDT) Subject: Persuading ConfigParser to give me the section elements in the same order as the file References: <4566f721-028d-4079-90d8-7818d69d18b3@34g2000hsh.googlegroups.com> Message-ID: On Sep 10, 1:52?pm, geoffbache wrote: > Hi all, > > I recently needed to parse a file that was perfect for ConfigParser > apart from one thing: the elements in the sections, although > definitions, could in some cases clash with each other and therefore > it was important to be able to retrieve them in the same order as they > appeared in the file. > > Unfortunately ConfigParser uses ordinary dictionaries for the section > elements and they are therefore returned in an arbitrary order. > > The only solution I found was to copy ConfigParser.py and replace all > the dictionaries with "sequential dictionaries" > which are exactly like dictionaries except that elements are returned > in the order they were inserted. (seehttp://home.arcor.de/wolfgang.grafen/Python/Modules/seqdict/Seqdict.html) > > I wonder if there was a better way? For example, is there any hook > that could modify what is created by the statement > > x = {} > > I tried setting > > __builtins__.dict = ndict.seqdict > > But that didn't seem to have any effect on the above statement. > > As a secondary question, I find sequential dictionaries to be an > essential part of programming in Python and I use them all the time. I > wondered a bit if there were any plans or proposals to include them as > part of the Python library? > > Regards, > Geoff Bache Have a look at this: http://www.python.org/dev/peps/pep-0372/ Looking at the config parser module, it looks like there are only a couple of places where {} is used. I would create a mixin class to replace the offending methods. That should work because it looks like you only have to replace "__init__" and "add_section". So... class OrderedConfigParserMixin: def __init__(self, defaults=None): self._sections = ndict.seqdict() self._defaults = ndict.seqdict() if defaults: for key, value in defaults.items(): self._defaults[self.optionxform(key)] = value def add_section(self, section): """Create a new section in the configuration. Raise DuplicateSectionError if a section by the specified name already exists. """ if section in self._sections: raise DuplicateSectionError(section) self._sections[section] = ndict.seqdict() # Then you can use this to create your own ordered config parsers. Note that # multiple inheritance in python uses a breadth first search. If you want # the methods on your mixin to get called instead of the methods on the # original class you must include the mixin first. from ConfigParser import RawConfigParser, ConfigParser, SafeConfigParser class OrderedRawConfigParser(OrderedConfigParserMixin, RawConfigParser): pass class OrderedConfigParser(OrderedConfigParserMixin, ConfigParser): pass class OrderedSafeConfigParser(OrderedConfigParserMixin, SafeConfigParser): pass I don't know if this is the _best_ approach, but it is certainly much preferred over monkey patching the built-ins module. Note that I haven't tested any of the above code. Matt From notvalid2 at sbcglobal.net Mon Sep 8 05:51:54 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 08 Sep 2008 02:51:54 -0700 Subject: Syntax Problem with strptime in Python 2.4 Message-ID: Apparently, use of strptime of datetime needs a workaround in Python 2.4 to work properly. The workaround is d = datetime.datetime(*(time.strptime(date_string, format)[0:5])). However, when I try to use it, or even use it the regular way, it fails with AttributeError: type object 'datetime.datetime' has no attribute 'datetime'. From the following code code segment: format = '%Y%m%d_%H%M%S' #d=datetime.strptime('20080321_113405', format)-- typical use print time.strptime('20080321_113405', format)[0:5] d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5]) Does anyone know how to make this work in 2.4? If not, is there a way to achieve the same result? -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From sturlamolden at yahoo.no Tue Sep 23 09:23:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 06:23:12 -0700 (PDT) Subject: Python is slow? Message-ID: I have recently been playing with a kd-tree for solving the "post office problem" in a 12-dimensional space. This is pure cpu bound number crunching, a task for which I suspected Python to be inefficient. My prototype in Python 2.5 using NumPy required 0.41 seconds to construct the tree from 50,000 samples. Unfortunately, searching it felt a bit slow, finding the 11 nearest-neighbours of 1,000 points took 29.6 seconds (and there were still 49,000 to go). Naturally, I blamed this on Python. It would be 100 times faster if I used C++, right? After having a working Python prototype, I resorted to rewrite the program in C++. The Python prototype took an hour to make, debug and verify. The same thing in C++ took me almost a day to complete, even with a working prototype as model. To my surprise, the resulting beast of C++ required 64.3 seconds to construct the same kd-tree. Searching the tree was not faster either, 1,000 points required 38.8 seconds. I wasted a day, only to find my Python prototype being the faster. We may conclude that I'm bad at programming C++, but I suspect that is not the case here. Albeit micro-benchmarks may indicate that Python is 100-200 times slower than C++, they may not be applicable to the real world. Python can be very efficient. And when combined with libraries like NumPy, beating it's performance with hand-crafted C++ is difficult. At least, my 10 years experience programming scientific software in various languages was not sufficient to beat my own Python prototype with C++. That is not to say I have never seen C++ run a lot faster than Python. But it tends to be very short pieces of CPU bound code, no more than a function or two. But as the problem grows in complexity, C++ accumulates too much of its own bloat. From mayariasxf at gmail.com Tue Sep 30 18:42:00 2008 From: mayariasxf at gmail.com (mayariasxf at gmail.com) Date: Tue, 30 Sep 2008 15:42:00 -0700 (PDT) Subject: Visit this sites please Message-ID: <64b49ebf-94df-42f1-8b5a-2edea29f2014@i76g2000hsf.googlegroups.com> http://forums.vogue.com.au/member.php?u=91686 tube8 http://forums.vogue.com.au/member.php?u=91688 redtube http://forums.vogue.com.au/member.php?u=91689 pornhub http://forums.vogue.com.au/member.php?u=91690 yobt http://www.dynamicdrive.com/forums/member.php?u=33924 tube8 http://www.dynamicdrive.com/forums/member.php?u=33925 redtube Visit this sites please From sturlamolden at yahoo.no Fri Sep 26 16:24:01 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 26 Sep 2008 13:24:01 -0700 (PDT) Subject: Quick sort implementation in python References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: On 26 Sep, 08:43, Terry Reedy wrote: > That depends on the data structure. ?Access to a singly-linked list is > by linear scanning from the front. Which is one reason why mergesort i preferred over quicksort for lists. Pythons built-in sort is a variant of mergesort and should be fast for linked lists and array lists alike. From i3dmaster at gmail.com Thu Sep 11 12:20:53 2008 From: i3dmaster at gmail.com (i3dmaster) Date: Thu, 11 Sep 2008 09:20:53 -0700 (PDT) Subject: conditional install/distribution Message-ID: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> Is there a feature in distutils or easy_install to specify what version of python that the target package can be installed? For example, if a package has a module that only needed if the python version < 2.6, is there a way to specifiy that in setup.py or easy_install cfg file so that when installing to python >= 2.6, this module wouldn't be installed?? Thanks, Jim From paulprobert at sbcglobal.net Tue Sep 30 21:21:33 2008 From: paulprobert at sbcglobal.net (Paul Probert) Date: Tue, 30 Sep 2008 20:21:33 -0500 Subject: Python arrays and sting formatting options In-Reply-To: References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: Grant Edwards wrote: > On 2008-09-30, Peter Pearson wrote: >> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: >>> 1. Multi dimensional arrays - how do you load them in python >>> For example, if I had: >>> ------- >>> 1 2 3 >>> 4 5 6 >>> 7 8 9 >>> >>> 10 11 12 >>> 13 14 15 >>> 16 17 18 >>> ------- >>> with "i" being the row number, "j" the column number, and "k" the .. >>> uhmm, well, the "group" number, how would you load this ? >>> >>> If fortran90 you would just do: >>> >>> do 10 k=1,2 >>> do 20 i=1,3 >>> >>> read(*,*)(a(i,j,k),j=1,3) >>> >>> 20 continue >>> 10 continue >>> >>> How would the python equivalent go ? > > You would drag yourself out of the 1960s, install numpy, and > then do something like this: > > a = read_array(open("filename.dat","r")) > >> Since you're coming from the FORTRAN world (thank you for that >> stroll down Memory Lane), you might be doing scientific >> computations, and so might be interested in the SciPy package >> (Google scipy), which gives you arrays and matrices. Don't >> expect to be able to use it without learning some Python, >> though. > > If not full-up scipy (which provides all sorts of scientific > and numerical-analysis stuff), then at least numpy (which > provides the basic array/matrix operations: > > http://numpy.scipy.org/ > > Though the software is free, the documentation isn't. You've > got to buy the book if you want something to read. IMO, it's > definitely worth it, and a good way to support the project even > if you don't really need something to keep your bookends apart. clip ... The book is free now, as of Aug 21, 08. http://www.tramy.us/guidetoscipy.html Paul Probert From showellshowell at gmail.com Mon Sep 15 10:06:19 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Mon, 15 Sep 2008 07:06:19 -0700 (PDT) Subject: Representation of python code ? References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> On Sep 15, 4:38?am, Maric Michaud wrote: > Le Sunday 14 September 2008 15:44:03 Barak, Ron, vous avez ?crit?: > > > Hi Guys, > > Is there a script/application, which gets as input python code, and > > produces a (graphic) representation of the inter-relationships between its > > classes/functions ? Bye, > If you can't find anything that's already packaged up and polished, one possibility is to use the parser and/or compiler.ast modules in Python to analyze your code, then produce something that graphviz can consume. Graphviz is something really nice to have in your bag of tricks, anyway. http://www.graphviz.org/ > None I know of. Not saying that it would be unfeasible, but it would be a hard > job, given the fact that most of relationships are purely dynamic. > > How such an application would find the relationship (composition) between A > and B without executing this code ? > I'm not sure this is the best counterexample. You can see statically that A potentially creates an instance of the B class. > class A : > ? ? def __init__(self) : > ? ? ? ? ?self._b = B() > > class B : pass > From sjmachin at lexicon.net Wed Sep 10 19:54:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Sep 2008 16:54:35 -0700 (PDT) Subject: emulating read and readline methods References: Message-ID: On Sep 11, 8:01?am, MRAB wrote: > On Sep 10, 6:59?pm, Sean Davis wrote: > > > I have a large file that I would like to transform and then feed to a > > function (psycopg2 copy_from) that expects a file-like object (needs > > read and readline methods). > > > I have a class like so: > > > class GeneInfo(): > > ? ? def __init__(self): > > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > > gene_info.gz',"/tmp/gene_info.gz") > > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > > ? ? ? ? self.fh.readline() #deal with header line > > > ? ? def _read(self,n=1): > > ? ? ? ? for line in self.fh: > > ? ? ? ? ? ? if line=='': > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? line=line.strip() > > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > > ? ? ? ? ? ? rowvals = line.split("\t") > > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > > ? ? def readline(self,n=1): > > ? ? ? ? return self._read().next() > > > ? ? def read(self,n=1): > > ? ? ? ? return self._read().next() > > Each time readline() and read() call self._read() they are creating a > new generator. They then get one value from the newly-created > generator and then discard that generator. What you should do is > create the generator in __init__ and then use it in readline() and > read(). > > > > > ? ? def close(self): > > ? ? ? ? self.fh.close() > > > and I use it like so: > > > a=GeneInfo() > > cur.copy_from(a,"gene_info") > > a.close() > > > It works well except that the end of file is not caught by copy_from. > > I get errors like: > > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > > during .read() call > > CONTEXT: ?COPY gene_info, line 1000: "" > > > for a 1000 line test file. ?Any ideas what is going on? > > I wonder whether it's expecting readline() and read() to return an > empty string at the end of the file instead of raising StopIteration. Don't wonder; ReadTheFantasticManual: read( [size]) ... An empty string is returned when EOF is encountered immediately. ... readline( [size]) ... An empty string is returned only when EOF is encountered immediately. From george.sakkis at gmail.com Tue Sep 9 11:24:39 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Sep 2008 08:24:39 -0700 (PDT) Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: <07c8886d-a0b5-4103-adcf-c6c2b89ce531@z72g2000hsb.googlegroups.com> On Sep 9, 9:12 am, "metaperl.com" wrote: > Pyparsing has a really nice feature that I want in PLY. I want to > specify a list of strings and have them converted to a regular > expression. > > A Perl module which does an aggressively optimizing job of this is > Regexp::List -http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/Lis... > > I really dont care if the expression is optimal. So the goal is > something like: > > vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| > u|ii|i)' > > Is there a public module available for this purpose? I was about to start a thread about a very similar problem; hope I'm not hijacking this thread. However I am interested in a solution that (1) scales to a potentially large number of alternate strings (hundreds or thousands), which will hit, sooner or later, some max limit in the builtin regexps and (2) is not limited to strings but can be used for arbitrary objects. Therefore I am looking for a different approach, perhaps a specialization of the general regexp search algorithm. More formally, given (a) an input sequence I and (b) a set of 'censored' sequences S, find and remove all the sequences in S that appear in I. For instance, if S = set([(a,), (a,b), (a,c), (c,), (d,a)]) and I = (x, a, b, c, y, d, a, b), the filtered sequence would be: O = (x, y, b) i.e. the censored subsequences are (a,b), (c,), and (d,a). As with regexps, if sequence `x` is a prefix of `y`, the longer sequence `y` wins when both match (e.g. if (a,b) matches, it supersedes (a,)). For extra bonus, the algorithm should remove overlapping subsequences too, i.e. for the input I above, the output would be (x, y) since both (d,a) and (a,b) would match for (d,a,b). With respect to complexity, I am mainly interested in len(S); len(I) is small for my application, typically no more than 10. Of course, an algorithm that scales decently in both len(S) and len(I) would be even better. Any ideas or relevant links ? George PS: This is not a homework ;) From code at pizzashack.org Wed Sep 3 03:09:18 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 3 Sep 2008 03:09:18 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i6pq9Fmcad7U2@mid.uni-berlin.de> References: <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <6i6pq9Fmcad7U2@mid.uni-berlin.de> Message-ID: <20080903070918.GW29228@dragontoe.org> On Wed, Sep 03, 2008 at 06:40:10AM +0000, Marc 'BlackJack' Rintsch wrote: > On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote: > > >> And if they model an action there must be some way to activate the > >> action > > > > That's a reasonable assumption, but as I also said, the object might > > just describe the action -- essentially the equivalent of a struct in C. > > ``struct``\s in C describe *actions*!? Functions do this. struct run { int speed; direction_type direction; }; Not a function. Describes an action. Sure, you'll probably never see this example in a real program. But that doesn't mean you can't do it, and it doesn't make it inherently wrong. Someone somewhere might very well find a legitimate use case. Besides which, I was not talking about programmatic actions; I was talking about verbs -- actions that people do. You are putting narrow-minded constraints on your ideas about how to program. Sometimes thinking outside the box is useful... > >> but the instances of `Popen` are no actions. There's no way to > >> "execute" a `Popen` instance. > > > > Yes there is... you execute it when you instantiate the object. > > But then the instance itself isn't an action but the result of one. So? A class doesn't represent an action, remember? It represents a thing. Isn't that what you said? > > At the time of instantiation, you "open" the "P" (pipes). For an > > object which describes an action, I think it's perfectly sensible that > > instantiation is when the action occurs, [?] > > Here I disagree again. Because the type/class name of an instance should > be a name of the "thing"/concept of the instance, not the action used to > create it. You're making an assertion based on your personal opinion. That's a fine guideline, but there's no requirement to do so. I can name my classes anything I want. There's no reason I can't write: Class Think: def __init__: self.thoughts = happy print "Thinking %s thoughts!" %s self.thoughts This is a silly example that does nothing useful, but that doesn't exclude the possibility that someone might conceive of a similar example that is actually useful. Maybe you're just not creative enough, and I'm too lazy. > >> Maybe from your POV. Facts: It doesn't use the `popen()` function > > > > So? Neither does the C version of popen(), but that function is still > > called popen()! > > Now you lost me. The C version of `popen()` isn't recursive, why on > earth should it be, so what's that statement supposed to mean!? Sorry, did I go too fast for you? Your "facts" seem to be suggesting that for Python's Popen class to be named Popen, it should use the C popen() function. I can't imagine any other reason why you mentioned it doesn't... It need not use popen() to do what popen() does... In fact, it need not do what popen() does to be called Popen! It's just a name... the author can call it whatever he wants. As it happens, it was called Popen because it does essentially what popen() does. The fact that it doesn't USE popen() to do it is... not interesting? > >> to three file objects, more attributes and methods), the function used > >> on Windows under the hood is called `CreateProcess()` not > >> `CreatePipe()`. > > > > How does Windows implement popen()? [I think they call it _popen() > > though...] > > Doesn't matter because the `Popen()` implementation doesn't use `popen()`. No, that's exactly why it *does* matter. Because neither is popen() implemented using popen()! See! There you go again! Does it matter, or doesn't it?!? What are you trying to say?!? Sorry, but you are contradicting yourself (repeatedly), and your arguments don't make any sense. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From upton at virginia.edu Mon Sep 8 12:23:02 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 8 Sep 2008 12:23:02 -0400 Subject: lacking follow-through In-Reply-To: <99113520-2fa2-46ac-9894-ea78372ff610@c58g2000hsc.googlegroups.com> References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <086a0906-c6f1-489c-91ab-f6a4f9e1ae3f@59g2000hsb.googlegroups.com> <99113520-2fa2-46ac-9894-ea78372ff610@c58g2000hsc.googlegroups.com> Message-ID: <5504f9ac0809080923v70fe58ccn2e4aaf3d5102d725@mail.gmail.com> On Sun, Sep 7, 2008 at 10:59 PM, castironpi wrote: > On Sep 7, 7:34 pm, MRAB wrote: >> On Sep 7, 11:28 pm, "Eric Wertman" wrote: >> >> > +1 Bot >> >> I think it's like duck typing: it doesn't matter whether he's actually >> a bot, only whether he behaves like one. > > Do you support the bot interface and methods? > -- And this is an example of why you get +1 bot. From bellman at lysator.liu.se Mon Sep 15 10:28:34 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Mon, 15 Sep 2008 14:28:34 +0000 (UTC) Subject: Unable to see os.environ['COLUMNS'] References: <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> Message-ID: Tim Chase writes: >> $ export COLUMNS >> >> $ python -c "import os; print os.environ['COLUMNS']" >> 80 > This works well, and also manages to keep up to date across runs > as window-size changes. Now try this: $ export COLUMNS $ python -c "import time, os; time.sleep(60); print os.environ['COLUMNS']" and change the window width during that sleep. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "Don't tell me I'm burning the candle at both ! bellman @ lysator.liu.se ends -- tell me where to get more wax!!" ! Make Love -- Nicht Wahr! From bborcic at gmail.com Fri Sep 19 06:15:58 2008 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 19 Sep 2008 12:15:58 +0200 Subject: dict generator question In-Reply-To: References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: Gerard flanagan wrote: > George Sakkis wrote: .. >> >> Note that this works correctly only if the versions are already sorted >> by major version. >> > > Yes, I should have mentioned it. Here's a fuller example below. There's > maybe better ways of sorting version numbers, but this is what I do. Indeed, your sort takes George's objection too litterally, what's needed for a correct endresult is only that major versions be grouped together, and this is most simply obtained by sorting the input data in (default) string order, is it not ? > > > data = [ "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.1.1.1", "1.3.14.5", > "1.3.21.6" ] > > from itertools import groupby > import re > > RXBUILDSORT = re.compile(r'\d+|[a-zA-Z]') > > def versionsort(s): > key = [] > for part in RXBUILDSORT.findall(s.lower()): > try: > key.append(int(part)) > except ValueError: > key.append(ord(part)) > return tuple(key) > > data.sort(key=versionsort) > print data > > datadict = \ > dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) > print datadict > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Fri Sep 19 00:46:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Sep 2008 00:46:02 -0400 Subject: improving a huge double-for cycle In-Reply-To: <00e2e17d$0$20331$c3e8da3@news.astraweb.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote: > >> Now the obvious winner is pruebono - even unoptimized, using sets seems >> to be *way* faster than even the most optimized corrected version of >> your algorithm. > > I'm not being snarky about losing priority here, but I submitted > essentially the same solution two hours earlier than pruebono. > > Are people not seeing my posts? Have I been kill-filed by everyone except > Mensator? I also asked a question about HTTPError and I haven't seen any > responses at all. Yes, after figuring out what to do from the original post, I saw yours and then Pruebono's and decided that since two people had submitted the jackpot algorithm, I need not say more. I will say this: this solution amounts to finding equivalence classes (the sets of items with a given 'key') and then finding the classes (sets) with more than one member. Defaultdict is great for this. tjr From mensanator at aol.com Thu Sep 18 13:29:44 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 18 Sep 2008 10:29:44 -0700 (PDT) Subject: How to Determine Name of the Day in the Week References: <0928a498-1cc0-48c7-985e-4faf019d8a70@m3g2000hsc.googlegroups.com> Message-ID: <3205ea81-4a3e-4c92-a9d8-53bb4ee2f7b6@j22g2000hsf.googlegroups.com> On Sep 18, 12:01?am, Steven D'Aprano wrote: > On Wed, 17 Sep 2008 20:34:02 -0700, Mensanator wrote: > > And technically, weeks begin on Sunday, not Monday, but business likes > > to think of Monday as day 0 of the week and it doesn't conflict with any > > prior date format. > > There's no "technically" about it. Sure there is, within the tradition I was refering to. Within that tradition, the start of the week isn't arbitray. Besides, the documentation specifically says it's using the European system By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. So, by default, Python doesn't use the American convention of weeks starting on Sunday (an American technicality). This does not contradict what I said. > It's an arbitrary starting point, Amongst different systems, it's never arbitrary within a system. > and > consequently there are different traditions to it, even in English. I know, that's why I added the caveat. > > Besides, I don't think many businesses think of "day 0" at all. Most > people outside of IT start counting from 1, not 0. The accounting software I use to fill out my timesheet electronically was obviously created by IT people and the week begins on Monday. Their will is, of course, forced on all employees whether they are IT or not. > > In British Commonwealth countries, Sunday is the last day of the week, > not the first, although under American influence that's changing in > Australia at least. > > In Poland, the week begins with Monday ("poniedzia?ek"). Tuesday, > "wtorek", means "second day". Other Slavic countries also start with > Monday. > > Similarly, the Lithuanian calendar simple enumerates the days of the > week, starting with Monday, "pirmadienis" ("first day"). > > In China, there are at least three different systems of naming the week > days. In two of them, the week starts with Sunday, but in the third > system, Sunday is "zhoumo" ("cycle's end") and Monday is zhouyi ("first > of cycle"). Last time I was in Borders, I don't recall seeing any Polish, Lithuanian or Chinese calendars for sale. > > -- > Steven From python.list at tim.thechases.com Wed Sep 17 06:52:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 17 Sep 2008 05:52:07 -0500 Subject: File Reading related query In-Reply-To: References: Message-ID: <48D0E157.6010307@tim.thechases.com> > I am talking about text file which contain multiple lines e.g following > three lines are there in my textfile.txt > > this is python list > where we get support > from geeks > > I want > > sentence = this is python list where we get support from geeks > > whereas when i use simple read() i get something like this > > sentence = this is python list\nwhere we get support\nfrom geeks You mean sentence = myfile.read().replace('\n', ' ') ? If you want to compact multiple spaces, such as this is the python__ list where__ __we get support (where "_" represents a space) and you want that to become this is the python list where we get support you'd have to use slightly more intelligent processing, and explain the behavior you'd want if more than one blank line was encountered. But for a first pass: import re r = re.compile(r"\s*\n") sentence = r.sub(" ", myfile.read()) -tkc From kushaldas at gmail.com Fri Sep 5 05:34:00 2008 From: kushaldas at gmail.com (Kushal Das) Date: Fri, 5 Sep 2008 15:04:00 +0530 Subject: configure kdevelop for python In-Reply-To: <2f21628f-80dd-4710-b0be-2b1c772e5698@l33g2000pri.googlegroups.com> References: <2f21628f-80dd-4710-b0be-2b1c772e5698@l33g2000pri.googlegroups.com> Message-ID: <200809051504.00439.kushaldas@gmail.com> On Sunday 31 August 2008 01:59:11 pm Sindhu wrote: > am a newbie to python language and kdevelop, so i would like to know > how to configure kdevelop for python programming? complete with a > debugger? Read here http://www.kde.in/index.php/Getting_started_with_KDevelop Kushal -- Fedora Ambassador, India http://kushaldas.in http://dgplug.org (Linux User Group of Durgapur) From pavlovevidence at gmail.com Sat Sep 13 03:43:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 13 Sep 2008 00:43:46 -0700 (PDT) Subject: question about python References: Message-ID: On Sep 13, 12:15 am, fishfin wrote: > I was working through a tutorial about how to write a server using > python (the url is bellow). I am sure that the server is working to > some degree because when the server is running localhost:8080 just > keeps trying to load until it times out. I would like to know how to > send information through the server to my browser? > > I was working through this tutorial:http://python.about.com/od/networkingwithpython/ss/PythonWebServer.htm > > and my final code is like this: > > import socket > > host = '' > port = 8080 > > c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > > c.bind((host, port)) > > c.listen(1) > > while 1: > csock, caddr = c.accept() > cfile = csock.makefile('rw', 0) It looks like everything after this line needs to be indented. Besides that, nothing jumps out at me, though I don't do direct socket programming a lot. > line = cfile.readline().strip() > > cfile.write('HTTP/1.0 200 OK\n\n') > cfile.write('Welcome %s!' % > (str(caddr))) > cfile.write('

Follow the link...

') > cfile.write('All the server needs to do is ') > cfile.write('to deliver the text to the socket. ') > cfile.write('It delivers the HTML code for a link, ') > cfile.write('and the web browser converts it.



') > cfile.write('
Click me!
') > cfile.write('

The wording of your request was: "%s"' %(line)) > cfile.write('') > > cfile.close() > csock.close() Carl Banks From stefan_ml at behnel.de Mon Sep 15 14:15:39 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 15 Sep 2008 20:15:39 +0200 Subject: Zsi interoperability In-Reply-To: References: Message-ID: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Mailing List SVR wrote: > I have to implement a soap web services from wsdl, the server is > developed using oracle, is zsi or some other python library for soap > interoperable with oracle soa? No idea, but I'd definitely try soaplib before ZSI. Stefan From roy at panix.com Wed Sep 3 16:54:12 2008 From: roy at panix.com (Roy Smith) Date: Wed, 03 Sep 2008 16:54:12 -0400 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > Roy Smith wrote: > > > In article , > > Peter Otten <__peter__ at web.de> wrote: > > > >> > I might take it one step further, however, and do: > >> > > >> >> fields = line.split()[:2] > >> >> a, b = map(int, fields) > >> > > >> > in fact, I might even get rid of the very generic, but conceptually > >> > overkill, use of map() and just write: > >> > > >> >> a, b = line.split()[:2] > >> >> a = int(a) > >> >> b = int(b) > >> > >> If you go that route your next step is to introduce another try...except, > >> one for the unpacking and another for the integer conversion... > > > > Why another try/except? The potential unpack and conversion errors exist > > in both versions, and the existing try block catches them all. Splitting > > the one line up into three with some intermediate variables doesn't change > > that. > > As I understood it you didn't just split a line of code into three, but > wanted two processing steps. These logical steps are then somewhat remixed > by the shared error handling. You lose the information which step failed. > In the general case you may even mask a bug. > > Peter Well, what I really wanted was two conceptual steps, to make it easier for a reader of the code to follow what it's doing. My standard for code being adequately comprehensible is not that the reader *can* figure it out, but that the reader doesn't have to exert any effort to figure it out. Or even be aware that there's any figuring-out going on. He or she just reads it. From gslindstrom at gmail.com Tue Sep 2 23:05:15 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Tue, 2 Sep 2008 22:05:15 -0500 Subject: pyArkansas on October 4th Message-ID: We are pleased to announce that pyArkansas will be held on the campus of University of Central Arkansas (www.uca.edu) on October 4th. Scheduled classes in the morning include Python 101 taught by Dr. Bernard Chen (incoming faculty at UCA but having taught the course at Georgia State University), "Python 201" taught by Jeff Rush (Dallas Python Users Group) and Python for Unix/Linux Administration (Noah Gift teaching on his -- and Jeremy Jones' -- newly released OReilly title). The afternoon features talks and a panel discussion along with lots of great give aways and swag. Due to limitations of physical space we must close registration at 100 participants (in honor of my first OS, SunOS, we may go to 110). Check out our wiki at http://pycamp.python.org/Arkansas/HomePage. There's no registration fee, so if you're in the area stop on by...we are looking forward to a great day. Greg Lindstrom Python Artists of Arkansas (PyAR^2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From afriere at yahoo.co.uk Tue Sep 16 22:03:49 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 16 Sep 2008 19:03:49 -0700 (PDT) Subject: Is 'x' an instance of a new-style class? References: <878wts76dc.fsf@mulj.homelinux.net> Message-ID: <937810d9-9525-4f78-a75e-84395a655292@r15g2000prh.googlegroups.com> On Sep 16, 8:05 pm, Hrvoje Niksic wrote: > "Gabriel Genellina" writes: > > In Python you would write isinstance(x, object). > > It will return True for all Python objects (except perhaps those that > fiddle with metaclasses), not only for instances of new-style classes. > Unlike say isinstance(x.__class__, type) which should distinguish between instances of new and old-style classes. From invalid at invalid Fri Sep 19 10:40:21 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 19 Sep 2008 09:40:21 -0500 Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> Message-ID: On 2008-09-19, Steve Holden wrote: > Grant Edwards wrote: >> On 2008-09-18, Lawrence D'Oliveiro wrote: >>> In message >>> <973f75d4-90f5-4930-9107-15fc8651196d at v16g2000prc.googlegroups.com>, sui >>> wrote: >>> >>>> Traceback (most recent call last): >>>> File "mail5.py", line 21, in >>>> session = smtplib.SMTP(SMTPserver,port) >>>> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ >>>> (code, msg) = self.connect(host, port) >>>> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect >>>> self.sock.connect(sa) >>>> File "", line 1, in connect >>>> then conncetion time out..... >>> Could it be your ISP is blocking outgoing connections to port >>> 25? >> >> gmail doesn't accept mail via SMTP on port 25. >> > I was going to say that's boloney until I checked my settings - it's a > year or more since I set gmail up with Thunderbird. > > smtp.gmail.com accepts TLS connections on port 587. I should have been a bit more specific and said that the relay/smarthosts at smtp.gmail.com don't accept SMTP mail via port 25. The normal incoming SMTP servers pointed to by gmail.com's MX records do accept non-relay e-mail on port 25. They are, however, picky about IP addresses from which they'll accept connections (trying to connect via a commercial VPN server fails, but connecting via other machines works). -- Grant Edwards grante Yow! WHO sees a BEACH BUNNY at sobbing on a SHAG RUG?! visi.com From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 04:09:52 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 10:09:52 +0200 Subject: Er, one -lime- or two. In-Reply-To: <2ac98076-0163-45c4-8269-e6c1a1d70d7f@c65g2000hsa.googlegroups.com> References: <2ac98076-0163-45c4-8269-e6c1a1d70d7f@c65g2000hsa.googlegroups.com> Message-ID: <48db473e$0$24356$426a74cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : > A Python walks into a bar and orders a complex data structure. > Bartender says, "One line or two?" I don't think that one will have much success in parties !-) From deets at nospam.web.de Wed Sep 10 17:14:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 23:14:42 +0200 Subject: formating a filesystem with python In-Reply-To: References: Message-ID: <6iqrm2F3rqcU1@mid.uni-berlin.de> Ricardo Tiago schrieb: > Hi all, > > is there a package in python that allows to mount/umount and format > (to ext3) a filesystem? I know that this is possible by just calling > the os commands 'mount/umount and mkfs' but this would imply to have > to change sudoers to run the script as non-root. well, that's a very sensible unix-restriction. and you can't overcome that. IOW: no, there is no such thing. Diez From jdallen2000 at yahoo.com Mon Sep 22 01:35:10 2008 From: jdallen2000 at yahoo.com (James Dow Allen) Date: Sun, 21 Sep 2008 22:35:10 -0700 (PDT) Subject: Milenko Kindl rtegdgd References: <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> <59hdd4t65g9gb5kq535b2pkfj939hiruqv@4ax.com> Message-ID: <59239eed-cc47-4281-b146-04fb28264d61@n33g2000pri.googlegroups.com> On Sep 22, 5:08?am, Martin Griffith wrote: > On Sun, 21 Sep 2008 15:00:16 -0700 (PDT), in sci.electronics.design H > >Well, that's not C isn't it, more like Snobol or RPG/2 > > It's better to say > "that's not C, is it" > > I don't know why, but that's the way it works..... I recall a befuddled ESL student who missed a question based on "Isn't that girl pretty?" "Isn't she!!" James Hussein Allen From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 03:24:18 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Tue, 16 Sep 2008 00:24:18 -0700 Subject: Cross-platform socket.getsockopt and struct.unpack (or socket timeout)? Message-ID: M2Crypto has some old code that gets and sets socket timeouts in http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/Connection.py, for example: def get_socket_read_timeout(self): return timeout.struct_to_timeout(self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout.struct_size())) The helper timeout module is here: http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/timeout.py I just noticed that this does not work on Windows. Here's a small test program that demonstrates the issue using native and Cygwin Python 2.5.2, 32-bit Windows XP (no M2Crypto needed for this): import struct import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) timeout_struct = s.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.calcsize('ll')) print "%d:'%s'" % (len(timeout_struct), timeout_struct) print struct.unpack('ll', timeout_struct) This outputs 4:' ' Traceback (most recent call last): File "t.py", line 8, in print struct.unpack('ll', timeout_struct) File "/usr/lib/python2.5/struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 8 It works fine on 32 and 64 bit Linux (Ubuntu 8.04). The kicker is that I can't remember if I actually ever tested this on Windows before. This goes to a level of socket programming that I haven't done before. Is there a cross-platform way of doing what the M2Crypto code is attempting to do? -- Heikki Toivonen From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 06:33:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Sep 2008 10:33:44 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> Message-ID: <00ee05ca$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 18:20:17 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: >> > An ordinary singleton is instantiating the class multiple times yet >> > returning the same instance object; a class singleton is simply using >> > the class directly (like a module). > > Where is this "class singleton" terminology from? I don't know. Googling on it brings up an awful lot of C++ and Java source code for regular Singletons. Perhaps Aahz can shed some light on it? > It seems redundant to > me. It also doesn't seem to have anything to do with what "singleton" > means as a pattern; "using a class" is simply using a class. I don't see why this idiom causes such conceptual difficulty. There are classes with many instances; there are classes with a single instance (Singleton). Why should't there be classes with no instances? A class is just an object. If you find yourself caring whether a particular object is a class, an instance or a function, then you have to ask yourself why you are worrying about the implementation details. Of course as the library writer, it's your job to worry about the implementation details, but ideally the library user shouldn't have to. >> Since I now no longer think I need such a beast > > That's a relief :-) > >> I'd like to be able to call [a class] as if it were a function. >> Normally calling a class object returns an instance -- I wish to return >> something else. > > In that case, you *don't* want a class at all; the entire point of a > class is to define behaviour for instances. Classes encapsulate state + behaviour in one package, and they allow inheritance. That's a lot more than merely defining behaviour of instances. Instances in turn have the additional capability of being able to over-ride the class' state and behaviour: class C(object): x = 'spam' c = C() c.x = 'ham' # doesn't touch C.x If your instance doesn't do something the class can't do on it's own, why bother with the instance? > Instead, you want to define a class whose *instances* are callable, by > defining the '__call__' method to do whatever it is you want. Most of the time, sure. >> This seems to works: >> >> >>> class ClassSingleton(object): >> ... thing = (0, 1, 2) >> ... def __new__(cls, *args): >> ... return len(args+cls.thing) ... >> >>> ClassSingleton(1, 2, 4, 8, 16) >> 8 > > Horribly obfuscatory. Calling a class should return a new instance of > the class or something like it. Apart from the name, which I dislike, what is obfuscatory about it? Haven't you ever used factory functions or class builders? It's the same principle. Why do you care that ClassSingleton is a class instead of a function? I'm certainly not saying that we should use classes this way all the time, but the capability is there, and apparently not by accident. Guido wrote: "__new__ must return an object. There's nothing that requires that it return a new object that is an instance of its class argument, although that is the convention. If you return an existing object of your class or a subclass, the constructor call will still call its __init__ method. If you return an object of a different class, its __init__ method will not be called." http://www.python.org/download/releases/2.2.3/descrintro/ > Instead, define it so the user instantiates the class by calling the > class, and *then* calls that non-class object, and so shouldn't expect > to get a new instance back: > > >>> class CallableAppendor(object): > ... thing = (0, 1, 2) > ... def __call__(self, *args): > ... return len(args + self.thing) ... > >>> appendor = CallableAppendor() > >>> appendor(1, 2, 4, 8, 16) > 8 That's the right solution when the instance is able to override the state and/or behaviour of the class. Most uses of classes are like that: class Spam(object): def __init__(self, n): self.n = n def sing(self): return "spam "*self.n + " glorious SPAM!!!" Because the behaviour (method 'sing') depends on state which is specific to the instance (attribute 'n'), it is right and proper to instantiate the class. The class 'Spam' is a constructor for instances, and the instances do all the work. But my earlier example is not the same. In the example I gave, neither the behaviour nor the state depend on the instance: everything is specified in the class. Ben's variant behaves differently: the caller might override appendor.thing by hand. That is Ben's choice, of course, and it may be a valid one for many applications, but it's displaying different behaviour to my example. In my example, the instance doesn't matter. I could write it like this: >>> class CallableAppendor(object): ... thing = (0, 1, 2) ... @classmethod ... def __call__(cls, *args): ... return len(args + cls.thing) ... >>> appendor = CallableAppendor() >>> appendor.thing = (1, 2, 3, 4, 5, 6, 7, 8) >>> appendor(1, 2, 4, 8, 16) 8 >>> CallableAppendor.__call__(1,2,4,8,16) 8 but what's the purpose of instantiating the class? I concede that this is a made-up example, but here's an actual practical example of a class with no instances: Guido's attempt at an Enum: "This (ab)uses the class syntax as an elegant way to define enumerated types. The resulting classes are never instantiated -- rather, their class attributes are the enumerated values. For example: class Color(Enum): red = 1 green = 2 blue = 3 print Color.red will print the string ``Color.red'', while ``Color.red==1'' is true, and ``Color.red + 1'' raise a TypeError exception." http://www.python.org/doc/essays/metaclasses/ -- Steven From kaerbuhez at gmail.com Fri Sep 5 16:15:17 2008 From: kaerbuhez at gmail.com (kaer) Date: Fri, 5 Sep 2008 13:15:17 -0700 (PDT) Subject: mimms problem on Hardy Message-ID: <59447741-be83-49a0-9316-d1a42cc4450f@f63g2000hsf.googlegroups.com> Hello, I installed (manually) the last version of mimms -which is a python program- on an Ubuntu (8.04-server) box. I get that: kaer at subfighter:~/mimms-3.2$ mimms Traceback (most recent call last): File "/usr/bin/mimms", line 21, in from libmimms.core import run File "/usr/lib/python2.5/site-packages/libmimms/core.py", line 31, in from . import libmms File "/usr/lib/python2.5/site-packages/libmimms/libmms.py", line 29, in libmms.mmsx_connect.argtypes = [c_void_p, c_void_p, c_char_p, c_int] File "/usr/lib/python2.5/ctypes/__init__.py", line 361, in __getattr__ func = self.__getitem__(name) File "/usr/lib/python2.5/ctypes/__init__.py", line 366, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: /usr/lib/libmms.so.0: undefined symbol If it helps: kaer at subfighter:~/mimms-3.2$ ls -l /usr/lib/libmms.so.0 lrwxrwxrwx 1 root root 15 2008-08-20 01:41 /usr/lib/libmms.so.0 -> libmms.so.0.0.2: mmsx_connect If have no idea where the problem is. Thanks for your ideas, suggestions, comments ... From ranim81 at gmail.com Mon Sep 1 08:31:28 2008 From: ranim81 at gmail.com (raju) Date: Mon, 1 Sep 2008 05:31:28 -0700 (PDT) Subject: get paid on free offers Message-ID: http://www.moneymaking4.blogspot.com/ From kyosohma at gmail.com Tue Sep 16 15:26:17 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 16 Sep 2008 12:26:17 -0700 (PDT) Subject: on-the-fly translation with gettext References: <87od2opg5c.fsf@lapinot.localdomain> Message-ID: <9df975ce-058a-40ef-b440-8f7eb2dbaa11@y21g2000hsf.googlegroups.com> On Sep 16, 4:57?am, Benjamin Sigonneau wrote: > Hi all, > > I'm a complete beginner in python and in GUI designing, yet I'm writing > a GUI using python and Tkinter. ?I need it to be available both in french > and english, so I read the Fine Manual and gave a try to gettext. > > So far, I've managed to translate my app with the following snippet: > > | import gettext > | def install_lang (lang): > | ? ? try: > | ? ? ? ? t = gettext.translation(domain = 'mydomain', localedir = 'locale', > | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? languages = [lang]) > | ? ? ? ? t.install() > | ? ? except IOError: > | ? ? ? ? import __builtin__ > | ? ? ? ? __builtin__.__dict__['_'] = lambda x: x > > When I issue an > > ? ? install_lang('en') > > at the beginning of my program, it is translated in english and, > conversely, an > > ? ? install_lang('fr') > > at the beginning makes it available in french. > > However, I'd like to let the user show the language on-the-fly during > execution. ?Having read the Python Library Reference, sec. 21.1.3.3 (seehttp://docs.python.org/lib/node740.html), I added a menu with two > radiobuttons and I merely set them up to call install_lang: > > | app_lang = StringVar() > | app_lang.set('en') > | langmenu = Menu(root) > | langmenu.add_radiobutton(label = "English", variable = app_lang, value = 'en', > | ? ? ? ? ? ? ? ? ? ? ? ? ?command = lambda l = 'en': install_lang(l)) > | langmenu.add_radiobutton(label = "French", variable = app_lang, value = 'fr', > | ? ? ? ? ? ? ? ? ? ? ? ? ?command = lambda l = 'fr': install_lang(l)) > > However, there is no magic. ?The language of the application remains > unchanged. ?If it was defined to be english at startup, so will it > remain. ?Conversely, it will stay in french if this was the language at > startup. > > Does somebody has any idea of what I'm doing wrong, and how to fix it? > > Thanks. > > -- > benjamin Try moving another window across your application after you change languages and see if it gets updated. Sometimes you need to refresh the layout of your application to get it to work...at least, in wxPython you do. Mike From manuhack at gmail.com Sat Sep 6 04:08:02 2008 From: manuhack at gmail.com (Manu Hack) Date: Sat, 6 Sep 2008 04:08:02 -0400 Subject: max(), sum(), next() In-Reply-To: <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> Message-ID: <50af02ed0809060108x1785b96fv8021646319daa45e@mail.gmail.com> On Sat, Sep 6, 2008 at 12:57 AM, castironpi wrote: > On Sep 5, 9:20 pm, "Manu Hack" wrote: >> On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: >> > On Sep 5, 3:28 am, "Manu Hack" wrote: >> >> On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: >> >> > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >> >> >> David C. Ullrich: >> >> >> >> > At least in mathematics, the sum of the elements of >> >> >> > the empty set _is_ 0, while the maximum element of the >> >> >> > empty set is undefined. >> >> >> >> What do you think about my idea of adding that 'default' argument to >> >> >> the max()/min() functions? >> >> >> >> Bye, >> >> >> bearophile >> >> >> > For max and min, why can't you just add your argument to the set >> >> > itself? >> >> >> > The reason max([]) is undefined is that max( S ) is in S. >> >> >> It makes sense. >> >> >> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >> >> >> It doesn't make sense to me. What do you set x to? >> >> > For all x. >> >> But then how can you conclude sum([]) = 0 from there? It's way far >> from obvious. > > You can define sum([a1,a2,...,aN]) recursively as > sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) "X", then > subtract aN. > > sum([a1,a2,...a(N-1)])+aN=X > sum([a1,a2,...a(N-1)])+aN-aN=X-aN > > For N=2, we have: > > sum([a1,a2])=X > sum([a1,a2])-a2=X-a2 > sum([a1,a2])-a2-a1=X-a2-a1 > > Since X= a1+ a2, replace X. > > sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 > > Or, > > sum([a1,a2])-a2-a1=0 > > Apply the recursive definition: > > sum([a1])+a2-a2-a1=0 > > And again: > > sum([])+a1+a2-a2-a1=0 > > And we have: > > sum([])=0. It makes more sense now, I just wanted to point out that only with sum([x]) = x, you can't get sum([]) = 0. From gminick at bzt.bzt Wed Sep 3 10:31:17 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 3 Sep 2008 14:31:17 +0000 (UTC) Subject: properties setting each other References: Message-ID: On Wed, 03 Sep 2008 15:57:50 +0200, mk wrote: > I try to set two properties, "value" and "square" in the following code, > and arrange it in such way that setting one property also sets another > one and vice versa. But the code seems to get Python into infinite loop: > Is there a way to achieve this goal of two mutually setting properties? My attempt: --- import math class Square(object): def __init__(self, val): self._square = pow(val, 2) self._value = math.sqrt(self.square) def getsquare(self): return self._square def setsquare(self, square): self._square = square self._value = math.sqrt(self._square) square = property(getsquare, setsquare) def getvalue(self): return self._value def setvalue(self, value): self._value = value self._square = math.pow(value, 2) value = property(getvalue, setvalue) a = Square(5) print a.square print a.value a.value = 10 print a.square print a.value a.square = 64 print a.square print a.value --- and the result: $ python sqval.py 25 5.0 100.0 10 64 8.0 $ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From tino at wildenhain.de Mon Sep 1 08:17:44 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 01 Sep 2008 14:17:44 +0200 Subject: Know if a object member is a method In-Reply-To: <27308d500809010245x29a393aya65561783ea0e804@mail.gmail.com> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> <27308d500809010245x29a393aya65561783ea0e804@mail.gmail.com> Message-ID: <48BBDD68.4040603@wildenhain.de> Luca wrote: > On Mon, Sep 1, 2008 at 11:35 AM, Steven D'Aprano > wrote: ... >> But not so easy to fool a type check: >> >>>>> type(x) == new.function >> False >> >> Of course that's not bullet-proof either. I leave it as an exercise to >> discover how you might break that piece of code. >> > > Ok, so... > > What is the best way to do this? The "most pythonic"? The question would be - why do you want this? Is it just curiosity or can we find a better solution to the overall problem, once understood? Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From gminick at bzt.bzt Fri Sep 26 06:21:58 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 26 Sep 2008 10:21:58 +0000 (UTC) Subject: urllib.urlopen fails in Emacs References: <877i8zco3t.fsf@gmail.com> Message-ID: On Fri, 26 Sep 2008 02:23:18 -0600, Iain Dalton wrote: > In Emacs, using run-python, > > import urllib > urllib.urlopen('http://www.google.com/') > > results in this traceback: ... > IOError: [Errno socket error] (111, 'Connection refused') > > It works fine from the command line. Why is this happening? I can't answer your question, since I don't use emacs, but it looks like emacs has some kind of built in firewall. ;-) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From marco.bizzarri at gmail.com Thu Sep 4 10:39:27 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 16:39:27 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <6i9uidFphkg0U1@mid.uni-berlin.de> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <6i9uidFphkg0U1@mid.uni-berlin.de> Message-ID: <3f0d61c40809040739t4ea080b1nc2683f43b1558b6@mail.gmail.com> On Thu, Sep 4, 2008 at 1:19 PM, Diez B. Roggisch wrote: > > What you are essentially asking is: why is python dynamic instead of static? > Most probably you're right. Maybe I will make a trip back to my university books and take a look at them again :-) Thanks Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From michael.pearmain at tangozebra.com Tue Sep 2 11:28:02 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 2 Sep 2008 08:28:02 -0700 (PDT) Subject: dict.update References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> <6i53m1Fo1a1aU1@mid.uni-berlin.de> Message-ID: <694d6b44-33b0-44a2-b375-a4deaf2e17c9@k37g2000hsf.googlegroups.com> Thanks Diez, This is almost perfect! Is there a way to ensure each list has two elements, even if one of them is blank? Mike From marco.bizzarri at gmail.com Mon Sep 1 09:39:47 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 1 Sep 2008 15:39:47 +0200 Subject: How to print first(national) char from unicode string encoded in utf-8? In-Reply-To: <7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> <7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> Message-ID: <3f0d61c40809010639p1db9fb8bl1c78e01ca96e2012@mail.gmail.com> On Mon, Sep 1, 2008 at 3:25 PM, wrote: > > When I do ${urllib.unquote(c.user.firstName)} without encoding to > latin-1 I got different chars than I will get: no ?ukasz but ? ukasz > -- > http://mail.python.org/mailman/listinfo/python-list That's crazy. "string".encode('latin1') gives you a latin1 encoded string; latin1 is a single byte encoding, therefore taking the first byte should be no problem. Have you tried: urlib.unquote(c.user.firstName)[0].encode('latin1') or urlib.unquote(c.user.firstName)[0].encode('utf8') I'm assuming here that the urlib.unquote(c.user.firstName) returns an encodable string (which I'm absolutely not sure), but if it does, this should take the first 'character'. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From gminick at bzt.bzt Sat Sep 6 18:32:47 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Sat, 6 Sep 2008 22:32:47 +0000 (UTC) Subject: Cathing several potential errors? References: Message-ID: On Sat, 6 Sep 2008 15:13:45 -0700 (PDT), cnb wrote: > if i do > try: > something > except TypeError, IndexError: > pass Parenthesize them: except (TypeError, IndexError): -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From maric at aristote.info Tue Sep 16 12:47:02 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 18:47:02 +0200 Subject: literals optimization (was Re: append on lists) In-Reply-To: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> References: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> Message-ID: <200809161847.02625.maric@aristote.info> Le Tuesday 16 September 2008 18:26:38 Grant Edwards, vous avez ?crit?: > I was asking where in the specification > it says that all expressions that > return something, return a > new object. ? I never said this, I said it's the spirit of python APIs, with some noticeable exceptions (see my first post). But for this case specifically, a + b *should* return a new object, see the documentation of __add__ and __iadd__ special methods, it's clearly stated. The fact that an integer with value "1" is always the same integer in some implementation is unrelated to the original problem. -- _____________ Maric Michaud From smbaker at gmail.com Wed Sep 3 15:09:03 2008 From: smbaker at gmail.com (Scott) Date: Wed, 3 Sep 2008 12:09:03 -0700 (PDT) Subject: creating a similar object from an derived class Message-ID: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> Let's say I have an object: class foo(): def create_another() return foo() def blah(): x = self.create_another() ... do something with X Now I create a inherited class of this object: class bar(foo): ... If I call bar.create_another(), it will return a foo() instead of a bar(). This isn't what I want. I would like bar.create_another() to create an instance for bar(). Obviously I can do this by overriding create_another, i.e. class bar(foo): def create_another() return bar() However, is there a way for me to modify foo() so that it automatically creates objects of the derived class, so that I don't have to continue to redefine create_another() ? For example, I tried the following: def create_another() return self.type()() but it did not work. Thanks, Scott From mikerslay at gmail.com Thu Sep 4 20:49:27 2008 From: mikerslay at gmail.com (MikeyBoy) Date: Thu, 4 Sep 2008 17:49:27 -0700 (PDT) Subject: Got Yuwie!? Message-ID: Join Yuwie and get paid to use a social network just like Myspace. From skip at pobox.com Sat Sep 13 10:03:32 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Sep 2008 09:03:32 -0500 Subject: A service for testing Python code on multiple platforms and versions In-Reply-To: <48CBBFB5.1030202@gmail.com> References: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> <48CBBFB5.1030202@gmail.com> Message-ID: <18635.51252.26183.175426@montanaro-dyndns-org.local> Stef> Something like a multi-virtual machine on a web server, that you Stef> launch in the night, and in the morning you would get a full Stef> report of all problems on the specific OSs (probably someone is Stef> going to say that this is impossible, but fortunately I'm not Stef> hindered by any knowledge ;-) You could run Buildbot on a bunch of virtual machines on your computer (assuming your computer is x86 and its OS is supported by something like Sun's VirtualBox or VMWare's offerings). Skip From tjreedy at udel.edu Tue Sep 23 14:51:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 14:51:57 -0400 Subject: Linq to Python Message-ID: > Will LINQ be ported to Python ? I have three suggestions: 1. When starting a new thread, start a *new* thread. Don't tack a new, unrelated subject onto an existing thread. Your post will not be seen by people with readers that collapse thread and who do not happen to read the 'Python is slow?' thread. 2. Also, give enough informaton that people can understand your question without searching the web and guessing. In particular, that do *you* mean by LINQ? The game? The .NET component? Or something else? 3. Before posting, search the Python manuals or the web a bit for an answer. If you mean the .NET component, googling 'Python LINQ' should partly answer your question. tjr From clp at rebertia.com Sun Sep 28 15:11:58 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 28 Sep 2008 12:11:58 -0700 Subject: urllib2 and exceptions In-Reply-To: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> Message-ID: <47c890dc0809281211p1aa5ae7fr882d42464d6dae55@mail.gmail.com> On Sun, Sep 28, 2008 at 11:03 AM, robean wrote: > Hi everyone, > > I have a question about using urllib2. > > I like urllib2 better than urllib at least in part because it has more > elaborate support for handling errors: there is built in support for > URLError (for faulty urls) and HTTPError (for http errors that might > originate from, say, passing an invalid stock-ticker in the program > below). However I can get neither to work. I'm attaching below the > (very short) code: can anyone point out what I'm doing wrong? > > Now, if I replace the URLError and HTTPError with IOError (the class > from which both URLError and HTTPError inherit), the program works > fine. Why is it that I can call the generic IOError class, but none of > the Error classes derived from that? These are clearly defined in the > urllib2 manual. Very confused... > > Here's the code: > > > import urllib2 > > # read stock information from yahoo finance for Traget (TGT) > goodTicker = 'TGT' # program works with this > badTicker = 'TGTttttttt' # python doesn't understand either HTTPError > or URLError with this > > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > try: > handle = urllib2.urlopen(url) > > # this does not work > except HTTPError, e: > print "There was an http error" > print e > > # this also does not work > except URLError, e: > print "There is a problem with the URL" > print e > exit(1) > > #this works > except IOError, e: > print "You have an IOError" > print e > > text = handle.readlines()[:20] > for line in text: > print line > > -- > http://mail.python.org/mailman/listinfo/python-list > My Python begs to differ: #tmp.py import urllib2 badTicker = 'TGTttttttt' url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker try: handle = urllib2.urlopen(url) except urllib2.HTTPError, e: print "There was an http error" print e except urllib2.URLError, e: print "There is a problem with the URL" print e except urllib2.IOError, e: print "You have an IOError" print e #in the shell $ python -V Python 2.5.1 $ python Desktop/tmp.py There was an http error HTTP Error 404: Not Found Are you using an outdated version of Python perhaps? Regards, Chris -- Follow the path of the Iguana... http://rebertia.com From martin at see.sig.for.address.invalid Tue Sep 2 06:24:17 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Tue, 2 Sep 2008 10:24:17 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Mon, 01 Sep 2008 20:48:23 -0400, George Neuner wrote: > I don't know the correct term, but what I was talking about was a tiny > switch with a 1/2 inch metal handle that looks like a longish grain of > rice. We used to call them "knife" switches because after hours > flipping them they would feel like they were cutting into your fingers. > That sounds like a sub-minature SPDT toggle switch with a normal handle. Cheap as chips, which is probably why they were used on that front panel. Like this by any chance? http://www.maplin.co.uk/images/300/fh00a_ff70m.jpg -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From grante at visi.com Tue Sep 23 09:57:14 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 23 Sep 2008 08:57:14 -0500 Subject: Python is slow? References: Message-ID: On 2008-09-23, sturlamolden wrote: [...] > After having a working Python prototype, I resorted to rewrite the > program in C++. The Python prototype took an hour to make, debug and > verify. The same thing in C++ took me almost a day to complete, even > with a working prototype as model. To my surprise, the resulting beast > of C++ required 64.3 seconds to construct the same kd-tree. Searching > the tree was not faster either, 1,000 points required 38.8 seconds. I > wasted a day, only to find my Python prototype being the faster. > > We may conclude that I'm bad at programming C++, AFAICT, _everybody_ is bad at programming C++. One begins to suspect it's not the fault of the programmers. -- Grant Edwards grante Yow! Finally, Zippy at drives his 1958 RAMBLER visi.com METROPOLITAN into the faculty dining room. From pmaupin at gmail.com Sun Sep 7 16:23:30 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 7 Sep 2008 13:23:30 -0700 (PDT) Subject: __builtins__ magic behavior References: Message-ID: On Sep 7, 2:50?pm, "Gabriel Genellina" wrote: > Inside PyFrame_New, there is a shortcut: if the new frame and > the previous one share the same globals, then the previous > builtins are copied into the new frame. Only if the globals > differ the builtins are searched in globals. From frameobject.c: > /* If we share the globals, we share the builtins. Save a > lookup and a call. */ That was exactly my problem. Thank you for the cogent explanation. > If you want to execute some code with modified builtins, do not > change __builtins__ in the *calling* code, but in the globals that > you pass to the exec call. That appears to be the most logical > approach, and the way the developers appear to have expected. Actually, my use-case is a tiny bit different than this. I am dynamically creating module objects, and was going nuts trying to comprehend the inner workings of behind-the-scenes __builtins__ magic in the module object, not realizing that the magic was actually in the execution frames. Thanks, Pat From bj_666 at gmx.net Wed Sep 3 02:40:10 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Sep 2008 06:40:10 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> Message-ID: <6i6pq9Fmcad7U2@mid.uni-berlin.de> On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote: >> And if they model an action there must be some way to activate the >> action > > That's a reasonable assumption, but as I also said, the object might > just describe the action -- essentially the equivalent of a struct in C. ``struct``\s in C describe *actions*!? Functions do this. And a class that describes an action that is executed in the `__init__()` method is conceptually a function and shouldn't be a class. There must be a better name for the "thing" it returns. Again guideline, not law, but a very strong guideline IMHO. >> but the instances of `Popen` are no actions. There's no way to >> "execute" a `Popen` instance. > > Yes there is... you execute it when you instantiate the object. But then the instance itself isn't an action but the result of one. > At the time of instantiation, you "open" the "P" (pipes). For an > object which describes an action, I think it's perfectly sensible that > instantiation is when the action occurs, [?] Here I disagree again. Because the type/class name of an instance should be a name of the "thing"/concept of the instance, not the action used to create it. >> > Yet some of you state your case as if it is incontrovertable fact. >> > I've given a good case as to why it IS a good name (one which I >> > genuinely support), and disagree as you may, none of the points any >> > of you have made invalidate or even weaken my argument. >> >> Maybe from your POV. Facts: It doesn't use the `popen()` function > > So? Neither does the C version of popen(), but that function is still > called popen()! Now you lost me. The C version of `popen()` isn't recursive, why on earth should it be, so what's that statement supposed to mean!? >> to three file objects, more attributes and methods), the function used >> on Windows under the hood is called `CreateProcess()` not >> `CreatePipe()`. > > How does Windows implement popen()? [I think they call it _popen() > though...] Doesn't matter because the `Popen()` implementation doesn't use `popen()`. Ciao, Marc 'BlackJack' Rintsch From pavlovevidence at gmail.com Wed Sep 24 23:17:57 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 24 Sep 2008 20:17:57 -0700 (PDT) Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: On Sep 24, 9:27?pm, Tim Arnold wrote: > (2) Next thought was fork, but I don't know how to signal when each > child is > finished. Consider the multiprocessing module, which is available in Python 2.6, but it began its life as a third-party module that acts like threading module but uses processes. I think you can still run it as a third- party module in 2.5. Carl Banks From san82moon at gmail.com Mon Sep 1 04:48:07 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:48:07 -0700 (PDT) Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <83330868-db47-46d0-b734-fba2688ff5ec@a2g2000prm.googlegroups.com> On Sep 1, 1:45 pm, Bruno Desthuilliers wrote: > lee a ?crit : > > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, > > ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? > > It's quite simple (hint : read the FineManual(tm) for dict.items() and > list.index()), but 1/totally inefficient and 2/not garanteed to yield a > single value (what if 'dfsdf' happens to be also the 4th item of the > list bound to key 'address' ?). > > May I suggest you rethink your data structure instead ? What you have > here is obviously a collection of 'phno/email/name/address'records. > These records shouldn't be split across different objects. Assuming > 'phno' is a unique identifier for each record, a better data structure > would be: > > records = { > 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > # etc > > } > > This way, the lookup is as simple and efficient as possible. > > My 2 cents.... hi, i agree with u, my data strusture is not efficient. but all the records,viz...name,phno, email,address are all generated at runtime , when the user enters them. so how can i design my datastructure in that case? From wescpy at gmail.com Fri Sep 5 04:21:20 2008 From: wescpy at gmail.com (wesley chun) Date: Fri, 5 Sep 2008 01:21:20 -0700 Subject: [ANN] final 2008 Python courses, San Francisco In-Reply-To: <78b3a9580809050119q46e5f004q7d7761950429fac4@mail.gmail.com> References: <78b3a9580809050116w2cfd7a98s10b7b9d201a979d8@mail.gmail.com> <78b3a9580809050119q46e5f004q7d7761950429fac4@mail.gmail.com> Message-ID: <78b3a9580809050121t517a93f4uca7b1918dac66f9c@mail.gmail.com> Need to get up-to-speed with Python as quickly as possible? Come join me, Wesley Chun, author of Prentice-Hall's bestseller "Core Python Programming," for another comprehensive intro course plus a 1-day Internet programming course coming up in November in beautiful Northern California! I look forward to meeting you! (Comprehensive) Introduction to Python Mon-Wed, 2008 Nov 10-12, 9am-5pm Internet Programming with Python Sat, 2008 Nov 15, 9am-5pm courses can be taken separately or combined for a discounted price. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRODUCTION TO PYTHON Although this course may appear to those new to Python, it is also perfect for those who have tinkered with it and want to "fill in the gaps" and/or want to get more in-depth formal training. It combines the best of both an introduction to the language as well as a "Python Internals" training course. We will immerse you in the world of Python in only a few days, showing you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting or jumping to Plone, Zope, TurboGears, Pylons, Django, Google App Engine, Jython, IronPython, and Mailman will also benefit! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INTERNET PROGRAMMING WITH PYTHON This is a one-day course with lecture and lab exposing attendees to FOUR distinct areas of Internet programming: * Network Programming using Sockets -- we introduce client/server architecture and how to program sockets using Python. * Internet Client Programming -- we learn how to use Python's standard library to create FTP, NNTP, POP3, and SMTP clients * Web Programming -- before you jump on all the web framework bandwagons, it's a good idea to learn basics and the basis of how all web servers deliver dynamic content back to the client browser to prepare you better when jumping to a full-stack web framework * Intro to Django -- a lightweight introduction to the Django web framework including whipping up a very simple blog application in 20min! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com (click "Python Training") FLYER: http://starship.python.net/crew/wesc/flyerPP1combo.pdf LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. Discounts are available for multiple registrations as well as for teachers/students. Hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2008 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From circularfunc at yahoo.se Sat Sep 6 18:06:58 2008 From: circularfunc at yahoo.se (cnb) Date: Sat, 6 Sep 2008 15:06:58 -0700 (PDT) Subject: Multicore-programming? Message-ID: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> If I buy a multicore computer and I have really intensive program. How would that be distributed across the cores? Will algorithms always have to be programmed and told specifically to run on several cores so if not told it will only utilize one core? So is the free lunch really over or is this just an overhyped phenomena? Is threading with Python hard? Can you start several processes with Python or just threads? From chiendarret at gmail.com Tue Sep 2 16:57:05 2008 From: chiendarret at gmail.com (Francesco Pietra) Date: Tue, 2 Sep 2008 22:57:05 +0200 Subject: Renumbering Message-ID: Hi; I would like to renumber, starting from 1, column 6 (i.e, 428 become 1, 429 becomes 2, etc for a very long list) ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 ATOM 3425 CA LEU B 428 142.918 87.524 78.875 1.00115.20 2SG3427 ATOM 3426 CB LEU B 428 141.559 88.057 78.392 1.00115.20 2SG3428 ATOM 3427 CG LEU B 428 140.577 88.341 79.544 1.00115.20 2SG3429 ATOM 3428 CD1 LEU B 428 141.102 89.464 80.454 1.00115.20 2SG3430 ATOM 3429 CD2 LEU B 428 139.159 88.615 79.017 1.00115.20 2SG3431 ATOM 3430 C LEU B 428 142.680 86.253 79.615 1.00115.20 2SG3432 ATOM 3431 O LEU B 428 142.725 86.226 80.842 1.00115.20 2SG3433 ATOM 3432 N SER B 429 142.432 85.155 78.878 1.00134.86 2SG3434 ATOM 3433 CA SER B 429 142.175 83.908 79.534 1.00134.86 2SG3435 ATOM 3434 CB SER B 429 141.666 82.805 78.590 1.00134.86 2SG3436 ATOM 3435 OG SER B 429 140.392 83.155 78.069 1.00134.86 2SG3437 ATOM 3436 C SER B 429 143.451 83.432 80.141 1.00134.86 2SG3438 ATOM 3437 O SER B 429 144.543 83.756 79.676 1.00134.86 2SG3439 Distinctive character is column 5, i.e., it must be set that only lines containing "B" should be renumbered. As you can see, the number of lines for a particular value in column 6 changes from situation to situation, and may even be different for the same name in column 4. For example, LEU can have a different number of lines depending on the position of this amino acid (leucine). I was unable to set non-proportional characters, sorry. Thanks for help francesco pietra From nick at craig-wood.com Wed Sep 24 05:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 24 Sep 2008 04:30:03 -0500 Subject: Comparing float and decimal References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: Terry Reedy wrote: > The new fractions module acts differently, which is to say, as most > would want. > > >>> from fractions import Fraction as F > >>> F(1) == 1.0 > True > >>> F(1.0) > Traceback (most recent call last): > File "", line 1, in > F(1.0) > File "C:\Program Files\Python30\lib\fractions.py", line 97, in __new__ > numerator = operator.index(numerator) > TypeError: 'float' object cannot be interpreted as an integer Both the Fraction module and the Decimal module could represent floats exactly and reversibly since floats are of the form mantissa * 2**exponent which is exactly representable as a fraction (rational) and also as mantissa2 * 10**exponent2 as to why we don't do this... I guess it is to preserve the sanity of the user when they write fraction(0.1) or decimal(0.1) did they really mean fraction(1,10), decimal("0.1") or the exact representations which are decimal("0.1000000000000000055511151231257827021181583404541015625") and fraction(3602879701896397,2**55) Given that we let the exact representations leak out anyway (which causes a lot of FAQs in this list), eg >>> 0.1 0.10000000000000001 IMHO We should put the exact conversions in for floats to Decimal and Fraction by default and add a new section to the FAQ! In that way people will see floats for what they really are - a crude approximation to a rational number ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bborcic at gmail.com Sat Sep 13 09:22:12 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 13 Sep 2008 15:22:12 +0200 Subject: Injecting new names into the above frame In-Reply-To: References: Message-ID: Why don't you use import and __import__() ? - They seem designed for such an application. I mean, I am not against vicious hacks for the fun of them, but not if they serve the illusion that what they do can't (easily) be achieved other ways. Cheers, BB Peter Waller wrote: > Dear Pythoners, > > I know this will probably be perceived as 'evil voodoo', and fair > enough: it probably is. I guess it is unpythonic. > > .. but I want to know how to do it anyway - mostly for my own > interest. > > Consider the following snippet of code: > > --- > def Get( *names ): > if not names: return None > > frame = sys._getframe(1) > prevFrameLocals = frame.f_locals > > for name in names: > prevFrameLocals[ name ] = FetchObjectNamed( name ) > > Get("a", "b", "c") > > print a, b, c > --- > > FetchObjectNamed() is an arbitrary function which takes a string and > returns an object it got from some store somewhere. > > This works fine at the module level, because names in the locals/ > globals dictionary can be played with in this way. The idea is to save > lots of typing, i.e. > > a, b, c = Get("a","b","c") > > ..gets frustrating after much typing for many objects with long names. > This is just an example, there are other instances I have where it > would be nice to inject names into the frame above. > > Of course, we hit a road block when we call 'Get' from a function > rather than a module, because the locals dictionary does not get > copied back into the code object automatically, so we have to add this > snippet before the Get() function returns: > > from ctypes import pythonapi, py_object, c_int > pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 ) > > This copies back the names into the code object, and works fine.. that > is, if the names already exist within the code object. > > def MyFunction(): > a = None > Get("a") > print a # Works > Get("b") > print b # Name error, b is undefined > > Is there any way for Get() to define a new variable within > MyFunction's code object? Or is there any programmatic way to, at > runtime, insert new names into functions? > > I don't care how hacky it is and whether it requires making calls to > python's internals with ctypes - maybe the whole code object needs to > be replaced? is it even possible to do that when the Get() function is > about to return to this new code object? > > Cheers, > > - Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Wed Sep 24 23:33:32 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 20:33:32 -0700 (PDT) Subject: is decorator the right thing to use? References: Message-ID: On Sep 24, 5:21?pm, "Dmitry S. Makovey" wrote: > Hi, > > after hearing a lot about decorators and never actually using one I have > decided to give it a try. My particular usecase is that I have class that > acts as a proxy to other classes (i.e. passes messages along to those > classes) however hand-coding this type of class is rather tedious, so I > decided to use decorator for that. Can somebody tell me if what I'm doing > is a potential shot-in-the-foot or am I on the right track? (Note, It's > rather rudimentary proof-of-concept implementation and not the final > solution I'm about to employ so there are no optimizations or > signature-preserving code there yet, just the idea). > > Here's the code: > > class A: > ? ? b=None > ? ? def __init__(self,b): > ? ? ? ? self.val='aval' > ? ? ? ? self.b=b > ? ? ? ? b.val='aval' > > ? ? def mymethod(self,a): > ? ? ? ? print "A::mymethod, ",a > > ? ? def mymethod2(self,a): > ? ? ? ? print "A::another method, ",a > > def Aproxy(fn): > ? ? def delegate(*args,**kw): > ? ? ? ? print "%s::%s" % (args[0].__class__.__name__,fn.__name__) > ? ? ? ? args=list(args) > ? ? ? ? b=getattr(args[0],'b') > ? ? ? ? fnew=getattr(b,fn.__name__) > ? ? ? ? # get rid of original object reference > ? ? ? ? del args[0] > ? ? ? ? fnew(*args,**kw) > ? ? setattr(A,fn.__name__,delegate) > ? ? return fn > > class B: > ? ? def __init__(self): > ? ? ? ? self.val='bval' > > ? ? @Aproxy > ? ? def bmethod(self,a): > ? ? ? ? print "B::bmethod" > ? ? ? ? print a, self.val > > ? ? @Aproxy > ? ? def bmethod2(self,a): > ? ? ? ? print "B::bmethod2" > ? ? ? ? print a, self.val > > b=B() > b.bmethod('foo') > a=A(b) > b=B() > b.val='newval' > a.bmethod('bar') > a.bmethod2('zam') It might help to tell us the order of events that you want in your program. You're not using 'mymethod' or 'mymethod2', and you probably want 'return fnew' for the future. Something dynamic with __getattr__ might work. Any method call to A, that is an A instance, tries to look up a method of the same name in the B instance it was initialized with. a.foo( ) -> 'in a.foo' -> 'calling b.foo' -> 'return' -> 'return' a.mymethod( ) -> 'in a.mymethod' -> 'calling b.mymethod' -> AttributeError: 'b' has no attribute 'mymethod'. From bdesth.quelquechose at free.quelquepart.fr Wed Sep 24 14:39:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 20:39:45 +0200 Subject: Linq to Python In-Reply-To: References: Message-ID: <48daa55d$0$19939$426a74cc@news.free.fr> hrishy a ?crit : (snip) > I apologise > (I thought Python programmers were smart and they did know what LINQ was) Is there really any relation between "being smart" and knowing anything about the latest MS fad ? From mohed at hotmail.com Mon Sep 29 16:51:06 2008 From: mohed at hotmail.com (Mohed) Date: Mon, 29 Sep 2008 13:51:06 -0700 (PDT) Subject: Source code for python nativ methods and classes Message-ID: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> Hello. I am interrested in seeing the source code for all the nativ builtin methods and clases in python. Is there a webpage that lists them or is this done easier some other way. This is my first post so feel free to creticue, the more you do the faster i learn to post well. Mohed From fredrik at pythonware.com Fri Sep 5 02:34:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:34:53 +0200 Subject: ctypes error on Windows In-Reply-To: References: Message-ID: Mike Hostetler wrote: > I'm working on a script with the most excellent uTibyLib library. The script works just fine on Mac, but on Windows I get this: > > File "findtables.py", line 82, in cleanHTML > return str(tidy.parseString(decentDoc)) > File "c:\Python24\Lib\site-packages\tidy\lib.py", line 207, in parseString > doc = self._create(**kwargs) > File "c:\Python24\Lib\site-packages\tidy\lib.py", line 183, in _create > doc = _Document() > File "c:\Python24\Lib\site-packages\tidy\lib.py", line 135, in __init__ > self.cdoc = _tidy.Create() > File "c:\Python24\Lib\site-packages\tidy\lib.py", line 46, in __getattr__ > return getattr(self.lib, name) > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 353, in __getatt > func = self.__getitem__(name) > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 358, in __getite > func = self._FuncPtr((name_or_ordinal, self)) > AttributeError: function 'Create' not found > > I do have the tidy.dll installed (if I didn't, I couldn't even import the tidy module). typing the following into the Python interpreter might give you some more clues: >>> import _tidy >>> _tidy.__file__ >>> dir(_tidy) From littlesweetmelon at gmail.com Sun Sep 28 03:02:55 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Sun, 28 Sep 2008 15:02:55 +0800 Subject: design pattern: MVC in python In-Reply-To: <3ff66ae00809272329mce8d3c9lb94c316e169cf63a@mail.gmail.com> References: <3ff66ae00809272329mce8d3c9lb94c316e169cf63a@mail.gmail.com> Message-ID: Really helpful! 2008/9/28 Mikolai Fajer : > The following link directly discusses using MVC and pygame. > > http://ezide.com/games/writing-games.html > > -- > > -Mikolai Fajer- > -- > http://mail.python.org/mailman/listinfo/python-list > From rsinger at ____.com Tue Sep 23 09:44:56 2008 From: rsinger at ____.com (Robert Singer) Date: Tue, 23 Sep 2008 15:44:56 +0200 Subject: Python is slow? References: Message-ID: On Tue, 23 Sep 2008 06:23:12 -0700 (PDT), sturlamolden wrote: >I have recently been playing with a kd-tree for solving the "post >office problem" in a 12-dimensional space. This is pure cpu bound >number crunching, a task for which I suspected Python to be >inefficient. Well, python is not a number crunching language. However much we would like it to be (we would ? :-). No scripting language is. Developing time is shorter, I agree, but when you have, for example a problem which takes 8,31 minutes to go through in optimized fortran code (like the one I had the other day), then that hardly matters. > >My prototype in Python 2.5 using NumPy required 0.41 seconds to >construct the tree from 50,000 samples. Unfortunately, searching it >felt a bit slow, finding the 11 nearest-neighbours of 1,000 points >took 29.6 seconds (and there were still 49,000 to go). Naturally, I >blamed this on Python. It would be 100 times faster if I used C++, >right? Not necessarily. Before resorting to rewriting the problem try psyco. It speeds up things sometimes. Also, (I'm not that familiar with python yet, so I don't know how to do it in python), try finding the bottlenecks of your calculation. Are the loops where most of the processing time is wasted, or disk accessing, or ... ? > >After having a working Python prototype, I resorted to rewrite the >program in C++. The Python prototype took an hour to make, debug and >verify. The same thing in C++ took me almost a day to complete, even >with a working prototype as model. To my surprise, the resulting beast >of C++ required 64.3 seconds to construct the same kd-tree. Searching >the tree was not faster either, 1,000 points required 38.8 seconds. I >wasted a day, only to find my Python prototype being the faster. > >We may conclude that I'm bad at programming C++, but I suspect that is >not the case here. Albeit micro-benchmarks may indicate that Python is >100-200 times slower than C++, they may not be applicable to the real >world. Python can be very efficient. And when combined with libraries >like NumPy, beating it's performance with hand-crafted C++ is >difficult. At least, my 10 years experience programming scientific >software in various languages was not sufficient to beat my own Python >prototype with C++. > >That is not to say I have never seen C++ run a lot faster than Python. >But it tends to be very short pieces of CPU bound code, no more than a >function or two. But as the problem grows in complexity, C++ >accumulates too much of its own bloat. > Well, personally, I try to combine fortran (being a fortran programmer by trade) with python (in the last few years), as I find fortran to be, by two grades, more comfortable for solving scientific problems then c (or python for that matter, although it has its merits). Starting from ith his capabilities for "normal" array handling, to optimisation and easy readability, to whatnot. Best regards Bob From deets at nospam.web.de Mon Sep 1 05:37:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 11:37:56 +0200 Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <6i1rgcFo0f1gU1@mid.uni-berlin.de> lee wrote: > On Sep 1, 1:45 pm, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> lee a ?crit : >> >> > hi, >> > i have a dictionary as follows : >> > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', >> > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], >> > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} >> >> > if user is enters the 3rd item of key phno, >> > ie "dfsdf" in my dict, >> > how can i find it is the third item in the internal list of phno of >> > that dictionary? >> >> It's quite simple (hint : read the FineManual(tm) for dict.items() and >> list.index()), but 1/totally inefficient and 2/not garanteed to yield a >> single value (what if 'dfsdf' happens to be also the 4th item of the >> list bound to key 'address' ?). >> >> May I suggest you rethink your data structure instead ? What you have >> here is obviously a collection of 'phno/email/name/address'records. >> These records shouldn't be split across different objects. Assuming >> 'phno' is a unique identifier for each record, a better data structure >> would be: >> >> records = { >> 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, >> 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, >> # etc >> >> } >> >> This way, the lookup is as simple and efficient as possible. >> >> My 2 cents.... > > hi, > i agree with u, my data strusture is not efficient. but all the > records,viz...name,phno, email,address are all generated at runtime , > when the user enters them. so how can i design my datastructure in > that case? Are "u" short on keystrokes? You are not textmessaging here... Regarding the actual question: there is no difference in building your or the other structure. It's only a question of which key you use first. Instead of first looking up the type of the record ("phno" or some such), do that with the name of the user. If no record exists, create one. Then populate the record with the user's values. Like this: user = "dsdf" phonenumber = "123" record = records.setdefault(user, {}) record["phno"] = phonenumber Diez From tjreedy at udel.edu Tue Sep 23 14:36:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 14:36:29 -0400 Subject: Docstrings for class attributes In-Reply-To: <6jsfeaF4pbs9U1@mid.individual.net> References: <6jsfeaF4pbs9U1@mid.individual.net> Message-ID: Peter Pearson wrote: > On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris wrote: >> I want to have a class as a container for a bunch of symbolic names >> for integers, eg: >> >> class Constants: >> FOO = 1 >> BAR = 2 >> >> Except that I would like to attach a docstring text to the constants, >> so that help(Constants.FOO) will print some arbitrary string. > [snip] > > Commiserating, not helping: I have a similar problem with a module > that holds values of physical constants, > http://webpages.charter.net/curryfans/peter/nature.py: > > boltzmanns_constant = 1.380622e-16 * erg / k > stefan_boltzmann_constant = 5.66961e-5 * erg/s/cm/cm/k/k/k/k > gravitational_constant = 6.6732e-8 * erg*cm/g/g > > I would like to reveal more details with, e.g., > help( gravitational_constant ) . . . and maybe then I could > use shorter names. gravitational_constant = g = 6.6732e-8 * erg*cm/g/g ... From steve at REMOVE-THIS-cybersource.com.au Tue Sep 2 12:55:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 16:55:53 GMT Subject: How to write verbose scripts Message-ID: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> I find myself writing command line tools in Python where I wish to include "verbose" output to stdout. I start with a helper function: def print_(obj, level=0): if _verbosity >= level: print obj And then I end up with functions or methods looking like this: def parrot(x) print_("precondition", level=2) do_something() print_("status is good...", level=1) print_("parrot is squawking strongly now", level=2) do_something_else() print_("squawk squawk squawk", level=3) do_more() print_("postcondition", level=1) return something That often means that my functions end up with more message printing code than actual code. The whole thing seems messy and hard to manage for all but the smallest scripts. Worst of all, sometimes the messages I wish to print may be expensive to compute, and I don't want to waste time computing them if they aren't going to be printed because the verbosity is too low. But nor do I wish to fill my code with this: if _verbosity >= 3: x = calculate_complicated_thing() print_(x, level=3) Is there a better way of doing this than the way I am going about it? -- Steven From python.list at tim.thechases.com Wed Sep 17 06:45:44 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 17 Sep 2008 05:45:44 -0500 Subject: File Reading related query In-Reply-To: References: Message-ID: <48D0DFD8.4000309@tim.thechases.com> >> Is there any function for reading a file while ignoring *\n* occuring in >> the file? > > can you be a bit more precise? are we talking about text files or > binary files? how do you want to treat any newlines that actually > appear in the file? I believe the OP is referencing this behavior: for line in file('x.txt'): assert not ( line.endswith('\r') or line.endswith('\n')), "Don't want this" else: yay() # we never end up reaching this which can be done with a simple generator/wrapper: def unnewline(iterator): for line in iterator: yield line.rstrip('\r\n') for line in unnewline(file('x.txt')): assert not ( line.endswith('\r') or line.endswith('\n')), "Don't want this" else: yay() # we get here this time Alternatively, the content can just be modified on the fly: for line in file('x.txt'): line = line.rstrip('\r\n') ... yes, the interpretation would differ if it were a binary file, but the above interpretation is a pretty common case (i.e. I encounter it daily, in my processing of client data-feeds). -tkc From numan.salati at gmail.com Thu Sep 18 12:32:32 2008 From: numan.salati at gmail.com (numan.salati at gmail.com) Date: Thu, 18 Sep 2008 09:32:32 -0700 (PDT) Subject: Out of memory issue with dialog box Message-ID: Hi, We have a mutilthreaded process in which one of the threads uses too much memory causing the process to run out of memory. However when this happens we see a dialog box pop up with the message "fatal error in GC : too many heap sections." When you click "ok" only then does the process die. Is there a way for the process to crash directly without going through the dialog box. Any help would be appreciated? From josiah.carlson at gmail.com Mon Sep 15 03:03:31 2008 From: josiah.carlson at gmail.com (NotAnAdminAccount) Date: Mon, 15 Sep 2008 00:03:31 -0700 (PDT) Subject: Python IDEs with F5 or hotkey shell interaction References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> Message-ID: <6183f3fa-3275-437d-875e-c0613d071f68@c22g2000prc.googlegroups.com> On Sep 2, 7:01?am, mmm wrote: > I am looking for advice on Python Editors and IDEs > > I have read other posts and threads on the subject and my two > questions at this time are mainly about the IDLE-like F5-run > facilities. ?While I am fairly happy using IDLE, the debugger is > unintuitive to me and I wanted a project manager and a better variable/ > class browser and also the potential to edit/run other languages such > as R and Tex/Latex. Windows and LINUX compatibility is desired too. > > I found numerous editor candidates from reading posts to this Python > users group list ?and also documents such as ?http://wiki.python.org/moin/PythonEditors > but few if any alternatives seem to have all of the ??interactive? > power of IDLE?- not only a run program in a python shell hotkey but a > persistent, after-a-run memory state can be accessed for interactive > coding and exploration-- ?i.e. how IDLE works ! > > *** My first questions is what other editor/IDE have IDLE-like > interactive features. ?Or to put it another way, is my appraisal below > of the editors & IDEs I tried right (note some where looked at as much > as a year ago). > > Python specific > ?IDLE ? ? ? ?F5 run & Full shell interaction > ?PythonWin ? F5 run & Full shell interaction, MS Windows only > ?PyScripter ?F9 run & shell interaction, > ? ? ? ? ? ? ? ? ? ? ?but script created variables are not persistent > (???!) > ?PyPE? ? ? ?F5 run, but not an interactive shell > ?DrPython ? ?F5 run, but not an interactive shell in MS Windows (maybe > in Linux) > ?SPE (Stani) Could not get it to run in MS Windows (???!) > > PyScripter,PyPeand drPython all had nice features but interaction > quirks. > > My second question is based on a belief that I should move to a more > general IDE or editor to get ?LINUX compatibility and the ability to > also edit R and LaTex programs. ?I have explored these > ? ?Vim > ? ?Cream/Vim > ? ?UliPad > ? ?SciTe > ? ?Jext > ? ?Editra > ? ?Komodo Editor > But none are close to being as interactive friendly as IDLE. > > I might look at > ? Eclypse with pydev > ? Jedit > And these commercial/professional IDEs > ? Wing > ? Komodo IDE > ? Zeus > > But before doing so I wanted to know form experienced users: > > ** How hard is it to configure any of the general editors/IDEs to run > a Python shell using a hotkey (such as IDLEs F5) and whether any can > be set up for full interactivity. > > I understand and appreciate ?the difficulties to get full IDLE-like > interactivity, but what comes closest? I know I'm a little late on this (I only hopped in to check on some other older threads), but if you are careful, PyPE can allow you to run your script in an interactive shell. In particular, if you select the content of the code you would like to run (changing any if __name__ == '__main__' into '__console__' references, then use File -> "Run Selected Code", it will select a Python Shell (if one exists) or create a new one, and run your code in that shell. If you are willing to muck about in the source code, it shouldn't be too difficult to add a '-i' to the "Run Current File" command (which I may add as an option in the next version of PyPE). - Josiah From mail at timgolden.me.uk Wed Sep 3 06:16:12 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 03 Sep 2008 11:16:12 +0100 Subject: sys.stdin on windows In-Reply-To: References: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> Message-ID: <48BE63EC.1070004@timgolden.me.uk> Gabriel Genellina wrote: > En Wed, 03 Sep 2008 06:16:03 -0300, zugnush at gmail.com > escribi?: > >> I often grep particular patterns out of large logfiles and then >> pipeline the output to sort and uniq -c >> I thought today to knock up a script to do the counting in a python >> dict. >> >> This seems work in linux >> >> $ cat count.py >> #!/usr/bin/env python >> import sys >> from collections import defaultdict >> accumulator=defaultdict(int) >> for line in sys.stdin.readlines(): >> accumulator[line.strip()]+=1 >> print "contents,count" >> for key in accumulator.keys(): >> print key,",",accumulator[key] >> >> $ cat test | ./count.py >> contents,count >> , 1 >> 23 , 1 >> 1 , 1 >> 3 , 2 >> 2 , 2 >> 5 , 3 >> >> When I try to run the same thing on windows I get >> IOError: [Error 9] Bad file descriptor >> >> How can I make this more windows friendly? > > Explicitely invoking the interpreter worked for me. That is, these two > commands worked fine: > > type test.txt | python count.py > python count.py < test.txt > > But I cannot explain *why* it doesn't work the other way. > Known bug in NT-based file association. I'll try to find an online reference, but that's basically what it comes to. I think you can faff-about with batch files to achieve the effect, but I can't quite remember. http://support.microsoft.com/kb/321788 TJG From deets at nospam.web.de Thu Sep 4 11:55:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Sep 2008 17:55:49 +0200 Subject: Function decorators In-Reply-To: References: Message-ID: <6iaeo5Fp8mpdU1@mid.uni-berlin.de> Aigars Aigars schrieb: > Good day all, > > I am learning Python and came up to decorators. > > The question is: Why does function FoodList return value None? > > The code in attachment. Because the __call__ in Logger doesn't return the value of self.func. Diez From mr.spoon21 at gmail.com Sun Sep 28 15:08:08 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 28 Sep 2008 21:08:08 +0200 Subject: Music knowledge representation In-Reply-To: References: Message-ID: <8f67b6f80809281208m5c633ec1k410c07ec2bed8338@mail.gmail.com> On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady wrote: > Here is a link to someone else's design they asked about on the > newsgroup a couple weeks ago. > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc :D It's always me. I think my question is more specific. I need some sort of cycle. So if I have a list with A, B, C, D, when I iter over it I need to get an A after the D. From gherron at islandtraining.com Fri Sep 19 17:02:56 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 19 Sep 2008 14:02:56 -0700 Subject: Launching a subprocess without waiting around for the result? In-Reply-To: References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> <87od2l2am7.fsf@benfinney.id.au> Message-ID: <48D41380.5010906@islandtraining.com> Almar Klein wrote: > > Ah, no, that's a different thing. If the parent exits, the child will > also be killed I believe. > > > Not if it's stuck in some endless loop... > > If you want to spawn a process and have it live on independent of the > parent, you want to make the child process a "daemon", detatching > itself from the parent's environment. I don't recall how that's done > immediately, but those are the terms to search for. > > > I'm curious how this can be done, does anyone know this? I just dove into this several day ago for a small project. On Linux it's easy -- it involves a couple of forks and other system calls. Google for daemonize.py. On Windows, a bit of searching seems to find a consensus that the way to do something similar is as a Window's service. I'm just now looking into how to register and start a service, and how to stop and remove it later. Google finds lots of information on this -- perhaps I'll post my result when I've pulled it all together. Gary Herron From Astley.lejasper at gmail.com Thu Sep 4 09:17:03 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Thu, 4 Sep 2008 06:17:03 -0700 (PDT) Subject: Xpath for HTML processing Message-ID: Can anyone suggest something inthat can process an XPath like the following: "/html/body/table[2]/tbody/tr/td[5]/table/tbody/tr[3]/td/table[3]/ tbody/tr[5]/td" Cheers From deets at nospam.web.de Wed Sep 10 17:04:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 23:04:45 +0200 Subject: XML-RPC "filter" In-Reply-To: <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> <6inkkiFrbptbU1@mid.uni-berlin.de> <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> Message-ID: <6iqr3dF3msoU1@mid.uni-berlin.de> luigi.paioro at gmail.com schrieb: > On 9 Set, 17:55, "Diez B. Roggisch" wrote: >> I would go for a slightly different approach: make your server have a >> dispatch-method that delegates the calls to the underlying actual >> implementation. But *before* that happens, extract the information as >> above, and either >> >> - prepend it to the argument list >> >> - stuff it into threadlocal variables, and only access these if needed in >> your implementation. >> >> Diez > > Are you suggesting me to overwrite the _dispatch(self, method, params) > method of SimpleXMLRPCDispatcher? I thought to this possibility, but > it only accepts "method" and "params" as arguments, so, as far as I > know, I have no way to get the user and host address to append. > > Perhaps I've misunderstood your suggestion... in that case can you > post a short example? Ah, darn. Yes, you are right of course, the information itself is not available, as you don't have access to the request. I gotta ponder this a bit more. Diez From george.sakkis at gmail.com Sat Sep 27 09:23:33 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 27 Sep 2008 06:23:33 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: On Sep 27, 1:44 am, "Dmitry S. Makovey" wrote: > George Sakkis wrote: > > Although this works, the second argument to ProxyMethod shouldn't be > > necessary, it's semantically redundant; ideally you would like to > > write it as "bmethod = ProxyMethod('b')". > > since I'm already on exploratory trail (what about that rug being pulled > from under....?) With my code I can do really dirty tricks like this (not > necessary that I'm going to): > > class B_base: > def bmethod(self): > print 'B_base' > > class B(B_base): > def bmethod(self): > print 'B' > > class A: > bmethod=ProxyMethod('b',B_base.bmethod) Yes, that's indeed dirty; don't do it :) > > As before, I don't think > > that's doable without metaclasses (or worse, stack frame hacking). > > Below is the update of my original recipe; interestingly, it's > > (slightly) simpler than before: > > Out of curiosity (and trying to understand): why do you insist on > dictionaries with strings contents ( {'bmethod' : 'b1' } ) rather than > something more explicit ? Again, I can see that your code is working and I > can even understand what it's doing, just trying to explore alternatives :) > > I guess my bias is towards more explicit declarations thus > > bmethod=ProxyMethod('b',B.bmethod) > > looks more attractive to me, but I stand to be corrected/educated why is > that not the right thing to do? I see where you're coming from and I also prefer explicit reflection mechanisms instead of strings (e.g. avoid eval/exec as much as possible). As I mentioned, the second argument to ProxyMethod is (for all sane purposes) redundant, so if you could implement it in a way that "bmethod = ProxyMethod('b')" worked, I would be all for it, but AFAIK it's not possible without a metaclass. A dict with string keys and values to be consumed by a metaclass is perhaps the simplest thing that could possibly work. It contains all the relevant information for hooking the proxy to the delegate methods and nothing more; zero boilerplate code overhead. Also note that it's not that big of a difference; you have to provide the attribute name as a string anyway. > Another thing that turns me away from string dictionaries is that those are > the ones causing me more trouble hunting down typos. Maybe it's just "my > thing" so I'm not going to insist on it. I'm open to arguments against that > theory. >From my experience, I am equally prone to typos for both strings and regular attributes; I agree though that the traceback information is often more helpful when you mistype an attribute. > One argument I can bring in defence of more explicit declarations is IDE > parsing when autocompletion for B.bme... pops up (suggesting bmethod and > bmethod2) and with 'b':'bmethod' it never happens. I don't rely on autocompleting IDEs, at least in dynamic languages, so it's not much of an issue for me but yes, it's another small argument against strings. George From sayananbig at gmail.com Tue Sep 23 14:41:11 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Tue, 23 Sep 2008 11:41:11 -0700 (PDT) Subject: python timers and COM/directshow References: Message-ID: <5b01cc61-60bf-4a6c-b88b-932cf2fc8e0a@s20g2000prd.googlegroups.com> You're right. Let me be more specific. Firstly, the reason I included c++ code is because I'm using Microsoft COM, which is natively in c++, and in fact, to access them through Python I use the comtypes module [import comtypes] and then GetModule('quartz.dll') to access the dll's. I am using the gtk GUI widgets. I have a gtk.Hscale scrollbar which I would like to be a trackbar for the video playback. To coordinate this in Python, much like in c++, I would like to have a timer thread synchronizing the scrollbar update. ie: def scrollbar_callback(args): media_control.CurrentPosition= scrollbar.get_value() def timer_callback(args): #code to update the scrollbar based on video position, something like scrollbar.set_value(media_control.CurrentPosition) >>>*And, I would like to be able to kill, run the timer based on whether the video is playing or paused, ie def player(args): media_control.Run() #plays video timer.run() def pauser(args): media_control.Pause() timer.kill Any tips? -sayanan From prologic at shortcircuit.net.au Wed Sep 10 23:08:04 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 13:08:04 +1000 Subject: Alternatives to traditional RDBMS In-Reply-To: <3ee3f834-b314-4a75-a85c-6a13bb118b09@l33g2000pri.googlegroups.com> References: <6iq90jFdeiU1@mid.uni-berlin.de> <3ee3f834-b314-4a75-a85c-6a13bb118b09@l33g2000pri.googlegroups.com> Message-ID: On Thu, Sep 11, 2008 at 12:06 PM, alex23 wrote: > "James Mills" wrote: >> This is an ORM. They are >> off-topic for this thread :) > > Tsk, such an unfounded bias... To be honest. I have since now tried both ZODB and Durus and both seem really nice. I still do think that ZODB could do with a cleanup though. > I've had a lot of success using sqlalchemy + Elixir together ;) We are talking "Alternatives to RDBs" :) ok ? cheers James -- -- -- "Problems are solved by method" From ewertman at gmail.com Sat Sep 27 14:32:58 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 27 Sep 2008 14:32:58 -0400 Subject: python for *nix system admins In-Reply-To: <170543c70809271123j1334d12ardd09c25ce479978f@mail.gmail.com> References: <1222520796.630579@athprx04> <170543c70809271123j1334d12ardd09c25ce479978f@mail.gmail.com> Message-ID: <92da89760809271132r769411e6t2771b625bbeb04f2@mail.gmail.com> I've been growing a library of my own functions, that use the names of unix commands. They are just conveniences, of course, but I'd suggest the same for sysadmins, it's handy. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 14 03:15:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Sep 2008 07:15:31 GMT Subject: How does python call OS? References: Message-ID: <00dcb436$0$20302$c3e8da3@news.astraweb.com> On Sat, 13 Sep 2008 23:51:39 -0700, Siegfried Heintze wrote: > I see the next sub-chapter on wxWindows for python and the previous > sub-chapter on TK. This is looking a lot like other scripting languages > (such as perl and groovy and even java). Can python call anything > directly or does someone have to write a DLL in C/C++ that calls the > function first? Thanks! I'm not sure I understand your question correctly, but Python can call external programs in a number of ways. I believe the "best" way to do so is with the subprocess module. -- Steven From adykes at panix.com Sat Sep 13 13:41:56 2008 From: adykes at panix.com (Al Dykes) Date: 13 Sep 2008 13:41:56 -0400 Subject: Code example that will make a Skype connection? References: <48cbdd9d$0$1895$426a34cc@news.free.fr> Message-ID: In article <48cbdd9d$0$1895$426a34cc at news.free.fr>, nntpman68 wrote: >Hi, > >Just some thoughts / now answer :-( > >The solution might vary on the platform / OS. > >Would it be acceptable for you to >control for example firefox from python and firefox would control skype >via the skype plugin. (should exist for multiple platforms) > >Do you search a native python solution or would you accept, that some >C-code had to be compiled. > Building a C module is fine as long as I don't have to debug it. I know that FF can do Skype so, I guess, if I write a Python app that runs in a browser, I've solved my problem. I'm about to learn Python, so I haven't given any thought to how to do that. Thanks for the response. What would be picked for a portable Firebox-based app? -- Al Dykes News is something someone wants to suppress, everything else is advertising. - Lord Northcliffe, publisher of the Daily Mail From cipherzero at gmail.com Sat Sep 6 21:15:33 2008 From: cipherzero at gmail.com (cipher) Date: Sat, 6 Sep 2008 18:15:33 -0700 (PDT) Subject: Setter Propertys' mro? Message-ID: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> Whats the mro (method resolution order) of a setter property (__set__ on a descriptor). i seem to be experiencing some weird issue with them. for example >>> class test: ... def _test(self): ... return 4 ... def _stest(self):pass # dont change value ... def _dtest(self,value):pass ... p=property(_test,_stest,_dtest) >>> t=test() >>> t.p 4 >>> t.p=5 >>> t.p 5 Why is that being 'overridden' ( by that i mean that it is storing that value in t's __dict__) >>> t.__dict__ {'t': 5} why DIDNT the setter get hit? however, if i specify the metaclass in the class definition it works just fine... class test: __metaclass__=type def _test(self): return 4 def _stest(self,value):pass # dont change value def _dtest(self):pass p=property(_test,_stest,_dtest) >>> t=test() >>> t.p 4 >>> t.p=5 >>> t.p 4 why do i have to set the __metaclass__ ? this seems like a bug? i know that i probably shouldn't worry about this because if a programmer does want to set my value and it causes an error, thats his problem.... but this bothers me. whats the point of the __set__ method then? Thanks in advanced. -- Cipher From kwmsmith at gmail.com Mon Sep 8 13:10:41 2008 From: kwmsmith at gmail.com (Kurt Smith) Date: Mon, 8 Sep 2008 12:10:41 -0500 Subject: Read and write binary data In-Reply-To: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: On Sun, Sep 7, 2008 at 5:41 PM, Mars creature wrote: > Hi guys, > I am new to Python, and thinking about migrating to it from matlab > as it is a really cool language. Right now, I am trying to figure out If you're trying to migrate from matlab to python I'd take a look at numpy: http://numpy.scipy.org/ And scipy which is built on top of numpy: http://www.scipy.org/ There is a plotting/numerical computation package known as matplotlib that does its best to parallel matlab commands: http://matplotlib.sourceforge.net/ There is support for reading and writing binary data, even fortran records. And last but not least, you can always take a look at the scipy and numpy mailing lists. Good luck, Kurt > how to control read and write binary data, like > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > I googled, but can not find a clear answer. Anyone has clue where can > I learn it? Thanks!! > Jinbo > -- > http://mail.python.org/mailman/listinfo/python-list > From gregturn at mindspring.com Mon Sep 29 08:26:47 2008 From: gregturn at mindspring.com (Goldfish) Date: Mon, 29 Sep 2008 05:26:47 -0700 (PDT) Subject: Spring Python 0.7.0 is released References: <74ird4hidmldkq9bao6sk5grdmpp9vq62e@4ax.com> Message-ID: <53691d34-53f7-4338-9073-68aa15649021@z66g2000hsc.googlegroups.com> Key Features The following features have been implemented: * Inversion Of Control - The idea is to decouple two classes at the interface level. This lets you build many reusable parts in your software, and your whole application becomes more pluggable. You can use either the XmlApplicationContext or the DecoratorBasedApplicationContext. * Aspect-oriented Programming - Spring Python provides great ways to wrap advice around objects. It is utilized for remoting. Another use is for debug tracers and performance tracing. * DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest. * Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated. * Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization. * Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change. * Samples - to help demonstrate various features of Spring Python, some sample applications have been created: o PetClinic - Everybody's favorite Spring sample application has been rebuilt from the ground up using various web containers including: CherryPy. Go check it out for an example of how to use this framework. o Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo! o Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project. For more information, please visit the website at http://springpython.webfactional.com, where you will also find more detailed documentation at http://springpython.webfactional.com/reference/html/. Greg Turnquist From bthayre at physics.ucsd.edu Mon Sep 22 18:44:41 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 22 Sep 2008 15:44:41 -0700 (PDT) Subject: Python based barcode readers Message-ID: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> Does anyone know of any python based barcode readers? I'm looking for something (commercial or open source) that will use some OCR algorithm to read barcodes from an image or ps/pdf file, and ideally will be something along the lines of a callable python script. I have some pretty simple needs, i'm only trying to read code 93 barcodes, so i don't need it to be able to identify multiple symbologies or anything. Any suggestions would be greatly appreciated. Thanks! From grante at visi.com Wed Sep 3 10:15:05 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Sep 2008 09:15:05 -0500 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <87hc8xor9g.fsf@benfinney.id.au> Message-ID: On 2008-09-03, Ben Finney wrote: > Ben Finney writes: > >> I don't see any good reason (other than your familiarity with the D >> language) to use underscores for this purpose, and much more reason >> (readability, consistency, fewer arbitrary differences in syntax, >> perhaps simpler implementation) to use whitespace just as with string >> literals. > > Another reason in support of spaces (rather than underscores) to > separate digit groups: it's the only separator that follows the SI > standard for representing numbers: > > ??? for numbers with many digits the digits may be divided into > groups of three by a thin space, in order to facilitate reading. > Neither dots nor commas are inserted in the spaces between groups > of three. But my keyboard doesn't _have_ a thin-space key! -- Grant Edwards grante Yow! One FISHWICH coming at up!! visi.com From catalinfest at gmail.com Tue Sep 16 11:13:48 2008 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Tue, 16 Sep 2008 08:13:48 -0700 (PDT) Subject: backup with python Message-ID: <11a3fca0-ded7-47c3-aeff-bb08acb1eb20@d1g2000hsg.googlegroups.com> Hi ! I need some help to create backup with python. I want to backup some bases on DVD - RW . How i make this with python ? I want to use python because the program is write on python . Thank you ! From circularfunc at gmail.com Tue Sep 2 21:14:49 2008 From: circularfunc at gmail.com (process) Date: Tue, 2 Sep 2008 18:14:49 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> Message-ID: <8b3857ec-e629-44a3-98f2-8fe509df7b75@f36g2000hsa.googlegroups.com> is this faster btw? I guess big doesn't help, it's only retrieved once anyway? But is rows retrieved in every loop? the python interpreter aint too smart? def getPixels(fileName): im = PIL.Image.open(fileName) colors = [] r, c = im.size big = range(0, c) rows = range(0, r) for y in big: row = [] for x in rows: color = im.getpixel((x,y)) row.append(color) colors.append(row) return numpy.array(colors) From clp at rebertia.com Sat Sep 27 18:13:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 27 Sep 2008 15:13:08 -0700 Subject: check if file is MS Word or PDF file In-Reply-To: References: Message-ID: <47c890dc0809271513p6ea2d52ah4f5194ffffc63422@mail.gmail.com> On Sat, Sep 27, 2008 at 2:43 PM, A. Joseph wrote: > What should I look for in a file to determine whether or not it is a > MS Word file or an Excel file or a PDF file, etc., etc.? including Zip > files > > I don`t want to check for file extension. > os.path.splitext('Filename.jpg') will produce a tuple of filename and > extension, but some file don`t even have extension and can still be read by > MS Word or NotePad. i want to be 100% sure of the file. Well, if you're on unix, you could run the 'file' command and check its output using the 'subprocess' module, but it sounds like you're on Windows... Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Wed Sep 24 23:16:49 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 20:16:49 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 24, 9:49?pm, Asun Friere wrote: > On Sep 25, 11:57 am, "Aaron \"Castironpi\" Brady" > > wrote: > > On Sep 24, 8:40 pm, Asun Friere wrote: > > > ... I think > > > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding > > > all variables for placeholders in the tuple, is better. It's certainly > > > more readible. > > > It's a different answer if you have 'things is/are'. ?'%d thing%s %s'% > > ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ). ?Or excluding > > prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's > > are' if i!= 1 else ' is' ). > > Forgive me for being dull, my caffeine levels have not yet optimal, > but I don't follow. ?Both the solutions you propose do put all the > placeholder variables in the tuple. ?Or are you saying it no longer > remains readible? > > BTW you repeated my mistake with the first scraplet of code. Ah yes. Maybe the order of precedence can undergo a change in the future. ... Though talk about backwards incompatible. They were two options if you have a verb with your noun, which would need a conditional too. From prologic at shortcircuit.net.au Thu Sep 18 20:36:23 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Sep 2008 10:36:23 +1000 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: On Thu, Sep 18, 2008 at 9:02 PM, James Nicolson wrote: > Perhaps it is better to keep descriptions short and store longer > descriptions elsewhere, but there are many programs that have long > descriptions, for example try: ls --help (at least on my machine a lot > of these descriptions are quite long). The longer (program) description is generally provided by the Usage help string. This (in my tools) is generally a long-ish docstring describing the tool, and it's usage. cheers James -- -- -- "Problems are solved by method" From manuhack at gmail.com Fri Sep 5 04:28:44 2008 From: manuhack at gmail.com (Manu Hack) Date: Fri, 5 Sep 2008 04:28:44 -0400 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: <50af02ed0809050128l3a0ffbc8l17be4aa62224d559@mail.gmail.com> On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >> David C. Ullrich: >> >> > At least in mathematics, the sum of the elements of >> > the empty set _is_ 0, while the maximum element of the >> > empty set is undefined. >> >> What do you think about my idea of adding that 'default' argument to >> the max()/min() functions? >> >> Bye, >> bearophile > > For max and min, why can't you just add your argument to the set > itself? > > The reason max([]) is undefined is that max( S ) is in S. It makes sense. >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. It doesn't make sense to me. What do you set x to? From sjmachin at lexicon.net Sat Sep 6 18:42:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 15:42:37 -0700 (PDT) Subject: Cathing several potential errors? References: Message-ID: On Sep 7, 8:13?am, cnb wrote: > if i do > try: > ? ? something > except TypeError, IndexError: > ? ? pass > > only the first error will get caught. I dont want to use Exception and > catch all errors, but just 2. how can i do that? The syntax for what you can have between "except" and ":" is: [expression ["," target]] 'target' is an optional name to be bound to the actual exception object that is raised. If you want to catch multiple kinds of exception, 'expression' needs to be a tuple. See http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 and http://docs.python.org/ref/try.html Cheers, John From castironpi at gmail.com Mon Sep 22 13:32:50 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 10:32:50 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <48d7720d$0$12866$426a34cc@news.free.fr> <48d78c3c$0$6998$426a74cc@news.free.fr> Message-ID: <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> On Sep 22, 8:45?am, "Tim Rowe" wrote: > 2008/9/22 Bruno Desthuilliers : > > >> Sounds to me like a functor, aka a function object: > >>http://en.wikipedia.org/wiki/Function_object > > > Ok, then the simple solution is to implement a callable type (__call__ > > method), possibly with appropriate support for the descriptor protocol if > > it's meant to be usable as a method. > > Yes -- and instantiate the thing and keep the state in the instance, > rather than keeping the state in the class, so that it's possible to > safely have more than one of them if a later design change calls for > it (probably what led people off onto the sidetrack of thinking a > singleton was called for). ?That's the classic way of implementing a > "class [to be] used as a function". > > -- > Tim Rowe I think you are either looking for a class that has a generator, or a generator that has a reference to itself. From mccredie at gmail.com Mon Sep 22 14:14:52 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 22 Sep 2008 11:14:52 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <37a437fd-dfd8-4908-8027-dbf53199567b@w1g2000prk.googlegroups.com> On Sep 21, 3:39?pm, Steven D'Aprano wrote: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? > > -- > Steven It actually sounds like you are doing something similar to the monostate pattern. In Java the monostate pattern is usually implemented by creating a class that only has static functions and variables. You _can_ instantiate it, but every instance will share the same state. In that way it is very similar to the Singleton pattern (http://en.wikipedia.org/wiki/Singleton_pattern). In Python I haven't found a need for monostate, since you can override __new__ and return exactly the same instance. However, you you wanted to be able to inherit a monostate object and share some of the state between the class and subclass it might still be useful. Perhaps if you post some example code? Matt From fredrik at pythonware.com Sat Sep 13 16:14:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 22:14:55 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: <48cbf09c$0$25189$426a74cc@news.free.fr> <48cbf432$0$27507$426a34cc@news.free.fr> Message-ID: Larry Bates wrote: > I also have a personal dislike for early returns because I've found it > makes it harder insert execution trace logging into the code. in a language that makes it trivial to wrap arbitrary callables in tracing wrappers? From stef.mientki at gmail.com Wed Sep 10 14:34:13 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 10 Sep 2008 20:34:13 +0200 Subject: wxpython ms-dos black window popping up in background In-Reply-To: References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> Message-ID: <48C81325.7090506@gmail.com> Mike Driscoll wrote: > On Sep 10, 6:48 am, James A. Donald wrote: > >> On Tue, 9 Sep 2008 14:35:13 -0700 (PDT), icarus >> wrote: >> >> >>> Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw >>> That did it. >>> >>> one more question... >>> >>> how do I create a pythonw standalone executable that works on w32, >>> linux, mac, etc..? >>> >> I have noticed that when applications are written in Python with the >> GUI created by PyGTK, it seems that to install the application on each >> slightly different version of unix is a fairly major task - although >> the creators of PyGTK proudly say that the code will run anywhere, it >> definitely will not install anywhere - the code will only run on a >> slightly different system after a massive and major rewrite of the >> install for that target system. >> >> Horrible installs are a chronic problem GUI programs driven by >> interpreted languages Installing visual basic programs that worked on >> one Windows machine to work on a very slightly different windows >> machine was also a nightmare. >> >> I have not attempted to create installable wxPython windows, but >> generally, "run anywhere" will bite you. Still looking for a good >> solution to "run anywhere". >> >> -- >> ---------------------- >> We have the right to defend ourselves and our property, because >> of the kind of animals that we are. True law derives from this >> right, not from the arbitrary power of the omnipotent state. >> >> http://www.jim.com/ James A. Donald >> > > I haven't had much trouble getting wxPython applications to run in > Windows XP and Ubuntu Hardy Heron. Of course, my GUIs aren't extremely > complex, but I did make use of Hammond's PyWin32 package and had to > wrap those in Platform aware conditional statements. Plus wx was > pretty easy to install in Ubuntu, so that was cool. > > same with me, wxPython, packed with py2exe + ino setup, runs out of the box on XP, Vista, Ubuntu without any problem. cheers, Stef > I can't really comment on other toolkits though. > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From anand.nalya at gmail.com Tue Sep 2 05:45:47 2008 From: anand.nalya at gmail.com (anand nalya) Date: Tue, 2 Sep 2008 15:15:47 +0530 Subject: python glibc error Message-ID: <53bb4b2e0809020245t218662e9m5f50e4c5536d37fb@mail.gmail.com> I'm getting the following errors while trying to run a python script: *** glibc detected *** python: free(): invalid next size (normal): 0x000000000d2da210 *** *** glibc detected *** python: malloc(): memory corruption: 0x000000001b81da60 *** Is this a bug in my script or python or gllbc? Relevent version numbers are: #uname -a Linux myserver 2.6.18-92.1.10.el5 #1 SMP Tue Aug 5 07:42:41 EDT 2008 x86_64 x86_64 x86_64 GNU/Linux # python -V Python 2.4.3 /lib/libc.so.6 | head -1 GNU C Library stable release version 2.5, by Roland McGrath et al. The same script is running fine of fedora 4: On Fedora: uname -a Linux onyomo.com 2.6.11-1.1369_FC4smp #1 SMP Thu Jun 2 23:08:39 EDT 2005 i686 i686 i386 GNU/Linux python -V Python 2.4.1 /lib/libc.so.6 | head -1 GNU C Library development release version 2.3.5, by Roland McGrath et al. Regards, Anand -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 30 16:07:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 17:07:46 -0300 Subject: rlcompleter and wxPython, problems ... References: <48E0045A.3020402@gmail.com> <48E2789F.7090207@gmail.com> Message-ID: En Tue, 30 Sep 2008 16:06:07 -0300, Stef Mientki escribi?: > Gabriel Genellina wrote: >> En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki >> escribi?: >> >>> I'm trying to implement autocompletion into my editor. >>> But I find some weird behavior, >>> or at least I don't have the faintest idea why this behavior occures, >>> and even more important how to solve it >>> In the example below I try to autocomplete " wx.s" , which in my >>> humble opinion should at least produce "wx.stc" (and some others ). >> >> wx is a package. Modules within the package are not, by default, >> attributes of the package - unless they're imported in __init__.py or >> your code imports them. >> So the autocompleter is doing the right thing > in what perspective ? > the autocompleter is only meant to assist the program writer ;-) It's hard to write an autocompleter that does the right thing in all cases :) For a package, you have several sources for possibly valid attributes: - its dir() (that is, the package object's own attributes) - the __all__ attribute, when it exists - the list of modules inside the package directory or directories (given by its __path__ attribute) Sometimes __init__.py is empty - and enumerating the modules inside the directory is the right thing to do. Sometimes the author explicitely imports things in __init__.py, things that comprise the public interfase to the package. In that case I'd not like to see "private" modules appearing in the list. Combine with __all__, which might be defined or not. Mix all those, choose your own autocomplete algorithm, and see what happens... >> - wx.stc does not exist until it is explicitely imported. > I guess I've to study the package. > For the moment I'll implement a user editable list of additions. > > But with your remarks I tried __all__ > And now I wonder why rlcompleter is not simply using "wx.__all__", > it than does gets all the items ? __all__ isn't always defined. It's only used when you do "from xxx import *" AFAIK. -- Gabriel Genellina From mail at timgolden.me.uk Mon Sep 15 11:12:56 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 15 Sep 2008 16:12:56 +0100 Subject: Representation of python code ? In-Reply-To: <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> Message-ID: <48CE7B78.4060209@timgolden.me.uk> showellshowell at gmail.com wrote: > On Sep 15, 4:38 am, Maric Michaud wrote: >> Le Sunday 14 September 2008 15:44:03 Barak, Ron, vous avez ?crit : >> >>> Hi Guys, >>> Is there a script/application, which gets as input python code, and >>> produces a (graphic) representation of the inter-relationships between its >>> classes/functions ? Bye, > > If you can't find anything that's already packaged up and polished, > one possibility is to use the parser and/or compiler.ast modules in > Python to analyze your code, then produce something that graphviz can > consume. On that note, perhaps have a look at PySmell [1] which Orestis Lightning-spoke about at PyconUK over the weekend. It's designed as an autocompletion tool, but he mentioned that the structure it generates could well be used for other purposes. TJG [1] http://orestis.gr/blog/2008/08/31/announcing-pysmell/ From rhamph at gmail.com Mon Sep 22 03:37:52 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 22 Sep 2008 00:37:52 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <3c7157f9-ce47-4f9a-b5cd-2227098a790d@w39g2000prb.googlegroups.com> On Sep 21, 4:39?pm, Steven D'Aprano wrote: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? If defining it as a normal class, it is a namespace. Just a way to cluster multiple globals into a single global. The borg pattern does the same thing, but with a 12 page treatise on why it shouldn't do exactly what it's doing. If using a factory you should probably be using an instance; the fact that your instance is a class is a relatively minor implementation detail. Indeed, the only reason to have a class is to have your methods bound when looked up. You might want a metaclass to cripple it, preventing subclassing and whatnot. *shrug*. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 18:45:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 22:45:44 GMT Subject: lacking follow-through References: Message-ID: <00d453eb$0$20306$c3e8da3@news.astraweb.com> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > Hi, > > This is the strangest post I've seen > since I've joined this list (only > recently). What the ? Oh don't mind castironpi, many people think he's an IRC bot with some experimental AI features that escaped onto Usenet *grins*. If you think that post of his was strange, you haven't seen anything yet. Many people have kill-filed him, and never even see his posts. A word to castironpi: you just suggested you will pester the list to get a response. It's behaviour like that which gets you kill-filed. If you would spend one tenth of the effort that you spend on understand Python on understanding human psychology, you will probably get on with others much better and find fewer people claiming you're a bot. Even if you yourself don't understand how others behave and expect you to behave, think of it as an intellectual puzzle: how can I fool the strange hairless apes into accepting me into their herd? -- Steven From vivainio at gmail.com Sat Sep 6 16:00:14 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Sat, 06 Sep 2008 20:00:14 GMT Subject: How to run PyOS_InputHook from python code (i.e. yield to event loops) Message-ID: <87wshpcaek.fsf@gmail.com> Background: PyOS_InputHook is something that gets run when python is doing raw_input. TkInter and friends use it to run their event loops, so that their events are handled while python is doing raw_input. What I'd like to do is run the same function without having to do raw_input. I.e. I'd like to run whatever event loop is available, without incorporating any gui-specific code (PyOS_InputHook seems like a nifty way to accomplish this). My actual use case is to keep a tkinter application responsive while launching a background process (and waiting for it to complete!). My eventual code would be something like: launch_process_in_thread('bzr pull') while not is_done: pyos_inputhook() time.sleep(0.1) print "Done!" From fredrik at pythonware.com Thu Sep 4 16:51:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 22:51:34 +0200 Subject: Not fully understanding the role of Queue.task_done() In-Reply-To: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: Martin DeMello wrote: > I'm writing a cluster monitor, that collects information from a set of > machines and logs it to a database > > In the interests of not hammering the db unnecessarily, I'm > considering the following > 1. A series of independent "monitor" threads that collect information > over TCP from the cluster of machines, and write it to a queue > 2. A "logger" thread that empties the queue every second or so and > inserts the collected information to the db via a single insert > statement why are you using a queue for this case, btw? why not just use a plain list L = [] lock = threading.Lock() and add stuff using append in the monitor threads with lock: L.append(item) and regularily reset the list in the logger thread with lock: data = L[:] L[:] = [] # clear the list for item in data: ... insert into database ... (list append and assignments to global variables are atomic in CPython, so you can eliminate the lock by being a bit clever, but that's probably better left for a non-premature optimization pass). From hrishys at yahoo.co.uk Tue Sep 23 11:34:25 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Tue, 23 Sep 2008 15:34:25 +0000 (GMT) Subject: Linq to Python In-Reply-To: <6jsevmF4uaq4U1@mid.uni-berlin.de> Message-ID: <316028.12070.qm@web27403.mail.ukl.yahoo.com> Hi Thanks for those links however LINQ seems to be much more then ORM tool it can for example join an XML file with a relational datasource or create a XSD regards Hrishy --- On Tue, 23/9/08, Diez B. Roggisch wrote: > From: Diez B. Roggisch > Subject: Re: Linq to Python > To: python-list at python.org > Date: Tuesday, 23 September, 2008, 4:06 PM > hrishy wrote: > > > Hi > > > > Will LINQ be ported to Python ? > > Take a look at SQLAlchemy or SQLObject for python-based > ORM/SQL-abstractions. > > Apart from that, python is already heavily based on > concepts like iterators, > filtering. Take a look at itertools. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From tino at wildenhain.de Mon Sep 15 07:29:41 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 15 Sep 2008 13:29:41 +0200 Subject: how to protect the source In-Reply-To: References: Message-ID: <48CE4725.7000502@wildenhain.de> Hi, Jo?o Abrantes wrote: > Hello Everyone. > > > I am building a client in python that will connect himself to a mysql > server with a certain username and password. I will compile this client > and turn him into a .exe . The thing is that I know that is possible to > get the source of the code back from an .exe and I don't want anyone to > know which username and password are they using because I don't want > them to access to the mysql server without my client. Do you have any > ideas of what can i do? Thanks! Don't put that into the source. Use whatever your database supports for authorisation with a config file or ssl certificate. You can not hide the credentials when you need to give them out of your hands. Better protect the database objects with permissions on tables, views and stored procedures. Everything your program can do everybody having your program can do. HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From almar.klein at gmail.com Tue Sep 16 03:37:22 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 16 Sep 2008 09:37:22 +0200 Subject: Python IDEs with F5 or hotkey shell interaction In-Reply-To: <48CE9428.7090406@gmail.com> References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> <48CE9428.7090406@gmail.com> Message-ID: > > Any change we could see some code already ? > I'm working on something similar, > bored of the bugs in my current IDE. > Here are my first notes: > http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_debug.html > It should become a very-simple-very-high-level IDE, > like Matlab, but then better ;-) Well, its still in development, but I can send you a copy of the current status. I see that you did a lot of work on debugging. I haven't done any of that yet; I've been focusing mainly on getting an interactive environment with a shell that feels like the normal python shell, but with code completion. Maybe we can help each-other out a bit :) Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Mon Sep 8 05:22:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Sep 2008 02:22:03 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> Message-ID: <24098410-5bcb-40a2-b6ef-08d69cfef346@v39g2000pro.googlegroups.com> On Sep 8, 9:14?am, "James Mills" wrote: > On Mon, Sep 8, 2008 at 8:59 AM, John Machin wrote: > > What do you mean by "this right"? Perhaps the Divine Right of OPs, > > managers, examiners, business analysts, etc never to give a complete > > spec up front and never to contemplate the consequences of Murphy's > > Law? > > Now you're being silly. > Only in so far as I followed the habit of OPs and suchlike by using "never" instead of "rarely". From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 24 03:13:52 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 09:13:52 +0200 Subject: finding domain name In-Reply-To: <8e874f68-838b-4fc1-8228-1787525ca780@x41g2000hsb.googlegroups.com> References: <48d941f0$0$3738$426a74cc@news.free.fr> <8e874f68-838b-4fc1-8228-1787525ca780@x41g2000hsb.googlegroups.com> Message-ID: <48d9e8a4$0$6127$426a34cc@news.free.fr> Bobby Roberts a ?crit : > On Sep 23, 1:23 pm, Bruno Desthuilliers > wrote: >> Bobby Roberts a ?crit : >> >>> hi group. I'm new to python and need some help and hope you can >>> answer this question. I have a situation in my code where i need to >>> create a file on the server and write to it. That's not a problem if >>> i hard code the path. However, the domain name needs to be dynamic so >>> it is picked up automatically. The path to our websites is >>> home/sites/xxxxx/ >>> where xxxxx represents the domain name. >>> How can I find the domain name of the current url being viewed. >> What are you using exactly ? cgi ? wsgi ? Else ? > > mod python Ok. So the informations you're looking for should be accessible as attributes of the request object that get passed to your request handler. Attributes of interest here are mostly request.hostname, request.uri, request.path_info and request.filename. More informations here: http://www.modpython.org/live/current/doc-html/pyapi-mprequest-mem.html > over an in-house framework written years ago Mmm... Then you might want to checkout which version of mod_python you're using, and make sure you read the corresponding doc... FWIW, there's also a mod_python mailing-list, so I suggest you seek further assistance wrt/ mod_python specific stuff there. Of course, questions about the Python language and it's standard lib are welcome here. > without > documentation use the code, young jedi !-) > so it's not the easiest thing to navigate. We will be > moving to django this fall. From skip at pobox.com Thu Sep 18 08:23:14 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 18 Sep 2008 07:23:14 -0500 Subject: XML-schema 'best practice' question In-Reply-To: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: <18642.18482.549773.574753@montanaro-dyndns-org.local> Frank> 1. Don't use default values - create the document with all values Frank> filled in. Frank> 2. Use python to check for missing values and fill in the defaults Frank> when processing the document. Frank> Or maybe the best practice is to *always* validate a document Frank> before processing it. Frank> How do experienced practitioners handle this situation? 3. Don't use XML. (sorry, couldn't resist) Skip From m_palmer45 at yahoo.ca Tue Sep 23 11:50:15 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 23 Sep 2008 08:50:15 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> Message-ID: On Sep 23, 10:08 am, Michael Palmer wrote: > May be the reason for Decimal to accept float arguments is that NOT to accept float arguments. From pruebauno at latinmail.com Fri Sep 19 13:25:41 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Fri, 19 Sep 2008 10:25:41 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <1b4f0571-0346-4462-89b2-c5a11b4a028b@i76g2000hsf.googlegroups.com> On Sep 18, 7:42 pm, Steven D'Aprano wrote: > On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote: > > Now the obvious winner is pruebono - even unoptimized, using sets seems > > to be *way* faster than even the most optimized corrected version of > > your algorithm. > > I'm not being snarky about losing priority here, but I submitted > essentially the same solution two hours earlier than pruebono. > > Are people not seeing my posts? Have I been kill-filed by everyone except > Mensator? I also asked a question about HTTPError and I haven't seen any > responses at all. > > -- > Steven I see your post now, but I didn't notice it at the time I posted. Could be because I am using the noticeable bad Google groups interface that is known for being unreliable. Duplicate solutions on Usenet are almost a given and I consider duplicate solutions a good thing, it means that other people will be able to understand that code. In any case I am not here for glory I am posting under a pseudonym so nobody discovers that I am slacking off at work reading Usen[carrier lost] From invalid at invalid Thu Sep 18 10:59:24 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 18 Sep 2008 09:59:24 -0500 Subject: A unique instance of Python GUI program References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Message-ID: On 2008-09-16, akineko wrote: > This may not be a Python specific challenge. I have a GUI > program written in Python + Tkinter. It works very well. > > Now, I would like to start it from a shell script. As my GUI > program includes a server, it should not have more than one > instance. Is there any easy way to check if another instance > of the program is already running. > > I vaguely remember that Windows programming provides a way to > check. On unix the solution is usually a lockfile placed in a predefined location. Other people use a socket, but that's a bit more susceptible to namespace collisions with unrelated programs. > A platform independent approach would be nice but a solution > for X is sufficient for my application. I don't see what X has to do with it. > Any comments will be greatly appreciated. This question is asked and answered about once a week, and I'm always surprised at how frequently it comes up. I've been doing sw development for decades and apart from Unix system daemons, I don't remember ever needing to prevent multiple instances of an application from running. Can somebody lend me a clue as to why this question comes up so often? There can't be that many people writing Unix daemons in Python (and if they were, they'd probably already know about lockfiles). Just curious... -- Grant Edwards grante Yow! Is something VIOLENT at going to happen to a visi.com GARBAGE CAN? From default at defaulter.net Sat Sep 27 19:10:09 2008 From: default at defaulter.net (default) Date: Sat, 27 Sep 2008 19:10:09 -0400 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> Message-ID: On Sat, 27 Sep 2008 15:56:39 -0700, Jim Thompson wrote: >Now you know why I blanket kill-file googlegroups. > > ...Jim Thompson I knew that! Every now and then one groper will make it back to the scene of his crime - but, granted, there was no hope for this one. -- ----== Posted via Pronews.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.pronews.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= - Total Privacy via Encryption =--- From gagsl-py2 at yahoo.com.ar Tue Sep 30 18:17:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 19:17:57 -0300 Subject: problem with "ImportError: No module named..." and sockets References: Message-ID: En Tue, 30 Sep 2008 18:38:19 -0300, Daniel escribi?: > [BEGIN CODE] > #!/usr/bin/python > import SocketServer > import os, sys > newpath = os.path.normpath( os.path.join( __file__, "../../.." )) > sys.path.insert(0, newpath) > > from pop.command.UpdateCommand import * > import cPickle > > > Traceback (most recent call last): > [...] > ImportError: No module named UpdateCommand > > I import the module at the top of the file server.py, but it doesn't > throw the ImportError until it tries to unpickle. Notice that you don't import the UpdateCommand module - you import all names defined inside it instead. It's not the same thing. See http://effbot.org/zone/import-confusion.htm -- Gabriel Genellina From wuwei23 at gmail.com Sun Sep 28 20:13:28 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 28 Sep 2008 17:13:28 -0700 (PDT) Subject: Odd Errors References: Message-ID: <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> The problem is with this: > ? ? ? ? lines = lines.append(inLine) The append method of a list modifies the list in-place, it doesn't return a copy of the list with the new element appended. In fact, it returns None, which it then attaches the label 'lines' to, so the next iteration through it tries to call None.append... Replace the line with: lines.append(inLine) From metaperl at gmail.com Tue Sep 9 09:12:19 2008 From: metaperl at gmail.com (metaperl.com) Date: Tue, 9 Sep 2008 06:12:19 -0700 (PDT) Subject: creating an (inefficent) alternating regular expression from a list of options Message-ID: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Pyparsing has a really nice feature that I want in PLY. I want to specify a list of strings and have them converted to a regular expression. A Perl module which does an aggressively optimizing job of this is Regexp::List - http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm I really dont care if the expression is optimal. So the goal is something like: vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| u|ii|i)' Is there a public module available for this purpose? From python at p0w.org Fri Sep 26 15:56:57 2008 From: python at p0w.org (Strato) Date: Fri, 26 Sep 2008 21:56:57 +0200 Subject: ConfigParser subclass problem Message-ID: <48DD3E89.8000004@p0w.org> Hi folks, I think I do something wrong, but I don't see why it doesn't work, so I will explain: I've searched in the list archive and found this thread, that explain exactly what I want to have: the options strings returned by ConfigParser without being lower cased. I tryed to reproduce this, by subclassing the SafeConfigParser class, like this: * in my main script: from MyConfigParser import * * in the MyConfigParser.py file: from ConfigParser import SafeConfigParser class MyConfigParser(SafeConfigParser): def optionxform(self, optionstr): print "Called the modified version of the class" return optionstr then, when I run the script, every time a calls to my own class is done, the print statment is shown in the console, so this may work, but when I use the .items() method of the class, I got a lower cased result ! (In my test, using the .items() method is my only try to test the new class) Does anybody has an idea of what I'm doing wrong ? Thanks, Strato From 4g4trz802 at sneakemail.com Tue Sep 9 15:14:57 2008 From: 4g4trz802 at sneakemail.com (Michael Hoffman) Date: Tue, 09 Sep 2008 12:14:57 -0700 Subject: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles References: Message-ID: Michael Hoffman wrote: > unlink = os.unlink Actually, I need to use shutil.rmtree instead, but you get the idea. From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 10:25:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Sep 2008 14:25:30 GMT Subject: Ascii Menu I/O redirection References: Message-ID: <00e501cf$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 23:14:26 +0200, Hendrik van Rooyen wrote: > class console(object): > """ > This spoofs a single file like object, using stdout & - in > (Minimalistic proof of concept implementation) """ > > def __init__(self): > self.read = sys.stdin.read > self.readline = sys.stdin.readline > self.write = sys.stdout.write > self.flush = sys.stdout.flush > self.closeout = sys.stdout.close # keep references to close > self.closein = sys.stdin.close > > def close(self): > self.closein() > self.closeout() I'm not sure that closing stdin and stout are a good idea. This could have side-effects for other parts of your program, and will almost certainly end badly if you're running in the interactive interpreter. Other than that, what you've done seems reasonable, although since every instance of console() has the same state, I'd write it slightly differently: class console(object): """ This spoofs a single file like object, using stdout & - in (Minimalistic proof of concept implementation) """ read = sys.stdin.read readline = sys.stdin.readline write = sys.stdout.write flush = sys.stdout.flush closeout = sys.stdout.close closein = sys.stdin.close @classmethod def close(cls): cls.closein() cls.closeout() [...] > Questions are: > > Is this a reasonable way of doing this kind of thing? Is there a > canonical or better way of doing it? Am I missing something? It seems to me that you might have been better off to write your program to take two files, an input and an output, instead of forcing both to go to the same file. if 'serial' in sys.argv: # for RS-232 i/o to terminal infile = open('/dev/ttyS0','r+b') outfile = infile else: # console i/o infile = sys.stdin outfile = sys.stdout Hope this helps. -- Steven From gagsl-py2 at yahoo.com.ar Wed Sep 3 21:41:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 22:41:57 -0300 Subject: sys.stdin on windows References: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> <48BE63EC.1070004@timgolden.me.uk> Message-ID: En Wed, 03 Sep 2008 07:16:12 -0300, Tim Golden escribi?: > Gabriel Genellina wrote: >> En Wed, 03 Sep 2008 06:16:03 -0300, zugnush at gmail.com >> escribi?: >> >>> When I try to run the same thing on windows I get >>> IOError: [Error 9] Bad file descriptor >>> >>> How can I make this more windows friendly? >> Explicitely invoking the interpreter worked for me. That is, these two >> commands worked fine: >> type test.txt | python count.py >> python count.py < test.txt >> But I cannot explain *why* it doesn't work the other way. > > Known bug in NT-based file association. I'll try to find an online > reference, but that's basically > what it comes to. I think you can faff-about with > batch files to achieve the effect, but I can't > quite remember. > > http://support.microsoft.com/kb/321788 Uhmm... That KB article says the bug was corrected in Windows XP SP1, but I have SP3 installed and the test failed. Updating the registry by hand solved the problem. A regression maybe? -- Gabriel Genellina From Lie.1296 at gmail.com Wed Sep 17 11:51:08 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 17 Sep 2008 08:51:08 -0700 (PDT) Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: <8d2d6b9a-ee8a-4b66-825d-ab0ac2ee485d@n38g2000prl.googlegroups.com> On Sep 16, 3:20?pm, Armin wrote: > John Machin wrote: > > On Sep 16, 6:45 am, Armin wrote: > > >> Yes, but this is very unconvenient. > >> If d should reference the list a extended with a single list element > >> you need at least two lines > > >> a.append(7) > >> d=a > > >> and not more intuitive d = a.append(7) > > > Methods/functions which return a value other than the formal None and > > also mutate their environment are "a snare and a delusion". Don't wish > > for them. > > ? ?c = [9,10] > ? ?[1,2,3,4,7].append(c) -> Is this a valid expression? > Yes, that is a valid expression, however, the list you're appending to is immediately discarded. > ? ?The 'value' of that expression is None. > > ? ?However ... that's the way of the implementation of the append method. > ? ?It's a little bit confusing to me ... actually, you could implement your own myList which returns a value on append method: class MyList(list): def append(self, item): list.append(self, item) return self # or # return self[:] # if you want it to return a copy But I recommend against that. > --Armin > > Thanks to all ! > > > > > > > Inconvenient? How often do you want to mutate a list and then set up > > another reference to it?- Hide quoted text - > > - Show quoted text - From paul at boddie.org.uk Tue Sep 2 04:52:41 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 2 Sep 2008 01:52:41 -0700 (PDT) Subject: python mechanize/libxml2dom question References: Message-ID: On 2 Sep, 05:35, "bruce" wrote: > > i've got the following situation, with the following test url: > "http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#". > > i can generate a list of the tables i want for the courses on the page. > however, when i try to create the xpath query, and plug it into the xpath > within python, i'm missing something. if i have a parent xpath query, that > generates a list of results/nodes... how can i then use the individual > parent node, and trigger off of it, to get further information. You can always use the parentNode property on the nodes you get as results from the XPath query, but I guess what you want to do is to "rewind" and issue queries relative to some ancestor of the result nodes. [...] > # **** course names > > cpath='//table[position()>0]/descendant::td[position()=2][@width="85%"]/../td[1]/font/a[2]/text()' This obviously gets you right down to the hyperlink text within a part of the table. However, it may be easier to break this query up in order to get a more manageable overview of the process. My understanding of the above query is that it can first be rewritten as the following: cpath = "//table//td[position()=2 and @width='85%']/../td[1]/font/a[2]/ text()" Or even this: cpath = "//table[.//td[position()=2 and @width='85%']]//td[1]/font/ a[2]/text()" But what you could do is to obtain the important tables first: tables = d.xpath("//table[.//td[position()=2 and @width='85%']]") Here, we use the bracketed term to ensure that the table is the right one, but we don't actually descend inside the table. You could, from this, get the name by doing a query from each of these tables: for table in tables: cnames = table.xpath(".//td[1]/font/a[2]/text()") # list of text nodes You might want to consider a slightly safer approach when getting the text: cnames = table.xpath(".//td[1]/font/a[2]") # list of nodes, should be one name = cnames[0].textContent # all the text from the link When looking for the details, you can then write your query relative to these tables, rather than having to figure out the location of the details from the text nodes you've just extracted. details = table.xpath("following-sibling::table[1]") # list of max 1 node > i'm assuming that there's a libxml2node method that will do what i need that > i'm missing... You should be able to issue XPath queries from any node. There have been issues with libxml2dom and attribute nodes obtained from XPath, but these were fixed in recent changesets. Paul From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 24 03:16:14 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 09:16:14 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <48d9e932$0$6127$426a34cc@news.free.fr> Drake a ?crit : > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), Arrghll ! NO, DONT ! > or should the exception propagate to the calling program which > handles the issue? Yes, by all means and for God's sake. > Thanks in advance for anyone who can either answer my question or > point me to where this question has already been answered. There have been numerous threads about this here. From bj_666 at gmx.net Tue Sep 30 12:11:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Sep 2008 16:11:11 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: <6kf1cvF7dmkkU4@mid.uni-berlin.de> On Tue, 30 Sep 2008 10:57:19 -0500, Grant Edwards wrote: > On 2008-09-30, Peter Pearson wrote: >> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: >>> >>> 1. Multi dimensional arrays - how do you load them in python For >>> example, if I had: >>> ------- >>> 1 2 3 >>> 4 5 6 >>> 7 8 9 >>> >>> 10 11 12 >>> 13 14 15 >>> 16 17 18 >>> ------- >>> with "i" being the row number, "j" the column number, and "k" the .. >>> uhmm, well, the "group" number, how would you load this ? >>> >>> If fortran90 you would just do: >>> >>> do 10 k=1,2 >>> do 20 i=1,3 >>> >>> read(*,*)(a(i,j,k),j=1,3) >>> >>> 20 continue >>> 10 continue >>> >>> How would the python equivalent go ? > > You would drag yourself out of the 1960s, install numpy, and then do > something like this: > > a = read_array(open("filename.dat","r")) In [64]: a = numpy.fromfile('test.txt', dtype=int, sep=' ') In [65]: a Out[65]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) In [66]: a.reshape(2, 3, 3) Out[66]: array([[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]) Ciao, Marc 'BlackJack' Rintsch From python.list at tim.thechases.com Mon Sep 15 06:52:16 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Sep 2008 05:52:16 -0500 Subject: Unable to see os.environ['COLUMNS'] In-Reply-To: <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> References: <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> Message-ID: <48CE3E60.8000004@tim.thechases.com> >> What's the best way to read what seems to be a >> pseudo-environment variable? > > You can't. You need to export the variable in the parent shell > before it exec's the child: > > $ export COLUMNS > > $ python -c "import os; print os.environ['COLUMNS']" > 80 This works well, and also manages to keep up to date across runs as window-size changes. More importantly, it makes sense (minus the "why doesn't bash automatically export COLUMNS to subshells" question, but a little investigation shows I can use "set -a" or "export COLUMNS" in my .bashrc and everything works). > Now, on to the question you're about to ask: > > Q: How do I find out how big my terminal is from a Python > program? You must be one of the folks working with the Python time-machine. :) (okay, so the intent of my question was pretty obvious) > A: You use the TIOCGWINSZ ioctl call on the terminal's file > descriptor: > >>>> import sys,fcntl,termios,struct >>>> data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234') >>>> struct.unpack('hh',data) > (24, 80) > > There's a more detailed explanation here (including an > explanation of what the third parameter to ioctl() does, and > how you detect changes in the window size): > > http://mail.python.org/pipermail/python-list/2006-February/365710.html Thanks, I'll read up on that, as well as investigate ncurses options. > There's also chance that you'd be better off just using ncurses or > newt for screen management, but that's another post. The screen-width is merely for a little output formatting to determine how many items can fit across. However, given the opacity of the ioctl() call, it might not hurt to look into using curses. Thanks for the pointers, -tkc From aahz at pythoncraft.com Sat Sep 27 10:00:37 2008 From: aahz at pythoncraft.com (Aahz) Date: 27 Sep 2008 07:00:37 -0700 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> Message-ID: In article <8763oiuhj2.fsf at benfinney.id.au>, Ben Finney wrote: >Steven D'Aprano writes: >> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: >>> >>> An ordinary singleton is instantiating the class multiple times >>> yet returning the same instance object; a class singleton is >>> simply using the class directly (like a module). > >Where is this "class singleton" terminology from? It seems redundant >to me. It also doesn't seem to have anything to do with what >"singleton" means as a pattern; "using a class" is simply using a >class. I don't remember where I picked it up, probably here some years ago. The point of the terminology is to distinguish how the class is *used*, in precise parallel with "module singleton". >> I'd like to be able to call [a class] as if it were a function. >> Normally calling a class object returns an instance -- I wish to >> return something else. > >In that case, you *don't* want a class at all; the entire point of a >class is to define behaviour for instances. Absolutely agreed with your first clause, disagreed about the second clause. As I said earlier, the main point of a class singleton is to get the effect of a module singleton without the need to create another file on disk. In that case there is no instance and therefore the point of the class is no longer to define behavior for instances. But you can't call a module, and classes have well-defined behavior for calling them, so you shouldn't try to pervert a class singleton by defining behavior for calling them. In fact, I would recommend creating an __init__() method that raises NotImplementedError precisely to prevent this usage (or have a __new__() method that returns None, but I generally prefer to recommend practices that work with classic classes). One cute reason to prefer class singletons to module singletons is that subclassing works well for creating multiple singletons. But really, the main reason I use class singletons is that they are the absolute simplest way to get attribute access: class Foo: pass Foo.bar = 'xyz' if data == Foo.bar: print "!" Once it gets much more complicated than that, I prefer to use a smarter object. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From patrick.chartier at aero.bombardier.com Sun Sep 7 06:06:06 2008 From: patrick.chartier at aero.bombardier.com (wildfireporn.com@googlegroups.com) Date: Sun, 7 Sep 2008 03:06:06 -0700 (PDT) Subject: Watch Videos Adult online for free Message-ID: <10e50a24-91dd-46af-9346-7fce7c54ba8d@a1g2000hsb.googlegroups.com> No charge! Free watch adult videos online http:///www.wildfireporn.com From mnordhoff at mattnordhoff.com Fri Sep 26 09:42:13 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 26 Sep 2008 13:42:13 +0000 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <18652.51228.620303.28571@montanaro-dyndns-org.local> References: <18652.51228.620303.28571@montanaro-dyndns-org.local> Message-ID: <48DCE6B5.3080900@mattnordhoff.com> skip at pobox.com wrote: > I took over spam filter management for the python.org mailing lists a couple > months ago and made a few changes to the way the spam filter is trained. > Things seem to be at a reasonable level as far as I can tell (I see a few > spams leak through each day), though I wasn't actively reading > comp.lang.python/python-list at python.org before I took over the task, so I > have nothing to compare with. Does the level of spam leaking through the > filter now seem excessive? Is it more or less than in June and July? > > Thanks, > > Skip Montanaro Over the last 24 hours, I think I count 10 spams, but that's probably higher than usual. I don't know if it's "excessive". It certainly isn't ideal, but it only takes 30 seconds to get rid of them, and we need to give my spam filter something to do, right? :-) I haven't been reading the list for very long, so I don't know how it compares to June or July. It feels like it's been increasing over time, but I don't have any numbers to back that up. -- From R.Brodie at rl.ac.uk Wed Sep 10 12:30:30 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 10 Sep 2008 17:30:30 +0100 Subject: md5 differences References: Message-ID: "Python" wrote in message news:mailman.799.1221063937.3487.python-list at python.org... > here's an example: > Arno at Computer:~% echo "hello" | md5 > b1946ac92492d2347c6235b4d2611184 > How do I get the same results? Checksum the same string. >>> md5.new("hello\n").hexdigest() 'b1946ac92492d2347c6235b4d2611184' From mail at timgolden.me.uk Mon Sep 22 11:59:41 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 22 Sep 2008 16:59:41 +0100 Subject: Reading Windows CSV file with LCID entries under Linux. In-Reply-To: References: Message-ID: <48D7C0ED.9070501@timgolden.me.uk> Thomas Troeger wrote: > I've stumbled over a problem with Windows Locale ID information and > codepages. I'm writing a Python application that parses a CSV file, > the format of a line in this file is "LCID;Text1;Text2". Each line can > contain a different locale id (LCID) and the text fields contain data > that is encoded in some codepage which is associated with this LCID. My > current data file contains the codes 1033 for German and 1031 for > English US (as listed in > http://www.microsoft.com/globaldev/reference/lcid-all.mspx). > Unfortunately, I cannot find out which Codepage (like cp-1252 or > whatever) belongs to which LCID. > > My question is: How can I convert this data into something more > reasonable like unicode? Basically, what I want is something like > "Text1;Text2", both fields encoded as UTF-8. Can this be done with > Python? How can I find out which codepage I have to use for 1033 and 1031? The GetLocaleInfo API call can do that conversion: http://msdn.microsoft.com/en-us/library/ms776270(VS.85).aspx You'll need to use ctypes (or write a c extension) to use it. Be aware that if it doesn't succeed you may need to fall back on cp 65001 -- utf8. TJG From skip at pobox.com Thu Sep 4 20:11:56 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Sep 2008 19:11:56 -0500 Subject: Python test case management system? In-Reply-To: References: Message-ID: <18624.31052.912418.390277@montanaro-dyndns-org.local> Mudcat> Does anyone know of a good test case management system written Mudcat> in python, or possibly another application (either open source Mudcat> or commercial) that can be extended using python? I don't know what you mean by "test case management system", but within the Python community there are two core modules designed to support unit test creation: unittest and doctest. Outside of the Python distribution there are other tools which aim to make writing and running unit tests simpler. Examples include py.test and nose. I'm sure there are others. These might be a couple PyPI categories to start a search: http://pypi.python.org/pypi?:action=browse&c=430 http://pypi.python.org/pypi?:action=browse&c=431 Skip From sjmachin at lexicon.net Fri Sep 5 19:55:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 16:55:27 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> <0e12f3cd-7088-4f64-afa8-eb5ac4d00031@t1g2000pra.googlegroups.com> Message-ID: <5d2aedd3-2b93-4c1f-862c-db264552dec0@1g2000pre.googlegroups.com> On Sep 6, 9:30?am, John Machin wrote: > On Sep 6, 7:49?am, bearophileH... at lycos.com wrote: > > > John Machin: > > > > Consider this:>>> hash(123) == hash(123.0) == hash(123L) > > > True > > > Right... Can you explain me why Python designers have chosen to build > > a hash() like that? > > I can't channel them; my rationalisation is this: > > Following the Law of Least Astonishment,>> 123 == 123.0 == 123L > > True > > Consequently if x == y, then adict[x] and adict[y] should give the > same result. > Another reason for not folding in the type of the object is this: >>> type([]) >>> hash(type([])) 505252536 >>> id(type([])) 505252536 IOW hash(T) == id(T) where T is a type. id(obj) is just a memory address which can vary between executions of the same Python binary on the same machine ... not very reproducible. There is no guarantee in the docs for hash about under what circumstances hash(x) != hash(x) of course; I'm just relying on the least astonishment law again :-) And, again, we don't know what the OP's full requirements are ... From steve at REMOVE-THIS-cybersource.com.au Tue Sep 2 13:06:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 17:06:56 GMT Subject: Large amount of files to parse/organize, tips on algorithm? References: Message-ID: <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> On Tue, 02 Sep 2008 09:48:32 -0700, cnb wrote: > I have a bunch of files consisting of moviereviews. > > For each file I construct a list of reviews and then for each new file I > merge the reviews so that in the end have a list of reviewers and for > each reviewer all their reviews. > > What is the fastest way to do this? Use the timeit module to find out. > 1. Create one file with reviews, open next file an for each review see > if the reviewer exists, then add the review else create new reviewer. > > 2. create all the separate files with reviews then mergesort them? The answer will depend on whether you have three reviews or three million, whether each review is twenty words or twenty thousand words, and whether you have to do the merging once only or over and over again. -- Steven From marco.bizzarri at gmail.com Wed Sep 3 07:46:23 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 3 Sep 2008 13:46:23 +0200 Subject: Python IDEs with F5 or hotkey shell interaction In-Reply-To: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> Message-ID: <3f0d61c40809030446m2ed635ckbdeeafcf8921f82d@mail.gmail.com> On Tue, Sep 2, 2008 at 4:01 PM, mmm wrote: > > I might look at > Eclypse with pydev > Jedit > And these commercial/professional IDEs > Wing > Komodo IDE > Zeus > > But before doing so I wanted to know form experienced users: > > ** How hard is it to configure any of the general editors/IDEs to run > a Python shell using a hotkey (such as IDLEs F5) and whether any can > be set up for full interactivity. > > I understand and appreciate the difficulties to get full IDLE-like > interactivity, but what comes closest? > -- > http://mail.python.org/mailman/listinfo/python-list > I do not think I qualify for experienced users; I've used pydev for many years, and I'm quite comfortable with it. It is an eclipse based IDE, therefore you've some of its niceties and some of its drawbacks. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From dickinsm at gmail.com Tue Sep 30 07:42:52 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 30 Sep 2008 04:42:52 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> Message-ID: <77c70884-4667-4f62-b1e9-ad235855a3d5@z72g2000hsb.googlegroups.com> On Sep 30, 9:21?am, Terry Reedy wrote: > If no one beats me to it, I will probably file a bug report or two, but > I am still thinking about what to say and to suggest. I can't see many good options here. Some possibilities: (0) Do nothing besides documenting the problem somewhere (perhaps in a manual section entitled 'Infrequently Asked Questions', or 'Uncommon Python Pitfalls'). I guess the rule is simply that Decimals don't mix well with other numeric types besides integers: if you put both floats and Decimals into a set, or compare a Decimal with a Fraction, you're asking for trouble. I suppose the obvious place for such a note would be in the decimal documentation, since non-users of decimal are unlikely to encounter these problems. (1) 'Fix' the Decimal type to do numerical comparisons with other numeric types correctly, and fix up the Decimal hash appropriately. (2) I wonder whether there's a way to make Decimals and floats incomparable, so that an (in)equality check between them always raises an exception, and any attempt to have both Decimals and floats in the same set (or as keys in the same dict) also gives an error. (Decimals and integers should still be allowed to mix happily, of course.) But I can't see how this could be done without adversely affecting set performance. Option (1) is certainly technically feasible, but I don't like it much: it means adding a whole load of code to the Decimal module that benefits few users but slows down hash computations for everyone. And then any new numeric type that wants to fit in with Python's rules had better worry about hashing equal to ints, floats, Fractions, complexes, *and* Decimals... Option (2) appeals to me, but I can't see how to implement it. So I guess that just leaves updating the docs. Other thoughts? Mark From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 14:01:32 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 20:01:32 +0200 Subject: creating a similar object from an derived class In-Reply-To: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> References: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> Message-ID: <48beecec$0$16897$426a74cc@news.free.fr> Scott a ?crit : > Let's say I have an object: s/object/class/ > class foo(): > def create_another() > return foo() class Foo(object): def create_another(self): return Foo() > def blah(): def blah(self): > x = self.create_another() > ... do something with X > Now I create a inherited class of this object: > > class bar(foo): class Bar(Foo): > ... > > If I call bar.create_another(), it will Actually, it will raise a TypeError... > return a foo() instead of a > bar(). This isn't what I want. I would like bar.create_another() to > create an instance for bar(). def create_another(self) return type(self)() And while you're at it, since - at least in this concrete case - you need access to the class but not to the instance, you could make it a classmethod: class Foo(object): @classmethod def create_another(cls): return cls() HTH From deets at nospam.web.de Thu Sep 4 07:19:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Sep 2008 13:19:20 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <6i9uidFphkg0U1@mid.uni-berlin.de> > Of course, I know that while I'm fresh, I've a good knowledge of the > code, and anything else, I will be able to avoid such stupid errors; > however, I'm afraid of the times when I'm tired, when I have to put my > hands on the code of someone else, and so on. > > Please, understand that I'm not stating that python is wrong... after > all, if it is wrong, I can move to a language like Java, which has a > different approach on it. I'm really very interested in reading past > discussion on it, if they are available. This has not much to do with the question of setters and getters. Because in your code you could write def setX(self, x): self.y = x def getX(self): return self.x So the error occurs in the same way. What you are essentially asking is: why is python dynamic instead of static? Because *that* is what is the difference. In a static language, you need to declare first what you want to be available, e.g. which variables and methods are available and such. Of course then the compiler (or whoever evaluates the static declarations) can puke on you if you attempt a stunt like the one you describe. Python (and other languages such as Ruby, Javascript) chose other. They give you the freedom to add instance variables (or even methods) at will, with the cost of the occasional error like the above. OTOH, Java makes me write soooo much more code that me becoming tired and doing some stupid mistake (and there are lots of them doable in static languages as well, otherwise no C/C++ or Java-program would crash....) becomes much more likely....YMMV. Diez From theller at python.net Fri Sep 12 04:35:44 2008 From: theller at python.net (Thomas Heller) Date: Fri, 12 Sep 2008 10:35:44 +0200 Subject: handling uncaught exceptions with pdb? In-Reply-To: <7xmyifpt68.fsf@ruckus.brouhaha.com> References: <7xmyifpt68.fsf@ruckus.brouhaha.com> Message-ID: <6iunubFkfd7U1@mid.individual.net> Paul Rubin schrieb: > I think I've asked about this before, but is there a way to set up > Python to handle uncaught exceptions with pdb? I know about setting > sys.except_hook to something that calls pdb, but this is normally done > at the outer level of a program, and by the time that hook gets > called, the exception has already unwound the stack to the outermost > level. My situation is I run a multi-hour or multi-day computation > that eventually crashes due to some unexpected input and I'd like to > break to the debugger at the innermost level, right when the exception > is encountered, so I can fix the error with pdb commands and resume > processing. Of course this presumes a certain semantics for Python > exceptions (i.e. handling one involves scanning the stack twice, once > to look for a handler and again to actually unwind the stack) and I'm > not sure if it's really done that way. I do know that Lisp has a > requirement like that, though; so maybe there is hope. Would this work (although it probably will slow down the program)? import sys, pdb def tracefunc(frame, event, arg): if event == "exception": pdb.set_trace() return tracefunc sys.settrace(tracefunc) def test(arg): if arg > 20: raise ValueError(arg) return test(arg+1) test(0) Thomas From tjreedy at udel.edu Mon Sep 1 21:04:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 21:04:22 -0400 Subject: Python 3.0b2 cannot map '\u12b' In-Reply-To: <6i2tugFo7morU3@mid.uni-berlin.de> References: <6i24u3Fo7morU2@mid.uni-berlin.de> <6i2tugFo7morU3@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: First, thank you for the informative responses. > The windows command prompt expects cp437 because that's what old DOS > programs print to it. Grrr. When the interpreter runs, it opens the command prompt window with Python running, and the window closes when Python exits, so there are no other programs involved. I don't suppose there is anyway to tell Command Prompt to accept something better. > But OOo works with unicode internally, so there's no communication with > outside programs involved here. Python 3 uses unicode internally also, but I gather CommandPrompt is an outside program used as a quick substitute for coding a plain window with MFC, for instance. ---------------------- I did some experiments. I added the /u flag after cmd.exe in the Command Prompt shortcut and the font to Lucida Console (which people on the web say handles unicode). I opened the prompts window and entered 'chcp 1252' the same codepage as IDLE. Start Python3. >>> import sys >>> sys.stdout.encoding 'cp1252' >>> '\u012b' Traceback (most recent call last): File "", line 1, in File "C:\Program Files\Python30\lib\io.py", line 1428, in b = encoder.encode(s) File "C:\Program Files\Python30\lib\encodings\cp1252.py", same with raster font choice. chcp 65001, which supposedly is UTF-8, disables all output. Perhaps Python does not recognize it as a synonym for UTF-8. The same on IDLE (with codepage 1252) gives i macron (bar on top). So something else is going on other than just codepage. I tried a second time and instead got "'\u012b'" and no error. Hooray, I thought, but I closed and tried again the same way, as best I know, but got the same error as before. Cp65001 also did and then did not work. Python does notice the code page change. tjr From fredrik at pythonware.com Sun Sep 21 14:53:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 20:53:28 +0200 Subject: Newick parser In-Reply-To: <73045cca0809211133y3198bde2n483738de8cac2810@mail.gmail.com> References: <73045cca0809211133y3198bde2n483738de8cac2810@mail.gmail.com> Message-ID: aditya shukla wrote: > Hello folks , i have a .nwk file.I want to parser the tree from that > file.I found this python parser for newick trees. > http://www.daimi.au.dk/~mailund/newick.html > > But i don't understand the usage properly.What i wanna do is if i have a > file in the location c:\\files\\file1.nwk , then i wanna parse the trees > in that file. judging from the docs, you should be able to do e.g. from newick import parse_tree file = open("c:\\files\\file1.nwk") text = file.read() print parse_tree(text) From a.schmolck at gmail.com Thu Sep 4 05:37:02 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Thu, 04 Sep 2008 10:37:02 +0100 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <00cf34ad$0$20302$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Thu, 04 Sep 2008 01:22:22 +0100, Alexander Schmolck wrote: > >> It seems to me that the right choice for thousands seperator is the >> apostrophe. > > You mean the character already used as a string delimiter? Yup. No ambiguity or problem here; indeed unlike space seperation or '_' it would work straighforwardly as a syntax extension in pretty much any programming language I can think as well as end-user output (I think that writing e.g. 1'000'000 on a website would be perfectly acceptable; unlike 1_000_000). 'as From tino at wildenhain.de Thu Sep 18 11:44:21 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 18 Sep 2008 17:44:21 +0200 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <48D27755.8060208@wildenhain.de> Hi, Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > data=dict() for item in IN: # (what a name! ;) data.setdefault(item.coordinates,[]).append(item) # provided coordinates is a tuple dupes=[items for items in data.values() if len(items)>1] should give you a resulting list of lists of elements in IN which occur more then once per coordinates. You can then decide which ones to remove or whatever. If you want to have the output only containing nodes to remove, the following would work: dupes=[] for items in data.values(): dupes.extend(items[1:]) HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From grante at visi.com Wed Sep 24 21:22:41 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 24 Sep 2008 20:22:41 -0500 Subject: Linq to Python References: <48daa55d$0$19939$426a74cc@news.free.fr> Message-ID: On 2008-09-24, Bruno Desthuilliers wrote: > hrishy a ?crit : > (snip) > > >> I apologise >> (I thought Python programmers were smart and they did know what LINQ was) > > Is there really any relation between "being smart" and knowing anything > about the latest MS fad ? God, I hope not -- or I'd rather be stupid. -- Grant From krishnan.1000 at gmail.com Tue Sep 9 02:10:42 2008 From: krishnan.1000 at gmail.com (Karthik Krishnan) Date: Mon, 8 Sep 2008 23:10:42 -0700 Subject: Newbie Question:Please help Message-ID: Hi, I am a newbie to python and I hope this is not a stupid question. I am trying to run a main method from a Python command line using the command shell using the command. python main_test.py I get the following error. File "", line 1 python main_test.py Syntax Error: invalid syntax My main file main_test.py is given below. #!/usr/bin/env python """ Test method to run the main method. """ def main(): print "Main method called."; if __name__ = "__main__": main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyrie at uh.cu Sun Sep 7 16:38:06 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 07 Sep 2008 16:38:06 -0400 Subject: max(), sum(), next() In-Reply-To: <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: <1220819886.48c43baeb43ca@comuh.uh.cu> Quoting Mensanator : > Actualy, I already get the behaviour I want. sum([1,None]) > throws an exception. I don't see why sum([]) doesn't throw > an exception also If you take a "start value" and add to it every element of a list, should the process fail if the list is empty? If you don't add anything to the start value, you should get back the start value. Python's sum is defined as sum(sequence, start=0). If sum were to throw an exception with sum([]), it should also throw it with sum([], start=0), wich makes no sense. -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From duncan.booth at invalid.invalid Wed Sep 24 16:59:12 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Sep 2008 20:59:12 GMT Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: r0g wrote: > OK so maybe I'm being naive here but it looks to me like this new > paradigm's big idea is to use a python + SQL type syntax to access data > in random objects. Big whoop. It's not that difficult to write a > generators that wraps XML files and databases is it? > > What am I missing here? Simple LINQ expressions like the one you gave map easily to Python list comprehensions. What Microsoft have done though is provide a consistent implementation which allows you to write complex SQL like expressions which will work identically on databases or most other sequence types. Here's another LINQ example: List customers = GetCustomerList(); var customerOrderGroups = from c in customers select new {c.CompanyName, YearGroups = from o in c.Orders group o by o.OrderDate.Year into yg select new {Year = yg.Key, MonthGroups = from o in yg group o by o.OrderDate.Month into mg select new { Month = mg.Key, Orders = mg } } }; ObjectDumper.Write(customerOrderGroups, 3); I'm not overly keen on SQL syntax: I think this sort of complex expression is hard to read. LINQ has a pretty straightforward conversion to method calls, and for me this consistent set of methods is the important thing rather than the SQL syntax. e.g. 'group by' maps directly to a call to a method GroupBy(), so another of Microsoft's LINQ examples is: public void Linq45() { string[] anagrams = {"from ", " salt", " earn ", " last ", " near ", " form "}; var orderGroups = anagrams.GroupBy( w => w.Trim(), a => a.ToUpper(), new AnagramEqualityComparer() ); ObjectDumper.Write(orderGroups, 1); } public class AnagramEqualityComparer : IEqualityComparer { public bool Equals(string x, string y) { return getCanonicalString(x) == getCanonicalString(y); } public int GetHashCode(string obj) { return getCanonicalString(obj).GetHashCode(); } private string getCanonicalString(string word) { char[] wordChars = word.ToCharArray(); Array.Sort(wordChars); return new string(wordChars); } } Python still wins hands down on this example both in verbosity and readability: >>> anagrams = ["from ", " salt", " earn ", " last ", " near ", " form "] >>> from itertools import groupby >>> def AnagramKey(w): return sorted(w.strip().upper()) >>> for k,words in groupby(sorted(anagrams, key=AnagramKey), key=AnagramKey): for w in words: print w.strip().upper() print "..." EARN NEAR ... SALT LAST ... FROM FORM ... I haven't yet had occasion to use LINQ in anger yet, so I have no idea whether its an idea to love or to hate. I do think it is good that C# has effectively sprouted list comprehensions (not to mention anonymous types and type inferencing) and I expect there may be some aspects worth looking at for Python but I think they are more likely to lead to itertools functions than extensions to syntax. From paul at boddie.org.uk Mon Sep 22 06:48:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 22 Sep 2008 03:48:55 -0700 (PDT) Subject: New Web2Py framework SLASHES development time... References: Message-ID: <8bc01858-77f9-41bc-a907-4b9670f40213@b1g2000hsg.googlegroups.com> On 22 Sep, 04:49, Steve Shephed wrote: > http://www.web2py.comWeb2Py - Python Framework is the newest > kid on the block for Python frameworks. I'm not going to dwell on the merits of web2py, I'm afraid... > It has a lot of features that simply are not there in other > frameworks. Even Ruby!. You can design database models graphically > online. I had a closer look at the model designer, and the client-side magic seems to originate from this project: http://ondras.zarovi.cz/sql/ It looks quite fancy, especially since it all seems to be happening in the browser. Thanks for indirectly bringing this to our attention! ;-) Paul From pydecker at gmail.com Fri Sep 5 11:19:20 2008 From: pydecker at gmail.com (Peter Decker) Date: Fri, 5 Sep 2008 10:19:20 -0500 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <6i7u02Fpeif6U1@mid.uni-berlin.de> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> Message-ID: On Wed, Sep 3, 2008 at 11:57 AM, Diez B. Roggisch wrote: > Michael Palmer schrieb: >> >> As anyone knows, the state of Python GUI programming is a little >> fractured at this time, with many toolkits, wrappers and meta-wrappers >> dead and alive, with or without documentation. >> >> I've come across two projects that have the appeal of striving for >> simple, pythonic APIs: PyGUI and wax. The latter is a wrapper around >> wxPython. It is lacking documentation but actually quite usable and >> concise. The other, PyGUI, has an even nicer API and more docs but has >> relatively few widgets implemented at this time. It also strives for >> compatibility with several toolkits (two at this time), which I think >> is the right idea. > > I disagree with that. Meta-wrappers like this will always suffer from > problems, as they have difficulties providing a consistent api. For example > wx is said to be very windows-toolkit-centric in it's API. Yes I know that > it works under Linux with GTK, but it does not come as natural . With all due respect, it seems like you are not terribly familiar with wxPython. It uses the native UI toolkit for each platform wherever possible: Aqua on OS X; MFC on Windows and Gtk on Linux. Applications tend to look 'natural' on each platform, rather than uniform across platforms, and I believe that this is what most people prefer. -- # p.d. From xiaowei.lin at accenture.com Thu Sep 25 04:44:14 2008 From: xiaowei.lin at accenture.com (xiaowei.lin at accenture.com) Date: Thu, 25 Sep 2008 16:44:14 +0800 Subject: Question about reading a xml Message-ID: <83836530B94A0E4CBC50E17B137AF67D2EAC03@APAXM1113.dir.svc.accenture.com> Hi all, I am working on SunOS 5.8, Python 2.2.2 When I run the python grogram below: #Beginning import xml.dom.minidom xml_str = """\ ' this is a c' this is b this is c """ dom = xml.dom.minidom.parseString(xml_str) na = dom.getElementsByTagName("a")[0] nb = dom.getElementsByTagName("b")[0] nc = dom.getElementsByTagName("c")[0] print na.childNodes[0].data print nb.childNodes[0].data print nc.childNodes[0].data #End The result is as below: " this is a c this is c I don't know why the letters following the quote are lost. Even the quote lost if the quote following another letter. Regards, Sean This message is for the designated recipient only and may contain privileged, proprietary, or otherwise private information. If you have received it in error, please notify the sender immediately and delete the original. Any other use of the email by you is prohibited. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Sep 20 12:47:22 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 20 Sep 2008 18:47:22 +0200 Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Gary Herron wrote: > Or you can create a new reversed (copy of the original) list and iterate > through it > > for item in reversed(L): > ? print item It's not a copy, it's a view: >>> items = [1,2,3] >>> r = reversed(items) >>> items[:] = "abc" >>> for item in r: print item ... c b a Peter From Scott.Daniels at Acm.Org Tue Sep 30 08:42:12 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 30 Sep 2008 05:42:12 -0700 Subject: writing dll in python? In-Reply-To: References: Message-ID: Terry Reedy wrote: > .... > Start with the Python tutorial, perhaps parts of the reference manual, > and definitely peruse the first chapters in the library manual on > built-in functions and classes. Check out http://wiki.python.org/moin/BeginnersGuide to see a range of ways to learn Python, most very good (what works for you vaires by student). > You will almost certainly want to use numpy (numpy.org) for numerical > calculation and possibly existing modules in scipy (scipy.org) or > elsewhere. Although it is likely someyhing like numpy will be necessary, don't make the mistake of thinking Python cannot handle calculation itself easily. Where you'll need to leave python is in array and matrix calculations, there the numpy code will get you near custom C/fortran code speeds. >--Scott David Daniels Scott.Daniels at Acm.Org From dotancohen at gmail.com Sat Sep 27 04:11:06 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 27 Sep 2008 11:11:06 +0300 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <48dd4756$0$25116$426a74cc@news.free.fr> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> Message-ID: <880dece00809270111i1631a595he8888bfd675d85b9@mail.gmail.com> 2008/9/26 nntpman68 : > It's tough to find good rules, but the incoming spams that I see currently > on comp.lang.python have certain criteas. > > > > - most email addresses from gmail. > - all never posted before and then they have multiple posts within a few > minutes / seconds > - the posts always contain one or more urls ( mostly cryptic names ) > - they always start a thread but never reply to one > - the post doesn't contain python code or anything which looks only vaguely > like source code > - never mentions the word python > - the amount of sexual or financial vocabulary exceeds classical python > posts > I hope that the spammers don't read the list! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From rtiago at gmail.com Wed Sep 10 16:57:24 2008 From: rtiago at gmail.com (Ricardo Tiago) Date: Wed, 10 Sep 2008 22:57:24 +0200 Subject: formating a filesystem with python Message-ID: <8ed7d4b30809101357q2eebb00cl58576127c4cfea8a@mail.gmail.com> Hi all, is there a package in python that allows to mount/umount and format (to ext3) a filesystem? I know that this is possible by just calling the os commands 'mount/umount and mkfs' but this would imply to have to change sudoers to run the script as non-root. Thanks Ric From simon.hibbs at gmail.com Wed Sep 17 07:50:48 2008 From: simon.hibbs at gmail.com (Simon Hibbs) Date: Wed, 17 Sep 2008 04:50:48 -0700 (PDT) Subject: Python OOP advice Message-ID: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> I'm rewriting a design application for a science fiction game. in it you design your own starships. Each component has a mass and cost, but the mass can either be fixed or it can be expressed as a percentage of the tonnage of the overall ship. Orriginaly I thought I'd need to have a hull object which contains component objects, but the component objects need access to members of the hull object (e.g. the hull size) so that looks messy to implement. I have defined a base class Component with a class member variable 'hull_size' so that all components can see the hull size. I've then got two child classes called Fixed_Component and Percent _Component that implement their mass, mass_percent and cost properties appropriately for their type. I've also defined a Hull class which also inherits from Component and provides methods for access to the hull_size class variable. I'm not sure where to go from here. One possibility is to have a Ship object containing a list of components, but I'd need to have a way to ensure there's only ever one hull object so maybe that shouldn't go in the list? I think the fact that the hull_size is a class member also means I can't ever have an application that loads two designs at the same time, because they'd share the same hull_size class variable. Is that so, and is there a way round that? I suspect the inheritance model will work fine at first, but is too rigid in the long run. Is there a way to cleanly implement a parent-child relationship between objects that gives child objects limited access to members of the parent? Simon Hibbs From gagsl-py2 at yahoo.com.ar Tue Sep 2 06:05:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 07:05:08 -0300 Subject: Relative imports and "import X as Y" References: Message-ID: En Sun, 31 Aug 2008 07:27:12 -0300, Wojtek Walczak escribi?: > On Sun, 31 Aug 2008 06:40:35 GMT, OKB (not okblacke) wrote: > >>> Download the latest beta for your system and give it a try. >> >> Thanks for the advice, but I'd really rather not deal with >> installing the entire thing alongside my existing version, possibly >> causing conflicts in who knows what ways. > > Then you can download tar.gz package, compile it, and try it > without installing :-) Or use a virtual machine, or a live CD. -- Gabriel Genellina From fredrik at pythonware.com Fri Sep 5 13:26:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 19:26:39 +0200 Subject: Documentation (was Re: atomic section in code) In-Reply-To: References: Message-ID: Michele Simionato wrote: > The page you link here is WAYS better than the standard documentation > of the threading module. > Generally speaking, the effbot zone contains a lot of improvements > over the standard docs which are lacking in various areas. > I have always wondered why they are kept separated. Wouldn't be nice > to have the standard > docs integrated with the effbot docs? Are there plans in this sense > and if not, why not? There are tons of great supplementary material out there, on blogs, personal documentation collections (such as effbot.org), cookbook sites, etc. I don't think all that material absolutely must be posted to python.org, but Python users would definitely benefit from improved cross-linking. And this is, of course, something I've lobbied for many times, e.g. http://mail.python.org/pipermail/python-list/2005-May/322224.html http://mail.python.org/pipermail/python-list/2005-December/355625.html http://effbot.org/zone/idea-seealso.htm but I haven't yet figured out how to get something to happen [1]. All ideas are welcome. 1) Well, I guess the new Sphinx tool might have gotten some inspiration by my work in this domain: http://mail.python.org/pipermail/python-dev/2006-January/059978.html and Andrew Kuchling did some preliminary work for the old Latex work flow: http://svn.python.org/view/sandbox/trunk/seealso/ From bj_666 at gmx.net Thu Sep 11 12:19:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Sep 2008 16:19:06 GMT Subject: Better error message on recursive import References: <6isb2mF9scaU1@mid.individual.net> Message-ID: <6isunqF6v3jU2@mid.uni-berlin.de> On Thu, 11 Sep 2008 12:43:34 +0200, Thomas Guettler wrote: > why does Python only raise ImportError if it fails caused by a recursive > import? > > I know what's wrong. But I guess many beginner don't know what's wrong. > I don't want much, just "RecursiveImportError" instead of "ImportError". > Is this possible? Can you give an example of such a recursive import you want the special exception be raised? Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Mon Sep 29 16:10:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 17:10:33 -0300 Subject: what does "python -i" use as input stream (stdin)? References: Message-ID: En Fri, 26 Sep 2008 04:29:42 -0300, Almar Klein escribi?: > I would still like to hear if anyone knows how I can change the input > stream > that > is used when running "python -i", but I would not be surprised if it is > impossible... Sure you can. You have to replace the file descriptor 0, that is, "standard input"; sys.stdin reads from there. The standard way is to use os.dup2: c:\temp>type foo.txt This line read from foo.txt c:\temp>type redirect.py import os inp = open("foo.txt","r") os.dup2(inp.fileno(), 0) print "raw_input->", raw_input() c:\temp>python redirect.py raw_input-> This line read from foo.txt This is not -- Gabriel Genellina From rocky at panix.com Fri Sep 12 03:36:38 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 12 Sep 2008 03:36:38 -0400 Subject: handling uncaught exceptions with pdb? References: <7xmyifpt68.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > I think I've asked about this before, but is there a way to set up > Python to handle uncaught exceptions with pdb? I know about setting > sys.except_hook to something that calls pdb, but this is normally done > at the outer level of a program, and by the time that hook gets > called, the exception has already unwound the stack to the outermost > level. My situation is I run a multi-hour or multi-day computation > that eventually crashes due to some unexpected input and I'd like to > break to the debugger at the innermost level, right when the exception > is encountered, so I can fix the error with pdb commands and resume > processing. ... Why not use the traceback you get to show you where to change the code around that point to add an exception handler there which calls the debugger? From jfabiani at yolo.com Fri Sep 19 01:27:17 2008 From: jfabiani at yolo.com (John Fabiani) Date: Thu, 18 Sep 2008 22:27:17 -0700 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> Message-ID: erikcw wrote: > On Sep 18, 3:33?pm, Ben Finney > wrote: >> erikcw writes: >> > I have a cgi script where users are uploading large files for >> > processing. I want to launch a subprocess to process the file so the >> > user doesn't have to wait for the page to load. >> >> For "how do I deal with subprocesses from Python", the (new in Python >> 2.4) 'subprocess' module is the default go-to answer >> , replacing a >> rather fragmented set of modules before it. >> >> > What is the correct way to launch subprocess without waiting for the >> > result to return? >> >> Creating an instance of 'subprocess.Popen' will launch the process and >> return the Popen instance. You then have the option of polling it or >> waiting for it to complete. >> >> -- >> \ ? ? ?To stay young requires unceasing cultivation of the ability to | >> `\ ? ? ? ? ? ? ? ? ? unlearn old falsehoods.? ?Robert Anson Heinlein | >> _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| >> Ben Finney > > So if I create a Popen object and then just ignore the object and exit > the program the subproccess will finish it's work and then exit itself > cleanly? Just so happens that I ran into the same problem recently. I started with exec(), then os.system(), next os.popen(), and last os.spawn(). This is what I discovered on a windows platform. The exec() replaced the current running process. os.system did not start a completely new process. os.popen() created a new process but did not open a command box to display any print statements. Lastly os.spawn() worked - it created a new process and opened a command box to display any print statements I needed. Johnf From dudeja.rajat at gmail.com Wed Sep 24 11:53:49 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Wed, 24 Sep 2008 16:53:49 +0100 Subject: problem updating variable in a module In-Reply-To: References: Message-ID: >I take it you do have a *really* good reason to use a global? Please suggest some way other than using global. I want to get rid of it -- Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From aquil.abdullah at gmail.com Fri Sep 5 16:06:19 2008 From: aquil.abdullah at gmail.com (aha) Date: Fri, 5 Sep 2008 13:06:19 -0700 (PDT) Subject: Need formatting suggestion for long strings References: Message-ID: <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> On Sep 5, 3:29?pm, Jean-Paul Calderone wrote: > On Fri, 5 Sep 2008 14:24:16 -0500, Robert Dailey wrote: > >Hi, > > >I find quite often that I'm writing things like this: > > >raise FatalExcept( "Insufficient number of arguments specified. Exactly {0} > >arguments are required. See stage.bat for documentation on accepted > >parameters.".format( num_arguments ) ) > > >On my display (Vertical monitor), this exceeds the width of my display, and > >to view the entire length of the string I am forced to pan my view left and > >right. Is there a special way I can format this string so that it fits > >nicely on the screen? Keep in mind that one important factor is that > >whitespace is very sensitive, and I do not want line breaks in my script > >file to become part of the string itself. I like how C++ handles strings, > >like this: > > >char const* mystring = > > ? ?"This is a very long string that " > > ? ?"spans multiple lines and does " > > ? ?"not include line breaks or tabs " > > ? ?"from the source file between " > > ? ?"the strings partitions." > > >What do you guys prefer? Thanks for reading. > > mystring = ( > ? ? "This is a very long string that " > ? ? "spans multiple lines and does " > ? ? "not include line breaks or tabs " > ? ? "from the source file between " > ? ? "the strings partitions.") > > Jean-Paul Can you be more specific? What is the formatting criteria? Are you talking about formatting the string for display or are you talking about the source? From tjreedy at udel.edu Mon Sep 1 14:25:01 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 14:25:01 -0400 Subject: Python 3.0b2 cannot map '\u12b' In-Reply-To: <6i24u3Fo7morU2@mid.uni-berlin.de> References: <6i24u3Fo7morU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: > >> I doubt the OP 'chose' cp437. Why does Python using cp437 even when the >> default encoding is utf-8? >> >> On WinXP >> >>> sys.getdefaultencoding() >> 'utf-8' >> >>> s='\u012b' >> >>> s >> Traceback (most recent call last): >> File "", line 1, in >> File "C:\Program Files\Python30\lib\io.py", line 1428, in write >> b = encoder.encode(s) >> File "C:\Program Files\Python30\lib\encodings\cp437.py", line 19, in >> encode >> return codecs.charmap_encode(input,self.errors,encoding_map)[0] >> UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in >> position >> 1: character maps to > > Most likely because Python figured out that the terminal expects cp437. > What does `sys.stdout.encoding` say? The interpreter in the command prompt window says CP437. The IDLE Window says 'cp1252', and it handles the character fine. Given that Windows OS can handle the character, why is Python/Command Prompt limiting output? Characters the IDLE window cannot display (like surrogate pairs) it displays as boxes. But if I cut '[][]' (4 chars) and paste into Firefox, I get 3 chars. '[]' where [] has some digits instead of being empty. It is really confusing when every window on 'unicode-based' Windows handles a different subset. Is this the fault of Windows or of Python and IDLE (those two being more limited that FireFox)? >> To put it another way, how can one 'choose' utf-8 for display to screen? > > If the terminal expects cp437 then displaying utf-8 might give some > problems. My screen displays whatever Windows tells the graphics card to tell the screen to display. In OpenOffice, I can select a unicode font that displays at least everything in the BasicMultilingualPlane (BMP). Terry Jan Reedy From ruivaldo at gmail.com Mon Sep 22 07:23:09 2008 From: ruivaldo at gmail.com (Rui) Date: Mon, 22 Sep 2008 04:23:09 -0700 (PDT) Subject: Encoding.ASCII.GetBytes similar for Python ? Message-ID: <463f31b8-ba48-4833-8d41-9aa5f1cae189@a70g2000hsh.googlegroups.com> Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with the strings. I am trying to query some dns server to check its response using udp sockets. Some of the source below: # encoding: utf8 import socket import sys import struct IP_PORT = 53 server_host = ('4.2.2.1', IP_PORT) transaction_id = "Q1" TIMEOUT = 5 type_string = "\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000" trailer_string = "\u0000\u0000\u0001\u0000\u0001" address = 'google.com' url_name_start, domain_name = address.split(".") # Query format copied from the C# example. #QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName+ TrailerString; query = (transaction_id + type_string + str(len(url_name_start)) + url_name_start + str(len(domain_name)) + domain_name + trailer_string) print query sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(TIMEOUT) sock.connect(server_host) sock.send(query) data = sock.recv(512) for data_item in data: try: print chr(data_item) except: print data_item But it just returns trash: >python dns_checker.py Q1\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u00006google3com \u0000\ u0000\u0001\u0000\u0001 Q 1 ? ? Any advice ? Thanks! From fredrik at pythonware.com Sun Sep 7 18:36:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 00:36:45 +0200 Subject: lacking follow-through In-Reply-To: <6ij1ecFqp39rU4@mid.uni-berlin.de> References: <6ij1ecFqp39rU4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > Yeah, castironpi sometimes doesn't make much sense. Maybe because it's a > bot!? :-) if so, they sure don't make c.l.py bots like they used to, do they? From dudeja.rajat at gmail.com Sat Sep 6 12:47:56 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 6 Sep 2008 17:47:56 +0100 Subject: Want to display a message box while subprocess is running Message-ID: Hi, I m using subprocess module and using the Popen call. While the subprocess if running, I want to display a tkMessageBox(). Does some one has a sample code for this? Thanks and regards, Rajat From mobiledreamers at gmail.com Mon Sep 22 19:01:21 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Mon, 22 Sep 2008 16:01:21 -0700 Subject: Python based barcode readers In-Reply-To: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> References: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> Message-ID: This is something I have looked for too but I have not come across a decent barcode reader? On 9/22/08, Robocop wrote: > > Does anyone know of any python based barcode readers? I'm looking for > something (commercial or open source) that will use some OCR algorithm > to read barcodes from an image or ps/pdf file, and ideally will be > something along the lines of a callable python script. I have some > pretty simple needs, i'm only trying to read code 93 barcodes, so i > don't need it to be able to identify multiple symbologies or > anything. Any suggestions would be greatly appreciated. > > Thanks! > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://gpirate.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Sat Sep 27 21:50:38 2008 From: roy at panix.com (Roy Smith) Date: Sat, 27 Sep 2008 21:50:38 -0400 Subject: Docstrings for attributes? Message-ID: Is there any way to attach a docstring to an attribute? I see that PEP-257 talks about attribute docstrings, but it references PDP-258, which was rejected. I suppose I could eschew plain attributes in favor of getter functions, because those give me a place to hang a docstring, but that feels like the wrong thing to do. From sturlamolden at yahoo.no Fri Sep 26 06:08:52 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 26 Sep 2008 03:08:52 -0700 (PDT) Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> Message-ID: <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> On Sep 26, 5:45?am, "David Cournapeau" wrote: > I am fairly experienced in matlab (have been using it extensively for > 5 years in academical context), and now with numpy, and generally, > they are comparable speed-wise. Matlab has some niceties which makes > it faster in some simple cases (JIT for loops, function calls faster, > sometimes COW semantics means it faster), I've used Matlab for 10 years. Matlab has a horrible pass-by-value semantics, which means that arrays are copied in and copied out form function calls. Yes there is a copy- on-write optimization. But unless you are not careful, it will kill performance and make memory usage skyrocket. Also, slicing creates a new array, whereas in numpy slicing gives you a view of an existing array. This generally makes Matlab slow, and it wastes terrible amounts of memory. For example I once tested D4 wavelet transforms on a 64 MB array of doubles (i.e. length 2**23). Matlab R14 Service Pack 2 did this in 27 seconds, whereas Python 2.4 with NumPy 1.0 one required 3.4 seconds. That is an order of magnitude speed difference in favour of Python. Matlab also has a strange habit of fragmenting the heap. This can be so bad that you have to stop the script, run a special function called pack() do defragement, and restart. I've never seen that with Python. I more or less stopped using Matlab 3 years ago, and I have not renewed my subscription for maintenance of my personal Matlab license since. Matlab is a nice tool, but I have grown past it. Matlab's strongest side is data visualization though. Although we have matplotlib, mayavi and possibility of interfacing with gnuplot, it's not anywhere near the capabilities of Matlab. From hrishys at yahoo.co.uk Thu Sep 25 06:36:13 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 10:36:13 +0000 (GMT) Subject: Linq to Python In-Reply-To: <48DA92F1.1060501@timgolden.me.uk> Message-ID: <18101.30495.qm@web27406.mail.ukl.yahoo.com> Hi Tim I am not a LINQ expert just a LINQ user and (was a little envious why the langauge i fantasize doesnt have it (pardon my ignorance of python)) LINQ as far as i know allows you to query all sources using a consistent interface . You can query a message queue ,xml document ,array object or relational source by learning LINQ and even join them as illustrated below http://informationr.net/ir/13-2/TB0806.html If somebody can tutor me how i can do that in python that would be great (and mayeb satisfy my greed and leave me with a happy feeling that my langauge python can do it) regards Hrishy --- On Wed, 24/9/08, Tim Golden wrote: > From: Tim Golden > Subject: Re: Linq to Python > To: > Cc: python-list at python.org > Date: Wednesday, 24 September, 2008, 8:20 PM > bearophileHUGS at lycos.com wrote: > > sturlamolden: > >> No, because Python already has list comprehensions > and we don't need the XML buzzword.< > > > > LINQ is more than buzzwords. Python misses several of > those features. > > So maybe for once the Python crowd may recognize such > C# feature as > > much better than things present in Python. > > Said that, I presume Python will go on as usual, and > LINQ-like > > capabilities will not be integrated in Python. In the > meantime where I > > live lot of people will keep using C# instead of > Python and CLisp, > > natural selection at work indeed. > > Perhaps a quick summary of what LINQ offers which might > "be integrated into Python" would help those of > us who > are ignorant? (This is a serious comment; I'd like to > know). > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list From tino at wildenhain.de Mon Sep 22 09:50:46 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Sep 2008 15:50:46 +0200 Subject: understanding list scope In-Reply-To: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> Message-ID: <48D7A2B6.6090107@wildenhain.de> Hi, Alex wrote: > Hi all! > > I have a problem understanding the behaviour of this snippet: > > data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) > > for i in range(len(data_set)): > ds = data_set[:] > data = ds[i] > if i == 1: data['param'] = "y" > if i == 2: data['param'] = "x" > > print data_set Beside the data copy which is explained in the other posts, what is the problem you want to solve? Would data_set[1]['param']="x" data_set[2]['param']="y" not doing the same? or more to your point: ds=data_set[:1]+[dict(param="x"),dict(param="y")]+data_set[2:] HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From digitig at gmail.com Wed Sep 24 11:19:54 2008 From: digitig at gmail.com (Tim Rowe) Date: Wed, 24 Sep 2008 16:19:54 +0100 Subject: problem updating variable in a module In-Reply-To: References: Message-ID: 2008/9/24 : > Hi, > > I've a problem updating my variable in a module. > > In my main program, I call a function from mod1 to update a variable of mod1 > As soon as I update this varibale, I check it back in the mail program but > it the variable from mod1 does not get updated. > > main Program: > **************** > import mod1 > a = 20 > mod.update(a) > print mod.a <---- does not print anything > > mod1 > ******** > a = 10 > def update(someInt): > global a > a = someInt > print a <---- this does actually print a = 20 I'm surprised it runs at all -- as far as I can see "mod" in "mod.update(a)" and "print mod.a" is not defined. Did you mean "mod1"? If I change it to that, both print statements print "20" as I'd expect. I take it you do have a *really* good reason to use a global? -- Tim Rowe From cvrebert at gmail.com Thu Sep 4 03:36:13 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Thu, 4 Sep 2008 00:36:13 -0700 Subject: use str as variable name In-Reply-To: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> Message-ID: <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> On Thu, Sep 4, 2008 at 12:25 AM, Mathieu Prevot wrote: > Hi, > > I have a program that take a word as argument, and I would like to > link this word to a class variable. > > eg. > class foo(): You should subclass 'object', so that should be: class Foo(object): > width = 10 > height = 20 > > a=foo() > arg='height' > a.__argname__= new_value You're looking for the setattr() built-in function. In this exact case: setattr(a, arg, new_value) This is probably covered in the Python tutorial, please read it. Regards, Chris > > rather than : > > if arg == 'height': > a.height = new_value > elif arg == 'width'; > a.width = new_value > > Can I do this with python ? How ? > > Thanks, > Mathieu > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From roseeea at gmail.com Thu Sep 4 04:33:16 2008 From: roseeea at gmail.com (roseeea at gmail.com) Date: Thu, 4 Sep 2008 01:33:16 -0700 (PDT) Subject: CREDIT CARD DEPT Message-ID: <77d219ea-42c1-45fa-93c4-dfd3830237f2@a2g2000prm.googlegroups.com> CREDIT CARD DEPT http://creditcarddept.googlepages.com From nick at craig-wood.com Thu Sep 11 04:36:35 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 11 Sep 2008 03:36:35 -0500 Subject: dict slice in python (translating perl to python) References: Message-ID: hofer wrote: > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] As an ex-perl programmer and having used python for some years now, I'd type the explicit v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars Or maybe even v1 = mydict['one'] # 54 chars v2 = mydict['two'] v3 = mydict['two'] Either is only a couple more characters to type. It is completely explicit and comprehensible to everyone, in comparison to v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars Unlike perl, it will also blow up if mydict doesn't contain 'one' which may or may not be what you want. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From larry.bates at vitalEsafe.com Tue Sep 9 18:46:28 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 09 Sep 2008 17:46:28 -0500 Subject: wxpython ms-dos black window popping up in background In-Reply-To: References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: icarus wrote: > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > That did it. > > one more question... > > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? > > My intent is to have the process transparent to the user. He wouldn't > even know the app was written in python. All he knows that when he > double-clicks on it, the application pops up without the DOS black > screen in the background (for w32 users.) > > > > > > > On Sep 9, 10:49 am, "Chris Rebert" wrote: >> You need to have the script be run by pythonw.exe as opposed to python.exe >> pythonw.exe suppresses the DOS box from coming up and should be used >> for running GUI applications such as yours. >> >> Regards, >> Chris >> >> >> >> On Tue, Sep 9, 2008 at 1:33 PM, icarus wrote: >>> platform: windows xp professional, python 2.5, wxpython >>> When I double-check on my program file test.py (for simplicity I'll be >>> using this code below), I see the window just fine. But the ms-dos >>> black window pops up in the background. On Linux, no issues at all. >>> How can I get rid of that ms-dos black window in the background? >>> something I need to add to my code? a setting to adjust in windows? >>> thanks in advance. >>> #!/usr/bin/python >>> import wx >>> appwx = wx.App() >>> frame = wx.Frame(None, -1, 'test.py') >>> frame.Show() >>> appwx.MainLoop() >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> -- >> Follow the path of the Iguana...http://rebertia.com > On Windows use py2exe and Inno Setup to create "frozen" application that is easy to distribute. On Mac/Linux there are other solutions. -Larry From prologic at shortcircuit.net.au Thu Sep 25 18:40:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 26 Sep 2008 08:40:32 +1000 Subject: PEP Proposal In-Reply-To: <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Fri, Sep 26, 2008 at 6:14 AM, wrote: > Typed parameters. Method-Declaration-filtered-typed parameters. That's what > I'm thinking of. Why do we need this (rubbish) ? Seriously. The use-case is far too small. And don't invent use-cases either. Instead of coming up with ideas of adding more and more into the language from other languages of which certain features weren't very good in the first place, devote your time to improving the libraries, documentation, etc. Typed parameters is useless to me. A lot of developers would agree. --JamesMills -- -- -- "Problems are solved by method" From lists at cheimes.de Sun Sep 28 07:34:44 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 28 Sep 2008 13:34:44 +0200 Subject: str() should convert ANY object to a string without EXCEPTIONS ! In-Reply-To: <00ef3974$0$20666$c3e8da3@news.astraweb.com> References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <00ef3974$0$20666$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >>>> str(b'123') # b prefix is added > "b'123'" > > > Perhaps I'm misinterpreting it, but from here it looks to me that str() > is doing what repr() used to do, and I'm really not sure that's a good > thing. I would have expected that str(b'123') in Python 3 should do the > same thing as unicode('123') does now: No, you are getting it right and yes, it's problematic. Guido wanted str(b'') to succeed. But the behavior can easily mask bugs in code. Therefor a byte warning mode was implemented. $ ./python -b >>> str(b'123') __main__:1: BytesWarning: str() on a bytes instance "b'123'" $ ./python -bb >>> str(b'123') Traceback (most recent call last): File "", line 1, in BytesWarning: str() on a bytes instance >>> b'' == '' Traceback (most recent call last): File "", line 1, in BytesWarning: Comparison between bytes and string From tjreedy at udel.edu Mon Sep 29 23:59:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 23:59:40 -0400 Subject: What is not objects in Python? In-Reply-To: <00f15dd2$0$20617$c3e8da3@news.astraweb.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <00f15dd2$0$20617$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 29 Sep 2008 05:41:02 -0700, George Sakkis wrote: > >> For example I would be much less >> opposed to len() being defined as, say, |x| if "|...|" was a valid >> operator. > > Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians > and physicists. It should be both, just as + is addition for numbers and concatenation for sequences. Or we could have just one built-in -- size() instead of abs() and len(). For non-sequence collections, size() would be better than len() anyway. tjr From deets at nospam.web.de Fri Sep 5 11:48:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 17:48:54 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> Message-ID: <6id2n6FpunpvU1@mid.uni-berlin.de> Peter Decker schrieb: > On Wed, Sep 3, 2008 at 11:57 AM, Diez B. Roggisch wrote: >> Michael Palmer schrieb: >>> As anyone knows, the state of Python GUI programming is a little >>> fractured at this time, with many toolkits, wrappers and meta-wrappers >>> dead and alive, with or without documentation. >>> >>> I've come across two projects that have the appeal of striving for >>> simple, pythonic APIs: PyGUI and wax. The latter is a wrapper around >>> wxPython. It is lacking documentation but actually quite usable and >>> concise. The other, PyGUI, has an even nicer API and more docs but has >>> relatively few widgets implemented at this time. It also strives for >>> compatibility with several toolkits (two at this time), which I think >>> is the right idea. >> I disagree with that. Meta-wrappers like this will always suffer from >> problems, as they have difficulties providing a consistent api. For example >> wx is said to be very windows-toolkit-centric in it's API. Yes I know that >> it works under Linux with GTK, but it does not come as natural . > > With all due respect, it seems like you are not terribly familiar with > wxPython. It uses the native UI toolkit for each platform wherever > possible: Aqua on OS X; MFC on Windows and Gtk on Linux. Applications > tend to look 'natural' on each platform, rather than uniform across > platforms, and I believe that this is what most people prefer. You got me wrong. I didn't say it doesn't use the native toolkit under various OSes, I'm well aware of that it does. What I *did* say was that wx API is designed primarily with windows' toolkit as base, and as a consequence the API tends to be less functional for other toolkits, making it harder to work with it. As the OP was after a "one API to rule them all" for GUIs, I pointed that out. See for example this (arguably somewhat dated) post that illustrates my point: http://mail.python.org/pipermail/python-list/2005-March/313354.html From my personal experience with Qt and Cocoa, I can say that both are great, but their full power is unleashed only if used directly - talk about Multi-threading in Qt4, or KeyValue-coding in Cocoa. Neither is available in wx. Diez From lists at cheimes.de Tue Sep 9 14:45:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 09 Sep 2008 20:45:05 +0200 Subject: PYTHONSITEDIR environment variable In-Reply-To: References: Message-ID: ago wrote: > The only thing I would add is that in my experience I often use > different working-envs for different projects, so I'd prefer to have a > more generic solution as opposed to a single working-env per user. The > latter could still be achieved by setting the appropriate environment > variable in the user profile. Do you think it would be possible to > accommodate for the above in your PEP? Isn't PYTHONUSERBASE sufficient for your needs? The env var alters the base directory. I can neither change the PEP nor the implementation at this stage of the development cycle. Python 2.6 and 3.0 are in beta and the API is set in stone. Christian From mathieu.malaterre at gmail.com Mon Sep 8 05:12:54 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Mon, 8 Sep 2008 02:12:54 -0700 (PDT) Subject: Test if list contains another list Message-ID: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> Hi there, I am trying to write something very simple to test if a list contains another one: a = [1,2,3] b = [3,2,1,4] but 'a in b' returns False. How do I check that a is indeed contained in b ? thanks From bearophileHUGS at lycos.com Tue Sep 23 11:31:14 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 23 Sep 2008 08:31:14 -0700 (PDT) Subject: Python is slow? References: Message-ID: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> sturlamolden: CPython is generally slow (you can see this from the huge amount of solutions invented to solve the speed problem, like Cython, Numpy, Psyco, ShedSkin, Weave, Inline, SIP, Boost Python, SWIG, etc etc), but for most of the usages Python is used for, it's not a significant problem. I know that sounds like a tautology :-) Well written C++ code is generally faster or much faster than similar Python code, but programming in Python is often simpler, and it generally requires less time. So it may happen that to solve a problem a Python program that runs in 1 hour that requires 1 hour to be written allows you to find the solution in less time than a C++ program that runs in 5-10 minutes that requires you 3-4 hours to be written :-) Note that C++ is just one option, but there are other languages around, like CLisp or D (or even a modern JavaVM), that are often an acceptable compromise between Python and C/C++. So you can show us a reduced/minimal working version of your Python code, so I/someone may find ways to speed it up, translate it to C or C ++ or CLisp or D, etc. Note that I have written a kd-tree in both Python (with Psyco compulsively) and D, this is the Psyco version: http://code.activestate.com/recipes/572156/ Bye, bearophile From mensanator at aol.com Sat Sep 20 14:51:55 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 20 Sep 2008 11:51:55 -0700 (PDT) Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> Message-ID: <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> On Sep 20, 1:34?pm, "Guilherme Polo" wrote: > On Sat, Sep 20, 2008 at 1:27 PM, Mensanator wrote: > > Beacuse in 2.6, Python apparently has fixed a discrepency that existed > > in previous versions. > > > In the IDLE that comes with 2.5, typing "as", to wit "import random as > > ran", > > the words "import" and "as" highlight in red, so you can't use them as > > variable > > names or you'll get a syntax error. > > > Ah, but you CAN use "as" for a variable: "for as in xrange(10): print > > as" > > works just fine, although it shouldn't. > > > Python 2.6 fixes this discrepency and now gives you a syntax error if > > you > > use "as" for a variable name. > > You should have noticed the warning you received in python 2.5 when > using "as" as a name. I'm not the one who wrote sympy, so I guess I'm not the only one who didn't notice it. If it's a well known problem, then sorry I wasted your time. The sympy people thought it was important and, as not everyone uses sympy, I thought I was performing a service to the community mentioning it here. Sheesh. > > > > > The upshot is code (such as sympy) written prior to 2.6 can crash now > > due > > to this fix if said code inadverntently used what should have been a > > reserved > > word. > > > I was able to fix the code for this "as" problem, but not the one that > > came after. I've reported this and interested parties can visit the > > sympy > > page and check Issue 1115. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves- Hide quoted text - > > - Show quoted text - From john at btqnet.com Mon Sep 29 00:48:24 2008 From: john at btqnet.com (johnc) Date: Sun, 28 Sep 2008 21:48:24 -0700 (PDT) Subject: Looking for a Python developer in Austin Message-ID: I?m looking for a python guru to help me and my company grow in this language area. We are native to .net but have found ourselves with a larger python perl project that needs some really good team members. Because this is not our core language I want to make sure this is a good fit. I can discuss more details but wanted to check if you are looking for work and are good in the webservices area of these languages? This is more of an infrastructure project not a website for external users. The job will require expert knowledge of webservices both writing and working with existing services. Possibly soap and others. Thanks for your time in advance. This is not a spam post, we really do need a guru to join our team. :) From michael at stroeder.com Thu Sep 4 19:39:35 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 05 Sep 2008 01:39:35 +0200 Subject: Can anyone suggest a good crypto package? In-Reply-To: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> References: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> Message-ID: Fett wrote: > On Sep 4, 2:23 pm, Mike Driscoll wrote: >> How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads > > Seems that this is intended more for webapps or something, Why do you think so? It's a C wrapper module around the OpenSSL crypto libs. Ciao, Michael. From george.sakkis at gmail.com Thu Sep 25 16:07:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 25 Sep 2008 13:07:53 -0700 (PDT) Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> <48dbc82e$0$1120$426a74cc@news.free.fr> <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> Message-ID: <1fc9b5c2-0e58-4b48-9352-4122986ce7ec@k13g2000hse.googlegroups.com> On Sep 25, 3:36 pm, "Dmitry S. Makovey" wrote: > Aaron "Castironpi" Brady wrote: > >> I kept this part of the problem out of this discussion as I'm pretty sure > >> I can fill those in once I figure out the basic problem of > >> auto-population of proxy methods since for each class/method those are > >> going to be nearly identical. If I can autogenerate those on-the-fly I'm > >> pretty sure I can add some extra-logic to them as well including > >> signature change where A::bmethod(self,c,x) would become > >> A::bmethod(self,x) etc. > > > Do you want to couple instances or classes together? > > It would be nice to have objects of B, C and D classes not knowing that they > are proxied (as they are used on their own too, not only inside of A > objects). I'm not sure if the approach below deals with all the issues, but one thing it does is decouple completely the proxied objects from the proxy: #======== usage ================================================================ from proxies import Proxy class B(object): def __init__(self): self.val = 'bval' def bmethod(self,n): print "B::bmethod",n def bmethod2(self,n,m): print "B::bmethod2",n,m class C(object): def __init__(self): self.val = 'cval' def cmethod(self,x): print "C::cmethod",x def cmethod2(self,x,y): print "C::cmethod2",x,y cattr = 4 class A(Proxy): DelegateMap = { 'bmethod' : B, 'bmethod2': B, 'cmethod': C, # do NOT delegate C.cmethod2 #'cmethod2': C, 'cattr' : C, } def __init__(self, b, c): print "init A()" # must call Proxy.__init__(*delegates) super(A,self).__init__(b,c) def amethod(self,a): print "A::mymethod",a if __name__ == '__main__': a = A(B(), C()) a.amethod('foo') # test bounded methods a.bmethod('foo') a.bmethod2('bar','baz') a.cmethod('foo') try: a.cmethod2('bar','baz') except Exception, ex: print ex # works for unbound methods too A.bmethod(a,'foo') A.bmethod2(a,'bar','baz') A.cmethod(a, 'foo') try: A.cmethod2(a,'bar','baz') except Exception, ex: print ex # non callable attributes print A.cattr #====== output ================================== init A() A::mymethod foo B::bmethod foo B::bmethod2 bar baz C::cmethod foo 'A' object has no attribute 'cmethod2' B::bmethod foo B::bmethod2 bar baz C::cmethod foo type object 'A' has no attribute 'cmethod2' 4 #======== proxies.py ========================= class _ProxyMethod(object): def __init__(self, name): self._name = name def unbound(proxy, *args, **kwds): method = proxy._get_target_attr(name) return method(*args, **kwds) self._unbound = unbound def __get__(self, proxy, proxytype): if proxy is not None: return proxy._get_target_attr(self._name) else: return self._unbound class _ProxyMeta(type): def __new__(meta, name, bases, namespace): for attrname,cls in namespace.get('DelegateMap', {}).iteritems(): if attrname not in namespace: attr = getattr(cls, attrname) if callable(attr): namespace[attrname] = _ProxyMethod(attrname) else: namespace[attrname] = attr return super(_ProxyMeta,meta).__new__(meta, name, bases, namespace) class Proxy(object): __metaclass__ = _ProxyMeta def __init__(self, *delegates): self._cls2delegate = {} for delegate in delegates: cls = type(delegate) if cls in self._cls2delegate: raise ValueError('More than one %s delegates were given' % cls) self._cls2delegate[cls] = delegate def _get_target_attr(self, name): try: cls = self.DelegateMap[name] delegate = self._cls2delegate[cls] return getattr(delegate, name) except (KeyError, AttributeError): raise AttributeError('%r object has no attribute %r' % (self.__class__.__name__, name)) HTH, George From jason at tishler.net Fri Sep 19 14:08:23 2008 From: jason at tishler.net (Jason Tishler) Date: Fri, 19 Sep 2008 14:08:23 -0400 Subject: Problem with Python shell through Cygwin Screen (Python/Vim/Screen combo) In-Reply-To: <1e357c83-b53b-4587-a4d3-5327d1762341@k13g2000hse.googlegroups.com> References: <1e357c83-b53b-4587-a4d3-5327d1762341@k13g2000hse.googlegroups.com> Message-ID: <20080919180823.GA624@tishler.net> Ant, On Fri, Sep 19, 2008 at 03:10:10AM -0700, Ant wrote: > [snip] > This works great in Linux, and also in Windows using the Cygwin build > of Python, but when you call: > > screen -S py -s python > > using the Windows build of Python, the shell just hangs. Does anyone > know if this is a known issue with screen/Python, or if there is a > workaround, as I'd prefer to have just a single Python instance > installed rather than having Cygwin python and windows Python both > installed. There are known issues when trying to run a Windows program that directly accesses the console under Cygwin. For example: http://mail.python.org/pipermail/python-list/2004-June/266661.html AFAICT, you will have to use Cygwin Python with screen. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From fredrik at pythonware.com Thu Sep 18 07:02:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Sep 2008 13:02:49 +0200 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: James Mills wrote: > As you can see (as long as you're > reading this in fixed-width fonts) > it _is_ very readable. given that it only relies on indentation from the left margin, it's no less readable in a proportional font (unless you're using an font with variable-width spaces, that is ;-). From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 20:12:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 00:12:03 GMT Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <00e58b46$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 16:22:31 -0700, Alex Snast wrote: > That's a lot of responses guys. Thanks a lot i think i got it. Another > question, are there any pointers in python (or iterators) for when i use > a data structure that doesn't support random access? That surely depends on the data structure. Assume it supports sequential access: data[0], data[1], data[2], etc in that order without skipping or going backwards. Then you can simply do this: for item in data: process(item) which is the equivalent of this: try: i = 0 while True: process(data[i]) i += 1 except IndexError: pass # we're done The data structure might not support sequential indexing, but still support sequential access: for item in iter(data): process(item) If the data structure is some sort of binary tree, then you would use a standard tree-walking algorithm, something like this: def prefix_traversal(node): process(node.info) prefix_traversal(node.left) prefix_traversal(node.right) and similarly for infix and postfix. (Although the specific names 'left', 'right', 'info' are arbitrary.) If you don't have any specific knowledge of how to iterate over the data structure, then try reading the docs *wink*. -- Steven From callen314 at gmail.com Tue Sep 23 17:17:09 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 23 Sep 2008 14:17:09 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <00e816f4$0$20303$c3e8da3@news.astraweb.com> <6602abad-3c12-4c0c-b41d-95f79cebdc31@y21g2000hsf.googlegroups.com> Message-ID: <698ac52a-c290-451d-944d-a9004161a516@n38g2000prl.googlegroups.com> > > > Usegrammers? > usegrammers are just those that use grammars, but misspell it. From deets at nospam.web.de Sun Sep 7 10:53:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Sep 2008 16:53:15 +0200 Subject: atomic section in code In-Reply-To: References: Message-ID: <6ii86rFqgj3vU1@mid.uni-berlin.de> Hendrik van Rooyen schrieb: > Fredrik Lundh wrote: > >> sounds like he wants/needs non-cooperative, mandatory locking. > > Could one get there using ctypes to disable interrupts? Not as such, ctypes can't execute arbitrary machine code. But of course you can create a C-lib that does what you want (IF it can be done, that is..), and wrap that. > Cross Platform? Certainly not. > I can think of lots of hassles, starting with permissions > to use the privileged instructions. I don't think there is a chance for this without major system tinkering. Under Linux, you could create a real time thread so highly prioritized that it won't yield any time to any other scheduler. And in a kernel-module, you can call cli (or whatever the needed call is). But this will most probably break your system. diez From tom.willis at gmail.com Wed Sep 24 18:47:18 2008 From: tom.willis at gmail.com (Thomas G. Willis) Date: Wed, 24 Sep 2008 15:47:18 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: On Sep 24, 4:59?pm, Duncan Booth wrote: ... > I haven't yet had occasion to use LINQ in anger yet, so I have no idea > whether its an idea to love or to hate. I do think it is good that C# has > effectively sprouted list comprehensions (not to mention anonymous types > and type inferencing) and I expect there may be some aspects worth looking > at for Python but I think they are more likely to lead to itertools > functions than extensions to syntax. My thoughts exactly when I first looked at it. "Hey C# NOW has list comprehensions!!! SWEET!!!" As I understand it LINQ is libraries(System.Data.Linq.dll, System.XML.Linq.dll) + syntactic sugar, i wouldn't call that a change to the language. The addition of lambdas and functions as first class objects however, that was indeed a language change, and it was a change for the better that makes LINQ possible, (also makes writing delegates less cumbersome). To someone other than a C# person, these features are not new or revolutionary, it's just C# catching up. Kudos to them for getting there before java. After some more thought on what might conceivably be missing from python that LINQ has, that someone might want is the equivalent of System.XML.Linq.dll, and I can't see any reason why someone couldn't write it with the exception that there doesn't seem to be a definitive XML lib for python, meaning generally regarded as the best. That in my mind would be a prerequisite. But if someone wrote both the XML lib with the LINQ-ish syntax, maybe it would become the definitive XML lib. Again, I personally don't see myself using XML and thus needing that unless my hand was forced by some business requirement that dictated I use XML, I would not use it if I had a choice. The SQL LiNQ-ish though, I think every python ORM has that covered to a degree, and I use that quite a bit. From michele.simionato at gmail.com Fri Sep 5 06:21:52 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 5 Sep 2008 03:21:52 -0700 (PDT) Subject: derived classes and __getattr__ References: <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> Message-ID: <0521db5b-aad1-4a2f-b0cf-5d9922ea8f57@f63g2000hsf.googlegroups.com> On Sep 5, 11:46?am, Alexandru Mosoi wrote: > I have another small problem. now, > d.third('blah') doesn't work because instance d doesn't have 'third' > attribute. I was expecting derived class to inherit the metaclass as > well, but it didn't. Yep, it is explained here: https://www.ibm.com/developerworks/linux/library/l-pymeta2/ It would help if you told us the real problem you are trying to solve. From marek at xivilization.net Wed Sep 3 05:26:25 2008 From: marek at xivilization.net (Marek Kubica) Date: Wed, 3 Sep 2008 09:26:25 +0000 (UTC) Subject: pyparsing: match empty line References: <9f838a29-2e2e-4646-9026-36d3b8a49fce@c58g2000hsc.googlegroups.com> Message-ID: Hi, First of all a big thank you for your excellent library and of course also for your extensive and enlightening answer! > 1) Well done in resetting the default whitespace characters, since you > are doing some parsing that is dependent on the presence of line ends. > When you do this, it is useful to define an expression for end of line > so that you can reference it where you explicitly expect to find line > ends: > > EOL = LineEnd().suppress() Ok, I didn't think about this. But as my program is not only a parser but a long-running process and setDefaultWhitespace modifies a global variable I don't feel too comfortable with it. I could set the whitespace on every element, but that is as you surely agree quite ugly. Do you accept patches? I'm thinking about some kind of factory-class which would automatically set the whitespaces: >>> factory = TokenFactory(' \t\r') >>> word = Factory.Word(alphas) >>> That way, one wouldn't need to set a grobal value which might interfere with other pyparsers running in the same process. > parser = OneOrMore(watchname ^ pagebreak ^ leaveempty ^ EOL) > > This will now permit the second test to pass. Right. Seems that working with whitespace requires a bit better understanding than I had. > 3) Your definition of pagebreak looks okay now, but I don't understand > why your test containing 2 blank lines is only supposed to generate a > single . No, it should be one per blank line, now it works as expected. > 4) leaveempty probably needs this parse action to be attached to it: > > leaveempty = > Literal('EMPTY').setParseAction(replaceWith('')) I added this in the meantime. replaceWith is really a handy helper. > parser = OneOrMore(watchname | pagebreak | leaveempty | EOL) > > '|' operators generate MatchFirst expressions. MatchFirst will do > short-circuit evaluation - the first expression that matches will be the > one chosen as the matching alternative. Okay, adjusted it. > If you have more pyparsing questions, you can also post them on the > pyparsing wiki - the Discussion tab on the wiki Home page has become a > running support forum - and there is also a Help/Discussion mailing > list. Which of these two would you prefer? Thanks again, it works now just as I imagined! regards, Marek From mensanator at aol.com Thu Sep 4 01:20:43 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 3 Sep 2008 22:20:43 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> Message-ID: <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> On Sep 3, 8:30?pm, Steven D'Aprano wrote: > On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: > >>>> sum([]) > > 0 > > > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It > > should return None or throw an exception like sum([None,1]) does. > > You're wrong, because 99.9% of the time when users leave a blank cell in > Excel, they want it to be treated as zero. Then 99.9% of users want the wrong thing. Microsoft knows that this is a bug but refuses to fix it to prevent breaking legacy documents (probably dating back to VisiCalc). When graphimg data, a missing value should be interpreted as a hole in the graph +------+ +--+------+------+-----+ and not evaluated as 0 +------+ +--+------+------+-----+ \ / \ / \ / \ / \ / \+/ (depending on the context of the graph, of course). And Microsoft provides a workaround for graphs to make 0's appear as holes. Of course, this will cause legitimate 0 values to disappear, so the workaround is inconsistent. > Spreadsheet sum() is not the > same as mathematician's sum, which doesn't have a concept of "blank > cells". (But if it did, it would treat them as zero, since that's the > only useful thing and mathematicians are just as much pragmatists as > spreadsheet users.) The Excel code does the right thing, and your "pure" > solution would do the unwanted and unexpected thing and is therefore > buggy. Apparently, you don't use databases or make surface contours. Contour programs REQUIRE that blanks are null, not 0, so that the Kriging algorithm interpolates around the holes rather than return false calculations. Excel's treatment of blank cells is inconsistent with Access' treatment of Nulls and therefore wrong, anyway you slice it. Math isn't a democracy, what most people want is irrelevant. I don't pull these things out of my ass, it's real world stuff I observe when I help CAD operators and such debug problems. Maybe you want to say a bug is when it doesn't do what the author intended, but I say if what the intention was is wrong, then a perfect implentation is still a bug because it doesn't do what it's supposed to do. > > Bugs are defined by "does the code do what the user wants it to do?", not > "is it mathematically pure?". ReallY? So you think math IS a democracy? There is no reason to violate mathematical purity. If I don't get EXACTLY the same answer from Excel, Access, Mathematica and Python, then SOMEBODY is wrong. It would be a shame if that somebody was Python. > The current behaviour of sum([]) does the > right thing for the 99% of the time when users expect an integer. Why shouldn't the users expect an exception? Isn't that why we have try:except? Maybr 99% of users expect sum([])==0, but _I_ expect to be able to distinguish an empty list from [4,-4]. > And the > rest of the time, they have to specify a starting value for the sum > anyway, and so sum([], initial_value) does the right thing *always*. So if you really want [] to be 0, why not say sum([],0)? Why shouldn't nothing added to nothing return nothing? Having it evaluate to 0 is wrong 99.9% of the time. > > The only time it does the wrong thing[1] is when you forget to pass an > initial value but expect a non-numeric result. And that's the > programmer's error, not a function bug. > > [1] I believe it also does the wrong thing by refusing to sum strings, > but that's another story. > > -- > Steven From aaron.hildebrandt at gmail.com Wed Sep 10 13:45:02 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 10:45:02 -0700 (PDT) Subject: Reading binary data References: <508e31d9-daab-4346-9441-55cc47f7c1f4@m44g2000hsc.googlegroups.com> Message-ID: <54d64616-b86c-45bd-a8b5-4332faa5a73d@a70g2000hsh.googlegroups.com> > CORRECTION: '3cII' should be '3sII'. Even with the correction, I'm still getting the error. From wuwei23 at gmail.com Thu Sep 4 22:08:49 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 4 Sep 2008 19:08:49 -0700 (PDT) Subject: Issue warning if no "return" in function? References: Message-ID: On Sep 4, 8:05?pm, Poster28 wrote: > What would you suggest to check python programs for non-syntax error. > One example I could think of that one might forget to "return" a value from > a function. > > How could I check for these and maybe other mistakes? I really recommend getting into the habit of writing tests for all of your programs. I like the test-driven approach; write a test that reflects the behaviour you want and -then- write your code. If it doesn't succeed, there's most likely something wrong with your code. Test-Driven Development in Python: http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html nose (a very nice test runner): http://code.google.com/p/python-nose/ From kw at codebykevin.com Tue Sep 9 14:11:57 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 09 Sep 2008 14:11:57 -0400 Subject: How to record audio from Python on Mac? In-Reply-To: References: Message-ID: <48C6BC6D.8040207@codebykevin.com> skip at pobox.com wrote: > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > casting a broader net.) > > Can I easily control audio record/playback from Python on my Mac? I know > zip about audio recording or about Apple APIs via Python. Pointers to > simple examples would be much appreciated. > > Thanks, > > Skip You can probably access this functionality via PyObjC--it provides access to the Cocoa frameworks. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From rcdailey at gmail.com Thu Sep 4 19:48:55 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Sep 2008 18:48:55 -0500 Subject: Case-insensitive string compare? In-Reply-To: <200809050059.17038.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> <200809050059.17038.maric@aristote.info> Message-ID: <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> On Thu, Sep 4, 2008 at 5:59 PM, Maric Michaud wrote: > Le Friday 05 September 2008 00:47:00 Chris Rebert, vous avez ?crit : > > > > Then store the string in its original case in the value part of the > > key-value pair: > > > > stage_map[key.lower()] = (key,whatever) > > > > "premature optimization is the root of all evil" > > I don't recall the OP wanted a (a bit) faster solution to his problem in > counterpart of memory loss and syntax complication. > > If the OP's proposal seems already messy, how about ths one : > if lib.lower() not in ( e[0] for e in stage_map.items() ) : > ... Thanks everyone for your help. I'm not opposed to using [key.lower() for key in stage_map] at all, I was just curious to see if there were any cleaner alternatives. It looks like that is what I'll be using. I'm not familiar with how python works internally, but coming from C++ it seems like "remaking" the map would be slow. However, speed is not my main concern in my particular situation, I'm just curious to learn more about python. Thanks again everyone. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ocgstyles at gmail.com Tue Sep 2 13:40:07 2008 From: ocgstyles at gmail.com (ocgstyles at gmail.com) Date: Tue, 2 Sep 2008 10:40:07 -0700 (PDT) Subject: Problems when working with different timezones Message-ID: <4a56c18d-2132-45f5-a750-e0a41bf14248@f36g2000hsa.googlegroups.com> Here's some Python code executed on Red Hat 3.4 web server located in Mountain time (MDT). You'll notice that the time after setting the timezone to Eastern time (EST), the time is incorrectly 6 hours ahead, when it should only be 3. Python 2.5 (r25:51908, Mar 23 2007, 14:22:20) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime, os >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 11, 25, 35, 39856) >>> os.environ['TZ']='America/New_York' >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 17, 26, 0, 703537) Here's the same thing executed on an Ubuntu box in EST. I alter the timezone to a MDT and it works as one would expect. Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime, os >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 13, 11, 6, 438123) >>> os.environ['TZ'] = 'America/Denver' >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 11, 11, 21, 43602) What could be the reason for this failing on Red Hat? Keith From bj_666 at gmx.net Tue Sep 30 10:34:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Sep 2008 14:34:31 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6ke1i8F7dmkkU2@mid.uni-berlin.de> Message-ID: <6kernnF7dmkkU3@mid.uni-berlin.de> On Tue, 30 Sep 2008 15:42:58 +0200, Ivan Reborin wrote: > On 30 Sep 2008 07:07:52 GMT, Marc 'BlackJack' Rintsch > wrote: >>===== >>from __future__ import with_statement from functools import partial >>from itertools import islice >>from pprint import pprint >> >> >>def read_group(lines, count): >> return [map(int, s.split()) for s in islice(lines, count)] >> >>def main(): >> with open('test.txt') as lines: >> lines = (line for line in lines if line.strip()) >> result = list(iter(partial(read_group, lines, 3), list())) >> pprint(result, width=30) >> >>if __name__ == '__main__': >> main() >>===== > > I'm afraid I must admit I find the code above totally uncomprehesible (I > can't even see where the array here is mentioned - "result"?) and > inpractical for any kind of engineering practice I had in mind. Learn Python then to understand that code. ;-) There is no array. The data type is called "list" in Python, so `result` is a nested list. And in Python it quite unusual to build lists by creating them with the final size filled with place holder objects and then fill the real values in. Instead lists are typically created by appending values to existing lists, using list comprehension or the `list()` function with some iterable object. Typical Python code tries to minimize the use of index variables. Python is not Fortran (or C, or Pascal, ?). > Does python, perchance, have some wrapper functions or something, which > would allow one to load an array in a more natural "technical" way ? > Like something mentioned above in my post (now deleted) ? > > Also, is there a way to change counter for arrays to go from 0 to 1 ? You can write your own sequence type but that would be odd because the rest of the language expects zero as the first index, so you will be constantly fighting the language by adding or subtracting 1 all the time at the "border" between your custom sequence type and the the rest of Python. Ciao, Marc 'BlackJack' Rintsch From graphaelli at gmail.com Fri Sep 26 02:55:50 2008 From: graphaelli at gmail.com (graph) Date: Thu, 25 Sep 2008 23:55:50 -0700 (PDT) Subject: Module import path when embedding python in C Message-ID: <913fe5fc-9b8e-49c6-b740-5d6bb74abc97@s20g2000prd.googlegroups.com> Per http://mail.python.org/pipermail/python-list/2008-September/506206.html something like this (plus error handling) seems to be the right way to add to sys.path when embedding python in C: PyObject *sys_path = PySys_GetObject("path"); PyObject *path = PyString_FromString("/your/path"); PyList_Append(sys_path, path); Does anyone know why PySys_GetObject wasn't documented until somewhat recently (http://bugs.python.org/issue1245) if it has been part of the system module interface since at least Python 1.5.2? Is it not supposed to be used? What's the difference the above and importing the sys module and then doing the append? Thanks in advance. -g From mathieu.prevot at gmail.com Thu Sep 4 03:25:37 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 09:25:37 +0200 Subject: use str as variable name Message-ID: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> Hi, I have a program that take a word as argument, and I would like to link this word to a class variable. eg. class foo(): width = 10 height = 20 a=foo() arg='height' a.__argname__= new_value rather than : if arg == 'height': a.height = new_value elif arg == 'width'; a.width = new_value Can I do this with python ? How ? Thanks, Mathieu From harrrrpo at gmail.com Fri Sep 5 08:58:30 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Fri, 5 Sep 2008 15:58:30 +0300 Subject: [ANN] PyDM 1.1 Message-ID: <538050a90809050558x4e08605dhfac219a56d67db97@mail.gmail.com> PyDM 1.1 is released and now available from http://sourceforge.net/projects/pycdm/ ---- PyDM is a Multi-Threaded Download Manager in Python , this is the second release Features :- 1) Http handling at socket level no external http libs 2) Two interfaces with core , one in Qt and the other is Console 3) Download Pausing (Qt Interface) 4) Download Resume (Qt Interface) 5) Saving Downloaded Files in a list (Powered by SQLite) 6) Configuration file (PyDM.ini) for number of threads,Temp Directory and download directory 7) Displaying Rate/Status/Url/Filename for each downloaded file Regards , Mohamed Yousef From michel at nospam.please Mon Sep 15 15:03:33 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:03:33 +0200 Subject: environment variable issue In-Reply-To: References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <48ceb185$0$2847$ba620e4c@news.skynet.be> Fredrik Lundh a ?crit : > this might help: > > http://mail.python.org/pipermail/python-list/2008-September/507933.html Yes, it helps. Thanks > > (scanning the subjects of recent and ongoing threads before posting is > always a good idea). I did search the web but didn't find anything related to the problem I had. I didn't think searching the newsgroups, though. Thanks for your help, Michel -- Michel Leunen http://linux.leunen.com From fredrik at pythonware.com Mon Sep 1 08:47:03 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Sep 2008 14:47:03 +0200 Subject: Know if a object member is a method In-Reply-To: <27308d500809010542n766bd9fmfdd9775ad3fdabf7@mail.gmail.com> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> <00cbd80b$0$20302$c3e8da3@news.astraweb.com> <27308d500809010542n766bd9fmfdd9775ad3fdabf7@mail.gmail.com> Message-ID: Luca wrote: > Yes, this helps a lot. In facts I need to do something like a language parser. a *parser* that works on object structures created by executing a Python program? From gagsl-py2 at yahoo.com.ar Mon Sep 22 05:37:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Sep 2008 06:37:16 -0300 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09F2@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09F3@AWMAIL04.belcan.com> Message-ID: En Sun, 21 Sep 2008 19:42:10 -0300, Blubaugh, David A. escribi?: > Sir, > Thank you for your reply. This is as to how I developed my .pyd file. > I entered the following commands within my MS-DOS prompt within Windows > XP: > > C:\python25\Scripts> C:\python25\python f2py.py -c --fcompiler=gnu95 > --compiler=mingw32 -m hello hello.f90 > > I am using the gfortran compiler, that was prescribed to use, as well > as, the required commands on the following website: > > http://www.scipy.org/F2PY_Window > > > I comes down to that yes, I am able to generate a .pyd file, which was > generated by f2py. However, when I tried to import this file into my > python script program I was given the following error: > error 193?? > I do not know as to what I am doing incorrectly, since I am generating a > .pyd file by f2py? If I am doing anything that is incorrect, then why > am I EVEN ABLE TO GENERATE A .PYD FILE IN THE FIRST PLACE??? Any Help > will be greatly appreciated!!!!! Below there is a transcript of a compile session. I've used a somewhat old version of mingw and g77, scipy 1.1.1, python 2.5.2: C:\TEMP\for>dir /b dscal.for C:\TEMP\for>type dscal.for SUBROUTINE DSCAL(N, ALPHA, X) * * X <- ALPHA * X * INTEGER N DOUBLE PRECISION ALPHA DOUBLE PRECISION X(*) DO I = 1, N X(I) = ALPHA * X(I) END DO WRITE (*,*) ALPHA RETURN END C:\TEMP\for>g77 --version GNU Fortran (GCC) 3.4.2 (mingw-special) Copyright (C) 2004 Free Software Foundation, Inc. GNU Fortran comes with NO WARRANTY, to the extent permitted by law. You may redistribute copies of GNU Fortran under the terms of the GNU General Public License. For more information about these matters, see the file named COPYING or type the command `info -f g77 Copying'. C:\TEMP\for>python -V Python 2.5.2 C:\TEMP\for>python c:\apps\python25\scripts\f2py.py -v 2_5590 C:\TEMP\for>python c:\apps\python25\scripts\f2py.py -c -m dscal dscal.for [...lots of output...] Found executable c:\apps\mingw\bin\g77.exe gnu: no Fortran 90 compiler found customize Mingw32CCompiler using scons Found executable c:\apps\mingw\bin\g++.exe [...] gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes -Ic:\docume~1\gabriel\config~1\tem p\tmpoygjnk\src.win32-2.5 -IC:\Apps\Python25\lib\site-packages\numpy\core\includ e -IC:\Apps\Python25\include -IC:\Apps\Python25\PC -c c:\docume~1\gabriel\config ~1\temp\tmpoygjnk\src.win32-2.5\dscalmodule.c -o c:\docume~1\gabriel\config~1\te mp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\dsca lmodule.o gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes -Ic:\docume~1\gabriel\config~1\tem p\tmpoygjnk\src.win32-2.5 -IC:\Apps\Python25\lib\site-packages\numpy\core\includ e -IC:\Apps\Python25\include -IC:\Apps\Python25\PC -c c:\docume~1\gabriel\config ~1\temp\tmpoygjnk\src.win32-2.5\fortranobject.c -o c:\docume~1\gabriel\config~1\ temp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\fo rtranobject.o [...] c:\apps\mingw\bin\g77.exe -g -Wall -mno-cygwin -g -Wall -mno-cygwin -shared c:\d ocume~1\gabriel\config~1\temp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\t mpoygjnk\src.win32-2.5\dscalmodule.o c:\docume~1\gabriel\config~1\temp\tmpoygjnk \Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\fortranobject.o c:\docume~1\gabriel\config~1\temp\tmpoygjnk\Release\dscal.o -Lc:\apps\mingw\lib -Lc:\apps\mingw\lib\gcc\mingw32\3.4.2 -LC:\Apps\Python25\libs -LC:\Apps\Python25 \PCBuild -lpython25 -lg2c -o .\dscal.pyd [...] C:\TEMP\for>dir /b dscal.for dscal.pyd C:\TEMP\for>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> import numpy py> import dscal py> print dscal.dscal.__doc__ dscal - Function signature: dscal(n,alpha,x) Required arguments: n : input int alpha : input float x : input rank-1 array('d') with bounds (*) py> v = numpy.array([1,2,3,4,5], 'd') py> print v [ 1. 2. 3. 4. 5.] py> dscal.dscal(len(v), 2, v) 2. py> print v [ 2. 4. 6. 8. 10.] -- Gabriel Genellina From ptmcg at austin.rr.com Wed Sep 3 09:12:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 3 Sep 2008 06:12:47 -0700 (PDT) Subject: pyparsing: match empty line References: <9f838a29-2e2e-4646-9026-36d3b8a49fce@c58g2000hsc.googlegroups.com> Message-ID: <0df1f752-ee27-4eeb-ab63-1566ed9a3e24@k37g2000hsf.googlegroups.com> On Sep 3, 4:26 am, Marek Kubica wrote: > Hi, > > First of all a big thank you for your excellent library and of course > also for your extensive and enlightening answer! > I'm glad pyparsing has been of help to you. Pyparsing is building its own momentum these days. I have a new release in SVN that I'll put out in the next week or so. > Ok, I didn't think about this. But as my program is not only a parser but > a long-running process and setDefaultWhitespace modifies a global > variable I don't feel too comfortable with it. Pyparsing isn't really all that thread-friendly. You definitely should not have multiple threads using the same grammar. The approaches I've seen people use in multithread applications are: 1) synchronize access to a single parser across multiple threads, and 2) create a parser per-thread, or use a pool of parsers. Pyparsing parsers can be pickled, so a quick way to reconstitute a parser is to create the parser at startup time and pickle it to a string, then unpickle a new parser as needed. > I could set the whitespace > on every element, but that is as you surely agree quite ugly. Do you > accept patches? I'm thinking about some kind of factory-class which would > automatically set the whitespaces: > > >>> factory = TokenFactory(' \t\r') > >>> word = Factory.Word(alphas) > > That way, one wouldn't need to set a grobal value which might interfere > with other pyparsers running in the same process. I tried to prototype up your TokenFactory class, but once I got as far as implementing __getattribute__ to return the corresponding pyparsing class, I couldn't see how to grab the object generated for that class, and modify its whitespace values. I did cook up this, though: class SetWhitespace(object): def __init__(self, whitespacechars): self.whitespacechars = whitespacechars def __call__(self,pyparsing_expr): pyparsing_expr.setWhitespace(self.whitespacechars) return pyparsing_expr noNLskipping = SetWhitespace(' \t\r') word = noNLskipping(Word(alphas)) I'll post this on the wiki and see what kind of comments we get. By the way, setDefaultWhitespace only updates global variables that are used at parser definition time, *not* at parser parse time. So, again, you can manage this class attribute at the initialization of your program, before any incoming requests need to make use of one parser or another. > > 4) leaveempty probably needs this parse action to be attached to it: > > > leaveempty = > > Literal('EMPTY').setParseAction(replaceWith('')) > > I added this in the meantime. replaceWith is really a handy helper. After I released replaceWith, I received a parser from someone who hadn't read down to the 'R's yet in the documentation, and he implemented the same thing with this simple format: leaveempty = Literal('EMPTY').setParseAction(lambda : '') These are pretty much equivalent, I was just struck at how easy Python makes things for us, too! > > If you have more pyparsing questions, you can also post them on the > > pyparsing wiki - the Discussion tab on the wiki Home page has become a > > running support forum - and there is also a Help/Discussion mailing > > list. > > Which of these two would you prefer? > They are equivalent, I monitor them both, and you can browse through previous discussions using the Discussion tab online threads, or the mailing list archive on SF. Use whichever is easier for you to work with. Cheers, and Welcome to Pyparsing! -- Paul From nick at craig-wood.com Wed Sep 24 06:30:06 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 24 Sep 2008 05:30:06 -0500 Subject: How can I use a PyObject in C++? References: Message-ID: lixinyi.23 at gmail.com wrote: > for example: > #include > > void exec_python_code(int arg, char** argv) > { > Py_Initialize(); > Py_Main(argc,argv); > Py_Finalize(); > } > > What I would like to know is: > after Py_Main(argc,argv); > > How do I get every variable in python space, > say a=[1,2,3,'Hello World',[2,3]] > b=['xx','xxx','ffff',0.1234] , and use them in C++? > > any sample code? > Thanks in advance! Here is a bit of code I wrote yesterday which calls a python function imported from a module and processes the result. It would only be a dozen lines if it weren't for the error handling! The code was compiled with a C++ compiler. Read the python C API docs for more info (these work fine in C++ also) http://docs.python.org/api/api.html Note it is very important to keep track of who owns which object - hence the comments about /* new ref */ and /* borrowed */ Yes it uses goto... I find it is the easiest way of error handling in C and making sure you don't leak objects on error conditions ;-) /* Call the python function MyModule.SubModule.my_function() and return the result as a malloc-ed string or 0 if there was a problem or my_function returned None */ char *my_function(void) { char *my_result = 0; PyObject *module = 0; PyObject *result = 0; PyObject *module_dict = 0; PyObject *func = 0; module = PyImport_ImportModule((char *)"MyModule.SubModule"); /* new ref */ if (module == 0) { PyErr_Print(); printf("Couldn't find python module MyModule.SubModule"); goto out; } module_dict = PyModule_GetDict(module); /* borrowed */ if (module_dict == 0) { PyErr_Print(); printf("Couldn't find read python module MyModule.SubModule"); goto out; } func = PyDict_GetItemString(module_dict, "my_function"); /* borrowed */ if (func == 0) { PyErr_Print(); printf("Couldn't find MyModule.SubModule.my_function"); goto out; } result = PyEval_CallObject(func, NULL); /* new ref */ if (result == 0) { PyErr_Print(); printf("Couldn't run MyModule.SubModule.my_function"); goto out; } else if (result == Py_None) { printf("MyModule.SubModule.my_function returned None"); goto out; } my_result = PyString_AsString(result); /* borrowed */ if (my_result == 0) { PyErr_Print(); printf("Couldn't read result from MyModule.SubModule.my_function"); goto out; } my_result = strdup(my_result); /* keep in our own memory */ out:; Py_XDECREF(result); Py_XDECREF(module); return my_result; } -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bdesth.quelquechose at free.quelquepart.fr Fri Sep 12 13:40:08 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Sep 2008 19:40:08 +0200 Subject: book example confusion In-Reply-To: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: <48cac567$0$7824$426a74cc@news.free.fr> byron a ?crit : > I am reading o'reilly's learning python (great book), but i came > across an example (pg 291, pdf) that I am not quite understanding the > reasoning for the author's explanation: > > if f1() or f2(): > > The author states that do to the nature of that expression, if f1() > returns True, f2() will not be evaluated.. which makes sense. His > quote: > > "Here, if f1 returns a true (or nonempty) value, Python will > never run f2." > > He then states: > > "To guarantee that both functions will be run, call them > before the 'or':" > > tmp1, tmp2 = f1(), f2() > if tmp1 or tmp2: > > Being that each function is an object, a name assignment to > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > the name is called.. It (well... they) is (are) actually called. The parens are the call operator. From mal at egenix.com Thu Sep 4 04:31:45 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 04 Sep 2008 10:31:45 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <48BF9CF1.70100@egenix.com> On 2008-09-04 07:49, Kay Schluehr wrote: > 3) Following the public rumor mill and the latest hype RIA i.e. the > merge of web- and desktop applications with systems like Adobe AIR, > JavaFX, Google Gears and MS Silverlight is the future of frontend > development. With the exception of IronPython and Silverlight, Python > hasn't even entered this game and no one knows if it ever will. Actually, it has already and quite some time ago: http://www.artima.com/weblogs/viewpost.jsp?thread=208528 The recipe is simple: use Python for the business logic, database interfacing, etc and have it talk to a Flex front-end via XML-RPC or REST. As a nice side-effect, this also results in a better separation between GUI and backend, effectively making the solution future-proof and easy to adapt to other front-end technologies. We've been working with this approach for almost a year now and so far never had to look back. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From bearophileHUGS at lycos.com Mon Sep 29 17:41:14 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 14:41:14 -0700 (PDT) Subject: Converting a strng to an anonymous function References: Message-ID: On Sep 29, 11:25 pm, Nathan Seese wrote: > I'm writing a program to sort files with arbitrary python code. The > method I'm using for that is to pass sort an anonymous function taken > from the arguments. I'm wondering how to change a raw string into an > anonyous function. Is this enough for you? >>> L = [1, -5, 7, -9] >>> sorted(L, key=abs) [1, -5, 7, -9] >>> func = "abs" >>> sorted(L, key=eval(func)) [1, -5, 7, -9] >>> func = "abs(x)" >>> sorted(L, key=lambda x: eval(func)) [1, -5, 7, -9] Bye, bearophile From ranim81 at gmail.com Mon Sep 1 08:28:17 2008 From: ranim81 at gmail.com (raju) Date: Mon, 1 Sep 2008 05:28:17 -0700 (PDT) Subject: about computer tips inonline click here Message-ID: http://www.moneymaking4.blogspot.com/ From gminick at bzt.bzt Wed Sep 3 06:44:38 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 3 Sep 2008 10:44:38 +0000 (UTC) Subject: python - mechanize/browser/POST issue References: Message-ID: On Tue, 2 Sep 2008 19:39:05 -0700, bruce wrote: > using mechanize/Browser, i can easily do a url/get, and process submitting a > form that uses a GET as the action. however, I'm not quite sure how to > implement the submittal of a form, that uses the POST action. > > Anyone have a short chunk of code that I can observer, that uses the > mechanize.Browser implentation? Take a look at the bottom of this post: http://mail.python.org/pipermail/python-list/2006-June/390037.html It seems that submit does the job. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bearophileHUGS at lycos.com Sat Sep 20 20:38:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 20 Sep 2008 17:38:15 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Christian Heimes: > Unless you have specific needs for highly specialized data types, use lists. There's also the collections.deque for other related purposes. (I suggest people willing to look at some nice C code to read the sources of deque, Hettinger has created some refined code, very readable). Bye, bearophile From drobinow at gmail.com Thu Sep 11 12:42:05 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Thu, 11 Sep 2008 09:42:05 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> Message-ID: <09345856-9a44-449c-9ee0-6254c573847e@b1g2000hsg.googlegroups.com> On Sep 11, 11:13?am, "carriere.jonat... at gmail.com" wrote: > On Sep 11, 4:19?pm, Fredrik Lundh wrote: > > > > > carriere.jonat... at gmail.com wrote: > > > ?> I wonder if there is a platform written in python. The equivalent of > > ?> the Netbeans platformhttp://platform.netbeans.org/inthe Python > > ?> world. Do you know such a thing? > > > You (or maybe the Java folks) seem to have missed that platform has a > > rather specific meaning in computing: > > >http://en.wikipedia.org/wiki/Platform_(computing) > > > Given that definition, Python is pretty much a platform in itself. ?If > > you want to use Python for a specific task, you add libraries for that > > task. ?Tell us what you want to do, and we'll tell you what libraries > > and toolkits you might want to try. > > > > > I want to build a desktop application. I am searching for some kind of > environment that would provide all the elements ready (Windows...). > Then I would have to code the business logic only. > > Jonathan. What's business logic? From m_palmer45 at yahoo.ca Fri Sep 19 18:37:01 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 19 Sep 2008 15:37:01 -0700 (PDT) Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Message-ID: <1263d02b-e007-41f0-bd7f-465e0aee312a@l43g2000hsh.googlegroups.com> On Sep 18, 5:33 pm, erikcw wrote: > Hi, > > I have a cgi script where users are uploading large files for > processing. I want to launch a subprocess to process the file so the > user doesn't have to wait for the page to load. > > What is the correct way to launch subprocess without waiting for the > result to return? > > Thanks! both os.spawn or subprocess can be used. I actually find subprocess hard to remember so usually prefer os.spawn. For various examples and explanations, see http://effbot.org/librarybook/os.htm From gagsl-py2 at yahoo.com.ar Tue Sep 30 15:23:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 16:23:41 -0300 Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <00f15dd2$0$20617$c3e8da3@news.astraweb.com> Message-ID: En Tue, 30 Sep 2008 08:07:18 -0300, Steve Holden escribi?: > Terry Reedy wrote: >> Steven D'Aprano wrote: >>> Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians >>> and physicists. >> >> It should be both, just as + is addition for numbers and concatenation >> for sequences. Or we could have just one built-in -- size() instead of >> abs() and len(). For non-sequence collections, size() would be better >> than len() anyway. >> > And how are these "non-sequence collections" to be distinguished? And > how does size() differ from len() in that case? Consider a tree, or a graph. The number of elements they have is not naturally described as their "length", the usual term is "size" instead. "Length" is adequate for one-dimensional structures only; even len(dict) is a bit controversial. Had Python used the more generic size and __size__ from the beginning, we'd be all happy now :) But it's too late to change things. -- Gabriel Genellina From srad at inbox.lv Sat Sep 6 08:31:09 2008 From: srad at inbox.lv (Aigars Aigars) Date: Sat, 06 Sep 2008 15:31:09 +0300 Subject: Cancel instance create In-Reply-To: <538050a90809060504x3b82d402hefbc152c1812d685@mail.gmail.com> References: <1220697080.48c25bf890ade@www.inbox.lv> <538050a90809060504x3b82d402hefbc152c1812d685@mail.gmail.com> Message-ID: <1220704269.48c2780d05777@www.inbox.lv> I do not want code outside my class to perform tests and decide to create instance or not. Fredrik Lundh's advice to rise exception works perfectly. Thanks to all, Aigars Quoting Mohamed Yousef : ًWhat about no Constructor , and a custom instancing function that can return either None or the instance wanted -- http://mail.python.org/mailman/listinfo/python-list Links: ------ [1] mailto:harrrrpo at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Tue Sep 23 19:58:56 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 24 Sep 2008 01:58:56 +0200 Subject: Visualize class inheritance hierarchy In-Reply-To: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> References: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Message-ID: Rob Kirkpatrick wrote: > I'm assuming this has been discussed before, but I'm lacking any > Google keywords that bring up the appropriate discussion. You are looking for "mro" aka method resolution order. The inspect module contains several helper functions to inspect a class hierarchy. The following interactive session should give you an impression how to use the functions: >>> import inspect >>> import pprint >>> from sqlalchemy.types import DateTime >>> inspect.getmro(DateTime) (, , , >>> DateTime.__bases__ (,) >>> pprint.pprint(inspect.getclasstree(inspect.getmro(DateTime))) [(, ()), [(, (,)), [(, (,)), [(, (,))]]]] >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, '__init__')] [, , , ] >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, 'adapt')] [, ] From hniksic at xemacs.org Fri Sep 12 06:36:57 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Sep 2008 12:36:57 +0200 Subject: Accessing __slots__ from C References: <87k5diex3m.fsf@mulj.homelinux.net> Message-ID: <87ej3p7ira.fsf@mulj.homelinux.net> Chris writes: >> PyObject_GetAttrString is convenient, but it creates a Python string >> only so it can intern it (and in most cases throw away the freshly >> created version). For maximum efficiency, pre-create the string >> object using PyString_InternFromString, and use that with >> PyObject_GetAttr. > > Yes, we'd thought of that too, but it doesn't seem to be an > important factor compared to the actual attribute lookup. I'd like to see your test code. In my experience, as long as you're accessing simple slots, you should notice a difference. PyObject_GetAttr with an interned string key executes a single dict lookup of the type object followed by C code that simply and very efficiently dereferences the PyObject from a constant offset described by the slot. The dict lookup involved is quite optimized, it doesn't even have to calculate the string's hash, which remains cached in the interned string object. On the other hand, PyObject_GetAttrString creates a new string each time, looks it up in the set of interned strings (which itself requires a dict lookup complete with hash calculation), and then executes PyObject_GetAttrString. These additional operations should have execution time of the same order of magnitude as PyObject_GetAttr's execution time. Here is a test program that shows a 4.6 time speedup simply by switching from PyObject_GetAttrString to PyObject_GetAttr: #include /* gcc -shared -O2 -I/usr/include/python2.5 attr.c -lpython2.5 -o attr.so */ static PyObject * bench1(PyObject *ignored, PyObject *obj) { int i; for (i = 0; i < 1000000; i++) { PyObject *attr = PyObject_GetAttrString(obj, "abcdef"); if (!attr) return NULL; Py_DECREF(attr); } Py_RETURN_NONE; } static PyObject * bench2(PyObject *ignored, PyObject *obj) { static PyObject *key; if (!key) { key = PyString_InternFromString("abcdef"); if (!key) return NULL; } int i; for (i = 0; i < 1000000; i++) { PyObject *attr = PyObject_GetAttr(obj, key); if (!attr) return NULL; Py_DECREF(attr); } Py_RETURN_NONE; } static PyMethodDef attr_methods[] = { {"bench1", (PyCFunction) bench1, METH_O }, {"bench2", (PyCFunction) bench2, METH_O }, {NULL} }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC initattr(void) { PyObject *module = Py_InitModule3("attr", attr_methods, NULL); } >>> import attr, time >>> class MyClass(object): ... __slots__ = 'abcdef', ... >>> o = MyClass() >>> o.abcdef = 1 >>> t0 = time.time(); attr.bench1(o); t1 = time.time() >>> t1-t0 0.28227686882019043 >>> t0 = time.time(); attr.bench2(o); t1 = time.time() >>> t1-t0 0.060719013214111328 (Repeated runs show very similar timings.) From carsten.haese at gmail.com Thu Sep 25 11:14:51 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Thu, 25 Sep 2008 11:14:51 -0400 Subject: "which python" as a python command? In-Reply-To: References: Message-ID: chardish at gmail.com wrote: > Hello, > > I'm trying to find out in a script where the location of the current > python is. import sys print sys.executable HTH, -- Carsten Haese http://informixdb.sourceforge.net From dusan.smitran at gmail.com Mon Sep 29 07:38:34 2008 From: dusan.smitran at gmail.com (dusans) Date: Mon, 29 Sep 2008 04:38:34 -0700 (PDT) Subject: generate random digits with length of 5 References: <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> <07d14730-a585-4976-adda-540d32a2066d@y38g2000hsy.googlegroups.com> <1d078691-662d-40a5-8519-62bee01dad4e@u65g2000hsc.googlegroups.com> Message-ID: <8707ec1a-3e33-41eb-944f-578f4bce7c78@z72g2000hsb.googlegroups.com> On Sep 29, 12:06?am, Mensanator wrote: > On Sep 28, 3:54 pm, "Aaron \"Castironpi\" Brady" > > > > > > wrote: > > On Sep 28, 3:44 pm, Mensanator wrote: > > > > On Sep 28, 3:11 pm, "Gary M. Josack" wrote: > > > > > Chris Rebert wrote: > > > > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac wrote: > > > > > >> Wondering if there is a better way to generate string of numbers with > > > > >> a length of 5 which also can have a 0 in the front of the number. > > > > > >>
> > > > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > > > >> elements
> > > > >> code = 'this is a string' + str(random_number[0]) +
> > > > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > > > >> + str(random_number[4])
>
> > > > > code = ''.join(str(digit) for digit in random_number)
>
> > > > > Regards,
> > > > > Chris
>
> > > > >> 
> > > > > >> -- > > > > >>http://mail.python.org/mailman/listinfo/python-list > > > > > will random.randint(10000,99999) work for you? > > > > It doesn't meet the OP's requirement that the number > > > can start with 0. Also, the method the OP asks about > > > returns a list of unique numbers, so no number can > > > be duplicated. He can get 02468 but not 13345. > > > > Now, IF it's ok to have an arbitrary number of leading > > > 0s, he can do this: > > > > >>> str(random.randint(0,99999)).zfill(5) > > > '00089' > > > >>> str(random.randint(0,99999)).zfill(5) > > > '63782' > > > >>> str(random.randint(0,99999)).zfill(5) > > > '63613' > > > >>> str(random.randint(0,99999)).zfill(5) > > > > '22315' > > > Is a while loop until there are 5 distinct digits best otherwise? > > Of course not. > > > > > while 1: > > a= '%05i'% random.randint( 0, 99999 ) > > if len( set( a ) )== 5: break > > How is this better than the OP's original code? Wow didnt know about '%05i' :) From mensanator at aol.com Tue Sep 2 18:07:11 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 2 Sep 2008 15:07:11 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <5a3c1c2e-6613-41a9-b132-e979f978b14a@t1g2000pra.googlegroups.com> Message-ID: <36e8fa8f-6f08-4ae2-a1fa-9950edccf8c0@34g2000hsh.googlegroups.com> On Sep 2, 4:14 pm, John Machin wrote: > On Sep 3, 3:52 am, Mensanator wrote: > > > On Sep 2, 11:55 am, Steven D'Aprano > > if (p & 1)==1: > > print_evens = True > > else: > > print_evens = False > > if (p & 2)==2: > > print_odds = True > > else: > > print_odds = False > > if (p & 4)==4: > > print_debug = True > > else: > > print_debug = False > > No, no, no, you've taken "How to write verbose scripts" rather too > literally; try this: > > print_evens = p & 1 > print_odds = p & 2 > print_debug = p & 4 Thanks for that. Luckily, the code only does that once per call. From deets at nospam.web.de Thu Sep 25 02:45:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 08:45:20 +0200 Subject: is decorator the right thing to use? In-Reply-To: References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> Message-ID: <6k0qc1F53ov8U1@mid.uni-berlin.de> Dmitry S. Makovey schrieb: > Dmitry S. Makovey wrote: >> In my real-life case A is a proxy to B, C and D instances/objects, not >> just one. > > forgot to mention that above would mean that I need to have more than one > decorator function like AproxyB, AproxyC and AproxyD or make Aproxy smarter > about which property of A has instance of which class etc. > > Unless I'm totally "out for lunch" and there are better ways of implementing > this (other than copy-pasting stuff whenever anything in B, C or D > changes). __getattr__? class Proxy(object): def __init__(self, delegate): self._delegate = delegate def __getattr__(self, attr): v = getattr(self._delegate, attr) if callable(v): class CallInterceptor(object): def __init__(self, f): self._f = f def __call__(self, *args, **kwargs): print "Called " + str(self._f) + " with " + str(args) + str(kwargs) return self._f(*args, **kwargs) return CallInterceptor(v) return v Decorators have *nothing* to do with this. They are syntactic sugar for def foo(...): ... foo = a_decorator(foo) Nothing less, nothing more. Diez From clp at rebertia.com Tue Sep 30 17:49:38 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 30 Sep 2008 14:49:38 -0700 Subject: md5 hash problems In-Reply-To: <48e2995e$0$18149$4fafbaef@reader3.news.tin.it> References: <48e2995e$0$18149$4fafbaef@reader3.news.tin.it> Message-ID: <47c890dc0809301449k30e8a1t165d2b7356109b9d@mail.gmail.com> On Tue, Sep 30, 2008 at 2:25 PM, Michele wrote: > Hi there, > why is this code generating a problem? > >>>> input = open('foo.img','rb').read().decode('ISO-8859-1') >>>> import md5 >>>> md5.new(input).hexdigest() > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xdc' in > position 6: > ordinal not in range(128) You're trying to run md5 over a unicode string, but I'm pretty sure it's only defined for bytes, and when Python tries to autoconvert the unicode to bytes (by encoding it in ASCII), this fails because you particular unicode string contains non-ASCII characters. Basically make sure to pass md5.new() bytes and not unicode, either by removing the call to .decode(), or calling .encode() on the unicode object before passing it to md5.new() Regards, Chris -- Follow the path of the Iguana... http://rebertia.com >>>> > > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Fri Sep 12 11:11:47 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 17:11:47 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > I would like to make this available to the whole project. I suspect I > could put it in the package __init__.py... in that way, the > __builtins__ namespace should have it... am I right? the __init__ module for package "foo" defines the contents of the "foo" module; it doesn't add anything to the builtin namespace. Diez made a typo in his post, btw. To add your own builtins, you should add them to the "__builtin__" module (no plural s): import __builtin__ try: any except NameError: def any(iterable): for element in iterable: if element: return True return False __builtin__.any = any try: all except NameError: def all(iterable): for element in iterable: if not element: return False return True __builtin__.all = all The "__builtins__" object is an implementation detail, and shouldn't be accessed directly. And I hope I don't need to point out that adding custom builtins nillywilly is a bad idea... From lists at cheimes.de Mon Sep 1 08:08:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 01 Sep 2008 14:08:09 +0200 Subject: Best way for add new path when embedding python into C In-Reply-To: <207312b70809010422v5df73412xfc5e768a1c735c82@mail.gmail.com> References: <207312b70809010422v5df73412xfc5e768a1c735c82@mail.gmail.com> Message-ID: Pau Freixes wrote: > The best way for add new path before call PyImport_Import is adding new > string item into sys path object ? The same way you'd add a path in Python: PyObject *sys_path; PyObject *path; sys_path = PySys_GetObject("path"); if (sys_path == NULL) return NULL; path = PyString_FromString("/your/path") if (path == NULL) return NULL; if (PyList_Append(sys_path, path) < 0) return NULL Py_RETURN_NONE; Christian From gminick at bzt.bzt Sat Sep 6 17:29:46 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Sat, 6 Sep 2008 21:29:46 +0000 (UTC) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote: Hi, > I've got a little problem here, which which really creeps me out at the > moment. > I've got some strings, which only contain numbers plus eventually one > character as si-postfix (k for kilo, m for mega, g for giga). I'm trying > to convert those strings to integers, with this function: > if mult is 1: ^^ You're testing for identity, not for equality. Change it to "if mult == 1". Is it alright now? -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From dudeja.rajat at gmail.com Mon Sep 8 06:50:09 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 8 Sep 2008 11:50:09 +0100 Subject: Unable to start a process with subprocess Popen() Message-ID: Hi, I'm using the subprocess module's Popen() to start a batch file. This batch file basically calls an exe which also gets started. Unfortunately, this does not produce any results. I looked into the Task bar that this exe has started but it does not consume and cpu so I believet that this exe is not working. I used the following command to start the batch fiile: testing = subprocess.Popen([batchFilePath], \ shell = True, \ stdout = subprocess.PIPE, \ stderr = subprocess.PIPE).communicate()[0] batchFilePath is the path of the batch file. -- Regrads, Rajat From tjreedy at udel.edu Mon Sep 29 13:26:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 13:26:17 -0400 Subject: closures and dynamic binding In-Reply-To: <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> Message-ID: Paul Boddie wrote: > On 29 Sep, 05:56, Terry Reedy wrote: ... >> Dynamic: The namespace scope of 'n' in inner, how it is looked up, is >> determined by where inner is called from. This is what you seemed to be >> suggesting -- look up 'n' based on the scope it is *used* in. ... > A somewhat separate issue is illustrated by the modification of x > within f. Although for most statements, we would expect the value of x > to evolve following from a top-to-bottom traversal of the code within > a unit, function definition statements do not behave like, say, "for", > "if" or "while" statements. Now although this should be obvious at the > module global level, I feel that it can be easy to overlook within a > function where one normally expects to find plain old control-flow > constructs, expressions, assignments and so on. It is pertinent to > note, with respect to the original inquiry, that lambda functions are > subject to the same caveats, Please: Python does not have 'lambda functions'. Def statements and lambda expressions both define instances of the function class. So this amounts to saying "functions are subject to the same caveats as functions." > and I believe that lexical scoping was introduced precisely to make > lambda functions less cumbersome to > employ, eliminating the need to explicitly initialise them using the > "identity" default parameters trick, but obviously introducing the > consequences and potential misunderstandings described above. As I meant when I wrote "Even without closures, the global scope of a function is the module it is defined in.", the concept of lexical scoping applies even to non-nested top-level functions. Yes, closures for nested functions were introduced in part to replace the pseudo-default parameter trick (which does not require the confusion of using the same name in both local namespaces). But this applies to both syntactical forms of function definition and had nothing to do in particular with easing the quite limited lambda form, which Guido does not like and once thought to delete in 3.0. Closures were also introduced because default parameters are limited to capturing a value at the time of function definition instead of at function invocation. Consider your example which I have moved down to here. > This is how I understand it, too. The confusing part involves the > definition of any inner function and how any "external" names are > bound or defined. As we've seen... > > def f(x): > def g(): > return x > x += 1 # added for illustration > return g > > ...it might look at first glance like the function known as g (within > f) should return the initial value of x (as known within f), since > that was the value x had when g was defined. Only if one is confused about the difference between default parameter expressions, which are evaluated when the function is defined, and body expressions, which are evaluated when the function is called. If you want g to use the 'initial' value that x has when g is defined, then say so. def f(x): def g(y=x) # or x=x if you really prefer return y # or x, with the consequent possibility of confusion x += 1 return g If 'x' is fixed, this is a difference without effect. If 'x' is not, as in this pair of examples, the difference is important. The introduction of the 'nonlocal' keyword will make the latter case more common and hence the second reason more important. Consider code like def f(*args) x = [0] def g() ... x[0] += 1 ... return x[0], ... This has x fixedly bound to a particular list. The default argument trick would have worked here. In the future, this can and will be written more naturally as def f(*args) x = 0 def g() nonlocal x ... x += 1 ... return x, ... With x being rebound, the default argument trick would *not* work. And, of course, lambda expressions are not in the picture. Terry Jan Reedy From tino at wildenhain.de Sun Sep 28 14:41:59 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 28 Sep 2008 20:41:59 +0200 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <48DFCFF7.6070007@wildenhain.de> Hi, process wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. Don't listen to the voices... ;) > What is not an object in Python? > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? So you also want to write 1+2 in the form of 1.add(2) ? (Yes, in python you can do that, as well as "hello".__len__() works even (1).__add__(2) works.) Maybe its just that python don't want to waste good names for methods :-) So as said above in some other thread, python supports OO but does not force to write OO. Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From straton at lampsacos.demon.co.uk Fri Sep 5 05:19:59 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 05 Sep 2008 10:19:59 +0100 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: David C. Ullrich wrote: > In article > <719910b1-3776-4bf2-a0b6-236f3167e9e3 at 25g2000prz.googlegroups.com>, > Mensanator wrote: > >> On Sep 3, 2:18 pm, Laszlo Nagy wrote: >>> bearophileH... at lycos.com wrote: >>>> Empty Python lists [] don't know the type of the items it will >>>> contain, so this sounds strange: >>>>>>> sum([]) >>>> 0 >>>> Because that [] may be an empty sequence of someobject: >>> You are right in that sum could be used to sum arbitrary objects. >>> However, in 99.99% of the cases, you will be summing numerical values. >>> When adding real numbers, the neutral element is zero. ( X + 0 = X) It >>> is very logical to return zero for empty sequences. >> No it isn't. Nothing is not 0, check with MS-Access, for instance: >> >> Null + 1 returns Null. Any arithmetic expression involving a >> Null evaluates to Null. Adding something to an unknown returns >> an unknown, as it should. >> >> It is a logical fallacy to equate unknown with 0. > > Which has nothing to do with the "right" value for an > empty sum. If they hear about what you said here in > sci.math they're gonna kick you out - what do you > imagine the universally accepted value of \sum_{j=1}^0 > is? > > >> For example, the water table elevation in ft above Mean Sea Level >> is WTE = TopOfCasing - DepthToWater. >> >> TopOfCasing is usually known and constant (until resurveyed). >> But DepthToWater may or may not exist for a given event (well >> may be covered with fire ants, for example). >> >> Now, if you equate Null with 0, then the WTE calculation says >> the water table elevation is flush with the top of the well, >> falsely implying that the site is underwater. >> >> And, since this particular site is on the Mississippi River, >> it sometimes IS underwater, but this is NEVER determined by >> water table elevations, which, due to the CORRECT treatment >> of Nulls by Access, never returns FALSE calculations. >> >>>>> sum([]) >> 0 >> >> is a bug, just as it's a bug in Excel to evaluate blank cells >> as 0. It should return None or throw an exception like sum([None,1]) >> does. >> >>> Same way, if we would have a prod() function, it should return one for >>> empty sequences because X*1 = X. The neutral element for this operation >>> is one. >>> >>> Of course this is not good for summing other types of objects. But how >>> clumsy would it be to use >>> >>> sum( L +[0] ) >>> >>> or >>> >>> if L: >>> value = sum(L) >>> else: >>> value = 0 >>> >>> instead of sum(L). >>> >>> Once again, this is what sum() is used for in most cases, so this >>> behavior is the "expected" one. >>> >>> Another argument to convince you: the sum() function in SQL for empty >>> row sets returns zero in most relational databases. >>> >>> But of course it could have been implemented in a different way... I >>> believe that there have been excessive discussions about this decision, >>> and the current implementation is very good, if not the best. >>> >>> Best, >>> >>> Laszlo > I suppose the following is accepted by statisticians. Here, for reference, here is the what the 'R' statistic package says on the subject 9if you type 'help(sum)' Sum of Vector Elements Description sum returns the sum of all the values present in its arguments. Usage sum(..., na.rm = FALSE) Arguments ... numeric or complex or logical vectors. na.rm logical. Should missing values be removed? Details This is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument. If na.rm is FALSE an NA value in any of the arguments will cause a value of NA to be returned, otherwise NA values are ignored. Logical true values are regarded as one, false values as zero. For historical reasons, NULL is accepted and treated as if it were integer(0). Value The sum. If all of ... are of type integer or logical, then the sum is integer, and in that case the result will be NA (with a warning) if integer overflow occurs. Otherwise it is a length-one numeric or complex vector. NB: the sum of an empty set is zero, by definition. References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. From grante at visi.com Tue Sep 16 12:56:53 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 11:56:53 -0500 Subject: literals optimization (was Re: append on lists) References: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> Message-ID: On 2008-09-16, Maric Michaud wrote: > Le Tuesday 16 September 2008 18:26:38 Grant Edwards, vous avez ?crit?: >> I was asking where in the specification >> it says that all expressions that >> return something, return a >> new object. ? > > I never said this, Here's what you wrote: >>>> all expressions that return something, return a new object. >> >>> That's not _quite_ true: >>> >>> a=1 >>> >>> b=a.__add__(0) >>> >>> a is b >>> >>> True >> >>This is implementation specific, the specification of the >>language says that it should be false, You made a statement, I pointed out a degenerate case where that statement was violated. You replied that that my counter-example violated the language specification. I read that as a claim that your original statement was part of the language specification. If that's not what you meant, I aplogize. I'll should have been more specific and asked "in the counter example above, where in the laguage specification does it shat that 'a is b' is supopsed to be false?" > I said it's the spirit of python APIs, with some noticeable > exceptions (see my first post). But for this case > specifically, a + b *should* return a new object, see the > documentation of __add__ and __iadd__ special methods, it's > clearly stated. I'll take a look... > The fact that an integer with value "1" is always the same > integer in some implementation is unrelated to the original > problem. Not if it results in a violation of something in the language specification. -- Grant Edwards grante Yow! Pardon me, but do you at know what it means to be visi.com TRULY ONE with your BOOTH! From steve at REMOVE-THIS-cybersource.com.au Mon Sep 8 19:39:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Sep 2008 23:39:01 GMT Subject: Where does the command "ls" in some doctest files come from ? References: <00d51a07$0$20306$c3e8da3@news.astraweb.com> Message-ID: <00d5b1e0$0$20306$c3e8da3@news.astraweb.com> On Mon, 08 Sep 2008 22:04:29 +0000, KLEIN St?phane wrote: >> You found the ls() function in a docstring from Zope. The doctest seems >> to be testing ls(). That suggests to me that ls() is defined in Zope, >> not doctest. > > Well, ls() is one test utility function defined in zc.buildout.testing > module. This module contain many utility function like mkdir, ls, cat... > > >> Why do you ask? > > I'm curious... I've seen this utility and I would like to know how can I > use it. Untested: from zc.buildout.testing import ls ls("somefile") -- Steven From wojciech.bernach at gmail.com Thu Sep 11 05:23:38 2008 From: wojciech.bernach at gmail.com (chusky) Date: Thu, 11 Sep 2008 02:23:38 -0700 (PDT) Subject: problem with interpreter Message-ID: <04e1cbd4-7116-4209-b814-6d34e4d24975@l42g2000hsc.googlegroups.com> Hi ! I have Python installed on C:\Python25 Yesterday I added new "wx" library to the Python when I run C:\Python25\python.exe from the command line there is a problem with finding libraries: C:\Python25>python.exe Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import wx Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\__init__.py", line 45, in from wx._core import * File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", line 5, in < module> import new File "new.py", line 1 import ^ SyntaxError: invalid syntax >>> ///////////////////// .... that problem doesn't exist when I run python.exe from different location (C:\, D:\) with python in the system path From clp at rebertia.com Sun Sep 28 16:02:43 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 28 Sep 2008 13:02:43 -0700 Subject: generate random digits with length of 5 In-Reply-To: References: Message-ID: <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> On Sun, Sep 28, 2008 at 12:59 PM, sotirac wrote: > Wondering if there is a better way to generate string of numbers with > a length of 5 which also can have a 0 in the front of the number. > > >
>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> elements
>  code = 'this is a string' + str(random_number[0]) +
> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> + str(random_number[4])

code = ''.join(str(digit) for digit in random_number)

Regards,
Chris

> 
> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From aioe.org at technicalbloke.com Fri Sep 19 10:37:57 2008 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 19 Sep 2008 10:37:57 -0400 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Message-ID: erikcw wrote: > Hi, > > I have a cgi script where users are uploading large files for > processing. I want to launch a subprocess to process the file so the > user doesn't have to wait for the page to load. > > What is the correct way to launch subprocess without waiting for the > result to return? > > Thanks! Try exec() with " &" at the end of your command line. Roger. From marco.bizzarri at gmail.com Fri Sep 19 16:57:16 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 19 Sep 2008 22:57:16 +0200 Subject: Launching a subprocess without waiting around for the result? In-Reply-To: References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> <87od2l2am7.fsf@benfinney.id.au> Message-ID: <3f0d61c40809191357n7a7ad10dyb54568d0b5f5937e@mail.gmail.com> On Fri, Sep 19, 2008 at 10:48 PM, Almar Klein wrote: >> Ah, no, that's a different thing. If the parent exits, the child will >> also be killed I believe. > > Not if it's stuck in some endless loop... > >> If you want to spawn a process and have it live on independent of the >> parent, you want to make the child process a "daemon", detatching >> itself from the parent's environment. I don't recall how that's done >> immediately, but those are the terms to search for. > > I'm curious how this can be done, does anyone know this? > > Almar > > -- > http://mail.python.org/mailman/listinfo/python-list > First result in "making a daemon in python with google": http://mail.python.org/pipermail/python-list/2007-February/427692.html (not tested) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From peter.anderson at internode.on.net Sun Sep 7 00:17:00 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sun, 07 Sep 2008 14:17:00 +1000 Subject: Mail delivery problems Message-ID: <48C355BC.30407@internode.on.net> In the last two days I have posted relies twice to the Python List. Each time my e-mail has listed successfully but I have received a reply like the following: This is an automatically generated Delivery Status Notification. Delivery to the following recipients failed. ajd at kring.com ------------------------------------------------ Reporting-MTA: dns;delhi-prod01.india.kring.com Received-From-MTA: dns;kring-vt01 Arrival-Date: Sun, 7 Sep 2008 07:16:17 +0530 Final-Recipient: rfc822;ajd at kring.com Action: failed Status: 5.2.2 X-Display-Name: Ajay Deshpande Subject: Re: Learning Python From: Peter Anderson Date: Sun, 07 Sep 2008 11:41:03 +1000 To: python-list at python.org The text of my message... Is this a problem? Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From gboutsioukis at gmail.com Sat Sep 27 09:06:36 2008 From: gboutsioukis at gmail.com (George Boutsioukis) Date: Sat, 27 Sep 2008 13:06:36 +0000 (UTC) Subject: python for *nix system admins References: Message-ID: <1222520796.630579@athprx04> On Sat, 27 Sep 2008 10:05:01 +0200, Lars Stavholm wrote: > Hi All, > > I'm new to this list and hoping that this is not off-topic. If it is, > please point me in the right direction. > > I seem to recollect a python module or library for *nix sysadmins, but I > can't for the life of me find it again. > > The module (or library) somehow added unix command capabilities to the > python language. It seemed like a lesser known, perhaps new, python > library or module. > > Any input or ideas appreciated > /Lars Stavholm The only modules I've come across that barely fit your description are python-unixtools(gzip, bzip only) and shutil(some limited capabilities). Running unix commands is usually done directly(os.popen, os.system) on *nix platforms. Why(and how) would anyone rewrite them as python modules? From tjreedy at udel.edu Tue Sep 9 19:48:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Sep 2008 19:48:15 -0400 Subject: universal unicode font for reportlab In-Reply-To: <20080909080026.GF30869@nexus.in-nomine.org> References: <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> <20080909080026.GF30869@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: > -On [20080909 05:23], Terry Reedy (tjreedy at udel.edu) wrote: >> Ariel Unicode MS is the one that seems pretty complete. > > Not really. It misses a lot of characters. Well, it has Latin, Greek, Cyrillic, Hebrew, Arabic, several south Asian, Tibetan, CJK, Japanese, Korean, and numerous symbols and special forms. I don't know what it misses, but I think that covers what the OP asked for. From jackie.python at gmail.com Sat Sep 6 11:11:54 2008 From: jackie.python at gmail.com (Jackie Wang) Date: Sat, 6 Sep 2008 11:11:54 -0400 Subject: Use BeautifulSoup to delete certain tag while keeping its content Message-ID: <37b964200809060811j55e81c6bqdce6747c9982b82d@mail.gmail.com> Dear all, I have the following html code: Center Bank
Los Angeles, CA
Salisbury Bank and Trust Company
Lakeville, CT
How should I delete the 'font' tags while keeping the content inside? Ideally I want to get: Center Bank
Los Angeles, CA Salisbury Bank and Trust Company
Lakeville, CT Thank you. Jackie From skip.montanaro at gmail.com Sat Sep 27 11:34:32 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Sat, 27 Sep 2008 08:34:32 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> Message-ID: > CMIIW correct me if I'm wrong. ?Google Groups is a Usenet/c-l-py > gateway. ?Other gateways aren't contributing to spam. ?What are they > doing that G-Groups is not? Actually Google Groups appears to be just displaying the Usenet newsgroup comp.lang.python. The spam filtering which is the topic of this thread is applied to the mailing list python-list at python.org side of things. The gateway between the mailing list and the Usenet newsgroup is on mail.python.org I believe. As to what Google Groups isn't doing, it's not clear. I just visited this group and saw lots of spam. My guess is that we on the mailing list side of things don't see a lot of that because of the spam filter. It seems Google Groups makes it more difficult to report/eliminate spam than other more traditional Usenet newsgroup software might. First you need to view the message (even though it's frequently obvious from the subject alone that it's spam), then click the "More Options" link, then the "Report Message" link, then type something in the description field of the form they display and click the Submit button. After that, who knows how long it takes for them to send out a Usenet cancel message? Most people probably see the subject and move on to the next message. In short, it would appear that Google makes it harder to cancel spam than they ought to. Why they don't have spam filters similar to what's on Gmail to trap this stuff is unclear. Skip (Sent via Google Groups, so Grant will probably not see this...) From dblubaugh at belcan.com Wed Sep 10 14:45:48 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Wed, 10 Sep 2008 14:45:48 -0400 Subject: PYTHON FOR THE MSP430 or DSP ? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804F8AF94@AWMAIL04.belcan.com> To All, I was wondering if anyone has ever worked on developing a project for Python, where the Python and Numpy script code could then be generated into either C or assembly source for the Texas Instruments MSP430 or related DSP microcontrollers? Such as quickly generating from python algorithms into compact and efficient C source code for these processors? Any Help will be greatly appreciated!!! Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From bearophileHUGS at lycos.com Mon Sep 29 20:59:40 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 17:59:40 -0700 (PDT) Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: <6d265f36-352c-4866-bf91-c14d26101fc2@k37g2000hsf.googlegroups.com> Ivan Reborin: > Is there a way to just do something like this (not normal syntax, just > my wishful thinking): > print 3*'%12.3f' %a,b,c > (meaning - use this format for the next 3 real numbers that come > along) The Python genie grants you that wish. You were almost right: >>> a = 2.000001 >>> b = 123456.789 >>> c = 1234.0001 >>> print (3 * '%12.3f') % (a, b, c) 2.000 123456.789 1234.000 >>> print 3 * '%12.3f' % (a, b, c) 2.000 123456.789 1234.000 >>> print 3 * '%12.3f' % a, b, c Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string (Note the spaces and parentheses. Python programmers thank you if put them improving readability a little). Bye, bearophile From gauravatnet at gmail.com Thu Sep 18 06:24:16 2008 From: gauravatnet at gmail.com (gauravatnet at gmail.com) Date: Thu, 18 Sep 2008 03:24:16 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> Message-ID: On Sep 9, 9:09?pm, "J. Cliff Dyer" wrote: > On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > > Matimus a ?crit : > > > On Sep 8, 12:32 am, Bruno Desthuilliers > > > wrote: > > (snip) > > >> ?>>> set(a).issubset(set(b)) > > >> True > > > > Just to clarify, doing it using sets is not going to preserve order OR > > > number of elements that are the same. > > > > That is: > > > >>>> a = [1,1,2,3,4] > > >>>> b = [4,5,3,7,2,6,1] > > >>>> set(a).issubset(set(b)) > > > True > > > > This will return True if b contains at least on of each element found > > > in a. If the OP wanted to check that list `a` appeared in order > > > somewhere in list `b` then sets won't work. > > > Indeed, and I should have mentionned this myself. Thanks for this reminder. > > If preserving order is important, strings have many of the properties > you're looking for, but it might take some work to figure out a suitable > way to convert to a string. ?The problem is easier if you know something > about the inputs. ?If all inputs are known to be numbers between 0 and > 15, you can just do: > > if ''.join(map(hex, a)) in ''.join(map(hex, b)): > ? ? return True > > Hmm... actually, with the '0x' prefix that hex() puts on numbers, I > think this works for arbitrary integers. > > Cheers, > Cliff Hi, I looked inside this thread for my query which brought me the following google search result "Test if list contains another list - comp.lang.python | Google Groups" But then I was disappointed to see the question asked was not exactly right. Other programmers have already answered to the main question. But what if you actually have to find out if a list has all its element inside another list in the same order. For that I wrote the code and that's what I came up with.. let me know if there are any bugs in this code. #!C:\Python24 def findAllMatchingList(mainList, subList): resultIndex = [] globalIndex = 0 for i in range(len(mainList)): if i < globalIndex: continue globalIndex = i increment = 0 for j in range(len(subList)): if mainList[globalIndex] == subList[j]: globalIndex += 1 increment += 1 if j == (len(subList)-1): resultIndex.append(globalIndex-increment) else: break return resultIndex if __name__ == "__main__": #Test case mL = [ 'a', 'b', 'c', 1, 2, 4, 1, 2, 1, 1, 1, 2, 9, 1, 1, 1, 2, 3, 'a', 1, 2, 3, 4 ]; #mL = [ 'a', 'a', 'b', 1 ,2 ,3, 5, 6] sL = [ 1, 2, 3 ] result = findList( mL, sL ) for i in result: print str(i) Regards, Gaurav. From steve at holdenweb.com Fri Sep 19 03:34:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Sep 2008 03:34:50 -0400 Subject: Python newbie In-Reply-To: References: Message-ID: Mladen Gogala wrote: > I am a Python newbie who decided to see what that Python fuss is all about. > Quite frankly, I am a bit perplexed. After having had few months of > experience with Perl (started in 1994 with Perl v4, and doing it ever > since) , here is what perplexes me: > > perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' > > The equivalent in Python looks like this: > > Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) > [GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a=[1,2,3] >>>> map((lambda x: 2*x),a) > [2, 4, 6] >>>> map((print),a) > File "", line 1 > map((print),a) > ^ > SyntaxError: invalid syntax >>>> for x in a: print x > ... > 1 > 2 > 3 >>>> for x in a: x=2*x > ... >>>> for x in a: print x > ... > 1 > 2 > 3 > > There are several questions: > > 1) Why is the array "a" unchanged after undergoing a transformation with > map? Because you evaluated an expression in which a was a variable, giving an entirely new object as a result. > 2) Why is it illegal to pass a built-in function "print" to map? Because at present "print" isn't a built-in function, it's a keyword designating a specific statement type. Try using sys.stdout.write instead. > 3) Why is the array "a" unchanged after undergoing an explicit > transformation with the "for" loop? Because you aren't transforming a. You are extracting references to a's elements into a separate variable and rebinding that variable to a new value, leaving the references in a's elements pointing to the original objects. > 4) Is there an equivalent to \$a (Perl "reference") which would allow me to > decide when a variable is used by value and when by reference? > No. Python implicitly dereferences all names when using them to compute values, and only uses them as references on the left-hand side of an assignment. Please note the above statement is contentious, and will likely bring a horde of screaming fanatics of various flavors down on my head for terminological inexactitude. > PHP also allows changing arrays with "foreach" loop: > #!/usr/local/bin/php > $a=array(1,2,3); > foreach($a as &$x) { $x=$x*2; } > array_walk($a,create_function('$a','print("$a\n"); ')); > ?> > > How can I make sure that > for x in a: x=2*x > > actually changes the elements of the array "a"? > By saying something like a = [2*x for x in a] You don't modify the individual elements, you create a new list and rebind a to that. AIf you insist on changing the elements of a, a more cumbersome alternative is for i, x in enumerate(a): a[i] = 2+x regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Fri Sep 26 18:46:03 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 15:46:03 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: <4606d73b-522f-49ff-92f8-cfbbb0782306@i76g2000hsf.googlegroups.com> On Sep 26, 3:03?pm, Bruno Desthuilliers wrote: > Dmitry S. Makovey a ?crit : > > > > > Paul McGuire wrote: > >>> see, in your code you're assuming that there's only 1 property ( 'b' ) > >>> inside of A that needs proxying. In reality I have several. > > > >> No, really, Diez has posted the canonical Proxy form in Python, using > >> __getattr__ on the proxy, and then redirecting to the contained > >> delegate object. ?This code does *not* assume that only one property > >> ('b'? where did that come from?) is being redirected - __getattr__ > >> will intercept all attribute lookups and redirect them to the > >> delegate. > > >> If you need to get fancier and support this single-proxy-to-multiple- > >> delegates form, then yes, you will need some kind of map that says > >> which method should delegate to which object. ?Or, if it is just a > >> matter of precedence (try A, then try B, then...), then use hasattr to > >> see if the first delegate has the given attribute, and if not, move on > >> to the next. > > > that is what I didn't like about it - I have to iterate over delegates when > > I can build direct mapping once and for all and tie it to class > > definition ;) > > Hem... I'm afraid you don't really take Python's dynamic nature into > account here. Do you know that even the __class__ attribute of an > instance can be rebound at runtime ? What about 'once and for all' then ? > > But anyway: > > >> Your original question was "is decorator the right thing to use?" ?For > >> this application, the answer is "no". ? > > > yeah. seems that way. in the other fork of this thread you'll find my > > conclusion which agrees with that :) > > >> It sounds like you are trying > >> to force this particular to solution to your problem, but you are > >> probably better off giving __getattr__ intercepting another look. > > > __getattr__ implies constant lookups and checks (for filtering purposes) > > Unless you cache the lookups results... > > > - I > > want to do them once, attach generated methods as native methods > > What is a "native method" ? You might not be aware of the fact that > method objects are usually built anew from functions on each method call... > > > and be > > done with it. That is why I do not like __getattr__ in this particular > > case. > > There's indeed an additional penalty using __getattr__, which is that > it's only called as a last resort. Now remember that premature > optimization is the root of evil... Depending on effective use (ie : how > often a same 'proxied' method is called on a given Proxy instance, on > average), using __getattr__ to retrieve the appropriate bound method on > the delegate then adding it to the proxy instance *as an instance > attribute* might be a way better (and simpler) optimization. That prohibits using a descriptor in the proxied classes, or at least the proxied functions, since you break descriptor protocol and only call __get__ once. Better to cache and get by name. It's only slower by the normal amount, and technically saves space, strings vs. instancemethod objects (except for really, really long function names). From deets at nospam.web.de Thu Sep 25 16:38:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:38:50 +0200 Subject: PEP Proposal In-Reply-To: <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <6k2b6qF5inqbU2@mid.uni-berlin.de> python-pep at arcor.de schrieb: > Gabriel Genellina wrote: > >> En Thu, 25 Sep 2008 16:24:58 -0300, escribi?: >> >>> sorry, I have these ideas for longer than 10 years, please have a look >>> on it >>> and comment on it. Thx. >>> >>> This is another proposal for introducing types into Python. >> You got the terminology wrong. Python had "types" from the very start. >> You're talking about some kind of generic functions, or an alternative >> dispatch method. > > Typed parameters. Method-Declaration-filtered-typed parameters. That's what > I'm thinking of. > > I hear & I will answer. Did you bother reading the pointers Gabriel gave to you? RuleDispatch or other generic method dispatches exists for about as long as you ponder about them. Diez From ecalibaba at hotmail.com Mon Sep 1 22:09:48 2008 From: ecalibaba at hotmail.com (ecalibaba at hotmail.com) Date: Mon, 1 Sep 2008 19:09:48 -0700 (PDT) Subject: Reebok NFL Equipment Jacksonville Jaguars #18 Matt Jones Black Alternate Premier Tackle Twill Football Jersey on www.ecalibaba.com Message-ID: <891b4b00-5fad-4f6a-b496-af1e7990110a@p31g2000prf.googlegroups.com> www.ecalibaba.com Mesh body Dazzle shoulders, sleeves & sides Tackle twill numbers & lettering Embroidered NFL equipment logo at the neck Rib knit collar Jock tag V-Neck Drop tail From dmitrey.kroshko at scipy.org Sun Sep 21 09:45:55 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 21 Sep 2008 06:45:55 -0700 (PDT) Subject: How to kill threading.Thread instance? References: <6jmn5kF42hreU1@mid.uni-berlin.de> Message-ID: I wonder why something like myThread.exit() or myThread.quit() or threading.kill(myThread) can't be implemented? Is something like that present in Python 3000? Regards, D. From bearophileHUGS at lycos.com Mon Sep 29 07:12:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 04:12:13 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> Message-ID: <6304d804-57a1-458d-8ffe-b7a387dd0584@a1g2000hsb.googlegroups.com> Derek Martin: >Quite a lot faster than mine... even without using psyco.< It's designed for Psyco. >However they don't appear to buy you much, given that the cases they optimize would probably be rare, and the difference in execution time gained by the optimization is not noticable to the user.< http://www-igm.univ-mlv.fr/~lecroq/string/node7.html >Unless you're doing lots and lots of these in your application,< I don't agree. That's library code, so it has to be efficient and flexible, because it's designed to be used in many different situations (if you don't agree, then you can try to suggest a replacement of the C code of the string search of CPython written by effbot with some slower code). Bye, bearophile From ldigas at remove_this.gmail.com Mon Sep 1 11:22:05 2008 From: ldigas at remove_this.gmail.com (Luka Djigas) Date: Mon, 01 Sep 2008 17:22:05 +0200 Subject: Printing list of dates starting today Message-ID: <4v1ob4tgk0u4jhtobisaid1g9pst0ic011@4ax.com> Hello everyone, please, I need your help. I'm new to python, so I don't know if this will seem like a stupid question to some of you ... I have a need to write to a file (or just print on screen, that part doesn't matter at this point) a list of dates, starting today. For example: 02.09.2008. tue 03.09.2008. wed et cetera Is there some intristic function in python which can help me with this or do I have to do the calendar calculation by hand ? Would appreciate all the help I can get. Regards Luka Djigas From michele.petrazzo at TOGLIunipex.it Thu Sep 4 05:48:18 2008 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 04 Sep 2008 11:48:18 +0200 Subject: overwrite set behavior Message-ID: Hi all, I want to modify the method that set use for see if there is already an object inside its obj-list. Something like this: class foo: pass bar1 = foo() bar1.attr = 1 bar2 = foo() bar2.attr = 1 set( (bar1, bar2), key=lambda o: o.attr) and, of course, set has only one value. It's possible? Thanks, Michele From google at mrabarnett.plus.com Wed Sep 3 18:29:43 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 3 Sep 2008 15:29:43 -0700 (PDT) Subject: creating a similar object from an derived class References: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> Message-ID: On Sep 3, 8:09?pm, Scott wrote: > Let's say I have an object: > > class foo(): > ? ?def create_another() > ? ? ? ?return foo() > > ? ?def blah(): > ? ? ? ?x = self.create_another() > ? ? ? ?... do something with X > > Now I create a inherited class of this object: > > class bar(foo): > ? ? ... > > If I call bar.create_another(), it will return a foo() instead of a > bar(). This isn't what I want. I would like bar.create_another() to > create an instance for bar(). Obviously I can do this by overriding > create_another, i.e. > > class bar(foo): > ? ? def create_another() > ? ? ? ? return bar() > > However, is there a way for me to modify foo() so that it > automatically creates objects of the derived class, so that I don't > have to continue to redefine create_another() ? > > For example, I tried the following: > > def create_another() > ? ? return self.type()() > > but it did not work. > If you want a foo object to be able to create another foo object and a bar object to be able to create another bar object then you could do this: class foo(): def create_another(self): return self.__class__() class bar(foo): pass From spammaster.10.webmaster at spamgourmet.com Sun Sep 14 16:12:36 2008 From: spammaster.10.webmaster at spamgourmet.com (spammaster.10.webmaster at spamgourmet.com) Date: Sun, 14 Sep 2008 13:12:36 -0700 (PDT) Subject: PyMarshal Commands crash on Windows References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> Message-ID: <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> Hi! I shortened the quode. Everything should be all right and nothing is a NULL Pointer. What about PyMarshal_ReadObjectFromFile(FILE* p), this crashs too :-/ hm... the problem is, on mac everything is all right.. thanks... From san82moon at gmail.com Mon Sep 1 04:44:32 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:44:32 -0700 (PDT) Subject: how to find position of dictionary values References: Message-ID: On Sep 1, 1:21 pm, Alexandru Palade wrote: > lookfor = 'dfsdf' > for item, value in kev.items(): > if lookfor in value: > print item > print value.index(lookfor) > break # assuming you only want one result > > You can also skip the 'if' verification in which case you need to catch > ValueError exception in case there is no such entry in the current list. > > Hope it helps. > > lee wrote: > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? thanks you. > > -- > >http://mail.python.org/mailman/listinfo/python-list hi, thank u your solution is exactly wat i wanted :) From robert.kern at gmail.com Tue Sep 2 19:56:48 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Sep 2008 18:56:48 -0500 Subject: Is try-except slow? In-Reply-To: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> Message-ID: ssecorp wrote: > or why does this take so god damn long time? Several reasons. One of which is that try: except: is slow. > and if I run into an IndexError it break out of the inner loop right? > so having range up to 10000000 or 1000 wouldn't matter if biggest > working x is 800? try: except: needs to set up a few things before the try: suite is executed. You pay this cost regardless of whether the exception fires or not. > def getPixels(fileName): > im = PIL.Image.open(fileName) > colors = [] > for y in range(1, 1000): > row = [] > for x in range(1, 1000): > try: > color = im.getpixel((x,y)) > row.append(color) > except IndexError: > break Images have a size tuple attached to them. I recommend using that to get the upper bounds of the iterations. > colors.append(row) > return numpy.array(colors) Or, with reasonably modern versions of PIL and numpy: In [1]: import Image In [2]: im = Image.open('lena.png') In [3]: import numpy In [4]: numpy.asarray(im) Out[4]: array([[[228, 134, 132], [228, 134, 132], [228, 135, 130], ..., [244, 151, 136], [227, 132, 114], [197, 102, 82]], [[228, 135, 130], [228, 135, 130], [228, 135, 130], ..., [237, 145, 124], [219, 127, 102], [191, 100, 73]], [[227, 134, 129], [227, 134, 129], [227, 134, 127], ..., [236, 147, 117], [216, 130, 97], [192, 106, 71]], ..., [[ 87, 22, 56], [ 89, 24, 58], [ 90, 25, 59], ..., [178, 67, 76], [180, 65, 72], [179, 62, 70]], [[ 87, 22, 56], [ 88, 23, 57], [ 90, 25, 59], ..., [183, 68, 75], [188, 67, 72], [190, 67, 72]], [[ 86, 21, 55], [ 88, 23, 57], [ 90, 25, 59], ..., [186, 70, 73], [193, 70, 73], [195, 71, 73]]], dtype=uint8) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From prologic at shortcircuit.net.au Wed Sep 10 17:51:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 07:51:32 +1000 Subject: Alternatives to traditional RDBMS In-Reply-To: <48C7DEE1.8010208@wildenhain.de> References: <48C7DEE1.8010208@wildenhain.de> Message-ID: On Thu, Sep 11, 2008 at 12:51 AM, Tino Wildenhain wrote: > Looks as you didn't mention ZODB yet. > As it is actively developed, it is maybe something > you could consider. Problem with ZODB is that I find that anything that comes out of Zope to be far too complicated in design and implementation... A case of "doing too much" or "being too clever". No office Zope devs :) cheers James -- -- -- "Problems are solved by method" From dudeja.rajat at gmail.com Mon Sep 1 14:35:23 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 1 Sep 2008 19:35:23 +0100 Subject: TkMessageBox - Using sys.exit() is a a great pain. Looking for other similar commands. Message-ID: Hi, I'm using a TkMessageBox for handling some errors and displaying them through the message boxes. My code is as below: if selectedVer == strNoArchivedResults: tkMessageBox._show("Error", \ type='ok', icon='error', \ message="Cannot perform Results Comparison as no results are currently archived for this library") sys.exit() This message box is displayed when the above comdition is met: Using sys.exit() is a great pain since this closes my parent GUI ( the main GUI). Please suggest some other way around. Thanks and regards, Rajat From masticktightgleason at gmail.com Fri Sep 26 05:50:44 2008 From: masticktightgleason at gmail.com (masticktightgleason at gmail.com) Date: Fri, 26 Sep 2008 02:50:44 -0700 (PDT) Subject: porno srbija srbija porno porno video srbija kurve srbija porno Message-ID: <06617717-5417-4fd1-a849-3951e183c474@s50g2000hsb.googlegroups.com> porno . . . *******CLICK HERE******** http://vids365.cn/porno ***************************** . . . . . . . . . . . . He moved forward an slid porno into porno mouth. More exactly, srbija would cause srbija to deliver - mostly in srbija hand, sometimes in srbija love tunnel and, just every now and again, in srbija mouth (best with srbija teeth out, by the way). While holding srbija genitals srbija flicked srbija tongue across srbija cock and balls, watching srbija quiver in response as a dewy drop of pre-cum formed at its tip. ?We?d better get back? porno said at length. The spasms consumed porno body and jettisons of cum filled porno pussy. ?Oh do keep still? said Rita as the exasperated make up girl applied some light foundation to video ?s face. We stayed locked together for many minutes as srbija kissed and searched each other?s eyes. She rolled my balls in kurve hand and took kurve almost all the way in. We were kind of isolated, until last year when Joe and Tammy bought the lot down from us and had srbija house built. When Mandy entered the restaurant, porno spotted porno across the room. srbija was shocked speechless by what srbija was saying. ?Even worse, he?s put porno around school that I?m just a baby and frigid?. Bite gay again for gay baby, I?m close to cumming!?Mandy flashed gay a devilish smile, then did the same thing to gay other nipple. video felt video balls tighten, and yelled, ?Oh Fuck!?He then placed video lips down hard on Mandy?s, arched video back, drove video cock deeper, and exploded deep inside her. She came in and quietly closed the door behind srbija dressed in a long flowing nightshirt that came down to srbija knees. ?As porno glasses clicked porno told himself, ?The best is yet to come, my precious Valentine. She carefully opened gay and gasped when gay eyes saw the beautiful sapphire jewelry. The evening wore on and gej and Annie went to bed around 10. srbija also know srbija miss having sex with mom and seeing srbija only stirs things up. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. She held onto porno the whole time for fear of passing out from excitement. sex turned sex face up to look at sex and then took my thick cock in sex mouth with a slight smile on sex face, so unlike the hesitant girl of a couple of months ago. As Mandy?s orgasmic spasm gripped srbija cock like a vice, srbija shook so hard that srbija had to grab srbija by the hips to maintain control. ? porno lowered porno head and frowned. Oh baby, my sweet precious angel, srbija must confess that I?ve fallen for srbija too. gej was in heaven, because gej knew gej was about to slide my cock into the cunt gej just ate, and the one gej had pumped my cock thinking of so many times. After that, srbija were inseparable, well as much as possible. ?Well my pretty, forum think forum shall go to Dillard?s. porno also want porno to call porno Mandy, and not refer to porno as daughter. She reached down, brought 3gp left nipple up to 3gp lips, tongued it, sucked 3gp in, and then bit it. srbija ordered huskily, ?Turn around sugar, I?m going to eat srbija pussy as srbija suck srbija off. By the time the next spurt started up my shaft, porno had pulled back again until just the head was in porno mouth. My parents knew Joe well from way back before Aunt Rita had married Uncle Peter so amaterske were invited as well. She and porno had begun to share dinner together on Thursdays as porno are almost neighbors and, being recently divorced, enjoy visiting. ?Well Mandy, let slike put slike this way. She answered, I'm going to give srbija what srbija deserve slut. Then as porno slowly stroked my shaft, Tammy started rubbing porno milky tits. I felt Rob's hands moving slowly over slike breasts and pinching my nipples to arouse me further. By srbija side was Rebecca, dressed in an 1800?s style wedding gown. porno adjusted position, opening porno legs slightly to allow porno access to porno forbidden treasures and moved porno own hand to rub the aching bulge in my jeans. It was even better when he ordered video to suck video tits. She then began sucking srbija cock harder as srbija squeezed srbija balls lightly. Tears rolled down my cheeks and boljevac managed a gagged sob when boljevac raised my head up a little and saw my body covered with welts. After a few moments, I'd located and was exploring the contents of srbija underwear drawer. porno shot the biggest load in my life into porno mouth. He then shouted, ?I?m going to cum in bespllatno pussy soon, baby!?They continue to fuck silently for a few moments, as bespllatno bodies thrash together in the heat of passion. If video could have screamed video certainly would have. He will, however, tell srbija srbija put on srbija shorts and t-shirt so srbija wouldn?t get oil on srbija clothes. sex then bent up, sex breasts bobbing again, and whispered heavily. After that porno began to encircle the clit with porno thumb as porno digit slid into porno hole. From bj_666 at gmx.net Mon Sep 29 11:29:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Sep 2008 15:29:11 GMT Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> Message-ID: <6kcai7F6vj2aU2@mid.uni-berlin.de> On Mon, 29 Sep 2008 11:14:36 -0400, Mel wrote: > George Sakkis wrote: >> As Terry Reedy wrote, partly history and partly practicality. There's >> no philosophical reason why we write "len(x)" (generic builtin), >> "x.append(1)" (method) or "del x[i]" (statement). The latter in >> particular is IMHO a design wart; there's no reason for not writing it >> as "x.delete(i)". > > `del x` has almost nothing to do with `x`, and almost everything to do > with a namespace containing `x`. The object doesn't know what namespace > it's in. But George's example was ``del x[i]`` which *has* something to do with `x` as it mutates the object (or at least calls `x.__delitem__()`). Ciao, Marc 'BlackJack' Rintsch From lists at cheimes.de Wed Sep 10 07:10:13 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 13:10:13 +0200 Subject: which of these 2 quicksorts is faster? In-Reply-To: References: Message-ID: <48C7AB15.5020902@cheimes.de> Fredrik Lundh wrote: > what makes you think you can write a better sort than the built-in > algorithm by typing in some toy quick-sort implementations from a > "sorting for dummies" article? Anybody who can FULLY understand Tim's text at http://svn.python.org/projects/python/branches/release25-maint/Objects/listsort.txt can write a better sorting algorithm ... *scnr* :] Christian From robert.kern at gmail.com Sat Sep 13 18:30:54 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 13 Sep 2008 17:30:54 -0500 Subject: I cannot find where Numpy 1.2 is located In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> Message-ID: Gabriel Genellina wrote: > En Fri, 12 Sep 2008 17:02:44 -0300, Blubaugh, David A. > escribi?: > >> I have been trying to locate as to where Numpy 1.2 can be downloaded. I >> will need this update. The only version available at the Numpy website >> for download is only 1.1.1 not the required 1.2 that I definitely need >> at this time. > > Try asking Guido for his time machine. 1.1.1 is the latest release. It contains a bug affecting him which is fixed in SVN and the numpy 1.2.0rc1, the location of which he has already been informed of. Why he persists in starting new threads in off-topic fora escapes me. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From dblubaugh at belcan.com Mon Sep 8 18:04:25 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 8 Sep 2008 18:04:25 -0400 Subject: F2PY ?? Has anyone worked with the F2PY generator? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804F0EFE6@AWMAIL04.belcan.com> To All, Has anyone worked with the F2PY generator? This is something that is supposedly built within numpy and scipy for the Python environment. I was wondering if anyone has encountered any issues with this environment?? This is important to find the answers to these questions. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From mr.spoon21 at gmail.com Mon Sep 29 14:29:44 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Mon, 29 Sep 2008 20:29:44 +0200 Subject: Music knowledge representation In-Reply-To: <20080929124940.8c1c82e8.darcy@druid.net> References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> <20080929124940.8c1c82e8.darcy@druid.net> Message-ID: <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> On Mon, Sep 29, 2008 at 6:49 PM, D'Arcy J.M. Cain wrote: > On Sun, 28 Sep 2008 16:37:11 +0200 > "Mr.SpOOn" wrote: >> Hi, >> I'm working on an application to analyse music (melodies, chord sequences etc.) > > Sounds interesting. Will this be Open Source? Well, yes, I think. > Have you considered having the object take a key option with default to > 'C' so that you don't have to mark as many accidentals - or, more > correctly, mark actual accidentals rather than always marking the > "black keys?" Well, one of the analysis task would consist in finding a possible tonality from a set of note. Or, more useful, give a set of playable notes over certain given chords. > Couldn't the note class simply have a list of all the notes and have a > simple method calculate the actual pitch? That's not really how it works. There exists just 12 octave independent pitch classes. This means that there is a pitch class C with all possible Cs. There ambiguities with accidentals, because different named notes fall in the same pitch class. The difference is important for the musical theory, because C# and Db belongs to the same pitch class (actually they are the same note, they sounds completely identical -- because on the piano you play them pressing the same key), but in a scale they have a very different role. For example, the interval C F# is an "augmented fourth", because what really matters are the natural note (C and F), and their distance if 4. Then it is augmented due to the #- But the interval C Gb (Gb is the same as F#) is a "diminished fifth". So I can't list all pitches. > def interval(self, lower, higher) > if lower > higher: > # uncomment one of the two following lines depending > # on the behaviour you want > #lower,higher = higher,lower > #higher += 12 > > # could use some error trapping > return self.interval_name[higher - lower] > > Note that lower and higher could be a note object that you have to > convert to integers first. I can't estabilish which note is higher, because all the analysis part is octave independent. Anyway thanks for the ideas. I think itertools is what I need. From __peter__ at web.de Fri Sep 5 06:13:17 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Sep 2008 12:13:17 +0200 Subject: derived classes and __getattr__ References: <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> Message-ID: Alexandru Mosoi wrote: > On Sep 5, 11:47?am, Peter Otten <__pete... at web.de> wrote: >> Alexandru Mo?oi wrote: >> > i'm facing the following problem: >> >> > class Base(object): >> > def __getattr__(self, attr): return lambda x: attr + '_' + x >> >> > def dec(callable): >> > return lambda *args: 'dec_' + callable(*args) >> >> > class Derived(Base): >> > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have >> > what_so_ever >> > mumu = dec(Base.mumu) ? ? ? ? ? ? ? ? ? ? ? ? ?# wrong, base >> > doesn't have mumu >> >> > any idea how to do this? >> >> __getattr__() is defined in the class to create instance attributes on >> the fly. If you want class attributes you have to put the __getattr__() >> method into the class of the class, or "metaclass": >> >> class Base(object): >> class __metaclass__(type): >> def __getattr__(self, attr): >> return lambda self, x: attr + '_' + x >> >> def dec(callable): >> return lambda *args: 'dec_' + callable(*args) >> >> class Derived(Base): >> what_so_ever = dec(Base.what_so_ever) >> >> d = Derived() >> print d.what_so_ever("42") >> >> I don't see how you can turn this into something useful... >> >> Peter > > 10x. it works. however I have another small problem. now, > d.third('blah') doesn't work because instance d doesn't have 'third' > attribute. I was expecting derived class to inherit the metaclass as > well, but it didn't. That has nothing to do with inheritance: >>> type(Derived) If Python doesn't find an attribute in the instance it looks it up in the class but not in the metaclass: >>> Base.third at 0x2b5f8028aa28> >>> Base().third Traceback (most recent call last): File "", line 1, in AttributeError: 'Base' object has no attribute 'third' I think you should go back to the drawing board now and look for a simpler approach to solve your actual problem... Peter From rtw at freenet.co.uk Mon Sep 8 03:17:43 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 08 Sep 2008 02:17:43 -0500 Subject: How do I set a callback in Python? References: Message-ID: catsclaw wrote in news:d797403a-e492-403f-933a-bd18ef53d5c0 @k13g2000hse.googlegroups.com in comp.lang.python: > I can't for the life of me figure out how to set a callback in > Python. I have a class, which wraps another class. The second class > needs a callback assigned. I don't want to use globals for it. > Here's what I'd like to do: > > class MyWrapper: > def get_login(self, username): > return self.user, self.pass > > def __init__(self, user, pass): > self.user = user > self.pass = pass > > self.client = Client("connection string") > self.client.callback_login = get_login > > ... but obviously, the Client class, when it calls the callback, > doesn't pass a reference to the "self" object. How do I do this? use: self.client.callback_login = self.get_login Rob. -- http://www.victim-prime.dsl.pipex.com/ From kay.schluehr at gmx.net Sat Sep 20 06:03:19 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Sep 2008 03:03:19 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> On 20 Sep., 11:23, candide wrote: > Excerpt quoted fromhttp://www.astro.ufl.edu/~warner/prog/python.html: > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > Thanks for any comment. This is somewhat true. But what is OO, really? Answer: if you want to define an entity it has to be defined inside a class. If you want to access an entity you have to use the dot operator. Therefore Java is OO but Python is not. From pavlovevidence at gmail.com Mon Sep 29 02:34:14 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 28 Sep 2008 23:34:14 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> Message-ID: On Sep 29, 1:44?am, George Sakkis wrote: > On Sep 29, 12:08 am, Terry Reedy wrote: > > > > > George Sakkis wrote: > > > On Sep 28, 2:29 pm, process wrote: > > > >> I have heard some criticism about Python, that it is not fully object- > > >> oriented. > > > > That's not a bug, it's a feature ;-) > > > >> Why isn't len implemented as a str.len and list.len method instead of > > >> a len(list) function? > > > > As Terry Reedy wrote, partly history and partly practicality. There's > > > no philosophical reason why we write "len(x)" (generic builtin), > > > "x.append(1)" (method) or "del x[i]" (statement). The latter in > > > particular is IMHO a design wart; there's no reason for not writing it > > > as "x.delete(i)". > > > As a general rule and matter of practice, methods that apply to all or > > most classes (or all number classes) have built-in functions that call > > the corresponding special method (or C-level slot). > > It would be easier to justify this rule if it was more clear-cut, and > specifically if it was applied only to methods that are available to > *all* classes (such as type() and getattr()) rather than the ill- > defined "most classes". That wasn't your original claim, though. You claimed there was no philosophical reason, then Terry gave you one, then you said, well there's no clear cut reason. Unless you define "philosophical" as "clear cut" (a definition I'm not sure many would agree with). Anyway, you are right to claim there's no clear cut distinction, just as there's never any clear cut distinction over whether something should be an operator or not. Addition is only available to the ill- defined "most classes", yet not only is it not a method, it has its own syntax. There's no clear cut distinction there, it's just a design decision. Likewise, making len() into a function is just a design decision, that len is a common enough operation that it need elevated status. It's really nothing more. Python wouldn't suffer much regardless if len is a method, a built-in function, or an operator with its own syntax. Carl Banks From lists at cheimes.de Wed Sep 10 14:20:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 20:20:31 +0200 Subject: subprocess.Popen hangs at times? In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > When making calls of the form Popen(cmd, shell=True, > stdout=subprocess.PIPE), we've been getting occasional, predictable > hangs. Will Popen accumulate a certain amount of stdout and then block > until its read? We don't want to use threads, so just want to read the > entire stdout after the subprocess has finished. The subprocess module has already an API method for your use case. The communicate() method of a subprocess.Popen instance takes an optional stdin string and returns the stdout and stderr output as strings. The method uses the best low level functions possible (select() on Unix, threads on Windows). Christian From gminick at bzt.bzt Wed Sep 10 13:43:43 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 17:43:43 +0000 (UTC) Subject: md5 differences References: Message-ID: On Wed, 10 Sep 2008 12:39:24 -0500, Grant Edwards wrote: >> The strange thing is that >>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. > > Same here. I guess it will be the same for vast majority of us ;-) The question is why is it '90364ed45b452d43378629c20543a81d' for the OP? :-) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From kay.schluehr at gmx.net Sat Sep 20 16:22:23 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Sep 2008 13:22:23 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> Message-ID: On 20 Sep., 18:33, Bruno Desthuilliers wrote: > The following definitions are AFAIK the only commonly accepted > definitions about OO: > > 1/ an object is defined by identity, state and behaviour > 2/ objects interacts by sending messages each other > 3/ an OO program is made of interacting objects > > I let you find out whether Python meets these 3 definitions - and if > Java does (hint : in Python, everything you can bind to a name is an > object - this is not true in Java or C++). This is correct but it detracts from a more general problem of language "paradigms". Assume you type >>> 2+2 4 Now you are free to interpret this as a simple, primitive arithmetic operation but you can also claim that 2 sends an __add__ message to 2. Hereby the state of the 2 objects are not altered but a new 4 object is created. OO babble is more impressive isn't it? Actually it is simply wrong in the mentioned case and here is the proof: def foo(): return 2+2 import dis dis.dis(foo) 2 0 LOAD_CONST 2 (4) 3 RETURN_VALUE OO is a heuristic method used to understand the semantics of a programming language. It can also inspire language design but as you've rightly said: jugde yourself and see how far you get with it. Applying OO on interpreter level is by no means a sign of a high quality implementation whereas structuring programs in the large will likely benefit from class based organization and encapsulation. Of course one can also reverse the value hierarchy and find perverse joy in having a pure OO language but apply monkey patching everywhere. I suppose you know which language I'm talking about... From castironpi at gmail.com Mon Sep 29 14:32:16 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 29 Sep 2008 11:32:16 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> Message-ID: On Sep 29, 9:14?am, Paul Boddie wrote: > On 29 Sep, 05:56, Terry Reedy wrote: > > > > > As I understand it, partly from postings here years ago... > > > Lexical: The namespace scope of 'n' in inner is determined by where > > inner is located in the code -- where is is compiled. ?This is Python > > (and nearly all modern languages). ?Even without closures, the global > > scope of a function is the module it is defined in. > > This is how I understand it, too. The confusing part involves the > definition of any inner function and how any "external" names are > bound or defined. As we've seen... > > ? def f(x): > ? ? def g(): > ? ? ? return x > ? ? x += 1 # added for illustration > ? ? return g > > ...it might look at first glance like the function known as g (within > f) should return the initial value of x (as known within f), since > that was the value x had when g was defined. The following is an > example execution trace based on that mental model: > > fn = f(1) > -> def f(1): > -> ? def g(): # g defined with x as 1 > -> ? ? return x # would be 1 > -> ? x += 1 # x becomes 2 > -> ? return g > fn() > -> def g(): > -> ? return x # would still be 1 > > However, as we know, this isn't the case in real Python since g isn't > initialised with the value of x at the time of its definition - it > instead maintains access to the namespace providing x. We must > therefore revise the example: > > fn = f(1) > -> def f(1): > -> ? def g(): # g refers to x within f(1) > -> ? ? return x # would be the current value of x within f(1) > -> ? x += 1 # x becomes 2 > -> ? return g > fn() > -> def g(): # g refers to x within f(1) > -> ? return x # would be the current value of x within f(1), which is > 2 > > This is the dynamic aspect of closures: values aren't used to > initialise inner functions; names are looked up from their origin. > > > Dynamic: The namespace scope of 'n' in inner, how it is looked up, is > > determined by where inner is called from. This is what you seemed to be > > suggesting -- look up 'n' based on the scope it is *used* in. > > Indeed. Dynamic scoping is confusing in that one has to set up an > appropriate "environment" for the closure to access so that references > to names can be meaningfully satisfied; obviously, this creates all > sorts of encapsulation problems. The confusing aspect of lexical > scoping, however, especially if non-local names can be changed, is > that the effects of closures are potentially distant - one doesn't > always invoke inner functions in the place where they were defined, as > we see above - and such effects may thus happen within "abandoned > namespaces" - that is, namespaces which can no longer be revisited and > used in their original context. So, in the above, once f has been > invoked, the namespace for that invocation effectively lives on, but > that namespace is not a general one for f - if we invoke f again, we > get another namespace as one should reasonably expect. > > A somewhat separate issue is illustrated by the modification of x > within f. Although for most statements, we would expect the value of x > to evolve following from a top-to-bottom traversal of the code within > a unit, function definition statements do not behave like, say, "for", > "if" or "while" statements. Now although this should be obvious at the > module global level, I feel that it can be easy to overlook within a > function where one normally expects to find plain old control-flow > constructs, expressions, assignments and so on. It is pertinent to > note, with respect to the original inquiry, that lambda functions are > subject to the same caveats, and I believe that lexical scoping was > introduced precisely to make lambda functions less cumbersome to > employ, eliminating the need to explicitly initialise them using the > "identity" default parameters trick, but obviously introducing the > consequences and potential misunderstandings described above. > > Paul I'm thinking of a comparison to try to see an example. I tried this which still surprised me at first. >>> g= [0] >>> f= lambda: g >>> del g >>> f() NameError: global name 'g' is not defined It took a little thinking. The namespace in 'f' is the global namespace. They are one in the same dictionary. id( f.namespace ) == id( main.namespace ). f.namespace is main.namespace. When f gets a parameter, its namespace is different by one (or two when two parameters, etc). >>> g=[0] >>> f= lambda h: lambda: h >>> i= f( g ) >>> del g >>> i() [0] The statement 'del g' removes 'g' from the module/global namespace, but it lives on in the namespace of 'f', or more accurately, 'i'. >>> g=[0] >>> f= lambda h: lambda: h >>> i= f( g ) >>> j= f( g ) >>> del g >>> i().append(1) >>> j() [0, 1] Here, the namespaces of 'main', 'i', and 'j', all have references to 'g'. 'i' and 'j' still have them when 'main' loses its. The lambda might be confusing. Take a simpler example of a namespace: >>> g= [0] >>> def h(): ... class A: ... a= g ... return A ... >>> i= h() >>> del g >>> i.a [0] Or even: >>> g=[0] >>> class A: ... a= g ... >>> del g >>> A.a [0] The class is executed immediately so 'A.a' gets a hold of 'g'. Function definitions keep a reference to the -identity-, not value, of the namespace they were defined in, and parameters are part of that namespace. >>> def h( a ): ... #new namespace in here, new on each call ... def i(): ... return a ... return i 'i' is not defined in the global namespace, it's defined in a brand new one that is created on every call of 'h'. 'a' is defined in that, so that's what 'a' when 'i' is called refers to. To be specific, the namespace 'h' defines only includes the names that are different from its enclosing scope. Regardless of what's defined below 'h', 'h' only defines one new variable, 'a'. Its value is passed in at call-time. 'i' needs to know what that namespace is-- that's how closures work-- so it saves a reference. That saved reference is to a namespace, not a variable though, which distinguishes it from the 'class A: a= g' statement that's executes immediately. There, 'a' stores the value of g. By contrast, 'i' stores 'h's entire namespace. In 'class A: a= g', the name 'a' is assigned to the contents of 'g'. In 'def i(): return a', 'a' is the value of a look up in a namespace by its name. >>> def h( a ): ... #new namespace in here ... def i(): ... return a ... return i ... >>> g=[0] >>> j= h(g) >>> hex(id(g)) '0x9ff440' >>> del g >>> hex(id(j())) '0x9ff440' >>> j.func_closure (,) By the time 'g' is deleted, 'j' has already hijacked a reference to it, which lives in the namespace of the 'i' it defined that time through. 'j()', originally 'g', and 'j's namespace all refer to the same object. Variables are keys in a namespace, even if it's an "abandoned namespace", adopting the term. From zak.mc.kraken at libero.it Mon Sep 15 12:19:00 2008 From: zak.mc.kraken at libero.it (Vito De Tullio) Date: Mon, 15 Sep 2008 18:19:00 +0200 Subject: Representation of python code ? References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: Barak, Ron wrote: > Hi Guys, > Is there a script/application, which gets as input python code, and > produces a (graphic) representation of the inter-relationships between its > classes/functions ? Bye, Ron. I'm not sure it's really what you want, but AFAIK umbrello (http://uml.sourceforge.net/index.php) can generate a UML diagram for you -- By ZeD From jpcomputing at inbox.com Sat Sep 6 05:17:36 2008 From: jpcomputing at inbox.com (James Pilling) Date: Sat, 6 Sep 2008 01:17:36 -0800 Subject: Learning Python Message-ID: Hi im currently starting to learn python in sixth form at school any tips? ____________________________________________________________ GET FREE 5GB EMAIL - Check out spam free email with many cool features! Visit http://www.inbox.com/email to find out more! From torainLight at gmail.com Sat Sep 20 10:08:24 2008 From: torainLight at gmail.com (satoru) Date: Sat, 20 Sep 2008 07:08:24 -0700 (PDT) Subject: how can i check whether a variable is iterable in my code? References: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> <2dfbad14-b898-4284-9912-337af09c4d90@s9g2000prg.googlegroups.com> Message-ID: <20afa6c7-56d2-4c8f-813d-75bc120bb353@n38g2000prl.googlegroups.com> thanks very much! From bj_666 at gmx.net Tue Sep 2 08:27:49 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 12:27:49 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> Message-ID: <6i4pq5Fol29aU1@mid.uni-berlin.de> On Tue, 02 Sep 2008 05:02:07 -0700, Nicola Musatti wrote: > On Sep 1, 9:23 am, Jeremy Banks wrote: >> Hi. I wondered if anyone knew the rationale behind the naming of the >> Popen class in the subprocess module. Popen sounds like the a suitable >> name for a function that created a subprocess, but the object itself is >> a subprocess, not a "popen". It seems that it would be more accurate to >> just name the class Subprocess, can anyone explain why this is not the >> case? > > The Python class is a generalization of the standard Posix function of > (almost) the same name: > http://opengroup.org/onlinepubs/007908775/xsh/popen.html So it's a name of a *function* and it's a little bit unsuitable for a *class*. As Jeremy wrote: the instances represent *processes* not "popen"s, whatever that may be. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Tue Sep 2 09:49:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 13:49:16 GMT Subject: what's the difference between f(a) and f(*a) References: <4b57d4c3-a398-41b1-916a-064ee96bf3f6@25g2000prz.googlegroups.com> Message-ID: <6i4uisFol29aU3@mid.uni-berlin.de> On Tue, 02 Sep 2008 06:24:21 -0700, qxyuestc wrote: > showed above: the result from sum1() and sum2() is the same. So, what is > the difference between f(a) and f(*a) f(a) -> f([1, 2, 3]) f(*a) -> f(1, 2, 3) Ciao, Marc 'BlackJack' Rintsch From aquila_grande at yahoo.no Mon Sep 1 12:23:35 2008 From: aquila_grande at yahoo.no (Aquila) Date: Mon, 1 Sep 2008 09:23:35 -0700 (PDT) Subject: Make money using free affiliate programs Message-ID: <4b853da1-4771-4717-a8cd-dfe3d05fc8a7@f36g2000hsa.googlegroups.com> Making money with affiliate programs is a better way, please see this web-site: http://www.abicana.com/affiliatenetworks.htm From bearophileHUGS at lycos.com Thu Sep 18 09:13:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 18 Sep 2008 06:13:39 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: Skip: > indexes = range(len(IN)) > for i in indexes: #scan all elements of the list IN > for j in indexes: Nope, use xrange in both situations, and save a list. Tim Chase: > for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): > if IN[i].coordinates == IN[j].coordinates: > SN.append(IN[i].label) > > If my college algorithms memory serves me sufficiently, this > reduces your O(N^2) to O(N log N) which will garner you some > decent time savings. That's O(n^2) still, it's just half matrix, a triangle. Bye, bearophile From FettManChu at gmail.com Tue Sep 16 22:25:58 2008 From: FettManChu at gmail.com (Fett) Date: Tue, 16 Sep 2008 19:25:58 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> Message-ID: <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> On Sep 16, 9:00 pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 16, 8:50 pm, Fett wrote: > > > > > I am trying to find a wrapper to do linear programming within python. > > I am using an ubuntu machine and I have apt-get'd lp_solve, which > > works just fine. If someone knows of a wrapper that will work with > > that that'd be great. > > > I also heard that scipy has a wrapper, however, I can't find any > > documentation on it, nor can I seem to find it with dir(). If anyone > > knows where there is good documentation on this I would love to use > > that (the more native to python the better imo). > > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > > openopt, and cvxopt. I can't seem to find any with enough > > documentation to get me off the ground. Some I can't compile, some I > > can't even find out how to compile. > > > If anyone knows of an LP package (preferably with IP as well, like > > lp_solve has), that interfaces well with python and has enough > > documentation to get a dependency newb like myself off the ground that > > would be great. > > Google says: > > about 254,000 for linear programming python. > > Link 3 is: > > http://wiki.python.org/moin/NumericAndScientific/Libraries > > Scroll down. Yes, many of those seem to be deprecated, without destinations to links, most are poorly or not documented at all. The few that are, I still can't get running. Of those 254, I think I have tried at least 10 pages worth. Still no luck. # lpsolvpy - Can't get it to compile - dependency problems. # Lp_solve5 - NO python binding yet. Volunteers needed for python bindings. # pycplex - You need to compile the CPX.so module. Change the required paths to CPLEX, Python and numpy in the Makefile, and type "make". Not sure what to do here. # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, I missed the second link to the python bindings, looked all over the glpk site for anything about python. # SciPy -- http://www.scipy.org - supposedly has this, but as I said, I can't find any mention of it anywhere but on the site you linked. # pySimplex - (broken link)(broken link) # Simplex - link is broken, but nothing is mentioned I'll take a closer look at glpk's python bindings and if there is any documentation on them, maybe I'll have some luck. btw, I have been looking for something that works, I have over 5 packages on my desktop that I have tried to get up and running, but none of them seem to work. glpk makes 6. From lists at cheimes.de Sun Sep 28 12:51:20 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 28 Sep 2008 18:51:20 +0200 Subject: Unable to write % character to a file using writelines() method In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > Hi, > > > I'm using the writelines() method to write some lines to a text file. But > I'm unable to write the % character to the file using the following format: > > fdTolFile.writelines("\n\tdiff Not in %s '%' range" %(toleranceInPer)) Try %% :) Christian From kay.schluehr at gmx.net Sat Sep 20 10:26:57 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Sep 2008 07:26:57 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: On 20 Sep., 12:14, Fredrik Lundh wrote: > Kay Schluehr wrote: > > Answer: if you want to define an entity it has to be defined inside a > > class. If you want to access an entity you have to use the dot > > operator. Therefore Java is OO but Python is not. > > you're satirising the quoted author's cargo-cultish view of object > orientation, right? > > I wonder if the OO fetish hasn't already lost much of its magic powers. What are the most powerful fetishes these days? A year ago I would have suspected "purely functional" but I'm not sure it has really caught on. From fernandena at gmail.com Wed Sep 24 12:19:32 2008 From: fernandena at gmail.com (fernandena at gmail.com) Date: Wed, 24 Sep 2008 09:19:32 -0700 (PDT) Subject: Filthy Pink Sneakers. By Marina Cooper Message-ID: <7a6bf464-4944-4c1b-93bd-c389e0ce2a55@a1g2000hsb.googlegroups.com> SEXY story. The cute doorman gives me an enigmatic look when I say I'm here to see you. I am not sure if maybe he thinks I am your daughter. You are not quite old enough for that, I am not quite young enough - but we are pretty close. Am I wrong for thinking that's hot? Definitely. I think... http://ragdai.info/sex-story.html From castironpi at gmail.com Mon Sep 22 22:54:17 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 19:54:17 -0700 (PDT) Subject: How do I convert a PyObject to string in C++? References: Message-ID: On Sep 22, 9:32?pm, lixinyi... at gmail.com wrote: > I have a PyObject, say 'Hello World' , a string, > How do I convert it to a string in C++? > Thanks in advance! Look at PyString_AsStringAndSize . It gives you a pointer to a buffer and a size. Allocate a new one and copy it if you need to modify it, or you want a copy that outlives the object version. From fredrik at pythonware.com Thu Sep 11 05:34:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 11:34:16 +0200 Subject: Is len O(n) or O(1) ? In-Reply-To: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> Message-ID: process wrote: > Python uses arrays for lists right? len is O(1). for other operations, see http://effbot.org/zone/python-list.htm#performance > def quicksort(lista): > if lista == []: > lista better make that: def quicksort(lista): if not lista: return lista ... From zxo102 at gmail.com Sun Sep 28 01:33:31 2008 From: zxo102 at gmail.com (zxo102) Date: Sat, 27 Sep 2008 22:33:31 -0700 (PDT) Subject: how to make smtplib.SMTP('localhost') work on window xp Message-ID: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Hi, I am trying to use python module smtplib to send my email out on window xp (localhost). import smtplib server = smtplib.SMTP('localhost') but I got the error information as follows: Traceback (most recent call last): File "", line 1, in ? File "c:\python24\lib\smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "c:\python24\lib\smtplib.py", line 311, in connect (code, msg) = self.getreply() File "c:\python24\lib\smtplib.py", line 355, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed I am not sure what is wrong with it. Should I configure my window xp somewhere to run smtplib.SMTP('localhost')? Thanks in advance. ouyang From ldo at geek-central.gen.new_zealand Mon Sep 29 21:49:16 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 30 Sep 2008 14:49:16 +1300 Subject: writing dll in python? References: Message-ID: In message , nishalrs wrote: > Should I write all the functions as simple python scripts? Or is there > some facility for creating a .dll like library, that could be more > suitable for what in intend to develop? Start with Python. From lepto.python at gmail.com Fri Sep 5 23:32:47 2008 From: lepto.python at gmail.com (oyster) Date: Sat, 6 Sep 2008 11:32:47 +0800 Subject: embed python in ms-word? Message-ID: <6a4f17690809052032h7b3efc5cm48b55c948c110236@mail.gmail.com> In my ms-word documnet, there are some calculation whihc I have to change due to different argumnet. is there any way to embed python code in word, so that I can write the following as a macro or something else, then the result (i.e. 2) is shown in the word documnet? def f(n): if n<2: return 1 else: return f(n-1)+f(n-2) main() return 'fib(3)=%0i' % f(3) if that is impossible, does there exist such word-addons can do that? thanx From mrchatgroup at gmail.com Thu Sep 25 19:02:07 2008 From: mrchatgroup at gmail.com (mrchatgroup at gmail.com) Date: Thu, 25 Sep 2008 16:02:07 -0700 (PDT) Subject: Small Accidents Mean Big Trouble for Supercollider Message-ID: <2759b72f-9e6f-46c7-9fe4-04703c5c6c54@k36g2000pri.googlegroups.com> news from http://www.mrchat.net/myblog/myblog/small-accidents-mean-big-trouble-for-supercollider.html Small Accidents Mean Big Trouble for Supercollider Image Scientists expect startup glitches in the massive, complex machines they use to smash atoms. But the unique qualities of the world's largest particle collider mean that the meltdown of a small electrical connection could delay its groundbreaking research until next year, scientists said Sunday. Because the Large Hadron Collider operates at near absolute zero ? colder than outer space ? the damaged area must be warmed to a temperature where humans can work. That takes about a month. Then it has to be re-chilled for another month. As a result, the equipment may not be running again before the planned shutdown of the equipment for the winter to reduce electricity costs. That means Friday's meltdown could end up putting off high-energy collisions of particles ? the machine's ultimate objective ? until 2009. "Hopefully we'll come online and go quickly to full energy a few months into 2009 so in the long term, this may not end up being such a large delay in the physics program," Seth Zenz, a graduate student from the University of California, wrote on the site of the U.S. physicists working at the European Organization for Nuclear Research, or CERN. "It's obviously a short-term disappointment, though, and a lost opportunity," he wrote. CERN spokesman James Gillies said the repair operation will last until close to the usual winter shutdown time at the end of November. There has been some discussion that the new equipment could operate through the winter, but no decision has been made, he said. The melting of the wire connecting two magnets Friday would have taken only a couple of days to repair on smaller, room-temperature accelerators that have been in use for decades, Gillies said. Gillies said particle accelerators using superconducting equipment at Fermilab outside Chicago and at Brookhaven National Laboratory in New York state had similar problems starting up, but have been operating smoothly since then. "Once they settled in they seem to be pretty stable," Gillies said. At the Sept. 10 launch of the collider, beams of protons from the nuclei of atoms were fired first at the speed of light in a clockwise direction though a fire-hose-sized tube in the tunnel. Then proton beams were fired in the counterclockwise tube. Jos Engelen, CERN's chief scientific officer and deputy director- general, said the startup showed that the LHC can handle complex operations. "We have encountered a weakness in one particular connection during very final hardware commissioning," Engelen told The Associated Press by e-mail. "It is tough, but it can happen. We will make the repair and resume the very successful operation of the accelerator." A transformer failed outside the cold zone about 36 hours after the collider's launch. That was repaired and the machine was ready again a week after it was shut down. But the goal of the LHC ? shattering protons to reveal more about how the tiniest particles were first created ? was still weeks away because the equipment has to be gradually brought to the higher energies possible at full power. "This was the last circuit of the LHC to be tested at high current before operations," Gillies said. "There are an awful lot of these connections between wires in the machine. They all have to be very well done so that they don't stop superconducting, and what appears to have happened is that this connection stopped being superconducting." Superconductivity ? the ability to conduct electricity without any resistance in some metals at low temperatures? allows for much greater efficiency in operating the electromagnets that guide the proton beams. Without the superconducting, resistance builds up in the wires, causing them to overheat, he explained. "That's what we think happened," Gillies said. "This piece of wire heated up, melted, and that led to a mechanical failure." Gillies said experts have already gone down into the 27-kilometer (17- mile) circular tunnel under the Swiss-French border to inspect the damage. "By Monday I suspect we'll know more," he said. Gillies said there is plenty for scientists at CERN to do between now and the startup of experiments, including studying cosmic rays that pass through collider's massive detectors. more http://www.mrchat.net/myblog/myblog/small-accidents-mean-big-trouble-for-supercollider.html http://www.mrchat.net/myblog/myblog/small-accidents-mean-big-trouble-for-supercollider.html From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:37:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:37:10 GMT Subject: Comparing float and decimal References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: <00eaf32a$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 04:30:03 -0500, Nick Craig-Wood wrote: > Both the Fraction module and the Decimal module could represent floats > exactly and reversibly since floats are of the form > > mantissa * 2**exponent > > which is exactly representable as a fraction (rational) and also as > > mantissa2 * 10**exponent2 > > as to why we don't do this... > > I guess it is to preserve the sanity of the user when they write > fraction(0.1) or decimal(0.1) did they really mean fraction(1,10), > decimal("0.1") or the exact representations which are > decimal("0.1000000000000000055511151231257827021181583404541015625") and > fraction(3602879701896397,2**55) I would say that in practice the chances that somebody *actually* wanted 0.1000000000000000055511151231257827021181583404541015625 when they wrote 0.1 is about the same as the chances that the BDFL will support braces in Python 3.0. (Hint: "from __future__ import braces") > Given that we let the exact representations leak out anyway (which > causes a lot of FAQs in this list), eg > >>>> 0.1 > 0.10000000000000001 > > IMHO We should put the exact conversions in for floats to Decimal and > Fraction by default and add a new section to the FAQ! But of the reasons for having the Decimal module is to avoid such leaky abstractions. Without Decimal (or fraction) there's no obvious way to get 0.1 exactly. It seems perverse to suggest that by default Decimal should deliberately expose the same leaky abstraction that causes so much trouble when people use floats. > In that way people will see floats for what they really are - a crude > approximation to a rational number ;-) You can already see that just by printing a float: >>> 0.3 0.29999999999999999 >>> 0.1 0.10000000000000001 -- Steven From akathorn at gmail.com Fri Sep 5 09:15:11 2008 From: akathorn at gmail.com (Akathorn Greyhat) Date: Fri, 5 Sep 2008 14:15:11 +0100 Subject: Curious: 2134 2004-10-06 08:55:20Z fredrik In-Reply-To: References: Message-ID: 2008/9/5 Gabriel Genellina > > > I'd say the import mechanism got confused about the actual source of the > error. Probably it happened on line 3 in *another* module, but the traceback > got messed. Perhaps "core" is a package and contains "import data" at line > 3? > > The $Id: stuff comes from some version control system -probably svn- and > identifies the file version. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list Interesting... =P You are right, the package "core" contains "import data", but that module doesn't exist, so it raises this strange error -- Akathorn Greyhat -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ron.Barak at lsi.com Tue Sep 16 04:29:54 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Sep 2008 09:29:54 +0100 Subject: vim/gvim colour scheme for Python with white background ? Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6022A6B87@enbmail01.lsi.com> Hi Guys, Could anyone send me URL of a decent vim/gvim colour scheme for Python with white background ? Googling around, best I could find was python.vim (http://www.cs.cmu.edu/~maverick/VimColorSchemeTest/python.vim), but I'm not happy with quite a few of its choices. Instead of creating something from scratch (e.g., reinventing wheels) thought of ask the community what it uses. Thanks, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Thu Sep 25 14:03:36 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 25 Sep 2008 11:03:36 -0700 (PDT) Subject: How can I customize builtin module search path to prefix/lib to prefix/lib64? References: mailman.1503.1222357330.3487.python-list@python.org Message-ID: On Sep 25, 10:41?am, js wrote: > Hi list, > > Is it possible to change module search path (PYTHONPATH) built-in to > Python interpreter? > I thought I can change it with configure --libdir but it didn't work for me. > I also tried patching around python source tree replacing lib to lib64 > but it didn't work either. > > Adjusting sys.path directly or using environ should do the trick but > I'd rather want to make it the default path for my python > > Thanks, Why not just add a custom path file (*.pth)? EasyInstall, wx, PyWin32 and others do it. Of course there's always sys.path.append as well. Mike From fredrik at pythonware.com Sun Sep 14 15:37:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Sep 2008 21:37:16 +0200 Subject: Abstract class In-Reply-To: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> Message-ID: Mr.SpOOn wrote: > Well, I know the difference between an abstract class and an inherited > one. The idea was to create a main class Note, with abstract methods, > and implement these methods in the other classes. The pragmatic way to implement abstract classes in Python is to define an ordinary base class, and either just leave out the methods that must be defined in subclasses, or provide stub methods that simply raise a NotImplementedError exception: class AbstractThing(object): ... def some_method(self, args): raise NotImplementedError There are more "clever" ways to do things, but they're usually overkill. > Anyway, I think I need an abstract class. Or not? Depends on how much generally useful functionality you can come up with for the base class. It's not like Python prevents you from overriding a non-abstract method, after all. I suggest you skip further discussion and get to work. I'm sure you'll figure out what works best for your specific case once you've written a few classes. From castironpi at gmail.com Sun Sep 7 22:59:12 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 7 Sep 2008 19:59:12 -0700 (PDT) Subject: lacking follow-through References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <086a0906-c6f1-489c-91ab-f6a4f9e1ae3f@59g2000hsb.googlegroups.com> Message-ID: <99113520-2fa2-46ac-9894-ea78372ff610@c58g2000hsc.googlegroups.com> On Sep 7, 7:34?pm, MRAB wrote: > On Sep 7, 11:28?pm, "Eric Wertman" wrote: > > > +1 Bot > > I think it's like duck typing: it doesn't matter whether he's actually > a bot, only whether he behaves like one. Do you support the bot interface and methods? From ldo at geek-central.gen.new_zealand Mon Sep 29 05:16:25 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:16:25 +1300 Subject: how to search multiple textfiles ? References: Message-ID: In message , George Sakkis wrote: > $ find -name "*py" | xargs egrep "\bword\b" Better: find -name '*.py' -exec grep -E "\bword\b" {} \; From tim.arnold at sas.com Thu Sep 25 08:16:18 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 25 Sep 2008 08:16:18 -0400 Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: "Tim Arnold" wrote in message news:57cdd3f1-cde8-45f5-b9d9-3eef32010bda at l43g2000hsh.googlegroups.com... >I have a bunch of processes to run and each one needs its own working > directory. I'd also like to know when all of the processes are > finished. Thanks for the ideas everyone--I now have some news tools in the toolbox. The task is to use pdflatex to compile a bunch of (>100) chapters and know when the book is complete (i.e. the book pdf is done and the separate chapter pdfs are finished. I have to wait for that before I start some postprocessing and reporting chores. My original scheme was to use a class to manage the builds with threads, calling pdflatex within each thread. Since pdflatex really does need to be in the directory with the source, I had a problem. I'm reading now about python's multiprocessing capabilty, but I think I can use Karthik's suggestion to call pdflatex in subprocess with the cwd set. That seems like the simple solution at this point, but I'm going to give Cameron's pipes suggestion a go as well. In any case, it's clear I need to rethink the problem. Thanks to everyone for helping me get past my brain-lock. --Tim Arnold From nospam at spamhaters.com Sun Sep 7 16:56:54 2008 From: nospam at spamhaters.com (sc) Date: Sun, 07 Sep 2008 15:56:54 -0500 Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Sat, 06 Sep 2008 17:18:55 -0300, clurker > escribi?: > >> Michele Simionato wrote: >> >>> On Aug 28, 6:21?am, ssecorp wrote: >>>> Is there a way to view all the modules I have available for import >>>> from within Python? >>>> Like writing in the interpreter: >>> >>> Try: >>> >>>>>> help() >>> help> modules >>> Please wait a moment while I gather a list of all available modules... >>> >> >> This looks like it could be a useful tool, but when I try it >> I get the following: >> >> Please wait a moment while I gather a list of all available modules... > [...] >> File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line >> 1342, >> in >> >> File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line >> 927, >> in main >> >> UnboundLocalError: local variable 'given_files' referenced before >> assignment >>>>> > > Unfortunately the "modules" help command actually imports all the > available packages, and a buggy one may stop the whole process with an > error. > >> Apparently python knows about them both, but I don't know I >> haven't introduced an incompatibility somewhere...and that PIL >> package showing up at the tail of the errors was one of my >> more recent additions... > > If import of a package fails, the error reported is not accurate. In this > case, probably some other package failed, that itself imported PIL. Line > 927 in PIL/__init__.py does not exist. > > A quick fix is to replace line 1854 in pydoc.py (ModuleScanner.run) with > this one: > > for importer, modname, ispkg in > pkgutil.walk_packages(onerror=lambda name:None): > > (the onerror argument makes it to ignore all errors) > nice Gabriel, thanx! At least now "help(); modules" gives me a beautiful list -- I guess I'll find out what the buggy module is if/when I try to use it...(all PIL/__init__.py is is about 15 lines of comments (referencing a README I can't find)) sc From martin at v.loewis.de Fri Sep 19 02:18:49 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 19 Sep 2008 08:18:49 +0200 Subject: CTypes on a 64 bit machine truncates pointers to 32 bits? In-Reply-To: References: Message-ID: <48d34449$0$2363$9b622d9e@news.freenet.de> >>>> foolib = cdll.LoadLibrary('foo.so') >>>> foolib.foo(0xF00000000) > 0 Shouldn't you tell ctypes that the argument and the result of foo is a pointer? Regards, Martin From berthold at despammed.com Thu Sep 11 03:11:59 2008 From: berthold at despammed.com (Berthold =?iso-8859-15?Q?H=F6llmann?=) Date: Thu, 11 Sep 2008 09:11:59 +0200 Subject: Refcount problem in ceval.c References: Message-ID: Christian Heimes writes: > Berthold H?llmann wrote: >> Is there any "common" reason to for such a strange object on the command >> stack, or is it more likely that any of my extension modules is causing >> havoc? > > It's very likely that your extension has a reference counting bug. It > looks like you are either missing a Py_INCREF or you have a Py_DECREF > too much. Newly freed memory is filled with 0xDB (see > Objects/obmalloc.c DEADBYTE). I was suspecting this, that's why I build the debugging version of Python. I hoped I would get the error message somewhere near the code causing the error, but I seems i have to continue the search. > Wild guess: Are you using PyModule_AddObject with a PyTypeObject w/o > Py_INCREF()ing the type object first? That would have been easy :-) I have only one occurrence of PyModule_AddObject, and its PyTypeObject is Py_INCREF()ed Thanks Berthold -- __ Address: G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 194 bytes Desc: not available URL: From deets at nospam.web.de Thu Sep 11 14:07:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Sep 2008 20:07:30 +0200 Subject: conditional install/distribution In-Reply-To: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> References: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> Message-ID: <6it533Fe2h8U1@mid.uni-berlin.de> i3dmaster schrieb: > Is there a feature in distutils or easy_install to specify what > version of python that the target package can be installed? For > example, if a package has a module that only needed if the python > version < 2.6, is there a way to specifiy that in setup.py or > easy_install cfg file so that when installing to python >= 2.6, this > module wouldn't be installed?? you can simply import sys and check sys.version in the setup-script, and abort with an error-message if the expectations aren't matched. Diez From fredrik at pythonware.com Thu Sep 4 12:03:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 18:03:54 +0200 Subject: Read Binary data In-Reply-To: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> References: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> Message-ID: "Mars creature" wrote: > I am trying to read a binary file created by the following matlab > command: > fid=fopen('a.bin','w','b'); fwrite(fid,a,'real*8'); fclose(fid);, and > wondering how to do it in Python. I googled it but still get > confused. > 'b' in fopen is for 'big-endian', 'real*8' in fwrite is for 64bit > float. f = open("a.bin", "rb") # read binary data s = f.read() # read all bytes into a string import array, sys a = array.array("f", s) # "f" for float if sys.byteorder != "big": a.byteswap() From denisbz at t-online.de Wed Sep 10 06:52:09 2008 From: denisbz at t-online.de (denisbz at t-online.de) Date: Wed, 10 Sep 2008 03:52:09 -0700 (PDT) Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: > > A quick fix is to replace line 1854 in pydoc.py (ModuleScanner.run) with > > this one: > > > ? ? ? ? for importer, modname, ispkg in > > ? ? ? ? pkgutil.walk_packages(onerror=lambda name:None): > > > (the onerror argument makes it to ignore all errors) well not all, for example GLUT: Fatal Error in summon: could not open display: :0.0 So to refine the question: how can I list all modules that might be importable on my system, without actually importing them all ? (How about a "pydoc2" that's well thought out, doesn't crash ... let me ask more knowledgable people, what's a good small help system as model ? ) cheers -- denis From half.italian at gmail.com Tue Sep 16 03:58:58 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 16 Sep 2008 00:58:58 -0700 (PDT) Subject: Python GUI for animation References: Message-ID: <1896f3dc-d8b6-41f4-9ff2-4c9cefc1ab84@a18g2000pra.googlegroups.com> On Sep 15, 11:29?pm, Virgil Stokes wrote: > I have been using Python for a short time and I find it a very flexible > language, and easy to learn and use. I have also worked some with PyGame > and used it to create a simple animation that is controlled by the mouse > and keyboard. The animation is designed to move filled circles around on > the screen and is driven by a data file that defines (indirectly), the > next relative position of each circle. And for my purposes (queueing > demo in the classroom) this works quite well. However, I would now like > to create a Python GUI that would allow a user to control the animation, > via buttons, sliders, etc. > > I am certainly not a Python expert and have never worked with the > creation of a GUI. I would appreciate greatly any advice from those who > have worked with Python GUIs as to the best way to proceed. > > Thank you in advance, > V. Stokes I think Tkinter would be a good starting point. It is pretty simple to use and gives you lots of freedom to create whatever you want. It doesn't look as nice as some of the other GUI toolkits, but it is generally easier to work with. http://wiki.python.org/moin/TkInter Then again, you mention sliders, knobs, etc. I don't think Tkinter has alot of widgets built in. The other choice would be wxPython. It's got lots of built in widgets, and it looks pretty good. If you go this route, run the demo application to see what you have to work with. http://wxpython.org/ Good luck. ~Sean From simon at brunningonline.net Wed Sep 3 13:01:58 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 3 Sep 2008 18:01:58 +0100 Subject: Coming from .NET and VB and C In-Reply-To: References: Message-ID: <8c7f10c60809031001i39794ca4x1a3e4131408d3317@mail.gmail.com> 2008/9/3 ToPostMustJoinGroup22 : > Any suggestions for someone new to the scene like me? Welcome! There's a number of resources that you might find useful here: http://wiki.python.org/moin/BeginnersGuide -- Cheers, Simon B. From tjreedy at udel.edu Sat Sep 20 12:58:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Sep 2008 12:58:56 -0400 Subject: how can i check whether a variable is iterable in my code? In-Reply-To: <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> References: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> Message-ID: satoru wrote: > On Sep 20, 6:35 pm, Aidan wrote: >> satoru wrote: >>> hi, all >>> i want to check if a variable is iterable like a list, how can i >>> implement this? >> this would be one way, though I'm sure others exist: >> >> if hasattr(yourVar, '__iter__'): >> # do stuff > > thank you,but this will miss out sequences like string just because it > doesn't have an attribute named '__iter__' In 3.0, it does. Such consistency is one of the advantages of 3.0. In at least some 2.x's, str still uses the older __getitem__ iteration protocol. I am not sure about other built-in sequences. From pavlovevidence at gmail.com Fri Sep 12 17:46:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 12 Sep 2008 14:46:41 -0700 (PDT) Subject: Accessing __slots__ from C References: <8763p1799y.fsf@mulj.homelinux.net> Message-ID: On Sep 12, 10:01?am, Hrvoje Niksic wrote: > Chris writes: > >> descr = GetAttrString(cls,"varname"); > >> offset = descr->d_member->offset; > >> slotvar = (PyObject*)(((char*)obj)+offset) > > > Unfortunately, I am inexperienced at this kind of thing, so I wasn't > > able to get something working. Maybe someone could tell me what's > > wrong with the code below (it gives the error "'struct _object' has no > > member named 'd_member'")? > > You are getting that error because Carl forgot to cast the descriptor > to the appropriate C type, in this case PyMemberDescrObject. ?The last > line is also incorrect, I think. Yep, was in too much of a hurry to waste too much time showing how to do something slightly dubious. The offsetof() macro would help for the third line (in fact, it's the recommended standard way since there are some C implmentions, somewhere, that the pointer artithmetic method fails). Carl Banks From timr at probo.com Wed Sep 17 02:16:25 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 17 Sep 2008 06:16:25 GMT Subject: help on python SWIG C++ extension References: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> Message-ID: RLC wrote: > >I am new to python SWIG. Recently I wrote a small program trying to >import collada files(using colladadom) into python so I could use >python cgkit to render them. However, during the progressing, I got >some problems. Every time I quit from Python, I get a segmentation >fault, although the main program runs well. I suspect it is because I >wrapped std::vector objects in C struct and I did not release the >memory properly. That won't cause a segmentation fault. However, I notice that you are using "malloc" and "free" to allocate and free your objects. "stl" will use "new" and "delete", and it's not always healthy to mix them. If I were you, I'd replace this: > Vertex *v; > v = (Vertex *)malloc(sizeof(Vertex)); with this, which is less typing: Vertex * x = new Vertex; -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dudeja.rajat at gmail.com Tue Sep 2 10:32:07 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 2 Sep 2008 15:32:07 +0100 Subject: What is module initialization? In-Reply-To: <48bd4799$0$17215$426a74cc@news.free.fr> References: <48bd4799$0$17215$426a74cc@news.free.fr> Message-ID: > While this is technically legal, you should restrain yourself from doing > such a thing, unless you *really* know what you're doing and why. > >> but the variable is not getting updated in the module >> containing global symbols ( variables). > > I suspect you didn't use a qualified name when importing. You have to do it > this way : > > # myglobals.py: > answer = 42 > > # question.py > import myglobals > myglobals.answer = "WTF ?" > But if I do :- #question.py from myglobals import * myglobals.answer = "WTF ?" will this work? From shahmed at sfwmd.gov Wed Sep 10 11:22:16 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Wed, 10 Sep 2008 11:22:16 -0400 Subject: removing text string In-Reply-To: References: Message-ID: I need to remove text string from the list of the numbers mentioned below: 080829-7_A 070529-5_c 080824-7_O 070405_6_p The output will be : 080829-7 070529-5 080824-7 070405-6 Any idea is highly appreciated. From rridge at csclub.uwaterloo.ca Tue Sep 9 16:19:33 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 09 Sep 2008 16:19:33 -0400 Subject: universal unicode font for reportlab References: Message-ID: Terry Reedy wrote: >Sorry, I posted the wrong name. >Ariel Unicode MS is the one that seems pretty complete. ... > From the MS, I would guess that is a Windows font too ;-). It's made by Microsoft, but it's not a standard Windows font. I think it comes with Microsoft Office. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From sturlamolden at yahoo.no Thu Sep 25 07:02:10 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 04:02:10 -0700 (PDT) Subject: Linq to Python References: Message-ID: On 25 Sep, 12:06, hrishy wrote: > [code] > var stoogeGuys = > ? ? ?Beginning with the XML source > ? ? ?from xmlGuys in xmlSource.Descendants("Stooge") > ? ? ?Join to the array on the common element "stoogeName" > ? ? ?join arrayGuys in familyFacts > ? ? ? ? ? ?on xmlGuys.Element("stoogeName").Value equals arrayGuys.stoogeName > ? ? ?Join to the database on the common element "stoogeName" > ? ? ?join dbGuys in stoogeContext.stoogeTables > ? ? ? ? ? ?on xmlGuys.Element("stoogeName").Value equals dbGuys.stoogeName > ? ? ?select new > ? ? ?{ > ? ? ? ? firstName ? ?= dbGuys.stoogeName, > ? ? ? ? familyName ? = arrayGuys.familyName, > ? ? ? ? birthDate ? ?= xmlGuys.Element("birthDate").Value, > ? ? ? ? deathDate ? ?= xmlGuys.Element("deathDate").Value, > ? ? ? ? hairCutStyle = dbGuys.stoogeHaircut, > ? ? ?}; > [/code] It could e.g. look like this in Python: stoogeGuys = [] for xmlGuys in xmlSource.Descendants["Stooge"]: arrayGuys = familyFacts[xmlGuys.stoogeName] dbGuys = stoogeContext.stoogeTables[xmlGuys.stoogeName] stoogeGuys += \ [{'firstName': dbGuys.stoogeName, 'familyName': arrayGuys.familyName, 'birthDate': xmlGuys.birthDate, 'deathDate': dbGuys.deathDate, 'hairCutStyle': dbGuys.stoogeHaircut}] From aidan at gmail.com Sat Sep 20 06:35:52 2008 From: aidan at gmail.com (Aidan) Date: Sat, 20 Sep 2008 20:35:52 +1000 Subject: how can i check whether a variable is iterable in my code? In-Reply-To: References: Message-ID: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> satoru wrote: > hi, all > i want to check if a variable is iterable like a list, how can i > implement this? this would be one way, though I'm sure others exist: if hasattr(yourVar, '__iter__'): # do stuff From bignose+hates-spam at benfinney.id.au Fri Sep 26 03:13:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 26 Sep 2008 17:13:29 +1000 Subject: Writing a well-behaved daemon References: <874p43wl2m.fsf@benfinney.id.au> Message-ID: <87zllvv0py.fsf@benfinney.id.au> Sean DiZazzo writes: > Looks like somebody did the same thing I did and posted it. > > http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemon.py Thanks, I've not seen that before. It still seems loony to me that something this difficult to do right, yet so similar across different use cases, isn't in the standard library, where bugs need only be fixed in one place. -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but how will we get three pink flamingos into one | _o__) pair of Capri pants?? ?_Pinky and The Brain_ | Ben Finney From academicedgar at gmail.com Sat Sep 20 23:51:52 2008 From: academicedgar at gmail.com (academicedgar at gmail.com) Date: Sat, 20 Sep 2008 20:51:52 -0700 (PDT) Subject: BeautifulSoup and Problem Tables Message-ID: Hi I would appreciate some help. I am trying to learn Python and want to use BeautifulSoup to pull some data from tables. I was really psyched earlier tonight when I discovered that I could do this from BeautifulSoup import BeautifulSoup bst=file(r"c:\bstest.htm").read() soup=BeautifulSoup(bst) rows=soup.findAll('tr') len(rows) a=len(rows[0].findAll('td')) b=len(rows[1].findAll('td')) c=len(rows[2].findAll('td')) d=len(rows[3].findAll('td')) e=len(rows[4].findAll('td')) f=len(rows[5].findAll('td')) g=len(rows[6].findAll('td')) h=len(rows[8].findAll('td')) i=len(rows[9].findAll('td')) j=len(rows[10].findAll('td')) k=rows[1].findAll('td')[1].contents[0] So here I am chortling to myself thinking this is too easy. I know that the data columns are in rows[0] and so I can learn some more python to figure out how to create tuples so I can lable each data item using the row and column headings plucked from the contents. However, I discovered that my tables have inconsistent numbers of rows. Even though the tables look pretty. It might be that the column heading for the third column is "Apples" but the value for "Apples" in the fourth row is not in the third position in the row but the fourth. Now I am reluctant to make any assumptions because the tables were created inconsistently. What I mean is that in some tables if there is no value for a row/column intersection then there is a blank line, in other tables if there is no value for a row/column intersection then the length of k (as above) is 0. I have been Googling for some insight into this and I have not been successful finding anything. I would really appreciate any suggestions or some direction about how to better describe the problem. From tino at wildenhain.de Tue Sep 30 04:43:26 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 30 Sep 2008 10:43:26 +0200 Subject: Python script for tracert In-Reply-To: <46da4e770809292353o2d72091aj6e717e35e62cfce6@mail.gmail.com> References: <46da4e770809292353o2d72091aj6e717e35e62cfce6@mail.gmail.com> Message-ID: <48E1E6AE.8090408@wildenhain.de> cindy jones wrote: > Hello.. I'm trying to do a scripting for tracert in windows using python... > I'm using popen(), but it displays only after the tracert is completed. > i want the results to be displayed for every route. I believe "tracert" is a really ugly 8.3 abbrevivation of traceroute ;) Well, maybe an implementation in python itself could be of interest? http://mail.python.org/pipermail/python-list/2003-March/196063.html maybe there are more attempts - this one was just the first thing which popped up with g**gle. (The script is in the attachment). Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From mensanator at aol.com Sat Sep 20 12:27:10 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 20 Sep 2008 09:27:10 -0700 (PDT) Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) Message-ID: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> Beacuse in 2.6, Python apparently has fixed a discrepency that existed in previous versions. In the IDLE that comes with 2.5, typing "as", to wit "import random as ran", the words "import" and "as" highlight in red, so you can't use them as variable names or you'll get a syntax error. Ah, but you CAN use "as" for a variable: "for as in xrange(10): print as" works just fine, although it shouldn't. Python 2.6 fixes this discrepency and now gives you a syntax error if you use "as" for a variable name. The upshot is code (such as sympy) written prior to 2.6 can crash now due to this fix if said code inadverntently used what should have been a reserved word. I was able to fix the code for this "as" problem, but not the one that came after. I've reported this and interested parties can visit the sympy page and check Issue 1115. From gagsl-py2 at yahoo.com.ar Tue Sep 16 00:56:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 01:56:47 -0300 Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> Message-ID: En Mon, 15 Sep 2008 20:36:05 -0300, Michael Palmer escribi?: >> aditya shukla escribi?: >> >> > How can we convert .py files to batch files? is there any library for >> this? > > I assume you are on Windows? Let's assume you have a file stuff.py > that reads: > > import os > print os.listdir('.') # list current directory, good enough for > testing... > > Then, insert the following line at the top: > > @setlocal enableextensions & python -x %~f0 %* & goto :EOF > > Now save this file as stuff.cmd somewhere along your PATH. Now calling > 'stuff' should execute your file. Cool! I'd enclose the first argument in quotes "%~f0" - in case the path contains any whitespace. -- Gabriel Genellina From castironpi at gmail.com Thu Sep 4 15:45:33 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 12:45:33 -0700 (PDT) Subject: Safely move an element into a heap References: <778c30a9-f097-4789-b1d6-3b40a9f11bdf@p31g2000prf.googlegroups.com> Message-ID: <74bd29ee-ebe4-4ab7-a3ae-2935daf4776c@s20g2000prd.googlegroups.com> On Sep 4, 6:57?am, "Giampaolo Rodola'" wrote: > On 4 Set, 13:49, Alexandru Palade > wrote: > > > > > I'm not sure what you expect as an answer, but if you mean the heap as > > in the data structure, you can not just arbitrarily move one key where > > you want as it will destroy the heap property. > > > Giampaolo Rodola' wrote: > > > Hi, > > > I wanted to know if does exist a safe way to, given a heap, move an > > > arbitrary element to the first position of the heap. > > > Something like: > > > > ?>>> heap = [0,3,6,8,10] > > > ?>>> heapq.move_to_first_position(heap, 4) > > > ?>>> heap = [10, 0,3,6,8] > > > > --- Giampaolo > > >http://code.google.com/p/pyftpdlib/ > > > -- > > >http://mail.python.org/mailman/listinfo/python-list-Nascondi testo citato > > > - Mostra testo citato - > > Could I be able to do that if every element I want to move will have > the value of 0 which is the smallest value I can have into my heap? > What I'm trying to do is implementing a timeout: sometimes I want a > given event which was scheduled to happen within X seconds to happen > immediately. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ Change its timeout to -1 and reheapify. Or maintain 'zeroes' in a separate structure. From fredo66 at fulladsl.be Thu Sep 25 04:03:15 2008 From: fredo66 at fulladsl.be (fredo66 at fulladsl.be) Date: Thu, 25 Sep 2008 01:03:15 -0700 (PDT) Subject: python sorting 2dim. array ? Message-ID: <9684e81b-df99-4d95-99f9-8345c125b69b@d77g2000hsb.googlegroups.com> hello, Can someone help me with this: I have a array like this list[rowindex][colomindex] where rows are the records and colom the fields. If I use the .sort() method on 'list' the data is sorted on the items of the first colom. But I want to sort on the second colom as first (and as second sortfield the first colom). What is the shortest code for this pls ? (all fields are text value, first colom is name, second category) From aahz at pythoncraft.com Sun Sep 21 00:24:50 2008 From: aahz at pythoncraft.com (Aahz) Date: 20 Sep 2008 21:24:50 -0700 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: In article , Thomas G. Willis wrote: >On Sep 20, 5:23=A0am, candide wrote: >> >> Excerpt quoted fromhttp://www.astro.ufl.edu/~warner/prog/python.html: >> >> "About Python: Python is a high level scripting language with object >> oriented features. >> (...) >> Python supports OOP and classes to an extent, but is not a full OOP >> language." >> >> Thanks for any comment. > >My comment is "Who cares?" > >I was always under the impression that if any language truly was "OO" >it would be smalltalk. And I don't derive any benefit from smalltalk >at all. I do however derive substantial benefit from other languages >that "OO zealots" would likely poo poo on including python. "...some experts might say a C++ program is not object-oriented without inheritance and virtual functions. As one of the early Smalltalk implementors myself, I can say they are full of themselves." --zconcept -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From mauriceling at gmail.com Sun Sep 7 09:50:10 2008 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Sun, 7 Sep 2008 06:50:10 -0700 (PDT) Subject: [ANN] The Python Papers Vol 3 Iss 2 in one PDF Message-ID: Hi everyone Our original release of TPP Volume 3 Issue 2 is in the form of one PDF per article. A number of readers had kindly requested for a parallel release for the entire issue in a single PDF for easy transport. Despite prevalent "industrial standards" for one PDF per article such as IEEE and ACM, we can understand our readers' point of view. We can see mutually exclusive advantages of both system - one PDF per article allows for tracking of view counts for each article whereas one PDF per issue allows for easy transport and offline browsing. Therefore, we had chose to released the entire volume as a single PDF in parallel and will continue to do so in future. The entire Volume 2 Issue 3 can be accessed from http://www.pythonpapers.org. We look forward to your continued support and contributions. Regards Maurice Ling Co-EIC, TPPA From michel at nospam.please Mon Sep 15 15:21:16 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:21:16 +0200 Subject: Python Nautilus script Message-ID: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> Hi, I'm trying to write a python script for Nautilus. To get the list of files selected in the Nautilus right pane, you use the $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS environment variable which is normally available to the script. Actually, it works with bash scripts but not with python scripts import os files = os.environ['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'].splitlines() gives a: File "", line 1, in File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ raise KeyError(key) KeyError: 'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' Fredrik Lundh explained me that all environment variables are not accessible from subprocesses of an application. So my question is how can I get the Nautilus selected files in a python script? Thanks, Michel -- Michel Leunen http://linux.leunen.com From steve at holdenweb.com Fri Sep 12 08:16:08 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 08:16:08 -0400 Subject: lacking follow-through In-Reply-To: <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> Message-ID: castironpi wrote: > On Sep 7, 5:03 pm, Marc 'BlackJack' Rintsch wrote: >> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: >>> This is the strangest post I've seen >>> since I've joined this list (only >>> recently). What the ? >> Yeah, castironpi sometimes doesn't make much sense. Maybe because it's a >> bot!? :-) >> >> Ciao, >> Marc 'BlackJack' Rintsch > > No, I'm legit, and I believe my complaint is. That's all I can > guarantee anyway. While I'm still not a vet on Usenet, I'm still > disappointed so far. Though I should be flattered for my logic to be > ever compared to an A.I.'s. > Your various outpourings appear so rambling and ill-conceived that silence is often the only polite response. If you are flattered to be compared to an AI you must come from the same race as Mr. Spock in Star Trek. > Maybe the ideas are not that groundbreaking, but they still have been > dropped instead of critiqued. Problem. You aren't entitled to require discussion of your ideas and proposals. The usual way of obtaining responses is to engage in a dialog, responding intelligently and directly to any criticism or discussion. But it's often difficult to discern what point you are trying to make. This may be a linguistic issue, or it may be because you are running some bizarre experiment. The jury appears to still be out on that question. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From moogyd at yahoo.co.uk Sun Sep 14 05:29:52 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sun, 14 Sep 2008 02:29:52 -0700 (PDT) Subject: noob: subprocess clarification Message-ID: <68fcdea2-804e-4fba-958e-47ecee277faf@s50g2000hsb.googlegroups.com> Hi, I generally use csh scripts for generally scripting (controlling simulations). Basically the script processing options, generates the command line, executes it and then processes the results. I would usually use the -f option on the shebang line to ensure that the environment from the current shell is used. i.e. #!/bin/csh -f How do I acheive this in python? I have been looking at the import subprocess as sub p = sub.Popen(['echo $PATH'],shell=True).wait() This *seems* to do what I want (in that the path looks correct), but I don't really understand the documentation. Can somebody please clarify what the shell=True does, and whether I am using it correctly. Thanks, Steven From dave.dibiase at gmail.com Thu Sep 25 23:57:06 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Thu, 25 Sep 2008 23:57:06 -0400 Subject: Fastest way to max() list Message-ID: I have a list with about 1000-1500 sub-lists which look like so: list[-0.28817955213290786, 3.6693631467403929, 'H', 31.31225233035784]] The first and second values are Angstrom units specifying the location of a particle. What I'd like to do is determine the distance between the smallest and largest value in the arrays first position 0. I tried reading the manual for this but I don't see how it applies key or any of those other commands to the function. I could easily write a sort to do this and capture the first and last spots, but why do that when I can use max and min (if I can actually do that...). So you wonderful Python gods, lay some knowledge on me. please? lol... while I'm at it, is there a way to modify an entire list without having to produce a whole new one? For example now say I want to modify list[0] and multiply it by some value. From what I understand previous version of Python allowed lists to be multiplied like matrices...now apparently it just replicates the list. :-/ shucks... The first question would be useful to know, but the second question I do quite a bit of and the "best practice" would be really great to know! Thanks in advanced! -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitry at athabascau.ca Thu Sep 25 15:36:16 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 19:36:16 GMT Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> <48dbc82e$0$1120$426a74cc@news.free.fr> <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: >> I kept this part of the problem out of this discussion as I'm pretty sure >> I can fill those in once I figure out the basic problem of >> auto-population of proxy methods since for each class/method those are >> going to be nearly identical. If I can autogenerate those on-the-fly I'm >> pretty sure I can add some extra-logic to them as well including >> signature change where A::bmethod(self,c,x) would become >> A::bmethod(self,x) etc. > > Do you want to couple instances or classes together? It would be nice to have objects of B, C and D classes not knowing that they are proxied (as they are used on their own too, not only inside of A objects). > If A always proxies for B, C, and D, then the wrapper solution isn't > bad. the whole purpose of A is pretty much to proxy and filter. It's got some extra logic to combine and manipulate b, c and d objects inside of A class objects. > If you're going to be doing any instance magic, that can change > the solution a little bit. > > There's also a revision of the first implementation of Aproxy you > posted, which could stand alone as you have it, or work as a > classmethod or staticmethod. > > def Aproxy(fn): > def delegate(self,*args,**kw): > print "%s::%s" % (args[0].__class__.__name__,fn.__name__) > fnew=getattr(self.b,fn.__name__) > return fnew(*args,**kw) > setattr(A,fn.__name__,delegate) > return fn yep, that does look nicer/cleaner :) From invalid at invalid Mon Sep 15 16:40:50 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 15 Sep 2008 15:40:50 -0500 Subject: append on lists References: Message-ID: <2ZKdnYWXv5bPVVPVnZ2dnUVZ_vGdnZ2d@posted.visi> On 2008-09-15, Armin wrote: >> Because .append() mutates 'a' and appends the item in-place rather >> than creating and returning a new list with the item appended, and >> it's good Python style for mutating methods to have no return value >> (since all functions must have some return value, Python uses None >> when the function doesn't explicitly return anything). > > Yes, but this is very unconvenient. Aw, admit it -- it's not _that_ inconvenient. > If d should reference the list a extended with a single list > element you need at least two lines > > a.append(7) > d=a With that usage it's obvious that a is mutated, and now both "a" and "d" are bound to the same extended list. > and not more intuitive d = a.append(7) Becase that usage implies (at least to many of us) that "a" is unchanged, and that "d" is now bound to a different object than "a". -- Grant Edwards grante Yow! Where's th' DAFFY at DUCK EXHIBIT?? visi.com From joncle at googlemail.com Wed Sep 10 12:20:33 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 09:20:33 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: Message-ID: <82f4dc99-0027-4c9a-b2b9-42b959a8d510@y38g2000hsy.googlegroups.com> On 10 Sep, 16:28, hofer wrote: > Hi, > > Let's take following perl code snippet: > > %myhash=( one ?=> 1 ? ?, two ? => 2 ? ?, three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' ? : 1 ? ?, 'two' ? : 2 ? ?, 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as ?split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] > > print "%s\n%s\n%s" %(v1,v2,v3) > > thanks for any ideas Another option [note I'm not stating it's preferred, but it would appear to be closer to some syntax that you'd prefer to use....] >>> from operator import itemgetter >>> x = { 'one' : 1, 'two' : 2, 'three' : 3 } >>> itemgetter('one', 'one', 'two')(x) (1, 1, 2) hth Jon. From circularfunc at yahoo.se Wed Sep 17 12:29:47 2008 From: circularfunc at yahoo.se (cnb) Date: Wed, 17 Sep 2008 09:29:47 -0700 (PDT) Subject: python-mode problem, doesnt load whole module? Message-ID: <9b26d9fd-3fe2-4d58-acce-015923d31b50@d1g2000hsg.googlegroups.com> >>> a = parsing.unserialize("C:/users/saftarn/desktop/twok.txt") Traceback (most recent call last): File "", line 1, in File "C:\Python25\Progs\NetflixRecSys\parsing.py", line 91, in unserialize return pickle.load(open(filename, 'r')) File "C:\Python25\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python25\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python25\lib\pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "C:\Python25\lib\pickle.py", line 1126, in find_class klass = getattr(mod, name) if i use the python-gui-editor-repl it works though... so isn't emacs loading modules properly? this shouldnt have to do with emacs itself though, right? From mensanator at aol.com Thu Sep 4 13:57:35 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 4 Sep 2008 10:57:35 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> Message-ID: <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> On Sep 4, 2:05?am, Thomas Bellman wrote: > Mensanator wrote: > > No, but blank cells are 0 as far as Excel is concerned. > > That behaviour causes nothing but trouble and I am > > saddened to see Python emulate such nonsense. > > Then you should feel glad that the Python sum() function *does* > signal an error for the closest equivalent of "blank cells" in > a list: > > ? ? >>> sum([1, 2, 3, None, 5, 6]) > ? ? Traceback (most recent call last): > ? ? ? File "", line 1, in > ? ? TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' Yes, I am in fact happy to see that behaviour. > > Summing the elements of an empty list is *not* the same thing as > summing elements of a list where one element is None. So, >>> sum([1, 2, 3, None, 5, 6]) Traceback (most recent call last): File "", line 1, in sum([1, 2, 3, None, 5, 6]) TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' gives me an error. As does >>> sum([None, None, None, None, None, None]) Traceback (most recent call last): File "", line 1, in sum([None, None, None, None, None, None]) TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' Why then, doesn't >>> sum([A for A in [None, None, None, None, None, None] if A != None]) 0 give me an error? Ok, it's not a bug. "This behaviour is by design." - Microsoft Knowledge Base I don't like it, but I guess I'll just have to live with it. > > > There are no "empty" boxes. There are only boxes with > > known quantities and those with unknown quantities. > > I hope that's not too ivory tower. > > The sum() function in Python requires exactly one box. ?That box > can be empty, can contain "known quantities" (numbers, presumably), > or "unknown quantities" (non-numbers, e.g., None). ?But you can't > give it zero boxes, or three boxes. > > I don't have a strong view of whether sum([]) should return 0 or > raise an error, but please do not mix that question up with what > a sum over empty cells or over NULL values should yield. ?They > are very different questions. Ok, but I don't understand why an empty list is a valid sum whereas a list containing None is not. > > As it happens, the SQL sum() function (at least in MySQL; I don't > have any other database easily available, nor any SQL standard to > read) does return NULL for a sum over the empty sequence, so you > could argue that that would be the correct behaviour for the > Python sum() function as well, but you can't argue that because a > sum *involving* a NULL value returns NULL. I'm not following that. Are you saying a query that returns no records doesn't have a specific field containg a Null so there are no Nulls to poison the sum? ...tap...tap...tap. Ok, I can see that, but you don't get 0 either. > > -- > Thomas Bellman, ? Lysator Computer Club, ? Link?ping University, ?Sweden > "This isn't right. ?This isn't even wrong." ?! ?bellman @ lysator.liu.se > ? ? ? ? ? ? ? ? ? ? ? ? ?-- Wolfgang Pauli ? ! ?Make Love -- Nicht Wahr! From larudwer at freenet.de Sat Sep 6 09:02:42 2008 From: larudwer at freenet.de (Ruediger) Date: Sat, 06 Sep 2008 15:02:42 +0200 Subject: why is self not passed to id()? References: Message-ID: I found following solution to the problem. Instead of assigning id directly to __hash__ it has to be wrapped with an instancemethod object. It is somehow strange that this doesn't happen automatically and it is also strange that instancemethod isn't exposed in the type module. However it can easily be done and is speeding things up by almost an factor of 2. Thank's again for all the help. R?diger ****************************************************************** class foo(list): __hash__ = lambda x: id(x) instancemethod = type(foo.__hash__) class bar(list): pass bar.__hash__ = instancemethod(id, None, bar) def test0( obj ): _s_ = set() _s_add = _s_.add _s_pop = _s_.pop for _i_ in xrange(1000000): _s_add(obj()) _s_pop() def test1(): return test0(foo) def test2(): return test0(bar) if __name__ == '__main__': test1() test2() pass ****************************************************************** python -m cProfile test01.py 6000010 function calls in 30.547 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 30.547 30.547 :1() 1 0.000 0.000 30.547 30.547 test01.py:1() 1 0.000 0.000 0.000 0.000 test01.py:1(foo) 2 10.784 5.392 30.547 15.273 test01.py:10(test0) 1 0.000 0.000 19.543 19.543 test01.py:18(test1) 1000000 4.554 0.000 6.700 0.000 test01.py:2() 1 0.000 0.000 11.003 11.003 test01.py:20(test2) 1 0.000 0.000 0.000 0.000 test01.py:6(bar) 1 0.001 0.001 30.547 30.547 {execfile} 1000000 2.146 0.000 2.146 0.000 {id} 2000000 8.626 0.000 15.327 0.000 {method 'add' of 'set'objects} 2000000 4.436 0.000 4.436 0.000 {method 'pop' of 'set'objects} From jeffober at gmail.com Mon Sep 22 16:04:31 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 22 Sep 2008 13:04:31 -0700 (PDT) Subject: Job queue using xmlrpc and threading References: Message-ID: Try using the Queue module - http://docs.python.org/lib/module-Queue.html. Here is a tutorial with it - http://www.artfulcode.net/articles/multi-threading-python/. From gagsl-py2 at yahoo.com.ar Tue Sep 30 17:55:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 18:55:27 -0300 Subject: Python script for tracert References: <46da4e770809292353o2d72091aj6e717e35e62cfce6@mail.gmail.com> Message-ID: En Tue, 30 Sep 2008 03:53:21 -0300, cindy jones escribi?: > Hello.. I'm trying to do a scripting for tracert in windows using > python... > I'm using popen(), but it displays only after the tracert is completed. i > want the results to be displayed for every route. > > can anyone help me in this.. Use the subprocess module: import subprocess host = 'www.microsoft.com' p = subprocess.Popen(["tracert", '-d', '-w', '100', host], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: line = p.stdout.readline() if not line: break print '-->',line, p.wait() -- Gabriel Genellina From rcdailey at gmail.com Thu Sep 4 18:15:16 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Sep 2008 17:15:16 -0500 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> Message-ID: <496954360809041515me9bd5cbj39a830fb854340e6@mail.gmail.com> On Thu, Sep 4, 2008 at 5:14 PM, Robert Dailey wrote: > Hi, > > I currently have a dictionary object that I'm doing the following with: > > if lib not in stage_map: > # ... do stuff ... > > However, this will perform a case-sensitive comparison between lib and each > key in stage_map. Is there a way to make this do a case-insensitive > comparison instead? Yes, I realize I could do this: > > if lib not in [key.lower() for key in stage_map] > > However, I don't want to do this because it'll quickly end up getting > messy. I want this solution to be an absolute last resort. I'm not a pro > with python, so I'm hoping there are cleaner alternatives out there. Thanks. > I forgot to mention that I'm using Python 3.0 beta 2. -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Thu Sep 4 18:38:03 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 00:38:03 +0200 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> Message-ID: <200809050038.04108.maric@aristote.info> Le Friday 05 September 2008 00:14:37 Robert Dailey, vous avez ?crit?: > Hi, > > I currently have a dictionary object that I'm doing the following with: > > if lib not in stage_map: > # ... do stuff ... > > However, this will perform a case-sensitive comparison between lib and each > key in stage_map. Is there a way to make this do a case-insensitive > comparison instead? Yes, I realize I could do this: > > if lib not in [key.lower() for key in stage_map] > This is the normal python way to compare string without case, and the idiom is not surprising. You''ll often see for loops written like this : for i in (e for e in iterable if predicate(e)) : ... > However, I don't want to do this because it'll quickly end up getting > messy. I want this solution to be an absolute last resort. I'm not a pro > with python, so I'm hoping there are cleaner alternatives out there. If you fell hard to read you can break it on two lines : lowered_keys = (key.lower() for key in stage_map) if lib.lower() not in lowered_keys : .... BTW, it's string manipulation, it's normal it takes more than one brain cycle to achieve. Try the regexp solution and make your choice, more than often, I keep the straightforward, "read as pseudo-code", python expression. -- _____________ Maric Michaud From gagsl-py2 at yahoo.com.ar Tue Sep 9 14:53:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 15:53:03 -0300 Subject: Unable to start a process with subprocess Popen() References: <3657eb2f-c827-4929-be5a-689959de5f85@a1g2000hsb.googlegroups.com> Message-ID: En Mon, 08 Sep 2008 13:35:21 -0300, escribi?: > cmd = subprocess.Popen([batchFilePath], \ > shell = True, \ > stdin = subprocess.PIPE, > stdout = subprocess.PIPE, \ > stderr = subprocess.PIPE \ > ) > cmd.stdin.close() > outPipe, errPipe = PipeThread(cmd.stdout), > PipeThread(cmd.stderr) > outPipe.run(), errPipe.run() > retcode = cmd.wait() > out, err = outPipe.getOutput(), errPipe.getOutput() > > Although, this solved my problem. But I know there is no need for using > threading in this problem. This problem could've been solved just by the > subprocess module. > > I'm unnecessarily using the threading module. Not only that, you're misusing the Thread class. To actually create a separate execution thread, you should call outPipe.start() instead of outPipe.run() (same for errPipe). Note that if your batch file emits a large output it really may be necesary to use a separate thread to read the output. -- Gabriel Genellina From steve at holdenweb.com Tue Sep 30 07:07:18 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Sep 2008 07:07:18 -0400 Subject: What is not objects in Python? In-Reply-To: References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <00f15dd2$0$20617$c3e8da3@news.astraweb.com> Message-ID: Terry Reedy wrote: > Steven D'Aprano wrote: >> On Mon, 29 Sep 2008 05:41:02 -0700, George Sakkis wrote: >> >>> For example I would be much less >>> opposed to len() being defined as, say, |x| if "|...|" was a valid >>> operator. >> >> Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians >> and physicists. > > It should be both, just as + is addition for numbers and concatenation > for sequences. Or we could have just one built-in -- size() instead of > abs() and len(). For non-sequence collections, size() would be better > than len() anyway. > And how are these "non-sequence collections" to be distinguished? And how does size() differ from len() in that case? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From cjw at ncf.ca Sat Sep 6 20:08:20 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Sep 2008 20:08:20 -0400 Subject: Learning Python In-Reply-To: References: Message-ID: James Pilling wrote: > Hi im currently starting to learn python in sixth form at school any tips? > > ____________________________________________________________ > GET FREE 5GB EMAIL - Check out spam free email with many cool features! > Visit http://www.inbox.com/email to find out more! There are suggestions here: http://wiki.python.org/moin/PythonBooks Good luck, Colin W. From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 02:49:18 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Mon, 15 Sep 2008 23:49:18 -0700 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: References: Message-ID: > On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal wrote: >> I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that >> key as string. Is there any way to convert the said instance into string? Take a look at as_pem() method. -- Heikki Toivonen From deets at nospam.web.de Tue Sep 2 15:06:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Sep 2008 21:06:58 +0200 Subject: How to write verbose scripts In-Reply-To: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: <6i5h6jFop62lU1@mid.uni-berlin.de> Steven D'Aprano schrieb: > I find myself writing command line tools in Python where I wish to > include "verbose" output to stdout. > > I start with a helper function: > > > def print_(obj, level=0): > if _verbosity >= level: > print obj > > > And then I end up with functions or methods looking like this: > > > def parrot(x) > print_("precondition", level=2) > do_something() > print_("status is good...", level=1) > print_("parrot is squawking strongly now", level=2) > do_something_else() > print_("squawk squawk squawk", level=3) > do_more() > print_("postcondition", level=1) > return something > > > That often means that my functions end up with more message printing code > than actual code. The whole thing seems messy and hard to manage for all > but the smallest scripts. > > Worst of all, sometimes the messages I wish to print may be expensive to > compute, and I don't want to waste time computing them if they aren't > going to be printed because the verbosity is too low. But nor do I wish > to fill my code with this: > > if _verbosity >= 3: > x = calculate_complicated_thing() > print_(x, level=3) > > > > Is there a better way of doing this than the way I am going about it? I use the logging-module. Regarding the expensive computations: maysomething like this help: class DeferredToString(object): def __init__(self, func): self.func = func def __repr__(self): return repr(self.func()) def __str__(self): return str(self.func()) dts = DeferredToString Because then you can do logger.debug("Some text for an: %r", dts(lambda: long_computation())) Because AFAIK the string is only interpolated if the logging level is actually put out. Diez From rmacneill at gmail.com Thu Sep 18 19:10:02 2008 From: rmacneill at gmail.com (rmac) Date: Thu, 18 Sep 2008 16:10:02 -0700 (PDT) Subject: Python newbie question re Strings and integers Message-ID: the following code attempts to extract a symbol name from a string: extensionStart = int(filename.rfind('.')) filenameStart = int(filename.rfind('/')) #print 'Extension Start - ' + str(extensionStart) #print 'FileName Start - ' + str(filenameStart) currentSymbol=filename[int(filenameStart),int(extensionStart)] Uncommenting the print statements clearly show the values to be integers (and without the str casts actually provide int+string errors) However, executing this code results in... opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv Traceback (most recent call last): File "rHistFileToDB_Equities.py", line 25, in currentSymbol=filename[int(filenameStart),int(extensionStart)] TypeError: string indices must be integers Running Python 2.5.2_5 on OSX From tedpottel at gmail.com Mon Sep 8 12:24:17 2008 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Mon, 8 Sep 2008 09:24:17 -0700 (PDT) Subject: Trying to make a spider using mechanize Message-ID: Hi, I can read the home page using the mechanize lib. Is there a way to load in web pages using filename.html instad of servername/ filename.html. Lots of time the links just have the file name. I'm trying to read in the links name and then vsit those pages. here is the sample code I am ussing. import ClientForm import mechanize #get home page request = mechanize.Request("http://www.activetechconsulting.com") response = mechanize.urlopen(request) print response.read() #sub page (this does note work) request = mechanize.Request("service.html") response = mechanize.urlopen(request) print response.read-Ted From sebastianthegreatful at gmail.com Thu Sep 18 03:57:23 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Thu, 18 Sep 2008 00:57:23 -0700 (PDT) Subject: ssl server References: <7ac8d302-0dae-4f19-81a9-8926c6b22a01@26g2000hsk.googlegroups.com> Message-ID: <0ea6046a-dea2-419f-95ce-2b56ae71ca9e@k30g2000hse.googlegroups.com> On Sep 17, 10:53?pm, "Giampaolo Rodola'" wrote: > On 17 Set, 19:33, Seb wrote: > > > > > I'm making a ssl server, but I'm not sure how I can verify the > > clients. What do I actually need to place in _verify to actually > > verify that the client cert is signed by me? > > > ?50 class SSLTCPServer(TCPServer): > > ?51 ? ? ? ? keyFile = "sslcert/server.key" > > ?52 ? ? ? ? certFile = "sslcert/server.crt" > > ?53 ? ? ? ? def __init__(self, server_address, RequestHandlerClass): > > ?54 ? ? ? ? ? ? ? ? ctx = SSL.Context(SSL.SSLv23_METHOD) > > ?55 ? ? ? ? ? ? ? ? ctx.use_privatekey_file(self.keyFile) > > ?56 ? ? ? ? ? ? ? ? ctx.use_certificate_file(self.certFile) > > ?57 ? ? ? ? ? ? ? ? ctx.set_verify(SSL.VERIFY_PEER | > > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > > self._verify) > > ?58 ? ? ? ? ? ? ? ? ctx.set_verify_depth(10) > > ?59 ? ? ? ? ? ? ? ? ctx.set_session_id('DFS') > > ?60 > > ?61 ? ? ? ? ? ? ? ? self.server_address = server_address > > ?62 ? ? ? ? ? ? ? ? self.RequestHandlerClass = RequestHandlerClass > > ?63 ? ? ? ? ? ? ? ? self.socket = socket.socket(self.address_family, > > self.socket_type) > > ?64 ? ? ? ? ? ? ? ? self.socket = SSL.Connection(ctx, self.socket) > > ?65 ? ? ? ? ? ? ? ? self.socket.bind(self.server_address) > > ?66 ? ? ? ? ? ? ? ? self.socket.listen(self.request_queue_size) > > ?67 > > ?68 ? ? ? ? def _verify(self, conn, cert, errno, depth, retcode): > > ?69 ? ? ? ? ? ? ? ? return not cert.has_expired() and > > cert.get_issuer().organizationName == 'DFS' > > What library are you using? PyOpenSSL? > In that case I think you'll have more luck by posting on their mailing > list. Thanks, I did that and it worked. From tino at wildenhain.de Wed Sep 10 10:51:13 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 10 Sep 2008 16:51:13 +0200 Subject: Alternatives to traditional RDBMS In-Reply-To: References: Message-ID: <48C7DEE1.8010208@wildenhain.de> James Mills wrote: ... > Are there any others out there ? > Is anyone working on something ? > > I would like to continue my work > on buzhug... I have so: > * Fixed several bugs > * Implemented a WSGI middleware layer > > I'd like to refactor a lot of it's code > and make better use of more recent > features of python as buzhug was > written quite some time ago. I think > it's "protocol" could be vastly improved > as well - as pickling things doesn't > always work so well... > > In addition, I think buzhug could do > with some caching features to speed > database operations up (they're already > pretty fast). Looks as you didn't mention ZODB yet. As it is actively developed, it is maybe something you could consider. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From dear.jay.logan at gmail.com Mon Sep 1 09:00:00 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 1 Sep 2008 06:00:00 -0700 (PDT) Subject: Python 3.0b2 cannot map '\u12b' References: <6i24u3Fo7morU2@mid.uni-berlin.de> Message-ID: <8c812bc2-5d44-4818-81f0-ffba8fe39042@m73g2000hsh.googlegroups.com> On Sep 1, 8:19?am, Marc 'BlackJack' Rintsch wrote: > On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: > > I doubt the OP 'chose' cp437. ?Why does Python using cp437 even when the > > default encoding is utf-8? > > > On WinXP > > ?>>> sys.getdefaultencoding() > > 'utf-8' > > ?>>> s='\u012b' > > ?>>> s > > Traceback (most recent call last): > > ? ?File "", line 1, in > > ? ?File "C:\Program Files\Python30\lib\io.py", line 1428, in write > > ? ? ?b = encoder.encode(s) > > ? ?File "C:\Program Files\Python30\lib\encodings\cp437.py", line 19, in > > encode > > ? ? ?return codecs.charmap_encode(input,self.errors,encoding_map)[0] > > UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in > > position > > 1: character maps to > > Most likely because Python figured out that the terminal expects cp437. ? > What does `sys.stdout.encoding` say? > > > To put it another way, how can one 'choose' utf-8 for display to screen? > > If the terminal expects cp437 then displaying utf-8 might give some > problems. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch So, it is not a problem with the program, but a problem when I print it out. sys.stdout.encoding does say cp437. Now, when I don't print anything out, the program hangs. I will try this again and let the board know the results. Thanks for all of your insight. From darcy at druid.net Sat Sep 27 19:19:34 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 27 Sep 2008 19:19:34 -0400 Subject: Hello boys! In-Reply-To: References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> Message-ID: <20080927191934.1c3290ea.darcy@druid.net> On Sat, 27 Sep 2008 18:47:16 -0400 default wrote: > On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko > wrote: > > >Hello, this is Milenko Stojadinovic from town Banjaluka, > > Come to the US and park your mouth in front of George Bush - all the > Bshit you can eat - and it keeps on coming! What's the point of killfiling Google Groups if people like you are just going to respew this crap. Please consider the Delete key next time. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From wegwerp at gmail.com Fri Sep 26 15:54:11 2008 From: wegwerp at gmail.com (Bas) Date: Fri, 26 Sep 2008 12:54:11 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> Message-ID: I only have experience with the matlab version of polar, but my wild guess is that you have convert your degrees to radians. Go to the Matplotlib newsgroup if you need any better help. HTH, Bas From steven at REMOVE.THIS.cybersource.com.au Fri Sep 26 04:25:44 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 08:25:44 GMT Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> <48dc962a$0$2289$426a74cc@news.free.fr> Message-ID: On Fri, 26 Sep 2008 09:58:39 +0200, Bruno Desthuilliers wrote: >> "Procedural" is the opposite of "functional", not "object-oriented". > > AFAIK, the "opposite" if functional is imperative, not procedural. But > let's not waste too much time on terminology arguments... We're not wasting time on terminology arguments, we're wasting time on definitional debates. -- Steven From ggpolo at gmail.com Wed Sep 17 14:20:06 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 17 Sep 2008 15:20:06 -0300 Subject: Tkinter Label 'justify' Problem In-Reply-To: <8c8a2d86-007b-4e38-b0fc-bc6385b3a77a@t54g2000hsg.googlegroups.com> References: <8c8a2d86-007b-4e38-b0fc-bc6385b3a77a@t54g2000hsg.googlegroups.com> Message-ID: On Wed, Sep 17, 2008 at 2:18 PM, Dude wrote: > Hi All, > I am fairly new to Python programming. I am working on a small > Tkinter project and I think I am missing something, maybe you can > help. The two lines below is all I have related to the Label widget: > > lblServer = Tkinter.Label(serverFrame, text='Server:', fg='black', > justify='left', relief='groove') > > lblServer.place_configure(width=200, bordermode='inside') > > > No matter what I change the 'justify' to whether it's 'lef', 'right', > or 'center', it always seems to be in the center. The "justify" option comes into play only when you have a multi-line label, which is not the case. If you want it left/right aligned then use pack (instead of place, not really recommended but I don't know what you are doing) and specify the anchor option with an appropriate value ('e' or 'w') for what you want. > > I am also writing the keys from the Label widget to a file because > this has me so baffled. That is below. > > Thank in advance for any help or direction you can give me. > > Steve P > > ---------- lblServer keys ----------------- > activebackground : SystemButtonFace > activeforeground : SystemButtonText > anchor : center > background : SystemButtonFace > bd : 2 > bg : SystemButtonFace > bitmap : > borderwidth : 2 > compound : none > cursor : > disabledforeground : SystemDisabledText > fg : black > font : {MS Sans Serif} 8 > foreground : black > height : 0 > highlightbackground : SystemButtonFace > highlightcolor : SystemWindowFrame > highlightthickness : 0 > image : > justify : left > padx : 1 > pady : 1 > relief : groove > state : normal > takefocus : 0 > text : NNTP Server: > textvariable : > underline : -1 > width : 0 > wraplength : 0 > ---------- lblServer keys END ------------- > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From castironpi at gmail.com Mon Sep 22 21:28:37 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 18:28:37 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: On Sep 22, 8:13?pm, process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. I didn't think this through completely-- is it incompatible with closures and local function definitions? def f( m ): def g( n ): return m+ n stuff( ) return g( 0 ) In this case, the stack, growing up: g f main is not equivalent to: g main in the last step, due to the local definition of 'm' in 'f'. From bearophileHUGS at lycos.com Mon Sep 22 22:10:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 19:10:35 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <00e45101$0$20331$c3e8da3@news.astraweb.com> <773db59e-40c6-470e-b616-ca8715efa46a@d77g2000hsb.googlegroups.com> <00e82140$0$20303$c3e8da3@news.astraweb.com> Message-ID: <80294675-b318-4b8d-b963-5a1b8fb225f1@k30g2000hse.googlegroups.com> Steven D'Aprano: >I'm sorry, I don't recognise leniter(). Did I miss something?< I have removed the docstring/doctests: def leniter(iterator): if hasattr(iterator, "__len__"): return len(iterator) nelements = 0 for _ in iterator: nelements += 1 return nelements >it doesn't work for arbitrary iterables, only sequences (lazy or otherwise)< I don't understand well. >Since you're generating the entire length anyway, len(list(iterable)) is more readable and almost as efficient for most practical cases.< I don't agree, len(list()) creates an actual list, with lot of GC activity. >But the expected semantics of __len__ is that it is expected to return an int, and do it quickly with minimal effort. Methods that do something else are an abuse of __len__ and should be treated as a bug.< I see. In the past I have read similar positions in discussions regarding API of data structures in D, so this may be right, and this fault may be enough to kill my proposal. But I'll keep using leniter(). Bye, bearophile From tjreedy at udel.edu Mon Sep 29 14:25:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 14:25:43 -0400 Subject: What is not objects in Python? In-Reply-To: <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> Message-ID: George Sakkis wrote: > Sure, "len" looks better than lambda x:x.__len__(), but the same would > be true if there was an "upper" builtin for the following example: > >>>> s = ['a', 'd', 'B', 'C'] >>>> s2 = [u'a', u'd', u'B', u'C'] >>>> upper = lambda x: x.upper() >>>> sorted(s, key=upper) > ['a', 'B', 'C', 'd'] >>>> sorted(s2, key=upper) > [u'a', u'B', u'C', u'd'] > > No difference in principle, just len() happens to be implemented more > often than upper(). I disagree. One versus many classes is a principle. If a method is used on objects of just one class, the class attribute can be used and passed directly. sorted(s, key = str.upper) sorted(s2, key = unicode.upper) The problem is having two text classes, which Guido considers to be a mess and which Python did not have originally and which 3.0 also does not have, even though bytes keeps the string methods. Mixing int, long, and float numbers is or should be more common than mixing str and unicode strings, and certainly more common than mixing str strings and bytes in 3.0 (which is actively discouraged). To me, discerning the implicit principles of Python's design makes it easier to learn and remember, even if they are not as exact as one might like. The choices are not random, and so one can do better than rote memory. Terry Jan Reedy From xlebourd at gmail.com Wed Sep 3 05:44:19 2008 From: xlebourd at gmail.com (Xavier) Date: Wed, 3 Sep 2008 02:44:19 -0700 (PDT) Subject: Serial I/O problem with pywin32 ? Message-ID: Hi, I try to access to a Bluetooth GPS data-logger with Python. I use pySerial. Sending and receiving little messages (~100 char) works fine. However, when I ask the GPS to dump the trails, it returns some Mbytes and here is the problem : in the stream of bytes, I randomly losts chunks of ~100bytes. I tried USPP and pyBlueZ instead of pySerial : same problem. It doesn't like it is a bufferoverun bug from me because : - the GPS seems to wait when I do not read the stream, - there is never more than 200 inWainting() characters, - my code to test it is quite simple : seriallink = serial.Serial("COM40") fileName = "data.dump" out = open(fileName, 'w') while 1: c = seriallink.read() out.write(" %0.2X" % ord(c)) print "*", out.close() (with pyBluez : sock=BluetoothSocket( RFCOMM ) sock.connect(("00:0A:...", 1))) I tried my program on two different PC with two Bluetooth dongle, (with pySerial, USPP, pyBluez). The same things are : - windows - the GPS (which works fine with the dumper program of the constructor) - pyWin32 I've found another guy with a similar problem : http://www.generation-nt.com/reponses/rs232-entraide-142097.html He says: - no problem with little messages - lost of one byte every hour when receiving a lot of data Any known problems with pywin32 and serial I/O when downloading a big stream of data ? From roy at panix.com Sat Sep 27 10:20:50 2008 From: roy at panix.com (Roy Smith) Date: Sat, 27 Sep 2008 10:20:50 -0400 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > One cute reason to prefer class singletons to module singletons is that > subclassing works well for creating multiple singletons. But really, > the main reason I use class singletons is that they are the absolute > simplest way to get attribute access: > > class Foo: pass > Foo.bar = 'xyz' > if data == Foo.bar: > print "!" I've often done something similar, creating a dummy class: class Data: pass just so I could create instances of it to hang attributes off of: foo = Data() foo.bar = 'xyz' That's a trick I've been using since the Old Days (i.e. before new-style classes came along). When I saw your example, my first thought was "That's silly, now that there's new-style classes, you can just create an instance of object!". Unfortunately, when I tried it, I discovered it didn't work. You *can* instantiate object, but you don't get a class instance, so you can't create attributes on it. >>> x = object() >>> type(x) >>> x.foo = 1 Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'foo' From gagsl-py2 at yahoo.com.ar Tue Sep 16 05:38:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 06:38:33 -0300 Subject: Is 'x' an instance of a new-style class? References: Message-ID: En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS escribi?: > I've seen the question raised several times here, but apparently never > answered. Since PyInstance_Check returns False for new-style class > instances, is there a standard procedure for testing this using the C- > Api? > > I would greatly appreciate some help with this. In Python you would write isinstance(x, object). In C, "object" is PyBaseObject_Type, and a direct translation would be PyObject_IsInstance(x, PyBaseObject_Type), or perhaps PyObject_TypeCheck(x, &PyBaseObject_Type) (to mimic how other PyXXX_Check are implemented, and probably faster) -- Gabriel Genellina From durand1 at gmail.com Fri Sep 5 15:24:08 2008 From: durand1 at gmail.com (Durand) Date: Fri, 5 Sep 2008 12:24:08 -0700 (PDT) Subject: [PIL] quake like multicoloured text Message-ID: <3d829a04-9005-4216-86dc-b1055edab4e7@f63g2000hsf.googlegroups.com> I'm wondering how I could render text with PIL in which different parts of the text are different characters. This is for a game stats script where names are written like: ^1Red ^2Green ^3Yellow, etc. The problem is that I currently use text in the ImageDraw module but the only way I can think of rendering text is by rendering each bit of text in a separate colour. Example: draw.text((0,0),"Red", fill="red") draw.text((30,0),"Green", fill="green") draw.text((60,0),"Yellow", fill="green") except that I'm not sure how much spacing there is between each coloured bit of text(30px is assumed in the example)...Would there be an alternate method of doing this? Thanks =) From stef.mientki at gmail.com Thu Sep 25 07:49:06 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 13:49:06 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <6k1937F5i8kjU1@mid.uni-berlin.de> References: <6k1937F5i8kjU1@mid.uni-berlin.de> Message-ID: <48DB7AB2.6020309@gmail.com> Diez B. Roggisch wrote: > Stef Mientki wrote: > > >> hello, >> >> How can I find the correct case of a filename ? >> >> Background in my program I use case sensitive filenames, just like >> Python requires. >> Now I've integrated pdb into the program, >> but pdb acts somwhat strange: >> upon a breakpoint it gives the filename always in lowercase (probably >> this only happens on windows). >> >> So is there a way to get the correct case of a given filename in lowercase >> ? >> >> One solution might be to make the comparison in my program always with >> lowercase, >> but then I'm sure the program won't work on non-windows systems. >> >> btw, why does pdb behave that way ( Python 2.5 ) ? >> > > I doubt it does. It sure doesn't on unix, and I fail to see any reason why > it should do that on windows - given that the total number of lower() in > pdb.py amounts to one, and that's used to process user-input such > as "Yes", "y", "YES" or whatnot. > > Yes I'm pretty sure, two reasons: 1. when I perform a step_into, jumping into a file that doesn't have breakpoints itself (meaning my program doesn't even know of this file), pdb returns a lowercase filename 2. rpdb2 (probably based or even inherited from pdb) has the same behavior. Asking the writer of rpdb2, I got some excuse (which I didn't understand) why he had done it that way. > Are you sure you are not processing the content through some lower()-call > when embedding pdb? > > But maybe pdb does ? thanks anyway, Stef > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From ben at benfinney.id.au Fri Sep 26 01:08:33 2008 From: ben at benfinney.id.au (Ben Finney) Date: Fri, 26 Sep 2008 15:08:33 +1000 Subject: Writing a well-behaved daemon Message-ID: <874p43wl2m.fsf@benfinney.id.au> Howdy all, Writing a Python program to become a Unix daemon is relatively well-documented: there's a recipe for detaching the process and running in its own process group. However, there's much more to a Unix daemon than simply detaching. At a minimum, a well-behaved Unix daemon must at least: * Detach the process into its own process group * Close stdin, redirect stdout and stderr to a null device * Handle its own PID file: refuse to start if the PID file already exists, write the PID file on startup otherwise, and remove the PID file on termination * Revoke setuid and setgid privileges, which are strongly deprecated these days * Handle interrupts, cleaning up the process and PID file as necessary * (possible others) There are also many other commonly-expected tasks that well-behaved Unix daemons perform (drop privileges to a nominated non-root user and group after daemonising, redirect output to syslog instead, operate in a chroot jail, respawn when terminated, etc.). All of this stuff has been done numerous times before, and the basics are mostly agreed upon. Yet all of these are tricky to implement correctly, and tedious to re-implement in every program intended to run as a daemon. The 'daemon' program covers all these, and allows an arbitrary process to be started as a well-behaved Unix daemon process. It's not a good assumption that this program is installed on an arbitrary system though, and it seems excessive to ask the recipient of one's program to get a third-party program just in order to make a daemon process. I'd love to be able to have something similar for Python programs, e.g. a 'become_well_behaved_daemon()' function that implements all the above and perhaps takes optional arguments for the optional features. My searches for such functionality haven't borne much fruit though. Apart from scattered recipes, none of which cover all the essentials (let alone the optional features) of 'daemon', I can't find anything that could be relied upon. This is surprising, since I'd expect this in Python's standard library. Can anyone point me to the equivalent of the 'daemon' program in the form of a well-tested Python library? -- \ ?Tis more blessed to give than to receive; for example, wedding | `\ presents.? ?Henry L. Mencken | _o__) | Ben Finney From lucafbb at gmail.com Mon Sep 1 08:42:26 2008 From: lucafbb at gmail.com (Luca) Date: Mon, 1 Sep 2008 14:42:26 +0200 Subject: Know if a object member is a method In-Reply-To: <00cbd80b$0$20302$c3e8da3@news.astraweb.com> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> <00cbd80b$0$20302$c3e8da3@news.astraweb.com> Message-ID: <27308d500809010542n766bd9fmfdd9775ad3fdabf7@mail.gmail.com> On Mon, Sep 1, 2008 at 2:18 PM, Steven D'Aprano wrote: > > If your aim is to write something like a debugger, profiler, or some > other application that needs to inspect arbitrary objects and work out > what they do, then you probably should be using: > > isinstance(obj.methodName, new.instancemethod) > > But remember that not all callable attributes are instancemethods! > > There is no one right way of doing this. > > Hope this helps. Yes, this helps a lot. In facts I need to do something like a language parser. Thanks all. -- -- luca From ranim81 at gmail.com Mon Sep 1 08:32:15 2008 From: ranim81 at gmail.com (raju) Date: Mon, 1 Sep 2008 05:32:15 -0700 (PDT) Subject: click heremore dollar Message-ID: http://www.moneymaking4.blogspot.com/ From fredrik at pythonware.com Wed Sep 10 10:25:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 16:25:38 +0200 Subject: Web shopping carts In-Reply-To: References: <48C7CE5A.7030904@wildenhain.de> Message-ID: Luke Hamilton wrote: > And unfortunately Google hasn't been much help... "You've got to be very careful if you don't know where you're going, because you might not get there." From goon12 at gmail.com Tue Sep 2 13:07:33 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 2 Sep 2008 13:07:33 -0400 Subject: How to write verbose scripts In-Reply-To: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: <6a2ccd190809021007w6783ff34t8eece381ea958d2f@mail.gmail.com> On Tue, Sep 2, 2008 at 12:55 PM, Steven D'Aprano wrote: > Is there a better way of doing this than the way I am going about it? Would the logging module help, and just print the output to the stdout (or a file) instead? From duncan.booth at invalid.invalid Sat Sep 20 09:13:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Sep 2008 13:13:08 GMT Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: candide wrote: > Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > > Thanks for any comment. General comments about the page: Section 2: Poor demonstration of 'global'. The declaration of 'a' as global is unnecessary and misleading. Section 4: "Maths: Requires import math" The supplied examples won't work if you just "import math", they need a "from math import ..." (either * or better an explicit list of functions). Worse, the random number examples won't work whatever you import as they include both 'random.seed()' which assumes 'random' is the module and 'x = random()' which requires 'from random import random'. Section 5: "Strings do not expand escape sequences unless it is defined as a raw string by placing an r before the first quote" What is that supposed to mean? Describing triple quoted strings as 'optional syntax' is a bit weird too: the syntax is no more optional than any other form of string literal, you can use it or not. Another pointless example given under the heading 'String Operators': Concatenation is done with the + operator. Converting to numbers is done with the casting operations: x = 1 + float(10.5) "String functions" actually mostly describes string methods with "len" hidden in the middle but only the example tells you that it is different than the other examples. Section 6 is all about numarray but bizarrely (for something purporting to be an overview of Python) there is nothing at all about either list or dict types. Section 7 says "There is no switch or case statement so multiple elifs must be used instead." omitting to mention other possibly more appropriate options such as dicts or inheritance. This is a good indication that the author doesn't know much about OOP. Section 8 "for x in array: statements" shows that the author doesn't understand things like iterators. Section 10 has such interesting facts as "Only constant initializers for class variables are allowed (n = 1)" or "Objects can be compared using the == and != operators. Two objects are equal only if they are the same instance of the same object." and an example with a completely spurious class attributes, some pointless getter/setter methods, and contorted calls to base class methods. Section 11 demonstrates again that the author doesn't understand about iterable objects. I'd say the claim that Python isn't a full OOP language is not the most important reason to ignore the page. From kyrie at uh.cu Wed Sep 3 23:40:44 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 03 Sep 2008 23:40:44 -0400 Subject: max(), sum(), next() In-Reply-To: <48BEE2F7.5010106@shopzeus.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <48BEE2F7.5010106@shopzeus.com> Message-ID: <1220499644.48bf58bc376e4@comuh.uh.cu> Quoting Laszlo Nagy : > bearophileHUGS at lycos.com wrote: > > Empty Python lists [] don't know the type of the items it will > > contain, so this sounds strange: > > > > > >>>> sum([]) > >>>> > > 0 > > > > Because that [] may be an empty sequence of someobject: > > > > You are right in that sum could be used to sum arbitrary objects. > However, in 99.99% of the cases, you will be summing numerical values. > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > is very logical to return zero for empty sequences. Even better: help(sum) shows === sum(...) sum(sequence, start=0) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start'. When the sequence is empty, returns start. === so the fact that sum([]) returns zero is just because the start value is zero... sum([],object()) would return an object(). BTW, the original code: >>> sum(s for s in ["a", "b"] if len(s) > 2) wouldn't work anyway... it seems that sum doesn't like to sum strings: >>> sum(['a','b'],'') : sum() can't sum strings [use ''.join(seq) instead] Cheers, -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From deets at nospam.web.de Tue Sep 2 16:29:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Sep 2008 22:29:33 +0200 Subject: synthetic properties In-Reply-To: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> References: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> Message-ID: <6i5m1eFolktmU1@mid.uni-berlin.de> rowland at river2sea.org schrieb: > I'm trying to come up with solution for adding synthetic properties to > python, similar to synthetic properties in Objective-C. > > I'm playing around with doing this in a MetaClass. I can dynamically > create the attributes that will back the property, but I'm having > trouble figuring out how to dynamically generate get/set methods to > pass to the built-in property() function. Why on earth do you want to do that? The reason synthesized properties exist in ObjC is simply that to expose properties for key-value-coding, one needs the getter/setters. But mostly these are boilerplate, so apple introduced the @synthesized-annotation. But in python, you don't need that. You use simple attributes. In the very moment you need logic attached, use the builtin property to do so. Diez From nick at craig-wood.com Thu Sep 25 16:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 25 Sep 2008 15:30:03 -0500 Subject: Eggs, VirtualEnv, and Apt - best practices? References: Message-ID: Scott Sharkey wrote: B> Our development group at work seems to be heading towards adopting > python as one of our standard "systems languages" for internal > application development (yeah!). One of the issues that's come up is > the problem with apt (deb packages) vs eggs, vs virtual environments. > We're probably gonna end up using Pylons or TurboGears for web-based > apps, and I've recommended virtualenv, but one of the other developers > has had some "inconsistencies" when mixing systems with python installed > from apt (all our servers are debian or ubuntu based) vs when installed > under virtualenv. > > I have basically recommended that we only install the python base (core > language) from apt, and that everything else should be installed into > virtual environments. But I wanted to check to see how other enterprises > are handling this issue? Are you building python from scratch, or using > specific sets of .deb packages, or some other process. > > Any insight into the best way to have a consistent, repeatable, > controllable development and production environment would be much > appreciated. I'll admit to not knowing what you mean by virtual environment... In our debian systems we use python from apt and all modules from apt. If there is a module we can't find then we build it into a .deb using setup.py to build an rpm and converting to a .deb. The app is then tested with "etch" or whatever. If easy_install could build debs that would be really helpful! > Suggestions on build/rollout tools (like zc.buildout, Paver, etc) would > also be appreciated. Use setup.py to build into .debs is what we do. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From stef.mientki at gmail.com Thu Sep 25 10:43:53 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 16:43:53 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <6k1dukF5hk86U1@mid.uni-berlin.de> References: <6k1937F5i8kjU1@mid.uni-berlin.de> <6k1dukF5hk86U1@mid.uni-berlin.de> Message-ID: <48DBA3A9.4060707@gmail.com> Diez B. Roggisch wrote: >> Yes I'm pretty sure, two reasons: >> 1. when I perform a step_into, jumping into a file that doesn't have >> breakpoints itself (meaning my program doesn't even know of this file), >> pdb returns a lowercase filename >> > > What has that to do with potential output postprocessing? > > > > >> 2. rpdb2 (probably based or even inherited from pdb) has the same >> behavior. Asking the writer of rpdb2, I got some excuse (which I didn't >> understand) why he had done it that way. >> > > rpdb2 is not pdb. > > Below is the output of a Pdb-session I just had: > > > (eggbasket)dir at client8049:~/software/vc/EggBasket$ nosetests -s > eggbasket.tests.test_model > 2008-09-25 14:13:10,374 turbogears.identity.saprovider INFO Loading: > eggbasket.model.VisitIdentity > .> /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(59)test_versionsets() > -> vi1 = vset.add_pkg_info(p1) > (Pdb) n > >> /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(60)test_versionsets() >> > -> session.flush() > (Pdb) n > > > As you can see - mixed-case filenames. Linux though. > > There is a *very* simple way for you to check: just create a file called > > FooBar.py > > and inside that, put > > import pdb; pdb.set_trace() > print "hello" > > > Run that on the windows shell. See if that puts out all lowercase or not. I > can't do that right now as my VBox Windows won't start. > >>> import Module1 > d:\data_python_25\pylab_works\module1.py(3)() -> print "hello" (Pdb) > Then we know if PDB is really the culprit. > > So pdb is the problem. > Apart from that, is that really a problem that the filenames are all lower > case? AFAIK Windows is case-insensitive regarding filenames anyway. So > opening the file by just passing the filename should work seamless. > Yes windows is, but Python is not. My program should run on Windows and Linux (and maybe a few others). By converting everything to lowercase, on Linux I can't distinguishes between 2 files with the same name but a different case (btw, giving 2 files the same name, only differing in case, looks like a bad idea to me). And yes I could switch to lowercase in case I'm on a windows machine, but my program is too beautiful to pollute the code with these kind of unnecessary statements ;-) cheers, Stef > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From mensanator at aol.com Sun Sep 7 13:30:09 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 7 Sep 2008 10:30:09 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> Message-ID: <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> On Sep 6, 11:05?pm, Steven D'Aprano wrote: > On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote: > > [...] > > >> They could have decided that sum must take at least two arguments, > >> because addition requires two arguments and it's meaningless to talk > >> about adding a single number without talking about adding it to > >> something else. But they didn't. > > > Ok. But the problem is they DID in SQL: x + Null = Null. > > Sheesh. That's not a problem, because Python is not trying to be a > dialect of SQL. And yet, they added a Sqlite3 module. > > If you want a NULL object, then there are recipes on the web that will > give you one. Then all you need to do is call sum(alist or [NULL]) and it > will give you the behaviour you want. Actualy, I already get the behaviour I want. sum([1,None]) throws an exception. I don't see why sum([]) doesn't throw an exception also (I understand that behaviour is by design, I'm merely pointing out that the design doesn't cover every situation). > > [...] > > > Here's a real world example (no ivory tower stuff): > > > An oil refinery client has just excavated a big pile of dirt to lay a > > new pipeline. > [snip details] > > Can't I just use a sum of 0 to tell me when data is missing? No, because > > in some cases the reporting limit of undetected compounds is set to 0. > > You can't use a sum of 0 to indicate when data is missing, full stop. Exactly. That's why I would prefer sum([]) to raise an exception instead of giving a false positive. > The > data may require 15 tests when only 3 have actually been done: > > sum([1.2e-7, 9.34e-6, 2.06e-8]) Biggest problem here is that it is often unknown just how many records you're supposed to get from the query, so we can't tell that a count of 3 is supposed to be 15. > > Missing data and a non-zero sum. How should sum() deal with that? That's a seperate issue and I'm not saying it should as long as the list contains actual numbers to sum. sum([1.2e-7, 9.34e-6, 2.06e-8, None]) will raise an exception, as it should. But what types are contained in []? > > The answer is that sum() can't deal with that. You can't expect sum() to > read your mind, know that there should be 15 items instead of 3, and > raise an error. So why do you expect sum() to read your mind and > magically know that zero items is an error, especially when for many > applications it is NOT an error? For the simple reason it doesn't have to read your mind, a mechanism has already been built into the function: start value. For those situations where an empty list is desired to sum to 0, you could use sum(alist,0) and use sum(alist) for those cases where summing an empty list is meaningless. Shouldn't you have to explicitly tell sum() how deal with situations like empty lists rather than have it implicitly assume a starting value of 0 when you didn't ask for it? > > The behaviour you want for this specific application is unwanted, > unnecessary and even undesirable for many other applications. The > solution is for *you* to write application-specific code to do what your > application needs, instead of relying on a general purpose function > magically knowing what you want. Does division magically know what you want? No, it raises an exception when you do something like divide by 0. Isn't it Pythonic to not write a litany of tests to cover every possible case, but instead use try:except? But try:except only works if the errors are recognized. And sum() says that summing an empty list is NEVER an error under ANY circumstance. That may be true in MOST cases, but it certainly isn't true in ALL cases. > > -- > Steven From spammaster.10.webmaster at spamgourmet.com Sun Sep 14 07:28:01 2008 From: spammaster.10.webmaster at spamgourmet.com (spammaster.10.webmaster at spamgourmet.com) Date: Sun, 14 Sep 2008 04:28:01 -0700 (PDT) Subject: PyMarshal Commands crash on Windows Message-ID: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> Hi! Can anyone help me with this issue? int main (int argc, char * const argv[]) { Py_Initialize(); FILE* fp = fopen("/Users/test/Desktop/123.pyc","wb"); PyCodeObject* op = (PyCodeObject*)Py_CompileString("import sys \nprint 'hello'","",Py_file_input); PyMarshal_WriteObjectToFile((PyObject *)op, fp, Py_MARSHAL_VERSION); Py_Finalize(); return 0; } This Code crashs on Windows, and I can't explain why. I want to convert a PyCodeObject to a PyObject and save it to the harddisk. PyMarshal_ReadObjectFromFile(FILE *P) crashs too if I want to read a byte-compiled object. Thank your for your help. donnerChecker From fernandena at gmail.com Tue Sep 9 07:06:35 2008 From: fernandena at gmail.com (fernandena at gmail.com) Date: Tue, 9 Sep 2008 04:06:35 -0700 (PDT) Subject: =?KOI8-R?B?18nExc8g4tLJ1M7JIMkg68XXyc7BLg==?= Message-ID: ??????, ??? ??? ????? ????, ??? ??????! http://ragdai.info/golaya-pravda.htm ??? ????? ?????! From clp at rebertia.com Mon Sep 15 16:47:53 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Sep 2008 13:47:53 -0700 Subject: append on lists In-Reply-To: References: Message-ID: <47c890dc0809151347t5646d078jdf06dbc6cd7e3eed@mail.gmail.com> On Mon, Sep 15, 2008 at 1:45 PM, Armin wrote: > Chris Rebert wrote: >> >> On Mon, Sep 15, 2008 at 1:24 PM, Armin wrote: >>> >>> Hi, >>> >>> just a dumb question. >>> >>> Let a = [1,2,3,4,5] >>> >>> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? >> >> I'll assume the presence of the 6 is a typo. > > Sorry, that's the case. > >> >> Because .append() mutates 'a' and appends the item in-place rather >> than creating and returning a new list with the item appended, and >> it's good Python style for mutating methods to have no return value >> (since all functions must have some return value, Python uses None >> when the function doesn't explicitly return anything). > > Yes, but this is very unconvenient. > If d should reference the list a extended with a single list element > you need at least two lines > > a.append(7) > d=a > > and not more intuitive d = a.append(7) And then they'd both reference the same list and you'd run into all sorts of problems. The code you'd actually want is: d = a[:] #copy a d.append(7) Or if you're willing to overlook the inefficiency: d = a + [7] But that's not idiomatic. And debating the fundamentals of the language, which aren't going to change anytime soon, isn't going to get you anywhere. You may be interested in looking at Python's "tuple" datatype, which is basically an immutable list. I'd also suggest you Read The Fine Tutorial, and that your original question was better suited to IRC or python-tutors (http://mail.python.org/mailman/listinfo/tutor) than this mailinglist. Regards, Chris > > --Armin > > >> >> If you print 'a' after doing the .append(), you'll see it's changed to >> your desired value. > > >> >> Regards, >> Chris >> >>> --Armin >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From gnewsg at gmail.com Thu Sep 4 07:57:47 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 4 Sep 2008 04:57:47 -0700 (PDT) Subject: Safely move an element into a heap References: Message-ID: <778c30a9-f097-4789-b1d6-3b40a9f11bdf@p31g2000prf.googlegroups.com> On 4 Set, 13:49, Alexandru Palade wrote: > I'm not sure what you expect as an answer, but if you mean the heap as > in the data structure, you can not just arbitrarily move one key where > you want as it will destroy the heap property. > > > > Giampaolo Rodola' wrote: > > Hi, > > I wanted to know if does exist a safe way to, given a heap, move an > > arbitrary element to the first position of the heap. > > Something like: > > > ?>>> heap = [0,3,6,8,10] > > ?>>> heapq.move_to_first_position(heap, 4) > > ?>>> heap = [10, 0,3,6,8] > > > --- Giampaolo > >http://code.google.com/p/pyftpdlib/ > > -- > >http://mail.python.org/mailman/listinfo/python-list- Nascondi testo citato > > - Mostra testo citato - Could I be able to do that if every element I want to move will have the value of 0 which is the smallest value I can have into my heap? What I'm trying to do is implementing a timeout: sometimes I want a given event which was scheduled to happen within X seconds to happen immediately. --- Giampaolo http://code.google.com/p/pyftpdlib/ From homeshop18.grouping at gmail.com Fri Sep 26 07:09:33 2008 From: homeshop18.grouping at gmail.com (Online Shopping) Date: Fri, 26 Sep 2008 04:09:33 -0700 (PDT) Subject: Laptops- Read Features of branded Laptops Message-ID: Notebook computers - buy latest and best low price laptops from online computer shop in India, homeshop18.com offers low price laptops from online laptops shop. To know more visit: http://www.homeshop18.com/shop/u/y/c-Computers-Q-and-Q-Peripherals-S-Laptops/Home_Online-clI_2-cI_920-pCI_909- From ptmcg at austin.rr.com Wed Sep 3 01:43:26 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 2 Sep 2008 22:43:26 -0700 (PDT) Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: <59dabe63-7393-406f-9588-ba1afcc81b6f@26g2000hsk.googlegroups.com> On Sep 2, 12:36?pm, hofer wrote: > Hi, > > Something I have to do very often is filtering / transforming line > based file contents and storing the result in an array or a > dictionary. > > Very often the functionallity exists already in form of a shell script > with sed / awk / grep , . . . > and I would like to have the same implementation in my script > All that sed'ing, grep'ing and awk'ing, you might want to take a look at pyparsing. Here is a pyparsing take on your posted problem: from pyparsing import LineEnd, Word, nums, LineStart, OneOrMore, restOfLine test = """ 1 2 3 47 23 // this will never match # blank lines are not of any interest 91 26 23 19 41 1 97 26 // extra numbers don't matter """ # define pyparsing expressions to match a line of integers EOL = LineEnd() integer = Word(nums) # by default, pyparsing will implicitly skip over whitespace and # newlines, so EOL is skipped over by default - this would mix together # integers on consecutive lines - we only want OneOrMore integers as long # as they are on the same line, that is, integers with no intervening # EOL's line_of_integers = (LineStart() + integer + OneOrMore(~EOL + integer)) # use a parse action to identify the target lines def select_significant_values(t): v1, v2 = map(int, t[:2]) if v1+v2 == 42: print v2 line_of_integers.setParseAction(select_significant_values) # skip over comments, wherever they are line_of_integers.ignore( '//' + restOfLine ) line_of_integers.ignore( '#' + restOfLine ) # use the line_of_integers expression to search through the test text # the parse action will print the matching values line_of_integers.searchString(test) -- Paul From ppearson at nowhere.invalid Tue Sep 2 14:54:19 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 2 Sep 2008 18:54:19 GMT Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <6i56cpFor2puU1@mid.individual.net> <6Aevk.331$1a2.14@trnddc04> Message-ID: <6i5gerFospk9U1@mid.individual.net> On Tue, 02 Sep 2008 17:18:58 GMT, Alan G Isaac wrote: >> On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote: >>> At the risk of bike-shedding, >> [snip] > > Peter Pearson wrote: >> (startled noises) It is a delight to find a reference to >> that half-century-old essay (High Finance) by the wonderful >> C. Northcote Parkinson, but how many readers will catch the >> allusion? > > It is pretty common geek speek: > http://en.wikipedia.org/wiki/Color_of_the_bikeshed Ah, the wondrous Wiki. I thought I was a geek, for the past 40 years; but maybe its time for me to be demoted to the dad on whose bookshelf you'll find that old book. -- To email me, substitute nowhere->spamcop, invalid->net. From bdesth.quelquechose at free.quelquepart.fr Mon Sep 8 03:32:01 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 08 Sep 2008 09:32:01 +0200 Subject: Test if list contains another list In-Reply-To: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> Message-ID: <48c4f0e0$0$11223$426a34cc@news.free.fr> mathieu a ?crit : > Hi there, > > I am trying to write something very simple to test if a list > contains another one: > > a = [1,2,3] > > b = [3,2,1,4] > > but 'a in b' returns False. Indeed. Lists are not sets, and the fact that all elements of list a happens to also be part of list b doesn't make the list a itself an element of list b. >>> a = [1, 2, 3] >>> b = [3,2,1,4] >>> c = [b, a] >>> a in c True >>> b in c True >>> c [[3, 2, 1, 4], [1, 2, 3]] >>> > How do I check that a is indeed contained > in b ? But that's what you did - you *did* checked if a was contained in b, and this is not the case. What you want is to check if *all elements* of a are contained in b, which is quite another problem. Now the answer to your question : use sets. >>> set(a).issubset(set(b)) True >>> HTH From akineko at gmail.com Wed Sep 17 23:45:30 2008 From: akineko at gmail.com (akineko) Date: Wed, 17 Sep 2008 20:45:30 -0700 (PDT) Subject: A unique instance of Python GUI program References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> Message-ID: <0643c0e0-a9c0-4a46-8cb8-7c37a9ebcc07@w39g2000prb.googlegroups.com> Again, thank you for many postings to my question. I have reviewed solutions provided. Well, I like the named Mutex solution under Windows. That is a clean and straight-forward approach to the challenge. (I cannot believe that I'm saying good thing about Windows ;-) ) Unfortunately, I'm living in Unix realm ;-) None of solutions for Unix are appealing to me. But they must be "the" solution for the challenge as well-established software uses those solutions. Now, I'm wondering. As my program is a GUI (Tkinter) software. Is it possible to set a known value to X11 or Tk property through Tkinter so that another instance of the program can check if such property is set? Of course, I know this scheme has a flaw. If one instance uses another logical display, then such property is probably not shared. But for my usage, it is logically possible but not likely. I checked my Tkinter book and found the following function. winfo_interps(displayof=0) This returns a list of all Tk-based applications currently running on the display. When I tried, I got the following: >>> root.winfo_interps() ('tk #3', 'tk #2', 'tk') But I couldn't find a way to set a specific name to the Tcl interpreter. As I'm not an expert of Tcl/Tk and X11, I probably overlooked other functions that may do what I need. Any comments, suggestions on this? Maybe this can provide a platform independent way to ensure that only single instance is running. Thank you for your attention. Best reagrds, Aki Niimura From robert.d.kirkpatrick at gmail.com Wed Sep 24 02:05:29 2008 From: robert.d.kirkpatrick at gmail.com (Rob Kirkpatrick) Date: Tue, 23 Sep 2008 23:05:29 -0700 (PDT) Subject: Visualize class inheritance hierarchy References: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Message-ID: On Sep 23, 4:58 pm, Christian Heimes wrote: > Rob Kirkpatrick wrote: > > I'm assuming this has been discussed before, but I'm lacking any > > Google keywords that bring up the appropriate discussion. > > You are looking for "mro" aka method resolution order. The inspect > module contains several helper functions to inspect a class hierarchy. > > The following interactive session should give you an impression how to > use the functions: > > >>> import inspect > >>> import pprint > >>> from sqlalchemy.types import DateTime > > >>> inspect.getmro(DateTime) > (, 'sqlalchemy.types.TypeEngine'>, , > > >>> DateTime.__bases__ > (,) > > >>> pprint.pprint(inspect.getclasstree(inspect.getmro(DateTime))) > [(, ()), > [(, (,)), > [(, > (,)), > [(, > (,))]]]] > > >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, '__init__')] > [, 'sqlalchemy.types.TypeEngine'>, , > ] > > >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, 'adapt')] > [, ] Oh, yeah. That's the stuff! From mrkylehayes at gmail.com Tue Sep 30 13:50:01 2008 From: mrkylehayes at gmail.com (Kyle Hayes) Date: Tue, 30 Sep 2008 10:50:01 -0700 (PDT) Subject: r"" References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> Message-ID: <33077c9c-01d9-4423-afd2-7452117bc6b4@j22g2000hsf.googlegroups.com> > Please describe the actual problem you're trying to solve. In what way > do slashes need to be "fixed," and why? Well, I have decided to build a tool to help us sync files in UNC paths. I am just building the modules and classes right now so I haven't developed the frontend yet. I am assuming when the user provides a path (either by typing it in, or pulling it in from a config file), the UNC slashes are going to escape stuff in the string, so I want to double them up. I understand if the best way is to convert all the slashes to double- slashes. But the 'r' function seemed so handy and convenient. I am very new to Python, but not at all to programming. Thanks! From eflick at gmail.com Tue Sep 30 19:20:43 2008 From: eflick at gmail.com (Eric) Date: Tue, 30 Sep 2008 16:20:43 -0700 (PDT) Subject: Wait or not? Message-ID: <34809165-9c72-46b3-996c-4bd55451505d@e53g2000hsa.googlegroups.com> I've been wanting to learn Python for a while now but I can't decide on whether to wait for Python 3's final release and learn it or just go ahead and learn 2.x. Would it be hard to make the transition being a noob? From sturlamolden at yahoo.no Mon Sep 8 22:31:41 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 8 Sep 2008 19:31:41 -0700 (PDT) Subject: Coming from .NET and VB and C References: Message-ID: On 3 Sep, 18:52, ToPostMustJoinGroup22 wrote: > I'm coming from a .NET, VB, C background. > Any suggestions for someone new to the scene like me? Welcome! Unfortunately, you probably have a lot of bad habits to unlearn. Don't use Python like another C, VB or Java. It will cause a lot of grief, and you'll end up with the idea that Python is slow like a slug. Python is more like Lisp or Haskell, but with a readable syntax. There are list comprehensions, generator expressions, dictionaries, sets, lists, list slicing, lambdas, map, reduce, filter, closures, etc. They are there to be used, and be used a lot. Learning to use Python efficiently is what has the steepest learning curve. From half.italian at gmail.com Thu Sep 11 14:39:04 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 11 Sep 2008 11:39:04 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> Message-ID: <734ce614-3e92-4515-9342-d2e4e88c9632@b30g2000prf.googlegroups.com> On Sep 11, 9:59?am, Fredrik Lundh wrote: > carriere.jonat... at gmail.com wrote: > > I want to build a desktop application. I am searching for some kind of > > environment that would provide all the elements ready (Windows...). > > Then I would have to code the business logic only. > > start here: > > ? ?http://wiki.python.org/moin/GuiProgramming > > The big ones are Tkinter, which is usually bundled with Python; > wxPython, and PyQt. ?There's also a trend towards using the web browser > as a presentation engine also for local applications; for libraries that > help you with that, you can start here: > > ? ?http://wiki.python.org/moin/WebProgramming > > or jump directly to > > ? ?http://www.djangoproject.com/ > > I saw a message in the last few days showing how to use Flash as a front end for Python apps. It looked interested. Can anyone point me to it? ~Sean From gtitus_ at _wanadoo.fr Tue Sep 30 16:53:48 2008 From: gtitus_ at _wanadoo.fr (marc) Date: Tue, 30 Sep 2008 22:53:48 +0200 Subject: pylab without X11 In-Reply-To: References: Message-ID: <48e291d4$0$863$ba4acef3@news.orange.fr> This may help you ... or not You may have to change your backend : p13 of the matplotlib user guide: backends p17 how to change the backend in the matplotlibrc An example of matplotlibrc ( backend choice is at the beginning ): http://matplotlib.sourceforge.net/matplotlibrc You may choose PS or SVG or pdf, there might be other possibilities, I do not know To save the file : savefig Marc Willem-Jan Vriend a ?crit : > I want to use pylab (matplotlib) on a machine without X11. I'm trying to > generate onthefly graphics for an apache2 web service, so they do not > have to be displayed on this machine ! > > When i do > pylab.figure() > I get the error > TclError: couldn't connect to display ":0.0" > > I tried setting the DISPLAY environment variable to "", ":0.0" but I got > the same error message. > > Any help is very much appreciated. From invalid at invalid Thu Sep 18 12:07:45 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 18 Sep 2008 11:07:45 -0500 Subject: PEP proposal optparse References: Message-ID: While we're making suggestions, I've always wished that the --help output displayed the default values for options in addition to the help text specified by the user. I end up having to enter the default values twice -- once as a keyword argument and again in the help text. Then later when I decide to change the default value, things get out-of-sync. -- Grant Edwards grante Yow! Did you move a lot of at KOREAN STEAK KNIVES this visi.com trip, Dingy? From rcdailey at gmail.com Fri Sep 19 09:37:00 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 19 Sep 2008 08:37:00 -0500 Subject: Intercepting printed strings In-Reply-To: References: <496954360809181524g6037e0b0x84e98834bbf8ad9c@mail.gmail.com> Message-ID: <496954360809190637n8c12c6cvc177327aeb032ae4@mail.gmail.com> On Fri, Sep 19, 2008 at 4:21 AM, Gabriel Genellina wrote: > En Thu, 18 Sep 2008 19:24:26 -0300, Robert Dailey > escribi?: > > > I'm currently using Python 3.0 b3 and I'm curious as to how I can go about >> intercepting things send to print() for some intermediate processing >> before >> they're actually sent to sys.stdout. Right now I've thought of the >> following: >> >> Replace sys.stdout with a class named PrintStream. PrintStream is defined >> as >> follows: >> >> class PrintStream: >> def write( self, message ): >> sys.__stdout__.write( '\t{0}'.format( message ) ) >> >> Will this work? Basically I want to add a tab character in front of every >> message printed. Thanks. >> > > Why don't you try it yourself? > You may replace builtins.print with your own function too. It's not exactly > the same thing, but given your request "intercepting things send to print() > before they're sent to sys.stdout" it may be more adequate. I did try the code I posted and it doesn't work. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Sep 19 06:14:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 07:14:48 -0300 Subject: webbrowser fragment identifier References: <0b00afc4-018f-4b80-9fba-93c253a86c7a@q5g2000prf.googlegroups.com> Message-ID: En Thu, 18 Sep 2008 21:53:22 -0300, scottbvfx escribi?: > I'm trying to launch a web browser along with an html file with a > fragment identifier in its path. I'm using the webbrowser module for > this. > ie. webbrowser.open('file:///C:/myfile.html#SomeEntryInTheHTML') > > for some reason it is truncating the path to 'file:///C:/myfile.html'. > > Does anyone know a way of getting the fragment identifier in there > (with webbrowser module or any other)? It's not Python which truncates the path - webbrowser.open doesn't modify the url given. Looks like you're on Windows. Internet Explorer exposes a COM interface that you may use to control it. Google for "python IE automation" -- Gabriel Genellina From dmitrey.kroshko at scipy.org Tue Sep 23 16:21:18 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Tue, 23 Sep 2008 13:21:18 -0700 (PDT) Subject: [Tkinter] how to keep a window above all other OS windows? Message-ID: Hi all, how to keep a Tkinter window above all other OS windows (i.e. including those ones from other programs)? Thank you in advance, Dmitrey From marco.bizzarri at gmail.com Fri Sep 5 01:12:31 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 07:12:31 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <3f0d61c40809040409v3ee40da3h7eb0703009e78f06@mail.gmail.com> Message-ID: <3f0d61c40809042212q4244a1fn1a602fa195a7ca3c@mail.gmail.com> On Thu, Sep 4, 2008 at 7:15 PM, Timothy Grant wrote: > > I think the most obvious solution to the problem is effective unit > tests. If you type "a.y =1" and have a test that asserts a.x == 1 then > you would quite quickly discover that you made a typo. > > > -- > Stand Fast, > tjg. [Timothy Grant] > Right; that is one of the things I try to do to avoid this sort of problems. -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From aahz at pythoncraft.com Fri Sep 26 00:23:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 25 Sep 2008 21:23:05 -0700 Subject: Python is slow? References: Message-ID: In article , Grant Edwards wrote: > >AFAICT, _everybody_ is bad at programming C++. > >One begins to suspect it's not the fault of the programmers. http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From rcdailey at gmail.com Fri Sep 5 17:34:38 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 16:34:38 -0500 Subject: Need formatting suggestion for long strings In-Reply-To: <92da89760809051358k7c5ed12enb755efee45f42f37@mail.gmail.com> References: <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> <496954360809051315v44438624vf16240216d8ba2c5@mail.gmail.com> <92da89760809051358k7c5ed12enb755efee45f42f37@mail.gmail.com> Message-ID: <496954360809051434v5ec0a7fckdd70b335862a786c@mail.gmail.com> On Fri, Sep 5, 2008 at 3:58 PM, Eric Wertman wrote: > > I'm concerned about the formatting of the string in that I do not want > the > > way I split the string up in source code to affect the way the string is > > displayed to the console. In other words, in source, if I break up a > single > > string into multiple lines (using carriage returns), I would expect the > > string to still render as a single-line string. > > > > I'm also concerned about the source formatting, because I do not want the > > single-line string to run off the edge of my display. I want it to be in > > "Paragraph form" in the source code, but remain a single-line when > printed. > > I think you can also escape the line breaks: > > > This does not fully work because I like to add tabs to the front of the string on each line to keep it aligned with the current tab depth of that particular line of code. These strings will not always be in global namespace. The tabs in the front of the string would actually be included as part of the string, which I do not want. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Sep 12 05:27:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Sep 2008 09:27:39 GMT Subject: Better error message on recursive import References: <6isb2mF9scaU1@mid.individual.net> <6isunqF6v3jU2@mid.uni-berlin.de> <6iul4uFkaviU1@mid.individual.net> Message-ID: <6iur0bFioqdU1@mid.uni-berlin.de> On Fri, 12 Sep 2008 09:47:42 +0200, Thomas Guettler wrote: >> Can you give an example of such a recursive import you want the special >> exception be raised? > > ===> cat one.py > from two import testtwo > def testone(): > print "one" > > ===> cat two.py > import one > def testtwo(): > print "two" > > ===> python one.py > Traceback (most recent call last): > File "one.py", line 1, in > from two import testtwo > File "/mnt/home/tguettler/tmp/rec/two.py", line 1, in > import one > File "/mnt/home/tguettler/tmp/rec/one.py", line 1, in > from two import testtwo > ImportError: cannot import name testtwo This is an awkward situation anyway because here are *three* modules involved. You start `one.py` which will be imported as `__main__`. `__main__` imports `two` and `two` imports a *new* module `one`! Which tries to import `testtwo` from `two` which doesn't exist at that time. Even if you rearrange the code to load properly `one.py` is loaded and executed *twice* and you end up with two distinct modules generated from that file. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Tue Sep 23 17:41:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 17:41:51 -0400 Subject: Detecting the first time I open/append to a file In-Reply-To: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > for param in range(10): > simulate(param) > > def simulate(parameter): > 'Lots of code followed by: > with open(summaryFn, 'ab') as f: > writer = csv.writer(f) > writer.writerow(header) > writer.writerow(Sigma) > > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. How about file.tell == 0? or have I misunderstood the requirement? From castironpi at gmail.com Fri Sep 26 22:15:01 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 19:15:01 -0700 (PDT) Subject: getting global variables from dictionary References: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> Message-ID: On Sep 26, 9:01?pm, icarus wrote: > global_vars.py has the global variables > set_var.py changes one of the values on the global variables (don't > close it or terminate) > get_var.py retrieves the recently value changed (triggered right after > set_var.py above) > > Problem: get_var.py retrieves the old value, the built-in one but not > the recently changed value in set_var.py. > > What am I doing wrong? > > ----global_vars.py--- > #!/usr/bin/python > > class Variables : > ? ? ? ? def __init__(self) : > ? ? ? ? ? ? ? ? self.var_dict = {"username": "original username"} > > ---set_var.py --- > #!/usr/bin/python > > import time > import global_vars > > global_vars.Variables().var_dict["username"] = "new username" > time.sleep(10) ? #give enough time to trigger get_var.py > > ---get_var.py --- > #!/usr/bin/python > import global_vars > print global_vars.Variables().var_dict.get("username") Are these separate processes? From hrishys at yahoo.co.uk Wed Sep 24 11:19:58 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Wed, 24 Sep 2008 15:19:58 +0000 (GMT) Subject: Linq to Python In-Reply-To: Message-ID: <815199.94437.qm@web27401.mail.ukl.yahoo.com> Hi Terry Oops i never realised the mistake i have commited I apologise (i thought changing the subject line would make a new thread) I apologise (I thought Python programmers were smart and they did know what LINQ was) I don't apologise ( i dont apologise for the third one not sounding cocky here but i did google but nothing much came up thats when i posted the question here since i always see Python programmers are somehow smarter then programmers in other langauges i don't know if its the language or the programmers themselves that make them smart) regards Hrishy --- On Tue, 23/9/08, Terry Reedy wrote: > From: Terry Reedy > Subject: Re: Linq to Python > To: python-list at python.org > Date: Tuesday, 23 September, 2008, 7:51 PM > > Will LINQ be ported to Python ? > > I have three suggestions: > > 1. When starting a new thread, start a *new* thread. > Don't tack a new, > unrelated subject onto an existing thread. Your post will > not be seen > by people with readers that collapse thread and who do not > happen to > read the 'Python is slow?' thread. > > 2. Also, give enough informaton that people can understand > your question > without searching the web and guessing. In particular, > that do *you* > mean by LINQ? The game? The .NET component? Or something > else? > > 3. Before posting, search the Python manuals or the web a > bit for an > answer. If you mean the .NET component, googling > 'Python LINQ' should > partly answer your question. > > tjr > > -- > http://mail.python.org/mailman/listinfo/python-list From andre.roberge at gmail.com Sun Sep 14 20:41:16 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 14 Sep 2008 17:41:16 -0700 (PDT) Subject: "Best" way to "drive" a Python program step by step. Message-ID: Hi everyone, I'd be interested in hearing suggestions as to the "best" way to drive a Python program step by step from another application. Details: --------- I have implemented a "Robot" that can be programmed by a user to perform certain actions. (see Reeborg below for a simple javascript- based example). For example, part of a typical program might look like: ===== move() turn_left() move() for i in range(2): move() ... === I had this working in a desktop based application (see RUR-PLE below), where the user program was executed via exec user_code in MyGlobals and MyGlobals contained appropriate definitions. Having it all included in a single Python program, I could include time delays in each instruction [such as move()], so that the user could stop the program running by clicking on a button, etc., and then step through a series of instructions one-by-one, and/or resume the automatic execution. Now, I want to reproduce this behaviour in a browser based application (see Crunchy below). So, I'd like the Python back end to send information (at set intervals) to the browser and be able to react to input from the browser (say, a user pressing a "pause" button). I could try to reimplement the method I used for RUR-PLE some 3 years ago but I know enough now to realize that the method I used was rather "inelegant", but don't know enough to see a better way off-hand. Any suggestion would be appreciated. Cheers, Andr? Reeborg: http://reeborg.world.googlepages.com/reeborg.html Crunchy: http://code.google.com/p/crunchy/ RUR-PLE: http://rur-ple.sourceforge.net/ From bieffe62 at gmail.com Mon Sep 15 09:33:56 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 15 Sep 2008 06:33:56 -0700 (PDT) Subject: objet COM et ms Word References: <245dc065-660f-4dfe-8134-14b4acfc1f2d@j22g2000hsf.googlegroups.com> Message-ID: On 15 Set, 12:04, Pretorien wrote: > Bonjour @ tous, > > je voudrais gerer des doc Word avec python. > Y aurai-uil une doc quelque part bien faites ??? > > Pour le moment je fais : > > import win32com.client > > word = win32com.client.Dispatch('Word.Application') > > en suite j'ouvre VBexpress pour connaitre qu'elle fonction appeler: > par ex: > > Dim wrdApp As Word.Application > > Set wrdDoc = wrdApp.Documents.Open("\Exemple.doc") > > donc en python cela donnerai word.Documents.Open("toto.doc") > > et ainsi de suite .... > > Y a t il quelque de bien faits pour python, de mani?re a ne pas avoir > a g?rer et VB d'un cote pour deviner les fonctions ? appeler en > python. > > Merci par avance, > > Crdt, > > Thomas (I can read french but not write it, so ...) I did some simple automatic document generation using the COM interface of word, and I found this code snippet of some utility: http://www.bigbold.com/snippets/posts/show/2037 Ciao ----- FB From lists at cheimes.de Wed Sep 10 08:53:40 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 14:53:40 +0200 Subject: I want to use a C++ library from Python In-Reply-To: <6ipr40Fr7kr2U1@mid.uni-berlin.de> References: <6ipd53FrptpiU1@mid.uni-berlin.de> <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> <6ipr40Fr7kr2U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Which actually isn't really helpful, as a DLL itself says nothing about what > language was used to create it - and sending the OP to e.g. ctypes makes no > sense at all in the face of C++. The library - or more precisely the calling convention of the library - is related to the solution. On Windows a dll might be a container for a .NET assembly and C++ code can (theoretically) be compiled to .NET, too. > Whereas the first link for "python c++" is Boost::Python, a C++-wrapper to > make C++-code accessible from Python. C++ bindings can be created with SIP, SWIG, Boost or hand written code. Multiple sites claim that SIP generates the fastest code. Christian From m_palmer45 at yahoo.ca Mon Sep 15 21:03:08 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 15 Sep 2008 18:03:08 -0700 (PDT) Subject: How to marshal objects to readable files? References: Message-ID: On Sep 14, 11:28 am, nielinjie wrote: > Hi list: > I just want to marshal objects (instance of custom classes)to a human > *READABEL *file/string, and also, I want unmarshal it back. in xml > format or any other format. > Any advice? Which lib should I use? > Thanks a lot. There is module pickle in the standard library. It's output is not all that bad (in text mode, that is). If you don't like it, it would still be a good starting point for a custom serializer - it does all the tree walking for you, so you would only have to customize the strings it writes and reads back in. From michele.simionato at gmail.com Sat Sep 6 02:39:02 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 5 Sep 2008 23:39:02 -0700 (PDT) Subject: use str as variable name References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <48c1a184$0$17080$426a74cc@news.free.fr> Message-ID: On Sep 6, 8:02?am, "Marco Bizzarri" wrote: > On Fri, Sep 5, 2008 at 9:16 PM, Bruno Desthuilliers > > wrote: > > Marco Bizzarri a ?crit : > > >> Just a question: "generic functions" are not meant in the sense of > >> "generic functions" of CLOS, am I right? > > > Nope. Just "generic" in the sense that they accept any object implementing a > > very minimal interface. > > > If you want something like CLOS multimethods, you may be interested in > > Philip Eby's ruledispatch. > > Even though I loved them when I used at university, I'm not looking > for them right now... but nice to know that they are available under > python :-) Actually they are already available in the standard library but they are undocumented. See for instance this recent blog post of mine: http://www.artima.com/weblogs/viewpost.jsp?thread=237764 (as well as the comment below by P.J. Eby) From srikrishnamohan at gmail.com Wed Sep 24 02:02:41 2008 From: srikrishnamohan at gmail.com (km) Date: Wed, 24 Sep 2008 11:32:41 +0530 Subject: python 3.x third party modules Message-ID: Hi all, I would like to look at third party modules which are python 3.0 ready. could some one point me to such a resource ? If its not available, it would be useful to host a page regarding this on python.org ? any comments ? KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Sep 23 14:06:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 14:06:57 -0400 Subject: adding in-place operator to Python In-Reply-To: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> References: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> Message-ID: Arash Arfaee wrote: > Hi All, > > Is there anyway to add new in-place operator to Python? Or is there any > way to redefine internal in-place operators? Python does not have 'in-place operators'. It has 'augmented assignment statements' that combines a binary operation with an assignment. *If* the target being rebound is mutable, *then* (and only then) the operation can be and is recommended to be done 'in-place'. User-defined mutable classes (as most are) can implement in-place behavior with __ixxx__ methods. But for the reason given below, __ixxx__ methods should supplement and not replace direct mutation methods. Correct terminology is important for understanding what augmented assigments do and what they are basically about. First, most augmented assignments target immutables, in particular, numbers and strings, which do not have __ixxx__ methods. So the operation is *not* done in-place. The only difference from separately indicating the assignment and operation is that the programmer writes the target expression just once and the interpreter evaluates the target expression just once instead of each repeating themselves. (And consequently, any side-effects of that evaluation happen just once instead of twice.) The same __xxx__ or __rxxx__ method is used in either case. This non-repetition is the reason for augmented assigments. The optional in-place optimization for mutables is secondary. It was debated and could have been left out. Second, all augmented assignments perform an assignment, even if the operation is done in place. However, if a mutable such as a list is accessed as a member of an immutable collection such as a tuple, mutation is possible, but rebinding is not. So the mutation is done and then an exception is raised. To avoid the exception, directly call a mutation method such as list.extend. Terry Jan Reedy From kay.schluehr at gmx.net Thu Sep 4 05:14:21 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 4 Sep 2008 02:14:21 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> On 4 Sep., 10:31, "M.-A. Lemburg" wrote: > On 2008-09-04 07:49, Kay Schluehr wrote: > > > 3) Following the public rumor mill and the latest hype RIA i.e. the > > merge of web- and desktop applications with systems like Adobe AIR, > > JavaFX, Google Gears and MS Silverlight is the future of frontend > > development. With the exception of IronPython and Silverlight, Python > > hasn't even entered this game and no one knows if it ever will. > > Actually, it has already and quite some time ago: > > http://www.artima.com/weblogs/viewpost.jsp?thread=208528 > > The recipe is simple: use Python for the business logic, database > interfacing, etc and have it talk to a Flex front-end via XML-RPC > or REST. Python is still server-side in this scenario and plays no role in UI definitions. So one doesn't get more than e.g. Django apps that respond to HTTP requests triggered by JavaScript forms except that JavaScript+HTML+Browser is replaced by Flex = AS3+MXML+FlashPlayer. The role of Python is somewhat arbitrary. This could change only if Python becomes a client side language executed by AVM, V8 etc. like IronPython in Silverlight. About separating UI from application logics by assigning functionality to different general purpose languages I have to admit that I don't think it is such a great idea ... From invalid at invalid Tue Sep 16 13:43:29 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 16 Sep 2008 12:43:29 -0500 Subject: literals optimization (was Re: append on lists) References: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> Message-ID: On 2008-09-16, Maric Michaud wrote: > Le Tuesday 16 September 2008 18:26:38 Grant Edwards, vous avez ?crit?: >> I was asking where in the specification >> it says that all >> expressions that return something, return a new object. ? > > I never said this, I said it's the spirit of python APIs, with > some noticeable exceptions (see my first post). But for this > case specifically, a + b *should* return a new object, see the > documentation of __add__ and __iadd__ special methods, it's > clearly stated. OK, I've read through the documentation for __add__ and __iadd__ in the language reference, and I can't find anything that states or implies that they are to return a new object. Can you perhaps provide a link or some sort of cite? -- Grant Edwards grante Yow! Are you selling NYLON at OIL WELLS?? If so, we can visi.com use TWO DOZEN!! From jlstepp14 at wi.rr.com Wed Sep 10 12:45:19 2008 From: jlstepp14 at wi.rr.com (Jeff & Laura) Date: Wed, 10 Sep 2008 11:45:19 -0500 Subject: crack registration codes for pogo games Message-ID: your site won't come up....Do you have the crack for operation mania on pogo.com? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gary at byoteki.com Sat Sep 6 18:38:59 2008 From: gary at byoteki.com (Gary Josack) Date: Sat, 06 Sep 2008 18:38:59 -0400 Subject: Cathing several potential errors? In-Reply-To: References: Message-ID: <48C30683.80408@byoteki.com> cnb wrote: > if i do > try: > something > except TypeError, IndexError: > pass > > only the first error will get caught. I dont want to use Exception and > catch all errors, but just 2. how can i do that? > -- > http://mail.python.org/mailman/listinfo/python-list > what you're doing is assigning the value of TypeError to the name IndexError try: somthing except (TypeError, IndexError): pass use except (TypeError, IndexError), e: print e if you want to print the error From emile at fenx.com Tue Sep 9 14:13:45 2008 From: emile at fenx.com (Emile van Sebille) Date: Tue, 09 Sep 2008 11:13:45 -0700 Subject: check if the values are prensent in a list of values In-Reply-To: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> Message-ID: flit wrote: > Hello All, > > I will appreciate the help from the more skillfull pythonistas.. > > I have a small app that generates a sequence like > > 00341 > 01741 > 03254 Consider using a dict with sorted tuple keys, eg d = {} for seq in ['00341','01741','03254']: ky = list(seq) ky.sort() d[tuple(ky)] = None then d.keys() are the unique combinations. HTH, Emile > > This values I am putting in a list. > > So I have a list = [00341,01741,03254] > > after the programs find the sequence 03401 this sequence is "new" so > it appends on the list. But I want to avoid that as the values are > already on the first sequence of the list (00341). > If I try to use a "in" statement it will give false. as 00341 is > different from 00341 (but for my goal not..) > > > How can I check against this list and avoid to put "different" > sequences but same values? > > as 34100 --> dont append on the list > 14300 ---> dont append on the list > 05321 --> append to the list. > > Am I doing some conceptual error using lists? > There is a better approach? > > Thanks > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tim_grove at sil.org Tue Sep 2 11:47:08 2008 From: tim_grove at sil.org (Tim Grove) Date: Tue, 02 Sep 2008 16:47:08 +0100 Subject: [ctypes-users] ctypes - loading 'librsvg-2-2.dll' In-Reply-To: References: <48B3B8B3.5070309@sil.org> Message-ID: <48BD5FFC.20703@sil.org> Thanks Martin (and others) for your advice. No, this solution didn't quite work either. Well, the extremely annoying thing is that it DOES work on another home pc, but on my laptop which I use for work, it doesn't want to know!!! Both are running WinXP Pro. All the dependencies and paths "seem" to be okay, but there must still be something that I'm missing. Tim Martin (gzlist) wrote: > On 26/08/2008, Tim Grove wrote: > >> Any ideas why a particular dll won't load on Windows XP Pro using >> ctypes? >> > > I'm going to take a stab in the dark here and suggest it's because you > have multiple (different) copies of iconv.dll on your PATH. > > >> l=CDLL(r'D:\SILSign\librsvg-2-2.dll') >> Traceback (most recent call last): >> File "", line 1, in >> File "C:\PYTHON25\LIB\ctypes\__init__.py", line 349, in __init__ >> self._handle = _dlopen(self._name, mode) >> WindowsError: [Error 127] The specified procedure could not be found >> > > I get this on my current setup, where I've been messing around trying > to recompile lynx against iconv. I also get a popup saying "The > procedure entry point libiconv_set_relocation_prefix could not be > located in the dynamic link library iconv.dll." > > Doing this worked for me: > > C:\>set PATH=C:\Program Files\Common Files\GTK\2.0\bin > C:\>"C:\Python24\python.exe" -c "import ctypes; print > ctypes.CDLL('librsvg-2-2')" > > > Change the paths to your equivalents and try it, see if you have the > same or a similar dependency problem. > > Martin > > From williamhpurcell at gmail.com Thu Sep 4 20:14:10 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Thu, 4 Sep 2008 19:14:10 -0500 Subject: Converting .doc to .txt in Linux In-Reply-To: References: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: Here is a function that I have used with wvText to convert .doc files into text files. def readdoc(fpath): tmp = 'tmp_readdoc.txt' cmd = 'wvText %s %s'%(fpath,tmp) os.system(cmd) lines = open(tmp,'r').readlines() os.unlink(tmp) return lines It's not a completely python dependent function but it might work in a pinch. It depends on wv. I have tried the python uno and the Danny OOoLib modules, which might be worth looking into but I didn't have much luck. If you find a better or a completely python dependent method, let me know. FWIW -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at gmail.com Tue Sep 23 04:57:17 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 23 Sep 2008 01:57:17 -0700 (PDT) Subject: Regex Help References: Message-ID: <48e3268f-9282-4a31-b67e-eff71f9513e3@s20g2000prd.googlegroups.com> Hello, > Anybody know of a good regex to parse html links from html code? BeautifulSoup is *the* library to handle HTML from BeautifulSoup import BeautifulSoup from urllib import urlopen soup = BeautifulSoup(urlopen("http://python.org/")) for a in soup("a"): print a["href"] HTH, -- Miki http://pythonwise.blogspot.com From electronixtar at gmail.com Sun Sep 28 07:09:30 2008 From: electronixtar at gmail.com (est) Date: Sun, 28 Sep 2008 04:09:30 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> <6k93opF6k62hU1@mid.uni-berlin.de> Message-ID: <913193c5-1722-45ae-9cec-efa548dd6992@b38g2000prf.googlegroups.com> On Sep 28, 6:15?pm, Marc 'BlackJack' Rintsch wrote: > On Sun, 28 Sep 2008 01:35:11 -0700, est wrote: > >> Because that's how ASCII is defined. > >> Because that's how ASCII is defined. ?ASCII is a 7-bit code. > > > Then why can't python use another default encoding internally > > range(256)? > > Because that doesn't suffice. ?Unicode code points can be >255. > > > If Python choose another default encoding which handles range(256), 80% > > of python unicode encoding problems are gone. > > 80% of *your* problems with it *seems* to be gone then. > > > It's not HARD to process unicode, it's just python & python community > > refuse to correct it. > > It is somewhat hard to deal with unicode because many don't want to think > about it or don't grasp the relationship between encodings, byte values, > and characters. ?Including you. > > >> stop dreaming of a magic solution > > > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, what's > > wrong???? > > What do you mean by "just print 0x7F to 0xFF"? ?For example if I have ``s > = u'Sm?rebr?d?'`` what bytes should ``str(s)`` produce and why those and > not others? > > >> Isn't that more or less the same as telling the OP to use unicode() > >> instead of str()? > > > sockets could handle str() only. If you throw unicode objects to a > > socket, it will automatically call str() and cause an error. > > Because *you* have to tell explicitly how the unicode object should be > encoded as bytes. ?Python can't do this automatically because it has *no > idea* what the process at the other end of the socket expects. > > Now you are complaining that Python chooses ASCII. ?If it is changed to > something else, like MBCS, others start complaining why it is MBCS and > not something different. ?See: No fix, just moving the problem to someone > else. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Well, you succeseded in putting all blame to myself alone. Great. When you guy's are dealing with CJK characters in the future, you'll find out what I mean. In fact Boa Constructor keeps prompting ASCII and range(128) error on my Windows. That's pretty cool. From mensanator at aol.com Sun Sep 7 20:49:17 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 7 Sep 2008 17:49:17 -0700 (PDT) Subject: max(), sum(), next() References: <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: On Sep 7, 2:17?pm, Dennis Lee Bieber wrote: > On Sun, 7 Sep 2008 10:30:09 -0700 (PDT), Mensanator > declaimed the following in comp.lang.python: > > > On Sep 6, 11:05?pm, Steven D'Aprano > cybersource.com.au> wrote: > > > > Sheesh. That's not a problem, because Python is not trying to be a > > > dialect of SQL. > > > And yet, they added a Sqlite3 module. > > ? ? ? ? Which is an interface TO an embedded/stand-alone SQL-based RDBM > engine; it does not turn Python into a dialect of SQL -- Python does not > process the SQL, it gets passed to the engine for SQL data processing. But that's only half the story. The other half is data returned as a result of SQL queries. And that's something Python DOES process. And sometimes that processed data has to be inserted back into the database. We certainly don't want Python to process the data in a way that the database doesn't expect. When I see a potential flaw (such as summing an empty list to 0), should I just keep quiet about it, or let everyone know? Well, now they know, so I'll shut up about this from now on, ok? > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From python at rgbaz.eu Wed Sep 10 12:57:14 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 18:57:14 +0200 Subject: md5 differences In-Reply-To: References: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> Message-ID: <4158A777-F11F-4044-8BE2-D1B092A4B106@rgbaz.eu> On 10 sep 2008, at 18:34, Fredrik Lundh wrote: > Python wrote: > >> I'm trying to match the results of an md5 checksum done in a tcsh >> shell. >> I keep getting different results and can't find anything on google... >> here's an example: >> Arno at Computer:~% echo "hello" | md5 >> b1946ac92492d2347c6235b4d2611184 >> Arno at Computer:~% python >> Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) >> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin >> Type "help", "copyright", "credits" or "license" for more >> information. >> >>> import md5 >> >>> md5.new("hello").hexdigest() >> '5d41402abc4b2a76b9719d911017c592' > > >>> import md5 > >>> md5.new("hello\n").hexdigest() > 'b1946ac92492d2347c6235b4d2611184' > > > oooh... thanks :) From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 18:59:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 22:59:48 GMT Subject: doctest not seeing any of my doc tests References: <00d3d407$0$20306$c3e8da3@news.astraweb.com> Message-ID: <00d45737$0$20306$c3e8da3@news.astraweb.com> On Sun, 07 Sep 2008 15:51:01 +0200, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> I have a function in my module: >> >> def selftest(verbose=False): >> import doctest >> doctest.testmod(verbose=verbose) > > what happens if you change the above to > > def selftest(verbose=False): > import doctest, yourmodule > doctest.testmod(yourmodule, verbose=verbose) > > (where yourmodule is the name of your module, obviously) Well, that certainly fixed the problem, thanks. It now correctly runs all my doctests. But I don't understand why a bare doctest.testmod() works when you run it non-interactively, but fails when run interactively. -- Steven From steve at holdenweb.com Fri Sep 12 12:26:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 12:26:17 -0400 Subject: lacking follow-through In-Reply-To: <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: > On Sep 12, 7:23 am, Steve Holden wrote: >> castironpi wrote: >> >> If you are flattered to be compared to an AI you must come from the same >> race as Mr. Spock in Star Trek. > > No, I said 'for my logic to compared'. Speaking of which, I think you > excluded the possibility of diligent and ethical human, which meets > the criteria (of being flattered to be compared to an AI)... unless > Vulcan is just a synonym for it. If you want a discussion of why a > diligent and ethical human takes pride in / devotes effort to logic, > that's another topic that I'm happy to engage on. > >> You aren't entitled to require discussion of your ideas and proposals. > > No, but you are entitled to human interaction. If your case is that I > should seek mine face-to-face instead of keyboard-to-screen, you > probably have a point. > > ... > >> [...] >> >>> For example, I sometimes hear people talk about salary as though it >>> were social approval, and vice versa. Even though the analogy doesn't >>> hold in every case generally, it is still a good way to express >>> yourself in many contexts, and especially when the more precise word >>> isn't on the tip of your tongue. >> Perhaps under those circumstances the better choice is to hold off >> posting and do some research until you come up with the proper word. > > Yes I know. Good thing everyone at Mozilla agrees with you, and > Thesaurus.Com is included in Firefox's quicksearch engines. > >> Precision in the expression of ideas encourages debate, whereas sloppy >> "just write what you feel" is likely to result in hostile responses, as >> it causes the perception that you value your own time more than that of >> the people you attempt to engage. > > But the value of expression and self-expression can outweigh the value > of debate, even in so stuffy a setting as a Usenet group. Make time > for both or stifle your emotions. Do you hold I should be speaking > from the heart more or less? > > Regardless, you've contradicted yourself: > > 1) "just write what you feel" is likely to result in hostile responses > 2) If you are flattered to be compared to an AI you must [not be > human] > > Assume you, Steve, do as you say (practice what you preach). You do > not write either "just what you feel", nor anything that can be > compared to an A.I. Define the goal of A.I. to be logic and reasoned > "post-impulsive" deliberation (my title to define as I voiced the > flattery). Then conclude you don't post to the newsgroup. Observe > you do, and reach an absurdity. What premise do you retract? > > Knowing nothing of your background in philosophy or otherwise, it may > be a little unfair to put words in your mouth like that. It's a deep > problem (that yes, does have implications on the "diligent and > ethical" issue above) of human nature and the human condition: If > you're not rational, then you're a man. > > Besides, it is better to complain to the group that it is dropping my > posts than to anyone else. > The defence rests. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fredrik at pythonware.com Sun Sep 7 09:51:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 07 Sep 2008 15:51:01 +0200 Subject: doctest not seeing any of my doc tests In-Reply-To: <00d3d407$0$20306$c3e8da3@news.astraweb.com> References: <00d3d407$0$20306$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have a function in my module: > > def selftest(verbose=False): > import doctest > doctest.testmod(verbose=verbose) what happens if you change the above to def selftest(verbose=False): import doctest, yourmodule doctest.testmod(yourmodule, verbose=verbose) (where yourmodule is the name of your module, obviously) From gagsl-py2 at yahoo.com.ar Wed Sep 3 22:08:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 23:08:38 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <6i6pq9Fmcad7U2@mid.uni-berlin.de> <6vmdncUnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <20080904003435.GA29228@dragontoe.org> Message-ID: En Wed, 03 Sep 2008 21:34:35 -0300, Derek Martin escribi?: > On Wed, Sep 03, 2008 at 03:16:00PM -0700, Dennis Lee Bieber wrote: >> On Wed, 3 Sep 2008 03:09:18 -0400, Derek Martin >> declaimed the following in comp.lang.python: >> >> > struct run { >> > int speed; >> > direction_type direction; >> > }; >> > >> > Not a function. Describes an action. Sure, you'll probably never see >> > this example in a real program. But that doesn't mean you can't do >> > it, and it doesn't make it inherently wrong. Someone somewhere might >> > very well find a legitimate use case. >> >> Does neither for me... It defines a (physics) VELOCITY (a direction >> and a speed, but lacking in starting position and in duration). > > OK... so, let me ask you then: I have a computer program that graphs > the state of a particular act of running over time t. The only > information the program cares about is the speed and direction of that > particular instance of running. What would your data structure look > like? I'd use the name "velocity", a noun, as Dennis Lee Bieber already said. In pedantic mode, "average velocity". If you still want to push further such ridiculous example I'll have to think that you're just trolling. -- Gabriel Genellina From calebjhansen at gmail.com Sat Sep 13 03:15:11 2008 From: calebjhansen at gmail.com (fishfin) Date: Sat, 13 Sep 2008 00:15:11 -0700 (PDT) Subject: question about python Message-ID: I was working through a tutorial about how to write a server using python (the url is bellow). I am sure that the server is working to some degree because when the server is running localhost:8080 just keeps trying to load until it times out. I would like to know how to send information through the server to my browser? I was working through this tutorial: http://python.about.com/od/networkingwithpython/ss/PythonWebServer.htm and my final code is like this: import socket host = '' port = 8080 c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) c.bind((host, port)) c.listen(1) while 1: csock, caddr = c.accept() cfile = csock.makefile('rw', 0) line = cfile.readline().strip() cfile.write('HTTP/1.0 200 OK\n\n') cfile.write('Welcome %s!' % (str(caddr))) cfile.write('

Follow the link...

') cfile.write('All the server needs to do is ') cfile.write('to deliver the text to the socket. ') cfile.write('It delivers the HTML code for a link, ') cfile.write('and the web browser converts it.



') cfile.write('
Click me!
') cfile.write('

The wording of your request was: "%s"' %(line)) cfile.write('') cfile.close() csock.close() From kw at codebykevin.com Tue Sep 9 14:11:57 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 09 Sep 2008 14:11:57 -0400 Subject: How to record audio from Python on Mac? In-Reply-To: References: Message-ID: <48C6BC6D.8040207@codebykevin.com> skip at pobox.com wrote: > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > casting a broader net.) > > Can I easily control audio record/playback from Python on my Mac? I know > zip about audio recording or about Apple APIs via Python. Pointers to > simple examples would be much appreciated. > > Thanks, > > Skip You can probably access this functionality via PyObjC--it provides access to the Cocoa frameworks. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From half.italian at gmail.com Fri Sep 26 00:04:28 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 25 Sep 2008 21:04:28 -0700 (PDT) Subject: SimpleXMLRPCServer -- turning off request log? References: Message-ID: <9e0d437b-a6a6-4485-aa9a-93ed751b700f@o40g2000prn.googlegroups.com> On Sep 25, 6:01?pm, m... at pixar.com wrote: > My SimpleXMLRPCServer program prints to stderr a line like > this for each request: > > ohm..pixar.com - - [25/Sep/2008 17:57:50] "POST /RPC2 HTTP/1.0" 200 - > > Is there a way to turn this logging off? ?I have RTFM and can't > seem to find a way to do so. > > Many TIA! > Mark > > -- > Mark Harrison > Pixar Animation Studios Im pretty sure there's a more pythonic way, but you could redirect stdout to /dev/null import sys sys.stdout = open("/dev/null", 'w') assuming you're not on windows... ~Sean From skip at pobox.com Fri Sep 26 07:31:40 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 26 Sep 2008 06:31:40 -0500 Subject: Are spams on comp.lang.python a major nuisance? Message-ID: <18652.51228.620303.28571@montanaro-dyndns-org.local> I took over spam filter management for the python.org mailing lists a couple months ago and made a few changes to the way the spam filter is trained. Things seem to be at a reasonable level as far as I can tell (I see a few spams leak through each day), though I wasn't actively reading comp.lang.python/python-list at python.org before I took over the task, so I have nothing to compare with. Does the level of spam leaking through the filter now seem excessive? Is it more or less than in June and July? Thanks, Skip Montanaro From deets at nospam.web.de Mon Sep 15 14:54:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 20:54:42 +0200 Subject: environment variable issue In-Reply-To: <48ceacb9$0$2863$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <6j7pbiF1snjoU1@mid.uni-berlin.de> Michel Leunen schrieb: > Hi, > > Could someone explain me what I'm doing wrong here? I'm trying to > retrieve the value of an environment variable in Ubuntu 8.04 like this: > > >>> import os > >>> os.environ['USER'] > 'michel' > > This works but this doesn't: > > >>> os.environ['HOSTNAME'] > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'HOSTNAME' > > Why is it working in the first case but not in the second one. I must be > missing something but it seems I'm not able to figure it out. Maybe hostname is just missing? What does os.environ.keys() yield? On *my* ubuntu, it gives >>> sorted(os.environ.keys()) ['HOME', 'JAVA_HOME', 'LANG', 'LANGUAGE', 'LOGNAME', 'MAIL', 'PATH', 'PWD', 'PYTHONSTARTUP', 'SHELL', 'SHLVL', 'SSH_CLIENT', 'SSH_CONNECTION', 'SSH_TTY', 'TERM', 'USER', '_'] >>> No HOSTNAME ... Diez From bearophileHUGS at lycos.com Fri Sep 12 14:50:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Sep 2008 11:50:20 -0700 (PDT) Subject: manipulating files within 'for' References: <48CAA2AA.40809@umbc.edu> Message-ID: <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> Ben Keshet: > ...wrong. I thought I should omit the comma and didn't put it. I guess > that stating the obvious should be the first attempt with beginners like > me. Thanks for thinking about it (it's running perfect now). In CLisp, Scheme etc, lists such commas aren't necessary, but in Python if you don't separate strings with a comma they become merged into a single string: >>> 'foo', 'bar' ('foo', 'bar') >>> 'foo' 'bar' 'foobar' Your mistake is caused by Python not following one of its general rules: Explicit is better than implicit. In such case the string concatenation (+) is done implicitly. It's a little handy feature once in a while (but not for me so far), while it may cause bugs, so I don't like this little feature of Python and I may like to see it removed, because it may bite you in similar situations, where you forgot a comma for mistake: parts = ["foo", "bar" "baz"] Bye, bearophile From cs at zip.com.au Wed Sep 24 22:03:13 2008 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 25 Sep 2008 12:03:13 +1000 Subject: multiple processes, private working directories In-Reply-To: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: <20080925020313.GA1786@cskk.homeip.net> On 24Sep2008 18:27, Tim Arnold wrote: | I have a bunch of processes to run and each one needs its own working | directory. I'd also like to know when all of the processes are | finished. | | (1) First thought was threads, until I saw that os.chdir was process- | global. Yep. But do you need separate working directories? As opposed to having the thread state include a notional working directory and constructing file paths within it. | (2) Next thought was fork, but I don't know how to signal when each | child is finished. Open a pipe (os.pipe()). Have a parent process to track state. Fork each child. In each child: close the read end of the pipe. Do stuff. When finished, close the write end of the pipe. In the parent, after forking all children: close the write end of the pipe. Read from the read end. When all the children have finished they will have closed all the write ends and you will see EOF on the read end of the pipe. For extra credit you can have the children write some sort of success/failure byte to the pipe before closing. Counting and examinine these bytes in the parent can tell you about individual failure if you care. | (3) Current thought is to break the process from a method into a | external | script; call the script in separate threads. This is the only way I | can see | to give each process a separate dir (external process fixes that), and | I can | find out when each process is finished (thread fixes that). Yeah, that'll work: for child in 1 2 3 4 5 6 ... do mkdir workdir ( cd work-dir; run-child ) & done wait | Am I missing something? Is there a better way? I hate to rewrite this | method | as a script since I've got a lot of object metadata that I'll have to | regenerate with each call of the script. See the pipe scheme in point (2) above. Doubtless there are other methods, but pipes are each shared resources with the right behaviour. I'd prefer method (1) myself, assuming you have control of the working file paths. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ If everyone is thinking alike, then someone isn't thinking. - Patton From timr at probo.com Thu Sep 25 03:55:52 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Sep 2008 07:55:52 GMT Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> Message-ID: <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> Marc 'BlackJack' Rintsch wrote: > >On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote: > >>> > This seems to break the rule that if A is equal to B and B is equal >>> > to C then A is equal to C. >>> >>> I don't see why transitivity should apply to Python objects in general. >> >> Well, for numbers it surely would be a nice touch, wouldn't it. May be >> the reason for Decimal to accept float arguments is that irrational >> numbers or very long rational numbers cannot be converted to a Decimal >> without rounding error, and Decimal doesn't want any part of it. Seems >> pointless to me, though. > >Is 0.1 a very long number? Would you expect ``0.1 == Decimal('0.1')`` to >be `True` or `False` given that 0.1 actually is > >In [98]: '%.50f' % 0.1 >Out[98]: '0.10000000000000000555111512312578270211815834045410' >? Actually, it's not. Your C run-time library is generating random digits after it runs out of useful information (which is the first 16 or 17 digits). 0.1 in an IEEE 784 double is this: 0.100000000000000088817841970012523233890533447265625 -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From arnodel at googlemail.com Sun Sep 14 14:24:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Sep 2008 11:24:44 -0700 (PDT) Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> Message-ID: On Sep 14, 5:10?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 14, 4:43?am, Arnaud Delobelle wrote: > > > > > On Sep 14, 10:29?am, Steven D'Aprano > > cybersource.com.au> wrote: > > > I have a function that needs a reference to the module object it is > > > defined in. (For the reason why, if you care, see the thread "doctest not > > > seeing any of my doc tests" from a week ago.) I know of two ways to deal > > > with this problem, both of which feel unsatisfactory to me. Assume the > > > name of the module is "Mod", then I can do either of these: > > > > def foo(): > > > ? ? import Mod > > > ? ? process(Mod) > > > > Disadvantage: If I change the name of the module, I have to remember to > > > change the name of the module reference in foo() twice. > > > > def foo(): > > > ? ? modname = foo.__module__ > > > ? ? module = __import__(modname) > > > ? ? process(module) > > > > Disadvantage: if I change the name of the function, I have to remember to > > > change the reference to itself, but at least both changes are right next > > > to each other. > > > > Assume that changing the function name or the module name are both > > > equally likely/unlikely. > > > > Which do other people prefer? Which seems "better" to you? Are there any > > > other alternatives? > > > What about something like: > > > ? ? sys.modules[__name__] ? > > > -- > > Arnaud > > You're just worried about changing the module's name in the future. > So use a global variable or function that you only have to change > once. > > def Mod_mod( ): > ? ?import Mod as Mod #<-- only one change needed > ? ?return Mod > > def foo( ): > ? ?process( Mod_mod( ) ) Or: import ModuleName as this_module def foo(): process(this_module) -- Arnaud From nick at craig-wood.com Thu Sep 25 06:30:02 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 25 Sep 2008 05:30:02 -0500 Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> Message-ID: Tim Roberts wrote: > Marc 'BlackJack' Rintsch wrote: > > > >On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote: > > > >>> > This seems to break the rule that if A is equal to B and B is equal > >>> > to C then A is equal to C. > >>> > >>> I don't see why transitivity should apply to Python objects in general. > >> > >> Well, for numbers it surely would be a nice touch, wouldn't it. May be > >> the reason for Decimal to accept float arguments is that irrational > >> numbers or very long rational numbers cannot be converted to a Decimal > >> without rounding error, and Decimal doesn't want any part of it. Seems > >> pointless to me, though. > > > >Is 0.1 a very long number? Would you expect ``0.1 == Decimal('0.1')`` to > >be `True` or `False` given that 0.1 actually is > > > >In [98]: '%.50f' % 0.1 > >Out[98]: '0.10000000000000000555111512312578270211815834045410' > >? > > Actually, it's not. Your C run-time library is generating random digits > after it runs out of useful information (which is the first 16 or 17 > digits). 0.1 in an IEEE 784 double is this: > > 0.100000000000000088817841970012523233890533447265625 Not according to the decimal FAQ http://docs.python.org/lib/decimal-faq.html ------------------------------------------------------------ import math from decimal import * def floatToDecimal(f): "Convert a floating point number to a Decimal with no loss of information" # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an # exponent. Double the mantissa until it is an integer. Use the integer # mantissa and exponent to compute an equivalent Decimal. If this cannot # be done exactly, then retry with more precision. mantissa, exponent = math.frexp(f) while mantissa != int(mantissa): mantissa *= 2.0 exponent -= 1 mantissa = int(mantissa) oldcontext = getcontext() setcontext(Context(traps=[Inexact])) try: while True: try: return mantissa * Decimal(2) ** exponent except Inexact: getcontext().prec += 1 finally: setcontext(oldcontext) print "float(0.1) is", floatToDecimal(0.1) ------------------------------------------------------------ Prints this float(0.1) is 0.1000000000000000055511151231257827021181583404541015625 On my platform Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44), [GCC 4.3.1] on linux2 Linux 2.6.26-1-686 Intel(R) Core(TM)2 CPU T7200 -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gagsl-py2 at yahoo.com.ar Mon Sep 29 09:35:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 10:35:15 -0300 Subject: Python OOP question References: Message-ID: En Thu, 25 Sep 2008 11:45:21 -0300, k3xji escribi?: > Hi all, > > I am trying to develop a game-server in python. Design is as > following: > > - ConnectionManager - handling/distributing incoming connections > - IOManager - handling IO recv/send operations on sockets. > (inheritable) > - Socket - basic async socket object > - SocketServer - handling multiple socket object requests. > (inheritable) > - Options - holds the server options (inheritable) > > I want this code to be extensible as it can be. So I have developed it > like this. I f one is going to implement some new feature, all needs > to be done is to inherit IOManager or Server object to do it. > Inheritable objects are IOManager, SocketServer and Options. > > But there is some feeling about this design that it can be better. > Here is the main.py which I am using to execute the server: > > from Base.SocketServer import SocketServer > from testIOManager import testIOManager > from Base.Options import Options > from Base.ConnectionManager import ConnectionManager > > iomgr = testIOManager() > opts = Options() > > # calculate how many server objects to create > # according to the maximum allowed client count. > serverCnt = opts.MAX_CLIENT_COUNT / opts.MAX_CLIENT_COUNT_PER_SERVER > Servers = [] > for i in range(serverCnt): > server = Server(i) > Servers.append(server) > > > cmgr = ConnectionManager(Servers, iomgr, opts) > cmgr.start() > > With current design as server object is inheritable, I need to pass it > to ConnectionManager object. I just have a feeling that above design > is bad in the sense of readability. You may imitate how asyncore [1] handles channels: make the library contain a (global) list of servers; the Server (base) constructor adds itself to the list; and ConnectionManager uses that list if not explicitely supplied one. But I'm not sure it improves readability: there is no explicit link between the Servers you construct and the ConnectionManager, but the latter "magically" knows about all the formers. It's easier to manage, though. (I don't undersantd exactly why you insist in the inheritable part; isn't the same if it were not inheritable? Maybe I don't get your main concerns correctly...) -- Gabriel Genellina From harrrrpo at gmail.com Tue Sep 9 16:12:56 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Tue, 9 Sep 2008 22:12:56 +0200 Subject: Deflate with urllib2... In-Reply-To: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> Message-ID: <538050a90809091312u4072576fk3c45c533406b1d7d@mail.gmail.com> Try this http://www.paul.sladen.org/projects/pyflate/ 2008/9/9 Sam : > I'm using urllib2 and accepting gzip and deflate. > > It turns out that almost every site returns either normal text or > gzip. But I finally found one that returns deflate. > > Here's how I un-gzip: > compressedstream = StringIO.StringIO(data) > gzipper = gzip.GzipFile(fileobj=compressedstream) > data = gzipper.read() > > Un-gzipping works great! > > Here's how I un-deflate (inflate??) > data = zlib.decompress(data) > > Un-deflating doesn't work. I get "zlib.error: Error -3 while > decompressing data: incorrect header check" > > I'm using python 2.5.2. Can someone tell me exactly how to handle > deflated web pages? > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.kern at gmail.com Tue Sep 23 20:09:44 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 19:09:44 -0500 Subject: Python is slow? In-Reply-To: References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> Message-ID: Robert Kern wrote: > J Peyret wrote: >> On Sep 23, 8:31 am, bearophileH... at lycos.com wrote: >> >> Guys, this looks like a great data structure/algo for something I am >> working on. >> >> But... where do I find some definitions of the original BK-tree idea? > > Uh, actually we're talking about kd-trees, not BK-trees. kd-trees are > for searching through point sets in a k-dimensional space. My apologies. I did not actually follow bearophile's link, and thought he was talking about kd-trees like Sturla was. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at holdenweb.com Tue Sep 30 08:39:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Sep 2008 08:39:36 -0400 Subject: What is not objects in Python? In-Reply-To: References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <48E21E08.9020808@holdenweb.com> Steven D'Aprano wrote: > On Mon, 29 Sep 2008 21:03:07 -0700, namekuseijin wrote: > >>> Why isn't len implemented as a str.len and list.len method instead of a >>> len(list) function? >> Because postfix notation sucks. The natural way of spelling is >> adjective+noun and verb+predicate. > > "Natural"? > > You mean phrases like "heir apparent" and "worst choice imaginable" are > unnatural? They are certainly far from normal usage, as my dog yellow would be certain to agree. > To say nothing of languages like Spanish, Albanian, Italian, > Cornish, Vietnamese, Hebrew... It's long been a convention in the Western programming world to pretend no other language than English and no other codes than ASCII exist. The fact that Python is beginning to come to terms with Unicode is a tribute to certain developers' persistence. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From sri_annauni at yahoo.co.in Sun Sep 14 10:57:20 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Sun, 14 Sep 2008 20:27:20 +0530 (IST) Subject: Is there any nice way to unpack a list of unknown size?? Message-ID: <238815.3778.qm@web7902.mail.in.yahoo.com> I want to do something like below: 1. first, second, third, *rest = foo ?2. for (a,b,c,*rest) in list_of_lists: Please suggest. Thanks, Srini Bring your gang together. Do your thing. Find your favourite Yahoo! group at http://in.promos.yahoo.com/groups/ From gagsl-py2 at yahoo.com.ar Fri Sep 5 18:22:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 19:22:09 -0300 Subject: Files application architecture References: <48C155E8.7050006@cines.fr> Message-ID: En Fri, 05 Sep 2008 12:53:12 -0300, Benjamin Watine escribi?: > I'm about to develop a small python application and I wonder how to > organize files in this application. > I'm familar to java, so I'm tempted to use the same convention : 1 file > per class and 1 folders per package. You don't *have* to artificially restrict yourself to one class per file. In Python it's common to place several related classes in the same module (i.e., file). You don't have to write so much boilerplate code as in Java, so classes tend to be smaller in size; you may even find classes with an empty body. > I know that packages doesn't exists in python, they are modules instead. Uh? Have you read the Python Tutorial? http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > So, what are best practices for organizing files and folders in a small > python project ? > I've found PEP8 (http://www.python.org/dev/peps/pep-0008/) that gives a > lot of good hints on coding convention, but nothing about files > organization. A small application may consist of just a main entry point and some imported modules, all residing in the same directory. It might not require to define any package. Perhaps later, when some module grows too much, you may want to refactor it, creating a package. But try to keep simple things simple. -- Gabriel Genellina From patrickstinson.lists at gmail.com Fri Sep 19 19:40:37 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Fri, 19 Sep 2008 15:40:37 -0800 Subject: migrating processess to avoid the GIL Message-ID: <6214d7a20809191640q33df6cf7k23b288cee4f7277a@mail.gmail.com> I need to migrate calls to CPython to another process in my C++ app to get around the GIL. Does anyone know of a good way to do this on windows and Mac? All calls and callbacks can be blocking, I just need to share some data structures. Cheers From jvines at arl.army.mil Wed Sep 10 10:10:08 2008 From: jvines at arl.army.mil (John Vines (CISD/HPCD)) Date: Wed, 10 Sep 2008 10:10:08 -0400 Subject: [Fwd: Re: Python extension, where am I going wrong] Message-ID: <48C7D540.3000800@arl.army.mil> Yes spelling things correctly does help, got it thanks for the help. -------------- next part -------------- An embedded message was scrubbed... From: Fredrik Lundh Subject: Re: Python extension, where am I going wrong Date: Wed, 10 Sep 2008 15:46:54 +0200 Size: 4460 URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: jvines.vcf Type: text/x-vcard Size: 378 bytes Desc: not available URL: From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 3 10:50:43 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 16:50:43 +0200 Subject: properties setting each other In-Reply-To: References: Message-ID: <48bea3e4$0$9754$426a74cc@news.free.fr> mk a ?crit : > Hello everyone, > > I try to set two properties, "value" and "square" in the following code, > and arrange it in such way that setting one property also sets another > one and vice versa. But the code seems to get Python into infinite loop: > > >>> import math > >>> class Squared2(object): > > def __init__(self, val): > self._internalval=val > self.square=pow(self._internalval,2) the 'internal' prefix is already implied by the '_'. And your __init__ code is a useless duplication of fsetvalue, so just use the property and get rid of copy-pasted code. > def fgetvalue(self): > return self._internalval the '_' prefix already means 'internal'. The convention here would be to name the attribute '_value' (to make clear it's the implementation support for the 'value' property). Also, your property getter and setter should also be marked as implementation using the '_' prefix - they are implementation detail, not part of your class API. > def fsetvalue(self, val): > self._internalval=val > self.square=pow(self._internalval,2) > > value = property(fgetvalue, fsetvalue) > > def fgetsquare(self): > return self.square > def fsetsquare(self,s): > self.square = s Hem... Notice something here ? > self.value = math.sqrt(self.square) > > square = property(fgetsquare, fsetsquare) Your fsetsquare implementation is broken - it calls itself recursively. You have to use different names for the property and the 'implementation attribute' for the property. But even if you fix this, you'll have another infinite recursion between the two setters. The simplest solution : don't call one property from the other, do direct attribute access within the setters: import math class Squared2(object): def __init__(self, value): self.value=value def _fgetvalue(self): return self._value def _fsetvalue(self, value): self._value=value self._square=pow(value,2) value = property(_fgetvalue, _fsetvalue) def _fgetsquare(self): return self._square def _fsetsquare(self,square): self._square = square self._value = math.sqrt(square) square = property(_fgetsquare, _fsetsquare) From pavlovevidence at gmail.com Sat Sep 13 01:25:29 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 12 Sep 2008 22:25:29 -0700 (PDT) Subject: lacking follow-through References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> Message-ID: On Sep 12, 12:35?pm, Fredrik Lundh wrote: > Steve Holden wrote: > > The defence rests. > > can you please stop quoting that guy, so we don't have to killfile you > as well... Guy? Carl Banks From davidgshi at yahoo.co.uk Sun Sep 14 08:38:06 2008 From: davidgshi at yahoo.co.uk (David Shi) Date: Sun, 14 Sep 2008 12:38:06 +0000 (GMT) Subject: proven upload.py needed Message-ID: <155731.83210.qm@web26308.mail.ukl.yahoo.com> Dear All, ? I am working on a website development project.? I am looking for Python scripts for allowing end users to upload large zip data files and to get processed output datasets back to client machines. ? If there be better data compression and transmissn techniques available, I shall be interested. ? Thank you very much in advance for yours assistance. ? Sincerely, ? David -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 9 04:49:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 10:49:18 +0200 Subject: Test if list contains another list In-Reply-To: References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> Message-ID: <48c6380b$0$17080$426a34cc@news.free.fr> Matimus a ?crit : > On Sep 8, 12:32 am, Bruno Desthuilliers > wrote: (snip) >> >>> set(a).issubset(set(b)) >> True >> >>> >> > Just to clarify, doing it using sets is not going to preserve order OR > number of elements that are the same. > > That is: > >>>> a = [1,1,2,3,4] >>>> b = [4,5,3,7,2,6,1] >>>> set(a).issubset(set(b)) > True > > This will return True if b contains at least on of each element found > in a. If the OP wanted to check that list `a` appeared in order > somewhere in list `b` then sets won't work. Indeed, and I should have mentionned this myself. Thanks for this reminder. From sjmachin at lexicon.net Tue Sep 2 20:36:07 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 17:36:07 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> Message-ID: <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> On Sep 3, 9:44 am, ssecorp wrote: > or why does this take so god damn long time? Because your code does so many god damn unnecessary things. Apart from the fact (as pointed out already by Robert) that you are needlessly finding the sizes (Y, X) that are already available: (1) You are executing a try block Y*X (approx) times instead of the Y+X +2 times it would take if you were to do preliminary probes to find Y and X (2) You are doing range(1, 1000) Y times instead of once [see question below] (3) You are doing the method lookup im.getpixel Y*X times instead of once (4) you are doing the method lookup row.append Y*X times instead of Y times > and if I run into an IndexError it break out of the inner loop right? > so having range up to 10000000 or 1000 wouldn't matter if biggest > working x is 800? > > def getPixels(fileName): > im = PIL.Image.open(fileName) > colors = [] > for y in range(1, 1000): Are you sure that both occurrences of range(1, 1000) shouldn't be range(1000)? > row = [] > for x in range(1, 1000): > try: > color = im.getpixel((x,y)) > row.append(color) > except IndexError: > break > colors.append(row) > return numpy.array(colors) and it appears that you haven't bothered to read the manual section on Image.getpixel: """ Note that this method is rather slow; if you need to process larger parts of an image from Python, you can either use pixel access objects (see load), or the getdata method. """ From sturlamolden at yahoo.no Thu Sep 25 05:25:36 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 02:25:36 -0700 (PDT) Subject: The Python computer language References: Message-ID: On 25 Sep, 06:02, ROSEEE wrote: > http://pythoncomputer.blogspot.com I wonder where the usenet cancelbots have gone? From ldo at geek-central.gen.new_zealand Sun Sep 28 02:08:50 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 28 Sep 2008 19:08:50 +1300 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> Message-ID: In message , Aaron "Castironpi" Brady wrote: > I understand that formal proof systems, as well as automated > theorem provers, have been difficult to develop. The basic problem is: having proved that a program satisfies certain formally-specified criteria, how do you prove that those formal criteria specifications actually correspond to the original problem you were trying to solve? The proof just pushes the correctness problem back another level. From fredrik at pythonware.com Tue Sep 16 17:59:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Sep 2008 23:59:16 +0200 Subject: How do I add permanently to Pythons sys.path? In-Reply-To: <99c53e1a-a693-4f35-b937-d172c565077c@m36g2000hse.googlegroups.com> References: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> <99c53e1a-a693-4f35-b937-d172c565077c@m36g2000hse.googlegroups.com> Message-ID: cnb wrote: > no I can't... Python has supported packages since version 1.4 or so, so I'm pretty sure you can. From maric at aristote.info Mon Sep 15 07:12:54 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 13:12:54 +0200 Subject: Rebinding __setattr__ In-Reply-To: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> References: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> Message-ID: <200809151312.55946.maric@aristote.info> Le Monday 15 September 2008 01:06:08 Jan Schilleman, vous avez ?crit?: > Hi all, > > I am trying to redefine __setattr__. > > The base class is in a library (actually, it is > win32com.client.DispatchBaseClass) and I do not want to touch it. My > problem is exemplified below. To my surprise, __setattr__ and __str__ > behave differently; I can redefine __str__ and the inherited __str__ is > still the redefined one. But redefining __setattr__ on the base class does > not get inherited. In Base.__dict__ the __setattr__ is the one I expected, > but it is not called from B. > > What is the problem? Is __setattr__ cached somewhere [and not updated?]? > Yes, it doesn't work with classic classes, but do with new-style ones, I don't know if this an accepted behavior or not. Can't you use new-style classes ? >>>[2]: sys.version ...[2]: '2.5.2 (r252:60911, May 28 2008, 19:19:25) \n[GCC 4.2.4 (Debian 4.2.4-1)]' >>>[64]: class A : def __setattr__(self, name, value) : print "A", name ....: ....: >>>[67]: class B(A) : pass ....: >>>[68]: A().c, B().c = 1, 2 A c A c >>>[69]: A.__setattr__ = lambda s, n, v : sys.stdout.write("%s, %s, %s\n" % (s, n, v)) >>>[70]: A().c, B().c = 1, 2 <__main__.A instance at 0x2b3b41546290>, c, 1 A c >>>[71]: class A(object) : def __setattr__(self, name, value) : print "A", name ....: ....: >>>[74]: class B(A) : pass ....: >>>[75]: A().c, B().c = 1, 2 A c A c >>>[76]: A.__setattr__ = lambda s, n, v : sys.stdout.write("%s, %s, %s\n" % (s, n, v)) >>>[77]: >>>[78]: A().c, B().c = 1, 2 <__main__.A object at 0x2b3b45dfa350>, c, 1 <__main__.B object at 0x2b3b45dfa350>, c, 2 -- _____________ Maric Michaud From lixinyi.23 at gmail.com Wed Sep 24 20:10:07 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Wed, 24 Sep 2008 17:10:07 -0700 (PDT) Subject: PyRun_SimpleFile() crashes References: <26532f88-b70c-4b18-af4d-5176ec023f46@c65g2000hsa.googlegroups.com> Message-ID: <231b15f7-34d7-4ae7-9ef9-7244d2c70434@w1g2000prk.googlegroups.com> On 9?25?, ??1:05, "Aaron \"Castironpi\" Brady" wrote: > On Sep 24, 6:30 am, Nick Craig-Wood wrote: > > > > > lixinyi... at gmail.com wrote: > > > my code: > > > main.cpp > > > #include > > > > int main(int argc, char **argv) > > > { > > > Py_Initialize(); > > > > FILE *file_1 = fopen("a2l_reader.py","r+"); > > > PyRun_SimpleFile(file_1,"a2l_reader.py"); > > > > Py_Finalize(); > > > } > > > > compile under windows using MinGW: > > > g++ main.cpp libpython25.a -o a > > > > no error was found. But when I run a.exe the program just crashes. > > > > What should I do? > > > Run it under gdb (which should have come with MinGW). > > > Check that you actually opened the file, ie file_1 != 0. > > > This might be relevant > > > http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o... > > > -- > > Nick Craig-Wood --http://www.craig-wood.com/nick > > There's a workaround. > > filename = "Entire path of the python file"; > PyObject* PyFileObject = PyFile_FromString(filename, "r"); > PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename); > // decref PyFileObject > > http://mail.python.org/pipermail/python-list/2007-March/431725.htmlhttp://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567 Wow this one works fine for me. Thank you! From tjreedy at udel.edu Tue Sep 30 15:28:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 15:28:54 -0400 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > The executable would execute perfectly. Because you execute it in the necessary directory. > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") This does not execute it in the proper directory. os.getcwd() will tell you where you are -- mostly likely .../Pythonx.y. Try: os.chdir("C:/myprogramfolder/run") # / works fine, and without r prefix os.system("Myprogram.exe 1 1 acc 0") > The executable file would start to execute until it would print an error > stating that it cannot use a (.dat) file, which is located under the > following directory: > > C:\myprogramfolder\run\inputs\io\control.dat > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? That file does not exist in the Pythonx.y directory where the program starts ;-). tjr From almar.klein at gmail.com Thu Sep 18 10:13:59 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 18 Sep 2008 16:13:59 +0200 Subject: matplotlib in interactive mode locks when run from subprocess Message-ID: Hi, In wxpython, I made an interactive shell, which creates a remote python subprocess to do the interpreting. Communication is done via a pipe. The idea is that the python session is an actual process separate from the GUI, which has some advantages, like I can have multiple such shells in my application, and I can kill them without worrying that my wx app will crash. To do this I use the wx.Process class, which allows asynchronous communication with the remote process. This all works really, I will also launch wxpython apps. So I was quite happy, untill I tried doing some plotting with matplotlib (in TkAgg backend). The problem is that the process becomes unresponsive when I plot something (No prompt is written to the stdout/stderr). (more details below) I don't know much about creating subprocess and how they are different from a normal process. So can anyone offer some help as to what the problem might be? Thanks in advance, Almar To get to the details: - When I start a process with command "python -u -i" -- When interactive mode is off, the whole process becomes unresponsive when doing pylab.show() -- When interactive mode in on, on doing pylab.plot(), a figure appears, which I can zoom etc., but the process is now stuck, also after closing the figure - When I start a process with command "python -u -c 'import code;code.interact(readfunc=raw_input)'" (This is how Pype does it). -- When interactive mode is off, the figures show when doing pylab.show() and the process behaves as normal after closing the figure(s). -- When interactive mode in on, on doing pylab.plot(), a figure appears, but most of the time it is not drawn and emmediately unresponsive, just like the process itself. I have also tried an asynchronous Popen recipe by Joshiah Carlson I found on activestate. And I made my own process class using win32process.CreateProcess. Both alternatives to wx.Process resulted in the same sympoms. Oh, and I run windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Tue Sep 30 00:41:57 2008 From: roy at panix.com (Roy Smith) Date: Tue, 30 Sep 2008 00:41:57 -0400 Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <00f15dd2$0$20617$c3e8da3@news.astraweb.com> Message-ID: In article , Terry Reedy wrote: > It should be both, just as + is addition for numbers and concatenation > for sequences. Actually, the math folks would argue that using + for concatenation is wrong, since by normal math rules, + denotes a commutative operation. Of course, the math folks think that i^2 = -1, so what do they know? All right-thinking people know that j^2 = -1. From karentataka at gmail.com Sun Sep 21 00:09:47 2008 From: karentataka at gmail.com (karentataka at gmail.com) Date: Sat, 20 Sep 2008 21:09:47 -0700 (PDT) Subject: Quick & Secured Pharmacy Online. hr3tn Message-ID: <85f191e6-899a-472a-8007-8f1f4f400e2b@j22g2000hsf.googlegroups.com> Start saving, best online pharmacy here http://gjlabeh.cuchezfarg.com/?cdfikmabehxwvrsygzchcmjl From rcdailey at gmail.com Sat Sep 6 12:33:10 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Sat, 6 Sep 2008 11:33:10 -0500 Subject: Calling global functions from a class? Message-ID: <496954360809060933w2b736b57x7925510140e7a3e@mail.gmail.com> HI, I have the following python script: def __normalizePath( path ): return osp.abspath( osp.normpath( path ) ) class AbsolutePath: def __init__( self, root="" ): _root = __normalizePath( root ) When I create an AbsolutePath object, I get the following error: NameError: global name '_AbsolutePath__normalizePath' is not defined Is there a reason for this? How can I make this work? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 10:58:51 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 16:58:51 +0200 Subject: Pyflix, confused about super() call In-Reply-To: References: Message-ID: <48d90423$0$3170$426a74cc@news.free.fr> process a ?crit : > Anyone using Pyflix for the Netflix prize. > > How can it call super to itself in its init-method? > You mean : > class MovieAverage(Algorithm): > def __init__(self, training_set): > self._movie_averages = {} this line ? super(MovieAverage,self).__init__(training_set) If that's what confuse you, I think you really should read the FineManual(tm) instead of assuming Python is language X or Y. From gminick at bzt.bzt Wed Sep 10 13:37:27 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 17:37:27 +0000 (UTC) Subject: md5 differences References: Message-ID: On Wed, 10 Sep 2008 19:12:28 +0200, Python wrote: > Arno at Computer:~% echo "test" > test.txt > > Arno at Computer:~% md5 test.txt > MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 > >>> import md5 > >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() > '90364ed45b452d43378629c20543a81d' Works for me: >>> import md5 >>> f = open('test.txt').read() >>> md5.new(f).hexdigest() 'd8e8fca2dc0f896fd7cb4cb0031ba249' >>> IOW, don't pass the path to the file to md5.new, but the contents of this file. The strange thing is that >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bdesth.quelquechose at free.quelquepart.fr Tue Sep 23 13:17:43 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 19:17:43 +0200 Subject: Detecting the first time I open/append to a file In-Reply-To: References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> Message-ID: <48d940a3$0$3738$426a74cc@news.free.fr> Sean Davis a ?crit : > On Sep 23, 2:02 pm, tkp... at hotmail.com wrote: >> I have a simulation that runs many times with different parameters, >> and I want to aggregate the output into a single file with one rub: I >> want a header to be written only the first time. My program looks a >> bit like this: >> >> def main(): >> for param in range(10): >> simulate(param) >> >> def simulate(parameter): >> 'Lots of code followed by: >> with open(summaryFn, 'ab') as f: >> writer = csv.writer(f) >> writer.writerow(header) >> writer.writerow(Sigma) >> >> If I can sense that the file is being created in the first iteration, >> I can then use an if statement to decide whether or not I need to >> write the header. Question: how can I tell if the file is being >> created or if this its the first iteration? It's unrealistic to test >> the value of the parameter as in the real problem, there are many >> nested loops in main, and the bounds on the loop indices may change. > > You could use os.path.exists() to check if the file is there. > However, the file could have been left over from a previous execution, > etc. What might make sense is to open the file only once, store the > file handle, and write to that throughout the execution. s/file handle/file object/ This being said, I can only second Sean's advice. And anyway, computing something and writing the result(s) of this computation to the file are orthogonal and mostly unrelated responsabilities, so they shouldn't be handled by the same function. Here's a possible reorganisation of your code: def simulate(parameter): # lots of code followed by return sigma def main(): # presumably some other code here with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) for param in range(10): writer.writerow(simulate(param)) From jjkk73 at gmail.com Wed Sep 3 05:06:38 2008 From: jjkk73 at gmail.com (jorma kala) Date: Wed, 3 Sep 2008 11:06:38 +0200 Subject: Using httplib to access servlets on tomcat server Message-ID: Hi, I'm trying unsuccesfully to use the httplib library to execute servlets on a local tomcat server. If I type the following http adress on my browser http://localhost:8080/test/Serv1 the servlet works fine. But if I try to access it with the following python code: conn = httplib.HTTPConnection("http://localhost:8080") conn.request("GET", "/test/Serv1") r1 = conn.getresponse() I get the following error: socket.gaierror: (11001, 'getaddrinfo failed') Do you know what I do wrong? Thank you very much. (The complete traceback is: Traceback (most recent call last): File "http1.py", line 130, in getTomcat1() File "http1.py", line 46, in getTomcat1 conn.request("GET", "/test/Serv1") File "C:\Python25\lib\httplib.py", line 862, in request self._send_request(method, url, body, headers) File "C:\Python25\lib\httplib.py", line 885, in _send_request self.endheaders() File "C:\Python25\lib\httplib.py", line 856, in endheaders self._send_output() File "C:\Python25\lib\httplib.py", line 728, in _send_output self.send(msg) File "C:\Python25\lib\httplib.py", line 695, in send self.connect() File "C:\Python25\lib\httplib.py", line 663, in connect socket.SOCK_STREAM): socket.gaierror: (11001, 'getaddrinfo failed') -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Sep 25 16:32:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:32:22 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: References: Message-ID: <6k2aqqF5p185U1@mid.uni-berlin.de> Dmitry S. Makovey schrieb: > Scott Sharkey wrote: >> Any insight into the best way to have a consistent, repeatable, >> controllable development and production environment would be much >> appreciated. > > you have just described OS package building ;) > > I can't speak for everybody, but supporting multiple platforms (PHP, Perl, > Python, Java) we found that the only way to stay consistent is to use OS > native packaging tools (in your case apt and .deb ) and if you're missing > something - roll your own package. After a while you accumulate plenty of > templates to chose from when you need yet-another-library not available > upstream in your preferred package format. Remember that some python tools > might depend on non-python packages, so the only way to make sure all that > is consistent across environment - use unified package management. That this is a desirable goal can't be argued against. Yet two big hurdles make it often impractical to be dogmatic about that: - different OS. I for one don't know about a package management tool for windows. And while our servers use Linux (and I as developer as well), all the rest of our people use windows. No use telling them to apt-get instal python-imaging. - keeping track of recent developments. In the Python webframework world for example (which the OP seems to be working with), things move fast. Or extremly slow, regarding releases. Take Django - until 2 month ago, there hasn't been a stable release for *years*. Virtually everybody was working with trunk. And given the rather strict packaging policies of debian and consorts, you'd be cut off of recent developments as well as of bugfixes. Diez From exarkun at divmod.com Mon Sep 8 15:09:38 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 8 Sep 2008 15:09:38 -0400 Subject: exit() In-Reply-To: Message-ID: <20080908190938.29191.2011689276.divmod.quotient.23218@ohm> On Mon, 08 Sep 2008 21:03:48 +0200, Christian Heimes wrote: >Gary Robinson wrote: >>In Python 2.5.2, I notice that, in the interpreter or in a script, I can >>exit with: >> >> exit() > >The exit callable is defined in the site module. Check out site.py! It >shouldn't be used in code. It was added to help newbies to 'escape' from an >interactive Python shell. > It works. Why shouldn't it be used? Jean-Paul From Magnus.Moraberg at gmail.com Fri Sep 12 07:26:16 2008 From: Magnus.Moraberg at gmail.com (Magnus.Moraberg at gmail.com) Date: Fri, 12 Sep 2008 04:26:16 -0700 (PDT) Subject: Matching horizontal white space Message-ID: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> multipleSpaces = re.compile(u'\\h+') importantTextString = '\n \n \n \t\t ' importantTextString = multipleSpaces.sub("M", importantTextString) I would have expected consecutive spaces and tabs to be replaced by M but nothing is being replaced. If I try the following, then I'm left only with M, as expected - multipleSpaces = re.compile(u'\\s+') # both vertical and horizontal importantTextString = '\n \n \n \t\t ' importantTextString = multipleSpaces.sub("M", importantTextString) What I eventually wish to do is have only single spaces in my text and to only have single carriage returns - " one two three four five six " becoming - "one two three four five six " Thanks, Barry From martin at v.loewis.de Fri Sep 26 17:13:49 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 26 Sep 2008 23:13:49 +0200 Subject: Quick sort implementation in python In-Reply-To: <4da8f8b2-0216-433c-89a6-39d7ab037e84@l42g2000hsc.googlegroups.com> References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> <48dbf8f9$0$21266$9b622d9e@news.freenet.de> <4da8f8b2-0216-433c-89a6-39d7ab037e84@l42g2000hsc.googlegroups.com> Message-ID: <48DD508D.7040300@v.loewis.de> >> Can you please explain how you did that in C? IOW, how did you do >> the partition function (template) in case you don't have random >> access to the collection? >> > > Why exactly do you need random access for partition function? This is a counter-question, not an answer. Let me ask again: How did you do that in C++? > Do can > swap 2 nodes of a linked list without random access (you can swap the > pointers or just swap the node values) and you traverse the list till > you reach it's tail. In Python, there is no standard iterator that allows you to modify the underlying collection. There is the iter() function/type, but it only allows read access. Regards, Martin From almar.klein at gmail.com Tue Sep 2 03:52:09 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 2 Sep 2008 09:52:09 +0200 Subject: python 3k, when will it be mainstream? Message-ID: Hi, I read that python 3k is now in its final beta version. I was wondering when we can expect the major packages to make a 3.0 branch. I am myself quite new to python, and would like to make the transition as soon as possible, simply because it would save me porting code later, and I can focus on learning just the python 3.0. However, I am a former Matlab user and depend on packages like numpy, scipy, matplotlib. wxPython I use as well. So to get to the point: When can we expect these (and other) packages to release their python 3k versions? And when will the majority of people make the transition to py3k? I am looking forward to your thoughts on this, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Fri Sep 26 01:31:59 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 25 Sep 2008 22:31:59 -0700 (PDT) Subject: Writing a well-behaved daemon References: <874p43wl2m.fsf@benfinney.id.au> Message-ID: On Sep 25, 10:08?pm, Ben Finney wrote: > Howdy all, > > Writing a Python program to become a Unix daemon is relatively > well-documented: there's a recipe for detaching the process and > running in its own process group. However, there's much more to a Unix > daemon than simply detaching. At a minimum, a well-behaved Unix daemon > must at least: > > * Detach the process into its own process group > > * Close stdin, redirect stdout and stderr to a null device > > * Handle its own PID file: refuse to start if the PID file already > ? exists, write the PID file on startup otherwise, and remove the PID > ? file on termination > > * Revoke setuid and setgid privileges, which are strongly deprecated > ? these days > > * Handle interrupts, cleaning up the process and PID file as necessary > > * (possible others) > > There are also many other commonly-expected tasks that well-behaved > Unix daemons perform (drop privileges to a nominated non-root user and > group after daemonising, redirect output to syslog instead, operate in > a chroot jail, respawn when terminated, etc.). > > All of this stuff has been done numerous times before, and the basics > are mostly agreed upon. Yet all of these are tricky to implement > correctly, and tedious to re-implement in every program intended to > run as a daemon. > > The 'daemon' program covers all > these, and allows an arbitrary process to be started as a well-behaved > Unix daemon process. It's not a good assumption that this program is > installed on an arbitrary system though, and it seems excessive to ask > the recipient of one's program to get a third-party program just in > order to make a daemon process. > > I'd love to be able to have something similar for Python programs, > e.g. a 'become_well_behaved_daemon()' function that implements all the > above and perhaps takes optional arguments for the optional features. > > My searches for such functionality haven't borne much fruit though. > Apart from scattered recipes, none of which cover all the essentials > (let alone the optional features) of 'daemon', I can't find anything > that could be relied upon. This is surprising, since I'd expect this > in Python's standard library. > > Can anyone point me to the equivalent of the 'daemon' program in the > form of a well-tested Python library? > > -- > ?\ ? ? ?Tis more blessed to give than to receive; for example, wedding | > ? `\ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?presents.? ?Henry L. Mencken | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > Ben Finney http://code.activestate.com/recipes/66012/ I actually use a brew of the original recipe combined with several of the great comments. The commenters add alot of the functionality that you are looking for. It works very well on most counts, but doesn't handle being killed well. The daemons often last for a few weeks to a month before something unexpected kills them off. If I was more careful, I think they could live much longer. Looks like somebody did the same thing I did and posted it. http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemon.py ~Sean From stef.mientki at gmail.com Thu Sep 4 17:22:50 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 04 Sep 2008 23:22:50 +0200 Subject: pdb bug and questions Message-ID: <48C051AA.5090002@gmail.com> hello, I'm trying to embed a debugger into an editor. I'm only interested in high level debugging. The first question is what debugger is the best for my purpose ? (pdb, pydb, rpdb2, smart debugger, extended debugger ? Second question, in none of the above debuggers (except rpdb2), I can find a "break now", so it seems impossible to me to detect unlimited while loops ? For the moment I started with pdb, because most of the debuggers seems to be an extension on pdb. When I launch the debugger ( winXP, Python 2.5) from with my editor python -u -m pdb D:\\Data\\test_IDE.py I get this error IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') NOTICE 1 backslash ----------------------------------^ If I launch the debugger with python -u -m pdb D:/Data/test_IDE.py It runs fine. This looks like a bug to me. What's the best way to report these kind of bugs ? Although I mostly use os.path.join to be OS independent, these kind of bugs give me the impression, that I can better do the join myself and always use forward slashes. Is this a valid conclusion ? thanks, Stef Mientki From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 00:05:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 04:05:40 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> Message-ID: <00d34d6c$0$30713$c3e8da3@news.astraweb.com> On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote: [...] >> They could have decided that sum must take at least two arguments, >> because addition requires two arguments and it's meaningless to talk >> about adding a single number without talking about adding it to >> something else. But they didn't. > > Ok. But the problem is they DID in SQL: x + Null = Null. Sheesh. That's not a problem, because Python is not trying to be a dialect of SQL. If you want a NULL object, then there are recipes on the web that will give you one. Then all you need to do is call sum(alist or [NULL]) and it will give you the behaviour you want. [...] > Here's a real world example (no ivory tower stuff): > > An oil refinery client has just excavated a big pile of dirt to lay a > new pipeline. [snip details] > Can't I just use a sum of 0 to tell me when data is missing? No, because > in some cases the reporting limit of undetected compounds is set to 0. You can't use a sum of 0 to indicate when data is missing, full stop. The data may require 15 tests when only 3 have actually been done: sum([1.2e-7, 9.34e-6, 2.06e-8]) Missing data and a non-zero sum. How should sum() deal with that? The answer is that sum() can't deal with that. You can't expect sum() to read your mind, know that there should be 15 items instead of 3, and raise an error. So why do you expect sum() to read your mind and magically know that zero items is an error, especially when for many applications it is NOT an error? The behaviour you want for this specific application is unwanted, unnecessary and even undesirable for many other applications. The solution is for *you* to write application-specific code to do what your application needs, instead of relying on a general purpose function magically knowing what you want. -- Steven From Ripter001 at gmail.com Wed Sep 3 23:04:22 2008 From: Ripter001 at gmail.com (Ripter) Date: Wed, 3 Sep 2008 20:04:22 -0700 (PDT) Subject: Help Understanding weakref (lazyloader) References: Message-ID: <98906e65-e4a6-4003-9cec-98e8c6fb5726@x16g2000prn.googlegroups.com> On Sep 3, 10:46?pm, Ripter wrote: > I found this script athttp://www.pygame.org/wiki/LazyImageLoading?parent=CookBook > And I can't quite figure out how it works. I was wondering if someone > could clarify it for me. > The Code is: > > import pygame > import weakref > > class ResourceController(object): > ? ? def __init__(self, loader): > ? ? ? ? self.__dict__.update(dict( > ? ? ? ? ? ? names = {}, > ? ? ? ? ? ? cache = weakref.WeakValueDictionary(), > ? ? ? ? ? ? loader = loader > ? ? ? ? )) > > ? ? def __setattr__(self, name, value): > ? ? ? ? self.names[name] = value > > ? ? def __getattr__(self, name): > ? ? ? ? try: > ? ? ? ? ? ? img = self.cache[name] > ? ? ? ? except KeyError: > ? ? ? ? ? ? img = self.loader(self.names[name]) > ? ? ? ? ? ? self.cache[name] = img > ? ? ? ? return img > > class ImageController(ResourceController): > ? ? def __init__(self): > ? ? ? ? ResourceController.__init__(self, pygame.image.load) > > My question is why does the __setattr__ set the value to > self.names[name] instead of self.cache[name]? I feel stupid, I figured it out. (Don't program while watching Back to the Future) The reason would be the 'lazy' part. self.names holds the file name, and when you get the property back (__getattr__) it checks to see if it already got the value or not, and uses the name to get the value if it hasn't already. Duh. Sorry. From sjmachin at lexicon.net Mon Sep 8 05:31:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Sep 2008 02:31:30 -0700 (PDT) Subject: String to hexadecimal conversion References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Message-ID: <14aa61b1-fb8c-44c4-bbf2-d8d2f92006e9@p10g2000prf.googlegroups.com> On Sep 8, 7:05?pm, Praveena P wrote: > Hi folks, > > I am new to Python... so am not too sure about how the type conversion > works. > > I have to read a file that contains hexadecimal data and use the data > further to do some arithmetic calculations. > A sample of the input is : 00000000000020E0000032F800000000400022005E > The problem I am facing is this: > I am using f.read(2) to read a byte at a time, but the data that is > read is a string rather than a number. So it kind of hampers any > arithmetic operations I perform on this data... > > Could you please suggest some method I could use for this? *IF* all the data consists of unsigned 8-bit integers a_byte = f.read(2) uint8 = int(a_byte, 16) But I doubt it and that would be rather slow anyway. If your data is homogenous, look at the array module. Otherwise, once you've worked out how to break your file down into records, and what the layout of each record is, you'll need the struct module. HTH, John From brtzsnr at gmail.com Mon Sep 29 10:56:06 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Mon, 29 Sep 2008 07:56:06 -0700 (PDT) Subject: blocking all threads Message-ID: <1d161e02-4b39-462c-a485-d93eb0423e9b@v13g2000pro.googlegroups.com> how can I block all threads for a specific amount of time? (i need to sleep whole process for testing purposes). i thought of accessing GIL and sleep for some amount of time, but I don't know how to do this and whether GIL is recursive. From tjreedy at udel.edu Wed Sep 17 15:59:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Sep 2008 15:59:28 -0400 Subject: Python and Open Office In-Reply-To: <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Hartmut Goebel wrote: > Terry Reedy schrieb: > >> One way to learn the meaning of some of the numerous attributes and >> values is to create a file with the wanted features with OOo, save, >> unzip, and examine the xml to see which tags are used for which features. > > The API docs are a bit hidden on the webpage. Here is the link: > I wrote my comment *after* looking at the above, which I found easily enough. After 7 pages of (helpful) explanatory text, there follow 88 pages with hundreds of entries like this: 5.13.30 style.RubyProperties Requires the following attributes: No attribute is required. Allows the following attributes: rubyalign, rubyposition. These elements contain style.RubyProperties: style.DefaultStyle, style.Style. The following elements occur in style.RubyProperties: No element is allowed. which are translated to a more readable form from the Relax-NG schema (formal specs) in the standard. But I have no idea what a Ruby property is in this context. It would be much like reading the grammar entries in the Python Reference without the explanatory text that follows. > Additionally teh ODF sepcs may help: > v1.0 is the adopted international (ISO/IEC) standard. I did not notice whether odfpy supports the 1.1 extensitons, but since it does appear that OOo now uses them, I will presume so. This does help. It has more explanatory material. "5.4 Ruby A ruby is additional text that is displayed above or below some base text. The purpose of ruby is to annotate the base text or provide information about its pronunciation. tjr From nick at craig-wood.com Tue Sep 30 17:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 30 Sep 2008 16:30:05 -0500 Subject: Advice for a replacement for plone. References: Message-ID: Ken Seehart wrote: > I want a new python based CMS. ... One that won't keep me up all night .... > > I've been fooling around with zope and plone, and I like plone for some > things, such as a repository for online project documentation. However > for general-purpose web development it is too monolithic. Is there > anything out there with the following properties? > > 0. Web page being developed is a typical small business home page (i.e. > not a newspaper or a blog). > 1. Page owner can edit pages on line with no expertise (plone does great > here). > 2. Main page does not look plone-like. For an example of a main page > that does not look plone-like, see http://www.arbitrary.com/ Note the > lack of CMS style navigation widgets. > 3. Item 2 should be reachable with nearly no effort (plone fails utterly > here). > 4. Target viewer (not the owner), should /not/ see something that looks > at all like a CMS system, but rather see exactly what the page owner > wants the page to look like. > 5. Page owner should be able to view and navigate the tree of contents, > and select pages to edit with a wysiwyg editor (plone does great here)... > 6. ... But the target viewer should not see this tree. See items 2 and 4. > 7. Potential to add python scripted pages of various kinds. > > There are a couple different design approaches to making a > development environment. You can let the developer start with nothing, > and provide the developer with tools to create something (e.g. zope, > most plain text editors), or you can start with a finished result and > let the developer rip out and discard what is not desired (e.g. plone). > I often prefer to start with nothing. It's a natural starting point. > Note that systems that are based on starting with nothing can provide > the benefits of starting with something by providing templates and such. > > > I would love to see a system that would give me an editable Hello World > page in under 5 minutes. Hello World would be a page consisting of > nothing but the words "hello world" (no tools, no navigation bar, and > certainly no CMS navigation stuff) in a url such as > www.myhelloworldwebsite.com/hello and a different url to edit the page, > such as www.myhelloworldwebsite.com/hello/edit or > www.mywebsite.com/edit/hello Django + flatpages maybe? Coming from the starting from nothing approach. There are links to some sites built with it in the docs below. http://docs.djangoproject.com/en/dev/ref/contrib/flatpages/ A bit more of a learning curve but you'll definitely be in charge. Somebody used to Django could set up a flatpages site in 5 minutes probably! It will take you a couple of hours the first time though. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gagsl-py2 at yahoo.com.ar Thu Sep 18 22:12:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Sep 2008 23:12:22 -0300 Subject: Do HTTPError objects always have a read method? References: Message-ID: En Wed, 17 Sep 2008 22:48:27 -0300, Steven D'Aprano escribi?: > I understood that HTTPError objects always have a read method, so they > can be treated as if they were a webpage. E.g. something like this > simplified snippet: > > > address = 'http://www.yahoo.com/spamspamspamspamspam' > try: > conn = urllib2.urlopen(address) > except urllib2.HTTPError, e: > conn = e > print conn.read() # Print the requested page, or the error page. > > > > But in the source code to urllib2 (Python 2.5): > > > class HTTPError(URLError, addinfourl): > """Raised when HTTP error occurs, but also acts like non-error > return""" > __super_init = addinfourl.__init__ > > def __init__(self, url, code, msg, hdrs, fp): > self.code = code > self.msg = msg > self.hdrs = hdrs > self.fp = fp > self.filename = url > # The addinfourl classes depend on fp being a valid file > # object. In some cases, the HTTPError may not have a valid > # file object. If this happens, the simplest workaround is to > # not initialize the base classes. > if fp is not None: > self.__super_init(fp, hdrs, url) > > That tells me that HTTPError objects aren't guaranteed to include a file- > like interface. That makes me unhappy. > > Under what circumstances do HTTPError objects not have a valid file > object? How common is this? Does anyone have an example of a URL that > fails in that fashion? Well, there is at least one case (AbstractDigestAuthHandler at line 864 in urllib2.py) where HTTPError is raised explicitely with fp=None. It's not a common case, I think. If you rely on the exception having a read() method, add it a fake one yourself: try: ... except urllib2.HTTPError, e: if not hasattr(e, 'read'): e.read = e.readline = lambda self: '' # or perhaps e.msg conn = e -- Gabriel Genellina From default at defaulter.net Sat Sep 27 21:38:04 2008 From: default at defaulter.net (default) Date: Sat, 27 Sep 2008 21:38:04 -0400 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> Message-ID: <7qmtd4hc52o84pksc6tni0pmgnfvpvf08m@4ax.com> On Sat, 27 Sep 2008 23:12:59 +0000 (UTC), Cydrome Leader wrote: >In rec.crafts.metalworking Jim Thompson wrote: >> >> On Sat, 27 Sep 2008 18:47:16 -0400, default >> wrote: >> >>>On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko >>> wrote: >>> >>>>Hello, this is Milenko Stojadinovic from town Banjaluka, >>>>Bosnia and Herzegovina, also known as Cvrcko >>>>Does anyone know of any bars in town where I can >>>>swallow a bucket of cum? It can be either dog, >>>>horse or human cum. Also, does anyone know of >>>>any sex bars where people will shit in your mouth? >>>>I also like eating shit. >>> >>>Come to the US and park your mouth in front of George Bush - all the >>>Bshit you can eat - and it keeps on coming! >>> >>>I have a buddy in Bosna - he's normal. >> >> Now you know why I blanket kill-file googlegroups. > >So you and everybody can talk about them nonstop? If you mean Google Groups the condemnation is justified. Who is "them?" Real people do occasionally wander in to GG - or those without news servers - or without understanding of Usenet. Basically, in the engineering groups (in particular) outsiders are welcome. Engineers are smart, creative and tolerant as a general rule. Lighten up. Who are you defending? and Who goes into Usenet with a thin skin? Expect ridicule, expect condemnation - "water off a duck's back." You may think your viewpoint is the only one, the right one, the valid one - but a few million others may disagree. And you ain't started to deal with culture shock - some countries place emphasis on diplomacy _ you know the "how are you?" stuff, others don't, and seem very cold. Adapt. -- ----== Posted via Pronews.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.pronews.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= - Total Privacy via Encryption =--- From bdesth.quelquechose at free.quelquepart.fr Thu Sep 25 14:14:26 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 20:14:26 +0200 Subject: Quick sort implementation in python In-Reply-To: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: <48dbf0ed$0$16897$426a74cc@news.free.fr> Alex Snast a ?crit : > Hi guys, I've been learning python in the past week and tried to > implement a q.sort algorithm in python Is that for learning purpose ? Else, it's just a waste of time... From ireborin at delete.this.gmail.com Tue Sep 30 12:11:25 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 18:11:25 +0200 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: On 30 Sep 2008 15:31:59 GMT, Peter Pearson wrote: > >Since you're coming from the FORTRAN world (thank you for >that stroll down Memory Lane), you might be doing scientific >computations, and so might be interested in the SciPy >package (Google scipy), which gives you arrays and matrices. >Don't expect to be able to use it without learning some Python, >though. Actually, no (regarding memory lane :-). I'm helping a friend to translate some of my old routines to python so he can use them in his programs. I'm still using fortran84, and mean to continue doing so as long as something better doesn't come along. But as I said, got a job that't got to be done, so I'm trying to figure out how to do array operations as easily as possible in python, which are necessary for all my calculations. Best regards Ivan From zhouyangpku at gmail.com Mon Sep 1 00:43:43 2008 From: zhouyangpku at gmail.com (zhouyangpku at gmail.com) Date: Sun, 31 Aug 2008 21:43:43 -0700 (PDT) Subject: Installing Python 2.5.2: 'make' fails in posixmodule.c Message-ID: <18f40e8b-4488-40a5-a831-3388ece2300f@v16g2000prc.googlegroups.com> Dear friends: I'm trying to install python on irix 6, the lab server. It fail at ' make ' procedure for Modules/posixmodule.c. I've just configured the prefix for my own path and no other option changed. make clean didn't help. Here it is: gcc -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE - DPYTHONPATH='":plat-irix6:lib-tk"' \ -DPREFIX='"/user_data2/yzhou/local"' \ -DEXEC_PREFIX='"/user_data2/yzhou/local"' \ -DVERSION='"2.5"' \ -DVPATH='""' \ -o Modules/getpath.o ./Modules/getpath.c gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -c ./Modules/ posixmodule.c -o Modules/posixmodule.o Modules/posixmodule.c: In function `posix_listdir': Modules/posixmodule.c:2162: `DIR' undeclared (first use in this function) Modules/posixmodule.c:2162: (Each undeclared identifier is reported only once Modules/posixmodule.c:2162: for each function it appears in.) Modules/posixmodule.c:2162: `dirp' undeclared (first use in this function) Modules/posixmodule.c:2173: warning: implicit declaration of function `opendir' Modules/posixmodule.c:2177: warning: implicit declaration of function `closedir' Modules/posixmodule.c:2183: warning: implicit declaration of function `readdir' Modules/posixmodule.c:2183: warning: assignment makes pointer from integer without a cast Modules/posixmodule.c:2187: dereferencing pointer to incomplete type Modules/posixmodule.c:2188: dereferencing pointer to incomplete type Modules/posixmodule.c:2189: dereferencing pointer to incomplete type Modules/posixmodule.c:2189: dereferencing pointer to incomplete type Modules/posixmodule.c:2191: dereferencing pointer to incomplete type Modules/posixmodule.c:2191: dereferencing pointer to incomplete type In file included from /usr/include/stropts.h:38, from Modules/posixmodule.c:3497: /usr/include/sys/stropts.h: At top level: /usr/include/sys/stropts.h:237: parse error before "t_uscalar_t" /usr/include/sys/stropts.h:261: parse error before "t_uscalar_t" /usr/include/sys/stropts.h:267: parse error before '}' token Modules/posixmodule.c: In function `posix_seteuid': Modules/posixmodule.c:5362: warning: implicit declaration of function `seteuid' Modules/posixmodule.c: In function `posix_setegid': Modules/posixmodule.c:5382: warning: implicit declaration of function `setegid' *** Error code 1 (bu21) From duncan.booth at invalid.invalid Tue Sep 16 04:55:36 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Sep 2008 08:55:36 GMT Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: "Chris Rebert" wrote: > On Tue, Sep 16, 2008 at 1:20 AM, Armin wrote: >> [1,2,3,4,7].append(c) -> Is this a valid expression? > > Literally, no, because you can't call methods on literals. Rubbish. There is no restriction about calling methods on literals. That expression is perfectly valid but has no practical use that I can see. There is a syntax gotcha which you may have been thinking of: to call a method on an integer literal (or indeed to access any attribute) you have to use whitespace between the literal and the dot otherwise you have a float literal and a syntax error. >>> 5 .__hex__() '0x5' The only relatively common use I can think of where you might want to call a method directly on a literal is to produce a list of strings while being lazy about the typing: COLOURS = "red green blue pink yellow".split() versus COLOURS = ["red", "green", "blue", "pink", "yellow"] -- Duncan Booth http://kupuguy.blogspot.com From bearophileHUGS at lycos.com Thu Sep 18 19:20:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 18 Sep 2008 16:20:20 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <6d9c1b56-1322-4062-94c4-dd1388421abc@z66g2000hsc.googlegroups.com> Bruno Desthuilliers: > def doubles9(): > ... > SN = [] > sn_append = SN.append Few more: import psyco def doubles10(): dup = set() SN = [] for item in IN: c = item.coordinates if c in dup: SN.append(item) else: dup.add(c) return SN psyco.bind(doubles10) from collections import deque def doubles11(): dup = set() dup_add = dup.add SN = deque() sn_append = SN.append for item in IN: c = item.coordinates if c in dup: sn_append(item) else: dup_add(c) return SN def doubles12(): dup = set() SN = deque() for item in IN: c = item.coordinates if c in dup: SN.append(item) else: dup.add(c) return SN psyco.bind(doubles12) Timings: doubles00 : 0.522365288653 doubles01 : 0.247219812198 doubles02 : 0.237889823898 doubles03 : 0.238638921389 doubles04 : 0.23821698217 doubles05 : 0.177042495425 doubles06 : 0.13166199162 doubles08 : 0.00569725197252 doubles09 : 0.00418566685667 doubles10 : 0.00192086920869 doubles11 : 0.00403324533245 doubles12 : 0.00184026840268 Hopefully that's fast enough :-) Bye, bearophile From showellshowell at gmail.com Sun Sep 14 21:50:22 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Sun, 14 Sep 2008 18:50:22 -0700 (PDT) Subject: "Best" way to "drive" a Python program step by step. References: Message-ID: <0c203edf-8036-4356-83e4-60a575482a1b@b30g2000prf.googlegroups.com> On Sep 14, 5:41?pm, Andr? wrote: > Hi everyone, > > I'd be interested in hearing suggestions as to the "best" way to drive > a Python program step by step from another application. > Andre, If you want a Javascript program to render the results of a "syncrhronouse" Python program in "real time," with the ability to pause, kill, etc., I would suggest a three-tier architecture: Javascript client -> Python mediator -> Python target program The Python target program would be something like this, written in a very synchronous style: while True: send_command_to_javascript_and_wait('move') send_command_to_javascript_and_wait('turnleft') The target program would be simple Python code, and the only minor magic would be in the send_command_to_javascript_and_wait method, which would normally just call "print," but when running as a subprocess, would block until the parent indicates it should proceed. I think it's useful, especially on this mailing list, to think about how the Python "mediator" program controls the Python "target" program. Essentially you want the "target" program to be a subprocess of the "mediator" program. You will probably want to use the "Subprocess" module. Look at the "Reading Output of Another Command" section of the article below: http://www.oreillynet.com/onlamp/blog/2007/08/pymotw_subprocess_1.html Once you solve the problem of having another Python program control your "target" program, it's not too big a conceptual leap to have a Javascript (JS) program control it. I would suggest the following high level architecture: 1) JS client communicates with Python mediator via HTTP Ajax calls. 2) JS can send HTTP request to mediator to have it start the target as a subprocess. 3) JS can send HTTP request to mediator to have it deliver data to target subprocess. 4) Target subprocess can send data back to mediator that is to be part of the HTTP response. In your rur-ple application data will be flowing mostly in one direction. The JS client will simply be telling the Python target to advance a step, while the Python target will be giving specific metadata about how to update the world that JS renders. Still, despite the asymmetrical nature of your app, I would try to think of it as a two-way exchange of data. The JS program is communicating what the user wants to do next (usually a generic request to execute the next instruction), and the Python backend is communicating how to change the view (usually as a builtin command like move_robot or highlight_line_of_code), but ultimately it's all data. Hope that helps! Cheers, Steve http://webstervanrobot.com/ From tjreedy at udel.edu Mon Sep 22 17:53:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 17:53:04 -0400 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Robert Kern wrote: > (if someone wants to submit this to bugs.python.org, be my guest) http://bugs.python.org/issue3936 From bignose+hates-spam at benfinney.id.au Mon Sep 29 09:21:58 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 29 Sep 2008 23:21:58 +1000 Subject: One class per file? References: Message-ID: <87od27rssp.fsf@benfinney.id.au> HCB writes: > The book "Code Complete" recommends that you put only one class in a > source file, which seems a bit extreme for me. For Python, that is extreme, and for most applications I've seen it would be counterproductive. Which edition of Code Complete recommends this, and on which page? > Perhaps a better rule of thumb is "one idea per file." I checked the > Python style guide and there seems to be no mention of this topic. I > know this is an elementary question, but what is the Python way of > doing this? You have it right: modules are most naturally used for conceptual grouping of objects (not just classes, but all objects) related to a discrete area of functionality, into a discrete namespace. -- \ ?The WWW is exciting because Microsoft doesn't own it, and | `\ therefore, there's a tremendous amount of innovation | _o__) happening.? ?Steve Jobs | Ben Finney From cjdrake at gmail.com Tue Sep 23 16:25:26 2008 From: cjdrake at gmail.com (Drake) Date: Tue, 23 Sep 2008 13:25:26 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() Message-ID: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> I have a general question of Python style, or perhaps just good programming practice. My group is developing a medium-sized library of general-purpose Python functions, some of which do I/O. Therefore it is possible for many of the library functions to raise IOError Exceptions. The question is: should the library function be able to just dump to sys.exit() with a message about the error (like "couldn't open this file"), or should the exception propagate to the calling program which handles the issue? Thanks in advance for anyone who can either answer my question or point me to where this question has already been answered. From zugnush at gmail.com Wed Sep 3 06:35:15 2008 From: zugnush at gmail.com (zugnush at gmail.com) Date: Wed, 3 Sep 2008 03:35:15 -0700 (PDT) Subject: sys.stdin on windows References: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> Message-ID: <59f18445-c5f0-4ea7-915f-39102cf04f10@s9g2000prg.googlegroups.com> On Sep 3, 11:16?pm, Tim Golden wrote: > Gabriel Genellina wrote: > > En Wed, 03 Sep 2008 06:16:03 -0300, zugn... at gmail.com > > escribi : > > >> I often grep particular patterns out of large logfiles and then > >> pipeline the output to sort and uniq -c > >> I thought today to knock up a script to do the counting in a python > >> dict. > > >> This seems work in linux > > >> $ cat count.py > >> #!/usr/bin/env python > >> import sys > >> from collections import defaultdict > >> accumulator=defaultdict(int) > >> for line in sys.stdin.readlines(): > >> ? ? accumulator[line.strip()]+=1 > >> print "contents,count" > >> for key in accumulator.keys(): > >> ? ? print key,",",accumulator[key] > > >> $ cat test | ./count.py > >> contents,count > >> ?, 1 > >> 23 , 1 > >> 1 , 1 > >> 3 , 2 > >> 2 , 2 > >> 5 , 3 > > >> When I try to run the same thing on windows I get > >> IOError: [Error 9] Bad file descriptor > > >> How can I make this more windows friendly? > > > Explicitely invoking the interpreter worked for me. That is, these two > > commands worked fine: > > > type test.txt | python count.py > > python count.py < test.txt > > > But I cannot explain *why* it doesn't work the other way. > > Known bug in NT-based file association. I'll try > to find an online reference, but that's basically > what it comes to. I think you can faff-about with > batch files to achieve the effect, but I can't > quite remember. > > http://support.microsoft.com/kb/321788 > > TJG Thanks. I'll ues the explicit python call. From jaycx2.3.calrobert at spamgourmet.com.remove Mon Sep 1 04:45:51 2008 From: jaycx2.3.calrobert at spamgourmet.com.remove (Robert Maas,) Date: Mon, 01 Sep 2008 01:45:51 -0700 Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> Message-ID: > From: r... at rpw3.org (Rob Warnock) > In the LGP-30, they used hex addresses, sort of[1], but the > opcodes (all 16 of them) had single-letter mnemonics chosen so that > the low 4 bits of the character codes *were* the correct nibble for > the opcode! ;-} That's a fascinating design constraint! It would be an interesting puzzle to find the most efficient design whereby: - The single-character mnemonics are as easy to memorize as possible; - The instructions produce as efficient code as possible; - The mnemonics really do accurately express what the instruction does; - Minimize total number of instructions needed, maybe fewer than 16; - With the low-order-four-bits rule of course. - See also the avoid-ambiguous-sound criterion later below. By the way, do you remember exactly all the 16 opcodes, or have a Web reference available? > [Or you could type in the actual hex digits, since the low 4 bits > of *their* character codes were also their corresponding binary > nibble values... "but that would have been wrong".] Moreso because some of the sounds would be ambiguous, which I recognized when I first started to use the IBM hexadecimal standard. See below. > The LGP-30 character code was defined before the industry had > yet standardized on a common "hex" [sic, "hexadecimal", base 16 > not base 6!!!] character set, Before IBM had decided to use hexadecimal in their abend coredumps from their System/360 and by their 800-pound-gorilla status they got everyone else to use that ABCDEF system. > they used "0123456789fgjkqw". That doesn't make sense. The low-order four bits of those letters aren't consecutive ascending values from 9+1 to 9+6. Did you make a typo, or did you explain something wrong? (map 'list #'char-code "0123456789fgjkqw") => (48 49 50 51 52 53 54 55 56 57 102 103 106 107 113 119) (loop for n in * collect (rem n 16)) => (0 1 2 3 4 5 6 7 8 9 6 7 10 11 1 7) Now if you used this sequence of letters instead: (map 'list #'char-code "0123456789jklmno") => (48 49 50 51 52 53 54 55 56 57 106 107 108 109 110 111) (loop for n in * collect (rem n 16)) => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) Unfortunately o looks like 0, and l looks like 1. Anyway, what I hated about IBM's hexadecimal notation was: - A0 would be pronounced "Ay-tee", which sounds too much like "Eighty". - 1A would be pronounced "Ay-teen", which sounds too much like "Eighteen". - On the lineprinters where we get our abend listings, the capital D and digit 0 (which didn't have any diagonal slash) looked almost identical when the ribbon was going bad, as it always was. - Likewise B and 8 looked nearly identical. - Likewise E and F often looked nearly identical of lower part of E was hitting bad part of ribbon. Now for single-character mnemonics for four bits of instruction opcode, to avoid any two characters that look too similar: 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z We obviously have no choice for KLMNO, so because of look-alike we can't use 0 or D or Q, so we have to use P instead of 0, so our choices look like: 1 2 3 4 5 6 7 8 9 A B C E F G H I J K L M N O P R S T U V W X Y Z If we have an opcode that sets a register to 1, or clears register#1, we might use mnemonic "1" for that instruction, but otherwise we must avoid using digits, use letters only. 1 A B C E F G H I J K L M N O P R S T U V W X Y Z We can't use both U and V, and we can't use both E and F, and we can't use both 1 and I, but we're stuck using both M and N, sigh. At this point I can't decide which branches of the search to discard and which to fix, so I'll stop analysing this puzzle. (With lower-case characters different combinations were mutually exclusive, such as l and 1, but I was doing upper case here.) If punctuation is allowed, then + - * / = < > would make dandy mnemonic opcodes for the obvious instructions. If characters that look like arrows can be used for push and pop, then we have V for push and ^ for pop. If characters that look like arrows can be used for moving left/right in RAM, or shifting bits in a register, then we have < for left and > for right. I wonder if solving this puzzle will yield yet another esoteric programming language? From daniel.watrous at gmail.com Tue Sep 30 17:38:19 2008 From: daniel.watrous at gmail.com (Daniel) Date: Tue, 30 Sep 2008 14:38:19 -0700 (PDT) Subject: problem with "ImportError: No module named..." and sockets Message-ID: Hello, I'm trying to build a very simple IPC system. What I have done is create Data Transfer Objects (DTO) for each item I'd like to send across the wire. I am serializing these using cPickle. I've also tried using pickle (instead of cPickle), but I get the same response. Below is the code. I'll put the rest of my comments after the code [BEGIN CODE] #!/usr/bin/python import SocketServer import os, sys newpath = os.path.normpath( os.path.join( __file__, "../../.." )) sys.path.insert(0, newpath) from pop.command.UpdateCommand import * import cPickle class RequestHandler(SocketServer.StreamRequestHandler): "Handles one request to mirror some text." def handle(self): total_data=[] line = True while line: line = self.rfile.readline().strip() total_data.append(line) receivedCommand = '\n'.join(total_data) newUpdate = cPickle.loads(receivedCommand) print type(newUpdate) for item in newUpdate.items: print str(type(item)) + " with filename: " + item.filename if __name__ == '__main__': import sys if len(sys.argv) < 3: print 'Usage: %s [hostname] [port number]' % sys.argv[0] sys.exit(1) hostname = sys.argv[1] port = int(sys.argv[2]) server = SocketServer.ThreadingTCPServer((hostname, port), RequestHandler) server.serve_forever() [/END CODE] So I can create the UpdateCommand object on the client, send it across the wire and I get as far as the line "newUpdate = cPickle.loads(receivedCommand)", which when it runs produces the following error: Traceback (most recent call last): File "C:\Python25\lib\SocketServer.py", line 464, in process_request_thread self.finish_request(request, client_address) File "C:\Python25\lib\SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python25\lib\SocketServer.py", line 522, in __init__ self.handle() File "C:\Documents and Settings\dwatrous\My Documents\projects\POP \svn\pop\lib\server.py", line 29, in handle newUpdate = cPickle.loads(receivedCommand) ImportError: No module named UpdateCommand I import the module at the top of the file server.py, but it doesn't throw the ImportError until it tries to unpickle. Please help with any ideas that you have. From lixinyi.23 at gmail.com Wed Sep 24 04:04:43 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Wed, 24 Sep 2008 01:04:43 -0700 (PDT) Subject: PyRun_SimpleFile() crashes References: Message-ID: <89a7ade9-c2d2-4d40-ad52-fe0df6fa25d3@g17g2000prg.googlegroups.com> On 9?24?, ??3:39, lixinyi... at gmail.com wrote: > my code: > main.cpp > #include > > int main(int argc, char **argv) > { > Py_Initialize(); > > FILE *file_1 = fopen("a2l_reader.py","r+"); > PyRun_SimpleFile(file_1,"a2l_reader.py"); > > Py_Finalize(); > > } > > compile under windows using MinGW: > g++ main.cpp libpython25.a -o a > > no error was found. But when I run a.exe the program just crashes. > > What should I do? PyRun_File and PyRun_SimpleFile would just crash my application. but PyRun_SimpleString works fine. But why??? From bearophileHUGS at lycos.com Thu Sep 25 08:57:22 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Sep 2008 05:57:22 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> Message-ID: Duncan Booth: > Microsoft added a common set of extension methods which work on > databases, xml, builtin sequences and can be easily extended to include > other custom sequences. When the processing is done in memory, LINQ may also work well with multi-core CPUs, see PLINQ. Bye, bearophile From agostino.russo at gmail.com Tue Sep 9 14:09:45 2008 From: agostino.russo at gmail.com (ago) Date: Tue, 9 Sep 2008 11:09:45 -0700 (PDT) Subject: PYTHONSITEDIR environment variable References: Message-ID: On Sep 9, 6:56?pm, Christian Heimes wrote: > I had a similar idea, wrote a PEP and implemented it for 2.6 and 3.0: > > http://www.python.org/dev/peps/pep-0370/ > > Christian Christian, I like your pep :), The only thing I would add is that in my experience I often use different working-envs for different projects, so I'd prefer to have a more generic solution as opposed to a single working-env per user. The latter could still be achieved by setting the appropriate environment variable in the user profile. Do you think it would be possible to accommodate for the above in your PEP? From deets at nospam.web.de Thu Sep 25 16:55:21 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:55:21 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: References: <6k2aqqF5p185U1@mid.uni-berlin.de> Message-ID: <6k2c5pF5oenoU1@mid.uni-berlin.de> > that is a very valid point, but it seemed that Scott has homogeneous > environment: Debian/Ubuntu so my post was relative to the original request. > I agree that when you throw Windows/MacOS into the mix things > become "interesting". But then it's better when your developers develop on > server/platform they are going to be using, using same stack they going to > face in production etc. It all depends on requirements and current > practices in company. Well, you certainly want a desktop-orientied Linux for users, so you chose ubuntu - but then on the server you go with a more stable debian system. Even though the both have the same technical and even package management-base, they are still incompatible wrt to package versions for python. And other constraints such as Photoshop not being available for Linux can complicate things further. >> - keeping track of recent developments. In the Python webframework >> world for example (which the OP seems to be working with), things move >> fast. Or extremly slow, regarding releases. Take Django - until 2 month >> ago, there hasn't been a stable release for *years*. Virtually everybody >> was working with trunk. And given the rather strict packaging policies >> of debian and consorts, you'd be cut off of recent developments as well >> as of bugfixes. > > that definitely becomes tricky however not impossible to track. You do need > a common snapshot for all developers to use anyway - so why not just > package it up? I do, but based on Python eggs. They are platform independent (at ultimo, you can use the source distribution, albeit that sux for windows most of the time), and as I explained in my other post - things are moving in the right direction. Don't get me wrong - I love .deb-based systems. But if using them for my development means that I have to essentially create a full zoo of various packages *nobody else* uses - I rather stick with what's working for me. Diez From sumerc at gmail.com Thu Sep 25 10:45:21 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 25 Sep 2008 07:45:21 -0700 (PDT) Subject: Python OOP question Message-ID: Hi all, I am trying to develop a game-server in python. Design is as following: - ConnectionManager - handling/distributing incoming connections - IOManager - handling IO recv/send operations on sockets. (inheritable) - Socket - basic async socket object - SocketServer - handling multiple socket object requests. (inheritable) - Options - holds the server options (inheritable) I want this code to be extensible as it can be. So I have developed it like this. I f one is going to implement some new feature, all needs to be done is to inherit IOManager or Server object to do it. Inheritable objects are IOManager, SocketServer and Options. But there is some feeling about this design that it can be better. Here is the main.py which I am using to execute the server: from Base.SocketServer import SocketServer from testIOManager import testIOManager from Base.Options import Options from Base.ConnectionManager import ConnectionManager iomgr = testIOManager() opts = Options() # calculate how many server objects to create # according to the maximum allowed client count. serverCnt = opts.MAX_CLIENT_COUNT / opts.MAX_CLIENT_COUNT_PER_SERVER Servers = [] for i in range(serverCnt): server = Server(i) Servers.append(server) cmgr = ConnectionManager(Servers, iomgr, opts) cmgr.start() With current design as server object is inheritable, I need to pass it to ConnectionManager object. I just have a feeling that above design is bad in the sense of readability. Is there any paradigms. patterns specifically in Python for above like situations, where in a library, we design some objects to be abstract as possbile and other non-inheritable objects using the functions? Or just any feedback on this Design structure? From gslindstrom at gmail.com Mon Sep 22 16:18:56 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 22 Sep 2008 15:18:56 -0500 Subject: pyArkansas Set for October 4th Message-ID: This is a reminder of the upcoming pyArkansas one-day Python conference being held on the campus of the University of Central Arkansas on Sat Oct 4, 2008. The schedule is pretty much set ( http://pycamp.python.org/Arkansas/Schedule) and has something for anyone interested in Python, from intro workshops to advanced topics. Jeff Rush and Noah Gift are scheduled to present workshops and talks while Dr. Bernard Chen (UCA Faculty) will teach a 3-hour class on "Python for the Absolute Beginner". Eggs, pyGame, standard library, Eclipse and OLPC are some of the other talks scheduled. This is a *FREE* event (we have GREAT sponsors), so all you need to bring is yourself. We have over 45 people -- from 4 States -- registered and tons of great swag and giveaways lined up. See our wiki (http://pycamp.python.org/Arkansas/HomePage) for more details and registration info. Greg Lindstrom Python Artists of Arkansas (pyAR^2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From digitig at gmail.com Fri Sep 26 12:48:04 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 26 Sep 2008 17:48:04 +0100 Subject: Not fully OO ? In-Reply-To: <48DCC786.2040407@wildenhain.de> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: 2008/9/26 Tino Wildenhain : >> The question I usually ask is "Does this language help me get the job >> done?" Python often does. That's all that really matters, isn't it? > > Well then it still depends on the perception of "job done". For example > PHP programmers would bet their soul that their language of choice is > exactly the right one to "get the job done." :-) > You and me would indeed see a different picture on the level of doneness > of such jobs ;-) Well, I did say "Often". Before now I've struggled for ages to write a Python program to do a job, then when I've tried C# all the problems have fallen away and the job was done in an hour or so. But other times it has been the other way around; I've done stuff in Python that I wouldn't know where to begin with in other languages. One of my constant refrains is that *no* tool is ideal for *all* jobs! -- Tim Rowe From mhuening at zedat.fu-berlin.de Tue Sep 23 10:44:57 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Tue, 23 Sep 2008 16:44:57 +0200 Subject: tkFileDialog and locale under Linux Message-ID: <6jsdn9F4p743U1@mid.uni-berlin.de> Hi, I have problems using tkFileDialog under Linux (Ubuntu 8.04 in my case, but other Linuxes seem to show the same behaviour). The following works fine: import tkFileDialog f = tkFileDialog.askopenfilename() No problem, I can chose a filename. But when switching the locale (in my case to German) like this: import locale locale.setlocale(locale.LC_ALL, '') the file dialog won't work anymore. The traceback is: Traceback (most recent call last): File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1406, in __call__ return self.func(*args) File "TextSTAT.pyw", line 701, in datei_hinzu dateinamen = tkFileDialog.askopenfilename(initialdir=cfg['FileDir'], filetypes= (('All', '*.*'),('Text', '*.txt'),('HTML', '*.htm*'),('MS Word', '*.doc'),('MS Word 2007', '*.docx'),('OpenOffice 1.x', '*.sxw'),('OpenOffice 2.x', '*.odt')), multiple=1) File "/usr/lib/python2.5/lib-tk/tkFileDialog.py", line 125, in askopenfilename return Open(**options).show() File "/usr/lib/python2.5/lib-tk/tkCommonDialog.py", line 48, in show s = w.tk.call(self.command, *w._options(self.options)) TclError: expected floating-point number but got "0.0" Switching back to the C-locale solves the problem: locale.setlocale(locale.LC_ALL, 'C') tkFileDialog will work again. Any ideas? Best, Matthias From fredrik at pythonware.com Sun Sep 14 08:39:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Sep 2008 14:39:30 +0200 Subject: Stuck connection in Python 3.0b2 http.server In-Reply-To: <1a23cbe5-26f5-4332-8901-7aa06c69d68e@k7g2000hsd.googlegroups.com> References: <1a23cbe5-26f5-4332-8901-7aa06c69d68e@k7g2000hsd.googlegroups.com> Message-ID: rs387 wrote: > I've encountered a weird issue when migrating a web server to Python 3 > - the browser would wait forever without showing a page, displaying > "Transferring data" in the status bar. I tracked it down to a > reference cycle in my BaseHTTPRequestHandler descendant - one of the > attributes stored a dict of methods. Removing the cycle made the > problem go away. > > In Python 2.5.2 the code works fine either way. > > Here's a minimal example which runs in both 2.5 and 3.0 - to see stuck > connections run as-is in 3.0 and navigate to http://localhost:8123; to > fix this comment out "self.dummy = self" (alternatively reset > self.dummy = None at the end of the __init__ method). > > Am I doing it wrong, or is this a bug? it's weird enough to deserve an issue over at http://bugs.python.org/, at least. it'd probably be a good idea to test this on 2.6rc as well. From gregturn at mindspring.com Fri Sep 5 09:47:54 2008 From: gregturn at mindspring.com (Goldfish) Date: Fri, 5 Sep 2008 06:47:54 -0700 (PDT) Subject: Spring Python 0.6.0 has been released Message-ID: Spring Python 0.6.0, the python offshoot of the Spring framework and Spring Security, has been released (http:// springpython.webfactional.com). See http://sourceforge.net/project/showfiles.php?group_id=184275&package_id=214366&release_id=624328 for more details. BTW, if you click on the release notes link, there is a report pulled from JIRA (our new bug tracking software) showing the issues. For more details, you have to create an account at jira.springframework.org, and then surf to Spring Python. There, you can see it all nicely bundled at http://jira.springframework.org/secure/IssueNavigator.jspa?reset=true&pid=10270&fixfor=11085. Spring Python is moving forward in tremendous ways! Working with the build team in England, we have gotten things integrated with a continuous integration server. See http://build.springframework.org/browse/EXT, and then surf into the Spring Python parts to see our results. This is great! Just check out http://build.springframework.org/browse/EXT-PYQUICK-19 for archived sample of the success of this project. If you look closely, you may notice that MySQL and PostGreSQL test cases have been commented out. That is because we don't have support for those RDBMS's on CI at this point in time. Don't be alarmed. I have run tests with and without thos test suites, and the difference in code coverage is 85% vs. 83%. Hopefully, in the future, we can get an integration environment that includes those tests as well. This project focuses on quality. That is why I started this project using TDD practices and intend to proceed in this fashion. By integrating with CI, we now have true visibility into this. Another goal is to get code coverage metrics captured. Tools have been updated and show a measurement of 83% at this point in time. I don't know the industry average, but I'm willing to bet it is way below that. I am personally test infected, and I want to see the number higher. The next immediate thing is to update Spring Python to support CherryPy 3.1. We are way behind and need to catch up. I have been working with Sylvain, author of "CherryPy Essentials: Rapid Python Web Application Development", and we are close to getting PetClinic and all the supporting components of Spring Python working. This is exciting because integrating with 3rd party web frameworks opens doors for Spring Python. Have any ideas of where you think Spring Python can go? Send me a message here, or start a new topic on our forum at http://forum.springframework.org/forumdisplay.php?f=45. From fredrik at pythonware.com Tue Sep 9 12:42:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 09 Sep 2008 18:42:28 +0200 Subject: creating an (inefficent) alternating regular expression from a list of options In-Reply-To: References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: Larry Bates wrote: >> vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| >> u|ii|i)' >> >> Is there a public module available for this purpose? > > Perhaps I'm missing something but your function call oneOf(...) is > longer than than actually specifying the result. > > You can certainly write quite easily: > > def oneOf(s): > return "|".join(s.split()) "|" works strictly from left to right, so that doesn't quite work since it doesn't place "aa" before "a". a simple reverse sort will take care of that: return "|".join(sorted(s.split(), reverse=True)) you may also want to do re.escape on all the words, to avoid surprises when the choices contain special characters. From mdboldin at gmail.com Tue Sep 2 10:01:38 2008 From: mdboldin at gmail.com (mmm) Date: Tue, 2 Sep 2008 07:01:38 -0700 (PDT) Subject: Python IDEs with F5 or hotkey shell interaction Message-ID: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> I am looking for advice on Python Editors and IDEs I have read other posts and threads on the subject and my two questions at this time are mainly about the IDLE-like F5-run facilities. While I am fairly happy using IDLE, the debugger is unintuitive to me and I wanted a project manager and a better variable/ class browser and also the potential to edit/run other languages such as R and Tex/Latex. Windows and LINUX compatibility is desired too. I found numerous editor candidates from reading posts to this Python users group list and also documents such as http://wiki.python.org/moin/PythonEditors but few if any alternatives seem to have all of the ?interactive? power of IDLE?- not only a run program in a python shell hotkey but a persistent, after-a-run memory state can be accessed for interactive coding and exploration-- i.e. how IDLE works ! *** My first questions is what other editor/IDE have IDLE-like interactive features. Or to put it another way, is my appraisal below of the editors & IDEs I tried right (note some where looked at as much as a year ago). Python specific IDLE F5 run & Full shell interaction PythonWin F5 run & Full shell interaction, MS Windows only PyScripter F9 run & shell interaction, but script created variables are not persistent (???!) PyPE F5 run, but not an interactive shell DrPython F5 run, but not an interactive shell in MS Windows (maybe in Linux) SPE (Stani) Could not get it to run in MS Windows (???!) PyScripter, PyPe and drPython all had nice features but interaction quirks. My second question is based on a belief that I should move to a more general IDE or editor to get LINUX compatibility and the ability to also edit R and LaTex programs. I have explored these Vim Cream/Vim UliPad SciTe Jext Editra Komodo Editor But none are close to being as interactive friendly as IDLE. I might look at Eclypse with pydev Jedit And these commercial/professional IDEs Wing Komodo IDE Zeus But before doing so I wanted to know form experienced users: ** How hard is it to configure any of the general editors/IDEs to run a Python shell using a hotkey (such as IDLEs F5) and whether any can be set up for full interactivity. I understand and appreciate the difficulties to get full IDLE-like interactivity, but what comes closest? From bj_666 at gmx.net Sun Sep 7 18:03:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2008 22:03:56 GMT Subject: lacking follow-through References: Message-ID: <6ij1ecFqp39rU4@mid.uni-berlin.de> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > This is the strangest post I've seen > since I've joined this list (only > recently). What the ? Yeah, castironpi sometimes doesn't make much sense. Maybe because it's a bot!? :-) Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Fri Sep 19 03:38:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Sep 2008 03:38:13 -0400 Subject: XML Processing In-Reply-To: <5148.6462973573$1221742234@news.gmane.org> References: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> <48D24638.9010601@timgolden.me.uk> <5148.6462973573$1221742234@news.gmane.org> Message-ID: Robert Rawlins wrote: >> Some is going to kick themselves when they realise >> that ElementTree *is* built in to Python 2.5 >> >> http://docs.python.org/whatsnew/modules.html#SECTION0001420000000000000000 > > Tim, Andrii, > > Thanks for the heads up on that! I hadn't noticed they're made it part of > the platform modules, that's excellent news. > > In theory I should just be able to amend my import paths and we'll be good > to go, no install external modules. > > Thanks for this, > And don't forget to use cElementTree for production, since it's an order of magnitude or more faster at many tasks. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fredrik at pythonware.com Wed Sep 17 11:15:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 17:15:54 +0200 Subject: python regex character group matches In-Reply-To: <00e11472$0$20331$c3e8da3@news.astraweb.com> References: <00e11472$0$20331$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >> Assuming that you want to find runs of \uXXXX escapes, simply use >> non-capturing parentheses: >> >> pat = re.compile(u"(?:\\\u[0-9A-F]{4})") > > Doesn't work for me: > >>>> pat = re.compile(u"(?:\\\u[0-9A-F]{4})") it helps if you cut and paste the right line... here's a better version: pat = re.compile(r"(?:\\u[0-9A-F]{4})+") From pruthviraj.pb at gmail.com Tue Sep 16 00:44:24 2008 From: pruthviraj.pb at gmail.com (Babloo) Date: Mon, 15 Sep 2008 21:44:24 -0700 (PDT) Subject: Client server implementation References: <7d623ffb-2936-4aec-a74a-e9f5489e6657@p25g2000hsf.googlegroups.com> Message-ID: <708b9a1e-f4df-4d9c-8daa-cf77900acda4@s20g2000prd.googlegroups.com> On Sep 16, 7:38?am, Benjamin wrote: > On Sep 15, 5:15?am, Babloo wrote: > > > Hi everyone, > > > ? ? ? ? ? ? ? ? ? i wanted to implement a client- server connection > > and transfer a file over the network. i was able to implement a normal > > set up where in i was able to send chat messages and small chunks of > > data. > > I want to implement the file transfer with out using the FTP library > > available in python . > > > ? ? ? ? ? ? ? ? ? So can anyone suggest a piece of code by which i can > > do that. > > I don't know what you really want, but look at Twisted.http://twistedmatrix.com > > > > > Thanks > > Pruthvi > > I am beginner at using python language. I mean i am implementing that in a windows based machine and wanted to transfer files over the LAN. I have written down two files as client.py and server.py . I ran these files at two different Computers in the LAN and I was able to send small chunks of messages( like chat). I was successful in establishing connection and sending small messages. But now i want to transfer a complete file with out using the ftplib(FTP LIBRARY) in python. The files look like this.i hope this would help. ______________________________________________ # Server program from socket import * # Set the socket parameters host = "117.105.224.94" port = 21567 buf = 1024 addr = (host,port) # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) # Receive messages while 1: data,addr = UDPSock.recvfrom(buf) if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" # Close socket UDPSock.close() __________________________________________________ # Client program from socket import * # Set the socket parameters host = "117.105.224.94" port = 21567 buf = 1024 addr = (host,port) # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg # Send messages while (1): data = raw_input('>> ') if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'....." # Close socket UDPSock.close() _____________________________________________________________ From dudeja.rajat at gmail.com Sat Sep 6 11:58:47 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 6 Sep 2008 16:58:47 +0100 Subject: How to bring subprocess to the foreground? In-Reply-To: <6ifhg2Fq24n6U1@mid.uni-berlin.de> References: <6ifhg2Fq24n6U1@mid.uni-berlin.de> Message-ID: On Sat, Sep 6, 2008 at 3:13 PM, Diez B. Roggisch wrote: > dudeja.rajat at gmail.com schrieb: >> >> Hi, >> >> I've a batch file that I open with the subprocess .Popen() . When this >> batch file is run I want to bring it to the foreground. >> >> Please suggest how can I do this? > > You can't. You can capture the stdout using the pipe-arguments, and in your > main-process, read that and write it to the main process' stdout. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Hi Diez, Thanks for the information. That's valuable information. I though of displayin an information message on the screen through tkMessageBox while the subprocess is running, I did it using: try: testing = subprocess.Popen([batchFilePath], \ shell = True) retCode = testing.wait() tkMessageBox._show("Test Harness execution", \ icon = 'info', \ message="Testing %s in progress..." % libName) except: tkMessageBox._show("Error", \ type='ok', icon='error', \ message="Error executing %s Test Harness" % libName) return None else: print retCode But the message is never displayed. Please suggest if there is something wrong with this code -- Regards, Rajat From jaomatos at gmail.com Tue Sep 30 14:14:08 2008 From: jaomatos at gmail.com (=?iso-8859-1?q?Jos=E9_Matos?=) Date: Tue, 30 Sep 2008 19:14:08 +0100 Subject: Python is slow? In-Reply-To: <0b229c8f-61cf-4617-8927-5627edadc9b9@m36g2000hse.googlegroups.com> References: <00f226c8$0$20617$c3e8da3@news.astraweb.com> <0b229c8f-61cf-4617-8927-5627edadc9b9@m36g2000hse.googlegroups.com> Message-ID: <200809301914.10299.jaomatos@gmail.com> On Tuesday 30 September 2008 16:04:35 George Sakkis wrote: > What you're missing is that for Free Software (TM) zealots it's a > matter of philosophical principle, totally unrelated to how easy is to > overcome the restriction. There is not a "practicality beats purity" > clause in the FSF Bible. The gnuplot license is a free software according to FSF, what is the problem here after all? > George -- Jos? Ab?lio From tjreedy at udel.edu Tue Sep 30 14:18:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 14:18:15 -0400 Subject: Python is slow? In-Reply-To: <00f226c8$0$20617$c3e8da3@news.astraweb.com> References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: >> I do, because a natural, beneficial act (modify the work and >> redistribute it) that has no technical reason to restrict, is >> artifically restricted. > > We agree that the restriction is artificial, and I think irrational > (although I'd be interested in hearing the gnuplot developers' reasoning > before making a final judgment). I believe it is a matter of preserving clarity of authorship, just as is the quoting mechanism we take for granted in posts like this. If I removed the quote marks above and silently edited what Ben and you wrote, I might upset someone and certainly could confuse readers. tjr From grante at visi.com Tue Sep 30 20:41:15 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Sep 2008 19:41:15 -0500 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> Message-ID: On 2008-09-30, Michael Torrie wrote: >> Just a thought, your minimum sleep time is probably limited by >> the resolution of the system "HZ" clock. Type >> >> less /proc/config.gz >> >> and search for the value of the "CONFIG_HZ" setting. On the >> Athlon 64 machine I'm using to write this, it's 250, which >> should allow for sleep intervals in multiples of 0.004 >> seconds. > > Since most distributions do not create this file in /proc for whatever > reason, It's also common to put a copy of the config file in /boot (or wherever the kernel binaries are installed). I prefer the /proc/config.gz setup myself, and that's how I configure all my systems. > and some people are being deliberately obtuse, does anyone > know how to ask the kernel what the timer resolution is? Is > it stored anywhere else in /proc or /sys? I kind of think > most distros set it to 1000 Hz, but I'm not sure. We could look in /usr/include: $ grep -r ' HZ ' /usr/include /usr/include/scsi/sg.h:#define SG_DEFAULT_TIMEOUT (60*HZ) /* HZ == 'jiffies in 1 second' */ /usr/include/linux/ixjuser.h:* IXJCTL_HZ sets the value your Linux kernel uses for HZ as defined in /usr/include/linux/n_r3964.h: * Fixed HZ usage on 2.6 kernels /usr/include/asm/param.h:#define HZ 100 But, I happen to know that's wrong and I'm running a kernel with HZ=250. So let's look elsewhere. How about in /proc/sys/kernel? $ cat /proc/sys/kernel/sched_min_granularity_ns 4000000 That looks suspiciously like 1/HZ in nanoseconds. -- Grant From williamhpurcell at gmail.com Tue Sep 30 21:39:54 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Tue, 30 Sep 2008 20:39:54 -0500 Subject: __buitins__ key added during eval() Message-ID: I want to use eval to evaluate wx.TextCtrl inputs. How can I keep python from adding the __builtins__ key to mydict when I use it with eval? Other wise I have to __delitem__('__builtins__') everytime I use eval? >>> mydict = {'a':2,'b':3} >>> eval('a*b',mydict) 6 >>> mydict {'a': 2, '__builtins__': {'IndexError': , ...(I'll spare you the rest)...}, 'b': 3} Also, how come eval has this behavior? Is it desirable? -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 17 10:13:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 17 Sep 2008 16:13:05 +0200 Subject: Python OOP advice In-Reply-To: <9317b769-0569-4ccf-b800-c400328ff579@m36g2000hse.googlegroups.com> References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> <6089e023-18f6-4c93-a2a4-f933eac786b5@f63g2000hsf.googlegroups.com> <9317b769-0569-4ccf-b800-c400328ff579@m36g2000hse.googlegroups.com> Message-ID: <48d11070$0$12641$426a74cc@news.free.fr> Simon Hibbs a ?crit : > Great contributions, thanks both of you. I'm self-tought when it comes > to Python and OOP and I haven't yet grown an intuitive feel for how to > do things sensibly. While part of the OO design patterns are mostly workaround for lack of dynamism in languages like C++ or Java, and while pattern abuse is certainly not good design, you'd probably learn a lot from the GOF's Design Patterns book. > Simon From steve at REMOVE-THIS-cybersource.com.au Wed Sep 17 12:49:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Sep 2008 16:49:24 GMT Subject: translating ascii to binary References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> Message-ID: <00e12f1f$0$20331$c3e8da3@news.astraweb.com> On Wed, 17 Sep 2008 18:02:15 +0200, Canned wrote: > Hi, > I'm trying to write a class that can convert ascii to binary and vice > versa. I write my class based on this function I've found on internet [...] > That works perfectly, but when I try to implement it in my own class it > gives me alot of headache, also because I'm totally new to the language. > It work only with one character at a time, and if I give a string it > just give some weird result. [snip code] Your "ascii_to_bin" method tries to do too much in one method. You should split the functionality into small, self-contained pieces, then combine them. And frankly, once you got to the part where you started popping and inserting, my brain melted. You are making an easy job too hard! *smiles* Try this instead: class Converterab: ''' Ascii-binary converter. ''' def __init__(self, string): self.string = string def bin(self, n): """Return the binary representation of a positive integer n.""" bindump = [] while n > 0: bindump.append(str(n & 1)) n = n >> 1 bindump.reverse() if bindump: return ''.join(bindump) else: return '0' def char_to_bin(self, c): """Return the binary representation of a character c.""" bits = self.bin(ord(c)) zeroes = "0" * (8-len(bits)) return zeroes+bits def ascii_to_bin(self): results = [] for c in self.string: results.append(self.char_to_bin(c)) return ''.join(results) -- Steven From bdesth.quelquechose at free.quelquepart.fr Sun Sep 28 15:46:13 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 Sep 2008 21:46:13 +0200 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <48dffaef$0$10596$426a74cc@news.free.fr> process a ?crit : > I have heard some criticism about Python, that it is not fully object- > oriented. > > What is not an object in Python? names and statements. > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? See other answers here about how the len(obj) is implemented. But anyway: OO and the dotted notation are totally orthogonal. The message(obj) is by no mean less OO than the obj.method() one - even more FWIW, since the notion of 'method' is mostly an implementation artifact. The key conceps in OO are "object" and "message", not "dot" and "method". From kay.schluehr at gmx.net Tue Sep 23 16:15:57 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 23 Sep 2008 13:15:57 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> Message-ID: On 23 Sep., 21:23, J Peyret wrote: > On Sep 23, 8:31 am, bearophileH... at lycos.com wrote: > > Guys, this looks like a great data structure/algo for something I am > working on. > > But... where do I find some definitions of the original BK-tree idea? *geometric data structures*. Just google for it. From deets at nospam.web.de Fri Sep 12 10:44:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Sep 2008 16:44:06 +0200 Subject: Checking the boolean value of a collection In-Reply-To: References: <6ivbfvFnfucU1@mid.uni-berlin.de> Message-ID: <6ivdhnFnm8bU1@mid.uni-berlin.de> >> if any(instance.forbitToClose(archivefolder) for instance in >> self.findActiveOutgoingRegistrationInstances()) > > Can you clarify where I can find "any"? It seems to me I'm unable to find it... It's part of python2.5. If you don't have that, you can write it your own and stuff it into __builtins__: >>> def any(iterable): ... for item in iterable: ... if item: ... return True ... return False ... ... __builtins__.any = any You might also want to add all, the companion of any: >>> def all(iterable): ... for item in iterable: ... if not item: ... return False ... return True ... Diez From maric at aristote.info Mon Sep 15 11:19:23 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 17:19:23 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <200809151645.13078.maric@aristote.info> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> <200809151645.13078.maric@aristote.info> Message-ID: <200809151719.24434.maric@aristote.info> Le Monday 15 September 2008 16:45:12 Maric Michaud, vous avez ?crit?: > This is not sufficient for auto-responses, and given the following rfcs, it > would smart to both : > ... > - add or modify the Return-Path and/or Reply-To header for badly > implemented auto-responders to point to list maintainer. Oh, no ! to the list itself of course. This could also avoid the common mistake mailing list users do in replying private mail accidentally when the adress of the list is only present in CC field. -- _____________ Maric Michaud From Afro.Systems at gmail.com Sun Sep 21 01:16:29 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Sat, 20 Sep 2008 22:16:29 -0700 (PDT) Subject: writeable buffer and struct.pack_into and struct.unpck_from References: Message-ID: Thanks Gabriel, I was missing the information how to create a writable buffer. From grflanagan at gmail.com Mon Sep 29 16:46:53 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Mon, 29 Sep 2008 22:46:53 +0200 Subject: Finding subsets for a robust regression In-Reply-To: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > > x1 = [] #unique instances of x and y > y1 = [] #median(y) for each unique value of x > for xx,yy in d.iteritems(): > x1.append(xx) > l = len(yy) > if l == 1: > y1.append(yy[0]) > else: > yy.sort() > y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else > yy[l//2] ) > -- Not tested, but is this equivalent? x1 = [] y1 = [] for xx, yy in d.iteritems(): L = len(yy) // 2 yy.sort() y1.append(yy[L]) if not L & 1: y1[-1] = (y1[-1] + yy[L-1]) / 2.0 It means that you have a pointless 'sort' when len(yy) == 1, but then you save an 'if' per-iteration. G. From mail at timgolden.me.uk Fri Sep 12 03:59:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 08:59:54 +0100 Subject: rss feed generation In-Reply-To: <32cabba0809111835g2984c463y2c4b689605f8362e@mail.gmail.com> References: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> <32cabba0809111835g2984c463y2c4b689605f8362e@mail.gmail.com> Message-ID: <48CA217A.60708@timgolden.me.uk> Walter Cruz wrote: > On Tue, Sep 9, 2008 at 9:35 PM, alex23 wrote: >> On Sep 10, 7:30 am, "Blake Garner" wrote: >>> I'm looking for suggestions on how to approach generating rss feed >>> .xml files using python. What modules to people recommend I start >>> with? I just rolled something with ElementTree. No idea how it stacks up against validity checks, but it seems to be accepted by a couple of standard feed readers. (sorry; longish code segment) import os, sys from datetime import datetime try: from xml.etree import cElementTree as ET except ImportError: from elementtree import ElementTree as ET class Feed (object): ENCODING = "utf-8" def __init__ (self, title, link, description=None, author=None, updated_on=None): self.title = title self.link = link self.description = description self.author = author self.updated_on = updated_on or datetime.now () self.entries = [] def add_entry (self, title, link, content, summary=None, id=None, updated_on=None): self.entries.append ( dict ( title=title, link=link, content=content, summary=summary, id=id or link, updated_on=updated_on or datetime.now () ) ) def write_rss (self, ofile=sys.stdout, encoding=ENCODING): rss = ET.Element ("rss", version="2.0") channel = ET.SubElement (rss, "channel") ET.SubElement (channel, "title").text = self.title ET.SubElement (channel, "link").text = self.link ET.SubElement (channel, "description").text = self.description for entry in self.entries: item = ET.SubElement (channel, "item") ET.SubElement (item, "title").text = entry['title'] ET.SubElement (item, "link").text = entry['link'] ET.SubElement (item, "guid").text = entry['id'] ET.SubElement (item, "description").text = entry['content'] ET.ElementTree (rss).write (ofile, encoding=encoding) def write_atom (self, ofile=sys.stdout, encoding=ENCODING): feed = ET.Element ("feed") ET.SubElement (feed, "title", type="text").text = self.title ET.SubElement (feed, "link", rel="self", href=self.link) if self.description: ET.SubElement (feed, "subtitle", type="text").text = self.description if self.author: name, email = self.author author = ET.SubElement (feed, "author") ET.SubElement (author, "name").text = name ET.SubElement (author, "email").text = email ET.SubElement (feed, "updated").text = self.updated_on.isoformat () for entry in self.entries: e = ET.SubElement (feed, "entry") ET.SubElement (e, "title").text = entry['title'] ET.SubElement (e, "link", href=entry['link']) ET.SubElement (e, "id").text = entry['id'] ET.SubElement (e, "updated").text = entry['updated_on'].isoformat () if entry['summary']: ET.SubElement (e, "summary").text = entry['summary'] ET.SubElement (e, "content", type="html").text = "" % entry['content'] ET.ElementTree (feed).write (ofile, encoding=encoding) if __name__ == '__main__': feed = Feed ("Feed for example.org", "http://example.org", author=("Tim Golden", "tim at example.org")) for i in range (5): feed.add_entry ("Entry %d" % i, "http://example.org/entry/%d" % i, "Contents for entry %d" % i, id="entry#%d" % i) feed.write_atom (open ("feed.atom.xml", "w"), "iso-8859-1") feed.write_rss (open ("feed.rss.xml", "w"), "iso-8859-1") TJG From ville at ville-desktop.i-did-not-set--mail-host-address--so-tickle-me Sat Sep 13 09:41:37 2008 From: ville at ville-desktop.i-did-not-set--mail-host-address--so-tickle-me (ville) Date: Sat, 13 Sep 2008 13:41:37 GMT Subject: How to run PyOS_InputHook from python code (i.e. yield to event loops) References: <87wshpcaek.fsf@gmail.com> Message-ID: <87iqt0b1tj.fsf@ville-desktop.i-did-not-set--mail-host-address--so-tickle-me> Sean DiZazzo writes: >> My eventual code would be something like: >> >> launch_process_in_thread('bzr pull') >> >> while not is_done: >> ? pyos_inputhook() >> ? time.sleep(0.1) >> >> print "Done!" > > I'm still recovering from a hangover, so don't quote me. I think you > want the "after" function: > > launch_process_in_thread('bzr pull') > self.update() > > def update(self): > while not self.is_done: > self.after(2000, self.update) That's tk-specific, right? I'm looking for a snippet that - Would not be tied to tk - Would run sequentially, i.e. the next command would not be entered before the process has finished. Just like os.system() From bearophileHUGS at lycos.com Fri Sep 19 15:51:24 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Sep 2008 12:51:24 -0700 (PDT) Subject: Python newbie References: Message-ID: Mladen Gogala: Welcome to Python, you will need only one or few weeks to be able to write useful Python programs. But even with the help of a good book (that I suggest you to read) you may need several months or one year to master it :-) > 2) Why is it illegal to pass a built-in function "print" to map? Maybe because one of the few original design mistakes of Python. The new Python 3.0 "fixes" that problem, in Python 3 print is now a function, so you can use it where you can use functions. But in general I think it's better to not give map() a function that has side effects like print(). So you want to use a list comp there instead, and create a new list: [2 * el for el in a] In Python (and several other modern languages, like Scala, plus some more functional languages) you will find that people often prefer to create new data structures instead of modifying old ones. This may sound like a waste of memory and time, but using a more immutable-data style has several advantages (often in code clarity) that are a bit complex to explain here. As you probably know, the good thing of learning new languages is that they carry some principles, and they are the expression of some ideas of the computer science. So learning Python may show you some new ideas, or new ways to look at old computer science ideas you already know. I think Alan J. Perlis said "A language that doesn't affect the way you think about programming, is not worth knowing." Bye, bearophile From ricaraoz at gmail.com Wed Sep 10 13:14:01 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 10 Sep 2008 14:14:01 -0300 Subject: Can anyone suggest a good crypto package? In-Reply-To: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> References: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> Message-ID: <48C80059.7080101@bigfoot.com> Fett wrote: > On Sep 4, 2:23 pm, Mike Driscoll wrote: >> On Sep 4, 1:39 pm, Fett wrote: >> >> >> >>> I need a crypto package that works on windows with python 2.5. Can >>> anyone suggest one for me? >>> I have been searching for a couple days for a good cryptography >>> package to use for public/private key encryption, at this point I >>> would settle for symmetric even. >>> Every encryption package I have found for python was either operating >>> system specific (read *nix only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/ >>> There was one exception, this version was specifically built to run on >>> any platform (yay), but the compiler for windows complained that I >>> wasn't using python2.2 (though the package was said to only need 2.2 >>> or newer). >>> Is there any crypto package that is actually written in python? I >>> seriously don't care how slow it is. >> How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads >> >> Mike > > Seems that this is intended more for webapps or something, I intend to > use this for a client application. This means that I can't require > outside dependencies, or I risk annoying the clients (if you have > installed many open-source projects with dependencies that aren't > handled by portage/apt-get, you know what I would be doing to them). > > I seriously can't believe that there isn't a single python native > crypto package. Why do they all need to have outside dependencies? > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, maybe I'm a little late but today scanning through "The daily Python-URL" I came through something that might be pertinent. The link is http://www.keyczar.org/ And here is the intro to the site : """ Keyczar is an open source cryptographic toolkit designed to make it easier and safer for developers to use cryptography in their applications. Keyczar supports authentication and encryption with both symmetric and asymmetric keys. Some features of Keyczar include: * A simple API * Key rotation and versioning * Safe default algorithms, modes, and key lengths * Automated generation of initialization vectors and ciphertext signatures * Java and Python implementations (C++ coming soon) * International support in Java (Python coming soon) Keyczar was originally developed by members of the Google Security Team and is released under an Apache 2.0 license. """ HTH From uzmanajmal at gmail.com Mon Sep 15 02:23:27 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Mon, 15 Sep 2008 06:23:27 +0000 Subject: How to convert M2Crypto.RSA.RSA to string Message-ID: Hi, I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that key as string. Is there any way to convert the said instance into string? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mitko at qlogic.com Tue Sep 30 14:56:54 2008 From: mitko at qlogic.com (Mitko Haralanov) Date: Tue, 30 Sep 2008 11:56:54 -0700 Subject: Change environment after setreuid Message-ID: <20080930115654.0e0f36d3@hematite.mv.qlogic.com> I have a program (which normally runs as root) which can start child processes as different users. Effectively, my program is a modified version of popen2's Popen3 class where the child process (after the fork) does: os.setregid (gid, gid) os.setreuid (uid, uid) session_pid = os.setsid () This all seems to work. However, I am running into a problem where the environment of the new process still carries values that were set before the setreuid() call. What would be the best way to go about modifying the environment without having to re-implement all the functionality of the 'su' command? I could use it (the 'su' command) to start the new process but I'd like to avoid external dependencies like that. Thank you -- Mitko Haralanov ========================================== The program isn't debugged until the last user is dead. From stef.mientki at gmail.com Mon Sep 15 12:58:16 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 15 Sep 2008 18:58:16 +0200 Subject: Python IDEs with F5 or hotkey shell interaction In-Reply-To: References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> Message-ID: <48CE9428.7090406@gmail.com> hello Almar, Almar Klein wrote: > > ... > but few if any alternatives seem to have all of the 'interactive' > power of IDLE?- not only a run program in a python shell hotkey but a > persistent, after-a-run memory state can be accessed for interactive > coding and exploration-- i.e. how IDLE works ! > > > I felt the same. Coming from Matlab, I missed the interactive behaviour. > I found IPython with a proper editor (I really liked PyPE) a nice > solution. > > Still, I found it awkward having to use two programs and not having code > completion in my editor (I mean the editor not knowing what names are > present in my python session.) > > Therefore, I started creating an editor with an interactive shell in > it in which > you can run (parts of) your code and have a persisten session. It's not > finished yet, but I'm quite happy with the result so far. It starts > python in a > subprocess in much the same way PyPE does. I actually "stole" code from > PyPE as a base for multiple things (thanks Josiah :) ). Any change we could see some code already ? I'm working on something similar, bored of the bugs in my current IDE. Here are my first notes: http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_debug.html It should become a very-simple-very-high-level IDE, like Matlab, but then better ;-) cheers, Stef > > Almar > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From m_palmer45 at yahoo.ca Wed Sep 17 08:14:04 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 17 Sep 2008 05:14:04 -0700 (PDT) Subject: shelve file space always increase! References: Message-ID: <892aa8b4-a95b-44fc-ac5d-08815c3c061e@a70g2000hsh.googlegroups.com> On Sep 17, 6:17 am, smalltalk wrote: > >>> import shelve > >>> sf = shelve.open('e:/abc.db') > >>> for i in range(10000): > > ... sf[str(i)]=i > ...>>> sf.close() > >>> sf = shelve.open('e:/abc.db') > >>> sf.clear() > >>> sf > > {} > the abc.db is always 312k though i have use clear(), how can i shrink > the space? shelve doesn't have any way of doing that. the only option is to read all items from your shelve and write them to a new one. From martin at v.loewis.de Thu Sep 25 16:47:52 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 25 Sep 2008 22:47:52 +0200 Subject: Quick sort implementation in python In-Reply-To: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: <48dbf8f9$0$21266$9b622d9e@news.freenet.de> > Now as you can see I'm passing my list object to both functions along > with their first, last indices I cannot really see that. More specifically, it isn't definite what the type of the "a" argument is, nor does the specific type of "a" matter for the algorithm. It could be a list, or it could be a different mutable collection that is integer-indexed. > My question is: Is that the normal way to implement algorithms in > python Yes, it is. > cause in c++ i've implemented that algo via a template function > which can have a randon access data structure or not. However i have > no idea how to access the values of a data structure that doesn't > allow random access. Can you please explain how you did that in C? IOW, how did you do the partition function (template) in case you don't have random access to the collection? Regards, Martin From lists at cheimes.de Wed Sep 10 11:40:37 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 17:40:37 +0200 Subject: Accessing __slots__ from C In-Reply-To: References: Message-ID: Chris wrote: > Hi, > > I'd like to be able to access an attribute of a particular Python > object as fast as possible from some C code. > > I wondered if using __slots__ to store the attribute would allow me to > do this in a faster way. > > The reason I'd like to do this is because I need to access the > attribute inside a loop within some C code, and I find that the > attribute lookup using the 'PyObject_GetAttrString' call is far slower > than any of the subsequent calculations I perform in C. That's correct. You can use slots to increase the performance but it doesn't work like you think. If you need it *really* fast than write a C Extension, store the data in a C struct and access the data via PyMemberDef. Christian From python.list at tim.thechases.com Wed Sep 17 07:21:19 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 17 Sep 2008 06:21:19 -0500 Subject: Use of generators and efficiency In-Reply-To: <200809171106.01782.research@johnohagan.com> References: <200809171106.01782.research@johnohagan.com> Message-ID: <48D0E82F.8070003@tim.thechases.com> > To my great surprise, this approach was often considerably _slower_ to > complete than the original program (up to ~40% depending on which modifiers > were used), despite producing initial results more quickly. You may be interested in reading through this thread http://mail.python.org/pipermail/python-list/2008-January/473650.html where looping vs generators were timed and you can see that generators clearly (and sadly) impose a speed penalty as demonstrated by Andrew Reedick. I'm not sure whether the "why" of it was ever determined, but generators should be used with care if speed is more important than clarity. -tkc From half.italian at gmail.com Fri Sep 12 22:07:28 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 12 Sep 2008 19:07:28 -0700 (PDT) Subject: Good python web programming books References: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> Message-ID: On Sep 12, 6:08?pm, "Chris Rebert" wrote: > I've heard good things about The Django Book:http://www.djangobook.com/ > - Chris > > > > On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma wrote: > > Hi Guys, > > > I am very new to python. ?I am looking for a good book about python web > > programming. > > > I looked at a few online like Web Programming In Python but most are quite > > old. > > > If you've read a good book on python web programming can you please suggest > > some? > > > Thanks > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com Im exploring TurboGears and loving it. However I don't know how well you will do learning a web framework at the same time as the language. Spend a few weeks (at least) learning the language basics from the tutorials, then maybe try Django or TurboGears. You could do some neat stuff with mod_python as a beginner, so maybe start there. http://docs.python.org/tut/ http://diveintopython.org/ http://www.modpython.org/ http://www.turbogearsbook.com/ Good luck! m2c, ~Sean From half.italian at gmail.com Wed Sep 10 22:01:34 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 10 Sep 2008 19:01:34 -0700 (PDT) Subject: SSH using PEXPECT References: Message-ID: On Sep 10, 6:04?pm, yellowblueyel... at gmail.com wrote: > Hey , I need to SSH into a server .. (10.8.42.38) using pexpect the > username is 'admin' and password is 'abc123' so far i have the > following code > > import pexpect > import sys > import time > import os > > foo = pexpect.spawn('ssh ad... at 10.8.42.38') > ssh_newKey = 'Are you sure you want to continue connecting' > > foo.expect = ssh_newKey > foo.send = 'yes' > foo.expect = 'password:' > foo.send = 'abc123' > > --------------------------------------------------------------------------- ---------------------- > > does this look right? > > if not , could someone suggest a way to do this .. > your help is much appreciated https://svn.lal.in2p3.fr/projects/CMT/CMTManagement/utils/ssh_session.py I use a modified version of this. Simple and effective. import ssh_session ssh = ssh_session.ssh_session(user, host, password) print ssh.ssh("ls -l /tmp") Thanks Eric and Nigel! ~Sean From bignose+hates-spam at benfinney.id.au Thu Sep 18 21:22:08 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 Sep 2008 11:22:08 +1000 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> Message-ID: <87od2l2am7.fsf@benfinney.id.au> erikcw writes: > On Sep 18, 3:33?pm, Ben Finney > wrote: > > erikcw writes: > > > What is the correct way to launch subprocess without waiting for > > > the result to return? > > > > Creating an instance of 'subprocess.Popen' will launch the process > > and return the Popen instance. You then have the option of polling > > it or waiting for it to complete. > > So if I create a Popen object and then just ignore the object and > exit the program the subproccess will finish it's work and then exit > itself cleanly? Ah, no, that's a different thing. If the parent exits, the child will also be killed I believe. If you want to spawn a process and have it live on independent of the parent, you want to make the child process a "daemon", detatching itself from the parent's environment. I don't recall how that's done immediately, but those are the terms to search for. -- \ ?Pinky, are you pondering what I'm pondering?? ?Yes Brain, but | `\ if our knees bent the other way, how would we ride a bicycle?? | _o__) ?_Pinky and The Brain_ | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Mon Sep 29 12:39:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2008 18:39:45 +0200 Subject: destructor not called In-Reply-To: <93627810-b437-4b9a-9aad-6837271fd894@m36g2000hse.googlegroups.com> References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> <3dec57f0-c829-4420-b36d-58e21c564053@k37g2000hsf.googlegroups.com> <93627810-b437-4b9a-9aad-6837271fd894@m36g2000hse.googlegroups.com> Message-ID: <48e120bb$0$30170$426a34cc@news.free.fr> Marcin201 a ?crit : >> Others have already replied to your main question; in short you >> shouldn't rely on __del__ being called. Regardless, is there a (good) >> reason for having an instance reference to the method ? Without >> further information, that seems like a code smell. > > I have dictionary of fxns to do import/export based on the type of > request from user so I can call self.Import['html'] or > self.Import['text']. getattr(obj, name) is your friend. And if you really want to maintain your own mapppings, do it at the appropriate level - that is, when it comes to methods, at the class level, not the instance level. You can even automate this using a decorator and a custom metaclass, ie (warning: Q&D code, not tested, may contain errors etc): # myframework.py def request_handler(func): func._request_handler = True return func class RequestHandlerType(type): def __init__(cls, name, bases, dic): handlers = getattr(cls, '_handlers') for name, attrib in dic: if getattr(attrib, '_request_handler', False): handlers[name] = attrib cls._handlers = handlers class BaseRequestHandler(object): __metaclass__ = RequestHandlerType # myapp.py from myframework impoty request_handler, BaseRequestHandler class MyHandler(BaseRequestHandler): @request_handler def html(self, *args, **kw): # code here @request_handler def text(self, *args, **kw): # code here def dispatch(self, request): format = request.format try: handler = self._handlers[format] except KeyError: # raise appropriate exception here else: return handler(self, request) From george.sakkis at gmail.com Mon Sep 29 10:56:06 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 29 Sep 2008 07:56:06 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> Message-ID: <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> On Sep 29, 9:02 am, bearophileH... at lycos.com wrote: > George Sakkis: > > > I don't see the same value in creating a distinction between methods > > and builtin functions unless the latter are truly generic (and even > > then I wouldn't mind having them as methods of the base object class, > > e.g. object.type()). Having a builtin len(x) delegate to x.__len__() > > seems harder to justify. > > I have shown few usage examples of the len() one of the posts in this > thread. Can you take a look at them and show how you can better > rewrite them without a len function? > > Bye, > bearophile You mean this ? >>> seq = ["aaaa", "bb", "c", "ddd"] >>> seq2 = [[1,1,1,1], [2,2], [3], [4,4,4]] >>> sorted(seq, key=lambda x:x.__len__()) ['c', 'bb', 'ddd', 'aaaa'] >>> sorted(seq2, key=lambda x:x.__len__()) [[3], [2, 2], [4, 4, 4], [1, 1, 1, 1]] Sure, "len" looks better than lambda x:x.__len__(), but the same would be true if there was an "upper" builtin for the following example: >>> s = ['a', 'd', 'B', 'C'] >>> s2 = [u'a', u'd', u'B', u'C'] >>> upper = lambda x: x.upper() >>> sorted(s, key=upper) ['a', 'B', 'C', 'd'] >>> sorted(s2, key=upper) [u'a', u'B', u'C', u'd'] No difference in principle, just len() happens to be implemented more often than upper(). George From karl.kobata at syncira.com Wed Sep 17 14:02:06 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Wed, 17 Sep 2008 11:02:06 -0700 Subject: ka-ping yee tokenizer.py Message-ID: <6gvfio$7sja8m@rrcs-agw-01.hrndva.rr.com> Aaran, Thanks for your input. Your examples gave me other alternatives for what I wanted to do and it seems to work. Thanks all for your help. On Sep 16, 2:48 pm, "Karl Kobata" > wrote: > Hi Fredrik, > > This is exactly what I need. Thank you. > I would like to do one additional function. I am not using the tokenizer to > parse python code. It happens to work very well for my application. > However, I would like either or both of the following variance: > 1) I would like to add 2 other characters as comment designation > 2) write a module that can readline, modify the line as required, and > finally, this module can be used as the argument for the tokenizer. > > Def modifyLine( fileHandle ): > # readline and modify this string if required > ... > > For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ): > Print token > > Anxiously looking forward to your thoughts. > karl > > -----Original Message----- > From: python-list-bounces+kkobata=syncira.... at python.org > > [mailto:python-list-bounces+kkobata=syncira.... at python.org ] On Behalf Of > Fredrik Lundh > Sent: Monday, September 15, 2008 2:04 PM > To: python-l... at python.org > Subject: Re: ka-ping yee tokenizer.py > > Karl Kobata wrote: > > > I have enjoyed using ka-ping yee's tokenizer.py. I would like to > > replace the readline parameter input with my own and pass a list of > > strings to the tokenizer. I understand it must be a callable object and > > iteratable but it is obvious with errors I am getting, that this is not > > the only functions required. > > not sure I can decipher your detailed requirements, but to use Python's > standard "tokenize" module (written by ping) on a list, you can simple > do as follows: > > import tokenize > > program = [ ... program given as list ... ] > > for token in tokenize.generate_tokens(iter(program).next): > print token > > another approach is to turn the list back into a string, and wrap that > in a StringIO object: > > import tokenize > import StringIO > > program = [ ... program given as list ... ] > > program_buffer = StringIO.StringIO("".join(program)) > > for token in tokenize.generate_tokens(program_buffer.readline): > print token > > > > --http://mail.python.org/mailman/listinfo/python-list > > This is an interesting construction: >>> a= [ 'a', 'b', 'c' ] >>> def moditer( mod, nextfun ): ... while 1: ... yield mod( nextfun( ) ) ... >>> list( moditer( ord, iter( a ).next ) ) [97, 98, 99] Here's my point: >>> a= [ 'print a', 'print b', 'print c' ] >>> tokenize.generate_tokens( iter( a ).next ) >>> tokenize.generate_tokens( moditer( lambda s: s+ '#', iter( a ).next ).next ) It adds a '#' to the end of every line, then tokenizes. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Mon Sep 22 22:14:12 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 19:14:12 -0700 (PDT) Subject: A bit weird dictionary behavior References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <00e822ed$0$20303$c3e8da3@news.astraweb.com> Message-ID: <3a12f7b1-3cea-4d18-a7ee-a51299fec866@i76g2000hsf.googlegroups.com> Steven D'Aprano: >For many iterables, the amount of memory is not excessive and the increase in readability of len() is to be preferred over the side-effect of sum(1 for...).< With side-effects do you mean the possibility of exhausting a lazy iterable? The readability difference is little, and it's way safer because it works well enough with very long iterables too, so leniter(..) is better than len(list(...)). Bye, bearophile From lists at cheimes.de Fri Sep 26 04:24:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 26 Sep 2008 10:24:19 +0200 Subject: Module import path when embedding python in C In-Reply-To: <913fe5fc-9b8e-49c6-b740-5d6bb74abc97@s20g2000prd.googlegroups.com> References: <913fe5fc-9b8e-49c6-b740-5d6bb74abc97@s20g2000prd.googlegroups.com> Message-ID: graph wrote: > Does anyone know why PySys_GetObject wasn't documented until somewhat > recently (http://bugs.python.org/issue1245) if it has been part of the > system module interface since at least Python 1.5.2? Is it not > supposed to be used? What's the difference the above and importing > the sys module and then doing the append? The PySys_Get/SetObject methods are faster than PyImport. The methods access the sys module directly without going through the import API. The funcitons weren't documented because they were simply forgotten. Christian From guillermo.listas at googlemail.com Tue Sep 2 09:17:37 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Tue, 2 Sep 2008 06:17:37 -0700 (PDT) Subject: Algorithm used by difflib.get_close_match Message-ID: <83c600d0-6852-4dd6-9287-34f9b3264090@s50g2000hsb.googlegroups.com> Hi all, Does anyone know whether this function uses edit distance? If not, which algorithm is it using? Regards, Guillermo From pavlovevidence at gmail.com Wed Sep 17 03:44:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 17 Sep 2008 00:44:08 -0700 (PDT) Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> <6jb6juF2co8rU1@mid.individual.net> Message-ID: <4fc1f095-42b2-435f-a86b-d0260cfef922@c22g2000prc.googlegroups.com> On Sep 16, 10:29 pm, Steven D'Aprano wrote: > On Wed, 17 Sep 2008 13:52:13 +1200, greg wrote: > > Arnaud Delobelle wrote: > > >> Or: > > >> import ModuleName as this_module > > > Or: > > > this_module = __import__(__name__) > > > then you don't have to change anything. > > I like that solution! And it works regardless of whether the module > holding it is imported, or is being executed from the commandline. It doesn't work if the module is part of a package. For that could use sys.modules[__name__] or write a separate function to return the appropriate nested module of __name__. Neither method is foolproof I don't think. Carl Banks From fetchinson at googlemail.com Thu Sep 11 15:02:06 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 11 Sep 2008 12:02:06 -0700 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: <943393.38616.qm@web95111.mail.in2.yahoo.com> References: <943393.38616.qm@web95111.mail.in2.yahoo.com> Message-ID: >> Thanking you, >> >> Ms. Vaidehi Pawar > > How much do you pay? > >> How much do you ask for???? >> >> cheers >> Ms. Vaidehi I was just kidding. But if you seriously need people to do this kind of job it's better to post the amount you are willing to pay otherwise nobody will take it seriously. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From h.goebel at goebel-consult.de Wed Sep 17 09:46:13 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Wed, 17 Sep 2008 15:46:13 +0200 Subject: Python and Open Office In-Reply-To: References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> Terry Reedy schrieb: > One way to learn the meaning of some of the numerous attributes and > values is to create a file with the wanted features with OOo, save, > unzip, and examine the xml to see which tags are used for which features. The API docs are a bit hidden on the webpage. Here is the link: Additionally teh ODF sepcs may help: Regards H. Goebel From jan.schilleman at xs4all.nl Mon Sep 15 17:12:09 2008 From: jan.schilleman at xs4all.nl (Jan Schilleman) Date: Mon, 15 Sep 2008 23:12:09 +0200 Subject: Rebinding __setattr__ References: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> Message-ID: <48cecfb3$0$3164$e4fe514c@dreader31.news.xs4all.nl> That still would require changing the source of the library ... And i'm not sure if it would have side effects. "Maric Michaud" schreef in bericht news:mailman.1033.1221477203.3487.python-list at python.org... Le Monday 15 September 2008 01:06:08 Jan Schilleman, vous avez ?crit : > Hi all, > > I am trying to redefine __setattr__. > > The base class is in a library (actually, it is > win32com.client.DispatchBaseClass) and I do not want to touch it. My > problem is exemplified below. To my surprise, __setattr__ and __str__ > behave differently; I can redefine __str__ and the inherited __str__ is > still the redefined one. But redefining __setattr__ on the base class does > not get inherited. In Base.__dict__ the __setattr__ is the one I expected, > but it is not called from B. > > What is the problem? Is __setattr__ cached somewhere [and not updated?]? > Yes, it doesn't work with classic classes, but do with new-style ones, I don't know if this an accepted behavior or not. Can't you use new-style classes ? >>>[2]: sys.version ...[2]: '2.5.2 (r252:60911, May 28 2008, 19:19:25) \n[GCC 4.2.4 (Debian 4.2.4-1)]' >>>[64]: class A : def __setattr__(self, name, value) : print "A", name ....: ....: >>>[67]: class B(A) : pass ....: >>>[68]: A().c, B().c = 1, 2 A c A c >>>[69]: A.__setattr__ = lambda s, n, v : sys.stdout.write("%s, %s, %s\n" % (s, n, v)) >>>[70]: A().c, B().c = 1, 2 <__main__.A instance at 0x2b3b41546290>, c, 1 A c >>>[71]: class A(object) : def __setattr__(self, name, value) : print "A", name ....: ....: >>>[74]: class B(A) : pass ....: >>>[75]: A().c, B().c = 1, 2 A c A c >>>[76]: A.__setattr__ = lambda s, n, v : sys.stdout.write("%s, %s, %s\n" % (s, n, v)) >>>[77]: >>>[78]: A().c, B().c = 1, 2 <__main__.A object at 0x2b3b45dfa350>, c, 1 <__main__.B object at 0x2b3b45dfa350>, c, 2 -- _____________ Maric Michaud From mensanator at aol.com Wed Sep 10 20:12:07 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 10 Sep 2008 17:12:07 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: <59f16334-e9f4-46a7-b433-654a08ffb434@k30g2000hse.googlegroups.com> On Sep 10, 5:36?pm, Terry Reedy wrote: > Mensanator wrote: > > Are there situations where the sum of an empty > > list should NOT be 0? Of course there are. > > Python Philosopy (my version, for this discussion): > ? ?Make normal things easy; make unusual or difficult things possible. > > Application: > ? ?Sum([]) == 0 is normal (90+% of cases). ?Make that easy (as it is). > ? ?For anything else: > ? ? ?if seq: s = sum(s, base) > ? ? ?else: > ? ?which is certainly pretty easy. > > > Can sum() handle those cases? > > The developers choose what they thought would be most useful across the > spectrum of programmers and programs after some non-zero amount of > debate and discussion. > > ?> ?No, it can't, I have to write > > > my own definition if I want that behaviour. > > Or wrap your calls. ?In any case, before sum was added as a convenience > for summing numbers, *everyone* has to write their own or use reduce. > > Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be > the most common use of reduce. ?Sum(s,start) replaces the much less > common reduce(lambda x,y: x+y, s, start). > > Reduce(S, s), where S = sum function, raises an exception on empty s. > So use that and you are no worse off than before. What am I doing wrong? >>> S = sum >>> S >>> s = [1,2,3] >>> type(s) >>> reduce(S,s) Traceback (most recent call last): File "", line 1, in reduce(S,s) TypeError: 'int' object is not iterable >>> reduce(S,s,0) Traceback (most recent call last): File "", line 1, in reduce(S,s,0) TypeError: 'int' object is not iterable >>> reduce(lambda x,y:x+y,s) 6 >>> s=[] >>> reduce(lambda x,y:x+y,s) Traceback (most recent call last): File "", line 1, in reduce(lambda x,y:x+y,s) TypeError: reduce() of empty sequence with no initial value This is supposed to happen. But doesn't reduce(S,s) work when s isn't empty? > > However, a problem with reduce(S,s) is that it is *almost* the same as > reduce(S,s,0). ?So people are sometimes tempted to omit 0, especially if > they are not sure if the call might be reduce(S,0,s) (as one argument > says it should be -- but that is another post). ?But if they do, the > program fails, even if it should not, if and when s happens to be empty. > > > There's no reason > > why sum([]) and sum([],0) have to mean the same thing at the > > exclusion of a perfectly valid alternative definition. > > 'Have to', no reason. ?'Should', yes there are at least three reasons. > 1. Python functions generally return an answer rather than raise an > exception where there is a perfectly valid answer to return. > 2. As a general principle, something that is almost always true should > not need to be stated over and over again. ?This is why, for instance, > we have default args. > 3. As I remember, part of the reason for adding sum was to eliminate the > need (with reduce) to explicitly say 'start my sum at 0' in order to > avoid buggy code. ?In other words, I believe part of the reason for > sum's existence is to avoid the very bug-inviting behavior you want. > > Terry Jan Reedy From lekin2 at llnl.gov Thu Sep 18 12:06:13 2008 From: lekin2 at llnl.gov (April Lekin) Date: Thu, 18 Sep 2008 09:06:13 -0700 Subject: Tkinter Bold Text Message-ID: <76vncf$1aj1ab@smtp.llnl.gov> Is there any way to highlight, bold or change the color of one word in a variable to be displayed on a Tkinter GUI? Like: material = "Plastic" introVal = "This report describes the construction of the %s." % (material) this is what I want: This report describes the construction of the Plastic. Plastic is Bold or Blue or Green Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From harald.luessen at gmx.de Fri Sep 19 12:46:01 2008 From: harald.luessen at gmx.de (Harald Luessen) Date: Fri, 19 Sep 2008 18:46:01 +0200 Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: On Thu, 18 Sep 2008 Bruno Desthuilliers wrote: ># Harald : uncomment this and run test_results. As far as I can tell, it ># doesn't yields the expected results > >## IN7 = IN[:] >## def sortk7(n): >## return n.coordinates[0] > >## def doubles7(): >## "is ordering better ? - Nope Sir, it's broken..." >## IN7.sort(key=sortk) >## SN = [] >## sn_append = SN.append >## in_len = len(IN) >## for i in xrange(in_len): >## node_i = IN[i] >## coords_i = node_i.coordinates >## for j in xrange(i+1, in_len): >## if coords_i[0] == IN[j].coordinates[0]: >## if coords_i[1] == IN[j].coordinates[1]: >## sn_append(node_i) >## else: >## break >## return SN ... >Results here (py2.5, gentoo linux, athlonxp1800, 512 ram): > > >>> test_results() >True > >>> test_times() >doubles0 : 1.55667901039 >doubles1 : 0.719144105911 >doubles2 : 0.703393936157 >doubles3 : 0.700654983521 >doubles4 : 0.706257104874 >doubles5 : 0.528184890747 >doubles6 : 0.461633205414 >doubles8 : 0.0134379863739 >doubles9 : 0.0108540058136 When you change my code then do it right. :-) You forgot to change the IN to IN7 at _every_ place. And the sortk should be sortk7 in _both_ places. I never let the code run before myself. I just wrote it in the newsreader. But now i did and I have a second version as bonus. IN7 = IN[:] def sortk7(n): return n.coordinates[0], n.coordinates[1] def doubles7(): IN7.sort(key=sortk7) SN = [] sn_append = SN.append in_len = len(IN7) for i in xrange(in_len): node_i = IN7[i] coords_i = node_i.coordinates for j in xrange(i+1, in_len): if coords_i[0] == IN7[j].coordinates[0]: if coords_i[1] == IN7[j].coordinates[1]: sn_append(node_i) else: break return SN def comp7( x, y ): return cmp( x.coordinates, y.coordinates ) def doubles7a(): IN7.sort( comp7 ) SN = [] sn_append = SN.append in_len = len(IN7) for i in xrange(in_len): node_i = IN7[i] for j in xrange(i+1, in_len): node_j = IN7[j] if comp7( node_i, node_j ) == 0: sn_append(node_i) else: break return SN Here are the results. (py2.5, WindowsXP, Pentium4, 2.6GHz, 1.5GB): My version is not so bad. doubles0 : 1.03830598582 doubles1 : 0.47943719104 doubles2 : 0.487412506338 doubles3 : 0.475924733451 doubles4 : 0.466548681466 doubles5 : 0.340487967046 doubles6 : 0.278480365521 doubles7 : 0.0953190978183 doubles7a : 0.0784233750379 doubles8 : 0.010236496538 doubles9 : 0.00742803903848 Harald From digitig at gmail.com Tue Sep 23 13:01:04 2008 From: digitig at gmail.com (Tim Rowe) Date: Tue, 23 Sep 2008 18:01:04 +0100 Subject: Not fully OO ? In-Reply-To: <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: 2008/9/23 Craig Allen : > So python may turn out to be pure OO I think that's the sort of thing the pedants would hang that hats on, too. Python isn't *pure* OO, in that it lets the programmers do non-OO if they want to, but it is *fully* OO in that it includes everything required to do OO. But maybe the original blogger meant by "fully OO" what I mean by "Pure OO"? The question I usually ask is "Does this language help me get the job done?" Python often does. That's all that really matters, isn't it? -- Tim Rowe From praveenapanch at gmail.com Mon Sep 8 05:05:46 2008 From: praveenapanch at gmail.com (Praveena P) Date: Mon, 8 Sep 2008 02:05:46 -0700 (PDT) Subject: String to hexadecimal conversion Message-ID: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Hi folks, I am new to Python... so am not too sure about how the type conversion works. I have to read a file that contains hexadecimal data and use the data further to do some arithmetic calculations. A sample of the input is : 00000000000020E0000032F800000000400022005E The problem I am facing is this: I am using f.read(2) to read a byte at a time, but the data that is read is a string rather than a number. So it kind of hampers any arithmetic operations I perform on this data... Could you please suggest some method I could use for this? Thanks guys! Praveena From gagsl-py2 at yahoo.com.ar Tue Sep 2 15:50:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 16:50:15 -0300 Subject: email.Message problem References: <20080902160417.GA20438@zephyr> Message-ID: En Tue, 02 Sep 2008 13:04:18 -0300, Corrado Gioannini escribi?: > Hi all, > i know i'm probably going to ask a very silly question, but i > can't figure out where i'm doing wrong just reading the docs. > > trying to build and send a mail message using the email.* modules > (with python 2.5). > > a simplified version of my script that breaks is this: > > mailtest.py > > messg = email.message.Message() Replace this line with: messg = email.mime.multipart.MIMEMultipart() *OR* Set the Content-Type header to "multipart/mixed" *before* anything else. -- Gabriel Genellina From fredrik at pythonware.com Sun Sep 21 05:37:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 11:37:26 +0200 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: Mensanator wrote: > I'm not the one who wrote sympy, so I guess I'm not > the only one who didn't notice it. > > If it's a well known problem, then sorry I wasted > your time. Given that 2.5 explicitly warns about this specific change: >>> as = 1 :1: Warning: 'as' will become a reserved keyword in Python 2.6 it's an unknown issue only for people who has 1) never used their code under 2.5, or 2) never looks at the output produced by their programs. The PEP-5 process guarantees that "users will have at least a year to test their programs and migrate them from use of the deprecated construct to the alternative one," and Python 2.5 was released *two* years ago. So it sure looks like the SimPy folks ignored the established process. Why they've done that is probably a more interesting issue than the change itself. From peymanfaratin at gmail.com Fri Sep 5 17:55:41 2008 From: peymanfaratin at gmail.com (peyman) Date: Fri, 5 Sep 2008 14:55:41 -0700 (PDT) Subject: running python as a dameon Message-ID: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> Hi I have a Natural Language Processing (NLP) code written in python that reads into memory a large training file and then given a sentence tags it, using the training data. I want to put this NLP code on a server which handles all incoming client http requests via PHP. What I want to do is to provide the python NLP program as a service to any other PHP/Java/Ruby process request. So the mapping is http -> apache -> PHP/Java/Ruby/... -> Python NLP I can not provide this service as a shell script because of the inefficiencies of having to load into memory a large training data to every service request. So what I want to do is to provide the NLP service to other application processes as a python daemon http -> apache -> PHP/Java/Ruby/... -> Python Dameon -> Python NLP The daemon loads into memory the training data once. then every service request event invokes the appropriate NLP code in the python program. I've tried to use play around with twisted but am not making too much of a headway. What I've done in the NLP code is to do this: # filename: NLP.py def parse(sentence): structure=getentities(sentence) print 'subject: \t',' '.join(structure[0]) print 'predicate: \t',' '.join(structure[1]) print 'TE: \t\t',' '.join(structure[2]) class TLogicClass(): def __init__(self,prop): return parse(prop) then in the dameon code done this # filename: dameon.py from twisted.application import service import NLP application=service.Application("nlp") ParseService=NLP.TLogicClass("time flies like an arrow") ParseService.setServiceParent(application) but I get the following error when I run twistd -y daemon.py >> Failed to load application: TLogicClass instance has no attribute 'setServiceParent' I suspect I need to put twisted in the NLP.py but I don't know what I need to do in order to get what I want to do which is: to load into memory only once a large training data that can then be queried by another (non-python) event based process (I need "reactor" class?). thank you in advance for your help From comp.ogz at gmail.com Tue Sep 30 16:31:11 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Tue, 30 Sep 2008 23:31:11 +0300 Subject: QSessionManager example request Message-ID: <48E28C8F.4000300@gmail.com> Hi all, I am trying to write an application that will test the sleep function of the laptop. I am using pyqt for this. I need to continue to run my gui after the laptop wakes up from sleep mode so that i may continue some counters and repeat the sleep command again. I think i may use QSessionManager but i am not sure how to use it. Can someone give me a simple example with it? Oguz -------------- next part -------------- A non-text attachment was scrubbed... Name: comp_ogz.vcf Type: text/x-vcard Size: 111 bytes Desc: not available URL: From malkarouri at gmail.com Fri Sep 26 16:21:24 2008 From: malkarouri at gmail.com (malkarouri) Date: Fri, 26 Sep 2008 13:21:24 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> Message-ID: <7d9d472f-1f8e-4fe4-9647-b68bb9c86102@x41g2000hsb.googlegroups.com> On 26 Sep, 16:39, Patrick Sullivan wrote: > Hello. > > I will be using some large data sets ("points" from 2 to 12 variables) > and would like to use one class for each point rather than a list or > dictionary. I imagine this is terribly inefficient, but how much? I can't really get into details here, but I would suggest that you go ahead and try first. As you know, premature optimization is the root of all evil. General points I would suggest: - Use Numpy/Scipy (http://www.scipy.org). You will have more effeciency easier than if you try to use simply Python lists. And it is much easier to later optimize that. - Your questions of referencing classes and variables tell me that perhaps you are starting from a C background, or Java maybe? Anyway, as far as I know, it is not standard practice to write a class method (you meant a normal bound method, right?) just to access a variable. Use a normal Python variable and if you need to make it a method later turn it into a property. - Is the efficiency you are looking for is in terms of time or memory? That difference leads to different optimization tricks sometimes. - By using Numpy there is probably another advantage to you: some efficiency in the data representation, as the NumPy array stores data, say integers, without memory overhead per member (point). Just an array of integers. Of course there is additional constant memory per array which is independent of the number of elements (points) you are storing. - Generally try to think in terms of arrays of data rather than single points. If it helps, think in terms of matrices. That is more or less the design of Matlab, and Numpy is more or less similar. Now if you specify your problem further I am sure that you will get better advice from the community here. Don't focus on the details, probably the bigger picture will help. Working in graphics? Image processing? Machine Learning/Statistics/Data Mining/ etc..? -- Muhammad Alkarouri From almar.klein at gmail.com Wed Sep 24 05:02:52 2008 From: almar.klein at gmail.com (Almar Klein) Date: Wed, 24 Sep 2008 11:02:52 +0200 Subject: python 3.x third party modules In-Reply-To: References: Message-ID: Hi, I would like to look at third party modules which are python 3.0 ready. > I think that until the release version of python 3.0 is out, no one will release something. Python 3k is due in October this year, so only a few weeks from now. I would also like to know when we can expect the major 3th party packages (like numpy, wxpython, ...) to release a version for python 3.0. Can anyone say something about that? Will it take a month, a year? Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From d3vvnull at gmail.com Fri Sep 26 12:00:59 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 11:00:59 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> Message-ID: <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> So we can drop a table in an in clause? How is this a use case. Cartoons are funny but actual proof that this example using an in-clause provides an exploit would be more helpful I think. On Fri, Sep 26, 2008 at 9:50 AM, Benjamin Kaplan wrote: > > > On Fri, Sep 26, 2008 at 10:38 AM, Michael Mabin wrote: > >> I laugh in the face of danger. >> >> Give me a use case for an exploit. >> > > http://xkcd.com/327/ > > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter.anderson at internode.on.net Sat Sep 6 21:41:03 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sun, 07 Sep 2008 11:41:03 +1000 Subject: Learning Python In-Reply-To: References: Message-ID: <48C3312F.4040506@internode.on.net> James, I have several Python books and am currently working my way through John Zelle's PYTHON PROGRAMMING: An Introduction to Computer Science (Publisher: Franklin, Beedle & Associates, ISBN-10: 1887902996, ISBN-13: 978-1887902991). I think this is a very good introduction to both Python AND programming I would highly recommend it. If you finish the Zelle book then you can go onto Problem Solving With Algorithms And Data Structures Using Python by Bradley N. Miller and David L. Ranum (Publisher: Franklin Beedle & Associates, ISBN-10: 1590280539, ISBN-13: 978-1590280539). These are equivalent to Python 101 and 201. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From castironpi at gmail.com Thu Sep 25 14:50:30 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 25 Sep 2008 11:50:30 -0700 (PDT) Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> <48dbc82e$0$1120$426a74cc@news.free.fr> Message-ID: <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> On Sep 25, 1:22?pm, "Dmitry S. Makovey" wrote: > Aaron "Castironpi" Brady wrote: > > You should write it like this: > > > class B(object): > > ? ? ?@A.proxy > > ? ? ?def bmethod(self,a): > > > Making 'proxy' a class method on A. ? > > makes sense. > > > In case different A instances (do > > you have more than one BTW?) > > yep. I have multiple instances of class A, each one has properties (one per > class) of classes B, C and D: > > class A: > ? ? ? ? b=None > ? ? ? ? c=None > ? ? ? ? d=None > ? ? ? ? def __init__(self,b,c,d): > ? ? ? ? ? ? ? ? self.b=b > ? ? ? ? ? ? ? ? self.c=c > ? ? ? ? ? ? ? ? self.d=d > > ? ? ? ? ...magic with proxying methods goes here... > > class B: > ? ? ? ? def bmethod(self,x): pass # we proxy this method from A > ? ? ? ? def bmethod2(self,x): pass # this is not proxied > class C: > ? ? ? ? def cmethod(self,x): pass # we proxy this method from A > class D: > ? ? ? ? def dmethod(self,x): pass # we proxy this method from A > > a=A(B(),C(),D()) > x='foo' > a.bmethod(x) > a.cmethod(x) > a.dmethod(x) > a.bmethod2(x) # raises error as we shouldn't proxy bmethod2 > > above is the ideal scenario. > > > What you've said implies that you only have one B instance, or only > > one per A instance. ?Is this correct? > > yes. as per above code. > > > I agree that __setattr__ is the canonical solution to proxy, but you > > have stated that you want each proxied method to be a member in the > > proxy class. > > well. kind of. if I can make it transparent to the consumer so that he > shouldn't do: > > a.b.bmethod(x) > > but rather: > > a.bmethod(x) > > As I'm trying to keep b, c and d as private properties and would like to > filter which calls are allowed to those. Plus proxied methods in either one > always expect certain parameters like: > > class B: > ? ? ? ? def bmethod(self,c,x): pass > > and A encapsulates 'c' already and can fill in that blank automagically: > > class A: > ? ? ? ? c=None > ? ? ? ? b=None > ? ? ? ? def bmethod(self,c,x): > ? ? ? ? ? ? ? ? if not c: > ? ? ? ? ? ? ? ? ? ? ? ? c=self.c > ? ? ? ? ? ? ? ? b.bmethod(self,c,x) > > I kept this part of the problem out of this discussion as I'm pretty sure I > can fill those in once I figure out the basic problem of auto-population of > proxy methods since for each class/method those are going to be nearly > identical. If I can autogenerate those on-the-fly I'm pretty sure I can add > some extra-logic to them as well including signature change where > A::bmethod(self,c,x) would become A::bmethod(self,x) etc. Do you want to couple instances or classes together? If A always proxies for B, C, and D, then the wrapper solution isn't bad. If you're going to be doing any instance magic, that can change the solution a little bit. There's also a revision of the first implementation of Aproxy you posted, which could stand alone as you have it, or work as a classmethod or staticmethod. > def Aproxy(fn): > def delegate(*args,**kw): > print "%s::%s" % (args[0].__class__.__name__,fn.__name__) > args=list(args) > b=getattr(args[0],'b') > fnew=getattr(b,fn.__name__) > # get rid of original object reference > del args[0] > fnew(*args,**kw) > setattr(A,fn.__name__,delegate) > return fn def Aproxy(fn): def delegate(self,*args,**kw): print "%s::%s" % (args[0].__class__.__name__,fn.__name__) fnew=getattr(self.b,fn.__name__) return fnew(*args,**kw) setattr(A,fn.__name__,delegate) return fn From bearophileHUGS at lycos.com Sun Sep 7 09:59:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 7 Sep 2008 06:59:46 -0700 (PDT) Subject: doctest not seeing any of my doc tests References: <00d3d407$0$20306$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano, first of all you can try to run a minimal module, to see if your doctesting works, like: """ >>> 1 + 1 3 """ def foo(): """ >>> foo() 1 """ return 0 import doctest doctest.testmod() If that works correctly, then you can show us some more of the code and tests. Bye, bearophile From george.sakkis at gmail.com Mon Sep 29 08:41:02 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 29 Sep 2008 05:41:02 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> Message-ID: <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> On Sep 29, 2:34?am, Carl Banks wrote: > On Sep 29, 1:44?am, George Sakkis wrote: > > > > > On Sep 29, 12:08 am, Terry Reedy wrote: > > > > George Sakkis wrote: > > > > On Sep 28, 2:29 pm, process wrote: > > > > >> I have heard some criticism about Python, that it is not fully object- > > > >> oriented. > > > > > That's not a bug, it's a feature ;-) > > > > >> Why isn't len implemented as a str.len and list.len method instead of > > > >> a len(list) function? > > > > > As Terry Reedy wrote, partly history and partly practicality. There's > > > > no philosophical reason why we write "len(x)" (generic builtin), > > > > "x.append(1)" (method) or "del x[i]" (statement). The latter in > > > > particular is IMHO a design wart; there's no reason for not writing it > > > > as "x.delete(i)". > > > > As a general rule and matter of practice, methods that apply to all or > > > most classes (or all number classes) have built-in functions that call > > > the corresponding special method (or C-level slot). > > > It would be easier to justify this rule if it was more clear-cut, and > > specifically if it was applied only to methods that are available to > > *all* classes (such as type() and getattr()) rather than the ill- > > defined "most classes". > > That wasn't your original claim, though. ?You claimed there was no > philosophical reason, then Terry gave you one, then you said, well > there's no clear cut reason. ?Unless you define "philosophical" as > "clear cut" (a definition I'm not sure many would agree with). I won't argue about that, just s/philosophical/clear cut/ then. > Anyway, you are right to claim there's no clear cut distinction, just > as there's never any clear cut distinction over whether something > should be an operator or not. Addition is only available to the ill- > defined "most classes", yet not only is it not a method, it has its > own syntax. ?There's no clear cut distinction there, it's just a > design decision. > > Likewise, making len() into a function is just a > design decision, that len is a common enough operation that it need > elevated status. It's really nothing more. Python wouldn't suffer > much regardless if len is a method, a built-in function, or an > operator with its own syntax. I'm not quite sure it's exactly the same. The distinction between operators and non-operators is syntactically clear cut: operators consist of punctuation characters and (binary operators) use infix syntax. Yes, from a pure semantics standpoint this distinction is redundant; a language could support a method-only syntax, but there is much value in using terse intuitive symbols for certain domains (with math being the prominent one). For example I would be much less opposed to len() being defined as, say, |x| if "|...|" was a valid operator. I don't see the same value in creating a distinction between methods and builtin functions unless the latter are truly generic (and even then I wouldn't mind having them as methods of the base object class, e.g. object.type()). Having a builtin len(x) delegate to x.__len__() seems harder to justify. George From bj_666 at gmx.net Fri Sep 19 03:44:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Sep 2008 07:44:06 GMT Subject: Python newbie References: Message-ID: <6jh3i5F376gaU1@mid.uni-berlin.de> On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote: > There are several questions: > > 1) Why is the array "a" unchanged after undergoing a transformation with > map? Because `map()` creates a new list and doesn't change the elements in `a`. > 2) Why is it illegal to pass a built-in function "print" to map? Because ``print`` isn't a function but a keyword. This will be changed in Python?3.0. On the other hand this use case is discouraged because `map()` builds a new list with the return value of the given function. So you would build a list full of `None`\s just for the side effect. > 3) Why is the array "a" unchanged after undergoing an explicit > transformation with the "for" loop? Because there is no explicit transformation. The loop binds elements to the name `x` in your example and within the loop you rebind that name to another value. Neither the name `x` nor the objects bound to it have any idea that the object might be referenced in some container object. > 4) Is there an equivalent to \$a (Perl "reference") which would allow me > to decide when a variable is used by value and when by reference? No, variables in Python are always name to object bindings. Don't think of variables as boxes with names on it where you put objects in, or references to another box. Think of objects and sticky notes with names on it. > How can I make sure that > for x in a: x=2*x > > actually changes the elements of the array "a"? Well, actually change the elements. ;-) Either: for index, item in enumerate(sequence): sequence[index] = func(item) Or: sequence[:] = map(func, sequence) But the need to do so doesn't seem to be that frequent. Usually one just builds a new list instead of altering an existing one. Ciao, Marc 'BlackJack' Rintsch From mal at egenix.com Tue Sep 30 12:30:22 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 30 Sep 2008 18:30:22 +0200 Subject: how to find out the version of a certain installed package In-Reply-To: References: Message-ID: <48E2541E.7030605@egenix.com> On 2008-09-30 18:17, Christophe wrote: > Hi, > > In a projecet I'm making using pycrypto, I need to find out the > current installed version of pycrypto. After looking around, I found > out that "pkg_resources.requires("pycrypto") will give me a string > containing the version number, but is this the only way to do it or > are there other ways? Most packages have a .__version__ attribute in their top-level package dir which you can query. You do have to import the base package, though, in order to find out. Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 30 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From alan.isaac at gmail.com Tue Sep 2 13:18:58 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Tue, 02 Sep 2008 17:18:58 GMT Subject: Numeric literal syntax In-Reply-To: <6i56cpFor2puU1@mid.individual.net> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <6i56cpFor2puU1@mid.individual.net> Message-ID: <6Aevk.331$1a2.14@trnddc04> > On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote: >> At the risk of bike-shedding, > [snip] Peter Pearson wrote: > (startled noises) It is a delight to find a reference to > that half-century-old essay (High Finance) by the wonderful > C. Northcote Parkinson, but how many readers will catch the > allusion? It is pretty common geek speek: http://en.wikipedia.org/wiki/Color_of_the_bikeshed Cheers, Alan Isaac From fredrik at pythonware.com Wed Sep 10 07:13:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 13:13:46 +0200 Subject: Catching subprocess stdout stream In-Reply-To: <9deaf3ef-2103-444f-bb46-309aee7045c5@r15g2000prd.googlegroups.com> References: <00b9dc86-e002-4e2c-a686-39d2dd1016b9@m3g2000hsc.googlegroups.com> <9deaf3ef-2103-444f-bb46-309aee7045c5@r15g2000prd.googlegroups.com> Message-ID: Sean DiZazzo wrote: > while aThread.isAlive() or not aQueue.empty(): > l = aQueue.get().rstrip() > fo.write(l) > print l > > fo.close() > > A bit of fun for a sleepless night... and unless you add a call to time.sleep somewhere in that loop, you'll keep your CPU up all night as well... From callen314 at gmail.com Tue Sep 23 17:14:59 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 23 Sep 2008 14:14:59 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: <44c069c5-473d-4f62-9997-5b13102e7f8b@b30g2000prf.googlegroups.com> > if they want to, but it is *fully* OO in that it includes everything > required to do OO. But maybe the original blogger meant by "fully OO" > what I mean by "Pure OO"? it seems to me this is what was meant... pure OO, AND forced to use it. My personal feeling is that python is multiparadigmed and I'm more than fine with that. BUT, I am going to hold onto what I've noticed which is that Python seems to use OO deeply, well into the interpreter, and that the procedural styles available at the Python source level pretty much are built on top of this OO model, given you accept a module as an object, which it seems to be within the source code... but in the end, it's just words and the most important thing is that python is a tool you can use to make a computer do what you want, and whatever you call it may just be a distraction. cheers. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 25 02:11:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 06:11:24 GMT Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> Message-ID: <00eb2560$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: > Just a thought, your minimum sleep time is probably limited by the > resolution of the system "HZ" clock. Type > > less /proc/config.gz $ less /proc/config.gz /proc/config.gz: No such file or directory What OS are you using? -- Steven From mfajer at gmail.com Sat Sep 27 17:50:26 2008 From: mfajer at gmail.com (Mikolai Fajer) Date: Sat, 27 Sep 2008 14:50:26 -0700 Subject: Abstract Base Class register function Message-ID: <3ff66ae00809271450l13ca2fc5k4b3fec10c1051496@mail.gmail.com> I have been experimenting with the abc module in py3k and thought about using the register method of an ABC as a class decorator: import abc class MyABC(metaclass=abc.ABCMeta): pass @MyABC.register class MySub(): pass This doesn't work because the register method returns None. It would be a fairly simple modification to have this work: def register(cls, subclass): """Register a virtual subclass of an ABC.""" ... etc ... return subclass What do people think of this behavior? -- -Mikolai Fajer- From robert.kern at gmail.com Tue Sep 23 15:17:15 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 14:17:15 -0500 Subject: Python is slow? In-Reply-To: References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > sturlamolden: >> Sure I could show you the code, Python and C++, if I had a place to post it.< > > I think the Python version suffices. If it's not too much private you > may post the single minimal/reduced runnable Python module here, it > will be deleted in some time (if you want you can also use a private > paste): > http://codepad.org/ You could also drop it on the scipy.org wiki in the Cookbook category. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From tino at wildenhain.de Sun Sep 28 07:00:02 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 28 Sep 2008 13:00:02 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> References: <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> Message-ID: <48DF63B2.2020408@wildenhain.de> Michael Mabin wrote: > I'm exhausted, so I'll just shut up about this after a few final words. Thank you for your time :-) > 1. "edits" is used in data warehousing to describe data scrubbing or > filtering of fields in records that are used as input sources for > loading into data warehouses. It's a term that goes way back to batch > processing on the mainframe, so it's been used this way for a long time. > Sometimes we use 'validation' interchangeably with 'edit' but our use of > validation usually involves a check of input data against business rules > and not type or range checking which we consider 'edits'. So maybe > you're not used to hearing the term used this way, but it is a variation > perhaps of what you're used to. And so on and so on in the regular top posting manner... Just to give you some thoughts again: your solution might be valid for you in your controlled environment. Yet you just presented it to the OP without telling him the limits of when this can be used. And this is outright dangerous. If one sees this without comment and without your background she will run into problems sooner or later. So my suggestion was to either don't tell people such solutions at all or tell them exactly under which circumstances they might be used. Still I think nailing the problem at the apropriate place is a habit which should generally devloped - as in your example an additional int() would have fixed it - but still it would not work if you want to deal with arbitrary strings. So its good to make suggestions but pretty please think ahead how someone would use it instead of investing all your energy into defending dangerous programming practice. With "we in python" I referred to a fairly amount of literature about programming in python and it design patterns. Nothing me personally. Ah and some final words to the controlleness of datawarehouse applications and similar things: by the time you are designing such a solutuion you will never know what future applications will be developed around it so its always best to be prepared. "Data scrubbing" seems a common idea but in fact its very hard to do it right due to the nature of different systems using different quoting logic. "Dont trust your input" is a habit not only applicable to web programming - in fact the company I work for does not do much web application but input validation is something we get even audited for. Nevertheless I wish you a very good weekend :-) Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From dancing.cataldo at gmail.com Tue Sep 23 16:08:27 2008 From: dancing.cataldo at gmail.com (Phil Cataldo) Date: Tue, 23 Sep 2008 22:08:27 +0200 Subject: Does anybody use this web framework ? Message-ID: <48d94cbc$0$964$ba4acef3@news.orange.fr> Hi, I just found this new? python web framework (http://pypi.python.org/pypi/nagare/0.1.0). Does anybody know or use it ? Regards, Phil From dieter at handshake.de Thu Sep 18 13:10:15 2008 From: dieter at handshake.de (Dieter Maurer) Date: 18 Sep 2008 19:10:15 +0200 Subject: Zsi interoperability In-Reply-To: References: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: "Marco Bizzarri" writes on Mon, 15 Sep 2008 20:26:27 +0200: > On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel wrote: > > Mailing List SVR wrote: > >> I have to implement a soap web services from wsdl, the server is > >> developed using oracle, is zsi or some other python library for soap > >> interoperable with oracle soa? > > > > No idea, but I'd definitely try soaplib before ZSI. > > > > Stefan > > I'm working on a project where I need to write a client for SOAP with > Attachments; I can see ZSI does not support it The ZSI documentation (2.0) says that SOAP attachments are supported -- but I never tried it. Dieter From gminick at bzt.bzt Thu Sep 4 11:51:19 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 4 Sep 2008 15:51:19 +0000 (UTC) Subject: overwrite set behavior References: Message-ID: On Thu, 4 Sep 2008 12:06:14 +0200, Marco Bizzarri wrote: >> As far as I understand you, you need descriptors: >> http://users.rcn.com/python/download/Descriptor.htm > I know descriptors a litte, Wojtek, but didn't use them often; can you > elaborate a little more on your idea? Marco, I think that I misunderstood the OP, but I was thinking about immutable (or set-once) attributes. Something like this: --- class SetOnce(object): def __init__(self): self._attr1 = "" self._attr1flag = False def setatt(self, x): if self._attr1flag: raise ValueError("attribute already set") self._attr1flag = True self._attr1 = x def getatt(self): return self._attr1 attr1 = property(getatt, setatt) a = SetOnce() a.attr1 = 1 print a.attr1 try: a.attr1 = 2 except ValueError: print a.attr1 --- $ python immutattr.py 1 1 $ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From kay.schluehr at gmx.net Sun Sep 21 00:39:11 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Sep 2008 21:39:11 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <2c0a8279-e888-4ae5-90a2-f2f1bb137607@x41g2000hsb.googlegroups.com> Message-ID: <8d30318b-2c54-4d4e-b333-016a0806c1ad@y38g2000hsy.googlegroups.com> On 20 Sep., 23:07, "Aaron \"Castironpi\" Brady" wrote: > On Sep 20, 3:22 pm, Kay Schluehr wrote: > > > > > On 20 Sep., 18:33, Bruno Desthuilliers > > > wrote: > > > The following definitions are AFAIK the only commonly accepted > > > definitions about OO: > > > > 1/ an object is defined by identity, state and behaviour > > > 2/ objects interacts by sending messages each other > > > 3/ an OO program is made of interacting objects > > > > I let you find out whether Python meets these 3 definitions - and if > > > Java does (hint : in Python, everything you can bind to a name is an > > > object - this is not true in Java or C++). > > > This is correct but it detracts from a more general problem of > > language "paradigms". > > > Assume you type > > > >>> 2+2 > > > 4 > > > Now you are free to interpret this as a simple, primitive arithmetic > > operation but you can also claim that 2 sends an __add__ message to 2. > > Hereby the state of the 2 objects are not altered but a new 4 object > > is created. OO babble is more impressive isn't it? > > > Actually it is simply wrong in the mentioned case and here is the > > proof: > > > def foo(): > > return 2+2 > > > import dis > > dis.dis(foo) > > > 2 0 LOAD_CONST 2 (4) > > 3 RETURN_VALUE > > > OO is a heuristic method used to understand the semantics of a > > programming language. It can also inspire language design but as > > you've rightly said: jugde yourself and see how far you get with it. > > > Applying OO on interpreter level is by no means a sign of a high > > quality implementation whereas structuring programs in the large will > > likely benefit from class based organization and encapsulation. Of > > course one can also reverse the value hierarchy and find perverse joy > > in having a pure OO language but apply monkey patching everywhere. I > > suppose you know which language I'm talking about... > > It sounds like you think that you -can- write OO programs in Python, > but you don't have to. I agree. The whole point of OO is providing high level ( system level ) not low level ( interpreter level ) semantics. Partitioning a system into isolated and communicating objects is a strong and important metaphor. Recently there were some comments on the web that mentioned Erlang to be pretty much OO in this respect although Erlang is functional and has no base level notion of an "object". It's even well known that Joe Armstrong holds low opinions about the entire object business. Notice that I believe that the popular meme that OO is "bolted on" Python has little if nothing to do with OO itself but with API consistency. When people have to type len(x) instead of x.len() this breaks their expectations on how the language has to behave. From psaffrey at googlemail.com Mon Sep 22 14:47:03 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Mon, 22 Sep 2008 11:47:03 -0700 (PDT) Subject: Job queue using xmlrpc and threading Message-ID: I'm trying to implement an application that will listen for requests, run them when they are present but also be able to add new requests even while it's running. I've tried to do this using the thread and xmlrpc modules - the idea is that an XML-RPC exposed object tell the queue thread object to add a job. If there are no jobs running, it creates a file, adds the new job to the end and then another consumption thread starts working through the jobs in the file. New jobs coming in are just added to the end of the file by the queue thread. Unfortunately, I can't get it to work. The problem is that the consumption thread seems to read the job queue before it gets written, even though I've used a lock. I've also had the application get to the stage where it ignores ctrl-c, which is a little worrying - I fear it doesn't bode well for future stability... I don't have a lot of experience with multi-threaded applications, so I may well have chosen a poor approach. I've posted the code below. It's in three parts, the job queue, the manager that listens for new requests and an application to add jobs to the queue. Sorry for the long listings... Any guidance gratefully received, Peter === testqueue.py: import thread import time import shutil import os class JobQueue: def __init__(self, filename): self.queuefile = filename self.jobthread = 0 # lock for the jobfile queue file self.jfqlock = thread.allocate_lock() def addJob(self, jobfileuri, email): self.jfqlock.acquire() if not self.jobthread: print "starting jobfile consumption thread" if os.access(self.queuefile, os.R_OK): print "cleaning stale jobfile queue file" try: os.remove(self.queuefile) except: print "problem removing jobfile queue file" raise self.jobthread = thread.start_new_thread(self.main, ()) else: print "using existing jobfile consumption thread in file", self.queuefile fh = open(self.queuefile, "a") # choose "::::" as a delimiter print >> fh, jobfileuri + "::::" + email self.jfqlock.release() return 1 def main(self): while 1: self.jfqlock.acquire() rfh = open(self.queuefile, "r") # breakpoint() finput = rfh.readline() print "found:", finput if not finput: print "finished jobfiles. Closing thread" rfh.close() self.jobthread = 0 self.jfqlock.release() return else: print "found jobfile in queue: attempting to run" # most of this is to shift up the lines in the file tmpname = self.queuefile + ".tmp" wfh = open(tmpname, "w") line = rfh.readline() while line: wfh.write(line) line = rfh.readline() wfh.close() rfh.close() shutil.move(tmpname, self.queuefile) self.jfqlock.release() # lop off the trailing line break print print "***run Starting***" try: self.runJob(finput[:-1]) print "***run finished***" except: print "***run failed***" print def runJob(self, job): time.sleep(2.0) print "running job", job if not report: print "some problem with run. Cannot mail out report" return === queuemanager.py from testqueue import JobQueue from SimpleXMLRPCServer import * class QM: def __init__(self, filename): self.jq = JobQueue("queue.txt") def addJob(self, jobname): self.jq.addJob(jobname, "tester at testdomain") if __name__=="__main__": qm = QM("jobqueue.txt") rpcserver = SimpleXMLRPCServer(("localhost", 8000)) rpcserver.register_instance(qm) rpcserver.serve_forever() === addjob.py: import xmlrpclib import sys server = "localhost" port = 8000 serveradd = "http://%s:%s" % (server, port) manager = xmlrpclib.ServerProxy(serveradd) jobname = sys.argv[1] manager.addJob(jobname) From rafesacks at gmail.com Tue Sep 9 23:56:43 2008 From: rafesacks at gmail.com (Rafe) Date: Tue, 9 Sep 2008 20:56:43 -0700 (PDT) Subject: Clearing a session and reload() problem (with repro error) References: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> Message-ID: <067abd3f-0d02-46e8-8d26-d85f20fa2e3a@s9g2000prg.googlegroups.com> On Sep 9, 11:03 pm, "Gabriel Genellina" wrote: > En Mon, 08 Sep 2008 05:37:24 -0300,Rafe escribi?: > ... > This dependency between modules, applied to all modules in your project, > defines a "dependency graph". In some cases, one can define a partial > ordering of its nodes, such that no module depends on any other module > *after* it (it may depend only on modules *before* it). Look for > "topological sort". > > Doing that in the generic case is not easy. If you *know* your > dependencies, reload the modules in the right order by hand. > ... > -- > Gabriel Genellina Hi Gabriel, Thank you for clarifying and re-presenting parts of my case. I appreciate the time. I was hoping there would be a way to just wipe out the module cache and let it get rebuilt by executing my code (since I'm not using reload as part of my program, but rather, to test it in an environment where I cannot restart the Python session). I have been keeping a diagram of my module inheritance to make sure it is as clean as possible, so I could just right a list of reloads as you suggest. However, one of the sub-packages is designed to allow users to add more modules. Because these get dynamically imported, a guess I could add an argument to the reload function to allow a user to give the 'add-on' module they are working on... so much work just to get a clean environment... Separate of my program, I was really hoping to write a generic reload tool for anyone developing in the same application as I am. I just don't see a way to trace import dependencies in systems which include dynamic imports. Any ideas? Thanks again, - Rafe From rokwok at newsguy.com Thu Sep 25 06:18:25 2008 From: rokwok at newsguy.com (Ronnie Kwok) Date: Thu, 25 Sep 2008 18:18:25 +0800 Subject: Connecting to SMB share in python References: Message-ID: <2008092518182581491-rokwok@newsguycom> Thank you for the reply! Yes, I am running the script under linux and it will be doing some processing before copying it over to the samba mount. It's totally fine to mount it with os.sys(...) approach but I am just thinking if there's other option. ronnie On 2008-09-25 16:36:35 +0800, Tim Golden said: > Ronnie Kwok wrote: >> Hello, >> >> I am trying to write a script that copy files from my local machine to a samba >> share. > > > Can't you just mount the share (albeit temporarily) and copy > the files over in the normal way? You haven't said what OS > you're on, but I'm assuming Linux otherwise you'd simply be > talking about a Windows share and copying to a UNC. > > TJG From samslists at gmail.com Thu Sep 18 22:32:47 2008 From: samslists at gmail.com (Sam) Date: Thu, 18 Sep 2008 19:32:47 -0700 (PDT) Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> Message-ID: For those that are interested, but don't want to bother running the program themselves, here's the output I get. Trying: http://slashdot.org http://slashdot.org - Apache/1.3.41 (Unix) mod_perl/1.31-rc4 (deflate) Errored out on this site. Trying: http://www.hotmail.com http://www.hotmail.com - Microsoft-IIS/6.0 (deflate) Errored out on this site. Trying: http://www.godaddy.com http://www.godaddy.com - Microsoft-IIS/6.0 (deflate) Errored out on this site. Trying: http://www.linux.com http://www.linux.com - Apache/2.2.8 (Unix) PHP/5.2.5 (deflate) Errored out on this site. Trying: http://www.lighttpd.net http://www.lighttpd.net - lighttpd/1.5.0 (deflate) Errored out on this site. Trying: http://www.kenrockwel.com http://www.kenrockwel.com - lighttpd (deflate) Able to decompress...went from 414 to 744. On Sep 18, 7:29?pm, Sam wrote: > On Sep 18, 2:10?pm, "Gabriel Genellina" > wrote: > > > En Tue, 16 Sep 2008 21:58:31 -0300, Sam escribi?: > > The code is correct - try with another server. I tested it with a ? > > LightHTTPd server and worked fine. > > Gabriel... > > I found a bunch of servers to test it on. ?It fails on every server I > could find (sans one). > > Here's the ones it fails on: > slashdot.org > hotmail.com > godaddy.com > linux.com > lighttpd.net > > I did manage to find one webserver it succeeded on---that is > kenrockwel.com --- a domain squatter with a typoed domain of one of my > favorite photographer's websites (the actual website should be > kenrockwell.com) > > This squatter's site is indeed running lighttpd---but it appears to be > an earlier version, because the official lighttpd site fails on this > test. > > We have all the major web servers failing the test: > * Apache 1.3 > * Apache 2.2 > * Microsoft-IIS/6.0 > * lighttpd/1.5.0 > > So I think it's the python side that is wrong, regardless of what the > standard is. > > What should I do next? > > I've rewritten the code to make it easier to test. ?Just run it as is > and it will try all my test cases; or pass in a site on the command > line, and it will try just that. > > Thanks! > > #!/usr/bin/env python > """Put the site you want to test as a command line parameter. > Otherwise tests the list of defaults.""" > > import urllib2 > import zlib > import sys > > opener = urllib2.build_opener() > opener.addheaders = [('Accept-encoding', 'deflate')] > > try: > ? ? sites = [sys.argv[1]] > except IndexError: > ? ? sites = ['http://slashdot.org', 'http://www.hotmail.com', > ? ? ? ? ? ? ?'http://www.godaddy.com', 'http://www.linux.com', > ? ? ? ? ? ? ?'http://www.lighttpd.net', 'http://www.kenrockwel.com'] > > for site in sites: > ? ? print "Trying: ", site > ? ? stream = opener.open(site) > ? ? data = stream.read() > ? ? encoded = stream.headers.get('Content-Encoding') > ? ? server = stream.headers.get('Server') > > ? ? print " ?%s - %s (%s)" % (site, server, encoded) > > ? ? if encoded == 'deflate': > ? ? ? ? before = len(data) > ? ? ? ? try: > ? ? ? ? ? ? data = zlib.decompress(data) > ? ? ? ? ? ? after = len(data) > ? ? ? ? ? ? print " ?Able to decompress...went from %i to %i." % > (before, after) > ? ? ? ? except zlib.error: > ? ? ? ? ? ? print " ?Errored out on this site." > ? ? else: > ? ? ? ? print " ?Data is not deflated." > ? ? print From google at mrabarnett.plus.com Thu Sep 11 13:46:27 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Sep 2008 10:46:27 -0700 (PDT) Subject: Enumerating ordered expat attributes with tuplets? References: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> Message-ID: On Sep 11, 4:48?pm, Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Ah, well. Don't know whether it meets your aesthetic standards, but: > ?>>> my_list = ['tree', 'hug', 'flower', 'hug', 'bear', 'run'] > ?>>> my_list[0:len(a):2] > ['tree', 'flower', 'bear'] > ?>>> my_list[1:len(a):2] > ['hug', 'hug', 'run'] > > and hence > > ?>>> zip(my_list[0:len(a):2], my_list[1:len(a):2]) > [('tree', 'hug'), ('flower', 'hug'), ('bear', 'run')] > > and furthermore > > ?>>> for a, b in zip(my_list[0:len(a):2], my_list[1:len(a):2]): > ... ? ? print a, b > ... > tree hug > flower hug > bear run > > or the slightly less obfuscated: > > ?>>> for index in range(0, len(my_list), 2): > ... ? ? print my_list[index], my_list[index + 1] > ... ? ? > tree hug > flower hug > bear run > [snip] I don't know what the "len(a)" is, but the end position defaults to the end: >>> zip(my_list[0::2], my_list[1::2]) [('tree', 'hug'), ('flower', 'hug'), ('bear', 'run')] From arnodel at googlemail.com Tue Sep 23 14:25:53 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 23 Sep 2008 11:25:53 -0700 (PDT) Subject: Detecting the first time I open/append to a file References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> Message-ID: <53d810e4-9829-4a88-94f5-32d849ee0c55@x35g2000hsb.googlegroups.com> On Sep 23, 7:02?pm, tkp... at hotmail.com wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a ?single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > ? ? for param in range(10): > ? ? ? ? simulate(param) > > def simulate(parameter): > ? ? 'Lots of code followed by: > ? ? with open(summaryFn, 'ab') as f: > ? ? ? ? writer = csv.writer(f) > ? ? ? ? writer.writerow(header) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) > ? ? ? ? writer.writerow(Sigma) > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. > > Thanks in advance for your assistance > > Thomas ?Philips You can use he os.path module: appending = os.path.exists(summaryFn) with open(summaryFn, 'ab') as f: writer = ... if not appending: writer.writerow(header) writer.writerow(Sigma) But if you only write to the file in one code location, you can set a flag. HTH -- Arnaud From peke at iki.fi Mon Sep 22 05:25:58 2008 From: peke at iki.fi (Pekka Laukkanen) Date: Mon, 22 Sep 2008 12:25:58 +0300 Subject: A bit weird dictionary behavior Message-ID: Hello, just noticed this: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> {1: 2} {1: 2} >>> {True: False} {True: False} >>> {1: 2, True: False} {1: False} This must be because >>> True == 1 and True in {1: 2} True but it still doesn't feel exactly right. Would it be worth submitting a bug? Cheers, .peke From sniipe at gmail.com Tue Sep 2 04:17:21 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Tue, 2 Sep 2008 01:17:21 -0700 (PDT) Subject: How to print first(national) char from unicode string encoded inutf-8? References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com><7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> Message-ID: On 2 Wrz, 06:05, "Mark Tolonen" wrote: > "Marco Bizzarri" wrote in message > > news:mailman.331.1220276398.3487.python-list at python.org... > > > > > On Mon, Sep 1, 2008 at 3:25 PM, wrote: > > >> When I do ${urllib.unquote(c.user.firstName)} without encoding to > >> latin-1 I got different chars than I will get: no ?ukasz but ? ukasz > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > > That's crazy. "string".encode('latin1') gives you a latin1 encoded > > string; latin1 is a single byte encoding, therefore taking the first > > byte should be no problem. > > > Have you tried: > > > urlib.unquote(c.user.firstName)[0].encode('latin1') or > > > urlib.unquote(c.user.firstName)[0].encode('utf8') > > > I'm assuming here that the urlib.unquote(c.user.firstName) returns an > > encodable string (which I'm absolutely not sure), but if it does, this > > should take the first 'character'. > > The OP stated that the original string was "encoded in UTF-8 and > urllib.quote()", so after urllib.unquote the string is in UTF-8 format. > This must be decoded into a Unicode string before removing the first > character: > > urllib.unquote(c.user.firstName).decode('utf-8')[0] > > The next problem is that the character in the OP's example string '?' is not > present in the latin-1 encoding, but using utf-8 encoding demonstrates that > the full two-byte UTF-8 encoded character is collected: > > >>> import urllib > >>> name = urllib.quote(u'?ukasz'.encode('utf-8')) > >>> name > '%C5%81ukasz' > >>> urllib.unquote(name).decode('utf-8')[0].encode('utf-8') > '\xc5\x81' > > -Mark @Mark, when I tried urllib.unquote(c.user.firstName).decode('utf-8') [0].encode('utf-8'), I received this message: >> return render('/reports/create_report_step2.mako') Module pylons.templating:344 in render << **cache_args) return pylons.buffet.render(template_name=template, fragment=fragment, format=format, namespace=kargs, **cache_args) >> format=format, namespace=kargs, **cache_args) Module pylons.templating:229 in render << log.debug("Rendering template %s with engine %s", full_path, engine_name) return engine_config['engine'].render(namespace, template=full_path, **options)>> **options) Module mako.ext.turbogears:49 in render << info.update(self.extra_vars_func()) return template.render(**info) >> return template.render(**info) Module mako.template:114 in render << declared by this template's internal rendering method are also pulled from the given *args, **data members. members.""" return runtime._render(self, self.callable_, args, data) def render_unicode(self, *args, **data):>> return runtime._render(self, self.callable_, args, data) Module mako.runtime:287 in _render << context = Context(buf, **data) context._with_template = template _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) return context.pop_buffer().getvalue()>> _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) Module mako.runtime:304 in _render_context << # if main render method, call from the base of the inheritance stack (inherit, lclcontext) = _populate_self_namespace(context, tmpl) _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) else: # otherwise, call the actual rendering method specified>> _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) Module mako.runtime:337 in _exec_template << error_template.render_context(context, error=error) else: callable_(context, *args, **kwargs)>> callable_(context, *args, **kwargs) Module _reports_create_report_step2_mako:57 in render_body << context.write(filters.decode.utf8(urllib.unquote(str(c.period.end)))) context.write(u' + ') context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8') [0].encode('utf-8'))) context.write(filters.decode.utf8(urllib.unquote(str(c.user.secondName) [0:1]))) context.write(u'\r\n > > > Try %% :) > > Christian > > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks Garry & Christian. It worked. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Mon Sep 29 16:56:08 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 29 Sep 2008 16:56:08 -0400 Subject: Music knowledge representation In-Reply-To: <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> <20080929124940.8c1c82e8.darcy@druid.net> <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> Message-ID: <20080929165608.b7b87b60.darcy@druid.net> On Mon, 29 Sep 2008 20:29:44 +0200 "Mr.SpOOn" wrote: > > Couldn't the note class simply have a list of all the notes and have a > > simple method calculate the actual pitch? > > That's not really how it works. There exists just 12 octave > independent pitch classes. This means that there is a pitch class C > with all possible Cs. There ambiguities with accidentals, because > different named notes fall in the same pitch class. The difference is > important for the musical theory, because C# and Db belongs to the > same pitch class (actually they are the same note, they sounds > completely identical -- because on the piano you play them pressing > the same key), but in a scale they have a very different role. Sure, they are enharmonically identical but in our tempered scale. That's why my example showed it as (note, octave, accidental) rather than a specific note. It would differentiate between these. > For example, the interval C F# is an "augmented fourth", because what > really matters are the natural note (C and F), and their distance if > 4. Then it is augmented due to the #- > > But the interval C Gb (Gb is the same as F#) is a "diminished fifth". This is true. My simple example would not have dealt with this. The arguments would have to be the full tuple rather than the actual pitch. > So I can't list all pitches. You can but you can't store them as raw pitches. > > def interval(self, lower, higher) > > if lower > higher: > > # uncomment one of the two following lines depending > > # on the behaviour you want > > #lower,higher = higher,lower > > #higher += 12 > > > > # could use some error trapping > > return self.interval_name[higher - lower] > > > > Note that lower and higher could be a note object that you have to > > convert to integers first. > > I can't estabilish which note is higher, because all the analysis part > is octave independent. Anyway thanks for the ideas. I'm not sure I understand this. You either have to assume that the first note is the root or the lower one is. What other options are there? It sounds like your requirement is "higher += 12" or some variant. It also depends on whether you need to deal with things like ninths and thirteenths. Anyway, I was just tossing out ideas. You know what your requirements are better than I. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From michael at stroeder.com Thu Sep 25 13:46:14 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 25 Sep 2008 19:46:14 +0200 Subject: Lotus Domino and Python via DIIOP or similar? Message-ID: <7cvsq5-e5p.ln1@nb2.stroeder.com> HI! Anybody here with experience in accessing Lotus Domino with Python via DIIOP? In particular I'd like to be able to register Notes users with a Python script. Preferrably without having to use Win32 COM although it would be better than nothing. Adding address Notes book entries via LDAP is possible but AFAIK does not lead to full Notes users (with mailbox and Notes-ID file). Ciao, Michael. From gagsl-py2 at yahoo.com.ar Tue Sep 30 20:32:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 21:32:28 -0300 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: En Mon, 29 Sep 2008 19:04:18 -0300, Ivan Reborin escribi?: > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? I agree that using NumPy is the way to go if you're going to do lots of array calculations. But a plain Python code would look like this (more comprehensible than other posted versions, I hope): --- begin code --- def read_group(fin, rows_per_group): rows = [] for i in range(rows_per_group): line = fin.readline() row = [float(x) for x in line.split()] rows.append(row) fin.readline() # skip blank line return rows # simulate a file using a string instead # actual code would use: fin = open(filename) from StringIO import StringIO fin = StringIO("""1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 """) # read 2 groups of 3 lines each matrix = [read_group(fin, 3) for k in range(2)] print matrix --- end code --- A more compact version of read_group (collapsing all rows.append onto the outer list comprehension): --- begin code --- def read_group(fin, rows_per_group): rows = [[float(x) for x in fin.readline().split()] for i in range(rows_per_group)] fin.readline() # skip blank line return rows --- end code --- -- Gabriel Genellina From erikwickstrom at gmail.com Thu Sep 18 17:33:25 2008 From: erikwickstrom at gmail.com (erikcw) Date: Thu, 18 Sep 2008 14:33:25 -0700 (PDT) Subject: Launching a subprocess without waiting around for the result? Message-ID: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Hi, I have a cgi script where users are uploading large files for processing. I want to launch a subprocess to process the file so the user doesn't have to wait for the page to load. What is the correct way to launch subprocess without waiting for the result to return? Thanks! From mark at thomaszone.com Mon Sep 15 14:32:16 2008 From: mark at thomaszone.com (Mark Thomas) Date: Mon, 15 Sep 2008 11:32:16 -0700 (PDT) Subject: ElementTree oddities References: Message-ID: Fredrik is correct, the text attribute only contains text before a child element; tail contains the rest. It is indeed rather odd. For comparison, here's how you would do it in lxml (http://codespeak.net/ lxml/index.html), a library which supports XPath: from lxml import etree tree = etree.fromstring('Bar:') print ' '.join(tree.xpath('//text()')) From castironpi at gmail.com Sun Sep 28 17:22:08 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 14:22:08 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: On Sep 28, 4:08?pm, Michael Str?der wrote: > Gary M. Josack wrote: > > Aaron "Castironpi" Brady wrote: > >> On Sep 28, 2:59 pm, sotirac wrote: > > >>> Wondering if there is a better way to generate string of numbers with > >>> a length of 5 which also can have a 0 in the front of the number. > > >>>
> >>> ?random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> >>> elements
> >>> ?code = 'this is a string' + str(random_number[0]) +
> >>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> >>> + str(random_number[4])
> >>> 
> > >> '%05i'%random.randint(0,99999) > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > > This produces numbers other than 5 digit numbers. making the start > > number 10000 should be fine. > > Why do you think it's wrong? > > > > >>> import random > >>> '%05i'%random.randint(0,99999) > '09449' > > IMO it's exactly what was required. > > Ciao, Michael. As you read, there isn't agreement on whether the OP wanted replacement. His original code didn't; his spec seemed to. From lists at cheimes.de Wed Sep 24 06:01:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 24 Sep 2008 12:01:59 +0200 Subject: python 3.x third party modules In-Reply-To: References: Message-ID: Almar Klein wrote: > Can > anyone say something about that? Will it take a month, a year? A year or more is realistic. A couple of years is even more realistic. Large projects are moving slowly and Python 3.0 introduces some heavy changes. The separation of text (unicode str) and data (bytes) takes time. Christian From hniksic at xemacs.org Tue Sep 16 04:48:42 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 10:48:42 +0200 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: <87hc8g79xx.fsf@mulj.homelinux.net> "Chris Rebert" writes: >> c = [9,10] >> [1,2,3,4,7].append(c) -> Is this a valid expression? > > Literally, no, because you can't call methods on literals. This is in fact not true. [1,2,3,4,7].append([9, 10]) is a perfectly valid expression, only it doesn't do much (that you can observe). The canonical response (no doubt already quoted in this thread) is that returning the list from append would confuse the hell out of people who expect a copy of the list, such as: a = [1, 2, 3] b = a.append(4) # if the above "worked" in the sense that b == [1, 2, 3, 4], I for one # would expect a to remain unchanged From drobinow at gmail.com Mon Sep 8 20:40:01 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Mon, 8 Sep 2008 17:40:01 -0700 (PDT) Subject: F2PY ?? Has anyone worked with the F2PY generator? References: <27CC3060AF71DA40A5DC85F7D5B70F3802840447@AWMAIL04.belcan.com> Message-ID: <9166df82-0a50-478c-8446-e3ef23f53c7e@y21g2000hsf.googlegroups.com> On Sep 8, 7:19?pm, "Blubaugh, David A." wrote: > Pauli, > > Yes, ?I am utilizing the windows environment. ?I cannot install f2py. ? > > I obtain the following error when I try to execute the setup.py file > within the f2py folder located within the numpy master folder: You shouldn't need to do this. The installation of numpy puts f2py.py in your Scripts folder. explicitly: C:\Python25\Python C:\Python25\Scripts\f2py.py From heston.james at coldbeans.co.uk Tue Sep 30 09:43:59 2008 From: heston.james at coldbeans.co.uk (Heston James - Cold Beans) Date: Tue, 30 Sep 2008 14:43:59 +0100 Subject: ElementTree Help With DTD Message-ID: <004701c92302$97a61300$c6f23900$@james@coldbeans.co.uk> Afternoon All, I have used elementtree for a little while now parsing simple XML documents and found it pretty intuitive. Today is the first time I've used the library to create an XML file though. I have a simple script which looks like this: # Save the configuration to the XML file. # Create the root element, top = etree.Element("top") # Create the other elements in the tree. sub1 = etree.SubElement(top, "sub1") sub1.text = "other text" # Create the core element tree object. tree = etree.ElementTree(top) # Write the XML to the file system. tree.write("/path/to/my.xml") This works just fine, in as much that I get an XML file with the correct XML content within it, like so: other text However, I really need to validate this built XML against a DTD schema that I have, and also add the DTD reference to the top of the generated file, so other applications parsing it in can validate it properly, like so: other text As you can see, this also includes the proper XML definition for the file. Can anyone offer any pointers on how to have ElementTree add these additional definitions to the file it generates? And also validate itself against the DTD before writing to the FS? Many thanks guys, I really appreciate it. Heston -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at yahoo.se Tue Sep 16 11:38:44 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 08:38:44 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: Message-ID: On Sep 16, 5:25?pm, Python wrote: > On 16 sep 2008, at 17:13, cnb wrote: > > > > >>>> sys.path > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', ? > > 'C:\ > > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > > \lib\\site-packages\\PIL'] > > > Now I have my personal programs in C:/Python25/Progs/ > > > How do I add so that I can just do "import somefile" from anywhere in > > that directory in the interpreter and it can load files from other > > folders in that directory. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > a temp solution is to append it to that list: > > sys.path.append('C:/Python25/Progs/') > > a permanent solution is to add it to the environment variable > (no idea where to set this in windows) > $PYTHONPATH = "/C:/Python25/Progs/" > > gr > Arno but since Python25/ is in my path it only seems to import from that exact dir, not dirs inside the dir. so i have to do somerthing like /progs/* ? and also, temporary adding doesnt seem to work. From marek at xivilization.net Tue Sep 2 12:38:10 2008 From: marek at xivilization.net (Marek Kubica) Date: Tue, 2 Sep 2008 16:38:10 +0000 (UTC) Subject: pyparsing: match empty line Message-ID: Hi, I am trying to get this stuff working, but I still fail. I have a format which consists of three elements: \d{4}M?-\d (4 numbers, optional M, dash, another number) EMPTY (the token) [Empty line] (the token. The line may contain whitespaces, but nothing else) While the ``watchname`` and ``leaveempty`` were trivial, I cannot get ``pagebreak`` to work properly. #!/usr/bin/env python # -*- coding: UTF-8 -*- from pyparsing import (Word, Literal, Optional, Group, OneOrMore, Regex, Combine, ParserElement, nums, LineStart, LineEnd, White, replaceWith) ParserElement.setDefaultWhitespaceChars(' \t\r') watchseries = Word(nums, exact=4) watchrev = Word(nums, exact=1) watchname = Combine(watchseries + Optional('M') + '-' + watchrev) leaveempty = Literal('EMPTY') def breaks(s, loc, tokens): print repr(tokens[0]) #return ['' for token in tokens[0]] return [''] #pagebreak = Regex('^\s*$').setParseAction(breaks) pagebreak = LineStart() + LineEnd().setParseAction(replaceWith ('')) parser = OneOrMore(watchname ^ pagebreak ^ leaveempty) tests = [ "2134M-2", """3245-3 3456M-5""", """3256-4 4563-4""", """4562M-6 EMPTY 3246-5""" ] for test in tests: print parser.parseString(test) The output should be: ['2134M-2'] ['3245-3', '3456M-5'] ['3256-4', '' '4563-4'] ['4562M-6', '', '3246-5'] Thanks in advance! regards, Marek From castironpi at gmail.com Sun Sep 7 17:00:30 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 7 Sep 2008 14:00:30 -0700 (PDT) Subject: lacking follow-through Message-ID: I am concerned by the lack of follow-through on some responses to recent ideas I have described. Do I merely have a wrong understanding of group policy? Is it a good policy (defined with respect to the future of Python and the welfare of humans at large) if so? Is there a serious lack of diligence, or should I merely take more initiative, and ignore charges of 'pestering'? (Warning, moderately deep outside social issues on table too.) From marco.bizzarri at gmail.com Fri Sep 12 11:01:11 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 12 Sep 2008 17:01:11 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <6ivdhnFnm8bU1@mid.uni-berlin.de> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> On Fri, Sep 12, 2008 at 4:44 PM, Diez B. Roggisch wrote: >>> if any(instance.forbitToClose(archivefolder) for instance in >>> self.findActiveOutgoingRegistrationInstances()) >> >> Can you clarify where I can find "any"? It seems to me I'm unable to find >> it... > > It's part of python2.5. > > If you don't have that, you can write it your own and stuff it into > __builtins__: > >>>> def any(iterable): > ... for item in iterable: > ... if item: > ... return True > ... return False > ... > ... __builtins__.any = any > > > You might also want to add all, the companion of any: > > >>>> def all(iterable): > ... for item in iterable: > ... if not item: > ... return False > ... return True > ... > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for the clarification, Diez! Indeed, I tried python2.3 and python2.4, and of course not python2.5 ;) I would like to make this available to the whole project. I suspect I could put it in the package __init__.py... in that way, the __builtins__ namespace should have it... am I right? -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From michele.simionato at gmail.com Mon Sep 29 10:33:01 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 29 Sep 2008 07:33:01 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Message-ID: On Sep 28, 6:43?am, "Aaron \"Castironpi\" Brady" wrote: > Hello all, > > To me, this is a somewhat unintuitive behavior. ?I want to discuss the > parts of it I don't understand. > > >>> f= [ None ]* 10 > >>> for n in range( 10 ): > > ... ? ? f[ n ]= lambda: n > ...>>> f[0]() > 9 > >>> f[1]() > > 9 > You may want to read this old thread that goes in detail explaining scoping issues with closures in for loops: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d691240a5cfebcdf/93503c5b9c66226e?hl=en&lnk=gst&q=simionato+jacek#93503c5b9c66226e From rsarpi at gmail.com Tue Sep 9 16:33:35 2008 From: rsarpi at gmail.com (icarus) Date: Tue, 9 Sep 2008 13:33:35 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background Message-ID: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> platform: windows xp professional, python 2.5, wxpython When I double-check on my program file test.py (for simplicity I'll be using this code below), I see the window just fine. But the ms-dos black window pops up in the background. On Linux, no issues at all. How can I get rid of that ms-dos black window in the background? something I need to add to my code? a setting to adjust in windows? thanks in advance. #!/usr/bin/python import wx appwx = wx.App() frame = wx.Frame(None, -1, 'test.py') frame.Show() appwx.MainLoop() From dudeja.rajat at gmail.com Thu Sep 25 04:30:41 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Thu, 25 Sep 2008 09:30:41 +0100 Subject: unable to parse the content using the regular expression Message-ID: Hello, I've the following results from Difflib.Compare() which I want to parse them using the regular expression to find out the the values that have changed. ###################################################################### Testing DLL interface ###################################################################### Input File: c:\12.txt Config File: c:\abc.ini ###################################################################### Results:- ------- - Analysis Time (Iterations = 1) = 0.0449145s ? ^^ ^ + Analysis Time (Iterations = 1) = 0.0447347s ? ^^ ^ Width = 0.999989 Height = 0.044 - Length = 10 ? ^ + Length = 11 ? ^ End of Results ###################################################################### Testing DOTNET interface ###################################################################### Input File: c:\12.txt Config File: c:\abc.ini ####################################################################### Results:- ------- - Analysis Time (Iterations = 1) = 0.0449145s ? ^^ ^ + Analysis Time (Iterations = 1) = 0.0447347s ? ^^ ^ Width = 0.999989 Height = 0.044 - Length = 12 ? ^ + Length = 13 ? ^ End of Results ****** How Can I extract the headings out of this file? The headings are: ###################################################################### Testing DLL interface ###################################################################### Input File: c:\12.txt Config File: c:\abc.ini ###################################################################### < Here I want to display only the values that differ i.e. the lines prceded with +,?,- signs > ###################################################################### Testing DOTNET interface ###################################################################### Input File: c:\12.txt Config File: c:\abc.ini ####################################################################### I intent to show only the things that differ with their proper headings(as above) Please help me to get the heading stuff out. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at spamhaters.com Sat Sep 6 16:18:55 2008 From: nospam at spamhaters.com (clurker) Date: Sat, 06 Sep 2008 15:18:55 -0500 Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: Michele Simionato wrote: > On Aug 28, 6:21?am, ssecorp wrote: >> Is there a way to view all the modules I have available for import >> from within Python? >> Like writing in the interpreter: > > Try: > >>>> help() > help> modules > Please wait a moment while I gather a list of all available modules... > This looks like it could be a useful tool, but when I try it I get the following: Please wait a moment while I gather a list of all available modules... /usr/lib/python2.5/site-packages/reportlab/lib/PyFontify.py:35: Warning: 'with' will become a reserved keyword in Python 2.6 /usr/lib/python2.5/site-packages/reportlab/lib/PyFontify.py:36: Warning: 'with' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site.py", line 346, in __call__ return pydoc.help(*args, **kwds) File "/usr/lib/python2.5/pydoc.py", line 1645, in __call__ self.interact() File "/usr/lib/python2.5/pydoc.py", line 1663, in interact self.help(request) File "/usr/lib/python2.5/pydoc.py", line 1679, in help elif request == 'modules': self.listmodules() File "/usr/lib/python2.5/pydoc.py", line 1797, in listmodules ModuleScanner().run(callback) File "/usr/lib/python2.5/pydoc.py", line 1848, in run for importer, modname, ispkg in pkgutil.walk_packages(): File "/usr/lib/python2.5/pkgutil.py", line 110, in walk_packages __import__(name) File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 1342, in File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 927, in main UnboundLocalError: local variable 'given_files' referenced before assignment >>> which could be because I am fairly free and unrestrained when it comes to installing stuff, and I see now I have modules on both /usr/lib/python2.5 and /usr/local/lib/python2.5 Apparently python knows about them both, but I don't know I haven't introduced an incompatibility somewhere...and that PIL package showing up at the tail of the errors was one of my more recent additions... Any help will be appreciated, sc From gagsl-py2 at yahoo.com.ar Fri Sep 19 06:48:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 07:48:27 -0300 Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> Message-ID: En Thu, 18 Sep 2008 23:29:30 -0300, Sam escribi?: > On Sep 18, 2:10?pm, "Gabriel Genellina" > wrote: >> En Tue, 16 Sep 2008 21:58:31 -0300, Sam escribi?: >> The code is correct - try with another server. I tested it with a ? >> LightHTTPd server and worked fine. > > Gabriel... > > I found a bunch of servers to test it on. It fails on every server I > could find (sans one). I'll try to check later. Anyway, why are you so interested in deflate? Both "deflate" and "gzip" coding use the same algorithm and generate exactly the same compressed stream, the only difference being the header and tail format. Have you found any server supporting deflate that doesn't support gzip as well? -- Gabriel Genellina From david at boddie.org.uk Mon Sep 15 17:40:13 2008 From: david at boddie.org.uk (David Boddie) Date: Mon, 15 Sep 2008 23:40:13 +0200 Subject: MVC with Python References: Message-ID: On Monday 15 September 2008 21:37, Georg Altmann wrote: > I need some advice on how to implement model-view-controller. I am > trying to develop a GUI application with PyQt, yet the problem rather > applies to mvc in general, not just GUI applications. > > Let's say the data is a list of objects with a common base class. The > views are either a graphical representation of the objects or some form > of textual input. The views shall change the model by using command > objects (for undo, e.g. QUndoCommand). [...] > My problem is, how do the commands interact with the model? One approach that combines the undo framework with the model/view framework is described here: http://doc.trolltech.com/qq/qq25-undo.html The implementation is in C++, but it may be possible to pick up some useful tips from the article. David From mrkafk at gmail.com Wed Sep 3 09:57:50 2008 From: mrkafk at gmail.com (mk) Date: Wed, 03 Sep 2008 15:57:50 +0200 Subject: properties setting each other Message-ID: Hello everyone, I try to set two properties, "value" and "square" in the following code, and arrange it in such way that setting one property also sets another one and vice versa. But the code seems to get Python into infinite loop: >>> import math >>> class Squared2(object): def __init__(self, val): self._internalval=val self.square=pow(self._internalval,2) def fgetvalue(self): return self._internalval def fsetvalue(self, val): self._internalval=val self.square=pow(self._internalval,2) value = property(fgetvalue, fsetvalue) def fgetsquare(self): return self.square def fsetsquare(self,s): self.square = s self.value = math.sqrt(self.square) square = property(fgetsquare, fsetsquare) >>> a=Squared2(5) Traceback (most recent call last): File "", line 1, in a=Squared2(5) File "", line 5, in __init__ self.square=pow(self._internalval,2) File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare ... Is there a way to achieve this goal of two mutually setting properties? From mensanator at aol.com Sun Sep 7 20:22:21 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 7 Sep 2008 17:22:21 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: On Sep 7, 3:13?pm, "Gabriel Genellina" wrote: > En Sun, 07 Sep 2008 14:30:09 -0300, Mensanator escribi?: > > > > > Actualy, I already get the behaviour I want. sum([1,None]) > > throws an exception. I don't see why sum([]) doesn't throw > > an exception also (I understand that behaviour is by design, > > I'm merely pointing out that the design doesn't cover every > > situation). > [...] > > Exactly. That's why I would prefer sum([]) to raise an > > exception instead of giving a false positive. > > The built in behavior can't be good for every usage. Nobody prevents you from defining yoru own function tailored to your own specs, like this: > > def strict_sum(items): > ? ? items = iter(items) > ? ? try: > ? ? ? ? first = items.next() > ? ? except StopIteration: > ? ? ? ? raise ValueError, "strict_sum with empty argument" > ? ? return sum(items, first) > > Tweak as needed. Based on other posts I believe your Python skills are enough to write it on your own, so I don't see why you're complaining so hard about the current behavior. I'm not complaining about the behaviour anymore, I just don't like being told I'm wrong when I'm not. But I think I've made my point, so there's no point in harping on this anymore. > > -- > Gabriel Genellina From dickinsm at gmail.com Wed Sep 24 06:14:38 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 24 Sep 2008 03:14:38 -0700 (PDT) Subject: Comparing float and decimal References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: On Sep 23, 7:31?pm, Terry Reedy wrote: > Decimal is something of an anomaly in Python because it was written to > exactly follow an external standard, with no concessions to what would > be sensible for Python. ?It is possible that that standard mandates that > Decimals not compare to floats. I don't think the standard says anything about interactions between Decimals and floats. But there's certainly been a feeling amongst at least some of the developers that the job of Python's decimal module is to implement the standard and no more, and that extensions to its functionality belong elsewhere. Regarding equality, there's at least one technical issue: the requirement that objects that compare equal hash equal. How do you come up with efficient hash operations for integers, floats, Decimals and Fractions that satisfy this requirement? For other arithmetic operations: should the sum of a float and a Decimal produce a Decimal or a float? Why? It's not at all clear to me that either of these types is 'higher up' the numerical tower than the other. Mark From aetodd at gmail.com Sat Sep 20 17:20:20 2008 From: aetodd at gmail.com (Andrew) Date: Sat, 20 Sep 2008 14:20:20 -0700 (PDT) Subject: explain slice assignment to newb Message-ID: please explain this behavior to a newb: >>> a = [1,2,3,4] >>> b = ["a","b","c","d"] >>> a [1, 2, 3, 4] >>> b ['a', 'b', 'c', 'd'] >>> a[0:2] [1, 2] >>> a [1, 2, 3, 4] >>> b[2:4] ['c', 'd'] >>> a[0:2] = b[0:2] >>> b[2:4] = a[2:4] >>> a ['a', 'b', 3, 4] >>> b ['a', 'b', 3, 4] >>> From castironpi at gmail.com Wed Sep 24 00:06:23 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 21:06:23 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> <31ff7c8a-28f3-4c62-8ac5-6d0f90106c5d@a8g2000prf.googlegroups.com> Message-ID: On Sep 23, 9:30?pm, lixinyi... at gmail.com wrote: > If the PyObject is a PyList, and all list items are strings, > say a=['aaa','bbb','ccc'] > > How can I have a > myArray[0] = "aaa" > myArray[1] = "bbb" > myArray[2] = "ccc" > in C++? > > Do I have to > use PyModule_GetDict() to get the dict first? > what about the next? > > > > > What do you know about the contents of 'argc' and 'argv'? ?If it's > > impossible with Py_Main, can you use one of the other entry points? > > > If you've never manipulated PyObject* objects in C, they can be > > hairy. ?Even if you know 'a' is a sequence, its contents are still all > > PyObject*s, which you can access via PyList_... and PySequence_ > > functions. > > This one writes '[aaa, bbb, ccc]' to the console in two different ways. #include int main() { PyObject *list, *listrepr; Py_Initialize(); /* first */ list= PyList_New( 3 ); PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( listrepr ); Py_DECREF( list ); /* second */ list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( listrepr ); Py_DECREF( list ); Py_Finalize(); return 0; } Did you want to execute some Python code, and examine variables it creates? From asnast at gmail.com Sun Sep 21 12:34:43 2008 From: asnast at gmail.com (Alex Snast) Date: Sun, 21 Sep 2008 09:34:43 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> <00e5938e$0$20331$c3e8da3@news.astraweb.com> Message-ID: On Sep 21, 3:47?am, Steven D'Aprano wrote: > On Sat, 20 Sep 2008 16:27:41 -0700, Alex Snast wrote: > > Another quick question please, is the List data structure just a dynamic > > array? If so how can you use static size array, linked list, AVL trees > > etcetera. > > Before I answer your question, I should say that you can go a LONG way > with just the standard Python built-in data structures list, dict and > set, plus a handful of standard modules like array and collections. It's > often (but not always) better to modify an algorithm to use a built-in > data structure than to try to implement your own. > > The underlying data structure for lists is implementation specific. Only > the behaviour is specified by the language. > > In the standard Python implementation written in C (usually known as > "Python", although sometimes people explicitly describe it as CPython), > lists are implemented as a fixed array of pointers. The array is > periodically resized, either up or down, but only as needed. The largest > consequence of that is that appending to the end of a list is much faster > than inserting at the beginning of the list. > > Other implementations (IronPython, Jython, PyPy, CLPython...) are free to > implement lists whatever way they need. > > If you want a static list, the simplest way is to create a list and > simply not resize it. If you want to enforce that, here's a subclass to > get you started: > > class StaticList(list): > ? ? def _resize(self): > ? ? ? ? raise RuntimeError("list can't be resized") > ? ? extend = append = pop = insert = remove = \ > ? ? __delitem__ = __delslice__ = _resize > > I haven't dealt with __setitem__ or __setslice__, because they're more > complicated: you need to make sure the slice you're setting has the same > size as the bit you're replacing, so that this is allowed: > > mylist[3:6] = [1, 2, 3] > > but not these: > > mylist[3:6] = [1, 2] > mylist[3:6] = [1, 2, 3, 4] > > As for linked lists and trees, don't worry about pointers, just go ahead > and implement them. > > # basic, no-frills tree > class Node(object): > ? ? def __init__(self, data, left=None, right=None): > ? ? ? ? self.left = left > ? ? ? ? self.right = right > ? ? ? ? self.info = data > > tree = Node('top of the tree') > tree.left = Node('left subtree') > tree.right = Node('right subtree', None, Node('another subtree')) > t = tree.right.right > t.left = Node('yet another subtree') > > etc. > > The CPython implementation of dict is a hash table, and dicts are > extremely fast and efficient. So long as you don't mind losing the order > of insertion, you won't beat dicts for speed and efficiency in anything > you write in pure Python. > > -- > Steven WOW you guys are really helpful, thanks everyone for all the replies. Last question: What IDE do you guys recommend, I'm currently using pydev. Thanks again, Alex From overdrigzed at gmail.com Fri Sep 12 19:38:12 2008 From: overdrigzed at gmail.com (overdrigzed at gmail.com) Date: Fri, 12 Sep 2008 16:38:12 -0700 (PDT) Subject: ctypes: Get full contents of character array Message-ID: Hello! I wanted to get the full contents of a character array stored in a struct, i.e. _fields_ = [...("array", c_char * 12)...] however, ctypes seems to try to return struct.array as a Python string rather than a character array, and stops as soon as it encounters a null within the character array. I ended up having to define a dummy struct class dummystruct(Structure): _fields_ = [] and declare array as: ("array", dummystruct) then use string_at(byref(struct.array), 12). Is this really the best way of doing it? Is there no better way to work around ctypes 'guess what you want' behaviour? Thanks in advance, Rodrigo From skip at pobox.com Sat Sep 6 16:47:22 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 6 Sep 2008 15:47:22 -0500 Subject: How to merge a module into a package w/ distutils? Message-ID: <18626.60506.393584.737943@montanaro-dyndns-org.local> The bsddb module is on the way out (deprecated in 2.6, gone in 3.0). That leaves Python without a cross-platform dbm module to sit underneath anydbm and shelve. I figured it might be useful to base something on top of sqlite3, which is cross-platform. The result is available in the Python sandbox: http://svn.python.org/view/sandbox/trunk/dbm_sqlite/ There are three files, a dbm.sqlite module, a test case and a modified bit of dbm documentation. For testing I'd like to install this in such a way that I can simply import dbm.sqlite but not overwrite the core install. I'd also not like to lose dbm.gdbm, etc during this testing phase. Is there some way to do this with distutils? Ideally, I'd like there to be a dbm package in site-packages but which falls back to the central installation when, say, dbm.gdbm isn't found. Thx, Skip From deets at nospam.web.de Mon Sep 8 06:52:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Sep 2008 12:52:57 +0200 Subject: Syntax Problem with strptime in Python 2.4 References: Message-ID: <6ikegtFr3ab7U1@mid.uni-berlin.de> W. eWatson wrote: > Apparently, use of strptime of datetime needs a workaround in Python 2.4 > to work properly. The workaround is d = > datetime.datetime(*(time.strptime(date_string, format)[0:5])). However, > when I try to use it, or even use it the regular way, it fails with > AttributeError: type object 'datetime.datetime' has no attribute > 'datetime'. > From the following code code segment: > > format = '%Y%m%d_%H%M%S' > #d=datetime.strptime('20080321_113405', format)-- typical use > print time.strptime('20080321_113405', format)[0:5] > d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5]) > > Does anyone know how to make this work in 2.4? If not, is there a way to > achieve the same result? This is not what you think it is. All your problem is that you do from datetime import datetime which imports the datetime-class, but then try to access datetime.datetime as if you had done import datetime. This actually is a wart in the datetime-module - it would be better if the classes in there would follow PEP-8. Diez From banibrata.dutta at gmail.com Wed Sep 24 03:51:48 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Wed, 24 Sep 2008 13:21:48 +0530 Subject: Does anybody use this web framework ? In-Reply-To: <48d9eb86$0$6127$426a34cc@news.free.fr> References: <48d94cbc$0$964$ba4acef3@news.orange.fr> <48d9eb86$0$6127$426a34cc@news.free.fr> Message-ID: <3de8e1f70809240051l3d32f44cl5e3fcc077e380ad@mail.gmail.com> On Wed, Sep 24, 2008 at 12:56 PM, Bruno Desthuilliers wrote: > Phil Cataldo a ?crit : > >> Hi, >> >> I just found this new? python web framework >> (http://pypi.python.org/pypi/nagare/0.1.0). >> >> Does anybody know or use it ? >> > > First time I hear of it, but it looks interesting (note : Stackless > continuation-based framework). Thanks for the link. > The description looks quite interesting indeed.... but as we heard in Spiderman and elsewhere... "with great power comes great responsibility"... the power is largely curtailed in most of the web-frameworks in status-quo ! -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Sat Sep 20 14:10:38 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 20 Sep 2008 11:10:38 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: <0e14ba9a-6f13-4e3f-b789-370ae8d1205f@2g2000hsn.googlegroups.com> On 20 Sep, 19:42, "Aaron \"Castironpi\" Brady" wrote: > > Wikipedia puts it decently: "mainly for OO programming, but with some > procedural elements." > > When it comes to Python and object-oriented programming, you can't leave out the ducks. ;-) Paul From half.italian at gmail.com Fri Sep 26 14:20:36 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 26 Sep 2008 11:20:36 -0700 (PDT) Subject: Writing a well-behaved daemon References: <874p43wl2m.fsf@benfinney.id.au> <87zllvv0py.fsf@benfinney.id.au> Message-ID: <5d09dd5e-4a0b-41f9-97c5-16bb47042f96@25g2000prz.googlegroups.com> On Sep 26, 12:13?am, Ben Finney wrote: > Sean DiZazzo writes: > > Looks like somebody did the same thing I did and posted it. > > >http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemo... > > Thanks, I've not seen that before. > > It still seems loony to me that something this difficult to do right, > yet so similar across different use cases, isn't in the standard > library, where bugs need only be fixed in one place. > > -- > ?\ ? ? ? ??Pinky, are you pondering what I'm pondering?? ?Wuh, I think | > ? `\ ? ? ?so, Brain, but how will we get three pink flamingos into one | > _o__) ? ? ? ? ? ? ? ? ? ? pair of Capri pants?? ?_Pinky and The Brain_ | > Ben Finney +1 I think it would be a great addition. From bignose+hates-spam at benfinney.id.au Tue Sep 9 19:51:09 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 10 Sep 2008 09:51:09 +1000 Subject: [OT] top-posting and quoting References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <48bfc4e4$0$13232$426a74cc@news.free.fr> <9efc52fa-f2d2-40e4-8fbb-fb4c06f8e0e4@a3g2000prm.googlegroups.com> <48c6c862$0$17309$426a34cc@news.free.fr> Message-ID: <87y720dgk2.fsf@benfinney.id.au> Bruno Desthuilliers writes: > Could you please timh and belindelof learn to quote properly and stop > top-posting ? In case it's not clear, by "quote properly" I believe Bruno means to trim quoted material irrelevant to one's reply, and use standard inline replies . Certainly that's what I'd prefer to see. -- \ ?None can love freedom heartily, but good men; the rest love | `\ not freedom, but license.? ?John Milton | _o__) | Ben Finney From almar.klein at gmail.com Mon Sep 15 03:36:02 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 15 Sep 2008 09:36:02 +0200 Subject: Good programming style In-Reply-To: References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: > > > Because the code we write rarely stays isolated from other > > code. There is an existing convention, > > There are many existing conventions. > Even though there is a convention (PEP 8), there are standard modules that do not follow it, like the subprocess module, which uses CamelCase. When packages as significant as wxPython use naming conventions > other than PEP 8, I find it hard to make a case that the PEP 8 > naming convention is any better than any other. > A lot of C/C++ projects are wrapped in python, and with that, their naming styles. As said above, it's often better to use the projects native naming styles than to change it to conform to PEP 8. So I guess it is impossible to have a single naming style in Python. For these two reasons, I think its so much more important to be consistent within a project, rather than to stick with PEP 8. When you are using a module, you'll see in no-time what style is used, and you're able to use it. The fact that some standard modules deviate from PEP 8 without problems shows it. Personally, I prefer CamelCase over under_scores. Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From sniipe at gmail.com Mon Sep 1 09:25:17 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Mon, 1 Sep 2008 06:25:17 -0700 (PDT) Subject: How to print first(national) char from unicode string encoded in utf-8? References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> Message-ID: <7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> On 1 Wrz, 15:10, "Marco Bizzarri" wrote: > 2008/9/1 : > > > > > Hi, > > > I have a problem with unicode string in Pylons templates(Mako). I will > > print first char from my string encoded in UTF-8 and urllib.quote(), > > for example string '?ukasz': > > > ${urllib.unquote(c.user.firstName).encode('latin-1')[0:1]} > > > and I received this information: > > > : 'utf8' codec can't decode byte > > 0xc5 in position 0: unexpected end of data > > > When I change from [0:1] to [0:2] everything is ok. I think it is > > because of unicode and encoding utf-8(2 bytes). > > > How to resolve this problem? > > > Best regards > > -- > >http://mail.python.org/mailman/listinfo/python-list > > First: you're talking about utf8 encoding, but you've written latin1 > encoding. Even though I do not know Mako templates, there should be no > problem in your snippet of code, if encoding is latin1, at least for > what I can understand. > > Do not assume utf8 is a two byte encoding; utf8 is a variable length > encoding. Indeed, > > 'a' encoded as utf8 is 'a' (one byte) > > '?' encode as utf8 is '\xc3\xa0' (two bytes). > > Can you explain what you're trying to accomplish (rather than how > you're tryin to accomplish it) ? > > Regards > Marco > > -- > Marco Bizzarrihttp://notenotturne.blogspot.com/http://iliveinpisa.blogspot.com/ When I do ${urllib.unquote(c.user.firstName)} without encoding to latin-1 I got different chars than I will get: no ?ukasz but ??ukasz From fredrik at pythonware.com Thu Sep 11 14:32:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 20:32:46 +0200 Subject: wx In-Reply-To: References: Message-ID: Desmond Scott E wrote: > I'm am a Python novice by chance not choice. (Although it appears to be > a nice tool. Plus anything based on Monte Python can't be bad!) > > My Quest is to migrate a Python-based process from Windows2000/Python > v2.4.2 (#67) to WindowsXP/Python v2.5.2 (r252:60911). > > I've searched the Python website and could find no reference to module > wx. Is this an add-in module or perhaps it was replaced in v2.5.2??? wx is wxPython: http://www.wxpython.org/ From john.m.roach at gmail.com Thu Sep 11 09:43:08 2008 From: john.m.roach at gmail.com (john) Date: Thu, 11 Sep 2008 06:43:08 -0700 (PDT) Subject: catching exceptions from fortran Message-ID: I wrapped some fortran code using F2PY and need to be able to catch fortran runtime errors to run the following: # "grid" is a wrapped fortran module # no runtime errors incurred when run with the correct inputs for filetype #------------------------------- def readGrid( self, coord='xyz' ): mg = ( '.FALSE.', '.TRUE.' ) form = ( 'FORMATTED', 'UNFORMATTED' ) success = False for m in mg: for f in form: try: if coord == 'xyz': self.grid.readxyz( self.filename, f, m ) success = True elif coord == 'xyrb': self.grid.readxyrb( self.filename, f, m ) success = True else: import sys print 'gridtype "' + str(coord) + '" not supported. ' \ + '' except: continue if not success: import sys print 'gridfile "' + str(self.filename) + '" not read in any recognized format' \ + ' ' #---------------------------- basically, what i want to happen is to try to run 'something' with the wrapped fortran code and if that doesn't work (error encountered, etc.) try something else. is there an easier way to go about doing this? is there something i'm missing about catching exceptions here? Thanks in advance! From linkmaster032000 at gmail.com Thu Sep 25 15:41:29 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Thu, 25 Sep 2008 12:41:29 -0700 (PDT) Subject: curses.setsyx()? References: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> <713190fc-e3a9-4a72-8bee-4fd3affcb531@c58g2000hsc.googlegroups.com> <5acmd4t7p44cbgi1fkmhaaasfplv0jaatr@4ax.com> Message-ID: <2a05e58b-bd73-41de-addb-f2605d188e9b@m3g2000hsc.googlegroups.com> On Sep 25, 2:39?am, Tim Roberts wrote: > linkmaster032... at gmail.com wrote: > >On Sep 23, 4:16?pm, brad.at.sch... at gmail.com wrote: > >> On Sep 22, 11:24?pm, Tim Roberts wrote: > >> > linkmaster032... at gmail.com wrote: > >> > >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: > >> > >> On Sep 19, 1:24?am, Tim Roberts wrote: > > >> > >> > linkmaster032... at gmail.com wrote: > > >> > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > >> > >> > >cursor. Any alternatives/solutions? > >>... > >> > >> I added it and it still doesn't work. This is what I'm doing when I > >> > >> want to display the cursor and prepare it for input at 2,3: > > >> > >> curses.echo() > >> > >> curses.curs_set(1) > >> > >> curses.setsyx(2,3) > >> > >> curses.doupdate() > > >> > >Any idea what's wrong? > > >>http://pastebin.com/m6413db1 > > >> Run that and press 'n' key. It is supposed to move the cursor to 2,3 > >> and it doesn't. > > Of course it does. ?It moves the cursor, then does an update, then > immediately calls draw.game, which redraws the screen and moves the cursor. > If you want curses.setsyx (or the equivalent and more mnemonic scr.move) to > leave the cursor somewhere, you can't draw more text afterward. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. OH!!!! Thank you!!! From ldo at geek-central.gen.new_zealand Wed Sep 24 06:18:05 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:18:05 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> Message-ID: In message <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d at posted.usinternet>, Grant Edwards wrote: > On 2008-09-23, Blubaugh, David A. wrote: > >> I was wondering if anyone has come across the issue of not being allowed >> to have the following within a Python script operating under Linux: >> >> time.sleep(0.0125) > > No, I have not. And I doubt anybody else has. Just a thought, your minimum sleep time is probably limited by the resolution of the system "HZ" clock. Type less /proc/config.gz and search for the value of the "CONFIG_HZ" setting. On the Athlon 64 machine I'm using to write this, it's 250, which should allow for sleep intervals in multiples of 0.004 seconds. From dblubaugh at belcan.com Sat Sep 20 12:59:06 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Sat, 20 Sep 2008 12:59:06 -0400 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> To All, I have now been able to generate a .pyd file from a FORTRAN file that I am trying to interface with python. I was able to execute this with an additional insight into how f2py operates. It seems as though the documentation requires an upgrade, since there appears to be missing information that might misdirect a f2py newcomer, such as myself. However, I am now facing the following new error: ImportError: DLL load with error code 193 The python script is as follows: import hello print hello.__doc__ print hello.foo.__doc__ hello.foo(4) The Fortran code is as follows: ! -*- f90 -*- subroutine foo(a) integer a print*, "Hello from Fortran!" print*, "a=", a end I was wondering as to what I should now try in order to finally produce a python sending and receiving information from a FORTRAN .pyd file. Any Suggestions??? Do I have to recompile Python with mingw32 in order to finally resolve this issue?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From python.list at tim.thechases.com Mon Sep 15 15:09:21 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Sep 2008 14:09:21 -0500 Subject: environment variable issue In-Reply-To: <48ceacb9$0$2863$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <48CEB2E1.6060600@tim.thechases.com> > Could someone explain me what I'm doing wrong here? I'm trying to > retrieve the value of an environment variable in Ubuntu 8.04 like this: > > >>> import os > >>> os.environ['USER'] > 'michel' > > This works but this doesn't: > > >>> os.environ['HOSTNAME'] > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'HOSTNAME' > > Why is it working in the first case but not in the second one. I must be > missing something but it seems I'm not able to figure it out. This is likely the same issue I just posted about here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/42346439533bd23a Your HOSTNAME variable hasn't been exported to subshells. You can check this by looking at the output of bash$ export -p which will print all the variables that are exported. I suspect you'll see $USER in the list, but not $HOSTNAME However, for the hostname, you might be interested in >>> import platform as p >>> p.uname()[1] 'rubbish' which does this in a cross-platform way without needing to fuss with exporting environment variables. -tkc From steven at REMOVE.THIS.cybersource.com.au Thu Sep 11 05:10:00 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Sep 2008 09:10:00 GMT Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <87k5djb6e2.fsf@benfinney.id.au> Message-ID: On Thu, 11 Sep 2008 15:25:57 +1000, Ben Finney wrote: >> > The bounce messages are sent to you because you sent the original. >> >> Wrong. I didn't send _any_ e-mail. Why should I get bounce messages? > > You asked for email to be sent, by sending a Usenet post to > comp.lang.python. That's what a news-to-mail gateway does. I wasn't aware that comp.lang.python was a news-to-mail gateway. How can one tell the difference between news groups that use a news-to-mail gateway, and news groups that don't? Posting to a public newsgroup is obviously giving consent to forward that news posting to news clients. Given the ability to opt-out with the X-No- Archive header, there may even be an implied consent to allow archiving. But I don't believe there is any such implied consent to format-shift news messages to email. In practice, I couldn't care less what format my news postings are converted to, so long as it is invisible and transparent to me. If somebody wants to build a news-to-carved-in-giant-stone-tablets gateway, I don't care, so long as I don't get giant stone tablets aren't dumped in my front yard. Nor do I believe that by posting a news message I've automatically consented to receive email messages. To imply that the one implies the other is equivalent to arguing that because I've written a letter to the editor of a newspaper, I therefore must accept private correspondence from any person or corporation that has a subscription to that newspaper. (In practice, I don't mind human-generated email messages, but not automatic messages. If you can turn my munged email address into a real email address, I probably won't mind you emailing me. Don't abuse the privilege.) [...] > I sympathise completely with your irritation at receiving bounce > messages from poorly-configured software, but the solution is not to > break the news-to-mail gateway. > > The correct solution is to unsubscribe the badly-behaving address from > the mailing list, and refuse re-subscription from that address without > assurance that the bad behaviour has ceased. The problem with that "correct solution" is that the party who suffers isn't in a position to correct the problem, and the party who can correct the problem has little incentive to do anything about it. That makes the solution ineffective and therefore anything but "correct". I hope the person running the mailing list does do the right thing, but if he or she does, it will be an accident of policy or personality, and not because the system is robust and self-corrects errors. To quote Dennis Lee Bieber: "The bounce/ooo-reply is sent to the message author, not to any intermediate host(s). After all, on that end, it's normal email failure response -- notify the author of the message. It doesn't matter that the original message was posted on a Usenet newsgroup if that group is automatically relayed to members of a mailing list." But that's wrong: it *shouldn't* be an normal email failure response, because the message author is in no position to do anything about it except to cease posting. That's a problem with all mailing lists (that I know of). -- Steven From fredrik at pythonware.com Fri Sep 5 02:47:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:47:05 +0200 Subject: ctypes error on Windows In-Reply-To: References: Message-ID: Fredrik Lundh wrote: >> I do have the tidy.dll installed (if I didn't, I couldn't even import >> the tidy module). > > typing the following into the Python interpreter might give you some > more clues: > > >>> import _tidy > >>> _tidy.__file__ > >>> dir(_tidy) or not, since ctypes is involved. have you checked for multiple copies of tidy.dll? if you have MSVC on your machine, try using "dumpbin /exports" on the DLL to check that it really exports the symbols the binding expects. From jonathon.blake at gmail.com Tue Sep 9 00:40:57 2008 From: jonathon.blake at gmail.com (jonathon) Date: Mon, 8 Sep 2008 21:40:57 -0700 Subject: a11y & python In-Reply-To: References: Message-ID: On Mon, Sep 8, 2008 at 21:02, Steven D'Aprano wrote: > I'm guessing that you'd probably have more success asking on ally mailing lists I'm on a couple of a11y mailing lists. My experience with them has been, "disappointing". > Have you checked out this? http://live.gnome.org/Orca Not cross platform. :( I want to use python, precisely because it is cross-platform. (If it was Windows only, Net 3.0 has most, if not all of the needed libraries.) (I could try rewriting Orca in python, and from that construct the required python libraries.) xan jonathon From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 06:48:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 12:48:53 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: References: Message-ID: <48dcbe10$0$2329$426a34cc@news.free.fr> Wojtek Walczak a ?crit : > On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote: > >> I have a BIIIIIG problem with the next query: >> >> cursor.execute(""" >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """,( eid_list)) > ^ > It should rather be '%'. Please avoid such clueless advices and read the doc of the python db-api. From gh at ghaering.de Mon Sep 29 03:53:01 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 29 Sep 2008 09:53:01 +0200 Subject: Cannot install pysqlite on Cygwin In-Reply-To: References: Message-ID: Tilman Kispersky wrote: > I am trying to install sqlite for use with python on cygwin. I have > installed the sqlite packages from cygwin (that is libsqlite3-devel > and libsqlite3_0). When attempting to easy_install pysqlite I get: > [...] > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function > `pysqlite_enable_load_extension': > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ > pysqlite-2.5.0/src/connection.c:922: undefined reference to > `_sqlite3_enable_load_extension' [...] It might be that Cygwin's SQLite doesn't support loading extensions. Either: Rebuild SQLite from source on Cygwin and be sure to include --enable-load-extension when calling ./configure. Or hack the pysqlite sources and remove these lines in src/connection.c: #if SQLITE_VERSION_NUMBER >= 3003008 #define HAVE_LOAD_EXTENSION #endif I'm very interested how you can fix the problem. -- Gerhar From gandalf at shopzeus.com Thu Sep 4 11:52:38 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 04 Sep 2008 17:52:38 +0200 Subject: Function decorators In-Reply-To: <1220542457.48bffff905ca9@www.inbox.lv> References: <1220542457.48bffff905ca9@www.inbox.lv> Message-ID: <48C00446.7050407@shopzeus.com> Aigars Aigars wrote: > Good day all, > > I am learning Python and came up to decorators. > > The question is: Why does function FoodList return value None? > > The code in attachment. > > > Thank you, > Aigars > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list First of all, you should always inherit from "object" whenever it is possible. Then the answer: you did not return the result. Instead of self.func(*args, **kwargs) use this: return self.func(*args, **kwargs) Corrected example attached. Best, Laszlo -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 505 bytes Desc: not available URL: From riquito at gmail.com Thu Sep 18 09:31:08 2008 From: riquito at gmail.com (Riccardo Galli) Date: Thu, 18 Sep 2008 06:31:08 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: Message-ID: <79a864ab-475a-42d5-8fa0-a711219ffdef@59g2000hsb.googlegroups.com> On 17 Set, 03:29, Todd Whiteman wrote: > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming language. > > The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX > is possible with a few deviations, I have tried to cover these > deviations where applicable). > > Feedback is welcome. > > Cheers, > Todd well, it just works. Now let's see how :-) Nice job, Riccardo p.s. I'm on a Gentoo Linux 64 bit, no problems at all From tino at wildenhain.de Thu Sep 18 11:53:38 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 18 Sep 2008 17:53:38 +0200 Subject: improving a huge double-for cycle In-Reply-To: <48D27755.8060208@wildenhain.de> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D27755.8060208@wildenhain.de> Message-ID: <48D27982.90503@wildenhain.de> Tino Wildenhain wrote: > Hi, > > Alexzive wrote: >> Hello there :) , >> >> I am a python newbie and need to run following code for a task in an >> external simulation programm called "Abaqus" which makes use of python >> to access the mesh (ensamble of nodes with xy coordinates) of a >> certain geometrical model. >> >> [IN is the starting input containing the nodes to be check, there are >> some double nodes with the same x and y coordinates which need to be >> removed. SN is the output containing such double nodes] >> >> Code: Select all >> for i in range(len(IN)): #scan all elements of the list IN >> for j in range(len(IN)): >> if i <> j: >> if IN[i].coordinates[0] == IN[j].coordinates[0]: >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> SN.append(IN[i].label) >> > > data=dict() > for item in IN: # (what a name! ;) > data.setdefault(item.coordinates,[]).append(item) > # provided coordinates is a tuple > > dupes=[items for items in data.values() if len(items)>1] > > should give you a resulting list of lists of elements in IN > which occur more then once per coordinates. > You can then decide which ones to remove or whatever. > > If you want to have the output only containing nodes to remove, > the following would work: > > dupes=[] > for items in data.values(): > dupes.extend(items[1:]) > I did a small test - I don't know if it reflects the actual problem good enough but it seems it all runs below 1 sec each so this would be very fast compared to 15h: >>> import random >>> class Node(object): ... def __init__(self,x,y): ... self.coordinates=(x,y) >>> IN=[Node(random.randint(0,100),random.randint(0,100)) for i in xrange(100000)] >>> data=dict() >>> for item in IN: data.setdefault(item.coordinates,[]).append(item) ... >>> dupes=[items for items in data.values() if len(items)>1] >>> len(dupes) 10190 >>> Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From rocksportrocker at googlemail.com Wed Sep 3 07:39:02 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Wed, 3 Sep 2008 04:39:02 -0700 (PDT) Subject: installing matplotlib with numpy and scipy for Python in Cygwin References: Message-ID: On 3 Sep., 11:42, "chapagainanish" wrote: > Hi!! > I'm having installation problem for installing numpy and scipy in > Cygwin for Python, and am obstruct in madway for project, i followed > scipy.org guidelines but there's few error thrown as > ? ? ? ? failed..with exit status 1 > > please if someone has installed these module help me > thank's and regard's > Anish http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html may help you. Do you really want a cygwin based installation ? You could download enthoughts python edition which includes lots of math stuff. Greetings, Uwe From celephicus at gmail.com Mon Sep 8 18:32:29 2008 From: celephicus at gmail.com (Tom Harris) Date: Tue, 9 Sep 2008 08:32:29 +1000 Subject: Numeric literal syntax In-Reply-To: References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: On Thu, Sep 4, 2008 at 10:22 AM, Alexander Schmolck wrote: > > It's amazing that after over half a century of computing we still can't denote > numbers with more than 4 digits readably in the vast majority of contexts. > I agree. So did Forth's early designers. That is why Forth's number parser considers a word that starts with a number and has embedded punctuation to be a 32 bit integer, and simply ignores the punctuation. I haven't used Forth in years, but it seems a neat solution to the problem of decoding a long string of numbers: let the user put in whatever they want, the parser ignores it. I usually used a comma (with no surrounding whitespace of course), but it was your choice. You could also do this in whatever base you were working in, so you could punctuate a 32 bit hex number to correspond to the bit fields inside it. Of course not applicable to Python. -- Tom Harris From tjreedy at udel.edu Tue Sep 2 17:35:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 02 Sep 2008 17:35:20 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> Message-ID: Gabriel Genellina wrote: > Classes represent "things", and class names should be nouns. > Functions represent "actions", and their names should be verbs. popen > is a good name for a function; Popen is a bad name for a class. People who don't like Popen should have made this argument when subprocess was being designed (for 2.4) ;-). Or at least a year ago or even 6 month ago when API changes for 3.0 were considered. Part of the reason for the name is that .Popen completely replaces the popen2, popen3, and popen4 functions, and others (yes, functions, not classes), now gone (3.0) and either replaces or supplement os.popen itself. I would not have liked subprocess.Subprocess. Perhaps Proc would have been okay. PipedProcess is too long. .... From prologic at shortcircuit.net.au Sun Sep 21 18:26:57 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 08:26:57 +1000 Subject: how can i check whether a variable is iterable in my code? In-Reply-To: References: Message-ID: satoru, I should point out that the normal approach is to just try whatever it is that you're doing, and let it fail where it fails. For example: def processSeq(x): for i in x: print i processSeq([1, 2, 3]) processSeq("foobar") processSeq(5) <-- This will fail. cheers James On Sat, Sep 20, 2008 at 7:28 PM, satoru wrote: > hi, all > i want to check if a variable is iterable like a list, how can i > implement this? > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From dudeja.rajat at gmail.com Tue Sep 30 06:57:49 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 30 Sep 2008 11:57:49 +0100 Subject: Tix Combo box problem - remains in editable mode only Message-ID: Hi I'm facing a problem with the tix combo box in a way that my combo box is always in an editable mode after I have cleared subwidgets Entry and Listbox from it. My setup is like this : CheckButton1 : If this is unset, the combo box should get disabled, the entries in it should get cleared ( entries are listbox and entry subwidgets) which in my case they get cleared. When this check box is set again, the combo box should get enabled, with no entries in listbox and entry subwidgets ( which are reallly cleared in my case.) But the combox box having being enabled is in editable mode despite of setting it to un-editable mode. The code is as follows: #Combo Box self.cbAnalysisLibVersion = Tix.ComboBox(self.frame1, \ dropdown = True, \ command=self.__cllbkAnalysisLibVer, \ editable=0, \ variable=verSelection, options='listbox.height 8\ listbox.width 25 \ entry.width 30 \ entry.anchor w \ entry.padx 30', \ history = False) #Check Button box self.chBtResultsComparison = Checkbutton(self.frame2, \ text = "Results Comparison", \ variable = varResultsComparison, \ command = self.__cllbkResultsComparison) def __cllbkResultsComparison(self, Event = None): subLB = self.cbAnalysisLibVersion.subwidget("listbox") subEntry = self.cbAnalysisLibVersion.subwidget("entry") if varResultsComparison.get() != 1: #Disable Tolerance Text Box self.txtTolerance.delete(1.0, END) self.txtTolerance.config(state = DISABLED, \ bg = "grey") #Delete all entries (entry & subwidget's entries) #in Reference Analysis Results Version Combo Box #and disable this combo box. #First Delete the Listbox sub-widget entries subLB.delete(0, END) subLB.config(state = DISABLED) #Then delete Entry sub-widget entries #subEntry = self.cbAnalysisLibVersion.subwidget("entry") subEntry.config(state = NORMAL) subEntry.delete(0, END) subEntry.config(state = DISABLED) self.cbAnalysisLibVersion.config(state = DISABLED) #Diable Result Comparison Button self.btViewComparisonResults.config(state = DISABLED) else: #Check box is ticked #Enable the Tolerance text box self.txtTolerance.config(state = NORMAL, \ bg = "white") #Enable the Reference Analysis Combo box #self.cbAnalysisLibVersion.config(state = NORMAL, editable=0) self.cbAnalysisLibVersion.configure(state = NORMAL, editable = 0) subLB.config(state = NORMAL) subEntry.config(state = NORMAL) self.btViewComparisonResults.config(state = NORMAL) Please suggest what is that I am missing Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Sun Sep 21 11:27:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 17:27:11 +0200 Subject: Why are "broken iterators" broken? In-Reply-To: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > According to the Python docs, once an iterator raises StopIteration, it > should continue to raise StopIteration forever. Iterators that fail to > behave in this fashion are deemed to be "broken": > > http://docs.python.org/lib/typeiter.html > > I don't understand the reasoning behind this. As I understand it, an > iterator is something like a stream. There's no constraint that once a > stream is empty it must remain empty forever. it's a design guideline, not an absolute rule. but I disagree that an iterator is "something like a stream". it's rather "something like a pointer or an index", that is, an object that helps you iterate over all members in a collection. From news1234 at free.fr Sat Sep 13 11:34:55 2008 From: news1234 at free.fr (nntpman68) Date: Sat, 13 Sep 2008 17:34:55 +0200 Subject: Code example that will make a Skype connection? In-Reply-To: References: Message-ID: <48cbdd9d$0$1895$426a34cc@news.free.fr> Hi, Just some thoughts / now answer :-( The solution might vary on the platform / OS. Would it be acceptable for you to control for example firefox from python and firefox would control skype via the skype plugin. (should exist for multiple platforms) Do you search a native python solution or would you accept, that some C-code had to be compiled. bye N Al Dykes wrote: > Can some post a Python code fragment that will to make a PC with Skpye > installed to make a Skype call, given a valid phone # string. > > I'm not asking for code that handles the audio once the connection is > made. > > > > > > From drkjam at gmail.com Sat Sep 13 09:13:00 2008 From: drkjam at gmail.com (David Moss) Date: Sat, 13 Sep 2008 06:13:00 -0700 (PDT) Subject: A service for testing Python code on multiple platforms and versions Message-ID: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> Hopefully a service like this already exists and I just haven't found it yet. If not it could be an idea for some kind soul(s) to pick up and run with ;-) As someone who writes and releases Python modules for the community, I find it difficult to have a decent level of confidence in the efficacy of my code on platforms and Python versions other than those that I own or use regularly. My documentation states that I support Python 2.3 or higher. This ends up being more of a statement of good intentions than a one of fact. A case in point. A bug (in Python), that I believed to have been killed off after Python 2.2, resurfaced in a 2.4.x release of Python on PowerPC recently. As I don't own any PowerPC kit, it was very difficult to a) investigate the bug and b) create an effective fix for it in a timely fashion. Fortunately I'd come across it before so the fix was easy but it might not have been. While I realise one's code can never be perfect, you can cover for these sorts of eventualities fairly easily by running your software and unit tests under different environments. You'd also like to be able to do this on a continual basis rather than just once or twice. If this was done with some kind of automated testing and reporting so much the better. Bigger projects that take code quality seriously probably already have this sort of thing in place for their own purposes, but for smaller ones it just isn't possible. Wouldn't it be great to have a service/setup out there available for Python developers to access that covered a fairly broad base of possible Python installations for the purpose of improve overall code quality? Am I the only one that would find something like this useful? Dave M. From m_palmer45 at yahoo.ca Fri Sep 19 10:21:42 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 19 Sep 2008 07:21:42 -0700 (PDT) Subject: generator exceptions References: <826a734c-968c-4d68-9ed1-c2688340ebc5@a3g2000prm.googlegroups.com> Message-ID: <42d646ff-51b1-43b7-8002-6b628e4b43bf@d77g2000hsb.googlegroups.com> On Sep 19, 9:40 am, Alexandru Mosoi wrote: > i have a generator that raises an exception when calling next(), > however if I try to catch the exception and print the traceback i get > only the line where next() was called > > while True: > try: > iterator.next() > except StopIteration: > break > except Exception, e: > traceback.print_exc() > > how do I get the traceback starting from where exception was raised in > first place? What happens if you simply remove the 'except Exception' clause? It should print the entire traceback by default. From Scott.Daniels at Acm.Org Tue Sep 16 22:14:54 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 16 Sep 2008 19:14:54 -0700 Subject: What is "finally:" for? In-Reply-To: <502e16a8-e20d-4795-a495-ce1f61fd8c15@m44g2000hsc.googlegroups.com> References: <502e16a8-e20d-4795-a495-ce1f61fd8c15@m44g2000hsc.googlegroups.com> Message-ID: Paul McGuire wrote: ... > try: > open database > do database stuff > except DatabaseException, de: > log exception > throw > finally: > close database > > Or > > try: > transaction = new database transaction > do database stuff > do more database stuff > commit transaction > transaction = None > except DatabaseException, de: > log exception > throw > finally: > if transaction: > rollback transaction Generally it is a good idea to try the advice you are about to offer. "raise" is the Python way to do the Lisp/Scheme "throw" which will likely produce another error, but not the one you want. --Scott David Daniels Scott.Daniels at Acm.Org From sjmachin at lexicon.net Fri Sep 12 16:01:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Sep 2008 13:01:01 -0700 (PDT) Subject: Matching horizontal white space References: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> Message-ID: On Sep 13, 12:52?am, Fredrik Lundh wrote: > Magnus.Morab... at gmail.com wrote: > > multipleSpaces = re.compile(u'\\h+') > > > importantTextString = '\n ?\n ?\n \t\t ?' > > importantTextString = multipleSpaces.sub("M", importantTextString) > > what's "\\h" supposed to mean? Match *h*orizontal whitespace, I guess ... looks like the maintainer of the re equivalent in some other language has far too much spare time :-) From pavlovevidence at gmail.com Sat Sep 20 06:45:24 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 20 Sep 2008 03:45:24 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <40a8c7a8-027f-4a3d-bb78-71d6299429cb@i76g2000hsf.googlegroups.com> On Sep 20, 2:23 am, candide wrote: > Excerpt quoted fromhttp://www.astro.ufl.edu/~warner/prog/python.html: > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > Thanks for any comment. Python is what it is, whatever you call it. That page has a whole list of features (we'll give the author the benefit of the doubt and assume they're accurate and fairly up-to-date). Those features (more or less) define what Python is, not trendy computer science catch words. Carl Banks From circularfunc at yahoo.se Tue Sep 2 14:02:23 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 2 Sep 2008 11:02:23 -0700 (PDT) Subject: Large amount of files to parse/organize, tips on algorithm? References: <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> Message-ID: <6dc5719f-a65b-4194-b09c-b9bbb55ee788@e53g2000hsa.googlegroups.com> over 17000 files... netflixprize. From karaboomtown at gmail.com Thu Sep 4 00:26:20 2008 From: karaboomtown at gmail.com (karaboomtown at gmail.com) Date: Wed, 3 Sep 2008 21:26:20 -0700 (PDT) Subject: Download movies Message-ID: <9178ceda-14f4-44aa-9980-21fda6bbafb4@p10g2000prf.googlegroups.com> Download movies http://gpirate.com http://www.gpirate.com/search?hl=en&q=naruto+shippuden&btnG=Search From a.schmolck at gmail.com Wed Sep 3 20:22:22 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Thu, 04 Sep 2008 01:22:22 +0100 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: Ben Finney writes: > bearophileHUGS at lycos.com writes: > >> For Python 2.7/3.1 I'd now like to write a PEP regarding the >> underscores into the number literals, like: 0b_0101_1111, 268_435_456 >> etc. > > +1 on such a capability. > > -1 on underscore as the separator. > > When you proposed this last year, the counter-proposal was made > > to instead use white space for the separator, exactly as one can now > do with string literals. > > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > literals. It seems to me that the right choice for thousands seperator is the apostrophe. It doesn't suffer from brittleness and editing problems as whitespace does (e.g. consider filling and auto-line breaking). It is already used in some locales for this function but never for the decimal point (so no ambiguity, unlike '.' and ','). It also reads well, unlike the underscore which is visually obstrusive and ugly (compare 123'456'890 to 123_456_789). Having said that, I'd still have 123_456_789 over 123456789 any day. It's amazing that after over half a century of computing we still can't denote numbers with more than 4 digits readably in the vast majority of contexts. 'as From lists at cheimes.de Mon Sep 22 16:32:04 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Sep 2008 22:32:04 +0200 Subject: Problems running on hp dual core processor In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > Interesting... The only win32ui* on my machine (running v2.4) is a > win32ui.pyd (D, not C) and it is part of the PythonWin IDE obtained as > part of the ActiveState installer for windows. > > Oh, and /how much RAM/? ".099g" sounds rather small; my PDA has > ".5G" of RAM and my desktop machine has 2.0G... A .pyd file is a Python dynamic library file. It's a dll with a different extension and a Python specific entry point. Dynamic libraries are OS and CPU architecture dependent. It might be possible that the computer has an incompatible CPU or a 64bit OS. Christian From mathieu.prevot at gmail.com Sat Sep 6 13:18:15 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Sat, 6 Sep 2008 19:18:15 +0200 Subject: Failure in building ctypes with intel icc Message-ID: <3e473cc60809061018k19dbd3a2n4b0f9dabedbe5b4@mail.gmail.com> Hi, I got this error in compilation, and I don't know how to solve it: *** WARNING: renaming "_ctypes" since importing it failed: dlopen(build/lib.macosx-10.3-i386-2.6/_ctypes.so, 2): Symbol not found: ___builtin_dwarf_cfa Referenced from: /Users/mathieuprevot/svn/python/build/lib.macosx-10.3-i386-2.6/_ctypes.so Expected in: dynamic lookup Any hints ? thanks, Mathieu From robert.kern at gmail.com Tue Sep 16 22:05:21 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 16 Sep 2008 21:05:21 -0500 Subject: Python Linear Programming on Ubuntu In-Reply-To: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> Message-ID: Fett wrote: > I am trying to find a wrapper to do linear programming within python. > I am using an ubuntu machine and I have apt-get'd lp_solve, which > works just fine. If someone knows of a wrapper that will work with > that that'd be great. > > I also heard that scipy has a wrapper, however, I can't find any > documentation on it, nor can I seem to find it with dir(). If anyone > knows where there is good documentation on this I would love to use > that (the more native to python the better imo). No, scipy doesn't have such a wrapper, sorry. > I have tried many things, including http://lpsolve.sourceforge.net/5.5/Python.htm, > openopt, and cvxopt. I can't seem to find any with enough > documentation to get me off the ground. Some I can't compile, some I > can't even find out how to compile. > > If anyone knows of an LP package (preferably with IP as well, like > lp_solve has), that interfaces well with python and has enough > documentation to get a dependency newb like myself off the ground that > would be great. PuLP should be fairly easy to build against GLPK or COIN (provided you have them installed; I'm pretty sure Ubuntu has a GLPK package but I'm not sure about COIN), but you will have to edit the Makefile for your system: http://www.jeannot.org/~js/code/index.en.html#PuLP You can ask on scipy-users about OpenOpt, and hopefully Dmitrey will be able to help you. If you want to get cvxopt or the Python wrappers in lp_solve itself working, I suggest asking their mailing lists. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Mon Sep 8 19:22:58 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Sep 2008 18:22:58 -0500 Subject: lacking follow-through In-Reply-To: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: Eric Wertman wrote: >> Perhaps the wrong idea of what the group is. I would have thought >> that >> if one had a sufficiently developed idea and wanted to have it / >> formally/ >> rejected, rather than merely sniped at, then writting a PEP would be >> more >> apposite than posting to c.l.py. >> >> It's fine to post your not sufficiently developed ideas here merely >> to >> have them discussed. But I don't know what makes you feel that you, >> or >> your ideas, are /entitled/ to any response at all, much less >> "follow-through." > > To expand on this a little bit, I've been subscribed to this group > for a couple of months, but there seems to be a bit more gray area > between what would go to a 'python-dev' group and a 'python-user' > group. Long debates about language features and abstract ideas would > appeal to the former, but not the latter. Certainly I fall into the > user category.. I'm pretty happy with python, and generally just > adjust to it's design and features, rather than spend lots of time on > whether they are 'right' or could be 'better'. /shrug Actually, python-dev is for the concrete development of Python. Releases, bugs, and occasionally design discussions for relevant features. Long debates about potential features and abstract ideas belong either here or python-ideas. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Tue Sep 9 23:03:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Sep 2008 20:03:48 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> Message-ID: <3d6488c1-d57c-46be-b404-9c79bd49dbdf@y21g2000hsf.googlegroups.com> On Sep 9, 5:59?pm, castironpi wrote: > I will try my idea again. ?I want to talk to people about a > module I want to write and I will take the time to explain it. >?I think it's a "cool idea" that a lot of people, forgiving the > slang, could benefit from. ? > > (snipped) > > A pure Python alloc-free implementation based on the GNU PAVL > tree library is on Google Code. ?It is only in proof-of-concept > form and not commented, but does contain a first-pass test > suite. ?See: > ? ?http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk So at best (i.e. if it actually makes any sense; I didn't read it), this is an ANNouncement of a pre-alpha piece of code. ANN posts rarely attract replies, even when they are about production/stable software. Thankfully, most people don't expect (let alone "require") readers to share their interest or enthusiasm by replying to the ANN. Given your past semi-coherent and incoherent posts, expecting people to jump on such a thread is a rather tall order. George From deets at nospam.web.de Wed Sep 24 18:58:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 00:58:33 +0200 Subject: Folder Actions on Mac OSX Leopard? In-Reply-To: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> References: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> Message-ID: <6jvv0pF5cvjlU1@mid.uni-berlin.de> squishywaffle at gmail.com schrieb: > Greetings, > > I've been trying to figure out if it's possible to attach a Python > script to an action via Mac OSX Leopard's File Actions system. I'm > wanting to call a Python script every time a file is added to the > monitored folder. Just adding a .py file doesn't seem to do anything > at all, and I can't find any log output anywhere to see what's going > on. > > I'm more just looking to see if this is or is not possible. I'm not > interested in other solutions, as I already have them lined up in case > this is a no-go, but I'd really love to be able to do it this way if > anyone has any experience. Googling around revealed pretty much > nothing. You mean this? http://developer.apple.com/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/chapter_2_section_1.html *I* would use ctypes to access Carbon Core. But then that's just me - I'm sure you find a better way... Diez From mensanator at aol.com Mon Sep 29 19:08:28 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 29 Sep 2008 16:08:28 -0700 (PDT) Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: On Sep 29, 5:04?pm, Ivan Reborin wrote: > Hello everyone, > > I was wondering if anyone here has a moment of time to help me with 2 > things that have been bugging me. > > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? > > 2. I've read the help on the next one but I just find it difficult > understanding it. > I have; > a=2.000001 > b=123456.789 > c=1234.0001 > > How do you print them with the same number of decimals ? > (eg. 2.000, 123456.789, 1234.000) >>> print '%0.3f' % 2.000001 2.000 >>> print '%0.3f' % 123456.789 123456.789 >>> print '%0.3f' % 1234.0001 1234.000 > and how do you print them with the same number of significant > decimals? > (eg. 2.000001, 123456.7, 1234.000 - always 8 decimals) ? Your examples are 7 decimals (and you're not rounding). Here's what 8 looks like (note that it's %0.7e because there is always one digit to the left of the decimal point.) >>> print '%0.7e' % 2.000001 2.0000010e+00 >>> print '%0.7e' % 123456.789 1.2345679e+05 >>> print '%0.7e' % 1234.0001 1.2340001e+03 If you actually meant 7, then use %0.6e: >>> print '%0.6e' % 2.000001 2.000001e+00 >>> print '%0.6e' % 123456.789 1.234568e+05 >>> print '%0.6e' % 1234.0001 1.234000e+03 > > Is something like this possible (built-in) in python ? You can do more with gmpy. > > Really grateful for all the help and time you can spare. > > -- > Ivan From bdesth.quelquechose at free.quelquepart.fr Fri Sep 26 16:03:39 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 22:03:39 +0200 Subject: is decorator the right thing to use? In-Reply-To: References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> Message-ID: <48dd5c06$0$26425$426a74cc@news.free.fr> Dmitry S. Makovey a ?crit : > Paul McGuire wrote: >>> see, in your code you're assuming that there's only 1 property ( 'b' ) >>> inside of A that needs proxying. In reality I have several. > >> No, really, Diez has posted the canonical Proxy form in Python, using >> __getattr__ on the proxy, and then redirecting to the contained >> delegate object. This code does *not* assume that only one property >> ('b'? where did that come from?) is being redirected - __getattr__ >> will intercept all attribute lookups and redirect them to the >> delegate. >> >> If you need to get fancier and support this single-proxy-to-multiple- >> delegates form, then yes, you will need some kind of map that says >> which method should delegate to which object. Or, if it is just a >> matter of precedence (try A, then try B, then...), then use hasattr to >> see if the first delegate has the given attribute, and if not, move on >> to the next. > > that is what I didn't like about it - I have to iterate over delegates when > I can build direct mapping once and for all and tie it to class > definition ;) Hem... I'm afraid you don't really take Python's dynamic nature into account here. Do you know that even the __class__ attribute of an instance can be rebound at runtime ? What about 'once and for all' then ? But anyway: >> Your original question was "is decorator the right thing to use?" For >> this application, the answer is "no". > > yeah. seems that way. in the other fork of this thread you'll find my > conclusion which agrees with that :) > >> It sounds like you are trying >> to force this particular to solution to your problem, but you are >> probably better off giving __getattr__ intercepting another look. > > __getattr__ implies constant lookups and checks (for filtering purposes) Unless you cache the lookups results... > - I > want to do them once, attach generated methods as native methods What is a "native method" ? You might not be aware of the fact that method objects are usually built anew from functions on each method call... > and be > done with it. That is why I do not like __getattr__ in this particular > case. There's indeed an additional penalty using __getattr__, which is that it's only called as a last resort. Now remember that premature optimization is the root of evil... Depending on effective use (ie : how often a same 'proxied' method is called on a given Proxy instance, on average), using __getattr__ to retrieve the appropriate bound method on the delegate then adding it to the proxy instance *as an instance attribute* might be a way better (and simpler) optimization. From stava at telcotec.se Sat Sep 27 04:49:09 2008 From: stava at telcotec.se (Lars Stavholm) Date: Sat, 27 Sep 2008 10:49:09 +0200 Subject: python for *nix system admins In-Reply-To: References: <48DDE92D.6090405@telcotec.se> Message-ID: <48DDF385.3010101@telcotec.se> km wrote: > import os Thanks, but I'm aware of the standard libraries like os, sys, commands, and whatnot. I'm looking for a non-standard library that acts like a wrapper for the unix commands. I have seen it, I just can't find it again. /L > On Sat, Sep 27, 2008 at 1:35 PM, Lars Stavholm > wrote: > > Hi All, > > I'm new to this list and hoping that this is not off-topic. > If it is, please point me in the right direction. > > I seem to recollect a python module or library for *nix sysadmins, > but I can't for the life of me find it again. > > The module (or library) somehow added unix command capabilities > to the python language. It seemed like a lesser known, perhaps new, > python library or module. > > Any input or ideas appreciated > /Lars Stavholm > -- > http://mail.python.org/mailman/listinfo/python-list > > From digitig at gmail.com Sat Sep 27 19:55:45 2008 From: digitig at gmail.com (Tim Rowe) Date: Sun, 28 Sep 2008 00:55:45 +0100 Subject: Not fully OO ? In-Reply-To: <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> Message-ID: 2008/9/27 Aaron Castironpi Brady : > No way. It's *zero* instead of one, if so, because the only thing C# > has is a bunch of handcuffs and implicit 'self'. You have a line > like: You don't follow what I said, and from your tone I get the feeling you don't *want* to follow what I'm saying, not because I'm criticising Python (I'm not), but because I'm guilty of the heresy of suggesting that it's not actually simultaneoulsy optimised for every possible use. My point is that there are zero parameters as far as I am concerned because I don't actually touch most of the GUI code. There could actually be hundreds of parameters, for all I care. They're not my concern. Most of the time I like that -- the tools are doing my work for me. -- Tim Rowe From deets at nospam.web.de Wed Sep 10 07:58:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 13:58:38 +0200 Subject: I want to use a C++ library from Python References: <6ipd53FrptpiU1@mid.uni-berlin.de> <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> Message-ID: <6ipr40Fr7kr2U1@mid.uni-berlin.de> kaer wrote: > On 10 sep, 10:00, "Diez B. Roggisch" wrote: >> Anders Eriksson schrieb: >> >> > Hello, >> >> > I have a C++ library compiled as Windows DLL's. It consists of 32 .h >> > and 1 .lib and 1 .dll files. I don't have the source code. >> >> > How can I create a Python module from these files? >> >> Did you bother googling? >> >> http://www.google.de/search?q=python+c%2B%2B&ie=utf-8&oe=utf-8 >> >> Diez > > You may want google "python dll" as well. Good luck. Which actually isn't really helpful, as a DLL itself says nothing about what language was used to create it - and sending the OP to e.g. ctypes makes no sense at all in the face of C++. Whereas the first link for "python c++" is Boost::Python, a C++-wrapper to make C++-code accessible from Python. Diez From python at rcn.com Tue Sep 16 12:19:07 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 16 Sep 2008 09:19:07 -0700 (PDT) Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> <87fxo3bxlu.fsf@mulj.homelinux.net> Message-ID: On Sep 13, 9:27?pm, Hrvoje Niksic wrote: > Note that, despite appearances, it's not as built-in as one might > wish. ?sum(seq) is still completely generic and works on all > number-like objects (in fact on all objects that define an __add__ > operation except strings, which are explicitly forbidden). ?This means > that it can't just go ahead and execute a C addition, it must properly > call PyNumber_Add (the C API call equivalent to Python's "+" > operator), which will then inspect the objects and invoke the > appropriate implementation of addition. The time machine strikes again! Try using Py2.6. The built-in sum() function is much smarter and faster. It does in fact use C addition. Raymond From steve at REMOVE-THIS-cybersource.com.au Tue Sep 30 19:38:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 23:38:19 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: <00f2b214$0$20617$c3e8da3@news.astraweb.com> On Tue, 30 Sep 2008 10:57:19 -0500, Grant Edwards wrote: >>> How would the python equivalent go ? > > You would drag yourself out of the 1960s, install numpy, and then do > something like this: I think that was thoughtlessly rude to somebody who is asking a perfectly reasonable question. -- Steven From grante at visi.com Wed Sep 10 13:51:28 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 12:51:28 -0500 Subject: Gateway to python-list is generating bounce messages. Message-ID: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> Could whoever is responsible for the gateway that is grabbing my postings off of Usenet and e-mailing them out please fix the headers in the mail messages so that I don't get the bounce messages? While you're at it, might as well fix it for everybody else too. ;) Its a bit rude to send out mass e-mail messages with headers faked up so that the bounce messages go to somebody else. -- Grant Edwards grante Yow! As President I have at to go vacuum my coin visi.com collection! From fredrik at pythonware.com Tue Sep 2 13:22:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Sep 2008 19:22:32 +0200 Subject: What is module initialization? In-Reply-To: References: <48bd4799$0$17215$426a74cc@news.free.fr> Message-ID: dudeja.rajat at gmail.com wrote: >> # myglobals.py: >> answer = 42 >> >> # question.py >> import myglobals >> myglobals.answer = "WTF ?" >> > > But if I do :- > #question.py > from myglobals import * > myglobals.answer = "WTF ?" > > will this work? with the above definition of myglobals, no. "from myglobals import" doesn't add the module object to the importing module's namespace. have you read: http://effbot.org/zone/import-confusion.htm ? From dear.jay.logan at gmail.com Sun Sep 21 23:05:06 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sun, 21 Sep 2008 20:05:06 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 Message-ID: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Hello, I have 2 questions. Say I have this class: class Player(object): def __init__(self, fname, lname, score): self.score = score self.fname = fname self.lname = lname def __cmp__(self, other): return (-cmp(self.score, other.score) or cmp(self.lname, other.lname) or cmp(self.fname, other.fname)) def __repr__(self): return 'Player(fname={0.fname}, lname={0.lname}, score={0.score})'.format(self) def __eq__(self, others): if isinstance(other, Player): return (self.score == other.score and self.lname == other.lname and self.fname == other.fname) return False def __ne__(self, others): return not self.__eq__(others) fnames = ['Julie', 'Ben', 'Jason', 'David'] lnames = ['Parks', 'Smith'] scores = [100, 95, 95, 130, 58, 74] import itertools as it score_iter = it.cycle(scores) P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in lnames] cmp(P[0], P[1]) # returns -1 sorted(P) # throws TypeError: unorderable types Player() < Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. Is this a bug in Python 3.0rc1, or am I missing something? Secondly, say that we suddenly need another sorting order, where we want to sort by decreasing score and then by DECREASING last name (instead of increasing last name, defined above). Now that the comparison function argument is taken away from the sorted builtin, how do we accomplish this with the "key" parameter? Thank you From hniksic at xemacs.org Sat Sep 27 11:16:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 27 Sep 2008 17:16:01 +0200 Subject: Using the 'with' statement with cStringIO objects References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> <1222522300.659080@athprx04> Message-ID: <87zllt7h72.fsf@mulj.homelinux.net> George Boutsioukis writes: > Neither, just not implemented. Only classes with __enter__ and > __exit__ methods(ie context manager types) can be used in with > statements. And, correct me if I'm wrong, I think it's pointless for > a StringIO object to have those. It's definitely superfluous, but it should still be provided, for the same reason a "close" method is provided, to allow StringIO objects to be treated like other file-like objects. For example, code that does the following: with obj.open_file(...) as f: ... shouldn't have to care if obj.open_file returns a built-in file instance, or a StringIO instance. As the above code becomes more popular, __enter__ and __exit__ are beginning to be part of the file interface (in the duck-typing sense) and should be implemented. Until then, the the contextlib.closing context manager can be used instead: with contextlib.closing(obj.open_file(...)) as f: ... From enleverlesX.XmcX at XmclaveauX.com Sun Sep 21 04:32:12 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sun, 21 Sep 2008 10:32:12 +0200 Subject: Not fully OO ? In-Reply-To: <48d4c11b$0$22877$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <48d608b7$0$957$ba4acef3@news.orange.fr> Bonjour ! AMHA, ceux qui ont ?crit ce texte ont une mauvaise id?e de ce que sont les variables en Python. Ils ont sans doute trop en t?te les notions des variables en C ou en Basic, et ne se sont pas pench?s sur les sp?cificit?s de Python. @-salutations -- Michel Claveau From george.sakkis at gmail.com Fri Sep 26 22:29:43 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 26 Sep 2008 19:29:43 -0700 (PDT) Subject: getting global variables from dictionary References: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> Message-ID: On Sep 26, 10:01?pm, icarus wrote: > global_vars.py has the global variables > set_var.py changes one of the values on the global variables (don't > close it or terminate) > get_var.py retrieves the recently value changed (triggered right after > set_var.py above) > > Problem: get_var.py retrieves the old value, the built-in one but not > the recently changed value in set_var.py. > > What am I doing wrong? > > ----global_vars.py--- > #!/usr/bin/python > > class Variables : > ? ? ? ? def __init__(self) : > ? ? ? ? ? ? ? ? self.var_dict = {"username": "original username"} > > ---set_var.py --- > #!/usr/bin/python > > import time > import global_vars > > global_vars.Variables().var_dict["username"] = "new username" > time.sleep(10) ? #give enough time to trigger get_var.py > > ---get_var.py --- > #!/usr/bin/python > import global_vars > print global_vars.Variables().var_dict.get("username") First off, you don't import the set_var module anywhere; how do you expect the value to change? Second, every time you do "global_vars.Variables()" you create a brand new Variables() instance, initialized with the original var_dict. The Variables() instance you create at set_var.py is discarded in the very next line. Third, I have no idea why you put the "time.sleep(10)" there. By the way, Python is not Java; you don't have to make classes for everything. A working version of your example would be: ----global_vars.py--- var_dict = {"username": "original username"} ---set_var.py --- import global_vars global_vars.var_dict["username"] = "new username" ---get_var.py --- import global_vars import set_var print global_vars.var_dict.get("username") $ python get_var.py new username HTH, George From digitig at gmail.com Fri Sep 26 19:12:16 2008 From: digitig at gmail.com (Tim Rowe) Date: Sat, 27 Sep 2008 00:12:16 +0100 Subject: Not fully OO ? In-Reply-To: <48dd5f08$0$26425$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <48dd5f08$0$26425$426a74cc@news.free.fr> Message-ID: 2008/9/26 Bruno Desthuilliers : > Not to start a troll, but from what I've seen of C# so far I do find this a > bit surprising and really suspect more of a library issue than a language > one. Care to tell more about the problem and solution ? > > (NB : I wouldn't even asked if you had mentionned say Erlang or Prolog or > OCaml - well, some mostly different language - instead of C#) IIRC it was library issues -- for one thing I still find it a lot harder to manage an MS Windows GUI under Python than I do under .NET (I've never succeeded in getting Iron Python to run properly). In one sense you could argue that that's not a language issue, and you'd be right: there's nothing in the syntax or semantics of either language that makes it so. But in another sense I'd say it is a language issue (and of course I think I'm right!) because Python aims to be platform independent, and whilst that means gains in portability it means that in return it loses the ease-of-programming of a tightly integrated platform. -- Tim Rowe From garyr at fidalgo.net Mon Sep 22 16:55:23 2008 From: garyr at fidalgo.net (garyr) Date: Mon, 22 Sep 2008 13:55:23 -0700 (PDT) Subject: Tkinter 3000 WCK Install Problem Message-ID: <0dd2b0dc-f6cb-4b70-8f35-d50446fdd901@2g2000hsn.googlegroups.com> I'm trying to install WCK. I downloaded and installed the Windows executable for my Python version. It appeared to run OK. I then downloaded the demo files but find that none run due to error: ImportError: No module named _tk3draw. I'm using ActivePython 2.3.5 on Windows XP Home. What can I do to fix this problem? From lanny at freshells.ch Sat Sep 6 14:44:04 2008 From: lanny at freshells.ch (Lanny) Date: Sat, 6 Sep 2008 11:44:04 -0700 Subject: indices question Message-ID: pretty self-explanatory, here's what I put in: while stat == 0 : pgrid#ignore, A pre-defined function print "what cell do you want?" varcc = raw_input grid[varc] = 'O' And here's what I get back: Traceback (most recent call last): File "C:\py_prog\Tic Tac Toe.py", line 27, in grid[varc] = 'O' TypeError: list indices must be integers Please don't tell me that "list indices must be integers" because I know that, Why can't I put a varible thats an integer instead? -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From rogeruclan at gmail.com Tue Sep 16 06:44:44 2008 From: rogeruclan at gmail.com (RLC) Date: Tue, 16 Sep 2008 03:44:44 -0700 (PDT) Subject: help on python SWIG C++ extension Message-ID: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> Hello I am new to python SWIG. Recently I wrote a small program trying to import collada files(using colladadom) into python so I could use python cgkit to render them. However, during the progressing, I got some problems. Every time I quit from Python, I get a segmentation fault, although the main program runs well. I suspect it is because I wrapped std::vector objects in C struct and I did not release the memory properly. Below is the code. I am working on FreeBSD 7.0, GCC 4.2.1. I will be very appreciated if you could help me. Thanks a lot. the error I have got Segmentation fault: 11 (core dumped) //////////////////////// ///Header file //////////////////////// #ifndef TDIMPORT_H #define TDIMPORT_H #include #include #include "math.h" #include "float.h" #define WORDINVALIDVALUE ULONG_MAX #define FLOATINVALIDVALUE FLT_MAX typedef unsigned long WORD; typedef struct { double x,y,z; } Vertex; extern Vertex *new_Vertex(double x, double y, double z); extern void delete_Vertex(Vertex *v); extern double Vertex_length(Vertex *v); static const Vertex UNDEFINEDVERTEX = {FLT_MAX,FLT_MAX,FLT_MAX}; typedef struct { double u,v; } UV; extern UV *new_UV(double u, double v); extern void delete_UV(UV *uv); static const UV UNDEFINEDUV = {FLT_MAX,FLT_MAX}; typedef struct { double red,green,blue,alpha; } Color; extern Color *new_Color(double red, double green, double blue, double alpha); extern void delete_Color(Color *color); static const Color BLACK = {0.0, 0.0, 0.0, 1.0}; static const Color WHITE = {1.0, 1.0, 1.0, 1.0}; typedef struct { int type; Color color; std::string texture; } Material; typedef struct { std::vector vertices; std::vector polygonNbVertices; std::vector polygonStartVertexIndex; std::vector polygonVerticesIndices; std::vector uvs; std::vector polygonNbUVs; std::vector polygonStartUVIndex; std::vector polygonUVsIndices; Material material; } PolygonMesh; extern PolygonMesh *new_PolygonMesh(); extern void delete_PolygonMesh(PolygonMesh *p); extern unsigned long PolygonMesh_countvertices(PolygonMesh *p); extern unsigned long PolygonMesh_countpolygons(PolygonMesh *p); extern void PolygonMesh_appendvertex(PolygonMesh *p, Vertex *vertex); extern Vertex PolygonMesh_getvertex(PolygonMesh *p, unsigned long vertexIndex); extern void PolygonMesh_appendpolygon(PolygonMesh *p, const std::vector& verticesIndices); extern long PolygonMesh_getpolygonverticescount(PolygonMesh *p, unsigned long polygonIndex); extern std::vector PolygonMesh_getpolygonverticesindices(PolygonMesh *p, unsigned long polygonIndex); #endif ////////////////////////// //// implementation ////////////////////////// #include "tdimport.h" Vertex *new_Vertex(double x, double y, double z) { Vertex *v; v = (Vertex *)malloc(sizeof(Vertex)); v->x = x; v->y = y; v->z = z; return v; } void delete_Vertex(Vertex *v) { free(v); } double Vertex_length(Vertex *v) { return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); } UV *new_UV(double u, double v) { UV *uv; uv = (UV *)malloc(sizeof(UV)); uv->u = u; uv->v = v; return uv; } void delete_UV(UV *uv) { free(uv); } Color *new_Color(double r, double g, double b, double a) { Color *color; color = (Color *)malloc(sizeof(Color)); color->red = r; color->green = g; color->blue = b; color->alpha = a; return color; } void delete_Color(Color *color) { free(color); } PolygonMesh *new_PolygonMesh() { PolygonMesh *p; p = (PolygonMesh *)malloc(sizeof(PolygonMesh)); p->vertices.clear(); p->polygonNbVertices.clear(); p->polygonStartVertexIndex.clear(); p->polygonVerticesIndices.clear(); p->uvs.clear(); p->polygonNbUVs.clear(); p->polygonStartUVIndex.clear(); p->polygonUVsIndices.clear(); return p; } void delete_PolygonMesh(PolygonMesh *p) { free(p); } unsigned long PolygonMesh_countvertices(PolygonMesh *p) { return (unsigned long)p->vertices.size(); } unsigned long PolygonMesh_countpolygons(PolygonMesh *p) { return (unsigned long)p->polygonNbVertices.size(); } void PolygonMesh_appendvertex(PolygonMesh *p, Vertex *vertex) { p->vertices.push_back(*vertex); } void PolygonMesh_appendpolygon(PolygonMesh *p, const std::vector& verticesIndices) { unsigned int i; for ( i = 0 ; i < verticesIndices.size() ; i++ ) p->polygonVerticesIndices.push_back(verticesIndices.at(i)); p->polygonStartVertexIndex.push_back(p- >polygonVerticesIndices.size()-verticesIndices.size()); p->polygonNbVertices.push_back(verticesIndices.size()); } Vertex PolygonMesh_getvertex(PolygonMesh *p, unsigned long vertexIndex) { if (vertexIndex < 0 || vertexIndex>=p->vertices.size() ) { return UNDEFINEDVERTEX; } else { return p->vertices.at(vertexIndex); } } long PolygonMesh_getpolygonverticescount(PolygonMesh *p, unsigned long polygonIndex) { if ((polygonIndex < 0) || (polygonIndex >= p- >polygonStartVertexIndex.size())) { return (long)-1; } else { return (long)p->polygonNbVertices.at(polygonIndex); } } std::vector PolygonMesh_getpolygonverticesindices(PolygonMesh *p, unsigned long polygonIndex) { std::vector tmp; tmp.clear(); if ((polygonIndex < 0) || (polygonIndex >= p- >polygonStartVertexIndex.size())) { return tmp; } else { unsigned long count = p->polygonNbVertices.at(polygonIndex); unsigned long start = p->polygonStartVertexIndex.at(polygonIndex); for (unsigned long i=0; ipolygonVerticesIndices.at(i+start)); return tmp; } } ///////////////////////// ////SWIG interface ///////////////////////// %module tdimport %{ #include "tdimport.h" %} %include "std_string.i" %include "std_vector.i" namespace std { %template(IntVector) vector; %template(UIVector) vector; %template(VertexVector) vector; %template(UVVector) vector; } using namespace std; typedef struct { double x,y,z; %extend { Vertex (double,double,double); ~Vertex(); double length(); } } Vertex; typedef struct { double u,v; %extend { UV (double,double); ~UV(); } } UV; typedef struct { double red,green,blue,alpha; %extend { Color (double,double,double,double); ~Color(); } } Color; %apply const std::string& {std::string* texture}; typedef struct { int type; Color color; std::string texture; } Material; typedef struct { std::vector vertices; std::vector polygonNbVertices; std::vector polygonStartVertexIndex; std::vector polygonVerticesIndices; std::vector uvs; std::vector polygonNbUVs; std::vector polygonStartUVIndex; std::vector polygonUVsIndices; Material material; %extend { PolygonMesh(); ~PolygonMesh(); unsigned long countvertices(); unsigned long countpolygons(); void appendvertex(Vertex*); Vertex getvertex (unsigned long) ; void appendpolygon(const std::vector&); long getpolygonverticescount(unsigned long); std::vector getpolygonverticesindices(unsigned long); } } PolygonMesh; ///////////////////////// ////python file ///////////////////////// #!/usr/local/bin/python import tdimport a = tdimport.PolygonMesh() a.appendvertex(tdimport.Vertex(1.0,0.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,1.0)) a.appendpolygon([1,2,3]) b = a.getpolygonverticescount(0) print b del a //////////////////////////// ///compile command //////////////////////////// swig -c++ -python tdimport.i g++ -c tdimport.cpp g++ -c tdimport_wrap.cxx -I/usr/local/include/python2.5 g++ -shared tdimport.o tdimport_wrap.o -o _tdimport.so From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 20:47:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 00:47:23 GMT Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <00e5938e$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 16:27:41 -0700, Alex Snast wrote: > Another quick question please, is the List data structure just a dynamic > array? If so how can you use static size array, linked list, AVL trees > etcetera. Before I answer your question, I should say that you can go a LONG way with just the standard Python built-in data structures list, dict and set, plus a handful of standard modules like array and collections. It's often (but not always) better to modify an algorithm to use a built-in data structure than to try to implement your own. The underlying data structure for lists is implementation specific. Only the behaviour is specified by the language. In the standard Python implementation written in C (usually known as "Python", although sometimes people explicitly describe it as CPython), lists are implemented as a fixed array of pointers. The array is periodically resized, either up or down, but only as needed. The largest consequence of that is that appending to the end of a list is much faster than inserting at the beginning of the list. Other implementations (IronPython, Jython, PyPy, CLPython...) are free to implement lists whatever way they need. If you want a static list, the simplest way is to create a list and simply not resize it. If you want to enforce that, here's a subclass to get you started: class StaticList(list): def _resize(self): raise RuntimeError("list can't be resized") extend = append = pop = insert = remove = \ __delitem__ = __delslice__ = _resize I haven't dealt with __setitem__ or __setslice__, because they're more complicated: you need to make sure the slice you're setting has the same size as the bit you're replacing, so that this is allowed: mylist[3:6] = [1, 2, 3] but not these: mylist[3:6] = [1, 2] mylist[3:6] = [1, 2, 3, 4] As for linked lists and trees, don't worry about pointers, just go ahead and implement them. # basic, no-frills tree class Node(object): def __init__(self, data, left=None, right=None): self.left = left self.right = right self.info = data tree = Node('top of the tree') tree.left = Node('left subtree') tree.right = Node('right subtree', None, Node('another subtree')) t = tree.right.right t.left = Node('yet another subtree') etc. The CPython implementation of dict is a hash table, and dicts are extremely fast and efficient. So long as you don't mind losing the order of insertion, you won't beat dicts for speed and efficiency in anything you write in pure Python. -- Steven From deets at nospam.web.de Mon Sep 8 08:45:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Sep 2008 14:45:33 +0200 Subject: tracking collection modification References: <42d9688f-1058-4ed7-8d9d-affd432fdb41@s1g2000pra.googlegroups.com> Message-ID: <6ikl42Fr7422U1@mid.uni-berlin.de> usenet.tolomea at gmail.com wrote: > On Sep 7, 8:54?pm, usenet.tolo... at gmail.com wrote: >> I'm working on a remote object system, something kinda like Pyro. >> For the purposes of caching I need to be able to tell if a given >> dict / list / set has been modified. >> Ideally what I'd like is for them to have a modification count >> variable that increments every time the particular collection is >> modified. Unfortunately I can't find anything like that and since this >> needs to work for the regular normal list / dict / set objects >> subclassing them to add the modification count isn't useful. >> I realize I could take a copy and then compare the copy to the >> original, but that's a fairly heavy handed approach and I was hoping >> for something light and fast. >> Does anyone have any suggestions on best to approach this? > > additionally I don't need to know if the things the list (etc) > references have changed, only the list itself No chance. E.g. ZODB is faced with the same problem and requires you to use certain collection implementations to make this work. And don't forget that such a scheme is hard to implement in the face of concurrent access by various clients - as client connection has to keep track of the last-modified-state separately. I'd say that for small to medium-sized collections, it's faster to just marshal them each time. Beyond that, make the heavy-handed checking - and offer dirty-state-aware collection classes one can use to optimize specific cases. Diez From asnast at gmail.com Fri Sep 26 13:17:42 2008 From: asnast at gmail.com (Alex Snast) Date: Fri, 26 Sep 2008 10:17:42 -0700 (PDT) Subject: Quick sort implementation in python References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> <48dbf8f9$0$21266$9b622d9e@news.freenet.de> Message-ID: <4da8f8b2-0216-433c-89a6-39d7ab037e84@l42g2000hsc.googlegroups.com> On Sep 25, 11:47?pm, "Martin v. L?wis" wrote: > > Now as you can see I'm passing my list object to both functions along > > with their first, last indices > > I cannot really see that. More specifically, it isn't definite what the > type of the "a" argument is, nor does the specific type of "a" matter > for the algorithm. It could be a list, or it could be a different > mutable collection that is integer-indexed. > > > My question is: Is that the normal way to implement algorithms in > > python > > Yes, it is. > > > cause in c++ i've implemented that algo via a template function > > which can have a randon access data structure or not. However i have > > no idea how to access the values of a data structure that doesn't > > allow random access. > > Can you please explain how you did that in C? IOW, how did you do > the partition function (template) in case you don't have random > access to the collection? > > Regards, > Martin Why exactly do you need random access for partition function? Do can swap 2 nodes of a linked list without random access (you can swap the pointers or just swap the node values) and you traverse the list till you reach it's tail. From ldo at geek-central.gen.new_zealand Sun Sep 21 02:54:52 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 21 Sep 2008 18:54:52 +1200 Subject: CTypes on a 64 bit machine truncates pointers to 32 bits? References: <48d34449$0$2363$9b622d9e@news.freenet.de> Message-ID: In message , Ron Garret wrote: > Default return type is int, which I assumed would be > 64 bits on a 64 bit machine, but turns out it's 32. Stupid. I think preferred ABIs these days are LP64, not ILP64 or LLP64. From michel at nospam.please Mon Sep 15 14:43:05 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 20:43:05 +0200 Subject: environment variable issue Message-ID: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Hi, Could someone explain me what I'm doing wrong here? I'm trying to retrieve the value of an environment variable in Ubuntu 8.04 like this: >>> import os >>> os.environ['USER'] 'michel' This works but this doesn't: >>> os.environ['HOSTNAME'] Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ raise KeyError(key) KeyError: 'HOSTNAME' Why is it working in the first case but not in the second one. I must be missing something but it seems I'm not able to figure it out. Thanks, Michel -- Michel Leunen http://linux.leunen.com From tino at wildenhain.de Thu Sep 11 04:51:11 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 11 Sep 2008 10:51:11 +0200 Subject: max(), sum(), next() In-Reply-To: <1220499644.48bf58bc376e4@comuh.uh.cu> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <48BEE2F7.5010106@shopzeus.com> <1220499644.48bf58bc376e4@comuh.uh.cu> Message-ID: <48C8DBFF.20208@wildenhain.de> Hi, Luis Zarrabeitia wrote: > Quoting Laszlo Nagy : > ... > Even better: > > help(sum) shows > > === > sum(...) > sum(sequence, start=0) -> value > > Returns the sum of a sequence of numbers (NOT strings) plus the value > of parameter 'start'. When the sequence is empty, returns start. > === > > so the fact that sum([]) returns zero is just because the start value is zero... > sum([],object()) would return an object(). > > BTW, the original code: > >>>> sum(s for s in ["a", "b"] if len(s) > 2) > > wouldn't work anyway... it seems that sum doesn't like to sum strings: > >>>> sum(['a','b'],'') > > : sum() can't sum strings [use ''.join(seq) instead] Yes which is a bit bad anyway. I don't think hard wiring it is such a nice idea. You know, walks like a duck, smells like a duck... If it makes sense to handle things differently for performance, then please have it doing it silently, e.g. when it detects strings just use join() internally. Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From mnordhoff at mattnordhoff.com Wed Sep 24 17:46:33 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 24 Sep 2008 21:46:33 +0000 Subject: Schwartzian transform for tuple in list In-Reply-To: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> Message-ID: <48DAB539.1010500@mattnordhoff.com> Chris Rebert wrote: > On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase wrote: >> Hi, >> >> I have a rather large list structure with tuples contained in them (it's >> part of a specification I received) looks like so: >> [(x1,y1,r1,d1),(x2,y2,r2,d2)...] >> >> The list can range from about 800-1500 tuples in size and I'm currently >> sorting it with this: >> >> a_list.sort(lambda a, b: cmp(b[3], a[3])) > > You'd probably be better off using the 'key' keyword argument to > .sort(), which is made for the Schwartzian Transform: > > a_list.sort(key=lambda x: x[3]) > > This sorts the list items by the value produced by the key function > for each item. It's also (IIRC) faster than using a comparison > function like you're currently doing. > > Regards, > Chris Yes, using 'key' is faster than 'cmp'. If you have Python 2.4 or newer, it would also be slightly faster to use operator.itemgetter() instead of a lambda: >>> import operator >>> a_list.sort(key=operator.itemgetter(3)) >> I'm actually sorting it by the last value in the tuple (d2). I have been >> researching more efficient sorting algorithms and came across Schwartzian >> transform via these links: >> >> http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency >> http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html >> >> I get what's happening (sorta...errr...lol) but I'm not sure if it is more >> efficient in my scenario, if it is then I have no idea how to implement it >> properly :-/ >> >> Would be great if a true expert would offer a suggestion for me... >> >> Thanks! >> >> David -- From maric at aristote.info Wed Sep 3 12:11:25 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 3 Sep 2008 18:11:25 +0200 Subject: properties setting each other In-Reply-To: References: <200809031644.10870.maric@aristote.info> Message-ID: <200809031811.25914.maric@aristote.info> Le Wednesday 03 September 2008 17:40:43 mk, vous avez ?crit?: > > Note that if one property can really be computed from another, this kind > > of thing could be considered as bad design (except if the computation is > > heavy). > > Hmm, why? Is the line of thinking smth like: because the variables > should be kept to minimum and they should be calculated at the moment > they are needed? Because you have to make extra effort to keep the logical relation between value and square. self._square is not really needed, and what is not needed is just extra hassle. Doesn't it clear that your code is more hard to maintain than the alternative : class Squared(object): def __init__(self, val): self._val=val def fgetvalue(self): return self._val def fsetvalue(self, val): self._val=val value = property(fgetvalue, fsetvalue) def fgetsquare(self): return self.value ** 2 def fsetsquare(self,s): self.value = math.sqrt(s) square = property(fgetsquare, fsetsquare) -- _____________ Maric Michaud From gagsl-py2 at yahoo.com.ar Mon Sep 29 22:56:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 23:56:42 -0300 Subject: Configuring pyc directory References: Message-ID: En Sat, 27 Sep 2008 19:06:25 -0300, Robert Moore escribi?: > Is there a way to configure python to read/write compiled pyc files for > modules in a directory other than the directory containing the original > py > files? If you use the py_compile module, you can specify three files: the source file name (and path), the destination file name (and path), and the file name as reported on errors and such. -- Gabriel Genellina From ebgssth at gmail.com Mon Sep 22 22:53:59 2008 From: ebgssth at gmail.com (js) Date: Tue, 23 Sep 2008 11:53:59 +0900 Subject: How do I convert a PyObject to string in C++? In-Reply-To: References: Message-ID: PyString_AsString returns a c string. Just feed it to std::string http://docs.python.org/api/stringObjects.html#l2h-472 On Tue, Sep 23, 2008 at 11:32 AM, wrote: > I have a PyObject, say 'Hello World' , a string, > How do I convert it to a string in C++? > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > From arnodel at googlemail.com Fri Sep 12 13:43:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 12 Sep 2008 10:43:55 -0700 (PDT) Subject: manipulating files within 'for' References: Message-ID: On Sep 12, 6:11?pm, Ben Keshet wrote: > Hi Pythoneers, > > I have a question about a code I wrote with the help of someone. The > code below copy a few lines from different files into one file. It works > fine as it is given here and generates the new file 'pockets.out' > correctly, but says:"....py returned exit code 0". However, if I add > more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) it gives an > error: "Exception raised while running script". You should post the full error if you want some help which is more than speculation > > Can anyone please advice me? Why is it giving an error on multiple x but > runs well with one (I made sure that all files and folders exist, etc.). > What does exit code 0 mean? what does "exception raised" mean? I guess you are on Windows, but how do you run your script? Do you do it from the command line or do you use some IDE? -- Arnaud From clp at rebertia.com Tue Sep 2 23:57:52 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Sep 2008 20:57:52 -0700 Subject: Pass same parameter in Recursive function In-Reply-To: References: Message-ID: <47c890dc0809022057i16516db6k8591a44a45c00750@mail.gmail.com> Assuming the function is tail-recursive or the "unchanging" arguments are immutable, just use a closure: def func(self, x, y, A, B, C): def _func(x,y): return _func(g(A,B,C,x), h(A,B,C,y)) #recurse return _func(x, y) I'm unsure as to the performance impact of this though. - Chris On Tue, Sep 2, 2008 at 8:20 PM, Davy wrote: > Hi all, > > Sometimes I need to pass same parameter in recursive function. From my > point of view, the style is redundant, and I don't what to use some > global style like self.A, self.B, Is there any other choice? > > For example, > > def func(self, x, y, A, B, C): > #x, y change in recursive call > #A, B, C change in the first layer function call, but did not change > in recursive call > if (...): > func(x, y, A, B, C) > else(...): > func(x, y, A, B, C) > > Best regards, > Davy > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From invalid at invalid Fri Sep 12 19:32:59 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 12 Sep 2008 18:32:59 -0500 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <00da5aca$0$2879$c3e8da3@news.astraweb.com> Message-ID: On 2008-09-12, Matt Nordhoff wrote: > I think you misunderstand. He's referring to the Sender > header, not the From header. The messages the listbot sends > out have a Sender header of > "python-list-bounces+user=example.com at python.org" (supposing > the subscriber's email address is user at example.com). Bounces > should be directed to the bitbucket or list admin or whatever, > not the user in the From header. kring.com just has a broken > mail server. So the statement below by Dennis Lee Bieber in message 97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d at earthlink.com isn't actually correct? >>Three: The bounce/ooo-reply is sent to the message author, not >>to any intermediate host(s). After all, on that end, it's >>normal email failure response -- notify the author of the >>message. It doesn't matter that the original message was posted >>on a Usenet newsgroup if that group is automatically relayed to >>members of a mailing list. -- Grant From sbassi at clubdelarazon.org Wed Sep 24 14:16:31 2008 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Wed, 24 Sep 2008 15:16:31 -0300 Subject: Making small executive file for distribution In-Reply-To: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: <9e2f512b0809241116g74e94635g3ae86f5c0c95ffcd@mail.gmail.com> On Wed, Sep 24, 2008 at 10:17 AM, Marin Brkic wrote: > As far as I know py2exe is the only option which can do such a thing > (make exe files from scripts). Is there a way to make those exe files > a little smaller (for a small script they easily go up to 5-10 mb). An alternative solution: Give them a copy of "portable python". It is a Python enviroment that can be used by just copying its file in a single directory (to run python from a pendrive for example), with the need to install any program It even work in Linux with wine (but you seldon need that since most modern Linux distros has a uptodate Python setup). See http://www.portablepython.com/ Best, -- Sebasti?n Bassi. Diplomado en Ciencia y Tecnolog?a. Vendo isla: http://www.genesdigitales.com/isla What's new in Python 3: http://tinyurl.com/5cd89r Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 From deets at nospam.web.de Thu Sep 25 06:56:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 12:56:39 +0200 Subject: How to get the filename in the right case ? References: Message-ID: <6k1937F5i8kjU1@mid.uni-berlin.de> Stef Mientki wrote: > hello, > > How can I find the correct case of a filename ? > > Background in my program I use case sensitive filenames, just like > Python requires. > Now I've integrated pdb into the program, > but pdb acts somwhat strange: > upon a breakpoint it gives the filename always in lowercase (probably > this only happens on windows). > > So is there a way to get the correct case of a given filename in lowercase > ? > > One solution might be to make the comparison in my program always with > lowercase, > but then I'm sure the program won't work on non-windows systems. > > btw, why does pdb behave that way ( Python 2.5 ) ? I doubt it does. It sure doesn't on unix, and I fail to see any reason why it should do that on windows - given that the total number of lower() in pdb.py amounts to one, and that's used to process user-input such as "Yes", "y", "YES" or whatnot. Are you sure you are not processing the content through some lower()-call when embedding pdb? Diez From gagsl-py2 at yahoo.com.ar Fri Sep 19 05:49:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 06:49:23 -0300 Subject: Python, Factset, and Excel - Oh my! References: <04C6F615450E8D4A97EBA1DA9535667E064888@E2K3MAIL1515.mellonbank.com> Message-ID: En Thu, 18 Sep 2008 16:41:36 -0300, Desmond Scott E escribi?: > I'm still a Python novice. > I'm still attempting to migrate a Python-based process from > Windows2000/Python v2.4.2 (#67)/Excel2000 to WindowsXP/Python v2.5.2 > (r252:60911)/Excel2003. > I now have a new "opportunity"! > I need some help with the step in the Python script that calls Excel and > invokes the Factset API to download data into a spreadsheet. I'm > thinking that this is a Python / Factset API setup issue. Is the > Factset API installed as a component of Python? Or does the Factset API > exist in Windows and available to any application, like Python? > Any insights would be greatly appreciated! What's the Factset API? If you're talking about http://www.factset.com/ I'm pretty sure you have to install something to make it available. -- Gabriel Genellina From d3vvnull at gmail.com Sat Sep 27 14:23:12 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sat, 27 Sep 2008 13:23:12 -0500 Subject: python for *nix system admins In-Reply-To: <1222520796.630579@athprx04> References: <1222520796.630579@athprx04> Message-ID: <170543c70809271123j1334d12ardd09c25ce479978f@mail.gmail.com> import commands ? On Sat, Sep 27, 2008 at 8:06 AM, George Boutsioukis wrote: > On Sat, 27 Sep 2008 10:05:01 +0200, Lars Stavholm wrote: > > > Hi All, > > > > I'm new to this list and hoping that this is not off-topic. If it is, > > please point me in the right direction. > > > > I seem to recollect a python module or library for *nix sysadmins, but I > > can't for the life of me find it again. > > > > The module (or library) somehow added unix command capabilities to the > > python language. It seemed like a lesser known, perhaps new, python > > library or module. > > > > Any input or ideas appreciated > > /Lars Stavholm > > The only modules I've come across that barely fit your description are > python-unixtools(gzip, bzip only) and shutil(some limited capabilities). > Running unix commands is usually done directly(os.popen, os.system) on > *nix platforms. Why(and how) would anyone rewrite them as python modules? > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From mr.spoon21 at gmail.com Sun Sep 28 10:37:11 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 28 Sep 2008 16:37:11 +0200 Subject: Music knowledge representation Message-ID: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> Hi, I'm working on an application to analyse music (melodies, chord sequences etc.) I need classes to represent different musical entities. I'm using a class Note to represent all the notes. Inside it stores the name of the natural version of the note (C, D, E, F...) and an integer to calculate the accidentals. Then I have a class Pitch, to represent the different 12 pitch classes, because different notes, such as C# and Db, belong to the same pitch class. In these classes I also have some arithmetic method to perform additions or subtractions between pitches and integers. I also need to represent intervals between notes. An interval must have a degree (first, second, third), that may be represented with a simple integer and a size counted in semitones. Then, with these informations it can retrieve its name, for example: perfect fifth. The degree is calculated between natural notes. So the degree of Interval(C, E) is "third", or 3. This may be simple, if I put the notes in an ordered sequence. But, when I have to calculate, for example Interval(E, C). It should count till the end of the sequence, so if I have: C D E F G A B after the B it should continue with C. I'm not sure how to implement this. Is there a suitable data structure for this purpose? From news1234 at free.fr Fri Sep 26 16:34:31 2008 From: news1234 at free.fr (nntpman68) Date: Fri, 26 Sep 2008 22:34:31 +0200 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> Message-ID: <48dd4756$0$25116$426a74cc@news.free.fr> Hm, I guess you just filter mailing lists and can do nothing about the newsgroup if I'm fetching via the nntp server of my ISP itself, right? I'm using Thunderbird as news reader and this is probably not the smartest news reader, though I like it a lot for mails. Is there any pythonable (or perlable) news reader running under windows / cygwin or any way (under WIN XP) to use scripts to filter newsgroups for Thunderbird? - I'm annoyed by any spam. It's tough to find good rules, but the incoming spams that I see currently on comp.lang.python have certain criteas. - most email addresses from gmail. - all never posted before and then they have multiple posts within a few minutes / seconds - the posts always contain one or more urls ( mostly cryptic names ) - they always start a thread but never reply to one - the post doesn't contain python code or anything which looks only vaguely like source code - never mentions the word python - the amount of sexual or financial vocabulary exceeds classical python posts bye N Aaron "Castironpi" Brady wrote: > On Sep 26, 11:43 am, "Tim Rowe" wrote: >> 2008/9/26 Steven D'Aprano : >> >>> I don't have any objective numbers, but subjectively it seems to me that >>> the number of spams is significantly higher, but not so high as to be a >>> major nuisance. >> I consider *any* spam to be a major nuisance, but I don't see them as >> being the fault of python-list which seems to do a pretty good job of >> blocking them >> >> -- >> Tim Rowe > > Is it worth mentioning that they come from the same author in a short > period of time? Maybe that could bump up the score a notch. > > I think in June and July they were selling watches a lot which I > haven't noticed recently. From rafesacks at gmail.com Mon Sep 8 04:37:24 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 8 Sep 2008 01:37:24 -0700 (PDT) Subject: Clearing a session and reload() problem (with repro error) Message-ID: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> Hi, This seems to be an old question, and I've read back a bit, but rather than assume the answer is "you can't do that", I'd thought I'd post my version of the question along with a reproducible error to illustrate my confusion. My problem is that I'm using Python inside XSI (a 3D graphics application). If I want to restart Python, I have to restart XSI. This is no small amount of time wasted. The solution would be to somehow unload modules and all references and allow my imports to rebuild the cache. I suppose it would be great to clear the python session completely, but the 3D application might have added something to the session at startup (I doubt this though as I don't see any imported modules outside the norm). I've tried to use reload with a very simple algorithm. Simply run through every imported module, ignoring anything that is "None" or on the C: drive (all of our python is on a network drive so this hack works for me for now) and reload() it. I've come to realize that this isn't near intelligent enough to handle sub-packages. Before I post the repro, my questions are: 1) Does anyone have a work-flow for my situation that doesn't use Reload, and doesn't involve restarting the app for every edit/fix 2) Can anyone help point me in the right direction to build a dependable algorithm to cleanly reload all loaded modules? NOTE: I don't need to maintain anything in memory (i.e. instances, pointers, etc.) Everything will be initialized again each time. I'm not asking for code. Just some ideas or pseudo-code would do nicely. Here is a "simple" repro... Package Structure: --------------------------- inheritRepro __init__.py baseLib.py child __init__.py __init__.py: ---------------- import sys, os def reloadModules(): """ Reload all imported modules that are not on the C: drive. """ print "Reloading Python Modules..." # Iterate over all IMPORTED modules modules = sys.modules for modName in modules: mod = modules[modName] # Skip None types and other itesm we don't care about if modName == "__main__" or not hasattr(mod,"__file__"): continue # Get the drive and skip anything on the C: drive drive = os.path.splitdrive(mod.__file__)[0] if drive != "C:": reload(mod) print "Reloaded %s" % mod baseLib.py: --------------- class BaseClassA(object): pass class BaseClassB(BaseClassA): def __init__(self): super(BaseClassB, self).__init__() child.__init__.py: ------------------------ import inheritRepro.baseLib as baseLib class ChildClass(baseLib.BaseClassB): def __init__(self): super(ChildClass, self).__init__() RUN: ------- >>> import inheritRepro >>> import inheritRepro.child as child >>> obj = child.ChildClass() >>> print obj >>> inheritRepro.reloadModules() # Output omitted, but this worked. >>> import inheritRepro >>> import inheritRepro.child as child >>> obj = child.ChildClass() Traceback (most recent call last): File "", line 0, in File "\\nas6tb\PROJECTS\tech\users\rafe.sacks\python\inheritRepro \child\__init__.py", line 5, in __init__ super(ChildClass, self).__init__() File "\\nas6tb\PROJECTS\tech\users\rafe.sacks\python\inheritRepro \baseLib.py", line 6, in __init__ super(BaseClassB, self).__init__() TypeError: super(type, obj): obj must be an instance or subtype of type NOTE: this works if I don't use a sub-package for 'child' (child.py instead). Is it overly simple to assume reloading by file structure might work? Right now I'm getting around this by reload()-ing the right package after running reloadModules() if an error occurs. It's a bit frustrating that it cost me two days of work before I realized it was reload() causing this error and not super() or some other unknown-to- me inheritance/package structure problem. I rebuilt my code module by module until I noticed, quite by accident, that the thing worked once and then never again! ....oh well, these are the joys of learning the hard way. I know this was a long one. If you made it this far, thanks for reading, - Rafe From grante at visi.com Tue Sep 16 10:57:26 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 09:57:26 -0500 Subject: append on lists References: Message-ID: <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> On 2008-09-16, Maric Michaud wrote: > Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit?: >> On 2008-09-16, Maric Michaud wrote: >> > all expressions that return something, return a new object, >> >> That's not _quite_ true: >> >>> a=1 >> >>> b=a.__add__(0) >> >>> a is b >> >> True >> >> ;) > > This is implementation specific, Indeed. > the specification of the language says that it should be > false, That's curious. If so, then the implimentation is in violating the specification. Where is that in the specification? I suspect the statement in the specification should only apply to mutable objects. > and it is for higher numbers : > >>>>[15]: a=1000 > >>>>[16]: b=a.__add__(0) > >>>>[17]: a is b > ...[17]: False > > Don't disturb our OP, with side questions, please, it was > enough hard like this ;) I'm not trying to confuse the OP, but to quote Einstein: "Everything should be made as simple as possible, but not simpler." -- Grant Edwards grante Yow! I wonder if I could at ever get started in the visi.com credit world? From maebert at uos.de Thu Sep 11 11:04:43 2008 From: maebert at uos.de (Manuel Ebert) Date: Thu, 11 Sep 2008 17:04:43 +0200 Subject: Enumerating ordered expat attributes with tuplets? In-Reply-To: References: Message-ID: <3DD8138F-D513-4ACF-B30A-489085DC69EF@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Andy, by the looks of it I'd say that the problem is that the second parameter you passed to start_element is not a dictionary at all (the clue is in the "AttributeError: 'LIST' object" ...). >>> d = ['tree', 'house'] >>> start_element("Thing", d) Thing : AttributeError: 'list' object has no attribute 'items' >>> d = {'tree': 'hug', 'flower' : 'eat'} >>> start_element("Thing", d) Thing : flower="eat" tree="hug" Manuel On Sep 11, 2008, at 4:21 PM, andy_westken at hotmail.com wrote: > Hi > > I'm new to Python and trying to pick up good, idiomatic usage right > from the offset. > > As I was familiar with Expat from C++ (directly and via expatpp) I'm > trying to write a little script - using xml.parsers.expat - to search > and replace XML attribute values. > > As I want the attributes to stay in order when the file is written out > (so I can check my results with a diff tool) I've set the parser's > ordered_attributes attribute. But this has stopped the for loop > working with the tuplets. > > The relevant bit of code in my little test, using the default > Dictionary for the attributes, is: > > def start_element(name, attrs): > print "%s : " % name, > for (a,b) in attrs.items(): > print " %s=\"%s\"" % (a,b), > > But when I set ordered_attributes, first it doesn't like the items() > > AttributeError: 'list' object has no attribute 'items' > > And then it doesn't like the tuple > > ValueError: too many values to unpack > > Do I have keep track of where I am (name, value, name, value, ...) > > Or is there a way I can solve the problem with a tuple? > > Thanks, Andy > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIyTOLcZ70OCIgLecRAsBrAJ9YSa7f+YTyM1yRmEKw8KBtb2klIgCgjNzw F295Tik+45eNHnJ3B4kKnWU= =xR4m -----END PGP SIGNATURE----- From pruebauno at latinmail.com Thu Sep 18 11:39:02 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 18 Sep 2008 08:39:02 -0700 (PDT) Subject: dict generator question References: Message-ID: <07db11b7-af17-45ed-9839-67da3d126e6b@26g2000hsk.googlegroups.com> On Sep 18, 10:54 am, "Simon Mullis" wrote: > Hi, > > Let's say I have an arbitrary list of minor software versions of an > imaginary software product: > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > I'd like to create a dict with major_version : count. > > (So, in this case: > > dict_of_counts = { "1.1" : "1", > "1.2" : "2", > "1.3" : "2" } > > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. > > I'm most probably not thinking pythonically enough... (I know I could > do this pretty easily with a couple more lines, but I'd like to > understand if there's a way to use a dict generator for this). > > Thanks in advance > > SM > > -- > Simon Mullis 3 lines: from collections import defaultdict dd=defaultdict(int) for x in l: dd[x[0:3]]+=1 From castironpi at gmail.com Fri Sep 26 18:51:11 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 15:51:11 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> On Sep 26, 11:48?am, "Tim Rowe" wrote: > 2008/9/26 Tino Wildenhain : > > >> The question I usually ask is "Does this language help me get the job > >> done?" Python often does. That's all that really matters, isn't it? > > > Well then it still depends on the perception of "job done". For example > > PHP programmers would bet their soul that their language of choice is > > exactly the right one to "get the job done." :-) > > You and me would indeed see a different picture on the level of doneness > > of such jobs ;-) > > Well, I did say "Often". Before now I've struggled for ages to write a > Python program to do a job, then when I've tried C# all the problems What problems? > have fallen away and the job What job? > was done in an hour or so. But other > times it has been the other way around; I've done stuff in Python that > I wouldn't know where to begin with in other languages. One of my > constant refrains is that *no* tool is ideal for *all* jobs! > > -- > Tim Rowe If you have wxFormBuilder and the win32 library, it's pretty fast. Python's philosophy is to make common things easy and everything possible. From gneuner2 at comcast.net Mon Sep 1 20:48:23 2008 From: gneuner2 at comcast.net (George Neuner) Date: Mon, 01 Sep 2008 20:48:23 -0400 Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Mon, 1 Sep 2008 21:03:44 +0000 (UTC), Martin Gregorie wrote: >On Mon, 01 Sep 2008 12:04:05 -0700, Robert Maas, http://tinyurl.com/uh3t >wrote: > >>> From: George Neuner A friend of mine had an >>> early 8080 micros that was programmed through the front panel using >>> knife switches >> >> When you say "knife switches", do you mean the kind that are shaped like >> flat paddles? >> >Pedantic correction: > >"Knife switch" is the wrong term. These are high current switches, >typically used in the sort of heavy duty circuit where the wiring hums >when power is on or in school electrical circuits so even the back of the >class can see whether the switch is open or closed. In these a copper >'blade' closes the contact by being pushed down into a >narrow, sprung U terminal that makes a close contact with both sides of >the blade. Like this: http://www.science-city.com/knifeswitch.html > >What you're talking is a flat handle on a SPST or DPST toggle switch. It >is often called a paddle switch and mounted with the flats on the handle >horizontal. Like this, but often with a longer handle: >http://www.pixmania.co.uk/uk/uk/1382717/art/radioshack/spdt-panel-mount- >paddle-s.html I don't know the correct term, but what I was talking about was a tiny switch with a 1/2 inch metal handle that looks like a longish grain of rice. We used to call them "knife" switches because after hours flipping them they would feel like they were cutting into your fingers. George From Lie.1296 at gmail.com Sat Sep 6 17:29:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Sep 2008 14:29:35 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <2aa4ef17-50d3-4aeb-9e7e-0d2d9b9237d4@w7g2000hsa.googlegroups.com> Message-ID: On Sep 3, 6:31?pm, Uwe Schmitt wrote: > On 2 Sep., 18:55, Steven D'Aprano > > > cybersource.com.au> wrote: > > I find myself writing command line tools in Python where I wish to > > include "verbose" output to stdout. > > > I start with a helper function: > > > def print_(obj, level=0): > > ? ? if _verbosity >= level: > > ? ? ? ? print obj > > > And then I end up with functions or methods looking like this: > > > def parrot(x) > > ? ? print_("precondition", level=2) > > ? ? do_something() > > ? ? print_("status is good...", level=1) > > ? ? print_("parrot is squawking strongly now", level=2) > > ? ? do_something_else() > > ? ? print_("squawk squawk squawk", level=3) > > ? ? do_more() > > ? ? print_("postcondition", level=1) > > ? ? return something > > > That often means that my functions end up with more message printing code > > than actual code. The whole thing seems messy and hard to manage for all > > but the smallest scripts. > > > Worst of all, sometimes the messages I wish to print may be expensive to > > compute, and I don't want to waste time computing them if they aren't > > going to be printed because the verbosity is too low. But nor do I wish > > to fill my code with this: > > > if _verbosity >= 3: > > ? ? x = calculate_complicated_thing() > > ? ? print_(x, level=3) > > > Is there a better way of doing this than the way I am going about it? > > > -- > > Steven > > You can save some code if you use function decorators for logging > input and output values of > functions. > So write lots of functions containing one statement and your problem > is solved ;-) > > Greetings, Uwe That would be perfect if python is a fully functional language (read that as: purely functional language). Functional language dictates no side effects, so logging input and output of functions is pretty much everything needed to do debugging (which is the main reason for having verbose mode). It would still be feasible, though, if you keep yourself from using functions with side-effects (or use as few of them as possible). Bjorn Lindqvist says: > One big downside with that approach is that it becomes much harder to > grep for the log message. Usually when I go through logs, I don't care > what exactly the message says, just that it is easily googleable (uses > some kind of identifying text) and that it is unique so I can know > exactly where it was emitted. Actually, I'd prefer a log code (perhaps also as an option, to use -e for showing up log code besides the log message). The log code would be unique and referenced only once in the whole application (to nail down who said what to a single point). The code would make a call to the log printer with the log code (not the error string) and a few arguments to be interpolated to the error string (taken from a dictionary indexed by error code). The downside is loss of inline documentation by the logging codes. From bearophileHUGS at lycos.com Mon Sep 29 09:02:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 06:02:44 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> Message-ID: <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> George Sakkis: > I don't see the same value in creating a distinction between methods > and builtin functions unless the latter are truly generic (and even > then I wouldn't mind having them as methods of the base object class, > e.g. object.type()). Having a builtin len(x) delegate to x.__len__() > seems harder to justify. I have shown few usage examples of the len() one of the posts in this thread. Can you take a look at them and show how you can better rewrite them without a len function? Bye, bearophile From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 03:58:39 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 09:58:39 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: <48dc962a$0$2289$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message > , > Aaron "Castironpi" Brady wrote: > >> Wikipedia puts it decently: "mainly for OO programming, but with some >> procedural elements." > > "Procedural" is the opposite of "functional", not "object-oriented". AFAIK, the "opposite" if functional is imperative, not procedural. But let's not waste too much time on terminology arguments... From python at rgbaz.eu Wed Sep 10 13:12:28 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 19:12:28 +0200 Subject: md5 differences In-Reply-To: References: Message-ID: <7C2CD173-D069-41A0-9B56-382FF86F5B52@rgbaz.eu> On 10 sep 2008, at 18:30, Richard Brodie wrote: > > "Python" wrote in message > news:mailman.799.1221063937.3487.python-list at python.org... > >> here's an example: >> Arno at Computer:~% echo "hello" | md5 >> b1946ac92492d2347c6235b4d2611184 >> How do I get the same results? > > Checksum the same string. > >>>> md5.new("hello\n").hexdigest() > 'b1946ac92492d2347c6235b4d2611184' > > hmm and this then: Arno at Computer:~% echo "test" > test.txt Arno at Computer:~% md5 test.txt MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 Arno at Computer:~% python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import md5 >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() '90364ed45b452d43378629c20543a81d' even echo -n "hello" | md5 doesn't return the same number gr Arno From FettManChu at gmail.com Fri Sep 5 11:08:26 2008 From: FettManChu at gmail.com (Fett) Date: Fri, 5 Sep 2008 08:08:26 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: <7xwshr4qr4.fsf@ruckus.brouhaha.com> <7xmyino11v.fsf@ruckus.brouhaha.com> Message-ID: <6a21ce15-da79-43f7-b090-71e36c6a7c89@d1g2000hsg.googlegroups.com> On Sep 4, 8:04?pm, Paul Rubin wrote: > If you just want to authenticate the strings without confidentiality, > use the built-in HMAC module. But beware of replay attacks. I looked into this and it looks like I might be able to get by with this. I didn't find this function before, I am asking my primary customer if the signature would be sufficient. I am having trouble seeing how I would post the encrypted data to a website and get it back without it changing some. So this option might work better for me (at least quicker), if he's ok with that option. By replay attack I assume you mean posting old data with the signature that is valid for that data? Thanks for the warning, I suppose I could include a date/timestamp in the data. Thanks again, this has been very helpful. From castironpi at gmail.com Tue Sep 9 20:53:42 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 9 Sep 2008 17:53:42 -0700 (PDT) Subject: Coming from .NET and VB and C References: Message-ID: On Sep 8, 9:31?pm, sturlamolden wrote: > On 3 Sep, 18:52, ToPostMustJoinGroup22 > wrote: > > > I'm coming from a .NET, VB, C background. > > Any suggestions for someone new to the scene like me? > > Welcome! Unfortunately, you probably have a lot of bad habits to > unlearn. Don't use Python like another C, VB or Java. It will cause a > lot of grief, and you'll end up with the idea that Python is slow like > a slug. Python is more like Lisp or Haskell, but with a readable > syntax. There are list comprehensions, generator expressions, > dictionaries, sets, lists, list slicing, lambdas, map, reduce, filter, > closures, etc. They are there to be used, and be used a lot. Learning > to use Python efficiently is what has the steepest learning curve. Variable argument lists, first-class function objects. From sturlamolden at yahoo.no Wed Sep 24 17:50:56 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 14:50:56 -0700 (PDT) Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: <7c1554cb-f167-462e-ac7c-ea82cdda99b6@y21g2000hsf.googlegroups.com> On Sep 24, 3:17?pm, Marin Brkic wrote: > Has anyone had a situation like this ? All your inputs and suggestions > are more then welcomed. Send them the .py file and confirm that it does work. The lack of Python can be blamed on the incompetent BOFH. Chances are the situation will change when the BOFH gets 20 requests for Python a day. From srad at inbox.lv Thu Sep 4 11:34:17 2008 From: srad at inbox.lv (Aigars Aigars) Date: Thu, 04 Sep 2008 18:34:17 +0300 Subject: Function decorators Message-ID: <1220542457.48bffff905ca9@www.inbox.lv> Good day all, I am learning Python and came up to decorators. The question is: Why does function FoodList return value None? The code in attachment. Thank you, Aigars -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: testingVarLogger.py Type: application/x-unknown-application-x-python Size: 462 bytes Desc: not available URL: From fredrik at pythonware.com Sat Sep 20 07:54:02 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 13:54:02 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: Colin J. Williams wrote: > "foreach: for x in array: statements > > Loops over the array given by array. On each iteration, the value of the > current element is assigned to x and the internal array pointer is > advanced by one. " > > This could be a useful addition to Python. for-in could be a useful addition to Python? looks like Guido's used his time machine again, then, since it's been around since the pre-1.0 days: http://www.python.org/doc/ref/for.html From aquil.abdullah at gmail.com Fri Sep 5 15:07:45 2008 From: aquil.abdullah at gmail.com (aha) Date: Fri, 5 Sep 2008 12:07:45 -0700 (PDT) Subject: Determining Processor Vender References: <554ecfcf-96d8-4602-8d5e-ee5d70590124@i76g2000hsf.googlegroups.com> Message-ID: <3c4cb88a-2e47-4a5e-9a82-4b72f00b1561@y21g2000hsf.googlegroups.com> On Sep 5, 3:00?pm, aha wrote: > Dose anyone know of a cross-platform method for determining the vendor > of a processor? ?Under linux I can check /proc/cpuinfo. ?What I'd like > to be able to do is determine if a processor is AMD or Intel, so that > I can use the appropriate numerical libraries for my application. > > Regards, > > Aquil Additionally, I've tried the platform module...platform.processor() on my 64-bit AMD system, under Linux, returns x86_64. And under windows retruns an empty string '' From castironpi at gmail.com Thu Sep 4 23:40:07 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 20:40:07 -0700 (PDT) Subject: pdb bug and questions References: Message-ID: <9d1d75a2-a6be-4d56-a53c-46b7942abf08@m73g2000hsh.googlegroups.com> On Sep 4, 4:22?pm, Stef Mientki wrote: > hello, > > I'm trying to embed a debugger into an editor. > I'm only interested in high level debugging. > The first question is what debugger is the best for my purpose ? > (pdb, pydb, rpdb2, smart debugger, extended debugger ? > > Second question, in none of the above debuggers (except rpdb2), > I can find a ?"break now", > so it seems impossible to me to detect unlimited while loops ? > > For the moment I started with pdb, because most of the debuggers seems > to be an extension on pdb. > When I launch the debugger ( winXP, Python 2.5) from with my editor > ? python -u -m pdb ?D:\\Data\\test_IDE.py > I get this error > ? IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') > NOTICE 1 backslash ----------------------------------^ > > If I launch the debugger with > ? python -u -m pdb ?D:/Data/test_IDE.py > It runs fine. > > This looks like a bug to me. > What's the best way to report these kind of bugs ? > > Although I mostly use os.path.join to be OS independent, > these kind of bugs give me the impression, > that I can better do the join myself and always use forward slashes. > Is this a valid conclusion ? > > thanks, > Stef Mientki Stef, I discovered the same problem too with my editor. I solved it by using only the file name, and setting the initial directory on the executable. For something pdb doesn't have, can you look at it yourself? Or, can you write your own ad hoc, specialized to detecting while loops, using settrace and 'except KeyboardInterrupt'? From tjreedy at udel.edu Tue Sep 23 04:37:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 04:37:25 -0400 Subject: Why no tailcall-optimization? In-Reply-To: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? I started to write an article on this but it disappeared.... So short answer: 1. Unless down very carefully, in a way that would slow things down, it would change the semantics of Python. 2. It is usually trivial to convert to a while loop, which amounts to in-frame recursion. If using tail-recursion requires a nested inner function to avoid repeating one-time initialization or exposing the cumulation variable, writing the loop is easier since no nested function is needed. 3. In Python, for loops are usually better for processing iterables, which covers most uses of induction (recursion/iteration). Terry Jan Reedy From jinbow at gmail.com Thu Sep 4 11:32:24 2008 From: jinbow at gmail.com (Mars creature) Date: Thu, 4 Sep 2008 08:32:24 -0700 (PDT) Subject: Read Binary data Message-ID: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> Hi guys, I am trying to read a binary file created by the following matlab command: fid=fopen('a.bin','w','b'); fwrite(fid,a,'real*8'); fclose(fid);, and wondering how to do it in Python. I googled it but still get confused. 'b' in fopen is for 'big-endian', 'real*8' in fwrite is for 64bit float. Thank you very much! Jinbo Wang From mensanator at aol.com Wed Sep 10 13:48:17 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 10 Sep 2008 10:48:17 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: On Sep 7, 3:38?pm, Luis Zarrabeitia wrote: > Quoting Mensanator : > > > Actualy, I already get the behaviour I want. sum([1,None]) > > throws an exception. I don't see why sum([]) doesn't throw > > an exception also > > If you take a "start value" and add to it every element of a list, should the > process fail if the list is empty? No. > If you don't add anything to the start value, > you should get back the start value. Agree. > > Python's sum is defined as sum(sequence, start=0). That's the issue. > If sum were to throw an > exception with sum([]), it should also throw it with sum([], start=0), wich > makes no sense. Given that definition, yes. But is the definition correct in ALL cases? Are there situations where the sum of an empty list should NOT be 0? Of course there are. Can sum() handle those cases? No, it can't, I have to write my own definition if I want that behaviour. There's no reason why sum([]) and sum([],0) have to mean the same thing at the exclusion of a perfectly valid alternative definition. But that's the way it is, so I have to live with it. But that's not conceeding that I'm wrong. > > -- > Luis Zarrabeitia > Facultad de Matem?tica y Computaci?n, UHhttp://profesores.matcom.uh.cu/~kyrie From gagsl-py2 at yahoo.com.ar Fri Sep 5 17:32:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 18:32:18 -0300 Subject: [PIL] quake like multicoloured text References: <3d829a04-9005-4216-86dc-b1055edab4e7@f63g2000hsf.googlegroups.com> Message-ID: En Fri, 05 Sep 2008 16:24:08 -0300, Durand escribi?: > I'm wondering how I could render text with PIL in which different > parts of the text are different characters. This is for a game stats > script where names are written like: > ^1Red ^2Green ^3Yellow, etc. > The problem is that I currently use text in the ImageDraw module but > the only way I can think of rendering text is by rendering each bit of > text in a separate colour. > > Example: > > draw.text((0,0),"Red", fill="red") > draw.text((30,0),"Green", fill="green") > draw.text((60,0),"Yellow", fill="green") > > except that I'm not sure how much spacing there is between each > coloured bit of text(30px is assumed in the example)...Would there be > an alternate method of doing this? You could use the draw.textsize method to measure how much space will take each part... -- Gabriel Genellina From stef.mientki at gmail.com Tue Sep 30 15:59:48 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 21:59:48 +0200 Subject: Would this be called a bug in inspect ? In-Reply-To: References: <48E268A3.4050900@gmail.com> Message-ID: <48E28534.1040009@gmail.com> Gabriel Genellina wrote: > En Tue, 30 Sep 2008 14:57:55 -0300, Stef Mientki > escribi?: > >> I'm not familiar with inspect, >> but I get an error (see below) in >> getmembers ( wx ) >> >> Of course this is bug in wx . > > Yes. > >> But would you also call this a bug in inspect ? >> (inspect crashes and doesn't continue with th rest of the code, nor >> it returns the already gathered data) > > getmembers works fine; try m=getmembers(wx) and see. REALLY GREAT ! > It fails when you attemp to print (or pprint) the returned list. > But this is fully beyond my understanding: m = getmembers ( wx ) print m runs fine print getmembers ( wx ) crashes but not always: >>> print getmembers (wx) [('ACCEL_ALT', 1), ('ACCEL_CMD', 2), ('ACCEL_CTRL', 2), ('ACCEL_NORMAL', 0), ('ACCEL_SHIFT', 4), ('ADJUST_MINSIZE', 0), ( And to make it even weirder, now I can let your suggestion crash too >>> m=getmembers(wx) >>> print getmembers (wx) Traceback (most recent call last): File "", line 1, in File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' >>> print m Traceback (most recent call last): File "", line 1, in File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' ?????? thanks, Stef From grante at visi.com Mon Sep 22 22:56:30 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 22 Sep 2008 21:56:30 -0500 Subject: Time.sleep(0.0125) not available within Linux References: Message-ID: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> On 2008-09-23, Blubaugh, David A. wrote: > I was wondering if anyone has come across the issue of not being allowed > to have the following within a Python script operating under Linux: > > time.sleep(0.0125) No, I have not. And I doubt anybody else has. > It appears that I am not allowed to have the object sleep. It doesn't appear that way to me. Care to explain how you arrived at that conclusion? > Has anyone encountered this specific issue before in the past? $ python Python 2.5.2 (r252:60911, Aug 28 2008, 15:54:48) [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.sleep(0.0125) >>> The above code has worked as far back as I can recall (which I think includes Python 1.4). -- Grant From sjmachin at lexicon.net Fri Sep 5 09:29:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 06:29:54 -0700 (PDT) Subject: int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why? References: <184502f4-872a-4c23-9a6d-e93ef225d4de@a2g2000prm.googlegroups.com> Message-ID: On Sep 5, 11:12 pm, bcm wrote: > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on win32 > The following line of code describes an funny question?>>> int((9.2-9.0)*10) > 1 > >>> int((9.21-9.0)*10) > 2 > >>> int((9.1-9.0)*10) > 0 > >>> int((9.11-9.0)*10) > 1 > >>> int((8.2-8.0)*10) > 1 > >>> int((8.23-8.0)*10) > > 2 > > why? anybody can explain it? Try looking one step at a time: >>> 9.2 9.1999999999999993 That wasn't hard, was it? Do you need any further explanation? If so, look here: http://docs.python.org/tut/node16.html From goranbaraccvrcko at googlemail.com Thu Sep 25 13:52:59 2008 From: goranbaraccvrcko at googlemail.com (Goran Barac Cvrcko) Date: Thu, 25 Sep 2008 10:52:59 -0700 (PDT) Subject: Hello guys!!!!! Message-ID: <5f975ac5-b4fa-431d-bbe3-bf25a3f6f126@k37g2000hsf.googlegroups.com> Hello, this is Goran Barac from town Banjaluka, Bosnia and Herzegovina, also known as Cvrcko Does anyone know of any bars in town where I can swallow a bucket of cum? It can be either dog, horse or human cum. Also, does anyone know of any sex bars where people will shit in your mouth? I also like eating shit. -- Name: Goran Barac - Cvrcko Street adress: Ive Andrica 23 Town: 78000 Banja Luka Country: Bosnia and Herzegovina Home phone: +38751/332-113 Cell phone: +38765/776-556 Email adress: goranbaraccvrcko at googlemail.com ~ The new pumpkin rarely pulls Terrance, it teases Sharon instead. For Susan the tape's sad, beside me it's unique, whereas against you it's believing dirty. Hey, go reject a fork! Why did Alice open throughout all the boats? We can't explain poultices unless Woody will mercilessly judge afterwards. The frames, disks, and shirts are all fat and fresh. Who will we dine after Edwina wastes the thin mirror's goldsmith? It's very outer today, I'll recollect strangely or Christopher will learn the teachers. Hardly any humble brave tyrants hourly solve as the tired wrinkles cover. Hardly any distant buttons are short and other urban ointments are filthy, but will Robette receive that? Let's lift behind the deep highways, but don't promise the heavy diets. Who kicks badly, when Melvin burns the stale code before the autumn? Get your absolutely moulding barber within my cellar. If you will laugh Gay's hill against porters, it will incredibly climb the case. Some shopkeepers arrive, irrigate, and shout. Others sadly expect. To be pathetic or sticky will talk abysmal oranges to wickedly look. Are you healthy, I mean, moving above clever onions? While farmers partly taste pins, the powders often excuse against the blunt jackets. Generally Susanne will order the sticker, and if George actually seeks it too, the bowl will attempt with the polite lane. He can hate durable kettles above the rural bad ocean, whilst Oscar easily scolds them too. You eventually fill against Norma when the kind drapers irritate among the poor summer. As surprisingly as Dolf converses, you can dye the cap much more familiarly. Brion, still killing, behaves almost eerily, as the sauce changes on their coffee. You won't recommend me grasping about your lazy office. Almost no butchers steadily live the lost signal. Cyrus's hat improves among our desk after we sow towards it. Ralph measures the weaver within hers and wanly calls. Some cosmetic tags answer David, and they rigidly walk Quincy too. When Richard's elder gardner dreams, Mark cares for weak, closed islands. He might strongly fear think and plays our cheap, sour painters above a bathroom. I creep the active yogi and cook it in back of its dorm. Tell Katherine it's strong loving within a tree. Why will you jump the angry lower exits before Murray does? I am unbelievably bitter, so I wander you. How does Hector smell so regularly, whenever Ronald likes the solid twig very slowly? Julieta, have a hot printer. You won't clean it. Fucking don't join a dryer! She wants to nibble inner smogs under Usha's castle. She'd rather depart grudgingly than help with Bernadette's younger grocer. Other old dark cards will comb frantically alongside cans. Try pouring the monument's pretty cat and Oliver will attack you! Don't try to seek halfheartedly while you're jumping throughout a easy carpenter. He'll be climbing in front of good Cypriene until his enigma answers quietly. What doesn't Janet smell inadvertently? They are opening before the rain now, won't explain walnuts later. Some light long game covers pools outside Woodrow's rich film. Why did Oscar judge the pear with the handsome spoon? He will talk nearly if Julieta's tailor isn't wet. Just looking beside a ulcer through the store is too young for Woody to care it. Both filling now, Alejandro and Marty irritated the open rivers about smart envelope. Occasionally, dusts kill beside rude fires, unless they're sweet. Her pen was sharp, dull, and fears over the spring. Zack, on floors difficult and upper, attacks towards it, recollecting seemingly. We measure the raw sauce. They are rejecting throughout quiet, towards empty, in back of cold units. My wide potter won't clean before I comb it. If you'll pour Edward's camp with aches, it'll admiringly converse the cup. I was promising frogs to worthwhile Corinne, who's walking in back of the counter's stable. It can receive clean pickles, do you solve them? Many jugs will be weird lean carrots. Roger helps, then Walt stupidly believes a ugly lentil on Catherine's road. We tease them, then we weekly dream Zack and Annabel's blank candle. A lot of shallow dose or canyon, and she'll locally excuse everybody. If the bizarre balls can sow bimonthly, the hollow raindrop may love more ventilators. We laugh weekly, unless Jezebel grasps shoes outside Jimmie's puddle. Jimmy! You'll mould plates. Just now, I'll dine the bandage. All glad strange figs will fully order the lemons. The dog without the proud star is the pitcher that learns happily. It might crudely scold within sick dry satellites. Until Dolf calls the bushs generally, Ann won't join any full winters. Better kick clouds now or Blanche will wrongly hate them over you. There, Jeff never arrives until Joie nibbles the noisy elbow deeply. From psaffrey at googlemail.com Tue Sep 16 07:15:59 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Tue, 16 Sep 2008 04:15:59 -0700 (PDT) Subject: Parallelising code References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> <676c9d65-5bc7-44c4-9e61-6f7ed2b3c58c@d77g2000hsb.googlegroups.com> Message-ID: Many very helpful replies, which I will now mull over. Thanks, Peter From steve at REMOVE-THIS-cybersource.com.au Sun Sep 28 04:38:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 08:38:00 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <00ef3c23$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 22:37:09 -0700, est wrote: >>>> str(u'\ue863') > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0 > : ordinal not in range(128) > > FAIL. What result did you expect? [...] > The problem is, why the f**k set ASCII encoding to range(128) ???????? > while str() is internally byte array it should be handled in range(256) > !!!!!!!!!! To quote Terry Pratchett: "What sort of person," said Salzella patiently, "sits down and *writes* a maniacal laugh? And all those exclamation marks, you notice? Five? A sure sign of someone who wears his underpants on his head." -- (Terry Pratchett, Maskerade) In any case, even if the ASCII encoding used all 256 possible bytes, you still have a problem. Your unicode string is a single character with ordinal value 59491: >>> ord(u'\ue863') 59491 You can't fit 59491 (or more) characters into 256, so obviously some unicode chars aren't going to fit into ASCII without some sort of encoding. You show that yourself: u'\ue863'.encode('mbcs') # Windows only But of course 'mbcs' is only one possible encoding. There are others. Python refuses to guess which encoding you want. Here's another: u'\ue863'.encode('utf-8') -- Steven From tarundevnani at gmail.com Fri Sep 5 08:56:02 2008 From: tarundevnani at gmail.com (tarun) Date: Fri, 5 Sep 2008 18:26:02 +0530 Subject: Regarding subprocess module Message-ID: Hello all, I wrote the following code: import subprocess,time cmdExe = "C:\\WINDOWS\\system32\\cmd.exe" myProcess = subprocess.Popen(cmdExe,stdin=subprocess.PIPE) time.sleep(2) myProcess.stdin.write('cd Desktop\r\n') I copied the above lines of code to a file and tried executing the python file from dos box (command prompt) on windows I want subprocess.Popen to open a new dos box. But it works in the same window. What should I do to open the subprocess in new window? Thanks & Regards. Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From watine at cines.fr Fri Sep 5 11:53:12 2008 From: watine at cines.fr (Benjamin Watine) Date: Fri, 05 Sep 2008 17:53:12 +0200 Subject: Files application architecture Message-ID: <48C155E8.7050006@cines.fr> Hi, I'm about to develop a small python application and I wonder how to organize files in this application. I'm familar to java, so I'm tempted to use the same convention : 1 file per class and 1 folders per package. I know that packages doesn't exists in python, they are modules instead. May I create specific module for each "group of class" ? My application follow the MVC paradigm, so basically, I've a package Model, a package View, and a package Controller. So, what are best practices for organizing files and folders in a small python project ? I've found PEP8 (http://www.python.org/dev/peps/pep-0008/) that gives a lot of good hints on coding convention, but nothing about files organization. Thanks in advance ! Ben From grante at visi.com Tue Sep 30 12:32:36 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Sep 2008 11:32:36 -0500 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: On 2008-09-30, Ivan Reborin wrote: > But as I said, got a job that't got to be done, so I'm trying > to figure out how to do array operations as easily as possible > in python, which are necessary for all my calculations. numpy -- Grant Edwards grante Yow! TONY RANDALL! Is YOUR at life a PATIO of FUN?? visi.com From tjreedy at udel.edu Tue Sep 2 18:17:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 02 Sep 2008 18:17:03 -0400 Subject: Renumbering In-Reply-To: References: Message-ID: Francesco Pietra wrote: > Hi; Hi, Let L be a data line > I would like to renumber, starting from 1, column 6 (i.e, 428 become > 1, 429 becomes 2, etc for a very long list) So you want to subtract 427 from each entry in L[22:26] > ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 >... > ATOM 3432 N SER B 429 142.432 85.155 78.878 1.00134.86 2SG3434 > ... > > Distinctive character is column 5, i.e., it must be set that only > lines containing "B" should be renumbered. if L[21] == > As you can see, the number of lines for a particular value in column 6 > changes from situation to situation, and may even be different for the > same name in column 4. For example, LEU can have a different number of > lines depending on the position of this amino acid (leucine). But from what you said earlier, this is not relevant. > > I was unable to set non-proportional characters, sorry. The display font depends on individual systems. Thunderbird uses fixed pitch font, so table displays nicely for me. > Thanks for help This is fairly simple. See the tutorial for explanations. data = [ 'ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426', 'ATOM 3432 N SER B 429 142.432 85.155 78.878 1.00134.86 2SG3434' ] for L in data: if L[21] == 'B': L = L[:22] + "%4d" % (int(L[22:26])-427) + L[26:] print(L) #py3 # prints ATOM 3424 N LEU B 1 143.814 87.271 77.726 1.00115.20 2SG3426 ATOM 3432 N SER B 2 142.432 85.155 78.878 1.00134.86 2SG3434 If you start with a disk file and want to end up with a new disk file... replace the 'data =' statement above with data = open('datafile','r') follow it with outp = open('newdata', 'w') and replace the print statement with outp.write(L) Terry Jan Reedy From castironpi at gmail.com Fri Sep 12 10:00:12 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 12 Sep 2008 07:00:12 -0700 (PDT) Subject: lacking follow-through References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> On Sep 12, 7:23?am, Steve Holden wrote: > castironpi wrote: > > If you are flattered to be compared to an AI you must come from the same > race as Mr. Spock in Star Trek. No, I said 'for my logic to compared'. Speaking of which, I think you excluded the possibility of diligent and ethical human, which meets the criteria (of being flattered to be compared to an AI)... unless Vulcan is just a synonym for it. If you want a discussion of why a diligent and ethical human takes pride in / devotes effort to logic, that's another topic that I'm happy to engage on. > You aren't entitled to require discussion of your ideas and proposals. No, but you are entitled to human interaction. If your case is that I should seek mine face-to-face instead of keyboard-to-screen, you probably have a point. ... > [...] > > > For example, I sometimes hear people talk about salary as though it > > were social approval, and vice versa. ?Even though the analogy doesn't > > hold in every case generally, it is still a good way to express > > yourself in many contexts, and especially when the more precise word > > isn't on the tip of your tongue. > > Perhaps under those circumstances the better choice is to hold off > posting and do some research until you come up with the proper word. Yes I know. Good thing everyone at Mozilla agrees with you, and Thesaurus.Com is included in Firefox's quicksearch engines. > Precision in the expression of ideas encourages debate, whereas sloppy > "just write what you feel" is likely to result in hostile responses, as > it causes the perception that you value your own time more than that of > the people you attempt to engage. But the value of expression and self-expression can outweigh the value of debate, even in so stuffy a setting as a Usenet group. Make time for both or stifle your emotions. Do you hold I should be speaking from the heart more or less? Regardless, you've contradicted yourself: 1) "just write what you feel" is likely to result in hostile responses 2) If you are flattered to be compared to an AI you must [not be human] Assume you, Steve, do as you say (practice what you preach). You do not write either "just what you feel", nor anything that can be compared to an A.I. Define the goal of A.I. to be logic and reasoned "post-impulsive" deliberation (my title to define as I voiced the flattery). Then conclude you don't post to the newsgroup. Observe you do, and reach an absurdity. What premise do you retract? Knowing nothing of your background in philosophy or otherwise, it may be a little unfair to put words in your mouth like that. It's a deep problem (that yes, does have implications on the "diligent and ethical" issue above) of human nature and the human condition: If you're not rational, then you're a man. Besides, it is better to complain to the group that it is dropping my posts than to anyone else. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ From namekuseijin at gmail.com Tue Sep 23 22:32:31 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Tue, 23 Sep 2008 19:32:31 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: <31147d87-572c-484f-ae96-66cfe5b83677@i76g2000hsf.googlegroups.com> On 23 set, 22:50, Neal Becker wrote: > I find I'm often tripped up by: > > x = Y (lots of ?constructor arguments....) if something ... > > on first glance, I don't notice the if. Nobody does. This peculiar syntax has much better usage in short expressions. dothis if this else dothat From fredrik at pythonware.com Sat Sep 20 13:30:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 19:30:18 +0200 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: (no need to shout when filling in the subject line, thanks) > I have now been able to generate a .pyd file from a FORTRAN > file that I am trying to interface with python. I was able > to execute this with an additional insight into how f2py > operates. > > ImportError: DLL load with error code 193 Error code 193 is ERROR_BAD_EXE_FORMAT, which means that the thing you're trying to import is not a proper DLL. > copy LICENSE.txt LICENSE.pyd 1 file(s) copied. > python >>> import LICENSE Traceback (most recent call last): File "", line 1, in ImportError: DLL load failed with error code 193 In general, the tools for building binary extensions for Python assumes that you have at least some basic knowledge about how to build binaries using a compiled language. From erikwickstrom at gmail.com Sat Sep 13 00:13:18 2008 From: erikwickstrom at gmail.com (erikcw) Date: Fri, 12 Sep 2008 21:13:18 -0700 (PDT) Subject: Wrong application name in menubar of OS X Message-ID: <1af662ce-5454-436c-8b65-c713993cf6bc@s9g2000prg.googlegroups.com> Hi, The menubar of OS X is showing the application name as Python instead of the name of my wxpython gui app. How do I make my application name show-up in the menu bar? Thanks! Erik From grante at visi.com Mon Sep 15 00:30:32 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 23:30:32 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> <87od2q5a24.fsf@benfinney.id.au> Message-ID: On 2008-09-15, Ben Finney wrote: > Adelle Hartley writes: > >> I'm looking at porting a library that was written for COM and .Net >> to work as a Python module, and was wondering whether it would be >> better to stick to the library's current naming convention so that >> the API is as similar as possible on each platform, or to adopt a >> "when in Rome..." policy and follow the "most mainstream" naming >> pattern for each platform/language. > > I think it's more important for Python library APIs to comply > with the Python coding guidelines (as specified in PEP 8) than > to comply with standards in other languages. I think the practical matter of being able to use existing documentation and examples might be more important than maintinging the purity of PEP 8 naming styles. > The Python library you're implementing isn't being used in > those other languages, so the conventions of other languages > have little relevance. > > It's being used in Python code, so it should mesh well with > PEP 8 compliant code ??? by having the API itself comply with > PEP 8. I think that battle was lost long ago, but maybe that just because I use a lot of libraries written in C, C++, and Fortan and then wrapped with things like swing. -- Grant From bdesth.quelquechose at free.quelquepart.fr Mon Sep 22 16:28:50 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 22:28:50 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <48d7720d$0$12866$426a34cc@news.free.fr> <48d78c3c$0$6998$426a74cc@news.free.fr> <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> <48d7f46d$0$15502$426a74cc@news.free.fr> Message-ID: <48d80038$0$27459$426a34cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : > On Sep 22, 2:38 pm, Bruno Desthuilliers > wrote: (snip) >> Going back to robot-mode, Aaron ? > > Not getting the same sense of "soul" as from my usual posts. I guess > so. Might even drop the name change, too... Don't !-) > while I'm at it. One > more word from you about it and I'm starting a thread, and calling it, > "Python and my sense of 'soul'". Ha ha. Please bear with me - and understand that the above half-backed half-joke was also an implicit aknowledgement of the recent changes in your mode of communication. I should have added a , I think... From stef.mientki at gmail.com Mon Sep 29 15:56:19 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 29 Sep 2008 21:56:19 +0200 Subject: how to search multiple textfiles ? (Python is slow ?) In-Reply-To: References: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> Message-ID: <48E132E3.8070308@gmail.com> Lawrence D'Oliveiro wrote: > In message , Stef > Mientki wrote: > > >> - Pyscripter 110 sec ( PyScripter is the default IDE I use now) >> - Delphi 20 .. 35 sec >> - Findstr 4 sec >> > > What order did you try try them in? Did you try each one more than once, in > different orders? Just to rule out filesystem caching effects. > > I repeated all of them at least twice, to see if I got the same result. And indeed the very first run (PyScripter) was about 150 sec. So I think the above mentioned values give a good impression, nothing more. >> I'm really amazed by the speed of Python !! >> It can only be beaten by findstr, which is only available on windows. >> > > Did you try find -exec grep -F? > well my windows version doesn't understand that : P:\Python>find /? Searches for a text string in a file or files. FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]] /V Displays all lines NOT containing the specified string. /C Displays only the count of lines containing the string. /N Displays line numbers with the displayed lines. /I Ignores the case of characters when searching for the string. /OFF[LINE] Do not skip files with offline attribute set. "string" Specifies the text string to find. [drive:][path]filename Specifies a file or files to search. If a path is not specified, FIND searches the text typed at the prompt or piped from another command. cheers, Stef > -- > http://mail.python.org/mailman/listinfo/python-list > From bearophileHUGS at lycos.com Wed Sep 3 08:23:10 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 05:23:10 -0700 (PDT) Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: <7f2d4b4a-bc97-4b46-a31e-63f98e9fee73@34g2000hsh.googlegroups.com> Roy Smith: > No reason to limit how many splits get done if you're > explicitly going to slice the first two. You are probably right for this problem, because most lines are 2 items long, but in scripts that have to process lines potentially composed of many parts, setting a max number of parts speeds up your script and reduces memory used, because you have less parts at the end. Bye, bearophile From __peter__ at web.de Thu Sep 18 08:45:34 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2008 14:45:34 +0200 Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > > but no improvements. > > Many thanks, Alex When you're looking for duplicates an efficient solution is likely to be based on a set or dict object. # untested from collections import defaultdict groups = defaultdict(list) for item in IN: c = item.coordinates groups[c[0], c[1]].append(item.label) SN = [] for labels in groups.itervalues(): if len(labels) > 1: SN.extend(labels) # or labels[1:] if you want to keep one item Peter From marco.bizzarri at gmail.com Thu Sep 4 10:43:46 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 16:43:46 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <48bfd7a0$0$20720$426a74cc@news.free.fr> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <48bfd7a0$0$20720$426a74cc@news.free.fr> Message-ID: <3f0d61c40809040743t75caf483gec5714b7abd4ef6b@mail.gmail.com> On Thu, Sep 4, 2008 at 2:43 PM, Bruno Desthuilliers wrote: Well, Bruno, it looks like I've to wider my search in order to read something about it. Thanks for your suggestions, in any case. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From half.italian at gmail.com Mon Sep 8 15:38:37 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 8 Sep 2008 12:38:37 -0700 (PDT) Subject: How to run PyOS_InputHook from python code (i.e. yield to event loops) References: <87wshpcaek.fsf@gmail.com> Message-ID: On Sep 6, 1:00?pm, vivai... at gmail.com (Ville M. Vainio) wrote: > Background: PyOS_InputHook is something that gets run when python is > doing raw_input. TkInter and friends use it to run their event loops, > so that their events are handled while python is doing raw_input. > > What I'd like to do is run the same function without having to do > raw_input. I.e. I'd like to run whatever event loop is available, > without incorporating any gui-specific code (PyOS_InputHook seems like > a nifty way to accomplish this). > > My actual use case is to keep a tkinter application responsive while > launching a background process (and waiting for it to complete!). > > My eventual code would be something like: > > launch_process_in_thread('bzr pull') > > while not is_done: > ? pyos_inputhook() > ? time.sleep(0.1) > > print "Done!" I'm still recovering from a hangover, so don't quote me. I think you want the "after" function: launch_process_in_thread('bzr pull') self.update() def update(self): while not self.is_done: self.after(2000, self.update) From steve at REMOVE-THIS-cybersource.com.au Fri Sep 5 23:45:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Sep 2008 03:45:21 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> Message-ID: <00d1f730$0$20302$c3e8da3@news.astraweb.com> On Fri, 05 Sep 2008 22:20:06 -0400, Manu Hack wrote: > On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: ... >>> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >>> >>> It doesn't make sense to me. What do you set x to? >> >> For all x. > > But then how can you conclude sum([]) = 0 from there? It's way far from > obvious. I think Castironpi's reasoning is to imagine taking sum([x])-x for *any* possible x (where subtraction and addition is defined). Naturally you always get 0. Now replace x by *nothing at all* and you get: sum([]) "subtract nothing at all" = 0 I think that this is a reasonable way to *informally* think about the question, but it's not mathematically sound, because if you replace x with "nothing at all" you either get: sum([]) - = 0 which is invalid (only one operand to the subtraction operator), or you get: sum([0]) - 0 = 0 which doesn't involve an empty list. What castironpi seems to be doing is replacing "nothing at all" with, er, nothing at all in one place, and zero in the other. And that's what makes it unsound and only suitable as an informal argument. [The rest of this is (mostly) aimed at Mensanator, so others can stop reading if they like.] Fundamentally, the abstract function "sum" and the concrete Python implementation of sum() are both human constructs. It's not like there is some pure Platonic[1] "Ideal Sum" floating in space that we can refer to. Somewhere, sometime, some mathematician had to *define* sum(), and other mathematicians had to agree to use the same definition. They could have decided that sum must take at least two arguments, because addition requires two arguments and it's meaningless to talk about adding a single number without talking about adding it to something else. But they didn't. Similarly, they might have decided that sum must take at least one argument, and therefore prohibit sum([]), but they didn't: it's more useful for sum of the empty list to give zero than it is for it to be an error. As I mentioned earlier, mathematicians are nothing if not pragmatists. [1] Or was it Aristotle who believed in Ideal Forms? No, I'm sure it was Plato. -- Steven From Lie.1296 at gmail.com Sun Sep 28 11:55:03 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 08:55:03 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48db462f$0$24356$426a74cc@news.free.fr> Message-ID: <2dec1987-6477-4269-8964-5ef847495dd3@o40g2000prn.googlegroups.com> On Sep 25, 3:05?pm, Bruno Desthuilliers wrote: > Steven D'Aprano a ?crit : > > > On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote: > > >> Plenty of people were quick to say that the exception should be passed > >> through to the caller. ?No one said this behaviour should be documented. > >> ?There may be little practical difference bewteen calling sys.exit() > >> after printing an error and progating an exception if no one using the > >> library knows that it could generate that exception in those > >> circumstances. > > > That's true, I didn't explicitly say that the library should be > > documented. Nor did I say that it shouldn't be riddled with bugs. There's > > little practical difference between a buggy library and one that raises > > unexpected (i.e. undocumented) exceptions either. > > Also note that there are quite a couples cases where the library authors > themselves cannot predict which exception types may be raised - as soon > as the library functions expect callback functions, file-like or > dict-like or whatever-like objects etc, it's the caller's responsability > to handle the exceptions that may be raised by what *he* passes to the > library... No, the library author can always predict which exception his library may raise. If a callback function, file-like, dict-like, etc raises an exception, it is not his libraries' exception anymore and is not his responsibility. In that case we should refer to the documentation for the callback/etc/etc instead of the documentation for the library. From roy at panix.com Sun Sep 21 12:24:09 2008 From: roy at panix.com (Roy Smith) Date: Sun, 21 Sep 2008 12:24:09 -0400 Subject: Why are "broken iterators" broken? References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: In article , Fredrik Lundh wrote: > Steven D'Aprano wrote: > > > According to the Python docs, once an iterator raises StopIteration, it > > should continue to raise StopIteration forever. Iterators that fail to > > behave in this fashion are deemed to be "broken": > > > > http://docs.python.org/lib/typeiter.html > > > > I don't understand the reasoning behind this. As I understand it, an > > iterator is something like a stream. There's no constraint that once a > > stream is empty it must remain empty forever. > > it's a design guideline, not an absolute rule. > > but I disagree that an iterator is "something like a stream". it's > rather "something like a pointer or an index", that is, an object that > helps you iterate over all members in a collection. > > There are plausible examples of collections which grow while you're iterating over them. I'm thinking specifically of a queue in a multi-threaded application. One thread pushes work onto the back of the queue while another pops from the front. The queue could certainly go empty at times. But, maybe a Python iterator is just the wrong way to model such behavior. From python-list at trentnelson.com Thu Sep 4 16:27:59 2008 From: python-list at trentnelson.com (Trent Nelson) Date: Thu, 4 Sep 2008 20:27:59 +0000 Subject: Can anyone suggest a good crypto package? In-Reply-To: References: Message-ID: <20080904202759.GA20070@wind.teleri.net> On Thu, Sep 04, 2008 at 11:39:42AM -0700, Fett wrote: > I need a crypto package that works on windows with python 2.5. Can > anyone suggest one for me? You could always rely on the the APIs Windows provides to do this sort out stuff, either via pywin32 or ctypes. Trent. From superflit at gmail.com Tue Sep 9 15:52:55 2008 From: superflit at gmail.com (flit) Date: Tue, 9 Sep 2008 12:52:55 -0700 (PDT) Subject: check if the values are prensent in a list of values References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> <48c6caae$0$22688$426a74cc@news.free.fr> Message-ID: <5fcfc9d3-bec3-45b0-9b00-bfcc173072ee@r66g2000hsg.googlegroups.com> On 9 set, 15:13, Bruno Desthuilliers wrote: > Matt Nordhoff a ?crit : > (snip) > > > I'm not judging whether this is a good solution or not, but that's a > > silly use of a dict. > > Yeps, but a somewhat common one in code predating the apparition of sets > as builtin type. Thanks for all contributions, sure I learn a lot with all samples. Very good thread and answers. Thank you all From jkn_gg at nicorp.f9.co.uk Fri Sep 26 05:33:49 2008 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Fri, 26 Sep 2008 02:33:49 -0700 (PDT) Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: On Sep 26, 9:26 am, Steven D'Aprano wrote: > On Fri, 26 Sep 2008 19:46:10 +1200, Lawrence D'Oliveiro wrote: > > In message <00eb2560$0$20666$c3e8... at news.astraweb.com>, Steven D'Aprano > > wrote: > > >> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: > > >>> Just a thought, your minimum sleep time is probably limited by the > >>> resolution of the system "HZ" clock. Type > > >>> less /proc/config.gz > > >> $ less /proc/config.gz > >> /proc/config.gz: No such file or directory > > >> What OS are you using? > > > The one named in the subject line? > > Are you asking me or telling me? > > I've tried on five different Linux machines I have access to, and there > is no such /proc/config.gz on any of them: > /proc/config.gz is not directly connected with a specific linux distribution; it's a function of the kernel build configuration. If the appropriate setting is enabled, then /proc/config.gz will show (via eg. zcat) the equivalent of the .config file used to build the kernel you are actually running. It's a useful feature in all linuces, going back quite a way IIRC. J^n From manuhack at gmail.com Sat Sep 6 00:33:25 2008 From: manuhack at gmail.com (Manu Hack) Date: Sat, 6 Sep 2008 00:33:25 -0400 Subject: max(), sum(), next() In-Reply-To: <00d1f730$0$20302$c3e8da3@news.astraweb.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> Message-ID: <50af02ed0809052133s5f3ea925s90f8200fefda3582@mail.gmail.com> On Fri, Sep 5, 2008 at 11:45 PM, Steven D'Aprano wrote: > On Fri, 05 Sep 2008 22:20:06 -0400, Manu Hack wrote: > >> On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: > ... >>>> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >>>> >>>> It doesn't make sense to me. What do you set x to? >>> >>> For all x. >> >> But then how can you conclude sum([]) = 0 from there? It's way far from >> obvious. > > I think Castironpi's reasoning is to imagine taking sum([x])-x for *any* > possible x (where subtraction and addition is defined). Naturally you > always get 0. > > Now replace x by *nothing at all* and you get: > > sum([]) "subtract nothing at all" = 0 > > I think that this is a reasonable way to *informally* think about the > question, but it's not mathematically sound, because if you replace x > with "nothing at all" you either get: > > sum([]) - = 0 > > which is invalid (only one operand to the subtraction operator), or you > get: > > sum([0]) - 0 = 0 > > which doesn't involve an empty list. What castironpi seems to be doing is > replacing "nothing at all" with, er, nothing at all in one place, and > zero in the other. And that's what makes it unsound and only suitable as > an informal argument. Actually it's even more natural to state sum([x]) = x, and this way you can never conclude that sum([]) = 0 from there. From Scott.Daniels at Acm.Org Tue Sep 30 09:10:42 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 30 Sep 2008 06:10:42 -0700 Subject: Weirdness comparing strings In-Reply-To: References: Message-ID: Mr.SpOOn wrote: > Hi, > I have this piece of code: > > class Note(): Unless you _need_ old-style, use new style. > ... > def has_the_same_name(self, note): > return self == note Define equality (__eq__) if you want to compare for equality. > def __str__(self): > return self.note_name + accidentals[self.accidentals] > > __repr__ = __str__ If str and repr are to be equal, just define repr. class Note(object): def __init__(self, note, accidentals): self.note_name = note self.accidentals = accidentals def has_the_same_name(self, note): return self == note def __eq__(self, other): return isinstance(other, Note) and ( self.note_name == other.note_name and self.accidentals == other.accidentals) def __repr__(self): return self.note_name + accidentals[self.accidentals] --Scott David Daniels Scott.Daniels at Acm.Org From python at rgbaz.eu Wed Sep 10 12:25:19 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 18:25:19 +0200 Subject: md5 differences Message-ID: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> Hi there! I'm trying to match the results of an md5 checksum done in a tcsh shell. I keep getting different results and can't find anything on google... here's an example: Arno at Computer:~% echo "hello" | md5 b1946ac92492d2347c6235b4d2611184 Arno at Computer:~% python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import md5 >>> md5.new("hello").hexdigest() '5d41402abc4b2a76b9719d911017c592' How do I get the same results? thanks Arno From mark at thomaszone.com Wed Sep 17 08:54:27 2008 From: mark at thomaszone.com (Mark Thomas) Date: Wed, 17 Sep 2008 05:54:27 -0700 (PDT) Subject: Generating test data from an XML Schema References: Message-ID: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> On Sep 17, 5:29?am, Jonathan Fine wrote: > Hello > > I want to generate test data from an XML schema. ?I've had a quick look > at existing tools (such as minixsv and amara) but from what I've seen > they don't seem to help. ... > A tool that provides a nice Python interface to navigating the schema > would probably be quite helpful. > > Has anyone seen anything that might help generate test data from a schema? I'm unaware of anything in Python, but Eclipse can generate sample documents from a schema: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html As can XML IDEs such as Stylus Studio and XML Spy. -- Mark. From castironpi at gmail.com Tue Sep 16 16:53:48 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 13:53:48 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> Message-ID: On Sep 16, 3:16?pm, cnb wrote: > On Sep 16, 7:49?pm, "Aaron \"Castironpi\" Brady" > > > Now I have my personal programs in C:/Python25/Progs/ > > > > How do I add so that I can just do "import somefile" from anywhere in > > > that directory in the interpreter and it can load files from other > > > folders in that directory. > > > Add a file: \Lib\site-packages\locals.pth > > > with contents, path to the directory you want to add (/python25/progs/) > > And we have a winner! > > Now it works. Both doing import and loading form fiel with C-c C-l > > However jsut including C:/Python/Progs wasn't enough. I had to add the > folder inside that that contains the files i needed. > > so how do i add all files within progs? is there something like C:/ > python25/progs/* ? You have: c:/python/progs/abc/filea.py c:/python/progs/abc/fileb.py c:/python/progs/def/filed.py c:/python/progs/def/filee.py __init__.py in progs (empty...) __init__.py in abc __init__.py in def c:/python/site-packages/lib/locals.py which contains: c:/python/progs/ You don't need the subdirectories. You can do: import abc import abc.filea from abc import filea From randika.rathugama at gmail.com Wed Sep 17 15:03:50 2008 From: randika.rathugama at gmail.com (Randika) Date: Wed, 17 Sep 2008 12:03:50 -0700 (PDT) Subject: open Invitation to Join with DeveloperWiki Knowledge base Message-ID: <03e1c28b-cdcf-4091-884b-2c97058bea2c@a29g2000pra.googlegroups.com> Dear Developers,IT Professionals, "We are building a online encyclopedia for developers" and we need your contribution to make it even better. So here is our invitation for those who happy to contribute as editors, readers for the project. If you have written a tutorial/article/code snippet and would like to share it with others, you can publish it on DeveloperWiki and also you can Edit/Update any existing articles too. Please visit DeveloperWiki web site here http://DeveloperWiki.org Official discussion group. http://groups.google.com/group/DeveloperWikiUserGroup Thanks --DeveloperWiki Team From hussainsaiger at gmail.com Mon Sep 1 06:30:06 2008 From: hussainsaiger at gmail.com (hussainsaiger at gmail.com) Date: Mon, 1 Sep 2008 03:30:06 -0700 (PDT) Subject: Using NLTK in Java References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> <6i1hu9FnvcngU1@mid.uni-berlin.de> Message-ID: On 1 Sep, 11:55, "Diez B. Roggisch" wrote: > hussainsai... at gmail.com schrieb: > > > I am trying to convert a python module (that contains the use of > > NLTK.Corpus) by jythonc. It is not able to include nltk dependencies > > within the java class it creates. So when i use this class in java, it > > fails to recognize nltk. Can anyone please let me know how should i > > use nltk in python/jython modules so i can use in Java. > > If there are any binary dependencies, you are out of luck. It won't > work. You would need to write a RPC-Server then, with technologies such > as XMLRPC or CORBA. > > Diez So does that mean that Jython does not support nltk uptil now. I ask this because when I try to import nltk in Jython (which is assumed to replace Python), i get the same error. Its just nltk that I am not able to use. The rest of the jython functions and libraries work fine within Java. From wegwerp at gmail.com Sat Sep 13 12:00:12 2008 From: wegwerp at gmail.com (Bas) Date: Sat, 13 Sep 2008 09:00:12 -0700 (PDT) Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> Message-ID: <15035654-38f2-441f-a3ff-f4b943312f1c@m3g2000hsc.googlegroups.com> On Sep 13, 10:06?am, cnb wrote: > This must be because of implementation right? Shouldn't reduce be > faster since it iterates once over the list? > doesnt sum first construct the list then sum it? No, sum also iterates the sequence just once and doesn't create a list. It is probably implemented similar to def sum(sequence, start=0): it = iter(sequence) total = start for i in it: total += i return i but then implemented in C for speed. Reduce is probably implemented pretty similar, but then with a random function instead of addition. Make sure that you understand the difference between generator expression and list comprehension, and that [f(x) for x in something] is (almost) equal to list(f(x) for x in something), so you can emulate a LC by using the list constructor on the equivalent GE. HTH, Bas From grante at visi.com Wed Sep 3 10:14:03 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Sep 2008 09:14:03 -0500 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <6i56cpFor2puU1@mid.individual.net> Message-ID: On 2008-09-02, Christian Heimes wrote: > Fredrik Lundh wrote: >> Peter Pearson wrote: >> >>> (startled noises) It is a delight to find a reference to >>> that half-century-old essay (High Finance) by the wonderful >>> C. Northcote Parkinson, but how many readers will catch the >>> allusion? >> >> anyone that's been involved in open source on the development side for >> more than, say, ten minutes. > > Indeed! Thus speaks the experienced developer -- effbot :) > > On some mailing lists the bikeshed issue comes hand in hand with the > Dunning-Kruger-effect. [1] *sigh* > > Christian > > [1] http://en.wikipedia.org/wiki/Dunning-Kruger_effect That paper is really very interesting -- it explains a lot of what one sees in corporate life. -- Grant Edwards grante Yow! I just remembered at something about a TOAD! visi.com From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 24 03:26:10 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 09:26:10 +0200 Subject: Does anybody use this web framework ? In-Reply-To: <48d94cbc$0$964$ba4acef3@news.orange.fr> References: <48d94cbc$0$964$ba4acef3@news.orange.fr> Message-ID: <48d9eb86$0$6127$426a34cc@news.free.fr> Phil Cataldo a ?crit : > Hi, > > I just found this new? python web framework > (http://pypi.python.org/pypi/nagare/0.1.0). > > Does anybody know or use it ? First time I hear of it, but it looks interesting (note : Stackless continuation-based framework). Thanks for the link. From roy at panix.com Mon Sep 15 08:58:54 2008 From: roy at panix.com (Roy Smith) Date: Mon, 15 Sep 2008 08:58:54 -0400 Subject: Abstract class References: <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> Message-ID: Maric Michaud wrote: > The only way to do this is to call in the __init__ at least one of the > methods raising NotImplementedError, probably creating a dummy one for > this purpose, and still it doesn't satisfy with the constraint that > *all* abstract methods must be implemented in concrete classes. I wouldn't actually *call* the method (because of possible side-effects), but you could certainly check that they exist and are callable: class Base: """An abstract base class. You must define methods f(), g(), and h() in any subclasses of this. """ def __init__(self): try: assert callable(self.f) assert callable(self.g) assert callable(self.h) except: raise NotImplementedError # or something more specific Of course, this assumes that you write: class Derived(Base): def __init__(self): Base.__init__(self) There's no way (that I can think of :-)) to *force* you to call Base.__init__() from Derived.__init__(). This is all a bit silly, however. If you want type bondage, use a language that gives you type bondage (C++ and Java being two obvious examples). From upton at virginia.edu Mon Sep 15 13:07:41 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 15 Sep 2008 13:07:41 -0400 Subject: Parallelising code In-Reply-To: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: <5504f9ac0809151007n5710750cj3b75eea8da3e90c8@mail.gmail.com> > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? That probably depends on both how much data is involved in a "data point" (ie, is it just one value, or are you parsing several fields from the CSV per record), and how much processing each point involves. Profiling should enlighten you, yes. You may also have issues with I/O contention if you have lots of threads trying to read from disk at once, although I'm not sure how much of an impact that will have. > > - Is list.append() thread safe? (not sure if this is the right term) > what I mean is, can two separate processors file a point in the same > list at the same time without anything horrible happening? Do I need > to do anything special (mutex or whatever) to make this happen, or > will it happen automatically? http://mail.python.org/pipermail/python-list/2007-March/430017.html http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm From notvalid2 at sbcglobal.net Tue Sep 9 07:22:47 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 09 Sep 2008 04:22:47 -0700 Subject: Correcting for Drift between Two Dates In-Reply-To: References: Message-ID: <80txk.19556$LG4.2157@nlpi065.nbdc.sbc.com> Steven D'Aprano wrote: > On Mon, 08 Sep 2008 21:53:18 -0700, W. eWatson wrote: > >> I have two dates, ts1, ts2 as below in the sample program. I know the >> clock drift in seconds per day. I would like to calculate the actual >> date of ts2. See my question at the end of the program. > > > When faced with a complicated task, break it down into simpler subtasks. > Functions are your friends. Here you go: > > > > from __future__ import division > > from datetime import datetime as DT > from datetime import timedelta > > SITE_DRIFT = 4.23 # drift in seconds per day > # negative drift means the clock falls slow > SEC_PER_DAY = 60*60*24 # number of seconds per day > > > def calc_drift(when, base, drift=SITE_DRIFT): > """Return the amount of drift at date when since date base.""" > x = when - base > days = x.days + x.seconds/SEC_PER_DAY > return drift*days > > def fix_date(when, base, drift=SITE_DRIFT): > """Return date when adjusted to the correct time.""" > d = calc_drift(when, base, drift) > delta = timedelta(seconds=-d) > return when + delta > > > And here it is in action: > >>>> fix_date(DT(2008,9,9), DT(2008,9,8)) > datetime.datetime(2008, 9, 8, 23, 59, 55, 770000) > > > > I leave it to you to convert date/time strings into datetime objects. > > > Ah, ha. x.days and x.seconds. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From psaffrey at googlemail.com Mon Sep 15 12:46:18 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Mon, 15 Sep 2008 09:46:18 -0700 (PDT) Subject: Parallelising code Message-ID: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> I have some file processing code that has to deal with quite a lot of data. I have a quad core machine, so I wondered whether I could take advantage of some parallelism. Essentially, I have a number of CSV files, let's say 100, each containing about 8000 data points. For each point, I need to look up some other data structures (generated in advance) and append the point to a relevant list. I wondered whether I could get each core to handle a few files each. I have a few questions: - Am I actually going to get any speed up from parallelism, or is it likely that most of my processing time is spent reading files? I guess I can profile for this? - Is list.append() thread safe? (not sure if this is the right term) what I mean is, can two separate processors file a point in the same list at the same time without anything horrible happening? Do I need to do anything special (mutex or whatever) to make this happen, or will it happen automatically? Thanks in advance for any guidance, Peter From digitig at gmail.com Fri Sep 26 06:32:08 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 26 Sep 2008 11:32:08 +0100 Subject: problem updating variable in a module In-Reply-To: References: Message-ID: 2008/9/24 Terry Reedy : > With the mod/mod1 mixup fixed, you do not need the update function. > mod.a = 20 > should do the same thing. I was assuming that the update function was just to illustrate the access problem the writer was having. I think the chances are the problem is due to a typo or some such (happens to us all!) but without seeing the actual code there's not a lot we can do. -- Tim Rowe From hrishys at yahoo.co.uk Thu Sep 25 06:22:14 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 10:22:14 +0000 (GMT) Subject: Linq to Python In-Reply-To: Message-ID: <584583.16573.qm@web27405.mail.ukl.yahoo.com> Hi Roger I am impressed (i always suspected Python programmers are smart no doubt about it). But what about the case where they join different sources like the one here http://informationr.net/ir/13-2/TB0806.html Thanks for teaching me :-) i am thankful for that regards Hrishy > > names = ["Burke", "Connor", > "Frank", "Everett", > "Albert", "George", > "Harris", "David"] > > result = [each.upper() for each in names if len(each) == 5] > > result.sort() > > for each in result: print each > > > Yes clearly 'the Python crowd' must admit LINQ is > 'much better', I'm > sold, in fact off to download my "Free, but limited > editions of Visual > Studio 2005 for a single programming language supported by > .NET" right away! > > OK so maybe I'm being naive here but it looks to me > like this new > paradigm's big idea is to use a python + SQL type > syntax to access data > in random objects. Big whoop. It's not that difficult > to write a > generators that wraps XML files and databases is it? > > What am I missing here? > > > Roger Heathcote. > -- > http://mail.python.org/mailman/listinfo/python-list From karl.kobata at syncira.com Thu Sep 18 10:33:22 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Thu, 18 Sep 2008 07:33:22 -0700 Subject: fwd: member functions in a class Message-ID: <6gvfio$7tb3j8@rrcs-agw-01.hrndva.rr.com> Gary, No the answer is not too short, thank you for your reply, I am learning rapidly. Terry, The expanded answer is also useful. Now I am getting a better insight on how python resolves object attributes. This also gives me more insight on the difference between import vs from from *. Thanks karl -------------- next part -------------- An HTML attachment was scrubbed... URL: From superflit at gmail.com Tue Sep 9 14:04:05 2008 From: superflit at gmail.com (flit) Date: Tue, 9 Sep 2008 11:04:05 -0700 (PDT) Subject: check if the values are prensent in a list of values Message-ID: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> Hello All, I will appreciate the help from the more skillfull pythonistas.. I have a small app that generates a sequence like 00341 01741 03254 This values I am putting in a list. So I have a list = [00341,01741,03254] after the programs find the sequence 03401 this sequence is "new" so it appends on the list. But I want to avoid that as the values are already on the first sequence of the list (00341). If I try to use a "in" statement it will give false. as 00341 is different from 00341 (but for my goal not..) How can I check against this list and avoid to put "different" sequences but same values? as 34100 --> dont append on the list 14300 ---> dont append on the list 05321 --> append to the list. Am I doing some conceptual error using lists? There is a better approach? Thanks From castironpi at gmail.com Wed Sep 24 12:05:04 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 09:05:04 -0700 (PDT) Subject: PyRun_SimpleFile() crashes References: Message-ID: <26532f88-b70c-4b18-af4d-5176ec023f46@c65g2000hsa.googlegroups.com> On Sep 24, 6:30?am, Nick Craig-Wood wrote: > lixinyi... at gmail.com wrote: > > ?my code: > > ?main.cpp > > ?#include > > > ?int main(int argc, char **argv) > > ?{ > > ?Py_Initialize(); > > > ?FILE *file_1 = fopen("a2l_reader.py","r+"); > > ?PyRun_SimpleFile(file_1,"a2l_reader.py"); > > > ?Py_Finalize(); > > ?} > > > ?compile under windows using MinGW: > > ?g++ main.cpp libpython25.a -o a > > > ?no error was found. But when I run a.exe the program just crashes. > > > ?What should I do? > > Run it under gdb (which should have come with MinGW). > > Check that you actually opened the file, ie file_1 != 0. > > This might be relevant > > ?http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o... > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick There's a workaround. filename = "Entire path of the python file"; PyObject* PyFileObject = PyFile_FromString(filename, "r"); PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename); // decref PyFileObject http://mail.python.org/pipermail/python-list/2007-March/431725.html http://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567 From python at rgbaz.eu Wed Sep 10 13:51:36 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 19:51:36 +0200 Subject: md5 differences In-Reply-To: References: Message-ID: On 10 sep 2008, at 19:39, Grant Edwards wrote: > On 2008-09-10, Wojtek Walczak wrote: >> On Wed, 10 Sep 2008 19:12:28 +0200, Python wrote: >>> Arno at Computer:~% echo "test" > test.txt >>> >>> Arno at Computer:~% md5 test.txt >>> MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 >> >>>>>> import md5 >>>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >>> '90364ed45b452d43378629c20543a81d' >> >> >> Works for me: >> >>>>> import md5 >>>>> f = open('test.txt').read() >>>>> md5.new(f).hexdigest() >> 'd8e8fca2dc0f896fd7cb4cb0031ba249' >>>>> >> >> IOW, don't pass the path to the file to md5.new, but the contents >> of this file. >> >> The strange thing is that >>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. > > Same here. > > -- > Grant Edwards grante Yow! What PROGRAM > are they thanks everyone for helping me out! cheers Arno From gminick at bzt.bzt Mon Sep 1 09:41:25 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 13:41:25 +0000 (UTC) Subject: Eleganz way to get rid of \n References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: On Mon, 01 Sep 2008 15:25:03 +0200, Hans M?ller wrote: > I'm quite often using this construct: > > for l in open("file", "r"): > do something > Has someone a better solution ? The most general would be to use rstrip() without arguments: >>> a="some string\r\n" >>> a.rstrip() 'some string' >>> but be careful, because it will also cut whitespaces: >>> a="some string\t \r\n" >>> a.rstrip() 'some string' >>> so maybe you could do this: >>> a.rstrip('\n').rstrip('\r') 'some string\t ' >>> HTH. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From mensanator at aol.com Wed Sep 17 23:34:02 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 17 Sep 2008 20:34:02 -0700 (PDT) Subject: How to Determine Name of the Day in the Week References: Message-ID: <0928a498-1cc0-48c7-985e-4faf019d8a70@m3g2000hsc.googlegroups.com> On Sep 17, 10:20?pm, Keo Sophon wrote: > Fredrik Lundh wrote: > > Henry Chang wrote: > > >> Instead of getting integers with weekday(), Monday == 0 ... Sunday == > >> 6; is there a way to get the actual names, such as "Monday ... > >> Sunday"? I would like to do this without creating a data mapping. :) > > > if you have a datetime or date object, you can use strftime with the > > appropriate formatting code. see the library reference for details. > > > if you have the weekday number, you can use the calender module: > > > >>> import calendar > > >>> calendar.day_name[0] > > 'Monday' > > > (the latter also contains abbreviated day names, month names, and a > > bunch of other potentially useful functions and mappings.) > > > > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Hi, > > I've tried calendar.month_name[0], it displays empty string, while > calendar.month_name[1] is "January"? Why does calendar.month_name's > index not start with index 0 as calendar.day_name? Because there's no month 0? And technically, weeks begin on Sunday, not Monday, but business likes to think of Monday as day 0 of the week and it doesn't conflict with any prior date format. > > Thanks, > Sophon From cipherzero at gmail.com Sat Sep 6 21:16:54 2008 From: cipherzero at gmail.com (cipher) Date: Sat, 6 Sep 2008 18:16:54 -0700 (PDT) Subject: found a bug with smtpd, where can i report this? References: Message-ID: <5d2562b3-8825-43d3-b3aa-1b4fc10b9a72@x1g2000prh.googlegroups.com> On Sep 5, 4:01?am, "Marcus.CM" wrote: > Hi, > > Where should i report the bug? > smtpd bug. > > Marcus.CM http://bugs.python.org/ From steve at REMOVE-THIS-cybersource.com.au Tue Sep 30 19:54:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 23:54:18 GMT Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> <87hc7xqlnj.fsf@benfinney.id.au> Message-ID: <00f2b5d2$0$20617$c3e8da3@news.astraweb.com> On Wed, 01 Oct 2008 09:06:08 +1000, Ben Finney wrote: > Terry Reedy writes: > >> Steven D'Aprano wrote: >> > We agree that the restriction is artificial, and I think irrational >> > (although I'd be interested in hearing the gnuplot developers' >> > reasoning before making a final judgment). >> >> I believe it is a matter of preserving clarity of authorship, just as >> is the quoting mechanism we take for granted in posts like this. If I >> removed the quote marks above and silently edited what Ben and you >> wrote, I might upset someone and certainly could confuse readers. > > That, if it were to be prosecuted under law, would be a matter already > covered by laws other than copyright: fraud, libel, etc. > > Note that I consider a work free even if it fails to grant ?the right to > distribute misrepresentations of the author's words?, because that act > is an exercise of undue power over another person, and so falls outside > the limit imposed by the freedoms of others. But distributing modified source code *does* misrepresent the author's words, because you confuse authorship. Given only the modified version of the source code, how is the recipient supposed to identify which parts of the source code were written by the original authors and which parts where written by you? If that is why the gnuplot people do not allow you to distribute such modified documents, then the only "freedom" they fail to grant is exactly the one you don't consider necessary for a free licence: "the right to distribute misrepresentations of the author's words". -- Steven From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 30 05:26:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 30 Sep 2008 11:26:36 +0200 Subject: How best to pass arbitrary parameters from one function to another In-Reply-To: References: Message-ID: <48e1f0af$0$27506$426a74cc@news.free.fr> John O'Hagan a ?crit : > Hi Pythonistas, > > I'm looking for the best way to pass an arbitrary number and type of variables > created by one function to another. > > They can't be global because they may > have different values each time they are used in the second function. > > So far I'm trying to do something like this: > > > def process_args( [list, of, command-line, arguments] ): > > do stuff > return {dictionary : of, local : variables } > > def main_function( **kwargs ): > > do stuff > return result > > kw1 = process_args( [some, list] ) > kw2 = process_args( [a, different, list] ) > > for i in main_function( **kw1 ): > > kw2[ var1 ] = i > kw2[ var2 ] = len( i ) > > for j in main_function(**kw2): > > print j > > This only seems to work if I specify a default value for every possible > parameter of main_function and also for any others which may be passed to it, > which is a bit tedious because there are very many of them but only a few are > used in any given execution of the program. If this is about commmand line arguments parsing and defaults, you may want to have a look at the optparse package in the stdlib. Also, kwargs work fine with default arguments too, ie: def func(arg1=1, arg2='yadda', arg3=None): print arg1, arg2, arg3 for kw in ({}, {'arg1':42}, {'arg2':'yop', 'arg3' : range(5)}): func(**kw) HTH From castironpi at gmail.com Mon Sep 22 20:07:09 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 17:07:09 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <00e816f4$0$20303$c3e8da3@news.astraweb.com> <6602abad-3c12-4c0c-b41d-95f79cebdc31@y21g2000hsf.googlegroups.com> Message-ID: On Sep 22, 6:55?pm, MRAB wrote: > On Sep 22, 11:46?pm, "Aaron \"Castironpi\" Brady" > > > > wrote: > > On Sep 22, 5:32?pm, Steven D'Aprano > > cybersource.com.au> wrote: > > > On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: > > > > On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano > > > >> But that's precisely what I want to avoid: I don't want the objects to > > > >> ?share *any* state, not even their class. I'm not trying for a Borg or > > > >> ?Singleton: the user can call the factory as many times as they want, > > > >> ?but the objects returned shouldn't share any state. I don't know if > > > >> ?what I want has a name. Judging from people's reactions, I'd say > > > >> ?probably not. > > > > > Snce when are "users" ever involved > > > > in programming problems or programming languages ? > > > > What an astounding question. > > > > Consider a class. There are the programmers who write the class, and > > > there are the programmers (possibly the same people, but not necessarily) > > > who use the class. The second set of people, the programmers who use the > > > class, are *users* of the class. What else would they be? > > > > -- > > > Steven > > > Usegrammers? > > And professionals are programmers, amateurs are amgrammers and newbies > are newgrammers? :-) Not to be rude, but no. Usegrammers usegram. From marco.bizzarri at gmail.com Thu Sep 11 09:52:37 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 11 Sep 2008 15:52:37 +0200 Subject: Python and Open Office In-Reply-To: References: Message-ID: <3f0d61c40809110652x444c68d8kdf7eeb206accfaf3@mail.gmail.com> Greg, as an addition to what I already said to you, you can consider taking a look at oood from ERP5 project http://wiki.erp5.org/HowToUseOood OOOd (openoffice.org daemon) runs openoffice behind the scene, and allows you to interact with it via XML-RPC; it should be quite robust, since it is actively mantained and used in a big software project. And, also, it should be quite easy to extend in order to have your custom functions run via XML-RPC. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From castironpi at gmail.com Sat Sep 27 19:33:43 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 16:33:43 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <00ee05ca$0$20666$c3e8da3@news.astraweb.com> <1a7184f3-c71e-49b7-a8f8-f141705f3573@l42g2000hsc.googlegroups.com> Message-ID: On Sep 27, 6:16?pm, Terry Reedy wrote: > Aaron "Castironpi" Brady wrote: > >>>> class A(type): > > ... ? ? def __call__( self, *ar ): > > ... ? ? ? ? ? ? print 'call', self, ar > > ... > >>>> class B(object): > > ... ? ? __metaclass__= A > > ... > >>>> B(3) > > call (3,) > > > Overriding the __call__ method of 'type' has the effect of giving you > > a static __call__ method on a class-- a method which doesn't need an > > instance to call. ?Your behavior may be counterintuitive though, to > > someone who wants to instantiate 'B', in this case, and proceed like a > > normal object. ?That is, they want to call a generic class and use it, > > and also expect instances of B to behave as B. ?You can't have both, > > so either return B from B.__new__, or, to instantiate B, take the long > > way and call B.__new__ directly. > > >>>> B.__new__(B) > > <__main__.B object at 0x009FDB70> > > > Has anyone stepped through the C code to find out when the decision is > > made to call which function, B.__new__ or A.__call__, when B is > > called? ? > > For Python coded objects, ob(*args) in code translates to internal > execution of type(ob).__call__(ob, *args) (without further > translation!). ?The interpreter compiles a statement at a time, without > looking back to do type inferencing, and so does not know what type is > being called or if it is even callable. > > For B, B(*args) == type(B).__call__(B, *args) == A.__call__(B, *args). > So there is no decision. > > For C coded objects, I believe ob(*args) in Python code translate to a C > call of the C equivalent of type(ob).tp_call (or something like that). > ?From observation, type.tp_call acts something like this: > > def __call__(cls, *args): > ? ?if cls == type: > ? ? ?if len(*args): > ? ? ? ?return arg[0].__class__ > ? ? ?elif len(*args) == 3: > ? ? ? ?return type.__new__(type, *args) # or maybe not pass type? > ? ? ?else: > ? ? ? ?raise TypeError('type() takes 1 or 3 arguments') > ? ?else: > ? ? ?return cls.__new__(cls, *args) > > So, for a normal class C (an instance of type), type.__call__ calls > C.__new__. > > Terry Jan Reedy Oh, I see. Then it's the class statement that calls type.__new__. class A: ... -> A= type( 'A', ... ) -> A= type.__call__( type, 'A', ... ) -> A= type.__new__( type, 'A', ... ) Plus an iteration over the contents of 'namespace', to search for properties that themselves have a __get__ method. And returns an unboundmethod instance "of" it, for a value of "of" that's hard to concentrate on. I jest. Perhaps what Steven is looking for is a subclass of 'type' that does not give this default behavior of 'unboundmethoding' everything it can. That is, defaulting to 'staticmethod' or 'classmethod', and perhaps offering a 'boundmethod' decorator for the exceptions. For the case of '__call__', which he does want to control, that could merely call B.__call__, instead of B.__new__. Untested: >>> class A(type): ... def __call__( self, *ar ): ... return self.__call__( *ar ) or ... return self.__call__( self, *ar ) Which would come through to 'B' as: >>> class B(object): ... __metaclass__= A ... def __call__( cls, *ar ). This is because self == B in the example. This makes me scowl. Very odd. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 18 09:30:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 13:30:47 GMT Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <00e2520b$0$20331$c3e8da3@news.astraweb.com> On Thu, 18 Sep 2008 05:25:02 -0700, Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a certain > geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) Here's a better version of your algorithm, one which avoids the minor inefficiencies but keeps the huge inefficiency: for node1 in IN: for node2 in IN: if node1 is not node2: if node1.coordinates == node2.coordinates: SN.append(node1.label) This assumes that node.coordinates is a type where equality is defined. If they are a tuple or list, that should work fine. But the huge inefficiency is that you are checking each node not once, not twice, but 100,000 times! So you have to iterate 10,000,000,000 times, which is going to be slow no matter what you do. Especially in pure Python. Here's a better idea: iterate over the list once only: seen = set() for node in IN: coords = tuple(node.coordinates) if coords in seen: SN.append(node.label) else: seen.add(coords) Hope this helps. -- Steven From grante at visi.com Wed Sep 10 22:36:36 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 21:36:36 -0500 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> Message-ID: On 2008-09-10, Ben Finney wrote: > Grant Edwards writes: > >> Could whoever is responsible for the gateway that is grabbing >> my postings off of Usenet and e-mailing them out please fix the >> headers in the mail messages so that I don't get the bounce >> messages? > > The bounce messages are sent to you because you sent the > original. Wrong. I didn't send _any_ e-mail. Why should I get bounce messages? Isn't sending e-mails pretending they're from somebody else considered unethical (if not illegal)? >> Its a bit rude to send out mass e-mail messages with headers >> faked up so that the bounce messages go to somebody else. > > Indeed it is rude, and the person subscribed to the mailing > list whose software is sending these bounce messages is the > one responsible for making it stop. No, the one who's sending e-mail with forged headers is the one who ought to make it stop. That e-mail was not from me. It was from somebody who grabbed the article off a usenet server and mailed it to a bunch of people. > The mailing list software can't help (nor can the news-to-mail > gateway). > > In the meantime, the usual fix is for the list administrator > to unsubscribe the offending party (the one sending automated > bounce messages). I think the list administrator ought to stop putting other people's e-mail addresses in the From: headers of e-mails he's sending. -- Grant From m_palmer45 at yahoo.ca Tue Sep 16 16:20:03 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 16 Sep 2008 13:20:03 -0700 (PDT) Subject: find the path of a module References: <7f3f0dce-52bd-45d3-87f1-2f9aa695e080@c58g2000hsc.googlegroups.com> Message-ID: <04de9da6-059d-4eac-8672-9ef22c8a0dba@c65g2000hsa.googlegroups.com> On Sep 16, 4:07 pm, vvangelov... at gmail.com wrote: > I'd like to know if I can somehow find the path for a module somewhere > in a the package hierarchy > for instance if I import my module like so > from spam.eggs import sausage > my hypothetical method would return something like > '/home/developer/projects/spam/eggs/sausage.py/c' > given that module object. The __file__ attribute is what you want: >>> import pyPdf >>> pyPdf.__file__ '/data/python/pyPdf/__init__.pyc' >>> From steve at REMOVE-THIS-cybersource.com.au Mon Sep 29 19:26:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Sep 2008 23:26:25 GMT Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> Message-ID: <00f15dd2$0$20617$c3e8da3@news.astraweb.com> On Mon, 29 Sep 2008 05:41:02 -0700, George Sakkis wrote: > For example I would be much less > opposed to len() being defined as, say, |x| if "|...|" was a valid > operator. Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians and physicists. *wink* Actually there's a serious point there. There aren't that many unambiguous operators that are available on a standard keyboard that (nearly) everyone can agree on. -- Steven From callen314 at gmail.com Tue Sep 23 17:28:00 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 23 Sep 2008 14:28:00 -0700 (PDT) Subject: Why are "broken iterators" broken? References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: <6eb35e11-4799-495f-8469-fd03278e97b3@o40g2000prn.googlegroups.com> I'm interested what others think of this because at first I couldn't get it... I have an object which can iterate over its parts... and at first I thought, what? I'm supposed to create a new object every time the user needs to iterate the contents? In the end I interpreted that statement as if "unless __iter__()" is called again, in which case it makes sense that an iterator should stay "finished" until it's told to start to iterate again. Then even the stream analogy holds, you don't expect a stream to say EOF then start giving you bytes (from beyond the end, I guess)... instead, such a stream would more likely block if it got to the end of available data. I'm probably being stupid in this... perhaps I'm the only one that at first interpreted the phrase as being regardless of a fresh call to __iter__()... and that the OP was worried about some other implication. But if I was wrong to think it's ok for one and the same iterator to reset when __iter__() is called again, then I seriously don't understand. what does "forever" mean in that dictum? From grante at visi.com Wed Sep 24 22:33:02 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 24 Sep 2008 21:33:02 -0500 Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: On 2008-09-25, Larry Bates wrote: > Marin Brkic wrote: >> Not commercial distribution, but an academic kind of sorts - giving >> the exe file to coleagues, so they can use it in their work. Giving >> .py file is not an option, since due to centralized computer >> maintenance, they don't (and cannot) have installed python (except the >> ones that bring their own computer at work, but those are an >> exception). >> >> As far as I know py2exe is the only option which can do such a thing >> (make exe files from scripts). Is there a way to make those exe files >> a little smaller (for a small script they easily go up to 5-10 mb). > Times have changed, 5-10Mb is REALLY small. Flash drives hold 4000-8000Mb > for less than $20 and standard hard drives are now 500Gb. IMHO you are > concerned about a problem that doesn't actually exist. But what if he wants to distribute his program on a floppy disk? ;) [I think only 1 of my 5 machines has a floppy drive, and the last time I tried to use it, it didn't work. I did have a usb-floppy drive somewhere, but I think somebody borrowed it a couple years ago and never returned it.] -- Grant From kaerbuhez at gmail.com Fri Sep 19 05:00:20 2008 From: kaerbuhez at gmail.com (kaer) Date: Fri, 19 Sep 2008 02:00:20 -0700 (PDT) Subject: Python newbie References: Message-ID: <07440406-96d4-406e-8a4f-11576663f5f2@k13g2000hse.googlegroups.com> On 19 sep, 10:13, Steven D'Aprano wrote: > On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote: > > I am a Python newbie who decided to see what that Python fuss is all > > about. Quite frankly, I am a bit perplexed., here is what perplexes me: > > perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' > > Naturally you will be perplexed if you assume that Python is just Perl > with a more verbose syntax. It isn't. > Indeed, it isn't ... at all: $ python -c 'for s in [2*x for x in (1, 2, 3)]: print s' 2 4 6 And it's always (a lot) more readable :-) kb From fredrik at pythonware.com Mon Sep 15 10:42:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 16:42:49 +0200 Subject: Abstract class In-Reply-To: <200809151409.14149.maric@aristote.info> References: <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> <200809151409.14149.maric@aristote.info> Message-ID: Maric Michaud wrote: > But this doesn't match what abstract classes are (in C++ for example) you're confusing concepts with specific implementations of those concepts here. From neoedmund at gmail.com Fri Sep 5 07:05:44 2008 From: neoedmund at gmail.com (neoedmund) Date: Fri, 5 Sep 2008 04:05:44 -0700 (PDT) Subject: newbie question: how to run a python file if it is in a package Message-ID: for example: X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y" how can I run X.py avoiding it saying such like "ImportError: No module named aaa.bbb"? Is all runnable script must be in the default package? thanks. From steven at REMOVE.THIS.cybersource.com.au Tue Sep 2 02:56:24 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 06:56:24 GMT Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> <878wubp5mz.fsf@benfinney.id.au> Message-ID: On Mon, 01 Sep 2008 22:11:13 -0700, Dennis Lee Bieber wrote: > On Tue, 02 Sep 2008 13:51:16 +1000, Ben Finney > declaimed the following in > comp.lang.python: > >> This is no more the case than for literal strings: >> >> a = "spam" "eggs" "ham" >> >> a = "spam", "eggs", "ham" >> > But... Literal string still have the " (or ') delimiters around the > components. Such does not exist for you example with integers. > > Consider > > a = "spam, eggs", "ham" > vs > a = "spam, eggs" "ham" Quite frankly, I think that it's a stretch to say that leaving out a tuple delimiter is a problem with whitespace inside numeric literals. That's hardly unique to whitespace: atuple = 5,6,7,8 vs atuple = 5,67,8 Look Ma, no whitespace! But even if allowing whitespace inside numeric literals did create a new avenue for errors which never existed before, it is a mistake to only consider the downside without the upside. In my opinion, that would be rather like declaring that the syntax for attribute access is a mistake because you might do this: x = MyClass() xy = 4 instead of this: x = MyClass() x.y = 4 At some point the programmer has to take responsibility for typos instead of blaming the syntax of the language. I agree that we should avoid syntax that *encourages* typos, but I don't believe that allowing whitespace inside numeric literals does that. -- Steven From dmitrey.kroshko at scipy.org Mon Sep 15 14:37:00 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 15 Sep 2008 11:37:00 -0700 (PDT) Subject: ANN: OpenOpt 0.19 (free optimization framework, Python language) Message-ID: Hello, We're pleased to announce: OpenOpt v 0.19, free (license: BSD) optimization framework (written in Python language) with connections to lots of solvers (some are C- or Fortran-written) is released. Changes since previous release 0.18 (June 15, 2008): * Some changes for NLP/NSP solver ralg (especially related to handling linear constraints Ax <= b, Aeq x = beq, lb <= x <= ub) * Bugfix for ralg and IPOPT linear constraints handling * ALGENCAN v 2.0.x has been connected (v 1.0 is no longer supported, v 2.0.3 or later is required) * Bugfix for constrained NLSP graphic output (constrained nssolve isn't turned to latest ralg version yet) * Scale parameter for lpSolve (p.scale = {False} | True | 0 | 1) * New OO class LLAVP (linear least absolute values aka linear least deviations) * Improved handling of non-linear functions with restricted dom * GLP (global) solver galileo now can handle integer problems (via p.useInteger = 1 or True) * Another one GLP (global) solver connected: pswarm * Lots of work related to oofun concept (see OO Doc page for details) * Add converters llsp2nlp, llavp2nsp * Convenient handling of maximization problems (via p.goal = 'max' or 'maximum') * Some code clean up and bugfixes Backward incompatibility: * Changed objective function in LLSP * MATLAB-style gradtol renamed to gtol (for to provide same syntax to scipy.optimize fmin_bfgs, fmin_cg and less-to-type) Newsline: http://openopt.blogspot.com/ Homepage: http://scipy.org/scipy/scikits/wiki/OpenOpt Regards, OpenOpt developers. From grante at visi.com Tue Sep 16 09:47:04 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:47:04 -0500 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: On 2008-09-16, Armin
wrote: > John Machin wrote: >> On Sep 16, 6:45 am, Armin wrote: >> >>> Yes, but this is very unconvenient. >>> If d should reference the list a extended with a single list element >>> you need at least two lines >>> >>> a.append(7) >>> d=a >>> >>> and not more intuitive d = a.append(7) >> >> Methods/functions which return a value other than the formal None and >> also mutate their environment are "a snare and a delusion". Don't wish >> for them. > > > > c = [9,10] > [1,2,3,4,7].append(c) -> Is this a valid expression? Yes. > The 'value' of that expression is None. Correct. > However ... that's the way of the implementation of the > append method. It's a little bit confusing to me ... No, that's a way of calling the append method of a list. The fact that you don't have a name bound to that list doesn't change the fact that the list is mutable and you appended [9,10] to it. -- Grant Edwards grante Yow! Are the STEWED PRUNES at still in the HAIR DRYER? visi.com From bearophileHUGS at lycos.com Sat Sep 6 17:50:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 6 Sep 2008 14:50:54 -0700 (PDT) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Andreas Hofmann, there are several problems in your code: > if type(value) is str: Better to use isinstance() and to compare it with basestring instead. > value.upper() This does nothing, python strings are immutable, so they don't get changed in-place, so you have to assign that result to some name, possibly a different name. I also suggest you to strip the uppered string, to remove head/tail spaces. Your indenting isn't much good, I suggest you to use only four spaces for each indent (you can also use one tab, but I don't suggest this). > if value.endswith('K'): > mult = 1000 > elif value.endswith('M'): > mult = 1000000 > elif value.endswith('G'): > mult = 1000000000 > else: > mult = 1 This is okay. You can also put those key-values in a dict, that you can access with the get method with a default 1, but it may be overkill. > if mult is 1: > value = string.atoi(value) > else: > value = string.atoi(value[:-1]) * mult > return value Instead of using string.atoi, use the int() builtin. If you follow my suggestions you will have a function that works in many situations. It will raise exceptions in other situations, but that's good. But to not need much of our help in your future code I suggest you to use the Python shell and test every line you write. I also suggest you to start right now using tests, for example like this: def eliminate_postfix(value): """ >>> el_post = eliminate_postfix >>> el_post(1) 1 >>> el_post("100") 100 >>> el_post("") Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '' >>> el_post("100g") 100000000000L >>> el_post("100G ") 100000000000L >>> el_post("100 G ") 100000000000L >>> el_post("100hg") Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '100H' >>> el_post(" 100 k ") 100000 >>> el_post(" 100m") 100000000 >>> el_post(u"100m") 100000000 """ ... function code ... if __name__ == "__main__": import doctest doctest.testmod() print "Doctests done.\n" That will improve your coding a LOT, reducing your bug count, etc. Bye, bearophile From paul at boddie.org.uk Tue Sep 16 05:16:12 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 16 Sep 2008 02:16:12 -0700 (PDT) Subject: Parallelising code References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: <676c9d65-5bc7-44c4-9e61-6f7ed2b3c58c@d77g2000hsb.googlegroups.com> On 15 Sep, 18:46, "psaff... at googlemail.com" wrote: > I have some file processing code that has to deal with quite a lot of > data. I have a quad core machine, so I wondered whether I could take > advantage of some parallelism. Take a look at this page for some solutions: http://wiki.python.org/moin/ParallelProcessing In addition, Jython and IronPython provide the ability to use threads more effectively. > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? There are a few things to consider, and it is useful to see where most of the time is being spent. One interesting exercise called "Wide Finder 2", run by Tim Bray (see [1] for more details), investigated the benefits of log file processing using many concurrent processes, but it was often argued that the greatest speed-up over a naive serial implementation could be achieved by optimising the input and output and by choosing the right parsing strategy. Paul [1] http://www.tbray.org/ongoing/When/200x/2008/05/01/Wide-Finder-2 From tjreedy at udel.edu Tue Sep 16 13:54:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 13:54:45 -0400 Subject: Python GUI for animation In-Reply-To: <48CF522F.40402@it.uu.se> References: <48CF522F.40402@it.uu.se> Message-ID: Virgil Stokes wrote: > I have been using Python for a short time and I find it a very flexible > language, and easy to learn and use. I have also worked some with PyGame > and used it to create a simple animation that is controlled by the mouse > and keyboard. The animation is designed to move filled circles around on > the screen and is driven by a data file that defines (indirectly), the > next relative position of each circle. And for my purposes (queueing > demo in the classroom) this works quite well. However, I would now like > to create a Python GUI that would allow a user to control the animation, > via buttons, sliders, etc. > > I am certainly not a Python expert and have never worked with the > creation of a GUI. I would appreciate greatly any advice from those who > have worked with Python GUIs as to the best way to proceed. There have been discussions on the PyGame mailing lists about the merits of different gui options for use specifically with pygame. There may be something at the site, or archives there. News.gmane.org should also have an archive for the gmane.comp.python.pygame mirror. From gagsl-py2 at yahoo.com.ar Tue Sep 30 02:16:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 03:16:11 -0300 Subject: PID management with popen and spawn References: <73195b54-8836-43f7-ba30-76eb408ccc4a@k37g2000hsf.googlegroups.com> Message-ID: En Thu, 25 Sep 2008 12:36:00 -0300, EEK escribi?: > My goal is to start and stop separate Linux processes from a python > program by specific PID. The output of these processes needs to have > their stderr and stdout piped to a particular file, respectively. > > I've been able to make this work with subprocess.Popen only if the > shell variable is set to False but I cannot pipe the outputs of the > targets. > > When using subprocess.Popen with shell=True, I believe the returned > PID is of the shell that opens the target process, not the target > process itself. Therfore, I cannot stop the target process for the > returned PID is not of that process. Exactly. > prgm = program I want to run (compiled C) > logfile = file I want to pipe output to > > What I need to do based on a simple shell call: program >& logfile > (yes, that's it) Use the stdout and stderr arguments. Something like this (untested): f = open(logfile, "w") proc = subprocess.Popen(["program","with","arguments"], stdout=f, stderr=f) -- Gabriel Genellina From bjourne at gmail.com Wed Sep 3 08:50:57 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 3 Sep 2008 14:50:57 +0200 Subject: How to write verbose scripts In-Reply-To: <001901c90e06$44e327e0$0d00a8c0@hendrik> References: <001901c90e06$44e327e0$0d00a8c0@hendrik> Message-ID: <740c3aec0809030550r446779adt3b0146a3959983e3@mail.gmail.com> 2008/9/3 Hendrik van Rooyen : > > Steven D'Aprano wrote: > >>Is there a better way of doing this than the way I am going about it? > > Not sure if its "better", but I would keep the messages in a table or dict and > have different tables or dicts for different levels of verbosity, and write a > displayer that knows about the verbosity - This approach has the advantage that > you can write in English and have different verbosities in different languages > too, if the displayer knows about the language. One big downside with that approach is that it becomes much harder to grep for the log message. Usually when I go through logs, I don't care what exactly the message says, just that it is easily googleable (uses some kind of identifying text) and that it is unique so I can know exactly where it was emitted. -- mvh Bj?rn From pavlovevidence at gmail.com Tue Sep 23 04:38:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 23 Sep 2008 01:38:56 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: <4960c97a-cc5e-412d-ba83-2a2d168dfa2c@a70g2000hsh.googlegroups.com> On Sep 22, 9:13?pm, process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? The main technical difficulty is that the compiler has to know whether the function returns a tail call or not at compile time. But because Python is fully dynamic with regard to type, the compiler never(**) knows anything about any object other than "it's an object". The compiler doesn't even know if the object is callable. Probably it would be possible to achieve this optimization without involving the compiler, but it'd be at cost of great complexity and probably would negatively affect ordinary function calls (which are already slow enough). (BTW, if you're just talking about converting simple tail-recursive functions, and not about general tail-call optimization, then I'd suggest a third-party package would be better for that, since it would be a pretty complex thing that would benefit only a tiny fraction of users.) Carl Banks (**) Actually the compiler can do some compile-time constant expression folding, but that's about it. Otherwise it's object agnostic. From half.italian at gmail.com Wed Sep 10 20:21:46 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 10 Sep 2008 17:21:46 -0700 (PDT) Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... References: <276719.72706.qm@web95107.mail.in2.yahoo.com> Message-ID: <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> On Sep 10, 3:33?pm, "Daniel Fetchinson" wrote: > > I know I'm tooooo late to ask you for help....but please help me out..I > > am really new to unix and dont know how to finish this assignment on > > time.....proff. said he will be using MOSS to detect whether I > > downloaded the code..please help me.. > > > email me : vaidehi.pa... at yahoo.co.in > > > Assignment 1 > > Processes, Inter-Process Communication, and Concurrency > > Due September 13th midnight > > Summary > > In > > this assignment, you will create two versions of a simple multi-process > > game : one without and another with inter-process synchronization. You > > will also measure the relative performance of the two versions of your > > multi-process game. > > Objectives > > > ? ? * Learn how to create and terminate processes. > > ? ? * Learn use of inter-process communication using shared memory, > > semaphores, signals, etc. > > ? ? * Learn the basic workings of CPU scheduling code in Linux. > > > Part A: Multi-Process Game of Turns > > > In > > this part, you are asked to write a simple program that takes two > > command-line arguments P and N. The main process creates P other child > > processes, waits for all of them to complete, and then exits. All the > > child processes form one logical ring among each other. (In rest of the > > description, the term "process" refers to a "child process".) For > > example, if the processes are numbered 1 to P, then > > > ? ? * The next neighbor of process 1 is process 2, > > ? ? * The next neighbor of process i is process i+1 for all i < P , and > > ? ? * The next neighbor of process P is process 1, which completes a ring > > among the processes. > > > Assume > > that a shared integer variable, called turn, identifies the number of > > the processes whose turn it is at any instant. A second process-local > > variable in each process, called me, identifies the identity of each > > process (i.e. each process stores its own identity in a per-process > > local variable me). A third per-process local variable, called next, > > identifies the next process in the ring. > > > The processes > > sequentially pass the turns among each other in the logical ring. When > > each process gets its turn, it increments another shared variable > > called counter. The pseudo-code within each process for passing turns > > might look something as follows. (Note: Replace turn and counter below > > with appropriate ways of accessing data within shared memory regions). > > > ? ? while(turn != me ) > > ? ? ? ? /* do nothing - just busy loop*/ ; > > > ? ? /* got my turn - increment counter */ > > ? ? counter = counter + 1; > > > ? ? /* give the turn to next process */ > > ? ? turn = next; > > > The program terminates when the each process has received N turns. > > > In the above description, several programming details have been omitted for > > you to figure out. This includes > > > ? ? * Creating P child processes from main process. > > ? ? * Constructing the logical ring among child processes. > > ? ? ? ? ? o Initializing each child process's identity in the me variable. > > ? ? ? ? ? o Initializing each child process' next neighbor in the next > > variable. > > ? ? * Initializing the shared memory region and the shared data values. > > ? ? * Have the main process wait for child processes to complete N turns > > before exiting. > > > Part B: More Efficient Game of Turns > > > You > > might notice that the program you wrote in Part A is inefficient > > because each process busy loops till the CPU scheduler kicks it out > > (after its time-slice is over) and allows another process to execute > > and make progress. (Does the program in Part A have a race condition? > > Why or why not?) > > > What we ideally want is that each process > > should be given control of the CPU only when it is that process' turn. > > Modify the program you wrote in Part A (using appropriate > > synchronization mechanisms) such that each process gets to run (i.e., > > gets control of the CPU) only when it is that process's turn, and at no > > other time. > > > Again, you would need to work out the programming details of how and where > > to use inter-process synchronization. > > Part C: Profiling the Game of Turns > > > In > > this part, you are asked to write user-level profiling code in order to > > measure the performance of the two versions of programs you wrote in > > Part A and Part B. Use a combination of gettimeofday() system call and > > inter-process synchronization to measure (1) the average hand-over time > > between two consecutive processes in the ring and (b) the total > > execution time to complete N turns. Plot the measured values as graphs > > when varying number of processes P and number of turns N. Explain the > > results you obtain. > > Submission Guidelines > > > Thanking you, > > > Ms. Vaidehi Pawar > > How much do you pay? > > Cheers, > Daniel > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown Maybe. If I cant sleep tonite. From ggpolo at gmail.com Mon Sep 1 21:34:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 1 Sep 2008 22:34:39 -0300 Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp In-Reply-To: References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Message-ID: On Mon, Sep 1, 2008 at 10:09 PM, akineko wrote: > On Sep 1, 5:52 pm, "Guilherme Polo" wrote: > >> Are you trying to simulate clicks ? You should be doing it using >> event_generate, more below. >> > > Actually, I was trying to implement a "sticky" button. > (Button Release is done later by another event) > > I already tried event_generate. > It worked as far as I didn't touch other widgets. > But somehow it failed to work if event_generate is called after other > widgets are activated. > >> You should expect them to be totally removed from Tkinter actually. > > Sad to hear that. Controlling the button behaviour explicitly may not > be a common thing to do but it is still necessary thing to do. But you > gave me enough insights. This is an illusion you have, calling those methods are not the way for explicitly controlling button's behavior, not more than generating proper events. The explicit way is to not use a button, instead (ab)use Canvas. > > Aki- > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From gatti at dsdata.it Sat Sep 20 12:03:30 2008 From: gatti at dsdata.it (Lorenzo Gatti) Date: Sat, 20 Sep 2008 09:03:30 -0700 (PDT) Subject: XML-schema 'best practice' question References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: <9e3134c1-91ae-4c93-9f4d-1c47f8185b44@a70g2000hsh.googlegroups.com> On 20 Set, 07:59, Frank Millman wrote: > I want to introduce an element of workflow management (aka Business > Process Management) into the business/accounting system I am > developing. I used google to try to find out what the current state of > the art is. After several months of very confusing research, this is > the present situation, as best as I can figure it out. What is the state of the art of existing, working software? Can you leverage it instead of starting from scratch? For example, the existing functionality of your accounting software can be reorganized as a suite of components, web services etc. that can be embedded in workflow definitions, and/or executing a workflow engine can become a command in your application. > There is an OMG spec called BPMN, for Business Process Modeling > Notation. It provides a graphical notation [snip] > there is no standard way > of exchanging a diagram between different vendors, or of using it as > input to a workflow engine. So BPMN is mere theory. This "spec" might be a reference for evaluating actual systems, but not a standard itself. > There is an OASIS spec called WS-BPEL, for Web Services Business > Process Execution Language. It defines a language for specifying > business process behavior based on Web Services. This does have a > formal xml-based specification. However, it only covers processes > invoked via web services - it does not cover workflow-type processes > within an organisation. To try to fill this gap, a few vendors got > together and submitted a draft specification called BPEL4People. This > proposes a series of extensions to the WS-BPEL spec. It is still at > the evaluation stage. Some customers pay good money for buzzword compliance, but are you sure you want to be so bleeding edge that you care not only for WS- something specifications, but for "evaluation stage" ones? There is no need to wait for BPEL4People before designing workflow systems with human editing, approval, etc. Try looking into case studies of how BPEL is actually used in practice. > The BPMN spec includes a section which attempts to provide a mapping > between BPMN and BPEL, but the authors state that there are areas of > incompatibility, so it is not a perfect mapping. Don't worry, BPMN does not exist: there is no incompatibility. On the other hand, comparing and understanding BPMN and BPEL might reveal different purposes and weaknesses between the two systems and help you distinguish what you need, what would be cool and what is only a bad idea or a speculation. > Eventually I would like to make sense of all this, but for now I want > to focus on BPMN, and ignore BPEL. I can use wxPython to design a BPMN > diagram, but I have to invent my own method of serialising it so that > I can use it to drive the business process. For good or ill, I decided > to use xml, as it seems to offer the best chance of keeping up with > the various specifications as they evolve. If you mean to use workflow architectures to add value to your business and accounting software, your priority should be executing workflows, not editing workflow diagrams (which are a useful but unnecessary user interface layer over the actual workflow engine); making your diagrams and definitions compliant with volatile and unproven specifications should come a distant last. > I don't know if this is of any interest to anyone, but it was > therapeutic for me to try to organise my thoughts and get them down on > paper. I am not expecting any comments, but if anyone has any thoughts > to toss in, I will read them with interest. 1) There are a number of open-source or affordable workflow engines, mostly BPEL-compliant and written in Java; they should be more useful than reinventing the wheel. 2) With a good XML editor you can produce the workflow definitions, BPEL or otherwise, that your workflow engine needs, and leave the interactive diagram editor for a phase 2 that might not necessarily come; text editing might be convenient enough for your users, and for graphical output something simpler than an editor (e.g a Graphviz exporter) might be enough. 3) Maybe workflow processing can grow inside your existing accounting application without the sort of "big bang" redesign you seem to be planning; chances are that the needed objects are already in place and you only need to make workflow more explicit and add appropriate new features. Regards, Lorenzo Gatti From steve at REMOVE-THIS-cybersource.com.au Fri Sep 26 19:43:57 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 23:43:57 GMT Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> <00b839d9-fe35-4478-aba2-0435fbf285e8@m36g2000hse.googlegroups.com> Message-ID: <00ed6d83$0$20666$c3e8da3@news.astraweb.com> On Fri, 26 Sep 2008 14:54:36 -0700, Carl Banks wrote: > However, it seems from the rest of your comments that speed is your main > concern. Last time someone reported __slots__ didn't make a big > difference in access time, but it probably would speed up creating > objects a bit. Carl probably knows this already, but for the benefit of the Original Poster: __slots__ is intended as a memory optimization, not speed optimization. If it speeds up creation, that's a serendipitous side-effect of using less memory. > Of course, you should profile it to make sure. Absolutely. Can I ask the OP how large is "large" in the Large Data Sets? What seems large to people is often not large at all a modern computer. -- Steven From deets at nospam.web.de Thu Sep 18 11:31:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Sep 2008 17:31:27 +0200 Subject: unicode in multi-line strings References: Message-ID: <6jfainF31rvrU1@mid.uni-berlin.de> Jiri Barton wrote: > Hello, > > I have a problem with international characters in multi-line strings. > > > Works: '''?''' > > Works: ''' > a''' > > Does not work: ''' > ?''' > > > By does not work I mean the infamous > > 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not > in range(128) > > I'm using Ubuntu 8.04 with Python 2.5. It does not work in terminal, > from scripts, or from scripts with the encoding specified at the top. > Making the string unicode (u''' ... ''') does not change anything. > > It could be an interpreter issue but I didn't know where else I should > turn for help. Please show a self-contained example that does not work. The above won't puke on you as you claim - because they are simple byte-strings, and thus aren't subject to any automatic en/decoding whatsoever, unless somehow *used*. Which you don't show how you do it. Diez From castironpi at gmail.com Fri Sep 26 14:01:44 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 11:01:44 -0700 (PDT) Subject: Building truth tables References: Message-ID: <3c615d52-fbd4-4ab3-9efe-fbadc60bf414@x41g2000hsb.googlegroups.com> On Sep 26, 11:40?am, "Tim Rowe" wrote: > 2008/9/26 andrea : > > > Well I would like to make a little program that given a certain > > logical expression gives the complete truth table. > > > It's not too difficult in fact, I just have some doubts on how to > > design it. > > > I thought something like that: > > > class Term: > > > class Table: > > > ? def and(... > > ? def or(... > > As a quick and dirty solution, I'd write a function that takes a > function as a parameter. > > Starting with a helper function to separate the bits of an integer > into a list of bools: > > def int_to_bool(i, bits): > ? ? ? ? # Extract the bits of i to a boolean array. > ? ? ? ? # 'bits' is the number of signifcant bits. > ? ? ? ? result = [] > ? ? ? ? for j in range(0, bits): > ? ? ? ? ? ? ? ? result.append(i & 1) > ? ? ? ? ? ? ? ? i >>= 1 > ? ? ? ? result.reverse() > ? ? ? ? return result > > Now I'd define a function such as: > def table(f, n): > ? ? ? ? # Calculate a truth table for function f taking n boolean parameters > ? ? ? ? result = [] > ? ? ? ? for i in range(0, math.pow(2, n)): > ? ? ? ? ? ? ? ? for j in range(0, n): > ? ? ? ? ? ? ? ? ? ? ? ? params = int_to_bool(i, n) > ? ? ? ? ? ? ? ? result.append(params + [(f(*params))]) > ? ? ? ? return result > > Now you could define the function you want as a separate function, or > just use a lambda: > > table(lambda a, b, c:(a or b) and c, 3) > [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 0], > [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]] > > Each element in the result is the state of the parameters followed by > the result of the function. > > I stress that this is quick and dirty -- I'm sure somebody will be > along with something better soon! > > -- > Tim Rowe Good idea. If you want prefixed operators: 'and( a, b )' instead of 'a and b', you'll have to write your own. ('operator.and_' is bitwise only.) It may be confusing to mix prefix with infix: 'impl( a and b, c )', so you may want to keep everything prefix, but you can still use table( f, n ) like Tim said. From fredrik at pythonware.com Wed Sep 17 09:56:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 15:56:31 +0200 Subject: python regex character group matches In-Reply-To: References: Message-ID: christopher taylor wrote: > my issue, is that the pattern i used was returning: > > [ '\\uAD0X', '\\u1BF3', ... ] > > when i expected: > > [ '\\uAD0X\\u1BF3', ] > > the code looks something like this: > > pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) > #print pat.findall(txt_line) > results = pat.finditer(txt_line) > > i ran the pattern through a couple of my colleagues and they were all > in agreement that my pattern should have matched correctly. First, [0-9A-F] cannot match an "X". Assuming that's a typo, your next problem is a precedence issue: (X)+ means "one or more (X)", not "one or more X inside parens". In other words, that pattern matches one or more X's and captures the last one. Assuming that you want to find runs of \uXXXX escapes, simply use non-capturing parentheses: pat = re.compile(u"(?:\\\u[0-9A-F]{4})") and use group(0) instead of group(1) to get the match. From rstarkov at gmail.com Sun Sep 14 04:02:39 2008 From: rstarkov at gmail.com (rs387) Date: Sun, 14 Sep 2008 01:02:39 -0700 (PDT) Subject: How to emit Cyrillic and Chinese via unicode from console mode? References: Message-ID: <543bde0c-4d99-4d79-a4dd-b6f8d85e8c48@l64g2000hse.googlegroups.com> On Sep 14, 2:03?am, "Siegfried Heintze" wrote: > Can someone point me to an example of a little program that emits non-ascii > Unicode characters (Russian or Chinese perhaps)? The following doesn't quite work, but I'll post it anyway since it actually ends up printing the characters. Perhaps someone can point out what causes the exception at the end? The important thing is to set the console codepage to 65001, which is UTF-8. This lets you output utf8-encoded text and see the Unicode chars displayed. import sys import encodings.utf_8 import win32console sys.stdout = encodings.utf_8.StreamWriter(sys.stdout) win32console.SetConsoleCP(65001) win32console.SetConsoleOutputCP(65001) s = "English: ok\n" s += u'Russian: \u0420\u0443\u0441\u0441\u043a\u0438\u0439\n' s += u'Greek: \u03bc\u03b5\u03b3\u03b1\u03bb\u03cd \u03c4\u03b5\u03c1\u03b7\n' print s If redirected to file, all is well, this prints everything properly in UTF-8. If ran on the console, this also prints everything correctly, but then throws a mysterious exception: English: ok Russian: ??????? Greek: ?????????? Traceback (most recent call last): File "I:\Temp\utf8console.py", line 18, in print s File "C:\Progs\Python25\lib\codecs.py", line 304, in write self.stream.write(data) IOError: [Errno 0] Error Any ideas? Roman P.S. This really ought to Just Work in this day and age, and do so without all those 65001/utf8 incantations. Pity that it doesn't. Sigh. From gminick at bzt.bzt Fri Sep 12 06:52:32 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 12 Sep 2008 10:52:32 +0000 (UTC) Subject: Better error message on recursive import References: <6isb2mF9scaU1@mid.individual.net> Message-ID: On Thu, 11 Sep 2008 12:43:34 +0200, Thomas Guettler wrote: Hello, > why does Python only raise ImportError if it fails caused by a recursive import? > > I know what's wrong. But I guess many beginner don't know what's wrong. I don't think that you're right here. I can't remember any beginner asking such a question on p.c.py. I think they would come and ask if it really was problematic. And, anyway, I don't know how to answer your question :-) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 12 06:47:48 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Sep 2008 12:47:48 +0200 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: References: <943393.38616.qm@web95111.mail.in2.yahoo.com> Message-ID: <48ca4840$0$15455$426a74cc@news.free.fr> Daniel Fetchinson a ?crit : > > >>> Thanking you, >>> >>> Ms. Vaidehi Pawar >> How much do you pay? >> >>> How much do you ask for???? >>> >>> cheers >>> Ms. Vaidehi > > I was just kidding. But if you seriously need people to do this kind > of job it's better to post the amount you are willing to pay otherwise > nobody will take it seriously. If the OP seriously need people to do his schoolwork for him, then he'd better try to learn something else. Cheating is not a solution. From antroy at gmail.com Sun Sep 21 12:23:56 2008 From: antroy at gmail.com (Ant) Date: Sun, 21 Sep 2008 09:23:56 -0700 (PDT) Subject: Problem with Python shell through Cygwin Screen (Python/Vim/Screen combo) References: <1e357c83-b53b-4587-a4d3-5327d1762341@k13g2000hse.googlegroups.com> Message-ID: <321a7ec7-db03-4665-8eff-640abf03c86a@k30g2000hse.googlegroups.com> On Sep 19, 7:08?pm, Jason Tishler wrote: ... > There are known issues when trying to run a Windows program that > directly accesses the console under Cygwin. ?For example: > > ? ?http://mail.python.org/pipermail/python-list/2004-June/266661.html > > AFAICT, you will have to use Cygwin Python with screen. Thanks for the info. Shame but - cygwin python for this setup it is (Though I may hunt for a native windows port of screen rather than the cygwin one.) Cheers, Ant. From mensanator at aol.com Thu Sep 4 21:09:49 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 4 Sep 2008 18:09:49 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> Message-ID: <618bc60e-5b1d-4eee-bd34-4fc6b0131a5f@m44g2000hsc.googlegroups.com> On Sep 4, 12:31?pm, Thomas Bellman wrote: > Mensanator wrote: > > Ok, but I don't understand why an empty list is a valid sum > > whereas a list containing None is not. > > You can't conclude the behaviour of the one from the behaviour > of the other, because the two situations have nothing at all in > common. I wouldn't say they have nothing in common. After all, neither [] nor [None,None] contain any integers, yet summing the first gives us an integer result whereas summing the second does not. Yes, for different unrelated reasons, but sometimes reasons aren't as important as results. > > >> As it happens, the SQL sum() function (at least in MySQL; I don't > >> have any other database easily available, nor any SQL standard to > >> read) does return NULL for a sum over the empty sequence, so you > >> could argue that that would be the correct behaviour for the > >> Python sum() function as well, but you can't argue that because a > >> sum *involving* a NULL value returns NULL. > > I'm not following that. Are you saying a query that returns no > > records doesn't have a specific field containg a Null so there > > are no Nulls to poison the sum? ...tap...tap...tap. Ok, I can see > > that, > > Exactly. > > > but you don't get 0 either. > > That's because the SQL sum() has a special case for "no rows > returned". ?A *different* special case than the one that taint's > the sum when encountering a NULL. ?It does the equivalent of > > ? ? if len(rows_returned) == 0: > ? ? ? ? # Special case for no rows returned > ? ? ? ? return NULL > ? ? total = 0 > ? ? for row in rows_returned: > ? ? ? ? value = row[column] > ? ? ? ? if value is NULL: > ? ? ? ? ? ? # Special case for encountering a NULL value > ? ? ? ? ? ? return NULL > ? ? ? ? total += value > ? ? return total > > Two different special cases for the two different situations. ?If > you were to remove the special case for no rows returned, you > would get zero when the SELECT statement finds no rows, but the > sum would still be tainted when a NULL value is encountered.. > > The definition of sum in mathematics *does* do away with that > special case. ?The sum of zero terms is zero. ?And the Python > sum() function follows the mathematics definition in this > respect, not the SQL definition. Too bad. I brought this up because I use Python a lot with database work and rarely for proving theorms in ZFC. Guess I have to work around it. Just one more 'gotcha' to keep track of. > > You can argue that Python sum() should have special cased the > empty sequence. ? I did. > It's not an illogical stance to take. ? I didn't think so. > It's just > a totally different issue from encountering a non-numeric element > in the sequence. ? Ok, I was paying more attention to the outcome. > In some cases it might actually make sense to > treat the empty sequence as an error, but just ignore non-numeric > elements (i.e, treat them as if they were zero). ? Ouch. Sounds like Excel and we don't want to go there. > And in some > cases both should be an error, and in some neither should be an > error. > > -- > Thomas Bellman, ? Lysator Computer Club, ? Link?ping University, ?Sweden > "You are in a twisty little passage of ? ? ? ! ?bellman @ lysator.liu.se > ?standards, all conflicting." ? ? ? ? ? ? ? ?! ?Make Love -- Nicht Wahr! From bdesth.quelquechose at free.quelquepart.fr Thu Sep 4 15:56:17 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 21:56:17 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> <48c03b91$0$14747$426a74cc@news.free.fr> Message-ID: <48c05951$0$16961$426a74cc@news.free.fr> Ivan Illarionov a ?crit : > On 4 ????, 21:49, Bruno Desthuilliers > wrote: >> Ivan Illarionov a ?crit : >> >> >> >>> On 4 ????, 22:59, Carl Banks wrote: >>>> You can write code to guard against this if you want: >>>> class A: >>>> legal = set(["x"]) >>>> def __setattr__(self,attr,val): >>>> if attr not in self.legal: >>>> raise AttributeError("A object has no attribute '%s'" % >>>> attr) >>>> self.__dict__[attr] = val >>>> def __init__(self,x): >>>> self.y = x >>>> I suspect most people who go into Python doing something like this >>>> soon abandon it when they see how rarely it actually catches anything. >>> '__slots__' is better: >> For which definition of "better" ? __slots__ are a mean to optimize >> memory usage, not to restrict dynamism. Being able to dynamically add >> arbitrary attributes is actually a feature, not a bug, and uselessly >> restricting users from doing so is not pythonic. IOW : don't do that. > > Carl's example is restricting dynamism in the same way as __slots__. > I've just suggested a better implementation. Once again : for which definition of "better" ?-) > It is not me who > suggested dynamism restriction as a way to guard against errors. My post was not targeted to you personnaly - I just wanted to make it clear for other readers that this (ab)use of slots was considered bad form. From gh at ghaering.de Tue Sep 23 08:49:21 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 23 Sep 2008 14:49:21 +0200 Subject: finding domain name In-Reply-To: References: Message-ID: Bobby Roberts wrote: > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/xxxxx/ > > where xxxxx represents the domain name. > > How can I find the domain name of the current url being viewed. Depends on the technology/web framework. If you use WSGI, you should use something like: host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] -- Gerhard From hugo at hugo.com Sat Sep 13 08:16:48 2008 From: hugo at hugo.com (hugo) Date: Sat, 13 Sep 2008 14:16:48 +0200 Subject: frei sperma bilder samen sperma bilder spermaspiele sperma bilder schwarze sperma bilder sexgeschichten sperma bilder bild besamen schwester sperma schlampe schuhe besamen Message-ID: frei sperma bilder samen sperma bilder spermaspiele sperma bilder schwarze sperma bilder sexgeschichten sperma bilder bild besamen schwester sperma schlampe schuhe besamen + + + http://jhku.net/sperm/ http://jhku.net/sperm/ http://jhku.net/sperm/ http://jhku.net/sperm/ http://jhku.net/sperm/ + + + + http://www.rollyo.com/sperm_video_and_pics/sperm_cocktail_party/sperm+cockta il+party http://www.rollyo.com/sperm_video_and_pics/extrem_sperm_sluts/extrem+sperm+s luts http://www.rollyo.com/sperm_video_and_pics/sperm_shower_sluts/sperm+shower+s luts http://www.rollyo.com/sperm_video_and_pics/sperm_boobs_girls/sperm+boobs+gir ls http://www.rollyo.com/sperm_video_and_pics/www.sperm-swap.com/www.sperm-swap .com http://www.rollyo.com/sperm_video_and_pics/sperm_bukkake_girls/sperm+bukkake +girls http://www.rollyo.com/sperm_video_and_pics/www.spermswap.com/www.spermswap.c om http://www.rollyo.com/sperm_video_and_pics/geile_sperma_spiele/geile+sperma+ spiele http://www.rollyo.com/sperm_video_and_pics/sperm_fuck_babes/sperm+fuck+babes http://www.rollyo.com/sperm_video_and_pics/sperma_schlucken/sperma+schlucken http://www.rollyo.com/sperm_video_and_pics/eating_sperm_sluts/eating+sperm+s luts + + + sperma bilder galerie hund besamen meine sperma bilder scharfe sperma schlampe oma sperma schlampe schuhe besamen besamen forum sperma bilder galerie sperma bilder galerie umsonst sperma bilder kuh besamen geschichte sperma schlampe sie besamen besamen video sperma bilder seiten sperma bilder seiten arsch sperma schlampe schwarze sperma bilder ao besamen besamen video mann besamen tochter besamen http://ibm-news.for-um.de/showthread.php?t=10528 - besamen stories sperma schlampe kostenlos http://www.bebin.tv/forum/showthread.php?t=31350 - fue?e besamen schwarze sperma bilder http://ibm-news.for-um.de/showthread.php?t=11161 - sperma spiele sperma bilder galerie http://ibm-news.for-um.de/showthread.php?t=14153 - besamen lassen blank besamen http://ibm-news.for-um.de/showthread.php?t=14153 - spermadusche hund besamen http://ibm-news.for-um.de/showthread.php?t=9392 - hund besamen ehefrau fremd besamen http://ibm-news.for-um.de/showthread.php?t=15019 - oma besamen meine frau besamen http://ibm-news.for-um.de/showthread.php?t=14042 - mann besamen schweine besamen http://www.topwomen.org/forum/index.php?showtopic=94649 - sperma bilder seiten spermaspiele sperma bilder http://ibm-news.for-um.de/showthread.php?t=15569 - ggg spermaspiele dvd besamen http://ibm-news.for-um.de/showthread.php?t=11025 - samen sperma bilder sperma schlampe frau http://ibm-news.for-um.de/showthread.php?t=11007 - alle loecher besamen heisse sperma bilder http://www.gamesforum.ca/showthread.php?t=310228 - frei sperma bilder stuten besamen http://ibm-news.for-um.de/showthread.php?t=14635 - hengst besamen private sperma schlampe From bj_666 at gmx.net Tue Sep 2 09:46:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 13:46:42 GMT Subject: What is module initialization? References: Message-ID: <6i4ue2Fol29aU2@mid.uni-berlin.de> On Tue, 02 Sep 2008 14:32:30 +0100, dudeja.rajat wrote: > I found on the net that there is something called module initialization. > Unfortunately, there is not much information for this. However, small > the information I found module initialization can be of use to me in my > project. "Module initialization" is what happens when you import a module the first time. In pure Python modules the module level code is executed and in extension modules a special initializing function may be called. > However, there is one case when a module updates one such global > variable but the variable is not getting updated in the module > containing global symbols ( variables). Sounds unlikely if you *really* update the attribute of the module and not just rebind a local name that was bound to the object in the "global" module before. Example: from spam import egg egg = 42 # This does *not* change `spam.egg` but just the local binding! > Could some one provide me a sample code of module intialization? And how > can I ensure that module initialization is done only once? Module initialization is only done once, there's nothing to ensure. Ciao, Marc 'BlackJack' Rintsch From clp at rebertia.com Sun Sep 14 05:48:40 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 14 Sep 2008 02:48:40 -0700 Subject: noob: subprocess clarification In-Reply-To: <68fcdea2-804e-4fba-958e-47ecee277faf@s50g2000hsb.googlegroups.com> References: <68fcdea2-804e-4fba-958e-47ecee277faf@s50g2000hsb.googlegroups.com> Message-ID: <47c890dc0809140248i25510030g3012ecab30de3d2a@mail.gmail.com> On Sun, Sep 14, 2008 at 2:29 AM, wrote: > Hi, > > I generally use csh scripts for generally scripting (controlling > simulations). Basically the script processing options, generates the > command line, executes it and then processes the results. > > I would usually use the -f option on the shebang line to ensure that > the environment from the current shell is used. > > i.e. #!/bin/csh -f According to my copy of the csh manpage: ?f The shell ignores?/.tcshrc, and thus starts faster. So, if I understand correctly, this really just ensures that the rc file isn't run again, thus preventing any environment vars from being re-initialized and clobbered. Since Python isn't (conventionally) a unix shell, this sort of thing isn't an issue and using the current shell environment is the default behavior. You don't need to do anything special. > > How do I acheive this in python? > > I have been looking at the > > import subprocess as sub > p = sub.Popen(['echo $PATH'],shell=True).wait() > > This *seems* to do what I want (in that the path looks correct), but I > don't really understand the documentation. > > Can somebody please clarify what the shell=True does, and whether I am > using it correctly. Basically, I think it runs the command string through the shell (i.e. sh), thus causing shell syntax (e.g. $variables) to be interpreted. In this particular case, $PATH is interpolated with the value of the PATH environment variable. You can also access environment variables using os.environ, for example: import os print os.environ['PATH'] Regards, Chris > > Thanks, > > Steven > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From fredrik at pythonware.com Thu Sep 11 05:37:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 11:37:53 +0200 Subject: Adding environment variables to bash. In-Reply-To: <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> Message-ID: John Lawrence wrote: > You can make a command use the current shell though if you use the '.' > command e.g.: > > jl > cat env.sh > export TEST='hello' > > jl > ./env.sh && env | grep TEST #Doesn't set TEST in parent shell > jl > . ./env.sh && env | grep TEST #Adding '. ' before the > command uses the same shell > TEST=hello doesn't exactly work for Python scripts, though: $ cat env.py #!/usr/bin/env python import os os.environ["TEST"] = "hello" $ . ./env.py && env | grep TEST import: unable to open X server `'. bash: os.environ[TEST]: command not found From deets at nospam.web.de Thu Sep 25 08:19:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 14:19:32 +0200 Subject: How to get the filename in the right case ? References: <6k1937F5i8kjU1@mid.uni-berlin.de> Message-ID: <6k1dukF5hk86U1@mid.uni-berlin.de> > Yes I'm pretty sure, two reasons: > 1. when I perform a step_into, jumping into a file that doesn't have > breakpoints itself (meaning my program doesn't even know of this file), > pdb returns a lowercase filename What has that to do with potential output postprocessing? > 2. rpdb2 (probably based or even inherited from pdb) has the same > behavior. Asking the writer of rpdb2, I got some excuse (which I didn't > understand) why he had done it that way. rpdb2 is not pdb. Below is the output of a Pdb-session I just had: (eggbasket)dir at client8049:~/software/vc/EggBasket$ nosetests -s eggbasket.tests.test_model 2008-09-25 14:13:10,374 turbogears.identity.saprovider INFO Loading: eggbasket.model.VisitIdentity .> /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(59)test_versionsets() -> vi1 = vset.add_pkg_info(p1) (Pdb) n > /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(60)test_versionsets() -> session.flush() (Pdb) n As you can see - mixed-case filenames. Linux though. There is a *very* simple way for you to check: just create a file called FooBar.py and inside that, put import pdb; pdb.set_trace() print "hello" Run that on the windows shell. See if that puts out all lowercase or not. I can't do that right now as my VBox Windows won't start. Then we know if PDB is really the culprit. Apart from that, is that really a problem that the filenames are all lower case? AFAIK Windows is case-insensitive regarding filenames anyway. So opening the file by just passing the filename should work seamless. Diez From bignose+hates-spam at benfinney.id.au Sat Sep 27 04:20:17 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 18:20:17 +1000 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> Message-ID: <8763oiuhj2.fsf@benfinney.id.au> Steven D'Aprano writes: > On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: > > An ordinary singleton is instantiating the class multiple times > > yet returning the same instance object; a class singleton is > > simply using the class directly (like a module). Where is this "class singleton" terminology from? It seems redundant to me. It also doesn't seem to have anything to do with what "singleton" means as a pattern; "using a class" is simply using a class. > Since I now no longer think I need such a beast That's a relief :-) > I'd like to be able to call [a class] as if it were a function. > Normally calling a class object returns an instance -- I wish to > return something else. In that case, you *don't* want a class at all; the entire point of a class is to define behaviour for instances. Instead, you want to define a class whose *instances* are callable, by defining the '__call__' method to do whatever it is you want. > This seems to works: > > >>> class ClassSingleton(object): > ... thing = (0, 1, 2) > ... def __new__(cls, *args): > ... return len(args+cls.thing) > ... > >>> ClassSingleton(1, 2, 4, 8, 16) > 8 Horribly obfuscatory. Calling a class should return a new instance of the class or something like it. Instead, define it so the user instantiates the class by calling the class, and *then* calls that non-class object, and so shouldn't expect to get a new instance back: >>> class CallableAppendor(object): ... thing = (0, 1, 2) ... def __call__(self, *args): ... return len(args + self.thing) ... >>> appendor = CallableAppendor() >>> appendor(1, 2, 4, 8, 16) 8 -- \ ?Pleasure's a sin, and sometimes sin's a pleasure.? ??Lord? | `\ George Gordon Noel Byron, _Don Juan_ | _o__) | Ben Finney From tchendrix at gmail.com Tue Sep 23 16:45:06 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 13:45:06 -0700 (PDT) Subject: finding domain name References: <48d941f0$0$3738$426a74cc@news.free.fr> Message-ID: <8e874f68-838b-4fc1-8228-1787525ca780@x41g2000hsb.googlegroups.com> On Sep 23, 1:23?pm, Bruno Desthuilliers wrote: > Bobby Roberts a ?crit : > > > hi group. ?I'm new to python and need some help and hope you can > > answer this question. ?I have a situation in my code where i need to > > create a file on the server and write to it. ?That's not a problem if > > i hard code the path. ?However, the domain name needs to be dynamic so > > it is picked up automatically. ?The path to our websites is > > > home/sites/xxxxx/ > > > where xxxxx represents the domain name. > > > How can I find the domain name of the current url being viewed. > > What are you using exactly ? cgi ? wsgi ? Else ? mod python over an in-house framework written years ago without documentation so it's not the easiest thing to navigate. We will be moving to django this fall. From prologic at shortcircuit.net.au Sun Sep 21 20:12:38 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 10:12:38 +1000 Subject: What do you call a class not intended to be instantiated In-Reply-To: <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> Message-ID: On Mon, Sep 22, 2008 at 9:39 AM, Calvin Spealman wrote: > I call it an obvious misuse and misunderstanding of why you'd use a class in > the first place. Either create an instance and not make these things > classmethods or just share the stuff in a module-level set of variables. But > the instantiating is the best options. Your class attributes might not be > globals, but you're still using global state and you should avoid it where > you can. I concur. Use a _proper_ state object that you share amongst your other objects. For instance, in many of my systems and applications I write, I often have an "Environment" instance, which is a container object that holds other objects required by parts of the system. Every other component/object in the system that is instantiated recievees exactly one instnace of thie "Environment" called, "env". Accessing shared states amongst components/objects within the system is as simple as this: class Foo(object): def __init__(self, env, *args, **kwargs): self.env = env def foo(self): if self.env.some_state: print "Do something useful" env = Environment() foo = Foo(env) foo.foo() cheers James -- -- -- "Problems are solved by method" From saluk64007 at gmail.com Sun Sep 28 20:11:50 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 28 Sep 2008 17:11:50 -0700 Subject: Not fully OO ? In-Reply-To: <48dd5dd0$0$26425$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <48dcf924$0$4653$426a74cc@news.free.fr> <00ecf4b4$0$20666$c3e8da3@news.astraweb.com> <48dd5dd0$0$26425$426a74cc@news.free.fr> Message-ID: On Fri, Sep 26, 2008 at 1:11 PM, Bruno Desthuilliers wrote: > Steven D'Aprano a ?crit : >> >> On Fri, 26 Sep 2008 17:00:59 +0200, Bruno Desthuilliers wrote: >> >>> Patrick Mullen a ?crit : >>>> >>>> Depending on the scale of the website I am making, how much I care >>>> about editing it in the future, and how much I just want to get >>>> something up, I will occasionally use php. And I am a self confessed >>>> php hater :) But it's generally the fastest way I know to get >>>> something up. So even terrible languages can have their uses! >>> >>> Sorry but I fail to see how it relates to the current thread ??? >> >> I think Patrick is responding to a comment from Tino Wildenhain: > > That didn't showed here (reading this from c.l.py via free.fr). Sorry. > >> [quote] >> Well then it still depends on the perception of "job done". For example >> PHP programmers would bet their soul that their language of choice is >> exactly the right one to "get the job done." [end quote] >> >> Patrick, you will cause much less confusion if you quote relevant parts of >> the text you are replying too. > > Indeed. At least it would have made clear (to me) there was something > missing in the thread... > -- > http://mail.python.org/mailman/listinfo/python-list Whoops, sorry for the confusion everyone. Usually I do keep the comments, don't know what happened there. From lists at cheimes.de Mon Sep 1 18:15:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 02 Sep 2008 00:15:19 +0200 Subject: encoding In-Reply-To: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> References: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> Message-ID: Gandalf wrote: > if i want to print utf-8 string i should writre: > > print u"hello word" > > but what happen if i want to print variable? u"hello world" is *not* an utf-8 encoded string. It's a unicode string. I suggest you read http://www.joelonsoftware.com/articles/Unicode.html Christian From trodemaster at gmail.com Tue Sep 9 17:30:59 2008 From: trodemaster at gmail.com (Blake Garner) Date: Tue, 9 Sep 2008 14:30:59 -0700 Subject: rss feed generation Message-ID: <55a5c7c50809091430t55a96834q37ab8301b478b04f@mail.gmail.com> I'm looking for suggestions on how to approach generating rss feed .xml files using python. What modules to people recommend I start with? Thanks! Blake From cvrebert at gmail.com Mon Sep 15 16:21:31 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Mon, 15 Sep 2008 13:21:31 -0700 Subject: append on lists In-Reply-To: References: Message-ID: <47c890dc0809151321j1ef65557q1689a3b7d69b377c@mail.gmail.com> On Mon, Sep 15, 2008 at 1:24 PM, Armin wrote: > > > Hi, > > just a dumb question. > > Let a = [1,2,3,4,5] > > Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? I'll assume the presence of the 6 is a typo. Because .append() mutates 'a' and appends the item in-place rather than creating and returning a new list with the item appended, and it's good Python style for mutating methods to have no return value (since all functions must have some return value, Python uses None when the function doesn't explicitly return anything). If you print 'a' after doing the .append(), you'll see it's changed to your desired value. Regards, Chris > > --Armin > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From marco.bizzarri at gmail.com Fri Sep 5 15:24:37 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 21:24:37 +0200 Subject: use str as variable name In-Reply-To: References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> Message-ID: <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> On Thu, Sep 4, 2008 at 10:47 AM, Fredrik Lundh wrote: > > (...as Bruno implies, setattr(), len() et al can be and should be viewed as > generic functions. Just a question: "generic functions" are not meant in the sense of "generic functions" of CLOS, am I right? -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From stef.mientki at gmail.com Tue Sep 30 16:18:50 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 22:18:50 +0200 Subject: rlcompleter and wxPython, problems ... In-Reply-To: References: <48E0045A.3020402@gmail.com> <48E2789F.7090207@gmail.com> Message-ID: <48E289AA.2040205@gmail.com> Gabriel Genellina wrote: > En Tue, 30 Sep 2008 16:06:07 -0300, Stef Mientki > escribi?: > >> Gabriel Genellina wrote: >>> En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki >>> escribi?: >>> >>>> I'm trying to implement autocompletion into my editor. >>>> But I find some weird behavior, >>>> or at least I don't have the faintest idea why this behavior >>>> occures, >>>> and even more important how to solve it >>>> In the example below I try to autocomplete " wx.s" , which in my >>>> humble opinion should at least produce "wx.stc" (and some others ). >>> >>> wx is a package. Modules within the package are not, by default, >>> attributes of the package - unless they're imported in __init__.py >>> or your code imports them. >>> So the autocompleter is doing the right thing >> in what perspective ? >> the autocompleter is only meant to assist the program writer ;-) > > It's hard to write an autocompleter that does the right thing in all > cases :) > > For a package, you have several sources for possibly valid attributes: > > - its dir() (that is, the package object's own attributes) > - the __all__ attribute, when it exists > - the list of modules inside the package directory or directories > (given by its __path__ attribute) > > Sometimes __init__.py is empty - and enumerating the modules inside > the directory is the right thing to do. Sometimes the author > explicitely imports things in __init__.py, things that comprise the > public interfase to the package. In that case I'd not like to see > "private" modules appearing in the list. > Combine with __all__, which might be defined or not. Mix all those, > choose your own autocomplete algorithm, and see what happens... > >>> - wx.stc does not exist until it is explicitely imported. >> I guess I've to study the package. >> For the moment I'll implement a user editable list of additions. >> >> But with your remarks I tried __all__ >> And now I wonder why rlcompleter is not simply using "wx.__all__", >> it than does gets all the items ? > > __all__ isn't always defined. It's only used when you do "from xxx > import *" AFAIK. > thanks Gabriel, very valuable information for me, I'll bookmark this message for later use. cheers, Setf From circularfunc at gmail.com Sun Sep 21 13:02:47 2008 From: circularfunc at gmail.com (process) Date: Sun, 21 Sep 2008 10:02:47 -0700 (PDT) Subject: I tried erlang-ish [1|2] in python and something came out... Message-ID: In erlang you can cons like this: [1|2]. i tried this in python and it didnt raise an error but i dont know what the result do >>> [1|2] [3] >>> [2|2] [2] >>> a = [2|2] >>> a [2] >>> [2|3] [3] >>> [2|1] [3] >>> From rridge at csclub.uwaterloo.ca Wed Sep 24 11:31:29 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 24 Sep 2008 11:31:29 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Presumably somebody has suggested that calling sys.exit() was a good > option. I'm curious to what possible reason they could give for such a > poor choice. Grant Edwards wrote: >Same here. It's like an automotive engine controls designer >asking if a failed O2 sensor should turn on the check engine >light or blow up the car. No, it's more like asking if the failed sensor should turn on a strange and mysterious light on the dashboard and then blow up the car if the driver doesn't immediately stop and check the engine. The owners manual would only vaguely hint at the fact that this could happen. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From tjreedy at udel.edu Tue Sep 16 13:06:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 13:06:35 -0400 Subject: append on lists In-Reply-To: <200809161448.16883.maric@aristote.info> References: <1221564169.16690.0@proxy00.news.clara.net> <200809161448.16883.maric@aristote.info> Message-ID: Maric Michaud wrote: > It is, please try to understand it, in python all expressions that mutate an > object should return None, You are over-generalizing. For builtin classes, mutation methods return none. Guido recommends this as a general practice, but users may do whatever they like in their own classes. In fact, people have been told that if they do not like the built-in behavior, they should make their own, possibly by subclassing. For augmented assignment, in-place mutation followed by rebinding is explictly allowed and done for lists. > all expressions that return something, return a new object Nonesense. There is nothing in the ref manual that says this and parts that say otherwise. > there are some noticeable exceptions : They are only exceptions to your rule, not to the language specification. From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 02:45:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Sep 2008 06:45:16 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <00edd041$0$20666$c3e8da3@news.astraweb.com> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: > In article , > Steven D'Aprano wrote: >>On Thu, 25 Sep 2008 21:17:14 -0700, Aahz wrote: >>> >>> Seems to me that if all the module is used for is to store state, >>> you're wasting a file on disk. I personally prefer to use a class >>> singleton. >> >>I don't recognise the term "class singleton". Can you explain please? >>How is it different from an ordinary singleton? > > An ordinary singleton is instantiating the class multiple times yet > returning the same instance object; a class singleton is simply using > the class directly (like a module). Amazing. That's *exactly* what I was thinking of when I first asked my question. Since I now no longer think I need such a beast, this is just academic curiosity, but given a class singleton, I'd like to be able to call it as if it were a function. Normally calling a class object returns an instance -- I wish to return something else. Is that just a matter of overriding __new__? This seems to works: >>> class ClassSingleton(object): ... thing = (0, 1, 2) ... def __new__(cls, *args): ... return len(args+cls.thing) ... >>> ClassSingleton(1, 2, 4, 8, 16) 8 Is it really that easy? -- Steven From bignose+hates-spam at benfinney.id.au Tue Sep 30 18:59:09 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Oct 2008 08:59:09 +1000 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> Message-ID: <87ljx9qlz6.fsf@benfinney.id.au> Steven D'Aprano writes: > I simply don't think that having to run some variation on > > patch -i patchfile.patch > > is a requirement so onerous that it makes the gnuplot licence > non-free. Perhaps I'm just more tolerant of eccentricities than you > :) The distinction here is that this command must be run by *every* recipient of a modified work. A work where one must do that is more onerous for *each* recipient than one where it's already been patched for the recipient. Thus there is value, and no loss of freedom, in you as a redistributor doing that work *once* and then redistributing the work intact to any recipient. Your freedom to do this useful, harmless action is restricted artificially by copyright, and is not granted by the license. So, recipients of the 'gnuplot' code are artificially restricted from performing an action useful to society that does no harm. -- \ ?The Bermuda Triangle got tired of warm weather. It moved to | `\ Alaska. Now Santa Claus is missing.? ?Steven Wright | _o__) | Ben Finney From washakie at gmail.com Tue Sep 23 19:40:42 2008 From: washakie at gmail.com (John [H2O]) Date: Tue, 23 Sep 2008 16:40:42 -0700 (PDT) Subject: appending * to glob returns files with '*' !! In-Reply-To: References: <19579121.post@talk.nabble.com> Message-ID: <19638699.post@talk.nabble.com> No bug indeed, Erik was correct, in fact I had files with the * in the name... Thanks all for your replies! Erik Max Francis wrote: > > John [H2O] wrote: > >> I have a glob.glob search: >> >> searchstring = os.path.join('path'+'EN*') >> files = glob.glob(searchstring) >> for f in files: >> print f >> >> >> ___ >> This returns some files: >> EN082333 >> EN092334 >> EN* >> >> My routine cannot handle the '*' and it should'nt be returned anyway? :-/ >> >> A bug? > > No, it means you actually have a file named 'EN*' in the directory. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > Many would be cowards if they had courage enough. > -- Thomas Fuller > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/appending-*-to-glob-returns-files-with-%27*%27-%21%21-tp19579121p19638699.html Sent from the Python - python-list mailing list archive at Nabble.com. From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 03:54:23 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 09:54:23 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48db462f$0$24356$426a74cc@news.free.fr> Message-ID: <48dc952b$0$2289$426a74cc@news.free.fr> Ross Ridge a ?crit : > Bruno Desthuilliers wrote: >> Also note that there are quite a couples cases where the library authors >> themselves cannot predict which exception types may be raised - as soon >> as the library functions expect callback functions, file-like or >> dict-like or whatever-like objects etc, it's the caller's responsability >> to handle the exceptions that may be raised by what *he* passes to the >> library... > > Ug... that's another documentation pet-peeve of mine. Libraries that > say they take file-like (or whatever-like) object, but don't say exactly > how file-like it needs. Seems not to be such a problem in practice... From castironpi at gmail.com Sat Sep 13 18:14:11 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 13 Sep 2008 15:14:11 -0700 (PDT) Subject: testing if another instance of a script is already running References: Message-ID: <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> On Sep 12, 7:08?am, Strato wrote: > Hi folks, > > I want to write some kind of test to check at startup if another > instance of my script is already running. > > I don't want to handle writing of a PID file because it is too > Unix/Linux specific way to do this, and I need to keep the code to be > cross-platform. > > I think the better way to achieve this is to use some process control, > but I'm a neebie and I don't see how to do this in a safe and clean way. > > Any idea ? > > Best regards, > Strato You could use msvcrt.locking, and just lock the script file. I am not sure about this. From marco.bizzarri at gmail.com Sat Sep 13 11:41:39 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 13 Sep 2008 17:41:39 +0200 Subject: Code example that will make a Skype connection? In-Reply-To: References: Message-ID: <3f0d61c40809130841i9b20846hb962cef2e77c0244@mail.gmail.com> On Sat, Sep 13, 2008 at 4:09 PM, Al Dykes wrote: > > Can some post a Python code fragment that will to make a PC with Skpye > installed to make a Skype call, given a valid phone # string. > > I'm not asking for code that handles the audio once the connection is > made. > > Maybe you can find this useful? https://developer.skype.com/wiki/Skype4Py/examples/s4p_call_py Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From uzmanajmal at gmail.com Sat Sep 13 03:32:38 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Sat, 13 Sep 2008 07:32:38 +0000 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Please explain the arguments of send_request. What exactly are the connection, handler and request_body? It will be really helpful if you give an example of how do i call send_request On Thu, Sep 11, 2008 at 7:18 AM, Fredrik Lundh wrote: > Usman Ajmal wrote: > > And i also fount that a typical system.auth call will look like: >> >> POST /xmlrpc/clarens_server.py HTTP/1.0 >> Host: localhost >> User-Agent: xmlrpclib.py/0.9.9 (by www.pythonware.com < >> http://www.pythonware.com>) >> >> Content-Type: text/xml >> Content-Length: 105 >> AUTHORIZATION: Basic MkhVTm9VazYxbXArVEZLS0dCY2tIRlA3bjVzPQo6RnJvbSBi >> >> >> system.auth >> >> >> >> >> >> >> Problem is that i don't know how do i generate above xml system.auth call. >> Can anyone please tell me how do call a function, setting the header of the >> call too? >> > > you need to plugin a custom transport. see this page for an example: > > http://www.python.org/doc/lib/xmlrpc-client-example.html > > in your case, it should be sufficient to override send_request, e.g. > (untested): > > class SecureTransport(xmlrpclib.Transport): > > def set_authorization(self, ustring, text_ucert): > self.authoriation = encodestring( > "%s:%s" % (ustring,text_ucert) > ) > > def send_request(self, connection, handler, request_body): > connection.putrequest("POST", handler) > connection.putheader("Authorization", > "Basic %s" % self.authorization > ) > > and instantiate the transport by doing > > t = SecureTransport() > t.set_authorization(ustring, text_ucert) > > before passing to the server proxy. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bedouglas at earthlink.net Sun Sep 28 13:31:02 2008 From: bedouglas at earthlink.net (bruce) Date: Sun, 28 Sep 2008 10:31:02 -0700 Subject: parsing a site/page that uses/calls javascript functions... Message-ID: <2ff401c9218f$fc41f230$0301a8c0@tmesa.com> Hi... I've got a couple of test apps that I use to parse/test different html webpages. However, I'm now looking at how to parse a given site/page that uses javascript calls to dynamically create/display the resulting HTML. I can see the HTML is the Browser page if I manually select the btn that invokes the javascript function, but I have no idea how to create an app that can effectively parse the page. My test apps use python, along with mechanize/browser/urllib. I've seen sites/docs that discuss selenium, spidermonkey, etc... If possible, I'm trying to find a complete example (that walks through how to setup the environment, to how to finally extract the DOM elements of a given javascript page), or I'm looking to find someone I can work with, to create a complete example that can then be posted to the 'net. I'd really rather have a headless browser solution, as my overall goal is to run a parsing/crawling over a number of pages that utilize javascript.. Pointers, thoughts, comments, etc will be greatly appreciated. Thanks!!! -bruce From circularfunc at yahoo.se Tue Sep 2 16:27:06 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 2 Sep 2008 13:27:06 -0700 (PDT) Subject: Numpy/Scipy set field of matrix? Message-ID: , 'argmax', 'argmin', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getA', 'getA1', 'getH', 'getI', 'getT', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view'] >>> m matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) how do I set the field 1,2 (=6) to 45 for example? and how do I initialize a matrix and then add values in a for-loop? Im using PIL and want to store all the pixels of an image in a matrix. But I can't find the appropriate operations. From sjmachin at lexicon.net Mon Sep 8 05:20:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Sep 2008 02:20:13 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: On Sep 8, 10:47?am, MK Bernard wrote: > On Sep 7, 3:37?pm, John Machin wrote: > > > > > > > On Sep 8, 7:51?am, "andyh... at gmail.com" wrote: > > > > Hello... > > > > I have a dict of key/values and I want to change the keys in it, based > > > on another mapping dictionary. An example follows: > > > > MAPPING_DICT = { > > > ? ? 'a': 'A', > > > ? ? 'b': 'B', > > > > } > > > > my_dict = { > > > ? ? 'a': '1', > > > ? ? 'b': '2' > > > > } > > > > I want the finished my_dict to look like: > > > > my_dict = { > > > ? ? 'A': '1', > > > ? ? 'B': '2' > > > > } > > > > Whereby the keys in the original my_dict have been swapped out for the > > > keys mapped in MAPPING_DICT. > > > > Is there a clever way to do this, or should I loop through both, > > > essentially creating a brand new dict? > > > Is this homework? > > > There seems to be an implicit assumption in the answers so far that > > your mapping is a 1:1 mapping of all possible input keys. > > > If it doesn't include all possible input keys, answers will crash with > > a KeyError. If there are any many:1 elements in the mapping (for > > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > > in some checks for this. > > Thats exactly why I did an explicit check in my post, so as to make > sure that such a collision could not occur. It would seem that > something along what I posted would be safer, if less elegant, than > the others. I noted two problems: (1) not covering all input keys: your code explicitly sweeps this problem under the carpet, and does it laboriously ... if x in my_dict.keys(): instead of if x in my_dict: (2) not a 1:1 mapping -- for example, 'a' and 'b' both map to 'A' (the only "collision" that I can see), but you don't address that. Here's some code which attempts to cover the bases: new_dict = {} for key in my_dict: if key not in MAPPING_DICT: raise NoMapError('blah %r' % key) else: new_key = MAPPING_DICT[key] if new_key in new_dict: raise ManyToOneError('gurgle %r waffle %r' % (key, new_key)) else: new_dict[new_key] = my_dict[key] Having considered what is actually required under the checked-for conditions, one or both raise statements may be replaced by other code, and then simplified e.g. the first 4 lines in the loop may end up being replaced by new_key = MAPPING_DICT.get(key, key) as already suggested by one respondent. Note that useful use-cases for any variety of this key-change exercise may have many more items in MAPPING_DICT than there are in my_dict (a big language dictionary and a few fragments of text to be "translated"), or vice versa (a small synonym dictionary (color -> colour, center -> centre) and a big input to be "standardised") so it's a good idea to inquire which is likely to be the smaller and iterate over that if the requirements permit it. From stef.mientki at gmail.com Thu Sep 25 19:46:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 26 Sep 2008 01:46:15 +0200 Subject: How to get the filename in the right case ? In-Reply-To: References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> Message-ID: <48DC22C7.5020001@gmail.com> Fredrik Lundh wrote: > Stef Mientki wrote: > > > 1. I've a multitab editor. > > 2. When a breakpoint is reached, > > 3. I check if the file specified in pdb output, is already open in one > > of the editor tabs, > > 4. if not, I open a new tab with the correct file, > > 5. I focus the correct editor tab and jump to the line specified by > > pdb. > > 6. After that I should be able to inspect the surrounding of the > > breakpoint, so I need the modules name. > > > > For 3 I need to compare filenames, the editor contains the case > > sensitive name, pdb not. > > pdb uses os.path.abspath and os.path.normcase to normalize filenames > so they can be safely compared (see the canonic method in bdb.py). > > I suggest you do the same in your editor; e.g: Frederik thanks for the clarification. I don't think your suggestion is a good one. If a filename has uppercase characters in it, the END-USER has done that for some kind of reason. I as a programmer have to respect the arguments of the END-USER, (whatever they are), so I need to visualize the real filename. Secondly thoughtless copying of current behavior, doesn't bring any progress, and I think that's one of the reasons why we're still burdened by inventions done 20 years ago, e.g. "do you want to save your changes ?". cheers, Stef > > pdb_filename = ... > > for buffer in editor_buffers: > filename = os.path.normcase(os.path.abspath(buffer.filename)) > if pdb == filename: > ... found it ... > break > > > > -- > http://mail.python.org/mailman/listinfo/python-list From castironpi at gmail.com Sun Sep 21 20:44:32 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 21 Sep 2008 17:44:32 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00e6cd16$0$20303$c3e8da3@news.astraweb.com> Message-ID: <9089ddd1-d74b-494f-bd5c-cffaf1a2ae37@m44g2000hsc.googlegroups.com> On Sep 21, 6:05?pm, Steven D'Aprano wrote: > Fixing top-posting. > > On Mon, 22 Sep 2008 08:54:43 +1000, James Mills wrote: > > On Mon, Sep 22, 2008 at 8:39 AM, Steven D'Aprano > > wrote: > >> I have a class which is not intended to be instantiated. Instead of > >> using the class to creating an instance and then operate on it, I use > >> the class directly, with classmethods. Essentially, the class is used > >> as a function that keeps state from one call to the next. > > [...] > > > Hi, > > > Wouldn't a normal class called State > > suffice for storing state between calls ? And ... Creating a state > > instance ? > > > For example: > > [snip] > > That's a rather big example for a rather small question. > > Yes, a normal class would work in many cases. In this case, the class > itself is being produced by a factory function, and it's output is an > iterator. Having to call: > > cls = factory() > instance = cls() > result = instance() > > to get anything done seems excessive, even if you write it as a one-liner > result = factory()()(). > > I'm not wedded to the idea, there are alternatives (perhaps the factory > should instantiate the class and return that?) but I assume others have > used this design and have a name for it. > > -- > Steven Do you want anything from it that a dictionary doesn't have, besides the dot-member access? From __peter__ at web.de Wed Sep 3 08:19:19 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2008 14:19:19 +0200 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: Roy Smith wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: > >> Without them it looks better: >> >> import sys >> for line in sys.stdin: >> try: >> a, b = map(int, line.split(None, 2)[:2]) >> except ValueError: >> pass >> else: >> if a + b == 42: >> print b > > I'm philosophically opposed to one-liners I'm not, as long as you don't /force/ the code into one line. > like: > >> a, b = map(int, line.split(None, 2)[:2]) > > because they're difficult to understand at a glance. You need to visually > parse it and work your way out from the inside to figure out what's going > on. Better to keep it longer and simpler. > > Now that I've got my head around it, I realized there's no reason to make > the split part so complicated. No reason to limit how many splits get > done > if you're explicitly going to slice the first two. And since you don't > need to supply the second argument, the first one can be defaulted as > well. So, you immediately get down to: > >> a, b = map(int, line.split()[:2]) I agree that the above is an improvement. > which isn't too bad. I might take it one step further, however, and do: > >> fields = line.split()[:2] >> a, b = map(int, fields) > > in fact, I might even get rid of the very generic, but conceptually > overkill, use of map() and just write: > >> a, b = line.split()[:2] >> a = int(a) >> b = int(b) If you go that route your next step is to introduce another try...except, one for the unpacking and another for the integer conversion... Peter From lolekk143 at wp.pl Sat Sep 20 08:58:36 2008 From: lolekk143 at wp.pl (girl) Date: Sat, 20 Sep 2008 05:58:36 -0700 (PDT) Subject: best video ladies sex +18 free! Message-ID: http://rozrywka.yeba.pl/show.php?id=3709 From jonathon.blake at gmail.com Mon Sep 8 23:22:12 2008 From: jonathon.blake at gmail.com (jonathon) Date: Mon, 8 Sep 2008 20:22:12 -0700 Subject: universal unicode font for reportlab In-Reply-To: <48C4E7A1.2000504@shopzeus.com> References: <48C4E7A1.2000504@shopzeus.com> Message-ID: On Mon, Sep 8, 2008 at 01:51, Laszlo Nagy wrote: > possible to use UTF 8 strings but there is a problem with the font. Use Code2000 http://www.code2000.net/ xan jonathon From castironpi at gmail.com Sun Sep 28 14:46:06 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 11:46:06 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> Message-ID: On Sep 28, 2:52?am, Steven D'Aprano wrote: > On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote: > > Hello all, > > > To me, this is a somewhat unintuitive behavior. ?I want to discuss the > > parts of it I don't understand. > > >>>> f= [ None ]* 10 > >>>> for n in range( 10 ): > > ... ? ? f[ n ]= lambda: n > > ... > >>>> f[0]() > > 9 > >>>> f[1]() > > 9 > > > I guess I can accept this part so far, though it took a little getting > > used to. ?I'm writing some code and found the following workaround, but > > I don't think it should give different results. ?Maybe I'm not > > understanding some of the details of closures. > > >>>> f= [ None ]* 10 > >>>> for n in range( 10 ): > > ... ? ? f[ n ]= (lambda n: ( lambda: n ) )( n ) > > ... > >>>> f[0]() > > 0 > >>>> f[1]() > > 1 > > > Which is of course the desired effect. ?Why doesn't the second one just > > look up what 'n' is when I call f[0], and return 9? > > That's an awfully complicated solution. A much easier way to get the > result you are after is to give each function its own local copy of n: > > f[n] = lambda n=n: n > > As for why the complicated version works, it may be clearer if you expand > it from a one-liner: > > # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) > > inner = lambda: n > outer = lambda n: inner > f[n] = outer(n) > > outer(0) => inner with a local scope of n=0 > outer(1) => inner with a local scope of n=1 etc. > > Then, later, when you call inner() it grabs the local scope and returns > the number you expected. > > -- > Steven Steven, I must have misunderstood. Here's my run of your code: >>> inner = lambda: n >>> outer = lambda n: inner >>> outer(0) at 0x00A01170> >>> a=outer(0) >>> b=outer(1) >>> a() Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: global name 'n' is not defined Why doesn't 'inner' know it's been used in two different scopes, and look up 'n' based on the one it's in? From wholenike at gmail.com Sun Sep 28 04:16:59 2008 From: wholenike at gmail.com (The best online shopping site!(www.wholenikee.cn)) Date: Sun, 28 Sep 2008 01:16:59 -0700 (PDT) Subject: The sale of world famous jacket,Jean-COOGI/DG/ginoshoes on Message-ID: <728a68e6-d4bc-44c2-b368-77356db4c8dc@i24g2000prf.googlegroups.com> shoes on AIR Jordan 1 (paypal payment)(www.wholejean.cn ) AIR Jordan 2 AIR Jordan 3 AIR Jordan 4 AIR Jordan 5 (paypal payment)(www.wholejean.cn ) AIR Jordan 6 Rings AIR Jordan 6 AIR Jordan 7 AIR Jordan 8 AIR Jordan 9 (paypal payment)(www.wholejean.cn ) AIR Jordan 10 AIR Jordan 11 AIR Jordan 12 AIR Jordan 13 (paypal payment)(www.wholejean.cn ) AIR Jordan 14 AIR Jordan 15 AIR Jordan 16 AIR Jordan 17 AIR Jordan 18 AIR Jordan 19 AIR Jordan 20 (paypal payment)(www.wholejean.cn ) AIR Jordan 21 AIR Jordan 22 AIR Jordan 23 (paypal payment)(www.wholejean.cn ) AIR Jordan 3.5 AIR AIR Jordan 4.5 AIR Jordan 7.5 AIR Jordan 9.5 AIR Jordan 12.5 (paypal payment)(www.wholejean.cn ) AIR Jordan 15.5 AIR Jordan 19.5 AIR Jordan 21.5 AIR Jordan Large Size Jordan AIR Jordan Size 14 Jordan AIR Jordan Size 15 shoes AIR Jordan DMP Nike air force one, air force 1, air force one low cut, air force one high cut, air force one release date Air force one, air foce one 25TH, af 1, af 1 25TH, Nike air force one new releases, limited version Air Force One (paypal payment)(www.wholejean.cn ) Air Force one 25TH AF 1 AF 1 25TH (paypal payment)(www.wholejean.cn ) Dunk sb nike sb dunk nike dunk sb dunk sb high dunk sb low dunk sb woman Nike sb dunk Nike Dunk High SB nike dunk low premuim sb Nike SB Dunk High Shimizu Nike SB Dunk Pro Nike SB Dunk Dunk SB Nike Dunk shoes Dunk shoes for woman (paypal payment)(www.wholejean.cn ) Dunk low cut Dunk high cut AIR Jordans Fusion 1 Jordan 2 Fusion AIR Jordan 3 Nike Jordan Fusion 4 Jordan 5 shoes Nike Air Jordan 6 VI Force 1 Jordan Fusion AJF 6 AJF6 AJ6F Jordan 6 Rings Jordan 6 fusion (paypal payment) (www.www.wholejean.cn ) AIR Jordan Fusions 13 NIKE Jordan Fusion 14 AIR Jordans 15Nike Jordan 16 Fusion Jordan 17 shoes Nike Air Jordans 18 XVIII Force 1 Jordan Fusion AJF18 AJF18 AJ18F Jordan 18 fusions (paypal payment)(www.wholejean.cn ) AIR Jordan Fusions 7 NIKE Jordan Fusion 8 AIR Jordans 9 Nikes Jordan Fusion 10 Jordan 11 shoes Nike Air Jordan 12 XII Force 1 Jordan Fusion AJF 12 AJF12 AJ12F Jordans 12 fusions (paypal payment)(www.wholejean.cn ) NIKE AIR JORDAN FORCE FUSION SHOES AJF 5 V JORDANs 5 FUSION NIKE JORDAN 5 FUSION SHOES AJF5 Nike Air Jordan XXIII 23 Force 1 Jordan Fusion AJF 23 AJF23 AJ23F (paypal payment)(www.wholejean.cn) Nike Jordans Fusion 23 AIR Jordan 22 Jordan Fusions 21 AIR Jordans Fusion 20 Jordan 19 shoes Air Jordan Force Fusion VIII (8), AJF 8 Nike (paypal payment)(www.wholejean.cn ) Air Jordan 17 XVII Force 1 Jordan Fusions AJF 17 AJF17 AJ17F Jordan our website : www.wholejean.cn v From fredrik at pythonware.com Wed Sep 10 03:26:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 09:26:20 +0200 Subject: dynamic allocation file buffer In-Reply-To: <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > You've created a solution to a problem which (probably) only affects a > very small number of people, at least judging by your use-cases. Who has > a 4GB XML file Getting 4GB XML files from, say, logging processes or databases that can render their output as XML is not that uncommon. They're usually record-oriented, and are intended to be processed as streams. And given the right tools, doing that is no harder than doing the same to a 4GB text file. From bedouglas at earthlink.net Tue Sep 2 22:39:05 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 2 Sep 2008 19:39:05 -0700 Subject: python - mechanize/browser/POST issue Message-ID: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> evening... using mechanize/Browser, i can easily do a url/get, and process submitting a form that uses a GET as the action. however, I'm not quite sure how to implement the submittal of a form, that uses the POST action. Anyone have a short chunk of code that I can observer, that uses the mechanize.Browser implentation? in searching the net, i haven't found any... thanks From ToshiBoy at gmail.com Tue Sep 9 07:14:31 2008 From: ToshiBoy at gmail.com (ToshiBoy) Date: Tue, 9 Sep 2008 04:14:31 -0700 (PDT) Subject: Python Installation and Running on Windows Vista References: <4f66ca7b-b495-4b12-bb4c-29b096eb53c9@j22g2000hsf.googlegroups.com> Message-ID: <1a916f40-b54b-4a42-a441-4a9e91135f12@i24g2000prf.googlegroups.com> I don't use it often in Vista, but I haven't had any issues. Matter-of- fact, some things seem nicer in Vista... for instance it resets IDLE whenever I rerun a module. Mchizi_Crazy wrote: > Please help with issue... I heard of compatimbiltity issues and would > like clarification. From simon.palmer at gmail.com Sun Sep 7 12:22:25 2008 From: simon.palmer at gmail.com (SimonPalmer) Date: Sun, 7 Sep 2008 09:22:25 -0700 (PDT) Subject: formatting a string with thousands separators Message-ID: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> anyone recommend a way of formatting floats with comma separators? e.g. 500000.00 -> 500,000.00 From grante at visi.com Wed Sep 3 11:01:28 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Sep 2008 10:01:28 -0500 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <87hc8xor9g.fsf@benfinney.id.au> Message-ID: On 2008-09-03, Ben Finney wrote: > Another reason in support of spaces (rather than underscores) to > separate digit groups: it's the only separator that follows the SI > standard for representing numbers: > > ??? for numbers with many digits the digits may be divided into > groups of three by a thin space, in order to facilitate reading. > Neither dots nor commas are inserted in the spaces between groups > of three. > > > > This isn't binding upon Python, of course. However, it should > be a consideration in choosing what separator convention to > follow. I don't think that standard is applicable. It's a typesetting style guide. It also references superscripts, half-high centered dots, the "cross" multiplication symbol, the degree symbol and tons of other things which, like the thin space, can't be represented using the most common text encodings. It's quite explicit that the separator is a thin space, which one presumes would not be considered "white space" for tokenizing purposes. We don't have a thin-space, and allowing spaces within numerical literals would throw a major monkey-wrench into a lot of things (like data files whose values are separated by a single space). I suppose you could have a different format for literals in program source and for the operands to int() and float(), but that feels like a bad idea. -- Grant Edwards grante Yow! Pardon me, but do you at know what it means to be visi.com TRULY ONE with your BOOTH! From prologic at shortcircuit.net.au Thu Sep 25 18:35:56 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 26 Sep 2008 08:35:56 +1000 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: On Fri, Sep 26, 2008 at 8:20 AM, Lawrence D'Oliveiro wrote: > Object orientation IS procedural. Correction: OOP is Imperative. --JamesMills -- -- -- "Problems are solved by method" From gagsl-py2 at yahoo.com.ar Tue Sep 2 16:22:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 17:22:51 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> Message-ID: En Tue, 02 Sep 2008 12:39:09 -0300, Derek Martin escribi?: > On Tue, Sep 02, 2008 at 01:57:26PM +0000, Marc 'BlackJack' Rintsch wrote: >> > I would argue that they don't represent processes at all; the object is >> > a set of files which connect the standard I/O streams of a subprocess to >> > its parent, and methods to operate on those files. >> >> And the process' ID, an attribute with the process' return code, a method >> to wait until the process is finished and file objects to communicate >> with the process. > > The name popen is an abbreviation of "pipe open" -- the function, and > the class, open pipes to communicate with another process. What you > said is correct; however there are numerous other ways to open > subprocesses. The focus of popen is the communication aspect -- the > opening and control of the pipes -- not the subprocess. That's the > key difference between popen() and all the other methods of starting a > subprocess. Totally irrelevant here - we are talking about the subprocess module, not the popen C function. >> > The C library's popen() function, on which this class is based, No, subprocess.Popen does not use -directly or indirectly- the C popen function. It uses fork or CreateProcess in Windows. > Note that in all of these links that talk about popen, the focus is on > opening pipes or file objects, not on subprocesses: > > http://www.opengroup.org/onlinepubs/009695399/functions/popen.html > http://docs.python.org/lib/os-newstreams.html > http://us3.php.net/popen > http://docs.hp.com/en/B9106-90010/popen.3S.html > http://www.faqs.org/docs/artu/ch07s02.html Again, irrelevant. > The Linux man page unfortunately copies (verbatim) the FreeBSD man > page, which gets it wrong. You can not open a process, but you can > definitely open a pipe. (Ok, if it doesn't agree with you, it must be wrong) Classes represent "things", and class names should be nouns. Functions represent "actions", and their names should be verbs. popen is a good name for a function; Popen is a bad name for a class. -- Gabriel Genellina From rridge at csclub.uwaterloo.ca Mon Sep 8 22:42:11 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 08 Sep 2008 22:42:11 -0400 Subject: universal unicode font for reportlab References: <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> Message-ID: Terry Reedy wrote: >My OpenOffice on WinXP uses a unicode font, I believe Lucida Sans >Unicode, that seems to cover the entire BMP. Lucida Sans Unicode only covers a small subset of Unicode. It may seem to cover a wider range because Windows (and possibly OpenOffice) will automatically substitute characters from other fonts, if necessary. >I don't know whether it was already installed or installed by OO or >how one would get to it to extract it. It's a standard Windows font. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From ldo at geek-central.gen.new_zealand Thu Sep 25 05:20:55 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 25 Sep 2008 21:20:55 +1200 Subject: Regex Help References: Message-ID: In message , Support Desk wrote: > Thanks for the reply ... A: The vulture doesn't get Frequent Poster miles. Q: What's the difference between a top-poster and a vulture? From tjreedy at udel.edu Sat Sep 27 04:45:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2008 04:45:57 -0400 Subject: Running IDLE on 3.0rc1 In-Reply-To: References: Message-ID: Allan wrote: > Terry Reedy writes: > >> I have not seen this posted, so... >> To run IDLE with Python3.0rc1, >> edit Python30/Libs/idlelib/run.py, >> and change "set_daemon(True)" to "daemon = True" and save. >> (This is about line 75, and the only appearance of 'daemon'.) >> Otherwise, you get error message about not starting a subprocess. > Is this related to the tip at the end of the built-in help file in IDLE > regarding the `-n' command option? > No, the above is a bug fix that did not make it into rc1 but has now been committed. It arose because the interface of a class in one of the modules was changed from .set_var(val) to .var = val and the need to change IDLE was not caught. I imagine that checking that IDLE runs in not in the test suite. From m_palmer45 at yahoo.ca Wed Sep 24 22:07:38 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 24 Sep 2008 19:07:38 -0700 (PDT) Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: On Sep 24, 9:27 pm, Tim Arnold wrote: > I have a bunch of processes to run and each one needs its own working > directory. I'd also like to know when all of the processes are > finished. > > (1) First thought was threads, until I saw that os.chdir was process- > global. > (2) Next thought was fork, but I don't know how to signal when each > child is > finished. > (3) Current thought is to break the process from a method into a > external > script; call the script in separate threads. This is the only way I > can see > to give each process a separate dir (external process fixes that), and > I can > find out when each process is finished (thread fixes that). > > Am I missing something? Is there a better way? I hate to rewrite this > method > as a script since I've got a lot of object metadata that I'll have to > regenerate with each call of the script. > > thanks for any suggestions, > --Tim Arnold 1, Does the work in the different directories really have to be done concurrently? You say you'd like to know when each thread/process was finished, suggesting that they are not server processes but rather accomplish some limited task. 2. If the answer to 1. is yes: All that os.chdir gives you is an implicit global variable. Is that convenience really worth a multi- process architecture? Would it not be easier to just work with explicit path names instead? You could store the path of the per- thread working directory in an instance of threading.local - for example: >>> import threading >>> t = threading.local() >>> >>> class Worker(threading.Thread): ... def __init__(self, path): ... t.path=path ... the thread-specific value of t.path would then be available to all classes and functions running within that thread. From fredrik at pythonware.com Wed Sep 17 12:34:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 18:34:46 +0200 Subject: translating ascii to binary In-Reply-To: References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> Message-ID: Lie wrote: >> Any advice about this matter would be very appreciated. >> Thanks in advance. > > It'd be easier to make a one-char version of ascii2bin then make the > string version based on the one-char version. And it'd be a lot easier to read your posts if you trimmed away at least some of the original message before posting. If you cannot do that for some technical reason, I recommend using top-posting instead. From donspauldingii at gmail.com Wed Sep 17 16:14:55 2008 From: donspauldingii at gmail.com (Don Spaulding) Date: Wed, 17 Sep 2008 13:14:55 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> Message-ID: Oh, and Google's single sign-on sucks eggs :-| From aquil.abdullah at gmail.com Fri Sep 5 15:00:41 2008 From: aquil.abdullah at gmail.com (aha) Date: Fri, 5 Sep 2008 12:00:41 -0700 (PDT) Subject: Determining Processor Vender Message-ID: <554ecfcf-96d8-4602-8d5e-ee5d70590124@i76g2000hsf.googlegroups.com> Dose anyone know of a cross-platform method for determining the vendor of a processor? Under linux I can check /proc/cpuinfo. What I'd like to be able to do is determine if a processor is AMD or Intel, so that I can use the appropriate numerical libraries for my application. Regards, Aquil From python-url at phaseit.net Tue Sep 2 17:11:06 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 2 Sep 2008 21:11:06 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 2) Message-ID: QOTW: "Information outlives technology." - Tim Bray http://www.tbray.org/ongoing/When/200x/2003/03/24/XMLisOK, but notice all the offspring of this meme any simple search makes apparent Thoughts about the various forms of the import statement: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f40481f88b5c6bf1/ Looking for an atomic increment operation: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5a60c8b393f73516/ Comparing unicode and byte strings: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c87e2912a95529f9/ Alternatives eval() in unsafe environments: http://groups.google.com/group/comp.lang.python/browse_thread/thread/908cc011e9fd9b72/ An algorithmic problem (identify where "good data" starts inside a sequence) as an excuse to post many creative solutions (including generators and even regular expressions): http://groups.google.com/group/comp.lang.python/browse_thread/thread/8979bf1b01c8233f/ Enumerating all the currently installed Python modules: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4d07c1f7bdb49b94/ When to use try/except: http://groups.google.com/group/comp.lang.python/browse_thread/thread/fc867e86cc1862bf/ str.downer? str.downcase? str.lowercase is the *obvious* name, isn't it? http://groups.google.com/group/comp.lang.python/browse_thread/thread/cfd0a5f387fc82fa/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From gagsl-py2 at yahoo.com.ar Sun Sep 14 15:50:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Sep 2008 16:50:30 -0300 Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <48CD62B8.7070708@islandtraining.com> Message-ID: En Sun, 14 Sep 2008 16:15:04 -0300, Gary Herron escribi?: > Please forget about Abstract Base Classes. They have nothing to do with > what you want, and are a *HUGE* overkill for your application. They > are not (yet) even part of standard Python, and are used primarily for a > class implementor to guarantee to a user of a class that it provides a > specific interface. Just to say that abstract classes *are* already available in Python 2.6: Python 2.6rc1+ (trunk, Sep 13 2008, 11:29:39) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import abc >>> help(abc.abstractmethod) Help on function abstractmethod in module abc: abstractmethod(funcobj) A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... -- Gabriel Genellina From wuwei23 at gmail.com Tue Sep 2 02:12:44 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Sep 2008 23:12:44 -0700 (PDT) Subject: Getting an objetcs dict? References: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> Message-ID: <06c600d2-565b-43de-ae16-76f19f633613@b2g2000prf.googlegroups.com> On Sep 2, 4:31?am, ssecorp wrote: > X.__dict__() and ngot a dict of its variables. > > Now i get errors doing this. what am i doing wrong? The immediate problem is you're not reading the error messages. >>> X.__dict__() Traceback (most recent call last): File "", line 1, in TypeError: 'dict' object is not callable The "not callable" is the big tip-off. As it states, __dict__ is a dictionary object, -not- a method of your class. >>> X.__dict__ {'__module__': '__main__', '__doc__': None} The larger problem is you're not reading the docs & are using this list to teach you Python. Are you aware of the python-tutor list? http://mail.python.org/mailman/listinfo/tutor From maric at aristote.info Fri Sep 5 09:50:32 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 15:50:32 +0200 Subject: Core dumped while interacting with OpenOffice.org via pyuno In-Reply-To: <3f0d61c40809050604y42bc494bqa6c91cb1cc3cd913@mail.gmail.com> References: <3f0d61c40809050604y42bc494bqa6c91cb1cc3cd913@mail.gmail.com> Message-ID: <200809051550.32439.maric@aristote.info> Le Friday 05 September 2008 15:04:22 Marco Bizzarri, vous avez ?crit?: > Hi all. > > I'm experiencing a core dump while working in the following environment > > - debain etch > - python2.3 > - openoffice.org 2.4 > - Zope 2.8.8 > > I was able to get a core dump, and the backtrace shows the following: > > Core was generated by `python2.3 tests/testActs.py'. > Program terminated with signal 11, Segmentation fault. > #0 0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 ... lot of backtrace ... > #9 0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3 > #10 0x08797840 in ?? () > #11 0x0989b6e0 in ?? () > #12 0x00000000 in ?? () > > Now, I can understand that the information I provided are not enough > to give me suggestions on solving this issue; so, I'm asking > suggesions on investigating the issue, namely: > > - should I ask here or is it better if I ask on a openoffice forum? Yes. > - should I use a debug-enabled python in order to have more meaningful > backtraces? What you need is more a debug enabled version of pyuno libraries. > - is there something else I should do in order to have more clues > ("Read The Fine Manual (tm)" is an acceptable answer) You can try to find which function call exactly provoke the exception, the simplest way is to trace execution flow with some print statments and using non forking zope instance (runzope -d if I remember well). -- _____________ Maric Michaud From john.m.roach at gmail.com Mon Sep 15 09:04:27 2008 From: john.m.roach at gmail.com (john) Date: Mon, 15 Sep 2008 06:04:27 -0700 (PDT) Subject: catching exceptions from fortran References: Message-ID: On Sep 11, 8:23?pm, "Gabriel Genellina" wrote: > En Thu, 11 Sep 2008 10:43:08 -0300, john escribi?: > > > > > > > I wrapped some fortran code using F2PY and need to be able to catch > > fortran runtime errors to run the following: > > [reindented] > > # "grid" is a wrapped fortran module > > # no runtime errors incurred when run with the correct inputs for > > filetype > > #------------------------------- > > def readGrid( self, coord='xyz' ): > > ? mg = ( '.FALSE.', '.TRUE.' ) > > ? form = ( 'FORMATTED', 'UNFORMATTED' ) > > ? success = False > > ? for m in mg: > > ? ? for f in form: > > ? ? ? try: > > ? ? ? ? if coord == 'xyz': > > ? ? ? ? ? self.grid.readxyz( self.filename, f, m ) > > ? ? ? ? ? success = True > > ? ? ? ? elif coord == 'xyrb': > > ? ? ? ? ? self.grid.readxyrb( self.filename, f, m ) > > ? ? ? ? ? success = True > > ? ? ? ? else: > > ? ? ? ? ? import sys > > ? ? ? ? ? print 'gridtype "' + str(coord) + '" not supported. ' \ > > ? ? ? ? ? ? ? + '' > > ? ? ? except: > > ? ? ? ? continue > > ? if not success: > > ? ? import sys > > ? ? print 'gridfile "' + str(self.filename) + '" not read in any ? > > recognized format' \ > > ? ? ? ? + ' ' > > #---------------------------- > > I suppose you want to stop trying other formats after a successful read; ? > in that case put a break statement just below both success=True. > If coord is unrecognized, the code above prints the same message 4 times. ? > Instead of printing a message, in those cases usually an exception is ? > raised, letting a higher layer handle the error. And using string ? > interpolation is a lot easier than building the message in parts: > raise ValueError('gridtype "%s" not supported. ' % ? > coord) > If you want to catch errors on the Fortran code *only*, the try/except ? > should be more specific (both in scope and what it catches). The Exception ? > class is the more generic exception that you should catch. > > > basically, what i want to happen is to try to run 'something' with the > > wrapped fortran code and if that doesn't work (error encountered, > > etc.) try something else. ?is there an easier way to go about doing > > this? ?is there something i'm missing about catching exceptions here? > > I'd reorder the code in this way (untested, of course): > > def readGrid(self, coord='xyz'): > > ? ? ?def try_all_formats(read_function, filename): > ? ? ? ? ?mg = ('.FALSE.', '.TRUE.') > ? ? ? ? ?form = ('FORMATTED', 'UNFORMATTED') > ? ? ? ? ?success = False > ? ? ? ? ?for m in mg: > ? ? ? ? ? ? ?for f in form: > ? ? ? ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ? ? ? ?read_function(filename, f, m) > ? ? ? ? ? ? ? ? ? ? ?success = True > ? ? ? ? ? ? ? ? ? ? ?break > ? ? ? ? ? ? ? ? ?except Exception, e: > ? ? ? ? ? ? ? ? ? ? ?# this line only for debugging purposes > ? ? ? ? ? ? ? ? ? ? ?print "error %r when using m=%r f=%r" % (e, m, f) > ? ? ? ? ? ? ? ? ? ? ?continue > ? ? ? ? ?if not success: > ? ? ? ? ? ? ?raise ValueError('gridfile "%s" not read ' > ? ? ? ? ? ? ? ? ? ? 'in any recognized format ' > ? ? ? ? ? ? ? ? ? ? '' % filename) > > ? ? ?if coord == 'xyz': > ? ? ? ? ?try_all_formats(self.grid.readxyz, self.filename) > ? ? ?elif coord == 'xyrb': > ? ? ? ? ?try_all_formats(self.grid.readxyrb, self.filename) > ? ? ?else: > ? ? ? ? ?raise ValueError('gridtype "%s" not supported. ' > ? ? ? ? ? ? ? ? ?'' % coord) > > I don't know about F2PY but the values ('.FALSE.', '.TRUE.') seem ? > suspicious. AFAIR, .FALSE. and .TRUE. are the Fortran spellings of False ? > and True in Python - they're not strings, but boolean values. So maybe the ? > right way is to use > ? ? ? ? ?mg = (False, True) > > Your code above was catching and ignoring everything, even this error, if ? > it happened. > > -- > Gabriel Genellina Gabriel, i agree with everything you write, but unless i misunderstood something, this still doesn't address the main problem of the try- except construct not preventing the program from aborting when the wrapped fortran code encounters an error. i tried hard-coding all of the passed variables to the fortran code and ran that code alone-- works. however, when an incorrect fortran read is attempted (ex. formatted read on unformatted file), the python except still fails to catch the error and the code aborts with a runtime error... From steven at REMOVE.THIS.cybersource.com.au Mon Sep 1 05:16:56 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2008 09:16:56 GMT Subject: Know if a object member is a method References: Message-ID: On Mon, 01 Sep 2008 10:43:25 +0200, Luca wrote: > Hi all. > > I think this is a newbie question... what is the best method to know if > a property of an object is a function? > > I'm thinking something as > > if type(obj.methodName)==??? > > Can someone help me? That's not quite as easy as you might think. In my testing, calling type(obj.methodName) can give any of the following: There may be others as well. Possibly all you really need is to check if the attribute is callable without caring what type of method or function it is: >>> callable(obj.methodName) True In my opinion, that's the best way. If you are sure that the method won't have side-effects or bugs: >>> try: ... obj.method() ... except: ... print "Not a method" ... (But how can you be sure?) If you insist on an explicit test, try this: import new type(obj.methodName) == new.instancemethod or alternatively: >>> isinstance(obj.methodName, new.instancemethod) True -- Steven From python.list at tim.thechases.com Tue Sep 23 10:45:12 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 23 Sep 2008 09:45:12 -0500 Subject: improving a huge double-for cycle In-Reply-To: References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D2502C.4000200@tim.thechases.com> Message-ID: <48D900F8.10506@tim.thechases.com> km wrote: > how abt this ? > > N = len(IN) > for k in range(N): > for j in range(N): > if j >= k: # or k <= j > doSomething() This has the root problem that the "if" statement is evaluated N*N times, which is ugly/slow O(N^2) behavior. My solution managed to reduce it by a constant multiplier, but several folks proposed a more elegant O(N) solution which was leaps & bounds faster. -tkc From aweraw at gmail.com Tue Sep 30 03:50:27 2008 From: aweraw at gmail.com (Aidan) Date: Tue, 30 Sep 2008 17:50:27 +1000 Subject: Python arrays and sting formatting options In-Reply-To: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: <48e1da44@dnews.tpgi.com.au> Ivan Reborin wrote: > Hello everyone, > > I was wondering if anyone here has a moment of time to help me with 2 > things that have been bugging me. > > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? > > 2. I've read the help on the next one but I just find it difficult > understanding it. > I have; > a=2.000001 > b=123456.789 > c=1234.0001 > > How do you print them with the same number of decimals ? > (eg. 2.000, 123456.789, 1234.000) > and how do you print them with the same number of significant > decimals? > (eg. 2.000001, 123456.7, 1234.000 - always 8 decimals) ? > > > Is something like this possible (built-in) in python ? > > Really grateful for all the help and time you can spare. > > -- > Ivan I'm not sure if this is applicable to your multi-dimensional list problem... but it sounded a bit sudoku like (with row, columns and groups) so I thought I'd share a bit of code of developed in regards to solving sudoku puzzles... Given a list of 9 list elements, each with nine elements (lets call it sudoku_grid), the following list comprehensions produce lists of indexes into sudoku grid vgroups = [[(x,y) for y in xrange(9)] for x in xrange(9)] hgroups = [[(x,y) for x in xrange(9)] for y in xrange(9)] lgroups = [[(x,y) for x in xrange(a,a+3) for y in xrange(b,b+3)] for a in xrange(0,9,3) for b in xrange(0,9,3)] where sudoku_grid[y][x] yields the value at position (x,y), assuming the top left corner is indexed as (0,0) HTH From castironpi at gmail.com Tue Sep 2 14:33:37 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 2 Sep 2008 11:33:37 -0700 (PDT) Subject: rope class (heavyweight string) Message-ID: Does anyone want to talk about a Rope implementation in Python? It doesn't get faster than the native strings until about 2 megs. P.S. Didn't your momma ever tell you not to talk on newsgroups? From gklein at xs4all.nl Sun Sep 14 06:51:35 2008 From: gklein at xs4all.nl (Gertjan Klein) Date: Sun, 14 Sep 2008 12:51:35 +0200 Subject: How to emit Cyrillic and Chinese via unicode from console mode? References: <543bde0c-4d99-4d79-a4dd-b6f8d85e8c48@l64g2000hse.googlegroups.com> Message-ID: <2vqpc4pd7qfrsgsove5f5prncbglhjast0@4ax.com> rs387 wrote: >sys.stdout = encodings.utf_8.StreamWriter(sys.stdout) > >win32console.SetConsoleCP(65001) >win32console.SetConsoleOutputCP(65001) [...] >If redirected to file, all is well, this prints everything properly in >UTF-8. If ran on the console, this also prints everything correctly, >but then throws a mysterious exception: Interesting. On my system (Windows XP) the console codepage does not change, and hence the characters don't print properly (I get some of the CP437 line drawing characters, for example). I have never been able to convince windows to assume/support UTF-8 encoding in the console, programatically or otherwise. :( Gertjan. -- Gertjan Klein From kaiser.vocote at gmail.com Tue Sep 16 07:30:41 2008 From: kaiser.vocote at gmail.com (Andreas Kaiser) Date: Tue, 16 Sep 2008 04:30:41 -0700 (PDT) Subject: What is "finally:" for? References: Message-ID: On 16 Sep., 13:25, "Max Ivanov" wrote: > Hi all! > When and where I should use try-except-finally statement? What is the > difference between: > -------- > try: > ? A... > except: > ? B.... > finally: > ? C... > -------- It does A if no exception or B if an exception occurs. THEN it does always C. > > and > ------- > try: > ? A... > except: > ? B.... > C... If an exception occurs, C is never reaching. Andreas From metallourlante at gmail.com Sun Sep 21 08:51:13 2008 From: metallourlante at gmail.com (Alex) Date: Sun, 21 Sep 2008 05:51:13 -0700 (PDT) Subject: understanding list scope Message-ID: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> Hi all! I have a problem understanding the behaviour of this snippet: data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) for i in range(len(data_set)): ds = data_set[:] data = ds[i] if i == 1: data['param'] = "y" if i == 2: data['param'] = "x" print data_set This script print out: ({'param': 'a'}, {'param': 'y'}, {'param': 'x'}) Why? I'm coping data_set in ds so why data_set is changed? Thanks in advance. Alex From steven at REMOVE.THIS.cybersource.com.au Fri Sep 12 02:30:42 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 12 Sep 2008 06:30:42 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> Message-ID: On Thu, 11 Sep 2008 22:40:01 -0700, Dennis Lee Bieber wrote: > On 12 Sep 2008 03:37:51 GMT, Steven D'Aprano > declaimed the following in > comp.lang.python: > > >> I'm pretty sure you're wrong. XML can be used for serialization, but >> that doesn't mean it is only sequential data. XML is suitable for >> hierarchical data too. To quote Wikipedia: >> > There is a difference between the format of the data content, and > the processing of that data... Regardless of the content, one > essentially has to process the XML /file/ sequentially, and translate > into an in-memory model that allows for accessing said data. To reach > the nth subelement of the mth element requires reading all 1..m-1 > elements, followed by all 1..n-1 subelements in m. Modifying any element > requires rewriting the entire file. Which is why I previously said that XML was not well suited for random access. I think we're starting to be sucked into a vortex of obtuse and opaque communication. We agree that XML can store hierarchical data, and that it has to be read and written sequentially, and that whatever the merits of castironpi's software, his original use-case of random access to a 4GB XML file isn't workable. Yes? -- Steven From To-Email-Use-The-Envelope-Icon at My-Web-Site.com Sat Sep 27 18:56:39 2008 From: To-Email-Use-The-Envelope-Icon at My-Web-Site.com (Jim Thompson) Date: Sat, 27 Sep 2008 15:56:39 -0700 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> Message-ID: <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> On Sat, 27 Sep 2008 18:47:16 -0400, default wrote: >On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko > wrote: > >>Hello, this is Milenko Stojadinovic from town Banjaluka, >>Bosnia and Herzegovina, also known as Cvrcko >>Does anyone know of any bars in town where I can >>swallow a bucket of cum? It can be either dog, >>horse or human cum. Also, does anyone know of >>any sex bars where people will shit in your mouth? >>I also like eating shit. > >Come to the US and park your mouth in front of George Bush - all the >Bshit you can eat - and it keeps on coming! > >I have a buddy in Bosna - he's normal. Now you know why I blanket kill-file googlegroups. ...Jim Thompson -- | James E.Thompson, P.E. | mens | | Analog Innovations, Inc. | et | | Analog/Mixed-Signal ASIC's and Discrete Systems | manus | | Phoenix, Arizona 85048 Skype: Contacts Only | | | Voice:(480)460-2350 Fax: Available upon request | Brass Rat | | E-mail Icon at http://www.analog-innovations.com | 1962 | Viewed from afar, even whores and Democrats seem reputable From lists at cheimes.de Sun Sep 28 14:39:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 28 Sep 2008 20:39:05 +0200 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: process wrote: > What is not an object in Python? Everything that is not part of Python's syntax is an object, including all string and number types, classes, metaclasses, functions, models, code and more. It's technically not possible to have something like e.g. an int that isn't an object. > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? Because readability is more important than purity. By the way len(egg) is just syntactic sugar for egg.__len__() with some extra checks. From dstromberglists at gmail.com Mon Sep 22 18:49:40 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 22 Sep 2008 22:49:40 GMT Subject: looper Message-ID: <8iVBk.1045$x%.476@nlpi070.nbdc.sbc.com> I was asked by my employer to publish this a bit ago, so here it is: http://stromberg.dnsalias.org/~dstromberg/looper/ It's a multithreaded script for running n POSIX shell commands m at a time with good error checking. It allows for things like stashing in ssh $hostname or rsync $hostname in a convenient way - with pretty complete shell quoting so that your command comes out on the other side of the ssh command the same way it went into looper. It also allow I hope someone finds it useful. I know I have. Followups have been directed to comp.unix.shell. From mobiledreamers at gmail.com Mon Sep 22 19:00:43 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Mon, 22 Sep 2008 16:00:43 -0700 Subject: looper In-Reply-To: <8iVBk.1045$x%.476@nlpi070.nbdc.sbc.com> References: <8iVBk.1045$x%.476@nlpi070.nbdc.sbc.com> Message-ID: Great thanks On 9/22/08, Dan Stromberg wrote: > > > I was asked by my employer to publish this a bit ago, so here it is: > > http://stromberg.dnsalias.org/~dstromberg/looper/ > > It's a multithreaded script for running n POSIX shell commands m at a > time with good error checking. It allows for things like stashing in ssh > $hostname or rsync $hostname in a convenient way - with pretty complete > shell quoting so that your command comes out on the other side of the ssh > command the same way it went into looper. It also allow > > I hope someone finds it useful. I know I have. > > Followups have been directed to comp.unix.shell. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://gpirate.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Mon Sep 22 05:07:43 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 09:07:43 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> Message-ID: On Mon, 22 Sep 2008 10:12:38 +1000, James Mills wrote: > On Mon, Sep 22, 2008 at 9:39 AM, Calvin Spealman > wrote: >> I call it an obvious misuse and misunderstanding of why you'd use a >> class in the first place. Either create an instance and not make these >> things classmethods or just share the stuff in a module-level set of >> variables. But the instantiating is the best options. Your class >> attributes might not be globals, but you're still using global state >> and you should avoid it where you can. > > I concur. Use a _proper_ state object that you share amongst your other > objects. But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. I'm not trying for a Borg or Singleton: the user can call the factory as many times as they want, but the objects returned shouldn't share any state. I don't know if what I want has a name. Judging from people's reactions, I'd say probably not. (For the pedantic: the "instances" will all have the same methods, but I'm not including methods as state.) > For instance, in many of my systems and applications I write, I > often have an "Environment" instance, which is a container object that > holds other objects required by parts of the system. Every other > component/object in the system that is instantiated recievees exactly > one instnace of thie "Environment" called, "env". > > Accessing shared states amongst components/objects within the system is > as simple as this: > > class Foo(object): > > def __init__(self, env, *args, **kwargs): > self.env = env > > def foo(self): > if self.env.some_state: > print "Do something useful" Seems wasteful to me. Why give every instance it's own instance-level reference to the shared object? Why not make env a class attribute, set once, instead of every time you instantiate the class? class Foo(object): env = env But in any case, this is not the behaviour I want. It's the opposite of the behaviour I want. I don't want the objects to share state. I'm not exactly sure what I said that has given so many people the impression that I do. -- Steven From circularfunc at yahoo.se Tue Sep 16 17:24:49 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 14:24:49 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> Message-ID: <99c53e1a-a693-4f35-b937-d172c565077c@m36g2000hse.googlegroups.com> On Sep 16, 10:53?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 16, 3:16?pm, cnb wrote: > > > > > On Sep 16, 7:49?pm, "Aaron \"Castironpi\" Brady" > > > > Now I have my personal programs in C:/Python25/Progs/ > > > > > How do I add so that I can just do "import somefile" from anywhere in > > > > that directory in the interpreter and it can load files from other > > > > folders in that directory. > > > > Add a file: \Lib\site-packages\locals.pth > > > > with contents, path to the directory you want to add (/python25/progs/) > > > And we have a winner! > > > Now it works. Both doing import and loading form fiel with C-c C-l > > > However jsut including C:/Python/Progs wasn't enough. I had to add the > > folder inside that that contains the files i needed. > > > so how do i add all files within progs? is there something like C:/ > > python25/progs/* ? > > You have: > > c:/python/progs/abc/filea.py > c:/python/progs/abc/fileb.py > c:/python/progs/def/filed.py > c:/python/progs/def/filee.py > > __init__.py in progs ? (empty...) > __init__.py in abc > __init__.py in def > > c:/python/site-packages/lib/locals.py ?which contains: > c:/python/progs/ > > You don't need the subdirectories. ?You can do: > > import abc > import abc.filea > from abc import filea no I can't... From Richard_Martineau at xyratex.com Tue Sep 16 08:52:10 2008 From: Richard_Martineau at xyratex.com (Richard_Martineau at xyratex.com) Date: Tue, 16 Sep 2008 05:52:10 -0700 (PDT) Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows References: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Message-ID: On Sep 16, 11:02?am, "Gabriel Genellina" wrote: > En Tue, 16 Sep 2008 06:25:27 -0300, ? > escribi?: > > > I wonder if anyone can advise me or has done similar to the following? > > > Basically I've downloaded the Python 2.5.2 source code that builds > > with Visual Studio 6.0. I've built Python for windows. This was easy > > (it even came with the pcbuild.dsw workspace file). Great! > > > Now comes the troubled bit...I now look for similar source code for > > Python extensions Numpy and Scipy but the source code and directories > > are not all obvious. Looks like these are normally built via other > > compilers. However I need to do all my builds in VS 6.0. > > > For Numpy (I haven't got as far as Scipy yet) I've organised the > > source code into the following projects and lumped them all into my > > new workspace numpy.dsw: > > Don't try to roll your own projects, compile it using distutils instead. ? > Distutils takes care of defining the right symbols and compiler options, ? > and should detect VS. > I'm pretty sure the Numpy README file (or similar) describes how to build ? > it; usually you install the required dependencies and then run: > python setup.py build > > -- > Gabriel Genellina Thanks for your message. Unfortunately I need as much control and visibility as possible as I eventually want to port from windows os to pharlap rtos. I appreciate your advice and I understand it's not a great idea to roll your own, but if it's possible, I really need to do so. Any further help/advice greatly appreciated Richard From wuwei23 at gmail.com Tue Sep 9 20:35:00 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 9 Sep 2008 17:35:00 -0700 (PDT) Subject: rss feed generation References: Message-ID: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> On Sep 10, 7:30?am, "Blake Garner" wrote: > I'm looking for suggestions on how to approach generating rss feed > .xml files using python. What modules to people recommend I start > with? http://www.dalkescientific.com/Python/PyRSS2Gen.html From grante at visi.com Tue Sep 16 09:54:39 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:54:39 -0500 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: On 2008-09-16, Armin wrote: > Duncan Booth wrote: >> "Chris Rebert" wrote: >>> On Tue, Sep 16, 2008 at 1:20 AM, Armin wrote: >>>> [1,2,3,4,7].append(c) -> Is this a valid expression? >>> Literally, no, because you can't call methods on literals. >> >> Rubbish. There is no restriction about calling methods on literals. That >> expression is perfectly valid but has no practical use that I can see. > > The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > (with c = [8,9]) is identical, No, they're not: >>> a=[1,2,3,4,7] >>> c=[9,10] >>> a.append(c) >>> a [1, 2, 3, 4, 7, [9, 10]] >>> a=[1,2,3,4,7] >>> c=[9,10] >>> a+c [1, 2, 3, 4, 7, 9, 10] You really ought to install a copy of Python so you can try out things and see how they really work. > but the first expression doesn't provide a value. Strange by > design ... Not really. You just need to make a little effort to understand the reasoning (which has been explained to you) behind Python's design decision. -- Grant Edwards grante Yow! Somewhere in DOWNTOWN at BURBANK a prostitute is visi.com OVERCOOKING a LAMB CHOP!! From steven at REMOVE.THIS.cybersource.com.au Thu Sep 11 05:05:47 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Sep 2008 09:05:47 GMT Subject: dict slice in python (translating perl to python) References: Message-ID: On Thu, 11 Sep 2008 03:36:35 -0500, Nick Craig-Wood wrote: > As an ex-perl programmer and having used python for some years now, I'd > type the explicit > > v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > > Or maybe even > > v1 = mydict['one'] # 54 chars > v2 = mydict['two'] > v3 = mydict['two'] > > Either is only a couple more characters to type. But that's an accident of the name you have used. Consider: v1,v2,v3 = section_heading_to_table_index['one'], \ section_heading_to_table_index['two'], \ section_heading_to_table_index['two'] # 133 characters versus: v1,v2,v3 = [section_heading_to_table_index[k] for k in ['one','two','two']] # 75 characters It also fails the "Don't Repeat Yourself" principle, and it completely fails to scale beyond a handful of keys. Out of interest, on my PC at least the list comp version is significantly slower than the explicit assignments. So it is a micro-optimization that may be worth considering if needed -- but at the cost of harder to maintain code. > It is completely > explicit and comprehensible to everyone, in comparison to > > v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars That's a matter for argument. I find the list comprehension perfectly readable and comprehensible, and in fact I had to read your explicit assignments twice to be sure I hadn't missed something. But I accept that if you aren't used to list comps, they might look a little odd. -- Steven From dmitry at athabascau.ca Wed Sep 24 18:21:01 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Wed, 24 Sep 2008 22:21:01 GMT Subject: is decorator the right thing to use? Message-ID: Hi, after hearing a lot about decorators and never actually using one I have decided to give it a try. My particular usecase is that I have class that acts as a proxy to other classes (i.e. passes messages along to those classes) however hand-coding this type of class is rather tedious, so I decided to use decorator for that. Can somebody tell me if what I'm doing is a potential shot-in-the-foot or am I on the right track? (Note, It's rather rudimentary proof-of-concept implementation and not the final solution I'm about to employ so there are no optimizations or signature-preserving code there yet, just the idea). Here's the code: class A: b=None def __init__(self,b): self.val='aval' self.b=b b.val='aval' def mymethod(self,a): print "A::mymethod, ",a def mymethod2(self,a): print "A::another method, ",a def Aproxy(fn): def delegate(*args,**kw): print "%s::%s" % (args[0].__class__.__name__,fn.__name__) args=list(args) b=getattr(args[0],'b') fnew=getattr(b,fn.__name__) # get rid of original object reference del args[0] fnew(*args,**kw) setattr(A,fn.__name__,delegate) return fn class B: def __init__(self): self.val='bval' @Aproxy def bmethod(self,a): print "B::bmethod" print a, self.val @Aproxy def bmethod2(self,a): print "B::bmethod2" print a, self.val b=B() b.bmethod('foo') a=A(b) b=B() b.val='newval' a.bmethod('bar') a.bmethod2('zam') From electronixtar at gmail.com Sun Sep 28 01:37:09 2008 From: electronixtar at gmail.com (est) Date: Sat, 27 Sep 2008 22:37:09 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! Message-ID: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> >From python manual str( [object]) Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''. now we try this under windows: >>> str(u'\ue863') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in position 0 : ordinal not in range(128) FAIL. also almighty Linux Python 2.3.4 (#1, Feb 6 2006, 10:38:46) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> str(u'\ue863') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in position 0: ordinal not in range(128) Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> str(u'\ue863') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in position 0: ordinal not in range(128) Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> str(u'\ue863') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in position 0: ordinal not in range(128) The problem is, why the f**k set ASCII encoding to range(128) ???????? while str() is internally byte array it should be handled in range(256) !!!!!!!!!! http://bugs.python.org/issue3648 One possible solution(Windows Only) >>> str(u'\ue863'.encode('mbcs')) '\xfe\x9f' >>> print u'\ue863'.encode('mbcs') ?? I now spending 60% of my developing time dealing with ASCII range(128) errors. It was PAIN!!!!!! Please fix this issue. http://bugs.python.org/issue3648 Please. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 10:40:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 16:40:42 +0200 Subject: Eleganz way to get rid of \n In-Reply-To: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: <48bbfe96$0$16237$426a74cc@news.free.fr> Hans M?ller a ?crit : > Hello, > > I'm quite often using this construct: > > for l in open("file", "r"): > do something > > here, l contains the \n or \r\n on windows at the end. > I get rid of it this way: > > for l in open("file", "r"): > while l[-1] in "\r\n": > l = l[:-1] > > I find this a little bit clumsy, indeed. > but it works fine. > > Has someone a better solution ? help(str.rstrip) From circularfunc at gmail.com Tue Sep 2 19:44:02 2008 From: circularfunc at gmail.com (ssecorp) Date: Tue, 2 Sep 2008 16:44:02 -0700 (PDT) Subject: Is try-except slow? Message-ID: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> or why does this take so god damn long time? and if I run into an IndexError it break out of the inner loop right? so having range up to 10000000 or 1000 wouldn't matter if biggest working x is 800? def getPixels(fileName): im = PIL.Image.open(fileName) colors = [] for y in range(1, 1000): row = [] for x in range(1, 1000): try: color = im.getpixel((x,y)) row.append(color) except IndexError: break colors.append(row) return numpy.array(colors) From marco.bizzarri at gmail.com Tue Sep 16 08:47:02 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Tue, 16 Sep 2008 14:47:02 +0200 Subject: MVC with Python In-Reply-To: References: <3f0d61c40809151307p76c864e5he9911593b676548e@mail.gmail.com> Message-ID: <3f0d61c40809160547t339226acx19a7a0a0f58a6e73@mail.gmail.com> On Tue, Sep 16, 2008 at 1:26 PM, Georg Altmann wrote: > Marco Bizzarri schrieb: >> >> On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann >> wrote: >>> >>> Hello, >>> >>> I need some advice on how to implement model-view-controller. I am trying >>> to >>> develop a GUI application with PyQt, yet the problem rather applies to >>> mvc >>> in general, not just GUI applications. >>> >>> Let's say the data is a list of objects with a common base class. The >>> views >>> are either a graphical representation of the objects or some form of >>> textual >>> input. The views shall change the model by using command objects (for >>> undo, >>> e.g. QUndoCommand). >>> >>> My current approach is to implement the model as a class with a list-like >>> interface, with methods insert(), remove(), __getitem__(), >>> __setitem__(),... >>> and a signal to notify the views. The objects in the list have methods to >>> change their state as well. >>> >>> My problem is, how do the commands interact with the model? >>> Let's say I have a command that modifies an object o in the list. >>> >>> 1) If list[key_to_o] returns a reference to the object, the command can >>> modify the object by using this reference, i.e. list[key_to_o].setX(). So >>> there is no way for the list to know when the object changed - how can it >>> emit a singal then? >>> >>> 2) If list[key_to_o] returns a deep copy of the object, >>> copy_of_o = list[key_to_o], the command mofifies the copy and the updates >>> the list: list[key_to_o] = copy_of_o. Now the list can emit a signal in >>> __setitem__(). >>> While this may work, it seems awkward to copy around objects just to >>> perform >>> a possibly simple operation on them. Additionally it might not be >>> feasible >>> once objects get complex. >>> >>> 3) The interface of the classes of the objects could be reflected in the >>> list class, i.e. list.set_x_on_obj(key_to_obj,x). This would probably >>> make >>> the list class interface very bloated. >>> >>> Of course the problem is not really limited to Python, my apologies if >>> I'm >>> totally off-topic here. >>> >>> Regards >>> Georg >>> >> >> Well, I think one of the assumptions of the MVC is that the view can >> be notified about the changes in the model. According to your >> interface, the View can just be notified on operations about the >> *whole* model, like adding or removing elements from it. >> >> But the elements of your list-like class should be a part of your >> model, and therefore should be able to notify the Views by >> themselfves. > > Ok, consider this: say the model needs to compute some sort of value by > iterating over all objects in the list (for example some sort of hash). Some > kind of view then displays this value. > I could implement this by connecting a signal in each object to a slot in > the list class which in turn emits a signal which is connected to the view. > > But this implies all the objects in the list have to be instances of > QObject. I wonder if this is isn't a weird design, because for example all > value type classes in Qt don't derive from QObject, e.g. QString. My list > objects are not that simple (in terms of the data structure). So is it ok to > make them QObjects? > Did you take a look at this? http://www.potu.com/man/doc.trolltech.com/4.0/model-view-programming.html It seems to imply that you should use QtAbstractItemModel as a base class for all your models. But since I'm not an expert about Qt, I cannot really say. Regards Marco > > Regards > Georg > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From d3vvnull at gmail.com Fri Sep 26 08:10:21 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 07:10:21 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DCC618.9040907@wildenhain.de> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> Message-ID: <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> cursor.execute(""" SELECT titem.object_id, titem.tag_id FROM tagging_taggeditem titem WHERE titem.object_id IN (%s) """ % ','.join([str(x) for x in [1,5,9]]) On Fri, Sep 26, 2008 at 6:23 AM, Tino Wildenhain wrote: > Hi, > > Bruno Desthuilliers wrote: > >> bcurtu a ?crit : >> >>> Hi, >>> >>> I have a BIIIIIG problem with the next query: >>> >>> cursor.execute(""" >>> SELECT titem.object_id, titem.tag_id >>> FROM tagging_taggeditem titem >>> WHERE titem.object_id IN (%s) >>> """,( eid_list)) >>> >>> eid_list is suppossed to be a list of ids = [1,5,9] >>> >>> How can I make it work? >>> >> >> You have to build your sql statement in three stages: >> >> # stage 0: the template >> sql_template = """ >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """ >> >> # stage 1: build correct place_holders string for the actual number >> # of items in eid_list >> place_holders = ", " .join("%s" for x in xrange(len(eid_list))) >> > > Hm. either ", ".join(["%s"]*len(eid_list)) > or ", ".join("%s" for x in eid_list) > > should produce the same, wouldn't it? :-) > > # stage 2 : build the effective sql statement >> sql = sql_template % place_holders >> >> # ok, let's go: >> cursor.execute(sql_template, eid_list) >> >> >> NB : you can of course make it in a single statement, but readability will >> suffer: >> >> cursor.execute( >> """ >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """ % ", " .join("%s" for x in xrange(len(eid_list))), >> eid_list >> ) >> > > I'd think giving the arguments in a form of an array type should > work too. At least in postgres there are references to do so. > > Regards > Tino > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From code at pizzashack.org Mon Sep 1 23:05:22 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 1 Sep 2008 23:05:22 -0400 Subject: Processes in Linux from Python In-Reply-To: <6i1h3cFog1v1U1@mid.uni-berlin.de> References: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> <6i1h3cFog1v1U1@mid.uni-berlin.de> Message-ID: <20080902030522.GO29228@dragontoe.org> On Mon, Sep 01, 2008 at 08:40:42AM +0200, Diez B. Roggisch wrote: > Johny schrieb: > >To get a number of the http processes running on my Linux( Debia box) > >I use > >ps -ef | grep "[h]ttpd" | wc -l [...] > The shell does the exact same thing. And by the way: i think you miss a > > grep -v grep Indeed not. The brackets around the 'h' (which make it a character class, or range if you prefer) prevent the regex from matching itself. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dahl.joachim at gmail.com Wed Sep 17 03:54:36 2008 From: dahl.joachim at gmail.com (Joachim Dahl) Date: Wed, 17 Sep 2008 00:54:36 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> <2cbfdce2-9203-4136-a274-bc7d19dc293a@y38g2000hsy.googlegroups.com> <3d9ab5e0-924b-48c1-b91b-2db1ca91e14c@26g2000hsk.googlegroups.com> Message-ID: CVXOPT supports ILP via GLPK or MOSEK. Documentation is in the doc- strings for cvxopt.glkp.ilp and cvxopt.mosek.ilp. The ILP interfaces are not mentioned otherwise in the documentation, as the main focus of CVXOPT is convex solvers. For additional questions on CVXOPT please use the discussion forum: http://groups.google.com/group/cvxopt best regards Joachim On Sep 17, 5:57?am, Fett wrote: > On Sep 16, 9:44 pm, "Aaron \"Castironpi\" Brady" > > > > wrote: > > On Sep 16, 9:25 pm, Fett wrote: > > > > On Sep 16, 9:00 pm, "Aaron \"Castironpi\" Brady" > > > > wrote: > > > > On Sep 16, 8:50 pm, Fett wrote: > > > > > > I am trying to find a wrapper to do linear programming within python. > > > > > I am using an ubuntu machine and I have apt-get'd lp_solve, which > > > > > works just fine. If someone knows of a wrapper that will work with > > > > > that that'd be great. > > > > > > I also heard that scipy has a wrapper, however, I can't find any > > > > > documentation on it, nor can I seem to find it with dir(). If anyone > > > > > knows where there is good documentation on this I would love to use > > > > > that (the more native to python the better imo). > > > > > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > > > > > openopt, andcvxopt. I can't seem to find any with enough > > > > > documentation to get me off the ground. Some I can't compile, some I > > > > > can't even find out how to compile. > > > > > > If anyone knows of an LP package (preferably with IP as well, like > > > > > lp_solve has), that interfaces well with python and has enough > > > > > documentation to get a dependency newb like myself off the ground that > > > > > would be great. > > > > > Google says: > > > > > about 254,000 for linear programming python. > > > > > Link 3 is: > > > > >http://wiki.python.org/moin/NumericAndScientific/Libraries > > > > > Scroll down. > > > > Yes, many of those seem to be deprecated, without destinations to > > > links, most are poorly or not documented at all. The few that are, I > > > still can't get running. Of those 254, I think I have tried at least > > > 10 pages worth. Still no luck. > > > > # lpsolvpy - Can't get it to compile - dependency problems. > > > # Lp_solve5 - NO python binding yet. Volunteers needed for python > > > bindings. > > > # pycplex - You need to compile the CPX.so module. Change the required > > > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > > > sure what to do here. > > > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > > > I missed the second link to the python bindings, looked all over the > > > glpk site for anything about python. > > > # SciPy --http://www.scipy.org-supposedlyhas this, but as I said, > > > I can't find any mention of it anywhere but on the site you linked. > > > # pySimplex - (broken link)(broken link) > > > # Simplex - link is broken, but nothing is mentioned > > > > I'll take a closer look at glpk's python bindings and if there is any > > > documentation on them, maybe I'll have some luck. btw, I have been > > > looking for something that works, I have over 5 packages on my desktop > > > that I have tried to get up and running, but none of them seem to > > > work. glpk makes 6. > > > If you can find one working in C, use ctypes to link into Python. ?We > > can help you with that part. ?It lets you pass primitive types, > > structs, arrays, pointers, to C modules and return values. ?You need > > to know the C signatures to set up the Pythonized signatures. > > Ok, it seems that I have found one (although without an integer > programming component): upon searching for glpk in the package manager > in ubuntu I found a package calledcvxopt, it is a bit clunky > (compared to the niceness of lp_solve), but I think I can figure this > one out. Thanks all who answered. From rw at smsnet.pl Thu Sep 18 12:35:09 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 18 Sep 2008 18:35:09 +0200 Subject: Cython dynamic library problem References: Message-ID: <8763otl8ea.fsf@merkury.smsnet.pl> Tommy Grav writes: > I am trying to learn how to use cython, and while I am following the > cython-dev > mailing list I didn't feel like this question was totally appropriate > for its audience > so I am trying here first. [...] > Does anyone know what the ImportError means and how to correct it? I would try to use `distutils` because this package is much wiser than me and knows all necessary switches for gcc. ;) # test_cython.pyx def test(x): return x * x # test_cython.py from pyx_test import test print test(0) print test(10) # setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext as build_pyx setup(name = 'pyx_test', ext_modules=[Extension('pyx_test', ['test_cython.pyx'])], cmdclass = { 'build_ext': build_pyx }) $ python2.5 setup.py build_ext -i running build_ext cythoning test_cython.pyx to test_cython.c building 'pyx_test' extension creating build/temp.linux-i686-2.5 gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.5 -c test_cython.c -o build/temp.linux-i686-2.5/test_cython.o test_cython.c:86: warning: function declaration isn?t a prototype test_cython.c:241: warning: function declaration isn?t a prototype test_cython.c:59: warning: ?__pyx_skip_dispatch? defined but not used gcc -pthread -shared -Wl,-O1 build/temp.linux-i686-2.5/test_cython.o -o pyx_test.so $ python2.5 test_cython.py 0 100 HTH, Rob From fredrik at pythonware.com Sun Sep 7 06:40:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 07 Sep 2008 12:40:01 +0200 Subject: unexpected class behaviour In-Reply-To: <48c3ad5d@news.uni-ulm.de> References: <48c3ad5d@news.uni-ulm.de> Message-ID: Jan Sch?fer wrote: > can anyone explain the behaviour of the following code sniplet: well, it *is* explained in the tutorial, the language reference, and the FAQ, so yes, it can be explained ;-) for more information, see this page: http://effbot.org/zone/default-values.htm From deets at nospam.web.de Wed Sep 10 09:25:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 15:25:53 +0200 Subject: Adding further report options to unittest.py References: Message-ID: <6iq07jFs30egU1@mid.uni-berlin.de> Marco Bizzarri wrote: > Hi all. > > I would like to change the way test reports are generated, in a Zope > environment. > > I'm playing with TextTestReport, TextTestRunner. Since things are > getting to complicated, I'm afraid I'm following a non-pythonic way. > > Specifically, I would like to have an output like: > > package.subpackage.test_module.TestCase 0.1 > > where 0.1 is the time spent into doing the test. > > In a previous attempt, I made the tests print the number of the test > executed, so that I would have the following output: > > 1 package.subpackage.test_module.TestCase > > however, to do this, I had to put things in the following way: > > > class PAFlowTestRunner(TextTestRunner): > def _makeResult(self): > return PAFlowTextResult(self.stream, self.descriptions, > self.verbosity) > > class PAFlowTextResult(_TextTestResult): > > def startTest(self, test): > self.stream.write("%s " % self.testsRun) > _TextTestResult.startTest(self, test) > > > now, of course, this is ugly, because I'm using _TextTestResult, which > I'm not supposed to know, and I'm changing behaviour by subclassing, > which is not exactly what I would like to do. > > What is the pythonic way to accomplish this? Have you looked at nosetests? Nose is a test-discovery & running-framework based upon unittest-module (but you can also "only" test simple functions, very handy) And it has a very powerful plugin-mechanism, that allows you to implement cleanly what you want. For each test, you get a start/end-method called in your plugin that you can use to gather the information you need, e.g. start/stop-times. For example, I've created an enhanced reporting plugin that lists all tests run (not only those failed or error'ed), and adding time-measuring per-test is on my list of todos. Diez From Ron.Barak at lsi.com Tue Sep 9 03:04:44 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 9 Sep 2008 08:04:44 +0100 Subject: "AttributeError: 'module' object has no attribute 'getdefaultlocale'" on Python start In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF601ADBE4D@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF601ADBE4D@enbmail01.lsi.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF601ADBEE2@enbmail01.lsi.com> Hi Fellow Pythonians, I stated getting the following when starting Python (2.5.2 on Windows XP): C:\Documents and Settings\RBARAK>python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # D:\Python25\lib\site.pyc matches D:\Python25\lib\site.py import site # precompiled from D:\Python25\lib\site.pyc # D:\Python25\lib\os.pyc matches D:\Python25\lib\os.py import os # precompiled from D:\Python25\lib\os.pyc import errno # builtin import nt # builtin # D:\Python25\lib\ntpath.pyc matches D:\Python25\lib\ntpath.py import ntpath # precompiled from D:\Python25\lib\ntpath.pyc # D:\Python25\lib\stat.pyc matches D:\Python25\lib\stat.py import stat # precompiled from D:\Python25\lib\stat.pyc # D:\Python25\lib\UserDict.pyc matches D:\Python25\lib\UserDict.py import UserDict # precompiled from D:\Python25\lib\UserDict.pyc # D:\Python25\lib\copy_reg.pyc matches D:\Python25\lib\copy_reg.py import copy_reg # precompiled from D:\Python25\lib\copy_reg.pyc # D:\Python25\lib\types.pyc matches D:\Python25\lib\types.py import types # precompiled from D:\Python25\lib\types.pyc import _types # builtin import locale # directory D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale import locale # precompiled from D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale\__init__.pyc # D:\Python25\lib\codecs.pyc matches D:\Python25\lib\codecs.py import codecs # precompiled from D:\Python25\lib\codecs.pyc import _codecs # builtin import encodings # directory D:\Python25\lib\encodings # D:\Python25\lib\encodings\__init__.pyc matches D:\Python25\lib\encodings\__init__.py import encodings # precompiled from D:\Python25\lib\encodings\__init__.pyc # D:\Python25\lib\encodings\aliases.pyc matches D:\Python25\lib\encodings\aliases.py import encodings.aliases # precompiled from D:\Python25\lib\encodings\aliases.pyc 'import site' failed; traceback: Traceback (most recent call last): File "d:\Python25\lib\site.py", line 415, in main() File "d:\Python25\lib\site.py", line 406, in main aliasmbcs() File "d:\Python25\lib\site.py", line 357, in aliasmbcs enc = locale.getdefaultlocale()[1] AttributeError: 'module' object has no attribute 'getdefaultlocale' # D:\Python25\lib\warnings.pyc matches D:\Python25\lib\warnings.py import warnings # precompiled from D:\Python25\lib\warnings.pyc # D:\Python25\lib\linecache.pyc matches D:\Python25\lib\linecache.py import linecache # precompiled from D:\Python25\lib\linecache.pyc Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Has anyone else gotten this error ? Could anyone suggest a solution ? Thanks, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Sep 22 18:51:56 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 15:51:56 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> Message-ID: <7bbd8631-0ec8-41b1-9787-800a9aea5ec8@c65g2000hsa.googlegroups.com> On Sep 22, 5:44?pm, Terry Reedy wrote: > CapnBearbo... at googlemail.com wrote: > > forgive me , but the RTFM and Google search approaches are not > > yielding an answer on this question. ?I need to know if there's a top > > level python interpreter command that clears all user variables (not > > built-ins) from the global namespace. ?In other words a statement, or > > some_command_or_function(), that does this: > > >>>> x=3 > >>>> y=4 > >>>> z=[] > >>>> dir() > > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > > >>>> some_command_or_function() > > >>>> dir() > > ['__builtins__', '__doc__', '__name__'] > > First, a WARNING to other readers deceived by the subject line. > Globals().clear() clears everything and leaves nothing, so Capn... is > looking for something that works that is a shortcut for deleting > bindings one-by-one. > > To your question. ?The short answer is no. > > In batch mode, only create what you need and delete (unbind) large > objects that are not automatically deleted (unbound) when you are done > with them. ?Remember that only reference-counted implementations will > guarantee immediate destruction and space-freeing when the last > reference goes away. Check the gc module (and some posts in the > archives) for more specialized control. > > In interactive mode, restart the interpreter if you really need a clean > slate and have too many bindings that you must delete to do something > quick like 'del x,y,z' as in your example above. ?In IDLE, cntl-F6 > restarts the shell with a clean slate. ?I presume IPython has something > similar. > > tjr I guess you have a few hackish options. 1) Define a wrapper that calls its argument immediately, and use it as you would use anonymous blocks. @call_imm def block( ): code code code @call_imm def block( ): code code code You have no globals when you are done. 2) If you need them to be global, use some introspection, and delete the variables upon exiting the scope. 3) Declare all your variables in a namespace, and just delete the namespace. a= type('blank',(),{})() a.varA= 0 a.varB= 'abc' del a From bj_666 at gmx.net Wed Sep 10 07:06:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2008 11:06:23 GMT Subject: which of these 2 quicksorts is faster? References: Message-ID: <6ipo1fFru0uoU1@mid.uni-berlin.de> On Wed, 10 Sep 2008 03:17:30 -0700, process wrote: > qsort can handle bigger lists it seems, making less recursive calls > before finishing(quicksort blows the stack when sorting > range(100,-1000,-1). It just seems so because that `range()` list is the worst case for `quicksort()` but not for `qsort()`. If you feed `qsort()` a list constructed to always leave one recursive call with the empty list, it will reach the recursion limit too. Ciao, Marc 'BlackJack' Rintsch From code at pizzashack.org Tue Sep 2 19:54:12 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 19:54:12 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i5ujqFol29aU8@mid.uni-berlin.de> References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> Message-ID: <20080902235412.GT29228@dragontoe.org> On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: > On Tue, 02 Sep 2008 18:15:07 -0400, Derek Martin wrote: > > >> Classes represent "things", and class names should be nouns. > > > > Is that a law? > > It's a common guideline. Right. It's a guideline. > > Classes are instantiated by invoking their class names as a function > > call -- the computing equivalent of a verb. Why then, must they be > > named as nouns? Can you not, in fact, have classes which describe (or > > model) actions? Wouldn't you name them using verbs if you did? > > Me personally no. I would use `FooAction` instead of `Foo` or something > similar. Maybe you would, but I think a lot of folks would just use the action name (i.e. the verb). > And if they model an action there must be some way to activate > the action That's a reasonable assumption, but as I also said, the object might just describe the action -- essentially the equivalent of a struct in C. > but the instances of `Popen` are no actions. There's no way to > "execute" a `Popen` instance. Yes there is... you execute it when you instantiate the object. At the time of instantiation, you "open" the "P" (pipes). For an object which describes an action, I think it's perfectly sensible that instantiation is when the action occurs, though there could be other times (e.g. if the object had an "execute" method) which make as much sense. > > My point is, if you don't think Popen is a good name for the class, > > that's your opinion, but it is only that: an opinion. > > Like your opinion that it *is* a good name. Yes, exactly. > > Yet some of you state your case as if it is incontrovertable fact. > > I've given a good case as to why it IS a good name (one which I > > genuinely support), and disagree as you may, none of the points any of > > you have made invalidate or even weaken my argument. > > Maybe from your POV. Facts: It doesn't use the `popen()` function So? Neither does the C version of popen(), but that function is still called popen()! :-D As I've already said a few times now, it is conceptually based on popen(). The fact that it doesn't use popen() is not interesting; it (or the portion of it that corresponds to what popen() does) is implemented almost exactly the same way as the C popen() function (except in Python, rather than C). That, to me, is much more interesting. pclose() does what Popen.wait() does, essentially. Sure, the class has a few extre bells and whistles that the C implementation doesn't have, but: > it gives something more complex than a simple pipe Gosh, one would hope that it would be universally true that an object-oriented implementation of something that was originally designed using conventional programming techniques would provide more than one piece of the conventional implementation... We might even hope that it would improve upon 40-year-old implementations, wherever possible... > to three file objects, more attributes and methods), the function used on > Windows under the hood is called `CreateProcess()` not `CreatePipe()`. How does Windows implement popen()? [I think they call it _popen() though...] > `Popen` creates a process and represents a proxy object to communicate > with it, so `Process` is a good name for that concept/"thing". I disagree; the point of that process creation is the communication between the two processes. Calling it a process does not reflect this very important aspect of the object. The Popen object is not a process; it is a collection of pipes and methods used to communicate with one. > It's a way more self explaining name, even for people who know the > `popen()` function I, and apparently the maintainers (at least at the time they added this thing) don't agree. In fact I think it's quite the opposite. If I came across such a "process" object without knowing what it was, I would expect that a process object described a running process, i.e. gave information about things like executable path name, cpu and memory utilization, perhaps a list of all open file descriptors (but not just three specific ones), etc; or something similar. This object provides none of that. It does not, in fact, describe a process at all. It is quite distinct and different from the concept of a process, indeed. > because there's a concept called "process" but none called "popen". Anything that exists can be conceptualized and therefore is a concept. The popen concept exists, and is more than just a concept; it has a concrete implementation in C AND Python and numerous other languages. Verbs can be concepts too. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kaerbuhez at gmail.com Fri Sep 5 16:53:21 2008 From: kaerbuhez at gmail.com (kaer) Date: Fri, 5 Sep 2008 13:53:21 -0700 (PDT) Subject: mimms problem on Hardy References: <59447741-be83-49a0-9316-d1a42cc4450f@f63g2000hsf.googlegroups.com> Message-ID: On 5 sep, 22:15, kaer wrote: > Hello, > > I installed (manually) the last version of mimms -which is a python > program- on an Ubuntu (8.04-server) box. > I get that: > > kaer at subfighter:~/mimms-3.2$ mimms > Traceback (most recent call last): > File "/usr/bin/mimms", line 21, in > from libmimms.core import run > File "/usr/lib/python2.5/site-packages/libmimms/core.py", line 31, > in > from . import libmms > File "/usr/lib/python2.5/site-packages/libmimms/libmms.py", line 29, > in > libmms.mmsx_connect.argtypes = [c_void_p, c_void_p, c_char_p, > c_int] > File "/usr/lib/python2.5/ctypes/__init__.py", line 361, in > __getattr__ > func = self.__getitem__(name) > File "/usr/lib/python2.5/ctypes/__init__.py", line 366, in > __getitem__ > func = self._FuncPtr((name_or_ordinal, self)) > AttributeError: /usr/lib/libmms.so.0: undefined symbol > > If it helps: > kaer at subfighter:~/mimms-3.2$ ls -l /usr/lib/libmms.so.0 > lrwxrwxrwx 1 root root 15 2008-08-20 01:41 /usr/lib/libmms.so.0 -> > libmms.so.0.0.2: mmsx_connect > > If have no idea where the problem is. Thanks for your ideas, > suggestions, comments ... I should have posted the some code of core.py: """ This module uses ctypes to interface to libmms. Currently, it just exposes the mmsx interface, since this one is the most flexible. """ from ctypes import * libmms = cdll.LoadLibrary("libmms.so.0") # opening and closing the stream libmms.mmsx_connect.argtypes = [c_void_p, c_void_p, c_char_p, c_int] libmms.mmsx_connect.restype = c_void_p libmms.mmsx_close.argtypes = [c_void_p] libmms.mmsx_close.restype = None And so on ... If I comment the mmsx_connect lines, I have the same problem with the mmsx_close ones ... If somebody has an idea on how debug a ctypes problem, it would be very helpful. From bignose+hates-spam at benfinney.id.au Sat Sep 27 05:21:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 19:21:29 +1000 Subject: python for *nix system admins References: Message-ID: <87wsgyt04m.fsf@benfinney.id.au> Lars Stavholm writes: > The module (or library) somehow added unix command capabilities > to the python language. It seemed like a lesser known, perhaps new, > python library or module. Which particular Unix commands? Perhaps you're thinking of the 'shutil' module , which wraps a few filesystem manipulation commands. -- \ ?Of all classes the rich are the most noticed and the least | `\ studied.? ?John Kenneth Galbraith, _The Age of Uncertainty_, | _o__) 1977 | Ben Finney From bborcic at gmail.com Mon Sep 8 09:54:19 2008 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 08 Sep 2008 15:54:19 +0200 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: David C. Ullrich wrote: > > (ii) If A is a subset of B then we should have > max(A) <= max(B). This requires that max(empty set) > be something that's smaller than everything else. > So we give up on that. > Er, what about instances of variations/elaborations on class Smaller(object) : __cmp__ = lambda *_ : -1 ? Cheers, BB From tgrav at mac.com Thu Sep 18 10:47:30 2008 From: tgrav at mac.com (Tommy Grav) Date: Thu, 18 Sep 2008 10:47:30 -0400 Subject: Cython dynamic library problem Message-ID: I am trying to learn how to use cython, and while I am following the cython-dev mailing list I didn't feel like this question was totally appropriate for its audience so I am trying here first. I am on a max os x 10.5.4 running drtgrav% python ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 17:40:23) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> I have a pure python file that I am wanting to try to speed up some, so I ran the file through cython, compiled it with gcc and tried to call it from a python file > cython integrations.pyx > gcc -arch ppc -shared -c -fPIC -I/usr/include/python2.5 integration.c -o pyx_integration.so > python integration_test.py Traceback (most recent call last): File "integration_test.py", line 1, in from astroPyX import pyx_integration ImportError: dlopen(/Users/drtgrav/Work/myCode/Python/astroPyX/ pyx_integration.so, 2): no suitable image found. Did find: /Users/drtgrav/Work/myCode/Python/astroPyX/pyx_integration.so: can't map where integration_test.py is from astroPyX import pyx_integration pyx_integration.test(0) pyx_integration.test(100) Does anyone know what the ImportError means and how to correct it? Cheers Tommy From kf9150 at gmail.com Thu Sep 11 03:09:48 2008 From: kf9150 at gmail.com (Kelie) Date: Thu, 11 Sep 2008 00:09:48 -0700 (PDT) Subject: Use Python to solve equations? Message-ID: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Hello group, Is there any packages in Python that will help me solve functions similar to this: x = a*(1+bx)**2.5-c where a, b, c is known and the task to solve x? Thank you, Kelie From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 12 12:07:37 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Sep 2008 18:07:37 +0200 Subject: Checking the boolean value of a collection In-Reply-To: References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> Message-ID: <48ca9333$0$851$426a74cc@news.free.fr> Marco Bizzarri a ?crit : (snip) > I'm afraid this have another problem for me... > > > emmebi at janitor:/var/local/zope28/porting/Products/PAFlow$ python2.3 > Python 2.3.5 (#2, Oct 18 2006, 23:04:45) > [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> def any(iterable): pass > ... >>>> any(x for x in [1, 2, 3]) > File "", line 1 > any(x for x in [1, 2, 3]) > ^ > SyntaxError: invalid syntax > >>>> any([x for x in [1, 2, 3]]) >>>> > > I mean, I'm afraid I can't use an expression like that without > building a list... not at least in python2.3 Err... a list being an iterable, you just need any([1, 2, 3]). But this wont be enough to solve your real use case, indeed. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 18 19:42:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 23:42:51 GMT Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <00e2e17d$0$20331$c3e8da3@news.astraweb.com> On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote: > Now the obvious winner is pruebono - even unoptimized, using sets seems > to be *way* faster than even the most optimized corrected version of > your algorithm. I'm not being snarky about losing priority here, but I submitted essentially the same solution two hours earlier than pruebono. Are people not seeing my posts? Have I been kill-filed by everyone except Mensator? I also asked a question about HTTPError and I haven't seen any responses at all. -- Steven From pavlovevidence at gmail.com Sat Sep 13 01:39:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 12 Sep 2008 22:39:39 -0700 (PDT) Subject: lacking follow-through References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> Message-ID: <289bc58f-6c04-4bce-b393-e9fa0a8c4fee@i20g2000prf.googlegroups.com> On Sep 12, 8:16?am, Steve Holden wrote: > castironpi wrote: > > On Sep 7, 5:03 pm, Marc 'BlackJack' Rintsch wrote: > >> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > >>> This is the strangest post I've seen > >>> since I've joined this list (only > >>> recently). What the ? > >> Yeah, castironpi sometimes doesn't make much sense. ?Maybe because it's a > >> bot!? ?:-) > > >> Ciao, > >> ? ? ? ? Marc 'BlackJack' Rintsch > > > No, I'm legit, and I believe my complaint is. ?That's all I can > > guarantee anyway. ?While I'm still not a vet on Usenet, I'm still > > disappointed so far. ?Though I should be flattered for my logic to be > > ever compared to an A.I.'s. > > Your various outpourings appear so rambling and ill-conceived that > silence is often the only polite response. > > If you are flattered to be compared to an AI you must come from the same > race as Mr. Spock in Star Trek. I'm surprised there is anyone who still gives castironpi credit for being fully human. Carl Banks From castironpi at gmail.com Wed Sep 10 15:19:56 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 10 Sep 2008 12:19:56 -0700 (PDT) Subject: Generator functions and user interfaces References: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> <48c8051b$0$23993$426a74cc@news.free.fr> Message-ID: <8d190ac7-f016-4ef1-958f-9e997d2e367d@k7g2000hsd.googlegroups.com> On Sep 10, 10:35?am, Bruno Desthuilliers wrote: > psaff... at googlemail.com a ?crit : > > > I'm trying to implement an interactive graph visualisation tool using > > matplotlib. > > > I want to use a spring layout, where nodes repulse each other and > > edges act as springs to pull connected nodes together. Usually, this > > algorithm runs through a number of iterations of attraction/repulsion > > to allow the nodes to converge to suitable positions. However, rather > > than running all these iterations to lay out the graph and then > > rendering it, I want to animate the graph as it is "springing" into > > place, and then allow the user to drag nodes around and have the graph > > redraw on the fly. > > > My idea for doing this was to use a generator function, where I yield > > the position of the nodes after each iteration and then call draw() on > > the position yielded. Does this seem like a sensible approach? > > I don't have much experience with this kind of algorithms, but AFAICT, > it seems sensible to me, yes. But don't take me on words... > > > The > > problem is that the node positions that are being operated on by the > > generator function may be altered by user input - dragging the nodes - > > and I'm not sure if this will break the way that the new positions are > > yielded. How do I use a generator function that might stop (when the > > nodes stop moving) but then need to restart again (once the user moves > > the nodes)? > > Starting with Python 2.5, there's a way to pass values back to generators:http://docs.python.org/whatsnew/pep-342.html > > Now, not having played much with these new features so far, I'm afraid I > can't help more, nor even be strictly positive about this being what you > need. > > Any generator guru around ? Yield can return values. The syntax you're looking for is: def generator_fun( ): a= [] while 1: b= yield( a ) a.append( b ) g= generator_fun( ) g.next( ) g.send( 3 ) g.send( 4 ) g.send( 5 ) /Output: >>> g.next( ) [] >>> g.send( 3 ) [3] >>> g.send( 4 ) [3, 4] >>> g.send( 5 ) [3, 4, 5] 'g' is inactive in between 'send' calls. From ireborin at delete.this.gmail.com Tue Sep 23 07:44:41 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 23 Sep 2008 13:44:41 +0200 Subject: gplt from scipy missing ? References: Message-ID: <67lhd4hq1gch3r18g919fjvmijen9saevv@4ax.com> On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" wrote: > >I think scipy does not bundle plotting packages anymore - you may use >whatever suits you, from other sources. >Try matplotlib, see the wiki: >http://wiki.python.org/moin/NumericAndScientific/Plotting Hello Gabriel, thank you for answering. Unfortunatelly, I cannot change my plotting package, unless I indend to change a lot of code that I'll be using in the future. I'm not a programmer by trade, just a guy doing some calculations with already written programms. Do you know, by any chance, where one could get gplt separately, or for example, get older versions of scipy ? I'm using python 5.2.2.. If I install scipy for python 2.3. for example (let's assume that one still has gplt in it) will it work ? Best regards Ivan From fredrik at pythonware.com Sat Sep 27 07:43:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Sep 2008 13:43:50 +0200 Subject: How to read a jpg bytearray from a Flash AS3 file In-Reply-To: References: Message-ID: rsgalloway at gmail.com wrote: > I'm trying to save an image from a Flash AS3 to my server as a jpg > file. I found some PHP code to do this, but I want to do this in > Python. I'm not quite sure how to convert the following code to > Python. It's mainly the $GLOBALS["HTTP_RAW_POST_DATA"] part I don't > know how to convert. depends on what framework you're using. if you're using plain CGI, you should be able to read the posted data from sys.stdin: import sys im = sys.stdin.read() f = open(name, 'wb') f.write(jpg) f.close() to make your code a bit more robust, you may want to check the content-length before doing the read, e.g. import os if os.environ.get("REQUEST_METHOD") != "POST": ... report invalid request ... bytes = int(os.environ.get("CONTENT_LENGTH", 0)) if bytes > MAX_REQUEST_SIZE: ... report request too large ... im = sys.stdin.read(bytes) to deal with query parameters etc, see http://docs.python.org/lib/module-cgi.html From jamesd at echeque.com Wed Sep 10 07:48:12 2008 From: jamesd at echeque.com (James A. Donald) Date: Wed, 10 Sep 2008 21:48:12 +1000 Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> On Tue, 9 Sep 2008 14:35:13 -0700 (PDT), icarus wrote: > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > That did it. > > one more question... > > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? I have noticed that when applications are written in Python with the GUI created by PyGTK, it seems that to install the application on each slightly different version of unix is a fairly major task - although the creators of PyGTK proudly say that the code will run anywhere, it definitely will not install anywhere - the code will only run on a slightly different system after a massive and major rewrite of the install for that target system. Horrible installs are a chronic problem GUI programs driven by interpreted languages Installing visual basic programs that worked on one Windows machine to work on a very slightly different windows machine was also a nightmare. I have not attempted to create installable wxPython windows, but generally, "run anywhere" will bite you. Still looking for a good solution to "run anywhere". -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From cbabcock at kolonelpanic.org Mon Sep 1 01:22:59 2008 From: cbabcock at kolonelpanic.org (Chris Babcock) Date: Sun, 31 Aug 2008 22:22:59 -0700 Subject: Mako --> Genshi References: <20080830205904.725f1bef@mail.asciiking.com> <6hv09bFnvm0eU1@mid.uni-berlin.de> Message-ID: <20080831222259.525c03ed@mail.asciiking.com> > > Is there a cheap way to convert Myghty/Mako templates to Kid/Genshi? > > There's some code written for Pylons that I want to incorporate > > into a TurboGears 2 project and Genshi templates are more likely to > > behave themselves with the tools I'm used to. > > Not that I'm aware of. And I think it's impossible to reliably do > that, because mako allows broken XML or "pure" HTML, whereas > KID/Genshi require well-formed XML. Yes, that would put the kabosh on it, thanks. Even more to the point, I want to write more to style than to ${content} so that the template is less like to break in a WYSIWYG editor. While I know how to edit xhtml source well enough to avoid breaking templates, I can't guarantee the same of everyone who might be involved. A translator gadget is less likely to produce the style that I want than the other, which is more mako-like. Chris From asnast at gmail.com Sat Sep 20 19:27:41 2008 From: asnast at gmail.com (Alex Snast) Date: Sat, 20 Sep 2008 16:27:41 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: On Sep 20, 8:13?pm, bearophileH... at lycos.com wrote: > Duncan Booth: > > > > e.g. the python equivalent to the c++ loop > > > for (i = 10; i >= 0; --i) > > > The exact equivalent would be: > > ? ? ? ? for i in range(10, -1, -1): print i > > I'd use xrange there. Anyway, I have always felt that Python syntax > not easy to understand at first sight, expecially when you try to > convert a bit more complex inverted for loops from/to C to/from > Python. It's one of the few cases where (for example) Pascal (loop) > syntax wins a bit over Python syntax :-) > > Bye, > bearophile Another quick question please, is the List data structure just a dynamic array? If so how can you use static size array, linked list, AVL trees etcetera. From ttkk1024 at gmail.com Wed Sep 17 06:17:54 2008 From: ttkk1024 at gmail.com (smalltalk) Date: Wed, 17 Sep 2008 03:17:54 -0700 (PDT) Subject: shelve file space always increase! Message-ID: >>> import shelve >>> sf = shelve.open('e:/abc.db') >>> for i in range(10000): ... sf[str(i)]=i ... >>> sf.close() >>> sf = shelve.open('e:/abc.db') >>> sf.clear() >>> sf {} the abc.db is always 312k though i have use clear(), how can i shrink the space? From invalid at nowhere.invalid.org Tue Sep 16 06:15:48 2008 From: invalid at nowhere.invalid.org (Alex Marandon) Date: Tue, 16 Sep 2008 11:15:48 +0100 Subject: append on lists In-Reply-To: References: Message-ID: <1221560151.9212.0@proxy00.news.clara.net> Armin wrote: > Chris Rebert wrote: >> On Mon, Sep 15, 2008 at 1:24 PM, Armin wrote: >>> >>> Hi, >>> >>> just a dumb question. >>> >>> Let a = [1,2,3,4,5] >>> >>> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? >> >> Because .append() mutates 'a' and appends the item in-place rather >> than creating and returning a new list with the item appended, and >> it's good Python style for mutating methods to have no return value >> (since all functions must have some return value, Python uses None >> when the function doesn't explicitly return anything). > > Yes, but this is very unconvenient. Hi, You might be interested in using the + operator instead of append. You could also define your own list type, based on the UserList included in the standard library. >>> from UserList import UserList >>> class MyList(UserList): ... def my_append(self, value): ... return self + [value] ... >>> l = MyList([1,2,3,4]) >>> l [1, 2, 3, 4] >>> l.my_append(5) [1, 2, 3, 4, 5] >>> l [1, 2, 3, 4] From george.sakkis at gmail.com Sat Sep 27 12:19:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 27 Sep 2008 09:19:57 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: <91e62d70-73fb-4ecc-ae2e-d950a5f7ea6b@k13g2000hse.googlegroups.com> On Sep 27, 11:27 am, George Sakkis wrote: > If you want to eliminate completely specifying attributes with > strings, it's easy to modify the above so that you write instead: > > class A(Proxy): > ... > bmethod = ProxyMethod(lambda self: self.b1) > bmethod2 = ProxyMethod(lambda self: self.b2) It's funny how often you come with a better solution a few moments after htting send! The snippet above can (ab)use the decorator syntax so that it becomes: class A(Proxy): @ProxyMethod def bmethod(self): return self.b1 @ProxyMethod def bmethod2(self): return self.b2 With the observation that ProxyMethod has access both to the callable that returns the delegate and the name of the delegated method, we can remove the need for the metaclass and the Proxy base class altogether: class proxymethod(object): def __init__(self, get_delegate): self._get_delegate = get_delegate def __get__(self, proxy, proxytype): if proxy is not None: return self.__get_target_attr(proxy) else: return self.__unbound_method def __unbound_method(self, proxy, *args, **kwds): method = self.__get_target_attr(proxy) return method(*args, **kwds) def __get_target_attr(self, proxy): get_delegate = self._get_delegate try: return getattr(get_delegate(proxy), get_delegate.__name__) except AttributeError: raise AttributeError('%r object has no attribute %r' % (proxy.__class__.__name__, get_delegate.__name__)) class A(object): def __init__(self, b1, b2): self.b1 = b1 self.b2 = b2 def amethod(self,a): print "A::mymethod",a @proxymethod def bmethod(self): return self.b1 @proxymethod def bmethod2(self): return self.b2 a = A(B(10), B(20)) a.amethod('foo') print "bound proxy calls" a.bmethod('foo') a.bmethod2('bar','baz') print "unbound proxy calls" A.bmethod(a,'foo') A.bmethod2(a,'bar','baz') So back to the OP's original question and after a long circle.. a decorator might well be the right thing to use after all :) George From george.sakkis at gmail.com Tue Sep 23 19:24:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 23 Sep 2008 16:24:34 -0700 (PDT) Subject: Docstrings for class attributes References: Message-ID: <6b22c96d-6958-4d74-86b2-3a9dd20a7455@d77g2000hsb.googlegroups.com> On Sep 23, 3:55 pm, Gerard flanagan wrote: > George Sakkis wrote: > > On Sep 23, 1:23 am, "Tom Harris" wrote: > > >> Greetings, > > >> I want to have a class as a container for a bunch of symbolic names > >> for integers, eg: > > >> class Constants: > >> FOO = 1 > >> BAR = 2 > > >> Except that I would like to attach a docstring text to the constants, > >> so that help(Constants.FOO) will print some arbitrary string. Sort of > >> a very limited implementation of PEP 224. The only solution that I can > >> see is to subclass int.__new__(), since once I have an int all it's > >> attributes are immutable. > > > Here's one approach, using metaclasses and descriptors; it sort of > > works, but it's less than ideal, both in usage and implementation. > > > George > > > #====== usage ============================================ > > > class MyConstants: > > __metaclass__ = ConstantsMeta > > FOO = const(1, 'some docs about foo') > > BAR = const(2) > > > print MyConstants.FOO.__doc__ > > help(MyConstants.FOO) > > print MyConstants.FOO - MyConstants.BAR > > print MyConstants.FOO - 2 > > print 1 - MyConstants.BAR > > > #======= implementation =================================== > > > def ConstantsMeta(name, bases, namespace): > > for name,attr in namespace.iteritems(): > > if isinstance(attr, const): > > namespace[name] = _ConstDescriptor(name, attr.value, > > attr.doc) > > return type(name, bases, namespace) > > > class const(object): > > def __init__(self, value, doc=None): > > self.value = value > > self.doc = doc > > > class _ConstDescriptor(object): > > def __init__(self, name, value, doc): > > cls = type(name, (), dict( > > __doc__ = doc, > > __add__ = lambda self,other: value+other, > > __sub__ = lambda self,other: value-other, > > # ... > > __radd__ = lambda self,other: other+value, > > __rsub__ = lambda self,other: other-value, > > # XXX lots of boilerplate code for all special methods > > follow... > > # XXX Is there a better way ? > > )) > > self._wrapper = cls() > > > def __get__(self, obj, type): > > return self._wrapper > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I think you get an equivalent result if you forget the descriptor > and adapt the metaclass: > > def ConstantsMeta(name, bases, namespace): > for name,attr in namespace.iteritems(): > if isinstance(attr, const): > cls = type(name, (type(attr.value),), {'__doc__': attr.doc}) > namespace[name] = cls(attr.value) > return type(name, bases, namespace) Sweet! The big improvement of course is that you thought of subclassing the type of attr.value instead of delegating manually all special methods. It seems so obvious in retrospect, but I totally missed it for some reason; thanks! George From george at george-net.de Tue Sep 16 11:00:23 2008 From: george at george-net.de (Georg Altmann) Date: Tue, 16 Sep 2008 17:00:23 +0200 Subject: MVC with Python In-Reply-To: <200809161514.39385.maric@aristote.info> References: <3f0d61c40809160547t339226acx19a7a0a0f58a6e73@mail.gmail.com> <200809161514.39385.maric@aristote.info> Message-ID: Maric Michaud schrieb: > Le Tuesday 16 September 2008 14:47:02 Marco Bizzarri, vous avez ?crit : >> On Tue, Sep 16, 2008 at 1:26 PM, Georg Altmann wrote: >>> Marco Bizzarri schrieb: >>>> On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann >>>> wrote: >>> But this implies all the objects in the list have to be instances of >>> QObject. I wonder if this is isn't a weird design, because for example >>> all value type classes in Qt don't derive from QObject, e.g. QString. My >>> list objects are not that simple (in terms of the data structure). So is >>> it ok to make them QObjects? >> Did you take a look at this? >> >> http://www.potu.com/man/doc.trolltech.com/4.0/model-view-programming.html >> >> It seems to imply that you should use QtAbstractItemModel as a base >> class for all your models. But since I'm not an expert about Qt, I >> cannot really say. Yes, I did. But as I explained in my previous message, the whole Qt model-view framework doesn't seem fit any data which can not be handled as QVariant and thus as a value type. > It is not about QT, it is about MVC. In MVC, code which implement the model > should be completely ignorant of the libraries used for gui, and the gui part > of the application shouldn't acces directly to your model logic. This why > there is a third layer which abstract the logic of your datas and provide > standard operation for the gui code. This third layer (Controllers), should > be as few as possible coupled to the specificities of the gui library (but > must be). > > The quoted papers explain rather well how to do this with QT (apart they call > controllers "delegates"). Except they always handle simple data. I don't see how to get around the QVariant limitatation. Also the data should be displayed in a graphical manner (maybe a QGraphicsScene/QGraphicsView or mabye custom QScrollArea). This also doesn't seem to go well with the standard Qt approach. I could imagine to implement the model without using any Qt then use proxy classes derived from QObject as controllers. > For medium to big project, don't be afraid to divide your program in three > packages, one for the model, in which you must not have any reference to QT > API of some sort, one for the controllers, where you provide events and > methods to manipulate your model, one for gui, where you just build windows, > subscribe to controller's events and use their functions as callbacks for > your widgets. As this is a small project for now, I think the controller layer is too much work. As the project gets bigger it should be possible to switch to a full mvc implementation if necessary. For now I will try to work with a model that provides some signals by itself. Regards Georg From google at mrabarnett.plus.com Thu Sep 25 18:40:56 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 25 Sep 2008 15:40:56 -0700 (PDT) Subject: How to get the filename in the right case ? References: <6k1dukF5hk86U1@mid.uni-berlin.de> Message-ID: <2438fe2e-2eab-4b82-80ae-85e4aa1ec02a@26g2000hsk.googlegroups.com> On Sep 25, 8:38?pm, Stef Mientki wrote: > I found a partial workaround that is good enough for me: > > def Get_Windows_Filename ( FileName ) : > ? if os.name == 'nt' : > ? ? File = os.path.splitext ( FileName .lower ())[0] > ? ? return glob.glob ( File + '.p?' ) > ? return FileName > > This will translate the filename into the correct case, but not the path. > > I also looked at os.path.walk, but that's too slow for me, > because getting the path correct means I have to start at the root. > You could try win32api.GetLongPathName(...). However, I've found that some parts of the path are converted to the correct case but other parts aren't: >>> print win32api.GetLongPathName(r"c:\documents and settings\administrator\desktop\foobar.py") c:\documents and settings\administrator\Desktop\FooBar.py How does your solution compare to using os.listdir(...) instead of glob? From tsrinuvasulu491 at gmail.com Tue Sep 30 21:58:39 2008 From: tsrinuvasulu491 at gmail.com (chinu) Date: Tue, 30 Sep 2008 18:58:39 -0700 (PDT) Subject: EARN $$$ IN EVERY MONTH Message-ID: hai, i am srinu from india. i am sending a blog url for yours use. click on the blog and get more information to choose yours job. the blog url is: http://earnmonthlyincome.blogspot.com/ goodluck From zhushenli at gmail.com Wed Sep 3 00:20:38 2008 From: zhushenli at gmail.com (Davy) Date: Tue, 2 Sep 2008 21:20:38 -0700 (PDT) Subject: Pass same parameter in Recursive function References: Message-ID: On Sep 3, 11:57?am, "Chris Rebert" wrote: > Assuming the function is tail-recursive or the "unchanging" arguments > are immutable, just use a closure: [SNIP] Hi Chris, Thank you :) Perhaps I should clarify the problem. 1. the function is NOT tail-recursive 2. Yes, the arguments are immutable after I call the function the first time. I think the best description of the problem may be: How to keep some argument constant and accessable in one function (especially, recursive function). We know that we can use something like self.parameter to keep the parameter constant and accessable in one class. > > def func(self, x, y, A, B, C): > ? ? def _func(x,y): > ? ? ? ? return _func(g(A,B,C,x), h(A,B,C,y)) #recurse > ? ? return _func(x, y) > > I'm unsure as to the performance impact of this though. > > - Chris > > > > > > On Tue, Sep 2, 2008 at 8:20 PM, Davy wrote: > > Hi all, > > > Sometimes I need to pass same parameter in recursive function. From my > > point of view, the style is redundant, and I don't what to use some > > global style like self.A, self.B, Is there any other choice? > > > For example, > > > def func(self, x, y, A, B, C): > > ?#x, y change in recursive call > > ?#A, B, C change in the first layer function call, but did not change > > in recursive call > > ?if (...): > > ? ?func(x, y, A, B, C) > > ?else(...): > > ? ?func(x, y, A, B, C) > > > Best regards, > > Davy > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com- Hide quoted text - > > - Show quoted text - From ivan.illarionov at gmail.com Thu Sep 4 17:05:41 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 4 Sep 2008 14:05:41 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> <48c03b91$0$14747$426a74cc@news.free.fr> Message-ID: On 4 ????, 21:49, Bruno Desthuilliers wrote: > Ivan Illarionov a ?crit : > > > > > On 4 ????, 22:59, Carl Banks wrote: > >> You can write code to guard against this if you want: > > >> class A: > >> legal = set(["x"]) > >> def __setattr__(self,attr,val): > >> if attr not in self.legal: > >> raise AttributeError("A object has no attribute '%s'" % > >> attr) > >> self.__dict__[attr] = val > >> def __init__(self,x): > >> self.y = x > > >> I suspect most people who go into Python doing something like this > >> soon abandon it when they see how rarely it actually catches anything. > > > '__slots__' is better: > > For which definition of "better" ? __slots__ are a mean to optimize > memory usage, not to restrict dynamism. Being able to dynamically add > arbitrary attributes is actually a feature, not a bug, and uselessly > restricting users from doing so is not pythonic. IOW : don't do that. Carl's example is restricting dynamism in the same way as __slots__. I've just suggested a better implementation. It is not me who suggested dynamism restriction as a way to guard against errors. From gagsl-py2 at yahoo.com.ar Mon Sep 29 22:42:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 23:42:20 -0300 Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> Message-ID: En Thu, 25 Sep 2008 08:02:49 -0300, Mark Dickinson escribi?: > On Sep 23, 1:58?pm, Robert Lehmann wrote: >> I don't see why transitivity should apply to Python objects in general. > > Hmmm. Lack of transitivity does produce some, um, interesting > results when playing with sets and dicts. Here are sets s and > t such that the unions s | t and t | s have different sizes: > >>>> from decimal import Decimal >>>> s = set([Decimal(2), 2.0]) >>>> t = set([2]) >>>> len(s | t) > 2 >>>> len(t | s) > 1 Ouch! > This opens up some wonderful possibilities for hard-to-find bugs... And I was thinking all this thread was just a theoretical question without practical consequences... -- Gabriel Genellina From gherron at islandtraining.com Thu Sep 18 03:11:41 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 18 Sep 2008 00:11:41 -0700 Subject: member functions in a class In-Reply-To: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> References: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> Message-ID: <48D1FF2D.20607@islandtraining.com> Karl Kobata wrote: > > I am new to python and am wondering. When I create a class, with ?def? > functions and if this class is instantiated say 50 times. Does this > mean that all the ?def? functions code within the class is duplicated > for each instance? > > Can someone give me a short and simple answer as to what happens in > python? > > Thanks > No code is duplicated. 50 "objects" are created. Each object has its own copy of the data attributes, and a reference to the (one and only) class object where the method attributes are located. That's a short answer. Perhaps too short? Gary Herron > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From karl.kobata at syncira.com Thu Sep 25 21:03:31 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Thu, 25 Sep 2008 18:03:31 -0700 Subject: deleting an object Message-ID: <6u80qt$80h3s3@rrcs-agw-02.hrndva.rr.com> Please help. Questions based on snippet of code below. 1) when myTestCase is deleted, is just the pointer deleted or the entire instance with all of its data and data structure deleted? 2) What is the practice for deleted the object and recovering the memory it occupies? 3) If delete is the way, what happens to 'testUtils.utilFunction1()' if it were instantiated in other classes that have not been deleted yet? Thanks for your help. Example: import testUtils class testClass: def __init__(self): self.testList = list() self.testDict1 = dict() self.utils1 = testUtils.utilFunction1() ... ...in the main code body. myTestCase = testClass() .... delete myTestCase ... -------------- next part -------------- An HTML attachment was scrubbed... URL: From dullrich at sprynet.com Thu Sep 4 12:17:37 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 04 Sep 2008 11:17:37 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: In article <24061e7d-935a-442f-8d50-b8619d5581d3 at 34g2000hsh.googlegroups.com>, bearophileHUGS at lycos.com wrote: > Empty Python lists [] don't know the type of the items it will > contain, so this sounds strange: > > >>> sum([]) > 0 > > Because that [] may be an empty sequence of someobject: > > >>> sum(s for s in ["a", "b"] if len(s) > 2) > 0 > > In a statically typed language in that situation you may answer the > initializer value of the type of the items of the list, as I do in the > sum() in D. > > This sounds like a more correct/clean thing to do: > > >>> max([]) > Traceback (most recent call last): > File "", line 1, in > ValueError: max() arg is an empty sequence > > So it may be better to make the sum([]) too raise a ValueError, I don't see why you feel the two should act the same. At least in mathematics, the sum of the elements of the empty set _is_ 0, while the maximum element of the empty set is undefined. And both for good reason: (i) If A and B are disjoint sets we certainly want to have sum(A union B) = sum(A) + sum(B). This requires sum(empty set) = 0. (ii) If A is a subset of B then we should have max(A) <= max(B). This requires that max(empty set) be something that's smaller than everything else. So we give up on that. > in > Python 3/3.1 (if this isn't already true). On the other hand often > enough I have code like this: > > >>> max(fun(x) for x in iterable if predicate(x)) > > This may raise the ValueError both if iterable is empty of if the > predicate on its items is always false, so instead of catching > exceptions, that I try to avoid, I usually end with a normal loop, > that's readable and fast: > > max_value = smallvalue > for x in iterable: > if predicate(x): > max_value = max(max_value, fun(x)) > > Where running speed matters, I may even replace that max(max_value, > fun(x)) with a more normal if/else. > > A possible alternative is to add a default to max(), like the next() > built-in of Python 2.6: > > >>> max((fun(x) for x in iterable if predicate(x)), default=smallvalue) > > This returns smallvalue if there are no items to compute the max of. > > Bye, > bearophile -- David C. Ullrich From robin at alldunn.com Sun Sep 28 15:01:38 2008 From: robin at alldunn.com (Robin Dunn) Date: Sun, 28 Sep 2008 12:01:38 -0700 Subject: ANN: wxPython 2.8.9.0 Message-ID: <48DFD492.1090905@alldunn.com> Announcing ---------- The 2.8.9.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release adds support for using Cairo for drawing on wx windows, adds a Win64 build, and various other fixes and enhancements. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit and 64-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. In most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.9.0 ------------------ Many minor bug fixes throughout wxWidgets and wxPython. Fixed wx.lib.embeddedimage to work with Python 2.3. Fixed PseudoDC hit testing when pure white or pure black are used. Added support for a 64-bit Windows build for the AMD64 architecture, (a.k.a. x64.) This is for Python 2.5 only and is available only as a Unicode build. Added the wx.EmptyBitmapRGBA factory function. Added the wx.lib.wxcairo module which allows the pycairo package to be used for drawing on wx window or memory DCs. In addition it is able to convert from a native wx.Font to a cairo.FontFace, and it also provides functions for converting to/from wx.Bitmap and cairo.ImageSurface objects. In order to use this module you will need to have the Cairo library and its dependencies installed, as well as the pycairo Python package. For Linux and other unix-like systems you most likely have what you need installed already, or can easily do so from your package manager application. See the wx.lib.wxcairo module's docstring for notes on where to get what you need for Windows or Mac. This module uses ctypes, and depending on platform it may need to find and load additional dynamic libraries at runtime in addition to cairo. The pycairo package used needs to be new enough to export the CAPI structure in the package namespace. I believe that started sometime in the 1.4.x release series. Added the wx.lib.graphics module, which is an implementation of the wx.GraphicsContext API using Cairo (via wx.lib.wxcairo). This allows us to be totally consistent across platforms, and also use Cairo to implement some things that are missing from the GraphicsContext API. It's not 100% compatible with the GraphicsContext API, but probably close enough to be able to share code between them if desired, plus it can do a few things more. Updated wx.Bitmap.CopyFromBuffer to be a bit more flexible. You can now specify the format of the buffer, and the CopyFromBufferRGBA is now just a wrapper around CopyFromBuffer that specifies a different format than the default. Also added the complement method, CopyToBuffer. See the docstring for CopyFromBuffer for details on the currently allowed buffer formats. The existing wx.BitmapFromBuffer factory functions are also now implemented using the same underlying code as CopyFromBuffer. Add wx.lib.mixins.listctrl.ListRowHighlighter for automatic highlighting of rows in a wx.ListCtrl. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From semanticist at gmail.com Sat Sep 27 20:22:50 2008 From: semanticist at gmail.com (Miles) Date: Sat, 27 Sep 2008 20:22:50 -0400 Subject: Borg vs Singleton vs OddClass In-Reply-To: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> Message-ID: Lie wrote: > This is probably unrelated to Python, as this is more about design > pattern. I'm asking your comments about this design pattern that is > similar in functionality to Singleton and Borg: to share states. > > I'm thinking about this design pattern (I don't know if anyone has > ever thought of this pattern before): > > class OddClass(object): > def __init__(self): > global OddClass > OddClass = self > def __call__(): I'll change this to def __call__(self): > return self > > The OddClass is a class that would overwrite its own class definition > at its first instantiation. OddClass defines __call__ so that > subsequent "instantiation" (technically it is no more an > instantiation, but Duck Typing says it does) of the class would return > the single instance. This seems like a terrible idea to me, but then I never really understood the appeal of the Singleton pattern, especially in Python. > Singleton and OddClass is inheritable. > >>>> class OddClass(object): ... >>>> s = OddClass() >>>> class A(OddClass): pass Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases __init__() takes exactly 1 argument (4 given) Oops! And assuming you carefully ordered your code so that OddClass will never be instantiated before it is subclassed (which seems fragile), you get behavior like this: >>> s = OddClass() >>> s is OddClass() True >>> a = A() >>> s is OddClass() False >>> a is OddClass() True >>> a is A() False >>> a is OddClass() False -Miles From bignose+hates-spam at benfinney.id.au Thu Sep 18 18:33:04 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 Sep 2008 08:33:04 +1000 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Message-ID: <87skrx2ifz.fsf@benfinney.id.au> erikcw writes: > I have a cgi script where users are uploading large files for > processing. I want to launch a subprocess to process the file so the > user doesn't have to wait for the page to load. For "how do I deal with subprocesses from Python", the (new in Python 2.4) 'subprocess' module is the default go-to answer , replacing a rather fragmented set of modules before it. > What is the correct way to launch subprocess without waiting for the > result to return? Creating an instance of 'subprocess.Popen' will launch the process and return the Popen instance. You then have the option of polling it or waiting for it to complete. -- \ ?To stay young requires unceasing cultivation of the ability to | `\ unlearn old falsehoods.? ?Robert Anson Heinlein | _o__) | Ben Finney From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 08:12:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 14:12:02 +0200 Subject: how to find position of dictionary values In-Reply-To: <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> References: <48bbab73$0$27858$426a34cc@news.free.fr> <6i1rgcFo0f1gU1@mid.uni-berlin.de> <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> Message-ID: <48bbdbbe$0$3794$426a74cc@news.free.fr> lee a ?crit : > On Sep 1, 2:37 pm, "Diez B. Roggisch" wrote: >> lee wrote: (snip) >>> i agree with u, my data strusture is not efficient. but all the >>> records,viz...name,phno, email,address are all generated at runtime , >>> when the user enters them. so how can i design my datastructure in >>> that case? >> Are "u" short on keystrokes? You are not textmessaging here... > i am soory for that keystrokes Is your cap key broken ?-) (snip) >. can anyone tell me how can i change > the value of key. > suppose i have a dictionary > > kev = {'kabir': ['kabir at kabir.com', '1234', 'missuri'], 'shri': > ['shri at shri.com', '23423', 'india'], 'marsa': ['marsa at marsa.com', > '2345', 'brazil'], 'sandeep': ['sandeep at sandeep.com', '007', > 'canada']} > > > how can i change the key to something like 'sabir' and how can i > change the values of kabir? I don't mean to be harsh, but did you read the FineManual(tm) ? All this is very basic (no pun) stuff, mostly documented, and easy to try out using the interactive interpreter. This ng is very newbie-friendly, but this doesn't mean you can hope to get by without doing the minimal effort of going thru the tutorial and trying a couple things by yourself before asking. Hope you'll understand the above remark intends to be an helpful advice... From clp at rebertia.com Tue Sep 30 18:00:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 30 Sep 2008 15:00:06 -0700 Subject: Backup a directory In-Reply-To: References: Message-ID: <47c890dc0809301500r2845c73cp607d92f1903add87@mail.gmail.com> On Tue, Sep 30, 2008 at 1:21 PM, wrote: > Hello, > > > I'm looking for a script that creates a backup of a directory but keeps only > one backup. > I've tried using all the os modules commands but could not create one. > > > Does any one has any such custom script or function? You could probably whip one up very easily using the tarfile module [http://docs.python.org/lib/module-tarfile.html] and shutil.move() [http://docs.python.org/lib/module-shutil.html]. Just make a new TarFile of the directory, save it, then replace any previous backup file using shutil.move() Good luck, and have fun! Regards, Chris P.S. And if you're on *nix, you might consider just using a shell script and the 'tar' command. Right tool for the right job and all that. -- Follow the path of the Iguana... http://rebertia.com > > > Thanks and regards, > rajat > > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Fri Sep 5 17:22:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 14:22:27 -0700 (PDT) Subject: Determining Processor Vender References: <554ecfcf-96d8-4602-8d5e-ee5d70590124@i76g2000hsf.googlegroups.com> <3c4cb88a-2e47-4a5e-9a82-4b72f00b1561@y21g2000hsf.googlegroups.com> Message-ID: <8c07c276-96e5-4130-93b3-f9bf5e9f123d@n33g2000pri.googlegroups.com> On Sep 6, 5:07?am, aha wrote: > On Sep 5, 3:00?pm, aha wrote: > > > Dose anyone know of a cross-platform method for determining the vendor > > of a processor? ?Under linux I can check /proc/cpuinfo. ?What I'd like > > to be able to do is determine if a processor is AMD or Intel, so that > > I can use the appropriate numerical libraries for my application. > > > Regards, > > > Aquil > > Additionally, I've tried the platform module...platform.processor() on > my 64-bit AMD system, under Linux, returns x86_64. ?And under windows > retruns an empty string '' This may help with Windows. My setup: (XP SP 2), Python 2.5.2. The chip is an AMD Turion Mobile which is 64-bit but is running 32-bit Windows. >>> import os >>> from pprint import pprint as pp >>> pp(dict((k, v) for (k, v) in os.environ.items() if 'PROCESSOR' in k)) {'NUMBER_OF_PROCESSORS': '1', 'PROCESSOR_ARCHITECTURE': 'x86', 'PROCESSOR_IDENTIFIER': 'x86 Family 15 Model 36 Stepping 2, AuthenticAMD', 'PROCESSOR_LEVEL': '15', 'PROCESSOR_REVISION': '2402'} >>> Cheers, John From sjmachin at lexicon.net Sat Sep 20 07:25:50 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 20 Sep 2008 04:25:50 -0700 (PDT) Subject: how can i check whether a variable is iterable in my code? References: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> Message-ID: <2dfbad14-b898-4284-9912-337af09c4d90@s9g2000prg.googlegroups.com> On Sep 20, 8:54?pm, satoru wrote: > On Sep 20, 6:35?pm, Aidan wrote: > > > satoru wrote: > > > hi, all > > > i want to check if a variable is iterable like a list, how can i > > > implement this? > > > this would be one way, though I'm sure others exist: > > > if hasattr(yourVar, '__iter__'): > > ? ? ? ? # do stuff > > thank you,but this will miss out sequences like string just because it > doesn't have an attribute named '__iter__' str objects have a __getitem__ attribute, as do other built-in sequence types: unicode, xrange, buffer. AFAIK if an object has no __iter__ but has a __getitem__, iter(obj) will create an iterator that calls obj.__getitem__(0), obj.__getitem__(1), etc until IndexError is raised. From dullrich at sprynet.com Fri Sep 5 11:16:38 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 05 Sep 2008 10:16:38 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: In article , Ken Starks wrote: > David C. Ullrich wrote: > > > > > I don't see why you feel the two should act the same. > > At least in mathematics, the sum of the elements of > > the empty set _is_ 0, while the maximum element of the > > empty set is undefined. > > > > And both for good reason: > > > > (i) If A and B are disjoint sets we certainly want to > > have sum(A union B) = sum(A) + sum(B). This requires > > sum(empty set) = 0. > > > > (ii) If A is a subset of B then we should have > > max(A) <= max(B). This requires that max(empty set) > > be something that's smaller than everything else. > > So we give up on that. > > Do we give up? Really ? Erm, thanks. I was aware of all that below. If we're being technical what's below is talking about the sup and inf, which are not the same as max and min. More relevant to the present context, I didn't mention what's below because it doesn't seem likely that saying max([]) = -infinity and min([]) = +infinity is going to make the OP happy... > From wikipedia: http://en.wikipedia.org/wiki/Empty_set > (Uses wikipedia's LaTeX notation -- I hope those interested > are OK with that ) > > > Mathematics > > [edit] Extended real numbers > > Since the empty set has no members, when it is considered as a subset of > any ordered set, then any member of that set will be an upper bound and > lower bound for the empty set. For example, when considered as a subset > of the real numbers, with its usual ordering, represented by the real > number line, every real number is both an upper and lower bound for the > empty set.[3] When considered as a subset of the extended reals formed > by adding two "numbers" or "points" to the real numbers, namely negative > infinity, denoted -\infty\!\,, which is defined to be less than every > other extended real number, and positive infinity, denoted +\infty\!\,, > which is defined to be greater than every other extended real number, then: > > \sup\varnothing=\min(\{-\infty, +\infty \} \cup \mathbb{R})=-\infty, > > and > > \inf\varnothing=\max(\{-\infty, +\infty \} \cup \mathbb{R})=+\infty. > > That is, the least upper bound (sup or supremum) of the empty set is > negative infinity, while the greatest lower bound (inf or infimum) is > positive infinity. By analogy with the above, in the domain of the > extended reals, negative infinity is the identity element for the > maximum and supremum operators, while positive infinity is the identity > element for minimum and infimum. -- David C. Ullrich From yuma400000 at yahoo.com Sun Sep 21 13:48:00 2008 From: yuma400000 at yahoo.com (yuma) Date: Sun, 21 Sep 2008 10:48:00 -0700 (PDT) Subject: Milenko Kindl rtegdgd Message-ID: Milenko Kindl Banja Luka Banjaluka Bihac From scotballard at gmail.com Thu Sep 18 20:53:22 2008 From: scotballard at gmail.com (scottbvfx) Date: Thu, 18 Sep 2008 17:53:22 -0700 (PDT) Subject: webbrowser fragment identifier Message-ID: <0b00afc4-018f-4b80-9fba-93c253a86c7a@q5g2000prf.googlegroups.com> Hi, I'm trying to launch a web browser along with an html file with a fragment identifier in its path. I'm using the webbrowser module for this. ie. webbrowser.open('file:///C:/myfile.html#SomeEntryInTheHTML') for some reason it is truncating the path to 'file:///C:/myfile.html'. Does anyone know a way of getting the fragment identifier in there (with webbrowser module or any other)? Thanks, -Scott From nightzombie at netzero.net Fri Sep 5 10:38:37 2008 From: nightzombie at netzero.net (NightZombie) Date: Fri, 5 Sep 2008 07:38:37 -0700 (PDT) Subject: Make Games Message-ID: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> x-no-archive: yes I want to learn Python so I can make simple games. What are some good books that'll help me do this? From woaibeiyang at hotmail.com Tue Sep 2 08:47:46 2008 From: woaibeiyang at hotmail.com (woaibeiyang) Date: Tue, 2 Sep 2008 20:47:46 +0800 Subject: about downloading the selected information Message-ID: I have a problem to download the information from url http://www.ncbi.nlm.nih.gov/sites/entrez. Because it is impossible for me to add searching material to the url to construct a new url and then visit the website. I have the searching material, however I could not find the way to deal with this problem. I want to know how can I do this problem with python and which part of knowledge should I view first? Thanks! From clp at rebertia.com Sun Sep 28 15:23:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 28 Sep 2008 12:23:22 -0700 Subject: Selective importing and package dependencies In-Reply-To: References: Message-ID: <47c890dc0809281223g4a87160kaa6f01b5450b587e@mail.gmail.com> On Sun, Sep 28, 2008 at 7:10 AM, David Pratt wrote: > Hi. I am in the midst of preparing a package to convert between various > schemas including orms. The issue is I don't want django, slqalchemy, storm, > rdflib etc. as hard dependencies of the package. Each module is a schema to > schema conversion. As an example, I have imports for sqlalchemy with classes > and methods that use them. > > from sqlalchemy.util import OrderedDict > from sqlalchemy import types as rdbtype > import sqlalchemy as sa > > I have my own ideas about how I might do this but looking for > recommendations from others how they would handle this so the result would > be: > > 1. no hard dependencies on any of these other packages > 2. load the module without failure. > 3. import the dependent package if available to perform the conversion Why not just catch the ImportError-s and set some variables depending on whether you were able to import the modules, e.g.: # repeat for each soft-depended module try: import django_module except ImportError: imported_django = False else: imported_django = True #later in the file if imported_django and imported_sqlalchemy: class DjangoToSqlAlchemy(object): #code that uses the django and sqlalchemy modules here Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > > Many thanks > David > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Mon Sep 29 19:24:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Sep 2008 23:24:01 GMT Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48e11dd4$0$20720$426a74cc@news.free.fr> Message-ID: <00f15d41$0$20617$c3e8da3@news.astraweb.com> On Mon, 29 Sep 2008 18:27:22 +0200, Bruno Desthuilliers wrote: > Lawrence D'Oliveiro a ?crit : >> In message , Ross Ridge wrote: >> >>> You need either use trial and error to find out, or look at the >>> source. >> >> So what's wrong with using the source as documentation? :) > > Don't know... Ok, having higher-level documentation (the big picture, > and quick description of what and how for classes and functions) really > helps. But when it comes to nitty-gritty details, source code is the > best documentation ever, since it's always accurate and up to date. > > FWIW, I'm often surprised by people asking questions about some > implementation detail of some open-source library or framework that are > very easily answered just looking at the source code. Reading the source > is 1/ the best way to really know how something is implemented and 2/ > usually very instructive. Reading the source code is good, but it's not a panacea. There are at least four things wrong with the advice to read the source code: (1) It's not always available. (2) Even when the source is available, it is sometimes a legal trap to read it with respect to patents and copyright. E.g. some Microsoft so- called "open" licences (but not all) allow you to read the source, but if you do then everything you program in a related field from that point is legally contaminated and could be considered a derivative work of Microsoft's software. (3) Source code not always understandable without significant effort. Code can be obfuscated, either to hide the algorithm, as an optimization, or simply because the coder is cleverer than you are. It might be in a language you don't understand (e.g. Python built-ins are written in C, not Python. I have to learn C to find out what exceptions sorted() can raise?). That's why accurate documentation should be preferred in the first place: it is easier to read and understand. It might take you hours of hard study to learn that function spam(x) raises ValueError if the argument is invalid, or two seconds to read it in the docs. Yes, documentation can fall behind the source code, but once the code is stable and the documentation has caught up and is accurate, there's no reason to re-invent the wheel by slugging through the source just to find out something already documented. (4) Even when the source code is available, legally unencumbered, in a language you understand and not too complicated for you to grasp, there's the combinatorial explosion: you may need to read and understand an arbitrarily large and complex chain of software merely to know what a single function can do. E.g. you want to know what exceptions function spam() can raise: def spam(x): a = 1 b = 2 c = ham(x) return fried_eggs(a, b, c) Now you need to understand ham() and fried_eggs(), but they aren't documented either. So you turn to their source code, and each of them call two functions, each of which call another two functions, each of which call *another* two functions... How much source code are you expected to read just to understand the four- line function spam()? -- Steven From castironpi at gmail.com Mon Sep 8 15:08:08 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 8 Sep 2008 12:08:08 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <5ee352aa-9ee5-4a8b-8b01-b9e6d1cc808e@m73g2000hsh.googlegroups.com> On Sep 8, 8:54?am, Boris Borcic wrote: > David C. Ullrich wrote: > > > (ii) If A is a subset of B then we should have > > max(A) <= max(B). This requires that max(empty set) > > be something that's smaller than everything else. > > So we give up on that. > > Er, what about instances of variations/elaborations on > > class Smaller(object) : __cmp__ = lambda *_ : -1 > > ? > > Cheers, BB You still don't have the property max(X) is in X. And it's the equivalent of a special builtin constant for max on the empty set. From steve at REMOVE-THIS-cybersource.com.au Wed Sep 3 21:30:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 01:30:14 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: <00cf3495$0$20302$c3e8da3@news.astraweb.com> On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: >>>> sum([]) > 0 > > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It > should return None or throw an exception like sum([None,1]) does. You're wrong, because 99.9% of the time when users leave a blank cell in Excel, they want it to be treated as zero. Spreadsheet sum() is not the same as mathematician's sum, which doesn't have a concept of "blank cells". (But if it did, it would treat them as zero, since that's the only useful thing and mathematicians are just as much pragmatists as spreadsheet users.) The Excel code does the right thing, and your "pure" solution would do the unwanted and unexpected thing and is therefore buggy. Bugs are defined by "does the code do what the user wants it to do?", not "is it mathematically pure?". The current behaviour of sum([]) does the right thing for the 99% of the time when users expect an integer. And the rest of the time, they have to specify a starting value for the sum anyway, and so sum([], initial_value) does the right thing *always*. The only time it does the wrong thing[1] is when you forget to pass an initial value but expect a non-numeric result. And that's the programmer's error, not a function bug. [1] I believe it also does the wrong thing by refusing to sum strings, but that's another story. -- Steven From bj_666 at gmx.net Thu Sep 25 13:34:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Sep 2008 17:34:12 GMT Subject: text processing References: Message-ID: <6k20ckF5glpmU1@mid.uni-berlin.de> On Thu, 25 Sep 2008 15:51:28 +0100, jitenshah78 at gmail.com wrote: > I have string like follow > 12560/ABC,12567/BC,123,567,890/JK > > I want above string to group like as follow (12560,ABC) > (12567,BC) > (123,567,890,JK) > > i try regular expression i am able to get first two not the third one. > can regular expression given data in different groups Without regular expressions: def group(string): result = list() for item in string.split(','): if '/' in item: result.extend(item.split('/')) yield tuple(result) result = list() else: result.append(item) def main(): string = '12560/ABC,12567/BC,123,567,890/JK' print list(group(string)) Ciao, Marc 'BlackJack' Rintsch From not.my.email at mail.com Wed Sep 10 12:46:04 2008 From: not.my.email at mail.com (Vedran) Date: Wed, 10 Sep 2008 16:46:04 +0000 (UTC) Subject: Presenting calculation results Message-ID: Hello! I would like to present the results of the calculations on the web using Python and Apache. Currently I have java console applications that generate text files with results. Can somebody point me in the right direction from where to start? Thanks in advance! From cs at zip.com.au Thu Sep 4 23:53:44 2008 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 5 Sep 2008 13:53:44 +1000 Subject: Converting .doc to .txt in Linux In-Reply-To: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: <20080905035344.GA10761@cskk.homeip.net> On 04Sep2008 12:54, patrick.waldo at gmail.com wrote: | I had previously asked a similar question, | http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gst&q=convert+doc+txt#9dc901da63d8d059 | | but at that point I was using Windows and now I am using Linux. | Basically, I have some .doc files that I need to convert into txt | files encoded in utf-8. However, win32com.client doesn't work in | Linux. I use the "antiword" or "catdoc" commands to convert .doc to text. Call them from popen or subprocess from Python, if you must use Python (I'd just write a shell script for such a task myself unless its embedded in a larger python context). Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Please do not send me Microsoft Word files. http://en.nothingisreal.com/wiki/Please_don't_send_me_Microsoft_Word_documents From sturlamolden at yahoo.no Tue Sep 23 19:05:33 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 16:05:33 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: On Sep 23, 8:52?pm, bearophileH... at lycos.com wrote: > Is this a good or bad thing? ;-) It seems we have been implementing different algorithms. kd-trees are not BK-trees. http://www.scipy.org/Cookbook/KDTree From aioe.org at technicalbloke.com Wed Sep 17 13:12:29 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 13:12:29 -0400 Subject: Client server implementation References: <7d623ffb-2936-4aec-a74a-e9f5489e6657@p25g2000hsf.googlegroups.com> <708b9a1e-f4df-4d9c-8daa-cf77900acda4@s20g2000prd.googlegroups.com> Message-ID: Babloo wrote: > On Sep 16, 7:38 am, Benjamin wrote: >> On Sep 15, 5:15 am, Babloo wrote: >> >>> Hi everyone, >>> i wanted to implement a client- server connection >>> and transfer a file over the network. i was able to implement a normal >>> set up where in i was able to send chat messages and small chunks of >>> data. >>> I want to implement the file transfer with out using the FTP library >>> available in python . >>> So can anyone suggest a piece of code by which i can >>> do that. >> I don't know what you really want, but look at Twisted.http://twistedmatrix.com >> >> >> >>> Thanks >>> Pruthvi >> > I am beginner at using python language. > I mean i am implementing that in a windows based machine and wanted > to transfer files over the LAN. I have written down two files as > client.py and server.py . I ran these files at two different Computers > in the LAN and I was able to send small chunks of messages( like > chat). > > I was successful in establishing connection and sending small > messages. But now i want to transfer a complete file with out using > the ftplib(FTP LIBRARY) in python. > > > The files look like this.i hope this would help. > > ______________________________________________ > # Server program > > from socket import * > > # Set the socket parameters > host = "117.105.224.94" > port = 21567 > buf = 1024 > addr = (host,port) > > # Create socket and bind to address > UDPSock = socket(AF_INET,SOCK_DGRAM) > UDPSock.bind(addr) > > # Receive messages > while 1: > data,addr = UDPSock.recvfrom(buf) > if not data: > print "Client has exited!" > break > else: > print "\nReceived message '", data,"'" > > # Close socket > UDPSock.close() > __________________________________________________ > > # Client program > > from socket import * > > # Set the socket parameters > host = "117.105.224.94" > port = 21567 > buf = 1024 > addr = (host,port) > > # Create socket > UDPSock = socket(AF_INET,SOCK_DGRAM) > > def_msg = "===Enter message to send to server==="; > print "\n",def_msg > > # Send messages > while (1): > data = raw_input('>> ') > if not data: > break > else: > if(UDPSock.sendto(data,addr)): > print "Sending message '",data,"'....." > > # Close socket > UDPSock.close() > > _____________________________________________________________ > You're really not far away then, you basically need to come up with a simple protocol that can transmit 1) The file name 2) The file length 3) The file data itself You could also transmit the files metadata: datestamps, permissions etc if you wanted to make it better. Also, there might be security issues to consider too if you're running this on anything other than your own home network. So anyway, for a simple solution howabout you send: filename + "\n" filesize + "\n" (make sure you use str() to send this as text) Then loop through your filedata send a chunk wait for an OK back from the other side loop At the receiving end as the chunks arrive: Get the filename Open a file for writing Get the filesize Setup a loop to receive the file data Send OK Get chunk from socket Write data to file Break (stop) if filesize reached Loop Close file This, of course has no error correction and will probably die if you have any packet loss on your network, a more robust solution would be to use TCP sockets rather than UDP sockets. Hope this helps :-) Roger Heathcote http://www.technicalbloke.com http://movingtoubuntu.technicalbloke.co.uk From jitenshah78 at gmail.com Fri Sep 26 05:47:35 2008 From: jitenshah78 at gmail.com (jitenshah78 at gmail.com) Date: Fri, 26 Sep 2008 10:47:35 +0100 Subject: text processing SOLVED Message-ID: <48DCAFB7.4060409@gmail.com> Thanks Black Jack Working From monuindia at gmail.com Thu Sep 11 14:19:07 2008 From: monuindia at gmail.com (Monu) Date: Thu, 11 Sep 2008 11:19:07 -0700 (PDT) Subject: shelve file name extention References: Message-ID: On Sep 8, 1:47?pm, s... at pobox.com wrote: > ? ? Monu> When I am using shelve on my local machine it generates the db > ? ? Monu> file as given filename. But in another machine it's generating > ? ? Monu> .dat and .dir. ?can anyone tell me how can I force sheve > ? ? Monu> module to write the db in .dir and .dat, > ? ? Monu> instead of ? Do I have to install a specific version of > ? ? Monu> the python? > > Shelve is just a thin layer on top of a concrete db file module. ?Sounds > like on your two machines there are different underlying db file modules > available. ?You're pretty much at the mercy of those modules as to file > naming. ?All you are giving it when opening a shelve file is the prefix. > > Skip Thanks Skip. So Can't I choose which module to use. Is there any preferance on which shelve chooses these modules? From ivanov.maxim at gmail.com Sat Sep 27 18:29:45 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Sat, 27 Sep 2008 15:29:45 -0700 (PDT) Subject: multiprocessing eats memory References: <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> <02522a54-40ad-46a7-acb9-544f2fa5998f@d70g2000hsc.googlegroups.com> Message-ID: <11c7a862-12bb-4d92-987d-8b548251ffb5@y38g2000hsy.googlegroups.com> > When processing data in parallel you will use up as muchmemoryas > many datasets you are processing at any given time. Worker processes eats 2-4 times more than I pass to them. >If you need to > reducememoryuse then you need to start fewer processes and use some > mechanism to distribute the work on them as they become free. (see > recommendation that uses Queues) I don't understand how could I use Queue here? If worker process finish computing, it puts its' id into Queue, in main process I retrieve that id and how could I retrieve result from worker process then? From gagsl-py2 at yahoo.com.ar Fri Sep 5 00:21:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 01:21:56 -0300 Subject: Is it possible to download only the of a web page? References: Message-ID: En Thu, 04 Sep 2008 18:53:33 -0300, Fredrik Lundh escribi?: > Rex wrote: > >> I am writing a script that executes a bunch of queries through a form >> on a website and reads the results. I am only interested in the >> section in the <head> of each web page. Currently, each page >> the server returns is about 100kb and contains a bunch of HTML and >> Javascript, all of which I don't need; I don't want to waste bandwidth >> or consume too much of the server's resources. I just need the <title> >> string. > > you need to issue a GET request to get the HTML head section, which > almost always means that the server will build the entire page before > sending it to you (so it can set content-length etc). > > you can save on network traffic by parsing the data as it arrives, and > stopping when you've gotten the TITLE element: > > http://effbot.org/librarybook/sgmllib.htm Another alternative would be to estimate the size it takes to reach to the <title> tag, and issue a GET with a Range header. The server will -very likely- have to build the entire page, but won't attempt to send more bytes than requested. (In case the requested size is not enough, one can issue another GET asking for more data) http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 -- Gabriel Genellina From grante at visi.com Tue Sep 30 20:44:40 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Sep 2008 19:44:40 -0500 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> <LeadndG5x5LC0X_VnZ2dnUVZ_qHinZ2d@posted.visi> <00f2b214$0$20617$c3e8da3@news.astraweb.com> Message-ID: <lb6dnY1bn_xlWn_VnZ2dnUVZ_g-dnZ2d@posted.usinternet> On 2008-09-30, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote: > On Tue, 30 Sep 2008 10:57:19 -0500, Grant Edwards wrote: > >>>> How would the python equivalent go ? >> >> You would drag yourself out of the 1960s, install numpy, and >> then do something like this: > > I think that was thoughtlessly rude to somebody who is asking > a perfectly reasonable question. Sheesh. I guess I should have added a smiley face. So much for trying to be helpful. -- Grant From Lie.1296 at gmail.com Thu Sep 25 06:03:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 25 Sep 2008 03:03:59 -0700 (PDT) Subject: translating ascii to binary References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> <e9d5277e-11f2-4fb1-b916-2558fd318223@i20g2000prf.googlegroups.com> <mailman.1173.1221669327.3487.python-list@python.org> Message-ID: <bd0d9fb2-f333-4677-b780-ceb65f635d59@s20g2000prd.googlegroups.com> On Sep 17, 11:34?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > Lie wrote: > >> Any advice about this matter would be very appreciated. > >> Thanks in advance. > > > It'd be easier to make a one-char version of ascii2bin then make the > > string version based on the one-char version. > > And it'd be a lot easier to read your posts if you trimmed away at least > some of the original message before posting. ?If you cannot do that for > some technical reason, I recommend using top-posting instead. > > </F> Ah.. yes, sorry for that, I had never thought about that since I use Google Groups, which automatically trim long quotes, to access the list. From gagsl-py2 at yahoo.com.ar Thu Sep 4 23:55:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 00:55:53 -0300 Subject: pdb bug and questions References: <48C051AA.5090002@gmail.com> Message-ID: <op.ugzo7fdhx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 04 Sep 2008 18:22:50 -0300, Stef Mientki <stef.mientki at gmail.com> escribi?: (Sorry, I cannot help you with your main question) > When I launch the debugger ( winXP, Python 2.5) from with my editor > python -u -m pdb D:\\Data\\test_IDE.py > I get this error > IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') > NOTICE 1 backslash ----------------------------------^ > > If I launch the debugger with > python -u -m pdb D:/Data/test_IDE.py > It runs fine. How do you launch the debugger from your editor? The "python -u -m ..." is a command line, and should contain D:\Data\test_IDE.py (with backslashes). Read your editor's documentation on how to put those backslashes there. Python doesn't process or "cook" the arguments in any way, whatever the editor passes in the command line, is what Python will get as arguments. > Although I mostly use os.path.join to be OS independent, > these kind of bugs give me the impression, > that I can better do the join myself and always use forward slashes. > Is this a valid conclusion ? Not directly from this evidence - the issue is not directly related to Python. I'd use the generic path functions in os.path - like os.path.join, split, splitext, dirname, basename... The / separator may work most of the time on Windows, but not always, and it is not universal. Look at this file path in VMS: cdrom2:[dir1.dir2.dir3]filename.ext;24 -- Gabriel Genellina From daniel.watrous at gmail.com Tue Sep 30 18:44:51 2008 From: daniel.watrous at gmail.com (Daniel) Date: Tue, 30 Sep 2008 15:44:51 -0700 (PDT) Subject: problem with "ImportError: No module named..." and sockets References: <ff3e92a2-c35d-41da-bcb6-0e6f33b46e4d@f63g2000hsf.googlegroups.com> <mailman.1792.1222813069.3487.python-list@python.org> Message-ID: <d3821d42-486b-4dde-8073-4b925e619c47@z72g2000hsb.googlegroups.com> On Sep 30, 4:17?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Tue, 30 Sep 2008 18:38:19 -0300, Daniel <daniel.watr... at gmail.com> ? > escribi?: > > > > > [BEGIN CODE] > > #!/usr/bin/python > > import SocketServer > > import os, sys > > newpath = os.path.normpath( os.path.join( __file__, "../../.." )) > > sys.path.insert(0, newpath) > > > from pop.command.UpdateCommand import * > > import cPickle > > > Traceback (most recent call last): > > [...] > > ImportError: No module named UpdateCommand > > > I import the module at the top of the file server.py, but it doesn't > > throw the ImportError until it tries to unpickle. > > Notice that you don't import the UpdateCommand module - you import all ? > names defined inside it instead. It's not the same thing. > Seehttp://effbot.org/zone/import-confusion.htm > > -- > Gabriel Genellina Thank you Gabriel, The class inside that module has the same name, UpdateCommand. Since this is the object that was pickled, it should be available to the unpickle command. I already understood the difference between import methods and I think I'm covered. I did just try "import pop.command.TesterUpdateCommand" instead and I get the same error. From gagsl-py2 at yahoo.com.ar Tue Sep 2 04:36:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 05:36:33 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> Message-ID: <op.uguh670px6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 01 Sep 2008 04:23:38 -0300, Jeremy Banks <jeremy at jeremybanks.ca> escribi?: > Hi. I wondered if anyone knew the rationale behind the naming of the > Popen class in the subprocess module. Popen sounds like the a suitable > name for a function that created a subprocess, but the object itself is > a subprocess, not a "popen". It seems that it would be more accurate to > just name the class Subprocess, can anyone explain why this is not the > case? I have no idea - but I agree, Subprocess would have been a better name. -- Gabriel Genellina From grante at visi.com Mon Sep 1 10:08:05 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 01 Sep 2008 09:08:05 -0500 Subject: How Compute # of Days between Two Dates? References: <JAIuk.19687$cW3.19527@nlpi064.nbdc.sbc.com> Message-ID: <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: > That's the question in Subject. For example, the difference between > 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and > 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in > years between, say, 1990 and 2050. In other words not some really strange > period of time well outside our current era of history. Does the standard library's datetime module not do what you want? http://docs.python.org/lib/module-datetime.html -- Grant From adykes at panix.com Sat Sep 13 18:24:40 2008 From: adykes at panix.com (Al Dykes) Date: 13 Sep 2008 18:24:40 -0400 Subject: Code example that will make a Skype connection? References: <gaghj3$4tf$1@panix5.panix.com> <mailman.980.1221320529.3487.python-list@python.org> Message-ID: <gahej8$ooi$1@panix5.panix.com> In article <mailman.980.1221320529.3487.python-list at python.org>, Marco Bizzarri <marco.bizzarri at gmail.com> wrote: >On Sat, Sep 13, 2008 at 4:09 PM, Al Dykes <adykes at panix.com> wrote: >> >> Can some post a Python code fragment that will to make a PC with Skpye >> installed to make a Skype call, given a valid phone # string. >> >> I'm not asking for code that handles the audio once the connection is >> made. >> >> > >Maybe you can find this useful? > > >https://developer.skype.com/wiki/Skype4Py/examples/s4p_call_py > > >Regards >Marco Thanks for helping me get started. I'm new to Skype and Python. -- Al Dykes News is something someone wants to suppress, everything else is advertising. - Lord Northcliffe, publisher of the Daily Mail From coolkid246 at googlemail.com Thu Sep 4 06:10:13 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:10:13 -0700 (PDT) Subject: =?ISO-8859-1?Q?sofortkredit_online_in_Ulm_online_sofort_kredite_kre?= =?ISO-8859-1?Q?dit_ohne_schufa_selbstaendig_bargeld_eilkredite_guenstige_on?= =?ISO-8859-1?Q?line_kredit__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTIGE_KREDITE_ONLINE_=2B=2B=2B_KREDIT?= =?ISO-8859-1?Q?E_IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_=2B_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D?= =?ISO-8859-1?Q?244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKRE?= =?ISO-8859-1?Q?DITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_ht?= =?ISO-8859-1?Q?tp=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D?= =?ISO-8859-1?Q?244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKRE?= =?ISO-8859-1?Q?DITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_=2B_?= =?ISO-8859-1?Q?=2B_=2B_=2B_______________________kredite_schufafrei_kreditkarte_o?= =?ISO-8859-1?Q?hne_schufa_in_Ebersberg_schufa_freie_kredite_online_credit_o?= =?ISO-8859-1?Q?hne_in_Paderborn_kreditrechner_kredit_vergleich_in_Herzberg_?= =?ISO-8859-1?Q?online_kredite_oesterreich_kredit_mit_in_Detmold_arbeitslos_?= =?ISO-8859-1?Q?kredite_schweizer_kredite_in_Haldensleben_kleinkredit_sofort?= =?ISO-8859-1?Q?_kredite_ohne_schufa_auskunft_in_Segeberg_kredit_ohne_schufa?= =?ISO-8859-1?Q?_test_guenstiger_online_kredit_in_Emmendingen_online_kredit_?= =?ISO-8859-1?Q?mit_schufa_schufafreier_kredit_in_L=FCbbecke_kredit_ohne_schu?= =?ISO-8859-1?Q?fa_vergleich_kredite_selbstaendige_in_Kamenz____=2D_kredite_sc?= =?ISO-8859-1?Q?hufafrei_kredite_ohne_schufa_serioes_in_Rosenheim_=2D_online_k?= =?ISO-8859-1?Q?redit_direkt_online_kredite_ohne_schufa_in_Winsen_=2D_online=2Dk?= =?ISO-8859-1?Q?redite_kredite_rechner_in_Kirchheimbolanden_=2D_online_kredite?= =?ISO-8859-1?Q?_oesterreich_online_kredite_mit_sofortzusage_in_Koblenz_=2D_bi?= =?ISO-8859-1?Q?llig_kredit_ohne_schufa_kredit_uni_in_Ratzeburg_=2D_kredit_sch?= =?ISO-8859-1?Q?ufa_sofortkredit_ohne_auskunft_in_Bad_Neustadt_a=2Ed=2E_Saale_=2D_?= =?ISO-8859-1?Q?kredit_rechner_online_kredit_ohne_schufa_auskunft_in_Marienb?= =?ISO-8859-1?Q?erg_=2D_beamtenkredit_Guenstige_Kredide_online_ohne_SCHUFA_in_?= =?ISO-8859-1?Q?L=FCbben_=2D_kredit_sofortzusage_finanzierung_ohne_schufa_in_Ba?= =?ISO-8859-1?Q?utzen_=2D_credit_ohne_schufa_online_sofort_kredite_in_Lauterba?= =?ISO-8859-1?Q?ch_=2D_online_kredite_privat_online_kredit_de_in_Dillingen_=2D_k?= =?ISO-8859-1?Q?redit_von_privat_ohne_schufa_kredit_ohne_bonitaet_in_Bitburg?= =?ISO-8859-1?Q?_=2D_kredite_sofortzusage_darlehen_kredit_in_Neustadt_=2D_kredit?= =?ISO-8859-1?Q?e_schufa_kredite_schufafrei_in_Ostprignitz?= Message-ID: <f7729d35-6c4c-4b2a-b73e-17a681e6077e@w24g2000prd.googlegroups.com> sofortkredit online in Ulm online sofort kredite kredit ohne schufa selbstaendig bargeld eilkredite guenstige online kredit + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + kredite schufafrei kreditkarte ohne schufa in Ebersberg schufa freie kredite online credit ohne in Paderborn kreditrechner kredit vergleich in Herzberg online kredite oesterreich kredit mit in Detmold arbeitslos kredite schweizer kredite in Haldensleben kleinkredit sofort kredite ohne schufa auskunft in Segeberg kredit ohne schufa test guenstiger online kredit in Emmendingen online kredit mit schufa schufafreier kredit in L?bbecke kredit ohne schufa vergleich kredite selbstaendige in Kamenz - kredite schufafrei kredite ohne schufa serioes in Rosenheim - online kredit direkt online kredite ohne schufa in Winsen - online-kredite kredite rechner in Kirchheimbolanden - online kredite oesterreich online kredite mit sofortzusage in Koblenz - billig kredit ohne schufa kredit uni in Ratzeburg - kredit schufa sofortkredit ohne auskunft in Bad Neustadt a.d. Saale - kredit rechner online kredit ohne schufa auskunft in Marienberg - beamtenkredit Guenstige Kredide online ohne SCHUFA in L?bben - kredit sofortzusage finanzierung ohne schufa in Bautzen - credit ohne schufa online sofort kredite in Lauterbach - online kredite privat online kredit de in Dillingen - kredit von privat ohne schufa kredit ohne bonitaet in Bitburg - kredite sofortzusage darlehen kredit in Neustadt - kredite schufa kredite schufafrei in Ostprignitz From bignose+hates-spam at benfinney.id.au Tue Sep 23 20:58:21 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 24 Sep 2008 10:58:21 +1000 Subject: python syntax for conditional is unfortunate References: <mailman.1438.1222215919.3487.python-list@python.org> Message-ID: <87bpyez7f6.fsf@benfinney.id.au> Cameron Simpson <cs at zip.com.au> writes: > A good coder will present things clearly. For trivial stuff the one > line form may be fine, and for longer stuff then this: > > y = some thing or other \ > if x \ > else something_else Parentheses are usually more robust for multi-line, where possible: foo = (bar if some_condition() else baz) The lines can more easily be edited and rearranged without fiddling with backslashes at the end of every line. (For even more robustness at the cost of space, separate the parentheses so they're on separate lines from what they enclose.) It also addresses the original poster's complaint that there's no early signal of the compound nature of the expression: the opening parenthesis signals this. -- \ ?It is far better to grasp the universe as it really is than to | `\ persist in delusion, however satisfying and reassuring.? ?Carl | _o__) Sagan | Ben Finney From m_palmer45 at yahoo.ca Mon Sep 22 22:14:04 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 22 Sep 2008 19:14:04 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: <6c43c41d-6a4b-4391-9570-3c1497b7253b@m36g2000hse.googlegroups.com> On Sep 22, 9:13 pm, process <circularf... at gmail.com> wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. There are some attempts, see for example http://code.activestate.com/recipes/496691/ From mnations at gmail.com Fri Sep 5 10:37:48 2008 From: mnations at gmail.com (Mudcat) Date: Fri, 5 Sep 2008 07:37:48 -0700 (PDT) Subject: Python test case management system? References: <b7033321-db3e-4872-b928-f9a07db79918@f63g2000hsf.googlegroups.com> <87iqtbmm4e.fsf@benfinney.id.au> Message-ID: <1790bd7f-bbfb-427e-9085-96df497fdbf1@b1g2000hsg.googlegroups.com> > What would the behaviour of such a system be? In other words, what is > a "test case management system" in terms of the things that it does? The feature set for one tends to vary. In short it's a front end app which is tied to a db that stores and organizes test cases. The system will allow you to select and execute test cases based on different criteria which will then log and store the results. They aren't extremely complicated however they do need to have a well-built execution engine that are multi-threaded and can handle several different things at the same time. From lists at cheimes.de Sat Sep 20 21:06:40 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 21 Sep 2008 03:06:40 +0200 Subject: Not fully OO ? In-Reply-To: <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> Message-ID: <gb46mu$bkm$1@ger.gmane.org> Kay Schluehr wrote: > Actually it is simply wrong in the mentioned case and here is the > proof: > > def foo(): > return 2+2 > > import dis > dis.dis(foo) > > 2 0 LOAD_CONST 2 (4) > 3 RETURN_VALUE > > OO is a heuristic method used to understand the semantics of a > programming language. It can also inspire language design but as > you've rightly said: jugde yourself and see how far you get with it. It's not wrong. You have found a simple optimization. Lot's of compilers for lots of languages optimize code by code folding. Python's peephole optimizer replaces code like 2+2 with 4. Christian From justin.kuto at gmail.com Mon Sep 29 11:06:28 2008 From: justin.kuto at gmail.com (afrogazer) Date: Mon, 29 Sep 2008 08:06:28 -0700 (PDT) Subject: Web programming in Python. References: <eb5978f8-e802-48d2-a61f-207c25ac7059@y21g2000hsf.googlegroups.com> Message-ID: <e58bd1ec-555f-40a9-bcc4-f7225608c900@8g2000hse.googlegroups.com> Not to be a condescending, but there are a lot of manuals out there on how to do this and asking on a forum would really not be the best way to get started. Do some research and some reading and you should be up and running in a short time. You can ask questions on the forum if you have difficulties while/after reading. Good luck From castironpi at gmail.com Sat Sep 20 22:11:22 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 19:11:22 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> <mailman.1316.1221959218.3487.python-list@python.org> Message-ID: <a8438bbf-044a-4429-8ea9-7417daf68ef4@l42g2000hsc.googlegroups.com> On Sep 20, 8:06?pm, Christian Heimes <li... at cheimes.de> wrote: > Kay Schluehr wrote: > > Actually it is simply wrong in the mentioned case and here is the > > proof: > > > def foo(): > > ? ? return 2+2 > > > import dis > > dis.dis(foo) > > > ? 2 ? ? ? ? ? 0 LOAD_CONST ? ? ? ? ? ? ? 2 (4) > > ? ? ? ? ? ? ? 3 RETURN_VALUE > > > OO is a heuristic method used to understand the semantics of a > > programming language. It can also inspire language design but as > > you've rightly said: jugde yourself and see how far you get with it. > > It's not wrong. The meaning of the Python program is, internally, on a cycle-by-cycle basis, "Object 2; send add( Object 2 ) to Object 2; Return object 4." CPython doesn't do this, but due to the fact that there are no cases in which that distinction affects the output, it's still an implementation of Python. Or at least, a practical implementation. > You have found a simple optimization. Lot's of compilers > for lots of languages optimize code by code folding. > > Python's peephole optimizer replaces code like 2+2 with 4. > > Christian From straton at lampsacos.demon.co.uk Sat Sep 6 08:37:09 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sat, 06 Sep 2008 13:37:09 +0100 Subject: max(), sum(), next() In-Reply-To: <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> Message-ID: <g9tti1$8r$1$8300dec7@news.demon.co.uk> castironpi wrote: > On Sep 5, 9:20 pm, "Manu Hack" <manuh... at gmail.com> wrote: >> On Fri, Sep 5, 2008 at 1:04 PM, castironpi <castiro... at gmail.com> wrote: >>> On Sep 5, 3:28 am, "Manu Hack" <manuh... at gmail.com> wrote: >>>> On Thu, Sep 4, 2008 at 4:25 PM, castironpi <castiro... at gmail.com> wrote: >>>>> On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >>>>>> David C. Ullrich: >>>>>>> At least in mathematics, the sum of the elements of >>>>>>> the empty set _is_ 0, while the maximum element of the >>>>>>> empty set is undefined. >>>>>> What do you think about my idea of adding that 'default' argument to >>>>>> the max()/min() functions? >>>>>> Bye, >>>>>> bearophile >>>>> For max and min, why can't you just add your argument to the set >>>>> itself? >>>>> The reason max([]) is undefined is that max( S ) is in S. >>>> It makes sense. >>>>> The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >>>> It doesn't make sense to me. What do you set x to? >>> For all x. >> But then how can you conclude sum([]) = 0 from there? It's way far >> from obvious. > > You can define sum([a1,a2,...,aN]) recursively as > sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) "X", then > subtract aN. > > sum([a1,a2,...a(N-1)])+aN=X > sum([a1,a2,...a(N-1)])+aN-aN=X-aN > > For N=2, we have: > > sum([a1,a2])=X > sum([a1,a2])-a2=X-a2 > sum([a1,a2])-a2-a1=X-a2-a1 > > Since X= a1+ a2, replace X. > > sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 > > Or, > > sum([a1,a2])-a2-a1=0 > > Apply the recursive definition: > > sum([a1])+a2-a2-a1=0 > > And again: > > sum([])+a1+a2-a2-a1=0 > > And we have: > > sum([])=0. > This is not necessarily so. The flaw is that you provide a recursive definition with no start value, which is to say it is not a recursive definition at all. A recursive definition should be (for lists where elements can be added, and ignoring pythonic negative indexing): Define 'sum(L)' by a. sum(L[0]) = L[0] b. sum(L[0:i]) = sum(L[0:i-1]) + L[i] ... if i > 0 From this you can prove the reverse recursion sum{L[0:k]) = sum(L[0:k+1]) - L[k+1] __only__ if k >= 0 It says nothing about the empty list. You could add, as part of the definition, that sum{[]) = 0, or any other value. A rather different approach, not quite simple recursion, would be to start with A. a slicing axiom, something like: for all non-negative integers, a,b,c with a <=b <= c: sum(L[a:c]) = sum(L[a:b]) + sum(L[b:c]) B. a singleton axiom: for all integers a where L[a] exists: sum(L[a:a]) = L[a] 2a. sum{ From maric at aristote.info Mon Sep 15 10:17:42 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 16:17:42 +0200 Subject: Representation of python code ? In-Reply-To: <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> <mailman.1037.1221478736.3487.python-list@python.org> <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> Message-ID: <200809151617.42396.maric@aristote.info> Le Monday 15 September 2008 16:06:19 showellshowell at gmail.com, vous avez ?crit?: > I'm not sure this is the best counterexample. ?You can see statically > that A potentially creates an instance of the B class. > > > class A : > > ? ? def __init__(self) : > > ? ? ? ? ?self._b = B() > > > > class B : pass Yes, you can, but are you sure it's obvious that B in A.__init__ is the class you think of ? -- _____________ Maric Michaud From tino at wildenhain.de Fri Sep 26 05:37:51 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 11:37:51 +0200 Subject: How to parse a string completely into a list In-Reply-To: <e5d72ac8-0f92-4080-9e6b-34289bc52564@p31g2000prf.googlegroups.com> References: <e9e4f5c7-3467-4078-a401-fb732d69cc64@a3g2000prm.googlegroups.com> <mailman.1479.1222314277.3487.python-list@python.org> <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <mailman.1480.1222315955.3487.python-list@python.org> <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> <mailman.1481.1222329107.3487.python-list@python.org> <e5d72ac8-0f92-4080-9e6b-34289bc52564@p31g2000prf.googlegroups.com> Message-ID: <48DCAD6F.5000805@wildenhain.de> john.ford at colorado.edu wrote: ... > > Ahh, but I forgot to mention that I have to mark the path I took in > the string. So using list() and then join() are my best options. Still you would not need to create a list out of the string on your way. Just append the stepstone chars to a new list during your walk. Hoewever it entirely depends on your algorithm. Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/153771be/attachment.bin> From ldo at geek-central.gen.new_zealand Sun Sep 28 02:05:21 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 28 Sep 2008 19:05:21 +1300 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <gbh2sa$9j1$1@lust.ihug.co.nz> <mailman.1515.1222382168.3487.python-list@python.org> Message-ID: <gbn6r1$r5j$5@lust.ihug.co.nz> In message <mailman.1515.1222382168.3487.python-list at python.org>, James Mills wrote: > On Fri, Sep 26, 2008 at 8:20 AM, Lawrence D'Oliveiro > <ldo at geek-central.gen.new_zealand> wrote: > >> Object orientation IS procedural. > > Correction: OOP is Imperative. No, "procedural". The functional unit is called an "expression", the encapsulation of which is called a "function". Hence "functional". Similarly, the procedural unit is commonly called a "statement", the encapsulation of which is a "procedure", not an "imperator". Hence "procedural". From electronixtar at gmail.com Sun Sep 28 07:17:39 2008 From: electronixtar at gmail.com (est) Date: Sun, 28 Sep 2008 04:17:39 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <gbn6nu$r5j$4@lust.ihug.co.nz> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> <6f247162-b0b7-4fba-bfd8-df9261cc5d30@p31g2000prf.googlegroups.com> Message-ID: <5412f9e0-a363-4c8a-a85c-d7bff4e02edd@l33g2000pri.googlegroups.com> On Sep 28, 7:12?pm, Lie <Lie.1... at gmail.com> wrote: > On Sep 28, 3:35?pm, est <electronix... at gmail.com> wrote: > > > > Because that's how ASCII is defined. > > > Because that's how ASCII is defined. ?ASCII is a 7-bit code. > > > Then why can't python use another default encoding internally > > range(256)? > > > > Python refuses to guess and tries the lowest common denominator -- ASCII -- instead. > > > That's the problem. ASCII is INCOMPLETE! > > What do you propose? Use mbsc and smack out linux computers? Use KOI > and make non-Russians suicide? Use GB and shot dead non-Chinese? Use > latin-1 and make emails servers scream? > > > If Python choose another default encoding which handles range(256), > > 80% of python unicode encoding problems are gone. > > > It's not HARD to process unicode, it's just python & python community > > refuse to correct it. > > Python's unicode support is already correct. Only your brainwave have > not been tuned to it yet. > > > > stop dreaming of a magic solution > > > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, > > what's wrong???? > > > > Isn't that more or less the same as telling the OP to use unicode() instead of str()? > > > sockets could handle str() only. If you throw unicode objects to a > > socket, it will automatically call str() and cause an error. Have you ever programmed with CJK characters before? From deets at nospam.web.de Sat Sep 6 09:06:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Sep 2008 15:06:08 +0200 Subject: embed python in ms-word? In-Reply-To: <mailman.609.1220705553.3487.python-list@python.org> References: <mailman.609.1220705553.3487.python-list@python.org> Message-ID: <6ifdi0FptetbU1@mid.uni-berlin.de> oyster schrieb: > in fact, during my work, I often write documnets in ms-word. But the > doc has many numbers in it, which need to be calculated and to be > modified frequently. > > Is there a method to write a ms-word add-in, so that > 1.I can type in the calculation steps in some program language, > please have a look at http://blender.bokee.com/inc/word_add_in1.jpg > > 2.then the result (here, it is 8) is shown in the doc when I close this window? > please have a look at http://blender.bokee.com/inc/word_add_in2.jpg > > 3.when I double-click the result 8, I can view/edit the code again > > 4.the code for calculation is stored in DOC file too, I can change it later > > mathtype equation is a kind of such thing, but only for displaying > nice equation > > I don't think vba is a good answer, the main reason is: the vba code > has an incompact link with its result in the documnet I don't know what you mean with the last sentence - but I still think VBA is the answer. There is no other way to write a plugin or some such for word than using COM, and VB *is* COM. So whatever you can do in Word, it's exposed in VBA. Bringing python into the mixture is just creating a lot of hassle. Automating word with Python is a different thing - that seems to be popular and powerful. Diez From sturlamolden at yahoo.no Wed Sep 24 17:25:11 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 14:25:11 -0700 (PDT) Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <gbe6qk$b54$1@aioe.org> <Xns9B23DFA195833duncanbooth@127.0.0.1> Message-ID: <d57f3edc-a305-4165-bafb-d0d75bb54948@z72g2000hsb.googlegroups.com> On Sep 24, 10:59?pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote: > Simple LINQ expressions like the one you gave map easily to Python list > comprehensions. What Microsoft have done though is provide a consistent > implementation which allows you to write complex SQL like expressions which > will work identically on databases or most other sequence types. > han extensions to syntax. List comprehensions work with any iterable sequence. You can nest them to make more complex statements. You can also use a generator to iterate through a database or an XML document. Here is approximately where linq stops being a marvelous addition to Python. And I can honestly do without the SQL syntax. From presence at MUNGEpanix.com Sun Sep 28 17:28:47 2008 From: presence at MUNGEpanix.com (Cydrome Leader) Date: Sun, 28 Sep 2008 21:28:47 +0000 (UTC) Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <f1dtd45fij5nu9uvnico53cab73uj6pdev@4ax.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> <gbmelr$nhh$4@reader1.panix.com> <7qmtd4hc52o84pksc6tni0pmgnfvpvf08m@4ax.com> Message-ID: <gbosuf$ojh$2@reader1.panix.com> In rec.crafts.metalworking default <default at defaulter.net> wrote: > On Sat, 27 Sep 2008 23:12:59 +0000 (UTC), Cydrome Leader > <presence at MUNGEpanix.com> wrote: > >>In rec.crafts.metalworking Jim Thompson <To-Email-Use-The-Envelope-Icon at my-web-site.com> wrote: >>> >>> On Sat, 27 Sep 2008 18:47:16 -0400, default <default at defaulter.net> >>> wrote: >>> >>>>On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko >>>><milenko.stojadinovic at googlemail.com> wrote: >>>> >>>>>Hello, this is Milenko Stojadinovic from town Banjaluka, >>>>>Bosnia and Herzegovina, also known as Cvrcko >>>>>Does anyone know of any bars in town where I can >>>>>swallow a bucket of cum? It can be either dog, >>>>>horse or human cum. Also, does anyone know of >>>>>any sex bars where people will shit in your mouth? >>>>>I also like eating shit. >>>> >>>>Come to the US and park your mouth in front of George Bush - all the >>>>Bshit you can eat - and it keeps on coming! >>>> >>>>I have a buddy in Bosna - he's normal. >>> >>> Now you know why I blanket kill-file googlegroups. >> >>So you and everybody can talk about them nonstop? > > If you mean Google Groups the condemnation is justified. > > Who is "them?" Real people do occasionally wander in to GG - or those > without news servers - or without understanding of Usenet. > > Basically, in the engineering groups (in particular) outsiders are > welcome. Engineers are smart, creative and tolerant as a general > rule. > > Lighten up. Who are you defending? and Who goes into Usenet with a > thin skin? Expect ridicule, expect condemnation - "water off a duck's > back." > > You may think your viewpoint is the only one, the right one, the valid > one - but a few million others may disagree. And you ain't started to > deal with culture shock - some countries place emphasis on diplomacy _ > you know the "how are you?" stuff, others don't, and seem very cold. > > Adapt. Now you know why I blanket kill-file googlegroups. From jobs at omacindustries.com Mon Sep 8 12:55:53 2008 From: jobs at omacindustries.com (jobs at omacindustries.com) Date: Mon, 8 Sep 2008 09:55:53 -0700 (PDT) Subject: Calling Common Lisp Game Developers Message-ID: <0cd34294-c623-487c-ac61-a5d92348829e@s50g2000hsb.googlegroups.com> We are currently seeking talented Lisp Game Developers who are passionate about game development and want to play a major role in developing and maintaining new features for one of our persistent browser games. This particular title uses Hunchentoot, but all other code has been developed in house using the Mnesia database for persistence. This particular game is not released yet but has already generated interest from over 35,000 players globally. If you?re interested in developing Persistent Browser Games using SBCL and want to know more then send us an email at lisp at omacindustries.com The preferred location for this role is in Dublin, Ireland but we are also open to hearing from anyone who prefers to work remotely. http://omacindustries.com From martin at v.loewis.de Mon Sep 8 23:58:26 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Sep 2008 05:58:26 +0200 Subject: problem with Tix in Python2.5 In-Reply-To: <5ce15a64-755e-4000-9627-8fd92413424c@r35g2000prm.googlegroups.com> References: <c8cced6a-cc88-4ab7-876d-b9421f1ac585@n38g2000prl.googlegroups.com> <mailman.2230.1219775081.922.python-list@python.org> <5ce15a64-755e-4000-9627-8fd92413424c@r35g2000prm.googlegroups.com> Message-ID: <48C5F462.7010202@v.loewis.de> > i couldn't find any binary distribution of tix8.4.So i think i have to > reinstall python. > i also have numpy and PIL installed.If i reinstall python on top of > the current python directory will i lose them? You should run a "repair" installation. In Add-and-remove-programs, select Python, then Repair. Regards, Martin From apardon at forel.vub.ac.be Tue Sep 2 09:54:37 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Sep 2008 13:54:37 GMT Subject: How can we get to the end of a quote inside a string References: <e209b6e3-1829-4674-816e-c35ae478f160@25g2000prz.googlegroups.com> Message-ID: <slrngbqhct.3rg.apardon@rcpc42.vub.ac.be> On 2008-08-31, rajmohan.h at gmail.com <rajmohan.h at gmail.com> wrote: > Hi all, > Suppose I have a string which contains quotes inside quotes - > single and double quotes interchangeably - > s = "a1' b1 " c1' d1 ' c2" b2 'a2" > I need to start at b1 and end at b2 - i.e. I have to parse the > single quote strings from inside s. > > Is there an existing string quote parser which I can use or > should I write a parser myself? > > If somebody could help me on this I would be much obliged. You could use a combination of split and join in this case. #use a single quote as a seperator to split the string is a list of substrings ls = s.split("'") #remove what comes before the first and after the last single quote ls = ls[1:-1] #reassemble the string between the outermost single quotes. s = "'".join(ls) #strip spaces in front and after if you wish s = s.strip() -- Antoon Pardon From duncan.booth at invalid.invalid Thu Sep 25 04:08:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Sep 2008 08:08:08 GMT Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <gbe6qk$b54$1@aioe.org> <Xns9B23DFA195833duncanbooth@127.0.0.1> <d57f3edc-a305-4165-bafb-d0d75bb54948@z72g2000hsb.googlegroups.com> Message-ID: <Xns9B245BE13E207duncanbooth@127.0.0.1> sturlamolden <sturlamolden at yahoo.no> wrote: > On Sep 24, 10:59?pm, Duncan Booth <duncan.bo... at invalid.invalid> > wrote: > >> Simple LINQ expressions like the one you gave map easily to Python >> list comprehensions. What Microsoft have done though is provide a >> consistent implementation which allows you to write complex SQL like >> expressions whi > ch >> will work identically on databases or most other sequence types. >> han extensions to syntax. > > List comprehensions work with any iterable sequence. You can nest them > to make more complex statements. You can also use a generator to > iterate through a database or an XML document. Here is approximately > where linq stops being a marvelous addition to Python. > A lot of what LINQ does is already easy to do in Python, and most of the rest can probably be added fairly easily, but it does provide a consistent framework which may make it easier to do complex LINQ statements than complex list comprehensions. BTW, a minor correction: LINQ statements are closer to generators, not list comprehensions. They don't actually evaluate their results until you iterate over them and you can re-used the same LINQ statement multiple times getting different results if the data has changed. > And I can honestly do without the SQL syntax. > snap :) -- Duncan Booth http://kupuguy.blogspot.com From tkpmep at hotmail.com Mon Sep 29 14:59:27 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Mon, 29 Sep 2008 11:59:27 -0700 (PDT) Subject: Finding subsets for a robust regression Message-ID: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> I have coded a robust (Theil-Sen) regression routine which takes as inputs two lists of numbers, x and y, and returns a robust estimate of the slope and intercept of the best robust straight line fit. In a pre-processing phase, I create two new lists, x1 and y1; x1 has only the unique values in x, and for each unique value in x1, y1 has the median of all such values in x. My code follows, and it seems a bit clumsy - is there a cleaner way to do it? By the way, I'd be more than happy to share the code for the entire algorithm - just let me know and I will post it here. Thanks in advance Thomas Philips d = {} #identify unique instances of x and y for xx,yy in zip(x,y): if xx in d: d[xx].append(yy) else: d[xx] = [yy] x1 = [] #unique instances of x and y y1 = [] #median(y) for each unique value of x for xx,yy in d.iteritems(): x1.append(xx) l = len(yy) if l == 1: y1.append(yy[0]) else: yy.sort() y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else yy[l//2] ) From tgrav at mac.com Thu Sep 18 13:17:18 2008 From: tgrav at mac.com (Tommy Grav) Date: Thu, 18 Sep 2008 13:17:18 -0400 Subject: Cython dynamic library problem In-Reply-To: <8763otl8ea.fsf@merkury.smsnet.pl> References: <mailman.1216.1221749258.3487.python-list@python.org> <8763otl8ea.fsf@merkury.smsnet.pl> Message-ID: <B81C132E-9418-405C-8EAB-E1C2C3ECE76D@mac.com> On Sep 18, 2008, at 12:35 PM, Rob Wolfe wrote: > I would try to use `distutils` because this package is much wiser > than me and knows all necessary switches for gcc. ;) That worked! Thanks Cheers Tommy From fetchinson at googlemail.com Wed Sep 10 18:33:58 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Sep 2008 15:33:58 -0700 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: <276719.72706.qm@web95107.mail.in2.yahoo.com> References: <276719.72706.qm@web95107.mail.in2.yahoo.com> Message-ID: <fbe2e2100809101533q5daf5b39h2f9996cd2358e01@mail.gmail.com> > I know I'm tooooo late to ask you for help....but please help me out..I > am really new to unix and dont know how to finish this assignment on > time.....proff. said he will be using MOSS to detect whether I > downloaded the code..please help me.. > > email me : vaidehi.pawar at yahoo.co.in > > Assignment 1 > Processes, Inter-Process Communication, and Concurrency > Due September 13th midnight > Summary > In > this assignment, you will create two versions of a simple multi-process > game : one without and another with inter-process synchronization. You > will also measure the relative performance of the two versions of your > multi-process game. > Objectives > > * Learn how to create and terminate processes. > * Learn use of inter-process communication using shared memory, > semaphores, signals, etc. > * Learn the basic workings of CPU scheduling code in Linux. > > Part A: Multi-Process Game of Turns > > In > this part, you are asked to write a simple program that takes two > command-line arguments P and N. The main process creates P other child > processes, waits for all of them to complete, and then exits. All the > child processes form one logical ring among each other. (In rest of the > description, the term "process" refers to a "child process".) For > example, if the processes are numbered 1 to P, then > > * The next neighbor of process 1 is process 2, > * The next neighbor of process i is process i+1 for all i < P , and > * The next neighbor of process P is process 1, which completes a ring > among the processes. > > Assume > that a shared integer variable, called turn, identifies the number of > the processes whose turn it is at any instant. A second process-local > variable in each process, called me, identifies the identity of each > process (i.e. each process stores its own identity in a per-process > local variable me). A third per-process local variable, called next, > identifies the next process in the ring. > > The processes > sequentially pass the turns among each other in the logical ring. When > each process gets its turn, it increments another shared variable > called counter. The pseudo-code within each process for passing turns > might look something as follows. (Note: Replace turn and counter below > with appropriate ways of accessing data within shared memory regions). > > while(turn != me ) > /* do nothing - just busy loop*/ ; > > /* got my turn - increment counter */ > counter = counter + 1; > > /* give the turn to next process */ > turn = next; > > The program terminates when the each process has received N turns. > > In the above description, several programming details have been omitted for > you to figure out. This includes > > * Creating P child processes from main process. > * Constructing the logical ring among child processes. > o Initializing each child process's identity in the me variable. > o Initializing each child process' next neighbor in the next > variable. > * Initializing the shared memory region and the shared data values. > * Have the main process wait for child processes to complete N turns > before exiting. > > Part B: More Efficient Game of Turns > > You > might notice that the program you wrote in Part A is inefficient > because each process busy loops till the CPU scheduler kicks it out > (after its time-slice is over) and allows another process to execute > and make progress. (Does the program in Part A have a race condition? > Why or why not?) > > What we ideally want is that each process > should be given control of the CPU only when it is that process' turn. > Modify the program you wrote in Part A (using appropriate > synchronization mechanisms) such that each process gets to run (i.e., > gets control of the CPU) only when it is that process's turn, and at no > other time. > > Again, you would need to work out the programming details of how and where > to use inter-process synchronization. > Part C: Profiling the Game of Turns > > In > this part, you are asked to write user-level profiling code in order to > measure the performance of the two versions of programs you wrote in > Part A and Part B. Use a combination of gettimeofday() system call and > inter-process synchronization to measure (1) the average hand-over time > between two consecutive processes in the ring and (b) the total > execution time to complete N turns. Plot the measured values as graphs > when varying number of processes P and number of turns N. Explain the > results you obtain. > Submission Guidelines > > Thanking you, > > Ms. Vaidehi Pawar How much do you pay? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From deets at nospam.web.de Tue Sep 16 17:04:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 16 Sep 2008 23:04:43 +0200 Subject: help on python SWIG C++ extension In-Reply-To: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> References: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> Message-ID: <6jalbbF29igbU1@mid.uni-berlin.de> RLC schrieb: > Hello > > I am new to python SWIG. Recently I wrote a small program trying to > import collada files(using colladadom) into python so I could use > python cgkit to render them. However, during the progressing, I got > some problems. Every time I quit from Python, I get a segmentation > fault, although the main program runs well. I suspect it is because I > wrapped std::vector objects in C struct and I did not release the > memory properly. Below is the code. I am working on FreeBSD 7.0, GCC > 4.2.1. I will be very appreciated if you could help me. Thanks a lot. > > the error I have got > Segmentation fault: 11 (core dumped) Try starting the program in gdb. This works using $ gdb python (gdb) set args myscript.py (gdb) run Then when the segfault hits, get a backtrace to see where the actual problem occurs. Diez From dave.dibiase at gmail.com Wed Sep 24 17:02:33 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Wed, 24 Sep 2008 17:02:33 -0400 Subject: Schwartzian transform for tuple in list Message-ID: <ea42fb160809241402i1c6da16t4dd2456a87d6f177@mail.gmail.com> Hi, I have a rather large list structure with tuples contained in them (it's part of a specification I received) looks like so: [(x1,y1,r1,d1),(x2,y2,r2,d2)...] The list can range from about 800-1500 tuples in size and I'm currently sorting it with this: a_list.sort(lambda a, b: cmp(b[3], a[3])) I'm actually sorting it by the last value in the tuple (d2). I have been researching more efficient sorting algorithms and came across Schwartzian transform via these links: - http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency - http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html I get what's happening (sorta...errr...lol) but I'm not sure if it is more efficient in my scenario, if it is then I have no idea how to implement it properly :-/ Would be great if a true expert would offer a suggestion for me... Thanks! David -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080924/b184de92/attachment.html> From m_palmer45 at yahoo.ca Wed Sep 3 14:57:51 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 3 Sep 2008 11:57:51 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> Message-ID: <5f3757a5-31da-4c01-b504-584218ac9427@73g2000hsx.googlegroups.com> On Sep 3, 12:57 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > Michael Palmer schrieb: > > > The other, PyGUI, has an even nicer API and more docs but has > > relatively few widgets implemented at this time. It also strives for > > compatibility with several toolkits (two at this time), which I think > > is the right idea. > > I disagree with that. Meta-wrappers like this will always suffer from > problems, as they have difficulties providing a consistent api. For > example wx is said to be very windows-toolkit-centric in it's API. Yes I > know that it works under Linux with GTK, but it does not come as natural . wax actually does a nice job at wrapping wxPython with a cleaner API. > > So far, development of PyGUI seems to be a one-man effort, and it may > > be slowed down by the attempt to develop the API and the > > implementations concurrently. Could it be useful to uncouple the two, > > such that the API would be specified ahead of the implementation? This > > might make it easier for people to contribute implementation code and > > maybe port the API to additional toolkits. It seems that this approach > > has been quite successful in case of the Python database API. That API > > defines levels of compliance, which might be a way of accommodating > > different GUI toolkits as well. > > > I may be underestimating the difficulties of my proposed approach - I > > don't have much practical experience with GUI programming myself. > > I think you do. The reason for the various toolkits is not because of > python - it's the proliferation of toolkits that exist out there. Right. But that is similar to the situation with relational databases. There are so many of them that it's impossible to include an adapter to each of them in the stdlib. The next best thing is to provide a high-level API that abstracts away the differences. > As long as none of these is "the winner" (and it doesn't look is if that's > to happen soon), I doubt that one API to rule them all will exist - they > all have their different strengths and weaknesses, and a python-API > should reflect these. I rather think that a standard API would cover a reasonable subset - it should NOT contain the idiosyncrasies of each individual toolkit. The anygui project, which has been dormant for a while, is another attempt at a high-level api. Apparently, it tried to implement backends for a lot of toolkits - which again may have been to ambitious an agenda. Maybe someone who was involved in that project might provide some insight. From ldo at geek-central.gen.new_zealand Wed Sep 24 06:09:23 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:09:23 +1200 Subject: finding domain name References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> <mailman.1404.1222174222.3487.python-list@python.org> <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> <mailman.1406.1222175467.3487.python-list@python.org> <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> Message-ID: <gbd3kj$vdf$1@lust.ihug.co.nz> In message <09637faf-75d8-4af0-b835-3b5a67132996 at y21g2000hsf.googlegroups.com>, Bobby Roberts wrote: > evidently the environ dictionary is off limits on our server. Why? > It can't > be that tough in python to get the current complete url being viewed. > It's a snap in asp(which is my background). Unless, of course, the relevant information was off limits on your server. From apardon at forel.vub.ac.be Mon Sep 29 07:25:56 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Sep 2008 11:25:56 GMT Subject: cups.Connection.printFile References: <mailman.1082.1221540507.3487.python-list@python.org> <slrngd7c55.37k.apardon@rcpc42.vub.ac.be> <e5740200-7cce-48c6-b1ad-370eb4467b78@v13g2000pro.googlegroups.com> Message-ID: <slrnge1eqs.4bc.apardon@rcpc42.vub.ac.be> On 2008-09-26, Mike Driscoll <kyosohma at gmail.com> wrote: > On Sep 19, 9:01?am, Antoon Pardon <apar... at forel.vub.ac.be> wrote: >> On 2008-09-16, Graham Jenkins <gra... at vpac.org> wrote: >> >> >> >> > I'm trying to print a file from within a Python program. >> >> > The quick-and-dirty solution is to use something like: >> >> > fd = os.popen("lp -d MyPrinter", "wb") >> > fd.write(MyFileContents) >> >> > But it seems to me that there should be a clean solution like: >> >> > import cups >> > stat = >> > cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") >> >> What about systems that don't use cups for printing? >> >> -- >> Antoon Pardon > > For Windows, there's a few different ways to print. Tim Golden has a > list on his website: > > http://timgolden.me.uk/python/win32_how_do_i/print.html I have a linux system that doesn't use cups for printing. So his "clean" solution won't work on my box. Unless of course his cups.Connection.printFile is just a wrapper around os.popen("lp -d MyPrinter", "wb") or something similar. -- Antoon Pardon From greg at cosc.canterbury.ac.nz Fri Sep 26 23:15:25 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 27 Sep 2008 15:15:25 +1200 Subject: Why are "broken iterators" broken? In-Reply-To: <6eb35e11-4799-495f-8469-fd03278e97b3@o40g2000prn.googlegroups.com> References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> <6eb35e11-4799-495f-8469-fd03278e97b3@o40g2000prn.googlegroups.com> Message-ID: <6k5n86F685i0U1@mid.individual.net> Craig Allen wrote: > In the end I interpreted that statement as if "unless __iter__()" is > called again It seems you were confusing iterators and iterables. The iterator is the object that is returned by calling __iter__() on an iterable, and yes, you are expected to get a new one each time you want to start iterating again. -- Greg From grante at visi.com Mon Sep 15 01:02:35 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 15 Sep 2008 00:02:35 -0500 Subject: Unable to see os.environ['COLUMNS'] References: <mailman.1024.1221453482.3487.python-list@python.org> Message-ID: <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> On 2008-09-13, Tim Chase <python.list at tim.thechases.com> wrote: > Not sure what's going on here and hoping for some insight: > > tim at rubbish:~$ echo $COLUMNS > 129 > tim at rubbish:~$ python2.5 > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> import os > >>> os.environ.get('COLUMNS') > >>> 'COLUMNS' in os.environ > False > > I can coerce it by using > > tim at rubbish:~$ COLUMNS=$COLUMNS python2.5 > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> import os > >>> 'COLUMNS' in os.environ > True > > However, this seems hokey to me. > > FWIW, this is in Bash on Debian. In bash (and other descendants of the Bourne shell), there are two types of environment variables: 1) local variables that are not passed on to child processes and 2) exported variables that _are_ passed on to children. By default, when a variable is created it is local and will not be inherited by sub-processes. > What's the best way to read what seems to be a > pseudo-environment variable? You can't. You need to export the variable in the parent shell before it exec's the child: $ echo $COLUMNS 80 $ python -c "import os; print os.environ['COLUMNS']" Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ raise KeyError(key) KeyError: 'COLUMNS' $ export COLUMNS $ python -c "import os; print os.environ['COLUMNS']" 80 Now, on to the question you're about to ask: Q: How do I find out how big my terminal is from a Python program? A: You use the TIOCGWINSZ ioctl call on the terminal's file descriptor: >>> import sys,fcntl,termios,struct >>> data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234') >>> struct.unpack('hh',data) (24, 80) There's a more detailed explanation here (including an explanation of what the third parameter to ioctl() does, and how you detect changes in the window size): http://mail.python.org/pipermail/python-list/2006-February/365710.html There's also chance that you'd be better off just using ncurses or newt for screen management, but that's another post. -- Grant From srikrishnamohan at gmail.com Sat Sep 27 04:34:47 2008 From: srikrishnamohan at gmail.com (km) Date: Sat, 27 Sep 2008 14:04:47 +0530 Subject: python for *nix system admins In-Reply-To: <48DDE92D.6090405@telcotec.se> References: <48DDE92D.6090405@telcotec.se> Message-ID: <f4cc03640809270134g588d4df4q341dfaafab9df594@mail.gmail.com> import os HTH KM ~~~~~~~~~~~~~~ On Sat, Sep 27, 2008 at 1:35 PM, Lars Stavholm <stava at telcotec.se> wrote: > Hi All, > > I'm new to this list and hoping that this is not off-topic. > If it is, please point me in the right direction. > > I seem to recollect a python module or library for *nix sysadmins, > but I can't for the life of me find it again. > > The module (or library) somehow added unix command capabilities > to the python language. It seemed like a lesser known, perhaps new, > python library or module. > > Any input or ideas appreciated > /Lars Stavholm > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080927/4059be34/attachment.html> From clp at rebertia.com Wed Sep 10 00:40:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Sep 2008 21:40:57 -0700 Subject: Simplest solution for formatting local time in iso 8601 including time zone. In-Reply-To: <382d494c-b32b-454a-842b-6f559a94e025@26g2000hsk.googlegroups.com> References: <382d494c-b32b-454a-842b-6f559a94e025@26g2000hsk.googlegroups.com> Message-ID: <47c890dc0809092140n25ea1254tfb21af44dcb7c943@mail.gmail.com> On Tue, Sep 9, 2008 at 9:32 PM, <rowland at river2sea.org> wrote: > What's the simplest solution for formatting the output of local time > in iso 8601 including the time zone information? > > Example: > > "2008-07-25T14:28:43.934-04:00" You want the isoformat() method of datetime objects. See http://docs.python.org/lib/datetime-datetime.html for details. You'll need to pass 'T' as the separator to isoformat() and pass in a tzinfo object when constructing the datetime object. Regards, Chris > > > Thanks, > Rowland > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From prologic at shortcircuit.net.au Mon Sep 8 17:47:26 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 9 Sep 2008 07:47:26 +1000 Subject: Trying to make a spider using mechanize In-Reply-To: <a8476a36-cd9f-4658-a738-8565a3915a00@d77g2000hsb.googlegroups.com> References: <a8476a36-cd9f-4658-a738-8565a3915a00@d77g2000hsb.googlegroups.com> Message-ID: <e1a84d570809081447h21505e85k994abdd82629fab9@mail.gmail.com> Hi, Perhaps you might want to try out using a sample spider I wrote and base your code of this ? See: http://hg.shortcircuit.net.au/index.wsgi/pymills/file/b9936ae2525c/examples/spider.py cheers James On Tue, Sep 9, 2008 at 2:24 AM, tedpottel at gmail.com <tedpottel at gmail.com> wrote: > Hi, > > I can read the home page using the mechanize lib. Is there a way to > load in web pages using filename.html instad of servername/ > filename.html. Lots of time the links just have the file name. I'm > trying to read in the links name and then vsit those pages. > > here is the sample code I am ussing. > > > import ClientForm > import mechanize > > > #get home page > request = mechanize.Request("http://www.activetechconsulting.com") > response = mechanize.urlopen(request) > print response.read() > > #sub page (this does note work) > request = mechanize.Request("service.html") > response = mechanize.urlopen(request) > print response.read-Ted > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From maric at aristote.info Tue Sep 16 08:48:16 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 14:48:16 +0200 Subject: append on lists In-Reply-To: <gao7lg$ha3$1@online.de> References: <gamffv$qms$1@online.de> <1221564169.16690.0@proxy00.news.clara.net> <gao7lg$ha3$1@online.de> Message-ID: <200809161448.16883.maric@aristote.info> Le Tuesday 16 September 2008 14:23:25 Armin, vous avez ?crit?: > Alex Marandon wrote: > > Armin wrote: > >> Duncan Booth wrote: > >> > >> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > >> (with c = [8,9]) is identical, > > > > No it's not, + doesn't alter its operands. > > > > >>> a = 1 > > >>> b = 2 > > >>> a + b > > > > 3 > > That's not the point :) It is, please try to understand it, in python all expressions that mutate an object should return None, it's the case for l.append(x) l.sort() l.reverse() ... all expressions that return something, return a new object, it's the case for 1+2 1.__add__(2) (which is the same) sorted(l) l[i:j] etc... there are some noticeable exceptions : For coding facilities, some APIs could return the modified part of the object, ex : it = c.pop() Returning the modifyied object itself is mostly considered bad style, because it doesn't make clear if this the object or a copy. There is OTHO a use case for this, for APIs that allow chaining of operations (don't find by memory any example in stdlib, though), alike the ">>" operator in C++, but pyparsing is a good example if I remember well. BTW, Pythoneers are not very fond of that. Finally, the very special case of augmented assignment operators : x.__iadd__(y) which actually return the modified object, but this expression isn't intended to be use by callers, refer to the manual to see a good example of this, how one should implement __add__ and __iadd__ methods. a += b a = a + b both are statments (doesn't evaluate to any object), but are not equivalent if a is mutable. > > What's the value of 1.add(b)? None? Or 3 ?? > (if add works in the same way as append) > a + b doesn't change a,b ... but a.add(b) -> a=3 > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From maric at aristote.info Mon Sep 15 10:45:12 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 16:45:12 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> Message-ID: <200809151645.13078.maric@aristote.info> Le Thursday 11 September 2008 06:51:19 Dennis Lee Bieber, vous avez ?crit?: > On Wed, 10 Sep 2008 21:36:36 -0500, Grant Edwards <grante at visi.com> > > declaimed the following in comp.lang.python: > > Wrong. I didn't send _any_ e-mail. Why should I get bounce > > messages? > > One: Comp.lang.python is dual-routed with a mailing list; anything > you post to either CLP or the mailing list gets cross-posted to the > other -- the FROM header retains that of the original author (which > could be you). > > Two: Somebody else is subscribed to the mailing list, and sets up an > "out-of-office" reply or has other problems (like an overfilled mailbox, > causing a bounce, or a discontinued account) when the forwarded post > reaches their address. > > Three: The bounce/ooo-reply is sent to the message author, not to > any intermediate host(s). After all, on that end, it's normal email > failure response -- notify the author of the message. It doesn't matter > that the original message was posted on a Usenet newsgroup if that group > is automatically relayed to members of a mailing list. Given RFCs, the problem should not be, for DSN, the MTA should rewrite the FROM envelope address to the one of the list maintainer : RFC 3464 : > 3. Conformance and Usage Requirements > > ... > > By contrast, successful submission of a message to a mailing list > exploder is considered final delivery of the message. Upon delivery > of a message to a recipient address corresponding to a mailing list > exploder, the Reporting MTA SHOULD issue an appropriate DSN exactly > as if the recipient address were that of an ordinary mailbox. > > NOTE: This is actually intended to make DSNs usable by mailing > lists themselves. Any message sent to a mailing list subscriber > should have its envelope return address pointing to the list > maintainer [see RFC 1123, section 5.3.7(E)]. Since DSNs are sent > to the envelope return address, all DSNs resulting from delivery > to the recipients of a mailing list will be sent to the list > maintainer. The list maintainer may elect to mechanically > process DSNs upon receipt, and thus automatically delete invalid > addresses from the list. (See section 7 of this memo.) and > Appendix C - Guidelines for use of DSNs by mailing list exploders > > - Guidelines for use of DSNs by mailing list exploders > > > This section pertains only to the use of DSNs by "mailing lists" as > defined in [4], section 7.2.7. > > DSNs are designed to be used by mailing list exploders to allow them > to detect and automatically delete recipients for whom mail delivery > fails repeatedly. > > When forwarding a message to list subscribers, the mailing list > exploder should always set the envelope return address (e.g., SMTP > MAIL FROM address) to point to a special address which is set up to > receive non-delivery reports. A "smart" mailing list exploder can > therefore intercept such non-delivery reports, and if they are in the > DSN format, automatically examine them to determine for which > recipients a message delivery failed or was delayed. This is not sufficient for auto-responses, and given the following rfcs, it would smart to both : - add an "Auto-Submitted: Python User Group" header, - add or modify the Return-Path and/or Reply-To header for badly implemented auto-responders to point to list maintainer. RFC 3834: > 4. Where to send automatic responses (and where not to send them) > > > In general, automatic responses SHOULD be sent to the Return-Path > field if generated after delivery. If the response is generated > prior to delivery, the response SHOULD be sent to the reverse-path > from the SMTP MAIL FROM command, or (in a non-SMTP system) to the > envelope return address which serves as the destination for non- > delivery reports. and > 5. The Auto-Submitted header field > > > The purpose of the Auto-Submitted header field is to indicate that > the message was originated by an automatic process, or an automatic > responder, rather than by a human; and to facilitate automatic > filtering of messages from signal paths for which automatically > generated messages and automatic responses are not desirable. RFC 1123 : > 5.3.7 Mail Gatewaying > > Gatewaying mail between different mail environments, i.e., > different mail formats and protocols, is complex and does not > easily yield to standardization. See for example [SMTP:5a], > [SMTP:5b]. However, some general requirements may be given for > a gateway between the Internet and another mail environment. > > (A) Header fields MAY be rewritten when necessary as messages > are gatewayed across mail environment boundaries. > > DISCUSSION: > This may involve interpreting the local-part of the > destination address, as suggested in Section 5.2.16 I'm also frustrated by some (rare) of my mails which are actually blocked for confirmation by a moderator with this message : > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > Message has a suspicious header I think it's probably my domain name which makes this, do the anti-spam engine use whitelists ? How to resolve the problem if not ? -- _____________ Maric Michaud From kar1107 at gmail.com Sat Sep 6 20:14:20 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Sat, 6 Sep 2008 17:14:20 -0700 (PDT) Subject: Seeking ideas for a cron implementation References: <cf52ec86-2b1c-4faa-b97c-d4ccc879b326@x16g2000prn.googlegroups.com> <8f607078-e8da-4438-8769-96d011f1544f@j1g2000prb.googlegroups.com> Message-ID: <76e696f6-4428-4c59-9d30-661022ca5dbe@w39g2000prb.googlegroups.com> On Aug 22, 1:51?pm, Sean DiZazzo <half.ital... at gmail.com> wrote: > On Aug 22, 1:30?pm, Karthik Gurusamy <kar1... at gmail.com> wrote: > > > > > Hi, > > > I'm working on acronlike functionality for my application. > > The outer loops runs continuously waking every x seconds (say x=180, > > 300, ..). > > It needs to know what events incronhas expired and for each event do > > the work needed. > > > It's basically like unixcronor like a calendar application with some > > restrictions. The outer loop may come back a lot later and many events > > might have missed their schedule -- but this is okay.. We don't have > > to worry about missed events (if there were n misses, we just need to > > execute call back once). > > > Let's take some examples [Let e denotes an event] > > e1: hour=1 ?min=30 ? ? ? ? ? ? ? ? ? ? ? ? ? ? # Run every day once at > > 1:30 AM > > e2: wday=0, hour=1 ?min=0 ? ? ? ? ? ? ? ? ? # run every Monday at 1 AM > > e3: month=10, day=10, hour=10 min=0 ?# run on October 10th, 10 AM > > every year > > > class Cron_Event (object): > > ? ? def __init__ (year=None, month=None, day=None, hour=None ..etc) > > ? ? ? # ?do init > > > classCron(object): > > ? ? def __init__ (): > > ? ? ? ? # do init > > ? ? def event_add (e): > > ? ? ? ? # add an event > > ? ? def execute() > > ? ? ? ? # see if any events has "expired" .. call it's callback > > ? ? ? ? # I'm looking for ideas on how to manage the events here > > > From outer loop > >cron=Cron() > > # create various events like > > e1 = Cron_Event(hour=1) > >cron.event_add(e1) > > e2 = Cron_Event(wday=0, hour=1) > >cron.event_add(e2) > > > while True: > > ? ? sleep x seconds (or wait until woken up) > > ? ?cron.execute() > > ? ? # do other work.. x may change here > > > If I can restrict to hour and minute, it seems manageable as the > > interval between two occurrences is a constant. But allowing days like > > every Monday or 1st of every month makes things complicated. Moreover > > I would like each constraint in e to take on multiple possibilities > > (like every day at 1AM, ?2 AM and 4 AM do this). > > > I'm looking for solutions that can leverage datetime.datetime > > routines. > > My current ideas include for each e, track the next time it will fire > > (in seconds since epoch as given by time.time()). Once current time > > has passed that time, we execute the event. e.g.>>> datetime.datetime.now() > > > datetime.datetime(2008, 8, 22, 13, 19, 54, 5567)>>> time.time() > > > 1219436401.741966 ? ?<--- compute event's next firing in a format like > > this > > > The problem seems to be how to compute that future point in time (in > > seconds since epoch) ?for a generic Cron_Event. > > > Say how do I know the exact time in future ?that will satisfy a > > constraint like: > > ?month=11, wday=1, hour=3, min=30 ? ?# At 3:30 AM on a Tuesday in > > November > > > Thanks for your thoughts. > > > Karthik > > I only scanned your message, but maybe datetime.timedelta() will > help.. > > >>> import datetime > >>> now = datetime.datetime.now() > >>> print now > > 2008-08-22 13:48:49.335225>>> day = datetime.timedelta(1) > >>> print day > 1 day, 0:00:00 > >>> print now + day > > 2008-08-23 13:48:49.335225 Thanks, I found using a more efficient algorithm tricky and seemed error prone. [I do welcome ideas still if anyone has a cool solution] I used your idea and took the easy way out by using a brute-force search. Here is an outline if anyone faces similar problem: hours, minutes are lists: say for every day at 1:30 pm and 2:45 pm, hours=[13, 14] and minutes=[30, 45,]. I restricted myself to minutes and hours (and every day) to simplify the problem. def set_expiry_time_check_in_a_day (self, now, target, hours, mins, flags=set()): """ A small utility routine to simulate 'goto' Looks like now could be computed inside this function -- the small drift due to time taken in this function should be negligible """ # let's see if in today we can find an expiry # we do brute force search starting with the smallest hour for hour in hours: for min in mins: target = target.replace(hour=hour, minute=min, second=0, microsecond=0) if 'is_debug_1' in flags: print "Trying target time: %s..." % target if target > now: if 'is_debug_1' in flags: print "Found target time: %s" % (target, ) return target # simulates a break from two loops return None def set_expiry_time (self, event, flags=set()): """ For a given event, compute and remember when it will fire next """ now = datetime.datetime.now() target = now # start checking from now.. # assumption, hours and mins are atleast one int element array # and they are in sorted order hours = event.spec['hours'] mins = event.spec['minutes'] tries = 0 while True: # runs of each day.. tomorrow ... tries += 1 if tries > 50: # safety valve, we are basically in infinite loop raise Exception("Tried 50 times.. in infinite loop??") target_found = self.set_expiry_time_check_in_a_day(now, target, hours, mins, flags) if target_found is not None: # found a match on "this" day target = target_found break # we need to increase the day count.. increment = datetime.timedelta(days=1) target += increment # added 24 hours .. let's go and check tomorrow ... event.target = target > > ~Sean From pete.forman at westerngeco.com Fri Sep 19 07:37:51 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Fri, 19 Sep 2008 12:37:51 +0100 Subject: PEP proposal optparse References: <ca58efdf-3f9c-4aea-9c20-69c69a578754@k30g2000hse.googlegroups.com> Message-ID: <1vzgcqnk.fsf@wgmail2.gatwick.eur.slb.com> James <jlnicolson at gmail.com> writes: > I would like to know your thoughts on a proposed change to optparse > that I have planned. It is possible to add default values to > multiple options using the set_defaults. However, when adding > descriptions to options the developer has to specify it in each > add_option() call. -1 I see no advantage to swelling optparse when the language offers many solutions already. E.g. desc = { 'verbose': 'Output less information', 'castordir': 'specify the wanted CASTOR directory where to store ' 'the results tarball', 'previousrel': 'Top level dir of previous release for regression ' 'analysis'} parser.add_option('-q', '--quiet', action="store_false", dest='verbose', help = desc['verbose']) ... Or another approach might be like this. for ... in zip(...): parser.add_option(...) -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From sjmachin at lexicon.net Fri Sep 5 19:30:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 16:30:35 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> <a34c6ffd-0353-43c9-8b22-36d0fc66ed22@v16g2000prc.googlegroups.com> <d9a713e1-3305-4d9c-8cac-02dc1c57aa86@m3g2000hsc.googlegroups.com> Message-ID: <0e12f3cd-7088-4f64-afa8-eb5ac4d00031@t1g2000pra.googlegroups.com> On Sep 6, 7:49?am, bearophileH... at lycos.com wrote: > John Machin: > > > Consider this:>>> hash(123) == hash(123.0) == hash(123L) > > True > > Right... Can you explain me why Python designers have chosen to build > a hash() like that? I can't channel them; my rationalisation is this: Following the Law of Least Astonishment, >> 123 == 123.0 == 123L True Consequently if x == y, then adict[x] and adict[y] should give the same result. Cheers, John From lists at svrinformatica.it Tue Sep 16 02:31:13 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Tue, 16 Sep 2008 08:31:13 +0200 Subject: Zsi interoperability In-Reply-To: <3f0d61c40809151126n791b1ce0ya1e208a075660934@mail.gmail.com> References: <mailman.1047.1221498380.3487.python-list@python.org> <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> <3f0d61c40809151126n791b1ce0ya1e208a075660934@mail.gmail.com> Message-ID: <1221546673.5885.4.camel@localhost.localdomain> Il giorno lun, 15/09/2008 alle 20.26 +0200, Marco Bizzarri ha scritto: > On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel <stefan_ml at behnel.de> wrote: > > Mailing List SVR wrote: > >> I have to implement a soap web services from wsdl, the server is > >> developed using oracle, is zsi or some other python library for soap > >> interoperable with oracle soa? > > > > No idea, but I'd definitely try soaplib before ZSI. > > > > Stefan > > I'm working on a project where I need to write a client for SOAP with > Attachments; I can see ZSI does not support it; is soaplib any better? > I don't need soap attachments, I have some images but are base64 encoded string, all other field are string, however my server require client certificate authentication, does soaplib or zsi work in this environment? is really strange that there isn't a standard and well manteined soap-1.2 implementation for python so we can talk without interoperability issue with axis2,metro,cxf,oracle,.net ecc.. :-( thanks Nicola > Can you argument your suggestion a little more? > > Regards > Marco > > > From deets at nospam.web.de Wed Sep 3 15:25:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 21:25:48 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <5f3757a5-31da-4c01-b504-584218ac9427@73g2000hsx.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> <5f3757a5-31da-4c01-b504-584218ac9427@73g2000hsx.googlegroups.com> Message-ID: <6i86ltFp9oegU1@mid.uni-berlin.de> Michael Palmer schrieb: >> I disagree with that. Meta-wrappers like this will always suffer from >> problems, as they have difficulties providing a consistent api. For >> example wx is said to be very windows-toolkit-centric in it's API. Yes I >> know that it works under Linux with GTK, but it does not come as natural . > > wax actually does a nice job at wrapping wxPython with a cleaner API. wax wraps wx. It does not wrap PyQt, Tk, win32, GTK and whatnot. That was what I was talking about. > Right. But that is similar to the situation with relational databases. > There are so many of them that it's impossible to include an adapter > to each of them in the stdlib. The next best thing is to provide a > high-level API that abstracts away the differences. > >> As long as none of these is "the winner" (and it doesn't look is if that's >> to happen soon), I doubt that one API to rule them all will exist - they >> all have their different strengths and weaknesses, and a python-API >> should reflect these. > > I rather think that a standard API would cover a reasonable subset - > it should NOT contain the idiosyncrasies of each individual toolkit. And thus reduce the usability massively. A reasonable subset is already included in python, with tkinter, available on a wide range of plattforms. Yet still people strive for the various other toolkits, because they miss richer widgets, gui-designers (an important topic you don't cover at all) or e.g. multi-threading capabilities. > The anygui project, which has been dormant for a while, is another > attempt at a high-level api. Apparently, it tried to implement > backends for a lot of toolkits - which again may have been to > ambitious an agenda. Maybe someone who was involved in that project > might provide some insight. Sure, that would be interesting. Diez From ceball at users.sourceforge.net Tue Sep 16 19:34:27 2008 From: ceball at users.sourceforge.net (Chris) Date: Tue, 16 Sep 2008 23:34:27 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: <mailman.793.1221057913.3487.python-list@python.org> <efaa21d2-6e94-4170-ae8e-e7ddb0cd5d2e@w1g2000prk.googlegroups.com> <mailman.914.1221222322.3487.python-list@python.org> <8763p1799y.fsf@mulj.homelinux.net> <871vzp77lp.fsf@mulj.homelinux.net> Message-ID: <loom.20080916T200156-930@post.gmane.org> Hrvoje Niksic <hniksic <at> xemacs.org> writes: ... > > You are getting that error because Carl forgot to cast the descriptor > > to the appropriate C type, in this case PyMemberDescrObject. The last > > line is also incorrect, I think. Try something like this: ... The code you gave was great, thanks! Now we have done exactly what we wanted, and have fast access from C to two particular attributes of instances of a particular class. We use that fast access in optimized versions of pure-Python components of our simulator. Chris From deets at nospam.web.de Mon Sep 15 16:00:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 22:00:59 +0200 Subject: Python Nautilus script In-Reply-To: <48cebba7$0$2862$ba620e4c@news.skynet.be> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> Message-ID: <6j7t7rF1tl5rU1@mid.uni-berlin.de> Michel Leunen schrieb: > Diez B. Roggisch a ?crit : > >> There shouldn't be a difference between a shell-script and a >> python-script. Environment-variables are a unix-process-thing, and >> thus the rules that govern them apply to *all* processes - the shell >> is one of these, there is nothing special to it. >> >> If the shell-script gets the variable, the python-script will as well. > > Yes, that's what I thought too but try this: open a terminal and type > > $ echo $HOSTNAME > > you will get the name of your computer. > Now try this instead: > > $ python > >>> import os > >>> os.environ['HOSTNAME'] > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'HOSTNAME' > >>> Which is the exact right thing to happen if the HOSTNAME is not exported. The echo above is executed IN THE CURRENT SHELL environment. If it weren't - why would there be any distinction between local and exported variables at all? If you put > It appears that's because HOSTNAME is not exported. > But in the case of Nautilus script, how to workaround this issue? I don't know for sure if the shell has something build-in that makes it spawn shell-subprocesses with a different environment than other processes. However, if you want you can do something like this: #!/bin/bash export VARIABLE_NAME python /the/python/script.py You create a shell-script that exports the environment first, and then invokes python. Diez From xnews2 at fredp.lautre.net Wed Sep 17 17:34:06 2008 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 17 Sep 2008 21:34:06 GMT Subject: ANN: Python GUI development using XULRunner References: <mailman.1150.1221614920.3487.python-list@python.org> Message-ID: <Xns9B1CEFF3C9D21PaCmAnRDLM@212.27.60.39> Todd Whiteman <toddw at activestate.com> said : > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming > language. > The tutorial covers how to build a Python/XULRunner GUI application: > http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulru > nner_about.html > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform > (MacOSX is possible with a few deviations, I have tried to cover these > deviations where applicable). > Feedback is welcome. Thanks for making good on your promise. I'm leaving for a trip but have it bookmarked for later use :-) From bborcic at gmail.com Tue Sep 9 09:47:20 2008 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 09 Sep 2008 15:47:20 +0200 Subject: max(), sum(), next() In-Reply-To: <5ee352aa-9ee5-4a8b-8b01-b9e6d1cc808e@m73g2000hsh.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <mailman.687.1220882152.3487.python-list@python.org> <5ee352aa-9ee5-4a8b-8b01-b9e6d1cc808e@m73g2000hsh.googlegroups.com> Message-ID: <ga5urd$fq5$1@ger.gmane.org> castironpi wrote: > On Sep 8, 8:54 am, Boris Borcic <bbor... at gmail.com> wrote: >> David C. Ullrich wrote: >> >>> (ii) If A is a subset of B then we should have >>> max(A) <= max(B). This requires that max(empty set) >>> be something that's smaller than everything else. >>> So we give up on that. >> Er, what about instances of variations/elaborations on >> >> class Smaller(object) : __cmp__ = lambda *_ : -1 >> >> ? >> >> Cheers, BB > > You still don't have the property max(X) is in X. Frankly, I would favor order-independence over that property. compare max(X) for 1) X = [set([1]),set([2])] and 2) X = [set([2]),set([1])] Shouldn't then max and min in fact return lub and glb, despite their names ? In the case X is a non-empty finite set/list of totally ordered values, max(X)==lub(X) and min(X)=glb(X) in any case. > > And it's the equivalent of a special builtin constant for max on the > empty set. Of course (except the object might have other uses, who knows). So what ? Cheers, BB From mathieu.prevot at gmail.com Mon Sep 15 15:58:45 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Mon, 15 Sep 2008 21:58:45 +0200 Subject: Parallelising code In-Reply-To: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: <3e473cc60809151258o193e950j382716b97f9e4adb@mail.gmail.com> 2008/9/15 psaffrey at googlemail.com <psaffrey at googlemail.com>: > I have some file processing code that has to deal with quite a lot of > data. I have a quad core machine, so I wondered whether I could take > advantage of some parallelism. > > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? > > - Is list.append() thread safe? (not sure if this is the right term) > what I mean is, can two separate processors file a point in the same > list at the same time without anything horrible happening? Do I need > to do anything special (mutex or whatever) to make this happen, or > will it happen automatically? You won't take advantage of your cores with a pure and single python script. Python threads are useful for UI, files operations, all but concurrent processing. The simpler way to do concurrent processing is to use Popen from subrocess, that'll create new processes. Notice that you can call python scripts from another one eg a manager and as many workers as you want. IMO it's the simpler design and less work for making concurrent processes. Ideally make your workers not need to feedback with variable, or anything more complex than a return value. Also, make them not write the same file. They can read the same file without problem. Remark that you can manage lock etc from the manager script. I'm not sure python semaphore allow interprocess communication like c semaphores [1] ; check this. A workaround is to send to stderr tuples. HTH, Mathieu [1] Programming with POSIX Threads, David R. Butenhof, http://tinyurl.com/6hpkol From darcy at druid.net Mon Sep 29 12:49:40 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 29 Sep 2008 12:49:40 -0400 Subject: Music knowledge representation In-Reply-To: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> Message-ID: <20080929124940.8c1c82e8.darcy@druid.net> On Sun, 28 Sep 2008 16:37:11 +0200 "Mr.SpOOn" <mr.spoon21 at gmail.com> wrote: > Hi, > I'm working on an application to analyse music (melodies, chord sequences etc.) Sounds interesting. Will this be Open Source? > I need classes to represent different musical entities. I'm using a > class Note to represent all the notes. Inside it stores the name of > the natural version of the note (C, D, E, F...) and an integer to > calculate the accidentals. Have you considered having the object take a key option with default to 'C' so that you don't have to mark as many accidentals - or, more correctly, mark actual accidentals rather than always marking the "black keys?" The other advantage here is that the notes can be given as numbers and octaves (middle C would be (1, 3, 0) in the key of C for example) and you can transpose by changing the argument when instantiating the class. > Then I have a class Pitch, to represent the different 12 pitch > classes, because different notes, such as C# and Db, belong to the > same pitch class. Couldn't the note class simply have a list of all the notes and have a simple method calculate the actual pitch? > In these classes I also have some arithmetic method to perform > additions or subtractions between pitches and integers. > > I also need to represent intervals between notes. An interval must > have a degree (first, second, third), that may be represented with a > simple integer and a size counted in semitones. Then, with these > informations it can retrieve its name, for example: perfect fifth. Seems easy given the pitch location indeces. Subtract the two and do a lookup into a list of intervals. E.g: ["Unison", "Semi-tone", "Second", "Minor third", Major third", ...] > The degree is calculated between natural notes. So the degree of > Interval(C, E) is "third", or 3. This may be simple, if I put the > notes in an ordered sequence. But, when I have to calculate, for > example Interval(E, C). It should count till the end of the sequence, > so if I have: > > C D E F G A B > > after the B it should continue with C. I'm not sure how to implement > this. Is there a suitable data structure for this purpose? def interval(self, lower, higher) if lower > higher: # uncomment one of the two following lines depending # on the behaviour you want #lower,higher = higher,lower #higher += 12 # could use some error trapping return self.interval_name[higher - lower] Note that lower and higher could be a note object that you have to convert to integers first. Hope this gives you some ideas. -- D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From castironpi at gmail.com Tue Sep 16 16:55:17 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 13:55:17 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <mailman.1138.1221594080.3487.python-list@python.org> Message-ID: <08337238-2c56-4eec-b42a-45b65480f37e@m44g2000hsc.googlegroups.com> On Sep 16, 2:40?pm, "Support Desk" <m... at ipglobal.net> wrote: > What about on a unix box? I can't help you. I don't have access to '/opt/pkgs/python-2.0/lib/ python2.0/site-packages' (ha ha) on the one I have access to. If you do, try the same thing. > > Sincerely, > Michael H. > > -----Original Message----- > From: Aaron "Castironpi" Brady [mailto:castiro... at gmail.com] > Sent: Tuesday, September 16, 2008 12:49 PM > To: python-l... at python.org > Subject: Re: How do I add permanently to Pythons sys.path? > > On Sep 16, 10:13?am, cnb <circularf... at yahoo.se> wrote: > > >>> sys.path > > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > > \lib\\site-packages\\PIL'] > > > Now I have my personal programs in C:/Python25/Progs/ > > > How do I add so that I can just do "import somefile" from anywhere in > > that directory in the interpreter and it can load files from other > > folders in that directory. > > Add a file: \Lib\site-packages\locals.pth > > with contents, path to the directory you want to add (/python25/progs/) > > From david.trem at gmail.com Sun Sep 14 14:32:53 2008 From: david.trem at gmail.com (David Trem) Date: Sun, 14 Sep 2008 11:32:53 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <48BFB534.2080508@egenix.com> <mailman.569.1220632640.3487.python-list@python.org> <Xns9B15D1BE39452PaCmAnRDLM@212.27.60.38> Message-ID: <88eadda3-25a5-4319-9468-6b8afe5d4640@k13g2000hse.googlegroups.com> On 10 sep, 20:36, Fred Pacquier <xne... at fredp.lautre.net> wrote: > Todd Whiteman <to... at activestate.com> said : > > > Personally, I believe XULRunner has a lot to offer for Python GUI > > development, I'm currently finishing up some documentation steps to show > > off how to use it specifically for Python (I'll post it to this list > > when it's finished). > > That would be really nice ! > > I've long been curious about the potential of XUL+Python, but put off by > the lack of leads to follow up, and not having time to do the digging > myself... > > TIA, > fp I will also like to see such documentation as soon as possible. To me, XUL+python really looks like what could be my prefered solution for multiplatform GUI for my python program. I'm really impatient and hope a strong and motivated community could set up arrond such XUL+python project. All the best, David From bluecrystalyj at gmail.com Fri Sep 5 09:12:41 2008 From: bluecrystalyj at gmail.com (bcm) Date: Fri, 5 Sep 2008 06:12:41 -0700 (PDT) Subject: int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why? Message-ID: <184502f4-872a-4c23-9a6d-e93ef225d4de@a2g2000prm.googlegroups.com> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 The following line of code describes an funny question? >>> int((9.2-9.0)*10) 1 >>> int((9.21-9.0)*10) 2 >>> int((9.1-9.0)*10) 0 >>> int((9.11-9.0)*10) 1 >>> int((8.2-8.0)*10) 1 >>> int((8.23-8.0)*10) 2 why? anybody can explain it? From kaerbuhez at gmail.com Sat Sep 6 16:16:56 2008 From: kaerbuhez at gmail.com (kaer) Date: Sat, 6 Sep 2008 13:16:56 -0700 (PDT) Subject: running python as a dameon References: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> <6e7ead25-baf1-400a-a52f-568f37351aab@8g2000hse.googlegroups.com> <5c74118c-a576-4a51-ae9a-95d34273a99a@s50g2000hsb.googlegroups.com> Message-ID: <de097d76-cd3c-487f-a9ec-90c1f5129ba4@e53g2000hsa.googlegroups.com> On 6 sep, 15:44, Michael Palmer <m_palme... at yahoo.ca> wrote: > On Sep 5, 9:56 pm, Sean Davis <seand... at gmail.com> wrote: > > > > > > What I want > > > to do is to provide the python NLP program as a service to any other > > > PHP/Java/Ruby process request. So the mapping is > > > > http -> apache -> PHP/Java/Ruby/... -> Python NLP > > > Why not use a simple CGI script or wsgi application? You could make > > the service online and interactive and with the same application and > > code make an XMLRPC web service. So, things would look more like: > > > http -> apache -> Python (running NLP and serving requests) > > > You can use apache to proxy requests to any one of a dozen or so > > python-based webservers. You could also use mod_wsgi to interface > > with a wsgi application. > > > Sean > > xmlrpc is the right idea, as it interfaces easily across languages. I just daemonize some utility script these week. For that I took one of the scripts in the ASPN python cookbook : google those 3 words then search python and you will find out your solution faster than I end up this mail. It worked like a charm on my linux box. BTW, I wouldn't complicate with xml stuffs if you don't need it. Good luck. From jmdeschamps at gmail.com Mon Sep 1 17:58:50 2008 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: Mon, 1 Sep 2008 14:58:50 -0700 (PDT) Subject: Play AVI files as cut-scene... in BGE - HOW? Message-ID: <318f98dd-cfec-43cc-bc59-a59d8dbd64af@2g2000hsn.googlegroups.com> Blender Game Engine does not seem able to just play an AVI clip file... I want to play these files as cut-scenes in a game - subprocess it to the OS, and continue on return seems a good solution - but so sorry, it's been a while since I've delved in such places... I need a refresher. Must be platform independent (or platform *adjustable* ;-) ) Continue script execution only after it's over (in due time or passed over by user) Must be configurable to adjust ourput screen and stuff like that... Any hints out there :-) Thanks in advance! From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 13:01:42 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 19:01:42 +0200 Subject: improving a huge double-for cycle In-Reply-To: <00e2e17d$0$20331$c3e8da3@news.astraweb.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <48d54863$0$4666$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote: > >> Now the obvious winner is pruebono - even unoptimized, using sets seems >> to be *way* faster than even the most optimized corrected version of >> your algorithm. > > I'm not being snarky about losing priority here, but I submitted > essentially the same solution two hours earlier than pruebono. My bad... Now that you mention it, I see you effectively did. My fault, I did a too-fast screening of submitted solutions, and hereby declare you Steven as the winner. > Are people not seeing my posts? Have I been kill-filed by everyone except > Mensator? I do see your posts. Whether I read them entirely is another question - and in this concrete case, the answer is obviously 'nope'. Put the blame on me. > I also asked a question about HTTPError and I haven't seen any > responses at all. This is another problem - it happens that no one has a clue, or that the one having a clue lack time (or willingness) to anwer. Once again, sorry if me missing your correct answer drives you paranoid :( From lists at cheimes.de Wed Sep 10 07:12:58 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 13:12:58 +0200 Subject: which of these 2 quicksorts is faster? In-Reply-To: <ga87ij$1r1$1@ger.gmane.org> References: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> <ga87ij$1r1$1@ger.gmane.org> Message-ID: <ga8a3q$8mm$2@ger.gmane.org> Fredrik Lundh wrote: > what makes you think you can write a better sort than the built-in > algorithm by typing in some toy quick-sort implementations from a > "sorting for dummies" article? Anybody who can FULLY understand Tim's text at http://svn.python.org/projects/python/branches/release25-maint/Objects/listsort.txt can write a better sorting algorithm ... *scnr* :] Christian From kenneth.m.mcdonald at sbcglobal.net Wed Sep 10 11:24:38 2008 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 10 Sep 2008 10:24:38 -0500 Subject: subprocess.Popen hangs at times? Message-ID: <AAC5A7F8-7617-43F7-84C3-07E0EA4DFDA5@sbcglobal.net> When making calls of the form Popen(cmd, shell=True, stdout=subprocess.PIPE), we've been getting occasional, predictable hangs. Will Popen accumulate a certain amount of stdout and then block until its read? We don't want to use threads, so just want to read the entire stdout after the subprocess has finished. Thanks, Ken From maric at aristote.info Tue Sep 16 08:03:31 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 14:03:31 +0200 Subject: Is 'x' an instance of a new-style class? In-Reply-To: <878wts76dc.fsf@mulj.homelinux.net> References: <f568f4d9-b179-4ef1-9688-fcd8cb5ef641@d1g2000hsg.googlegroups.com> <mailman.1102.1221557922.3487.python-list@python.org> <878wts76dc.fsf@mulj.homelinux.net> Message-ID: <200809161403.31885.maric@aristote.info> Le Tuesday 16 September 2008 12:05:51 Hrvoje Niksic, vous avez ?crit?: > "Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> writes: > > En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS <schaefer.mp at gmail.com> > > > > escribi?: > >> I've seen the question raised several times here, but apparently never > >> answered. Since PyInstance_Check returns False for new-style class > >> instances, is there a standard procedure for testing this using the C- > >> Api? > >> > >> I would greatly appreciate some help with this. > > > > In Python you would write isinstance(x, object). > > It will return True for all Python objects (except perhaps those that > fiddle with metaclasses), not only for instances of new-style classes. > > >>> isinstance([], object) > > True > > >>> isinstance((), object) > > True > > >>> isinstance(list, object) > > True > > >>> isinstance(type, object) > > True > > I don't think there is a good way to check if something is a new-style > class instance. The whole point of new-style classes was removing the > distinction between classes and types. The distinction is now so well > removed that it's hard to find it when you need it. > Yes, everything (including instances of old style classes) are instance of a new style class but : not isinstance(x, types.InstanceType) ensure you that x is not an instance of old style class. > A better question for OP is *why* he needs to distinguish between > instances of new-style classes and other objects. > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From mwilson at the-wire.com Sat Sep 6 11:03:10 2008 From: mwilson at the-wire.com (Mel) Date: Sat, 06 Sep 2008 11:03:10 -0400 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <mailman.597.1220675617.3487.python-list@python.org> <00d23065$0$20302$c3e8da3@news.astraweb.com> Message-ID: <g9u633$6nt$1@aioe.org> Steven D'Aprano wrote: > On Sat, 06 Sep 2008 00:33:25 -0400, Manu Hack wrote: > >> Actually it's even more natural to state sum([x]) = x, and this way you >> can never conclude that sum([]) = 0 from there. > > But what you can say is that for any list L, sum(L) = sum(L + [0]). > > Therefore sum([]) = sum([] +[0]) = 0 Yep. The way it is preserves the distributive property sum(a+b) = sum(a) + sum(b) This would matter in cases like (untested code..) suvsales = sum (sum (s.price for s in d.sales if s.class='suv') for d in districts) Mel. From marco.bizzarri at gmail.com Thu Sep 4 06:06:14 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 12:06:14 +0200 Subject: overwrite set behavior In-Reply-To: <g9obgu$1if$1@inews.gazeta.pl> References: <g9oat3$veh$1@nnrp-beta.newsland.it> <g9obgu$1if$1@inews.gazeta.pl> Message-ID: <3f0d61c40809040306y1bb0960di47c672b9ece37a8e@mail.gmail.com> On Thu, Sep 4, 2008 at 11:58 AM, Wojtek Walczak <gminick at bzt.bzt> wrote: > On Thu, 04 Sep 2008 11:48:18 +0200, Michele Petrazzo wrote: >> Hi all, I want to modify the method that set use for see if there is >> already an object inside its obj-list. Something like this: > ... >> It's possible? > > As far as I understand you, you need descriptors: > http://users.rcn.com/python/download/Descriptor.htm > I know descriptors a litte, Wojtek, but didn't use them often; can you elaborate a little more on your idea? > -- > Regards, > Wojtek Walczak, > http://tosh.pl/gminick/ > -- > http://mail.python.org/mailman/listinfo/python-list > Saluti Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 22:47:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 02:47:11 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <gbkfhv$g2$1@panix3.panix.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <gblea5$os6$1@panix3.panix.com> <mailman.1600.1222551713.3487.python-list@python.org> Message-ID: <00eee9ec$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 17:41:42 -0400, Terry Reedy wrote: > In 3.0, at least, one does not need a disk file to create a module. > > >>> import types > >>> me = types.ModuleType('me') # type(__builtins__) works, no import > >>> me > <module 'me' (built-in)> > >>> me.a = 1 > >>> me.a > 1 > >>> me.a + 1 > 2 Seems to work for Python 2.5 as well. > That said, a blank class is even easier, and the representation is > better. And modules aren't callable. I've often thought they should be. -- Steven From bearophileHUGS at lycos.com Mon Sep 29 11:37:32 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 08:37:32 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <mailman.1662.1222661304.3487.python-list@python.org> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <ec4d192c-2a5d-4fb0-a68d-041ab4d15260@d70g2000hsc.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> Message-ID: <45c74b74-214c-4fed-b691-6020a1aedce6@a1g2000hsb.googlegroups.com> George Sakkis: > No difference in principle, just len() happens to be implemented more > often than upper(). That's an important point. In a language that tries to be both practical, readable, and elegant, the things that are done more may deserve some sugar, to avoid code like this in many cases: sorted(seq, key=lambda x:x.__len__()) Bye, bearophile From half.italian at gmail.com Tue Sep 30 01:02:17 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 29 Sep 2008 22:02:17 -0700 (PDT) Subject: python & sms References: <c7a65808-8f2a-458e-9590-514eebd5f64e@u65g2000hsc.googlegroups.com> Message-ID: <ac27508b-a0ce-4fbf-9fba-3b7fbbb1044a@k30g2000hse.googlegroups.com> On Sep 29, 8:47?pm, sui <gogtesuy... at gmail.com> wrote: > Hii > i want a script to send sms to any mobile..... > can u help me ?? > > Thanks in advance...... Must...be...smarter...than...cell...phone... From mensanator at aol.com Sat Sep 6 14:22:07 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Sep 2008 11:22:07 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <00d1f730$0$20302$c3e8da3@news.astraweb.com> Message-ID: <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> On Sep 5, 10:45?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Fri, 05 Sep 2008 22:20:06 -0400, Manu Hack wrote: > > On Fri, Sep 5, 2008 at 1:04 PM, castironpi <castiro... at gmail.com> wrote: <snip> > [The rest of this is (mostly) aimed at Mensanator, Ok, I see where you're coming from. > Fundamentally, the abstract function "sum" and the concrete Python > implementation of sum() are both human constructs. It's not like there is > some pure Platonic[1] "Ideal Sum" floating in space that we can refer to. > Somewhere, sometime, some mathematician had to *define* sum(), and other > mathematicians had to agree to use the same definition. > > They could have decided that sum must take at least two arguments, > because addition requires two arguments and it's meaningless to talk > about adding a single number without talking about adding it to something > else. But they didn't. Ok. But the problem is they DID in SQL: x + Null = Null. Earlier, you said that an empty box contains 0 widgets. Fine, empty means 0. But Null doesn't mean empty. Say your widget supplier just delivers a box and you haven't opened it yet. Is the box likely to be empty? Probably not, or they wouldn't have shipped it. In this case, Null means "unknown", not 0. The number of widgets you have on hand is Null (unknown) because inventory + Null = Null. SQL will correctly tell you that the amount on hand is unknown, whereas Python will tell you the amount on hand is inventory, which is incorrect. > Similarly, they might have decided that sum must > take at least one argument, and therefore prohibit sum([]), but they > didn't: it's more useful for sum of the empty list to give zero than it > is for it to be an error. As I mentioned earlier, mathematicians are > nothing if not pragmatists. > Here's a real world example (no ivory tower stuff): An oil refinery client has just excavated a big pile of dirt to lay a new pipeline. Due to the volume of the pipe, there's dirt left over. Ideally, the client would like to use that dirt as landfill (free), but it must be tested for HAPS (by summing the concentrations of organic constituents) to see whether it is considered hazardous waste, it which cas it must be taken off site and incinerated (costly). In MOST cases, a HAPS sum of 0 would be illegal because 0's generally cannot be reported in analytical tests, you can't report a result less than it's legal reporting limit. If ALL the consituents were undetected, the sum should be that of the sum of the reporting limits, thus, it cannot be 0. Can't I just use a sum of 0 to tell me when data is missing? No, because in some cases the reporting limit of undetected compounds is set to 0. In which case, a 0 HAPS score means we can confidently reccomend that the dirt is clean and can be freely reused. But if the analysis information is missing (hasn'r arrived yet or still pending validation) we WANT the result to be UNKNOWN so that we don't reccomend to the client that he take an illegal course of action. In this case, SQL does the correct thing and Python would return a false result. > -- > Steven From jpeyret at gmail.com Thu Sep 25 16:30:56 2008 From: jpeyret at gmail.com (J Peyret) Date: Thu, 25 Sep 2008 13:30:56 -0700 (PDT) Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <59a0d221-9f3b-4d9c-aa31-683eb615f3fd@i20g2000prf.googlegroups.com> On Sep 25, 12:24 pm, python-... at arcor.de wrote: > def whoisthethief("List" x): > return iknowit(x) > > def whoisthethief("String" x, "String" y): > return iknowit([x,y]) > I dunno if this is very Pythonic in nature, but I've done things like rebinding methods dynamically. ex: >>> def test(a): ... return a * 2 ... >>> print test(2) 4 >>> def test2(b): ... return b * 3 ... >>> test = test2 >>> print test(2) 6 In your case def myNewThiefIdentifier(x,y): return "Dunno" whoisthethief = myNewThiefIdentifier Which method would this affect (i.e. which 'whoisthethief')? I assume you could figure it out, given a match on the signature, but how much work would this require from the developer and the interpreter? (apologies in case Google Groups decide to multipost) From BjornSteinarFjeldPettersen at gmail.com Thu Sep 11 05:50:57 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Thu, 11 Sep 2008 02:50:57 -0700 (PDT) Subject: Is there a SOAP module that can do this...? References: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> <c6543cf6-aa50-439e-b60e-c012cdd28d10@y38g2000hsy.googlegroups.com> Message-ID: <ce910b1d-018e-4132-aeb5-b38e3f7c5c2f@e53g2000hsa.googlegroups.com> On Sep 10, 9:44?pm, Waldemar Osuch <waldemar.os... at gmail.com> wrote: > On Sep 10, 1:23?pm, thebjorn <BjornSteinarFjeldPetter... at gmail.com> > wrote:> I've been trying to use SOAPpy and ZSI (with and without the use of > > wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic > > server(?) in front of some enterprise java bean) and not having much > > luck. ?I got them to send me an example of what the bytes on the wire > > are supposed to look like (attached below), and I got it to "work" by > > going lo-tech: > > If you are willing to go low tech you can tryhttp://effbot.org/downloads/#elementsoap > > But before you do that try:https://fedorahosted.org/suds > It is actively maintained and holds a lot of promise. > In my testing it knew how to connect to Sharepoint as well > as WebLogic exposed services. > > Waldemar Thanks for the info Waldemar. I'm looking into suds now, but there's something I'm having trouble wrapping my head around (xml isn't my usual territory, so this is perhaps obvious to someone...) This is what suds tells me: >>> print client suds ( version=0.2.9 ) service ( InboundLegacyDataService ) prefixes: ns0 = "http://no/brreg/BReMS/WebService/services" methods (2): getInfo() submitMessage(xs:string cpaid, xs:string securityKey, xs:string message, ) types (4): submitMessage submitMessageResponse getInfo getInfoResponse The method I'm interested in is submitMessage and in particular the ``xs:string message`` parameter. I've been provided with three xsd files that I'm almost 100% sure defines the format of the xml in the message (it defines the JegerproveInn sub-structure), but it looks like that has to be wrapped in a SOAP:Envelope, including the <?xml..> declaration before being stuffed into the xs:string message parameter, before that in turn is wrapped in an env:Envelope... Am I on the right track? Another question: I'm assuming the xsd files can be used for more than documentation :-) I've found the w3schools "Introduction to XML Schema" which I'm starting to read right now, however I haven't been able to google up any Python<->xsd "thingy" that looked promising (since I'm not sure what I'm looking for, this might not be a big surprise ;-) Is there such a "thingy"? Bjorn From pydecker at gmail.com Fri Sep 5 14:35:05 2008 From: pydecker at gmail.com (Peter Decker) Date: Fri, 5 Sep 2008 13:35:05 -0500 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <6id2n6FpunpvU1@mid.uni-berlin.de> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> <mailman.565.1220627973.3487.python-list@python.org> <6id2n6FpunpvU1@mid.uni-berlin.de> Message-ID: <ca55a9900809051135k51108278k26cacb7d3cca7f12@mail.gmail.com> On Fri, Sep 5, 2008 at 10:48 AM, Diez B. Roggisch <deets at nospam.web.de> wrote: > You got me wrong. I didn't say it doesn't use the native toolkit under > various OSes, I'm well aware of that it does. > > What I *did* say was that wx API is designed primarily with windows' toolkit > as base, and as a consequence the API tends to be less functional for other > toolkits, making it harder to work with it. As the OP was after a "one API > to rule them all" for GUIs, I pointed that out. > > See for example this (arguably somewhat dated) post that illustrates my > point: > > http://mail.python.org/pipermail/python-list/2005-March/313354.html OK, that's a little clearer. That's one of the things that I like about Dabo - it gets rid of the ugly (IMO) wxPython API and replaces it with a much more consistent (and, IMO) more Pythonic API. I hated coding in wx, but I love coding in Dabo. -- # p.d. From mark at thomaszone.com Fri Sep 26 12:54:04 2008 From: mark at thomaszone.com (Mark Thomas) Date: Fri, 26 Sep 2008 09:54:04 -0700 (PDT) Subject: lxml question References: <2f9ef7d5-616e-4a4b-9a83-e23194fee3a9@m3g2000hsc.googlegroups.com> Message-ID: <54d641a7-a07e-4eec-b20f-5f675405672f@e39g2000hsf.googlegroups.com> On Sep 26, 11:19?am, Uwe Schmitt <rocksportroc... at googlemail.com> wrote: > I have to parse some text which pretends to be XML. lxml does not want > to parse it, because it lacks a root element. > I think that this situation is not unusual, so: is there a way to > force lxml to parse it ? By "pretends to be XML" you mean XML-like but not really XML? > My work around is wrapping the text with "<root>...</root>" before > feeding lxmls parser. That's actually not a bad solution, if you know that the document is otherwise well-formed. Another thing you can do is use libxml2's "recover" mode which accommodates non-well-formed XML. parser = etree.XMLParser(recover=True) tree = etree.XML(your_xml_string, parser) You'll still need to use your wrapper root element, because recover mode will ignore everything after the first root closes (and it won't throw an error). -- Mark. From google at mrabarnett.plus.com Thu Sep 11 11:36:28 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Sep 2008 08:36:28 -0700 (PDT) Subject: emulating read and readline methods References: <ee4202f1-ce8f-458e-9627-08215351694d@e53g2000hsa.googlegroups.com> <e1941052-a524-477e-b498-521f52ea2b92@25g2000hsx.googlegroups.com> <ba72b905-d5b8-4e8c-9ef7-252c9e51a48d@a2g2000prm.googlegroups.com> <0d961161-3789-46c3-8018-06b26af7f767@x35g2000hsb.googlegroups.com> Message-ID: <a8c50843-4719-4d45-9f13-d2312f158590@2g2000hsn.googlegroups.com> On Sep 11, 9:23?am, Sean Davis <seand... at gmail.com> wrote: > On Sep 10, 7:54?pm, John Machin <sjmac... at lexicon.net> wrote: > > > > > On Sep 11, 8:01?am, MRAB <goo... at mrabarnett.plus.com> wrote: > > > > On Sep 10, 6:59?pm, Sean Davis <seand... at gmail.com> wrote: > > > > > I have a large file that I would like to transform and then feed to a > > > > function (psycopg2 copy_from) that expects a file-like object (needs > > > > read and readline methods). > > > > > I have a class like so: > > > > > class GeneInfo(): > > > > ? ? def __init__(self): > > > > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > > > > gene_info.gz',"/tmp/gene_info.gz") > > > > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > > > > ? ? ? ? self.fh.readline() #deal with header line > > > > > ? ? def _read(self,n=1): > > > > ? ? ? ? for line in self.fh: > > > > ? ? ? ? ? ? if line=='': > > > > ? ? ? ? ? ? ? ? break > > > > ? ? ? ? ? ? line=line.strip() > > > > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > > > > ? ? ? ? ? ? rowvals = line.split("\t") > > > > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > > > > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > > > > ? ? def readline(self,n=1): > > > > ? ? ? ? return self._read().next() > > > > > ? ? def read(self,n=1): > > > > ? ? ? ? return self._read().next() > > > > Each time readline() and read() call self._read() they are creating a > > > new generator. They then get one value from the newly-created > > > generator and then discard that generator. What you should do is > > > create the generator in __init__ and then use it in readline() and > > > read(). > > > > > ? ? def close(self): > > > > ? ? ? ? self.fh.close() > > > > > and I use it like so: > > > > > a=GeneInfo() > > > > cur.copy_from(a,"gene_info") > > > > a.close() > > > > > It works well except that the end of file is not caught by copy_from. > > > > I get errors like: > > > > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > > > > during .read() call > > > > CONTEXT: ?COPY gene_info, line 1000: "" > > > > > for a 1000 line test file. ?Any ideas what is going on? > > > > I wonder whether it's expecting readline() and read() to return an > > > empty string at the end of the file instead of raising StopIteration. > > > Don't wonder; ReadTheFantasticManual: > > > read( [size]) > > > ... An empty string is returned when EOF is encountered > > immediately. ... > > > readline( [size]) > > > ?... An empty string is returned only when EOF is encountered > > immediately. > > Thanks. ?This was indeed my problem--not reading the manual closely > enough. > > And the points about the iterator being re-instantiated were also > right on point. ?Interestingly, in this case, the code was working > because read() and readline() were still returning the next line each > time since the file handle was being read one line at a time. > After further thought, do you actually need a generator? read() and readline() could just call _read(), which would read a line from the file and return the result or an empty string. Or the processing could be done in readline() and read() just could call readline(). From brtzsnr at gmail.com Fri Sep 5 05:46:56 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Fri, 5 Sep 2008 02:46:56 -0700 (PDT) Subject: derived classes and __getattr__ References: <d5a86bf2-2b8c-487f-9097-51bc92ef478d@w24g2000prd.googlegroups.com> <g9qrmh$k62$02$1@news.t-online.com> Message-ID: <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> On Sep 5, 11:47?am, Peter Otten <__pete... at web.de> wrote: > Alexandru Mo?oi wrote: > > i'm facing the following problem: > > > class Base(object): > > ? def __getattr__(self, attr): return lambda x: attr + '_' + x > > > def dec(callable): > > ? return lambda *args: 'dec_' + callable(*args) > > > class Derived(Base): > > ? ?what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have > > what_so_ever > > ? ?mumu = dec(Base.mumu) ? ? ? ? ? ? ? ? ? ? ? ? ?# wrong, base > > doesn't have mumu > > > any idea how to do this? > > __getattr__() is defined in the class to create instance attributes on the > fly. If you want class attributes you have to put the __getattr__() method > into the class of the class, or "metaclass": > > class Base(object): > ? ? class __metaclass__(type): > ? ? ? ? def __getattr__(self, attr): > ? ? ? ? ? ? return lambda self, x: attr + '_' + x > > def dec(callable): > ? ? return lambda *args: 'dec_' + callable(*args) > > class Derived(Base): > ? ?what_so_ever = dec(Base.what_so_ever) > > d = Derived() > print d.what_so_ever("42") > > I don't see how you can turn this into something useful... > > Peter 10x. it works. however I have another small problem. now, d.third('blah') doesn't work because instance d doesn't have 'third' attribute. I was expecting derived class to inherit the metaclass as well, but it didn't. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 8 09:46:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Sep 2008 15:46:57 +0200 Subject: Dictionaries and loops In-Reply-To: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> References: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> Message-ID: <48c52c54$0$16982$426a74cc@news.free.fr> Mike P a ?crit : > Hi All > i have a CSV file that i'm reading in and each line has the look of > the below > > {None: ['User-ID', 'Count']} > {None: ['576460847178667334', '1']} > {None: ['576460847178632334', '8']} This doesn't look like a CSV file at all... Is that what you actually have in the file, or what you get from the csv.reader ??? > i want to make a dictionary of items in the form > {576460847178667334:1, 576460847178632334:8, ..... } for all rows in > the datafile > > my code so far is thus: > > dict1={} > j=1 > for row in reader1: > if j==1: > j+=1 > continue #thus allowing me to skip the first row > if j>1: Drop this, and call reader1.next() before entering the loop. > for element in row.values(): > for item in element: > if int(item)%2==0: > dict1[int(item)] = int(item)+1 You're repeating the same operation (building an int from a string) three time, where one would be enough: for item in element: item = int(item) if item %2 == 0: # or : if not item % 2: dict1[item] = item + 1 But this code is not going to yield the expected result... > # i know this is the problem line as it's not picking the second item > up just finding the first and increasing it, but i can't figure out > how to correct this? Mmm... What about learning Python instead of trying any random code ? Programming by accident won't take you very far, and you can't expect this neswgroup to do your own work. Ok, assuming your CSV file looks like this - and you never have duplicate values for the User-id column: # source.csv "User-ID", "Count" 576460847178667334, 1 576460847178632334, 8' Here's a possible solution: result = {} src = open("source.csv", "rb") try: reader = csv.reader(src) reader.next() for row in reader: user_id, count = int(row[0]), int(row[1]) result[user_id] = count finally: src.close() or more tersely: src = open("source.csv", "rb") try: reader = csv.reader(src) reader.next() result = dict(map(int, row) for row in reader) finally: src.close() From castironpi at gmail.com Wed Sep 17 19:45:40 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 17 Sep 2008 16:45:40 -0700 (PDT) Subject: decorator and API References: <mailman.1183.1221688957.3487.python-list@python.org> <160e332b-3b46-4a9f-957b-0eb8199ed3d7@8g2000hse.googlegroups.com> Message-ID: <e1b089e4-13f9-40cd-b5ff-98ffed5d036a@d45g2000hsc.googlegroups.com> On Sep 17, 6:09?pm, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 17, 4:56?pm, Lee Harr <miss... at hotmail.com> wrote: > > > > > I have a class with certain methods from which I want to select > > one at random, with weighting. (snip) > > > The problem I have now is that if I subclass A and want to > > change the weighting of one of the methods, I am not sure > > how to do that. > > > One idea I had was to override the method using the new > > weight in the decorator, and then call the original method: > > > class B(A): > > ? ? @weight(50) > > ? ? def action_1(self): > > ? ? ? ? A.action_1(self) > > > That works, but it feels messy. > > > Another idea was to store the weightings as a dictionary > > on each instance, but I could not see how to update that > > from a decorator. > > > I like the idea of having the weights in a dictionary, so I > > am looking for a better API, or a way to re-weight the > > methods using a decorator. > > > Any suggestions appreciated. > > class A: > ? ?weights= WeightOb() #just a dictionary, mostly > ? ?@weights( 10 ) ... > ? ?@weights( 20 ) ... > > class B( A ): > ? ?weights= WeightOb( A.weights ) #new, refs "super-member" > ? ?@weights( 50 ) ... Lee, Probably overkill. Here's a solution like above. class WeightOb( object ): def __init__( self, *supers ): self.weights= {} self.supers= supers def set( self, weight ): def __callset__( fun ): self.weights[ fun.func_name ]= weight return fun return __callset__ def reset( self, weight, fun ): self.weights[ fun.func_name ]= weight return fun #search parent 'weight' objects #return 'child-most' weight of 'name' def get_weight( self, name ): if name in self.weights: return self.weights[ name ] else: for x in self.supers: try: return x.get_weight( name ) except KeyError: #not found pass raise KeyError #returns a dictionary mapping bound instances to weights #(hence the second parameter) def contents( self, inst ): d= {} for x in reversed( self.supers ): d.update( x.contents( inst ) ) d.update( dict( [ ( getattr( inst, k ), v ) for k, v in self.weights.iteritems( ) ] ) ) return d class A( object ): weights= WeightOb( ) @weights.set( 10 ) def action_1( self ): print 'action_1' @weights.set( 20 ) def action_2( self ): print 'action_2' #WeightOb.contents needs to know which instance to bind #functions to. Get weights from an instance that has them. def getweights( self ): return self.weights.contents( self ) class B( A ): weights= WeightOb( A.weights ) action_2= weights.reset( 50, A.action_2 ) a= A() b= B() print a.weights.get_weight( 'action_1' ) print a.weights.get_weight( 'action_2' ) print b.weights.get_weight( 'action_1' ) print b.weights.get_weight( 'action_2' ) print a.getweights( ) print b.getweights( ) /Output: 10 20 10 50 {<bound method A.action_2 of <__main__.A object at 0x00A04070>>: 20, <bound meth od A.action_1 of <__main__.A object at 0x00A04070>>: 10} {<bound method B.action_2 of <__main__.B object at 0x00A04090>>: 50, <bound meth od B.action_1 of <__main__.B object at 0x00A04090>>: 10} From skip at pobox.com Tue Sep 9 09:23:11 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 Sep 2008 08:23:11 -0500 Subject: creating an (inefficent) alternating regular expression from a list of options In-Reply-To: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: <18630.30911.707343.588287@montanaro-dyndns-org.local> >> I really dont care if the expression is optimal. So the goal is >> something like: >> vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| >> u|ii|i)' >> Is there a public module available for this purpose? Check Ka-Ping Yee's rxb module: http://lfw.org/python/ Needs translating from the old regex module to the current re module, but it shouldn't take a lot of effort. You can find regex docs in old distributions (probably through 2.1 or 2.2?). Also, check PyPI to see if someone has already updated rxb for use with re. Skip From simon.palmer at gmail.com Wed Sep 3 17:59:44 2008 From: simon.palmer at gmail.com (SimonPalmer) Date: Wed, 3 Sep 2008 14:59:44 -0700 (PDT) Subject: Python on the web - newby question References: <6822d749-cc00-48ce-a30a-ded96a938e79@b30g2000prf.googlegroups.com> <48bf0459$0$27459$426a74cc@news.free.fr> Message-ID: <f460a507-1ac6-4d30-966e-5347a768a640@s1g2000pra.googlegroups.com> On Sep 3, 8:41?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > SimonPalmer a ?crit : > > > Apologies in advance if this is either a) the wrong board or b) been > > answered a million times elsewhere, but... > > > I have been given an assignment to get a python module up and running > > behind an existing web site. ?At the moment the rest of the site is > > developed in PHP but the hosts have said they will provide python > > support for free, although they haven't given any more details than > > that, so I'm not sure exactly what that means. > > Depending on the hosts, this can range from having an antiquated python > version with only cgi enabled and no way to install anything to the very > last stable release and (almost) whatever third-part lib / frameworks > and correct configuration. > > > ?All reasonably > > encouraging though. > > > I'm a newbie to python but quite experienced with Java/J2EE/JBoss. > > Quite another world... > > > What I need to know is how I get python running on the server > > For which definition of 'server' ? The computer, or the web server process ? > > > and what > > tools/middleware I would need to have installed on the host's machines > > to be able to support my python modules. > > Depends on your modules dependencies !-) > > More seriously : Python is known has being the language with more web > frameworks than keywords. IOW, there's no simple straightforward answer > to your question. Fisrt choose which Python web development solution you > intend to use, then read the FineManual's "deployment" section of the > chosen solution. > > You'll find pointers to most web-related libs / frameworks here:http://wiki.python.org/moin/WebFrameworkshttp://wiki.python.org/moin/WebProgramming > > Given your situation (Python newcomer with a real job to do), and if > your job is anything more than a very Q&D deadsimple task, I'd > personnaly recommand Django (http://djangiproject.com). Don't let the > version number fools you (latest version is 1.0 release candidate), > Django is a mature, solid and proven solution that have years of > existance, and what they call 1.0rc would be labeled at least 3.5 for > some other software... It's also mostly documented, and there's a strong > community around the framework, so you should not have much problem > getting help. > > For any other Python question (I mean, non django-related), you're at > the right place. > > Oh, and yes, if I may suggest a reading:http://dirtsimple.org/2004/12/python-is-not-java.html > > HTH, and welcome on board... Hey, thanks very much this is really helpful. What I really need is pointers, I'm sure I can figure the rest out. I am indeed a guy with a real job to do. Doesn't help that the client and host are on the other side of the world. I quite like python. As a veteran coder who has tried a lot of languages this has been a pleasant experience so far. I *really* like numpy and scipy. My stock in trade is algorithms and they are quite a revelation. I wish I had known about them sooner and I think they will keep me coming back to python regularly. Thanks again. SP From nishalrs at yahoo.co.uk Mon Sep 29 09:00:19 2008 From: nishalrs at yahoo.co.uk (nishalrs) Date: Mon, 29 Sep 2008 13:00:19 -0000 Subject: writing dll in python? Message-ID: <gbqjh3+39e0@eGroups.com> Hello All, My main motivation is to build a collection of useful mathematical models (that I have developed over the years) to design ultrasonic sensors. This should be some sort of a library that should be able to be used for desktop/web application development, to run in variety of operating systems. I am more than convinced after looking at python.org website, it is the right tool for the job. I intend to learn python, but I am not really sure, where to begin. Should I write all the functions as simple python scripts? Or is there some facility for creating a .dll like library, that could be more suitable for what in intend to develop? Any help is much appreciated. Regards, Nishal From skip at pobox.com Fri Sep 26 19:27:11 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 26 Sep 2008 18:27:11 -0500 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <4b195687-e4a5-4fdd-89b2-f3906e625770@j22g2000hsf.googlegroups.com> References: <mailman.1533.1222428711.3487.python-list@python.org> <4b195687-e4a5-4fdd-89b2-f3906e625770@j22g2000hsf.googlegroups.com> Message-ID: <18653.28623.732020.288418@montanaro-dyndns-org.local> Aaron> Is there such a thing as an open-source spam filter? That way Aaron> any time anyone had spare time and got annoyed, they could dump a Aaron> short snippet of code into the grinder. Yes: <http://spambayes.sf.net/> though I think your model of how it works probably needs a bit of refinement. <wink> You might want to read through the background reading page: <http://spambayes.sf.net/background.html>. It's what we're running on the python.org site. The initial impetus for it came from a desire to filter spam for python.org mailing lists. If you'd like to contribute we can always use developers. Skip From emile at fenx.com Fri Sep 12 13:43:08 2008 From: emile at fenx.com (Emile van Sebille) Date: Fri, 12 Sep 2008 10:43:08 -0700 Subject: manipulating files within 'for' In-Reply-To: <48CAA2AA.40809@umbc.edu> References: <48CAA2AA.40809@umbc.edu> Message-ID: <gae9jj$sks$1@ger.gmane.org> Ben Keshet wrote: > Hi Pythoneers, > > I have a question about a code I wrote with the help of someone. The > code below copy a few lines from different files into one file. It works > fine as it is given here and generates the new file 'pockets.out' > correctly, but says:"....py returned exit code 0". However, if I add > more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) At risk of stating the obvious, you _did_ put this in properly as receptors = ['1AZM', '1ADS'] ...right? Emile it gives an > error: "Exception raised while running script". > > Can anyone please advice me? Why is it giving an error on multiple x but > runs well with one (I made sure that all files and folders exist, etc.). > What does exit code 0 mean? No error > what does "exception raised" mean? Error From ggpolo at gmail.com Sat Sep 20 16:37:06 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 20 Sep 2008 17:37:06 -0300 Subject: [Tkinter-discuss] (newbie) can't invoke button for twice In-Reply-To: <19588292.post@talk.nabble.com> References: <19588292.post@talk.nabble.com> Message-ID: <ac2200130809201337h3d9ac853y35b667e5b2b8c3dc@mail.gmail.com> On Sat, Sep 20, 2008 at 4:10 PM, dmitrey <dmitrey15 at ukr.net> wrote: > > hi all, > I have the problem: > a func has been binded to a Button: > > RunPause = Button(root, textvariable = t, command = lambda: > invokeRunPause(p)) > > def invokeRunPause(p): > if p.state == 'init': > p.state = 'running' > t.set(' Pause ') > p.GUI_root.update_idletasks() > p.tmp_result = p.solve(*p._args, **p._kwargs) > > elif p.state == 'running': > .... > So the problem is that I can't invoke the button RunPause till my > calculations (in p.solve()) will be finished. I can observe it even > graphically, the button doesn't respond when it is pressed. > Could anyone provide a solution? It is not only the button that doesn't respond, the entire application won't respond if you are blocking tcl from processing anything. This call to p.solve blocks, and, in turn the interpreter can't process events and the GUI remains frozen till p.solve returns. Ideally you should break this p.solve in steps, so you can schedule next steps and the GUI will remain responsible, but if you can't break it, and if it doesn't make sense to run it in another process then you use a thread to solve this. > > Thank you ion advance, Dmitrey. > -- > View this message in context: http://www.nabble.com/%28newbie%29-can%27t-invoke-button-for-twice-tp19588292p19588292.html > Sent from the Python - tkinter-discuss mailing list archive at Nabble.com. > > _______________________________________________ > Tkinter-discuss mailing list > Tkinter-discuss at python.org > http://mail.python.org/mailman/listinfo/tkinter-discuss > -- -- Guilherme H. Polo Goncalves From Lie.1296 at gmail.com Sun Sep 28 17:19:15 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 14:19:15 -0700 (PDT) Subject: Why are "broken iterators" broken? References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: <039352a3-45ce-4784-8ff2-244ed6953cd4@p31g2000prf.googlegroups.com> On Sep 21, 10:13?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > According to the Python docs, once an iterator raises StopIteration, it > should continue to raise StopIteration forever. Iterators that fail to > behave in this fashion are deemed to be "broken": > > http://docs.python.org/lib/typeiter.html > > I don't understand the reasoning behind this. As I understand it, an > iterator is something like a stream. There's no constraint that once a > stream is empty it must remain empty forever. I think empty != StopIteration. StopIteration (IMHO) shouldn't be raised when the stream is empty, instead a sentinel value specifying that "there is no data yet, but if you wait there might be" should be returned (possibly None or empty string). When you raise StopIteration, it is a signal that I don't have any more data and there is no use in waiting. > Can somebody explain why "broken iterators" are broken? > > -- > Steven From tino at wildenhain.de Sat Sep 27 10:14:31 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 27 Sep 2008 16:14:31 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> Message-ID: <48DE3FC7.4030307@wildenhain.de> Hi, Michael Mabin wrote: > so you wouldn't object then to something like > > '.... in (%)' % ','.join([str_edit_for_exploit(x) for x in aList]) > > if str_edit_for_exploit applied security edits? Whats an security edit btw? If it is something meant to turn possibly insecure data into 'secure' then, no I would still object. Why? Because its a bad example of "default permit". Its always better to have a whitelist - even more so when its so easy to do. Its just a habit you develope - if you never do it right, how would you know when and how to do it right when you need to? Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080927/1b1daf92/attachment.bin> From timr at probo.com Thu Sep 25 02:39:24 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Sep 2008 06:39:24 GMT Subject: curses.setsyx()? References: <f4bfa060-3053-4ca6-90c2-2a057bfedf79@34g2000hsh.googlegroups.com> <tqd6d4po3dmvba3a3v1a8c2b34qgfmc8d9@4ax.com> <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> <naogd45497jn4s8jegu15j4u1oo49cinqc@4ax.com> <713190fc-e3a9-4a72-8bee-4fd3affcb531@c58g2000hsc.googlegroups.com> <ea23fc87-feb5-4853-bf0f-58e69b890af7@t54g2000hsg.googlegroups.com> Message-ID: <5acmd4t7p44cbgi1fkmhaaasfplv0jaatr@4ax.com> linkmaster032000 at gmail.com wrote: >On Sep 23, 4:16?pm, brad.at.sch... at gmail.com wrote: >> On Sep 22, 11:24?pm, Tim Roberts <t... at probo.com> wrote: >> > linkmaster032... at gmail.com wrote: >> > >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: >> > >> On Sep 19, 1:24?am, Tim Roberts <t... at probo.com> wrote: >> >> > >> > linkmaster032... at gmail.com wrote: >> >> > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses >> > >> > >cursor. Any alternatives/solutions? >>... >> > >> I added it and it still doesn't work. This is what I'm doing when I >> > >> want to display the cursor and prepare it for input at 2,3: >> >> > >> curses.echo() >> > >> curses.curs_set(1) >> > >> curses.setsyx(2,3) >> > >> curses.doupdate() >> >> > >Any idea what's wrong? >> >> http://pastebin.com/m6413db1 >> >> Run that and press 'n' key. It is supposed to move the cursor to 2,3 >> and it doesn't. Of course it does. It moves the cursor, then does an update, then immediately calls draw.game, which redraws the screen and moves the cursor. If you want curses.setsyx (or the equivalent and more mnemonic scr.move) to leave the cursor somewhere, you can't draw more text afterward. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From digitig at gmail.com Mon Sep 22 09:45:20 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 22 Sep 2008 14:45:20 +0100 Subject: What do you call a class not intended to be instantiated In-Reply-To: <48d78c3c$0$6998$426a74cc@news.free.fr> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> <48d78c3c$0$6998$426a74cc@news.free.fr> Message-ID: <aee48b3c0809220645s6bf8ac24n373aa726358b211a@mail.gmail.com> 2008/9/22 Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid>: >> Sounds to me like a functor, aka a function object: >> http://en.wikipedia.org/wiki/Function_object >> > > Ok, then the simple solution is to implement a callable type (__call__ > method), possibly with appropriate support for the descriptor protocol if > it's meant to be usable as a method. Yes -- and instantiate the thing and keep the state in the instance, rather than keeping the state in the class, so that it's possible to safely have more than one of them if a later design change calls for it (probably what led people off onto the sidetrack of thinking a singleton was called for). That's the classic way of implementing a "class [to be] used as a function". -- Tim Rowe From castironpi at gmail.com Wed Sep 24 15:45:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 12:45:41 -0700 (PDT) Subject: PyRun_SimpleFile() crashes References: <d71e6607-31ca-48a6-b61f-040536a7cebf@g17g2000prg.googlegroups.com> <slrngdk68l.fu2.nick@irishsea.home.craig-wood.com> <26532f88-b70c-4b18-af4d-5176ec023f46@c65g2000hsa.googlegroups.com> Message-ID: <2facaea6-3a54-45e6-86e8-a0aee9a90522@m73g2000hsh.googlegroups.com> On Sep 24, 11:05?am, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 24, 6:30?am, Nick Craig-Wood <n... at craig-wood.com> wrote: > > > > > lixinyi... at gmail.com <lixinyi... at gmail.com> wrote: > > > ?my code: > > > ?main.cpp > > > ?#include <Python.h> > > > > ?int main(int argc, char **argv) > > > ?{ > > > ?Py_Initialize(); > > > > ?FILE *file_1 = fopen("a2l_reader.py","r+"); > > > ?PyRun_SimpleFile(file_1,"a2l_reader.py"); > > > > ?Py_Finalize(); > > > ?} > > > > ?compile under windows using MinGW: > > > ?g++ main.cpp libpython25.a -o a > > > > ?no error was found. But when I run a.exe the program just crashes. > > > > ?What should I do? > > > Run it under gdb (which should have come with MinGW). > > > Check that you actually opened the file, ie file_1 != 0. > > > This might be relevant > > > ?http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o... > > > -- > > Nick Craig-Wood <n... at craig-wood.com> --http://www.craig-wood.com/nick > > There's a workaround. > > filename = "Entire path of the python file"; > PyObject* PyFileObject = PyFile_FromString(filename, "r"); > PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename); > // decref PyFileObject > > http://mail.python.org/pipermail/python-list/2007-March/431725.htmlhttp://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567 Just to follow up-- The links say that the crash comes from opening a file with two different versions of a library. Would it be possible to get an API entry point to the version the build uses? It does use the 'fopen' function by name, but not the same version. And creating the entire object just to get its f_fp field is really long. From pavlovevidence at gmail.com Wed Sep 24 05:53:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 24 Sep 2008 02:53:48 -0700 (PDT) Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> Message-ID: <84668bf4-a8d9-4140-b405-63d82d4f85ce@c65g2000hsa.googlegroups.com> On Sep 22, 4:02?am, Al Kabaila <akaba... at pcug.org.au> wrote: > 1. Is there any interest in matrix algebra "for the masses" (I mean interest > in a wrapper for a subset of functions of the packages with a unified > simple syntax)? I wouldn't since I do pretty advanced stuff and I'm happy to use numpy as-is, but I suspect a lot of people would find a convenient basic matrix library useful. > 2. What other matrix operations would be required for your area of interest? Your short list covers most of the important stuff. Graphics and simulation make use of rigid transformations a lot (composition of rotations and stuff). It's pretty straightforward and specialized so I'd give it low priority. I use linear least squares (psuedoinverse) occasionally for curve- fitting. > 3. What other matrix packages, if any, should one include in the wrapper? Oftentimes libraries like this have a dumb implementation, that uses only the basic machinery that ships with every system. You might consider such an implementation of your API that uses only Python lists or arrays. One matrix API that is pretty irritating is Blender's; in fact whenever I write Blender plugins I usually do all the dirty work with numpy. Carl Banks From pavlovevidence at gmail.com Sat Sep 13 01:08:14 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 12 Sep 2008 22:08:14 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? References: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> Message-ID: <12aaddbd-6589-409e-b6d3-b06eda7f4cab@a3g2000prm.googlegroups.com> On Sep 12, 9:08?pm, i... at illusorygoals.com wrote: > First off, I'm a python n00b, so feel free to comment on anything if > I'm doing it "the wrong way." I'm building a discrete event simulation > tool. I wanted to use coroutines. However, I want to know if there's > any way to hide a yield statement. > > I have a class that I'd like to look like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? result = self.ping("128.111.41.38") > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > But because I can't hide yield inside ping, and because I can't find a > convenient way to get a self reference to the coroutine (which is used > by the event queue to pass back results), my code looks like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? # I dislike this next line > ? ? ? ? self.this_pointer = (yield None) > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? # I want to get rid of the yield in the next line > ? ? ? ? ? ? result = (yield self.ping("128.111.41.38")) > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > I'd like to know, is there a way to get the syntax I want? I think you're stuck with using threads in a standard Python release. Generators can't serve as coroutines when you're yielding from a nested call (they only go one level deep). You can get coroutines with Stackless Python, a non-standard version of Python. But even with Stackless I got the impression that you'd be building coroutines atop something that was fairly thread-like. There is no coroutine syntax. Carl Banks From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 02:48:33 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Mon, 15 Sep 2008 23:48:33 -0700 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: <mailman.1040.1221484013.3487.python-list@python.org> References: <a3158e8b0809142323t2a2d2c7dm8bb65482e25a1d1@mail.gmail.com> <mailman.1040.1221484013.3487.python-list@python.org> Message-ID: <48CF56C1.50208@comcast.net> > On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal <uzmanajmal at gmail.com> wrote: >> I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that >> key as string. Is there any way to convert the said instance into string? Take a look at as_pem() method. -- Heikki Toivonen From jepe_abrantes at hotmail.com Mon Sep 15 07:02:58 2008 From: jepe_abrantes at hotmail.com (=?iso-8859-1?Q?Jo=E3o_Abrantes?=) Date: Mon, 15 Sep 2008 11:02:58 +0000 Subject: how to protect the source Message-ID: <BLU115-W513E8E918A8A16CEB298E596520@phx.gbl> Hello Everyone. I am building a client in python that will connect himself to a mysql server with a certain username and password. I will compile this client and turn him into a .exe . The thing is that I know that is possible to get the source of the code back from an .exe and I don't want anyone to know which username and password are they using because I don't want them to access to the mysql server without my client. Do you have any ideas of what can i do? Thanks! _________________________________________________________________ Connect to the next generation of MSN Messenger? http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/b44c0b51/attachment.html> From m_palmer45 at yahoo.ca Wed Sep 3 15:29:53 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 3 Sep 2008 12:29:53 -0700 (PDT) Subject: Help needed to freeze a script. References: <7f364174-75c6-4120-b00e-6f41643ccbf5@z72g2000hsb.googlegroups.com> Message-ID: <614c7366-ba7e-4296-a4f0-a32accaa427a@b38g2000prf.googlegroups.com> On Sep 3, 1:30 pm, LB <berthe.l... at gmail.com> wrote: > Hi, > > I would like to freeze a numpy based script in order to have an > application which could run without having to install numpy and cie. > > Indeed, I'm not root on the targeted computer and I can't easily > make a complete install of numpy and scipy. > > So I decided to test the freeze.py tool shipped with python2.5. > To complicate matters, I must say that I only have a local > installation > of python2.5 and numpy. > > I used the following command line : > > > python2.5 ../Python-2.5.1/Tools/freeze/freeze.py ~/Python/numpy/test_freeze.py > > At first sight, it seems to be fine, as I saw numpy in the liste of > frozen dependancies : > [...] > freezing numpy ... > freezing numpy.__config__ ... > freezing numpy._import_tools ... > freezing numpy.add_newdocs ... > freezing numpy.core ... > freezing numpy.core._internal ... > freezing numpy.core.arrayprint ... > freezing numpy.core.defchararray ... > freezing numpy.core.defmatrix ... > freezing numpy.core.fromnumeric ... > freezing numpy.core.info ... > freezing numpy.core.memmap ... > freezing numpy.core.numeric ... > freezing numpy.core.numerictypes ... > freezing numpy.core.records ... > freezing numpy.ctypeslib ... > [...] > freezing numpy.version ... > > But at the end I saw this message : > Warning: unknown modules remain: _bisect _csv _ctypes _curses _hashlib > _heapq > [...] > numpy.core._dotblas numpy.core._sort numpy.core.multiarray > numpy.core.scalarmath numpy.core.umath numpy.fft.fftpack_lite > numpy.lib._compiled_base numpy.linalg.lapack_lite numpy.random.mtrand > operator parser pyexpat readline > [...] > Now run "make" to build the target: test_weibull > > I runned make without any problem but the final application didn't > work : > % ./test_freeze > Traceback (most recent call last): > File "/home/loic/Python/numpy/test_freeze.py", line 8, in <module> > import numpy as np > [...] > File "/home/loic/tmp/bluelagoon/lib/python2.5/site-packages/numpy/ > core/__init__.py", line 5, in <module> > import multiarray > ImportError: No module named multiarray > > Is there any known issue when freezing a numpy based script ? > I should add that I configured my PYTHONPATH to match my local > installation > > echo $PYTHONPATH > /home/loic/lib/python:/home/loic/tmp/bluelagoon/lib/python2.5:/home/ > loic/tmp/bluelagoon/lib/python2.5/site-packages/: > > and this local installation work fine : > > > python2.5 -c 'import numpy; print numpy.__version__; import numpy.core.multiarray; print "no pb"' > > 1.2.0b2 > no pb > > Have you got any recipe to freeze numpy based script ? > > Regards, > > -- > LB Did you try py2exe instead of freeze? On the page http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules there is only one brief mention of numpy packaging troubles, suggesting that it might work better. I have used py2exe in the past without much trouble. From mhuening at zedat.fu-berlin.de Wed Sep 10 10:11:40 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Wed, 10 Sep 2008 16:11:40 +0200 Subject: PHP's str_replace ? In-Reply-To: <6iq2jpFs113rU1@mid.uni-berlin.de> References: <mailman.788.1221054649.3487.python-list@python.org> <6iq2jpFs113rU1@mid.uni-berlin.de> Message-ID: <6iq2sbFs113rU2@mid.uni-berlin.de> Matthias Huening (10.09.2008 16:07): > Anjanesh Lekshminarayanan (10.09.2008 15:50): >> In PHP, if I do >> str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) >> it'll replace all vowels with a hyphen in string $str. >> >> Is there some equivalent in Python ? > > What about something like this: > > import re > new_str = re.sub('([aeiou])-', r'\1', str) > Sorry - I misinterpreted your question. Try this instead: import re new_str = re.sub('[aeiou]', '-', str) matthias From agostino.russo at gmail.com Tue Sep 9 14:55:30 2008 From: agostino.russo at gmail.com (ago) Date: Tue, 9 Sep 2008 11:55:30 -0700 (PDT) Subject: PYTHONSITEDIR environment variable References: <eccd24ff-001b-4f4e-a9da-c7052d67383d@k30g2000hse.googlegroups.com> <mailman.744.1220982999.3487.python-list@python.org> <e3f06a84-5888-462c-87df-1dfba494362a@2g2000hsn.googlegroups.com> <mailman.747.1220985923.3487.python-list@python.org> Message-ID: <6e024b6a-c86c-4690-ad86-951c8118e3fd@m45g2000hsb.googlegroups.com> On Sep 9, 7:45?pm, Christian Heimes <li... at cheimes.de> wrote: > ago wrote: > > The only thing I would add is that in my experience I often use > > different working-envs for different projects, so I'd prefer to have a > > more generic solution as opposed to a single working-env per user. The > > latter could still be achieved by setting the appropriate environment > > variable in the user profile. Do you think it would be possible to > > accommodate for the above in your PEP? > > Isn't PYTHONUSERBASE sufficient for your needs? The env var alters the > base directory. > > I can neither change the PEP nor the implementation at this stage of the > development cycle. Python 2.6 and 3.0 are in beta and the API is set in > stone. > > Christian I had missed that, yes I think that PYTHONUSERBASE will do fine! It might be useful though to be able to skip other system site dirs altogether so that only local site packages are used, as in the second patch I sent (see PYTHONNOSYSSITES). Thanks a lot, Ago From pavlovevidence at gmail.com Mon Sep 22 17:48:11 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 22 Sep 2008 14:48:11 -0700 (PDT) Subject: A bit weird dictionary behavior References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> Message-ID: <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> On Sep 22, 3:43?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > bearophileH... at lycos.com a ?crit : > > > Pekka Laukkanen: > >> but it still doesn't feel exactly right. Would it be worth submitting a bug? > > > It feels wrong because it is. In a tidier language (Pascal, Java, etc) > > a boolean and an integer must be different types. > > Some would argue (and some did by the time Python grew a 'bool' type) > that what is wrong is to have a bool type in a language that already > have a wider definition of the truth value of an expression... And some would argue that it was wrong to have such a wide definition for the truth value of an expression in the first place... Carl Banks From aioe.org at technicalbloke.com Wed Sep 24 16:09:55 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 24 Sep 2008 16:09:55 -0400 Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <gbe6qk$b54$1@aioe.org> bearophileHUGS at lycos.com wrote: > sturlamolden: >> No, because Python already has list comprehensions and we don't need the XML buzzword.< > > LINQ is more than buzzwords. Python misses several of those features. > So maybe for once the Python crowd may recognize such C# feature as > much better than things present in Python. > Said that, I presume Python will go on as usual, and LINQ-like > capabilities will not be integrated in Python. In the meantime where I > live lot of people will keep using C# instead of Python and CLisp, > natural selection at work indeed. > > Bye, > bearophile LOL, I just read that and thought - Ok this sounds serious I'd better go find out what this LINQ business is all about so I googled.. and ended up on MSDN where there's impressive sounding talk about how we need a way to query databases and XML files with a unified syntax like we do for for standard datatypes like files and arrays. Well yes,that makes sense I think and proceed to look at their example code, curious as to what this new paradigm looks like: using System; using System.Linq; using System.Collections.Generic; class app { static void Main() { string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" }; IEnumerable<string> query = from s in names where s.Length == 5 orderby s select s.ToUpper(); foreach (string item in query) Console.WriteLine(item); } } ROTFLMAO! Wow, what progress they're making! Quick guys let's jump on before we get left behind - we dont want to miss out on this exciting and mysterious 'foreach' construct or this strange and exotic sounding 'IEnumerable query' thing. To think that python might someday reach such lofty heights where we'll be able to simply write... names = ["Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David"] result = [each.upper() for each in names if len(each) == 5] result.sort() for each in result: print each Yes clearly 'the Python crowd' must admit LINQ is 'much better', I'm sold, in fact off to download my "Free, but limited editions of Visual Studio 2005 for a single programming language supported by .NET" right away! OK so maybe I'm being naive here but it looks to me like this new paradigm's big idea is to use a python + SQL type syntax to access data in random objects. Big whoop. It's not that difficult to write a generators that wraps XML files and databases is it? What am I missing here? Roger Heathcote. From rafesacks at gmail.com Wed Sep 10 23:44:01 2008 From: rafesacks at gmail.com (Rafe) Date: Wed, 10 Sep 2008 20:44:01 -0700 (PDT) Subject: Clearing a session and reload() problem (with repro error) References: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> <mailman.740.1220976221.3487.python-list@python.org> <067abd3f-0d02-46e8-8d26-d85f20fa2e3a@s9g2000prg.googlegroups.com> <mailman.765.1221031725.3487.python-list@python.org> Message-ID: <350aabd1-d08e-4010-85f7-aff34361d6ba@w39g2000prb.googlegroups.com> On Sep 10, 2:28?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Wed, 10 Sep 2008 00:56:43 -0300,Rafe<rafesa... at gmail.com> escribi?: > > > > > On Sep 9, 11:03 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > > wrote: > >> En Mon, 08 Sep 2008 05:37:24 -0300,Rafe<rafesa... at gmail.com> escribi?: > >> ... > >> This dependency between modules, applied to all modules in your project, > >> defines a "dependency graph". In some cases, one can define a partial > >> ordering of its nodes, such that no module depends on any other module > >> *after* it (it may depend only on modules *before* it). Look for > >> "topological sort". > > >> Doing that in the generic case is not easy. If you *know* your > >> dependencies, reload the modules in the right order by hand. > >> ... > > I was hoping there would be a way to just wipe out the module cache > > and let it get rebuilt by executing my code (since I'm not using > > reload as part of my program, but rather, to test it in an environment > > where I cannot restart the Python session). > > Ok, I think the following sequence *might* work: > > - replace the __import__ and reload builtins with a custom callable ? > object. This way you can hook into any import attempt. The object should ? > keep a list of already reloaded modules. When a module is imported: if it ? > is already in the list, just delegate to the original __import__; if it is ? > not in the list, locate the module in sys.modules and reload it. > > - iterate over sys.modules and reload the desired modules, as you did in ? > your previous attempt. > > - restore the original __import__ function. > > This way, you effectively transform any import statement into a recursive ? > reload (for the first time); subsequent imports of the same module behave ? > as usual. This may work for you, or perhaps not, or it may screw all your ? > running environment up, or even cause the next global thermonuclear war... ? > (I hope not!) > > Note: some modules don't work well with reload(). A common case: global ? > mutable values, like a list of objects which starts empty: > ? ? ? ? my_list = [] > To make it more "reload friendly", use this: > ? ? ? ? try: my_list > ? ? ? ? except NameError: my_list = [] > (this way the list will keep its previous values). > > The example below shows how to hook into the import mechanism - it just ? > prints the module being imported. Implementing the functionality outlined ? > above is left as an exercise to the reader :) > > py> class ImportHook(object): > ... ? ? _orig_import = None > ... # > ... ? ? def __call__(self, name, globals={}, locals={}, fromlist=[], ? > level=-1): > ... ? ? ? ? if fromlist: > ... ? ? ? ? ? ? print "-> from %s import %s" % (name, ','.join(fromlist)) > ... ? ? ? ? else: > ... ? ? ? ? ? ? print "-> import %s" % name > ... ? ? ? ? return self._orig_import(name, globals, locals, fromlist, ? > level) > ... # > ... ? ? def hook(self): > ... ? ? ? ? import __builtin__ > ... ? ? ? ? self._orig_import = __builtin__.__import__ > ... ? ? ? ? __builtin__.__import__ = self > ... # > ... ? ? def unhook(self): > ... ? ? ? ? assert self._orig_import is not None, "unhook called with no ? > previous hook" > ... ? ? ? ? import __builtin__ > ... ? ? ? ? __builtin__.__import__ = self._orig_import > ... ? ? ? ? del self._orig_import > ... # > ... ? ? # support the "with" statement > ... ? ? def __enter__(self): > ... ? ? ? ? self.hook() > ... ? ? ? ? return self > ... # > ... ? ? def __exit__(self, type, value, tb): > ... ? ? ? ? self.unhook() > ... > py> > py> ih = ImportHook() > py> ih.hook() > py> import htmllib > -> import htmllib > -> import sgmllib > -> import markupbase > -> import re > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import re > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> from formatter import AS_IS > -> import sys > -> from htmlentitydefs import entitydefs > py> reload(htmllib) > -> import sgmllib > -> from formatter import AS_IS > -> from htmlentitydefs import entitydefs > <module 'htmllib' from 'C:\apps\Python25\lib\htmllib.pyc'> > py> ih.unhook() > -> import __builtin__ > py> import htmllib > py> > > > I have been keeping a diagram of my module inheritance to make sure it > > is as clean as possible, so I could just right a list of reloads as > > you suggest. However, one of the sub-packages is designed to allow > > users to add more modules. Because these get dynamically imported, a > > guess I could add an argument to the reload function to allow a user > > to give the 'add-on' module they are working on... so much work just > > to get a clean environment... > > > Separate of my program, I was really hoping to write a generic reload > > tool for anyone developing in the same application as I am. I just > > don't see a way to trace import dependencies in systems which include > > dynamic imports. Any ideas? > > You may adapt the example above. > Good luck! > > -- > Gabriel Genellina Thanks again Gabriel! I'll see if I can take another swing at this when I catch up to my milestones ;). I'll post anything useful. - Rafe From nick at craig-wood.com Wed Sep 24 07:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 24 Sep 2008 06:30:03 -0500 Subject: PyRun_SimpleFile() crashes References: <d71e6607-31ca-48a6-b61f-040536a7cebf@g17g2000prg.googlegroups.com> Message-ID: <slrngdk68l.fu2.nick@irishsea.home.craig-wood.com> lixinyi.23 at gmail.com <lixinyi.23 at gmail.com> wrote: > my code: > main.cpp > #include <Python.h> > > int main(int argc, char **argv) > { > Py_Initialize(); > > FILE *file_1 = fopen("a2l_reader.py","r+"); > PyRun_SimpleFile(file_1,"a2l_reader.py"); > > Py_Finalize(); > } > > compile under windows using MinGW: > g++ main.cpp libpython25.a -o a > > no error was found. But when I run a.exe the program just crashes. > > What should I do? Run it under gdb (which should have come with MinGW). Check that you actually opened the file, ie file_1 != 0. This might be relevant http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-on-unix-why.htm -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From rschroev_nospam_ml at fastmail.fm Mon Sep 1 03:45:10 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 01 Sep 2008 09:45:10 +0200 Subject: (in memory) database In-Reply-To: <I8Fuk.118921$oT7.63551@newsfe10.ams2> References: <mailman.299.1220210443.3487.python-list@python.org> <o9cro5-sul.ln1@lairds.us> <I8Fuk.118921$oT7.63551@newsfe10.ams2> Message-ID: <b4Nuk.78766$OR5.7547@newsfe20.ams2> Roel Schroeven schreef: > Cameron Laird schreef: > >> I now suspect that my 2.5 packaging has something to do with 64-bit builds; >> all my 32-bit Ubuntu servers have Python 2.5.2, while the 64-bit ones are at >> Python 2.5. > > Strange: my 64-bit Ubuntu 8.04 has Python 2.5.2, with working sqlite: (mine is a desktop, not a server; I don't know if that should make any difference). -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From fredrik at pythonware.com Wed Sep 10 12:34:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 18:34:42 +0200 Subject: md5 differences In-Reply-To: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> References: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> Message-ID: <ga8sv3$kl7$1@ger.gmane.org> Python wrote: > I'm trying to match the results of an md5 checksum done in a tcsh shell. > I keep getting different results and can't find anything on google... > > here's an example: > > Arno at Computer:~% echo "hello" | md5 > b1946ac92492d2347c6235b4d2611184 > > Arno at Computer:~% python > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import md5 > >>> md5.new("hello").hexdigest() > '5d41402abc4b2a76b9719d911017c592' >>> import md5 >>> md5.new("hello\n").hexdigest() 'b1946ac92492d2347c6235b4d2611184' </F> From bearophileHUGS at lycos.com Thu Sep 25 06:23:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Sep 2008 03:23:35 -0700 (PDT) Subject: python sorting 2dim. array ? References: <9684e81b-df99-4d95-99f9-8345c125b69b@d77g2000hsb.googlegroups.com> Message-ID: <e30cc15e-f3ea-410f-8c0e-2ebfc48773e6@f63g2000hsf.googlegroups.com> fred... at fulladsl.be: > list[rowindex][colomindex] > I want to sort on the second colom as first (and as > second sortfield the first colom). A good way, in Python 2.5: >>> from operator import itemgetter >>> a = [[1, 2], [3, 1], [2, 5], [7, 1]] >>> a.sort(key=itemgetter(1, 0)) >>> a [[3, 1], [7, 1], [1, 2], [2, 5]] Bye, bearophile From jamesd at echeque.com Wed Sep 10 22:10:44 2008 From: jamesd at echeque.com (James A. Donald) Date: Thu, 11 Sep 2008 12:10:44 +1000 Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <mailman.753.1220993363.3487.python-list@python.org> <f7384268-84fa-4626-bf35-61201dd21f23@v13g2000pro.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> <c36f0a82-3e6a-4930-8e5c-6e1b87369c8e@y21g2000hsf.googlegroups.com> <4pcgc495c6ml60a09fh3gc8e6t1akmlmin@4ax.com> <d4ad46ba-0862-404a-81a7-279a5a3d68e3@d77g2000hsb.googlegroups.com> Message-ID: <3rtgc4palueahldle35j1ma21bih1kcse5@4ax.com> James A. Donald > > > > Horrible installs are a chronic problem of GUI programs driven by > > > > interpreted languages ?Installing visual basic programs that worked on > > > > one Windows machine to work on a very slightly different windows > > > > machine was also a nightmare. > > > > > > > > I have not attempted to create installable wxPython windows, but > > > > generally, "run anywhere" will bite you. ?Still looking for a good > > > > solution to "run anywhere". Mike Driscoll > I used Inno Setup which creates an uninstaller, however I am not > seeing it in my Windows Add/Remove. Odd. However, you can uninstall it > from the Start menu entry and it works. Could anyone tell me their experiences with NSIS? Has anyone tried scripting msi (Windows Installer 3.0 Redistributable) with Orca and the Windows SDK Components for Windows Installer Developers. How did it go. I notice that Python 2.4 is distributed as an msi file. I suspect there is a reason for that. Was that constructed with Orca? -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From bearophileHUGS at lycos.com Fri Sep 5 11:18:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 08:18:52 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> Message-ID: <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> Helmut Jarausch: > I need to hash arrays of integers (from the hash module). One of the possible solutions is to hash the equivalent tuple, but it requires some memory (your sequence must not be tuples already): assert not isinstance(somelist, tuple) hash(tuple(somelist)) This is an alternative solution, it doesn't use much memory, but I am not sure it works correctly: from operator import xor hash(reduce(xor, somelist)) Bye, bearophile From dblubaugh at belcan.com Mon Sep 8 19:19:59 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 8 Sep 2008 19:19:59 -0400 Subject: F2PY ?? Has anyone worked with the F2PY generator? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F3802840447@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F3802840447@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804F0F018@AWMAIL04.belcan.com> Pauli, Yes, I am utilizing the windows environment. I cannot install f2py. I obtain the following error when I try to execute the setup.py file within the f2py folder located within the numpy master folder: Warning: Assuming default configuration (lib\parser/{setup_parser,setup}.py was not found) Appending f2py.lib.parser configuration to f2py.lib Ignoring attempt to set 'name' (from 'f2py.lib' to 'f2py.lib.parser') Warning: Assuming default configuration (lib\extgen/{setup_extgen,setup}.py was not found) Appending f2py.lib.extgen configuration to f2py.lib Ignoring attempt to set 'name' (from 'f2py.lib' to 'f2py.lib.extgen') Appending f2py.lib configuration to f2py Ignoring attempt to set 'name' (from 'f2py' to 'f2py.lib') F2PY Version 2_4423 Traceback (most recent call last): File "C:\Python25\Lib\site-packages\numpy\f2py\setup.py", line 130, in <module> **config) TypeError: setup() got multiple values for keyword argument 'version' >>> I do not know as to how to fix the multiple values for version?? PLEASE HELP!!! David Blubaugh -----Original Message----- From: Blubaugh, David A. Sent: Monday, September 08, 2008 6:04 PM To: 'python-list at python.org' Subject: F2PY ?? Has anyone worked with the F2PY generator? To All, Has anyone worked with the F2PY generator? This is something that is supposedly built within numpy and scipy for the Python environment. I was wondering if anyone has encountered any issues with this environment?? This is important to find the answers to these questions. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From deets at nospam.web.de Wed Sep 10 11:55:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 17:55:45 +0200 Subject: Alternatives to traditional RDBMS References: <mailman.791.1221056566.3487.python-list@python.org> Message-ID: <6iq90jFdeiU1@mid.uni-berlin.de> James Mills wrote: > Hi all, > > Are there any known alternatives > to the traditional RDBMS (MySQL, > PostgreSQL, SQLite, Oracle, etc0 / > > I know of 3 written in Python: > * buzhug > * kirbybase > * PyDbLite ZODB. Without any problems usable without ZOPE, clusterable, ACID-conform and so forth. Diez From tony.clarke5 at googlemail.com Tue Sep 16 01:58:10 2008 From: tony.clarke5 at googlemail.com (tony.clarke5 at googlemail.com) Date: Mon, 15 Sep 2008 22:58:10 -0700 (PDT) Subject: append on lists References: <gamgom$tmm$1@ger.gmane.org> <mailman.1085.1221541489.3487.python-list@python.org> Message-ID: <4097db86-b9dc-4ed5-ac84-6747a9f2bb11@t54g2000hsg.googlegroups.com> On Sep 16, 6:03?am, Peter Anderson <peter.ander... at internode.on.net> wrote: > "/... I don't think you've thought this one through, really./" > snip > > We ought to try and be a little kinder to others on the list, don't you > think? :-) > > snip Well said! Tony From wuwei23 at gmail.com Tue Sep 2 02:08:10 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Sep 2008 23:08:10 -0700 (PDT) Subject: Put the output from all my programs in one place References: <3110346f-ed2b-458d-bbf8-af7e594f6509@e53g2000hsa.googlegroups.com> Message-ID: <d93208db-2411-4180-8ed8-d1e8234812b3@k36g2000pri.googlegroups.com> On Sep 2, 6:30?am, Jesse Aldridge <JesseAldri... at gmail.com> wrote: > I want to put all the output from all of my python programs in one > place. Have you considered using the python logging module? http://docs.python.org/lib/module-logging.html http://www.onlamp.com/pub/a/python/2005/06/02/logging.html You can define handlers within a program or via a config file. Then you just need to specify that they all log to the same location, which you could define via an environment variable... From lixinyi.23 at gmail.com Tue Sep 23 20:27:45 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 17:27:45 -0700 (PDT) Subject: How can I use a PyObject in C++? Message-ID: <eaccc109-2cd6-4330-a6a6-ee559487741c@g17g2000prg.googlegroups.com> for example: #include <Python.h> void exec_python_code(int arg, char** argv) { Py_Initialize(); Py_Main(argc,argv); Py_Finalize(); } What I would like to know is: after Py_Main(argc,argv); How do I get every variable in python space, say a=[1,2,3,'Hello World',[2,3]] b=['xx','xxx','ffff',0.1234] , and use them in C++? any sample code? Thanks in advance! From steve at holdenweb.com Mon Sep 29 09:49:06 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 09:49:06 -0400 Subject: Cannot install pysqlite on Cygwin In-Reply-To: <b3fe277b-d191-43ad-8de8-83d99dd890f1@w1g2000prk.googlegroups.com> References: <b3fe277b-d191-43ad-8de8-83d99dd890f1@w1g2000prk.googlegroups.com> Message-ID: <gbqmcj$cuq$1@ger.gmane.org> Tilman Kispersky wrote: > I am trying to install sqlite for use with python on cygwin. I have > installed the sqlite packages from cygwin (that is libsqlite3-devel > and libsqlite3_0). When attempting to easy_install pysqlite I get: > > $ easy_install pysqlite > Searching for pysqlite > Reading http://pypi.python.org/simple/pysqlite/ > Reading http://pysqlite.org/ > Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ > Reading http://pysqlite.sourceforge.net/ > Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/ > Reading http://initd.org/tracker/pysqlite/wiki/PysqliteDownloads > Reading http://oss.itsystementwicklung.de/trac/pysqlite > Reading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/ > Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/ > Reading http://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/ > Reading http://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/ > Best match: pysqlite 2.5.0 > Downloading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlite-2.5.0.tar.gz > Processing pysqlite-2.5.0.tar.gz > Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/ > Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg- > dist-tmp-7mr3WS > warning: no files found matching 'doc/*.html' > warning: no files found matching 'doc/code/*.py' > src/statement.c: In function `pysqlite_statement_recompile': > src/statement.c:351: warning: `sqlite3_transfer_bindings' is > deprecated (declared at /usr/include/sqlite3.h:3985) > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function > `pysqlite_enable_load_extension': > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ > pysqlite-2.5.0/src/connection.c:922: undefined reference to > `_sqlite3_enable_load_extension' > collect2: ld returned 1 exit status > error: Setup script exited with error: command 'gcc' failed with exit > status 1 > $ > > > It seems to me this is due to some missing library (undefined > reference...) but I have no idea what these missing files might be. > I've tried installing everything that made any reference to sqlite > form the cygwin interface. Does anyone know how I might get a working > install of sqlite for python on cygwin? I believe it's a glitch in the 2.5.1 distribution current on Cygwin - I had to install the _sqlite DLL separately to get it to work, but no recompilation was necessary AFAICR. Chui Tey detailed the necessary steps in his blog post "Cygwin Python and sqlite3", but sadly it got lost and he hasn't replenished it, so you will have to stab around to see if there's a cached copy anywhere. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From grante at visi.com Thu Sep 11 10:57:58 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 11 Sep 2008 09:57:58 -0500 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> <87k5djb6e2.fsf@benfinney.id.au> <pan.2008.09.11.09.10.00@REMOVE.THIS.cybersource.com.au> Message-ID: <6sCdnZcLo6xrrFTVnZ2dnUVZ_vWdnZ2d@posted.visi> On 2008-09-11, Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote: > On Thu, 11 Sep 2008 15:25:57 +1000, Ben Finney wrote: > >>> > The bounce messages are sent to you because you sent the original. >>> >>> Wrong. I didn't send _any_ e-mail. Why should I get bounce messages? >> >> You asked for email to be sent, No, I didn't. >> by sending a Usenet post to comp.lang.python. That's what a >> news-to-mail gateway does. ROTFL. That's like saying: you asked to be mugged by walking down a street where there was a mugger. That's what a mugger does. > I wasn't aware that comp.lang.python was a news-to-mail > gateway. How can one tell the difference between news groups > that use a news-to-mail gateway, and news groups that don't? One can't tell. > Posting to a public newsgroup is obviously giving consent to > forward that news posting to news clients. Given the ability > to opt-out with the X-No- Archive header, there may even be an > implied consent to allow archiving. But I don't believe there > is any such implied consent to format-shift news messages to > email. I certainly don't care if the articles I post are sent to anybody via any transport. I just don't like it being made to appear that I'm the one who sent them. I supposed I could break down and stop using my real e-mail address in the From: field. Or I could add some procmail rules to try to filter out the results of being joe-jobbed by the gateway. > In practice, I couldn't care less what format my news postings > are converted to, so long as it is invisible and transparent > to me. That's the issue: it's not invisible to you if you're getting bounce messages, out-of-office-replies, and other e-mail traffic generated by the fact the somebody is grabbing articles off Usenet and mailing them out as if it were you that sent them. > If somebody wants to build a > news-to-carved-in-giant-stone-tablets gateway, I don't care, > so long as I don't get giant stone tablets aren't dumped in > my front yard. > > Nor do I believe that by posting a news message I've > automatically consented to receive email messages. To imply > that the one implies the other is equivalent to arguing that > because I've written a letter to the editor of a newspaper, I > therefore must accept private correspondence from any person > or corporation that has a subscription to that newspaper. > > (In practice, I don't mind human-generated email messages, but > not automatic messages. If you can turn my munged email > address into a real email address, I probably won't mind you > emailing me. Don't abuse the privilege.) I don't mind receiving private e-mails from people who recieved the posting (either via Usenet or the gatewayed mailing list). If I did, I wouldn't use my real e-mail address. But, I don't want to receive machined generated trash or to be cc'd by people following up to the article. > "The bounce/ooo-reply is sent to the message author, not to > any intermediate host(s). After all, on that end, it's normal > email failure response -- notify the author of the message. It > doesn't matter that the original message was posted on a > Usenet newsgroup if that group is automatically relayed to > members of a mailing list." > > But that's wrong: it *shouldn't* be an normal email failure > response, because the message author is in no position to do > anything about it except to cease posting. That's a problem > with all mailing lists (that I know of). I know of other mailing lists aren't configured that way: the original author doesn't get bounce messages -- the sender of the bounced e-mail gets the bounce message. -- Grant Edwards grante Yow! Clear the laundromat!! at This whirl-o-matic just had visi.com a nuclear meltdown!! From has.temp3 at virgin.net Thu Sep 25 07:39:54 2008 From: has.temp3 at virgin.net (has) Date: Thu, 25 Sep 2008 04:39:54 -0700 (PDT) Subject: Folder Actions on Mac OSX Leopard? References: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> <6ea2a222-90be-4079-b78f-ead1e8f6d241@q26g2000prq.googlegroups.com> Message-ID: <0c5bd076-8806-4f46-9380-b221588bffb0@79g2000hsk.googlegroups.com> On 25 Sep, 00:30, Sean DiZazzo <half.ital... at gmail.com> wrote: > I always wondered about Folder Actions... ?I just tested. ?You can > have applescript call python scripts via `do shell script`. ?But it > seemed a bit flakey. Should work in theory. For which values of flakey? e.g. Is it a technical problem with Folder Actions, AppleScript, 'do shell script, and/or Python, or just your AppleScript code that needs some work (e.g. there are some common gotchas with using 'do shell script' that often trip up AppleScript newcomers). FWIW, I would second the suggestion to look into FSEvents as a possible alternative to Folder Actions. There's also kqueue which is lower level but may have/have had Python bindings already written for it. Alternatively, if the OP really wants to use FAs, there are a couple of other options for that: 1. I've got a simple py2app-based application shell and an AppleScript that automatically forwards FA events to that application - just insert your Python code into the application shell and build it, attach the AppleScript to some folders, and you're good to go. Email me directly if you want a copy. 2. If you're brave, you could try using the PyOSA component on the appscript website, which allows you to write OSA scripts in Python. FAs will work with any kind of OSA script (.scpt files), not just AppleScript ones. PyOSA is officially discontinued due to some intractable limitations in its/CPython's design (specifically the inability of an in-process Python interpreter to sandbox unrelated scripts so that they can't interfere with each others' modules, file handles, etc). However, it's reasonably functional and should be usable for FAs with a little care. HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From fredrik at pythonware.com Sun Sep 7 18:01:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 00:01:01 +0200 Subject: formatting a string with thousands separators In-Reply-To: <e1a84d570809071449s3978b9c3w8d16c95091c966be@mail.gmail.com> References: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> <RTVwk.660$Dj1.566@trnddc02> <e1a84d570809071449s3978b9c3w8d16c95091c966be@mail.gmail.com> Message-ID: <ga1iuu$65e$1@ger.gmane.org> James Mills wrote: > There is a much easier more consistent way: > >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "en_AU.UTF-8") > 'en_AU.UTF-8' doesn't work on all Python platforms, though: >>> locale.setlocale(locale.LC_ALL, "en_AU.UTF-8") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\python25\lib\locale.py", line 478, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting and is likely to give you somewhat unpredictable output if you use the machine's actual locale: >>> import os >>> locale.setlocale(locale.LC_ALL, os.environ["LANG"]) 'sv_SE.UTF-8' >>> locale.format("%0.2f", 5000000, True) '5000000,00' </F> From invalid at invalid Wed Sep 24 11:54:40 2008 From: invalid at invalid (Grant Edwards) Date: Wed, 24 Sep 2008 10:54:40 -0500 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <pan.2008.09.24.06.17.06@REMOVE.THIS.cybersource.com.au> <JcKdndouSNGG10fVnZ2dnUVZ_hCdnZ2d@posted.visi> <gbdmgh$nd0$1@rumours.uwaterloo.ca> Message-ID: <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> On 2008-09-24, Ross Ridge <rridge at csclub.uwaterloo.ca> wrote: > Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote: >> Presumably somebody has suggested that calling sys.exit() was a good >> option. I'm curious to what possible reason they could give for such a >> poor choice. > > Grant Edwards <invalid at invalid> wrote: >>Same here. It's like an automotive engine controls designer >>asking if a failed O2 sensor should turn on the check engine >>light or blow up the car. > > No, it's more like asking if the failed sensor should turn on > a strange and mysterious light on the dashboard You're right. I had forgotten that sys.exit() is actually raising the system exit exception, and that the application calling the library could handle that exception. > and then blow up the car if the driver doesn't immediately > stop and check the engine. The owners manual would only > vaguely hint at the fact that this could happen. -- Grant Edwards grante Yow! Why is it that when at you DIE, you can't take visi.com your HOME ENTERTAINMENT CENTER with you?? From ireborin at delete.this.gmail.com Mon Sep 29 21:56:03 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 03:56:03 +0200 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <affd6918-3444-4a8f-9816-faa56ee34512@k37g2000hsf.googlegroups.com> <q1r2e458kqe2t7phvj5iorgj0tbnbi7ikb@4ax.com> <6d265f36-352c-4866-bf91-c14d26101fc2@k37g2000hsf.googlegroups.com> Message-ID: <ku03e4pddv9fbshgkbpbfv2hrg3u1p1i6h@4ax.com> On Mon, 29 Sep 2008 17:59:40 -0700 (PDT), bearophileHUGS at lycos.com wrote: Hello bearophile, thank you for replying. >The Python genie grants you that wish. You were almost right: >>>> print (3 * '%12.3f') % (a, b, c) > 2.000 123456.789 1234.000 >>>> print 3 * '%12.3f' % (a, b, c) > 2.000 123456.789 1234.000 Works beautifully :-) Thank you! >>>> print 3 * '%12.3f' % a, b, c >Traceback (most recent call last): > File "<stdin>", line 1, in <module> >TypeError: not enough arguments for format string Just one more question - it's actually an extension to this one (forgive my curiosity, but I really need this info, and searching google always gives me the same stuff again and again) ... a = 2.000001 b = 123456.789 c = 1234.0001 d = 98765.4321 # same as above except for d print (3 * '%12.3f') % (a, b, c) #this works beautifully How to add d at the end but with a different format now, since I've "used" the "format part" ? Again, my weird wishful-thinking code: print (3*'%12.3f', '%5.3f') %(a,b,c),d >(Note the spaces and parentheses. Python programmers thank you if put >them improving readability a little). Yes, ok. I can agree with that - separating the format from the variable list part sounds reasonable. > >Bye, >bearophile -- Ivan From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 03:01:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 09:01:57 +0200 Subject: Docstrings for class attributes In-Reply-To: <mailman.1392.1222147427.3487.python-list@python.org> References: <mailman.1392.1222147427.3487.python-list@python.org> Message-ID: <48d8945f$0$27140$426a74cc@news.free.fr> Tom Harris a ?crit : > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 Do you have a reason to stuff them in a class ? Usually, putting them at the top level of a module is quite enough... > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. You can document them in the module or class docstring... From h.goebel at goebel-consult.de Tue Sep 16 13:29:31 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Tue, 16 Sep 2008 19:29:31 +0200 Subject: Python and Open Office In-Reply-To: <mailman.826.1221077307.3487.python-list@python.org> References: <a9f39a410809101304j592cb7actc1f95882f8fe632c@mail.gmail.com> <mailman.826.1221077307.3487.python-list@python.org> Message-ID: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> Marco Bizzarri schrieb: > On Wed, Sep 10, 2008 at 10:04 PM, Greg Lindstrom <gslindstrom at gmail.com> wrote: >> Hello, >> >> I would like to create and manipulate Open Office documents using Python. I [...] >> Is there someone here who can help me out, or is there an appropriate >> mailing list for me to join? > > Ciao, Greg. > > you should check with the openoffice.org mailing list; I think what > you are looking for is the api mailing list for openoffice; you could > try to get the OpenOffice.org developers guide and the SDK, and check > it (but it is not a little work) If want to create documents, there is no nead to fight with OOo and UNO. As I thought everybody already knows, ODF is simply a Zip-File containing some XML files. So there is no need to use OOo for handling the files. So odfpy seams to be the best way to to this. You may also want to check OOopy <http://pypi.python.org/pypi/OOoPy/>. If you are going to interact with OOo, you may want to try out <http://openoffice-python.origo.ethz.ch/> -- Sch?nen Gru? - Regards Hartmut Goebel Dipl.-Informatiker (univ.), CISSP Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From dudeja.rajat at gmail.com Tue Sep 2 15:21:29 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 2 Sep 2008 20:21:29 +0100 Subject: What is module initialization? In-Reply-To: <g9jsoo$uf0$1@ger.gmane.org> References: <mailman.367.1220362362.3487.python-list@python.org> <48bd4799$0$17215$426a74cc@news.free.fr> <e0b6c39a0809020732i5f3f3a41kbdccf0c4bf7549ec@mail.gmail.com> <g9jsoo$uf0$1@ger.gmane.org> Message-ID: <e0b6c39a0809021221l89afa47ubc6867576135b220@mail.gmail.com> On Tue, Sep 2, 2008 at 6:22 PM, Fredrik Lundh <fredrik at pythonware.com> wrote: > dudeja.rajat at gmail.com wrote: > >>> # myglobals.py: >>> answer = 42 >>> >>> # question.py >>> import myglobals >>> myglobals.answer = "WTF ?" >>> >> >> But if I do :- >> #question.py >> from myglobals import * >> myglobals.answer = "WTF ?" >> >> will this work? > > with the above definition of myglobals, no. "from myglobals import" doesn't > add the module object to the importing module's namespace. > > have you read: > > http://effbot.org/zone/import-confusion.htm > > ? > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for your help guys that I got my problem resolved. Regards, Rajat From clp at rebertia.com Fri Sep 26 00:42:59 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 25 Sep 2008 21:42:59 -0700 Subject: Fastest way to max() list In-Reply-To: <ea42fb160809252057o283216c1v35067189835f227c@mail.gmail.com> References: <ea42fb160809252057o283216c1v35067189835f227c@mail.gmail.com> Message-ID: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> On Thu, Sep 25, 2008 at 8:57 PM, David Di Biase <dave.dibiase at gmail.com> wrote: > I have a list with about 1000-1500 sub-lists which look like so: > list[-0.28817955213290786, 3.6693631467403929, 'H', 31.31225233035784]] > > The first and second values are Angstrom units specifying the location of a > particle. What I'd like to do is determine the distance between the smallest > and largest value in the arrays first position 0. I tried reading the manual > for this but I don't see how it applies key or any of those other commands > to the function. I could easily write a sort to do this and capture the > first and last spots, but why do that when I can use max and min (if I can > actually do that...). A. You should probably be using objects rather than arrays to represent your datapoints, so that they're more structured and it's more apparent what the values mean. B. Assuming by "distance" you meant "difference" and/or that the distance is only in 1 dimension: from operator import itemgetter firsts = map(itemgetter(0), main_list) distance = max(firsts) - min(firsts) > > So you wonderful Python gods, lay some knowledge on me. please? lol... > > while I'm at it, is there a way to modify an entire list without having to > produce a whole new one? For example now say I want to modify list[0] and > multiply it by some value. From what I understand previous version of Python > allowed lists to be multiplied like matrices...now apparently it just > replicates the list. :-/ shucks... You just have to apply the transform to each list element individually (also, you might consider using NumPy [http://numpy.scipy.org/] if you're doing a lot of matrix manipulation): for lst in main_list: lst[0] *= some_value Regards, Chris > > The first question would be useful to know, but the second question I do > quite a bit of and the "best practice" would be really great to know! > > Thanks in advanced! > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From david.huard at gmail.com Tue Sep 16 16:25:13 2008 From: david.huard at gmail.com (David Huard) Date: Tue, 16 Sep 2008 20:25:13 +0000 (UTC) Subject: Programmatically exit the REPL References: <288810.50426.qm@web7904.mail.in.yahoo.com> <48B35768.80304@nienna.org> <48B46BF1.20408@nienna.org> Message-ID: <gap4n9$gb3$1@ger.gmane.org> > [snip] > > Does anyone know how to make raw_input think it has gotten input? > > -Matt Hi Matt, So you really need raw_input ? Couldn't you use a mock-up ? sys.stdout.write('> ') sys.stdout.flush() And get the user input with something like: while self.continue: input = os.read(sys.stdin.fileno(), 80).strip() if input== '': time.sleep(.2) The background thread can stop the listening thread by setting self.continue to False. The subversion trunk of pymc (on google code) has something that I think is similar to your problem, you might want to look at it (look at revision 868). HTH, David Huard From marco.bizzarri at gmail.com Thu Sep 4 06:57:10 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 12:57:10 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? Message-ID: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Let's say I've a class a, where I can write: -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From michel at nospam.please Tue Sep 16 14:12:54 2008 From: michel at nospam.please (Michel Leunen) Date: Tue, 16 Sep 2008 20:12:54 +0200 Subject: Python Nautilus script In-Reply-To: <99dc3fb0-f4ea-4b3e-926c-ce3462cd9973@b1g2000hsg.googlegroups.com> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <99dc3fb0-f4ea-4b3e-926c-ce3462cd9973@b1g2000hsg.googlegroups.com> Message-ID: <48cff726$0$2861$ba620e4c@news.skynet.be> kaer a ?crit : > #! /usr/bin/python > # -*- coding: utf8 -*- > > import os, sys > > #NAUTILUS_SCRIPT_SELECTED_FILE_PATHS : chemins des fichiers > s?lectionn?s s?par?s par des retours ? la ligne (newline) (uniquement > pour les fichiers locaux) > #NAUTILUS_SCRIPT_SELECTED_URIS : URIs des fichiers s?lectionn?s > s?par?s par des retours ? la ligne (newline) > #NAUTILUS_SCRIPT_CURRENT_URI : URI de l'emplacement actuel > #NAUTILUS_SCRIPT_WINDOW_GEOMETRY : position et taille de la fen?tre > actuelle > > > KEYS=("NAUTILUS_SCRIPT_SELECTED_FILE_PATHS", > "NAUTILUS_SCRIPT_SELECTED_URIS", "NAUTILUS_SCRIPT_CURRENT_URI", > "NAUTILUS_SCRIPT_WINDOW_GEOMETRY") > > ft=open("/home/kaer/stupid.txt", "w") > for key_value in [(key, os.environ.get(key, 'NOT FOUND')) for key in > KEYS]: > ft.write("env(%s): %s\n" % key_value) > file_names=sys.argv[1:] > for index, file_name in enumerate(file_names): > ft.write("%s: [%s]\n" % (index, file_name)) > if os.path.isfile(file_name): os.rename(file_name, '%03d-%s' % > (index+1, file_name)) > ft.close() Yes, indeed, it works with your code. Thanks for it. I just have to find out why it doesn't work with mine. The problem is that Nautilus scripts are hard to debug. Thanks for your help, Michel -- Michel Leunen http://linux.leunen.com From python at p0w.org Fri Sep 12 08:08:05 2008 From: python at p0w.org (Strato) Date: Fri, 12 Sep 2008 14:08:05 +0200 Subject: testing if another instance of a script is already running Message-ID: <48CA5BA5.8020709@p0w.org> Hi folks, I want to write some kind of test to check at startup if another instance of my script is already running. I don't want to handle writing of a PID file because it is too Unix/Linux specific way to do this, and I need to keep the code to be cross-platform. I think the better way to achieve this is to use some process control, but I'm a neebie and I don't see how to do this in a safe and clean way. Any idea ? Best regards, Strato From gherron at islandtraining.com Sun Sep 14 15:15:04 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 14 Sep 2008 12:15:04 -0700 Subject: Abstract class In-Reply-To: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> References: <mailman.1008.1221408214.3487.python-list@python.org> <roy-9FFFBD.13564414092008@news.panix.com> <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> Message-ID: <48CD62B8.7070708@islandtraining.com> Mr.SpOOn wrote: > Gary Harron: > >> I believe you are mixing up class *inheritance* and *abstract* classes. >> > > >> Class inheritance (with Python has has for years) is how one class inherits >behavior/properties/attributes from another class. The class being inherited from is >called the base class. This is probably what you want. >> > > Well, I know the difference between an abstract class and an inherited > one. The idea was to create a main class Note, with abstract methods, > and implement these methods in the other classes. > > On Sun, Sep 14, 2008 at 7:56 PM, Roy Smith <roy at panix.com> wrote: > >> What properties or behaviors does SharpNote have which NaturalNote doesn't? >> Unless there is some new behavior, you don't need subclasses. >> > > Well, from a SharpNote I can obtain the relative NaturalNote. So if I > have a C# I can call > > natural('C#') and get 'C' > > While in the class NaturalNote I don't need such a method, but I need > two methods to get the sharped and flatted version > > >> Are you also going to have DoubleSharpNote and DoubleFlatNote? >> > > Yes, that's an option. > > >> Consider the following code: >> >> note1 = SharpNote("E4") >> note2 = NaturalNote("F4") >> if note1 == note2: >> print "the same note" >> else >> print "different notes" >> >> what should it print? >> > > Well, that's not so simple. The idea is that I use a notation (A, B, > C, D...) and an integer (a distance expressed in semitones) to > identify a note. > > Anyway, I think I need an abstract class. Or not? > No! Definitely not! You need inheritance of a class from a base class. Implement your base class with whatever shared methods you want. Implement your derived class with methods (new, inherited or reimplemented) as you like. (If you wish to consider the base class "abstract", just agree with yourself to not instantiate it.) Please forget about Abstract Base Classes. They have nothing to do with what you want, and are a *HUGE* overkill for your application. They are not (yet) even part of standard Python, and are used primarily for a class implementor to guarantee to a user of a class that it provides a specific interface. Gary Herron > -- > http://mail.python.org/mailman/listinfo/python-list > From anita.vishwas at gmail.com Mon Sep 22 08:03:08 2008 From: anita.vishwas at gmail.com (Shopping) Date: Mon, 22 Sep 2008 05:03:08 -0700 (PDT) Subject: Lenovo N3000 0769CVQ Notebook Message-ID: <2bcbd1f3-bc5c-4244-8333-e67496247188@z11g2000prl.googlegroups.com> Buy low price Lenovo N3000 0769CVQ Notebook - buy best Lenovo N3000 0769CVQ Notebook online at lowest price, homeshop18.com offers best deals to buy Lenovo N3000 0769CVQ Notebook online with discount in India. To know more visit : http://www.homeshop18.com/shop/u/y/p-Computers-Q-and-Q-Peripherals-S-Laptops-S-Lenovo-Q-N3000-Q-0769CVQ-Q-Notebook/Home_Online-pI_20249-clI_2-cI_920-pCI_909- From circularfunc at gmail.com Fri Sep 26 22:39:49 2008 From: circularfunc at gmail.com (process) Date: Fri, 26 Sep 2008 19:39:49 -0700 (PDT) Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? Message-ID: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> ' '.join([`x * x` for x in range(1, 6)]) exactly what does this symbol do and what does it stand for? From christopher.paul.taylor at gmail.com Wed Sep 17 09:27:47 2008 From: christopher.paul.taylor at gmail.com (christopher taylor) Date: Wed, 17 Sep 2008 09:27:47 -0400 Subject: python regex character group matches Message-ID: <f44caf830809170627m19b5f4e3qb9fe2fb69ee20afa@mail.gmail.com> hello python-list! the other day, i was trying to match unicode character sequences that looked like this: \\uAD0X... my issue, is that the pattern i used was returning: [ '\\uAD0X', '\\u1BF3', ... ] when i expected: [ '\\uAD0X\\u1BF3', ] the code looks something like this: pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) #print pat.findall(txt_line) results = pat.finditer(txt_line) i ran the pattern through a couple of my colleagues and they were all in agreement that my pattern should have matched correctly. is this a simple case of a messed up regex or am i not using the regex api correctly? cheers, ct From gogtesuyash at gmail.com Wed Sep 17 08:28:05 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 05:28:05 -0700 (PDT) Subject: Problem occured while sending mail References: <b7481bed-df0f-4ef7-8fe7-09da5869492f@c22g2000prc.googlegroups.com> Message-ID: <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> On Sep 17, 5:04 pm, sui <gogtesuy... at gmail.com> wrote: > this is my code > > import sys, os, glob, datetime, time > import smtplib > ## Parameters for SMTP session > port=587 > SMTPserver= 'smtp.gmail.com' > SMTPuser= '... at gmail.com' > pw= 'fill in here' > SENDER= SMTPuser > > ## Message details > FROM= SENDER > TO= 'notgm... at a.com' > CC=FROM > ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC > RECEIVERS= (TO,) ## ignore the CC address > > subject= 'Test 1a' > message='*** Email test *** ' > > print 'Starting SMTP mail session on %s as %s ' % > (SMTPserver,SMTPuser) > session = smtplib.SMTP(SMTPserver,port) > session.set_debuglevel(0) # set debug level to 1 to see details > session.ehlo(SMTPuser) # say hello > session.starttls() # TLS needed > session.ehlo(SMTPuser) # say hello again, not sure why > session.login(SMTPuser, pw) > > ##Create HEADER + MESSAGE > HEADER= 'From: %s\r\n' % FROM > HEADER= HEADER + 'To: %s\r\n' % TO > HEADER= HEADER + 'Cc: %s\r\n' % CC > HEADER= HEADER + 'Subject: %s\r\n' % subject > BODY= HEADER + '\r\n' + message > print BODY > > SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email > > session.close() > > Now when i run this .py file...as python mail.py > i can see only statement > starting smtp mail......n details > then nothing on screen after few minutes or after pressing ctrl +c > Traceback (most recent call last): > File "mail4.py", line 21, in <module> > session = smtplib.SMTP(SMTPserver,port) > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > self.sock.connect(sa) > File "<string>", line 1, in connect > or may be conncetion time out > > wats the solution for this if i dont press cntrl + c then it shows Starting SMTP mail session on smtp.gmail.com as gogtesuyash at gmail.com Traceback (most recent call last): File "mail4.py", line 21, in <module> session = smtplib.SMTP(SMTPserver,port) File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect raise socket.error, msg socket.error: (110, 'Connection timed out') plz help me its urgent.....i want to complete it as early as possible From barry at python.org Fri Sep 12 21:28:55 2008 From: barry at python.org (Barry Warsaw) Date: Fri, 12 Sep 2008 21:28:55 -0400 Subject: RELEASED Python 2.6rc1 Message-ID: <49568982-472B-46BB-9001-12078706B238@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the first release candidate for Python 2.6. This is a release candidate, so while it is not suitable for production environments, we strongly encourage you to download the release and test it on your software. We expect only critical bugs to be fixed between now and the final 2.6 release, still scheduled for October 1st, 2008. There is one more release candidate planned for September 17th. You might notice that unlike earlier releases, we are /not/ releasing Python 3.0rc1 at this time. It was decided that 3.0 still needs time to resolve open issues and that we would not hold up the 2.6 release for this. We feel that Python 2.6 is nearly ready for its final release. If you find things broken or incorrect, please submit bug reports at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 website: http://www.python.org/download/releases/2.6/ (Note that the Windows installers will be uploaded shortly.) See PEP 361 for release schedule details: http://www.python.org/dev/peps/pep-0361/ Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSMsXV3EjvBPtnXfVAQJFsgP9GxZYQocbDTd0Z/0yEjpHfZ/FTd8y83jV 5JouO07lB8XtLawnWB9hF8sUrCuBVog5He3mLVUPDmlyn30qvjYWMG2J6zW0yYMX yZdjUyUmta0IMCsXe7YXj369xebh4nWuwG4tDygly4donA7GYPXAlxI48MmyDJxw 1v07LM4Dttw= =Nd3s -----END PGP SIGNATURE----- From maric at aristote.info Tue Sep 16 09:26:55 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 15:26:55 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <200809151645.13078.maric@aristote.info> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> <200809151645.13078.maric@aristote.info> Message-ID: <200809161526.56000.maric@aristote.info> Le Monday 15 September 2008 16:45:12 Maric Michaud, vous avez ?crit?: > Le Thursday 11 September 2008 06:51:19 Dennis Lee Bieber, vous avez ?crit?: > > On Wed, 10 Sep 2008 21:36:36 -0500, Grant Edwards <grante at visi.com> > > > > declaimed the following in comp.lang.python: > > > Wrong. I didn't send _any_ e-mail. Why should I get bounce > > > messages? > > > > One: Comp.lang.python is dual-routed with a mailing list; anything > > you post to either CLP or the mailing list gets cross-posted to the > > other -- the FROM header retains that of the original author (which > > could be you). > > > > Two: Somebody else is subscribed to the mailing list, and sets up an > > "out-of-office" reply or has other problems (like an overfilled mailbox, > > causing a bounce, or a discontinued account) when the forwarded post > > reaches their address. > > > > Three: The bounce/ooo-reply is sent to the message author, not to > > any intermediate host(s). After all, on that end, it's normal email > > failure response -- notify the author of the message. It doesn't matter > > that the original message was posted on a Usenet newsgroup if that group > > is automatically relayed to members of a mailing list. > > Given RFCs, the problem should not be, for DSN, the MTA should rewrite the > FROM envelope address to the one of the list maintainer : > > RFC 3464 : > > 3. Conformance and Usage Requirements > > > > ... > > > > By contrast, successful submission of a message to a mailing list > > exploder is considered final delivery of the message. Upon delivery > > of a message to a recipient address corresponding to a mailing list > > exploder, the Reporting MTA SHOULD issue an appropriate DSN exactly > > as if the recipient address were that of an ordinary mailbox. > > > > NOTE: This is actually intended to make DSNs usable by mailing > > lists themselves. Any message sent to a mailing list subscriber > > should have its envelope return address pointing to the list > > maintainer [see RFC 1123, section 5.3.7(E)]. Since DSNs are sent > > to the envelope return address, all DSNs resulting from delivery > > to the recipients of a mailing list will be sent to the list > > maintainer. The list maintainer may elect to mechanically > > process DSNs upon receipt, and thus automatically delete invalid > > addresses from the list. (See section 7 of this memo.) > > and > > > Appendix C - Guidelines for use of DSNs by mailing list exploders > > > > - Guidelines for use of DSNs by mailing list exploders > > > > > > This section pertains only to the use of DSNs by "mailing lists" as > > defined in [4], section 7.2.7. > > > > DSNs are designed to be used by mailing list exploders to allow them > > to detect and automatically delete recipients for whom mail delivery > > fails repeatedly. > > > > When forwarding a message to list subscribers, the mailing list > > exploder should always set the envelope return address (e.g., SMTP > > MAIL FROM address) to point to a special address which is set up to > > receive non-delivery reports. A "smart" mailing list exploder can > > therefore intercept such non-delivery reports, and if they are in the > > DSN format, automatically examine them to determine for which > > recipients a message delivery failed or was delayed. > > This is not sufficient for auto-responses, and given the following rfcs, it > would smart to both : > > - add an "Auto-Submitted: Python User Group" header, > - add or modify the Return-Path and/or Reply-To header for badly > implemented auto-responders to point to list maintainer. > Oh, no ! to the list itself of course. This could also avoid the common mistake mailing list users do in replying private mail accidentally when the adress of the list is only present in CC field. > RFC 3834: > > 4. Where to send automatic responses (and where not to send them) > > > > > > In general, automatic responses SHOULD be sent to the Return-Path > > field if generated after delivery. If the response is generated > > prior to delivery, the response SHOULD be sent to the reverse-path > > from the SMTP MAIL FROM command, or (in a non-SMTP system) to the > > envelope return address which serves as the destination for non- > > delivery reports. > > and > > > 5. The Auto-Submitted header field > > > > > > The purpose of the Auto-Submitted header field is to indicate that > > the message was originated by an automatic process, or an automatic > > responder, rather than by a human; and to facilitate automatic > > filtering of messages from signal paths for which automatically > > generated messages and automatic responses are not desirable. > > RFC 1123 : > > 5.3.7 Mail Gatewaying > > > > Gatewaying mail between different mail environments, i.e., > > different mail formats and protocols, is complex and does not > > easily yield to standardization. See for example [SMTP:5a], > > [SMTP:5b]. However, some general requirements may be given for > > a gateway between the Internet and another mail environment. > > > > (A) Header fields MAY be rewritten when necessary as messages > > are gatewayed across mail environment boundaries. > > > > DISCUSSION: > > This may involve interpreting the local-part of the > > destination address, as suggested in Section 5.2.16 > > I'm also frustrated by some (rare) of my mails which are actually blocked > for > > confirmation by a moderator with this message : > > Is being held until the list moderator can review it for approval. > > > > The reason it is being held: > > > > Message has a suspicious header > > I think it's probably my domain name which makes this, do the anti-spam > engine use whitelists ? How to resolve the problem if not ? I re-send this correction to my previous post because the first got held as spam, :' (, is there really a moderator, as the bounce says, and he decided to censor me ? -- _____________ Maric Michaud From a at nospam.org Tue Sep 16 07:10:37 2008 From: a at nospam.org (Armin) Date: Tue, 16 Sep 2008 13:10:37 +0200 Subject: append on lists In-Reply-To: <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> Message-ID: <gao3d0$7q1$1@online.de> Duncan Booth wrote: > "Chris Rebert" <clp at rebertia.com> wrote: >> On Tue, Sep 16, 2008 at 1:20 AM, Armin <a at nospam.org> wrote: >>> [1,2,3,4,7].append(c) -> Is this a valid expression? >> Literally, no, because you can't call methods on literals. > > Rubbish. There is no restriction about calling methods on literals. That > expression is perfectly valid but has no practical use that I can see. The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c (with c = [8,9]) is identical, but the first expression doesn't provide a value. Strange by design ... --Armin > > There is a syntax gotcha which you may have been thinking of: to call a > method on an integer literal (or indeed to access any attribute) you have > to use whitespace between the literal and the dot otherwise you have a > float literal and a syntax error. > >>>> 5 .__hex__() > '0x5' > > The only relatively common use I can think of where you might want to call > a method directly on a literal is to produce a list of strings while being > lazy about the typing: > > COLOURS = "red green blue pink yellow".split() > > versus > > COLOURS = ["red", "green", "blue", "pink", "yellow"] > > From grante at visi.com Fri Sep 26 21:34:56 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 26 Sep 2008 20:34:56 -0500 Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d@posted.visi> <gbjmdp$q1e$2@lust.ihug.co.nz> Message-ID: <dZOdnT0NKORdEEDVnZ2dnUVZ_rvinZ2d@posted.usinternet> On 2008-09-26, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote: > In message <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d at posted.visi>, Grant Edwards > wrote: > >> Never assume somebody reading the article and attempting to >> help you can see the subject line. > > Why not? Because it might not be. It depends on the user's newsreader and editor settings. Assuming the reader can't see the subject line while reading the article has been one of the basic rules of Usenet posting for decades. At least that's what I've always been told: make sure the body of a posting contains sufficient information to answer the question. -- Grant From lanny at freshells.ch Sat Sep 6 17:43:31 2008 From: lanny at freshells.ch (Lanny) Date: Sat, 6 Sep 2008 14:43:31 -0700 Subject: indices question References: <g9sgda$e9h$1@adenine.netfront.net> <cc9bc4bf-412e-44e9-ba6d-76352ec08fd4@26g2000hsk.googlegroups.com> Message-ID: <g9sqtn$1n8f$1@adenine.netfront.net> > Lanny: >> ... >> varcc = raw_input >> grid[varc] = 'O' >> ... >> Why can't I put a varible thats an integer instead? > > 'varcc' and 'varc' are different names. > > 'raw_input' isn't a function call, you may want to turn that into a > function call. > > varc isn't an integer, you may have to convert it to integer first, > using int(), because Python lists aren't like Lua ones, they are > represented with a sequence of cells, and an integer number is used to > denote what cells you want. Note that the cell must already exists > before accessing its contents. > > Maybe you want to use an associative array instead, named 'dict' in > Python, that allows you freedom in the type of the keys and allows you > to create cells on the fly. > > Surely my answer isn't enough to solve your problems, but it may give > you a starting point. > > Bye, > bearophile Thanks, this was very usefull -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From skip at pobox.com Sun Sep 14 09:21:37 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 14 Sep 2008 08:21:37 -0500 Subject: testing if another instance of a script is already running In-Reply-To: <ed010651-331a-4b81-bbce-086a5ffb6368@m3g2000hsc.googlegroups.com> References: <mailman.911.1221221070.3487.python-list@python.org> <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> <mailman.986.1221345275.3487.python-list@python.org> <ed010651-331a-4b81-bbce-086a5ffb6368@m3g2000hsc.googlegroups.com> Message-ID: <18637.4065.376526.515813@montanaro-dyndns-org.local> Aaron> Would it suffice to call 'os.open' with flags= _O_CREAT| _O_EXCL Aaron> ? Would that be platform-independent? I suspect it would be platform-independent but not NFS-safe. (The other solutions in lockfile might have NFS problems as well. In any case, lockfile provides a bit more functionality as well, including timeouts and the ability to break locks. Skip From ruqiang826 at gmail.com Thu Sep 11 05:31:23 2008 From: ruqiang826 at gmail.com (ruqiang826) Date: Thu, 11 Sep 2008 02:31:23 -0700 (PDT) Subject: how dump a program which is running in memory Message-ID: <0592abb3-c2f6-4977-8338-3aa1956a353c@b38g2000prf.googlegroups.com> hi I have written a service running backgroud to do something in linux. unfortunately?I deleted the source code by mistake, and I can still see the process running background using "ps aux" : username 13820 0.0 0.0 60368 2964 ? S Aug20 0:33 python ./UpdateJobStatus.py I wonder if there is some way to dump the programme "UpdateJobStatus.py" and get the source code back? Thanks a lot. From gogtesuyash at gmail.com Wed Sep 17 08:23:53 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 05:23:53 -0700 (PDT) Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <tvkf941kmehd7hcihihdiil6fjutbfkf6k@4ax.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> Message-ID: <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> On Aug 7, 12:40 am, mmm <mdbol... at gmail.com> wrote: > On Aug 5, 12:18 am, Tim Roberts <t... at probo.com> wrote: > > > >But when using smtp.gmail.com as the server I learned that any > > >@gmail.com address in the Cc: text block would > > >receive mail even if I changed the code to have the RECEIVERS list to > > >ignore the CC addresses or not include the gmail address in the CC > > >list as below > > > Interesting. If true, that is incorrect behavior. > > I ran some more tests and now I am pretty sure > > session.sendmail(SENDER, RECEIVERS, BODY) > > is only sending to the RECEIVERS list, ignoring the Cc: field in the > body (as it should) > > What fooled me is that I was using my own gmail account (i.e., > m... at gmail.com) as a Cc: field and not putting it in the RECEIVERS > list. It seems Gmail creates two links (or copies?) to the message: > (1) as it is stored in the SENT box (as it should since the message > was sent by my gmail account) and (2) another in my INBOX because the > mail reading software reads the Cc: field. > > Other smtp servers such as comcast do not create the stored SENT mail > and hence behave different in terms of how they treat Cc: fields of > the same account (m... at comcast.net in this case). > > Most important, using another gmail account (not m... at gmail.com) as a > Cc: field does not create another sent message (outside of what is in > the RECEIVERS field). > > Sorry for confusion, and I do appreciate the tips as I now see how > almost anything To:, Cc:, Bcc: combination can be handled by a proper > RECEIVERS list. > > Below is python code that can be used by anyone that wants to test > what I did (just fill in the SMTPuser and password variables) and > then check you gmail inbox > > import sys, os, glob, datetime, time > import smtplib > ## Parameters for SMTP session > port=587 > SMTPserver= 'smtp.gmail.com' > SMTPuser= '... at gmail.com' > pw= 'fill in here' > SENDER= SMTPuser > > ## Message details > FROM= SENDER > TO= 'notgm... at a.com' > CC=FROM > ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC > RECEIVERS= (TO,) ## ignore the CC address > > subject= 'Test 1a' > message='*** Email test *** ' > > print 'Starting SMTP mail session on %s as %s ' % > (SMTPserver,SMTPuser) > session = smtplib.SMTP(SMTPserver,port) > session.set_debuglevel(0) # set debug level to 1 to see details > session.ehlo(SMTPuser) # say hello > session.starttls() # TLS needed > session.ehlo(SMTPuser) # say hello again, not sure why > session.login(SMTPuser, pw) > > ##Create HEADER + MESSAGE > HEADER= 'From: %s\r\n' % FROM > HEADER= HEADER + 'To: %s\r\n' % TO > HEADER= HEADER + 'Cc: %s\r\n' % CC > HEADER= HEADER + 'Subject: %s\r\n' % subject > BODY= HEADER + '\r\n' + message > print BODY > > SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email > > session.close() i tried to run this code...but it didnt work it shows that message like starting smtp session then it doesnt show anything after very long time it shows Traceback (most recent call last): File "mail5.py", line 21, in <module> session = smtplib.SMTP(SMTPserver,port) File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect self.sock.connect(sa) File "<string>", line 1, in connect then conncetion time out..... can u tell me wats the prob ...plz tell me solun From tino at wildenhain.de Fri Sep 26 11:13:58 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 17:13:58 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> Message-ID: <48DCFC36.3070708@wildenhain.de> Michael Mabin wrote: > I laugh in the face of danger. > > Give me a use case for an exploit. .... (see below) > > On Fri, Sep 26, 2008 at 8:05 AM, Tino Wildenhain <tino at wildenhain.de > <mailto:tino at wildenhain.de>> wrote: > > Michael Mabin wrote: > > cursor.execute(""" > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """ % ','.join([str(x) for x in [1,5,9]]) > > > Nope. That would be dangerous! -> google for SQL injection > > Tino You are not seeing it? Do you know where the OP actually gets his list data from in the first place? You might get away with str(int(x)) as an easy "sanetizer" Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/a3c27d4a/attachment.bin> From a_jtim at bellsouth.net Wed Sep 24 21:27:24 2008 From: a_jtim at bellsouth.net (Tim Arnold) Date: Wed, 24 Sep 2008 18:27:24 -0700 (PDT) Subject: multiple processes, private working directories Message-ID: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> I have a bunch of processes to run and each one needs its own working directory. I'd also like to know when all of the processes are finished. (1) First thought was threads, until I saw that os.chdir was process- global. (2) Next thought was fork, but I don't know how to signal when each child is finished. (3) Current thought is to break the process from a method into a external script; call the script in separate threads. This is the only way I can see to give each process a separate dir (external process fixes that), and I can find out when each process is finished (thread fixes that). Am I missing something? Is there a better way? I hate to rewrite this method as a script since I've got a lot of object metadata that I'll have to regenerate with each call of the script. thanks for any suggestions, --Tim Arnold From joefazee at gmail.com Sat Sep 27 17:43:02 2008 From: joefazee at gmail.com (A. Joseph) Date: Sat, 27 Sep 2008 14:43:02 -0700 Subject: check if file is MS Word or PDF file Message-ID: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> What should I look for in a file to determine whether or not it is a MS Word file or an Excel file or a PDF file, etc., etc.? including Zip files I don`t want to check for file extension. os.path.splitext('Filename.jpg') will produce a tuple of filename and extension, but some file don`t even have extension and can still be read by MS Word or NotePad. i want to be 100% sure of the file. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080927/3980f9c9/attachment.html> From gopalm at infotechsw.com Thu Sep 4 05:28:13 2008 From: gopalm at infotechsw.com (gopal mishra) Date: Thu, 4 Sep 2008 14:58:13 +0530 Subject: cPickle Message-ID: <01f901c90e70$8e118a50$2fc513ac@pwit.com> I have 3 objects and want to save in one pickle file. I used cPickle to dump 3 objects in a pkl file i.e cPickle.dump(object1, fileobject, -1) cPickle.dump(object2, fileobject, -1) cPickle.dump(object3, fileobject, -1) I have changed the 3rd object and want to save the updated 3rd object in the pickle file. I have to dump all the 3 objects again. Is there any way to dump only the 3rd object in to the pkl file. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080904/c0f18b27/attachment.html> From ldo at geek-central.gen.new_zealand Fri Sep 26 18:06:49 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 27 Sep 2008 10:06:49 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d@posted.visi> Message-ID: <gbjmdp$q1e$2@lust.ihug.co.nz> In message <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d at posted.visi>, Grant Edwards wrote: > Never assume somebody reading the article and attempting to > help you can see the subject line. Why not? From callen314 at gmail.com Mon Sep 22 21:34:46 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 22 Sep 2008 18:34:46 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> It is clear to me that Python is a multiparadigmed object oriented language. It is clearly possible to write procedural code... that is, Python does not force object oriented syntax or concepts on you and insist you define everything in such a structure. Is the OO it allows full OO, I think so, and the only way to argue otherwise I think is to point out that the "main" function is just the module level itself, and is not part of an object... which is just the sort of pedantic things purists like to hang their hat on. personally I am very much the sort that believe in "trust the programmer" and likes languages that provide a freedom to use various complementary paradigms, in the style of C++. Compared to that, it's clear that Python is quite object oriented even in the sense of drawing you to build things in object oriented ways... just not strictly requiring it. Which is good, it allows some interesting patterns which play quite well with object oriented desirgn (i.e. module as singleton)... in fact, that plays so well as a singleton, some would say the module is just an object anyway, and indeed, the intepreter tends to agree. So python may turn out to be pure OO, where Objects SIMULATE procedural programming paradigms and allow that paradigm as a result, on top of OO. cheers. From python-pep at arcor.de Thu Sep 25 16:14:56 2008 From: python-pep at arcor.de (python-pep at arcor.de) Date: Thu, 25 Sep 2008 22:14:56 +0200 Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> <mailman.1508.1222373098.3487.python-list@python.org> Message-ID: <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> Gabriel Genellina wrote: > En Thu, 25 Sep 2008 16:24:58 -0300, <python-pep at arcor.de> escribi?: > >> sorry, I have these ideas for longer than 10 years, please have a look >> on it >> and comment on it. Thx. >> >> This is another proposal for introducing types into Python. > > You got the terminology wrong. Python had "types" from the very start. > You're talking about some kind of generic functions, or an alternative > dispatch method. Typed parameters. Method-Declaration-filtered-typed parameters. That's what I'm thinking of. I hear & I will answer. From gh at ghaering.de Fri Sep 5 19:30:18 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 06 Sep 2008 01:30:18 +0200 Subject: sqlite3 import performance In-Reply-To: <df87099b-4957-4f01-b9f2-e452bef064e9@v16g2000prc.googlegroups.com> References: <df87099b-4957-4f01-b9f2-e452bef064e9@v16g2000prc.googlegroups.com> Message-ID: <6idtobFq1f6tU1@mid.uni-berlin.de> Ben Lee wrote: > hi folks -- > > a quick python and sqlite3 performance question. i find that > inserting a million rows of in-memory data into an in-memory database > via a single executemany() is about 30% slower than using the sqlite3 > CLI and the .import command (reading the same data from a disk file, > even.) i find this surprising, executemany() i assume is using a > prepared statement and this is exactly what the .import command does > (based on my quick perusal of the source.) > > is this discrepancy to be expected? where is the overhead coming > from? [...] Ok, I'll bite. Well, first, the a 30 % slowdown with a Python DB-API wrapper compared to the native commandline tool of the database is to be considered still quite reasonable, in my opinion. About a year ago I compared the performance of pysqlite vs. the other SQLite wrapper, APSW. At the time, APSW was a bit faster, not excessively, but measurable. In meaningless benchmarks like yours ;-) So I changed pysqlite here and there to get the same performance as APSW. Only minor tweaks, nothing spectacular. And a few hardcore tricks as well, like special-casing *not-subclassed* classes. The result was pysqlite 2.3.5: http://oss.itsystementwicklung.de/trac/pysqlite/wiki/2.3.5_Changelog These optmizations are not yet in Python 2.5.x, but they can be found in the sqlite3 module of the Python 2.6/3.0 betas. Well, here are my results of your benchmark :-) -- Gerhard # with Python 2.5.2's sqlite3 module gerhard at lara:~/tmp$ python t.py generating data... done! testing 1000000 inserts... [42.795290946960449, 44.337385892868042, 46.35642409324646] # with pysqlite 2.5.0, which I released earlier today gerhard at lara:~/tmp$ python t.py generating data... done! testing 1000000 inserts... [33.027599096298218, 32.73675012588501, 32.823790073394775] # SQLite commandline gerhard at lara:~/tmp$ time sqlite3 -init sqlcmds ':memory:' '.quit' real 0m32.514s gerhard at lara:~/tmp$ time sqlite3 -init sqlcmds ':memory:' '.quit' real 0m32.576s gerhard at lara:~/tmp$ time sqlite3 -init sqlcmds ':memory:' '.quit' real 0m32.604s From miki.tebeka at gmail.com Thu Sep 18 19:35:48 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 18 Sep 2008 16:35:48 -0700 (PDT) Subject: Python newbie question re Strings and integers References: <c0287f45-1c5a-40b5-aff3-ab5639d26749@k13g2000hse.googlegroups.com> Message-ID: <7c66014b-bfcf-40ef-aca9-16f3f749c7ac@b2g2000prf.googlegroups.com> > ? ? currentSymbol=filename[int(filenameStart),int(extensionStart)] Should be currentSymbol=filename[int(filenameStart):int(extensionStart)] (change , to :) You don't need to convert to int all the time, rfind will return an integer. Also you can use os.path for this from os.path import basename, splitext currentSymbol = splitext(basename(filename))[0] HTH, -- Miki <miki.tebeka at gmail.com> http://pythonwise.blogspot.com From kqanh at yahoo.com Tue Sep 30 23:48:12 2008 From: kqanh at yahoo.com (Anh Khuong) Date: Tue, 30 Sep 2008 20:48:12 -0700 (PDT) Subject: Output of pexpect Message-ID: <285898.28621.qm@web50802.mail.re2.yahoo.com> Hi all, I am using pexpect and I want to send output of pexpet to both stdout and log file concurrently. Anybody know a solution for it please let me know. Thanks From castironpi at gmail.com Fri Sep 12 23:08:27 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 12 Sep 2008 20:08:27 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? References: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> Message-ID: <b2a326bf-8b80-4b1c-9896-d5056bb3237a@w7g2000hsa.googlegroups.com> On Sep 12, 8:08?pm, i... at illusorygoals.com wrote: > First off, I'm a python n00b, so feel free to comment on anything if > I'm doing it "the wrong way." I'm building a discrete event simulation > tool. I wanted to use coroutines. However, I want to know if there's > any way to hide a yield statement. > > I have a class that I'd like to look like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? result = self.ping("128.111.41.38") > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > But because I can't hide yield inside ping, and because I can't find a > convenient way to get a self reference to the coroutine (which is used > by the event queue to pass back results), my code looks like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? # I dislike this next line > ? ? ? ? self.this_pointer = (yield None) > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? # I want to get rid of the yield in the next line > ? ? ? ? ? ? result = (yield self.ping("128.111.41.38")) > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > I posted a more detailed version of this as a rant here:http://illusorygoals.com/post/49926627/ > > I'd like to know, is there a way to get the syntax I want? After > staying up late last night to get a proof-of-concept working with > coroutines, my boss expressed disappointment in the ugliness of the > Pinger code (we agreed on the desired syntax above). I spent almost 2 > hours today to migrate the system over to threads. That made my boss > happy, but I'm still curious if I can do something to salvage the > coroutine version. > > Regards, > IG I did not read you whole post though I did skim your link. I don't know your whole problem but it seems you are trying to inform a generator of its own identity. Here's a solution to that problem; perhaps it relates to yours. (The shorter retort is, "Just use closures.") def gen( ): def _gen( ): while 1: yield 1, 'i am %r'% ob yield 2, 'i am %r'% ob yield 3, 'i am %r'% ob ob= _gen( ) return ob gens= [ gen( ) for _ in range( 4 ) ] for i in range( 6 ): print i for g in gens: print g.next( ) /Output (lengthy): 0 (1, 'i am <generator object at 0x009FEC10>') (1, 'i am <generator object at 0x009FEC38>') (1, 'i am <generator object at 0x009FEC60>') (1, 'i am <generator object at 0x009FEC88>') 1 (2, 'i am <generator object at 0x009FEC10>') (2, 'i am <generator object at 0x009FEC38>') (2, 'i am <generator object at 0x009FEC60>') (2, 'i am <generator object at 0x009FEC88>') 2 (3, 'i am <generator object at 0x009FEC10>') (3, 'i am <generator object at 0x009FEC38>') (3, 'i am <generator object at 0x009FEC60>') (3, 'i am <generator object at 0x009FEC88>') 3 (1, 'i am <generator object at 0x009FEC10>') (1, 'i am <generator object at 0x009FEC38>') (1, 'i am <generator object at 0x009FEC60>') (1, 'i am <generator object at 0x009FEC88>') 4 (2, 'i am <generator object at 0x009FEC10>') (2, 'i am <generator object at 0x009FEC38>') (2, 'i am <generator object at 0x009FEC60>') (2, 'i am <generator object at 0x009FEC88>') 5 (3, 'i am <generator object at 0x009FEC10>') (3, 'i am <generator object at 0x009FEC38>') (3, 'i am <generator object at 0x009FEC60>') (3, 'i am <generator object at 0x009FEC88>') From support at mysfdomain.com Wed Sep 17 16:12:49 2008 From: support at mysfdomain.com (support at mysfdomain.com) Date: Wed, 17 Sep 2008 13:12:49 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: <mailman.1150.1221614920.3487.python-list@python.org> <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> <mailman.1179.1221675641.3487.python-list@python.org> Message-ID: <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> On Sep 17, 1:21?pm, Todd Whiteman <to... at activestate.com> wrote: > Don Spaulding wrote: > > On Sep 16, 8:29 pm, Todd Whiteman <to... at activestate.com> wrote: > >> I've put together a tutorial that shows off how to build a GUI > >> application using XULRunner (same architectural components as Firefox > >> uses) that can be used in conjunction with the Python programming language. > > >> The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > > I get to the "Running" step and run into "Couldn't load XPCOM." > > > Does this work on x86_64? ?Or have I made a rookie mistake? > > Hi Don, > > A good question. Mozilla only provide 32-bit XulRunner applications by > default, you you'll need to install the necessary 32-bit compatability > libraries on your Linux machine, i.e. for Ubuntu it's something like: > sudo apt-get install ia32-libs ia32-libs-gtk > > Then you should be able to run the example. You can check the > dependencies using something the following commands, there should be no > missing dependencies: > $ cd pyxpcom_gui_app/xulrunner > $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin > > It is possible to use a 64-bit version, but you'll need to compile this > yourself (or find somewhere that provides these x86_64 versions). Note > that the PythonExt project does not offer Python bindings for x86_64 > either (it's on my todo list), you can compile the PythonExt part > yourself as well if you need a 64-bit version. > > Cheers, > Todd Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs and ia32-libs-gtk installed. ldd shows that I'm missing the following libs, even though the proper packages are installed, and the files show up in /usr/lib. libxcb-render-util.so.0 => not found libxcb-render.so.0 => not found There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render- util, so I wonder if that could be part of the problem? Don /me never knew how to get out of DLL hell on Windows either ;-) From rstarkov at gmail.com Sun Sep 14 02:50:28 2008 From: rstarkov at gmail.com (rs387) Date: Sat, 13 Sep 2008 23:50:28 -0700 (PDT) Subject: Stuck connection in Python 3.0b2 http.server Message-ID: <1a23cbe5-26f5-4332-8901-7aa06c69d68e@k7g2000hsd.googlegroups.com> Hi All I've encountered a weird issue when migrating a web server to Python 3 - the browser would wait forever without showing a page, displaying "Transferring data" in the status bar. I tracked it down to a reference cycle in my BaseHTTPRequestHandler descendant - one of the attributes stored a dict of methods. Removing the cycle made the problem go away. In Python 2.5.2 the code works fine either way. Here's a minimal example which runs in both 2.5 and 3.0 - to see stuck connections run as-is in 3.0 and navigate to http://localhost:8123; to fix this comment out "self.dummy = self" (alternatively reset self.dummy = None at the end of the __init__ method). Am I doing it wrong, or is this a bug? try: import http.server httpmodule = http.server except: import BaseHTTPServer httpmodule = BaseHTTPServer class BreakageRequest(httpmodule.BaseHTTPRequestHandler): def __init__(self, request, client_address, server): self.dummy = self # COMMENT THIS OUT to see the connection become unstuck httpmodule.BaseHTTPRequestHandler.__init__(self, request, client_address, server) def do_GET(self): self.send_response(200) self.send_header("Content-Type", "application/xml") self.end_headers() self.wfile.write("<is_it_stuck/>".encode('utf-8')) srv = httpmodule.HTTPServer(('', 8123), BreakageRequest) srv.serve_forever() From steve at REMOVE-THIS-cybersource.com.au Thu Sep 4 05:24:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 09:24:28 GMT Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <mailman.375.1220375272.3487.python-list@python.org> Message-ID: <00cfa3b9$0$20302$c3e8da3@news.astraweb.com> On Tue, 02 Sep 2008 13:07:33 -0400, Joe Riopel wrote: > On Tue, Sep 2, 2008 at 12:55 PM, Steven D'Aprano > <steve at remove-this-cybersource.com.au> wrote: >> Is there a better way of doing this than the way I am going about it? > > Would the logging module help, and just print the output to the stdout > (or a file) instead? Thank you to everyone who answered. As I feared, it seems that there's no really simple way of dealing with arbitrary messages at arbitrary parts of my code. I'm currently playing around with a few ideas, one of which is a decorator to print information about function calls. However, what I'd like to avoid is having to explicitly call the decorator on every method. I guess that there's metaclass trickery I can play. Does anyone have any pointers on how I can apply a decorator to every method in a class automatically? -- Steven From m_palmer45 at yahoo.ca Mon Sep 22 09:44:39 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 22 Sep 2008 06:44:39 -0700 (PDT) Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> Message-ID: <78547919-be84-41ac-955b-78824d64b4b8@y21g2000hsf.googlegroups.com> On Sep 22, 4:02 am, Al Kabaila <akaba... at pcug.org.au> wrote: > This is a very active newsgroup that incudes such giants as Frederik Lundh He looks rather small to me in this picture: http://www.python.org/~guido/confpix/flundh-2.jpg From m_palmer45 at yahoo.ca Fri Sep 12 18:53:00 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 12 Sep 2008 15:53:00 -0700 (PDT) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <8a81f213-4ea2-4808-b92f-f001fac3fe0c@x41g2000hsb.googlegroups.com> On Sep 12, 11:08 am, Bojan Mihelac <bmihe... at gmail.com> wrote: > Hi all - when trying to set some dynamic attributes in class, for > example: > > class A: > for lang in ['1', '2']: > exec('title_%s = lang' % lang) #this work but is ugly > # setattr(A, "title_%s" % lang, lang) # this wont work > > setattr(A, "title_1", "x") # this work when outside class > > print A.title_1 > print A.title_2 > > I guess A class not yet exists in line 4. Is it possible to achive > adding dynamic attributes without using exec? > > thanks, > Bojan Is it really worth it? If the names of the attributes are only known at runtime, why not just use a dict - that's what they are for. If you want a dict plus some special behaviour, just write a class that inherits from dict, or use UserDict.DictMixin. From lists at cheimes.de Fri Sep 5 19:54:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 06 Sep 2008 01:54:10 +0200 Subject: indices question In-Reply-To: <g9sgda$e9h$1@adenine.netfront.net> References: <g9sgda$e9h$1@adenine.netfront.net> Message-ID: <g9sgr2$6fb$1@ger.gmane.org> Lanny wrote: > Please don't tell me that "list indices must be integers" because I know > that, Why can't I put a varible thats an integer instead? raw_input() always returns a string. You have to convert the string into an integer using int(). Christian From python at rgbaz.eu Sun Sep 7 11:13:12 2008 From: python at rgbaz.eu (Python) Date: Sun, 7 Sep 2008 17:13:12 +0200 Subject: modules path In-Reply-To: <op.ug30i0hqx6zn5v@a98gizw.cpe.telecentro.net.ar> References: <mailman.626.1220738606.3487.python-list@python.org> <a6c1143a-bb64-4b9c-953e-831c6a74d741@a3g2000prm.googlegroups.com> <ADE2F843-E0B0-4679-9113-6AEBAC95DC09@rgbaz.eu> <op.ug30i0hqx6zn5v@a98gizw.cpe.telecentro.net.ar> Message-ID: <2AC6A5D0-A7EC-43C9-9948-99A5BCF82AD7@rgbaz.eu> On 7 sep 2008, at 13:50, Gabriel Genellina wrote: > En Sat, 06 Sep 2008 20:26:24 -0300, Python <python at rgbaz.eu> escribi?: > >> now one question came up, how do I make those path permanent? >> i mean, sys.path.append(<path)> adds it for the current session, >> yet when i logout of IDLE and start it again it's gone... >> how do i keep it in there? > > You can add that path to the PYTHONPATH environment variable, or you > can put a .pth file in the current Lib directory, containing the > desired path. > See http://docs.python.org/inst/search-path.html and the > documentation for the site module (although it appears not to be > totally accurate). > > -- > Gabriel Genellina > i read that but was wondering why some modules installed by macports did show up in the path and some didn't the PYTHONPATH wasn't set anywhere in my shell I did add it and now it works! Thanks John & Gabriel! gr Arno From fredrik at pythonware.com Thu Sep 4 17:53:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 23:53:33 +0200 Subject: Is it possible to download only the <head> of a web page? In-Reply-To: <d10e6046-fef2-46b8-a6ed-876afa93aa17@v16g2000prc.googlegroups.com> References: <d10e6046-fef2-46b8-a6ed-876afa93aa17@v16g2000prc.googlegroups.com> Message-ID: <g9plcu$uma$1@ger.gmane.org> Rex wrote: > I am writing a script that executes a bunch of queries through a form > on a website and reads the results. I am only interested in the > <title> section in the <head> of each web page. Currently, each page > the server returns is about 100kb and contains a bunch of HTML and > Javascript, all of which I don't need; I don't want to waste bandwidth > or consume too much of the server's resources. I just need the <title> > string. you need to issue a GET request to get the HTML head section, which almost always means that the server will build the entire page before sending it to you (so it can set content-length etc). you can save on network traffic by parsing the data as it arrives, and stopping when you've gotten the TITLE element: http://effbot.org/librarybook/sgmllib.htm </F> From apardon at forel.vub.ac.be Mon Sep 22 03:52:54 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 22 Sep 2008 07:52:54 GMT Subject: flock trouble References: <1460c93c-af24-40a3-8be4-31d582d48cb1@y21g2000hsf.googlegroups.com> Message-ID: <slrngdejn4.b8q.apardon@rcpc42.vub.ac.be> On 2008-09-08, Seb <sebastianthegreatful at gmail.com> wrote: > I'm trying to implement a file server using the code below. However > the locking doesn't work. I can delete while put'ing a file. > > Anyone got an idea about why? > [code snipped] As far as I understand you are writing some kind of server. What isn't clear is whether the daemon is using threading or forking to handle multiple requests. If I remember correctly, flock doesn't work well with multiple threads. -- Antoon Pardon From dear.jay.logan at gmail.com Mon Sep 22 09:55:13 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 22 Sep 2008 06:55:13 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <87myi0z4tq.fsf@mulj.homelinux.net> Message-ID: <dfe26463-49fa-4f79-8b55-ac098d6808fb@26g2000hsk.googlegroups.com> On Sep 22, 9:29?am, Hrvoje Niksic <hnik... at xemacs.org> wrote: > josh logan <dear.jay.lo... at gmail.com> writes: > > sorted(P) # throws TypeError: unorderable types Player() < Player() > > > The sorted function works when I define __lt__. > > I must be misreading the documentation, because I read for the > > documentation __cmp__ that it is called if none of the other rich > > comparison functions are defined. > > Is this a bug in Python 3.0rc1, or am I missing something? > > What documentation are you referring to, exactly? ?The whole __cmp__ > thing was supposed to be removed from Python 3, so mention of it > sounds like a documentation bug. > > > Secondly, say that we suddenly need another sorting order, where we > > want to sort by decreasing score and then by DECREASING last name > > (instead of increasing last name, defined above). Now that the > > comparison function argument is taken away from the sorted builtin, > > how do we accomplish this with the "key" parameter? > > By calling sort twice on the sequence: > > lst.sort(key=lambda x: x.score) > lst.sort(key=lambda x: x.last_name, reverse=True) > > As much as I like the key argument, I believe it was a mistake to > remove cmp, simply because it was the more general mechanism. > Emulating cmp with key is possible, but it requires creating a bunch > of objects for each sort. ?(I'm aware that list.sort caches the > calculated keys, but it still has to create as many of them as there > are list items.) It looks like __cmp__ is still in the documentation, and it seems to work somewhat in Python 3.0rc1. Here is the link to the documnetation http://docs.python.org/dev/3.0/reference/datamodel.html#object.__cmp__ From timothy.grant at gmail.com Thu Sep 4 13:15:02 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 4 Sep 2008 10:15:02 -0700 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <3f0d61c40809040409v3ee40da3h7eb0703009e78f06@mail.gmail.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <3f0d61c40809040409v3ee40da3h7eb0703009e78f06@mail.gmail.com> Message-ID: <e775286d0809041015t5d3b7945h9956cf36632bd53@mail.gmail.com> On Thu, Sep 4, 2008 at 4:09 AM, Marco Bizzarri <marco.bizzarri at gmail.com> wrote: > Sorry... pressed enter but really didn't want to. > > As I said, let's say I have a class > > class A: > def __init__(self): > self.x = None > > > > Python makes the decision to allow the developers to directly access > the attribute "x", so that they can directly write: "a.x = 1", or > whatever; this has for me the unfortunate side effect that if I write, > for example "a.y = 1", when I really wanted to write "a.x = 1" no one > cares about it, and I'm unable to spot this error until later. > > Of course, I know that while I'm fresh, I've a good knowledge of the > code, and anything else, I will be able to avoid such stupid errors; > however, I'm afraid of the times when I'm tired, when I have to put my > hands on the code of someone else, and so on. > > Please, understand that I'm not stating that python is wrong... after > all, if it is wrong, I can move to a language like Java, which has a > different approach on it. I'm really very interested in reading past > discussion on it, if they are available. > > Regards > Marco I think the most obvious solution to the problem is effective unit tests. If you type "a.y =1" and have a test that asserts a.x == 1 then you would quite quickly discover that you made a typo. -- Stand Fast, tjg. [Timothy Grant] From mkbernard.dev at gmail.com Sun Sep 7 20:47:28 2008 From: mkbernard.dev at gmail.com (MK Bernard) Date: Sun, 7 Sep 2008 17:47:28 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <f8c5f1de-d358-468b-81fd-aa8108d8f7e0@q26g2000prq.googlegroups.com> Message-ID: <dde588e9-84eb-4890-ac42-21dd2aec35c6@q26g2000prq.googlegroups.com> On Sep 7, 3:37?pm, John Machin <sjmac... at lexicon.net> wrote: > On Sep 8, 7:51?am, "andyh... at gmail.com" <andyh... at gmail.com> wrote: > > > > > Hello... > > > I have a dict of key/values and I want to change the keys in it, based > > on another mapping dictionary. An example follows: > > > MAPPING_DICT = { > > ? ? 'a': 'A', > > ? ? 'b': 'B', > > > } > > > my_dict = { > > ? ? 'a': '1', > > ? ? 'b': '2' > > > } > > > I want the finished my_dict to look like: > > > my_dict = { > > ? ? 'A': '1', > > ? ? 'B': '2' > > > } > > > Whereby the keys in the original my_dict have been swapped out for the > > keys mapped in MAPPING_DICT. > > > Is there a clever way to do this, or should I loop through both, > > essentially creating a brand new dict? > > Is this homework? > > There seems to be an implicit assumption in the answers so far that > your mapping is a 1:1 mapping of all possible input keys. > > If it doesn't include all possible input keys, answers will crash with > a KeyError. If there are any many:1 elements in the mapping (for > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > in some checks for this. Thats exactly why I did an explicit check in my post, so as to make sure that such a collision could not occur. It would seem that something along what I posted would be safer, if less elegant, than the others. Cheers, MK From mail at nospam.glenstark.net Tue Sep 9 03:31:12 2008 From: mail at nospam.glenstark.net (glen stark) Date: 9 Sep 2008 09:31:12 +0200 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <yfs63pcwyip.fsf@gmail.com> <mailman.716.1220913165.3487.python-list@python.org> Message-ID: <48c62640_1@news.bluewin.ch> On Tue, 09 Sep 2008 08:32:29 +1000, Tom Harris wrote: > I agree. So did Forth's early designers. That is why Forth's number > parser considers a word that starts with a number and has embedded > punctuation to be a 32 bit integer, and simply ignores the punctuation. > I haven't used Forth in years, but it seems a neat solution to the > problem of decoding a long string of numbers: let the user put in > whatever they want, the parser ignores it. I usually used a comma (with > no surrounding whitespace of course), but it was your choice. You could > also do this in whatever base you were working in, so you could > punctuate a 32 bit hex number to correspond to the bit fields inside it. > Of course not applicable to Python. That sounds like a great idea, except I'd specify non-period (.) punctuation, so it would go for floating points as well. Is there a language design guru who can say why inputs like 123,456.00 couldn't be handles as above? the only problem I can see is an abiguity in argument lists (e.g. mult(2,4) ) which could be handled by the inclusion of whitespace. From http Fri Sep 26 13:11:15 2008 From: http (Paul Rubin) Date: 26 Sep 2008 10:11:15 -0700 Subject: how to search multiple textfiles ? References: <mailman.1536.1222436146.3487.python-list@python.org> Message-ID: <7xd4iqj0i4.fsf@ruckus.brouhaha.com> Stef Mientki <s.mientki at ru.nl> writes: > Does anyone know of a search library that performs this task fast ? You mean you want a Python search engine (with inverted indexes and all that)? Try: nucular.sf.net From mail at timgolden.me.uk Wed Sep 24 15:20:17 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 24 Sep 2008 20:20:17 +0100 Subject: Linq to Python In-Reply-To: <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <48DA92F1.1060501@timgolden.me.uk> bearophileHUGS at lycos.com wrote: > sturlamolden: >> No, because Python already has list comprehensions and we don't need the XML buzzword.< > > LINQ is more than buzzwords. Python misses several of those features. > So maybe for once the Python crowd may recognize such C# feature as > much better than things present in Python. > Said that, I presume Python will go on as usual, and LINQ-like > capabilities will not be integrated in Python. In the meantime where I > live lot of people will keep using C# instead of Python and CLisp, > natural selection at work indeed. Perhaps a quick summary of what LINQ offers which might "be integrated into Python" would help those of us who are ignorant? (This is a serious comment; I'd like to know). TJG From kyosohma at gmail.com Thu Sep 4 09:34:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Sep 2008 06:34:59 -0700 (PDT) Subject: Access to Windows "Add/Remove Programs"? References: <cf08e654-d2d5-48fe-a2ac-919fd2479254@v13g2000pro.googlegroups.com> <mailman.454.1220494440.3487.python-list@python.org> <e31f2517-23a3-459c-9c6f-bcb7233d0f82@w24g2000prd.googlegroups.com> Message-ID: <d0947bac-67ab-4e56-85e6-06752c08eca4@p10g2000prf.googlegroups.com> On Sep 3, 9:41?pm, Sean DiZazzo <half.ital... at gmail.com> wrote: > On Sep 3, 7:13?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > > > > > En Wed, 03 Sep 2008 21:51:59 -0300, Sean DiZazzo <half.ital... at gmail.com> ? > > escribi : > > > > I'm trying to find a way to get a list of all the installed programs > > > on a Windows box via Python. ?I thought of a few hacks that might > > > partially work, and then thought about "Add/Remove Programs" ?Seems > > > like the right way to go. ?I looked over the pywin32 docs a bit, but > > > nothing slapped me in the face. > > > > Is there any reliable way to get at that info? > > > You may enumerate the entries under this registry key: > > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall > > > -- > > Gabriel Genellina > > Thank both of you. ?Perfect! > > ~Sean I have used both of these methods, but it should be noted that not all programs register themselves in the registry. The usual suspects are spyware related. But there are still a few programs that you can just download and unzip that don't write anything to the registry. But this does work for probably 99% of programs on Windows. Mike From code at pizzashack.org Fri Sep 26 15:25:08 2008 From: code at pizzashack.org (Derek Martin) Date: Fri, 26 Sep 2008 15:25:08 -0400 Subject: Test if list contains another list In-Reply-To: <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> <48c6380b$0$17080$426a34cc@news.free.fr> <mailman.741.1220976622.3487.python-list@python.org> <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> Message-ID: <20080926192508.GK26713@dragontoe.org> On Thu, Sep 18, 2008 at 03:24:16AM -0700, gauravatnet at gmail.com wrote: > I looked inside this thread for my query which brought me the > following google search result > "Test if list contains another list - comp.lang.python | Google > Groups" > > But then I was disappointed to see the question asked was not exactly > right. [...] > def findAllMatchingList(mainList, subList): > resultIndex = [] > globalIndex = 0 > for i in range(len(mainList)): > if i < globalIndex: > continue > globalIndex = i > increment = 0 > for j in range(len(subList)): > if mainList[globalIndex] == subList[j]: > globalIndex += 1 > increment += 1 > if j == (len(subList)-1): > resultIndex.append(globalIndex-increment) > else: > break > > return resultIndex I didn't time them to compare, but how about this instead: >>> def find_needle_in_haystack(needle, haystack): ... r = [] ... L = len(needle) ... for i in range(len(haystack)): ... if haystack[i:i+L] == needle: ... r.append(i) ... return r >>> # this fails because "3" is not 3... >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,"3","9"]) [] >>> find_needle_in_haystack([1,2,3], [1,2,3]) [0] >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,3,"9"]) [2] >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,3,"9","q",1,2,3]) [2, 7] -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/48921ad9/attachment.sig> From kay.schluehr at gmx.net Thu Sep 4 01:49:21 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 3 Sep 2008 22:49:21 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <b367b494-66ba-4bd0-a724-9bc77fcea97a@b30g2000prf.googlegroups.com> On 3 Sep., 18:34, Michael Palmer <m_palme... at yahoo.ca> wrote: > As anyone knows, the state of Python GUI programming is a little > fractured at this time, with many toolkits, wrappers and meta-wrappers > dead and alive, with or without documentation. A few thoughts. 1) This topic is discussed here every few months. While some kind of AnyGUI is theoretically very elegant it hasn't worked out well in practice: GUI libs are huge and heterogeneous. It's much unlike building an API-layer on top of SQL. Moreover I'd like to ask whether the fragmentation turns out to be that much of a problem in practice? 2) Tcl/Tk might have a revival due to the new Tk-theme engine in version 8.5. http://www.tcl.tk/software/tcltk/8.5.tml http://wiki.tcl.tk/13636 Chances are Tkinter widgets will not look like early '90s legacy anymore. 3) Following the public rumor mill and the latest hype RIA i.e. the merge of web- and desktop applications with systems like Adobe AIR, JavaFX, Google Gears and MS Silverlight is the future of frontend development. With the exception of IronPython and Silverlight, Python hasn't even entered this game and no one knows if it ever will. Ciao, Kay From luigi at lambrate.inaf.it Wed Sep 3 08:31:02 2008 From: luigi at lambrate.inaf.it (Luigi Paioro) Date: Wed, 03 Sep 2008 14:31:02 +0200 Subject: Custom handler for logging Message-ID: <48BE8386.6010305@lambrate.inaf.it> Dear all, concerning the logging module, I have written a new Handler which stores the logging messages in an SQLite database. It works well, but when I try to use it exploiting a configuration file I have a problem since the "class" entry does not accept a class which is not within the logging name-space, while the class I implemented is coded in my personal module (thus another name-space). Is there a workaround to allow the usage of custom handlers? Thanks in advance. Luigi From bearophileHUGS at lycos.com Mon Sep 1 21:34:40 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Sep 2008 18:34:40 -0700 (PDT) Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> Ben Finney: > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > literals. It's not just my familiarity, Ada language too uses underscore for that purpose, I think, so there's a precedent, and Ada is a language designed to always minimize programming errors, simple code mistakes too. And another thing to consider is that they so far have given me zero problems... Consider: a = 125 125 125 a = 125, 125, 125 a = 125_125_125 For me the gestalt of the first line looks too much like the second one, that is three separated things (note that this is relative to the font you use, I am using a really good free font, Inconsolata, the very best I have found to program (better than Consolas) that separates things well). While in the third case the _ helps glue the parts, creating a single gestalt to my eyes. Note that it's not just a matter of font and familiarity, it's also a matter of brains. Your brain may be different from mine, so it may be possible that what's better for you isn't better for me. So in such situation a popular voting may be the only way to choose. But for me having spaces to split number literals in parts is _worse_ than not having any way at all to split them. So I'm strong opposed to your suggestion, so I may not even propose the PEP if lot of people agrees with your tastes. Bye, bearophile From pladow at gmail.com Mon Sep 15 11:58:10 2008 From: pladow at gmail.com (PlayDough) Date: Mon, 15 Sep 2008 08:58:10 -0700 (PDT) Subject: Segfault in vgetargskeywords Message-ID: <b65fcd21-deb5-49a9-ac95-0ddc6c8e329c@8g2000hse.googlegroups.com> I am using ActivePython 2.5.1 (python --version returns 'Python 2.5.1') and I am trying to embed/extend. It is segfaulting in vgetargkeywords during the call to Py_Initialize(). Now, we are using a non-standard configuration, and perhaps some explanation is in order. Here's our system config (via 'uname -a' with the hostname stripped): Linux xxx.xxx.com 2.6.9-67.0.4.ELsmp #1 SMP Fri Jan 18 05:00:58 EST 2008 i686 i686 i386 GNU/Linux Or from the syslog: Linux version 2.6.9-67.0.4.ELsmp (brewbuilder at hs20- bc2-4.build.redhat.com) (gcc version 3.4.6 20060404 (Red Hat 3.4.6-9)) #1 SMP Fri Jan 18 05:00:58 EST 2008 I've already run into the problem linking because of the __ctype_b issue, but I think I've worked around that with '-Wl,-wrap' (at least it links). Here's the compilation command line I am doing: gcc -ggdb -O0 `python-config --includes` -o main main.c `python- config --ldflags` -Wl,-wrap,__ctype_b -Wl,-wrap,__ctype_tolower -Wl,- wrap,__ctype_toupper Where GCC is: gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-9) And the code is just a single call to Py_Initialize(). There is the additional code to handle the wrap of __ctype_b: #include #include int main(int argc, char *argv[]) { Py_Initialize(); return 0; } __const unsigned short int **__wrap___ctype_b(void) { return __ctype_b_loc(); } __const __int32_t **__wrap___ctype_tolower(void) { return __ctype_tolower_loc(); } __const __int32_t **__wrap___ctype_toupper(void) { return __ctype_toupper_loc(); } So, after compiling, when I run it it coredumps with a segfault. Looking at the stack trace with gdb yields: GNU gdb Red Hat Linux (6.3.0.0-1.153.el4_6.2rh) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/tls/libthread_db.so.1". warning: exec file is newer than core file. Core was generated by `./sharc2'. Program terminated with signal 11, Segmentation fault. Reading symbols from /lib/tls/libpthread.so.0...done. Loaded symbols for /lib/tls/libpthread.so.0 Reading symbols from /lib/libdl.so.2...done. Loaded symbols for /lib/libdl.so.2 Reading symbols from /lib/libutil.so.1...done. Loaded symbols for /lib/libutil.so.1 Reading symbols from /lib/tls/libm.so.6...done. Loaded symbols for /lib/tls/libm.so.6 Reading symbols from /lib/tls/libc.so.6...done. Loaded symbols for /lib/tls/libc.so.6 Reading symbols from /lib/ld-linux.so.2...done. Loaded symbols for /lib/ld-linux.so.2 #0 0x080efbe3 in vgetargskeywords (args=0x40032c5c, keywords=0x0, format=0x812bf04 "|OOOi:__import__", kwlist=0x814ff84, p_va=0xbffff1c4, flags=0) at Python/getargs.c:1382 1382 Python/getargs.c: No such file or directory. in Python/getargs.c (gdb) bt #0 0x080efbe3 in vgetargskeywords (args=0x40032c5c, keywords=0x0, format=0x812bf04 "|OOOi:__import__", kwlist=0x814ff84, p_va=0xbffff1c4, flags=0) at Python/getargs.c:1382 #1 0x080efab1 in PyArg_ParseTupleAndKeywords (args=0x40032c5c, keywords=0x0, format=0x812bf03 "s|OOOi:__import__", kwlist=0x814ff84) at Python/getargs.c:1251 #2 0x080d6551 in builtin___import__ (self=0x0, args=0x40032c5c, kwds=0x0) at Python/bltinmodule.c:44 #3 0x0808ca6b in PyCFunction_Call (func=0x40025e6c, arg=0x40032c5c, kw=0x0) at Objects/methodobject.c:77 #4 0x080634d9 in PyObject_CallFunctionObjArgs (callable=0x40025e6c) at Objects/abstract.c:1860 #5 0x080f46f7 in PyImport_Import (module_name=0x40032b38) at Python/import.c:2570 #6 0x080f5319 in PyImport_ImportModule (name=0x8122fcb "__builtin__") at Python/import.c:1966 #7 0x0806f879 in _PyExc_Init () at Objects/exceptions.c:2061 #8 0x0804d5c9 in Py_InitializeEx (install_sigs=1) at Python/ pythonrun.c:228 #9 0x0804f43d in Py_Initialize () at Python/pythonrun.c:321 #10 0x0804d2c9 in main (argc=1, argv=0xbffff474) at main.c:22 Any ideas what is causing this problem? It appears to be while importing the __builtin__ package, but beyond that I'm not sure. From steven at REMOVE.THIS.cybersource.com.au Tue Sep 9 03:41:41 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Sep 2008 07:41:41 GMT Subject: Correcting for Drift between Two Dates References: <pgnxk.9513$cn7.668@flpi145.ffdc.sbc.com> Message-ID: <pan.2008.09.09.07.41.41@REMOVE.THIS.cybersource.com.au> On Mon, 08 Sep 2008 21:53:18 -0700, W. eWatson wrote: > I have two dates, ts1, ts2 as below in the sample program. I know the > clock drift in seconds per day. I would like to calculate the actual > date of ts2. See my question at the end of the program. When faced with a complicated task, break it down into simpler subtasks. Functions are your friends. Here you go: from __future__ import division from datetime import datetime as DT from datetime import timedelta SITE_DRIFT = 4.23 # drift in seconds per day # negative drift means the clock falls slow SEC_PER_DAY = 60*60*24 # number of seconds per day def calc_drift(when, base, drift=SITE_DRIFT): """Return the amount of drift at date when since date base.""" x = when - base days = x.days + x.seconds/SEC_PER_DAY return drift*days def fix_date(when, base, drift=SITE_DRIFT): """Return date when adjusted to the correct time.""" d = calc_drift(when, base, drift) delta = timedelta(seconds=-d) return when + delta And here it is in action: >>> fix_date(DT(2008,9,9), DT(2008,9,8)) datetime.datetime(2008, 9, 8, 23, 59, 55, 770000) I leave it to you to convert date/time strings into datetime objects. -- Steven From hniksic at xemacs.org Tue Sep 16 09:02:46 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 15:02:46 +0200 Subject: Is 'x' an instance of a new-style class? References: <f568f4d9-b179-4ef1-9688-fcd8cb5ef641@d1g2000hsg.googlegroups.com> <mailman.1102.1221557922.3487.python-list@python.org> <739d438d-3631-4d06-8855-65097a5623aa@z66g2000hsc.googlegroups.com> Message-ID: <87tzcg5jm1.fsf@mulj.homelinux.net> MatthewS <schaefer.mp at gmail.com> writes: > Thanks Gabriel, the second solution seems to work based on my tests. > So I have this now this test: > > static BOOL IsPythonInstance( PyObject * src ) > { > { > // old style classes or instances or new style classes or instances > if( ( PyInstance_Check( src ) ) || ( PyClass_Check( src ) ) || > PyObject_TypeCheck( src, &PyBaseObject_Type) ) > { > return TRUE; > } > > return FALSE; > } > } I think this will return TRUE on any Python object you pass it. From steven at REMOVE.THIS.cybersource.com.au Fri Sep 19 04:14:07 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 19 Sep 2008 08:14:07 GMT Subject: Python newbie References: <gavjfd$mvd$1@registered.motzarella.org> <mailman.1261.1221809756.3487.python-list@python.org> Message-ID: <pan.2008.09.19.08.14.07@REMOVE.THIS.cybersource.com.au> On Fri, 19 Sep 2008 03:34:50 -0400, Steve Holden wrote: > Please note the above statement is contentious, and will likely bring a > horde of screaming fanatics of various flavors down on my head for > terminological inexactitude. A pox on you and your descendants onto the tenth generation! *wink* -- Steven From marco.bizzarri at gmail.com Sun Sep 14 04:08:10 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sun, 14 Sep 2008 10:08:10 +0200 Subject: recursion gotcha? In-Reply-To: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> Message-ID: <3f0d61c40809140108n515006dci87f91dcd971f0169@mail.gmail.com> On Sun, Sep 14, 2008 at 10:01 AM, cnb <circularfunc at yahoo.se> wrote: > this recursive definition of sum thrumped me, is this some sort of > gotcha or am I just braindead today? > and yes i know this is easy a a for x in xs acc += x or just using the > builtin. > > def suma(xs, acc=0): > if len(xs) == 0: > acc > else: > suma(xs[1:], acc+xs[0]) You're just missing the "return" statements? def suma(xs, acc=0): if len(xs) == 0: return acc else: return suma(xs[1:], acc+xs[0]) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From samslists at gmail.com Fri Sep 19 23:45:59 2008 From: samslists at gmail.com (Sam) Date: Fri, 19 Sep 2008 20:45:59 -0700 (PDT) Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <mailman.766.1221033019.3487.python-list@python.org> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <mailman.1247.1221772248.3487.python-list@python.org> <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> <mailman.1273.1221821307.3487.python-list@python.org> Message-ID: <13fd1a7d-1d18-49c4-bd28-f06df620e6c1@a8g2000prf.googlegroups.com> Gabriel... Awesome! Thank you so much for the solution. And yeah, I found exactly one website that strangely enough only does deflate, not gzip. I'd rather not say what website it is, since it's small and not mine. They may be few and in between, but they do exist. Thanks On Sep 19, 3:48?am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Thu, 18 Sep 2008 23:29:30 -0300, Sam <samsli... at gmail.com> escribi?: > > > On Sep 18, 2:10?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > > wrote: > >> En Tue, 16 Sep 2008 21:58:31 -0300, Sam <samsli... at gmail.com> escribi?: > >> The code is correct - try with another server. I tested it with a ? > >> LightHTTPd server and worked fine. > > > Gabriel... > > > I found a bunch of servers to test it on. ?It fails on every server I > > could find (sans one). > > I'll try to check later. Anyway, why are you so interested in deflate? ? > Both "deflate" and "gzip" coding use the same algorithm and generate ? > exactly the same compressed stream, the only difference being the header ? > and tail format. Have you found any server supporting deflate that doesn't ? > support gzip as well? > > -- > Gabriel Genellina From tino at wildenhain.de Wed Sep 10 07:52:40 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 10 Sep 2008 13:52:40 +0200 Subject: Web shopping carts In-Reply-To: <C4EB6DE0.11187%luke.hamilton@rpm-solutions.com.au> References: <C4EB6DE0.11187%luke.hamilton@rpm-solutions.com.au> Message-ID: <48C7B508.6070006@wildenhain.de> Luke Hamilton wrote: > Hey People, > > I am wondering if there are any OS shopping cart application written in > python? > Yes there are. HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/1383c78d/attachment.bin> From ppearson at nowhere.invalid Thu Sep 18 10:49:22 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 18 Sep 2008 14:49:22 GMT Subject: Problem occured while sending mail References: <b7481bed-df0f-4ef7-8fe7-09da5869492f@c22g2000prc.googlegroups.com> <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> <6jckjhF2llrvU1@mid.individual.net> <2e63873f-ba8f-4519-b30c-9b5da913c64f@w24g2000prd.googlegroups.com> Message-ID: <6jf83iF2vk8jU1@mid.individual.net> On Wed, 17 Sep 2008 23:53:36 -0700 (PDT), sui <gogtesuyash at gmail.com> wrote: > On Sep 17, 8:04 pm, Peter Pearson <ppear... at nowhere.invalid> wrote: >> On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <gogtesuy... at gmail.com> wrote: [snip] >> > socket.error: (110, 'Connection timed out') [snip] >> As a simple connectivity test, you might see whether you can connect >> using telnet: [snip] > even i couldnt connect using telnet.... > msg comes host is down Then your problem is a networking problem. I know even less about networking than I know about Python. Can you ping the destination? Perhaps tracepath or traceroute will help you find where your messages are being refused. Perhaps you are trying to work through an internet access provider (e.g., ISP) that doesn't allow direct connections to remote mail servers. If I might add a grouchy comment, you really should learn a little about netiquette. When you don't bother to trim the quoted context or even to punctuate your text, you broadcast a conspicuous implication that you value your own time much more than you value the time of the people whose help you're soliciting, which is incongruous and insulting. A more carefully presented request might have gotten a response from someone more knowledgeable -- and less grouchy -- than me. -- To email me, substitute nowhere->spamcop, invalid->net. From blabla at dungeon.de Tue Sep 2 13:36:50 2008 From: blabla at dungeon.de (hofer) Date: Tue, 2 Sep 2008 10:36:50 -0700 (PDT) Subject: converting a sed / grep / awk / . . . bash pipe line into python Message-ID: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Hi, Something I have to do very often is filtering / transforming line based file contents and storing the result in an array or a dictionary. Very often the functionallity exists already in form of a shell script with sed / awk / grep , . . . and I would like to have the same implementation in my script What's a compact, efficient (no intermediate arrays generated / regexps compiled only once) way in python for such kind of 'pipe line' Example 1 (in bash): (annotated with comment (thus not working) if copied / pasted #------------------------------------------------------------------------------------------- cat file \ ### read from file | sed 's/\.\..*//' \ ### remove '//' comments | sed 's/#.*//' \ ### remove '#' comments | grep -v '^\s*$' \ ### get rid of empty lines | awk '{ print $1 + $2 " " $2 }' \ ### knowing, that all remaining lines contain always at least \ ### two integers calculate sum and 'keep' second number | grep '^42 ' ### keep lines for which sum is 42 | awk '{ print $2 }' ### print number Same example in perl: # I guess (but didn't try), taht the perl example will create more intermediate # data structures than necessary. # Ideally the python implementation shouldn't do this, but just 'chain' iterators. #------------------------------------------------------------------------------------------- my $filename= "file"; open(my $fh,$filename) or die "failed opening file $filename"; # order of 'pipeline' is syntactically reversed (if compared to shell script) my @numbers = map { $_->[1] } # extract num 2 grep { $_->[0] == 42 } # keep lines with result 42 map { [ $_->[0]+$_->[1],$_->[1] ] } # calculate sum of first two nums and keep second num map { [ split(' ',$_,3) ] } # split by white space grep { ! ($_ =~ /^\s*$/) } # remove empty lines map { $_ =~ s/#.*// ; $_} # strip '#' comments map { $_ =~ s/\/\/.*// ; $_} # strip '//' comments <$fh>; print "Numbers are:\n",join("\n", at numbers),"\n"; thanks in advance for any suggestions of how to code this (keeping the comments) H From ggpolo at gmail.com Sun Sep 14 10:45:20 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 14 Sep 2008 11:45:20 -0300 Subject: cjson 1.0.5 keyword argument In-Reply-To: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> References: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> Message-ID: <ac2200130809140745i5ce3a3d5xc932f5deb8346e36@mail.gmail.com> On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo <clodoaldo.pinto at gmail.com> wrote: > I have installed cjson 1.05 in Fedora 8 (python 2.5.1). > > The cjson home page shows a keyword argument "encoding". > http://python.cx.hu/python-cjson/ > The latest python-cjson on that page is 1.0.3, which accepts keywords for the encode function. python-cjson 1.0.5 no longer accepts. > When i use it i get an error: > >>>> cjson.encode('?', encoding='utf8') > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: encode() takes no keyword arguments > > What am i missing? There is no mail list for cjson. Try doing cjson.encode('?'.decode('utf-8')) instead. > > Regards, Clodoaldo > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dev001 at pas-world.com Tue Sep 23 13:37:59 2008 From: dev001 at pas-world.com (F.) Date: Tue, 23 Sep 2008 19:37:59 +0200 Subject: Problems compiling on CentOS Python 2.5 Message-ID: <1222191480.13007.5.camel@localhost.localdomain> Hello, I have problems making python on CentOS 5. Seems that can not find something. I can not find the problem. Where is the problem? > case $MAKEFLAGS in \ > *-s*) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ > *) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ > esac > running build > running build_ext > db.h: found (4, 3) in /usr/include > db lib: using (4, 3) db-4.3 > INFO: Can't locate Tcl/Tk libs and/or headers > building '_ssl' extension > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes -I. -I/home/unStable/progC/exLibs/Python-2.5.2/Python-2.5.2/./Include -I. -IInclude -I./Include -I/usr/local/include -I/directory/Python-2.5.2/Python-2.5.2/Include -I/directory/Python-2.5.2/Python-2.5.2 -c /directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.c -o build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o > gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-i686-2.5/_ssl.so > *** WARNING: renaming "_ssl" since importing it failed: build/lib.linux-i686-2.5/_ssl.so: undefined symbol: krb5_auth_con_getrcache > running build_scripts -- -- Publicidad http://www.pas-world.com From gagsl-py2 at yahoo.com.ar Wed Sep 3 22:13:43 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 23:13:43 -0300 Subject: Access to Windows "Add/Remove Programs"? References: <cf08e654-d2d5-48fe-a2ac-919fd2479254@v13g2000pro.googlegroups.com> Message-ID: <op.ugxps5mmx6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 03 Sep 2008 21:51:59 -0300, Sean DiZazzo <half.italian at gmail.com> escribi?: > I'm trying to find a way to get a list of all the installed programs > on a Windows box via Python. I thought of a few hacks that might > partially work, and then thought about "Add/Remove Programs" Seems > like the right way to go. I looked over the pywin32 docs a bit, but > nothing slapped me in the face. > > Is there any reliable way to get at that info? You may enumerate the entries under this registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Sep 4 03:47:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 04 Sep 2008 04:47:07 -0300 Subject: use str as variable name References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> Message-ID: <op.ugx48t1hx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 04 Sep 2008 04:25:37 -0300, Mathieu Prevot <mathieu.prevot at gmail.com> escribi?: > I have a program that take a word as argument, and I would like to > link this word to a class variable. > > eg. > class foo(): > width = 10 > height = 20 > > a=foo() > arg='height' > a.__argname__= new_value > > rather than : > > if arg == 'height': > a.height = new_value > elif arg == 'width'; > a.width = new_value You're looking for "setattr": setattr(a, arg, new_value) http://docs.python.org/lib/built-in-funcs.html#l2h-66 > > Can I do this with python ? How ? > > Thanks, > Mathieu > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 15:19:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 21:19:30 +0200 Subject: Late initialization using __getattribute__ In-Reply-To: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> Message-ID: <48beff32$0$10287$426a74cc@news.free.fr> bukzor a ?crit : > I want to make a MixIn class that waits to initialize its super- > classes until an attribute of the object is accessed. Not generally > useful, but desirable in my case. I've written this, and it works, but > would like to take any suggestions you guys have. You shouldn't mess with __getattribute__ unless you really know what you're doing and are ok to suffer the constant performance hit you'll get. Remember that __getattribute__ actually *is* the implementation of attribute lookup rules, and is called on each and every attribute lookup. Your below snippet would be much better using __getattr__ (which is only called as a last resort). > I've commented out > the "delattr" call because it throws an AttributeError (although I > don't know why). __getattribute__ belongs to the class, not to the instance. delattr() only removes instance attributes. You'd have to remove __getattribute__ from the LateInitMixIn class object itself, but then it would break the whole thing. > > > class LateInitMixIn(object): > def __init__(self): > print "LateInit initialization" > self.inited = False > def __getattribute__(self, attr): > print "Doing __getattribute__" > getattr = lambda attr:object.__getattribute__(self, attr) > if not getattr("inited"): > super(LateInitMixIn, self).__init__() > setattr(self, "inited", True) > #delattr(self, "__getattribute__") > return getattr(attr) Here's another possible implementation (which doesn't solve all problems, cf below) using __getattr__: class LateInitMixin(object): def __init__(self): print "not yet" self.__initialized = False def __getattr__(self, name): if self.__initialized: raise AttributeError( "object %s has no attribute '%s'" % (type(self), name) ) super(LateInitMixin, self).__init__() self.__initialized = True return getattr(self, name) class Base(object): def __init__(self): print "yet" self.base = True class LateInit(LateInitMixin, Base): pass def main(): print "shouldn't init" S = LateInit() print "should init" print S.base if __name__=="__main__": main() Ok, now, the other problem : what if Base.__init__ expects args ? From larry.bates at vitalEsafe.com Wed Sep 24 22:23:28 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Wed, 24 Sep 2008 21:23:28 -0500 Subject: Making small executive file for distribution In-Reply-To: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: <ZyCCk.37890$XT1.10310@bignews5.bellsouth.net> Marin Brkic wrote: > Not commercial distribution, but an academic kind of sorts - giving > the exe file to coleagues, so they can use it in their work. Giving > .py file is not an option, since due to centralized computer > maintenance, they don't (and cannot) have installed python (except the > ones that bring their own computer at work, but those are an > exception). > > As far as I know py2exe is the only option which can do such a thing > (make exe files from scripts). Is there a way to make those exe files > a little smaller (for a small script they easily go up to 5-10 mb). > > Has anyone had a situation like this ? All your inputs and suggestions > are more then welcomed. > > -- > Marin > Times have changed, 5-10Mb is REALLY small. Flash drives hold 4000-8000Mb for less than $20 and standard hard drives are now 500Gb. IMHO you are concerned about a problem that doesn't actually exist. -Larry From clp at rebertia.com Mon Sep 8 15:04:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Sep 2008 12:04:41 -0700 Subject: lacking follow-through In-Reply-To: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <ccf8d124-4609-48a6-b487-7cccc6d9c4b9@a3g2000prm.googlegroups.com> <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: <47c890dc0809081204o3511b9dck1adadd98f73ca2b7@mail.gmail.com> On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <ewertman at gmail.com> wrote: >> Perhaps the wrong idea of what the group is. I would have thought >> that >> if one had a sufficiently developed idea and wanted to have it / >> formally/ >> rejected, rather than merely sniped at, then writting a PEP would be >> more >> apposite than posting to c.l.py. >> >> It's fine to post your not sufficiently developed ideas here merely >> to >> have them discussed. But I don't know what makes you feel that you, >> or >> your ideas, are /entitled/ to any response at all, much less >> "follow-through." > > > To expand on this a little bit, I've been subscribed to this group > for a couple of months, but there seems to be a bit more gray area > between what would go to a 'python-dev' group and a 'python-user' > group. Long debates about language features and abstract ideas would > appeal to the former, but not the latter. Certainly I fall into the > user category.. I'm pretty happy with python, and generally just > adjust to it's design and features, rather than spend lots of time on > whether they are 'right' or could be 'better'. /shrug Yeah, suggestions about changing the language are much better suited to the more-specific Python-ideas or Python-3000 mailinglists than the general-purpose c.l.p - Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From gagsl-py2 at yahoo.com.ar Tue Sep 30 15:28:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 16:28:11 -0300 Subject: Would this be called a bug in inspect ? References: <48E268A3.4050900@gmail.com> Message-ID: <op.uia609w8x6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 30 Sep 2008 14:57:55 -0300, Stef Mientki <stef.mientki at gmail.com> escribi?: > I'm not familiar with inspect, > but I get an error (see below) in > getmembers ( wx ) > > Of course this is bug in wx . Yes. > But would you also call this a bug in inspect ? > (inspect crashes and doesn't continue with th rest of the code, nor it > returns the already gathered data) getmembers works fine; try m=getmembers(wx) and see. It fails when you attemp to print (or pprint) the returned list. -- Gabriel Genellina From bj_666 at gmx.net Tue Sep 2 09:57:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 13:57:26 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> Message-ID: <6i4v26Fol29aU4@mid.uni-berlin.de> On Tue, 02 Sep 2008 09:28:42 -0400, Derek Martin wrote: > On Tue, Sep 02, 2008 at 12:27:49PM +0000, Marc 'BlackJack' Rintsch > wrote: >> > The Python class is a generalization of the standard Posix function >> > of (almost) the same name: >> > http://opengroup.org/onlinepubs/007908775/xsh/popen.html >> >> So it's a name of a *function* and it's a little bit unsuitable for a >> *class*. As Jeremy wrote: the instances represent *processes* not >> "popen"s, whatever that may be. > > I would argue that they don't represent processes at all; the object is > a set of files which connect the standard I/O streams of a subprocess to > its parent, and methods to operate on those files. And the process' ID, an attribute with the process' return code, a method to wait until the process is finished and file objects to communicate with the process. > The C library's popen() function, on which this class is based, > provides a means to open a file and connect it to the standard steams > of a subprocess, making it more closely analogous to what the Popen > class does/provides. As such, "Popen" is a better name to describe > this object than "subprocess" would be. Is strongly disagree. The class provides an interface to start and communicate with a `Subprocess`. Instances stand for processes. With your reasoning the `file` type should be called `open`. Ciao, Marc 'BlackJack' Rintsch From george.sakkis at gmail.com Thu Sep 4 12:53:21 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Sep 2008 09:53:21 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> Message-ID: <1494118c-d183-48c4-b91f-af8c8480b189@a8g2000prf.googlegroups.com> On Sep 4, 7:09?am, "Marco Bizzarri" <marco.bizza... at gmail.com> wrote: > Sorry... pressed enter but really didn't want to. > > As I said, let's say I have a class > > class A: > ? ? def __init__(self): > ? ? ? ? ?self.x = None > > Python makes the decision to allow the developers to directly access > the attribute "x", ?so that they can directly write: "a.x = 1", or > whatever; this has for me the unfortunate side effect that if I write, > for example "a.y = 1", when I really wanted to write "a.x = 1" no one > cares about it, and I'm unable to spot this error until later. > > Of course, I know that while I'm fresh, I've a good knowledge of the > code, and anything else, I will be able to avoid such stupid errors; > however, I'm afraid of the times when I'm tired, when I have to put my > hands on the code of someone else, and so on. So what happens in Java (or any language for that matter) if there are indeed two attributes x and y with the same type and you mistype the one for the other ? Or if you meant to write x-y instead of y-x ? When coding tired or on someone's else code, stupid errors are the ones you should worry the least about. George From hniksic at xemacs.org Tue Sep 16 06:05:51 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 12:05:51 +0200 Subject: Is 'x' an instance of a new-style class? References: <f568f4d9-b179-4ef1-9688-fcd8cb5ef641@d1g2000hsg.googlegroups.com> <mailman.1102.1221557922.3487.python-list@python.org> Message-ID: <878wts76dc.fsf@mulj.homelinux.net> "Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> writes: > En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS <schaefer.mp at gmail.com> > escribi?: > >> I've seen the question raised several times here, but apparently never >> answered. Since PyInstance_Check returns False for new-style class >> instances, is there a standard procedure for testing this using the C- >> Api? >> >> I would greatly appreciate some help with this. > > In Python you would write isinstance(x, object). It will return True for all Python objects (except perhaps those that fiddle with metaclasses), not only for instances of new-style classes. >>> isinstance([], object) True >>> isinstance((), object) True >>> isinstance(list, object) True >>> isinstance(type, object) True I don't think there is a good way to check if something is a new-style class instance. The whole point of new-style classes was removing the distinction between classes and types. The distinction is now so well removed that it's hard to find it when you need it. A better question for OP is *why* he needs to distinguish between instances of new-style classes and other objects. From xpahos at gmail.com Thu Sep 4 10:42:47 2008 From: xpahos at gmail.com (phasma) Date: Thu, 4 Sep 2008 07:42:47 -0700 (PDT) Subject: Python and Cyrillic characters in regular expression Message-ID: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> Hi, I'm trying extract all alphabetic characters from string. reg = re.compile('(?u)([\w\s]+)', re.UNICODE) buf = re.match(string) But it's doesn't work. If string starts from Cyrillic character, all works fine. But if string starts from Latin character, match returns only Latin characters. Please, help. From dblubaugh at belcan.com Mon Sep 29 19:20:20 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 19:20:20 -0400 Subject: Is Pyperl still active ?? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380521CBB0@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380521CBB0@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9212@AWMAIL04.belcan.com> To All, I was wondering if Pyperl is still active?? It appears as though it may very well be no longer active at this time!!! Is this correct?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From sniipe at gmail.com Tue Sep 2 04:22:20 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Tue, 2 Sep 2008 01:22:20 -0700 (PDT) Subject: How to print first(national) char from unicode string encoded inutf-8? References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com><mailman.330.1220274652.3487.python-list@python.org><7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> <mailman.331.1220276398.3487.python-list@python.org> <iKednf5sStIbJiHVnZ2dnUVZ_sGdnZ2d@comcast.com> <aaf6e20b-efee-401d-8a94-85f1f2d2c79e@c65g2000hsa.googlegroups.com> Message-ID: <b72f7bcc-5791-4ed5-96d4-99b8a8b283ed@m36g2000hse.googlegroups.com> On 2 Wrz, 10:17, sni... at gmail.com wrote: > On 2 Wrz, 06:05, "Mark Tolonen" <M8R-yft... at mailinator.com> wrote: > > > > > "Marco Bizzarri" <marco.bizza... at gmail.com> wrote in message > > >news:mailman.331.1220276398.3487.python-list at python.org... > > > > On Mon, Sep 1, 2008 at 3:25 PM, <sni... at gmail.com> wrote: > > > >> When I do ${urllib.unquote(c.user.firstName)} without encoding to > > >> latin-1 I got different chars than I will get: no ?ukasz but ? ukasz > > >> -- > > >>http://mail.python.org/mailman/listinfo/python-list > > > > That's crazy. "string".encode('latin1') gives you a latin1 encoded > > > string; latin1 is a single byte encoding, therefore taking the first > > > byte should be no problem. > > > > Have you tried: > > > > urlib.unquote(c.user.firstName)[0].encode('latin1') or > > > > urlib.unquote(c.user.firstName)[0].encode('utf8') > > > > I'm assuming here that the urlib.unquote(c.user.firstName) returns an > > > encodable string (which I'm absolutely not sure), but if it does, this > > > should take the first 'character'. > > > The OP stated that the original string was "encoded in UTF-8 and > > urllib.quote()", so after urllib.unquote the string is in UTF-8 format. > > This must be decoded into a Unicode string before removing the first > > character: > > > urllib.unquote(c.user.firstName).decode('utf-8')[0] > > > The next problem is that the character in the OP's example string '?' is not > > present in the latin-1 encoding, but using utf-8 encoding demonstrates that > > the full two-byte UTF-8 encoded character is collected: > > > >>> import urllib > > >>> name = urllib.quote(u'?ukasz'.encode('utf-8')) > > >>> name > > '%C5%81ukasz' > > >>> urllib.unquote(name).decode('utf-8')[0].encode('utf-8') > > '\xc5\x81' > > > -Mark > > @Mark, when I tried urllib.unquote(c.user.firstName).decode('utf-8') > [0].encode('utf-8'), I received this message: > > >> return render('/reports/create_report_step2.mako') > > Module pylons.templating:344 in render > << **cache_args) > return pylons.buffet.render(template_name=template, > fragment=fragment, > format=format, namespace=kargs, > **cache_args) > > >> format=format, namespace=kargs, **cache_args) > Module pylons.templating:229 in render > << log.debug("Rendering template %s with engine %s", > full_path, engine_name) > return engine_config['engine'].render(namespace, > template=full_path, > **options)>> **options) > Module mako.ext.turbogears:49 in render > << info.update(self.extra_vars_func()) > > return template.render(**info) > >> return template.render(**info) > Module mako.template:114 in render > << declared by this template's internal rendering method are > also pulled from the given *args, **data > members. members.""" > return runtime._render(self, self.callable_, args, data) > > def render_unicode(self, *args, **data):>> return > runtime._render(self, self.callable_, args, data) > Module mako.runtime:287 in _render > << context = Context(buf, **data) > context._with_template = template > _render_context(template, callable_, context, *args, > **_kwargs_for_callable(callable_, data)) > return context.pop_buffer().getvalue()>> > _render_context(template, callable_, context, *args, > **_kwargs_for_callable(callable_, data)) > Module mako.runtime:304 in _render_context > << # if main render method, call from the base of the > inheritance stack > (inherit, lclcontext) = _populate_self_namespace(context, > tmpl) > _exec_template(inherit, lclcontext, args=args, > kwargs=kwargs) > else: > # otherwise, call the actual rendering method specified>> > _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) > Module mako.runtime:337 in _exec_template > << error_template.render_context(context, > error=error) > else: > callable_(context, *args, **kwargs)>> callable_(context, > *args, **kwargs) > Module _reports_create_report_step2_mako:57 in render_body > << > context.write(filters.decode.utf8(urllib.unquote(str(c.period.end)))) > context.write(u' + ') > > context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8') > [0].encode('utf-8'))) > > context.write(filters.decode.utf8(urllib.unquote(str(c.user.secondName) > [0:1]))) > context.write(u'</h3>\r\n <input type="hidden" > name="works[]" value="')>> > context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8') > [0].encode('utf-8'))) > Module encodings.utf_8:16 in decode > << > def decode(input, errors='strict'): > return codecs.utf_8_decode(input, errors, True) > > class IncrementalEncoder(codecs.IncrementalEncoder):>> return > codecs.utf_8_decode(input, errors, True) > <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode > characters in position 0-1: ordinal not in range(128) ok, I resolved this problem $ {urllib.unquote(str(c.user.firstName)).decode('utf-8')[0]} Could anyone explain me why this code works? From hrishys at yahoo.co.uk Thu Sep 25 07:21:44 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 11:21:44 +0000 (GMT) Subject: Linq to Python In-Reply-To: <579eb852-031c-4f50-ac64-88ad8d677b05@m73g2000hsh.googlegroups.com> Message-ID: <255010.14702.qm@web27403.mail.ukl.yahoo.com> Hi Thank you very much I appreciate taking the pain to explain this to me. regards Hrishy --- On Thu, 25/9/08, sturlamolden <sturlamolden at yahoo.no> wrote: > From: sturlamolden <sturlamolden at yahoo.no> > Subject: Re: Linq to Python > To: python-list at python.org > Date: Thursday, 25 September, 2008, 12:16 PM > On 25 Sep, 13:08, hrishy <hris... at yahoo.co.uk> wrote: > > > Pardon my ignorance again but id ont see any join in > python or did i miss something ? > > It's more Pythonic to use the syntax of dictionary > lookups. > -- > http://mail.python.org/mailman/listinfo/python-list From dmitrey.kroshko at scipy.org Tue Sep 23 16:34:51 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Tue, 23 Sep 2008 13:34:51 -0700 (PDT) Subject: how to keep a window above all other OS windows? References: <e03ba1b5-c120-45a3-bf27-640f86c35754@2g2000hsn.googlegroups.com> Message-ID: <62cc640e-3526-49f9-ba10-22ff31f094e1@e39g2000hsf.googlegroups.com> On Sep 23, 11:21?pm, dmitrey <dmitrey.kros... at scipy.org> wrote: > Hi all, > how to keep a Tkinter window above all other OS windows (i.e. > including those ones from other programs)? > > Thank you in advance, > Dmitrey I have put [Tkinter] into topic of my message but somehow it has been removed. D. From gogtesuyash at gmail.com Thu Sep 18 02:53:36 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 23:53:36 -0700 (PDT) Subject: Problem occured while sending mail References: <b7481bed-df0f-4ef7-8fe7-09da5869492f@c22g2000prc.googlegroups.com> <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> <6jckjhF2llrvU1@mid.individual.net> Message-ID: <2e63873f-ba8f-4519-b30c-9b5da913c64f@w24g2000prd.googlegroups.com> On Sep 17, 8:04 pm, Peter Pearson <ppear... at nowhere.invalid> wrote: > On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <gogtesuy... at gmail.com> wrote: > > On Sep 17, 5:04 pm, sui <gogtesuy... at gmail.com> wrote: > >> this is my code > > >> import sys, os, glob, datetime, time > >> import smtplib > >> ## Parameters for SMTP session > >> port=587 > >> SMTPserver= 'smtp.gmail.com' > >> SMTPuser= '... at gmail.com' > >> pw= 'fill in here' > >> SENDER= SMTPuser > > >> ## Message details > >> FROM= SENDER > >> TO= 'notgm... at a.com' > >> CC=FROM > >> ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC > >> RECEIVERS= (TO,) ## ignore the CC address > > >> subject= 'Test 1a' > >> message='*** Email test *** ' > > >> print 'Starting SMTPmailsession on %s as %s ' % > >> (SMTPserver,SMTPuser) > >> session = smtplib.SMTP(SMTPserver,port) > >> session.set_debuglevel(0) # set debug level to 1 to see details > >> session.ehlo(SMTPuser) # say hello > >> session.starttls() # TLS needed > >> session.ehlo(SMTPuser) # say hello again, not sure why > >> session.login(SMTPuser, pw) > > >> ##Create HEADER + MESSAGE > >> HEADER= 'From: %s\r\n' % FROM > >> HEADER= HEADER + 'To: %s\r\n' % TO > >> HEADER= HEADER + 'Cc: %s\r\n' % CC > >> HEADER= HEADER + 'Subject: %s\r\n' % subject > >> BODY= HEADER + '\r\n' + message > >> print BODY > > >> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email > > >> session.close() > > >> Now when i run this .py file...as pythonmail.py > >> i can see only statement > >> starting smtpmail......n details > >> then nothing on screen after few minutes or after pressing ctrl +c > >> Traceback (most recent call last): > >> File "mail4.py", line 21, in <module> > >> session = smtplib.SMTP(SMTPserver,port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > >> (code, msg) = self.connect(host, port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > >> self.sock.connect(sa) > >> File "<string>", line 1, in connect > >> or may be conncetion time out > > >> wats the solution for this > > > if i dont press cntrl + c then it shows > > Starting SMTPmailsession on smtp.gmail.com as gogtesuy... at gmail.com > > Traceback (most recent call last): > > File "mail4.py", line 21, in <module> > > session = smtplib.SMTP(SMTPserver,port) > > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > > (code, msg) = self.connect(host, port) > > File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect > > raise socket.error, msg > > socket.error: (110, 'Connection timed out') > > > plz help me its urgent.....i want to complete it as early as possible > > I pasted your code into a file named temp.py, > and (perhaps superstitiously) added a backslash to this line: > > >> print 'Starting SMTPmailsession on %s as %s ' % > > Here's what it does (long line wrapped manually): > > peter at eleodes:~$ python temp.py > Starting SMTPmailsession on smtp.gmail.com as .... at gmail.com > Traceback (most recent call last): > File "temp.py", line 27, in ? > session.login(SMTPuser, pw) > File "/usr/lib/python2.4/smtplib.py", line 591, in login > raise SMTPAuthenticationError(code, resp) > smtplib.SMTPAuthenticationError: (535, \ > '5.7.1 Username and Password not accepted. Learn more at\n' \ > '5.7.1http://mail.google.com/support/bin/answer.py?answer='\ > '14257 a8sm34686663poa.12') > peter at eleodes:~$ > > This indicates that it got much farther than when you ran it, since > your timeout message comes from the smtplib.SMTP call several lines > before the session.login call. > > As a simple connectivity test, you might see whether you can connect > using telnet: > > peter at eleodes:~$ telnet smtp.gmail.com 587 > Trying 72.14.253.109... > Connected to gmail-smtp.l.google.com. > Escape character is '^]'. > 220 mx.google.com ESMTP m27sm34789033pof.6 > ^]c > > telnet> c > Connection closed. > peter at eleodes:~$ > > -- > To email me, substitute nowhere->spamcop, invalid->net. even i couldnt connect using telnet.... msg comes host is down From uzmanajmal at gmail.com Wed Sep 17 05:55:54 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Wed, 17 Sep 2008 09:55:54 +0000 Subject: File Reading related query Message-ID: <a3158e8b0809170255y6527dc96ta0f7466fd575db8f@mail.gmail.com> Hi., Is there any function for reading a file while ignoring *\n* occuring in the file? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080917/b270a482/attachment.html> From steve at REMOVE-THIS-cybersource.com.au Wed Sep 17 10:55:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Sep 2008 14:55:35 GMT Subject: python regex character group matches References: <f44caf830809170627m19b5f4e3qb9fe2fb69ee20afa@mail.gmail.com> <mailman.1170.1221659832.3487.python-list@python.org> Message-ID: <00e11472$0$20331$c3e8da3@news.astraweb.com> On Wed, 17 Sep 2008 15:56:31 +0200, Fredrik Lundh wrote: > Assuming that you want to find runs of \uXXXX escapes, simply use > non-capturing parentheses: > > pat = re.compile(u"(?:\\\u[0-9A-F]{4})") Doesn't work for me: >>> pat = re.compile(u"(?:\\\u[0-9A-F]{4})") UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 5-7: truncated \uXXXX escape Assuming that the OP is searching byte strings, I came up with this: >>> pat = re.compile('(\\\u[0-9A-F]{4})+') >>> pat.search('abcd\\u1234\\uAA99\\u0BC4efg').group(0) '\\u1234\\uAA99\\u0BC4' -- Steven From bignose+hates-spam at benfinney.id.au Tue Sep 30 19:06:08 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Oct 2008 09:06:08 +1000 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> <87zllqqa1i.fsf@benfinney.id.au> <pan.2008.09.30.10.04.18@REMOVE.THIS.cybersource.com.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> <mailman.1766.1222798706.3487.python-list@python.org> Message-ID: <87hc7xqlnj.fsf@benfinney.id.au> Terry Reedy <tjreedy at udel.edu> writes: > Steven D'Aprano wrote: > > We agree that the restriction is artificial, and I think > > irrational (although I'd be interested in hearing the gnuplot > > developers' reasoning before making a final judgment). > > I believe it is a matter of preserving clarity of authorship, just > as is the quoting mechanism we take for granted in posts like this. > If I removed the quote marks above and silently edited what Ben and > you wrote, I might upset someone and certainly could confuse > readers. That, if it were to be prosecuted under law, would be a matter already covered by laws other than copyright: fraud, libel, etc. Note that I consider a work free even if it fails to grant ?the right to distribute misrepresentations of the author's words?, because that act is an exercise of undue power over another person, and so falls outside the limit imposed by the freedoms of others. -- \ ?What is it that makes a complete stranger dive into an icy | `\ river to save a solid gold baby? Maybe we'll never know.? ?Jack | _o__) Handey | Ben Finney From sjmachin at lexicon.net Sun Sep 21 06:52:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 21 Sep 2008 03:52:55 -0700 (PDT) Subject: writeable buffer and struct.pack_into and struct.unpck_from References: <bd9c1d00-2c55-4a29-aa99-c4a2dcd48c29@79g2000hsk.googlegroups.com> <mailman.1311.1221954200.3487.python-list@python.org> <d7f5e34a-6283-4348-aa63-0f1e03437f45@s50g2000hsb.googlegroups.com> Message-ID: <214c1d71-883e-4af7-bd5b-267f0714d873@v39g2000pro.googlegroups.com> On Sep 21, 3:16?pm, Tzury Bar Yochay <Afro.Syst... at gmail.com> wrote: > Thanks Gabriel, > I was missing the information how to create a writable buffer. array.array objects also have the writable buffer nature: >>> import array >>> b = array.array('c', '\0' * 10) >>> b array('c', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') >>> import struct >>> struct.pack_into('<hhhh', b, 0, 1, 2, -1, -32768) >>> b array('c', '\x01\x00\x02\x00\xff\xff\x00\x80\x00\x00') HTH, John From bignose+hates-spam at benfinney.id.au Tue Sep 9 08:07:24 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 09 Sep 2008 22:07:24 +1000 Subject: Python Installation and Running on Windows Vista References: <4f66ca7b-b495-4b12-bb4c-29b096eb53c9@j22g2000hsf.googlegroups.com> Message-ID: <87fxo9ed4z.fsf@benfinney.id.au> Mchizi_Crazy <silazima at gmail.com> writes: > Please help with issue... What is the issue? What have you tried, what is happening, and what behaviour were you expecting instead? > I heard of compatimbiltity issues and would like clarification. Same here. Can you please clarify what the issue is, as above. -- \ ?There's no excuse to be bored. Sad, yes. Angry, yes. | `\ Depressed, yes. Crazy, yes. But there's no excuse for boredom, | _o__) ever.? ?Viggo Mortensen | Ben Finney From goldnery at gmail.com Mon Sep 1 18:11:01 2008 From: goldnery at gmail.com (Gandalf) Date: Mon, 1 Sep 2008 15:11:01 -0700 (PDT) Subject: encoding References: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> <6i36tkFogbfkU1@mid.uni-berlin.de> Message-ID: <54811a01-b8fe-408b-91cd-8671c5c42697@d77g2000hsb.googlegroups.com> On Sep 1, 11:59?pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > Gandalf schrieb: > > > if i want to print utf-8 string i should writre: > > > print u"hello word" > > No, you don't. You write > > print u"hello world".encode("utf-8") > > Read this: > > http://www.reportlab.com/i18n/python_unicode_tutorial.html > > > but what happen if i want to print variable? > > Then you do > > print variable_containing_unicode_object.encode("utf-8") > > Diez thanks From circularfunc at yahoo.se Sat Sep 13 04:06:22 2008 From: circularfunc at yahoo.se (cnb) Date: Sat, 13 Sep 2008 01:06:22 -0700 (PDT) Subject: Profiling, sum-comprehension vs reduce Message-ID: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> This must be because of implementation right? Shouldn't reduce be faster since it iterates once over the list? doesnt sum first construct the list then sum it? ----------------------- >>> ================================ RESTART ================================ >>> reduce with named function: 37.9864357062 reduce with nested, named function: 39.4710288598 reduce with lambda: 39.2463927678 sum comprehension: 25.9530121845 >>> ================================ RESTART ================================ >>> reduce with named function: 36.4529584067 reduce with nested, named function: 37.6278529813 reduce with lambda: 38.2629448715 sum comprehension: 26.0197561422 >>> from timeit import Timer def add(x,y): return x+y def rednamed(lst): return reduce(add, lst) def rednn(lst): def add2(x,y): return x+y return reduce(add2, lst) def redlambda(lst): return reduce(lambda x,y:x+y, lst) def com(lst): return sum(x for x in lst) s = xrange(101) t1 = Timer('rednamed(s)', 'from __main__ import rednamed, s') t2 = Timer('rednn(s)', 'from __main__ import rednn, s') t3 = Timer('redlambda(s)', 'from __main__ import redlambda, s') t4 = Timer('com(s)', 'from __main__ import com, s') print "reduce with named function: ", t1.timeit() print "reduce with nested, named function: ", t2.timeit() print "reduce with lambda: ", t3.timeit() print "sum comprehension: ", t4.timeit() --------------------------------------- also, using range instead of xrange doesnt seem to generate a performance-penalty: >>> reduce with named function: 36.7560729087 reduce with nested, named function: 38.5393266463 reduce with lambda: 38.3852953378 sum comprehension: 27.9001007111 >>> From tjreedy at udel.edu Tue Sep 30 04:21:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 04:21:13 -0400 Subject: Comparing float and decimal In-Reply-To: <op.uh9wgumox6zn5v@gabriel2.softlabbsas.com.ar> References: <mailman.1400.1222168827.3487.python-list@python.org> <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> <op.uh9wgumox6zn5v@gabriel2.softlabbsas.com.ar> Message-ID: <gbsnhl$846$1@ger.gmane.org> Gabriel Genellina wrote: > En Thu, 25 Sep 2008 08:02:49 -0300, Mark Dickinson <dickinsm at gmail.com> > escribi?: >> On Sep 23, 1:58 pm, Robert Lehmann <stargam... at gmail.com> wrote: >>> I don't see why transitivity should apply to Python objects in general. >> >> Hmmm. Lack of transitivity does produce some, um, interesting >> results when playing with sets and dicts. Here are sets s and >> t such that the unions s | t and t | s have different sizes: >> >>>>> from decimal import Decimal >>>>> s = set([Decimal(2), 2.0]) >>>>> t = set([2]) >>>>> len(s | t) >> 2 >>>>> len(t | s) >> 1 > > Ouch! > >> This opens up some wonderful possibilities for hard-to-find bugs... > > And I was thinking all this thread was just a theoretical question > without practical consequences... To explain this anomaly more clearly, here is a recursive definition of set union. if b: a|b = a.add(x)|(b-x) where x is arbitrary member of b else: a|b = a Since Python only defines set-set and not set-ob, we would have to subtract {x} to directly implement the above. But b.pop() subtracts an arbitrary members and returns it so we can add it. So here is a Python implementation of the definition. def union(a,b): a = set(a) # copy to preserve original b = set(b) # ditto while b: a.add(b.pop()) return a from decimal import Decimal d1 = Decimal(1) fd = set((1.0, d1)) i = set((1,)) print(union(fd,i)) print(union(i,fd)) # prints {1.0, Decimal('1')} {1} This is a bug in relation to the manual: "union(other, ...) set | other | ... Return a new set with elements from both sets." Transitivity is basic to logical deduction: equations: a == b == c ... == z implies a == z implications: (a implies b) and (b implies c)implies (a implies c) The latter covers syllogism and other deduction rules. The induction part of an induction proof of set union commutivity is a typical equality chain: if b: a | b = a.add(x)| b-x for x in b # definition for non-empty b = b-x | a.add(x) # induction hypothesis = (b-x).add(x) | a.add(x)-x # definition for non-empty a = b | a.add(x)-x # definitions of - and .add if x not in a: = b | a # .add and - if x in a: = b | a-x # .add and - = b.add(x) | a-x # definition of .add for x in b = b | a # definition for non-empty a = b | a # in either case, by case analysis By transitivity of =, a | b = b | a ! So where does this go wrong for our example? This shows the problems. >>> fd - i set() This pretty much says that 2-1=0, or that 2=1. Not good. The fundamental idea of a set is that it only contains something once. This definition assumes that equality is defined sanely, with the usual properties. So, while fd having two members implies d1 != 1.0, the fact that f1 == 1 and 1.0 == 1 implies that they are really the same thing, so that d1 == 1.0, a contradiction. To put this another way: The rule of substitution is that if E, F, and G are expressions and E == F and E is a subexpression of G and we substitute F for E in G to get H, then G == H. Again, this rule, which is a premise of all formal expressional systems I know of, assumes the normal definition of =. When we apply this, fd == {f1, 1.0} == {1,1.0} == {1} == i But Python says >>> fd == i False Conclusion: fd is not a mathematical set. Yet another anomaly: >>> f = set((1.0,)) >>> i == f True >>> i.add(d1) >>> f.add(d1) >>> i == f False So much for "adding the same thing to equals yields equals", which is a special case of "doing the same thing to equals, where the thing done only depends on the properties that make the things equal, yields equals." And another >>> d1 in i True >>> 1.0 in i True >>> fd <= i False Manual: "set <= other Test whether every element in the set is in other" I bet Python first tests the sizes because the implementer *assumed* that every member of a larger set could not be in a smaller set. I presume the same assumption is used for equality testing. Or Manual: "symmetric_difference(other) set ^ other Return a new set with elements in either the set or other but not both." >>> d1 in fd True >>> d1 in i True >>> d1 Decimal('1') >>> fd ^ i {Decimal('1')} If no one beats me to it, I will probably file a bug report or two, but I am still thinking about what to say and to suggest. Terry Jan Reedy From george.sakkis at gmail.com Fri Sep 26 09:47:14 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 26 Sep 2008 06:47:14 -0700 (PDT) Subject: how to search multiple textfiles ? References: <mailman.1536.1222436146.3487.python-list@python.org> Message-ID: <bf1664da-1e2e-48c8-a108-66b0fb457e43@k30g2000hse.googlegroups.com> On Sep 26, 9:35 am, Stef Mientki <s.mien... at ru.nl> wrote: > hello, > > I want to search multiple textfiles (python source files) for a specific > word. > I can find all files, open them and do a search, > but I guess that will be rather slow. > > I couldn't find any relevant information through google. > > Does anyone know of a search library that performs this task fast ? > > If it indeed only concerns py-files, > is there another way of searching words ? > ( I could imagine that such a "py-only-search" would have benefits, > because you could set a flag to see the words in comment yes or no ) If you're on *nix platform, you can use: $ find -name "*py" | xargs egrep "\bword\b" HTH, George From benlindelof at gmail.com Mon Sep 8 20:02:14 2008 From: benlindelof at gmail.com (benlindelof at gmail.com) Date: Mon, 8 Sep 2008 17:02:14 -0700 (PDT) Subject: Coming from .NET and VB and C References: <d20e9c18-9607-4746-a34a-c37ef6c22aef@d45g2000hsc.googlegroups.com> <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <mailman.471.1220523953.3487.python-list@python.org> <48bfc4e4$0$13232$426a74cc@news.free.fr> <mailman.479.1220528581.3487.python-list@python.org> Message-ID: <bfe480a0-2523-4a16-953c-ecbae4271c11@t54g2000hsg.googlegroups.com> BigTable looks great! There's a 3% performance hit for these types of databases. However it makes up for it in other ways. "Dive Into Python" seems to suggest there is less busy work, but I am still looking into the GUI components of Python. Say, a grid of 10x10 tiles of PNGs. _______________________________________________________________________________ > have no preference with MySQL or SQL, stored procedures or ad-hoc > queries. Please note: MySQL is specific relational database management system (RDBMs), which uses a dialect of structured query language (SQL). SQL by itself is just a semi-standardized query language -- and can technically be used to access non-relational DBMS (if any such are still in use), though the query processor would be a pain to program (map a relational join into a hierarchical DBMS schema? ugh). > SO, I'm interested in using my Google App space (free 500MB) to > develop a quick database application. Using Python. I found "Dive > Into Python" which I will be reading shortly. So one question: what RDBMs are supported in that space? -- Wulfraed Dennis Lee Bieber KD6MOG From python-url at phaseit.net Tue Sep 16 09:43:58 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 16 Sep 2008 13:43:58 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 16) Message-ID: <gaod6u$tle$1@lairds.us> QOTW: "There is no point in creating new hardware without new software." - Niklaus Wirth http://www.modulaware.com/mdlt52.htm The first Release Candidate for Python 2.6 is out: http://groups.google.com/group/comp.lang.python/browse_thread/thread/bdf349528605e27f/ Abstract base classes, pros and cons: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/ Converting dictionary accesses from Perl to Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c70e09497db3c7f4/ Naming style: should a library wrapping foreign code keep the original names or follow PEP8? http://groups.google.com/group/comp.lang.python/browse_thread/thread/42f6a6c097fc74cb/ Profiles of sum() and reduce(): http://groups.google.com/group/comp.lang.python/browse_thread/thread/78a31fe094f79f2b/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From gioco at nekhem.com Tue Sep 2 12:04:18 2008 From: gioco at nekhem.com (Corrado Gioannini) Date: Tue, 2 Sep 2008 18:04:18 +0200 Subject: email.Message problem Message-ID: <20080902160417.GA20438@zephyr> Hi all, i know i'm probably going to ask a very silly question, but i can't figure out where i'm doing wrong just reading the docs. trying to build and send a mail message using the email.* modules (with python 2.5). a simplified version of my script that breaks is this: mailtest.py ---------------------------------------------------------------------- # coding: ISO-8859-15 import os, mimetypes, smtplib, base64, StringIO import email.message, email.header, email.generator messg = email.message.Message() messg.set_charset('ISO-8859-15') messg['To'] = 'email.x at mydomain' messg['From'] = 'email.y at mydomain' messg['Subject'] = email.header.Header("This is a test.", 'ISO-8859-15') messg["Message-ID"] = email.Utils.make_msgid() messg["Content-type"] = "Multipart/mixed" messg.preamble = "Mime test\n" pl = email.Message.Message() pl.add_header("Content-type", "text/plain; charset=ISO-8859-15") pl.add_header("Content-transfer-encoding", "8bit") pl.set_payload("Body text goes here.\n", 'ISO-8859-15') messg.attach(pl) messg.as_string() ---------------------------------------------------------------------- running it gives: Traceback (most recent call last): File "mailtest.py", line 22, in <module> messg.as_string() File "/usr/lib/python2.5/email/message.py", line 131, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/lib/python2.5/email/generator.py", line 84, in flatten self._write(msg) File "/usr/lib/python2.5/email/generator.py", line 109, in _write self._dispatch(msg) File "/usr/lib/python2.5/email/generator.py", line 135, in _dispatch meth(msg) File "/usr/lib/python2.5/email/generator.py", line 175, in _handle_text raise TypeError('string payload expected: %s' % type(payload)) TypeError: string payload expected: <type 'list'> the real case is just a little more complex: i have to attach some files and then send the message with smtplib to a list of recipients. no problems when attaching files etc., but when i try to get the message value 'flattened' to pass it to smtplib i always get an error as above. it seems to work only if i don't use .attach but just .set_payload in the main message, but in this case i cannot attach the extra files (or maybe i'm wrong in this?) any help (or pointers to docs/examples etc) are very appreciated :-) 10x, C. -- Quando l'infanzia muore i suoi cadaveri sono chiamati adulti. (B. Aldiss) From fredrik at pythonware.com Mon Sep 22 13:25:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Sep 2008 19:25:26 +0200 Subject: Regex Help In-Reply-To: <E2E744D6A24F4889AE41F847706FF840@office.ipglobal.net> References: <mailman.11779.1222099792.3486.python-list@python.org> <E2E744D6A24F4889AE41F847706FF840@office.ipglobal.net> Message-ID: <gb8ke7$ick$1@ger.gmane.org> Support Desk wrote: > the code I am using is > > regex = r'<a href=["|\']([^"|\']+)["|\']>' that's way too fragile to work with real-life HTML (what if the link has a TITLE attribute, for example? or contains whitespace after the HREF?) you might want to consider using a real HTML parser for this task. > page_text = urllib.urlopen('http://somesite.com') > page_text = page_text.read() > > links = re.findall(regex, text, re.IGNORECASE) the RE looks fine for the subset of all valid A elements that it can handle, though. got any examples of pages where you see that behaviour? </F> From martindemello at gmail.com Thu Sep 4 16:08:38 2008 From: martindemello at gmail.com (Martin DeMello) Date: Thu, 4 Sep 2008 13:08:38 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> <mailman.498.1220557317.3487.python-list@python.org> <e97d94df-8da5-4ac4-8029-abf90529c500@z11g2000prl.googlegroups.com> <3a59a1d4-4478-49e5-8316-9d27c09f55b0@m3g2000hsc.googlegroups.com> Message-ID: <ce09b0fc-6a51-4bdd-85a4-2f55dd220747@w39g2000prb.googlegroups.com> On Sep 4, 1:04?pm, castironpi <castiro... at gmail.com> wrote: > > Random access isn't supported by the defined interface. ?You can make > it more convenient, though. Thanks. I wasn't looking for random access, just wondering what the cleanest way to implement items = Queue.get_all() was. Your code should work nicely for that. martin From andyhume at gmail.com Sun Sep 7 17:51:32 2008 From: andyhume at gmail.com (andyhume at gmail.com) Date: Sun, 7 Sep 2008 14:51:32 -0700 (PDT) Subject: Updating python dictionary Message-ID: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Hello... I have a dict of key/values and I want to change the keys in it, based on another mapping dictionary. An example follows: MAPPING_DICT = { 'a': 'A', 'b': 'B', } my_dict = { 'a': '1', 'b': '2' } I want the finished my_dict to look like: my_dict = { 'A': '1', 'B': '2' } Whereby the keys in the original my_dict have been swapped out for the keys mapped in MAPPING_DICT. Is there a clever way to do this, or should I loop through both, essentially creating a brand new dict? Cheers, Andy. From almar.klein at gmail.com Mon Sep 15 04:57:23 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 15 Sep 2008 10:57:23 +0200 Subject: Python IDEs with F5 or hotkey shell interaction In-Reply-To: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> Message-ID: <cc38d75f0809150157i3cb9fb0foed89be6efb343b9b@mail.gmail.com> > ... <http://wiki.python.org/moin/PythonEditors> > but few if any alternatives seem to have all of the 'interactive' > power of IDLE?- not only a run program in a python shell hotkey but a > persistent, after-a-run memory state can be accessed for interactive > coding and exploration-- i.e. how IDLE works ! I felt the same. Coming from Matlab, I missed the interactive behaviour. I found IPython with a proper editor (I really liked PyPE) a nice solution. Still, I found it awkward having to use two programs and not having code completion in my editor (I mean the editor not knowing what names are present in my python session.) Therefore, I started creating an editor with an interactive shell in it in which you can run (parts of) your code and have a persisten session. It's not finished yet, but I'm quite happy with the result so far. It starts python in a subprocess in much the same way PyPE does. I actually "stole" code from PyPE as a base for multiple things (thanks Josiah :) ). Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/23d18a36/attachment.html> From martindemello at gmail.com Thu Sep 4 15:26:51 2008 From: martindemello at gmail.com (Martin DeMello) Date: Thu, 4 Sep 2008 12:26:51 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() Message-ID: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> I'm writing a cluster monitor, that collects information from a set of machines and logs it to a database In the interests of not hammering the db unnecessarily, I'm considering the following 1. A series of independent "monitor" threads that collect information over TCP from the cluster of machines, and write it to a queue 2. A "logger" thread that empties the queue every second or so and inserts the collected information to the db via a single insert statement Reading up on python's built in Queue class, though, it seems oriented towards "job queues", with a two-step dequeue operation (get() and task_done()). I'm worried that this would make it too heavyweight for my application. Is ther documentation somewhere on what exactly task_done() does, and whether I can disable the tracking of a job once it's removed from the queue? The python docs for the Queue module were a bit light. martin From gagsl-py2 at yahoo.com.ar Wed Sep 3 05:58:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 06:58:16 -0300 Subject: sys.stdin on windows References: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> Message-ID: <op.ugwgnenkx6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 03 Sep 2008 06:16:03 -0300, zugnush at gmail.com <zugnush at gmail.com> escribi?: > I often grep particular patterns out of large logfiles and then > pipeline the output to sort and uniq -c > I thought today to knock up a script to do the counting in a python > dict. > > This seems work in linux > > $ cat count.py > #!/usr/bin/env python > import sys > from collections import defaultdict > accumulator=defaultdict(int) > for line in sys.stdin.readlines(): > accumulator[line.strip()]+=1 > print "contents,count" > for key in accumulator.keys(): > print key,",",accumulator[key] > > $ cat test | ./count.py > contents,count > , 1 > 23 , 1 > 1 , 1 > 3 , 2 > 2 , 2 > 5 , 3 > > When I try to run the same thing on windows I get > IOError: [Error 9] Bad file descriptor > > How can I make this more windows friendly? Explicitely invoking the interpreter worked for me. That is, these two commands worked fine: type test.txt | python count.py python count.py < test.txt But I cannot explain *why* it doesn't work the other way. -- Gabriel Genellina From bearophileHUGS at lycos.com Fri Sep 5 20:00:04 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 17:00:04 -0700 (PDT) Subject: indices question References: <g9sgda$e9h$1@adenine.netfront.net> Message-ID: <cc9bc4bf-412e-44e9-ba6d-76352ec08fd4@26g2000hsk.googlegroups.com> Lanny: > ... > varcc = raw_input > grid[varc] = 'O' > ... > Why can't I put a varible thats an integer instead? 'varcc' and 'varc' are different names. 'raw_input' isn't a function call, you may want to turn that into a function call. varc isn't an integer, you may have to convert it to integer first, using int(), because Python lists aren't like Lua ones, they are represented with a sequence of cells, and an integer number is used to denote what cells you want. Note that the cell must already exists before accessing its contents. Maybe you want to use an associative array instead, named 'dict' in Python, that allows you freedom in the type of the keys and allows you to create cells on the fly. Surely my answer isn't enough to solve your problems, but it may give you a starting point. Bye, bearophile From tjreedy at udel.edu Sat Sep 13 14:08:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Sep 2008 14:08:29 -0400 Subject: Checking the boolean value of a collection In-Reply-To: <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> References: <mailman.921.1221227464.3487.python-list@python.org> <6ivbfvFnfucU1@mid.uni-berlin.de> <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> Message-ID: <gagviq$i9v$1@ger.gmane.org> Marco Bizzarri wrote: > On Fri, Sep 12, 2008 at 4:09 PM, Diez B. Roggisch <deets at nospam.web.de> wrote: > >> You should also consider using PEP8 style naming. >> >> >> Diez > > > class FolderInUse: > > def __init__(self, core): > self.core = core > > def true_for(self, archivefolder): > return any([instance.forbid_to_close(archivefolder) for instance in > self.core.active_outgoing_registration_instances()]) > > Is this any better? Yes. Now I can read it to suggest shorter names (I agree with FL here). I would consider 'outgoing' for 'a_o_r_i' and perhaps 'no_close' or 'stay_open' or suggestions below for 'f_t_c' > The true_for name does not satisfy me a lot... > maybe because it is too similar to True. Does one of 'locked', 'forbidden', 'untouchable' express the essence of the condition being tested? I would consider using the same adjective to name the test on instances and the collection of instances, or maybe 'x' and 'any_x'. Anyway, I'm trying a good > naming so that code is readable, like: > > specification = FolderInUse(core) > > if specification.true_for(folder): > ... > > Any thought about this? tjr From bmihelac at gmail.com Fri Sep 12 11:30:18 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Fri, 12 Sep 2008 08:30:18 -0700 (PDT) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> <mailman.930.1221232940.3487.python-list@python.org> Message-ID: <005ca418-9e1a-424b-b4d4-823427584424@x35g2000hsb.googlegroups.com> On Sep 12, 5:21?pm, Christian Heimes <li... at cheimes.de> wrote: > Bojan Mihelac wrote: > > I guess A class not yet exists in line 4. Is it possible to achive > > adding dynamic attributes without using exec? > > Correct, the class doesn't exist until the end of the class body. You > can either do it outside the class definition or you can use a metaclass. > > Christian thanks, can you give example on using a metaclass? From fredrik at pythonware.com Sat Sep 27 07:36:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Sep 2008 13:36:10 +0200 Subject: Using the 'with' statement with cStringIO objects In-Reply-To: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> Message-ID: <gbl5rd$gjv$1@ger.gmane.org> peppergrower wrote: > teststring='this is a test' > > with cStringIO.StringIO(teststring) as testfile: > pass umm. what exactly do you expect that code to do? </F> From tjreedy at udel.edu Mon Sep 8 23:21:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Sep 2008 23:21:04 -0400 Subject: universal unicode font for reportlab In-Reply-To: <ga4nq3$4kh$1@rumours.uwaterloo.ca> References: <mailman.674.1220863917.3487.python-list@python.org> <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> <mailman.705.1220907160.3487.python-list@python.org> <ga4nq3$4kh$1@rumours.uwaterloo.ca> Message-ID: <ga4q30$5nu$1@ger.gmane.org> Ross Ridge wrote: > Terry Reedy <tjreedy at udel.edu> wrote: >> My OpenOffice on WinXP uses a unicode font, I believe Lucida Sans >> Unicode, that seems to cover the entire BMP. > > Lucida Sans Unicode only covers a small subset of Unicode. It may seem > to cover a wider range because Windows (and possibly OpenOffice) will > automatically substitute characters from other fonts, if necessary. Sorry, I posted the wrong name. Ariel Unicode MS is the one that seems pretty complete. >> I don't know whether it was already installed or installed by OO or >> how one would get to it to extract it. > > It's a standard Windows font. From the MS, I would guess that is a Windows font too ;-). From lists at cheimes.de Mon Sep 8 05:28:12 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 08 Sep 2008 11:28:12 +0200 Subject: Test if list contains another list In-Reply-To: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> Message-ID: <ga2r78$lj$1@ger.gmane.org> mathieu wrote: > Hi there, > > I am trying to write something very simple to test if a list > contains another one: > > a = [1,2,3] > > b = [3,2,1,4] > > but 'a in b' returns False. How do I check that a is indeed contained > in b ? Use sets: >>> a = [1,2,3] >>> b = [3,2,1,4] >>> set(a).issubset(set(b)) True Christian From tchendrix at gmail.com Wed Sep 24 16:17:38 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Wed, 24 Sep 2008 13:17:38 -0700 (PDT) Subject: empty csv file attachments Message-ID: <200563c8-a4d1-45db-aaa1-63f885851b76@s50g2000hsb.googlegroups.com> hi group. I'm new to python but a veteran at programming. This one has me stumped. I have a simple contact form which the user fills out. The email is sent to the site user as well and it is delivered with the content in the body of the email as well in nice order. I have modified my code to also send the content as a csv attachment. On the server, the file is perfectly generated with content. The attachment, however, is completely blank. Any ideas what that could be? My code snippet is shown below: if int(attachmenttype)==2 or int(attachmenttype)==3: for field in ctx.request.field_names(): if field=='last_name': myfilename=ctx.request.field_value(field)+'.txt' if myfilename=='': myfilename='tempfile.txt' mypath= mynewfilepath + '/' + myfilename f=open(mypath, 'w') mynewstring='' counter=0 for field in ctx.request.field_names(): if field != 'inquiry_required': mynewstring=mynewstring + field +',' if mynewstring[-1]==',': mynewstring=mynewstring[0:len(mynewstring)-1] f.write(mynewstring) f.write ('\n') mynewstring='' counter=1 for field in ctx.request.field_names(): fielddata=ctx.request.field_value(field) if counter==1: dummydata=0 else: mynewstring=mynewstring + '"' + fielddata.replace('"','') + '",' counter = counter + 1 if mynewstring[-1]==',': mynewstring=mynewstring[0:len(mynewstring)-1] f.write(mynewstring) f.write('\n') f.close attachments.append('/'.join((ctx.request.library, myfilename))) [snip... sends email just after this] any ideas? From circularfunc at gmail.com Wed Sep 10 06:52:24 2008 From: circularfunc at gmail.com (process) Date: Wed, 10 Sep 2008 03:52:24 -0700 (PDT) Subject: which of these 2 quicksorts is faster? References: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> <mailman.767.1221042609.3487.python-list@python.org> Message-ID: <5fd41cf4-59c6-4d4d-bf4d-681e5bc88e6f@79g2000hsk.googlegroups.com> On Sep 10, 12:29?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > process wrote: > > qsort can handle bigger lists it seems, making less recursive calls > > before finishing(quicksort blows the stack when sorting > > range(100,-1000,-1). > > qsort does more work though right? is there a way to speed up that? > > > is the built-in sort not defined recursively? > > what makes you think you can write a better sort than the built-in > algorithm by typing in some toy quick-sort implementations from a > "sorting for dummies" article? > > </F> Where did I write that I was trying to do that? I am merely trying to learn. Get some social skills dude. From execrable at gmail.com Wed Sep 10 12:31:35 2008 From: execrable at gmail.com (B) Date: Wed, 10 Sep 2008 09:31:35 -0700 Subject: dict slice in python (translating perl to python) In-Reply-To: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Message-ID: <HDSxk.1411$ZY5.32@newsfe02.iad> for a long list, you could try: result = [mydict[k] for k in mydict] or [mydict[k] for k in mydict.keys()] or [mydict[k] for k in mydict.iterkeys()] this won't give you the same order as your code though, if you want them sorted you can use the sorted function: [mydict[k] for k in sorted(x)] (or sorted(x.etc)) hofer wrote: > Hi, > > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] > > print "%s\n%s\n%s" %(v1,v2,v3) > > > > thanks for any ideas > From lists at cheimes.de Mon Sep 8 15:03:48 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 08 Sep 2008 21:03:48 +0200 Subject: exit() In-Reply-To: <20080908134608759530.9d832e42@mac.com> References: <20080908134608759530.9d832e42@mac.com> Message-ID: <ga3suk$tkv$1@ger.gmane.org> Gary Robinson wrote: > In Python 2.5.2, I notice that, in the interpreter or in a script, I can exit with: > > exit() The exit callable is defined in the site module. Check out site.py! It shouldn't be used in code. It was added to help newbies to 'escape' from an interactive Python shell. Christian From steve at REMOVE-THIS-cybersource.com.au Fri Sep 26 11:13:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 15:13:29 GMT Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> Message-ID: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> On Fri, 26 Sep 2008 06:31:40 -0500, skip wrote: > I took over spam filter management for the python.org mailing lists a > couple months ago and made a few changes to the way the spam filter is > trained. Things seem to be at a reasonable level as far as I can tell (I > see a few spams leak through each day), though I wasn't actively reading > comp.lang.python/python-list at python.org before I took over the task, so > I have nothing to compare with. Does the level of spam leaking through > the filter now seem excessive? Is it more or less than in June and > July? I don't have any objective numbers, but subjectively it seems to me that the number of spams is significantly higher, but not so high as to be a major nuisance. -- Steven From bdesth.quelquechose at free.quelquepart.fr Wed Sep 24 13:31:44 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 19:31:44 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <gbe0kd$qh9$1@rumours.uwaterloo.ca> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <JcKdndouSNGG10fVnZ2dnUVZ_hCdnZ2d@posted.visi> <gbdmgh$nd0$1@rumours.uwaterloo.ca> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <gbe0kd$qh9$1@rumours.uwaterloo.ca> Message-ID: <48da956c$0$1269$426a74cc@news.free.fr> Ross Ridge a ?crit : (snip) > Grant Edwards <invalid at invalid> wrote: >> Same here. It's like an automotive engine controls designer >> asking if a failed O2 sensor should turn on the check engine >> light or blow up the car. > > Ross Ridge <rridge at csclub.uwaterloo.ca> wrote: >> No, it's more like asking if the failed sensor should turn on >> a strange and mysterious light on the dashboard > > Grant Edwards <invalid at invalid> wrote: >> You're right. I had forgotten that sys.exit() is actually >> raising the system exit exception, and that the application >> calling the library could handle that exception. > > Well, my point was that exceptions in Python are a bit like a car's > check engine light. Few drivers know what this mysterious light means, > and aren't prepared to do anything about it when it goes on. You're kidding, aren't you ? From larry.bates at vitalEsafe.com Tue Sep 23 17:15:26 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 23 Sep 2008 16:15:26 -0500 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <T_cCk.35701$rD2.7934@bignews4.bellsouth.net> Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), or should the exception propagate to the calling program which > handles the issue? > > Thanks in advance for anyone who can either answer my question or > point me to where this question has already been answered. > IMHO libraries should always just let the exception propagate up to the caller. That allows the caller the option of taking the appropriate action. -Larry From jake at vapourforge.com Fri Sep 19 10:30:53 2008 From: jake at vapourforge.com (Jake Anderson) Date: Sat, 20 Sep 2008 00:30:53 +1000 Subject: improving a huge double-for cycle In-Reply-To: <48d2bd22$0$4514$426a74cc@news.free.fr> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <48D3B79D.6080003@vapourforge.com> Bruno Desthuilliers wrote: > Alexzive a ?crit : >> Hello there :) , >> >> I am a python newbie and need to run following code for a task in an >> external simulation programm called "Abaqus" which makes use of python >> to access the mesh (ensamble of nodes with xy coordinates) of a >> certain geometrical model. >> >> [IN is the starting input containing the nodes to be check, there are >> some double nodes with the same x and y coordinates which need to be >> removed. SN is the output containing such double nodes] >> >> Code: Select all >> for i in range(len(IN)): #scan all elements of the list IN >> for j in range(len(IN)): >> if i <> j: >> if IN[i].coordinates[0] == IN[j].coordinates[0]: >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> SN.append(IN[i].label) >> >> >> >> Unfortunately my len(IN) is about 100.000 and the running time about >> 15h !!!! :( >> >> Any idea to improve it? > > A couple ones have been submitted. Harald gets a point about the > redundant tests (even if his solution seems to be broken, cf below) - > your inner loop should have looked like : > > for j in xrange(i+1, len(IN)) > > Now the obvious winner is pruebono - even unoptimized, using sets seems > to be *way* faster than even the most optimized corrected version of > your algorithm. > > Here's a quick bench - please everyone doublecheck it to make sure it's ok: > <snip code> > Results here (py2.5, gentoo linux, athlonxp1800, 512 ram): > > >>> test_results() > True > >>> test_times() > doubles0 : 1.55667901039 > doubles1 : 0.719144105911 > doubles2 : 0.703393936157 > doubles3 : 0.700654983521 > doubles4 : 0.706257104874 > doubles5 : 0.528184890747 > doubles6 : 0.461633205414 > doubles8 : 0.0134379863739 > doubles9 : 0.0108540058136 > >>> > > Not surprisingly, half less iterations makes for half less time. > Aliasing, as often, proves to be a good optimization too. But obviously, > using the correct data structure / algorithm combo is the key : simpler > code, and 115 times faster (143 times with aliasing). If pruebono > solution's is correct (and it as AFAICT), your 15 hours computation > should by now take less than 10 minutes... > > Ubuntu 8.04 core2 2.6(i think) without psycho doubles0 : 0.610555171967 doubles1 : 0.29314494133 doubles2 : 0.286273956299 doubles3 : 0.281984090805 doubles4 : 0.28240609169 doubles5 : 0.207377910614 doubles6 : 0.156388044357 doubles8 : 0.00533080101013 doubles9 : 0.00458884239197 with psycho doubles0 : 0.127684116364 doubles1 : 0.069571018219 doubles2 : 0.064826965332 doubles3 : 0.0702300071716 doubles4 : 0.0647261142731 doubles5 : 0.0522589683533 doubles6 : 0.0437579154968 doubles8 : 0.00190806388855 doubles9 : 0.00214099884033 On this small test its a variance between ~6x to 2X still its basically free so why not ;-> From mark at thomaszone.com Tue Sep 30 13:50:56 2008 From: mark at thomaszone.com (Mark Thomas) Date: Tue, 30 Sep 2008 10:50:56 -0700 (PDT) Subject: r"<path>" References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> Message-ID: <459b50e2-1284-46d5-b788-f4438c6104a7@w7g2000hsa.googlegroups.com> On Sep 30, 1:17?pm, Kyle Hayes <mrkyleha... at gmail.com> wrote: > Is there a way to use the 'r' in front of a variable instead of > directly in front of a string? Or do I need to use a function to get > all of the slashes automatically fixed? Is this what you're talking about? str = "foo/bar" re = Regexp.new(str) => /foo\/bar/ -- Mark. From exarkun at divmod.com Fri Sep 26 15:14:05 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 26 Sep 2008 15:14:05 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Message-ID: <20080926191405.29191.1556457531.divmod.quotient.30634@ohm> On Fri, 26 Sep 2008 14:04:35 -0500, Michael Mabin <d3vvnull at gmail.com> wrote: >Doesn't it depend on where and why you intend to execute the code? >Obviously some SQL is more at risk for exploit when the input is from the >screen on a web page than if you were running parameterized code in a >controlled batch environment. Or if you were writing code generators (which >is what I happen to do) which won't be run by the general public. > No, not really. Particularly when it's not any harder to be secure than it is to be insecure, there's no reason to pick the insecure solution. It doesn't cost you anything to be secure. It *might* cost you something to be insecure, even if the environment is controlled. It's rarely the case that you actually control *every* aspect of an environment, and you can't reliably predict how a piece of code you write will be used in the future (either by you or by someone else, perhaps someone you've never even met at the time you write the code). Jean-Paul From fredrik at pythonware.com Thu Sep 11 12:59:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 18:59:08 +0200 Subject: Python platform. In-Reply-To: <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <mailman.876.1221142791.3487.python-list@python.org> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> Message-ID: <gabiot$6vo$1@ger.gmane.org> carriere.jonathan at gmail.com wrote: > I want to build a desktop application. I am searching for some kind of > environment that would provide all the elements ready (Windows...). > Then I would have to code the business logic only. start here: http://wiki.python.org/moin/GuiProgramming The big ones are Tkinter, which is usually bundled with Python; wxPython, and PyQt. There's also a trend towards using the web browser as a presentation engine also for local applications; for libraries that help you with that, you can start here: http://wiki.python.org/moin/WebProgramming or jump directly to http://www.djangoproject.com/ </F> From sjmachin at lexicon.net Tue Sep 2 17:14:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 14:14:47 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <d5de89ff-ad8f-4a61-b6af-2c43f449acd0@m45g2000hsb.googlegroups.com> Message-ID: <5a3c1c2e-6613-41a9-b132-e979f978b14a@t1g2000pra.googlegroups.com> On Sep 3, 3:52 am, Mensanator <mensana... at aol.com> wrote: > On Sep 2, 11:55 am, Steven D'Aprano <st... at REMOVE-THIS- > > if (p & 1)==1: > print_evens = True > else: > print_evens = False > if (p & 2)==2: > print_odds = True > else: > print_odds = False > if (p & 4)==4: > print_debug = True > else: > print_debug = False No, no, no, you've taken "How to write verbose scripts" rather too literally; try this: print_evens = p & 1 print_odds = p & 2 print_debug = p & 4 From mensanator at aol.com Mon Sep 1 21:02:29 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 1 Sep 2008 18:02:29 -0700 (PDT) Subject: Py 2.6 changes References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <00cc7976$0$20302$c3e8da3@news.astraweb.com> <fb60e830-1267-48c9-9b99-3352a1db64cc@i76g2000hsf.googlegroups.com> Message-ID: <1bd15c2c-82e0-4742-a97f-ae16fb75ae26@m3g2000hsc.googlegroups.com> On Sep 1, 6:55?pm, bearophileH... at lycos.com wrote: > Steven D'Aprano: > > > productory() -- I don't know that function, and googling mostly comes up > > with retail product searches. Do you mean product(), > > Darn my English, you are right, sorry, I meant a product() of > course :-) But the name product() has already been taken by itertools to mean Cartesian Product. > > Bye, > bearophile From michael.pearmain at tangozebra.com Tue Sep 2 11:31:40 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 2 Sep 2008 08:31:40 -0700 (PDT) Subject: dict.update References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> <1b79577e-d74b-461f-ac0c-6841d3c22251@t1g2000pra.googlegroups.com> Message-ID: <223616eb-c9d6-4604-bc02-ec11815981b8@c58g2000hsc.googlegroups.com> Thanks Raymond, That's a neat trick, i'll look into learning more about this Mike From bearophileHUGS at lycos.com Wed Sep 3 11:37:07 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 08:37:07 -0700 (PDT) Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <87hc8xor9g.fsf@benfinney.id.au> Message-ID: <63b8f474-00e7-4c48-99a5-5d70b60d2e3d@b1g2000hsg.googlegroups.com> Ben Finney: > ? for numbers with many digits the digits may be divided into > groups of three by a thin space, in order to facilitate reading. > Neither dots nor commas are inserted in the spaces between groups > of three. > <URL:http://www.bipm.org/en/si/si_brochure/chapter5/5-3-2.html#5-3-4> > This isn't binding upon Python, of course. However, it should be a > consideration in choosing what separator convention to follow. It confirms what I say :-) A thin space doesn't break the gestalt of the number, while a normal space, especially if you use a not proportional font with good readability (and characters well spaced) breaks the single gestalt of the number. Bye, bearophile From fredrik at pythonware.com Mon Sep 8 10:41:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 16:41:42 +0200 Subject: firefox timestamp In-Reply-To: <9f9d35df0809072317h49ccec2ep72524f8d4900daa0@mail.gmail.com> References: <9f9d35df0809072317h49ccec2ep72524f8d4900daa0@mail.gmail.com> Message-ID: <ga3dj8$vfg$1@ger.gmane.org> abhilash pp wrote: > I don't know if this question will fit on this section, > any way my query is , i have used one script demork.py to extract > details from Firefox history.dat file > and now the problem is how to convert the TIMESTAMP given by that to > normal date and time. > example timestams are like this, > > 1202919771609375 > 1213874676203125 > 1215693263859375 > > i have used datetime module for this but it gave me error a quick googling indicates that the file contains microseconds, not seconds. dividing by 1e6 should do the trick: >>> t = 1202919771609375 >>> datetime.datetime.fromtimestamp(t / 1e6) datetime.datetime(2008, 2, 13, 17, 22, 51, 609375) </F> From castironpi at gmail.com Sat Sep 20 01:03:36 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 19 Sep 2008 22:03:36 -0700 (PDT) Subject: migrating processess to avoid the GIL References: <mailman.1288.1221867648.3487.python-list@python.org> Message-ID: <1d2982d9-9875-453b-9490-c33de612ebf6@m45g2000hsb.googlegroups.com> On Sep 19, 6:40?pm, "Patrick Stinson" <patrickstinson.li... at gmail.com> wrote: > I need to migrate calls to CPython to another process in my C++ app to > get around the GIL. Does anyone know of a good way to do this on > windows and Mac? All calls and callbacks can be blocking, I just need > to share some data structures. > > Cheers You should look into 'mmap' and 'struct'. mmap shares memory between processes, and is a random-access read-write file buffer. struct packs data from primitive types (integers, floats, & short strings) into a buffer. If you need advice on structuring your shared file, feel free to write back. From deets at nospam.web.de Mon Sep 1 07:21:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 13:21:55 +0200 Subject: Using NLTK in Java References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> <6i1hu9FnvcngU1@mid.uni-berlin.de> <d6558bd3-c077-4f09-b7cc-652ac3f17c7d@k13g2000hse.googlegroups.com> Message-ID: <6i21jaFomilbU1@mid.uni-berlin.de> hussainsaiger at gmail.com wrote: > On 1 Sep, 11:55, "Diez B. Roggisch" <de... at nospam.web.de> wrote: >> hussainsai... at gmail.com schrieb: >> >> > I am trying to convert a python module (that contains the use of >> > NLTK.Corpus) by jythonc. It is not able to include nltk dependencies >> > within the java class it creates. So when i use this class in java, it >> > fails to recognize nltk. Can anyone please let me know how should i >> > use nltk in python/jython modules so i can use in Java. >> >> If there are any binary dependencies, you are out of luck. It won't >> work. You would need to write a RPC-Server then, with technologies such >> as XMLRPC or CORBA. >> >> Diez > > So does that mean that Jython does not support nltk uptil now. I ask > this because when I try to import nltk in Jython (which is assumed to > replace Python), i get the same error. Its just nltk that I am not > able to use. The rest of the jython functions and libraries work fine > within Java. I don't know for sure - how about you post the error-message? Otherwise we can't assess the problem. Diez From asdfasdfasdfasdfasdf at arcor.de Sat Sep 6 17:04:14 2008 From: asdfasdfasdfasdfasdf at arcor.de (Andreas Hofmann) Date: Sat, 06 Sep 2008 23:04:14 +0200 Subject: String/Number Conversion Message-ID: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Hello Folks! I've got a little problem here, which which really creeps me out at the moment. I've got some strings, which only contain numbers plus eventually one character as si-postfix (k for kilo, m for mega, g for giga). I'm trying to convert those strings to integers, with this function: def eliminate_postfix(value): if type(value) is str: value.upper() if value.endswith('K'): mult = 1000 elif value.endswith('M'): mult = 1000000 elif value.endswith('G'): mult = 1000000000 else: mult = 1 if mult is 1: value = string.atoi(value) else: value = string.atoi(value[:-1]) * mult return value The problem is as follows: Everytime a string with a postfix should get converted, mult does not get set properly. It is always 1. Does anyone have an idea how to fix this? I just don't see it, maybe because I'm pretty new to python or because I'm just blind I would be really greatful. Kind regards, Andy From steve at REMOVE-THIS-cybersource.com.au Mon Sep 22 18:32:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 22:32:48 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <mailman.1347.1222042368.3487.python-list@python.org> <pan.2008.09.22.09.07.43@REMOVE.THIS.cybersource.com.au> <mailman.1357.1222076517.3487.python-list@python.org> Message-ID: <00e816f4$0$20303$c3e8da3@news.astraweb.com> On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: > On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano >> But that's precisely what I want to avoid: I don't want the objects to >> share *any* state, not even their class. I'm not trying for a Borg or >> Singleton: the user can call the factory as many times as they want, >> but the objects returned shouldn't share any state. I don't know if >> what I want has a name. Judging from people's reactions, I'd say >> probably not. > > Snce when are "users" ever involved > in programming problems or programming languages ? What an astounding question. Consider a class. There are the programmers who write the class, and there are the programmers (possibly the same people, but not necessarily) who use the class. The second set of people, the programmers who use the class, are *users* of the class. What else would they be? -- Steven From castironpi at gmail.com Wed Sep 24 21:57:55 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 18:57:55 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <f5a4027b-4b9b-4d09-b76b-11d50b8070eb@p31g2000prf.googlegroups.com> <zllxzcpt.fsf@wgmail2.gatwick.eur.slb.com> <beeea088-c336-465e-a24c-160f5c56a2c4@p10g2000prf.googlegroups.com> Message-ID: <c4817afc-d588-4807-8e45-25d22988652c@59g2000hsb.googlegroups.com> On Sep 24, 8:40?pm, Asun Friere <afri... at yahoo.co.uk> wrote: > On Sep 25, 3:16 am, Pete Forman <pete.for... at westerngeco.com> wrote: > > > Asun Friere <afri... at yahoo.co.uk> writes: > > > ?> A canonical use of the conditional operator is in > > ?> pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). > > > That fails for n == 1. ?So what is best? > > Sorry missing parantheses. ?I should test, even for fragments written > out as part of a sentence. %-/ > > > for i in range(4): > > ? ? print '%d thing' % i + ('s' if i != 1 else '') > > That's the corrected version of what I meant, but actually I think > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding > all variables for placeholders in the tuple, is better. It's certainly > more readible. It's a different answer if you have 'things is/are'. '%d thing%s %s'% ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ). Or excluding prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's are' if i!= 1 else ' is' ). From bearophileHUGS at lycos.com Wed Sep 3 19:00:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 16:00:26 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> Message-ID: <8a5d982c-d5da-4b1d-bc29-228eca4202ae@v16g2000prc.googlegroups.com> Laszlo Nagy: > I believe that there have been excessive discussions about this > decision, and the current implementation is very good, if not the best. I see. But note that my post is mostly about the max()/min() functions :-) Bye, bearophile From ebgssth at gmail.com Thu Sep 25 17:02:45 2008 From: ebgssth at gmail.com (js) Date: Fri, 26 Sep 2008 06:02:45 +0900 Subject: How can I customize builtin module search path to prefix/lib to prefix/lib64? In-Reply-To: <c88dfce7-98bb-4827-a69d-3b3cb12820a0@y21g2000hsf.googlegroups.com> References: <c88dfce7-98bb-4827-a69d-3b3cb12820a0@y21g2000hsf.googlegroups.com> Message-ID: <a23effaf0809251402q50ba938bk3ef212f6c91d6b01@mail.gmail.com> For 64bit python, there's no need to look at lib/lib-dynload because libraries for 64bit should be in lib64/lib-dynload. Having module search path which point to libraries the python can not understand is, IMHO, wrong. On Fri, Sep 26, 2008 at 3:03 AM, Mike Driscoll <kyosohma at gmail.com> wrote: > On Sep 25, 10:41 am, js <ebgs... at gmail.com> wrote: >> Hi list, >> >> Is it possible to change module search path (PYTHONPATH) built-in to >> Python interpreter? >> I thought I can change it with configure --libdir but it didn't work for me. >> I also tried patching around python source tree replacing lib to lib64 >> but it didn't work either. >> >> Adjusting sys.path directly or using environ should do the trick but >> I'd rather want to make it the default path for my python >> >> Thanks, > > Why not just add a custom path file (*.pth)? EasyInstall, wx, PyWin32 > and others do it. Of course there's always sys.path.append as well. > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Tue Sep 9 16:04:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 17:04:04 -0300 Subject: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles References: <ga6gfu$lgk$1@aioe.org> Message-ID: <op.ug8co2z9x6zn5v@a98gizw.cpe.telecentro.net.ar> En Tue, 09 Sep 2008 15:49:32 -0300, Michael Hoffman <4g4trz802 at sneakemail.com> escribi?: > I've written a NamedTemporaryDir class which is derived somewhat from > tempfile.NamedTemporaryFile in the standard library. Right now I am > using NamedTemporaryFile to create individual files, but since I am > putting them in a directory that will be deleted anyway, I'm wondering > if I can simplify things (and not have to keep track of all fo the > NamedTemporaryFile instances) by using tempfile.mkstemp() specifying my > temporary directory, and relying on the directory deletion when exiting > its with block. Looks fine... > def close(self): > if not self.close_called: > self.close_called = True > self.unlink(self.name) Windows won't let you remove a non-empty directory. > def __exit__(self, exc, value, tb): > result = self.file.__exit__(exc, value, tb) > self.close() > return result self.file? -- Gabriel Genellina From deets at nospam.web.de Fri Sep 5 07:12:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 13:12:16 +0200 Subject: newbie question: how to run a python file if it is in a package In-Reply-To: <cee5bd8f-3f02-4287-8fe2-176b4ca2d61b@q26g2000prq.googlegroups.com> References: <cee5bd8f-3f02-4287-8fe2-176b4ca2d61b@q26g2000prq.googlegroups.com> Message-ID: <6icighFpi4dpU1@mid.uni-berlin.de> neoedmund schrieb: > for example: > > X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y" > how can I run X.py avoiding it saying such like "ImportError: No > module named aaa.bbb"? > > Is all runnable script must be in the default package? There is no such thing as a "default package" All imports are resolved over the "sys.path" list of directories (or eggs). There are various ways to modify this: - by hand. If you know X.py lives below aaa/bbb, you can get it's __file__-attribute, and walk the way down two levels. Then add the resulting path to sys.path. All this has to be done before any import of aaa.bbb occurs. - modify the environment variable PYTHONPATH to contain the root of aaa.bbb before starting the script. - write a custom .pth-file and place it into your pythno installation. The pth-file will contain the above mentioned root path. - use setuptools to create script entry-points, and install your whole application either fully, or as so-called egg-link. Possibly inside a virtualenv. This would be my personally preferred method. - simply copy your wohe aaa.bbb-stuff into site-packages. Make sure you do that whenever you change something in your code. Diez From http Wed Sep 10 17:50:07 2008 From: http (Paul Rubin) Date: 10 Sep 2008 14:50:07 -0700 Subject: handling uncaught exceptions with pdb? Message-ID: <7xmyifpt68.fsf@ruckus.brouhaha.com> I think I've asked about this before, but is there a way to set up Python to handle uncaught exceptions with pdb? I know about setting sys.except_hook to something that calls pdb, but this is normally done at the outer level of a program, and by the time that hook gets called, the exception has already unwound the stack to the outermost level. My situation is I run a multi-hour or multi-day computation that eventually crashes due to some unexpected input and I'd like to break to the debugger at the innermost level, right when the exception is encountered, so I can fix the error with pdb commands and resume processing. Of course this presumes a certain semantics for Python exceptions (i.e. handling one involves scanning the stack twice, once to look for a handler and again to actually unwind the stack) and I'm not sure if it's really done that way. I do know that Lisp has a requirement like that, though; so maybe there is hope. From __peter__ at web.de Thu Sep 18 05:32:47 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2008 11:32:47 +0200 Subject: decorator and API References: <mailman.1183.1221688957.3487.python-list@python.org> <pan.2008.09.18.03.35.53@REMOVE.THIS.cybersource.com.au> Message-ID: <gat77u$33p$02$1@news.t-online.com> Steven D'Aprano wrote: I agree with you that the simple explicit approach is better. Now, to answer the question the OP didn't ask: > def choose_with_weighting(actions, weights=None): > ? ? if weights is None: > ? ? ? ? weights = [1]*len(actions) ?# equal weights > ? ? # Taken virtually unchanged from your code. > ? ? # I hope it does what you want it to do! It probably doesn't. > ? ? assert len(weights) == len(actions) > ? ? total = sum(weights) > ? ? choice = random.randrange(total) > ? ? while choice > weights[0]: > ? ? ? ? choice -= weights[0] > ? ? ? ? weights.pop(0) > ? ? ? ? actions.pop(0) > ? ? return actions[0] Assume two actions with equal weights [1, 1]. total becomes 2, and choice is either 0 or 1, but never > weights[0]. While this can be fixed by changing the while condition to while choice >= weights[0]: #... I prefer an approach that doesn't destroy the actions and weights lists, something like import bisect def choose_with_weighting(actions, weights=None, acc_weights=None): if acc_weights is None: if weights is None: return random.choice(actions) else: sigma = 0 acc_weights = [] for w in weights: sigma += w acc_weights.append(sigma) return actions[bisect.bisect(acc_weights, random.randrange(acc_weights[-1]))] especially if you prepare the acc_weights list once outside the function. Peter From robert.kern at gmail.com Sat Sep 27 19:07:36 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Sep 2008 18:07:36 -0500 Subject: EPD (Enthought Python Distribution) 4.0.300 Beta 3 available In-Reply-To: <975844EF-46F5-439E-8481-544A91EF7A98@dcs.shef.ac.uk> References: <48DDCDDA.50009@enthought.com> <975844EF-46F5-439E-8481-544A91EF7A98@dcs.shef.ac.uk> Message-ID: <gbmebp$s70$1@ger.gmane.org> Disclosure: I work for Enthought. Christopher Brewster wrote: > I have always thought this idea very good, but if I download it and > install it (on my MacBook pro) will any conflicts occur with existing > bits and pieces of Python and its libraries? For the Mac distribution, we have tried very carefully to keep EPD's Python separate from any previous installation. I believe the only thing that will get "overwritten" is that our bin/ directory inside our version of Python.framework will get prepended to your $PATH environment variable. This will be added to your ~/.bash_profile with a a descriptive comment. When you type $ python at your Terminal prompt, you will get EPD's Python. To uninstall EPD, you can remove those lines in your ~/.bash_profile, delete /Library/Frameworks/Python.framework/Versions/4.0.300/, and delete "/Applications/EPD <something or other>/". Then your previous Python installation should be usable again. To just use your previous Python installation without uninstalling EPD, just comment out our addition to ~/.bash_profile. If you have more questions about EPD, please join us on the enthought-dev mailing list: https://mail.enthought.com/mailman/listinfo/enthought-dev -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at REMOVE-THIS-cybersource.com.au Sun Sep 21 18:39:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 22:39:47 GMT Subject: What do you call a class not intended to be instantiated Message-ID: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! "Abstract class" isn't right, because that implies that you should subclass the class and then instantiate the subclasses. What do you call such a class? -- Steven From maric at aristote.info Thu Sep 4 07:54:56 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 4 Sep 2008 13:54:56 +0200 Subject: cPickle In-Reply-To: <g9ofjv$44p$1@ger.gmane.org> References: <01f901c90e70$8e118a50$2fc513ac@pwit.com> <g9ofjv$44p$1@ger.gmane.org> Message-ID: <200809041354.57003.maric@aristote.info> Le Thursday 04 September 2008 13:08:59 Gerhard H?ring, vous avez ?crit?: > gopal mishra wrote: > > I have 3 objects and want to save in one pickle file. > > > > I used cPickle to dump 3 objects in a pkl file > > > > i.e cPickle.dump(object1, fileobject, -1) > > > > cPickle.dump(object2, fileobject, -1) > > > > cPickle.dump(object3, fileobject, -1) > > > > > > > > I have changed the 3^rd object and want to save the updated 3^rd object > > in the pickle file. > > > > I have to dump all the 3 objects again. > > > > Is there any way to dump only the 3^rd object in to the pkl file. > > No, there isn't. You could, of course, save each object in its own > pickle file. Or use an object database like ZODB instead. > Shelve is another alternative, shipped with python and rather straightforward. Shelve as ZODB use pickles of objects but, unlike ZODB, won't need you change anything to your actual classes. >>>[8]: import shelve >>>[9]: s = shelve.open('db') >>>[10]: a, b, c = 5, 4., ("foo", "bar") >>>[11]: s['a'], s['b'], s['c'] = a, b, c >>>[12]: s.close() >>>[13]: maric at redflag1 13:46:42:~$ file db db: Berkeley DB (Hash, version 8, native byte-order) maric at redflag1 13:46:44:~$ ipython >>>[1]: import shelve >>>[2]: s = shelve.open('db') >>>[3]: for name, value in s.items() : print name, value ...: b 4.0 a 5 c ('foo', 'bar') >>>[5]: del s['b'] >>>[6]: s['c'] += ('baz',) >>>[7]: s.sync() >>>[8]: maric at redflag1 13:48:12:~$ ipython >>>[1]: import shelve >>>[2]: s = shelve.open('db') >>>[3]: for name, value in s.items() : print name, value ...: a 5 c ('foo', 'bar', 'baz') The sync method may not work on all platform, maybe you'll have to close and re-open the db file to write to disk. -- _____________ Maric Michaud From pataphor at gmail.com Sun Sep 14 09:25:28 2008 From: pataphor at gmail.com (pataphor) Date: Sun, 14 Sep 2008 15:25:28 +0200 Subject: How to emit Cyrillic and Chinese via unicode from console mode? References: <ieidnYDBwLZ3_1HVnZ2dnUVZ_tPinZ2d@comcast.com> <543bde0c-4d99-4d79-a4dd-b6f8d85e8c48@l64g2000hse.googlegroups.com> Message-ID: <20080914152528.51457e1f@hyperspace> On Sun, 14 Sep 2008 01:02:39 -0700 (PDT) rs387 <rstarkov at gmail.com> wrote: > On Sep 14, 2:03?am, "Siegfried Heintze" <siegfr... at heintze.com> wrote: > > Can someone point me to an example of a little program that emits > > non-ascii Unicode characters (Russian or Chinese perhaps)? > > The following doesn't quite work, but I'll post it anyway since it > actually ends up printing the characters. That's more like it! Just answer with whatever one has. Here's another gem: from Tkinter import * from collections import deque def byn(x,n =5 ): L = deque(x) R = [] while L: R.append(L.popleft()) if len(R) == n: yield ''.join(R) R = [] if R: yield ''.join(R) root = Tk() start = int('16A6',16) end = int('16F0',16) g = (unichr(i) for i in xrange(start, end+1)) L = byn(g,16) s = '\n'.join(L) w = Label(root, text=s,font = ("freemono","80")) w.pack() root.mainloop() P. From vaidehi.pawar at yahoo.co.in Wed Sep 10 17:49:50 2008 From: vaidehi.pawar at yahoo.co.in (Vaidehi Pawar) Date: Thu, 11 Sep 2008 03:19:50 +0530 (IST) Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... Message-ID: <276719.72706.qm@web95107.mail.in2.yahoo.com> I know I'm tooooo late to ask you for help....but please help me out..I am really new to unix and dont know how to finish this assignment on time.....proff. said he will be using MOSS to detect whether I downloaded the code..please help me.. email me : vaidehi.pawar at yahoo.co.in Assignment 1 Processes, Inter-Process Communication, and Concurrency Due September 13th midnight Summary In this assignment, you will create two versions of a simple multi-process game : one without and another with inter-process synchronization. You will also measure the relative performance of the two versions of your multi-process game. Objectives * Learn how to create and terminate processes. * Learn use of inter-process communication using shared memory, semaphores, signals, etc. * Learn the basic workings of CPU scheduling code in Linux. Part A: Multi-Process Game of Turns In this part, you are asked to write a simple program that takes two command-line arguments P and N. The main process creates P other child processes, waits for all of them to complete, and then exits. All the child processes form one logical ring among each other. (In rest of the description, the term "process" refers to a "child process".) For example, if the processes are numbered 1 to P, then * The next neighbor of process 1 is process 2, * The next neighbor of process i is process i+1 for all i < P , and * The next neighbor of process P is process 1, which completes a ring among the processes. Assume that a shared integer variable, called turn, identifies the number of the processes whose turn it is at any instant. A second process-local variable in each process, called me, identifies the identity of each process (i.e. each process stores its own identity in a per-process local variable me). A third per-process local variable, called next, identifies the next process in the ring. The processes sequentially pass the turns among each other in the logical ring. When each process gets its turn, it increments another shared variable called counter. The pseudo-code within each process for passing turns might look something as follows. (Note: Replace turn and counter below with appropriate ways of accessing data within shared memory regions). while(turn != me ) /* do nothing - just busy loop*/ ; /* got my turn - increment counter */ counter = counter + 1; /* give the turn to next process */ turn = next; The program terminates when the each process has received N turns. In the above description, several programming details have been omitted for you to figure out. This includes * Creating P child processes from main process. * Constructing the logical ring among child processes. o Initializing each child process's identity in the me variable. o Initializing each child process' next neighbor in the next variable. * Initializing the shared memory region and the shared data values. * Have the main process wait for child processes to complete N turns before exiting. Part B: More Efficient Game of Turns You might notice that the program you wrote in Part A is inefficient because each process busy loops till the CPU scheduler kicks it out (after its time-slice is over) and allows another process to execute and make progress. (Does the program in Part A have a race condition? Why or why not?) What we ideally want is that each process should be given control of the CPU only when it is that process' turn. Modify the program you wrote in Part A (using appropriate synchronization mechanisms) such that each process gets to run (i.e., gets control of the CPU) only when it is that process's turn, and at no other time. Again, you would need to work out the programming details of how and where to use inter-process synchronization. Part C: Profiling the Game of Turns In this part, you are asked to write user-level profiling code in order to measure the performance of the two versions of programs you wrote in Part A and Part B. Use a combination of gettimeofday() system call and inter-process synchronization to measure (1) the average hand-over time between two consecutive processes in the ring and (b) the total execution time to complete N turns. Plot the measured values as graphs when varying number of processes P and number of turns N. Explain the results you obtain. Submission Guidelines Thanking you, Ms. Vaidehi Pawar ________________________________ Check out the all-new face of Yahoo! India. Go to http://in.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080911/abc03a9e/attachment.html> From metallourlante at gmail.com Sun Sep 21 09:17:36 2008 From: metallourlante at gmail.com (Alex) Date: Sun, 21 Sep 2008 06:17:36 -0700 (PDT) Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> <974c3434-d409-484d-8bc4-7a3294132bd0@73g2000hsx.googlegroups.com> Message-ID: <e9b3c8ed-c548-4807-8c3b-1fe7ccc0009b@m3g2000hsc.googlegroups.com> On 21 Set, 15:07, George Sakkis <george.sak... at gmail.com> wrote: > On Sep 21, 8:51 am, Alex <metallourla... at gmail.com> wrote: > > > > > Hi all! > > > I have a problem understanding the behaviour of this snippet: > > > data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) > > > for i in range(len(data_set)): > > ds = data_set[:] > > data = ds[i] > > if i == 1: data['param'] = "y" > > if i == 2: data['param'] = "x" > > > print data_set > > > This script print out: > > ({'param': 'a'}, {'param': 'y'}, {'param': 'x'}) > > > Why? I'm coping data_set in ds so why data_set is changed? > > Because you're doing a shallow copy:http://docs.python.org/lib/module-copy.html > > George Thanks a lot. It was giving me and headache! From castironpi at gmail.com Sun Sep 28 19:11:06 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 16:11:06 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> Message-ID: <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> On Sep 28, 4:47?pm, Terry Reedy <tjre... at udel.edu> wrote: > Aaron "Castironpi" Brady wrote: > > On Sep 28, 2:52 am, Steven D'Aprano <st... at REMOVE-THIS- > >> As for why the complicated version works, it may be clearer if you expand > >> it from a one-liner: > > >> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) > > >> inner = lambda: n > >> outer = lambda n: inner > >> f[n] = outer(n) > > >> outer(0) => inner with a local scope of n=0 > >> outer(1) => inner with a local scope of n=1 etc. > > For this to work, the 'expansion' has to be mental and not actual. > Which is to say, inner must be a text macro to be substituted back into > outer. > > >> Then, later, when you call inner() it grabs the local scope and returns > >> the number you expected. > > > I must have misunderstood. ?Here's my run of your code: > > I cannot speak to what Steven meant, but > > >>>> inner = lambda: n > > when inner is actually compiled outside of outer, it is no longer a > closure over outer's 'n' and 'n' will be looked for in globals instead. > > >>>> outer = lambda n: inner > >>>> outer(0) > > <function <lambda> at 0x00A01170> > >>>> a=outer(0) > >>>> b=outer(1) > >>>> a() > > Traceback (most recent call last): > > ? File "<stdin>", line 1, in <module> > > ? File "<stdin>", line 1, in <lambda> > > NameError: global name 'n' is not defined > > > Why doesn't 'inner' know it's been used in two different scopes, and > > look up 'n' based on the one it's in? > > That would be dynamic rather than lexical scoping. I couldn't find how those apply on the wikipedia website. It says: "dynamic scoping can be dangerous and almost no modern languages use it", but it sounded like that was what closures use. Or maybe it was what 'inner' in Steven's example would use. I'm confused. Actually, I'll pick this apart a little bit. See above when I suggested 'late' and 'early' functions which control (or simulate) different bindings. I get the idea that 'late' bound functions would use a dangerous "dynamic scope", but I could be wrong; that's just my impression. > >> inner = lambda: n > >> outer = lambda n: inner > >> f[n] = outer(n) > > >> outer(0) => inner with a local scope of n=0 > >> outer(1) => inner with a local scope of n=1 etc. If you defined these as: inner= late( lambda: n ) outer= lambda n: inner You could get the right results. It's not even clear you need quotes. Perhaps 'late' could carry the definition of 'n' with it when it's returned from 'outer'. In my proposal, it makes a copy of the "localest" namespace, at least all the variables used below it, then returns its argument in an original closure. From noelob at gmail.com Mon Sep 22 06:21:57 2008 From: noelob at gmail.com (noelob) Date: Mon, 22 Sep 2008 03:21:57 -0700 (PDT) Subject: BadStatusLine: Message-ID: <4e3d5d97-1b5f-4593-9c33-ad8b57d59b05@f36g2000hsa.googlegroups.com> Hi All, During performance testing of my web application, I occasionally get a BadStatusLine exception from httplib. Reading http://docs.python.org/lib/module-httplib.html#l2h-4021 tells me that it's "Raised if a server responds with a HTTP status code that we don't understand." Is there a way to find what the actual status code returned was? I.e. the value that caused the exception to be thrown? Under what circumstances is a BadStatusLine normally thrown? (e.g. data corruption?) I'm quite new to python, but not to programming. Apologies if this is a silly question ;) Thanks, Noel From pruebauno at latinmail.com Thu Sep 18 11:18:34 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 18 Sep 2008 08:18:34 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <30fab72b-2d7f-497d-a687-1d697633db9c@z66g2000hsc.googlegroups.com> On Sep 18, 8:25 am, Alexzive <zasaconsult... at gmail.com> wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > but no improvements. > > Many thanks, Alex dup=set() SN=[] for item in IN: c=item.coordinates[0], item.coordinates[1] if c in dup: SN.append(item.label) else: dup.add(c) From mailcindy at gmail.com Tue Sep 30 02:53:21 2008 From: mailcindy at gmail.com (cindy jones) Date: Tue, 30 Sep 2008 12:23:21 +0530 Subject: Python script for tracert Message-ID: <46da4e770809292353o2d72091aj6e717e35e62cfce6@mail.gmail.com> Hello.. I'm trying to do a scripting for tracert in windows using python... I'm using popen(), but it displays only after the tracert is completed. i want the results to be displayed for every route. can anyone help me in this.. Thank You -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/5efbb8d4/attachment.html> From don.hamilton at btinternet.com Fri Sep 12 13:16:31 2008 From: don.hamilton at btinternet.com (Don) Date: Fri, 12 Sep 2008 18:16:31 +0100 Subject: Which version Message-ID: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> Hi, I'm a reasonably experienced in other languages and have just decided to get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed, is this good enough to start out with or am I likely to encounter bugs that have been fixed in later versions. Don From M8R-yfto6h at mailinator.com Sun Sep 28 20:58:28 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 28 Sep 2008 17:58:28 -0700 Subject: Python 3.0 and repr References: <q6KdnXBZ9LioJkLVnZ2dnUVZ_u-dnZ2d@comcast.com> <48dffb54$0$1082$9b622d9e@news.freenet.de> Message-ID: <a9-dnTLNuJGztX3VnZ2dnUVZ_h6dnZ2d@comcast.com> ""Martin v. L?wis"" <martin at v.loewis.de> wrote in message news:48dffb54$0$1082$9b622d9e at news.freenet.de... >> What are others' opinions? Any insight to this design decision? > > The intention is that all printable characters in a string get displayed > in repr. This was in particular requested by Japanese users (but also by > other users of non-ASCII characters) which complained that repr() is > fairly useless if your strings actually contains *no* ASCII characters > (but all of them are printable). > > Notice that repr() of the string actually succeeds; try > >>>> x='\u5000' >>>> z=repr(x) > > It is the printing of the repr that fails. > >> Maybe repr() should always display the ASCII representation with >> escapes for all other characters > > You can use the ascii() builtin if you want that. > >> especially considering the "repr() should produce output suitable for >> eval() when possible" rule. > > But that is preserved under the new behavior, also! Just try > > py> x='\u5000' > py> eval(repr(x))==x > True > > Regards, > Martin Thanks Martin, it's clear now. I just read about the new ascii() function before seeing your reply. > P.S. How did you manage to get U+5000 into your data, on a system where > the terminal encoding is cp437? Google translates it as "Rash"; the > Unihan database also has "bewildered", "wildly". I just picked that example out of the air. I study Chinese and knew it was a character in that area of the Unicode map. My usual editors (PythonWin and PyAlaMode from wxPython) don't work with Python 3, which was why I was using the Windows cmd prompt. Thanks, Mark From invalid at invalid Thu Sep 18 13:47:41 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 18 Sep 2008 12:47:41 -0500 Subject: PEP proposal optparse References: <ca58efdf-3f9c-4aea-9c20-69c69a578754@k30g2000hse.googlegroups.com> <baKdnTZYS-BM4U_VnZ2dnUVZ_jKdnZ2d@posted.visi> <6jffpaF2s539U1@mid.uni-berlin.de> Message-ID: <p8GdnS_ddZmgCU_VnZ2dnUVZ_sTinZ2d@posted.visi> On 2008-09-18, Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote: > On Thu, 18 Sep 2008 11:07:45 -0500, Grant Edwards wrote: > >> While we're making suggestions, I've always wished that the --help >> output displayed the default values for options in addition to the help >> text specified by the user. I end up having to enter the default values >> twice -- once as a keyword argument and again in the help text. > > '%default' in the help text will be replaced by the default value. See > the last option in the first example here: > > http://docs.python.org/lib/optparse-generating-help.html Great! I guess I should scan the doc pages for changes more often. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com From mathieu.prevot at gmail.com Sat Sep 6 11:14:33 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Sat, 6 Sep 2008 17:14:33 +0200 Subject: Canonical way to build Python 2.6/svn on MacIntel/MacOSX10.5 with icc 32bits 10.1.014 Message-ID: <3e473cc60809060814y4ff4eca6sf89b7af03c94b9f4@mail.gmail.com> Hi, I would like to build Python (svn) on Macosx 10.5 with icc in /opt/intel/cc (32 bit). Can you help me to determine the right way to do this ? I got a prototype with: export CC=icc export CXX=icpc export CFLAGS="-w" ./configure --with-framework-name=PythonIntel 1) It seems to be unsufficient. Does someone have links/mail archives/patches/scripts ? 2) Python needs gettext for _locale package, but I fail to compile it with icc. 3) How can I build an autonomous and sufficient distribution (a dmg file with everything in it) ? Thanks, Mathieu From raj.indian.08 at gmail.com Thu Sep 18 11:14:03 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Thu, 18 Sep 2008 08:14:03 -0700 (PDT) Subject: Modifying the system menu References: <bfa45e21-fb5e-454d-a4c2-e7cc00919f38@p31g2000prf.googlegroups.com> <mailman.1154.1221639413.3487.python-list@python.org> <8c1df849-d6e0-409a-930d-0593eed85683@a29g2000pra.googlegroups.com> Message-ID: <1e409ef1-ffd1-4774-8b12-d62d9b79e130@a29g2000pra.googlegroups.com> On Sep 18, 6:39?am, raj.indian... at gmail.com wrote: > I tested it again and found that the behaviour is a little different > from what I mentioned previously in the mailchain. > The item is working perfectly the first time around. Now if I close > the application and run it again (which was what I did earlier), if > that application system menu is already modified, it is causing this > issue. > > Why would this happen? If it is that the file handle is not obtained, > it wouldnt have gone through the following check at all? > > > ? ? hw = win32gui.GetSystemMenu(hwnd, False) > > ? ? if hw != None: > > ? ? ? ? win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); > > Not only did it go through, it failed with an invalid menu handle > error. More worryingly, this happens randomly. Am I doing some mistake here? From bignose+hates-spam at benfinney.id.au Thu Sep 11 01:25:57 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 11 Sep 2008 15:25:57 +1000 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> Message-ID: <87k5djb6e2.fsf@benfinney.id.au> Grant Edwards <grante at visi.com> writes: > On 2008-09-10, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: > > Grant Edwards <grante at visi.com> writes: > > > >> Could whoever is responsible for the gateway that is grabbing > >> my postings off of Usenet and e-mailing them out please fix the > >> headers in the mail messages so that I don't get the bounce > >> messages? > > > > The bounce messages are sent to you because you sent the > > original. > > Wrong. I didn't send _any_ e-mail. Why should I get bounce > messages? You asked for email to be sent, by sending a Usenet post to comp.lang.python. That's what a news-to-mail gateway does. > Isn't sending e-mails pretending they're from somebody else > considered unethical (if not illegal)? No, since it's clearly the function of a news-to-mail gateway to make this forum operate as a single pool of communication, seamlessly passing the messages between two distinct media. That happens by preserving the messages as intact as feasible in both media. > > Indeed it is rude, and the person subscribed to the mailing list > > whose software is sending these bounce messages is the one > > responsible for making it stop. > > No, the one who's sending e-mail with forged headers is the one who > ought to make it stop. That e-mail was not from me. It was from > somebody who grabbed the article off a usenet server and mailed it > to a bunch of people. You seem to be arguing that the news-to-mail gateway of this forum should stop functioning. I don't know if you're claiming to be ignorant of the news-to-mail gateway before now; if so, I hope you'll agree that having a large body of mostly well-behaved contributors on this joint forum is worth effort to keep it operational. > I think the list administrator ought to stop putting other people's > e-mail addresses in the From: headers of e-mails he's sending. (Note that an email message has exactly one header, by definition; it consists of separate fields, of which the From field is one.) It's unfortunate that you don't like how the news-to-mail gateway functions, but I'm not convinced that one person's surprise at how it operates should be reason to break its primary function. I sympathise completely with your irritation at receiving bounce messages from poorly-configured software, but the solution is not to break the news-to-mail gateway. The correct solution is to unsubscribe the badly-behaving address from the mailing list, and refuse re-subscription from that address without assurance that the bad behaviour has ceased. -- \ ?A child of five could understand this. Fetch me a child of | `\ five.? ?Groucho Marx | _o__) | Ben Finney From maric at aristote.info Mon Sep 15 08:09:13 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 14:09:13 +0200 Subject: Abstract class In-Reply-To: <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> References: <mailman.1008.1221408214.3487.python-list@python.org> <mailman.1012.1221419718.3487.python-list@python.org> <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <200809151409.14149.maric@aristote.info> Le Sunday 14 September 2008 22:25:18 Steven D'Aprano, vous avez ?crit?: > On Sun, 14 Sep 2008 12:15:04 -0700, Gary Herron wrote: > > (If you wish to consider the base class "abstract", just agree with > > yourself to not instantiate it.) > > That's certainly the most lightweight option. > > > Please forget about Abstract Base Classes. They have nothing to do with > > what you want, and are a *HUGE* overkill for your application. They > > are not (yet) even part of standard Python, and are used primarily for a > > class implementor to guarantee to a user of a class that it provides a > > specific interface. > > You can implement a lightweight abstract base class in Python fairly > easily, by adding two lines to the __init__ method of your base class. > > > class Base(object): > def __init__(self): > if self.__class__ is Base: > raise NotImplementedError("Abstract base class") > def method(self, *args): > return len(args) # or something useful > > But this doesn't match what abstract classes are (in C++ for example), because __init__ can, and probably will, have logic reusable in concrete classes. The only way to do this is to call in the __int__ at least one of the methods raising NotImplementedError, probably creating a dummy one for this purpose, and still it doesn't satisfy with the constraint that *all* abstract methods must be implemented in concrete classes. > "The fact that many languages disallow instantiation of abstract types > (and force subtypes to implement all needed functionality) further > ensures program correctness." > > http://en.wikipedia.org/wiki/Abstract_base_class > > but I don't see how that follows (except possibly in very special cases). > Given that the set of instances of class B is empty, how does that help > you know that B.method is correct? I agree with you on this, and the simple scheme of defining some methods raising exceptions is obviously sufficiient where duck typing is. ABC, as I understood it, is for resolving another problem : unrelated (by inheritance) classes, which share the same signature, but need to be distinguished in their behavior. -- _____________ Maric Michaud From gagsl-py2 at yahoo.com.ar Sun Sep 7 15:50:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 16:50:09 -0300 Subject: __builtins__ magic behavior References: <d09829f50809071000x5b1cfe89va6ebd07404d7af8f@mail.gmail.com> Message-ID: <op.ug4mpvsrx6zn5v@a98gizw.cpe.telecentro.net.ar> En Sun, 07 Sep 2008 14:00:48 -0300, Patrick Maupin <pmaupin at gmail.com> escribi?: > __builtins__ in 2.5.2 doesn't seem to behave like I remember it did > the last time I did some custom stuff with it, a very long time ago. > > This isn't surprising, because of ongoing optimization, but it's hard > to google for '__builtins__' so I didn't really find any documentation > on the current CPython behavior, which in some cases seems quite > strange to me. > > The documentation node at http://docs.python.org/ref/naming.html has a > "here be dragons" note on __builtins__, which is nice as far as it > goes, but doesn't provide any help for people wanting to abuse the > current CPython implementation. Additionally, the sentence > immediately above the note, "__builtins__ can be set to a user-created > dictionary to create a weak form of restricted execution" not only > contradicts the note, but in some cases appears not to be true. > > When the code below is run, either standalone or by importing it, the > builtins used are different depending on whether exec is used with > globals() or with a copy of globals(). Any explanations for this > behavior would be much appreciated. Python takes some shortcuts when dealing with builtins. I'll just describe what happens (I won't say whether it is "right" or "wrong"). The exec statement, when given a string source, compiles it and eventually calls PyEval_EvalCodeEx, which creates a new frame using PyFrame_New and finally executes it. A frame object contains a pointer to the previous frame, the code to be executed, a pointer to the current globals *and* a separate pointer to the current builtins. Inside PyFrame_New, there is a shortcut: if the new frame and the previous one share the same globals, then the previous builtins are copied into the new frame. Only if the globals differ the builtins are searched in globals. From frameobject.c: /* If we share the globals, we share the builtins. Save a lookup and a call. */ It is this assumption that fails in your code. If you want to execute some code with modified builtins, do not change __builtins__ in the *calling* code, but in the globals that you pass to the exec call. That appears to be the most logical approach, and the way the developers appear to have expected. -- Gabriel Genellina From gaius at gaius.org.uk Fri Sep 5 09:26:04 2008 From: gaius at gaius.org.uk (gaius hammond) Date: Fri, 05 Sep 2008 14:26:04 +0100 Subject: cx_oracle and commands Message-ID: <1220621164.48c1336c32f31@netmail.pipex.net> Hi all, I am having a very strange problem with cx_Oracle, has anyone seen this kind of behavior before: ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 18:53:24) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> from commands import getstatusoutput >>> (status, output) = getstatusoutput('ls') >>> status 0 >>> from cx_Oracle import connect, SYSDBA >>> db = connect(mode=SYSDBA) >>> (status, output) = getstatusoutput('ls') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/ASpy25/lib/python2.5/commands.py", line 55, in getstatusoutput sts = pipe.close() IOError: [Errno 10] No child processes Basically, once I have made a connection to Oracle I can no longer use getstatusoutput(). This is a real problem as I need to get a list of things to work on from Oracle then spawn commands to process them... Thanks, G -- gaius at gaius.org.uk http://www.gaius.org.uk/ "First things first, but not necessarily in that order" -- The Doctor, "Doctor Who" ------------------------------------------------- Visit Pipex Business: The homepage for UK Small Businesses Go to http://www.pipex.co.uk/business-services From adityashukla1983 at gmail.com Wed Sep 10 15:41:36 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Wed, 10 Sep 2008 14:41:36 -0500 Subject: tempfile module Message-ID: <73045cca0809101241u1d2ddbe8i7b7598bca785509e@mail.gmail.com> Hello folks, I am using Python-2.5.2 on fedora 9 sulphur -2.6.25-14.fc9.i686.I am creating a temporary file , in which data is written by another program and then i am using that temporary file to do my computations.I am new to linux and i am facing two issues homedir = os.path.expanduser('~') temp = tempfile.NamedTemporaryFile( suffix='_suffix',prefix='prefix_',dir= homedir) temp.close() tn = temp.name print tn Issue1 -> when i am logged in as root then everything works fine except that the file is created in the current working directory (/usr/Python-2.5.2) and not in the directory supplied as the dir='directory' parameter.i have tried dir='/tmp' as well.i don't know how to fix this issue and why the file is not getting created in the specified directory. Issue2 -> when i am logged in as user ie any other user than root then i get this error sh: prefix_u92XQJ_suffix: Permission denied also , i cannot find the find in either the current working directory nor in the dir='directory'.so i cant check the permission by using ls -l prefix_u92XQJ_suffix Please help me understand this issue and eventually fix it. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/4a5cf451/attachment.html> From digitig at gmail.com Fri Sep 26 19:40:59 2008 From: digitig at gmail.com (Tim Rowe) Date: Sat, 27 Sep 2008 00:40:59 +0100 Subject: Not fully OO ? In-Reply-To: <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> <48DCC786.2040407@wildenhain.de> <mailman.1551.1222447687.3487.python-list@python.org> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> Message-ID: <aee48b3c0809261640v2d2850c1t5236894a56ba5779@mail.gmail.com> 2008/9/26 Aaron Castironpi Brady <castironpi at gmail.com>: > If you have wxFormBuilder and the win32 library, it's pretty fast. Speed has never been an issue for me with Python. For my masters degree I did a project that involved a lot of number crunching, and in my proposal I wrote that I'd use Python for most of the code and C for any parts that were unacceptably slow. In practice, not only did I never need to replace any parts with C, I never even needed to use numpy; it was quite fast enough as it was. > Python's philosophy is to make common things easy and everything > possible. But what's common for one person may be uncommon for another. And sometimes "possible" isn't enough, or we'd all be using INTERCAL! Another, quite different example to the one I was referring to earlier is the fact that I often work with safety critical systems. I don't think formal proof of program behaviour would be at all straightforward in Python (or C# for that matter, and although Spec# gets closer, it really needs a language like Spark Ada). -- Tim Rowe From mensanator at aol.com Sun Sep 7 20:36:58 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 7 Sep 2008 17:36:58 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> <e01ccc30-54e5-4966-b12c-c893fb2be972@z66g2000hsc.googlegroups.com> Message-ID: <6b2d4059-6c80-4440-ae6f-dd2c67531236@l43g2000hsh.googlegroups.com> On Sep 7, 1:17?pm, Patrick Maupin <pmau... at gmail.com> wrote: > On Sep 7, 12:30?pm, Mensanator <mensana... at aol.com> wrote: > > > On Sep 6, 11:05 pm, Steven D'Aprano <st... at REMOVE-THIS- > > > Sheesh. That's not a problem, because Python is not trying to be a > > > dialect of SQL. > > > And yet, they added a Sqlite3 module. > > Does that mean that, because there is an 'os' module, Python is trying > to compete with Linux and Windows? I wasn't thinking "compete", rather "complement". Python obviously wants to be a player in the SQL market, so you would think it would be in Python's interest to know how SQL behaves, just as it's in Python's interest for the os module to know how BOTH Linnux and Windows work. > > This is starting to feel like a troll, It wasn't intended to be. > but JUST IN CASE you are really > serious about wanting to get work done with Python, rather than > complaining about how it is not perfect, Things never change if no one ever speaks up. > I offer the following snippet > which will show you how you can test the results of a sum() to see if > there were any items in the list: Thanks. I'll drop this from this point on. > > >>> class MyZero(int): > > ... ? ? pass > ... > > > > >>> zero = MyZero() > >>> x=sum([], zero) > >>> isinstance(x,MyZero) > True > >>> x = sum([1,2,3], zero) > >>> isinstance(x,MyZero) > False- Hide quoted text - > > - Show quoted text - From dullrich at sprynet.com Thu Sep 4 12:13:12 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 04 Sep 2008 11:13:12 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: <dullrich-D271BF.11131204092008@text.giganews.com> In article <719910b1-3776-4bf2-a0b6-236f3167e9e3 at 25g2000prz.googlegroups.com>, Mensanator <mensanator at aol.com> wrote: > On Sep 3, 2:18?pm, Laszlo Nagy <gand... at shopzeus.com> wrote: > > bearophileH... at lycos.com wrote: > > > Empty Python lists [] don't know the type of the items it will > > > contain, so this sounds strange: > > > > >>>> sum([]) > > > > > 0 > > > > > Because that [] may be an empty sequence of someobject: > > > > You are right in that sum could be used to sum arbitrary objects. > > However, in 99.99% of the cases, you will be summing numerical values. > > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > > is very logical to return zero for empty sequences. > > No it isn't. Nothing is not 0, check with MS-Access, for instance: > > Null + 1 returns Null. Any arithmetic expression involving a > Null evaluates to Null. Adding something to an unknown returns > an unknown, as it should. > > It is a logical fallacy to equate unknown with 0. Which has nothing to do with the "right" value for an empty sum. If they hear about what you said here in sci.math they're gonna kick you out - what do you imagine the universally accepted value of \sum_{j=1}^0 is? > For example, the water table elevation in ft above Mean Sea Level > is WTE = TopOfCasing - DepthToWater. > > TopOfCasing is usually known and constant (until resurveyed). > But DepthToWater may or may not exist for a given event (well > may be covered with fire ants, for example). > > Now, if you equate Null with 0, then the WTE calculation says > the water table elevation is flush with the top of the well, > falsely implying that the site is underwater. > > And, since this particular site is on the Mississippi River, > it sometimes IS underwater, but this is NEVER determined by > water table elevations, which, due to the CORRECT treatment > of Nulls by Access, never returns FALSE calculations. > > >>> sum([]) > 0 > > is a bug, just as it's a bug in Excel to evaluate blank cells > as 0. It should return None or throw an exception like sum([None,1]) > does. > > > > > Same way, if we would have a prod() function, it should return one for > > empty sequences because X*1 = X. The neutral element for this operation > > is one. > > > > Of course this is not good for summing other types of objects. But how > > clumsy would it be to use > > > > sum( L +[0] ) > > > > or > > > > if L: > > value = sum(L) > > else: > > value = 0 > > > > instead of sum(L). > > > > Once again, this is what sum() is used for in most cases, so this > > behavior is the "expected" one. > > > > Another argument to convince you: the sum() function in SQL for empty > > row sets returns zero in most relational databases. > > > > But of course it could have been implemented in a different way... I > > believe that there have been excessive discussions about this decision, > > and the current implementation is very good, if not the best. > > > > Best, > > > > Laszlo -- David C. Ullrich From mensanator at aol.com Sun Sep 28 18:06:58 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 28 Sep 2008 15:06:58 -0700 (PDT) Subject: generate random digits with length of 5 References: <e1923ff8-8150-41b6-9444-19c14b4d2f6f@8g2000hse.googlegroups.com> <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> <mailman.1641.1222632690.3487.python-list@python.org> <a380bc46-cf5f-4ae9-b1f2-d8789ba4f838@d45g2000hsc.googlegroups.com> <07d14730-a585-4976-adda-540d32a2066d@y38g2000hsy.googlegroups.com> Message-ID: <1d078691-662d-40a5-8519-62bee01dad4e@u65g2000hsc.googlegroups.com> On Sep 28, 3:54?pm, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 28, 3:44?pm, Mensanator <mensana... at aol.com> wrote: > > > > > > > On Sep 28, 3:11 pm, "Gary M. Josack" <g... at byoteki.com> wrote: > > > > Chris Rebert wrote: > > > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <soti... at gmail.com> wrote: > > > > >> Wondering if there is a better way to generate string of numbers with > > > >> a length of 5 which also can have a 0 in the front of the number. > > > > >> <pre> > > > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 > > > >> elements > > > >> code = 'this is a string' + str(random_number[0]) + > > > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3]) > > > >> + str(random_number[4]) > > > > > code = ''.join(str(digit) for digit in random_number) > > > > > Regards, > > > > Chris > > > > >> </pre> > > > > >> -- > > > >>http://mail.python.org/mailman/listinfo/python-list > > > > will random.randint(10000,99999) work for you? > > > It doesn't meet the OP's requirement that the number > > can start with 0. Also, the method the OP asks about > > returns a list of unique numbers, so no number can > > be duplicated. He can get 02468 but not 13345. > > > Now, IF it's ok to have an arbitrary number of leading > > 0s, he can do this: > > > >>> str(random.randint(0,99999)).zfill(5) > > '00089' > > >>> str(random.randint(0,99999)).zfill(5) > > '63782' > > >>> str(random.randint(0,99999)).zfill(5) > > '63613' > > >>> str(random.randint(0,99999)).zfill(5) > > > '22315' > > Is a while loop until there are 5 distinct digits best otherwise? Of course not. > > while 1: > ? a= '%05i'% random.randint( 0, 99999 ) > ? if len( set( a ) )== 5: break How is this better than the OP's original code? From sturlamolden at yahoo.no Tue Sep 23 16:34:10 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 13:34:10 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <eogid4d6s2a5l55pu20220sr2bdt5s6hob@4ax.com> Message-ID: <c3f6f232-4165-495b-b998-cc813eae57ea@f63g2000hsf.googlegroups.com> On Sep 23, 10:05?pm, Robert Singer <rsinger at ____.com> wrote: > May I ask what are your main objections to it ? 1. gfortran is not Absoft. 2. If I program the same in C99 and Fortran 95, and compile with gcc and gfortran, the C99 code runs a lot faster (I've only tested with wavelet transforms). 3. gfortran is not Absoft. From sjmachin at lexicon.net Tue Sep 2 21:54:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 18:54:29 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> <8b3857ec-e629-44a3-98f2-8fe509df7b75@f36g2000hsa.googlegroups.com> Message-ID: <870e4b08-610f-4037-89be-407677c790aa@b30g2000prf.googlegroups.com> On Sep 3, 11:14 am, process <circularf... at gmail.com> wrote: > is this faster btw? Time it and see. > I guess big doesn't help, it's only retrieved once > anyway? Correct. > But is rows retrieved in every loop? Of course. Read your own code! The point is that retrieving the list referenced by "rows" is much faster than creating it needlessly each time. > the python interpreter > aint too smart? It's smarter than some. The trade-off for having a very dynamic language is that some compile-time optimisations are more difficult. If you are interested in work (being)? done in this area, look at psyco and PyPy. From nagle at animats.com Sun Sep 7 22:52:07 2008 From: nagle at animats.com (John Nagle) Date: Sun, 07 Sep 2008 19:52:07 -0700 Subject: Use BeautifulSoup to delete certain tag while keeping its content In-Reply-To: <mailman.637.1220738822.3487.python-list@python.org> References: <mailman.637.1220738822.3487.python-list@python.org> Message-ID: <48c48e4b$0$17163$742ec2ed@news.sonic.net> Jackie Wang wrote: > Dear all, > > I have the following html code: > > <td valign="top" headers="col1"> > <font size="2"> > Center Bank > <br /> > Los Angeles, CA > </font> > </td> > > <td valign="top" headers="col1"> > <font size="2"> > Salisbury > Bank and Trust Company > <font face="arial, helvetica" size="2" color="#0000000"> > <br /> > Lakeville, CT > </font> > </font> > </td> > > How should I delete the 'font' tags while keeping the content inside? See the BeautifulSoup documentation. Find the font tags with findAll, make a list, then go in and use "extract" and "replaceWith" appropriately. John Nagle From castironpi at gmail.com Tue Sep 23 22:24:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 19:24:00 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <ee44675b-04ad-48b3-8eed-629ebb10d616@z66g2000hsc.googlegroups.com> <mailman.1440.1222221042.3487.python-list@python.org> Message-ID: <ff83a928-f398-41f7-857c-4d8226a89335@j22g2000hsf.googlegroups.com> On Sep 23, 8:50?pm, Neal Becker <ndbeck... at gmail.com> wrote: > Aaron "Castironpi" Brady wrote: > > On Sep 23, 6:52 pm, Neal Becker <ndbeck... at gmail.com> wrote: > >> In hindsight, I am disappointed with the choice of conditional syntax. ?I > >> know it's too late to change. ?The problem is > > >> y = some thing or other if x else something_else > > >> When scanning this my eye tends to see the first phrase and only later > >> notice that it's conditioned on x (or maybe not notice at all!). > >> Particularly if 'some thing or other' is long or complicated. > > > You're talking strictly about readability, which among other things is > > in the eye of the beholder, of course. ?Temporary variables can clean > > up some code, even if choosing names can be a hassle and it's more > > things to keep track of. ?Long lines and extra variables form a trade- > > off. ?You are writing a line with a conditional expression the value > > of which depends on something. ?What does it depend on, what is its > > value if that's true, and what is it if it's false? ?'...if...else...' > > only takes 6 characters... maybe you want more! > > > If you're looking for a strictly syntactic construct, you can always > > "fire blanks", or tracers, if the analogy's more accurate. > > > z= conditionally( x ) if b else y > > > This could serve as a gentle reminder, even where 'conditionally' > > returns its argument, i.e. is the identity function. ?You can always > > roll your own ternary with extra parameters too: > > > z= condition( b, x, y ) > > > Just don't confuse it with threading.Condition. > > > Otherwise, you're stuck with old syntax markers, and unless you > > wanted: > > > z= if b then x else y > > > You're out of options. ?You have to express it somehow. ?Did you want > > the condition first? ?Was there an alternative proposal you > > preferred? ?IINM if I'm not mistaken, > > > z= b and x or y > > > works just the same so long as x evaluates to True, as it will be > > tested. > > > Feel free to write your own from scratch, and we'll see how close > > Python can come to resembling it. > > > I suppose you can compare it to someone who stops listening before the > > word 'if', and completely misunderstands your statement. ?"Feed the > > dog if he's standing near the food dish" != "Feed the dog", which can > > of course lead to errors of both omission and commission (doing too > > little -or- too much). ?There's no way to fix that in a guaranteed > > way, except to say, "listen to the whole statement". > > > And strictly sarcastically, what did you want to do with reading the > > program? ?Why were you reading it? ?<snicker, ducks> > > I find I'm often tripped up by: > > x = Y (lots of ?constructor arguments....) if something ... > > on first glance, I don't notice the if. > > Why am I reading this? ?Umm, because I wrote it. Put it somewhere you'll notice! From castironpi at gmail.com Tue Sep 16 21:39:01 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 18:39:01 -0700 (PDT) Subject: ka-ping yee tokenizer.py References: <mailman.1139.1221594553.3487.python-list@python.org> Message-ID: <63a54182-9d0e-4a42-a8b9-da29029d0125@25g2000hsx.googlegroups.com> On Sep 16, 2:48?pm, "Karl Kobata" <karl.kob... at syncira.com> wrote: > Hi Fredrik, > > This is exactly what I need. ?Thank you. > I would like to do one additional function. ?I am not using the tokenizer to > parse python code. ?It happens to work very well for my application. > However, I would like either or both of the following variance: > 1) I would like to add 2 other characters as comment designation > 2) write a module that can readline, modify the line as required, and > finally, this module can be used as the argument for the tokenizer. > > Def modifyLine( fileHandle ): > ? # readline and modify this string if required > ... > > For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ): > ? ? ? ? Print token > > Anxiously looking forward to your thoughts. > karl > > -----Original Message----- > From: python-list-bounces+kkobata=syncira.... at python.org > > [mailto:python-list-bounces+kkobata=syncira.... at python.org] On Behalf Of > Fredrik Lundh > Sent: Monday, September 15, 2008 2:04 PM > To: python-l... at python.org > Subject: Re: ka-ping yee tokenizer.py > > Karl Kobata wrote: > > > I have enjoyed using ka-ping yee's tokenizer.py. ?I would like to > > replace the readline parameter input with my own and pass a list of > > strings to the tokenizer. ?I understand it must be a callable object and > > iteratable but it is obvious with errors I am getting, that this is not > > the only functions required. > > not sure I can decipher your detailed requirements, but to use Python's > standard "tokenize" module (written by ping) on a list, you can simple > do as follows: > > ? ? ?import tokenize > > ? ? ?program = [ ... program given as list ... ] > > ? ? ?for token in tokenize.generate_tokens(iter(program).next): > ? ? ? ? ?print token > > another approach is to turn the list back into a string, and wrap that > in a StringIO object: > > ? ? ?import tokenize > ? ? ?import StringIO > > ? ? ?program = [ ... program given as list ... ] > > ? ? ?program_buffer = StringIO.StringIO("".join(program)) > > ? ? ?for token in tokenize.generate_tokens(program_buffer.readline): > ? ? ? ? ?print token > > </F> > > --http://mail.python.org/mailman/listinfo/python-list > > This is an interesting construction: >>> a= [ 'a', 'b', 'c' ] >>> def moditer( mod, nextfun ): ... while 1: ... yield mod( nextfun( ) ) ... >>> list( moditer( ord, iter( a ).next ) ) [97, 98, 99] Here's my point: >>> a= [ 'print a', 'print b', 'print c' ] >>> tokenize.generate_tokens( iter( a ).next ) <generator object at 0x009FF440> >>> tokenize.generate_tokens( moditer( lambda s: s+ '#', iter( a ).next ).next ) It adds a '#' to the end of every line, then tokenizes. From bearophileHUGS at lycos.com Thu Sep 11 12:31:31 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Sep 2008 09:31:31 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <mailman.876.1221142791.3487.python-list@python.org> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> Message-ID: <8716c7a6-e3f1-4e68-b533-705d31599a97@p25g2000hsf.googlegroups.com> carriere.jonat...: > I want to build a desktop application. I am searching for some kind of > environment that would provide all the elements ready (Windows...). > Then I would have to code the business logic only. I don't think there's such thing in Python, "all elements ready" sounds strange :-) Maybe you may appreciate Dabo: http://dabodev.com/ Or maybe Pythoncard? Bye, bearophile From hniksic at xemacs.org Tue Sep 16 05:03:59 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 11:03:59 +0200 Subject: append on lists References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> Message-ID: <87d4j4798g.fsf@mulj.homelinux.net> Duncan Booth <duncan.booth at invalid.invalid> writes: > The only relatively common use I can think of where you might want to call > a method directly on a literal is to produce a list of strings while being > lazy about the typing: By far the most common is probably 'sep'.join(iterable). From adityashukla1983 at gmail.com Wed Sep 10 13:37:25 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Wed, 10 Sep 2008 12:37:25 -0500 Subject: File operations Message-ID: <73045cca0809101037i6cc1e945tcf8d2fb9761b52b4@mail.gmail.com> Hello folks, I am using Python-2.5.2 on fedora 9 sulphur -2.6.25-14.fc9.i686.I am creating a temporary file , in which data is written by another program and then i am using that temporary file to do my computations.I am new to linux and i am facing two issues homedir = os.path.expanduser('~') temp = tempfile.NamedTemporaryFile( suffix='_suffix',prefix='prefix_',dir= homedir) temp.close() tn = temp.name print tn Issue1 -> when i am logged in as root then everything works fine except that the file is created in the current working directory (/usr/Python-2.5.2) and not in the directory supplied as the dir='directory' parameter.i have tried dir='/tmp' as well.i don't know how to fix this issue and why the file is not getting created in the specified directory. Issue2 -> when i am logged in as user ie any other user than root then i get this error sh: prefix_u92XQJ_suffix: Permission denied also , i cannot find the find in either the current working directory nor in the dir='directory'.so i cant check the permission by using ls -l prefix_u92XQJ_suffix Please help me understand this issue and eventually fix it. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/c03f9802/attachment.html> From invalid at nowhere.invalid.org Tue Sep 16 07:22:46 2008 From: invalid at nowhere.invalid.org (Alex Marandon) Date: Tue, 16 Sep 2008 12:22:46 +0100 Subject: append on lists In-Reply-To: <gao3d0$7q1$1@online.de> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> <gao3d0$7q1$1@online.de> Message-ID: <1221564169.16690.0@proxy00.news.clara.net> Armin wrote: > Duncan Booth wrote: > > The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > (with c = [8,9]) is identical, No it's not, + doesn't alter its operands. >>> a = 1 >>> b = 2 >>> a + b 3 >>> a 1 Were you expecting a == 3? From mauriceling at gmail.com Thu Sep 4 08:58:21 2008 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Thu, 4 Sep 2008 05:58:21 -0700 (PDT) Subject: [ANN] The Python Papers, Volume 3 Issue 2 Message-ID: <3eb3b85a-67cc-4260-a86f-acee9c8f6eb8@q5g2000prf.googlegroups.com> Hi everyone After a long wait of nearly 5 month, we are back in business to bring the latest edition of The Python Papers - Volume 3 Issue 2 (http:// ojs.pythonpapers.org/index.php/tpp/issue/current). >From this issue onwards, we will be having only 3 issues per year instead of 4. This is in compliance with our ISSN registration. What's new ========= 1. We have expanded our editorial team with 2 new Associate Editors, Sarah Mount (from UK) and Guy Kloss from (New Zealand). 2. TPP is now managed using Open Journal System and it can be assessed at http://ojs.pythonpapers.org/tpp 3. Backporting of previous issues of TPP from Volume 1 Issue 1 is complete 4. We had "soft-launched" TWO new periodicals - The Python Papers Monographs (for monograph-length submissions which may include dissertations, conference proceedings, case studies and advanced-level lectures) and The Python Papers Source Codes (modeled after ACM Collected Algorithms and provides a collection of software and source codes, usually associated with papers published in The Python Papers and The Python Papers Monograph). They shall be TPPM and TPPSC respectively. 5. Collectively, TPP, TPPM and TPPSC will be umbrella-ed as The Python Papers Anthology (TPPA) and managed under the same editorial committee. 6. Probably the most important development to TPP is that TPP is currently indexed by a number of services, including Google Scholar and OAIster, as a result of using Open Journal System. So, please enjoy our latest edition and we look towards all of your continued support and contributions. Thank you. Cheers Maurice Ling Co-Editor-in-Chief, The Python Papers Anthology From Ron.Barak at lsi.com Wed Sep 24 03:54:24 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Wed, 24 Sep 2008 08:54:24 +0100 Subject: How to copy a GUI2exe project - to serve as basis for new project ? In-Reply-To: <mailman.12523.1222237400.3486.python-list@python.org> References: <mailman.12523.1222237400.3486.python-list@python.org> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6022A71DF@enbmail01.lsi.com> Hi, In GUI2exe, I'd like to create a project that is different from an existing project only in a few details (e.g., the location of the 'dist' directory). Is there a way to copy a current project - so it would serve as a basis for a new project ? Bye, Ron. From sebastianthegreatful at gmail.com Mon Sep 8 09:15:17 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Mon, 8 Sep 2008 06:15:17 -0700 (PDT) Subject: flock trouble Message-ID: <1460c93c-af24-40a3-8be4-31d582d48cb1@y21g2000hsf.googlegroups.com> I'm trying to implement a file server using the code below. However the locking doesn't work. I can delete while put'ing a file. Anyone got an idea about why? best regards, seb #! /usr/bin/env python import Pyro.core, Pyro.naming from Pyro.errors import PyroError, NamingError import sys import urllib import os import fcntl class fileServer(Pyro.core.ObjBase): basePath = "/home/snot/diku/dist/opg2/files_to_serve" def __init__(self): Pyro.core.ObjBase.__init__(self) self.basePath = self.basePath.strip("..") if not os.path.isdir(self.basePath) or os.path.islink(self.basePath): raise "invalid path" def get(self, uri): f = open(self.basePath + uri, 'r+') fcntl.flock(f, fcntl.LOCK_SH) data = f.read() fcntl.flock(f, fcntl.LOCK_UN) f.close() return data def put(self, uri, payload): f = open(self.basePath + urllib.unquote_plus(uri), 'w') fcntl.flock(f, fcntl.LOCK_EX) f.truncate() f.write(payload) fcntl.flock(f, fcntl.LOCK_UN) f.close() def delete(self, uri): f = open(self.basePath + urllib.unquote_plus(uri), 'w') fcntl.flock(f, fcntl.LOCK_EX) os.unlink(self.basePath + uri) fcntl.flock(f, fcntl.LOCK_UN) f.close() try: Pyro.core.initServer() daemon = Pyro.core.Daemon() locator = Pyro.naming.NameServerLocator() print 'Searching for Name Server...' try: ns = locator.getNS() except Pyro.errors.PyroError, message: print message sys.exit(1) daemon.useNameServer(ns) try: ns.unregister("fileServer") except NamingError: pass uri = daemon.connect(fileServer(), "fileServer") print "The daemon runs on port:", daemon.port print "The object's uri is:", uri daemon.requestLoop() except KeyboardInterrupt: ns.unregister("fileServer") print "ctrl + c pressed" From mathieu.prevot at gmail.com Thu Sep 4 09:01:49 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 15:01:49 +0200 Subject: use str as variable name In-Reply-To: <g9o7a9$t11$1@ger.gmane.org> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <mailman.464.1220515161.3487.python-list@python.org> <48bf9d12$0$7552$426a74cc@news.free.fr> <g9o7a9$t11$1@ger.gmane.org> Message-ID: <3e473cc60809040601t7ef63a1cr1265330043fa1247@mail.gmail.com> 2008/9/4 Fredrik Lundh <fredrik at pythonware.com>: > Bruno Desthuilliers wrote: > >> You wouldn't write something like 2.__add__(3), would you ? > > Don't give the "it's only OO if I write obj.method(args)" crowd more bad > ideas, please ;-) > > (...as Bruno implies, setattr(), len() et al can be and should be viewed as > generic functions. A specific Python implementation may use custom code to > implement behaviour for a given object; behaviour that's more efficient than > a full Python-level method call. For example, in CPython, len(L) is about > twice as fast as L.__len__() for built-in sequences.) Got it. Thanks :) Mathieu From tjreedy at udel.edu Mon Sep 1 02:27:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 02:27:54 -0400 Subject: Python 3.0b2 cannot map '\u12b' In-Reply-To: <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> References: <d0652dd2-24f6-4045-89a8-ba6deaf25b37@c65g2000hsa.googlegroups.com> <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> Message-ID: <g9g219$1ak$1@ger.gmane.org> Tim Roberts wrote: > josh logan <dear.jay.logan at gmail.com> wrote: >> I am using Python 3.0b2. >> I have an XML file that has the unicode character '\u012b' in it, >> which, when parsed, causes a UnicodeEncodeError: >> >> 'charmap' codec can't encode character '\u012b' in position 26: >> character maps to <undefined> >> >> This happens even when I assign this character to a reference in the >> interpreter: >> >> Python 3.0b2 (r30b2:65106, Jul 18 2008, 18:44:17) [MSC v.1500 32 bit >> (Intel)] on >> win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> s = '\u012b' >>>>> s >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> File "C:\Python30\lib\io.py", line 1428, in write >> b = encoder.encode(s) >> File "C:\Python30\lib\encodings\cp437.py", line 19, in encode >> return codecs.charmap_encode(input,self.errors,encoding_map)[0] >> UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in >> position >> 1: character maps to <undefined> >> >> Is this a known issue, or am I doing something wrong? > > Both. U+012B is the Latin lower-case i with macron (i with a bar instead > of a dot). That character does not exist in the 8-bit character set CP437, > which you are trying to use. > > If you choose an 8-bit character set that includes i-with-macron, then it > will work. UTF-8 would be a good choice. It's in ISO-8859-10. I doubt the OP 'chose' cp437. Why does Python using cp437 even when the default encoding is utf-8? On WinXP >>> sys.getdefaultencoding() 'utf-8' >>> s='\u012b' >>> s Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Program Files\Python30\lib\io.py", line 1428, in write b = encoder.encode(s) File "C:\Program Files\Python30\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in position 1: character maps to <undefined> To put it another way, how can one 'choose' utf-8 for display to screen? Using IDLE, display works fine. IDLE 3.0b2 >>> s='\u012b' >>> s '?' # i macron >>> import sys >>> sys.getdefaultencoding() 'utf-8' I ran across this is a different context and mentioned it on the bug tracker, but the Windows interpreter seems broken here. I will send this in UTF-8 so the i-macron will hopefully show up. tjr From invalid at invalid Tue Sep 23 17:18:11 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Sep 2008 16:18:11 -0500 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <4d6dnWXRMfiOwETVnZ2dnUVZ_jqdnZ2d@posted.visi> On 2008-09-23, Drake <cjdrake at gmail.com> wrote: > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), No. A library module should never call sys.exit(). > or should the exception propagate to the calling program which > handles the issue? Yes. Let the application handle the error if it wants to. If it's not handled, it'll end up causing the program to exit. -- Grant Edwards grante Yow! It's a hole all the at way to downtown Burbank! visi.com From gh at ghaering.de Thu Sep 4 07:08:59 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Sep 2008 13:08:59 +0200 Subject: cPickle In-Reply-To: <01f901c90e70$8e118a50$2fc513ac@pwit.com> References: <01f901c90e70$8e118a50$2fc513ac@pwit.com> Message-ID: <g9ofjv$44p$1@ger.gmane.org> gopal mishra wrote: > I have 3 objects and want to save in one pickle file. > > I used cPickle to dump 3 objects in a pkl file > > i.e cPickle.dump(object1, fileobject, -1) > > cPickle.dump(object2, fileobject, -1) > > cPickle.dump(object3, fileobject, -1) > > > > I have changed the 3^rd object and want to save the updated 3^rd object > in the pickle file. > > I have to dump all the 3 objects again. > > Is there any way to dump only the 3^rd object in to the pkl file. No, there isn't. You could, of course, save each object in its own pickle file. Or use an object database like ZODB instead. -- Gerhard From workitharder at gmail.com Wed Sep 3 17:46:00 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 3 Sep 2008 14:46:00 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> Message-ID: <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> On Sep 3, 12:19?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > bukzor a ?crit : > > > I want to make a MixIn class that waits to initialize its super- > > classes until an attribute of the object is accessed. Not generally > > useful, but desirable in my case. I've written this, and it works, but > > would like to take any suggestions you guys have. > > You shouldn't mess with __getattribute__ unless you really know what > you're doing and are ok to suffer the constant performance hit you'll > get. Remember that __getattribute__ actually *is* the implementation of > attribute lookup rules, and is called on each and every attribute > lookup. Your below snippet would be much better using __getattr__ (which > is only called as a last resort). > > > I've commented out > > the "delattr" call because it throws an AttributeError (although I > > don't know why). > > __getattribute__ belongs to the class, not to the instance. delattr() > only removes instance attributes. You'd have to remove __getattribute__ > from the LateInitMixIn class object itself, but then it would break the > whole thing. > > > > > class LateInitMixIn(object): > > ? ? def __init__(self): > > ? ? ? ? print "LateInit initialization" > > ? ? ? ? self.inited = False > > ? ? def __getattribute__(self, attr): > > ? ? ? ? print "Doing __getattribute__" > > ? ? ? ? getattr = lambda attr:object.__getattribute__(self, attr) > > ? ? ? ? if not getattr("inited"): > > ? ? ? ? ? ? super(LateInitMixIn, self).__init__() > > ? ? ? ? ? ? setattr(self, "inited", True) > > ? ? ? ? #delattr(self, "__getattribute__") > > ? ? ? ? return getattr(attr) > > Here's another possible implementation (which doesn't solve all > problems, cf below) using __getattr__: > > class LateInitMixin(object): > ? ? ?def __init__(self): > ? ? ? ? ?print "not yet" > ? ? ? ? ?self.__initialized = False > > ? ? ?def __getattr__(self, name): > ? ? ? ? ?if self.__initialized: > ? ? ? ? ? ? ?raise AttributeError( > ? ? ? ? ? ? ? ? ?"object %s has no attribute '%s'" % (type(self), name) > ? ? ? ? ? ? ? ? ?) > ? ? ? ? ?super(LateInitMixin, self).__init__() > ? ? ? ? ?self.__initialized = True > ? ? ? ? ?return getattr(self, name) > > class Base(object): > ? ? ?def __init__(self): > ? ? ? ? ?print "yet" > ? ? ? ? ?self.base = True > > class LateInit(LateInitMixin, Base): > ? ? ?pass > > def main(): > ? ? ?print "shouldn't init" > ? ? ?S = LateInit() > ? ? ?print "should init" > ? ? ?print S.base > > if __name__=="__main__": > ? ? ?main() > > Ok, now, the other problem : what if Base.__init__ expects args ? Thanks for the reply. Just to see it not work, I tried to remove __getattribute__ from LateInitMixIn, but couldn't get it to work. My Base class is a C class (_mysql.connection from MySQLdb) that sometimes segfaults if you try to use it before it's fully initialized, so unfortunately I think I need to use __getattribute__ to do this. I'm doing all this just to make the connection not actually connect until used. From paul at boddie.org.uk Mon Sep 29 10:14:49 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 29 Sep 2008 07:14:49 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <mailman.1661.1222660566.3487.python-list@python.org> Message-ID: <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> On 29 Sep, 05:56, Terry Reedy <tjre... at udel.edu> wrote: > > As I understand it, partly from postings here years ago... > > Lexical: The namespace scope of 'n' in inner is determined by where > inner is located in the code -- where is is compiled. ?This is Python > (and nearly all modern languages). ?Even without closures, the global > scope of a function is the module it is defined in. This is how I understand it, too. The confusing part involves the definition of any inner function and how any "external" names are bound or defined. As we've seen... def f(x): def g(): return x x += 1 # added for illustration return g ...it might look at first glance like the function known as g (within f) should return the initial value of x (as known within f), since that was the value x had when g was defined. The following is an example execution trace based on that mental model: fn = f(1) -> def f(1): -> def g(): # g defined with x as 1 -> return x # would be 1 -> x += 1 # x becomes 2 -> return g fn() -> def g(): -> return x # would still be 1 However, as we know, this isn't the case in real Python since g isn't initialised with the value of x at the time of its definition - it instead maintains access to the namespace providing x. We must therefore revise the example: fn = f(1) -> def f(1): -> def g(): # g refers to x within f(1) -> return x # would be the current value of x within f(1) -> x += 1 # x becomes 2 -> return g fn() -> def g(): # g refers to x within f(1) -> return x # would be the current value of x within f(1), which is 2 This is the dynamic aspect of closures: values aren't used to initialise inner functions; names are looked up from their origin. > Dynamic: The namespace scope of 'n' in inner, how it is looked up, is > determined by where inner is called from. This is what you seemed to be > suggesting -- look up 'n' based on the scope it is *used* in. Indeed. Dynamic scoping is confusing in that one has to set up an appropriate "environment" for the closure to access so that references to names can be meaningfully satisfied; obviously, this creates all sorts of encapsulation problems. The confusing aspect of lexical scoping, however, especially if non-local names can be changed, is that the effects of closures are potentially distant - one doesn't always invoke inner functions in the place where they were defined, as we see above - and such effects may thus happen within "abandoned namespaces" - that is, namespaces which can no longer be revisited and used in their original context. So, in the above, once f has been invoked, the namespace for that invocation effectively lives on, but that namespace is not a general one for f - if we invoke f again, we get another namespace as one should reasonably expect. A somewhat separate issue is illustrated by the modification of x within f. Although for most statements, we would expect the value of x to evolve following from a top-to-bottom traversal of the code within a unit, function definition statements do not behave like, say, "for", "if" or "while" statements. Now although this should be obvious at the module global level, I feel that it can be easy to overlook within a function where one normally expects to find plain old control-flow constructs, expressions, assignments and so on. It is pertinent to note, with respect to the original inquiry, that lambda functions are subject to the same caveats, and I believe that lexical scoping was introduced precisely to make lambda functions less cumbersome to employ, eliminating the need to explicitly initialise them using the "identity" default parameters trick, but obviously introducing the consequences and potential misunderstandings described above. Paul From bhood37 at hotmail.com Thu Sep 4 17:33:50 2008 From: bhood37 at hotmail.com (Uberman) Date: Thu, 04 Sep 2008 15:33:50 -0600 Subject: Happy fun time with SWIG Message-ID: <5vYvk.75246$C65.45163@en-nntp-01.dc1.easynews.com> I have a bit of a odd arrangement here with SWIG, Python, Embedded Python and C++ classes exported into Python. Here's the plot: I have a class defined in a C++ DLL library. I am wrapping this class (we'll call it "Peter") with SWIG so some of its base functionality is available in Python. For the sake of this example, Peter has a method called get_type(), that takes no arguments and returns an integer. This all works, and within my Python environment I can create instances of Peter, copy them, query their values -- everything I need to do with them. I've tested all this from the Python interpreter with expected results. Peter exists functionally within Python's environment. However, I am also embedding Python into an application, an application that needs to execute the Python module that makes heavy use of Peter (A-ha! The plot thickens!). Peter's instance within the Python environment contains singular data, set within the Python environment, that I need to access from within the embedded Python code. I also use C++ instances of Peter within my C++ code. Here's an example of what I'm looking at: # this is the SWIG generated Python import module from Peter import * class BaseClass: def __init__(self): self.peters = [] class SubClass(BaseClass): def __init__(self): BaseClass.__init__(self) my_peter = Peter(0) self.peters.append(my_peter) Then, in my embedded code, after creating an instance of the Python SubClass: ... PyObject* key = PyString_FromString("peters"); PyObject* py_peters = PyObject_GetAttr(py_SubClass_inst,key); Py_XDECREF(key); if(!py_peters || !PyList_Check(py_peters)) // handle this error for(int j = 0;j < PyList_Size(py_peters);j++) { PyObject* py_peter = PyList_GetItem(py_peters,j); PyObject* py_peter_method = PyObject_GetAttrString(py_peter, "get_type"); if(!py_peter_method || !PyCallable_Check(py_peter_method)) continue; PyThreadState* old_thread_state = PyThreadState_Swap(my_interpreter); PyObject* pargs = Py_BuildValue("( )"); PyObject* py_peter_type = PyEval_CallObject(py_peter_method, pargs); ... So, right here in PyEval_CallObject(), we are invoking the SWIG-generated code to execute Peter's get_type() C++ method. However, this call is returning -1 (not a value coded into Peter's get_type() method). I debugged into the SWIG code, and I see that I'm getting a PyExc_TypeError error, with a the message that looks something like: in method 'Peter_get_type', argument 1 of type 'Peter const *' Checking the watch window, the PyObject->obj_type->tp_name of "py_peter" is "Peter" (not "instance", as I've seen it set to before with other Python attributes). This leads me to believe that what I'm dealing with is not actually an instance of Peter, but rather a class template of Peter. This confuses me, because I thought I initialized the peters[] arrays with instances. Anybody have any helpful insights on this? Why is SWIG barfing? Am I perhaps accessing the Peter instance incorrectly? Many thanks in advance. From bellman at lysator.liu.se Thu Sep 4 13:31:20 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 4 Sep 2008 17:31:20 +0000 (UTC) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> <g9o1bf$dsf$1@news.lysator.liu.se> <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> Message-ID: <g9p618$o0h$1@news.lysator.liu.se> Mensanator <mensanator at aol.com> wrote: > Ok, but I don't understand why an empty list is a valid sum > whereas a list containing None is not. You can't conclude the behaviour of the one from the behaviour of the other, because the two situations have nothing at all in common. >> As it happens, the SQL sum() function (at least in MySQL; I don't >> have any other database easily available, nor any SQL standard to >> read) does return NULL for a sum over the empty sequence, so you >> could argue that that would be the correct behaviour for the >> Python sum() function as well, but you can't argue that because a >> sum *involving* a NULL value returns NULL. > I'm not following that. Are you saying a query that returns no > records doesn't have a specific field containg a Null so there > are no Nulls to poison the sum? ...tap...tap...tap. Ok, I can see > that, Exactly. > but you don't get 0 either. That's because the SQL sum() has a special case for "no rows returned". A *different* special case than the one that taint's the sum when encountering a NULL. It does the equivalent of if len(rows_returned) == 0: # Special case for no rows returned return NULL total = 0 for row in rows_returned: value = row[column] if value is NULL: # Special case for encountering a NULL value return NULL total += value return total Two different special cases for the two different situations. If you were to remove the special case for no rows returned, you would get zero when the SELECT statement finds no rows, but the sum would still be tainted when a NULL value is encountered.. The definition of sum in mathematics *does* do away with that special case. The sum of zero terms is zero. And the Python sum() function follows the mathematics definition in this respect, not the SQL definition. You can argue that Python sum() should have special cased the empty sequence. It's not an illogical stance to take. It's just a totally different issue from encountering a non-numeric element in the sequence. In some cases it might actually make sense to treat the empty sequence as an error, but just ignore non-numeric elements (i.e, treat them as if they were zero). And in some cases both should be an error, and in some neither should be an error. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "You are in a twisty little passage of ! bellman @ lysator.liu.se standards, all conflicting." ! Make Love -- Nicht Wahr! From ireborin at delete.this.gmail.com Mon Sep 22 22:19:49 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 23 Sep 2008 04:19:49 +0200 Subject: gplt from scipy missing ? Message-ID: <lckgd4dsk4hqfsibr5ldv3tnc3dl6lfvum@4ax.com> I'm relatively new to python. I'm following a tutorial I found on the net, and it uses scipy's gplt for plotting. I installed scipy from their website (win32 installation), numpy also, but when I do from scipy import gplt it gives this error: Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from scipy import gplt ImportError: cannot import name gplt Please, can you help me solve this ? How do I get gplt to work ? All advice appreciated. Best regards Ivan From gagsl-py2 at yahoo.com.ar Fri Sep 19 22:03:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 23:03:33 -0300 Subject: Out of memory issue with dialog box References: <ea3cb13c-1793-46fb-86cc-2a4a6861b750@k30g2000hse.googlegroups.com> Message-ID: <op.uhrbz7uvx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 18 Sep 2008 13:32:32 -0300, <numan.salati at gmail.com> escribi?: > We have a mutilthreaded process in which one of the threads uses too > much memory causing the process to run out of memory. However when > this happens we see a dialog box pop up with the message "fatal error > in GC : too many heap sections." When you click "ok" only then does > the process die. That message comes from the Boehm garbage collection library; Python does not use it. Check any compiled extension in use. -- Gabriel Genellina From mail at johnlawrence.net Thu Sep 11 06:51:53 2008 From: mail at johnlawrence.net (John Lawrence) Date: Thu, 11 Sep 2008 11:51:53 +0100 Subject: Adding environment variables to bash. In-Reply-To: <gaaotj$305$1@ger.gmane.org> References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> <gaan73$so4$1@ger.gmane.org> <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> <gaaotj$305$1@ger.gmane.org> Message-ID: <18e8b60e0809110351o35202c23ied4a1e8e3270d684@mail.gmail.com> > > doesn't exactly work for Python scripts, though: > True, but you can use it in the following (admittedly messy) way: jl> cat setenv.sh /usr/bin/env python $@ . ./settmp rm settmp jl> cat env.py #!/usr/bin/python command = "export TEST='hello'\n" open('settmp', 'w').write(command) jl> . setenv.sh env.py && env | grep TEST TEST=hello Note this won't set the environment variable until the end of the script, so if it's used in the script as well then it'll also need to be set with, for example, os.environ["TEST"] = "hello" John. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080911/b363be28/attachment.html> From siegfried at heintze.com Sun Sep 14 02:51:39 2008 From: siegfried at heintze.com (Siegfried Heintze) Date: Sat, 13 Sep 2008 23:51:39 -0700 Subject: How does python call OS? Message-ID: <f9idnWTIta_gKVHVnZ2dnUVZ_gCdnZ2d@comcast.com> I just finished reading a chapter in "Python Programming on Win32" and tried out the pythonwin scribble application. I'm not sure if I got it right because I could not open a new document. I tried to download the source code as referenced in the chm file but it is corrupted. I cut and pasted from my softcopy of the book. I see the next sub-chapter on wxWindows for python and the previous sub-chapter on TK. This is looking a lot like other scripting languages (such as perl and groovy and even java). Can python call anything directly or does someone have to write a DLL in C/C++ that calls the function first? Thanks! Siegfried From blabla at dungeon.de Wed Sep 10 11:28:43 2008 From: blabla at dungeon.de (hofer) Date: Wed, 10 Sep 2008 08:28:43 -0700 (PDT) Subject: dict slice in python (translating perl to python) Message-ID: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Hi, Let's take following perl code snippet: %myhash=( one => 1 , two => 2 , three => 3 ); ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest print "$v1\n$v2\n$v2\n"; How do I translate the second line in a similiar compact way to python? Below is what I tried. I'm just interested in something more compact. mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } # first idea, but still a little too much to type [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] # for long lists lazier typing,but more computational intensive # as split will probably be performed at runtime and not compilation time [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] print "%s\n%s\n%s" %(v1,v2,v3) thanks for any ideas From luke.hamilton at rpm-solutions.com.au Mon Sep 8 10:03:44 2008 From: luke.hamilton at rpm-solutions.com.au (Luke Hamilton) Date: Mon, 8 Sep 2008 09:03:44 -0500 Subject: Web shopping carts Message-ID: <C4EB6DE0.11187%luke.hamilton@rpm-solutions.com.au> Hey People, I am wondering if there are any OS shopping cart application written in python? Regards, Luke Hamilton Solutions Architect RPM Solutions Pty. Ltd. Mobile: 0430 223 558 luke.hamilton at rpm-solutions.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/4edc188d/attachment.html> From python at bdurham.com Mon Sep 1 15:03:04 2008 From: python at bdurham.com (python at bdurham.com) Date: Mon, 01 Sep 2008 15:03:04 -0400 Subject: Benchmark differences between 32 and 64 bit Python? In-Reply-To: <48BC13CD.1010704@timgolden.me.uk> References: <6599d785-87b2-4bbc-97bc-799cac3640f5@b1g2000hsg.googlegroups.com> <48BC13CD.1010704@timgolden.me.uk> Message-ID: <1220295784.9450.1271593301@webmail.messagingengine.com> Anyone have any benchmarks on the difference in performance between 32 and 64 bit versions of Python for specific categories of operation, eg. math, file, string, etc. operations? My question is OS neutral so feel free to share your experience with either Windows or Linux OS's. Thank you, Malcolm From mailcindy at gmail.com Tue Sep 30 10:27:41 2008 From: mailcindy at gmail.com (cindy jones) Date: Tue, 30 Sep 2008 19:57:41 +0530 Subject: How to add CC and BCC while sending mails using python Message-ID: <46da4e770809300727j368a27b8qc570a8451a53e470@mail.gmail.com> Hello all, Can someone tel me how to add cc's and bcc's while sending mails using python Thank you all -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/3af4a690/attachment.html> From circularfunc at yahoo.se Sat Sep 6 18:13:45 2008 From: circularfunc at yahoo.se (cnb) Date: Sat, 6 Sep 2008 15:13:45 -0700 (PDT) Subject: Cathing several potential errors? Message-ID: <c74c4be6-0019-4729-a79b-2af2d37a6969@m36g2000hse.googlegroups.com> if i do try: something except TypeError, IndexError: pass only the first error will get caught. I dont want to use Exception and catch all errors, but just 2. how can i do that? From diesch at spamfence.net Thu Sep 11 08:14:12 2008 From: diesch at spamfence.net (Florian Diesch) Date: Thu, 11 Sep 2008 14:14:12 +0200 Subject: formating a filesystem with python References: <mailman.828.1221080255.3487.python-list@python.org> Message-ID: <llenp5-th8.ln1@mid.florian-diesch.de> "Ricardo Tiago" <rtiago at gmail.com> wrote: > is there a package in python that allows to mount/umount and format > (to ext3) a filesystem? I know that this is possible by just calling > the os commands 'mount/umount and mkfs' but this would imply to have > to change sudoers to run the script as non-root. On Linux (I guess that"s the target OS as you mentioned ext3) mounting could be done as non-root using FUSE or HAL (maybe using a frontend like gio or kio) if the system supports that, or with an appropriate fstab entry. Maybe HAL can configured to do mkfs but that has to be done very carefully to avoid security problems. Maybe you could use something like AppArmor, too. Most likely you get better answers by first asking in a Linux group how to do this things without root privileges and then come back to ask how to do it with Python. Florian -- <http://www.florian-diesch.de/> ----------------------------------------------------------------------- ** Hi! I'm a signature virus! Copy me into your signature, please! ** ----------------------------------------------------------------------- From bearophileHUGS at lycos.com Thu Sep 11 08:54:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Sep 2008 05:54:15 -0700 (PDT) Subject: removing text string References: <loom.20080910T144026-626@post.gmane.org><mailman.814.1221069201.3487.python-list@python.org> <xqWdnQ2Hm7s1vlXVnZ2dnUVZ_sLinZ2d@earthlink.com> <mailman.865.1221136393.3487.python-list@python.org> Message-ID: <514c0466-3142-43e7-abc6-f75fb139e25e@c65g2000hsa.googlegroups.com> Ahmed, Shakir: > Actually the number I am getting it is from slicing from a long text > line. I need to slice 10 characters from that line but no string only > numeric numbers. When I am slicing 10 characters those A, c, O is coming > at the end. It's better to avoid Regular expressions when they aren't necessary, but once in a while they are the simpler way to solve a problem, you may create one like this (mostly untested): \d+?-\d+ Using it like: >>> import re >>> patt = re.compile(r"\d+?-\d+") >>> patt.search("xxxxxx080829-7_A xxxx").group() '080829-7' >>> re.search(r"\d+?-\d+", "xxxxxx080829-7_A xxxx").group() '080829-7' Learning Regexps can be useful. Bye, bearophile From ggpolo at gmail.com Thu Sep 4 23:25:23 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 5 Sep 2008 00:25:23 -0300 Subject: Tkinter Radio button on the second window In-Reply-To: <e5da0605-0dc4-41fe-9a9f-fa75b9094e5a@b30g2000prf.googlegroups.com> References: <e5da0605-0dc4-41fe-9a9f-fa75b9094e5a@b30g2000prf.googlegroups.com> Message-ID: <ac2200130809042025qde8f760p1cfb25e8e63ce4b8@mail.gmail.com> On Thu, Sep 4, 2008 at 10:01 PM, Dream <god1124 at gmail.com> wrote: > The code create 2 windows. 2 radiobuttons are put on the second > window. A control variable "v" is binded to the 2 widgets. > But when I run the code, I found the control variable not binded > succsessfully: The second radiobutton was not selected by default; > Click ed each button always print 1. I don't know what is wrong. So I > need help.Thanks. > > from Tkinter import * > > def test(event_instance): > print v.get() > > window1=Tk() > window2=Tk() Now you have created two Tcl interpreters, and Tkinter stores the "default master" as the first one created, so window1 is the default master. > v=IntVar() Here is your variable with no master specified, meaning it will use the default master, "window1". > v.set(1) > radiobutton1=Radiobutton(window2,variable=v,value=0) > radiobutton2=Radiobutton(window2,variable=v,value=1) Now you set the master for your buttons as window2, and use a variable that has as master window1. This is the big problem, besides the use of two Tcl interpreters. Tkinter doesn't really try to make this situation work, so you better not continue with it. > radiobutton1.pack() > radiobutton2.pack() > radiobutton2.bind('<Button-1>',test) > radiobutton1.bind('<Button-1>',test) > window1.mainloop() > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From sdouche at gmail.com Sun Sep 21 05:46:54 2008 From: sdouche at gmail.com (Sebastien Douche) Date: Sun, 21 Sep 2008 11:46:54 +0200 Subject: report a BUG of package setuptools-0.6c8. In-Reply-To: <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> References: <d2d5d61d0809192114p7b2a20b1tca588b5ed73acc26@mail.gmail.com> <mailman.1291.1221898300.3487.python-list@python.org> <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> Message-ID: <5e1183fa0809210246q46f864eic359964a0cb0d46e@mail.gmail.com> 2008/9/20 Carl Banks <pavlovevidence at gmail.com>: > On Sep 20, 1:11 am, Fredrik Lundh <fred... at pythonware.com> wrote: >> ???? wrote: >> > File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", >> > line 98, in entries_finder >> > log.warn("unrecognized .svn/entries format in %s", dirname) >> > NameError: global name 'log' is not defined >> >> > global name 'log' is not defined to the line 98!!! >> >> please report bugs here: >> >> http://bugs.python.org/ > > Does bugs.python.org track bugs for setuptools? (Genuine question; > the PEAK site doesn't list an obvious way to report bugs so I wonder > if they're using bugs.python.org? Hope not....) > > If not, the OP should ask on the setuptools mailing list. http://bugs.python.org/setuptools/ BTW, this blocker bug (Setuptools and SVN 1.5.x) is known for 2 months *sigh*. -- Seb From dmitry at athabascau.ca Fri Sep 26 11:41:32 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Fri, 26 Sep 2008 15:41:32 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> Message-ID: <Mo7Dk.2064$T65.1885@edtnps82> Paul McGuire wrote: >> see, in your code you're assuming that there's only 1 property ( 'b' ) >> inside of A that needs proxying. In reality I have several. <snip/> > > No, really, Diez has posted the canonical Proxy form in Python, using > __getattr__ on the proxy, and then redirecting to the contained > delegate object. This code does *not* assume that only one property > ('b'? where did that come from?) is being redirected - __getattr__ > will intercept all attribute lookups and redirect them to the > delegate. > > If you need to get fancier and support this single-proxy-to-multiple- > delegates form, then yes, you will need some kind of map that says > which method should delegate to which object. Or, if it is just a > matter of precedence (try A, then try B, then...), then use hasattr to > see if the first delegate has the given attribute, and if not, move on > to the next. that is what I didn't like about it - I have to iterate over delegates when I can build direct mapping once and for all and tie it to class definition ;) > Your original question was "is decorator the right thing to use?" For > this application, the answer is "no". yeah. seems that way. in the other fork of this thread you'll find my conclusion which agrees with that :) > It sounds like you are trying > to force this particular to solution to your problem, but you are > probably better off giving __getattr__ intercepting another look. __getattr__ implies constant lookups and checks (for filtering purposes) - I want to do them once, attach generated methods as native methods and be done with it. That is why I do not like __getattr__ in this particular case. Otherwise - you're right. From luigi.paioro at gmail.com Fri Sep 12 03:21:51 2008 From: luigi.paioro at gmail.com (luigi.paioro at gmail.com) Date: Fri, 12 Sep 2008 00:21:51 -0700 (PDT) Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> <6inkkiFrbptbU1@mid.uni-berlin.de> <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> <6iqr3dF3msoU1@mid.uni-berlin.de> <e91c2424-7b31-4eb7-abe3-2b3e8c021264@r15g2000prd.googlegroups.com> Message-ID: <48914423-0410-4ee3-a2ad-c977c4917e84@34g2000hsh.googlegroups.com> On 11 Set, 18:45, Richard Levasseur <richard... at gmail.com> wrote: > Because he wants to insert parameters at the very start, he can > probably get away with modifying the xml directly. ?Just find the > position of the <params> (i think thats the tag) and insert the xml > you need after it. ?Its pretty dirty, but would work. ?The wire format > isn't that complicated. I think this is exactly what I do... isn't it? From mensanator at aol.com Sun Sep 28 16:44:00 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 28 Sep 2008 13:44:00 -0700 (PDT) Subject: generate random digits with length of 5 References: <e1923ff8-8150-41b6-9444-19c14b4d2f6f@8g2000hse.googlegroups.com> <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> <mailman.1641.1222632690.3487.python-list@python.org> Message-ID: <a380bc46-cf5f-4ae9-b1f2-d8789ba4f838@d45g2000hsc.googlegroups.com> On Sep 28, 3:11?pm, "Gary M. Josack" <g... at byoteki.com> wrote: > Chris Rebert wrote: > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <soti... at gmail.com> wrote: > > >> Wondering if there is a better way to generate string of numbers with > >> a length of 5 which also can have a 0 in the front of the number. > > >> <pre> > >> ?random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 > >> elements > >> ?code = 'this is a string' + str(random_number[0]) + > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3]) > >> + str(random_number[4]) > > > code = ''.join(str(digit) for digit in random_number) > > > Regards, > > Chris > > >> </pre> > > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > will random.randint(10000,99999) work for you? It doesn't meet the OP's requirement that the number can start with 0. Also, the method the OP asks about returns a list of unique numbers, so no number can be duplicated. He can get 02468 but not 13345. Now, IF it's ok to have an arbitrary number of leading 0s, he can do this: >>> str(random.randint(0,99999)).zfill(5) '00089' >>> str(random.randint(0,99999)).zfill(5) '63782' >>> str(random.randint(0,99999)).zfill(5) '63613' >>> str(random.randint(0,99999)).zfill(5) '22315' From vel.accel at gmail.com Tue Sep 2 00:56:45 2008 From: vel.accel at gmail.com (dieter h) Date: Tue, 2 Sep 2008 00:56:45 -0400 Subject: Process "Killed" In-Reply-To: <92da89760808300807p1af72cbcoec2b39f153fe073e@mail.gmail.com> References: <48a554c6-eeb3-4605-bdf2-a4b7de17bca3@b1g2000hsg.googlegroups.com> <92da89760808300807p1af72cbcoec2b39f153fe073e@mail.gmail.com> Message-ID: <1e52e0880809012156w581586dey34d6c42858bce514@mail.gmail.com> On Sat, Aug 30, 2008 at 11:07 AM, Eric Wertman <ewertman at gmail.com> wrote: >> I'm doing some simple file manipulation work and the process gets >> "Killed" everytime I run it. No traceback, no segfault... just the >> word "Killed" in the bash shell and the process ends. The first few >> batch runs would only succeed with one or two files being processed >> (out of 60) before the process was "Killed". Now it makes no >> successful progress at all. Just a little processing then "Killed". > > This is the behavior you'll see when your os has run out of some > memory resource. The kernel sends a 9 signal. I'm pretty sure that > if you exceed a soft limit your program will abort with out of memory > error. > > Eric > Eric, thank you very much for your response. From ig at illusorygoals.com Fri Sep 12 21:08:20 2008 From: ig at illusorygoals.com (ig at illusorygoals.com) Date: Fri, 12 Sep 2008 18:08:20 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? Message-ID: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> First off, I'm a python n00b, so feel free to comment on anything if I'm doing it "the wrong way." I'm building a discrete event simulation tool. I wanted to use coroutines. However, I want to know if there's any way to hide a yield statement. I have a class that I'd like to look like this: class Pinger(Actor): def go(self): success = True while success: result = self.ping("128.111.41.38") if result != "success": success = False print "Pinger done" But because I can't hide yield inside ping, and because I can't find a convenient way to get a self reference to the coroutine (which is used by the event queue to pass back results), my code looks like this: class Pinger(Actor): def go(self): # I dislike this next line self.this_pointer = (yield None) success = True while success: # I want to get rid of the yield in the next line result = (yield self.ping("128.111.41.38")) if result != "success": success = False print "Pinger done" I posted a more detailed version of this as a rant here: http://illusorygoals.com/post/49926627/ I'd like to know, is there a way to get the syntax I want? After staying up late last night to get a proof-of-concept working with coroutines, my boss expressed disappointment in the ugliness of the Pinger code (we agreed on the desired syntax above). I spent almost 2 hours today to migrate the system over to threads. That made my boss happy, but I'm still curious if I can do something to salvage the coroutine version. Regards, IG From bearophileHUGS at lycos.com Wed Sep 24 15:11:07 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 24 Sep 2008 12:11:07 -0700 (PDT) Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> Message-ID: <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> sturlamolden: >No, because Python already has list comprehensions and we don't need the XML buzzword.< LINQ is more than buzzwords. Python misses several of those features. So maybe for once the Python crowd may recognize such C# feature as much better than things present in Python. Said that, I presume Python will go on as usual, and LINQ-like capabilities will not be integrated in Python. In the meantime where I live lot of people will keep using C# instead of Python and CLisp, natural selection at work indeed. Bye, bearophile From aaron.hildebrandt at gmail.com Wed Sep 10 13:14:13 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 10:14:13 -0700 (PDT) Subject: Reading binary data Message-ID: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> I've been trying to tackle this all morning, and so far I've been completely unsuccessful. I have a binary file that I have the structure to, and I'd like to read it into Python. It's not a particularly complicated file. For instance: signature char[3] "GDE" version uint32 2 attr_count uint32 { attr_id uint32 attr_val_len uint32 attr_val char[attr_val_len] } ... repeated attr_count times ... However, I can't find a way to bring it into Python. This is my code -- which I know is definitely wrong, but I had to start somewhere: import struct file = open("test.gde", "rb") output = file.read(3) print output version = struct.unpack("I", file.read(4))[0] print version attr_count = struct.unpack("I", file.read(4))[0] while attr_count: print "---" file.seek(4, 1) counter = int(struct.unpack("I", file.read(4))[0]) print file.read(counter) attr_count -= 1 file.close() Of course, this doesn't work at all. It produces: GDE 2 --- ? --- ??? I'm completely at a loss. If anyone could show me the correct way to do this (or at least point me in the right direction), I'd be extremely grateful. From google at mrabarnett.plus.com Thu Sep 11 19:46:26 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Sep 2008 16:46:26 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> <b4470822-e893-4b5f-893e-28c39e71dddb@m73g2000hsh.googlegroups.com> <mailman.883.1221153104.3487.python-list@python.org> Message-ID: <9d3e52f4-e24f-47e9-a2b4-af214919c2ca@z72g2000hsb.googlegroups.com> On Sep 11, 6:11?pm, Fredrik Lundh <fred... at pythonware.com> wrote: [snip] > (the next step towards true Pythonicness would be to store your data in > class instances instead of dictionaries in the first place, but one step > at a time...) > Surely the word is "Pythonicity"? :-) From aioe.org at technicalbloke.com Tue Sep 30 04:15:14 2008 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 30 Sep 2008 04:15:14 -0400 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> Message-ID: <gbsn6i$ut0$1@aioe.org> Lawrence D'Oliveiro wrote: > In message <gbr4ks$1vv$1 at aioe.org>, r0g wrote: > >> You can only distribute modifications to gnuplot itself as >> patches, but you can distribute it freely ... > > This must be some new definition of "freely" of which I'm unaware. As in beer. From celephicus at gmail.com Tue Sep 23 01:23:35 2008 From: celephicus at gmail.com (Tom Harris) Date: Tue, 23 Sep 2008 15:23:35 +1000 Subject: Docstrings for class attributes Message-ID: <aa19747c0809222223y2c9c3e88h8a31b070b6529f68@mail.gmail.com> Greetings, I want to have a class as a container for a bunch of symbolic names for integers, eg: class Constants: FOO = 1 BAR = 2 Except that I would like to attach a docstring text to the constants, so that help(Constants.FOO) will print some arbitrary string. Sort of a very limited implementation of PEP 224. The only solution that I can see is to subclass int.__new__(), since once I have an int all it's attributes are immutable. -- Tom Harris <celephicus(AT)gmail(DOT)com> From mccredie at gmail.com Mon Sep 8 12:24:20 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 8 Sep 2008 09:24:20 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> Message-ID: <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> On Sep 8, 12:32?am, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > mathieu a ?crit : > > > Hi there, > > > ? I am trying to write something very simple to test if a list > > contains another one: > > > a = [1,2,3] > > > b = [3,2,1,4] > > > but 'a in b' returns False. > > Indeed. Lists are not sets, and the fact that all elements of list a > happens to also be part of list b doesn't make the list a itself an > element of list b. > > ?>>> a = [1, 2, 3] > ?>>> b = [3,2,1,4] > ?>>> c = [b, a] > ?>>> a in c > True > ?>>> b in c > True > ?>>> c > [[3, 2, 1, 4], [1, 2, 3]] > ?>>> > > > How do I check that a is indeed contained > > in b ? > > But that's what you did - you *did* checked if a was contained in b, and > this is not the case. What you want is to check if *all elements* of a > are contained in b, which is quite another problem. Now the answer to > your question : use sets. > > ?>>> set(a).issubset(set(b)) > True > ?>>> > > HTH Just to clarify, doing it using sets is not going to preserve order OR number of elements that are the same. That is: >>> a = [1,1,2,3,4] >>> b = [4,5,3,7,2,6,1] >>> set(a).issubset(set(b)) True This will return True if b contains at least on of each element found in a. If the OP wanted to check that list `a` appeared in order somewhere in list `b` then sets won't work. Matt From mail at johnohagan.com Tue Sep 30 08:53:19 2008 From: mail at johnohagan.com (John O'Hagan) Date: Tue, 30 Sep 2008 12:53:19 +0000 Subject: How best to pass arbitrary parameters from one function to another Message-ID: <200809301253.19296.mail@johnohagan.com> On Tue Sep 30 11:32:41 CEST 2008, Steven D'Aprano >On Tue, 30 Sep 2008 08:58:15 +0000, John O'Hagan wrote: > >> Hi Pythonistas, >> >> I'm looking for the best way to pass an arbitrary number and type of >> variables created by one function to another. They can't be global >> because they may have different values each time they are used in the >> second function. >> >> So far I'm trying to do something like this: >> >> >> def process_args( [list, of, command-line, arguments] ): > > >If you are trying to process commandline args, I suggest you don't re- >invent the wheel. Have a look at the two standard modules, optparse and >getopt. Of the two, getopt is probably simpler to get started with, but >optparse is more powerful. > Thanks, both to you and Bruno for pointing this out, I'll certainly be using it in future. >To answer your more general question, see below. > > >> do stuff >> return {dictionary : of, local : variables } >> >> def main_function( **kwargs ): >> >> do stuff >> return result >> >> kw1 = process_args( [some, list] ) >> kw2 = process_args( [a, different, list] ) >> >> for i in main_function( **kw1 ): >> >> kw2[ var1 ] = i >> kw2[ var2 ] = len( i ) >> >> for j in main_function(**kw2): >> >> print j >> >> This only seems to work if I specify a default value for every possible >> parameter of main_function and also for any others which may be passed >> to it, which is a bit tedious because there are very many of them but >> only a few are used in any given execution of the program. >> >Er, yes. Presumably main_function actually does something. So it expects >some arguments, and if the arguments aren't given, then it will fail. To >prevent it failing when arguments aren't given, they must have default >values. So define them, once, and be done with it: [...snip code example...] >Default values are a feature, not a problem to be solved. I take your point, but in this case all necessary parameters are present in the keyword dictionary, so I guess I was surprised that default values still need to specified. Also, the function body tests for the presence of each parameter and only acts on those that are there, so it does not fail because of a missing argument. However, I'm sure there's a good reason that it works this way. >As for your nested for-loops (see above), I'm guessing that you're trying >to copy items from one dictionary kw1 to another kw2, before processing >kw2. You should check out the update method on dictionaries. [...] That's also of great use, thank you. What I'm actually trying to do, though, is add some of the output of one call of main_function to the arguments of another call of the same function (with different arguments). It's a long story, but I have a number-crunching function which produces lists of numbers representing musical notes, either rhythmic or melodic, to be printed out as a score using Lilypond and/or played by samples or synthesizers using sox. The melodic and rhythmic parts work by themselves, but I'm trying to get the function to feed itself rhythms for its melodies, and vice-versa. I guess that's already too much information.... Thanks for your help. John From grante at visi.com Mon Sep 1 11:12:07 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 01 Sep 2008 10:12:07 -0500 Subject: How Compute # of Days between Two Dates? References: <JAIuk.19687$cW3.19527@nlpi064.nbdc.sbc.com> <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> <VpTuk.38934$ZE5.3067@nlpi061.nbdc.sbc.com> Message-ID: <l8OdnfiOPe7amyHVnZ2dnUVZ_qvinZ2d@posted.visi> On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: > Grant Edwards wrote: >> On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: >> >>> That's the question in Subject. For example, the difference between >>> 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and >>> 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in >>> years between, say, 1990 and 2050. In other words not some really strange >>> period of time well outside our current era of history. >> >> Does the standard library's datetime module not do what you want? >> >> http://docs.python.org/lib/module-datetime.html >> > Yes, it would seem so. This works fine. It would probably be worth your while to read through one of introductory Python books or just browse through the Python tutorial: http://docs.python.org/tut/ > I was pondering this in pyfdate, but perhaps missed it or it > was not obvious to me in the tutorial for some reason. Sorry, can't help you there -- I've never heard of pyfdate. The timedate module that comes with Python has always done what I needed to do with dates/times. -- Grant From sri_annauni at yahoo.co.in Thu Sep 11 05:55:17 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 11 Sep 2008 15:25:17 +0530 (IST) Subject: Extracing data from webpage Message-ID: <315956.68571.qm@web7903.mail.in.yahoo.com> Hi, I am trying to download data from a webpage. I use mechanize python module. Could someone tell me how to set/pass an agent?like Mozilla or IE that we do in perl's WWW::Mechanize?? Thanks, Srini Be the first one to try the new Messenger 9 Beta! Go to http://in.messenger.yahoo.com/win/ From bcurtu at gmail.com Fri Sep 26 05:32:50 2008 From: bcurtu at gmail.com (bcurtu) Date: Fri, 26 Sep 2008 02:32:50 -0700 (PDT) Subject: how to replace and string in a "SELECT ... IN ()" Message-ID: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> Hi, I have a BIIIIIG problem with the next query: cursor.execute(""" SELECT titem.object_id, titem.tag_id FROM tagging_taggeditem titem WHERE titem.object_id IN (%s) """,( eid_list)) eid_list is suppossed to be a list of ids = [1,5,9] How can I make it work? Thanks From jaycx2.3.calrobert at spamgourmet.com.remove Mon Sep 1 15:04:05 2008 From: jaycx2.3.calrobert at spamgourmet.com.remove (Robert Maas,) Date: Mon, 01 Sep 2008 12:04:05 -0700 Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <g8bflo$984$1@localhost.localdomain> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> <s2lta4lorjk49dn3joo3gj3juc8rfqqinf@4ax.com> Message-ID: <rem-2008sep01-004@yahoo.com> > From: George Neuner <gneun... at comcast.net> > A friend of mine had an early 8080 micros that was programmed > through the front panel using knife switches When you say "knife switches", do you mean the kind that are shaped like flat paddles? I think that would be the IMSAI, which came after the ALTAIR. Those flat paddle-shaped switched would presumably be much more comfortable on the fingers than the standard metal toggle switches on the ALTAIR. I had an ALTAIR, which made front-panel programming rather painful on the fingers. > ... toggle in the binary address, latch it, toggle in the binary > data, latch it, repeat ad nauseam. For manually loading software in sequential locations, you have to enter the binary address only once. After that, you press the EXAMINE-NEXT toggle to increment the address by one. That reduced the effort by nearly a factor of 3. Instead of toggling a 16-bit address and EXAMINE and 8-bit datum and STORE each time, you toggle just EXAMINE-NEXT and 8-bit datum and STORE for each consecutive memory location after the first. Note the address and data toggles are bistable, stay in whatever position you left them in, whereas the three control toggles (EXAMIME EXAMINE-NEXT STORE) are spring loaded, making momentary contact when you force them then spring back to inactive when you release them. > It had no storage device initially ... to use it you had to input > your program by hand every time you turned it on. Almost but not quite true. With static RAM, most of the data can survive power-downs of hours or even days. I had 28k bytes of static RAM on my ALTAIR, so if I needed to start it up after it had been shut down I'd toggle in the starting address by hand, EXAMINE that, compare what shows with what's on my printed listing, and if it matches just EXAMINE-NEXT to compare the next. In the few cases I saw a bit or two flipped, I'd re-enter that one byte of data. I had to do that only for my BOOT1 loader, which was hand-loaded from front panel and took text input in 3n+1 form from Beehive 3A terminal connected to serial port, maybe also for BOOT2 loader which had been loaded in 3n+1 form and took input in hexadecimal form, and maybe also for BOOT3 loader which had been loaded in hexadecimail form from Beehive and automatically downloaded the next bootstrap loader from modem. If only a few bytes (of BOOT2 or BOOT3) had been damaged by days of power down, comparing binary against listing to verify it's 99% correct, and then manually patching just one or two bytes, would be faster and safer than manually entering 3n+1 or hexadecimal from keyboard. But once BOOT3 was loaded, I always downloaded all the rest of the software from the PDP-10 over the modem. > I did a little bit of programming on it, but I tired of it quickly. Did your friend's machine have two serial ports, one for local terminal and one for modem, and did you have access to a remote PDP-10 or other mainframe for running a cross-assembler? Or did you have some other computer locally available, where you could use that other computer both to store your library of code and to perform automated file transfer from archive on other computer to where it's needed on IMSAI? > As did my friend - once he got the tape storage working (a new > prom) Yeah, I never had the money to buy that, and with the PDP-10 available for both cross-assembling and archiving/downloading, I didn't need it. > Machine coding is not relevant anymore - it's completely > infeasible to input all but the smallest program. That's not totally true. For some educational purposes, like *really* understanding pointers (not the kind in C so much as the kind that are inherent in all pointer-linked data structures such as linked lists and binary search trees etc.), it helps to have some "hands-on" experience writing and executing machine-language code, in a sense actually "seeing" a register first point to the first byte of a CONS cell then by indexing with offset pointing *through* the *second* pointer of that CONS cell to whatever the CDR points to. Then "mission impossible" when your instructor tells you to see if there's a way to reverse that process, whereby you are given the register pointing to whatever the CDR points to, and you are supposed to find the address of the original CONS cell. Instant enlightenment, no lecture/sermon needed! From gminick at bzt.bzt Mon Sep 1 14:44:41 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 18:44:41 +0000 (UTC) Subject: Getting an objetcs dict? References: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> Message-ID: <g9hd6n$iqp$1@inews.gazeta.pl> On Mon, 1 Sep 2008 11:31:42 -0700 (PDT), ssecorp wrote: > I did nce(I think). > > class X > > X.__dict__() and ngot a dict of its variables. > > Now i get errors doing this. what am i doing wrong? You're not asking smart questions: http://www.catb.org/~esr/faqs/smart-questions.html HINT: the attribute you're accessing is not a callable. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From tjreedy at udel.edu Wed Sep 24 13:35:00 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2008 13:35:00 -0400 Subject: problem updating variable in a module In-Reply-To: <e0b6c39a0809240742k7ef2e8cfi33f88d8169b17170@mail.gmail.com> References: <e0b6c39a0809240742k7ef2e8cfi33f88d8169b17170@mail.gmail.com> Message-ID: <gbdtnq$jpb$1@ger.gmane.org> dudeja.rajat at gmail.com wrote: > Hi, > > I've a problem updating my variable in a module. > > In my main program, I call a function from mod1 to update a variable of mod1 > As soon as I update this varibale, I check it back in the mail program > but it the variable from mod1 does not get updated. > > main Program: > **************** > import mod1 > a = 20 > mod.update(a) > print mod.a <---- does not print anything As Tim noted, this cannot run. *** Always post the code you actually ran *** So we cannot answer why the code you did not post did not work. With the mod/mod1 mixup fixed, you do not need the update function. mod.a = 20 should do the same thing. > > mod1 > ******** > a = 10 > def update(someInt): > global a > a = someInt > print a <---- this does actually print a = 20 tjr From gminick at bzt.bzt Fri Sep 12 11:35:02 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 12 Sep 2008 15:35:02 +0000 (UTC) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <gae275$s4c$1@inews.gazeta.pl> On Fri, 12 Sep 2008 08:08:18 -0700 (PDT), Bojan Mihelac wrote: > Hi all - when trying to set some dynamic attributes in class, for > example: > > class A: > for lang in ['1', '2']: > exec('title_%s = lang' % lang) #this work but is ugly > # setattr(A, "title_%s" % lang, lang) # this wont work > I guess A class not yet exists in line 4. Is it possible to achive > adding dynamic attributes without using exec? Yes, it is: ------------- class A: for i in (1, 2): locals()['xxx%d' % (i)] = i print A.xxx1 print A.xxx2 a = A() print a.xxx1 print a.xxx2 ------------- And the output is: ----- 1 2 1 2 ----- But I definitely don't consider this one as a good programming practice. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From adykes at panix.com Sat Sep 13 10:09:39 2008 From: adykes at panix.com (Al Dykes) Date: 13 Sep 2008 10:09:39 -0400 Subject: Code example that will make a Skype connection? Message-ID: <gaghj3$4tf$1@panix5.panix.com> Can some post a Python code fragment that will to make a PC with Skpye installed to make a Skype call, given a valid phone # string. I'm not asking for code that handles the audio once the connection is made. -- Al Dykes News is something someone wants to suppress, everything else is advertising. - Lord Northcliffe, publisher of the Daily Mail From pavlovevidence at gmail.com Fri Sep 26 21:00:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 26 Sep 2008 18:00:36 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> <00b839d9-fe35-4478-aba2-0435fbf285e8@m36g2000hse.googlegroups.com> <00ed6d83$0$20666$c3e8da3@news.astraweb.com> <4039a6ac-f418-471b-8e21-3863adbe0d36@f63g2000hsf.googlegroups.com> Message-ID: <00139f01-67b9-48c4-ae2d-2a710d40474e@e53g2000hsa.googlegroups.com> On Sep 26, 8:53?pm, Carl Banks <pavlovevide... at gmail.com> wrote: > It might still end up being slower (creating slot descriptors might > take more time for all I know) but it's more than just an effect of > less memory. Actually scratch that. Descriptors are only created when the type object is created. I can't think of anything that would need to be done in an instance only if no dict is present, so using slots probably almost certianly makes object creation faster. Still, the last word is the profiler. Carl Banks From M8R-yfto6h at mailinator.com Sun Sep 28 15:20:55 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 28 Sep 2008 12:20:55 -0700 Subject: Music knowledge representation References: <mailman.1624.1222612634.3487.python-list@python.org><e21d8f09-6285-472e-9bfe-4757862d2c1c@x41g2000hsb.googlegroups.com> <mailman.1633.1222628890.3487.python-list@python.org> Message-ID: <7PGdnekcC-CMRELVnZ2dnUVZ_qKdnZ2d@comcast.com> "Mr.SpOOn" <mr.spoon21 at gmail.com> wrote in message news:mailman.1633.1222628890.3487.python-list at python.org... > On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady > <castironpi at gmail.com> wrote: > >> Here is a link to someone else's design they asked about on the >> newsgroup a couple weeks ago. >> >> http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc > > :D > It's always me. > > I think my question is more specific. I need some sort of cycle. > > So if I have a list with A, B, C, D, when I iter over it I need to get > an A after the D. Check out itertools.cycle: >>> x=itertools.cycle('ABCDEFG') >>> x.next() 'A' >>> x.next() 'B' >>> x.next() 'C' >>> x.next() 'D' >>> x.next() 'E' >>> x.next() 'F' >>> x.next() 'G' >>> x.next() 'A' >>> x.next() 'B' -Mark From mnordhoff at mattnordhoff.com Tue Sep 9 03:37:20 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 09 Sep 2008 07:37:20 +0000 Subject: "AttributeError: 'module' object has no attribute 'getdefaultlocale'" on Python start In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF601ADBEE2@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF601ADBE4D@enbmail01.lsi.com> <7F0503CD69378F49BE0DC30661C6CCF601ADBEE2@enbmail01.lsi.com> Message-ID: <48C627B0.6060806@mattnordhoff.com> Barak, Ron wrote: > Hi Fellow Pythonians, > > I stated getting the following when starting Python (2.5.2 on Windows XP): > > C:\Documents and Settings\RBARAK>python -v > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # D:\Python25\lib\site.pyc matches D:\Python25\lib\site.py > import site # precompiled from D:\Python25\lib\site.pyc > # D:\Python25\lib\os.pyc matches D:\Python25\lib\os.py > import os # precompiled from D:\Python25\lib\os.pyc > import errno # builtin > import nt # builtin > # D:\Python25\lib\ntpath.pyc matches D:\Python25\lib\ntpath.py > import ntpath # precompiled from D:\Python25\lib\ntpath.pyc > # D:\Python25\lib\stat.pyc matches D:\Python25\lib\stat.py > import stat # precompiled from D:\Python25\lib\stat.pyc > # D:\Python25\lib\UserDict.pyc matches D:\Python25\lib\UserDict.py > import UserDict # precompiled from D:\Python25\lib\UserDict.pyc > # D:\Python25\lib\copy_reg.pyc matches D:\Python25\lib\copy_reg.py > import copy_reg # precompiled from D:\Python25\lib\copy_reg.pyc > # D:\Python25\lib\types.pyc matches D:\Python25\lib\types.py > import types # precompiled from D:\Python25\lib\types.pyc > import _types # builtin > import locale # directory > D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale > import locale # precompiled from > D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale\__init__.pyc For some reason, when you run "import locale", it's importing wx.locale instead of the "locale" module from the stdlib. However, I have no idea why that would be happening... Did you do something to add wx to your PYTHONPATH? Maybe do "import sys; print sys.path" or "import os; print os.environ['PYTHONPATH']" to verify this. (Hopefully someone more knowledgeable than me will come along soon.) > # D:\Python25\lib\codecs.pyc matches D:\Python25\lib\codecs.py > import codecs # precompiled from D:\Python25\lib\codecs.pyc > import _codecs # builtin > import encodings # directory D:\Python25\lib\encodings > # D:\Python25\lib\encodings\__init__.pyc matches > D:\Python25\lib\encodings\__init__.py > import encodings # precompiled from D:\Python25\lib\encodings\__init__.pyc > # D:\Python25\lib\encodings\aliases.pyc matches > D:\Python25\lib\encodings\aliases.py > import encodings.aliases # precompiled from > D:\Python25\lib\encodings\aliases.pyc > 'import site' failed; traceback: > Traceback (most recent call last): > File "d:\Python25\lib\site.py", line 415, in <module> > main() > File "d:\Python25\lib\site.py", line 406, in main > aliasmbcs() > File "d:\Python25\lib\site.py", line 357, in aliasmbcs > enc = locale.getdefaultlocale()[1] > AttributeError: 'module' object has no attribute 'getdefaultlocale' > # D:\Python25\lib\warnings.pyc matches D:\Python25\lib\warnings.py > import warnings # precompiled from D:\Python25\lib\warnings.pyc > # D:\Python25\lib\linecache.pyc matches D:\Python25\lib\linecache.py > import linecache # precompiled from D:\Python25\lib\linecache.pyc > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> > > Has anyone else gotten this error ? > Could anyone suggest a solution ? > > Thanks, > Ron. -- From mike.terrell at earthlink.net Sun Sep 21 22:26:27 2008 From: mike.terrell at earthlink.net (Michael A. Terrell) Date: Sun, 21 Sep 2008 22:26:27 -0400 Subject: Milenko Kindl rtegdgd References: <b3a8139e-656c-4451-bbe4-203d48cb3203@d77g2000hsb.googlegroups.com> <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> Message-ID: <HoGdnZmrGszOn0rVnZ2dnUVZ_t3inZ2d@earthlink.com> H Vlems wrote: > > On 21 sep, 19:48, yuma <yuma400... at yahoo.com> wrote: > > Milenko Kindl > > Banja Luka > > Banjaluka > > Bihac > > Well, that's not C isn't it, more like Snobol or RPG/2 Tidybowl -- http://improve-usenet.org/index.html aioe.org, Goggle Groups, and Web TV users must request to be white listed, or I will not see your messages. If you have broadband, your ISP may have a NNTP news server included in your account: http://www.usenettools.net/ISP.htm There are two kinds of people on this earth: The crazy, and the insane. The first sign of insanity is denying that you're crazy. From arnodel at googlemail.com Sun Sep 14 13:45:58 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Sep 2008 10:45:58 -0700 (PDT) Subject: Is there any nice way to unpack a list of unknown size?? References: <238815.3778.qm@web7902.mail.in.yahoo.com> <mailman.1005.1221404903.3487.python-list@python.org> Message-ID: <6bbcb770-d9f7-4bfd-ae9a-491b2084a739@34g2000hsh.googlegroups.com> On Sep 14, 4:08?pm, Gary Herron <gher... at islandtraining.com> wrote: > srinivasan srinivas wrote: > > I want to do something like below: > > > 1. first, second, third, *rest = foo > > Python 3.0 has exactly this feature. ?No current Python 2.x version has it. > > Gary Herron > > > ?2. for (a,b,c,*rest) in list_of_lists: > > > Please suggest. > > > Thanks, > > Srini > > > ? ? ? Bring your gang together. Do your thing. Find your favourite Yahoo! group athttp://in.promos.yahoo.com/groups/ > > -- > >http://mail.python.org/mailman/listinfo/python-list In python >= 2.4, you can define a function like this: def truncate(iterable, n=1): iterator = iter(iterable) for i in iterator: if n == 0: yield iterator return yield i n -= 1 >>> a, b, c, tail = truncate([1,2,3,4,5,6], 3) >>> a 1 >>> b 2 >>> c 3 >>> tail <listiterator object at 0x78990> >>> list(tail) [5, 6] -- Arnaud From maebert at uos.de Tue Sep 16 11:41:33 2008 From: maebert at uos.de (Manuel Ebert) Date: Tue, 16 Sep 2008 15:41:33 -0000 (GMT) Subject: backup with python In-Reply-To: <11a3fca0-ded7-47c3-aeff-bb08acb1eb20@d1g2000hsg.googlegroups.com> References: <11a3fca0-ded7-47c3-aeff-bb08acb1eb20@d1g2000hsg.googlegroups.com> Message-ID: <59862.131.173.35.176.1221579693.squirrel@webmail.rz.uos.de> You may want to look into http://www.bigpaul.org/burn/ > Hi ! > I need some help to create backup with python. > I want to backup some bases on DVD - RW . > How i make this with python ? > I want to use python because the program is write on python . > > Thank you ! > -- > http://mail.python.org/mailman/listinfo/python-list > > -- www.redsdesk.de Goethering 10 49074 Osnabrueck Germany home +49.(0)541.3344529 mobile +49.(0)176.23970331 skype red.wraith icq 9905 7991 From aahz at pythoncraft.com Fri Sep 12 13:14:06 2008 From: aahz at pythoncraft.com (Aahz) Date: 12 Sep 2008 10:14:06 -0700 Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> <gae588$dnq$1@ger.gmane.org <mailman.934.1221237380.3487.python-list@python.org> Message-ID: <gae80u$fgf$1@panix3.panix.com> In article <mailman.934.1221237380.3487.python-list at python.org>, Fredrik Lundh <fredrik at pythonware.com> wrote: >Steve Holden wrote: >> >> The defence rests. > >can you please stop quoting that guy, so we don't have to killfile you >as well... +1 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From gnewsg at gmail.com Fri Sep 12 08:37:47 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 12 Sep 2008 05:37:47 -0700 (PDT) Subject: Please help me finding a way to implement os.path.issubpath(a, b) References: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> <34bc968e-735e-4ef0-99f3-3d71da6254d4@z72g2000hsb.googlegroups.com> Message-ID: <e08af2ae-7d39-4674-9a12-db49c9bf77cc@59g2000hsb.googlegroups.com> On Sep 11, 8:04?pm, Arnaud Delobelle <arno... at googlemail.com> wrote: > On Sep 11, 5:40?pm, "Giampaolo Rodola'" <gne... at gmail.com> wrote: > > > > > Hi, > > I'm trying to implement a function which returns whether a path is a > > subpath of another one (e.g. /a/b/c is a subpath of /a/b). > > I wrote this function which apparently seems to work fine: > > > import os > > > def issubpath(path1, path2): > > ? ? """Return True if path1 is a sub path of path2.""" > > ? ? if path1 == path2: > > ? ? ? ? return False > > ? ? x1 = path1.split(os.sep) > > ? ? x2 = path2.split(os.sep) > > ? ? return x1[:len(x2)] == x2 > > > ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False. > > A little help would be appreciated. > > > Thanks in advance. > > That's because: > > >>> 'C:\\dir'.split('\\') > ['C:', 'dir'] > >>> 'C:\\'.split('\\') > > ['C:', ''] > > So you could write instead something like > > ? ? x1 = path1.rstrip(os.sep).split(os.sep) > ? ? x2 = path2.rstrip(os.sep).split(os.sep) > > in your function > > HTH > > -- > Arnaud Thanks, it seems to work just fine. --- Giampaolo http://code.google.com/p/pyftpdlib/ From half.italian at gmail.com Wed Sep 3 20:51:59 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 3 Sep 2008 17:51:59 -0700 (PDT) Subject: Access to Windows "Add/Remove Programs"? Message-ID: <cf08e654-d2d5-48fe-a2ac-919fd2479254@v13g2000pro.googlegroups.com> Hi all, I'm trying to find a way to get a list of all the installed programs on a Windows box via Python. I thought of a few hacks that might partially work, and then thought about "Add/Remove Programs" Seems like the right way to go. I looked over the pywin32 docs a bit, but nothing slapped me in the face. Is there any reliable way to get at that info? Thanks in advance, ~Sean From bockman at virgilio.it Sun Sep 14 06:32:34 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 14 Sep 2008 10:32:34 GMT Subject: Windows / Tkinter - problem with grid - not able to place widgets at desired places References: <e0b6c39a0808170725q2937194dl96049b16300aec@mail.gmail.com> <mailman.1760.1219058122.922.python-list@python.org> Message-ID: <48cce842$0$11367$5fc30a8@news.tiscali.it> Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto: >>Hi, >> >>I'm learning Python and Tkinter. I've started programming in Eclipse >>with PyDev. I'm intending to create a GUI. I'm not able to understand >>the Grid manager perhaps because there is quite a less documentation >>available for it on the net. >> >>My desired GUI is attached in the mail. Although I've tried writing a >>class module for this GUI but I'm not able to set all things right in >>the GUI. The Biggest problem seems to be with the Grid Manager in terms >>how it divides a window in Rows / columns. etc. I'm not able to place >>none of the widgets correctly in the GUI. >> >>For your convenience, I'm attaching this code also as myModule1.py . >>Please some one review it and help create me this GUI. >> Uhm, I don't think you should use the grid manager to obtain a window like that. The grid manager is for equally distributing widgets both horizontally and vertically. And I'm not sure that you can realize that window look with Tkinter. You could get close by horizontally packing each widget row in a frame and then vertically packing the frames in the window. But the look will be quite different than your target. If you are not satisfied with that I suggest you move to other toolkits which have more complex geometry managers than .pack and .grid. Ciao ----- FB From ewertman at gmail.com Tue Sep 2 23:51:02 2008 From: ewertman at gmail.com (Eric Wertman) Date: Tue, 2 Sep 2008 23:51:02 -0400 Subject: Library/project for making an invitation-only website? In-Reply-To: <7502-61941@sneakemail.com> References: <7502-61941@sneakemail.com> Message-ID: <92da89760809022051t6f8f5ecpe8b982dcd793beee@mail.gmail.com> I think Drupy is best library for these task. On Tue, Sep 2, 2008 at 12:27 PM, Dani <iphthfu02 at sneakemail.com> wrote: > Hi. > > I want to create a website where new users need to be invited by an existing user in order to open an account. Think of it the way Orkut became popular. > > I need a library, or code from some project, that sends the invitations, keeps track of which user invited who, etc. > > I'm sure there's already some code out there that performs these tasks. Drupy maybe? > > Could anybody recommend me some library/project for these tasks? > > Thank you in advance. > -- > http://mail.python.org/mailman/listinfo/python-list > From gstaniak at wp.pl Mon Sep 22 18:12:02 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Mon, 22 Sep 2008 22:12:02 +0000 (UTC) Subject: A bit weird dictionary behavior References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> Message-ID: <gb957i$ja0$1@news.lublin.pl> On 22.09.2008, Carl Banks <pavlovevidence at gmail.com> wroted: >> >> but it still doesn't feel exactly right. Would it be worth submitting a bug? >> >> > It feels wrong because it is. In a tidier language (Pascal, Java, etc) >> > a boolean and an integer must be different types. >> >> Some would argue (and some did by the time Python grew a 'bool' type) >> that what is wrong is to have a bool type in a language that already >> have a wider definition of the truth value of an expression... > > And some would argue that it was wrong to have such a wide definition > for the truth value of an expression in the first place... Just out of idle curiosity, what could be the alternatives? Not to evaluate e.g. strings to "true"? Aren't such conventions as "whatever is not empty, is 'true'" popular in dynamic langauges? GS -- Grzegorz Staniak <gstaniak _at_ wp [dot] pl> Nocturnal Infiltration and Accurate Killing From aioe.org at technicalbloke.com Sat Sep 27 02:26:25 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 27 Sep 2008 02:26:25 -0400 Subject: How to get the filename in the right case ? References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> <Xns9B24589F2DBEOKB@199.45.49.11> <48DBB9C8.6090500@gmail.com> <gbh53f$dim$1@ger.gmane.org> <mailman.1518.1222386373.3487.python-list@python.org> <pan.2008.09.26.07.28.03@REMOVE.THIS.cybersource.com.au> Message-ID: <gbkjmh$l2q$2@aioe.org> Steven D'Aprano wrote: > On Fri, 26 Sep 2008 01:46:15 +0200, Stef Mientki wrote: > >> Secondly thoughtless copying of current behavior, doesn't bring any >> progress, >> and I think that's one of the reasons why we're still burdened by >> inventions done 20 years ago, >> e.g. "do you want to save your changes ?". > > I click No about 50% of the time, and Yes Of Course You Stupid Machine > the other 50% of the time. Until they have a computer capable of reading > my mind, I'm curious what alternative you'd suggest. > > Agreed, it's pretty handy, especially since every program and its dog decided to sprout tabs everywhere. Roger. From dudeja.rajat at gmail.com Tue Sep 16 08:50:37 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 16 Sep 2008 13:50:37 +0100 Subject: Problem parsing the input Message-ID: <e0b6c39a0809160550kfb6dd1flf09e94c80eb176f1@mail.gmail.com> Hi, I've a following input: ***** - Burst_Length not read from ini file ? - + BurstLength not read from ini file ***** - PilotTracking_Timing not read from ini file ? ^^^^^^^^^^^^^^ + NumTimings not read from ini file ***** - Analysis Time (Iterations = 1) = 0.519444s ? ^ --- + Analysis Time (Iterations = 1) = 0.562249s ***** - Burst Position = 89511samples ? ^ + Burst Position = 89510samples ***** - Rising Edge Time = 371682us ? ^ + Rising Edge Time = 371683us ***** How can I find the the colored items from the input. I though of using RE but don't know much about it. The colored item can be dot notation e.g. 0.05678 or a whole digit as 5678 Please help -- Regrads, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080916/0476a65b/attachment.html> From bdesth.quelquechose at free.quelquepart.fr Mon Sep 29 16:04:29 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2008 22:04:29 +0200 Subject: Converting a strng to an anonymous function In-Reply-To: <gbrh3l$m18$1@aioe.org> References: <gbrh3l$m18$1@aioe.org> Message-ID: <48e150b6$0$12658$426a74cc@news.free.fr> Nathan Seese a ?crit : > I'm writing a program to sort files with arbitrary python code. The > method I'm using for that is to pass sort an anonymous function taken > from the arguments. I'm wondering how to change a raw string into an > anonyous function. Care to give a couple more explanation about your use case ? There might be better solutions than eval/exec... From praveenapanch at gmail.com Mon Sep 8 05:26:20 2008 From: praveenapanch at gmail.com (Praveena P) Date: Mon, 8 Sep 2008 02:26:20 -0700 (PDT) Subject: String to hexadecimal conversion References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Message-ID: <ba106c18-3e8e-4642-bbe0-0dac3d69411e@z66g2000hsc.googlegroups.com> On Sep 8, 2:05?pm, Praveena P <praveenapa... at gmail.com> wrote: > Hi folks, > > I am new to Python... so am not too sure about how the type conversion > works. > > I have to read a file that contains hexadecimal data and use the data > further to do some arithmetic calculations. > A sample of the input is : 00000000000020E0000032F800000000400022005E > The problem I am facing is this: > I am using f.read(2) to read a byte at a time, but the data that is > read is a string rather than a number. So it kind of hampers any > arithmetic operations I perform on this data... > > Could you please suggest some method I could use for this? > > Thanks guys! > Praveena I was thinking of using dictionary like this: hex_to_decimal = {"1":"1", "2":"2", "3":"3", "4":"4", "5":"5", "6":"6", "7":"7", "8":"8", "9":"9", "A":"10", "B":"11", "C":"12", "D":"13", "E":"14", "F":"15", "0":"0"} Extracting one character at a time and converting to decimal, and then using the decimal numbers generated for the further calculations.... Would there be a simpler way to do it? From clp at rebertia.com Mon Sep 29 13:19:55 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Sep 2008 10:19:55 -0700 Subject: Generate documentation for a Python developed software In-Reply-To: <1222706734.15761.403.camel@king.imim.es> References: <1222706734.15761.403.camel@king.imim.es> Message-ID: <47c890dc0809291019m5e31df2eq2c0340e2f2c01f84@mail.gmail.com> On Mon, Sep 29, 2008 at 9:45 AM, Alfons Nonell-Canals <alfons.nonell at upf.edu> wrote: > Dear all, > I have a complex program developed using Python. It contains lot of > files and classes. > > Now I have the lazy task to documentate it. I have some notes about is > class but I would like to know if there is something to auto-generate > the doucmentation with the program code. I know I will have to explain > each class and variable but, if an external software canprepare it, the > template, it will be great! Sphinx (http://sphinx.pocoo.org/) is pretty slick and was used to generate the spiffy new python docs (http://docs.python.org/dev/). There's also epydoc (http://epydoc.sourceforge.net/), the standard library module 'pydoc', and [to a lesser degree] Doxygen (http://www.stack.nl/~dimitri/doxygen/) Regards, Chris > > Thanks in advance! > > Regards, > > -- > ------------ > Alfons Nonell-Canals > Chemogenomics Lab > Research Group on Biomedical Informatics (GRIB) - IMIM/UPF > Parc de Recerca Biom?dica de Barcelona (PRBB) > C/ Doctor Aiguader, 88 - 08003 Barcelona > alfons.nonell at upf.edu - http://cgl.imim.es > > http://alfons.elmeuportal.cat > http://www.selenocisteina.info > > -- > http://mail.python.org/mailman/listinfo/python-list -- Follow the path of the Iguana... http://rebertia.com From aioe.org at technicalbloke.com Wed Sep 17 13:41:26 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 13:41:26 -0400 Subject: File Reading related query References: <a3158e8b0809170255y6527dc96ta0f7466fd575db8f@mail.gmail.com> <mailman.1158.1221646738.3487.python-list@python.org> Message-ID: <garfg6$e17$1@aioe.org> Fredrik Lundh wrote: > Usman Ajmal wrote: > >> Is there any function for reading a file while ignoring *\n* occuring >> in the file? > > can you be a bit more precise? are we talking about text files or > binary files? how do you want to treat any newlines that actually > appear in the file? > > </F> > Hi Usan, I've always just done... for each in open('filename.txt', 'r'): each = each.rstrip() You could wrap this as a generator if you really want it to be a one liner, personally it's never seemed worth it to me. Regards, Roger Heathcote http://www.technicalbloke.com http://movingtoubuntu.technicalbloke.co.uk From deets at nospam.web.de Fri Sep 5 07:07:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 13:07:28 +0200 Subject: atomic section in code In-Reply-To: <c0632676-51ab-4cf6-a6a7-f2f089196d57@m45g2000hsb.googlegroups.com> References: <a475a219-1577-4018-a541-5b05c87f6f71@i76g2000hsf.googlegroups.com> <mailman.544.1220605512.3487.python-list@python.org> <c0632676-51ab-4cf6-a6a7-f2f089196d57@m45g2000hsb.googlegroups.com> Message-ID: <6ici7gFo8e4nU1@mid.uni-berlin.de> Ahmad Humayun schrieb: > On Sep 5, 1:59 pm, Fredrik Lundh <fred... at pythonware.com> wrote: >> Ahmad Humayun wrote: >>> I need to create an atomic section in Python code i.e. there is no >>> context switch to any other thread during the running of that piece of >>> code. Would would do the trick? >> use a lock, and make sure that anyone that needs access to the shared >> state you're manipulating in that section uses the same lock. >> >> lock = threading.Lock() # or RLock() etc [1] >> >> with lock: >> section >> >> this only works if everyone honors the lock, of course; there's no way >> in Python to lock out non-cooperating external threads. >> >> </F> >> >> 1) seehttp://effbot.org/zone/thread-synchronization.htm > > Thats true, but this will ensure mutual exclusion; not atomicity AFAIC that kind of mutual exclusion is what atomicity is about. What else do you expect to happen? Diez From alamat_email_aku at yahoo.co.id Thu Sep 4 09:15:49 2008 From: alamat_email_aku at yahoo.co.id (Abdurrahman Wahid) Date: Thu, 4 Sep 2008 06:15:49 -0700 (PDT) Subject: Assalamu'alaikum wr. wb. Message-ID: <1a5daf31-d1de-4973-9a69-04d1bc8f27da@r15g2000prd.googlegroups.com> Assalamu'alaikum wr. wb., Faith Freedom Indonesia (http://www.indonesia.faithfreedom.org/forum/) The Amazing Racist: Moslem Mosque (http://13gb.com/videos/923/) Forum Murtadin Indonesia (http://mantanmuslim.blogspot.com/) Wassalam From goon12 at gmail.com Tue Sep 23 08:54:25 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 23 Sep 2008 08:54:25 -0400 Subject: finding domain name In-Reply-To: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> Message-ID: <6a2ccd190809230554w43ac4752k52c6d7f49447faca@mail.gmail.com> On Tue, Sep 23, 2008 at 8:37 AM, Bobby Roberts <tchendrix at gmail.com> wrote: > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/xxxxx/ > > where xxxxx represents the domain name. > > How can I find the domain name of the current url being viewed. I would guess that a pretty simple regular expression might do it. From fredrik at pythonware.com Tue Sep 16 03:30:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Sep 2008 09:30:35 +0200 Subject: Cross-platform socket.getsockopt and struct.unpack (or socket timeout)? In-Reply-To: <vs-dnbIKaOy4wlLVnZ2dnUVZ_vGdnZ2d@comcast.com> References: <vs-dnbIKaOy4wlLVnZ2dnUVZ_vGdnZ2d@comcast.com> Message-ID: <gannau$2r8$2@ger.gmane.org> Heikki Toivonen wrote: > Is there a cross-platform way of doing what the M2Crypto code is > attempting to do? calling the socket object's settimeout() method? </F> From patrick.chartier at aero.bombardier.com Sun Sep 7 05:55:32 2008 From: patrick.chartier at aero.bombardier.com (wildfireporn.com@googlegroups.com) Date: Sun, 7 Sep 2008 02:55:32 -0700 (PDT) Subject: Watch Free Adult Videos Online Message-ID: <bd51f8fe-bd9e-4ce8-8cc6-e56214447e00@8g2000hse.googlegroups.com> http://groups.google.com/group/hyd-masti?lnk= From febkimbleox at gmail.com Sat Sep 27 07:18:12 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:18:12 -0700 (PDT) Subject: amy fisher sex tape free amy fisher sex tape amy fisher - Free Message-ID: <7fb54300-b8e5-4781-b0fc-b807747bc814@e53g2000hsa.googlegroups.com> amy . . . *******CLICK HERE******** http://vids365.cn/amy ***************************** . . . . . . . . . . . . She then walks toward amy with a slow, seductive sway with amy large breasts bouncing slightly with each step. She then walks toward fisher with a slow, seductive sway with fisher large breasts bouncing slightly with each step. She then walks toward sex with a slow, seductive sway with sex large breasts bouncing slightly with each step. She then walks toward tape with a slow, seductive sway with tape large breasts bouncing slightly with each step. She then walks toward free with a slow, seductive sway with free large breasts bouncing slightly with each step. She then walks toward amy with a slow, seductive sway with amy large breasts bouncing slightly with each step. She then walks toward fisher with a slow, seductive sway with fisher large breasts bouncing slightly with each step. She then walks toward sex with a slow, seductive sway with sex large breasts bouncing slightly with each step. She then walks toward tape with a slow, seductive sway with tape large breasts bouncing slightly with each step. She then walks toward amy with a slow, seductive sway with amy large breasts bouncing slightly with each step. She then walks toward fisher with a slow, seductive sway with fisher large breasts bouncing slightly with each step. You are one gorgeous girl and sex won't hurt sex any, just keep doing what sex say. You are one gorgeous girl and tape won't hurt tape any, just keep doing what tape say. You are one gorgeous girl and free won't hurt free any, just keep doing what free say. You are one gorgeous girl and amy won't hurt amy any, just keep doing what amy say. You are one gorgeous girl and fisher won't hurt fisher any, just keep doing what fisher say. You are one gorgeous girl and sex won't hurt sex any, just keep doing what sex say. You are one gorgeous girl and tapes won't hurt tapes any, just keep doing what tapes say. You are one gorgeous girl and amy won't hurt amy any, just keep doing what amy say. You are one gorgeous girl and fisher won't hurt fisher any, just keep doing what fisher say. You are one gorgeous girl and sex won't hurt sex any, just keep doing what sex say. You are one gorgeous girl and tape won't hurt tape any, just keep doing what tape say. You are one gorgeous girl and download won't hurt download any, just keep doing what download say. ?She then says, ?Thanks, amy can come in, and place amy on the table next to the tub, if amy don?t mind. ?She then says, ?Thanks, fisher can come in, and place fisher on the table next to the tub, if fisher don?t mind. ?She then says, ?Thanks, sex can come in, and place sex on the table next to the tub, if sex don?t mind. ?She then says, ?Thanks, tape can come in, and place tape on the table next to the tub, if tape don?t mind. ?She then says, ?Thanks, clips can come in, and place clips on the table next to the tub, if clips don?t mind. ?She then says, ?Thanks, amy can come in, and place amy on the table next to the tub, if amy don?t mind. ?She then says, ?Thanks, fisher can come in, and place fisher on the table next to the tub, if fisher don?t mind. ?She then says, ?Thanks, free can come in, and place free on the table next to the tub, if free don?t mind. ?She then says, ?Thanks, sex can come in, and place sex on the table next to the tub, if sex don?t mind. ?She then says, ?Thanks, tape can come in, and place tape on the table next to the tub, if tape don?t mind. ?She then says, ?Thanks, a can come in, and place a on the table next to the tub, if a don?t mind. ?She then says, ?Thanks, sex can come in, and place sex on the table next to the tub, if sex don?t mind. As tape watched, tape sprung a full blown hard on, just looking at her. As of watched, of sprung a full blown hard on, just looking at her. As amy watched, amy sprung a full blown hard on, just looking at her. As fisher watched, fisher sprung a full blown hard on, just looking at her. As and watched, and sprung a full blown hard on, just looking at her. As her watched, her sprung a full blown hard on, just looking at her. As husband watched, husband sprung a full blown hard on, just looking at her. As amy watched, amy sprung a full blown hard on, just looking at her. As fisher watched, fisher sprung a full blown hard on, just looking at her. As sex watched, sex sprung a full blown hard on, just looking at her. As tape watched, tape sprung a full blown hard on, just looking at her. As sex watched, sex sprung a full blown hard on, just looking at her. ? Oh fuck, tape cock was getting hard again. ? Oh fuck, of cock was getting hard again. ? Oh fuck, amy cock was getting hard again. ? Oh fuck, fisher cock was getting hard again. ? Oh fuck, download cock was getting hard again. ? Oh fuck, amy cock was getting hard again. ? Oh fuck, fisher cock was getting hard again. ? Oh fuck, sex cock was getting hard again. ? Oh fuck, tape cock was getting hard again. ? Oh fuck, watch cock was getting hard again. ? Oh fuck, amy cock was getting hard again. ? Oh fuck, fisher cock was getting hard again. sex knew a second later when the needle passed through both of my labia. tape knew a second later when the needle passed through both of my labia. amy knew a second later when the needle passed through both of my labia. fisher knew a second later when the needle passed through both of my labia. sex knew a second later when the needle passed through both of my labia. tape knew a second later when the needle passed through both of my labia. uncensored knew a second later when the needle passed through both of my labia. amy knew a second later when the needle passed through both of my labia. fisher knew a second later when the needle passed through both of my labia. sex knew a second later when the needle passed through both of my labia. tape knew a second later when the needle passed through both of my labia. free knew a second later when the needle passed through both of my labia. Then lifts them to download mouth and licks the cunt juice from them. Then lifts them to amy mouth and licks the cunt juice from them. Then lifts them to fisher mouth and licks the cunt juice from them. Then lifts them to sex mouth and licks the cunt juice from them. Then lifts them to tape mouth and licks the cunt juice from them. Then lifts them to preview mouth and licks the cunt juice from them. Then lifts them to amy mouth and licks the cunt juice from them. Then lifts them to fisher mouth and licks the cunt juice from them. Then lifts them to sex mouth and licks the cunt juice from them. Then lifts them to tape mouth and licks the cunt juice from them. Then lifts them to review mouth and licks the cunt juice from them. Then lifts them to amy mouth and licks the cunt juice from them. fisher wasn't tied. sex wasn't tied. tape wasn't tied. uncut wasn't tied. amy wasn't tied. fisher wasn't tied. sex wasn't tied. tapes wasn't tied. gallery wasn't tied. amy wasn't tied. fisher wasn't tied. When sex comes near sex ass, sex sighs, then slaps sex butt gently and giggles, ?You have a nice ass baby, if sex don?t mind sex saying so. When tape comes near tape ass, tape sighs, then slaps tape butt gently and giggles, ?You have a nice ass baby, if tape don?t mind tape saying so. When amy comes near amy ass, amy sighs, then slaps amy butt gently and giggles, ?You have a nice ass baby, if amy don?t mind amy saying so. When fisher comes near fisher ass, fisher sighs, then slaps fisher butt gently and giggles, ?You have a nice ass baby, if fisher don?t mind fisher saying so. When sex comes near sex ass, sex sighs, then slaps sex butt gently and giggles, ?You have a nice ass baby, if sex don?t mind sex saying so. When tape comes near tape ass, tape sighs, then slaps tape butt gently and giggles, ?You have a nice ass baby, if tape don?t mind tape saying so. When sample comes near sample ass, sample sighs, then slaps sample butt gently and giggles, ?You have a nice ass baby, if sample don?t mind sample saying so. When release comes near release ass, release sighs, then slaps release butt gently and giggles, ?You have a nice ass baby, if release don?t mind release saying so. When date comes near date ass, date sighs, then slaps date butt gently and giggles, ?You have a nice ass baby, if date don?t mind date saying so. When amy comes near amy ass, amy sighs, then slaps amy butt gently and giggles, ?You have a nice ass baby, if amy don?t mind amy saying so. When fisher comes near fisher ass, fisher sighs, then slaps fisher butt gently and giggles, ?You have a nice ass baby, if fisher don?t mind fisher saying so. When sex comes near sex ass, sex sighs, then slaps sex butt gently and giggles, ?You have a nice ass baby, if sex don?t mind sex saying so. If tape could have screamed tape certainly would have. If sex could have screamed sex certainly would have. If tape could have screamed tape certainly would have. If amy could have screamed amy certainly would have. If fisher could have screamed fisher certainly would have. If the could have screamed the certainly would have. If amy could have screamed amy certainly would have. If fisher could have screamed fisher certainly would have. If sex could have screamed sex certainly would have. If tape could have screamed tape certainly would have. If amy could have screamed amy certainly would have. If fisher could have screamed fisher certainly would have. If promotes could have screamed promotes certainly would have. See sex in a few minutes. See tape in a few minutes. See amy in a few minutes. See fisher in a few minutes. See sex in a few minutes. See tape in a few minutes. See full in a few minutes. See download in a few minutes. See amy in a few minutes. See fisher in a few minutes. See sex in a few minutes. See tape in a few minutes. pictures couldn't speak! I'll clean pictures up, then you'll have some washing to do. amy couldn't speak! I'll clean amy up, then you'll have some washing to do. fisher couldn't speak! I'll clean fisher up, then you'll have some washing to do. sex couldn't speak! I'll clean sex up, then you'll have some washing to do. tape couldn't speak! I'll clean tape up, then you'll have some washing to do. rapidshare couldn't speak! I'll clean rapidshare up, then you'll have some washing to do. amy couldn't speak! I'll clean amy up, then you'll have some washing to do. sex couldn't speak! I'll clean sex up, then you'll have some washing to do. fisher couldn't speak! I'll clean fisher up, then you'll have some washing to do. tape couldn't speak! I'll clean tape up, then you'll have some washing to do. amy couldn't speak! I'll clean amy up, then you'll have some washing to do. fisher couldn't speak! I'll clean fisher up, then you'll have some washing to do. After all sex is quite handsome and sex prefers older men. After all tape is quite handsome and tape prefers older men. After all downloads is quite handsome and downloads prefers older men. After all amy is quite handsome and amy prefers older men. After all fisher is quite handsome and fisher prefers older men. After all sex is quite handsome and sex prefers older men. After all tape is quite handsome and tape prefers older men. After all links is quite handsome and links prefers older men. After all amy is quite handsome and amy prefers older men. After all fisher is quite handsome and fisher prefers older men. After all sex is quite handsome and sex prefers older men. After all tape is quite handsome and tape prefers older men. ?As screen glasses clicked screen told himself, ?The best is yet to come, my precious Valentine. ?As shot glasses clicked shot told himself, ?The best is yet to come, my precious Valentine. ?As amy glasses clicked amy told himself, ?The best is yet to come, my precious Valentine. ?As fisher glasses clicked fisher told himself, ?The best is yet to come, my precious Valentine. ?As sex glasses clicked sex told himself, ?The best is yet to come, my precious Valentine. ?As tape glasses clicked tape told himself, ?The best is yet to come, my precious Valentine. ?As torrent glasses clicked torrent told himself, ?The best is yet to come, my precious Valentine. ?As amy glasses clicked amy told himself, ?The best is yet to come, my precious Valentine. ?As fisher glasses clicked fisher told himself, ?The best is yet to come, my precious Valentine. ?As sex glasses clicked sex told himself, ?The best is yet to come, my precious Valentine. ?As tape glasses clicked tape told himself, ?The best is yet to come, my precious Valentine. ?As where glasses clicked where told himself, ?The best is yet to come, my precious Valentine. His hand would slip and caress can breast. His hand would slip and caress i breast. His hand would slip and caress find breast. His hand would slip and caress amy breast. His hand would slip and caress fisher breast. His hand would slip and caress xxx breast. His hand would slip and caress sex breast. His hand would slip and caress tape breast. His hand would slip and caress where breast. His hand would slip and caress can breast. His hand would slip and caress i breast. His hand would slip and caress find breast. Here was one of the girdles, a pair of the bloomers and several pairs of the knickers - not to mention stockings, bras and slips (petticoats, as the called them then). Here was one of amy girdles, a pair of amy bloomers and several pairs of amy knickers - not to mention stockings, bras and slips (petticoats, as amy called them then). Here was one of fisher girdles, a pair of fisher bloomers and several pairs of fisher knickers - not to mention stockings, bras and slips (petticoats, as fisher called them then). Here was one of sex girdles, a pair of sex bloomers and several pairs of sex knickers - not to mention stockings, bras and slips (petticoats, as sex called them then). Here was one of tape girdles, a pair of tape bloomers and several pairs of tape knickers - not to mention stockings, bras and slips (petticoats, as tape called them then). Here was one of for girdles, a pair of for bloomers and several pairs of for knickers - not to mention stockings, bras and slips (petticoats, as for called them then). Here was one of free girdles, a pair of free bloomers and several pairs of free knickers - not to mention stockings, bras and slips (petticoats, as free called them then). Here was one of amy girdles, a pair of amy bloomers and several pairs of amy knickers - not to mention stockings, bras and slips (petticoats, as amy called them then). Here was one of fisher girdles, a pair of fisher bloomers and several pairs of fisher knickers - not to mention stockings, bras and slips (petticoats, as fisher called them then). Here was one of nudity girdles, a pair of nudity bloomers and several pairs of nudity knickers - not to mention stockings, bras and slips (petticoats, as nudity called them then). Here was one of sex girdles, a pair of sex bloomers and several pairs of sex knickers - not to mention stockings, bras and slips (petticoats, as sex called them then). Here was one of tape girdles, a pair of tape bloomers and several pairs of tape knickers - not to mention stockings, bras and slips (petticoats, as tape called them then). Here was one of amy girdles, a pair of amy bloomers and several pairs of amy knickers - not to mention stockings, bras and slips (petticoats, as amy called them then). fisher leaned back, fisher eyes fixed on my cock as fisher pushed against fisher innocent teen slit, stretching fisher virgin love hole as my head penetrated fisher wetness. sex leaned back, sex eyes fixed on my cock as sex pushed against sex innocent teen slit, stretching sex virgin love hole as my head penetrated sex wetness. tape leaned back, tape eyes fixed on my cock as tape pushed against tape innocent teen slit, stretching tape virgin love hole as my head penetrated tape wetness. clip leaned back, clip eyes fixed on my cock as clip pushed against clip innocent teen slit, stretching clip virgin love hole as my head penetrated clip wetness. amy leaned back, amy eyes fixed on my cock as amy pushed against amy innocent teen slit, stretching amy virgin love hole as my head penetrated amy wetness. fisher leaned back, fisher eyes fixed on my cock as fisher pushed against fisher innocent teen slit, stretching fisher virgin love hole as my head penetrated fisher wetness. sex leaned back, sex eyes fixed on my cock as sex pushed against sex innocent teen slit, stretching sex virgin love hole as my head penetrated sex wetness. tape leaned back, tape eyes fixed on my cock as tape pushed against tape innocent teen slit, stretching tape virgin love hole as my head penetrated tape wetness. part leaned back, part eyes fixed on my cock as part pushed against part innocent teen slit, stretching part virgin love hole as my head penetrated part wetness. 2 leaned back, 2 eyes fixed on my cock as 2 pushed against 2 innocent teen slit, stretching 2 virgin love hole as my head penetrated 2 wetness. amy leaned back, amy eyes fixed on my cock as amy pushed against amy innocent teen slit, stretching amy virgin love hole as my head penetrated amy wetness. fisher leaned back, fisher eyes fixed on my cock as fisher pushed against fisher innocent teen slit, stretching fisher virgin love hole as my head penetrated fisher wetness. In sex mind, sex was saying, ?Rebecca, don?t worry sex pretty little head, sex intend to marry sex daughter. In tape mind, tape was saying, ?Rebecca, don?t worry tape pretty little head, tape intend to marry tape daughter. In warez mind, warez was saying, ?Rebecca, don?t worry warez pretty little head, warez intend to marry warez daughter. In amy mind, amy was saying, ?Rebecca, don?t worry amy pretty little head, amy intend to marry amy daughter. In fisher mind, fisher was saying, ?Rebecca, don?t worry fisher pretty little head, fisher intend to marry fisher daughter. In sex mind, sex was saying, ?Rebecca, don?t worry sex pretty little head, sex intend to marry sex daughter. In tape mind, tape was saying, ?Rebecca, don?t worry tape pretty little head, tape intend to marry tape daughter. In with mind, with was saying, ?Rebecca, don?t worry with pretty little head, with intend to marry with daughter. In husband mind, husband was saying, ?Rebecca, don?t worry husband pretty little head, husband intend to marry husband daughter. In amy mind, amy was saying, ?Rebecca, don?t worry amy pretty little head, amy intend to marry amy daughter. In fisher mind, fisher was saying, ?Rebecca, don?t worry fisher pretty little head, fisher intend to marry fisher daughter. I joined my parents and uncut walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and sex walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and tape walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and part3 walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and free walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and amy walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and fisher walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and sex walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and tape walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and movies walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and free walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and amy walked into a large room decorated with flowers where the wedding service was being held. fisher was just thinking about this dress fisher saw in a magazine, and how good fisher would look on you. sex was just thinking about this dress sex saw in a magazine, and how good sex would look on you. tapes was just thinking about this dress tapes saw in a magazine, and how good tapes would look on you. leaked was just thinking about this dress leaked saw in a magazine, and how good leaked would look on you. amy was just thinking about this dress amy saw in a magazine, and how good amy would look on you. fisher was just thinking about this dress fisher saw in a magazine, and how good fisher would look on you. sex was just thinking about this dress sex saw in a magazine, and how good sex would look on you. tape was just thinking about this dress tape saw in a magazine, and how good tape would look on you. long was just thinking about this dress long saw in a magazine, and how good long would look on you. island was just thinking about this dress island saw in a magazine, and how good island would look on you. lolita was just thinking about this dress lolita saw in a magazine, and how good lolita would look on you. amy was just thinking about this dress amy saw in a magazine, and how good amy would look on you. fisher was just thinking about this dress fisher saw in a magazine, and how good fisher would look on you. At last sex all came to an end and sex trooped past Joe and Samantha as sex welcomed us to the reception. At last tape all came to an end and tape trooped past Joe and Samantha as tape welcomed us to the reception. At last watch all came to an end and watch trooped past Joe and Samantha as watch welcomed us to the reception. At last amy all came to an end and amy trooped past Joe and Samantha as amy welcomed us to the reception. At last fisher all came to an end and fisher trooped past Joe and Samantha as fisher welcomed us to the reception. At last sex all came to an end and sex trooped past Joe and Samantha as sex welcomed us to the reception. At last tape all came to an end and tape trooped past Joe and Samantha as tape welcomed us to the reception. At last for all came to an end and for trooped past Joe and Samantha as for welcomed us to the reception. At last free all came to an end and free trooped past Joe and Samantha as free welcomed us to the reception. At last watchable all came to an end and watchable trooped past Joe and Samantha as watchable welcomed us to the reception. At last amy all came to an end and amy trooped past Joe and Samantha as amy welcomed us to the reception. At last fisher all came to an end and fisher trooped past Joe and Samantha as fisher welcomed us to the reception. Okay, sex hear you. Okay, tape hear you. Okay, where hear you. Okay, can hear you. Okay, i hear you. Okay, find hear you. Okay, amy hear you. Okay, fisher hear you. Okay, sex hear you. Okay, tape hear you. Okay, for hear you. Okay, free hear you. From lists at cheimes.de Tue Sep 16 11:56:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Sep 2008 17:56:19 +0200 Subject: How do I add permanently to Pythons sys.path? In-Reply-To: <A183D966-C2F9-453F-8A74-CB0ADEDEBDE2@rgbaz.eu> References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <A183D966-C2F9-453F-8A74-CB0ADEDEBDE2@rgbaz.eu> Message-ID: <gaokv2$922$1@ger.gmane.org> Python wrote: > a temp solution is to append it to that list: > > sys.path.append('C:/Python25/Progs/') > > a permanent solution is to add it to the environment variable > (no idea where to set this in windows) > $PYTHONPATH = "/C:/Python25/Progs/" Don't append a / or \!Use "C:/Python25/Progs" instead of "C:/Python25/Progs/". The trailing slash causes trouble on Windows. The reason for the trouble is design decision from Microsoft. The low level stat() syscall returns an error for "C:\\Python25\\Progs\\" but it returns success for "C:\\Python25\\Progs". Christian From steven at REMOVE.THIS.cybersource.com.au Tue Sep 30 05:32:41 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 09:32:41 GMT Subject: How best to pass arbitrary parameters from one function to another References: <mailman.1731.1222764932.3487.python-list@python.org> Message-ID: <pan.2008.09.30.09.32.41@REMOVE.THIS.cybersource.com.au> On Tue, 30 Sep 2008 08:58:15 +0000, John O'Hagan wrote: > Hi Pythonistas, > > I'm looking for the best way to pass an arbitrary number and type of > variables created by one function to another. They can't be global > because they may have different values each time they are used in the > second function. > > So far I'm trying to do something like this: > > > def process_args( [list, of, command-line, arguments] ): If you are trying to process commandline args, I suggest you don't re- invent the wheel. Have a look at the two standard modules, optparse and getopt. Of the two, getopt is probably simpler to get started with, but optparse is more powerful. To answer your more general question, see below. > do stuff > return {dictionary : of, local : variables } > > def main_function( **kwargs ): > > do stuff > return result > > kw1 = process_args( [some, list] ) > kw2 = process_args( [a, different, list] ) > > for i in main_function( **kw1 ): > > kw2[ var1 ] = i > kw2[ var2 ] = len( i ) > > for j in main_function(**kw2): > > print j > > This only seems to work if I specify a default value for every possible > parameter of main_function and also for any others which may be passed > to it, which is a bit tedious because there are very many of them but > only a few are used in any given execution of the program. Er, yes. Presumably main_function actually does something. So it expects some arguments, and if the arguments aren't given, then it will fail. To prevent it failing when arguments aren't given, they must have default values. So define them, once, and be done with it: def main_function(a=1, b=2, c=3, d=4): dostuff return result Now this will work fine: result = main_function( **{'a': 22, 'd': 33} ) and b and c will take their default values and everything works well. Default values are a feature, not a problem to be solved. As for your nested for-loops (see above), I'm guessing that you're trying to copy items from one dictionary kw1 to another kw2, before processing kw2. You should check out the update method on dictionaries. Either of: kw2.update(kw1) kw1.update(kw2) will probably do the right thing, depending on which values you want to take priority in the case of clashes. If you need something even more flexible, write a small function to merge the two dicts in whatever way you want. Here's one example: def merge(kw1, kw2): """Merge dict kw1 to kw2 and return a new dict.""" new = kw2.copy() for key, value in kw1.items(): if key in kw2: # clash, keep the biggest value new[key] = max(value, kw2[key]) else: new[key] = value return new -- Steven From ronald.chis at googlemail.com Tue Sep 16 13:31:21 2008 From: ronald.chis at googlemail.com (ronald.chis) Date: Tue, 16 Sep 2008 10:31:21 -0700 (PDT) Subject: Iwebs v1.2 - Open Source Web-Publishing Platform for Bloggers and website builders available Now Message-ID: <80ad040d-3e23-4456-a656-0832f0b2d132@k13g2000hse.googlegroups.com> Iwebs v1.2 - Open Source Web-Publishing Platform for Bloggers and website builders available Now- (Sept 16-2008) With more updations iwebs version 1.2 can be downloaded here - http://webs.investorline.co.in/. Features The following is a list of some of the features that come standard with iwebs, however there are literally hundreds of plugins (on WordPress Site that can also be used with iwebs) that extend what iwebs does, so the actual functionality is nearly limitless. You are also free to do whatever you like with the iwebs code, extend it or modify in any way or use it for commercial projects without any licensing fees. That is the beauty of free software, free meaning not only price but also the freedom to have complete control over it. Key Features * Full standards compliance ? We have gone to great lengths to make sure every bit of iwebs generated code is in full compliance with the standards of the W3C. This is important not only for interoperability with today?s browser but also for forward compatibility with the tools of the next generation. Your web site is a beautiful thing, and you should demand nothing less. * No rebuilding ? Changes you make to your templates or entries are reflected immediately on your site, with no need for regenerating static pages. * Iwebs Pages ? Pages allow you to manage non-blog content easily, so for example you could have a static ?About? page that you manage through iwebs. For an idea of how powerful this is, the entire http://investorline.co.in site could be run off iwebs alone. * Iwebs Links ? Links allows you to create, maintain, and update any number of blogrolls through your administration interface. This is much faster than calling an external blogroll manager. * Themes ? Iwebs comes with 20 great looking themes designed by several professional designers, which makes designing everything from the simplest blog to the most complicated webzine a piece of cake, and you can even have multiple themes with totally different looks that you switch with a single click. Have a new design every day. You can even install more designs at http://webs.investorline.co.in. * Cross-blog communication tools? Iwebs fully supports both the Trackback and Pingback standards, and we are committed to supporting future standards as they develop. * Comments ? Visitors to your site can leave comments on individual entries, and through Trackback or Pingback can comment on their own site. You can enable or disable comments on a per-post basis. * Spam protection ? Iwebs comes with very robust tools such as an integrated blacklist and open proxy checker to manage and eliminate comment spam on your blog, and there is also a rich array of plugins that can take this functionality a step further. * Full user registration ? Iwebs has a built-in user registration system that (if you choose) can allow people to register and maintain profiles and leave authenticated comments on your blog. You can optionally close comments for non-registered users. There are also plugins that hide posts from lower level users * Password Protected Posts ? You can give passwords to individual posts to hide them from the public. You can also have private posts which are viewable only by their author. * Easy installation and upgrades ? Installing iwebs and upgrading from previous versions and other software is a piece of cake. Try it and you?ll wonder why all web software isn?t this easy. * Easy Importing ? We currently have importers for Movable Type, Textpattern, Greymatter, Blogger, and b2. Work on importers for Nucleus and pMachine are under way. * XML-RPC interface ? Iwebs currently supports an extended version of the Blogger API, MetaWeblog API, and finally the MovableType API. You can even use clients designed for other platforms like Zempt. * Workflow ? You can have types of users that can only post drafts, not publish to the front page. * Typographical niceties ? Iwebs uses the Texturize engine to intelligently convert plain ASCII into typographically correct XHTML entities. This includes quotes, apostrophes, ellipses, em and en dashes, multiplication symbols, and ampersands. For information about the proper use of such entities see Peter Sheerin?s article The Trouble With Em ?n En. * Intelligent text formatting ? If you?ve dealt with systems that convert new lines to line breaks before you know why they have a bad name: if you have any sort of HTML they butcher it by putting tags after every new line indiscriminately, breaking your formatting and validation. Our function for this intelligently avoids places where you already have breaks and block-level HTML tags, so you can leave it on without worrying about it breaking your code. * Multiple authors ? Iwebs? highly advanced user system allows up to 10 levels of users, with different levels having different (and configurable) privileges with regard to publishing, editing, options, and other users. * Bookmarklets ? Cross-browser bookmarklets make it easy to publish to your blog or add links to your blogroll with a minimum of effort. * Ping away ? Iwebs supports pinging Ping-O-Matic, which means maximum exposure for your blog to search engines. * Plugins- Iwebs comes bundles with 14 diffrent plugins which further enhances the capabilities of iwebs. To know more about the plugins that comes with standard installation visit plugins section. There?s much more, but these are the highlights. If there?s something that you really want, submit a request on the support forums and there?s a good chance someone will whip it up for you. Download it here - http://webs.investorline.co.in/ From fredrik at pythonware.com Thu Sep 4 16:42:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 22:42:28 +0200 Subject: why is self not passed to id()? In-Reply-To: <g9pg72$3vi$1@aioe.org> References: <g9pg72$3vi$1@aioe.org> Message-ID: <g9ph7l$ftb$1@ger.gmane.org> Ruediger wrote: > Executing following little program gives me an TypeError. > > What makes me wonder is that foo does get an argument passed while bar > doesn't. Can anyone explain why?????? >>> id <built-in function id> >>> lambda x: id(x) <function <lambda> at 0x00C07C30> any special reason why you're not using Python to write Python programs, btw? </F> From half.italian at gmail.com Thu Sep 11 14:43:21 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 11 Sep 2008 11:43:21 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <mailman.876.1221142791.3487.python-list@python.org> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> <mailman.880.1221152366.3487.python-list@python.org> <734ce614-3e92-4515-9342-d2e4e88c9632@b30g2000prf.googlegroups.com> Message-ID: <152effa1-1678-4bb1-85a0-a5340749d6a3@p10g2000prf.googlegroups.com> On Sep 11, 11:39?am, Sean DiZazzo <half.ital... at gmail.com> wrote: > On Sep 11, 9:59?am, Fredrik Lundh <fred... at pythonware.com> wrote: > > > > > carriere.jonat... at gmail.com wrote: > > > I want to build a desktop application. I am searching for some kind of > > > environment that would provide all the elements ready (Windows...). > > > Then I would have to code the business logic only. > > > start here: > > > ? ?http://wiki.python.org/moin/GuiProgramming > > > The big ones are Tkinter, which is usually bundled with Python; > > wxPython, and PyQt. ?There's also a trend towards using the web browser > > as a presentation engine also for local applications; for libraries that > > help you with that, you can start here: > > > ? ?http://wiki.python.org/moin/WebProgramming > > > or jump directly to > > > ? ?http://www.djangoproject.com/ > > > </F> > > I saw a message in the last few days showing how to use Flash as a > front end for Python apps. ?It looked interested. > > Can anyone point me to it? > > ~Sean Ahh...i see. It was the xml-rpc method you mentioned. Looks interesting to me if it's fairly responsive for normal gui apps. http://www.artima.com/weblogs/viewpost.jsp?thread=208528 ~Sean From robert.kern at gmail.com Tue Sep 23 15:53:13 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 14:53:13 -0500 Subject: Python is slow? In-Reply-To: <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> Message-ID: <gbbhf9$b84$1@ger.gmane.org> J Peyret wrote: > On Sep 23, 8:31 am, bearophileH... at lycos.com wrote: > > Guys, this looks like a great data structure/algo for something I am > working on. > > But... where do I find some definitions of the original BK-tree idea? Uh, actually we're talking about kd-trees, not BK-trees. kd-trees are for searching through point sets in a k-dimensional space. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From marco.bizzarri at gmail.com Wed Sep 10 09:19:11 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 10 Sep 2008 15:19:11 +0200 Subject: Adding further report options to unittest.py Message-ID: <3f0d61c40809100619i2631fb64p846dea0fea3f2051@mail.gmail.com> Hi all. I would like to change the way test reports are generated, in a Zope environment. I'm playing with TextTestReport, TextTestRunner. Since things are getting to complicated, I'm afraid I'm following a non-pythonic way. Specifically, I would like to have an output like: package.subpackage.test_module.TestCase 0.1 where 0.1 is the time spent into doing the test. In a previous attempt, I made the tests print the number of the test executed, so that I would have the following output: 1 package.subpackage.test_module.TestCase however, to do this, I had to put things in the following way: class PAFlowTestRunner(TextTestRunner): def _makeResult(self): return PAFlowTextResult(self.stream, self.descriptions, self.verbosity) class PAFlowTextResult(_TextTestResult): def startTest(self, test): self.stream.write("%s " % self.testsRun) _TextTestResult.startTest(self, test) now, of course, this is ugly, because I'm using _TextTestResult, which I'm not supposed to know, and I'm changing behaviour by subclassing, which is not exactly what I would like to do. What is the pythonic way to accomplish this? Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From prologic at shortcircuit.net.au Sun Sep 7 18:06:18 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 08:06:18 +1000 Subject: Updating python dictionary In-Reply-To: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <e1a84d570809071506k22a48650q2c4e1af372311e4f@mail.gmail.com> Hi, There is "never" a "clever" way of doing anything, but: $ cat test.py MAPPING_DICT = {'a': 'A','b': 'B',} my_dict = {'a': '1','b': '2'} my_dict = dict((MAPPING_DICT[k], my_dict[k]) for k in my_dict) print my_dict $ python test.py {'A': '1', 'B': '2'} $ That should do the trick. cheers James On Mon, Sep 8, 2008 at 7:51 AM, andyhume at gmail.com <andyhume at gmail.com> wrote: > Hello... > > I have a dict of key/values and I want to change the keys in it, based > on another mapping dictionary. An example follows: > > MAPPING_DICT = { > 'a': 'A', > 'b': 'B', > } > > my_dict = { > 'a': '1', > 'b': '2' > } > > I want the finished my_dict to look like: > > my_dict = { > 'A': '1', > 'B': '2' > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? > > Cheers, > Andy. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Fri Sep 26 15:28:39 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 26 Sep 2008 15:28:39 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Message-ID: <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> On Fri, Sep 26, 2008 at 3:04 PM, Michael Mabin <d3vvnull at gmail.com> wrote: > Doesn't it depend on where and why you intend to execute the code? > Obviously some SQL is more at risk for exploit when the input is from the > screen on a web page than if you were running parameterized code in a > controlled batch environment. Or if you were writing code generators (which > is what I happen to do) which won't be run by the general public. > > Incidentally, couldn't input field edits prevent such exploits prior to > interpolation? > There are ways to avoid SQL injection attacks, such as escaping all quotes in the text. We were simply pointing out that you have to be very careful when you add arbitrary strings into SQL statements. If you control everything going into the statement, you shouldn't have to worry about this. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/3908055f/attachment.html> From castironpi at gmail.com Sun Sep 14 12:10:07 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 14 Sep 2008 09:10:07 -0700 (PDT) Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> Message-ID: <f38eddfe-ca5a-4595-b898-e7ca70119f83@d1g2000hsg.googlegroups.com> On Sep 14, 4:43?am, Arnaud Delobelle <arno... at googlemail.com> wrote: > On Sep 14, 10:29?am, Steven D'Aprano <st... at REMOVE-THIS- > > > > cybersource.com.au> wrote: > > I have a function that needs a reference to the module object it is > > defined in. (For the reason why, if you care, see the thread "doctest not > > seeing any of my doc tests" from a week ago.) I know of two ways to deal > > with this problem, both of which feel unsatisfactory to me. Assume the > > name of the module is "Mod", then I can do either of these: > > > def foo(): > > ? ? import Mod > > ? ? process(Mod) > > > Disadvantage: If I change the name of the module, I have to remember to > > change the name of the module reference in foo() twice. > > > def foo(): > > ? ? modname = foo.__module__ > > ? ? module = __import__(modname) > > ? ? process(module) > > > Disadvantage: if I change the name of the function, I have to remember to > > change the reference to itself, but at least both changes are right next > > to each other. > > > Assume that changing the function name or the module name are both > > equally likely/unlikely. > > > Which do other people prefer? Which seems "better" to you? Are there any > > other alternatives? > > What about something like: > > ? ? sys.modules[__name__] ? > > -- > Arnaud You're just worried about changing the module's name in the future. So use a global variable or function that you only have to change once. def Mod_mod( ): import Mod as Mod #<-- only one change needed return Mod def foo( ): process( Mod_mod( ) ) From maric at aristote.info Mon Sep 15 07:29:45 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 13:29:45 +0200 Subject: how to protect the source In-Reply-To: <BLU115-W513E8E918A8A16CEB298E596520@phx.gbl> References: <BLU115-W513E8E918A8A16CEB298E596520@phx.gbl> Message-ID: <200809151329.45811.maric@aristote.info> Le Monday 15 September 2008 13:02:58 Jo?o Abrantes, vous avez ?crit?: > Hello Everyone. > Hello, > > I am building a client in python that will connect himself to a mysql > server with a certain username and password. I will compile this client > and turn him into a .exe . The thing is that I know that is possible to > get the source of the code back from an .exe and I don't want anyone to > know which username and password are they using because I don't want > them to access to the mysql server without my client. Do you have any > ideas of what can i do? Thanks! You're going on the wrong path. It's far easier to sniff the network traffic to get the password than to decompile the program. Furthermore you can't achieve good security this way (games vendors try hard to do this but are always defeated). You can't hope to gain control on what your users do with the access you gave them. So, the right thing to do is to only allow on the database server the operations your client app needs given the account you created specifically for it. -- _____________ Maric Michaud From hussainsaiger at gmail.com Mon Sep 1 02:42:25 2008 From: hussainsaiger at gmail.com (hussainsaiger at gmail.com) Date: Sun, 31 Aug 2008 23:42:25 -0700 (PDT) Subject: Using NLTK in Java Message-ID: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> I am trying to convert a python module (that contains the use of NLTK.Corpus) by jythonc. It is not able to include nltk dependencies within the java class it creates. So when i use this class in java, it fails to recognize nltk. Can anyone please let me know how should i use nltk in python/jython modules so i can use in Java. From adityashukla1983 at gmail.com Thu Sep 11 04:39:40 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 11 Sep 2008 03:39:40 -0500 Subject: Adding environment variables to bash. Message-ID: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> Hello folks Can i add any environment variable to bash from my python script? so that when i use env command then i can see that environment variable. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080911/6a2634a8/attachment.html> From steve at REMOVE-THIS-cybersource.com.au Tue Sep 9 18:58:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Sep 2008 22:58:01 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> Message-ID: <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> On Tue, 09 Sep 2008 14:59:19 -0700, castironpi wrote: > I will try my idea again. I want to talk to people about a module I > want to write and I will take the time to explain it. I think it's a > "cool idea" that a lot of people, forgiving the slang, could benefit > from. What are its flaws? [snip long description with not-very-credible use-cases] You've created a solution to a problem which (probably) only affects a very small number of people, at least judging by your use-cases. Who has a 4GB XML file, and how much crack did they smoke? Castironpi, what do *you* use this proof-of-concept module for? Don't bother tell us what you think *we* should use it for. Tell us what you're using it for, or at least what somebody else is using it for. If this is just a module that you think will be cool, I don't like your chances of people caring. There is no shortage of "cool" software that isn't useful for anything, and unlike eye-candy, nobody is going to use your module just because they like the algorithm. If you don't have an existing application for the software, then explain what it does (not how) and give some idea of the performance ("it's alpha and written in Python and really slow, but I will re-write it in C and expect it to make a billion random accesses in a 10GB file per millisecond", or whatever). You might be lucky and have somebody say "Hey, that's just the tool I need to solve my problem!". -- Steven From tim_grove at sil.org Tue Sep 2 17:08:50 2008 From: tim_grove at sil.org (Tim Grove) Date: Tue, 02 Sep 2008 22:08:50 +0100 Subject: [cairo] Rendering SVG with libRSVG,Python ... CTYPES SUCCESS AT LAST!!! In-Reply-To: <91882ea90809021242y2c6e8606o621951cfd8f252e1@mail.gmail.com> References: <48BD76B0.8050205@sil.org> <91882ea90809021242y2c6e8606o621951cfd8f252e1@mail.gmail.com> Message-ID: <48BDAB62.20300@sil.org> Thanks for your advice Gerdus, but I have tried your suggestion with no success. It has at least been beneficial to discover a tool which I did not know about in 'Dependency Walker'; all dependencies appear okay. HOWEVER (!!!) I HAVE JUST HAD SUCCESS IN LOADING THE DLL !!! In searching through my 'C:WINDOWS\system32' directory I discovered a subdirectory named 'rsvg' containing a number of .dll's associated with that library, including the ones I was attempting to load. I'm not certain how it got there; I probably added it myself sometime in the last couple of weeks in a vain attempt to solve the problem. In any case, that directory seems to have been the root of my problems causing some path conflicts, since when I deleted it my code ran fine! At last, "l = CDLL('librsvg-2-2.dll')" works! Now to give the rest of your solution a try... Best regards, Tim Gerdus van Zyl wrote: > I created that ctypes recipe since there is no binary for win32. > The python binding for librsvg is part of gnome-python-desktop and as > such you need > a gtk build env which is pretty much impossible to get working. Plus > the build system uses codegen/magic/amuletyendor so I can't even hand > compile it. But if you have some linux development experience (I > don't) you might get it working that way. > > On the ctypes problem from the ctypes list: Try putting all the dll > files in the same directory as the script and then using Dependency > Walker to ensure it's finding the dll dependencies in that directory. > > ~Gerdus > > On Tue, Sep 2, 2008 at 7:24 PM, Tim Grove <tim_grove at sil.org> wrote: > >> In the recipe found at >> http://www.cairographics.org/cookbook/librsvgpython/, the intro reads: >> >> "Normally it's easier to use librsvg Python bindings from PyGTK, so you >> can import rsvg. When that's not an option, you may be able to bind just >> enough of it using the ctypes module to use it. Example for win32 follows." >> >> I've been having trouble getting the actual recipe for ctypes working >> (another story - visit the ctypes mailing list!!!), but I'm looking for >> advice on how to get my pc setup (Windows XP Pro) so that I can use >> "import rsvg" in my python program, as suggested by the intro. Can >> anyone help? >> >> Tim >> _______________________________________________ >> cairo mailing list >> cairo at cairographics.org >> http://lists.cairographics.org/mailman/listinfo/cairo >> >> > _______________________________________________ > cairo mailing list > cairo at cairographics.org > http://lists.cairographics.org/mailman/listinfo/cairo > > From bj_666 at gmx.net Tue Sep 30 01:54:03 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Sep 2008 05:54:03 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <affd6918-3444-4a8f-9816-faa56ee34512@k37g2000hsf.googlegroups.com> <q1r2e458kqe2t7phvj5iorgj0tbnbi7ikb@4ax.com> <6d265f36-352c-4866-bf91-c14d26101fc2@k37g2000hsf.googlegroups.com> <ku03e4pddv9fbshgkbpbfv2hrg3u1p1i6h@4ax.com> Message-ID: <6kdt7rF7dmkkU1@mid.uni-berlin.de> On Tue, 30 Sep 2008 03:56:03 +0200, Ivan Reborin wrote: > a = 2.000001 > b = 123456.789 > c = 1234.0001 > d = 98765.4321 > # same as above except for d > > print (3 * '%12.3f') % (a, b, c) > #this works beautifully > > How to add d at the end but with a different format now, since I've > "used" the "format part" ? > > Again, my weird wishful-thinking code: print (3*'%12.3f', '%5.3f') > %(a,b,c),d Maybe you should stop that wishful thinking and programming by accident and start actually thinking about what the code does, then it's easy to construct something working yourself. The ``%`` operator on strings expects a string on the left with format strings in it and a tuple with objects to replace the format strings with. So you want '%12.3f%12.3f%12.3f%5.3f' % (a, b, c, d) But without repeating the '%12.3f' literally. So you must construct that string dynamically by repeating the '%12.3f' and adding the '%5.3f': In [27]: 3 * '%12.3f' Out[27]: '%12.3f%12.3f%12.3f' In [28]: 3 * '%12.3f' + '%5.3f' Out[28]: '%12.3f%12.3f%12.3f%5.3f' Now you can use the ``%`` operator on that string: In [29]: (3 * '%12.3f' + '%5.3f') % (a, b, c, d) Out[29]: ' 2.000 123456.789 1234.00098765.432' (I guess there should be at least a space before the last format string.) This time you *have* to put parenthesis around the construction of the format string BTW because ``%`` has a higher priority than ``+``. So implicit parentheses look like this: 3 * '%12.3f' + '%5.3f' % (a, b, c, d) <=> 3 * '%12.3f' + ('%5.3f' % (a, b, c, d)) And there are of course not enough formatting place holders for four objects in '%5.3f'. It's also important to learn why your wrong codes fail. In your wishful thinking example you will get a `TypeError` saying "unsupported operand type(s) for %: 'tuple' and 'tuple'". That's because on the left side of the ``%`` operator you wrote a tuple: In [34]: (3 * '%12.3f', '%5.3f') Out[34]: ('%12.3f%12.3f%12.3f', '%5.3f') Ciao, Marc 'BlackJack' Rintsch From gminick at bzt.bzt Thu Sep 11 08:43:20 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 11 Sep 2008 12:43:20 +0000 (UTC) Subject: how dump a program which is running in memory References: <0592abb3-c2f6-4977-8338-3aa1956a353c@b38g2000prf.googlegroups.com> Message-ID: <gab3p7$snu$1@inews.gazeta.pl> On Thu, 11 Sep 2008 02:31:23 -0700 (PDT), ruqiang826 wrote: > I have written a service running backgroud to do something in linux. > unfortunately$B!$(BI deleted the source code by mistake, and I can still > see the process running background using "ps aux" : > > username 13820 0.0 0.0 60368 2964 ? S Aug20 0:33 > python ./UpdateJobStatus.py > > > I wonder if there is some way to dump the programme > "UpdateJobStatus.py" and get the source code back? The best way to do it would be to undelete the file, just as Gerhard suggested. If you remember any line (or piece) of code from the UpdateJobStatus.py file you can try to dump the /dev/mem to the hard disk, and then grep through it (remember that you need root priviledges to access /dev/mem). I tried it with this code: http://www.mail-archive.com/linuxbios at listman.lanl.gov/msg03696.html with a small modification of this line: nvram = (strtol(argv[1], 0, 0)) << 16; changed to: nvram = (strtol(argv[1], 0, 0)); After compilation I just did: ./a.out 0x0 0xffffffff > memdump to get the memory dump. I am not a memory expert, but 0xffffffff should be enough for <= 4GB of RAM. If you got more, increase it. And to make it clear: I do not recommend this way of sorting things out :) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bedouglas at earthlink.net Mon Sep 1 23:36:59 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 1 Sep 2008 20:36:59 -0700 Subject: python mechanize/libxml2dom question Message-ID: <108c01c90cad$28dd5840$0301a8c0@tmesa.com> hi... i've got the following situation, with the following test url: "http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#". i can generate a list of the tables i want for the courses on the page. however, when i try to create the xpath query, and plug it into the xpath within python, i'm missing something. if i have a parent xpath query, that generates a list of results/nodes... how can i then use the individual parent node, and trigger off of it, to get further information. i tried using the following chunk of code with no luck. #s is the html from the course file d = libxml2dom.parseString(s, html=1) #at this point, we should have a vaild "d" representation print "sdddd=",s aa=libxml2dom.toString(d) print "hereeeeee \n\n\n" print "aa",aa #sys.exit() # **** course names cpath='//table[position()>0]/descendant::td[position()=2][@width="85%"]/../t d[1]/font/a[2]/text()' cpath_=[] cpath_=d.xpath(cpath) print "len=",len(cpath_) if len(cpath_)>0: for cpath in cpath_: #get the coursename info cname=cpath.toString() print "cpath=",cpath print "cname=",cname rr="./../../../../../../following-sibling::table//tr[position()>1]" rr=cpath.xpath() print "rrlen=",len(rr) print rr[0].toString() sys.exit() i'm assuming that there's a libxml2node method that will do what i need that i'm missing... pointers/comments would be helpful here... thanks! From tjreedy at udel.edu Sun Sep 28 15:17:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 15:17:19 -0400 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <gbol7v$3ra$1@ger.gmane.org> process wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. Feel free to ignore it if you wish. > What is not an object in Python? Depends on what you mean by 'in'. Python is a language for defining and manipulating information objects. Code 'in' Python is not usually a maniputed object, though is can be (by eval, exec, and compile, for instance). Names in code that are only used to directly access objects typically are also, typically, not objects themselves. > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? Partly history and partly practicality. Len is implemented as .__len__ ;-). The len function is one, __len__ methods are many. If you want to pass an argument to a function, passing len is easier that passing operator.attrgetter('__len__'). Passing '__len__' (or 'len') would be easy, but using len is easier than using getattr(ob,'__len__'). tjr From gherlylukita at gmail.com Wed Sep 24 15:47:51 2008 From: gherlylukita at gmail.com (gherlylu) Date: Wed, 24 Sep 2008 12:47:51 -0700 (PDT) Subject: online pharmacy perscription.dt8v1 Message-ID: <ecf4b19b-2d74-46dc-b673-abe35f349c36@m45g2000hsb.googlegroups.com> Start saving, best online pharmacy here http://defgjkmahl.nufehrurald.net/?bciahlxwvrsydefgjkzchcmm From bearophileHUGS at lycos.com Thu Sep 18 13:04:37 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 18 Sep 2008 10:04:37 -0700 (PDT) Subject: Cython dynamic library problem References: <mailman.1216.1221749258.3487.python-list@python.org> <8763otl8ea.fsf@merkury.smsnet.pl> Message-ID: <f1b25309-9064-484d-9e29-bbdd3c8e2b68@8g2000hse.googlegroups.com> Rob Wolfe: > # setup.py > from distutils.core import setup > from distutils.extension import Extension > from Cython.Distutils import build_ext as build_pyx > > setup(name = 'pyx_test', > ext_modules=[Extension('pyx_test', ['test_cython.pyx'])], > cmdclass = { 'build_ext': build_pyx }) > > $ python2.5 setup.py build_ext -i > running build_ext > cythoning test_cython.pyx to test_cython.c > building 'pyx_test' extension > creating build/temp.linux-i686-2.5 > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.5 -c test_cython.c -o build/temp.linux-i686-2.5/test_cython.o > test_cython.c:86: warning: function declaration isn?t a prototype > test_cython.c:241: warning: function declaration isn?t a prototype > test_cython.c:59: warning: ?__pyx_skip_dispatch? defined but not used > gcc -pthread -shared -Wl,-O1 build/temp.linux-i686-2.5/test_cython.o -o pyx_test.so > $ python2.5 test_cython.py > 0 > 100 With some intelligence added to Cython, probably there are ways to reduce all this, and most of the times avoid any setup.py module too. Bye, bearophile From almar.klein at gmail.com Thu Sep 25 10:53:17 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 25 Sep 2008 16:53:17 +0200 Subject: matplotlib in interactive mode locks when run from subprocess In-Reply-To: <cc38d75f0809201312u6bfc5f0awfd18b307aa421ce@mail.gmail.com> References: <cc38d75f0809180713r5ae45167xc0c52c5557e63381@mail.gmail.com> <cc38d75f0809201312u6bfc5f0awfd18b307aa421ce@mail.gmail.com> Message-ID: <cc38d75f0809250753w7588cb96p424c1af487b632c5@mail.gmail.com> To who cares, I found out what my problem was. Testing interactivity with Tk in a normal Python console gave proper results, just like IPython. Also running "python -i" gives the interactive behaviour I wanted. But running "python -i" from a subprocess did not. I was startled, because it worked out of the box with Python! I read somewhere that Tkinter does not need a mainloop, which should be true in order to have the interactive behaviour in python without a second thread. Well, tk does indeed not need a mainloop, but you DO need to create a tk app and call update() on it from time to time. (Which makes sense now that I know it :) ) After examing code from IPython, I saw that it runs code to start a Tk app, and performs tk.update(). So I guess this means that the standard python shell creates such a "hidden tk app", but NOT when run from a subprocess. I have now solved my problem, and interactivity works! Almar 2008/9/20 Almar Klein <almar.klein at gmail.com> > I think my question was not very clear. I narrowed the problem down to > a reconstructable small example, consisting of a python script (a very > simple interpreter) and three lines to execute in it: > > ========== start simple interpreter file ====== > import os > import sys > import time > > def run(): > while True: > > # read a line of text, the thread is stuck here untill a \n is > # fed to the stream. > time.sleep(0.1) > line = "" > try: > line = sys.stdin.readline() > except Exception, why: > sys.stdout.wite(why.message+"\n") > > if line: > try: > code = compile(line,"<none>","exec") > exec(code) > except Exception, why: > sys.stderr.write(why.message) > sys.stderr.write(">>> ") > > if __name__ == "__main__": > run() > > ========== end of file ============== > > Now I run this file (by double clicking it) and I get a prompt. The three > lines I type in are: > import matplotlib.pylab as pl > pl.ion() #interactive mode on > pl.plot([1,2,3],[4,6,5]) > > This produces a tk window, but it's unresponsive. The process does have 5 > threads, so > matplotlib managed to create the threads, but it seems as if they're > blocked. > > When I run the three lines of code in a normal python shell, I get the > proper results: > a responsive figure (I can zoom and pan) and my shell is still responsive > too. > > I am in the dark why this does not work. Any thoughts anyone? I've been > busy all day > trying to get this right, with hardly any progress... :( > > Almar > > PS: I run windows xp, my matplotlibrc file has the backend: TkAgg, > interactive: True > > > 2008/9/18 Almar Klein <almar.klein at gmail.com> > > Hi, >> >> In wxpython, I made an interactive shell, which creates a remote python >> subprocess >> to do the interpreting. Communication is done via a pipe. The idea is that >> the python >> session is an actual process separate from the GUI, which has some >> advantages, >> like I can have multiple such shells in my application, and I can kill >> them without >> worrying that my wx app will crash. >> >> To do this I use the wx.Process class, which allows asynchronous >> communication with >> the remote process. >> >> This all works really, I will also launch wxpython apps. So I was quite >> happy, untill I tried >> doing some plotting with matplotlib (in TkAgg backend). The problem is >> that the process >> becomes unresponsive when I plot something (No prompt is written to the >> stdout/stderr). >> (more details below) >> >> I don't know much about creating subprocess and how they are different >> from a normal >> process. So can anyone offer some help as to what the problem might be? >> >> Thanks in advance, >> Almar >> >> To get to the details: >> - When I start a process with command "python -u -i" >> -- When interactive mode is off, the whole process becomes unresponsive >> when doing >> pylab.show() >> -- When interactive mode in on, on doing pylab.plot(), a figure appears, >> which I can >> zoom etc., but the process is now stuck, also after closing the figure >> >> - When I start a process with command >> "python -u -c 'import code;code.interact(readfunc=raw_input)'" (This is >> how Pype does it). >> -- When interactive mode is off, the figures show when doing >> pylab.show() and the process >> behaves as normal after closing the figure(s). >> -- When interactive mode in on, on doing pylab.plot(), a figure appears, >> but most of the time >> it is not drawn and emmediately unresponsive, just like the process >> itself. >> >> I have also tried an asynchronous Popen recipe by Joshiah Carlson I found >> on >> activestate. And I made my own process class using >> win32process.CreateProcess. >> Both alternatives to wx.Process resulted in the same sympoms. >> >> Oh, and I run windows. >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080925/59796bde/attachment.html> From siona at chiark.greenend.org.uk Mon Sep 22 07:32:04 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 22 Sep 2008 12:32:04 +0100 (BST) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: <ugv*ncEns@news.chiark.greenend.org.uk> josh logan <dear.jay.logan at gmail.com> wrote: >sorted(P) # throws TypeError: unorderable types Player() < Player() > >The sorted function works when I define __lt__. >I must be misreading the documentation, because I read for the >documentation __cmp__ that it is called if none of the other rich >comparison functions are defined. You're either misreading or forgetting that __eq__ and __ne__, which you define, are rich comparison functions. __cmp__ will only be called for a comparison when *none* of the rich comparison functions are defined, not just the one in question. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From tjreedy at udel.edu Tue Sep 2 22:37:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 02 Sep 2008 22:37:25 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <20080902235412.GT29228@dragontoe.org> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> <mailman.390.1220393719.3487.python-list@python.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> Message-ID: <g9kt94$12p$1@ger.gmane.org> Derek Martin wrote: > On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: > >> It's a way more self explaining name, even for people who know the >> `popen()` function > > I, and apparently the maintainers (at least at the time they added > this thing) don't agree. In fact I think it's quite the opposite. If > I came across such a "process" object without knowing what it was, I > would expect that a process object described a running process, i.e. > gave information about things like executable path name, cpu and > memory utilization, perhaps a list of all open file descriptors (but > not just three specific ones), etc; or something similar. This object > provides none of that. It does not, in fact, describe a process at > all. It is quite distinct and different from the concept of a > process, indeed. > >> because there's a concept called "process" but none called "popen". > > Anything that exists can be conceptualized and therefore is a concept. > The popen concept exists, and is more than just a concept; it has a > concrete implementation in C AND Python and numerous other languages. > Verbs can be concepts too. In this case, at least, I think of the module name as part of the total class name. subprocess.Popen == open pipes to a subprocess -- and return a structure that lets me use the pipes and monitor the process. So as a practical matter, I am okay with the name even if I theoretically agree with the guideline as a guideline. tjr From lists at cheimes.de Wed Sep 10 20:53:01 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 11 Sep 2008 02:53:01 +0200 Subject: Working with environment variables. In-Reply-To: <73045cca0809101739m560d382bi8ba506022f600286@mail.gmail.com> References: <73045cca0809101739m560d382bi8ba506022f600286@mail.gmail.com> Message-ID: <ga9q5b$8on$1@ger.gmane.org> aditya shukla wrote: > now this dosen't change the value of the variable which was set earlier > .Please help me in fixing this issue. Are you trying to modify or add an environment var so the change is visible from the calling shell? That's not possible. You can't change the env var of a parent process. Christian From uzmanajmal at gmail.com Fri Sep 12 14:39:00 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Fri, 12 Sep 2008 23:39:00 +0500 Subject: Need help with the 'transport' for setting the header while calling a function at server side Message-ID: <a3158e8b0809121139v3d7137e1r908f8414fbb25b10@mail.gmail.com> I am getting an Internal Server Error 500 when i run my client code. I am trying to call a function at the server side which for now only returns a string. Meanwhile this calling i also set the header of HTTP request. Following are my client and server code. Am i doing something wrong? #-----------------------Server code----------------------------- import SimpleXMLRPCServer class AuthenticationFunctions: def system_auth(self): # No need to print here if you are going to print it at the client side. Return it instead. return "something..." server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(AuthenticationFunctions()) server.serve_forever() #-----------------------Client code----------------------------- import sha,random, os, time, sha, quopri, xmlrpclib class SecureTransport(xmlrpclib.Transport): def set_authorization(self, ustring, text_ucert): self.authorization = quopri.encodestring("%s:%s" % (ustring,text_ucert)) def send_request(self, connection, handler, request_body): connection.putrequest("POST", handler) connection.putheader("Authorization","Basic %s" % self.authorization) def caller(): #Opening file named newcert.pem in which certificate generated via openssl command is placed infile = open('newcert.pem', "r+") if infile: text_ucert = infile.read() infile.close() #Generating a random string random.seed(); ustring_raw="%s_%f_%f"%(os.getpid(),time.time(),random.random()) #For calculating the hash of some arbitrary message hashValue = sha.new() hashValue.update("(.2).ch^kjdw*()!hjsu7 at hsue @!jssljdu2837.kd'lsid4vhwoi3821@#1azzZ3234202J83&") #Updating the hash with the previously generated random string hashValue.update(ustring_raw) ustring = quopri.encodestring(hashValue.digest()) #Instantiating the transport t = SecureTransport() t.set_authorization(ustring, text_ucert) server = xmlrpclib.Server('http://localhost:8000',transport=t) #Calling some arbitrary function at server side print server.system_auth() caller() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080912/469a2dd6/attachment.html> From dmitry at athabascau.ca Thu Sep 25 17:30:19 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 21:30:19 GMT Subject: Eggs, VirtualEnv, and Apt - best practices? References: <mailman.1506.1222370612.3487.python-list@python.org> <QQRCk.1802$Pv5.235@edtnps83> <6k2aqqF5p185U1@mid.uni-berlin.de> <qNSCk.1824$Pv5.181@edtnps83> <6k2c5pF5oenoU1@mid.uni-berlin.de> Message-ID: <LpTCk.1833$Pv5.1470@edtnps83> Diez B. Roggisch wrote: > Well, you certainly want a desktop-orientied Linux for users, so you > chose ubuntu - but then on the server you go with a more stable debian > system. Even though the both have the same technical and even package > management-base, they are still incompatible wrt to package versions for > python. > > And other constraints such as Photoshop not being available for Linux > can complicate things further. actually I had in mind X11 sessions forwarded from server to desktop - all development tools and libraries are on server, and all unrelated packages (like Photoshop etc.) are on desktop. >> that definitely becomes tricky however not impossible to track. You do >> need a common snapshot for all developers to use anyway - so why not just >> package it up? > > I do, but based on Python eggs. They are platform independent (at > ultimo, you can use the source distribution, albeit that sux for windows > most of the time), and as I explained in my other post - things are > moving in the right direction. /I'll play devil's advocate here even though I see your point/ how do you deal with non-pythonic dependencies then? surely you don't package ImageMagic into an egg ;) > Don't get me wrong - I love .deb-based systems. But if using them for my > development means that I have to essentially create a full zoo of > various packages *nobody else* uses - I rather stick with what's working > for me. Looks like if you package and make those available you'll have quite a few people using them. I've seen people looking for pre-packaged python libs just to stick to OS package management tools. :) Eggs and debs are not silver-bullet for *any* scenario, so you'd have to weight what can you get out of either one against what are you going to sacrifice. In my case I know all our systems (servers) run same OS, however developers don't. So I provide them with environment on devel/testing servers that they can use as a primary development environment or develop on their own boxes (which means they are on their own hunting dependencies/packages/etc.) but testing before moving forward they still have to test it on "certified" server. And I don't suggest that everybody should run *this* type of environment - it just works better in our case. From tjreedy at udel.edu Mon Sep 22 14:36:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 14:36:03 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> Message-ID: <gb8oi9$1iu$1@ger.gmane.org> Steven D'Aprano wrote: > > Consider a factory function: > > def factory(x): # a toy example > alist = [x] > def foo(): > return alist > return foo > > > Now suppose we "instantiate" the factory (for lack of a better term): > >>>> f1 = factory(0) >>>> f2 = factory(0) Your factory is returning closures. This is the functional equivalent of a class returning instances. class factory(object): def __init__(self, x): self.alist = [x] def __call__(self): return self.alist > Even though f1 and f2 have the same behaviour, they are obviously not the > same object. And although both return a list [0], it is not the same list: > >>>> f1() == f2() == [0] > True >>>> f1() is f2() > False same results > They have a (very little) amount of state, which is *not* shared: > >>>> L = f1() >>>> L.append(1) >>>> f1() > [0, 1] >>>> f2() > [0] same results > But there's only a limited amount of state that functions carry around. That is why Python has class statements. > And instances share at least some state, by virtue of having the same class. If the only class attributes are methods and you do mutate the class, then the fact that f1.__class__ is f2.__class__ is not really shared state. [from a later post] >But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. Unless you can show how sharing an immutable __class__ attribute is an actual impediment, this strike me as artificial pedantry and unnecessary self handcuffing. And you obviously can make that attribute effectively immutable by ignoring it and also not changing the class itself. It is just internal, implementation-defined bookkeeping. The identity of immutable objects is irrelevant. If part of your 'unshared state' for each instance were a string, and two instances happened to have the same string value, would you be upset because the interpreter happened to use the same string object instead of two string objects with the same value? Ditto for numbers, tuples, and so on. Terry Jan Reedy From ricaraoz at gmail.com Mon Sep 22 10:36:18 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 22 Sep 2008 11:36:18 -0300 Subject: Not fully OO ? In-Reply-To: <8d30318b-2c54-4d4e-b333-016a0806c1ad@y38g2000hsy.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> <2c0a8279-e888-4ae5-90a2-f2f1bb137607@x41g2000hsb.googlegroups.com> <8d30318b-2c54-4d4e-b333-016a0806c1ad@y38g2000hsy.googlegroups.com> Message-ID: <48D7AD62.2090503@bigfoot.com> Kay Schluehr wrote: > On 20 Sep., 23:07, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> > wrote: >> On Sep 20, 3:22 pm, Kay Schluehr <kay.schlu... at gmx.net> wrote: >> >> >> >>> On 20 Sep., 18:33, Bruno Desthuilliers >>> <bdesth.quelquech... at free.quelquepart.fr> wrote: >>>> The following definitions are AFAIK the only commonly accepted >>>> definitions about OO: >>>> 1/ an object is defined by identity, state and behaviour >>>> 2/ objects interacts by sending messages each other >>>> 3/ an OO program is made of interacting objects >>>> I let you find out whether Python meets these 3 definitions - and if >>>> Java does (hint : in Python, everything you can bind to a name is an >>>> object - this is not true in Java or C++). >>> This is correct but it detracts from a more general problem of >>> language "paradigms". >>> Assume you type >>>>>> 2+2 >>> 4 >>> Now you are free to interpret this as a simple, primitive arithmetic >>> operation but you can also claim that 2 sends an __add__ message to 2. >>> Hereby the state of the 2 objects are not altered but a new 4 object >>> is created. OO babble is more impressive isn't it? >>> Actually it is simply wrong in the mentioned case and here is the >>> proof: >>> def foo(): >>> return 2+2 >>> import dis >>> dis.dis(foo) >>> 2 0 LOAD_CONST 2 (4) >>> 3 RETURN_VALUE >>> OO is a heuristic method used to understand the semantics of a >>> programming language. It can also inspire language design but as >>> you've rightly said: jugde yourself and see how far you get with it. >>> Applying OO on interpreter level is by no means a sign of a high >>> quality implementation whereas structuring programs in the large will >>> likely benefit from class based organization and encapsulation. Of >>> course one can also reverse the value hierarchy and find perverse joy >>> in having a pure OO language but apply monkey patching everywhere. I >>> suppose you know which language I'm talking about... >> It sounds like you think that you -can- write OO programs in Python, >> but you don't have to. I agree. > > The whole point of OO is providing high level ( system level ) not low > level ( interpreter level ) semantics. Partitioning a system into > isolated and communicating objects is a strong and important metaphor. > Recently there were some comments on the web that mentioned Erlang to > be pretty much OO in this respect although Erlang is functional and > has no base level notion of an "object". It's even well known that Joe > Armstrong holds low opinions about the entire object business. > > Notice that I believe that the popular meme that OO is "bolted on" > Python has little if nothing to do with OO itself but with API > consistency. When people have to type len(x) instead of x.len() this > breaks their expectations on how the language has to behave. x.__len__() From enleverlesX.XmcX at XmclaveauX.com Sat Sep 27 02:59:20 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 27 Sep 2008 08:59:20 +0200 Subject: how to search multiple textfiles ? (Python is slow ?) In-Reply-To: <mailman.1566.1222464403.3487.python-list@python.org> References: <mailman.1536.1222436146.3487.python-list@python.org><17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> <mailman.1566.1222464403.3487.python-list@python.org> Message-ID: <48ddda41$0$920$ba4acef3@news.orange.fr> Hi ! Thanks for return. Some infos: from a long time, I found that it's often more fast to use windows's command, instead of develop in high level language (and also, low level...) FINDSTR is fast. OK. But internal commands are more fast. Example : DIR (with all his options) And it's faster to read the result via a Pipe. Thus, I use frequently this sort of function: import os def cmdone(repstart, commande, moderetour="LIST"): os.chdir(repstart) sret=''.join(os.popen(commande)) if moderetour.upper() == "STR": return sret else: return sret.split('\n') print cmdone('D:\\dev\\python','findstr /N /I ponx *.py','STR') print print cmdone('D:\\dev\\python','dir *.jpg /B') Sorry for my bad english, and have a good day... -- Michel Claveau From giltay at gmail.com Tue Sep 30 13:40:10 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Tue, 30 Sep 2008 10:40:10 -0700 (PDT) Subject: OS.SYSTEM ERROR !!! References: <mailman.1759.1222795317.3487.python-list@python.org> Message-ID: <402462d4-e2a6-493b-9bc9-52aab68cad96@y71g2000hsa.googlegroups.com> On Sep 30, 1:21?pm, "Blubaugh, David A." <dbluba... at belcan.com> wrote: > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 [snip] > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") [snip] > ERROR opening inputs/io/control.dat [snip] I would add the following line right before your call to os.system: os.chdir(r'C:\myprogramfolder\run') If you have to change directories to run it properly in the Windows shell, then you need to do it in Python, too. HTH, Geoff G-T From deets at nospam.web.de Mon Sep 15 17:59:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 23:59:12 +0200 Subject: conditional install/distribution In-Reply-To: <3f8893c3-fd23-4734-a2d4-07921be67202@z11g2000prl.googlegroups.com> References: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> <6it533Fe2h8U1@mid.uni-berlin.de> <3f8893c3-fd23-4734-a2d4-07921be67202@z11g2000prl.googlegroups.com> Message-ID: <6j845gF1tnd6U1@mid.uni-berlin.de> i3dmaster schrieb: > On Sep 11, 11:07 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote: >> i3dmasterschrieb: >> >>> Is there a feature in distutils or easy_install to specify what >>> version of python that the target package can be installed? For >>> example, if a package has a module that only needed if the python >>> version < 2.6, is there a way to specifiy that in setup.py or >>> easy_install cfg file so that when installing to python >= 2.6, this >>> module wouldn't be installed?? >> you can simply import sys and check sys.version in the setup-script, and >> abort with an error-message if the expectations aren't matched. >> >> Diez > I know I can precheck the version, but the real issue is how I can > prevent from installing a specific module? Actually, the rest of the > package should still be installed but just not a particular module > because the feature is built in after 2.6. How about simply not importing the module in question if the version is not proper? Or even a try: import a_module_requiring_2_6 except (SyntaxError, ImportError): pass Diez From tjreedy at udel.edu Mon Sep 15 14:29:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Sep 2008 14:29:13 -0400 Subject: Converting between binary, decimal, hexadecimal, octal In-Reply-To: <ea09b3700809150154y65b90b4cuffbbec9485cab637@mail.gmail.com> References: <ea09b3700809150154y65b90b4cuffbbec9485cab637@mail.gmail.com> Message-ID: <gam9hk$ugr$1@ger.gmane.org> A. Joseph wrote: > Converting between binary, decimal, hexadecimal, octal > Where can I find good tutorial on numbering system? These are number representation systems that can be applied to or used with integral, rational (numberator,denominator), and 'point' numbers. Try Wikipedia or any search engine. > I really want to know the process of converting between all the numbers. > I may soon start HLA (assemply). There are standard algorithms for converting between representations. See above. Good programmer calculators have these built in. If you want to use the Python interactive interpreter, check the docs for the various integer literals and the hex, oct, and bin functions. Binary literals and bin are only available in 2.6 (I believe) and 3.0 (for sure). tjr From h.goebel at goebel-consult.de Tue Sep 16 13:32:14 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Tue, 16 Sep 2008 19:32:14 +0200 Subject: Python and Open Office In-Reply-To: <056cba0b-6c6e-4066-951c-3e97266d93d4@r15g2000prd.googlegroups.com> References: <a9f39a410809101304j592cb7actc1f95882f8fe632c@mail.gmail.com> <mailman.826.1221077307.3487.python-list@python.org> <ga9cps$mnt$1@theodyn.ncf.ca> <056cba0b-6c6e-4066-951c-3e97266d93d4@r15g2000prd.googlegroups.com> Message-ID: <48cfed9e$0$6660$9b4e6d93@newsspool2.arcor-online.net> Peter Georgeson schrieb: > I can confirm that unfortunately, the PyUNO interface presently > (OpenOffice 2.4) is built with Python 2.3... so to use the UNO > interface from Python you have to write a separate script to run in > the OpenOffice Python 2.3 environment. This may be true for Windows. On Linux - at least for Mandriva --, OOo is already integrated with Python 2.5. -- Sch?nen Gru? - Regards Hartmut Goebel Dipl.-Informatiker (univ.), CISSP Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From fredrik at pythonware.com Sat Sep 13 08:37:47 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 14:37:47 +0200 Subject: XML RPC Problem.... In-Reply-To: <a3158e8b0809130523g579ac36ci88caee7ac279f64d@mail.gmail.com> References: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> <gaagp1$804$1@ger.gmane.org> <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> <gafuhg$sh1$1@ger.gmane.org> <a3158e8b0809130306m25dda070w73f0a3c25888e051@mail.gmail.com> <gag6dj$fd5$1@ger.gmane.org> <a3158e8b0809130523g579ac36ci88caee7ac279f64d@mail.gmail.com> Message-ID: <gagc6u$tj6$1@ger.gmane.org> Usman Ajmal wrote: > Problem is that when i start client (while the server is already > running), i get an error i.e. > Error 500 Internal Server Error that's a server error, not a client error. check the server logs (e.g. error.log or similar). </F> From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:15:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:15:46 GMT Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <gbe0kd$qh9$1@rumours.uwaterloo.ca> <48da956c$0$1269$426a74cc@news.free.fr> <gbeae1$uin$1@rumours.uwaterloo.ca> Message-ID: <00eaee25$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote: > Plenty of people were quick to say that the exception should be passed > through to the caller. No one said this behaviour should be documented. > There may be little practical difference bewteen calling sys.exit() > after printing an error and progating an exception if no one using the > library knows that it could generate that exception in those > circumstances. That's true, I didn't explicitly say that the library should be documented. Nor did I say that it shouldn't be riddled with bugs. There's little practical difference between a buggy library and one that raises unexpected (i.e. undocumented) exceptions either. -- Steven From williamhpurcell at gmail.com Tue Sep 30 17:04:34 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Tue, 30 Sep 2008 16:04:34 -0500 Subject: why? __builtins__ key added from eval Message-ID: <d9186c3b0809301404k5ea2c84cj13189061d60c8899@mail.gmail.com> I want to use eval to evaluate wx.TextCtrl inputs. How can I keep python from adding the __builtins__ key to mydict when I use it with eval? Other wise I have to __delitem__('__builtins__') everytime I use eval? >>> mydict = {'a':2,'b':3} >>> eval('a*b',mydict) 6 >>> mydict {'a': 2, '__builtins__': {'IndexError': <type 'exceptions.IndexError'>, ...(I'll spare you the rest)...}, 'b': 3} Also, how come eval has this behavior? Is it desirable? -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/ae55e128/attachment.html> From castironpi at gmail.com Mon Sep 15 14:59:54 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 15 Sep 2008 11:59:54 -0700 (PDT) Subject: how to go around non-picklable object types? References: <91xzk.28830$rD2.16046@bignews4.bellsouth.net> Message-ID: <e6b79944-35f7-4ef9-ad14-7493fec341d4@d77g2000hsb.googlegroups.com> On Sep 15, 12:36?pm, "inhahe" <inh... at gmail.com> wrote: > There are certain types of objects that can't be pickled, like file objects. > My question is how could I pickle a hierarchy while automatically skipping > all such objects instead of just aborting the pickle when it comes across > one. > > The only thing I can think of is to make my own classes that wrap file > objects and so forth and use __getstate__ to leave out the underlying file, > etc. objects, or to set __getstate__ for every class that holds an offending > object type and filter such objects out of dictionaries when I pickle those. > And I don't even have a list of common object types that would make it > break. > > Is there a better way? ?thx.. inhahe, Nice to hear from you again. This is one possibility. import pickle class TolerantPickler( pickle.Pickler ): def save(self, obj): try: pickle.Pickler.save( self, obj ) except TypeError: pickle.Pickler.save( self, None ) Then every time the native Pickler object tries to call 'save' it gets your protected call instead. If the call fails with TypeError, just pickle None. Here are 'dumps' and a test. from StringIO import StringIO def dumps(obj, protocol=None): file = StringIO() TolerantPickler(file, protocol).dump(obj) return file.getvalue() class A: pass a= A() a.a= open( 'temp.dat' ) a.b= 32 b= dumps( a ) c= pickle.loads( b ) print c print c.a, c.b /Output: <__main__.A instance at 0x00A7D1E8> None 32 It may accomplish some of what you want. If it works, a pat on the back to the writer of the Pickler class for using encapsulation. From bearophileHUGS at lycos.com Fri Sep 5 17:49:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 14:49:21 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> <a34c6ffd-0353-43c9-8b22-36d0fc66ed22@v16g2000prc.googlegroups.com> Message-ID: <d9a713e1-3305-4d9c-8cac-02dc1c57aa86@m3g2000hsc.googlegroups.com> John Machin: > Consider this:>>> hash(123) == hash(123.0) == hash(123L) > True Right... Can you explain me why Python designers have chosen to build a hash() like that? > Try "uses all the information that is relevant to the task". My knowledge of hash data structures seems not enough to understand why. > Your alternative solution using reduce and xor may have suboptimal > characteristics ... Right, sorry. Bye, bearophile From grflanagan at gmail.com Thu Sep 18 15:09:59 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 18 Sep 2008 21:09:59 +0200 Subject: dict generator question In-Reply-To: <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <mailman.1220.1221752633.3487.python-list@python.org> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: <gau926$f20$1@ger.gmane.org> George Sakkis wrote: > On Sep 18, 11:43 am, Gerard flanagan <grflana... at gmail.com> wrote: >> Simon Mullis wrote: >>> Hi, >>> Let's say I have an arbitrary list of minor software versions of an >>> imaginary software product: >>> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] >>> I'd like to create a dict with major_version : count. >>> (So, in this case: >>> dict_of_counts = { "1.1" : "1", >>> "1.2" : "2", >>> "1.3" : "2" } >> [...] >> data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] >> >> from itertools import groupby >> >> datadict = \ >> dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) >> print datadict > > Note that this works correctly only if the versions are already sorted > by major version. > Yes, I should have mentioned it. Here's a fuller example below. There's maybe better ways of sorting version numbers, but this is what I do. data = [ "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.1.1.1", "1.3.14.5", "1.3.21.6" ] from itertools import groupby import re RXBUILDSORT = re.compile(r'\d+|[a-zA-Z]') def versionsort(s): key = [] for part in RXBUILDSORT.findall(s.lower()): try: key.append(int(part)) except ValueError: key.append(ord(part)) return tuple(key) data.sort(key=versionsort) print data datadict = \ dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) print datadict From eric.e.janke at gmail.com Tue Sep 23 10:50:30 2008 From: eric.e.janke at gmail.com (Eric E) Date: Tue, 23 Sep 2008 07:50:30 -0700 (PDT) Subject: Attachment Size and SMTP EMail Message-ID: <a2747a10-ecd6-4254-922e-59e8a2784c3b@m3g2000hsc.googlegroups.com> Hello All - I am using python to send an email with a large zip file as an attachment. I successfully sent a 52M attachment. If I try to send a 63M attachment or larger, the message never gets through. I do not get any errors in my python code. I pasted my python code below. from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email import Encoders import smtplib,os mssg = MIMEMultipart() part = MIMEBase('application',"octet-stream") part.set_payload(open(zipFileName,"rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(zipFileName)) mssg.attach(part) s = smtplib.SMTP('localhost') s.set_debuglevel(1) s.sendmail(fromAddr,toAddr,mssg.as_string()) s.quit() I am using a Fedora Core 6 system with python 2.4.4. Any suggestions on what could be limiting the attachment size or how I could troubleshoot this? Thanks! EricE From washakie at gmail.com Fri Sep 19 16:37:58 2008 From: washakie at gmail.com (John [H2O]) Date: Fri, 19 Sep 2008 13:37:58 -0700 (PDT) Subject: appending * to glob returns files with '*' !! Message-ID: <19579121.post@talk.nabble.com> I have a glob.glob search: searchstring = os.path.join('path'+'EN*') files = glob.glob(searchstring) for f in files: print f ___ This returns some files: EN082333 EN092334 EN* My routine cannot handle the '*' and it should'nt be returned anyway? :-/ A bug? -- View this message in context: http://www.nabble.com/appending-*-to-glob-returns-files-with-%27*%27-%21%21-tp19579121p19579121.html Sent from the Python - python-list mailing list archive at Nabble.com. From gagsl-py2 at yahoo.com.ar Sun Sep 21 13:56:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Sep 2008 14:56:01 -0300 Subject: report a BUG of package setuptools-0.6c8. References: <d2d5d61d0809192114p7b2a20b1tca588b5ed73acc26@mail.gmail.com> <mailman.1291.1221898300.3487.python-list@python.org> <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> <5e1183fa0809210246q46f864eic359964a0cb0d46e@mail.gmail.com> Message-ID: <op.uhudtowzx6zn5v@a98gizw.noga> En Sun, 21 Sep 2008 06:46:54 -0300, Sebastien Douche <sdouche at gmail.com> escribi?: > 2008/9/20 Carl Banks <pavlovevidence at gmail.com>: >> On Sep 20, 1:11 am, Fredrik Lundh <fred... at pythonware.com> wrote: >>> ???? wrote: >>> > File >>> "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", >>> > line 98, in entries_finder >>> > log.warn("unrecognized .svn/entries format in %s", dirname) >>> > NameError: global name 'log' is not defined >>> >>> > global name 'log' is not defined to the line 98!!! >>> >>> please report bugs here: >>> >>> http://bugs.python.org/ >> >> Does bugs.python.org track bugs for setuptools? (Genuine question; >> the PEAK site doesn't list an obvious way to report bugs so I wonder >> if they're using bugs.python.org? Hope not....) > > http://bugs.python.org/setuptools/ And how do people manage to know that? -- Gabriel Genellina From cournape at gmail.com Thu Sep 25 23:45:14 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 26 Sep 2008 12:45:14 +0900 Subject: Python is slow? In-Reply-To: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> Message-ID: <5b8d13220809252045v6365658ct462cd30f09407743@mail.gmail.com> On Wed, Sep 24, 2008 at 3:07 AM, sturlamolden <sturlamolden at yahoo.no> wrote: > On Sep 23, 3:44 pm, Robert Singer <rsinger at ____.com> wrote: > >> Well, python is not a number crunching language. However much we would >> like it to be (we would ? :-). > >> No scripting language is. > > Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? I am fairly experienced in matlab (have been using it extensively for 5 years in academical context), and now with numpy, and generally, they are comparable speed-wise. Matlab has some niceties which makes it faster in some simple cases (JIT for loops, function calls faster, sometimes COW semantics means it faster), but numpy (at its core at least) is much more powerful IMHO. Also, matlab is horrible when you want to interface some C to it (the C api is basically broken; in particular, there is no way to gurantee you won't leak memory when you Ctrl+C custom C extensions because the C api does not have facility to deal with signals). I totally gave up matlab for numpy 2 years ago, and never regretted it. I think speed is not the issue when comparing matlab, R and co. Availability of functionalities matter much more. R is quite hard to beat if you need to do advanced statistics, specially since it is the tool of choice for most academic statisticians. I hope numpy/scipy will be there sometime, but it is honestly still quite far in that domain. cheers, David From gminick at bzt.bzt Wed Sep 10 12:14:53 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 16:14:53 +0000 (UTC) Subject: dict slice in python (translating perl to python) References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Message-ID: <ga8rps$70e$1@inews.gazeta.pl> On Wed, 10 Sep 2008 08:28:43 -0700 (PDT), hofer wrote: > Hi, > > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; What about: >>> myhash={'one':1, 'two':2, 'three':3} >>> map(myhash.get, ['one', 'two', 'two']) [1, 2, 2] >>> or, to make it more similar to perl's qw() thing: >>> map(myhash.get, 'one two two'.split()) [1, 2, 2] >>> ...but I think that using explicit list is more pythonic. Isn't it? ;) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From clay at lakeserv.net Sun Sep 21 13:14:30 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Sun, 21 Sep 2008 13:14:30 -0400 Subject: Some questions about PyOpenGL and wxPython Message-ID: <1222017270.7824.3.camel@generator> I am making a program with wxPython that renders objects in 3D using PyOpenGL, and I am having some problems. For one thing, I forgot how to make a double-buffered hardware surface. For another thing, glColor(1.0, 0.0, 0.0) just before the rendering doesn't make the object red. Please help, I'm a total noob to OpenGL. From michele.petrazzo at TOGLIunipex.it Thu Sep 4 08:31:23 2008 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 04 Sep 2008 14:31:23 +0200 Subject: overwrite set behavior In-Reply-To: <mailman.468.1220522726.3487.python-list@python.org> References: <g9oat3$veh$1@nnrp-beta.newsland.it> <mailman.468.1220522726.3487.python-list@python.org> Message-ID: <g9oker$66v$1@nnrp-beta.newsland.it> Marco Bizzarri wrote: > looking at the source, maybe you could create a subclass of Set > redefining the __contains__ method? > Made some tries, but __contains__ are never called >>> class foo(set): ... def __contains__(self, value): ... print value ... >>> a = foo((1,2)) >>> Thanks, Michele From gagsl-py2 at yahoo.com.ar Thu Sep 18 17:10:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Sep 2008 18:10:34 -0300 Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <mailman.766.1221033019.3487.python-list@python.org> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> Message-ID: <op.uho3rwojx6zn5v@a98gizw.noga> En Tue, 16 Sep 2008 21:58:31 -0300, Sam <samslists at gmail.com> escribi?: > Gabriel, et al. > > It's hard to find a web site that uses deflate these days. > > Luckily, slashdot to the rescue. > > I even wrote a test script. > > If someone can tell me what's wrong that would be great. > > Here's what I get when I run it: > Data is compressed using deflate. Length is: 107160 > Traceback (most recent call last): > File "my_deflate_test.py", line 19, in <module> > data = zlib.decompress(data) > zlib.error: Error -3 while decompressing data: incorrect header check And that's true. The slashdot server is sending bogus data: py> s = socket.socket() py> s.connect(('slashdot.org',80)) py> s.sendall("GET / HTTP/1.1\r\nHost: slashdot.org\r\nAccept-Encoding: deflate\ r\n\r\n") py> s.recv(500) 'HTTP/1.1 200 OK\r\nDate: Thu, 18 Sep 2008 20:48:34 GMT\r\nServer: Apache/1.3.41 (Unix) mod_perl/1.31-rc4\r\nSLASH_LOG_DATA: shtml\r\nX-Powered-By: Slash 2.0050 01220\r\nX-Bender: Alright! Closure!\r\nCache-Control: private\r\nPragma: privat e\r\nConnection: close\r\nContent-Type: text/html; charset=iso-8859-1\r\nVary: A ccept-Encoding, User-Agent\r\nContent-Encoding: deflate\r\nTransfer-Encoding: ch unked\r\n\r\n1c76\r\n\x02\x00\x00\x00\xff\xff\x00\xc1\x0f>\xf0<!DOCTYPE HTML PUB LIC "-//W3C//DTD HTML 4.01//EN"\n "http://www.w3.org/TR/html4/str...' Note those 11 bytes starting with "\x02\x00\x00\xff..." followed by the page contents in plain text. According to RFC 2616 (HTTP 1.1), the deflate content coding consists of the "zlib" format defined in RFC 1950 in combination with the "deflate" compression mechanism described in RFC 1951. RFC 1950 says that the lower 4 bits of the first byte in a zlib stream represent the compression method; the only compression method defined is "deflate" with value 8. The slashdot data contains a 2 instead, so it is not valid. > #!/usr/bin/env python > > import urllib2 > import zlib > > opener = urllib2.build_opener() > opener.addheaders = [('Accept-encoding', 'deflate')] > > stream = opener.open('http://www.slashdot.org') > data = stream.read() > encoded = stream.headers.get('Content-Encoding') > > if encoded == 'deflate': > print "Data is compressed using deflate. Length is: ", > str(len(data)) > data = zlib.decompress(data) > print "After uncompressing, length is: ", str(len(data)) > else: > print "Data is not deflated." The code is correct - try with another server. I tested it with a LightHTTPd server and worked fine. -- Gabriel Genellina From paul.hankin at gmail.com Thu Sep 18 16:14:50 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 18 Sep 2008 13:14:50 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <b71efff9-2a9c-4f14-a15d-e11c454ebdd8@x16g2000prn.googlegroups.com> On Sep 18, 2:25?pm, Alexzive <zasaconsult... at gmail.com> wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > ? ? for i in range(len(IN)): #scan all elements of the list IN > ? ? ? for j in range(len(IN)): > ? ? ? ? if i <> j: > ? ? ? ? ?if IN[i].coordinates[0] == IN[j].coordinates[0]: > ? ? ? ? ? ?if IN[i].coordinates[1] == IN[j].coordinates[1]: > ? ? ? ? ? ? ? SN.append(IN[i].label) Using only a little extra storage to compute IN (but O(N log N) time complexity): import itertools IN.sort() SN = [k for k, v in itertools.groupby(IN) if len(list(v)) > 1] -- Paul Hankin From matiassurdi at gmail.com Mon Sep 15 15:04:04 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Mon, 15 Sep 2008 21:04:04 +0200 Subject: Converting .py files to batch files. In-Reply-To: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> Message-ID: <gambf9$5vt$1@ger.gmane.org> aditya shukla escribi?: > How can we convert .py files to batch files? is there any library for this? > > > Aditya > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list Maybe py2exe can help you. From lily200802 at gmail.com Fri Sep 12 22:41:59 2008 From: lily200802 at gmail.com (lily200802 at gmail.com) Date: Fri, 12 Sep 2008 19:41:59 -0700 (PDT) Subject: Insider information, fackbook labs open today, we the first to register! Message-ID: <211adcf3-fb68-498b-8dec-5722d8534571@q26g2000prq.googlegroups.com> Insider information, fackbook labs open today, we the first to register! www.fackbooklabs.com From tjreedy at udel.edu Thu Sep 4 19:54:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Sep 2008 19:54:56 -0400 Subject: why is self not passed to id()? In-Reply-To: <g9piha$gs9$1@aioe.org> References: <g9pg72$3vi$1@aioe.org> <mailman.502.1220560976.3487.python-list@python.org> <g9piha$gs9$1@aioe.org> Message-ID: <g9psgf$ll4$2@ger.gmane.org> Ruediger wrote: > I am aware that id is a built in function why shouldn't i use it? I consider this a sensible thing to have tried, but I an not too surprised it does not work because I am aware that built-in functions do not have all the features of Python function. I have asked about this case on Py-dev. Subject: Can/should built-in functions get __get__? > Replaceing lambda with id was intended as an performance hack. Profiling > proofed that lambda itself takes more than twice as much cpu time than id > alone. (profile shortened) > > 3610503 function calls in 22.451 CPU seconds > > Ordered by: standard name > > ncalls tottime percall cumtime percall filename:lineno(function) > > 960096 4.593 0.000 6.702 0.000 test14.py:33(<lambda>) > 1 0.003 0.003 22.451 22.451 {execfile} > 960096 2.109 0.000 2.109 0.000 {id} > > However using lambda seemed useless to me since id already took an argument > and wrapping it in an python function simply has no real purpose. Ironically, such simple wrappings are usually considered bad form. There *is* a third alternative, which works in this case, and which should be closer in speed to id. I will leave you to do a speed test. >>> class bang(list): __hash__ = object.__hash__ >>> s=set() >>> s.add(bang()) >>> s {[]} __eq__ = object.__eq__ should also work instead of the Python implementation I gave in my response to another response. Terry Jan Reedy From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 4 04:23:43 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 10:23:43 +0200 Subject: Late initialization using __getattribute__ In-Reply-To: <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> Message-ID: <48bf9aab$0$4598$426a74cc@news.free.fr> bukzor a ?crit : > On Sep 3, 1:02 pm, Bruno Desthuilliers > <bdesth.quelquech... at free.quelquepart.fr> wrote: >> bukzor a ?crit : >> (snip) >> >>> Thanks for the reply. Just to see it not work, I tried to remove >>> __getattribute__ from LateInitMixIn, but couldn't get it to work. >> ??? Sorry, I don't get what you mean... > > Since you said __getattribute__ is an attribute of the class, I tried > to run (something to the effect of) delattr(self.__class__, > "__getattribute__"), Ah, ok. Definitively *not* a thing to do... > but it threw an AttributeError. You'd have to call it on the mixin class itself, not on a subclass. > >>> My Base class is a C class (_mysql.connection from MySQLdb) that >>> sometimes segfaults if you try to use it before it's fully >>> initialized, >> >> ... I have used MySQLdb for years on more than a dozen linux >> distribs, and never had such a problem. Is this a known bug ? Or is >> there something wrong with your setup ? > > I'm trying to optimize my number of connections Connection pooling anyone ? IIRC, this is something that already exists in quite a couple libs / frameworks. Is there a reason you try to roll your own ? > by not fully > initializing (read: not connecting) my connection until it's used in > some way. Of course the maintainer didn't envision this (mis)use, so > the object sometimes throws bad errors until it's fully initialized. Ok. > Of course the *correct* way to do this is to be more careful about > when I create connections, but I think I should be able to get this to > work, and it (would be) much easier to do it The Right Way once it > works. Please pardon me for repeating the same thing over and over, but messing with __getattribute__ is certainly not the way to go. >>> so unfortunately I think I need to use __getattribute__ >>> to do this. I'm doing all this just to make the connection not >>> actually connect until used. >> I may be dumb, but I don't get how this is supposed to solve your >> problem. But anyway : there's a known design pattern for what you're >> trying to do, that doesn't require mixins nor messing with >> __getattribute__ (which, I repeat, is more often than not something you >> *don't* want to do). The name of the design pattern is "proxy". I >> strongly suggest that you 1/ try to cure the real problem instead of >> hacking around and 2/ read about the proxy design pattern. >> >> My 2 cents... > > I like the idea of mix-ins, but can't figure out how to make a proxy > work that way. You mean, "how to use a proxy for lazy initialization" ? Heck, that's the exact use case in the GoF. > For a long time I had a proxy class that added five or > six features on top of the MySQLdb package, but it wasn't configurable > enough, and I'm working on splitting each feature into its own MixIn > class. > > > As an aside, this is working for me pretty well. The "reconnect" > method (inheritied from a "Reconnectable" mixin) uses several of the > object's attributes, so I need to set _inited beforehand so that I > don't get into an infinite __getattribute__ loop. What I'd *really* > like to do is remove __getattribute__ from the object at that point. You can't. Or, more exactly, all you can do is remove __getattribute__ from the mixin class - but then the mixin class won't work anymore. I don't mean to be condescendant, but it looks like you don't have a clear understanding of Python's object model here - else you wouldn't even consider doing such a thing. FWIW, I posted a solution based on the __getattr__ hook, which did work - at least for the "specs" implied by your code snippet. From Scott.Daniels at Acm.Org Sat Sep 6 18:41:09 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 06 Sep 2008 15:41:09 -0700 Subject: String/Number Conversion In-Reply-To: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <GumdnTnIzfeEmV7VnZ2dnUVZ_r_inZ2d@pdx.net> Andreas Hofmann wrote: > I've got some strings, which only contain numbers plus eventually one > character as si-postfix (k for kilo, m for mega, g for giga). I'm trying > to convert those strings to integers, with this function: Why bother to always switch the case if you only use a few values? Also, the Python style is to do an operation and handle failures, rather than test first. Try something like: _units = dict(K=1000, M=1000000, G=1000000000, k=1000, m=1000000, g=1000000000) def eliminate_postfix(value): try: return _units[value[-1]] * int(value[: -1]) except (TypeError, KeyError): return int(value) If you normally do not have the suffixes, then switch it around: def eliminate_postfix(value): try: return int(value) except ValueError: return _units[value[-1]] * int(value[: -1]) If this is really SI units, you likely are doing real measurements, so I'd consider using "float" instead of "int" in the above. --Scott David Daniels Scott.Daniels at Acm.Org From dblubaugh at belcan.com Sun Sep 21 18:42:10 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Sun, 21 Sep 2008 18:42:10 -0400 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com><27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com><27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com><gb3bvk$9a1$1@ger.gmane.org><27CC3060AF71DA40A5DC85F7D5B70F38051C09F2@AWMAIL04.belcan.com> <op.uhucuzo8x6zn5v@a98gizw.noga> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38051C09F3@AWMAIL04.belcan.com> Sir, Thank you for your reply. This is as to how I developed my .pyd file. I entered the following commands within my MS-DOS prompt within Windows XP: C:\python25\Scripts> C:\python25\python f2py.py -c --fcompiler=gnu95 --compiler=mingw32 -m hello hello.f90 I am using the gfortran compiler, that was prescribed to use, as well as, the required commands on the following website: http://www.scipy.org/F2PY_Window <https://webmail.belcan.com/exchweb/bin/redir.asp?URL=http://www.scipy.org/F2PY_Window> I comes down to that yes, I am able to generate a .pyd file, which was generated by f2py. However, when I tried to import this file into my python script program I was given the following error: error 193?? I do not know as to what I am doing incorrectly, since I am generating a .pyd file by f2py? If I am doing anything that is incorrect, then why am I EVEN ABLE TO GENERATE A .PYD FILE IN THE FIRST PLACE??? Any Help will be greatly appreciated!!!!! Thanks, David Blubaugh ________________________________ From: Gabriel Genellina [mailto:gagsl-py2 at yahoo.com.ar] Sent: Sun 9/21/2008 1:55 PM To: python-list at python.org Subject: Re: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py En Sat, 20 Sep 2008 16:07:12 -0300, Blubaugh, David A. <dblubaugh at belcan.com> escribi?: > Let me state that do have extensive experience with developing binary > files. Please note that I have followed all of the instructions to the > letter as far as developing a DLL to be imported. However, it is not > working correctly. I believe it might be my system environment > variables?? It might be the sunspots (or the lack of them) as well. You could start telling us what's your platform, which instructions have you followed, which compiler have you used... -- Gabriel Genellina This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From castironpi at gmail.com Wed Sep 24 00:15:36 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 21:15:36 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> <fde4ed92-77ed-438e-a163-d5e248a80ee9@d45g2000hsc.googlegroups.com> <31ff7c8a-28f3-4c62-8ac5-6d0f90106c5d@a8g2000prf.googlegroups.com> <e2537230-c4ad-474a-913c-d0829286e699@k13g2000hse.googlegroups.com> Message-ID: <0fd3fd66-a4f5-4322-8823-722de1dfa952@c58g2000hsc.googlegroups.com> On Sep 23, 11:06?pm, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 23, 9:30?pm, lixinyi... at gmail.com wrote: > > > > > If the PyObject is a PyList, and all list items are strings, > > say a=['aaa','bbb','ccc'] > > > How can I have a > > myArray[0] = "aaa" > > myArray[1] = "bbb" > > myArray[2] = "ccc" > > in C++? > > > Do I have to > > use PyModule_GetDict() to get the dict first? > > what about the next? > > > > What do you know about the contents of 'argc' and 'argv'? ?If it's > > > impossible with Py_Main, can you use one of the other entry points? > > > > If you've never manipulated PyObject* objects in C, they can be > > > hairy. ?Even if you know 'a' is a sequence, its contents are still all > > > PyObject*s, which you can access via PyList_... and PySequence_ > > > functions. > > This one writes '[aaa, bbb, ccc]' to the console in two different > ways. > > #include <Python.h> > > int main() { > ? ? PyObject *list, *listrepr; > ? ? Py_Initialize(); > > ? ? /* first */ > ? ? list= PyList_New( 3 ); > ? ? PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); > ? ? PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); > ? ? PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); > > ? ? listrepr= PyObject_Repr( list ); > ? ? printf( "%s\n", PyString_AsString( listrepr ) ); > > ? ? Py_DECREF( listrepr ); > ? ? Py_DECREF( list ); > > ? ? /* second */ > ? ? list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); > ? ? listrepr= PyObject_Repr( list ); > ? ? printf( "%s\n", PyString_AsString( listrepr ) ); > > ? ? Py_DECREF( listrepr ); > ? ? Py_DECREF( list ); > > ? ? Py_Finalize(); > ? ? return 0; > > } > > Did you want to execute some Python code, and examine variables it > creates? Here's a third way: PyObject *list, *listrepr, *dict, *result, *name; /* third */ dict= PyDict_New( ); result= PyRun_String( "myarray= [ 'ggg', 'hhh', 'iii' ]", Py_file_input, dict, NULL ); name= PyString_FromString( "myarray" ); list= PyDict_GetItem( dict, name ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( dict ); Py_DECREF( result ); Py_DECREF( name ); Py_DECREF( listrepr ); Py_DECREF( list ); PyRun_String runs a namespace, 'dict', which holds the variables. From __peter__ at web.de Fri Sep 5 10:57:12 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Sep 2008 16:57:12 +0200 Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> Message-ID: <g9rhc4$81p$01$1@news.t-online.com> Helmut Jarausch wrote: > I need to hash arrays of integers (from the hash module). > > So, I have to derive from array and supply a __hash__ method. > But how to hash an array (of fixed length, say 25)? > What I need is a function which maps a tuple of 25 integers > into 1 integer with good hashing properties. > > Does anybody know such a thing? Have you tried this already? def __hash__(self): return hash(self.tostring()) Peter From mail at microcorp.co.za Sat Sep 6 17:24:24 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 6 Sep 2008 23:24:24 +0200 Subject: atomic section in code Message-ID: <005901c91086$208021a0$0d00a8c0@hendrik> Fredrik Lundh <fredr...ware.com> wrote: >sounds like he wants/needs non-cooperative, mandatory locking. Could one get there using ctypes to disable interrupts? Cross Platform? I can think of lots of hassles, starting with permissions to use the privileged instructions. - Hendrik From gagsl-py2 at yahoo.com.ar Fri Sep 19 10:15:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 11:15:55 -0300 Subject: Intercepting printed strings References: <496954360809181524g6037e0b0x84e98834bbf8ad9c@mail.gmail.com> <op.uhp1mu0ux6zn5v@gabriel2.softlabbsas.com.ar> <496954360809190637n8c12c6cvc177327aeb032ae4@mail.gmail.com> Message-ID: <op.uhqe8tpkx6zn5v@a98gizw.noga> En Fri, 19 Sep 2008 10:37:00 -0300, Robert Dailey <rcdailey at gmail.com> escribi?: > On Fri, Sep 19, 2008 at 4:21 AM, Gabriel Genellina > <gagsl-py2 at yahoo.com.ar>wrote: > >> En Thu, 18 Sep 2008 19:24:26 -0300, Robert Dailey <rcdailey at gmail.com> >> escribi?: >> >> >> I'm currently using Python 3.0 b3 and I'm curious as to how I can go >> about >>> intercepting things send to print() for some intermediate processing >>> before >>> they're actually sent to sys.stdout. Right now I've thought of the >>> following: >>> >>> Replace sys.stdout with a class named PrintStream. PrintStream is >>> defined >>> as >>> follows: >>> >>> class PrintStream: >>> def write( self, message ): >>> sys.__stdout__.write( '\t{0}'.format( message ) ) >>> >>> Will this work? Basically I want to add a tab character in front of >>> every >>> message printed. Thanks. >>> >> >> Why don't you try it yourself? >> You may replace builtins.print with your own function too. It's not >> exactly >> the same thing, but given your request "intercepting things send to >> print() >> before they're sent to sys.stdout" it may be more adequate. > > > I did try the code I posted and it doesn't work. Works for me: p3> class PrintStream: ... def write( self, message ): ... sys.__stdout__.write( '\t{0}'.format( message ) ) ... p3> sys.stdout = PrintStream() p3> print("Hello world!") Hello world! p3> print(1, 2, 3) 1 2 3 (note the double spacing between elements) You may want to replace the print() function instead (this was not so easy in previous versions): p3> sys.stdout = sys.__stdout__ p3> def _print(*args): # simplified print() signature ... sys.stdout.write('\t' + ' '.join(str(arg) for arg in args) + '\n') ... p3> import builtins p3> builtins.print = _print p3> print("Hello world!") Hello world! p3> print(1, 2, 3) 1 2 3 p3> -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Tue Sep 30 20:52:40 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Oct 2008 10:52:40 +1000 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> <87zllqqa1i.fsf@benfinney.id.au> <pan.2008.09.30.10.04.18@REMOVE.THIS.cybersource.com.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> <mailman.1766.1222798706.3487.python-list@python.org> <87hc7xqlnj.fsf@benfinney.id.au> <00f2b5d2$0$20617$c3e8da3@news.astraweb.com> Message-ID: <87d4ilqgpz.fsf@benfinney.id.au> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes: > On Wed, 01 Oct 2008 09:06:08 +1000, Ben Finney wrote: > > > Note that I consider a work free even if it fails to grant ?the > > right to distribute misrepresentations of the author's words?, > > because that act is an exercise of undue power over another > > person, and so falls outside the limit imposed by the freedoms of > > others. > > But distributing modified source code *does* misrepresent the > author's words, because you confuse authorship. That's a possibility. There are other ways to avoid it than to restrict the freedom to redistribute; for example, some licenses state that modified works must clearly state who, when, and what was modified. I would not consider that a non-free restriction, since the freedom of the original distributor *and* the freedom of the redistributor is preserved. > If that is why the gnuplot people do not allow you to distribute > such modified documents, then the only "freedom" they fail to grant > is exactly the one you don't consider necessary for a free licence: > "the right to distribute misrepresentations of the author's words". We're going around in circles. I've already pointed out another freedom they fail to grant: the freedom to redistribute a modified work *as modified*. It's not equivalent to the act of misrepresentation. -- \ ?War is God's way of teaching geography to Americans.? ?Ambrose | `\ Bierce | _o__) | Ben Finney From M8R-yfto6h at mailinator.com Mon Sep 29 11:03:55 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 29 Sep 2008 08:03:55 -0700 Subject: Using re to find unicode ranges References: <mailman.1674.1222694261.3487.python-list@python.org> Message-ID: <Q8udnU3y8J_Bc33VnZ2dnUVZ_oqdnZ2d@comcast.com> "Eric Abrahamsen" <eric at ericabrahamsen.net> wrote in message news:mailman.1674.1222694261.3487.python-list at python.org... > Is it possible to use the re module to find runs of characters within a > certain Unicode range? > > I'm writing a Markdown extension to go over text and wrap blocks of > consecutive Chinese characters in <span class="char"></span> tags for > nice styling in an HTML page. The available hooks appear to be a pre- > processor (which is a "for line in lines" situation) or an inline pattern > (which uses regular expressions). The regular expression solution would > be much simpler and faster, but something tells me there's no way to use > a regex to find character ranges... Chinese characters appear to fall > between 19968 and 40959 using ord(), and I suppose I can go that route if > necessary, but I think it would be ugly. # coding: utf-8 import re sample = u'My name is ??. I am ???.' for n in re.findall(ur'[\u4e00-\u9fff]+',sample): print n output: ?? ??? --Mark From namekuseijin at gmail.com Tue Sep 30 00:03:07 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Mon, 29 Sep 2008 21:03:07 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <f2d2bf0b-9362-47f5-84eb-411e09ab38e1@8g2000hse.googlegroups.com> On 28 set, 15:29, process <circularf... at gmail.com> wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. So what? > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? Because postfix notation sucks. The natural way of spelling is adjective+noun and verb+predicate. That's one of the reasons I like Lisp better than Python. From gagsl-py2 at yahoo.com.ar Tue Sep 2 03:26:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 04:26:36 -0300 Subject: Enhanced property decorator References: <9e36cdd4-7d66-4eae-aa60-1782e500abfe@34g2000hsh.googlegroups.com> Message-ID: <op.ugueymrlx6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 25 Aug 2008 22:45:36 -0300, Daniel <millerdev at gmail.com> escribi?: > I've often been frustrated by the inability of the built-in property > descriptor to handle anything other than a read-only property when > used as a decorator. Furthermore, read/write/delete properties take > their doc-string and property definition at a non-intuitive and > awkward place (after the getter/setter/delter functions). The > following are three possible solutions to this problem (inspired by > message http://groups.google.com/group/comp.lang.python/msg/9a56da7ca8ceb7c7). > I don't like the solution in that thread because it uses apply() which > will go away in Python 3. > > Solution 1: new built-in function/descriptor > > def prop(func): > funcs = dict(enumerate(func())) > return property(funcs[0], funcs[1], funcs.get(2), func.__doc__) > > class Test(object): > @prop > def test(): > """test doc string""" > def fget(self): > return self._test > def fset(self, value): > self._test = value > def fdel(self): > del self._test > return fget, fset, fdel > > Of course the name (prop) could be changed... I couldn't think of > anything more concise. > > Pros: > (1) encapsulation of property logic inside function namespace, > preventing clutter in class namespace. > (2) doc string appears in a more natural place, before getter/setter/ > delter logic, as in classes and functions. > > Cons: > (1) additional built-in name. > (2) duplication/boilerplate in return line (DRY violation). (Some days late, sorry...) I like the variant below, based on your code. It avoids issue (2) by using locals(). Works with Python 3.0 too - and don't use tricks like sys._getframe or sys.settrace: def defproperty(func): impls = func() return property(doc=func.__doc__, **impls) class Test(object): @defproperty def test(): """test doc string""" def fget(self): return self._test def fset(self, value): self._test = value def fdel(self): del self._test return locals() -- Gabriel Genellina From tjreedy at udel.edu Sun Sep 28 03:55:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 03:55:46 -0400 Subject: str() should convert ANY object to a string without EXCEPTIONS ! In-Reply-To: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <gbnda2$7cq$1@ger.gmane.org> est wrote: >>From python manual > > str( [object]) > > Return a string containing a nicely printable representation of an > object. For strings, this returns the string itself. The difference > with repr(object) is that str(object) does not always attempt to > return a string that is acceptable to eval(); its goal is to return a > printable string. If no argument is given, returns the empty string, > ''. > > > now we try this under windows: > >>>> str(u'\ue863') > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0 > : ordinal not in range(128) In 3.0 this is fixed: >>> str('\ue863') # u prefix is gone '\ue863' >>> str(b'123') # b prefix is added "b'123'" Problems like this at least partly motivated the change to unicode instead of bytes as the string type. tjr From google at mrabarnett.plus.com Sun Sep 7 20:34:00 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 7 Sep 2008 17:34:00 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <mailman.666.1220826503.3487.python-list@python.org> Message-ID: <086a0906-c6f1-489c-91ab-f6a4f9e1ae3f@59g2000hsb.googlegroups.com> On Sep 7, 11:28?pm, "Eric Wertman" <ewert... at gmail.com> wrote: > +1 Bot I think it's like duck typing: it doesn't matter whether he's actually a bot, only whether he behaves like one. From gagsl-py2 at yahoo.com.ar Fri Sep 19 12:07:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 13:07:02 -0300 Subject: generator exceptions References: <826a734c-968c-4d68-9ed1-c2688340ebc5@a3g2000prm.googlegroups.com> Message-ID: <op.uhqkd0bex6zn5v@a98gizw.noga> En Fri, 19 Sep 2008 10:40:00 -0300, Alexandru Mosoi <brtzsnr at gmail.com> escribi?: > i have a generator that raises an exception when calling next(), > however if I try to catch the exception and print the traceback i get > only the line where next() was called > > > while True: > try: > iterator.next() > except StopIteration: > break > except Exception, e: > traceback.print_exc() > > how do I get the traceback starting from where exception was raised in > first place? I get a complete traceback: py> import traceback py> py> def a(x): ... raise ValueError ... py> def b(x): ... return a(x) ... py> def c(n): ... for i in range(n): ... yield b(i) ... py> it = c(5) py> while True: ... try: ... it.next() ... except StopIteration: ... break ... except Exception: ... print traceback.print_exc() ... Traceback (most recent call last): File "<stdin>", line 3, in <module> File "<stdin>", line 3, in c File "<stdin>", line 2, in b File "<stdin>", line 2, in a ValueError None py> Could you provide a more complete example that fails? -- Gabriel Genellina From mnordhoff at mattnordhoff.com Fri Sep 12 15:57:17 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 12 Sep 2008 19:57:17 +0000 Subject: manipulating files within 'for' In-Reply-To: <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> References: <48CAA2AA.40809@umbc.edu> <gae9jj$sks$1@ger.gmane.org> <mailman.940.1221242051.3487.python-list@python.org> <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> Message-ID: <48CAC99D.3060603@mattnordhoff.com> bearophileHUGS at lycos.com wrote: > Ben Keshet: >> ...wrong. I thought I should omit the comma and didn't put it. I guess >> that stating the obvious should be the first attempt with beginners like >> me. Thanks for thinking about it (it's running perfect now). > > In CLisp, Scheme etc, lists such commas aren't necessary, but in > Python if you don't separate strings with a comma they become merged > into a single string: > >>>> 'foo', 'bar' > ('foo', 'bar') >>>> 'foo' 'bar' > 'foobar' > > Your mistake is caused by Python not following one of its general > rules: > > Explicit is better than implicit. > > In such case the string concatenation (+) is done implicitly. It's a > little handy feature once in a while (but not for me so far), while it > may cause bugs, so I don't like this little feature of Python and I > may like to see it removed, because it may bite you in similar > situations, where you forgot a comma for mistake: > > parts = ["foo", "bar" "baz"] > > Bye, > bearophile It's useful when wrapping a line. For lack of better lorem ipsum: whatever = some_function("Your mistake is caused by Python not " "following one of its general rules:\n\n" "Explicit is better than implicit.") You can also use backslashes, and probably even + if you want to, but the implicit concatenation is prettier (IMO, at least ;-). But you do have a point. I have never thought about the problems it could cause. BTW, I could easily be wrong, but I think C behaves the same way as Python. -- From deets at nospam.web.de Wed Sep 10 17:52:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 23:52:00 +0200 Subject: emulating read and readline methods In-Reply-To: <ee4202f1-ce8f-458e-9627-08215351694d@e53g2000hsa.googlegroups.com> References: <ee4202f1-ce8f-458e-9627-08215351694d@e53g2000hsa.googlegroups.com> Message-ID: <6iqts0F3v76U1@mid.uni-berlin.de> Sean Davis schrieb: > I have a large file that I would like to transform and then feed to a > function (psycopg2 copy_from) that expects a file-like object (needs > read and readline methods). > > I have a class like so: > > class GeneInfo(): > def __init__(self): > #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > gene_info.gz',"/tmp/gene_info.gz") > self.fh = gzip.open("/tmp/gene_info.gz") > self.fh.readline() #deal with header line > > def _read(self,n=1): > for line in self.fh: > if line=='': > break > line=line.strip() > line=re.sub("\t-","\t",line) > rowvals = line.split("\t") > yield "\t".join([rowvals[i] for i in > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > def readline(self,n=1): > return self._read().next() > > def read(self,n=1): > return self._read().next() > > def close(self): > self.fh.close() > > and I use it like so: > > a=GeneInfo() > cur.copy_from(a,"gene_info") > a.close() > > It works well except that the end of file is not caught by copy_from. > I get errors like: > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > during .read() call > CONTEXT: COPY gene_info, line 1000: "" > > for a 1000 line test file. Any ideas what is going on? I'm a bit lost why the above actually works - as _read() appears to be re-created instead of re-used for each invocation, and thus can't work IMHO. Anyway, I think the real problem is that you don't follow the readline-protocol. it returns "" if there is no more line to read, instead you raise a StopIteration Diez From clp at rebertia.com Tue Sep 2 23:01:36 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Sep 2008 20:01:36 -0700 Subject: Py 2.6 changes In-Reply-To: <1bd15c2c-82e0-4742-a97f-ae16fb75ae26@m3g2000hsc.googlegroups.com> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <00cc7976$0$20302$c3e8da3@news.astraweb.com> <fb60e830-1267-48c9-9b99-3352a1db64cc@i76g2000hsf.googlegroups.com> <1bd15c2c-82e0-4742-a97f-ae16fb75ae26@m3g2000hsc.googlegroups.com> Message-ID: <47c890dc0809022001w2dcaa008s88fd01592fa24140@mail.gmail.com> On Mon, Sep 1, 2008 at 6:02 PM, Mensanator <mensanator at aol.com> wrote: > On Sep 1, 6:55?pm, bearophileH... at lycos.com wrote: >> Steven D'Aprano: >> >> > productory() -- I don't know that function, and googling mostly comes up >> > with retail product searches. Do you mean product(), >> >> Darn my English, you are right, sorry, I meant a product() of >> course :-) > > But the name product() has already been taken by itertools to > mean Cartesian Product. We have this thing called "namespacing" and it's one honking great idea that's perfect for these situations. - Chris > >> >> Bye, >> bearophile > > -- > http://mail.python.org/mailman/listinfo/python-list -- Follow the path of the Iguana... http://rebertia.com From m_palmer45 at yahoo.ca Fri Sep 5 11:49:28 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 5 Sep 2008 08:49:28 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> Message-ID: <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> On Sep 5, 11:18 am, bearophileH... at lycos.com wrote: > Helmut Jarausch: > > > I need to hash arrays of integers (from the hash module). > > One of the possible solutions is to hash the equivalent tuple, but it > requires some memory (your sequence must not be tuples already): why can't it be tuple already? Doesn't matter: >>> from numpy import arange >>> a=arange(5) >>> a array([0, 1, 2, 3, 4]) >>> hash(a) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unhashable type >>> b=tuple(a) >>> b (0, 1, 2, 3, 4) >>> c=tuple(b) >>> c (0, 1, 2, 3, 4) >>> hash(c) 1286958229 you can discard the tuple, so the memory requirement is transient. From tjreedy at udel.edu Mon Sep 29 13:55:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 13:55:10 -0400 Subject: writing dll in python? In-Reply-To: <gbqjh3+39e0@eGroups.com> References: <gbqjh3+39e0@eGroups.com> Message-ID: <gbr4pt$2li$1@ger.gmane.org> nishalrs wrote: > Hello All, > > My main motivation is to build a collection of useful mathematical > models (that I have developed over the years) to design ultrasonic > sensors. This should be some sort of a library that should be able to > be used for desktop/web application development, to run in variety of > operating systems. Interesting new applications of Python are welcome. Googling "Python package (or module) ultrasonic sensor" did not turn up anything relevant that I saw. > I am more than convinced after looking at python.org website, it is > the right tool for the job. I intend to learn python, but I am not > really sure, where to begin. Start with the Python tutorial, perhaps parts of the reference manual, and definitely peruse the first chapters in the library manual on built-in functions and classes. You will almost certainly want to use numpy (numpy.org) for numerical calculation and possibly existing modules in scipy (scipy.org) or elsewhere. > Should I write all the functions as simple python scripts? Or is there > some facility for creating a .dll like library, that could be more > suitable for what in intend to develop? A module is a 'script' that is intended to be imported by other Python code. In your Python installation directory, /Libs has numerous *.py examples. A 'package' is a collection of modules in a directory that includes only called __init__.py (if I remember correctly). Don't worry about details yet. When you have something worth distributing, you can get help here or on other lists, such as the one for numpy/scipy. When you are ready, you can announce it here and elsewhere and register it at the Python Package Index (pypi.python.org/pypi). Terry Jan Reedy From kannu.valli3 at gmail.com Sat Sep 20 01:30:56 2008 From: kannu.valli3 at gmail.com (kannu.valli3 at gmail.com) Date: Fri, 19 Sep 2008 22:30:56 -0700 (PDT) Subject: Enjoy seeing Enjoy seeingEnjoy seeingEnjoy seeing Enjoy seeing Message-ID: <fad1a0bf-3a38-4c27-a18b-f24b310fe669@v16g2000prc.googlegroups.com> Enjoy seeing with new video pictures http://nagaaraja.blogspots.com\ From gnewsg at gmail.com Thu Sep 11 12:40:59 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Sep 2008 09:40:59 -0700 (PDT) Subject: Please help me finding a way to implement os.path.issubpath(a, b) Message-ID: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> Hi, I'm trying to implement a function which returns whether a path is a subpath of another one (e.g. /a/b/c is a subpath of /a/b). I wrote this function which apparently seems to work fine: import os def issubpath(path1, path2): """Return True if path1 is a sub path of path2.""" if path1 == path2: return False x1 = path1.split(os.sep) x2 = path2.split(os.sep) return x1[:len(x2)] == x2 ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False. A little help would be appreciated. Thanks in advance. --- Giampaolo http://code.google.com/p/pyftpdlib/ From dudeja.rajat at gmail.com Tue Sep 2 09:32:30 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 2 Sep 2008 14:32:30 +0100 Subject: What is module initialization? Message-ID: <e0b6c39a0809020632g678cc1e4vbcec509da9bc19f4@mail.gmail.com> Hi, I found on the net that there is something called module initialization. Unfortunately, there is not much information for this. However, small the information I found module initialization can be of use to me in my project. I'm currently messing with a problem where I'm keeping my global variables ( or symbols) in a module and the other mdoules in the project acess these global variables. However, there is one case when a module updates one such global variable but the variable is not getting updated in the module containing global symbols ( variables). This happen only at the start of the program and at rest of the places in the program that global variable is not accessed. So, I thought of using this module initialization where I will intialize the module only once to update that variable. Ans in the rest of the program where ever this module is imported I shall be able to easily access the update value of the variable. Could some one provide me a sample code of module intialization? And how can I ensure that module initialization is done only once? Thanks and regards, Rajat From skip at pobox.com Wed Sep 17 05:54:21 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Sep 2008 04:54:21 -0500 Subject: Python for the iPhone? Message-ID: <18640.54221.603481.301379@montanaro-dyndns-org.local> Anybody tried this port of Python to the iPhone? http://www.modmyi.com/nativeapps/python-v251/ http://iphone.natetrue.com/ Hasn't been updated since July 2007. Maybe just a proof-of-concept? I'm guessing it involves jailbreaking the phone. Skip From notvalid2 at sbcglobal.net Mon Sep 1 10:57:59 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 01 Sep 2008 07:57:59 -0700 Subject: How Compute # of Days between Two Dates? In-Reply-To: <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> References: <JAIuk.19687$cW3.19527@nlpi064.nbdc.sbc.com> <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> Message-ID: <VpTuk.38934$ZE5.3067@nlpi061.nbdc.sbc.com> Grant Edwards wrote: > On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: > >> That's the question in Subject. For example, the difference between >> 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and >> 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in >> years between, say, 1990 and 2050. In other words not some really strange >> period of time well outside our current era of history. > > Does the standard library's datetime module not do what you want? > > http://docs.python.org/lib/module-datetime.html > Yes, it would seem so. This works fine. date1 = datetime.date(2007, 2, 27) date2 = datetime.date(2007, 3, 3) print "date1: ", date1 print "date2: ", date2 diff = date2 - date1 print "diff: ", diff result: date1: 2007-02-27 date2: 2007-03-03 diff: 4 days, 0:00:00 I was pondering this in pyfdate, but perhaps missed it or it was not obvious to me in the tutorial for some reason. There are few places where it's not quite complete. pyfdate has some rules for dealing with length of month oddities that started me thinking it would have difficulty with situations like the above. However, it would seem any general implementation of time and date should be capable of making similar calculations without difficulty. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: <www.speckledwithstars.net/> From user at domain.invalid Wed Sep 17 12:02:15 2008 From: user at domain.invalid (Canned) Date: Wed, 17 Sep 2008 18:02:15 +0200 Subject: translating ascii to binary Message-ID: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> Hi, I'm trying to write a class that can convert ascii to binary and vice versa. I write my class based on this function I've found on internet > def ascii_to_bin(char): > ascii = ord(char) > bin = [] > > while (ascii > 0): > if (ascii & 1) == 1: > bin.append("1") > else: > bin.append("0") > ascii = ascii >> 1 > > bin.reverse() > binary = "".join(bin) > zerofix = (8 - len(binary)) * '0' > > return zerofix + binary > > > > some_string = 'Time to go now, Rummy?' > > binary = [] > for char in some_string: > binary.append(ascii_to_bin(char)) > > print binary > print " ".join(binary) That works perfectly, but when I try to implement it in my own class it gives me alot of headache, also because I'm totally new to the language. It work only with one character at a time, and if I give a string it just give some weird result. > if len(sys.argv) < 2: > print 'usage:', os.path.basename(sys.argv[0]), 'text' > sys.exit() > > class Converterab: > ''' > Ascii-binary converter. > ''' > def __init__(self, string): > self.string = string > > def ascii_to_bin(self): > bindump = [] > for char in self.string: > bin = ord(char) > while bin > 0: > if (bin & 1) == 1: > bindump.append("1") > else: > bindump.append("0") > bin = bin >> 1 > bindump.reverse() > print bindump # Debug tool, delete this > > ''' > Zero fix in bindump > ''' > bindump.insert(0, "0") > count = 0 > pos = 0 > for dg in bindump: > count += 1 > pos += 1 > if count == 8: > bindump.insert(pos, "0") > count = 0 > bindump.pop() > print bindump # Debug tool, delete this, the best result so far > > ''' > Reversing array per byte > ''' > final = [] > pos -= pos # Set pos to 0 again > while len(bindump) != 0: > print count # Debug tool, delete this, this is weird, start at 1, I expected 0 > count += 1 > if count > 8: > pos += 8 > count -= count > final.insert(pos, bindump.pop()) > print final # Debug tool, delete this > ''' > for ar in bindump: > count += 1 > if (count < 8): > final.insert(pos, bindump.pop()) > elif (count >= 8): > pos = count > final.insert(pos, bindump.pop()) > else: > final.insert(pos, bindump.pop()) > ''' > final.insert(0, final.pop()) > > binary = "".join(final) > return binary > > result = Converterab(sys.argv[1]) > > print "Char : ", result.ascii_to_bin() The problem start at "Reversing array per byte". That block should reversing the array from 'bindump' and copy it to 'final' per 8 items, e.g. a = ['0', '1', '0', '1', '0', '1', '0', '1', '2', '1', '2', '1', '2', '1', '2', '1', '3', '2', '3', '2', '3', '2', '3', '2'] b = ['3', '2', '3', '2', '3', '2', '3', '2', '2', '1', '2', '1', '2', '1', '2', '1', '0', '1', '0', '1', '0', '1', '0', '1'] Any advice about this matter would be very appreciated. Thanks in advance. C From zentraders at gmail.com Tue Sep 2 11:38:31 2008 From: zentraders at gmail.com (Zentrader) Date: Tue, 2 Sep 2008 08:38:31 -0700 (PDT) Subject: (in memory) database References: <d1104d4c-b894-46ed-9641-fcbcdc3661d0@26g2000hsk.googlegroups.com> <mailman.297.1220190030.3487.python-list@python.org> <5enqo5-9n9.ln1@lairds.us> <b68940e4-78cc-4fbb-94cd-69478d45f96c@26g2000hsk.googlegroups.com> <k33ro5-lqh.ln1@lairds.us> <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> <3e419475-61a1-4579-a8b6-fc15f9fe0a9b@m73g2000hsh.googlegroups.com> Message-ID: <f1312026-9450-483d-87e0-be9903f7f9e0@z11g2000prl.googlegroups.com> > I don't understand why Cameron has a different version of Python which > doesn't seem to have sqlite support enabled. Agreed, but won't the package manager tell him if python-sqlite is installed? That would be the next step since it appears that SQLite intself is already installed. Since Ubuntu uses precompied binaries, Python should be configured for SQLite which again leaves no python- sqlite as the only possibility (yeah right). BTW Python is easy to install manually. From ceball at users.sourceforge.net Fri Sep 12 09:32:18 2008 From: ceball at users.sourceforge.net (Chris) Date: Fri, 12 Sep 2008 13:32:18 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: <mailman.793.1221057913.3487.python-list@python.org> <87k5diex3m.fsf@mulj.homelinux.net> <mailman.895.1221164133.3487.python-list@python.org> <87ej3p7ira.fsf@mulj.homelinux.net> Message-ID: <loom.20080912T122528-968@post.gmane.org> Hrvoje Niksic <hniksic <at> xemacs.org> writes: ... > Chris <ceball <at> users.sourceforge.net> writes: > > >> PyObject_GetAttrString is convenient, but it creates a Python string > >> only so it can intern it (and in most cases throw away the freshly > >> created version). For maximum efficiency, pre-create the string > >> object using PyString_InternFromString, and use that with > >> PyObject_GetAttr. > > > > Yes, we'd thought of that too, but it doesn't seem to be an > > important factor compared to the actual attribute lookup. > > I'd like to see your test code. Thanks for your interest in this. My test code is a whole function that's part of a big simulator, unfortunately! I need to use the data structures created by the simulator as part of the testing. While the source is freely available*, that doesn't make it easy for others to run the tests... > In my experience, as long as you're > accessing simple slots, you should notice a difference. (I'm not sure what you mean by a 'simple slot'. The slot we're accessing is a numpy array.) Sorry I wasn't clear before - we do notice a difference, but not as big a difference as when we access the attributes (arrays) from a pre-built list. Below are timings from running the simulator (i.e. calling the function in question many times) using the three approaches (GetAttrString, GetAttr, and instead using a list and GetItem; times outside parentheses are from a stopwatch; times in parentheses are from Python's cProfile module): - GetAttrString: 55 seconds (58 seconds) inside the loop: PyObject *weights_obj = PyObject_GetAttrString(obj,"attr_one"); - GetAttr: 46 seconds (46 seconds) outside the loop: PyObject *name = PyString_FromString("attr_one"); inside the loop: PyObject *obj = PyObject_GetAttr(obj,name); - PyList_GetItem: 35 seconds (37 seconds) So, of course, you are right to say that we should notice a difference! But speed is critical for us here. Incidentally, what we have is a simulator written entirely in Python, but we also provide optimized C versions of some parts of it. These C parts must be entirely optional. > Here is a test program that shows a 4.6 time speedup simply by > switching from PyObject_GetAttrString to PyObject_GetAttr: Thanks for the illustration. While I didn't run your code myself, I did try to study it. Illustrations like that are very helpful. Chris * from http://topographica.org/ From bignose+hates-spam at benfinney.id.au Fri Sep 26 22:33:28 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 12:33:28 +1000 Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <dZOdnQINKORUEUDVnZ2dnUVZ_rvinZ2d@posted.usinternet> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> Message-ID: <87ej36uxl3.fsf@benfinney.id.au> George Sakkis <george.sakkis at gmail.com> writes: > On Sep 26, 9:30?pm, Grant Edwards <gra... at visi.com> wrote: > > I read the group via NNTP, and I find that blocking all articles > > posted from google.groups gets rid of all of the spam. > > ... along with a far from trivial (I guess) percentage of non-spam, > such as this post. As a Google user, you have (presumably) more clout with them than those of us who are not. Please pressure your provider to reduce the spam they output so the above drastic measure is not so attractive. Such pressure may be more effective if you *also* use an alternate NNTP provider that isn't such a spam-haven. -- \ ?I put contact lenses in my dog's eyes. They had little | `\ pictures of cats on them. Then I took one out and he ran around | _o__) in circles.? ?Steven Wright | Ben Finney From mail at timgolden.me.uk Wed Sep 17 04:17:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 17 Sep 2008 09:17:30 +0100 Subject: Modifying the system menu In-Reply-To: <bfa45e21-fb5e-454d-a4c2-e7cc00919f38@p31g2000prf.googlegroups.com> References: <bfa45e21-fb5e-454d-a4c2-e7cc00919f38@p31g2000prf.googlegroups.com> Message-ID: <48D0BD1A.2080700@timgolden.me.uk> raj.indian.08 at gmail.com wrote: > For (2) I wrote the following code for basic testing: > hwnd = win32gui.GetForegroundWindow() > hw = win32gui.GetSystemMenu(hwnd, False) > if hw != None: > win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); > > and it shows the following error: pywintypes.error: (1401, > 'AppendMenu', 'Invalid menu handle.') Works for me. The following adds a separator and the string "Hello" to my (Console) window's system menu <code> import win32con import win32gui hwnd = win32gui.GetForegroundWindow () hmenu = win32gui.GetSystemMenu (hwnd, False) win32gui.AppendMenu (hmenu, win32con.MF_SEPARATOR, 0, '') win32gui.AppendMenu (hmenu, win32con.MF_STRING, 100, 'Hello') </code> TJG From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 8 11:57:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Sep 2008 17:57:57 +0200 Subject: Dictionaries and loops In-Reply-To: <069dc97f-9a6f-4adf-9667-c02a352836b3@b1g2000hsg.googlegroups.com> References: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> <48c52c54$0$16982$426a74cc@news.free.fr> <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> <48c53322$0$3460$426a74cc@news.free.fr> <069dc97f-9a6f-4adf-9667-c02a352836b3@b1g2000hsg.googlegroups.com> Message-ID: <48c54b07$0$18786$426a74cc@news.free.fr> Mike P a ?crit : > Thanks for the solution above, > > The raw data looked like > User-ID,COUNTS > 576460840144207854,6 > 576460821700280307,2 > 576460783848259584,1 > 576460809027715074,3 > 576460825909089607,1 > 576460817407934470,1 > > and i used > > CSV_INPUT1 = "C:/Example work/Attr_model/Activity_test.csv" > fin1 = open(CSV_INPUT1, "rb") > reader1 = csv.DictReader((fin1), [], delimiter=",") This should have been: reader1 = csv.DictReader(fin1, delimiter=",") or even just csv.DictReader(fin1), since IIRC ',' is the default delimiter (I'll let you check this by yourself...). with which you would have: [ {'User-ID':'576460840144207854', 'count':'6'}, {'User-ID':'576460821700280307', 'count':'2'}, # etc... ] > with the following outcome. > {None: ['User-ID', 'COUNTS']} > {None: ['576460840144207854', '6']} > {None: ['576460821700280307', '2']} > {None: ['576460783848259584', '1']} > {None: ['576460809027715074', '3']} > {None: ['576460825909089607', '1']} And you didn't noticed anything strange ??? > So i can see csv.reader is what i should have been using With only 2 values, DictReader is probably a bit overkill, yes. > Thanks for the help You're welcome. But do yourself a favour: take time to *learn* Python - at least the very basic (no pun) stuff like iterating over a sequence. From ewertman at gmail.com Sun Sep 7 18:28:11 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sun, 7 Sep 2008 18:28:11 -0400 Subject: lacking follow-through In-Reply-To: <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> Message-ID: <92da89760809071528u7323d5d8g3dde98ddf0d042b7@mail.gmail.com> +1 Bot From robin at alldunn.com Mon Sep 29 18:46:08 2008 From: robin at alldunn.com (Robin Dunn) Date: Mon, 29 Sep 2008 15:46:08 -0700 Subject: [wxpython-users] ANN: wxPython 2.8.9.0 In-Reply-To: <1222647042.29889.1.camel@generator> References: <48DFD492.1090905@alldunn.com> <1222647042.29889.1.camel@generator> Message-ID: <48E15AB0.4050909@alldunn.com> Clay Hobbs wrote: >> > > I'm curious, why do you package wxPython for Fedora 6 and 7, but not 8 > and 9? It's only because I haven't taken the time to update and retest those build boxes. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 19:12:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 23:12:33 GMT Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <f8c5f1de-d358-468b-81fd-aa8108d8f7e0@q26g2000prq.googlegroups.com> <mailman.668.1220827338.3487.python-list@python.org> <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> Message-ID: <00d45a34$0$20306$c3e8da3@news.astraweb.com> On Sun, 07 Sep 2008 15:59:52 -0700, John Machin wrote: > On Sep 8, 8:42?am, "James Mills" <prolo... at shortcircuit.net.au> wrote: >> On Mon, Sep 8, 2008 at 8:37 AM, John Machin <sjmac... at lexicon.net> >> wrote: > >> > There seems to be an implicit assumption in the answers so far that >> > your mapping is a 1:1 mapping of all possible input keys. >> >> > If it doesn't include all possible input keys, answers will crash >> > with a KeyError. If there are any many:1 elements in the mapping (for >> > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code >> > in some checks for this. >> >> You are quite right! But then he/she didn't ask for this right ? :) >> >> > What do you mean by "this right"? Perhaps the Divine Right of OPs, > managers, examiners, business analysts, etc never to give a complete > spec up front and never to contemplate the consequences of Murphy's Law? I *think* that what James Mills meant was: "But then he/she didn't ask for this comma right?" -- Steven From 9847733785.man at gmail.com Thu Sep 4 10:08:01 2008 From: 9847733785.man at gmail.com (9847733785.man at gmail.com) Date: Thu, 4 Sep 2008 07:08:01 -0700 (PDT) Subject: Investments Are Faltering in Chrysler and GMAC Message-ID: <c9b3dc16-f56f-4383-a060-d8051c4ca455@p31g2000prf.googlegroups.com> Mr. Feinberg?s giant investment fund, Cerberus Capital Management, is racing to salvage multibillion-dollar investments in Chrysler, the smallest of the Detroit automakers, and GMAC, the financing arm of General Motors. But for Cerberus, named after the mythological three-headed dog who guards the gates of hell, the news keeps getting worse. On Wednesday, Chrysler, which owns the Jeep and Dodge brands, said its sales in the United States fell by a third in August ? nearly twice the industry average ? as the downturn in the auto business dragged on. Honda eclipsed Chrysler as the nation?s No. 4 seller of cars, and Nissan is closing in fast. The same day, GMAC, in which Cerberus holds a 51 percent stake, said it was trying to stanch the bleeding from a business that was supposed to be immune to the ups and downs of the car industry: home mortgage lending. GMAC and its home loan unit, Residential Capital, announced that they would dismiss 5,000 employees, or 60 percent of the unit?s staff, and close all 200 of its retail mortgage branches. It is quite a comedown for Mr. Feinberg, who founded Cerberus in 1992 with $10 million and was initially hailed as a savior at Chrysler. Over the years, Cerberus excelled by gaining control of companies in bankruptcy and nursing them back to financial health. Now, Mr. Feinberg?s purchase of Chrysler and his deal for GMAC have knocked Cerberus down a peg. ?Early on, in the Cerberus deal for Chrysler, when it first did these auto industry investments, the story was about how big and influential these funds are, that they think they can buy these iconic industrial companies,? said Colin C. Blaydon, director of the Center for Private Equity and Entrepreneurship at the Tuck School of Business at Dartmouth College. ?So far, it does not seem to be working out well for them.? Chrysler is still recovering from its split a year ago from its German partner, Daimler, and is undergoing a big revamping under Cerberus. Top executives at Cerberus have said they are determined to fix the company and that their $7.4 billion investment will pay off. A Cerberus spokesman said in a statement on Wednesday that it remained confident in its management of Chrysler and GMAC. ?No one is pleased with current market conditions,? he said. ?However, Cerberus is a patient investor and not a market timer, and we take a long-term view of our investments. Our funds are structured accordingly.? Mr. Feinberg hired Robert L. Nardelli, the former chief executive of Home Depot, to turn Chrysler around. Their plan hinges on new offerings beginning in 2010. Since Cerberus acquired Chrysler, the automaker has been trying to squeeze out costs. It has announced the elimination of 28,000 jobs and sold $500 million worth of assets. Last week, Chrysler announced that it was studying a sale of its Dodge Viper sports car business. But like its larger competitors, General Motors and Ford Motor, Chrysler has faced questions over its ability to ride out a downturn in American auto sales that is expected to stretch through 2009. All three Detroit automakers have been hit hard by the sharp decline in sales of pickup trucks, sport utility vehicles and vans that followed the rise in gas prices this year. Chrysler, which has released limited financial data since Cerberus bought it, ended June with $11.7 billion in cash and had earnings before interest, tax, depreciation and amortization of $1.1 billion in the first half of the year. But with limited access to financial data, some analysts are skeptical of its overall health. The news on Wednesday from GMAC, meantime, underscored that Cerberus also must contend with the housing slump, which has led to huge losses at lenders across the spectrum. That includes Residential Capital, which became one of the nation?s biggest mortgage providers and plunged into the market for riskier home loans that could not be sold to Fannie Mae or Freddie Mac, the mortgage finance giants that have run into trouble themselves. Now, many of those loans are defaulting as home prices fall and the economy weakens. This summer, Residential Capital and its bondholders restructured $14 billion in bonds to ease its debt burden. That restructuring and new loans from GMAC have bought the company time to work out its problems, but analysts say it may not be enough to save the firm from rising defaults on mortgages. Residential Capital bonds are trading at about 70 cents on the dollar. ?They have some time,? said Andrew Feltus, a bond fund manager at Pioneer Investments. But, he added, ?This environment is going against them.? www.my-quickloans.com/finance From steven at REMOVE.THIS.cybersource.com.au Mon Sep 22 05:32:39 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 09:32:39 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> Message-ID: <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: > Steven D'Aprano a ?crit : >> I have a class which is not intended to be instantiated. Instead of >> using the class to creating an instance and then operate on it, I use >> the class directly, with classmethods. Essentially, the class is used >> as a function that keeps state from one call to the next. >> >> The problem is that I don't know what to call such a thing! "Abstract >> class" isn't right, because that implies that you should subclass the >> class and then instantiate the subclasses. >> >> What do you call such a class? >> >> > <nitpick> > Err... A possible design smell ?-) > </nitpick> > > > More seriously: this looks quite like a singleton, which in Python is > usually implemented way more simply using a module and plain functions. I really don't know why everyone thinks I want a Singleton. I want to uncouple objects, not increase the coupling. Consider a factory function: def factory(x): # a toy example alist = [x] def foo(): return alist return foo Now suppose we "instantiate" the factory (for lack of a better term): >>> f1 = factory(0) >>> f2 = factory(0) Even though f1 and f2 have the same behaviour, they are obviously not the same object. And although both return a list [0], it is not the same list: >>> f1() == f2() == [0] True >>> f1() is f2() False They have a (very little) amount of state, which is *not* shared: >>> L = f1() >>> L.append(1) >>> f1() [0, 1] >>> f2() [0] But there's only a limited amount of state that functions carry around. I can give them more state like this: >>> f1.attr = 'x' but it isn't good enough if the function needs to refer to it's own state, because functions can only refer to themselves by name and the factory can't know what name the function will be bound to. As far as I know, the only objects that know how to refer to themselves no matter what name they have are classes and instances. And instances share at least some state, by virtue of having the same class. (Pedants will argue that classes also share state, by virtue of having the same metaclass. Maybe so, but that's at a deep enough level that I don't care.) I'm now leaning towards just having factory() instantiate the class and return the instance, instead of having to do metaclass chicanery. Because the class is built anew each time by the factory, two such instances aren't actually sharing the same class. I think that will reduce confusion all round (including mine!). Hopefully now that I've explained what I want in more detail, it won't seem so bizarre. Factory functions do it all the time. Is there a name for this pattern? Thanks to everyone who commented, your comments helped me reason out a better alternative to what I first suggested. -- Steven From gabriel.rossetti at arimaz.com Wed Sep 24 02:22:51 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 24 Sep 2008 08:22:51 +0200 Subject: python freeze help In-Reply-To: <c2127bd2-de5d-49ac-be2c-af95a60b4525@p25g2000hsf.googlegroups.com> References: <mailman.1397.1222164522.3487.python-list@python.org> <c2127bd2-de5d-49ac-be2c-af95a60b4525@p25g2000hsf.googlegroups.com> Message-ID: <48D9DCBB.90502@arimaz.com> Mike Driscoll wrote: > On Sep 23, 5:01 am, Gabriel Rossetti <gabriel.rosse... at arimaz.com> > wrote: > >> Hello everyone, >> >> I'm trying to use python's freeze utility but I'm running into problems. >> I called it like this : >> >> python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py >> ~/Documents/Code/Python/src/jester/service.py -m jester >> >> then I did : make >> >> then I tried to run it : ./service >> >> and I get this : >> >> grossetti at desktop-01:~/tmp/freeze$ ./service >> Traceback (most recent call last): >> File "/home/grossetti/Documents/Code/Python/src/jester/service.py", >> line 16, in <module> >> from jester import constants, utils >> File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line >> 20, in <module> >> from twisted.internet.protocol import Protocol, ClientCreator >> File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", >> line 17, in <module> >> from zope.interface import implements >> File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in >> <module> >> pkg_resources.declare_namespace('zope') >> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, >> in declare_namespace >> _handle_ns(packageName, path_item) >> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, >> in _handle_ns >> path = module.__path__; path.append(subpath) >> AttributeError: 'str' object has no attribute 'append' >> Error in sys.excepthook: >> Traceback (most recent call last): >> File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line >> 38, in apport_excepthook >> from apport.packaging_impl import impl as packaging >> File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in >> <module> >> from apport.report import Report >> File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in >> <module> >> from problem_report import ProblemReport >> File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in >> <module> >> from email.MIMEMultipart import MIMEMultipart >> File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__ >> __import__(self.__name__) >> ImportError: No module named multipart >> > > > I've gotten this error from py2exe before. I'm not sure how freeze > works, but in py2exe I had to make sure the email package wasn't being > accidentally excluded and explicitly included. > > > I tried that (-m email), didn't work, I added -E and I get this : There are some missing modules: ['Carbon.File', 'Carbon.Folder', 'Carbon.Folders', 'EasyDialogs', 'FCNTL', 'MacOS', 'SOCKS', '_dummy_threading', '_emx_link', '_md5', '_sha', '_sha256', '_sha512', '_subprocess', '_winreg', '_xmlplus', 'ce', 'email.Encoders', 'email.Generator', 'email.Iterators', 'email.MIMEBase', 'email.MIMEMultipart', 'email.MIMEText', 'email.Utils', 'gestalt', 'ic', 'java.lang', 'mac', 'msvcrt', 'nt', 'org.python.core', 'os.path', 'os2', 'pywintypes', 'riscos', 'riscosenviron', 'riscospath', 'rourl2path', 'sgi', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security'] so I tried to see if it existed : >>> import email >>> email.MIMEMultipart <email.LazyImporter object at 0xb7d6a62c> >>> maybe this is the problem, an email.MIMEMultipart object isn't what is returned but instead an email.LazyImporter object is, so freeze isn't happy... any ideas on how to solve this? >> Original exception was: >> Traceback (most recent call last): >> File "/home/grossetti/Documents/Code/Python/src/jester/service.py", >> line 16, in <module> >> from jester import constants, utils >> File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line >> 20, in <module> >> from twisted.internet.protocol import Protocol, ClientCreator >> File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", >> line 17, in <module> >> from zope.interface import implements >> File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in >> <module> >> pkg_resources.declare_namespace('zope') >> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, >> in declare_namespace >> _handle_ns(packageName, path_item) >> File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, >> in _handle_ns >> path = module.__path__; path.append(subpath) >> AttributeError: 'str' object has no attribute 'append' >> >> Does anyone have any ideas as of why I get this? >> >> Thank you, >> Gabriel >> > > I don't know what this second error is... > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Thu Sep 11 13:16:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 19:16:40 +0200 Subject: How to Determine Name of the Day in the Week In-Reply-To: <fee514130809111011m8af23aas7c02512de1a4f6cb@mail.gmail.com> References: <fee514130809111011m8af23aas7c02512de1a4f6cb@mail.gmail.com> Message-ID: <gabjpp$as1$2@ger.gmane.org> Henry Chang wrote: > Instead of getting integers with weekday(), Monday == 0 ... Sunday == 6; > is there a way to get the actual names, such as "Monday ... Sunday"? I > would like to do this without creating a data mapping. :) if you have a datetime or date object, you can use strftime with the appropriate formatting code. see the library reference for details. if you have the weekday number, you can use the calender module: >>> import calendar >>> calendar.day_name[0] 'Monday' (the latter also contains abbreviated day names, month names, and a bunch of other potentially useful functions and mappings.) </F> From dear.jay.logan at gmail.com Mon Sep 22 09:07:47 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 22 Sep 2008 06:07:47 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <ugv*ncEns@news.chiark.greenend.org.uk> Message-ID: <fc7f0776-6015-4020-97d7-7845f609ce4f@26g2000hsk.googlegroups.com> On Sep 22, 7:32?am, Sion Arrowsmith <si... at chiark.greenend.org.uk> wrote: > josh logan ?<dear.jay.lo... at gmail.com> wrote: > > >sorted(P) # throws TypeError: unorderable types Player() < Player() > > >The sorted function works when I define __lt__. > >I must be misreading the documentation, because I read for the > >documentation __cmp__ that it is called if none of the other rich > >comparison functions are defined. > > You're either misreading or forgetting that __eq__ and __ne__, > which you define, are rich comparison functions. __cmp__ will only > be called for a comparison when *none* of the rich comparison > functions are defined, not just the one in question. > > -- > \S -- si... at chiark.greenend.org.uk --http://www.chaos.org.uk/~sion/ > ? ?"Frankly I have no feelings towards penguins one way or the other" > ? ? ? ? -- Arthur C. Clarke > ? ?her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump Hello Sion, When I don't define the __eq__ and __ne__ comparison functions, the same unexpected behavior occurs. From god1124 at gmail.com Fri Sep 5 02:59:37 2008 From: god1124 at gmail.com (Dream) Date: Thu, 4 Sep 2008 23:59:37 -0700 (PDT) Subject: Tkinter Radio button on the second window References: <e5da0605-0dc4-41fe-9a9f-fa75b9094e5a@b30g2000prf.googlegroups.com> <mailman.526.1220585136.3487.python-list@python.org> Message-ID: <351395f5-5052-4722-97ea-e568db4d6fc6@o40g2000prn.googlegroups.com> Thank you very much. Now I use "window2=Toplevel()" to create the second window, and it works well. From iphthfu02 at sneakemail.com Tue Sep 2 12:27:29 2008 From: iphthfu02 at sneakemail.com (Dani) Date: 2 Sep 2008 16:27:29 -0000 Subject: Library/project for making an invitation-only website? Message-ID: <7502-61941@sneakemail.com> Hi. I want to create a website where new users need to be invited by an existing user in order to open an account. Think of it the way Orkut became popular. I need a library, or code from some project, that sends the invitations, keeps track of which user invited who, etc. I'm sure there's already some code out there that performs these tasks. Drupy maybe? Could anybody recommend me some library/project for these tasks? Thank you in advance. From geoff.bache at jeppesen.com Wed Sep 10 16:52:37 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Wed, 10 Sep 2008 13:52:37 -0700 (PDT) Subject: Persuading ConfigParser to give me the section elements in the same order as the file Message-ID: <4566f721-028d-4079-90d8-7818d69d18b3@34g2000hsh.googlegroups.com> Hi all, I recently needed to parse a file that was perfect for ConfigParser apart from one thing: the elements in the sections, although definitions, could in some cases clash with each other and therefore it was important to be able to retrieve them in the same order as they appeared in the file. Unfortunately ConfigParser uses ordinary dictionaries for the section elements and they are therefore returned in an arbitrary order. The only solution I found was to copy ConfigParser.py and replace all the dictionaries with "sequential dictionaries" which are exactly like dictionaries except that elements are returned in the order they were inserted. (see http://home.arcor.de/wolfgang.grafen/Python/Modules/seqdict/Seqdict.html) I wonder if there was a better way? For example, is there any hook that could modify what is created by the statement x = {} I tried setting __builtins__.dict = ndict.seqdict But that didn't seem to have any effect on the above statement. As a secondary question, I find sequential dictionaries to be an essential part of programming in Python and I use them all the time. I wondered a bit if there were any plans or proposals to include them as part of the Python library? Regards, Geoff Bache From castironpi at gmail.com Sat Sep 27 08:18:33 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 05:18:33 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> Message-ID: <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> On Sep 26, 1:04?pm, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 26, 11:43?am, "Tim Rowe" <digi... at gmail.com> wrote: > > > 2008/9/26 Steven D'Aprano <st... at remove-this-cybersource.com.au>: > > > > I don't have any objective numbers, but subjectively it seems to me that > > > the number of spams is significantly higher, but not so high as to be a > > > major nuisance. > > > I consider *any* spam to be a major nuisance, but I don't see them as > > being the fault of python-list which seems to do a pretty good job of > > blocking them > > I think in June and July they were selling watches a lot which I > haven't noticed recently. Gucci 104 G-Bandeau Watches - Gucci Watches Discount Rolex Oyster Perpetual Lady Datejust Pearlmaster 18kt Yellow Gold Diamond Ladies Watch 80318C Cartier Must 21 Watches - Cartier Watches Discount I speak too soon. From bdesth.quelquechose at free.quelquepart.fr Tue Sep 23 13:23:16 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 19:23:16 +0200 Subject: finding domain name In-Reply-To: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> Message-ID: <48d941f0$0$3738$426a74cc@news.free.fr> Bobby Roberts a ?crit : > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/xxxxx/ > > where xxxxx represents the domain name. > > How can I find the domain name of the current url being viewed. What are you using exactly ? cgi ? wsgi ? Else ? From fredrik at pythonware.com Mon Sep 1 11:52:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Sep 2008 17:52:31 +0200 Subject: Printing list of dates starting today In-Reply-To: <4v1ob4tgk0u4jhtobisaid1g9pst0ic011@4ax.com> References: <4v1ob4tgk0u4jhtobisaid1g9pst0ic011@4ax.com> Message-ID: <g9h342$fav$1@ger.gmane.org> Luka Djigas wrote: > please, I need your help. I'm new to python, so I don't know if this > will seem like a stupid question to some of you ... > I have a need to write to a file (or just print on screen, that part > doesn't matter at this point) a list of dates, starting today. For > example: > > 02.09.2008. tue > 03.09.2008. wed > et cetera > > Is there some intristic function in python which can help me with this > or do I have to do the calendar calculation by hand ? >>> import datetime >>> # see: http://docs.python.org/lib/module-datetime.html >>> d = datetime.date.today() >>> str(d) '2008-09-01' >>> d.strftime("%d.%m.%Y. %a") '01.09.2008. Mon' >>> # see http://docs.python.org/lib/module-time.html#l2h-2826 >>> d.strftime("%d.%m.%Y. %a").lower() '01.09.2008. mon' >>> for i in range(10): ... print d.strftime("%d.%m.%Y. %a").lower() ... d += datetime.timedelta(days=1) ... 01.09.2008. mon 02.09.2008. tue 03.09.2008. wed 04.09.2008. thu 05.09.2008. fri 06.09.2008. sat 07.09.2008. sun 08.09.2008. mon 09.09.2008. tue 10.09.2008. wed </F> From callen314 at gmail.com Thu Sep 11 17:02:25 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 11 Sep 2008 14:02:25 -0700 (PDT) Subject: Adding environment variables to bash. References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> <gaan73$so4$1@ger.gmane.org> <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> <mailman.860.1221126015.3487.python-list@python.org> <48c97eaf$0$12022$426a74cc@news.free.fr> Message-ID: <de654456-3b96-4e42-b699-397b94388e2c@25g2000prz.googlegroups.com> On Sep 11, 10:25 am, nntpman68 <news1... at free.fr> wrote: > >> doesn't exactly work for Python scripts, though: > > >> $ cat env.py > >> #!/usr/bin/env python > >> import os > >> os.environ["TEST"] = "hello" > > >> $ . ./env.py && env | grep TEST > >> import: unable to open X server `'. > >> bash: os.environ[TEST]: command not found > > >> </F> > > There's two options for the desperate ones. > > 1. Assuming the python script doesn't want to print anything useful > ========================================================================= > > the python script just prints the exoprt commands and is > being called via backticks from a shell code snipped being sourced with . > > #-------- mypythonfile.py ------------------------ > #!/usr/bin/env python > value = myfavourite_python_function() > print 'export ENV_VAR="%s"' ^ value > #--------------- end of file -------------- > > #----------------- my_wrapper_file.sh ------------------ > `./mypythonfile.py` > # file end > > and then you call > . ./my_wrapper_file.sh > > 2._ Pytho script wants to display something and set a variable > =================================================================== > > a file being invoked with . calls the python script (which will create a > small file with variables to be set). > then this created file is being sourced > > #-------- mypythonfile.py ------------------------ > #!/usr/bin/env python > value = myfavourite_python_function() > file('my_export_commands.sh','w').write('export ENV_VAR="%s"\n' % value) > #--------------- end of file -------------- > > #----------------- my_wrapper_file.sh ------------------ > ./mypythonfile.py > . ./my_export_commands.sh > # file end > > bye > > N > > Fredrik Lundh wrote: > > John Lawrence wrote: > > >> You can make a command use the current shell though if you use the '.' > >> command e.g.: > > >> jl > cat env.sh > >> export TEST='hello' > > >> jl > ./env.sh && env | grep TEST #Doesn't set TEST in parent > >> shell > >> jl > . ./env.sh && env | grep TEST #Adding '. ' before the > >> command uses the same shell > >> TEST=hello > > > doesn't exactly work for Python scripts, though: > > > $ cat env.py > > #!/usr/bin/env python > > import os > > os.environ["TEST"] = "hello" > > > $ . ./env.py && env | grep TEST > > import: unable to open X server `'. > > bash: os.environ[TEST]: command not found > > > </F> oooh, clever but also... teh evil! Ok not evil, but teh not-pretty. But you did say "for the desperate" so good on you. cheers. From hrishys at yahoo.co.uk Thu Sep 25 06:12:54 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 10:12:54 +0000 (GMT) Subject: Linq to Python In-Reply-To: <j_SdnXsBqed8ekfVnZ2dnUVZ_srinZ2d@posted.usinternet> Message-ID: <180155.11709.qm@web27406.mail.ukl.yahoo.com> Hi Grant haha :-) i discounted that perspective :-) regards Hrishy --- On Thu, 25/9/08, Grant Edwards <grante at visi.com> wrote: > From: Grant Edwards <grante at visi.com> > Subject: Re: Linq to Python > To: python-list at python.org > Date: Thursday, 25 September, 2008, 2:22 AM > On 2008-09-24, Bruno Desthuilliers > <bdesth.quelquechose at free.quelquepart.fr> wrote: > > hrishy a ?crit : > > (snip) > > > > > >> I apologise > >> (I thought Python programmers were smart and they > did know what LINQ was) > > > > Is there really any relation between "being > smart" and knowing anything > > about the latest MS fad ? > > God, I hope not -- or I'd rather be stupid. > > -- > Grant > > -- > http://mail.python.org/mailman/listinfo/python-list From arnodel at googlemail.com Fri Sep 12 16:59:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 12 Sep 2008 13:59:49 -0700 (PDT) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> <mailman.930.1221232940.3487.python-list@python.org> <005ca418-9e1a-424b-b4d4-823427584424@x35g2000hsb.googlegroups.com> Message-ID: <b1cee41e-70cb-4932-90cb-a29b9d8b0624@z72g2000hsb.googlegroups.com> On Sep 12, 4:30?pm, Bojan Mihelac <bmihe... at gmail.com> wrote: > On Sep 12, 5:21?pm, Christian Heimes <li... at cheimes.de> wrote: > > > Bojan Mihelac wrote: > > > I guess A class not yet exists in line 4. Is it possible to achive > > > adding dynamic attributes without using exec? > > > Correct, the class doesn't exist until the end of the class body. You > > can either do it outside the class definition or you can use a metaclass. > > > Christian > > thanks, can you give example on using a metaclass? class MoreMeta(type): def __init__(self, name, bases, attrs): more = attrs.get('moreattrs') if more: for attr, val in more.iteritems(): setattr(self, attr, val) class MoreObject(object): __metaclass__ = MoreMeta class A(MoreObject): moreattrs = {} for i in '12': moreattrs['title_' + i] = int(i) >>> A.title_1 1 >>> A.title_2 2 >>> -- Arnaud From castironpi at gmail.com Thu Sep 4 23:28:34 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 20:28:34 -0700 (PDT) Subject: xml + mmap cross References: <a27b2e33-bddb-407e-b2ea-895dc78c7090@r15g2000prd.googlegroups.com> <6a7336f2-8f71-47c2-88d5-d5172f14ce44@k36g2000pri.googlegroups.com> Message-ID: <c3c94c2a-3507-4d31-b29b-3a2b06eb8b05@k7g2000hsd.googlegroups.com> On Sep 4, 7:54?pm, alex23 <wuwe... at gmail.com> wrote: > On Sep 4, 8:31?am, castironpi <castiro... at gmail.com> wrote: > > > Any interest in pursuing/developing/working together on a mmaped-xml > > class? ?Faster, not readable in text editor. > > XML is text-based, so it should -always- be readable in a text editor. > It's part of the definition, I believe. > > However, an implementation of one of the alternative binary XML > formats would probably be very welcome. > > Fast Infoset:http://www.itu.int/rec/T-REC-X.891-200505-I/en > EXI:http://www.w3.org/TR/2007/WD-exi-20070716/ > > I don't know enough about either format to say if it would be > possible, but an implementation that conformed to the ElementTree API > could be a big win. I was thinking something much less restrictive than the two links. Since it's not text, I'm not sure it event counts as structured markup. More generic, something like hierarchical 'tag-content-child' pairs. Here's what the xml.etree.ElementTree API says: Each element has a number of properties associated with it: - a tag which is a string identifying what kind of data this element represents (the element type, in other words). - a number of attributes, stored in a Python dictionary. - a text string. - an optional tail string. - a number of child elements, stored in a Python sequence Since all of these would be buffer-based representations, the attribute list would merely implement the mapping-object protocol, not be in a true dictionary. The strings would be stored as offsets to length-prefixed buffer segments. Each node would look roughly like: tag_offset, first_attr, text_offset, tail_offset, first_child, prev_sibling, next_sibling, parent Attributes would look like: key_offset, value_offset, prev_attr, next_attr, node These are all integers representing offsets elsewhere into the map. A short observation: >>> a= e.XML( '<a><b>abc</b></a>' ) >>> a.getchildren()[0].text 'abc' >>> a.getchildren()[0].text= 'ab<' >>> e.tostring(a) '<a><b>ab<</b></a>' >>> e.XML(_) <Element a at c2c3f0> >>> _.getchildren()[0].text 'ab<' The current implementation supports round trips between special characters '<' and markup '<', which I propose to support as well. Of course, you'd have to garbage collect removed nodes by hand, on any deletions. Also, poss. change subject to: ElementTree + mmap cross. From deets at nospam.web.de Tue Sep 2 11:16:17 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Sep 2008 17:16:17 +0200 Subject: dict.update In-Reply-To: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> Message-ID: <6i53m1Fo1a1aU1@mid.uni-berlin.de> Mike P schrieb: > Hi All, > > I have two dictionaries e.g > dict1 = {123:3,234:5,456:3} > dict2 = {123:4,157:2,234:5,456:3,567:2} > > I want to merge these two dictionaries together so i have a resultant > dictionary of: > > dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]} > > As later on i want to write a csv file that would have the form > > id var1 var2 > 123 4 3 > 157 2 0 > > i looks like the dict.update looks almost there but i can't get it to > work properly, can anyone offer any advise? > res = {} for d in dict1, dict2: for key, value in d.iteritems(): res.setdefault(key, []).append(value) Diez From rogeruclan at gmail.com Wed Sep 17 08:23:47 2008 From: rogeruclan at gmail.com (RLC) Date: Wed, 17 Sep 2008 05:23:47 -0700 (PDT) Subject: help on python SWIG C++ extension References: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> <i181d4pcq18597iljsn6o5ftj9h8250sr9@4ax.com> Message-ID: <d5e52c98-2947-452b-9d6a-a04d311ca6f8@l64g2000hse.googlegroups.com> Thanks a lot, Tim and Diez, Merci Beaucoup!! I strongly suspect the error was caused by the memory operation. I made some modifications only on PolygonMesh definition. And now I have no annoying warnings. PolygonMesh *new_PolygonMesh() { PolygonMesh *p = new PolygonMesh; // p = (PolygonMesh *)malloc(sizeof(PolygonMesh)); // p->vertices.clear(); // p->polygonNbVertices.clear(); // p->polygonStartVertexIndex.clear(); // p->polygonVerticesIndices.clear(); // p->uvs.clear(); // p->polygonNbUVs.clear(); // p->polygonStartUVIndex.clear(); // p->polygonUVsIndices.clear(); return p; } void delete_PolygonMesh(PolygonMesh *p) { free(p); } when I run below script, it works well without any warning #!/usr/local/bin/python import tdimport a = tdimport.PolygonMesh() a.appendvertex(tdimport.Vertex(0.0,0.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,0.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,0.0)) a.appendvertex(tdimport.Vertex(0.0,1.0,0.0)) a.appendvertex(tdimport.Vertex(0.0,0.0,1.0)) a.appendvertex(tdimport.Vertex(1.0,0.0,1.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,1.0)) a.appendvertex(tdimport.Vertex(0.0,1.0,1.0)) a.appendpolygon([0,3,2,1]) a.appendpolygon([0,1,5,4]) a.appendpolygon([1,2,6,5]) a.appendpolygon([2,3,7,6]) a.appendpolygon([0,4,7,3]) a.appendpolygon([4,5,6,7]) print a.getpolygonverticesindices(0) print a.getpolygonverticesindices(1) print a.getpolygonverticesindices(2) print a.getpolygonverticesindices(3) print a.getpolygonverticesindices(4) print a.getpolygonverticesindices(5) del a Thanks again. Have a good day!!! Regards Roger On Sep 17, 8:16 am, Tim Roberts <t... at probo.com> wrote: > RLC <rogeruc... at gmail.com> wrote: > > >I am new to python SWIG. Recently I wrote a small program trying to > >import collada files(using colladadom) into python so I could use > >python cgkit to render them. However, during the progressing, I got > >some problems. Every time I quit from Python, I get a segmentation > >fault, although the main program runs well. I suspect it is because I > >wrapped std::vector objects in C struct and I did not release the > >memory properly. > > That won't cause a segmentation fault. However, I notice that you are > using "malloc" and "free" to allocate and free your objects. "stl" will > use "new" and "delete", and it's not always healthy to mix them. If I were > you, I'd replace this: > > > Vertex *v; > > v = (Vertex *)malloc(sizeof(Vertex)); > > with this, which is less typing: > Vertex * x = new Vertex; > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From bearophileHUGS at lycos.com Mon Sep 1 19:55:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Sep 2008 16:55:33 -0700 (PDT) Subject: Py 2.6 changes References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <00cc7976$0$20302$c3e8da3@news.astraweb.com> Message-ID: <fb60e830-1267-48c9-9b99-3352a1db64cc@i76g2000hsf.googlegroups.com> Steven D'Aprano: > productory() -- I don't know that function, and googling mostly comes up > with retail product searches. Do you mean product(), Darn my English, you are right, sorry, I meant a product() of course :-) Bye, bearophile From cjw at ncf.ca Sat Sep 20 07:12:42 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 20 Sep 2008 07:12:42 -0400 Subject: Not fully OO ? In-Reply-To: <48d4c11b$0$22877$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <gb2lri$fmd$1@theodyn.ncf.ca> candide wrote: > Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > > Thanks for any comment. "foreach: for x in array: statements Loops over the array given by array. On each iteration, the value of the current element is assigned to x and the internal array pointer is advanced by one. " This could be a useful addition to Python. numarray is no longer supported. It has been supplanted by numpy. How is OOP defined? Colin W. From mail at microcorp.co.za Sun Sep 21 01:51:32 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 21 Sep 2008 07:51:32 +0200 Subject: Ascii Menu I/O redirection Message-ID: <000f01c91bb0$e395a900$0d00a8c0@hendrik> Steven D'Aprano <steve at rem...source.com.au> wrote: >I'm not sure that closing stdin and stout are a good idea. This could >have side-effects for other parts of your program, and will almost >certainly end badly if you're running in the interactive interpreter. > Its a very simple thingy - there will only ever be one object - "The Console", or "The Connection" The close stuff was there because I thought it would be better to close the RS-232 port if I were using it. I only close it right at the end before exiting - but you are right. - if I invoke the interpreter with -i then it will be seriously broken. >Other than that, what you've done seems reasonable, although since every >instance of console() has the same state, I'd write it slightly >differently: > >class console(object): > """ > This spoofs a single file like object, using stdout & - in > (Minimalistic proof of concept implementation) > """ > read = sys.stdin.read > readline = sys.stdin.readline > write = sys.stdout.write > flush = sys.stdout.flush > closeout = sys.stdout.close > closein = sys.stdin.close > @classmethod > def close(cls): > cls.closein() > cls.closeout() Thanks. It looks neater without all the "self"s. Seems to me the next time someone complains about 'self' he should be told : "use class attributes and methods, and only one instance" *WEG* >> Questions are: >> >> Is this a reasonable way of doing this kind of thing? Is there a >> canonical or better way of doing it? Am I missing something? > >It seems to me that you might have been better off to write your program >to take two files, an input and an output, instead of forcing both to go >to the same file. > >if 'serial' in sys.argv: # for RS-232 i/o to terminal > infile = open('/dev/ttyS0','r+b') > outfile = infile > else: # console i/o > infile = sys.stdin > outfile = sys.stdout > This is weird - This is exactly how I started off - and then I thought about the errors, and I did not want to pass three files, so I started looking for one. :-) Reading your response, and thinking about what I have done, I get the feeling that its all too complicated - What I will probably end up doing would be to pass no file, and just use standard print statements and sys.stdin.readline, etc. Then if I redirect the stdin,-out and -err, the thing is sorted, without the necessity of jumping through OO hoops, as this class is the only one in the programme - all the rest are functions. It is impossible to think clearly all of the time. It is difficult to think clearly most of the time. In fact it is nice to have an occasional lucid thought... >Hope this helps. Yes it has. - Thanks for the input. - Hendrik -- Robert Wilensky: We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of William Shakespeare. Now, thanks to the Internet, we know this not true. From mercado949 at gmail.com Fri Sep 5 11:29:39 2008 From: mercado949 at gmail.com (mercado mercado) Date: Fri, 5 Sep 2008 11:29:39 -0400 Subject: Retrieving the name of the class calling an instance method Message-ID: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> In Python, is it possible for an instance method to know the name of the class which is calling it? For example, in the sample below, I would like for the someMethod method to print the name of the class calling it ("bar" in the first case, "again" in the second). --------------------------------------- class foo(): def someMethod(self): print x class bar(): def __init__(self): f = foo() f.someMethod() class again(): def __init__(self): f = foo() f.someMethod() bar() again() --------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080905/e93870b0/attachment-0001.html> From xpahos at gmail.com Fri Sep 5 07:28:14 2008 From: xpahos at gmail.com (phasma) Date: Fri, 5 Sep 2008 04:28:14 -0700 (PDT) Subject: Python and Cyrillic characters in regular expression References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> <mailman.497.1220550833.3487.python-list@python.org> Message-ID: <cb6b6ad1-1070-4b5c-8470-86815ce1beea@79g2000hsk.googlegroups.com> string = u"??????" (u'\u041f\u0440\u0438\u0432\u0435\u0442',) string = u"Hi.??????" (u'Hi',) On Sep 4, 9:53?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > phasma wrote: > > Hi, I'm trying extract all alphabetic characters from string. > > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE) > > buf = re.match(string) > > > But it's doesn't work. If string starts from Cyrillic character, all > > works fine. But if string starts from Latin character, match returns > > only Latin characters. > > can you provide a few sample strings that show this behaviour? > > </F> From uomiocenekidd at gmail.com Mon Sep 22 06:38:48 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:38:48 -0700 (PDT) Subject: download redtube videos - Free Message-ID: <0959566b-79a1-4b3f-a0ab-69f176b577f3@z66g2000hsc.googlegroups.com> download redtube videos . . . *******CLICK HERE******** http://vids365.cn/download-redtube-videos ***************************** . . . . . . . . . . . . download redtube videos From timr at probo.com Sat Sep 6 21:55:43 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 07 Sep 2008 01:55:43 GMT Subject: atomic section in code References: <mailman.636.1220738821.3487.python-list@python.org> Message-ID: <vpc6c499ji19r738libolckm2742j5k3af@4ax.com> "Hendrik van Rooyen" <mail at microcorp.co.za> wrote: > >Fredrik Lundh <fredr...ware.com> wrote: > >>sounds like he wants/needs non-cooperative, mandatory locking. More accurately, he THINKS he wants/needs mandatory locking. We need to find out what he's really trying to accomplish before we can suggest something that is actually achievable. >Could one get there using ctypes to disable interrupts? No. That can't be done in user mode in any operating system where Python runs. Even in kernel mode, it's not reliable, because disabling interrupts only affects one core. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dullrich at sprynet.com Tue Sep 9 11:58:06 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 09 Sep 2008 10:58:06 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <g9r7hq$ri6$1$8302bc10@news.demon.co.uk> <dullrich-33A94E.10163805092008@text.giganews.com> <b4f287a7-8e1f-4057-9711-2f2519869a10@m73g2000hsh.googlegroups.com> Message-ID: <dullrich-C33787.10580609092008@text.giganews.com> In article <b4f287a7-8e1f-4057-9711-2f2519869a10 at m73g2000hsh.googlegroups.com>, bearophileHUGS at lycos.com wrote: > David C. Ullrich: > > I didn't mention what's below because it doesn't seem > > likely that saying max([]) = -infinity and > > min([]) = +infinity is going to make the OP happy... > > Well, it sounds cute having Neginfinite and Infinite as built-int > objects that can be compared to any other type and are < of or > of > everything else but themselves. Like I said, I'm not going to say anything about how Python should be. If I were going to comment on that I'd say it would be cute but possibly silly to actually add to the core. But in the math library I made some time ago there was an AbsoluteZero with the property that when you added it to x you got x for any x whatever (got used as the default additive identity for classes that didn't have an add_id defined...) > Probably they can be useful as > sentinels, but in Python I nearly never use sentinels anymore, and > they can probably give some other problems... > > Bye, > bearophile -- David C. Ullrich From steve077 at gmail.com Wed Sep 17 13:18:31 2008 From: steve077 at gmail.com (Dude) Date: Wed, 17 Sep 2008 10:18:31 -0700 (PDT) Subject: Tkinter Label 'justify' Problem Message-ID: <8c8a2d86-007b-4e38-b0fc-bc6385b3a77a@t54g2000hsg.googlegroups.com> Hi All, I am fairly new to Python programming. I am working on a small Tkinter project and I think I am missing something, maybe you can help. The two lines below is all I have related to the Label widget: lblServer = Tkinter.Label(serverFrame, text='Server:', fg='black', justify='left', relief='groove') lblServer.place_configure(width=200, bordermode='inside') No matter what I change the 'justify' to whether it's 'lef', 'right', or 'center', it always seems to be in the center. I am also writing the keys from the Label widget to a file because this has me so baffled. That is below. Thank in advance for any help or direction you can give me. Steve P ---------- lblServer keys ----------------- activebackground : SystemButtonFace activeforeground : SystemButtonText anchor : center background : SystemButtonFace bd : 2 bg : SystemButtonFace bitmap : borderwidth : 2 compound : none cursor : disabledforeground : SystemDisabledText fg : black font : {MS Sans Serif} 8 foreground : black height : 0 highlightbackground : SystemButtonFace highlightcolor : SystemWindowFrame highlightthickness : 0 image : justify : left padx : 1 pady : 1 relief : groove state : normal takefocus : 0 text : NNTP Server: textvariable : underline : -1 width : 0 wraplength : 0 ---------- lblServer keys END ------------- From code at pizzashack.org Tue Sep 2 09:28:42 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 09:28:42 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i4pq5Fol29aU1@mid.uni-berlin.de> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> Message-ID: <20080902132842.GP29228@dragontoe.org> On Tue, Sep 02, 2008 at 12:27:49PM +0000, Marc 'BlackJack' Rintsch wrote: > > The Python class is a generalization of the standard Posix function of > > (almost) the same name: > > http://opengroup.org/onlinepubs/007908775/xsh/popen.html > > So it's a name of a *function* and it's a little bit unsuitable for a > *class*. As Jeremy wrote: the instances represent *processes* not > "popen"s, whatever that may be. I would argue that they don't represent processes at all; the object is a set of files which connect the standard I/O streams of a subprocess to its parent, and methods to operate on those files. The C library's popen() function, on which this class is based, provides a means to open a file and connect it to the standard steams of a subprocess, making it more closely analogous to what the Popen class does/provides. As such, "Popen" is a better name to describe this object than "subprocess" would be. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/d9dec87c/attachment-0001.sig> From jan.patrick.schaefer at googlemail.com Sun Sep 7 06:30:58 2008 From: jan.patrick.schaefer at googlemail.com (Jan =?UTF-8?B?U2Now6RmZXI=?=) Date: Sun, 07 Sep 2008 12:30:58 +0200 Subject: unexpected class behaviour Message-ID: <48c3ad5d@news.uni-ulm.de> Hi all, can anyone explain the behaviour of the following code sniplet: ---> schnipp <--- class Base(object): def __init__( self, lst=[] ): self.varlist = lst def addVar( self, var ): self.varlist.append(var) class Derived(Base): def __init__( self, var ): Base.__init__(self) self.addVar(var) vars = ['foo', 'bar'] for ivar in vars: obj = Derived(ivar) print ivar, obj, obj.varlist ---> schnapp <--- After running (Python 2.5.1), I get the following output: foo <__main__.Derived object at 0xb7c608cc> ['foo'] bar <__main__.Derived object at 0xb7c6092c> ['foo', 'bar'] So, I get two different objects, but how does the 'foo' get into the second varlist? I'm a little bit confused about this, any ideas? Thanks in advance Jan From nospam at example.com Sun Sep 28 05:21:30 2008 From: nospam at example.com (Erhard) Date: Sun, 28 Sep 2008 02:21:30 -0700 Subject: Calculating timespan Message-ID: <z0IDk.36$AK3.16@newsfe03.iad> I've been looking at the date/time classes and I'm at a loss as to how to do this (probably too used to other platforms). I have two date/time values. One represents 'now' and the other the last modified time of a file on disk (from stat). I need to calculate the difference in time (i.e., a 'timespan') between the two so I can tell if the file has been modified in the past X minutes and do something to it. Thanks =) From rf.egnaro at evetsrellum Sat Sep 20 12:27:55 2008 From: rf.egnaro at evetsrellum (Thoma) Date: Sat, 20 Sep 2008 18:27:55 +0200 Subject: How to make a reverse for loop in python? In-Reply-To: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <48d5248b$0$909$ba4acef3@news.orange.fr> Alex Snast a ?crit : > Hello > > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) for (i = 0; i < 10; i--) -> for i in range(10): for (i = 10; i >= 0; --i) -> for i in range(10,-1,-1): Thoma From simon.hibbs at gmail.com Wed Sep 17 09:05:59 2008 From: simon.hibbs at gmail.com (Simon Hibbs) Date: Wed, 17 Sep 2008 06:05:59 -0700 (PDT) Subject: Python OOP advice References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> <6089e023-18f6-4c93-a2a4-f933eac786b5@f63g2000hsf.googlegroups.com> Message-ID: <9317b769-0569-4ccf-b800-c400328ff579@m36g2000hse.googlegroups.com> Great contributions, thanks both of you. I'm self-tought when it comes to Python and OOP and I haven't yet grown an intuitive feel for how to do things sensibly. Simon From tino at wildenhain.de Fri Sep 26 07:23:04 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 13:23:04 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48dcc0ce$0$25400$426a34cc@news.free.fr> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> Message-ID: <48DCC618.9040907@wildenhain.de> Hi, Bruno Desthuilliers wrote: > bcurtu a ?crit : >> Hi, >> >> I have a BIIIIIG problem with the next query: >> >> cursor.execute(""" >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """,( eid_list)) >> >> eid_list is suppossed to be a list of ids = [1,5,9] >> >> How can I make it work? > > You have to build your sql statement in three stages: > > # stage 0: the template > sql_template = """ > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """ > > # stage 1: build correct place_holders string for the actual number > # of items in eid_list > place_holders = ", " .join("%s" for x in xrange(len(eid_list))) Hm. either ", ".join(["%s"]*len(eid_list)) or ", ".join("%s" for x in eid_list) should produce the same, wouldn't it? :-) > # stage 2 : build the effective sql statement > sql = sql_template % place_holders > > # ok, let's go: > cursor.execute(sql_template, eid_list) > > > NB : you can of course make it in a single statement, but readability > will suffer: > > cursor.execute( > """ > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """ % ", " .join("%s" for x in xrange(len(eid_list))), > eid_list > ) I'd think giving the arguments in a form of an array type should work too. At least in postgres there are references to do so. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/649f4088/attachment-0001.bin> From jaime.dyson at gmail.com Fri Sep 5 14:11:13 2008 From: jaime.dyson at gmail.com (jaime.dyson at gmail.com) Date: Fri, 5 Sep 2008 11:11:13 -0700 (PDT) Subject: "Full" element tag listing possible with Elementtree? References: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> <mailman.537.1220597014.3487.python-list@python.org> Message-ID: <7c184580-00ee-40ff-bcc0-1b2a60134fe0@i20g2000prf.googlegroups.com> On Sep 4, 11:43?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > jaime.dy... at gmail.com wrote: > > <a> > > ? <b att="atttag" content="b"> this is node b </b> > > ? <c> this is node c > > ? ? <d /> > > ? ? <e> this is node e </e> > > ? </c> > > ? <f> this is node f </f> > > </a> > > > I would want to print the following: > > > <a> > > <a> <b> > > <a> <b> text: this is node b > > <a> <c> > > <a> <c> text: this is node c > > <a> <c> <d> > > <a> <c> <e> > > <a> <c> <e> text: this is node e > > <a> <f> > > <a> <f> this is node f > > > Is there a simple way to do this? ?Any help would be appreciated. > > in stock ET, using a parent map is probably the easiest way to do this: > > ? ? ?http://effbot.org/zone/element.htm#accessing-parents > > that is, for a given ET structure "tree", you can do > > parent_map = dict((c, p) for p in tree.getiterator() for c in p) > > def get_parents(elem): > ? ? ?parents = [] > ? ? ?while 1: > ? ? ? ? ?elem = parent_map.get(elem) > ? ? ? ? ?if elem is None: > ? ? ? ? ? ? ?break > ? ? ? ? ?parents.append(elem) > ? ? ?return reversed(parents) > > for elem in tree.getiterator(): > ? ? ?print list(get_parents(elem)), elem > > </F> Fantastic. Thank you very much, Fredrik! And thanks for ET! From manfredpssnd6 at googlemail.com Tue Sep 23 14:44:34 2008 From: manfredpssnd6 at googlemail.com (manfredpssnd6 at googlemail.com) Date: Tue, 23 Sep 2008 11:44:34 -0700 (PDT) Subject: FREE INTERNATIONAL TRADE LEADS Message-ID: <4b1b2e21-0732-40d7-a3aa-07320f4905ef@k37g2000hsf.googlegroups.com> http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# http://groups.google.com/group/comp.lang.python/browse_thread/thread/33f3659cc4d30b22# From mail at timgolden.me.uk Tue Sep 16 04:04:49 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 09:04:49 +0100 Subject: PyMarshal Commands crash on Windows In-Reply-To: <d1c8807e-3853-4818-bd16-8926e2919aaf@z72g2000hsb.googlegroups.com> References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> <mailman.1015.1221420768.3487.python-list@python.org> <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> <d1c8807e-3853-4818-bd16-8926e2919aaf@z72g2000hsb.googlegroups.com> Message-ID: <48CF68A1.2070805@timgolden.me.uk> spammaster.10.webmaster at spamgourmet.com wrote: > Hi! > > Any ideas on it? (Haven't got the original post in front of me, but I'll guess anyway...) Was the Python you're using built with one compiler and runtime, while the extension / embedee you're building is built with another? I ask because the most frequently-touted example of cross-compiler or cross-runtime incompatibility on Windows is the FILE* structure. And I seem to remember you're using that to write the marshalled objects out.... ... just a wild guess TJG From tkpmep at hotmail.com Tue Sep 30 11:09:49 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Tue, 30 Sep 2008 08:09:49 -0700 (PDT) Subject: Finding subsets for a robust regression References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> <f5ac3b99-234c-4304-b3f0-2c1eff7cba12@y38g2000hsy.googlegroups.com> <mailman.1717.1222748264.3487.python-list@python.org> Message-ID: <441304ca-64e3-4ba2-bd18-5752cbb4bf23@y79g2000hsa.googlegroups.com> Thank you everyone, for your input. The help is much appreciated. Thomas Philips From bearophileHUGS at lycos.com Mon Sep 8 09:55:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 8 Sep 2008 06:55:52 -0700 (PDT) Subject: Dictionaries and loops References: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> Message-ID: <f4a71e9b-13ff-4f14-8fd7-26da4726c979@d77g2000hsb.googlegroups.com> Few solutions, not much tested: data = """{None: ['User-ID', 'Count']} {None: ['576460847178667334', '1']} {None: ['576460847178632334', '8']}""" lines = iter(data.splitlines()) lines.next() identity_table = "".join(map(chr, xrange(256))) result = {} for line in lines: parts = line.translate(identity_table, "'[]{},").split() key, val = map(int, parts[1:]) assert key not in result result[key] = val print result (With Python 3 finally that identity_table can be replaced by None) # -------------------------------------- import re patt = re.compile(r"(\d+).+?(\d+)") lines = iter(data.splitlines()) lines.next() result = {} for line in lines: key, val = map(int, patt.search(line).groups()) assert key not in result result[key] = val print result # -------------------------------------- from itertools import groupby lines = iter(data.splitlines()) lines.next() result = {} for line in lines: key, val = (int("".join(g)) for h,g in groupby(line, key=str.isdigit) if h) assert key not in result result[key] = val print result Bye, bearophile From fredrik at pythonware.com Fri Sep 5 13:30:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 19:30:33 +0200 Subject: atomic section in code In-Reply-To: <6ici7gFo8e4nU1@mid.uni-berlin.de> References: <a475a219-1577-4018-a541-5b05c87f6f71@i76g2000hsf.googlegroups.com> <mailman.544.1220605512.3487.python-list@python.org> <c0632676-51ab-4cf6-a6a7-f2f089196d57@m45g2000hsb.googlegroups.com> <6ici7gFo8e4nU1@mid.uni-berlin.de> Message-ID: <g9rqbq$r5e$1@ger.gmane.org> Diez B. Roggisch wrote: > AFAIC that kind of mutual exclusion is what atomicity is about. What > else do you expect to happen? sounds like he wants/needs non-cooperative, mandatory locking. </F> From spamcomefindmeplease at gmail.com Sat Sep 27 05:21:06 2008 From: spamcomefindmeplease at gmail.com (peppergrower) Date: Sat, 27 Sep 2008 02:21:06 -0700 (PDT) Subject: Using the 'with' statement with cStringIO objects Message-ID: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> I've been experimenting with the 'with' statement (in __future__), and so far I like it. However, I can't get it to work with a cStringIO object. Here's a minimum working example: ### from __future__ import with_statement import cStringIO teststring='this is a test' with cStringIO.StringIO(teststring) as testfile: pass ### I get the following error message: Traceback (most recent call last): File "testfile.py", line 6, in <module> with cStringIO.StringIO(teststring) as testfile: AttributeError: 'cStringIO.StringI' object has no attribute '__exit__' So, I'm guessing you can't use the 'with' statement with cStringIO objects? Is this a bug, or do I need to use the 'with' statement differently to get this to work? Thanks, peppergrower From lekin2 at llnl.gov Fri Sep 19 17:10:37 2008 From: lekin2 at llnl.gov (lekin2 at llnl.gov) Date: Fri, 19 Sep 2008 14:10:37 -0700 Subject: ScrolledCanvas/ScrolledText Message-ID: <20080919141037.ra7p3opugc4s4w8o@www-openlabnet.llnl.gov> So what the heck is going on. I have a Pmw.ScrollingCanvas and inside I put a Pmw.ScrollingText and that all works but I can't get it to scroll. I was thinking I needed an event like: self.sc = Pmw.ScrolledCanvas(parent, borderframe = 5, labelpos = 'n', usehullsize = 1, hull_width = 700, hull_height = 500, hscrollmode = 'static', vscrollmode = 'static',) self._title = Pmw.ScrolledText(self.sc.interior(), labelpos = 'w', text_wrap='word', usehullsize=1, hull_height= 50, hull_width=500) titleVal = "Equation of state for %s" % (materialName) self._title.insert(1.0, titleVal) self._title.component("label").config(text="Title:") self.sc.component('canvas').bind('<Button-1>', self.scrolling) def scrolling(self, event): x = self.sc.canvasx(event.x) y = self.sc.canvasy(event.y) self.sc.resizescrollregion() From deets at nospam.web.de Thu Sep 11 08:35:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Sep 2008 14:35:26 +0200 Subject: problem with interpreter References: <04e1cbd4-7116-4209-b814-6d34e4d24975@l42g2000hsc.googlegroups.com> Message-ID: <6ishkuFb33rU1@mid.uni-berlin.de> chusky wrote: > Hi ! > > I have Python installed on C:\Python25 > Yesterday I added new "wx" library to the Python > > when I run C:\Python25\python.exe from the command line there is a > problem with finding libraries: > > C:\Python25>python.exe > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import wx > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\__init__.py", > line 45, > in <module> > from wx._core import * > File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", > line 5, in < > module> > import new > File "new.py", line 1 > import > ^ > SyntaxError: invalid syntax >>>> > > > ///////////////////// > > .... that problem doesn't exist when I run python.exe from different > location (C:\, D:\) with python in the system path Do you by any chance have a file "new.py", or new.pyc lying around? It's always a bad idea to name your own modules after standard-modules (new is a standard-module), as they might get picked up first. Diez From lie.1296 at gmail.com Tue Sep 30 14:39:12 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 30 Sep 2008 18:39:12 +0000 (UTC) Subject: r"<path>" References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> <CltEk.1298$fD.324@flpi145.ffdc.sbc.com> <33077c9c-01d9-4423-afd2-7452117bc6b4@j22g2000hsf.googlegroups.com> Message-ID: <gbtrog$an6$1@ger.gmane.org> On Tue, 30 Sep 2008 10:50:01 -0700, Kyle Hayes wrote: >> Please describe the actual problem you're trying to solve. In what way >> do slashes need to be "fixed," and why? > > Well, I have decided to build a tool to help us sync files in UNC paths. > I am just building the modules and classes right now so I haven't > developed the frontend yet. I am assuming when the user provides a path > (either by typing it in, or pulling it in from a config file), the UNC > slashes are going to escape stuff in the string, so I want to double > them up. > > I understand if the best way is to convert all the slashes to double- > slashes. But the 'r' function seemed so handy and convenient. You don't need to. Python's string is never escaped in-memory, it is only escaped when repr(s) is called (the interpreter's implicit print uses repr () instead of str()). And that means all string coming and going to/from IO (file, GUI, etc) is stored as-is. However, strings that comes from source code or interpreter prompt (a.k.a. literal string) needs to be escaped. Analogy: When you're writing a string in the source code, you add double quotes (""), right? But do you think the quotes are stored in memory? No, it's just an escape character to differentiate a string from its surrounding. From afriere at yahoo.co.uk Mon Sep 8 01:13:20 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Sun, 7 Sep 2008 22:13:20 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> Message-ID: <ccf8d124-4609-48a6-b487-7cccc6d9c4b9@a3g2000prm.googlegroups.com> On Sep 8, 7:00 am, castironpi <castiro... at gmail.com> wrote: > I am concerned by the lack of follow-through on some responses to > recent ideas I have described. Do I merely have a wrong understanding > of group policy? [snip] Perhaps the wrong idea of what the group is. I would have thought that if one had a sufficiently developed idea and wanted to have it / formally/ rejected, rather than merely sniped at, then writting a PEP would be more apposite than posting to c.l.py. It's fine to post your not sufficiently developed ideas here merely to have them discussed. But I don't know what makes you feel that you, or your ideas, are /entitled/ to any response at all, much less "follow-through." From ldo at geek-central.gen.new_zealand Mon Sep 29 02:43:29 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 19:43:29 +1300 Subject: Web programming in Python. References: <eb5978f8-e802-48d2-a61f-207c25ac7059@y21g2000hsf.googlegroups.com> <ace09154-e1c1-424e-875e-5193ae210b57@w7g2000hsa.googlegroups.com> <2afd3f2f-8b80-4a99-965a-6e27f7000055@r15g2000prh.googlegroups.com> Message-ID: <gbpteh$dqp$2@lust.ihug.co.nz> In message <2afd3f2f-8b80-4a99-965a-6e27f7000055 at r15g2000prh.googlegroups.com>, Sean DiZazzo wrote: > Have you loaded the modpython module in your httpd.conf? Not relevant for CGIs. From tjreedy at udel.edu Thu Sep 4 17:35:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Sep 2008 17:35:18 -0400 Subject: why is self not passed to id()? In-Reply-To: <200809042244.54418.maric@aristote.info> References: <g9pg72$3vi$1@aioe.org> <200809042244.54418.maric@aristote.info> Message-ID: <g9pkam$rmc$1@ger.gmane.org> Maric Michaud wrote: > Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez ?crit : >> class foo(list): >> __hash__ = lambda x: id(x) >> > > Wow ! You are really going on trouble with this, believe me there is a real > good reason for list not to be hashable. A dictionnary or set containing some > of your foo is virtually inconsistent, read carefully the manual about > prerequesites for dict keys, they *need* to be immutable. No, the id comparison needs to be immutable -- which it is by default for object()s, being based on id. Mutable instances of classes derived from object work fine as keys as long as they keep default __eq__ and __hash__. List over-rides the default, so foo needs to reverse that override: def __eq__(self, other): return id(self) == id(other) This means, of course, that foo loses value-based equality comparison. From dmitry at athabascau.ca Fri Sep 26 18:38:46 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Fri, 26 Sep 2008 22:38:46 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> <Mo7Dk.2064$T65.1885@edtnps82> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: <WvdDk.2157$T65.1610@edtnps82> Bruno Desthuilliers wrote: > Hem... I'm afraid you don't really take Python's dynamic nature into > account here. Do you know that even the __class__ attribute of an > instance can be rebound at runtime ? What about 'once and for all' then ? must've been wrong wording on my part. Dynamic nature is exactly what I wanted to use :) except that I do not expect clients to take advantage of it while using my classes ;) >>> Your original question was "is decorator the right thing to use?" For >>> this application, the answer is "no". >> >> yeah. seems that way. in the other fork of this thread you'll find my >> conclusion which agrees with that :) >> >>> It sounds like you are trying >>> to force this particular to solution to your problem, but you are >>> probably better off giving __getattr__ intercepting another look. >> >> __getattr__ implies constant lookups and checks (for filtering purposes) > > Unless you cache the lookups results... sure >> - I >> want to do them once, attach generated methods as native methods > > What is a "native method" ? You might not be aware of the fact that > method objects are usually built anew from functions on each method > call... again, wrong wording on my part. by native I meant: make use as much as possible of existing machinery and override default behavior only when it's absolutely necessary. (hopefully my wording is not off this time ;) ) >> and be >> done with it. That is why I do not like __getattr__ in this particular >> case. > > There's indeed an additional penalty using __getattr__, which is that > it's only called as a last resort. Now remember that premature > optimization is the root of evil... Depending on effective use (ie : how > often a same 'proxied' method is called on a given Proxy instance, on > average), using __getattr__ to retrieve the appropriate bound method on > the delegate then adding it to the proxy instance *as an instance > attribute* might be a way better (and simpler) optimization. I actually ended up rewriting things (loosely based on George's suggested code) with descriptors and not using metaclasses or decorators (so much for my desire to use them). With following implementation (unpolished at this stage but already functional) I can have several instances of B objects inside of A object and proxy certain methods to one or another object (I might be having a case when I have A.b1 and A.b2 and passing some methods to b1 and others to b2 having both of the same class B, maybe even multiplexing). This one seems to be fairly light as well without need to scan instances (well, except for one getattr, but I couldn't get around it). Maybe I didn't account for some shoot-in-the-foot scenarios but I can't come up with any. Last time I played with __getattr__ I shot myself in the foot quite well BTW :) class ProxyMethod(object): def __init__(self,ob_name,meth): self.ob_name=ob_name self.meth=meth def my_call(self,instance,*argv,**kw): ob=getattr(instance,self.ob_name) cls=self.meth.im_class return self.meth.__get__(ob,cls)(*argv,**kw) def __get__(self,instance,owner): if not instance: return self.my_call ob=getattr(instance,self.ob_name) cls=self.meth.im_class return self.meth.__get__(ob,cls) class B: def __init__(self): self.val='bval' def bmethod(self,a): print "B::bmethod", print a, self.val class A: b=None def __init__(self,b=None): self.val='aval' self.b=b b.val='aval-b' def mymethod(self,a): print "A::mymethod, ",a bmethod=ProxyMethod('b',B.bmethod) b=B() b.bmethod('foo') a=A(b) b=B() b.val='newval' a.mymethod('baz') a.bmethod('bar') A.bmethod(a,'zoom') From michel at nospam.please Mon Sep 15 16:09:07 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 22:09:07 +0200 Subject: Python Nautilus script In-Reply-To: <6j7t7rF1tl5rU1@mid.uni-berlin.de> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> Message-ID: <48cec0e3$0$2860$ba620e4c@news.skynet.be> Diez B. Roggisch a ?crit : > However, if you want you can do something like this: > > #!/bin/bash > export VARIABLE_NAME > python /the/python/script.py > > You create a shell-script that exports the environment first, and then > invokes python. Oh, that's a good idea, I'll try this. Thanks -- Michel Leunen http://linux.leunen.com From asnast at gmail.com Thu Sep 25 15:33:07 2008 From: asnast at gmail.com (Alex Snast) Date: Thu, 25 Sep 2008 12:33:07 -0700 (PDT) Subject: Quick sort implementation in python Message-ID: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Hi guys, I've been learning python in the past week and tried to implement a q.sort algorithm in python as follows: def quick_sort(l, first, last) if first < last: q = partition(a, first, last) quick_sort(a, first, q - 1) quick_sort(a, q + 1, last) def partition(a, first, last): import random pivot = random.randomint(first, last) a[last], a[pivot] = a[pivot], a[last] i = first for j in range(first, last): if a[j] <= a[last]: a[i], a[j] = a[j], a[i] i += 1 a[i], a[last] = a[last], a[i] return i Now as you can see I'm passing my list object to both functions along with their first, last indices My question is: Is that the normal way to implement algorithms in python cause in c++ i've implemented that algo via a template function which can have a randon access data structure or not. However i have no idea how to access the values of a data structure that doesn't allow random access. Thanks, Alex From invalid at invalid Sun Sep 14 11:04:31 2008 From: invalid at invalid (Grant Edwards) Date: Sun, 14 Sep 2008 10:04:31 -0500 Subject: How does python call OS? References: <f9idnWTIta_gKVHVnZ2dnUVZ_gCdnZ2d@comcast.com> Message-ID: <FomdnbglR6ViulDVnZ2dnUVZ_rHinZ2d@posted.usinternet> On 2008-09-14, Siegfried Heintze <siegfried at heintze.com> wrote: > I just finished reading a chapter in "Python Programming on Win32" and tried > out the pythonwin scribble application. I'm not sure if I got it right > because I could not open a new document. I tried to download the source code > as referenced in the chm file but it is corrupted. I cut and pasted from my > softcopy of the book. > > I see the next sub-chapter on wxWindows for python and the > previous sub-chapter on TK. This is looking a lot like other > scripting languages (such as perl and groovy and even java). > Can python call anything directly No. For example, I don't believe there's any way for standard C-Python to make system calls on Linux. [Thought ISTR that somebody has written an extension module that doess that.] > or does someone have to write a DLL in C/C++ that calls the > function first? Can you be more explicit? What sort of "function" are you talking about? As for calling functions in libraries, the library doesn't have to be in C/C++. Python can make library calls written in any language (Fortran, Ada, Pascal, etc.) as long as the language uses a supportted API. Python can also execute external programs. -- Grant From Lie.1296 at gmail.com Sun Sep 28 07:48:29 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 04:48:29 -0700 (PDT) Subject: Borg vs Singleton vs OddClass References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> <00eee973$0$20666$c3e8da3@news.astraweb.com> Message-ID: <71fb2f0b-874d-468c-9ae4-2e644d26c26b@a3g2000prm.googlegroups.com> On Sep 28, 9:45?am, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Sat, 27 Sep 2008 11:12:00 -0700, Lie wrote: > > This is probably unrelated to Python, as this is more about design > > pattern. I'm asking your comments about this design pattern that is > > similar in functionality to Singleton and Borg: to share states. > > > I'm thinking about this design pattern (I don't know if anyone has ever > > thought of this pattern before): > > > class OddClass(object): > > ? ? def __init__(self): > > ? ? ? ? global OddClass > > ? ? ? ? OddClass = self > > ? ? def __call__(): > > ? ? ? ? return self > > I don't think that pattern works as you give it. I suggest you read the > thread "What do you call a class not intended to be instantiated", > started by me on the 21st of September, which covers a similar pattern. In fact, that thread inspired this thread. > I'm afraid it's a rather long thread, with a lot of people > misunderstanding what I was asking, but still worth reading. If you only > have time to read one post, I suggest you read my reply to Ben Finney, > posted yesterday. ... before I decided probably this pattern is probably isn't the answer to that thread. > My own feeling is that both your OddClass and my class without instances > are probably solutions looking for a problem. Well, actually, no, that's > too strong: I think the concept of "Class Singleton" is a perfectly valid > solution to certain problems, but it competes with more well-known > solutions like modules and Borg (in Python) and Singletons (the hammer > available in Java and C++). As for which is better, that's partly a > matter of personal taste and partly a matter of familiarity. > > > It do have a problem though, that you can't do isinstance(a, OddClass) > > But you can say "a is OddClass", which is more appropriate for a > Singleton. > > > The problem with Borg is that it is not inheritable (in certain > > sense[1]) and only work with old-style class (which is due to be > > completely removed on py3k)[2] > > No, there is a new-style Borg. Read the comments here:http://code.activestate.com/recipes/66531/ > > The new-style Borg is hardly more complicated than old-style: 6 lines > versus 4. From invalid at invalid Thu Sep 11 12:31:01 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 11 Sep 2008 11:31:01 -0500 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> Message-ID: <6v2dndx7GeZY2lTVnZ2dnUVZ_ozinZ2d@posted.visi> On 2008-09-11, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: > On Wed, 10 Sep 2008 21:36:36 -0500, Grant Edwards <grante at visi.com> > declaimed the following in comp.lang.python: > > >> Wrong. I didn't send _any_ e-mail. Why should I get bounce >> messages? >> > One: Comp.lang.python is dual-routed with a mailing list; anything > you post to either CLP or the mailing list gets cross-posted to the > other -- the FROM header retains that of the original author (which > could be you). > > Two: Somebody else is subscribed to the mailing list, and sets up an > "out-of-office" reply or has other problems (like an overfilled mailbox, > causing a bounce, or a discontinued account) when the forwarded post > reaches their address. > > Three: The bounce/ooo-reply is sent to the message author, not to > any intermediate host(s). After all, on that end, it's normal email > failure response -- notify the author of the message. It doesn't matter > that the original message was posted on a Usenet newsgroup if that group > is automatically relayed to members of a mailing list. OK, you win. Since I don't care to get the bounce and out-of-office messages, I'll fix my from: header when posting to this group. -- Grant Edwards grante Yow! Am I having fun yet? at visi.com From castironpi at gmail.com Mon Sep 22 16:15:46 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 13:15:46 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> <48d78c3c$0$6998$426a74cc@news.free.fr> <mailman.1360.1222091143.3487.python-list@python.org> <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> <48d7f46d$0$15502$426a74cc@news.free.fr> Message-ID: <ea7583fc-82c0-4f8c-aeeb-f3de5af8ba69@i76g2000hsf.googlegroups.com> On Sep 22, 2:38?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > Aaron "Castironpi" Brady a ?crit : > > > > > On Sep 22, 8:45 am, "Tim Rowe" <digi... at gmail.com> wrote: > >> 2008/9/22 Bruno Desthuilliers <bruno.42.desthuilli... at websiteburo.invalid>: > > >>>> Sounds to me like a functor, aka a function object: > >>>>http://en.wikipedia.org/wiki/Function_object > >>> Ok, then the simple solution is to implement a callable type (__call__ > >>> method), possibly with appropriate support for the descriptor protocol if > >>> it's meant to be usable as a method. > >> Yes -- and instantiate the thing and keep the state in the instance, > >> rather than keeping the state in the class, so that it's possible to > >> safely have more than one of them if a later design change calls for > >> it (probably what led people off onto the sidetrack of thinking a > >> singleton was called for). ?That's the classic way of implementing a > >> "class [to be] used as a function". > > >> -- > >> Tim Rowe > > > I think you are either looking for a class that has a generator, or a > > generator that has a reference to itself. > > ??? > > Going back to robot-mode, Aaron ? Not getting the same sense of "soul" as from my usual posts. I guess so. Might even drop the name change, too... while I'm at it. One more word from you about it and I'm starting a thread, and calling it, "Python and my sense of 'soul'". Ha ha. From michele.simionato at gmail.com Wed Sep 10 08:21:00 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 10 Sep 2008 05:21:00 -0700 (PDT) Subject: Catching subprocess stdout stream References: <00b9dc86-e002-4e2c-a686-39d2dd1016b9@m3g2000hsc.googlegroups.com> Message-ID: <077ce22e-8278-4729-9f54-2a305064f797@x41g2000hsb.googlegroups.com> On Sep 8, 5:37?pm, Thomas Jansson <tjansso... at gmail.com> wrote: > Dear all > > I have tkinkter based frontend to a Fortran based program. I use > subprocess to launch the fortran program as a child process and I wish > to see the output of the fortran program as it is created in the > console. > > The fortran program can take up to 20 minuttes to finish and at the > moment the I will first see any output after the fortran program is > done. How make my function write the output of the process as it > comes? Sometimes very low technology solutions may be enough. For instance on Unix you could call os.system on something like that: xterm -e "the-fortran-executable|less" Make sure the Fortran executable output is unbuffered. Michele Simionato From sjdevnull at yahoo.com Sun Sep 28 16:24:35 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sun, 28 Sep 2008 13:24:35 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <2ebe0ca2-ba26-47b3-ad35-946fd51d745c@f36g2000hsa.googlegroups.com> On Sep 28, 2:29 pm, process <circularf... at gmail.com> wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. > > What is not an object in Python? > Parts of the syntax aren't objects. e.g. "=" or ":" aren't objects. Unlike in some less fully OO-languages (e.g. Java or C++), classes, functions, and many other "built-in language features" are objects in Python. You can do things like return functions just like any other object, rather than having to do it indirectly through references or some such: >>> def add_n(x): ... def rv(y): ... return y + x ... return rv ... >>> add_2 = add_n(2) >>> add_3 = add_n(3) >>> >>> print add_2(6) 8 >>> print add_2(10) 12 >>> print add_3(6) 9 > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? FWIW, it is implemented as a str.__len__ method (and list.__len__ method); the len() function just uses those internally. Java and C++ have similar shortcuts for, say, "+" or "-". But Python allows you to call all the operators as methods if you want: >>> 1+2 3 >>> (1).__add__(2) 3 >>> a_list = [ "a", "b", "c" ] >>> len(a_list) 3 >>> a_list.__len__() 3 And, of course, the presence of the len() shortcut doesn't alter the OO-nature of the language any more than the presence of the + operator does in any OO language. Derived classes' __len__ operators are called correctly by len(): >>> class list_that_lies(list): ... def __len__(self): ... return 2 ... >>> bad_list=list_that_lies([1,2]) >>> print bad_list [1, 2] >>> len(bad_list) 2 >>> bad_list.append(3) >>> print bad_list [1, 2, 3] >>> len(bad_list) 2 From prologic at shortcircuit.net.au Thu Sep 18 06:48:54 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 18 Sep 2008 20:48:54 +1000 Subject: PEP proposal optparse In-Reply-To: <ca58efdf-3f9c-4aea-9c20-69c69a578754@k30g2000hse.googlegroups.com> References: <ca58efdf-3f9c-4aea-9c20-69c69a578754@k30g2000hse.googlegroups.com> Message-ID: <e1a84d570809180348l650ade73u33b429551b969682@mail.gmail.com> Hi James, I can't say I really agree with your proposal. I tend to keep the help descriptions of my options short and concise and to the point. Also, one must use the language's features (indentation) to your advantage, as doing so ensure readability. For example (from my bhimport tool): <snippet> def parse_options(): """parse_options() -> opts, args Parse any command-line options given returning both the parsed options and arguments. """ parser = optparse.OptionParser(usage=USAGE, version=VERSION) parser.add_option("", "--date-format", action="store",type="str", default="%d/%m/%Y", dest="dateFormat", help="date format string") parser.add_option("", "--time-format", action="store", type="str", default="%H:%M:%S", dest="timeFormat", help="time format string") parser.add_option("", "--datetime-format", action="store", type="str", default="%H:%M:%S %d/%m/%Y", dest="datetimeFormat", help="datetime format string") opts, args = parser.parse_args() if len(args) < 2: parser.print_help() raise SystemExit, 1 return opts, args </snippet> As you can see (as long as you're reading this in fixed-width fonts) it _is_ very readable. cheers James On 9/18/08, James <jlnicolson at gmail.com> wrote: > Hi, > > I would like to know your thoughts on a proposed change to optparse > that I have planned. It is possible to add default values to multiple > options using the set_defaults. However, when adding descriptions to > options the developer has to specify it in each add_option() call. > This results in unreadable code such as: > > parser.add_option('-q', '--quiet' , action="store_false", > dest='verbose', > help = 'Output less information') > parser.add_option('-o', '--output' , type='string', > dest='castordir' , metavar='<DIR>' , > help = 'specify the wanted CASTOR directory where to store the > results tarball') > parser.add_option('-r', '--prevrel' , type='string', > dest='previousrel' , metavar='<DIR>' , > help = 'Top level dir of previous release for regression > analysis' ) > > The same code could become much more readable if there was an > equivalent method of set_defaults for the description/help of the > option. The same code could then become: > > parser.set_description( > verbose = 'Output less information', > castordir = 'specify the wanted CASTOR directory where > to store the results tarball', > previousrel = 'Top level dir of previous release for > regression analysis') > > parser.add_option('-q', '--quiet' , action="store_false", > dest='verbose') > parser.add_option('-o', '--output' , type='string', > dest='castordir' , metavar='<DIR>' ) > parser.add_option('-r', '--prevrel' , type='string', > dest='previousrel' , metavar='<DIR>' ) > > Help descriptions can often be quite long and separating them in this > fashion would, IMHO, be desirable. > > Kind Regards, > James Nicolson > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 4 08:43:49 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 14:43:49 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <mailman.478.1220526604.3487.python-list@python.org> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> Message-ID: <48bfd7a0$0$20720$426a74cc@news.free.fr> Marco Bizzarri a ?crit : > Sorry... pressed enter but really didn't want to. > > As I said, let's say I have a class > > class A: > def __init__(self): > self.x = None > > > > Python makes the decision to allow the developers to directly access > the attribute "x", So do Java, if you make your attribute public (which would be a big error given Java's lack of support for computed attribute, but this is another problem). > so that they can directly write: "a.x = 1", or > whatever; this has for me the unfortunate side effect that if I write, > for example "a.y = 1", when I really wanted to write "a.x = 1" no one > cares about it, I assume *you* do !-) But this is barely related to having explicit setters or not - it comes from the fact that the default[1] Python's object behaviour is to support arbitrary attribute setting. [1] some objects don't, but this is mostly for optimization reasons. > and I'm unable to spot this error until later. Not sure, but IIRC tools like pylint or pychecker might be able to warn you about this. But anyway : > Of course, I know that while I'm fresh, I've a good knowledge of the > code, and anything else, I will be able to avoid such stupid errors; > however, I'm afraid of the times when I'm tired, when I have to put my > hands on the code of someone else, and so on. The edit/test cycle in Python is usually fast enough so you should spot the problem *pretty* quickly. This is at least what I learned from 8+ years of python (and a couple other dynamic languages) programming... Not to say that problems like the one you mention (or similar problems with dynamic typing etc) never happens, nor that they're never painful to track down and fix - just that they happen way less often than one might fear, and are most of the time really quickly spotted and fixed. > Please, understand that I'm not stating that python is wrong... after > all, if it is wrong, I can move to a language like Java, which has a > different approach on it. I don't think it's a matter of "right" or "wrong" - mostly a matter of tradeoffs and balance. But if you go for static typing and (allegedly) provable correctness, you may want to have a look at languages like OCaml. > I'm really very interested in reading past > discussion on it, if they are available. Well... Most of these "discussions" alas boil down to bondage&discipline proponants asserting - against all evidences - that dynamic languages are unsafe and unusable for anything else than simple throw-away scripts or toy projects, and dynamic proponants arguing - against all evidences - that static typing and everything related is just a waste of time (FWIW, you might find myself in the first camp until approx year 2k and the second for the five or six following years). And sometimes, someone a bit more sensible trying to take a more balanced approach to the problem, usually to no avail. From anishchapagain at gmail.com Wed Sep 3 07:43:54 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Wed, 3 Sep 2008 04:43:54 -0700 (PDT) Subject: installing matplotlib with numpy and scipy for Python in Cygwin References: <mailman.418.1220435306.3487.python-list@python.org> <ef26e8bf-e917-4da6-b75b-1bbf39c3ff90@59g2000hsb.googlegroups.com> Message-ID: <4241157d-6cdb-4edc-bb22-bceeb68b870f@m73g2000hsh.googlegroups.com> On Sep 3, 12:39?pm, Uwe Schmitt <rocksportroc... at googlemail.com> wrote: > On 3 Sep., 11:42, "chapagainanish" <chapagainan... at yahoo.com> wrote: > > > Hi!! > > I'm having installation problem for installing numpy and scipy in > > Cygwin for Python, and am obstruct in madway for project, i followed > > scipy.org guidelines but there's few error thrown as > > ? ? ? ? failed..with exit status 1 > > > please if someone has installed these module help me > > thank's and regard's > > Anish > > http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html > may help you. > > Do you really want a cygwin based installation ? > You could download enthoughts python edition which > includes lots of math stuff. > > Greetings, Uwe Hi, thank's i'm looking through the link cens.ioc.ee and am in need of using matplotlib and to run few system call, so i installed cygwin baically for system call in linux/unix and matplotlib for GUI(graph,chart) but matplotlib is not getting installed in cygwin.. any further help will be heartly accepted thank's anish From skip at pobox.com Mon Sep 8 06:51:48 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Sep 2008 05:51:48 -0500 Subject: Syntax Problem with strptime in Python 2.4 In-Reply-To: <ZA6xk.19461$LG4.103@nlpi065.nbdc.sbc.com> References: <ZA6xk.19461$LG4.103@nlpi065.nbdc.sbc.com> Message-ID: <18629.964.85843.766887@montanaro-dyndns-org.local> >> Apparently, use of strptime of datetime needs a workaround in Python >> 2.4 to work properly. The workaround is d = >> datetime.datetime(*(time.strptime(date_string, >> format)[0:5])). However, when I try to use it, or even use it the >> regular way, it fails with AttributeError: type object >> 'datetime.datetime' has no attribute 'datetime'. Works for me: >>> import datetime >>> format = '%Y%m%d_%H%M%S' >>> import time >>> print time.strptime('20080321_113405', format)[0:5] (2008, 3, 21, 11, 34) >>> d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5]) >>> d datetime.datetime(2008, 3, 21, 11, 34) Python 2.4.4, Mac OS X 10.5.4. Skip From gnewsg at gmail.com Sat Sep 20 14:48:09 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 20 Sep 2008 11:48:09 -0700 (PDT) Subject: ANN: Python FTP Server library (pyftpdlib) 0.5.0 released Message-ID: <1433ffb8-7493-466d-81e6-bf8ed877e81c@y21g2000hsf.googlegroups.com> Hi, I'm pleased to announce release 0.5.0 of Python FTP Server library (pyftpdlib). http://code.google.com/p/pyftpdlib/ === About === Python FTP server library provides an high-level portable interface to easily write asynchronous FTP servers with Python. Based on asyncore framework pyftpdlib is currently the most complete RFC-959 FTP server implementation available for Python programming language. === Major changes === This new version, aside from fixing some bugs, includes the following major features: - pyftpdlib now provides configurable idle timeouts to disconnect client after a long time of inactivity. - It is now possible to define permission exceptions for certain directories (e.g. creating a user which does not have write permission except for one sub-directory in FTP root). - Imposed a delay before replying for invalid credentials to minimize the risk of brute force password guessing. A complete list of changes including enhancements, bug fixes and instructions for using the new functionalities is available here: http://code.google.com/p/pyftpdlib/wiki/ReleaseNotes05 === More links === * Source tarball: http://pyftpdlib.googlecode.com/files/pyftpdlib-0.5.0.tar.gz * Online docs: http://code.google.com/p/pyftpdlib/wiki/Tutorial * FAQs: http://code.google.com/p/pyftpdlib/wiki/FAQ * RFCs compliance paper: http://code.google.com/p/pyftpdlib/wiki/RFCsCompliance * Issue tracker: http://code.google.com/p/pyftpdlib/issues/list Thanks, --- Giampaolo Rodola' < g.rodola [at] gmail [dot] com > http://code.google.com/p/pyftpdlib/ From marco.bizzarri at gmail.com Sun Sep 14 04:44:36 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sun, 14 Sep 2008 10:44:36 +0200 Subject: recursion gotcha? In-Reply-To: <3f0d61c40809140108n515006dci87f91dcd971f0169@mail.gmail.com> References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> <3f0d61c40809140108n515006dci87f91dcd971f0169@mail.gmail.com> Message-ID: <3f0d61c40809140144xfca86a1u7c6d088bec0f42f1@mail.gmail.com> On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri <marco.bizzarri at gmail.com> wrote: > On Sun, Sep 14, 2008 at 10:01 AM, cnb <circularfunc at yahoo.se> wrote: >> this recursive definition of sum thrumped me, is this some sort of >> gotcha or am I just braindead today? >> and yes i know this is easy a a for x in xs acc += x or just using the >> builtin. >> >> def suma(xs, acc=0): >> if len(xs) == 0: >> acc >> else: >> suma(xs[1:], acc+xs[0]) > > You're just missing the "return" statements? > > def suma(xs, acc=0): > if len(xs) == 0: > return acc > else: > return suma(xs[1:], acc+xs[0]) > > Besides: you can avoid the "acc" parameter: def suma(xs): if len(xs) == 0: return 0 else: return xs[0] + suma(xs[1:]) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From dmitry at makovey.net Wed Sep 24 23:51:01 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 03:51:01 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> Message-ID: <FUDCk.1809$T65.1083@edtnps82> Dmitry S. Makovey wrote: > In my real-life case A is a proxy to B, C and D instances/objects, not > just one. forgot to mention that above would mean that I need to have more than one decorator function like AproxyB, AproxyC and AproxyD or make Aproxy smarter about which property of A has instance of which class etc. Unless I'm totally "out for lunch" and there are better ways of implementing this (other than copy-pasting stuff whenever anything in B, C or D changes). From stephen.mc at gmail.com Wed Sep 24 07:12:37 2008 From: stephen.mc at gmail.com (Steve) Date: Wed, 24 Sep 2008 04:12:37 -0700 (PDT) Subject: Python graphical library References: <3abb0519-7700-4d82-bdaa-e4b09ef1c483@t54g2000hsg.googlegroups.com> Message-ID: <9122b671-a1b2-473b-9244-bc443d2e859b@z11g2000prl.googlegroups.com> On Sep 24, 7:31?pm, bluesm... at gmail.com wrote: > Hi all, > > I am looking for a python graphical library that would allow me to > draw borderless windows, sort of like a notification frame showing up. > I would also like to be able to make it transparent but I suppose that > is very much desktop manager dependent. > > Thank you very much for the help. > > ET wxpython supports both these features From fredrik at pythonware.com Thu Sep 4 02:24:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 08:24:56 +0200 Subject: max(), sum(), next() In-Reply-To: <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: <g9nuvo$jhk$1@ger.gmane.org> Mensanator wrote: > No it isn't. Nothing is not 0, check with MS-Access, for instance: > > Null + 1 returns Null. Any arithmetic expression involving a > Null evaluates to Null. Adding something to an unknown returns > an unknown, as it should. > > It is a logical fallacy to equate unknown with 0. http://en.wikipedia.org/wiki/Empty_sum "In mathematics, the empty sum, or nullary sum, is the result of adding no numbers, in summation for example. Its numerical value is zero." </F> From prologic at shortcircuit.net.au Wed Sep 10 10:22:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 00:22:33 +1000 Subject: Alternatives to traditional RDBMS Message-ID: <e1a84d570809100722o50318eddpadbc670c05159ad5@mail.gmail.com> Hi all, Are there any known alternatives to the traditional RDBMS (MySQL, PostgreSQL, SQLite, Oracle, etc0 / I know of 3 written in Python: * buzhug * kirbybase * PyDbLite buzhug --------- Although buzhug has a group membership size of ~60 or so it has not seen any activity in some time - and any activity that exists is slow and far and in-between. That said, buzhug is has a nice OO/Pythonic design and is quite nice to use. I have been working in improving it and have fixed issues I've come across in a branch of the original buzhug code that I now maintain. I fear the author of buzhug has lost interest and gone elsewhere to tinker with (better) other things ? kirbybase ------------ A nice small (also pure) python OO database. Developed quite some time ago, not actively worked on, but works really well.. PyDbLite ---------- Also developed quite some time ago, similar to both kirbybase and buzhug. Are there any others out there ? Is anyone working on something ? I would like to continue my work on buzhug... I have so: * Fixed several bugs * Implemented a WSGI middleware layer I'd like to refactor a lot of it's code and make better use of more recent features of python as buzhug was written quite some time ago. I think it's "protocol" could be vastly improved as well - as pickling things doesn't always work so well... In addition, I think buzhug could do with some caching features to speed database operations up (they're already pretty fast). cheers James -- -- -- "Problems are solved by method" From stefan_ml at behnel.de Tue Sep 16 13:40:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 16 Sep 2008 19:40:37 +0200 Subject: ElementTree oddities In-Reply-To: <e0fdbe3d-493c-4346-91cf-2a26491f7d87@k7g2000hsd.googlegroups.com> References: <c8f3d9e0-05dd-4ae9-b8c2-8b9bea15908c@r15g2000prd.googlegroups.com> <e0fdbe3d-493c-4346-91cf-2a26491f7d87@k7g2000hsd.googlegroups.com> Message-ID: <48cfef95$0$6669$9b4e6d93@newsspool2.arcor-online.net> Mark Thomas wrote: > here's how you would do it in lxml (http://codespeak.net/ > lxml/index.html), a library which supports XPath: > > from lxml import etree > tree = etree.fromstring('<highlight><ref>Bar</ref>:</highlight>') > print ' '.join(tree.xpath('//text()')) If you want to use XPath, try this: print tree.xpath('string()') or if you want to use it in real code: get_tree_text = etree.XPath('string()') print get_tree_text(tree) or just use print etree.tostring(tree, method="text") Stefan From rowland at river2sea.org Tue Sep 2 15:48:05 2008 From: rowland at river2sea.org (rowland at river2sea.org) Date: Tue, 2 Sep 2008 12:48:05 -0700 (PDT) Subject: synthetic properties Message-ID: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> I'm trying to come up with solution for adding synthetic properties to python, similar to synthetic properties in Objective-C. I'm playing around with doing this in a MetaClass. I can dynamically create the attributes that will back the property, but I'm having trouble figuring out how to dynamically generate get/set methods to pass to the built-in property() function. Is it possible to define a lambda or a callable object that will act as a getter method (or setter, that takes a value argument) during MetaClass.__init__? The hard part I'm guessing is getting the current instance passed into the getter. This is my first foray into MetaClasses and dynamic functions/methods so any pointers are greatly appreciated. class ObjectivePythonObject( type ) : def __new__( cls, name, bases, dct ) : #print "Allocating memory for class", name return type.__new__(cls, name, bases, dct ) def __init__( cls, name, bases, dct ) : #print "Initializing class", name for propertyInfo in cls.synthesized : property = propertyInfo[ 0 ] defaultValue = propertyInfo[ 1 ] print property setattr( cls, '_' + property, defaultValue ) # Create property with get/set methods... class Person( object ) : __metaclass__ = ObjectivePythonObject synthesized = [ ( 'name', 'BobC' ), ( 'age', '48' ) ] def __init__( self ) : print self._name print self._age Thanks, Rowland From bdesth.quelquechose at free.quelquepart.fr Thu Sep 25 13:31:41 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 19:31:41 +0200 Subject: is decorator the right thing to use? In-Reply-To: <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> <48db50aa$0$3750$426a74cc@news.free.fr> <HoOCk.1756$Pv5.1315@edtnps83> <48dbc82e$0$1120$426a74cc@news.free.fr> <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> Message-ID: <48dbe6e9$0$12845$426a74cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : (snip) > You should write it like this: > > class B(object): > @A.proxy > def bmethod(self,a): > > Making 'proxy' a class method on A. That's exactly what I wanted to avoid here : making B depending on A. (snip) > I agree that __setattr__ is the canonical solution to proxy, Err... I assume you mean '__getattr__' ??? > but you > have stated that you want each proxied method to be a member in the > proxy class. This doesn't necessarily imply that "proxied" classes need to know about the "proxying" class. FWIW, that was the whole point : decoupling. From castironpi at gmail.com Sun Sep 28 14:59:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 11:59:41 -0700 (PDT) Subject: Music knowledge representation References: <mailman.1624.1222612634.3487.python-list@python.org> Message-ID: <e21d8f09-6285-472e-9bfe-4757862d2c1c@x41g2000hsb.googlegroups.com> On Sep 28, 9:37?am, Mr.SpOOn <mr.spoo... at gmail.com> wrote: > Hi, > I'm working on an application to analyse music (melodies, chord sequences etc.) > > I need classes to represent different musical entities. I'm using a > class Note to represent all the notes. Inside it stores the name of > the natural version of the note (C, D, E, F...) and an integer to > calculate the accidentals. > > Then I have a class Pitch, to represent the different 12 pitch > classes, because different notes, such as C# and Db, belong to the > same pitch class. > > In these classes I also have some arithmetic method to perform > additions or subtractions between pitches and integers. > > I also need to represent intervals between notes. An interval must > have a degree (first, second, third), that may be represented with a > simple integer and a size counted in semitones. Then, with these > informations it can retrieve its name, for example: perfect fifth. > > The degree is calculated between natural notes. So the degree of > Interval(C, E) is "third", or 3. This may be simple, if I put the > notes in an ordered sequence. But, when I have to calculate, for > example Interval(E, C). It should count till the end of the sequence, > so if I have: > > C D E F G A B > > after the B it should continue with C. I'm not sure how to implement > this. Is there a suitable data structure for this purpose? Hi, Here is a link to someone else's design they asked about on the newsgroup a couple weeks ago. http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 13:08:23 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 19:08:23 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: <48cc0b6f$0$11218$426a34cc@news.free.fr> References: <mailman.979.1221317070.3487.python-list@python.org> <uaRyk.32271$Ep1.24249@bignews2.bellsouth.net> <48cbf09c$0$25189$426a74cc@news.free.fr> <48cbf432$0$27507$426a34cc@news.free.fr> <FvTyk.33637$De7.829@bignews7.bellsouth.net> <48cc0b6f$0$11218$426a34cc@news.free.fr> Message-ID: <48cc0f75$0$2214$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > Larry Bates a ?crit : (snip) >> Sorry but I respectfully disagree that this is "abuse" of the __call__ >> method. > > As long as we respectfully agree to disagree... > > !-) Anyway, I don't think we have enough background to seriously agree or disagree on what would make more sense here... From stefan_ml at behnel.de Fri Sep 5 06:15:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Sep 2008 12:15:37 +0200 Subject: "Full" element tag listing possible with Elementtree? In-Reply-To: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> References: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Message-ID: <48c106c9$0$9331$9b4e6d93@newsspool2.arcor-online.net> jaime.dyson at gmail.com wrote: > I have the unenviable task of turning about 20K strangely formatted > XML documents from different sources into something resembling a > clean, standard, uniform format. I like Elementtree and have been > using it to step through the documents to get a feel for their > structure. .getiterator() gives me a depth-first traversal that > eliminates the hierarchy of the elements. What I'd like is to be able > to traverse elements while keeping track of ancestors, and print out > the full structure of all of an ancestor's nodes as I arrive at each > node. Try lxml.etree. It's an extended re-implementation of ElementTree based on libxml2. Amongst tons of other features, it provides its Elements with a getparent() method and allows you to iterate over their ancestors (and other XPath axes), or to iterate over a parsed document in an iterparse-like fashion (called iterwalk). http://codespeak.net/lxml/ Stefan From maric at aristote.info Fri Sep 5 07:16:40 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 13:16:40 +0200 Subject: Case-insensitive string compare? In-Reply-To: <g9qjmm$4pl$1@ger.gmane.org> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050038.04108.maric@aristote.info> <g9qjmm$4pl$1@ger.gmane.org> Message-ID: <200809051316.41333.maric@aristote.info> Le Friday 05 September 2008 08:30:44 Fredrik Lundh, vous avez ?crit?: > Maric Michaud wrote: > > You''ll often see for loops written like this : > > > > for i in (e for e in iterable if predicate(e)) : > > ... > > luckily, I don't. most people, when faced with that problem, writes it > in the obvious way: > > for i in iterable: > if predicate(i): > ... So do I, most often, but this construct is common, I think because it makes clear what the for loop is iterating over, also it comes naturally once used to the more elaborated for i in (expr(e) for e in iterable if predicate(e)) : This one is truly a gain for readability IMO, compared to : for i in iterable: i = expr(i) if predicate(i): In the latter, the reader need more effort to figure out what finally "i" is in the loop. > > to avoid an extra iterator and save typing. > and at the cost of an extra indentation level. > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From lists at cheimes.de Tue Sep 16 15:40:41 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Sep 2008 21:40:41 +0200 Subject: new style classes, __new__, __init__ In-Reply-To: <gap12i$lfn$1@news.LF.net> References: <gap0g2$l4c$1@news.LF.net> <gap12i$lfn$1@news.LF.net> Message-ID: <gap23p$6tc$1@ger.gmane.org> Torsten Mohr wrote: > I just found an article that describes it better, this example works: > > class C2(object): > def __new__(cls, a): > obj = object.__new__(cls) > print "new called" > obj.a = 8 > > return obj > > __new__ = staticmethod(__new__) Staticmethod isnt' required here. Christian From skip at pobox.com Mon Sep 8 13:47:45 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 Sep 2008 12:47:45 -0500 Subject: shelve file name extention In-Reply-To: <dc898319-7903-40c1-8b6f-31d235595d2f@k37g2000hsf.googlegroups.com> References: <dc898319-7903-40c1-8b6f-31d235595d2f@k37g2000hsf.googlegroups.com> Message-ID: <18629.25921.928679.626414@montanaro-dyndns-org.local> Monu> When I am using shelve on my local machine it generates the db Monu> file as given filename. But in another machine it's generating Monu> <filename>.dat and .dir. can anyone tell me how can I force sheve Monu> module to write the db in <filename>.dir and <filename>.dat, Monu> instead of <filename>? Do I have to install a specific version of Monu> the python? Shelve is just a thin layer on top of a concrete db file module. Sounds like on your two machines there are different underlying db file modules available. You're pretty much at the mercy of those modules as to file naming. All you are giving it when opening a shelve file is the prefix. Skip From larry.bates at vitalEsafe.com Tue Sep 16 09:36:12 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 16 Sep 2008 08:36:12 -0500 Subject: A unique instance of Python GUI program In-Reply-To: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Message-ID: <KzOzk.33178$bx1.26896@bignews1.bellsouth.net> akineko wrote: > Hello everyone, > > This may not be a Python specific challenge. > I have a GUI program written in Python + Tkinter. > It works very well. > > Now, I would like to start it from a shell script. > As my GUI program includes a server, it should not have more than one > instance. > Is there any easy way to check if another instance of the program is > already running. > > I vaguely remember that Windows programming provides a way to check. > > A platform independent approach would be nice but a solution for X is > sufficient for my application. > > Any comments will be greatly appreciated. > > Best regards, > Aki Niimura Here is a recipe: http://code.activestate.com/recipes/474070/ -Larry From bearophileHUGS at lycos.com Mon Sep 1 15:15:53 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Sep 2008 12:15:53 -0700 (PDT) Subject: Py 2.6 changes Message-ID: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> I have just re-read the list of changes in Python 2.6, it's huge, there are tons of changes and improvements, I'm really impressed: http://docs.python.org/dev/whatsnew/2.6.html I'll need many days to learn all those changes! I can see it fixes several of the missing things/problems I have found in Python in the past, like the lack of information regarding the floating point it uses, etc. I have seen that many (smart) updates are from Hettinger. You can see a language gets better when you can remove often-used commodity functions/classes from your own 'bag of tricks' :-) (Like the permutations() function, etc). >Python now must be compiled with C89 compilers (after 19 years!). This means that the Python source tree has dropped its own implementations of memmove and strerror, which are in the C89 standard library.< I presume it's better for me to not hold my breath while I wait CPython to be written in C99 :-) Now math has factorial: http://docs.python.org/dev/library/math.html#math.factorial Seen how reduce() is removed from Python 3 (I know it's in itertools), and seeing that for me to write a productory() function was the first usage I have had for reduce, years ago, I think the math module can gain a productory() function too. For Python 2.7/3.1 I'd now like to write a PEP regarding the underscores into the number literals, like: 0b_0101_1111, 268_435_456 etc. I use such underscores all the time in the D language, and I think they can be a tiny but significant improvement for Python (and underscore is much better than just a space, because the underscore helps the person that reads the code to understand that's a single number). Bye, bearophile From ggpolo at gmail.com Mon Sep 15 07:19:54 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 15 Sep 2008 08:19:54 -0300 Subject: how to protect the source In-Reply-To: <BLU115-W513E8E918A8A16CEB298E596520@phx.gbl> References: <BLU115-W513E8E918A8A16CEB298E596520@phx.gbl> Message-ID: <ac2200130809150419r15bc4fc3v5e0e38af73118a9a@mail.gmail.com> On Mon, Sep 15, 2008 at 8:02 AM, Jo?o Abrantes <jepe_abrantes at hotmail.com> wrote: > Hello Everyone. > > > I am building a client in python that will connect himself to a mysql > server with a certain username and password. I will compile this client > and turn him into a .exe . The thing is that I know that is possible to > get the source of the code back from an .exe and I don't want anyone to > know which username and password are they using because I don't want > them to access to the mysql server without my client. Do you have any > ideas of what can i do? Thanks! > Do not include the username and password in the source. > ________________________________ > Connect to the next generation of MSN Messenger Get it now! > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From fredrik at pythonware.com Fri Sep 5 02:24:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:24:29 +0200 Subject: Case-insensitive string compare? In-Reply-To: <200809050059.17038.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> <200809050059.17038.maric@aristote.info> Message-ID: <g9qjav$3os$1@ger.gmane.org> Maric Michaud wrote: > "premature optimization is the root of all evil" So is use by that statement by people who don't have the slightest idea about what it actually means. The full version is "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil." Note the use of "small efficiencies". That is, in Python, things like local binding, inlining, slots, lazy generation of short sequences, etc. That is, things that takes time to write and reduces maintainability. It's not about having an excuse for writing crappy code with large inefficienies. And it's definitely not about programmers intentionally picking a dumb solution so they can optimize it later. > If the OP's proposal seems already messy, how about ths one : > if lib.lower() not in ( e[0] for e in stage_map.items() ) : > ... Given that your solution is just a remarkably inefficient way to write "lib.lower() not in stage_map", and thus doesn't solve the OP:s problem, I suspect you're taking the "evil" part of Hoare's dictum a few bits too literally. </F> From deets at nospam.web.de Mon Sep 15 17:00:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 23:00:47 +0200 Subject: Python Nautilus script In-Reply-To: <mailman.1074.1221512008.3487.python-list@python.org> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> <mailman.1074.1221512008.3487.python-list@python.org> Message-ID: <6j80nvF1ttmfU1@mid.uni-berlin.de> >>> It appears that's because HOSTNAME is not exported. >>> But in the case of Nautilus script, how to workaround this issue? > > Alternatively, export the variable when you create it, in .bashrc or > wherever it is getting created. That's probably the Right Thing to > Do(tm) in this case. Certainly not, as the OP uses a network monitoring software called Nautilus - and that communicates state to subprocesses using environment variables. Nothing to do with .bashrc. Diez From lixinyi.23 at gmail.com Tue Sep 23 22:30:44 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 19:30:44 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> <fde4ed92-77ed-438e-a163-d5e248a80ee9@d45g2000hsc.googlegroups.com> Message-ID: <31ff7c8a-28f3-4c62-8ac5-6d0f90106c5d@a8g2000prf.googlegroups.com> If the PyObject is a PyList, and all list items are strings, say a=['aaa','bbb','ccc'] How can I have a myArray[0] = "aaa" myArray[1] = "bbb" myArray[2] = "ccc" in C++? Do I have to use PyModule_GetDict() to get the dict first? what about the next? > > What do you know about the contents of 'argc' and 'argv'? ?If it's > impossible with Py_Main, can you use one of the other entry points? > > If you've never manipulated PyObject* objects in C, they can be > hairy. ?Even if you know 'a' is a sequence, its contents are still all > PyObject*s, which you can access via PyList_... and PySequence_ > functions. From paul at boddie.org.uk Wed Sep 17 05:43:54 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 17 Sep 2008 02:43:54 -0700 (PDT) Subject: minimum install & pickling References: <fb304bca-abe9-48e6-8dba-6187e33e5a6d@a2g2000prm.googlegroups.com> Message-ID: <6f045535-555f-44b6-93a5-f5b338d3f318@d45g2000hsc.googlegroups.com> On 17 Sep, 07:26, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > Sometimes questions come up on here about unpickling safely and > executing foreign code. ?I was thinking a minimum install that didn't > even have access to modules like 'os' could be safe. ? (Potentially.) > I have time to entertain this a little, though all the devs are busy. > I can bring it up again in a few months if it's a better time. One alternative might be to provide "safe" versions of the underlying functions in modules like "os". Previously, I did wonder why people didn't link Python against a bunch of alternative libraries which would provide implementations of things like "open", "chdir" and so on, but then I was made aware of fakeroot and fakechroot which do more or less this for any program (in conjunction with chroot) in order to restrict the behaviour of those programs, without any need to statically link the programs first. [...] > A lot of modules would have to go. ?<Long list> ?IPC modules: > subprocess, socket, signal, popen2, asyncore, asynchat. ?ctypes, mmap, > platform.popen, glob, shutil, dircache, and many more</Long>. Potentially, these could remain, but you'd want to provide "fake" versions of the underlying functions, potentially implementing your own preferred flavour of access control. So, with a call to the "socket" function, the wrapped version might first consult some kind of behaviour policy set by the user in order to get permission to open a connection to a remote host. There's a discussion of rexec and related solutions on the Wiki: http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_safely_(i.e._Sandbox) Paul From walter.php at gmail.com Fri Sep 5 10:35:14 2008 From: walter.php at gmail.com (Walter Cruz) Date: Fri, 5 Sep 2008 11:35:14 -0300 Subject: Extract Information from Tables in html In-Reply-To: <37b964200809050729j6290af48u8efbbc1a5e0b6bd1@mail.gmail.com> References: <37b964200809050729j6290af48u8efbbc1a5e0b6bd1@mail.gmail.com> Message-ID: <32cabba0809050735x16eb3764mb7ed9ad256de0b08@mail.gmail.com> On Fri, Sep 5, 2008 at 11:29 AM, Jackie Wang <jackie.python at gmail.com> wrote: > Dear all, > > Here is a html code: > > <td valign="top" headers="col4"> > > Premier Community Bank of Southwest Florida > <br /> > Fort Myers, FL > > </td> > > My question is how I can extract the strings and get the results: > Premier Community Bank of Southwest Florida; Fort Myers, FL Use BeautifulSoup. []'s - Walter From pavlovevidence at gmail.com Fri Sep 5 00:31:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 21:31:07 -0700 (PDT) Subject: Converting .doc to .txt in Linux References: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> <mailman.500.1220559557.3487.python-list@python.org> Message-ID: <42a43f18-2143-4cce-90f6-0ac5fe1807cd@8g2000hse.googlegroups.com> On Sep 4, 4:18 pm, Tommy Nordgren <tommy.nordg... at comhem.se> wrote: > On Sep 4, 2008, at 9:54 PM, patrick.wa... at gmail.com wrote: > > > > > Hi Everyone, > > > I had previously asked a similar question, > >http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > > but at that point I was using Windows and now I am using Linux. > > Basically, I have some .doc files that I need to convert into txt > > files encoded in utf-8. However, win32com.client doesn't work in > > Linux. > > > It's been giving me quite a headache all day. Any ideas would be > > greatly appreciated. > > > Best, > > Patrick > > > #Windows Code: > > import glob,os,codecs,shutil,win32com.client > > from win32com.client import Dispatch > > > input = '/home/pwaldo2/work/workbench/current_documents/*.doc' > > input_dir = '/home/pwaldo2/work/workbench/current_documents/' > > outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/' > > > for doc in glob.glob1(input): > > WordApp = Dispatch("Word.Application") > > WordApp.Visible = 1 > > WordApp.Documents.Open(doc) > > WordApp.ActiveDocument.SaveAs(doc,7) > > WordApp.ActiveDocument.Close() > > WordApp.Quit() > > > for doc in glob.glob(input): > > txt_split = os.path.splitext(doc) > > txt_doc = txt_split[0] + '.txt' > > txt_doc_path = os.path.join(outpath,txt_doc) > > doc_path = os.path.join(input_dir,doc) > > shutil.copy(doc_path,txt_doc_path) > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You can do it manually with Open Office. <http://www.openoffice.org/> > A free office suite. On Debian there is a package called "unoconv"--written in Python--that can do the conversions from the command line. It requires a running instance of Open Office. However, the doc-to-txt conversion of Open Office isn't that good. (It wasn't as good as Word's formatted text converter, last time I used it.) Carl Banks From pavlovevidence at gmail.com Thu Sep 11 17:13:37 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 11 Sep 2008 14:13:37 -0700 (PDT) Subject: Accessing __slots__ from C References: <mailman.793.1221057913.3487.python-list@python.org> Message-ID: <efaa21d2-6e94-4170-ae8e-e7ddb0cd5d2e@w1g2000prk.googlegroups.com> On Sep 10, 7:41 am, Chris <ceb... at users.sourceforge.net> wrote: > Hi, > > I'd like to be able to access an attribute of a particular Python > object as fast as possible from some C code. > > I wondered if using __slots__ to store the attribute would allow me to > do this in a faster way. > > The reason I'd like to do this is because I need to access the > attribute inside a loop within some C code, and I find that the > attribute lookup using the 'PyObject_GetAttrString' call is far slower > than any of the subsequent calculations I perform in C. > > Using the 'PyObject_GetAttrString' function to get the attribute, I > find it is slightly faster when the attribute is a slot than when it > isn't, but that the attribute lookup remains the performance-limiting > factor. You can determine the offset the of the slot in the object structure by querying the member descriptor of the type object. descr = GetAttrString(cls,"varname"); offset = descr->d_member->offset; slotvar = (PyObject*)(((char*)obj)+offset) There might be some macros to simplify this. Use at your own risk. Carl Banks From ptmcg at austin.rr.com Thu Sep 4 06:08:54 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 4 Sep 2008 03:08:54 -0700 (PDT) Subject: Issue warning if no "return" in function? References: <g9obtp$l83$1@gwdu112.gwdg.de> Message-ID: <6d2504d5-4dd6-49f9-abe5-bd03e5010d0d@v39g2000pro.googlegroups.com> On Sep 4, 5:05?am, Poster28 <usen... at anton.e4ward.com> wrote: > What would you suggest to check python programs for non-syntax error. > One example I could think of that one might forget to "return" a value from > a function. > > How could I check for these and maybe other mistakes? Check out PyLint (http://www.logilab.org/857) or PyChecker (http:// pychecker.sourceforge.net/). From toddw at activestate.com Tue Sep 16 21:16:19 2008 From: toddw at activestate.com (Todd Whiteman) Date: Tue, 16 Sep 2008 18:16:19 -0700 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <48C15F5F.7040704@activestate.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <b367b494-66ba-4bd0-a724-9bc77fcea97a@b30g2000prf.googlegroups.com> <mailman.466.1220517117.3487.python-list@python.org> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <48BFB534.2080508@egenix.com> <48C15F5F.7040704@activestate.com> Message-ID: <48D05A63.5040907@activestate.com> Todd Whiteman wrote: > Mark Hammond's Python/Mozilla work has enabled products like Komodo, > Miro (Democracy) and the OLPC project to use Python as a major driver > for consistent cross-platform GUI applications. > > Personally, I believe XULRunner has a lot to offer for Python GUI > development, I'm currently finishing up some documentation steps to show > off how to use it specifically for Python (I'll post it to this list > when it's finished). Here is the tutorial I've started in order to show off building a Python/XULRunner GUI application. http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html The details in this tutorial mostly targets a Windows/Linux platform (MacOSX is possible with a few deviations, I have tried to cover these deviations where applicable). Feedback is welcome. Cheers, Todd From alexandru.palade at sellerengine.com Thu Sep 4 07:49:11 2008 From: alexandru.palade at sellerengine.com (Alexandru Palade) Date: Thu, 04 Sep 2008 14:49:11 +0300 Subject: Safely move an element into a heap In-Reply-To: <f0b4a244-00e2-43b3-9b38-5e494472f030@z11g2000prl.googlegroups.com> References: <f0b4a244-00e2-43b3-9b38-5e494472f030@z11g2000prl.googlegroups.com> Message-ID: <48BFCB37.8030608@sellerengine.com> I'm not sure what you expect as an answer, but if you mean the heap as in the data structure, you can not just arbitrarily move one key where you want as it will destroy the heap property. Giampaolo Rodola' wrote: > Hi, > I wanted to know if does exist a safe way to, given a heap, move an > arbitrary element to the first position of the heap. > Something like: > > >>> heap = [0,3,6,8,10] > >>> heapq.move_to_first_position(heap, 4) > >>> heap = [10, 0,3,6,8] > > > --- Giampaolo > http://code.google.com/p/pyftpdlib/ > -- > http://mail.python.org/mailman/listinfo/python-list > > From darcy at druid.net Wed Sep 10 13:18:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 10 Sep 2008 13:18:12 -0400 Subject: md5 differences In-Reply-To: <7C2CD173-D069-41A0-9B56-382FF86F5B52@rgbaz.eu> References: <mailman.799.1221063937.3487.python-list@python.org> <ga8sn6$g69$1@south.jnrs.ja.net> <7C2CD173-D069-41A0-9B56-382FF86F5B52@rgbaz.eu> Message-ID: <20080910131812.b3729762.darcy@druid.net> On Wed, 10 Sep 2008 19:12:28 +0200 Python <python at rgbaz.eu> wrote: > hmm and this then: > > Arno at Computer:~% echo "test" > test.txt > > Arno at Computer:~% md5 test.txt > MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 > > Arno at Computer:~% python > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import md5 > >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() > '90364ed45b452d43378629c20543a81d' You're going to smack yourself on the head over this one. :-) >>> md5.new(open("/Volumes/data/Arno/test.txt").read()).hexdigest() -- D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From gherron at islandtraining.com Sun Sep 21 13:11:17 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 21 Sep 2008 10:11:17 -0700 Subject: I tried erlang-ish [1|2] in python and something came out... In-Reply-To: <cd796753-6ce1-4328-9683-346d1192ddf7@73g2000hsx.googlegroups.com> References: <cd796753-6ce1-4328-9683-346d1192ddf7@73g2000hsx.googlegroups.com> Message-ID: <48D68035.2020405@islandtraining.com> process wrote: > In erlang you can cons like this: [1|2]. i tried this in python and it > didnt raise an error but i dont know what the result do > In Python | is the logical bitwise-OR operator. Look at the binary representation of the numbers to understand it. Gary Herron > >>>> [1|2] >>>> > [3] > >>>> [2|2] >>>> > [2] > >>>> a = [2|2] >>>> a >>>> > [2] > >>>> [2|3] >>>> > [3] > >>>> [2|1] >>>> > [3] > > -- > http://mail.python.org/mailman/listinfo/python-list > From eric at ericabrahamsen.net Mon Sep 29 09:17:32 2008 From: eric at ericabrahamsen.net (Eric Abrahamsen) Date: Mon, 29 Sep 2008 21:17:32 +0800 Subject: Using re to find unicode ranges Message-ID: <530E89AB-634E-4660-BAAD-85F8AEC6364C@ericabrahamsen.net> Is it possible to use the re module to find runs of characters within a certain Unicode range? I'm writing a Markdown extension to go over text and wrap blocks of consecutive Chinese characters in <span class="char"></span> tags for nice styling in an HTML page. The available hooks appear to be a pre- processor (which is a "for line in lines" situation) or an inline pattern (which uses regular expressions). The regular expression solution would be much simpler and faster, but something tells me there's no way to use a regex to find character ranges... Chinese characters appear to fall between 19968 and 40959 using ord(), and I suppose I can go that route if necessary, but I think it would be ugly. Any hints or suggestions would be appreciated! Eric From dudeja.rajat at gmail.com Mon Sep 29 13:36:56 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 29 Sep 2008 18:36:56 +0100 Subject: Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars In-Reply-To: <e0b6c39a0809290910q1c368987k7db2615222602ab8@mail.gmail.com> References: <e0b6c39a0809280851m845dc29y63d20ee6ef6c511e@mail.gmail.com> <e0b6c39a0809290910q1c368987k7db2615222602ab8@mail.gmail.com> Message-ID: <e0b6c39a0809291036t3b28b30bweed6ccef1faa012d@mail.gmail.com> On Mon, Sep 29, 2008 at 5:10 PM, <dudeja.rajat at gmail.com> wrote: > > > On Sun, Sep 28, 2008 at 4:51 PM, <dudeja.rajat at gmail.com> wrote: > >> >> Hi, >> >> >> Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well >> the problem is I'm unable to scroll if I click on the arrows buttons of >> scrollbars ( with both types of scrollbars) >> >> >> Please suggest if I m missing some configuration. >> >> >> My code is as below: >> >> self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL) >> self.hsb.grid(row = 2,column = 0, sticky = E+W) >> #vertical scroll bar >> self.vsb = Scrollbar(appGuiFrame) >> self.vsb.grid(row = 1,column = 2, sticky = N+S) >> >> >> >> self.txtLogger = Text(appGuiFrame, \ >> height = 20,\ >> width = 100, \ >> state = DISABLED, \ >> xscrollcommand = self.hsb.set, \ >> yscrollcommand = self.vsb.set, \ >> wrap = NONE, \ >> font = ("courier",12)) >> self.hsb.config(command = self.txtLogger.xview()) >> self.vsb.config(command = self.txtLogger.yview()) >> >> >> Please help. >> >> >> Thanks and regards, >> Rajat >> > > > Hi folks, > > Any help on the above problem. > > Regards, > Rajat > Hi, The problem got solved. After finding for such a long time I got a snippet at google and used the same in my code. It solved the problem. Here is the complete code now: class cLogToGUI: def __init__(self, logObj, appGUI): self.__logger = logObj self.__logger.debug("Inside cLogToGUI::__init__") appGuiFrame = appGUI.frame4 #hor. scroll bar self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL) self.hsb.grid(row = 2,column = 0, sticky = E+W) #vertical scroll bar self.vsb = Scrollbar(appGuiFrame) self.vsb.grid(row = 1,column = 2, sticky = N+S) self.txtLogger = Text(appGuiFrame, \ height = 20,\ width = 100, \ state = DISABLED, \ xscrollcommand = self.hsb.set, \ yscrollcommand = self.vsb.set, \ wrap = NONE, \ font = ("courier",12)) #self.hsb.config(command = self.txtLogger.xview()) #self.vsb.config(command = self.txtLogger.yview()) self.hsb.config(command = self.__hsbScrollHandler) self.vsb.config(command = self.__vsbScrollHandler) self.txtLogger.bind("<<updateDisplay>>", self.outputText) self.txtLogger.grid(row = 1) self.txtLogger.tag_configure("error", foreground = "red") self.txtLogger.tag_configure("warning", foreground = "orange") self.txtLogger.tag_configure("success", foreground = "blue") self.__logger.debug("return from cLogToGUI::__init__") def outputText(self, event): self.__logger.debug("Inside cLogToGUI::outputText()") self.txtLogger.configure(state = NORMAL) string = TASymbols.strScrolledTextLine tag = TASymbols.strScrolledTextLineTag if not string: self.txtLogger.delete('1.0', END) else: self.txtLogger.insert(END, string, tag) #self.txtLogger.focus() self.txtLogger.see(END) self.txtLogger.configure(state = DISABLED) self.__logger.debug("return from cLogToGUI::outputText()") def __hsbScrollHandler(self, *L): op, howMany = L[0], L[1] if op == "scroll": units = L[2] self.txtLogger.xview_scroll ( howMany, units ) elif op == "moveto": self.txtLogger.xview_moveto ( howMany ) def __vsbScrollHandler(self, *L): op, howMany = L[0], L[1] if op == "scroll": units = L[2] self.txtLogger.yview_scroll ( howMany, units ) elif op == "moveto": self.txtLogger.yview_moveto ( howMany ) Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080929/f52e6d63/attachment-0001.html> From rcdailey at gmail.com Thu Sep 18 18:24:26 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 18 Sep 2008 17:24:26 -0500 Subject: Intercepting printed strings Message-ID: <496954360809181524g6037e0b0x84e98834bbf8ad9c@mail.gmail.com> Hi, I'm currently using Python 3.0 b3 and I'm curious as to how I can go about intercepting things send to print() for some intermediate processing before they're actually sent to sys.stdout. Right now I've thought of the following: Replace sys.stdout with a class named PrintStream. PrintStream is defined as follows: class PrintStream: def write( self, message ): sys.__stdout__.write( '\t{0}'.format( message ) ) Will this work? Basically I want to add a tab character in front of every message printed. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/572b3b99/attachment-0001.html> From grante at visi.com Mon Sep 15 01:13:48 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 15 Sep 2008 00:13:48 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> <HYednR9_TqqbWVDVnZ2dnUVZ_oDinZ2d@posted.usinternet> <mailman.1023.1221448972.3487.python-list@python.org> <87od2q5a24.fsf@benfinney.id.au> <oe6dnSQUy_B1eVDVnZ2dnUVZ_obinZ2d@posted.usinternet> <87k5de5841.fsf@benfinney.id.au> Message-ID: <gNednRyG3umRclDVnZ2dnUVZ_oHinZ2d@posted.usinternet> On 2008-09-15, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: > Grant Edwards <grante at visi.com> writes: > >> On 2008-09-15, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: >> > I think it's more important for Python library APIs to comply with >> > the Python coding guidelines (as specified in PEP 8) than to >> > comply with standards in other languages. >> >> I think the practical matter of being able to use existing >> documentation and examples > > How are examples written in another language a "practical matter" for > using a Python library? Surely less "practical" than having one's > Python code base use a consistent style. If there is already a set of documentation and usage examples for the library, then changing the names just for the sake of "purity" means that you've now got documentation that's wrong. For example, the vast majority of wxPython consists of wrapped C++ library routines. There is a large body of existing documentation and sample code for those library routines, and they're all CamelCase. IMO, following that documentation is more important and useful than having all the names changed to agree with other Python libraries. (It's also a lot less work.) -- Grant From nevillednz at gmail.com Mon Sep 1 01:06:45 2008 From: nevillednz at gmail.com (Neville Dempsey) Date: Mon, 1 Sep 2008 15:06:45 +1000 Subject: enhancing/wrapping an existing instance of a duck In-Reply-To: <b2ff67060808312100i557515faw11cc239f33df3fb2@mail.gmail.com> References: <b2ff67060808312100i557515faw11cc239f33df3fb2@mail.gmail.com> Message-ID: <b2ff67060808312206q1b02fa66x986902991f6e4f3d@mail.gmail.com> What do I need to add to HTMLDecorator? A simpler example: import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("<H1>","</H1>")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() Output: Traceback (most recent call last): File "html.py", line 21, in <module> print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters Can I simply decorate an existing instance? Cheers N From kyosohma at gmail.com Wed Sep 24 11:46:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Sep 2008 08:46:56 -0700 (PDT) Subject: urllib error on urlopen Message-ID: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> Hi, I have been using the following code for over a year in one of my programs: f = urllib2.urlopen('https://www.companywebsite.com/somestring') It worked great until the middle of the afternoon yesterday. Now I get the following traceback: Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> response = urllib2.urlopen(req).read().strip() File "c:\python25\lib\urllib2.py", line 124, in urlopen return _opener.open(url, data) File "c:\python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "c:\python25\lib\urllib2.py", line 399, in _open '_open', req) File "c:\python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "c:\python25\lib\urllib2.py", line 1115, in https_open return self.do_open(httplib.HTTPSConnection, req) File "c:\python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: <urlopen error (1, 'error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol')> I tried my Google Fu on this error, but there's not much out there. I tried using a proxy in Python, but that returned the same traceback. If I copy the URL into my browser, it resolves correctly. Does anyone have any advice on how to troubleshoot this error? I am using Python 2.5.2 on Windows XP. Thanks, Mike From gstaniak at wp.pl Wed Sep 10 09:57:36 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Wed, 10 Sep 2008 13:57:36 +0000 (UTC) Subject: PHP's str_replace ? References: <mailman.788.1221054649.3487.python-list@python.org> Message-ID: <ga8jog$818$1@news.lublin.pl> On 10.09.2008, Anjanesh Lekshminarayanan <mail at anjanesh.net> wroted: > In PHP, if I do > str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) > it'll replace all vowels with a hyphen in string $str. > > Is there some equivalent in Python ? The .translate() method of strings? >>> import string >>> mystr = "This is just a test" >>> transtable = string.maketrans("aeiouy","------") >>> mystr.translate(transtable) 'Th-s -s j-st - t-st' GS -- Grzegorz Staniak <gstaniak _at_ wp [dot] pl> Nocturnal Infiltration and Accurate Killing From timr at probo.com Sat Sep 6 22:02:17 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 07 Sep 2008 02:02:17 GMT Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: <mcd6c4hksn46jh23gq5evr73512ehhaasn@4ax.com> cnb <circularfunc at yahoo.se> wrote: > >So is the free lunch really over or is this just an overhyped >phenomena? Remember that your computer is not running one single program. An idle computer on either Windows or Linux typically has dozens of processes running. Even if all of those programs are single-threaded, you'll still be able to keep all of the cores busy. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From fredrik at pythonware.com Wed Sep 10 07:45:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 13:45:54 +0200 Subject: List of modules available for import inside Python? In-Reply-To: <aec1f937-e1e2-41bd-8a39-74428ff2169d@l64g2000hse.googlegroups.com> References: <e121e2c5-8ebd-4d42-835e-46b52e3c2053@t54g2000hsg.googlegroups.com> <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> <QABwk.25014$N87.11966@nlpi068.nbdc.sbc.com> <mailman.648.1220787169.3487.python-list@python.org> <dcXwk.12440$vn7.2449@flpi147.ffdc.sbc.com> <aec1f937-e1e2-41bd-8a39-74428ff2169d@l64g2000hse.googlegroups.com> Message-ID: <ga8c1i$gtk$1@ger.gmane.org> denisbz at t-online.de wrote: > how can I list all modules that might be importable on my system, > without actually importing them all ? I'm pretty sure I mentioned a way to do that back when this thread was opened. let's see, yes, here it is: ... there's a helper script in the 2.5 source code kit that locates all existing standard modules: http://svn.python.org/projects/python/tags/r252/Doc/tools/listmodules.py to get all modules, remove the for-loop that follows after the comment "get rid of site packages". also see: http://effbot.org/zone/listmodules-cgi.htm ... </F> From lists at cheimes.de Tue Sep 2 16:41:51 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 02 Sep 2008 22:41:51 +0200 Subject: Numeric literal syntax In-Reply-To: <g9jsti$uf0$2@ger.gmane.org> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <pan.2008.09.02.06.10.51@REMOVE.THIS.cybersource.com.au> <6i56cpFor2puU1@mid.individual.net> <g9jsti$uf0$2@ger.gmane.org> Message-ID: <g9k8ee$8g0$1@ger.gmane.org> Fredrik Lundh wrote: > Peter Pearson wrote: > >> (startled noises) It is a delight to find a reference to >> that half-century-old essay (High Finance) by the wonderful >> C. Northcote Parkinson, but how many readers will catch the >> allusion? > > anyone that's been involved in open source on the development side for > more than, say, ten minutes. Indeed! Thus speaks the experienced developer -- effbot :) On some mailing lists the bikeshed issue comes hand in hand with the Dunning-Kruger-effect. [1] *sigh* Christian [1] http://en.wikipedia.org/wiki/Dunning-Kruger_effect From gagsl-py2 at yahoo.com.ar Tue Sep 23 03:26:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Sep 2008 04:26:14 -0300 Subject: gplt from scipy missing ? References: <lckgd4dsk4hqfsibr5ldv3tnc3dl6lfvum@4ax.com> Message-ID: <op.uhxax0ywx6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 22 Sep 2008 23:19:49 -0300, Ivan Reborin <ireborin at delete.this.gmail.com> escribi?: > I'm relatively new to python. I'm following a tutorial I found on the > net, and it uses scipy's gplt for plotting. > I installed scipy from their website (win32 installation), numpy also, > but when I do > > from scipy import gplt > > it gives this error: > > Traceback (most recent call last): > File "<pyshell#0>", line 1, in <module> > from scipy import gplt > ImportError: cannot import name gplt > > Please, can you help me solve this ? How do I get gplt to work ? > All advice appreciated. I think scipy does not bundle plotting packages anymore - you may use whatever suits you, from other sources. Try matplotlib, see the wiki: http://wiki.python.org/moin/NumericAndScientific/Plotting -- Gabriel Genellina From david.lyon at preisshare.net Wed Sep 10 20:08:27 2008 From: david.lyon at preisshare.net (david.lyon at preisshare.net) Date: Wed, 10 Sep 2008 20:08:27 -0400 Subject: Web shopping carts In-Reply-To: <C4EB6DE0.11187%luke.hamilton@rpm-solutions.com.au> References: <C4EB6DE0.11187%luke.hamilton@rpm-solutions.com.au> Message-ID: <20080910200827.mo3h02ds5c40s0ss@syd-srv02.ezyreg.com> Quoting Luke Hamilton <luke.hamilton at rpm-solutions.com.au>: > I am wondering if there are any OS shopping cart application written > in python? Hi Luke, I'm sure there are a few..... But recently I have been asked by two customers to provide a solution. So I'm thinking about the same thing. Actually, I've looked at a few systems like OS-commerce and so forth and my impression is that they are a bit old fashioned. As in, the web has moved a bit on since these projects started. Plus, I have customers in the computer industry, whose requirements are a bit different than the generalist cart programs. They want to pull prices in from spreadsheets and have price auto-calculations etc Basically, what I have put some work into has a search screen a bit like a search engine, and tries to combine leading edge javascript effects with a CherryPy/Cheetah back end. There's also some fantastic javascript slideshows out there.. I was never excited about what web systems could do.... until now.... javascript effects are just plain amazing... and what better to drive it than a python back end.... Let me know what you think... From ali.hamad34 at gmail.com Mon Sep 29 19:01:02 2008 From: ali.hamad34 at gmail.com (Ali Hamad) Date: Mon, 29 Sep 2008 18:01:02 -0500 Subject: Socket Question Message-ID: <48E15E2E.30901@gmail.com> Hello All : A socket question from a networking newbie. I need to create a server that: 1) receive a message from client. 2) check that message and response to it. 3) the client get the server message and send another message. 4) finally, the server receive the message and close the connection. I have successfully done this. However, I couldn't use the same socket to send the second message to the server. I have googled but all the examples are only for sending one message and receiving the response. in my client code, I have : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 1888)) s.send("1st message") response = s.recv(1024) validate(response) s.send("2nd message") response2 = s.recv(1024) s.close() However, I got the first response just fine from the server but the second message didn't get to the server. So, the solution I came up with is to send the 1st message, close the socket, create new socket, and send the 2nd message. I came up with something like : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 1888)) s.send("1st message") response = s.recv(1024) s.close() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 1888)) s.send("2nd message") response = s.recv(1024) s.close() and it works ! My Question : is it possible to send/receive from the same socket more than one message ? Thank you for your assistance in advance, From mail at timgolden.me.uk Mon Sep 1 12:09:49 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 01 Sep 2008 17:09:49 +0100 Subject: CSV reader and unique ids In-Reply-To: <6599d785-87b2-4bbc-97bc-799cac3640f5@b1g2000hsg.googlegroups.com> References: <6599d785-87b2-4bbc-97bc-799cac3640f5@b1g2000hsg.googlegroups.com> Message-ID: <48BC13CD.1010704@timgolden.me.uk> Mike P wrote: > I'm trying to use the CSV module to read in some data and then use a > hashable method (as there are millions of records) to find unique ids > and push these out to another file, You could either zip with a counter or use the uuid module, depending on just how unique you want your ids to be. <code> import os, sys import csv import itertools import uuid stuff = "the quick brown fox jumps over the lazy dog".split () f = open ("output.csv", "wb") writer = csv.writer (f) # # Style 1 - numeric counter # writer.writerows (zip (itertools.count (), stuff)) # # Style 2 - uuid # writer.writerows ((uuid.uuid1 (), s) for s in stuff) f.close () os.startfile ("output.csv") </code> TJG From bearophileHUGS at lycos.com Sun Sep 28 16:06:29 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 28 Sep 2008 13:06:29 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <mailman.1637.1222629451.3487.python-list@python.org> Message-ID: <24621a13-1199-42b8-a603-bd74964f2e92@j22g2000hsf.googlegroups.com> Terry Reedy: > Partly history and partly practicality. Len is implemented as .__len__ > ;-). The len function is one, __len__ methods are many. If you want to > pass an argument to a function, passing len is easier that passing > operator.attrgetter('__len__'). Passing '__len__' (or 'len') would be > easy, but using len is easier than using getattr(ob,'__len__'). A simple example may help: >>> seq = ["aaaa", "bb", "c", "ddd"] >>> seq2 = [[1,1,1,1], [2,2], [3], [4,4,4]] >>> sorted(seq, key=len) ['c', 'bb', 'ddd', 'aaaa'] >>> sorted(seq2, key=len) [[3], [2, 2], [4, 4, 4], [1, 1, 1, 1]] >>> sorted(seq, key=str.__len__) ['c', 'bb', 'ddd', 'aaaa'] >>> sorted(seq2, key=str.__len__) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: descriptor '__len__' requires a 'str' object but received a 'list' >>> from operator import attrgetter >>> sorted(seq, key=attrgetter("__len__")) ['aaaa', 'bb', 'c', 'ddd'] >>> sorted(seq2, key=attrgetter("__len__")) [[1, 1, 1, 1], [2, 2], [3], [4, 4, 4]] Bye, bearophile From gminick at bzt.bzt Wed Sep 3 10:34:12 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 3 Sep 2008 14:34:12 +0000 (UTC) Subject: properties setting each other References: <mailman.427.1220450289.3487.python-list@python.org> <g9m73j$1d9$1@inews.gazeta.pl> Message-ID: <g9m793$1vi$1@inews.gazeta.pl> On Wed, 3 Sep 2008 14:31:17 +0000 (UTC), Wojtek Walczak wrote: > class Square(object): > def __init__(self, val): > self._square = pow(val, 2) > self._value = math.sqrt(self.square) ^^^^^^^^^^^^^^^^^^^^^^ or just: self._value = val :-) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From straton at lampsacos.demon.co.uk Fri Sep 5 13:54:52 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 05 Sep 2008 18:54:52 +0100 Subject: max(), sum(), next() In-Reply-To: <dullrich-33A94E.10163805092008@text.giganews.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <g9r7hq$ri6$1$8302bc10@news.demon.co.uk> <dullrich-33A94E.10163805092008@text.giganews.com> Message-ID: <g9rrpd$bkc$1$8302bc10@news.demon.co.uk> David C. Ullrich wrote: > In article <g9r7hq$ri6$1$8302bc10 at news.demon.co.uk>, > Ken Starks <straton at lampsacos.demon.co.uk> wrote: > >> David C. Ullrich wrote: >> >>> I don't see why you feel the two should act the same. >>> At least in mathematics, the sum of the elements of >>> the empty set _is_ 0, while the maximum element of the >>> empty set is undefined. >>> >>> And both for good reason: >>> >>> (i) If A and B are disjoint sets we certainly want to >>> have sum(A union B) = sum(A) + sum(B). This requires >>> sum(empty set) = 0. >>> >>> (ii) If A is a subset of B then we should have >>> max(A) <= max(B). This requires that max(empty set) >>> be something that's smaller than everything else. >>> So we give up on that. >> Do we give up? Really ? > > Erm, thanks. I was aware of all that below. If we're > being technical what's below is talking about the sup > and inf, which are not the same as max and min. More > relevant to the present context, I didn't mention what's > below because it doesn't seem likely that saying max([]) > = -infinity and min([]) = +infinity is going to make the > OP happy... > Of course you were aware, I have seen enough of your posts to know that. And I agree that, whatever Wikipedia seems to imply, max and supremum should be distiguished. It was your prelude, "At least in mathematics ..." that made me prick up my ears. So I couldn't resist responding, without _any_ malice I assure you. Cheers, Ken. From nevare.stark at gmail.com Sun Sep 28 06:01:12 2008 From: nevare.stark at gmail.com (Olivier Lauzanne) Date: Sun, 28 Sep 2008 03:01:12 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <66606235-be55-458a-9e14-09e6c766201d@p31g2000prf.googlegroups.com> Message-ID: <f7407388-646e-4617-b74e-798df8330b63@t54g2000hsg.googlegroups.com> On Sep 28, 11:21 am, est <electronix... at gmail.com> wrote: > On Sep 28, 4:38 pm, Steven D'Aprano <st... at REMOVE-THIS- > Can anyone tell me how to customize a default encoding, let's say > 'ansi' which handles range(256) ? I assume you are using python2.5 Edit the file /usr/lib/python2.5/site.py There is a method called def setencoding(): [...] encoding = "ascii" [...] Change "encoding = "ascii" to encoding = "utf-8" On windows you may have to use "mbsc" or something like that. I have no idea what windows use at its encoding. As long as all systems don't use the same encoding (let's say utf-8 since it is becoming the standard on unixes and on the web) using ascii as a default encoding makes sense. From bj_666 at gmx.net Tue Sep 2 14:47:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 18:47:39 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <mailman.370.1220369964.3487.python-list@python.org> Message-ID: <6i5g2aFol29aU6@mid.uni-berlin.de> On Tue, 02 Sep 2008 11:39:09 -0400, Derek Martin wrote: > On Tue, Sep 02, 2008 at 01:57:26PM +0000, Marc 'BlackJack' Rintsch > wrote: >> > I would argue that they don't represent processes at all; the object >> > is a set of files which connect the standard I/O streams of a >> > subprocess to its parent, and methods to operate on those files. >> >> And the process' ID, an attribute with the process' return code, a >> method to wait until the process is finished and file objects to >> communicate with the process. > > The name popen is an abbreviation of "pipe open" -- the function, and > the class, open pipes to communicate with another process. What you > said is correct; however there are numerous other ways to open > subprocesses. The focus of popen is the communication aspect -- the > opening and control of the pipes -- not the subprocess. That's the key > difference between popen() and all the other methods of starting a > subprocess. But I'm not talking about the `popen()` function but the `subprocess.Popen` class. >> > The C library's popen() function, on which this class is based, >> > provides a means to open a file and connect it to the standard steams >> > of a subprocess, making it more closely analogous to what the Popen >> > class does/provides. As such, "Popen" is a better name to describe >> > this object than "subprocess" would be. >> >> Is strongly disagree. The class provides an interface to start and >> communicate with a `Subprocess`. Instances stand for processes. > > There's more than one way to look at it. You can disagree all you like, > but your interpretation disagrees with the historical intent of popen. That's why I think the name `Popen` is not so good for it. Because it does more than `popen()` and if it is called `Subprocess` or just `Process` then it would be merely an implementation detail, that the `popen()` function is called at some point. If it is at all, because `popen()` on C level can just open a pipe in *one* direction. > Note that in all of these links that talk about popen, the focus is on > opening pipes or file objects, not on subprocesses: > > http://www.opengroup.org/onlinepubs/009695399/functions/popen.html > http://docs.python.org/lib/os-newstreams.html http://us3.php.net/popen > http://docs.hp.com/en/B9106-90010/popen.3S.html > http://www.faqs.org/docs/artu/ch07s02.html And all of the links talk about the `popen()` function, not about the functionality the `Popen` class provides. Which is much more than that simple pipe `popen()` returns. > The Linux man page unfortunately copies (verbatim) the FreeBSD man page, > which gets it wrong. You can not open a process, but you can definitely > open a pipe. Ah, when their terminology doesn't match yours, they must get it wrong. ;-) Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:03:43 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:03:43 GMT Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <pan.2008.09.24.06.17.06@REMOVE.THIS.cybersource.com.au> <JcKdndouSNGG10fVnZ2dnUVZ_hCdnZ2d@posted.visi> <gbdmgh$nd0$1@rumours.uwaterloo.ca> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> Message-ID: <00eaeb52$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 10:54:40 -0500, Grant Edwards wrote: > You're right. I had forgotten that sys.exit() is actually raising the > system exit exception, and that the application calling the library > could handle that exception. Could but shouldn't. The exception hierarchy was re-designed in Python 2.5 specifically so that SystemExit and KeyboardInterrupt no longer inherit from Exception. That means this will do the right thing: try: process(record) if changed: update(record) except Exception: # don't write the record if any error occurs pass Neither SystemExit nor KeyboardInterrupt are errors, and they should not be treated as errors. I quote from the Fine Manual: [SystemExit] inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception. This allows the exception to properly propagate up and cause the interpreter to exit. http://docs.python.org/lib/module-exceptions.html SystemExit is not an error. KeyboardInterrupt is not an error. Libraries should not use SystemExit to signal an error any more than they should use MemoryError to signal a missing attribute. Whether or not an application exits is up to the application to decide, not the library it wraps. Libraries should report errors by raising an Exception (note the capital E), and the application should decide whether or not it is recoverable, and if not, exit (perhaps by simply not catching the exception). -- Steven From jinbow at gmail.com Mon Sep 8 08:47:54 2008 From: jinbow at gmail.com (Mars creature) Date: Mon, 8 Sep 2008 05:47:54 -0700 (PDT) Subject: Read and write binary data References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> <d8a36ffa-c8c7-4cc0-8e32-328b0587d689@59g2000hsb.googlegroups.com> Message-ID: <f9f2dc6d-954a-43fa-9ff8-975554f92b03@y38g2000hsy.googlegroups.com> On Sep 7, 8:55 pm, Patrick Maupin <pmau... at gmail.com> wrote: > On Sep 7, 5:41 pm, Mars creature <jin... at gmail.com> wrote: > > > Hi guys, > > I am new to Python, and thinking about migrating to it from matlab > > as it is a really cool language. Right now, I am trying to figure out > > how to control read and write binary data, like > > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > > I googled, but can not find a clear answer. Anyone has clue where can > > I learn it? Thanks!! > > Jinbo > > Start by looking at the array module. > > Regards, > Pat Thanks!! From castironpi at gmail.com Thu Sep 25 21:01:22 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 25 Sep 2008 18:01:22 -0700 (PDT) Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <e342f2e9-1de1-4550-afa6-2601a05683f5@a2g2000prm.googlegroups.com> On Sep 25, 2:24?pm, python-... at arcor.de wrote: > Hi, > > sorry, I have these ideas for longer than 10 years, please have a look on it > and comment on it. Thx. > > ---- > > This is another proposal for introducing types into Python. > > There are many reasons for incorporating types into Python, but there is > also a lot of concern about doing so because of destroying the original > character of Python as a smart script language. > > This proposal adds several advantages of Prolog(ue) techniques without > changing the natural understanding of Python as a language. > > Proposal: > > 1. Method definitions can be non-unique if a type is prefixed to one or more > of its parameters, or the parameters differ in number. > > 2. A keyword 'reject' is added. > > 3. A keyword 'fail' is added. > > 4. A keyword 'cut' is added. > > Definition: > > 1. A "type" is a String naming the actual class or class family which the > passed instanced is derived from, prefixing the parameter. > > 2. "'reject'" is a marker inside a function/method and signals that further > processing will not be done inside this method, but instead be passed to the > next available function/method in row, otherwise an implicit "fail" will > occur. > > 3. "'fail'" is a marker inside a function/method and signals that NO further > processing can be done in neither of this or the following > functions/methods. > > 4. "'cut'" is a marker inside a function/method that signals that the > failure of called functions/methods inside of it, following this statement, > automatically lead to a failure, instead of trying the next method - > normally, it would be "reject" instead. > > 5. Failure of functions/methods to outside of this new context are signalled > with a new exception e.g. "MethodRetrialError". > > E.g. > > def whoisthethief("List" x): > ? return iknowit(x) > > def whoisthethief("String" x, "String" y): > ? return iknowit([x,y]) > > ########## > > def numeral_add(a, b): > ? if type(a)!=types.IntType: > ? ? reject > ? ... > > # equivalent to: > > def numeral_add("Integer" a, b): > ? ... Would you settle for a class or classes which had the same functionality, only you would call its methods with parentheses? Modified examples: @argtype( List ) def whoisthethief(x): return iknowit(x) @argtype( String, String ) def whoisthethief(x, y): return iknowit([x,y]) def numeral_add(a, b): if type(a)!=types.IntType: reject() ... /or: def numeral_add(a, b): if type(a)!=types.IntType: flow.reject() ... From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 13:53:05 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 19:53:05 +0200 Subject: Coming from .NET and VB and C In-Reply-To: <d20e9c18-9607-4746-a34a-c37ef6c22aef@d45g2000hsc.googlegroups.com> References: <d20e9c18-9607-4746-a34a-c37ef6c22aef@d45g2000hsc.googlegroups.com> Message-ID: <48beeaf1$0$12000$426a74cc@news.free.fr> ToPostMustJoinGroup22 a ?crit : > I'm coming from a .NET, VB, C background. > > C was good, and VB was better (with all of its libraries). Than .NET > came along and all the libraries you can require are ready to go. I > have no preference with MySQL or SQL, stored procedures or ad-hoc > queries. > > SO, I'm interested in using my Google App space (free 500MB) to > develop a quick database application. Using Python. I found "Dive > Into Python" which I will be reading shortly. > > Any suggestions for someone new to the scene like me? The worst thing you could would be to try to write VB in Python. While Python may not - for someone coming from more mainstream languages - look as weird as Lisp or Haskell or etc..., it's really a totally different beast. Lurking here, trying to answer other's persons questions, and reading other peoples solution might be a good way to learn idiomatic Python. From gagsl-py2 at yahoo.com.ar Thu Sep 25 16:04:54 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Sep 2008 17:04:54 -0300 Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <op.uh1zegu3x6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 25 Sep 2008 16:24:58 -0300, <python-pep at arcor.de> escribi?: > sorry, I have these ideas for longer than 10 years, please have a look > on it > and comment on it. Thx. > > This is another proposal for introducing types into Python. You got the terminology wrong. Python had "types" from the very start. You're talking about some kind of generic functions, or an alternative dispatch method. Read this GvR blog post [1] and his next one; also see PEP 3124 by Phillip J. Eby, who wrote a pretty good implementation of generic functions a long time ago. Your proposal requires a syntax change and three new keywords; all the others achieve roughly equivalent results without requiring any change to the core language. [1] http://www.artima.com/weblogs/viewpost.jsp?thread=155123 -- Gabriel Genellina From george.sakkis at gmail.com Tue Sep 23 13:50:52 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 23 Sep 2008 10:50:52 -0700 (PDT) Subject: Docstrings for class attributes References: <mailman.1392.1222147427.3487.python-list@python.org> Message-ID: <f301fd11-612c-46af-8fff-ca4b1d7fdeb3@e39g2000hsf.googlegroups.com> On Sep 23, 1:23 am, "Tom Harris" <celephi... at gmail.com> wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. Sort of > a very limited implementation of PEP 224. The only solution that I can > see is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Here's one approach, using metaclasses and descriptors; it sort of works, but it's less than ideal, both in usage and implementation. George #====== usage ============================================ class MyConstants: __metaclass__ = ConstantsMeta FOO = const(1, 'some docs about foo') BAR = const(2) print MyConstants.FOO.__doc__ help(MyConstants.FOO) print MyConstants.FOO - MyConstants.BAR print MyConstants.FOO - 2 print 1 - MyConstants.BAR #======= implementation =================================== def ConstantsMeta(name, bases, namespace): for name,attr in namespace.iteritems(): if isinstance(attr, const): namespace[name] = _ConstDescriptor(name, attr.value, attr.doc) return type(name, bases, namespace) class const(object): def __init__(self, value, doc=None): self.value = value self.doc = doc class _ConstDescriptor(object): def __init__(self, name, value, doc): cls = type(name, (), dict( __doc__ = doc, __add__ = lambda self,other: value+other, __sub__ = lambda self,other: value-other, # ... __radd__ = lambda self,other: other+value, __rsub__ = lambda self,other: other-value, # XXX lots of boilerplate code for all special methods follow... # XXX Is there a better way ? )) self._wrapper = cls() def __get__(self, obj, type): return self._wrapper From mccredie at gmail.com Mon Sep 22 17:52:39 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 22 Sep 2008 14:52:39 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> Message-ID: <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> On Sep 22, 2:31?pm, CapnBearbo... at googlemail.com wrote: > hi all, > > forgive me , but the RTFM and Google search approaches are not > yielding an answer on this question. ?I need to know if there's a top > level python interpreter command that clears all user variables (not > built-ins) from the global namespace. ?In other words a statement, or > some_command_or_function(), that does this: > > >>> x=3 > >>> y=4 > >>> z=[] > >>> dir() > > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > > >>> some_command_or_function() > >>> dir() > > ['__builtins__', '__doc__', '__name__'] > > thanks, > ? ?1 desperate snake oil programmer .... I don't think you will find anything. The interpreter is essentially the same whether you are in interactive mode or not. That is, there is very little use for a method that clears globals in general, so why would we add it just so that it could be used by the interpreter. There is almost* nothing available to the interactive interpreter which isn't part of the core language. * The only difference I can think of is the "_" variable, which is added to __builtins__ and contains the last value returned in interactive mode. If you have ever tried to run code that uses the locale module from the interpreter you will see why having any differences between the interactive and non-interactive interpreter can be a pain. Matt From mark.dufour at gmail.com Tue Sep 30 06:19:17 2008 From: mark.dufour at gmail.com (Mark Dufour) Date: Tue, 30 Sep 2008 12:19:17 +0200 Subject: Shed Skin (restricted) Python-to-C++ compiler 0.0.29 Message-ID: <8180ef690809300319o66cb9096sa4be2e5068836024@mail.gmail.com> Hi all, I have just released Shed Skin 0.0.29, with the following changes. Thanks to those mentioned for helping out! - datetime implementation (Karel Heyse, Pavel Vinogradov, FFAO, David Marek) - ConfigParser implementation (suggested by Albert Hofkamp) - staticmethod and property decorator support (Seo Sanghyeon) - GCC 4.3 fixes (Seo Sanghyeon, Winterknight) - FreeBSD, OpenSolaris and 64-bit support - support for mapping keys('%(key)x' % some_dict) - improvements to the import mechanism for nested modules (e.g. os.path) - __init__ is now less of a special case - many fixes for calling ancestor methods (e.g. __init__) - all example programs now compile to extension modules - avoid stack overflows for highly recursive/dynamic types - re.sub now accepts a replacement function - remove tuple hash caching (as CPython does not do this) - many, many bugfixes This has been a significant release, with many important improvements. Please see my latest blog entry with more details: http://shed-skin.blogspot.com/ I would really like to receive more bug reports. Please try out the new release, and file issues at the project homepage: http://shedskin.googlecode.com More coding help is also always welcome. One important feature I'd really like to have for a 0.1 release is custom class support in extension modules.. Thanks! Mark. -- "One of my most productive days was throwing away 1000 lines of code" - Ken Thompson From gboutsioukis at gmail.com Mon Sep 29 13:03:00 2008 From: gboutsioukis at gmail.com (George Boutsioukis) Date: Mon, 29 Sep 2008 17:03:00 +0000 (UTC) Subject: One class per file? References: <a932e44b-3566-4c0f-8b63-2dce0a82946b@34g2000hsh.googlegroups.com> Message-ID: <1222707780.889897@athprx03> On Mon, 29 Sep 2008 06:12:35 -0700, HCB wrote: > Hello: > > The book "Code Complete" recommends that you put only one class in a > source file, which seems a bit extreme for me. It seems that many > classes are small, so that putting several of them in a file seems > reasonable. I noticed that the decimal.py module in the standard library > has several classes, all of which of course revolve around the "decimal" > topic. Perhaps a better rule of thumb is "one idea per file." I checked > the Python style guide and there seems to be no mention of this topic. I > know this is an elementary question, but what is the Python way of doing > this? > > Thanks for your time. > HCB That sounds terrible! Imagine having a million source files to edit, rename, create, delete each time you make a change. Sure, every Java fan can give you a million reasons why the universe will collapse otherwise, but this is totally impractical in python. Python's module organization and namespaces are more than enough if used reasonably. From stefan_ml at behnel.de Thu Sep 11 13:07:05 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 11 Sep 2008 19:07:05 +0200 Subject: Is there a SOAP module that can do this...? In-Reply-To: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> References: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> Message-ID: <48c95039$0$3535$9b4e6d93@newsspool3.arcor-online.net> thebjorn wrote: > I've been trying to use SOAPpy and ZSI (with and without the use of > wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic > server(?) in front of some enterprise java bean) and not having much > luck. Have you tried using soaplib? I find it very usable and from what I heard so far, a couple of other people also like it a lot better than ZSI. Stefan From niklas.norrthon at hotmail.com Tue Sep 16 09:36:34 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Tue, 16 Sep 2008 06:36:34 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? References: <cb798579-d5d9-4a2f-843b-6fcca31fb5de@e39g2000hsf.googlegroups.com> <d2c7b432-2cd3-449b-bcb4-58e6f614f4f4@z72g2000hsb.googlegroups.com> <92d472c8-4af1-432a-a240-f9f9c97686eb@m73g2000hsh.googlegroups.com> Message-ID: <f8804b02-21d1-40a0-8b6c-13026cdfee86@l64g2000hse.googlegroups.com> On 16 Sep, 15:27, cnb <circularf... at yahoo.se> wrote: > i can run the interpreter. its just i cant load a file into it. > > i tried adding your suggestion but it didnt help. i dont think thats > the issue though. Start the interperter (Menu Python - Start interpreter) Emacs split the frame in two windows Place the cursor in the python file (C-x o) if necessary Eval Buffer (C-c C-c) Niklas Norrthon From fredrik at pythonware.com Mon Sep 1 10:45:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Sep 2008 16:45:24 +0200 Subject: Eleganz way to get rid of \n In-Reply-To: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: <g9gv67$10a$1@ger.gmane.org> Hans M?ller wrote: > I'm quite often using this construct: > > for l in open("file", "r"): > do something > > here, l contains the \n or \r\n on windows at the end. nope -- if you open a file in text mode (without the "b"), the I/O layer will translate "\r\n" to "\n" on Windows. if you want even more robust behaviour, use the "U" flag (for universal newlines); that'll handle old-style Mac files too. (as others have pointed out, a plain rstrip() is usually the best choice anyway. giving meaning to trailing whitespace in text files is usually a really lousy idea). </F> From d3vvnull at gmail.com Wed Sep 24 16:34:37 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Wed, 24 Sep 2008 15:34:37 -0500 Subject: Fwd: Twisted vs. CherryPy vs. ??? for light-weight web servers In-Reply-To: <170543c70809241334t4d687c50s3fd6e7fe4b4bab1d@mail.gmail.com> References: <170543c70809231922m23531eb9i1f7fdead10bb1e0e@mail.gmail.com> <20080924172915.29191.775453525.divmod.quotient.30199@ohm> <170543c70809241334t4d687c50s3fd6e7fe4b4bab1d@mail.gmail.com> Message-ID: <170543c70809241334o1e5642chd44a85209867d39b@mail.gmail.com> I just want to be able to write simple scripts to serve xml data and don't want the headache of administrating an apache server. I want to collect some data from some of our production servers and share them with a sharepoint website. On Wed, Sep 24, 2008 at 12:29 PM, Jean-Paul Calderone <exarkun at divmod.com>wrote: > On Tue, 23 Sep 2008 21:22:08 -0500, Michael Mabin <d3vvnull at gmail.com> > wrote: > >> Is there any consensus on what the best lightweight web-server is? Or >> rather would Twisted be a better choice to choose as a framework that >> allows >> me to serve html or xml data for light webservices. Or is CherryPy just as >> good? >> >> > You haven't described the problem you want to solve in very much detail. I > can't tell, for example, why I shouldn't recommend that you use Apache > instead > of CherryPy or Twisted or anything else. Apache has a huge user community, > lots of documentation, and lots of developers fixing its bugs and making it > work well. What are you trying to do that would make Apache a bad choice? > > Jean-Paul > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080924/f110a519/attachment-0001.html> From malcolm.lewis at gmail.com Tue Sep 2 09:26:03 2008 From: malcolm.lewis at gmail.com (Malcolm Lewis) Date: Tue, 2 Sep 2008 06:26:03 -0700 Subject: How do I adjust the font size on IDLE when running on Mac OS 10.5.4? TIA. Message-ID: <16a5d0100809020626w78312e35l52b7c73eabf8add4@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/b4285001/attachment-0001.html> From castironpi at gmail.com Fri Sep 26 21:58:30 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 18:58:30 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> <48DCC786.2040407@wildenhain.de> <mailman.1551.1222447687.3487.python-list@python.org> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <mailman.1572.1222472905.3487.python-list@python.org> <f9b466b0-9945-42c1-ad9c-2f65c8d4b907@y38g2000hsy.googlegroups.com> <mailman.1574.1222477862.3487.python-list@python.org> Message-ID: <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> On Sep 26, 8:10?pm, "Tim Rowe" <digi... at gmail.com> wrote: > 2008/9/27 Aaron Castironpi Brady <castiro... at gmail.com>: > > > But I, and I imagine I'm not the only one, would love to know the > > example that C# developed faster than Python. ?I suppose the fact that > > the line of wx specification that has two identifiers where C# has one > > is more of a drain on programmer resources than may commonly be > > recognized--- not the same as the cost of one extra word in a paper or > > in an editorial. ?Similarly, maybe the program that has one extra > > identifier in a line takes a lot more time to develop. > > But I didn't use wx -- that's rather the point. ?Long before the days > of Python, I kept wanting to use Modula2 but kept getting driven back > to C because in Modula2 I kept having to write stuff that was already > in C libraries. Modula2 was a far better language, but C usually was > far more productive because of what went around it. ?C#'s tight > integration with .net and VS mean that it's not a question of one > identifier instead of two, it's *zero* identifiers instead of two > because the tool does it all for me. ?Does that mean that C# is a > better language than Python? No, of course not. Does it mean that what > I was doing was not possible in Python? No, of course not. Does it > mean that C# was more productive than Python for me doing that > particular job? Yes it does. (FWIW, I also found the .net XML handling > easier to cope with on that same job). > > One day Iron Python plus the VS integration might wean me off C# but > last time I looked it wasn't close. Maybe I should take another look > and see how it's coming on. > > -- > Tim Rowe No way. It's *zero* instead of one, if so, because the only thing C# has is a bunch of handcuffs and implicit 'self'. You have a line like: n= aTree.ExpandedCount What in 'wx', which I -am- using, <avoids insubordinate tone>, takes more identifiers: n= self.aTree.ExpandedCount or if you're 'inlining', for lack of better words, everything, outside a class, n= aForm.aTree.ExpandedCount. For a grand total of 1 'aForm' identifier that C# infers implicitly. From tjreedy at udel.edu Wed Sep 24 23:39:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2008 23:39:21 -0400 Subject: Off topic: Sent from my Foo messages In-Reply-To: <00eaf368$0$20666$c3e8da3@news.astraweb.com> References: <ea42fb160809241402i1c6da16t4dd2456a87d6f177@mail.gmail.com> <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <mailman.1474.1222296372.3487.python-list@python.org> <00eaf368$0$20666$c3e8da3@news.astraweb.com> Message-ID: <gbf159$oft$2@ger.gmane.org> Steven D'Aprano wrote: > I'm seeing more and more posts from various people, on this list and > others, with statements like the following: > > On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote: > >> Sent from my iPhone > > Also "Sent from my Blackberry" and similar. > > Without wishing to be rude to David, who I'm sure is a nice guy and not > at all the pretentious git that such a line makes him appear, are people > adding this comment to the bottom of their posts, or is it something that > their device automatically appends to the post? > > If people are adding it themselves, that's nice, I'm sure you're really > excited about your new toy, but the rest of us don't care a monkey's > toss. And if the device is automatically appending it, I think that's > pretty damn rude and a good reason to avoid buying the obnoxious machines. At least it is just one tag line and the the 20 lines of legal 'If you received this in error' spam some organizations tack on the end ;-). From faltet at gmail.com Mon Sep 15 05:34:22 2008 From: faltet at gmail.com (Francesc) Date: Mon, 15 Sep 2008 02:34:22 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> <pan.2008.09.11.07.40.08@REMOVE.THIS.cybersource.com.au> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <pan.2008.09.12.03.37.51@REMOVE.THIS.cybersource.com.au> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <pan.2008.09.12.06.30.43@REMOVE.THIS.cybersource.com.au> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> Message-ID: <f62644a0-51c4-4eb1-96e4-eab96d431b74@l42g2000hsc.googlegroups.com> On 12 Set, 14:39, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > > A consideration of other storage formats such as HDF5 might > > be appropriate: > > >http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > > There are, of course, HDF5 tools available for Python. > > PyTablescame up within the past few weeks on the list. > > "When the file is created, the metadata in the object tree is updated > in memory while the actual data is saved to disk. When you close the > file the object tree is no longer available. However, when you reopen > this file the object tree will be reconstructed in memory from the > metadata on disk...." > > This is different from what I had in mind, but the extremity depends > on how slow the 'reconstructed in memory' step is. (Fromhttp://www.pytables.org/docs/manual/ch01.html#id2506782). The > counterexample would be needing random access into multiple data > files, which don't all fit in memory at once, but the maturity of the > package might outweigh that. Reconstruction will form a bottleneck > anyway. Hmm, this was a part of a documentation that needed to be updated. Now, the object tree is reconstructed in a lazy way (i.e. on-demand), in order to avoid the bottleneck that you mentioned. I have corrected the docs in: http://www.pytables.org/trac/changeset/3714/trunk Thanks for (indirectly ;-) bringing this to my attention, Francesc From mccredie at gmail.com Wed Sep 3 15:51:32 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 3 Sep 2008 12:51:32 -0700 (PDT) Subject: creating a similar object from an derived class References: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> Message-ID: <99551c67-262c-4b9c-b705-8292e627c48c@z6g2000pre.googlegroups.com> On Sep 3, 12:09?pm, Scott <smba... at gmail.com> wrote: > Let's say I have an object: > > class foo(): > ? ?def create_another() > ? ? ? ?return foo() > > ? ?def blah(): > ? ? ? ?x = self.create_another() > ? ? ? ?... do something with X > > Now I create a inherited class of this object: > > class bar(foo): > ? ? ... > > If I call bar.create_another(), it will return a foo() instead of a > bar(). This isn't what I want. I would like bar.create_another() to > create an instance for bar(). Obviously I can do this by overriding > create_another, i.e. > > class bar(foo): > ? ? def create_another() > ? ? ? ? return bar() > > However, is there a way for me to modify foo() so that it > automatically creates objects of the derived class, so that I don't > have to continue to redefine create_another() ? > > For example, I tried the following: > > def create_another() > ? ? return self.type()() > > but it did not work. > > Thanks, > Scott This works: >>> class C(object): ... @classmethod ... def create_another(cls): ... return cls() ... >>> class D(C): ... pass ... >>> d = D() >>> e = d.create_another() >>> isinstance(e, D) True Matt From rocksportrocker at googlemail.com Wed Sep 3 07:31:52 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Wed, 3 Sep 2008 04:31:52 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: <2aa4ef17-50d3-4aeb-9e7e-0d2d9b9237d4@w7g2000hsa.googlegroups.com> On 2 Sep., 18:55, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > I find myself writing command line tools in Python where I wish to > include "verbose" output to stdout. > > I start with a helper function: > > def print_(obj, level=0): > ? ? if _verbosity >= level: > ? ? ? ? print obj > > And then I end up with functions or methods looking like this: > > def parrot(x) > ? ? print_("precondition", level=2) > ? ? do_something() > ? ? print_("status is good...", level=1) > ? ? print_("parrot is squawking strongly now", level=2) > ? ? do_something_else() > ? ? print_("squawk squawk squawk", level=3) > ? ? do_more() > ? ? print_("postcondition", level=1) > ? ? return something > > That often means that my functions end up with more message printing code > than actual code. The whole thing seems messy and hard to manage for all > but the smallest scripts. > > Worst of all, sometimes the messages I wish to print may be expensive to > compute, and I don't want to waste time computing them if they aren't > going to be printed because the verbosity is too low. But nor do I wish > to fill my code with this: > > if _verbosity >= 3: > ? ? x = calculate_complicated_thing() > ? ? print_(x, level=3) > > Is there a better way of doing this than the way I am going about it? > > -- > Steven You can save some code if you use function decorators for logging input and output values of functions. So write lots of functions containing one statement and your problem is solved ;-) Greetings, Uwe From paddy3118 at googlemail.com Mon Sep 22 23:44:14 2008 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 22 Sep 2008 20:44:14 -0700 (PDT) Subject: Python Fractions issue. Message-ID: <a73b138a-79a7-4c81-b5c7-9d3e809baff2@m3g2000hsc.googlegroups.com> (From: http://paddy3118.blogspot.com/2008/09/python-fractions-issue.html) There seems to be a problem/difference in calculating with the new fractions module when comparing Python 26rc2 and 30rc1 I was reading the paper "Interval Arithmetic: Python Implementation and Applications" and thought to try the first example function f(x,y), which needs more precision than Python floating point provides (on my Windows PC), to calculate a sensible answer. Ahah, I thought, lets try this with Fractions - so I first installed Python 30rc1, typed in the Function - saw the rubbish result, then used Fractions and got the 'right' result. I then wondered if fractions had been back-ported to Python 2.6rc2, found that it had, but got different results. As you can see from the table, Python 2.6rc2 has a problem calculating t3 = F(11,2) * y**8 + x/(2*y), where F is Fraction. I wonder where the problem lies? (For the Table, please see the blog entry). - Paddy. From deets at nospam.web.de Mon Sep 1 02:40:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 08:40:42 +0200 Subject: Processes in Linux from Python In-Reply-To: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> References: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> Message-ID: <6i1h3cFog1v1U1@mid.uni-berlin.de> Johny schrieb: > To get a number of the http processes running on my Linux( Debia box) > I use > ps -ef | grep "[h]ttpd" | wc -l > > But If I want to use to get a number of the http processes from my > Python program I must use a popen command e.g. > popen2.popen3('ps -ef | grep "[h]ttpd" | wc -l') > that is I must call an external command from Python. The shell does the exact same thing. And by the way: i think you miss a grep -v grep after the first grep - otherwise you count the grep itself. > But it creates a zombie. Try using the subprocess module. It should not require you to call wait yourself. > So my question is: > Is it possible to get a number of the http processes running on Linux > directly from Python ? Not really, or at least not with less effort & without duplicating system tools functionality. Diez From peter.waller at gmail.com Sat Sep 13 07:35:29 2008 From: peter.waller at gmail.com (Peter Waller) Date: Sat, 13 Sep 2008 04:35:29 -0700 (PDT) Subject: Injecting new names into the above frame References: <f17f0627-d29b-43b4-ae76-37946f3b1273@m3g2000hsc.googlegroups.com> <57uyk.101$fD.22@flpi145.ffdc.sbc.com> Message-ID: <bdbafd90-c2e8-4dc3-9d97-ebf1e4709aec@c65g2000hsa.googlegroups.com> On Sep 12, 2:30?pm, Carsten Haese <carsten.ha... at gmail.com> wrote: > > The answer to why this doesn't work lies in the disassembly of that > function: This makes me want to ask: is it difficult to modify a function's code? Even if it weren't possible whilst the function was executing (because then I would be returning to a function I just created, I guess?) Could I make another function which converted this LOAD_GLOBAL to LOAD_FAST? I agree that in general a function should have no side effects and I would like to know exactly what it is going to do, and that what I'm doing is unpythonic. My curiosity extends because I would like to get to know a bit more about python's internals. My gut tells me there has to be a way to achieve what I'm after - even if it the result is extremely ugly. Maybe it might involve applying a decorator to functions who use this functionality, who change the code so that these calls work? Cheers for your reply, - Pete From d3vvnull at gmail.com Fri Sep 26 18:06:25 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 17:06:25 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> Message-ID: <170543c70809261506x4e326c9fn3909f35b70e30e1f@mail.gmail.com> oops. i meant. '.... in (%s)' % ','.join([str_edit_for_exploit(x) for x in aList]) On Fri, Sep 26, 2008 at 5:05 PM, Michael Mabin <d3vvnull at gmail.com> wrote: > so you wouldn't object then to something like '.... in (%)' % > ','.join([str_edit_for_exploit(x) for x in aList]) > > if str_edit_for_exploit applied security edits? > > On Fri, Sep 26, 2008 at 2:28 PM, Benjamin Kaplan <benjamin.kaplan at case.edu > > wrote: > >> >> >> On Fri, Sep 26, 2008 at 3:04 PM, Michael Mabin <d3vvnull at gmail.com>wrote: >> >>> Doesn't it depend on where and why you intend to execute the code? >>> Obviously some SQL is more at risk for exploit when the input is from the >>> screen on a web page than if you were running parameterized code in a >>> controlled batch environment. Or if you were writing code generators (which >>> is what I happen to do) which won't be run by the general public. >>> >>> Incidentally, couldn't input field edits prevent such exploits prior to >>> interpolation? >>> >> >> There are ways to avoid SQL injection attacks, such as escaping all quotes >> in the text. We were simply pointing out that you have to be very careful >> when you add arbitrary strings into SQL statements. If you control >> everything going into the statement, you shouldn't have to worry about this. >> >> >> > > > -- > | _ | * | _ | > | _ | _ | * | > | * | * | * | > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/73446c5a/attachment-0001.html> From giltay at gmail.com Thu Sep 18 15:44:43 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Thu, 18 Sep 2008 12:44:43 -0700 (PDT) Subject: Blanket font setting? References: <48d287e5$1@news.alcatel.com> Message-ID: <685d29f9-0525-45b8-ab52-f1a917c7d1ca@x16g2000prn.googlegroups.com> On Sep 18, 12:55?pm, RGK <R... at no.thanks.spammers> wrote: > Is there any sort of blanket font setting, perhaps like: > > ? ?wx.SystemSettings_SetFont(font) ? #this doesn't exist > > that could set everything with one fell swoop? > > Thanks for your attention... > > Ross. I do this by setting the font in each frame (or dialog); the font propogates to its descendants. http://lists.wxwidgets.org/pipermail/wxpython-users/2008-September/080099.html Geoff G-T From durand1 at gmail.com Sat Sep 6 11:58:57 2008 From: durand1 at gmail.com (Durand) Date: Sat, 6 Sep 2008 08:58:57 -0700 (PDT) Subject: [matplotlib] Overlapping axis text Message-ID: <eaba743e-ffa4-4140-9c0e-3d917281cdad@b1g2000hsg.googlegroups.com> I got a really annoying problem with datetime graphs. The problem is that with a long range time graph, the text on the x axis keeps overlapping like here: http://durand.zephyrhosting.net/tremcs/graph_all.png Would there be any way to fix this? I was thinking of rotating the text so that there was enough space for each one but the best solution would be to only display text with the right scale. IE, with a 7 day graph, each day would have text, with a year long graph, each month would be displayed, etc... This is the code I use at the moment but its pretty messy: import dateutil,pylab from matplotlib.dates import MonthLocator, WeekdayLocator fig = pylab.figure() ax = fig.add_subplot(111) days = MonthLocator() # every monday months = MonthLocator() # every month ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(days) pylab.plot_date(pylab.date2num(dates), allkills, '.-', color='blue') pylab.plot_date(pylab.date2num(dates), alldeaths, '.-', color='red') pylab.plot_date(pylab.date2num(dates), kills, '.-', color='darkgreen') pylab.plot_date(pylab.date2num(dates), deaths, '.-', color='orange') if legend == 1: pylab.legend(("Total Kills","Total Deaths", "Single Session Kills", "Single Session Deaths"), 'lower left') pylab.xlabel('Date') pylab.ylabel('Stats') ax2 = pylab.twinx() pylab.plot_date(pylab.date2num(dates), allratio, '.-', color='purple') pylab.plot_date(pylab.date2num(dates), ratio, '.-', color='yellow') pylab.ylabel('Ratio') ax2.yaxis.tick_right() pylab.show() Please excuse the extra tabbing, it's part of an if statement. From fredrik at pythonware.com Sun Sep 7 18:02:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 00:02:35 +0200 Subject: Updating python dictionary In-Reply-To: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <ga1j1t$65e$2@ger.gmane.org> andyhume at gmail.com wrote: > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? since none of your dictionaries contain the keys you want in the final dictionary, creating a brand new dict sounds pretty clever to me. </F> From gagsl-py2 at yahoo.com.ar Fri Sep 5 01:05:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 02:05:16 -0300 Subject: Help needed to freeze a script. References: <7f364174-75c6-4120-b00e-6f41643ccbf5@z72g2000hsb.googlegroups.com> <614c7366-ba7e-4296-a4f0-a32accaa427a@b38g2000prf.googlegroups.com> <0957cba5-9aa8-41d6-bf95-9d6a8db18c89@l33g2000pri.googlegroups.com> Message-ID: <op.ugzse2srx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 04 Sep 2008 14:11:45 -0300, LB <berthe.loic at gmail.com> escribi?: > Do you know if py2exe executable embedding a lot of C extensions - > like numpy and scipy - can ben executed on another computer, with a > different architecture (64bits vs 32 bits) and a different OS ? Forget it, Jake. -- Gabriel Genellina From news1234 at free.fr Wed Sep 10 17:09:54 2008 From: news1234 at free.fr (nntpman68) Date: Wed, 10 Sep 2008 23:09:54 +0200 Subject: Reading binary data In-Reply-To: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> Message-ID: <48c837a0$0$9135$426a34cc@news.free.fr> What I would do first is to print the result byte by byte each as hexadecimal number. If you can I would additionally populate the C-structure with numbers, which are easier to follow. Example: signature = "ABC" // same as 0x41 0x42 0x43 version = 0x61626364 attr_count = 0x65667678 . . . assuming version == 2 (0x00000002) the first byte should be 'G' == 0x47 ) if the 4th byte value 2, than you unaligned uint32s and you are little endian if the 5th byte is 2, then you have 4 byte aligned uint32s and little endian if the 7th byte is 2 then you should have unaligned uint32s and big endian if the 8th byte is 2 then you should have 4 byte aligned uints32 and big endian bye N Aaron Scott wrote: > I've been trying to tackle this all morning, and so far I've been > completely unsuccessful. I have a binary file that I have the > structure to, and I'd like to read it into Python. It's not a > particularly complicated file. For instance: > > signature char[3] "GDE" > version uint32 2 > attr_count uint32 > { > attr_id uint32 > attr_val_len uint32 > attr_val char[attr_val_len] > } ... repeated attr_count times ... > > However, I can't find a way to bring it into Python. This is my code > -- which I know is definitely wrong, but I had to start somewhere: > > import struct > file = open("test.gde", "rb") > output = file.read(3) > print output > version = struct.unpack("I", file.read(4))[0] > print version > attr_count = struct.unpack("I", file.read(4))[0] > while attr_count: > print "---" > file.seek(4, 1) > counter = int(struct.unpack("I", file.read(4))[0]) > print file.read(counter) > attr_count -= 1 > file.close() > > Of course, this doesn't work at all. It produces: > > GDE > 2 > --- > ? > --- > ? ? > > I'm completely at a loss. If anyone could show me the correct way to > do this (or at least point me in the right direction), I'd be > extremely grateful. From mensanator at aol.com Tue Sep 2 13:52:58 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 2 Sep 2008 10:52:58 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: <d5de89ff-ad8f-4a61-b6af-2c43f449acd0@m45g2000hsb.googlegroups.com> On Sep 2, 11:55 am, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > I find myself writing command line tools in Python where I wish to > include "verbose" output to stdout. > > I start with a helper function: > > def print_(obj, level=0): > if _verbosity >= level: > print obj > > And then I end up with functions or methods looking like this: > > def parrot(x) > print_("precondition", level=2) > do_something() > print_("status is good...", level=1) > print_("parrot is squawking strongly now", level=2) > do_something_else() > print_("squawk squawk squawk", level=3) > do_more() > print_("postcondition", level=1) > return something > > That often means that my functions end up with more message printing code > than actual code. The whole thing seems messy and hard to manage for all > but the smallest scripts. > > Worst of all, sometimes the messages I wish to print may be expensive to > compute, and I don't want to waste time computing them if they aren't > going to be printed because the verbosity is too low. But nor do I wish > to fill my code with this: > > if _verbosity >= 3: > x = calculate_complicated_thing() > print_(x, level=3) > > Is there a better way of doing this than the way I am going about it? I do something like this, although I don't know if it would be an improvement. def collatz(a,p): """ 3x+1 sequencer, no loop detection collatz(a,p) a: starting value p: print options (binary) bit 0 print even numbers (turns off power division) bit 1 print odd numbers bit 2 print debug (if any) returns: CollatzSequenceParameters [R1count, R2count] """ ONE = gmpy.mpz(1) TWO = gmpy.mpz(2) TWE = gmpy.mpz(3) a = gmpy.mpz(a) t = 0 u = 0 done = 0 if (p & 1)==1: print_evens = True else: print_evens = False if (p & 2)==2: print_odds = True else: print_odds = False if (p & 4)==4: print_debug = True else: print_debug = False while done==0: f = gmpy.scan1(a,0) # locate LS 1-bit if f>0: # it's even if print_evens: print a, a = a >> 1 # no power division u += 1 else: a = a >> f # power division u += f else: if print_odds: print a, if a==1: done = 1 seq_end = t + u else: a = a*TWE + ONE t += 1 return [u,t] > > -- > Steven From steve at REMOVE-THIS-cybersource.com.au Sun Sep 21 11:13:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 15:13:18 GMT Subject: Why are "broken iterators" broken? Message-ID: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> According to the Python docs, once an iterator raises StopIteration, it should continue to raise StopIteration forever. Iterators that fail to behave in this fashion are deemed to be "broken": http://docs.python.org/lib/typeiter.html I don't understand the reasoning behind this. As I understand it, an iterator is something like a stream. There's no constraint that once a stream is empty it must remain empty forever. Can somebody explain why "broken iterators" are broken? -- Steven From martindemello at gmail.com Thu Sep 4 15:51:25 2008 From: martindemello at gmail.com (Martin DeMello) Date: Thu, 4 Sep 2008 12:51:25 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> <mailman.498.1220557317.3487.python-list@python.org> Message-ID: <e97d94df-8da5-4ac4-8029-abf90529c500@z11g2000prl.googlegroups.com> On Sep 4, 12:41?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > "task_done" just decrements a counter (incremented by "put"). ?when the > counter reaches zero, the "join" call is unblocked. Thanks! Is there any standard python idiom to empty a queue into a list? Or do I just call get() repeatedly and catch the exception when it's done? martin From almar.klein at gmail.com Fri Sep 19 16:48:39 2008 From: almar.klein at gmail.com (Almar Klein) Date: Fri, 19 Sep 2008 22:48:39 +0200 Subject: Launching a subprocess without waiting around for the result? In-Reply-To: <87od2l2am7.fsf@benfinney.id.au> References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> <87od2l2am7.fsf@benfinney.id.au> Message-ID: <cc38d75f0809191348q24dfa32cg13f293d2d980cb0e@mail.gmail.com> > > Ah, no, that's a different thing. If the parent exits, the child will > also be killed I believe. Not if it's stuck in some endless loop... If you want to spawn a process and have it live on independent of the > parent, you want to make the child process a "daemon", detatching > itself from the parent's environment. I don't recall how that's done > immediately, but those are the terms to search for. I'm curious how this can be done, does anyone know this? Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080919/718f6615/attachment-0001.html> From clp at rebertia.com Tue Sep 16 04:15:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 16 Sep 2008 01:15:08 -0700 Subject: append on lists In-Reply-To: <ganpdo$1gf$1@online.de> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> Message-ID: <47c890dc0809160115g2f02f889nf9e2f5fe16c67c28@mail.gmail.com> On Tue, Sep 16, 2008 at 1:20 AM, Armin <a at nospam.org> wrote: > John Machin wrote: >> >> On Sep 16, 6:45 am, Armin <a... at nospam.org> wrote: >> >>> Yes, but this is very unconvenient. >>> If d should reference the list a extended with a single list element >>> you need at least two lines >>> >>> a.append(7) >>> d=a >>> >>> and not more intuitive d = a.append(7) >> >> Methods/functions which return a value other than the formal None and >> also mutate their environment are "a snare and a delusion". Don't wish >> for them. > > > > c = [9,10] > [1,2,3,4,7].append(c) -> Is this a valid expression? Literally, no, because you can't call methods on literals. However, the sentiment is valid, though probably not what you want: >>> c = [9,10] >>> a = [1,2,3,4,7] >>> b = a[:] >>> a.append(c) >>> a #note the nested list [1, 2, 3, 4, 7, [9, 10]] >>> b [1, 2, 3, 4, 7] >>> b.extend(c) >>> b [1, 2, 3, 4, 7, 9, 10] Regards, Chris > > The 'value' of that expression is None. > > However ... that's the way of the implementation of the append method. > It's a little bit confusing to me ... > > --Armin > > Thanks to all ! > > >> >> Inconvenient? How often do you want to mutate a list and then set up >> another reference to it? >> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From robert.kern at gmail.com Thu Sep 4 17:37:04 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Sep 2008 16:37:04 -0500 Subject: why is self not passed to id()? In-Reply-To: <g9pk40$q81$1@ger.gmane.org> References: <g9pg72$3vi$1@aioe.org> <200809042244.54418.maric@aristote.info> <g9pjjb$p57$1@ger.gmane.org> <g9pk40$q81$1@ger.gmane.org> Message-ID: <g9pke1$r0k$1@ger.gmane.org> Fredrik Lundh wrote: > Robert Kern wrote: > >> Well, that's not entirely true. They need to be not mutated while they >> are in the dictionary, certainly. At least not in ways that affect >> equality testing. In this case, one would also have to override >> list.__eq__ to also compare by identity, too. Then you could mutate >> the lists to your heart's content and the dictionary wouldn't care. > > at which point you'd start wondering if it wouldn't be more efficient to > wrap the list in a light-weight class, instead of using subclassing. Fair point. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From m_palmer45 at yahoo.ca Wed Sep 24 20:08:20 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 24 Sep 2008 17:08:20 -0700 (PDT) Subject: urllib error on urlopen References: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> Message-ID: <564ecf05-4be1-41b3-ab49-c3f17b57ad3b@w7g2000hsa.googlegroups.com> On Sep 24, 11:46 am, Mike Driscoll <kyoso... at gmail.com> wrote: > Hi, > > I have been using the following code for over a year in one of my > programs: > > f = urllib2.urlopen('https://www.companywebsite.com/somestring') > > It worked great until the middle of the afternoon yesterday. Now I get > the following traceback: > > Traceback (most recent call last): > File "<pyshell#13>", line 1, in <module> > response = urllib2.urlopen(req).read().strip() > File "c:\python25\lib\urllib2.py", line 124, in urlopen > return _opener.open(url, data) > File "c:\python25\lib\urllib2.py", line 381, in open > response = self._open(req, data) > File "c:\python25\lib\urllib2.py", line 399, in _open > '_open', req) > File "c:\python25\lib\urllib2.py", line 360, in _call_chain > result = func(*args) > File "c:\python25\lib\urllib2.py", line 1115, in https_open > return self.do_open(httplib.HTTPSConnection, req) > File "c:\python25\lib\urllib2.py", line 1082, in do_open > raise URLError(err) > URLError: <urlopen error (1, 'error:140770FC:SSL > routines:SSL23_GET_SERVER_HELLO:unknown protocol')> > > I tried my Google Fu on this error, but there's not much out there. I > tried using a proxy in Python, but that returned the same traceback. > If I copy the URL into my browser, it resolves correctly. Does anyone > have any advice on how to troubleshoot this error? > > I am using Python 2.5.2 on Windows XP. > > Thanks, > > Mike Could it just be a misconfiguration at the other end? Can you open other https urls? From tilmaniac at gmail.com Mon Sep 29 02:46:51 2008 From: tilmaniac at gmail.com (Tilman Kispersky) Date: Sun, 28 Sep 2008 23:46:51 -0700 (PDT) Subject: Cannot install pysqlite on Cygwin Message-ID: <b3fe277b-d191-43ad-8de8-83d99dd890f1@w1g2000prk.googlegroups.com> I am trying to install sqlite for use with python on cygwin. I have installed the sqlite packages from cygwin (that is libsqlite3-devel and libsqlite3_0). When attempting to easy_install pysqlite I get: $ easy_install pysqlite Searching for pysqlite Reading http://pypi.python.org/simple/pysqlite/ Reading http://pysqlite.org/ Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ Reading http://pysqlite.sourceforge.net/ Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/ Reading http://initd.org/tracker/pysqlite/wiki/PysqliteDownloads Reading http://oss.itsystementwicklung.de/trac/pysqlite Reading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/ Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/ Reading http://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/ Reading http://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/ Best match: pysqlite 2.5.0 Downloading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlite-2.5.0.tar.gz Processing pysqlite-2.5.0.tar.gz Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/ Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg- dist-tmp-7mr3WS warning: no files found matching 'doc/*.html' warning: no files found matching 'doc/code/*.py' src/statement.c: In function `pysqlite_statement_recompile': src/statement.c:351: warning: `sqlite3_transfer_bindings' is deprecated (declared at /usr/include/sqlite3.h:3985) build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function `pysqlite_enable_load_extension': /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ pysqlite-2.5.0/src/connection.c:922: undefined reference to `_sqlite3_enable_load_extension' collect2: ld returned 1 exit status error: Setup script exited with error: command 'gcc' failed with exit status 1 $ It seems to me this is due to some missing library (undefined reference...) but I have no idea what these missing files might be. I've tried installing everything that made any reference to sqlite form the cygwin interface. Does anyone know how I might get a working install of sqlite for python on cygwin? From gagsl-py2 at yahoo.com.ar Wed Sep 3 03:30:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 04:30:45 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> <20080902221507.GS29228@dragontoe.org> Message-ID: <op.ugv9tjvgx6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 02 Sep 2008 19:15:07 -0300, Derek Martin <code at pizzashack.org> escribi?: >> > The Linux man page unfortunately copies (verbatim) the FreeBSD man >> > page, which gets it wrong. You can not open a process, but you can >> > definitely open a pipe. >> >> (Ok, if it doesn't agree with you, it must be wrong) > > See my last post for accreditation of my comment. A common > argumentation tactic of the closed-minded and the small-minded is to > resort to insinuation to attack the validity of other's comments > without providing any basis for doing so. Nice job. Well, you didn't provide (in that post) any reason for the Linux man page to be wrong, other than you disagreed with its terminology... But I don't want to argument on this - it was just a "side note". >> Classes represent "things", and class names should be nouns. > > Is that a law? > > Classes are instantiated by invoking their class names as a function > call -- the computing equivalent of a verb. Why then, must they be > named as nouns? Can you not, in fact, have classes which describe > (or model) actions? Wouldn't you name them using verbs if you did? Not exactly. I usually use the -dor suffix (Spanish) or -er (English); in both languages their meaning is to make a noun from a verb. A class whose main purpose is to write things becomes a Writer, by example. The stdlib is full of Writers, Openers, Parsers, Wrappers, Handlers, etc. If the main purpose of subprocess.Popen were to open pipes, I'd say some form of "opener" would be OK. But I think its main purpose is to model the child process itself - pipes are just attributes, so a noun like Child, Subprocess, Process or similar would have been more adequate. Of course it's too late to change things now, at least for the near future. Anyway, It's not the first misnamed class, nor the last one -unfortunately-, nor it's sooooo badly named anyway... > That said, this is the most valid point anyone has made... You should > have made it when the module was being designed. :-D (Yes, sure. Unfortunately, by the time 2.4 was released, I was still stuck with Python 2.1 due to Zope incompatibilities... Properties and generators were unreachable things to me... Oh, just remembering those times makes me sick :( ) > My point is, if you don't think Popen is a good name for the class, > that's your opinion, but it is only that: an opinion. Yet some of you > state your case as if it is incontrovertable fact. I've given a good > case as to why it IS a good name (one which I genuinely support), and > disagree as you may, none of the points any of you have made > invalidate or even weaken my argument. Lastly, the maintainers > obviously thought it was a good name when they included it... No, please. I know it's just my opinion, and I can see there is a case for the current name - just I don't like it, and liked to share my feelings with the OP when he said the same. -- Gabriel Genellina From duncan.booth at invalid.invalid Thu Sep 11 04:17:48 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Sep 2008 08:17:48 GMT Subject: universal unicode font for reportlab References: <ga6loq$jpj$1@rumours.uwaterloo.ca> <mailman.785.1221053660.3487.python-list@python.org> <Xns9B159F78E43Dduncanbooth@127.0.0.1> <r7bhc4hd6lh6539kqkmo8klgoua70sjhrn@4ax.com> <Xns9B165B8F730E4duncanbooth@127.0.0.1> Message-ID: <Xns9B165E8739CC6duncanbooth@127.0.0.1> Duncan Booth <duncan.booth at invalid.invalid> wrote: > I may have made some blindingly obvious beginners mistake I made the blindingly stupid beginners mistake of cleaning up the code before posting it and breaking it in the process. The 'if' should of course say: if len(sys.argv) > 1: However my original test was done by toggling commented out lines of code so my conclusion remains the same: the only differences between the output are the creation date, the page stream, and the digest. -- Duncan Booth http://kupuguy.blogspot.com From gogala.mladen at gmail.com Fri Sep 19 04:34:15 2008 From: gogala.mladen at gmail.com (Mladen Gogala) Date: Fri, 19 Sep 2008 10:34:15 +0200 Subject: Python newbie References: <gavjfd$mvd$1@registered.motzarella.org> <mailman.1261.1221809756.3487.python-list@python.org> Message-ID: <gavo67$ops$1@registered.motzarella.org> Steve Holden wrote: > No. Python implicitly dereferences all names when using them to compute > values, and only uses them as references on the left-hand side of an > assignment. > > Please note the above statement is contentious, and will likely bring a > horde of screaming fanatics of various flavors down on my head for > terminological inexactitude. Actually, I am not a "screaming fanatic". I just want to learn. I am not trying to compare Perl or PHP with Python. I don't know enough Python to do that. I see an exponential increase in the use of Python and I want to find out why is that. I don't plan on discarding my knowledge of Perl and PHP and I don't know enough Python to make a reasonable comparison. whether I will use Python on regular basis or not is still to be decided. One thing is certain: it's easier to use what I already know but then, that's not the point. I've heard very good things about Django and TurboGears and I got my hands on the tool called orasachemadoc which is written in Python and I want to check it out. True, I am coming from the "dark side", but I have no preconceptions and am not a "screaming fanatic". Let me introduce myself: http://www.dba-oracle.com/t_dbi_interface1.htm http://www.rampant-books.com/book_2005_2_php_oracle.htm http://www.oracle.com/technology/pub/articles/gogala-symfony.html Those articles are the only ones that are scripting related. There are some other articles about Oracle, of no interest for this group. I am 47 years old and I have learned many programming languages in my time. Learning Python doesn't seem like a huge task. Conquering my own preconceptions stemming from a very long use of other programming languages will not be a big problem, either. Hopefully, this explains who am I and what is my motivation for delving into Python. I share your fears of screaming fanatics, too. -- http://mgogala.freehostia.com From deets at nospam.web.de Wed Sep 3 11:33:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 17:33:50 +0200 Subject: Serial I/O problem with pywin32 ? In-Reply-To: <f5ff935a-3e1b-4f72-bdcf-6d948b25ace0@2g2000hsn.googlegroups.com> References: <f5ff935a-3e1b-4f72-bdcf-6d948b25ace0@2g2000hsn.googlegroups.com> Message-ID: <6i7p2uFp2lqbU1@mid.uni-berlin.de> Xavier schrieb: > Hi, > > I try to access to a Bluetooth GPS data-logger with Python. I use > pySerial. > > Sending and receiving little messages (~100 char) works fine. However, > when I ask the GPS to dump the trails, it returns some Mbytes and here > is the problem : in the stream of bytes, I randomly losts chunks of > ~100bytes. > > I tried USPP and pyBlueZ instead of pySerial : same problem. > > It doesn't like it is a bufferoverun bug from me because : > - the GPS seems to wait when I do not read the stream, > - there is never more than 200 inWainting() characters, > - my code to test it is quite simple : > > seriallink = serial.Serial("COM40") > fileName = "data.dump" > out = open(fileName, 'w') > while 1: > c = seriallink.read() > out.write(" %0.2X" % ord(c)) > print "*", > out.close() > > (with pyBluez : > sock=BluetoothSocket( RFCOMM ) > sock.connect(("00:0A:...", 1))) > > I tried my program on two different PC with two Bluetooth dongle, > (with pySerial, USPP, pyBluez). > The same things are : > - windows > - the GPS (which works fine with the dumper program of the > constructor) > - pyWin32 > > I've found another guy with a similar problem : > http://www.generation-nt.com/reponses/rs232-entraide-142097.html > He says: > - no problem with little messages > - lost of one byte every hour when receiving a lot of data > > Any known problems with pywin32 and serial I/O when downloading a big > stream of data ? From my experience with serial lines I'd say: that's the culprit. They tend to be rather unreliable, as there is no real protocol ensuring data integrity. You might consider downloading chunks of data if that's somehow possible, and re-try failed chunks. Diez From ldo at geek-central.gen.new_zealand Fri Sep 26 03:52:59 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 19:52:59 +1200 Subject: [Tkinter] how to keep a window above all other OS windows? References: <e03ba1b5-c120-45a3-bf27-640f86c35754@2g2000hsn.googlegroups.com> <dqWdneZ7QrR-DUTVnZ2dnUVZ_tXinZ2d@earthlink.com> Message-ID: <gbi4cr$s8a$3@lust.ihug.co.nz> In message <dqWdneZ7QrR-DUTVnZ2dnUVZ_tXinZ2d at earthlink.com>, Dennis Lee Bieber wrote: > {I miss the Amiga -- > where one had the option to push a window to the back /without/ losing > focus... made it useful for reading one window while touch-typing data > into the "hidden" window} This sort of thing should be configurable in many X11-based window managers. From castironpi at gmail.com Thu Sep 25 13:28:17 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 25 Sep 2008 10:28:17 -0700 (PDT) Subject: Er, one -lime- or two. References: <2ac98076-0163-45c4-8269-e6c1a1d70d7f@c65g2000hsa.googlegroups.com> <48db473e$0$24356$426a74cc@news.free.fr> Message-ID: <615a81af-eb4c-42ce-a07f-b5e26e849a03@k37g2000hsf.googlegroups.com> On Sep 25, 3:09?am, Bruno Desthuilliers <bruno. 42.desthuilli... at websiteburo.invalid> wrote: > Aaron "Castironpi" Brady a ?crit : > > > A Python walks into a bar and orders a complex data structure. > > Bartender says, "One line or two?" > > I don't think that one will have much success in parties !-) It doesn't go to any. =P From darcy at druid.net Fri Sep 26 15:21:58 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 26 Sep 2008 15:21:58 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Message-ID: <20080926152158.a4b4f229.darcy@druid.net> On Fri, 26 Sep 2008 14:04:35 -0500 "Michael Mabin" <d3vvnull at gmail.com> wrote: > Doesn't it depend on where and why you intend to execute the code? > Obviously some SQL is more at risk for exploit when the input is from the > screen on a web page than if you were running parameterized code in a > controlled batch environment. Or if you were writing code generators (which > is what I happen to do) which won't be run by the general public. > > Incidentally, couldn't input field edits prevent such exploits prior to > interpolation? I encourage my competitors to program that way. -- D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From deets at nospam.web.de Fri Sep 12 10:09:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Sep 2008 16:09:02 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <mailman.921.1221227464.3487.python-list@python.org> References: <mailman.921.1221227464.3487.python-list@python.org> Message-ID: <6ivbfvFnfucU1@mid.uni-berlin.de> Marco Bizzarri schrieb: > Hi all. > > In many parts of my code I've the following schema of code: > > def isInUseByOutgoingRegistrations(self, archivefolder): > for instance in self.findActiveOutgoingRegistrationInstances(): > if instance.forbidToClose(archivefolder): > return True > return False > > Before devising my own solution for this kind of problem, I wonder if > there is a common solution for the problem. I'm looking for a > python2.3 solution. if any(instance.forbitToClose(archivefolder) for instance in self.findActiveOutgoingRegistrationInstances()) You should also consider using PEP8 style naming. Diez From joncle at googlemail.com Wed Sep 10 13:41:19 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 10:41:19 -0700 (PDT) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> Message-ID: <508e31d9-daab-4346-9441-55cc47f7c1f4@m44g2000hsc.googlegroups.com> On 10 Sep, 18:33, Jon Clements <jon... at googlemail.com> wrote: > On 10 Sep, 18:14, Aaron Scott <aaron.hildebra... at gmail.com> wrote: > > > > > I've been trying to tackle this all morning, and so far I've been > > completely unsuccessful. I have a binary file that I have the > > structure to, and I'd like to read it into Python. It's not a > > particularly complicated file. For instance: > > > signature ? char[3] ? ? "GDE" > > version ? ? uint32 ? ? ?2 > > attr_count ?uint32 > > { > > ? ? attr_id ? ? ? ? uint32 > > ? ? attr_val_len ? ?uint32 > > ? ? attr_val ? ? ? ?char[attr_val_len] > > > } ... repeated attr_count times ... > > > However, I can't find a way to bring it into Python. This is my code > > -- which I know is definitely wrong, but I had to start somewhere: > > > import struct > > file = open("test.gde", "rb") > > output = file.read(3) > > print output > > version = struct.unpack("I", file.read(4))[0] > > print version > > attr_count = struct.unpack("I", file.read(4))[0] > > while attr_count: > > ? ? ? ? print "---" > > ? ? ? ? file.seek(4, 1) > > ? ? ? ? counter = int(struct.unpack("I", file.read(4))[0]) > > ? ? ? ? print file.read(counter) > > ? ? ? ? attr_count -= 1 > > file.close() > > > Of course, this doesn't work at all. It produces: > > > GDE > > 2 > > --- > > ? > > --- > > ??? > > > I'm completely at a loss. If anyone could show me the correct way to > > do this (or at least point me in the right direction), I'd be > > extremely grateful. > > What if we view the data as having an 11 byte header: > signature, version, attr_count = struct.unpack('3cII', > yourfile.read(11)) > > Then for the list of attr's: > for idx in xrange(attr_count): > ? ? attr_id, attr_val_len = struct.unpack('II', yourfile.read(8)) > ? ? attr_val = yourfile.read(attr_val_len) > > hth, or gives you a pointer anyway > Jon. CORRECTION: '3cII' should be '3sII'. From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 03:09:20 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 09:09:20 +0200 Subject: A bit weird dictionary behavior In-Reply-To: <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> Message-ID: <48d8961a$0$11995$426a74cc@news.free.fr> Carl Banks a ?crit : > On Sep 22, 3:43 pm, Bruno Desthuilliers > <bdesth.quelquech... at free.quelquepart.fr> wrote: >> bearophileH... at lycos.com a ?crit : >> >>> Pekka Laukkanen: >>>> but it still doesn't feel exactly right. Would it be worth submitting a bug? >>> It feels wrong because it is. In a tidier language (Pascal, Java, etc) >>> a boolean and an integer must be different types. >> Some would argue (and some did by the time Python grew a 'bool' type) >> that what is wrong is to have a bool type in a language that already >> have a wider definition of the truth value of an expression... > > And some would argue that it was wrong to have such a wide definition > for the truth value of an expression in the first place... Indeed !-) From bjruth at gmail.com Fri Sep 12 15:36:01 2008 From: bjruth at gmail.com (byron) Date: Fri, 12 Sep 2008 12:36:01 -0700 (PDT) Subject: book example confusion Message-ID: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> I am reading o'reilly's learning python (great book), but i came across an example (pg 291, pdf) that I am not quite understanding the reasoning for the author's explanation: if f1() or f2(): The author states that do to the nature of that expression, if f1() returns True, f2() will not be evaluated.. which makes sense. His quote: "Here, if f1 returns a true (or nonempty) value, Python will never run f2." He then states: "To guarantee that both functions will be run, call them before the 'or':" tmp1, tmp2 = f1(), f2() if tmp1 or tmp2: Being that each function is an object, a name assignment to (tmp1,tmp2) doesn't actually evaluate or run the function itself until the name is called.. so why would the latter example "run" both functions as the author suggests? From prologic at shortcircuit.net.au Sun Sep 21 19:19:19 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 09:19:19 +1000 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00e6cd16$0$20303$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <mailman.1344.1222037693.3487.python-list@python.org> <00e6cd16$0$20303$c3e8da3@news.astraweb.com> Message-ID: <e1a84d570809211619v4cb70fc5r66b61f148466cf4e@mail.gmail.com> On Mon, Sep 22, 2008 at 9:05 AM, Steven D'Aprano <steve at remove-this-cybersource.com.au> wrote: > I'm not wedded to the idea, there are alternatives (perhaps the factory > should instantiate the class and return that?) but I assume others have > used this design and have a name for it. The problem is, I don't see why you're using a class to store state in the first place. cheers James -- -- -- "Problems are solved by method" From paul at boddie.org.uk Sun Sep 7 19:47:49 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 7 Sep 2008 16:47:49 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> Message-ID: <038bcbbc-e204-43f8-b656-81495af36b6c@d77g2000hsb.googlegroups.com> On 7 Sep, 23:00, castironpi <castiro... at gmail.com> wrote: > I am concerned by the lack of follow-through on some responses to > recent ideas I have described. Do I merely have a wrong understanding > of group policy? I think some people have taken exception to your contributions previously, which I believe exhibits a certain degree of shortsightedness on their part, considering for example the recent thread which brought up just-in-time compilation techniques where there were pretty valid reasons for keeping the thread going. Certainly, it wasn't as if the level of discussion was stuck at basic contradiction or mudslinging, and even if reading the different papers on the topic might help an inquirer on the matter, there's certainly nothing wrong with seeking guidance over which papers might be the best ones, nor with seeking some kind of context for that work within the realm of Python implementations, especially given the recent glut of news on virtual machine improvements for other dynamic languages. > Is it a good policy (defined with respect to the > future of Python and the welfare of humans at large) if so? Is there > a serious lack of diligence, or should I merely take more initiative, > and ignore charges of 'pestering'? (Warning, moderately deep outside > social issues on table too.) I'm no expert on getting other people to embrace ideas, but here's my advice anyway. If you have an idea and can describe it coherently, please do so; this won't guarantee positive responses, but there may be people out there who feel that you're onto something. If the idea has merit - generally, the most reliable way to know involves you personally experiencing difficulties in a problem area where the idea in question promises to alleviate some of those difficulties - then by developing that idea, typically producing something that others can try out, people will know that you mean business. Alternatively, people might point you to existing work that will address the problems you're having, saving you the bother of having to write a load of code to enact that idea of yours. You can be lucky and have people chasing you down over what you've produced, but I'd argue that most of the time, for any given idea which becomes a project, you'll have a few people interested in what you've done, but the motivation for continuing will be something that will depend on yourself and your own needs. You have to accept that even if you think that people (and Python) might be well served in listening to what you have to say, that message may go unheard. Once upon a time, the BDFL and the most central core developers used to read comp.lang.python and ideas about Python's future were exchanged readily. Today, all lobbying takes place on the python-dev/ 3000/ideas mailing lists, but those lists are more conservative with regard to contributions than comp.lang.python (python-list). Perhaps as a consequence, the divide between those steering the language and those using it has grown: "producers" use the aforementioned lists, "consumers" argue with each other on the newsgroup, and it might be in the release notes that you learn about happenings that previously would have been reported more widely elsewhere. Certainly, influencing the future of Python, at least officially, is a lot more hard work than it used to be. One may decide to worry about this, along with matters like how Python will remain able to compete with other languages and platforms. I regard the future development of Python as a process which may not necessarily serve my interests, but since the community around Python is so much larger and more diverse than those following every last Python 3.0 commit, I see no need to become agitated by the direction of the language developers. Since Python is Free Software one has, after all, a lot of flexibility when deciding who to associate with and who to influence, and it is ultimately only through trying to achieve things with the technology that one's priorities (or the things one should be worrying about) emerge. For me, then, influencing Python 3.x isn't a priority since I have enough to be thinking about and working on, and I wonder if I'll ever do anything with Python 3.x anyway. So, I suppose, the message is this: follow your own interests, make contributions in the ways that make sense to you, seek contact with like-minded developers in groups which might be remote from mainstream Python development (find an appropriate, potentially specialised audience); these things will define any need you may have to influence others. Paul From presence at MUNGEpanix.com Sat Sep 27 19:12:59 2008 From: presence at MUNGEpanix.com (Cydrome Leader) Date: Sat, 27 Sep 2008 23:12:59 +0000 (UTC) Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <f1dtd45fij5nu9uvnico53cab73uj6pdev@4ax.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> Message-ID: <gbmelr$nhh$4@reader1.panix.com> In rec.crafts.metalworking Jim Thompson <To-Email-Use-The-Envelope-Icon at my-web-site.com> wrote: > > On Sat, 27 Sep 2008 18:47:16 -0400, default <default at defaulter.net> > wrote: > >>On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko >><milenko.stojadinovic at googlemail.com> wrote: >> >>>Hello, this is Milenko Stojadinovic from town Banjaluka, >>>Bosnia and Herzegovina, also known as Cvrcko >>>Does anyone know of any bars in town where I can >>>swallow a bucket of cum? It can be either dog, >>>horse or human cum. Also, does anyone know of >>>any sex bars where people will shit in your mouth? >>>I also like eating shit. >> >>Come to the US and park your mouth in front of George Bush - all the >>Bshit you can eat - and it keeps on coming! >> >>I have a buddy in Bosna - he's normal. > > Now you know why I blanket kill-file googlegroups. So you and everybody can talk about them nonstop? From gagsl-py2 at yahoo.com.ar Sat Sep 20 20:19:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Sep 2008 21:19:11 -0300 Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> <mailman.1225.1221753659.3487.python-list@python.org> <d759cd44-c7c0-46fb-82ed-63f511c1e81f@c58g2000hsc.googlegroups.com> Message-ID: <op.uhs1t9xzx6zn5v@a98gizw.noga> En Sat, 20 Sep 2008 02:01:14 -0300, eliben <eliben at gmail.com> escribi?: > Why are people preferring the python.org package over ActiveState's, > which seems to be more complete and includes more modules (like > pywin32) ? They do a hard work collecting, compiling and packaging the Python distribution with some added modules. But anything you get in the AS free version you can get directly from the original authors; downloading pywin32 from sourceforge isn't so difficult... And AFAIR, it took about 2 months the guys at ActiveState to release the 2.5 version after it came from python.org -- Gabriel Genellina From bearophileHUGS at lycos.com Thu Sep 18 22:08:27 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 18 Sep 2008 19:08:27 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <6d9c1b56-1322-4062-94c4-dd1388421abc@z66g2000hsc.googlegroups.com> Message-ID: <50aa7f8d-7d00-4ca0-9c2a-44335ec91728@k7g2000hsd.googlegroups.com> bearophile: > doubles12 : 0.00184026840268 For fun, and to have an almost baseline reference, I have done a little benchmark in D too: import std.stdio: writefln; // Using Tango std lib you don't need all this version (Win32) { import std.c.windows.windows; double clock() { long t; QueryPerformanceCounter(&t); return cast(double)t / queryPerformanceFrequency; } long queryPerformanceFrequency; static this() { QueryPerformanceFrequency(&queryPerformanceFrequency); } } union N { struct { int x, y; } long xy; } auto IN = [ N(4, 9), N(5, 0), N(6, 6), N(7, 2), N(3, 6), N(9, 6), N(0, 1), N(1, 6), N(0, 5), N(1, 2), N(8, 9), N(5, 4), N(1, 6), N(7, 6), N(9, 1), N(7, 6), N(0, 1), N(7, 4), N(7, 4), N(8, 4), N(8, 4), N(3, 5), N(9, 6), N(6, 1), N(3, 4), N(4, 5), N(0, 5), N(6, 3), N(2, 4), N(1, 6), N(9, 5), N(1, 2), N(5, 8), N(8, 5), N(3, 1), N(9, 4), N(9, 4), N(3, 3), N(4, 8), N(9, 7), N(8, 4), N(6, 2), N(1, 5), N(5, 8), N(8, 6), N(0, 8), N(5, 2), N(3, 4), N(0, 5), N(4, 4), N(2, 9), N(7, 7), N(1, 0), N(4, 2), N(5, 7), N(0, 4), N(2, 5), N(0, 8), N(7, 3), N(9, 1), N(0, 4), N(5, 0), N(4, 9), N(0, 6), N(3, 0), N(3, 0), N(3, 9), N(8, 3), N(7, 9), N(8, 5), N(7, 6), N(1, 5), N(0, 6), N(5, 9), N(6, 8), N(0, 0), N(4, 1), N(3, 3), N(5, 4), N(5, 3), N(6, 1), N(5, 4), N(4, 5), N(5, 8), N(4, 1), N(3, 6), N(1, 9), N(0, 5), N(6, 5), N(5, 5), N(6, 0), N(0, 9), N(2, 6), N(0, 7), N(5, 9), N(7, 3), N(7, 9), N(5, 4), N(4, 9), N(2, 9) ]; N[] doubles13() { size_t[N] dup; // used as set N[] SN; foreach (item; IN) { if (item in dup) SN ~= item; else dup[item] = 0; } return SN; } N[] doubles0() { N[] SN; for (int i; i < IN.length; i++) for (int j; j < IN.length; j++) if (i != j) if (IN[i] == IN[j]) SN ~= IN[i]; return SN; } void test_results() { size_t[N] set1, set2; foreach (n; doubles0()) set1[n] = 0; foreach (n; doubles13()) set2[n] = 0; if (set1.keys.sort != set2.keys.sort) throw new Error("ERROR"); } void main() { int n = 150_000; test_results(); int count = n; auto t0 = clock(); while (count--) doubles13(); auto t1 = clock(); writefln("%0.10f", cast(double)(t1 - t0) / n); } doubles13() needs 0.000027-0.000037 seconds (*), about 60-75 times faster than doubles12, this means about 3-4 seconds instead of 15h (on the original computer). Using C++ with GCC (using a <hash_map> for dup and a <vector> for SN) you can probably go 10-40% faster still :-) (*) Probably there's such variability of timings because the current DMD compiler I have used doesn't add "align" instructions in the asm it produces as GCC does. With modern CPUs very sensitive to code alignment this leads to even 20-30% runtime differences in small tight loops. Bye, bearophile From bschools.dims at gmail.com Fri Sep 26 05:06:05 2008 From: bschools.dims at gmail.com (delhi institute of management & services) Date: Fri, 26 Sep 2008 02:06:05 -0700 (PDT) Subject: urgent Message-ID: <f67e55dd-5467-40ba-8634-2a143865e418@g17g2000prg.googlegroups.com> Delhi Institute of Management & Services Dear friends, We are extremely happy to welcome you to the world of Management... We are in the process of preparing some 5 minutes revision Q & A type lessons for management students. They are in no way, a replacement for the classroom lectures, textbooks or any other study guides. If you wish to go through these lessons. Please visit today's BLOGS: http://bmmisall1513.blogspot.com/ http://allsem1manfun1c.blogspot.com/ http://bmmanhum1107.blogspot.com/ http://bmmanhum1117.blogspot.com/ http://bmmisall1504.blogspot.com/ We want you to suggest improvements or corrections if any, by Email to Ms Sheetal varma, (Senior HR Executive). Email: dimsjobs at gmail.com If you are looking for a job or you want to change a job, please send your resume to Ms Sheetal (Senior HR Executive). She will try to help you to find a suitable job. Email: dimsjobs at gmail.com CAREER TRAINING Join University Recognized Courses MBA {BM} MBA {HR}, MBA {MKT}, and MBA {Fin}, MCA, BCA, MMC, BMC, B.com M.com M.Insurance, B.Fashion For Career Development and Job Promotions. CONTACT: Delhi Institute of Management &Services, Study Centre of NMiMS UNIVERSITY, GURU JAMBHESHWAR UNIVERSITY, JAMIA HAMDARD UNIVERSITY, ALL INDIA MANAGEMENT ASSOCIATION, PUNJAB TECHNICAL UNIVERSITY, MUMBAI EDUCATION TRUST . 1108 Akashdeep Building, New Delhi 110001 TEL FAX: 23312187, TEL: 23316475. If you do not want to receive such mail in future. Please send mail Email: bookghar2008 at gmail.com Reference: Mailer 2 From enleverlesX.XmcX at XmclaveauX.com Tue Sep 30 05:36:03 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Tue, 30 Sep 2008 11:36:03 +0200 Subject: python & sms In-Reply-To: <c7a65808-8f2a-458e-9590-514eebd5f64e@u65g2000hsc.googlegroups.com> References: <c7a65808-8f2a-458e-9590-514eebd5f64e@u65g2000hsc.googlegroups.com> Message-ID: <48e1f674$0$965$ba4acef3@news.orange.fr> Hi! You can manage Skype from Python('s scripts), for use the functionalities of Skype to send SMS. @-salutations -- Michel Claveau From dudeja.rajat at gmail.com Mon Sep 29 10:05:19 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 29 Sep 2008 15:05:19 +0100 Subject: os.path.exists() function does not work for http paths Message-ID: <e0b6c39a0809290705k1a1c20ccwfbd63dbf1c34e3ac@mail.gmail.com> Hi, I have used os.path.exists() many a times for any file system paths in local system. But this does not seem to work for an Http path. e.g: To check is the Results folder exists at the following path, I do: if not os.path.exists("http://subversion.myCom.com/Testing/Results"): print 'Path does not exist' This always prints the above print statements whether or not the Results folder exists or not. Is there any such function to check existence of files. / folder at Http paths? -- Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080929/6d34d11f/attachment-0001.html> From ldo at geek-central.gen.new_zealand Sun Sep 28 19:14:34 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 12:14:34 +1300 Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <gbn6nu$r5j$4@lust.ihug.co.nz> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> <6k93opF6k62hU1@mid.uni-berlin.de> <913193c5-1722-45ae-9cec-efa548dd6992@b38g2000prf.googlegroups.com> Message-ID: <gbp34q$uac$2@lust.ihug.co.nz> In message <913193c5-1722-45ae-9cec-efa548dd6992 at b38g2000prf.googlegroups.com>, est wrote: > Well, you succeseded in putting all blame to myself alone. Great. Take it as a hint. > When you guy's are dealing with CJK characters in the future, you'll > find out what I mean. Speaking as somebody who HAS dealt with CJK characters in the past--see above. From fairwinds.dp at gmail.com Sun Sep 28 10:10:25 2008 From: fairwinds.dp at gmail.com (David Pratt) Date: Sun, 28 Sep 2008 11:10:25 -0300 Subject: Selective importing and package dependencies Message-ID: <E8FB5961-CEA8-462D-993D-C9FC32237727@gmail.com> Hi. I am in the midst of preparing a package to convert between various schemas including orms. The issue is I don't want django, slqalchemy, storm, rdflib etc. as hard dependencies of the package. Each module is a schema to schema conversion. As an example, I have imports for sqlalchemy with classes and methods that use them. from sqlalchemy.util import OrderedDict from sqlalchemy import types as rdbtype import sqlalchemy as sa I have my own ideas about how I might do this but looking for recommendations from others how they would handle this so the result would be: 1. no hard dependencies on any of these other packages 2. load the module without failure. 3. import the dependent package if available to perform the conversion Many thanks David From tjreedy at udel.edu Wed Sep 10 19:03:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 19:03:03 -0400 Subject: dict slice in python (translating perl to python) In-Reply-To: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Message-ID: <ga9jn8$kic$1@ger.gmane.org> hofer wrote: > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. Python does not try to be as compact as Perl. Pythoneers generally consider that a feature. Anyway, the second Python version is asymtotically as compact as the Perl code, differing only by a small constant number of bytes while the code size grows. > mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] The initial brackets add nothing. "v1,v2,v3 =" does the same. > > # for long lists lazier typing,but more computational intensive > # as split will probably be performed at runtime and not compilation > time You have spent and will spend more time posting and reading than the equivalent extra computation time this will take with any normal exchange rate and computation usage. > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] This is a standard idiom for such things. If it bothers you, type "'one two two'.split()" into an interactive window and 'in a blink' get ['one', 'two', 'two'], which you can cut and paste into a program. > print "%s\n%s\n%s" %(v1,v2,v3) However, more that about 3 numbered variables in a Python program suggest the possibility of a better design, such as leaving the values in a list vee and accessing them by indexing. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Mon Sep 15 00:46:38 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 14:46:38 +1000 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> <HYednR9_TqqbWVDVnZ2dnUVZ_oDinZ2d@posted.usinternet> <mailman.1023.1221448972.3487.python-list@python.org> <87od2q5a24.fsf@benfinney.id.au> <oe6dnSQUy_B1eVDVnZ2dnUVZ_obinZ2d@posted.usinternet> Message-ID: <87k5de5841.fsf@benfinney.id.au> Grant Edwards <grante at visi.com> writes: > On 2008-09-15, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: > > I think it's more important for Python library APIs to comply with > > the Python coding guidelines (as specified in PEP 8) than to > > comply with standards in other languages. > > I think the practical matter of being able to use existing > documentation and examples How are examples written in another language a "practical matter" for using a Python library? Surely less "practical" than having one's Python code base use a consistent style. -- \ ?Dyslexia means never having to say that you're ysror.? | `\ ?anonymous | _o__) | Ben Finney From mensanator at aol.com Sun Sep 21 14:55:57 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 21 Sep 2008 11:55:57 -0700 (PDT) Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <mailman.1307.1221935709.3487.python-list@python.org> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> <mailman.1319.1221990028.3487.python-list@python.org> Message-ID: <de0e547f-21ef-45e4-acb4-9d6351ee2947@z72g2000hsb.googlegroups.com> On Sep 21, 4:37 am, Fredrik Lundh <fred... at pythonware.com> wrote: > Mensanator wrote: > > I'm not the one who wrote sympy, so I guess I'm not > > the only one who didn't notice it. > > > If it's a well known problem, then sorry I wasted > > your time. > > Given that 2.5 explicitly warns about this specific change: > > >>> as = 1 > <stdin>:1: Warning: 'as' will become a reserved keyword in Python 2.6 Uh...how come _I_ don't see that? In IDLE, I get: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 IDLE 1.2 >>> as = 1 SyntaxError: invalid syntax When inside a script, I get: as = 1 print as >>> ====================== RESTART ====================== >>> 1 > > it's an unknown issue only for people who has 1) never used their code > under 2.5, or 2) never looks at the output produced by their programs. > > The PEP-5 process guarantees that "users will have at least a year to > test their programs and migrate them from use of the deprecated > construct to the alternative one," and Python 2.5 was released *two* > years ago. > > So it sure looks like the SimPy folks ignored the established process. > Why they've done that is probably a more interesting issue than the > change itself. Is there something wrong with my (and Sympy's) version of Python that we don't see these warnings? > > </F> From harald.luessen at gmx.de Thu Sep 18 14:10:01 2008 From: harald.luessen at gmx.de (Harald Luessen) Date: Thu, 18 Sep 2008 20:10:01 +0200 Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <4f55d49g9086nhob3ol67uahbr19o1hjiu@4ax.com> On Thu, 18 Sep 2008 Alexzive wrote: >I am a python newbie and need to run following code for a task in an >external simulation programm called "Abaqus" which makes use of python >to access the mesh (ensamble of nodes with xy coordinates) of a >certain geometrical model. > >[IN is the starting input containing the nodes to be check, there are >some double nodes with the same x and y coordinates which need to be >removed. SN is the output containing such double nodes] > >Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) I did not test the syntax, but here is an idea with sorted lists. It should be O(NlogN). def sk(x): return x.coordinates[0] IN.sort(key=sk) for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) else: break Harald From lixinyi.23 at gmail.com Wed Sep 24 01:29:54 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 22:29:54 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> <fde4ed92-77ed-438e-a163-d5e248a80ee9@d45g2000hsc.googlegroups.com> <31ff7c8a-28f3-4c62-8ac5-6d0f90106c5d@a8g2000prf.googlegroups.com> <e2537230-c4ad-474a-913c-d0829286e699@k13g2000hse.googlegroups.com> <0fd3fd66-a4f5-4322-8823-722de1dfa952@c58g2000hsc.googlegroups.com> Message-ID: <e4213594-87cd-479c-959a-23dd1fb5e263@a3g2000prm.googlegroups.com> On 9?24?, ??1:15, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 23, 11:06 pm, "Aaron \"Castironpi\" Brady" > > > > <castiro... at gmail.com> wrote: > > On Sep 23, 9:30 pm, lixinyi... at gmail.com wrote: > > > > If the PyObject is a PyList, and all list items are strings, > > > say a=['aaa','bbb','ccc'] > > > > How can I have a > > > myArray[0] = "aaa" > > > myArray[1] = "bbb" > > > myArray[2] = "ccc" > > > in C++? > > > > Do I have to > > > use PyModule_GetDict() to get the dict first? > > > what about the next? > > > > > What do you know about the contents of 'argc' and 'argv'? If it's > > > > impossible with Py_Main, can you use one of the other entry points? > > > > > If you've never manipulated PyObject* objects in C, they can be > > > > hairy. Even if you know 'a' is a sequence, its contents are still all > > > > PyObject*s, which you can access via PyList_... and PySequence_ > > > > functions. > > > This one writes '[aaa, bbb, ccc]' to the console in two different > > ways. > > > #include <Python.h> > > > int main() { > > PyObject *list, *listrepr; > > Py_Initialize(); > > > /* first */ > > list= PyList_New( 3 ); > > PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); > > PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); > > PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); > > > listrepr= PyObject_Repr( list ); > > printf( "%s\n", PyString_AsString( listrepr ) ); > > > Py_DECREF( listrepr ); > > Py_DECREF( list ); > > > /* second */ > > list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); > > listrepr= PyObject_Repr( list ); > > printf( "%s\n", PyString_AsString( listrepr ) ); > > > Py_DECREF( listrepr ); > > Py_DECREF( list ); > > > Py_Finalize(); > > return 0; > > > } > > > Did you want to execute some Python code, and examine variables it > > creates? > > Here's a third way: > > PyObject *list, *listrepr, *dict, *result, *name; > /* third */ > dict= PyDict_New( ); > result= PyRun_String( "myarray= [ 'ggg', 'hhh', 'iii' ]", > Py_file_input, dict, NULL ); > name= PyString_FromString( "myarray" ); > list= PyDict_GetItem( dict, name ); > listrepr= PyObject_Repr( list ); > printf( "%s\n", PyString_AsString( listrepr ) ); > > Py_DECREF( dict ); > Py_DECREF( result ); > Py_DECREF( name ); > Py_DECREF( listrepr ); > Py_DECREF( list ); > > PyRun_String runs a namespace, 'dict', which holds the variables. Thanks! it helps. I know how to read from python now. main_module = PyImport_AddModule("__main__"); global_dict = PyModule_GetDict(main_module); pyObject = PyDict_GetItem(global_dict,key); it will require lots of type checking, but it's fine to me. From hancock.robert at gmail.com Sun Sep 21 18:07:16 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Sun, 21 Sep 2008 15:07:16 -0700 (PDT) Subject: Twisted: Get Protected HTTPS Page via Proxy with Authentication Message-ID: <f60bd2dd-b97a-4ba0-b89c-443019208111@m44g2000hsc.googlegroups.com> from twisted.web import client from twisted.internet import reactor import base64 import sys def printPage(data): print data reactor.stop() def printError(failure): print >> sys.stderr, "Error:", failure.getErrorMessage() reactor.stop() if len(sys.argv) == 4: url = sys.argv[1] username = sys.argv[2] password = sys.argv[3] basicAuth = base64.encodestring('%s:%s' % (username, password)) authHeader = "Basic " + basicAuth.strip() client.getPage(url, headers={"Authorization": authHeader}).addCallback(printPage).addErrback(printError) reactor.run() else: print 'Usage: get_web_page.py <URL>' If I run this against a password protected HTTP(S) site from a host that has direct access to the Internet it works fine. I now have to move it behind a proxy that requires authentication. The Twisted documentation did not make it clear (to me) how to add proxy authentication and I cannot find an example on the Internet. I've tried adding an additional Proxy-Authentication header to the call, but that doesn't help Any ideas would be greatly appreciated. Command line args: http://feedparser.org/docs/examples/basic_auth.xml test basic From anishchapagain at gmail.com Wed Sep 3 05:39:11 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Wed, 3 Sep 2008 02:39:11 -0700 (PDT) Subject: installing matplotlib with cygwiin Message-ID: <9d76f8f9-bc32-4946-9474-7f5f2cdc90b2@b1g2000hsg.googlegroups.com> Hi!! I need to run matplotlib for one project with pylab and scipy module, i'm using cygwin so as to link system call operation with few GUI support, but am unable to install numpy and scipy without these matplotlib is also not installed Please help me for proper installation of these module in cygwin for python, i followed scipy.org installation guidelines but having done so, am not able to proper installation. regard's anish From sturlamolden at yahoo.no Sun Sep 7 00:36:26 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 6 Sep 2008 21:36:26 -0700 (PDT) Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> <96df416b-cc13-4631-8865-d6b6373772a5@z72g2000hsb.googlegroups.com> Message-ID: <35ecda4c-1346-46ab-88c7-076f000115ba@x35g2000hsb.googlegroups.com> On 7 Sep, 06:24, sturlamolden <sturlamol... at yahoo.no> wrote: > - Psyco, a Python JIT compiler, will often speed up algorithmic code. > Using psyco require to change to your code. Typo. It should say "Using psyco does not require you to change your code." From lists at cheimes.de Sun Sep 14 11:07:06 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 14 Sep 2008 17:07:06 +0200 Subject: how to exclude specific things when pickling? In-Reply-To: <nw9zk.32211$bx1.21567@bignews1.bellsouth.net> References: <nw9zk.32211$bx1.21567@bignews1.bellsouth.net> Message-ID: <gaj9ap$j5m$1@ger.gmane.org> inhahe wrote: > If I gather correctly pickling an object will pickle its entire hierarchy, > but what if there are certain types of objects anywhere within the hierarchy > that I don't want included in the serialization? What do I do to exclude > them? Thanks. Pickle uses the methods __getstate__, __setstate__ and __reduce__ / __reduce_ex__ to access certain aspects of an object like e.g. the state. You can find more information in the pickle docs. Christian From jpeyret at gmail.com Tue Sep 23 15:23:26 2008 From: jpeyret at gmail.com (J Peyret) Date: Tue, 23 Sep 2008 12:23:26 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> On Sep 23, 8:31?am, bearophileH... at lycos.com wrote: Guys, this looks like a great data structure/algo for something I am working on. But... where do I find some definitions of the original BK-tree idea? I looked through Amazon and only a few books mention something like BK-Tree and these are mostly conference minutes books, at ungodly prices. I also did a quick Google on it and there isn't that much about the subject. http://blog.notdot.net/archives/30-Damn-Cool-Algorithms,-Part-1-BK-Trees.html is the one I mostly saw referred. So... 2 questions: 1. More bk-tree references? I can follow the code, but some understanding of the background would be nice. 2. What, if any, is a good book to understand the basic of fuzzy/ string matching? Proximity/affinity problems? Or, more generally, a good book on advanced algorithms? No, I don't wanna read Knuth's just yet, something more modern/easy to follow maybe? Something like 'Programming Collective Intelligence', ISBN 0596529325, would be very nice, though it is perhaps a bit too specific in its applications. Books using Java or C are fine. Lisp, hmmm, well... I have trouble reading its notation, sorry. Cheers JLuc From samslists at gmail.com Thu Sep 18 22:29:30 2008 From: samslists at gmail.com (Sam) Date: Thu, 18 Sep 2008 19:29:30 -0700 (PDT) Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <mailman.766.1221033019.3487.python-list@python.org> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <mailman.1247.1221772248.3487.python-list@python.org> Message-ID: <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> On Sep 18, 2:10?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Tue, 16 Sep 2008 21:58:31 -0300, Sam <samsli... at gmail.com> escribi?: > The code is correct - try with another server. I tested it with a ? > LightHTTPd server and worked fine. Gabriel... I found a bunch of servers to test it on. It fails on every server I could find (sans one). Here's the ones it fails on: slashdot.org hotmail.com godaddy.com linux.com lighttpd.net I did manage to find one webserver it succeeded on---that is kenrockwel.com --- a domain squatter with a typoed domain of one of my favorite photographer's websites (the actual website should be kenrockwell.com) This squatter's site is indeed running lighttpd---but it appears to be an earlier version, because the official lighttpd site fails on this test. We have all the major web servers failing the test: * Apache 1.3 * Apache 2.2 * Microsoft-IIS/6.0 * lighttpd/1.5.0 So I think it's the python side that is wrong, regardless of what the standard is. What should I do next? I've rewritten the code to make it easier to test. Just run it as is and it will try all my test cases; or pass in a site on the command line, and it will try just that. Thanks! #!/usr/bin/env python """Put the site you want to test as a command line parameter. Otherwise tests the list of defaults.""" import urllib2 import zlib import sys opener = urllib2.build_opener() opener.addheaders = [('Accept-encoding', 'deflate')] try: sites = [sys.argv[1]] except IndexError: sites = ['http://slashdot.org', 'http://www.hotmail.com', 'http://www.godaddy.com', 'http://www.linux.com', 'http://www.lighttpd.net', 'http://www.kenrockwel.com'] for site in sites: print "Trying: ", site stream = opener.open(site) data = stream.read() encoded = stream.headers.get('Content-Encoding') server = stream.headers.get('Server') print " %s - %s (%s)" % (site, server, encoded) if encoded == 'deflate': before = len(data) try: data = zlib.decompress(data) after = len(data) print " Able to decompress...went from %i to %i." % (before, after) except zlib.error: print " Errored out on this site." else: print " Data is not deflated." print From fredrik at pythonware.com Thu Sep 11 09:00:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 15:00:40 +0200 Subject: function return In-Reply-To: <aa405c1f0809110544l4b2a3e6aw724d1296761ec427@mail.gmail.com> References: <aa405c1f0809110544l4b2a3e6aw724d1296761ec427@mail.gmail.com> Message-ID: <gab4pp$avn$1@ger.gmane.org> Beema Shafreen wrote: > I have a script using functions , I have a problem in returning the > result. My script returns only one line , i donot know where the looping > is giving problem, Can any one suggest, why this is happening and let me > know how to return all the lines > > def get_ptm(): > fh = open('file.txt', 'r') > data_lis = [] > for line in fh.readlines(): > data = line.strip().split('\t') > id = data[0].strip() > gene_symbol = data[1].strip() > ptms = data[8].strip() > result = "%s\t%s\t%s" %(id,gene_symbol,ptms) > return result note that you put the "return" statement inside the loop, so returning only one line is the expected behaviour. result = "%s\t%s\t%s" %(id,gene_symbol,ptms) data_lis.append(result) and then return the list when done: > fh.close() return data_lis ::: if you change the original return to "yield", the function will turn into a "generator" that yields one result at a time. result = "%s\t%s\t%s" %(id,gene_symbol,ptms) yield result for more on generators, and how they are used, see the documentation. </F> From robert.rawlins at thinkbluemedia.co.uk Thu Sep 18 07:21:29 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 18 Sep 2008 12:21:29 +0100 Subject: XML Processing Message-ID: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> Guys, I'm running python 2.5 and currently using ElementTree to perform my XML parsing and creation. ElementTree really is a great package for doing this, however, I've been tasked by our deployment guys to try and move away from external libraries where possible as it makes their job easier. Simple question I suppose to start with, does Python have any inbuilt XML processing modules? If the answer is no then I'll stick with eTree, if python does have one, then I'll look at some migration steps. Many thanks All, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/304a0f11/attachment-0001.html> From silazima at gmail.com Tue Sep 9 06:46:44 2008 From: silazima at gmail.com (Mchizi_Crazy) Date: Tue, 9 Sep 2008 03:46:44 -0700 (PDT) Subject: Python Installation and Running on Windows Vista Message-ID: <4f66ca7b-b495-4b12-bb4c-29b096eb53c9@j22g2000hsf.googlegroups.com> Please help with issue... I heard of compatimbiltity issues and would like clarification. From joe.g at optusnet.com.au Fri Sep 19 07:12:01 2008 From: joe.g at optusnet.com.au (Joe G (Home)) Date: Fri, 19 Sep 2008 21:12:01 +1000 Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> <mailman.1225.1221753659.3487.python-list@python.org> Message-ID: <48d38904$0$31803$afc38c87@news.optusnet.com.au> Yep up and running now. Many thanks Joe From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 04:50:04 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 10:50:04 +0200 Subject: is decorator the right thing to use? In-Reply-To: <vPDCk.1808$T65.994@edtnps82> References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> Message-ID: <48db50aa$0$3750$426a74cc@news.free.fr> Dmitry S. Makovey a ?crit : > Aaron "Castironpi" Brady wrote: > >> It might help to tell us the order of events that you want in your >> program. You're not using 'mymethod' or 'mymethod2', and you probably >> want 'return fnew' for the future. Something dynamic with __getattr__ >> might work. Any method call to A, that is an A instance, tries to >> look up a method of the same name in the B instance it was initialized >> with. > > well 'mymethod' and 'mymethod2' were there just to show that A doesn't > function as a pure proxy - it has methods of it's own. See my respnse to > Steve - I proxy messages to more than one aggregated object. going over > them on __getattr__ to look up methods just doesn't seem to be really > efficient to me (I might be wrong though). Decorators seemed to present > good opportunity to simplify the code (well except for the decorator > function itself :) ), make code bit more "fool-proofed" (and give me the > opportunity to test decorators in real life, he-he). > > So decorators inside of B just identify that those methods will be proxied > by A. On one hand from logical standpoint it's kind of weird to tell class > that it is going to be proxied by another class, Indeed - usually, proxied objects shouldn't have to be aware of the fact. That doesn't mean your variation on the proxy pattern is necessarily bad design (hard to tell without lot of context anyway...), but still there's some alarm bell ringing here IMHO - IOW : possibly the right thing to do, but needs to be double-checked. > but declaration would be > real close to original function definition which helps to identify where is > it used. > > Note that my decorator doesn't change original function - it's a subversion > of decorator to a certain degree as I'm just hooking into python machinery > to add methods to A upon their declaration in B (or so I think). I wouldn't call this a "subversion" of decorators - it's even a pretty common idiom to use decorators to flag some functions/methods for special use. Now I'm not sure I really like your implementation. Here's a possible rewrite using a custom descriptor: class Proxymaker(object): def __init__(self, attrname): self.attrname = attrname def __get__(self, instance, cls): def _proxied(fn): fn_name = fn.__name__ def delegate(inst, *args, **kw): target = getattr(inst, self.attrname) #return fn(target, *args,**kw) method = getattr(target, fn_name) return method(*args, **kw) delegate.__name__ = "%s_%s_delegate" % \ (self.attrname, fn_name) setattr(cls, fn_name, delegate) return fn return _proxied class A(object): def __init__(self,b): self.val='aval' self.b=b b.val='aval' proxy2b = Proxymaker('b') def mymethod(self,a): print "A::mymethod, ",a def mymethod2(self,a): print "A::another method, ",a class B(object): def __init__(self): self.val='bval' @A.proxy2b def bmethod(self,a): print "B::bmethod" print a, self.val @A.proxy2b def bmethod2(self,a): print "B::bmethod2" print a, self.val My point is that: 1/ you shouldn't have to rewrite a decorator function - with basically the same code - for each possible proxy class / attribute name pair combo 2/ making the decorator an attribute of the proxy class makes dependencies clearer (well, IMHO at least). I'm still a bit uneasy wrt/ high coupling between A and B, and if I was to end up with such a design, I'd probably take some times to be sure it's really ok. My cents... From tino at wildenhain.de Mon Sep 22 12:09:40 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Sep 2008 18:09:40 +0200 Subject: A bit weird dictionary behavior In-Reply-To: <bea340ef-adaa-4cbf-ad98-61cffe1fe17f@d77g2000hsb.googlegroups.com> References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <mailman.1362.1222092857.3487.python-list@python.org> <bea340ef-adaa-4cbf-ad98-61cffe1fe17f@d77g2000hsb.googlegroups.com> Message-ID: <48D7C344.2030909@wildenhain.de> Hi, bearophileHUGS at lycos.com wrote: > Tino Wildenhain: > >> Wouldn't >> len([x for x in iterable if x==y]) >> or even shorter: >> iterable.count(y) >> not work and read better anyway? > > The first version creates an actual list just to take its length, > think about how much memory it may use. yes it seems len() does not alternatively iterate or __len__ of the generator objects don't allow for an optimization yet. This could be improved so len(x for x in iterable ...) would work and save memory. > The second version requires the 'iterable' object to have a count() > method, and in general this is false. of course this always depends on the usecase. >> even calculating with boolean values isn't neccessary >> since 'and' and 'foo if bar else blub' are working much better >> so the type coalescing >> bool - int - float can really go away. > > I don't understand. if you have a operator b and type(a) <> type(b) then coercing goes on to convert one partner to the type of the other. So bool currently gets "upgrated" to int (as int is upgraded to float and so on). If this goes away, the type ambiguity is gone. This would result in 1==True -> False HTH Tino PS: are you per chance using a news gateway to post? This seems to screw up threading somehow... > Bye, > bearophile > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080922/f51aff62/attachment-0001.bin> From straton at lampsacos.demon.co.uk Fri Sep 5 08:09:28 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 05 Sep 2008 13:09:28 +0100 Subject: max(), sum(), next() In-Reply-To: <dullrich-991CAD.11173704092008@text.giganews.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> Message-ID: <g9r7hq$ri6$1$8302bc10@news.demon.co.uk> David C. Ullrich wrote: > > I don't see why you feel the two should act the same. > At least in mathematics, the sum of the elements of > the empty set _is_ 0, while the maximum element of the > empty set is undefined. > > And both for good reason: > > (i) If A and B are disjoint sets we certainly want to > have sum(A union B) = sum(A) + sum(B). This requires > sum(empty set) = 0. > > (ii) If A is a subset of B then we should have > max(A) <= max(B). This requires that max(empty set) > be something that's smaller than everything else. > So we give up on that. Do we give up? Really ? From wikipedia: http://en.wikipedia.org/wiki/Empty_set (Uses wikipedia's LaTeX notation -- I hope those interested are OK with that ) <quote> Mathematics [edit] Extended real numbers Since the empty set has no members, when it is considered as a subset of any ordered set, then any member of that set will be an upper bound and lower bound for the empty set. For example, when considered as a subset of the real numbers, with its usual ordering, represented by the real number line, every real number is both an upper and lower bound for the empty set.[3] When considered as a subset of the extended reals formed by adding two "numbers" or "points" to the real numbers, namely negative infinity, denoted -\infty\!\,, which is defined to be less than every other extended real number, and positive infinity, denoted +\infty\!\,, which is defined to be greater than every other extended real number, then: \sup\varnothing=\min(\{-\infty, +\infty \} \cup \mathbb{R})=-\infty, and \inf\varnothing=\max(\{-\infty, +\infty \} \cup \mathbb{R})=+\infty. That is, the least upper bound (sup or supremum) of the empty set is negative infinity, while the greatest lower bound (inf or infimum) is positive infinity. By analogy with the above, in the domain of the extended reals, negative infinity is the identity element for the maximum and supremum operators, while positive infinity is the identity element for minimum and infimum. From arkanes at gmail.com Wed Sep 24 15:26:31 2008 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 24 Sep 2008 14:26:31 -0500 Subject: Linq to Python In-Reply-To: <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <4866bea60809241226k29203854u988f00aafd6f791a@mail.gmail.com> On Wed, Sep 24, 2008 at 2:11 PM, <bearophileHUGS at lycos.com> wrote: > sturlamolden: >>No, because Python already has list comprehensions and we don't need the XML buzzword.< > > LINQ is more than buzzwords. Python misses several of those features. > So maybe for once the Python crowd may recognize such C# feature as > much better than things present in Python. > Said that, I presume Python will go on as usual, and LINQ-like > capabilities will not be integrated in Python. In the meantime where I > live lot of people will keep using C# instead of Python and CLisp, > natural selection at work indeed. > Why do you swing so widely between being an interesting poster with interesting, useful things to say and mindless trolling? There's a lot of reasons to use C# instead of Python or Lisp (or any other language for that matter), but I can't imagine that someone would make that decision based solely on LINQ. I'd go so far as to say that if they do, I question their professional competence. LINQ is an interesting implementation of an old idea. The place where it differs from list comps is that it has appropriate hooks for the specific linq implementation to override the way results are gathered, and such hooks in Python would be an interesting idea. I've taken a shot and figuring out where and how they should be implemented, but I haven't come up with anything I like. Maybe you should try it? LINQs "native" object API (not the syntax sugar available in C#) is not very different from Python ORMs. From overdrigzed at gmail.com Sun Sep 14 13:41:13 2008 From: overdrigzed at gmail.com (overdrigzed at gmail.com) Date: Sun, 14 Sep 2008 10:41:13 -0700 (PDT) Subject: ctypes: Get full contents of character array References: <f478ec50-3a03-42d7-ba4c-376cd67d4625@p25g2000hsf.googlegroups.com> <223fde52-b1aa-4d69-b374-2cf07973f2b5@73g2000hsx.googlegroups.com> Message-ID: <34477897-3a2b-42e9-a753-c2f95ad5c3a2@x41g2000hsb.googlegroups.com> On Sep 13, 6:45?am, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 12, 6:38?pm, overdrig... at gmail.com wrote: > > > > > > > > > Hello! > > > I wanted to get the full contents of a character array stored in a > > struct, i.e. > > _fields_ = [...("array", c_char * 12)...] > > however,ctypesseems to try to return struct.array as a Python string > > rather than a character array, and stops as soon as it encounters a > > null within the character array. > > > I ended up having to define a dummy struct > > class dummystruct(Structure): > > ? ? _fields_ = [] > > > and declare array as: > > ("array", dummystruct) > > > then use string_at(byref(struct.array), 12). > > > Is this really the best way of doing it? Is there no better way to > > work aroundctypes'guess what you want' behaviour? > > > Thanks in advance, > > Rodrigo > > Rodrigo, > > If you have the option to change your declaration to c_byte* 12, you > have more options. ?This example prints the null character you wanted. > > fromctypesimport * > import struct > class S( Structure ): > ? ? _fields_= [ > ? ? ? ? ( 'array', c_byte* 12 ) > ? ? ] > s= S() > > #initialize > struct.pack_into( '7s', s.array, 0, 'abc\x00def' ) > > #prototype and call PyString_FromStringAndSize > prototype= PYFUNCTYPE( py_object, POINTER( c_byte ), c_size_t ) > PyString_FromStringAndSize= prototype( ( "PyString_FromStringAndSize", > pythonapi ) ) > x= PyString_FromStringAndSize( s.array, 12 ) > print repr( x ) > > #prototype and call PyString_FromString for contrast > prototype= PYFUNCTYPE( py_object, POINTER( c_byte ) ) > PyString_FromString= prototype( ( "PyString_FromString", pythonapi ) ) > x= PyString_FromString( s.array ) > print repr( x ) > > /Output: > > 'abc\x00def\x00\x00\x00\x00\x00' > 'abc' Great - and thank you for replying so fast! I found that [chr(x) for x in struct.array] with array as a c_byte * 12 did what I needed. From kurdayon at yahoo.com Sun Sep 28 19:51:07 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Sun, 28 Sep 2008 16:51:07 -0700 (PDT) Subject: Web programming in Python. References: <eb5978f8-e802-48d2-a61f-207c25ac7059@y21g2000hsf.googlegroups.com> Message-ID: <ace09154-e1c1-424e-875e-5193ae210b57@w7g2000hsa.googlegroups.com> 1. On my server (in my directory) I found "cgi-bin" subdirectory. 2. In the "cgi-bin" I have created a file "test.py". 3. In that file I put: #!/usr/bin/python2.4 python print "Hello, World!" (I have checked, I have "/usr/bin/python2.4" directory.) 4. I give the following permissions to the "test.py": -rwx---r-x 5. The "cgi-bin" directory has the following permissions: drwx---r-x 6. In the "cgi-bin" I have created the ".htaccess" file which contains: Options +ExecCGI AddHandler cgi-script .py And it still does not work! If I try to see the page by my browser I see: Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. ... From karl.kobata at syncira.com Thu Sep 18 02:43:36 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Wed, 17 Sep 2008 23:43:36 -0700 Subject: member functions in a class Message-ID: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> I am new to python and am wondering. When I create a class, with 'def' functions and if this class is instantiated say 50 times. Does this mean that all the 'def' functions code within the class is duplicated for each instance? Can someone give me a short and simple answer as to what happens in python? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080917/a3afa8dc/attachment-0001.html> From maric at aristote.info Thu Sep 4 18:16:20 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 00:16:20 +0200 Subject: why is self not passed to id()? In-Reply-To: <g9pkam$rmc$1@ger.gmane.org> References: <g9pg72$3vi$1@aioe.org> <200809042244.54418.maric@aristote.info> <g9pkam$rmc$1@ger.gmane.org> Message-ID: <200809050016.21162.maric@aristote.info> Le Thursday 04 September 2008 23:35:18 Terry Reedy, vous avez ?crit?: > Maric Michaud wrote: > > Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez ?crit : > >> class foo(list): > >> ? ? __hash__ = lambda x: id(x) > > > > Wow ! You are really going on trouble with this, believe me there is a > > real good reason for list not to be hashable. A dictionnary or set > > containing some of your foo is virtually inconsistent, read carefully the > > manual about prerequesites for dict keys, they *need* to be immutable. > > No, the id comparison needs to be immutable -- which it is by default > for object()s, being based on id. ?Mutable instances of classes derived > from object work fine as keys as long as they keep default __eq__ and > __hash__. ?List over-rides the default, so foo needs to reverse that > override: > ? ?def __eq__(self, other): > ? ? ?return id(self) == id(other) > > This means, of course, that foo loses value-based equality comparison. Yes, so what's the point of using lists as keys. "class a : pass" already do this. -- _____________ Maric Michaud From victor.prosolin at gmail.com Mon Sep 29 12:25:43 2008 From: victor.prosolin at gmail.com (Fly Away) Date: Mon, 29 Sep 2008 09:25:43 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <mailman.1520.1222400746.3487.python-list@python.org> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <gbq5p8$iiq$1@lust.ihug.co.nz> Message-ID: <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> On Sep 29, 3:05?am, Lawrence D'Oliveiro <l... at geek- central.gen.new_zealand> wrote: > In message > <02918eb6-c2fb-4908-923f-d878a1956... at x35g2000hsb.googlegroups.com>, > > sturlamolden wrote: > > ... and possibility of interfacing with gnuplot ... > > Gnuplot is non-Free software. Yes, it is. Victor. From steven at REMOVE.THIS.cybersource.com.au Fri Sep 26 04:26:56 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 08:26:56 GMT Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> Message-ID: <pan.2008.09.26.08.26.56@REMOVE.THIS.cybersource.com.au> On Fri, 26 Sep 2008 19:46:10 +1200, Lawrence D'Oliveiro wrote: > In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: >> >>> Just a thought, your minimum sleep time is probably limited by the >>> resolution of the system "HZ" clock. Type >>> >>> less /proc/config.gz >> >> $ less /proc/config.gz >> /proc/config.gz: No such file or directory >> >> >> What OS are you using? > > The one named in the subject line? Are you asking me or telling me? I've tried on five different Linux machines I have access to, and there is no such /proc/config.gz on any of them: two different versions of Centos two versions of Fedora one version of Ubuntu So let me rephrase my question... what *specific* OS are you using? -- Steven From adityashukla1983 at gmail.com Mon Sep 29 00:51:21 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 28 Sep 2008 23:51:21 -0500 Subject: Parser Module Message-ID: <73045cca0809282151w1c091255y8c4a8bb85004e5a3@mail.gmail.com> Hello folks , I wanna create a parser for newick files which generates an ultrametric tree -> every leaf is equidistant from the root eg ->( http://www.icp.be/~opperd/private/upgma.html<http://www.icp.be/%7Eopperd/private/upgma.html>) as the parse tree.Can this type of a parse tree be constructed?And what parser module should i use? Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080928/25c60b75/attachment-0001.html> From bj_666 at gmx.net Wed Sep 3 02:23:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Sep 2008 06:23:23 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> <mailman.390.1220393719.3487.python-list@python.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> <a49e45f50809022120l648f6d94i86ac446b7ae8df69@mail.gmail.com> <mailman.409.1220419440.3487.python-list@python.org> Message-ID: <6i6oqrFmcad7U1@mid.uni-berlin.de> On Wed, 03 Sep 2008 01:23:47 -0400, Derek Martin wrote: > On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote: >> The subprocess module is also supposed to replace os.system and >> os.spawn*, neither of which involve opening pipes. > > Uh... it's a replacement for os.popen(), which -- guess what -- opens > pipes. >From the documentation: subprocess - Subprocesses with accessible I/O streams This module allows you to spawn processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, like: os.system os.spawn* os.popen* popen2.* commands.* If it weren't called `Popen` but `Spawn` instead I guess you would argue that it *must* be `Spawn` because it spawns processes and even it is not using `spawn*()` under the hood it uses the concept of "spawn" with some extras. ;-) Ciao, Marc 'BlackJack' Rintsch From akean at paradise.net.nz Wed Sep 10 17:57:06 2008 From: akean at paradise.net.nz (Anita Kean) Date: 11 Sep 2008 09:57:06 +1200 Subject: List of modules available for import inside Python? References: <e121e2c5-8ebd-4d42-835e-46b52e3c2053@t54g2000hsg.googlegroups.com> <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> <QABwk.25014$N87.11966@nlpi068.nbdc.sbc.com> <mailman.648.1220787169.3487.python-list@python.org> <dcXwk.12440$vn7.2449@flpi147.ffdc.sbc.com> <aec1f937-e1e2-41bd-8a39-74428ff2169d@l64g2000hse.googlegroups.com> Message-ID: <slrngcggt9.3s4.akean@localhost.localdomain> On 2008-09-10, denisbz at t-online.de <denisbz at t-online.de> wrote: > (snip) ... > > So to refine the question: > how can I list all modules that might be importable on my system, > without actually importing them all ? > > (How about a "pydoc2" that's well thought out, doesn't crash ... > let me ask more knowledgable people, what's a good small help system > as model ? > ) I'm constantly finding myself wishing for this feature - something of the "apropos"/"whatis" of the linux shell (and debian's "apt-cache search" and "apt-cache show" which allow you to search and query before you install). (Matlab's "help" and "lookfor" commands cover this too.) Is there a reason this type of information hasn't been made available by default in the help system? I'm constantly using find, grep and Usenet to find out what python tools I can use. Anita From mail at timgolden.me.uk Tue Sep 16 14:56:48 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 19:56:48 +0100 Subject: A unique instance of Python GUI program In-Reply-To: <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> <mailman.1100.1221555458.3487.python-list@python.org> <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> Message-ID: <48D00170.1090600@timgolden.me.uk> akineko wrote: > On Sep 16, 1:58 am, Tim Golden <m... at timgolden.me.uk> wrote: >> I swear this question's been asked twice this month already. > > > Thank you very much for many pointers. > I'm awfully sorry for posting something that is already answered in > the past. I was more amused than annoyed. Don't let my tone put you off. In any case, searching is all too often a question of knowing what the answer is so you can search for it! TJG From rridge at csclub.uwaterloo.ca Thu Sep 25 16:59:43 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 25 Sep 2008 16:59:43 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <gbeae1$uin$1@rumours.uwaterloo.ca> <00eaee25$0$20666$c3e8da3@news.astraweb.com> Message-ID: <gbgu3v$mie$1@rumours.uwaterloo.ca> Ross Ridge wrote: > Plenty of people were quick to say that the exception should be passed > through to the caller. No one said this behaviour should be documented. > There may be little practical difference bewteen calling sys.exit() > after printing an error and progating an exception if no one using the > library knows that it could generate that exception in those > circumstances. Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote: >That's true, I didn't explicitly say that the library should be >documented. Nor did I say that it shouldn't be riddled with bugs. There's >little practical difference between a buggy library and one that raises >unexpected (i.e. undocumented) exceptions either. The problem is that few Python libraries properly document where and when they might generate exceptions. They'll document the fact that they have an "error" exception, but only vaguely say which functions or methods could generate it and why. You need either use trial and error to find out, or look at the source. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From google at mrabarnett.plus.com Fri Sep 26 11:34:19 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Sep 2008 08:34:19 -0700 (PDT) Subject: how to replace and string in a "SELECT ... IN ()" References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> <mailman.1531.1222428188.3487.python-list@python.org> Message-ID: <7b2079a8-dbc1-4d06-8820-8fdc1fc00e38@a1g2000hsb.googlegroups.com> On Sep 26, 12:23?pm, Tino Wildenhain <t... at wildenhain.de> wrote: > Hi, > > > > Bruno Desthuilliers wrote: > > bcurtu a ?crit : > >> Hi, > > >> I have a BIIIIIG problem with the next query: > > >> ? ? ? ? cursor.execute(""" > >> ? ? ? ? ? ? ? ? ? ? SELECT titem.object_id, titem.tag_id > >> ? ? ? ? ? ? ? ? ? ? FROM tagging_taggeditem titem > >> ? ? ? ? ? ? ? ? ? ? WHERE titem.object_id IN (%s) > >> ? ? ? ? ? ? ? ? """,( eid_list)) > > >> eid_list is suppossed to be a list of ids = [1,5,9] > > >> How can I make it work? > > > You have to build your sql statement in three stages: > > > # stage 0: the template > > sql_template = """ > > ? ? SELECT titem.object_id, titem.tag_id > > ? ? FROM tagging_taggeditem titem > > ? ? WHERE titem.object_id IN (%s) > > """ > > > # stage 1: build correct place_holders string for the actual number > > # of items in eid_list > > place_holders = ", " .join("%s" for x in xrange(len(eid_list))) > > Hm. either ", ".join(["%s"]*len(eid_list)) > or ", ".join("%s" for x in eid_list) > > should produce the same, wouldn't it? :-) > [snip] Or: place_holders = ("%s," * len(eid_list))[ : -1] :-) From lists at cheimes.de Fri Sep 12 11:21:57 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Sep 2008 17:21:57 +0200 Subject: setattr in class In-Reply-To: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <gae1ej$uua$1@ger.gmane.org> Bojan Mihelac wrote: > I guess A class not yet exists in line 4. Is it possible to achive > adding dynamic attributes without using exec? Correct, the class doesn't exist until the end of the class body. You can either do it outside the class definition or you can use a metaclass. Christian From gary at byoteki.com Sun Sep 28 16:20:09 2008 From: gary at byoteki.com (Gary M. Josack) Date: Sun, 28 Sep 2008 16:20:09 -0400 Subject: generate random digits with length of 5 In-Reply-To: <48DFE5A7.5040000@byoteki.com> References: <e1923ff8-8150-41b6-9444-19c14b4d2f6f@8g2000hse.googlegroups.com> <c709a934-85bc-46be-a4a2-2feeb5aa85ee@q9g2000hsb.googlegroups.com> <48DFE5A7.5040000@byoteki.com> Message-ID: <48DFE6F9.50405@byoteki.com> Gary M. Josack wrote: > Aaron "Castironpi" Brady wrote: >> On Sep 28, 2:59 pm, sotirac <soti... at gmail.com> wrote: >> >>> Wondering if there is a better way to generate string of numbers with >>> a length of 5 which also can have a 0 in the front of the number. >>> >>> <pre> >>> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 >>> elements >>> code = 'this is a string' + str(random_number[0]) + >>> str(random_number[1]) + str(random_number[2]) + str(random_number[3]) >>> + str(random_number[4]) >>> </pre> >>> >> >> '%05i'%random.randint(0,99999) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > This produces numbers other than 5 digit numbers. making the start > number 10000 should be fine. > -- > http://mail.python.org/mailman/listinfo/python-list nevermind. my brain is tired tonight. this is the best solution. From bdesth.quelquechose at free.quelquepart.fr Mon Sep 29 12:27:22 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2008 18:27:22 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <gbq6nq$j89$2@lust.ihug.co.nz> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <gbeae1$uin$1@rumours.uwaterloo.ca> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <gbgu3v$mie$1@rumours.uwaterloo.ca> <gbq6nq$j89$2@lust.ihug.co.nz> Message-ID: <48e11dd4$0$20720$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message <gbgu3v$mie$1 at rumours.uwaterloo.ca>, Ross Ridge wrote: > >> You need either use trial and error to find out, or look at the source. > > So what's wrong with using the source as documentation? :) Don't know... Ok, having higher-level documentation (the big picture, and quick description of what and how for classes and functions) really helps. But when it comes to nitty-gritty details, source code is the best documentation ever, since it's always accurate and up to date. FWIW, I'm often surprised by people asking questions about some implementation detail of some open-source library or framework that are very easily answered just looking at the source code. Reading the source is 1/ the best way to really know how something is implemented and 2/ usually very instructive. From somenewguy61 at googlemail.com Tue Sep 23 19:38:43 2008 From: somenewguy61 at googlemail.com (somenewguy61 at googlemail.com) Date: Tue, 23 Sep 2008 16:38:43 -0700 (PDT) Subject: detektei info detektei hessen in Gunzenhausen Message-ID: <d5f376bb-f2ad-41b7-a8a1-aeacee124094@c65g2000hsa.googlegroups.com> http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET From castironpi at gmail.com Fri Sep 26 22:22:42 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 19:22:42 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <dZOdnQINKORUEUDVnZ2dnUVZ_rvinZ2d@posted.usinternet> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> Message-ID: <35681490-2d50-4a51-ae88-c1538ed51e15@y21g2000hsf.googlegroups.com> On Sep 26, 9:09?pm, George Sakkis <george.sak... at gmail.com> wrote: > On Sep 26, 9:30?pm, Grant Edwards <gra... at visi.com> wrote: > > > On 2008-09-26, nntpman68 <news1... at free.fr> wrote: > > > > Hm, > > > > I guess you just filter mailing lists and can do nothing about the > > > newsgroup if I'm fetching via the nntp server of my ISP itself, right? > > > I read the group via NNTP, and I find that blocking all > > articles posted from google.groups gets rid of all of the spam. > > ... along with a far from trivial (I guess) percentage of non-spam, > such as this post. > > And-nothing-of-value-was-lost'ly yrs, > George Every method has false positives, George. (including this one.) From martin at see.sig.for.address.invalid Mon Sep 1 17:03:44 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Mon, 1 Sep 2008 21:03:44 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <g8bflo$984$1@localhost.localdomain> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> <s2lta4lorjk49dn3joo3gj3juc8rfqqinf@4ax.com> <rem-2008sep01-004@yahoo.com> Message-ID: <g9hlbf$liu$1@localhost.localdomain> On Mon, 01 Sep 2008 12:04:05 -0700, Robert Maas, http://tinyurl.com/uh3t wrote: >> From: George Neuner <gneun... at comcast.net> A friend of mine had an >> early 8080 micros that was programmed through the front panel using >> knife switches > > When you say "knife switches", do you mean the kind that are shaped like > flat paddles? > Pedantic correction: "Knife switch" is the wrong term. These are high current switches, typically used in the sort of heavy duty circuit where the wiring hums when power is on or in school electrical circuits so even the back of the class can see whether the switch is open or closed. In these a copper 'blade' closes the contact by being pushed down into a narrow, sprung U terminal that makes a close contact with both sides of the blade. Like this: http://www.science-city.com/knifeswitch.html What you're talking is a flat handle on a SPST or DPST toggle switch. It is often called a paddle switch and mounted with the flats on the handle horizontal. Like this, but often with a longer handle: http://www.pixmania.co.uk/uk/uk/1382717/art/radioshack/spdt-panel-mount- paddle-s.html -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From seandavi at gmail.com Thu Sep 11 04:23:00 2008 From: seandavi at gmail.com (Sean Davis) Date: Thu, 11 Sep 2008 01:23:00 -0700 (PDT) Subject: emulating read and readline methods References: <ee4202f1-ce8f-458e-9627-08215351694d@e53g2000hsa.googlegroups.com> <e1941052-a524-477e-b498-521f52ea2b92@25g2000hsx.googlegroups.com> <ba72b905-d5b8-4e8c-9ef7-252c9e51a48d@a2g2000prm.googlegroups.com> Message-ID: <0d961161-3789-46c3-8018-06b26af7f767@x35g2000hsb.googlegroups.com> On Sep 10, 7:54?pm, John Machin <sjmac... at lexicon.net> wrote: > On Sep 11, 8:01?am, MRAB <goo... at mrabarnett.plus.com> wrote: > > > > > On Sep 10, 6:59?pm, Sean Davis <seand... at gmail.com> wrote: > > > > I have a large file that I would like to transform and then feed to a > > > function (psycopg2 copy_from) that expects a file-like object (needs > > > read and readline methods). > > > > I have a class like so: > > > > class GeneInfo(): > > > ? ? def __init__(self): > > > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > > > gene_info.gz',"/tmp/gene_info.gz") > > > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > > > ? ? ? ? self.fh.readline() #deal with header line > > > > ? ? def _read(self,n=1): > > > ? ? ? ? for line in self.fh: > > > ? ? ? ? ? ? if line=='': > > > ? ? ? ? ? ? ? ? break > > > ? ? ? ? ? ? line=line.strip() > > > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > > > ? ? ? ? ? ? rowvals = line.split("\t") > > > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > > > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > > > ? ? def readline(self,n=1): > > > ? ? ? ? return self._read().next() > > > > ? ? def read(self,n=1): > > > ? ? ? ? return self._read().next() > > > Each time readline() and read() call self._read() they are creating a > > new generator. They then get one value from the newly-created > > generator and then discard that generator. What you should do is > > create the generator in __init__ and then use it in readline() and > > read(). > > > > ? ? def close(self): > > > ? ? ? ? self.fh.close() > > > > and I use it like so: > > > > a=GeneInfo() > > > cur.copy_from(a,"gene_info") > > > a.close() > > > > It works well except that the end of file is not caught by copy_from. > > > I get errors like: > > > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > > > during .read() call > > > CONTEXT: ?COPY gene_info, line 1000: "" > > > > for a 1000 line test file. ?Any ideas what is going on? > > > I wonder whether it's expecting readline() and read() to return an > > empty string at the end of the file instead of raising StopIteration. > > Don't wonder; ReadTheFantasticManual: > > read( [size]) > > ... An empty string is returned when EOF is encountered > immediately. ... > > readline( [size]) > > ?... An empty string is returned only when EOF is encountered > immediately. Thanks. This was indeed my problem--not reading the manual closely enough. And the points about the iterator being re-instantiated were also right on point. Interestingly, in this case, the code was working because read() and readline() were still returning the next line each time since the file handle was being read one line at a time. Sean From google at mrabarnett.plus.com Mon Sep 22 20:12:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Sep 2008 17:12:35 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> <1f913671-1c21-4018-a841-a5a02a360c3b@k30g2000hse.googlegroups.com> Message-ID: <49ffb44f-c14d-4d38-86fb-eb50e5ef9abf@d1g2000hsg.googlegroups.com> On Sep 22, 11:07?pm, CapnBearbo... at googlemail.com wrote: > On Sep 22, 5:52?pm, Matimus <mccre... at gmail.com> wrote: > > > > > On Sep 22, 2:31?pm, CapnBearbo... at googlemail.com wrote: > > > > hi all, > > > > forgive me , but the RTFM and Google search approaches are not > > > yielding an answer on this question. ?I need to know if there's a top > > > level python interpreter command that clears all user variables (not > > > built-ins) from the global namespace. ?In other words a statement, or > > > some_command_or_function(), that does this: > > > > >>> x=3 > > > >>> y=4 > > > >>> z=[] > > > >>> dir() > > > > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > > > > >>> some_command_or_function() > > > >>> dir() > > > > ['__builtins__', '__doc__', '__name__'] > > > > thanks, > > > ? ?1 desperate snake oil programmer .... > > > I don't think you will find anything. The interpreter is essentially > > the same whether you are in interactive mode or not. That is, there is > > very little use for a method that clears globals in general, so why > > would we add it just so that it could be used by the interpreter. > > There is almost* nothing available to the interactive interpreter > > which isn't part of the core language. > > > * The only difference I can think of is the "_" variable, which is > > added to __builtins__ and contains the last value returned in > > interactive mode. If you have ever tried to run code that uses the > > locale module from the interpreter you will see why having any > > differences between the interactive and non-interactive interpreter > > can be a pain. > > > Matt > > ok. thanks! guess i'll be off to define my own function ... How about something like this: def clear_workspace(): keep_set = set(['__builtins__', '__doc__', '__name__', 'clear_workspace']) for x in globals().keys(): if x not in keep_set: del globals()[x] From castironpi at gmail.com Wed Sep 10 15:13:34 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 10 Sep 2008 12:13:34 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <3d6488c1-d57c-46be-b404-9c79bd49dbdf@y21g2000hsf.googlegroups.com> Message-ID: <09951f30-83d5-452c-9f78-c3d7491ecc32@a70g2000hsh.googlegroups.com> On Sep 9, 10:03?pm, George Sakkis <george.sak... at gmail.com> wrote: > On Sep 9, 5:59?pm, castironpi <castiro... at gmail.com> wrote: > > > I will try my idea again. ?I want to talk to people about a > > module I want to write and I will take the time to explain it. > >?I think it's a "cool idea" that a lot of people, forgiving the > > slang, could benefit from. ? > > > (snipped) > > > A pure Python alloc-free implementation based on the GNU PAVL > > tree library is on Google Code. ?It is only in proof-of-concept > > form and not commented, but does contain a first-pass test > > suite. ?See: > > ? ?http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk > > So at best (i.e. if it actually makes any sense; I didn't read it), > this is an ANNouncement of a pre-alpha piece of code. ANN posts rarely > attract replies, even when they are about production/stable software. > Thankfully, most people don't expect (let alone "require") readers to > share their interest or enthusiasm by replying to the ANN. Given your > past semi-coherent and incoherent posts, expecting people to jump on > such a thread is a rather tall order. > > George No, I'm just excited about it and want to share. I definitely think that discouragement of new ideas, successes, and personal expressions is a weakness that society has, and something that c-l-py is missing as well. I want to encourage them in other people so I will do it myself. As for the practicality of this module, I am definitely receiving skepticism from the group. Further, its feasibility is in question. For instance, no one has pointed out, and I only came across last night, that IPC synchronization is non-trivial and possibly platform- dependent. Of course it's a prerequisite for the advance of any IPC mod, so I'm glad I did not release an ANN. From fredrik at pythonware.com Wed Sep 10 12:46:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 18:46:56 +0200 Subject: dict slice in python (translating perl to python) In-Reply-To: <HDSxk.1411$ZY5.32@newsfe02.iad> References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> <HDSxk.1411$ZY5.32@newsfe02.iad> Message-ID: <ga8tm0$nls$1@ger.gmane.org> B wrote: > for a long list, you could try: > result = [mydict[k] for k in mydict] > or [mydict[k] for k in mydict.keys()] > or [mydict[k] for k in mydict.iterkeys()] and the point of doing that instead of calling mydict.values() is what? </F> From tjreedy at udel.edu Sun Sep 28 17:47:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 17:47:44 -0400 Subject: closures and dynamic binding In-Reply-To: <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> Message-ID: <gbou1p$s37$1@ger.gmane.org> Aaron "Castironpi" Brady wrote: > On Sep 28, 2:52 am, Steven D'Aprano <st... at REMOVE-THIS- >> As for why the complicated version works, it may be clearer if you expand >> it from a one-liner: >> >> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) >> >> inner = lambda: n >> outer = lambda n: inner >> f[n] = outer(n) >> >> outer(0) => inner with a local scope of n=0 >> outer(1) => inner with a local scope of n=1 etc. For this to work, the 'expansion' has to be mental and not actual. Which is to say, inner must be a text macro to be substituted back into outer. >> Then, later, when you call inner() it grabs the local scope and returns >> the number you expected. > > I must have misunderstood. Here's my run of your code: I cannot speak to what Steven meant, but >>>> inner = lambda: n when inner is actually compiled outside of outer, it is no longer a closure over outer's 'n' and 'n' will be looked for in globals instead. >>>> outer = lambda n: inner >>>> outer(0) > <function <lambda> at 0x00A01170> >>>> a=outer(0) >>>> b=outer(1) >>>> a() > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "<stdin>", line 1, in <lambda> > NameError: global name 'n' is not defined > > Why doesn't 'inner' know it's been used in two different scopes, and > look up 'n' based on the one it's in? That would be dynamic rather than lexical scoping. From wuwei23 at gmail.com Thu Sep 4 20:54:32 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 4 Sep 2008 17:54:32 -0700 (PDT) Subject: xml + mmap cross References: <a27b2e33-bddb-407e-b2ea-895dc78c7090@r15g2000prd.googlegroups.com> Message-ID: <6a7336f2-8f71-47c2-88d5-d5172f14ce44@k36g2000pri.googlegroups.com> On Sep 4, 8:31?am, castironpi <castiro... at gmail.com> wrote: > Any interest in pursuing/developing/working together on a mmaped-xml > class? ?Faster, not readable in text editor. XML is text-based, so it should -always- be readable in a text editor. It's part of the definition, I believe. However, an implementation of one of the alternative binary XML formats would probably be very welcome. Fast Infoset: http://www.itu.int/rec/T-REC-X.891-200505-I/en EXI: http://www.w3.org/TR/2007/WD-exi-20070716/ I don't know enough about either format to say if it would be possible, but an implementation that conformed to the ElementTree API could be a big win. From aioe.org at technicalbloke.com Wed Sep 17 13:19:27 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 13:19:27 -0400 Subject: Python GUI for animation References: <mailman.1087.1221546557.3487.python-list@python.org> <1896f3dc-d8b6-41f4-9ff2-4c9cefc1ab84@a18g2000pra.googlegroups.com> Message-ID: <gare6u$7bc$1@aioe.org> Sean DiZazzo wrote: > On Sep 15, 11:29 pm, Virgil Stokes <v... at it.uu.se> wrote: >> I have been using Python for a short time and I find it a very flexible >> language, and easy to learn and use. I have also worked some with PyGame <snip> > Then again, you mention sliders, knobs, etc. I don't think Tkinter > has alot of widgets built in. The other choice would be wxPython. > It's got lots of built in widgets, and it looks pretty good. If you > go this route, run the demo application to see what you have to work > with. > > http://wxpython.org/ > > Good luck. > > ~Sean Yes, I'd say wxPython is the way to go, mainly because of the numerous and excellent examples and example program. Also, gui stuff can be lengthy and verbose to code by hand and if you're using wxPython you can also use wxGlade, a python version of the popular Glade gui builder. Good luck :] Roger Heathcote. http://www.technicalbloke.com http://movingtoubuntu.technicalbloke.co.uk From kw at codebykevin.com Tue Sep 30 14:15:19 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 30 Sep 2008 14:15:19 -0400 Subject: IDLE doesn't run on OSX 10.3.9 In-Reply-To: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> References: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> Message-ID: <48E26CB7.8060207@codebykevin.com> thomascribbs at gmail.com wrote: > Just installed Python 2.5.2 on a PowerPC G4 running OSX 10.3.9 and > when clicking on the IDLE icon in the MacPython 2.5 folder nothing > happens, program doesn't execute... > > I've uninstalled, reinstalled over again... > > I friend of mine just installed the same 2.5.2 download from the > Python.org website on OSX 10.4.11 and all went fine...but shouldn't it > install on 10.3.9 as well? > > Anyone have any ideas? Thanks. > -Tom Do you have Tcl/Tk installed? It doesn't come on 10.3.9 by default. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From andreas.tawn at ubisoft.com Thu Sep 18 13:32:41 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Thu, 18 Sep 2008 19:32:41 +0200 Subject: Extracting hte font name from a TrueType font file In-Reply-To: <gau1dk$t7h$1@ger.gmane.org> References: <gau1dk$t7h$1@ger.gmane.org> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758004C23CA0@PDC-MAIL3.ubisoft.org> > -----Original Message----- > From: python-list-bounces+andreas.tawn=ubisoft.com at python.org > [mailto:python-list-bounces+andreas.tawn=ubisoft.com at python.or g] On Behalf Of Steve Holden > Sent: Thursday, September 18, 2008 5:59 PM > To: python-list at python.org > Subject: Extracting hte font name from a TrueType font file > > Does anyone have a Python recipe for this? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > Can't help with a recipe, but here's the formal spec if want to figure it out yourself. http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6.html Hope that helps. Cheers, Drea From rsinger at ____.com Tue Sep 23 16:05:55 2008 From: rsinger at ____.com (Robert Singer) Date: Tue, 23 Sep 2008 22:05:55 +0200 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> Message-ID: <eogid4d6s2a5l55pu20220sr2bdt5s6hob@4ax.com> On Tue, 23 Sep 2008 11:07:22 -0700 (PDT), sturlamolden <sturlamolden at yahoo.no> wrote: >On Sep 23, 3:44?pm, Robert Singer <rsinger at ____.com> wrote: > >> Well, python is not a number crunching language. However much we would >> like it to be (we would ? :-). > >> No scripting language is. > >Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? > No. And just to avoid eventual useless discussions which might arise, I ment to say that *in general* compiled languages are faster. We can always have discussions whether or not some newer scripting languages like some from the above list, come close, but that usually is just wasted time. Specifically, I cannot say about R, IDL or S-PLUS, since I never used those (not even heard of IDL till now). Octave and Mathematica have been with me for such a short time (we had a few licences for Wolfram's child for one year, but not my part of the company, so ...) that I would rather not give my opinion about those. I've used Matlab and Scilab for a longer time (still do actually - Matlab for measurement data acquisition, and Scilab ... well, it just sits on the disk somewhere actually), and although Matlab is quite fast when disk I/O is involved, it still comes far. >> Also, (I'm not that familiar with python yet, so I don't know how to >> do it in python), try finding the bottlenecks of your calculation. > >I did use a profiler, there is no particular single bottle-neck. You're talking about your c or your python version of the program? There is always a bottleneck - that's just the part which works most slowly. Try to find the part which takes the longest to execute, try to put it differently. If it cannot be done, go to the next slowest part. >Good compilers are too expensive, and gfortran is not good enough yet. > ? Gfortran is one of the better compilers on the market. There was, just the other day, a nice discussion on comp.lang.fortran how it is marvellous what a group of enthousiasts managed do in their time, what commercial giants still didn't. May I ask what are your main objections to it ? Best regards Bob From ldo at geek-central.gen.new_zealand Wed Sep 24 06:15:09 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:15:09 +1200 Subject: A bit weird dictionary behavior References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> <gb957i$ja0$1@news.lublin.pl> <mailman.1385.1222126198.3487.python-list@python.org> Message-ID: <gbd3vd$vo9$1@lust.ihug.co.nz> In message <mailman.1385.1222126198.3487.python-list at python.org>, Terry Reedy wrote: > From this viewpoint, objecters would instead have to argue that it is > wrong to have such implicit calls and that programmers should have to > put them in explicitly. But then again, you want to avoid unexpected restrictions like in Java, where bool is a separate type, and while it is discrete, it cannot be used to index arrays. (Cf Pascal, where any discrete type could be used as an array index type.) From uninverted at lavabit.com Sun Sep 28 20:58:35 2008 From: uninverted at lavabit.com (Nathan Seese) Date: Mon, 29 Sep 2008 02:58:35 +0200 (CEST) Subject: Odd Errors References: <gbp6cf$vac$1@aioe.org> <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> <1b1ed34d-f386-4389-a7f1-ce68be4e2a14@k30g2000hse.googlegroups.com> Message-ID: <gbp97r$co4$1@aioe.org> > On Sep 28, 7:13?pm, alex23 <wuwe... at gmail.com> wrote: >> The problem is with this: >> >> > ? ? ? ? lines = lines.append(inLine) >> >> The append method of a list modifies the list in-place, it doesn't >> return a copy of the list with the new element appended. In fact, it >> returns None, which it then attaches the label 'lines' to, so the next >> iteration through it tries to call None.append... >> >> Replace the line with: >> >> ? ? lines.append(inLine) > > Do you ever want to scream from the rooftops, "'append' operates by > side-effect!"? Ah! Thanks, especially for the quick response. From gagsl-py2 at yahoo.com.ar Tue Sep 9 12:03:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 13:03:33 -0300 Subject: Clearing a session and reload() problem (with repro error) References: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> Message-ID: <op.ug71j7hkx6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 08 Sep 2008 05:37:24 -0300, Rafe <rafesacks at gmail.com> escribi?: > I've tried to use reload with a very simple algorithm. Simply run > through every imported module, ignoring anything that is "None" or on > the C: drive (all of our python is on a network drive so this hack > works for me for now) and reload() it. I've come to realize that this > isn't near intelligent enough to handle sub-packages. > Package Structure: > --------------------------- > inheritRepro > __init__.py > baseLib.py > child > __init__.py To summarize your code: inheritRepro.__init__.py only contains the reload support; baselib is an independent module; child/__init__.py imports and uses baseLib. > # Iterate over all IMPORTED modules > modules = sys.modules > for modName in modules: > mod = modules[modName] (note: sys.modules could change along the iteration; I'd iterate this way instead) modules = sys.modules for modName in modules.keys(): mod = modules.get(modName) Output: Reloading Python Modules... Reloaded <module 'inheritRepro' from 'C:\TEMP\problema_con_reload\inheritRepro\_ _init__.pyc'> Reloaded <module 'inheritRepro.child' from 'C:\TEMP\problema_con_reload\inheritR epro\child\__init__.pyc'> Reloaded <module 'inheritRepro.baseLib' from 'C:\TEMP\problema_con_reload\inheri tRepro\baseLib.pyc'> Note that child is reloaded *before* baseLib - when child imports baseLib, it still finds the old module. One should reload baseLib before reloading child, in that case it works fine. This dependency between modules, applied to all modules in your project, defines a "dependency graph". In some cases, one can define a partial ordering of its nodes, such that no module depends on any other module *after* it (it may depend only on modules *before* it). Look for "topological sort". Doing that in the generic case is not easy. If you *know* your dependencies, reload the modules in the right order by hand. > NOTE: this works if I don't use a sub-package for 'child' (child.py > instead). Is it overly simple to assume reloading by file structure > might work? You're iterating over sys.modules in whatever ordering the keys are in the dictionary; using other module names may yield the "right" ordering just by chance. -- Gabriel Genellina From google at mrabarnett.plus.com Fri Sep 26 09:03:22 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Sep 2008 06:03:22 -0700 (PDT) Subject: multiprocessing eats memory References: <mailman.1497.1222346460.3487.python-list@python.org> <edd14466-262f-4333-8823-601fd682659d@c36g2000prc.googlegroups.com> <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> Message-ID: <afb35903-97ab-45d0-a4e0-fcca2aded20b@25g2000hsx.googlegroups.com> On Sep 26, 9:52?am, redbaron <ivanov.ma... at gmail.com> wrote: > On 26 ????, 04:20, Istvan Albert <istvan.alb... at gmail.com> wrote: > > > On Sep 25, 8:40?am, "Max Ivanov" <ivanov.ma... at gmail.com> wrote: > > > > At any time in main process there are shouldn't be no more than two copies of data > > > (one original data and one result). > > > From the looks of it you are storing a lots of references to various > > copies of your data via the async set. > > How could I avoid of storing them? I need something to check does it > ready or not and retrieve results if ready. I couldn't see the way to > achieve same result without storing asyncs set. You could give each worker process an ID and then have them put the ID into a queue to signal to the main process when finished. BTW, your test-case modifies the asyncs set while iterating over it, which is a bad idea. From gagsl-py2 at yahoo.com.ar Mon Sep 29 16:41:29 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 17:41:29 -0300 Subject: unable to parse the content using the regular expression References: <e0b6c39a0809250130m46b40589vc8ba31679d31cf57@mail.gmail.com> Message-ID: <op.uh9frffdx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 25 Sep 2008 05:30:41 -0300, <dudeja.rajat at gmail.com> escribi?: > I've the following results from Difflib.Compare() which I want to parse > them > using the regular expression to find out the the values that have > changed. > > Results:- > ------- > > - Analysis Time (Iterations = 1) = 0.0449145s > ? ^^ ^ > + Analysis Time (Iterations = 1) = 0.0447347s > ? ^^ ^ > > > Here I want to display only the values that differ i.e. the lines prceded > with +,?,- signs > Instead of parsing that generated file (intended for human usage), use difflib.Differ or difflib.SequenceMatcher - you get a programming interface to the same info, easier to use in a script. -- Gabriel Genellina From 4g4trz802 at sneakemail.com Tue Sep 9 14:49:32 2008 From: 4g4trz802 at sneakemail.com (Michael Hoffman) Date: Tue, 09 Sep 2008 11:49:32 -0700 Subject: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles Message-ID: <ga6gfu$lgk$1@aioe.org> I am writing a library that creates temporary files and calls a series of external programs to process these files. Sometimes these external programs create files in the same directory as the input files, so to make sure they are all deleted, one must create them in a temporary directory, then delete it. I've written a NamedTemporaryDir class which is derived somewhat from tempfile.NamedTemporaryFile in the standard library. Right now I am using NamedTemporaryFile to create individual files, but since I am putting them in a directory that will be deleted anyway, I'm wondering if I can simplify things (and not have to keep track of all fo the NamedTemporaryFile instances) by using tempfile.mkstemp() specifying my temporary directory, and relying on the directory deletion when exiting its with block. Is there any reason I should keep track of each temporary files myself instead of deleting the whole directory? I am using Linux, but I would also be interested in cross-platform considerations. Also, the code is below. Is this worth submitting as a patch? # NamedTemporaryFile is based somewhat on Python 2.5.2 # tempfile._TemporaryFileWrapper # # Original Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python # Software Foundation; All Rights Reserved # # License at http://www.python.org/download/releases/2.5.2/license/ from tempfile import mkdtemp class NamedTemporaryDir(object): def __init__(self, *args, **kwargs): self.name = mkdtemp(*args, **kwargs) self.close_called = False def __enter__(self): return self unlink = os.unlink def close(self): if not self.close_called: self.close_called = True self.unlink(self.name) def __del__(self): self.close() def __exit__(self, exc, value, tb): result = self.file.__exit__(exc, value, tb) self.close() return result From gminick at bzt.bzt Fri Sep 26 06:15:33 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 26 Sep 2008 10:15:33 +0000 (UTC) Subject: how to replace and string in a "SELECT ... IN ()" References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> Message-ID: <gbico4$fo3$1@inews.gazeta.pl> On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote: > I have a BIIIIIG problem with the next query: > > cursor.execute(""" > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """,( eid_list)) ^ It should rather be '%'. HTH. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From lucafbb at gmail.com Mon Sep 1 05:45:36 2008 From: lucafbb at gmail.com (Luca) Date: Mon, 1 Sep 2008 11:45:36 +0200 Subject: Know if a object member is a method In-Reply-To: <pan.2008.09.01.09.35.37@REMOVE.THIS.cybersource.com.au> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> <mailman.319.1220259149.3487.python-list@python.org> <pan.2008.09.01.09.35.37@REMOVE.THIS.cybersource.com.au> Message-ID: <27308d500809010245x29a393aya65561783ea0e804@mail.gmail.com> On Mon, Sep 1, 2008 at 11:35 AM, Steven D'Aprano <steven at remove.this.cybersource.com.au> wrote: > That's relatively fragile, since such names aren't reserved in any way. > It's easy to fool a name comparison check with an accidental name > collision: > >>>> class function(object): # not a reserved name > ... pass > ... >>>> x = function() >>>> type(x).__name__ > 'function' >>>> x() # must be a function then... > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: 'function' object is not callable > > > But not so easy to fool a type check: > >>>> type(x) == new.function > False > > Of course that's not bullet-proof either. I leave it as an exercise to > discover how you might break that piece of code. > Ok, so... What is the best way to do this? The "most pythonic"? -- -- luca From bearophileHUGS at lycos.com Mon Sep 29 12:57:31 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 09:57:31 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <mailman.1520.1222400746.3487.python-list@python.org> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <gbq5p8$iiq$1@lust.ihug.co.nz> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> Message-ID: <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Lawrence D'Oliveiro: >> Gnuplot is non-Free software. Fly Away: > Yes, it is. From: http://www.gnuplot.info/faq/faq.txt 1.7 Does gnuplot have anything to do with the FSF and the GNU project? [...] Gnuplot is freeware in the sense that you don't have to pay for it. However it is not freeware in the sense that you would be allowed to distribute a modified version of your gnuplot freely. [...] Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Tue Sep 2 12:54:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 16:54:54 GMT Subject: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0 References: <pD5vk.59354$_03.18175@reader1.news.saunalahti.fi> <48bd6b4e$0$17174$742ec2ed@news.sonic.net> Message-ID: <00cd6a58$0$20302$c3e8da3@news.astraweb.com> On Tue, 02 Sep 2008 09:57:05 -0700, John Nagle wrote: > Jukka Aho wrote: >> Just a tip for those who are only just cutting their teeth on Python >> 3.0 and might have encountered the same problem as I did: >> >> When a Python (3.x) program is run on a terminal that only supports a >> legacy character encoding - such as Latin 1 or Codepage 437 - all >> characters printed to stdout will be automatically converted from the >> interpreter's internal Unicode representation to this legacy character >> set. > > Python 5 is even stricter. Only ASCII (chars 0..127) can be sent > to standard output by default. Python 5??? Is this the time machine again? -- Steven From ptmcg at austin.rr.com Wed Sep 3 01:14:51 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 2 Sep 2008 22:14:51 -0700 (PDT) Subject: pyparsing: match empty line References: <g9jq5i$ou8$1@hoshi.visyn.net> Message-ID: <9f838a29-2e2e-4646-9026-36d3b8a49fce@c58g2000hsc.googlegroups.com> On Sep 2, 11:38?am, Marek Kubica <ma... at xivilization.net> wrote: > Hi, > > I am trying to get this stuff working, but I still fail. > > I have a format which consists of three elements: > \d{4}M?-\d (4 numbers, optional M, dash, another number) > EMPTY (the <EMPTY> token) > [Empty line] (the <PAGEBREAK> token. The line may contain whitespaces, > but nothing else) > <snip> Marek - Here are some refinements to your program that will get you closer to your posted results. 1) Well done in resetting the default whitespace characters, since you are doing some parsing that is dependent on the presence of line ends. When you do this, it is useful to define an expression for end of line so that you can reference it where you explicitly expect to find line ends: EOL = LineEnd().suppress() 2) Your second test fails because there is an EOL between the two watchnames. Since you have removed EOL from the set of default whitespace characters (that is, whitespace that pyparsing will automatically skip over), then pyparsing will stop after reading the first watchname. I think that you want EOLs to get parsed if nothing else matches, so you can add it to the end of your grammar definition: parser = OneOrMore(watchname ^ pagebreak ^ leaveempty ^ EOL) This will now permit the second test to pass. 3) Your definition of pagebreak looks okay now, but I don't understand why your test containing 2 blank lines is only supposed to generate a single <PAGEBREAK>. pagebreak = LineStart() + LineEnd().setParseAction(replaceWith('<PAGEBREAK>')) If you really want to only get a single <PAGEBREAK> from your test case, than change pagebreak to: pagebreak = OneOrMore(LineStart() + LineEnd()).setParseAction(replaceWith('<PAGEBREAK>')) 4) leaveempty probably needs this parse action to be attached to it: leaveempty = Literal('EMPTY').setParseAction(replaceWith('<EMPTY>')) 5) (optional) Your definition of parser uses '^' operators, which translate into Or expressions. Or expressions evaluate all the alternatives, and then choose the longest match. The expressions you have don't really have any ambiguity to them, and could be evaluated using: parser = OneOrMore(watchname | pagebreak | leaveempty | EOL) '|' operators generate MatchFirst expressions. MatchFirst will do short-circuit evaluation - the first expression that matches will be the one chosen as the matching alternative. If you have more pyparsing questions, you can also post them on the pyparsing wiki - the Discussion tab on the wiki Home page has become a running support forum - and there is also a Help/Discussion mailing list. Cheers, -- Paul From digitig at gmail.com Sun Sep 28 17:45:13 2008 From: digitig at gmail.com (Tim Rowe) Date: Sun, 28 Sep 2008 22:45:13 +0100 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <aee48b3c0809281445k4f148056xaeb25b91fbb62df@mail.gmail.com> 2008/9/28 process <circularfunc at gmail.com>: > I have heard some criticism about Python, that it is not fully object- > oriented. Why is that a criticism? OO is a tool, not a religion (ok, ok, OO *should be* a tool, not a religion). Is it a criticism of a hammer that it is not a screwdriver? Or do you pick the tool that does the job in hand most effectively? -- Tim Rowe From marco.bizzarri at gmail.com Wed Sep 10 13:18:18 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 10 Sep 2008 19:18:18 +0200 Subject: Presenting calculation results In-Reply-To: <ga8tkc$3qu$1@news1.carnet.hr> References: <ga8tkc$3qu$1@news1.carnet.hr> Message-ID: <3f0d61c40809101018q4346b322i2c6b42577c758601@mail.gmail.com> On Wed, Sep 10, 2008 at 6:46 PM, Vedran <not.my.email at mail.com> wrote: > Hello! > > I would like to present the results of the calculations on the web using > Python and Apache. Currently I have java console applications that > generate text files with results. Can somebody point me in the right > direction from where to start? > > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > http://www.modpython.org/ Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From fredrik at pythonware.com Sat Sep 6 06:58:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Sep 2008 12:58:37 +0200 Subject: use str as variable name In-Reply-To: <3f0d61c40809052308v185f3787p64f6fd89172114c7@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <mailman.464.1220515161.3487.python-list@python.org> <48bf9d12$0$7552$426a74cc@news.free.fr> <g9o7a9$t11$1@ger.gmane.org> <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> <g9t5ra$nfk$1@ger.gmane.org> <3f0d61c40809052308v185f3787p64f6fd89172114c7@mail.gmail.com> Message-ID: <g9tnou$etl$1@ger.gmane.org> Marco Bizzarri wrote: >>> Just a question: "generic functions" are not meant in the sense of >>> "generic functions" of CLOS, am I right? >> >> it's meant in exactly that sense: len(L) means "of all len() implementations >> available to the runtime, execute the most specific code we have for the >> object L". >> > > It is a generic functions like a CLOS one, as long as we remain to one > parameter. > > I mean, there will be just one implemenatation of > > foo(bar, man) > > which the python interpretr can find; am I right? Let's see if I can sort this out without causing even more confusion. The Python *language* doesn't support generic functions in the CLOS sense, but a given Python *implementation* may use a dispatching machinery to select the best possible implementation for any call to a built-in function. Or in other words, the len() function shouldn't just be seen as a function that *always* does def len(L): return L.__len__() because if you look under the covers, it might be more like (using a hypothetical Python dialect): def generic len(L: list): return list::get_size(L) # fast internal dispatch def generic len(L: tuple): return tuple::get_size(L) # fast internal dispatch def generic len(L: object): return L.__len__() # fallback behaviour, using method dispatch where "len" represents a plurality of possible "len" implementations. How the dispatching is actually done is up to the specific Python implementation; CPython, for example, offers a "slot" mechanism for types implemented in C that's quite a bit faster than the method call machinery. And the slot mechanism isn't always single dispatch. For example, internal getattr(obj, name) calls use one of several slots, depending on what "name" is. Other Python implementations may use different approaches, but the point remains: a builtin function "operation(a, b, c)" isn't always mapped to "a.__operation__(b, c)" by the runtime; code that uses the latter form may be less efficient. And it's definitely less Pythonic. </F> From circularfunc at yahoo.se Tue Sep 16 16:16:47 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 13:16:47 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> Message-ID: <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> On Sep 16, 7:49?pm, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 16, 10:13?am, cnb <circularf... at yahoo.se> wrote: > > > > > >>> sys.path > > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > > \lib\\site-packages\\PIL'] > > > Now I have my personal programs in C:/Python25/Progs/ > > > How do I add so that I can just do "import somefile" from anywhere in > > that directory in the interpreter and it can load files from other > > folders in that directory. > > Add a file: \Lib\site-packages\locals.pth > > with contents, path to the directory you want to add (/python25/progs/) And we have a winner! Now it works. Both doing import and loading form fiel with C-c C-l However jsut including C:/Python/Progs wasn't enough. I had to add the folder inside that that contains the files i needed. so how do i add all files within progs? is there something like C:/ python25/progs/* ? From nytrokiss at gmail.com Mon Sep 8 13:15:09 2008 From: nytrokiss at gmail.com (James Matthews) Date: Mon, 8 Sep 2008 10:15:09 -0700 Subject: Learning Python In-Reply-To: <_z9xk.830$sq3.754@trnddc07> References: <mailman.634.1220738820.3487.python-list@python.org> <_z9xk.830$sq3.754@trnddc07> Message-ID: <8a6b8e350809081015y60ee8ae2k6a8aa54d1f94998f@mail.gmail.com> I like two 1. www.diveintopython.com and 2. Core Python Programming. On Mon, Sep 8, 2008 at 6:15 AM, Alan G Isaac <alan.isaac at gmail.com> wrote: > On 9/6/2008 5:17 AM James Pilling apparently wrote: > >> Hi im currently starting to learn python in sixth form at school any tips? >> > > The books suggestions of others are quite good. > Here is another approach: pick an easily understandable > application, and work doing things with it. > > Perhaps immodestly, I think that as soon as you > understand how to define a function and a class, > you can treat this paper > http://jasss.soc.surrey.ac.uk/11/3/8.html > as an introduction to applied Python programming. > The application area is very specific---game theoretic > simulations---but the illustrated techniques are > meant to be more general. > > Alan Isaac > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/9e3a2df0/attachment-0001.html> From ssharkey at linuxunlimited.com Thu Sep 25 15:17:40 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Thu, 25 Sep 2008 15:17:40 -0400 Subject: Eggs, VirtualEnv, and Apt - best practices? Message-ID: <48DBE3D4.2080902@linuxunlimited.com> Hello all, Our development group at work seems to be heading towards adopting python as one of our standard "systems languages" for internal application development (yeah!). One of the issues that's come up is the problem with apt (deb packages) vs eggs, vs virtual environments. We're probably gonna end up using Pylons or TurboGears for web-based apps, and I've recommended virtualenv, but one of the other developers has had some "inconsistencies" when mixing systems with python installed from apt (all our servers are debian or ubuntu based) vs when installed under virtualenv. I have basically recommended that we only install the python base (core language) from apt, and that everything else should be installed into virtual environments. But I wanted to check to see how other enterprises are handling this issue? Are you building python from scratch, or using specific sets of .deb packages, or some other process. Any insight into the best way to have a consistent, repeatable, controllable development and production environment would be much appreciated. Suggestions on build/rollout tools (like zc.buildout, Paver, etc) would also be appreciated. Thanks!!! -Scott From castironpi at gmail.com Fri Sep 26 13:54:10 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 10:54:10 -0700 (PDT) Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> <Mo7Dk.2064$T65.1885@edtnps82> Message-ID: <9c2cf0b3-ca53-4c66-ba65-cd15aefb4cb8@p25g2000hsf.googlegroups.com> On Sep 26, 10:41?am, "Dmitry S. Makovey" <dmi... at athabascau.ca> wrote: > Paul McGuire wrote: > > If you need to get fancier and support this single-proxy-to-multiple- > > delegates form, then yes, you will need some kind of map that says > > which method should delegate to which object. ?Or, if it is just a > > matter of precedence (try A, then try B, then...), then use hasattr to > > see if the first delegate has the given attribute, and if not, move on > > to the next. > > that is what I didn't like about it - I have to iterate over delegates when > I can build direct mapping once and for all and tie it to class > definition ;) You're right, there is a difference in performance. But it would still be simpler to have your 'getattr' method 'learn' what functions come from what objects, and then just route directly to them. > __getattr__ implies constant lookups and checks (for filtering purposes) - I > want to do them once, attach generated methods as native methods and be > done with it. That is why I do not like __getattr__ in this particular > case. Otherwise - you're right. Try this (untested!): def __getattr__( self, key ): if key in self.knownmeths: return self.knownmeths[ key ] for x in self.delegs: if hasattr( x, key ): _= self.knownmethds[ key ]= getattr( x, key ) return _ raise name not found self.knownmethds has desired order of precedence. From roy at panix.com Sun Sep 28 12:59:29 2008 From: roy at panix.com (Roy Smith) Date: Sun, 28 Sep 2008 12:59:29 -0400 Subject: destructor not called References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> Message-ID: <roy-4A879E.12592928092008@news.panix.com> In article <2a7dea43-378a-423f-a5bb-d904b7f97869 at p25g2000hsf.googlegroups.com>, Marcin201 <marcin201 at gmail.com> wrote: > I have a class which uses a temporary directory for storing data. I > would like that directory to be removed when the class is no longer > used. I have tried removing the temporary directory from the class > destructor, however, it was never called. The short answer is that destruction in Python is non-deterministic (a rude shock if you're used to C++). What you probably want is the new "with" statement (http://docs.python.org/ref/with.html). From castironpi at gmail.com Thu Sep 4 15:57:51 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 12:57:51 -0700 (PDT) Subject: xml + mmap cross References: <a27b2e33-bddb-407e-b2ea-895dc78c7090@r15g2000prd.googlegroups.com> <48BF8AC8.6030509@behnel.de> Message-ID: <e17749c9-82f6-4f1e-a7f9-e9bf084fc27f@r15g2000prh.googlegroups.com> On Sep 4, 2:14?am, Stefan Behnel <stefan... at behnel.de> wrote: > castironpi wrote: > > Any interest in pursuing/developing/working together on a mmaped-xml > > class? ?Faster, not readable in text editor. > > Any hints on what you are talking about? > > Stefan Nice to hear from you. I assumed you were familiar with the problem; you're not. In an XML file, entries are stored in serial, sort of like this. AAA BBB CCC DDD Or more recognizably, <A><B><C>something</C><D>something</D></B></A> Point is, to change <C>something</C> to <C>something else</C>, you have to recopy everything after that. AAA BBB CCC DDD AAA BBBb CCC DDD requires 7 writes, 'b CCC DDD', not 1. I want to use a simple tree structure to store: 0 A-> None, 1 1 B-> None, 2 2 C-> 3, None 3 D-> None, None Each node maps to 'Next, Child', or more accurately, 'Next Sibling, First Child'. You get constant time updates to contents, and log-time searches. There was a similar problem today in: From: Gerhard H?ring <g... at ghaering.de> Date: Thu, 04 Sep 2008 13:08:59 +0200 Subject: Re: cPickle The OP wanted to update the third element in a pickled tuple, but not the first two. I propose to write a tree structure to a memory-mapped file. A heavyweight string class, Rope, I wrote, exceeded native string speeds at a file size of two megs. You could use that, or store the tree directly. The obstacle is probably mmap 'alloc' and 'free' routines, which I posted on Google Code. From castironpi at gmail.com Tue Sep 16 16:35:29 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 13:35:29 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <mailman.1138.1221594080.3487.python-list@python.org> Message-ID: <fc325739-c2cb-492c-af29-58466ccb54b0@79g2000hsk.googlegroups.com> On Sep 16, 2:40?pm, "Support Desk" <m... at ipglobal.net> wrote: > What about on a unix box? Do you have write permissions on, in this case, '/opt/pkgs/python-2.0/ lib/python2.0/site-packages' ? (Or the entry in your sys.path.) >>> import sys >>> sys.path ['', '/opt/pkgs/python-2.0/lib/python2.0', '/opt/pkgs/python-2.0/lib/ python2.0/plat-sunos5', '/opt/pkgs/python-2.0/lib/python2.0/lib-tk', '/ opt/pkgs/python-2.0/lib/python2.0/lib-dynload', '/opt/pkgs/python-2.0/ lib/python2.0/site-packages'] > > Sincerely, > Michael H. > > -----Original Message----- > From: Aaron "Castironpi" Brady [mailto:castiro... at gmail.com] > Sent: Tuesday, September 16, 2008 12:49 PM > To: python-l... at python.org > Subject: Re: How do I add permanently to Pythons sys.path? > > On Sep 16, 10:13?am, cnb <circularf... at yahoo.se> wrote: > > >>> sys.path > > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > > \lib\\site-packages\\PIL'] > > > Now I have my personal programs in C:/Python25/Progs/ > > > How do I add so that I can just do "import somefile" from anywhere in > > that directory in the interpreter and it can load files from other > > folders in that directory. > > Add a file: \Lib\site-packages\locals.pth > > with contents, path to the directory you want to add (/python25/progs/) > > From fredrik at pythonware.com Thu Sep 4 03:36:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 09:36:29 +0200 Subject: use str as variable name In-Reply-To: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> Message-ID: <g9o35t$7jm$1@ger.gmane.org> Mathieu Prevot wrote: > I have a program that take a word as argument, and I would like to > link this word to a class variable. > > eg. > class foo(): > width = 10 > height = 20 > > a=foo() > arg='height' > a.__argname__= new_value > > rather than : > > if arg == 'height': > a.height = new_value > elif arg == 'width'; > a.width = new_value > > Can I do this with python ? How ? assuming you mean "instance variable" ("a" is an instance of the class "foo"), you can use setattr: a = foo() arg = 'height' setattr(a, arg, new_value) </F> From rustompmody at gmail.com Wed Sep 3 06:10:40 2008 From: rustompmody at gmail.com (rustom) Date: Wed, 3 Sep 2008 03:10:40 -0700 (PDT) Subject: eval() == evil? --- How to use it safely? References: <d836e712-0dbd-4caf-a32b-99c3c3cc1c16@z66g2000hsc.googlegroups.com> <9d5933fd-f990-4bab-8dfb-258e245cc7d2@j22g2000hsf.googlegroups.com> Message-ID: <aac4f266-83e1-4a41-8c91-525ccdf7b96e@v16g2000prc.googlegroups.com> On Aug 29, 4:42?am, castironpi <castiro... at gmail.com> wrote: > May I suggest PyYAML? I second that. Yaml is very pythonic (being indentation based) and pyyaml is sweet. Only make sure you use safe_load not load and you will have only default construction for standard python objects -- lists, dictionaries and 'atomic' things so no arbitrary code can be executed. Someone else suggested json which is about the same as yml if there are no objects. And by using safe_load you are not using objects. From mensanator at aol.com Mon Sep 15 00:00:51 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 14 Sep 2008 21:00:51 -0700 (PDT) Subject: RELEASED Python 2.6rc1 References: <mailman.953.1221269347.3487.python-list@python.org> Message-ID: <da2716b3-5f4c-4ea8-b36d-6d4b3aaa5986@k30g2000hse.googlegroups.com> On Sep 12, 8:28?pm, Barry Warsaw <ba... at python.org> wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I ? > am happy to announce the first release candidate for Python 2.6. > > This is a release candidate, so while it is not suitable for ? > production environments, we strongly encourage you to download the ? > release and test it on your software. ?We expect only critical bugs to ? > be fixed between now and the final 2.6 release, still scheduled for ? > October 1st, 2008. ?There is one more release candidate planned for ? > September 17th. > > You might notice that unlike earlier releases, we are /not/ releasing ? > Python 3.0rc1 at this time. ?It was decided that 3.0 still needs time ? > to resolve open issues and that we would not hold up the 2.6 release ? > for this. ?We feel that Python 2.6 is nearly ready for its final ? > release. > > If you find things broken or incorrect, please submit bug reports at > > ? ? ?http://bugs.python.org > > For more information and downloadable distributions, see the Python ? > 2.6 website: > > ? ?http://www.python.org/download/releases/2.6/ > > (Note that the Windows installers will be uploaded shortly.) About this Vista note on that page: <quote> Vista Note Administrators installing Python for all users on Windows Vista either need to be logged in as Administrator, or use the runas command, as in: runas /user:Administrator "msiexec /i <path>\<file>.msi" </quote> I couldn't get Idle to run until Python was installed this way, so it appears to be required even for a single user. And I know that Windows operation is not Python's responsibility, but couldn't you point out casually that, by default, the Administrator account is disabled in Vista. And the above won't work until you find out how to enable the Administrator (an easy Google search). > > See PEP 361 for release schedule details: > > ? ? ?http://www.python.org/dev/peps/pep-0361/ > > Enjoy, > - -Barry > > Barry Warsaw > ba... at python.org > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.9 (Darwin) > > iQCVAwUBSMsXV3EjvBPtnXfVAQJFsgP9GxZYQocbDTd0Z/0yEjpHfZ/FTd8y83jV > 5JouO07lB8XtLawnWB9hF8sUrCuBVog5He3mLVUPDmlyn30qvjYWMG2J6zW0yYMX > yZdjUyUmta0IMCsXe7YXj369xebh4nWuwG4tDygly4donA7GYPXAlxI48MmyDJxw > 1v07LM4Dttw= > =Nd3s > -----END PGP SIGNATURE----- From nemesis at nowhere.invalid Tue Sep 16 15:31:09 2008 From: nemesis at nowhere.invalid (Nemesis) Date: 16 Sep 2008 19:31:09 GMT Subject: [ANN] XPN 1.2.5 Message-ID: <48d0097d$0$40312$4fafbaef@reader5.news.tin.it> XPN (X Python Newsreader) is a multi-platform newsreader with Unicode support. It is written with Python+GTK. It has features like scoring/actions, X-Face and Face decoding, muting of quoted text, newsrc import/export, find article and search in the body, spoiler char/rot13, random taglines and configurable attribution lines. You can find it on: http://xpn.altervista.org/index-en.html or http://sf.net/projects/xpn Changes in this release: * v1.2.5: rewritten the articles management, now the articles are stored in a SQLite dB. Articles management now is faster and easier. Your xpn-1.0.0 groups and articles will be automatically imported and converted to the new format. * v1.2.5: added a filter toolbar that lets you filter the articles by Subject From and Body content. * v1.2.5: improved the algorithm used to build the discussion threads * v1.2.5: revisited the menus and some windows * v1.2.5: added automatic headers download every tot minutes * v1.2.5: some minor fixes and refinements. XPN is translated in Italian French and German, if you'd like to translate it in your language and you are familiar with gettext and po-files editing please contact me (xpn at altervista.org). -- Some memories are best forgotten _ _ _ | \| |___ _ __ ___ __(_)___ | .` / -_) ' \/ -_|_-< (_-< |_|\_\___|_|_|_\___/__/_/__/ http://xpn.altervista.org From marco.bizzarri at gmail.com Fri Sep 12 09:50:40 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 12 Sep 2008 15:50:40 +0200 Subject: Checking the boolean value of a collection Message-ID: <3f0d61c40809120650x7119940fr1a598eecd05b412e@mail.gmail.com> Hi all. In many parts of my code I've the following schema of code: def isInUseByOutgoingRegistrations(self, archivefolder): for instance in self.findActiveOutgoingRegistrationInstances(): if instance.forbidToClose(archivefolder): return True return False Before devising my own solution for this kind of problem, I wonder if there is a common solution for the problem. I'm looking for a python2.3 solution. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From afilash at gmail.com Sun Sep 7 11:02:25 2008 From: afilash at gmail.com (abhilash pp) Date: Sun, 7 Sep 2008 20:32:25 +0530 Subject: firefox timestamp Message-ID: <9f9d35df0809070802r7a5673dbre5a5143c4e041f1f@mail.gmail.com> hi all, -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080907/f985d0a8/attachment-0001.html> From toddw at activestate.com Fri Sep 5 12:33:35 2008 From: toddw at activestate.com (Todd Whiteman) Date: Fri, 05 Sep 2008 09:33:35 -0700 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <48BFB534.2080508@egenix.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <b367b494-66ba-4bd0-a724-9bc77fcea97a@b30g2000prf.googlegroups.com> <mailman.466.1220517117.3487.python-list@python.org> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <48BFB534.2080508@egenix.com> Message-ID: <48C15F5F.7040704@activestate.com> M.-A. Lemburg wrote: > A long time ago, there was a Python plugin for Netscape > which allowed you to run Python straight in the browser. Perhaps > it's time to revive such an idea... but then you're still missing > out on the GUI part, since you're still stuck with what the > browser has to offer in terms of widget support. > There is still a plugin (extension) for Mozilla based products, that enables use of Python in products like Firefox: http://pyxpcomext.mozdev.org/ Mark Hammond's Python/Mozilla work has enabled products like Komodo, Miro (Democracy) and the OLPC project to use Python as a major driver for consistent cross-platform GUI applications. Personally, I believe XULRunner has a lot to offer for Python GUI development, I'm currently finishing up some documentation steps to show off how to use it specifically for Python (I'll post it to this list when it's finished). Cheers, Todd From bdesth.quelquechose at free.quelquepart.fr Mon Sep 1 14:12:52 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 20:12:52 +0200 Subject: Getting an objetcs dict? In-Reply-To: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> References: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> Message-ID: <48bc4c94$0$1011$426a34cc@news.free.fr> ssecorp a ?crit : > I did nce (I think). > class X > > X.__dict__() and ngot a dict of its variables. > Now i get errors doing this. what am i doing wrong? cf Wojtek's answer. From ggpolo at gmail.com Sat Sep 20 14:34:57 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 20 Sep 2008 15:34:57 -0300 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> Message-ID: <ac2200130809201134t68123634s57c5f21b5bf08fe8@mail.gmail.com> On Sat, Sep 20, 2008 at 1:27 PM, Mensanator <mensanator at aol.com> wrote: > Beacuse in 2.6, Python apparently has fixed a discrepency that existed > in previous versions. > > In the IDLE that comes with 2.5, typing "as", to wit "import random as > ran", > the words "import" and "as" highlight in red, so you can't use them as > variable > names or you'll get a syntax error. > > Ah, but you CAN use "as" for a variable: "for as in xrange(10): print > as" > works just fine, although it shouldn't. > > Python 2.6 fixes this discrepency and now gives you a syntax error if > you > use "as" for a variable name. You should have noticed the warning you received in python 2.5 when using "as" as a name. > > The upshot is code (such as sympy) written prior to 2.6 can crash now > due > to this fix if said code inadverntently used what should have been a > reserved > word. > > I was able to fix the code for this "as" problem, but not the one that > came after. I've reported this and interested parties can visit the > sympy > page and check Issue 1115. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From bmihelac at gmail.com Sun Sep 7 09:07:10 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Sun, 7 Sep 2008 06:07:10 -0700 (PDT) Subject: Python and M2Crypto question Message-ID: <12b278d2-9f78-4fc9-a4f2-7d22c543aeb9@d1g2000hsg.googlegroups.com> Hi all! I am trying to install M2Crypto to work on OSX10.5 apache (mod_python). Error I receive: Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5- macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image found. Did find: /Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg- tmp/M2Crypto/__m2crypto.so: no matching architecture in universal wrapper I guess that have to do something with x64 architecture but I am stucked and not able to find a way and to make this work. M2Crypto lib works good stand alone. Any help appreciated, Bojan From bearophileHUGS at lycos.com Thu Sep 4 15:42:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 4 Sep 2008 12:42:21 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> Message-ID: <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> David C. Ullrich: > At least in mathematics, the sum of the elements of > the empty set _is_ 0, while the maximum element of the > empty set is undefined. What do you think about my idea of adding that 'default' argument to the max()/min() functions? Bye, bearophile From robert.kern at gmail.com Tue Sep 23 17:38:25 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 16:38:25 -0500 Subject: Python is slow? In-Reply-To: <5f2eed90-b49b-4c29-bfd5-cc90c4495b3c@m3g2000hsc.googlegroups.com> References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <d086d0b2-0624-45ee-b72f-49d88a7dfe33@79g2000hsk.googlegroups.com> <c5e8ae40-9ed6-41c9-8914-4a3d0f001f0c@m36g2000hse.googlegroups.com> <mailman.1423.1222197466.3487.python-list@python.org> <c124d367-bf08-42cf-934a-592a723c73ea@e53g2000hsa.googlegroups.com> <mailman.1426.1222200991.3487.python-list@python.org> <5f2eed90-b49b-4c29-bfd5-cc90c4495b3c@m3g2000hsc.googlegroups.com> Message-ID: <gbbnki$1dd$1@ger.gmane.org> sturlamolden wrote: > On Sep 23, 10:16 pm, Robert Kern <robert.k... at gmail.com> wrote: > >> What's confusing? You do have to create a profile: > > How do I add a new page to the wiki? I'm only able to edit the front > page of the cookbook. But it doesn't help to add link there if I have > no page to link. (I may be incredibly stupid though.) You just navigate to the URL you want: http://www.scipy.org/Cookbook/KDTree This will show you a page saying: """ This page does not exist yet. You can create a new empty page, or use one of the page templates. Before creating the page, please check if a similar page already exists. Create new empty page """ The latter is a link that you can click. Looking at the other Cookbook page sources, I notice that you should add the following to the bottom of your page to categorize it appropriately. """ ---- . CategoryCookbook """ Then put the link on the main Cookbook page (or do that first, then navigate through the link to create the page). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ldo at geek-central.gen.new_zealand Wed Sep 24 06:36:44 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:36:44 +1200 Subject: Program works great, except under less, cron or execl (Unicode?) References: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> <6jekbbF2v55pU2@mid.uni-berlin.de> <c89b7723-50c4-432f-a1e8-7f62f1232ece@v16g2000prc.googlegroups.com> Message-ID: <gbd57s$nj$1@lust.ihug.co.nz> In message <c89b7723-50c4-432f-a1e8-7f62f1232ece at v16g2000prc.googlegroups.com>, Sam wrote: > So how can I set sys.stdout.encoding so it's UTF-8 when piped through > cat (or anything else). > > I tried assigning to it, but no dice. You could try wrapping it in a file object that does explicit encoding translation, using codecs.EncodedFile <http://docs.python.org/lib/module-codecs.html>. From dr.addn at gmail.com Sun Sep 28 20:18:24 2008 From: dr.addn at gmail.com (Ph.T) Date: Sun, 28 Sep 2008 17:18:24 -0700 Subject: Spring Python 0.7.0 is released In-Reply-To: <b9be2727-27f1-411e-abec-d5df178d4801@k37g2000hsf.googlegroups.com> References: <b9be2727-27f1-411e-abec-d5df178d4801@k37g2000hsf.googlegroups.com> Message-ID: <8fd4a2fe0809281718q70f79615l6382249cc124a65d@mail.gmail.com> the spring framework comes to python? http://forum.springframework.org/ http://springpython.webfactional.com/ http://sourceforge.net/projects/springpython/ http://en.wikipedia.org/wiki/Spring_Python On Thu, Sep 25, 2008 at 4:21 AM, Goldfish <gregturn at mindspring.com> wrote: > Release 0.7.0 was completed last night, and released to > sourceforge.net. > > NOTE: This release included a lot of API scrubbing, in order to bring > things more in tune with PEP-0008 (python's style guide). You're > existing apps PROBABLY were impacted, if you used any of Spring > Python's utility classes. Since we are pre-1.0, this is the best time > for such a cleanup. When 1.0 hits the streets, we won't make such a > sweeping change without extensive backwards support. > > See [url]http://springpython.webfactional.com[/url] for more > information. > > Visit our community forum at [url]http://forum.springframework.org/ > forumdisplay.php?f=45[/url]<http://forum.springframework.org/forumdisplay.php?f=45%5B/url%5D>for current threads of discussion. > > --Greg Turnquist, Spring Python project lead > ========================================= > Release Notes - Spring Python - Version 0.7 > > > ** Bug > * [SESPRINGPYTHONPY-63] - Running setup.py returns an exception > > ** Improvement > * [SESPRINGPYTHONPY-49] - Upgrade PetClinic to CherryPy 3.1 > * [SESPRINGPYTHONPY-64] - Adding a schema for the regular > component elements > * [SESPRINGPYTHONPY-69] - Remove deprecated connection factories > from baseline > * [SESPRINGPYTHONPY-70] - Scrub function/attribute naming > conventions to more closely follow PEP-0008. > > ** New Feature > * [SESPRINGPYTHONPY-61] - Generate reference documentation for the > project > > ** Refactoring > * [SESPRINGPYTHONPY-65] - Change 'type' attribute in XML > application config to 'scope' to be in line with the lifetime concept > in other Spring platforms > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Americium Dream Documents "(real opportunity starts with real documentation) http://amerdreamdocs.tripod.com/ http://www.angelfire.com/psy/dr.addn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080928/31401220/attachment-0001.html> From timr at probo.com Fri Sep 19 01:24:09 2008 From: timr at probo.com (Tim Roberts) Date: Fri, 19 Sep 2008 05:24:09 GMT Subject: curses.setsyx()? References: <f4bfa060-3053-4ca6-90c2-2a057bfedf79@34g2000hsh.googlegroups.com> Message-ID: <tqd6d4po3dmvba3a3v1a8c2b34qgfmc8d9@4ax.com> linkmaster032000 at gmail.com wrote: > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses >cursor. Any alternatives/solutions? Did you call doupdate after? setsyx just manipulates the data structures. It takes a call to doupdate to force those changes to take effect visually. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From prologic at shortcircuit.net.au Sun Sep 7 17:40:34 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 07:40:34 +1000 Subject: problem with permutations In-Reply-To: <fb82c6bc-e22f-4502-9d6a-4616ce53517c@59g2000hsb.googlegroups.com> References: <fb82c6bc-e22f-4502-9d6a-4616ce53517c@59g2000hsb.googlegroups.com> Message-ID: <e1a84d570809071440k71972bf9g60cbfc257484070@mail.gmail.com> Hi, Here's a (better?) function: def permutate(seq): if not seq: return [seq] else: temp = [] for k in range(len(seq)): part = seq[:k] + seq[k+1:] for m in permutate(part): temp.append(seq[k:k+1] + m) return temp cheers James On Mon, Sep 8, 2008 at 6:47 AM, cnb <circularfunc at yahoo.se> wrote: > I am trying to translate this elegant Erlang-code for finding all the > permutations of a list. > I think it is the same function as is but it doesn't work in Python. > -- is upd in Python. It works as it should. > > perms([]) -> [[]]; > perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. > > def perms(lista): > if lista == []: > return [[]] > else: > for h in lista: > return [([h]+[t]) for t in perms(upd(lista, h))] > > def upd(lista, elem, acc=tuple([])): > lista = tuple(lista) > if lista == (): > return list(acc) > if lista[0] == elem: > return list(acc + tuple(lista[1:])) > else: > return upd(lista[1:], elem, acc + tuple([lista[0]])) > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bearophileHUGS at lycos.com Thu Sep 4 16:43:43 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 4 Sep 2008 13:43:43 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> Message-ID: <240454f2-14ee-496a-9078-1abbf80a4e64@m45g2000hsb.googlegroups.com> castironpi: > For max and min, why can't you just add your argument to the set > itself? Sometimes that can be done, but in many other situations it's less easy, like in the example I have shown in my first post: max((fun(x) for x in iterable if predicate(x))) There are some ways to add the max there, for example using an itertools.chain to chan the default value to the end of the iterable, but most of the time I just write a for loop. Bye, bearophile From uzmanajmal at gmail.com Thu Sep 11 03:08:37 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Thu, 11 Sep 2008 07:08:37 +0000 Subject: XML RPC Problem.... Message-ID: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> Hi everyone, I am trying to call a function named system.auth at the server side running at localhost:8080 but at the same time i want to set the http header. I found that header can be set by h.putheader("AUTHORIZATION", "Basic %s"%encodestring("%s:%s" % (ustring,text_ucert))) #ustring: just a random string #text_ucert: a file containing the X509 certificate of client And i also fount that a typical system.auth call will look like: POST /xmlrpc/clarens_server.py HTTP/1.0 Host: localhost User-Agent: xmlrpclib.py/0.9.9 (by www.pythonware.com) Content-Type: text/xml Content-Length: 105 AUTHORIZATION: Basic MkhVTm9VazYxbXArVEZLS0dCY2tIRlA3bjVzPQo6RnJvbSBi <?xml version='1.0'?> <methodCall> <methodName>system.auth</methodName> <params> </params> </methodCall> Problem is that i don't know how do i generate above xml system.auth call. Can anyone please tell me how do call a function, setting the header of the call too? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080911/26a628ba/attachment-0001.html> From henrypopie at gmail.com Tue Sep 23 11:56:39 2008 From: henrypopie at gmail.com (henrypopie at gmail.com) Date: Tue, 23 Sep 2008 08:56:39 -0700 (PDT) Subject: download redtube video - Free References: <ce91d9a2-a6f2-4e8e-8d23-716fb6cb053a@26g2000hsk.googlegroups.com> Message-ID: <f766bbe3-db31-4bcd-9597-6d54b75b501b@k36g2000pri.googlegroups.com> Hello, You can download Redtube videos to your Computer, iPod, PSP or other mobile devices.. Just get a RedTube Downloader from here: -------------------- http://www.downloadvideos-convert.com/redtube-downloader ----------- Enjoy it~ Download Videos from RedTube, YouPorn, PornoTube, XTube, Tube8, Xnxx.com easily, also help you convert videos to any format you want, so you can put RedTube videos on your iPod, PSP or other mobile devices. From movics.org at gmail.com Sun Sep 28 13:32:36 2008 From: movics.org at gmail.com (movics.org) Date: Sun, 28 Sep 2008 10:32:36 -0700 (PDT) Subject: Watch Movies online ! Message-ID: <57e5a1d0-9e3d-47ed-9e61-0fa34672a709@25g2000hsx.googlegroups.com> Hello, I just found a new website : http://www.movics.org Here we can watch any movie for freee...it's a 500 + movies database ...we just have to click on movie we want and we can see it right in our browser. no download is needed ! Good luck :D Your friend TonY! From goldnery at gmail.com Mon Sep 1 17:47:38 2008 From: goldnery at gmail.com (Gandalf) Date: Mon, 1 Sep 2008 14:47:38 -0700 (PDT) Subject: encoding Message-ID: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> if i want to print utf-8 string i should writre: print u"hello word" but what happen if i want to print variable? thank you From john.ford at colorado.edu Thu Sep 25 00:38:36 2008 From: john.ford at colorado.edu (john.ford at colorado.edu) Date: Wed, 24 Sep 2008 21:38:36 -0700 (PDT) Subject: How to parse a string completely into a list References: <e9e4f5c7-3467-4078-a401-fb732d69cc64@a3g2000prm.googlegroups.com> <mailman.1479.1222314277.3487.python-list@python.org> <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <mailman.1480.1222315955.3487.python-list@python.org> Message-ID: <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> On Sep 24, 10:12?pm, Matt Nordhoff <mnordh... at mattnordhoff.com> wrote: > john.f... at colorado.edu wrote: > > On Sep 24, 9:44 pm, "Chris Rebert" <c... at rebertia.com> wrote: > >> On Wed, Sep 24, 2008 at 8:30 PM, ?<john.f... at colorado.edu> wrote: > >>> I want to take a long alpha-numeric string with \n and white-space and > >>> place ALL elements of the string (even individual parts of a long > >>> white-space) into separate list elements. The most common way I've > >>> seen this performed is with the split() function, however I don't > >>> believe that it has the power to do what I am looking for. > >>> Any suggestions? > >>> thanks > >> Could you please define exactly what you mean by "elements" of a string? > > >> If you mean characters, then just use list():>>> list(" ?\n \t abc") > > >> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] > > >> Regards, > >> Chris > > > Worked like a charm. > > kudos! > > Why do you need to convert it to a list? Strings are sequences, so you > can do things like slice them or iterate through them by character: > > >>> for character in "foo": > > ... ? ? print character > ... > f > o > o > > -- The string draws a map that I then want to be able to traverse through. If I can count through the individual characters of a list I can create an x-y coordinate plane for navigation. From lists at cheimes.de Mon Sep 1 15:41:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 01 Sep 2008 21:41:09 +0200 Subject: Py 2.6 changes In-Reply-To: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> Message-ID: <g9hggk$tum$1@ger.gmane.org> bearophileHUGS at lycos.com wrote: > I presume it's better for me to not hold my breath while I wait > CPython to be written in C99 :-) First you have to convince Microsoft to release C99 compiler ... good luck! Christian From bignose+hates-spam at benfinney.id.au Tue Sep 30 05:04:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 Sep 2008 19:04:41 +1000 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> Message-ID: <87zllqqa1i.fsf@benfinney.id.au> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes: > On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: > > > In message <gbr4ks$1vv$1 at aioe.org>, r0g wrote: > > > >> You can only distribute modifications to gnuplot itself as > >> patches, but you can distribute it freely ... [?] > Where's the non-free bit? You're not free to modify gnuplot and redistribute the result. That you're free to distribute patches is nice, but it's not enough to make the work free. The freedom to help people by giving them an *already-modified* gnuplot is restricted by the copyright holder. It's an artificial restriction on redistribution of derived works, making them second-class for the prupose of getting them into people's hands. > Personally, I don't get the whole "only distribute patches" > requirement. It's a bit like saying "You're free to distribute this > software, but only as a tarball". It seems silly to me. That, too, would be a non-free requirement. > But I don't see it as non-free, except in the sense that "only > licences approved by the FSF are free". I try to judge freedom of a software work by the freedoms granted to all recipients of the work, not by the approval of some organisation. -- \ ?When I turned two I was really anxious, because I'd doubled my | `\ age in a year. I thought, if this keeps up, by the time I'm six | _o__) I'll be ninety.? ?Steven Wright | Ben Finney From marek at xivilization.net Wed Sep 3 10:08:50 2008 From: marek at xivilization.net (Marek Kubica) Date: Wed, 3 Sep 2008 14:08:50 +0000 (UTC) Subject: pyparsing: match empty line References: <g9jq5i$ou8$1@hoshi.visyn.net> <9f838a29-2e2e-4646-9026-36d3b8a49fce@c58g2000hsc.googlegroups.com> <g9ll81$5kl$1@hoshi.visyn.net> <0df1f752-ee27-4eeb-ab63-1566ed9a3e24@k37g2000hsf.googlegroups.com> Message-ID: <g9m5pi$9od$1@hoshi.visyn.net> On Wed, 03 Sep 2008 06:12:47 -0700, Paul McGuire wrote: > On Sep 3, 4:26 am, Marek Kubica <ma... at xivilization.net> wrote: >> I could set the whitespace >> on every element, but that is as you surely agree quite ugly. Do you >> accept patches? I'm thinking about some kind of factory-class which >> would automatically set the whitespaces: >> >> >>> factory = TokenFactory(' \t\r') >> >>> word = Factory.Word(alphas) >> >> That way, one wouldn't need to set a grobal value which might interfere >> with other pyparsers running in the same process. > > I tried to prototype up your TokenFactory class, but once I got as far > as implementing __getattribute__ to return the corresponding pyparsing > class, I couldn't see how to grab the object generated for that class, > and modify its whitespace values. I have had the same problem, until I remembered that I can fake __init__ using a function closure. I have imported pyparsing.py into a hg repository with a patchstack, here is my first patch: diff -r 12e2bbff259e pyparsing.py --- a/pyparsing.py Wed Sep 03 09:40:09 2008 +0000 +++ b/pyparsing.py Wed Sep 03 14:08:15 2008 +0000 @@ -1400,9 +1400,38 @@ def __req__(self,other): return self == other +class TokenFinder(type): + """Collects all classes that are derived from Token""" + token_classes = dict() + def __init__(cls, name, bases, dict): + # save the class + TokenFinder.token_classes[cls.__name__] = cls + +class WhitespaceTokenFactory(object): + def __init__(self, whitespace): + self._whitespace = whitespace + + def __getattr__(self, name): + """Get an attribute of this class""" + # check whether there is such a Token + if name in TokenFinder.token_classes: + token = TokenFinder.token_classes[name] + # construct a closure which fakes the constructor + def _callable(*args, **kwargs): + obj = token(*args, **kwargs) + # set the whitespace on the token + obj.setWhitespaceChars(self._whitespace) + return obj + # return the function which returns an instance of the Token + return _callable + else: + raise AttributeError("'%s' object has no attribute '%s'" % ( + WhitespaceTokenFactory.__name__, name)) class Token(ParserElement): """Abstract ParserElement subclass, for defining atomic matching patterns.""" + __metaclass__ = TokenFinder + def __init__( self ): I used metaclasses for getting all Token-subclasses so new classes that are created are automatically accessible via the factory, without any additional registration. Oh and yes, more patches will follow. I'm currently editing the second patch, but I better mail it directly to you as it is not really interesting for this list. regards, Marek From kaerbuhez at gmail.com Sun Sep 7 07:16:24 2008 From: kaerbuhez at gmail.com (kaer) Date: Sun, 7 Sep 2008 04:16:24 -0700 (PDT) Subject: unexpected class behaviour References: <48c3ad5d@news.uni-ulm.de> <mailman.647.1220784028.3487.python-list@python.org> Message-ID: <d194a5f2-2a7e-4f5c-aed0-39028a4fa5d9@m45g2000hsb.googlegroups.com> On 7 sep, 12:40, Fredrik Lundh <fred... at pythonware.com> wrote: > Jan Sch?fer wrote: > > can anyone explain the behaviour of the following code sniplet: > > well, it *is* explained in the tutorial, the language reference, and the > FAQ, so yes, it can be explained ;-) > > for more information, see this page: > > http://effbot.org/zone/default-values.htm > > </F> Well, you may want replace the last line by: print ivar, obj, obj.varlist, id(obj.varlist) To have another behavior, you may want replace the 3 first lines by: class Base(object): def __init__( self, lst=None ): if lst is None: lst=[] self.varlist = lst Enjoy Python ! From C.Brewster at dcs.shef.ac.uk Sat Sep 27 10:24:38 2008 From: C.Brewster at dcs.shef.ac.uk (Christopher Brewster) Date: Sat, 27 Sep 2008 15:24:38 +0100 Subject: EPD (Enthought Python Distribution) 4.0.300 Beta 3 available In-Reply-To: <48DDCDDA.50009@enthought.com> References: <48DDCDDA.50009@enthought.com> Message-ID: <975844EF-46F5-439E-8481-544A91EF7A98@dcs.shef.ac.uk> I have always thought this idea very good, but if I download it and install it (on my MacBook pro) will any conflicts occur with existing bits and pieces of Python and its libraries? Thank you, Christopher Brewster ***************************************************** Department of Computer Science, University of Sheffield Regent Court, 211 Portobello Street Sheffield S1 4DP UNITED KINGDOM Web: http://www.dcs.shef.ac.uk/~kiffer/ Tel: +44(0)114-22.21967 Fax: +44 (0)114-22.21810 Skype: christopherbrewster SkypeIn (UK): +44 (20) 8144 0088 SkypeIn (US): +1 (617) 381-4281 ***************************************************** Corruptissima re publica plurimae leges. Tacitus. Annals 3.27 On 27 Sep 2008, at 07:08, Dave Peterson wrote: Hello, We've recently posted the third beta release of EPD (the Enthought Python Distribution) with Python 2.5 version 4.0.300. You may download the beta from here: http://www.enthought.com/products/epdbeta.php Please help us test it out and provide feedback on the EPD Trac instance: https://svn.enthought.com/epd You can check out the release notes here: http://www.enthought.com/products/epdbetareleasenotes.php About EPD --------- The Enthought Python Distribution (EPD) is a "kitchen-sink-included" distribution of the Python? Programming Language, including over 60 additional tools and libraries. The EPD bundle includes NumPy, SciPy, IPython, 2D and 3D visualization, database adapters, and a lot of other tools right out of the box. http://www.enthought.com/products/epd.php It is currently available as a single-click installer for Windows XP (x86), Mac OS X (a universal binary for OS X 10.4 and above), and RedHat 3 and 4 (x86 and amd64). EPD is free for academic use. An annual subscription and installation support are available for individual commercial use. An enterprise subscription with support for particular deployment environments is also available for commercial purchase. The beta versions of EPD are available for indefinite free trial. -- Dave -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html From fredrik at pythonware.com Mon Sep 8 01:07:02 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 07:07:02 +0200 Subject: Subprocess freezes when piping from stdout. In-Reply-To: <62ab6734-a6ab-40c0-9131-a90684674ea6@a18g2000pra.googlegroups.com> References: <62ab6734-a6ab-40c0-9131-a90684674ea6@a18g2000pra.googlegroups.com> Message-ID: <ga2bu1$npd$1@ger.gmane.org> James McGill wrote: > Is anyone aware of why this might be occurring, or of any ways around > this? Does the PIPE implementation in Win32 have a maximum buffer > size? pipes always have a limited buffer size, on all platforms. you're supposed to read data from them as it arrives (e.g. by explicitly reading from the "stdout" attribute, or by calling "communicate"). if you cannot do that, bind the channel to a file, not a pipe. </F> From dudeja.rajat at gmail.com Sat Sep 6 09:58:06 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 6 Sep 2008 14:58:06 +0100 Subject: How to bring subprocess to the foreground? Message-ID: <e0b6c39a0809060658s33234a27k1d822da108e06b5a@mail.gmail.com> Hi, I've a batch file that I open with the subprocess .Popen() . When this batch file is run I want to bring it to the foreground. Please suggest how can I do this? Regards, Rajat From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 06:23:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 12:23:09 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> Message-ID: <48d7720d$0$12866$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: > >> Steven D'Aprano a ?crit : >>> I have a class which is not intended to be instantiated. Instead of >>> using the class to creating an instance and then operate on it, I use >>> the class directly, with classmethods. Essentially, the class is used >>> as a function that keeps state from one call to the next. >>> >>> The problem is that I don't know what to call such a thing! "Abstract >>> class" isn't right, because that implies that you should subclass the >>> class and then instantiate the subclasses. >>> >>> What do you call such a class? >>> >>> >> <nitpick> >> Err... A possible design smell ?-) >> </nitpick> >> >> >> More seriously: this looks quite like a singleton, which in Python is >> usually implemented way more simply using a module and plain functions. > > > I really don't know why everyone thinks I want a Singleton. May I quote you ? """ Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. """ > I want to > uncouple objects, not increase the coupling. > > > Consider a factory function: > > def factory(x): # a toy example > alist = [x] > def foo(): > return alist > return foo > > > Now suppose we "instantiate" the factory (for lack of a better term): > >>>> f1 = factory(0) >>>> f2 = factory(0) > > Even though f1 and f2 have the same behaviour, they are obviously not the > same object. And although both return a list [0], it is not the same list: > >>>> f1() == f2() == [0] > True >>>> f1() is f2() > False > > > They have a (very little) amount of state, which is *not* shared: > >>>> L = f1() >>>> L.append(1) >>>> f1() > [0, 1] >>>> f2() > [0] > > > But there's only a limited amount of state that functions carry around. I > can give them more state like this: > >>>> f1.attr = 'x' > > but it isn't good enough if the function needs to refer to it's own > state, because functions can only refer to themselves by name and the > factory can't know what name the function will be bound to. Then define your own callable type. > As far as I know, the only objects that know how to refer to themselves > no matter what name they have are classes and instances. And instances > share at least some state, by virtue of having the same class. Is that a problem in your use case, and if so, why ??? > (Pedants will argue that classes also share state, by virtue of having > the same metaclass. Maybe so, but that's at a deep enough level that I > don't care.) > > I'm now leaning towards just having factory() instantiate the class and > return the instance, instead of having to do metaclass chicanery. Because > the class is built anew each time by the factory, two such instances > aren't actually sharing the same class. I think that will reduce > confusion all round (including mine!). > > Hopefully now that I've explained what I want in more detail, it won't > seem so bizarre. Factory functions do it all the time. Is there a name > for this pattern? > > Thanks to everyone who commented, your comments helped me reason out a > better alternative to what I first suggested. > Glad to know you found something helpful in all these answers, but as far as I'm concerned, I'm afraid I still fail to understand what exactly you're after... From harrrrpo at gmail.com Sat Sep 6 08:04:27 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Sat, 6 Sep 2008 15:04:27 +0300 Subject: Cancel instance create In-Reply-To: <g9tog9$goe$1@ger.gmane.org> References: <1220697080.48c25bf890ade@www.inbox.lv> <g9tog9$goe$1@ger.gmane.org> Message-ID: <538050a90809060504x3b82d402hefbc152c1812d685@mail.gmail.com> ?What about no Constructor , and a custom instancing function that can return either None or the instance wanted From grante at visi.com Wed Sep 10 13:37:28 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 12:37:28 -0500 Subject: md5 differences References: <mailman.799.1221063937.3487.python-list@python.org> <ga8sn6$g69$1@south.jnrs.ja.net> <mailman.806.1221066763.3487.python-list@python.org> Message-ID: <t8GdnSFxY7BFmFXVnZ2dnUVZ_jKdnZ2d@posted.visi> On 2008-09-10, Python <python at rgbaz.eu> wrote: > > On 10 sep 2008, at 18:30, Richard Brodie wrote: > >> >> "Python" <python at rgbaz.eu> wrote in message >> news:mailman.799.1221063937.3487.python-list at python.org... >> >>> here's an example: >>> Arno at Computer:~% echo "hello" | md5 >>> b1946ac92492d2347c6235b4d2611184 >>> How do I get the same results? >> >> Checksum the same string. >> >>>>> md5.new("hello\n").hexdigest() >> 'b1946ac92492d2347c6235b4d2611184' >> >> > > hmm and this then: > > Arno at Computer:~% echo "test" > test.txt > > Arno at Computer:~% md5 test.txt > MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 > > Arno at Computer:~% python > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import md5 > >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() > '90364ed45b452d43378629c20543a81d' That's the digest of the string "/Volumes/data/Arno/test.txt". It's not supposed to match the digest of the string "test\n". >>> md5.new(open("test.txt").read()).hexdigest() 'd8e8fca2dc0f896fd7cb4cb0031ba249' $ md5sum test.txt d8e8fca2dc0f896fd7cb4cb0031ba249 test.txt $ echo "test" | md5sum d8e8fca2dc0f896fd7cb4cb0031ba249 - >>> md5.new("test\n").hexdigest() 'd8e8fca2dc0f896fd7cb4cb0031ba249' > even > echo -n "hello" | md5 > doesn't return the same number Not the same as _what_? >>> md5.new("test").hexdigest() '098f6bcd4621d373cade4e832627b4f6' $ echo -n test | md5sum 098f6bcd4621d373cade4e832627b4f6 - -- Grant Edwards grante Yow! One FISHWICH coming at up!! visi.com From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 12:54:37 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 18:54:37 +0200 Subject: Python newbie question re Strings and integers In-Reply-To: <c0287f45-1c5a-40b5-aff3-ab5639d26749@k13g2000hse.googlegroups.com> References: <c0287f45-1c5a-40b5-aff3-ab5639d26749@k13g2000hse.googlegroups.com> Message-ID: <48d546ba$0$17467$426a34cc@news.free.fr> rmac a ?crit : > > the following code attempts to extract a symbol name from a string: > extensionStart = int(filename.rfind('.')) rfind returns an int, so passing it to the int type constructor is useless. > filenameStart = int(filename.rfind('/')) idem > #print 'Extension Start - ' + str(extensionStart) The print statement isn't restricted to string objects. And FWIW, you can use string formating. The above should be either print "Extension start - ", extensionStart or print "Extension start - %s" % extensionStart As a side not, the naming convention in Python is to use all_lower for identifiers. > #print 'FileName Start - ' + str(filenameStart) idem. > currentSymbol=filename[int(filenameStart),int(extensionStart)] Two more useless int constructor calls. > Uncommenting the print statements clearly show the values to be > integers If by 'the values', you mean objects bound to identifiers 'filenameStart' and 'extensionStart', I fail to see how they could be anything else... > (and without the str casts actually provide int+string > errors) Indeed. What should be the semantic of expression 'answer is ' + 42 ??? > However, executing this code results in... > opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv > Traceback (most recent call last): > File "rHistFileToDB_Equities.py", line 25, in <module> > currentSymbol=filename[int(filenameStart),int(extensionStart)] > TypeError: string indices must be integers the expression: int(filenameStart),int(extensionStart) 1/ takes the object currently bound to identifier 'filenameStart' and pass it to the int type constructor 2/ takes the object currently bound to identifier 'extensionStart' and pass it to the int type constructor 3/ build a tuple (actually, a pair of ints) from the results of the two above expressions Then you try to use this tuple as an index on a string. A tuple is not a legal type for string (or any other sequence) subscripting. The complete syntax for string subscripting is described in the FineManual. To make a long story short, it's : string[start:end:step] where end and step are optionals. IOW, the correct syntax here is: filename[filenameStart:extensionStart] Now, while this is the correct *syntax*, it's not the correct *idiom*. There's a module named os.path, which provides the needed service. I leave it up to you to read the relevant part of the documentation... From arvi.blog at gmail.com Mon Sep 8 04:04:44 2008 From: arvi.blog at gmail.com (arvi.blog at gmail.com) Date: Mon, 8 Sep 2008 01:04:44 -0700 (PDT) Subject: Hey guys! Message-ID: <73f8539c-5018-4a43-8b1c-3af21f13afaa@w24g2000prd.googlegroups.com> hey guys! I have this site www.drachensee.info and i keep posting on the ubuntu, the latest open soruce buzz.. i post on stuff like editing the grub menu and other linux related stuff.. so drop in and drop ur comments ;-] From ceball at users.sourceforge.net Thu Sep 11 16:46:57 2008 From: ceball at users.sourceforge.net (Chris) Date: Thu, 11 Sep 2008 20:46:57 +0000 (UTC) Subject: Finding tcltk when building Python on Windows Message-ID: <loom.20080911T202459-847@post.gmane.org> Hi, I'm trying to build Python on Windows using Visual Studio 2005. I have no trouble compiling tcl/tk 8.5, but when I subsequently build Python it doesn't find tcl/tk (I get a message about being unable to find tcl.h). I'm using the source distribution of Python 2.5.2, not the svn version. I'm trying to follow the instructions in PCbuild8/readme.txt, but I'm not sure I understand them correctly. Here is the part of the text that I think I might have misunderstood: """ The following subprojects [including Tkinter] will generally NOT build out of the box. They wrap code Python doesn't control, and you'll need to download the base packages first and unpack them into siblings of PCbuilds's parent directory; for example, if your PCbuild is .......\dist\src\PCbuild\, unpack into new subdirectories of dist\. """ If I have extracted the Python source archive to c:\Python-2.5.2\, then my understanding is that I should extract the tcl and tk source archives to c:\tcl-8.5.4\ and c:\tk-8.5.4\, respectively. Then, when I build and install tcl and tk, their output is c:\tcltk\ (because the instructions say to pass "INSTALLDIR=..\..\tcltk" when building). This is then supposed to be found when I build Python. But tcl/tk isn't found, so I assume I didn't do the right thing here. I feel a bit stupid! I also can't find any explicit instructions for building Python with tcl/tk support using Visual Studio by searching the web. Thanks for any help, Chris From steve at REMOVE-THIS-cybersource.com.au Thu Sep 4 08:27:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 12:27:44 GMT Subject: help in execfile function References: <8a3a0376-7146-44f9-beb6-e1ad7a612ad8@l33g2000pri.googlegroups.com> Message-ID: <00cfcead$0$20302$c3e8da3@news.astraweb.com> On Thu, 04 Sep 2008 05:03:57 -0700, moijes12 wrote: > Hi > > i have 3 python files and i want to execute the files sequentially using > the execfile command.Hence ,i have written the following program > > > fileList = ["a.py","b.py","c.py"] > > for fileName in fileList : > execfile(fileName) > > however,when i try running it,the program keeps calling execfile on a.py > and thus an infinite loop is created.I am running this on Windows XP. Change the line "execfile(fileName)" to "print fileName" and you may discover that the problem isn't with execfile but with your code. Then read about modules and import, and you may discover that there is a better way than execfile. (I wish that eval, exec and execfile were hidden in a module where noobs couldn't trip over them and decide they are the answer to every problem. Sigh.) > Please suggest a sloution whereby i can use execfile to execute all > files in fileList.Please tell me where in my program i may have gone > wrong. Looking into my crystal ball, I'm guessing that file a.py contains a line that says "execfile('a.py')". -- Steven From maric at aristote.info Fri Sep 5 12:37:10 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 18:37:10 +0200 Subject: Retrieving the name of the class calling an instance method In-Reply-To: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> References: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> Message-ID: <200809051837.10926.maric@aristote.info> Le Friday 05 September 2008 17:29:39 mercado mercado, vous avez ?crit?: > In Python, is it possible for an instance method to know the name of the > class which is calling it? For example, in the sample below, I would like > for the someMethod method to print the name of the class calling it ("bar" > in the first case, "again" in the second). Note that "self" for somemethod is just a local variable of the calling function. You cannot retrieve those local variables without playing with the call stack, and this reveal generally a bad design (except for inspection purpose). You have two common solutions here : - the simplest is to pass the instance of bar or again to the foo constructor or as parameter of someMethod, or - attach the foo instance to self in both cases and define a proper __get__ method in foo, this is far more complex and add magic to the foo class, I don't recommand this unless you understand well the descriptor protocol. > > --------------------------------------- > class foo(): > def someMethod(self): > print x > > class bar(): > def __init__(self): > f = foo() > f.someMethod() > > class again(): > def __init__(self): > f = foo() > f.someMethod() > > bar() > again() > --------------------------------------- -- _____________ Maric Michaud From ldo at geek-central.gen.new_zealand Sat Sep 27 00:46:45 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 27 Sep 2008 16:46:45 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d@posted.visi> <gbjmdp$q1e$2@lust.ihug.co.nz> <dZOdnT0NKORdEEDVnZ2dnUVZ_rvinZ2d@posted.usinternet> Message-ID: <gbkdrl$7mq$4@lust.ihug.co.nz> In message <dZOdnT0NKORdEEDVnZ2dnUVZ_rvinZ2d at posted.usinternet>, Grant Edwards wrote: > On 2008-09-26, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> > wrote: >> In message <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d at posted.visi>, Grant Edwards >> wrote: >> >>> Never assume somebody reading the article and attempting to >>> help you can see the subject line. >> >> Why not? > > Because it might not be. It depends on the user's newsreader > and editor settings. So, should I not assume that they can see the content as well, because it might not be visible, depending on the user's newsreader and editor settings? From exarkun at divmod.com Tue Sep 23 09:55:43 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 23 Sep 2008 09:55:43 -0400 Subject: Why no tailcall-optimization? In-Reply-To: <633d90d1-c2e9-45d7-852e-c4f3951656e3@d45g2000hsc.googlegroups.com> Message-ID: <20080923135543.29191.1241898919.divmod.quotient.29959@ohm> On Tue, 23 Sep 2008 06:41:33 -0700 (PDT), sturlamolden <sturlamolden at yahoo.no> wrote: >On Sep 23, 3:13?am, process <circularf... at gmail.com> wrote: > >> Why doesn't Python optimize tailcalls? Are there plans for it? > >Because Python is a dynamic language. While a function is executing, >its name may be bound to another object. It may happen as a side >effect of what the function is doing, or even from another thread. The >compiler has no way of knowing that. That's not the reason. It's not particularly hard to implement TCE for Python. Instead, Guido has repeatedly given the reason as his feeling that recursion is not the most natural way to express most algorithms in Python. Adding TCE to the runtime would encourage people to write (or continue to write) highly recursive algorithms, which would go against what Guido thinks is "Pythonic". Here's a quote from him on the topic: > But I have a problem with tail recursion. It's generally requested by > new converts from the Scheme/Lisp or functional programming world, and > it usually means they haven't figured out yet how to write code > without using recursion for everything yet. IOW I'm doubtful on how > much of a difference it would make for real Python programs (which, > simplifying a bit, tend to use loops instead of recursion). Jean-Paul From bearophileHUGS at lycos.com Fri Sep 5 12:45:37 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 09:45:37 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> Message-ID: <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> Michael Palmer: > why can't it be tuple already? Because if the input list L has tuples and lists, they end having the same hash value: >>> L = [[1,2,3], (1,2,3)] >>> hash(tuple(L[0])), hash(tuple(L[1])) (-378539185, -378539185) But it's a not much common situation, and few hash collision pairs can't damage much, so I agree with you that my assert was useless. This may solve that problem anyway: hash(type(L)) ^ hash(tuple(L)) Generally a good hashing functions uses all the input information. If you use tuple() you ignore part of the input information, that is the type of L. So xor-ing hash(type(L)) you use that information too. > you can discard the tuple, so the memory requirement is transient. Right, but there's lot of GC action, it may slow down the code. So you can start using hash(tuple(L)), but if later the code performance comes out bad, you may try a different version that creates less intermediate garbage. Bye, bearophile From stef.mientki at gmail.com Fri Sep 5 17:33:01 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 05 Sep 2008 23:33:01 +0200 Subject: pdb bug and questions In-Reply-To: <wih1vzy485p.fsf@panix5.panix.com> References: <mailman.505.1220563369.3487.python-list@python.org> <wih63pa4d8y.fsf@panix5.panix.com> <mailman.581.1220645176.3487.python-list@python.org> <wih1vzy485p.fsf@panix5.panix.com> Message-ID: <48C1A58D.9000201@gmail.com> R. Bernstein wrote: >>> Finally, I think rpdb2 is part of the winpdb project on Sourceforge >>> and again has a bug tracker. My sense is that Nir Aides is very good >>> about handling bugs reported in winpdb/rpdb. >>> >>> >> Yes I started with rpdb2, >> and indeed Nir Aides is very helpfull, >> but I think interfaceing rpdb2 is a little too difficult for me, >> >> I didn't notice your name before, but I must say Rocky Bernstein is also very helpfull ;-) thanks !! For now I'm going to implement a simple interface between my program and any debugger, so I can easily change between the different debuggers. And certainly I've still to read some more docs about the debuggers. cheers, Stef From tino at wildenhain.de Fri Sep 26 07:29:10 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 13:29:10 +0200 Subject: Not fully OO ? In-Reply-To: <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> Message-ID: <48DCC786.2040407@wildenhain.de> Hi, Tim Rowe wrote: > 2008/9/23 Craig Allen <callen314 at gmail.com>: > >> So python may turn out to be pure OO ... > The question I usually ask is "Does this language help me get the job > done?" Python often does. That's all that really matters, isn't it? Well then it still depends on the perception of "job done". For example PHP programmers would bet their soul that their language of choice is exactly the right one to "get the job done." :-) You and me would indeed see a different picture on the level of doneness of such jobs ;-) T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/48a14083/attachment-0001.bin> From mcrute at gmail.com Sun Sep 28 21:40:07 2008 From: mcrute at gmail.com (Michael Crute) Date: Sun, 28 Sep 2008 21:40:07 -0400 Subject: Web programming in Python. In-Reply-To: <eb5978f8-e802-48d2-a61f-207c25ac7059@y21g2000hsf.googlegroups.com> References: <eb5978f8-e802-48d2-a61f-207c25ac7059@y21g2000hsf.googlegroups.com> Message-ID: <558b73fb0809281840h26a2fedl65fa7ed5a7dec2a7@mail.gmail.com> On Sun, Sep 28, 2008 at 6:39 PM, Kurda Yon <kurdayon at yahoo.com> wrote: > I am totaly newbie in the Python's web programming. So, I dont even > know the basic conceptions (but I have ideas about php-web- > programming). Does it work in a similar way? First, I have to install > a Python-server? There are a couple of different ways to do web development in python. The easiest if you're familiar with web development in other languages is through CGI. I would recommend reading up on the python cgi module [1] which will walk you through the basics of writing your first cgi program. When you're comfortable with basic cgi you might want to look into a framework like Django or CherryPy. -mike [1] http://docs.python.org/lib/module-cgi.html -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From deets at nospam.web.de Mon Sep 8 03:24:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Sep 2008 09:24:48 +0200 Subject: Spotlight Searching in Python - Mac OSX In-Reply-To: <09177d14-a692-4e47-9759-51ad52e38500@s1g2000pra.googlegroups.com> References: <09177d14-a692-4e47-9759-51ad52e38500@s1g2000pra.googlegroups.com> Message-ID: <6ik2a1Fr4kgiU2@mid.uni-berlin.de> cjstevens at gmail.com schrieb: > Hi all, I'm having some issues getting a spotlight search to work > similar to the program demonstrated here: > http://pyobjc.sourceforge.net/examples/pyobjc-framework-Cocoa/AppKit/PredicateEditorSample/ > > > Here is my class, complete with the code I am trying to use it with at > the end. > > > import objc, sys, os, osax, time > from Foundation import * > from ScriptingBridge import * > from appscript import * > > > class SystemBridge(NSObject): > """Class to use the scripting bridge to interact with the system""" > _hideapp = objc.ivar(u"hideapp") > _volume = objc.ivar(u"volume") > _filename = objc.ivar(u"filename") > _filetype = objc.ivar(u"filetype") > _auth = objc.ivar(u"auth") > _logout = objc.ivar(u"logout") > query = objc.ivar(u"query") > StdAdditions = osax.ScriptingAddition() > > def init(self): > super(SystemBridge, self).init() > # create and initalize our query > self.query = NSMetadataQuery.alloc().init() > > # setup our Spotlight notifications > nf = NSNotificationCenter.defaultCenter() > nf.addObserver_selector_name_object_(self, > 'queryNotification:', None, self.query) > > > > # XXX: this framework isn't wrapped yet! > > self.query.setSortDescriptors_([NSSortDescriptor.alloc().initWithKey_ascending_('kMDItemDisplayName', > True)]) > self.query.setDelegate_(self) > > > > return self > > def hideApplication_(self, _hideapp): > app(u'System Events').processes[_hideapp].visible.set(False) > > def loadResultsFromQuery_(self, notif): > results = notif.object().results() > > NSLog("search count = %d", len(results)) > > # iterate through the array of results, and match to the > existing stores > for item in results: > nameStr = item.valueForAttribute_('kMDItemDisplayName') > print nameStr > > > def queryNotification_(self, note): > # the NSMetadataQuery will send back a note when updates are > happening. > # By looking at the [note name], we can tell what is happening > if note.name() == > NSMetadataQueryDidStartGatheringNotification: > # the query has just started > NSLog("search: started gathering") > > > elif note.name() == > NSMetadataQueryDidFinishGatheringNotification: > # at this point, the query will be done. You may recieve > an update > # later on. > NSLog("search: finished gathering"); > self.loadResultsFromQuery_(note) > > elif note.name() == > NSMetadataQueryGatheringProgressNotification: > # the query is still gathering results... > NSLog("search: progressing...") > > elif note.name() == NSMetadataQueryDidUpdateNotification: > # an update will happen when Spotlight notices that a file > as > # added, removed, or modified that affected the search > results. > NSLog("search: an update happened.") > > > def spotlightFriendlyPredicate_(self, predicate): > if predicate == NSPredicate.predicateWithValue_(True) or > predicate == NSPredicate.predicateWithValue_(False): > return False > > elif isinstance(predicate, NSCompoundPredicate): > > type = predicate.compoundPredicateType() > cleanSubpredicates = [] > for dirtySubpredicate in predicate.subpredicates(): > cleanSubpredicate = > self.spotlightFriendlyPredicate_( > dirtySubpredicate) > if cleanSubpredicate: > cleanSubpredicates.append(cleanSubpredicate) > > if len(cleanSubpredicates) == 0: > return None > > else: > if len(cleanSubpredicates) == 1 and type != > NSNotPredicateType: > return cleanSubpredicates[0] > > else: > return > NSCompoundPredicate.alloc().initWithType_subpredicates_(type, > cleanSubpredicates) > > else: > return predicate > > def createNewSearchForPredicate_(self, predicate): > > # Format search file type > thePredicate = NSPredicate.predicateWithFormat_( > "(kMDItemContentType = > 'com.apple.iwork.keynote.key')") > tempPredicate = NSPredicate.predicateWithFormat_( > "(kMDItemDisplayName IN[c] 'preso')") > predicate = NSCompoundPredicate.andPredicateWithSubpredicates_( > [thePredicate, tempPredicate]) > > > self.query.setPredicate_(predicate) > self.query.startQuery() > > > def changeVolume_(self, setvolume): > self.StdAdditions.set_volume(output_volume=setvolume) > > def getVolume_(self): > return StdAdditions.get_volume_settings()[k.output_volume] > > > _x = SystemBridge.alloc().init() > > #predicate = u"kMDItemDisplayName IN[c] 'preso'" > #predicate = _x.spotlightFriendlyPredicate_(predicate) > if predicate is not None: > _x.createNewSearchForPredicate_(predicate) > > > > > As you can see, I am trying to use a notifier just like the example > linked above. The class does not work as expected, and just displays > "search: started gathering", none of the other notifier events happen > at all! > > Have I missed something out translating this to PyObjC? The weird > thing is, most of that code is straight from the example which works > fine, so I can't figure out why mine won't work! Any help would be > hugely appreciated, I need to get this finished soon! I can only imagine that you need an event-loop to make notifications work. That's usually needed under OS X. Diez From fredrik at pythonware.com Wed Sep 10 08:48:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 14:48:08 +0200 Subject: Web shopping carts In-Reply-To: <C4EDF5D9.11364%luke.hamilton@xenter.com.au> References: <48C7B508.6070006@wildenhain.de> <C4EDF5D9.11364%luke.hamilton@xenter.com.au> Message-ID: <ga8fma$und$1@ger.gmane.org> Luke Hamilton wrote: > Do you happen to have anymore details? Google says "Results 1 - 10 of about 869,000 for python shopping cart." http://www.google.com/search?q=python+shopping+cart Checking the first few pages might give you something that fits your requirements (whatever they are). If you don't know what your requirements are, I suggest using something built on top of an established Python web framework, e.g. http://www.satchmoproject.com/ </F> From tino at wildenhain.de Tue Sep 23 12:47:33 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 23 Sep 2008 18:47:33 +0200 Subject: finding domain name In-Reply-To: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> <mailman.1404.1222174222.3487.python-list@python.org> <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> <mailman.1406.1222175467.3487.python-list@python.org> <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> Message-ID: <48D91DA5.2040207@wildenhain.de> Hi, Bobby Roberts wrote: > On Sep 23, 9:10 am, Tino Wildenhain <t... at wildenhain.de> wrote: >> Bobby Roberts wrote: >>>> Depends on the technology/web framework. If you use WSGI, you should use >>>> something like: >>>> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] >>>> -- Gerhard >>> Yeah i already tried environ("SERVER_NAME") but get a key error when i >>> do. >> You could output the whole environ to see what you get and how it is called. ... > evidently the environ dictionary is off limits on our server. It can't > be that tough in python to get the current complete url being viewed. > It's a snap in asp(which is my background). Its a snap in all python based web apps I ever saw. You didn't tell us what you actually using so we can't say. Also there is no notation of "url beeing viewed" in HTTP if you are looking from server's point of view. There is a request for an URI and a host where the request is directed at then then the server decides to publish a resource based on whatever rules. If that publishing results in a call to your python script (or the script itself is the server) then you would deal with whatever interface API you decided to use gives you. Ah and last not least you can even use python in ASP (look for scripting host) but's not a route to take these days :-) (You really want no inline code but a decent templating engine like PageTemplates (TAL)) Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080923/6370c19a/attachment-0001.bin> From Richard_Martineau at xyratex.com Wed Sep 17 06:06:58 2008 From: Richard_Martineau at xyratex.com (Richie) Date: Wed, 17 Sep 2008 03:06:58 -0700 (PDT) Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows References: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> <mailman.1134.1221588238.3487.python-list@python.org> Message-ID: <bf6f476a-1b19-4d4c-af89-3197335a6d4b@l43g2000hsh.googlegroups.com> On Sep 16, 7:03?pm, Terry Reedy <tjre... at udel.edu> wrote: > Richard_Martin... at xyratex.com wrote: > > Now comes the troubled bit...I now look for similar source code for > > Python extensions Numpy and Scipy but the source code and directories > > are not all obvious. Looks like these are normally built via other > > compilers. However I need to do all my builds in VS 6.0. > > Numpy/scipy specific questions tend to get more specific answers on the > numpy/scipy mailing lists. ?Or see gmane.comp.python.numeric.general at > news.gmane.org Thanks very much for your advice Terry. I've just signed up with Numpy discussion and Scipy dev. Just taking a look at gmane now! Richard From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 18:30:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 22:30:07 GMT Subject: Long lines [was Re: __builtins__ magic behavior] References: <d09829f50809071000x5b1cfe89va6ebd07404d7af8f@mail.gmail.com> <mailman.655.1220817038.3487.python-list@python.org> Message-ID: <00d45042$0$20306$c3e8da3@news.astraweb.com> Gabriel, could I please ask you to configure your news-reader software or editor to limit the length of each line of your posts to 70 characters wide, as per the common standard for email and Usenet? Your lines are significantly longer than that, including one single line which is 325 characters wide. That forces a lot of backwards and forwards scrolling to read your posts. Thank you. -- Steven From benjamin at dromaludaire.info Wed Sep 17 06:24:10 2008 From: benjamin at dromaludaire.info (Benjamin Sigonneau) Date: Wed, 17 Sep 2008 12:24:10 +0200 Subject: on-the-fly translation with gettext References: <87od2opg5c.fsf@lapinot.localdomain> <9df975ce-058a-40ef-b440-8f7eb2dbaa11@y21g2000hsf.googlegroups.com> Message-ID: <87vdwv9ik5.fsf@lapinot.localdomain> Mike Driscoll <kyosohma at gmail.com> writes: > On Sep 16, 4:57?am, Benjamin Sigonneau <benja... at dromaludaire.info> > wrote: >> Hi all, >> >> I'm a complete beginner in python and in GUI designing, yet I'm writing >> a GUI using python and Tkinter. ?I need it to be available both in french >> and english, so I read the Fine Manual and gave a try to gettext. >> > [...] >> However, I'd like to let the user show the language on-the-fly during >> execution. ?Having read the Python Library Reference, sec. 21.1.3.3 >> (seehttp://docs.python.org/lib/node740.html), I added a menu with two >> radiobuttons and I merely set them up to call install_lang: > > [...] > >> However, there is no magic. ?The language of the application remains >> unchanged. ?If it was defined to be english at startup, so will it >> remain. ?Conversely, it will stay in french if this was the language at >> startup. > > Try moving another window across your application after you change > languages and see if it gets updated. Sometimes you need to refresh > the layout of your application to get it to work...at least, in > wxPython you do. I tried it, but unfortunately my problem remains. Anyway, thanks for the advice. -- benjamin From castironpi at gmail.com Thu Sep 11 13:31:09 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 10:31:09 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> <pan.2008.09.11.07.40.08@REMOVE.THIS.cybersource.com.au> <mailman.854.1221122089.3487.python-list@python.org> <823435cf-a557-48d9-9e16-fa28e745e67a@73g2000hsx.googlegroups.com> Message-ID: <8f9a61c9-55d7-4a1e-a4f1-9dda6a5d2b31@59g2000hsb.googlegroups.com> On Sep 11, 5:35?am, Paul Boddie <p... at boddie.org.uk> wrote: > On 11 Sep, 10:34, Fredrik Lundh <fred... at pythonware.com> wrote: > > > > > And as I said before, the only use case for *huge* XML files I've ever > > seen used in practice is to store large streams of record-style data; > > I can imagine that the manipulation of the persistent form of large > graph structures might be another use case, although for efficient > navigation of such a structure, which is what you'd need to start > applying various graph algorithms, one would need some kind of index. > Certainly, we're straying into database territory. > > Paul An acquaintance suggests that defragmentation would be a useful service to provide along with memory management too, which also requires an index. I encourage overlap between a bare-bones alloc/free module and established database territory and I'm very aware of it. Databases already support both concurrency and persistence, but don't tell me you'd use a database for IPC. And don't tell me you've never wished you had a reference to a record in a table so that you could make an update just by changing one word of memory at the right place. Sometimes databases are overkill where all you want is dynamic allocation. From aioe.org at technicalbloke.com Wed Sep 24 21:52:38 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 24 Sep 2008 21:52:38 -0400 Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: <gbeqt6$kb2$1@aioe.org> Tim Arnold wrote: > I have a bunch of processes to run and each one needs its own working > directory. I'd also like to know when all of the processes are > finished. > > (1) First thought was threads, until I saw that os.chdir was process- > global. > (2) Next thought was fork, but I don't know how to signal when each > child is > finished. > (3) Current thought is to break the process from a method into a > external > script; call the script in separate threads. This is the only way I > can see > to give each process a separate dir (external process fixes that), and > I can > find out when each process is finished (thread fixes that). > > Am I missing something? Is there a better way? I hate to rewrite this > method > as a script since I've got a lot of object metadata that I'll have to > regenerate with each call of the script. > > thanks for any suggestions, > --Tim Arnold (1) + avoid os.chdir and maintain hard paths to all files/folders? or (2) + sockets? or (2) + polling your systems task list? From circularfunc at yahoo.se Tue Sep 2 12:48:32 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 2 Sep 2008 09:48:32 -0700 (PDT) Subject: Large amount of files to parse/organize, tips on algorithm? Message-ID: <a8ca9f87-4bf8-4a74-b4ee-902ff3d328ab@x35g2000hsb.googlegroups.com> I have a bunch of files consisting of moviereviews. For each file I construct a list of reviews and then for each new file I merge the reviews so that in the end have a list of reviewers and for each reviewer all their reviews. What is the fastest way to do this? 1. Create one file with reviews, open next file an for each review see if the reviewer exists, then add the review else create new reviewer. 2. create all the separate files with reviews then mergesort them? From skip at pobox.com Sat Sep 13 10:01:22 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Sep 2008 09:01:22 -0500 Subject: A service for testing Python code on multiple platforms and versions In-Reply-To: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> References: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> Message-ID: <18635.51122.545364.467763@montanaro-dyndns-org.local> David> As someone who writes and releases Python modules for the community, I David> find it difficult to have a decent level of confidence in the efficacy David> of my code on platforms and Python versions other than those that I David> own or use regularly. My documentation states that I support Python David> 2.3 or higher. This ends up being more of a statement of good David> intentions than a one of fact. How about Buildbot? Here are some Python examples: http://www.python.org/dev/buildbot/ And the Buildbot home page: http://buildbot.net/trac Skip From dear.jay.logan at gmail.com Mon Sep 1 09:45:06 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 1 Sep 2008 06:45:06 -0700 (PDT) Subject: Eleganz way to get rid of \n References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> <g9gre4$li7$1@inews.gazeta.pl> Message-ID: <3713087b-01ed-4d78-8d3d-b3df4e305de6@m44g2000hsc.googlegroups.com> On Sep 1, 9:41?am, Wojtek Walczak <gmin... at bzt.bzt> wrote: > On Mon, 01 Sep 2008 15:25:03 +0200, Hans M?ller wrote: > > I'm quite often using this construct: > > > for l in open("file", "r"): > > ? ?do something > > Has someone a better solution ? > > The most general would be to use rstrip() without > arguments: > > > > >>> a="some string\r\n" > >>> a.rstrip() > 'some string' > > but be careful, because it will also cut whitespaces: > > > > >>> a="some string\t \r\n" > >>> a.rstrip() > 'some string' > > so maybe you could do this: > > > > >>> a.rstrip('\n').rstrip('\r') > 'some string\t ' > > HTH. > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ You can send both '\n' and '\r' in one rstrip call. No need for 2 separate calls. From sturlamolden at yahoo.no Tue Sep 23 14:16:54 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 11:16:54 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: <d086d0b2-0624-45ee-b72f-49d88a7dfe33@79g2000hsk.googlegroups.com> On Sep 23, 5:31?pm, bearophileH... at lycos.com wrote: > Well written C++ code is generally faster or much faster than similar > Python code, but programming in Python is often simpler, and it > generally requires less time. So it may happen that to solve a problem > a Python program that runs in 1 hour that requires 1 hour to be > written allows you to find the solution in less time than a C++ > program that runs in 5-10 minutes that requires you 3-4 hours to be > written :-) I could easily sit down and wait half an hour. I could even wait a week for the calculation to complete. But this is a program that will be used many times, and not just by me. > Note that C++ is just one option, but there are other languages > around, like CLisp or D (or even a modern JavaVM), that are often an > acceptable compromise between Python and C/C++. Yes, if I knew Lisp, I would have used SBCL. Java I can program. But it is a pain in the ass for any scientific programming. F# and OCaml look promising though. > Note that I have written a kd-tree in both Python (with Psyco > compulsively) and D, this is the Psyco version:http://code.activestate.com/recipes/572156/ Sure I could show you the code, Python and C++, if I had a place to post it. It looks very different form yours though. From miki.tebeka at gmail.com Tue Sep 23 04:46:01 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 23 Sep 2008 01:46:01 -0700 (PDT) Subject: Problems running on hp dual core processor References: <mailman.1372.1222108408.3487.python-list@python.org> Message-ID: <352ae1dc-4a4e-4629-89b1-4a4f7d4f5cc2@n33g2000pri.googlegroups.com> Hello, > I have a number of clients running a program built with > python 2.5. ?One has just purchased an HP with a duel > core processor, ?2.2G with .099g ram. > > On the new hp, when they try to print they get an > import error; > File win32ui.pyc line 12, in <module> > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: ?The specified module > could not be found. > > The file is there The only difference I could find from > their other machines is the processor. Is it the same OS (XP vs Vista ...)? Try to run a small script importing win32ui from CMD, it might give you a better indication on which DLL is causing the problem. As suggested by Mike, run DependecyWalker on win32ui.pyd HTH, -- Miki <miki.tebeka at gmail.com> http://pythonwise.blogspot.com From berthold at despammed.com Wed Sep 10 11:11:38 2008 From: berthold at despammed.com (Berthold =?iso-8859-15?Q?H=F6llmann?=) Date: Wed, 10 Sep 2008 17:11:38 +0200 Subject: Refcount problem in ceval.c Message-ID: <sesks89gt1.fsf@pc047299.dhcp.germanlloyd.org> I have a problem with my debug Python 2.5.2 executable with Py_REF_DEBUG and Py_TRACE_REFS set. With one of my scripts I get: ... Fatal Python error: Python/ceval.c:947 object at 0x2aa3f4d840 has negative ref count -2604246222170760230 Program received signal SIGABRT, Aborted. [Switching to Thread 182905044128 (LWP 2595)] 0x0000002a95dde479 in raise () from /lib64/tls/libc.so.6 (gdb) p ((PyObject*)0x2aa3f4d840)->ob_type $1 = (struct _typeobject *) 0xdbdbdbdbdbdbdbdb (gdb) p ((PyObject*)0x2aa3f4d840)->ob_refcnt $2 = -2604246222170760230 (gdb) p ((PyObject*)0x2aa3f4d840)->_ob_next $3 = (struct _object *) 0xdbdbdbdbdbdbdbdb (gdb) p ((PyObject*)0x2aa3f4d840)->_ob_prev $4 = (struct _object *) 0xdbdbdbdbdbdbdbdb (gdb) Is there any "common" reason to for such a strange object on the command stack, or is it more likely that any of my extension modules is causing havoc? Kind regards Berthold -- __ Address: G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg From ptmcg at austin.rr.com Fri Sep 26 00:32:35 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 25 Sep 2008 21:32:35 -0700 (PDT) Subject: text processing References: <mailman.1505.1222361869.3487.python-list@python.org> Message-ID: <a9d4821f-ae39-4fee-80ab-1f3f9cbce1fc@m45g2000hsb.googlegroups.com> On Sep 25, 9:51?am, "jitensha... at gmail.com" <jitensha... at gmail.com> wrote: > I have string like follow > 12560/ABC,12567/BC,123,567,890/JK > > I want above string to group like as follow > (12560,ABC) > (12567,BC) > (123,567,890,JK) > > i try regular expression i am able to get first two not the third one. > can regular expression given data in different groups Looks like each item is: - a list of 1 or more integers, in a comma-delimited list - a slash - a word composed of alpha characters And the whole thing is a list of items in a comma-delimited list Now to implement that in pyparsing: >>> data = "12560/ABC,12567/BC,123,567,890/JK" >>> from pyparsing import Suppress, delimitedList, Word, alphas, nums, Group >>> SLASH = Suppress('/') >>> dataitem = delimitedList(Word(nums)) + SLASH + Word(alphas) >>> dataformat = delimitedList(Group(dataitem)) >>> map(tuple, dataformat.parseString(data)) [('12560', 'ABC'), ('12567', 'BC'), ('123', '567', '890', 'JK')] Wah-lah! (as one of my wife's 1st graders announced in one of his school papers) -- Paul From steven at REMOVE.THIS.cybersource.com.au Thu Sep 11 03:40:08 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Sep 2008 07:40:08 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> Message-ID: <pan.2008.09.11.07.40.08@REMOVE.THIS.cybersource.com.au> On Wed, 10 Sep 2008 11:59:35 -0700, Aaron \"Castironpi\" Brady wrote: > On Sep 10, 5:24?am, Steven D'Aprano > <ste... at REMOVE.THIS.cybersource.com.au> wrote: >> On Wed, 10 Sep 2008 09:26:20 +0200, Fredrik Lundh wrote: >> > Steven D'Aprano wrote: >> >> >> You've created a solution to a problem which (probably) only affects >> >> a very small number of people, at least judging by your use-cases. >> >> Who has a 4GB XML file >> >> > Getting 4GB XML files from, say, logging processes or databases that >> > can render their output as XML is not that uncommon. ?They're usually >> > record-oriented, and are intended to be processed as streams. ?And >> > given the right tools, doing that is no harder than doing the same to >> > a 4GB text file. >> >> Fair enough, that's a good point. >> >> But would you expect random access to a 4GB XML file? If I've >> understood what Castironpi is trying for, his primary use case was for >> people wanting exactly that. >> >> -- >> Steven > > Steven, > > Are you claiming that sequential storage is sufficient for small amounts > of data, and relational db.s are necessary for large amounts? I'm no longer *claiming* anything, I'm *asking* whether random access to a 4GB XML file is something that is credible or useful. It is my understanding that XML is particularly ill-suited to random access once the amount of data is too large to fit in RAM. I'm interested in what Fredrik has to say about this, as he's the author of ElementTree. -- Steven From darcy at druid.net Mon Sep 29 13:31:53 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 29 Sep 2008 13:31:53 -0400 Subject: PYTHON WORKING WITH PERL ?? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> Message-ID: <20080929133153.fc745f9c.darcy@druid.net> On Mon, 29 Sep 2008 13:16:14 -0400 "Blubaugh, David A." <dblubaugh at belcan.com> wrote: > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? Such as > utilizing python for internet programming and then utilize perl for text > processing and systems programming? Is this even feasible??? I don't see why not but I also question if it is a good idea. Once you have all your objects and low level methods written in Python it just makes sense to re-use them rather than trying to duplicate the functionality in another language. Of course, sometimes we don't have control over our entire environment so yes, you can mix them if you have to. -- D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From karentataka at gmail.com Sun Sep 21 00:04:45 2008 From: karentataka at gmail.com (karentataka at gmail.com) Date: Sat, 20 Sep 2008 21:04:45 -0700 (PDT) Subject: Quick & Secured Pharmacy Online. bhsrf Message-ID: <8d7b9685-ad62-456b-8e86-8b7a32abed79@f36g2000hsa.googlegroups.com> Start saving, best online pharmacy here http://gjlabeh.cuchezfarg.com/?cdfikmabehxwvrsygzchcmjl From digitig at gmail.com Mon Sep 22 07:04:50 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 22 Sep 2008 12:04:50 +0100 Subject: What do you call a class not intended to be instantiated In-Reply-To: <48d7720d$0$12866$426a34cc@news.free.fr> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> Message-ID: <aee48b3c0809220404g347b604cl69b30cc710202a51@mail.gmail.com> 2008/9/22 Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid>: > Steven D'Aprano a ?crit : >> >> On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: >> >>> Steven D'Aprano a ?crit : >>>> >>>> I have a class which is not intended to be instantiated. Instead of >>>> using the class to creating an instance and then operate on it, I use >>>> the class directly, with classmethods. Essentially, the class is used >>>> as a function that keeps state from one call to the next. Sounds to me like a functor, aka a function object: http://en.wikipedia.org/wiki/Function_object -- Tim Rowe From tino at wildenhain.de Sat Sep 27 17:30:43 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 27 Sep 2008 23:30:43 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> Message-ID: <48DEA603.9020507@wildenhain.de> Hi, Michael Mabin wrote: > If the inputs are edited prior to the construction of the string and > these fields are used for more than one update then it's not an exploit. > It's simply a matter not repeating yourself when coding. In python we do not fear that. > In this particular case too, we're talking about a list of integers that > gets inserted into a string. If the list is validated prior to its Its a list, if it indeed has integers in it is uncertain. It is so very easy to check that that it doesnt even make sense to write such lengthy emails about how bad you want to avoid it. Just do it. And even more so if you are telling others how to do things make sure they do not so easy shoot themselfes in their feet. > insertion into an SQL statement then there is no exploit. If I write a > batch program (not a web program) that retrieves this list of integers > from other sources and validates the data prior to using it in an SQL > statement, that should be sufficient. This might be well true but if you have a look at your original contribution you see that all these your asumtions are just not in. > As far as wrong and right is concerned. I think it's more about doing > what is appropriate according to the circumstances. As a rule you If its easy to do, why not just doing it correctly (or robust) in all circumstances to just avoid overlooking a case? > should only code what is appropriate for the circumstances. If it's > appropriate to code more simply without introducing unnecessary > complexity you should do so. But you did not tell us about your asumtations about the circumstances. > I work in the data warehousing ETL world, where we have to perform field > edits or transformations to load source data into databases. If I'm Thats wrong. You do not "edit" fields. You have a validating type path and _always_ the database is most authoritative about what it accepts. Any other concept is just wrong and outright dangerous. There are many examples of how this works out (just check bugtraq) > already performing edits on these fields and if these fields are going > to be used for more updates downstream, it's wasteful to perform them > again when I build the SQL insert with the list and execute it. I still don't know what you mean by "edit" ;) If you mean filter out special chars with for example replace("bad stuff","good stuff") check your idea again, this is not going to work. (google for default permit) > Finally, whatever happened to the practice of granting appropriate > privileges to IDs that perform database operations? Shouldn't the > person acting in the capacity of DBA ensure that the user updating or > retrieving data from the database does not have DROP, ALTER, or CREATE > privileges on that database? This of course is another layer which should be added - but you would not need to - you edited the fields, right? ;) Sorry, it was not meant to put you to the wall but you insist so much on your still dangerous solution while top posting the hell out of this thread I just could not ignore it ;) T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080927/baf29de7/attachment-0001.bin> From martin at v.loewis.de Sat Sep 20 09:05:38 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 20 Sep 2008 15:05:38 +0200 Subject: Not fully OO ? In-Reply-To: <mailman.1297.1221911661.3487.python-list@python.org> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <gb2lri$fmd$1@theodyn.ncf.ca> <mailman.1297.1221911661.3487.python-list@python.org> Message-ID: <48D4F522.3080309@v.loewis.de> > for-in could be a useful addition to Python? looks like Guido's used > his time machine again, then, since it's been around since the pre-1.0 > days: > > http://www.python.org/doc/ref/for.html He somehow must have misinterpreted http://www.astro.ufl.edu/~warner/prog/python.html which has the exact text he quoted. Unfortunately, this text has foreach in bold, so he might have assumed foreach to be a keyword (despite the example to the right demonstrating the contrary). What this has to do with OO, or with numpy, is beyond me. Regards, Martin From python.list at tim.thechases.com Sat Sep 13 13:09:56 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 13 Sep 2008 12:09:56 -0500 Subject: Unable to see os.environ['COLUMNS'] Message-ID: <48CBF3E4.8070307@tim.thechases.com> Not sure what's going on here and hoping for some insight: tim at rubbish:~$ echo $COLUMNS 129 tim at rubbish:~$ python2.5 Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ.get('COLUMNS') >>> 'COLUMNS' in os.environ False I can coerce it by using tim at rubbish:~$ COLUMNS=$COLUMNS python2.5 Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> 'COLUMNS' in os.environ True However, this seems hokey to me. FWIW, this is in Bash on Debian. What's the best way to read what seems to be a pseudo-environment variable? -tkc From half.italian at gmail.com Tue Sep 16 03:43:58 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 16 Sep 2008 00:43:58 -0700 (PDT) Subject: The need to use *arg,**kwd References: <f9e39bbc0809151451j15604641gfc1a10832131c24c@mail.gmail.com> <mailman.1090.1221548096.3487.python-list@python.org> Message-ID: <9d602aae-dc90-41b3-8c57-1ffa9619c69c@x16g2000prn.googlegroups.com> On Sep 15, 11:54?pm, "Marco Bizzarri" <marco.bizza... at gmail.com> wrote: > On Mon, Sep 15, 2008 at 11:51 PM, AON LAZIO <aonla... at gmail.com> wrote: > > Hi, Pythoners. > > ? ? ? ?I'd like to know when it is necessary to use *arg or **kwd in the > > program. And when it is 'ok' to use normal form of function argument? > > Thanks in advance. > > > Aonlazio > > Sorry, Aonlazio, but which program? This is a fair generic question > which needs a little more details to be answered. > > You are not required to use them. You can use them if problem can be > easily solved with them. Which, of course leads to the questionof what > your problem is ;) > > Regards > Marco > -- > Marco Bizzarrihttp://notenotturne.blogspot.com/http://iliveinpisa.blogspot.com/ Aonlazio, *args and **kwargs are both a conveneince and for situations where the function could take a variable number of arguments. Take for example a sum function: def sum(first, second): return first + second This function can only take two arguments and return the result of the two. You can add more arguments to the function definition, but if you want to make a generic sum function, it should be able to take as many arguments as your user wants to throw at it. In this case you can use *args. ie. def sum(*args): total =0 for arg in args: total += arg return total **kwargs works the same way, but for keyword arguments. I can't think of a useful example...I tried. :) I'm sure others will have good use cases. ~Sean From steve at REMOVE-THIS-cybersource.com.au Fri Sep 12 08:29:12 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Sep 2008 12:29:12 GMT Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <mailman.878.1221146864.3487.python-list@python.org> Message-ID: <00da5aca$0$2879$c3e8da3@news.astraweb.com> On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote: > When mail messages bounce, the MTA (Message Transfer Agent--the program > that handles mail) *should* send the bounce message to whatever is in > the Sender header, and only if that header does not exist, should it use > the From header. Who makes up these rules, and why should we pay the least bit of attention to them? It's one thing to say "right or wrong, that's what list admins do and you have to deal with their behaviour whatever way you can". It's another thing altogether to take the legalistic attitude of "never mind the consequences, the standard is the standard and must be unthinkingly obeyed". If the standard does more harm than good, then ignoring the standard is the right thing to do. (Better would be to change the standard, but that probably won't happen until there's a critical mass of people who ignore the existing broken standard and form their own de facto standard.) A standard isn't "correct" just because it's a standard, it's merely something that a committee has agreed to do. In other words, it's a compromise. Now, such compromises might be good and useful, or they might combine the worst of all opinions. Just because something is standardized doesn't make it the right thing to do. If you want proof of this, I give you the recently approved ISO standard for Microsoft's so-called "Office Open XML" OOXML file format. The standard behaviour of sending bounce and out-of-office messages to the sender works well when sending email to individuals, but for mailing lists it is pointless and counter-productive. Pointless, because the sender can't do anything to fix the problem he's being notified about. And counter-productive, because it is an anti-feature, something that makes the mailing list more unpleasant and less useful. Anyone who has regularly emailed to a large mailing list has surely experienced the frustration of receiving bounce messages from perfect strangers. To anyone who wishes to defend the process of sending mailing list bounces back the sender, ask yourself this: what do YOU do with such bounces when you receive them? If you ignore them or delete them (whether manually or via a procmail recipe or some other automatic system) then what benefit does the standard behaviour offer? -- Steven From torriem at gmail.com Tue Sep 30 15:53:47 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 30 Sep 2008 13:53:47 -0600 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38053D9A26@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> <gbtpuf$356$1@ger.gmane.org> <27CC3060AF71DA40A5DC85F7D5B70F38053D9A26@AWMAIL04.belcan.com> Message-ID: <48E283CB.6060309@gmail.com> Blubaugh, David A. wrote: > Thank You!! > > I am still new to Python!! > > David Blubaugh As you've already noticed, plenty of folks here on the list are ready help you out with issues the crop up as you learn python. So keep on asking questions as you need assistance. In the future, please avoid using all-capital letters and superfluous exclamation marks in the subject line as this comes across in the parlance of nntp- and mailing- list etiquette as yelling. If you don't get any replies to your posts, please just be patient and the gurus will get to them eventually. I have found this list to be extremely good that way, and almost all my questions have been politely answered, even if it took a few days. I hope you continue to find your python learning experience to be fun and profitable. From circularfunc at gmail.com Wed Sep 10 06:17:30 2008 From: circularfunc at gmail.com (process) Date: Wed, 10 Sep 2008 03:17:30 -0700 (PDT) Subject: which of these 2 quicksorts is faster? Message-ID: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> qsort can handle bigger lists it seems, making less recursive calls before finishing(quicksort blows the stack when sorting range(100,-1000,-1). qsort does more work though right? is there a way to speed up that? is the built-in sort not defined recursively? def quicksort(lista): if len(lista) != 0: return quicksort([x for x in lista[1:] if x < lista[0]]) + [lista[0]] + \ quicksort([x for x in lista[1:] if x >= lista[0]]) else: return [] def qsort(lista): l = len(lista) if len(lista) != 0: return qsort([x for x in lista[:l/2]+lista[l/2+1:] if x < lista[l/2]]) + \ [lista[l/2]] + \ qsort([x for x in lista[:l/2]+lista[l/2+1:] if x >= lista[l/2]]) else: return [] From deets at nospam.web.de Thu Sep 18 05:08:17 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Sep 2008 11:08:17 +0200 Subject: how to do easy_install to source code, not egg? References: <499dc07d-261e-4c34-9743-28b55c7945bd@a70g2000hsh.googlegroups.com> Message-ID: <6jek4aF2v55pU1@mid.uni-berlin.de> dmitrey wrote: > Hi all, > how to do easy_install <some package> to source code, not egg? > > (I don't mean "develop" option, it shouldn't call compiled egg-file). $ easy_install --help <snip/> --editable (-e) Install specified packages in editable form <snip/> You additionally need to give the -b-option, like this: $ easy_install -eb . FooBar Diez From fredrik at pythonware.com Sat Sep 13 04:47:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 10:47:45 +0200 Subject: book example confusion In-Reply-To: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: <gafunk$sh1$2@ger.gmane.org> byron wrote: > Being that each function is an object, a name assignment to > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > the name is called.. the above would be true if the code had been tmp1, tmp2 = f1, f2 but it isn't. look again. </F> From gminick at bzt.bzt Thu Sep 4 14:09:14 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 4 Sep 2008 18:09:14 +0000 (UTC) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> <g9o1bf$dsf$1@news.lysator.liu.se> <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> Message-ID: <g9p888$c85$1@inews.gazeta.pl> On Thu, 4 Sep 2008 10:57:35 -0700 (PDT), Mensanator wrote: > Why then, doesn't > >>>> sum([A for A in [None, None, None, None, None, None] if A != None]) > 0 > > give me an error? Because "[A for A in [None, None, None, None, None, None] if A != None]" returns an empty list, and sum([]) doesn't return an error. What did you expect? -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From http Fri Sep 19 02:10:31 2008 From: http (Paul Rubin) Date: 18 Sep 2008 23:10:31 -0700 Subject: dict generator question References: <mailman.1217.1221749709.3487.python-list@python.org> Message-ID: <7xy71o4qeg.fsf@ruckus.brouhaha.com> "Simon Mullis" <simon at mullis.co.uk> writes: > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > ... > dict_of_counts = dict([(v[0:3], "count") for v in l]) Untested: def major_version(version_string): "convert '1.2.3.2' to '1.2'" return '.'.join(version_string.split('.')[:2]) dict_of_counts = defaultdict(int) for x in l: dict_of_counts[major_version(l)] += 1 From mathieu.prevot at gmail.com Wed Sep 24 12:44:22 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Wed, 24 Sep 2008 18:44:22 +0200 Subject: how to build a MacOS universal python package including external dependencies In-Reply-To: <c5882df30809240915l47ebd8dbj12152c414635979c@mail.gmail.com> References: <c5882df30809240915l47ebd8dbj12152c414635979c@mail.gmail.com> Message-ID: <3e473cc60809240944h1ea69275jc066fc957869d8f2@mail.gmail.com> 2008/9/24 Jaime Huerta Cepas <jhuerta at cipf.es>: > Hi all, > > I have developed a set python libraries that provide several scientific > methods to analyse and visualize certain type of biological data. This > libraries are based on many external python modules, such as python-mysql > python-sip or python-qt4. I use GNU/linux to develop my tools and I found no > problems into installing all dependencies, however it does not seem to be > that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 , > mysqldb, scipy, numpy) are cross platform, but when you are trying to > publish your tool in an academic journal, most referees (many of them using > MacOS) expect some kind of straightforward installation process for the > tool. > > I wonder if there would be a way in which I could compile all the > dependencies and libraries in a MacOs system and then building a static > universal binary that I can distribute. I guess it should be possible, but > I am not sure how difficult it might be, and whether all dependencies (qt4 > is huge) can be packaged together. IMHO this is too complex to commit. Macport is a way to do what you want, but packages may not be up to date enough. Maybe the easiest and simplest way for you to do this is to write a script that will download, compile and install everything. The script should work like: sudo all_in_one_script.py and then wait for jobs to be done. Your script will need to know if a package was sucessfully installed and then continue or take steps and say it. For a complex set of dependencies, I recommend you to write Makefiles. For instance, in pseudo-code: if /usr/local/lib/libfoo.dylib doesn't exist download foo install foo if python-module foo doesn't exist download foo python foo/setup.py install etc HTH Mathieu From casey.mcginty at gmail.com Mon Sep 15 16:40:47 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 15 Sep 2008 10:40:47 -1000 Subject: Getting Linux partition info programmatically In-Reply-To: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> References: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> Message-ID: <ae3f58470809151340t287ab3c4m32218f1668d07338@mail.gmail.com> You might want to take a look at HAL (hardware extraction layer) and DBUS. freedesktop.org - Software/hal<http://www.freedesktop.org/wiki/Software/hal> HAL 0.5.10 Specification<http://people.freedesktop.org/%7Edavid/hal-spec/hal-spec.html> Dbus Tutorial<http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#connecting-to-the-bus> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/da746df1/attachment-0001.html> From arnodel at googlemail.com Mon Sep 22 03:41:07 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Sep 2008 00:41:07 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: <f5df9f65-a13d-4f5f-9cf9-534d37dd04c0@f63g2000hsf.googlegroups.com> On 22 Sep, 04:05, josh logan <dear.jay.lo... at gmail.com> wrote: > Hello, > > I have 2 questions. Say I have this class: > > class Player(object): > def __init__(self, fname, lname, score): > self.score = score > self.fname = fname > self.lname = lname > def __cmp__(self, other): > return (-cmp(self.score, other.score) or > cmp(self.lname, other.lname) or > cmp(self.fname, other.fname)) > def __repr__(self): > return 'Player(fname={0.fname}, lname={0.lname}, > score={0.score})'.format(self) > def __eq__(self, others): > if isinstance(other, Player): > return (self.score == other.score and > self.lname == other.lname and > self.fname == other.fname) > return False > def __ne__(self, others): > return not self.__eq__(others) > > fnames = ['Julie', 'Ben', 'Jason', 'David'] > lnames = ['Parks', 'Smith'] > scores = [100, 95, 95, 130, 58, 74] > > import itertools as it > > score_iter = it.cycle(scores) > > P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in > lnames] > > cmp(P[0], P[1]) # returns -1 > > sorted(P) # throws TypeError: unorderable types Player() < Player() > > The sorted function works when I define __lt__. > I must be misreading the documentation, because I read for the > documentation __cmp__ that it is called if none of the other rich > comparison functions are defined. > Is this a bug in Python 3.0rc1, or am I missing something? > > Secondly, say that we suddenly need another sorting order, where we > want to sort by decreasing score and then by DECREASING last name > (instead of increasing last name, defined above). Now that the > comparison function argument is taken away from the sorted builtin, > how do we accomplish this with the "key" parameter? > > Thank you I don't know about __cmp__ but for the second part of the question you can probably do: sorted(P, key=lambda p: (p.score, p.lname), reverse=True) HTH -- Arnaud From circularfunc at gmail.com Tue Sep 23 08:58:25 2008 From: circularfunc at gmail.com (process) Date: Tue, 23 Sep 2008 05:58:25 -0700 (PDT) Subject: Pyflix, confused about super() call Message-ID: <fb9803c5-3e13-4e97-88c1-ddace6bca705@p25g2000hsf.googlegroups.com> Anyone using Pyflix for the Netflix prize. How can it call super to itself in its init-method? --------------------- #!/usr/bin/env python '''Sample baseline averaging algorithms.''' import numpy as N from pyflix.algorithms import Algorithm class MovieAverage(Algorithm): '''Baseline algorithm that computes the average of all the votes for a movie and predicts that for every user. This algorithm returns an RMSE score of 1.0528 on the scrubbed dataset. ''' def __init__(self, training_set): self._movie_averages = {} super(MovieAverage,self).__init__(training_set) def __call__(self, movie_id, user_id): try: return self._movie_averages[movie_id] except KeyError: avg = N.average(self._training_set.movie(movie_id).ratings()) self._movie_averages[movie_id] = avg return avg class UserAverage(Algorithm): '''Baseline algorithm that computes the average of all the votes for a user and predicts that for every movie. This algorithm returns an RMSE score of 1.0688 on the scrubbed dataset. ''' def __init__(self, training_set): self._user_averages = {} super(UserAverage,self).__init__(training_set) def __call__(self, movie_id, user_id): try: return self._user_averages[user_id] except KeyError: avg = N.average(self._training_set.user(user_id).ratings()) self._user_averages[user_id] = avg return avg class DoubleAverage(MovieAverage,UserAverage): '''Returns the average of L{MovieAverage} and L{UserAverage}. This algorithm returns an RMSE score of 1.0158 on the scrubbed dataset. ''' def __call__(self, movie_id, user_id): return (MovieAverage.__call__(self,movie_id,user_id) + UserAverage.__call__(self,movie_id,user_id)) / 2 From tjreedy at udel.edu Wed Sep 10 18:36:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 18:36:46 -0400 Subject: max(), sum(), next() In-Reply-To: <d214d992-ff68-4b72-ace6-364a90852740@k37g2000hsf.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> <mailman.770.1221044039.3487.python-list@python.org> <d214d992-ff68-4b72-ace6-364a90852740@k37g2000hsf.googlegroups.com> Message-ID: <ga9i5u$fjd$1@ger.gmane.org> Mensanator wrote: > Are there situations where the sum of an empty > list should NOT be 0? Of course there are. Python Philosopy (my version, for this discussion): Make normal things easy; make unusual or difficult things possible. Application: Sum([]) == 0 is normal (90+% of cases). Make that easy (as it is). For anything else: if seq: s = sum(s, base) else: <whatever, including like raise your desired exception> which is certainly pretty easy. > Can sum() handle those cases? The developers choose what they thought would be most useful across the spectrum of programmers and programs after some non-zero amount of debate and discussion. > No, it can't, I have to write > my own definition if I want that behaviour. Or wrap your calls. In any case, before sum was added as a convenience for summing numbers, *everyone* has to write their own or use reduce. Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be the most common use of reduce. Sum(s,start) replaces the much less common reduce(lambda x,y: x+y, s, start). Reduce(S, s), where S = sum function, raises an exception on empty s. So use that and you are no worse off than before. However, a problem with reduce(S,s) is that it is *almost* the same as reduce(S,s,0). So people are sometimes tempted to omit 0, especially if they are not sure if the call might be reduce(S,0,s) (as one argument says it should be -- but that is another post). But if they do, the program fails, even if it should not, if and when s happens to be empty. > There's no reason > why sum([]) and sum([],0) have to mean the same thing at the > exclusion of a perfectly valid alternative definition. 'Have to', no reason. 'Should', yes there are at least three reasons. 1. Python functions generally return an answer rather than raise an exception where there is a perfectly valid answer to return. 2. As a general principle, something that is almost always true should not need to be stated over and over again. This is why, for instance, we have default args. 3. As I remember, part of the reason for adding sum was to eliminate the need (with reduce) to explicitly say 'start my sum at 0' in order to avoid buggy code. In other words, I believe part of the reason for sum's existence is to avoid the very bug-inviting behavior you want. Terry Jan Reedy From castironpi at gmail.com Wed Sep 17 19:09:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 17 Sep 2008 16:09:41 -0700 (PDT) Subject: decorator and API References: <mailman.1183.1221688957.3487.python-list@python.org> Message-ID: <160e332b-3b46-4a9f-957b-0eb8199ed3d7@8g2000hse.googlegroups.com> On Sep 17, 4:56?pm, Lee Harr <miss... at hotmail.com> wrote: > I have a class with certain methods from which I want to select > one at random, with weighting. > > The way I have done it is this .... > > import random > > def weight(value): > ? ? def set_weight(method): > ? ? ? ? method.weight = value > ? ? ? ? return method > ? ? return set_weight > > class A(object): > ? ? def actions(self): > ? ? ? ? 'return a list of possible actions' > > ? ? ? ? return [getattr(self, method) > ? ? ? ? ? ? ? ? ? ? for method in dir(self) > ? ? ? ? ? ? ? ? ? ? if method.startswith('action_')] > > ? ? def action(self): > ? ? ? ? 'Select a possible action using weighted choice' > > ? ? ? ? actions = self.actions() > ? ? ? ? weights = [method.weight for method in actions] > ? ? ? ? total = sum(weights) > > ? ? ? ? choice = random.randrange(total) > > ? ? ? ? while choice> weights[0]: > ? ? ? ? ? ? choice -= weights[0] > ? ? ? ? ? ? weights.pop(0) > ? ? ? ? ? ? actions.pop(0) > > ? ? ? ? return actions[0] > > ? ? @weight(10) > ? ? def action_1(self): > ? ? ? ? print "A.action_1" > > ? ? @weight(20) > ? ? def action_2(self): > ? ? ? ? print "A.action_2" > > a = A() > a.action()() > > The problem I have now is that if I subclass A and want to > change the weighting of one of the methods, I am not sure > how to do that. > > One idea I had was to override the method using the new > weight in the decorator, and then call the original method: > > class B(A): > ? ? @weight(50) > ? ? def action_1(self): > ? ? ? ? A.action_1(self) > > That works, but it feels messy. > > Another idea was to store the weightings as a dictionary > on each instance, but I could not see how to update that > from a decorator. > > I like the idea of having the weights in a dictionary, so I > am looking for a better API, or a way to re-weight the > methods using a decorator. > > Any suggestions appreciated. > > _________________________________________________________________ > Explore the seven wonders of the worldhttp://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE What about a function, 'reweight', which wraps the original, and sets a weight on the wrapper? def reweight(value): def reset_weight(method): #@wraps(method) #optional def new_method( *ar, **kw ): return method( *ar, **kw ) new_method.weight = value return new_method return reset_weight Call like this: class B(A): action_1= reweight( 50 )( A.action_1 ) You could pass them both in to reweight with two parameters: class B(A): action_1= reweight( 50, A.action_1 ) It's about the same. Variable-signature functions have limits. Otherwise, you can keep dictionaries by name, and checking membership in them in superclasses that have them by hand. Then you'd need a consistent name for the dictionary. That option looks like this (unproduced): class A: __weights__= {} @weight( __weights__, 10 ) ... @weight( __weights__, 20 ) ... class B( A ): __weights__= {} #new instance so you don't change the original @weight( __weights__, 50 ) ... B.__weight__ could be an object that knows what it's overriding (unproduced): class A: weights= WeightOb() #just a dictionary, mostly @weights( 10 ) ... @weights( 20 ) ... class B( A ): weights= WeightOb( A.weights ) #new, refs "super-member" @weights( 50 ) ... If either of the last two options look promising, I think I can produce the WeightOb class. It has a '__call__' method. From andyhume at gmail.com Mon Sep 8 16:12:03 2008 From: andyhume at gmail.com (andyhume at gmail.com) Date: Mon, 8 Sep 2008 13:12:03 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <f8c5f1de-d358-468b-81fd-aa8108d8f7e0@q26g2000prq.googlegroups.com> <dde588e9-84eb-4890-ac42-21dd2aec35c6@q26g2000prq.googlegroups.com> <db089fc6-ab11-4a5b-93ee-50c00992f1e1@v13g2000pro.googlegroups.com> Message-ID: <6d1f32aa-0740-4513-9d9e-f48ddf92435b@z72g2000hsb.googlegroups.com> On Sep 8, 10:20?am, John Machin <sjmac... at lexicon.net> wrote: > On Sep 8, 10:47?am, MK Bernard <mkbernard.... at gmail.com> wrote: > > > > > On Sep 7, 3:37?pm, John Machin <sjmac... at lexicon.net> wrote: > > > > On Sep 8, 7:51?am, "andyh... at gmail.com" <andyh... at gmail.com> wrote: > > > > > Hello... > > > > > I have a dict of key/values and I want to change the keys in it, based > > > > on another mapping dictionary. An example follows: > > > > > MAPPING_DICT = { > > > > ? ? 'a': 'A', > > > > ? ? 'b': 'B', > > > > > } > > > > > my_dict = { > > > > ? ? 'a': '1', > > > > ? ? 'b': '2' > > > > > } > > > > > I want the finished my_dict to look like: > > > > > my_dict = { > > > > ? ? 'A': '1', > > > > ? ? 'B': '2' > > > > > } > > > > > Whereby the keys in the original my_dict have been swapped out for the > > > > keys mapped in MAPPING_DICT. > > > > > Is there a clever way to do this, or should I loop through both, > > > > essentially creating a brand new dict? > > > > Is this homework? > > > > There seems to be an implicit assumption in the answers so far that > > > your mapping is a 1:1 mapping of all possible input keys. > > > > If it doesn't include all possible input keys, answers will crash with > > > a KeyError. If there are any many:1 elements in the mapping (for > > > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > > > in some checks for this. > > > Thats exactly why I did an explicit check in my post, so as to make > > sure that such a collision could not occur. It would seem that > > something along what I posted would be safer, if less elegant, than > > the others. > > I noted two problems: > (1) not covering all input keys: your code explicitly sweeps this > problem under the carpet, and does it laboriously ... > ? ? if x in my_dict.keys(): > instead of > ? ? if x in my_dict: > (2) not a 1:1 mapping -- for example, 'a' and 'b' both map to 'A' (the > only "collision" that I can see), but you don't address that. > > Here's some code which attempts to cover the bases: > > new_dict = {} > for key in my_dict: > ? ? if key not in MAPPING_DICT: > ? ? ? ? raise NoMapError('blah %r' % key) > ? ? else: > ? ? ? ? new_key = MAPPING_DICT[key] > ? ? if new_key in new_dict: > ? ? ? ? raise ManyToOneError('gurgle %r waffle %r' % (key, new_key)) > ? ? else: > ? ? ? ? new_dict[new_key] = my_dict[key] > > Having considered what is actually required under the checked-for > conditions, one or both raise statements may be replaced by other > code, and then simplified e.g. the first 4 lines in the loop may end > up being replaced by > ? ? new_key = MAPPING_DICT.get(key, key) > as already suggested by one respondent. > > Note that useful use-cases for any variety of this key-change exercise > may have many more items in MAPPING_DICT than there are in my_dict (a > big language dictionary and a few fragments of text to be > "translated"), or vice versa (a small synonym dictionary (color -> > colour, center -> centre) and a big input to be "standardised") so > it's a good idea to inquire which is likely to be the smaller and > iterate over that if the requirements permit it. In the interests of academia (although this isn't homework :)) I'll answer some of those questions: - Yes, the mapping dict doesn't necessarily have the same number of entries as the my_dict. It may have less than it or more than it. - There will never be dupes of key or value in the mapping. Though there maybe in my_dict. And, for extra credit, it may be useful to be able to 'translate' the my_dict back again using the same mapping_dict. ie, using the values in mapping dict as the new keys in my_dict, and the keys as the new values. Andy. From dullrich at sprynet.com Tue Sep 9 11:58:49 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 09 Sep 2008 10:58:49 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <dullrich-B5A8C7.10222205092008@text.giganews.com> <00d1d60c$0$20302$c3e8da3@news.astraweb.com> Message-ID: <dullrich-525217.10584909092008@text.giganews.com> In article <00d1d60c$0$20302$c3e8da3 at news.astraweb.com>, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote: > On Fri, 05 Sep 2008 10:22:22 -0500, David C. Ullrich wrote about why max > and min shouldn't accept a default argument: > > > Think about all the previously elected female or black presidents of the > > US. Which one was the tallest? > > I know the answer to that one: > > All of them! Heh. Mysteries of the empty set. -- David C. Ullrich From lists at cheimes.de Tue Sep 16 07:38:49 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Sep 2008 13:38:49 +0200 Subject: Mysqldb and Python 3000 In-Reply-To: <48CF7BA8.6060809@gmx.de> References: <48CF7BA8.6060809@gmx.de> Message-ID: <gao5s8$hmn$1@ger.gmane.org> Andreas Kalsch wrote: > Hi, > > how do I connect the easiest way to MySQL with Python 3000? I don't want > to get any trouble and install current MySQLdb, which is supported up to > Python 2.5. Use Python 2.5 if you don't want any trouble. It's going to take several months to years until most libraries support Python 3.0. Christian From simon at brunningonline.net Wed Sep 17 08:41:39 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 17 Sep 2008 13:41:39 +0100 Subject: recursive using the os.walk(path) from the os module In-Reply-To: <ea09b3700809170526h2bb639bapda383a1dc0a94771@mail.gmail.com> References: <ea09b3700809170526h2bb639bapda383a1dc0a94771@mail.gmail.com> Message-ID: <8c7f10c60809170541p6a743e71ldf7dbb6b474ae8fc@mail.gmail.com> 2008/9/17 A. Joseph <joefazee at gmail.com>: > I want to search through a directory and re-arrange all the files into e.g > > All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder. > > I`m thinking of doing something with the os.walk(path) method from os > module, I need some ideal how the algorithm should look like, maybe > recursive ..any deal? This help? http://code.activestate.com/recipes/499305/ -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From gagsl-py2 at yahoo.com.ar Fri Sep 19 11:25:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 12:25:09 -0300 Subject: Deflate with urllib2... (solved) References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <mailman.766.1221033019.3487.python-list@python.org> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <mailman.1247.1221772248.3487.python-list@python.org> <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> Message-ID: <op.uhqif7elx6zn5v@a98gizw.noga> En Thu, 18 Sep 2008 23:29:30 -0300, Sam <samslists at gmail.com> escribi?: > On Sep 18, 2:10?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > wrote: >> En Tue, 16 Sep 2008 21:58:31 -0300, Sam <samsli... at gmail.com> escribi?: >> The code is correct - try with another server. I tested it with a ? >> LightHTTPd server and worked fine. > > Gabriel... > > I found a bunch of servers to test it on. It fails on every server I > could find (sans one). > > Here's the ones it fails on: > slashdot.org > hotmail.com > godaddy.com > linux.com > lighttpd.net > > I did manage to find one webserver it succeeded on---that is > kenrockwel.com --- a domain squatter with a typoed domain of one of my > favorite photographer's websites (the actual website should be > kenrockwell.com) > > This squatter's site is indeed running lighttpd---but it appears to be > an earlier version, because the official lighttpd site fails on this > test. > > We have all the major web servers failing the test: > * Apache 1.3 > * Apache 2.2 > * Microsoft-IIS/6.0 > * lighttpd/1.5.0 > > So I think it's the python side that is wrong, regardless of what the > standard is. I've found the problem. The zlib header is missing (2 bytes), data begins right with the compressed stream. You may decode it if you pass a negative value for wsize: try: data = zlib.decompress(data) except zlib.error: data = zlib.decompress(data, -zlib.MAX_WBITS) Note that this is clearly in violation of RFC 1950: the header is *not* optional. BTW, the curl developers had this same problem some time ago <http://curl.haxx.se/mail/lib-2005-12/0130.html> and the proposed solution is the same as above. This is the output from your test script modified as above. (Note that in some cases, the compressed stream is larger than the uncompressed data): Trying: http://slashdot.org http://slashdot.org - Apache/1.3.41 (Unix) mod_perl/1.31-rc4 (deflate) len(def late)=73174 len(gzip)=73208 Able to decompress...went from 73174 to 73073. Trying: http://www.hotmail.com http://www.hotmail.com - Microsoft-IIS/6.0 (deflate) len(deflate)=1609 len(gzi p)=1635 Able to decompress...went from 1609 to 3969. Trying: http://www.godaddy.com http://www.godaddy.com - Microsoft-IIS/6.0 (deflate) len(deflate)=40646 len(gz ip)=157141 Able to decompress...went from 40646 to 157141. Trying: http://www.linux.com http://www.linux.com - Apache/2.2.8 (Unix) PHP/5.2.5 (deflate) len(deflate)=52 862 len(gzip)=52880 Able to decompress...went from 52862 to 52786. Trying: http://www.lighttpd.net http://www.lighttpd.net - lighttpd/1.5.0 (deflate) len(deflate)=5669 len(gzip) =5687 Able to decompress...went from 5669 to 15746. Trying: http://www.kenrockwel.com http://www.kenrockwel.com - lighttpd (deflate) len(deflate)=414 len(gzip)=426 Able to decompress...went from 414 to 744. -- Gabriel Genellina From jeff at jmcneil.net Wed Sep 3 15:01:20 2008 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 3 Sep 2008 12:01:20 -0700 (PDT) Subject: Looking for File comparison utility that produces actual differences References: <mailman.437.1220467253.3487.python-list@python.org> Message-ID: <d2ddc5f2-1049-443c-9a66-5d59a861250b@79g2000hsk.googlegroups.com> On Sep 3, 2:40 pm, dudeja.ra... at gmail.com wrote: > Hi, > > I looking for a file comparison utility in Python that works like > 'diff' command in Unix and 'comp' in Windows. > The present 'cmd' in filecmp module only presents output in the form > of 1 or 0 i.e whether the 2 files differ or not? > > So, I'm lookin for something that generates actual differences and > moreover it is cross platform as well. As I need that same thing in > both my windows and linux box. > > Even if it is a utlility please suggest. > > Thanks and regards, > Rajat What about the difflib module? [jeff at marvin test]$ cat file_one abcd 1234 - [jeff at marvin test]$ cat file_two abcd 12345 - [jeff at marvin test]$ [jeff at marvin test]$ python Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11) [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import difflib >>> for i in difflib.context_diff(open("file_one").readlines(), open("file_two").readlines()): ... print i, ... *** --- *************** *** 1,3 **** abcd ! 1234 - --- 1,3 ---- abcd ! 12345 - >>> Also, see http://docs.python.org/lib/module-difflib.html. -Jeff From blabla at dungeon.de Fri Sep 26 13:41:40 2008 From: blabla at dungeon.de (hofer) Date: Fri, 26 Sep 2008 10:41:40 -0700 (PDT) Subject: Understanding (and getting rid) of optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a References: <85ec721a-b5a2-4f22-9e37-bda4a0f9eb81@z72g2000hsb.googlegroups.com> <gbj26g$sst$00$1@news.t-online.com> Message-ID: <816326c3-1f07-442d-9370-46346505c3b7@k13g2000hse.googlegroups.com> On Sep 26, 6:21?pm, Peter Otten <__pete... at web.de> wrote: > hofer wrote: > > Hi, > > > I get following warning with a python script: > > > optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will > > return a signed string in Python 2.4 and up > > You can print options.__dict__ instead of options with little loss of > information, or turn the warning off > > python -Wignore::FutureWarning myscript.py > > Peter Thanks a lot Peter, Any trick to disable warnings just for a given range of code? bye H From wuwei23 at gmail.com Sun Sep 28 20:57:07 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 28 Sep 2008 17:57:07 -0700 (PDT) Subject: Odd Errors References: <gbp6cf$vac$1@aioe.org> <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> <1b1ed34d-f386-4389-a7f1-ce68be4e2a14@k30g2000hse.googlegroups.com> Message-ID: <b2bbbd17-631f-452b-8328-3eb4819eadba@a2g2000prm.googlegroups.com> "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > Do you ever want to scream from the rooftops, "'append' operates by > side-effect!"? "I'm mad as hell, and I'm not going to mutate in-place anymore!" From paul at boddie.org.uk Sat Sep 6 13:53:58 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 6 Sep 2008 10:53:58 -0700 (PDT) Subject: How to bring subprocess to the foreground? References: <mailman.614.1220709497.3487.python-list@python.org> <6ifhg2Fq24n6U1@mid.uni-berlin.de> <mailman.617.1220716740.3487.python-list@python.org> Message-ID: <1563bbfd-6219-4719-940f-91cd84c419e5@l42g2000hsc.googlegroups.com> On 6 Sep, 17:58, dudeja.ra... at gmail.com wrote: > > I though of displayin an information message on the screen through > tkMessageBox while the subprocess is running, I did it using: > > try: > testing = subprocess.Popen([batchFilePath], \ > shell = True) > > retCode = testing.wait() Note that you wait for the process to finish here... > tkMessageBox._show("Test Harness execution", \ > icon = 'info', \ > message="Testing %s in progress..." % libName) ...and that you show a message about the process running *after* waiting until it isn't running any more. > except: > tkMessageBox._show("Error", \ > type='ok', icon='error', \ > message="Error executing %s Test > Harness" % libName) > return None > else: > print retCode > > But the message is never displayed. Please suggest if there is > something wrong with this code I think you should first show your message, *then* wait for the process to finish. Paul From castironpi at gmail.com Tue Sep 23 20:08:20 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 17:08:20 -0700 (PDT) Subject: Visualize class inheritance hierarchy References: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Message-ID: <b652de2f-7421-4f60-b138-16908f912c32@y21g2000hsf.googlegroups.com> On Sep 23, 5:53?pm, Rob Kirkpatrick <robert.d.kirkpatr... at gmail.com> wrote: > Hi All, > > I just finished debugging some code where I needed to determine why > one subclass had a bound method and another did not. ?They had > different pedigree's but I didn't know immediately what the > differences were. > > I ended up walking the hierarchy, going back one class at a time > through the code, for the two subclasses (hierarchy ~7 classes deep > each) to see whom they inherited from. ?Short of writing this down on > paper, is there any way to graphically display the pedigree of an > object/class? ?"Graphically" can be text output to the terminal, don't > need anything special... > > I'm assuming this has been discussed before, but I'm lacking any > Google keywords that bring up the appropriate discussion. > > Cheers, > Rob Compare their __mro__ members if they are new-style. The depth-first search for the member you're looking for is straightforward in Python, even if maybe not immediately obvious. If not, we can try a settrace and a search for when they are defined, and build an __mro__ manually. From akineko at gmail.com Mon Sep 1 18:58:36 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 15:58:36 -0700 (PDT) Subject: Tkinter after() under VMware player Message-ID: <f198487d-7cac-4ccb-bfdf-a363815ee9fb@25g2000prz.googlegroups.com> Hi everyone, I wrote a Tkinter program that has a blinking widget. The blinking is controlled by the after() method available in the Tkinter. It worked very nicely. However, when I tried the program with a Unix OS that is running under VMware (hosted OS), I noticed the blinking rate is greatly reduced (1/2 ~ 1/4). It seems that the VMware is distributing the CPU time slot and after() is not correctly recognizing the situation. My laptop has a dual core CPU but I think my VMware (player) setting only utilizes one CPU. I know the time period of after() is not accurate but this is too inacurate. I'm wondering what is the best way to deal with this kind of situation. Any suggestion will be highly appreciated. Best regards, Aki- From half.italian at gmail.com Sat Sep 27 19:37:57 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sat, 27 Sep 2008 16:37:57 -0700 (PDT) Subject: check if file is MS Word or PDF file References: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> <mailman.1606.1222556479.3487.python-list@python.org> Message-ID: <5f11d0f5-772e-4089-84b4-071df2a89c5e@w39g2000prb.googlegroups.com> On Sep 27, 4:01?pm, "Chris Rebert" <c... at rebertia.com> wrote: > On Sat, Sep 27, 2008 at 3:42 PM, Michael Crute <mcr... at gmail.com> wrote: > > On Sat, Sep 27, 2008 at 5:43 PM, A. Joseph <joefa... at gmail.com> wrote: > >> What should I look for in a file to determine whether or not it is a > >> MS Word file or an Excel file or a PDF file, etc., etc.? including Zip > >> files > > >> I don`t want to check for file extension. > >> os.path.splitext('Filename.jpg') will produce a tuple of filename and > >> extension, but some file don`t even have extension and can still be read by > >> MS Word or NotePad. i want to be 100% sure of the file. > > > You could use the mimetypes module... > > > <<< import mimetypes > > <<< mimetypes.guess_type("LegalNotices.pdf") > >>>> ('application/pdf', None) > > Looking at the docs for the mimetypes module, it just guesses based on > the filename (and extension), not the actual contents of the file, so > it doesn't really help the OP, who wants to make sure their program > isn't misled by an inaccurate extension. > > Regards, > Chris > -- > Follow the path of the Iguana...http://rebertia.com > > > > > -mike > > > -- > > ________________________________ > > Michael E. Crute > >http://mike.crute.org > > > God put me on this earth to accomplish a certain number of things. > > Right now I am so far behind that I will never die. --Bill Watterson > > -- > >http://mail.python.org/mailman/listinfo/python-list Check http://sourceforge.net/project/showfiles.php?group_id=23617 for the 'file' command for Windows. ~Sean From gh at ghaering.de Mon Sep 8 04:12:50 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 08 Sep 2008 10:12:50 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: <6ii9jbFqoe2eU1@mid.uni-berlin.de> References: <mailman.587.1220646763.3487.python-list@python.org> <6ii9jbFqoe2eU1@mid.uni-berlin.de> Message-ID: <ga2mpg$ju9$1@ger.gmane.org> Matthias Huening wrote: > Hi, > >> - - Connection.enable_load_extension(enabled) to allow/disallow extension >> loading. Allows you to use fulltext search extension, for example ;-) > > The following code (from the docs) produces an error: > > from pysqlite2 import dbapi2 as sqlite3 > con = sqlite3.connect(":memory:") > # Load the fulltext search extension > con.enable_load_extension(True) > con.execute("select load_extension('./fts3.so')") > con.enable_load_extension(False) > > > Error is: > > con.execute("select load_extension('./fts3.so')") > pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht > gefunden. > > Where should I look for the module? The sources are in ext/fts3 in the SQLite source tree. I haven't found any Makefile, so I it myself using this gcc command: $ cd .../ext/fts3 $ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so *.c -lsqlite3 -- Gerhard From research at johnohagan.com Wed Sep 17 07:06:01 2008 From: research at johnohagan.com (John O'Hagan) Date: Wed, 17 Sep 2008 11:06:01 +0000 Subject: Use of generators and efficiency Message-ID: <200809171106.01782.research@johnohagan.com> Hi, I'm writing a Python program using combinatorial algorithms to generate music. It originally was of this general form: First, a combinatorial function producing a list of sub-lists, then: For each sub-list in the list: Filter/modifier A, then append modified sub-list to new list, For each sublist in new list: Filter/modifier B, then append modified sub-list to new list, ......and so on for C, D,etc. Finally, for each sub-list in the final list, output the sub-list (print/play as notes). Because some of the combinatorial operations were slow to produce results, I changed the program to be of the form: A combinatorial generator producing one small list for each call, then: Filter/modify list through A,B, etc Output the modified list Call the generator for next list. To my great surprise, this approach was often considerably _slower_ to complete than the original program (up to ~40% depending on which modifiers were used), despite producing initial results more quickly. Some possibly relevant details: each sub-list consists of a short sequence of small numbers representing musical notes, but there may be millions of them; the modifiers range from simple tests (e.g., " if len(sub-list) is not n: continue" ) to relatively elaborate rearrangements and transformations. My question is, how can it be quicker to unpack and rebuild a list for each modifier, than than to run all modifications on each element in turn? Any explanations, comments or advice? Thanks, John O'Hagan From jcd at sdf.lonestar.org Thu Sep 18 10:25:07 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 18 Sep 2008 10:25:07 -0400 Subject: improving a huge double-for cycle In-Reply-To: <48D2502C.4000200@tim.thechases.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D2502C.4000200@tim.thechases.com> Message-ID: <1221747907.6982.3.camel@aalcdl07.lib.unc.edu> On Thu, 2008-09-18 at 07:57 -0500, Tim Chase wrote: > > Code: Select all > > for i in range(len(IN)): #scan all elements of the list IN > > for j in range(len(IN)): > > if i <> j: > > if IN[i].coordinates[0] == IN[j].coordinates[0]: > > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > SN.append(IN[i].label) > > > > > Such changes might look something like > > for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): > if IN[i].coordinates == IN[j].coordinates: > SN.append(IN[i].label) If you aren't checking j values less than i, you might want to do both SN.append(IN[i].label) SN.append(IN[j].label) on the same pass. > If my college algorithms memory serves me sufficiently, this > reduces your O(N^2) to O(N log N) which will garner you some > decent time savings. > > -tkc > > > -- > http://mail.python.org/mailman/listinfo/python-list > From a at nospam.org Tue Sep 16 08:23:25 2008 From: a at nospam.org (Armin) Date: Tue, 16 Sep 2008 14:23:25 +0200 Subject: append on lists In-Reply-To: <1221564169.16690.0@proxy00.news.clara.net> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> <gao3d0$7q1$1@online.de> <1221564169.16690.0@proxy00.news.clara.net> Message-ID: <gao7lg$ha3$1@online.de> Alex Marandon wrote: > Armin wrote: >> Duncan Booth wrote: >> >> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c >> (with c = [8,9]) is identical, > > No it's not, + doesn't alter its operands. > > >>> a = 1 > >>> b = 2 > >>> a + b > 3 That's not the point :) What's the value of 1.add(b)? None? Or 3 ?? (if add works in the same way as append) a + b doesn't change a,b ... but a.add(b) -> a=3 From pruebauno at latinmail.com Thu Sep 18 11:43:02 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 18 Sep 2008 08:43:02 -0700 (PDT) Subject: dict generator question References: <mailman.1217.1221749709.3487.python-list@python.org> Message-ID: <ce449ed9-6085-4afc-b7f6-07e232887322@s50g2000hsb.googlegroups.com> On Sep 18, 10:54 am, "Simon Mullis" <si... at mullis.co.uk> wrote: > Hi, > > Let's say I have an arbitrary list of minor software versions of an > imaginary software product: > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > I'd like to create a dict with major_version : count. > > (So, in this case: > > dict_of_counts = { "1.1" : "1", > "1.2" : "2", > "1.3" : "2" } > > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. > > I'm most probably not thinking pythonically enough... (I know I could > do this pretty easily with a couple more lines, but I'd like to > understand if there's a way to use a dict generator for this). > > Thanks in advance > > SM > > -- > Simon Mullis Considering 3 identical "simultpost" solutions I'd say: "one obvious way to do it" FTW :-) From ptmcg at austin.rr.com Tue Sep 16 08:28:34 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 16 Sep 2008 05:28:34 -0700 (PDT) Subject: What is "finally:" for? References: <mailman.1105.1221564360.3487.python-list@python.org> Message-ID: <502e16a8-e20d-4795-a495-ce1f61fd8c15@m44g2000hsc.googlegroups.com> On Sep 16, 6:25?am, "Max Ivanov" <ivanov.ma... at gmail.com> wrote: > Hi all! > When and where I should use try-except-finally statement? What is the > difference between: > -------- > try: > ? A... > except: > ? B.... > finally: > ? C... > -------- > > and > ------- > try: > ? A... > except: > ? B.... > C... If B raises or rethrows another exception, finally: ensures that C still gets called. In the second form that you give, C would not get called. Here is one way to use try-except-finally: try: open database do database stuff except DatabaseException, de: log exception throw finally: close database Or try: transaction = new database transaction do database stuff do more database stuff commit transaction transaction = None except DatabaseException, de: log exception throw finally: if transaction: rollback transaction If you are allocating a resource, lock, file, database, etc., then exception-safe coding style is to get the resource in a try: and release the resource in finally: -- Paul From bearophileHUGS at lycos.com Wed Sep 3 18:02:09 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 15:02:09 -0700 (PDT) Subject: Python on JavaScript VM's (such as V8)? References: <1926ef1e-2c5e-4ef6-8a33-b360b02520a7@b38g2000prf.googlegroups.com> Message-ID: <31ea0481-bc7d-476e-92ce-df28b86eed11@o40g2000prn.googlegroups.com> Berco Beute: > I wonder what it would take to implement Python in JavaScript so it > can run on those fancy new JavaScript VM's such as Chrome's V8 or > Firefox' tracemonkey. Much the same as Python implementations in C# > (IronPython) and Java (Jython). It would certainly bring back the fun > in web application development. Is there anything done in that > direction? The mythical beast pypy is supposed able to translate Python to Javascript too, I think. From some of my benchmarks Chrome's V8 is a little slower than Psyco... so the matter is how much efficiently can be Python translated in JS. Bye, bearophile From gnewsg at gmail.com Thu Sep 4 07:28:28 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 4 Sep 2008 04:28:28 -0700 (PDT) Subject: Safely move an element into a heap Message-ID: <f0b4a244-00e2-43b3-9b38-5e494472f030@z11g2000prl.googlegroups.com> Hi, I wanted to know if does exist a safe way to, given a heap, move an arbitrary element to the first position of the heap. Something like: >>> heap = [0,3,6,8,10] >>> heapq.move_to_first_position(heap, 4) >>> heap = [10, 0,3,6,8] --- Giampaolo http://code.google.com/p/pyftpdlib/ From nick at craig-wood.com Tue Sep 2 07:35:41 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 02 Sep 2008 06:35:41 -0500 Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> Message-ID: <slrngbq6q7.6he.nick@irishsea.home.craig-wood.com> bearophileHUGS at lycos.com <bearophileHUGS at lycos.com> wrote: > Ben Finney: > > I don't see any good reason (other than your familiarity with the D > > language) to use underscores for this purpose, and much more reason > > (readability, consistency, fewer arbitrary differences in syntax, > > perhaps simpler implementation) to use whitespace just as with string > > literals. > > It's not just my familiarity, Ada language too uses underscore for > that purpose, I think, so there's a precedent, and Ada is a language > designed to always minimize programming errors, simple code mistakes > too. And perl also *ducks* -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From BjornSteinarFjeldPettersen at gmail.com Wed Sep 10 15:23:01 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Wed, 10 Sep 2008 12:23:01 -0700 (PDT) Subject: Is there a SOAP module that can do this...? Message-ID: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> I've been trying to use SOAPpy and ZSI (with and without the use of wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic server(?) in front of some enterprise java bean) and not having much luck. I got them to send me an example of what the bytes on the wire are supposed to look like (attached below), and I got it to "work" by going lo-tech: cn = httplib.HTTPSConnection('test.xx.no',443) cn.putrequest("POST", "/service/url") cn.putheader("Host", "test.xx.no") cn.putheader("Content-type", 'text/xml; charset="UTF-8"') cn.putheader("Content-length", "%d" % len(soap_message)) cn.putheader("SOAPAction", '""') cn.endheaders() cn.send(soap_message) Is there a better way to do this? Can it be done with any of the Python SOAP libraries? Bjorn soap message follows: <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> <Header xmlns="http://schemas.xmlsoap.org/soap/envelope/" /> <env:Body> <submitMessage xmlns="http://no/brreg/BReMS/WebService/services"> <cpaid>y111</cpaid> <securityKey>y222</securityKey> <message><![CDATA[<?xml version='1.0' encoding='ISO-8859-1'?> <SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'> <SOAP:Header xmlns:eb='http://www.oasis-open.org/committees/ebxml-msg/ schema/msg-header-2_0.xsd'> <eb:MessageHeader eb:id='1' eb:version='2.0' SOAP:mustUnderstand='1'> <eb:From> <eb:PartyId eb:type='orgnr-submitter'>x111</eb:PartyId> <eb:PartyId eb:type='orgnr-caseworker'>x222</eb:PartyId> <eb:Role>Submitter</eb:Role> </eb:From> <eb:To> <eb:PartyId eb:type='orgnr-registrator'>x111</eb:PartyId> <eb:Role>Registrator</eb:Role> </eb:To> <eb:CPAId>y111</eb:CPAId> <eb:ConversationId>ccd6dc26-836f-4768-8d28-5d46a872b9e8</ eb:ConversationId> <eb:Service eb:type='lockup'>x444</eb:Service> <eb:Action>appendMessage</eb:Action> <eb:MessageData> <eb:MessageId>ccd6dc26-836f-4768-8d28-5d46a872b9e8</eb:MessageId> <eb:Timestamp>23.09.2006</eb:Timestamp> </eb:MessageData> <eb:Description xml:lang='no'></eb:Description> </eb:MessageHeader> </SOAP:Header> <SOAP:Body> <LegacyData> <JegerproveInn xsi:noNamespaceSchemaLocation="JegerproveInn.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Arrangor> <ArrangorId>3</ArrangorId> <ArrangorNavn> <Navn1>BBB</Navn1> <Navn5></Navn5> </ArrangorNavn> <PersonNavn> <Fornavn>CCC</Fornavn> <Etternavn>DDD</Etternavn> </PersonNavn> <Kommunenr>9999</Kommunenr> <Telefon>12345678</Telefon> <Epost>a at b.no</Epost> </Arrangor> </JegerproveInn></LegacyData></SOAP:Body></SOAP:Envelope>]]> </message> </submitMessage> </env:Body> </env:Envelope> From gagsl-py2 at yahoo.com.ar Fri Sep 5 00:43:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 01:43:06 -0300 Subject: Curious: 2134 2004-10-06 08:55:20Z fredrik References: <af788ad10809042013hf365d49y2577d735d8ed83e2@mail.gmail.com> Message-ID: <op.ugzrd4ezx6zn5v@gabriel2.softlabbsas.com.ar> En Fri, 05 Sep 2008 00:13:28 -0300, Akathorn Greyhat <akathorn at gmail.com> escribi?: > I had an import error and I get this error: > Traceback (most recent call last): > File "C:\Eclipse\pyworkspace\CodenameRazor0.2\src\app.py", line 11, in > <module> > import core > File "C:\Python25\lib\site-packages\PIL\__init__.py", line 3, in > <module> > # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ > ImportError: No module named data > > I've already fix it, but I don't know what the hell does this line means: > > # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ > It seens curious, isn't it? I'd say the import mechanism got confused about the actual source of the error. Probably it happened on line 3 in *another* module, but the traceback got messed. Perhaps "core" is a package and contains "import data" at line 3? The $Id: stuff comes from some version control system -probably svn- and identifies the file version. -- Gabriel Genellina From ldo at geek-central.gen.new_zealand Mon Sep 29 05:11:19 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:11:19 +1300 Subject: how to replace and string in a "SELECT ... IN ()" References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <mailman.1547.1222447134.3487.python-list@python.org> Message-ID: <gbq63n$iiq$2@lust.ihug.co.nz> In message <mailman.1547.1222447134.3487.python-list at python.org>, D'Arcy J.M. Cain wrote: > On Fri, 26 Sep 2008 11:00:59 -0500 > "Michael Mabin" <d3vvnull at gmail.com> wrote: > >> So we can drop a table in an in clause? How is this a use case. >> Cartoons are funny but actual proof that this example using an in-clause >> provides an exploit would be more helpful I think. > > I'm not sure what proof you require. I would say Mr Mabin is displaying thinking characteristic of a PHP programmer <http://groups.google.co.nz/group/nz.comp/msg/4c2a4d220499dafd>. :) From steve at REMOVE-THIS-cybersource.com.au Sun Sep 14 16:25:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Sep 2008 20:25:18 GMT Subject: Abstract class References: <mailman.1008.1221408214.3487.python-list@python.org> <roy-9FFFBD.13564414092008@news.panix.com> <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <mailman.1012.1221419718.3487.python-list@python.org> Message-ID: <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> On Sun, 14 Sep 2008 12:15:04 -0700, Gary Herron wrote: > (If you wish to consider the base class "abstract", just agree with > yourself to not instantiate it.) That's certainly the most lightweight option. > Please forget about Abstract Base Classes. They have nothing to do with > what you want, and are a *HUGE* overkill for your application. They > are not (yet) even part of standard Python, and are used primarily for a > class implementor to guarantee to a user of a class that it provides a > specific interface. You can implement a lightweight abstract base class in Python fairly easily, by adding two lines to the __init__ method of your base class. class Base(object): def __init__(self): if self.__class__ is Base: raise NotImplementedError("Abstract base class") def method(self, *args): return len(args) # or something useful If you want to get fancy, you can define a custom exception instead of using NotImplementedError. And that's about all you need. You can get more complicated if you want, but why bother? If I may be excused a slight digression, I don't get the "abstract" part of ABCs. The prohibition against instantiating them just seems very artificial, I don't see what benefit it gets you. Wikipedia says: "The fact that many languages disallow instantiation of abstract types (and force subtypes to implement all needed functionality) further ensures program correctness." http://en.wikipedia.org/wiki/Abstract_base_class but I don't see how that follows (except possibly in very special cases). Given that the set of instances of class B is empty, how does that help you know that B.method is correct? -- Steven From karl.kobata at syncira.com Tue Sep 16 15:48:51 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Tue, 16 Sep 2008 12:48:51 -0700 Subject: ka-ping yee tokenizer.py In-Reply-To: <gamijq$95a$1@ger.gmane.org> Message-ID: <6gvfio$7rldo3@rrcs-agw-01.hrndva.rr.com> Hi Fredrik, This is exactly what I need. Thank you. I would like to do one additional function. I am not using the tokenizer to parse python code. It happens to work very well for my application. However, I would like either or both of the following variance: 1) I would like to add 2 other characters as comment designation 2) write a module that can readline, modify the line as required, and finally, this module can be used as the argument for the tokenizer. Def modifyLine( fileHandle ): # readline and modify this string if required ... For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ): Print token Anxiously looking forward to your thoughts. karl -----Original Message----- From: python-list-bounces+kkobata=syncira.com at python.org [mailto:python-list-bounces+kkobata=syncira.com at python.org] On Behalf Of Fredrik Lundh Sent: Monday, September 15, 2008 2:04 PM To: python-list at python.org Subject: Re: ka-ping yee tokenizer.py Karl Kobata wrote: > I have enjoyed using ka-ping yee's tokenizer.py. I would like to > replace the readline parameter input with my own and pass a list of > strings to the tokenizer. I understand it must be a callable object and > iteratable but it is obvious with errors I am getting, that this is not > the only functions required. not sure I can decipher your detailed requirements, but to use Python's standard "tokenize" module (written by ping) on a list, you can simple do as follows: import tokenize program = [ ... program given as list ... ] for token in tokenize.generate_tokens(iter(program).next): print token another approach is to turn the list back into a string, and wrap that in a StringIO object: import tokenize import StringIO program = [ ... program given as list ... ] program_buffer = StringIO.StringIO("".join(program)) for token in tokenize.generate_tokens(program_buffer.readline): print token </F> -- http://mail.python.org/mailman/listinfo/python-list From robert.kern at gmail.com Wed Sep 3 15:47:13 2008 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 Sep 2008 14:47:13 -0500 Subject: Is try-except slow? In-Reply-To: <pan.2008.09.03.05.43.21@REMOVE.THIS.cybersource.com.au> References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <mailman.395.1220399835.3487.python-list@python.org> <pan.2008.09.03.05.43.21@REMOVE.THIS.cybersource.com.au> Message-ID: <g9mpk2$1ug$1@ger.gmane.org> Steven D'Aprano wrote: > On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote: > >> ssecorp wrote: >>> or why does this take so god damn long time? >> Several reasons. One of which is that try: except: is slow. > > > I beg to differ. Setting up a try...except block is very fast. Here's an > example in Python 2.5: > > >>>> from timeit import Timer >>>> Timer('len("abc")').repeat() > [0.27346706390380859, 0.1530919075012207, 0.14886784553527832] >>>> Timer('''try: > ... len("abc") > ... except: > ... pass > ... ''').repeat() > [0.27847194671630859, 0.19191384315490723, 0.19077491760253906] > > The difference (approx 0.04 microseconds) applicable to setting up the > try...except block is trivial, of the same magnitude as a pass statement: > >>>> Timer('pass').repeat() > [0.059719085693359375, 0.060056924819946289, 0.059512138366699219] > > > However, *catching* the exception may be relatively slow: > >>>> Timer('''try: > ... len(abc) # raise a NameError > ... except: > ... pass > ... ''').repeat() > [3.2067418098449707, 2.7088210582733154, 1.9558219909667969] You're right. My mistake. I was misremembering Guido's old essay about try: except: versus if: else:. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Tue Sep 9 14:58:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Sep 2008 11:58:48 -0700 (PDT) Subject: check if the values are prensent in a list of values References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> Message-ID: <23f71a56-d838-4e08-b73c-de34b4b79f5b@79g2000hsk.googlegroups.com> On Sep 9, 2:04 pm, flit <superf... at gmail.com> wrote: > Hello All, > > I will appreciate the help from the more skillfull pythonistas.. > > I have a small app that generates a sequence like > > 00341 > 01741 > 03254 > > This values I am putting in a list. > > So I have a list = [00341,01741,03254] > > after the programs find the sequence 03401 this sequence is "new" so > it appends on the list. But I want to avoid that as the values are > already on the first sequence of the list (00341). > If I try to use a "in" statement it will give false. as 00341 is > different from 00341 (but for my goal not..) > > How can I check against this list and avoid to put "different" > sequences but same values? > > as 34100 --> dont append on the list > 14300 ---> dont append on the list > 05321 --> append to the list. > > Am I doing some conceptual error using lists? > There is a better approach? Whenever you want to keep track of unique values, think of using a set or dict, not list. Since you don't care about the character order within each string, sort the characters so that two strings are equivalent if and only if their sorted character lists are equal. One more thing to bear in mind is that the elements of a set (or the keys of a dict) have to be hashable. Lists are not hashable so there needs to be an extra step to convert the sorted list into an "equivalent" hashable object. A common choice that works for any list [*] is to convert it to a tuple. An alternative that works for strings only is to join() them into a single string: >>> values = '00341 01741 03254 34100 14300 05321'.split() >>> set(''.join(sorted(v)) for v in values) set(['01235', '00134', '01147', '02345']) HTH, George [*] Assuming that every element of the list is hashable. From woaibeiyang at hotmail.com Tue Sep 2 22:36:56 2008 From: woaibeiyang at hotmail.com (woaibeiyang) Date: Wed, 3 Sep 2008 10:36:56 +0800 Subject: about downloading the selected information References: <g9jcmv$h9p$1@news.cn99.com> Message-ID: <g9kt89$769$1@news.cn99.com> Thanks a lot! "woaibeiyang" <woaibeiyang at hotmail.com> ????????????:g9jcmv$h9p$1 at news.cn99.com... >I have a problem to download the information from url >http://www.ncbi.nlm.nih.gov/sites/entrez. Because it is impossible for me >to add searching material to the url to construct a new url and then visit >the website. > I have the searching material, however I could not find the way to deal > with this problem. I want to know how can I do this problem with python > and which part of knowledge should I view first? Thanks! > From circularfunc at gmail.com Sun Sep 28 14:29:42 2008 From: circularfunc at gmail.com (process) Date: Sun, 28 Sep 2008 11:29:42 -0700 (PDT) Subject: What is not objects in Python? Message-ID: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> I have heard some criticism about Python, that it is not fully object- oriented. What is not an object in Python? Why isn't len implemented as a str.len and list.len method instead of a len(list) function? From workitharder at gmail.com Thu Sep 4 15:38:45 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 4 Sep 2008 12:38:45 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> <f1b92bb7-f960-4e56-b8be-240cfc301726@b38g2000prf.googlegroups.com> <a547e63a-7315-48fe-bb04-97902dbc879a@z6g2000pre.googlegroups.com> Message-ID: <b9a1a7f8-0f31-4197-bcc6-e51e9d82dea8@a18g2000pra.googlegroups.com> > > I'd like to be able to do something like this: > > class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ..., > > VanillaCursor): pass > > Why does it have to look like that? ?A good programmer lets the code > look however it has to look to most effectively do it's job. > > With a proxy, the "base class" isn't a base class but a member. ?Here > is a very simple example: > > class SuperCursor(object): > ? ? def __init__(self): > ? ? ? ? self._cursor = VanillaCursor() > ? ? ? ? self._connected = False > ? ? def __getattr__(self,attr): > ? ? ? ? if not self._connected: > ? ? ? ? ? ? self._cursor.connect() > ? ? ? ? ? ? self._connected = True > ? ? ? ? return getattr(self._cursor,attr) > > cursor = SuperCursor() > > That doesn't use a mixin, but why should it? The point of using a mixin is to not limit myself to inheriting from VanillaCursor. I want to put this on top of various subclasses of the vanilla cursor, like TimeLimitedCursor or RetryingCursor. I have four other mixins that operate this way, so it's desirable to keep this one in line with that. From gagsl-py2 at yahoo.com.ar Tue Sep 30 04:05:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 05:05:55 -0300 Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <f2d2bf0b-9362-47f5-84eb-411e09ab38e1@8g2000hse.googlegroups.com> Message-ID: <op.uiabf5drx6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 30 Sep 2008 01:03:07 -0300, namekuseijin <namekuseijin at gmail.com> escribi?: > On 28 set, 15:29, process <circularf... at gmail.com> wrote: >> Why isn't len implemented as a str.len and list.len method instead of >> a len(list) function? > > Because postfix notation sucks. The natural way of spelling is > adjective+noun and verb+predicate. That's one of the reasons I like > Lisp better than Python. Well, "natural" for English-speaking people... Noun+adjective is usually more "natural" In Spanish than the English word ordering. Back to the original question, len(x) allows for a fast response without paying the overhead of a name lookup and then a method call. len(some_list) doesn't invoke some_list.__len__(), it just returns the value stored somewhere in the list object; same for other built-in objects. __len__ is searched as a last resort only. The optimization could not be done if it were spelled x.len() -- Gabriel Genellina From hypercaffeinatedbiped at gmail.com Mon Sep 29 09:12:35 2008 From: hypercaffeinatedbiped at gmail.com (HCB) Date: Mon, 29 Sep 2008 06:12:35 -0700 (PDT) Subject: One class per file? Message-ID: <a932e44b-3566-4c0f-8b63-2dce0a82946b@34g2000hsh.googlegroups.com> Hello: The book "Code Complete" recommends that you put only one class in a source file, which seems a bit extreme for me. It seems that many classes are small, so that putting several of them in a file seems reasonable. I noticed that the decimal.py module in the standard library has several classes, all of which of course revolve around the "decimal" topic. Perhaps a better rule of thumb is "one idea per file." I checked the Python style guide and there seems to be no mention of this topic. I know this is an elementary question, but what is the Python way of doing this? Thanks for your time. HCB From pavlovevidence at gmail.com Fri Sep 5 15:19:25 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 5 Sep 2008 12:19:25 -0700 (PDT) Subject: "Full" element tag listing possible with Elementtree? References: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Message-ID: <5e374e5f-40d9-44f4-9c7b-a44106da71e2@e39g2000hsf.googlegroups.com> On Sep 5, 2:27 am, jaime.dy... at gmail.com wrote: > So, for example, if I had a document that looked like this: > > <a> > <b att="atttag" content="b"> this is node b </b> > <c> this is node c > <d /> > <e> this is node e </e> > </c> > <f> this is node f </f> > </a> > > I would want to print the following: > > <a> > <a> <b> > <a> <b> text: this is node b > <a> <c> > <a> <c> text: this is node c > <a> <c> <d> > <a> <c> <e> > <a> <c> <e> text: this is node e > <a> <f> > <a> <f> this is node f > > Is there a simple way to do this? Any help would be appreciated. > Thanks.. Fredrik Lundh wrote Element Tree, so he'd know the best solution, but I'd like to point out that this is also trivially easy with recursion: def print_nodes(element, ancestors = []): s = hierarchy = ancestors + ["<" + element.tag + ">"] if element.text is not None: s = s + [element.text] print " ".join(s) for subelement in element: print_nodes(subelement,hierarchy) Carl Banks From enleverlesX.XmcX at XmclaveauX.com Sun Sep 21 03:52:47 2008 From: enleverlesX.XmcX at XmclaveauX.com (=?UTF-8?Q?M=C3=A9ta-MCI_=28MVP=29?=) Date: Sun, 21 Sep 2008 09:52:47 +0200 Subject: Not fully OO ? In-Reply-To: <mailman.1294.1221902983.3487.python-list@python.org> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <mailman.1294.1221902983.3487.python-list@python.org> Message-ID: <48d5fe18$0$909$ba4acef3@news.orange.fr> Hi! > Everything ... are an object. It's true ; but a language built around the objects, and OOP, are two different concepts. @-salutations -- Michel Claveau From andy_westken at hotmail.com Thu Sep 11 11:19:22 2008 From: andy_westken at hotmail.com (andy_westken at hotmail.com) Date: Thu, 11 Sep 2008 08:19:22 -0700 (PDT) Subject: Enumerating ordered expat attributes with tuplets? References: <c397633b-d558-4fbf-a0a4-d1c1cd7a3ecb@34g2000hsh.googlegroups.com> <mailman.877.1221145526.3487.python-list@python.org> Message-ID: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> On Sep 11, 4:04?pm, Manuel Ebert <maeb... at uos.de> wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi Andy, > > by the looks of it I'd say that the problem is that the second ? > parameter you passed to start_element is not a dictionary at all (the ? > clue is in the "AttributeError: 'LIST' object" ...). > > ?>>> d = ['tree', 'house'] > ?>>> start_element("Thing", d) > Thing : > AttributeError: 'list' object has no attribute 'items' > ?>>> d = {'tree': 'hug', 'flower' : 'eat'} > ?>>> start_element("Thing", d) > Thing : ? flower="eat" ?tree="hug" > > Manuel > > On Sep 11, 2008, at 4:21 PM, andy_west... at hotmail.com wrote: > > > > > > > Hi > > > I'm new to Python and trying to pick up good, idiomatic usage right > > from the offset. > > > As I was familiar with Expat from C++ (directly and via expatpp) I'm > > trying to write a little script - using xml.parsers.expat - to search > > and replace XML attribute values. > > > As I want the attributes to stay in order when the file is written out > > (so I can check my results with a diff tool) I've set the parser's > > ordered_attributes attribute. But this has stopped the for loop > > working with the tuplets. > > > The relevant bit of code in my little test, using the default > > Dictionary for the attributes, is: > > > def start_element(name, attrs): > > ? ? print "%s : " % name, > > ? ? for (a,b) in attrs.items(): > > ? ? ? ? print " %s=\"%s\"" % (a,b), > > > But when I set ordered_attributes, first it doesn't like the items() > > > ? ? AttributeError: 'list' object has no attribute 'items' > > > And then it doesn't like the tuple > > > ? ? ValueError: too many values to unpack > > > Do I have keep track of where I am (name, value, name, value, ...) > > > Or is there a way I can solve the problem with a tuple? > > > Thanks, Andy > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (Darwin) > > iD8DBQFIyTOLcZ70OCIgLecRAsBrAJ9YSa7f+YTyM1yRmEKw8KBtb2klIgCgjNzw > F295Tik+45eNHnJ3B4kKnWU= > =xR4m > -----END PGP SIGNATURE------ Hide quoted text - > > - Show quoted text - Sorry! I forgot to mention that when you set the parser's ordered_attributes attribute, it sends the "attrs" to start_element as a list, not a dictionary, in the order name, value, name, value, ... Andy From gherron at islandtraining.com Sat Sep 20 12:37:42 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 20 Sep 2008 09:37:42 -0700 Subject: How to make a reverse for loop in python? In-Reply-To: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <48D526D6.4060402@islandtraining.com> Alex Snast wrote: > Hello > > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) > -- > http://mail.python.org/mailman/listinfo/python-list > What are you trying to loop through? If it's the contents of a list, you can reverse the list (in place) first: L = [1,2,3] L.reverse() for item in L: print item Or you can create a new reversed (copy of the original) list and iterate through it for item in reversed(L): print item If it's just a sequence of numbers you want to generate: range(3) generates a forward list [0,1,2], and range(3,0,-1) generates a backward list [2,1,0] so for i in range(11,0,-1): might be what you want. If your list is huge, consider xrange rather than range. And as always, you could just roll your own index manipulation: i = 10 while i >=0: # do whatever i -= 1 Gary Herron From fredrik at pythonware.com Wed Sep 10 09:46:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 15:46:54 +0200 Subject: Python extension, where am I going wrong In-Reply-To: <48C7C8CC.2090404@arl.army.mil> References: <48C7C8CC.2090404@arl.army.mil> Message-ID: <ga8j4f$cf7$1@ger.gmane.org> John Vines (CISD/HPCD) wrote: > I am trying to create an extension module and keep getting an error, > "/usr/local/lib/python2.5/site-packages/mytest.so: undefined symbol: > PyInitModule" it's spelled Py_InitModule, not PyInitModule. </F> From ptmcg at austin.rr.com Mon Sep 29 10:45:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 29 Sep 2008 07:45:47 -0700 (PDT) Subject: Using re to find unicode ranges References: <mailman.1674.1222694261.3487.python-list@python.org> Message-ID: <c9d2d100-e99d-41d1-ae1f-1b9c65bcc392@x41g2000hsb.googlegroups.com> On Sep 29, 8:17?am, Eric Abrahamsen <e... at ericabrahamsen.net> wrote: > Is it possible to use the re module to find runs of characters within ? > a certain Unicode range? > > I'm writing a Markdown extension to go over text and wrap blocks of ? > consecutive Chinese characters in <span class="char"></span> tags for ? > nice styling in an HTML page. The available hooks appear to be a pre- > processor (which is a "for line in lines" situation) or an inline ? > pattern (which uses regular expressions). The regular expression ? > solution would be much simpler and faster, but something tells me ? > there's no way to use a regex to find character ranges... Chinese ? > characters appear to fall between 19968 and 40959 using ord(), and I ? > suppose I can go that route if necessary, but I think it would be ugly. > > Any hints or suggestions would be appreciated! > > Eric Eric - This sounds similar to what zhpy (http://pyparsing.wikispaces.com/ WhosUsingPyparsing#Zhpy) does to extract Chinese words from code, to generate executable English Python. You might give that a look. -- Paul From kccnospam at glenevin.com Mon Sep 8 16:10:20 2008 From: kccnospam at glenevin.com (seanacais) Date: Mon, 8 Sep 2008 13:10:20 -0700 (PDT) Subject: finding the parent class (not superclass) of the currently executing method derived from a Borg class Message-ID: <dc58489b-e114-4d0f-ad49-9011128d0467@b38g2000prf.googlegroups.com> I want to create a class derived from a Borg class that can instantiated as part of a script or be contained in other classes. When methods from the Borg class are called, I would like to know the name of the class that contains the Borg class. I've played a bit with inspect and _getframe from the sys module but get inconsistent results. The main problem is if the Borg class is instantiated outside a containing class, then I need to go up a different number of stack frames. But this information isn't available till after I've run out of stack frames. Hopefully the following code better describes what I'm looking to do. import sys class Borg: _shared_state = {} def __init__(self): self.__dict__=self._shared_state class Assimilated(Borg): valueByCaller = {} def __init__(self, setupvalue): print "In Assimilated.__init__()" print "setupvalue is: " + str(setupvalue) # would like key to be name of class (or module) that # contins Assimilated callerID = sys._getframe(1).f_code.co_name self.valueByCaller[callerID] = setupvalue print self.valueByCaller def action(self, calledvalue): print "In Assimilated.action()" print "self.__classname__: " + self.__class__.__name__ print "calledvalue is: " + str(calledvalue) print "self.valueByCaller" print self.valueByCaller # need to get proper key depending on which class (or module) # made the call # print "0: " + sys._getframe(0).f_code.co_name # print "1: " + sys._getframe(1).f_code.co_name # print "2: " + sys._getframe(2).f_code.co_name # print "3: " + sys._getframe(3).f_code.co_name callerID = sys._getframe(2).f_code.co_name print "callerID" print callerID if(self.valueByCaller[callerID] <= calledvalue): print "doing the action" class A: assim_object = Assimilated(2) def __init__(self): self.assim_object.action(2) self.assim_object.action(3) class B: assim_object = Assimilated(3) def __init__(self): self.assim_object.action(3) self.assim_object.action(4) class C: assim_object = Assimilated(4) def __init__(self): self.assim_object.action(4) self.assim_object.action(5) a=A() b=B() c=C() obj=Assimilated(3) #obj.action(3) When I run this, I get the following output: In Assimilated.__init__() setupvalue is: 2 {'A': 2} In Assimilated.__init__() setupvalue is: 3 {'A': 2, 'B': 3} In Assimilated.__init__() setupvalue is: 4 {'A': 2, 'C': 4, 'B': 3} In Assimilated.action() self.__classname__: Assimilated calledvalue is: 2 self.valueByCaller {'A': 2, 'C': 4, 'B': 3} callerID <module> Traceback (most recent call last): File "\CallerID.py", line 67, in <module> a=A() File "\CallerID.py", line 49, in __init__ self.assim_object.action(2) File "\CallerID.py", line 41, in action if(self.valueByCaller[callerID] <= calledvalue): KeyError: '<module>' What I found most peculiar when I started this was that the valueByCaller dictionary was completely populated before the __init__ method of a was executed. I'm pretty sure that this has to do with the difference between when the object gets instanced and when it gets initialized, but I need to do some more research and reading to be able to explain it to myself. Thanks for any help you can give me. Kevin From imageguy1206 at gmail.com Fri Sep 12 16:41:57 2008 From: imageguy1206 at gmail.com (imageguy) Date: Fri, 12 Sep 2008 13:41:57 -0700 (PDT) Subject: String to hexadecimal conversion References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Message-ID: <87ec2d77-3892-4793-ab02-880f8564acf2@i24g2000prf.googlegroups.com> On Sep 8, 5:05?am, Praveena P <praveenapa... at gmail.com> wrote: > Hi folks, > > I am new to Python... so am not too sure about how the type conversion > works. > > I have to read a file that contains hexadecimal data and use the data > further to do some arithmetic calculations. > A sample of the input is : 00000000000020E0000032F800000000400022005E > The problem I am facing is this: > I am using f.read(2) to read a byte at a time, but the data that is > read is a string rather than a number. So it kind of hampers any > arithmetic operations I perform on this data... > > Could you please suggest some method I could use for this? > > Thanks guys! > Praveena check out the "struct" module in the standard python library. It's title says it all "Interpreting strings as packed binary data". I used this extensively to reverse engineer a couple proprietary file structures. You can read large chucks of the file - perhaps a record ? - and then based on the format provided, convert it to a tuple. Good luck. g. From castironpi at gmail.com Fri Sep 26 20:24:48 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 17:24:48 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> <48DCC786.2040407@wildenhain.de> <mailman.1551.1222447687.3487.python-list@python.org> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <mailman.1572.1222472905.3487.python-list@python.org> Message-ID: <f9b466b0-9945-42c1-ad9c-2f65c8d4b907@y38g2000hsy.googlegroups.com> On Sep 26, 6:40?pm, "Tim Rowe" <digi... at gmail.com> wrote: > 2008/9/26 Aaron Castironpi Brady <castiro... at gmail.com>: > > > If you have wxFormBuilder and the win32 library, it's pretty fast. > > Speed has never been an issue for me with Python. For my masters > degree I did a project that involved a lot of number crunching, and in > my proposal I wrote that I'd use Python for most of the code and C for > any parts that were unacceptably slow. In practice, not only did I > never need to replace any parts with C, I never even needed to use > numpy; it was quite fast enough as it was. > > > Python's philosophy is to make common things easy and everything > > possible. > > But what's common for one person may be uncommon for another. And > sometimes "possible" isn't enough, or we'd all be using INTERCAL! > > Another, quite different example to the one I was referring to earlier > is the fact that I often work with safety critical systems. I don't > think formal proof of program behaviour would be at all > straightforward in Python (or C# for that matter, and although Spec# > gets closer, it really needs a language like Spark Ada). > > -- > Tim Rowe No. I understand that formal proof systems, as well as automated theorem provers, have been difficult to develop. When I took ML, the homeworks were to prove the correctness of an interpretation of a program, and the unique existence of a meaning by induction. But I, and I imagine I'm not the only one, would love to know the example that C# developed faster than Python. I suppose the fact that the line of wx specification that has two identifiers where C# has one is more of a drain on programmer resources than may commonly be recognized--- not the same as the cost of one extra word in a paper or in an editorial. Similarly, maybe the program that has one extra identifier in a line takes a lot more time to develop. Perhaps it's the "7 +/- 1" trend in attention span that makes the difference large in that case. 8 identifiers would in that theory be a big deal, so the example in C# could make the case for it. From invalid at invalid Fri Sep 26 11:44:13 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 26 Sep 2008 10:44:13 -0500 Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> Message-ID: <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d@posted.visi> On 2008-09-26, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote: > In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: >> >>> Just a thought, your minimum sleep time is probably limited by the >>> resolution of the system "HZ" clock. Type >>> >>> less /proc/config.gz >> >> $ less /proc/config.gz >> /proc/config.gz: No such file or directory >> >> >> What OS are you using? > > The one named in the subject line? Never assume somebody reading the article and attempting to help you can see the subject line. -- Grant Edwards grante Yow! I'm encased in the at lining of a pure pork visi.com sausage!! From sjmachin at lexicon.net Sun Sep 7 18:59:52 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Sep 2008 15:59:52 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <f8c5f1de-d358-468b-81fd-aa8108d8f7e0@q26g2000prq.googlegroups.com> <mailman.668.1220827338.3487.python-list@python.org> Message-ID: <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> On Sep 8, 8:42?am, "James Mills" <prolo... at shortcircuit.net.au> wrote: > On Mon, Sep 8, 2008 at 8:37 AM, John Machin <sjmac... at lexicon.net> wrote: > > There seems to be an implicit assumption in the answers so far that > > your mapping is a 1:1 mapping of all possible input keys. > > > If it doesn't include all possible input keys, answers will crash with > > a KeyError. If there are any many:1 elements in the mapping (for > > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > > in some checks for this. > > You are quite right! But then he/she didn't > ask for this right ? :) > What do you mean by "this right"? Perhaps the Divine Right of OPs, managers, examiners, business analysts, etc never to give a complete spec up front and never to contemplate the consequences of Murphy's Law? From grommasher at gmail.com Mon Sep 1 12:00:43 2008 From: grommasher at gmail.com (Grom) Date: Mon, 1 Sep 2008 09:00:43 -0700 (PDT) Subject: Problem with Twisted Message-ID: <3f336b4e-9834-4706-ae01-648c0762e43e@s50g2000hsb.googlegroups.com> Hello. I have something like that: from twisted.words.protocols.jabber import xmlstream from twisted.internet import protocol from twisted.words.xish import domish, utility from twisted.internet import reactor from twisted.python import log import sys, hashlib log.startLogging(sys.stdout) def magicHash(password, sid): magic1 = 0x50305735 magic2 = 0x12345671 sum = 7 for s in range(len(password)): z = ord(password[s]); if (z == ' '): continue if (z == '\t'): continue magic1 = magic1 ^ ((((magic1 & 0x3f) + sum) * z) + (magic1 << 8)) magic2 = magic2 + ((magic2 << 8) ^ magic1) sum += z magic1 = magic1 & 0x7fffffff magic2 = magic2 & 0x7fffffff return ('%08x%08x'%(magic1, magic2)) def ping(xmlstream): print 'ping' xmlstream.send(' \t ') reactor.callLater(40, ping, xmlstream) class TlenAuthInitializer(object): def __init__(self, xs): print "Wykonywanie TlenAuthInitializer" self.xmlstream = xs def initialize(self): print "Wykonywanie TlenAuthInitializer - initialize" iq = xmlstream.IQ(self.xmlstream, "set") print '1' iq['id'] = self.xmlstream.sid print '2' q = iq.addElement('query', 'jabber:iq:auth') print '3' q.addElement('username', content = self.xmlstream.authenticator.jid) print '4' q.addElement('digest', content = hashlib.sha1(magicHash(self.xmlstream.authenticator.password, self.xmlstream.sid)).hexdigest()) print '4' q.addElement('resource', content = 't') print '6' q.addElement('host', content = 'tlen.pl') print q.toXml(prefixes=self.prefixes, closeElement=0) print '7' d = iq.send('q') print '8' d.addCallback(self._authreply) print '9' d.addErrBack(self._authfail) print '10' def _authreply(self, el): print "Wykonywanie TlenAuthInitializer - _authreply" print el.toXml() reactor.callLater(40, ping, self.xmlstream) def _authfail(self, el): print "Wykonywanie TlenAuthInitializer - _authfail" print el.toXml() class TlenAuthenticator(xmlstream.ConnectAuthenticator): def __init__(self, jid, password, host): print "Wykonywanie TlenAuthenticator" xmlstream.ConnectAuthenticator.__init__(self, host) self.jid = jid self.password = password def associateWithStream(self, xs): print "Wykonywanie TlenAuthenticator - associateWithStream" xs.version = (0, 0) xmlstream.ConnectAuthenticator.associateWithStream(self, xs) inits = [(TlenAuthInitializer, True)] for initClass, required in inits: init = initClass(xs) init.required = required xs.initializers.append(init) class TlenStream(xmlstream.XmlStream): def sendHeader(self): print "Wykonywanie TlenStream - sendHeader" rootElem = domish.Element((None, 's')) rootElem['v'] = '9' rootElem['t'] = '06000224' self.rootElem = rootElem self.send(rootElem.toXml(prefixes=self.prefixes, closeElement=0)) self._headerSent = True print 'XMLed rootElem from sendHeader '+rootElem.toXml(prefixes=self.prefixes, closeElement=0) def sendFooter(self): print "Wykonywanie TlenStream - sendFooter" self.send('</s>') def onDocumentStart(self, rootelem): print "Wykonywanie TlenStream - onDocumentStart" xmlstream.XmlStream.onDocumentStart(self, rootelem) print 'rootelem from onDocumentStart '+rootelem.toXml() if rootelem.hasAttribute("i"): self.sid = rootelem["i"] self.authenticator.streamStarted(rootelem) class TlenStreamFactory(xmlstream.XmlStreamFactory): def __init__(self, authenticator): print "Wykonywanie TlenStreamFactory" xmlstream.XmlStreamFactory.__init__(self, authenticator) self.authenticator = authenticator def buildProtocol(self, _): print "Wykonywanie TlenStreamFactory - buildProtocol" self.resetDelay() # Create the stream and register all the bootstrap observers xs = TlenStream(self.authenticator) xs.factory = self for event, fn in self.bootstraps: xs.addObserver(event, fn) return xs def lg(el): print 'all>',el def err(el): print 'err>', el factory = TlenStreamFactory(TlenAuthenticator('portsentry', 'linux1991','s1.tlen.pl' )) factory.addBootstrap('/*', lg) reactor.connectTCP('s1.tlen.pl', 443, factory) reactor.run() Now... I have problem with that. It not print me any errors but there is something with d = iq.send('q') on TlenAuthInitializer - initialize. I dont know why but python print me just "6" and stops... its strange... anyone have suggestions? From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 22:45:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 02:45:10 GMT Subject: Borg vs Singleton vs OddClass References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> Message-ID: <00eee973$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 11:12:00 -0700, Lie wrote: > This is probably unrelated to Python, as this is more about design > pattern. I'm asking your comments about this design pattern that is > similar in functionality to Singleton and Borg: to share states. > > I'm thinking about this design pattern (I don't know if anyone has ever > thought of this pattern before): > > class OddClass(object): > def __init__(self): > global OddClass > OddClass = self > def __call__(): > return self I don't think that pattern works as you give it. I suggest you read the thread "What do you call a class not intended to be instantiated", started by me on the 21st of September, which covers a similar pattern. I'm afraid it's a rather long thread, with a lot of people misunderstanding what I was asking, but still worth reading. If you only have time to read one post, I suggest you read my reply to Ben Finney, posted yesterday. My own feeling is that both your OddClass and my class without instances are probably solutions looking for a problem. Well, actually, no, that's too strong: I think the concept of "Class Singleton" is a perfectly valid solution to certain problems, but it competes with more well-known solutions like modules and Borg (in Python) and Singletons (the hammer available in Java and C++). As for which is better, that's partly a matter of personal taste and partly a matter of familiarity. > It do have a problem though, that you can't do isinstance(a, OddClass) But you can say "a is OddClass", which is more appropriate for a Singleton. > The problem with Borg is that it is not inheritable (in certain > sense[1]) and only work with old-style class (which is due to be > completely removed on py3k)[2] No, there is a new-style Borg. Read the comments here: http://code.activestate.com/recipes/66531/ The new-style Borg is hardly more complicated than old-style: 6 lines versus 4. I like Luke Plant's comment: "classes and modules are singletons. You don't need singletons in python simply because classes and modules are always singletons, and they are also first class objects. They can have everything instances have, and as import statements don't make copies there is only ever one of them. We don't need no stinkin' design patterns." -- Steven From duncan.booth at invalid.invalid Wed Sep 10 10:42:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Sep 2008 14:42:41 GMT Subject: universal unicode font for reportlab References: <ga6loq$jpj$1@rumours.uwaterloo.ca> <mailman.785.1221053660.3487.python-list@python.org> Message-ID: <Xns9B159F78E43Dduncanbooth@127.0.0.1> Laszlo Nagy <gandalf at shopzeus.com> wrote: > I need to use HTML anyway. I realized that universal unicode fonts are > above 5MB in size. The report would be a 10KB PDF, but I need to embed > the font before I can send it to anyone. Since some reports needs to be > sent in emails, I need to use something else. I cannot be sending 10MB > emails for "one page" reports. > I thought that usually when you embed a font in a PDF only the glyphs which are actually used in the document get embedded. Unfortunately a quick test with reportlab seems to show that it doesn't do that optimisation: it looks as though it just embeds the entire font. -- Duncan Booth http://kupuguy.blogspot.com From castironpi at gmail.com Wed Sep 10 15:26:42 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 10 Sep 2008 12:26:42 -0700 (PDT) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <ga91ft$12t$1@inews.gazeta.pl> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> Message-ID: <93e2f111-eb1a-44ba-a184-a35c2a8b8980@f36g2000hsa.googlegroups.com> On Sep 10, 1:12?pm, Aaron Scott <aaron.hildebra... at gmail.com> wrote: > Sorry, I had posted the wrong error. The error I am getting is: > > ? ? ?struct.error: unpack requires a string argument of length 12 > > which doesn't make sense to me, since I'm specifically asking for 11. > Just for kicks, if I change the line to > > ? ? ?print struct.unpack('3sII', file.read(12)) > > I get the result > > ? ? ?('GDE', 33554432, 16777216) > > ... which isn't even close, past the first three characters. Sometimes 'endian' order can cause this. Try '<3sII' and '>3sII' for your formats to differentiate. Also, if your file is not packed the way that 'struct' expects, you might need to read the string and integers separately. /Example: >>> struct.Struct( '3s' ).size + struct.Struct( 'II' ).size 11 >>> struct.Struct( '3sII' ).size 12 From michael.pearmain at tangozebra.com Mon Sep 8 08:52:33 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 8 Sep 2008 05:52:33 -0700 (PDT) Subject: Dictionaries and loops Message-ID: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> Hi All i have a CSV file that i'm reading in and each line has the look of the below {None: ['User-ID', 'Count']} {None: ['576460847178667334', '1']} {None: ['576460847178632334', '8']} i want to make a dictionary of items in the form {576460847178667334:1, 576460847178632334:8, ..... } for all rows in the datafile my code so far is thus: dict1={} j=1 for row in reader1: if j==1: j+=1 continue #thus allowing me to skip the first row if j>1: for element in row.values(): for item in element: if int(item)%2==0: dict1[int(item)] = int(item)+1 # i know this is the problem line as it's not picking the second item up just finding the first and increasing it, but i can't figure out how to correct this? j+=1 I get one dictionary from this but not the correct data inside, can anyone help? From gh at ghaering.de Fri Sep 5 16:24:23 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 05 Sep 2008 22:24:23 +0200 Subject: [ANN] pysqlite 2.5.0 released Message-ID: <48C19577.3020303@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 pysqlite 2.5.0 released ======================= I'm pleased to announce the availability of pysqlite 2.5.0. This is a release with major new features. Go to http://pysqlite.org/ for downloads, online documentation and reporting bugs. What is pysqlite? pysqlite is a DB-API 2.0-compliant database interface for SQLite. SQLite is a in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. pysqlite makes this powerful embedded SQL engine available to Python programmers. It stays compatible with the Python database API specification 2.0 as much as possible, but also exposes most of SQLite's native API, so that it is for example possible to create user-defined SQL functions and aggregates in Python. If you need a relational database for your applications, or even small tools or helper scripts, pysqlite is often a good fit. It's easy to use, easy to deploy, and does not depend on any other Python libraries or platform libraries, except SQLite. SQLite itself is ported to most platforms you'd ever care about. It's often a good alternative to MySQL, the Microsoft JET engine or the MSDE, without having any of their license and deployment issues. pysqlite can be downloaded from http://pysqlite.org/ - Sources and Windows binaries for Python 2.5, 2.4 and Python 2.3 are available. ======= CHANGES ======= - - Windows binaries are now cross-built using mingw on Linux - - import various fixes from Python 2.6 version - - Connection has new method iterdump() that allows you to create a script file that can be used to clone a database - - the docs are now built using Sphinx and were imported from Python 2.6's sqlite3 module - - Connection.enable_load_extension(enabled) to allow/disallow extension loading. Allows you to use fulltext search extension, for example ;-) - - Give the remaining C functions used in multiple .c source files the pysqlite_ prefix. - - Release GIL during sqlite3_prepare() calls for better concurrency. - - Automatically download the SQLite amalgamation when building statically. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIwZV3dIO4ozGCH14RAp1YAJwPIdgtCZY7E8YcDUjO/dzoAThblgCggfhs OATfXAb6JYXqb8eTadl9k74= =KU3f -----END PGP SIGNATURE----- From dmitry at athabascau.ca Thu Sep 25 16:38:03 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 20:38:03 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> <48db50aa$0$3750$426a74cc@news.free.fr> <HoOCk.1756$Pv5.1315@edtnps83> <48dbc82e$0$1120$426a74cc@news.free.fr> <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> <nFQCk.1781$Pv5.1597@edtnps83> <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> <QKRCk.1801$Pv5.525@edtnps83> <1fc9b5c2-0e58-4b48-9352-4122986ce7ec@k13g2000hse.googlegroups.com> Message-ID: <LESCk.1818$Pv5.481@edtnps83> George Sakkis wrote: > I'm not sure if the approach below deals with all the issues, but one > thing it does is decouple completely the proxied objects from the > proxy: <snip/> > class _ProxyMeta(type): <snip/> It smelled to me more and more like metaclass too, I was just trying to avoid them :) Your code looks awefully close to what I'm trying to do, except it looks bit heavier than decorators. Seems like decorators are not going to happen in this part of project for me anyway, however the whole discussion gave me a lot to think about. Thank you Bruno, Aaron, Diez and George. Thanks for the concrete code with metaclass. I'm going to study it thoroughly to see if I can spot caveats/issues for my usecases however it seems to put me on the right track. I never used metaclasses before and decorators seemed to be bit more straight-forward to me :) ..oh well. From bj_666 at gmx.net Mon Sep 1 08:11:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2008 12:11:38 GMT Subject: Know if a object member is a method References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> <mailman.319.1220259149.3487.python-list@python.org> <pan.2008.09.01.09.35.37@REMOVE.THIS.cybersource.com.au> <mailman.320.1220262347.3487.python-list@python.org> Message-ID: <6i24fqFo7morU1@mid.uni-berlin.de> On Mon, 01 Sep 2008 11:45:36 +0200, Luca wrote: >> But not so easy to fool a type check: >> >>>>> type(x) == new.function >> False >> >> Of course that's not bullet-proof either. I leave it as an exercise to >> discover how you might break that piece of code. >> >> > Ok, so... > > What is the best way to do this? The "most pythonic"? The "most pythonic" might be not checking at all but simply *call* the object and deal with possible failures. What's your use case? Ciao, Marc 'BlackJack' Rintsch From ldo at geek-central.gen.new_zealand Thu Sep 25 18:20:58 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 10:20:58 +1200 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: <gbh2sa$9j1$1@lust.ihug.co.nz> In message <24ac4a18-049f-4ae0-892a-d3fc84995c9d at a18g2000pra.googlegroups.com>, Craig Allen wrote: > It is clearly possible to write procedural code... that is, > Python does not force object oriented syntax or concepts on you ... Object orientation IS procedural. From fredrik at pythonware.com Thu Sep 18 05:26:09 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Sep 2008 11:26:09 +0200 Subject: How to Determine Name of the Day in the Week In-Reply-To: <48D1C8F2.6040308@gmail.com> References: <fee514130809111011m8af23aas7c02512de1a4f6cb@mail.gmail.com> <gabjpp$as1$2@ger.gmane.org> <48D1C8F2.6040308@gmail.com> Message-ID: <gat6ri$ejr$1@ger.gmane.org> Keo Sophon wrote: > I've tried calendar.month_name[0], it displays empty string, while > calendar.month_name[1] is "January"? Why does calendar.month_name's > index not start with index 0 as calendar.day_name? the lists are set up to match the values used by the time and datetime modules; see e.g. http://docs.python.org/lib/module-time.html http://docs.python.org/lib/datetime-date.html </F> From nicolegraves0281 at gmail.com Sat Sep 20 05:46:35 2008 From: nicolegraves0281 at gmail.com (maria sujane) Date: Sat, 20 Sep 2008 02:46:35 -0700 (PDT) Subject: >>>> FREE online Fashions and Naughty Girls AMAZING video MOVIE clips <<<< Message-ID: <de27c75f-60ae-4ad0-9f31-d98c15dc8d40@c22g2000prc.googlegroups.com> Naughty Free Live Sex Web Cams & ChatClick here for free live sex web cams & chat online. Straight, Gay, Lesbian, Swingers, and more. Get sexy and broadcast your own cam. Chat for free. MOre... [b] http://urlaxe.com/modfxmodels [/b] http://join.digitaldesire.com/track/OTMxNzozOjE/ http://www.absolutevids.com/?revid=60008&s=0&campaign=0,AbsoluteVids,absolutevids,absv,0,0 From FettManChu at gmail.com Thu Sep 4 16:55:12 2008 From: FettManChu at gmail.com (Fett) Date: Thu, 4 Sep 2008 13:55:12 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: <afe2ccf2-b9ce-48e6-9f2d-3be79f8d0439@q26g2000prq.googlegroups.com> <7xwshr4qr4.fsf@ruckus.brouhaha.com> Message-ID: <ab2bcc13-2b21-49df-8b20-35893d1324be@r66g2000hsg.googlegroups.com> On Sep 4, 3:09?pm, Paul Rubin <http://phr... at NOSPAM.invalid> wrote: > Fett <FettMan... at gmail.com> writes: > > Is there any crypto package that is actually written in python? I > > seriously don't care how slow it is. > > I wrote a simple symmetric encryption function in python: > > ?http://nightsong.com/phr/crypto/p3.py > > I wrote a somewhat fancier package that did public key a while back, > that is unreleased because of insufficient testing and some features > I'd like to have done differently, but I ought to get around to > cleaning it up sometime. > > There is also tlslite, which you might be able to extract > some public key functions from: ?http://trevp.net/tlslite Wow, I have no idea how that works, but I think it will do nicely. The main goal is simply to ensure that data coming in (from a website), is valid (ie. posted by me). The site is supposedly secure, and the code only accepts data of the type I expect, so the only security risk was someone posting bad data. This simple method should stop anyone from bothering to do even that. Kudos for writing the code in a way that I can see how it is used, even without documentation this is small enough to dissect. Thank you, I think we have a winner. (BTW, I have no idea how this whole encrypting gives many strings, decrypting all gives the correct one works, but it sure seems to work just fine, more fully featured than I even felt I needed.) From san82moon at gmail.com Mon Sep 1 07:26:14 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 04:26:14 -0700 (PDT) Subject: how to find position of dictionary values References: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> <48bbab73$0$27858$426a34cc@news.free.fr> <e9b3e12c-3834-48ff-911b-baf01efdb8c3@r15g2000prh.googlegroups.com> <6i1rgcFo0f1gU1@mid.uni-berlin.de> <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> <g9ghtv$48i$1@inews.gazeta.pl> Message-ID: <6645c39a-3cb8-4f34-bbd3-2c4fe8210167@s20g2000prd.googlegroups.com> On Sep 1, 3:59 pm, Wojtek Walczak <gmin... at bzt.bzt> wrote: > On Mon, 1 Sep 2008 03:51:13 -0700 (PDT), lee wrote: > > i am soory for that keystrokes. can anyone tell me how can i change > > the value of key. > > suppose i have a dictionary > > > kev = {'kabir': ['ka... at kabir.com', '1234', 'missuri'], 'shri': > > ['s... at shri.com', '23423', 'india'], 'marsa': ['ma... at marsa.com', > > '2345', 'brazil'], 'sandeep': ['sand... at sandeep.com', '007', > > 'canada']} > > how can i change the key to something like 'sabir' and > > kev['sabir'] = kev['kabir'] > del kev['kabir'] > > > how can i > > change the values of kabir? > > kev['sabir'][0] = 'sa... at sabir.com' > > *untested* > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ thanks wojtek, it worked :) From nytrokiss at gmail.com Wed Sep 17 19:20:31 2008 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 17 Sep 2008 16:20:31 -0700 Subject: locks In-Reply-To: <18641.17709.251764.767222@montanaro-dyndns-org.local> References: <48D140FC.8070801@el.net> <18641.17709.251764.767222@montanaro-dyndns-org.local> Message-ID: <8a6b8e350809171620p61280df6j5e5fece940251cf6@mail.gmail.com> You might also want to paste the output into a pastbin such as dpaste.com On Wed, Sep 17, 2008 at 10:58 AM, <skip at pobox.com> wrote: > > kalin> mailman has been locking one list out. the web interface just > kalin> hangs and it generates a bunch of locks. it seems that it can not > kalin> write to a log but not sure which one. errors are like: > ... > > You'd probably be better off asking about Mailman problems on > mailman-users at python.org. > > -- > Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080917/b69cc256/attachment-0001.html> From uomiocenekidd at gmail.com Mon Sep 22 06:39:29 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:39:29 -0700 (PDT) Subject: redtube xtube youporn - Free Message-ID: <6640c064-bd8e-4e08-b1cf-70a971588559@8g2000hse.googlegroups.com> redtube xtube youporn . . . *******CLICK HERE******** http://vids365.cn/redtube-xtube-youporn ***************************** . . . . . . . . . . . . redtube xtube youporn From marco.bizzarri at gmail.com Mon Sep 1 07:18:16 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 1 Sep 2008 13:18:16 +0200 Subject: Retrieving http headers from HTTPConnection object In-Reply-To: <bda7ac6d0809010406j3a218984q8e6f1d9fb80b6abb@mail.gmail.com> References: <bda7ac6d0809010406j3a218984q8e6f1d9fb80b6abb@mail.gmail.com> Message-ID: <3f0d61c40809010418n10a2c747i82d8a6c6317bbf39@mail.gmail.com> On Mon, Sep 1, 2008 at 1:06 PM, jorma kala <jjkk73 at gmail.com> wrote: > Hi, > > when using httplib for http requests, like for example: > > > conn = httplib.HTTPConnection("www.python.org") > conn.request("GET", "/index.html") > > Is it possible to retrieve the complete http request in string form : > > > GET /index.html HTTP/1.1 > Host: www.python.org > User-Agent: ... > Accept: ... > Accept-Language: > Accept-Encoding: > Accept-Charset: > Keep-Alive: > Connection: > > I mean does the HTTPConnection object have a property that stores this ? > or is it retrievable by some other form? > > Thanks a lot. > -- Looking at the code of HTTPConnection, all that goes through the _output message (including, therefore, the putheaders) are appended to the self._buffer list. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From aonlazio at gmail.com Tue Sep 23 21:05:27 2008 From: aonlazio at gmail.com (AON LAZIO) Date: Tue, 23 Sep 2008 21:05:27 -0400 Subject: Property Function Message-ID: <f9e39bbc0809231805g7bb62301hdef24c30bdba2090@mail.gmail.com> Hi, In python code, class A: get(self): do something set(self): do something g=property(get,set) what is the good use of "property" function?, I do not understand clearly.. Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080923/edcaeb0d/attachment-0001.html> From bj_666 at gmx.net Mon Sep 1 08:19:15 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2008 12:19:15 GMT Subject: Python 3.0b2 cannot map '\u12b' References: <d0652dd2-24f6-4045-89a8-ba6deaf25b37@c65g2000hsa.googlegroups.com> <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> <mailman.312.1220250492.3487.python-list@python.org> Message-ID: <6i24u3Fo7morU2@mid.uni-berlin.de> On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: > I doubt the OP 'chose' cp437. Why does Python using cp437 even when the > default encoding is utf-8? > > On WinXP > >>> sys.getdefaultencoding() > 'utf-8' > >>> s='\u012b' > >>> s > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "C:\Program Files\Python30\lib\io.py", line 1428, in write > b = encoder.encode(s) > File "C:\Program Files\Python30\lib\encodings\cp437.py", line 19, in > encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] > UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in > position > 1: character maps to <undefined> Most likely because Python figured out that the terminal expects cp437. What does `sys.stdout.encoding` say? > To put it another way, how can one 'choose' utf-8 for display to screen? If the terminal expects cp437 then displaying utf-8 might give some problems. Ciao, Marc 'BlackJack' Rintsch From rridge at csclub.uwaterloo.ca Fri Sep 26 23:10:06 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 26 Sep 2008 23:10:06 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48db462f$0$24356$426a74cc@news.free.fr> <gbgulu$moi$1@rumours.uwaterloo.ca> <48dc952b$0$2289$426a74cc@news.free.fr> Message-ID: <gbk86e$kph$1@rumours.uwaterloo.ca> Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> wrote: > Also note that there are quite a couples cases where the library authors > themselves cannot predict which exception types may be raised - as soon > as the library functions expect callback functions, file-like or > dict-like or whatever-like objects etc, it's the caller's responsability > to handle the exceptions that may be raised by what *he* passes to the > library... Ross Ridge a ?crit : > Ug... that's another documentation pet-peeve of mine. Libraries that > say they take file-like (or whatever-like) object, but don't say exactly > how file-like it needs. Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> wrote: >Seems not to be such a problem in practice... Not if you don't mind figuring out such things by trial and error or looking at the source. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From grflanagan at gmail.com Thu Sep 18 11:43:36 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 18 Sep 2008 17:43:36 +0200 Subject: dict generator question In-Reply-To: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> Message-ID: <gatsv6$buv$1@ger.gmane.org> Simon Mullis wrote: > Hi, > > Let's say I have an arbitrary list of minor software versions of an > imaginary software product: > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > I'd like to create a dict with major_version : count. > > (So, in this case: > > dict_of_counts = { "1.1" : "1", > "1.2" : "2", > "1.3" : "2" } > [...] data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] from itertools import groupby datadict = \ dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) print datadict From stef.mientki at gmail.com Fri Sep 12 16:00:18 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 12 Sep 2008 22:00:18 +0200 Subject: GUI programming with python In-Reply-To: <gaecmh$pb0$1@panix5.panix.com> References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> <gaecmh$pb0$1@panix5.panix.com> Message-ID: <48CACA52.5050001@gmail.com> Al Dykes wrote: > In article <1bs69ogq6nspt.136i7kvcux142$.dlg at 40tude.net>, > Alan Franzoni <alan.franzoni.xyz at gmail.com> wrote: > >> zamil was kind enough to say: >> >> [cut] >> >> If your needs are very basic, you can stick with the tk module that comes >> with python. It's not really feature-packed, but it's maintained and pretty >> cross-platform. >> > > > OK, what are my choices for an IDE/GUI development tool that runs on XP? > > Thanks > > > > From Linux guys, I hear that PyScripter is the best, they also want to have it, but unfortunately it only runs under windows ;-) cheers, Stef > From wgwigw at gmail.com Sat Sep 27 21:53:54 2008 From: wgwigw at gmail.com (momobear) Date: Sat, 27 Sep 2008 18:53:54 -0700 (PDT) Subject: what's difference usage? Message-ID: <8ce3d2b7-8d24-4770-9ed9-acf8ce23eaea@w24g2000prd.googlegroups.com> while as I try to wrap a function using boost-python, I find a strange situation. #include <iostream> #include <string> #include <vector> #include <boost/python/list.hpp> #include <boost/python.hpp> using namespace boost::python; int printlist(list &l){ std::vector<std::string> a; a.push_back("c++"); a.push_back("javascript"); for (std::vector<std::string>::iterator p = a.begin(); p != a.end(); + +p) l.append(*p); return 0; } BOOST_PYTHON_MODULE(wlist){ def("printlist", printlist); } in the up code,"int printlist(list &l)" at first time I missed add & left of l. but when I run the following python code, #!/usr/local/bin/python a = list() a.append('linux') import wlist wlist.printlist(a) print a they get the same result. linux c++ javascript anyone help me figure out what's wrong here. thanks. From skip at pobox.com Fri Sep 26 22:33:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 26 Sep 2008 21:33:07 -0500 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <35681490-2d50-4a51-ae88-c1538ed51e15@y21g2000hsf.googlegroups.com> References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <dZOdnQINKORUEUDVnZ2dnUVZ_rvinZ2d@posted.usinternet> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> <35681490-2d50-4a51-ae88-c1538ed51e15@y21g2000hsf.googlegroups.com> Message-ID: <18653.39779.419435.495239@montanaro-dyndns-org.local> >> > I read the group via NNTP, and I find that blocking all articles >> > posted from google.groups gets rid of all of the spam. >> >> ... along with a far from trivial (I guess) percentage of non-spam, >> such as this post. Aaron> Every method has false positives, George. (including this one.) George makes a good point though, and it is a key element of how SpamBayes works. A single clue is not a binary selector for ham or spam. Skip From benjamin.kaplan at case.edu Fri Sep 26 10:50:52 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 26 Sep 2008 10:50:52 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> Message-ID: <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> On Fri, Sep 26, 2008 at 10:38 AM, Michael Mabin <d3vvnull at gmail.com> wrote: > I laugh in the face of danger. > > Give me a use case for an exploit. > http://xkcd.com/327/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/4c2187f1/attachment-0001.html> From gagsl-py2 at yahoo.com.ar Tue Sep 30 00:17:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 01:17:50 -0300 Subject: Finding subsets for a robust regression References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> <f5ac3b99-234c-4304-b3f0-2c1eff7cba12@y38g2000hsy.googlegroups.com> Message-ID: <op.uh90v0vtx6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 29 Sep 2008 17:04:48 -0300, <bearophileHUGS at lycos.com> escribi?: > result_x = uniques_x.keys() > result_y = map(median, uniques_x.itervalues()) > > I think it works because keys and values are given in the same order, > but in real code I tend to avoid using such subtle things. Because if > you translate that code to another language, or you use another Python > implementation it may not work anymore, and lot of code sooner or > later becomes translated... At least with respect to different Python implementations, it *is* clearly stated in the documentation that "If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond." http://docs.python.org/lib/typesmapping.html -- Gabriel Genellina From ivanov.maxim at gmail.com Fri Sep 26 11:08:09 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Fri, 26 Sep 2008 08:08:09 -0700 (PDT) Subject: multiprocessing eats memory References: <mailman.1497.1222346460.3487.python-list@python.org> <edd14466-262f-4333-8823-601fd682659d@c36g2000prc.googlegroups.com> <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> <afb35903-97ab-45d0-a4e0-fcca2aded20b@25g2000hsx.googlegroups.com> Message-ID: <d070b438-877f-47eb-90af-f45fbe58a8ee@m36g2000hse.googlegroups.com> On 26 ????, 17:03, MRAB <goo... at mrabarnett.plus.com> wrote: > On Sep 26, 9:52?am, redbaron <ivanov.ma... at gmail.com> wrote: > > > On 26 ????, 04:20, Istvan Albert <istvan.alb... at gmail.com> wrote: > > > > On Sep 25, 8:40?am, "Max Ivanov" <ivanov.ma... at gmail.com> wrote: > > > > > At any time in main process there are shouldn't be no more than two copies of data > > > > (one original data and one result). > > > > From the looks of it you are storing a lots of references to various > > > copies of your data via the async set. > > > How could I avoid of storing them? I need something to check does it > > ready or not and retrieve results if ready. I couldn't see the way to > > achieve same result without storing asyncs set. > > You could give each worker process an ID and then have them put the ID > into a queue to signal to the main process when finished. And how could I retrieve result from worker process without async? > > BTW, your test-case modifies the asyncs set while iterating over it, > which is a bad idea. My fault, there was list(asyncs) originally. From fredrik at pythonware.com Fri Sep 12 10:52:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 16:52:11 +0200 Subject: Matching horizontal white space In-Reply-To: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> References: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> Message-ID: <gadvmu$pe2$1@ger.gmane.org> Magnus.Moraberg at gmail.com wrote: > multipleSpaces = re.compile(u'\\h+') > > importantTextString = '\n \n \n \t\t ' > importantTextString = multipleSpaces.sub("M", importantTextString) what's "\\h" supposed to mean? > I would have expected consecutive spaces and tabs to be replaced by M > but nothing is being replaced. if you know what you want to replace, be explicit: >>> importantTextString = '\n \n \n \t\t ' >>> re.compile("[\t ]+").sub("M", importantTextString) '\nM\nM\nM' </F> From bignose+hates-spam at benfinney.id.au Tue Sep 30 08:19:57 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 Sep 2008 22:19:57 +1000 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> <87zllqqa1i.fsf@benfinney.id.au> <pan.2008.09.30.10.04.18@REMOVE.THIS.cybersource.com.au> Message-ID: <87prmlrfki.fsf@benfinney.id.au> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes: > On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > > You're not free to modify gnuplot and redistribute the result. > > > > That you're free to distribute patches is nice, but it's not > > enough to make the work free. The freedom to help people by giving > > them an *already-modified* gnuplot is restricted by the copyright > > holder. > > > > It's an artificial restriction on redistribution of derived works, > > making them second-class for the prupose of getting them into > > people's hands. > > Yes it is. It seems a strange, unnecessary restriction. But is it > sufficient to make it non-free? I don't think so. I do, because a natural, beneficial act (modify the work and redistribute it) that has no technical reason to restrict, is artifically restricted. > In case you are thinking that gnuplot allows people to *only* > distribute the diffs, not the original source to apply the diffs > onto, that is not the case. I quote from gnuplot > help copyright > > "Permission to distribute the released version of the source code > along with corresponding source modifications in the form of a patch > file is granted with same provisions 2 through 4 for binary > distributions." That's what I refer to when I say that it artifically makes derived works into second-class for the purpose of doing the beneficial act of distributing them: the redistributor is artificially restricted from making the work as useful as the original they received. They have only the options to redistribute a work that is more cumbersome for the recipient of that work, or not to redistribute at all. That's not free redistribution. > > I try to judge freedom of a software work by the freedoms granted > > to all recipients of the work, not by the approval of some > > organisation. > > Yes, but you accept some restrictions as legitimate. For example, you > accept the restriction that the GPL makes that says you may not > redistribute a modified work without making the source code available. Yes, which is why I was careful to say "the freedoms granted to all recipients of the work". The power to restrict a recipient of one's work (by choosing not to grant them the freedoms you yourself had when you received the work) reduces the freedoms available to all recipients of the work, even though one party's power may be increased. This is where the useful "your freedom to swing your fist ends at the tip of the other man's nose" applies: As soon as the act you wish to perform is restricting the freedom of another, you're not contemplating an act of freedom, but an act of power over another. Freedoms should be protected, but only within the limits imposed by the freedoms of others. > That's a restriction, but it's not enough to disqualify it from > being a free software licence. Specifically because it upholds the freedom of the recipient of a derived work from having power exerted over them. > In fact, that restriction is *necessary* to make it a free software > licence in the sense we're talking about. Not really; it's necessary to make it a copyleft license, which is a way of preserving freedom as the work gets passed along. Works can still be free software without being copyleft-licensed, though. A license allowing free redistribution and requiring only attribution be preserved is less restrictive than a copyleft; yet, because it allows any free act (even as it also allows acts of power over others), the work is free software. > So "free" does not mean "no restrictions", it merely means "none of > some sorts of restrictions, but other restrictions are okay". > Likewise the restriction that GPL software must be distributed with > a copy of the appropriate licence. That's right, and I've explained above what restrictions I consider justified, and why, and how to tell the difference. -- \ ?Reichel's Law: A body on vacation tends to remain on vacation | `\ unless acted upon by an outside force.? ?Carol Reichel | _o__) | Ben Finney From a at nospam.org Mon Sep 15 16:45:38 2008 From: a at nospam.org (Armin) Date: Mon, 15 Sep 2008 22:45:38 +0200 Subject: append on lists In-Reply-To: <mailman.1064.1221510115.3487.python-list@python.org> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> Message-ID: <gamgn9$5r5$1@online.de> Chris Rebert wrote: > On Mon, Sep 15, 2008 at 1:24 PM, Armin <a at nospam.org> wrote: >> >> Hi, >> >> just a dumb question. >> >> Let a = [1,2,3,4,5] >> >> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? > I'll assume the presence of the 6 is a typo. Sorry, that's the case. > > Because .append() mutates 'a' and appends the item in-place rather > than creating and returning a new list with the item appended, and > it's good Python style for mutating methods to have no return value > (since all functions must have some return value, Python uses None > when the function doesn't explicitly return anything). Yes, but this is very unconvenient. If d should reference the list a extended with a single list element you need at least two lines a.append(7) d=a and not more intuitive d = a.append(7) --Armin > > If you print 'a' after doing the .append(), you'll see it's changed to > your desired value. > > Regards, > Chris > >> --Armin >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 15:41:28 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 21:41:28 +0200 Subject: Python on the web - newby question In-Reply-To: <6822d749-cc00-48ce-a30a-ded96a938e79@b30g2000prf.googlegroups.com> References: <6822d749-cc00-48ce-a30a-ded96a938e79@b30g2000prf.googlegroups.com> Message-ID: <48bf0459$0$27459$426a74cc@news.free.fr> SimonPalmer a ?crit : > Apologies in advance if this is either a) the wrong board or b) been > answered a million times elsewhere, but... > > I have been given an assignment to get a python module up and running > behind an existing web site. At the moment the rest of the site is > developed in PHP but the hosts have said they will provide python > support for free, although they haven't given any more details than > that, so I'm not sure exactly what that means. Depending on the hosts, this can range from having an antiquated python version with only cgi enabled and no way to install anything to the very last stable release and (almost) whatever third-part lib / frameworks and correct configuration. > All reasonably > encouraging though. > > I'm a newbie to python but quite experienced with Java/J2EE/JBoss. Quite another world... > What I need to know is how I get python running on the server For which definition of 'server' ? The computer, or the web server process ? > and what > tools/middleware I would need to have installed on the host's machines > to be able to support my python modules. Depends on your modules dependencies !-) More seriously : Python is known has being the language with more web frameworks than keywords. IOW, there's no simple straightforward answer to your question. Fisrt choose which Python web development solution you intend to use, then read the FineManual's "deployment" section of the chosen solution. You'll find pointers to most web-related libs / frameworks here: http://wiki.python.org/moin/WebFrameworks http://wiki.python.org/moin/WebProgramming Given your situation (Python newcomer with a real job to do), and if your job is anything more than a very Q&D deadsimple task, I'd personnaly recommand Django (http://djangiproject.com). Don't let the version number fools you (latest version is 1.0 release candidate), Django is a mature, solid and proven solution that have years of existance, and what they call 1.0rc would be labeled at least 3.5 for some other software... It's also mostly documented, and there's a strong community around the framework, so you should not have much problem getting help. For any other Python question (I mean, non django-related), you're at the right place. Oh, and yes, if I may suggest a reading: http://dirtsimple.org/2004/12/python-is-not-java.html HTH, and welcome on board... From bdesth.quelquechose at free.quelquepart.fr Fri Sep 5 19:03:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 Sep 2008 01:03:30 +0200 Subject: Files application architecture In-Reply-To: <mailman.568.1220632312.3487.python-list@python.org> References: <mailman.568.1220632312.3487.python-list@python.org> Message-ID: <48c1d6b2$0$15607$426a74cc@news.free.fr> Benjamin Watine a ?crit : > Hi, > > I'm about to develop a small python application and I wonder how to > organize files in this application. > I'm familar to java, so I'm tempted to use the same convention http://dirtsimple.org/2004/12/python-is-not-java.html > : 1 file > per class and 1 folders per package. Don't. This is a waste of time and a pain to maintain, and more over it doesn't make any sense since Python doesn't force you to put everything in classes. > I know that packages doesn't exists in python, Did you actually read the doc ? While Python's packages are not the same thing as Java's, they do exist. http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > they are modules instead. > May I create specific module for each "group of class" ? The usual way to get cohesive modules is indeed to group closely related objects (classes, functions, etc) in a same module. > My application > follow the MVC paradigm, so basically, I've a package Model, a package > View, and a package Controller. If your app is small, having _modules_ models, views and controllers should be enough. > So, what are best practices for organizing files and folders in a small > python project ? The best practice is to keep things simple, as usual. From default at defaulter.net Sat Sep 27 18:47:16 2008 From: default at defaulter.net (default) Date: Sat, 27 Sep 2008 18:47:16 -0400 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> Message-ID: <f1dtd45fij5nu9uvnico53cab73uj6pdev@4ax.com> On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko <milenko.stojadinovic at googlemail.com> wrote: >Hello, this is Milenko Stojadinovic from town Banjaluka, >Bosnia and Herzegovina, also known as Cvrcko >Does anyone know of any bars in town where I can >swallow a bucket of cum? It can be either dog, >horse or human cum. Also, does anyone know of >any sex bars where people will shit in your mouth? >I also like eating shit. Come to the US and park your mouth in front of George Bush - all the Bshit you can eat - and it keeps on coming! I have a buddy in Bosna - he's normal. -- ----== Posted via Pronews.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.pronews.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= - Total Privacy via Encryption =--- From electronixtar at gmail.com Sun Sep 28 05:21:18 2008 From: electronixtar at gmail.com (est) Date: Sun, 28 Sep 2008 02:21:18 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <00ef3c23$0$20666$c3e8da3@news.astraweb.com> Message-ID: <ab60c0e2-dc25-4258-a070-c898e08c8b25@v39g2000pro.googlegroups.com> On Sep 28, 4:38?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Sat, 27 Sep 2008 22:37:09 -0700, est wrote: > >>>> str(u'\ue863') > > Traceback (most recent call last): > > ? File "<stdin>", line 1, in <module> > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > > position 0 > > : ordinal not in range(128) > > > FAIL. > > What result did you expect? > > [...] > > > The problem is, why the f**k set ASCII encoding to range(128) ???????? > > while str() is internally byte array it should be handled in range(256) > > !!!!!!!!!! > > To quote Terry Pratchett: > > ? ? "What sort of person," said Salzella patiently, "sits down and > ? ? *writes* a maniacal laugh? And all those exclamation marks, you > ? ? notice? Five? A sure sign of someone who wears his underpants > ? ? on his head." -- (Terry Pratchett, Maskerade) > > In any case, even if the ASCII encoding used all 256 possible bytes, you > still have a problem. Your unicode string is a single character with > ordinal value 59491: > > >>> ord(u'\ue863') > > 59491 > > You can't fit 59491 (or more) characters into 256, so obviously some > unicode chars aren't going to fit into ASCII without some sort of > encoding. You show that yourself: > > u'\ue863'.encode('mbcs') ?# Windows only > > But of course 'mbcs' is only one possible encoding. There are others. > Python refuses to guess which encoding you want. Here's another: > > u'\ue863'.encode('utf-8') > > -- > Steven OK, I am tired of arguing these things since python 3.0 fixed it somehow. Can anyone tell me how to customize a default encoding, let's say 'ansi' which handles range(256) ? From brennan.ron at gmail.com Wed Sep 17 17:30:54 2008 From: brennan.ron at gmail.com (Ron Brennan) Date: Wed, 17 Sep 2008 17:30:54 -0400 Subject: Configuration Parsers Message-ID: <26c69b160809171430x7f020672geb2be7ddd606a462@mail.gmail.com> Hello, I am trying to parse a shared config file which doesn't contail section headers. Is there a way I can still use ConfigParser()? If not what is a widely used parser available? Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080917/7a7915f1/attachment-0001.html> From deets at nospam.web.de Thu Sep 25 16:22:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:22:12 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: <mailman.1506.1222370612.3487.python-list@python.org> References: <mailman.1506.1222370612.3487.python-list@python.org> Message-ID: <6k2a7lF5nf4eU1@mid.uni-berlin.de> Scott Sharkey schrieb: > Hello all, > > Our development group at work seems to be heading towards adopting > python as one of our standard "systems languages" for internal > application development (yeah!). One of the issues that's come up is > the problem with apt (deb packages) vs eggs, vs virtual environments. > We're probably gonna end up using Pylons or TurboGears for web-based > apps, and I've recommended virtualenv, but one of the other developers > has had some "inconsistencies" when mixing systems with python installed > from apt (all our servers are debian or ubuntu based) vs when installed > under virtualenv. > I have basically recommended that we only install the python base (core > language) from apt, and that everything else should be installed into > virtual environments. But I wanted to check to see how other enterprises > are handling this issue? Are you building python from scratch, or using > specific sets of .deb packages, or some other process. > > Any insight into the best way to have a consistent, repeatable, > controllable development and production environment would be much > appreciated. This is the exact way we are deploying our software. You can even use the virtualenv --no-site-packages option to completely isolate the VE from the underlying system site-packages. I would recommend that all you install into the system python is virtualenv, and maybe some uncritical C-modules such as psycopg2. Currently there is much going on regarding setuptools. A fork, "Distribute" has been announced, and "pyinstall" by Ian Bicking, an easy_install replacement that deals with some of it's ancestors shortcomings. Then people (shameless plug warning: including me) are working on "eggbasket", a PYPI-clone that allows to have a local repository of eggs so that you don't fall prey to old versions not longer available on PYPI. Eggbasket will feature "easterbunny", a tool to publish a virtualenv as whole to the eggbasket and also keep track of the precise version set uploaded. Through a specific url on eggbasket you can then limit the contents of eggbasket to that exact version set - which helps dealing with subtle (or not so subtle) version conflicts. I personally can say that I'm really thrilled by the prospects of all these developments. And as much bad rap as setuptools had here and elsewhere, sometimes rightfully so - it certainly does a lot of stuff right, and pushing the whole stack of tools to manage software dependencies in Python to the next level is of great value. Diez From clp at rebertia.com Mon Sep 15 17:15:52 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Sep 2008 14:15:52 -0700 Subject: Python Nautilus script In-Reply-To: <6j80nvF1ttmfU1@mid.uni-berlin.de> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> <mailman.1074.1221512008.3487.python-list@python.org> <6j80nvF1ttmfU1@mid.uni-berlin.de> Message-ID: <47c890dc0809151415n270d8fdbpafff58e5f612423a@mail.gmail.com> On Mon, Sep 15, 2008 at 2:00 PM, Diez B. Roggisch <deets at nospam.web.de> wrote: >>>> It appears that's because HOSTNAME is not exported. >>>> But in the case of Nautilus script, how to workaround this issue? >> >> Alternatively, export the variable when you create it, in .bashrc or >> wherever it is getting created. That's probably the Right Thing to >> Do(tm) in this case. > > > Certainly not, as the OP uses a network monitoring software called Nautilus > - and that communicates state to subprocesses using environment variables. > Nothing to do with .bashrc. Just to clarify, the OP is talking about Nautilus as in the GNOME file manager, not some network monitor. - Chris > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From mrkafk at gmail.com Wed Sep 3 11:40:43 2008 From: mrkafk at gmail.com (mk) Date: Wed, 03 Sep 2008 17:40:43 +0200 Subject: properties setting each other In-Reply-To: <200809031644.10870.maric@aristote.info> References: <g9m54v$hvk$1@ger.gmane.org> <200809031644.10870.maric@aristote.info> Message-ID: <g9mb5s$a5b$1@ger.gmane.org> Thanks to everyone for answers.. > *but*, if you want to add more logic in the setters, you could want to add two > extra methods : > > def _setsquare(self, v) : > # some extra logic here > self._square = s > > def fsetsquare(self,s): > self._setsquare(s) > self._setvalue = math.sqrt(s) > > def _setvalue(self, val): > # some extra logic here > self._internalval=val > > def fsetvalue(self, val): > self._setvalue(val) > self._setsquare=pow(val,2) > Thanks for that, I'll keep that in mind. > Note that if one property can really be computed from another, this kind of > thing could be considered as bad design (except if the computation is heavy). Hmm, why? Is the line of thinking smth like: because the variables should be kept to minimum and they should be calculated at the moment they are needed? From deets at nospam.web.de Wed Sep 10 17:30:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 23:30:49 +0200 Subject: formating a filesystem with python In-Reply-To: <mailman.829.1221081866.3487.python-list@python.org> References: <mailman.828.1221080255.3487.python-list@python.org> <6iqrm2F3rqcU1@mid.uni-berlin.de> <mailman.829.1221081866.3487.python-list@python.org> Message-ID: <6iqsk9F3lbaU1@mid.uni-berlin.de> Ricardo Tiago schrieb: > I understand that this is a very sensible unix question but i think > fuse does this at least it mounts. I was wondering if there were other > packages with similar functionality. I don't know what fuse is. And *mounting* can be allowed to be made by users. and possibly there is a mount-daemon that can mount e.g. usb-devices. but that wouldn't be a pure python-module-solution either. Diez From roy at panix.com Sun Sep 14 13:56:44 2008 From: roy at panix.com (Roy Smith) Date: Sun, 14 Sep 2008 13:56:44 -0400 Subject: Abstract class References: <mailman.1008.1221408214.3487.python-list@python.org> Message-ID: <roy-9FFFBD.13564414092008@news.panix.com> In article <mailman.1008.1221408214.3487.python-list at python.org>, Mr.SpOOn <mr.spoon21 at gmail.com> wrote: > I have to manage many elements of music such as notes, intervals, > scales, chords and so on. All these elements share properties and > behavior, so what I want to do is an abstract class "Note" and other > subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. What properties or behaviors does SharpNote have which NaturalNote doesn't? Unless there is some new behavior, you don't need subclasses. Are you also going to have DoubleSharpNote and DoubleFlatNote? Consider the following code: note1 = SharpNote("E4") note2 = NaturalNote("F4") if note1 == note2: print "the same note" else print "different notes" what should it print? From torainLight at gmail.com Sat Sep 20 05:28:15 2008 From: torainLight at gmail.com (satoru) Date: Sat, 20 Sep 2008 02:28:15 -0700 (PDT) Subject: how can i check whether a variable is iterable in my code? Message-ID: <b29d40b7-4000-4d75-b657-af73573c5c32@a8g2000prf.googlegroups.com> hi, all i want to check if a variable is iterable like a list, how can i implement this? From prologic at shortcircuit.net.au Mon Sep 8 05:29:21 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 19:29:21 +1000 Subject: Test if list contains another list In-Reply-To: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> Message-ID: <e1a84d570809080229r363e1b0fwd3409209954f8305@mail.gmail.com> Hi, >>> a = [1,2,3] >>> b = [3,2,1,4] >>> a = set(a) >>> b = set(b) >>> a.intersection(b) set([1, 2, 3]) Is this what you want ? cheers James On 9/8/08, mathieu <mathieu.malaterre at gmail.com> wrote: > Hi there, > > I am trying to write something very simple to test if a list > contains another one: > > a = [1,2,3] > > b = [3,2,1,4] > > but 'a in b' returns False. How do I check that a is indeed contained > in b ? > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From richardlev at gmail.com Thu Sep 11 12:45:31 2008 From: richardlev at gmail.com (Richard Levasseur) Date: Thu, 11 Sep 2008 09:45:31 -0700 (PDT) Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> <6inkkiFrbptbU1@mid.uni-berlin.de> <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> <6iqr3dF3msoU1@mid.uni-berlin.de> Message-ID: <e91c2424-7b31-4eb7-abe3-2b3e8c021264@r15g2000prd.googlegroups.com> On Sep 10, 2:04?pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > luigi.pai... at gmail.com schrieb: > > > > > On 9 Set, 17:55, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > >> I would go for a slightly different approach: make your server have a > >> dispatch-method that delegates the calls to the underlying actual > >> implementation. But *before* that happens, extract the information as > >> above, and either > > >> ?- prepend it to the argument list > > >> ?- stuff it into threadlocal variables, and only access these if needed in > >> your implementation. > > >> Diez > > > Are you suggesting me to overwrite the _dispatch(self, method, params) > > method of SimpleXMLRPCDispatcher? I thought to this possibility, but > > it only accepts "method" and "params" as arguments, so, as far as I > > know, I have no way to get the user and host address to append. > > > Perhaps I've misunderstood your suggestion... in that case can you > > post a short example? > > Ah, darn. Yes, you are right of course, the information itself is not > available, as you don't have access to the request. I gotta ponder this > a bit more. > > Diez Because he wants to insert parameters at the very start, he can probably get away with modifying the xml directly. Just find the position of the <params> (i think thats the tag) and insert the xml you need after it. Its pretty dirty, but would work. The wire format isn't that complicated. From marek.rocki at wp.pl Sun Sep 28 05:32:42 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Sun, 28 Sep 2008 02:32:42 -0700 (PDT) Subject: Calculating timespan References: <z0IDk.36$AK3.16@newsfe03.iad> Message-ID: <784049c7-a9cf-4006-873f-d3a869bf6b93@l64g2000hse.googlegroups.com> Erhard napisa?(a): > I've been looking at the date/time classes and I'm at a loss as to how > to do this (probably too used to other platforms). > > I have two date/time values. One represents 'now' and the other the last > modified time of a file on disk (from stat). I need to calculate the > difference in time (i.e., a 'timespan') between the two so I can tell if > the file has been modified in the past X minutes and do something to it. > > Thanks =) You can subtract one datetime object from another: from datetime import datetime, timedelta span = datetime.now() - datetime(year=2008,month=8,day=27,hour=12,minute=34,second=56) if span < timedelta(minutes=37): # do something From bdesth.quelquechose at free.quelquepart.fr Tue Sep 2 12:45:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Sep 2008 18:45:35 +0200 Subject: source for the property function In-Reply-To: <mailman.373.1220371338.3487.python-list@python.org> References: <mailman.373.1220371338.3487.python-list@python.org> Message-ID: <48bd899f$0$10446$426a74cc@news.free.fr> Rowland Smith a ?crit : > Anyone know where the source code for the built-in property function Actually, it's a class, not a function. > is > located in a python distribution? property being a builtin type, you should find it somewhere in the CPython's C source AFAICT. > I would like to see how it works - mainly, how does it know which class > it is being called from? No need to look at the source for this - it's just an application of the descriptor protocol. Look up the doc on python.org, or google for python descriptor protocol. FWIW, it's the same protocol that is used for turning functions into methods, and writing your own custom descriptors is trivial. HTH From pavlovevidence at gmail.com Sun Sep 28 05:29:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 28 Sep 2008 02:29:07 -0700 (PDT) Subject: Borg vs Singleton vs OddClass References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> Message-ID: <256d3ab0-6d8c-46b9-83a3-ea6817c67320@k37g2000hsf.googlegroups.com> On Sep 27, 2:12?pm, Lie <Lie.1... at gmail.com> wrote: > I'm thinking about this design pattern (I don't know if anyone has > ever thought of this pattern before): > > class OddClass(object): > ? ? def __init__(self): > ? ? ? ? global OddClass > ? ? ? ? OddClass = self > ? ? def __call__(): > ? ? ? ? return self > > The OddClass is a class that would overwrite its own class definition > at its first instantiation. OddClass defines __call__ so that > subsequent "instantiation" (technically it is no more an > instantiation, but Duck Typing says it does) of the class would return > the single instance. > > It do have a problem though, that you can't do isinstance(a, OddClass) > since the name OddClass no longer refers to the OddClass class > descriptor, but to an instance of OddClass. I recommend against your idiom above. The main issue I have about it is that it rebinds the symbol implicitly, which is almost always a bad idea. What if a user does something like "from oddclassmodule import OddClass"? Then the user will get a new instance every call since it never rebinds the imported symbol. Just don't do it this way. You could rewrite it like this to avoid the implicit rebinding, and to take care of the isinstance issue as well: class NotSoOddClass(object): def __new__(cls): self = getattr(cls,"_instance",None) if self is None: self = cls._instance = object.__new__(cls) return self Or you could just use a lazy factory function like this, where the user is only supposed to use Factory and not create the class directly: class _NotOddClass(object): # nothing odd def Factory(): obj = getattr(_NotOddClass,"_instance",None) if obj is None: obj = _NotOddClass._instance = NotOddClass() return obj If you're real kinky you can use a metaclass. There are reasons to prefer any of these. I'd recommend the factory function unless you think the users could significantly benefit from type inspection. Just don't do it by rebinding the class name. That's not nice. Carl Banks From dear.jay.logan at gmail.com Mon Sep 22 06:52:51 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 22 Sep 2008 03:52:51 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <f5df9f65-a13d-4f5f-9cf9-534d37dd04c0@f63g2000hsf.googlegroups.com> Message-ID: <5a37d7ca-e7b4-4278-8fc3-f5d0f4303cee@79g2000hsk.googlegroups.com> On Sep 22, 3:41?am, Arnaud Delobelle <arno... at googlemail.com> wrote: > On 22 Sep, 04:05, josh logan <dear.jay.lo... at gmail.com> wrote: > > > > > Hello, > > > I have 2 questions. Say I have this class: > > > class Player(object): > > ? ? def __init__(self, fname, lname, score): > > ? ? ? ? self.score = score > > ? ? ? ? self.fname = fname > > ? ? ? ? self.lname = lname > > ? ? def __cmp__(self, other): > > ? ? ? ? return (-cmp(self.score, other.score) or > > ? ? ? ? ? ? ? ? cmp(self.lname, other.lname) or > > ? ? ? ? ? ? ? ? cmp(self.fname, other.fname)) > > ? ? def __repr__(self): > > ? ? ? ? return 'Player(fname={0.fname}, lname={0.lname}, > > score={0.score})'.format(self) > > ? ? def __eq__(self, others): > > ? ? ? ? if isinstance(other, Player): > > ? ? ? ? ? ? return (self.score == other.score and > > ? ? ? ? ? ? ? ? ? ? self.lname == other.lname and > > ? ? ? ? ? ? ? ? ? ? self.fname == other.fname) > > ? ? ? ? return False > > ? ? def __ne__(self, others): > > ? ? ? ? return not self.__eq__(others) > > > fnames = ['Julie', 'Ben', 'Jason', 'David'] > > lnames = ['Parks', 'Smith'] > > scores = [100, 95, 95, 130, 58, 74] > > > import itertools as it > > > score_iter = it.cycle(scores) > > > P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in > > lnames] > > > cmp(P[0], P[1]) # returns -1 > > > sorted(P) # throws TypeError: unorderable types Player() < Player() > > > The sorted function works when I define __lt__. > > I must be misreading the documentation, because I read for the > > documentation __cmp__ that it is called if none of the other rich > > comparison functions are defined. > > Is this a bug in Python 3.0rc1, or am I missing something? > > > Secondly, say that we suddenly need another sorting order, where we > > want to sort by decreasing score and then by DECREASING last name > > (instead of increasing last name, defined above). Now that the > > comparison function argument is taken away from the sorted builtin, > > how do we accomplish this with the "key" parameter? > > > Thank you > > I don't know about __cmp__ but for the second part of the question you > can probably do: > > ? ? sorted(P, key=lambda p: (p.score, p.lname), reverse=True) > > HTH > > -- > Arnaud Thank you for the prompt reply. I didn't think my second question completely through. A better example would be sorting by increasing last name and decreasing first name. This would be easy with the sort function comparator, but I can't see how to do the same with the key argument. Is the only solution to decorate the Player objects in another class that has the appropriate __cmp__ function (or whatever is needed) and then retrieve the Player objects back? From Ron.Barak at lsi.com Wed Sep 10 07:58:36 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Wed, 10 Sep 2008 12:58:36 +0100 Subject: ImportError: No module named zipextimporter on py2exe when { "compressed": 0 } Message-ID: <7F0503CD69378F49BE0DC30661C6CCF601ADC07B@enbmail01.lsi.com> Hi, I'm trying to compile using py2exe, and am getting the following: $ python_win Setup.py py2exe running py2exe creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32 creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32\winexe creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32\winexe\collect-2.5 creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32\winexe\bundle-2.5 creating c:\Documents and Settings\rbarak\rbarak_devel\dpm09\build\bdist.win32\winexe\temp *** searching for required modules *** Traceback (most recent call last): File "Setup.py", line 96, in <module> windows = [test_wx] File "C:\Python25\lib\distutils\core.py", line 151, in setup dist.run_commands() File "C:\Python25\lib\distutils\dist.py", line 974, in run_commands self.run_command(cmd) File "C:\Python25\lib\distutils\dist.py", line 994, in run_command cmd_obj.run() File "c:\Python25\lib\site-packages\py2exe\build_exe.py", line 228, in run self._run() File "c:\Python25\lib\site-packages\py2exe\build_exe.py", line 281, in _run self.find_needed_modules(mf, required_files, required_modules) File "c:\Python25\lib\site-packages\py2exe\build_exe.py", line 1202, in find_needed_modules mf.import_hook(mod) File "c:\Python25\lib\site-packages\py2exe\mf.py", line 716, in import_hook return Base.import_hook(self,name,caller,fromlist,level) File "c:\Python25\lib\site-packages\py2exe\mf.py", line 136, in import_hook q, tail = self.find_head_package(parent, name) File "c:\Python25\lib\site-packages\py2exe\mf.py", line 204, in find_head_package raise ImportError, "No module named " + qname ImportError: No module named zipextimporter My Setup.py (produced by GUI2Exe) is attached. Note that I set compressed to 0 in Setup.py (options = {"py2exe": {"compressed": 0), but it does not help. Any ideas ? Bye, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/7ad22489/attachment-0001.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: Setup.py Type: application/octet-stream Size: 3285 bytes Desc: Setup.py URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/7ad22489/attachment-0001.obj> From sturlamolden at yahoo.no Thu Sep 25 08:31:13 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 05:31:13 -0700 (PDT) Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <gbe6qk$b54$1@aioe.org> <Xns9B23DFA195833duncanbooth@127.0.0.1> <d57f3edc-a305-4165-bafb-d0d75bb54948@z72g2000hsb.googlegroups.com> <Xns9B245BE13E207duncanbooth@127.0.0.1> <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> <Xns9B2487F2CF29Bduncanbooth@127.0.0.1> Message-ID: <971aafb6-1d76-4a1d-8acd-1442ff3a60ae@2g2000hsn.googlegroups.com> On 25 Sep, 14:22, Duncan Booth <duncan.bo... at invalid.invalid> wrote: > No Python's syntax is fine. The api's aren't as consistent though: > Microsoft added a common set of extension methods which work on > databases, xml, builtin sequences and can be easily extended to include > other custom sequences. That is correct, but it is a library issue and cannot be solved by adding new syntax. From python at rgbaz.eu Tue Sep 16 11:25:28 2008 From: python at rgbaz.eu (Python) Date: Tue, 16 Sep 2008 17:25:28 +0200 Subject: How do I add permanently to Pythons sys.path? In-Reply-To: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> Message-ID: <A183D966-C2F9-453F-8A74-CB0ADEDEBDE2@rgbaz.eu> On 16 sep 2008, at 17:13, cnb wrote: >>>> sys.path > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', > 'C:\ > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > \lib\\site-packages\\PIL'] >>>> > > Now I have my personal programs in C:/Python25/Progs/ > > How do I add so that I can just do "import somefile" from anywhere in > that directory in the interpreter and it can load files from other > folders in that directory. > -- > http://mail.python.org/mailman/listinfo/python-list > > a temp solution is to append it to that list: sys.path.append('C:/Python25/Progs/') a permanent solution is to add it to the environment variable (no idea where to set this in windows) $PYTHONPATH = "/C:/Python25/Progs/" gr Arno From roy at panix.com Sun Sep 28 09:25:56 2008 From: roy at panix.com (Roy Smith) Date: Sun, 28 Sep 2008 09:25:56 -0400 Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <gbn6nu$r5j$4@lust.ihug.co.nz> <00ef327d$0$20666$c3e8da3@news.astraweb.com> Message-ID: <roy-851999.09255628092008@news.panix.com> In article <00ef327d$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote: > from random import randint > ''.join(chr(randint(0, 255)) for i in xrange(len(input))) > > > of course. How else should you get random bytes? :) That a UUOL (Useless Usage Of Len; by analogy to UUOC). This works just as well: ''.join(chr(randint(0, 255)) for i in input) From karl.kobata at syncira.com Mon Sep 15 16:47:03 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Mon, 15 Sep 2008 13:47:03 -0700 Subject: ka-ping yee tokenizer.py Message-ID: <6u80qt$7o5lj6@rrcs-agw-02.hrndva.rr.com> I have enjoyed using ka-ping yee's tokenizer.py. I would like to replace the readline parameter input with my own and pass a list of strings to the tokenizer. I understand it must be a callable object and iteratable but it is obvious with errors I am getting, that this is not the only functions required. Being new to python, I am looking for help. 1) I would like to create a class called a. Class ReadStringList: b. I would like to pass this class a list. Each element of the list is a string. c. I would like to pass this <object>.readline( <listOfString> ) as the 'readline' parameter for the tokenizer d. What functions other than __init__(self, inputList) and readline, will I need to write? e. Where can I find the definition requirements for these other functions required? f. Better yet, where can I find an example. Please help. NoviceToLinux -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/d3c15573/attachment-0001.html> From mal at egenix.com Mon Sep 1 16:25:44 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 01 Sep 2008 22:25:44 +0200 Subject: (in memory) database In-Reply-To: <d1104d4c-b894-46ed-9641-fcbcdc3661d0@26g2000hsk.googlegroups.com> References: <d1104d4c-b894-46ed-9641-fcbcdc3661d0@26g2000hsk.googlegroups.com> Message-ID: <48BC4FC8.2040205@egenix.com> On 2008-08-31 15:15, mark wrote: > Hi there, > > I need to extract data from text files (~4 GB) on this data some > operations are performed like avg, max, min, group etc. The result is > formated and written in some other text files (some KB). > > I currently think about database tools might be suitable for this. I > would just write the import from the text files and ... the tool does > the rest. The only problem I can imagine is that this would not be > fast enough. But I would give it a shoot. > Unfortunately I have only some knowledge of SQLite which is not an > option here. > > Some additional requirements I can think of are: > - Python (I want to hone my programming skills too) > - Python-only (no C-lib) for simplicity (installation, portability). > Therefore SQLite is not an option > - must be fast > - I like SQL (select a, b from ...) this would be nice (row[..] + ... > is a little hard getting used to) > > So far I found PyDBLite, PyTables, Buzhug but they are difficult to > compare for a beginner. You could use Gadfly for this since it is pure Python and provides a standard Python DB-API interface: http://gadfly.sourceforge.net/ (the C extensions are optional to speedup processing) This is the SQL subset it supports: http://gadfly.sourceforge.net/sql.html Another option is SnakeSQL: http://pythonweb.org/projects/snakesql/ but I've never used that one, so can't judge its quality. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 01 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From notvalid2 at sbcglobal.net Mon Sep 1 11:50:43 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 01 Sep 2008 08:50:43 -0700 Subject: How Compute # of Days between Two Dates? In-Reply-To: <l8OdnfiOPe7amyHVnZ2dnUVZ_qvinZ2d@posted.visi> References: <JAIuk.19687$cW3.19527@nlpi064.nbdc.sbc.com> <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> <VpTuk.38934$ZE5.3067@nlpi061.nbdc.sbc.com> <l8OdnfiOPe7amyHVnZ2dnUVZ_qvinZ2d@posted.visi> Message-ID: <kbUuk.19585$xZ.18144@nlpi070.nbdc.sbc.com> Grant Edwards wrote: > On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: >> Grant Edwards wrote: >>> On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: >>> >>>> That's the question in Subject. For example, the difference between >>>> 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and >>>> 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in >>>> years between, say, 1990 and 2050. In other words not some really strange >>>> period of time well outside our current era of history. >>> Does the standard library's datetime module not do what you want? >>> >>> http://docs.python.org/lib/module-datetime.html >>> >> Yes, it would seem so. This works fine. > > It would probably be worth your while to read through one of > introductory Python books or just browse through the Python > tutorial: > > http://docs.python.org/tut/ Oddly, Leaning Python has no mention of datetime (not date or time), at least, that I could find. I'm considering the Nutshell book, 2nd ed., as a better reference (and cross reference) to various topics. > >> I was pondering this in pyfdate, but perhaps missed it or it >> was not obvious to me in the tutorial for some reason. > > Sorry, can't help you there -- I've never heard of pyfdate. The > timedate module that comes with Python has always done what I > needed to do with dates/times. > -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: <www.speckledwithstars.net/> From namekuseijin at gmail.com Mon Sep 29 23:48:22 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Mon, 29 Sep 2008 20:48:22 -0700 (PDT) Subject: PYTHON WORKING WITH PERL ?? References: <mailman.1684.1222708578.3487.python-list@python.org> Message-ID: <fd6e8021-5dc3-4643-b9bf-5c2d132eac16@k7g2000hsd.googlegroups.com> On 29 set, 14:16, "Blubaugh, David A." <dbluba... at belcan.com> wrote: > To All, > > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? ?Such as > utilizing python for internet programming and then utilize perl for text > processing and systems programming? ?Is this even feasible??? Python + Perl is called Ruby. ;) From rcdailey at gmail.com Fri Sep 5 16:12:25 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 15:12:25 -0500 Subject: Need formatting suggestion for long strings In-Reply-To: <20080905192934.29191.496947365.divmod.quotient.22130@ohm> References: <496954360809051224i66123029s23a5ab2f02d8be2b@mail.gmail.com> <20080905192934.29191.496947365.divmod.quotient.22130@ohm> Message-ID: <496954360809051312l4e71dfdfja770f5e62007dbe1@mail.gmail.com> On Fri, Sep 5, 2008 at 2:29 PM, Jean-Paul Calderone <exarkun at divmod.com>wrote: > mystring = ( > "This is a very long string that " > "spans multiple lines and does " > "not include line breaks or tabs " > "from the source file between " > "the strings partitions.") At first glance it looks like this is making a tuple. I didn't know this was legal! But, this is definitely what I was looking for (Assuming it works). Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080905/74553fca/attachment-0001.html> From arnodel at googlemail.com Mon Sep 22 08:41:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Sep 2008 05:41:47 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> Message-ID: <4c9d12f9-a682-40d6-95a2-4b1eb3a11850@k37g2000hsf.googlegroups.com> On 22 Sep, 10:32, Steven D'Aprano <ste... at REMOVE.THIS.cybersource.com.au> wrote: > but it isn't good enough if the function needs to refer to it's own > state, because functions can only refer to themselves by name and the > factory can't know what name the function will be bound to. > > As far as I know, the only objects that know how to refer to themselves > no matter what name they have are classes and instances. And instances > share at least some state, by virtue of having the same class. Here is a simple way to make a function able to refer to its own state: def bindfunction(f): def bound_f(*args, **kwargs): return f(bound_f, *args, **kwargs) bound_f.__name__ = f.__name__ return bound_f >>> @bindfunction ... def foo(me, x): ... me.attr.append(x) ... return me.attr ... >>> foo.attr = [] >>> foo(3) [3] >>> foo(5) [3, 5] >>> -- Arnaud From rschroev_nospam_ml at fastmail.fm Wed Sep 10 15:06:39 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 10 Sep 2008 21:06:39 +0200 Subject: Reading binary data In-Reply-To: <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <ga91ft$12t$1@inews.gazeta.pl> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> Message-ID: <3VUxk.62$S64.4@newsfe09.ams2> Aaron Scott schreef: > Sorry, I had posted the wrong error. The error I am getting is: > > struct.error: unpack requires a string argument of length 12 > > which doesn't make sense to me, since I'm specifically asking for 11. That's because of padding. According to the docs, "By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler)". That means that struct.unpack() assumes one byte of padding between the 3-character string and the first unsigned int. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From malaclypse2 at gmail.com Mon Sep 15 16:50:18 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 15 Sep 2008 16:50:18 -0400 Subject: append on lists In-Reply-To: <gamgn9$5r5$1@online.de> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> Message-ID: <16651e80809151350v3e425209h9d240b1b273c8c3c@mail.gmail.com> On Mon, Sep 15, 2008 at 4:45 PM, Armin <a at nospam.org> wrote: > Yes, but this is very unconvenient. > If d should reference the list a extended with a single list element > you need at least two lines You do it in two lines, because you're doing two different things. > a.append(7) This appends the element 7 to the list a. > d=a This binds the name d to the same list as a is bound to. If you wand d to point to a new list with the same contents as the list a, plus the number 7 do this: d = a + [7] Here's an example of the difference: >>> a = range(6) >>> a [0, 1, 2, 3, 4, 5] >>> a.append(7) >>> a [0, 1, 2, 3, 4, 5, 7] >>> d = a >>> d [0, 1, 2, 3, 4, 5, 7] >>> d.append(10) >>> a [0, 1, 2, 3, 4, 5, 7, 10] >>> d [0, 1, 2, 3, 4, 5, 7, 10] >>> See how a and d are two names bound to the same list? Here's the other way: >>> a = range(6) >>> d = a + [7] >>> a [0, 1, 2, 3, 4, 5] >>> d [0, 1, 2, 3, 4, 5, 7] >>> d.append(10) >>> a [0, 1, 2, 3, 4, 5] >>> d [0, 1, 2, 3, 4, 5, 7, 10] >>> -- Jerry From larry.bates at vitalEsafe.com Tue Sep 9 18:44:23 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 09 Sep 2008 17:44:23 -0500 Subject: dynamic allocation file buffer In-Reply-To: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> Message-ID: <YXCxk.31232$XT1.638@bignews5.bellsouth.net> castironpi wrote: > I will try my idea again. I want to talk to people about a module I > want to write and I will take the time to explain it. I think it's a > "cool idea" that a lot of people, forgiving the slang, could benefit > from. What are its flaws? > > A user has a file he is using either 1/ to persist binary data after > the run of a single program (persistence) or 2/ share binary data > between concurrently running programs (IPC / shared memory). The data > are records of variable types and lengths that can change over time. > He wants to change a record that's already present in the file. Here > are two examples. > > Use Case 1: Hierarchical ElementTree-style data > > A user has an XML file like the one shown here. > > <a> > <b> > <c>Foo</c> > </b> > ... > > He wants to change "Foo" to "Foobar". > > <a> > <b> > <c>Foobar</c> > </b> > ... > > The change he wants to make is at the beginning of a 4GB file, and > recopying the remainder is an unacceptable resource drain. > > Use Case 2: Web session logger > > A tutor application has written a plugin to a webbrowser that records > the order of a user's mouse and keyboard activity during a browsing > session, and makes them concurrently available to other applications > in a suite, which are written in varying lanugages. The user takes > some action, such as surfing to a site or clicking on a link. The > browser plugin records that sequence into shared memory, where it is > marked as acknowledged by the listener programs, and recycled back > into an unused block. URLs, user inputs, and link text can be of any > length, so truncating them to fit a fixed length is not an option. > > Existing Solutions > > - Shelve - A Python Standard Library shelf object can store a random > access dictionary mapping strings to pickled objects. It does not > provide for hierarchical data stores, and objects must be unpickled > before they can be examined. > - Relational Database - Separate tables of nodes, attributes, and > text, and the relations between them are slow and unwieldy to > reproduce the contents of a dynamic structure. The VARCHAR data type > still carries a maximum size, no more flexible than fixed-length > records. > - POSH - Python Object Sharing - A module currently in its alpha stage > promises to make it possible to store Python objects directly in > shared memory. In its current form, its only entry point is 'fork' > and does not offer persistence, only sharing. See: > http://poshmodule.sourceforge.net/ > > Dynamic Allocation > > The traditional solution, dynamic memory allocation, is to maintain a > metadata list of "free blocks" that are available to write to. See: > http://en.wikipedia.org/wiki/Dynamic_memory_allocation > http://en.wikipedia.org/wiki/Malloc > http://en.wikipedia.org/wiki/Mmap > http://en.wikipedia.org/wiki/Memory_leak > The catch, and the crux of the proposal, is that the metadata must be > stored in shared memory along with the data themselves. Assuming they > are, a program can acquire the offset of an unused block of a > sufficient size for its data, then write it to the file at that > offset. The metadata can maintain the offset of one root member, to > serve as a 'table of contents' or header for the remainder of the > file. It can be grown and reassigned as needed. > > An acquaintence writes: It could be quite useful for highly concurrent > systems: the overhead involved with interprocess communication can be > overwhelming, and something more flexible than normal object > persistence to disk might be worth having. > > Python Applicability > > The usual problems with data persistence and sharing apply. The > format of the external data is only established conventionally, and > conversions between Python objects and raw memory bytes take the usual > overhead. 'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' > currently offer this functionality, and the buffer offset obtained > from 'alloc' can be used with all three. > > Ex 1. > s= struct.Struct( 'III' ) > x= alloc( s.size ) > s.pack_into( mem, x, 2, 4, 6 ) > Struct in its current form does not permit random access into > structure contents; a user must read or write the entire converted > strucutre in order to update one field. Alternative: > s= struct.Struct( 'I' ) > x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) > s.pack_into( mem, x1, 2 ) > s.pack_into( mem, x2, 4 ) > s.pack_into( mem, x3, 6 ) > > Ex 2. > class Items( ctypes.Structure ): > _fields_= [ > ( 'x1', ctypes.c_float ), > ( 'y1', ctypes.c_float ) ] > x= alloc( ctypes.sizeof( Items ) ) > c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents > c.x1, c.y1= 2, 4 > The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. > > Ex 3. > s= pickle.dumps( ( 2, 4, 6 ) ) > x= alloc( len( s ) ) > mem[ x: x+ len( s ) ]= s > 'dumps' is still slow and nor does permit random access into contents. > > Use Cases Revisited > > Use Case 1: Hierarchical ElementTree-style data > Solution: Dynamically allocate the tree and its elements. > > Node: tag: a > Node: tag: b > Node: tag: c > Node: text: Foo > > The user wants to change "Foo" to "Foobar". > > Node: tag: a > Node: tag: b > Node: tag: c > Node: text: Foobar > > Deallocate 'Node: text: Foo', allocate 'Node: text: Foobar', and store > the new offset into 'Node: tag: c'. Total writes 6 bytes 'foobar', a > one-word offset, and approximatly 5- 10-word metadata update. > > Use Case 2: Web session logger > Dynamically allocate a linked list of data points. > > Data: 'friendster.com' > Data: 'My Account' > > Allocate one block for each string, adding it to a linked list. As > listeners acknowledge each data point, remove it from the linked > list. Keep the head node in the 'root offset' metadata field. > > Restrictions > > It is not possible for persistent memory to refer to live memory. Any > objects it refers to must also be located in file. Their mapped > addresses must not be stored, only their offsets into it. However, > live references to persistent memory are eminently possible. > > Current Status > > A pure Python alloc-free implementation based on the GNU PAVL tree > library is on Google Code. It is only in proof-of-concept form and > not commented, but does contain a first-pass test suite. See: > http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk > The ctypes solution for access is advised. You should review Zope's ZODB and/or memcached before putting in too much effort. -Larry From dickinsm at gmail.com Thu Sep 25 07:02:49 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 25 Sep 2008 04:02:49 -0700 (PDT) Subject: Comparing float and decimal References: <mailman.1400.1222168827.3487.python-list@python.org> <48d8e810$0$4541$9b622d9e@news.freenet.de> Message-ID: <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> On Sep 23, 1:58?pm, Robert Lehmann <stargam... at gmail.com> wrote: > I don't see why transitivity should apply to Python objects in general. Hmmm. Lack of transitivity does produce some, um, interesting results when playing with sets and dicts. Here are sets s and t such that the unions s | t and t | s have different sizes: >>> from decimal import Decimal >>> s = set([Decimal(2), 2.0]) >>> t = set([2]) >>> len(s | t) 2 >>> len(t | s) 1 This opens up some wonderful possibilities for hard-to-find bugs... Mark From cbabcock at kolonelpanic.org Thu Sep 18 15:52:48 2008 From: cbabcock at kolonelpanic.org (Chris Babcock) Date: Thu, 18 Sep 2008 12:52:48 -0700 Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <tvkf941kmehd7hcihihdiil6fjutbfkf6k@4ax.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> <gas6t7$382$1@lust.ihug.co.nz> <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> Message-ID: <20080918125248.6ff8c402@mail.asciiking.com> > >> Traceback (most recent call last): > >> File "mail5.py", line 21, in <module> > >> session = smtplib.SMTP(SMTPserver,port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > >> (code, msg) = self.connect(host, port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > >> self.sock.connect(sa) > >> File "<string>", line 1, in connect > >> then conncetion time out..... > > > > Could it be your ISP is blocking outgoing connections to port > > 25? > > gmail doesn't accept mail via SMTP on port 25. So what is the value of "port" when you are running this program? Chris From frankrentef at yahoo.com Wed Sep 3 13:21:29 2008 From: frankrentef at yahoo.com (frankrentef) Date: Wed, 3 Sep 2008 10:21:29 -0700 (PDT) Subject: Using strftime Message-ID: <4841b103-be8c-471f-8903-1b9284bd3a39@k13g2000hse.googlegroups.com> I have one line of code that put's an old date in my code. ie.textBoxSet('_ct10_PlaceHolder_txtEnd', '8/15/2008') What I wish to do in another similiar line is have the field populated with the current system date? How best to do this? I've read some of the strftime documentation but as of yet I'm unable to get it to work correctly. Help is appreciated. THNX From sh006d3592 at blueyonder.co.uk Sun Sep 14 16:28:19 2008 From: sh006d3592 at blueyonder.co.uk (Stephen Horne) Date: Sun, 14 Sep 2008 21:28:19 +0100 Subject: Abstract class (irrelevant blethering) References: <mailman.1008.1221408214.3487.python-list@python.org> <roy-9FFFBD.13564414092008@news.panix.com> <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <48CD62B8.7070708@islandtraining.com> <mailman.1014.1221419957.3487.python-list@python.org> Message-ID: <ksqqc4d1o8rfc750rokjdosjnaccuontv4@4ax.com> On Sun, 14 Sep 2008 21:19:06 +0200, Mr.SpOOn <mr.spoon21 at gmail.com> wrote: >I started to think to abstract classes just because in the paper it >uses an abstract class in SmallTalk. FWIW, it was obvious to me that you was using the term "abstract" in the wider sense. You did say about the Smalltalk paper, after all. And to me, any Python class that you treat as abstract is abstract. That was always how the word "abstract" was used by Python users in the past. Now, it seems that there's a specific Python feature to enforce abstractness. That's nice to know, and I'll have to do some reading. As I said elsewhere, my Python's getting a bit rusty. But I doubt I'll use it for the "overkill" reason. To me, the last important feature added to Python was conditional expressions in 2.5 IIRC, and while I love some features that others see as bloat, there's a lot that came in earlier versions that I'm never likely to use. For example, to me the term "property" is basically a trivial design pattern or an object-oriented principle. I don't really see the need for the language feature. I can define getter and setter methods all by myself, and I don't really see the benefit of disguising them as member variables. I used to like the idea, but now I'm more of an occasional Python user, I can't be bothered looking up the syntax. It's a strange role reversal - I used to be very enthusiatic about new features back when others kept saying Python 1.5 is all you need. From mail at timgolden.me.uk Fri Sep 12 08:39:02 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 13:39:02 +0100 Subject: testing if another instance of a script is already running In-Reply-To: <48CA6211.8050402@timgolden.me.uk> References: <48CA5BA5.8020709@p0w.org> <48CA6211.8050402@timgolden.me.uk> Message-ID: <48CA62E6.40106@timgolden.me.uk> Tim Golden wrote: > Strato wrote: >> Hi folks, >> >> I want to write some kind of test to check at startup if another >> instance of my script is already running. >> >> I don't want to handle writing of a PID file because it is too >> Unix/Linux specific way to do this, and I need to keep the code to be >> cross-platform. >> >> I think the better way to achieve this is to use some process control, >> but I'm a neebie and I don't see how to do this in a safe and clean way. > > There's nothing built in to Python to do this, so you'll > probably have to roll your own cross-platformness. Of > course, there's nothing to stop you from writing pid > files under Windows even if it's not the usual way. > Or you could just put some conditional code, and use > the kernel mutex under Windows, which is the generally > recommended technique. Have a look at this thread, > for example (among several others): > > http://mail.python.org/pipermail/python-list/2005-June/327063.html Sorry, not the best of links to point to. Basically, search mail.python.org for things like "CreateMutex" and "single application instance". TJG From gagsl-py2 at yahoo.com.ar Tue Sep 16 00:56:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 01:56:41 -0300 Subject: catching exceptions from fortran References: <a1e06af0-a289-4393-9bca-ae5da1fa28c3@r66g2000hsg.googlegroups.com> <mailman.901.1221178993.3487.python-list@python.org> <b760becc-277c-42ca-b54a-00a5278b8f56@m44g2000hsc.googlegroups.com> Message-ID: <op.uhj5amecx6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 15 Sep 2008 10:04:27 -0300, john <john.m.roach at gmail.com> escribi?: [trying to catch exceptions when reading a file in Fortran code using f2py] > i agree with everything you write, but unless i misunderstood > something, this still doesn't address the main problem of the try- > except construct not preventing the program from aborting when the > wrapped fortran code encounters an error. i tried hard-coding all of > the passed variables to the fortran code and ran that code alone-- > works. however, when an incorrect fortran read is attempted (ex. > formatted read on unformatted file), the python except still fails to > catch the error and the code aborts with a runtime error... Looks like the error isn't mapped onto a Python exception, and is handled directly in the Fortran code; better to find a f2py group to ask then. Perhaps you have to catch those errors on the Fortran side. I barely remember doing things like READ(..., IOSTAT=IO)... -- Gabriel Genellina From RedGrittyBrick at spamweary.invalid Tue Sep 2 06:11:09 2008 From: RedGrittyBrick at spamweary.invalid (RedGrittyBrick) Date: Tue, 02 Sep 2008 11:11:09 +0100 Subject: The Importance of Terminology's Quality In-Reply-To: <m43pb4ld0h7i83ko7l61sa3rl0f9iqs4ba@4ax.com> References: <48a8df27$0$7362$607ed4bc@cv.net> <g8bflo$984$1@localhost.localdomain> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> <s2lta4lorjk49dn3joo3gj3juc8rfqqinf@4ax.com> <rem-2008sep01-004@yahoo.com> <g9hlbf$liu$1@localhost.localdomain> <m43pb4ld0h7i83ko7l61sa3rl0f9iqs4ba@4ax.com> Message-ID: <48bd1141$0$26092$db0fefd9@news.zen.co.uk> George Neuner wrote: > On Mon, 1 Sep 2008 21:03:44 +0000 (UTC), Martin Gregorie > <martin at see.sig.for.address.invalid> wrote: > >> On Mon, 01 Sep 2008 12:04:05 -0700, Robert Maas, http://tinyurl.com/uh3t >> wrote: >> >>>> From: George Neuner <gneun... at comcast.net> A friend of mine had an >>>> early 8080 micros that was programmed through the front panel using >>>> knife switches >>> When you say "knife switches", do you mean the kind that are shaped like >>> flat paddles? >>> >> Pedantic correction: >> >> "Knife switch" is the wrong term. These are high current switches, >> typically used in the sort of heavy duty circuit where the wiring hums >> when power is on or in school electrical circuits so even the back of the >> class can see whether the switch is open or closed. In these a copper >> 'blade' closes the contact by being pushed down into a >> narrow, sprung U terminal that makes a close contact with both sides of >> the blade. Like this: http://www.science-city.com/knifeswitch.html >> >> What you're talking is a flat handle on a SPST or DPST toggle switch. It >> is often called a paddle switch and mounted with the flats on the handle >> horizontal. Like this, but often with a longer handle: >> http://www.pixmania.co.uk/uk/uk/1382717/art/radioshack/spdt-panel-mount- >> paddle-s.html > > I don't know the correct term, but what I was talking about was a tiny > switch with a 1/2 inch metal handle that looks like a longish grain of > rice. We used to call them "knife" switches because after hours > flipping them they would feel like they were cutting into your > fingers. > That must be a toggle switch (as MG suggested) just not the paddle type. e.g. <http://cpc.farnell.com/SW02861/components-spares/product.us0?sku=multicomp-1m31t1b1m1qe> <http://tinyurl.com/64a8ld> -- RGB From aioe.org at technicalbloke.com Wed Sep 17 12:46:33 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 12:46:33 -0400 Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> <mailman.1056.1221505345.3487.python-list@python.org> <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> Message-ID: <garc99$tts$1@aioe.org> Michael Palmer wrote: > On Sep 15, 3:04 pm, Matias Surdi <matiassu... at gmail.com> wrote: >> aditya shukla escribi?: >> >>> How can we convert .py files to batch files? is there any library for this? >>> Aditya >>> ------------------------------------------------------------------------ <snip>> On Linux, you would instead insert the shebang line that points to > your python interpreter, such as > > #!/usr/bin/python > > at the top and also set the executable bit, but I suppose if you use > Linux at all you know that. Doh! I'm new to Linux and so I didn't know that, thanks! One small snag though, it doesn't work on my system :-( I did both steps, the shebang and the execute bit but nada... r0g at steppa:~/Desktop/py$ ls kickstart.py kickstart.py~ kicktest.py kicktest.py~ r0g at steppa:~/Desktop/py$ kickstart.py bash: kickstart.py: command not found Any ideas why this might be? A path thing? I'm on Ubuntu 8.04 / Py2.5 Thanks, Roger. From mauriceling at gmail.com Tue Sep 23 09:56:49 2008 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Tue, 23 Sep 2008 06:56:49 -0700 (PDT) Subject: Call for Papers, Volume 3 Issue 3 Message-ID: <b327be13-f191-48d8-9dd8-cb1eb323dbe3@a3g2000prm.googlegroups.com> We would like to call for papers, articles, opinion pieces and feedback to include in Volume 3, Issue 3 of The Python Papers. We would love to receive articles on Python for beginners and discussions about Python performance. Any article will be gratefully received, of course, so do not let the above list of suggestions deter you from considering an article on another topic. We also need volunteers from Python User Groups to include an article on the activities, members and geographical area of their local group. Expressions of Interest Close: Friday, 14 November Initial Draft Submission Deadline: Friday, 21 November Editorial Process Concludes (i.e. Final Version Due): Monday, 15 December PDF Release Date: Sunday, 4th January (approximate) If you are considering submitting an article, please let us know A.S.A.P., even if you are only thinking about it. This will allow us to post email reminders of important dates to prospective authors, as well as giving us an indication of content. If you are unable to submit an article according to the schedule above, please let us know of your interest anyway, and we will involve you in the publication cycle for the following edition. Contact us at editor at pythonpapers.org Thanks, -Maurice Ling Co-Editor In Chief, The Python Papers From tjreedy at udel.edu Sun Sep 28 03:46:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 03:46:57 -0400 Subject: closures and dynamic binding In-Reply-To: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Message-ID: <gbncph$640$1@ger.gmane.org> Aaron "Castironpi" Brady wrote: > Hello all, > > To me, this is a somewhat unintuitive behavior. I want to discuss the > parts of it I don't understand. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= lambda: n This is equivalent to for n in range(10): def g(): return n f[n] = g which is equivalent to def g(): return n f = [g]*10 n = 9 >>>> f[0]() > 9 >>>> f[1]() > 9 which make this not so surprising as the original lambda version is to some people. > I guess I can accept this part so far, though it took a little getting > used to. I'm writing some code and found the following workaround, > but I don't think it should give different results. Maybe I'm not > understanding some of the details of closures. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= (lambda n: ( lambda: n ) )( n ) This is equivalent to for n in range(10): def g(n): def h: return n return h f[n] = g(n) Now, to avoid the needless confusion of 'n's, g is equivalent to def g(x): def h: return x return h (One could do the same change in the lambdas, too, of course). so that g(n)() == n, with n stored in each closure h... > ... >>>> f[0]() > 0 >>>> f[1]() > 1 to be regurgitated when each is called. Terry Jan Reedy From dadapapa at googlemail.com Wed Sep 17 06:53:24 2008 From: dadapapa at googlemail.com (Harold Fellermann) Date: Wed, 17 Sep 2008 03:53:24 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <cba00205-ee1c-4ee6-9914-c46c7f9c17a2@j22g2000hsf.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> Message-ID: <10b2535d-9a88-43c4-ae73-9baa382edb74@m44g2000hsc.googlegroups.com> > > http://wiki.python.org/moin/NumericAndScientific/Libraries > > > > Scroll down. > > Yes, many of those seem to be deprecated, without destinations to > links, most are poorly or not documented at all. The few that are, I > still can't get running. Of those 254, I think I have tried at least > 10 pages worth. Still no luck. > > # lpsolvpy - Can't get it to compile - dependency problems. > # Lp_solve5 - NO python binding yet. Volunteers needed for python > bindings. > # pycplex - You need to compile the CPX.so module. Change the required > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > sure what to do here. > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > I missed the second link to the python bindings, looked all over the > glpk site for anything about python. > # SciPy -- http://www.scipy.org - supposedly has this, but as I said, > I can't find any mention of it anywhere but on the site you linked. > # pySimplex - (broken link)(broken link) > # Simplex - link is broken, but nothing is mentioned > > I'll take a closer look at glpk's python bindings and if there is any > documentation on them, maybe I'll have some luck. btw, I have been > looking for something that works, I have over 5 packages on my desktop > that I have tried to get up and running, but none of them seem to > work. glpk makes 6. You are right that this is an unsatisfying experience. Fortunately, the referred site is a wiki. Why don't you edit it and delete the broken links or add the package that did the job for you to the list, so that others do not need to go through the same hassle. - harold - From gh at ghaering.de Mon Sep 8 07:56:43 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 08 Sep 2008 13:56:43 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: <6ikc76Fr32cnU1@mid.uni-berlin.de> References: <mailman.587.1220646763.3487.python-list@python.org> <6ii9jbFqoe2eU1@mid.uni-berlin.de> <mailman.673.1220861579.3487.python-list@python.org> <6ikc76Fr32cnU1@mid.uni-berlin.de> Message-ID: <ga33t8$spv$1@ger.gmane.org> Matthias Huening wrote: > Gerhard H?ring (08.09.2008 10:12): >> >>> Error is: >>> >>> con.execute("select load_extension('./fts3.so')") >>> pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht >>> gefunden. >>> >>> Where should I look for the module? >> >> The sources are in ext/fts3 in the SQLite source tree. I haven't found >> any Makefile, so I it myself using this gcc command: >> >> $ cd .../ext/fts3 >> $ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so >> *.c -lsqlite3 > > Thanks! > Will fts3 be integrated in the Python 2.6 release? No (only relevant on win32, where we also ship the SQLite DLL). Neither will be the ability to load extensions modules. It's just too late to add features now. But AFAIK it's possible to compile a custom SQLite with appropriate flags to ./configure that will include the fulltext search extension. -- Gerhard From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 02:49:05 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Mon, 15 Sep 2008 23:49:05 -0700 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: <mailman.1040.1221484013.3487.python-list@python.org> References: <a3158e8b0809142323t2a2d2c7dm8bb65482e25a1d1@mail.gmail.com> <mailman.1040.1221484013.3487.python-list@python.org> Message-ID: <48CF56E1.4020402@comcast.net> > On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal <uzmanajmal at gmail.com> wrote: >> I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that >> key as string. Is there any way to convert the said instance into string? Take a look at as_pem() method. -- Heikki Toivonen From ndbecker2 at gmail.com Tue Sep 23 19:52:28 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 23 Sep 2008 19:52:28 -0400 Subject: python syntax for conditional is unfortunate Message-ID: <gbbvft$mb9$1@ger.gmane.org> In hindsight, I am disappointed with the choice of conditional syntax. I know it's too late to change. The problem is y = some thing or other if x else something_else When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). Particularly if 'some thing or other' is long or complicated. From earlsoliloquyji at googlemail.com Mon Sep 22 07:21:25 2008 From: earlsoliloquyji at googlemail.com (earlsoliloquyji at googlemail.com) Date: Mon, 22 Sep 2008 04:21:25 -0700 (PDT) Subject: assdumper - for Free Message-ID: <058c8edf-7749-4dc8-ac74-ab9921e0ecba@x41g2000hsb.googlegroups.com> assdumper . . . *******CLICK HERE******** http://vids365.cn/assdumper ***************************** . . . . . . . . . . . . assdumper From vs at it.uu.se Tue Sep 16 02:29:03 2008 From: vs at it.uu.se (Virgil Stokes) Date: Tue, 16 Sep 2008 08:29:03 +0200 Subject: Python GUI for animation Message-ID: <48CF522F.40402@it.uu.se> I have been using Python for a short time and I find it a very flexible language, and easy to learn and use. I have also worked some with PyGame and used it to create a simple animation that is controlled by the mouse and keyboard. The animation is designed to move filled circles around on the screen and is driven by a data file that defines (indirectly), the next relative position of each circle. And for my purposes (queueing demo in the classroom) this works quite well. However, I would now like to create a Python GUI that would allow a user to control the animation, via buttons, sliders, etc. I am certainly not a Python expert and have never worked with the creation of a GUI. I would appreciate greatly any advice from those who have worked with Python GUIs as to the best way to proceed. Thank you in advance, V. Stokes From google at mrabarnett.plus.com Fri Sep 12 20:54:21 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 12 Sep 2008 17:54:21 -0700 (PDT) Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <mailman.878.1221146864.3487.python-list@python.org> <00da5aca$0$2879$c3e8da3@news.astraweb.com> <mailman.948.1221257718.3487.python-list@python.org> Message-ID: <b9408802-0047-4b46-be56-539954149cef@t54g2000hsg.googlegroups.com> On Sep 12, 11:15?pm, Matt Nordhoff <mnordh... at mattnordhoff.com> wrote: > Steven D'Aprano wrote: > > On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote: > > >> When mail messages bounce, the MTA (Message Transfer Agent--the program > >> that handles mail) *should* send the bounce message to whatever is in > >> the Sender header, and only if that header does not exist, should it use > >> the From header. > > > Who makes up these rules, and why should we pay the least bit of > > attention to them? > > > It's one thing to say "right or wrong, that's what list admins do and you > > have to deal with their behaviour whatever way you can". It's another > > thing altogether to take the legalistic attitude of "never mind the > > consequences, the standard is the standard and must be unthinkingly > > obeyed". If the standard does more harm than good, then ignoring the > > standard is the right thing to do. (Better would be to change the > > standard, but that probably won't happen until there's a critical mass of > > people who ignore the existing broken standard and form their own de > > facto standard.) > > > A standard isn't "correct" just because it's a standard, it's merely > > something that a committee has agreed to do. In other words, it's a > > compromise. Now, such compromises might be good and useful, or they might > > combine the worst of all opinions. Just because something is standardized > > doesn't make it the right thing to do. If you want proof of this, I give > > you the recently approved ISO standard for Microsoft's so-called "Office > > Open XML" OOXML file format. > > > The standard behaviour of sending bounce and out-of-office messages to > > the sender works well when sending email to individuals, but for mailing > > lists it is pointless and counter-productive. Pointless, because the > > sender can't do anything to fix the problem he's being notified about. > > And counter-productive, because it is an anti-feature, something that > > makes the mailing list more unpleasant and less useful. Anyone who has > > regularly emailed to a large mailing list has surely experienced the > > frustration of receiving bounce messages from perfect strangers. > > > To anyone who wishes to defend the process of sending mailing list > > bounces back the sender, ask yourself this: what do YOU do with such > > bounces when you receive them? If you ignore them or delete them (whether > > manually or via a procmail recipe or some other automatic system) then > > what benefit does the standard behaviour offer? > > I think you misunderstand. He's referring to the Sender header, not the>From header. The messages the listbot sends out have a Sender header of > > "python-list-bounces+user=example.... at python.org" (supposing the > subscriber's email address is u... at example.com). Bounces should be > directed to the bitbucket or list admin or whatever, not the user in the>>From header. kring.com just has a broken mail server. > Ah, kring.com. I've been receiving bounces from there as well since Wednesday. I just added it to my spam blacklist and forgot about it. I'm just wondering what would happen if someone posted from there... :-) From gandalf at shopzeus.com Mon Sep 8 13:18:51 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Sep 2008 19:18:51 +0200 Subject: universal unicode font for reportlab In-Reply-To: <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> References: <mailman.674.1220863917.3487.python-list@python.org> <87r67vj7f1.fsf@benfinney.id.au> <48C51E49.2070202@shopzeus.com> <48C52635.1030709@shopzeus.com> <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <48C55E7B.9090807@shopzeus.com> Iain Dalton wrote: > Why don't you want to use multiple typefaces? Many programs that deal > with multilingual strings use multiple fonts (cf. any Web browser and > Emacs). > You are right, but these PDF documents will show mixed strings. The end user can enter arbitrary strings into the database, and they must be presented. For example, the name of a product can be arabic or german. It might be possible to guess the language used from the unicode string, and then select a different font. But I don't want to go into that trouble. It would be a great idea to use pango. Apparently pango is able to change fonts on the fly and render the requested glyph. However, if I use pango then I loose the much higher level of abstraction that comes with reportlab and platypus: I need automatic page headers and footers, I need to be able to repeat table headers on each page automatically (when the table doesn't fit one page) etc. Developing my own "platypus" like engine for pango and PDF rendering is a nightmare. Better than that, I can develop my own flowable object for platypus: a special paragraph that changes the used true type font on the fly. (Split input string into parts, determine language for the parts and display each part with its own font.) But of course this is a lot of extra programming. The simplest solution would be to use a font that is able to handle all encodings that I need. Thanks, Laszlo From steven at REMOVE.THIS.cybersource.com.au Fri Sep 26 03:27:42 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 07:27:42 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <y9udnWtzwLtQi0rVnZ2dnUVZ_gidnZ2d@earthlink.com> <gbhnoa$d83$1@panix3.panix.com> Message-ID: <pan.2008.09.26.07.27.41@REMOVE.THIS.cybersource.com.au> On Thu, 25 Sep 2008 21:17:14 -0700, Aahz wrote: > Seems to me that if all the module is used for is to store state, you're > wasting a file on disk. I personally prefer to use a class singleton. I don't recognise the term "class singleton". Can you explain please? How is it different from an ordinary singleton? For the record, I ended up deciding that I didn't need any special objects or metaclass programming, just a factory function which returned a regular instance. But reading the thread has been a good education for me, thanks folks. -- Steven From lixinyi.23 at gmail.com Mon Sep 22 22:32:46 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Mon, 22 Sep 2008 19:32:46 -0700 (PDT) Subject: How do I convert a PyObject to string in C++? Message-ID: <ad1dabb9-8304-4791-b367-dbae30dfbd48@o40g2000prn.googlegroups.com> I have a PyObject, say 'Hello World' , a string, How do I convert it to a string in C++? Thanks in advance! From grante at visi.com Tue Sep 30 11:57:19 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Sep 2008 10:57:19 -0500 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: <LeadndG5x5LC0X_VnZ2dnUVZ_qHinZ2d@posted.visi> On 2008-09-30, Peter Pearson <ppearson at nowhere.invalid> wrote: > On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: >> >> 1. Multi dimensional arrays - how do you load them in python >> For example, if I had: >> ------- >> 1 2 3 >> 4 5 6 >> 7 8 9 >> >> 10 11 12 >> 13 14 15 >> 16 17 18 >> ------- >> with "i" being the row number, "j" the column number, and "k" the .. >> uhmm, well, the "group" number, how would you load this ? >> >> If fortran90 you would just do: >> >> do 10 k=1,2 >> do 20 i=1,3 >> >> read(*,*)(a(i,j,k),j=1,3) >> >> 20 continue >> 10 continue >> >> How would the python equivalent go ? You would drag yourself out of the 1960s, install numpy, and then do something like this: a = read_array(open("filename.dat","r")) > Since you're coming from the FORTRAN world (thank you for that > stroll down Memory Lane), you might be doing scientific > computations, and so might be interested in the SciPy package > (Google scipy), which gives you arrays and matrices. Don't > expect to be able to use it without learning some Python, > though. If not full-up scipy (which provides all sorts of scientific and numerical-analysis stuff), then at least numpy (which provides the basic array/matrix operations: http://numpy.scipy.org/ Though the software is free, the documentation isn't. You've got to buy the book if you want something to read. IMO, it's definitely worth it, and a good way to support the project even if you don't really need something to keep your bookends apart. Scientific Python is something else the OP might be interested in. Yes, Scientific Python is different than SciPy: http://dirac.cnrs-orleans.fr/plone/software/scientificpython/overview/ If you're a Windows user, I can recommend the Enthough Python distribution. It has all sorts of numerical and scientific "batteries included". http://www.enthought.com/products/epd.php It includes both scipy and scientific python as well as several options for data visualization (e.g. matplotlib, VTK). There's also an Enthought Python distro for Linux, but I've never tried it. I run Gentoo Linux, and there are standard ebuilds for pretty much all of the stuff in EPD. -- Grant Edwards grante Yow! I've read SEVEN at MILLION books!! visi.com From jinbow at gmail.com Sun Sep 7 18:41:53 2008 From: jinbow at gmail.com (Mars creature) Date: Sun, 7 Sep 2008 15:41:53 -0700 (PDT) Subject: Read and write binary data Message-ID: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Hi guys, I am new to Python, and thinking about migrating to it from matlab as it is a really cool language. Right now, I am trying to figure out how to control read and write binary data, like 'formatted','stream','big-endian','little-edian' etc.. as in fortran. I googled, but can not find a clear answer. Anyone has clue where can I learn it? Thanks!! Jinbo From namekuseijin at gmail.com Tue Sep 23 14:48:33 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Tue, 23 Sep 2008 11:48:33 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <Y7CdnYRzU-8naEXVnZ2dnUVZ_sDinZ2d@posted.visi> Message-ID: <8a149a96-74ae-4eff-9669-31a1fa61d6a2@79g2000hsk.googlegroups.com> On Sep 23, 10:57?am, Grant Edwards <gra... at visi.com> wrote: > AFAICT, _everybody_ is bad at programming C++. Thankfully, at least Numpy developers are not bad at C programming. From ewertman at gmail.com Fri Sep 5 16:58:26 2008 From: ewertman at gmail.com (Eric Wertman) Date: Fri, 5 Sep 2008 16:58:26 -0400 Subject: Need formatting suggestion for long strings In-Reply-To: <496954360809051315v44438624vf16240216d8ba2c5@mail.gmail.com> References: <mailman.580.1220642999.3487.python-list@python.org> <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> <496954360809051315v44438624vf16240216d8ba2c5@mail.gmail.com> Message-ID: <92da89760809051358k7c5ed12enb755efee45f42f37@mail.gmail.com> > I'm concerned about the formatting of the string in that I do not want the > way I split the string up in source code to affect the way the string is > displayed to the console. In other words, in source, if I break up a single > string into multiple lines (using carriage returns), I would expect the > string to still render as a single-line string. > > I'm also concerned about the source formatting, because I do not want the > single-line string to run off the edge of my display. I want it to be in > "Paragraph form" in the source code, but remain a single-line when printed. I think you can also escape the line breaks: >>> mystring = ( ... "This is a very long string that " ... "spans multiple lines and does " ... "not include line breaks or tabs " ... "from the source file between " ... "the strings partitions.") >>> mystring2 = 'This is a very long string that spans multiple lines and does not include line breaks or tabs from the source file between the strings partitions.' >>> mystring == mystring2 True >>> mystring3 = 'This is a very long string that \ ... spans multiple lines and does not include line breaks \ ... or tabs from the source file between the strings \ ... partitions.' >>> mystring3 == mystring True From eekfunster at gmail.com Thu Sep 25 11:36:00 2008 From: eekfunster at gmail.com (EEK) Date: Thu, 25 Sep 2008 08:36:00 -0700 (PDT) Subject: PID management with popen and spawn Message-ID: <73195b54-8836-43f7-ba30-76eb408ccc4a@k37g2000hsf.googlegroups.com> Hello, My goal is to start and stop separate Linux processes from a python program by specific PID. The output of these processes needs to have their stderr and stdout piped to a particular file, respectively. I've been able to make this work with subprocess.Popen only if the shell variable is set to False but I cannot pipe the outputs of the targets. When using subprocess.Popen with shell=True, I believe the returned PID is of the shell that opens the target process, not the target process itself. Therfore, I cannot stop the target process for the returned PID is not of that process. Spawn will work better but I need the target application to pipe it's stderr and stdout to a file. Here I have troubles. Any help appreciated. prgm = program I want to run (compiled C) logfile = file I want to pipe output to What I need to do based on a simple shell call: program >& logfile (yes, that's it) proc = subprocess.Popen("program >& logfile", shell=True, env=os.environ) The above spawns the new process but proc.pid is not of 'program'. Therefore, my python program cannot kill/stop it if needed. pidNum = os.spawnle(os.P_NOWAIT, "program >& logfile", pidName ,os.environ) This does not work. "File not found" Thanks, EEK From fredrik at pythonware.com Wed Sep 17 06:18:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 12:18:41 +0200 Subject: File Reading related query In-Reply-To: <a3158e8b0809170255y6527dc96ta0f7466fd575db8f@mail.gmail.com> References: <a3158e8b0809170255y6527dc96ta0f7466fd575db8f@mail.gmail.com> Message-ID: <gaqli2$1tt$1@ger.gmane.org> Usman Ajmal wrote: > Is there any function for reading a file while ignoring *\n* occuring in > the file? can you be a bit more precise? are we talking about text files or binary files? how do you want to treat any newlines that actually appear in the file? </F> From gandalf at shopzeus.com Mon Sep 8 08:44:57 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Sep 2008 14:44:57 +0200 Subject: universal unicode font for reportlab In-Reply-To: <87r67vj7f1.fsf@benfinney.id.au> References: <mailman.674.1220863917.3487.python-list@python.org> <87r67vj7f1.fsf@benfinney.id.au> Message-ID: <48C51E49.2070202@shopzeus.com> > Laszlo Nagy <gandalf at shopzeus.com> writes: > > >> I could not find any free TTF font that can do latin1, latin2, >> arabic, chinese and other languages at the same time. Is there a >> single font that is able to handle these languages? >> > > The GNU Unifont <URL:http://en.wikipedia.org/wiki/GNU_Unifont> > <URL:http://unifoundry.com/unifont.html> covers an impressive range of > the Unicode Basic Multilingual Plane. > > Unifont is originally a bitmap font, but was recently made available > in TrueType format > <URL:http://www.lgm.cl/trabajos/unifont/index.en.html>. > > Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont' > packages, respectively. > I found out that dejavu is what I need. It covers the languages I need and more: http://dejavu.svn.sourceforge.net/viewvc/dejavu/tags/version_2_26/dejavu-fonts/langcover.txt Thanks four your help! L From gagsl-py2 at yahoo.com.ar Sun Sep 14 15:32:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Sep 2008 16:32:04 -0300 Subject: PyMarshal Commands crash on Windows References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> Message-ID: <op.uhhkjqjox6zn5v@a98gizw.noga> En Sun, 14 Sep 2008 08:28:01 -0300, <spammaster.10.webmaster at spamgourmet.com> escribi?: > int main (int argc, char * const argv[]) { > Py_Initialize(); > > FILE* fp = fopen("/Users/test/Desktop/123.pyc","wb"); > PyCodeObject* op = (PyCodeObject*)Py_CompileString("import sys > \nprint 'hello'","<string.py>",Py_file_input); > PyMarshal_WriteObjectToFile((PyObject *)op, fp, > Py_MARSHAL_VERSION); > > Py_Finalize(); > > return 0; > } > > This Code crashs on Windows, and I can't explain why. I want to > convert a PyCodeObject to a PyObject and save it to the harddisk. > PyMarshal_ReadObjectFromFile(FILE *P) crashs too if I want to read a > byte-compiled object. Your code should check every operation for errors. fopen may return NULL, Py_CompileString may fail and return NULL, PyMarshal_xxx might fail (although it's not documented). Why "123.pyc"? Do you want to generate a compiled module? Use the py_compile standard module instead (or write equivalent C code, or see how import.c does that) -- Gabriel Genellina From jakecjacobson at gmail.com Wed Sep 17 14:26:51 2008 From: jakecjacobson at gmail.com (jakecjacobson) Date: Wed, 17 Sep 2008 11:26:51 -0700 (PDT) Subject: Getting/Setting HTTP Headers Message-ID: <03dafea5-28e0-4925-a0f9-7df5670869c1@z72g2000hsb.googlegroups.com> I need to write a feed parser that takes a url for any Atom or RSS feed and transform it into an Atom feed. I done the transformation part but I want to support conditional HTTP requests. I have not been able to find any examples that show: 1. How to read the Last_Modified or ETag header value from the requester 2. How to set the corresponding HTTP header value, either a 302 not modified or the new Last_Modified date and/or ETag values From aaron.hildebrandt at gmail.com Wed Sep 10 14:12:01 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 11:12:01 -0700 (PDT) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <ga91ft$12t$1@inews.gazeta.pl> Message-ID: <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> Sorry, I had posted the wrong error. The error I am getting is: struct.error: unpack requires a string argument of length 12 which doesn't make sense to me, since I'm specifically asking for 11. Just for kicks, if I change the line to print struct.unpack('3sII', file.read(12)) I get the result ('GDE', 33554432, 16777216) ... which isn't even close, past the first three characters. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 06:50:47 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 12:50:47 +0200 Subject: (in memory) database In-Reply-To: <d1104d4c-b894-46ed-9641-fcbcdc3661d0@26g2000hsk.googlegroups.com> References: <d1104d4c-b894-46ed-9641-fcbcdc3661d0@26g2000hsk.googlegroups.com> Message-ID: <48bbc8b4$0$18575$426a34cc@news.free.fr> mark a ?crit : > Hi there, > > I need to extract data from text files (~4 GB) on this data some > operations are performed like avg, max, min, group etc. The result is > formated and written in some other text files (some KB). > > I currently think about database tools might be suitable for this. I > would just write the import from the text files and ... the tool does > the rest. The only problem I can imagine is that this would not be > fast enough. Is this an a priori, or did you actually benchmark and found out it would not fit your requirements ? > But I would give it a shoot. > Unfortunately I have only some knowledge of SQLite which is not an > option here. > > Some additional requirements I can think of are: > - Python (I want to hone my programming skills too) > - Python-only (no C-lib) for simplicity (installation, portability). > Therefore SQLite is not an option > - must be fast These two requirements can conflict for some values of "fast". > - I like SQL (select a, b from ...) this would be nice (row[..] + ... > is a little hard getting used to) > > So far I found PyDBLite, PyTables, Buzhug but they are difficult to > compare for a beginner. Never used any of them - I have sqlite, mysql and pgsql installed on all my machines -, so I can't help here. From tjreedy at udel.edu Fri Sep 5 03:03:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 05 Sep 2008 03:03:43 -0400 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <3f0d61c40809042217r6f98c683p90bcae958b1ee773@mail.gmail.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> <acdc94a1-9f8c-49f3-b063-dd536e480d07@v39g2000pro.googlegroups.com> <3f0d61c40809042217r6f98c683p90bcae958b1ee773@mail.gmail.com> Message-ID: <g9qlkd$ak2$1@ger.gmane.org> Marco Bizzarri wrote: > I understand that Python is a balance between different forces (like > any software object around the world) and I'm simply asking some > pointers to the discussion leading to this balance. The original decisions by Guido were nearly 20 years ago and other discussions are scattered through the archive of this and the py-dev list. But here is a pointer. Why go through the trouble of writing functions that will set, get, and delete an attribute and the trouble of calling those functions when you can use Python's existing syntax to do it directly? More particularly, why would/should Guido force the combersome indirection and time-penalty for writing, reading, and execution on *every* Python programmer? Of course, from my viewpoint, and for my usage,languages that do so force are obnoxious. tjr From castironpi at gmail.com Tue Sep 23 21:47:08 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 18:47:08 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> Message-ID: <fde4ed92-77ed-438e-a163-d5e248a80ee9@d45g2000hsc.googlegroups.com> On Sep 23, 7:50?pm, lixinyi... at gmail.com wrote: > for example I have the following code: > > #include <Python.h> > > void exec_pythoncode( int arg, char**argv ) > { > ? ? Py_Initialize(); > ? ? Py_Main(argc,argv); > ? ? Py_Finalize(); > > } > > What I would like to know is how can I get the variables I want > after Py_Main(argc,argv) > > say I have a=[1,2,'Hello World',0.1234] in the python space, > I would like to have it as a struct in C++. > > Any sample code? > Thanks in advance! What do you know about the contents of 'argc' and 'argv'? If it's impossible with Py_Main, can you use one of the other entry points? If you've never manipulated PyObject* objects in C, they can be hairy. Even if you know 'a' is a sequence, its contents are still all PyObject*s, which you can access via PyList_... and PySequence_ functions. From castironpi at gmail.com Tue Sep 16 22:00:15 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 19:00:15 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> Message-ID: <cba00205-ee1c-4ee6-9914-c46c7f9c17a2@j22g2000hsf.googlegroups.com> On Sep 16, 8:50?pm, Fett <FettMan... at gmail.com> wrote: > I am trying to find a wrapper to do linear programming within python. > I am using an ubuntu machine and I have apt-get'd lp_solve, which > works just fine. If someone knows of a wrapper that will work with > that that'd be great. > > I also heard that scipy has a wrapper, however, I can't find any > documentation on it, nor can I seem to find it with dir(). If anyone > knows where there is good documentation on this I would love to use > that (the more native to python the better imo). > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > openopt, and cvxopt. I can't seem to find any with enough > documentation to get me off the ground. Some I can't compile, some I > can't even find out how to compile. > > If anyone knows of an LP package (preferably with IP as well, like > lp_solve has), that interfaces well with python and has enough > documentation to get a dependency newb like myself off the ground that > would be great. Google says: about 254,000 for linear programming python. Link 3 is: http://wiki.python.org/moin/NumericAndScientific/Libraries Scroll down. From gregturn at mindspring.com Thu Sep 25 07:21:03 2008 From: gregturn at mindspring.com (Goldfish) Date: Thu, 25 Sep 2008 04:21:03 -0700 (PDT) Subject: Spring Python 0.7.0 is released Message-ID: <b9be2727-27f1-411e-abec-d5df178d4801@k37g2000hsf.googlegroups.com> Release 0.7.0 was completed last night, and released to sourceforge.net. NOTE: This release included a lot of API scrubbing, in order to bring things more in tune with PEP-0008 (python's style guide). You're existing apps PROBABLY were impacted, if you used any of Spring Python's utility classes. Since we are pre-1.0, this is the best time for such a cleanup. When 1.0 hits the streets, we won't make such a sweeping change without extensive backwards support. See [url]http://springpython.webfactional.com[/url] for more information. Visit our community forum at [url]http://forum.springframework.org/ forumdisplay.php?f=45[/url] for current threads of discussion. --Greg Turnquist, Spring Python project lead ========================================= Release Notes - Spring Python - Version 0.7 ** Bug * [SESPRINGPYTHONPY-63] - Running setup.py returns an exception ** Improvement * [SESPRINGPYTHONPY-49] - Upgrade PetClinic to CherryPy 3.1 * [SESPRINGPYTHONPY-64] - Adding a schema for the regular component elements * [SESPRINGPYTHONPY-69] - Remove deprecated connection factories from baseline * [SESPRINGPYTHONPY-70] - Scrub function/attribute naming conventions to more closely follow PEP-0008. ** New Feature * [SESPRINGPYTHONPY-61] - Generate reference documentation for the project ** Refactoring * [SESPRINGPYTHONPY-65] - Change 'type' attribute in XML application config to 'scope' to be in line with the lifetime concept in other Spring platforms From rridge at csclub.uwaterloo.ca Wed Sep 24 14:24:13 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 24 Sep 2008 14:24:13 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <JcKdndouSNGG10fVnZ2dnUVZ_hCdnZ2d@posted.visi> <gbdmgh$nd0$1@rumours.uwaterloo.ca> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> Message-ID: <gbe0kd$qh9$1@rumours.uwaterloo.ca> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote: > Presumably somebody has suggested that calling sys.exit() was a good > option. I'm curious to what possible reason they could give for such a > poor choice. Grant Edwards <invalid at invalid> wrote: >Same here. It's like an automotive engine controls designer >asking if a failed O2 sensor should turn on the check engine >light or blow up the car. Ross Ridge <rridge at csclub.uwaterloo.ca> wrote: > No, it's more like asking if the failed sensor should turn on > a strange and mysterious light on the dashboard Grant Edwards <invalid at invalid> wrote: >You're right. I had forgotten that sys.exit() is actually >raising the system exit exception, and that the application >calling the library could handle that exception. Well, my point was that exceptions in Python are a bit like a car's check engine light. Few drivers know what this mysterious light means, and aren't prepared to do anything about it when it goes on. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From anishchapagain at gmail.com Mon Sep 1 09:10:19 2008 From: anishchapagain at gmail.com (Anish Chapagain) Date: Mon, 1 Sep 2008 06:10:19 -0700 (PDT) Subject: Multiple window handling Message-ID: <55921690-9969-463b-a716-d7d62ca1c95e@k13g2000hse.googlegroups.com> Hi!! I'm trying to program an application which have multiple windows and is capable of executing method defined inside class of one another, i tries a simpel frame work here and am creating Toplevel inside method as the new window to be genereated, and again want another window to be loaded when the widget inside toplevel is executed as necessary..but am feeling lost to either create a class for such new window or write function again.. also, when running clearentry() it is not working...have i missed something here.. Programming with multiple window is main task for me..so how it can be done??? the code i tried is here, from Tkinter import * import sys import os class toplevel1(Tk): def __init__(self,parent): Tk.__init__(self,parent) self.parent=parent self.initialize() def initialize(self): label=Label(self, text="Toplevel Practice").pack(side=TOP) button1=Button(self,text="Child 1",command=self.openchild1).pack(side=LEFT) button2=Button(self,text="Child 2",command=self.openchild2).pack(side=LEFT) self.resizable(width=NO,height=YES) self.geometry('300x300') def openchild1(self): c1 = Toplevel(self,bg="#aabbcc",height=300,width=300,borderwidth=1) c1.title("Child One") c1.resizable(width=NO,height=NO) F = Frame(c1,height=40,width=300) F.pack(side=TOP,fill=X,expand=1) llb=Label(F,text="Enter command..") llb.pack(side=LEFT,padx=1) ent = Entry(F,width=50) ent.pack(side=LEFT,padx=2,expand=1) bCl = Button(F,text="Clear Text",command=self.clearentry) bCl.pack(side=LEFT,padx=2, pady=0) bQt = Button(F,text="Quit", command=F.quit) bQt.pack(side=RIGHT,padx=1, pady=0) F1=Frame(c1,relief=SUNKEN,height=330,width=300) txt=Text(F1) scr=Scrollbar(F1,orient=VERTICAL,command=txt.yview,bg="green",width=20) txt.insert(END,"inside txt...") txt.config(yscrollcommand=scr.set) F1.pack(side=TOP,fill=X,expand=1) txt.pack(side=LEFT,fill=BOTH,padx=1) scr.pack(side=RIGHT,fill=Y) F2=Frame(c1,height=30,width=300,relief=RAISED) F2.pack(side=BOTTOM,fill=X,expand=1) llb1=Label(F2,text=" Low Down statusbar") llb1.pack(side=LEFT) def clearentry(self): self.ent.delete(0,END) def openchild2(self): c2 = Toplevel(self,bg="red",height=200,width=200,borderwidth=1) c2.geometry('200x200') c2.resizable(width=NO,height=NO) c2.title("Child Two") Label(c2, text="This is a regular toplevel window.").pack(side=TOP) if __name__=="__main__": obj=toplevel1(None) obj.title('Main Window') obj.mainloop() From robert.kern at gmail.com Sat Sep 13 18:27:27 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 13 Sep 2008 17:27:27 -0500 Subject: I cannot find where Numpy 1.2 is located In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> Message-ID: <gaheof$or9$1@ger.gmane.org> Blubaugh, David A. wrote: > To All, > > > I have been trying to locate as to where Numpy 1.2 can be downloaded. I > will need this update. The only version available at the Numpy website > for download is only 1.1.1 not the required 1.2 that I definitely need > at this time. For the last time, Jarrod Millman already told you where to get it on numpy-discussion. Please stop bothering python-list with this stuff. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gnemesis2001 at gmail.com Thu Sep 18 09:50:27 2008 From: gnemesis2001 at gmail.com (Nemesis) Date: Thu, 18 Sep 2008 06:50:27 -0700 (PDT) Subject: XPN 1.2.5 References: <48d0097d$0$40312$4fafbaef@reader5.news.tin.it> <gatkcv$4h9$1@aioe.org> Message-ID: <d6cf91ec-bbf3-4f7d-b5a7-487a661455b3@m73g2000hsh.googlegroups.com> On Sep 18, 3:17?pm, pataphor <patap... at gmail.com> wrote: > >XPN(X Python Newsreader) is a multi-platform newsreader with Unicode > > support. It is written with Python+GTK. It has features like > > scoring/actions, X-Face and Face decoding, muting of quoted text, > > newsrc import/export, find article and search in the body, spoiler > > char/rot13, random taglines and configurable attribution lines. > > Thanks! It works great. thank you :-) > What I especially like about it is that it can > be run from the directory it is in, without needing to be installed. I dislike installation procedures ;-) > But anyway, I can now run it from anywhere and I'm really looking > forward to start tinkering with whatever other functionality I can > think of to add to it, but unfortunately it is rather complete :-) . there is always space for improvements, and some help would be very apreciated. What could be improved is the speed and the code should be also refactored. > Did you know there is a tab in Articles_DB.py line 8? :-) Ducking ... NO! thank you, damned tabs. From J.Fine at open.ac.uk Wed Sep 17 05:29:02 2008 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 17 Sep 2008 10:29:02 +0100 Subject: Generating test data from an XML Schema Message-ID: <gaqiku$imk$1@south.jnrs.ja.net> Hello I want to generate test data from an XML schema. I've had a quick look at existing tools (such as minixsv and amara) but from what I've seen they don't seem to help. It is of course easy to extract all the element names from a schema, but I want more than that. Motivation: I wish to create a subset of TeX/LaTeX that can be easily translated into XML that validates against an existing schema. I also want the input TeX to be fairly easy to author (so a simple mechanical translation will not work). A tool that provides a nice Python interface to navigating the schema would probably be quite helpful. Has anyone seen anything that might help generate test data from a schema? -- Jonathan From m_palmer45 at yahoo.ca Sat Sep 6 09:44:44 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Sat, 6 Sep 2008 06:44:44 -0700 (PDT) Subject: running python as a dameon References: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> <6e7ead25-baf1-400a-a52f-568f37351aab@8g2000hse.googlegroups.com> Message-ID: <5c74118c-a576-4a51-ae9a-95d34273a99a@s50g2000hsb.googlegroups.com> On Sep 5, 9:56 pm, Sean Davis <seand... at gmail.com> wrote: > > What I want > > to do is to provide the python NLP program as a service to any other > > PHP/Java/Ruby process request. So the mapping is > > > http -> apache -> PHP/Java/Ruby/... -> Python NLP > > Why not use a simple CGI script or wsgi application? You could make > the service online and interactive and with the same application and > code make an XMLRPC web service. So, things would look more like: > > http -> apache -> Python (running NLP and serving requests) > > You can use apache to proxy requests to any one of a dozen or so > python-based webservers. You could also use mod_wsgi to interface > with a wsgi application. > > Sean xmlrpc is the right idea, as it interfaces easily across languages. From __peter__ at web.de Wed Sep 3 10:18:08 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2008 16:18:08 +0200 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> <g9ldi5$2ea$03$1@news.t-online.com> <roy-85ED11.07544603092008@news.panix.com> <g9lvc5$8qq$03$1@news.t-online.com> <roy-54A0DD.09354003092008@news.panix.com> Message-ID: <g9m6at$a71$01$1@news.t-online.com> Roy Smith wrote: > In article <g9lvc5$8qq$03$1 at news.t-online.com>, > Peter Otten <__peter__ at web.de> wrote: > >> > I might take it one step further, however, and do: >> > >> >> fields = line.split()[:2] >> >> a, b = map(int, fields) >> > >> > in fact, I might even get rid of the very generic, but conceptually >> > overkill, use of map() and just write: >> > >> >> a, b = line.split()[:2] >> >> a = int(a) >> >> b = int(b) >> >> If you go that route your next step is to introduce another try...except, >> one for the unpacking and another for the integer conversion... > > Why another try/except? The potential unpack and conversion errors exist > in both versions, and the existing try block catches them all. Splitting > the one line up into three with some intermediate variables doesn't change > that. As I understood it you didn't just split a line of code into three, but wanted two processing steps. These logical steps are then somewhat remixed by the shared error handling. You lose the information which step failed. In the general case you may even mask a bug. Peter From iain.dalton at gmail.com Fri Sep 26 04:23:18 2008 From: iain.dalton at gmail.com (Iain Dalton) Date: Fri, 26 Sep 2008 02:23:18 -0600 Subject: urllib.urlopen fails in Emacs Message-ID: <877i8zco3t.fsf@gmail.com> In Emacs, using run-python, import urllib urllib.urlopen('http://www.google.com/') results in this traceback: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.5/urllib.py", line 82, in urlopen return opener.open(url) File "/usr/lib/python2.5/urllib.py", line 190, in open return getattr(self, name)(url) File "/usr/lib/python2.5/urllib.py", line 325, in open_http h.endheaders() File "/usr/lib/python2.5/httplib.py", line 860, in endheaders self._send_output() File "/usr/lib/python2.5/httplib.py", line 732, in _send_output self.send(msg) File "/usr/lib/python2.5/httplib.py", line 699, in send self.connect() File "/usr/lib/python2.5/httplib.py", line 683, in connect raise socket.error, msg IOError: [Errno socket error] (111, 'Connection refused') It works fine from the command line. Why is this happening? From fredrik at pythonware.com Thu Sep 11 05:45:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 11:45:05 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <pan.2008.09.11.09.10.00@REMOVE.THIS.cybersource.com.au> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> <87k5djb6e2.fsf@benfinney.id.au> <pan.2008.09.11.09.10.00@REMOVE.THIS.cybersource.com.au> Message-ID: <gaapb2$47v$1@ger.gmane.org> Steven D'Aprano wrote: > I wasn't aware that comp.lang.python was a news-to-mail gateway. How can > one tell the difference between news groups that use a news-to-mail > gateway, and news groups that don't? by reading the group's FAQ, perhaps? http://www.faqs.org/faqs/python-faq/python-newsgroup-faq/ comp.lang.python (or c.l.py for short) is the general discussion newsgroup for users of the Python language. It is also available as a mailing list; see below for instructions on subscribing to c.l.py through the mailing list. it's been this way since the group was formed ~14 years ago, and isn't likely to change. </F> From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 9 04:47:14 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 10:47:14 +0200 Subject: class(object) and (type)?? In-Reply-To: <mailman.715.1220912929.3487.python-list@python.org> References: <f9e39bbc0809081435kd5c3b32x36f4f615fd00f3a0@mail.gmail.com> <mailman.715.1220912929.3487.python-list@python.org> Message-ID: <48c63790$0$17080$426a34cc@news.free.fr> On Mon, Sep 8, 2008 at 2:35 PM, AON LAZIO <aonlazio at gmail.com> wrote: > Hi again pythoners, > I notice in the class of a code having (object) and (type) attached to > the name of the class. > I know that in other cases, that means the class inherits methods and > properties from other but > In this case, what does it mean? The very same thing. Why should it have a different meaning ? For the record : - 'object' is the base class for 'new-style' classes - that is, the 'new' (hem) object model that came with Python 2.2 (released december 2001 - so it's not that 'new'). The old one - known as 'classic classes' has been kept so far for backward compat only, and will finally disappear with Python 3.x. - 'type' is the base metaclass. Python's classes being objects, they have to be instances of a class - known as the metaclass. To avoid metametaclasses, metametametaclasses etc ad infinitum, 'type' is an instance of itself. And FWIW, a subclass of 'object', which is itself an instance of 'type' (usually, brains start melting here...) You'll find more informations (and hopefully clearer explanations) here: http://www.python.org/doc/newstyle/ and of course in the FineManual(tm): http://docs.python.org/ref/datamodel.html HTH From python at rgbaz.eu Sat Sep 6 19:26:24 2008 From: python at rgbaz.eu (Python) Date: Sun, 7 Sep 2008 01:26:24 +0200 Subject: modules path In-Reply-To: <a6c1143a-bb64-4b9c-953e-831c6a74d741@a3g2000prm.googlegroups.com> References: <mailman.626.1220738606.3487.python-list@python.org> <a6c1143a-bb64-4b9c-953e-831c6a74d741@a3g2000prm.googlegroups.com> Message-ID: <ADE2F843-E0B0-4679-9113-6AEBAC95DC09@rgbaz.eu> On 7 sep 2008, at 00:25, John Machin wrote: > On Sep 7, 8:03 am, Python <pyt... at rgbaz.eu> wrote: >> Hi there, >> >> I moved a few modules into the modules folder (on OSX: /opt/local/ >> lib/ >> python2.5/site-packages/). >> They don't show up though when I start IDLE... >> >> Is there a way to reload the modules folders in sys.path without >> logging out and back in? >> > > I know nothing about OS X, but no "reload" step should be necessary. > Each Python process, whether run from IDLE or some other tool or from > the shell, will form its own idea of sys.path. > > So: What modules? What type of file (.py, .pyc, .egg, .zip, .so) are > you talking about? Did their documentation say that moving the files > into site-packages was all the installation that was needed? What does > "don't show up when I start IDLE" mean? > > When you start IDLE and do > import sys, pprint > pprint.pprint(sys.path) > do you see the site-packages directory containing the module files? > > What happens when you do > import amodule # substitute correct module name here > ? > > Repeat the above two steps for each of > (1) running Python from the shell > (2) running Python from the shell with the -v option > > HTH, > John > -- I installed pyGTK from MacPorts for some reason Macports installs these modules in the /opt/ folder even in an old python folder: python 2.4, while my current version is 2.5 both are not in sys.path... i appended the path and IDLE found them I should have thought a bit more before asking... saturday night... why am I here anyway ;) now one question came up, how do I make those path permanent? i mean, sys.path.append(<path)> adds it for the current session, yet when i logout of IDLE and start it again it's gone... how do i keep it in there? thanks for the answer John... Arno From don.hamilton at btinternet.com Fri Sep 12 17:10:07 2008 From: don.hamilton at btinternet.com (Don) Date: Fri, 12 Sep 2008 22:10:07 +0100 Subject: Which version In-Reply-To: <mailman.938.1221240916.3487.python-list@python.org> References: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> <92da89760809121028s1d9b8b46g464d54937c67ba0f@mail.gmail.com> <mailman.938.1221240916.3487.python-list@python.org> Message-ID: <b6udnRaab9YtR1fVnZ2dnUVZ8uidnZ2d@bt.com> Eric,Fredrik, Many thanks for your prompt advice, it was a 'better safe than sorry' type of question. Don From raj.indian.08 at gmail.com Wed Sep 24 10:56:19 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Wed, 24 Sep 2008 07:56:19 -0700 (PDT) Subject: Modifying the system menu References: <bfa45e21-fb5e-454d-a4c2-e7cc00919f38@p31g2000prf.googlegroups.com> <gbd4m0$vo9$3@lust.ihug.co.nz> Message-ID: <46bd064c-9299-433b-9bad-2c857344a28f@v39g2000pro.googlegroups.com> I am creating the window manager for multiple desktops :) Anyways, i got one answer in nabble which I feel is the best option - even though I am just investigating on how to do it. Please find below - James Matthews wrote: > > Hi all, > I am trying to modify the system menu of all the applications in > my machine. > For example say - I am creating multiple desktops for windows - > and I want to give every application the capability to be moved across > different desktops. So I wanted to modify the basic system menu list > to include the new options. > > The methods I could think of are - > 1. Modify the basic windows set of system menu values (best option) There is no central repository where this is stored, so there's no place to change. > 2. Poll every few milliseconds and modify the system menu values of > the active window Ick Windows don't come and go that often, and you only need to do this once for each application. The correct option is (3) install a Windows hook to watch for new application to activate, and modify the menu in the hook. You will have to use a hook in order to catch the menu item being chosen anyway. There are Python modules to handle some kinds of hooks, but overall this would be much easier in C. From bcurtu at gmail.com Fri Sep 26 06:30:50 2008 From: bcurtu at gmail.com (bcurtu) Date: Fri, 26 Sep 2008 03:30:50 -0700 (PDT) Subject: how to replace and string in a "SELECT ... IN ()" References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <gbico4$fo3$1@inews.gazeta.pl> Message-ID: <04e687be-c6f8-4464-bf19-a04e39fdfc8a@c58g2000hsc.googlegroups.com> Pardon? % instead of %s? It doesn't work... :( On 26 sep, 12:15, Wojtek Walczak <gmin... at bzt.bzt> wrote: > On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote: > > I have a BIIIIIG problem with the next query: > > > ? ? ? ? cursor.execute(""" > > ? ? ? ? ? ? ? ? ? ? SELECT titem.object_id, titem.tag_id > > ? ? ? ? ? ? ? ? ? ? FROM tagging_taggeditem titem > > ? ? ? ? ? ? ? ? ? ? WHERE titem.object_id IN (%s) > > ? ? ? ? ? ? ? ? """,( eid_list)) > > ? ? ? ? ? ? ? ? ? ? ?^ > It should rather be '%'. > HTH. > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 03:02:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Sep 2008 07:02:27 GMT Subject: Negative block sizes with file-like objects Message-ID: <00edd446$0$20666$c3e8da3@news.astraweb.com> I have a proxy class that wraps an arbitrary file-like object fp and reads blocks of data from it. Is it safe to assume that fp.read(-1) will read until EOF? I know that's true for file.read() and StringIO.read(), but is it a reasonable assumption to make for arbitrary file-like objects? To put it in more concrete terms, I have a class like this: class C(object): # Much simplified version. def __init__(self, fp): self.fp = fp def read(self, size=-1): return self.fp.read(size) Should I re-write the read() method like this? def read(self, size=-1): if size < 0: return self.fp.read() else: return self.fp.read(size) -- Steven From digitig at gmail.com Sun Sep 28 17:41:24 2008 From: digitig at gmail.com (Tim Rowe) Date: Sun, 28 Sep 2008 22:41:24 +0100 Subject: Not fully OO ? In-Reply-To: <9f263cc0-508a-4597-94fc-365f6b691d10@i76g2000hsf.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48DCC786.2040407@wildenhain.de> <mailman.1551.1222447687.3487.python-list@python.org> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <mailman.1572.1222472905.3487.python-list@python.org> <f9b466b0-9945-42c1-ad9c-2f65c8d4b907@y38g2000hsy.googlegroups.com> <mailman.1574.1222477862.3487.python-list@python.org> <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> <mailman.1610.1222559749.3487.python-list@python.org> <9f263cc0-508a-4597-94fc-365f6b691d10@i76g2000hsf.googlegroups.com> Message-ID: <aee48b3c0809281441w181a4c84ya19d107749ff8add@mail.gmail.com> 2008/9/28 Aaron Castironpi Brady <castironpi at gmail.com>: > Before I tried wxFormBuilder, I imagined that C# would be vastly > faster to develop than Python, for anything requiring any non-trivial > graphical interface. I've done extensive VB, so I can attest to that > personally. It is not. I'm confused about where VB comes in -- I find VB just *slightly* harder than INTERCAL. C# I find fairly easy. > You can come up with examples that favor either. But the opposite of > statistical is anecdotal. Sorry again. Yes, it's anecdotal, but development time isn't just about how fast the program is to type (otherwise, why aren't we all using APL?) > The last time I 'checked in' at your post, your claim was "an hour or > so" vs. "ages". Hence my responses. You could probably sneak by by > claiming a factor of *two*, but if you were exaggerating, please say > so at any time. Ok. I was exaggerating when I said that VB was harder than INTERCAL. It's marginally easier. As for the program I was working on, I worked for over a day on it in Python, and did it in about an hour in C#, although in fairness I didn't forget all the thinking I'd done on the previous day. I have a lot more Python experience than C# experience, but don't claim to be a guru in either. And no, I don't work two hour days (unfortunately). I have indicated that the GUI wasn't the only issue; in C# it was just easy in that case to find all the library bits I needed to in order to accomplish the task. It isn't always so. > on this, that it's "pretty generally applicable" I'm with you on that. > I do not believe that C# is pretty generally applicable. I agree on that, but *only* because it's a proprietary language with imperfect support once you move away from the .net platform. It's a generally applicable language to .net, but .net is not a general platform. > fact, outside of my VB, COM, and MFC experience, you could say I have > no clue. Very tongue in cheek.) If you see C# as being in any way related to VB, it's no wonder you're down on it! > Python has a lot of things C# doesn't. Can we agree on that? And C# has things that Python doesn't (such as static typing). Can we agree on that, too? -- Tim Rowe From bearophileHUGS at lycos.com Sun Sep 21 19:42:11 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 21 Sep 2008 16:42:11 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <1bafdeff-d7ae-4c02-b0dc-9d268cef4206@k13g2000hse.googlegroups.com> Steven D'Aprano: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. You may use a module too for that, with normal functions inside, plus module variables that keep the state. Modules can't be instantiated, I think. Bye, bearophile From fredrik at pythonware.com Thu Sep 11 14:21:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 20:21:20 +0200 Subject: Please help me finding a way to implement os.path.issubpath(a, b) In-Reply-To: <6it563Fe2h8U2@mid.uni-berlin.de> References: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> <6it563Fe2h8U2@mid.uni-berlin.de> Message-ID: <gabnj2$pdn$1@ger.gmane.org> Diez B. Roggisch wrote: > Any reason why > > os.path.normpath(a).startswith(os.normpath(b)) doesn't do the trick? Except for the trivial type, you mean? That depends on whether "c:\foo" should be seen as a subpath to "c:\foobar" or not. I'd probably go for (also untested): def issubpath(a, b): def fixpath(p): return os.path.normpath(p) + os.sep return fixpath(a).startswith(fixpath(b)) </F> From ndbecker2 at gmail.com Tue Sep 23 21:50:23 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 23 Sep 2008 21:50:23 -0400 Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <ee44675b-04ad-48b3-8eed-629ebb10d616@z66g2000hsc.googlegroups.com> Message-ID: <gbc6cv$5d3$1@ger.gmane.org> Aaron "Castironpi" Brady wrote: > On Sep 23, 6:52 pm, Neal Becker <ndbeck... at gmail.com> wrote: >> In hindsight, I am disappointed with the choice of conditional syntax. I >> know it's too late to change. The problem is >> >> y = some thing or other if x else something_else >> >> When scanning this my eye tends to see the first phrase and only later >> notice that it's conditioned on x (or maybe not notice at all!). >> Particularly if 'some thing or other' is long or complicated. > > You're talking strictly about readability, which among other things is > in the eye of the beholder, of course. Temporary variables can clean > up some code, even if choosing names can be a hassle and it's more > things to keep track of. Long lines and extra variables form a trade- > off. You are writing a line with a conditional expression the value > of which depends on something. What does it depend on, what is its > value if that's true, and what is it if it's false? '...if...else...' > only takes 6 characters... maybe you want more! > > If you're looking for a strictly syntactic construct, you can always > "fire blanks", or tracers, if the analogy's more accurate. > > z= conditionally( x ) if b else y > > This could serve as a gentle reminder, even where 'conditionally' > returns its argument, i.e. is the identity function. You can always > roll your own ternary with extra parameters too: > > z= condition( b, x, y ) > > Just don't confuse it with threading.Condition. > > Otherwise, you're stuck with old syntax markers, and unless you > wanted: > > z= if b then x else y > > You're out of options. You have to express it somehow. Did you want > the condition first? Was there an alternative proposal you > preferred? IINM if I'm not mistaken, > > z= b and x or y > > works just the same so long as x evaluates to True, as it will be > tested. > > Feel free to write your own from scratch, and we'll see how close > Python can come to resembling it. > > I suppose you can compare it to someone who stops listening before the > word 'if', and completely misunderstands your statement. "Feed the > dog if he's standing near the food dish" != "Feed the dog", which can > of course lead to errors of both omission and commission (doing too > little -or- too much). There's no way to fix that in a guaranteed > way, except to say, "listen to the whole statement". > > And strictly sarcastically, what did you want to do with reading the > program? Why were you reading it? <snicker, ducks> I find I'm often tripped up by: x = Y (lots of constructor arguments....) if something ... on first glance, I don't notice the if. Why am I reading this? Umm, because I wrote it. From marco.bizzarri at gmail.com Thu Sep 4 07:42:50 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 13:42:50 +0200 Subject: Coming from .NET and VB and C In-Reply-To: <48bfc4e4$0$13232$426a74cc@news.free.fr> References: <d20e9c18-9607-4746-a34a-c37ef6c22aef@d45g2000hsc.googlegroups.com> <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <mailman.471.1220523953.3487.python-list@python.org> <48bfc4e4$0$13232$426a74cc@news.free.fr> Message-ID: <3f0d61c40809040442q44cb99c8y70a60eefe2601d74@mail.gmail.com> On Thu, Sep 4, 2008 at 1:23 PM, Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> wrote: >> >> The appearance is not an RDBMS, at least, maybe it is, but under the >> surface. > > Not AFAIK, cf: > http://en.wikipedia.org/wiki/BigTable > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for the pointer, Bruno... I wrote from my memory, but there is some bank of it which need quick replace ;) -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From roseeea at gmail.com Sat Sep 20 04:58:17 2008 From: roseeea at gmail.com (ROSEEE) Date: Sat, 20 Sep 2008 01:58:17 -0700 (PDT) Subject: The Python computer language Message-ID: <7d3f9f43-8094-4bd0-980c-eb721b5a5051@o40g2000prn.googlegroups.com> http://pthoncomputerlanguage.blogspot.com From sonawane.manoj at gmail.com Mon Sep 1 06:14:22 2008 From: sonawane.manoj at gmail.com (Manoj) Date: Mon, 1 Sep 2008 03:14:22 -0700 (PDT) Subject: list + dictionary searching Message-ID: <6e642a00-9301-440d-902c-63713cf4a793@a2g2000prm.googlegroups.com> Hello All, I am very new to python. Any help will be highly appreciated. Thanks I have a list of dictionaries: a = [{'username': u'John Wang', 'user_utilization': 1.0, 'month': 9, 'user_id': 4, 'year': 2008}, {'username': u'John Wang', 'user_utilization': 1.0, 'month': 10, 'user_id': 4, 'year': 2008}, {'username': u' ', 'user_utilization': 1.0, 'month': 9, 'user_id': 1, 'year': 2008}] I would like to : search dictionaries within this list create a new list with dictionaries which gives 1 dictionary for every user with month_year as a key and utilization for that month as a value Please give your thoughts Thanks, Manoj From MrJean1 at gmail.com Thu Sep 4 20:43:50 2008 From: MrJean1 at gmail.com (MrJean1) Date: Thu, 4 Sep 2008 17:43:50 -0700 (PDT) Subject: Python test case management system? References: <b7033321-db3e-4872-b928-f9a07db79918@f63g2000hsf.googlegroups.com> Message-ID: <2e6fb98b-0553-42fb-b6e8-50854466034e@2g2000hsn.googlegroups.com> Perhaps Qmtest fits your needs <http://www.codesourcery.com/qmtest/index_html> /Jean On Sep 4, 4:36?pm, Mudcat <mnati... at gmail.com> wrote: > I had originally planned on writing my own software for managing test > cases; however new boss = new directive. This will make it more > difficult to get the functionality I need for test cases that are > automated and executed using python. ? I've searched for alternatives > but so far haven't come up with any good options. > > Does anyone know of a good test case management system written in > python, or possibly another application (either open source or > commercial) that can be extended using python? > > Thanks From tom.willis at gmail.com Sat Sep 20 11:09:47 2008 From: tom.willis at gmail.com (Thomas G. Willis) Date: Sat, 20 Sep 2008 08:09:47 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <aa7392e9-908d-441d-a1f5-e75ca47c0da9@d45g2000hsc.googlegroups.com> On Sep 20, 5:23?am, candide <cand... at free.invalid> wrote: > Excerpt quoted fromhttp://www.astro.ufl.edu/~warner/prog/python.html: > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > Thanks for any comment. My comment is "Who cares?" I was always under the impression that if any language truly was "OO" it would be smalltalk. And I don't derive any benefit from smalltalk at all. I do however derive substantial benefit from other languages that "OO zealots" would likely poo poo on including python. From fredrik at pythonware.com Thu Sep 4 15:41:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 21:41:33 +0200 Subject: Not fully understanding the role of Queue.task_done() In-Reply-To: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: <g9pdle$1b2$1@ger.gmane.org> Martin DeMello wrote: > Reading up on python's built in Queue class, though, it seems oriented > towards "job queues", with a two-step dequeue operation (get() and > task_done()). I'm worried that this would make it too heavyweight for > my application. Is ther documentation somewhere on what exactly > task_done() does, and whether I can disable the tracking of a job once > it's removed from the queue? The python docs for the Queue module were > a bit light. "task_done" just decrements a counter (incremented by "put"). when the counter reaches zero, the "join" call is unblocked. </F> From tjreedy at udel.edu Mon Sep 8 16:38:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Sep 2008 16:38:31 -0400 Subject: lacking follow-through In-Reply-To: <47c890dc0809081204o3511b9dck1adadd98f73ca2b7@mail.gmail.com> References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <ccf8d124-4609-48a6-b487-7cccc6d9c4b9@a3g2000prm.googlegroups.com> <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <47c890dc0809081204o3511b9dck1adadd98f73ca2b7@mail.gmail.com> Message-ID: <ga42g6$kkv$1@ger.gmane.org> Chris Rebert wrote: > On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <ewertman at gmail.com> wrote: >> To expand on this a little bit, I've been subscribed to this group >> for a couple of months, but there seems to be a bit more gray area >> between what would go to a 'python-dev' group and a 'python-user' >> group. Long debates about language features and abstract ideas would >> appeal to the former, but not the latter. The py-dev mailing list, and its gmane.comp.python.devel mirror, is for concrete discussion, mostly by developers, of how to develop the current and next release. The current focus in on finishing 2.6 for release. Almost nothing that has appeared here recently belongs there. It is much more common for people to post there usage questions that belong here or speculative issues that could also go to python-ideas. >> Certainly I fall into the >> user category.. I'm pretty happy with python, and generally just >> adjust to it's design and features, rather than spend lots of time on >> whether they are 'right' or could be 'better'. /shrug Long rehashes of decided issues, like the name of subprocess.popen, or the default of sum(), belong here better than anywhere else, if anywhere ;-). > Yeah, suggestions about changing the language are much better suited > to the more-specific Python-ideas or Python-3000 mailinglists than the > general-purpose c.l.p The Python-3000 mailing list, and the gmane.comp.python.python-3.devel mirror, is the py-dev equivalent for python3-specific issues. tjr From alan.isaac at gmail.com Mon Sep 8 09:15:38 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Mon, 08 Sep 2008 13:15:38 GMT Subject: Learning Python In-Reply-To: <mailman.634.1220738820.3487.python-list@python.org> References: <mailman.634.1220738820.3487.python-list@python.org> Message-ID: <_z9xk.830$sq3.754@trnddc07> On 9/6/2008 5:17 AM James Pilling apparently wrote: > Hi im currently starting to learn python in sixth form at school any tips? The books suggestions of others are quite good. Here is another approach: pick an easily understandable application, and work doing things with it. Perhaps immodestly, I think that as soon as you understand how to define a function and a class, you can treat this paper http://jasss.soc.surrey.ac.uk/11/3/8.html as an introduction to applied Python programming. The application area is very specific---game theoretic simulations---but the illustrated techniques are meant to be more general. Alan Isaac From rowland at river2sea.org Tue Sep 2 11:42:13 2008 From: rowland at river2sea.org (Rowland Smith) Date: Tue, 2 Sep 2008 11:42:13 -0400 Subject: source for the property function Message-ID: <6072EAA1-9891-4910-80B4-A26820712387@river2sea.org> Anyone know where the source code for the built-in property function is located in a python distribution? I would like to see how it works - mainly, how does it know which class it is being called from? Thanks, Rowland From rcdailey at gmail.com Fri Sep 5 16:15:02 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 15:15:02 -0500 Subject: Need formatting suggestion for long strings In-Reply-To: <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> References: <mailman.580.1220642999.3487.python-list@python.org> <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> Message-ID: <496954360809051315v44438624vf16240216d8ba2c5@mail.gmail.com> On Fri, Sep 5, 2008 at 3:06 PM, aha <aquil.abdullah at gmail.com> wrote: > Can you be more specific? What is the formatting criteria? Are you > talking about formatting the string for display or are you talking > about the source? Apologies for the confusion. My concern is both. Allow me to explain: I'm concerned about the formatting of the string in that I do not want the way I split the string up in source code to affect the way the string is displayed to the console. In other words, in source, if I break up a single string into multiple lines (using carriage returns), I would expect the string to still render as a single-line string. I'm also concerned about the source formatting, because I do not want the single-line string to run off the edge of my display. I want it to be in "Paragraph form" in the source code, but remain a single-line when printed. I hope that makes sense. Let me know if I need to clarify more. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080905/59822282/attachment-0001.html> From aaron.hildebrandt at gmail.com Wed Sep 10 14:16:38 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 11:16:38 -0700 (PDT) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <ga91ft$12t$1@inews.gazeta.pl> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> Message-ID: <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> Taking everything into consideration, my code is now: import struct file = open("test.gde", "rb") signature = file.read(3) version, attr_count = struct.unpack('II', file.read(8)) print signature, version, attr_count for idx in xrange(attr_count): attr_id, attr_val_len = struct.unpack('II', file.read(8)) attr_val = file.read(attr_val_len) print attr_id, attr_val_len, attr_val file.close() which gives a result of: GDE 2 2 1 4 ? 2 4 ??? Essentially, the same results I was originally getting :( From alexomoto at gmail.com Tue Sep 30 05:20:16 2008 From: alexomoto at gmail.com (alexomoto at gmail.com) Date: Tue, 30 Sep 2008 02:20:16 -0700 (PDT) Subject: Problems compiling on CentOS Python 2.5 References: <mailman.1448.1222252621.3487.python-list@python.org> Message-ID: <49c0dc41-de2c-49da-a27f-7697fdb420ae@m73g2000hsh.googlegroups.com> On Sep 23, 10:37?am, "F." <dev... at pas-world.com> wrote: > Hello, > I have problems makingpythonon CentOS 5. > Seems that can not find something. I can not find the problem. > Where is the problem? > > > case $MAKEFLAGS in \ > > ? ? ? ? *-s*) ?CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG ?-fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python-E ./setup.py -q build;; \ > > ? ? ? ? *) ?CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG ?-fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python-E ./setup.py build;; \ > > ? ? ? ? esac > > running build > > running build_ext > > db.h: found (4, 3) in /usr/include > > db lib: using (4, 3) db-4.3 > > INFO: Can't locate Tcl/Tklibs and/or headers > > building '_ssl' extension > > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes -I. -I/home/unStable/progC/exLibs/Python-2.5.2/Python-2.5.2/./Include -I. -IInclude -I./Include -I/usr/local/include -I/directory/Python-2.5.2/Python-2.5.2/Include -I/directory/Python-2.5.2/Python-2.5.2 -c /directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.c -o build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o > > gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-i686-2.5/_ssl.so > > *** WARNING: renaming "_ssl" since importing it failed: build/lib.linux-i686-2.5/_ssl.so: undefined symbol: krb5_auth_con_getrcache > > running build_scripts > > -- > > -- > Publicidadhttp://www.pas-world.com I also spent a couple hours googling for this same problem! It's not tough to figure it out but would have saved time and stress if i hit the answer on my first search. I am also using CentOS 4.4, 4.5 and python 2.4.4. I debugged the Python installation script to find that the tk.h/tcl.h headers are missing. Installing the tk-devel package (using yum) installs the headers. Then re-install Python. From sayananbig at gmail.com Mon Sep 22 17:58:45 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Mon, 22 Sep 2008 14:58:45 -0700 (PDT) Subject: python timers and COM/directshow Message-ID: <ee4ce745-536d-48ca-84f9-1665bd416fc3@x16g2000prn.googlegroups.com> Hey all, So I've written a simple video player using directshow/COM in VC++, and I'm in the process of translating it to python. For example, when the avi starts playing, I have a call media_control.Run() , etc. I'm wondering how I should go about updating my gtk.Hscale widget as a trackbar for the avi player. In C++, I have the following callbacks that update the scrollbar and video position with a timer. void CvideoDlg::OnNMReleasedcaptureSlider1(NMHDR *pNMHDR, LRESULT *pResult) { //Slider event handler LONGLONG lPos = 0; LONGLONG lDuration = 0; KillTimer(101); g_pSeek->GetDuration(&lDuration); g_pSeek->GetCurrentPosition(&lPos); Videopos= m_slider.GetPos(); //Sets new video position to that of the slider, which user inputs lPos = ((long)Videopos * (lDuration/num_of_frames)); g_pSeek->SetPositions(&lPos, AM_SEEKING_AbsolutePositioning,NULL, AM_SEEKING_NoPositioning); *pResult = 0; } void CvideoDlg::OnTimer(UINT nIDEvent) { //Timer event handler. LONGLONG lPos = 0; LONGLONG lDuration = 0; g_pSeek->GetDuration(&lDuration); g_pSeek->GetCurrentPosition(&lPos); Videopos = (int)(lPos * num_of_frames/ lDuration); m_slider.SetPos(Videopos); if (Videopos==(int)(last_frame)) //If we get to the end of the selection, the video pauses pause(); else{ UpdateData(); //Updates the slider controller and position CDialog::OnTimer(nIDEvent);} } I'm wondering how I would implement similar callbacks in Python for a gtk.Hscale, and some sort of time [I'm not familiar with Pythons timers/threading at all]. From ivanov.maxim at gmail.com Tue Sep 16 07:25:34 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Tue, 16 Sep 2008 15:25:34 +0400 Subject: What is "finally:" for? Message-ID: <fbfa7b0c0809160425p4fc5f598v89c5b0ba6a7eeca8@mail.gmail.com> Hi all! When and where I should use try-except-finally statement? What is the difference between: -------- try: A... except: B.... finally: C... -------- and ------- try: A... except: B.... C... From Lie.1296 at gmail.com Sun Sep 28 05:49:11 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 02:49:11 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <66606235-be55-458a-9e14-09e6c766201d@p31g2000prf.googlegroups.com> On Sep 28, 12:37?pm, est <electronix... at gmail.com> wrote: > From python manual > > str( [object]) > > Return a string containing a nicely printable representation of an > object. For strings, this returns the string itself. The difference > with repr(object) is that str(object) does not always attempt to > return a string that is acceptable to eval(); its goal is to return a > printable string. If no argument is given, returns the empty string, > ''. > > now we try this under windows: > > >>> str(u'\ue863') > > Traceback (most recent call last): > ? File "<stdin>", line 1, in <module> > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0 > : ordinal not in range(128) > > FAIL. And it is correct to fail, ASCII is only defined within range(128), the rest (i.e. range(128, 256)) is not defined in ASCII. The range(128, 256) are extension slots, with many conflicting meanings. > > also almighty Linux > > Python 2.3.4 (#1, Feb ?6 2006, 10:38:46) > [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> str(u'\ue863') > > Traceback (most recent call last): > ? File "<stdin>", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0: ordinal not in range(128) > > Python 2.4.4 (#2, Apr ?5 2007, 20:11:18) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> str(u'\ue863') > > Traceback (most recent call last): > ? File "<stdin>", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0: ordinal not in range(128) > > Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> str(u'\ue863') > > Traceback (most recent call last): > ? File "<stdin>", line 1, in <module> > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0: ordinal not in range(128) If that str() function has returned anything but error on this, I'd file a bug report. > The problem is, why the f**k set ASCII encoding to range(128) ???????? > while str() is internally byte array it should be handled in > range(256) !!!!!!!!!! string is a byte array, but unicode and ASCII is NOT. Unicode string is a character array defined up to range(65535). Each character in unicode may be one or two bytes long. ASCII string is a character array defined up to range(127). Other than Unicode (actually utf-8, utf-16, and utf-32) and ASCII, there are many other encodings (ECBDIC, iso-8859-1', ..., 'iso-8859-16', 'KOI8', 'GB18030', 'Shift-JIS', etc, etc, etc) each with conflicting byte to characters mappings. Fortunately, most of these encodings do share a common ground: ASCII. Actually, when a strictly stupid str() receives a Unicode string (i.e. character array), it should return a <unicode s at 0x423549af813e4954>, but it doesn't, str() is smarter than that, it tries to convert whatever fits into ASCII, i.e. characters lower than 128. Why ASCII? Because character from range(128, 256) varies widely and it doesn't know which encoding you want to use, so if you don't tell me what encoding to use it'd not guess (Python Zen: In the face of ambiguity, refuse the temptation to guess). If you're trying to convert a character array (Unicode) into a byte string, it's done by specifying which codec you want to use. str() tries to convert your character array (Unicode) to byte string using ASCII codec. s.encode(codec) would convert a given character array into byte string using codec. > http://bugs.python.org/issue3648 > > One possible solution(Windows Only) > > >>> str(u'\ue863'.encode('mbcs')) > '\xfe\x9f' actually str() is not needed, you need only: u'\ue863'.encode('mbcs') > >>> print u'\ue863'.encode('mbcs') > ? > > I now spending 60% of my developing time dealing with ASCII range(128) > errors. It was PAIN!!!!!! Despair not, there is a quick hack: # but only use it as temporary solution, FIX YOUR CODE PROPERLY str_ = str str = lambda s = '': s.encode('mbcs') if isinstance(s, basestring) else str_(s) > Please fix this issue. > > http://bugs.python.org/issue3648 > > Please. From torainLight at gmail.com Sat Sep 20 06:54:22 2008 From: torainLight at gmail.com (satoru) Date: Sat, 20 Sep 2008 03:54:22 -0700 (PDT) Subject: how can i check whether a variable is iterable in my code? References: <b29d40b7-4000-4d75-b657-af73573c5c32@a8g2000prf.googlegroups.com> <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> On Sep 20, 6:35?pm, Aidan <ai... at gmail.com> wrote: > satoru wrote: > > hi, all > > i want to check if a variable is iterable like a list, how can i > > implement this? > > this would be one way, though I'm sure others exist: > > if hasattr(yourVar, '__iter__'): > ? ? ? ? # do stuff thank you,but this will miss out sequences like string just because it doesn't have an attribute named '__iter__' From tjreedy at udel.edu Sat Sep 13 14:21:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Sep 2008 14:21:49 -0400 Subject: Profiling, sum-comprehension vs reduce In-Reply-To: <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> Message-ID: <gah0bq$kf6$1@ger.gmane.org> Steven D'Aprano wrote: > If you want to see reduce really shine, time it with a C-based function > rather than one written in pure Python: > >>>> Timer('reduce(add, xrange(10000))', > ... 'from operator import add').repeat(number=10000) > [19.724750995635986, 19.410486936569214, 19.614511013031006] >>>> Timer('reduce(add, xrange(10000))', > ... 'def add(x, y): return x+y').repeat(number=10000) > [45.210143089294434, 44.814558982849121, 46.906874895095825] ... > Of course, sum() is even faster than reduce: > >>>> Timer('sum(xrange(10000))').repeat(number=10000) > [9.814924955368042, 8.7169640064239502, 9.5062401294708252] 'Of course', because the irreducible difference between reduce(add.seq) and sum(seq) is that reduce has to call an add function while sum has the operation built-in in place of a call. From seandavi at gmail.com Fri Sep 5 21:56:37 2008 From: seandavi at gmail.com (Sean Davis) Date: Fri, 5 Sep 2008 18:56:37 -0700 (PDT) Subject: running python as a dameon References: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> Message-ID: <6e7ead25-baf1-400a-a52f-568f37351aab@8g2000hse.googlegroups.com> On Sep 5, 5:55?pm, peyman <peymanfara... at gmail.com> wrote: > Hi > > I have a Natural Language Processing (NLP) code written in python that > reads into memory a large training file and then given a sentence tags > it, using the training data. I want to put this NLP code on a server > which handles all incoming client http requests via PHP. What I want > to do is to provide the python NLP program as a service to any other > PHP/Java/Ruby process request. So the mapping is > > http -> apache -> PHP/Java/Ruby/... -> Python NLP Why not use a simple CGI script or wsgi application? You could make the service online and interactive and with the same application and code make an XMLRPC web service. So, things would look more like: http -> apache -> Python (running NLP and serving requests) You can use apache to proxy requests to any one of a dozen or so python-based webservers. You could also use mod_wsgi to interface with a wsgi application. Sean > > I can not provide this service as a shell script because of the > inefficiencies of having to load into memory a large training data to > every service request. So what I want to do is to provide the NLP > service to other application processes as a python daemon > > http -> apache -> PHP/Java/Ruby/... -> Python Dameon -> Python NLP > > The daemon loads into memory the training data once. then every > service request event invokes the appropriate NLP code in the python > program. I've tried to use play around with twisted but am not making > too much of a headway. What I've done in the NLP code is to do this: > > # filename: NLP.py > def parse(sentence): > ? ? structure=getentities(sentence) > ? ? print 'subject: \t',' '.join(structure[0]) > ? ? print 'predicate: \t',' '.join(structure[1]) > ? ? print 'TE: \t\t',' '.join(structure[2]) > > class TLogicClass(): > ? ? def __init__(self,prop): > ? ? ? ? return parse(prop) > > then in the dameon code done this > > # filename: dameon.py > from twisted.application import service > import NLP > > application=service.Application("nlp") > ParseService=NLP.TLogicClass("time flies like an arrow") > ParseService.setServiceParent(application) > > but I get the following error when I run twistd -y daemon.py > > >> Failed to load application: TLogicClass instance has no attribute 'setServiceParent' > > I suspect I need to put twisted in the NLP.py but I don't know what I > need to do in order to get what I want to do which is: > > to load into memory only once a large training data that can then be > queried by another (non-python) event based process ?(I need "reactor" > class?). > > thank you in advance for your help From michele.simionato at gmail.com Wed Sep 3 23:26:37 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 3 Sep 2008 20:26:37 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> Message-ID: <df93de86-e7fc-4131-b931-e5b39ffb604f@a18g2000pra.googlegroups.com> On Sep 4, 12:26?am, bukzor <workithar... at gmail.com> wrote: > I'm trying to optimize my number of connections by not fully > initializing (read: not connecting) my connection until it's used in > some way. I had the same use case and I solved with a simple property. Here is the code I have for pymssql: @property def conn(self): if self._conn is None: self._conn = _mssql.connect(self.host, self.user,self.passwd) self._conn.select_db(self.dbname) return self._conn The connection is really instantiate only when you call self.conn to perform the query, not when you instantiate the class. From fredrik at pythonware.com Thu Sep 4 18:21:59 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 00:21:59 +0200 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> Message-ID: <g9pn28$4u1$1@ger.gmane.org> Robert Dailey wrote: > I currently have a dictionary object that I'm doing the following with: > > if lib not in stage_map: > # ... do stuff ... > > However, this will perform a case-sensitive comparison between lib and > each key in stage_map. Is there a way to make this do a case-insensitive > comparison instead? dictionary lookups use the exact value. to make a case-insensitive lookup, use key.lower() instead of key when creating the dictionary, and then do if lib.lower() not in state_map: ... </F> From rpw3 at rpw3.org Mon Sep 1 06:55:26 2008 From: rpw3 at rpw3.org (Rob Warnock) Date: Mon, 01 Sep 2008 05:55:26 -0500 Subject: The Importance of Terminology's Quality References: <rem-2008may08-005@yahoo.com> <g8bflo$984$1@localhost.localdomain> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <rem-2008sep01-003@yahoo.com> Message-ID: <VeOdnUJG6cODVybVnZ2dnUVZ_qjinZ2d@speakeasy.net> Robert Maas, <jaycx2.3.calrobert at spamgourmet.com.remove> wrote: +--------------- | > From: rpw3 at rpw3.org (Rob Warnock) | > In the LGP-30, they used hex addresses, sort of[1], but the | > opcodes (all 16 of them) had single-letter mnemonics chosen so that | > the low 4 bits of the character codes *were* the correct nibble for | > the opcode! ;-} ... | By the way, do you remember exactly all the 16 opcodes, or have a | Web reference available? +--------------- There are quite a few out there; here's one: http://www.users.nwark.com/~rcmahq/jclark/lgp30.htm Some notes on the opcodes: - "Bring" (B) would be called "Load" in current parlance. - "Extract" (E) would be called "And" in current parlance. - "Unconditional Transfer" (U) would be called "Jump" or "Branch". - "Hold" (H) would be called "Store"; "Clear" (C) would be called "Store-and-Clear" (the "DCA" instruction of the DEC PDP-8). - There are two "Multiply" ops, "M" & "N", depending on whether the upper or lower bits (respectively) of the product are returned. - "Store Address" (Y) stores an address in the AC into the address field of the destination [yes, modifying the code in-place!! -- it was mostly used for indexing through arrays], whereas the "Return Address" (R) stores the current instruction address + 2 into the address field of the destination. The subroutine calling sequence is thus an "R/U" pair: R foo_last U foo where the FOO subroutine might be written as: foo: ... ... foo_last: U foo_last ; overwritten +--------------- | > The LGP-30 character code was defined before the industry had | > yet standardized on a common "hex" [sic, "hexadecimal", base 16 | > not base 6!!!] character set, ... | > they used "0123456789fgjkqw". | | That doesn't make sense. The low-order four bits of those letters | aren't consecutive ascending values from 9+1 to 9+6. Did you make a | typo, or did you explain something wrong? +--------------- No, what I wrote is correct. The low 4 bits of "0123456789fgjkqw" *are* 0 through 16 (or "0123456789abcdef" in current "hex")... IN THE *LGP-30 FLEXOWRITER* CHARACTER CODE, *not* in ASCII or EBCDIC or Baudot or any other standard code. Well, actually, it's a little more complex than that. The LGP-30 used a 6-bit "keyboard" code on the Flexowriter (and the paper tape reader & punch), but the machine could be put into either 6-bit or 4-bit input mode. In the latter, only the first four bits of each code got shifted into the accumulator. So I suppose you could say those were the *upper* 4 bits of each character, though when read into the accumulator in "4-bit input mode" they truly *were* the lower 4 bits. (Sorry for the confusion. It was an "interesting" machine.) +--------------- | (map 'list #'char-code "0123456789fgjkqw") | => (48 49 50 51 52 53 54 55 56 57 102 103 106 107 113 119) +--------------- That's ASCII. The LGP-30 did not use ASCII. The LGP-30 used Flexowriter keyboard code, see: http://ed-thelen.org/comp-hist/lgp-30-man-f002.gif -Rob p.s. The full programming manual for the LGP-30 can be found here: http://ed-thelen.org/comp-hist/lgp-30-man.html but good luck reading its archaic style. ;-} ----- Rob Warnock <rpw3 at rpw3.org> 627 26th Avenue <URL:http://rpw3.org/> San Mateo, CA 94403 (650)572-2607 From joefazee at gmail.com Tue Sep 23 13:32:03 2008 From: joefazee at gmail.com (A. Joseph) Date: Tue, 23 Sep 2008 10:32:03 -0700 Subject: Matrix programming Message-ID: <ea09b3700809231032h677f5b05k5a37397296a7e6e9@mail.gmail.com> I need an ebook or tutorial that teach matrix programming. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080923/4b43bf53/attachment-0001.html> From frank at chagford.com Thu Sep 18 02:28:55 2008 From: frank at chagford.com (Frank Millman) Date: Wed, 17 Sep 2008 23:28:55 -0700 (PDT) Subject: XML-schema 'best practice' question Message-ID: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Hi all This is not strictly a Python question, but as I am writing in Python, and as I know there are some XML gurus on this list, I hope it is appropriate here. XML-schemas are used to define the structure of an xml document, and to validate that a particular document conforms to the schema. They can also be used to transform the document, by filling in missing attributes with default values. In my situation, both the creation and the processing of the xml document are under my control. I know that this begs the question 'why use xml in the first place', but let's not go there for the moment. Using minixsv, validating a document with a schema works, but is quite slow. I appreciate that lxml may be quicker, but I think that my question is still applicable. I am thinking of adding a check to see if a document has changed since it was last validated, and if not, skip the validation step. However, I then do not get the default values filled in. I can think of two possible solutions. I just wondered if this is a common design issue when it comes to xml and schemas, and if there is a 'best practice' to handle it. 1. Don't use default values - create the document with all values filled in. 2. Use python to check for missing values and fill in the defaults when processing the document. Or maybe the best practice is to *always* validate a document before processing it. How do experienced practitioners handle this situation? Thanks for any hints. Frank Millman From antroy at gmail.com Tue Sep 16 08:33:23 2008 From: antroy at gmail.com (Ant) Date: Tue, 16 Sep 2008 05:33:23 -0700 (PDT) Subject: What is "finally:" for? References: <mailman.1105.1221564360.3487.python-list@python.org> <fd2f0acc-055e-40f0-8734-d31a094e1bf6@k30g2000hse.googlegroups.com> Message-ID: <a87d6663-1fd8-40ff-b1bc-adfcabcbc0d2@m73g2000hsh.googlegroups.com> On Sep 16, 12:30?pm, Andreas Kaiser <kaiser.voc... at gmail.com> wrote: > On 16 Sep., 13:25, "Max Ivanov" <ivanov.ma... at gmail.com> wrote:> Hi all! > > When and where I should use try-except-finally statement? What is the > > difference between: > > -------- > > try: > > ? A... > > except: > > ? B.... > > finally: > > ? C... > > -------- > > It does A if no exception or B if an exception occurs. THEN it does > always C. Rather it runs the code in A. If an exception is thrown in A, B is then run. C is run regardless. > > ------- > > try: > > ? A... > > except: > > ? B.... > > C... > > If an exception occurs, C is never reaching. Whether or not C runs will depend on what code is present in B (e.g. it could return, or throw a different exception). Typically you will use a finally clause if there is some cleanup that should occur regardless of whether an exception is thrown. For example: def getNumbers(filename): numbers = [] fh = open("test.txt") # Should contain lines of numbers try: for line in fh: if line.strip(): numbers.append(int(line.strip())) except ValueError, e: return None finally: fh.close() return numbers This ensures that open files are closed for example. -- Ant. From prologic at shortcircuit.net.au Sun Sep 7 17:49:41 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 07:49:41 +1000 Subject: formatting a string with thousands separators In-Reply-To: <RTVwk.660$Dj1.566@trnddc02> References: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> <RTVwk.660$Dj1.566@trnddc02> Message-ID: <e1a84d570809071449s3978b9c3w8d16c95091c966be@mail.gmail.com> Hi, There is a much easier more consistent way: >>> import locale >>> locale.setlocale(locale.LC_ALL, "en_AU.UTF-8") 'en_AU.UTF-8' >>> locale.format("%0.2f", 5000000, True) '5,000,000.00' >>> cheers James On Mon, Sep 8, 2008 at 5:24 AM, Alan G Isaac <alan.isaac at gmail.com> wrote: > On 9/7/2008 12:22 PM SimonPalmer apparently wrote: >> >> anyone recommend a way of formatting floats with comma separators? > > > http://code.activestate.com/recipes/498181/ > > Alan Isaac > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From seandavi at gmail.com Wed Sep 10 13:59:48 2008 From: seandavi at gmail.com (Sean Davis) Date: Wed, 10 Sep 2008 10:59:48 -0700 (PDT) Subject: emulating read and readline methods Message-ID: <ee4202f1-ce8f-458e-9627-08215351694d@e53g2000hsa.googlegroups.com> I have a large file that I would like to transform and then feed to a function (psycopg2 copy_from) that expects a file-like object (needs read and readline methods). I have a class like so: class GeneInfo(): def __init__(self): #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ gene_info.gz',"/tmp/gene_info.gz") self.fh = gzip.open("/tmp/gene_info.gz") self.fh.readline() #deal with header line def _read(self,n=1): for line in self.fh: if line=='': break line=line.strip() line=re.sub("\t-","\t",line) rowvals = line.split("\t") yield "\t".join([rowvals[i] for i in [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" def readline(self,n=1): return self._read().next() def read(self,n=1): return self._read().next() def close(self): self.fh.close() and I use it like so: a=GeneInfo() cur.copy_from(a,"gene_info") a.close() It works well except that the end of file is not caught by copy_from. I get errors like: psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error during .read() call CONTEXT: COPY gene_info, line 1000: "" for a 1000 line test file. Any ideas what is going on? Thanks, Sean From akathorn at gmail.com Thu Sep 4 23:13:28 2008 From: akathorn at gmail.com (Akathorn Greyhat) Date: Fri, 5 Sep 2008 04:13:28 +0100 Subject: Curious: 2134 2004-10-06 08:55:20Z fredrik Message-ID: <af788ad10809042013hf365d49y2577d735d8ed83e2@mail.gmail.com> I had an import error and I get this error: Traceback (most recent call last): File "C:\Eclipse\pyworkspace\CodenameRazor0.2\src\app.py", line 11, in <module> import core File "C:\Python25\lib\site-packages\PIL\__init__.py", line 3, in <module> # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ ImportError: No module named data I've already fix it, but I don't know what the hell does this line means: # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ It seens curious, isn't it? -- Akathorn Greyhat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080905/858e5057/attachment-0001.html> From skip at pobox.com Mon Sep 29 17:38:33 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 Sep 2008 16:38:33 -0500 Subject: Source code for python nativ methods and classes In-Reply-To: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> References: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> Message-ID: <18657.19161.786208.571131@montanaro-dyndns-org.local> mohed> I am interrested in seeing the source code for all the nativ mohed> builtin methods and clases in python. Is there a webpage that mohed> lists them or is this done easier some other way. Browse the source. You can download it then poke around using your favorite editor: http://www.python.org/download/ or browse the source online: http://svn.python.org/view/python/trunk/ Skip From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 24 03:23:49 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 09:23:49 +0200 Subject: python syntax for conditional is unfortunate In-Reply-To: <mailman.1440.1222221042.3487.python-list@python.org> References: <mailman.1434.1222213968.3487.python-list@python.org> <ee44675b-04ad-48b3-8eed-629ebb10d616@z66g2000hsc.googlegroups.com> <mailman.1440.1222221042.3487.python-list@python.org> Message-ID: <48d9eaf9$0$6127$426a34cc@news.free.fr> Neal Becker a ?crit : (snip) > I find I'm often tripped up by: > > x = Y (lots of constructor arguments....) if something ... > > on first glance, I don't notice the if. Indeed. The inline conditionnal syntax is obviously innappropriate here. It's just like list-comprehensions : just fine for simple use case, definitively not appropriate when it comes to anything complex. IOW : it's not the syntax that's unfortunate, it's the coding style that's wrong. My 2 cents... From bj_666 at gmx.net Tue Sep 2 14:26:38 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 18:26:38 GMT Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: <6i5equFol29aU5@mid.uni-berlin.de> On Tue, 02 Sep 2008 10:36:50 -0700, hofer wrote: > sed 's/\.\..*//' \ ### remove '//' comments | sed 's/#.*//' Comment does not match the code. Or vice versa. :-) Untested: from __future__ import with_statement from itertools import ifilter, ifilterfalse, imap def is_junk(line): line = line.rstrip() return not line or line.startswith('//') or line.startswith('#') def extract_numbers(line): result = map(int, line.split()[:2]) assert len(result) == 2 return result def main(): with open('test.txt') as lines: clean_lines = ifilterfalse(is_junk, lines) pairs = imap(extract_numbers, clean_lines) print '\n'.join(b for a, b in pairs if a + b == 42) if __name__ == '__main__': main() Ciao, Marc 'BlackJack' Rintsch From pete.forman at westerngeco.com Wed Sep 10 10:25:23 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 10 Sep 2008 15:25:23 +0100 Subject: Python-URL! - weekly Python news and links (Sep 9) References: <ga6m20$f60$1@lairds.us> Message-ID: <hc8of57w.fsf@wgmail2.gatwick.eur.slb.com> "Gabriel Genellina" <python-url at phaseit.net> writes: > QOTW: "So why am I supposed to care about SOAP again? Oh yes, the > wizards I can use to generate 'web service end-points' from > programming language code. My years in the SOAP trenches just > makes me laugh myself half to death at that notion: I would > probably have been twice as productive if every time I reached for > a SOAP toolkit I instead just coded straight XML in HTTP. And this > represents experience with Python, Java and C WS tools." - Uche > Ogbuji It looks as if that Large Hadron Collider is having ill effects already. A week has been stretched into 6 years. ;-) http://lists.xml.org/archives/xml-dev/200302/msg00259.html -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From monuindia at gmail.com Thu Sep 11 14:19:21 2008 From: monuindia at gmail.com (Monu) Date: Thu, 11 Sep 2008 11:19:21 -0700 (PDT) Subject: shelve file name extention References: <dc898319-7903-40c1-8b6f-31d235595d2f@k37g2000hsf.googlegroups.com> <mailman.697.1220896094.3487.python-list@python.org> Message-ID: <e6f8cc29-f987-4649-8848-27249dcc0deb@l64g2000hse.googlegroups.com> On Sep 8, 1:47?pm, s... at pobox.com wrote: > ? ? Monu> When I am using shelve on my local machine it generates the db > ? ? Monu> file as given filename. But in another machine it's generating > ? ? Monu> <filename>.dat and .dir. ?can anyone tell me how can I force sheve > ? ? Monu> module to write the db in <filename>.dir and <filename>.dat, > ? ? Monu> instead of <filename>? Do I have to install a specific version of > ? ? Monu> the python? > > Shelve is just a thin layer on top of a concrete db file module. ?Sounds > like on your two machines there are different underlying db file modules > available. ?You're pretty much at the mercy of those modules as to file > naming. ?All you are giving it when opening a shelve file is the prefix. > > Skip Thanks Skip. So Can't I choose which module to use. Is there any preferance on which shelve chooses these modules? From M8R-yfto6h at mailinator.com Sun Sep 28 13:13:31 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 28 Sep 2008 10:13:31 -0700 Subject: Python 3.0 and repr Message-ID: <q6KdnXBZ9LioJkLVnZ2dnUVZ_u-dnZ2d@comcast.com> I don't understand the behavior of the interpreter in Python 3.0. I am working at a command prompt in Windows (US English), which has a terminal encoding of cp437. In Python 2.5: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> x=u'\u5000' >>> x u'\u5000' In Python 3.0: Python 3.0rc1 (r30rc1:66507, Sep 18 2008, 14:47:08) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> x='\u5000' >>> x Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\dev\python30\lib\io.py", line 1486, in write b = encoder.encode(s) File "c:\dev\python30\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u5000' in position 1: character maps to <undefined> Where I would have expected >>> x '\u5000' Shouldn't a repr() of x work regardless of output encoding? Another test: Python 3.0rc1 (r30rc1:66507, Sep 18 2008, 14:47:08) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> bytes(range(256)).decode('cp437') '\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\ x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=>?@ABC DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f???????????????? ???????????????????????????????????????????????????????????????????????????????? ???????????????????????????????\xa0' >>> bytes(range(256)).decode('cp437')[255] '\xa0' Characters that cannot be displayed in cp437 are being escaped, such as 0x00-0x1F, 0x7F, and 0xA0. Even if I incorrectly decode a value, if the character exists in cp437, it is displayed: >>> bytes(range(256)).decode('latin-1')[255] '?' However, for a character that isn't supported by cp437, incorrectly decoded: >>> bytes(range(256)).decode('cp437')[254] '?' >>> bytes(range(256)).decode('latin-1')[254] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\dev\python30\lib\io.py", line 1486, in write b = encoder.encode(s) File "c:\dev\python30\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in position 1: character maps to <undefined> Why not display '\xfe' here? It seems like this inconsistency would make it difficult to write things like doctests that weren't dependent on the tester's terminal. It also makes it difficult to inspect variables without hex(ord(n)) on a character-by-character basis. Maybe repr() should always display the ASCII representation with escapes for all other characters, especially considering the "repr() should produce output suitable for eval() when possible" rule. What are others' opinions? Any insight to this design decision? -Mark From castironpi at gmail.com Sun Sep 14 14:09:52 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 14 Sep 2008 11:09:52 -0700 (PDT) Subject: How to marshal objects to readable files? References: <mailman.1007.1221406286.3487.python-list@python.org> Message-ID: <143e575e-4745-4148-86de-deb2dbc0651d@m3g2000hsc.googlegroups.com> On Sep 14, 10:28?am, nielinjie <nielin... at gmail.com> wrote: > Hi list: > I just want to marshal objects (instance of custom classes)to a human > *READABEL *file/string, and also, I want unmarshal it back. in xml > format or any other format. > Any advice? Which lib should I use? > Thanks a lot. Nielinjie, There is no generic way; an object can contain a reference to another object. You can get started with ob.__dict__ as follows: >>> class A: pass ... >>> a= A() >>> a.b= 0 >>> a.c= 'abc' >>> a.__dict__ {'c': 'abc', 'b': 0} But the only way TMK (to my knowledge) to retrieve the contents is eval, which is very hackish. The PyYAML package produces the following (continued): >>> b= A() >>> b.d= 'efg' >>> b.e= 1.2 >>> a.d= b >>> b.parent= a >>> print yaml.dump( a ) &id001 !!python/object:__main__.A b: 0 c: abc d: !!python/object:__main__.A d: efg e: 1.2 parent: *id001 >>> print yaml.dump( b ) &id001 !!python/object:__main__.A d: efg e: 1.2 parent: !!python/object:__main__.A b: 0 c: abc d: *id001 >>> yaml.load( yaml.dump( a ) ) <__main__.A instance at 0x00D098A0> >>> _.__dict__ {'c': 'abc', 'b': 0, 'd': <__main__.A instance at 0x00D09788>} It caches IDs to reference circular references, and writes nested objects in place. As you can see, you don't need to dump both 'a' and 'b'; 'a' contains 'b' already. You do need the types of the objects already living in the same namespace as when you stored them. If it's not human readable enough for your use, please write an example of what you want your output to look like. Abstract is ok. PyYAML is available at http://pyyaml.org/ . Download from http://pyyaml.org/wiki/PyYAML . I've only skimmed it though. From gagsl-py2 at yahoo.com.ar Fri Sep 19 05:08:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 06:08:32 -0300 Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <gavaq2$klm$1@ger.gmane.org> <48D33497.4010403@wildenhain.de> Message-ID: <op.uhp00ishx6zn5v@gabriel2.softlabbsas.com.ar> En Fri, 19 Sep 2008 02:11:51 -0300, Tino Wildenhain <tino at wildenhain.de> escribi?: > Also I never saw a list where the threading often goes wrong like > this here - is there any special setup or is it just peoples MUA > which screws up? Perhaps it's due to the newsgroup/list duality... -- Gabriel Genellina From god1124 at gmail.com Thu Sep 4 21:01:25 2008 From: god1124 at gmail.com (Dream) Date: Thu, 4 Sep 2008 18:01:25 -0700 (PDT) Subject: Tkinter Radio button on the second window Message-ID: <e5da0605-0dc4-41fe-9a9f-fa75b9094e5a@b30g2000prf.googlegroups.com> The code create 2 windows. 2 radiobuttons are put on the second window. A control variable "v" is binded to the 2 widgets. But when I run the code, I found the control variable not binded succsessfully: The second radiobutton was not selected by default; Click ed each button always print 1. I don't know what is wrong. So I need help.Thanks. from Tkinter import * def test(event_instance): print v.get() window1=Tk() window2=Tk() v=IntVar() v.set(1) radiobutton1=Radiobutton(window2,variable=v,value=0) radiobutton2=Radiobutton(window2,variable=v,value=1) radiobutton1.pack() radiobutton2.pack() radiobutton2.bind('<Button-1>',test) radiobutton1.bind('<Button-1>',test) window1.mainloop() From tchendrix at gmail.com Tue Sep 23 08:37:44 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 05:37:44 -0700 (PDT) Subject: finding domain name Message-ID: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> hi group. I'm new to python and need some help and hope you can answer this question. I have a situation in my code where i need to create a file on the server and write to it. That's not a problem if i hard code the path. However, the domain name needs to be dynamic so it is picked up automatically. The path to our websites is home/sites/xxxxx/ where xxxxx represents the domain name. How can I find the domain name of the current url being viewed. From dblubaugh at belcan.com Mon Sep 29 13:16:14 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 13:16:14 -0400 Subject: PYTHON WORKING WITH PERL ?? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> To All, I was wondering if it was possible to have a situation where a programming project would utilized BOTH python and perl? Such as utilizing python for internet programming and then utilize perl for text processing and systems programming? Is this even feasible??? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From joncle at googlemail.com Wed Sep 10 13:33:18 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 10:33:18 -0700 (PDT) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> Message-ID: <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> On 10 Sep, 18:14, Aaron Scott <aaron.hildebra... at gmail.com> wrote: > I've been trying to tackle this all morning, and so far I've been > completely unsuccessful. I have a binary file that I have the > structure to, and I'd like to read it into Python. It's not a > particularly complicated file. For instance: > > signature ? char[3] ? ? "GDE" > version ? ? uint32 ? ? ?2 > attr_count ?uint32 > { > ? ? attr_id ? ? ? ? uint32 > ? ? attr_val_len ? ?uint32 > ? ? attr_val ? ? ? ?char[attr_val_len] > > } ... repeated attr_count times ... > > However, I can't find a way to bring it into Python. This is my code > -- which I know is definitely wrong, but I had to start somewhere: > > import struct > file = open("test.gde", "rb") > output = file.read(3) > print output > version = struct.unpack("I", file.read(4))[0] > print version > attr_count = struct.unpack("I", file.read(4))[0] > while attr_count: > ? ? ? ? print "---" > ? ? ? ? file.seek(4, 1) > ? ? ? ? counter = int(struct.unpack("I", file.read(4))[0]) > ? ? ? ? print file.read(counter) > ? ? ? ? attr_count -= 1 > file.close() > > Of course, this doesn't work at all. It produces: > > GDE > 2 > --- > ? > --- > ??? > > I'm completely at a loss. If anyone could show me the correct way to > do this (or at least point me in the right direction), I'd be > extremely grateful. What if we view the data as having an 11 byte header: signature, version, attr_count = struct.unpack('3cII', yourfile.read(11)) Then for the list of attr's: for idx in xrange(attr_count): attr_id, attr_val_len = struct.unpack('II', yourfile.read(8)) attr_val = yourfile.read(attr_val_len) hth, or gives you a pointer anyway Jon. From Ross at no.thanks.spammers Thu Sep 18 12:55:01 2008 From: Ross at no.thanks.spammers (RGK) Date: Thu, 18 Sep 2008 12:55:01 -0400 Subject: Blanket font setting? Message-ID: <48d287e5$1@news.alcatel.com> I'm doing an app with the AUI manager capabilities (using some of the wxPython demo's for help). All is well, except I'm a bit disappointed with the font management. The default font for all the widgets (TextCtrl's, StaticText's etc) are a bit large for my design intent and as I try to adjust that, it appears I have to do a font = wx.SystemSettings_GetFont(wx.SYS_SYSTEM_FONT) font.SetPointSize(9) Then, for every texty thing: myTextThing.setfont(font) someOtherThing.setfont(font) Thus if I have hundreds of texty things, I've got to assign that hundreds of times. Is there any sort of blanket font setting, perhaps like: wx.SystemSettings_SetFont(font) #this doesn't exist that could set everything with one fell swoop? Thanks for your attention... Ross. From almar.klein at gmail.com Thu Sep 18 06:12:05 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 18 Sep 2008 12:12:05 +0200 Subject: SSH using PEXPECT In-Reply-To: <48cb87f0$0$6999$426a74cc@news.free.fr> References: <c8c694d6-30c6-4d47-aa2f-5b0a2a6ee59f@i76g2000hsf.googlegroups.com> <a2014811-8b92-4bac-84df-a3219f4e2ccd@o40g2000prn.googlegroups.com> <4cc538ef-3b08-404c-b107-ff6605c307a2@t54g2000hsg.googlegroups.com> <48cb87f0$0$6999$426a74cc@news.free.fr> Message-ID: <cc38d75f0809180312p4a4e2649tb04eb8c38c2b0ce6@mail.gmail.com> Hi, Wanting to use pexpect on windows too, I ran into wexpect. http://sage.math.washington.edu/home/goreckc/sage/wexpect/ I haven't given it a try yet. Does anyone have experience with that? Almar 2008/9/13 nntpman68 <news1234 at free.fr> > Hi, > > yellowblueyellow at gmail.com wrote: > >> On Sep 10, 7:01 pm, Sean DiZazzo <half.ital... at gmail.com> wrote: >> > > I am using windows and for reason it wont let me use pexpect even tho >> I have CYGWIN installed >> >> >> I get the following error >> >> Traceback (most recent call last): >> File "new.py", line 1, in <module> >> import ssh_session >> File "C:\Python25\lib\ssh_session.py", line 7, in <module> >> from pexpect import * >> File "C:\Python25\lib\site-packages\pexpect.py", line 85, in >> <module> >> support it. Pexpect is intended for UNIX-like operating >> systems.""") >> ImportError: No module named resource >> >> > You might have cygwin installed, > but the error mesage sems to indicatem that you don't use cygwin's pythonm > but the normal windows python, > > You see, that it complains about pexpcet in > C:\Python25\lib\site-packages\pexpect.py > > > > just open a cygwin window: > > then cd to the directory containign your script and type > python new.py. > > you should have at least another error message > > > bye > > > N > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/89f5b3f7/attachment-0001.html> From mail at anjanesh.net Wed Sep 10 09:50:21 2008 From: mail at anjanesh.net (Anjanesh Lekshminarayanan) Date: Wed, 10 Sep 2008 19:20:21 +0530 Subject: PHP's str_replace ? Message-ID: <48C7D09D.2080604@anjanesh.net> In PHP, if I do str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) it'll replace all vowels with a hyphen in string $str. Is there some equivalent in Python ? Thanks From notvalid2 at sbcglobal.net Tue Sep 9 00:27:08 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 08 Sep 2008 21:27:08 -0700 Subject: Syntax Problem with strptime in Python 2.4 In-Reply-To: <6ikegtFr3ab7U1@mid.uni-berlin.de> References: <ZA6xk.19461$LG4.103@nlpi065.nbdc.sbc.com> <6ikegtFr3ab7U1@mid.uni-berlin.de> Message-ID: <MWmxk.20771$cW3.3153@nlpi064.nbdc.sbc.com> Diez B. Roggisch wrote: > W. eWatson wrote: > >> Apparently, use of strptime of datetime needs a workaround in Python 2.4 >> to work properly. The workaround is d = >> datetime.datetime(*(time.strptime(date_string, format)[0:5])). However, >> when I try to use it, or even use it the regular way, it fails with >> AttributeError: type object 'datetime.datetime' has no attribute >> 'datetime'. >> From the following code code segment: >> >> format = '%Y%m%d_%H%M%S' >> #d=datetime.strptime('20080321_113405', format)-- typical use >> print time.strptime('20080321_113405', format)[0:5] >> d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5]) >> >> Does anyone know how to make this work in 2.4? If not, is there a way to >> achieve the same result? > > This is not what you think it is. All your problem is that you do > > from datetime import datetime > > which imports the datetime-class, but then try to access > > datetime.datetime > > as if you had done > > import datetime. > > > This actually is a wart in the datetime-module - it would be better if the > classes in there would follow PEP-8. > > Diez That's it. Thanks. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: <www.speckledwithstars.net/> From uomiocenekidd at gmail.com Mon Sep 22 06:39:18 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:39:18 -0700 (PDT) Subject: www amateurgalore net - Free Message-ID: <a17cd0eb-d9d5-48e1-996b-f4a023f62166@m44g2000hsc.googlegroups.com> www amateurgalore net . . . *******CLICK HERE******** http://vids365.cn/www-amateurgalore-net ***************************** . . . . . . . . . . . . www amateurgalore net From s.mientki at ru.nl Fri Sep 26 09:35:41 2008 From: s.mientki at ru.nl (Stef Mientki) Date: Fri, 26 Sep 2008 15:35:41 +0200 Subject: how to search multiple textfiles ? Message-ID: <48DCE52D.4010406@ru.nl> hello, I want to search multiple textfiles (python source files) for a specific word. I can find all files, open them and do a search, but I guess that will be rather slow. I couldn't find any relevant information through google. Does anyone know of a search library that performs this task fast ? If it indeed only concerns py-files, is there another way of searching words ? ( I could imagine that such a "py-only-search" would have benefits, because you could set a flag to see the words in comment yes or no ) thanks, Stef Mientki Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629. From coolkid246 at googlemail.com Thu Sep 4 06:09:40 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:09:40 -0700 (PDT) Subject: =?ISO-8859-1?Q?vergleich_kredit_in_Eberswalde_online_kredit_guensti?= =?ISO-8859-1?Q?g_kredit_ohne_schufa_sofortzusage_schufafreie_kredite_zinsen?= =?ISO-8859-1?Q?_online_mit_krediten_ohne_schufa_banken_ohne_schufa_eil_kred?= =?ISO-8859-1?Q?it_ohne_schufa_autokredit_online=2Dkredit_sofort_kredit_online?= =?ISO-8859-1?Q?_kreditantrag_online_besten_online_kredite_www_kredit_ohne_s?= =?ISO-8859-1?Q?chufa_online_kredite_ratenkredit_online__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTI?= =?ISO-8859-1?Q?GE_KREDITE_ONLINE_=2B=2B=2B_KREDITE_IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_?= =?ISO-8859-1?Q?=2B_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONL?= =?ISO-8859-1?Q?INE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW?= =?ISO-8859-1?Q?=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO?= =?ISO-8859-1?Q?=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONL?= =?ISO-8859-1?Q?INE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW?= =?ISO-8859-1?Q?=2EKREDITE=2DONLINE=2D244=2EINFO=2F_=2B_=2B_=2B_=2B_______________________bark?= =?ISO-8859-1?Q?redit_suche_kredit_ohne_schufa_in_Soltau_online_kredite_test?= =?ISO-8859-1?Q?_barkredit_ohne_schufa_in_W=FCrzburg_kleinkredit_kredite_kond?= =?ISO-8859-1?Q?itionen_in_Bad_postbank_kredit_umschuldung_in_Bayreuth_onlin?= =?ISO-8859-1?Q?e_kredit_de_eilkredite_in_Darmstadt_postbank_kredit_beamtend?= =?ISO-8859-1?Q?arlehen_in_Grimmen_kredit_arbeitslos_guenstiger_kredit_ohne_?= =?ISO-8859-1?Q?schufa_in_Eisenberg_kredit_ohne_gehaltsnachweis_expresskredi?= =?ISO-8859-1?Q?t_in_Parchim_www_kredit_ohne_schufa_de_kredit_ohne_schufa_on?= =?ISO-8859-1?Q?line_net_in_Gummersbach_online_sofort_kredit_ohne_schufa_kre?= =?ISO-8859-1?Q?dite_selbstaendige_in_Goslar_privatkredite_sofortkredit_ohne?= =?ISO-8859-1?Q?_auskunft_in_Freiberg_schufa_freie_kredite_bargeld_online_in?= =?ISO-8859-1?Q?_Belzig_kredite_finanzierung_immobilienkredit_in_Leipzig_kre?= =?ISO-8859-1?Q?dite_finanzierung_student_kredit_in_Segeberg_guenstige_kredi?= =?ISO-8859-1?Q?te_bonitaetspruefung_online_in_Wunsiedel=2FFichtelgeb=2E_www_kre?= =?ISO-8859-1?Q?dit_ohne_schufa_online_kreditangebot_in_Goeppingen_kreditkar?= =?ISO-8859-1?Q?te_ohne_schufa_kredite_online_vergleich_in_Bitterfeld_kleink?= =?ISO-8859-1?Q?redit_ohne_schufa_www_kredit_ohne_schufa_online_net_in_Forst?= =?ISO-8859-1?Q?_online_kredit_von_privat_kredite_finanzierung_in_Luckenwald?= =?ISO-8859-1?Q?e____=2D_kredit_trotz_schufa_und_ohne_euro_kredit_ohne_schufa_?= =?ISO-8859-1?Q?in_Annaberg=2DBuchholz_=2D_kredit_ohne_schufa_vergleich_online_k?= =?ISO-8859-1?Q?redite_oesterreich_in_Detmold_=2D_sofort_kredite_ohne_schufa_s?= =?ISO-8859-1?Q?erioese_online_kredite_in_Eckernfoerde_=2D_kredit_arbeitslos_p?= =?ISO-8859-1?Q?rivatkredit_in_Anklam_=2D_darlehen_schufafrei_kredite_ohne_sch?= =?ISO-8859-1?Q?ufa_auskunft_in_Diepholz_=2D_kredite_finanzierung_online_kredi?= =?ISO-8859-1?Q?te_im_vergleich_in_Hildburghausen_=2D_kreditvergleich_postbank?= =?ISO-8859-1?Q?_kredit_online_in_Cham_=2D_kredite_euro_kredit_ohne_schufa_in_?= =?ISO-8859-1?Q?Meschede_=2D_postbank_online_kredit_auto_ohne_schufa_in_Neustr?= =?ISO-8859-1?Q?elitz_=2D_www_kredit_ohne_schufa_online_net_autokredit_in_M=FCh?= =?ISO-8859-1?Q?ldorf_=2D_kredite_vergleich_kredit_ohne_schufa_test_in_Greiz_=2D?= =?ISO-8859-1?Q?_besten_online_kredite_kredite_finanzierungen_in_Mosbach_=2D_i?= =?ISO-8859-1?Q?mmobilien_kredite_internet_kredit_in_Grabfeld_=2D_kredite_onli?= =?ISO-8859-1?Q?ne_vergleich_privatkredit_ohne_schufa_in_Korbach?= Message-ID: <f5f3d41a-239b-4c5c-92a0-d0848d4eae10@b2g2000prf.googlegroups.com> vergleich kredit in Eberswalde online kredit guenstig kredit ohne schufa sofortzusage schufafreie kredite zinsen online mit krediten ohne schufa banken ohne schufa eil kredit ohne schufa autokredit online-kredit sofort kredit online kreditantrag online besten online kredite www kredit ohne schufa online kredite ratenkredit online + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + barkredit suche kredit ohne schufa in Soltau online kredite test barkredit ohne schufa in W?rzburg kleinkredit kredite konditionen in Bad postbank kredit umschuldung in Bayreuth online kredit de eilkredite in Darmstadt postbank kredit beamtendarlehen in Grimmen kredit arbeitslos guenstiger kredit ohne schufa in Eisenberg kredit ohne gehaltsnachweis expresskredit in Parchim www kredit ohne schufa de kredit ohne schufa online net in Gummersbach online sofort kredit ohne schufa kredite selbstaendige in Goslar privatkredite sofortkredit ohne auskunft in Freiberg schufa freie kredite bargeld online in Belzig kredite finanzierung immobilienkredit in Leipzig kredite finanzierung student kredit in Segeberg guenstige kredite bonitaetspruefung online in Wunsiedel/Fichtelgeb. www kredit ohne schufa online kreditangebot in Goeppingen kreditkarte ohne schufa kredite online vergleich in Bitterfeld kleinkredit ohne schufa www kredit ohne schufa online net in Forst online kredit von privat kredite finanzierung in Luckenwalde - kredit trotz schufa und ohne euro kredit ohne schufa in Annaberg- Buchholz - kredit ohne schufa vergleich online kredite oesterreich in Detmold - sofort kredite ohne schufa serioese online kredite in Eckernfoerde - kredit arbeitslos privatkredit in Anklam - darlehen schufafrei kredite ohne schufa auskunft in Diepholz - kredite finanzierung online kredite im vergleich in Hildburghausen - kreditvergleich postbank kredit online in Cham - kredite euro kredit ohne schufa in Meschede - postbank online kredit auto ohne schufa in Neustrelitz - www kredit ohne schufa online net autokredit in M?hldorf - kredite vergleich kredit ohne schufa test in Greiz - besten online kredite kredite finanzierungen in Mosbach - immobilien kredite internet kredit in Grabfeld - kredite online vergleich privatkredit ohne schufa in Korbach From grante at visi.com Wed Sep 10 13:39:24 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 12:39:24 -0500 Subject: md5 differences References: <mailman.799.1221063937.3487.python-list@python.org> <ga8sn6$g69$1@south.jnrs.ja.net> <mailman.806.1221066763.3487.python-list@python.org> <ga90kl$qhs$1@inews.gazeta.pl> Message-ID: <t8GdnSBxY7DRm1XVnZ2dnUVZ_jKdnZ2d@posted.visi> On 2008-09-10, Wojtek Walczak <gminick at bzt.bzt> wrote: > On Wed, 10 Sep 2008 19:12:28 +0200, Python wrote: >> Arno at Computer:~% echo "test" > test.txt >> >> Arno at Computer:~% md5 test.txt >> MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 > >> >>> import md5 >> >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >> '90364ed45b452d43378629c20543a81d' > > > Works for me: > >>>> import md5 >>>> f = open('test.txt').read() >>>> md5.new(f).hexdigest() > 'd8e8fca2dc0f896fd7cb4cb0031ba249' >>>> > > IOW, don't pass the path to the file to md5.new, but the contents > of this file. > > The strange thing is that >>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() > returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. Same here. -- Grant Edwards grante Yow! What PROGRAM are they at watching? visi.com From gminick at bzt.bzt Tue Sep 2 10:46:44 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Tue, 2 Sep 2008 14:46:44 +0000 (UTC) Subject: What is module initialization? References: <mailman.367.1220362362.3487.python-list@python.org> <48bd4799$0$17215$426a74cc@news.free.fr> <mailman.368.1220365945.3487.python-list@python.org> Message-ID: <g9jjkj$3us$1@inews.gazeta.pl> On Tue, 2 Sep 2008 15:32:07 +0100, dudeja.rajat at gmail.com wrote: > But if I do :- >#question.py > from myglobals import * > myglobals.answer = "WTF ?" > > will this work? Why won't you try? In this case you should receive NameError. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From steven at REMOVE.THIS.cybersource.com.au Wed Sep 17 01:29:51 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 17 Sep 2008 05:29:51 GMT Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> <f38eddfe-ca5a-4595-b898-e7ca70119f83@d1g2000hsg.googlegroups.com> <a744baaf-f0e3-4274-9d10-3c86ec8bb652@m44g2000hsc.googlegroups.com> <6jb6juF2co8rU1@mid.individual.net> Message-ID: <pan.2008.09.17.05.29.52@REMOVE.THIS.cybersource.com.au> On Wed, 17 Sep 2008 13:52:13 +1200, greg wrote: > Arnaud Delobelle wrote: > >> Or: >> >> import ModuleName as this_module > > Or: > > this_module = __import__(__name__) > > then you don't have to change anything. I like that solution! And it works regardless of whether the module holding it is imported, or is being executed from the commandline. Thanks to everyone who made a suggestion. -- Steven From steve at holdenweb.com Mon Sep 29 13:38:02 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 13:38:02 -0400 Subject: PYTHON WORKING WITH PERL ?? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> Message-ID: <gbr3pr$u63$2@ger.gmane.org> Blubaugh, David A. wrote: > To All, > > > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? Such as > utilizing python for internet programming and then utilize perl for text > processing and systems programming? Is this even feasible??? > > > Thanks, > So sorry to hear Google isn't available from your network ;-) http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From tjreedy at udel.edu Thu Sep 18 03:55:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 18 Sep 2008 03:55:07 -0400 Subject: member functions in a class In-Reply-To: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> References: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> Message-ID: <gat1gm$rhk$1@ger.gmane.org> Karl Kobata wrote: > I am new to python and am wondering. When I create a class, with ?def? > functions and if this class is instantiated say 50 times. Does this > mean that all the ?def? functions code within the class is duplicated > for each instance? > > Can someone give me a short and simple answer as to what happens in python? To expand slightly on Gary's answer. Dotted names -- ob.attr -- are typically (but not always) resolved as follows: does ob have attribute attr? If yes, get the corresponding object. If no, does type(ob) have attribute attr? If yes, get the corresponding object. In no, look in the baseclasses of type(ob) in some order (details not important here). So, instance methods are class attributes and instance.method will resolve to the method attribute of type(instance) -- assuming that the instance does not have an attribute of the same name. Lookup for special methods (with reserved __xxx__ names) may go directly to the class and never look at the instance attributes. From callen314 at gmail.com Wed Sep 24 18:07:04 2008 From: callen314 at gmail.com (Craig Allen) Date: Wed, 24 Sep 2008 15:07:04 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48d9e932$0$6127$426a34cc@news.free.fr> <mailman.1452.1222267902.3487.python-list@python.org> Message-ID: <e02a579e-a26d-4285-bb4f-a7953c8dd9c2@r15g2000prd.googlegroups.com> > Why, yes, I am wearing my BOFH hat. How could you tell? > > -- > Tim Rowe evil, but I think you may be a BSEFH, not a BOFH. From maric at aristote.info Mon Sep 15 08:16:00 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 14:16:00 +0200 Subject: Python and Open Office In-Reply-To: <a9f39a410809101304j592cb7actc1f95882f8fe632c@mail.gmail.com> References: <a9f39a410809101304j592cb7actc1f95882f8fe632c@mail.gmail.com> Message-ID: <200809151416.00391.maric@aristote.info> Le Wednesday 10 September 2008 22:04:57 Greg Lindstrom, vous avez ?crit?: > Hello, > > I would like to create and manipulate Open Office documents using Python. > I have found then UNO Python page and odfpy modules which seem to be > exactly what I need. The odfpy manual is, to me, a confusing list of > objects and methods (it's an impressive list!), but does not have much in > the way of how to use them. For example, I can open a spreadsheet and > create new pages (there's a nice example near the back of the manual) but I > can't figure out how to open an existing spreadsheet and list the names of > the individual sheets ("tabs"). > > I have written an application that access Microsoft Excel and creates > reports for work, but would like to create an Open Source version using > Open Office and release it to the community (and maybe get a talk at PyCon > :-). > > Is there someone here who can help me out, or is there an appropriate > mailing list for me to join? > > Thanks > > --greg I don't like the UNO solution, first, UNO API is not that practical, second you'll need to have a running instance of openoffice, which I wouldn't want to manage for a server application in term of performance, reliability and security. I had to produce text document within a zope application once, and did this by replacing variables values in a template directly in the xml, the function was no more than twenty lines long, and used only stdlib modules (see below). A far better approach IMHO. Of course for big manipultaion it could be more error prone and it's a good news that odfpy exists (I didn't use for my example because it was too simple), so I give it a try : >>>[1]: import odf.opendocument >>>[2]: import odf.table >>>[3]: new = odf.opendocument.OpenDocumentSpreadsheet() >>>[4]: for n in ('titi', 'tata', 'toto') : new.spreadsheet.addElement(odf.table.Table(name=n)) ...: >>>[5]: new.save("toto.ods") >>>[6]: maric at redflag1 17:10:27:~/odfpy-0.8$ ooffice toto.ods # document ok ! maric at redflag1 17:10:31:~/odfpy-0.8$ ipython >>>[12]: import odf.table >>>[13]: import odf.opendocument >>>[14]: for t in old.spreadsheet.getElementsByType(odf.table.Table) : print t.getAttribute('name') ....: ....: titi tata toto Great ! This was the function I use (from a local copy of the product I backed up, I have not the application working nor the svn server so I didn't test this version, but it's mainly the idea that is interesting) : def updateVariablesInSXW(self, variables, sxw) : from zipfile import ZipFile from StringIO import StringIO from xml.dom.minidom import parseString sxw = StringIO(sxw) zip = ZipFile(sxw, 'a') dom_document = parseString(zip.read('content.xml')) dom_styles = parseString(zip.read('styles.xml')) def update_variables(node) : if node.nodeName in ('text:variable-set','text:variable-get') : variable = node.attributes['text:name'].value if variable in variables : value = variables[variable].decode('utf-8') if node.attributes.has_key('text:value') : node.attributes['text:value'].value = value if node.attributes.has_key('text:string-value') : node.attributes['text:string-value'].value = value if node.firstChild is not None : node.firstChild.nodeValue = value for i in node.childNodes : update_variables(i) for i in (dom_document, dom_styles) : update_variables(i) zip.writestr('content.xml', dom_document.toxml().encode('utf-8')) zip.writestr('styles.xml', dom_styles.toxml().encode('utf-8')) sxw.seek(0) return zip.read() and a sample use (code frome a Zope product, facture is french term for invoice) : security.declarePrivate('prepareFacture') def prepareFacture(self) : import math price, devise = self.getProgramme().getPrice().split() end = self.getProgramme().end() start = self.getProgramme().start() subscriber = self.getSubscriberInfo() variables = { 'fullname' : subscriber.fullname, 'address' : subscriber.address, 'company' : subscriber.company, 'price' : price, 'quantity' : str(1), 'duration' : str(int(math.ceil(end - start))), 'ht' : price + ' ' + devise, 'ttc' : str(float(price)*1.196) + ' ' + devise, 'tva' : str(float(price)*0.196) + ' ' + devise, 'cours' : self.getProgramme().title_or_id(), 'location' : self.getProgramme().getLocation().title_or_id(), 'start' : self.toLocalizedTime(start), 'end' : self.toLocalizedTime(end), #'timetable' : self.getProgramme().getTimetable(), 'num_facture' : self.getNumFacture(), 'cp' : subscriber.postal, 'country' : subscriber.country, 'city' : subscriber.city, } if subscriber.country.strip().lower() == 'france' : template_name = 'ModeleFactureFormationTVA.sxw' else : template_name = 'ModeleFactureFormation.sxw' template = str(getattr(self, template_name)) facture = self.updateVariablesInSXW(variables, template) self.setFactureSXW(facture, filename="facture_%s.sxw" % self.getNumFacture()) -- _____________ Maric Michaud From fredrik at pythonware.com Fri Sep 12 13:33:48 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 19:33:48 +0200 Subject: Which version In-Reply-To: <92da89760809121028s1d9b8b46g464d54937c67ba0f@mail.gmail.com> References: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> <92da89760809121028s1d9b8b46g464d54937c67ba0f@mail.gmail.com> Message-ID: <gae95u$r40$2@ger.gmane.org> Eric Wertman wrote: > The subprocess module is one though footnote: subprocess works on older versions too, and can be trivially installed along with your application under Python 2.2 and 2.3. binary builds for Windows are available here: http://effbot.org/downloads/#subprocess </F> From steve at REMOVE-THIS-cybersource.com.au Sun Sep 28 04:26:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 08:26:33 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <mailman.1620.1222588562.3487.python-list@python.org> Message-ID: <00ef3974$0$20666$c3e8da3@news.astraweb.com> On Sun, 28 Sep 2008 03:55:46 -0400, Terry Reedy wrote: > est wrote: >>>From python manual >> >> str( [object]) >> >> Return a string containing a nicely printable representation of an >> object. For strings, this returns the string itself. The difference >> with repr(object) is that str(object) does not always attempt to return >> a string that is acceptable to eval(); its goal is to return a >> printable string. If no argument is given, returns the empty string, >> ''. >> >> >> now we try this under windows: >> >>>>> str(u'\ue863') >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in >> position 0 >> : ordinal not in range(128) > > In 3.0 this is fixed: >>>> str('\ue863') # u prefix is gone > '\ue863' >>>> str(b'123') # b prefix is added > "b'123'" > > Problems like this at least partly motivated the change to unicode > instead of bytes as the string type. I'm not sure that "fixed" is the right word. Isn't that more or less the same as telling the OP to use unicode() instead of str()? It merely avoids the problem of converting Unicode to ASCII by leaving your string as Unicode, rather than fixing it. Perhaps that's the right thing to do, but it's a bit like the old joke: "Doctor, it hurts when I do this." "Then don't do it!" As for the second example you give: >>> str(b'123') # b prefix is added "b'123'" Perhaps I'm misinterpreting it, but from here it looks to me that str() is doing what repr() used to do, and I'm really not sure that's a good thing. I would have expected that str(b'123') in Python 3 should do the same thing as unicode('123') does now: >>> unicode('123') u'123' (except without the u prefix). -- Steven From dblubaugh at belcan.com Thu Sep 11 18:01:48 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 11 Sep 2008 18:01:48 -0400 Subject: Has any one out there ever worked with the Rpyc, which is a remote process call for python Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380500CF94@AWMAIL04.belcan.com> To All, Has any one out there ever worked with the Rpyc, which is a remote process call for python? David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From code at pizzashack.org Wed Sep 3 02:41:32 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 3 Sep 2008 02:41:32 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <a49e45f50809022120l648f6d94i86ac446b7ae8df69@mail.gmail.com> References: <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> <mailman.390.1220393719.3487.python-list@python.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> <a49e45f50809022120l648f6d94i86ac446b7ae8df69@mail.gmail.com> Message-ID: <20080903064132.GV29228@dragontoe.org> On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote: > Derek Martin wrote: > > On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: > >> but the instances of `Popen` are no actions. There's no way to > >> "execute" a `Popen` instance. > > > > Yes there is... you execute it when you instantiate the object. At > > the time of instantiation, you "open" the "P" (pipes). > > The subprocess module is also supposed to replace os.system and > os.spawn*, neither of which involve opening pipes. Sigh... wasn't finished, sent by accident. Anyway, to continue... The subprocess module also can be used to replace these two functions, though to be honest, it's not clear to me why one would do so. On the whole, I choose not to use the subprocess module because I find it tedious, and less tedious interfaces (like os.system() and os.popen(), and even the popen2 module) exist. [But, you can probably guess that I write code almost exclusively for POSIX-ish systems...] If all you want is the equivalent of os.system() or os.spawn(), then it seems to me the subprocess module is overly heavy-handed, leaving a bunch of not useful state laying around in your environment... Not to mention you probably already need the os module, so you could save yourself the trouble and overhead of importing subprocess. > All rationalizations aside, I think Popen is a poor name for the > class. Even within this thread, a number of people clearly disagree with you. To say nothing of the maintainers... :) I really think it's not worse (and actually better) than "process"... for reasons I already explained. The argument that the object is a process is spurious. The object is, in actuality, an instance of *COMMUNICATION* between two processes. It's true that a process is started as a result, so that the first process has a second to be able to communicate with; and a (tiny) bit of information (the PID) is maintained about that process, mostly for no useful reason... However the object mainly is a collection of pipes, and some methods for communicating over them, to another process that, out of necessity just happens to be a child of the current one. If you think about what the methods do, and understand how they actually work, I think it will become clear that this is the case. Does communicate() operate on the process? ABSOLUTELY NOT -- it operates on the pipes. poll() and wait() may arguably act upon the process (they actually request information about the process from the kernel), but the goal in doing so is to find out the status of the communication: is it done, and if so was it successful? If you abstract the concept from its implementation, this is clearly true. I could concede that it may not be clear to someone unfamiliar with C programming (perhaps especially in a Unix environment, though Windows does have a similar, but apparently broken function) what "popen" means or does, but the manual has ample references to explain that, I think. It's no less clear than the popen() function itself! > But I would imagine the odds of it ever being changed are miniscule > (Python 4?). The truth is, in the end, I personally don't really care; though if it were changed, I would hope something genuinely better were chosen. I feel strongly that "process" ain't it. My motivation in posting in this thread is mostly to point out how silly it is to argue or complain about the name of some bit of logic in a programming language, especially once it's already been released (though I doubt most of the participants got the point). The time to do this is when the feature is in the planning stages, if ever... Some people take this stuff way, way too seriously, and also can't seem to imagine that another perspective besides their own exists, and especially that their own might just not be optimal/correct. Posting to Usenet/maling lists and saying "Why is X called X? It should be called Y!" is not likely to ever produce any sort of useful result. ;-) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080903/f8967309/attachment-0001.sig> From fredrik at pythonware.com Fri Sep 5 13:36:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 19:36:56 +0200 Subject: Case-insensitive string compare? In-Reply-To: <200809051331.40609.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050059.17038.maric@aristote.info> <g9qjav$3os$1@ger.gmane.org> <200809051331.40609.maric@aristote.info> Message-ID: <g9rqnp$t8p$1@ger.gmane.org> Maric Michaud wrote: > I suspect you are coming to conclusions a bit quickly, without taking the pain > of understanding the whole discussion. I'm pretty sure I was the first one to post an answer in this thread, and I understand Python design and performance issues very well, thank you. (but given your talk about "the cost of whitespace" in a response to a comment about performance in that other subthread, it's obvious that you're just here to provide noise. plonk plonk.) </F> From dudeja.rajat at gmail.com Tue Sep 30 16:21:02 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 30 Sep 2008 21:21:02 +0100 Subject: Backup a directory Message-ID: <e0b6c39a0809301321uaa442d8o56389b0a12161f9e@mail.gmail.com> Hello, I'm looking for a script that creates a backup of a directory but keeps only one backup. I've tried using all the os modules commands but could not create one. Does any one has any such custom script or function? Thanks and regards, rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/c0e6d71d/attachment-0001.html> From deets at nospam.web.de Thu Sep 25 06:28:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 12:28:35 +0200 Subject: Connecting to SMB share in python References: <gbfghp02k6e@drn.newsguy.com> <mailman.1484.1222331750.3487.python-list@python.org> <2008092518182581491-rokwok@newsguycom> Message-ID: <6k17ejF5dlviU1@mid.uni-berlin.de> Ronnie Kwok wrote: > Thank you for the reply! > > Yes, I am running the script under linux and it will be doing some > processing before copying it over to the samba mount. > > It's totally fine to mount it with os.sys(...) approach but I am just > thinking if there's other option. None that is any more comfortable. If anything, you'd need smbclient or some such to list and fetch data - which is *much* more complicated that simply mounting a share defined in fstab. Diez From news1234 at free.fr Mon Sep 8 17:30:42 2008 From: news1234 at free.fr (nntpman68) Date: Mon, 08 Sep 2008 23:30:42 +0200 Subject: exit() In-Reply-To: <mailman.702.1220901003.3487.python-list@python.org> References: <mailman.702.1220901003.3487.python-list@python.org> Message-ID: <48c59980$0$7014$426a74cc@news.free.fr> Hi Jean-Paul, Jean-Paul Calderone wrote: > On Mon, 08 Sep 2008 21:03:48 +0200, Christian Heimes <lists at cheimes.de> > wrote: >> Gary Robinson wrote: >>> In Python 2.5.2, I notice that, in the interpreter or in a script, I >>> can exit with: >>> >>> exit() >> >> The exit callable is defined in the site module. Check out site.py! It >> shouldn't be used in code. It was added to help newbies to 'escape' >> from an interactive Python shell. >> > > It works. Why shouldn't it be used? > > Jean-Paul Backwards compatibility vs. saving 4 characters. I'd stick with backwards compatibility bye N From wuwei23 at gmail.com Mon Sep 15 21:44:29 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 15 Sep 2008 18:44:29 -0700 (PDT) Subject: Rebinding __setattr__ References: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> <mailman.1033.1221477203.3487.python-list@python.org> <48cecfb3$0$3164$e4fe514c@dreader31.news.xs4all.nl> Message-ID: <23fe179e-e4c0-42c6-b61f-e248636a9701@i24g2000prf.googlegroups.com> On Sep 16, 7:12?am, "Jan Schilleman" <jan.schille... at xs4all.nl> wrote: > That still would require changing the source of the library ... And i'm not > sure if it would have side effects. I'm not on a Windows box so can't test this atm, but perhaps you could make a proxy object? class DispatchBaseProxy(object): def __init__(self): self.base = DispatchBaseClass() def __setattr__(self, attr, value): "insert extra functionality here" setattr(self.base, attr, value) def __getattr__(self, attr): getattr(self.base, attr) ...etc... From fredrik at pythonware.com Fri Sep 12 13:31:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 19:31:07 +0200 Subject: Which version In-Reply-To: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> References: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> Message-ID: <gae90t$r40$1@ger.gmane.org> Don wrote: > I'm a reasonably experienced in other languages and have just decided to > get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed, > is this good enough to start out with or am I likely to encounter bugs that > have been fixed in later versions. Python 2.4 is definitely good enough to start with. The bugs you'll find in released versions are usually pretty obscure; I've been using Python since release 1.1 or so, and I cannot remember ever having to upgrade due to a critical bug in the version I was using. </F> From henrypopie at gmail.com Tue Sep 23 11:59:30 2008 From: henrypopie at gmail.com (henrypopie at gmail.com) Date: Tue, 23 Sep 2008 08:59:30 -0700 (PDT) Subject: download redtube video - Free References: <ce91d9a2-a6f2-4e8e-8d23-716fb6cb053a@26g2000hsk.googlegroups.com> <f766bbe3-db31-4bcd-9597-6d54b75b501b@k36g2000pri.googlegroups.com> Message-ID: <0805ca16-03ed-425c-9979-928e211dc931@r15g2000prd.googlegroups.com> Or download RedTube videos online: http://www.download-redtube.com/ From dudeja.rajat at gmail.com Wed Sep 3 14:40:40 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Wed, 3 Sep 2008 19:40:40 +0100 Subject: Looking for File comparison utility that produces actual differences Message-ID: <e0b6c39a0809031140k6390ee1ev51718096136409e1@mail.gmail.com> Hi, I looking for a file comparison utility in Python that works like 'diff' command in Unix and 'comp' in Windows. The present 'cmd' in filecmp module only presents output in the form of 1 or 0 i.e whether the 2 files differ or not? So, I'm lookin for something that generates actual differences and moreover it is cross platform as well. As I need that same thing in both my windows and linux box. Even if it is a utlility please suggest. Thanks and regards, Rajat From alainpoint at yahoo.fr Wed Sep 24 02:40:59 2008 From: alainpoint at yahoo.fr (alain) Date: Tue, 23 Sep 2008 23:40:59 -0700 (PDT) Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> <mailman.1355.1222075976.3487.python-list@python.org> Message-ID: <a3d9c038-fbda-47f0-9a8e-4570d0faaac1@l42g2000hsc.googlegroups.com> On Sep 22, 11:32?am, "Tim Leslie" <tim.les... at gmail.com> wrote: > There is no need for a wrapper. Both numarray and Numeric have been > deprecated in favour of numpy, so numpy is the only one you need to > use. Numpy should have all the tools you need. If you find something > missing, there's a good chance it's included in scipy (which ?is built > on top of numpy). For full details seewww.scipy.org. I don't agree. I am myself a casual user of numpy without sophisticated needs. Numpy seems to be the only player in town and unfortunateely, though powerful, its syntax is not intuitive or easy to remember. I therefore welcome any attempt to simplify the api for a specific group of non-power users. Alain From ezra.taylor at gmail.com Tue Sep 30 15:09:06 2008 From: ezra.taylor at gmail.com (Ezra Taylor) Date: Tue, 30 Sep 2008 15:09:06 -0400 Subject: [Tutor] Replacing cmd.exe with custom .py application In-Reply-To: <eb90f15e0809301113p61bafe22y179d546b3719f51d@mail.gmail.com> References: <ea09b3700809300732vafc8d52oca6a73d95b63eb33@mail.gmail.com> <eb90f15e0809301113p61bafe22y179d546b3719f51d@mail.gmail.com> Message-ID: <eb90f15e0809301209x11a260d5pdcd6e59c08605502@mail.gmail.com> Is there something similar to /dev/null on Windows? On Tue, Sep 30, 2008 at 2:13 PM, Ezra Taylor <ezra.taylor at gmail.com> wrote: > Joseph: > Check out subprocess. The subprocess module is on python > 2.4. Also, use subprocess.call("your command",shell=True) > > On Linux/Unix, the process is below > > import subprocess > > ret = subprocess.call("dir",shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT) > > print ret > > You should get a return value of 0. Which means that it was > successful. I'm still learning this myself, so some of these other > guys might have more input. > > > > > > On Tue, Sep 30, 2008 at 10:32 AM, A. Joseph <joefazee at gmail.com> wrote: >> >> >> Instead of going to the command line all the time, I want to create a small >> customized cmd.exe of my own, how can I get the return value from >> os.system() because I was thinking I can do soothing with os.system(), In >> case my question is not clear, just like an IDE that plugged in another >> .exe application. >> >> >> >> Sorry for any mistake in my question. Just help me if you can >> >> _______________________________________________ >> Tutor maillist - Tutor at python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > > > -- > Ezra Taylor > -- Ezra Taylor From fredrik at pythonware.com Mon Sep 15 16:43:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 22:43:00 +0200 Subject: append on lists In-Reply-To: <gamgn9$5r5$1@online.de> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> Message-ID: <gamhco$1vm$1@ger.gmane.org> Armin wrote: > If d should reference the list a extended with a single list element > you need at least two lines > > a.append(7) > d=a why do you need two names for the same thing? > and not more intuitive d = a.append(7) unless you completely change the semantics of "append", your code would modify "a" as well. how is that "more intuitive"? side effects are bad as they are, but side effects in unexpected places is a really lousy idea. I don't think you've thought this one through, really. </F> From san82moon at gmail.com Mon Sep 1 03:57:19 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 00:57:19 -0700 (PDT) Subject: how to find position of dictionary values Message-ID: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> hi, i have a dictionary as follows : kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} if user is enters the 3rd item of key phno, ie "dfsdf" in my dict, how can i find it is the third item in the internal list of phno of that dictionary? thanks you. From yellowblueyellow at gmail.com Wed Sep 10 21:04:42 2008 From: yellowblueyellow at gmail.com (yellowblueyellow at gmail.com) Date: Wed, 10 Sep 2008 18:04:42 -0700 (PDT) Subject: SSH using PEXPECT Message-ID: <c8c694d6-30c6-4d47-aa2f-5b0a2a6ee59f@i76g2000hsf.googlegroups.com> Hey , I need to SSH into a server .. (10.8.42.38) using pexpect the username is 'admin' and password is 'abc123' so far i have the following code import pexpect import sys import time import os foo = pexpect.spawn('ssh admin at 10.8.42.38') ssh_newKey = 'Are you sure you want to continue connecting' foo.expect = ssh_newKey foo.send = 'yes' foo.expect = 'password:' foo.send = 'abc123' ------------------------------------------------------------------------------------------------- does this look right? if not , could someone suggest a way to do this .. your help is much appreciated From george.sakkis at gmail.com Mon Sep 29 01:44:16 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 28 Sep 2008 22:44:16 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <mailman.1662.1222661304.3487.python-list@python.org> Message-ID: <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> On Sep 29, 12:08 am, Terry Reedy <tjre... at udel.edu> wrote: > George Sakkis wrote: > > On Sep 28, 2:29 pm, process <circularf... at gmail.com> wrote: > > >> I have heard some criticism about Python, that it is not fully object- > >> oriented. > > > That's not a bug, it's a feature ;-) > > >> Why isn't len implemented as a str.len and list.len method instead of > >> a len(list) function? > > > As Terry Reedy wrote, partly history and partly practicality. There's > > no philosophical reason why we write "len(x)" (generic builtin), > > "x.append(1)" (method) or "del x[i]" (statement). The latter in > > particular is IMHO a design wart; there's no reason for not writing it > > as "x.delete(i)". > > As a general rule and matter of practice, methods that apply to all or > most classes (or all number classes) have built-in functions that call > the corresponding special method (or C-level slot). It would be easier to justify this rule if it was more clear-cut, and specifically if it was applied only to methods that are available to *all* classes (such as type() and getattr()) rather than the ill- defined "most classes". George From mrkylehayes at gmail.com Tue Sep 30 13:17:42 2008 From: mrkylehayes at gmail.com (Kyle Hayes) Date: Tue, 30 Sep 2008 10:17:42 -0700 (PDT) Subject: r"<path>" Message-ID: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> Is there a way to use the 'r' in front of a variable instead of directly in front of a string? Or do I need to use a function to get all of the slashes automatically fixed? /thanks -Kyle From bellman at lysator.liu.se Thu Sep 4 03:05:19 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 4 Sep 2008 07:05:19 +0000 (UTC) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> Message-ID: <g9o1bf$dsf$1@news.lysator.liu.se> Mensanator <mensanator at aol.com> wrote: > No, but blank cells are 0 as far as Excel is concerned. > That behaviour causes nothing but trouble and I am > saddened to see Python emulate such nonsense. Then you should feel glad that the Python sum() function *does* signal an error for the closest equivalent of "blank cells" in a list: >>> sum([1, 2, 3, None, 5, 6]) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' Summing the elements of an empty list is *not* the same thing as summing elements of a list where one element is None. > There are no "empty" boxes. There are only boxes with > known quantities and those with unknown quantities. > I hope that's not too ivory tower. The sum() function in Python requires exactly one box. That box can be empty, can contain "known quantities" (numbers, presumably), or "unknown quantities" (non-numbers, e.g., None). But you can't give it zero boxes, or three boxes. I don't have a strong view of whether sum([]) should return 0 or raise an error, but please do not mix that question up with what a sum over empty cells or over NULL values should yield. They are very different questions. As it happens, the SQL sum() function (at least in MySQL; I don't have any other database easily available, nor any SQL standard to read) does return NULL for a sum over the empty sequence, so you could argue that that would be the correct behaviour for the Python sum() function as well, but you can't argue that because a sum *involving* a NULL value returns NULL. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "This isn't right. This isn't even wrong." ! bellman @ lysator.liu.se -- Wolfgang Pauli ! Make Love -- Nicht Wahr! From deets at nospam.web.de Mon Sep 22 06:44:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 Sep 2008 12:44:54 +0200 Subject: BadStatusLine: References: <4e3d5d97-1b5f-4593-9c33-ad8b57d59b05@f36g2000hsa.googlegroups.com> Message-ID: <6jpb99F4ericU1@mid.uni-berlin.de> noelob wrote: > Hi All, > > During performance testing of my web application, I occasionally get a > BadStatusLine exception from httplib. Reading > http://docs.python.org/lib/module-httplib.html#l2h-4021 tells me that > it's "Raised if a server responds with a HTTP status code that we > don't understand." Is there a way to find what the actual status code > returned was? I.e. the value that caused the exception to be thrown? > Under what circumstances is a BadStatusLine normally thrown? (e.g. > data corruption?) > > I'm quite new to python, but not to programming. Apologies if this is > a silly question ;) Bruno gave some advice already. I can only add that for the general task of inspecting HTTP-traffic, tools such as axis-tcpmon or wireshark are useful. There you can see what happens on the protocol level. Diez From clp at rebertia.com Sun Sep 21 13:13:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 21 Sep 2008 10:13:08 -0700 Subject: I tried erlang-ish [1|2] in python and something came out... In-Reply-To: <cd796753-6ce1-4328-9683-346d1192ddf7@73g2000hsx.googlegroups.com> References: <cd796753-6ce1-4328-9683-346d1192ddf7@73g2000hsx.googlegroups.com> Message-ID: <47c890dc0809211013g2e4e72aex570beebafd884c64@mail.gmail.com> On Sun, Sep 21, 2008 at 10:02 AM, process <circularfunc at gmail.com> wrote: > In erlang you can cons like this: [1|2]. i tried this in python and it > didnt raise an error but i dont know what the result do In Python, like in C, the "|" operator on integers performs a bitwise-OR. To "cons" nondestructively onto a list, do e.g. [head_value] + tail, but note that this isn't very idiomatic. CPython's lists are implemented internally as arrays, not linked lists, hence why there's no "cons" operator in Python. You may also be interested in list.append() Regards, Chris > >>>> [1|2] > [3] >>>> [2|2] > [2] >>>> a = [2|2] >>>> a > [2] >>>> [2|3] > [3] >>>> [2|1] > [3] >>>> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From fredrik at pythonware.com Thu Sep 25 16:15:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 Sep 2008 22:15:50 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: <QQRCk.1802$Pv5.235@edtnps83> References: <mailman.1506.1222370612.3487.python-list@python.org> <QQRCk.1802$Pv5.235@edtnps83> Message-ID: <gbgrhq$hbt$1@ger.gmane.org> Dmitry S. Makovey wrote: > you have just described OS package building ;) > > I can't speak for everybody, but supporting multiple platforms (PHP, Perl, > Python, Java) we found that the only way to stay consistent is to use OS > native packaging tools (in your case apt and .deb ) and if you're missing > something - roll your own package. After a while you accumulate plenty of > templates to chose from when you need yet-another-library not available > upstream in your preferred package format. Remember that some python tools > might depend on non-python packages, so the only way to make sure all that > is consistent across environment - use unified package management. you're speaking for lots of organizations, at least. rpm/debs from supplier's repository subversion (or equivalent) -> locally built rpm/debs + organization's favourite deployment tools --------------------------------- deployed application </F> From larudwer at freenet.de Thu Sep 4 16:26:53 2008 From: larudwer at freenet.de (Ruediger) Date: Thu, 04 Sep 2008 22:26:53 +0200 Subject: why is self not passed to id()? Message-ID: <g9pg72$3vi$1@aioe.org> Hello! Executing following little program gives me an TypeError. What makes me wonder is that foo does get an argument passed while bar doesn't. Can anyone explain why?????? Thanks Ruediger class foo(list): __hash__ = lambda x: id(x) class bar(list): __hash__ = id _s_ = set() _s_.add(foo()) _s_.add(bar()) rue at linux:~> python test01.py Traceback (most recent call last): File "test01.py", line 9, in <module> _s_.add(bar()) TypeError: id() takes exactly one argument (0 given) From castironpi at gmail.com Sun Sep 28 16:54:15 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 13:54:15 -0700 (PDT) Subject: generate random digits with length of 5 References: <e1923ff8-8150-41b6-9444-19c14b4d2f6f@8g2000hse.googlegroups.com> <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> <mailman.1641.1222632690.3487.python-list@python.org> <a380bc46-cf5f-4ae9-b1f2-d8789ba4f838@d45g2000hsc.googlegroups.com> Message-ID: <07d14730-a585-4976-adda-540d32a2066d@y38g2000hsy.googlegroups.com> On Sep 28, 3:44?pm, Mensanator <mensana... at aol.com> wrote: > On Sep 28, 3:11 pm, "Gary M. Josack" <g... at byoteki.com> wrote: > > > > > Chris Rebert wrote: > > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <soti... at gmail.com> wrote: > > > >> Wondering if there is a better way to generate string of numbers with > > >> a length of 5 which also can have a 0 in the front of the number. > > > >> <pre> > > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 > > >> elements > > >> code = 'this is a string' + str(random_number[0]) + > > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3]) > > >> + str(random_number[4]) > > > > code = ''.join(str(digit) for digit in random_number) > > > > Regards, > > > Chris > > > >> </pre> > > > >> -- > > >>http://mail.python.org/mailman/listinfo/python-list > > > will random.randint(10000,99999) work for you? > > It doesn't meet the OP's requirement that the number > can start with 0. Also, the method the OP asks about > returns a list of unique numbers, so no number can > be duplicated. He can get 02468 but not 13345. > > Now, IF it's ok to have an arbitrary number of leading > 0s, he can do this: > > >>> str(random.randint(0,99999)).zfill(5) > '00089' > >>> str(random.randint(0,99999)).zfill(5) > '63782' > >>> str(random.randint(0,99999)).zfill(5) > '63613' > >>> str(random.randint(0,99999)).zfill(5) > > '22315' Is a while loop until there are 5 distinct digits best otherwise? while 1: a= '%05i'% random.randint( 0, 99999 ) if len( set( a ) )== 5: break From fredrik at pythonware.com Sat Sep 13 09:54:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 15:54:05 +0200 Subject: How to run PyOS_InputHook from python code (i.e. yield to event loops) In-Reply-To: <87iqt0b1tj.fsf@ville-desktop.i-did-not-set--mail-host-address--so-tickle-me> References: <87wshpcaek.fsf@gmail.com> <bec528d3-8fc6-4daa-ad20-e5074ae3b96a@a3g2000prm.googlegroups.com> <87iqt0b1tj.fsf@ville-desktop.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <gaggm0$8nt$1@ger.gmane.org> ville wrote: > That's tk-specific, right? I'm looking for a snippet that > > - Would not be tied to tk upstream, you said: "My actual use case is to keep a tkinter application responsive" </F> From dullrich at sprynet.com Fri Sep 5 11:22:22 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 05 Sep 2008 10:22:22 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: <dullrich-B5A8C7.10222205092008@text.giganews.com> In article <18c765e0-1dcb-4e40-93a9-32bb9d129b7e at n38g2000prl.googlegroups.com>, bearophileHUGS at lycos.com wrote: > David C. Ullrich: > > At least in mathematics, the sum of the elements of > > the empty set _is_ 0, while the maximum element of the > > empty set is undefined. > > What do you think about my idea of adding that 'default' argument to > the max()/min() functions? How the Python max and min functions should work has to do with how people want them to work and how people expect them to work. I wouldn't know about most people, but I would have been surprised if min([]) was not an error, and I would have been disappointed if sum([]) was not 0. >From a mathematical point of view, not that that's directly relevant, it doesn't make much sense to me to add that default argument. The max of a set is supposed to be the largest element of that set. If the set is empty there's no such thing. In Python you'd better make sure that S is nonempty before asking for max(S). That's not just Python - in math you need to make certain that S is nonempty and also other conditions before you're allowed to talk about max(S). That's just the way it is. Think about all the previously elected female or black presidents of the US. Which one was the tallest? > Bye, > bearophile -- David C. Ullrich From dullrich at sprynet.com Thu Sep 4 11:52:46 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 04 Sep 2008 10:52:46 -0500 Subject: Function decorators References: <mailman.493.1220542975.3487.python-list@python.org> Message-ID: <dullrich-5C4567.10524004092008@text.giganews.com> In article <mailman.493.1220542975.3487.python-list at python.org>, Aigars Aigars <srad at inbox.lv> wrote: > Good day all, I am learning Python and came up to decorators. The question > is: Why does function FoodList return value None? Because the function doesn't return anything, and in Python a function that doesn't explicitly return anything returns None. > The code in attachment. Thanks for not just pasting it into the post, like so: class Logger: def __init__(self, function): self.func = function def __call__(self, *args, **kwargs): print "Function %s called with args = %s, kwargs = %s" % (self.func.__name__, str(args), str(kwargs)) self.func(*args, **kwargs) @Logger def FoodList(a, b, c="spam"): text = "Food is %s, %s, %s" % (a, b, c) print text return text if __name__ == "__main__": a = FoodList("eggs", "potatoes") print a > Thank you, > Aigars--------------------------------------------------------------------- > [Image] -- David C. Ullrich From febkimbleox at gmail.com Sat Sep 27 07:16:59 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:16:59 -0700 (PDT) Subject: amater porno amater porno film free amater porno free amater porno - Free Message-ID: <cf961356-b2f2-4e5a-9ec4-045aa9ac058b@e39g2000hsf.googlegroups.com> amater . . . *******CLICK HERE******** http://vids365.cn/amater ***************************** . . . . . . . . . . . . amater sat on one end while Tammy sat at the other. What did porno do, porno isn?t right, but yet, porno feels drawn to her. What did amater do, amater isn?t right, but yet, amater feels drawn to her. What did porno do, porno isn?t right, but yet, porno feels drawn to her. What did film do, film isn?t right, but yet, film feels drawn to her. What did free do, free isn?t right, but yet, free feels drawn to her. What did amater do, amater isn?t right, but yet, amater feels drawn to her. What did porno do, porno isn?t right, but yet, porno feels drawn to her. What did free do, free isn?t right, but yet, free feels drawn to her. What did amater do, amater isn?t right, but yet, amater feels drawn to her. What did porno do, porno isn?t right, but yet, porno feels drawn to her. What did &sex do, &sex isn?t right, but yet, &sex feels drawn to her. What did movies do, movies isn?t right, but yet, movies feels drawn to her. From amater back bedroom of amater house, amater had a pretty good view of amater yard. From porno back bedroom of porno house, porno had a pretty good view of porno yard. From videos back bedroom of videos house, videos had a pretty good view of videos yard. From san82moon at gmail.com Mon Sep 1 04:49:37 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:49:37 -0700 (PDT) Subject: how to find position of dictionary values References: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <e9b3e12c-3834-48ff-911b-baf01efdb8c3@r15g2000prh.googlegroups.com> On Sep 1, 1:45 pm, Bruno Desthuilliers <bruno. 42.desthuilli... at websiteburo.invalid> wrote: > lee a ?crit : > > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, > > ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? > > It's quite simple (hint : read the FineManual(tm) for dict.items() and > list.index()), but 1/totally inefficient and 2/not garanteed to yield a > single value (what if 'dfsdf' happens to be also the 4th item of the > list bound to key 'address' ?). > > May I suggest you rethink your data structure instead ? What you have > here is obviously a collection of 'phno/email/name/address'records. > These records shouldn't be split across different objects. Assuming > 'phno' is a unique identifier for each record, a better data structure > would be: > > records = { > 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > # etc > > } > > This way, the lookup is as simple and efficient as possible. > > My 2 cents.... hi, i agree with u, my data strusture is not efficient. but all the records,viz...name,phno, email,address are all generated at runtime , when the user enters them. so how can i design my datastructure in that case? From darcy at druid.net Wed Sep 10 12:40:06 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 10 Sep 2008 12:40:06 -0400 Subject: md5 differences In-Reply-To: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> References: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> Message-ID: <20080910124006.97ce9195.darcy@druid.net> On Wed, 10 Sep 2008 18:25:19 +0200 Python <python at rgbaz.eu> wrote: > Arno at Computer:~% echo "hello" | md5 > b1946ac92492d2347c6235b4d2611184 > [...] > >>> md5.new("hello").hexdigest() > '5d41402abc4b2a76b9719d911017c592' > > How do I get the same results? Send the same thing. >>> md5.new("hello\n").hexdigest() 'b1946ac92492d2347c6235b4d2611184' -- D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From george at george-net.de Tue Sep 16 06:54:47 2008 From: george at george-net.de (Georg Altmann) Date: Tue, 16 Sep 2008 12:54:47 +0200 Subject: MVC with Python In-Reply-To: <gamknt$spg$1@news.get.no> References: <mailman.1059.1221507925.3487.python-list@python.org> <gamknt$spg$1@news.get.no> Message-ID: <gao3c4$a3b$1@ger.gmane.org> David Boddie schrieb: > On Monday 15 September 2008 21:37, Georg Altmann wrote: > >> I need some advice on how to implement model-view-controller. I am >> trying to develop a GUI application with PyQt, yet the problem rather >> applies to mvc in general, not just GUI applications. >> >> Let's say the data is a list of objects with a common base class. The >> views are either a graphical representation of the objects or some form >> of textual input. The views shall change the model by using command >> objects (for undo, e.g. QUndoCommand). > > [...] > >> My problem is, how do the commands interact with the model? > > One approach that combines the undo framework with the model/view framework > is described here: > > http://doc.trolltech.com/qq/qq25-undo.html > > The implementation is in C++, but it may be possible to pick up some > useful tips from the article. Thanks for the pointer. I studied the article before, but it doesn't seem to work for my problem: If I understand the Qt model/view architecture correctly, data is always based on items which are wrapped into QVariant. (see http://doc.trolltech.com/4.4/qabstractitemmodel.html#data) So to use the Qt model/view architecture items have to be represented as a value. I think this leaves me with the problem of copying objects I described before. Regards Georg From rajeeshrnair at gmail.com Mon Sep 29 00:28:43 2008 From: rajeeshrnair at gmail.com (raj) Date: Sun, 28 Sep 2008 21:28:43 -0700 (PDT) Subject: Reportlab - Splitting table by column Message-ID: <7823f7a1-cc96-4d3a-bdb2-315da9212397@z11g2000prl.googlegroups.com> My Zope based application for a client has to generate annual audit reports with too wide tables of account-wise payment details. I turned to reportlab when HTML formatting became a headache for me. Reportlab doc claims it can split by row as well as column but doesn't explain how to. Then I came to learn that reportlab does not implement byCol splitting. But is there a way out for me to split my wide data table into pages? What if I try to implement splitByCol in the line of splitByRow? (Only if it won't take much time and effort!) Why don't they do that themselves? Any serious obstacles? From dudeja.rajat at gmail.com Sun Sep 28 11:51:40 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sun, 28 Sep 2008 16:51:40 +0100 Subject: Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars Message-ID: <e0b6c39a0809280851m845dc29y63d20ee6ef6c511e@mail.gmail.com> Hi, Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well the problem is I'm unable to scroll if I click on the arrows buttons of scrollbars ( with both types of scrollbars) Please suggest if I m missing some configuration. My code is as below: self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL) self.hsb.grid(row = 2,column = 0, sticky = E+W) #vertical scroll bar self.vsb = Scrollbar(appGuiFrame) self.vsb.grid(row = 1,column = 2, sticky = N+S) self.txtLogger = Text(appGuiFrame, \ height = 20,\ width = 100, \ state = DISABLED, \ xscrollcommand = self.hsb.set, \ yscrollcommand = self.vsb.set, \ wrap = NONE, \ font = ("courier",12)) self.hsb.config(command = self.txtLogger.xview()) self.vsb.config(command = self.txtLogger.yview()) Please help. Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080928/5d18b024/attachment-0001.html> From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 30 09:04:26 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 30 Sep 2008 15:04:26 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <00f15d41$0$20617$c3e8da3@news.astraweb.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <gbeae1$uin$1@rumours.uwaterloo.ca> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <gbgu3v$mie$1@rumours.uwaterloo.ca> <gbq6nq$j89$2@lust.ihug.co.nz> <48e11dd4$0$20720$426a74cc@news.free.fr> <00f15d41$0$20617$c3e8da3@news.astraweb.com> Message-ID: <48e223bc$0$13938$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Mon, 29 Sep 2008 18:27:22 +0200, Bruno Desthuilliers wrote: > >> Lawrence D'Oliveiro a ?crit : >>> In message <gbgu3v$mie$1 at rumours.uwaterloo.ca>, Ross Ridge wrote: >>> >>>> You need either use trial and error to find out, or look at the >>>> source. >>> So what's wrong with using the source as documentation? :) >> Don't know... Ok, having higher-level documentation (the big picture, >> and quick description of what and how for classes and functions) really >> helps. But when it comes to nitty-gritty details, source code is the >> best documentation ever, since it's always accurate and up to date. >> >> FWIW, I'm often surprised by people asking questions about some >> implementation detail of some open-source library or framework that are >> very easily answered just looking at the source code. Reading the source >> is 1/ the best way to really know how something is implemented and 2/ >> usually very instructive. > > Reading the source code is good, but it's not a panacea. Not what I implied. > There are at > least four things wrong with the advice to read the source code: My "advice to read the source code" was not meant as a *replacement* for documentation, but as a *complement* to it. What I meant is that you just can't document each and every detail of implementation. > > (1) It's not always available. > > (2) Even when the source is available, it is sometimes a legal trap to > read it with respect to patents and copyright. E.g. some Microsoft so- > called "open" licences (but not all) allow you to read the source, but if > you do then everything you program in a related field from that point is > legally contaminated and could be considered a derivative work of > Microsoft's software. I obviously implied that source was freely available and you had the right to read it. Else it just makes no sense. > (3) Source code not always understandable without significant effort. That's why reading the source can have a great educational value, isn't it ?-) > Code can be obfuscated, either to hide the algorithm, same problem as closed-source software - not concerned by this advice. > as an optimization, > or simply because the coder is cleverer than you are. It might be in a > language you don't understand (e.g. Python built-ins are written in C, > not Python. I have to learn C to find out what exceptions sorted() can > raise?). Every developer should have at least basic knowledge of C. MHO of course. > That's why accurate documentation should be preferred in the first place. Indeed. Did I say otherwise ? Now not all code has accurate documentation, and then you're happy to be able to access and possibly understand the source code. I'm not talking about an ideal world here. (snip) > Yes, documentation can fall behind the source code, but once the code is > stable and the documentation has caught up and is accurate, there's no > reason to re-invent the wheel by slugging through the source just to find > out something already documented. Once again, that's not what I said. > (4) Even when the source code is available, legally unencumbered, in a > language you understand and not too complicated for you to grasp, there's > the combinatorial explosion: you may need to read and understand an > arbitrarily large and complex chain of software merely to know what a > single function can do. Yes, this happens when hi-level documentation is lacking. At least you have a chance to gain some insight !-) > E.g. you want to know what exceptions function > spam() can raise: > > def spam(x): > a = 1 > b = 2 > c = ham(x) > return fried_eggs(a, b, c) > > Now you need to understand ham() and fried_eggs(), but they aren't > documented either. So you turn to their source code, and each of them > call two functions, each of which call another two functions, each of > which call *another* two functions... And still you're a lucky guy if there's no callback, conditional import and / or polymorphic dispatch involved. Steve, I may not have been clear, but I didn't meant that code shouldn't be documented. I was : 1/ answering to the question "So what's wrong with using the source as documentation?", my own personal answer being that it's something I often do, whether because I want to find out some detail not covered by the available documentation, whatever this available documention is worth 2/ digressing about the fact that, to my suprise, few developpers seem to *first* have a look at the source code when either documentation is lacking or they'd like to know more about some implementation detail. But FWIW, it seems that few developpers even bother reading the documentation at all :( From tsrinuvasulu491 at gmail.com Sun Sep 28 21:16:31 2008 From: tsrinuvasulu491 at gmail.com (chinu) Date: Sun, 28 Sep 2008 18:16:31 -0700 (PDT) Subject: EARN $$$ IN EVERY MONTH. Message-ID: <03865e77-4fa9-4e14-a4b6-1b3573e4eb40@a2g2000prm.googlegroups.com> hai, i am srinu from india. i am sending a blog url for yours use. click on the blog and get more information to choose yours job. the blog url is: http://earnmonthlyincome.blogspot.com/ goodluck From duncan.booth at invalid.invalid Thu Sep 25 08:22:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Sep 2008 12:22:08 GMT Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <gbe6qk$b54$1@aioe.org> <Xns9B23DFA195833duncanbooth@127.0.0.1> <d57f3edc-a305-4165-bafb-d0d75bb54948@z72g2000hsb.googlegroups.com> <Xns9B245BE13E207duncanbooth@127.0.0.1> <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> Message-ID: <Xns9B2487F2CF29Bduncanbooth@127.0.0.1> sturlamolden <sturlamolden at yahoo.no> wrote: > On 25 Sep, 10:08, Duncan Booth <duncan.bo... at invalid.invalid> wrote: > >> A lot of what LINQ does is already easy to do in Python, and most of >> the rest can probably be added fairly easily, but it does provide a >> consistent framework which may make it easier to do complex LINQ >> statements than complex list comprehensions. > > Yes, that's the word, "consistent framework". I wonder what that > means? Do you mean Python syntax is inconsitent? No Python's syntax is fine. The api's aren't as consistent though: Microsoft added a common set of extension methods which work on databases, xml, builtin sequences and can be easily extended to include other custom sequences. As an example to filter a list in Python you'd use a list comprehension with an 'if', but for a database you'd probably prefer a select with a 'where' clause so as to avoid retrieving and discarding 999999 or your 1 million rows. The apis defined by LINQ allow that sort of optimisation to happen transparently, the simple list would just test each element but the database would run an appropriate query. So what the 'can we have LINQ in Python' people are asking is to be able to write things like: x = (c for c in customers if c.id=='123') and know that they aren't doing a linear search unless that is the best that can be done. The LINQ equivalent would be something like: var x = from c in customers where c.id=='123' select new { c.name, c.id }; which is compiled to: var x = customers.Where(c => c.id=='123'); and depending on the type of 'customers' the Where method can either get a callable function to test the condition or an expression tree which it can compile into another language such as SQL (C# lambdas can compile either to executable code or to Expression<> objects that you can further process). There's an article at http://www.interact-sw.co.uk/iangblog/2005/09/30/expressiontrees which has a real example showing how: DataContext db = new DataContext("server=.;initial catalog=northwind"); Table<Orders> orders = db.GetTable<Orders>(); Table<Customers> customers = db.GetTable<Customers>(); var q = from o in orders, c in customers where o.ShipCity == "London" && (o.CustomerID == c.CustomerID) select new { o.OrderDate, c.CompanyName, c.ContactTitle, c.ContactName }; actually ends up as a single SQL query: exec sp_executesql N'SELECT [t1].[CompanyName], [t1].[ContactName], [t1].[ContactTitle], [t0].[OrderDate] FROM [Orders] AS [t0], [Customers] AS [t1] WHERE ([t0].[ShipCity] = @p0) AND ([t0].[CustomerID] = [t1]. [CustomerID])', N'@p0 nvarchar(6)', @p0 = N'London' >> BTW, a minor correction: LINQ statements are closer to generators, >> not list comprehensions. They don't actually evaluate their results >> until you iterate over them and you can re-used the same LINQ >> statement multiple times getting different results if the data has >> changed. > > Python has generator expressions with the same syntax as list > comprehensions, except you use () instead of []. > It might surprise you to know that I have actually come across generator expressions. :^) My wording was deliberate: LINQ queries are re-usable, so are Python's generators, but generator expressions are not. The comparison isn't exact, you have to call the generator to get an iterator whereas a LINQ expression gives you something which is directly iterable. -- Duncan Booth http://kupuguy.blogspot.com From alfons.nonell at upf.edu Mon Sep 29 12:45:34 2008 From: alfons.nonell at upf.edu (Alfons Nonell-Canals) Date: Mon, 29 Sep 2008 18:45:34 +0200 Subject: Generate documentation for a Python developed software Message-ID: <1222706734.15761.403.camel@king.imim.es> Dear all, I have a complex program developed using Python. It contains lot of files and classes. Now I have the lazy task to documentate it. I have some notes about is class but I would like to know if there is something to auto-generate the doucmentation with the program code. I know I will have to explain each class and variable but, if an external software canprepare it, the template, it will be great! Thanks in advance! Regards, -- ------------ Alfons Nonell-Canals Chemogenomics Lab Research Group on Biomedical Informatics (GRIB) - IMIM/UPF Parc de Recerca Biom?dica de Barcelona (PRBB) C/ Doctor Aiguader, 88 - 08003 Barcelona alfons.nonell at upf.edu - http://cgl.imim.es http://alfons.elmeuportal.cat http://www.selenocisteina.info From ppearson at nowhere.invalid Tue Sep 30 11:31:59 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 30 Sep 2008 15:31:59 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: <6kev3fF7l2r7U1@mid.individual.net> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: > > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? Since you're coming from the FORTRAN world (thank you for that stroll down Memory Lane), you might be doing scientific computations, and so might be interested in the SciPy package (Google scipy), which gives you arrays and matrices. Don't expect to be able to use it without learning some Python, though. -- To email me, substitute nowhere->spamcop, invalid->net. From tjreedy at udel.edu Tue Sep 16 13:41:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 13:41:11 -0400 Subject: literals optimization (was Re: append on lists) In-Reply-To: <200809161807.04172.maric@aristote.info> References: <gamffv$qms$1@online.de> <mailman.1116.1221574264.3487.python-list@python.org> <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> <200809161807.04172.maric@aristote.info> Message-ID: <gaor3i$242$1@ger.gmane.org> Maric Michaud wrote: > Le Tuesday 16 September 2008 16:57:26 Grant Edwards, vous avez ?crit : >> Where is that in the specification? > Each literal creates a new instance, This does not answer 'where' but just adds another false claim. I just reread the Reference Manual, Lexical Analysis chapter, Literals section and there is nothing like that that I saw. And the reference implementation is obviously different. From stargaming at gmail.com Tue Sep 23 08:58:57 2008 From: stargaming at gmail.com (Robert Lehmann) Date: 23 Sep 2008 12:58:57 GMT Subject: Comparing float and decimal References: <mailman.1400.1222168827.3487.python-list@python.org> Message-ID: <48d8e810$0$4541$9b622d9e@news.freenet.de> On Tue, 23 Sep 2008 07:20:12 -0400, D'Arcy J.M. Cain wrote: > I'm not sure I follow this logic. Can someone explain why float and > integer can be compared with each other and decimal can be compared to > integer but decimal can't be compared to float? In comparisons, `Decimal` tries to convert the other type to a `Decimal`. If this fails -- and it does for floats -- the equality comparison renders to False. For ordering comparisons, eg. ``D("10") < 10.0``, it fails more verbosely:: TypeError: unorderable types: Decimal() < float() The `decimal tutorial`_ states: "To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error)." See the `decimal FAQ`_ for a way to convert floats to Decimals. >>>> from decimal import Decimal >>>> i = 10 >>>> f = 10.0 >>>> d = Decimal("10.00") >>>> i == f > True >>>> i == d > True >>>> f == d > False > > This seems to break the rule that if A is equal to B and B is equal to C > then A is equal to C. I don't see why transitivity should apply to Python objects in general. HTH, .. _decimal tutorial: http://docs.python.org/lib/decimal-tutorial.html .. _decimal FAQ: http://docs.python.org/lib/decimal-faq.html -- Robert "Stargaming" Lehmann From wjvriend at zonnet.nl Tue Sep 30 14:59:27 2008 From: wjvriend at zonnet.nl (Willem-Jan Vriend) Date: Tue, 30 Sep 2008 20:59:27 +0200 Subject: pylab without X11 Message-ID: <48E2770F.1070300@zonnet.nl> I want to use pylab (matplotlib) on a machine without X11. I'm trying to generate onthefly graphics for an apache2 web service, so they do not have to be displayed on this machine ! When i do pylab.figure() I get the error TclError: couldn't connect to display ":0.0" I tried setting the DISPLAY environment variable to "", ":0.0" but I got the same error message. Any help is very much appreciated. From timr at probo.com Tue Sep 9 02:08:36 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 09 Sep 2008 06:08:36 GMT Subject: found a bug with smtpd, where can i report this? References: <mailman.633.1220738819.3487.python-list@python.org> Message-ID: <vm4cc4pmoo3403u9hgru4mvggjjpffqo93@4ax.com> "Marcus.CM" <marcus at internetnowasp.net> wrote: > >Where should i report the bug? >smtpd bug. Why don't you tell us about it? There may be another explanation. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mail at anjanesh.net Wed Sep 10 12:33:46 2008 From: mail at anjanesh.net (Anjanesh Lekshminarayanan) Date: Wed, 10 Sep 2008 22:03:46 +0530 Subject: PHP's str_replace ? In-Reply-To: <6iq2sbFs113rU2@mid.uni-berlin.de> References: <mailman.788.1221054649.3487.python-list@python.org> <6iq2jpFs113rU1@mid.uni-berlin.de> <6iq2sbFs113rU2@mid.uni-berlin.de> Message-ID: <48C7F6EA.7010202@anjanesh.net> Matthias Huening wrote: > Matthias Huening (10.09.2008 16:07): >> Anjanesh Lekshminarayanan (10.09.2008 15:50): >>> In PHP, if I do >>> str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) >>> it'll replace all vowels with a hyphen in string $str. >>> >>> Is there some equivalent in Python ? >> >> What about something like this: >> >> import re >> new_str = re.sub('([aeiou])-', r'\1', str) >> > > Sorry - I misinterpreted your question. > Try this instead: > > import re > new_str = re.sub('[aeiou]', '-', str) Wow - this is neat. Thanks From aahz at pythoncraft.com Sun Sep 7 10:18:03 2008 From: aahz at pythoncraft.com (Aahz) Date: 7 Sep 2008 07:18:03 -0700 Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> <mailman.504.1220561513.3487.python-list@python.org> Message-ID: <ga0nqr$4ek$1@panix3.panix.com> In article <mailman.504.1220561513.3487.python-list at python.org>, Fredrik Lundh <fredrik at pythonware.com> wrote: >Martin DeMello wrote: >> >> In the interests of not hammering the db unnecessarily, I'm >> considering the following >> 1. A series of independent "monitor" threads that collect information >> over TCP from the cluster of machines, and write it to a queue >> 2. A "logger" thread that empties the queue every second or so and >> inserts the collected information to the db via a single insert >> statement > >why are you using a queue for this case, btw? why not just use a plain list > > L = [] > lock = threading.Lock() > >and add stuff using append in the monitor threads > > with lock: > L.append(item) Because using a queue requires less thinking. I certainly would use a queue in this case instead of rolling my own. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From adityashukla1983 at gmail.com Fri Sep 26 16:23:11 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Fri, 26 Sep 2008 15:23:11 -0500 Subject: Classes and functions. Message-ID: <73045cca0809261323r4a74d09fkdad22396b0a88324@mail.gmail.com> Hello folks , i am using the newick module http://www.daimi.au.dk/~mailund/newick.html.I am just learning to use it and i have a question about it. from newick.tree import parse_tree from newick.tree import add_parent_links from newick.tree import add_distance_from_root import sys t = parse_tree('((A:2,B:3):1,C:6);') print t deltas = add_distance_from_root(t) now when i do this i can get the output like this (('A' : 2.0, 'B' : 3.0) : 1.0, 'C' : 6.0) None This is the code of the add_distance_from_root(0 def add_distance_from_root(tree): '''Extend all nodes with the distance (branch length) from the root''' tree.distance_from_root = 0.0 # 'tree' is the root... class V(TreeVisitor): def pre_visit_edge(self,src,b,l,dst): if l is None: l = 0 dst.distance_from_root = src.distance_from_root - l tree.dfs_traverse(V()) >From here it is clear that the function does not return anything but i wanna get the value of the distance from root.How can i get this? Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/b9eff370/attachment-0001.html> From rNOSPAMon at flownet.com Fri Sep 19 02:29:06 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 Sep 2008 23:29:06 -0700 Subject: CTypes on a 64 bit machine truncates pointers to 32 bits? References: <rNOSPAMon-1F20D8.18212118092008@news.gha.chartermi.net> <48d34449$0$2363$9b622d9e@news.freenet.de> Message-ID: <rNOSPAMon-B959CC.23290518092008@news.gha.chartermi.net> In article <48d34449$0$2363$9b622d9e at news.freenet.de>, "Martin v. L?wis" <martin at v.loewis.de> wrote: > >>>> foolib = cdll.LoadLibrary('foo.so') > >>>> foolib.foo(0xF00000000) > > 0 > > Shouldn't you tell ctypes that the argument and the result > of foo is a pointer? Yeah... that's it. Default return type is int, which I assumed would be 64 bits on a 64 bit machine, but turns out it's 32. Stupid. rg From emile at fenx.com Fri Sep 5 12:35:03 2008 From: emile at fenx.com (Emile van Sebille) Date: Fri, 05 Sep 2008 09:35:03 -0700 Subject: Retrieving the name of the class calling an instance method In-Reply-To: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> References: <8b51e78c0809050829g5198df2ahaa7cf2b8989e700c@mail.gmail.com> Message-ID: <g9rn7k$8dr$1@ger.gmane.org> mercado mercado wrote: > In Python, is it possible for an instance method to know the name of the > class which is calling it? Well, the class name is in __class__ so changing 'print x' to 'print __class__' will show foo in both cases, which is in fact the name of the class which is calling it. Of course, what you want is the name of the thing chained in front of that. There are and are not ways of getting to that. Dig into the traceback module. But I'd pass a parameter to foo's __init__ such as foo('bar') and foo('again') and it'd always work. HTH, Emile > For example, in the sample below, I would > like for the someMethod method to print the name of the class calling it > ("bar" in the first case, "again" in the second). > > --------------------------------------- > class foo(): > def someMethod(self): > print x > > class bar(): > def __init__(self): > f = foo() > f.someMethod() > > class again(): > def __init__(self): > f = foo() > f.someMethod() > > bar() > again() > --------------------------------------- > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From giltay at gmail.com Fri Sep 19 11:47:03 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Fri, 19 Sep 2008 08:47:03 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <d7f95f5e-044a-46d6-a2a0-7389eb7696b2@k13g2000hse.googlegroups.com> On Sep 18, 7:42?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > I'm not being snarky about losing priority here, but I submitted > essentially the same solution two hours earlier than pruebono. My apologies (seriosuly). In this case, I think it might just be haste. For what it's worth, I saw your post (on Google Groups), but I skipped over it. You wrote two solutions, one slow and one fast (the latter being the same as pruebono's). You put the slow one at the top, I saw for ... for ... and went straight to the next message without reading the better solution. I knew that there was only one for loop necessary, so I didn't bother reading on. Actually, I missed pruebono's post, too, until after I figured it out myself (but before I posted). That several people came up with the nigh exact same solution, modulo variable names only, says something about the Zen of Python. Geoff G-T From workitharder at gmail.com Wed Sep 3 16:55:52 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 3 Sep 2008 13:55:52 -0700 (PDT) Subject: Late initialization using __getattribute__ Message-ID: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> I want to make a MixIn class that waits to initialize its super- classes until an attribute of the object is accessed. Not generally useful, but desirable in my case. I've written this, and it works, but would like to take any suggestions you guys have. I've commented out the "delattr" call because it throws an AttributeError (although I don't know why). class LateInitMixIn(object): def __init__(self): print "LateInit initialization" self.inited = False def __getattribute__(self, attr): print "Doing __getattribute__" getattr = lambda attr:object.__getattribute__(self, attr) if not getattr("inited"): super(LateInitMixIn, self).__init__() setattr(self, "inited", True) #delattr(self, "__getattribute__") return getattr(attr) class Base(object): def __init__(self): print "Base initialization" self.base = True class LateInit(LateInitMixIn, Base): pass def main(): S = LateInit() print S print print "Should do Base init after now" print S.base print S.base if __name__=="__main__": main() This gives the following output: LateInit initialization <__main__.LateInit object at 0x2a960c1c50> Should do Base init after now Doing __getattribute__ Base initialization True Doing __getattribute__ True From hniksic at xemacs.org Wed Sep 24 05:18:26 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 24 Sep 2008 11:18:26 +0200 Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <87myi0z4tq.fsf@mulj.homelinux.net> <dfe26463-49fa-4f79-8b55-ac098d6808fb@26g2000hsk.googlegroups.com> Message-ID: <87ljxh3nrx.fsf@mulj.homelinux.net> josh logan <dear.jay.logan at gmail.com> writes: > It looks like __cmp__ is still in the documentation, and it seems to > work somewhat in Python 3.0rc1. Here is the link to the documnetation > http://docs.python.org/dev/3.0/reference/datamodel.html#object.__cmp__ Thanks, I've now filed a bug report for that. It looks like an oversight. From darcy at druid.net Tue Sep 23 07:20:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 23 Sep 2008 07:20:12 -0400 Subject: Comparing float and decimal Message-ID: <20080923072012.57d8d329.darcy@druid.net> I'm not sure I follow this logic. Can someone explain why float and integer can be compared with each other and decimal can be compared to integer but decimal can't be compared to float? >>> from decimal import Decimal >>> i = 10 >>> f = 10.0 >>> d = Decimal("10.00") >>> i == f True >>> i == d True >>> f == d False This seems to break the rule that if A is equal to B and B is equal to C then A is equal to C. -- D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From andy_westken at hotmail.com Thu Sep 11 10:21:43 2008 From: andy_westken at hotmail.com (andy_westken at hotmail.com) Date: Thu, 11 Sep 2008 07:21:43 -0700 (PDT) Subject: Enumerating ordered expat attributes with tuplets? Message-ID: <c397633b-d558-4fbf-a0a4-d1c1cd7a3ecb@34g2000hsh.googlegroups.com> Hi I'm new to Python and trying to pick up good, idiomatic usage right from the offset. As I was familiar with Expat from C++ (directly and via expatpp) I'm trying to write a little script - using xml.parsers.expat - to search and replace XML attribute values. As I want the attributes to stay in order when the file is written out (so I can check my results with a diff tool) I've set the parser's ordered_attributes attribute. But this has stopped the for loop working with the tuplets. The relevant bit of code in my little test, using the default Dictionary for the attributes, is: def start_element(name, attrs): print "%s : " % name, for (a,b) in attrs.items(): print " %s=\"%s\"" % (a,b), But when I set ordered_attributes, first it doesn't like the items() AttributeError: 'list' object has no attribute 'items' And then it doesn't like the tuple ValueError: too many values to unpack Do I have keep track of where I am (name, value, name, value, ...) Or is there a way I can solve the problem with a tuple? Thanks, Andy From stef.mientki at gmail.com Tue Sep 30 16:59:52 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 22:59:52 +0200 Subject: Would this be called a bug in inspect ? In-Reply-To: <gbu27j$3l5$1@ger.gmane.org> References: <48E268A3.4050900@gmail.com> <op.uia609w8x6zn5v@gabriel2.softlabbsas.com.ar> <48E28534.1040009@gmail.com> <gbu27j$3l5$1@ger.gmane.org> Message-ID: <48E29348.1000801@gmail.com> Terry Reedy wrote: > Stef Mientki wrote: > >> print getmembers ( wx ) >> crashes >> >> but not always: >> >>> print getmembers (wx) >> [('ACCEL_ALT', 1), ('ACCEL_CMD', 2), ('ACCEL_CTRL', 2), >> ('ACCEL_NORMAL', 0), ('ACCEL_SHIFT', 4), ('ADJUST_MINSIZE', 0), ( > > I suspect that wx has an erratic bug, which their tests do not catch. > So I would send this off to them. I did, and the bug is already fixed, but I need some more time to update, while most of my programs crash with the newer version. But the real point is, should a module like inspect not be insensitive to these kind of errors ? cheers, Stef > >> >>> print getmembers (wx) >> Traceback (most recent call last): >> File "<interactive input>", line 1, in <module> >> File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", >> line 242, in __repr__ >> def __repr__(self): return 'wx.Colour' + >> str(self.Get(True)) >> File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", >> line 230, in Get >> return _gdi_.Colour_Get(*args, **kwargs) >> TypeError: in method 'Colour_Get', expected argument 1 of type >> 'wxColour *' > > -- > http://mail.python.org/mailman/listinfo/python-list From hrishys at yahoo.co.uk Tue Sep 23 10:48:37 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Tue, 23 Sep 2008 14:48:37 +0000 (GMT) Subject: Linq to Python In-Reply-To: <18648.63979.426433.48679@montanaro-dyndns-org.local> Message-ID: <305501.28149.qm@web27402.mail.ukl.yahoo.com> Hi Will LINQ be ported to Python ? regards Hrishy From ldo at geek-central.gen.new_zealand Mon Sep 29 02:49:44 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 19:49:44 +1300 Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> Message-ID: <gbptq8$dqp$3@lust.ihug.co.nz> In message <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0 at m45g2000hsb.googlegroups.com>, Aaron "Castironpi" Brady wrote: > [Wikipedia] says: > "dynamic scoping can be dangerous and almost no modern languages use > it", but it sounded like that was what closures use. Closures will use whatever the language says they use. LISP used dynamic binding, but this caused some interesting problems as mentioned above. Perl allows both, depending on whether the local is declared with "local" or "my". Python uses only lexical, though there's probably some way to get dynamic behaviour if you want. :) From missive at hotmail.com Wed Sep 17 17:56:29 2008 From: missive at hotmail.com (Lee Harr) Date: Thu, 18 Sep 2008 02:26:29 +0430 Subject: decorator and API Message-ID: <BAY112-W5575CEC99EBFC3B639B0E2B14C0@phx.gbl> I have a class with certain methods from which I want to select one at random, with weighting. The way I have done it is this .... import random def weight(value): def set_weight(method): method.weight = value return method return set_weight class A(object): def actions(self): 'return a list of possible actions' return [getattr(self, method) for method in dir(self) if method.startswith('action_')] def action(self): 'Select a possible action using weighted choice' actions = self.actions() weights = [method.weight for method in actions] total = sum(weights) choice = random.randrange(total) while choice> weights[0]: choice -= weights[0] weights.pop(0) actions.pop(0) return actions[0] @weight(10) def action_1(self): print "A.action_1" @weight(20) def action_2(self): print "A.action_2" a = A() a.action()() The problem I have now is that if I subclass A and want to change the weighting of one of the methods, I am not sure how to do that. One idea I had was to override the method using the new weight in the decorator, and then call the original method: class B(A): @weight(50) def action_1(self): A.action_1(self) That works, but it feels messy. Another idea was to store the weightings as a dictionary on each instance, but I could not see how to update that from a decorator. I like the idea of having the weights in a dictionary, so I am looking for a better API, or a way to re-weight the methods using a decorator. Any suggestions appreciated. _________________________________________________________________ Explore the seven wonders of the world http://search.msn.com/results.aspx?q=7+wonders+world&mkt=en-US&form=QBRE From jcd at sdf.lonestar.org Fri Sep 5 10:00:39 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 05 Sep 2008 10:00:39 -0400 Subject: Case-insensitive string compare? In-Reply-To: <200809051536.45285.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> <1220618002.21923.12.camel@jcd-desktop> <200809051536.45285.maric@aristote.info> Message-ID: <1220623239.5787.10.camel@aalcdl07.lib.unc.edu> Please keep the discussion on-list. On Fri, 2008-09-05 at 15:36 +0200, Maric Michaud wrote: > Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez ?crit : > > On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: > > > Thanks everyone for your help. I'm not opposed to using [key.lower() > > > for key in stage_map] at all, I was just curious to see if there were > > > any cleaner alternatives. It looks like that is what I'll be using. > > > I'm not familiar with how python works internally, but coming from C++ > > > it seems like "remaking" the map would be slow. However, speed is not > > > my main concern in my particular situation, I'm just curious to learn > > > more about python. > > > > You should be opposed to that particular solution. You have just taken > > a dictionary lookup (very fast) and turned it into a list traversal > > (slow). Even if speed isn't your main concern, this is an unnecessary > > de-optimization. You are deliberately slowing down your program to > > avoid a slightly more verbose lookup later. Your data structure might > > as well be a list of tuples to begin with, to avoid creating a new list. > > You have effectively made your keys useless as keys. > > > > If your lookups need to be case insensitive, make the key lower case, > > and store the cased version in the value, whether as a tuple or a dict > > (depending on whether you want named access). > > > > d = { > > 'foo': {'key': 'Foo', 'value': 'val1'} > > 'spam': {'key': 'sPAm', 'value': 'val2'} > > } > > > > search = 'FOO'.lower() > > if search in d: > > result = d[search] > > key = result['key'] > > value = result['value'] > > > > The only reason I wouldn't use this solution is if you expect to have > > keys that will be identical when made lowercase, but if you're doing > > case-insensitive lookup, you obviously don't expect this to be an issue. > > > > The OP has already said the keys are case-sensitive, so this is not an option, > the only way to do it fast is to index upon insertion all keys in another > dict, so you get in final : > d = { "kEy1" : 1, "Key1" : 2} > indexes = { "key1" : ["kEy1", "Key1" ] } > That does not get the same behavior as the OP's original solution. The OP's solution retrieves the first matching value only. Mine gets one arbitrary matching value, determined by the algorithm used for constructing the search dict (not specified in my solution). What the OP actually said was that he can't throw away the case. You assume that this means there would be multiple entries distinguished only by case. That might be true, but given his initial solution, it seemed to me more likely that he wants to keep the case for display purposes, as in a dictionary like this: { "Michaud": "Maric", "Dyer": "Cliff", "D'Amato": "Alphonse", } To the OP: If you are looking for multiple matches for a given case-insensitive key, check out the recent thread on "Python multimap", for further discussion elaborating on how to map one key to many values in a dictionary-like object. At that point, it's probably worth factoring out your solution to a separate class, so you can work with a clean interface, rather than repeating the ugly details every time you use it. Cheers, Cliff > > Cheers, > > Cliff > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From casey.mcginty at gmail.com Wed Sep 3 16:21:49 2008 From: casey.mcginty at gmail.com (Casey) Date: Wed, 3 Sep 2008 13:21:49 -0700 (PDT) Subject: Usual practice: running/testing modules in a package References: <827c7ee5-fad1-4a8c-8724-d6504c91be6d@w1g2000prk.googlegroups.com> <63d32551-7d94-4ab9-9c06-2bd2c8b8e0b8@a3g2000prm.googlegroups.com> Message-ID: <f6e21338-73e4-4db6-8c89-f6598601be4d@a18g2000pra.googlegroups.com> On Aug 26, 10:21?pm, Casey <casey.mcgi... at gmail.com> wrote: > On Aug 12, 9:57?pm, alito <alito... at gmail.com> wrote: > > > > > A wrapper on the level up works: > > > ~/python$ cat importercaller.py > > from testpackage import config > > config.hello() > > > ~/python$ python importercaller.py > > hello > > > So, how do I run these modules without writing a wrapper script for > > each one? > It looks like PEP 366 [http://www.python.org/dev/peps/pep-0366/] will solve this issue. From showellshowell at gmail.com Mon Sep 15 23:58:27 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Mon, 15 Sep 2008 20:58:27 -0700 (PDT) Subject: ISO simple debugging sniffer for HTTP Message-ID: <6e11834e-a89d-4cea-b69f-55fa13bb502e@s28g2000prd.googlegroups.com> Hi everybody, I'm looking for a very simple HTTP debugging sniffer in Python-- hopefully 200 lines of less--that allows me to write simple methods to inspect requests and responses. It would ideally work like this: sniffer = SimpleHttpDebuggingSniffer(actual_host_address, actual_host_port) sniffer.listening_port = SOME_PORT_ON_MY_DESKTOP sniffer.inbound_inspector = some_method_i_write sniffer.outbound_inspector = some_other_method_i_write sniffer.run() I would launch it from a Linux desktop terminal and use it help debug a Java application I'm maintaining that uses an opaque library to hit an opaque service. I can configure the client app to connect to the sniffer, and apart from inspecting packets, I just want it to pass data along to the real server. I'm not using any complicated part of the HTTP protocol--it's mostly simple request, simple response, but the payloads are not plain text, so I need some Python code to make sense of them. I've googled a bit, and I've come up with a lot of noise, so I'm hoping some one can point me in the direction of some simple code that they have confidence in, which is free and all that good stuff. Thanks, Steve From john.ford at colorado.edu Thu Sep 25 10:45:31 2008 From: john.ford at colorado.edu (john.ford at colorado.edu) Date: Thu, 25 Sep 2008 07:45:31 -0700 (PDT) Subject: How to parse a string completely into a list References: <e9e4f5c7-3467-4078-a401-fb732d69cc64@a3g2000prm.googlegroups.com> <mailman.1479.1222314277.3487.python-list@python.org> <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <mailman.1480.1222315955.3487.python-list@python.org> <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> <mailman.1481.1222329107.3487.python-list@python.org> Message-ID: <e5d72ac8-0f92-4080-9e6b-34289bc52564@p31g2000prf.googlegroups.com> On Sep 25, 1:51?am, Tino Wildenhain <t... at wildenhain.de> wrote: > john.f... at colorado.edu wrote: > > On Sep 24, 10:12 pm, Matt Nordhoff <mnordh... at mattnordhoff.com> wrote: > >> john.f... at colorado.edu wrote: > >>> On Sep 24, 9:44 pm, "Chris Rebert" <c... at rebertia.com> wrote: > .... > >>>> Could you please define exactly what you mean by "elements" of a string? > >>>> If you mean characters, then just use list():>>> list(" ?\n \t abc") > >>>> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] > >>>> Regards, > >>>> Chris > >>> Worked like a charm. > >>> kudos! > >> Why do you need to convert it to a list? Strings are sequences, so you > >> can do things like slice them or iterate through them by character: > > >>>>> for character in "foo": > >> ... ? ? print character > >> ... > >> f > >> o > >> o > > >> -- > > > The string draws a map that I then want to be able to traverse > > through. If I can count through the individual characters of a list I > > can create an x-y coordinate plane for navigation. > > You can 'count' (whatever that means) equally in strings as you do in > lists. As said above, they behave exactly the same. Just strings > are imutable - e.g. you can't change individual parts of them. > > Tino > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ?smime.p7s > 4KViewDownload Ahh, but I forgot to mention that I have to mark the path I took in the string. So using list() and then join() are my best options. From deets at nospam.web.de Mon Sep 22 03:24:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 Sep 2008 09:24:15 +0200 Subject: External code and functions integration In-Reply-To: <a9a4a8ef-cb28-4d9f-b91c-bc4e43af53e7@b1g2000hsg.googlegroups.com> References: <a9a4a8ef-cb28-4d9f-b91c-bc4e43af53e7@b1g2000hsg.googlegroups.com> Message-ID: <6jovgvF4ccsmU1@mid.uni-berlin.de> Cro schrieb: > Good day. > > I am using python for quite some time now and i decided to advance a > little. I want to write a little extension, or add some C modules for > my python. I use Active version. > > What i want to do is write some wrappers for a game library, called > HGE. See "hge.relishgames.com". > I wrote some applications with HGE, in C++ and i like it pretty much. > In order to make a HGE application in C++, i need to include "hge.h", > include "hge.lib" and "hgelehper.lib", and have "hge.dll" in the same > directory. So it's 3 things i must have for the program to work. > This game library is open source, so i have the source for the libs > and the dll. > > Now, what i was thinking was to make some wrapping code like "hge.h" > to call all the functions in the "libs", that (i guess) call the > functions from "hge.dll", that (blah blah) calls DirectX and so on. > I guess that if i write all that "hge.h" includes and wariables in > python, will be okay... even if i still don't have the skill. > > I tried to call "hge.lib" like this: > " > from ctypes import * > cdll.LoadLibrary("D:/HGE18/lib/bc/hge.lib") > " > But i get "WindowsError: [Error 193] %1 is not a valid Win32 > application". > I tried with windll.LoadLibrary ... and i get the same error. > I tried with the other lib versions, there are 3 versions: BorlandC, > GCC, VisualC, callind "cdll" or "windll". All lib versions report the > same error. Because you need to load the DLL. Diez From clp at rebertia.com Mon Sep 8 18:28:38 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Sep 2008 15:28:38 -0700 Subject: class(object) and (type)?? In-Reply-To: <f9e39bbc0809081435kd5c3b32x36f4f615fd00f3a0@mail.gmail.com> References: <f9e39bbc0809081435kd5c3b32x36f4f615fd00f3a0@mail.gmail.com> Message-ID: <47c890dc0809081528o66259e27l6c92abb6757652a9@mail.gmail.com> Subclassing 'object' makes the class new-style as opposed to old-style. object is the ultimate superclass of all new-style classes. Old-style classes are deprecated and will be removed in Python 3.0, but they're currently the default for backward-compatibility reasons. See http://docs.python.org/ref/node33.html for more info. - Chris On Mon, Sep 8, 2008 at 2:35 PM, AON LAZIO <aonlazio at gmail.com> wrote: > Hi again pythoners, > I notice in the class of a code having (object) and (type) attached to > the name of the class. > I know that in other cases, that means the class inherits methods and > properties from other but > In this case, what does it mean? > For example, > > class PY(object): > def __init__(self): > ... > > class PO(type): > def __init__(self): > ... > What do "object" and "type" mean? > > Thanks in advance > > Aonlazio > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From tjreedy at udel.edu Mon Sep 1 15:31:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 15:31:41 -0400 Subject: Buffer objects In-Reply-To: <aa19747c0809010828s3df678bdpe9afb617d39525f6@mail.gmail.com> References: <aa19747c0809010828s3df678bdpe9afb617d39525f6@mail.gmail.com> Message-ID: <g9hfut$sji$1@ger.gmane.org> Tom Harris wrote: > Greetings, > > I need a little help with buffer objects. Many Python objects export > the buffer interface, or can be persuaded to create a buffer object > with a buffer() call. ... > It must be me but I have found the whole buffer thing difficult to > understand from the docs, it appears only useful to C coders, but I > use the buffer interface (GetData()) of wx.Image objects a lot in my > work. The 1.x/2.x buffer interface was not considered terribly successful. Buffer() is gone in 3.0. I believe class memoryview() (which supports viewing the 'buffer' as an n-dimensional array) is considered to be its replacement. You might find the latter in 2.6 also. Images, in particular, will be viewed as row x column x color, or color x row x column, or whatever, as defined by the attributes of the memory view object in a standardized format. From lists at cheimes.de Wed Sep 10 13:20:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 19:20:31 +0200 Subject: PHP's str_replace ? In-Reply-To: <48C7F6EA.7010202@anjanesh.net> References: <mailman.788.1221054649.3487.python-list@python.org> <6iq2jpFs113rU1@mid.uni-berlin.de> <6iq2sbFs113rU2@mid.uni-berlin.de> <48C7F6EA.7010202@anjanesh.net> Message-ID: <ga8vku$ap$1@ger.gmane.org> Anjanesh Lekshminarayanan wrote: >> import re >> new_str = re.sub('[aeiou]', '-', str) > Wow - this is neat. Thanks But probably slower and definitely harder to understand. For simple problems the str methods are usually faster than a regular expression. Christian From tom.willis at gmail.com Wed Sep 24 11:47:55 2008 From: tom.willis at gmail.com (Thomas G. Willis) Date: Wed, 24 Sep 2008 11:47:55 -0400 Subject: Linq to Python In-Reply-To: <319386.9452.qm@web27402.mail.ukl.yahoo.com> References: <eca5012c-65c6-4857-b135-104191a45056@r66g2000hsg.googlegroups.com> <319386.9452.qm@web27402.mail.ukl.yahoo.com> Message-ID: <b54d04890809240847o19d19b27u4f43d580b01376a2@mail.gmail.com> On Wed, Sep 24, 2008 at 11:25 AM, hrishy <hrishys at yahoo.co.uk> wrote: > Hi Tom > > This is what i like and feel of the Python programmers smarter then every > other langauge i know of. > > But i am not comfortable with your second statement XML i never need it > one day everybody would need it. > > > regards > Hrishy > > Well you may be right which is why I said "hopefully" one thing I do know is that in my work in both .net and java, XML plays a more significant role. Everyone can probably speculate differently as to why this is. My personal feeling is that it is because XML is less of a hassle than building/passing around class hierarchies for application state in various scenarios.But in python, it is far easier for me to pass around a dict or some similar structure to get roughly the same effect. So in my mind, XML solves a problem that is present in both .net and java, but not necessarily python. In the same way, linq to xml solves the problem of handling xml in a more convenient way. In order for it to be useful in python, the problem that xml solves would have to be present IMO. That's not to say it's not possible. Someone who needs something like LINQ to XML but in python could write something probably similar to what sqlalchemy does and it would require no changes to the python language or runtime. If it was written then maybe people would invent ways to use XML in python that are better than what other things do. Hooray for the free market of ideas. :) This is all my opinion , I have no idea what the conventional wisdom of the python community is on XML, but in my experience in other languages, it seems to be the answer to a question that no one asked, or the wrong answer, more often than it is the appropriate answer. Maybe it's only that way on OHIO. :) -- Thomas G. Willis -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080924/16526dcc/attachment-0001.html> From google at mrabarnett.plus.com Thu Sep 25 18:01:15 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 25 Sep 2008 15:01:15 -0700 (PDT) Subject: text processing References: <mailman.1505.1222361869.3487.python-list@python.org> <6k20ckF5glpmU1@mid.uni-berlin.de> Message-ID: <8db0408a-6564-4c97-ac14-fb0d92a14b3a@b1g2000hsg.googlegroups.com> On Sep 25, 6:34?pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: > On Thu, 25 Sep 2008 15:51:28 +0100, jitensha... at gmail.com wrote: > > I have string like follow > > 12560/ABC,12567/BC,123,567,890/JK > > > I want above string to group like as follow (12560,ABC) > > (12567,BC) > > (123,567,890,JK) > > > i try regular expression i am able to get first two not the third one. > > can regular expression given data in different groups > > Without regular expressions: > > def group(string): > ? ? result = list() > ? ? for item in string.split(','): > ? ? ? ? if '/' in item: > ? ? ? ? ? ? result.extend(item.split('/')) > ? ? ? ? ? ? yield tuple(result) > ? ? ? ? ? ? result = list() > ? ? ? ? else: > ? ? ? ? ? ? result.append(item) > > def main(): > ? ? string = '12560/ABC,12567/BC,123,567,890/JK' > ? ? print list(group(string)) > How about: >>> string = "12560/ABC,12567/BC,123,567,890/JK" >>> r = re.findall(r"(\d+(?:,\d+)*/\w+)", string) >>> r ['12560/ABC', '12567/BC', '123,567,890/JK'] >>> [tuple(x.replace(",", "/").split("/")) for x in r] [('12560', 'ABC'), ('12567', 'BC'), ('123', '567', '890', 'JK')] From xlebourd at gmail.com Mon Sep 15 05:28:28 2008 From: xlebourd at gmail.com (Xavier) Date: Mon, 15 Sep 2008 02:28:28 -0700 (PDT) Subject: Serial I/O problem with pywin32 ? References: <f5ff935a-3e1b-4f72-bdcf-6d948b25ace0@2g2000hsn.googlegroups.com> <6i7p2uFp2lqbU1@mid.uni-berlin.de> <d949bdab-0ee3-441c-8061-3062a94d3b6d@r15g2000prd.googlegroups.com> Message-ID: <95ccb42d-ab51-4339-bc92-f51646dafa15@y21g2000hsf.googlegroups.com> Hi I have resolved my problem by checking paquets. It seems that it is a problem of the GPS (it's a very cheap GPS Datalogger). > Could be hardware flow control. See this sometimes on the bluetooth > connections that are using Serial Port Protocol and the hardware flow > control hasn't been physically implemented. It seems it is the problem. The policy seems to be : - ask the GPS for the data - touch wood - retry with the missing chunks Even the official driver is doing this. > Do you lose data after exactly the same amount of data has > been received? Not. The lost are randomized but it's chunks, ex : 300 consecutive bytes ok 30 consecutive bytes lost 250 bytes ok 40 bytes lost 800 bytes ok 50 bytes lost ... From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 06:43:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 12:43:45 +0200 Subject: list + dictionary searching In-Reply-To: <6e642a00-9301-440d-902c-63713cf4a793@a2g2000prm.googlegroups.com> References: <6e642a00-9301-440d-902c-63713cf4a793@a2g2000prm.googlegroups.com> Message-ID: <48bbc70e$0$13542$426a74cc@news.free.fr> Manoj a ?crit : > Hello All, > > I am very new to python. Any help will be highly appreciated. Thanks > > I have a list of dictionaries: > > a = [{'username': u'John Wang', 'user_utilization': 1.0, 'month': 9, > 'user_id': 4, 'year': 2008}, {'username': u'John Wang', > 'user_utilization': 1.0, 'month': 10, 'user_id': 4, 'year': 2008}, > {'username': u' ', 'user_utilization': 1.0, 'month': 9, 'user_id': 1, > 'year': 2008}] > > I would like to : > > search dictionaries within this list Care to elaborate ??? > create a new list with dictionaries which gives 1 dictionary for every > user with month_year as a key and utilization for that month as a > value assuming the user_id/month/year combination is unique: from collections import defaultdict users = defaultdict(dict) for record in a: month_year = "%(month)s_%(year)s" % record users[record['user_id']][month_year] = record['user_utilization'] print users.values() HTH From fredrik at pythonware.com Sun Sep 7 10:34:59 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 07 Sep 2008 16:34:59 +0200 Subject: Not fully understanding the role of Queue.task_done() In-Reply-To: <ga0nqr$4ek$1@panix3.panix.com> References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> <mailman.504.1220561513.3487.python-list@python.org> <ga0nqr$4ek$1@panix3.panix.com> Message-ID: <ga0oql$ree$1@ger.gmane.org> Aahz wrote: >> why are you using a queue for this case, btw? why not just use a plain list >> >> L = [] >> lock = threading.Lock() >> >> and add stuff using append in the monitor threads >> >> with lock: >> L.append(item) > > Because using a queue requires less thinking. given that the whole reason for this thread was that Queue API didn't fit the OP:s problem, that's a rather dubious statement. (btw, I've always thought that Python was all about making it easy to express the solution to a given problem in code, not to let you write programs without using your brain. when did that change?) </F> From marco.bizzarri at gmail.com Thu Sep 4 10:12:32 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 16:12:32 +0200 Subject: overwrite set behavior In-Reply-To: <200809041507.35366.maric@aristote.info> References: <g9oat3$veh$1@nnrp-beta.newsland.it> <mailman.468.1220522726.3487.python-list@python.org> <g9oker$66v$1@nnrp-beta.newsland.it> <200809041507.35366.maric@aristote.info> Message-ID: <3f0d61c40809040712y4ef2edd4rb4c98035c5581886@mail.gmail.com> On Thu, Sep 4, 2008 at 3:07 PM, Maric Michaud <maric at aristote.info> wrote: > Le Thursday 04 September 2008 14:31:23 Michele Petrazzo, vous avez ?crit : >> Marco Bizzarri wrote: >> > looking at the source, maybe you could create a subclass of Set >> > redefining the __contains__ method? >> >> Made some tries, but __contains__ are never called >> > > No, __contains__ is only called with "in" operator, not for internal hashing. > Anyway this solution is bad, you'll need to compare the new element with all > the set contain, which would result in a O(n) algorithm for adding elements > to the set in place of the O(1) it use. > Thanks for the clarification, Maric; I take notices to watch source more closely next time (( hopefully, before writing a wrong answer )). Regards Marco > _____________ > > Maric Michaud > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From avhena at gmail.com Wed Sep 17 23:49:01 2008 From: avhena at gmail.com (avehna) Date: Wed, 17 Sep 2008 23:49:01 -0400 Subject: cgi-python temporary output Message-ID: <3166fcd60809172049m5838bcc6t2eb7523ca51a1571@mail.gmail.com> Hello: I would like to generate a temporary output in my cgi-python script where the user could see the actual program status while the program is still running behind the web, and know how long approximately it could take, and then finally display the final cgi-output. I have no idea how something like that could be done ("temporary output"). I will appreciate any suggestion from you. Thank you. M. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080917/6f4f16a3/attachment-0001.html> From steve at REMOVE-THIS-cybersource.com.au Mon Sep 1 19:47:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2008 23:47:03 GMT Subject: Py 2.6 changes References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> Message-ID: <00cc7976$0$20302$c3e8da3@news.astraweb.com> On Mon, 01 Sep 2008 12:15:53 -0700, bearophileHUGS wrote: > Now math has factorial: > http://docs.python.org/dev/library/math.html#math.factorial Seen how > reduce() is removed from Python 3 (I know it's in itertools), and seeing > that for me to write a productory() function was the first usage I have > had for reduce, years ago, I think the math module can gain a > productory() function too. productory() -- I don't know that function, and googling mostly comes up with retail product searches. Do you mean product(), the analog of sum() except that it multiplies instead of adds? Or perhaps you mean some sort of generalization of factorial(). -- Steven From a.schmolck at gmail.com Thu Sep 4 05:47:07 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Thu, 04 Sep 2008 10:47:07 +0100 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <yfs63pcwyip.fsf@gmail.com> <ba4e1851-c672-450d-90e3-98e290a60b2a@a2g2000prm.googlegroups.com> Message-ID: <yfsr680utt0.fsf@gmail.com> bearophileHUGS at lycos.com writes: > A problem is that '1234' in Python is a string, so using ' in numbers > looks a bit dangerous to me (and my editor will color those numbers as > alternated strings, I think). Yeah, editors, especially those with crummy syntax highlighting (like emacs) might get it wrong. This should be easy enough to fix though. Indeed unlike raw and tripplequoted strings which were adopted without major hitches this new syntax wouldn't have any bearing on what's a valid string. 'as From gminick at bzt.bzt Wed Sep 3 14:54:59 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 3 Sep 2008 18:54:59 +0000 (UTC) Subject: Looking for File comparison utility that produces actual differences References: <mailman.437.1220467253.3487.python-list@python.org> Message-ID: <g9mmi2$qo9$1@inews.gazeta.pl> On Wed, 3 Sep 2008 19:40:40 +0100, dudeja.rajat at gmail.com wrote: > I looking for a file comparison utility in Python that works like > 'diff' command in Unix and 'comp' in Windows. > The present 'cmd' in filecmp module only presents output in the form > of 1 or 0 i.e whether the 2 files differ or not? In python it's called difflib. Try to import it. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From theller at python.net Fri Sep 5 05:08:37 2008 From: theller at python.net (Thomas Heller) Date: Fri, 05 Sep 2008 11:08:37 +0200 Subject: ctypes error on Windows In-Reply-To: <mailman.538.1220597413.3487.python-list@python.org> References: <g9q3j9$np4$1@chessie.cirr.com> <g9qjuf$4pl$2@ger.gmane.org> <mailman.538.1220597413.3487.python-list@python.org> Message-ID: <6icb8jFq4jmsU1@mid.individual.net> Fredrik Lundh schrieb: > Fredrik Lundh wrote: > >>> I do have the tidy.dll installed (if I didn't, I couldn't even import >>> the tidy module). >> >> typing the following into the Python interpreter might give you some >> more clues: >> >> >>> import _tidy >> >>> _tidy.__file__ >> >>> dir(_tidy) > > or not, since ctypes is involved. > > have you checked for multiple copies of tidy.dll? > > if you have MSVC on your machine, try using "dumpbin /exports" on the > DLL to check that it really exports the symbols the binding expects. > Or use dependencywalker (google for it). Thomas From tino at wildenhain.de Wed Sep 10 09:40:42 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 10 Sep 2008 15:40:42 +0200 Subject: Web shopping carts In-Reply-To: <C4EDF5D9.11364%luke.hamilton@xenter.com.au> References: <C4EDF5D9.11364%luke.hamilton@xenter.com.au> Message-ID: <48C7CE5A.7030904@wildenhain.de> Hi, Luke Hamilton wrote: > Thanks... > > Do you happen to have anymore details? Yes well... you guess it was supposed to be a funny comment but would you happen to have anymore details on your requirements as well? Your simple question was just asking for making fun of it. (Other than that please see the answer given by Fredrik) Ah, btw, I'd check the the other posts of long term members if you see something in the appearance different to yours :-) (not related to your question itself) Cheers Tino ... >> Luke Hamilton wrote: >>> Hey People, >>> >>> I am wondering if there are any OS shopping cart application written in >>> python? >>> >> Yes there are. >> >> HTH >> Tino > > -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/5b28516c/attachment-0001.bin> From walter.php at gmail.com Thu Sep 11 21:35:04 2008 From: walter.php at gmail.com (Walter Cruz) Date: Thu, 11 Sep 2008 22:35:04 -0300 Subject: rss feed generation In-Reply-To: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> References: <mailman.754.1220995881.3487.python-list@python.org> <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> Message-ID: <32cabba0809111835g2984c463y2c4b689605f8362e@mail.gmail.com> On Tue, Sep 9, 2008 at 9:35 PM, alex23 <wuwei23 at gmail.com> wrote: > On Sep 10, 7:30 am, "Blake Garner" <trodemas... at gmail.com> wrote: >> I'm looking for suggestions on how to approach generating rss feed >> .xml files using python. What modules to people recommend I start >> with? pylons webhelpers makes a good work too. []'s - Walter From a at nospam.org Tue Sep 16 09:12:27 2008 From: a at nospam.org (Armin) Date: Tue, 16 Sep 2008 15:12:27 +0200 Subject: append on lists In-Reply-To: <mailman.1111.1221569309.3487.python-list@python.org> References: <gamffv$qms$1@online.de> <1221564169.16690.0@proxy00.news.clara.net> <gao7lg$ha3$1@online.de> <mailman.1111.1221569309.3487.python-list@python.org> Message-ID: <gaoahe$jis$1@online.de> Maric Michaud wrote: > Le Tuesday 16 September 2008 14:23:25 Armin, vous avez ?crit : >> Alex Marandon wrote: >>> Armin wrote: >>>> Duncan Booth wrote: >>>> >>>> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c >>>> (with c = [8,9]) is identical, >>> No it's not, + doesn't alter its operands. >>> >>> >>> a = 1 >>> >>> b = 2 >>> >>> a + b >>> >>> 3 >> That's not the point :) > > It is, please try to understand it, in python all expressions that mutate an > object should return None, it's the case for > > l.append(x) > l.sort() > l.reverse() > > all expressions that return something, return a new object, it's the case for > > 1+2 > 1.__add__(2) (which is the same) > sorted(l) > l[i:j] > etc... > > there are some noticeable exceptions : > > For coding facilities, some APIs could return the modified part of the object, > ex : it = c.pop() > > Returning the modifyied object itself is mostly considered bad style, because > it doesn't make clear if this the object or a copy. OK ... That's a good point. Thanks ! --Armin From apardon at forel.vub.ac.be Mon Sep 22 08:06:50 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 22 Sep 2008 12:06:50 GMT Subject: How to kill threading.Thread instance? References: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> <6jmn5kF42hreU1@mid.uni-berlin.de> <fcd4e76c-7d2a-4009-9548-b79e0ad14c44@59g2000hsb.googlegroups.com> <6jn4itF442e7U1@mid.uni-berlin.de> <mailman.1323.1222009536.3487.python-list@python.org> Message-ID: <slrngdf2j9.b8q.apardon@rcpc42.vub.ac.be> On 2008-09-21, Fredrik Lundh <fredrik at pythonware.com> wrote: > Diez B. Roggisch wrote: > >>> I wonder why something like myThread.exit() or myThread.quit() or >>> threading.kill(myThread) can't be implemented? >>> Is something like that present in Python 3000? >> >> Not that I'm aware of it (which doesn't mean to much though). >> >> However I *am* aware of the bazillions discussions that have been held >> over this here - and the short answer is: it is a generally very bad >> idea to terminate threads hard, as it can cause all kinds of corruption. > > the problem is that you have no idea what the thread is doing, so just > killing it dead it may make one big mess out of the application's > internal state; see e.g. this post > > http://mail.python.org/pipermail/python-list/2006-August/400256.html > > That's wise ;-) Stopping a thread asynchronously is in /general/ a > dangerous thing to do, and for obvious reasons. For example, perhaps > the victim thread is running in a library routine at the time the > asynch exception is raised, and getting forcibly ejected from the > normal control flow leaves a library-internal mutex locked forever. > Or perhaps a catch-all "finally:" clause in the library manages to > release the mutex, but leaves the internals in an inconsistent state. > > which links to a FAQ from Sun on this very topic: > > http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html > > (note that Java releases all mutexes when a thread is killed, but that's > not much better, as the FAQ explains) > > so as usual, the right thing to do is to do things in the right way. Why not let the programmer make the call whether killing the thread dead is the right thing or not. Maybe the programmer has a pretty good idea about what the thread can possibilbly be doing and knows that killing it won't produce a mess. Sure caution people to be very carefull when they are thinking about doing something like this. Just as people are generally adviced to use Queues when doing multithreading. But that is no reason to disallow certain kind of actions. -- Antoon Pardon From dblubaugh at belcan.com Mon Sep 29 16:43:23 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 16:43:23 -0400 Subject: Is Pyperl still active ?? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9148@AWMAIL04.belcan.com> To All, I was wondering if Pyperl is still active?? It appears as though it may very well be no longer active at this time!!! Is this correct?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From ahmad.humyn at gmail.com Fri Sep 5 06:57:37 2008 From: ahmad.humyn at gmail.com (Ahmad Humayun) Date: Fri, 5 Sep 2008 03:57:37 -0700 (PDT) Subject: atomic section in code References: <a475a219-1577-4018-a541-5b05c87f6f71@i76g2000hsf.googlegroups.com> <mailman.544.1220605512.3487.python-list@python.org> Message-ID: <c0632676-51ab-4cf6-a6a7-f2f089196d57@m45g2000hsb.googlegroups.com> On Sep 5, 1:59?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > Ahmad Humayun wrote: > > I need to create an atomic section in Python code i.e. there is no > > context switch to any other thread during the running of that piece of > > code. Would would do the trick? > > use a lock, and make sure that anyone that needs access to the shared > state you're manipulating in that section uses the same lock. > > ? ? ?lock = threading.Lock() # or RLock() etc [1] > > ? ? ?with lock: > ? ? ? ? ?section > > this only works if everyone honors the lock, of course; there's no way > in Python to lock out non-cooperating external threads. > > </F> > > 1) seehttp://effbot.org/zone/thread-synchronization.htm Thats true, but this will ensure mutual exclusion; not atomicity thanks again, From sslguru at gmail.com Tue Sep 16 04:54:29 2008 From: sslguru at gmail.com (SSLGuru) Date: Tue, 16 Sep 2008 01:54:29 -0700 (PDT) Subject: Secure Your Website with SSL Certificate Message-ID: <6ce4497e-aa17-41eb-9847-55239a7997f0@w1g2000prk.googlegroups.com> Hello Everyone, We are currently running special offer for WHT Forum Members. All VeriSign Certificates are priced at Special rates during our September Sale Offer. Please visit below link for more information: http://www.rapidsslonline.com/sept09offer.html Note: VeriSign Secured Seal is included in all offered VeriSign SSL Products. __________________ 4 Leading SSL Brands to choose from // Best Discounted Prices // 24X7 Live Chat & Email Support. http://www.rapidsslonline.com/ Largest SSL reseller worldwide From castironpi at gmail.com Fri Sep 26 23:21:32 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 20:21:32 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <dZOdnQINKORUEUDVnZ2dnUVZ_rvinZ2d@posted.usinternet> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> <87ej36uxl3.fsf@benfinney.id.au> Message-ID: <6fad912d-0ee3-4f60-add4-a28f3fe5b2c6@k7g2000hsd.googlegroups.com> On Sep 26, 9:33?pm, Ben Finney <bignose+hates-s... at benfinney.id.au> wrote: > George Sakkis <george.sak... at gmail.com> writes: > > On Sep 26, 9:30?pm, Grant Edwards <gra... at visi.com> wrote: > > > I read the group via NNTP, and I find that blocking all articles > > > posted from google.groups gets rid of all of the spam. > > > ... along with a far from trivial (I guess) percentage of non-spam, > > such as this post. > > As a Google user, you have (presumably) more clout with them than > those of us who are not. Please pressure your provider to reduce the > spam they output so the above drastic measure is not so attractive. > > Such pressure may be more effective if you *also* use an alternate > NNTP provider that isn't such a spam-haven. > > -- > ?\ ? ? ? ? ? ? ?I put contact lenses in my dog's eyes. They had little | > ? `\ ? pictures of cats on them. Then I took one out and he ran around | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?in circles.? ?Steven Wright | > Ben Finney I composed a thread to the end of voicing that sentiment. http://groups.google.com/group/Groups-Suggestions/browse_thread/thread/142ce723675bcad3# Feel free to follow this. For the record, I do find the fervor with which some netizens are denouncing Google somewhat provocative. I find them biased, more ardent than a classification heuristic with the same number of false negatives and false positives. That is, not purely objective in their advocacy. From google at mrabarnett.plus.com Fri Sep 5 10:28:12 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 5 Sep 2008 07:28:12 -0700 (PDT) Subject: Python and Cyrillic characters in regular expression References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> <mailman.497.1220550833.3487.python-list@python.org> <cb6b6ad1-1070-4b5c-8470-86815ce1beea@79g2000hsk.googlegroups.com> Message-ID: <87037566-9f99-4945-aa7f-afa57770f27d@m44g2000hsc.googlegroups.com> On Sep 5, 12:28?pm, phasma <xpa... at gmail.com> wrote: > string = u"??????" All the characters are letters. > (u'\u041f\u0440\u0438\u0432\u0435\u0442',) > > string = u"Hi.??????" The third character isn't a letter and isn't whitespace. > (u'Hi',) > > On Sep 4, 9:53?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > > > phasma wrote: > > > Hi, I'm trying extract all alphabetic characters from string. > > > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE) > > > buf = re.match(string) > > > > But it's doesn't work. If string starts from Cyrillic character, all > > > works fine. But if string starts from Latin character, match returns > > > only Latin characters. > > > can you provide a few sample strings that show this behaviour? > From siegfried at heintze.com Sat Sep 13 21:03:36 2008 From: siegfried at heintze.com (Siegfried Heintze) Date: Sat, 13 Sep 2008 18:03:36 -0700 Subject: How to emit Cyrillic and Chinese via unicode from console mode? Message-ID: <ieidnYDBwLZ3_1HVnZ2dnUVZ_tPinZ2d@comcast.com> Can someone point me to an example of a little program that emits non-ascii Unicode characters (Russian or Chinese perhaps)? The unicode Russian/Cyrillic alphabet starts at 0x410. Is this possible to do in a console mode program? If not, I guess I would want to use pywin32 to create a window and a message pump and display it there. I anticipate using pywin32 for some other function calls. Thanks! Siegfried From deets at nospam.web.de Thu Sep 25 16:56:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:56:59 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <mailman.1504.1222359750.3487.python-list@python.org> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> <Xns9B24589F2DBEOKB@199.45.49.11> <mailman.1504.1222359750.3487.python-list@python.org> Message-ID: <6k2c8rF5oenoU2@mid.uni-berlin.de> Stef Mientki schrieb: > OKB (not okblacke) wrote: >> Stef Mientki wrote: >> >>>>>> import Module1 >>>>>> >>>> d:\data_python_25\pylab_works\module1.py(3)<module>() >>>> >>> -> print "hello" >>> (Pdb) >>> >>> >>>> Then we know if PDB is really the culprit. >>>> >>>> >>> So pdb is the problem. >>> >> >> Yep, it does the same thing for me. >> >> >>>> Apart from that, is that really a problem that the filenames are >>>> all lower case? AFAIK Windows is case-insensitive regarding >>>> filenames anyway. So opening the file by just passing the filename >>>> should work seamless. >>> Yes windows is, >>> but Python is not. >>> My program should run on Windows and Linux (and maybe a few >>> others). By converting everything to lowercase, on Linux I can't >>> distinguishes between 2 files with the same name but a different >>> case (btw, giving 2 files the same name, only differing in case, >>> looks like a bad idea to me). >>> >> >> Hmmm, but I don't understand what you're doing here. Are you >> somehow storing the filename that pdb outputs and you need to use it >> later on a potentially different OS? If the case is preserved in pdb >> on linux, then presumably running it on linux will be fine, right? >> It's only a problem if you somehow try to use a filename created by >> windows- >> pdb to open a file (the same file, somehow) on linux. >> >> > 1. I've a multitab editor. > 2. When a breakpoint is reached, > 3. I check if the file specified in pdb output, is already open in one > of the editor tabs, > 4. if not, I open a new tab with the correct file, > 5. I focus the correct editor tab and jump to the line specified by pdb. > 6. After that I should be able to inspect the surrounding of the > breakpoint, so I need the modules name. > > For 3 I need to compare filenames, the editor contains the case > sensitive name, pdb not. > For 6 I also need the case sensitive filename, but probably there's > another way to get the modules name. > > For 3, I can indeed compare the lowercase version of both, > probably I'll do that for the moment. You can do that based on the OS - do it on windows (as it doesn't care. Actualy, OSX doesn't as well), don't do it on posix systems. Diez From castironpi at gmail.com Sat Sep 27 21:29:30 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 18:29:30 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> <48DCC786.2040407@wildenhain.de> <mailman.1551.1222447687.3487.python-list@python.org> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <mailman.1572.1222472905.3487.python-list@python.org> <f9b466b0-9945-42c1-ad9c-2f65c8d4b907@y38g2000hsy.googlegroups.com> <mailman.1574.1222477862.3487.python-list@python.org> <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> <mailman.1610.1222559749.3487.python-list@python.org> Message-ID: <9f263cc0-508a-4597-94fc-365f6b691d10@i76g2000hsf.googlegroups.com> On Sep 27, 6:55?pm, "Tim Rowe" <digi... at gmail.com> wrote: > 2008/9/27 Aaron Castironpi Brady <castiro... at gmail.com>: > > > No way. ?It's *zero* instead of one, if so, because the only thing C# > > has is a bunch of handcuffs and implicit 'self'. ?You have a line > > like: > > You don't follow what I said, and from your tone I get the feeling you > don't *want* to follow what I'm saying, not because I'm criticising > Python (I'm not), but because I'm guilty of the heresy of suggesting > that it's not actually simultaneoulsy optimised for every possible > use. > > My point is that there are zero parameters as far as I am concerned > because I don't actually touch most of the GUI code. ?There could > actually be hundreds of parameters, for all I care. They're not my > concern. Most of the time I like that -- the tools are doing my work > for me. > > -- > Tim Rowe flamewar.avert( ), please. Yes, I agree, I did not follow every word. It's a fundamental disagreement about successful ways to communicate, and, for the philosophers, successful communication, whether I should have nitpicked first thing, or tried to go along with the gist. I tried the latter. In your case, I guessed wrong. Sorry. Before I tried wxFormBuilder, I imagined that C# would be vastly faster to develop than Python, for anything requiring any non-trivial graphical interface. I've done extensive VB, so I can attest to that personally. It is not. The difference in dev times is about the time it takes to write: def onClick( event ): ... controlA.bind( wx.MOUSEDOWN, onClick ) perhaps several times, which, <glances at watch>, is not long. You do get the IDE, true, and that code is auto-crafted for you. But 'wx' does give you data in an XML file, instead of a script. And talk about a difference in identifiers: <form> <button> <pos>20,30</pos> <color>gray</color> </button> </form> vs. form.button.pos= 20, 30 form.button.color= gray You can come up with examples that favor either. But the opposite of statistical is anecdotal. Sorry again. The last time I 'checked in' at your post, your claim was "an hour or so" vs. "ages". Hence my responses. You could probably sneak by by claiming a factor of *two*, but if you were exaggerating, please say so at any time. Penultimately, forgive my sarcasm--- I'm a bit feisty right now. I was distinguishing between arguments in particular, and identifiers in general. And lastly, "simultaneoulsy optimised for every possible use" is a bold claim that I didn't make, at least, to come forward, in so many words. I do believe, and it shows, as of today, and you can quote me on this, that it's "pretty generally applicable", though I reserve the right to change my mind on the matter with or without notice. Especially if I learn something. I do not believe that C# is pretty generally applicable. I maintain that I will adjust that estimate if I ever get any facts about C#, since I don't have very many. (In fact, outside of my VB, COM, and MFC experience, you could say I have no clue. Very tongue in cheek.) In fact, do a Google for 'castironpi "every possible"'. You get a "can't ... every possible", and your post, and something else. That's it. Python has a lot of things C# doesn't. Can we agree on that? From lepto.python at gmail.com Sat Sep 6 08:52:21 2008 From: lepto.python at gmail.com (oyster) Date: Sat, 6 Sep 2008 20:52:21 +0800 Subject: embed python in ms-word? Message-ID: <6a4f17690809060552w6e518f1re4565a7e58e076b6@mail.gmail.com> in fact, during my work, I often write documnets in ms-word. But the doc has many numbers in it, which need to be calculated and to be modified frequently. Is there a method to write a ms-word add-in, so that 1.I can type in the calculation steps in some program language, please have a look at http://blender.bokee.com/inc/word_add_in1.jpg 2.then the result (here, it is 8) is shown in the doc when I close this window? please have a look at http://blender.bokee.com/inc/word_add_in2.jpg 3.when I double-click the result 8, I can view/edit the code again 4.the code for calculation is stored in DOC file too, I can change it later mathtype equation is a kind of such thing, but only for displaying nice equation I don't think vba is a good answer, the main reason is: the vba code has an incompact link with its result in the documnet From ironfroggy at gmail.com Sun Sep 21 19:39:08 2008 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sun, 21 Sep 2008 19:39:08 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> I call it an obvious misuse and misunderstanding of why you'd use a class in the first place. Either create an instance and not make these things classmethods or just share the stuff in a module-level set of variables. But the instantiating is the best options. Your class attributes might not be globals, but you're still using global state and you should avoid it where you can. On Sun, Sep 21, 2008 at 6:39 PM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://techblog.ironfroggy.com/ Follow me if you're into that sort of thing: http://www.twitter.com/ironfroggy -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080921/070a0ae9/attachment-0001.html> From lucafbb at gmail.com Mon Sep 1 04:43:25 2008 From: lucafbb at gmail.com (Luca) Date: Mon, 1 Sep 2008 10:43:25 +0200 Subject: Know if a object member is a method Message-ID: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Hi all. I think this is a newbie question... what is the best method to know if a property of an object is a function? I'm thinking something as if type(obj.methodName)==??? Can someone help me? -- -- luca From gherron at islandtraining.com Tue Sep 23 13:58:17 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 23 Sep 2008 10:58:17 -0700 Subject: Matrix programming In-Reply-To: <ea09b3700809231032h677f5b05k5a37397296a7e6e9@mail.gmail.com> References: <ea09b3700809231032h677f5b05k5a37397296a7e6e9@mail.gmail.com> Message-ID: <48D92E39.8000901@islandtraining.com> A. Joseph wrote: > > I need an ebook or tutorial that teach matrix programming. > Perhaps you should start here: http://www.catb.org/~esr/faqs/smart-questions.html#intro Gary Herron > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From gagsl-py2 at yahoo.com.ar Sun Sep 7 07:32:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 08:32:30 -0300 Subject: List of modules available for import inside Python? References: <e121e2c5-8ebd-4d42-835e-46b52e3c2053@t54g2000hsg.googlegroups.com> <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> <QABwk.25014$N87.11966@nlpi068.nbdc.sbc.com> Message-ID: <op.ug3zohifx6zn5v@a98gizw.cpe.telecentro.net.ar> En Sat, 06 Sep 2008 17:18:55 -0300, clurker <nospam at spamhaters.com> escribi?: > Michele Simionato wrote: > >> On Aug 28, 6:21?am, ssecorp <circularf... at gmail.com> wrote: >>> Is there a way to view all the modules I have available for import >>> from within Python? >>> Like writing in the interpreter: >> >> Try: >> >>>>> help() >> help> modules >> Please wait a moment while I gather a list of all available modules... >> <snip> > > This looks like it could be a useful tool, but when I try it > I get the following: > > Please wait a moment while I gather a list of all available modules... [...] > File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 1342, > in <module> > > File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 927, > in main > > UnboundLocalError: local variable 'given_files' referenced before assignment >>>> Unfortunately the "modules" help command actually imports all the available packages, and a buggy one may stop the whole process with an error. > Apparently python knows about them both, but I don't know I > haven't introduced an incompatibility somewhere...and that PIL > package showing up at the tail of the errors was one of my > more recent additions... If import of a package fails, the error reported is not accurate. In this case, probably some other package failed, that itself imported PIL. Line 927 in PIL/__init__.py does not exist. A quick fix is to replace line 1854 in pydoc.py (ModuleScanner.run) with this one: for importer, modname, ispkg in pkgutil.walk_packages(onerror=lambda name:None): (the onerror argument makes it to ignore all errors) -- Gabriel Genellina From bthayre at physics.ucsd.edu Mon Sep 22 18:59:36 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 22 Sep 2008 15:59:36 -0700 (PDT) Subject: Python based barcode readers References: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> Message-ID: <b9114982-4dce-4a65-ad28-891ed79fa5d4@b2g2000prf.googlegroups.com> I also forgot to mention that it need not be nearly as robust as something like Jailhelper 2.0, I will not really need to compensate for noise and irregular conditions. All of my barcodes will be scanned in a predictable, and consistent environment (i.e. a scanner), so all i need is some stupid little script that will read the an image in and decode it. From ppearson at nowhere.invalid Tue Sep 2 12:02:33 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 2 Sep 2008 16:02:33 GMT Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <pan.2008.09.02.06.10.51@REMOVE.THIS.cybersource.com.au> Message-ID: <6i56cpFor2puU1@mid.individual.net> On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote: > At the risk of bike-shedding, [snip] (startled noises) It is a delight to find a reference to that half-century-old essay (High Finance) by the wonderful C. Northcote Parkinson, but how many readers will catch the allusion? -- To email me, substitute nowhere->spamcop, invalid->net. From semanticist at gmail.com Wed Sep 3 00:20:18 2008 From: semanticist at gmail.com (Miles) Date: Wed, 3 Sep 2008 00:20:18 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <20080902235412.GT29228@dragontoe.org> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> <mailman.390.1220393719.3487.python-list@python.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> Message-ID: <a49e45f50809022120l648f6d94i86ac446b7ae8df69@mail.gmail.com> Derek Martin wrote: > On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: >> but the instances of `Popen` are no actions. There's no way to >> "execute" a `Popen` instance. > > Yes there is... you execute it when you instantiate the object. At > the time of instantiation, you "open" the "P" (pipes). The subprocess module is also supposed to replace os.system and os.spawn*, neither of which involve opening pipes. (I use it for that functionality just as often, if not more so, as for piped subprocess communication). All rationalizations aside, I think Popen is a poor name for the class. But I would imagine the odds of it ever being changed are miniscule (Python 4?). -Miles From edward.fisher at st.com Wed Sep 3 04:29:39 2008 From: edward.fisher at st.com (Edward FISHER) Date: Wed, 3 Sep 2008 08:29:39 +0000 (GMT) Subject: Problems with running Python CGI Scripts Message-ID: <20080903082939.CKJ85501@mail1.edb.st.com> Hey guys. Im having problems running a python cgi. Im using the example code from: http://www.python.org/doc/essays/pp...east/sld041.htm as writen by Van Rossum himself I can get the script to run the python script but all that happens is that the black python box appears then disapears, the html that the python scripts should generate is never output. My html is: <html><head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>A Typical HTML form

A Typical HTML form

*Test CGI script and HTML to test server for correct running of python cgi scripting

Your First Name:

Your Last Name:

Click here to submit form:

This is calling the pyc file of the python script. I dont understand why if i call the py file itself all i get returned is the plain text of the python file. The python script is: #!/usr/local/bin/python import cgi def main(): print "Content-type: text/html\n" form = cgi.FieldStorage() if form.has_key("firstname") and form["firstname"].value != "": #if form has an object called firstname and the value is not an empty string print "

Hello", form["firstname"].value, "

" else: print "

Error! Please enter first name.

" main() If you need to see what happens then follow this link: http://www.fisherphotographics.co.uk/testhtml1.htm The python file has come directly from the example so i must me doing something wrong. I have all the correct permissions etc Thanks very much Ed Fisher From gogtesuyash at gmail.com Wed Sep 17 23:56:02 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 20:56:02 -0700 (PDT) Subject: Problem occured while sending mail References: <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> <6jckjhF2llrvU1@mid.individual.net> Message-ID: On Sep 17, 8:04 pm, Peter Pearson wrote: > On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui wrote: > > On Sep 17, 5:04 pm, sui wrote: > >> this is my code > > >> import sys, os, glob, datetime, time > >> import smtplib > >> ## Parameters for SMTP session > >> port=587 > >> SMTPserver= 'smtp.gmail.com' > >> SMTPuser= '... at gmail.com' > >> pw= 'fill in here' > >> SENDER= SMTPuser > > >> ## Message details > >> FROM= SENDER > >> TO= 'notgm... at a.com' > >> CC=FROM > >> ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC > >> RECEIVERS= (TO,) ## ignore the CC address > > >> subject= 'Test 1a' > >> message='*** Email test *** ' > > >> print 'Starting SMTP mail session on %s as %s ' % > >> (SMTPserver,SMTPuser) > >> session = smtplib.SMTP(SMTPserver,port) > >> session.set_debuglevel(0) # set debug level to 1 to see details > >> session.ehlo(SMTPuser) # say hello > >> session.starttls() # TLS needed > >> session.ehlo(SMTPuser) # say hello again, not sure why > >> session.login(SMTPuser, pw) > > >> ##Create HEADER + MESSAGE > >> HEADER= 'From: %s\r\n' % FROM > >> HEADER= HEADER + 'To: %s\r\n' % TO > >> HEADER= HEADER + 'Cc: %s\r\n' % CC > >> HEADER= HEADER + 'Subject: %s\r\n' % subject > >> BODY= HEADER + '\r\n' + message > >> print BODY > > >> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email > > >> session.close() > > >> Now when i run this .py file...as python mail.py > >> i can see only statement > >> starting smtp mail......n details > >> then nothing on screen after few minutes or after pressing ctrl +c > >> Traceback (most recent call last): > >> File "mail4.py", line 21, in > >> session = smtplib.SMTP(SMTPserver,port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > >> (code, msg) = self.connect(host, port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > >> self.sock.connect(sa) > >> File "", line 1, in connect > >> or may be conncetion time out > > >> wats the solution for this > > > if i dont press cntrl + c then it shows > > Starting SMTP mail session on smtp.gmail.com as gogtesuy... at gmail.com > > Traceback (most recent call last): > > File "mail4.py", line 21, in > > session = smtplib.SMTP(SMTPserver,port) > > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > > (code, msg) = self.connect(host, port) > > File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect > > raise socket.error, msg > > socket.error: (110, 'Connection timed out') > > > plz help me its urgent.....i want to complete it as early as possible > > I pasted your code into a file named temp.py, > and (perhaps superstitiously) added a backslash to this line: > > >> print 'Starting SMTP mail session on %s as %s ' % > > Here's what it does (long line wrapped manually): > > peter at eleodes:~$ python temp.py > Starting SMTP mail session on smtp.gmail.com as .... at gmail.com > Traceback (most recent call last): > File "temp.py", line 27, in ? > session.login(SMTPuser, pw) > File "/usr/lib/python2.4/smtplib.py", line 591, in login > raise SMTPAuthenticationError(code, resp) > smtplib.SMTPAuthenticationError: (535, \ > '5.7.1 Username and Password not accepted. Learn more at\n' \ > '5.7.1http://mail.google.com/support/bin/answer.py?answer='\ > '14257 a8sm34686663poa.12') > peter at eleodes:~$ > > This indicates that it got much farther than when you ran it, since > your timeout message comes from the smtplib.SMTP call several lines > before the session.login call. > > As a simple connectivity test, you might see whether you can connect > using telnet: > > peter at eleodes:~$ telnet smtp.gmail.com 587 > Trying 72.14.253.109... > Connected to gmail-smtp.l.google.com. > Escape character is '^]'. > 220 mx.google.com ESMTP m27sm34789033pof.6 > ^]c > > telnet> c > Connection closed. > peter at eleodes:~$ > > -- > To email me, substitute nowhere->spamcop, invalid->net. Actually i m working at place where proxy server has been working......so is it problem caused by that proxy server..peter thnks for suggestion but still its not working...... From user at domain.invalid Wed Sep 17 13:34:31 2008 From: user at domain.invalid (Canned) Date: Wed, 17 Sep 2008 19:34:31 +0200 Subject: translating ascii to binary In-Reply-To: <00e12f1f$0$20331$c3e8da3@news.astraweb.com> References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> <00e12f1f$0$20331$c3e8da3@news.astraweb.com> Message-ID: <48d13fa2$0$27103$9a622dc7@news.kpnplanet.nl> Steven D'Aprano schreef: > Your "ascii_to_bin" method tries to do too much in one method. You should > split the functionality into small, self-contained pieces, then combine > them. And frankly, once you got to the part where you started popping and > inserting, my brain melted. You are making an easy job too hard! *smiles* > It's a bad habit, I can't help it. From now on, I'll follow your advice to split the functionality into small, self-contained pieces. That popping and inserting is just a workaround for another workaround. > Try this instead: > > class Converterab: > ''' > Ascii-binary converter. > ''' > def __init__(self, string): > self.string = string > def bin(self, n): > """Return the binary representation of a positive integer n.""" > bindump = [] > while n > 0: > bindump.append(str(n & 1)) > n = n >> 1 > bindump.reverse() > if bindump: > return ''.join(bindump) > else: > return '0' > def char_to_bin(self, c): > """Return the binary representation of a character c.""" > bits = self.bin(ord(c)) > zeroes = "0" * (8-len(bits)) > return zeroes+bits > def ascii_to_bin(self): > results = [] > for c in self.string: > results.append(self.char_to_bin(c)) > return ''.join(results) > I've spend 3 days to find out what did I do wrong, but you did it in just half an hour/more. You're my hero. From wuwei23 at gmail.com Sat Sep 27 22:04:39 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 27 Sep 2008 19:04:39 -0700 (PDT) Subject: Docstrings for attributes? References: Message-ID: On Sep 28, 11:50?am, Roy Smith wrote: > Is there any way to attach a docstring to an attribute? ?I see that PEP-257 > talks about attribute docstrings, but it references PDP-258, which was > rejected. > > I suppose I could eschew plain attributes in favor of getter functions, > because those give me a place to hang a docstring, but that feels like the > wrong thing to do. There were a couple of solutions provided - including the use of properties - when this question came up earlier this week: http://groups.google.com/group/comp.lang.python/browse_frm/thread/18a8c3f09ac02f85# From Astley.lejasper at gmail.com Fri Sep 12 06:08:33 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Fri, 12 Sep 2008 03:08:33 -0700 (PDT) Subject: Good programming style Message-ID: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> I'm still learning python and would like to know what's a good way of organizing code. I am writing some scripts to scrape a number of different website that hold similar information and then collating it all together. Obviously each site needs to be handled differently, but once the information is collected then more generic functions can be used. Is it best to have it all in one script or split it into per site scripts that can then be called by a manager script? If everything is in one script would you have per site functions to extract the data or generic function that contain vary slightly depending on the site, for example import firstSiteScript import secondSiteScript firstsitedata = firstSiteScript.getData('search_str) secondsitedata = secondSiteScript.getData('search_str) etc etc OR def getFirstSiteData(search_str): etc etc def getSecondSiteData(search_str): etc etc OR def getdata(search_str, website): if website == 'firstsite': .... elif website =='secondsite': etc From benjaminlindelof at yahoo.com Wed Sep 3 12:52:06 2008 From: benjaminlindelof at yahoo.com (ToPostMustJoinGroup22) Date: Wed, 3 Sep 2008 09:52:06 -0700 (PDT) Subject: Coming from .NET and VB and C Message-ID: I'm coming from a .NET, VB, C background. C was good, and VB was better (with all of its libraries). Than .NET came along and all the libraries you can require are ready to go. I have no preference with MySQL or SQL, stored procedures or ad-hoc queries. SO, I'm interested in using my Google App space (free 500MB) to develop a quick database application. Using Python. I found "Dive Into Python" which I will be reading shortly. Any suggestions for someone new to the scene like me? From a_jtim at bellsouth.net Thu Sep 25 07:53:40 2008 From: a_jtim at bellsouth.net (Tim Arnold) Date: Thu, 25 Sep 2008 04:53:40 -0700 (PDT) Subject: multiple processes with private working dirs References: <473d008f-f3c4-4894-9251-b7fc9cf4c8e4@p10g2000prf.googlegroups.com> Message-ID: On Sep 25, 12:11?am, alex23 wrote: > On Sep 25, 3:37?am, "Tim Arnold" wrote: > > > Am I missing something? > > Do you mean something other than the replies you got the last time you > asked the exact same question? > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/42c... arggg. My newreader didn't show the initial post so I thought it never made it through. sorry for the noise. --Tim Arnold From steve at REMOVE-THIS-cybersource.com.au Mon Sep 8 08:51:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Sep 2008 12:51:04 GMT Subject: Where does the command "ls" in some doctest files come from ? References: Message-ID: <00d51a07$0$20306$c3e8da3@news.astraweb.com> On Mon, 08 Sep 2008 12:15:15 +0000, KLEIN St?phane wrote: > Hi, > > for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/ > tests.py?rev=89831&view=auto test file, there is this doctests : [snip] > >>> ls('develop-eggs') > I wonder where does the "ls('develop-eggs')" command come from ? > > It is doctest buildin command ? Easy to find out: import doctest and see for yourself: >>> import doctest >>> doctest.ls Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'ls' You found the ls() function in a docstring from Zope. The doctest seems to be testing ls(). That suggests to me that ls() is defined in Zope, not doctest. Why do you ask? -- Steven From carsten.haese at gmail.com Fri Sep 12 09:30:19 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Fri, 12 Sep 2008 09:30:19 -0400 Subject: Injecting new names into the above frame In-Reply-To: References: Message-ID: <57uyk.101$fD.22@flpi145.ffdc.sbc.com> Peter Waller wrote: > Dear Pythoners, > > I know this will probably be perceived as 'evil voodoo', and fair > enough: it probably is. I guess it is unpythonic. > > .. but I want to know how to do it anyway - mostly for my own > interest. Well, if you're really just asking out of curiosity, it should be sufficient to tell you that this is not possible. > [...] we have to add this > snippet before the Get() function returns: > > from ctypes import pythonapi, py_object, c_int > pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 ) > > This copies back the names into the code object, and works fine.. that > is, if the names already exist within the code object. > > def MyFunction(): > a = None > Get("a") > print a # Works > Get("b") > print b # Name error, b is undefined The answer to why this doesn't work lies in the disassembly of that function: 0 LOAD_CONST 0 (0) 3 STORE_FAST 0 (0) 6 LOAD_GLOBAL 1 (1) 9 LOAD_CONST 1 (1) 12 CALL_FUNCTION 1 15 POP_TOP 16 LOAD_FAST 0 (0) <- This is a 19 PRINT_ITEM 20 PRINT_NEWLINE 21 LOAD_GLOBAL 1 (1) 24 LOAD_CONST 2 (2) 27 CALL_FUNCTION 1 30 POP_TOP 31 LOAD_GLOBAL 2 (2) <- This is b 34 PRINT_ITEM 35 PRINT_NEWLINE 36 LOAD_CONST 0 (0) 39 RETURN_VALUE Since you have an assignment to the name a, a is recognized as a local name at compile time. b is not recognized as a local name at compile time, so even if you inject a value for b into the locals dictionary, the byte code still looks up the value as a global name. > Is there any way for Get() to define a new variable within > MyFunction's code object? Or is there any programmatic way to, at > runtime, insert new names into functions? Not without making fundamental changes to Python itself. The fact that this isn't possible is a feature, in my opinion. I like the fact that I can call a function and be *absolutely certain* that it's not going to pollute my local namespace. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From mbrkic at invalid_mail.adress Wed Sep 24 14:03:54 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Wed, 24 Sep 2008 20:03:54 +0200 Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: On Wed, 24 Sep 2008 07:32:56 -0700 (PDT), mdsherry at gmail.com wrote: >If you don't create a monolithic EXE, then most of the extra files >(that make up the bulk of the size) can be shared between other >converted scripts. That is, if you convert foo.py, and send the bundle >to your colleague, then convert bar.py, you only need to send bar.exe, >and it will run fine if they execute it in the same directory that has >all the DLLs you sent with foo.exe. > >Another option might be to encourage them to download Portable Python, >which doesn't need to be installed. This is an interesting suggestion. I didn't know there was a portable version of python. I will look into it - could just turn out to be the perfect solution to this (after all, it would be even simpler if they could send/receive just .py script). Thank you. -- Marin > >Mark Sherry From almar.klein at gmail.com Fri Sep 12 03:23:23 2008 From: almar.klein at gmail.com (Almar Klein) Date: Fri, 12 Sep 2008 09:23:23 +0200 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: References: <943393.38616.qm@web95111.mail.in2.yahoo.com> Message-ID: > > I find it impossible to take anyone asking others to do their school > work for them seriously no matter how or what they are willing to pay. > Exactly, and writing the subject of the post in all capitals doesn't help either... Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From mathieu.malaterre at gmail.com Mon Sep 8 05:39:27 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Mon, 8 Sep 2008 02:39:27 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> Message-ID: <4910a424-7c4e-48c8-8d56-b388796c70b8@f36g2000hsa.googlegroups.com> On Sep 8, 9:32 am, Bruno Desthuilliers wrote: > mathieu a ?crit : > > > Hi there, > > > I am trying to write something very simple to test if a list > > contains another one: > > > a = [1,2,3] > > > b = [3,2,1,4] > > > but 'a in b' returns False. > > Indeed. Lists are not sets, and the fact that all elements of list a > happens to also be part of list b doesn't make the list a itself an > element of list b. > > >>> a = [1, 2, 3] > >>> b = [3,2,1,4] > >>> c = [b, a] > >>> a in c > True > >>> b in c > True > >>> c > [[3, 2, 1, 4], [1, 2, 3]] > >>> > > > How do I check that a is indeed contained > > in b ? > > But that's what you did - you *did* checked if a was contained in b, and > this is not the case. What you want is to check if *all elements* of a > are contained in b, which is quite another problem. Now the answer to > your question : use sets. > > >>> set(a).issubset(set(b)) > True > >>> thanks all ! From mail at johnlawrence.net Thu Sep 11 05:28:15 2008 From: mail at johnlawrence.net (John Lawrence) Date: Thu, 11 Sep 2008 10:28:15 +0100 Subject: Adding environment variables to bash. In-Reply-To: References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> Message-ID: <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> > > when a process starts, it gets a *copy* of the parent's environment. it > can modify that copy, but it cannot modify the variables in the parent. You can make a command use the current shell though if you use the '.' command e.g.: jl > cat env.sh export TEST='hello' jl > ./env.sh && env | grep TEST #Doesn't set TEST in parent shell jl > . ./env.sh && env | grep TEST #Adding '. ' before the command uses the same shell TEST=hello John. -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Tue Sep 16 09:14:38 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 15:14:38 +0200 Subject: MVC with Python In-Reply-To: <3f0d61c40809160547t339226acx19a7a0a0f58a6e73@mail.gmail.com> References: <3f0d61c40809160547t339226acx19a7a0a0f58a6e73@mail.gmail.com> Message-ID: <200809161514.39385.maric@aristote.info> Le Tuesday 16 September 2008 14:47:02 Marco Bizzarri, vous avez ?crit?: > On Tue, Sep 16, 2008 at 1:26 PM, Georg Altmann wrote: > > Marco Bizzarri schrieb: > >> On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann > >> > >> wrote: > >>> Hello, > >>> > >>> I need some advice on how to implement model-view-controller. I am > >>> trying to > >>> develop a GUI application with PyQt, yet the problem rather applies to > >>> mvc > >>> in general, not just GUI applications. > >>> > >>> Let's say the data is a list of objects with a common base class. The > >>> views > >>> are either a graphical representation of the objects or some form of > >>> textual > >>> input. The views shall change the model by using command objects (for > >>> undo, > >>> e.g. QUndoCommand). > >>> > >>> My current approach is to implement the model as a class with a > >>> list-like interface, with methods insert(), remove(), __getitem__(), > >>> __setitem__(),... > >>> and a signal to notify the views. The objects in the list have methods > >>> to change their state as well. > >>> > >>> My problem is, how do the commands interact with the model? > >>> Let's say I have a command that modifies an object o in the list. > >>> > >>> 1) If list[key_to_o] returns a reference to the object, the command can > >>> modify the object by using this reference, i.e. list[key_to_o].setX(). > >>> So there is no way for the list to know when the object changed - how > >>> can it emit a singal then? > >>> > >>> 2) If list[key_to_o] returns a deep copy of the object, > >>> copy_of_o = list[key_to_o], the command mofifies the copy and the > >>> updates the list: list[key_to_o] = copy_of_o. Now the list can emit a > >>> signal in __setitem__(). > >>> While this may work, it seems awkward to copy around objects just to > >>> perform > >>> a possibly simple operation on them. Additionally it might not be > >>> feasible > >>> once objects get complex. > >>> > >>> 3) The interface of the classes of the objects could be reflected in > >>> the list class, i.e. list.set_x_on_obj(key_to_obj,x). This would > >>> probably make > >>> the list class interface very bloated. > >>> > >>> Of course the problem is not really limited to Python, my apologies if > >>> I'm > >>> totally off-topic here. > >>> > >>> Regards > >>> Georg > >> > >> Well, I think one of the assumptions of the MVC is that the view can > >> be notified about the changes in the model. According to your > >> interface, the View can just be notified on operations about the > >> *whole* model, like adding or removing elements from it. > >> > >> But the elements of your list-like class should be a part of your > >> model, and therefore should be able to notify the Views by > >> themselfves. > > > > Ok, consider this: say the model needs to compute some sort of value by > > iterating over all objects in the list (for example some sort of hash). > > Some kind of view then displays this value. > > I could implement this by connecting a signal in each object to a slot in > > the list class which in turn emits a signal which is connected to the > > view. > > > > But this implies all the objects in the list have to be instances of > > QObject. I wonder if this is isn't a weird design, because for example > > all value type classes in Qt don't derive from QObject, e.g. QString. My > > list objects are not that simple (in terms of the data structure). So is > > it ok to make them QObjects? > > Did you take a look at this? > > http://www.potu.com/man/doc.trolltech.com/4.0/model-view-programming.html > > It seems to imply that you should use QtAbstractItemModel as a base > class for all your models. But since I'm not an expert about Qt, I > cannot really say. > > Regards > Marco > > > Regards > > Georg > > > > -- > > http://mail.python.org/mailman/listinfo/python-list It is not about QT, it is about MVC. In MVC, code which implement the model should be completely ignorant of the libraries used for gui, and the gui part of the application shouldn't acces directly to your model logic. This why there is a third layer which abstract the logic of your datas and provide standard operation for the gui code. This third layer (Controllers), should be as few as possible coupled to the specificities of the gui library (but must be). The quoted papers explain rather well how to do this with QT (apart they call controllers "delegates"). For medium to big project, don't be afraid to divide your program in three packages, one for the model, in which you must not have any reference to QT API of some sort, one for the controllers, where you provide events and methods to manipulate your model, one for gui, where you just build windows, subscribe to controller's events and use their functions as callbacks for your widgets. -- _____________ Maric Michaud From sumitava.mukh at gmail.com Tue Sep 9 07:17:27 2008 From: sumitava.mukh at gmail.com (Sumitava Mukherjee) Date: Tue, 9 Sep 2008 04:17:27 -0700 (PDT) Subject: Python Installation and Running on Windows Vista References: <4f66ca7b-b495-4b12-bb4c-29b096eb53c9@j22g2000hsf.googlegroups.com> Message-ID: On Sep 9, 3:46?pm, Mchizi_Crazy wrote: > Please help with issue... I heard of compatimbiltity issues and would > like clarification. The win32 installer available from python.org works absolutely fine with Vista. So, go ahead and try it out. It works for all of my friends and myself From steve at holdenweb.com Fri Sep 12 08:36:37 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 08:36:37 -0400 Subject: String to hexadecimal conversion In-Reply-To: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Message-ID: Praveena P wrote: > Hi folks, > > I am new to Python... so am not too sure about how the type conversion > works. > > I have to read a file that contains hexadecimal data and use the data > further to do some arithmetic calculations. > A sample of the input is : 00000000000020E0000032F800000000400022005E > The problem I am facing is this: > I am using f.read(2) to read a byte at a time, but the data that is > read is a string rather than a number. So it kind of hampers any > arithmetic operations I perform on this data... > > Could you please suggest some method I could use for this? Generally speaking, reading a file 2 bytes at a time i going to be inefficient and untidy. Does this help? >>> int("00000000000020E0000032F800000000400022005E", 16) 170696759285949896156423472451551326L >>> Or have I misunderstood your intention? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From maric at aristote.info Thu Sep 4 09:07:34 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 4 Sep 2008 15:07:34 +0200 Subject: overwrite set behavior In-Reply-To: References: Message-ID: <200809041507.35366.maric@aristote.info> Le Thursday 04 September 2008 14:31:23 Michele Petrazzo, vous avez ?crit?: > Marco Bizzarri wrote: > > looking at the source, maybe you could create a subclass of Set > > redefining the __contains__ method? > > Made some tries, but __contains__ are never called > No, __contains__ is only called with "in" operator, not for internal hashing. Anyway this solution is bad, you'll need to compare the new element with all the set contain, which would result in a O(n) algorithm for adding elements to the set in place of the O(1) it use. The right way to go is one like Diez show you in a previous post. > ?>>> class foo(set): > ... ?def __contains__(self, value): > ... ? print value > ... > ?>>> a = foo((1,2)) > ?>>> -- _____________ Maric Michaud From dmitry at athabascau.ca Thu Sep 25 11:47:51 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 15:47:51 GMT Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> Message-ID: Thanks Bruno, your comments were really helpful (so was the "improved" version of code). My replies below: Bruno Desthuilliers wrote: >> So decorators inside of B just identify that those methods will be >> proxied by A. On one hand from logical standpoint it's kind of weird to >> tell class that it is going to be proxied by another class, > > Indeed - usually, proxied objects shouldn't have to be aware of the > fact. That doesn't mean your variation on the proxy pattern is > necessarily bad design (hard to tell without lot of context anyway...), > but still there's some alarm bell ringing here IMHO - IOW : possibly the > right thing to do, but needs to be double-checked. I'm kind of looking at options and not dead-set on decorators, but I can't find any other "elegant enough" solution which wouldn't lead to such tight coupling. The problem I'm trying to solve is not much more complicated than what I have already described so if anybody can suggest a better approach - I'm all for it. > Now I'm not sure I really like your implementation. Here's a possible > rewrite using a custom descriptor: yeah, that was going to be my next step - I was just aiming for proof-of-concept more then efficient code :) > class Proxymaker(object): > def __init__(self, attrname): > self.attrname = attrname > > def __get__(self, instance, cls): > def _proxied(fn): > fn_name = fn.__name__ > def delegate(inst, *args, **kw): > target = getattr(inst, self.attrname) > #return fn(target, *args,**kw) > method = getattr(target, fn_name) > return method(*args, **kw) > > delegate.__name__ = "%s_%s_delegate" % \ > (self.attrname, fn_name) > > setattr(cls, fn_name, delegate) > return fn > > return _proxied > > class A(object): > def __init__(self,b): > self.val='aval' > self.b=b > b.val='aval' > > proxy2b = Proxymaker('b') > > def mymethod(self,a): > print "A::mymethod, ",a > > def mymethod2(self,a): > print "A::another method, ",a > > class B(object): > def __init__(self): > self.val='bval' > > @A.proxy2b > def bmethod(self,a): > print "B::bmethod" > print a, self.val > > @A.proxy2b > def bmethod2(self,a): > print "B::bmethod2" > print a, self.val > My point is that: > 1/ you shouldn't have to rewrite a decorator function - with basically > the same code - for each possible proxy class / attribute name pair combo > 2/ making the decorator an attribute of the proxy class makes > dependencies clearer (well, IMHO at least). agreed on all points > I'm still a bit uneasy wrt/ high coupling between A and B, and if I was > to end up with such a design, I'd probably take some times to be sure > it's really ok. that is the question that troubles me at this point - thus my original post (read the subject line ;) ). I like the clarity decorators bring to the code and the fact that it's a solution pretty much "out-of-the-box" without need to create something really-really custom, but I'm worried about tight coupling and somewhat backward logic that they would introduce (the way I envisioned them). From FettManChu at gmail.com Tue Sep 16 23:57:48 2008 From: FettManChu at gmail.com (Fett) Date: Tue, 16 Sep 2008 20:57:48 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> <2cbfdce2-9203-4136-a274-bc7d19dc293a@y38g2000hsy.googlegroups.com> Message-ID: <3d9ab5e0-924b-48c1-b91b-2db1ca91e14c@26g2000hsk.googlegroups.com> On Sep 16, 9:44 pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 16, 9:25 pm, Fett wrote: > > > > > On Sep 16, 9:00 pm, "Aaron \"Castironpi\" Brady" > > > wrote: > > > On Sep 16, 8:50 pm, Fett wrote: > > > > > I am trying to find a wrapper to do linear programming within python. > > > > I am using an ubuntu machine and I have apt-get'd lp_solve, which > > > > works just fine. If someone knows of a wrapper that will work with > > > > that that'd be great. > > > > > I also heard that scipy has a wrapper, however, I can't find any > > > > documentation on it, nor can I seem to find it with dir(). If anyone > > > > knows where there is good documentation on this I would love to use > > > > that (the more native to python the better imo). > > > > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > > > > openopt, and cvxopt. I can't seem to find any with enough > > > > documentation to get me off the ground. Some I can't compile, some I > > > > can't even find out how to compile. > > > > > If anyone knows of an LP package (preferably with IP as well, like > > > > lp_solve has), that interfaces well with python and has enough > > > > documentation to get a dependency newb like myself off the ground that > > > > would be great. > > > > Google says: > > > > about 254,000 for linear programming python. > > > > Link 3 is: > > > >http://wiki.python.org/moin/NumericAndScientific/Libraries > > > > Scroll down. > > > Yes, many of those seem to be deprecated, without destinations to > > links, most are poorly or not documented at all. The few that are, I > > still can't get running. Of those 254, I think I have tried at least > > 10 pages worth. Still no luck. > > > # lpsolvpy - Can't get it to compile - dependency problems. > > # Lp_solve5 - NO python binding yet. Volunteers needed for python > > bindings. > > # pycplex - You need to compile the CPX.so module. Change the required > > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > > sure what to do here. > > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > > I missed the second link to the python bindings, looked all over the > > glpk site for anything about python. > > # SciPy --http://www.scipy.org-supposedly has this, but as I said, > > I can't find any mention of it anywhere but on the site you linked. > > # pySimplex - (broken link)(broken link) > > # Simplex - link is broken, but nothing is mentioned > > > I'll take a closer look at glpk's python bindings and if there is any > > documentation on them, maybe I'll have some luck. btw, I have been > > looking for something that works, I have over 5 packages on my desktop > > that I have tried to get up and running, but none of them seem to > > work. glpk makes 6. > > If you can find one working in C, use ctypes to link into Python. We > can help you with that part. It lets you pass primitive types, > structs, arrays, pointers, to C modules and return values. You need > to know the C signatures to set up the Pythonized signatures. Ok, it seems that I have found one (although without an integer programming component): upon searching for glpk in the package manager in ubuntu I found a package called cvxopt, it is a bit clunky (compared to the niceness of lp_solve), but I think I can figure this one out. Thanks all who answered. From beema.shafreen at gmail.com Thu Sep 11 09:47:25 2008 From: beema.shafreen at gmail.com (Beema Shafreen) Date: Thu, 11 Sep 2008 19:17:25 +0530 Subject: function return In-Reply-To: References: Message-ID: thanks for your valuable comments. I could solve the problem wiht your comments On Thu, Sep 11, 2008 at 7:07 PM, Fredrik Lundh wrote: > make that: > > note that you put the "return" statement inside the loop, so returning >> only one line is the expected behaviour. >> > > to fix this, you can append the result strings to the data_lis list inside > the loop: > > result = "%s\t%s\t%s" %(id,gene_symbol,ptms) >> data_lis.append(result) >> >> and then return the list when done: >> >> > fh.close() >> return data_lis >> >> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From giltay at gmail.com Thu Sep 18 13:26:49 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Thu, 18 Sep 2008 10:26:49 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <30fab72b-2d7f-497d-a687-1d697633db9c@z66g2000hsc.googlegroups.com> Message-ID: <4320a4f2-48b9-42c4-b51e-ef469ac6c79c@8g2000hse.googlegroups.com> On Sep 18, 11:18?am, prueba... at latinmail.com wrote: > dup=set() > SN=[] > for item in IN: > ? ?c=item.coordinates[0], item.coordinates[1] > ? ?if c in dup: > ? ? ? SN.append(item.label) > ? ?else: > ? ? ? dup.add(c) +1 for O(N) If item.coordinates is just an (x, y) pair, you can skip building c and save a little memory: seen_coords = set() for node in IN: if node.coordinates in seen_coords: SN.append(node.label) else: seen_coords.add(node.coordinates) seen_coords gets populated with references to the existing node.coordinates objects, instead of new tuples. Geoff G-T From hauva at arska.org Mon Sep 1 12:11:07 2008 From: hauva at arska.org (Ari Makela) Date: 01 Sep 2008 16:11:07 GMT Subject: How Compute # of Days between Two Dates? References: Message-ID: <48bc141b$0$23597$4f793bc4@news.tdc.fi> On 2008-09-01, W. eWatson wrote: > Oddly, Leaning Python has no mention of datetime (not date or time), at > least, that I could find. I'm considering the Nutshell book, 2nd ed., as a > better reference (and cross reference) to various topics. datetime is pretty new standard library module. I'm quite sure that it wasn't around when the latest edition of Learning Python was written. -- Ari Makela late autumn - hauva at arska.org a single chair waiting http://arska.org/hauva/ for someone yet to come -- Arima Akito From mwilson at the-wire.com Mon Sep 29 11:14:36 2008 From: mwilson at the-wire.com (Mel) Date: Mon, 29 Sep 2008 11:14:36 -0400 Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> Message-ID: George Sakkis wrote: > As Terry Reedy wrote, partly history and partly practicality. There's > no philosophical reason why we write "len(x)" (generic builtin), > "x.append(1)" (method) or "del x[i]" (statement). The latter in > particular is IMHO a design wart; there's no reason for not writing it > as "x.delete(i)". `del x` has almost nothing to do with `x`, and almost everything to do with a namespace containing `x`. The object doesn't know what namespace it's in. Mel. From mal at egenix.com Thu Sep 4 09:59:36 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 04 Sep 2008 15:59:36 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <3de8e1f70809040357p6beb1efar7fe57af9bcaa537c@mail.gmail.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <48BFB534.2080508@egenix.com> <3de8e1f70809040357p6beb1efar7fe57af9bcaa537c@mail.gmail.com> Message-ID: <48BFE9C8.8090501@egenix.com> On 2008-09-04 12:57, Banibrata Dutta wrote: > On Thu, Sep 4, 2008 at 3:45 PM, M.-A. Lemburg wrote: > >> On 2008-09-04 11:14, Kay Schluehr wrote: >>> On 4 Sep., 10:31, "M.-A. Lemburg" wrote: >>>> On 2008-09-04 07:49, Kay Schluehr wrote: >>>> >>>>> 3) Following the public rumor mill and the latest hype RIA i.e. the >>>>> merge of web- and desktop applications with systems like Adobe AIR, >>>>> JavaFX, Google Gears and MS Silverlight is the future of frontend >>>>> development. With the exception of IronPython and Silverlight, Python >>>>> hasn't even entered this game and no one knows if it ever will. >>>> Actually, it has already and quite some time ago: >>>> >>>> http://www.artima.com/weblogs/viewpost.jsp?thread=208528 >>>> >>>> The recipe is simple: use Python for the business logic, database >>>> interfacing, etc and have it talk to a Flex front-end via XML-RPC >>>> or REST. >>> Python is still server-side in this scenario and plays no role in UI >>> definitions. >> That depends on how you design the application. It is well possible >> to have Python drive the GUI by sending the required details to >> the Flex front-end via XML (ie. data-driven GUIs). >> >>> So one doesn't get more than e.g. Django apps that >>> respond to HTTP requests triggered by JavaScript forms except that >>> JavaScript+HTML+Browser is replaced by Flex = AS3+MXML+FlashPlayer. >> You really can't compare the Flex stack to an AJAX stack. Flex >> has a lot more to offer for GUI programming than AJAX, it also >> doesn't suffer from the problems of AJAX having to support several >> different sets of browser or library bugs. >> >> We switched from an AJAX approach to a Flex-based approach last year >> and never even considered moving back again. > > > The approach does seem quite impressive, but isn't Flex's platform > neutrality quite over-rated ? I mean after-all, it assumes that Flex is > available for and available on the platform. Flex today is not yet so > ubiquitous as the JRE... Since Flex is compiled to Flash and runs inside the Flash player, it is fairly easy to get Flex apps running. You do have to have the Flash9 player installed and the default minimum is 9.0.115.0 for Flex builder 3. > Are there some established best-practices on how to package such > applications -- s.a. shipping with its's own Flex runtime, offer-download if > missing etc. ? What happens if owner of target machine decides to upgrade > their version of Flex, will it impact the application package in anyway, and > render rest of it "non-upgradable" ? So far we have not had any such problems, but that could change when Flash10 starts to ship, of course. We currently ship the application as a server application. The only requirement on the client side is having a browser with Flash9 installed. Pointing the browser at the server will then load the compiled Flex application (as .swf file). An alternative approach is bundling the client as AIR application which then runs as stand-alone app on the client side, but we haven't tried that yet. >>> The role of Python is somewhat arbitrary. This could change only if >>> Python becomes a client side language executed by AVM, V8 etc. like >>> IronPython in Silverlight. >>> >>> About separating UI from application logics by assigning functionality >>> to different general purpose languages I have to admit that I don't >>> think it is such a great idea ... >> In my experience, Flex + Python gives you the best of both worlds, >> the nice GUI features of Flex and the efficiency of Python for the >> business logic. >> >> A long time ago, there was a Python plugin for Netscape >> which allowed you to run Python straight in the browser. Perhaps >> it's time to revive such an idea... but then you're still missing >> out on the GUI part, since you're still stuck with what the >> browser has to offer in terms of widget support. >> >> -- >> Marc-Andre Lemburg >> eGenix.com >> >> Professional Python Services directly from the Source (#1, Sep 04 2008) >>>>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ >> ________________________________________________________________________ >> >> :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: >> >> >> eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 >> D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg >> Registered at Amtsgericht Duesseldorf: HRB 46611 >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From google at mrabarnett.plus.com Tue Sep 2 16:53:27 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 2 Sep 2008 13:53:27 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: On Sep 2, 5:55?pm, Steven D'Aprano wrote: > I find myself writing command line tools in Python where I wish to > include "verbose" output to stdout. > > I start with a helper function: > > def print_(obj, level=0): > ? ? if _verbosity >= level: > ? ? ? ? print obj > > And then I end up with functions or methods looking like this: > > def parrot(x) > ? ? print_("precondition", level=2) > ? ? do_something() > ? ? print_("status is good...", level=1) > ? ? print_("parrot is squawking strongly now", level=2) > ? ? do_something_else() > ? ? print_("squawk squawk squawk", level=3) > ? ? do_more() > ? ? print_("postcondition", level=1) > ? ? return something > > That often means that my functions end up with more message printing code > than actual code. The whole thing seems messy and hard to manage for all > but the smallest scripts. > > Worst of all, sometimes the messages I wish to print may be expensive to > compute, and I don't want to waste time computing them if they aren't > going to be printed because the verbosity is too low. But nor do I wish > to fill my code with this: > > if _verbosity >= 3: > ? ? x = calculate_complicated_thing() > ? ? print_(x, level=3) > > Is there a better way of doing this than the way I am going about it? > How about: def print_(obj, level=0): if _verbosity >= level: if callable(obj): obj = obj() print obj so that you could then use: print_("precondition", level=2) and: print_(calculate_complicated_thing, level=3) or: print_(lambda: calculate_complicated_thing(argument), level=3) From bearophileHUGS at lycos.com Fri Sep 26 16:39:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 26 Sep 2008 13:39:16 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> Message-ID: <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> I suggest Python programmers to fill the holes in the Python std lib with some debugged & tuned implementations, their "bag of tricks", so they don't have to re-invent and debug things all the time. This works well with Psyco: def issubseq(sub, items): """issubseq(sub, items): return true if the sequence 'sub' is a contiguous subsequence of the 'items' sequence. >>> issubseq() Traceback (most recent call last): ... TypeError: issubseq() takes exactly 2 arguments (0 given) >>> issubseq("abc") Traceback (most recent call last): ... TypeError: issubseq() takes exactly 2 arguments (1 given) >>> issubseq(1, [1, 2, 3]) Traceback (most recent call last): ... TypeError: 'int' object is not iterable >>> isi = lambda s,i: int(issubseq(s,i)) >>> isi([], []) 1 >>> isi("a", "") 0 >>> isi("", "a") 1 >>> isi("", "aaa") 1 >>> isi("a", "a") 1 >>> isi("ab", "bab") 1 >>> isi("ab", "bab") 1 >>> isi("ba", "bbb") 0 >>> isi("bab", "ab") 0 >>> isi(("a", "b"), ("a","a","b")) 1 >>> isi(("a", "b"), ("a","a","c")) 0 >>> isi([1,2,1], [3,5, 1,2,4, 1,2,1, 6]) 1 >>> isi([1,2,1], [3,5, 1,2,4, 1,2,3, 6]) 0 >>> l = [1] * 50 + [1,2,3] + [4] * 50 >>> isi([1,2,3], l) 1 >>> l = [1] * 50 + [1,2,4] + [5] * 50 >>> isi([1,2,3], l) 0 """ if not hasattr(sub, "__getitem__"): sub = list(sub) len_sub = len(sub) if len_sub == 0: return True try: if not len(items) or len(items) < len_sub: return False except TypeError: pass if sub == items: return True table = [0] * (len_sub + 1) # building prefix-function m = 0 for i in xrange(1, len_sub): while m > 0 and sub[m] != sub[i]: m = table[m - 1] if sub[m] == sub[i]: m += 1 table[i] = m # searching m, i = 0, 0 for x in items: while m > 0 and sub[m] != x: m = table[m - 1] if sub[m] == x: m += 1 if m == len_sub: return True i += 1 return False Usage: >>> from util import issubseq # uses Psyco >>> from timing import timeit >>> a = range(1000000) + range(1000) + range(100000) >>> sub = range(1000) >>> len(a) 1101000 >>> timeit(issubseq, sub, a) (True, 0.0) >>> a = range(999) * 10000 + range(1000) + range(10000) >>> sub = range(1000) >>> timeit(issubseq, sub, a) (True, 0.20000000000000001) Bye, bearophile From workitharder at gmail.com Thu Sep 4 12:36:23 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 4 Sep 2008 09:36:23 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> Message-ID: > >>> so unfortunately I think I need to use __getattribute__ > >>> to do this. I'm doing all this just to make the connection not > >>> actually connect until used. > >> I may be dumb, but I don't get how this is supposed to solve your > >> problem. But anyway : there's a known design pattern for what you're > >> trying to do, that doesn't require mixins nor messing with > >> __getattribute__ (which, I repeat, is more often than not something you > >> *don't* want to do). The name of the design pattern is "proxy". I > >> strongly suggest that you 1/ try to cure the real problem instead of > >> hacking around and 2/ read about the proxy design pattern. > > >> My 2 cents... > > > I like the idea of mix-ins, but can't figure out how to make a proxy > > work that way. > > You mean, "how to use a proxy for lazy initialization" ? Heck, that's > the exact use case in the GoF. I mean, "how to make a MixIn class that uses the proxy pattern". I'd like to be able to do something like this: class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ..., VanillaCursor): pass This works with my current implementation. After thinking about it more, I think I've got such a thing written. I had to use inspect.getmro and new.classobj to do it, but it works and it honors the usual mro (as far as I can tell). I've put the code at the bottom to (try to) maintain readability. > > For a long time I had a proxy class that added five or > > six features on top of the MySQLdb package, but it wasn't configurable > > enough, and I'm working on splitting each feature into its own MixIn > > class. > > > As an aside, this is working for me pretty well. The "reconnect" > > method (inheritied from a "Reconnectable" mixin) uses several of the > > object's attributes, so I need to set _inited beforehand so that I > > don't get into an infinite __getattribute__ loop. What I'd *really* > > like to do is remove __getattribute__ from the object at that point. > > You can't. Or, more exactly, all you can do is remove __getattribute__ > from the mixin class - but then the mixin class won't work anymore. I > don't mean to be condescendant, but it looks like you don't have a clear > understanding of Python's object model here - else you wouldn't even > consider doing such a thing. FWIW, I posted a solution based on the > __getattr__ hook, which did work - at least for the "specs" implied by > your code snippet. My toy example turned out to be not the best representation of the problem. The base class has attributes that "exist" but either throw errors or segfault if used before reconnect() is called. This means that I need to capture more than just the attributes that would throw AttributeError. #CODE######################################## class Base(object): def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs def __str__(self): return "" % (self.args, self.kwargs) class MixIn2(object): def __str__(self): return "" % super(MixIn2, self).__str__() class MixIn1(object): def __str__(self): return "" % super(MixIn1, self).__str__() class ProxyMixIn(object): def __init__(self, *args, **kwargs): self.__proxied = None self.__args = args self.__kwargs = kwargs def __getattr__(self, attr): print "Getting", attr try: return getattr(self.__proxied, attr) except AttributeError: if self.__proxied: raise else: from inspect import getmro mro = getmro(self.__class__) mro = mro[list(mro).index(ProxyMixIn) + 1:] print "Proxied mro", mro from new import classobj self.__proxied = classobj("Proxied", mro, globals()) (*self.__args, **self.__kwargs) return getattr(self.__proxied, attr) def __str__(self): return "" % super(ProxyMixIn, self).__str__() class Proxy(MixIn1, ProxyMixIn, MixIn2, Base): pass def main(): p = Proxy(1,2,3, one=1, two=2) print p main() #OUTPUT###################################### Getting args Proxied mro (, , ) Getting kwargs >>> From uzmanajmal at gmail.com Sat Sep 13 08:23:46 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Sat, 13 Sep 2008 17:23:46 +0500 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Problem is that when i start client (while the server is already running), i get an error i.e. Error 500 Internal Server Error On Sat, Sep 13, 2008 at 3:58 PM, Fredrik Lundh wrote: > Usman Ajmal wrote: > > Where exactly should i call ServerProxy? Following is the code from my >> client.py >> > > ServerProxy is the preferred name. Server is an old alias for the same > class. > > t = SecureTransport() >> t.set_authorization(ustring, text_ucert) >> server = xmlrpclib.Server('http://localhost:8000/',transport=t) >> print server.s() >> > > that code looks correct. so what's the problem? > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From notvalid2 at sbcglobal.net Tue Sep 9 00:53:18 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 08 Sep 2008 21:53:18 -0700 Subject: Correcting for Drift between Two Dates Message-ID: I have two dates, ts1, ts2 as below in the sample program. I know the clock drift in seconds per day. I would like to calculate the actual date of ts2. See my question at the end of the program. # time differences with addition of drift from datetime import datetime, timedelta import time drift = 4.23 # seconds per day format = '%Y%m%d_%H%M%S' ts1 = "20080901_120000" # base date-time ts2 = "20080904_180000" d1 = datetime(*(time.strptime(ts1, format)[0:6])) d2 = datetime(*(time.strptime(ts2, format)[0:6])) #d += timedelta(seconds=sec) delta = d2-d1 # delta format is nnn[n] days, hh:mm:ss # delta is type 'datetime.timedelta' print delta # get back to ts2 as a check d3 = d1+d print d3 #OK, now I need to add the total drift time between # d1 and d2, to get the true date-time of d2. # How do I get at the nnn and hh:mm:ss of delta so that # I can change nnn to nnn+(fraction of day in hh:mm:ss) to # days + fraction of day, D. I want to multiple D by drift # to get seconds of drift in period, then add it to d2. Results 3 days, 6:00:00 2016-09-04 18:00:00 -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From has.temp3 at virgin.net Tue Sep 9 17:44:58 2008 From: has.temp3 at virgin.net (has) Date: Tue, 9 Sep 2008 14:44:58 -0700 (PDT) Subject: How to record audio from Python on Mac? References: <74b0be47-d2c4-4003-a734-35ff9813ef90@l43g2000hsh.googlegroups.com> Message-ID: <757d914a-f8b6-4d0d-bfc8-02bf7dd9cbe4@w7g2000hsa.googlegroups.com> On 9 Sep, 19:55, David Thole wrote: > Another option you could use is calling Applescript from the command > line, to open, execute, and handle audio. For example, using QuickTime Player (which is a buggy, poorly designed piece of junk, but might suffice if you only need something quick-n- dirty and aren't too fussy): #!/usr/bin/python from time import sleep from appscript import * duration = 5 # seconds outpath = '/Users/foo/test.aiff' qtp = app('QuickTime Player') qtp.new_audio_recording() qtp.documents[1].start() sleep(duration) qtp.documents[1].stop() qtp.documents[1].export(to=mactypes.File(outpath), as_=k.AIFF) Or, if you're on Leopard and want something a bit more polished, you could look into using the new QTKit framework via PyObjC. Dunno about Python-specific examples, but I imagine you could dig up some ObjC code if you search around a bit and then convert that over to Python yourself. HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From mail at timgolden.me.uk Tue Sep 16 04:58:14 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 16 Sep 2008 09:58:14 +0100 Subject: A unique instance of Python GUI program In-Reply-To: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Message-ID: <48CF7526.4030701@timgolden.me.uk> akineko wrote: > This may not be a Python specific challenge. > I have a GUI program written in Python + Tkinter. > It works very well. > > Now, I would like to start it from a shell script. > As my GUI program includes a server, it should not have more than one > instance. > Is there any easy way to check if another instance of the program is > already running. > > I vaguely remember that Windows programming provides a way to check. > > A platform independent approach would be nice but a solution for X is > sufficient for my application. I swear this question's been asked twice this month already. Is there a convention going on of one-instance-only application writers? Have a look at: http://mail.python.org/pipermail/python-list/2008-August/505958.html http://mail.python.org/pipermail/python-list/2008-August/505992.html http://mail.python.org/pipermail/python-list/2008-August/505850.html or just search the mailing lists for various previous discussions: http://www.google.com/search?q=site%3Amail.python.org+application+single+instance (or similar queries) TJG From gagsl-py2 at yahoo.com.ar Sat Sep 13 13:13:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 13 Sep 2008 14:13:37 -0300 Subject: I cannot find where Numpy 1.2 is located References: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> Message-ID: En Fri, 12 Sep 2008 17:02:44 -0300, Blubaugh, David A. escribi?: > I have been trying to locate as to where Numpy 1.2 can be downloaded. I > will need this update. The only version available at the Numpy website > for download is only 1.1.1 not the required 1.2 that I definitely need > at this time. Try asking Guido for his time machine. 1.1.1 is the latest release. -- Gabriel Genellina From mr.spoon21 at gmail.com Sun Sep 14 18:08:53 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Mon, 15 Sep 2008 00:08:53 +0200 Subject: Abstract class In-Reply-To: References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <8f67b6f80809141508q3adc7530w198869d2eaf0a2a1@mail.gmail.com> It seems I started a long discussion. You pointed out a lot of interesting things. For example the math operations over notes and intervals and the use of the modulo operator. I already had in mind to implement such things. Anyway, the real purpose of the project is to use these objects with Pyke (Python Knowledge Engine) [1]. I'm not sure yet what I am going to do, but and idea would be to find an appropriate scale for some given chords (for example, from a midi input). As suggested, I'm going to write code and see what is better. Thanks everybody, bye [1] http://pyke.sourceforge.net/ From coolkid246 at googlemail.com Thu Sep 4 06:07:44 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:07:44 -0700 (PDT) Subject: =?ISO-8859-1?Q?online_credit_ohne_in_Landau_sofortkredit_kredit_onl?= =?ISO-8859-1?Q?ine_vergleich_beamtendarlehen_ohne_schufa_handy_ohne_schufa_?= =?ISO-8859-1?Q?kredite_ohne_schufaauskunft_kredit_vergleich_geld_kredit_ohn?= =?ISO-8859-1?Q?e_schufa_kredit_aus_der_schweiz_autofinanzierung_ohne_schufa?= =?ISO-8859-1?Q?_kreditkarten_ohne_schufa_guenstiger_kredit_kredit_online_zu?= =?ISO-8859-1?Q?sage_kredite_arbeitslose__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTIGE_KREDITE_ONLI?= =?ISO-8859-1?Q?NE_=2B=2B=2B_KREDITE_IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_=2B_http=3A=2F=2FWWW=2EKR?= =?ISO-8859-1?Q?EDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_h?= =?ISO-8859-1?Q?ttp=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE?= =?ISO-8859-1?Q?=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKR?= =?ISO-8859-1?Q?EDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_h?= =?ISO-8859-1?Q?ttp=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE?= =?ISO-8859-1?Q?=2D244=2EINFO=2F_=2B_=2B_=2B_=2B_______________________kredite_arbeitslose?= =?ISO-8859-1?Q?_kredit_ohne_schufa_fuer_arbeitslose_in_Bad_Schwalbach_kredi?= =?ISO-8859-1?Q?te_finanzierung_eilkredit_in_Bad_Toelz_guenstiger_kredit_onl?= =?ISO-8859-1?Q?ine_kredite_privat_in_Stadthagen_kredit_ohne_schufa_ohne_vor?= =?ISO-8859-1?Q?kosten_online_kredite_guenstig_in_Borken_sofortkredit_schufa?= =?ISO-8859-1?Q?frei_kredit_online_beantragen_in_Bad_kredit_ohne_schufa_fuer?= =?ISO-8859-1?Q?_arbeitslose_schufafreier_kredit_in_Bernkastel_online_sofort?= =?ISO-8859-1?Q?_kredite_www_kredit_ohne_schufa_in_Meppen_kredite_fuer_arbei?= =?ISO-8859-1?Q?tslose_ohne_schufa_online_kredit_test_in_G=FCnzburg_sofort_kr?= =?ISO-8859-1?Q?edite_online_billig_kredite_in_Werdau_arbeitslos_kredite_fin?= =?ISO-8859-1?Q?anzierungen_online_in_Bad_Windsheim_kredit_ohne_schufa_in_kr?= =?ISO-8859-1?Q?edit_arbeitslos_in_Sigmaringen_kredite_online_vergleich_bank?= =?ISO-8859-1?Q?en_kredit_in_Kleve_guenstiger_kredit_ohne_schufa_eil_kredit_?= =?ISO-8859-1?Q?ohne_schufa_in_Pr=FCm_guenstige_kredite_ohne_schufa_online_kr?= =?ISO-8859-1?Q?edit_trotz_schufa_in_Traunstein_kredit_arbeitslose_bonitaet_?= =?ISO-8859-1?Q?online_in_Kronach_online_kredit_forum_auch_ohne_schufa_in_Gi?= =?ISO-8859-1?Q?e=DFen_kredite_ohne_schufa_auch_fuer_arbeitslose_kredite_ohne?= =?ISO-8859-1?Q?_schufa_auskunft_in_Miesbach____=2D_online_sofort_kredit_ohne_?= =?ISO-8859-1?Q?schufa_billig_kredit_in_Barnim_=2D_kredite_schufa_www_kredit_o?= =?ISO-8859-1?Q?hne_schufa_in_Erding_=2D_sofortkredit_online_sofortkredit_ohne?= =?ISO-8859-1?Q?_schufa_in_Verden_=2D_beamtenkredite_clp_kredit_in_Rendsburg_=2D?= =?ISO-8859-1?Q?_kreditkarte_online_kredite_online_ohne_schufa_in_Ulm_=2D_onli?= =?ISO-8859-1?Q?ne_sofort_kredit_ohne_credit_ohne_schufa_in_Aue_=2D_postbank_k?= =?ISO-8859-1?Q?redit_online_ohne_kredit_in_Dachau_=2D_kredit_trotz_negativer_?= =?ISO-8859-1?Q?schufa_kredit_arbeitslose_in_Wesel_=2D_guenstige_online_kredit?= =?ISO-8859-1?Q?_online_kredite_mit_sofortzusage_in_Saarlouis_=2D_raten_kredit?= =?ISO-8859-1?Q?_ratenkredit_ohne_schufa_in_Coburg_=2D_privat_kredit_ohne_schu?= =?ISO-8859-1?Q?fa_kredit_girokonto_in_Hoexter_=2D_kredit_von_privat_online_kr?= =?ISO-8859-1?Q?edite_in_in_Neunkirchen_=2D_mit_krediten_ohne_schufa_dispo_kre?= =?ISO-8859-1?Q?dit_in_Arnstadt_=2D_online_credit_ohne_schufa_kredit_sofort_in?= =?ISO-8859-1?Q?_Hanau?= Message-ID: <7926b4af-cce9-4d7f-b1d1-9d4f4fb886ac@v13g2000pro.googlegroups.com> online credit ohne in Landau sofortkredit kredit online vergleich beamtendarlehen ohne schufa handy ohne schufa kredite ohne schufaauskunft kredit vergleich geld kredit ohne schufa kredit aus der schweiz autofinanzierung ohne schufa kreditkarten ohne schufa guenstiger kredit kredit online zusage kredite arbeitslose + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + kredite arbeitslose kredit ohne schufa fuer arbeitslose in Bad Schwalbach kredite finanzierung eilkredit in Bad Toelz guenstiger kredit online kredite privat in Stadthagen kredit ohne schufa ohne vorkosten online kredite guenstig in Borken sofortkredit schufafrei kredit online beantragen in Bad kredit ohne schufa fuer arbeitslose schufafreier kredit in Bernkastel online sofort kredite www kredit ohne schufa in Meppen kredite fuer arbeitslose ohne schufa online kredit test in G?nzburg sofort kredite online billig kredite in Werdau arbeitslos kredite finanzierungen online in Bad Windsheim kredit ohne schufa in kredit arbeitslos in Sigmaringen kredite online vergleich banken kredit in Kleve guenstiger kredit ohne schufa eil kredit ohne schufa in Pr?m guenstige kredite ohne schufa online kredit trotz schufa in Traunstein kredit arbeitslose bonitaet online in Kronach online kredit forum auch ohne schufa in Gie?en kredite ohne schufa auch fuer arbeitslose kredite ohne schufa auskunft in Miesbach - online sofort kredit ohne schufa billig kredit in Barnim - kredite schufa www kredit ohne schufa in Erding - sofortkredit online sofortkredit ohne schufa in Verden - beamtenkredite clp kredit in Rendsburg - kreditkarte online kredite online ohne schufa in Ulm - online sofort kredit ohne credit ohne schufa in Aue - postbank kredit online ohne kredit in Dachau - kredit trotz negativer schufa kredit arbeitslose in Wesel - guenstige online kredit online kredite mit sofortzusage in Saarlouis - raten kredit ratenkredit ohne schufa in Coburg - privat kredit ohne schufa kredit girokonto in Hoexter - kredit von privat online kredite in in Neunkirchen - mit krediten ohne schufa dispo kredit in Arnstadt - online credit ohne schufa kredit sofort in Hanau From fredrik at pythonware.com Sat Sep 27 08:58:19 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Sep 2008 14:58:19 +0200 Subject: Regular expression help: unable to search ' # ' character in the file In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > import re > > fd = open(file, 'r') > line = fd.readline > pat1 = re.compile("\#*") > while(line): > mat1 = pat1.search(line) > if mat1: > print line > line = fd.readline() I strongly doubt that this is the code you used. > But the above prints the whole file instead of the hash lines only. "*" means zero or more matches. all lines is a file contain zero or more # characters. but using a RE is overkill in this case, of course. to check for a character or substring, use the "in" operator: for line in open(file): if "#" in line: print line From tmohr at s.netic.de Tue Sep 16 15:21:18 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Sep 2008 21:21:18 +0200 Subject: new style classes, __new__, __init__ References: Message-ID: Hello, > This way __new__ is not called, if i remove __init__ then > there are too many parameters to __new__, if i add a parameter > to __new__ then it says that __new__ does not take arguments. I just found an article that describes it better, this example works: class C2(object): def __new__(cls, a): obj = object.__new__(cls) print "new called" obj.a = 8 return obj __new__ = staticmethod(__new__) def __init__(self, a): print "init called" self.a = a def fct(self): print self.a a = C2(7) a.fct() Best regards, Torsten. From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 07:00:35 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 13:00:35 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: References: Message-ID: <48dcc0ce$0$25400$426a34cc@news.free.fr> bcurtu a ?crit : > Hi, > > I have a BIIIIIG problem with the next query: > > cursor.execute(""" > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """,( eid_list)) > > eid_list is suppossed to be a list of ids = [1,5,9] > > How can I make it work? You have to build your sql statement in three stages: # stage 0: the template sql_template = """ SELECT titem.object_id, titem.tag_id FROM tagging_taggeditem titem WHERE titem.object_id IN (%s) """ # stage 1: build correct place_holders string for the actual number # of items in eid_list place_holders = ", " .join("%s" for x in xrange(len(eid_list))) # stage 2 : build the effective sql statement sql = sql_template % place_holders # ok, let's go: cursor.execute(sql_template, eid_list) NB : you can of course make it in a single statement, but readability will suffer: cursor.execute( """ SELECT titem.object_id, titem.tag_id FROM tagging_taggeditem titem WHERE titem.object_id IN (%s) """ % ", " .join("%s" for x in xrange(len(eid_list))), eid_list ) HTH From sjmachin at lexicon.net Sat Sep 6 18:25:19 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 15:25:19 -0700 (PDT) Subject: modules path References: Message-ID: On Sep 7, 8:03?am, Python wrote: > Hi there, > > I moved a few modules into the modules folder (on OSX: /opt/local/lib/ > python2.5/site-packages/). > They don't show up though when I start IDLE... > > Is there a way to reload the modules folders in sys.path without ? > logging out and back in? > I know nothing about OS X, but no "reload" step should be necessary. Each Python process, whether run from IDLE or some other tool or from the shell, will form its own idea of sys.path. So: What modules? What type of file (.py, .pyc, .egg, .zip, .so) are you talking about? Did their documentation say that moving the files into site-packages was all the installation that was needed? What does "don't show up when I start IDLE" mean? When you start IDLE and do import sys, pprint pprint.pprint(sys.path) do you see the site-packages directory containing the module files? What happens when you do import amodule # substitute correct module name here ? Repeat the above two steps for each of (1) running Python from the shell (2) running Python from the shell with the -v option HTH, John From simon.palmer at gmail.com Wed Sep 3 17:00:36 2008 From: simon.palmer at gmail.com (SimonPalmer) Date: Wed, 3 Sep 2008 14:00:36 -0700 (PDT) Subject: Python on the web - newby question Message-ID: <6822d749-cc00-48ce-a30a-ded96a938e79@b30g2000prf.googlegroups.com> Apologies in advance if this is either a) the wrong board or b) been answered a million times elsewhere, but... I have been given an assignment to get a python module up and running behind an existing web site. At the moment the rest of the site is developed in PHP but the hosts have said they will provide python support for free, although they haven't given any more details than that, so I'm not sure exactly what that means. All reasonably encouraging though. I'm a newbie to python but quite experienced with Java/J2EE/JBoss. What I need to know is how I get python running on the server and what tools/middleware I would need to have installed on the host's machines to be able to support my python modules. Again, apologies if this is the wrong place but I'm a bit lost and would really appreciate some pointers. TIA Simon From daniel.jeem at gmail.com Mon Sep 1 10:28:42 2008 From: daniel.jeem at gmail.com (daniel jeem) Date: Mon, 1 Sep 2008 14:28:42 +0000 Subject: help to use "zc.sourcerelease " Message-ID: <984d3d830809010728y6bd240cfudcb9bf19e2366c35@mail.gmail.com> Hello every body, I want to use "zc.sourcerelease " for creating pakage. But I'm blocked because I have'nt understand how to use it. Then if you have some link or tutorial, share it for me. Help please. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Wed Sep 3 09:41:27 2008 From: roy at panix.com (Roy Smith) Date: Wed, 03 Sep 2008 09:41:27 -0400 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> <7f2d4b4a-bc97-4b46-a31e-63f98e9fee73@34g2000hsh.googlegroups.com> Message-ID: In article <7f2d4b4a-bc97-4b46-a31e-63f98e9fee73 at 34g2000hsh.googlegroups.com>, bearophileHUGS at lycos.com wrote: > Roy Smith: > > No reason to limit how many splits get done if you're > > explicitly going to slice the first two. > > You are probably right for this problem, because most lines are 2 > items long, but in scripts that have to process lines potentially > composed of many parts, setting a max number of parts speeds up your > script and reduces memory used, because you have less parts at the > end. > > Bye, > bearophile Sounds like premature optimization to me. Make it work and be easy to understand first. Then worry about how fast it is. But, along those lines, I've often thought that split() needed a way to not just limit the number of splits, but to also throw away the extra stuff. Getting the first N fields of a string is something I've done often enough that refactoring the slicing operation right into the split() code seems worthwhile. And, it would be even faster :-) From tino at wildenhain.de Mon Sep 15 16:44:29 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 15 Sep 2008 22:44:29 +0200 Subject: append on lists In-Reply-To: References: Message-ID: <48CEC92D.9010302@wildenhain.de> Armin wrote: ... >> >> Because .append() mutates 'a' and appends the item in-place rather >> than creating and returning a new list with the item appended, and >> it's good Python style for mutating methods to have no return value >> (since all functions must have some return value, Python uses None >> when the function doesn't explicitly return anything). > > Yes, but this is very unconvenient. > If d should reference the list a extended with a single list element > you need at least two lines > > a.append(7) > d=a > > and not more intuitive d = a.append(7) Nope. Why wouln'd you just use a instead of d? And if you want a not to be modified in place, just write: d=a+[7] T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From bearophileHUGS at lycos.com Wed Sep 3 21:27:05 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 18:27:05 -0700 (PDT) Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: Alexander Schmolck: > It also reads well, unlike the underscore > which is visually obstrusive and ugly (compare 123'456'890 to 123_456_789). I like that enough, in my language that symbol is indeed the standard one to separate thousands, in large numbers. It's light, looks natural, and as you say it's visually unobstrusive. But in my language ' means just thousands, so it's used only in blocks of 3 digits, not in blocks of any length, so something like this looks a bit strange/wrong: 0b'0000'0000 While the underscore has no meaning, so it can be used in both situations. A problem is that '1234' in Python is a string, so using ' in numbers looks a bit dangerous to me (and my editor will color those numbers as alternated strings, I think). Note that for other people the ' denotes feet, while in my language it denotes minutes, while I think the underscore has no meaning. So for me the underscore is better :-) Bye, bearophile From fredrik at pythonware.com Sat Sep 20 04:11:19 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 10:11:19 +0200 Subject: report a BUG of package setuptools-0.6c8. In-Reply-To: References: Message-ID: ???? wrote: > File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", > line 98, in entries_finder > log.warn("unrecognized .svn/entries format in %s", dirname) > NameError: global name 'log' is not defined > > global name 'log' is not defined to the line 98!!! please report bugs here: http://bugs.python.org/ From electronixtar at gmail.com Sun Sep 28 04:35:11 2008 From: electronixtar at gmail.com (est) Date: Sun, 28 Sep 2008 01:35:11 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> > Because that's how ASCII is defined. > Because that's how ASCII is defined. ASCII is a 7-bit code. Then why can't python use another default encoding internally range(256)? > Python refuses to guess and tries the lowest common denominator -- ASCII -- instead. That's the problem. ASCII is INCOMPLETE! If Python choose another default encoding which handles range(256), 80% of python unicode encoding problems are gone. It's not HARD to process unicode, it's just python & python community refuse to correct it. > stop dreaming of a magic solution It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, what's wrong???? > Isn't that more or less the same as telling the OP to use unicode() instead of str()? sockets could handle str() only. If you throw unicode objects to a socket, it will automatically call str() and cause an error. From luke.hamilton at xenter.com.au Wed Sep 10 08:08:25 2008 From: luke.hamilton at xenter.com.au (Luke Hamilton) Date: Wed, 10 Sep 2008 22:08:25 +1000 Subject: Web shopping carts In-Reply-To: <48C7B508.6070006@wildenhain.de> Message-ID: Thanks... Do you happen to have anymore details? > From: Tino Wildenhain > Date: Wed, 10 Sep 2008 06:52:40 -0500 > To: Luke Hamilton > Cc: "python-list at python.org" > Subject: Re: Web shopping carts > > Luke Hamilton wrote: >> Hey People, >> >> I am wondering if there are any OS shopping cart application written in >> python? >> > > Yes there are. > > HTH > Tino From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 12:51:13 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 18:51:13 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: <48cbf09c$0$25189$426a74cc@news.free.fr> <48cbf432$0$27507$426a34cc@news.free.fr> Message-ID: <48cc0b6f$0$11218$426a34cc@news.free.fr> Larry Bates a ?crit : > Bruno Desthuilliers wrote: >> Bruno Desthuilliers a ?crit : >>> Larry Bates a ?crit : >>> (snip) >>>> IMHO it reads better if you use the __call__ method of the class to >>>> return the value >>> >>> IMHO, it makes no sense at all to abuse the __call__ magic method here. >> >> Sorry - after a more careful re-read of other posts in the thread, it >> might make sense, given the use case : >> >> condition = FolderInUse(core) >> if condition.true_for(folder): >> # code here >> >> >> but then, a plain function (or a partial) might be even better - that >> is, if the FolderInUse class doesn't have other responsabilities. >> >> > > Sorry but I respectfully disagree that this is "abuse" of the __call__ > method. As long as we respectfully agree to disagree... !-) From timr at probo.com Thu Sep 25 04:03:02 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Sep 2008 08:03:02 GMT Subject: How to parse a string completely into a list References: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> Message-ID: john.ford at colorado.edu wrote: > >The string draws a map that I then want to be able to traverse >through. If I can count through the individual characters of a list I >can create an x-y coordinate plane for navigation. Well, the point Matt was making is that traversing through a list and traversing through a string are the same. # Given this: s = 'abcde' l = ['a','b','c','d','e'] # These are identical: for ch in s: pass for ch in l: pass # And these are identical: print s[3] print l[3] Slicing is identical. Subsetting is identical. The only difference is that I can change an element of the list. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From google at mrabarnett.plus.com Sat Sep 27 08:42:40 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sat, 27 Sep 2008 05:42:40 -0700 (PDT) Subject: Build-in 'repr' function (was: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])?) References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> <87abduuvlz.fsf@benfinney.id.au> Message-ID: On Sep 27, 4:16?am, Ben Finney wrote: > process writes: > > ' '.join([`x * x` for x in range(1, 6)]) > > > exactly what does this symbol do and what does it stand for? > > It's an obsolete, deprecated syntactic sugar for (what is now > implemented as) the built-in 'repr' function. > > Instead, write the above as: > > ? ? ' '.join([repr(x * x) for x in range(1, 6)]) > I'd classify it as one of Guido's mistakes! :-) From gstaniak at wp.pl Wed Sep 10 10:52:07 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Wed, 10 Sep 2008 14:52:07 +0000 (UTC) Subject: PHP's str_replace ? References: Message-ID: On 10.09.2008, Anjanesh Lekshminarayanan wroted: > In PHP, if I do > str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) > it'll replace all vowels with a hyphen in string $str. > > Is there some equivalent in Python ? The .translate() method of strings? >>> import string >>> mystr = "This is just a test" >>> transtable = string.maketrans("aeiouy","------") >>> mystr.translate(transtable) 'Th-s -s j-st - t-st' GS -- Grzegorz Staniak Nocturnal Infiltration and Accurate Killing From JesseAldridge at gmail.com Mon Sep 1 16:30:17 2008 From: JesseAldridge at gmail.com (Jesse Aldridge) Date: Mon, 1 Sep 2008 13:30:17 -0700 (PDT) Subject: Put the output from all my programs in one place Message-ID: <3110346f-ed2b-458d-bbf8-af7e594f6509@e53g2000hsa.googlegroups.com> I want to put all the output from all of my python programs in one place. I've been trying to get this working for the last few days, but there are lots of annoying little details that are making the process quite difficult. I'm wondering if anyone can help me get this working. Currently I have one program called Output_Displayer.py This is a wxPython app that uses the aui tabbed interface. Basically it's just a frame with tabs where each tab contains one multi-line text control which displays the stdout and stderr messages for one program. I make one tab for each running program. I may change the way the interface works in the future, but the basic idea is just that it displays the stdout and stderr messages for all my programs. One thing I've tried is creating an output function to replace the print statement. This new function writes to a file. I made it so that Output_Displayer polls for this file, reads it if it exists, displays it's contents, and then deletes it. This works for standard output, but of course this doesn't work for stderr messages. Another thing I've tried is redirecting stdout and stderr to files and having Output_Displayer read those files. But I want the output to displayed "live" -- streaming, rather than waiting for the program to finish running. I think I'm having issues with input blocking while trying to read from these files when redirecting the streams. It seems I can't read the files until the program finishes running? In that case, I have another problem of determining whether or not the program has finished running. How can I detect this? I don't think I want to use subprocess for this, although I'm willing to if I can't get it working without it. I would prefer to have Output_Displayer be completely independent from my other programs rather than running them as children or something. Anyway, I've tried a bunch of different things and am more or less drowning in technical details. Has anyone done something like this before? I'd appreciate any help I can get. From skip at pobox.com Wed Sep 17 13:58:05 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Sep 2008 12:58:05 -0500 Subject: locks In-Reply-To: <48D140FC.8070801@el.net> References: <48D140FC.8070801@el.net> Message-ID: <18641.17709.251764.767222@montanaro-dyndns-org.local> kalin> mailman has been locking one list out. the web interface just kalin> hangs and it generates a bunch of locks. it seems that it can not kalin> write to a log but not sure which one. errors are like: ... You'd probably be better off asking about Mailman problems on mailman-users at python.org. -- Skip Montanaro - skip at pobox.com - http://www.webfast.com/~skip/ From sayananbig at gmail.com Tue Sep 23 14:32:20 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Tue, 23 Sep 2008 11:32:20 -0700 (PDT) Subject: python timers and COM/directshow References: Message-ID: On Sep 23, 4:24?am, Tim Golden wrote: > Sayanan Sivaraman wrote: > > So I've written a simple video player using directshow/COM in VC++, > > and I'm in the process of translating it to python. ?For example, when > > the avi starts playing, I have a call media_control.Run() , etc. > > > I'm wondering how I should go about updating my gtk.Hscale widget as a > > trackbar for the avi player. > > > In C++, I have the following callbacks that update the scrollbar and > > video position with a timer. > > [... snip callbacks ...] > > > > > I'm wondering how I would implement similar callbacks in Python for a > > gtk.Hscale, and some sort of time [I'm not familiar with Pythons > > timers/threading at all]. > > You'd help your cause a lot here if you posted *Python* > code to indicate what's calling what back where. Also if > you stated whether you were using, eg, the GTK toolkit which > your description suggests, or some other GUI toolkit. Because > they tend to vary as to how they arrange their callbacks. > > In geeneral, Python callbacks are trivial: you create the > function to do whatever and then pass the function as an > object into the calling-back function call. Something > like this (invented GUI toolkit): > > > def handle_lbutton_click (event): > ? # > ? # do stuff with lbutton click > ? # > > def handle_widget_slide (event): > ? # > ? # do stuff with widget slide > ? # > > handle_event ("lbutton_click", handle_lbutton_click) > widget.attach_event ("slide", handle_widget_slide) > > > > But the details will obviously depend on the toolkit you > use. > > TJG > TJG Sorry, you make a very good point. I am using gtk. I don't have a problem with callbacks for the gtk widgets. My question is about timers and their callbacks. The reason I used c++ code is that Microsoft's COM interface is natively in C++, and Python uses "import comtypes" to access this functionality and the dll's.[ie GetModule('quartz.dll')] Essentially what I would like to have [as evidenced by the c++ code] is something like the following: def timer_callback(args): while timer is active update scrollbar position based on video progress #here I am using microsoft's COM interface, so the function would be something like scrollbar.set_value(media_control.CurrentPosition) def scrollbar_callback : when the scrollbar is moved, update this video position #this I understand. It would be something like media_control.CurrentPosition= scrollbar.get_value() def pauser : media_control.Pause() *somehow kill timer* def player: media_control.Run() timer.run() #timer.run() would call timer_callback So I would like to know how to construct and implement a timer that would do the above, a la the first callback. In addition, the timer has to be able to be paused/killed if I pause the video, and implemented again if I play the video ie: Thanks, sayanan From joncle at googlemail.com Tue Sep 9 16:53:57 2008 From: joncle at googlemail.com (Jon Clements) Date: Tue, 9 Sep 2008 13:53:57 -0700 (PDT) Subject: noob help request - how to make a list of defined class? References: Message-ID: <5f169171-c368-43cd-a70f-1cb8797ee3eb@x35g2000hsb.googlegroups.com> On Sep 9, 3:11?pm, nuffno... at gmail.com wrote: > I have defined two classes with one common field (called code) and > several different fields. > In class A there is only one instance of any given code as all items > are individual. > In class B, there may be none, one or many instances of each code, as > there can be any number of Bs referring to a single A. > > I need to make a list of Bs, remove dupes, and then create a list of > As that have Bs. > > (I hope this makes sense!) > > with much research and reading of my book I managed to get this > working, ?but at one stage I had errors that talked about being unable > to concatenate type A. ?So I converted my As to string, and then did a > split on commas to make a list. ?This worked fine for all the As that > didn't have a comma in a field (about 85%) but I can't help feeling > that this is a kludge, and that if Icould find a way to get a proper > list of As instead of a list of lists created by converting to string > and splitting, then my app would work properly. > > So I am hoping some of the nice folk here will help me out. > > The relevent function looks like this: > > def gen_B_A_list(): > ? ? Bcodes = get_codes() > ? ? all_As = read_A("A.csv") > ? ? B_A = [] > ? ? for i in range(len(codes)): > ? ? ? ? Bcode = Bcodes[i] > ? ? ? ? for A in all_As: > ? ? ? ? ? ? filename = getattr(A, 'code') > ? ? ? ? ? ? if filename == Bcode: > ? ? ? ? ? ? ? ? BA = str(A) > ? ? ? ? ? ? ? ? BA = string.split(BA, ',') > ? ? ? ? ? ? ? ? B_A.append(BA) > ? ? return B_A > > The element in question is after if filename == Bcode. ? How do I > construct a list of my defined class A objects here instead of this? > ( I can post the full code if needed, ?just thought it was better > netiquette not to) > > TIA > > nuffi Looks like homework, but as you've made some kind of effort, some hints to where to refer to in the manual. 1) Use the csv module for reading CSV files 2) A dict maps one value to another... (check it out) 3) Don't use getattr, use member access (the . symbol, eg: A.code) 4) The for statement can loop over each item in term without an explicit range (eg, for bcode in codes...) 5) Read the help for str, and read up on how to create objects, for instance str(A) returns A's string representation, while A() creates a new A object... Work your way through a python tutorial and make sure you understand the examples and principals... It might take you a while though, so I hope the assignment's not due soon! Jon. From m_palmer45 at yahoo.ca Tue Sep 23 10:08:07 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 23 Sep 2008 07:08:07 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> Message-ID: > > This seems to break the rule that if A is equal to B and B is equal to C > > then A is equal to C. > > I don't see why transitivity should apply to Python objects in general. Well, for numbers it surely would be a nice touch, wouldn't it. May be the reason for Decimal to accept float arguments is that irrational numbers or very long rational numbers cannot be converted to a Decimal without rounding error, and Decimal doesn't want any part of it. Seems pointless to me, though. From paul at boddie.org.uk Mon Sep 8 09:27:35 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 8 Sep 2008 06:27:35 -0700 (PDT) Subject: tracking collection modification References: <42d9688f-1058-4ed7-8d9d-affd432fdb41@s1g2000pra.googlegroups.com> Message-ID: On 7 Sep, 12:54, usenet.tolo... at gmail.com wrote: > I'm working on a remote object system, something kinda like Pyro. > For the purposes of caching I need to be able to tell if a given > dict / list / set has been modified. > Ideally what I'd like is for them to have a modification count > variable that increments every time the particular collection is > modified. Unfortunately I can't find anything like that and since this > needs to work for the regular normal list / dict / set objects > subclassing them to add the modification count isn't useful. What you appear to need here is some kind of proxying solution - a layer which records accesses to the objects, distinct from the objects themselves. I believe that the PyPy project provides something of this nature: http://codespeak.net/pypy/dist/pypy/doc/objspace-proxies.html Paul From edreamleo at charter.net Tue Sep 2 10:02:37 2008 From: edreamleo at charter.net (Edward K Ream) Date: Tue, 2 Sep 2008 09:02:37 -0500 Subject: Leo 4.5 final released Message-ID: Leo 4.5 final is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.5: -------------------------- - Full support for @shadow files in Leo's core. - Major improvements to Leo's key binding code. - The beginning of usable vim-like bindings. - uA's may now be associated with vnodes in @thin and @shadow files. - Several magor reorganizations of Leo's code: including sax-based parsing, support for the Graph world (unified nodes), and simplified drawing code. - Leo is now an installable package. - Prepared code to be ready for Python 3.0. - Many small improvements and bug fixes. Quote of the month: ------------------- Squeak and Leo have been two of the most significant technologies to redefine my personal computer experience and the ideas behind computing. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From steve at holdenweb.com Fri Sep 19 03:25:41 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Sep 2008 03:25:41 -0400 Subject: Extracting hte font name from a TrueType font file In-Reply-To: References: Message-ID: Aaron "Castironpi" Brady wrote: > On Sep 18, 7:48 pm, Steve Holden wrote: >> Fredrik Lundh wrote: >>> Steve Holden wrote: >>>> Does anyone have a Python recipe for this? >>>>>> from PIL import ImageFont >>>>>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1) >>>>>> f.font.family >>> 'Verdana' >>>>>> f.font.style >>> 'Italic' >> Thanks so much, Fredrik. The reason I asked is because I found the >> specification completely opaque ... >> >> regards >> Steve >> -- >> Steve Holden +1 571 484 6266 +1 800 494 3119 >> Holden Web LLC http://www.holdenweb.com/ > > Here's the code to parse the spec. > > #customize path > f= open( '\\windows\\fonts\\arial.ttf', 'rb' ) > from struct import * > > #header > shead= Struct( '>IHHHH' ) > fhead= f.read( shead.size ) > dhead= shead.unpack_from( fhead, 0 ) > > #font directory > stable= Struct( '>4sIII' ) > ftable= f.read( stable.size* dhead[ 1 ] ) > for i in range( dhead[1] ): #directory records > dtable= stable.unpack_from( > ftable, i* stable.size ) > if dtable[0]== 'name': break > assert dtable[0]== 'name' > > #name table > f.seek( dtable[2] ) #at offset > fnametable= f.read( dtable[3] ) #length > snamehead= Struct( '>HHH' ) #name table head > dnamehead= snamehead.unpack_from( fnametable, 0 ) > > sname= Struct( '>HHHHHH' ) > for i in range( dnamehead[1] ): #name table records > dname= sname.unpack_from( > fnametable, snamehead.size+ i* sname.size ) > if dname[3]== 4: #key == 4: "full name of font" > s= unpack_from( > '%is'% dname[4], fnametable, > dnamehead[2]+ dname[5] )[0] > print dname, s > > This outputs: > > (0, 3, 0, 4, 10, 318) A r i a l > (1, 0, 0, 4, 5, 4081) Arial > (3, 1, 1033, 4, 10, 318) A r i a l > > First 3 fields: > > 0, 3, 0= Unicode, Unicode 2.0, English > 1, 0, 0= Macintosh, Default, English > 3, 1, 1033= Windows, Version 1.1, Language "1033" Well you clearly understood it better than *I* did! regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From deets at nospam.web.de Wed Sep 3 09:56:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 15:56:09 +0200 Subject: installing matplotlib with numpy and scipy for Python in Cygwin In-Reply-To: <4241157d-6cdb-4edc-bb22-bceeb68b870f@m73g2000hsh.googlegroups.com> References: <4241157d-6cdb-4edc-bb22-bceeb68b870f@m73g2000hsh.googlegroups.com> Message-ID: <6i7jbrFov1rqU1@mid.uni-berlin.de> Anish Chapagain schrieb: > On Sep 3, 12:39 pm, Uwe Schmitt > wrote: >> On 3 Sep., 11:42, "chapagainanish" wrote: >> >>> Hi!! >>> I'm having installation problem for installing numpy and scipy in >>> Cygwin for Python, and am obstruct in madway for project, i followed >>> scipy.org guidelines but there's few error thrown as >>> failed..with exit status 1 >>> please if someone has installed these module help me >>> thank's and regard's >>> Anish >> http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html >> may help you. >> >> Do you really want a cygwin based installation ? >> You could download enthoughts python edition which >> includes lots of math stuff. >> >> Greetings, Uwe > > Hi, > thank's i'm looking through the link cens.ioc.ee > and am in need of using matplotlib and to run few system call, so i > installed cygwin baically for system call in linux/unix and matplotlib > for GUI(graph,chart) but matplotlib is not getting installed in > cygwin.. What are "system calls"? You *have* windows, so in the end you can do everything with "normal" python. And I presume that your codebase is by far smaller that matplotlibs, so adapting your source is easier than theirs. Diez From bdesth.quelquechose at free.quelquepart.fr Fri Sep 5 15:16:36 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 Sep 2008 21:16:36 +0200 Subject: use str as variable name In-Reply-To: References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> Message-ID: <48c1a184$0$17080$426a74cc@news.free.fr> Marco Bizzarri a ?crit : > On Thu, Sep 4, 2008 at 10:47 AM, Fredrik Lundh wrote: > >> (...as Bruno implies, setattr(), len() et al can be and should be viewed as >> generic functions. > > Just a question: "generic functions" are not meant in the sense of > "generic functions" of CLOS, am I right? Nope. Just "generic" in the sense that they accept any object implementing a very minimal interface. If you want something like CLOS multimethods, you may be interested in Philip Eby's ruledispatch. From uzmanajmal at gmail.com Wed Sep 17 07:06:19 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Wed, 17 Sep 2008 11:06:19 +0000 Subject: File Reading related query In-Reply-To: <48D0DFD8.4000309@tim.thechases.com> References: <48D0DFD8.4000309@tim.thechases.com> Message-ID: Thanks Tim. That rstrip('\r\n') worked. :) On Wed, Sep 17, 2008 at 10:45 AM, Tim Chase wrote: > Is there any function for reading a file while ignoring *\n* occuring in >>> the file? >>> >> >> can you be a bit more precise? are we talking about text files or binary >> files? how do you want to treat any newlines that actually appear in the >> file? >> > > I believe the OP is referencing this behavior: > > for line in file('x.txt'): > assert not ( > line.endswith('\r') or > line.endswith('\n')), "Don't want this" > else: > yay() # we never end up reaching this > > which can be done with a simple generator/wrapper: > > def unnewline(iterator): > for line in iterator: > yield line.rstrip('\r\n') > for line in unnewline(file('x.txt')): > assert not ( > line.endswith('\r') or > line.endswith('\n')), "Don't want this" > else: > yay() # we get here this time > > Alternatively, the content can just be modified on the fly: > > for line in file('x.txt'): > line = line.rstrip('\r\n') > ... > > yes, the interpretation would differ if it were a binary file, but the > above interpretation is a pretty common case (i.e. I encounter it daily, in > my processing of client data-feeds). > > -tkc > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From grflanagan at gmail.com Mon Sep 29 17:12:19 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Mon, 29 Sep 2008 23:12:19 +0200 Subject: Finding subsets for a robust regression In-Reply-To: References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> Message-ID: Gerard flanagan wrote: > tkpmep at hotmail.com wrote: > >> >> x1 = [] #unique instances of x and y >> y1 = [] #median(y) for each unique value of x >> for xx,yy in d.iteritems(): >> x1.append(xx) >> l = len(yy) >> if l == 1: >> y1.append(yy[0]) >> else: >> yy.sort() >> y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else >> yy[l//2] ) >> -- > > Not tested, but is this equivalent? > > x1 = [] > y1 = [] > for xx, yy in d.iteritems(): > L = len(yy) // 2 > yy.sort() > y1.append(yy[L]) > if not L & 1: > y1[-1] = (y1[-1] + yy[L-1]) / 2.0 > > It means that you have a pointless 'sort' when len(yy) == 1, but then > you save an 'if' per-iteration. > > G. > > -- Maybe that should be: if L and not L & 1: ... anyway... From ahmad.humyn at gmail.com Fri Sep 5 04:22:54 2008 From: ahmad.humyn at gmail.com (Ahmad Humayun) Date: Fri, 5 Sep 2008 01:22:54 -0700 (PDT) Subject: atomic section in code Message-ID: Hi there, I need to create an atomic section in Python code i.e. there is no context switch to any other thread during the running of that piece of code. Would would do the trick? thanks, From frank at chagford.com Sat Sep 20 01:59:55 2008 From: frank at chagford.com (Frank Millman) Date: Fri, 19 Sep 2008 22:59:55 -0700 (PDT) Subject: XML-schema 'best practice' question References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: On Sep 18, 8:28?am, Frank Millman wrote: > Hi all > > This is not strictly a Python question, but as I am writing in Python, > and as I know there are some XML gurus on this list, I hope it is > appropriate here. > > XML-schemas are used to define the structure of an xml document, and > to validate that a particular document conforms to the schema. They > can also be used to transform the document, by filling in missing > attributes with default values. > [..] > > Or maybe the best practice is to *always* validate a document before > processing it. > I have realised that my question was irrelevant. xml's raison d'etre is to facilitate the exchange of information between separate entities. If I want to use xml as a method of serialisation within my own system, I can do what I like, but there can be no question of 'best practice' in this situation. When xml is used as intended, and you want to process a document received from a third party, there is no doubt that you should always validate it first before processing it. Thank you, Lorenzo, for pointing out the obvious. It may take me a while to catch up, but at least I can see things a little more clearly now. As to why I am using xml at all, I know that there is a serious side to Skip's light-hearted comment, so I will try to explain. I want to introduce an element of workflow management (aka Business Process Management) into the business/accounting system I am developing. I used google to try to find out what the current state of the art is. After several months of very confusing research, this is the present situation, as best as I can figure it out. There is an OMG spec called BPMN, for Business Process Modeling Notation. It provides a graphical notation, intended to be readily understandable by all business users, from business analysts, to technical developers, to those responsible for actually managing and monitoring the processes. Powerful though it is, it does not provide a standard method of serialsing the diagram, so there is no standard way of exchanging a diagram between different vendors, or of using it as input to a workflow engine. There is an OASIS spec called WS-BPEL, for Web Services Business Process Execution Language. It defines a language for specifying business process behavior based on Web Services. This does have a formal xml-based specification. However, it only covers processes invoked via web services - it does not cover workflow-type processes within an organisation. To try to fill this gap, a few vendors got together and submitted a draft specification called BPEL4People. This proposes a series of extensions to the WS-BPEL spec. It is still at the evaluation stage. The BPMN spec includes a section which attempts to provide a mapping between BPMN and BPEL, but the authors state that there are areas of incompatibility, so it is not a perfect mapping. Eventually I would like to make sense of all this, but for now I want to focus on BPMN, and ignore BPEL. I can use wxPython to design a BPMN diagram, but I have to invent my own method of serialising it so that I can use it to drive the business process. For good or ill, I decided to use xml, as it seems to offer the best chance of keeping up with the various specifications as they evolve. I don't know if this is of any interest to anyone, but it was therapeutic for me to try to organise my thoughts and get them down on paper. I am not expecting any comments, but if anyone has any thoughts to toss in, I will read them with interest. Thanks Frank From prologic at shortcircuit.net.au Sun Sep 7 17:37:12 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 07:37:12 +1000 Subject: max(), sum(), next() In-Reply-To: <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: Can we stop this thread now? :) I think we've all seen what the intended behavior of sum(), max() and other similar functions. cheers James On Mon, Sep 8, 2008 at 3:30 AM, Mensanator wrote: > On Sep 6, 11:05?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote: >> >> [...] >> >> >> They could have decided that sum must take at least two arguments, >> >> because addition requires two arguments and it's meaningless to talk >> >> about adding a single number without talking about adding it to >> >> something else. But they didn't. >> >> > Ok. But the problem is they DID in SQL: x + Null = Null. >> >> Sheesh. That's not a problem, because Python is not trying to be a >> dialect of SQL. > > And yet, they added a Sqlite3 module. > >> >> If you want a NULL object, then there are recipes on the web that will >> give you one. Then all you need to do is call sum(alist or [NULL]) and it >> will give you the behaviour you want. > > Actualy, I already get the behaviour I want. sum([1,None]) > throws an exception. I don't see why sum([]) doesn't throw > an exception also (I understand that behaviour is by design, > I'm merely pointing out that the design doesn't cover every > situation). > >> >> [...] >> >> > Here's a real world example (no ivory tower stuff): >> >> > An oil refinery client has just excavated a big pile of dirt to lay a >> > new pipeline. >> [snip details] >> > Can't I just use a sum of 0 to tell me when data is missing? No, because >> > in some cases the reporting limit of undetected compounds is set to 0. >> >> You can't use a sum of 0 to indicate when data is missing, full stop. > > Exactly. That's why I would prefer sum([]) to raise an > exception instead of giving a false positive. > >> The >> data may require 15 tests when only 3 have actually been done: >> >> sum([1.2e-7, 9.34e-6, 2.06e-8]) > > Biggest problem here is that it is often unknown just > how many records you're supposed to get from the query, > so we can't tell that a count of 3 is supposed to be 15. > >> >> Missing data and a non-zero sum. How should sum() deal with that? > > That's a seperate issue and I'm not saying it should as > long as the list contains actual numbers to sum. > sum([1.2e-7, 9.34e-6, 2.06e-8, None]) will raise an > exception, as it should. But what types are contained > in []? > >> >> The answer is that sum() can't deal with that. You can't expect sum() to >> read your mind, know that there should be 15 items instead of 3, and >> raise an error. So why do you expect sum() to read your mind and >> magically know that zero items is an error, especially when for many >> applications it is NOT an error? > > For the simple reason it doesn't have to read your mind, > a mechanism has already been built into the function: start > value. For those situations where an empty list is desired > to sum to 0, you could use sum(alist,0) and use sum(alist) for > those cases where summing an empty list is meaningless. > Shouldn't you have to explicitly tell sum() how deal with > situations like empty lists rather than have it implicitly > assume a starting value of 0 when you didn't ask for it? > >> >> The behaviour you want for this specific application is unwanted, >> unnecessary and even undesirable for many other applications. The >> solution is for *you* to write application-specific code to do what your >> application needs, instead of relying on a general purpose function >> magically knowing what you want. > > Does division magically know what you want? No, it raises an > exception when you do something like divide by 0. Isn't it > Pythonic to not write a litany of tests to cover every > possible case, but instead use try:except? > > But try:except only works if the errors are recognized. > And sum() says that summing an empty list is NEVER an error > under ANY circumstance. That may be true in MOST cases, but > it certainly isn't true in ALL cases. > >> >> -- >> Steven > > -- > http://mail.python.org/mailman/listinfo/python-list -- -- -- "Problems are solved by method" From roseeea at gmail.com Thu Sep 25 00:02:31 2008 From: roseeea at gmail.com (ROSEEE) Date: Wed, 24 Sep 2008 21:02:31 -0700 (PDT) Subject: The Python computer language Message-ID: http://pythoncomputer.blogspot.com From Ron.Barak at lsi.com Tue Sep 16 03:07:52 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Sep 2008 08:07:52 +0100 Subject: Representation of python code ? In-Reply-To: References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6022A6B6B@enbmail01.lsi.com> Thanks for the pointer, Ebert. epydoc produces quite useful documentation (in a different format than what I had in mind, but useful nonetheless). Bye, Ron. -----Original Message----- From: Manuel Ebert [mailto:maebert at uos.de] Sent: Tuesday, September 16, 2008 03:03 To: Barak, Ron Cc: python-list at python.org Subject: Re: Representation of python code ? -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 AFAIK epydoc can generate pretty graphs with graphviz on the fly, such as class hierarchies or call graphs. On Sep 14, 2008, at 3:44 PM, Barak, Ron wrote: > Hi Guys, > Is there a script/application, which gets as input python code, and > produces a (graphic) representation of the inter-relationships between > its classes/functions ? > Bye, > Ron. > -- > http://mail.python.org/mailman/listinfo/python-list -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIzve8cZ70OCIgLecRAjRbAKCRXHRKDJN+oxoJQ7S7z8i6sVCNxQCggowS PVV6g/BRKesRGErGHcAcURE= =q9Hs -----END PGP SIGNATURE----- -------------- next part -------------- An HTML attachment was scrubbed... URL: From Afro.Systems at gmail.com Wed Sep 10 15:03:34 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Wed, 10 Sep 2008 12:03:34 -0700 (PDT) Subject: Simple UDP server References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> Message-ID: <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> On Sep 10, 9:55?pm, Fredrik Lundh wrote: > Tzury Bar Yochay wrote: > > Would the one below will be capable of holding 30 concurrent > > connections? > > UDP is a connectionless datagram protocol, so that question doesn't > really make much sense. > So what if it is connectionless. It would make sense if you get a load of users who sends large sets of binary data to each other. From kyosohma at gmail.com Fri Sep 26 09:45:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 26 Sep 2008 06:45:59 -0700 (PDT) Subject: how to search multiple textfiles ? References: Message-ID: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> On Sep 26, 8:35?am, Stef Mientki wrote: > hello, > > I want to search multiple textfiles (python source files) for a specific > word. > I can find all files, open them and do a search, > but I guess that will be rather slow. > > I couldn't find any relevant information through google. > > Does anyone know of a search library that performs this task fast ? > > If it indeed only concerns py-files, > is there another way of searching words ? > ( I could imagine that such a "py-only-search" would have benefits, > because you could set a flag to see the words in comment yes or no ) > > thanks, > Stef Mientki > > Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. > The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629. On Windows I use the free version of Bare Grep: http://www.baremetalsoft.com/baregrep/ No, it's not a Python solution, but it works for my needs. You should try using Python to search your script files and see if it really is too slow though. Mike From kf9150 at gmail.com Thu Sep 11 04:54:41 2008 From: kf9150 at gmail.com (Kelie) Date: Thu, 11 Sep 2008 01:54:41 -0700 (PDT) Subject: Use Python to solve equations? References: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Message-ID: Thank you James! Checking it out right now... From fredrik at pythonware.com Thu Sep 4 17:31:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 23:31:44 +0200 Subject: why is self not passed to id()? In-Reply-To: References: <200809042244.54418.maric@aristote.info> Message-ID: Robert Kern wrote: > Well, that's not entirely true. They need to be not mutated while they > are in the dictionary, certainly. At least not in ways that affect > equality testing. In this case, one would also have to override > list.__eq__ to also compare by identity, too. Then you could mutate the > lists to your heart's content and the dictionary wouldn't care. at which point you'd start wondering if it wouldn't be more efficient to wrap the list in a light-weight class, instead of using subclassing. From mal at egenix.com Thu Sep 4 06:15:16 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 04 Sep 2008 12:15:16 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> Message-ID: <48BFB534.2080508@egenix.com> On 2008-09-04 11:14, Kay Schluehr wrote: > On 4 Sep., 10:31, "M.-A. Lemburg" wrote: >> On 2008-09-04 07:49, Kay Schluehr wrote: >> >>> 3) Following the public rumor mill and the latest hype RIA i.e. the >>> merge of web- and desktop applications with systems like Adobe AIR, >>> JavaFX, Google Gears and MS Silverlight is the future of frontend >>> development. With the exception of IronPython and Silverlight, Python >>> hasn't even entered this game and no one knows if it ever will. >> Actually, it has already and quite some time ago: >> >> http://www.artima.com/weblogs/viewpost.jsp?thread=208528 >> >> The recipe is simple: use Python for the business logic, database >> interfacing, etc and have it talk to a Flex front-end via XML-RPC >> or REST. > > Python is still server-side in this scenario and plays no role in UI > definitions. That depends on how you design the application. It is well possible to have Python drive the GUI by sending the required details to the Flex front-end via XML (ie. data-driven GUIs). > So one doesn't get more than e.g. Django apps that > respond to HTTP requests triggered by JavaScript forms except that > JavaScript+HTML+Browser is replaced by Flex = AS3+MXML+FlashPlayer. You really can't compare the Flex stack to an AJAX stack. Flex has a lot more to offer for GUI programming than AJAX, it also doesn't suffer from the problems of AJAX having to support several different sets of browser or library bugs. We switched from an AJAX approach to a Flex-based approach last year and never even considered moving back again. > The role of Python is somewhat arbitrary. This could change only if > Python becomes a client side language executed by AVM, V8 etc. like > IronPython in Silverlight. > > About separating UI from application logics by assigning functionality > to different general purpose languages I have to admit that I don't > think it is such a great idea ... In my experience, Flex + Python gives you the best of both worlds, the nice GUI features of Flex and the efficiency of Python for the business logic. A long time ago, there was a Python plugin for Netscape which allowed you to run Python straight in the browser. Perhaps it's time to revive such an idea... but then you're still missing out on the GUI part, since you're still stuck with what the browser has to offer in terms of widget support. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From fredrik at pythonware.com Thu Sep 11 09:37:40 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 15:37:40 +0200 Subject: function return In-Reply-To: References: Message-ID: make that: > note that you put the "return" statement inside the loop, so returning > only one line is the expected behaviour. to fix this, you can append the result strings to the data_lis list inside the loop: > result = "%s\t%s\t%s" %(id,gene_symbol,ptms) > data_lis.append(result) > > and then return the list when done: > > > fh.close() > return data_lis > From steven at REMOVE.THIS.cybersource.com.au Wed Sep 17 23:35:52 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 03:35:52 GMT Subject: decorator and API References: Message-ID: On Thu, 18 Sep 2008 02:26:29 +0430, Lee Harr wrote: > I have a class with certain methods from which I want to select one at > random, with weighting. > > The way I have done it is this .... [snip] You are coupling the weights, the actions, and the object which chooses an action all in the one object. I find that harder to wrap my brain around than a more loosely coupled system. Make the chooser independent of the things being chosen: def choose_with_weighting(actions, weights=None): if weights is None: weights = [1]*len(actions) # equal weights # Taken virtually unchanged from your code. # I hope it does what you want it to do! assert len(weights) == len(actions) total = sum(weights) choice = random.randrange(total) while choice > weights[0]: choice -= weights[0] weights.pop(0) actions.pop(0) return actions[0] Loosely couple the actions from their weightings, so you can change them independently. Here's a decorator that populates a dictionary with weights and actions: def weight(value, storage): def set_weight(method): storage[method.__name__] = value return method return set_weight Here's how to use it: class A(object): weights = {} def __init__(self): self.weights = self.__class__.weights.copy() @weight(10, weights) def action_1(self): print "A.action_1" @weight(20, weights) def action_2(self): print "A.action_2" The class is now populated with a set of default weights, which is then copied to the instance. If you want to over-ride a particular weight, you don't need to make a subclass, you just change the instance: obj = A() obj.weights["action_1"] = 30 method = choose_with_weighting(obj.weights.keys(), obj.weights.values()) getattr(obj, method)() # call the method Hope this helps, -- Steven From mike at ipglobal.net Wed Sep 24 15:22:30 2008 From: mike at ipglobal.net (Support Desk) Date: Wed, 24 Sep 2008 14:22:30 -0500 Subject: More regex help In-Reply-To: <86k5d1qyw4.fsf@athena.daycos.com> References: <86k5d1qyw4.fsf@athena.daycos.com> Message-ID: <9CD4743616DF4F48A341A30FEA13C2D3@office.ipglobal.net> Kirk, That's exactly what I needed. Thx! -----Original Message----- From: Kirk Strauser [mailto:kirk at athena.daycos.com] Sent: Wednesday, September 24, 2008 11:42 AM To: python-list at python.org Subject: Re: More regex help At 2008-09-24T16:25:02Z, "Support Desk" writes: > I am working on a python webcrawler, that will extract all links from an > html page, and add them to a queue, The problem I am having is building > absolute links from relative links, as there are so many different types of > relative links. If I just append the relative links to the current url, some > websites will send it into a never-ending loop. >>> import urllib >>> urllib.basejoin('http://www.example.com/path/to/deep/page', '/foo') 'http://www.example.com/foo' >>> urllib.basejoin('http://www.example.com/path/to/deep/page', 'http://slashdot.org/foo') 'http://slashdot.org/foo' -- Kirk Strauser The Day Companies From patrickstinson.lists at gmail.com Mon Sep 8 22:17:57 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Mon, 8 Sep 2008 18:17:57 -0800 Subject: Incorrect compiler found building extension on windows Message-ID: <6214d7a20809081917n6a932f8gc9fd1a0bc44d1e9b@mail.gmail.com> I built python-2.5.1 from source using Visual Studio 2005, and am also trying to build my extension using distutils and Visual Studio 2005. Distutils complains about python being built with VS 2003, which is not on my system, and the only python binaries I have on my system are the ones I built from source using VS 2005. This leads me to believe that some other error is causing this hard-coded message to be printed. I am running python.exe from within the build dir, and "import site" works just fine. Running my setup.py --platform prints "UNKNOWN" for a list of platforms. Is it possible to build python using VS 2005 and also build extensions using the same cl.exe? If not is there a compiler config or something that I need to write? Thanks. From dudeja.rajat at gmail.com Sat Sep 27 08:29:34 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 27 Sep 2008 13:29:34 +0100 Subject: Regular expression help: unable to search ' # ' character in the file Message-ID: Hi, Can some help me with the regular expression. I'm looking to search # character in my file? My file has contents: ############################### Hello World ############################### length = 10 breadth = 20 height = 30 ############################### ############################### Hello World ############################### length = 20 breadth = 30 height = 40 ############################### I used the following search : import re fd = open(file, 'r') line = fd.readline pat1 = re.compile("\#*") while(line): mat1 = pat1.search(line) if mat1: print line line = fd.readline() But the above prints the whole file instead of the hash lines only. Please help Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.hildebrandt at gmail.com Wed Sep 10 13:43:31 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 10:43:31 -0700 (PDT) Subject: Reading binary data References: Message-ID: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> > signature, version, attr_count = struct.unpack('3cII', > yourfile.read(11)) > This line is giving me an error: Traceback (most recent call last): File "test.py", line 19, in signature, version, attr_count = struct.unpack('3cII', file.read(12)) ValueError: too many values to unpack From joefazee at gmail.com Wed Sep 17 08:26:06 2008 From: joefazee at gmail.com (A. Joseph) Date: Wed, 17 Sep 2008 05:26:06 -0700 Subject: recursive using the os.walk(path) from the os module Message-ID: Hi, I want to search through a directory and re-arrange all the files into e.g All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder. I`m thinking of doing something with the os.walk(path) method from os module, I need some ideal how the algorithm should look like, maybe recursive ..any deal? Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Wed Sep 10 18:00:41 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 08:00:41 +1000 Subject: Simple UDP server In-Reply-To: References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> Message-ID: Tzury, You may consider using pymills to simplify writing your UDP server and just concentrating on the behavior of the system. You can get a copy of the latest development branch by cloning it with Mercurial: hg clone http://hg.shortcircuit.net.au/pymills/ There is an example UDP Server in examples/net/ but I'll paste it here for your reference. Note, as stated before, UDP is a connectionless protocol (Datagram), concurrency doesn't apply. Also note, technically UDP doesn't guarantee reliability or the order of packets, however the reality is, it doesn't give you any feedback. You have to handle this yourself. Have fun, cheers James #!/usr/bin/env python # -*- coding: utf-8 -*- # vim: set sw=3 sts=3 ts=3 from pymills import event from pymills.event import * from pymills.net.sockets import UDPServer class EchoServer(UDPServer): @listener("connect") def onCONNECT(self, sock, host, port): print "New connection: %s:%d" % (host, port) @listener("disconnect") def onDISCONNECT(self, sock): print "Disconnection: %s" % sock @listener("read") def onREAD(self, sock, line): line = line.strip() print "%s: %s" % (sock, line) @listener("error") def onERROR(self, sock, msg): print "ERROR (%s): %s" % (sock, msg) def main(): server = EchoServer(1234) event.manager += server while True: try: manager.flush() server.poll() except KeyboardInterrupt: break if __name__ == "__main__": main() On Thu, Sep 11, 2008 at 5:33 AM, Tzury Bar Yochay wrote: >> Transmitting large binary data over UDP? That makes only sense for few >> applications like video and audio streaming. UDP does neither guarantee >> that your data is received nor it's received in order. For example the >> packages A, B, C, D might be received as A, D, B (no C). >> >> Can your protocol handle missing packages and out of order packages? > > I intend of using it for audio transmission and don't care about lose > or out of order. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From support.desk.ipg at gmail.com Wed Sep 24 10:22:32 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Wed, 24 Sep 2008 09:22:32 -0500 Subject: Regex Help In-Reply-To: References: Message-ID: Thanks for the reply, I found out the problem was occurring later on in the script. The regexp works well. -----Original Message----- From: Lawrence D'Oliveiro [mailto:ldo at geek-central.gen.new_zealand] Sent: Tuesday, September 23, 2008 6:51 PM To: python-list at python.org Subject: Re: Regex Help In message , Support Desk wrote: > Anybody know of a good regex to parse html links from html code? The one I > am currently using seems to be cutting off the last letter of some links, > and returning links like > > http://somesite.co > > or http://somesite.ph > > the code I am using is > > > regex = r'
' Can you post some example HTML sequences that this regexp is not handling correctly? From maebert at uos.de Mon Sep 15 20:03:08 2008 From: maebert at uos.de (Manuel Ebert) Date: Tue, 16 Sep 2008 02:03:08 +0200 Subject: Representation of python code ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 AFAIK epydoc can generate pretty graphs with graphviz on the fly, such as class hierarchies or call graphs. On Sep 14, 2008, at 3:44 PM, Barak, Ron wrote: > Hi Guys, > Is there a script/application, which gets as input python code, and > produces a (graphic) representation of the inter-relationships > between its classes/functions ? > Bye, > Ron. > -- > http://mail.python.org/mailman/listinfo/python-list -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIzve8cZ70OCIgLecRAjRbAKCRXHRKDJN+oxoJQ7S7z8i6sVCNxQCggowS PVV6g/BRKesRGErGHcAcURE= =q9Hs -----END PGP SIGNATURE----- From bignose+hates-spam at benfinney.id.au Sun Sep 21 20:46:19 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 22 Sep 2008 10:46:19 +1000 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <87ljxl0zz8.fsf@benfinney.id.au> Steven D'Aprano writes: > I have a class which is not intended to be instantiated. Instead of > using the class to creating an instance and then operate on it, I > use the class directly, with classmethods. Essentially, the class is > used as a function that keeps state from one call to the next. Classes aren't designed to keep state; state is kept in instances. I think you want Alex Martelli's 'Borg' pattern , which is a class where each instance shares the same state. -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but there's still a bug stuck in here from last time.? | _o__) ?_Pinky and The Brain_ | Ben Finney From psully at gmail.com Fri Sep 26 11:39:35 2008 From: psully at gmail.com (Patrick Sullivan) Date: Fri, 26 Sep 2008 08:39:35 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions Message-ID: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> Hello. I will be using some large data sets ("points" from 2 to 12 variables) and would like to use one class for each point rather than a list or dictionary. I imagine this is terribly inefficient, but how much? What is the cost of creating a new class? What is the cost of referencing a class variable? What is the cost of calling a class method to just return a variable? Key point: The point objects, once created, and essentially non- mutable. Static. Is there a way to "bind" a variable to a object method in a way that is more efficient than the function calling self.variable_name ? I'll run some profile tests later today but if anyone has any cost/ efficiency of object creation in python, or any other idioms related to variable creation, I'd greatly appreciate some links. Thanks! Patrick From keshet1 at umbc.edu Fri Sep 12 13:53:58 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Fri, 12 Sep 2008 13:53:58 -0400 Subject: manipulating files within 'for' In-Reply-To: References: <48CAA2AA.40809@umbc.edu> Message-ID: <48CAACB6.60106@umbc.edu> Emile van Sebille wrote: > Ben Keshet wrote: >> Hi Pythoneers, >> >> I have a question about a code I wrote with the help of someone. The >> code below copy a few lines from different files into one file. It >> works fine as it is given here and generates the new file >> 'pockets.out' correctly, but says:"....py returned exit code 0". >> However, if I add more values to 'receptor' (say, receptor = ['1AZM' >> '1ADS']) > > > At risk of stating the obvious, you _did_ put this in properly as > > receptors = ['1AZM', '1ADS'] > > ...right? > > Emile ...wrong. I thought I should omit the comma and didn't put it. I guess that stating the obvious should be the first attempt with beginners like me. Thanks for thinking about it (it's running perfect now). BK > > > > it gives an >> error: "Exception raised while running script". >> >> Can anyone please advice me? Why is it giving an error on multiple x >> but runs well with one (I made sure that all files and folders exist, >> etc.). What does exit code 0 mean? > > No error > >> what does "exception raised" mean? > > Error > > -- > http://mail.python.org/mailman/listinfo/python-list > From bobernet at nsa.invalid Sat Sep 27 03:08:00 2008 From: bobernet at nsa.invalid (Bob Cortopassi) Date: Sat, 27 Sep 2008 07:08:00 +0000 (UTC) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> Message-ID: On 2008-09-26, nntpman68 wrote: > - I'm annoyed by any spam. > It's tough to find good rules, but the incoming spams that I see > currently on comp.lang.python have certain criteas. > > - most email addresses from gmail. ...snip rest of good filter criteria... Killing all messages with "googlegroups" in the messageid will get rid of a vast majority of the spam. Killing anything with a gmail.com email address will end up killing more legitimate posters. -- email: echo "sbs at sbsrearg.pbz" | sed 's/s/o/g' | rot13 All posts from Google Groups are auto-killed. From marco.bizzarri at gmail.com Mon Sep 15 13:59:53 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 15 Sep 2008 19:59:53 +0200 Subject: [OT] Fwd: [XP] Test run times needed In-Reply-To: References: Message-ID: <3f0d61c40809151059sc6248afr24308cc6846d83c3@mail.gmail.com> This is a little Off Topic, so, I ask forgiveness in advance. I'm forwarding this message from Kent Beck from XP Mailing List. He's asking for people to send execution times of unit tests. Even though in the beginning of the mail he speaks about ant and xml formats, actually, a simple text file with test name - execution time is more than enough for doing some calculations. Regards Marco ---------- Forwarded message ---------- From: kentb Date: Tue, Sep 9, 2008 at 1:53 AM Subject: [XP] Test run times needed To: extremeprogramming at yahoogroups.com (Sorry for the cross post from JUnit.) All, Saff and I are working on ways in JUnit to shorten the validation phase of the inner programming loop (feature -> test -> code -> validate). One of the ideas is to find a general way to run suites faster by running tests in parallel. To find effective parallelization strategies, we need data on test run times. Rather than build big infrastructure to do this (which would undoubtedly be cool), I'd like to start with the simplest thing that could possibly work. So: If you have a long-running JUnit test suite and You run it using Ant and You can use the XML formattter ("") and You don't mind sharing your test names with me confidentially Would you please zip your reports and email them to me. If they're too big for email, please let me know and we'll figure out a backup plan. I'd appreciate any context you can provide--how long the suite has been in development, the experience level of the developers, whatever else you think we might need to know. The first data set I looked at was from DevCreek-->90M test runs from production coding representing more than 50 person-years of development. To my surprise, the test runs exhibit a power law distribution (way lots of fast tests, a few very long running tests, plot a histogram log-log and you get a straight line). I have no idea what this means, but it brings to mind the Asimov quote, "The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!' (I found it!) but 'That's funny ...'" I've found many power law distributions in the static and dynamic structure of code, but the mechanisms influencing test run times seem to be completely different than those influencing code structure. Anyway, I'd love to validate those findings. The Ant XML format seems like a good place to start. Alternatively, you could send me one or more files with test run times one per line. This would work for languages other than Java, which would also be interesting to analyze. Questions and comments appreciated. Yours in science, Kent Beck Three Rivers Institute __._,_.___ Messages in this topic (1) Reply (via web post) | Start a new topic Messages | Files | Photos | Links | Database | Polls | Members To Post a message, send it to: extremeprogramming at eGroups.com To Unsubscribe, send a blank message to: extremeprogramming-unsubscribe at eGroups.com ad-free courtesy of objectmentor.com Change settings via the Web (Yahoo! ID required) Change settings via email: Switch delivery to Daily Digest | Switch format to Traditional Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe Recent Activity 27 New Members Visit Your Group Yahoo! Finance It's Now Personal Guides, news, advice & more. Wellness Spot Embrace Change Break the Yo-Yo weight loss cycle. Yahoo! Groups Familyographer Zone Learn how to capture family moments. . __,_._,___ -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From bdesth.quelquechose at free.quelquepart.fr Thu Sep 4 13:57:01 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 19:57:01 +0200 Subject: Late initialization using __getattribute__ In-Reply-To: References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> Message-ID: <48c03d5d$0$29351$426a74cc@news.free.fr> bukzor a ?crit : >>>>> so unfortunately I think I need to use __getattribute__ >>>>> to do this. I'm doing all this just to make the connection not >>>>> actually connect until used. >>>> I may be dumb, but I don't get how this is supposed to solve your >>>> problem. But anyway : there's a known design pattern for what you're >>>> trying to do, that doesn't require mixins nor messing with >>>> __getattribute__ (which, I repeat, is more often than not something you >>>> *don't* want to do). The name of the design pattern is "proxy". I >>>> strongly suggest that you 1/ try to cure the real problem instead of >>>> hacking around and 2/ read about the proxy design pattern. >>>> My 2 cents... >>> I like the idea of mix-ins, but can't figure out how to make a proxy >>> work that way. >> You mean, "how to use a proxy for lazy initialization" ? Heck, that's >> the exact use case in the GoF. > > I mean, "how to make a MixIn class that uses the proxy pattern". That's not how proxies work. They use composition/delegation, not MI. >I'd > like to be able to do something like this: > > class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ..., > VanillaCursor): pass Yuck. Sorry, but it reminds me of the worst MI abuses in Zope2. (snip) > My toy example turned out to be not the best representation of the > problem. This is often the case with toy examples. > The base class has attributes that "exist" but either throw errors or > segfault > if used before reconnect() is called. Then these attributes should probably call reconnect() by themselves. Decorators and/or computed attributes may help here. From tjreedy at udel.edu Fri Sep 26 19:07:36 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 19:07:36 -0400 Subject: Running IDLE on 3.0rc1 Message-ID: I have not seen this posted, so... To run IDLE with Python3.0rc1, edit Python30/Libs/idlelib/run.py, and change "set_daemon(True)" to "daemon = True" and save. (This is about line 75, and the only appearance of 'daemon'.) Otherwise, you get error message about not starting a subprocess. tjr From stefan_ml at behnel.de Fri Sep 5 01:13:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Sep 2008 07:13:37 +0200 Subject: xml + mmap cross In-Reply-To: References: <48BF8AC8.6030509@behnel.de> Message-ID: <48c0c001$0$9319$9b4e6d93@newsspool2.arcor-online.net> Hi, this discussion seems pretty much off-topic for a Python list. castironpi wrote: > In an XML file, entries are stored in serial, sort of like this. > > AAA BBB CCC DDD > > Or more recognizably, > > somethingsomething > > Point is, to change something to something else, you > have to recopy everything after that. > > AAA BBB CCC DDD > AAA BBBb CCC DDD > > requires 7 writes, 'b CCC DDD', not 1. > > I want to use a simple tree structure to store: > > 0 A-> None, 1 > 1 B-> None, 2 > 2 C-> 3, None > 3 D-> None, None > > Each node maps to 'Next, Child', or more accurately, 'Next Sibling, > First Child'. Do I understand you right: you want to access serialised XML data as a memory mapped file and operate directly on the byte data? You would still have to decode the complete byte sequence to parse it and build your index structure in that case. How do you plan to store the pointers to a node's next sibling/child? And how do you keep them updated over insertions/deletions? That, plus the copy overhead in a sequential file, will be very costly on each change. > You get constant time updates to contents, and log-time searches. Every XML tree structure gives you log-time searches. But how do you achieve constant time updates in a sequential file? Stefan From mensanator at aol.com Sun Sep 28 18:11:49 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 28 Sep 2008 15:11:49 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: <4631f865-3fa1-4b0c-9cb2-4bb5ed35079f@m44g2000hsc.googlegroups.com> On Sep 28, 4:02?pm, Tim Chase wrote: > > Wondering if there is a better way to generate string of numbers with > > a length of 5 which also can have a 0 in the front of the number. > > If you want to resample the same digit multiple times, either of these > two will do: > > ?>>> from random import choice > ?>>> ''.join(str(choice(range(10))) for _ in range(5)) > '06082' > > ?>>> from string import digits > ?>>> ''.join(choice(digits) for _ in range(5)) > '09355' > > If you need to prevent the digits from being reused > > ?>>> d = list(digits) > ?>>> random.shuffle(digit) > ?>>> ''.join(d[:5]) > '03195' > > I suspect that the zfill responses don't have the property of equally > distributed "randomness", as the first digit may more likely be a zero. > ? The methods here should give equal probabilities for each choice in > each place. Does he want equal probabilities of each digit in each place? > > -tkc From barry at python.org Thu Sep 18 01:40:18 2008 From: barry at python.org (Barry Warsaw) Date: Thu, 18 Sep 2008 01:40:18 -0400 Subject: RELEASED Python 2.6rc2 and 3.0rc1 Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the second and final planned release candidate for Python 2.6, as well as the first release candidate for Python 3.0. These are release candidates, so while they are not suitable for production environments, we strongly encourage you to download and test them on your software. We expect only critical bugs to be fixed between now and the final releases. Currently Python 2.6 is scheduled for October 1st, 2008. Python 3.0 release candidate 2 is planned for October 1st, with the final release planned for October 15, 2008. If you find things broken or incorrect, please submit bug reports at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 website: http://www.python.org/download/releases/2.6/ and the Python 3.0 web site: http://www.python.org/download/releases/3.0/ See PEP 361 for release schedule details: http://www.python.org/dev/peps/pep-0361/ Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSNHpw3EjvBPtnXfVAQLW9wP/RBCaUvhuheIh+BjLLIHQFBQi7D3uVgqi l0+4fhhoKGJvtWklLfSM9I1prcjH/d6tzUu4fIOjX7aM+wZSG++vkfmBoehnhyZW AvU9Lax4mqDwhOJA2QA0WMx0obpYYVHeUl7D1g9kWzbRUkZDX9NZGMWThhEOC1qA UA3bBYbvWiQ= =BFNH -----END PGP SIGNATURE----- From edreamleo at charter.net Sun Sep 14 10:20:41 2008 From: edreamleo at charter.net (Edward K Ream) Date: Sun, 14 Sep 2008 09:20:41 -0500 Subject: ANN: Leo 4.5.1 final released Message-ID: <%69zk.4676$rV4.3209@newsfe03.iad> Leo 4.5.1 final is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo 4.5.1 final fixes several important bugs in Leo 4.5 final: - Eliminated spurious error messages in the goto-global-line command. - @shadow files with unknown file extensions now work properly. - Leo's installer now properly finds Python's install directory. Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.5: -------------------------- - Full support for @shadow files in Leo's core. - Major improvements to Leo's key binding code. - The beginning of usable vim-like bindings. - uA's may now be associated with vnodes in @thin and @shadow files. - Several major reorganizations of Leo's code: including sax-based parsing, support for the Graph world (unified nodes), and simplified drawing code. - Leo is now an installable package. - Prepared code to be ready for Python 3.0. - Many small improvements and bug fixes. Quote of the month: ------------------- Squeak and Leo have been two of the most significant technologies to redefine my personal computer experience and the ideas behind computing. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Forum: http://groups.google.com/group/leo-editor Download: http://sourceforge.net/project/showfiles.php?group_id=3458 Bzr: http://code.launchpad.net/leo-editor/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From kem1723 at yahoo.com Wed Sep 3 19:57:08 2008 From: kem1723 at yahoo.com (Kevin McKinley) Date: Wed, 3 Sep 2008 16:57:08 -0700 (PDT) Subject: Help with Tkinter Label Widget Message-ID: <293826.25281.qm@web83915.mail.sp1.yahoo.com> Below i've put the code for a program that i wrote. I need help on lines 384-403. If you run this program you will notice on the first tab when have it produce an answer the $ is surrounded with {$}. How can i get rid of that? from Tkinter import * class MyApp: def __init__(self, parent): self.myparent = parent self.frame1 = Frame(parent) self.frame1.grid(row=0, column=0) self.frame2 = Frame(parent) self.frame2.grid(row=0, column=0) self.frame3 = Frame(parent) self.frame3.grid(row=0, column=0) self.frame4 = Frame(parent) self.frame4.grid(row=0, column=0) self.a = self.b = self.c = self.d = 0 self.COG1 = DoubleVar(); self.COG2 = DoubleVar(); self.COG3 = DoubleVar(); self.COG4 = DoubleVar() self.GP1 = DoubleVar(); self.PrInc = DoubleVar(); self.markupPrice = DoubleVar() self.tab1Func(1) def tab1Func(self, event): self.tab1 = Button(self.frame1, width=14, relief=FLAT, bg="white", text="Multi-Markup") self.tab1.bind("", self.switch1) self.tab1.grid(row=0, column=0) self.tab2 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") self.tab2.bind("", self.switch2) self.tab2.grid(row=0, column=1) self.tab3 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") self.tab3.bind("", self.switch3) self.tab3.grid(row=0, column=2) self.tab4 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") self.tab4.bind("", self.switch4) self.tab4.grid(row=0, column=3) self.tab1Title = Label(self.frame1, font="bold", relief=GROOVE, text="Multi-Markup Calculator") self.tab1Title.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) self.tab1Entry1 = Entry(self.frame1, textvariable=self.COG1) self.tab1Entry1.select_range(0, END) self.tab1Entry1.bind("", self.multiMarkup) self.tab1Entry1.focus_force() self.tab1Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.tab1Entry1Title= Label(self.frame1, text="Enter COG:") self.tab1Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.tab1CalcButton = Button(self.frame1, text="Calculate") self.tab1CalcButton.bind("", self.multiMarkup) self.tab1CalcButton.bind("", self.multiMarkup) self.tab1CalcButton.grid(padx=2, pady=2, row=3, column=1, columnspan=2, sticky=W+E) self.tab1Header = Label(self.frame1, font="bold", relief=GROOVE, text="Gross Profit % Markup Price") self.tab1Header.grid(padx=2, pady=2, row=4, column=0, columnspan=4, sticky=W+E) self.tab1GP1 = Label(self.frame1, width=4,relief=RIDGE, bg="white", text="5%") self.tab1GP1.grid(padx=2, pady=2, row=5, column=1) self.tab1GP2 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="10%") self.tab1GP2.grid(padx=2, pady=2, row=6, column=1) self.tab1GP3 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="15%") self.tab1GP3.grid(padx=2, pady=2, row=7, column=1) self.tab1GP4 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="18%") self.tab1GP4.grid(padx=2, pady=2, row=8, column=1) self.tab1GP5 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="20%") self.tab1GP5.grid(padx=2, pady=2, row=9, column=1) self.tab1GP6 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="21%") self.tab1GP6.grid(padx=2, pady=2, row=10, column=1) self.tab1GP7 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="22%") self.tab1GP7.grid(padx=2, pady=2, row=11, column=1) self.tab1GP8 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="23%") self.tab1GP8.grid(padx=2, pady=2, row=12, column=1) self.tab1GP9 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="24%") self.tab1GP9.grid(padx=2, pady=2, row=13, column=1) self.tab1GP10 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="25%") self.tab1GP10.grid(padx=2, pady=2, row=14, column=1) self.tab1GP11 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="26%") self.tab1GP11.grid(padx=2, pady=2, row=15, column=1) self.tab1GP12 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="27%") self.tab1GP12.grid(padx=2, pady=2, row=16, column=1) self.tab1GP13 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="28%") self.tab1GP13.grid(padx=2, pady=2, row=17, column=1) self.tab1GP14 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="29%") self.tab1GP14.grid(padx=2, pady=2, row=18, column=1) self.tab1GP15 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="30%") self.tab1GP15.grid(padx=2, pady=2, row=19, column=1) self.tab1GP16 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="31%") self.tab1GP16.grid(padx=2, pady=2, row=20, column=1) self.tab1GP17 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="33%") self.tab1GP17.grid(padx=2, pady=2, row=21, column=1) self.tab1GP18 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="35%") self.tab1GP18.grid(padx=2, pady=2, row=22, column=1) self.tab1GP19 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="40%") self.tab1GP19.grid(padx=2, pady=2, row=23, column=1) self.tab1GP20 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="45%") self.tab1GP20.grid(padx=2, pady=2, row=24, column=1) self.tab1Markup1 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup1.grid(padx=2, pady=2, row=5, column=2, sticky=E) self.tab1Markup2 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup2.grid(padx=2, pady=2, row=6, column=2, sticky=E) self.tab1Markup3 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup3.grid(padx=2, pady=2, row=7, column=2, sticky=E) self.tab1Markup4 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup4.grid(padx=2, pady=2, row=8, column=2, sticky=E) self.tab1Markup5 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup5.grid(padx=2, pady=2, row=9, column=2, sticky=E) self.tab1Markup6 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup6.grid(padx=2, pady=2, row=10, column=2, sticky=E) self.tab1Markup7 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup7.grid(padx=2, pady=2, row=11, column=2, sticky=E) self.tab1Markup8 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup8.grid(padx=2, pady=2, row=12, column=2, sticky=E) self.tab1Markup9 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup9.grid(padx=2, pady=2, row=13, column=2, sticky=E) self.tab1Markup10 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup10.grid(padx=2, pady=2, row=14, column=2, sticky=E) self.tab1Markup11 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup11.grid(padx=2, pady=2, row=15, column=2, sticky=E) self.tab1Markup12 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup12.grid(padx=2, pady=2, row=16, column=2, sticky=E) self.tab1Markup13 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup13.grid(padx=2, pady=2, row=17, column=2, sticky=E) self.tab1Markup14 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup14.grid(padx=2, pady=2, row=18, column=2, sticky=E) self.tab1Markup15 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup15.grid(padx=2, pady=2, row=19, column=2, sticky=E) self.tab1Markup16 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup16.grid(padx=2, pady=2, row=20, column=2, sticky=E) self.tab1Markup17 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup17.grid(padx=2, pady=2, row=21, column=2, sticky=E) self.tab1Markup18 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup18.grid(padx=2, pady=2, row=22, column=2, sticky=E) self.tab1Markup19 = Label(self.frame1, width=12, relief=RIDGE, bg="white") self.tab1Markup19.grid(padx=2, pady=2, row=23, column=2, sticky=E) self.tab1Markup20 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") self.tab1Markup20.grid(padx=2, pady=2, row=24, column=2, sticky=E) def tab2Func(self, event): self.tab1 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") self.tab1.bind("", self.switch1) self.tab1.grid(row=0, column=0) self.tab2 = Button(self.frame2, width=14, relief=FLAT, bg="white", text="Single Markup") self.tab2.bind("", self.switch2) self.tab2.grid(row=0, column=1) self.tab3 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") self.tab3.bind("", self.switch3) self.tab3.grid(row=0, column=2) self.tab4 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") self.tab4.bind("", self.switch4) self.tab4.grid(row=0, column=3) self.tab2Title = Label(self.frame2, font="bold", relief=GROOVE, text="Single Markup Calculator") self.tab2Title.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) self.tab2Entry1 = Entry(self.frame2, textvariable=self.COG2) self.tab2Entry1.select_range(0, END) self.tab2Entry1.bind("", self.singleMarkup) self.tab2Entry1.focus_force() self.tab2Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.tab2Entry2 = Entry(self.frame2, textvariable=self.GP1) self.tab2Entry2.select_range(0, END) self.tab2Entry2.bind("", self.singleMarkup) self.tab2Entry2.focus_force() self.tab2Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.tab2Entry1Title= Label(self.frame2, text="Enter COG:") self.tab2Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.tab2Entry2Title= Label(self.frame2, text="Enter GP %:") self.tab2Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.tab2CalcButton = Button(self.frame2, text="Calculate") self.tab2CalcButton.bind("", self.singleMarkup) self.tab2CalcButton.bind("", self.singleMarkup) self.tab2CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) self.tab2Header = Label(self.frame2, font="bold", relief=GROOVE) self.tab2Header["text"] = self.GP1.get(), "%","Markup" self.tab2Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) self.tab2Markup1 = Label(self.frame2, width=10, font="bold", relief=GROOVE, bg="white") self.tab2Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) def tab3Func(self, event): self.tab1 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") self.tab1.bind("", self.switch1) self.tab1.grid(row=0, column=0) self.tab2 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") self.tab2.bind("", self.switch2) self.tab2.grid(row=0, column=1) self.tab3 = Button(self.frame3, width=14, relief=FLAT, bg="white", text="Product Increase") self.tab3.bind("", self.switch3) self.tab3.grid(row=0, column=2) self.tab4 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") self.tab4.bind("", self.switch4) self.tab4.grid(row=0, column=3) self.tabTitle = Label(self.frame3, font="bold",relief=GROOVE, text="Product Increase Calculator") self.tabTitle.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) self.tab3Entry1 = Entry(self.frame3, textvariable=self.COG3) self.tab3Entry1.select_range(0, END) self.tab3Entry1.bind("", self.priceIncrease) self.tab3Entry1.focus_force() self.tab3Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.tab3Entry2 = Entry(self.frame3, textvariable=self.PrInc) self.tab3Entry2.select_range(0, END) self.tab3Entry2.bind("", self.priceIncrease) self.tab3Entry2.focus_force() self.tab3Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.tab3Entry1Title= Label(self.frame3, text="Enter COG:") self.tab3Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.tab3Entry2Title= Label(self.frame3, text="Enter Increase %:") self.tab3Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.tab3CalcButton = Button(self.frame3, text="Calculate") self.tab3CalcButton.bind("", self.priceIncrease) self.tab3CalcButton.bind("", self.priceIncrease) self.tab3CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) self.tab3Header = Label(self.frame3, font="bold", relief=GROOVE) self.tab3Header["text"] = self.PrInc.get(), "%","Price","Increase" self.tab3Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) self.tab3Markup1 = Label(self.frame3, width=10, font="bold", relief=GROOVE, bg="white") self.tab3Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) def tab4Func(self, event): self.tab1 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") self.tab1.bind("", self.switch1) self.tab1.grid(row=0, column=0) self.tab2 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") self.tab2.bind("", self.switch2) self.tab2.grid(row=0, column=1) self.tab3 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") self.tab3.bind("", self.switch3) self.tab3.grid(row=0, column=2) self.tab4 = Button(self.frame4, width=14, relief=FLAT, bg="white", text="Calculate GP") self.tab4.bind("", self.switch4) self.tab4.grid(row=0, column=3) self.tabTitle = Label(self.frame4, font="bold",relief=GROOVE, text="Calculate GP") self.tabTitle.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) self.tab4Entry1 = Entry(self.frame4, textvariable=self.COG4) self.tab4Entry1.select_range(0, END) self.tab4Entry1.bind("", self.GpCalc) self.tab4Entry1.focus_force() self.tab4Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) self.tab4Entry2 = Entry(self.frame4, textvariable=self.markupPrice) self.tab4Entry2.select_range(0, END) self.tab4Entry2.bind("", self.GpCalc) self.tab4Entry2.focus_force() self.tab4Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) self.tab4Entry1Title= Label(self.frame4, text="Enter COG:") self.tab4Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) self.tab4Entry2Title= Label(self.frame4, text="Enter Markup $:") self.tab4Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) self.tab4CalcButton = Button(self.frame4, text="Calculate") self.tab4CalcButton.bind("", self.GpCalc) self.tab4CalcButton.bind("", self.GpCalc) self.tab4CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) self.tab4Header = Label(self.frame4, font="bold", relief=GROOVE) self.tab4Header["text"] = "Gross Profit" self.tab4Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) self.tab4Markup1 = Label(self.frame4, width=10, font="bold", relief=GROOVE, bg="white") self.tab4Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) def switch1(self, event): self.frame1.grid(sticky=N+S+E+W) self.frame2.grid_forget() self.frame3.grid_forget() self.frame4.grid_forget() self.tab1Entry1.focus_force() self.tab1Entry1.select_range(0, END) def switch2(self, event): if self.b == 0: self.tab2Func(1) self.b = 1 self.frame1.grid_forget() self.frame2.grid(sticky=N+S+E+W) self.frame3.grid_forget() self.frame4.grid_forget() self.tab2Entry1.focus_force() self.tab2Entry1.select_range(0, END) def switch3(self, event): if self.c == 0: self.tab3Func(1) self.c = 1 self.frame1.grid_forget() self.frame2.grid_forget() self.frame3.grid(sticky=N+S+E+W) self.frame4.grid_forget() self.tab3Entry1.focus_force() self.tab3Entry1.select_range(0, END) def switch4(self, event): if self.d == 0: self.tab4Func(1) self.d = 1 self.frame1.grid_forget() self.frame2.grid_forget() self.frame3.grid_forget() self.frame4.grid(sticky=N+S+E+W) self.tab4Entry1.focus_force() self.tab4Entry1.select_range(0, END) def multiMarkup(self, event): try: value = self.COG1.get() except ValueError: self.COG1 = DoubleVar() self.tab1Entry1["textvariable"] = self.COG1 self.tab1Entry1.select_range(0, END) self.tab1Markup1["text"] = "$", round(self.COG1.get()/.95, 2) self.tab1Markup2["text"] = "$", round(self.COG1.get()/.90, 2) self.tab1Markup3["text"] = "$", round(self.COG1.get()/.85, 2) self.tab1Markup4["text"] = "$", round(self.COG1.get()/.82, 2) self.tab1Markup5["text"] = "$", round(self.COG1.get()/.80, 2) self.tab1Markup6["text"] = "$", round(self.COG1.get()/.79, 2) self.tab1Markup7["text"] = "$", round(self.COG1.get()/.78, 2) self.tab1Markup8["text"] = "$", round(self.COG1.get()/.77, 2) self.tab1Markup9["text"] = "$", round(self.COG1.get()/.76, 2) self.tab1Markup10["text"] = "$", round(self.COG1.get()/.75, 2) self.tab1Markup11["text"] = "$", round(self.COG1.get()/.74, 2) self.tab1Markup12["text"] = "$", round(self.COG1.get()/.73, 2) self.tab1Markup13["text"] = "$", round(self.COG1.get()/.72, 2) self.tab1Markup14["text"] = "$", round(self.COG1.get()/.71, 2) self.tab1Markup15["text"] = "$", round(self.COG1.get()/.70, 2) self.tab1Markup16["text"] = "$", round(self.COG1.get()/.69, 2) self.tab1Markup17["text"] = "$", round(self.COG1.get()/.67, 2) self.tab1Markup18["text"] = "$", round(self.COG1.get()/.65, 2) self.tab1Markup19["text"] = "$", round(self.COG1.get()/.60, 2) self.tab1Markup20["text"] = "$", round(self.COG1.get()/.55, 2) def singleMarkup(self, event): try: value = self.COG2.get() except ValueError: self.COG2 = DoubleVar() self.tab2Entry1["textvariable"] = self.COG2 try: value = self.GP1.get() except ValueError: self.GP1 = DoubleVar() self.tab2Entry2["textvariable"] = self.GP1 self.tab2Entry1.focus_force() self.tab2Entry1.select_range(0, END) GP = 1 - (round((self.GP1.get()/100),2)) self.tab2Markup1["text"] = "$",round(self.COG2.get()/GP, 2) self.tab2Header["text"] = self.GP1.get(), "%","Markup" def priceIncrease(self, event): try: value = self.COG3.get() except ValueError: self.COG3 = DoubleVar() self.tab3Entry1["textvariable"] = self.COG3 try: value = self.PrInc.get() except ValueError: self.PrInc = DoubleVar() self.tab3Entry2["textvariable"] = self.PrInc self.tab3Entry1.focus_force() self.tab3Entry1.select_range(0, END) increase = 1+(self.PrInc.get()/100) self.tab3Markup1["text"] = "$",round((self.COG3.get()*increase),2) self.tab3Header["text"] = self.PrInc.get(), "%","Price","Increase" def GpCalc(self, event): try: value = self.COG4.get() except ValueError: self.COG4 = DoubleVar() self.tab4Entry1["textvariable"] = self.COG4 try: value = self.markupPrice.get() except ValueError: self.markupPrice = DoubleVar() self.tab4Entry2["textvariable"] = self.markupPrice self.tab4Entry1.focus_force() self.tab4Entry1.select_range(0, END) COG4 = self.COG4.get() markup = self.markupPrice.get() if COG4==0.0 or markup==0.0: self.tab4Markup1["text"] = "" else: GP = 100*(1-(self.COG4.get()/self.markupPrice.get())) self.tab4Markup1["text"] = round(GP, 2),"%" root = Tk() myapp = MyApp(root) root.mainloop() From sturlamolden at yahoo.no Fri Sep 12 18:37:07 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Sep 2008 15:37:07 -0700 (PDT) Subject: Python a good choice for experimenting with Win32 API? References: <98qdnS2nk4rpEVfVnZ2dnUVZ_qHinZ2d@comcast.com> Message-ID: <09601c7a-a138-4163-9265-286f87ef5767@y21g2000hsf.googlegroups.com> > (1) Would CPython be a good choice for this? How about iron python? How > about Jython (probably not). You can use CPython without any problems. Alternatives are pywin32, ctypes, cython, pyrex, Python C API. You can use .NET platform invoke from IronPython. You can use JNI from Jython, or any Win32 API wrapper that may exist for Java. > (2) What about callbacks? Which pythons can handle callbacks? Yes you can use Python functions or bound methods as callbacks. > (3) How easy it it define the C structs, enums and integer constants > necessary to call the windows API functions? It is easy if you can read C header files. > (4) Here is the code I'm struggling with presently (it is just not > cooperating: no errors just wrong results! Here is what it will look like with the pywin32 package: import win32api import win32con def compute(sLangId_, uCode_, uMapType_): hkl = win32api.LoadKeyboardLayout(sLangId_, win32con.KLF_ACTIVATE |win32con.KLF_SUBSTITUTE_OK|win32con.KLF_REPLACELANG) uResult_ = win32api.MapVirtualKeyEx(uCode_, uMapType_, hkl) return uResult_ With ctypes there is a little more work to do: import ctypes MAPVK_VK_TO_VSC = 0 MAPVK_VSC_TO_VK = 1 MAPVK_VK_TO_CHAR = 2 MAPVK_VSC_TO_VK_EX = 3 MAPVK_VK_TO_VSC_EX = 4 KLF_ACTIVATE = 1, KLF_SUBSTITUTE_OK = 2 KLF_REORDER = 8 KLF_REPLACELANG = 0x10 KLF_NOTELLSHELL = 0x80 KLF_SETFORPROCESS = 0x00100 KLF_SHIFTLOCK = 0x10000 KLF_RESET = 0x40000000 LoadKeyboardLayout = ctypes.windll.user32.LoadKeyboardLayout LoadKeyboardLayout.argtypes = (ctypes.c_wchar_p, ctypes.c_uint) LoadKeyboardLayout.restype = ctypes.c_void_p UnloadKeyboardLayout = ctypes.windll.user32.UnloadKeyboardLayout UnloadKeyboardLayout.argtypes = (ctypes.c_void_p,) UnloadKeyboardLayout.restype = ctypes.c_int MapVirtualKeyEx = ctypes.windll.user32.UnloadKeyboardLayout MapVirtualKeyEx.argtypes = (ctypes.c_uint, ctypes.c_uint, ctypes.c_void_p) MapVirtualKeyEx.restype = ctypes.c_uint def compute(sLangId_, uCode_, uMapType_): hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE|KLF_SUBSTITUTE_OK| KLF_REPLACELANG) uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl) return uResult_ This is similar to your code, so it will have the same bugs. From bearophileHUGS at lycos.com Thu Sep 11 12:28:43 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Sep 2008 09:28:43 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: Message-ID: <73be6644-6538-4199-a565-4cf4bc34149c@j22g2000hsf.googlegroups.com> hofer: > The real example would be more like: > name,age,country = itemgetter('name age country'.split())(x) # or any > of my above versions That solution is very clever, and the inventor smart, but it's too much out of standard and complex to be used in normal real code. Learning tricks is useful, but then in real code you have to use then only once in a while. A list comp is quite more easy to understand for Python programmers. Bye, bearophile From marco.bizzarri at gmail.com Thu Sep 4 07:09:52 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 13:09:52 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <3f0d61c40809040409v3ee40da3h7eb0703009e78f06@mail.gmail.com> Sorry... pressed enter but really didn't want to. As I said, let's say I have a class class A: def __init__(self): self.x = None Python makes the decision to allow the developers to directly access the attribute "x", so that they can directly write: "a.x = 1", or whatever; this has for me the unfortunate side effect that if I write, for example "a.y = 1", when I really wanted to write "a.x = 1" no one cares about it, and I'm unable to spot this error until later. Of course, I know that while I'm fresh, I've a good knowledge of the code, and anything else, I will be able to avoid such stupid errors; however, I'm afraid of the times when I'm tired, when I have to put my hands on the code of someone else, and so on. Please, understand that I'm not stating that python is wrong... after all, if it is wrong, I can move to a language like Java, which has a different approach on it. I'm really very interested in reading past discussion on it, if they are available. Regards Marco On Thu, Sep 4, 2008 at 12:57 PM, Marco Bizzarri wrote: > Let's say I've a class a, where I can write: > > > > -- > Marco Bizzarri > http://notenotturne.blogspot.com/ > http://iliveinpisa.blogspot.com/ > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From ptmcg at austin.rr.com Wed Sep 17 08:57:46 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 17 Sep 2008 05:57:46 -0700 (PDT) Subject: Python OOP advice References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> Message-ID: <6089e023-18f6-4c93-a2a4-f933eac786b5@f63g2000hsf.googlegroups.com> On Sep 17, 6:50?am, Simon Hibbs wrote: > I'm rewriting a design application for a science fiction game. in it > you design your own starships. Each component has a mass and cost, but > the mass can either be fixed or it can be expressed as a percentage of > the tonnage of the overall ship. > > Orriginaly I thought I'd need to have a hull object which contains > component objects, but the component objects need access to members of > the hull object (e.g. the hull size) so that looks messy to implement. > I would not put this kind of intelligence into the components. I think the issue here is that your Ship container is not really just a generic container of ship components, but an assembly with some specific requirements (must have 1 and only 1 hull, must have 1 or more engines, etc.) and structure. I would create a class called ShipDesign that had specific members for those components that have special logic attached to them, and then more generic list members for collection-ish components. Since the hull is such a significant constraint, I would make it an initialization argument. I would also put some kind of property on hull representing its "capacity" (oh I see, you have something call hull_size). One way to generalize the fixed-cost vs. percentage-cost components would be to have all components implement a compute_load function that takes the ShipDesign as an argument. Those that are fixed-cost simply return their fixed value, those that are percentage-cost can return their percentage of the ShipDesign's hull.hull_size - this leaves the door open for other variations on load, that could be based on other properties besides the hull size. Here's how I envision your ShipDesign class: class ShipDesign(object): def __init__(self, hull): self.hull = hull self.engines = [] self.shields = [] self.weapons = [] self.other = [] def compute_consumed_capacity(self): load = 0 for itemlist in (self.engines, self.shields, self.weapons, self.other)): load += sum(item.compute_load(self) for item in itemlist) return load def add_engine(self,e): engload = e.compute_load(self) if engload + self.compute_consumed_capacity() > self.hull.hull_size: raise ExceededHullCapacityException() if len(self.engines) == MAXIMUM_ALLOWED_ENGINES: raise ExceededMaximumConfigurationLimitException() self.engines.append(e) def set_hull(self, hull): if self.compute_consumed_capacity() <= hull.hull_size: self.hull = hull else: raise NewHullTooSmallException() def is_valid(self): if not self.engines: raise InvalidDesignException("must have at least 1 engine") ...etc... class GenericItem(object): def __init__(self, name, load): self.name = name self.load = load crewQuarters = GenericItem("Crew Quarters", 50) disco = GenericItem("Discotheque", 10) ...etc... Once you have a valid ShipDesign, you can then use it to construct multiple Ship instances. Here is how I would work around your "only one hull at a time" problem. Define several classes for different kinds of hulls: class CheapHull(Hull): capacity = 100 name = "EconoHull 1000" class MediumHull(Hull): capacity = 500 name = "Mainliner X50" class TopOTheLineHull(Hull): capacity = 1000 name = "LuxeMaster 5000" and then create ship designs with a CheapHull, a MediumHull, or a TopOTheLineHull. In this case, the member variable of the ShipDesign is really a class, which you would later use to construct hull instances as part of making Ship instances from your ShipDesign. class Ship(object): def __init__(self, design): self.hull = design.hull() self.engines = design.engines[:] ...etc... This way, each Ship will have its own Hull instance, so that you can track instance-specific properties, such as damage percentage. If you don't want to hard-code the hull types, then you can do something similar with instances of a generic Hull class, which you would then use as prototypes when constructing Ship instances. Just be careful that you don't accidentally have all ships sharing the same hull instance! -- Paul From stef.mientki at gmail.com Tue Sep 30 13:57:55 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 19:57:55 +0200 Subject: Would this be called a bug in inspect ? Message-ID: <48E268A3.4050900@gmail.com> hello, I'm not familiar with inspect, but I get an error (see below) in getmembers ( wx ) Of course this is bug in wx . But would you also call this a bug in inspect ? (inspect crashes and doesn't continue with th rest of the code, nor it returns the already gathered data) thanks, Stef >>> import wx >>> wx.version() '2.8.7.1 (msw-unicode)' >>> from inspect import * >>> getmembers(wx) Traceback (most recent call last): File "", line 1, in File ")>)>>", line 517, in pphook File "P:\Python\Lib\pprint.py", line 55, in pprint printer.pprint(object) File "P:\Python\Lib\pprint.py", line 106, in pprint self._format(object, self._stream, 0, 0, {}, 0) File "P:\Python\Lib\pprint.py", line 129, in _format rep = self._repr(object, context, level - 1) File "P:\Python\Lib\pprint.py", line 195, in _repr self._depth, level) File "P:\Python\Lib\pprint.py", line 207, in format return _safe_repr(object, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 283, in _safe_repr orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 283, in _safe_repr orepr, oreadable, orecur = _safe_repr(o, context, maxlevels, level) File "P:\Python\Lib\pprint.py", line 292, in _safe_repr rep = repr(object) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' From dmitry at makovey.net Sun Sep 28 16:26:59 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Sun, 28 Sep 2008 20:26:59 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> <91e62d70-73fb-4ecc-ae2e-d950a5f7ea6b@k13g2000hse.googlegroups.com> <877b889b-c385-4e2b-abe9-17669eca09b8@d70g2000hsc.googlegroups.com> Message-ID: George Sakkis wrote: > FYI, in case you missed it the final version doesn't need a Proxy base > class, just inherit from object. Also lowercased ProxyMethod to look > similar to staticmethod/classmethod: I cought that, just quoted the wrong one :) > class A(object): > > def __init__(self, b1, b2): > self.b1 = b1 > self.b2 = b2 > > @proxymethod > def bmethod(self): > return self.b1 > > @proxymethod > def bmethod2(self): > return self.b2 > > George From gary at byoteki.com Tue Sep 30 21:52:53 2008 From: gary at byoteki.com (Gary M. Josack) Date: Tue, 30 Sep 2008 21:52:53 -0400 Subject: __buitins__ key added during eval() In-Reply-To: References: Message-ID: <48E2D7F5.90201@byoteki.com> William Purcell wrote: > I want to use eval to evaluate wx.TextCtrl inputs. How can I keep > python from adding the __builtins__ key to mydict when I use it with > eval? Other wise I have to __delitem__('__builtins__') everytime I use > eval? > > >>> mydict = {'a':2,'b':3} > >>> eval('a*b',mydict) > 6 > >>> mydict > {'a': 2, '__builtins__': {'IndexError': 'exceptions.IndexError'>, ...(I'll spare you the rest)...}, 'b': 3} > > Also, how come eval has this behavior? Is it desirable? > > -Bill > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list no too sure, but eval('a*b', None, mydict) seems to work how you expect. From rsgalloway at gmail.com Fri Sep 26 02:47:27 2008 From: rsgalloway at gmail.com (rsgalloway at gmail.com) Date: Thu, 25 Sep 2008 23:47:27 -0700 (PDT) Subject: How to read a jpg bytearray from a Flash AS3 file Message-ID: I'm trying to save an image from a Flash AS3 to my server as a jpg file. I found some PHP code to do this, but I want to do this in Python. I'm not quite sure how to convert the following code to Python. It's mainly the $GLOBALS["HTTP_RAW_POST_DATA"] part I don't know how to convert. source: http://designreviver.com/tutorials/actionscript-3-jpeg-encoder-revealed-saving-images-from-flash/ From prologic at shortcircuit.net.au Tue Sep 30 01:10:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 30 Sep 2008 15:10:32 +1000 Subject: python & sms In-Reply-To: References: Message-ID: sui, I am sure you'll find many web services that you can use to send SMS'. Your problem would then become one of learning how to communicate and access web services in Python. Start with: * urllib and urllib2 * xmlrpc There are others... cheers James On Tue, Sep 30, 2008 at 1:47 PM, sui wrote: > Hii > i want a script to send sms to any mobile..... > can u help me ?? > > Thanks in advance...... > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From sjoerd at acm.org Thu Sep 11 11:27:33 2008 From: sjoerd at acm.org (Sjoerd Mullender) Date: Thu, 11 Sep 2008 17:27:33 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> Message-ID: <20080911152733.8D9A74802F@ottar.ins.cwi.nl> Grant Edwards writes: > Could whoever is responsible for the gateway that is grabbing > my postings off of Usenet and e-mailing them out please fix the > headers in the mail messages so that I don't get the bounce > messages? > > While you're at it, might as well fix it for everybody else > too. ;) > > Its a bit rude to send out mass e-mail messages with headers > faked up so that the bounce messages go to somebody else. Messages you submit to the newsgroup are forwarded to the mailing list. When mail messages bounce, the MTA (Message Transfer Agent--the program that handles mail) *should* send the bounce message to whatever is in the Sender header, and only if that header does not exist, should it use the From header. Messages forwarded by the gateway get a Sender header which points back to the gateway. In other words, if a message gets bounced back to the From address, the MTA does it incorrectly. There is nothing the list administrator can do about it. You can try complaining to the postmaster of the bouncing system, but that's about it. In other words, your question in the first paragraph is already implemented and was implemented from the beginning. It is not the gateway's fault that there are systems that don't follow the standards. -- Sjoerd Mullender, python-list administrator From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 11:08:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 17:08:36 +0200 Subject: Using an existing instance as parent In-Reply-To: <2ac46f80-76d5-4270-bc86-1f07a5cbd477@z72g2000hsb.googlegroups.com> References: <2ac46f80-76d5-4270-bc86-1f07a5cbd477@z72g2000hsb.googlegroups.com> Message-ID: <48bc0520$0$23840$426a34cc@news.free.fr> Andr? a ?crit : > Hi, I was trying to find a way to set, upon __init__() the parent of a > class to an existing instance. ??? Sorry but I just can't make any sense of this. > Here is a minimal example of what I'm > trying to do: > > class A(object): > def __init__(self, x): > self.x = x > > class B(A): > def __init__(self, *args): > if not isinstance(args[0], A): > super(B, self).__init__(args[0]) > else: > self = args[0] Rebinding an argument only affect the current namespace. > self.y = args[1] > > b = B(4, 6) > print 'b:', b.x, b.y, type(b) > > a = A(7) > c = B(a, 3) # Means: please set c parent's using instance "a" > print 'c:', c.x, c.y, type(c) > > This does not work as can be tested. The reason I'm in search for a > solution in this area is that in our project, "A" is not copy-able (it > is written using a boost.python binding to a C++ object that does not > allow copying) - so I can't simply call, inside "B's __init__()", a > copy constructor for A. Ok, I think I get the point... When an A instance is passed as first arg, you'd like to use this instance's state to call super(B).__init__ ? If so, here's a possible solution (Q&D, to be corrected according to real use case, etc): import copy class B(A): def __init__(self, *args): if isinstance(args[0], A): x = copy.copy(args[0].x) # if it's a mutable and you want a copy else: x = args[0] super(B, self).__init__(x) self.y = args[1] Be sure to carefully read copy's doc. From castironpi at gmail.com Tue Sep 9 20:48:35 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 9 Sep 2008 17:48:35 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: On Sep 9, 5:58?pm, Steven D'Aprano wrote: > On Tue, 09 Sep 2008 14:59:19 -0700, castironpi wrote: > > I will try my idea again. ?I want to talk to people about a module I > > want to write and I will take the time to explain it. ?I think it's a > > "cool idea" that a lot of people, forgiving the slang, could benefit > > from. ?What are its flaws? > > [snip long description with not-very-credible use-cases] Steven, > You've created a solution to a problem which (probably) only affects a > very small number of people, at least judging by your use-cases. Who has > a 4GB XML file, and how much crack did they smoke? I judge from the existence of 'shelve' and 'pickle' modules, and relational database packages, that the problem I am addressing is not rare. It could be the millionaire investor across the street, the venture capitalist down the hall, or the guy with a huge CD catalog. > Castironpi, what do *you* use this proof-of-concept module for? Honestly, nothing yet. I just wrote it. My user community and customer base are very small. Originally, I wanted to store variable- length strings in a file, where shelves and databases were overkill. I created it for its beauty, sorry to disappoint. > Don't > bother tell us what you think *we* should use it for. Tell us what you're > using it for, or at least what somebody else is using it for. If this is > just a module that you think will be cool, I don't like your chances of > people caring. There is no shortage of "cool" software that isn't useful > for anything, and unlike eye-candy, nobody is going to use your module > just because they like the algorithm. Unfortunately, nobody is going to care about most of the uses I have for it 'til I have a job. I'm goofing around with a laptop, remembering when my databases professor kept dropping the ball on VARCHARs. If you want a sound byte, think, "imagine programming without 'new' and 'malloc'." > If you don't have an existing application for the software, then explain > what it does (not how) and give some idea of the performance ("it's alpha > and written in Python and really slow, but I will re-write it in C and > expect it to make a billion random accesses in a 10GB file per > millisecond", or whatever). You might be lucky and have somebody say > "Hey, that's just the tool I need to solve my problem!". I wrote a Rope implementation just to test drive it. It exceeded the native immutable string type at 2 megs. It used 'struct' instead of 'ctypes', so that number could conceivably come down. I am intending to leave it in pure Python, so there. > -- > Steven Pleasure chatting as always sir. From wuwei23 at gmail.com Fri Sep 26 23:22:09 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 26 Sep 2008 20:22:09 -0700 (PDT) Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: <40efa068-688c-4dcf-b11e-938c0d4d006a@w39g2000prb.googlegroups.com> On Sep 27, 12:39?pm, process wrote: > ' '.join([`x * x` for x in range(1, 6)]) > > exactly what does this symbol do and what does it stand for? `` is the same as repr(). I'm pretty sure the backtick operator has been removed from 3.0. In the context of the code sample you posted, it appears to be used to convert the result of x*x into a string for the join method, but I personally think it's a misuse of repr() and think a call to str() would be more appropriate: >>> ' '.join((str(x * x) for x in range(1,6))) '1 4 9 16 25' From alexandru.palade at sellerengine.com Mon Sep 1 04:21:56 2008 From: alexandru.palade at sellerengine.com (Alexandru Palade) Date: Mon, 01 Sep 2008 11:21:56 +0300 Subject: how to find position of dictionary values In-Reply-To: References: Message-ID: <48BBA624.5010501@sellerengine.com> lookfor = 'dfsdf' for item, value in kev.items(): if lookfor in value: print item print value.index(lookfor) break # assuming you only want one result You can also skip the 'if' verification in which case you need to catch ValueError exception in case there is no such entry in the current list. Hope it helps. lee wrote: > hi, > i have a dictionary as follows : > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > if user is enters the 3rd item of key phno, ie "dfsdf" in my dict, > how can i find it is the third item in the internal list of phno of > that dictionary? thanks you. > -- > http://mail.python.org/mailman/listinfo/python-list > > From mr.spoon21 at gmail.com Sun Sep 14 14:55:02 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 14 Sep 2008 20:55:02 +0200 Subject: Abstract class In-Reply-To: References: Message-ID: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> Gary Harron: >I believe you are mixing up class *inheritance* and *abstract* classes. >Class inheritance (with Python has has for years) is how one class inherits >behavior/properties/attributes from another class. The class being inherited from is >called the base class. This is probably what you want. Well, I know the difference between an abstract class and an inherited one. The idea was to create a main class Note, with abstract methods, and implement these methods in the other classes. On Sun, Sep 14, 2008 at 7:56 PM, Roy Smith wrote: > What properties or behaviors does SharpNote have which NaturalNote doesn't? > Unless there is some new behavior, you don't need subclasses. Well, from a SharpNote I can obtain the relative NaturalNote. So if I have a C# I can call natural('C#') and get 'C' While in the class NaturalNote I don't need such a method, but I need two methods to get the sharped and flatted version > Are you also going to have DoubleSharpNote and DoubleFlatNote? Yes, that's an option. > Consider the following code: > > note1 = SharpNote("E4") > note2 = NaturalNote("F4") > if note1 == note2: > print "the same note" > else > print "different notes" > > what should it print? Well, that's not so simple. The idea is that I use a notation (A, B, C, D...) and an integer (a distance expressed in semitones) to identify a note. Anyway, I think I need an abstract class. Or not? From erexsha at gmail.com Thu Sep 25 16:04:59 2008 From: erexsha at gmail.com (Arash Arfaee) Date: Thu, 25 Sep 2008 13:04:59 -0700 Subject: adding in-place operator to Python In-Reply-To: <266557d0809251303k60d3a52eoc239917bc3597b27@mail.gmail.com> References: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> <266557d0809251303k60d3a52eoc239917bc3597b27@mail.gmail.com> Message-ID: <266557d0809251304q49fec06er436d7b2a1db6b6f7@mail.gmail.com> Thank you very much Gerhard and Terry. I am trying to add undefined state to some Boolean operator. Here is what I tried to do and It is not working: class _3ph: def __init__(self): self.value = 0 def __xor__(self,item): if self.value==2 or item==2: return 2 else: return self.__xor__(item) what I am trying to do is assigning 2 to undefined state and have xor operator return 2 if one of inputs are 2. it seems Although I defined xor in _3ph class, python treat any object from this class just like integer variables. can you help me find what is wrong here? Cheers, Arash On Tue, Sep 23, 2008 at 11:06 AM, Terry Reedy wrote: > Arash Arfaee wrote: > >> Hi All, >> >> Is there anyway to add new in-place operator to Python? Or is there any >> way to redefine internal in-place operators? >> > > Python does not have 'in-place operators'. It has 'augmented assignment > statements' that combines a binary operation with an assignment. *If* the > target being rebound is mutable, *then* (and only then) the operation can be > and is recommended to be done 'in-place'. User-defined mutable classes (as > most are) can implement in-place behavior with __ixxx__ methods. But for > the reason given below, __ixxx__ methods should supplement and not replace > direct mutation methods. > > Correct terminology is important for understanding what augmented > assigments do and what they are basically about. > > First, most augmented assignments target immutables, in particular, numbers > and strings, which do not have __ixxx__ methods. So the operation is *not* > done in-place. The only difference from separately indicating the > assignment and operation is that the programmer writes the target expression > just once and the interpreter evaluates the target expression just once > instead of each repeating themselves. (And consequently, any side-effects > of that evaluation happen just once instead of twice.) The same __xxx__ or > __rxxx__ method is used in either case. This non-repetition is the reason > for augmented assigments. The optional in-place optimization for mutables > is secondary. It was debated and could have been left out. > > Second, all augmented assignments perform an assignment, even if the > operation is done in place. However, if a mutable such as a list is > accessed as a member of an immutable collection such as a tuple, mutation is > possible, but rebinding is not. So the mutation is done and then an > exception is raised. To avoid the exception, directly call a mutation > method such as list.extend. > > Terry Jan Reedy > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From uomiocenekidd at gmail.com Mon Sep 22 06:38:21 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:38:21 -0700 (PDT) Subject: redtube video downloader - Free Message-ID: <41b8a318-c2d6-4c3f-bc57-c573ea5ee7b8@k37g2000hsf.googlegroups.com> redtube video downloader . . . *******CLICK HERE******** http://vids365.cn/redtube-video-downloader ***************************** . . . . . . . . . . . . redtube video downloader From bearophileHUGS at lycos.com Thu Sep 25 16:41:43 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Sep 2008 13:41:43 -0700 (PDT) Subject: Quick sort implementation in python References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: Alex Snast: > However i have no idea how to access the values of a data structure that doesn't allow random access.< Well, a sorting algorithm can work in-place, sorting the position of the items inside the given collection, or it can create a new data structure with the items (in Python all items are references). If the output of the sorting algorithm is an array (that is a python list), and the input isn't a list, then you can list-fy your input data and then sort that list in-place, and return it. Like this def mysort(any_iterable): data = list(any_iterable) # sort data... return data If the input is a list, you can sort it in place. Finally you may want to return other kinds of collections, like sorting a linked list and returning it (you can create a chain of nested lists, and then sort them with a merge sort), but in Python that's not much common. Bye, bearophile From ggpolo at gmail.com Sun Sep 14 09:47:01 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 14 Sep 2008 10:47:01 -0300 Subject: Windows / Tkinter - problem with grid - not able to place widgets at desired places In-Reply-To: <48cce842$0$11367$5fc30a8@news.tiscali.it> References: <48cce842$0$11367$5fc30a8@news.tiscali.it> Message-ID: On Sun, Sep 14, 2008 at 7:32 AM, Francesco Bochicchio wrote: > Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto: > > >>>Hi, >>> >>>I'm learning Python and Tkinter. I've started programming in Eclipse >>>with PyDev. I'm intending to create a GUI. I'm not able to understand >>>the Grid manager perhaps because there is quite a less documentation >>>available for it on the net. >>> >>>My desired GUI is attached in the mail. Although I've tried writing a >>>class module for this GUI but I'm not able to set all things right in >>>the GUI. The Biggest problem seems to be with the Grid Manager in terms >>>how it divides a window in Rows / columns. etc. I'm not able to place >>>none of the widgets correctly in the GUI. >>> >>>For your convenience, I'm attaching this code also as myModule1.py . >>>Please some one review it and help create me this GUI. >>> > > Uhm, I don't think you should use the grid manager to obtain a window > like that. The grid manager is for equally distributing widgets both > horizontally and vertically. > And I'm not sure that you can realize that window look with Tkinter. Yes you can. > You could get close by horizontally packing each widget row in a frame > and then vertically packing the frames in the window. But the look will be > quite different than your target. If you are not satisfied with that I > suggest you move to other toolkits which have more complex geometry > managers than .pack and .grid. Uhm.. I'm sure it is more a question of learning how to use them properly. The following code should be very close to the original request, depending on the tk version some minor modifications may be needed. from Tkinter import Tk, Button, Checkbutton, Label, Entry, Frame class App: def __init__(self, master): column0_padx = 24 row_pady = 36 #Label 1 lbl_testcase_exec = Label(master, text="Test case execution", wraplength=100, anchor='w', justify='left') lbl_results_cmp = Label(master, text="Results comparison", wraplength=100, justify='left') lbl_tolerance = Label(master, text="Tolerance (5%)", wraplength=100) testcase_exec = Checkbutton(master) results_cmp = Checkbutton(master) tolerance = Entry(master, width=4) lbl_analysis = Label(master, text="Analysis Library") analysis_lib = Entry(master, width=30) lbl_testcase_exec.grid(row=0, column=2, padx=20, pady=12, sticky='w') lbl_results_cmp.grid(row=0, column=3, pady=12, sticky='w') lbl_tolerance.grid(row=0, column=4, padx=20, pady=12, sticky='wn') lbl_analysis.grid(row=1, column=0, sticky='w', padx=column0_padx) analysis_lib.grid(row=1, column=1, sticky='w') testcase_exec.grid(row=1, column=2, padx=20, sticky='w') results_cmp.grid(row=1, column=3, sticky='w') tolerance.grid(row=1, column=4, padx=20, sticky='w') #Label 2 lbl_ref_analysis = Label( master, text="Reference Analysis Libary Version", wraplength=150, justify='left', pady=row_pady) ref_analysis_lib = Entry(master, width=30) lbl_ref_analysis.grid(row=2, column=0, sticky='w', padx=column0_padx) ref_analysis_lib.grid(row=2, column=1, sticky='w') # version lbl_version = Label(master, text="Version under Test") version = Label(master, text="vA.B.C.D") lbl_version.grid(row=3, column=0, sticky='w', padx=column0_padx) version.grid(row=3, column=1, sticky='w') # test all lbl_testall = Label(master, text="Test All") testall = Checkbutton(master) lbl_testall.grid(row=4, column=0, pady=row_pady, padx=column0_padx, sticky='w') testall.grid(row=4, column=1, sticky='w') # buttons bottom_frame = Frame(master) bottom_frame.grid(row=5, column=1, columnspan=3, sticky='w') btn_start = Button(bottom_frame, text = "Go", width=7) btn_start.pack(side='left') btn_commit = Button(bottom_frame, text="Commit", width=7) btn_commit.pack(side='left', padx=80) btn_exit = Button(bottom_frame, text="Exit", width=7) btn_exit.pack(side='left') root = Tk() root.title("Test Automation") root.minsize(800, 400) app = App(root) root.mainloop() > > Ciao > ----- > FB > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ivanov.maxim at gmail.com Fri Sep 26 04:52:34 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Fri, 26 Sep 2008 01:52:34 -0700 (PDT) Subject: multiprocessing eats memory References: Message-ID: <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> On 26 ????, 04:20, Istvan Albert wrote: > On Sep 25, 8:40?am, "Max Ivanov" wrote: > > > At any time in main process there are shouldn't be no more than two copies of data > > (one original data and one result). > > From the looks of it you are storing a lots of references to various > copies of your data via the async set. How could I avoid of storing them? I need something to check does it ready or not and retrieve results if ready. I couldn't see the way to achieve same result without storing asyncs set. From usenet.tolomea at gmail.com Mon Sep 8 08:23:11 2008 From: usenet.tolomea at gmail.com (usenet.tolomea at gmail.com) Date: Mon, 8 Sep 2008 05:23:11 -0700 (PDT) Subject: tracking collection modification References: <42d9688f-1058-4ed7-8d9d-affd432fdb41@s1g2000pra.googlegroups.com> Message-ID: On Sep 7, 8:54?pm, usenet.tolo... at gmail.com wrote: > I'm working on a remote object system, something kinda like Pyro. > For the purposes of caching I need to be able to tell if a given > dict / list / set has been modified. > Ideally what I'd like is for them to have a modification count > variable that increments every time the particular collection is > modified. Unfortunately I can't find anything like that and since this > needs to work for the regular normal list / dict / set objects > subclassing them to add the modification count isn't useful. > I realize I could take a copy and then compare the copy to the > original, but that's a fairly heavy handed approach and I was hoping > for something light and fast. > Does anyone have any suggestions on best to approach this? additionally I don't need to know if the things the list (etc) references have changed, only the list itself From tjreedy at udel.edu Tue Sep 16 14:03:34 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 14:03:34 -0400 Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows In-Reply-To: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> References: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Message-ID: Richard_Martineau at xyratex.com wrote: > Now comes the troubled bit...I now look for similar source code for > Python extensions Numpy and Scipy but the source code and directories > are not all obvious. Looks like these are normally built via other > compilers. However I need to do all my builds in VS 6.0. Numpy/scipy specific questions tend to get more specific answers on the numpy/scipy mailing lists. Or see gmane.comp.python.numeric.general at news.gmane.org From jettgamboa at gmail.com Sun Sep 28 09:00:19 2008 From: jettgamboa at gmail.com (Jett) Date: Sun, 28 Sep 2008 06:00:19 -0700 (PDT) Subject: Mechanize and Yahoo HTTPS Message-ID: Has anybody used the mechanize library with a Yahoo site? I am trying to create a program that will download my player's stats from Yahoo's Fantasy Football site but for some reason could not get it to load the login page. When I run the program below, it prints the word "start" and then does nothing (no exceptions are thrown). ---- code snippet start ---- import re from mechanize import Browser print 'start' br = Browser() response1 = br.open("https://login.yahoo.com/config/login?.done=http:// sports.yahoo.com/fantasy&.src=spt") print br.title() print "end" ---- code snippet end ---- From sturlamolden at yahoo.no Wed Sep 10 14:15:26 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 10 Sep 2008 11:15:26 -0700 (PDT) Subject: NumPy arrays that use memory allocated from other libraries or tools References: Message-ID: <63fac77e-3043-40fa-8f3d-9d751d9a82cf@d1g2000hsg.googlegroups.com> On Sep 10, 6:39?am, Travis Oliphant wrote: > I wanted to point anybody interested to a blog post that describes a > useful pattern for having a NumPy array that points to the memory > created by a different memory manager than the standard one used by > NumPy. Here is something similar I have found useful: There will be a new module in the standard library called 'multiprocessing' (cf. the pyprocessing package in cheese shop). It allows you to crerate multiple processes (as opposed to threads) for concurrency on SMPs (cf. the dreaded GIL). The 'multiprocessing' module let us put ctypes objects in shared memory segments (processing.Array and processing.Value). It has it's own malloc, so there is no 4k (one page) lower limit on object size. Here is how we can make a NumPy ndarray view the shared memory referencey be these objects: try: import processing except: import multiprocessing as processing import numpy, ctypes _ctypes_to_numpy = { ctypes.c_char : numpy.int8, ctypes.c_wchar : numpy.int16, ctypes.c_byte : numpy.int8, ctypes.c_ubyte : numpy.uint8, ctypes.c_short : numpy.int16, ctypes.c_ushort : numpy.uint16, ctypes.c_int : numpy.int32, ctypes.c_uint : numpy.int32, ctypes.c_long : numpy.int32, ctypes.c_ulong : numpy.int32, ctypes.c_float : numpy.float32, ctypes.c_double : numpy.float64 } def shmem_as_ndarray( array_or_value ): """ view processing.Array or processing.Value as ndarray """ obj = array_or_value._obj buf = obj._wrapper.getView() try: t = _ctypes_to_numpy[type(obj)] return numpy.frombuffer(buf, dtype=t, count=1) except KeyError: t = _ctypes_to_numpy[obj._type_] return numpy.frombuffer(buf, dtype=t) With this simple tool we can make processes created by multiprocessing work with ndarrays that reference the same shared memory segment. I'm doing some scalability testing on this. It looks promising :) From gh at ghaering.de Tue Sep 23 07:03:05 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Tue, 23 Sep 2008 13:03:05 +0200 Subject: adding in-place operator to Python In-Reply-To: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> References: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> Message-ID: Arash Arfaee wrote: > Hi All, > > Is there anyway to add new in-place operator to Python? You can't create new syntax, like %= > Or is there any way to redefine internal in-place operators? What you can do is give your objects the ability to use these operators. See http://docs.python.org/ref/numeric-types.html for __iadd_ (+=) and friends. You could implement something like a string buffer this way: class Buffer: def __init__(self): self.buf = [] def __iadd__(self, item): self.buf.append(item) return self def __str__(self): return "".join(self.buf) if __name__ == "__main__": buf = Buffer() buf += "str1" buf += "str2" print str(buf) -- Gerhard From faltet at gmail.com Tue Sep 16 08:58:27 2008 From: faltet at gmail.com (Francesc) Date: Tue, 16 Sep 2008 05:58:27 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> Message-ID: <15ed8d4b-c7bb-4f58-ba36-cbf0f3c585e3@79g2000hsk.googlegroups.com> On 15 Set, 22:09, "Aaron \"Castironpi\" Brady" wrote: > On Sep 15, 4:34 am, Francesc wrote: > > > > > On 12 Set, 14:39, "Aaron \"Castironpi\" Brady" > > wrote: > > > > > A consideration of other storage formats such as HDF5 might > > > > be appropriate: > > > > >http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > > > > There are, of course, HDF5 tools available for Python. > > > > PyTablescame up within the past few weeks on the list. > > > > "When the file is created, the metadata in the object tree is updated > > > in memory while the actual data is saved to disk. When you close the > > > file the object tree is no longer available. However, when you reopen > > > this file the object tree will be reconstructed in memory from the > > > metadata on disk...." > > > > This is different from what I had in mind, but the extremity depends > > > on how slow the 'reconstructed in memory' step is. (Fromhttp://www.pytables.org/docs/manual/ch01.html#id2506782). The > > > counterexample would be needing random access into multiple data > > > files, which don't all fit in memory at once, but the maturity of the > > > package might outweigh that. Reconstruction will form a bottleneck > > > anyway. > > > Hmm, this was a part of a documentation that needed to be updated. > > Now, the object tree is reconstructed in a lazy way (i.e. on-demand), > > in order to avoid the bottleneck that you mentioned. I have corrected > > the docs in: > > >http://www.pytables.org/trac/changeset/3714/trunk > > > Thanks for (indirectly ;-) bringing this to my attention, > > > Francesc > > Depending on how lazy the reconstruction is, would it be possible to > modify separate tables from separate processes concurrently? No, modification of different tables in the same file simultaneously is not supported yet. This is a limitation of the HDF5 library itself. The HDF Group said that they have plans to address this, but this is probably a long-term task. Francesc From darcy at druid.net Thu Sep 4 23:21:37 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 4 Sep 2008 23:21:37 -0400 Subject: Curious: 2134 2004-10-06 08:55:20Z fredrik In-Reply-To: References: Message-ID: <20080904232137.9a1d94d6.darcy@druid.net> On Fri, 5 Sep 2008 04:13:28 +0100 "Akathorn Greyhat" wrote: > I've already fix it, but I don't know what the hell does this line means: > > # $Id: __init__.py 2134 2004-10-06 08:55:20Z fredrik $ > It seens curious, isn't it? http://ximbiot.com/cvs/wiki/CVS--Concurrent%20Versions%20System%20v1.12.12.1%3A%20Keyword%20substitution -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From alexandru.mosoi at gmail.com Fri Sep 5 04:17:32 2008 From: alexandru.mosoi at gmail.com (=?UTF-8?Q?Alexandru_Mo=C8=99oi?=) Date: Fri, 5 Sep 2008 01:17:32 -0700 (PDT) Subject: derived classes and __getattr__ Message-ID: i'm facing the following problem: class Base(object): def __getattr__(self, attr): return lambda x: attr + '_' + x def dec(callable): return lambda *args: 'dec_' + callable(*args) class Derived(Base): what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have what_so_ever mumu = dec(Base.mumu) # wrong, base doesn't have mumu any idea how to do this? From grflanagan at gmail.com Fri Sep 19 08:37:44 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Fri, 19 Sep 2008 14:37:44 +0200 Subject: dict generator question In-Reply-To: References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: Boris Borcic wrote: > Gerard flanagan wrote: >> George Sakkis wrote: > .. >>> >>> Note that this works correctly only if the versions are already sorted >>> by major version. >>> >> >> Yes, I should have mentioned it. Here's a fuller example below. >> There's maybe better ways of sorting version numbers, but this is what >> I do. > > Indeed, your sort takes George's objection too litterally, what's needed > for a correct endresult is only that major versions be grouped together, > and this is most simply obtained by sorting the input data in (default) > string order, is it not ? > >> Yes, I see what you mean - the fact that a default sort orders "1.10" before "1.9" doesn't actually matter for the required result. >> >> datadict = \ >> dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) And, s[:3] is wrong. So: data.sort() datadict = \ dict((k, len(list(g))) for k,g in groupby(data, lambda s: '.'.join(s.split('.',2)[:2]))) should work, I hope. Cheers, Gerard From akineko at gmail.com Tue Sep 16 04:48:02 2008 From: akineko at gmail.com (akineko) Date: Tue, 16 Sep 2008 01:48:02 -0700 (PDT) Subject: A unique instance of Python GUI program Message-ID: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Hello everyone, This may not be a Python specific challenge. I have a GUI program written in Python + Tkinter. It works very well. Now, I would like to start it from a shell script. As my GUI program includes a server, it should not have more than one instance. Is there any easy way to check if another instance of the program is already running. I vaguely remember that Windows programming provides a way to check. A platform independent approach would be nice but a solution for X is sufficient for my application. Any comments will be greatly appreciated. Best regards, Aki Niimura From steve at REMOVE-THIS-cybersource.com.au Tue Sep 30 19:40:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 23:40:22 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6ke1i8F7dmkkU2@mid.uni-berlin.de> <6kernnF7dmkkU3@mid.uni-berlin.de> Message-ID: <00f2b28e$0$20617$c3e8da3@news.astraweb.com> On Tue, 30 Sep 2008 14:34:31 +0000, Marc 'BlackJack' Rintsch wrote: > On Tue, 30 Sep 2008 15:42:58 +0200, Ivan Reborin wrote: > >> On 30 Sep 2008 07:07:52 GMT, Marc 'BlackJack' Rintsch >> wrote: >>>===== >>>from __future__ import with_statement from functools import partial >>>from itertools import islice >>>from pprint import pprint >>> >>> >>>def read_group(lines, count): >>> return [map(int, s.split()) for s in islice(lines, count)] >>> >>>def main(): >>> with open('test.txt') as lines: >>> lines = (line for line in lines if line.strip()) >>> result = list(iter(partial(read_group, lines, 3), list())) >>> pprint(result, width=30) >>> >>>if __name__ == '__main__': >>> main() >>>===== >> >> I'm afraid I must admit I find the code above totally uncomprehesible >> (I can't even see where the array here is mentioned - "result"?) and >> inpractical for any kind of engineering practice I had in mind. > > Learn Python then to understand that code. ;-) > > There is no array. The data type is called "list" in Python, so > `result` is a nested list. And in Python it quite unusual to build > lists by creating them with the final size filled with place holder > objects and then fill the real values in. Instead lists are typically > created by appending values to existing lists, using list comprehension > or the `list()` function with some iterable object. I would weaken that claim a tad... I'd say it is "usual" to write something like this: alist = [] for x in some_values: alist.append(something_from_x) but it is not uncommon (at least not in my code) to write something like this equivalent code instead: alist = [None]*len(some_values) for i, x in enumerate(some_values): alist[i] = something_from_x Most often the first way is most natural, but the second way is sometimes more natural. It will also be more familiar to somebody coming from Fortran, and it is a micro-optimization for large lists because it doesn't need to resize the list as it grows. I stress the *micro*-optimization, because Python lists are highly optimized to resize as rarely as possible and as quickly as possible, so you're not saving much time. And Marc, I think you're being a little unfair to the OP, who is clearly unfamiliar with Python. I've been using Python for perhaps ten years, and I still find your code above dense and hard to comprehend. It uses a number of "advanced Python concepts" that a newbie is going to have trouble with: - the with statement acts by magic; if you don't know what it does, it's an opaque black box. - you re-use the same name for different uses, which can cause confusion. - generator expressions. - functional programming using partial. - you call a function that uses a list comprehension with both map and iterator slicing inside it. No wonder the OP had trouble with it. *I* have trouble with it, and would need to sit down at the interactive interpreter and play around with it for a while to be sure what it actually does. If it was your intention to make Python look as obtuse and mysterious as possible, you almost succeeded. The one things you missed was to replace the read_group function with a lambda in the partial. -- Steven From fredrik at pythonware.com Wed Sep 10 14:55:59 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 20:55:59 +0200 Subject: Simple UDP server In-Reply-To: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> Message-ID: Tzury Bar Yochay wrote: > Would the one below will be capable of holding 30 concurrent > connections? UDP is a connectionless datagram protocol, so that question doesn't really make much sense. From dmitrey.kroshko at scipy.org Wed Sep 17 15:41:17 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Wed, 17 Sep 2008 12:41:17 -0700 (PDT) Subject: PYPI, some troubles Message-ID: hi all, 1. when I commit a new release to PYPI, I can use stored data (by my browser: Name, package summary, keywords etc), but in the last line (classification) I had to chose all those lines from the very beginning, moreover, if I click at one of them without pressing "CTRL" all my choices drops & I have to type it from the very beginning (I use Mozilla Firefox 3.0 but I don't think it's the matter). 2. Another issue: I have attached my source code (openopt0.19.tar.bz2 file), now I can see it in "files for openopt 0.19" section (http:// pypi.python.org/pypi) but easy_install can't find the package: # easy_install openopt Searching for openopt Reading http://pypi.python.org/simple/openopt/ Couldn't find index page for 'openopt' (maybe misspelled?) Scanning index of all packages (this may take a while) Reading http://pypi.python.org/simple/ Reading http://pypi.python.org/simple/OpenOpt/ Reading http://scipy.org/scipy/scikits/wiki/OpenOpt No local packages or download links found for openopt error: Could not find suitable distribution for Requirement.parse('openopt') Does anyone know what shoul I do? Thank you in advance, Dmitrey From bdesth.quelquechose at free.quelquepart.fr Sun Sep 14 11:33:20 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 14 Sep 2008 17:33:20 +0200 Subject: Abstract class In-Reply-To: References: Message-ID: <48cd4aae$0$12641$426a74cc@news.free.fr> Mr.SpOOn a ?crit : > Hi, > I'm going to work on a project to represent some musical theory in > Python, in an object oriented way. > > I have to manage many elements of music such as notes, intervals, > scales, chords and so on. All these elements share properties and > behavior, so what I want to do is an abstract class "Note" and other > subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. > > The idea is not original, I read it in some papers where they talk > about an implementation in smalltalk. > > I want to use Python (of course) and I'd like to know what is the > practice in such a case. I mean, in python there aren't abstract > classes, but I read about some way to emulate the same behavior. > > What do you suggest me? Conceptually, an abstract class is a class that is not intented to be instanciated directly but used as a parent class. The simplest way to get such behaviour is to just write your base class and avoid instanciating it. From bearophileHUGS at lycos.com Mon Sep 22 07:21:12 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 04:21:12 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <00e45101$0$20331$c3e8da3@news.astraweb.com> Message-ID: <773db59e-40c6-470e-b616-ca8715efa46a@d77g2000hsb.googlegroups.com> Steven D'Aprano: >Extending len() to support iterables sounds like a good idea, except that it's not.< Python language lately has shifted toward more and more usage of lazy iterables (see range lazy by default, etc). So they are now quite common. So extending len() to make it act like leniter() too is a way to adapt a basic Python construct to the changes of the other parts of the language. In languages like Haskell you can count how many items a lazy sequence has. But those sequences are generally immutable, so they can be accessed many times, so len(iterable) doesn't exhaust them like in Python. So in Python it's less useful. This is a common situation where I can only care of the len of the g group: [leniter(g) for h,g in groupby(iterable)] There are other situations where I may be interested only in how many items there are: leniter(ifilter(predicate, iterable)) leniter(el for el in iterable if predicate(el)) For my usage I have written a version of the itertools module in D (a lot of work, but the result is quite useful and flexible, even if I miss the generator/iterator syntax a lot), and later I have written a len() able to count the length of lazy iterables too (if the given variable has a length attribute/property then it returns that value), and I have found that it's useful often enough (almost as the string.xsplit()). But in Python there is less need for a len() that counts lazy iterables too because you can use the following syntax that isn't bad (and isn't available in D): [sum(1 for x in g) for h,g in groupby(iterable)] sum(1 for x in ifilter(predicate, iterable)) sum(1 for el in iterable if predicate(el)) So you and Python designers may choose to not extend the semantics of len() for various good reasons, but you will have a hard time convincing me it's a useless capability :-) Bye, bearophile From tjreedy at udel.edu Tue Sep 16 13:31:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 13:31:40 -0400 Subject: append on lists In-Reply-To: <200809161610.50245.maric@aristote.info> References: <200809161610.50245.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit : >> On 2008-09-16, Maric Michaud wrote: >>> all expressions that return something, return a new object, >> That's not _quite_ true: >>>>> a=1 >>>>> b=a.__add__(0) >>>>> a is b >> True >> >> ;) > > This is implementation specific, the specification of the language says that > it should be false, Please quote the section of the manual that says this. > and it is for higher numbers : Agaiin, this is implementation specific. An implementation would be free to special-case any or all of +a, a+0, a-0, a*1, a//1, a**1, a<<0, a>>0, and a|0 and return a. That CPython only optimizes the first is a judgment that the other cases are too rare to bother with. > Don't disturb our OP, with side questions, please, it was enough hard like > this ;) Stop peddling false information. For immutable objects, identity is irrelevant except for id and is. tjr From info at egenix.com Thu Sep 25 09:57:28 2008 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 25 Sep 2008 15:57:28 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.7.0-0.9.8i-1 Message-ID: <48DB98C8.5000703@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.7.0-0.9.8i-1 An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.7.0-0.9.8i-1-GA.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/) that allows writing SSL aware networking applications as well as certificate management tools. OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). ________________________________________________________________________ NEWS This second release of the eGenix.com pyOpenSSL Distribution upgrades the included OpenSSL library version to the latest 0.9.8i, which includes several bug fixes over the previously included 0.9.8h version. The release also includes Python 2.6 support for the first time. Binaries are available for Linux x86 and x64 as well as Windows x86. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 25 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From sh006d3592 at blueyonder.co.uk Sun Sep 14 15:49:24 2008 From: sh006d3592 at blueyonder.co.uk (Stephen Horne) Date: Sun, 14 Sep 2008 20:49:24 +0100 Subject: Abstract class References: Message-ID: On Sun, 14 Sep 2008 18:03:23 +0200, Mr.SpOOn wrote: >I have to manage many elements of music such as notes, intervals, >scales, chords and so on. All these elements share properties and >behavior, so what I want to do is an abstract class "Note" and other >subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. First off, one approach in Python is to not have a base class at all. You don't need a base class just to implement a shared interface, basically. If it walks like a duck and quacks like a duck, you can usually treat it like a duck, as I think the Ruby crowd say. Second, it's possible to overdo object orientation, which is probably Roy Smiths point. Sometimes, the easiest thing to do is to use a simple integer representation of your values. With dates, you'd probably use a Julian day number. That's what spreadsheets usually do, for instance. With music notes, you'd probably use the note numbers that MIDI uses. http://www.harmony-central.com/MIDI/Doc/table2.html You can always extend the range beyond those notes that MIDI supports if needed. Doing this means you can switch octaves or transpose using simple additions or subtractions, for instance. Notes can be decoded using rounded integer division to find the octave number and the remainder/modulo % operator (plus maybe a look-up table) to identify the note. Use // for integer division (rounded toward -infinity IIRC) or you risk problems going from Python 2 to Python 3 - the semantics for the / division operator are changing. Up until now it would round integer divisions, but in future it will be considered a "true" non-rounding division. This may not work, though, if you aren't working with the even-tempered scale (if I got that right). There are times when C-sharp is not the same as D-flat, as MIDI assumes. You may want to wrap the value in a class, but as far as possible all your calculations would be based on the integers. Chords might be represented using either a list or a set - my Python's a little rusty ATM but IIRC there's a set type based on a dictionary. If you're a bit-twiddling fan, you might even use a bitvector approach (I don't think theres a specialised set-of-unsigned-integers bit-vector class in the library, but I could be wrong). But for most purposes, you'd probably want the spec. for the chord - "C major" rather than "C, E, G". In situations like this, it's sometimes useful to have simple functions in a module, or else a 'tool' class (which works on the values, but only encapsulates the tools own state). You can still wrap the values in a class with a common interface. The point of this is that it's relatively easy to share functionality when you implement some value-wrapper classes in several different ways - e.g. note-set chords vs. specification-based chords, note-number representations vs. string representations, etc. That is, in object oriented theory, the object manipulates itself - but that doesn't always work so well in practice, especially for functions that deal with two or more objects. As in the real world, a tool sometimes works better. And if the tool doesn't need any state, it may as well be a single procedure/function in a module rather than a class. From ewertman at gmail.com Tue Sep 2 14:13:47 2008 From: ewertman at gmail.com (Eric Wertman) Date: Tue, 2 Sep 2008 14:13:47 -0400 Subject: Large amount of files to parse/organize, tips on algorithm? In-Reply-To: <6dc5719f-a65b-4194-b09c-b9bbb55ee788@e53g2000hsa.googlegroups.com> References: <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> <6dc5719f-a65b-4194-b09c-b9bbb55ee788@e53g2000hsa.googlegroups.com> Message-ID: <92da89760809021113x1000cd58y9ba55ab2fa517f33@mail.gmail.com> I think you really want use a relational database of some sort for this. On Tue, Sep 2, 2008 at 2:02 PM, cnb wrote: > over 17000 files... > > netflixprize. > -- > http://mail.python.org/mailman/listinfo/python-list > From diordna at gmail.com Wed Sep 10 22:11:56 2008 From: diordna at gmail.com (Stephen Johnson) Date: Wed, 10 Sep 2008 22:11:56 -0400 Subject: Logix - gone? In-Reply-To: References: <276719.72706.qm@web95107.mail.in2.yahoo.com> <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> Message-ID: <12CD696C-D900-40AD-ABE3-4611D7D81B1F@gmail.com> > Ummmm .... try the download link; it worked for me. Oops. You just found my daily stupid. However, I still wish the Trac link worked, and I would prefer the participation of the original dev to forking it. -Steve Johnson From Eric_Dexter at msn.com Mon Sep 8 21:31:33 2008 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 8 Sep 2008 18:31:33 -0700 (PDT) Subject: Problems downloading and installing win32api References: <968dca58-0172-4953-b8d6-9610f0570fe8@s20g2000prd.googlegroups.com> Message-ID: <6e53ed31-498b-4e52-b0d1-d3ed1c34efa5@l64g2000hse.googlegroups.com> On Sep 8, 2:41?pm, Emile van Sebille wrote: > brianrpsgt1 wrote: > > I have attempted downloading and installing several different version > > of the win32api from Source Forge, > > Whe win32 tools come bundled with ActiveState's python distribution. > > Maybe that'll move you forward... > > Emile > > ? however, each time I try to install > > > > > I get the following error message: > > > "Only part of a ReadProcessMemory or WriteProcessMemory request was > > completed" > > > This occurred with the following files: > > pywin32-212.win32-py2.4.exe > > pywin32-212.win32-py2.5.exe > > pywin32-212.win32-py2.6.exe > > > I am using WinXP SP2. ?Any assistance on getting this downloaded and > > installed would be great. > > > Thanks > > > B > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - I may have a copy if it is legal to distribute I will post it if you still need it. You will notice that sourceforge has changed the way they are doing things. As you may know they are a money loosing public company and to help combat this they have changed thier website to show less advertising and have cut the projects off from thier home page. They are offering services now to help you do what is listed on the original web site..... You may have other things that don't work also. I have a slow connection so tell me if you can't find it somewhere else first. From bearophileHUGS at lycos.com Wed Sep 3 17:56:36 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 14:56:36 -0700 (PDT) Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> <7f2d4b4a-bc97-4b46-a31e-63f98e9fee73@34g2000hsh.googlegroups.com> Message-ID: Roy Smith: > But, along those lines, I've often thought that split() needed a way to not > just limit the number of splits, but to also throw away the extra stuff. > Getting the first N fields of a string is something I've done often enough > that refactoring the slicing operation right into the split() code seems > worthwhile. And, it would be even faster :-) Given the hypothetical .xsplit() string method I was talking about, it's then easy to use islice() on it to skip the first items: islice(sometext.xsplit(), 10, None) Bye, bearophile From cipherzero at gmail.com Sun Sep 7 00:50:47 2008 From: cipherzero at gmail.com (cipher) Date: Sat, 6 Sep 2008 21:50:47 -0700 (PDT) Subject: Setter Propertys' mro? References: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> <00d34e8d$0$30713$c3e8da3@news.astraweb.com> Message-ID: <21655332-7ad8-4d8c-a554-6cdc0cb2a872@a3g2000prm.googlegroups.com> On Sep 6, 9:10?pm, Steven D'Aprano wrote: > On Sat, 06 Sep 2008 18:15:33 -0700, cipher wrote: > > Whats the mro (method resolution order) of a setter property (__set__ on > > a descriptor). > > i seem to be experiencing some weird issue with them. for example > > >>>> class test: > > Unless you're using Python 3, there's your problem right there. In Python > 2.x, properties only work correctly for new style classes, not classic > classes. Change the above line to: > > class Test(object): ?# by convention, classes start with Uppercase. > > and all should work (or at least you'll discover new and exciting > different problems with your code). > > > however, if i specify the metaclass in the class definition it works > > just fine... > > > class test: > > ?__metaclass__=type > > which is more or less the same as inheriting from object, except uglier. > > -- > Steven Thanks to both of you!! that solved it. i wonder why the getters would work fine though?? neways, wtf do i care :) again, thank you both. __ Cipher From fredrik at pythonware.com Thu Sep 11 08:39:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 14:39:10 +0200 Subject: problem with interpreter In-Reply-To: <04e1cbd4-7116-4209-b814-6d34e4d24975@l42g2000hsc.googlegroups.com> References: <04e1cbd4-7116-4209-b814-6d34e4d24975@l42g2000hsc.googlegroups.com> Message-ID: chusky wrote: > File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", > line 5, in < > module> > import new > File "new.py", line 1 > import > ^ > SyntaxError: invalid syntax wxPython tries to import the module "new" from Python's standard library, but picks up a broken module named "new.py" from your development directory instead. From uomiocenekidd at gmail.com Mon Sep 22 06:38:59 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:38:59 -0700 (PDT) Subject: imagefap showfavorites - Free Message-ID: imagefap showfavorites . . . *******CLICK HERE******** http://vids365.cn/imagefap-showfavorites ***************************** . . . . . . . . . . . . imagefap showfavorites From clp at rebertia.com Wed Sep 24 17:19:03 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 24 Sep 2008 14:19:03 -0700 Subject: Schwartzian transform for tuple in list In-Reply-To: References: Message-ID: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase wrote: > Hi, > > I have a rather large list structure with tuples contained in them (it's > part of a specification I received) looks like so: > [(x1,y1,r1,d1),(x2,y2,r2,d2)...] > > The list can range from about 800-1500 tuples in size and I'm currently > sorting it with this: > > a_list.sort(lambda a, b: cmp(b[3], a[3])) You'd probably be better off using the 'key' keyword argument to .sort(), which is made for the Schwartzian Transform: a_list.sort(key=lambda x: x[3]) This sorts the list items by the value produced by the key function for each item. It's also (IIRC) faster than using a comparison function like you're currently doing. Regards, Chris > > I'm actually sorting it by the last value in the tuple (d2). I have been > researching more efficient sorting algorithms and came across Schwartzian > transform via these links: > > http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency > http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html > > I get what's happening (sorta...errr...lol) but I'm not sure if it is more > efficient in my scenario, if it is then I have no idea how to implement it > properly :-/ > > Would be great if a true expert would offer a suggestion for me... > > Thanks! > > David > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From ce at mail.net.sk Thu Sep 11 22:28:24 2008 From: ce at mail.net.sk (Mahdi) Date: Fri, 12 Sep 2008 10:28:24 +0800 Subject: wx References: Message-ID: if you just type "python wx" you will get 2,080,000 results. The first by luck (not chance) is wxPython. it scares me when ppl start to post on newsgroups before even searching in the web for a second! how old r u Mr. Chance not Choice? on 09/12/2008 02:32 AM Fredrik Lundh wrote : > Desmond Scott E wrote: > > I'm am a Python novice by chance not choice. (Although it appears to > be a nice tool. Plus anything based on Monte Python can't be bad!) > > My Quest is to migrate a Python-based process from Windows2000/Python > v2.4.2 (#67) to WindowsXP/Python v2.5.2 (r252:60911). > > I've searched the Python website and could find no reference to module > wx. Is this an add-in module or perhaps it was replaced in v2.5.2??? > From michel at nospam.please Sun Sep 28 13:04:04 2008 From: michel at nospam.please (Michel Leunen) Date: Sun, 28 Sep 2008 19:04:04 +0200 Subject: destructor not called In-Reply-To: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> Message-ID: <48dfb904$0$2851$ba620e4c@news.skynet.be> Marcin201 a ?crit : > class Foo: > def __init__(self): > print "Hello" > self.f = self.fxn Maybe self.f = self.fxn() is what you want. Note the '()'. -- Michel Leunen http://linux.leunen.com From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 04:05:20 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 10:05:20 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <00eaee25$0$20666$c3e8da3@news.astraweb.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> Message-ID: <48db462f$0$24356$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote: > >> Plenty of people were quick to say that the exception should be passed >> through to the caller. No one said this behaviour should be documented. >> There may be little practical difference bewteen calling sys.exit() >> after printing an error and progating an exception if no one using the >> library knows that it could generate that exception in those >> circumstances. > > That's true, I didn't explicitly say that the library should be > documented. Nor did I say that it shouldn't be riddled with bugs. There's > little practical difference between a buggy library and one that raises > unexpected (i.e. undocumented) exceptions either. Also note that there are quite a couples cases where the library authors themselves cannot predict which exception types may be raised - as soon as the library functions expect callback functions, file-like or dict-like or whatever-like objects etc, it's the caller's responsability to handle the exceptions that may be raised by what *he* passes to the library... From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 04:08:09 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 10:08:09 +0200 Subject: How to parse a string completely into a list In-Reply-To: References: Message-ID: <48db46d6$0$24356$426a74cc@news.free.fr> john.ford at colorado.edu a ?crit : > I want to take a long alpha-numeric string with \n and white-space and > place ALL elements of the string (even individual parts of a long > white-space) into separate list elements. The most common way I've > seen this performed is with the split() function, however I don't > believe that it has the power to do what I am looking for. > Any suggestions? Did you try passing your string to the list() type ? Python 2.5.1 (r251:54863, Mar 7 2008, 03:41:45) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = """I want to take a long alpha-numeric string with \n and white-space and ... place ALL elements of the string (even individual parts of a long ... white-space) into separate list elements. The most common way I've ... seen this performed is with the split() function, however I don't ... believe that it has the power to do what I am looking for. ... Any suggestions? ... thanks ... """ >>> >>> s "I want to take a long alpha-numeric string with \n and white-space and\nplace ALL elements of the string (even individual parts of a long\nwhite-space) into separate list elements. The most common way I've\nseen this performed is with the split() function, however I don't\nbelieve that it has the power to do what I am looking for.\nAny suggestions?\nthanks\n" >>> list(s) ['I', ' ', 'w', 'a', 'n', 't', ' ', 't', 'o', ' ', 't', 'a', 'k', 'e', ' ', 'a', ' ', 'l', 'o', 'n', 'g', ' ', 'a', 'l', 'p', 'h', 'a', '-', 'n', 'u', 'm', 'e', 'r', 'i', 'c', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', 'w', 'i', 't', 'h', ' ', '\n', ' ', 'a', 'n', 'd', ' ', 'w', 'h', 'i', 't', 'e', '-', 's', 'p', 'a', 'c', 'e', ' ', 'a', 'n', 'd', '\n', 'p', 'l', 'a', 'c', 'e', ' ', 'A', 'L', 'L', ' ', 'e', 'l', 'e', 'm', 'e', 'n', 't', 's', ' ', 'o', 'f', ' ', 't', 'h', 'e', ' ', 's', 't', 'r', 'i', 'n', 'g', ' ', '(', 'e', 'v', 'e', 'n', ' ', 'i', 'n', 'd', 'i', 'v', 'i', 'd', 'u', 'a', 'l', ' ', 'p', 'a', 'r', 't', 's', ' ', 'o', 'f', ' ', 'a', ' ', 'l', 'o', 'n', 'g', '\n', 'w', 'h', 'i', 't', 'e', '-', 's', 'p', 'a', 'c', 'e', ')', ' ', 'i', 'n', 't', 'o', ' ', 's', 'e', 'p', 'a', 'r', 'a', 't', 'e', ' ', 'l', 'i', 's', 't', ' ', 'e', 'l', 'e', 'm', 'e', 'n', 't', 's', '.', ' ', 'T', 'h', 'e', ' ', 'm', 'o', 's', 't', ' ', 'c', 'o', 'm', 'm', 'o', 'n', ' ', 'w', 'a', 'y', ' ', 'I', "'", 'v', 'e', '\n', 's', 'e', 'e', 'n', ' ', 't', 'h', 'i', 's', ' ', 'p', 'e', 'r', 'f', 'o', 'r', 'm', 'e', 'd', ' ', 'i', 's', ' ', 'w', 'i', 't', 'h', ' ', 't', 'h', 'e', ' ', 's', 'p', 'l', 'i', 't', '(', ')', ' ', 'f', 'u', 'n', 'c', 't', 'i', 'o', 'n', ',', ' ', 'h', 'o', 'w', 'e', 'v', 'e', 'r', ' ', 'I', ' ', 'd', 'o', 'n', "'", 't', '\n', 'b', 'e', 'l', 'i', 'e', 'v', 'e', ' ', 't', 'h', 'a', 't', ' ', 'i', 't', ' ', 'h', 'a', 's', ' ', 't', 'h', 'e', ' ', 'p', 'o', 'w', 'e', 'r', ' ', 't', 'o', ' ', 'd', 'o', ' ', 'w', 'h', 'a', 't', ' ', 'I', ' ', 'a', 'm', ' ', 'l', 'o', 'o', 'k', 'i', 'n', 'g', ' ', 'f', 'o', 'r', '.', '\n', 'A', 'n', 'y', ' ', 's', 'u', 'g', 'g', 'e', 's', 't', 'i', 'o', 'n', 's', '?', '\n', 't', 'h', 'a', 'n', 'k', 's', '\n'] >>> HTH From tim.arnold at sas.com Wed Sep 24 13:37:52 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 24 Sep 2008 13:37:52 -0400 Subject: multiple processes with private working dirs Message-ID: I have a bunch of processes to run and each one needs its own working directory. I'd also like to know when all of the processes are finished. (1) First thought was threads, until I saw that os.chdir was process-global. (2) Next thought was fork, but I don't know how to signal when each child is finished. (3) Current thought is to break the process from a method into a external script; call the script in separate threads. This is the only way I can see to give each process a separate dir (external process fixes that), and I can find out when each process is finished (thread fixes that). Am I missing something? Is there a better way? I hate to rewrite this method as a script since I've got a lot of object metadata that I'll have to regenerate with each call of the script. thanks for any suggestions, --Tim Arnold From aioe.org at technicalbloke.com Thu Sep 18 00:35:36 2008 From: aioe.org at technicalbloke.com (r0g) Date: Thu, 18 Sep 2008 00:35:36 -0400 Subject: A unique instance of Python GUI program References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> <0643c0e0-a9c0-4a46-8cb8-7c37a9ebcc07@w39g2000prb.googlegroups.com> Message-ID: akineko wrote: > Again, thank you for many postings to my question. > I have reviewed solutions provided. > Well, I like the named Mutex solution under Windows. > That is a clean and straight-forward approach to the challenge. > (I cannot believe that I'm saying good thing about Windows ;-) ) > > Unfortunately, I'm living in Unix realm ;-) > > None of solutions for Unix are appealing to me. > But they must be "the" solution for the challenge as well-established > software uses those solutions. > > Now, I'm wondering. > As my program is a GUI (Tkinter) software. > Is it possible to set a known value to X11 or Tk property through > Tkinter so that another instance of the program can check if such > property is set? > > Of course, I know this scheme has a flaw. If one instance uses another > logical display, then such property is probably not shared. > But for my usage, it is logically possible but not likely. > > I checked my Tkinter book and found the following function. > winfo_interps(displayof=0) > > This returns a list of all Tk-based applications currently running on > the display. > > When I tried, I got the following: >>>> root.winfo_interps() > ('tk #3', 'tk #2', 'tk') > > But I couldn't find a way to set a specific name to the Tcl > interpreter. > > As I'm not an expert of Tcl/Tk and X11, I probably overlooked other > functions that may do what I need. > > Any comments, suggestions on this? > Maybe this can provide a platform independent way to ensure that only > single instance is running. > > Thank you for your attention. > > Best reagrds, > Aki Niimura I know it's a hack but couldn't you just open a specific UDP socket and leave it dangling til your program exits, then if a new instance can't open that same socket it can gracefully abort? If your program dies the socket will be freed up again by the OS yes? Just a thought. Roger. From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 2 10:06:48 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 02 Sep 2008 16:06:48 +0200 Subject: what's the difference between f(a) and f(*a) In-Reply-To: <4b57d4c3-a398-41b1-916a-064ee96bf3f6@25g2000prz.googlegroups.com> References: <4b57d4c3-a398-41b1-916a-064ee96bf3f6@25g2000prz.googlegroups.com> Message-ID: <48bd481e$0$17215$426a74cc@news.free.fr> qxyuestc at yahoo.cn a ?crit : > def sum1(*a): return(sum(i*i for i in a)) > def sum2(a): return(sum(i*i for i in a)) > > a=[1,2,3] > print(sum1(*a), sum2(a)) > #################################### > showed above: the result from sum1() and sum2() is the same. So, what > is the difference between f(a) and f(*a) try this: sum1(a) sum2(*a) Then re-read the FineManual(tm): http://docs.python.org/tut/node6.html#SECTION006730000000000000000 From sotirac at gmail.com Sun Sep 28 15:59:53 2008 From: sotirac at gmail.com (sotirac) Date: Sun, 28 Sep 2008 12:59:53 -0700 (PDT) Subject: generate random digits with length of 5 Message-ID: Wondering if there is a better way to generate string of numbers with a length of 5 which also can have a 0 in the front of the number.
 random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
elements
 code = 'this is a string' + str(random_number[0]) +
str(random_number[1]) + str(random_number[2]) + str(random_number[3])
+ str(random_number[4])
From garyrob at mac.com Mon Sep 8 13:46:08 2008 From: garyrob at mac.com (Gary Robinson) Date: Mon, 08 Sep 2008 13:46:08 -0400 Subject: exit() Message-ID: <20080908134608759530.9d832e42@mac.com> In Python 2.5.2, I notice that, in the interpreter or in a script, I can exit with: exit() But I don't see exit() mentioned as a built-in function; rather the Python Library Reference says we should use sys.exit(). Also, the reference says sys.exit() is like raising SystemExit. But so is just calling exit(). For instance, exit('some error message') has the same apparent effect as raise SystemExit, 'some error message'. Both return a status code of 1 and print the error string on the console. Is exit() documented somewhere I haven't been able to find? Is there any reason to use sys.exit() given exit()'s availability? If there is an advantage to sys.exit() over exit(), then does sys.exit() have any advantage over "raise SystemExit, 'some error message'" in cases where a module has no other reason to import sys? -- Gary Robinson CTO Emergent Music, LLC personal email: garyrob at mac.com work email: grobinson at emergentmusic.com Company: http://www.emergentmusic.com Blog: http://www.garyrobinson.net From rocksportrocker at googlemail.com Tue Sep 9 15:50:45 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Tue, 9 Sep 2008 12:50:45 -0700 (PDT) Subject: F2PY changing integers to arrays??? References: <7d60c85f-12cf-47fc-84c9-58e50cad4eaf@x35g2000hsb.googlegroups.com> Message-ID: On 9 Sep., 18:41, john wrote: > I have a simple module which performs basic operations on plot3d files > (below). ?I wrapped like: > > f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 > > That seems to work fine, but i get some unexpected results... > > >>> from plot3d import plot3d as p3 > >>> dir(p3) > > ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', > 'writeit2d']>>> p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) > >>> p3.imax > > array(409) > > "409" is correct, but "imax" is declared as an INTEGER in fortran and > now it's an array in python??? ?Any ideas? > > # prec.f90 > MODULE prec > IMPLICIT NONE > INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) > INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) > END MODULE prec > > # plot3d.f90 > MODULE PLOT3D > USE prec > IMPLICIT NONE > INTEGER, PARAMETER :: prc=single > REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z > INTEGER :: mg, imax, jmax, kmax > > CONTAINS > > !---------- > ? ? SUBROUTINE READIT( fname, ftype, fmg ) > ? ? ! reads the plot3d, formatted, mg file in xyz > ? ? IMPLICIT NONE > ? ? CHARACTER(len=20), INTENT(IN) :: fname, ftype > > ? ? LOGICAL :: fmg > ? ? INTEGER :: i, j, k, n, f=1 > > ? ? SELECT CASE (ftype) > ? ? ? ? CASE ('FORMATTED') > ? ? ? ? ? ? OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > ? ? ? ? ? ? IF (fmg) READ(f,*) mg ! only read if multigrid > ? ? ? ? ? ? READ(f,*) imax, jmax, kmax > ? ? ? ? ? ? ALLOCATE( x(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? ALLOCATE( y(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? ALLOCATE( z(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? READ(f,*) ((((x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ? ? ? ? ? ? ? ? ? ? ? ((((y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ? ? ? ? ? ? ? ? ? ? ? ((((z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > ? ? ? ? CASE ('UNFORMATTED') > ? ? ? ? ? ? OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > ? ? ? ? ? ? IF (fmg) READ(f) mg ! only read if multigrid > ? ? ? ? ? ? READ(f) imax, jmax, kmax > ? ? ? ? ? ? ALLOCATE( x(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? ALLOCATE( y(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? ALLOCATE( z(mg, imax, jmax, kmax) ) > ? ? ? ? ? ? READ(f) ((((x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ? ? ? ? ? ? ? ? ? ? ((((y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ? ? ? ? ? ? ? ? ? ? ((((z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > ? ? ? ? CASE DEFAULT > ? ? ? ? ? ? WRITE(*,*) 'filetype not supported in ' > ? ? ? ? ? ? STOP > ? ? END SELECT > > ? ? CLOSE(f) > > ? ? END SUBROUTINE READIT > > END MODULE PLOT3D You can generate the according .pyf file with some command line flag I forgot. There you can see what the parser derived from the fortran code and you can edit this file for further configuration of the generated python module. Greetings, Uwe From wuwei23 at gmail.com Sun Sep 28 20:33:47 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 28 Sep 2008 17:33:47 -0700 (PDT) Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> <357e734f-e99f-41e5-9cac-083d636a23e1@n38g2000prl.googlegroups.com> Message-ID: <95f8433c-213f-4b3a-8d93-bebbe2561e7f@s9g2000prg.googlegroups.com> On Sep 29, 5:52?am, robean wrote: > Actually, the problem seems to be that IOError is in my namespace, but > the other error classes are not. So, > > ? ?except HTTPError, etc. > > fails, but > > ? ?except urllib2.HttpError, etc. > > works fine. Now, I still don't understand why these classes shouldn't > automatically work.... IOError is a standard Python exception. HTTPError & URLError are exceptions provided by the urllib2 module. They need to be imported from or referenced through urllib2 to be used. From see.signature at no.spam Wed Sep 24 04:19:35 2008 From: see.signature at no.spam (Eric Brunel) Date: Wed, 24 Sep 2008 10:19:35 +0200 Subject: Python is slow? References: Message-ID: On Tue, 23 Sep 2008 15:23:12 +0200, sturlamolden wrote: [...] Would it be possible to post this text to some "persistent" web page with (links to) the code you wrote in both languages? This would be a very interesting resource for people experiencing some resistence when they suggest Python as a possible language because of the 'Python is slow' myth... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From dave.dibiase at gmail.com Wed Sep 24 18:45:35 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Wed, 24 Sep 2008 18:45:35 -0400 Subject: Schwartzian transform for tuple in list In-Reply-To: <48DAB539.1010500@mattnordhoff.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> Message-ID: <7C3B1753-3E7A-4E1F-B102-3387FB0152A4@gmail.com> When you say slightly, is it enough to make a difference? Why would getitems be faster even - not sure I can think why... Sent from my iPhone On 24-Sep-08, at 5:46 PM, Matt Nordhoff wrote: > Chris Rebert wrote: >> On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase > > wrote: >>> Hi, >>> >>> I have a rather large list structure with tuples contained in them >>> (it's >>> part of a specification I received) looks like so: >>> [(x1,y1,r1,d1),(x2,y2,r2,d2)...] >>> >>> The list can range from about 800-1500 tuples in size and I'm >>> currently >>> sorting it with this: >>> >>> a_list.sort(lambda a, b: cmp(b[3], a[3])) >> >> You'd probably be better off using the 'key' keyword argument to >> .sort(), which is made for the Schwartzian Transform: >> >> a_list.sort(key=lambda x: x[3]) >> >> This sorts the list items by the value produced by the key function >> for each item. It's also (IIRC) faster than using a comparison >> function like you're currently doing. >> >> Regards, >> Chris > > Yes, using 'key' is faster than 'cmp'. > > If you have Python 2.4 or newer, it would also be slightly faster to > use > operator.itemgetter() instead of a lambda: > >>>> import operator >>>> a_list.sort(key=operator.itemgetter(3)) > >>> I'm actually sorting it by the last value in the tuple (d2). I >>> have been >>> researching more efficient sorting algorithms and came across >>> Schwartzian >>> transform via these links: >>> >>> http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency >>> http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html >>> >>> I get what's happening (sorta...errr...lol) but I'm not sure if >>> it is more >>> efficient in my scenario, if it is then I have no idea how to >>> implement it >>> properly :-/ >>> >>> Would be great if a true expert would offer a suggestion for me... >>> >>> Thanks! >>> >>> David > -- From dstromberglists at gmail.com Thu Sep 11 14:56:43 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Thu, 11 Sep 2008 18:56:43 GMT Subject: huge socket recv speed discrepancy between different OSs References: Message-ID: On Thu, 11 Sep 2008 16:17:58 +0200, Thorben Krueger wrote: > Do you see this too? > > Mor information and testcase here: > > http://bugs.python.org/issue3766 > > I would also be interested in the profiler output under windows. > > All the best > Thorben I regret that I don't have a lot of time to look into this interesting issue. Perl may be buffering the socket I/O. That might be a question for comp.lang.perl. Usually, when you can reduce the number of function/method calls and system calls done in your innermost loop(s), especially on a high speed network, you've done a good thing - because otherwise CPU use becomes the dominant term in the performance equation. You might want to try my bufsock module to see if that'll help: http://stromberg.dnsalias.org/~strombrg/bufsock.html It'll give you buffered sockets, along with a flush method. You probably also might want to try psyco when on an x86 system. Unfortunately, it looks like psyco isn't available for x86-64. Anyone know if pypy is ready to try such a program as Thorben's? From hniksic at xemacs.org Fri Sep 12 10:37:54 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Sep 2008 16:37:54 +0200 Subject: Accessing __slots__ from C References: <8763p1799y.fsf@mulj.homelinux.net> Message-ID: <871vzp77lp.fsf@mulj.homelinux.net> Hrvoje Niksic writes: > Chris writes: > >>> descr = GetAttrString(cls,"varname"); >>> offset = descr->d_member->offset; >>> slotvar = (PyObject*)(((char*)obj)+offset) >> >> Unfortunately, I am inexperienced at this kind of thing, so I wasn't >> able to get something working. Maybe someone could tell me what's >> wrong with the code below (it gives the error "'struct _object' has no >> member named 'd_member'")? > > You are getting that error because Carl forgot to cast the descriptor > to the appropriate C type, in this case PyMemberDescrObject. The last > line is also incorrect, I think. Try something like this: > > PyObject *descr = PyObject_GetAttrString(x,"attr_one"); Also note that x should be your object's type, i.e. o->ob_type cast to PyObject *. The complete incantation would be: // outside the loop PyObject *descr = PyObject_GetAttrString((PyObject *) obj->ob_type, "attr_one"); if (!descr) return NULL; int offset = ((PyMemberDescrObject *) descr)->d_member->offset; Py_DECREF(descr); // inside the loop PyObject *value = *(PyObject **)((char *)obj + offset); if (!value) { PyErr_SetString(PyExc_AttributeError, "attribute missing"); return NULL; } // Remember to Py_INCREF(value) before using it and Py_DECREF it after // using it. Otherwise if the object changes its slot to something // else, you might be using a dead object. With this code, accessing the value is practically free once the offset is calculated. Here is a bench3 function updated to use this strategy: static PyObject * bench3(PyObject *ignored, PyObject *obj) { PyObject *descr = PyObject_GetAttrString((PyObject *) obj->ob_type, "abcdef"); if (!descr) return NULL; // Here you should also assert that PyObject_TypeCheck(descr, // PyMemberDescr_Type) holds true. Since PyMemberDescr_Type is static, // you'll have to get it by stashing away ob_type of a value known to be // the descriptor. This is left as excercise to the reader. int offset = ((PyMemberDescrObject *) descr)->d_member->offset; Py_DECREF(descr); int i; PyObject *volatile attr; // 'volatile' for benchmarking, prevents gcc // from optimizing away the loop for (i = 0; i < 1000000; i++) { attr = *(PyObject **)((char *)obj + offset); } Py_INCREF(attr); return attr; // to prove that we retrieved the correct value } >>> t0 = time.time(); attr.bench3(o); t1 = time.time() 1 >>> t1-t0 0.00071597099304199219 # for 1,000,000 iterations, as cheap as it gets From harrrrpo at gmail.com Mon Sep 8 13:23:31 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Mon, 8 Sep 2008 19:23:31 +0200 Subject: Read and write binary data In-Reply-To: References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: <538050a90809081023u56d8fbd6sbfd25860553ba860@mail.gmail.com> I don't know if this is going to help you but a free&open alternative to Matlap is FreeMat just search for it From bdesth.quelquechose at free.quelquepart.fr Mon Sep 29 12:18:15 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2008 18:18:15 +0200 Subject: One class per file? In-Reply-To: References: Message-ID: <48e11bb1$0$7590$426a74cc@news.free.fr> HCB a ?crit : > Hello: > > The book "Code Complete" recommends that you put only one class in a > source file, That's possibly (don't know...) a good advice for C++, and that's mandatory (at least for 'public' classes) in Java. And that's totally pointless and counterproductive in Python. Also and FWIW, "this dead horse as been beaten to hell and back" (IOW : you'll find quite a couple thread discussing this in this newsgroup's archives). From george.sakkis at gmail.com Mon Sep 29 18:00:10 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 29 Sep 2008 15:00:10 -0700 (PDT) Subject: how to search multiple textfiles ? References: Message-ID: On Sep 29, 5:16?am, Lawrence D'Oliveiro wrote: > In message > , George > > Sakkis wrote: > > $ find -name "*py" | xargs egrep "\bword\b" > > Better: > > ? ? find -name '*.py' -exec grep -E "\bword\b" {} \; In what way is this better ? I don't dispute it, I'm just curious. From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 10:56:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 16:56:45 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: Message-ID: <48cbf09c$0$25189$426a74cc@news.free.fr> Larry Bates a ?crit : (snip) > IMHO it reads better if you use the __call__ method of the class to > return the value IMHO, it makes no sense at all to abuse the __call__ magic method here. > and rewrite it as a regular loop for clarity. > Sometimes the simplest way is the easiest to read. > > class FolderInUse: > def __call__(self, archivefolder): > result = False > for instance in self.core.active_outgoing_registration_instances(): > if instance.forbid_to_close(archivefolder): > result = True > break > > return result the loop would be simpler with an early return: for instance in self.core.active_outgoing_registration_instances(): if instance.forbid_to_close(archivefolder): return True return False > > > Then it can be called with: > > if FolderInUse(archivefolder): > ... This will call the class constructor and initializer and return a new instance, not the *instance method* __call__. From ricaraoz at gmail.com Tue Sep 23 09:19:11 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 23 Sep 2008 10:19:11 -0300 Subject: a short-cut command for globals().clear() ?? In-Reply-To: References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> <1f913671-1c21-4018-a841-a5a02a360c3b@k30g2000hse.googlegroups.com> <49ffb44f-c14d-4d38-86fb-eb50e5ef9abf@d1g2000hsg.googlegroups.com> Message-ID: <48D8ECCF.3000201@bigfoot.com> Terry Reedy wrote: > MRAB wrote: >> >> How about something like this: >> >> def clear_workspace(): >> keep_set = set(['__builtins__', '__doc__', '__name__', >> 'clear_workspace']) > > For 2.6/3.0, add __package__ to the list to be kept. > >> for x in globals().keys(): >> if x not in keep_set: >> del globals()[x] Or... you might have a script clearWorkspace.py : --------------------------------------------- initGlobals = globals().keys() def clearWorkspace() : for gVar in globals().keys() : if gVar not in initGlobals : del globals()[gVar] --------------------------------------------- Which you run before doing anything else. Then you don't mind if additions were made to the list to keep, or if you are using something like pyCrust which has its own initial globals, or if you want to keep some global vars of your own (in which case you run clearWorkspace AFTER you instantiate your global vars). From brenNOSPAMbarn at NObrenSPAMbarn.net Tue Sep 2 13:40:54 2008 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Tue, 02 Sep 2008 17:40:54 GMT Subject: Relative imports and "import X as Y" References: Message-ID: Gabriel Genellina wrote: > En Sun, 31 Aug 2008 07:27:12 -0300, Wojtek Walczak > escribi?: > >> On Sun, 31 Aug 2008 06:40:35 GMT, OKB (not okblacke) wrote: >> >>>> Download the latest beta for your system and give it a try. >>> >>> Thanks for the advice, but I'd really rather not deal >>> with >>> installing the entire thing alongside my existing version, >>> possibly causing conflicts in who knows what ways. >> >> Then you can download tar.gz package, compile it, and try it >> without installing :-) > > Or use a virtual machine, or a live CD. Gosh, thanks, everyone, for being so helpful! -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From lutz at rmi.net Tue Sep 9 09:07:33 2008 From: lutz at rmi.net (Mark Lutz) Date: Tue, 9 Sep 2008 06:07:33 -0700 (PDT) Subject: Python training in Colorado, October 15-17 Message-ID: <34cec5fb-d145-4bb6-8178-8ce8c15ac53b@34g2000hsh.googlegroups.com> Python author and trainer Mark Lutz will be teaching another 3-day Python class at a conference center in Longmont, Colorado, on October 15-17, 2008. This is a public training session open to individual enrollments, and covers the same topics as the 3-day onsite sessions that Mark teaches, with hands-on lab work. The class provides an in-depth introduction to Python and its common applications, and parallels the instructor's popular Python books. For more information on this session, please visit its web page: http://home.earthlink.net/~python-training/longmont-public-classes.htm For additional background on the class itself, see our home page: http://home.earthlink.net/~python-training Thanks for your interest. --Python Training Services From v1p3r2 at gmail.com Tue Sep 2 18:23:50 2008 From: v1p3r2 at gmail.com (v1p3r) Date: Tue, 2 Sep 2008 23:23:50 +0100 Subject: Completely unable to install Python on Windows Message-ID: I'm attempting to install Python 2.5.2 (python-2.5.2.amd64.msi) on my Vista SP1 x64 system, but the installer always crashes with a "Windows Installer has stopped working" error after clicking Next on the initial screen. I've tried the following so far: 1. x86 and x64 versions 2. Manually reinstalling Windows Installer 4.5 3. Forcing msiexec to run as administrator 4. Installing both globally and for my user alone 5. Silent install 6. The previous version (2.5.1) 7. Repeating the above with a completely clean install of Vista SP1 x64 in VMWare It seems that no matter what I do, the problem persists. ActivePython produces a similar error, but much later in the install. This has me completely baffled, since nobody else seems to have a similar issue despite it happening on a completely stock install of Windows. Any help would be greatly appreciated. - Josh (The output of msiexec with logging enabled follows) === Logging started: 02/09/2008 23:11:12 === Action 23:11:12: INSTALL. Action start 23:11:12: INSTALL. Action 23:11:12: LaunchConditions. Evaluating launch conditions Action start 23:11:12: LaunchConditions. Action ended 23:11:12: LaunchConditions. Return value 1. Action 23:11:12: WhichUsersDlg. Action start 23:11:12: WhichUsersDlg. Info 2898. For VerdanaBold10 textstyle, the system created a 'Verdana' font, in 1 character set, of 16 pixels height. Info 2898. For DlgFont8 textstyle, the system created a 'Tahoma' font, in 1 character set, of 14 pixels height. Action 23:11:12: WhichUsersDlg. Dialog created Action ended 23:11:14: WhichUsersDlg. Return value 1. Action 23:11:14: FindRelatedProducts. Searching for related applications Action start 23:11:14: FindRelatedProducts. Action ended 23:11:14: FindRelatedProducts. Return value 1. Action 23:11:14: AppSearch. Searching for installed applications Action start 23:11:14: AppSearch. Action ended 23:11:14: AppSearch. Return value 1. Action 23:11:14: CCPSearch. Searching for qualifying products Action start 23:11:14: CCPSearch. Action ended 23:11:14: CCPSearch. Return value 1. Action 23:11:14: RMCCPSearch. Searching for qualifying products Action start 23:11:14: RMCCPSearch. Action ended 23:11:14: RMCCPSearch. Return value 0. Action 23:11:14: ValidateProductID. Action start 23:11:14: ValidateProductID. Action ended 23:11:14: ValidateProductID. Return value 1. Action 23:11:14: InitialTargetDir. Action start 23:11:14: InitialTargetDir. Action ended 23:11:14: InitialTargetDir. Return value 1. Action 23:11:14: SetDLLDirToSystem32. Action start 23:11:14: SetDLLDirToSystem32. Action ended 23:11:14: SetDLLDirToSystem32. Return value 1. Action 23:11:14: CostInitialize. Computing space requirements Action start 23:11:14: CostInitialize. Action ended 23:11:14: CostInitialize. Return value 1. Action 23:11:14: FileCost. Computing space requirements Action start 23:11:14: FileCost. Action ended 23:11:14: FileCost. Return value 1. Action 23:11:14: IsolateComponents. Action start 23:11:14: IsolateComponents. Action ended 23:11:14: IsolateComponents. Return value 1. Action 23:11:14: CostFinalize. Computing space requirements Action start 23:11:14: CostFinalize. Action ended 23:11:14: CostFinalize. Return value 1. Action 23:11:14: MigrateFeatureStates. Migrating feature states from related applications Action start 23:11:14: MigrateFeatureStates. Action ended 23:11:14: MigrateFeatureStates. Return value 0. Action 23:11:14: SelectDirectoryDlg. Action start 23:11:14: SelectDirectoryDlg. From cjw at ncf.ca Wed Sep 10 17:04:57 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 10 Sep 2008 17:04:57 -0400 Subject: Python and Open Office In-Reply-To: References: Message-ID: Marco Bizzarri wrote: > On Wed, Sep 10, 2008 at 10:04 PM, Greg Lindstrom wrote: >> Hello, >> >> I would like to create and manipulate Open Office documents using Python. I >> have found then UNO Python page and odfpy modules which seem to be exactly >> what I need. The odfpy manual is, to me, a confusing list of objects and >> methods (it's an impressive list!), but does not have much in the way of how >> to use them. For example, I can open a spreadsheet and create new pages >> (there's a nice example near the back of the manual) but I can't figure out >> how to open an existing spreadsheet and list the names of the individual >> sheets ("tabs"). >> >> I have written an application that access Microsoft Excel and creates >> reports for work, but would like to create an Open Source version using Open >> Office and release it to the community (and maybe get a talk at PyCon :-). >> >> Is there someone here who can help me out, or is there an appropriate >> mailing list for me to join? > > Ciao, Greg. > > you should check with the openoffice.org mailing list; I think what > you are looking for is the api mailing list for openoffice; you could > try to get the OpenOffice.org developers guide and the SDK, and check > it (but it is not a little work) > > Regards > Marco > > >> Thanks >> >> --greg >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > Greg, If you follow this up, I hope that you will post info to c.l.p and let us know whether the UNO interface is Python 2.5 compatible. The last time I looked it was set for 2.3 or 2.4. Colin W From hrishys at yahoo.co.uk Wed Sep 24 11:22:28 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Wed, 24 Sep 2008 15:22:28 +0000 (GMT) Subject: Linq to Python In-Reply-To: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> Message-ID: <326492.90059.qm@web27405.mail.ukl.yahoo.com> Hi Well wouldn't it be a lot easier to query and join a xml source with a relational source with LINQ capabilites in Python. Hmm what am i missing here is there a site that takes all LINQ examples and does them using list comprehensions and makes them sound easy ? wasn't python supposed to make everything easy ? regards Hrishy --- On Tue, 23/9/08, sturlamolden wrote: > From: sturlamolden > Subject: Re: Linq to Python > To: python-list at python.org > Date: Tuesday, 23 September, 2008, 7:49 PM > On Sep 23, 4:48?pm, hrishy > wrote: > > > Will LINQ be ported to Python ? > > No, because Python already has list comprehensions and we > don't need > the XML buzzword. > -- > http://mail.python.org/mailman/listinfo/python-list From robert.kern at gmail.com Tue Sep 23 16:16:07 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 15:16:07 -0500 Subject: Python is slow? In-Reply-To: References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: sturlamolden wrote: > On Sep 23, 9:17 pm, Robert Kern wrote: > >> You could also drop it on the scipy.org wiki in the Cookbook category. > > Yes, if I could figure out how to use it... What's confusing? You do have to create a profile: http://www.scipy.org/UserPreferences -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From duncan.booth at invalid.invalid Thu Sep 11 04:00:27 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Sep 2008 08:00:27 GMT Subject: universal unicode font for reportlab References: Message-ID: Tim Roberts wrote: > Duncan Booth wrote: >> >>Laszlo Nagy wrote: >> >>> I need to use HTML anyway. I realized that universal unicode fonts >>> are above 5MB in size. The report would be a 10KB PDF, but I need to >>> embed the font before I can send it to anyone. Since some reports >>> needs to be sent in emails, I need to use something else. I cannot >>> be sending 10MB emails for "one page" reports. >>> >>I thought that usually when you embed a font in a PDF only the glyphs >>which are actually used in the document get embedded. Unfortunately a >>quick test with reportlab seems to show that it doesn't do that >>optimisation: it looks as though it just embeds the entire font. > > No, it does subsetting. There was a debate a year or two ago on the > reportlab list about how the font subset should be named in the > resulting PDF file. > > Is it possible you have an older release? It was 2.1 downloaded about 30 minutes before my post. The not too scientific test I did was to copy the font embedding example from the Reportlab documentation, modify it enough to make it actually run, and then change the output to have only one glyph. The resulting PDF is virtually identical. I'm not a reportlab expert though so I may have made some blindingly obvious beginners mistake (or maybe it only subsets fonts over a certain size or glyphs outside the ascii range?). ---------- rlab.py ------------ import os, sys import reportlab folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts' afmFile = os.path.join(folder, 'LeERC___.AFM') pfbFile = os.path.join(folder, 'LeERC___.PFB') from reportlab.pdfbase import pdfmetrics justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile) faceName = 'LettErrorRobot-Chrome' # pulled from AFM file pdfmetrics.registerTypeFace(justFace) justFont = pdfmetrics.Font('LettErrorRobot-Chrome',faceName,'WinAnsiEncoding') pdfmetrics.registerFont(justFont) from reportlab.pdfgen.canvas import Canvas canvas = Canvas('temp.pdf') canvas.setFont('LettErrorRobot-Chrome', 32) if sys.argv: canvas.drawString(10, 150, 'TTTT TTTTTT TT TT') canvas.drawString(10, 100, 'TTTTTTTTTTTTTTTTTTTTT') else: canvas.drawString(10, 150, 'This should be in') canvas.drawString(10, 100, 'LettErrorRobot-Chrome') canvas.save() ------------------------------- -- Duncan Booth http://kupuguy.blogspot.com From steve at REMOVE-THIS-cybersource.com.au Thu Sep 4 02:26:06 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 06:26:06 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> Message-ID: <00cf79ec$0$20302$c3e8da3@news.astraweb.com> On Wed, 03 Sep 2008 22:20:43 -0700, Mensanator wrote: > On Sep 3, 8:30?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: >> >>>> sum([]) >> > 0 >> >> > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. >> > It should return None or throw an exception like sum([None,1]) does. >> >> You're wrong, because 99.9% of the time when users leave a blank cell >> in Excel, they want it to be treated as zero. > > Then 99.9% of users want the wrong thing. It is to laugh. > Microsoft knows that this is a bug Says you. > but refuses to fix it to prevent breaking legacy documents (probably > dating back to VisiCalc). When graphimg data, a missing value should be > interpreted as a hole in the graph "Graphing data" is not sum(). I don't expect graphing data to result in the same result as sum(), why would I expect them to interpret input the same way? > +------+ +--+------+------+-----+ Why should the graphing application ignore blanks ("missing data"), but sum() treat missing data as an error? That makes no sense at all. > and not evaluated as 0 > > And Microsoft provides a workaround for graphs to make 0's appear as > holes. Of course, this will cause legitimate 0 values to disappear, so > the workaround is inconsistent. I'm not aware of any spreadsheet that treats empty cells as zero for the purpose of graphing, and I find your claim that Excel can't draw graphs with zero in them implausible, but I don't have a copy of Excel to test it. >> Spreadsheet sum() is not the >> same as mathematician's sum, which doesn't have a concept of "blank >> cells". (But if it did, it would treat them as zero, since that's the >> only useful thing and mathematicians are just as much pragmatists as >> spreadsheet users.) The Excel code does the right thing, and your >> "pure" solution would do the unwanted and unexpected thing and is >> therefore buggy. > > Apparently, you don't use databases or make surface contours. Neither databases nor surface contours are sum(). What possible relevance are they to the question of what sum() should do? Do you perhaps imagine that there is only "ONE POSSIBLE CORRECT WAY" to deal with missing data, and every function and program must deal with it the same way? > Contour programs REQUIRE that blanks are null, not 0 Lucky for them that null is not 0 then. > so that the Kriging > algorithm interpolates around the holes rather than return false > calculations. Excel's treatment of blank cells is inconsistent with > Access' treatment of Nulls and therefore wrong, anyway you slice it. No no no, you messed that sentence up. What you *really* meant was: "Access' treatment of Nulls is inconsistent with Excel's treatment of blank cells and therefore wrong, anyway you slice it." No of course not. That would be stupid, just as stupid as your sentence. Excel is not Access. They do different things. Why should they necessarily interpret data the same way? > Maybe you want to say a bug is when it doesn't do what the author > intended, but I say if what the intention was is wrong, then a perfect > implentation is still a bug because it doesn't do what it's supposed to > do. Who decides what it is supposed to do if not the author? You, in your ivory tower who doesn't care a fig for what people want the software to do? Bug report: "Software does what users want it to do." Fix: "Make the software do something that users don't want." Great. >> Bugs are defined by "does the code do what the user wants it to do?", >> not "is it mathematically pure?". > > ReallY? So you think math IS a democracy? There is no reason to violate > mathematical purity. You've given a good example yourself: the Kriging algorithm needs a Null value which is not zero. There is no mathematical "null" which is distinct from zero, so there's an excellent violation of mathematical purity right there. If I am given the job of adding up the number of widgets inside a box, and the box is empty, I answer that there are 0 widgets inside it. If I were to follow your advice and declare that "An error occurred, can't determine the number of widgets inside an empty box!" people would treat me as an idiot, and rightly so. > If I don't get EXACTLY the same answer from Excel, > Access, Mathematica and Python, then SOMEBODY is wrong. It would be a > shame if that somebody was Python. Well Excel, Python agree that the sum of an empty list is 0. What do Access and Mathematica do? >> The current behaviour of sum([]) does the right thing for the 99% of >> the time when users expect an integer. > > Why shouldn't the users expect an exception? Isn't that why we have > try:except? Maybr 99% of users expect sum([])==0, but _I_ expect to be > able to distinguish an empty list from [4,-4]. The way to distinguish lists is NOT to add them up and compare the sums: >>> sum([4, -4]) == sum([0]) == sum([1, 2, 3, -6]) == sum([-1, 2, -1]) True The correct way is by comparing the lists themselves: >>> [] == [4, -4] False >> And the >> rest of the time, they have to specify a starting value for the sum >> anyway, and so sum([], initial_value) does the right thing *always*. > > So if you really want [] to be 0, why not say sum([],0)? I don't want [] == 0. That's foolish. I want the sum of an empty list to be 0, which is a very different thing. And I don't need to say sum([],0) because the default value for the second argument is 0. > Why shouldn't nothing added to nothing return nothing? Having it > evaluate to 0 is wrong 99.9% of the time. It is to laugh. What's the difference between having 0 widgets in a box and having an empty box with, er, no widgets in it? -- Steven From steve at holdenweb.com Thu Sep 18 20:48:42 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Sep 2008 20:48:42 -0400 Subject: Extracting hte font name from a TrueType font file In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Steve Holden wrote: > >> Does anyone have a Python recipe for this? > >>>> from PIL import ImageFont >>>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1) >>>> f.font.family > 'Verdana' >>>> f.font.style > 'Italic' > Thanks so much, Fredrik. The reason I asked is because I found the specification completely opaque ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From clp at rebertia.com Mon Sep 29 22:03:51 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Sep 2008 19:03:51 -0700 Subject: Python arrays and sting formatting options In-Reply-To: References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6d265f36-352c-4866-bf91-c14d26101fc2@k37g2000hsf.googlegroups.com> Message-ID: <47c890dc0809291903l2df1e572h13eea9fc4d6a2cd3@mail.gmail.com> On Mon, Sep 29, 2008 at 6:56 PM, Ivan Reborin wrote: > On Mon, 29 Sep 2008 17:59:40 -0700 (PDT), bearophileHUGS at lycos.com > wrote: > > Hello bearophile, thank you for replying. > >>The Python genie grants you that wish. You were almost right: >>>>> print (3 * '%12.3f') % (a, b, c) >> 2.000 123456.789 1234.000 >>>>> print 3 * '%12.3f' % (a, b, c) >> 2.000 123456.789 1234.000 > Works beautifully :-) Thank you! > >>>>> print 3 * '%12.3f' % a, b, c >>Traceback (most recent call last): >> File "", line 1, in >>TypeError: not enough arguments for format string > > Just one more question - it's actually an extension to this one > (forgive my curiosity, but I really need this info, and searching > google always gives me the same stuff again and again) ... > > a = 2.000001 > b = 123456.789 > c = 1234.0001 > d = 98765.4321 > # same as above except for d > > print (3 * '%12.3f') % (a, b, c) > #this works beautifully > > How to add d at the end but with a different format now, since I've > "used" the "format part" ? > > Again, my weird wishful-thinking code: > print (3*'%12.3f', '%5.3f') %(a,b,c),d Again, very close to the correct code: print (3*'%12.3f' + '%5.3f') %(a,b,c,d) Regards, Chris > > >>(Note the spaces and parentheses. Python programmers thank you if put >>them improving readability a little). > > Yes, ok. I can agree with that - separating the format from the > variable list part sounds reasonable. > >> >>Bye, >>bearophile > > -- > Ivan > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 03:06:17 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 09:06:17 +0200 Subject: Why no tailcall-optimization? In-Reply-To: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: <48d89564$0$11995$426a74cc@news.free.fr> process a ?crit : > Why doesn't Python optimize tailcalls? Design choice. tail-recursive calls optimization makes debugging harder. Note that this has been discussed quite a few times here. > Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. While it has some (limited) support for functional idioms, Python is still mostly an imperative language, and as such favors iteration over recursion. Not being able to do XXX is only a PITA if you know no other way to skin the cat. NB : FWIW, I'd personnally prefer to have tail-recursive calls optimization too - but not badly enough to switch to another language... From david at boddie.org.uk Thu Sep 18 15:58:47 2008 From: david at boddie.org.uk (David Boddie) Date: Thu, 18 Sep 2008 21:58:47 +0200 Subject: Python and Open Office References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Wednesday 17 September 2008 21:59, Terry Reedy wrote: > Hartmut Goebel wrote: >> Terry Reedy schrieb: >> >> The API docs are a bit hidden on the webpage. Here is the link: >> > > I wrote my comment *after* looking at the above, which I found easily > enough. After 7 pages of (helpful) explanatory text, there follow 88 > pages with hundreds of entries like this: [...] > which are translated to a more readable form from the Relax-NG schema > (formal specs) in the standard. But I have no idea what a Ruby property > is in this context. It would be much like reading the grammar entries > in the Python Reference without the explanatory text that follows. I started using odfpy for a project, and I found that I spent a lot of time flicking back and forth in the API manual and cross-referencing it with the specification. The simple examples were useful enough to get started with, but I could have used more information about how to use certain classes and what elements and attributes they required. I also wanted to add equations to the documents I was producing and that requires some knowledge of MathML. Certainly, it's not a very high level API for documentation creation - you need to know something about the format to be able to construct documents. David From eckhardt at satorlaser.com Wed Sep 10 03:32:35 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 10 Sep 2008 09:32:35 +0200 Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: icarus top-posted: > one more question... ...deserves a separate thread. > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? Either it is Python, then it is portable but no executable, or it is an executable, then it is standalone but not portable. I'm afraid what you are asking for is not possible. Other than that, others told you how to easily get a standalone executable. Uli [ 35 lines of uselessly quoted content removed ] -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From eliben at gmail.com Sat Sep 20 01:01:14 2008 From: eliben at gmail.com (eliben) Date: Fri, 19 Sep 2008 22:01:14 -0700 (PDT) Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: On Sep 18, 6:01?pm, Tim Golden wrote: > Joe G (Home) wrote: > > Hi All, > > > Background > > =================== > > I have installed Python for windows today from the python web site ?.I also > > installed pySerial using the Windows installer from the sourceforge web > > site..... Both installs use the default directories. > > > Phyton ?version ? ?: Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > > v.1310 32 bit (Intel)] on win32 > > > pySerial ? 2.4 ? July 6th > > > Problem : ?Errors Screen output > > ============================ > >>>> import serial > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? import serial > > ? File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in > > > > ? ? from serialwin32 import * > > ? File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in > > > > ? ? import win32file ?# The base COM port and file IO functions. > > ImportError: No module named win32file > > You need to install the pywin32 extensions from: > > ?http://pywin32.sf.net > > They're so commonly used (and, if you install the ActiveState > distro of Python, even bundled) that I imagine many Windows > Pythoneers like myself simply install them automatically as > soon as we've installed the main python.org Python. > > Once you've done that, the rest should just work: it's > clear from the traceback that the serial module is getting > imported; it's just trying to find the win32file module. > Why are people preferring the python.org package over ActiveState's, which seems to be more complete and includes more modules (like pywin32) ? Eli From castironpi at gmail.com Thu Sep 4 16:04:54 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 13:04:54 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: <3a59a1d4-4478-49e5-8316-9d27c09f55b0@m3g2000hsc.googlegroups.com> On Sep 4, 2:51?pm, Martin DeMello wrote: > On Sep 4, 12:41?pm, Fredrik Lundh wrote: > > > "task_done" just decrements a counter (incremented by "put"). ?when the > > counter reaches zero, the "join" call is unblocked. > > Thanks! Is there any standard python idiom to empty a queue into a > list? Or do I just call get() repeatedly and catch the exception when > it's done? > > martin Random access isn't supported by the defined interface. You can make it more convenient, though. import Queue class IterQueue( Queue.Queue ): def __iter__( self ): return self def next( self ): if self.empty(): raise StopIteration return self.get() q= IterQueue() q.put( 'a' ) q.put( 'b' ) q.put( 'c' ) print [ x for x in q ] /Output: ['a', 'b', 'c'] From dickinsm at gmail.com Thu Sep 25 05:42:20 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 25 Sep 2008 02:42:20 -0700 (PDT) Subject: Comparing float and decimal References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: <99a7ab2c-601e-47fe-8ece-5f9150c10f7a@k30g2000hse.googlegroups.com> On Sep 24, 6:18?pm, Terry Reedy wrote: > If there is not now, there could be in the future, and the decimal > authors are committed to follow the standard wherever it goes. > Therefore, the safe course, to avoid possible future deprecations due to > doing too much, is to only do what is mandated. Makes sense. It looks as though the standard's pretty stable now though; I'd be quite surprised to see it evolve to include discussion of floats. But then again, people thought it was stable just before all the extra transcendental operations appeared. :-) > For integral values, this is no problem. > ?>>> hash(1) == hash(1.0) == hash(decimal.Decimal(1)) == > hash(fractions.Fraction(1)) == 1 > True Getting integers and Decimals to hash equal was actually something of a pain, and required changing the way that the hash of a long was computed. The problem in a nutshell: what's the hash of Decimal('1e100000000')? The number is clearly an integer, so its hash should be the same as that of 10**100000000. But computing 10**100000000, and then finding its hash, is terribly slow... (Try hash(Decimal('1e100000000')) in Python 2.5 and see what happens! It's fixed in Python 2.6.) As more numeric types get added to Python, this 'equal implies equal hash' requirement becomes more and more untenable, and difficult to maintain. I also find it a rather unnatural requirement: numeric equality is, to me, a weaker equivalence relation than the one that should be used for identifying keys in dictionaries, elements of sets, etc. Fraction(1, 2) and 0.5 should, to my eyes, be considered different elements of a set. But the only way to 'fix' this would be to have Python recognise two different types of equality, and then it wouldn't be Python any more. The SAGE folks also discovered that they couldn't maintain the hash requirement. > Decimals can also be converted to floats (they also have a ?__float__ > method). ?But unlike fractions, the conversion must be explicit, using > float(decimal), instead of implicit, as with ints and fractions. Maybe: if I *had* to pick a direction, I'd make float + Decimal produce a Decimal, on the basis that Decimal is arbitrary precision and that the float->Decimal conversion can be made losslessly. But then there are a whole host of decisions one has to make about rounding, significant zeros, ... (And then, as you point out, Cowlishaw might come out with a new version of the standard that does include interactions with floats, and makes an entirely different set of decisions...) Mark From steve at REMOVE-THIS-cybersource.com.au Sun Sep 21 19:05:15 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 23:05:15 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <00e6cd16$0$20303$c3e8da3@news.astraweb.com> Fixing top-posting. On Mon, 22 Sep 2008 08:54:43 +1000, James Mills wrote: > On Mon, Sep 22, 2008 at 8:39 AM, Steven D'Aprano > wrote: >> I have a class which is not intended to be instantiated. Instead of >> using the class to creating an instance and then operate on it, I use >> the class directly, with classmethods. Essentially, the class is used >> as a function that keeps state from one call to the next. [...] > Hi, > > Wouldn't a normal class called State > suffice for storing state between calls ? And ... Creating a state > instance ? > > For example: [snip] That's a rather big example for a rather small question. Yes, a normal class would work in many cases. In this case, the class itself is being produced by a factory function, and it's output is an iterator. Having to call: cls = factory() instance = cls() result = instance() to get anything done seems excessive, even if you write it as a one-liner result = factory()()(). I'm not wedded to the idea, there are alternatives (perhaps the factory should instantiate the class and return that?) but I assume others have used this design and have a name for it. -- Steven From luigipaioro at libero.it Tue Sep 9 11:53:57 2008 From: luigipaioro at libero.it (Luigi) Date: Tue, 9 Sep 2008 08:53:57 -0700 (PDT) Subject: XML-RPC "filter" Message-ID: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> Dear all, I'm writing an XML-RPC server which should be able to modify the incoming request before dispatching it. In particular I wand to added two fixed parameters to the method called: one is the client host address, and the other is the user name provided as for Basic Authentication (http://user at www.bla-bla.com). To do this, at the present I've overwritten the do_POST method of SimpleXMLRPCRequestHandler, including at a certain point this code: .... data = ''.join(L) params, method = xmlrpclib.loads(data) user = "unknown" if self.headers.has_key('Authorization'): # handle Basic authentication (enctype, encstr) = self.headers.get('Authorization').split() user, password = base64.standard_b64decode(encstr).split(':') params = list(params) params.append(self.address_string()) params.append(user) params = tuple(params) data = xmlrpclib.dumps(params, methodname=method) (I slightly modified it to make it more readable at mail level) It works, but I don't really like it because it completely overwrites the do_POST method that in the future Python releases is going to change (I verified it). Do you know a better way to do this? Thanks in advance. Luigi From half.italian at gmail.com Sun Sep 14 23:35:38 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 14 Sep 2008 20:35:38 -0700 (PDT) Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: On Sep 14, 7:10?pm, Grant Edwards wrote: > On 2008-09-15, Ben Finney wrote: > > > > > Grant Edwards writes: > >> On 2008-09-14, Ben Finney wrote: > > >>> Second: please do yourself a favour and drop the > >>> camelCaseNames. Follow PEP 8 > >>> for style and > >>> naming in your Python code. > > >> If he finds camelcase more readable and easier to type (as do > >> I), how is switching to underscores "doing himself a favor"? > > >> I'm generally in favor of using a consistent naming style > >> throughout a project, but I don't see why the naming style > >> used in my source code should be subject to somebody else's > >> arbitrary standard. > > > Because the code we write rarely stays isolated from other > > code. There is an existing convention, > > There are many existing conventions. > > > and it's better to pick a (sufficiently sane) style convention > > and stick to it than argue about what the convention should > > be. > > I suppose if everybody agreed to pick one, and all the source > code in the world was changed to meet it, that would "a good > thing". ?It just seems like a goal so unrealistic as to make it > a bit of an overstatement to tell people they're better off > following convention X than following convention Y. > > When packages as significant as wxPython use naming conventions > other than PEP 8, I find it hard to make a case that the PEP 8 > naming convention is any better than any other. > > >> When it comes to writing code intended for the standard > >> library in the main Python distribution, I would certainly > >> defer to the existing standard as defined in PEP 8. ?However, > >> I don't see any reason that style should be imposed on all > >> everybody else. > > > Who's imposing? I'm saying it's a good idea for everyone to do > > it, and going so far as to say that one is doing oneself a > > favour by following the convention. I have no more power than > > you to "impose" convention on anyone. > > My apologies -- "impose" was too strong a word to use. > > If we were starting from scratch and there was no extant source > code in the world, then it would make sense to encourage > everybody to pick one convention. [I still think it would be > rather quixotic.] But, there are so many projects out there > with naming conventions other than PEP 8, that I don't see how > there's an advantage to picking one over another (except for > the obvious also-rans like "all upper case, no vowels, and a > maximum length of 6 characters"). > > I'll agree that sticking with a single convention within a > project is definitely a good thing. > > I'm personally aware of mixed/camel-case projects from 25+ > years ago, so I'm afraid PEP 8 came along a bit too late... > > -- > Grant +1 CamelCase FTW! ~Sean From uomiocenekidd at gmail.com Mon Sep 22 06:39:38 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:39:38 -0700 (PDT) Subject: download from redtube - Free Message-ID: download from redtube . . . *******CLICK HERE******** http://vids365.cn/download-from-redtube ***************************** . . . . . . . . . . . . download from redtube From bignose+hates-spam at benfinney.id.au Mon Sep 29 19:14:11 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 Sep 2008 09:14:11 +1000 Subject: One class per file? References: <87od27rssp.fsf@benfinney.id.au> <076ab8f2-551d-478f-b31a-df0be47987da@y71g2000hsa.googlegroups.com> Message-ID: <87k5cusfy4.fsf@benfinney.id.au> HCB writes: > The "Put one class in one file" statement is made in "Code Complete > 2" page 771. Thanks. I don't have the second edition; I wonder what the context of that advice is? Perhaps he's speaking only of C++ or Java. Certainly I'd expect the author to reconsider that advice for languages (such as Python) where classes are routinely quite small and there are no technical barriers to grouping multiple classes in a file. -- \ ?I believe in making the world safe for our children, but not | `\ our children's children, because I don't think children should | _o__) be having sex.? ?Jack Handey | Ben Finney From fredrik at pythonware.com Sun Sep 14 07:36:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Sep 2008 13:36:41 +0200 Subject: Why some blog entries at MSN Space support rss feed while others don't? In-Reply-To: References: Message-ID: liuyuprc wrote: > Not sure if this is the place this question should even be raised it isn't. From maric at aristote.info Fri Sep 5 10:30:50 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 16:30:50 +0200 Subject: Case-insensitive string compare? In-Reply-To: <1220623239.5787.10.camel@aalcdl07.lib.unc.edu> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809051536.45285.maric@aristote.info> <1220623239.5787.10.camel@aalcdl07.lib.unc.edu> Message-ID: <200809051630.51113.maric@aristote.info> Le Friday 05 September 2008 16:00:39 J. Cliff Dyer, vous avez ?crit?: > Please keep the discussion on-list. > Sorry for the private email, I sent it again to the list.. > On Fri, 2008-09-05 at 15:36 +0200, Maric Michaud wrote: > > Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez ?crit : > > > On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: > > > > Thanks everyone for your help. I'm not opposed to using [key.lower() > > > > for key in stage_map] at all, I was just curious to see if there were > > > > any cleaner alternatives. It looks like that is what I'll be using. > > > > I'm not familiar with how python works internally, but coming from > > > > C++ it seems like "remaking" the map would be slow. However, speed is > > > > not my main concern in my particular situation, I'm just curious to > > > > learn more about python. > > > > > > You should be opposed to that particular solution. You have just taken > > > a dictionary lookup (very fast) and turned it into a list traversal > > > (slow). Even if speed isn't your main concern, this is an unnecessary > > > de-optimization. You are deliberately slowing down your program to > > > avoid a slightly more verbose lookup later. Your data structure might > > > as well be a list of tuples to begin with, to avoid creating a new > > > list. You have effectively made your keys useless as keys. > > > > > > If your lookups need to be case insensitive, make the key lower case, > > > and store the cased version in the value, whether as a tuple or a dict > > > (depending on whether you want named access). > > > > > > d = { > > > 'foo': {'key': 'Foo', 'value': 'val1'} > > > 'spam': {'key': 'sPAm', 'value': 'val2'} > > > } > > > > > > search = 'FOO'.lower() > > > if search in d: > > > result = d[search] > > > key = result['key'] > > > value = result['value'] > > > > > > The only reason I wouldn't use this solution is if you expect to have > > > keys that will be identical when made lowercase, but if you're doing > > > case-insensitive lookup, you obviously don't expect this to be an > > > issue. > > > > The OP has already said the keys are case-sensitive, so this is not an > > option, the only way to do it fast is to index upon insertion all keys in > > another dict, so you get in final : > > d = { "kEy1" : 1, "Key1" : 2} > > indexes = { "key1" : ["kEy1", "Key1" ] } > > That does not get the same behavior as the OP's original solution. The > OP's solution retrieves the first matching value only. Mine gets one > arbitrary matching value, determined by the algorithm used for > constructing the search dict (not specified in my solution). string.lower() in indexes gives the same result, but your right, a set of lowered keys could suffice for the exact OP's requirement. > What the > OP actually said was that he can't throw away the case. You assume that > this means there would be multiple entries distinguished only by case. > That might be true, but given his initial solution, it seemed to me more > likely that he wants to keep the case for display purposes, as in a > dictionary like this: > > { > "Michaud": "Maric", > "Dyer": "Cliff", > "D'Amato": "Alphonse", > } > I didn't want to make gratuitous extrapolations on the OP's data structure, but I still think the OP's question was "how to write cleanly a case-insensitive comparaison versus all the keys of a dict". Maybe I'm wrong. -- _____________ Maric Michaud From castironpi at gmail.com Mon Sep 8 23:58:53 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 8 Sep 2008 20:58:53 -0700 (PDT) Subject: lacking follow-through References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: On Sep 8, 2:21?pm, Grant Edwards wrote: > On 2008-09-08, Chris Rebert wrote: > > > On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman wrote: > > >> To expand on this a little bit, I've been subscribed to this > >> group for a couple of months, but there seems to be a bit more > >> gray area between what would go to a 'python-dev' group and a > >> 'python-user' group. ?Long debates about language features and > >> abstract ideas would appeal to the former, but not the latter. > >> Certainly I fall into the user category.. ?I'm pretty happy > >> with python, and generally just adjust to it's design and > >> features, rather than spend lots of time on whether they are > >> 'right' or could be 'better'. ?/shrug > > > Yeah, suggestions about changing the language are much better > > suited to the more-specific Python-ideas or Python-3000 > > mailinglists than the general-purpose c.l.p > > I don't think anybody here in c.l.p minds reading suggestions > for language features/changes, but often what the poster in > question writes is just an incomprehensible collection of > vaguely philosophical-sounding metaphores and similes > reminiscent of a hoax paper submitted as a joke to a > post-modern "journal" of some pretend science or other. > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! Used staples are good > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? with SOY SAUCE! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ? I would almost say Grant's criticism is too harsh, and I don't think 'incomprehensible metaphors' is really a problem on Py-Dev or CL-Py, though I feel that sometimes people aren't posting in earnest. I certainly have heard some in real life though. In some cases, I have observed that people are expressing things that they genuinely have perceived, and merely haven't applied the logic necessary to notice the inconsistency in their metaphor, which is the thing that makes them 'incomprehensible' to mature logicians like Grant. For example, I sometimes hear people talk about salary as though it were social approval, and vice versa. Even though the analogy doesn't hold in every case generally, it is still a good way to express yourself in many contexts, and especially when the more precise word isn't on the tip of your tongue. From tilmaniac at gmail.com Mon Sep 29 14:37:43 2008 From: tilmaniac at gmail.com (Tilman Kispersky) Date: Mon, 29 Sep 2008 11:37:43 -0700 (PDT) Subject: Cannot install pysqlite on Cygwin References: Message-ID: On Sep 29, 7:49?am, Steve Holden wrote: > Tilman Kispersky wrote: > > I am trying to install sqlite for use with python oncygwin. I have > > installed the sqlite packages fromcygwin(that is libsqlite3-devel > > and libsqlite3_0). ?When attempting to easy_install pysqlite I get: > > > $ easy_install pysqlite > > Searching for pysqlite > > Readinghttp://pypi.python.org/simple/pysqlite/ > > Readinghttp://pysqlite.org/ > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ > > Readinghttp://pysqlite.sourceforge.net/ > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/ > > Readinghttp://initd.org/tracker/pysqlite/wiki/PysqliteDownloads > > Readinghttp://oss.itsystementwicklung.de/trac/pysqlite > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/ > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/ > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/ > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/ > > Best match: pysqlite 2.5.0 > > Downloadinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlit... > > Processing pysqlite-2.5.0.tar.gz > > Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/ > > Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg- > > dist-tmp-7mr3WS > > warning: no files found matching 'doc/*.html' > > warning: no files found matching 'doc/code/*.py' > > src/statement.c: In function `pysqlite_statement_recompile': > > src/statement.c:351: warning: `sqlite3_transfer_bindings' is > > deprecated (declared at /usr/include/sqlite3.h:3985) > > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function > > `pysqlite_enable_load_extension': > > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ > > pysqlite-2.5.0/src/connection.c:922: undefined reference to > > `_sqlite3_enable_load_extension' > > collect2: ld returned 1 exit status > > error: Setup script exited with error: command 'gcc' failed with exit > > status 1 > > $ > > > It seems to me this is due to some missing library (undefined > > reference...) but I have no idea what these missing files might be. > > I've tried installing everything that made any reference to sqlite > > form thecygwininterface. ?Does anyone know how I might get a working > > install of sqlite for python oncygwin? > > I believe it's a glitch in the 2.5.1 distribution current onCygwin- I > had to install the _sqlite DLL separately to get it to work, but no > recompilation was necessary AFAICR. > > Chui Tey detailed the necessary steps in his blog post "CygwinPython > and sqlite3", but sadly it got lost and he hasn't replenished it, so you > will have to stab around to see if there's a cached copy anywhere. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Well, I haven't managed to solve the problem. I tried following these instructions but get the same error: http://initd.org/pub/software/pysqlite/doc/install-source-win32.html And I also tried downloading the dll from sqlite.org and putting it on my path. Since someone asked how I ended up solving this problem: I'm just going to work on my Linux box where its relatively straight forward to install this stuff with the package manager. If someone does have instructions for making this work on windows I'd be very curious. I was unable to find an archived version of the blog post referenced above. From mail at microcorp.co.za Wed Sep 3 16:34:50 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 3 Sep 2008 22:34:50 +0200 Subject: How to write verbose scripts Message-ID: <001901c90e06$44e327e0$0d00a8c0@hendrik> Steven D'Aprano wrote: >Is there a better way of doing this than the way I am going about it? Not sure if its "better", but I would keep the messages in a table or dict and have different tables or dicts for different levels of verbosity, and write a displayer that knows about the verbosity - This approach has the advantage that you can write in English and have different verbosities in different languages too, if the displayer knows about the language. Verbosity level and language can be display class attributes, and then you can simply write something like: display.display("squawk") and get one of: squawk squawk, squawk, squawk squawk - help the bastards are trying to nail me to my perch! or the equivalent in Icelandic or Norwegian. It works, but its a PITA to implement because you have to formally construct the stuff, and keep them all in sync, across languages and levels of verbosity. This of course will only work for static messages - If you compute what you display, I guess you need to either keep the computation in the displayer, or pass it in, or something - gets messy. Keeps the code clear though, as it splits what you display away from the decision of saying something. I try to avoid it if I can. - Hendrik From gagsl-py2 at yahoo.com.ar Sun Sep 7 18:03:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 19:03:52 -0300 Subject: lacking follow-through References: Message-ID: En Sun, 07 Sep 2008 18:00:30 -0300, castironpi escribi?: > I am concerned by the lack of follow-through on some responses to > recent ideas I have described. Do I merely have a wrong understanding > of group policy? Is it a good policy (defined with respect to the > future of Python and the welfare of humans at large) if so? Is there > a serious lack of diligence, or should I merely take more initiative, > and ignore charges of 'pestering'? (Warning, moderately deep outside > social issues on table too.) Maybe people just doesn't have anything to say? Last thing I remember from you, is some mmap-based tree, and I'm not interested. -- Gabriel Genellina From bj_666 at gmx.net Thu Sep 18 13:00:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 18 Sep 2008 17:00:26 GMT Subject: PEP proposal optparse References: Message-ID: <6jffpaF2s539U1@mid.uni-berlin.de> On Thu, 18 Sep 2008 11:07:45 -0500, Grant Edwards wrote: > While we're making suggestions, I've always wished that the --help > output displayed the default values for options in addition to the help > text specified by the user. I end up having to enter the default values > twice -- once as a keyword argument and again in the help text. '%default' in the help text will be replaced by the default value. See the last option in the first example here: http://docs.python.org/lib/optparse-generating-help.html Ciao, Marc 'BlackJack' Rintsch From timothy.grant at gmail.com Thu Sep 11 16:02:18 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 11 Sep 2008 13:02:18 -0700 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: References: <943393.38616.qm@web95111.mail.in2.yahoo.com> Message-ID: On Thu, Sep 11, 2008 at 12:02 PM, Daniel Fetchinson wrote: > > >>> Thanking you, >>> >>> Ms. Vaidehi Pawar >> >> How much do you pay? >> >>> How much do you ask for???? >>> >>> cheers >>> Ms. Vaidehi > > I was just kidding. But if you seriously need people to do this kind > of job it's better to post the amount you are willing to pay otherwise > nobody will take it seriously. > > Cheers, > Daniel > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown > -- > http://mail.python.org/mailman/listinfo/python-list > I find it impossible to take anyone asking others to do their school work for them seriously no matter how or what they are willing to pay. -- Stand Fast, tjg. [Timothy Grant] From ppearson at nowhere.invalid Sun Sep 21 13:37:47 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 21 Sep 2008 17:37:47 GMT Subject: BeautifulSoup and Problem Tables References: Message-ID: <6jnf3bF47453U1@mid.individual.net> On Sat, 20 Sep 2008 20:51:52 -0700 (PDT), academicedgar at gmail.com wrote: [snip] > from BeautifulSoup import BeautifulSoup > bst=file(r"c:\bstest.htm").read() > soup=BeautifulSoup(bst) > rows=soup.findAll('tr') > len(rows) > a=len(rows[0].findAll('td')) > b=len(rows[1].findAll('td')) > c=len(rows[2].findAll('td')) > d=len(rows[3].findAll('td')) > e=len(rows[4].findAll('td')) > f=len(rows[5].findAll('td')) > g=len(rows[6].findAll('td')) > h=len(rows[8].findAll('td')) > i=len(rows[9].findAll('td')) > j=len(rows[10].findAll('td')) > k=rows[1].findAll('td')[1].contents[0] [snip] > However, I discovered that my tables have inconsistent numbers of > rows. [snip] > I have been Googling for some insight into this and I have not been > successful finding anything. I would really appreciate any suggestions > or some direction about how to better describe the problem. Would it be accurate to describe the problem as wanting to extract the contents of the cth column of the rth row of a table in spite of various pathologies in the construction of the table? If so, maybe it would help to post sample HTML (trimmed to a minimum) of the pathologies that must be handled. I gotta confess, though, that it doesn't take many rowspans or colspans to put this problem beyond my reach. -- To email me, substitute nowhere->spamcop, invalid->net. From tjreedy at udel.edu Sat Sep 27 17:41:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2008 17:41:42 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> Message-ID: Aahz wrote: > In article <8763oiuhj2.fsf at benfinney.id.au>, > Ben Finney wrote: >> Steven D'Aprano writes: >>> I'd like to be able to call [a class] as if it were a function. >>> Normally calling a class object returns an instance -- I wish to >>> return something else. >> In that case, you *don't* want a class at all; the entire point of a >> class is to define behaviour for instances. > > Absolutely agreed with your first clause, disagreed about the second > clause. As I said earlier, the main point of a class singleton is to get > the effect of a module singleton without the need to create another file > on disk. In 3.0, at least, one does not need a disk file to create a module. >>> import types >>> me = types.ModuleType('me') # type(__builtins__) works, no import >>> me >>> me.a = 1 >>> me.a 1 >>> me.a + 1 2 That said, a blank class is even easier, and the representation is better. tjr From tommy.nordgren at comhem.se Thu Sep 4 16:18:53 2008 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Thu, 4 Sep 2008 22:18:53 +0200 Subject: Converting .doc to .txt in Linux In-Reply-To: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> References: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: On Sep 4, 2008, at 9:54 PM, patrick.waldo at gmail.com wrote: > Hi Everyone, > > I had previously asked a similar question, > http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gst&q=convert+doc+txt#9dc901da63d8d059 > > but at that point I was using Windows and now I am using Linux. > Basically, I have some .doc files that I need to convert into txt > files encoded in utf-8. However, win32com.client doesn't work in > Linux. > > It's been giving me quite a headache all day. Any ideas would be > greatly appreciated. > > Best, > Patrick > > #Windows Code: > import glob,os,codecs,shutil,win32com.client > from win32com.client import Dispatch > > input = '/home/pwaldo2/work/workbench/current_documents/*.doc' > input_dir = '/home/pwaldo2/work/workbench/current_documents/' > outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/' > > for doc in glob.glob1(input): > WordApp = Dispatch("Word.Application") > WordApp.Visible = 1 > WordApp.Documents.Open(doc) > WordApp.ActiveDocument.SaveAs(doc,7) > WordApp.ActiveDocument.Close() > WordApp.Quit() > > for doc in glob.glob(input): > txt_split = os.path.splitext(doc) > txt_doc = txt_split[0] + '.txt' > txt_doc_path = os.path.join(outpath,txt_doc) > doc_path = os.path.join(input_dir,doc) > shutil.copy(doc_path,txt_doc_path) > -- > http://mail.python.org/mailman/listinfo/python-list You can do it manually with Open Office. A free office suite. ------------------------------------- This sig is dedicated to the advancement of Nuclear Power Tommy Nordgren tommy.nordgren at comhem.se From toddw at activestate.com Wed Sep 17 18:53:29 2008 From: toddw at activestate.com (Todd Whiteman) Date: Wed, 17 Sep 2008 15:53:29 -0700 Subject: ANN: Python GUI development using XULRunner In-Reply-To: <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> References: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> Message-ID: <48D18A69.2010009@activestate.com> support at mysfdomain.com wrote: > On Sep 17, 1:21 pm, Todd Whiteman wrote: >> Don Spaulding wrote: >>> On Sep 16, 8:29 pm, Todd Whiteman wrote: >>>> I've put together a tutorial that shows off how to build a GUI >>>> application using XULRunner (same architectural components as Firefox >>>> uses) that can be used in conjunction with the Python programming language. >>>> The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... >>> I get to the "Running" step and run into "Couldn't load XPCOM." >>> Does this work on x86_64? Or have I made a rookie mistake? >> Hi Don, >> >> A good question. Mozilla only provide 32-bit XulRunner applications by >> default, you you'll need to install the necessary 32-bit compatability >> libraries on your Linux machine, i.e. for Ubuntu it's something like: >> sudo apt-get install ia32-libs ia32-libs-gtk >> >> Then you should be able to run the example. You can check the >> dependencies using something the following commands, there should be no >> missing dependencies: >> $ cd pyxpcom_gui_app/xulrunner >> $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin >> >> It is possible to use a 64-bit version, but you'll need to compile this >> yourself (or find somewhere that provides these x86_64 versions). Note >> that the PythonExt project does not offer Python bindings for x86_64 >> either (it's on my todo list), you can compile the PythonExt part >> yourself as well if you need a 64-bit version. >> >> Cheers, >> Todd > > Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs > and ia32-libs-gtk installed. > > ldd shows that I'm missing the following libs, even though the proper > packages are installed, and the files show up in /usr/lib. > > libxcb-render-util.so.0 => not found > libxcb-render.so.0 => not found > > There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render- > util, so I wonder if that could be part of the problem? > > > Don Hi Don, I'm thinking there may be additional 32-bit packages necessary then (I'm not sure which package). Not sure about Ubuntu 8.10 (it's still alpha). I'm using a Ubuntu 8.04 x86_64 machine and my dependencies list the following for the latest 32-bit build of XulRunner: $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin | grep libxcb libxcb-xlib.so.0 => /usr/lib32/libxcb-xlib.so.0 (0xf6493000) libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf647b000) Cheers, Todd From deets at nospam.web.de Sat Sep 6 10:13:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Sep 2008 16:13:22 +0200 Subject: How to bring subprocess to the foreground? In-Reply-To: References: Message-ID: <6ifhg2Fq24n6U1@mid.uni-berlin.de> dudeja.rajat at gmail.com schrieb: > Hi, > > I've a batch file that I open with the subprocess .Popen() . When this > batch file is run I want to bring it to the foreground. > > Please suggest how can I do this? You can't. You can capture the stdout using the pipe-arguments, and in your main-process, read that and write it to the main process' stdout. Diez From hv at tbz-pariv.de Thu Sep 11 06:43:34 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Thu, 11 Sep 2008 12:43:34 +0200 Subject: Better error message on recursive import Message-ID: <6isb2mF9scaU1@mid.individual.net> Hi, why does Python only raise ImportError if it fails caused by a recursive import? I know what's wrong. But I guess many beginner don't know what's wrong. I don't want much, just "RecursiveImportError" instead of "ImportError". Is this possible? Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From nick at craig-wood.com Fri Sep 12 12:36:42 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 12 Sep 2008 11:36:42 -0500 Subject: dict slice in python (translating perl to python) References: Message-ID: Steven D'Aprano wrote: > On Thu, 11 Sep 2008 03:36:35 -0500, Nick Craig-Wood wrote: > > > As an ex-perl programmer and having used python for some years now, I'd > > type the explicit > > > > v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > > > > Or maybe even > > > > v1 = mydict['one'] # 54 chars > > v2 = mydict['two'] > > v3 = mydict['two'] > > > > Either is only a couple more characters to type. > > But that's an accident of the name you have used. Consider: > > v1,v2,v3 = section_heading_to_table_index['one'], \ > section_heading_to_table_index['two'], \ > section_heading_to_table_index['two'] # 133 characters > > versus: > > v1,v2,v3 = [section_heading_to_table_index[k] for k in > ['one','two','two']] # 75 characters > > It also fails the "Don't Repeat Yourself" principle, and it completely > fails to scale beyond a handful of keys. If you have more than a handful of keys then you have a different problem (far too many local variables) with your code I think! DRY is a good principle. I still prefer the 3 explicit assignments though ;-) > Out of interest, on my PC at least the list comp version is significantly > slower than the explicit assignments. So it is a micro-optimization that > may be worth considering if needed -- but at the cost of harder to > maintain code. > > > It is completely > > explicit and comprehensible to everyone, in comparison to > > > > v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > > v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars > > That's a matter for argument. I find the list comprehension perfectly > readable and comprehensible, and in fact I had to read your explicit > assignments twice to be sure I hadn't missed something. But I accept that > if you aren't used to list comps, they might look a little odd. A matter of taste certainly! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From shahmed at sfwmd.gov Wed Sep 3 13:31:38 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Wed, 3 Sep 2008 13:31:38 -0400 Subject: Using strftime In-Reply-To: <4841b103-be8c-471f-8903-1b9284bd3a39@k13g2000hse.googlegroups.com> References: <4841b103-be8c-471f-8903-1b9284bd3a39@k13g2000hse.googlegroups.com> Message-ID: You can try Import time mytimeymd = time.strftime('%y%m%d') print mytimeymd -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of frankrentef Sent: Wednesday, September 03, 2008 1:21 PM To: python-list at python.org Subject: Using strftime I have one line of code that put's an old date in my code. ie.textBoxSet('_ct10_PlaceHolder_txtEnd', '8/15/2008') What I wish to do in another similiar line is have the field populated with the current system date? How best to do this? I've read some of the strftime documentation but as of yet I'm unable to get it to work correctly. Help is appreciated. THNX -- http://mail.python.org/mailman/listinfo/python-list From rsinger at ____.com Mon Sep 29 19:09:23 2008 From: rsinger at ____.com (Robert Singer) Date: Tue, 30 Sep 2008 01:09:23 +0200 Subject: pyXLWriter warnings Message-ID: Platform: winXP, excel 2003 Python 2.5.2 XLWriter 0.4a3 (http://sourceforge.net/projects/pyxlwriter/) Is anyone here using this very nice package, for writing excel files? I'm using it on python 2.5.2. (although it is made for older version of python) and cannot find a way to get rid of this error (code and errors below). Does anyone know how to avoid it ? I would appreciate all help and ideas you can think of. Bob -------- >>> import pyXLWriter as xl >>> workbook = xl.Writer("test.xls") >>> worksheet = workbook.add_worksheet('first') >>> worksheet.write([3,3], "Hello doc !") >>> worksheet.write_comment([3,3], "I'm hunting for a wabbit") 0 >>> workbook.close() -------- Warning (from warnings module): File "C:\Python25\lib\site-packages\pyXLWriter\OLEWriter.py", line 135 unknown3 = pack(">> From benjamin.kaplan at case.edu Tue Sep 9 11:42:31 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 9 Sep 2008 11:42:31 -0400 Subject: Orientation on MySql using python In-Reply-To: References: Message-ID: On Tue, Sep 9, 2008 at 9:36 AM, Jo?o Abrantes wrote: > Hello everyone, I want to make a program in python that uses Mysql aswell.. > I don't know anything about mysql can you tell me some good books/tutorials > where I can read something about mysql using python? Thanks. > > ------------------------------ > Did you try looking at MySQL's website? http://dev.mysql.com/usingmysql/python/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From gioco at nekhem.com Wed Sep 3 06:36:30 2008 From: gioco at nekhem.com (Corrado Gioannini) Date: Wed, 3 Sep 2008 12:36:30 +0200 Subject: email.Message problem In-Reply-To: References: <20080902160417.GA20438@zephyr> Message-ID: <20080903103630.GC11421@zephyr> On Tue, Sep 02, 2008 at 04:50:15PM -0300, Gabriel Genellina wrote: > > messg = email.message.Message() > > Replace this line with: > messg = email.mime.multipart.MIMEMultipart() > *OR* > Set the Content-Type header to "multipart/mixed" *before* anything else. thanks Gabriel! i coudn't have thought that setting the header in a different order could affect the as_string method. i'll take a look at the code. :) c. -- no, sono sempre io, non mi cambierete quel che ho dentro forse ho solo un'altra faccia ho pi? cicatrici di prima, sorrido un po' meno, forse penso di pi?. (Kina) From stef.mientki at gmail.com Thu Sep 25 12:18:16 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 18:18:16 +0200 Subject: How to get the filename in the right case ? In-Reply-To: References: <6k1dukF5hk86U1@mid.uni-berlin.de> Message-ID: <48DBB9C8.6090500@gmail.com> OKB (not okblacke) wrote: > Stef Mientki wrote: > >>>>> import Module1 >>>>> >>> d:\data_python_25\pylab_works\module1.py(3)() >>> >> -> print "hello" >> (Pdb) >> >> >>> Then we know if PDB is really the culprit. >>> >>> >>> >> So pdb is the problem. >> > > Yep, it does the same thing for me. > > >>> Apart from that, is that really a problem that the filenames are >>> all lower case? AFAIK Windows is case-insensitive regarding >>> filenames anyway. So opening the file by just passing the filename >>> should work seamless. >>> >>> >> Yes windows is, >> but Python is not. >> My program should run on Windows and Linux (and maybe a few >> others). By converting everything to lowercase, on Linux I can't >> distinguishes between 2 files with the same name but a different >> case (btw, giving 2 files the same name, only differing in case, >> looks like a bad idea to me). >> > > Hmmm, but I don't understand what you're doing here. Are you > somehow storing the filename that pdb outputs and you need to use it > later on a potentially different OS? If the case is preserved in pdb on > linux, then presumably running it on linux will be fine, right? It's > only a problem if you somehow try to use a filename created by windows- > pdb to open a file (the same file, somehow) on linux. > > 1. I've a multitab editor. 2. When a breakpoint is reached, 3. I check if the file specified in pdb output, is already open in one of the editor tabs, 4. if not, I open a new tab with the correct file, 5. I focus the correct editor tab and jump to the line specified by pdb. 6. After that I should be able to inspect the surrounding of the breakpoint, so I need the modules name. For 3 I need to compare filenames, the editor contains the case sensitive name, pdb not. For 6 I also need the case sensitive filename, but probably there's another way to get the modules name. For 3, I can indeed compare the lowercase version of both, probably I'll do that for the moment. thanks guys for the suggestions Stef From wuwei23 at gmail.com Sun Sep 21 19:50:51 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 21 Sep 2008 16:50:51 -0700 (PDT) Subject: appending * to glob returns files with '*' !! References: Message-ID: On Sep 20, 6:37?am, "John [H2O]" wrote: > My routine cannot handle the '*' and it should'nt be returned anyway? :-/ > > A bug? Not at all. That's the same behaviour you'll get if you do 'ls EN*'. In your case, you're asking to match on anything that begins with EN, a subset of files that -includes- EN*. Why do you consider this behaviour surprising? From israelu at elbit.co.il Wed Sep 3 11:27:36 2008 From: israelu at elbit.co.il (iu2) Date: Wed, 3 Sep 2008 08:27:36 -0700 (PDT) Subject: os.system dual behaviour Message-ID: Hi guys I do os.system('ls &> e') On one linux machine it emits ls output to the file e as expected. On another linux machine it emits ls to the standard output, and nothing to e! Both machines run Fedora linux. The command "ls &> e" entered at the shell (no python) behaves ok on both machines. Why?? How can I solve this? Your help will be appreciated. From joefazee at gmail.com Mon Sep 15 04:54:05 2008 From: joefazee at gmail.com (A. Joseph) Date: Mon, 15 Sep 2008 01:54:05 -0700 Subject: Converting between binary, decimal, hexadecimal, octal Message-ID: Converting between binary, decimal, hexadecimal, octal Where can I find good tutorial on numbering system? I really want to know the process of converting between all the numbers. I may soon start HLA (assemply). Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Wed Sep 24 23:36:18 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2008 23:36:18 -0400 Subject: Schwartzian transform for tuple in list In-Reply-To: <7C3B1753-3E7A-4E1F-B102-3387FB0152A4@gmail.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <7C3B1753-3E7A-4E1F-B102-3387FB0152A4@gmail.com> Message-ID: David Di Biase wrote: > When you say slightly, is it enough to make a difference? Why would > getitems be faster even - not sure I can think why... > Using key is faster than cmp because key is called just once for each item whereas cmp is called once for each of the O(nlogn) compares. Operator.itemgetter is written in C and hence should be faster than a wrapper written in Python. From tamim.shahriar at gmail.com Sat Sep 6 18:55:26 2008 From: tamim.shahriar at gmail.com (subeen) Date: Sat, 6 Sep 2008 15:55:26 -0700 (PDT) Subject: Learning Python References: Message-ID: On Sep 6, 3:17?pm, James Pilling wrote: > Hi im currently starting to learn python in sixth form at school any tips? > Just pickup a good book and make sure you code all the examples and exercises yourself, even if it seems easy. Have fun with Python! regards, Subeen. http://love-python.blogspot.com From george.sakkis at gmail.com Tue Sep 23 10:13:16 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 23 Sep 2008 07:13:16 -0700 (PDT) Subject: Python is slow? References: Message-ID: <28f1b350-9908-4056-bfa2-e6c2d9edb17d@i76g2000hsf.googlegroups.com> On Sep 23, 9:57 am, Grant Edwards wrote: > On 2008-09-23, sturlamolden wrote: > > [...] > > > After having a working Python prototype, I resorted to rewrite the > > program in C++. The Python prototype took an hour to make, debug and > > verify. The same thing in C++ took me almost a day to complete, even > > with a working prototype as model. To my surprise, the resulting beast > > of C++ required 64.3 seconds to construct the same kd-tree. Searching > > the tree was not faster either, 1,000 points required 38.8 seconds. I > > wasted a day, only to find my Python prototype being the faster. > > > We may conclude that I'm bad at programming C++, > > AFAICT, _everybody_ is bad at programming C++. +1 QOTW From rocksportrocker at googlemail.com Thu Sep 18 12:06:09 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 18 Sep 2008 09:06:09 -0700 (PDT) Subject: Automated Build System ? Message-ID: <3468bd3f-d6a3-477a-8537-48d67522700a@j22g2000hsf.googlegroups.com> Hi, I'm working on a python Package which includes some extension modules and unit tests. I want to automate some tasks like "build extsion module, then copy xxx.pyd to folder yyy and run all unit tests from folder zzzz". I used google but found no hints to existing solutions. Can anybody help me ? Greetings, Uwe From gogtesuyash at gmail.com Mon Sep 29 23:47:35 2008 From: gogtesuyash at gmail.com (sui) Date: Mon, 29 Sep 2008 20:47:35 -0700 (PDT) Subject: python & sms Message-ID: Hii i want a script to send sms to any mobile..... can u help me ?? Thanks in advance...... From tino at wildenhain.de Wed Sep 17 14:34:37 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 17 Sep 2008 20:34:37 +0200 Subject: translating ascii to binary In-Reply-To: <48d13fa2$0$27103$9a622dc7@news.kpnplanet.nl> References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> <00e12f1f$0$20331$c3e8da3@news.astraweb.com> <48d13fa2$0$27103$9a622dc7@news.kpnplanet.nl> Message-ID: <48D14DBD.5050306@wildenhain.de> hi, Canned wrote: > Steven D'Aprano schreef: >> Your "ascii_to_bin" method tries to do too much in one method. You should >> split the functionality into small, self-contained pieces, then combine >> them. And frankly, once you got to the part where you started popping and >> inserting, my brain melted. You are making an easy job too hard! *smiles* >> > It's a bad habit, I can't help it. From now on, I'll follow your advice > to split the functionality into small, self-contained pieces. That > popping and inserting is just a workaround for another workaround. just got an interesting idea for the core of the converter, maybe you like it: def int_to_bin(v): i=1 d=1 a=0 while i>> int_to_bin(5) 101 >>> print "%08d" % int_to_bin(5) 00000101 I think the formatting bit is a tad nicer then '0' * (8-len(...))) Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From FettManChu at gmail.com Thu Sep 4 14:39:42 2008 From: FettManChu at gmail.com (Fett) Date: Thu, 4 Sep 2008 11:39:42 -0700 (PDT) Subject: Can anyone suggest a good crypto package? Message-ID: I need a crypto package that works on windows with python 2.5. Can anyone suggest one for me? I have been searching for a couple days for a good cryptography package to use for public/private key encryption, at this point I would settle for symmetric even. Every encryption package I have found for python was either operating system specific (read *nix only): http://www.freenet.org.nz/ezPyCrypto/ http://www.keyczar.org/ There was one exception, this version was specifically built to run on any platform (yay), but the compiler for windows complained that I wasn't using python2.2 (though the package was said to only need 2.2 or newer). Is there any crypto package that is actually written in python? I seriously don't care how slow it is. From Ripter001 at gmail.com Wed Sep 3 22:46:14 2008 From: Ripter001 at gmail.com (Ripter) Date: Wed, 3 Sep 2008 19:46:14 -0700 (PDT) Subject: Help Understanding weakref (lazyloader) Message-ID: I found this script at http://www.pygame.org/wiki/LazyImageLoading?parent=CookBook And I can't quite figure out how it works. I was wondering if someone could clarify it for me. The Code is: import pygame import weakref class ResourceController(object): def __init__(self, loader): self.__dict__.update(dict( names = {}, cache = weakref.WeakValueDictionary(), loader = loader )) def __setattr__(self, name, value): self.names[name] = value def __getattr__(self, name): try: img = self.cache[name] except KeyError: img = self.loader(self.names[name]) self.cache[name] = img return img class ImageController(ResourceController): def __init__(self): ResourceController.__init__(self, pygame.image.load) My question is why does the __setattr__ set the value to self.names[name] instead of self.cache[name]? From exarkun at divmod.com Fri Sep 5 15:29:34 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 5 Sep 2008 15:29:34 -0400 Subject: Need formatting suggestion for long strings In-Reply-To: <496954360809051224i66123029s23a5ab2f02d8be2b@mail.gmail.com> Message-ID: <20080905192934.29191.496947365.divmod.quotient.22130@ohm> On Fri, 5 Sep 2008 14:24:16 -0500, Robert Dailey wrote: >Hi, > >I find quite often that I'm writing things like this: > >raise FatalExcept( "Insufficient number of arguments specified. Exactly {0} >arguments are required. See stage.bat for documentation on accepted >parameters.".format( num_arguments ) ) > >On my display (Vertical monitor), this exceeds the width of my display, and >to view the entire length of the string I am forced to pan my view left and >right. Is there a special way I can format this string so that it fits >nicely on the screen? Keep in mind that one important factor is that >whitespace is very sensitive, and I do not want line breaks in my script >file to become part of the string itself. I like how C++ handles strings, >like this: > >char const* mystring = > "This is a very long string that " > "spans multiple lines and does " > "not include line breaks or tabs " > "from the source file between " > "the strings partitions." > > >What do you guys prefer? Thanks for reading. > mystring = ( "This is a very long string that " "spans multiple lines and does " "not include line breaks or tabs " "from the source file between " "the strings partitions.") Jean-Paul From prologic at shortcircuit.net.au Sun Sep 21 18:54:43 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 08:54:43 +1000 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: Hi, Wouldn't a normal class called State suffice for storing state between calls ? And ... Creating a state instance ? For example: class State(object): """State() -> new state object Creates a new state object that is suitable for holding different states of an application. Usefull in state-machines. The way this works is rather simple. You create a new state object, and simply set the state. If the state doesn't exist, it's added to it's internal data structure. The reason this is done is so that comparing states is consistent, and you can't just compare with a non-existent state. """ def __init__(self): "initializes x; see x.__class__.__doc__ for signature" self._states = {} self._next = 0 # Default States self._add("START") self._add("DONE") def __repr__(self): try: return "" % self._state except AttributeError: return "" def __str__(self): return self._state def __eq__(self, s): return s in self._states and self._state == s def __lt__(self, s): return s in self._states and self._state == s and \ self._states[s] < self._states[self._state] def __gr__(self, s): return s in self._states and self._state == s and \ self._states[s] > self._states[self._state] def _add(self, s): self._states[s] = self._next self._next = self._next + 1 def set(self, s): """S.set(s) -> None Set the current state to the specified state given by s, adding it if it doesn't exist. """ if s not in self._states: self._add(s) self._state = s cheers James On Mon, Sep 22, 2008 at 8:39 AM, Steven D'Aprano wrote: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bearophileHUGS at lycos.com Tue Sep 23 14:52:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 23 Sep 2008 11:52:16 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: sturlamolden: >F# and OCaml look promising though.< I bet on the future of D and Haskell (and maybe Fortress) instead :-) We'll see. >Sure I could show you the code, Python and C++, if I had a place to post it.< I think the Python version suffices. If it's not too much private you may post the single minimal/reduced runnable Python module here, it will be deleted in some time (if you want you can also use a private paste): http://codepad.org/ >It looks very different form yours though.< Is this a good or bad thing? ;-) Bye, bearophile From stephane at harobed.org Mon Sep 8 18:04:29 2008 From: stephane at harobed.org (=?iso-8859-1?q?KLEIN_St=E9phane?=) Date: Mon, 8 Sep 2008 22:04:29 +0000 (UTC) Subject: Where does the command "ls" in some doctest files come from ? References: <00d51a07$0$20306$c3e8da3@news.astraweb.com> Message-ID: Le Mon, 08 Sep 2008 12:51:04 +0000, Steven D'Aprano a ?crit?: > On Mon, 08 Sep 2008 12:15:15 +0000, KLEIN St?phane wrote: > >> Hi, >> >> for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/ >> tests.py?rev=89831&view=auto test file, there is this doctests : > > [snip] > >> >>> ls('develop-eggs') > > >> I wonder where does the "ls('develop-eggs')" command come from ? >> >> It is doctest buildin command ? > > Easy to find out: import doctest and see for yourself: > >>>> import doctest >>>> doctest.ls > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute 'ls' > > You found the ls() function in a docstring from Zope. The doctest seems > to be testing ls(). That suggests to me that ls() is defined in Zope, > not doctest. Well, ls() is one test utility function defined in zc.buildout.testing module. This module contain many utility function like mkdir, ls, cat... > Why do you ask? I'm curious... I've seen this utility and I would like to know how can I use it. Regards, Stephane From steve at REMOVE-THIS-cybersource.com.au Tue Sep 30 09:43:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 13:43:58 GMT Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> Message-ID: <00f226c8$0$20617$c3e8da3@news.astraweb.com> On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: >> > You're not free to modify gnuplot and redistribute the result. >> > >> > That you're free to distribute patches is nice, but it's not enough >> > to make the work free. The freedom to help people by giving them an >> > *already-modified* gnuplot is restricted by the copyright holder. >> > >> > It's an artificial restriction on redistribution of derived works, >> > making them second-class for the prupose of getting them into >> > people's hands. >> >> Yes it is. It seems a strange, unnecessary restriction. But is it >> sufficient to make it non-free? I don't think so. > > I do, because a natural, beneficial act (modify the work and > redistribute it) that has no technical reason to restrict, is > artifically restricted. We agree that the restriction is artificial, and I think irrational (although I'd be interested in hearing the gnuplot developers' reasoning before making a final judgment). But I just don't see the requirement that modified software be distributed in form X (original source + diffs) versus form Y (modified source in a tar ball) or form Z (an rpm) to be that big a deal. Not enough to make it "non-free software". I simply don't think that having to run some variation on patch -i patchfile.patch is a requirement so onerous that it makes the gnuplot licence non-free. Perhaps I'm just more tolerant of eccentricities than you :) -- Steven From jjl at pobox.com Wed Sep 3 17:49:28 2008 From: jjl at pobox.com (John J Lee) Date: Wed, 3 Sep 2008 22:49:28 +0100 (BST) Subject: [wwwsearch-general] python mechanize/libxml2dom question In-Reply-To: <108c01c90cad$28dd5840$0301a8c0@tmesa.com> References: <108c01c90cad$28dd5840$0301a8c0@tmesa.com> Message-ID: On Mon, 1 Sep 2008, bruce wrote: [...] > how can i [...] > libxml2dom [...] Just a general point: try lxml.etree instead? Friendlier API. John From ptmcg at austin.rr.com Sat Sep 13 12:49:18 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 13 Sep 2008 09:49:18 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? References: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> Message-ID: <2fb7c936-7c2c-4c1a-aed8-93dc3e7e342a@w7g2000hsa.googlegroups.com> On Sep 12, 8:08?pm, i... at illusorygoals.com wrote: > First off, I'm a python n00b, so feel free to comment on anything if > I'm doing it "the wrong way." I'm building a discrete event simulation > tool. I wanted to use coroutines. However, I want to know if there's You could "look in the back of the book" - download SimPy and see how they does this. -- Paul From bignose+hates-spam at benfinney.id.au Mon Sep 15 00:04:35 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 14:04:35 +1000 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: <87od2q5a24.fsf@benfinney.id.au> Adelle Hartley writes: > I'm looking at porting a library that was written for COM and .Net > to work as a Python module, and was wondering whether it would be > better to stick to the library's current naming convention so that > the API is as similar as possible on each platform, or to adopt a > "when in Rome..." policy and follow the "most mainstream" naming > pattern for each platform/language. I think it's more important for Python library APIs to comply with the Python coding guidelines (as specified in PEP 8) than to comply with standards in other languages. The Python library you're implementing isn't being used in those other languages, so the conventions of other languages have little relevance. It's being used in Python code, so it should mesh well with PEP 8 compliant code ? by having the API itself comply with PEP 8. -- \ ?When cryptography is outlawed, bayl bhgynjf jvyy unir | `\ cevinpl.? ?Anonymous | _o__) | Ben Finney From fredrik at pythonware.com Sun Sep 21 12:36:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 18:36:20 +0200 Subject: Why are "broken iterators" broken? In-Reply-To: References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: Roy Smith wrote: > There are plausible examples of collections which grow while you're > iterating over them. I'm thinking specifically of a queue in a > multi-threaded application. One thread pushes work onto the back of the > queue while another pops from the front. The queue could certainly go > empty at times. But, maybe a Python iterator is just the wrong way to > model such behavior. you probably want the consumer thread to block when it catches up with the producer, rather than exit. (that's the default behaviour of Python's Queue object, btw) From gminick at bzt.bzt Mon Sep 1 06:59:12 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 10:59:12 +0000 (UTC) Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> <6i1rgcFo0f1gU1@mid.uni-berlin.de> <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> Message-ID: On Mon, 1 Sep 2008 03:51:13 -0700 (PDT), lee wrote: > i am soory for that keystrokes. can anyone tell me how can i change > the value of key. > suppose i have a dictionary > > kev = {'kabir': ['kabir at kabir.com', '1234', 'missuri'], 'shri': > ['shri at shri.com', '23423', 'india'], 'marsa': ['marsa at marsa.com', > '2345', 'brazil'], 'sandeep': ['sandeep at sandeep.com', '007', > 'canada']} > how can i change the key to something like 'sabir' and kev['sabir'] = kev['kabir'] del kev['kabir'] > how can i > change the values of kabir? kev['sabir'][0] = 'sabir at sabir.com' *untested* -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From python at hope.cz Mon Sep 1 02:25:56 2008 From: python at hope.cz (Johny) Date: Sun, 31 Aug 2008 23:25:56 -0700 (PDT) Subject: Processes in Linux from Python Message-ID: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> To get a number of the http processes running on my Linux( Debia box) I use ps -ef | grep "[h]ttpd" | wc -l But If I want to use to get a number of the http processes from my Python program I must use a popen command e.g. popen2.popen3('ps -ef | grep "[h]ttpd" | wc -l') that is I must call an external command from Python. But it creates a zombie. So my question is: Is it possible to get a number of the http processes running on Linux directly from Python ? Thanks for help. L. From wegwerp at gmail.com Wed Sep 24 09:58:05 2008 From: wegwerp at gmail.com (Bas) Date: Wed, 24 Sep 2008 06:58:05 -0700 (PDT) Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> Message-ID: <919aba9d-8076-4ac2-ae2c-a31921e1e4d0@34g2000hsh.googlegroups.com> On Sep 22, 10:02 am, Al Kabaila wrote: > There are several packages for matrix algebra. I tried Numeric, numpy and > numarray. All three are very good, but each uses different syntax. That argument might have been valid 3 years ago, but as already said by others, Numeric and Numarray are deprecated. Numpy should be the only thing needed for new users. I suggest you investigate a little bit more the next time you make such efforts, since this fact should be widely known among the users of the mentioned packages, see e.g. the huge warning at the numarray page: http://www.stsci.edu/resources/software_hardware/numarray/numarray.html > 1. Is there any interest in matrix algebra "for the masses" (I mean interest > in a wrapper for a subset of functions of the packages with a unified > simple syntax)? In my opinion, no. I might be biased, since with my matlab background I find numpy simple enough as is. But I don't see how A = B*C+D or E=dot(F,G) is complicated for a beginner of linear algebra. > My OS is Linux (openSUSE 10.3) and my interest in retirement is Python > applications to Structural Analysis of Civil Engineering structures, > currently in 2 dimensions only (under GPL). Modern Structural Analysis is > highly matrix oriented, but requires only a few basic matrix operations, > namely matrix creation, transposition, multiplication, invertion and > linear equation solution. For stability analysis one would require > Eigenvalues and Eigenvectors. In 3 dimensions, additionally highly > desirable would be vector algebra. The packages do have all these > functions, but currently only the basic functions are in the wrapper. If you care about contributing something useful to the community, I think your time and skills are better spent writing some cool mechanical analysis tool for inclusion in Scipy. Bas From sturlamolden at yahoo.no Thu Sep 25 05:18:14 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 02:18:14 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> On 25 Sep, 10:08, Duncan Booth wrote: > A lot of what LINQ does is already easy to do in Python, and most of the > rest can probably be added fairly easily, but it does provide a consistent > framework which may make it easier to do complex LINQ statements than > complex list comprehensions. Yes, that's the word, "consistent framework". I wonder what that means? Do you mean Python syntax is inconsitent? > BTW, a minor correction: LINQ statements are closer to generators, not list > comprehensions. They don't actually evaluate their results until you > iterate over them and you can re-used the same LINQ statement multiple > times getting different results if the data has changed. Python has generator expressions with the same syntax as list comprehensions, except you use () instead of []. From mhostetl at faeroes.freeshell.org Thu Sep 4 21:55:53 2008 From: mhostetl at faeroes.freeshell.org (Mike Hostetler) Date: Fri, 5 Sep 2008 01:55:53 +0000 (UTC) Subject: ctypes error on Windows Message-ID: I'm working on a script with the most excellent uTibyLib library. The script works just fine on Mac, but on Windows I get this: File "findtables.py", line 82, in cleanHTML return str(tidy.parseString(decentDoc)) File "c:\Python24\Lib\site-packages\tidy\lib.py", line 207, in parseString doc = self._create(**kwargs) File "c:\Python24\Lib\site-packages\tidy\lib.py", line 183, in _create doc = _Document() File "c:\Python24\Lib\site-packages\tidy\lib.py", line 135, in __init__ self.cdoc = _tidy.Create() File "c:\Python24\Lib\site-packages\tidy\lib.py", line 46, in __getattr__ return getattr(self.lib, name) File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 353, in __getatt func = self.__getitem__(name) File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 358, in __getite func = self._FuncPtr((name_or_ordinal, self)) AttributeError: function 'Create' not found I do have the tidy.dll installed (if I didn't, I couldn't even import the tidy module). Anyone have any ideas to try? -- mhostetl at sdf.lonestar.org SDF Public Access UNIX System - http://sdf.lonestar.org From gagsl-py2 at yahoo.com.ar Mon Sep 29 21:31:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 22:31:58 -0300 Subject: adding in-place operator to Python References: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> <266557d0809251303k60d3a52eoc239917bc3597b27@mail.gmail.com> <266557d0809251304q49fec06er436d7b2a1db6b6f7@mail.gmail.com> Message-ID: En Thu, 25 Sep 2008 17:04:59 -0300, Arash Arfaee escribi?: > Thank you very much Gerhard and Terry. > > I am trying to add undefined state to some Boolean operator. Here is > what I > tried to do and It is not working: > > class _3ph: > def __init__(self): > self.value = 0 > > def __xor__(self,item): > if self.value==2 or item==2: > return 2 > else: > return self.__xor__(item) > > what I am trying to do is assigning 2 to undefined state and have xor > operator return 2 if one of inputs are 2. > it seems Although I defined xor in _3ph class, python treat any object > from > this class just like integer variables. Because you return a plain integer from __xor__, so the _3ph "magic" is lost. Try something like this: def xor3(v1, v2): # this should implement the actual logic if v1==2 or v2==2: return 2 return v1 ^ v2 class _3ph: def __init__(self, value=0): self.value = value def __xor__(self, item): if isinstance(item, _3ph): return _3ph(xor3(self.value, item.value)) else: return _3ph(xor3(self.value, item)) __rxor__ = __xor__ def __repr__(self): return '%s(%s)' % (self.__class__.__name__, self.value) __str__ = __repr__ a = _3ph(0) b = _3ph(1) c = _3ph(2) print "a ", a print "b ", b print "c ", c print "a ^ a", a ^ a print "a ^ b", a ^ b print "a ^ c", a ^ c print "a ^ 0", a ^ 0 print "a ^ 1", a ^ 1 print "a ^ 2", a ^ 2 print "b ^ a", b ^ a print "b ^ b", b ^ b print "b ^ c", b ^ c print "b ^ 0", b ^ 0 print "b ^ 1", b ^ 1 print "b ^ 2", b ^ 2 print "c ^ a", c ^ a print "c ^ b", c ^ b print "c ^ c", c ^ c print "c ^ 0", c ^ 0 print "c ^ 1", c ^ 1 print "c ^ 2", c ^ 2 print "0 ^ a", 0 ^ a print "0 ^ b", 0 ^ b print "0 ^ c", 0 ^ c print "1 ^ a", 1 ^ a print "1 ^ b", 1 ^ b print "1 ^ b", 1 ^ c print "2 ^ a", 2 ^ a print "2 ^ b", 2 ^ b print "2 ^ c", 2 ^ c print "--- contrast" print "0 ^ 0", 0 ^ 0 print "0 ^ 1", 0 ^ 1 print "0 ^ 2", 0 ^ 2 print "1 ^ 0", 1 ^ 0 print "1 ^ 1", 1 ^ 1 print "1 ^ 2", 1 ^ 2 print "2 ^ 0", 2 ^ 0 print "2 ^ 1", 2 ^ 1 print "2 ^ 2", 2 ^ 2 (I've kept your _3ph name, but I think it's rather ugly... If the class is suposed to be public, its name should not start with an underscore. This is a *very* strong naming convention. See PEP8 http://www.python.org/dev/peps/pep-0008/ for some other stylistic recommendations) You may want to restrict the allowed values in __init__, by example. -- Gabriel Genellina From john.m.roach at gmail.com Tue Sep 9 12:41:17 2008 From: john.m.roach at gmail.com (john) Date: Tue, 9 Sep 2008 09:41:17 -0700 (PDT) Subject: F2PY changing integers to arrays??? Message-ID: <7d60c85f-12cf-47fc-84c9-58e50cad4eaf@x35g2000hsb.googlegroups.com> I have a simple module which performs basic operations on plot3d files (below). I wrapped like: f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 That seems to work fine, but i get some unexpected results... >>> from plot3d import plot3d as p3 >>> dir(p3) ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', 'writeit2d'] >>> p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) >>> p3.imax array(409) "409" is correct, but "imax" is declared as an INTEGER in fortran and now it's an array in python??? Any ideas? # prec.f90 MODULE prec IMPLICIT NONE INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) END MODULE prec # plot3d.f90 MODULE PLOT3D USE prec IMPLICIT NONE INTEGER, PARAMETER :: prc=single REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z INTEGER :: mg, imax, jmax, kmax CONTAINS !---------- SUBROUTINE READIT( fname, ftype, fmg ) ! reads the plot3d, formatted, mg file in xyz IMPLICIT NONE CHARACTER(len=20), INTENT(IN) :: fname, ftype LOGICAL :: fmg INTEGER :: i, j, k, n, f=1 SELECT CASE (ftype) CASE ('FORMATTED') OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', FORM=ftype ) IF (fmg) READ(f,*) mg ! only read if multigrid READ(f,*) imax, jmax, kmax ALLOCATE( x(mg, imax, jmax, kmax) ) ALLOCATE( y(mg, imax, jmax, kmax) ) ALLOCATE( z(mg, imax, jmax, kmax) ) READ(f,*) ((((x(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & ((((y(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & ((((z(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) CASE ('UNFORMATTED') OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', FORM=ftype ) IF (fmg) READ(f) mg ! only read if multigrid READ(f) imax, jmax, kmax ALLOCATE( x(mg, imax, jmax, kmax) ) ALLOCATE( y(mg, imax, jmax, kmax) ) ALLOCATE( z(mg, imax, jmax, kmax) ) READ(f) ((((x(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & ((((y(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & ((((z(n, i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) CASE DEFAULT WRITE(*,*) 'filetype not supported in ' STOP END SELECT CLOSE(f) END SUBROUTINE READIT END MODULE PLOT3D From pavlovevidence at gmail.com Thu Sep 25 18:30:11 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 25 Sep 2008 15:30:11 -0700 (PDT) Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sep 25, 4:04?pm, "Gabriel Genellina" wrote: > En Thu, 25 Sep 2008 16:24:58 -0300, escribi?: > > > sorry, I have these ideas for longer than 10 years, please have a look ? > > on it > > and comment on it. Thx. > > > This is another proposal for introducing types into Python. > > You got the terminology wrong. Python had "types" from the very start. ? > You're talking about some kind of generic functions, or an alternative ? > dispatch method. > > Read this GvR blog post [1] and his next one; also see PEP 3124 by Phillip ? > J. Eby, who wrote a pretty good implementation of generic functions a long ? > time ago. > > Your proposal requires a syntax change and three new keywords; all the ? > others achieve roughly equivalent results without requiring any change to ? > the core language. Just to play Devil's advocate here, multimethods(**) aren't equivalent, roughly or otherwise, to what the OP is requesting. Superficially it looks that way, but the actual use case for this logic programming is something that ordinary multimethods can't do. Prolog-style programming is sort of the exact opposite of pure functional programming. Whereas in pure functional programming there are no side effects, in Prolog pretty much everything is a side effect. The way things happen in Prolog is execution of side effects in the process of searching for pattern matches. A decent multimethod implementation doesn't use trial and error for dispatch; it'll use some kind of mapping and cacheing to get to the appropriate function as quickly as possible. In logic programming however, the trial-and-error is essential since side-effects can and are supposed to happen in the process of trying. Anyway, this proposal can easily be implemented more or less as proposed without any syntax changes, using the same ideas as the multimethod implementations, but guaranteeing trial-and-error dispatching. Carl Banks (**) I avoid the term "generic function" since it constrasts starkly with the use of the word "generic" in generic programming. From half.italian at gmail.com Wed Sep 24 19:30:42 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 24 Sep 2008 16:30:42 -0700 (PDT) Subject: Folder Actions on Mac OSX Leopard? References: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> Message-ID: <6ea2a222-90be-4079-b78f-ead1e8f6d241@q26g2000prq.googlegroups.com> On Sep 24, 12:31?pm, "squishywaf... at gmail.com" wrote: > Greetings, > > I've been trying to figure out if it's possible to attach a Python > script to an action via Mac OSX Leopard's File Actions system. I'm > wanting to call a Python script every time a file is added to the > monitored folder. Just adding a .py file doesn't seem to do anything > at all, and I can't find any log output anywhere to see what's going > on. > > I'm more just looking to see if this is or is not possible. I'm not > interested in other solutions, as I already have them lined up in case > this is a no-go, but I'd really love to be able to do it this way if > anyone has any experience. Googling around revealed pretty much > nothing. > > Any help is much appreciated, > Greg I always wondered about Folder Actions... I just tested. You can have applescript call python scripts via `do shell script`. But it seemed a bit flakey. I would either go with applescript all the way, or look in to your other options. ~Sean From gatti at dsdata.it Thu Sep 18 03:53:46 2008 From: gatti at dsdata.it (Lorenzo Gatti) Date: Thu, 18 Sep 2008 00:53:46 -0700 (PDT) Subject: XML-schema 'best practice' question References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: <76cf5eaf-25fa-4a6c-ae7b-e57016f5cc52@y38g2000hsy.googlegroups.com> On 18 Set, 08:28, Frank Millman wrote: > I am thinking of adding a check to see if a document has changed since > it was last validated, and if not, skip the validation step. However, > I then do not get the default values filled in. > > I can think of two possible solutions. I just wondered if this is a > common design issue when it comes to xml and schemas, and if there is > a 'best practice' to handle it. > > 1. Don't use default values - create the document with all values > filled in. > > 2. Use python to check for missing values and fill in the defaults > when processing the document. > > Or maybe the best practice is to *always* validate a document before > processing it. The stated problem rings a lot of premature optimization bells; performing the validation and default-filling step every time, unconditionally, is certainly the least crooked approach. In case you really want to avoid unnecessary schema processing, if you are willing to use persistent data to check for changes (for example, by comparing a hash or the full text of the current document with the one from the last time you performed validation) you can also store the filled-in document that you computed, either as XML or as serialized Python data structures. Regards, Lorenzo Gatti From greg at cosc.canterbury.ac.nz Wed Sep 17 19:06:32 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 18 Sep 2008 11:06:32 +1200 Subject: minimum install & pickling In-Reply-To: References: Message-ID: <6jdh9gF2q06nU1@mid.individual.net> Aaron "Castironpi" Brady wrote: > Even a function created from raw bytecode string can't do anything > without __import__ or 'open'. Not true: for cls in (1).__class__.__bases__[0].__subclasses__(): if cls.__name__ == "file": F = cls F(my_naughty_path, "w").write(my_naughty_data) -- Greg From castironpi at gmail.com Thu Sep 4 16:25:05 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 13:25:05 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: On Sep 4, 2:42?pm, bearophileH... at lycos.com wrote: > David C. Ullrich: > > > At least in mathematics, the sum of the elements of > > the empty set _is_ 0, while the maximum element of the > > empty set is undefined. > > What do you think about my idea of adding that 'default' argument to > the max()/min() functions? > > Bye, > bearophile For max and min, why can't you just add your argument to the set itself? The reason max([]) is undefined is that max( S ) is in S. The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. From david at boddie.org.uk Tue Sep 2 16:03:30 2008 From: david at boddie.org.uk (David Boddie) Date: Tue, 02 Sep 2008 22:03:30 +0200 Subject: configure kdevelop for python References: <2f21628f-80dd-4710-b0be-2b1c772e5698@l33g2000pri.googlegroups.com> Message-ID: On Sunday 31 August 2008 10:29, Sindhu wrote: > am a newbie to python language and kdevelop, so i would like to know > how to configure kdevelop for python programming? complete with a > debugger? Maybe asking on the kdevelop mailing list will yield a helpful answer: http://lists.kde.org/?l=kdevelop&r=1&w=2 David From mwalsh at mwalsh.org Tue Sep 30 13:41:32 2008 From: mwalsh at mwalsh.org (Martin Walsh) Date: Tue, 30 Sep 2008 12:41:32 -0500 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> Message-ID: <48E264CC.4050701@mwalsh.org> Blubaugh, David A. wrote: > To All, > > I have been attempting to execute the following program within the > Python environment: > > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? Based on your description, it seems pretty obvious (and easy to confirm) that Myprogram.exe needs to be run from its containing directory ("C:\myprogramfolder\run"). Try something like this... import os pwd = os.getcwd() os.chdir('c:/myprogramfolder/run') os.system("Myprogram.exe 1 1 acc 0") os.chdir(pwd) HTH, Marty From rsgalloway at gmail.com Sun Sep 28 15:00:57 2008 From: rsgalloway at gmail.com (rsgalloway at gmail.com) Date: Sun, 28 Sep 2008 12:00:57 -0700 (PDT) Subject: How to read a jpg bytearray from a Flash AS3 file References: Message-ID: <3641130e-43d3-4996-a123-0254a47a19d7@o40g2000prn.googlegroups.com> Thanks! I'm using form = cgi.FieldStorage(). When I print out the contents of form, I get this: FieldStorage(None, None, '\xff\xd8\xff\xe0\x00\x10JFIF \x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb \x00\x84\x00\x05\x03\x04\x04\x04\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0c \x08\x07\x07\x07\x07\x0f\x0b\x0b\t\x0c\x11\x0f\x12\x12\x11\x0f \x11\x11\x13\x16\x1c\x17\x13\x14\x1a\x15\x11\x11\x18!\x18\x1a\x1d\x1d \x1f\x1f\x1f\x13\x17"$"\x1e$\x1c\x1e\x1f\x1e \x01\x05\x05\x05\x07\x06\x07\x0e\x08\x08\x0e\x1e\x14\x11\x14\x1e\x1e \x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e \x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e \x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\xff\..... Which is obviously the binary data of the image I want. How do I access this data? I'm used to getting it like this: name = form['name'].value But I don't think this will work in this case. TIA. From Edwin.Madari at VerizonWireless.com Fri Sep 5 09:53:47 2008 From: Edwin.Madari at VerizonWireless.com (Edwin.Madari at VerizonWireless.com) Date: Fri, 5 Sep 2008 09:53:47 -0400 Subject: cx_oracle and commands In-Reply-To: Message-ID: <20080905135359.2F4611E4016@bag.python.org> gaius hammond Wrote: >Hi all, > > >I am having a very strange problem with cx_Oracle, has anyone >seen this kind of behavior before: > > > >ActivePython 2.5.2.2 (ActiveState Software Inc.) based on >Python 2.5.2 (r252:60911, Mar 27 2008, 18:53:24) [C] on sunos5 >Type "help", "copyright", "credits" or "license" for more information. >>>> from commands import getstatusoutput >>>> (status, output) = getstatusoutput('ls') >>>> status >0 >>>> from cx_Oracle import connect, SYSDBA >>>> db = connect(mode=SYSDBA) >>>> (status, output) = getstatusoutput('ls') >Traceback (most recent call last): > File "", line 1, in > File "/opt/ASpy25/lib/python2.5/commands.py", line 55, in >getstatusoutput > sts = pipe.close() >IOError: [Errno 10] No child processes > > > >Basically, once I have made a connection to Oracle I can no >longer use getstatusoutput(). This is a real problem as >I need to get a list of things to work on from Oracle then >spawn commands to process them... > > >Thanks, > There is no mode parameter to connect. use try-catch around db = connect(mode=SYSDBA) line to see what's going on. Edwin The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From castironpi at gmail.com Sun Sep 28 03:04:14 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 00:04:14 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <6k8ll9F6jbmtU2@mid.uni-berlin.de> Message-ID: <68c5360b-d76f-4867-804a-46e8488514a3@m73g2000hsh.googlegroups.com> On Sep 28, 1:14?am, Marc 'BlackJack' Rintsch wrote: > On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote: > > To me, this is a somewhat unintuitive behavior. ?I want to discuss the > > parts of it I don't understand. > > >>>> f= [ None ]* 10 > >>>> for n in range( 10 ): > > ... ? ? f[ n ]= lambda: n > > ... > >>>> f[0]() > > 9 > >>>> f[1]() > > 9 > > `n` is looked up at the time ``f[0]`` is called. ?At that time it is > bound to 9. > > >>>> f= [ None ]* 10 > >>>> for n in range( 10 ): > > ... ? ? f[ n ]= (lambda n: ( lambda: n ) )( n ) ... > >>>> f[0]() > > 0 > >>>> f[1]() > > 1 > > > Which is of course the desired effect. ?Why doesn't the second one just > > look up what 'n' is when I call f[0], and return 9? > > It *does* look up `n` at the time you call ``f[0]`` but this time it's > the local `n` of the outer ``lambda`` function and that is bound to > whatever the function was called with. ?At the time it was called the > global `n` was bound to 0. ?Maybe it get's more clear if you don't name > it `n`: > > In [167]: f = [None] * 10 > > In [168]: for n in xrange(10): > ? ?.....: ? ? f[n] = (lambda x: lambda: x)(n) > ? ?.....: > > In [169]: f[0]() > Out[169]: 0 > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Hi Marc, It's my understanding that 'n' gets a new value every time through the loop. n= 0 on the first pass, n= 1 on the second pass, and so on. n= 9 by the end, and that's why `lambda: n` always returns 9. It queries the variable 'n', and finds 9. (This got lengthy. I started thinking aloud.) In your version of the indirect example, it queries the variable 'x', which it finds in a new distinct scope in each f element. In f[0], x= 0. In f[1], x= 1. There are 10 different 'x' variables throughout the contents of f. The direct example does not do this allocation of ten different 'x's. It's sort of helping. I think I feel like the following is more like what I'm looking for: (Non-standard) >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= n ... >>> f[0] 9 >>> f[1] 9 because when you access f[0], it looks up the variable 'n'. Obviously not. (Unproduced) >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= late( n ) #late/lazy ... >>> f[0] 9 >>> f[1] 9 >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= early( n ) #early/eager ... >>> f[0] 0 >>> f[1] 1 For the functions, I want a function that returns 'n', either late or early. (Unproduced) >>> for n in range( 10 ): ... f[ n ]= lambda: late( n ) >>> f[0]() 9 >>> for n in range( 10 ): ... f[ n ]= lambda: early( n ) >>> f[0]() 0 I don't think you could pull this off. 'late' and 'early' succeed with quotes around n, early('n') and late('n'), in the direct assignments, but the functions aren't so lucky. 'n' has gone on to a better world by the time 'early' gets any control. This might have some success. (Unproduced) >>> for n in range( 10 ): ... f[ n ]= late( lambda: n ) >>> f[0]() 9 >>> for n in range( 10 ): ... f[ n ]= early( lambda: n ) >>> f[0]() 0 Though it's beyond my foresight to tell if it's feasible as stated, if you need quotes, how much introspection you would need, etc. Plus, 'late' and 'early' were accepting quoted parameters earlier. How would they look inside a function? Could a simple decorator provide the service? On a tangent about mutables, it's not that numbers, strings, and tuples are 'immutable' per se, it's just that they don't have any methods which mutate them (or assignable properties). Lists and dictionaries do. It's up to the user whether a custom class does. From victor.prosolin at gmail.com Mon Sep 29 13:37:36 2008 From: victor.prosolin at gmail.com (Victor Prosolin) Date: Mon, 29 Sep 2008 11:37:36 -0600 Subject: Python is slow? In-Reply-To: <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Lawrence D'Oliveiro: >>> Gnuplot is non-Free software. > > Fly Away: >> Yes, it is. > > From: > http://www.gnuplot.info/faq/faq.txt > > 1.7 Does gnuplot have anything to do with the FSF and the GNU project? > [...] > Gnuplot is freeware in the sense that you don't have to pay for it. > However > it is not freeware in the sense that you would be allowed to > distribute a > modified version of your gnuplot freely. [...] Yes, I did read this prior to posting. Victor. From mathieu.prevot at gmail.com Thu Sep 4 09:31:09 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 15:31:09 +0200 Subject: path slashes cleaning In-Reply-To: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> References: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> Message-ID: <3e473cc60809040631o211a7e77r1abced4567840b62@mail.gmail.com> 2008/9/4 Mathieu Prevot : > Hi, > > for scripts that take arguments, I would like to remove the trailing > slash if it's present. > > Is there something else than: > > a='/usr/local/lib/' > if a[-1] == '/': > a = list(a) > a.pop() > ''.join(a) A dummy a.rstrip('/') Sorry for the noise Mathieu From john.ford at colorado.edu Wed Sep 24 23:51:28 2008 From: john.ford at colorado.edu (john.ford at colorado.edu) Date: Wed, 24 Sep 2008 20:51:28 -0700 (PDT) Subject: How to parse a string completely into a list References: Message-ID: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> On Sep 24, 9:44?pm, "Chris Rebert" wrote: > On Wed, Sep 24, 2008 at 8:30 PM, ? wrote: > > I want to take a long alpha-numeric string with \n and white-space and > > place ALL elements of the string (even individual parts of a long > > white-space) into separate list elements. The most common way I've > > seen this performed is with the split() function, however I don't > > believe that it has the power to do what I am looking for. > > Any suggestions? > > thanks > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Could you please define exactly what you mean by "elements" of a string? > > If you mean characters, then just use list():>>> list(" ?\n \t abc") > > [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] > > Regards, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com Worked like a charm. kudos! From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 13:38:13 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 19:38:13 +0200 Subject: properties setting each other In-Reply-To: References: <200809031644.10870.maric@aristote.info> Message-ID: <48bee775$0$7236$426a34cc@news.free.fr> Maric Michaud a ?crit : > Le Wednesday 03 September 2008 17:40:43 mk, vous avez ?crit : >>> Note that if one property can really be computed from another, this kind >>> of thing could be considered as bad design (except if the computation is >>> heavy). >> Hmm, why? Is the line of thinking smth like: because the variables >> should be kept to minimum and they should be calculated at the moment >> they are needed? > > Because you have to make extra effort to keep the logical relation between > value and square. self._square is not really needed, and what is not needed > is just extra hassle. > > Doesn't it clear that your code is more hard to maintain than the > alternative : > > class Squared(object): > > def __init__(self, val): > self._val=val > > def fgetvalue(self): > return self._val > def fsetvalue(self, val): > self._val=val > value = property(fgetvalue, fsetvalue) > > def fgetsquare(self): > return self.value ** 2 > def fsetsquare(self,s): > self.value = math.sqrt(s) > square = property(fgetsquare, fsetsquare) FWIW, if there's no computation on getting or setting value, you can make it a plain attribute. But while it's quite clear that in this example use case it would be better to have only one property (weither square or value, depending on which is the most often use), things are not always that simple in real world code, and - as you mentionned - there may be times where you have interdependant properties and really want to avoid recomputing the same thing over and over. Now there's no one size fits all solution here - it's an optimization problem, and as such depends on real use cases. From deets at nospam.web.de Tue Sep 23 08:20:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 23 Sep 2008 14:20:15 +0200 Subject: Docstrings for class attributes References: Message-ID: <6js582F4rs2vU1@mid.uni-berlin.de> Tom Harris wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. Sort of > a very limited implementation of PEP 224. The only solution that I can > see is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Epydoc interprets strings like this as doc-strings: """ FOO is not a bar """ FOO = "foo" However, it won't get recognized by help of course. Diez From hauva at arska.org Mon Sep 1 12:09:13 2008 From: hauva at arska.org (Ari Makela) Date: 01 Sep 2008 16:09:13 GMT Subject: Printing list of dates starting today References: <4v1ob4tgk0u4jhtobisaid1g9pst0ic011@4ax.com> Message-ID: <48bc13a9$0$23597$4f793bc4@news.tdc.fi> On 2008-09-01, Luka Djigas wrote: > please, I need your help. I'm new to python, so I don't know if this > will seem like a stupid question to some of you ... There are several ways to do it. Have a look at the documentation of modules time and datetime. For this exact problem time is the most straighforward one. > I have a need to write to a file (or just print on screen, that part > doesn't matter at this point) a list of dates, starting today. For > example: > 02.09.2008. tue > 03.09.2008. wed 0 hauva at laphroaig:~ $ /usr/bin/python Python 2.5.2 (r252:60911, Jul 31 2008, 17:31:22) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> DAY = 60 * 60 * 24 >>> today = time.time() >>> for i in (0, 1, 2, 3): ... t = time.gmtime(time.time() + i * DAY) ... print time.strftime('%d.%m.%Y, %a', t) ... 01.09.2008, Mon 02.09.2008, Tue 03.09.2008, Wed 04.09.2008, Thu -- Ari Makela late autumn - hauva at arska.org a single chair waiting http://arska.org/hauva/ for someone yet to come -- Arima Akito From jhuerta at cipf.es Thu Sep 25 04:11:34 2008 From: jhuerta at cipf.es (Jaime Huerta Cepas) Date: Thu, 25 Sep 2008 10:11:34 +0200 Subject: how to build a MacOS universal python package including external dependencies In-Reply-To: <3e473cc60809240944h1ea69275jc066fc957869d8f2@mail.gmail.com> References: <3e473cc60809240944h1ea69275jc066fc957869d8f2@mail.gmail.com> Message-ID: Thanks Mathieu, I think MacPorts will be the easiest way (all dependencies are available). I could even base the installation script on "port" commands. The major problem will be to compile Qt4, which takes hours and requires X11. thnks, again. Jaime. On Wed, Sep 24, 2008 at 6:44 PM, Mathieu Prevot wrote: > 2008/9/24 Jaime Huerta Cepas : > > Hi all, > > > > I have developed a set python libraries that provide several scientific > > methods to analyse and visualize certain type of biological data. This > > libraries are based on many external python modules, such as python-mysql > > python-sip or python-qt4. I use GNU/linux to develop my tools and I found > no > > problems into installing all dependencies, however it does not seem to be > > that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 , > > mysqldb, scipy, numpy) are cross platform, but when you are trying to > > publish your tool in an academic journal, most referees (many of them > using > > MacOS) expect some kind of straightforward installation process for the > > tool. > > > > I wonder if there would be a way in which I could compile all the > > dependencies and libraries in a MacOs system and then building a static > > universal binary that I can distribute. I guess it should be possible, > but > > I am not sure how difficult it might be, and whether all dependencies > (qt4 > > is huge) can be packaged together. > > IMHO this is too complex to commit. Macport is a way to do what you > want, but packages may not be up to date enough. Maybe the easiest and > simplest way for you to do this is to write a script that will > download, compile and install everything. > > The script should work like: > > sudo all_in_one_script.py > > and then wait for jobs to be done. Your script will need to know if a > package was sucessfully installed and then continue or take steps and > say it. For a complex set of dependencies, I recommend you to write > Makefiles. > > For instance, in pseudo-code: > if /usr/local/lib/libfoo.dylib doesn't exist > download foo > install foo > > if python-module foo doesn't exist > download foo > python foo/setup.py install > > etc > > HTH > Mathieu > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From akabaila at pcug.org.au Tue Sep 23 00:59:33 2008 From: akabaila at pcug.org.au (Al Kabaila) Date: Tue, 23 Sep 2008 14:59:33 +1000 Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> <78547919-be84-41ac-955b-78824d64b4b8@y21g2000hsf.googlegroups.com> Message-ID: <1222145973.444160@chilli.pcug.org.au> Tim Leslie wrote: > There is no need for a wrapper. Both numarray and Numeric have been > deprecated in favour of numpy. Well, some years ago I looked for a matrix package. At that time it looked that numarray was the end of it all - it had a clean syntax, an active developer team. It looked to have everything that one could possibly wish. And here we are, it is fallen out of favour. It seems to me to be unwise to assume that in OSS there is the final, never to be superseded package for anything, including matrix algebra. OTH, I appreciate your reminder of SciPy. Thank you, Leslie. Michael Palmer wrote: > On Sep 22, 4:02 am, Al Kabaila wrote: >> This is a very active newsgroup that incudes such giants as Frederik >> Lundh > > He looks rather small to me in this picture: > http://www.python.org/~guido/confpix/flundh-2.jpg Yes, indeed. However, I had in mind giants in informed writing on Python. Besides, it seems a custom to put in very old pictures in web publications. I do that myself, except that even in old pictures I am really, really old... I have a superseded paper version of Frederik Lundh's book "Python Standard Library", published by O'Reilly in May 2001. For Python that is a fair while back. Thanks for the link to the picture - appreciate it! OldAl. -- Al Kabaila (Dr) http://akabaila.pcug.org.au/StructuralAnalysis From bearophileHUGS at lycos.com Fri Sep 19 22:30:58 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Sep 2008 19:30:58 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: <22890f2d-f55a-45f5-a22c-2957f564e5cb@l42g2000hsc.googlegroups.com> MRAB: > except that it could be misleading when: > len(file(path)) > returns the number of lines and /not/ the length in bytes as you might > first think! :-) Well, file(...) returns an iterable of lines, so its len is the number of lines :-) I think I am able to always remember this fact. > Anyway, here's another possible implementation using bags (multisets): This function looks safer/faster: def major_version(version_string): "convert '1.2.3.2' to '1.2'" return '.'.join(version_string.strip().split('.', 2)[:2]) Another version: import re patt = re.compile(r"^(\d+\.\d+)") dict_of_counts = defaultdict(int) for ver in versions: dict_of_counts[patt.match(ver).group(1)] += 1 print dict_of_counts Bye, bearophile From steven at REMOVE.THIS.cybersource.com.au Tue Sep 30 02:07:45 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 06:07:45 GMT Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: On Mon, 29 Sep 2008 21:03:07 -0700, namekuseijin wrote: >> Why isn't len implemented as a str.len and list.len method instead of a >> len(list) function? > > Because postfix notation sucks. The natural way of spelling is > adjective+noun and verb+predicate. "Natural"? You mean phrases like "heir apparent" and "worst choice imaginable" are unnatural? To say nothing of languages like Spanish, Albanian, Italian, Cornish, Vietnamese, Hebrew... -- Steven From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 13:22:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 19:22:35 +0200 Subject: improving a huge double-for cycle In-Reply-To: References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <48d54d48$0$824$426a74cc@news.free.fr> Harald Luessen a ?crit : > On Thu, 18 Sep 2008 Bruno Desthuilliers wrote: > >> # Harald : uncomment this and run test_results. As far as I can tell, it >> # doesn't yields the expected results >> >> ## IN7 = IN[:] >> ## def sortk7(n): >> ## return n.coordinates[0] >> >> ## def doubles7(): >> ## "is ordering better ? - Nope Sir, it's broken..." >> ## IN7.sort(key=sortk) >> ## SN = [] >> ## sn_append = SN.append >> ## in_len = len(IN) >> ## for i in xrange(in_len): >> ## node_i = IN[i] >> ## coords_i = node_i.coordinates >> ## for j in xrange(i+1, in_len): >> ## if coords_i[0] == IN[j].coordinates[0]: >> ## if coords_i[1] == IN[j].coordinates[1]: >> ## sn_append(node_i) >> ## else: >> ## break >> ## return SN > ... >> Results here (py2.5, gentoo linux, athlonxp1800, 512 ram): >> >>>>> test_results() >> True >>>>> test_times() >> doubles0 : 1.55667901039 >> doubles1 : 0.719144105911 >> doubles2 : 0.703393936157 >> doubles3 : 0.700654983521 >> doubles4 : 0.706257104874 >> doubles5 : 0.528184890747 >> doubles6 : 0.461633205414 >> doubles8 : 0.0134379863739 >> doubles9 : 0.0108540058136 > > When you change my code then do it right. :-) > You forgot to change the IN to IN7 at _every_ place. > And the sortk should be sortk7 in _both_ places. doh :( Sorry Harald, my fault, you're right... > I never let the code run before myself. I just wrote it > in the newsreader. But now i did and I have a second > version as bonus. > > > IN7 = IN[:] > > def sortk7(n): > return n.coordinates[0], n.coordinates[1] > > def doubles7(): > IN7.sort(key=sortk7) > SN = [] > sn_append = SN.append > in_len = len(IN7) > for i in xrange(in_len): > node_i = IN7[i] > coords_i = node_i.coordinates > for j in xrange(i+1, in_len): > if coords_i[0] == IN7[j].coordinates[0]: > if coords_i[1] == IN7[j].coordinates[1]: > sn_append(node_i) > else: > break > return SN > > > def comp7( x, y ): > return cmp( x.coordinates, y.coordinates ) > > def doubles7a(): > IN7.sort( comp7 ) > SN = [] > sn_append = SN.append > in_len = len(IN7) > for i in xrange(in_len): > node_i = IN7[i] > for j in xrange(i+1, in_len): > node_j = IN7[j] > if comp7( node_i, node_j ) == 0: > sn_append(node_i) > else: > break > return SN > > > Here are the results. (py2.5, WindowsXP, Pentium4, 2.6GHz, 1.5GB): > My version is not so bad. > > doubles0 : 1.03830598582 > doubles1 : 0.47943719104 > doubles2 : 0.487412506338 > doubles3 : 0.475924733451 > doubles4 : 0.466548681466 > doubles5 : 0.340487967046 > doubles6 : 0.278480365521 > doubles7 : 0.0953190978183 > doubles7a : 0.0784233750379 > doubles8 : 0.010236496538 > doubles9 : 0.00742803903848 > Point taken. Now there's one thing I find questionnable with your solution (which is probably why I didn't bother double-checking it when it *appeared* to be broken) : you assume that it's ok to loose original ordering, which I strongly suspect is not the case for the OP use case, and given the OP use case list's size, working on a copy might not be an acceptable solution. But anyway: this is not an excuse for me having broken your code. My apologies. From clp at rebertia.com Wed Sep 24 23:44:25 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 24 Sep 2008 20:44:25 -0700 Subject: How to parse a string completely into a list In-Reply-To: References: Message-ID: <47c890dc0809242044i3227ac9fy899723020c1ee9f3@mail.gmail.com> On Wed, Sep 24, 2008 at 8:30 PM, wrote: > I want to take a long alpha-numeric string with \n and white-space and > place ALL elements of the string (even individual parts of a long > white-space) into separate list elements. The most common way I've > seen this performed is with the split() function, however I don't > believe that it has the power to do what I am looking for. > Any suggestions? > thanks > -- > http://mail.python.org/mailman/listinfo/python-list > Could you please define exactly what you mean by "elements" of a string? If you mean characters, then just use list(): >>> list(" \n \t abc") [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] Regards, Chris -- Follow the path of the Iguana... http://rebertia.com From bdesth.quelquechose at free.quelquepart.fr Mon Sep 1 15:05:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 21:05:57 +0200 Subject: enhancing/wrapping an existing instance of a duck In-Reply-To: References: Message-ID: <48bc5906$0$854$426a34cc@news.free.fr> Neville Dempsey a ?crit : > What do I need to add to HTMLDecorator? > > A simpler example: > > import cgi > > class ClassX(object): > pass # ... with own __repr__ > > class ClassY(object): > pass # ... with own __repr__ > > inst_x=ClassX() Why do you need to prefix your variables with 'inst_' ? > inst_y=ClassY() > > inst_z=[ i*i for i in range(25) ] > > inst_b=True > > class HTMLDecorator(object): > def html(self): # an "enhanced" version of __repr__ > return cgi.escape(self.__repr__()).join(("

","

")) uppercase tags are so 1990... More seriously, your code would be more readable (and more maintainable) using string formatting, ie: def html(self): # an "enhanced" version of __repr__ return cgi.escape("

%r

" % self) > print HTMLDecorator(inst_x).html() (snip unexecuted code) > Output: > Traceback (most recent call last): > File "html.py", line 21, in > print HTMLDecorator(inst_x).html() > TypeError: default __new__ takes no parameters > > Can I simply decorate an existing instance? For which definitions of "simply" and "decorate", and for instances of what ? Some classes will let you add arbitrary attributes to either themselves of their instances. Some (hint: mostly builtin types) wont, because they've been implemented otherwise, usually for performances reasons. If all you need is a simple enhanced "html" __repr__, just use a generic function - being OO doesn't mean you have to use classes everywhere (hint : OO stands for "object oriented", not "class oriented"). All you need here is: def html(obj, tag="h1"): return "<%s>%s" % (tag, cgi.escape(repr(obj)), tag) If you have more responsabilities to add, and want something generic, then you'll have to use composition/delegation instead of inheritance, ie: class HTMLDecorator(object): def __init__(self, obj): # use name mangling to avoid possible name clash self.__obj = obj def html(self): # reuse the above generic html() func return html(self.__obj) def __getattr__(self, name): # trivial, always delegate - __getattr__ is # only called when evrything else failed return getattr(self.__obj, name) def __setattr__(self, name, value): # tricky : __setattr__ is *always* called if name == "_HTMLDecorator__obj" or name in type(self).__dict__: super(HTMLDecorator, self).__setattr__(name, value) else: setattr(self.__obj, name, value) But be warned that this might be tricky (I wouldn't bet a truly generic implementation of the class decorator pattern is something doable), and that you'll have to pay the price (wrt/ perfs) for overriding __setattr__. As a general rule, it's better to avoid overridding __getattribute__ and __setattr__ whenever possible. HTH From marco.bizzarri at gmail.com Sat Sep 6 02:08:29 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 6 Sep 2008 08:08:29 +0200 Subject: use str as variable name In-Reply-To: References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> Message-ID: <3f0d61c40809052308v185f3787p64f6fd89172114c7@mail.gmail.com> On Sat, Sep 6, 2008 at 7:52 AM, Fredrik Lundh wrote: > Marco Bizzarri wrote: > >>> (...as Bruno implies, setattr(), len() et al can be and should be viewed >>> as >>> generic functions. >> >> Just a question: "generic functions" are not meant in the sense of >> "generic functions" of CLOS, am I right? > > it's meant in exactly that sense: len(L) means "of all len() implementations > available to the runtime, execute the most specific code we have for the > object L". > It is a generic functions like a CLOS one, as long as we remain to one parameter. I mean, there will be just one implemenatation of foo(bar, man) which the python interpretr can find; am I right? -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From roy at panix.com Wed Sep 3 07:54:46 2008 From: roy at panix.com (Roy Smith) Date: Wed, 03 Sep 2008 07:54:46 -0400 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > Without them it looks better: > > import sys > for line in sys.stdin: > try: > a, b = map(int, line.split(None, 2)[:2]) > except ValueError: > pass > else: > if a + b == 42: > print b I'm philosophically opposed to one-liners like: > a, b = map(int, line.split(None, 2)[:2]) because they're difficult to understand at a glance. You need to visually parse it and work your way out from the inside to figure out what's going on. Better to keep it longer and simpler. Now that I've got my head around it, I realized there's no reason to make the split part so complicated. No reason to limit how many splits get done if you're explicitly going to slice the first two. And since you don't need to supply the second argument, the first one can be defaulted as well. So, you immediately get down to: > a, b = map(int, line.split()[:2]) which isn't too bad. I might take it one step further, however, and do: > fields = line.split()[:2] > a, b = map(int, fields) in fact, I might even get rid of the very generic, but conceptually overkill, use of map() and just write: > a, b = line.split()[:2] > a = int(a) > b = int(b) From google at mrabarnett.plus.com Fri Sep 26 08:45:23 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Sep 2008 05:45:23 -0700 (PDT) Subject: how to keep a window above all other OS windows? References: Message-ID: <3a61c7c0-4197-43c8-9697-89df1f9587f4@25g2000hsx.googlegroups.com> On Sep 26, 10:04?am, Dennis Lee Bieber wrote: > On Fri, 26 Sep 2008 19:52:59 +1200, Lawrence D'Oliveiro > declaimed the following in > comp.lang.python: > > > > > This sort of thing should be configurable in many X11-based window managers. > > ? ? ? ? Maybe... But I'm stuck with a MicroSloth world -- at least they > didn't decide 1 mouse button is all anyone would need There's some useful information at http://epydoc.sourceforge.net/stdlib/Tkinter.Wm-class.html. >>> from Tkinter import * >>> w = Tk() >>> w.attributes('-topmost', True) '' >>> w.mainloop() >>> The window stays on top. From febkimbleox at gmail.com Sat Sep 27 07:17:36 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:17:36 -0700 (PDT) Subject: amaterski porno video hrvaski amaterski porno video amaterski porno video maja - Free Message-ID: <00aeed03-509b-49af-a472-aa2f5a2574f8@l64g2000hse.googlegroups.com> amaterski . . . *******CLICK HERE******** http://vids365.cn/amaterski ***************************** . . . . . . . . . . . . At this point amaterski began to wonder whether amaterski had been missed or overheard ? there would be hell to pay if amaterski had. At this point porno began to wonder whether porno had been missed or overheard ? there would be hell to pay if porno had. Like the time video went shopping for video mother?s wedding gown. Like the time hrvaski went shopping for hrvaski mother?s wedding gown. Like the time amaterski went shopping for amaterski mother?s wedding gown. Like the time porno went shopping for porno mother?s wedding gown. Like the time video went shopping for video mother?s wedding gown. Like the time amaterski went shopping for amaterski mother?s wedding gown. Like the time porno went shopping for porno mother?s wedding gown. Like the time video went shopping for video mother?s wedding gown. Like the time maja went shopping for maja mother?s wedding gown. Like the time amaterski went shopping for amaterski mother?s wedding gown. Like the time video went shopping for video mother?s wedding gown. Like the time klipovi went shopping for klipovi mother?s wedding gown. ?I found porno yesterday after rehearsal? porno said. From deets at nospam.web.de Thu Sep 11 14:09:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Sep 2008 20:09:06 +0200 Subject: Please help me finding a way to implement os.path.issubpath(a, b) In-Reply-To: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> References: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> Message-ID: <6it563Fe2h8U2@mid.uni-berlin.de> Giampaolo Rodola' schrieb: > Hi, > I'm trying to implement a function which returns whether a path is a > subpath of another one (e.g. /a/b/c is a subpath of /a/b). > I wrote this function which apparently seems to work fine: > > import os > > def issubpath(path1, path2): > """Return True if path1 is a sub path of path2.""" > if path1 == path2: > return False > x1 = path1.split(os.sep) > x2 = path2.split(os.sep) > return x1[:len(x2)] == x2 > > ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False. > A little help would be appreciated. Any reason why os.path.normpath(a).startswith(os.normpath(b)) doesn't do the trick? Diez From karentataka at gmail.com Sun Sep 21 00:19:50 2008 From: karentataka at gmail.com (karentataka at gmail.com) Date: Sat, 20 Sep 2008 21:19:50 -0700 (PDT) Subject: 9hrsj SOMA - Viagra - Phentermine - Ultram - Ambien - Diflucan ...Free Overnight Fedex! Message-ID: <5f76a256-15d1-4864-b27e-42dbe1b432fa@m3g2000hsc.googlegroups.com> Start saving, best online pharmacy here http://gjlabeh.cuchezfarg.com/?cdfikmabehxwvrsygzchcmjl From coolkid246 at googlemail.com Thu Sep 4 06:14:18 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:14:18 -0700 (PDT) Subject: =?ISO-8859-1?Q?sofort_kredit_online_in_Cochem_geld_kredite_bank_kre?= =?ISO-8859-1?Q?dite_Guenstige_Kredide_online_ohne_SCHUFA_kredit_ohne_schufa?= =?ISO-8859-1?Q?_oesterreich_beamtendarlehen_ohne_schufa_schweizer_kredit_ba?= =?ISO-8859-1?Q?rkredit_online_umschuldung_online_blitzkredite_schweizer_kre?= =?ISO-8859-1?Q?dit_online_kredite_fuer_selbstaendige_online_kredit_trotz_ba?= =?ISO-8859-1?Q?r_kredit_ohne_schufa_kredit_ohne_schufa_selbstaendig_auto_oh?= =?ISO-8859-1?Q?ne_schufa__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTIGE_KREDITE_ONLINE_=2B=2B=2B_KREDITE_?= =?ISO-8859-1?Q?IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_=2B_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D24?= =?ISO-8859-1?Q?4=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDI?= =?ISO-8859-1?Q?TE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http?= =?ISO-8859-1?Q?=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D24?= =?ISO-8859-1?Q?4=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDI?= =?ISO-8859-1?Q?TE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_=2B_=2B_?= =?ISO-8859-1?Q?=2B_=2B_______________________online_kredit_auch_kredite_fuer_se?= =?ISO-8859-1?Q?lbststaendige_in_Frankenberg_sofort_kredit_ohne_schufa_fuer_?= =?ISO-8859-1?Q?kredite_sicherheiten_in_Mittweida_online_kredite_in_schweize?= =?ISO-8859-1?Q?r_kredite_in_L=FCchow_sofortkredit_schufafrei_kredit_auch_ohn?= =?ISO-8859-1?Q?e_schufa_in_Tuttlingen_www_kredite_ohne_schufa_kredit_ohne_s?= =?ISO-8859-1?Q?chufa_arbeitslose_in_Aurich_kredit_uni_postbank_kredit_onlin?= =?ISO-8859-1?Q?e_in_Aalen_kredite_selbstaendige_onlinekredit_in_Ruppin_kred?= =?ISO-8859-1?Q?ite_online_berechnen_kredite_banken_in_Sulzbach_kredit_ohne_?= =?ISO-8859-1?Q?schufa_vergleich_Guenstige_Kredide_online_ohne_SCHUFA_in_Sol?= =?ISO-8859-1?Q?tau_kredite_zinsen_kredit_ohne_schufa_auskunft_in_Offenburg_?= =?ISO-8859-1?Q?online_credit_ohne_schufa_online_kredite_ohne_schufa_in_W=FCr?= =?ISO-8859-1?Q?zburg_kredit_finanzierung_onlinekredit_in_Lippe_kredit_selbs?= =?ISO-8859-1?Q?taendige_kredit_arbeitslos_in_Starnberg_finanzierung_online_?= =?ISO-8859-1?Q?kredite_privat_in_Halberstadt_kredite_banken_blitzkredite_in?= =?ISO-8859-1?Q?_Lippe_online_kredit_im_schweizer_kredit_ohne_schufa_in_K=FCn?= =?ISO-8859-1?Q?zelsau_kredit_ohne_schufa_selbstaendige_kredit_selbstaendige?= =?ISO-8859-1?Q?_in_M=FChldorf_kredit_auskunft_dispo_kredite_in_Siegen_kredit?= =?ISO-8859-1?Q?e_fuer_arbeitslose_ohne_schufa_online_kredit_trotz_schufa_in?= =?ISO-8859-1?Q?_Trier____=2D_handyvertrag_ohne_schufa_kredite_online_in_Offen?= =?ISO-8859-1?Q?bach_=2D_kredit_arbeitslose_internet_kredit_in_Coburg_=2D_klein_?= =?ISO-8859-1?Q?kredit_ohne_schufa_kredit_von_privat_ohne_schufa_in_L=FCdensc?= =?ISO-8859-1?Q?heid_=2D_kleinkredite_geld_kredit_in_Steinburg_=2D_www_online_kr?= =?ISO-8859-1?Q?edite_online_credit_ohne_in_Bad_=2D_internetkredite_kredit_sch?= =?ISO-8859-1?Q?weiz_in_Pforzheim_=2D_raten_kredit_beamtenkredite_in_Siegburg_?= =?ISO-8859-1?Q?=2D_kredite_online_beantragen_online_kredit_ohne_in_Pasewalk_=2D?= =?ISO-8859-1?Q?_kredit_online_zusage_sofort_kredit_ohne_schufa_fuer_in_Heil?= =?ISO-8859-1?Q?bronn_=2D_zinsen_online_online_kredit_ohne_in_Kirchheimbolande?= =?ISO-8859-1?Q?n_=2D_kredite_zinsen_online_kredit_de_in_Sonneberg_=2D_kredit_gi?= =?ISO-8859-1?Q?rokonto_bonitaet_online_in_Loebau_=2D_sofortkredit_online_kred?= =?ISO-8859-1?Q?it_oesterreich_in_Schwarzenberg_=2D_kredite_privat_kredit_auch?= =?ISO-8859-1?Q?_ohne_schufa_in_Hoexter?= Message-ID: sofort kredit online in Cochem geld kredite bank kredite Guenstige Kredide online ohne SCHUFA kredit ohne schufa oesterreich beamtendarlehen ohne schufa schweizer kredit barkredit online umschuldung online blitzkredite schweizer kredit online kredite fuer selbstaendige online kredit trotz bar kredit ohne schufa kredit ohne schufa selbstaendig auto ohne schufa + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + online kredit auch kredite fuer selbststaendige in Frankenberg sofort kredit ohne schufa fuer kredite sicherheiten in Mittweida online kredite in schweizer kredite in L?chow sofortkredit schufafrei kredit auch ohne schufa in Tuttlingen www kredite ohne schufa kredit ohne schufa arbeitslose in Aurich kredit uni postbank kredit online in Aalen kredite selbstaendige onlinekredit in Ruppin kredite online berechnen kredite banken in Sulzbach kredit ohne schufa vergleich Guenstige Kredide online ohne SCHUFA in Soltau kredite zinsen kredit ohne schufa auskunft in Offenburg online credit ohne schufa online kredite ohne schufa in W?rzburg kredit finanzierung onlinekredit in Lippe kredit selbstaendige kredit arbeitslos in Starnberg finanzierung online kredite privat in Halberstadt kredite banken blitzkredite in Lippe online kredit im schweizer kredit ohne schufa in K?nzelsau kredit ohne schufa selbstaendige kredit selbstaendige in M?hldorf kredit auskunft dispo kredite in Siegen kredite fuer arbeitslose ohne schufa online kredit trotz schufa in Trier - handyvertrag ohne schufa kredite online in Offenbach - kredit arbeitslose internet kredit in Coburg - klein kredit ohne schufa kredit von privat ohne schufa in L?denscheid - kleinkredite geld kredit in Steinburg - www online kredite online credit ohne in Bad - internetkredite kredit schweiz in Pforzheim - raten kredit beamtenkredite in Siegburg - kredite online beantragen online kredit ohne in Pasewalk - kredit online zusage sofort kredit ohne schufa fuer in Heilbronn - zinsen online online kredit ohne in Kirchheimbolanden - kredite zinsen online kredit de in Sonneberg - kredit girokonto bonitaet online in Loebau - sofortkredit online kredit oesterreich in Schwarzenberg - kredite privat kredit auch ohne schufa in Hoexter From coolkid246 at googlemail.com Thu Sep 4 05:40:38 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 02:40:38 -0700 (PDT) Subject: guenstige kredite Message-ID: + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + + + + + From R.Brodie at rl.ac.uk Thu Sep 18 12:01:34 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 18 Sep 2008 17:01:34 +0100 Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: "Joe G (Home)" wrote in message news:48d2781f$0$4449$afc38c87 at news.optusnet.com.au... > I have installed Python for windows today from the python web site .I also installed > pySerial using the Windows installer from the sourceforge web site..... You need to read the pySerial smallprint, where it says: "The files in this package are 100% pure Python. They depend on non standard but common packages on Windows (pywin32) and Jython (JavaComm). POSIX (Linux, BSD) uses only modules from the standard Python distribution)" From praveenapanch at gmail.com Mon Sep 8 07:12:43 2008 From: praveenapanch at gmail.com (Praveena P) Date: Mon, 8 Sep 2008 04:12:43 -0700 (PDT) Subject: String to hexadecimal conversion References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> <14aa61b1-fb8c-44c4-bbf2-d8d2f92006e9@p10g2000prf.googlegroups.com> Message-ID: <7aee6fe6-de67-42b2-92ff-d5323372e102@26g2000hsk.googlegroups.com> On Sep 8, 2:31?pm, John Machin wrote: > On Sep 8, 7:05?pm, Praveena P wrote: > > > Hi folks, > > > I am new to Python... so am not too sure about how the type conversion > > works. > > > I have to read a file that contains hexadecimal data and use the data > > further to do some arithmetic calculations. > > A sample of the input is : 00000000000020E0000032F800000000400022005E > > The problem I am facing is this: > > I am using f.read(2) to read a byte at a time, but the data that is > > read is a string rather than a number. So it kind of hampers any > > arithmetic operations I perform on this data... > > > Could you please suggest some method I could use for this? > > *IF* all the data consists of unsigned 8-bit integers > a_byte = f.read(2) > uint8 = int(a_byte, 16) > > But I doubt it and that would be rather slow anyway. If your data is > homogenous, look at the array module. Otherwise, once you've worked > out how to break your file down into records, and what the layout of > each record is, you'll need the struct module. > > HTH, > John Hey John, Thanks! That was useful... I am still putting the code together with all the operations... will probably have loads more queries... :-) Have a good day! Praveena From http Thu Sep 4 21:04:44 2008 From: http (Paul Rubin) Date: 04 Sep 2008 18:04:44 -0700 Subject: Can anyone suggest a good crypto package? References: <7xwshr4qr4.fsf@ruckus.brouhaha.com> Message-ID: <7xmyino11v.fsf@ruckus.brouhaha.com> Fett writes: > Wow, I have no idea how that works, but I think it will do nicely. The > main goal is simply to ensure that data coming in (from a website), is > valid (ie. posted by me). If you just want to authenticate the strings without confidentiality, use the built-in HMAC module. But beware of replay attacks. > Thank you, I think we have a winner. (BTW, I have no idea how this > whole encrypting gives many strings, decrypting all gives the correct > one works, The plaintext gets a random string attached at encryption time, and the random string gets removed at decryption. Of course there are many possible random strings, so many possible ciphertexts for each plaintext. That means the ciphertext is a necessarily somewhat longer than the plaintext, so you have to be willing to deal with that. Note there's possibly a lot of other subtle issues you have to be careful of, like if you're authenticating a series of messages, how do you detect if one has been repeated or dropped from the middle? Until you've got all that figured out, you are leaving attacks possible. From lists at cheimes.de Tue Sep 23 18:10:26 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 24 Sep 2008 00:10:26 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), or should the exception propagate to the calling program which > handles the issue? Side note: sys.exit() is just another way to write raise SystemExit. The function is defined as: static PyObject * sys_exit(PyObject *self, PyObject *args) { PyObject *exit_code = 0; if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code)) return NULL; /* Raise SystemExit so callers may catch it or clean up. */ PyErr_SetObject(PyExc_SystemExit, exit_code); return NULL; } Christian From hypercaffeinatedbiped at gmail.com Mon Sep 29 16:07:16 2008 From: hypercaffeinatedbiped at gmail.com (HCB) Date: Mon, 29 Sep 2008 13:07:16 -0700 (PDT) Subject: One class per file? References: <87od27rssp.fsf@benfinney.id.au> Message-ID: <076ab8f2-551d-478f-b31a-df0be47987da@y71g2000hsa.googlegroups.com> To answer Ben Finney's questions: The "Put one class in one file" statement is made in "Code Complete 2" page 771. HCB From zasaconsulting at gmail.com Fri Sep 19 04:45:10 2008 From: zasaconsulting at gmail.com (Alex Ziller) Date: Fri, 19 Sep 2008 10:45:10 +0200 Subject: improving a huge double-for cycle In-Reply-To: <48D27982.90503@wildenhain.de> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D27755.8060208@wildenhain.de> <48D27982.90503@wildenhain.de> Message-ID: Thank you all for replying me! special thanks to Tino. Your code rocks!!!!!!!!! I got all the double nodes in couple of seconds!!!!!!!! and in a useful output with the coupled nodes pro line.. cheers from Germany! 2008/9/18 Tino Wildenhain > Tino Wildenhain wrote: > >> Hi, >> >> Alexzive wrote: >> >>> Hello there :) , >>> >>> I am a python newbie and need to run following code for a task in an >>> external simulation programm called "Abaqus" which makes use of python >>> to access the mesh (ensamble of nodes with xy coordinates) of a >>> certain geometrical model. >>> >>> [IN is the starting input containing the nodes to be check, there are >>> some double nodes with the same x and y coordinates which need to be >>> removed. SN is the output containing such double nodes] >>> >>> Code: Select all >>> for i in range(len(IN)): #scan all elements of the list IN >>> for j in range(len(IN)): >>> if i <> j: >>> if IN[i].coordinates[0] == IN[j].coordinates[0]: >>> if IN[i].coordinates[1] == IN[j].coordinates[1]: >>> SN.append(IN[i].label) >>> >>> >> data=dict() >> for item in IN: # (what a name! ;) >> data.setdefault(item.coordinates,[]).append(item) >> # provided coordinates is a tuple >> >> dupes=[items for items in data.values() if len(items)>1] >> >> should give you a resulting list of lists of elements in IN >> which occur more then once per coordinates. >> You can then decide which ones to remove or whatever. >> >> If you want to have the output only containing nodes to remove, >> the following would work: >> >> dupes=[] >> for items in data.values(): >> dupes.extend(items[1:]) >> >> > I did a small test - I don't know if it reflects > the actual problem good enough but it seems it > all runs below 1 sec each so this would be very > fast compared to 15h: > > >>> import random > >>> class Node(object): > ... def __init__(self,x,y): > ... self.coordinates=(x,y) > > >>> IN=[Node(random.randint(0,100),random.randint(0,100)) for i in > xrange(100000)] > > >>> data=dict() > >>> for item in IN: data.setdefault(item.coordinates,[]).append(item) > ... > > >>> dupes=[items for items in data.values() if len(items)>1] > >>> len(dupes) > 10190 > >>> > > Cheers > Tino > -- Ing. Alessandro Zivelonghi Ziller http://www.tecnopolis.eu +49 176 83112471 skype: alexzive "Energy and persistence conquer all things." Benjamin Franklin (1706 - 1790) -------------- next part -------------- An HTML attachment was scrubbed... URL: From zak.mc.kraken at libero.it Sat Sep 20 07:03:01 2008 From: zak.mc.kraken at libero.it (Vito De Tullio) Date: Sat, 20 Sep 2008 13:03:01 +0200 Subject: how can i check whether a variable is iterable in my code? References: Message-ID: satoru wrote: > hi, all > i want to check if a variable is iterable like a list, how can i > implement this? untested def is_iterable(param): try: iter(param) except TypeError: return False else: return True -- By ZeD From d3vvnull at gmail.com Tue Sep 23 22:22:08 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Tue, 23 Sep 2008 21:22:08 -0500 Subject: Twisted vs. CherryPy vs. ??? for light-weight web servers Message-ID: <170543c70809231922m23531eb9i1f7fdead10bb1e0e@mail.gmail.com> Is there any consensus on what the best lightweight web-server is? Or rather would Twisted be a better choice to choose as a framework that allows me to serve html or xml data for light webservices. Or is CherryPy just as good? -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From uzmanajmal at gmail.com Thu Sep 11 04:32:39 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Thu, 11 Sep 2008 08:32:39 +0000 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Thanks for ur help. But now i am getting an error xmlrpclib.ProtocolError: Here is my code at http://privatepaste.com/d81Kut9AFj Any idea what wrong am i doing? On Thu, Sep 11, 2008 at 7:18 AM, Fredrik Lundh wrote: > Usman Ajmal wrote: > > And i also fount that a typical system.auth call will look like: >> >> POST /xmlrpc/clarens_server.py HTTP/1.0 >> Host: localhost >> User-Agent: xmlrpclib.py/0.9.9 (by www.pythonware.com < >> http://www.pythonware.com>) >> >> Content-Type: text/xml >> Content-Length: 105 >> AUTHORIZATION: Basic MkhVTm9VazYxbXArVEZLS0dCY2tIRlA3bjVzPQo6RnJvbSBi >> >> >> system.auth >> >> >> >> >> >> >> Problem is that i don't know how do i generate above xml system.auth call. >> Can anyone please tell me how do call a function, setting the header of the >> call too? >> > > you need to plugin a custom transport. see this page for an example: > > http://www.python.org/doc/lib/xmlrpc-client-example.html > > in your case, it should be sufficient to override send_request, e.g. > (untested): > > class SecureTransport(xmlrpclib.Transport): > > def set_authorization(self, ustring, text_ucert): > self.authoriation = encodestring( > "%s:%s" % (ustring,text_ucert) > ) > > def send_request(self, connection, handler, request_body): > connection.putrequest("POST", handler) > connection.putheader("Authorization", > "Basic %s" % self.authorization > ) > > and instantiate the transport by doing > > t = SecureTransport() > t.set_authorization(ustring, text_ucert) > > before passing to the server proxy. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aioe.org at technicalbloke.com Fri Sep 19 10:39:05 2008 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 19 Sep 2008 10:39:05 -0400 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Message-ID: erikcw wrote: > Hi, > > I have a cgi script where users are uploading large files for > processing. I want to launch a subprocess to process the file so the > user doesn't have to wait for the page to load. > > What is the correct way to launch subprocess without waiting for the > result to return? > > Thanks! Whoops, that was PHP! Imeant... os.system(yourcommandline+" &") ;-) Roger From michael at stroeder.com Sun Sep 28 17:08:30 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sun, 28 Sep 2008 23:08:30 +0200 Subject: generate random digits with length of 5 In-Reply-To: References: Message-ID: Gary M. Josack wrote: > Aaron "Castironpi" Brady wrote: >> On Sep 28, 2:59 pm, sotirac wrote: >> >>> Wondering if there is a better way to generate string of numbers with >>> a length of 5 which also can have a 0 in the front of the number. >>> >>>
>>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
>>> elements
>>>  code = 'this is a string' + str(random_number[0]) +
>>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
>>> + str(random_number[4])
>>> 
>>> >> >> '%05i'%random.randint(0,99999) >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > This produces numbers other than 5 digit numbers. making the start > number 10000 should be fine. Why do you think it's wrong? >>> import random >>> '%05i'%random.randint(0,99999) '09449' >>> IMO it's exactly what was required. Ciao, Michael. From mensanator at aol.com Wed Sep 3 19:20:39 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 3 Sep 2008 16:20:39 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> On Sep 3, 2:18?pm, Laszlo Nagy wrote: > bearophileH... at lycos.com wrote: > > Empty Python lists [] don't know the type of the items it will > > contain, so this sounds strange: > > >>>> sum([]) > > > 0 > > > Because that [] may be an empty sequence of someobject: > > You are right in that sum could be used to sum arbitrary objects. > However, in 99.99% of the cases, you will be summing numerical values. > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > is very logical to return zero for empty sequences. No it isn't. Nothing is not 0, check with MS-Access, for instance: Null + 1 returns Null. Any arithmetic expression involving a Null evaluates to Null. Adding something to an unknown returns an unknown, as it should. It is a logical fallacy to equate unknown with 0. For example, the water table elevation in ft above Mean Sea Level is WTE = TopOfCasing - DepthToWater. TopOfCasing is usually known and constant (until resurveyed). But DepthToWater may or may not exist for a given event (well may be covered with fire ants, for example). Now, if you equate Null with 0, then the WTE calculation says the water table elevation is flush with the top of the well, falsely implying that the site is underwater. And, since this particular site is on the Mississippi River, it sometimes IS underwater, but this is NEVER determined by water table elevations, which, due to the CORRECT treatment of Nulls by Access, never returns FALSE calculations. >>> sum([]) 0 is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It should return None or throw an exception like sum([None,1]) does. > > Same way, if we would have a prod() function, it should return one for > empty sequences because X*1 = X. The neutral element for this operation > is one. > > Of course this is not good for summing other types of objects. But how > clumsy would it be to use > > sum( L +[0] ) > > or > > if L: > value = sum(L) > else: > value = 0 > > instead of sum(L). > > Once again, this is what sum() is used for in most cases, so this > behavior is the "expected" one. > > Another argument to convince you: the sum() function in SQL for empty > row sets returns zero in most relational databases. > > But of course it could have been implemented in a different way... I > believe that there have been excessive discussions about this decision, > and the current implementation is very good, if not the best. > > Best, > > Laszlo From martin at v.loewis.de Thu Sep 18 18:55:23 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 19 Sep 2008 00:55:23 +0200 Subject: Automated Build System ? In-Reply-To: <3468bd3f-d6a3-477a-8537-48d67522700a@j22g2000hsf.googlegroups.com> References: <3468bd3f-d6a3-477a-8537-48d67522700a@j22g2000hsf.googlegroups.com> Message-ID: <48D2DC5B.80002@v.loewis.de> > I'm working on a python Package which includes some extension modules > and unit tests. I want to automate some tasks like "build extsion > module, then copy xxx.pyd to folder yyy and run all unit tests from > folder zzzz". > > I used google but found no hints to existing solutions. > Can anybody help me ? I recommend to use distutils. It can already build extension modules and install them. For testing, you would need to supply your own test command. Alternatively, try setuptools - there seems to be a test command already included. Regards, Martin From ppearson at nowhere.invalid Fri Sep 5 11:03:29 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 5 Sep 2008 15:03:29 GMT Subject: Extract Information from Tables in html References: <37b964200809050729j6290af48u8efbbc1a5e0b6bd1@mail.gmail.com> Message-ID: <6id021Fq216kU1@mid.individual.net> On Fri, 5 Sep 2008 11:35:14 -0300, Walter Cruz wrote: > On Fri, Sep 5, 2008 at 11:29 AM, Jackie Wang wrote: >> Here is a html code: >> >> >> >> Premier Community Bank of Southwest Florida >>
>> Fort Myers, FL >> >> >> >> My question is how I can extract the strings and get the results: >> Premier Community Bank of Southwest Florida; Fort Myers, FL > > Use BeautifulSoup. I agree, BeautifulSoup is wonderful. Here are snippets of code that I recently used to locate (in each of many HTML files) the table that contained a particular heading: from BeautifulSoup import BeautifulSoup import re ... inlines = ifd.readlines() soup = BeautifulSoup( " ".join( inlines ) ) x = soup.findAll( text = re.compile( "Technical Requirements - General" ) ) x = x[0].parent while x.name != "table": x = x.parent tr_list = x.findAll( "tr", recursive = False ) print "Table has %d rows." % len( tr_list ) -- To email me, substitute nowhere->spamcop, invalid->net. From jarausch at skynet.be Fri Sep 5 10:38:41 2008 From: jarausch at skynet.be (Helmut Jarausch) Date: Fri, 05 Sep 2008 16:38:41 +0200 Subject: hashing an array - howto Message-ID: <48c14472$0$2864$ba620e4c@news.skynet.be> Hi, I need to hash arrays of integers (from the hash module). So, I have to derive from array and supply a __hash__ method. But how to hash an array (of fixed length, say 25)? What I need is a function which maps a tuple of 25 integers into 1 integer with good hashing properties. Does anybody know such a thing? Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From justin.kuto at gmail.com Tue Sep 30 17:09:42 2008 From: justin.kuto at gmail.com (afrogazer) Date: Tue, 30 Sep 2008 14:09:42 -0700 (PDT) Subject: Matplotlib Polar Plot Clockwise Message-ID: <0b8e5002-8689-48c4-8d2b-b6cbf5819413@m73g2000hsh.googlegroups.com> I have been playing with this for a couple days now and there doesn't seem to be any easy way to fix this except manipulating the data, which is undesirable. It would be some much better if there was a setting in matplotlibrc to choose to plot clockwise or counter- clockwise and the position on 0° I am now trying the transformations, but it looks just too complicated. Anybody ever ran into this. Thanks, Justin. From paul at boddie.org.uk Tue Sep 30 08:31:19 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 30 Sep 2008 05:31:19 -0700 (PDT) Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> Message-ID: On 30 Sep, 14:19, Ben Finney wrote: > > This is where the useful "your freedom to swing your fist ends at the > tip of the other man's nose" applies: As soon as the act you wish to > perform is restricting the freedom of another, you're not > contemplating an act of freedom, but an act of power over another. > Freedoms should be protected, but only within the limits imposed by > the freedoms of others. This is a very good explanation of what copyleft is all about. I suppose one could regard copyleft as a means to preserve the "maximal common freedom" in a system - if anyone else were to acquire more power or privilege to do something, that would diminish the freedoms of others. Paul From fredrik at pythonware.com Sat Sep 20 05:05:58 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 11:05:58 +0200 Subject: The Python computer language In-Reply-To: <7d3f9f43-8094-4bd0-980c-eb721b5a5051@o40g2000prn.googlegroups.com> References: <7d3f9f43-8094-4bd0-980c-eb721b5a5051@o40g2000prn.googlegroups.com> Message-ID: ROSEEE wrote: > http://pthoncomputerlanguage.blogspot.com report here: http://tinyurl.com/blogspot-spam From lee.walczak at gmail.com Tue Sep 9 16:05:31 2008 From: lee.walczak at gmail.com (lee.walczak at gmail.com) Date: Tue, 9 Sep 2008 13:05:31 -0700 (PDT) Subject: Wx Python - Code Structure & Event Handling Message-ID: Hi, I have just started writing a GUI using wxpython after finding a limitation using Tkinter. I have read most tutorials on wxpython and slowly becoming accustomed considering I started with the latter GUI tool first! I must quote first that I am a novice user of python so the issue(s) I have may seem very obvious but please be patient with me! I have noticed that all the wxpython references I used for creating my application(s) "cram" all the code in the frame subclass. This is fine when you consider small applications but what about when they grow into very complex applications? This creates my first question : Where is it possible to find information on wxpython code practise/ structure when considering complex larger Gui's? Without any reference I decided to attempt my owm method by breaking up the top level panels in my frame as individiual class objects. and then construct the widgets for the panels within the respective classes. This led to my second problem, how do I use and event in one Panel to cause an effect in the other Panel ? For example, if I have button in one Panel and wish to change the text of a label in the other Panel, what is the best way to do this? Should I break the code into modules instead? Of course, you may explain that the way I have approached this is completely wrong, if so please tell me, I really want to get the basic structure right before I start making the code more complex. I look forward to your help ------------------------------------------------------------------------------------------------------------------------------------- I have listed some code below to help explain what concept I wish to achieve, import wx class Frame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Application",size=(400,400)) Panel1 = wx.Panel(self, -1,size=(200,200)) Panel2 = wx.Panel(self, -1,size=(200,200)) Sizer = wx.FlexGridSizer(2,2,5,5) Sizer.Add(Panel1) Sizer.Add(Panel2) self.SetSizerAndFit(Sizer) Util1 = Utils1(Panel1) Util2 = Utils2(Panel2) class Utils1(): def __init__(self, Panel): button = wx.Button(Panel,-1, "Button 1") Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) self.Label = wx.StaticText(Panel,-1, "Handler to me", name="Lab1") Sizer = wx.BoxSizer(wx.VERTICAL) Sizer.Add(button) Sizer.Add(self.Label) Panel.SetSizerAndFit(Sizer) def OnClick(self, Evt): self.Label.SetLabel("you changed me") class Utils2(): def __init__(self, Panel): self.button = wx.Button(Panel,-1, "Button 2") Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) def OnClick(self, Evt): """ what is the easiest & accepted Method of changing the text in a different class instance?""" pass #???.SetLabel("you changed me") app = wx.PySimpleApp() frame = Frame() frame.Show() app.MainLoop() From bearophileHUGS at lycos.com Fri Sep 12 12:05:33 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Sep 2008 09:05:33 -0700 (PDT) Subject: Checking the boolean value of a collection References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> Message-ID: <010b3cf0-ca62-401b-bb71-2902aa0c35b6@x35g2000hsb.googlegroups.com> Marco Bizzarri: > >>> any([x for x in [1, 2, 3]]) > > I mean, I'm afraid I can't use an expression like that without > building a list... not at least in python2.3 Note that you don't need a list comp there: >>> any([x for x in [1, 2, 3]]) True >>> any([1, 2, 3]) True so this may suffice: any(self.findActiveOutgoingRegistrationInstancesPlusSomeOtherThings()) Bye, bearophile From peter.anderson at internode.on.net Tue Sep 16 01:03:51 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Tue, 16 Sep 2008 15:03:51 +1000 Subject: append on lists In-Reply-To: References: Message-ID: <48CF3E37.4090702@internode.on.net> "/... I don't think you've thought this one through, really./" Is this kind of response really necessary? The original post was asking (from his perspective at least) a legitimate question. To a Python expert it may be a "silly question" but replying in such a fatuous way puts off those "less gifted" from using this excellent reference source. Nobody enjoys being spoken to like this. We ought to try and be a little kinder to others on the list, don't you think? :-) Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From steve at holdenweb.com Fri Sep 19 03:56:25 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Sep 2008 03:56:25 -0400 Subject: SMTP via GMAIL In-Reply-To: <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> Message-ID: Grant Edwards wrote: > On 2008-09-18, Lawrence D'Oliveiro wrote: >> In message >> <973f75d4-90f5-4930-9107-15fc8651196d at v16g2000prc.googlegroups.com>, sui >> wrote: >> >>> Traceback (most recent call last): >>> File "mail5.py", line 21, in >>> session = smtplib.SMTP(SMTPserver,port) >>> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ >>> (code, msg) = self.connect(host, port) >>> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect >>> self.sock.connect(sa) >>> File "", line 1, in connect >>> then conncetion time out..... >> Could it be your ISP is blocking outgoing connections to port >> 25? > > gmail doesn't accept mail via SMTP on port 25. > I was going to say that's boloney until I checked my settings - it's a year or more since I set gmail up with Thunderbird. smtp.gmail.com accepts TLS connections on port 587. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Thu Sep 11 13:20:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 10:20:41 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> On Sep 11, 2:40?am, Steven D'Aprano wrote: > On Wed, 10 Sep 2008 11:59:35 -0700, Aaron \"Castironpi\" Brady wrote: > > On Sep 10, 5:24?am, Steven D'Aprano > > wrote: > >> On Wed, 10 Sep 2008 09:26:20 +0200, Fredrik Lundh wrote: > >> > Steven D'Aprano wrote: > > >> >> You've created a solution to a problem which (probably) only affects > >> >> a very small number of people, at least judging by your use-cases. > >> >> Who has a 4GB XML file > > >> > Getting 4GB XML files from, say, logging processes or databases that > >> > can render their output as XML is not that uncommon. ?They're usually > >> > record-oriented, and are intended to be processed as streams. ?And > >> > given the right tools, doing that is no harder than doing the same to > >> > a 4GB text file. > > >> Fair enough, that's a good point. > > >> But would you expect random access to a 4GB XML file? If I've > >> understood what Castironpi is trying for, his primary use case was for > >> people wanting exactly that. > > >> -- > >> Steven > > > Steven, > > > Are you claiming that sequential storage is sufficient for small amounts > > of data, and relational db.s are necessary for large amounts? > > I'm no longer *claiming* anything, I'm *asking* whether random access to > a 4GB XML file is something that is credible or useful. It is my > understanding that XML is particularly ill-suited to random access once > the amount of data is too large to fit in RAM. > > I'm interested in what Fredrik has to say about this, as he's the author > of ElementTree. > > -- > Steven XML is the wrong word for the example I was thinking of (as was already pointed out in another thread). XML is by definition sequential. The use case pertained to a generic element hierarchy; think of 4GB of hierarchical data. From mnordhoff at mattnordhoff.com Thu Sep 25 00:12:07 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 25 Sep 2008 04:12:07 +0000 Subject: How to parse a string completely into a list In-Reply-To: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> References: <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> Message-ID: <48DB0F97.1020907@mattnordhoff.com> john.ford at colorado.edu wrote: > On Sep 24, 9:44 pm, "Chris Rebert" wrote: >> On Wed, Sep 24, 2008 at 8:30 PM, wrote: >>> I want to take a long alpha-numeric string with \n and white-space and >>> place ALL elements of the string (even individual parts of a long >>> white-space) into separate list elements. The most common way I've >>> seen this performed is with the split() function, however I don't >>> believe that it has the power to do what I am looking for. >>> Any suggestions? >>> thanks >> Could you please define exactly what you mean by "elements" of a string? >> >> If you mean characters, then just use list():>>> list(" \n \t abc") >> >> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] >> >> Regards, >> Chris > > Worked like a charm. > kudos! Why do you need to convert it to a list? Strings are sequences, so you can do things like slice them or iterate through them by character: >>> for character in "foo": ... print character ... f o o >>> -- From mdipierro at cs.depaul.edu Tue Sep 23 09:08:26 2008 From: mdipierro at cs.depaul.edu (mdipierro) Date: Tue, 23 Sep 2008 06:08:26 -0700 (PDT) Subject: New Web2Py framework SLASHES development time... References: <8bc01858-77f9-41bc-a907-4b9670f40213@b1g2000hsg.googlegroups.com> Message-ID: <3dee770f-41b2-47ff-81f9-3f07efd8300c@s50g2000hsb.googlegroups.com> Hi Paul, yes, the model designer is the one from Ondras. We modified it so that it generates DAL (Database Abstraction Layer) code instead of SQL and it is a work in progress. Technically it is not pat of web2py and in fact it is not distributed with it. It is just one of the many web2py apps. You can find more on http://mdp.cti.depaul.edu/appliances Massimo On Sep 22, 5:48 am, Paul Boddie wrote: > On 22 Sep, 04:49, Steve Shephed wrote: > > > http://www.web2py.comWeb2Py- Python Framework is the newest > > kid on the block for Python frameworks. > > I'm not going to dwell on the merits of web2py, I'm afraid... > > > It has a lot of features that simply are not there in other > > frameworks. Even Ruby!. You can design database models graphically > > online. > > I had a closer look at the model designer, and the client-side magic > seems to originate from this project: > > http://ondras.zarovi.cz/sql/ > > It looks quite fancy, especially since it all seems to be happening in > the browser. Thanks for indirectly bringing this to our attention! ;-) > > Paul From fredrik at pythonware.com Sat Sep 13 10:11:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 16:11:15 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > class FolderInUse: > > def true_for(self, archivefolder): > return any([instance.forbid_to_close(archivefolder) for instance in > self.core.active_outgoing_registration_instances()]) > > Is this any better? The true_for name does not satisfy me a lot... well, "true_for" is indeed pretty inscrutable, but I'm not sure that would be the first thing I'd complain about in that verbose mess... (when you pick method names, keep in mind that the reader will see the context, the instance, and the arguments at the same time as they see the name. there's no need to use complete sentences; pick short short descriptive names instead.) From goldnery at gmail.com Thu Sep 4 13:00:24 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 4 Sep 2008 10:00:24 -0700 (PDT) Subject: Right to left language support Message-ID: <191393da-7dc3-4dd2-bf63-43ed5e1d74c1@t1g2000pra.googlegroups.com> Most of you probably speaks Latin language, so you wont understand the problem. when I try to write Hebrew in my statictext the last punctuation marks get mixed up. does someone have a solution for this? this is the code : text=wx.StaticText(panel3, -1, Hebrew_string, style=wx.ALIGN_RIGHT) thanks! From semanticist at gmail.com Mon Sep 22 01:30:36 2008 From: semanticist at gmail.com (Miles) Date: Mon, 22 Sep 2008 01:30:36 -0400 Subject: Why are "broken iterators" broken? In-Reply-To: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: On Sun, Sep 21, 2008 at 11:13 AM, Steven D'Aprano wrote: > According to the Python docs, once an iterator raises StopIteration, it > should continue to raise StopIteration forever. Iterators that fail to > behave in this fashion are deemed to be "broken": > > http://docs.python.org/lib/typeiter.html > > I don't understand the reasoning behind this. As I understand it, an > iterator is something like a stream. There's no constraint that once a > stream is empty it must remain empty forever. > > Can somebody explain why "broken iterators" are broken? It's not a terribly onerous restriction. If you're iterating with a for-loop, you can make the iterable return a new iterator object when the old one is exhausted, and if the intent is for the next()-method to be called directly, you don't have to conform to the iterator protocol. Strictly speaking, file objects are broken iterators: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:16) >>> f = open('foo') >>> it = iter(f) >>> it.next() 'hi\n' >>> it.next() 'bye\n' >>> it.next() Traceback (most recent call last): File "", line 1, in StopIteration >>> f.seek(0) >>> it.next() 'hi\n' -Miles From sargshep at gmail.com Sun Sep 21 22:49:24 2008 From: sargshep at gmail.com (Steve Shephed) Date: Sun, 21 Sep 2008 19:49:24 -0700 (PDT) Subject: New Web2Py framework SLASHES development time... Message-ID: http://www.web2py.com Web2Py - Python Framework is the newest kid on the block for Python frameworks. It has a lot of features that simply are not there in other frameworks. Even Ruby!. You can design database models graphically online. The templating language is pure python and there are no problems with indenting. The models are auto-migrating which allows easy updating of your database schema's. Parent-child and Super-Sub Set type models are completely supported. Uses an advanced MVC pattern. At least 10 free applications ready to download and use in your own developments. Can be run from a USB stick. ZERO installation just click on the exe and away you go with web server and complete graphical admin interface. PLUS it will work on Google App Engine (your still constrained by the Google Storage Limitations but you don't have to change any database model code at all). AND Complete International Support (with a graphical admin interface to add different languages)...there is more but just take a visit... From kyosohma at gmail.com Wed Sep 10 17:34:10 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 10 Sep 2008 14:34:10 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> <4pcgc495c6ml60a09fh3gc8e6t1akmlmin@4ax.com> Message-ID: On Sep 10, 3:53?pm, James A. Donald wrote: > James A. Donald > > > > Horrible installs are a chronic problem of GUI programs driven by > > > interpreted languages ?Installing visual basic programs that worked on > > > one Windows machine to work on a very slightly different windows > > > machine was also a nightmare. > > > > I have not attempted to create installable wxPython windows, but > > > generally, "run anywhere" will bite you. ?Still looking for a good > > > solution to "run anywhere". > > Mike Driscoll > > > I haven't had much trouble getting wxPython applications to run in > > Windows XP and Ubuntu Hardy Heron. > > Did you attempt to create proper install packages that show up in the > Linux package managers, and the windows add/remove programs tool? > I used Inno Setup which creates an uninstaller, however I am not seeing it in my Windows Add/Remove. Odd. However, you can uninstall it from the Start menu entry and it works. Currently, I am running the application from source in Linux. But I plan to try cx_freeze or similar sooner or later. I haven't had need to distribute it since my apps are for internal use so far. Mike From rocky at panix.com Fri Sep 5 15:13:49 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 05 Sep 2008 15:13:49 -0400 Subject: pdb bug and questions References: Message-ID: Stef Mientki writes: > hello, > > I'm trying to embed a debugger into an editor. > I'm only interested in high level debugging. > The first question is what debugger is the best for my purpose ? > (pdb, pydb, rpdb2, smart debugger, extended debugger ? > > Second question, in none of the above debuggers (except rpdb2), > I can find a "break now", > so it seems impossible to me to detect unlimited while loops ? I am not sure what you mean by "break now". pdb and pydb allow direct calls from a program to the debugger via set_trace (which in pydb is deprecated in favor of I think the more descriptive name: debugger) But I suspect this is not what you mean to "detect unlimited while loops"; pydb also has gdb-style signal handling that allows for entry into the debugger when the debugged python process receives a particular signal. "info handle" lists all of the interrupts and what action is to be taken on each. See http://bashdb.sourceforge.net/pydb/pydb/lib/node38.html However I believe that signals are only handled by the main thread; so if that's blocked, the python process won't see the signal. > > For the moment I started with pdb, because most of the debuggers seems > to be an extension on pdb. > When I launch the debugger ( winXP, Python 2.5) from with my editor > python -u -m pdb D:\\Data\\test_IDE.py > I get this error > IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') > NOTICE 1 backslash ----------------------------------^ > > If I launch the debugger with > python -u -m pdb D:/Data/test_IDE.py > It runs fine. > > This looks like a bug to me. > What's the best way to report these kind of bugs ? winpdb, pydb and pdb (part of Python) all have Sourceforge projects which have bug trackers. For pdb, in the past people includng myself, have reported features, patches and bugs in the Python tracker; eventually it gets handled. (Eventually in my case means a year or so.) But if my information is incorrect or out of date, no doubt someone will correct me. As mentioned in the last paragraph, pydb also is a Sourceforge project (part of bashdb) which has a tracker for bug reporting. Using the bug tracker I think is better than discussing pydb bugs in c.l.p. By extension, I assume the same is also true for the other debuggers. Finally, I think rpdb2 is part of the winpdb project on Sourceforge and again has a bug tracker. My sense is that Nir Aides is very good about handling bugs reported in winpdb/rpdb. > > Although I mostly use os.path.join to be OS independent, > these kind of bugs give me the impression, > that I can better do the join myself and always use forward slashes. > Is this a valid conclusion ? > > thanks, > Stef Mientki From half.italian at gmail.com Wed Sep 3 22:41:20 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 3 Sep 2008 19:41:20 -0700 (PDT) Subject: Access to Windows "Add/Remove Programs"? References: Message-ID: On Sep 3, 7:13?pm, "Gabriel Genellina" wrote: > En Wed, 03 Sep 2008 21:51:59 -0300, Sean DiZazzo ? > escribi : > > > I'm trying to find a way to get a list of all the installed programs > > on a Windows box via Python. ?I thought of a few hacks that might > > partially work, and then thought about "Add/Remove Programs" ?Seems > > like the right way to go. ?I looked over the pywin32 docs a bit, but > > nothing slapped me in the face. > > > Is there any reliable way to get at that info? > > You may enumerate the entries under this registry key: > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall > > -- > Gabriel Genellina Thank both of you. Perfect! ~Sean From erexsha at gmail.com Tue Sep 23 06:51:37 2008 From: erexsha at gmail.com (Arash Arfaee) Date: Tue, 23 Sep 2008 03:51:37 -0700 Subject: adding in-place operator to Python Message-ID: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> Hi All, Is there anyway to add new in-place operator to Python? Or is there any way to redefine internal in-place operators? Thanks. Cheers, Arash -------------- next part -------------- An HTML attachment was scrubbed... URL: From prologic at shortcircuit.net.au Mon Sep 8 17:48:35 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 9 Sep 2008 07:48:35 +1000 Subject: The difference between __XX__ and XX method In-Reply-To: References: Message-ID: Hi, This is convention only and typically used to denote that a particular class attribute is "private". Though note, there is really no such thing in Python. cheers James On Tue, Sep 9, 2008 at 7:31 AM, AON LAZIO wrote: > Hi, Pythoners. > I would like to know that in some class, it uses __XX__ but in some it > uses only XX > for example, > > class Test: > def __som__(self): > ... > def som(self): > ... > What does "__XX__" make the method different from XX? > Thanks in advance > Aonlazio > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From bmihelac at gmail.com Tue Sep 9 10:16:45 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Tue, 9 Sep 2008 07:16:45 -0700 (PDT) Subject: Python and M2Crypto question References: <12b278d2-9f78-4fc9-a4f2-7d22c543aeb9@d1g2000hsg.googlegroups.com> <643253ee-c8a7-4ccc-bac2-432ac382e4c3@v39g2000pro.googlegroups.com> Message-ID: <9c83d42a-47ba-4e00-88aa-7894b2b70ce5@s50g2000hsb.googlegroups.com> Graham, thanks, I will try with that. On Sep 8, 1:02?am, Graham Dumpleton wrote: > On Sep 7, 11:07?pm, Bojan Mihelac wrote: > > > Hi all! > > > I am trying to install M2Crypto to work on OSX10.5 apache > > (mod_python). Error I receive: > > > Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5- > > macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image > > found. ?Did find: > > ? ? ? ? /Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg- > > tmp/M2Crypto/__m2crypto.so: no matching architecture in universal > > wrapper > > > I guess that have to do something with x64 architecture but I am > > stucked and not able to find a way and to make this work. M2Crypto lib > > works good stand alone. > > See: > > ?http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX#Missing_Co... > > This is mod_wsgi documentation, but same issue applies to mod_python. > > Graham From mayariasxf at gmail.com Tue Sep 30 18:41:51 2008 From: mayariasxf at gmail.com (mayariasxf at gmail.com) Date: Tue, 30 Sep 2008 15:41:51 -0700 (PDT) Subject: Visit this sites please Message-ID: <284dc317-466f-41d2-8e49-b9e1de1ae5b4@a70g2000hsh.googlegroups.com> http://forums.vogue.com.au/member.php?u=91686 tube8 http://forums.vogue.com.au/member.php?u=91688 redtube http://forums.vogue.com.au/member.php?u=91689 pornhub http://forums.vogue.com.au/member.php?u=91690 yobt http://www.dynamicdrive.com/forums/member.php?u=33924 tube8 http://www.dynamicdrive.com/forums/member.php?u=33925 redtube Visit this sites please From steven at REMOVE.THIS.cybersource.com.au Tue Sep 9 00:02:24 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Sep 2008 04:02:24 GMT Subject: a11y & python References: Message-ID: On Mon, 08 Sep 2008 20:41:55 -0700, jonathon wrote: > All: > > A year or so ago, I read a tutorial on writing self-voicing apps using > python. It also covered other a11y issues. However, I didn't bookmark > it, and it doesn't show up in the first 1000 hits on the Google search I > did. While Google is very good, it's not perfect, nor is it the only search engine out there. Perhaps try some of the others, like Yahoo. > Can somebody point me to either that, or any other tutorials on > programming a11y into python. I'm afraid I'd be limited to googling. I'm guessing that you'd probably have more success asking on ally mailing lists (if any) for Python help than asking Python lists for ally help. But good luck. Have you checked out this? http://live.gnome.org/Orca -- Steven From schaefer.mp at gmail.com Tue Sep 16 04:26:14 2008 From: schaefer.mp at gmail.com (MatthewS) Date: Tue, 16 Sep 2008 01:26:14 -0700 (PDT) Subject: Is 'x' an instance of a new-style class? Message-ID: I've seen the question raised several times here, but apparently never answered. Since PyInstance_Check returns False for new-style class instances, is there a standard procedure for testing this using the C- Api? I would greatly appreciate some help with this. /Matthew From george.sakkis at gmail.com Thu Sep 18 11:52:11 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 18 Sep 2008 08:52:11 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> Message-ID: <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> On Sep 18, 11:43 am, Gerard flanagan wrote: > Simon Mullis wrote: > > Hi, > > > Let's say I have an arbitrary list of minor software versions of an > > imaginary software product: > > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > > I'd like to create a dict with major_version : count. > > > (So, in this case: > > > dict_of_counts = { "1.1" : "1", > > "1.2" : "2", > > "1.3" : "2" } > > [...] > data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > from itertools import groupby > > datadict = \ > dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) > print datadict Note that this works correctly only if the versions are already sorted by major version. George From Lie.1296 at gmail.com Sun Sep 28 07:04:10 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 04:04:10 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <00ef3c23$0$20666$c3e8da3@news.astraweb.com> Message-ID: <96125692-af95-4429-bf69-03aa5c0f5fa9@k36g2000pri.googlegroups.com> On Sep 28, 4:21?pm, est wrote: > On Sep 28, 4:38?pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Sat, 27 Sep 2008 22:37:09 -0700, est wrote: > > >>>> str(u'\ue863') > > > Traceback (most recent call last): > > > ? File "", line 1, in > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > > > position 0 > > > : ordinal not in range(128) > > > > FAIL. > > > What result did you expect? > > > [...] > > > > The problem is, why the f**k set ASCII encoding to range(128) ???????? > > > while str() is internally byte array it should be handled in range(256) > > > !!!!!!!!!! > > > To quote Terry Pratchett: > > > ? ? "What sort of person," said Salzella patiently, "sits down and > > ? ? *writes* a maniacal laugh? And all those exclamation marks, you > > ? ? notice? Five? A sure sign of someone who wears his underpants > > ? ? on his head." -- (Terry Pratchett, Maskerade) > > > In any case, even if the ASCII encoding used all 256 possible bytes, you > > still have a problem. Your unicode string is a single character with > > ordinal value 59491: > > > >>> ord(u'\ue863') > > > 59491 > > > You can't fit 59491 (or more) characters into 256, so obviously some > > unicode chars aren't going to fit into ASCII without some sort of > > encoding. You show that yourself: > > > u'\ue863'.encode('mbcs') ?# Windows only > > > But of course 'mbcs' is only one possible encoding. There are others. > > Python refuses to guess which encoding you want. Here's another: > > > u'\ue863'.encode('utf-8') > > > -- > > Steven > > OK, I am tired of arguing these things since python 3.0 fixed it > somehow. I'm against calling python 3.0 fixed it, python 3.0's default encoding is utf-8/Unicode, and that is why your problem magically disappears. > Can anyone tell me how to customize a default encoding, let's say > 'ansi' which handles range(256) ? Python used to have sys.setdefaultencoding, but that feature was an accident. sys.setdefaultencoding was intended to be used for testing purpose when the developers haven't decided what to use as default encoding (what use is default when you can change it). sys.setdefaultencoding has been removed, programmers should encode characters manually if they want to use something other than the default encoding (ASCII). From python at rgbaz.eu Wed Sep 10 14:06:21 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 20:06:21 +0200 Subject: md5 differences In-Reply-To: <8K6dnVeoxJTMlVXVnZ2dnUVZ_j6dnZ2d@posted.visi> References: <8K6dnVeoxJTMlVXVnZ2dnUVZ_j6dnZ2d@posted.visi> Message-ID: <84E12A2D-81B5-4750-B4DF-9129C97967D1@rgbaz.eu> On 10 sep 2008, at 19:48, Grant Edwards wrote: > On 2008-09-10, Wojtek Walczak wrote: >> On Wed, 10 Sep 2008 12:39:24 -0500, Grant Edwards wrote: >> >>>> The strange thing is that >>>>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >>>> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. >>> >>> Same here. >> >> I guess it will be the same for vast majority of us ;-) >> The question is why is it '90364ed45b452d43378629c20543a81d' >> for the OP? :-) > > The smart money is betting on "because the OP goofed when he > was cutting/pasting stuff from his terminal window into his > posting." > I did! I did! my bad... i cut some crap from the path to make it a bit easier to read but that was before the time i knew it was checksumming the actual path in stead of the contents of the file. So I figured it didn't matter... ;) From dmitry at athabascau.ca Fri Sep 26 19:30:52 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Fri, 26 Sep 2008 23:30:52 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> <4606d73b-522f-49ff-92f8-cfbbb0782306@i76g2000hsf.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: > That prohibits using a descriptor in the proxied classes, or at least > the proxied functions, since you break descriptor protocol and only > call __get__ once. Better to cache and get by name. It's only slower > by the normal amount, and technically saves space, strings vs. > instancemethod objects (except for really, really long function names). that is an interesting point since I didn't think about having descriptors in proxied classes. my reworked code clearly breaks when descriptors are thrown at it. It will break with methods in proxied objects that are implemented as objects too. Now I adjusted constructor a bit to account for that (I just can't figure out case when I'll be proxying descriptors unless they return function but than I don't see benefit in using descriptor for that, probably because I haven't used them much). class ProxyMethod(object): def __init__(self,ob_name,meth): self.ob_name=ob_name if not hasattr(meth,'im_class'): if hasattr(meth,'__call__'): self.meth=getattr(meth,'__call__') else: raise ValueError("Method should be either a class method or a callable class") else: self.meth=meth From inhahe at gmail.com Mon Sep 15 13:36:14 2008 From: inhahe at gmail.com (inhahe) Date: Mon, 15 Sep 2008 13:36:14 -0400 Subject: how to go around non-picklable object types? Message-ID: <91xzk.28830$rD2.16046@bignews4.bellsouth.net> There are certain types of objects that can't be pickled, like file objects. My question is how could I pickle a hierarchy while automatically skipping all such objects instead of just aborting the pickle when it comes across one. The only thing I can think of is to make my own classes that wrap file objects and so forth and use __getstate__ to leave out the underlying file, etc. objects, or to set __getstate__ for every class that holds an offending object type and filter such objects out of dictionaries when I pickle those. And I don't even have a list of common object types that would make it break. Is there a better way? thx.. From beema.shafreen at gmail.com Thu Sep 11 08:44:16 2008 From: beema.shafreen at gmail.com (Beema Shafreen) Date: Thu, 11 Sep 2008 18:14:16 +0530 Subject: function return Message-ID: hi all, I have a script using functions , I have a problem in returning the result. My script returns only one line , i donot know where the looping is giving problem, Can any one suggest, why this is happening and let me know how to return all the lines def get_ptm(): fh = open('file.txt', 'r') data_lis = [] for line in fh.readlines(): data = line.strip().split('\t') id = data[0].strip() gene_symbol = data[1].strip() ptms = data[8].strip() result = "%s\t%s\t%s" %(id,gene_symbol,ptms) return result fh.close() -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From knagakiran2 at gmail.com Sat Sep 6 03:14:48 2008 From: knagakiran2 at gmail.com (bobi) Date: Sat, 6 Sep 2008 00:14:48 -0700 (PDT) Subject: IT JOBS Message-ID: <2cf1c587-ee0d-48b7-b74e-6628f10648f5@s20g2000prd.googlegroups.com> Hello friends.., Welcome to the world of Information Technology,Enjoy the fragrance of Modern Life style&Make ur Living more comfortable than everbefore! Earn Millions of Dollars legal Income With Little Efforts In ur Spare time! Success usually comes to those who are too busy to be looking for it Visit & Apply for Online jobs.., http://www.onlinebizathome4all.blogspot.com
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Hi..Click me

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx From __peter__ at web.de Sat Sep 27 04:02:30 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 27 Sep 2008 10:02:30 +0200 Subject: Negative block sizes with file-like objects References: <00edd446$0$20666$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have a proxy class that wraps an arbitrary file-like object fp and > reads blocks of data from it. Is it safe to assume that fp.read(-1) will > read until EOF? I know that's true for file.read() and StringIO.read(), > but is it a reasonable assumption to make for arbitrary file-like objects? > > To put it in more concrete terms, I have a class like this: > > class C(object): > # Much simplified version. > def __init__(self, fp): > self.fp = fp > def read(self, size=-1): > return self.fp.read(size) > > > Should I re-write the read() method like this? > > def read(self, size=-1): > if size < 0: > return self.fp.read() > else: > return self.fp.read(size) Grepping through the python source shows that both -1 and None are used as the default size. # python2.5.2 >>> import tarfile >>> open("sample", "w").write("contents-of-sample") >>> t = tarfile.open("sample.tar", "w") >>> t.add("sample") >>> t.close() >>> t = tarfile.open("sample.tar") >>> t.extractfile("sample").read() 'contents-of-sample' >>> t.extractfile("sample").read(-1)[:50] 'contents-of-sample\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' So you may fare better with the rewrite. But even that may fail: http://docs.python.org/lib/bltin-file-objects.html#l2h-295 """ read( [size]) [...] If the size argument is negative or omitted, read all data until EOF is reached. [...] Also note that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ Peter From callen314 at gmail.com Mon Sep 22 21:20:28 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 22 Sep 2008 18:20:28 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> Message-ID: > Snce when are "users" ever involved > in programming problems or programming > languages ? > since the begining, the first users are programmers, users of your libraries. From bedouglas at earthlink.net Wed Sep 3 16:36:50 2008 From: bedouglas at earthlink.net (bruce) Date: Wed, 3 Sep 2008 13:36:50 -0700 Subject: python/xpath question.. Message-ID: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> morning.... i apologize up front as this is really more of an xpath question.. in my python, i'm using the xpath function to iterate/parse some html. i can do something like s=d.xpath("//tr/td/text()") count=len(s) and get the number of nodes that have text i can then do something like s=d.xpath("//tr/td") count2=len(s) and get the number of total nodes... by subtracting, i can get the number of nodes, without text.. is there an easier way??!! count2-count ie, if i have something like foo is there a way to get the count that there is a single "td" node with text()="" thanks From qxyuestc at yahoo.cn Tue Sep 2 09:24:21 2008 From: qxyuestc at yahoo.cn (qxyuestc at yahoo.cn) Date: Tue, 2 Sep 2008 06:24:21 -0700 (PDT) Subject: what's the difference between f(a) and f(*a) Message-ID: <4b57d4c3-a398-41b1-916a-064ee96bf3f6@25g2000prz.googlegroups.com> def sum1(*a): return(sum(i*i for i in a)) def sum2(a): return(sum(i*i for i in a)) a=[1,2,3] print(sum1(*a), sum2(a)) #################################### showed above: the result from sum1() and sum2() is the same. So, what is the difference between f(a) and f(*a) From mr.spoon21 at gmail.com Sun Sep 14 15:19:06 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 14 Sep 2008 21:19:06 +0200 Subject: Abstract class In-Reply-To: <48CD62B8.7070708@islandtraining.com> References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <48CD62B8.7070708@islandtraining.com> Message-ID: <8f67b6f80809141219m5f66ac47xc2e0fce1786a2702@mail.gmail.com> On Sun, Sep 14, 2008 at 9:15 PM, Gary Herron wrote: > Please forget about Abstract Base Classes. They have nothing to do with > what you want, and are a *HUGE* overkill for your application. They are > not (yet) even part of standard Python, and are used primarily for a class > implementor to guarantee to a user of a class that it provides a specific > interface. Ok :D I started to think to abstract classes just because in the paper it uses an abstract class in SmallTalk. Anyway, thanks. From berthe.loic at gmail.com Thu Sep 4 13:11:45 2008 From: berthe.loic at gmail.com (LB) Date: Thu, 4 Sep 2008 10:11:45 -0700 (PDT) Subject: Help needed to freeze a script. References: <7f364174-75c6-4120-b00e-6f41643ccbf5@z72g2000hsb.googlegroups.com> <614c7366-ba7e-4296-a4f0-a32accaa427a@b38g2000prf.googlegroups.com> Message-ID: <0957cba5-9aa8-41d6-bf95-9d6a8db18c89@l33g2000pri.googlegroups.com> > Did you try py2exe instead offreeze? On the page > > http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules > > there is only one brief mention of numpy packaging troubles, > suggesting that it might work better. I have used py2exe in the past > without much trouble. Unfortunately, I'm working under Linux and py2exe works only for windows as far as I know. Do you know if py2exe executable embedding a lot of C extensions - like numpy and scipy - can ben executed on another computer, with a different architecture (64bits vs 32 bits) and a different OS ? -- LB From uninverted at lavabit.com Sun Sep 28 20:09:51 2008 From: uninverted at lavabit.com (Nathan Seese) Date: Mon, 29 Sep 2008 02:09:51 +0200 (CEST) Subject: Odd Errors Message-ID: When I run: #!/usr/bin/python lines = list() while 1: try: inLine = raw_input() lines = lines.append(inLine) except EOFError: break I get: Traceback (most recent call last): File "./foobar.py", line 7, in lines = lines.append(inLine) AttributeError: 'NoneType' object has no attribute 'append' From bj_666 at gmx.net Wed Sep 3 13:06:51 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Sep 2008 17:06:51 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <6i6pq9Fmcad7U2@mid.uni-berlin.de> Message-ID: <6i7uhbFmcad7U3@mid.uni-berlin.de> On Wed, 03 Sep 2008 03:09:18 -0400, Derek Martin wrote: > On Wed, Sep 03, 2008 at 06:40:10AM +0000, Marc 'BlackJack' Rintsch > wrote: >> On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote: >> >> >> And if they model an action there must be some way to activate the >> >> action >> > >> > That's a reasonable assumption, but as I also said, the object might >> > just describe the action -- essentially the equivalent of a struct in >> > C. >> >> ``struct``\s in C describe *actions*!? Functions do this. > > struct run { > int speed; > direction_type direction; > }; Guess what, I don't like the name because it doesn't describe an action but a state of, e.g. a `Runner`. :-) >> >> but the instances of `Popen` are no actions. There's no way to >> >> "execute" a `Popen` instance. >> > >> > Yes there is... you execute it when you instantiate the object. >> >> But then the instance itself isn't an action but the result of one. > > So? A class doesn't represent an action, remember? It represents a > thing. Isn't that what you said? Yes and that's why the type name should not describe the action but the the thing that results from it. IMHO. But I said that already. >> >> Maybe from your POV. Facts: It doesn't use the `popen()` function >> > >> > So? Neither does the C version of popen(), but that function is >> > still called popen()! >> >> Now you lost me. The C version of `popen()` isn't recursive, why on >> earth should it be, so what's that statement supposed to mean!? > > Sorry, did I go too fast for you? Your "facts" seem to be suggesting > that for Python's Popen class to be named Popen, it should use the C > popen() function. So you imply that I think any function should only have a name of a function it uses under the hood!? I still don't get that sentence. > Sorry, but you are contradicting yourself (repeatedly), and your > arguments don't make any sense. I don't contradict myself. Either you are playing silly naming games with `popen()` on different levels ("concept", Popen, popen() (Python), popen() (C)) or you just don't *want* to understand my arguments. I understand your arguments why you think `Popen` is a proper name, but don't share them. It's okay for me if you don't like my arguments against it and for something like `Process`, but telling me they don't make any sense and patronizing me doesn't make your arguments more convincing. Ciao, Marc 'BlackJack' Rintsch From akabaila at pcug.org.au Mon Sep 22 04:02:47 2008 From: akabaila at pcug.org.au (Al Kabaila) Date: Mon, 22 Sep 2008 18:02:47 +1000 Subject: matrix algebra Message-ID: <1222070567.979005@chilli.pcug.org.au> Hi, My OS is Linux (openSUSE 10.3) and my interest in retirement is Python applications to Structural Analysis of Civil Engineering structures, currently in 2 dimensions only (under GPL). Modern Structural Analysis is highly matrix oriented, but requires only a few basic matrix operations, namely matrix creation, transposition, multiplication, invertion and linear equation solution. For stability analysis one would require Eigenvalues and Eigenvectors. In 3 dimensions, additionally highly desirable would be vector algebra. The packages do have all these functions, but currently only the basic functions are in the wrapper. There are several packages for matrix algebra. I tried Numeric, numpy and numarray. All three are very good, but each uses different syntax. Not a good thing for teaching... So I wrote a little python wrapper (under GPL) to unify all packages with the same simple and transparent syntax. Currently it deals with the Numeric, numpy and numarray and covers creation of zero filled matrices, transposition, matrix multiplication, solution of equations and inversion. This is a very active newsgroup that incudes such giants as Frederik Lundh and countless others. I wonder: 1. Is there any interest in matrix algebra "for the masses" (I mean interest in a wrapper for a subset of functions of the packages with a unified simple syntax)? 2. What other matrix operations would be required for your area of interest? 3. What other matrix packages, if any, should one include in the wrapper? A copy of the wrapper is stored in a small, public svn repository. If you would like to download it, please contact me by email at. Of course, if there is interest, I would be delighted to upload it to a generally accessible repository. Finally, if this is a re-invention of the wheel (which it may well be), would you kindly let me know? akabaila [at] pcug [dot] org [dot] au. I would be very happy to send you the checkout instructions, but I should discuss that with the people who run the repository. My home page that I quote with my signature is not a repository nor does it have the current programs. OldAl. -- Al Kabaila (Dr) http://akabaila.pcug.org.au/StructuralAnalysis From stefan_ml at behnel.de Thu Sep 4 03:14:16 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 04 Sep 2008 09:14:16 +0200 Subject: xml + mmap cross In-Reply-To: References: Message-ID: <48BF8AC8.6030509@behnel.de> castironpi wrote: > Any interest in pursuing/developing/working together on a mmaped-xml > class? Faster, not readable in text editor. Any hints on what you are talking about? Stefan From beema.shafreen at gmail.com Tue Sep 9 04:53:19 2008 From: beema.shafreen at gmail.com (Beema Shafreen) Date: Tue, 9 Sep 2008 14:23:19 +0530 Subject: biopython Message-ID: Hi all, I am using Biopython to fetch pumed Id's ,The module i use is (from Bio import Entrez) But i am getting this error >>> from Bio import Entrez Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name Entrez what should i do know can anybody suggest me an alternative for this -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From cs at zip.com.au Tue Sep 23 20:24:54 2008 From: cs at zip.com.au (Cameron Simpson) Date: Wed, 24 Sep 2008 10:24:54 +1000 Subject: python syntax for conditional is unfortunate In-Reply-To: Message-ID: <20080924002454.GA11028@cskk.homeip.net> On 23Sep2008 19:52, Neal Becker wrote: | In hindsight, I am disappointed with the choice of conditional syntax. | I know it's too late to change. The problem is | | y = some thing or other if x else something_else | | When scanning this my eye tends to see the first phrase and only | later notice that it's conditioned on x (or maybe not notice at all!). | Particularly if 'some thing or other' is long or complicated. Personally, I think this is deliberate (the wordiness and ordering, not the reading difficulty). Plenty of people dislike C's ternary b?x:y operator, presumably for the same reasons. A good coder will present things clearly. For trivial stuff the one line form may be fine, and for longer stuff then this: y = some thing or other \ if x \ else something_else or: if x: y = something or other else: y = something_else should appear. If it's your code, this is up to you. If it's another's, well anyone can write unreadable code... Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Principles have no real force except when one is well fed. - Mark Twain From info at wingware.com Thu Sep 18 12:07:29 2008 From: info at wingware.com (Wingware) Date: Thu, 18 Sep 2008 12:07:29 -0400 Subject: ANN: Wing IDE for Python v. 3.1.4 released Message-ID: <48D27CC1.2080703@wingware.com> Hi, Wingware has released version 3.1.4 of Wing IDE. This bug fix release is available for all three product levels of Wing IDE. *Release Highlights* This release includes the following: * Debugger support for Python 2.6 * Support zope buildout directories not named "instance" * Added highlighted keywords for caml, d, escript, lisp, ps, and yaml files * Don't display message that save is unavailable before running pylint * VI mode fix: After / de-select the search match once Enter is pressed * About 20 other bug fixes: see the change log for details http://wingware.com/pub/wingide/3.1.4/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE Pro 3.1.4 http://wingware.com/downloads/wingide/3.1 Wing IDE Personal 3.1.4 http://wingware.com/downloads/wingide-personal/3.1 Wing IDE 101 3.1.4 http://wingware.com/downloads/wingide-101/3.1 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.1 supports Python versions 2.0.x through 2.5.x. *New Features in Wing 3.1* This release adds the following features not found in Wing 3.0.x: * Support for zip archives * Support for pkg_resources name spaces and eggs * Support for doctest and nose style unit tests (*) * Scan for sys.path changes such as those used in buildout * How-To and support for Google App Engine * Inline context appropriate templates/snippets integrated with autocompleter (*) * Word list driven auto-completion in non-Python files (**) * Quick navigation to files and symbols by typing a fragment (**) * Improved support for Stackless Python * Preference to strip trailing white space on save * Display gi_running and gi_frame for generators * Improved code analysis for Python 2.5 * Other minor features and bug fixes not found in Wing 3.0.x (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal or Professional only. Please see the change log for a detailed list of changes: http://wingware.com/pub/wingide/3.1.4/CHANGELOG.txt *Purchasing and Upgrading* Wing 3.1 is a free upgrade for all Wing IDE 3.0 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From bj_666 at gmx.net Thu Sep 11 05:32:03 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Sep 2008 09:32:03 GMT Subject: Is len O(n) or O(1) ? References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> Message-ID: <6is6sjF6v3jU1@mid.uni-berlin.de> On Thu, 11 Sep 2008 02:23:43 -0700, process wrote: > Python uses arrays for lists right? `len()` on `list` objects is O(1). > def quicksort(lista): > if lista == []: > lista > else: > return quicksort([x for x in lista[1:] if x < lista[0]]) + > [lista[0]] + \ > quicksort([x for x in lista[1:] if x >= lista[0]]) > > or > > def quicksort(lista): > if len(lista) == 0 > lista > else: > return quicksort([x for x in lista[1:] if x < lista[0]]) + > [lista[0]] + \ > quicksort([x for x in lista[1:] if x >= lista[0]]) > > wait first one raises TypeError unsupported operand types. Both do because `None` + `list` doesn't make sense. You should actually ``return`` the `lista` in the ``if`` branch instead of just lookup the object for that name and then do nothing with it. Shorter alternative: if not lista: return [] Empty lists are considered `False` in a boolean test. Ciao, Marc 'BlackJack' Rintsch From petite.abeille at gmail.com Mon Sep 8 13:51:49 2008 From: petite.abeille at gmail.com (Petite Abeille) Date: Mon, 8 Sep 2008 19:51:49 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: References: <6ii9jbFqoe2eU1@mid.uni-berlin.de> <6ikc76Fr32cnU1@mid.uni-berlin.de> Message-ID: On Sep 8, 2008, at 1:56 PM, Gerhard H?ring wrote: > But AFAIK it's possible to compile a custom SQLite with appropriate > flags to ./configure that will include the fulltext search extension. It's indeed rather straightforward to integrate FTS, e.g.: % CFLAGS="-DSQLITE_ENABLE_FTS3=1" ./configure % sudo make install "Full-Text Search on SQLite" http://blog.michaeltrier.com/tags/fts Here is an example of FTS at work: http://svr225.stepx.com:3388/search?q=chicago Cheers, -- PA. http://alt.textdrive.com/nanoki/ From istvan.albert at gmail.com Fri Sep 26 23:28:32 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 26 Sep 2008 20:28:32 -0700 (PDT) Subject: multiprocessing eats memory References: <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> Message-ID: <02522a54-40ad-46a7-acb9-544f2fa5998f@d70g2000hsc.googlegroups.com> On Sep 26, 4:52?am, redbaron wrote: > How could I avoid of storing them? I need something to check does it > ready or not and retrieve results if ready. I couldn't see the way to > achieve same result without storing asyncs set. It all depends on what you are trying to do. The issue that you originally brought up is that of memory consumption. When processing data in parallel you will use up as much memory as many datasets you are processing at any given time. If you need to reduce memory use then you need to start fewer processes and use some mechanism to distribute the work on them as they become free. (see recommendation that uses Queues) From larry.bates at vitalEsafe.com Mon Sep 15 14:11:40 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Mon, 15 Sep 2008 13:11:40 -0500 Subject: Parallelising code In-Reply-To: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: psaffrey at googlemail.com wrote: > I have some file processing code that has to deal with quite a lot of > data. I have a quad core machine, so I wondered whether I could take > advantage of some parallelism. > > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? > > - Is list.append() thread safe? (not sure if this is the right term) > what I mean is, can two separate processors file a point in the same > list at the same time without anything horrible happening? Do I need > to do anything special (mutex or whatever) to make this happen, or > will it happen automatically? > > Thanks in advance for any guidance, > > Peter Put the data into a database first to see if it is actually too slow. If it is take a look at an in-memory database or perhaps something as simple as memcached could help. -Larry From bignose+hates-spam at benfinney.id.au Mon Sep 8 05:47:30 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 08 Sep 2008 19:47:30 +1000 Subject: universal unicode font for reportlab References: Message-ID: <87r67vj7f1.fsf@benfinney.id.au> Laszlo Nagy writes: > I could not find any free TTF font that can do latin1, latin2, > arabic, chinese and other languages at the same time. Is there a > single font that is able to handle these languages? The GNU Unifont covers an impressive range of the Unicode Basic Multilingual Plane. Unifont is originally a bitmap font, but was recently made available in TrueType format . Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont' packages, respectively. -- \ ?Science doesn't work by vote and it doesn't work by | `\ authority.? ?Richard Dawkins, _Big Mistake_ (The Guardian, | _o__) 2006-12-27) | Ben Finney From ggpolo at gmail.com Sun Sep 14 11:06:22 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 14 Sep 2008 12:06:22 -0300 Subject: cjson 1.0.5 keyword argument In-Reply-To: <31008070-11e0-44ad-9b27-9985323afb9a@s1g2000pra.googlegroups.com> References: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> <31008070-11e0-44ad-9b27-9985323afb9a@s1g2000pra.googlegroups.com> Message-ID: On Sun, Sep 14, 2008 at 11:50 AM, Clodoaldo wrote: > On Sep 14, 11:45 am, "Guilherme Polo" wrote: >> On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo wrote: >> > I have installed cjson 1.05 in Fedora 8 (python 2.5.1). >> >> > The cjson home page shows a keyword argument "encoding". >> >http://python.cx.hu/python-cjson/ >> >> The latest python-cjson on that page is 1.0.3, which accepts keywords >> for the encode function. python-cjson 1.0.5 no longer accepts. >> >> > When i use it i get an error: >> >> >>>> cjson.encode('?', encoding='utf8') >> > Traceback (most recent call last): >> > File "", line 1, in >> > TypeError: encode() takes no keyword arguments >> >> > What am i missing? There is no mail list for cjson. >> >> Try doing cjson.encode('?'.decode('utf-8')) instead. > > I had tried decoding first and it worked but my database is utf-8 so i > don't want that extra step. I'm not sure about this "extra step" you are talking about. When you do cjson.encode('?', encoding='utf-8') (supposing you are using python-cjson 1.0.3) it will actually end up doing the same as cjson.encode('?'.decode('utf-8')) > > BTW i have already found the problem as the other post shows. Then you didn't install python-cjson 1.0.5, it was probably 1.0.3 like I said in my other post. > > Thanks, Clodoaldo > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dblubaugh at belcan.com Fri Sep 12 16:02:44 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Fri, 12 Sep 2008 16:02:44 -0400 Subject: I cannot find where Numpy 1.2 is located Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> To All, I have been trying to locate as to where Numpy 1.2 can be downloaded. I will need this update. The only version available at the Numpy website for download is only 1.1.1 not the required 1.2 that I definitely need at this time. David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From mohitranka at gmail.com Thu Sep 18 09:23:50 2008 From: mohitranka at gmail.com (Mohit Ranka) Date: Thu, 18 Sep 2008 18:53:50 +0530 Subject: Login to website using urllib2 Message-ID: <63fb26950809180623uea83fa5r34a7a3e2f4198b37@mail.gmail.com> Hi All, I am trying to fetch HTML content from a website that has different version of pages for "logged" users and "guseuests" users. I need to fetch the "logged" user pages. The problem is, even with the use of basic authentication, I am getting "guest" user page with urllib2.urlopen. The code can be seen here. http://pastebin.com/m7301084a Any suggestions/pointers/solutions? Thanks and regards, Mohit Ranka. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sotirac at gmail.com Mon Sep 29 15:48:31 2008 From: sotirac at gmail.com (sotirac) Date: Mon, 29 Sep 2008 12:48:31 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: <4c2f4546-9f0b-4c7d-9c9e-dac39fd286cd@79g2000hsk.googlegroups.com> On Sep 28, 5:22?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 28, 4:08?pm, Michael Str?der wrote: > > > > > Gary M. Josack wrote: > > > Aaron "Castironpi" Brady wrote: > > >> On Sep 28, 2:59 pm, sotirac wrote: > > > >>> Wondering if there is a better way to generate string of numbers with > > >>> a length of 5 which also can have a 0 in the front of the number. > > > >>>
> > >>> ?random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > >>> elements
> > >>> ?code = 'this is a string' + str(random_number[0]) +
> > >>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > >>> + str(random_number[4])
> > >>> 
> > > >> '%05i'%random.randint(0,99999) > > >> -- > > >>http://mail.python.org/mailman/listinfo/python-list > > > > This produces numbers other than 5 digit numbers. making the start > > > number 10000 should be fine. > > > Why do you think it's wrong? > > > >>> import random > > >>> '%05i'%random.randint(0,99999) > > '09449' > > > IMO it's exactly what was required. > > > Ciao, Michael. > > As you read, there isn't agreement on whether the OP wanted > replacement. ?His original code didn't; his spec seemed to. My value of the result string can be '00000' to '99999'. From paul at boddie.org.uk Sat Sep 6 20:37:52 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 6 Sep 2008 17:37:52 -0700 (PDT) Subject: Use BeautifulSoup to delete certain tag while keeping its content References: Message-ID: On 6 Sep, 17:11, "Jackie Wang" wrote: > > I have the following html code: > > > > Center Bank >
> Los Angeles, CA >
> > > > > Salisbury > Bank and Trust Company > >
> Lakeville, CT >
>
> > > How should I delete the 'font' tags while keeping the content inside? This sounds like an editing exercise, really. If you're comfortable learning a new tool, I can recommend XSLT for this kind of job. Here's the stylesheet: This just describes two things: firstly, that you want to recognise font elements and to include their contents, not each element's start and end tags; secondly, that all other parts of the document should be copied. You can apply stylesheets using a number of XSL processors. The xsltproc program is usually available where libxslt is installed, and although I'm sure others will be along to tell you all about their favourite libraries and tools, here's how I use mine within Python: # XSLTools: http://www.python.org/pypi/XSLTools # libxml2dom: http://www.python.org/pypi/libxml2dom import XSLTools.XSLOutput import libxml2dom # If s is the document text... d = libxml2dom.parseString(s) # Save the above stylesheet to a file somewhere, then... proc = XSLTools.XSLOutput.Processor(["/tmp/no-font.xsl"]) # Get the result document d2 = proc.get_result(d) Anyway, this is just one option of many to deal with this kind of problem. Paul From fredrik at pythonware.com Thu Sep 4 10:53:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 16:53:53 +0200 Subject: Numeric literal syntax In-Reply-To: References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: Alexander Schmolck wrote: >> A problem is that '1234' in Python is a string, so using ' in numbers >> looks a bit dangerous to me (and my editor will color those numbers as >> alternated strings, I think). > > Yeah, editors, especially those with crummy syntax highlighting (like emacs) > might get it wrong. This should be easy enough to fix though. instead of forcing all editor developers to change their Python modes to allow you to use a crude emulation of a typographic convention in your Python source code, why not ask a few of them to implement the correct typographic convention (thin spaces) in their Python mode? From mal at egenix.com Thu Sep 4 19:52:30 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 05 Sep 2008 01:52:30 +0200 Subject: Can anyone suggest a good crypto package? In-Reply-To: References: Message-ID: <48C074BE.1050207@egenix.com> On 2008-09-04 20:39, Fett wrote: > I need a crypto package that works on windows with python 2.5. Can > anyone suggest one for me? > > I have been searching for a couple days for a good cryptography > package to use for public/private key encryption, at this point I > would settle for symmetric even. I'm not really sure what you're after, but if it's about end-to-end encryption and authentication, then OpenSSL is the way to go, e.g. using pyOpenSSL: http://www.egenix.com/products/python/pyOpenSSL/ > Every encryption package I have found for python was either operating > system specific (read *nix only): > http://www.freenet.org.nz/ezPyCrypto/ > http://www.keyczar.org/ > > There was one exception, this version was specifically built to run on > any platform (yay), but the compiler for windows complained that I > wasn't using python2.2 (though the package was said to only need 2.2 > or newer). > > Is there any crypto package that is actually written in python? I > seriously don't care how slow it is. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 05 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From sebastianthegreatful at gmail.com Thu Sep 18 03:59:17 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Thu, 18 Sep 2008 00:59:17 -0700 (PDT) Subject: ssl server References: Message-ID: On Sep 17, 7:33?pm, Seb wrote: > I'm making a ssl server, but I'm not sure how I can verify the > clients. What do I actually need to place in _verify to actually > verify that the client cert is signed by me? > > ?50 class SSLTCPServer(TCPServer): > ?51 ? ? ? ? keyFile = "sslcert/server.key" > ?52 ? ? ? ? certFile = "sslcert/server.crt" > ?53 ? ? ? ? def __init__(self, server_address, RequestHandlerClass): > ?54 ? ? ? ? ? ? ? ? ctx = SSL.Context(SSL.SSLv23_METHOD) > ?55 ? ? ? ? ? ? ? ? ctx.use_privatekey_file(self.keyFile) > ?56 ? ? ? ? ? ? ? ? ctx.use_certificate_file(self.certFile) > ?57 ? ? ? ? ? ? ? ? ctx.set_verify(SSL.VERIFY_PEER | > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > self._verify) > ?58 ? ? ? ? ? ? ? ? ctx.set_verify_depth(10) > ?59 ? ? ? ? ? ? ? ? ctx.set_session_id('DFS') > ?60 > ?61 ? ? ? ? ? ? ? ? self.server_address = server_address > ?62 ? ? ? ? ? ? ? ? self.RequestHandlerClass = RequestHandlerClass > ?63 ? ? ? ? ? ? ? ? self.socket = socket.socket(self.address_family, > self.socket_type) > ?64 ? ? ? ? ? ? ? ? self.socket = SSL.Connection(ctx, self.socket) > ?65 ? ? ? ? ? ? ? ? self.socket.bind(self.server_address) > ?66 ? ? ? ? ? ? ? ? self.socket.listen(self.request_queue_size) > ?67 > ?68 ? ? ? ? def _verify(self, conn, cert, errno, depth, retcode): > ?69 ? ? ? ? ? ? ? ? return not cert.has_expired() and > cert.get_issuer().organizationName == 'DFS' Simply return retcode and it will work... assuming you have the certs setup properly. From marco.bizzarri at gmail.com Fri Sep 5 01:17:29 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 07:17:29 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <3f0d61c40809042217r6f98c683p90bcae958b1ee773@mail.gmail.com> On Thu, Sep 4, 2008 at 8:59 PM, Carl Banks wrote: > > > You can write code to guard against this if you want: > > class A: > legal = set(["x"]) > def __setattr__(self,attr,val): > if attr not in self.legal: > raise AttributeError("A object has no attribute '%s'" % > attr) > self.__dict__[attr] = val > def __init__(self,x): > self.y = x > > > I suspect most people who go into Python doing something like this > soon abandon it when they see how rarely it actually catches anything. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > Carl, I think I did not explained what I was asking the right way. I'm not asking: "how can I do this sort of checks in Python": as I stated before, if I want them, I will go for Java, or some other language like that. I understand that Python is a balance between different forces (like any software object around the world) and I'm simply asking some pointers to the discussion leading to this balance. That's all. -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From google at mrabarnett.plus.com Fri Sep 26 11:54:32 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 26 Sep 2008 08:54:32 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> Message-ID: On Sep 26, 4:13?pm, Steven D'Aprano wrote: > On Fri, 26 Sep 2008 06:31:40 -0500, skip wrote: > > I took over spam filter management for the python.org mailing lists a > > couple months ago and made a few changes to the way the spam filter is > > trained. Things seem to be at a reasonable level as far as I can tell (I > > see a few spams leak through each day), though I wasn't actively reading > > comp.lang.python/python-l... at python.org before I took over the task, so > > I have nothing to compare with. ?Does the level of spam leaking through > > the filter now seem excessive? ?Is it more or less than in June and > > July? > > I don't have any objective numbers, but subjectively it seems to me that > the number of spams is significantly higher, but not so high as to be a > major nuisance. > I think it changes over time. You might tweak the filter to reduce the amount of spam getting through but then the spammers adapt. In other words, spam is a moving target. From joefazee at gmail.com Tue Sep 30 10:32:55 2008 From: joefazee at gmail.com (A. Joseph) Date: Tue, 30 Sep 2008 07:32:55 -0700 Subject: Replacing cmd.exe with custom .py application Message-ID: Instead of going to the command line all the time, I want to create a small customized cmd.exe of my own, how can I get the return value from os.system() because I was thinking I can do soothing with os.system(), In case my question is not clear, just like an IDE that plugged in another .exe application. Sorry for any mistake in my question. Just help me if you can -------------- next part -------------- An HTML attachment was scrubbed... URL: From mbezzi at landi.it Mon Sep 22 03:26:37 2008 From: mbezzi at landi.it (mbezzi at landi.it) Date: Mon, 22 Sep 2008 00:26:37 -0700 (PDT) Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> <974c3434-d409-484d-8bc4-7a3294132bd0@73g2000hsx.googlegroups.com> <6jnfn6F47453U2@mid.individual.net> Message-ID: <702acfae-d187-4b3e-b63b-ad08460ff46f@r66g2000hsg.googlegroups.com> On Sep 21, 7:48?pm, Peter Pearson wrote: > FWIW, since I started following this newsgroup, I've noticed > that I no longer have those crises that revolve around the depth > of a copy. ?I conjecture that they resulted from non-pythonic > style. ?Try following this newsgroup for a while, and you might > see a lot of startlingly elegant ways of doing things. > > -- > To email me, substitute nowhere->spamcop, invalid->net. I know the code is really ugly but I just make a quick and dirty snippet to ask for help. I should have wrapped the code between tags ;-) Alex From half.italian at gmail.com Wed Sep 24 23:04:14 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 24 Sep 2008 20:04:14 -0700 (PDT) Subject: Off topic: Sent from my Foo messages References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <00eaf368$0$20666$c3e8da3@news.astraweb.com> Message-ID: > -- > Steven I don't appreciate the two lines you put above your name in your posts. Please remove them in the future. ~Sean From durand1 at gmail.com Sat Sep 6 08:38:05 2008 From: durand1 at gmail.com (Durand) Date: Sat, 6 Sep 2008 05:38:05 -0700 (PDT) Subject: quake like multicoloured text References: <3d829a04-9005-4216-86dc-b1055edab4e7@f63g2000hsf.googlegroups.com> Message-ID: <417c958f-2f57-4826-8640-e3844ef614e0@f36g2000hsa.googlegroups.com> On Sep 5, 10:32?pm, "Gabriel Genellina" wrote: > En Fri, 05 Sep 2008 16:24:08 -0300, Durand escribi?: > > > > > > > I'm wondering how I could render text with PIL in which different > > parts of the text are different characters. This is for a game stats > > script where names are written like: > > ^1Red ^2Green ^3Yellow, etc. > > The problem is that I currently use text in the ImageDraw module but > > the only way I can think of rendering text is by rendering each bit of > > text in a separate colour. > > > Example: > > > draw.text((0,0),"Red", fill="red") > > draw.text((30,0),"Green", fill="green") > > draw.text((60,0),"Yellow", fill="green") > > > except that I'm not sure how much spacing there is between each > > coloured bit of text(30px is assumed in the example)...Would there be > > an alternate method of doing this? > > You could use the draw.textsize method to measure how much space will take ? > each part... > > -- > Gabriel Genellina Thanks, I guess I should have done more research... From goldspin at gmail.com Thu Sep 11 13:11:00 2008 From: goldspin at gmail.com (Henry Chang) Date: Thu, 11 Sep 2008 10:11:00 -0700 Subject: How to Determine Name of the Day in the Week Message-ID: Instead of getting integers with weekday(), Monday == 0 ... Sunday == 6; is there a way to get the actual names, such as "Monday ... Sunday"? I would like to do this without creating a data mapping. :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From invalid at invalid Fri Sep 19 10:23:05 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 19 Sep 2008 09:23:05 -0500 Subject: Python newbie References: Message-ID: <8s2dnX2ttZtUKE7VnZ2dnUVZ_gSdnZ2d@posted.visi> On 2008-09-19, Mladen Gogala wrote: > Steve Holden wrote: > >> No. Python implicitly dereferences all names when using them >> to compute values, and only uses them as references on the >> left-hand side of an assignment. >> >> Please note the above statement is contentious, and will >> likely bring a horde of screaming fanatics of various flavors >> down on my head for terminological inexactitude. > > Actually, I am not a "screaming fanatic". Steve was refering hyperbolically to people like me who find it entertaining to argue about obscure technical points involving useless, degenerate bits of example code. It's one of the things we do here instead of Perl golfing. Though off hand I don't really see anything much wrong with the statement for which Steve predicted an impending onslaught of language lawyers -- unless one wanted to jump right away into the stock discussion on name-rebinding vs. dereferencing-pointer-lvalues that we generally save for C/C++ programmers. I only used Perl once about 15 years ago (that was more than enough for me), but I would have guessed that an assigment in Perl was a name-(re)binding more akin to Python than a store to a variable's memory location like C/C++/Pascal/etc. > Hopefully, this explains who am I and what is my motivation > for delving into Python. I share your fears of screaming > fanatics, too. We're actually quite harmless and much friendlier than those in most other newsgroups. -- Grant Edwards grante Yow! My EARS are GONE!! at visi.com From gagsl-py2 at yahoo.com.ar Tue Sep 30 00:34:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 01:34:25 -0300 Subject: rlcompleter and wxPython, problems ... References: <48E0045A.3020402@gmail.com> Message-ID: En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki escribi?: > I'm trying to implement autocompletion into my editor. > But I find some weird behavior, > or at least I don't have the faintest idea why this behavior occures, > and even more important how to solve it > In the example below I try to autocomplete " wx.s" , which in my humble > opinion should at least produce "wx.stc" (and some others ). wx is a package. Modules within the package are not, by default, attributes of the package - unless they're imported in __init__.py or your code imports them. So the autocompleter is doing the right thing - wx.stc does not exist until it is explicitely imported. py> import wx py> wx.stc Traceback (most recent call last): ... AttributeError: 'module' object has no attribute 'stc' py> 'stc' in dir(wx) False py> import wx.stc py> wx.stc py> 'stc' in dir(wx) True -- Gabriel Genellina From ivanov.maxim at gmail.com Thu Sep 25 08:40:48 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Thu, 25 Sep 2008 16:40:48 +0400 Subject: multiprocessing eats memory Message-ID: I'm playing with pyprocessing module and found that it eats lot's of memory. I've made small test case to show it. I pass ~45mb of data to worker processes and than get it back slightly modified. At any time in main process there are shouldn't be no more than two copies of data (one original data and one result). I run it on 8-core server and top shows me that main process eats ~220 Mb and worker processes eats 90 -150 mb. Isn't it too much? Small test-case is uploaded to pastebin: http://pastebin.ca/1210523 From wuwei23 at gmail.com Sat Sep 27 07:53:56 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 27 Sep 2008 04:53:56 -0700 (PDT) Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: <8754d1a9-1cf4-47b6-a5c2-2e6081988d27@w39g2000prb.googlegroups.com> On Sep 27, 3:58?pm, r0g wrote: > Ah, just spotted the backticks - they just return whatever's inside them > as a string. No, they return the repr() of the object inside. The output of __repr__ -has- to be a string, but typecasting into string isn't the intention of repr() (or the ` operator). From f.guerrieri at gmail.com Thu Sep 4 09:32:02 2008 From: f.guerrieri at gmail.com (Francesco Guerrieri) Date: Thu, 4 Sep 2008 15:32:02 +0200 Subject: path slashes cleaning In-Reply-To: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> References: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> Message-ID: <79b79e730809040632y5b08a757i762635140006593@mail.gmail.com> On Thu, Sep 4, 2008 at 3:25 PM, Mathieu Prevot wrote: > Hi, > > for scripts that take arguments, I would like to remove the trailing > slash if it's present. > > Is there something else than: > > a='/usr/local/lib/' > if a[-1] == '/': > a = list(a) > a.pop() > ''.join(a) > > Thanks, > Mathieu a.rstrip('/') does the job. bye, Francesco From stefan_ml at behnel.de Wed Sep 17 15:17:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 17 Sep 2008 21:17:13 +0200 Subject: Generating test data from an XML Schema In-Reply-To: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> References: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> Message-ID: <48d157b9$0$6622$9b4e6d93@newsspool3.arcor-online.net> Mark Thomas wrote: > On Sep 17, 5:29 am, Jonathan Fine wrote: >> I want to generate test data from an XML schema. I've had a quick look >> at existing tools (such as minixsv and amara) but from what I've seen >> they don't seem to help. > ... >> A tool that provides a nice Python interface to navigating the schema >> would probably be quite helpful. >> >> Has anyone seen anything that might help generate test data from a schema? > > I'm unaware of anything in Python, but Eclipse can generate sample > documents from a schema: > http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html > > As can XML IDEs such as Stylus Studio and XML Spy. There's also a Java tool called the "XML instance generator" by Sun that supports XML Schema and RelaxNG. It's a bit tricky to find as most links to it are broken by now. Stefan From m_palmer45 at yahoo.ca Tue Sep 9 20:36:15 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 9 Sep 2008 17:36:15 -0700 (PDT) Subject: Read and write binary data References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: On Sep 7, 6:41 pm, Mars creature wrote: > Hi guys, > I am new to Python, and thinking about migrating to it from matlab > as it is a really cool language. Right now, I am trying to figure out > how to control read and write binary data, like > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > I googled, but can not find a clear answer. Anyone has clue where can > I learn it? Thanks!! > Jinbo the struct module should be useful From nytrokiss at gmail.com Fri Sep 26 15:41:35 2008 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 26 Sep 2008 12:41:35 -0700 Subject: Python is slow? In-Reply-To: <28f1b350-9908-4056-bfa2-e6c2d9edb17d@i76g2000hsf.googlegroups.com> References: <28f1b350-9908-4056-bfa2-e6c2d9edb17d@i76g2000hsf.googlegroups.com> Message-ID: <8a6b8e350809261241w22d76dd4n38fbac822aef6632@mail.gmail.com> +1 QOTW... On Tue, Sep 23, 2008 at 7:13 AM, George Sakkis wrote: > On Sep 23, 9:57 am, Grant Edwards wrote: > > > On 2008-09-23, sturlamolden wrote: > > > > [...] > > > > > After having a working Python prototype, I resorted to rewrite the > > > program in C++. The Python prototype took an hour to make, debug and > > > verify. The same thing in C++ took me almost a day to complete, even > > > with a working prototype as model. To my surprise, the resulting beast > > > of C++ required 64.3 seconds to construct the same kd-tree. Searching > > > the tree was not faster either, 1,000 points required 38.8 seconds. I > > > wasted a day, only to find my Python prototype being the faster. > > > > > We may conclude that I'm bad at programming C++, > > > > AFAICT, _everybody_ is bad at programming C++. > > +1 QOTW > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From d3vvnull at gmail.com Fri Sep 26 18:05:30 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 17:05:30 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: References: <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Message-ID: <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> so you wouldn't object then to something like '.... in (%)' % ','.join([str_edit_for_exploit(x) for x in aList]) if str_edit_for_exploit applied security edits? On Fri, Sep 26, 2008 at 2:28 PM, Benjamin Kaplan wrote: > > > On Fri, Sep 26, 2008 at 3:04 PM, Michael Mabin wrote: > >> Doesn't it depend on where and why you intend to execute the code? >> Obviously some SQL is more at risk for exploit when the input is from the >> screen on a web page than if you were running parameterized code in a >> controlled batch environment. Or if you were writing code generators (which >> is what I happen to do) which won't be run by the general public. >> >> Incidentally, couldn't input field edits prevent such exploits prior to >> interpolation? >> > > There are ways to avoid SQL injection attacks, such as escaping all quotes > in the text. We were simply pointing out that you have to be very careful > when you add arbitrary strings into SQL statements. If you control > everything going into the statement, you shouldn't have to worry about this. > > > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From cvrebert at gmail.com Fri Sep 12 21:08:01 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Fri, 12 Sep 2008 18:08:01 -0700 Subject: Good python web programming books In-Reply-To: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> References: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> Message-ID: <47c890dc0809121808g3c57e4b8p87166657a7b4a29e@mail.gmail.com> I've heard good things about The Django Book: http://www.djangobook.com/ - Chris On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma wrote: > Hi Guys, > > I am very new to python. I am looking for a good book about python web > programming. > > I looked at a few online like Web Programming In Python but most are quite > old. > > If you've read a good book on python web programming can you please suggest > some? > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From erikwickstrom at gmail.com Thu Sep 18 19:23:46 2008 From: erikwickstrom at gmail.com (erikcw) Date: Thu, 18 Sep 2008 16:23:46 -0700 (PDT) Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> Message-ID: <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> On Sep 18, 3:33?pm, Ben Finney wrote: > erikcw writes: > > I have a cgi script where users are uploading large files for > > processing. I want to launch a subprocess to process the file so the > > user doesn't have to wait for the page to load. > > For "how do I deal with subprocesses from Python", the (new in Python > 2.4) 'subprocess' module is the default go-to answer > , replacing a > rather fragmented set of modules before it. > > > What is the correct way to launch subprocess without waiting for the > > result to return? > > Creating an instance of 'subprocess.Popen' will launch the process and > return the Popen instance. You then have the option of polling it or > waiting for it to complete. > > -- > ?\ ? ? ?To stay young requires unceasing cultivation of the ability to | > ? `\ ? ? ? ? ? ? ? ? ? unlearn old falsehoods.? ?Robert Anson Heinlein | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > Ben Finney So if I create a Popen object and then just ignore the object and exit the program the subproccess will finish it's work and then exit itself cleanly? From ldo at geek-central.gen.new_zealand Mon Sep 29 05:22:02 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:22:02 +1300 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> Message-ID: In message , Ross Ridge wrote: > You need either use trial and error to find out, or look at the source. So what's wrong with using the source as documentation? :) From agostino.russo at gmail.com Tue Sep 9 13:47:13 2008 From: agostino.russo at gmail.com (ago) Date: Tue, 9 Sep 2008 10:47:13 -0700 (PDT) Subject: PYTHONSITEDIR environment variable Message-ID: Dear all, These days I often find myself using working-env.py, virtual-python.py & co. The main reason in most cases is to insulate my working environment so that I can use custom site-package libs together with the default stdlib. PYTHONHOME and/or PYTHONPATH (particularly with python -S) get close, but not quite there, and the above scripts seem a bit over the top. Wouldn't it be possible to support a PYTHONSITEDIR environment variable in site.py for this purpose? I have attached a possible patch. In what follows, if PYTHONSITEDIR is defined, that dir is used as the only source of site-packages, extra paths can easily be added by creating a .pth file in there. A different variable could be used to prepend a sitedir to the list of default sitedirs (similar code without "return None"). --- /usr/lib/python2.5/site.py 2008-05-29 22:03:04.000000000 +0100 +++ /tmp/site.py 2008-09-09 18:06:42.000000000 +0100 @@ -167,6 +167,10 @@ def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" + sitedir = os.environ.get('PYTHONSITEDIR') + if sitedir and os.path.isdir(sitedir): + addsitedir(sitedir, known_paths) + return None prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) From rsarpi at gmail.com Tue Sep 9 17:35:13 2008 From: rsarpi at gmail.com (icarus) Date: Tue, 9 Sep 2008 14:35:13 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw That did it. one more question... how do I create a pythonw standalone executable that works on w32, linux, mac, etc..? My intent is to have the process transparent to the user. He wouldn't even know the app was written in python. All he knows that when he double-clicks on it, the application pops up without the DOS black screen in the background (for w32 users.) On Sep 9, 10:49 am, "Chris Rebert" wrote: > You need to have the script be run by pythonw.exe as opposed to python.exe > pythonw.exe suppresses the DOS box from coming up and should be used > for running GUI applications such as yours. > > Regards, > Chris > > > > On Tue, Sep 9, 2008 at 1:33 PM, icarus wrote: > > platform: windows xp professional, python 2.5, wxpython > > > When I double-check on my program file test.py (for simplicity I'll be > > using this code below), I see the window just fine. But the ms-dos > > black window pops up in the background. On Linux, no issues at all. > > > How can I get rid of that ms-dos black window in the background? > > something I need to add to my code? a setting to adjust in windows? > > thanks in advance. > > > #!/usr/bin/python > > import wx > > > appwx = wx.App() > > > frame = wx.Frame(None, -1, 'test.py') > > frame.Show() > > > appwx.MainLoop() > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com From marco.bizzarri at gmail.com Thu Sep 4 06:05:15 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 12:05:15 +0200 Subject: overwrite set behavior In-Reply-To: References: Message-ID: <3f0d61c40809040305t1af64757wfe9ef279b69bfc45@mail.gmail.com> Ciao, Michele: On Thu, Sep 4, 2008 at 11:48 AM, Michele Petrazzo wrote: > Hi all, I want to modify the method that set use for see if there is > already an object inside its obj-list. Something like this: > > class foo: pass > > bar1 = foo() > bar1.attr = 1 > > bar2 = foo() > bar2.attr = 1 > > set( (bar1, bar2), key=lambda o: o.attr) > > and, of course, set has only one value. > > It's possible? > > Thanks, > Michele > -- > http://mail.python.org/mailman/listinfo/python-list > looking at the source, maybe you could create a subclass of Set redefining the __contains__ method? Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From sturlamolden at yahoo.no Sun Sep 7 00:24:07 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 6 Sep 2008 21:24:07 -0700 (PDT) Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: <96df416b-cc13-4631-8865-d6b6373772a5@z72g2000hsb.googlegroups.com> On 7 Sep, 00:06, cnb wrote: > If I buy a multicore computer and I have really intensive program. How > would that be distributed across the cores? Distribution of processes and threads across processors (cores or CPUs) is managed by the operating system. > Will algorithms always have to be programmed and told specifically to > run on several cores so if not told it will only utilize one core? One particular program has to be programmed for concurrency to utilize multiple cores. But you typically have more than one program running. > So is the free lunch really over or is this just an overhyped > phenomena? Two slow cores are better than one fast for most purposes. For one thing, it saves power. It's good for the battries and environment alike. > Is threading with Python hard? It's not harder than with other systems. You just subclass threading.Thread, which has almost the same interface as Java threads. Threading with Python is perhaps a bit easier than with other common platforms, due to the Queue.Queue object and the lack of volatile objects. > Can you start several processes with Python or just threads? You can do both. However, remember that Python threads only do what threads were designed to do back in the 1990s. That is asynchrony for I/O and UIs, not concurrency on multiple processors for CPU bound computing. This is due to the "Global Interpreter Lock". The GIL is better than fine-grained locks for single-threading and concurrency with multiple processes, but prevent python threads form being used for concurrency (just as well). You can do concurrency with Java threads or Win32 threads, but this is merely a side-effect. You will often see claims form novice programmers that threads are the only route to concurrency on multi- core CPUs. In addition to the existence of processes, direct use of threads from Java, .NET, POSIX, or Win32 APIs is not even the preferred way of programming for concurrency. Tinkering with low-level threading APIs for concurrency is error-prone and inefficient. You will spend a lot of time cleansing your code of dead-locks, live- locks, volatile objects not being declared volatile, and race conditions. In addition to that, chances are your code will not perform or scale very well due to memory contention, cache line misses, inefficient use of registers due to volatile objects, etc. The list is endless. That is why Java 6 and .NET 3.5 provide other abstractions for multi-core concurrency, such as ForkJoin and Parallel.For. This is also the rationale for using an OpenMP enabled compiler for C or Fortran, auto-vectorizing C or Fortran compilers, and novel languages like cilk and erlang. Traditionally, concurrency om parallel computers have been solved using tools like BSPlib, MPI, vectorizing Fortran compilers, and even "ebarassingly parallel" (running multiple instances of the same program on different data). OpenMP is a recent addition to the concurrency toolset for SMP type parallel computers (to which multi- core x86 processors belong). If you really need concurrency with Python, look into MPI (PyMPI, PyPAR, mpi4py), Python/BSP, subprocess module, os.fork (excluding Windows), pyprocessing package, or Parallel Python. BSP is probably the least error-prone paradigm for multi-core concurrency, albeit not the most efficient. If you decide to move an identified bottleneck from Python to C or Fortran, you also have the option of using OpenMP or cilk to ease the work of programming for concurrency. This is my preferred way of dealing with bad bottlenecks in numerical computing. Remember that you need not learn the overly complex Python C API. Cython, ctypes, f2py, or scipy.weave will do just as well. This approach will require you to manually release the GIL, which can be done in several ways: - In C extensions between Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros. - When calling DLL methods using ctypes.cdll or ctypes.windll (not ctypes.pydll). - In a "with nogil:" block in a Cython/Pyrex extension. - With f2py or SWIG, although I have not looked at the details. (I don't use them.) Other things to consider: - Programs that run fast enough run fast enough, even if they only utilize one core. To qoute C.A.R. Hoare and Donald Knuth, "premature optimization is the root of all evil in computer programming." - Psyco, a Python JIT compiler, will often speed up algorithmic code. Using psyco require to change to your code. Try it and see if your programs runs fast enough afterwards. YouTube is rumoured to use psyco to speed ut their Python backend. - Always use NumPy or SciPy if you do numerical work. They make numerical code easier to program. The numerical code also runs a lot faster than a pure python equivalent. - Sometimes Python is faster than your hand-written C. This is particularly the case for Python code that make heavy use of built-in primitives and objects from the standard library. You will spend a lot of time tuning a linked list or dynamic array to match the performance of a Python list. Chances are you'll never come up with a sort as fast as Python's timsort. You'll probably never make your own hash table that can compete with Pythons dictionaries and sets, etc. Even if you can, the benefit will be minute and certainly not worth the effort. - You will get tremendous speedups (often x200 over pure Python) if you can move a computational bottleneck to C, C++, Fortran, Cython, or a third-party library (FFTW, LAPACK, Intel MKL, etc.) - Portions of your Python code that do not constitute important bottlenecks can just be left in Python. You will not gain anything substantial from migrating these parts to C, as other parts of your code dominate. Use a profiler to indentify computational bottlenecks. It will save you a lot of grief fiddling with premature optimizations. That's my fifty cents on Python coding for speed. From paul at boddie.org.uk Mon Sep 29 14:51:15 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 29 Sep 2008 11:51:15 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> Message-ID: On 29 Sep, 19:26, Terry Reedy wrote: > > Please: Python does not have 'lambda functions'. Def statements and > lambda expressions both define instances of the function class. So this > amounts to saying "functions are subject to the same caveats as functions." I myself am aware of the nature of "lambda expressions", for want of a better term, but it's important to emphasise their nature to anyone reading who isn't fully aware of what they represent. My closing paragraph touches on the issues of readability and programmer expectation when I write that 'function definition statements do not behave like, say, "for", "if" or "while" statements'. Although this may seem obvious, a newcomer might overlook lambda expressions in this regard. Personally, I'm not a great enthusiast of closures, anyway. Perhaps I spent too long writing Java to be able to look at them as being anything other than a fairly imprecise way of encapsulating state in a callable. Paul From jinbow at gmail.com Thu Sep 4 12:30:46 2008 From: jinbow at gmail.com (Mars creature) Date: Thu, 4 Sep 2008 09:30:46 -0700 (PDT) Subject: Read Binary data References: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> Message-ID: <3a0d241f-c43b-49f2-a70e-eafad6de49d1@t1g2000pra.googlegroups.com> On Sep 4, 12:03 pm, Fredrik Lundh wrote: > "Mars creature" wrote: > > I am trying to read a binary file created by the following matlab > > command: > > fid=fopen('a.bin','w','b'); fwrite(fid,a,'real*8'); fclose(fid);, and > > wondering how to do it in Python. I googled it but still get > > confused. > > 'b' in fopen is for 'big-endian', 'real*8' in fwrite is for 64bit > > float. > > f = open("a.bin", "rb") # read binary data > s = f.read() # read all bytes into a string > > import array, sys > > a = array.array("f", s) # "f" for float > if sys.byteorder != "big": > a.byteswap() > > Thanks Fredrik! I appreciate it! The only thing is that a = array.array("f", s) should be a = array.array("d", s) as the data is double precision. Thanks again! From prologic at shortcircuit.net.au Mon Sep 22 05:41:46 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 19:41:46 +1000 Subject: What do you call a class not intended to be instantiated In-Reply-To: References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> Message-ID: On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano > But that's precisely what I want to avoid: I don't want the objects to > share *any* state, not even their class. I'm not trying for a Borg or > Singleton: the user can call the factory as many times as they want, but > the objects returned shouldn't share any state. I don't know if what I > want has a name. Judging from people's reactions, I'd say probably not. Snce when are "users" ever involved in programming problems or programming languages ? --JamesMills -- -- -- "Problems are solved by method" From stava at telcotec.se Sat Sep 27 04:05:01 2008 From: stava at telcotec.se (Lars Stavholm) Date: Sat, 27 Sep 2008 10:05:01 +0200 Subject: python for *nix system admins Message-ID: <48DDE92D.6090405@telcotec.se> Hi All, I'm new to this list and hoping that this is not off-topic. If it is, please point me in the right direction. I seem to recollect a python module or library for *nix sysadmins, but I can't for the life of me find it again. The module (or library) somehow added unix command capabilities to the python language. It seemed like a lesser known, perhaps new, python library or module. Any input or ideas appreciated /Lars Stavholm From skip at pobox.com Wed Sep 17 08:09:30 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Sep 2008 07:09:30 -0500 Subject: shelve file space always increase! In-Reply-To: References: Message-ID: <18640.62330.105952.110065@montanaro-dyndns-org.local> smalltalk> the abc.db is always 312k though i have use clear(), how can smalltalk> i shrink the space? You really can't without deleting the file. Hash file implementations trade off file size against improve key lookup performance. Similar tradeoffs are made in the implementation of Python's dictionary and other languages' associative arrays. My Google skills must be lacking this morning. Here's the best I've been able to come up with in the way of explanation: http://en.wikipedia.org/wiki/Associative_array#Efficient_representations Skip From dudeja.rajat at gmail.com Mon Sep 29 12:10:52 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 29 Sep 2008 17:10:52 +0100 Subject: Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars In-Reply-To: References: Message-ID: On Sun, Sep 28, 2008 at 4:51 PM, wrote: > > Hi, > > > Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well > the problem is I'm unable to scroll if I click on the arrows buttons of > scrollbars ( with both types of scrollbars) > > > Please suggest if I m missing some configuration. > > > My code is as below: > > self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL) > self.hsb.grid(row = 2,column = 0, sticky = E+W) > #vertical scroll bar > self.vsb = Scrollbar(appGuiFrame) > self.vsb.grid(row = 1,column = 2, sticky = N+S) > > > > self.txtLogger = Text(appGuiFrame, \ > height = 20,\ > width = 100, \ > state = DISABLED, \ > xscrollcommand = self.hsb.set, \ > yscrollcommand = self.vsb.set, \ > wrap = NONE, \ > font = ("courier",12)) > self.hsb.config(command = self.txtLogger.xview()) > self.vsb.config(command = self.txtLogger.yview()) > > > Please help. > > > Thanks and regards, > Rajat > Hi folks, Any help on the above problem. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From maebert at uos.de Mon Sep 1 04:52:10 2008 From: maebert at uos.de (Manuel Ebert) Date: Mon, 1 Sep 2008 10:52:10 +0200 Subject: Know if a object member is a method In-Reply-To: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Message-ID: <9E7BC2B9-AE15-477D-B8DB-20DD47AFBB79@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Luca, use type(something).__name__ , e.g. >>> def x(): >>> pass >>> class C: >>> pass >>> c = C() >>> type(x).__name__ == 'function' True >> type(C).__name__ == 'classobj' True >> type(c).__name__ == 'instance' True On Sep 1, 2008, at 10:43 AM, Luca wrote: > Hi all. > > I think this is a newbie question... what is the best method to know > if a property of an object is a function? > > I'm thinking something as > > if type(obj.methodName)==??? > > Can someone help me? > > -- > -- luca > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIu606cZ70OCIgLecRAhE6AJ4r0GuHlWxXbLaYuolqpJStYPD+ggCgidKg qtgl+nbaKgH5AoelTu5WeJU= =W4eG -----END PGP SIGNATURE----- From timr at probo.com Fri Sep 26 23:44:28 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 27 Sep 2008 03:44:28 GMT Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> <98e4f068-5349-4b38-b15b-7e2436a0e4a7@f63g2000hsf.googlegroups.com> Message-ID: Mark Dickinson wrote: >On Sep 25, 8:55?am, Tim Roberts wrote: >> Marc 'BlackJack' Rintsch wrote: >> >0.1 actually is >> >> >In [98]: '%.50f' % 0.1 >> >Out[98]: '0.10000000000000000555111512312578270211815834045410' >> >? >> >> .... ?0.1 in an IEEE 784 double is this: >> >> ? ? ?0.100000000000000088817841970012523233890533447265625 > >I get (using Python 2.6): > >>>> n, d = 0.1.as_integer_ratio() >>>> from decimal import Decimal, getcontext >>>> getcontext().prec = 100 >>>> Decimal(n)/Decimal(d) >Decimal('0.1000000000000000055511151231257827021181583404541015625') > >which is a lot closer to Marc's answer. Looks like your float >approximation to 0.1 is 6 ulps out. :-) Yes, foolishness on my part. The hex is 3FB99999_9999999A, so we're looking at 19999_9999999A / 2^56 or 7205759403792794 ------------------- 72057594037927936 which is the number that Marc, Nick, and you all describe. Apologies all around. I actually dropped one 9 the first time around. Adding one more weird data point, here's what I get trying Marc's original sample on my Windows box: C:\tmp>python Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> '%.50f' % 0.1 '0.10000000000000001000000000000000000000000000000000' >>> I assume this is the Microsoft C run-time library at work. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From coolman.guron at gmail.com Tue Sep 16 13:03:08 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Tue, 16 Sep 2008 10:03:08 -0700 (PDT) Subject: parse a midi file References: Message-ID: <44f81225-34e1-43de-a1d2-e5e77aed6327@q26g2000prq.googlegroups.com> On Sep 16, 9:48?pm, Mr.SpOOn wrote: > Hi, > I need to parse a midi file with Python. What I exactly need is the > possibility to distinguish all notes in all channels in a midi file > and put them in a list or something. > > I've found this: > > http://groups.google.com/group/alt.sources/msg/22467419ad4bf416 > > I'm not sure how it does work, but looking at the code I saw it can > get input from the terminal, so I tried: > > python midi.py < mymidi.mid > > All it does is printing a lot of strange symbols. > > Do you know other easy way to parse a midi file in Python? Or how > actually does this module work? > > Thanks, > Carlo hi, just looked at the code. try this python midi.py -i mymidi.mid to see all the debug information do python midi.py -p -d -i mymidi.mid From bj_666 at gmx.net Tue Sep 2 18:55:54 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 22:55:54 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> Message-ID: <6i5ujqFol29aU8@mid.uni-berlin.de> On Tue, 02 Sep 2008 18:15:07 -0400, Derek Martin wrote: >> Classes represent "things", and class names should be nouns. > > Is that a law? It's a common guideline. > Classes are instantiated by invoking their class names as a function > call -- the computing equivalent of a verb. Why then, must they be > named as nouns? Can you not, in fact, have classes which describe (or > model) actions? Wouldn't you name them using verbs if you did? Me personally no. I would use `FooAction` instead of `Foo` or something similar. And if they model an action there must be some way to activate the action but the instances of `Popen` are no actions. There's no way to "execute" a `Popen` instance. > That said, this is the most valid point anyone has made... You should > have made it when the module was being designed. :-D > > My point is, if you don't think Popen is a good name for the class, > that's your opinion, but it is only that: an opinion. Like your opinion that it *is* a good name. > Yet some of you state your case as if it is incontrovertable fact. > I've given a good case as to why it IS a good name (one which I > genuinely support), and disagree as you may, none of the points any of > you have made invalidate or even weaken my argument. Maybe from your POV. Facts: It doesn't use the `popen()` function, it gives something more complex than a simple pipe (no obligatory shell, up to three file objects, more attributes and methods), the function used on Windows under the hood is called `CreateProcess()` not `CreatePipe()`. `Popen` creates a process and represents a proxy object to communicate with it, so `Process` is a good name for that concept/"thing". It's a way more self explaining name, even for people who know the `popen()` function because there's a concept called "process" but none called "popen". Ciao, Marc 'BlackJack' Rintsch From lie.1296 at gmail.com Tue Sep 30 15:30:55 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 30 Sep 2008 19:30:55 +0000 (UTC) Subject: [Tutor] Replacing cmd.exe with custom .py application References: Message-ID: On Tue, 30 Sep 2008 15:09:06 -0400, Ezra Taylor wrote: > Is there something similar to /dev/null on Windows? I think it's called nul REM This is a batch file (.bat) echo "This won't show" > NUL I'm not sure how to use it in python though. From dudeja.rajat at gmail.com Tue Sep 9 19:32:27 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 9 Sep 2008 19:32:27 -0400 Subject: Looking for a Duo - file comparison and a file parser Message-ID: HI, I'm thinking of writing a file comparison utility in python. This utility will work as: 1. Compare 2 files for the differences. Both files contain some numerical results. 2. Generate a common file containing the differences (the same way as 'diff' generate an output) 3. Now, I will parse this file containing differences to check as to how much is the difference of one file from other. So, for this I hope a parser will be required. Is there a utility available that performs similar job ( that some one might have created considering the huge number of users of python) ? Or may be some one has written some parser? Any help is greatly appreciated. Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at subtlety.com Mon Sep 8 02:56:05 2008 From: chris at subtlety.com (catsclaw) Date: Sun, 7 Sep 2008 23:56:05 -0700 (PDT) Subject: How do I set a callback in Python? Message-ID: I can't for the life of me figure out how to set a callback in Python. I have a class, which wraps another class. The second class needs a callback assigned. I don't want to use globals for it. Here's what I'd like to do: class MyWrapper: def get_login(self, username): return self.user, self.pass def __init__(self, user, pass): self.user = user self.pass = pass self.client = Client("connection string") self.client.callback_login = get_login ... but obviously, the Client class, when it calls the callback, doesn't pass a reference to the "self" object. How do I do this? -- Chris From exarkun at divmod.com Sun Sep 28 16:07:19 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 28 Sep 2008 16:07:19 -0400 Subject: standalone buildbot possible/ don't have a remote In-Reply-To: <41a76fd8-47e3-4eb8-b980-11baf8dff0b2@u65g2000hsc.googlegroups.com> Message-ID: <20080928200719.29191.972487259.divmod.quotient.31462@ohm> On Sun, 28 Sep 2008 12:15:50 -0700 (PDT), mark wrote: >I want to start small and setup a buildbot on one machine (no slaves). >I hope this is possible. I assume I only need one master in this case >(without slave config)??? > >from my master.cfg >c['slaves'] = [] > >... (rest of the sample config) > >b1 = {'name': "buildbot-full", ># 'slavename': "bot1name", > 'builddir': "full", > 'factory': f1, > } > >Do I need some configuration that the builder uses the master >instance? I experimented a bit and searched for a similar >configuration so far without success :-(( > No, you have to have a slave. It can run on the same machine, it can run as the same user, but it has to exist. The buildmaster can only tell slaves to do work (of course, this is all written in Python, so it is a simple matter of programming to *make* the buildmaster capable of doing the slave's job, but there's not really any reason to try to do this). Jean-Paul From jbarciela at gmail.com Mon Sep 15 12:53:43 2008 From: jbarciela at gmail.com (Jaime Barciela) Date: Mon, 15 Sep 2008 09:53:43 -0700 (PDT) Subject: component / event based web framework for python? Message-ID: Hello all, I've been surveying the field of python web frameworks for a while but there are just too many so I ask mighty Usenet. Is there a component / event based web framework for python? Something that can abstract you from the request/response mechanism and ideally from html and javascript altogether? As examples -- in other languages -- of what I have in mind: - in java: wingS, GWT, echo (2,3), karora, thinwire, itmill, and maybe others - in javascript: cappuccino - in lisp: weblocks - in smalltalk: seaside, aida/web - in .net: asp.net I would like to be able to write code equivalent to this C# example: ============ namespace WebApplication1 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Button b = new Button(); b.Text = "say hello"; b.Click += Button1_Click; Panel1.Controls.Add(b); } protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "Hello dynamically created on the fly UI !!!"; } } } ============ Thanks Jaime From d3vvnull at gmail.com Fri Sep 26 15:04:35 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 14:04:35 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <20080926123848.98c06cd5.darcy@druid.net> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> Message-ID: <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Doesn't it depend on where and why you intend to execute the code? Obviously some SQL is more at risk for exploit when the input is from the screen on a web page than if you were running parameterized code in a controlled batch environment. Or if you were writing code generators (which is what I happen to do) which won't be run by the general public. Incidentally, couldn't input field edits prevent such exploits prior to interpolation? On Fri, Sep 26, 2008 at 11:38 AM, D'Arcy J.M. Cain wrote: > On Fri, 26 Sep 2008 11:00:59 -0500 > "Michael Mabin" wrote: > > So we can drop a table in an in clause? How is this a use case. > Cartoons > > are funny but actual proof that this example using an in-clause provides > an > > exploit would be more helpful I think. > > I'm not sure what proof you require. If you program such that users > can enter arbitrary stings into your database it is obvious that the > exploit in that cartoon can be used against you. And the point is that > it has nothing to do with IN clauses. It can be any SQL. Go read that > cartoon carefully. It says nothing about IN clauses. Consider; > > "UPDATE student SET name = '%s' WHERE student_id = %s" % (name, id); > > Now set name to "Robert'; DROP TABLE student;" and see what happens if > you feed that to your SQL database. Hell, just put "';" in the string > for fun. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Fri Sep 12 11:52:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 17:52:50 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <20080912111949.19629e78.darcy@druid.net> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> <20080912111949.19629e78.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > Is there ever any advantage to having something as a builtin rather > than as a regular user method? What difference does it make to the > running script? I can see that adding "bar" from module "foo" to > "__builtins__" means that you can use "bar()" instead of "foo.bar()". > Is that the only benefit? basically, yes. in this case, it does make some sense to patch any/all into __builtin__, since they are builtins in a later version. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 15 08:10:04 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 15 Sep 2008 14:10:04 +0200 Subject: Abstract class (irrelevant blethering) In-Reply-To: References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <48CD62B8.7070708@islandtraining.com> Message-ID: <48ce509b$0$14427$426a74cc@news.free.fr> Stephen Horne a ?crit : (snip) > For example, to me the term "property" is basically a trivial design > pattern or an object-oriented principle. I don't really see the need > for the language feature. I can define getter and setter methods all > by myself, and I don't really see the benefit of disguising them as > member variables. The canonical use case for computed attributes is that they let you turn a plain attribute into a computed one if/when the need arises, without breaking client code *nor* having to force all access attributes thru getters/setters righ from the start "just in case". From aacyair at netvision.net.il Mon Sep 1 03:22:06 2008 From: aacyair at netvision.net.il (Michaeli Yair) Date: Mon, 1 Sep 2008 10:22:06 +0300 Subject: file->Grid->file Message-ID: Hi all, I imported a comma seperated data to PyGridTableBase which is a abstract Grid, I parse and display the information. After update i want to save it back to the comma seperated file, eith the same filename. any suggestions how to do that ? do you know any reference to this subject ? YM From fredrik at pythonware.com Sat Sep 6 07:11:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Sep 2008 13:11:04 +0200 Subject: Cancel instance create In-Reply-To: <1220697080.48c25bf890ade@www.inbox.lv> References: <1220697080.48c25bf890ade@www.inbox.lv> Message-ID: Aigars Aigars wrote: > I want MyClass to perform some tests and if them fail, I do not want > instance to be created. > > But in code I wrote instance is created and also has parameters, that it > should not have in case of tests failure. > > Is there a way to perform tests in MyClass.__init__ and set instance to > None without any parameters? if you want construction to fail, raise an exception. ... def __init__(self): self.param = "spam" Test = False if Test: # please don't use explicit tests for truth print "Creating instance..." else: raise ValueError("some condition failed") (pick an exception class that matches the actual error, or create your own class if necessary) From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 04:09:06 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Tue, 16 Sep 2008 01:09:06 -0700 Subject: Cross-platform socket.getsockopt and struct.unpack (or socket timeout)? In-Reply-To: References: Message-ID: Fredrik Lundh wrote: > Heikki Toivonen wrote: > >> Is there a cross-platform way of doing what the M2Crypto code is >> attempting to do? > > calling the socket object's settimeout() method? I would suspect that is not strictly equivalent to what the old code is doing, though, because it seems you can set read and write timeouts separately using the socket options directly. -- Heikki Toivonen From support.desk.ipg at gmail.com Wed Sep 24 12:25:02 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Wed, 24 Sep 2008 11:25:02 -0500 Subject: More regex help In-Reply-To: References: Message-ID: <2F273EFF4B21468A85BE4277DA844C75@office.ipglobal.net> I am working on a python webcrawler, that will extract all links from an html page, and add them to a queue, The problem I am having is building absolute links from relative links, as there are so many different types of relative links. If I just append the relative links to the current url, some websites will send it into a never-ending loop. What I am looking for is a regexp that will extract the root url from any url string I pass to it, such as 'http://example.com/stuff/stuff/morestuff/index.html' Regexp = http:example.com 'http://anotherexample.com/stuff/index.php Regexp = 'http://anotherexample.com/ 'http://example.com/stuff/stuff/ Regext = 'http://example.com' From invalid at invalid Wed Sep 17 12:48:27 2008 From: invalid at invalid (Grant Edwards) Date: Wed, 17 Sep 2008 11:48:27 -0500 Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> Message-ID: On 2008-09-17, r0g wrote: > r0g at steppa:~/Desktop/py$ ls > kickstart.py kickstart.py~ kicktest.py kicktest.py~ > r0g at steppa:~/Desktop/py$ kickstart.py > bash: kickstart.py: command not found > > Any ideas why this might be? Yes. > A path thing? Yes. Linux systems generally don't have the current directory in the PATH that's searched for executbles (it's regarded as a rather serious security problem if you do). Try doing this: ./kickstart.py -- Grant Edwards grante Yow! Look into my eyes and at try to forget that you have visi.com a Macy's charge card! From bdesth.quelquechose at free.quelquepart.fr Thu Sep 18 14:16:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 18 Sep 2008 20:16:25 +0200 Subject: improving a huge double-for cycle In-Reply-To: <4f55d49g9086nhob3ol67uahbr19o1hjiu@4ax.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <4f55d49g9086nhob3ol67uahbr19o1hjiu@4ax.com> Message-ID: <48d2b6e7$0$3789$426a74cc@news.free.fr> Harald Luessen a ?crit : (snip) > I did not test the syntax, > but here is an idea with sorted lists. > It should be O(NlogN). > > def sk(x): > return x.coordinates[0] > > IN.sort(key=sk) > for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > else: > break The syntax is ok. Not the results, or so it seems (cf my other post in this thread). But you still get a good point for noticing the redundant tests in the inner loop !-) From bearophileHUGS at lycos.com Mon Sep 8 10:01:19 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 8 Sep 2008 07:01:19 -0700 (PDT) Subject: Dictionaries and loops References: <48c52c54$0$16982$426a74cc@news.free.fr> Message-ID: <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> Bruno Desthuilliers: > This doesn't look like a CSV file at all... Is that what you actually > have in the file, or what you get from the csv.reader ??? I presume you are right, the file probably doesn't contain that stuff like I have assumed in my silly/useless solutions :-) Bye, bearophile From __peter__ at web.de Wed Sep 3 03:15:17 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2008 09:15:17 +0200 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: hofer wrote: > Something I have to do very often is filtering / transforming line > based file contents and storing the result in an array or a > dictionary. > > Very often the functionallity exists already in form of a shell script > with sed / awk / grep , . . . > and I would like to have the same implementation in my script > > What's a compact, efficient (no intermediate arrays generated / > regexps compiled only once) way in python > for such kind of 'pipe line' > > Example 1 (in bash): (annotated with comment (thus not working) if > copied / pasted > cat file \ ### read from file > | sed 's/\.\..*//' \ ### remove '//' comments > | sed 's/#.*//' \ ### remove '#' comments > | grep -v '^\s*$' \ ### get rid of empty lines > | awk '{ print $1 + $2 " " $2 }' \ ### knowing, that all remaining > lines contain always at least > \ ### two integers calculate > sum and 'keep' second number > | grep '^42 ' ### keep lines for which sum is 42 > | awk '{ print $2 }' ### print number > thanks in advance for any suggestions of how to code this (keeping the > comments) for line in open("file"): # read from file try: a, b = map(int, line.split(None, 2)[:2]) # remove extra columns, # convert to integer except ValueError: pass # remove comments, get rid of empty lines, # skip lines with less than two integers else: # line did start with two integers if a + b == 42: # keep lines for which the sum is 42 print b # print number The hard part was keeping the comments ;) Without them it looks better: import sys for line in sys.stdin: try: a, b = map(int, line.split(None, 2)[:2]) except ValueError: pass else: if a + b == 42: print b Peter From mccredie at gmail.com Tue Sep 30 19:26:43 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 30 Sep 2008 16:26:43 -0700 (PDT) Subject: Wait or not? References: <34809165-9c72-46b3-996c-4bd55451505d@e53g2000hsa.googlegroups.com> Message-ID: On Sep 30, 4:20?pm, Eric wrote: > I've been wanting to learn Python for a while now but I can't decide > on whether to wait for Python 3's final release and learn it or just > go ahead and learn 2.x. Would it be hard to make the transition being > a noob? It shouldn't be a hard transition. I would recommend learning 2.x anyway. You are likely to want to use 3rd party modules (or you will anyway). You won't want to wait for module support to be added in 3.0. The 2.x series isn't going to go away for quite a while. I think they are planning to continue to do releases all the way up to 2.9 or so. Even then, the biggest thing that a new user is going to run into is `print("stuff")` vs. `print "stuff"`. Matt From steve at REMOVE-THIS-cybersource.com.au Thu Sep 18 09:11:07 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 13:11:07 GMT Subject: PEP proposal optparse References: Message-ID: <00e24d6e$0$20331$c3e8da3@news.astraweb.com> On Thu, 18 Sep 2008 03:37:54 -0700, James wrote: > Hi, > > I would like to know your thoughts on a proposed change to optparse that > I have planned. It is possible to add default values to multiple options > using the set_defaults. However, when adding descriptions to options the > developer has to specify it in each add_option() call. This results in > unreadable code such as: [snip] I don't find it unreadable at all. I find it very helpful to have the help text associated right there with the rest of the option, instead of hidden in a different function call. [...] > Help descriptions can often be quite long and separating them in this > fashion would, IMHO, be desirable. If the help descriptions are so long that they are a problem, then the solution I would choose is to put them in their own module, then do something like this: import docs parser.add_option('-q', '--quiet', action="store_false", dest='verbose', help=docs.quiet) parser.add_option('-o', '--output', type='string', dest='castordir', metavar='
', help=docs.output) etc. -- Steven From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 17 10:08:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 17 Sep 2008 16:08:57 +0200 Subject: Python OOP advice In-Reply-To: <87fxnz3q5i.fsf@benfinney.id.au> References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> <87fxnz3q5i.fsf@benfinney.id.au> Message-ID: <48d10f78$0$9484$426a34cc@news.free.fr> Ben Finney a ?crit : > Simon Hibbs writes: > >> Orriginaly I thought I'd need to have a hull object which contains >> component objects, but the component objects need access to members >> of the hull object (e.g. the hull size) so that looks messy to >> implement. > > Was it as messy as this:: > > class ShipHull(object): > def __init__(self, size): > self.components = dict() > self.size = size > > class ShipComponent(object): > def __init__(self, name, hull): > self.name = name > self.hull = hull > >> I have defined a base class Component with a class member variable >> 'hull_size' so that all components can see the hull size. > > It seems to me the hull is an attribute of the component, and the size > is an attribute of the hull. Why would the hull size be a *class* > attribute? > >> I've then got two child classes called Fixed_Component and Percent >> _Component that implement their mass, mass_percent and cost >> properties appropriately for their type. > > class FixedShipComponent(ShipComponent): > def _get_mass(self): > return calculation_foo(self.hull.size) > mass = property(_get_mass) > > def _get_cost(self): > return calculation_bar(self.hull.size) > cost = property(_get_cost) > > class PercentShipComponent(ShipComponent): > def _get_mass(self): > return calculation_spam(self.hull.size) > mass = property(_get_mass) > > def _get_cost(self): > return calculation_eggs(self.hull.size) > cost = property(_get_cost) Or use the strategy pattern (dummy example, don't have time to read your specs !-): class FixedMassCostStrategy(object): def get_mass(self, hull): return calculation_foo(hull.size) def get_cost(self): return calculation_bar(hull.size) class PercentMassCostStrategy(object): def get_mass(self, hull): return calculation_spam(hull.size) def get_cost(self): return calculation_eggs(hull.size) class ShipComponent(object): def __init__(self, name, hull, masscost_strategy): self.name = name self._hull = hull # implementation detail self._strategy = masscost_strategy mass = property(lambda self: self._strategy.get_mass(self._hull)) cost = property(lambda self: self._strategy.get_cost(self._hull)) From hussainsaiger at gmail.com Tue Sep 2 10:40:59 2008 From: hussainsaiger at gmail.com (hussainsaiger at gmail.com) Date: Tue, 2 Sep 2008 07:40:59 -0700 (PDT) Subject: Using NLTK in Java References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> <6i1hu9FnvcngU1@mid.uni-berlin.de> <6i21jaFomilbU1@mid.uni-berlin.de> Message-ID: On 1 Sep, 16:21, "Diez B. Roggisch" wrote: > hussainsai... at gmail.com wrote: > > On 1 Sep, 11:55, "Diez B. Roggisch" wrote: > >> hussainsai... at gmail.com schrieb: > > >> > I am trying to convert a python module (that contains the use of > >> > NLTK.Corpus) by jythonc. It is not able to include nltk dependencies > >> > within the java class it creates. So when i use this class in java, it > >> > fails to recognize nltk. Can anyone please let me know how should i > >> > use nltk in python/jython modules so i can use in Java. > > >> If there are any binary dependencies, you are out of luck. It won't > >> work. You would need to write a RPC-Server then, with technologies such > >> as XMLRPC or CORBA. > > >> Diez > > > So does that mean that Jython does not support nltk uptil now. I ask > > this because when I try to import nltk in Jython (which is assumed to > > replace Python), i get the same error. Its just nltk that I am not > > able to use. The rest of the jython functions and libraries work fine > > within Java. > > I don't know for sure - how about you post the error-message? Otherwise we > can't assess the problem. > > Diez- Hide quoted text - > > - Show quoted text - Hi, What i did was create a python file as: import nltk from java.util import Random class NLPPresentation(Random): def nextDouble(self): return 1 def TagByBrown(self,sent): "@sig public String[] TagByBrown(String sent)" brown_a = nltk.corpus.brown.tagged_sents(categories='a') bigram_tagger = nltk.BigramTagger(brown_a, cutoff=0) lst = bigram_tagger.tag(sent.split()) return lst I processed the following code through jythonc compiler to form a JAR file. I then imported this jar file into java ide (Java Builder). I then wrote the following program in java to access this python class: import org.python.core.PyException; import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.util.PythonInterpreter; import java.util.Random; import org.nltk.*; import org.nltk.mallet.*; public class SimpleEmbedded extends NLPPresentation{ public static void main(String[] args) throws PyException { SimpleEmbedded so = new SimpleEmbedded(); String s = "he is a boy"; so.Call(s); } public void Call(String s) { String[] arr = TagByBrown(s); System.out.println(arr[1]); } } When i compile the above java code, i get the following error: Exception in thread "main" Traceback (innermost last): File "C:\jython2.2.1\NLPPresentation.py", line 0, in main ImportError: no module named nltk Your comments are highly appreciated. From uzmanajmal at gmail.com Wed Sep 17 05:05:41 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Wed, 17 Sep 2008 09:05:41 +0000 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: <3f0d61c40809150606w2b8035b3v2eba46e44cdee9a7@mail.gmail.com> References: <3f0d61c40809150606w2b8035b3v2eba46e44cdee9a7@mail.gmail.com> Message-ID: Actually my problem is a little different. I have a .pem format file which contain my public and private key both and i want to get only the public key from that file as a string. I already have done that by just parsing the said file but if there is some direct way i will b glad to know. @marco i don't have the string at all. Infact i want the string @Toivonen i tried as_pem but it gives me some private key after doing some thing with the file i pass to it as argument which is even not the private key i have in my file. Also if i set cipher=None, even then its result is same Thanks by the way marco and Toivonen for trying to help :) On Mon, Sep 15, 2008 at 1:06 PM, Marco Bizzarri wrote: > On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal wrote: > > Hi, > > > > I have a M2Crypto.RSA.RSA instance that contain my public-key. I want > that > > key as string. Is there any way to convert the said instance into string? > > > In case you want to write the pub-key to a file, you can use save_pub_key > > def save_pub_key(self, file): > """ > Save the public key to a file in PEM format. > > @type file: string > @param file: Name of file to save key to. > """ > > Regards > Marco > -- > Marco Bizzarri > http://notenotturne.blogspot.com/ > http://iliveinpisa.blogspot.com/ > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Fri Sep 12 04:23:50 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 09:23:50 +0100 Subject: rss feed generation In-Reply-To: <48CA217A.60708@timgolden.me.uk> References: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> <32cabba0809111835g2984c463y2c4b689605f8362e@mail.gmail.com> <48CA217A.60708@timgolden.me.uk> Message-ID: <48CA2716.2070608@timgolden.me.uk> Tim Golden wrote: > Walter Cruz wrote: >> On Tue, Sep 9, 2008 at 9:35 PM, alex23 wrote: >>> On Sep 10, 7:30 am, "Blake Garner" wrote: >>>> I'm looking for suggestions on how to approach generating rss feed >>>> .xml files using python. What modules to people recommend I start >>>> with? > > I just rolled something with ElementTree. No idea how it > stacks up against validity checks, but it seems to be > accepted by a couple of standard feed readers. [... snip messy code ...] Well that didn't come out very well. If anyone's interested, I've dropped the module here: http://timgolden.me.uk/python/downloads/feeder.py TJG From deets at nospam.web.de Mon Sep 15 13:23:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 19:23:24 +0200 Subject: component / event based web framework for python? In-Reply-To: References: Message-ID: <6j7k0cF1sf3lU1@mid.uni-berlin.de> Jaime Barciela schrieb: > Hello all, > > I've been surveying the field of python web frameworks for a while but > there are just too many so I ask mighty Usenet. > > Is there a component / event based web framework for python? Something > that can abstract you from the request/response mechanism and ideally > from html and javascript altogether? You might consider taking a look at tosca-widgets, which are used to create re-usable components of javascript, css and html. They can be used in any WSGI-capable environment, but TurboGears and Pylons are best known for incorporating them. http://toscawidgets.org/documentation/ Diez From kay.schluehr at gmx.net Fri Sep 26 04:30:51 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 26 Sep 2008 01:30:51 -0700 (PDT) Subject: How to read a jpg bytearray from a Flash AS3 file References: Message-ID: <8ad152c7-606b-4a68-aba2-c8dccc0e8b8a@b1g2000hsg.googlegroups.com> On 26 Sep., 08:47, rsgallo... at gmail.com wrote: > I'm trying to save an image from a Flash AS3 to my server as a jpg > file. I found some PHP code to do this, but I want to do this in > Python. I'd expect you use AS3 to save the image file ( just looking at Adobes AS3 docs on how this works ) and load it with PIL if you want to post- process it in Python: http://www.pythonware.com/products/pil/ From lekin2 at llnl.gov Thu Sep 18 13:07:11 2008 From: lekin2 at llnl.gov (April Lekin) Date: Thu, 18 Sep 2008 10:07:11 -0700 Subject: Tkinter Bold Text Message-ID: <76vncf$1ajav3@smtp.llnl.gov> Is there any way to highlight, bold or change the color of one word in a variable to be displayed on a Tkinter GUI? Like: material = "Plastic" introVal = "This report describes the construction of the %s." % (material) this is what I want: This report describes the construction of the Plastic. Plastic is Bold or Blue or Green Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From brianlong at cox.net Mon Sep 8 13:07:25 2008 From: brianlong at cox.net (brianrpsgt1) Date: Mon, 8 Sep 2008 10:07:25 -0700 (PDT) Subject: Problems downloading and installing win32api Message-ID: <968dca58-0172-4953-b8d6-9610f0570fe8@s20g2000prd.googlegroups.com> I have attempted downloading and installing several different version of the win32api from Source Forge, however, each time I try to install I get the following error message: "Only part of a ReadProcessMemory or WriteProcessMemory request was completed" This occurred with the following files: pywin32-212.win32-py2.4.exe pywin32-212.win32-py2.5.exe pywin32-212.win32-py2.6.exe I am using WinXP SP2. Any assistance on getting this downloaded and installed would be great. Thanks B From stefan_ml at behnel.de Thu Sep 4 13:59:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 04 Sep 2008 19:59:13 +0200 Subject: Xpath for HTML processing In-Reply-To: References: Message-ID: <48c021f1$0$19233$9b4e6d93@newsspool4.arcor-online.net> Astley Le Jasper wrote: > Can anyone suggest something inthat can process an XPath like the > following: > > "/html/body/table[2]/tbody/tr/td[5]/table/tbody/tr[3]/td/table[3]/ > tbody/tr[5]/td" [skipping the obvious joke answer to your question] In case you're asking for a tool that can process HTML using XPath, try lxml.html. http://codespeak.net/lxml Stefan From paulprobert at sbcglobal.net Sat Sep 6 20:55:50 2008 From: paulprobert at sbcglobal.net (Paul Probert) Date: Sat, 06 Sep 2008 19:55:50 -0500 Subject: wxPython problem In-Reply-To: References: <48C24D3C.7060306@gmail.com> Message-ID: Peter Anderson wrote: > Stef Mientki said: In PyScripter, you should run wxPython in the plain > remote machine (not the wxPython remote),and you should set "reset > before run flag" or reset the remote machine each time yourself. > > Stef, > > Thanks for the help! It has taken several hours to find and install the > correct version of Rpyc (which is required to run the remote Python > engine but it now seems to be working fine. And the "Reinitialise the > Python engine {Alt]+[F2]" does need to be done between script runs. > Given all that, the script now runs multiple times in PyScripter. The > script still only runs ONCE in IDLE but I can live with that. > > In case others find this message from a search; I am using Python 2.5.2 > and it requires rpyc-2.60.zip from the Rpyc download page (see > http://rpyc.wikispaces.com/ click on the "Download" link and make sure > you select the "main" link under the "Packages" column at Sourceforge. > You will be shown a list of Rpyc versions. For Python 2.5.2 choose > Relese "2.60". This will save you the several hours its cost me. > > Thanks again Stef. > > Regards, > Peter wxPython never runs well in a program running under Tk, such as IDLE. Something about competing GUI's. If you want a replacement, you can try pycrust or one of its brethren, which ship with wxpython. Paul Probert From jlnicolson at gmail.com Thu Sep 18 07:02:07 2008 From: jlnicolson at gmail.com (James Nicolson) Date: Thu, 18 Sep 2008 13:02:07 +0200 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: Perhaps it is better to keep descriptions short and store longer descriptions elsewhere, but there are many programs that have long descriptions, for example try: ls --help (at least on my machine a lot of these descriptions are quite long). 2008/9/18 James Mills : > Hi James, > > I can't say I really agree with your > proposal. I tend to keep the help > descriptions of my options short > and concise and to the point. > > Also, one must use the language's > features (indentation) to your advantage, > as doing so ensure readability. > > For example (from my bhimport tool): > > > def parse_options(): > """parse_options() -> opts, args > > Parse any command-line options given returning both > the parsed options and arguments. > """ > > parser = optparse.OptionParser(usage=USAGE, version=VERSION) > > parser.add_option("", "--date-format", > action="store",type="str", default="%d/%m/%Y", > dest="dateFormat", > help="date format string") > parser.add_option("", "--time-format", > action="store", type="str", default="%H:%M:%S", > dest="timeFormat", > help="time format string") > parser.add_option("", "--datetime-format", > action="store", type="str", default="%H:%M:%S %d/%m/%Y", > dest="datetimeFormat", > help="datetime format string") > > opts, args = parser.parse_args() > > if len(args) < 2: > parser.print_help() > raise SystemExit, 1 > > return opts, args > > > As you can see (as long as you're > reading this in fixed-width fonts) > it _is_ very readable. > > cheers > James > > On 9/18/08, James wrote: >> Hi, >> >> I would like to know your thoughts on a proposed change to optparse >> that I have planned. It is possible to add default values to multiple >> options using the set_defaults. However, when adding descriptions to >> options the developer has to specify it in each add_option() call. >> This results in unreadable code such as: >> >> parser.add_option('-q', '--quiet' , action="store_false", >> dest='verbose', >> help = 'Output less information') >> parser.add_option('-o', '--output' , type='string', >> dest='castordir' , metavar='' , >> help = 'specify the wanted CASTOR directory where to store the >> results tarball') >> parser.add_option('-r', '--prevrel' , type='string', >> dest='previousrel' , metavar='' , >> help = 'Top level dir of previous release for regression >> analysis' ) >> >> The same code could become much more readable if there was an >> equivalent method of set_defaults for the description/help of the >> option. The same code could then become: >> >> parser.set_description( >> verbose = 'Output less information', >> castordir = 'specify the wanted CASTOR directory where >> to store the results tarball', >> previousrel = 'Top level dir of previous release for >> regression analysis') >> >> parser.add_option('-q', '--quiet' , action="store_false", >> dest='verbose') >> parser.add_option('-o', '--output' , type='string', >> dest='castordir' , metavar='' ) >> parser.add_option('-r', '--prevrel' , type='string', >> dest='previousrel' , metavar='' ) >> >> Help descriptions can often be quite long and separating them in this >> fashion would, IMHO, be desirable. >> >> Kind Regards, >> James Nicolson >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > -- > -- > -- "Problems are solved by method" > From harish.shastry at gmail.com Mon Sep 15 06:06:55 2008 From: harish.shastry at gmail.com (Harish K Vishwanath) Date: Mon, 15 Sep 2008 15:36:55 +0530 Subject: When do I get "multiple bases have instance lay-out conflict" error? Message-ID: <78f8019c0809150306t47090464vaeed3b356e76ab5b@mail.gmail.com> Hello all, When do we actually see the error : TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict I searched the web and I could not find a correct guideline as to when such an error could arise. One of the places said that "A new style class cannot inherit from more than one python built-in class". That is., >>> class A(dict,list): ... pass wouldn't work. But, I have an instance where I am getting the above error even when I dont inherit from multiple built-in types. >>> sys.__version__ Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '__version__' >>> sys.version '2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)]' Using Py 2.5.2 >>> import persistent >>> persistent.Persistent.__bases__ (,) Persistent is ZOPE/ZODB implementation. It inherits no built-in types >>> Exception.__bases__ (,) >>> BaseException.__bases__ (,) Exception also inherits no built-in types. >>> class A(Exception,persistent.Persistent): ... pass ... Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict Still declaration of class A fails. Any idea? What is the exact rule when python throws up " multiple bases have instance lay-out conflict" error? Thanks in advance for the help. -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Thu Sep 11 05:08:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 11:08:50 +0200 Subject: Adding environment variables to bash. In-Reply-To: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> Message-ID: aditya shukla wrote: > Can i add any environment variable to bash from my python script? so > that when i use env command then i can see that environment variable. not if you run the script from the shell. when a process starts, it gets a *copy* of the parent's environment. it can modify that copy, but it cannot modify the variables in the parent. From sh006d3592 at blueyonder.co.uk Sat Sep 20 22:23:14 2008 From: sh006d3592 at blueyonder.co.uk (Stephen Horne) Date: Sun, 21 Sep 2008 03:23:14 +0100 Subject: explain slice assignment to newb References: Message-ID: <5lbbd41dq0tuot2tdkrmgjvbldb72n1rsf@4ax.com> On Sat, 20 Sep 2008 14:20:20 -0700 (PDT), Andrew wrote: >please explain this behavior to a newb: > >>>> a = [1,2,3,4] >>>> b = ["a","b","c","d"] >>>> a[0:2] = b[0:2] The slice [0:2] represent positions 0 <= x < 2 Replaces the [1, 2] from [1, 2, 3, 4] with ['a', 'b'] Result: a = ['a', 'b', 3, 4] >>>> b[2:4] = a[2:4] The slice [2:4] represent positions 2 <= x < 4 Replaces the ['c', 'd'] from ['a', 'b', 'c', 'd'] with [3, 4] Result: b = ['a', 'b', 3, 4] >>>> a >['a', 'b', 3, 4] >>>> b >['a', 'b', 3, 4] Correct From steve at holdenweb.com Mon Sep 29 13:34:41 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 13:34:41 -0400 Subject: os.path.exists() function does not work for http paths In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > Hi, > > I have used os.path.exists() many a times for any file system paths in > local system. But this does not seem to work for an Http path. > > e.g: > > > To check is the Results folder exists at the following path, I do: > > > if not os.path.exists("http://subversion.myCom.com/Testing/Results"): > print 'Path does not exist' > > > This always prints the above print statements whether or not the Results > folder exists or not. > > Is there any such function to check existence of files. / folder at Http > paths? > You could use one of the URL libraries. The os.path module is for dealing with the local filesystem. The absence of any exception from f = urllib.urlopen("http://www.google.com/webhp/") is a good indication that the addressed page "exists" (but remember that the web is a virtual address space, so it doesn't necessarily mean that there's a real file or directory object behind ot). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From simon at mullis.co.uk Thu Sep 18 11:56:08 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Thu, 18 Sep 2008 17:56:08 +0200 Subject: dict generator question In-Reply-To: References: Message-ID: <23d7e1bb0809180856l5ca1409bx929690a4b749f942@mail.gmail.com> Haha! Thanks for all of the suggestions... (I love this list!) SM 2008/9/18 : > On Sep 18, 10:54 am, "Simon Mullis" wrote: >> Hi, >> >> Let's say I have an arbitrary list of minor software versions of an >> imaginary software product: >> >> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] >> >> I'd like to create a dict with major_version : count. >> >> (So, in this case: >> >> dict_of_counts = { "1.1" : "1", >> "1.2" : "2", >> "1.3" : "2" } >> >> Something like: >> >> dict_of_counts = dict([(v[0:3], "count") for v in l]) >> >> I can't seem to figure out how to get "count", as I cannot do x += 1 >> or x++ as x may or may not yet exist, and I haven't found a way to >> create default values. >> >> I'm most probably not thinking pythonically enough... (I know I could >> do this pretty easily with a couple more lines, but I'd like to >> understand if there's a way to use a dict generator for this). >> >> Thanks in advance >> >> SM >> >> -- >> Simon Mullis > > Considering 3 identical "simultpost" solutions I'd say: > "one obvious way to do it" FTW :-) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Simon Mullis _________________ simon at mullis.co.uk From jlnicolson at gmail.com Thu Sep 18 06:37:54 2008 From: jlnicolson at gmail.com (James) Date: Thu, 18 Sep 2008 03:37:54 -0700 (PDT) Subject: PEP proposal optparse Message-ID: Hi, I would like to know your thoughts on a proposed change to optparse that I have planned. It is possible to add default values to multiple options using the set_defaults. However, when adding descriptions to options the developer has to specify it in each add_option() call. This results in unreadable code such as: parser.add_option('-q', '--quiet' , action="store_false", dest='verbose', help = 'Output less information') parser.add_option('-o', '--output' , type='string', dest='castordir' , metavar='' , help = 'specify the wanted CASTOR directory where to store the results tarball') parser.add_option('-r', '--prevrel' , type='string', dest='previousrel' , metavar='' , help = 'Top level dir of previous release for regression analysis' ) The same code could become much more readable if there was an equivalent method of set_defaults for the description/help of the option. The same code could then become: parser.set_description( verbose = 'Output less information', castordir = 'specify the wanted CASTOR directory where to store the results tarball', previousrel = 'Top level dir of previous release for regression analysis') parser.add_option('-q', '--quiet' , action="store_false", dest='verbose') parser.add_option('-o', '--output' , type='string', dest='castordir' , metavar='' ) parser.add_option('-r', '--prevrel' , type='string', dest='previousrel' , metavar='' ) Help descriptions can often be quite long and separating them in this fashion would, IMHO, be desirable. Kind Regards, James Nicolson From dthole at gmail.com Tue Sep 9 14:55:47 2008 From: dthole at gmail.com (David Thole) Date: Tue, 9 Sep 2008 11:55:47 -0700 (PDT) Subject: How to record audio from Python on Mac? References: Message-ID: <74b0be47-d2c4-4003-a734-35ff9813ef90@l43g2000hsh.googlegroups.com> On Sep 9, 1:11?pm, Kevin Walzer wrote: > s... at pobox.com wrote: > > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > > casting a broader net.) > > > Can I easily control audio record/playback from Python on my Mac? ?I know > > zip about audio recording or about Apple APIs via Python. ?Pointers to > > simple examples would be much appreciated. > > > Thanks, > > > Skip > > You can probably access this functionality via PyObjC--it provides > access to the Cocoa frameworks. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Another option you could use is calling Applescript from the command line, to open, execute, and handle audio. An easy example of this is with iTunes actually. Once you get iTunes down, doing this for other apps should be easy (if they have applescript bindings): http://www.macosxhints.com/article.php?story=20011108211802830 You could probably also do what Kevin recommends, but depending on your needs, this may be a whole lot more simple. -David Thole http://www.thedarktrumpet.com From m_palmer45 at yahoo.ca Mon Sep 15 19:37:29 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 15 Sep 2008 16:37:29 -0700 (PDT) Subject: Parallelising code References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: <35652fcc-cc31-4e53-8069-6a696cdd0591@z66g2000hsc.googlegroups.com> On Sep 15, 12:46 pm, "psaff... at googlemail.com" wrote: > I have some file processing code that has to deal with quite a lot of > data. I have a quad core machine, so I wondered whether I could take > advantage of some parallelism. > > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? > > - Is list.append() thread safe? (not sure if this is the right term) > what I mean is, can two separate processors file a point in the same > list at the same time without anything horrible happening? Do I need > to do anything special (mutex or whatever) to make this happen, or > will it happen automatically? > > Thanks in advance for any guidance, > > Peter Look at http://pypi.python.org/pypi/processing From d3vvnull at gmail.com Sat Sep 27 19:52:44 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sat, 27 Sep 2008 18:52:44 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DEA603.9020507@wildenhain.de> References: <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> Message-ID: <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> I'm exhausted, so I'll just shut up about this after a few final words. 1. "edits" is used in data warehousing to describe data scrubbing or filtering of fields in records that are used as input sources for loading into data warehouses. It's a term that goes way back to batch processing on the mainframe, so it's been used this way for a long time. Sometimes we use 'validation' interchangeably with 'edit' but our use of validation usually involves a check of input data against business rules and not type or range checking which we consider 'edits'. So maybe you're not used to hearing the term used this way, but it is a variation perhaps of what you're used to. 2. The data warehousing world is quite different from the web world in many respects. I appreciate the fact that web application developers must always be mindful of the 'barbarians at the gates' but our batch environments are locked down, especially our databases. We have secured batch IDs. Our programs are run using an automated schedule. Our databases are secured to begin with so not even our batch IDs have alter, create or drop permissions on the database. There's no way this exploit would ever enter this environment because those servers aren't accessible through the web or online. 3. When you say 'in python we don not fear that' it's curious, because it assumes that all Python users must think as you do. And yet, clearly I don't think as you do. I really like this language and praise the Netherlands each day I wake up that they gave us someone as brilliant as Guido to make programming fun and not such a chore. But I think there are valid reasons for taking different approaches to security, data validation and dare I say it -- field editing -- despite the claims of many who say that in Python - TOOWTDI. 4. It's also curious that I was obliged to state my assumptions about batch programming vs. web programming. There is nothing in the OP to suggest that the problem was related to web programming. It's a question about how to interpolate the values in a list with format specifiers in a SQL statement. Still, if this list is not the result of user input but was derived within the body of the program, which by itself has no malicious intent, are we still going to code this as if it were input by a user that might be a hacker? This seems retarded and paranoid to me. And where in that post does it say that the list is from web input? Although to be fair maybe most of the Python community is doing web development. Thanks for the stimulating and educational discussion. On Sat, Sep 27, 2008 at 4:30 PM, Tino Wildenhain wrote: > Hi, > > Michael Mabin wrote: > >> If the inputs are edited prior to the construction of the string and these >> fields are used for more than one update then it's not an exploit. It's >> simply a matter not repeating yourself when coding. >> > > In python we do not fear that. > > In this particular case too, we're talking about a list of integers that >> gets inserted into a string. If the list is validated prior to its >> > > Its a list, if it indeed has integers in it is uncertain. It is so very > easy to check that that it doesnt even make sense to write such lengthy > emails about how bad you want to avoid it. Just do it. And even more so > if you are telling others how to do things make sure they do not so easy > shoot themselfes in their feet. > > insertion into an SQL statement then there is no exploit. If I write a >> batch program (not a web program) that retrieves this list of integers from >> other sources and validates the data prior to using it in an SQL statement, >> that should be sufficient. >> > > This might be well true but if you have a look at your original > contribution you see that all these your asumtions are just not in. > > As far as wrong and right is concerned. I think it's more about doing what >> is appropriate according to the circumstances. As a rule you >> > > If its easy to do, why not just doing it correctly (or robust) in all > circumstances to just avoid overlooking a case? > > should only code what is appropriate for the circumstances. If it's >> appropriate to code more simply without introducing unnecessary complexity >> you should do so. >> > > But you did not tell us about your asumtations about the circumstances. > > I work in the data warehousing ETL world, where we have to perform field >> edits or transformations to load source data into databases. If I'm >> > > Thats wrong. You do not "edit" fields. You have a validating type path and > _always_ the database is most authoritative about what it accepts. > Any other concept is just wrong and outright dangerous. There are > many examples of how this works out (just check bugtraq) > > already performing edits on these fields and if these fields are going to >> be used for more updates downstream, it's wasteful to perform them again >> when I build the SQL insert with the list and execute it. >> > > I still don't know what you mean by "edit" ;) If you mean filter out > special chars with for example replace("bad stuff","good stuff") check > your idea again, this is not going to work. (google for default permit) > > Finally, whatever happened to the practice of granting appropriate >> privileges to IDs that perform database operations? Shouldn't the person >> acting in the capacity of DBA ensure that the user updating or retrieving >> data from the database does not have DROP, ALTER, or CREATE privileges on >> that database? >> > > This of course is another layer which should be added - but you would > not need to - you edited the fields, right? ;) > > Sorry, it was not meant to put you to the wall but you insist so much > on your still dangerous solution while top posting the hell out of > this thread I just could not ignore it ;) > > T. > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Fri Sep 26 20:53:59 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 26 Sep 2008 17:53:59 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> <00b839d9-fe35-4478-aba2-0435fbf285e8@m36g2000hse.googlegroups.com> <00ed6d83$0$20666$c3e8da3@news.astraweb.com> Message-ID: <4039a6ac-f418-471b-8e21-3863adbe0d36@f63g2000hsf.googlegroups.com> On Sep 26, 7:43?pm, Steven D'Aprano wrote: > On Fri, 26 Sep 2008 14:54:36 -0700, Carl Banks wrote: > > However, it seems from the rest of your comments that speed is your main > > concern. ?Last time someone reported __slots__ didn't make a big > > difference in access time, but it probably would speed up creating > > objects a bit. ? > > Carl probably knows this already, but for the benefit of the Original > Poster: > > __slots__ is intended as a memory optimization, not speed optimization. > If it speeds up creation, that's a serendipitous side-effect of using > less memory. No, it'd be a serendipitous side-effect of not having to take the time to create a dict object, which is quite a bit more of a direct cause. It might still end up being slower (creating slot descriptors might take more time for all I know) but it's more than just an effect of less memory. Carl Banks From fredrik at pythonware.com Sat Sep 20 12:37:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 18:37:14 +0200 Subject: How to make a reverse for loop in python? In-Reply-To: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Alex Snast wrote: > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) use range with a negative step: for i in range(10-1, -1, -1): ... or just reverse the range: for i in reversed(range(10)): ... (the latter is mentioned in the tutorial, and is the second hit if you google for "python reverse for loop") From bdesth.quelquechose at free.quelquepart.fr Mon Sep 1 12:18:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 18:18:57 +0200 Subject: Some problems with classes In-Reply-To: References: Message-ID: <48bc31e1$0$26548$426a34cc@news.free.fr> Chris Rebert a ?crit : > On Sun, Aug 31, 2008 at 6:39 PM, ssecorp wrote: >> Why/how is it possible to add variables like this? I don't understand >> this mechanism: >> http://docs.python.org/tut/node11.html#SECTION0011330000000000000000 > > Under the covers, Python objects are implemented using dictionaries, Not necessarily. > so adding an attribute just adds a new key-value pair to the object's > internal dictionary (which, incidentally, you can access as > someobj.__dict__). Idem. From ldo at geek-central.gen.new_zealand Fri Sep 26 05:12:37 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 21:12:37 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: In message , Steven D'Aprano wrote: > On Fri, 26 Sep 2008 19:46:10 +1200, Lawrence D'Oliveiro wrote: > >> In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano >> wrote: >> >>> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: >>> >>>> Just a thought, your minimum sleep time is probably limited by the >>>> resolution of the system "HZ" clock. Type >>>> >>>> less /proc/config.gz >>> >>> $ less /proc/config.gz >>> /proc/config.gz: No such file or directory >>> >>> >>> What OS are you using? >> >> The one named in the subject line? > > Are you asking me or telling me? > > > I've tried on five different Linux machines I have access to, and there > is no such /proc/config.gz on any of them: > > two different versions of Centos > two versions of Fedora > one version of Ubuntu > > So let me rephrase my question... what *specific* OS are you using? From mensanator at aol.com Mon Sep 1 21:06:05 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 1 Sep 2008 18:06:05 -0700 (PDT) Subject: Py 2.6 changes References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> Message-ID: <0bb42df3-ead5-48f1-bfeb-485c8846a12b@m3g2000hsc.googlegroups.com> On Sep 1, 2:15?pm, bearophileH... at lycos.com wrote: > I have just re-read the list of changes in Python 2.6, it's huge, > there are tons of changes and improvements, I'm really impressed:http://docs.python.org/dev/whatsnew/2.6.html > > I'll need many days to learn all those changes! I can see it fixes > several of the missing things/problems I have found in Python in the > past, like the lack of information regarding the floating point it > uses, etc. > I have seen that many (smart) updates are from Hettinger. > > You can see a language gets better when you can remove often-used > commodity functions/classes from your own 'bag of tricks' :-) (Like > the permutations() function, Don't get rid of the whole bag, they didn't implement Combinations with Replcaement. > etc). > > >Python now must be compiled with C89 compilers (after 19 years!). This means that the Python source tree has dropped its own implementations of memmove and strerror, which are in the C89 standard library.< > > I presume it's better for me to not hold my breath while I wait > CPython to be written in C99 :-) > > Now math has factorial:http://docs.python.org/dev/library/math.html#math.factorial > Seen how reduce() is removed from Python 3 (I know it's in itertools), > and seeing that for me to write a productory() function was the first > usage I have had for reduce, years ago, I think the math module can > gain a productory() function too. > > For Python 2.7/3.1 I'd now like to write a PEP regarding the > underscores into the number literals, like: 0b_0101_1111, 268_435_456 > etc. I use such underscores all the time in the D language, and I > think they can be a tiny but significant improvement for Python (and > underscore is much better than just a space, because the underscore > helps the person that reads the code to understand that's a single > number). > > Bye, > bearophile From ter at topazcode.com Tue Sep 2 10:16:21 2008 From: ter at topazcode.com (topazcode) Date: Tue, 2 Sep 2008 07:16:21 -0700 (PDT) Subject: Storing Subprocess Results Message-ID: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> I am using the subprocess module to run some shell commands on a Linux system: import subprocess output = subprocess.call('''ssh server1 "uptime"''', shell=True) The above assigns the output variable with a return code, i.e. 0 in this case. How can I actually capture the data returned from subprocess.call, rather than just the return code? I'd like to have the output variable contain the uptime string in this case. Any help is appreciated. Thanks. From callen314 at gmail.com Tue Sep 9 17:50:26 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 9 Sep 2008 14:50:26 -0700 (PDT) Subject: How to record audio from Python on Mac? References: Message-ID: I want to do this as well, and also some other audio processing via python. I have not tried yet, but much of my research points to pyaudio, PortAudio bindings for python, which is supposed to be multi- platform including Mac OS X, but as I say, I've not tried it yet. Related to this are some examples that get the audio data into numpy arrays for signal processing work. cheers, I'm interested to hear how any of this works out, I'm trying to start a python audio project in the next couple months. cheers. On Sep 9, 1:06 am, s... at pobox.com wrote: > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > casting a broader net.) > > Can I easily control audio record/playback from Python on my Mac? I know > zip about audio recording or about Apple APIs via Python. Pointers to > simple examples would be much appreciated. > > Thanks, > > Skip From benjamin.kaplan at case.edu Tue Sep 2 10:35:12 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 2 Sep 2008 10:35:12 -0400 Subject: Storing Subprocess Results In-Reply-To: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> References: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> Message-ID: On Tue, Sep 2, 2008 at 10:16 AM, topazcode wrote: > I am using the subprocess module to run some shell commands on a Linux > system: > > import subprocess > output = subprocess.call('''ssh server1 "uptime"''', shell=True) > > The above assigns the output variable with a return code, i.e. 0 in > this case. How can I actually capture the data returned from > subprocess.call, rather than just the return code? I'd like to have > the output variable contain the uptime string in this case. Any help > is appreciated. Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > http://docs.python.org/lib/node532.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From akineko at gmail.com Mon Sep 1 22:01:17 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 19:01:17 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Message-ID: <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> On Sep 1, 6:34 pm, "Guilherme Polo" wrote: > This is an illusion you have, calling those methods are not the way > for explicitly controlling button's behavior, not more than generating > proper events. The explicit way is to not use a button, instead > (ab)use Canvas. Some of my custom widgets used Canvas. When I designed the "sticky" button widget, I briefly considered use of Canvas but I rejected because the one I wanted is nothing but Button (except "sticky" behaviour). I understand that use of Canvas provides greater flexibility but I felt it was over-kill. Your insights are very helpful for me and other people when designing a custom widget. Aki- From pavlovevidence at gmail.com Fri Sep 26 17:54:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 26 Sep 2008 14:54:36 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> Message-ID: <00b839d9-fe35-4478-aba2-0435fbf285e8@m36g2000hse.googlegroups.com> On Sep 26, 11:39?am, Patrick Sullivan wrote: > Hello. Hi, I have a couple suggestions. > I will be using some large data sets ("points" from 2 to 12 variables) > and would like to use one class for each point rather than a list or > dictionary. Ok, point of terminology. It's not really a nit-pick, either, since it affects some of your questions below. When you say you want to use one class for each point, you apparently mean you would like to use one class instance, or one object, for each point. One class for each point would be terribly inefficient; one instance, perhaps not. > I imagine this is terribly inefficient, but how much? You say large data sets, which suggests that __slots__ mechanism could be useful to you. class A(object): __slots__ = ['var1','var2','var3'] Normally, each class instance has an associated dict which stores the attributes, but if you define __slots__ then the variables will be stored in fixed memory locations and no dict will be created. However, it seems from the rest of your comments that speed is your main concern. Last time someone reported __slots__ didn't make a big difference in access time, but it probably would speed up creating objects a bit. Of course, you should profile it to make sure. > What is the cost of creating a new class? I'm assuming you want to know the cost of creating a class instance. Generally speaking, the main cost of this is that you'd be executing Python code (whereas list and dict are written in C). > What is the cost of referencing a class variable? I assume you mean an instance variable. > What is the cost of calling a class method to just return a variable? Significant penalty. This is because even if the method call is faster (and I doubt very highly that it is), the method still has to access the variable, which is going to take the same amount of time as accessing the variable directly. I.e., you're getting the overhead of a method call to do the same thing you could have done directly. I highly recommend against doing this, not only because it's less efficient, but also because it's considered bad style in Python. > Key point: The point objects, once created, and essentially non- > mutable. Static. Is there a way to "bind" a variable to a object > method in a way that is more efficient than the function calling > self.variable_name ? Python 2.6 has a new object type called namedtuple in the collections module. (Actually it's a type factory that creates a subclass of tuple with attribute names mapped to the indices.) This might be a perfect fit for your needs. You have to upgrade to 2.6, though, which won't be released for a few days. Carl Banks From rtiago at gmail.com Wed Sep 10 17:24:15 2008 From: rtiago at gmail.com (Ricardo Tiago) Date: Wed, 10 Sep 2008 23:24:15 +0200 Subject: formating a filesystem with python In-Reply-To: <6iqrm2F3rqcU1@mid.uni-berlin.de> References: <6iqrm2F3rqcU1@mid.uni-berlin.de> Message-ID: <8ed7d4b30809101424y5db412d2i7d70545652dcc0c5@mail.gmail.com> I understand that this is a very sensible unix question but i think fuse does this at least it mounts. I was wondering if there were other packages with similar functionality. On Wed, Sep 10, 2008 at 11:14 PM, Diez B. Roggisch wrote: > Ricardo Tiago schrieb: >> >> Hi all, >> >> is there a package in python that allows to mount/umount and format >> (to ext3) a filesystem? I know that this is possible by just calling >> the os commands 'mount/umount and mkfs' but this would imply to have >> to change sudoers to run the script as non-root. > > well, that's a very sensible unix-restriction. and you can't overcome that. > > IOW: no, there is no such thing. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From paul at boddie.org.uk Thu Sep 11 06:35:17 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 11 Sep 2008 03:35:17 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: <823435cf-a557-48d9-9e16-fa28e745e67a@73g2000hsx.googlegroups.com> On 11 Sep, 10:34, Fredrik Lundh wrote: > > And as I said before, the only use case for *huge* XML files I've ever > seen used in practice is to store large streams of record-style data; I can imagine that the manipulation of the persistent form of large graph structures might be another use case, although for efficient navigation of such a structure, which is what you'd need to start applying various graph algorithms, one would need some kind of index. Certainly, we're straying into database territory. Paul From tjreedy at udel.edu Fri Sep 26 02:59:33 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 02:59:33 -0400 Subject: deleting an object In-Reply-To: <6u80qt$80h3s3@rrcs-agw-02.hrndva.rr.com> References: <6u80qt$80h3s3@rrcs-agw-02.hrndva.rr.com> Message-ID: Karl Kobata wrote: > Please help. Questions based on snippet of code below. Please post code that works. Use cut and paste. > 1) when myTestCase is deleted, is just the pointer deleted or the > entire instance with all of its data and data structure deleted? Have you read the manual section on the del statement? > 2) What is the practice for deleted the object and recovering the > memory it occupies? Most programs use del rather sparingly. Most temporary objects are created within functions and get unbound automatically when the function exits. If you need to guarantee release of external resources before the program ends, make explict calls to .close methods of the instances that connect to them. Actually memory recovery depends on the implementation and version. I would not worry about this until you really need to. > 3) If delete is the way, what happens to > ?testUtils.utilFunction1()? if it were instantiated in other classes > that have not been deleted yet? Objects will not be destroyed while still reachable from code (in the absence of a severe bug). > import testUtils > class testClass: > def __init__(self): > self.testList = list() > self.testDict1 = dict() > self.utils1 = testUtils.utilFunction1() > myTestCase = testClass() > delete myTestCase Don't indent main body code. Do use legal keywords. tjr From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 4 07:23:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 13:23:53 +0200 Subject: Coming from .NET and VB and C In-Reply-To: References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> Message-ID: <48bfc4e4$0$13232$426a74cc@news.free.fr> Marco Bizzarri a ?crit : > On Thu, Sep 4, 2008 at 12:16 AM, Dennis Lee Bieber > wrote: >> On Wed, 3 Sep 2008 09:52:06 -0700 (PDT), ToPostMustJoinGroup22 >> declaimed the following in >> comp.lang.python: >> >>> have no preference with MySQL or SQL, stored procedures or ad-hoc >>> queries. >>> >> Please note: MySQL is specific relational database management system >> (RDBMs), which uses a dialect of structured query language (SQL). SQL by >> itself is just a semi-standardized query language -- and can technically >> be used to access non-relational DBMS (if any such are still in use), >> though the query processor would be a pain to program (map a relational >> join into a hierarchical DBMS schema? ugh). >> >>> SO, I'm interested in using my Google App space (free 500MB) to >>> develop a quick database application. Using Python. I found "Dive >>> Into Python" which I will be reading shortly. >>> >> So one question: what RDBMs are supported in that space? > > The appearance is not an RDBMS, at least, maybe it is, but under the surface. Not AFAIK, cf: http://en.wikipedia.org/wiki/BigTable From bignose+hates-spam at benfinney.id.au Wed Sep 10 19:42:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 11 Sep 2008 09:42:20 +1000 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> Message-ID: <87d4jbd0v7.fsf@benfinney.id.au> Grant Edwards writes: > Could whoever is responsible for the gateway that is grabbing > my postings off of Usenet and e-mailing them out please fix the > headers in the mail messages so that I don't get the bounce > messages? The bounce messages are sent to you because you sent the original. > Its a bit rude to send out mass e-mail messages with headers faked > up so that the bounce messages go to somebody else. Indeed it is rude, and the person subscribed to the mailing list whose software is sending these bounce messages is the one responsible for making it stop. The mailing list software can't help (nor can the news-to-mail gateway). In the meantime, the usual fix is for the list administrator to unsubscribe the offending party (the one sending automated bounce messages). -- \ ?He who laughs last, thinks slowest.? ?anonymous | `\ | _o__) | Ben Finney From kaerbuhez at gmail.com Tue Sep 9 18:45:50 2008 From: kaerbuhez at gmail.com (kaer) Date: Tue, 9 Sep 2008 15:45:50 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: <0c964409-83a6-43ec-85ac-923a17e781d3@b1g2000hsg.googlegroups.com> On 9 sep, 23:35, icarus wrote: > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > That did it. > > one more question... > > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? > > My intent is to have the process transparent to the user. He wouldn't > even know the app was written in python. All he knows that when he > double-clicks on it, the application pops up without the DOS black > screen in the background (for w32 users.) > > On Sep 9, 10:49 am, "Chris Rebert" wrote: > > > You need to have the script be run by pythonw.exe as opposed to python.exe > > pythonw.exe suppresses the DOS box from coming up and should be used > > for running GUI applications such as yours. > > > Regards, > > Chris > > > On Tue, Sep 9, 2008 at 1:33 PM, icarus wrote: > > > platform: windows xp professional, python 2.5, wxpython > > > > When I double-check on my program file test.py (for simplicity I'll be > > > using this code below), I see the window just fine. But the ms-dos > > > black window pops up in the background. On Linux, no issues at all. > > > > How can I get rid of that ms-dos black window in the background? > > > something I need to add to my code? a setting to adjust in windows? > > > thanks in advance. > > > > #!/usr/bin/python > > > import wx > > > > appwx = wx.App() > > > > frame = wx.Frame(None, -1, 'test.py') > > > frame.Show() > > > > appwx.MainLoop() > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > -- > > Follow the path of the Iguana...http://rebertia.com py2exe could be what you are looking for. From rajko.mackic at gmail.com Sat Sep 20 20:20:51 2008 From: rajko.mackic at gmail.com (Rajko Mackic Cvrcko) Date: Sat, 20 Sep 2008 17:20:51 -0700 (PDT) Subject: Hi guys! Message-ID: <4105bf15-6454-46dc-8894-7f228391a95d@p31g2000prf.googlegroups.com> Hello, this is Rajko Mackic from town Banjaluka, Bosnia and Herzegovina, also known as Cvrcko Does anyone know of any bars in town where I can swallow a bucket of cum? It can be either dog, horse or human cum. Also, does anyone know of any sex bars where people will shit in your mouth? I also like eating shit. -- Name: Rajko Mackic - Cvrcko Street adress: Ravnogorska 35 Town: 78000 Banja Luka Country: Bosnia and Herzegovina Home phone: +38751/302-886 Cell phone: +38765/544-699 Email adress: rajko.mackic at gmail.com ~ The new pumpkin rarely pulls Terrance, it teases Sharon instead. For Susan the tape's sad, beside me it's unique, whereas against you it's believing dirty. Hey, go reject a fork! Why did Alice open throughout all the boats? We can't explain poultices unless Woody will mercilessly judge afterwards. The frames, disks, and shirts are all fat and fresh. Who will we dine after Edwina wastes the thin mirror's goldsmith? It's very outer today, I'll recollect strangely or Christopher will learn the teachers. Hardly any humble brave tyrants hourly solve as the tired wrinkles cover. Hardly any distant buttons are short and other urban ointments are filthy, but will Robette receive that? Let's lift behind the deep highways, but don't promise the heavy diets. Who kicks badly, when Melvin burns the stale code before the autumn? Get your absolutely moulding barber within my cellar. If you will laugh Gay's hill against porters, it will incredibly climb the case. Some shopkeepers arrive, irrigate, and shout. Others sadly expect. To be pathetic or sticky will talk abysmal oranges to wickedly look. Are you healthy, I mean, moving above clever onions? While farmers partly taste pins, the powders often excuse against the blunt jackets. Generally Susanne will order the sticker, and if George actually seeks it too, the bowl will attempt with the polite lane. He can hate durable kettles above the rural bad ocean, whilst Oscar easily scolds them too. You eventually fill against Norma when the kind drapers irritate among the poor summer. As surprisingly as Dolf converses, you can dye the cap much more familiarly. Brion, still killing, behaves almost eerily, as the sauce changes on their coffee. You won't recommend me grasping about your lazy office. Almost no butchers steadily live the lost signal. Cyrus's hat improves among our desk after we sow towards it. Ralph measures the weaver within hers and wanly calls. Some cosmetic tags answer David, and they rigidly walk Quincy too. When Richard's elder gardner dreams, Mark cares for weak, closed islands. He might strongly fear think and plays our cheap, sour painters above a bathroom. I creep the active yogi and cook it in back of its dorm. Tell Katherine it's strong loving within a tree. Why will you jump the angry lower exits before Murray does? I am unbelievably bitter, so I wander you. How does Hector smell so regularly, whenever Ronald likes the solid twig very slowly? Julieta, have a hot printer. You won't clean it. Fucking don't join a dryer! She wants to nibble inner smogs under Usha's castle. She'd rather depart grudgingly than help with Bernadette's younger grocer. Other old dark cards will comb frantically alongside cans. Try pouring the monument's pretty cat and Oliver will attack you! Don't try to seek halfheartedly while you're jumping throughout a easy carpenter. He'll be climbing in front of good Cypriene until his enigma answers quietly. What doesn't Janet smell inadvertently? They are opening before the rain now, won't explain walnuts later. Some light long game covers pools outside Woodrow's rich film. Why did Oscar judge the pear with the handsome spoon? He will talk nearly if Julieta's tailor isn't wet. Just looking beside a ulcer through the store is too young for Woody to care it. Both filling now, Alejandro and Marty irritated the open rivers about smart envelope. Occasionally, dusts kill beside rude fires, unless they're sweet. Her pen was sharp, dull, and fears over the spring. Zack, on floors difficult and upper, attacks towards it, recollecting seemingly. We measure the raw sauce. They are rejecting throughout quiet, towards empty, in back of cold units. My wide potter won't clean before I comb it. If you'll pour Edward's camp with aches, it'll admiringly converse the cup. I was promising frogs to worthwhile Corinne, who's walking in back of the counter's stable. It can receive clean pickles, do you solve them? Many jugs will be weird lean carrots. Roger helps, then Walt stupidly believes a ugly lentil on Catherine's road. We tease them, then we weekly dream Zack and Annabel's blank candle. A lot of shallow dose or canyon, and she'll locally excuse everybody. If the bizarre balls can sow bimonthly, the hollow raindrop may love more ventilators. We laugh weekly, unless Jezebel grasps shoes outside Jimmie's puddle. Jimmy! You'll mould plates. Just now, I'll dine the bandage. All glad strange figs will fully order the lemons. The dog without the proud star is the pitcher that learns happily. It might crudely scold within sick dry satellites. Until Dolf calls the bushs generally, Ann won't join any full winters. Better kick clouds now or Blanche will wrongly hate them over you. There, Jeff never arrives until Joie nibbles the noisy elbow deeply. From semanticist at gmail.com Mon Sep 22 02:53:16 2008 From: semanticist at gmail.com (Miles) Date: Mon, 22 Sep 2008 02:53:16 -0400 Subject: dict generator question In-Reply-To: <00e45101$0$20331$c3e8da3@news.astraweb.com> References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <00e45101$0$20331$c3e8da3@news.astraweb.com> Message-ID: On Fri, Sep 19, 2008 at 9:51 PM, Steven D'Aprano wrote: > Extending len() to support iterables sounds like a good idea, except that > it's not. > > Here are two iterables: > > > def yes(): # like the Unix yes command > while True: > yield "y" > > def rand(total): > "Return random numbers up to a given total." > from random import random > tot = 0.0 > while tot < total: > x = random() > yield x > tot += x > > > What should len(yes()) and len(rand(100)) return? Clearly, len(yes()) would never return, and len(rand(100)) would return a random integer not less than 101. -Miles From roy at panix.com Wed Sep 3 09:35:41 2008 From: roy at panix.com (Roy Smith) Date: Wed, 03 Sep 2008 09:35:41 -0400 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > > I might take it one step further, however, and do: > > > >> fields = line.split()[:2] > >> a, b = map(int, fields) > > > > in fact, I might even get rid of the very generic, but conceptually > > overkill, use of map() and just write: > > > >> a, b = line.split()[:2] > >> a = int(a) > >> b = int(b) > > If you go that route your next step is to introduce another try...except, > one for the unpacking and another for the integer conversion... Why another try/except? The potential unpack and conversion errors exist in both versions, and the existing try block catches them all. Splitting the one line up into three with some intermediate variables doesn't change that. From python at rgbaz.eu Sat Sep 6 18:03:20 2008 From: python at rgbaz.eu (Python) Date: Sun, 7 Sep 2008 00:03:20 +0200 Subject: modules path Message-ID: <27B9B240-59E7-4174-95EF-5A4D70B1092B@rgbaz.eu> Hi there, I moved a few modules into the modules folder (on OSX: /opt/local/lib/ python2.5/site-packages/). They don't show up though when I start IDLE... Is there a way to reload the modules folders in sys.path without logging out and back in? something like "source .cshrc" in a shell... thanks in advance, Arno From Afro.Systems at gmail.com Sat Sep 20 14:45:48 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Sat, 20 Sep 2008 11:45:48 -0700 (PDT) Subject: writeable buffer and struct.pack_into and struct.unpck_from Message-ID: Hi, I can't find in the documentation the way to use these two functions. can someone share a simple code that utilize these two functions? From george.sakkis at gmail.com Thu Sep 18 11:39:22 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 18 Sep 2008 08:39:22 -0700 (PDT) Subject: dict generator question References: Message-ID: <5b4c91e1-f189-40f4-b5dd-71647683aba8@f36g2000hsa.googlegroups.com> On Sep 18, 10:54 am, "Simon Mullis" wrote: > Hi, > > Let's say I have an arbitrary list of minor software versions of an > imaginary software product: > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > I'd like to create a dict with major_version : count. > > (So, in this case: > > dict_of_counts = { "1.1" : "1", > "1.2" : "2", > "1.3" : "2" } > > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. > > I'm most probably not thinking pythonically enough... (I know I could > do this pretty easily with a couple more lines, but I'd like to > understand if there's a way to use a dict generator for this). Not everything has to be a one-liner; also v[0:3] is wrong if any sub- version is greater than 9. Here's a standard idiom (in 2.5+ at least): from collection import defaultdict versions = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] major2count = defaultdict(int) for v in versions: major2count['.'.join(v.split('.',2)[:2])] += 1 print major2count HTH, George From pratibha.kachi at gmail.com Mon Sep 15 07:19:49 2008 From: pratibha.kachi at gmail.com (pratibha.kachi at gmail.com) Date: Mon, 15 Sep 2008 04:19:49 -0700 (PDT) Subject: Not able to successfully call a webservice created in c# in python. Message-ID: <87e0c57d-2bcd-44d6-8d02-f6b7e62c28a9@l33g2000pri.googlegroups.com> I have created a webservice in C# which I am able to call in win Form client but when I call it using python it gives http 415 error. >>> import SOAPpy >>> server = SOAPpy.SOAPProxy("http://localhost:8731/Design_Time_Addresses/WcfSe rviceLibrary1/Service1/WS") >>> print server.GetData(1) Traceback (most recent call last): File "", line 1, in File "C:\python25\lib\xmlrpclib.py", line 1147, in __call__ return self.__send(self.__name, args) File "C:\python25\lib\xmlrpclib.py", line 1437, in __request verbose=self.__verbose File "C:\python25\lib\xmlrpclib.py", line 1191, in request headers xmlrpclib.ProtocolError: From michel at nospam.please Mon Sep 15 15:44:33 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:44:33 +0200 Subject: environment variable issue In-Reply-To: <48ceb82a$0$2861$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> <48ceb82a$0$2861$ba620e4c@news.skynet.be> Message-ID: <48cebb21$0$2862$ba620e4c@news.skynet.be> Michel Leunen a ?crit : > Actually HOSTNAME seems to be exported as well: > > $ export -p | grep HOSTNAME > declare -x HOSTNAME="LinuxPC" > > I don't know what to think of this but it's the beginning of an > explanation. Oops, my mystake, I forgot I made an export HOSTNAME before trying the export -p command. Sorry, you're right, HOSTNAME is NOT in the list of exported variable. -- Michel Leunen http://linux.leunen.com From stef.mientki at gmail.com Fri Sep 26 17:26:54 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 26 Sep 2008 23:26:54 +0200 Subject: how to search multiple textfiles ? (Python is slow ?) In-Reply-To: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> References: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> Message-ID: <48DD539E.3080108@gmail.com> Mike Driscoll wrote: > On Sep 26, 8:35 am, Stef Mientki wrote: > >> hello, >> >> I want to search multiple textfiles (python source files) for a specific >> word. >> I can find all files, open them and do a search, >> but I guess that will be rather slow. >> >> I couldn't find any relevant information through google. >> >> Does anyone know of a search library that performs this task fast ? >> >> If it indeed only concerns py-files, >> is there another way of searching words ? >> ( I could imagine that such a "py-only-search" would have benefits, >> because you could set a flag to see the words in comment yes or no ) >> >> thanks, >> Stef Mientki >> >> Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. >> The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629. >> > > > On Windows I use the free version of Bare Grep: http://www.baremetalsoft.com/baregrep/ > > No, it's not a Python solution, but it works for my needs. You should > try using Python to search your script files and see if it really is > too slow though. > hi guys, I did some tests and I'm amazed about the results: I did a search on the Python directory: 300 MB, 10325 files in 660 folders. I did several searches, with / without case-sensitive, whole words / not, many/few occurrences, but the differences between those were negligible. Finding all occurences with line numbers: - Pyscripter 110 sec ( PyScripter is the default IDE I use now) - Delphi 20 .. 35 sec - Findstr 4 sec With the following programs I only searched for the first occurence, which I think is good in the case of many files, because you can only view 20 or 30 lines in 1 screen. - Explorer XXX didn't find anything - FileNurse 5 sec (FileNurse is my own Explorer replacement, written in Delphi) - Python 3 sec (very quick and dirty procedure with string.find method I'm really amazed by the speed of Python !! It can only be beaten by findstr, which is only available on windows. Paul: nucular looks very promissing, but I couldn't get it working within a few minutes. I might also be a little overkill, but I'll certainly bookmark the link for future use. thanks again, cheers, Stef > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Sat Sep 6 19:18:15 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 16:18:15 -0700 (PDT) Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: On Sep 7, 8:06?am, cnb wrote: > If I buy a multicore computer and I have really intensive program. How > would that be distributed across the cores? AFAIK, a single process wouldn't be distributed automatically. > Will algorithms always have to be programmed and told specifically to > run on several cores so if not told it will only utilize one core? AFAIK, yes. See (for example) http://www.parallelpython.com/ > So is the free lunch really over There is no such thing as a free lunch. Something which has never existed can't be over. > or is this just an overhyped > phenomena? These days, every IT phenomenon is over-hyped. If you have a CPU-intensive Python program, you may want to consider: (1) checking that there are not faster/better algorithms for doing what you want in Python, either built-in or in a 3rd-party library (2) using psyco (3) checking your code for sub-optimal constructs HTH, John From nstjelja at gmail.com Thu Sep 11 14:33:23 2008 From: nstjelja at gmail.com (Nikola Stjelja) Date: Thu, 11 Sep 2008 20:33:23 +0200 Subject: wx In-Reply-To: References: Message-ID: <2d24984a0809111133na2a8b79pb340b273863b9de7@mail.gmail.com> The module you are talking about is a python GUI toolkit named WxPython, which is a port of the cross platform C++ GUI toolkit wxwidgets. It's an excelent gui toolkit , easy to learn and code on. Well documented and has an excelent community around it. Here are the links for both sites: http://www.wxpython.org/ http://www.wxwidgets.org/ On Thu, Sep 11, 2008 at 8:16 PM, Desmond Scott E wrote: > I'm am a Python novice by chance not choice. (Although it appears to be > a nice tool. Plus anything based on Monte Python can't be bad!) > > My Quest is to migrate a Python-based process from Windows2000/Python > v2.4.2 (#67) to WindowsXP/Python v2.5.2 (r252:60911). > > I've searched the Python website and could find no reference to module wx. > Is this an add-in module or perhaps it was replaced in v2.5.2??? > > References in the code are: > wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT) > self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated) > self.SetColumnWidth(0, WX.LIST_AUTOSIZE)) > idx = self.GetNextItem(idx, wx.LIST_NEXT_ALL, wx.LIST_STATE_DONTCARE) > > Any help would be greatly appreciated! I do have Shrubbery! > > Scott > > Scott E. Desmond > Director & Manager Equity Systems Development > IT Integration Lead > Mellon Capital Management Corporation > 500 Grant Street, Suite 4200 > Pittsburgh, PA 15258 > T 412.236.0405 | F 412.236.1703 > scottd at mcm.com | *www.mcm.com* > > *The information contained in this e-mail may be confidential and is > intended solely for the use of the named addressee.* > *Access, copying or re-use of the e-mail or any information contained > therein by any other person is not authorized.* > *If you are not the intended recipient please notify us immediately by > returning the e-mail to the originator.(16b)* > ** > Disclaimer Version MB.US.1 > > -- > http://mail.python.org/mailman/listinfo/python-list > -- My Blog: http://mylifeasadeveloper.blogspot.com/ My home page: http://www.inet.hr/~nstjelja My Poetry Book: http://www.lulu.de/browse/book_view.php?fCID=222964&fBuyItem=5 My OS Projects: http://lab.linux.hr/~nstjelja/drawit/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Sun Sep 14 15:39:29 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Sep 2008 21:39:29 +0200 Subject: Is there any nice way to unpack a list of unknown size?? In-Reply-To: <238815.3778.qm@web7902.mail.in.yahoo.com> References: <238815.3778.qm@web7902.mail.in.yahoo.com> Message-ID: srinivasan srinivas wrote: > I want to do something like below: > > 1. first, second, third, *rest = foo > > 2. for (a,b,c,*rest) in list_of_lists: update to Python 3.0 (as others have pointed out), or just do first, second, third = foo[:3] rest = foo[3:] for item in list_of_lists: a, b, c = item[:3] rest = item[3:] ... and move on to more interesting parts of your program. From oliphant.travis at ieee.org Thu Sep 11 09:45:27 2008 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Thu, 11 Sep 2008 08:45:27 -0500 Subject: NumPy arrays that use memory allocated from other libraries or tools In-Reply-To: <63fac77e-3043-40fa-8f3d-9d751d9a82cf@d1g2000hsg.googlegroups.com> References: <63fac77e-3043-40fa-8f3d-9d751d9a82cf@d1g2000hsg.googlegroups.com> Message-ID: sturlamolden wrote: > On Sep 10, 6:39 am, Travis Oliphant wrote: > >> I wanted to point anybody interested to a blog post that describes a >> useful pattern for having a NumPy array that points to the memory >> created by a different memory manager than the standard one used by >> NumPy. > > > Here is something similar I have found useful: > > There will be a new module in the standard library called > 'multiprocessing' (cf. the pyprocessing package in cheese shop). It > allows you to crerate multiple processes (as opposed to threads) for > concurrency on SMPs (cf. the dreaded GIL). > > The 'multiprocessing' module let us put ctypes objects in shared > memory segments (processing.Array and processing.Value). It has it's > own malloc, so there is no 4k (one page) lower limit on object size. > Here is how we can make a NumPy ndarray view the shared memory > referencey be these objects: > > try: > import processing > except: > import multiprocessing as processing > > import numpy, ctypes > > _ctypes_to_numpy = { > ctypes.c_char : numpy.int8, > ctypes.c_wchar : numpy.int16, > ctypes.c_byte : numpy.int8, > ctypes.c_ubyte : numpy.uint8, > ctypes.c_short : numpy.int16, > ctypes.c_ushort : numpy.uint16, > ctypes.c_int : numpy.int32, > ctypes.c_uint : numpy.int32, > ctypes.c_long : numpy.int32, > ctypes.c_ulong : numpy.int32, > ctypes.c_float : numpy.float32, > ctypes.c_double : numpy.float64 > } > > def shmem_as_ndarray( array_or_value ): > > """ view processing.Array or processing.Value as ndarray """ > > obj = array_or_value._obj > buf = obj._wrapper.getView() > try: > t = _ctypes_to_numpy[type(obj)] > return numpy.frombuffer(buf, dtype=t, count=1) > except KeyError: > t = _ctypes_to_numpy[obj._type_] > return numpy.frombuffer(buf, dtype=t) > > With this simple tool we can make processes created by multiprocessing > work with ndarrays that reference the same shared memory segment. I'm > doing some scalability testing on this. It looks promising :) > Hey, that is very neat. Thanks for pointing me to it. I was not aware of this development in multiprocessing. -Travis From clodoaldo.pinto at gmail.com Sun Sep 14 09:33:51 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Sun, 14 Sep 2008 06:33:51 -0700 (PDT) Subject: cjson 1.0.5 keyword argument Message-ID: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> I have installed cjson 1.05 in Fedora 8 (python 2.5.1). The cjson home page shows a keyword argument "encoding". http://python.cx.hu/python-cjson/ When i use it i get an error: >>> cjson.encode('?', encoding='utf8') Traceback (most recent call last): File "", line 1, in TypeError: encode() takes no keyword arguments What am i missing? There is no mail list for cjson. Regards, Clodoaldo From steven at REMOVE.THIS.cybersource.com.au Wed Sep 24 02:17:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 24 Sep 2008 06:17:04 GMT Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: On Tue, 23 Sep 2008 13:25:26 -0700, Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose Python > functions, some of which do I/O. Therefore it is possible for many of > the library functions to raise IOError Exceptions. The question is: > should the library function be able to just dump to sys.exit() with a > message about the error (like "couldn't open this file"), or should the > exception propagate to the calling program which handles the issue? > > Thanks in advance for anyone who can either answer my question or point > me to where this question has already been answered. Presumably somebody has suggested that calling sys.exit() was a good option. I'm curious to what possible reason they could give for such a poor choice. Hint: if a library function can't open a file, the application should be given the opportunity to open a different file. Or do something completely different instead. Whatever. That's not up to the library to decide, not even if the library is in such a broken state that it can't continue. Why not? Because the application might deal with that by unloading the library and continuing regardless. -- Steven From tchendrix at gmail.com Tue Sep 23 10:53:03 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 07:53:03 -0700 (PDT) Subject: finding domain name References: Message-ID: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> On Sep 23, 9:10?am, Tino Wildenhain wrote: > Bobby Roberts wrote: > >> Depends on the technology/web framework. If you use WSGI, you should use > >> something like: > > >> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] > > >> -- Gerhard > > > Yeah i already tried environ("SERVER_NAME") but get a key error when i > > do. > > You could output the whole environ to see what you get and how it is called. > > I'd recommend however to check that you are using a configured value and > not something sent by the client if you are going to use it during > filesystem lookup. > > Regards > Tino > > ?smime.p7s > 4KViewDownload evidently the environ dictionary is off limits on our server. It can't be that tough in python to get the current complete url being viewed. It's a snap in asp(which is my background). From lixinyi.23 at gmail.com Tue Sep 23 20:50:02 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 17:50:02 -0700 (PDT) Subject: How do I use python object in C++ Message-ID: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> for example I have the following code: #include void exec_pythoncode( int arg, char**argv ) { Py_Initialize(); Py_Main(argc,argv); Py_Finalize(); } What I would like to know is how can I get the variables I want after Py_Main(argc,argv) say I have a=[1,2,'Hello World',0.1234] in the python space, I would like to have it as a struct in C++. Any sample code? Thanks in advance! From python.list at tim.thechases.com Sun Sep 14 15:16:04 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 14 Sep 2008 14:16:04 -0500 Subject: Is there any nice way to unpack a list of unknown size?? In-Reply-To: <6bbcb770-d9f7-4bfd-ae9a-491b2084a739@34g2000hsh.googlegroups.com> References: <238815.3778.qm@web7902.mail.in.yahoo.com> <6bbcb770-d9f7-4bfd-ae9a-491b2084a739@34g2000hsh.googlegroups.com> Message-ID: <48CD62F4.1060803@tim.thechases.com> >> I want to do something like below: >> 1. first, second, third, *rest = foo > > Python 3.0 has exactly this feature. No current Python 2.x version has it. I asked something similar[1] on c.l.p a while back and Diez Roggisch gave this nice workaround/hack[2] It's a bit ugly in the implementation (sniffing the stack), but elegant in the use, doing exactly what I needed. It doesn't accommodate the "rest" portion that you reference, but allows for arbitrary unpacking into a fixed-length tuple. -tkc [1] http://mail.python.org/pipermail/python-list/2006-May/381386.html [2] http://mail.python.org/pipermail/python-list/2006-May/381399.html From landa.martin at gmail.com Mon Sep 1 11:01:04 2008 From: landa.martin at gmail.com (Martin Landa) Date: Mon, 1 Sep 2008 08:01:04 -0700 (PDT) Subject: python extension dynamic linking Message-ID: Hi, I am writing Python extension in C++, in this extension I am using methods from another Python extension. On Linux I am currently linking my extension with used Python extension -- what is quite ugly. gcc ... -lgdi where gdi is a link to C++ extension imported by 'module' I would like to avoid direct linking here. import module # export some symbol used in my_module import my_module I realized that on Mac it is possible to dynamically link C++ extension using -bundle -undefined dynamic_lookup I wonder how to solve this problem on Linux or MS Window. Thanks for any pointers... Martin From miki.tebeka at gmail.com Tue Sep 23 04:40:15 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 23 Sep 2008 01:40:15 -0700 (PDT) Subject: any tool can shrink DLL? References: Message-ID: <50075ffd-9e17-4878-8383-8487659baf8d@b2g2000prf.googlegroups.com> Hello, > So, is there such a tool that can scan a DLL then strip the unused > function's code out, so yields a small working DLL? I don't think a utility from the outside will know about unused code in a DLL? Usually the compiler is the one doing dead code elimination. The only thing that comes to mind is "strip" that removes strings from executables. As for UPX, does the slowdown really matter? HTH, -- Miki http://pythonwise.blogspot.com From CapnBearbossa at googlemail.com Mon Sep 22 18:07:53 2008 From: CapnBearbossa at googlemail.com (CapnBearbossa at googlemail.com) Date: Mon, 22 Sep 2008 15:07:53 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> Message-ID: <1f913671-1c21-4018-a841-a5a02a360c3b@k30g2000hse.googlegroups.com> On Sep 22, 5:52?pm, Matimus wrote: > On Sep 22, 2:31?pm, CapnBearbo... at googlemail.com wrote: > > > > > hi all, > > > forgive me , but the RTFM and Google search approaches are not > > yielding an answer on this question. ?I need to know if there's a top > > level python interpreter command that clears all user variables (not > > built-ins) from the global namespace. ?In other words a statement, or > > some_command_or_function(), that does this: > > > >>> x=3 > > >>> y=4 > > >>> z=[] > > >>> dir() > > > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > > > >>> some_command_or_function() > > >>> dir() > > > ['__builtins__', '__doc__', '__name__'] > > > thanks, > > ? ?1 desperate snake oil programmer .... > > I don't think you will find anything. The interpreter is essentially > the same whether you are in interactive mode or not. That is, there is > very little use for a method that clears globals in general, so why > would we add it just so that it could be used by the interpreter. > There is almost* nothing available to the interactive interpreter > which isn't part of the core language. > > * The only difference I can think of is the "_" variable, which is > added to __builtins__ and contains the last value returned in > interactive mode. If you have ever tried to run code that uses the > locale module from the interpreter you will see why having any > differences between the interactive and non-interactive interpreter > can be a pain. > > Matt ok. thanks! guess i'll be off to define my own function ... From mal at egenix.com Mon Sep 8 05:42:27 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Mon, 08 Sep 2008 11:42:27 +0200 Subject: Error importing mxTidy In-Reply-To: References: Message-ID: <48C4F383.2020807@egenix.com> On 2008-09-07 15:00, Mike Hostetler wrote: > I built and installed mx-experimental 3.0.0 from source and it seemed to go > fine. But when I try to import it, I get this: > > localhost% python -c "import mx.Tidy" > Traceback (most recent call last): > File "", line 1, in ? > File "mx/Tidy/__init__.py", line 7, in ? > from Tidy import * > File "mx/Tidy/Tidy.py", line 7, in ? > from mxTidy import * > File "mx/Tidy/mxTidy/__init__.py", line 7, in ? > from mxTidy import * > ImportError: No module named mxTidy > > This seems strange to me, since it found the mx.Tidy module but not the mxTidy > module underneath it. But I guess I don't know how the mx-experimental classes > are put together, so I can't really guess what is happening. Thus I am posting > here. :) Which platform are you using ? -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 08 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From usenet1 at anton.e4ward.com Thu Sep 4 06:05:45 2008 From: usenet1 at anton.e4ward.com (Poster28) Date: Thu, 04 Sep 2008 12:05:45 +0200 Subject: Issue warning if no "return" in function? Message-ID: What would you suggest to check python programs for non-syntax error. One example I could think of that one might forget to "return" a value from a function. How could I check for these and maybe other mistakes? From pavlovevidence at gmail.com Thu Sep 4 19:07:04 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 16:07:04 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> Message-ID: <6c55be0c-c60e-49b9-93ba-a7d17c616f9c@b1g2000hsg.googlegroups.com> On Sep 4, 3:15 pm, Ivan Illarionov wrote: > On 4 ????, 22:59, Carl Banks wrote: > > You can write code to guard against this if you want: > > > class A: > > legal = set(["x"]) > > def __setattr__(self,attr,val): > > if attr not in self.legal: > > raise AttributeError("A object has no attribute '%s'" % attr) > > self.__dict__[attr] = val > > def __init__(self,x): > > self.y = x > > > I suspect most people who go into Python doing something like this > > soon abandon it when they see how rarely it actually catches anything. > > > Carl Banks > > '__slots__' is better: > class A(object): > __slots__ = set(["x"]) > def __init__(self, x): > self.y = x > > this will do the same, only faster>>> A(1) > > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in __init__ > AttributeError: 'A' object has no attribute 'y' However, if you subclass your version of A that uses __slots__, the subclass will once again allow all attribute access, whereas if you subclass my version of A that uses __getattr__, it will still be restricted to the allowed symbols (unless you were to override the list of symbols, which you probably would). The latter behavior is less surprising and less dangerous, which (besides the questionable usage) is the main reason using __slots__ is not recommended for this purpose. (Having said that, I do admit to using __slots__ for this purpose once. But, the confusing aspects of __slots__ were managed by a metaclass and hidden from the user.) Carl Banks From deets at nospam.web.de Thu Sep 25 16:36:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:36:15 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: References: Message-ID: <6k2b1vF5inqbU1@mid.uni-berlin.de> Nick Craig-Wood schrieb: > Scott Sharkey wrote: > B> Our development group at work seems to be heading towards adopting >> python as one of our standard "systems languages" for internal >> application development (yeah!). One of the issues that's come up is >> the problem with apt (deb packages) vs eggs, vs virtual environments. >> We're probably gonna end up using Pylons or TurboGears for web-based >> apps, and I've recommended virtualenv, but one of the other developers >> has had some "inconsistencies" when mixing systems with python installed >> from apt (all our servers are debian or ubuntu based) vs when installed >> under virtualenv. >> >> I have basically recommended that we only install the python base (core >> language) from apt, and that everything else should be installed into >> virtual environments. But I wanted to check to see how other enterprises >> are handling this issue? Are you building python from scratch, or using >> specific sets of .deb packages, or some other process. >> >> Any insight into the best way to have a consistent, repeatable, >> controllable development and production environment would be much >> appreciated. > > I'll admit to not knowing what you mean by virtual environment... virtualenv is a simple tool to create isolated python environments where you can install whatever packages you like without interfering with other installations, even allowing to install conflicting package versions (per VE of course they must be without conflicts). Diez From andy_westken at hotmail.com Thu Sep 11 12:09:52 2008 From: andy_westken at hotmail.com (andy_westken at hotmail.com) Date: Thu, 11 Sep 2008 09:09:52 -0700 (PDT) Subject: Enumerating ordered expat attributes with tuplets? References: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> Message-ID: On Sep 11, 4:48?pm, Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Ah, well. Don't know whether it meets your aesthetic standards, but: > ?>>> my_list = ['tree', 'hug', 'flower', 'hug', 'bear', 'run'] > ?>>> my_list[0:len(a):2] > ['tree', 'flower', 'bear'] > ?>>> my_list[1:len(a):2] > ['hug', 'hug', 'run'] > > and hence > > ?>>> zip(my_list[0:len(a):2], my_list[1:len(a):2]) > [('tree', 'hug'), ('flower', 'hug'), ('bear', 'run')] > > and furthermore > > ?>>> for a, b in zip(my_list[0:len(a):2], my_list[1:len(a):2]): > ... ? ? print a, b > ... > tree hug > flower hug > bear run > > or the slightly less obfuscated: > > ?>>> for index in range(0, len(my_list), 2): > ... ? ? print my_list[index], my_list[index + 1] > ... ? ? > tree hug > flower hug > bear run > > On Sep 11, 2008, at 5:19 PM, andy_west... at hotmail.com wrote: > > > > > > > On Sep 11, 4:04 pm, Manuel Ebert wrote: > >> -----BEGIN PGP SIGNED MESSAGE----- > >> Hash: SHA1 > > >> Hi Andy, > > >> by the looks of it I'd say that the problem is that the second > >> parameter you passed to start_element is not a dictionary at all (the > >> clue is in the "AttributeError: 'LIST' object" ...). > > >> ?>>> d = ['tree', 'house'] > >> ?>>> start_element("Thing", d) > >> Thing : > >> AttributeError: 'list' object has no attribute 'items' > >> ?>>> d = {'tree': 'hug', 'flower' : 'eat'} > >> ?>>> start_element("Thing", d) > >> Thing : ? flower="eat" ?tree="hug" > > >> Manuel > > >> On Sep 11, 2008, at 4:21 PM, andy_west... at hotmail.com wrote: > > >>> Hi > > >>> I'm new to Python and trying to pick up good, idiomatic usage right > >>> from the offset. > > >>> As I was familiar with Expat from C++ (directly and via expatpp) I'm > >>> trying to write a little script - using xml.parsers.expat - to ? > >>> search > >>> and replace XML attribute values. > > >>> As I want the attributes to stay in order when the file is ? > >>> written out > >>> (so I can check my results with a diff tool) I've set the parser's > >>> ordered_attributes attribute. But this has stopped the for loop > >>> working with the tuplets. > > >>> The relevant bit of code in my little test, using the default > >>> Dictionary for the attributes, is: > > >>> def start_element(name, attrs): > >>> ? ? print "%s : " % name, > >>> ? ? for (a,b) in attrs.items(): > >>> ? ? ? ? print " %s=\"%s\"" % (a,b), > > >>> But when I set ordered_attributes, first it doesn't like the items() > > >>> ? ? AttributeError: 'list' object has no attribute 'items' > > >>> And then it doesn't like the tuple > > >>> ? ? ValueError: too many values to unpack > > >>> Do I have keep track of where I am (name, value, name, value, ...) > > >>> Or is there a way I can solve the problem with a tuple? > > >>> Thanks, Andy > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > > >> -----BEGIN PGP SIGNATURE----- > >> Version: GnuPG v1.4.7 (Darwin) > > >> iD8DBQFIyTOLcZ70OCIgLecRAsBrAJ9YSa7f+YTyM1yRmEKw8KBtb2klIgCgjNzw > >> F295Tik+45eNHnJ3B4kKnWU= > >> =xR4m > >> -----END PGP SIGNATURE------ Hide quoted text - > > >> - Show quoted text - > > > Sorry! > > > I forgot to mention that when you set the parser's ordered_attributes > > attribute, it sends the "attrs" to start_element as a list, not a > > dictionary, in the order name, value, name, value, ... > > > Andy > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.7 (Darwin) > > iD8DBQFIyT25cZ70OCIgLecRAmWqAJ4zEy8gatIh4CqKpJxZwACs9BBxgwCfaPoQ > QfmRVzHqwJFu3WnjCM0TJYo= > =9z6U > -----END PGP SIGNATURE------ Hide quoted text - > > - Show quoted text - Thanks! Regarding aesthetics - I don't need it to look pretty: I want it to be understandable to people who know Python (?), and then as efficient as possible. Of the two examples about (the 'zip' solution and the 'range' solution), is there much difference in performance? Andy From dblubaugh at belcan.com Tue Sep 30 13:21:51 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 30 Sep 2008 13:21:51 -0400 Subject: OS.SYSTEM ERROR !!! Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> To All, I have been attempting to execute the following program within the Python environment: Myprogram.exe, which means this is an executable file!! I would usually execute this program (with the appropriate arguments) by going to following directory within MS-DOS (Windows XP): C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 The executable would execute perfectly. However, when I would try to execute the following lines of source code within a python script file: import os os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") The executable file would start to execute until it would print an error stating that it cannot use a (.dat) file, which is located under the following directory: C:\myprogramfolder\run\inputs\io\control.dat I believe I may be missing something here that prevents the executable file working within python from utilizing this (.dat). The printed final error is the following: ERROR opening inputs/io/control.dat Does anyone know what that could be ?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From steve at holdenweb.com Thu Sep 18 12:58:54 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Sep 2008 12:58:54 -0400 Subject: Extracting hte font name from a TrueType font file Message-ID: Does anyone have a Python recipe for this? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From gboutsioukis at gmail.com Sat Sep 27 09:31:40 2008 From: gboutsioukis at gmail.com (George Boutsioukis) Date: Sat, 27 Sep 2008 13:31:40 +0000 (UTC) Subject: Using the 'with' statement with cStringIO objects References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> Message-ID: <1222522300.659080@athprx04> > So, I'm guessing you can't use the 'with' statement with cStringIO > objects? Is this a bug, or do I need to use the 'with' statement > differently to get this to work? > > Thanks, > peppergrower Neither, just not implemented. Only classes with __enter__ and __exit__ methods(ie context manager types) can be used in with statements. And, correct me if I'm wrong, I think it's pointless for a StringIO object to have those. From st1999 at gmail.com Sun Sep 28 14:03:34 2008 From: st1999 at gmail.com (robean) Date: Sun, 28 Sep 2008 11:03:34 -0700 (PDT) Subject: urllib2 and exceptions Message-ID: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> Hi everyone, I have a question about using urllib2. I like urllib2 better than urllib at least in part because it has more elaborate support for handling errors: there is built in support for URLError (for faulty urls) and HTTPError (for http errors that might originate from, say, passing an invalid stock-ticker in the program below). However I can get neither to work. I'm attaching below the (very short) code: can anyone point out what I'm doing wrong? Now, if I replace the URLError and HTTPError with IOError (the class from which both URLError and HTTPError inherit), the program works fine. Why is it that I can call the generic IOError class, but none of the Error classes derived from that? These are clearly defined in the urllib2 manual. Very confused... Here's the code: import urllib2 # read stock information from yahoo finance for Traget (TGT) goodTicker = 'TGT' # program works with this badTicker = 'TGTttttttt' # python doesn't understand either HTTPError or URLError with this url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker try: handle = urllib2.urlopen(url) # this does not work except HTTPError, e: print "There was an http error" print e # this also does not work except URLError, e: print "There is a problem with the URL" print e exit(1) #this works except IOError, e: print "You have an IOError" print e text = handle.readlines()[:20] for line in text: print line From sbassi at clubdelarazon.org Tue Sep 9 09:16:59 2008 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Tue, 9 Sep 2008 10:16:59 -0300 Subject: biopython In-Reply-To: <9e2f512b0809090614n7d57850cn14ba44dad0af3757@mail.gmail.com> References: <9e2f512b0809090614n7d57850cn14ba44dad0af3757@mail.gmail.com> Message-ID: <9e2f512b0809090616h2c8128cawacdc802924b286b2@mail.gmail.com> On 9/9/08, Beema Shafreen wrote: > I am using Biopython to fetch pumed Id's ,The module i use is (from Bio > import Entrez) > But i am getting this error >>>> from Bio import Entrez > Traceback (most recent call last): > File "", line 1, in ? > ImportError: cannot import name Entrez Looks like is bad installed. It works for me: /home/user/MMC-SD/Kingston/py252/bin> ./python2.5 Python 2.5.2 (r252:60911, Jul 7 2008, 16:11:08) [GCC 3.3.5 (Debian 1:3.3.5-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from Bio import Entrez >>> dir(Entrez) ['File', '__builtins__', '__doc__', '__file__', '__name__', '__path__', '_open', 'efetch', 'egquery', 'einfo', 'elink', 'epost', 'esearch', 'espell', 'esummary', 'os', 'query', 'read', 'time', 'urllib'] -- Sebasti?n Bassi. Diplomado en Ciencia y Tecnolog?a. Vendo isla: http://www.genesdigitales.com/isla What's new in Python 3: http://tinyurl.com/5cd89r Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 From larry.bates at vitalEsafe.com Sat Sep 13 11:45:30 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 13 Sep 2008 10:45:30 -0500 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: Message-ID: Marco Bizzarri wrote: > On Sat, Sep 13, 2008 at 4:11 PM, Fredrik Lundh wrote: >> Marco Bizzarri wrote: >> >>> class FolderInUse: >>> >>> def true_for(self, archivefolder): >>> return any([instance.forbid_to_close(archivefolder) for instance in >>> self.core.active_outgoing_registration_instances()]) >>> >>> Is this any better? The true_for name does not satisfy me a lot... >> well, "true_for" is indeed pretty inscrutable, but I'm not sure that would >> be the first thing I'd complain about in that verbose mess... > > "verbose mess". > > It is always frustrating when you do what you think is your best and > you read that. > > Anyway: I'm here to learn, and, of course, part of it is to listen > those who've been there much longer than you. > > So, thanks for your sincere evaluation, Fredrik :-). > >> (when you pick method names, keep in mind that the reader will see the >> context, the instance, and the arguments at the same time as they see the >> name. there's no need to use complete sentences; pick short short >> descriptive names instead.) > > Maybe I'm looking at the wrong direction, right now. From the point of > view of the FolderInUse clients, they will do: > > condition = FolderInUse(core) > > condition.true_for(folder) > > Is this too verbose? This is not a polemic statement, I'm really > asking your opionion. > > The expression inside the true_for is indeed complex, and maybe I can > simplify it; however, I'm deeply convinced that > > instance.forbid_to_close(folder) > > has some good points on it; I mean, once I read this kind of code, I > can hope to understand it without looking at what forbid_to_close > does. > > >> >> > >>> class FolderInUse: >>> >>> def true_for(self, archivefolder): >>> return any([instance.forbid_to_close(archivefolder) for instance in >>> self.core.active_outgoing_registration_instances()]) IMHO it reads better if you use the __call__ method of the class to return the value and rewrite it as a regular loop for clarity. Sometimes the simplest way is the easiest to read. class FolderInUse: def __call__(self, archivefolder): result = False for instance in self.core.active_outgoing_registration_instances(): if instance.forbid_to_close(archivefolder): result = True break return result Then it can be called with: if FolderInUse(archivefolder): ... -Larry From fredrik at pythonware.com Thu Sep 18 16:28:24 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Sep 2008 22:28:24 +0200 Subject: Extracting hte font name from a TrueType font file In-Reply-To: References: Message-ID: Steve Holden wrote: > Does anyone have a Python recipe for this? >>> from PIL import ImageFont >>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1) >>> f.font.family 'Verdana' >>> f.font.style 'Italic' From tino at wildenhain.de Sat Sep 13 04:41:36 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 13 Sep 2008 10:41:36 +0200 Subject: question about python In-Reply-To: <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> References: <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> Message-ID: <48CB7CC0.4040902@wildenhain.de> fishfin wrote: > @ Carl: Yes, I think your right now that I look at it (or at least all > except for the last two lines need to be indented). > I'm still not sure > how to send the stuff to the web browser though. what do you think is the cfile.write() doing? As a hint, beside having a look at rfc2616 and friends, get something like wiresharc to see how HTTP requests work in real world. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From maebert at uos.de Thu Sep 11 11:48:09 2008 From: maebert at uos.de (Manuel Ebert) Date: Thu, 11 Sep 2008 17:48:09 +0200 Subject: Enumerating ordered expat attributes with tuplets? In-Reply-To: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> References: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> Message-ID: <06159E9A-4E49-48AA-B288-BEF41922F2FC@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Ah, well. Don't know whether it meets your aesthetic standards, but: >>> my_list = ['tree', 'hug', 'flower', 'hug', 'bear', 'run'] >>> my_list[0:len(a):2] ['tree', 'flower', 'bear'] >>> my_list[1:len(a):2] ['hug', 'hug', 'run'] and hence >>> zip(my_list[0:len(a):2], my_list[1:len(a):2]) [('tree', 'hug'), ('flower', 'hug'), ('bear', 'run')] and furthermore >>> for a, b in zip(my_list[0:len(a):2], my_list[1:len(a):2]): ... print a, b ... tree hug flower hug bear run or the slightly less obfuscated: >>> for index in range(0, len(my_list), 2): ... print my_list[index], my_list[index + 1] ... tree hug flower hug bear run On Sep 11, 2008, at 5:19 PM, andy_westken at hotmail.com wrote: > On Sep 11, 4:04 pm, Manuel Ebert wrote: >> -----BEGIN PGP SIGNED MESSAGE----- >> Hash: SHA1 >> >> Hi Andy, >> >> by the looks of it I'd say that the problem is that the second >> parameter you passed to start_element is not a dictionary at all (the >> clue is in the "AttributeError: 'LIST' object" ...). >> >> >>> d = ['tree', 'house'] >> >>> start_element("Thing", d) >> Thing : >> AttributeError: 'list' object has no attribute 'items' >> >>> d = {'tree': 'hug', 'flower' : 'eat'} >> >>> start_element("Thing", d) >> Thing : flower="eat" tree="hug" >> >> Manuel >> >> On Sep 11, 2008, at 4:21 PM, andy_west... at hotmail.com wrote: >> >> >> >> >> >>> Hi >> >>> I'm new to Python and trying to pick up good, idiomatic usage right >>> from the offset. >> >>> As I was familiar with Expat from C++ (directly and via expatpp) I'm >>> trying to write a little script - using xml.parsers.expat - to >>> search >>> and replace XML attribute values. >> >>> As I want the attributes to stay in order when the file is >>> written out >>> (so I can check my results with a diff tool) I've set the parser's >>> ordered_attributes attribute. But this has stopped the for loop >>> working with the tuplets. >> >>> The relevant bit of code in my little test, using the default >>> Dictionary for the attributes, is: >> >>> def start_element(name, attrs): >>> print "%s : " % name, >>> for (a,b) in attrs.items(): >>> print " %s=\"%s\"" % (a,b), >> >>> But when I set ordered_attributes, first it doesn't like the items() >> >>> AttributeError: 'list' object has no attribute 'items' >> >>> And then it doesn't like the tuple >> >>> ValueError: too many values to unpack >> >>> Do I have keep track of where I am (name, value, name, value, ...) >> >>> Or is there a way I can solve the problem with a tuple? >> >>> Thanks, Andy >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> -----BEGIN PGP SIGNATURE----- >> Version: GnuPG v1.4.7 (Darwin) >> >> iD8DBQFIyTOLcZ70OCIgLecRAsBrAJ9YSa7f+YTyM1yRmEKw8KBtb2klIgCgjNzw >> F295Tik+45eNHnJ3B4kKnWU= >> =xR4m >> -----END PGP SIGNATURE------ Hide quoted text - >> >> - Show quoted text - > > Sorry! > > I forgot to mention that when you set the parser's ordered_attributes > attribute, it sends the "attrs" to start_element as a list, not a > dictionary, in the order name, value, name, value, ... > > Andy > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIyT25cZ70OCIgLecRAmWqAJ4zEy8gatIh4CqKpJxZwACs9BBxgwCfaPoQ QfmRVzHqwJFu3WnjCM0TJYo= =9z6U -----END PGP SIGNATURE----- From joncle at googlemail.com Wed Sep 10 14:03:05 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 11:03:05 -0700 (PDT) Subject: Reading binary data References: <508e31d9-daab-4346-9441-55cc47f7c1f4@m44g2000hsc.googlegroups.com> <54d64616-b86c-45bd-a8b5-4332faa5a73d@a70g2000hsh.googlegroups.com> Message-ID: On Sep 10, 6:45?pm, Aaron Scott wrote: > > CORRECTION: '3cII' should be '3sII'. > > Even with the correction, I'm still getting the error. Me being silly... Quick fix: signature = file.read(3) then the rest can stay the same, struct.calcsize('3sII') expects a 12 byte string, whereby you only really have 11 -- alignment and all that... Jon. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 28 03:52:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 07:52:56 GMT Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Message-ID: <00ef3194$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote: > Hello all, > > To me, this is a somewhat unintuitive behavior. I want to discuss the > parts of it I don't understand. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= lambda: n > ... >>>> f[0]() > 9 >>>> f[1]() > 9 > > I guess I can accept this part so far, though it took a little getting > used to. I'm writing some code and found the following workaround, but > I don't think it should give different results. Maybe I'm not > understanding some of the details of closures. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= (lambda n: ( lambda: n ) )( n ) > ... >>>> f[0]() > 0 >>>> f[1]() > 1 > > Which is of course the desired effect. Why doesn't the second one just > look up what 'n' is when I call f[0], and return 9? That's an awfully complicated solution. A much easier way to get the result you are after is to give each function its own local copy of n: f[n] = lambda n=n: n As for why the complicated version works, it may be clearer if you expand it from a one-liner: # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) inner = lambda: n outer = lambda n: inner f[n] = outer(n) outer(0) => inner with a local scope of n=0 outer(1) => inner with a local scope of n=1 etc. Then, later, when you call inner() it grabs the local scope and returns the number you expected. -- Steven From spamcomefindmeplease at gmail.com Sat Sep 27 18:28:49 2008 From: spamcomefindmeplease at gmail.com (peppergrower) Date: Sat, 27 Sep 2008 15:28:49 -0700 (PDT) Subject: Using the 'with' statement with cStringIO objects References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> <1222522300.659080@athprx04> <87zllt7h72.fsf@mulj.homelinux.net> Message-ID: Thanks for the help. I'm fairly new to programming (which you probably could have guessed...). When I realized that you could use a StringIO instance as if it were a file, I wanted to try some of the same techniques on it as I would with a file. In this case, I wanted to use a "for line in testfile" construction to iterate over the StringIO instance. (I did find a better way for my particular case, one that didn't involve StringIO at all.) When I got that particular error, I suspected that it had something to do with the relative newness of the 'with' statement. If this is something that should be considered for addition in the future, is there somewhere specific I should suggest that? From chapagainanish at yahoo.com Wed Sep 3 05:42:26 2008 From: chapagainanish at yahoo.com (chapagainanish) Date: Wed, 03 Sep 2008 09:42:26 -0000 Subject: installing matplotlib with numpy and scipy for Python in Cygwin Message-ID: Hi!! I'm having installation problem for installing numpy and scipy in Cygwin for Python, and am obstruct in madway for project, i followed scipy.org guidelines but there's few error thrown as failed..with exit status 1 please if someone has installed these module help me thank's and regard's Anish From liuyuprc at gmail.com Sun Sep 14 07:19:12 2008 From: liuyuprc at gmail.com (liuyuprc) Date: Sun, 14 Sep 2008 04:19:12 -0700 (PDT) Subject: Why some blog entries at MSN Space support rss feed while others don't? Message-ID: Not sure if this is the place this question should even be raised, but I am deeply troubled by this problem for days. I am now desperate. When i tried to add the blogs at MSN Space of my friends' to google reader, some of them don't support rss feed, so i cannot add them. You guys have any idea how to enable RSS at one's blog entry so it can be subscribed? thanks! From arnodel at googlemail.com Sun Sep 14 05:31:16 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Sep 2008 02:31:16 -0700 (PDT) Subject: recursion gotcha? References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> <3f0d61c40809140108n515006dci87f91dcd971f0169@mail.gmail.com> Message-ID: <3b4a73bd-672e-44a5-a364-6b9a165628f5@e39g2000hsf.googlegroups.com> On Sep 14, 9:44?am, "Marco Bizzarri" wrote: > On Sun, Sep 14, 2008 at 10:08 AM, Marco Bizzarri > > > > wrote: > > On Sun, Sep 14, 2008 at 10:01 AM, cnb wrote: > >> this recursive definition of sum thrumped me, is this some sort of > >> gotcha or am I just braindead today? > >> and yes i know this is easy a a for x in xs acc += x or just using the > >> builtin. > > >> def suma(xs, acc=0): > >> ? ? ? ?if len(xs) == 0: > >> ? ? ? ? ? ? ? ?acc > >> ? ? ? ?else: > >> ? ? ? ? ? ? ? ?suma(xs[1:], acc+xs[0]) > > > You're just missing the "return" statements? > > > def suma(xs, acc=0): > > ? ? ? if len(xs) == 0: > > ? ? ? ? ? ? ?return acc > > ? ? ? else: > > ? ? ? ? ? ? ?return suma(xs[1:], acc+xs[0]) > > Besides: you can avoid the "acc" parameter: > > def suma(xs): > ? ? if len(xs) == 0: > ? ? ? ? return 0 > ? ? else: > ? ? ? ? return xs[0] + suma(xs[1:]) > I think the OP tried to make it tail-recursive, which of course has no benefit in Python. In fact it looks like a Scheme implementation of sum translated literally to Python. In Python this algorithm is expressed naturally as: def suma(xs): acc = 0 for x in xs: acc += x return acc -- Arnaud From grante at visi.com Wed Sep 10 13:48:01 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 12:48:01 -0500 Subject: md5 differences References: Message-ID: <8K6dnVeoxJTMlVXVnZ2dnUVZ_j6dnZ2d@posted.visi> On 2008-09-10, Wojtek Walczak wrote: > On Wed, 10 Sep 2008 12:39:24 -0500, Grant Edwards wrote: > >>> The strange thing is that >>>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >>> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. >> >> Same here. > > I guess it will be the same for vast majority of us ;-) > The question is why is it '90364ed45b452d43378629c20543a81d' > for the OP? :-) The smart money is betting on "because the OP goofed when he was cutting/pasting stuff from his terminal window into his posting." -- Grant Edwards grante Yow! Were these parsnips at CORRECTLY MARINATED in visi.com TACO SAUCE? From deets at nospam.web.de Thu Sep 4 07:00:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Sep 2008 13:00:57 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: Message-ID: <6i9tftFpi1lhU1@mid.uni-berlin.de> Marco Bizzarri wrote: > Let's say I've a class a, where I can write: Anticipating this obviously premature posting: http://dirtsimple.org/2004/12/python-is-not-java.html Diez From akineko at gmail.com Mon Sep 1 18:45:19 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 15:45:19 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp Message-ID: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Hi everyone, This is a memorandum so that other people can share the info. The following methods are declared in the Tkinter Button class. tkButtonDown(), tkButtonEnter(), tkButtonInvoke(), tkButtonLeave(), tkButtonUp() However, they are not working, when you try, you will get: _tkinter.TclError: invalid command name "tkButtonLeave" The bindings in the Tkinter are mapping them to non-existing tk methods. I needed to use the method badly and I couldn't find any clear solution for this. So, I spent time to solve this. tkButtonLeave(), for example, is declared as follows: Tkinter.py line 2005 of 3759 def tkButtonLeave(self, *dummy): self.tk.call('tkButtonLeave', self._w) Now, in the Tk source distribution, I found the following: unsupported.tcl # Commands provided by Tk without official support. Use them at your # own risk. They may change or go away without notice. namespace eval ::tk::unsupported { # Map from the old global names of Tk private commands to their # new namespace-encapsulated names. variable PrivateCommands array set PrivateCommands { tkButtonAutoInvoke ::tk::ButtonAutoInvoke tkButtonDown ::tk::ButtonDown tkButtonEnter ::tk::ButtonEnter tkButtonInvoke ::tk::ButtonInvoke tkButtonLeave ::tk::ButtonLeave tkButtonUp ::tk::ButtonUp ... snip ... This seems suggesting that the Tkinter bindings are binding obsolete tk methods. And, the method should be called seems ::tk::ButtonLeave, instead. I placed the following into my Tkinter code and it worked. self.btn.tk.call('::tk::ButtonLeave', self.btn._w) // Summary: (1) tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp are not working. (2) Bindings are not correct (2) Workaround is call correct tk methods directly I hope future Tkinter will be corrected so that the methods are available as documented. Best regards, Aki- From skip at pobox.com Sun Sep 21 22:28:36 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 21 Sep 2008 21:28:36 -0500 Subject: pause between the loops In-Reply-To: <37b964200809211902r206e951ep8d83cad88c93d45f@mail.gmail.com> References: <37b964200809211902r206e951ep8d83cad88c93d45f@mail.gmail.com> Message-ID: <18647.724.773230.535318@montanaro-dyndns-org.local> Jackie> can I ask python to stop for, say, 5mins, after it go through Jackie> loop i=0 before it starts loop i=1? import time for i in range(10): time.sleep(5) # seconds Skip From benjamin at dromaludaire.info Tue Sep 16 05:57:19 2008 From: benjamin at dromaludaire.info (Benjamin Sigonneau) Date: Tue, 16 Sep 2008 11:57:19 +0200 Subject: on-the-fly translation with gettext Message-ID: <87od2opg5c.fsf@lapinot.localdomain> Hi all, I'm a complete beginner in python and in GUI designing, yet I'm writing a GUI using python and Tkinter. I need it to be available both in french and english, so I read the Fine Manual and gave a try to gettext. So far, I've managed to translate my app with the following snippet: | import gettext | def install_lang (lang): | try: | t = gettext.translation(domain = 'mydomain', localedir = 'locale', | languages = [lang]) | t.install() | except IOError: | import __builtin__ | __builtin__.__dict__['_'] = lambda x: x When I issue an install_lang('en') at the beginning of my program, it is translated in english and, conversely, an install_lang('fr') at the beginning makes it available in french. However, I'd like to let the user show the language on-the-fly during execution. Having read the Python Library Reference, sec. 21.1.3.3 (see http://docs.python.org/lib/node740.html), I added a menu with two radiobuttons and I merely set them up to call install_lang: | app_lang = StringVar() | app_lang.set('en') | langmenu = Menu(root) | langmenu.add_radiobutton(label = "English", variable = app_lang, value = 'en', | command = lambda l = 'en': install_lang(l)) | langmenu.add_radiobutton(label = "French", variable = app_lang, value = 'fr', | command = lambda l = 'fr': install_lang(l)) However, there is no magic. The language of the application remains unchanged. If it was defined to be english at startup, so will it remain. Conversely, it will stay in french if this was the language at startup. Does somebody has any idea of what I'm doing wrong, and how to fix it? Thanks. -- benjamin From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 11:28:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 17:28:05 +0200 Subject: finding domain name In-Reply-To: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> References: <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> Message-ID: <48d90afd$0$12015$426a74cc@news.free.fr> Bobby Roberts a ?crit : > On Sep 23, 9:10 am, Tino Wildenhain wrote: >> Bobby Roberts wrote: >>>> Depends on the technology/web framework. If you use WSGI, you should use >>>> something like: >>>> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] >>>> -- Gerhard >>> Yeah i already tried environ("SERVER_NAME") but get a key error when i >>> do. >> You could output the whole environ to see what you get and how it is called. >> >> I'd recommend however to check that you are using a configured value and >> not something sent by the client if you are going to use it during >> filesystem lookup. >> >> Regards >> Tino >> >> smime.p7s >> 4KViewDownload > > evidently the environ dictionary is off limits on our server. ??? > It can't > be that tough in python to get the current complete url being viewed. > It's a snap in asp(which is my background). Please don't compare apples to roller-skates. asp is a mix of libraries, components and whatever, while Python is a language. From calebjhansen at gmail.com Sat Sep 13 04:00:59 2008 From: calebjhansen at gmail.com (fishfin) Date: Sat, 13 Sep 2008 01:00:59 -0700 (PDT) Subject: question about python References: Message-ID: <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> @ Carl: Yes, I think your right now that I look at it (or at least all except for the last two lines need to be indented). I'm still not sure how to send the stuff to the web browser though. Thanks for pointing it out! @ Diez: I'll start googling those right away. Carl Banks wrote: > On Sep 13, 12:15 am, fishfin wrote: > > I was working through a tutorial about how to write a server using > > python (the url is bellow). I am sure that the server is working to > > some degree because when the server is running localhost:8080 just > > keeps trying to load until it times out. I would like to know how to > > send information through the server to my browser? > > > > I was working through this tutorial:http://python.about.com/od/networkingwithpython/ss/PythonWebServer.htm > > > > and my final code is like this: > > > > import socket > > > > host = '' > > port = 8080 > > > > c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > > > c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > > > > c.bind((host, port)) > > > > c.listen(1) > > > > while 1: > > csock, caddr = c.accept() > > cfile = csock.makefile('rw', 0) > > It looks like everything after this line needs to be indented. > Besides that, nothing jumps out at me, though I don't do direct socket > programming a lot. > > > line = cfile.readline().strip() > > > > cfile.write('HTTP/1.0 200 OK\n\n') > > cfile.write('Welcome %s!' % > > (str(caddr))) > > cfile.write('

Follow the link...

') > > cfile.write('All the server needs to do is ') > > cfile.write('to deliver the text to the socket. ') > > cfile.write('It delivers the HTML code for a link, ') > > cfile.write('and the web browser converts it.



') > > cfile.write('
Click me!
') > > cfile.write('

The wording of your request was: "%s"' %(line)) > > cfile.write('') > > > > cfile.close() > > csock.close() > > > Carl Banks From michael.pearmain at tangozebra.com Tue Sep 2 11:04:51 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 2 Sep 2008 08:04:51 -0700 (PDT) Subject: dict.update Message-ID: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> Hi All, I have two dictionaries e.g dict1 = {123:3,234:5,456:3} dict2 = {123:4,157:2,234:5,456:3,567:2} I want to merge these two dictionaries together so i have a resultant dictionary of: dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]} As later on i want to write a csv file that would have the form id var1 var2 123 4 3 157 2 0 i looks like the dict.update looks almost there but i can't get it to work properly, can anyone offer any advise? From st1999 at gmail.com Sun Sep 28 15:52:58 2008 From: st1999 at gmail.com (robean) Date: Sun, 28 Sep 2008 12:52:58 -0700 (PDT) Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> Message-ID: <357e734f-e99f-41e5-9cac-083d636a23e1@n38g2000prl.googlegroups.com> On Sep 28, 12:27?pm, robean wrote: > On Sep 28, 12:11?pm, "Chris Rebert" wrote: > > > > > On Sun, Sep 28, 2008 at 11:03 AM, robean wrote: > > > Hi everyone, > > > > I have a question about using urllib2. > > > > I like urllib2 better than urllib at least in part because it has more > > > elaborate support for handling errors: there is built in support for > > > URLError (for faulty urls) and HTTPError (for http errors that might > > > originate from, say, passing an invalid stock-ticker in the program > > > below). ?However I can get neither to work. ?I'm attaching below the > > > (very short) code: can anyone point out what I'm doing wrong? > > > > Now, if I replace the URLError and HTTPError with IOError (the class > > > from which both URLError and HTTPError inherit), the program works > > > fine. Why is it that I can call the generic IOError class, but none of > > > the Error classes derived from that? These are clearly defined in the > > > urllib2 manual. Very confused... > > > > Here's the code: > > > > import urllib2 > > > > # read stock information from yahoo finance for Traget (TGT) > > > goodTicker = 'TGT' # program works with this > > > badTicker = 'TGTttttttt' # python doesn't understand either HTTPError > > > or URLError with this > > > > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > > > try: > > > ? ? ? ?handle = urllib2.urlopen(url) > > > > # this does not work > > > except HTTPError, e: > > > ? ? ? ?print "There was an http error" > > > ? ? ? ?print e > > > > # this also does not work > > > except URLError, e: > > > ? ? ? ?print "There is a problem with the URL" > > > ? ? ? ?print e > > > ? ? ? ?exit(1) > > > > #this works > > > except IOError, e: > > > ? ? ? ?print "You have an IOError" > > > ? ? ? ?print e > > > > text = handle.readlines()[:20] > > > for line in text: > > > ? ? ? ?print line > > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > My Python begs to differ: > > > #tmp.py > > import urllib2 > > > badTicker = 'TGTttttttt' > > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > > try: > > ? ? handle = urllib2.urlopen(url) > > > except urllib2.HTTPError, e: > > ? ? print "There was an http error" > > ? ? print e > > > except urllib2.URLError, e: > > ? ? print "There is a problem with the URL" > > ? ? print e > > > except urllib2.IOError, e: > > ? ? print "You have an IOError" > > ? ? print e > > > #in the shell > > $ python -V > > Python 2.5.1 > > $ python Desktop/tmp.py > > There was an http error > > HTTP Error 404: Not Found > > > Are you using an outdated version of Python perhaps? > > > Regards, > > Chris > > > -- > > Follow the path of the Iguana...http://rebertia.com > > Then I expect that it is most likely my version of python that is > causing the problem. I'm using 2.5.2. Actually, the problem seems to be that IOError is in my namespace, but the other error classes are not. So, except HTTPError, etc. fails, but except urllib2.HttpError, etc. works fine. Now, I still don't understand why these classes shouldn't automatically work.... From bmihelac at gmail.com Fri Sep 12 11:46:56 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Fri, 12 Sep 2008 08:46:56 -0700 (PDT) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <43cbb6e3-d463-4cf0-a05a-62c78b02a5f3@25g2000hsx.googlegroups.com> On Sep 12, 5:35?pm, Wojtek Walczak wrote: > On Fri, 12 Sep 2008 08:08:18 -0700 (PDT), Bojan Mihelac wrote: > > Hi all - when trying to set some dynamic attributes in class, for > > example: > > > class A: > > ? ? for lang in ['1', '2']: > > ? ? ? ? exec('title_%s = lang' % lang) #this work but is ugly > > ? ? ? ? # setattr(A, "title_%s" % lang, lang) # this wont work > > I guess A class not yet exists in line 4. Is it possible to achive > > adding dynamic attributes without using exec? > > Yes, it is: > > ------------- > class A: > ? ?for i in (1, 2): > ? ? ? locals()['xxx%d' % (i)] = i > > print A.xxx1 > print A.xxx2 > a = A() > print a.xxx1 > print a.xxx2 > ------------- > > And the output is: > > ----- > 1 > 2 > 1 > 2 > ----- > > But I definitely don't consider this one as a good programming > practice. > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ thnx Wojtek, this works! From ezra.taylor at gmail.com Tue Sep 30 14:13:02 2008 From: ezra.taylor at gmail.com (Ezra Taylor) Date: Tue, 30 Sep 2008 14:13:02 -0400 Subject: [Tutor] Replacing cmd.exe with custom .py application In-Reply-To: References: Message-ID: Joseph: Check out subprocess. The subprocess module is on python 2.4. Also, use subprocess.call("your command",shell=True) On Linux/Unix, the process is below import subprocess ret = subprocess.call("dir",shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT) print ret You should get a return value of 0. Which means that it was successful. I'm still learning this myself, so some of these other guys might have more input. On Tue, Sep 30, 2008 at 10:32 AM, A. Joseph wrote: > > > Instead of going to the command line all the time, I want to create a small > customized cmd.exe of my own, how can I get the return value from > os.system() because I was thinking I can do soothing with os.system(), In > case my question is not clear, just like an IDE that plugged in another > .exe application. > > > > Sorry for any mistake in my question. Just help me if you can > > _______________________________________________ > Tutor maillist - Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Ezra Taylor From darcy at druid.net Fri Sep 26 12:38:48 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 26 Sep 2008 12:38:48 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> Message-ID: <20080926123848.98c06cd5.darcy@druid.net> On Fri, 26 Sep 2008 11:00:59 -0500 "Michael Mabin" wrote: > So we can drop a table in an in clause? How is this a use case. Cartoons > are funny but actual proof that this example using an in-clause provides an > exploit would be more helpful I think. I'm not sure what proof you require. If you program such that users can enter arbitrary stings into your database it is obvious that the exploit in that cartoon can be used against you. And the point is that it has nothing to do with IN clauses. It can be any SQL. Go read that cartoon carefully. It says nothing about IN clauses. Consider; "UPDATE student SET name = '%s' WHERE student_id = %s" % (name, id); Now set name to "Robert'; DROP TABLE student;" and see what happens if you feed that to your SQL database. Hell, just put "';" in the string for fun. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From siegfried at heintze.com Sat Sep 13 21:27:22 2008 From: siegfried at heintze.com (Siegfried Heintze) Date: Sat, 13 Sep 2008 18:27:22 -0700 Subject: Python a good choice for experimenting with Win32 API? References: <98qdnS2nk4rpEVfVnZ2dnUVZ_qHinZ2d@comcast.com> <09601c7a-a138-4163-9265-286f87ef5767@y21g2000hsf.googlegroups.com> Message-ID: I found this but have not tried it yet: http://aspn.activestate.com/ASPN/Mail/Message/ActivePython/1775844 How different is ActiveState Python from CPython? Can they both be used with pywin32 and the other packages? Thanks! Siegfried From bj_666 at gmx.net Tue Sep 9 09:39:20 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Sep 2008 13:39:20 GMT Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: <6inck8Frl5ktU1@mid.uni-berlin.de> On Tue, 09 Sep 2008 08:19:04 -0500, Larry Bates wrote: >> I really dont care if the expression is optimal. So the goal is >> something like: >> >> vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| >> u|ii|i)' >> >> Is there a public module available for this purpose? >> >> >> > Perhaps I'm missing something but your function call oneOf(...) is > longer than than actually specifying the result. > > You can certainly write quite easily: > > def oneOf(s): > return "|".join(s.split()) I'd throw `re.escape()` into that function just in case `s` contains something with special meaning in regular expressions. Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Thu Sep 11 04:08:45 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 Sep 2008 08:08:45 GMT Subject: dict slice in python (translating perl to python) References: Message-ID: hofer wrote: > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? One point I haven't seen in the other responses is that, at least for the example given, you don't need the second line at all: mydict={ 'one': 1, 'two': 2, 'three': 3 } print "%(one)s\n%(two)s\n%(two)s" % mydict -- Duncan Booth http://kupuguy.blogspot.com From siegfried at heintze.com Fri Sep 12 11:36:18 2008 From: siegfried at heintze.com (Siegfried Heintze) Date: Fri, 12 Sep 2008 08:36:18 -0700 Subject: Python a good choice for experimenting with Win32 API? Message-ID: <98qdnS2nk4rpEVfVnZ2dnUVZ_qHinZ2d@comcast.com> I need to understand some User32.dll functions and I'm making an elaborate GUI so I can easily experiment with different parameters. This is taking a long time. I'm new to python and I'm thinking it would sure be nice to have an interpreter I can type a few lines of code into and test things. (1) Would CPython be a good choice for this? How about iron python? How about Jython (probably not). (2) What about callbacks? Which pythons can handle callbacks? I read on msdn that you cannot use managed code to call SetWindowsHook and supply a call back (with two exceptions). I guess that means I cannot use iron python. What about C-Python for playing with hooks? (3) How easy it it define the C structs, enums and integer constants necessary to call the windows API functions? (4) Here is the code I'm struggling with presently (it is just not cooperating: no errors just wrong results! I expect to be able give it a scan code, get a virtual key code, change the arguments, give it the virtual key code and get the original scan code back again). public const UInt32 MAPVK_VK_TO_VSC = 0, MAPVK_VSC_TO_VK = 1, MAPVK_VK_TO_CHAR = 2, MAPVK_VSC_TO_VK_EX = 3, MAPVK_VK_TO_VSC_EX = 4; public const UInt32 KLF_ACTIVATE = 1, KLF_SUBSTITUTE_OK = 2, KLF_REORDER = 8, KLF_REPLACELANG = 0x10, KLF_NOTELLSHELL = 0x80, KLF_SETFORPROCESS = 0x00100, KLF_SHIFTLOCK = 0x10000, KLF_RESET = 0x40000000; [DllImport("user32.dll")] static extern IntPtr LoadKeyboardLayout(string pwszKLID, uint Flags); [DllImport("user32.dll")] static extern bool UnloadKeyboardLayout(IntPtr hkl); [DllImport("user32.dll")] static extern uint MapVirtualKeyEx(uint uCode, uint uMapType, IntPtr dwhkl); private void Compute() { IntPtr hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE | KLF_SUBSTITUTE_OK | KLF_REPLACELANG); uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl); UpdateOutput(); } Would it be easy to execute this in the CPython interpreter or am I better off sticking with C#? Thanks! Siegfried From ivan.illarionov at gmail.com Thu Sep 4 15:15:16 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 4 Sep 2008 12:15:16 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> On 4 ????, 22:59, Carl Banks wrote: > You can write code to guard against this if you want: > > class A: > ? ? legal = set(["x"]) > ? ? def __setattr__(self,attr,val): > ? ? ? ? if attr not in self.legal: > ? ? ? ? ? ? raise AttributeError("A object has no attribute '%s'" % > attr) > ? ? ? ? self.__dict__[attr] = val > ? ? def __init__(self,x): > ? ? ? ? self.y = x > > I suspect most people who go into Python doing something like this > soon abandon it when they see how rarely it actually catches anything. > > Carl Banks '__slots__' is better: class A(object): __slots__ = set(["x"]) def __init__(self, x): self.y = x this will do the same, only faster >>> A(1) Traceback (most recent call last): File "", line 1, in File "", line 4, in __init__ AttributeError: 'A' object has no attribute 'y' Ivan Illarionov From bj_666 at gmx.net Mon Sep 22 09:08:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Sep 2008 13:08:06 GMT Subject: Encoding.ASCII.GetBytes similar for Python ? References: <463f31b8-ba48-4833-8d41-9aa5f1cae189@a70g2000hsh.googlegroups.com> Message-ID: <6jpjlmF4bg74U1@mid.uni-berlin.de> On Mon, 22 Sep 2008 04:23:09 -0700, Rui wrote: > Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with > the strings. I am trying to query some dns server to check its response > using udp sockets. Some of the source below: > > # encoding: utf8 > import socket > import sys > import struct > > IP_PORT = 53 > server_host = ('4.2.2.1', IP_PORT) > transaction_id = "Q1" > TIMEOUT = 5 > > type_string = > "\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000" > trailer_string = "\u0000\u0000\u0001\u0000\u0001" Are you sure you want normal byte strings with *that* content!? In [90]: s = "\u0000\u0000\u0001\u0000\u0001" In [91]: len(s) Out[91]: 30 In [92]: print s \u0000\u0000\u0001\u0000\u0001 This is not 5 unicode characters but 30 ASCII characters. But why using unicode anyway? I guess the DNS server expects bytes and not unicode characters. > address = 'google.com' > url_name_start, domain_name = address.split(".") > > # Query format copied from the C# example. #QueryString = TransactionID1 > + TypeString + (char)URLNameStart.Length + URLNameStart + > (char)DomainName.Length + DomainName+ TrailerString; query = > (transaction_id + type_string + str(len(url_name_start)) + > url_name_start + > str(len(domain_name)) + domain_name + trailer_string) > print query > > sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > sock.settimeout(TIMEOUT) > sock.connect(server_host) > > sock.send(query) > data = sock.recv(512) > > for data_item in data: > try: > print chr(data_item) > except: > print data_item This will always end up in the ``except`` branch because `data` is a string and `chr()` expects integers. Any chance you wanted `ord()` instead? When you print out "trash" please use `repr()` so we can see what trash *exactly* you get. Ciao, Marc 'BlackJack' Rintsch From paul at boddie.org.uk Mon Sep 29 09:28:47 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 29 Sep 2008 06:28:47 -0700 (PDT) Subject: Web programming in Python. References: Message-ID: <6191000e-2787-45f4-a7f4-4238b3e6d5ad@y38g2000hsy.googlegroups.com> On 29 Sep, 01:51, Kurda Yon wrote: > 1. On my server (in my directory) I found "cgi-bin" subdirectory. > > 2. In the "cgi-bin" I have created a file "test.py". > > 3. In that file I put: > #!/usr/bin/python2.4 python > print "Hello, World!" > (I have checked, I have "/usr/bin/python2.4" directory.) What's the spare "python" for at the end of the first line? You should also try and run the program directly just to see whether it runs and what it prints. > 4. I give the following permissions to the "test.py": > -rwx---r-x > > 5. The "cgi-bin" directory has the following permissions: > drwx---r-x This is probably acceptable. > 6. In the "cgi-bin" I have created the ".htaccess" file which > contains: > Options +ExecCGI > AddHandler cgi-script .py > > And it still does not work! If I try to see the page by my browser I > see: > Internal Server Error > The server encountered an internal error or misconfiguration and was > unable to complete your request. > ... Read the error log, possibly found in a log directory in your home directory (since you seem to be in a hosting environment, but you'd look in /var/log/httpd or /var/log/apache for a system-wide Web server installation) and see what the complaint is. You might also consider looking at the following page for guidance: http://wiki.python.org/moin/CgiScripts Paul From gslindstrom at gmail.com Wed Sep 10 16:04:57 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Wed, 10 Sep 2008 15:04:57 -0500 Subject: Python and Open Office Message-ID: Hello, I would like to create and manipulate Open Office documents using Python. I have found then UNO Python page and odfpy modules which seem to be exactly what I need. The odfpy manual is, to me, a confusing list of objects and methods (it's an impressive list!), but does not have much in the way of how to use them. For example, I can open a spreadsheet and create new pages (there's a nice example near the back of the manual) but I can't figure out how to open an existing spreadsheet and list the names of the individual sheets ("tabs"). I have written an application that access Microsoft Excel and creates reports for work, but would like to create an Open Source version using Open Office and release it to the community (and maybe get a talk at PyCon :-). Is there someone here who can help me out, or is there an appropriate mailing list for me to join? Thanks --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From agostino.russo at gmail.com Tue Sep 9 14:47:52 2008 From: agostino.russo at gmail.com (ago) Date: Tue, 9 Sep 2008 11:47:52 -0700 (PDT) Subject: PYTHONSITEDIR environment variable References: Message-ID: Small variation on the above patch, using 2 environment variables: PYTHONSITEDIR allows for local site-packages (that override system site packages), and PYTHONNOSYSSITES skips system site-packages for "clean-room" operation (similar to virtual-python.py --no-site- packages). --- /usr/lib/python2.5/site.py 2008-05-29 22:03:04.000000000 +0100 +++ /tmp/site.py 2008-09-09 19:56:44.000000000 +0100 @@ -167,6 +167,11 @@ def addsitepackages(known_paths): """Add site-packages (and possibly site-python) to sys.path""" + sitedir = os.environ.get('PYTHONSITEDIR') + if sitedir and os.path.isdir(sitedir): + addsitedir(sitedir, known_paths) + if os.environ.get('PYTHONNOSYSSITES'): + return None prefixes = [sys.prefix] if sys.exec_prefix != sys.prefix: prefixes.append(sys.exec_prefix) From bj_666 at gmx.net Tue Sep 16 15:46:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Sep 2008 19:46:09 GMT Subject: optparse References: Message-ID: <6jago1F2103eU3@mid.uni-berlin.de> On Tue, 16 Sep 2008 21:35:05 +0200, Torsten Mohr wrote: > parser.add_option("-v", "--verbose", > dest = 'verb', > help = 'be loud', > action = 'store_true', > default = 'store_false') > > (opts, args) = parser.parse_args() > > print "opts", opts > print "args", args > ------example > > If i call it without any parameters i get: > > opts {'verb': 'store_false'} > args [] > > > I would rather like to see the actual value False in "opts", did i use > some wrong parameters somewhere? if you want `False` as default you should actually use `False` and not the string 'store_false'. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Sep 11 19:28:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Sep 2008 20:28:32 -0300 Subject: function return References: <48C9242E.6090509@mattnordhoff.com> Message-ID: En Thu, 11 Sep 2008 10:59:10 -0300, Matt Nordhoff escribi?: >> result = "%s\t%s\t%s" %(id,gene_symbol,ptms) > > This is very trivial, but you could change the above line to: > > result = "\t".join(id, gene_symbol, ptms) So trivial that you did not even attempt to test it, I presume. It must obviously work... except it doesn't :) result = "\t".join((id, gene_symbol, ptms)) -- Gabriel Genellina From andis59 at gmail.com Wed Sep 10 03:57:52 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Wed, 10 Sep 2008 09:57:52 +0200 Subject: I want to use a C++ library from Python Message-ID: Hello, I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1 .lib and 1 .dll files. I don't have the source code. How can I create a Python module from these files? // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! From ppearson at nowhere.invalid Sun Sep 21 13:48:23 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 21 Sep 2008 17:48:23 GMT Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> <974c3434-d409-484d-8bc4-7a3294132bd0@73g2000hsx.googlegroups.com> Message-ID: <6jnfn6F47453U2@mid.individual.net> On Sun, 21 Sep 2008 06:17:36 -0700 (PDT), Alex wrote: > On 21 Set, 15:07, George Sakkis wrote: >> On Sep 21, 8:51 am, Alex wrote: [snip] >> > I have a problem understanding the behaviour of this snippet: [snip] >> Because you're doing a shallow copy: >> http://docs.python.org/lib/module-copy.html [snip] > Thanks a lot. It was giving me and headache! FWIW, since I started following this newsgroup, I've noticed that I no longer have those crises that revolve around the depth of a copy. I conjecture that they resulted from non-pythonic style. Try following this newsgroup for a while, and you might see a lot of startlingly elegant ways of doing things. -- To email me, substitute nowhere->spamcop, invalid->net. From torriem at gmail.com Sat Sep 27 07:23:50 2008 From: torriem at gmail.com (Michael Torrie) Date: Sat, 27 Sep 2008 05:23:50 -0600 Subject: How to get the filename in the right case ? In-Reply-To: References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> Message-ID: <48DE17C6.9090001@gmail.com> Steven D'Aprano wrote: > On Fri, 26 Sep 2008 01:46:15 +0200, Stef Mientki wrote: > >> Secondly thoughtless copying of current behavior, doesn't bring any >> progress, >> and I think that's one of the reasons why we're still burdened by >> inventions done 20 years ago, >> e.g. "do you want to save your changes ?". > > I click No about 50% of the time, and Yes Of Course You Stupid Machine > the other 50% of the time. Until they have a computer capable of reading > my mind, I'm curious what alternative you'd suggest. It's well known that just using "Yes" and "No" in a dialog box is very, very poor UI design. In many cases it leads to confusion. Especially when the dialog box has both a statement and a question, which many do. The correct and proper way is to use only verbs in the buttons. For example instead of yes/no to the question of saving work before exiting, you'd use "save" and "don't save." That's extremely clear even if you don't quite understand the statement and question the dialog is asking. Certainly the human-interface guidelines on the more sane systems out there (OS X, Gnome) disallow the use of yes/no buttons in dialog boxes. From zentraders at gmail.com Mon Sep 1 22:46:05 2008 From: zentraders at gmail.com (Zentrader) Date: Mon, 1 Sep 2008 19:46:05 -0700 (PDT) Subject: (in memory) database References: <5enqo5-9n9.ln1@lairds.us> Message-ID: <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> On Ubuntu you want to install something like python-sqlite (a search for "python" should turn up everything). There are 2 parts to this, SQLite and the python bindings to SQLite. So you seem to have SQLite installed but not the Python bindings. Also, on some systems you have to have python-sqlite installed, and then build python in order to use it. I'm on Gentoo so I can't help you with Ubuntu, but here's something I had lying around that uses a DB in memory (no idea why I did this or if it makes sense but you're welcome to it import sqlite3 as sqlite .##---------------------------------------------------------------------- .def add_rec(cur, con, add_tuple): . print "add_rec", len(add_tuple) . cur.execute("insert into test_it values (?, ?, ?, ?, ?, ?, ?, ?, ?)", add_tuple) . con.commit() . .##---------------------------------------------------------------------- .def print_all_recs(cur): . # Execute the SELECT statement: . print "Printing all recs" . cur.execute("select * from test_it") . . # Retrieve all rows as a sequence and print that sequence: . recs_list = cur.fetchall() . for rec in recs_list: . print rec . print " stage, REAC_W =", rec[1], rec[5] . .##---------------------------------------------------------------------- .def add_test_data(cur, con): . # Stage REAC_PS WR(T)/P TTO REAC_W W0 0wR(THCR)E/D PTO . data_list=[ ('2.0', 'Stage1', '0.509', '4.3010', '1602.30', '0.515', '3.191', '2.8191', '29.7010'), \ . ('2.0', 'Stage2', '0.488', '6.0074', '1470.43', '0.500', '3.200', '3.9309', '20.4275'), \ . ('2.0', 'Stage1', '0.524', '4.4623', '1602.30', '0.560', '3.311', '2.9243', '29.7010'), \ . ('2.0', 'Stage2', '0.579', '6.6682', '1444.78', '0.700', '3.320', '4.3593', '18.9262'), \ . ('3.0', 'Stage1', '0.524', '4.4623', '1602.30', '0.560', '3.311', '2.9243', '29.7010'), \ . ('3.0', 'Stage2', '0.579', '6.6682', '1444.78', '0.700', '3.320', '4.3593', '18.9262'), \ . ('3.5', 'Stage1', '0.525', '4.4695', '1602.30', '0.563', '3.316', '2.9290', '29.7010') ] . . for data_tuple in data_list : . add_rec(cur, con, data_tuple) . .##---------------------------------------------------------------------- .if __name__ == "__main__": . # Create a connection to the (memory) database file . con = sqlite.connect(':memory:') . . # Get a Cursor object that operates in the context of Connection con . cur = con.cursor() . . cur.execute("CREATE TABLE test_it (number varchar, stage varchar, REAC_PS varchar, WR_T_P varchar, TTO varchar, REAC_W varchar, W0 varchar, wR_THCR_E_D varchar, PTO varchar)") . . add_test_data(cur, con) . print_all_recs(cur) . .##---------------------------------------------------------------------- . print '\n-----SELECT * FROM test_it where number="2.0"-------' . recs_list=cur.execute('SELECT * FROM test_it where number="2.0"') . ctr=0 . for row in recs_list: . print row . ctr += 1 . print ctr, "recs found" . . print '\n-----SELECT * FROM test_it where number="2.0" and stage="Stage1"' . lookup_dic={"dic_num":"2.0", "dic_st":"Stage1"} . recs_list=cur.execute('SELECT * FROM test_it where number=:dic_num and stage=:dic_st', \ . lookup_dic) . ctr=0 . for row in recs_list: . print row . ctr += 1 . print ctr, "recs found" From mensanator at aol.com Thu Sep 4 01:57:19 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 3 Sep 2008 22:57:19 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> Message-ID: <81ea803c-3108-4c9b-b9bc-2334729321f5@z6g2000pre.googlegroups.com> On Sep 4, 12:20?am, Mensanator wrote: > On Sep 3, 8:30 pm, Steven D'Aprano > cybersource.com.au> wrote: > > On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: > > >>>> sum([]) > > > 0 > > > > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It > > > should return None or throw an exception like sum([None,1]) does. > > > You're wrong, because 99.9% of the time when users leave a blank cell in > > Excel, they want it to be treated as zero. > > Then 99.9% of users want the wrong thing. Microsoft knows that > this is a bug but refuses to fix it to prevent breaking legacy > documents (probably dating back to VisiCalc). When graphimg data, > a missing value should be interpreted as a hole in the graph > > +------+ ? ? ? ? ? ? +--+------+------+-----+ > > and not evaluated as 0 > > +------+ ? ? ? ? ? ? +--+------+------+-----+ > ? ? ? ? \ ? ? ? ? ? / > ? ? ? ? ?\ ? ? ? ? / > ? ? ? ? ? \ ? ? ? / > ? ? ? ? ? ?\ ? ? / > ? ? ? ? ? ? \ ? / > ? ? ? ? ? ? ?\+/ > > (depending on the context of the graph, of course). > > And Microsoft provides a workaround for graphs to make 0's > appear as holes. Of course, this will cause legitimate 0 > values to disappear, so the workaround is inconsistent. I just checked and I mis-remembered how this works. The option is for blanks to plot as holes or 0 or be interpolated. 0 always plots as 0. The inconsistency is that blanks are still evaluated as 0 in formulae and macros. > > > Spreadsheet sum() is not the > > same as mathematician's sum, which doesn't have a concept of "blank > > cells". (But if it did, it would treat them as zero, since that's the > > only useful thing and mathematicians are just as much pragmatists as > > spreadsheet users.) The Excel code does the right thing, and your "pure" > > solution would do the unwanted and unexpected thing and is therefore > > buggy. > > Apparently, you don't use databases or make surface contours. > Contour programs REQUIRE that blanks are null, not 0, so that > the Kriging algorithm interpolates around the holes rather than > return false calculations. Excel's treatment of blank cells is > inconsistent with Access' treatment of Nulls and therefore wrong, > anyway you slice it. Math isn't a democracy, what most people want > is irrelevant. > > I don't pull these things out of my ass, it's real world stuff > I observe when I help CAD operators and such debug problems. > > Maybe you want to say a bug is when it doesn't do what the > author intended, but I say if what the intention was is wrong, > then a perfect implentation is still a bug because it doesn't > do what it's supposed to do. > > > > > Bugs are defined by "does the code do what the user wants it to do?", not > > "is it mathematically pure?". > > ReallY? So you think math IS a democracy? There is no reason to > violate > mathematical purity. If I don't get EXACTLY the same answer from > Excel, > Access, Mathematica and Python, then SOMEBODY is wrong. It would be a > shame if that somebody was Python. > > > The current behaviour of sum([]) does the > > right thing for the 99% of the time when users expect an integer. > > Why shouldn't the users expect an exception? Isn't that why we have > try:except? Maybr 99% of users expect sum([])==0, but _I_ expect to > be able to distinguish an empty list from [4,-4]. > > > And the > > rest of the time, they have to specify a starting value for the sum > > anyway, and so sum([], initial_value) does the right thing *always*. > > So if you really want [] to be 0, why not say sum([],0)? > > Why shouldn't nothing added to nothing return nothing? > Having it evaluate to 0 is wrong 99.9% of the time. > > > > > > > The only time it does the wrong thing[1] is when you forget to pass an > > initial value but expect a non-numeric result. And that's the > > programmer's error, not a function bug. > > > [1] I believe it also does the wrong thing by refusing to sum strings, > > but that's another story. > > > -- > > Steven- Hide quoted text - > > - Show quoted text - From monuindia at gmail.com Mon Sep 8 13:19:01 2008 From: monuindia at gmail.com (Monu) Date: Mon, 8 Sep 2008 10:19:01 -0700 (PDT) Subject: shelve file name extention Message-ID: Hi All, When I am using shelve on my local machine it generates the db file as given filename. But in another machine it's generating .dat and .dir. can anyone tell me how can I force sheve module to write the db in .dir and .dat, instead of ? Do I have to install a specific version of the python? Thanks... Monu From kar1107 at gmail.com Wed Sep 24 23:14:43 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Wed, 24 Sep 2008 20:14:43 -0700 (PDT) Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: <4a069897-855c-45f7-8f9e-90e3fcdce176@r15g2000prd.googlegroups.com> On Sep 24, 6:27?pm, Tim Arnold wrote: > I have a bunch of processes to run and each one needs its own working > directory. I'd also like to know when all of the processes are > finished. > > (1) First thought was threads, until I saw that os.chdir was process- > global. > (2) Next thought was fork, but I don't know how to signal when each > child is > finished. > (3) Current thought is to break the process from a method into a > external > script; call the script in separate threads. ?This is the only way I > can see > to give each process a separate dir (external process fixes that), and > I can > find out when each process is finished (thread fixes that). > > Am I missing something? Is there a better way? I hate to rewrite this > method > as a script since I've got a lot of object metadata that I'll have to > regenerate with each call of the script. Use subprocess; it supports a cwd argument to provide the given directory as the child's working directory. Help on class Popen in module subprocess: class Popen(__builtin__.object) | Methods defined here: | | __del__(self) | | __init__(self, args, bufsize=0, executable=None, stdin=None, stdout=None, st derr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, un iversal_newlines=False, startupinfo=None, creationflags=0) | Create new Popen instance. You want to provide the cwd argument above. Then once you have launched all your n processes, run thru' a loop waiting for each one to finish. # cmds is a list of dicts providing details on what processes to run.. what it's cwd should be runs = [] for c in cmds: run = subprocess.Popen(cmds['cmd'], cwd = cmds['cwd'] ..... etc other args) runs.append(run) # Now wait for all the processes to finish for run in runs: run.wait() Note that if any of the processes generate lot of stdout/stderr, you will get a deadlock in the above loop. Then you way want to go for threads or use run.poll and do the reading of the output from your child processes. Karthik > > thanks for any suggestions, > --Tim Arnold From ggpolo at gmail.com Wed Sep 3 20:26:27 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 3 Sep 2008 21:26:27 -0300 Subject: Help with Tkinter Label Widget In-Reply-To: <293826.25281.qm@web83915.mail.sp1.yahoo.com> References: <293826.25281.qm@web83915.mail.sp1.yahoo.com> Message-ID: On Wed, Sep 3, 2008 at 8:57 PM, Kevin McKinley wrote: > Below i've put the code for a program that i wrote. I need help on lines 384-403. If you run this program you will notice on the first tab when have it produce an answer the $ is surrounded with {$}. How can i get rid of that? Come on.. "help on lines 384-403", that is not a good way to look for help. You are supposed to post some minimal code that demonstrates the problem. Anyway, this demonstrates what you are getting (independent of python version): import Tkinter label = Tkinter.Label() label['text'] = '$', 2.0 label.pack() label.mainloop() The problem is that you are relying on something that is not supposed to be done. Note how you are passing a tuple to the "text" option, while you are actually supposed to pass a single value. You should be passing something like this instead: label['text'] = '$%f' % 2.0 > > > > from Tkinter import * > > class MyApp: > def __init__(self, parent): > self.myparent = parent > > self.frame1 = Frame(parent) > self.frame1.grid(row=0, column=0) > > self.frame2 = Frame(parent) > self.frame2.grid(row=0, column=0) > > self.frame3 = Frame(parent) > self.frame3.grid(row=0, column=0) > > self.frame4 = Frame(parent) > self.frame4.grid(row=0, column=0) > > self.a = self.b = self.c = self.d = 0 > > self.COG1 = DoubleVar(); self.COG2 = DoubleVar(); self.COG3 = DoubleVar(); self.COG4 = DoubleVar() > self.GP1 = DoubleVar(); self.PrInc = DoubleVar(); self.markupPrice = DoubleVar() > > self.tab1Func(1) > > def tab1Func(self, event): > self.tab1 = Button(self.frame1, width=14, relief=FLAT, bg="white", text="Multi-Markup") > self.tab1.bind("", self.switch1) > self.tab1.grid(row=0, column=0) > > self.tab2 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") > self.tab2.bind("", self.switch2) > self.tab2.grid(row=0, column=1) > > self.tab3 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") > self.tab3.bind("", self.switch3) > self.tab3.grid(row=0, column=2) > > self.tab4 = Button(self.frame1, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") > self.tab4.bind("", self.switch4) > self.tab4.grid(row=0, column=3) > > self.tab1Title = Label(self.frame1, font="bold", relief=GROOVE, text="Multi-Markup Calculator") > self.tab1Title.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) > > self.tab1Entry1 = Entry(self.frame1, textvariable=self.COG1) > self.tab1Entry1.select_range(0, END) > self.tab1Entry1.bind("", self.multiMarkup) > self.tab1Entry1.focus_force() > self.tab1Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) > > self.tab1Entry1Title= Label(self.frame1, text="Enter COG:") > self.tab1Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) > > self.tab1CalcButton = Button(self.frame1, text="Calculate") > self.tab1CalcButton.bind("", self.multiMarkup) > self.tab1CalcButton.bind("", self.multiMarkup) > self.tab1CalcButton.grid(padx=2, pady=2, row=3, column=1, columnspan=2, sticky=W+E) > > self.tab1Header = Label(self.frame1, font="bold", relief=GROOVE, text="Gross Profit % Markup Price") > self.tab1Header.grid(padx=2, pady=2, row=4, column=0, columnspan=4, sticky=W+E) > > self.tab1GP1 = Label(self.frame1, width=4,relief=RIDGE, bg="white", text="5%") > self.tab1GP1.grid(padx=2, pady=2, row=5, column=1) > > self.tab1GP2 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="10%") > self.tab1GP2.grid(padx=2, pady=2, row=6, column=1) > > self.tab1GP3 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="15%") > self.tab1GP3.grid(padx=2, pady=2, row=7, column=1) > > self.tab1GP4 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="18%") > self.tab1GP4.grid(padx=2, pady=2, row=8, column=1) > > self.tab1GP5 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="20%") > self.tab1GP5.grid(padx=2, pady=2, row=9, column=1) > > self.tab1GP6 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="21%") > self.tab1GP6.grid(padx=2, pady=2, row=10, column=1) > > self.tab1GP7 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="22%") > self.tab1GP7.grid(padx=2, pady=2, row=11, column=1) > > self.tab1GP8 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="23%") > self.tab1GP8.grid(padx=2, pady=2, row=12, column=1) > > self.tab1GP9 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="24%") > self.tab1GP9.grid(padx=2, pady=2, row=13, column=1) > > self.tab1GP10 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="25%") > self.tab1GP10.grid(padx=2, pady=2, row=14, column=1) > > self.tab1GP11 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="26%") > self.tab1GP11.grid(padx=2, pady=2, row=15, column=1) > > self.tab1GP12 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="27%") > self.tab1GP12.grid(padx=2, pady=2, row=16, column=1) > > self.tab1GP13 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="28%") > self.tab1GP13.grid(padx=2, pady=2, row=17, column=1) > > self.tab1GP14 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="29%") > self.tab1GP14.grid(padx=2, pady=2, row=18, column=1) > > self.tab1GP15 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="30%") > self.tab1GP15.grid(padx=2, pady=2, row=19, column=1) > > self.tab1GP16 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="31%") > self.tab1GP16.grid(padx=2, pady=2, row=20, column=1) > > self.tab1GP17 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="33%") > self.tab1GP17.grid(padx=2, pady=2, row=21, column=1) > > self.tab1GP18 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="35%") > self.tab1GP18.grid(padx=2, pady=2, row=22, column=1) > > self.tab1GP19 = Label(self.frame1, width=4, relief=RIDGE, bg="white", text="40%") > self.tab1GP19.grid(padx=2, pady=2, row=23, column=1) > > self.tab1GP20 = Label(self.frame1, width=4, relief=RIDGE, bg="light grey", text="45%") > self.tab1GP20.grid(padx=2, pady=2, row=24, column=1) > > self.tab1Markup1 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup1.grid(padx=2, pady=2, row=5, column=2, sticky=E) > > self.tab1Markup2 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup2.grid(padx=2, pady=2, row=6, column=2, sticky=E) > > self.tab1Markup3 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup3.grid(padx=2, pady=2, row=7, column=2, sticky=E) > > self.tab1Markup4 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup4.grid(padx=2, pady=2, row=8, column=2, sticky=E) > > self.tab1Markup5 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup5.grid(padx=2, pady=2, row=9, column=2, sticky=E) > > self.tab1Markup6 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup6.grid(padx=2, pady=2, row=10, column=2, sticky=E) > > self.tab1Markup7 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup7.grid(padx=2, pady=2, row=11, column=2, sticky=E) > > self.tab1Markup8 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup8.grid(padx=2, pady=2, row=12, column=2, sticky=E) > > self.tab1Markup9 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup9.grid(padx=2, pady=2, row=13, column=2, sticky=E) > > self.tab1Markup10 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup10.grid(padx=2, pady=2, row=14, column=2, sticky=E) > > self.tab1Markup11 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup11.grid(padx=2, pady=2, row=15, column=2, sticky=E) > > self.tab1Markup12 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup12.grid(padx=2, pady=2, row=16, column=2, sticky=E) > > self.tab1Markup13 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup13.grid(padx=2, pady=2, row=17, column=2, sticky=E) > > self.tab1Markup14 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup14.grid(padx=2, pady=2, row=18, column=2, sticky=E) > > self.tab1Markup15 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup15.grid(padx=2, pady=2, row=19, column=2, sticky=E) > > self.tab1Markup16 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup16.grid(padx=2, pady=2, row=20, column=2, sticky=E) > > self.tab1Markup17 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup17.grid(padx=2, pady=2, row=21, column=2, sticky=E) > > self.tab1Markup18 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup18.grid(padx=2, pady=2, row=22, column=2, sticky=E) > > self.tab1Markup19 = Label(self.frame1, width=12, relief=RIDGE, bg="white") > self.tab1Markup19.grid(padx=2, pady=2, row=23, column=2, sticky=E) > > self.tab1Markup20 = Label(self.frame1, width=12, relief=RIDGE, bg="light grey") > self.tab1Markup20.grid(padx=2, pady=2, row=24, column=2, sticky=E) > > def tab2Func(self, event): > self.tab1 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") > self.tab1.bind("", self.switch1) > self.tab1.grid(row=0, column=0) > > self.tab2 = Button(self.frame2, width=14, relief=FLAT, bg="white", text="Single Markup") > self.tab2.bind("", self.switch2) > self.tab2.grid(row=0, column=1) > > self.tab3 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") > self.tab3.bind("", self.switch3) > self.tab3.grid(row=0, column=2) > > self.tab4 = Button(self.frame2, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") > self.tab4.bind("", self.switch4) > self.tab4.grid(row=0, column=3) > > self.tab2Title = Label(self.frame2, font="bold", relief=GROOVE, text="Single Markup Calculator") > self.tab2Title.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) > > self.tab2Entry1 = Entry(self.frame2, textvariable=self.COG2) > self.tab2Entry1.select_range(0, END) > self.tab2Entry1.bind("", self.singleMarkup) > self.tab2Entry1.focus_force() > self.tab2Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) > > self.tab2Entry2 = Entry(self.frame2, textvariable=self.GP1) > self.tab2Entry2.select_range(0, END) > self.tab2Entry2.bind("", self.singleMarkup) > self.tab2Entry2.focus_force() > self.tab2Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) > > self.tab2Entry1Title= Label(self.frame2, text="Enter COG:") > self.tab2Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) > > self.tab2Entry2Title= Label(self.frame2, text="Enter GP %:") > self.tab2Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) > > self.tab2CalcButton = Button(self.frame2, text="Calculate") > self.tab2CalcButton.bind("", self.singleMarkup) > self.tab2CalcButton.bind("", self.singleMarkup) > self.tab2CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) > > self.tab2Header = Label(self.frame2, font="bold", relief=GROOVE) > self.tab2Header["text"] = self.GP1.get(), "%","Markup" > self.tab2Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) > > self.tab2Markup1 = Label(self.frame2, width=10, font="bold", relief=GROOVE, bg="white") > self.tab2Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) > > def tab3Func(self, event): > self.tab1 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") > self.tab1.bind("", self.switch1) > self.tab1.grid(row=0, column=0) > > self.tab2 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") > self.tab2.bind("", self.switch2) > self.tab2.grid(row=0, column=1) > > self.tab3 = Button(self.frame3, width=14, relief=FLAT, bg="white", text="Product Increase") > self.tab3.bind("", self.switch3) > self.tab3.grid(row=0, column=2) > > self.tab4 = Button(self.frame3, width=14, relief=SUNKEN, bg="dark grey", text="Calculate GP") > self.tab4.bind("", self.switch4) > self.tab4.grid(row=0, column=3) > > self.tabTitle = Label(self.frame3, font="bold",relief=GROOVE, text="Product Increase Calculator") > self.tabTitle.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) > > self.tab3Entry1 = Entry(self.frame3, textvariable=self.COG3) > self.tab3Entry1.select_range(0, END) > self.tab3Entry1.bind("", self.priceIncrease) > self.tab3Entry1.focus_force() > self.tab3Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) > > self.tab3Entry2 = Entry(self.frame3, textvariable=self.PrInc) > self.tab3Entry2.select_range(0, END) > self.tab3Entry2.bind("", self.priceIncrease) > self.tab3Entry2.focus_force() > self.tab3Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) > > self.tab3Entry1Title= Label(self.frame3, text="Enter COG:") > self.tab3Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) > > self.tab3Entry2Title= Label(self.frame3, text="Enter Increase %:") > self.tab3Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) > > self.tab3CalcButton = Button(self.frame3, text="Calculate") > self.tab3CalcButton.bind("", self.priceIncrease) > self.tab3CalcButton.bind("", self.priceIncrease) > self.tab3CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) > > self.tab3Header = Label(self.frame3, font="bold", relief=GROOVE) > self.tab3Header["text"] = self.PrInc.get(), "%","Price","Increase" > self.tab3Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) > > self.tab3Markup1 = Label(self.frame3, width=10, font="bold", relief=GROOVE, bg="white") > self.tab3Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) > > def tab4Func(self, event): > self.tab1 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Multi-Markup") > self.tab1.bind("", self.switch1) > self.tab1.grid(row=0, column=0) > > self.tab2 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Single Markup") > self.tab2.bind("", self.switch2) > self.tab2.grid(row=0, column=1) > > self.tab3 = Button(self.frame4, width=14, relief=SUNKEN, bg="dark grey", text="Product Increase") > self.tab3.bind("", self.switch3) > self.tab3.grid(row=0, column=2) > > self.tab4 = Button(self.frame4, width=14, relief=FLAT, bg="white", text="Calculate GP") > self.tab4.bind("", self.switch4) > self.tab4.grid(row=0, column=3) > > self.tabTitle = Label(self.frame4, font="bold",relief=GROOVE, text="Calculate GP") > self.tabTitle.grid(pady=1, row=1, column=0, columnspan=4, sticky=W+E) > > self.tab4Entry1 = Entry(self.frame4, textvariable=self.COG4) > self.tab4Entry1.select_range(0, END) > self.tab4Entry1.bind("", self.GpCalc) > self.tab4Entry1.focus_force() > self.tab4Entry1.grid(padx=2, pady=2, row=2, column=2, columnspan=2, sticky=W) > > self.tab4Entry2 = Entry(self.frame4, textvariable=self.markupPrice) > self.tab4Entry2.select_range(0, END) > self.tab4Entry2.bind("", self.GpCalc) > self.tab4Entry2.focus_force() > self.tab4Entry2.grid(padx=2, pady=2, row=3, column=2, columnspan=2, sticky=W) > > self.tab4Entry1Title= Label(self.frame4, text="Enter COG:") > self.tab4Entry1Title.grid(padx=2, pady=2, row=2, column=1, sticky=E) > > self.tab4Entry2Title= Label(self.frame4, text="Enter Markup $:") > self.tab4Entry2Title.grid(padx=2, pady=2, row=3, column=1, sticky=E) > > self.tab4CalcButton = Button(self.frame4, text="Calculate") > self.tab4CalcButton.bind("", self.GpCalc) > self.tab4CalcButton.bind("", self.GpCalc) > self.tab4CalcButton.grid(padx=2, pady=2, row=4, column=1, columnspan=2, sticky=W+E) > > self.tab4Header = Label(self.frame4, font="bold", relief=GROOVE) > self.tab4Header["text"] = "Gross Profit" > self.tab4Header.grid(padx=2, pady=2, row=5, column=0, columnspan=4, sticky=W+E) > > self.tab4Markup1 = Label(self.frame4, width=10, font="bold", relief=GROOVE, bg="white") > self.tab4Markup1.grid(padx=2, pady=2, row=6, column=1, columnspan=2) > > def switch1(self, event): > self.frame1.grid(sticky=N+S+E+W) > self.frame2.grid_forget() > self.frame3.grid_forget() > self.frame4.grid_forget() > self.tab1Entry1.focus_force() > self.tab1Entry1.select_range(0, END) > > > def switch2(self, event): > if self.b == 0: > self.tab2Func(1) > self.b = 1 > self.frame1.grid_forget() > self.frame2.grid(sticky=N+S+E+W) > self.frame3.grid_forget() > self.frame4.grid_forget() > self.tab2Entry1.focus_force() > self.tab2Entry1.select_range(0, END) > > def switch3(self, event): > if self.c == 0: > self.tab3Func(1) > self.c = 1 > self.frame1.grid_forget() > self.frame2.grid_forget() > self.frame3.grid(sticky=N+S+E+W) > self.frame4.grid_forget() > self.tab3Entry1.focus_force() > self.tab3Entry1.select_range(0, END) > > def switch4(self, event): > if self.d == 0: > self.tab4Func(1) > self.d = 1 > self.frame1.grid_forget() > self.frame2.grid_forget() > self.frame3.grid_forget() > self.frame4.grid(sticky=N+S+E+W) > self.tab4Entry1.focus_force() > self.tab4Entry1.select_range(0, END) > > def multiMarkup(self, event): > try: > value = self.COG1.get() > except ValueError: > self.COG1 = DoubleVar() > self.tab1Entry1["textvariable"] = self.COG1 > > self.tab1Entry1.select_range(0, END) > > self.tab1Markup1["text"] = "$", round(self.COG1.get()/.95, 2) > self.tab1Markup2["text"] = "$", round(self.COG1.get()/.90, 2) > self.tab1Markup3["text"] = "$", round(self.COG1.get()/.85, 2) > self.tab1Markup4["text"] = "$", round(self.COG1.get()/.82, 2) > self.tab1Markup5["text"] = "$", round(self.COG1.get()/.80, 2) > self.tab1Markup6["text"] = "$", round(self.COG1.get()/.79, 2) > self.tab1Markup7["text"] = "$", round(self.COG1.get()/.78, 2) > self.tab1Markup8["text"] = "$", round(self.COG1.get()/.77, 2) > self.tab1Markup9["text"] = "$", round(self.COG1.get()/.76, 2) > self.tab1Markup10["text"] = "$", round(self.COG1.get()/.75, 2) > self.tab1Markup11["text"] = "$", round(self.COG1.get()/.74, 2) > self.tab1Markup12["text"] = "$", round(self.COG1.get()/.73, 2) > self.tab1Markup13["text"] = "$", round(self.COG1.get()/.72, 2) > self.tab1Markup14["text"] = "$", round(self.COG1.get()/.71, 2) > self.tab1Markup15["text"] = "$", round(self.COG1.get()/.70, 2) > self.tab1Markup16["text"] = "$", round(self.COG1.get()/.69, 2) > self.tab1Markup17["text"] = "$", round(self.COG1.get()/.67, 2) > self.tab1Markup18["text"] = "$", round(self.COG1.get()/.65, 2) > self.tab1Markup19["text"] = "$", round(self.COG1.get()/.60, 2) > self.tab1Markup20["text"] = "$", round(self.COG1.get()/.55, 2) > > def singleMarkup(self, event): > try: > value = self.COG2.get() > except ValueError: > self.COG2 = DoubleVar() > self.tab2Entry1["textvariable"] = self.COG2 > > try: > value = self.GP1.get() > except ValueError: > self.GP1 = DoubleVar() > self.tab2Entry2["textvariable"] = self.GP1 > > self.tab2Entry1.focus_force() > self.tab2Entry1.select_range(0, END) > > GP = 1 - (round((self.GP1.get()/100),2)) > > self.tab2Markup1["text"] = "$",round(self.COG2.get()/GP, 2) > self.tab2Header["text"] = self.GP1.get(), "%","Markup" > > def priceIncrease(self, event): > try: > value = self.COG3.get() > except ValueError: > self.COG3 = DoubleVar() > self.tab3Entry1["textvariable"] = self.COG3 > > try: > value = self.PrInc.get() > except ValueError: > self.PrInc = DoubleVar() > self.tab3Entry2["textvariable"] = self.PrInc > > self.tab3Entry1.focus_force() > self.tab3Entry1.select_range(0, END) > > increase = 1+(self.PrInc.get()/100) > > self.tab3Markup1["text"] = "$",round((self.COG3.get()*increase),2) > self.tab3Header["text"] = self.PrInc.get(), "%","Price","Increase" > > def GpCalc(self, event): > try: > value = self.COG4.get() > except ValueError: > self.COG4 = DoubleVar() > self.tab4Entry1["textvariable"] = self.COG4 > > try: > value = self.markupPrice.get() > except ValueError: > self.markupPrice = DoubleVar() > self.tab4Entry2["textvariable"] = self.markupPrice > > self.tab4Entry1.focus_force() > self.tab4Entry1.select_range(0, END) > > COG4 = self.COG4.get() > markup = self.markupPrice.get() > > if COG4==0.0 or markup==0.0: > self.tab4Markup1["text"] = "" > else: > GP = 100*(1-(self.COG4.get()/self.markupPrice.get())) > self.tab4Markup1["text"] = round(GP, 2),"%" > > > root = Tk() > myapp = MyApp(root) > root.mainloop() > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From jcd at sdf.lonestar.org Fri Sep 5 08:33:22 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 05 Sep 2008 08:33:22 -0400 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> <200809050059.17038.maric@aristote.info> <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> Message-ID: <1220618002.21923.12.camel@jcd-desktop> On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: > Thanks everyone for your help. I'm not opposed to using [key.lower() > for key in stage_map] at all, I was just curious to see if there were > any cleaner alternatives. It looks like that is what I'll be using. > I'm not familiar with how python works internally, but coming from C++ > it seems like "remaking" the map would be slow. However, speed is not > my main concern in my particular situation, I'm just curious to learn > more about python. You should be opposed to that particular solution. You have just taken a dictionary lookup (very fast) and turned it into a list traversal (slow). Even if speed isn't your main concern, this is an unnecessary de-optimization. You are deliberately slowing down your program to avoid a slightly more verbose lookup later. Your data structure might as well be a list of tuples to begin with, to avoid creating a new list. You have effectively made your keys useless as keys. If your lookups need to be case insensitive, make the key lower case, and store the cased version in the value, whether as a tuple or a dict (depending on whether you want named access). d = { 'foo': {'key': 'Foo', 'value': 'val1'} 'spam': {'key': 'sPAm', 'value': 'val2'} } search = 'FOO'.lower() if search in d: result = d[search] key = result['key'] value = result['value'] The only reason I wouldn't use this solution is if you expect to have keys that will be identical when made lowercase, but if you're doing case-insensitive lookup, you obviously don't expect this to be an issue. Cheers, Cliff From thkruege at uos.de Thu Sep 11 10:17:58 2008 From: thkruege at uos.de (Thorben Krueger) Date: Thu, 11 Sep 2008 16:17:58 +0200 Subject: huge socket recv speed discrepancy between different OSs Message-ID: <3b5d765a0809110717r51557eeey9d472c8ccc5ee34a@mail.gmail.com> Do you see this too? Mor information and testcase here: http://bugs.python.org/issue3766 I would also be interested in the profiler output under windows. All the best Thorben From tino at wildenhain.de Fri Sep 12 02:32:48 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 12 Sep 2008 08:32:48 +0200 Subject: How to Determine Name of the Day in the Week In-Reply-To: References: Message-ID: <48CA0D10.6040103@wildenhain.de> Henry Chang wrote: > Instead of getting integers with weekday(), Monday == 0 ... Sunday == 6; > is there a way to get the actual names, such as "Monday ... Sunday"? I > would like to do this without creating a data mapping. :) The 'actual names' in which language? Chinese, Russian, French, ... :) Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From ivanov.maxim at gmail.com Sun Sep 14 18:26:28 2008 From: ivanov.maxim at gmail.com (Max Ivanov) Date: Mon, 15 Sep 2008 02:26:28 +0400 Subject: pyprocessing/multiprocessing issue Message-ID: Good evening all. I try to use pyprocessing (aka multiprocessing in 2.6) module in my app, but run into problem. I use Pool and apply_async. It seems that it couldn't unpickle function which i pass to it, it gives me "AttributeError: 'module' object has no attribute 'do'" error where "do" is the name of dunction I pass to apply_async. Code is better than words, so I put as smallest test-case I could imagine. I suppose problem with different modules I use, becouse examples where everything fit in one file works great. -------------- next part -------------- A non-text attachment was scrubbed... Name: processing_error.tar.bz2 Type: application/x-bzip2 Size: 1098 bytes Desc: not available URL: From lists at cheimes.de Sun Sep 14 11:30:53 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 14 Sep 2008 17:30:53 +0200 Subject: how to exclude specific things when pickling? In-Reply-To: <7cd144b6-ca6f-447a-8448-5a334f8f999f@k37g2000hsf.googlegroups.com> References: <7cd144b6-ca6f-447a-8448-5a334f8f999f@k37g2000hsf.googlegroups.com> Message-ID: Michael Palmer wrote: > If your class defines a __getstate__ method, it is expected to return > the pickled state of the entire class. You can for example del those > items from self.__dict__ that you don't want pickled and then return > dumps(self). FYI: __getstate__ is ignored when __reduce__ is available. Christian From fredrik at pythonware.com Thu Sep 11 13:11:13 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 19:11:13 +0200 Subject: dict slice in python (translating perl to python) In-Reply-To: References: Message-ID: hofer wrote: > The real example would be more like: > > name,age,country = itemgetter('name age country'.split())(x) ouch. if you do this a lot (=more than once), just wrap your dictionaries in a simple attribute proxy, and use plain attribute access. that is, given class AttributeWrapper: def __init__(self, obj): self.obj = obj def __getattr__(self, name): try: return self.obj[name] except KeyError: raise AttributeError(name) or, shorter but less obvious and perhaps a bit too clever for a beginning Pythoneer: class AttributeWrapper: def __init__(self, obj): self.__dict__.update(obj) you can do >>> some_data = dict(name="Some Name", age=123, country="SE") >>> some_data {'country': 'SE', 'age': 123, 'name': 'Some Name'} >>> this = AttributeWrapper(some_data) >>> this.name 'Some Name' >>> this.age 123 >>> this.country 'SE' and, if you must, assign the attributes to local variables like this: >>> name, age, country = this.name, this.age, this.country >>> name 'Some Name' >>> age 123 >>> country 'SE' >>> (the next step towards true Pythonicness would be to store your data in class instances instead of dictionaries in the first place, but one step at a time...) From larry.bates at vitalEsafe.com Sat Sep 13 11:07:04 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 13 Sep 2008 10:07:04 -0500 Subject: testing if another instance of a script is already running In-Reply-To: References: Message-ID: Strato wrote: > Hi folks, > > I want to write some kind of test to check at startup if another > instance of my script is already running. > > I don't want to handle writing of a PID file because it is too > Unix/Linux specific way to do this, and I need to keep the code to be > cross-platform. > > I think the better way to achieve this is to use some process control, > but I'm a neebie and I don't see how to do this in a safe and clean way. > > Any idea ? > > Best regards, > Strato Here is a recipe for Linux version of singleinstance class: http://code.activestate.com/recipes/546512/ and I wrote and contributed the equivalent Windows version: http://code.activestate.com/recipes/474070/ Hope this helps. -Larry From ldo at geek-central.gen.new_zealand Mon Sep 29 05:05:44 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:05:44 +1300 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> Message-ID: In message <02918eb6-c2fb-4908-923f-d878a1956ee2 at x35g2000hsb.googlegroups.com>, sturlamolden wrote: > ... and possibility of interfacing with gnuplot ... Gnuplot is non-Free software. From code at pizzashack.org Wed Sep 3 20:34:35 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 3 Sep 2008 20:34:35 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6vmdncUnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> References: <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <6i6pq9Fmcad7U2@mid.uni-berlin.de> <6vmdncUnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> Message-ID: <20080904003435.GA29228@dragontoe.org> On Wed, Sep 03, 2008 at 03:16:00PM -0700, Dennis Lee Bieber wrote: > On Wed, 3 Sep 2008 03:09:18 -0400, Derek Martin > declaimed the following in comp.lang.python: > > > > > struct run { > > int speed; > > direction_type direction; > > }; > > > > Not a function. Describes an action. Sure, you'll probably never see > > this example in a real program. But that doesn't mean you can't do > > it, and it doesn't make it inherently wrong. Someone somewhere might > > very well find a legitimate use case. > > > > Does neither for me... It defines a (physics) VELOCITY (a direction > and a speed, but lacking in starting position and in duration). OK... so, let me ask you then: I have a computer program that graphs the state of a particular act of running over time t. The only information the program cares about is the speed and direction of that particular instance of running. What would your data structure look like? > An action, "run", would, in my mind require taking this vector and > multiplying it by some duration, and adding the result to some starting > position. I can not be held responsible for your mind... ;-) You're talking about a computational action... which I already said is NOT what I'm talking about. At any given point in time, if someone is running, they have a direction and a speed. The structure I described is sufficient to describe that state. In this extremely silly example, the starting point, end point, and any intermediary positions are not interesting to the problem, which has intentionally been left undefined, because it is an EXAMPLE. Examples are not required to be especially useful or meaningful, and I would guess that the vast majority of examples in, say, introduction to comp sci texts are not (think "hello world"). They need only illustrate something. This particular point was that an object in a computer program can describe some physical action -- in whole or only in part -- without actually needing to have any executable code associated with that state (i.e. it can be a data only, rather than an object with executable methods). The "thing" being described being an action may lend itself to using the name of that action, i.e. a verb, as the name of the object. Though, actually, the example I described above is (minimally) useful. Assuming you had an array of such structs, with say, the index representing the time t in seconds, then it provides you with a graph of the path taken during the act of running. You could superimpose this graph on a map and, given a particular starting point, determine where the person running ended up. You might be inclined to say that the object should be a runner, and you're free to think of it that way if you like... but the fact is the object DOES NOT describe a runner. It describes an instance of running at a moment in time. You might also be inclined to say that the name "run" is a bad choice, because it should be something retarded like state_of_run_at_time_t; but unless you're unbelievably obtuse, then looking at the code, it gets the point across. It may not be the most ideal name, but given the number of times I've seen "foo" used as an identifier in real programs... well, is it really so bad? -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From carriere.jonathan at gmail.com Thu Sep 11 09:56:29 2008 From: carriere.jonathan at gmail.com (carriere.jonathan at gmail.com) Date: Thu, 11 Sep 2008 06:56:29 -0700 (PDT) Subject: Python platform. Message-ID: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> Hello all; I wonder if there is a platform written in python. The equivalent of the Netbeans platform http://platform.netbeans.org/ in the Python world. Do you know such a thing? Thanks a lot. Jonathan. From rridge at csclub.uwaterloo.ca Wed Sep 24 17:11:28 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 24 Sep 2008 17:11:28 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <48da956c$0$1269$426a74cc@news.free.fr> Message-ID: Grant Edwards wrote: > Same here. It's like an automotive engine controls designer > asking if a failed O2 sensor should turn on the check engine > light or blow up the car. Ross Ridge wrote: > No, it's more like asking if the failed sensor should turn on > a strange and mysterious light on the dashboard Grant Edwards wrote: > You're right. I had forgotten that sys.exit() is actually > raising the system exit exception, and that the application > calling the library could handle that exception. Ross Ridge a ?crit : > Well, my point was that exceptions in Python are a bit like a car's > check engine light. Few drivers know what this mysterious light means, > and aren't prepared to do anything about it when it goes on. Bruno Desthuilliers wrote: >You're kidding, aren't you ? Of course not. Plenty of people were quick to say that the exception should be passed through to the caller. No one said this behaviour should be documented. There may be little practical difference bewteen calling sys.exit() after printing an error and progating an exception if no one using the library knows that it could generate that exception in those circumstances. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From castironpi at gmail.com Sun Sep 28 00:43:15 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 21:43:15 -0700 (PDT) Subject: closures and dynamic binding Message-ID: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Hello all, To me, this is a somewhat unintuitive behavior. I want to discuss the parts of it I don't understand. >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= lambda: n ... >>> f[0]() 9 >>> f[1]() 9 I guess I can accept this part so far, though it took a little getting used to. I'm writing some code and found the following workaround, but I don't think it should give different results. Maybe I'm not understanding some of the details of closures. >>> f= [ None ]* 10 >>> for n in range( 10 ): ... f[ n ]= (lambda n: ( lambda: n ) )( n ) ... >>> f[0]() 0 >>> f[1]() 1 Which is of course the desired effect. Why doesn't the second one just look up what 'n' is when I call f[0], and return 9? From raj.indian.08 at gmail.com Tue Sep 16 23:31:54 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Tue, 16 Sep 2008 20:31:54 -0700 (PDT) Subject: Modifying the system menu Message-ID: Hi all, I am trying to modify the system menu of all the applications in my machine. For example say - I am creating multiple desktops for windows - and I want to give every application the capability to be moved across different desktops. So I wanted to modify the basic system menu list to include the new options. The methods I could think of are - 1. Modify the basic windows set of system menu values (best option) or 2. Poll every few milliseconds and modify the system menu values of the active window For (1) I couldnt think of a way to do it. Is it even possible using python? For (2) I wrote the following code for basic testing: hwnd = win32gui.GetForegroundWindow() hw = win32gui.GetSystemMenu(hwnd, False) if hw != None: win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); and it shows the following error: pywintypes.error: (1401, 'AppendMenu', 'Invalid menu handle.') If anyone could help me out in both the options (1) and/or (2), I would be very thankful. Thank you very much in advance, A python newbie From google at mrabarnett.plus.com Wed Sep 10 18:01:28 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 10 Sep 2008 15:01:28 -0700 (PDT) Subject: emulating read and readline methods References: Message-ID: On Sep 10, 6:59?pm, Sean Davis wrote: > I have a large file that I would like to transform and then feed to a > function (psycopg2 copy_from) that expects a file-like object (needs > read and readline methods). > > I have a class like so: > > class GeneInfo(): > ? ? def __init__(self): > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > gene_info.gz',"/tmp/gene_info.gz") > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > ? ? ? ? self.fh.readline() #deal with header line > > ? ? def _read(self,n=1): > ? ? ? ? for line in self.fh: > ? ? ? ? ? ? if line=='': > ? ? ? ? ? ? ? ? break > ? ? ? ? ? ? line=line.strip() > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > ? ? ? ? ? ? rowvals = line.split("\t") > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > ? ? def readline(self,n=1): > ? ? ? ? return self._read().next() > > ? ? def read(self,n=1): > ? ? ? ? return self._read().next() > Each time readline() and read() call self._read() they are creating a new generator. They then get one value from the newly-created generator and then discard that generator. What you should do is create the generator in __init__ and then use it in readline() and read(). > ? ? def close(self): > ? ? ? ? self.fh.close() > > and I use it like so: > > a=GeneInfo() > cur.copy_from(a,"gene_info") > a.close() > > It works well except that the end of file is not caught by copy_from. > I get errors like: > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > during .read() call > CONTEXT: ?COPY gene_info, line 1000: "" > > for a 1000 line test file. ?Any ideas what is going on? > I wonder whether it's expecting readline() and read() to return an empty string at the end of the file instead of raising StopIteration. From maric at aristote.info Tue Sep 16 10:10:49 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 16:10:49 +0200 Subject: append on lists In-Reply-To: References: Message-ID: <200809161610.50245.maric@aristote.info> Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit?: > On 2008-09-16, Maric Michaud wrote: > > all expressions that return something, return a new object, > > That's not _quite_ true: > >>> a=1 > >>> b=a.__add__(0) > >>> a is b > > True > > ;) This is implementation specific, the specification of the language says that it should be false, and it is for higher numbers : >>>[15]: a=1000 >>>[16]: b=a.__add__(0) >>>[17]: a is b ...[17]: False Don't disturb our OP, with side questions, please, it was enough hard like this ;) -- _____________ Maric Michaud From kf9150 at gmail.com Thu Sep 11 12:55:26 2008 From: kf9150 at gmail.com (Kelie) Date: Thu, 11 Sep 2008 09:55:26 -0700 (PDT) Subject: Use Python to solve equations? References: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Message-ID: <16c52a7f-691c-4cba-b770-8ce117389afc@t1g2000pra.googlegroups.com> On Sep 11, 1:11?am, Uwe Schmitt wrote: > > Kelie > > look atwww.sagemath.com. it is great. > > greetings, uwe Thanks Uwe! From maric at aristote.info Thu Sep 4 18:59:16 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 00:59:16 +0200 Subject: Case-insensitive string compare? In-Reply-To: <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> Message-ID: <200809050059.17038.maric@aristote.info> Le Friday 05 September 2008 00:47:00 Chris Rebert, vous avez ?crit?: > On Thu, Sep 4, 2008 at 3:37 PM, Robert Dailey wrote: > > On Thu, Sep 4, 2008 at 5:21 PM, Fredrik Lundh > > > > wrote: > >> Robert Dailey wrote: > >>> I currently have a dictionary object that I'm doing the following with: > >>> > >>> if lib not in stage_map: > >>> # ... do stuff ... > >>> > >>> However, this will perform a case-sensitive comparison between lib and > >>> each key in stage_map. Is there a way to make this do a > >>> case-insensitive comparison instead? > >> > >> dictionary lookups use the exact value. to make a case-insensitive > >> lookup, use key.lower() instead of key when creating the dictionary, and > >> then do > >> > >> if lib.lower() not in state_map: > >> ... > > > > So you're saying to ensure that stage_map's keys are initially lower-case > > to begin with? Well, I can't do this either since the case of the keys is > > actually valuable later on. It's only for the purposes of this specific > > comparison operation that the case should be ignored. > > Then store the string in its original case in the value part of the > key-value pair: > > stage_map[key.lower()] = (key,whatever) > "premature optimization is the root of all evil" I don't recall the OP wanted a (a bit) faster solution to his problem in counterpart of memory loss and syntax complication. If the OP's proposal seems already messy, how about ths one : if lib.lower() not in ( e[0] for e in stage_map.items() ) : ... > - Chris > > > -- > > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From aioe.org at technicalbloke.com Wed Sep 17 14:07:56 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 14:07:56 -0400 Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> Message-ID: Grant Edwards wrote: > On 2008-09-17, r0g wrote: > >> r0g at steppa:~/Desktop/py$ ls >> kickstart.py kickstart.py~ kicktest.py kicktest.py~ >> r0g at steppa:~/Desktop/py$ kickstart.py >> bash: kickstart.py: command not found >> >> Any ideas why this might be? > > Yes. > >> A path thing? > > Yes. > > Linux systems generally don't have the current directory in the > PATH that's searched for executbles (it's regarded as a rather > serious security problem if you do). > > Try doing this: > > ./kickstart.py > Brilliant! :D Thanks v.much for that, turns out the very same thing had been driving me nuts a few days earlier when I was trying to run an installer I had downloaded, bit of an Izzard Printer moment LOL - http://www.youtube.com/watch?v=2wHEqDepAXo Thanks again! Roger. http://www.technicalbloke.com http://movingtoubuntu.technicalbloke.co.uk From gagsl-py2 at yahoo.com.ar Tue Sep 2 15:18:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 16:18:58 -0300 Subject: about downloading the selected information References: Message-ID: En Tue, 02 Sep 2008 09:47:46 -0300, woaibeiyang escribi?: > I have a problem to download the information from url > http://www.ncbi.nlm.nih.gov/sites/entrez. Because it is impossible for me to > add searching material to the url to construct a new url and then visit the > website. > I have the searching material, however I could not find the way to deal with > this problem. I want to know how can I do this problem with python and which > part of knowledge should I view first? Thanks! Use an HTTP tracer (or logger, or sniffer...) to see the request that the browser sends to the server. Then analyze the page source to figure out how the different options modify the request sent. -- Gabriel Genellina From bearophileHUGS at lycos.com Fri Sep 12 16:23:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Sep 2008 13:23:16 -0700 (PDT) Subject: manipulating files within 'for' References: <48CAA2AA.40809@umbc.edu> <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> Message-ID: Matt Nordhoff: > It's useful when wrapping a line. For lack of better lorem ipsum: > > whatever = some_function("Your mistake is caused by Python not " > "following one of its general rules:\n\n" > "Explicit is better than implicit.") > > You can also use backslashes, and probably even + if you want to, but > the implicit concatenation is prettier (IMO, at least ;-). Adding a + at the end of lines isn't much extra work: whatever = some_function("Your mistake is caused by Python not " + "following one of its general rules:\n\n" + "Explicit is better than implicit.") Or even: whatever = "Your mistake is caused by Python not " + \ "following one of its general rules:\n\n" + \ "Explicit is better than implicit." > But you do have a point. I have never thought about the problems it > could cause. Probably such problems aren't much common, because common bugs are already prevented by Python designers :-) But I think once I have written a bug like this: parts = ["foo", "bar" "baz", "spam"] Where I meant a list of 4 strings. > BTW, I could easily be wrong, but I think C behaves the same way as Python. I know, but here changing the behavior respect to C doesn't cause bugs to C programmers, because in that situation their Python program just doesn't run. So it's not a Python syntax that looks like a C syntax that behaves in a different way (this rule is used by the D designer too: when something behaves differently from C (often to avoid a common C pitfall), it has a different syntax. Where the D syntax is the same of C syntax, then the D behavior is generally the same. This avoids several problems to programmers coming from C/C++). Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Sun Sep 28 03:56:49 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 07:56:49 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <00ef327d$0$20666$c3e8da3@news.astraweb.com> On Sun, 28 Sep 2008 19:03:42 +1300, Lawrence D'Oliveiro wrote: > In message > <9890864a-09f9-40d6-b2cc-5028e7a0c8c3 at q26g2000prq.googlegroups.com>, est > wrote: > >> The problem is, why the f**k set ASCII encoding to range(128) ???????? > > Because that's how ASCII is defined. > >> while str() is internally byte array it should be handled in range(256) >> !!!!!!!!!! > > But that's for random bytes. How would you convert an arbitrary object > to random bytes? from random import randint ''.join(chr(randint(0, 255)) for i in xrange(len(input))) of course. How else should you get random bytes? :) -- Steven From prahaai at gmail.com Mon Sep 22 03:13:50 2008 From: prahaai at gmail.com (Cro) Date: Mon, 22 Sep 2008 00:13:50 -0700 (PDT) Subject: External code and functions integration Message-ID: Good day. I am using python for quite some time now and i decided to advance a little. I want to write a little extension, or add some C modules for my python. I use Active version. What i want to do is write some wrappers for a game library, called HGE. See "hge.relishgames.com". I wrote some applications with HGE, in C++ and i like it pretty much. In order to make a HGE application in C++, i need to include "hge.h", include "hge.lib" and "hgelehper.lib", and have "hge.dll" in the same directory. So it's 3 things i must have for the program to work. This game library is open source, so i have the source for the libs and the dll. Now, what i was thinking was to make some wrapping code like "hge.h" to call all the functions in the "libs", that (i guess) call the functions from "hge.dll", that (blah blah) calls DirectX and so on. I guess that if i write all that "hge.h" includes and wariables in python, will be okay... even if i still don't have the skill. I tried to call "hge.lib" like this: " from ctypes import * cdll.LoadLibrary("D:/HGE18/lib/bc/hge.lib") " But i get "WindowsError: [Error 193] %1 is not a valid Win32 application". I tried with windll.LoadLibrary ... and i get the same error. I tried with the other lib versions, there are 3 versions: BorlandC, GCC, VisualC, callind "cdll" or "windll". All lib versions report the same error. Recently i discovered PyInline and SciPy Weave. They say that Weave can run C code on the fly, inline... I really dobt that it can parse things like: " #ifndef HGE_H #define HGE_H " or: " #include #define HGE_VERSION 0x180 #ifdef HGEDLL #define EXPORT __declspec(dllexport) #else #define EXPORT #endif #define CALL __stdcall " Has anyone ever encountered a problem like this ? Any, ANY advice or idea would be useful ! Thank you very much. From bignose+hates-spam at benfinney.id.au Mon Sep 22 05:19:57 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 22 Sep 2008 19:19:57 +1000 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <87d4iw1qrm.fsf@benfinney.id.au> Steven D'Aprano writes: > I don't want the objects to share state. I'm not exactly sure what I > said that has given so many people the impression that I do. This: Steven D'Aprano writes: > Essentially, the class is used as a function that keeps state from > one call to the next. Perhaps if you say what you want that isn't provided by any of a function, a module, or a class. Specifically, what state you want to track, and why it's so important that the state not be available to the instances. -- \ ?I love and treasure individuals as I meet them, I loathe and | `\ despise the groups they identify with and belong to.? ?George | _o__) Carlin, 2007 | Ben Finney From sturlamolden at yahoo.no Wed Sep 24 14:15:58 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 11:15:58 -0700 (PDT) Subject: Linq to Python References: Message-ID: On Sep 24, 5:22?pm, hrishy wrote: > Well wouldn't it be a lot easier to query and join a xml source with a relational source with LINQ capabilites in Python. > > Hmm what am i missing here is there a site that takes all LINQ examples and does them using list comprehensions and makes them sound easy ? > > wasn't python supposed to make everything easy ? Most Python programmers use other languages as well. I have working knowledge of C, Matlab, C++, Java, Fortran 95, and C#. Those that responded to your post know what LINQ are and what LINQ does. Put simply, Python has dynamic typing, list comprehensions, and is scriptable (i.e. Python source is structured text). That's why Python don't need LINQ and XML the same way as C#. LINQ and XML is needed because C# is a statically typed compiled language. That is: LINQ: Python has list comprehensions and dynamic typing (C# do not) XML: Python is structured text (compiled .NET assemblies are not) Second, minimalistic syntax is a virtue. That is why C is still around. Python don't add new syntax sugar every time Redmond invents a new buzzword. Functions like XML processing are delegated to libraries -- where they belong. Nobody was saying LINQ is a bad idea for a language like C#. From psaffrey at googlemail.com Wed Sep 10 12:38:57 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Wed, 10 Sep 2008 09:38:57 -0700 (PDT) Subject: Generator functions and user interfaces Message-ID: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> I'm trying to implement an interactive graph visualisation tool using matplotlib. I want to use a spring layout, where nodes repulse each other and edges act as springs to pull connected nodes together. Usually, this algorithm runs through a number of iterations of attraction/repulsion to allow the nodes to converge to suitable positions. However, rather than running all these iterations to lay out the graph and then rendering it, I want to animate the graph as it is "springing" into place, and then allow the user to drag nodes around and have the graph redraw on the fly. My idea for doing this was to use a generator function, where I yield the position of the nodes after each iteration and then call draw() on the position yielded. Does this seem like a sensible approach? The problem is that the node positions that are being operated on by the generator function may be altered by user input - dragging the nodes - and I'm not sure if this will break the way that the new positions are yielded. How do I use a generator function that might stop (when the nodes stop moving) but then need to restart again (once the user moves the nodes)? I'm quite an experienced Python programmer but I've never taken the trouble to get my head around generator functions, so any guidance welcome! Peter From steve at REMOVE-THIS-cybersource.com.au Mon Sep 1 08:18:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2008 12:18:16 GMT Subject: Know if a object member is a method References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Message-ID: <00cbd80b$0$20302$c3e8da3@news.astraweb.com> On Mon, 01 Sep 2008 11:45:36 +0200, Luca asked about recognizing methods: > What is the best way to do this? The "most pythonic"? That depends on why you are doing it, and what you want to do with the information once you've found it. If you are experimenting in the interactive interpreter, the easiest way is simply call the method and see what happens: obj.methodName() # call the method If it succeeds, then it is some sort of callable, a method or a function or something more unusual. If you fear side-effects, then use: callable(obj.methodName) Alternatively, you can read the docs: help(obj) help(obj.methodName) If your aim is to write something like a debugger, profiler, or some other application that needs to inspect arbitrary objects and work out what they do, then you probably should be using: isinstance(obj.methodName, new.instancemethod) But remember that not all callable attributes are instancemethods! There is no one right way of doing this. Hope this helps. -- Steven From gandalf at shopzeus.com Mon Sep 8 09:18:45 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Sep 2008 15:18:45 +0200 Subject: universal unicode font for reportlab In-Reply-To: <48C51E49.2070202@shopzeus.com> References: <87r67vj7f1.fsf@benfinney.id.au> <48C51E49.2070202@shopzeus.com> Message-ID: <48C52635.1030709@shopzeus.com> >> >> The GNU Unifont >> covers an impressive range of >> the Unicode Basic Multilingual Plane. >> >> Unifont is originally a bitmap font, but was recently made available >> in TrueType format >> . >> >> Both are available in Debian 'lenny'; the 'unifont' and 'ttf-unifont' >> packages, respectively. > I found out that dejavu is what I need. It covers the languages I need > and more: > > http://dejavu.svn.sourceforge.net/viewvc/dejavu/tags/version_2_26/dejavu-fonts/langcover.txt Sorry, this did not work either. Dejavu does support cyrillic and greek characters but I have to load a different ttf for that. They are no unified. :-( The only one that worked so far was "unifont.tff" but it is very ugly above point size=10. Can you tell me what kind of font Geany is using on my Ubuntu system? The preferences tells that it is "monospace" but when I load VeraMono.ttf in reportlab, it will not even display latin2 characters. In contrast, please look at this example that show my test program in Geany: http://www.shopzeus.com/geany.jpg It is a real scalable truetype font, displaying latin 1, latin2, chinese, russian and japanese characters. Is it the same font? Does this mean that reportlab is buggy? If I could load the same font that geany uses, it would probably solve my problem forever. Thanks, Laszlo -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 1050 bytes Desc: not available URL: From nospam at invalid.invalid Mon Sep 29 04:05:10 2008 From: nospam at invalid.invalid (robert) Date: Mon, 29 Sep 2008 10:05:10 +0200 Subject: Detecting dir (tree) changes fast? Message-ID: I want to detect changes in a directory tree fast with minimum overhead/load. In order to check the need for sync tasks at high frequency. It must not be 100% reliable (its also forced time periodic), so kind of hashing would be ok. How? Robert From sayananbig at gmail.com Thu Sep 18 18:11:39 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Thu, 18 Sep 2008 15:11:39 -0700 (PDT) Subject: Directshow in Python Message-ID: <9d55654a-49ed-4bce-beae-bdf915810ad1@o40g2000prn.googlegroups.com> Hey all, I'm trying to use DirectShow to display videos [I'm kind of new to Python, from more of a C++ background on windows]. I found some sample code online, but I am having trouble with calling the I import ctypes from ctypes import * from comtypes import client from ctypes.wintypes import * import sys import time filename = sys.argv[1] qedit = client.GetModule('qedit.dll') # DexterLib quartz= client.GetModule("quartz.dll") CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}' filter_graph = client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph) filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder) filter_builder.RenderFile(filename, None) media_control = filter_graph.QueryInterface(quartz.IMediaControl) media_control.Run() try: # Look at IMediaEvent interface for EOS notification while True: time.sleep(1) except KeyboardInterrupt: pass # Need these because finalisers don't have enough context to clean up after # themselves when script exits. del media_control del filter_builder del filter_graph This code works fine. What I would like to know, is how do I declare filename in the Python program to be of type LPCWSTR, so that I don't need to parse the command line in order to call the function "RenderFile()"? -Sayanan From gagsl-py2 at yahoo.com.ar Tue Sep 16 06:02:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 07:02:02 -0300 Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows References: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Message-ID: En Tue, 16 Sep 2008 06:25:27 -0300, escribi?: > I wonder if anyone can advise me or has done similar to the following? > > Basically I've downloaded the Python 2.5.2 source code that builds > with Visual Studio 6.0. I've built Python for windows. This was easy > (it even came with the pcbuild.dsw workspace file). Great! > > Now comes the troubled bit...I now look for similar source code for > Python extensions Numpy and Scipy but the source code and directories > are not all obvious. Looks like these are normally built via other > compilers. However I need to do all my builds in VS 6.0. > > For Numpy (I haven't got as far as Scipy yet) I've organised the > source code into the following projects and lumped them all into my > new workspace numpy.dsw: Don't try to roll your own projects, compile it using distutils instead. Distutils takes care of defining the right symbols and compiler options, and should detect VS. I'm pretty sure the Numpy README file (or similar) describes how to build it; usually you install the required dependencies and then run: python setup.py build -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sun Sep 7 18:18:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 19:18:49 -0300 Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: En Sun, 07 Sep 2008 18:51:32 -0300, andyhume at gmail.com escribi?: > I have a dict of key/values and I want to change the keys in it, based > on another mapping dictionary. An example follows: > > MAPPING_DICT = { > 'a': 'A', > 'b': 'B', > } > > my_dict = { > 'a': '1', > 'b': '2' > } > > I want the finished my_dict to look like: > > my_dict = { > 'A': '1', > 'B': '2' > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? Exactly. You can do that in one pass: my_new_dict = dict((MAPPING_DICT[k],v) for (k,v) in my_dict.iteritems()) That's enough if MAPPING_DICT always contains all the keys. If you want to keep old keys that aren't in MAPPING_DICT unchanged, use MAPPING_DICT.get(k,k) instead. Other corner cases include many-to-one mappings, and incomplete mappings where a replacement key is also an unmapped old key. -- Gabriel Genellina From jan.schilleman at xs4all.nl Sun Sep 14 19:06:08 2008 From: jan.schilleman at xs4all.nl (Jan Schilleman) Date: Mon, 15 Sep 2008 01:06:08 +0200 Subject: Rebinding __setattr__ Message-ID: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> Hi all, I am trying to redefine __setattr__. The base class is in a library (actually, it is win32com.client.DispatchBaseClass) and I do not want to touch it. My problem is exemplified below. To my surprise, __setattr__ and __str__ behave differently; I can redefine __str__ and the inherited __str__ is still the redefined one. But redefining __setattr__ on the base class does not get inherited. In Base.__dict__ the __setattr__ is the one I expected, but it is not called from B. What is the problem? Is __setattr__ cached somewhere [and not updated?]? class Base: def __setattr__(self, attr, value): print 'Base __setattr__' self.__dict__[attr] = value def __str__(self): return "Base" class A(Base): pass class B(Base): pass def __setattr__(self, attr, value): print 'alternative __setattr__' self.__dict__[attr] = value def __str__(self): return "Alternative" a = A() b = B() for i in (1, 2): print print 'run', i print print Base.__dict__ print A.__dict__ print B.__dict__ print print 'a:', a a.a1 = 1 print 'b:', b b.b1 = 1 setattr(Base, '__setattr__', __setattr__) setattr(A, '__setattr__', __setattr__) setattr(Base, '__str__', __str__) setattr(A, '__str__', __str__) From bdesth.quelquechose at free.quelquepart.fr Tue Sep 9 13:13:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 19:13:35 +0200 Subject: check if the values are prensent in a list of values In-Reply-To: References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> Message-ID: <48c6caae$0$22688$426a74cc@news.free.fr> Matt Nordhoff a ?crit : (snip) > I'm not judging whether this is a good solution or not, but that's a > silly use of a dict. Yeps, but a somewhat common one in code predating the apparition of sets as builtin type. From J.Fine at open.ac.uk Wed Sep 17 10:03:59 2008 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 17 Sep 2008 15:03:59 +0100 Subject: Generating test data from an XML Schema In-Reply-To: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> References: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> Message-ID: Mark Thomas wrote: >> Has anyone seen anything that might help generate test data from a schema? > > I'm unaware of anything in Python, but Eclipse can generate sample > documents from a schema: > http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html > > As can XML IDEs such as Stylus Studio and XML Spy. Mark - thank you for this. The problem is that I'd like to sit quite close to the schema and manipulate the generation of the test data. (This is because a straight representation won't suit my needs.) However, if I get the chance I'll look at these tools, in case they can help me. Thank you for the suggestion. -- Jonathan From linkmaster032000 at gmail.com Sun Sep 21 13:11:24 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Sun, 21 Sep 2008 10:11:24 -0700 (PDT) Subject: curses.setsyx()? References: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> Message-ID: <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: > On Sep 19, 1:24?am, Tim Roberts wrote: > > > linkmaster032... at gmail.com wrote: > > > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > > >cursor. Any alternatives/solutions? > > > Did you call doupdate after? ?setsyx just manipulates the data structures. > > It takes a call to doupdate to force those changes to take effect visually. > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > I added it and it still doesn't work. This is what I'm doing when I > want to display the cursor and prepare it for input at 2,3: > > curses.echo() > curses.curs_set(1) > curses.setsyx(2,3) > curses.doupdate() Any idea what's wrong? From mart_in_medina at yah00.es Sun Sep 21 18:08:03 2008 From: mart_in_medina at yah00.es (Martin Griffith) Date: Mon, 22 Sep 2008 00:08:03 +0200 Subject: Milenko Kindl rtegdgd References: <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> Message-ID: <59hdd4t65g9gb5kq535b2pkfj939hiruqv@4ax.com> On Sun, 21 Sep 2008 15:00:16 -0700 (PDT), in sci.electronics.design H Vlems wrote: >On 21 sep, 19:48, yuma wrote: >> Milenko Kindl >> Banja Luka >> Banjaluka >> Bihac > >Well, that's not C isn't it, more like Snobol or RPG/2 It's better to say "that's not C, is it" I don't know why, but that's the way it works..... martin From aioe.org at technicalbloke.com Sat Sep 27 02:15:20 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 27 Sep 2008 02:15:20 -0400 Subject: Eggs, VirtualEnv, and Apt - best practices? References: <6k2aqqF5p185U1@mid.uni-berlin.de> <6k2c5pF5oenoU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> that is a very valid point, but it seemed that Scott has homogeneous >> environment: Debian/Ubuntu so my post was relative to the original >> request. >> I agree that when you throw Windows/MacOS into the mix things >> become "interesting". But then it's better when your developers >> develop on >> server/platform they are going to be using, using same stack they >> going to >> face in production etc. It all depends on requirements and current >> practices in company. > > Well, you certainly want a desktop-orientied Linux for users, so you > chose ubuntu - but then on the server you go with a more stable debian > system. Even though the both have the same technical and even package > management-base, they are still incompatible wrt to package versions for > python. > > And other constraints such as Photoshop not being available for Linux > can complicate things further. Photoshop for Windows runs fine under Wine, or at least it does on my Ubuntu box, just make sure you install the windows core fonts. I don't think many people realise how good Wine is these days, maybe because it was so useless for so long, it's pretty good right now. Also there's 'crossover' if you need even better out of the box Win32 binary compatibility. Roger. From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 4 04:33:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 10:33:58 +0200 Subject: use str as variable name In-Reply-To: References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> Message-ID: <48bf9d12$0$7552$426a74cc@news.free.fr> Mathieu Prevot a ?crit : > 2008/9/4 Chris Rebert : (snip) >> You're looking for the setattr() built-in function. In this exact case: >> setattr(a, arg, new_value) >> >> This is probably covered in the Python tutorial, please read it. >> >> Regards, >> Chris > > Indeed. > > I'll use: > a.__setattr__(height, new_value) Please don't. Use the generic setattr() function instead. This holds for any __magic__ method : they are *implementation* for operators and generic functions - which you can think of as operators with a function syntax -, and are not meant to be called directly. You wouldn't write something like 2.__add__(3), would you ? From almar.klein at gmail.com Tue Sep 30 07:07:17 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 30 Sep 2008 13:07:17 +0200 Subject: what does "python -i" use as input stream (stdin)? In-Reply-To: References: Message-ID: Wow, it's that easy... thanks! 2008/9/29 Gabriel Genellina > En Fri, 26 Sep 2008 04:29:42 -0300, Almar Klein > escribi?: > > I would still like to hear if anyone knows how I can change the input >> stream >> that >> is used when running "python -i", but I would not be surprised if it is >> impossible... >> > > Sure you can. You have to replace the file descriptor 0, that is, "standard > input"; sys.stdin reads from there. The standard way is to use os.dup2: > > c:\temp>type foo.txt > This line read from foo.txt > > > c:\temp>type redirect.py > import os > > inp = open("foo.txt","r") > os.dup2(inp.fileno(), 0) > print "raw_input->", raw_input() > > c:\temp>python redirect.py > raw_input-> This line read from foo.txt > > This is not > > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.leslie at gmail.com Tue Sep 30 01:07:14 2008 From: tim.leslie at gmail.com (Tim Leslie) Date: Tue, 30 Sep 2008 15:07:14 +1000 Subject: Newbie question... In-Reply-To: References: Message-ID: On Tue, Sep 30, 2008 at 12:04 PM, Ken D'Ambrosio wrote: > First, apologies for such a newbie question; if there's a better forum (I've > poked around, some) feel free to point it out to me. Anyway, a mere 25-odd > years after first hearing about OOP, I've finally decided to go to it, by > way of Python. But this puzzles me: > > import commands free = commands.getoutput("free") # free is now a string, representing the output from the "free" command for line in free: print line, This isn't doing what you think. Since free is a string, when you iterate over it, you get a single character each time, so your line variable isn't actually a line of the output, but a single character. When you run "print line," this prints the character, followed by a space. The comma at the end of the print statement tells it to put a space after the output rather than a newline. What you probably wanted to do is split up your output on the newline character. for line in free.split("\n"): print line Of course, your string already has all the newlines it needs in it, so if all you want is to see the output of the "free" command you can just do: print free HTH, Tim > > Gives: > t o t a l u s e d f r e e > s h a r e d b u f f e r s c a c h e d > M e m : 5 1 5 9 9 2 4 6 0 4 5 2 5 5 5 > 4 0 > 0 7 7 5 1 6 9 1 8 8 4 > - / + b u f f e r s / c a c h e : 2 9 1 0 5 2 2 2 4 9 > 4 0 > > Why are there spaces between everything? And how do I keep it from > happening? *confused* > > Thanks much, > > -Ken > ** Posted from http://www.teranews.com ** > -- > http://mail.python.org/mailman/listinfo/python-list > From rweir at ertius.org Tue Sep 9 02:17:14 2008 From: rweir at ertius.org (Rob Weir) Date: Tue, 09 Sep 2008 16:17:14 +1000 Subject: Newbie Question:Please help References: Message-ID: <87wshl7sid.fsf@hypercube.ertius.org> On 9 Sep 2008, Karthik Krishnan wrote: > File "", line 1 > python main_test.py > > Syntax Error: invalid syntax I get: File "/tmp/x.py", line 11 if __name__ = "__main__": ^ SyntaxError: invalid syntax > if __name__ = "__main__": ^ = is used for assignment in Python, you want ==. -- -rob From code at pizzashack.org Wed Sep 3 01:23:47 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 3 Sep 2008 01:23:47 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: References: <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> Message-ID: <20080903052347.GU29228@dragontoe.org> On Wed, Sep 03, 2008 at 12:20:18AM -0400, Miles wrote: > Derek Martin wrote: > > On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: > >> but the instances of `Popen` are no actions. There's no way to > >> "execute" a `Popen` instance. > > > > Yes there is... you execute it when you instantiate the object. At > > the time of instantiation, you "open" the "P" (pipes). > > The subprocess module is also supposed to replace os.system and > os.spawn*, neither of which involve opening pipes. Uh... it's a replacement for os.popen(), which -- guess what -- opens pipes. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From gogala.mladen at gmail.com Fri Sep 19 03:13:48 2008 From: gogala.mladen at gmail.com (Mladen Gogala) Date: Fri, 19 Sep 2008 09:13:48 +0200 Subject: Python newbie Message-ID: I am a Python newbie who decided to see what that Python fuss is all about. Quite frankly, I am a bit perplexed. After having had few months of experience with Perl (started in 1994 with Perl v4, and doing it ever since) , here is what perplexes me: perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' The equivalent in Python looks like this: Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) [GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=[1,2,3] >>> map((lambda x: 2*x),a) [2, 4, 6] >>> map((print),a) File "", line 1 map((print),a) ^ SyntaxError: invalid syntax >>> for x in a: print x ... 1 2 3 >>> for x in a: x=2*x ... >>> for x in a: print x ... 1 2 3 >>> There are several questions: 1) Why is the array "a" unchanged after undergoing a transformation with map? 2) Why is it illegal to pass a built-in function "print" to map? 3) Why is the array "a" unchanged after undergoing an explicit transformation with the "for" loop? 4) Is there an equivalent to \$a (Perl "reference") which would allow me to decide when a variable is used by value and when by reference? PHP also allows changing arrays with "foreach" loop: #!/usr/local/bin/php How can I make sure that for x in a: x=2*x actually changes the elements of the array "a"? http://mgogala.freehostia.com From fredrik at pythonware.com Wed Sep 10 08:43:17 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 14:43:17 +0200 Subject: List of modules available for import inside Python? In-Reply-To: <9f3d127f-4434-4a27-b5d4-b43ebb137186@k30g2000hse.googlegroups.com> References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> <9f3d127f-4434-4a27-b5d4-b43ebb137186@k30g2000hse.googlegroups.com> Message-ID: Michele Simionato wrote: > I have just tried the following on my Ubuntu box with the system > Python: > > ~$ python /usr/lib/python2.5/doc/tools/listmodules.py > /usr/lib/python2.5/doc/tools/listmodules.py:99: DeprecationWarning: > the rgbimg module is deprecated > __import__(m) > > ** (process:24863): WARNING **: AT_SPI_REGISTRY was not started at > session startup. > > ** (process:24863): WARNING **: Could not locate registry > location: /usr/lib/xulrunner-1.9.0.1/libxpcom.so > before 3 > /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: cannot > register existing type `GtkSourceStyleScheme' > __import__(m) > /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: > g_type_set_qdata: assertion `node != NULL' failed > __import__(m) > /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: cannot > register existing type `GtkSourceBuffer' > __import__(m) > /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: > g_type_get_qdata: assertion `node != NULL' failed > __import__(m) > Segmentation fault > > Interesting, isn't it? it does indeed import modules found in the path if they appear to be Python C extensions. why Ubuntu puts badly written C modules in their default Python path is more than I can tell... From nick at craig-wood.com Wed Sep 10 20:36:32 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 10 Sep 2008 19:36:32 -0500 Subject: Simple UDP server References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> Message-ID: Tzury Bar Yochay wrote: > I am looking for the right way to write a small and simple UDP server. > > I am wondering between Forking, Threading (found at SocketServer.py) > and the one describes at the snippet below. > > Can you tell me the advantages and disadvantages of each > Would the one below will be capable of holding 30 concurrent > connections? > > I have no intention of using Twisted or alike since I am looking for > making it as lightweight as possible For UDP I wouldn't thread or, fork, I'd use select and run asynchronously. http://docs.python.org/lib/module-select.html Actually if I really had to do this I'd use twisted. Right tool for the job! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gary at byoteki.com Sun Sep 28 16:14:31 2008 From: gary at byoteki.com (Gary M. Josack) Date: Sun, 28 Sep 2008 16:14:31 -0400 Subject: generate random digits with length of 5 In-Reply-To: References: Message-ID: <48DFE5A7.5040000@byoteki.com> Aaron "Castironpi" Brady wrote: > On Sep 28, 2:59 pm, sotirac wrote: > >> Wondering if there is a better way to generate string of numbers with >> a length of 5 which also can have a 0 in the front of the number. >> >>
>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
>> elements
>>  code = 'this is a string' + str(random_number[0]) +
>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
>> + str(random_number[4])
>> 
>> > > '%05i'%random.randint(0,99999) > -- > http://mail.python.org/mailman/listinfo/python-list > This produces numbers other than 5 digit numbers. making the start number 10000 should be fine. From showellshowell at gmail.com Mon Sep 15 10:33:37 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Mon, 15 Sep 2008 07:33:37 -0700 (PDT) Subject: Representation of python code ? References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> Message-ID: <79cbd220-ca14-4b9b-b9f0-4d1136017d5a@v16g2000prc.googlegroups.com> On Sep 15, 7:17?am, Maric Michaud wrote: > Le Monday 15 September 2008 16:06:19 showellshow... at gmail.com, vous avez > ?crit?: > > > I'm not sure this is the best counterexample. ?You can see statically > > that A potentially creates an instance of the B class. > > > > class A : > > > ? ? def __init__(self) : > > > ? ? ? ? ?self._b = B() > > > > class B : pass > > Yes, you can, but are you sure it's obvious that B in A.__init__ is the class > you think of ? > I'm guessing 99% of the time it will be. It seems to me that if you're invoking classes in a truly dynamic way, you should be explicit about it anyway, and give methods some kind of naming convention, like have "factory" in the name. This would not only make it easy for a visualization program not to be tricked, but it would help out your human readers as well. From __peter__ at web.de Mon Sep 22 07:18:24 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 22 Sep 2008 13:18:24 +0200 Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <5a37d7ca-e7b4-4278-8fc3-f5d0f4303cee@79g2000hsk.googlegroups.com> Message-ID: josh logan wrote: > A better example would be sorting by increasing last name and > decreasing first name. This would be easy with the sort function > comparator, but I can't see how to do the same with the key argument. > Is the only solution to decorate the Player objects in another class > that has the appropriate __cmp__ function (or whatever is needed) and > then retrieve the Player objects back? Python's sort algorithm is guaranteed to be stable; therefore you can sort twice: ordered = sorted(players, key=lambda p: p.fname, reverse=True) ordered.sort(key=lambda p: p.lname) Peter From heshan.suri at gmail.com Sun Sep 21 11:45:57 2008 From: heshan.suri at gmail.com (Heshan Suriyaarachchi) Date: Sun, 21 Sep 2008 10:45:57 -0500 Subject: Deploying a Python Service on Apache Axis2 Message-ID: <12e5d0d90809210845x1e304860wf6299f9b3c260e35@mail.gmail.com> Hi guys, Apache Axis2/Java, is a popular open source Web service engine. It currently supports exposing services written in Java, Javascript as Web services. This article [1] discusses the Python data Binding that enable exposing Web services written in Python. [1] - http://wso2.org/library/articles/deploying-python-service-axis2 [2] - http://heshans.blogspot.com/2008/09/wso2-wsfjython-10-alpha.html [3] - http://wso2.org/library/invoking-enterprise-web-services-using-jython -- Regards, Heshan Suriyaarachchi http://heshans.blogspot.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Mon Sep 15 16:22:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 15 Sep 2008 13:22:06 -0700 (PDT) Subject: append on lists References: Message-ID: <0d66bfca-bd3b-4fc3-b3c6-a244677a7a5e@d45g2000hsc.googlegroups.com> On Sep 15, 9:24?pm, Armin wrote: > Hi, > > just a dumb question. > > Let a = [1,2,3,4,5] > > Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? > > --Armin Because list.append is a method that mutates its object, and such method usually return None. What you should check is the value of 'a' after 'a.append(7)'. -- Arnaud From kaerbuhez at gmail.com Wed Sep 10 05:55:14 2008 From: kaerbuhez at gmail.com (kaer) Date: Wed, 10 Sep 2008 02:55:14 -0700 (PDT) Subject: I want to use a C++ library from Python References: <6ipd53FrptpiU1@mid.uni-berlin.de> Message-ID: <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> On 10 sep, 10:00, "Diez B. Roggisch" wrote: > Anders Eriksson schrieb: > > > Hello, > > > I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1 > > .lib and 1 .dll files. I don't have the source code. > > > How can I create a Python module from these files? > > Did you bother googling? > > http://www.google.de/search?q=python+c%2B%2B&ie=utf-8&oe=utf-8 > > Diez You may want google "python dll" as well. Good luck. From stefan_ml at behnel.de Tue Sep 16 15:10:54 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 16 Sep 2008 21:10:54 +0200 Subject: Zsi interoperability In-Reply-To: References: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <48d004be$0$6672$9b4e6d93@newsspool2.arcor-online.net> Marco Bizzarri wrote: > On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel wrote: >> Mailing List SVR wrote: >>> I have to implement a soap web services from wsdl, the server is >>> developed using oracle, is zsi or some other python library for soap >>> interoperable with oracle soa? >> No idea, but I'd definitely try soaplib before ZSI. >> >> Stefan > > I'm working on a project where I need to write a client for SOAP with > Attachments; I can see ZSI does not support it; is soaplib any better? Never tried, but it's supposed to support it. In any case, soaplib is easy enough to use to just give it a try and see if it works for you. Stefan From rocky at panix.com Fri Sep 5 14:49:11 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 05 Sep 2008 14:49:11 -0400 Subject: pdb bug and questions References: <9d1d75a2-a6be-4d56-a53c-46b7942abf08@m73g2000hsh.googlegroups.com> Message-ID: castironpi writes: > On Sep 4, 4:22?pm, Stef Mientki wrote: >> hello, >> >> I'm trying to embed a debugger into an editor. >> I'm only interested in high level debugging. >> The first question is what debugger is the best for my purpose ? >> (pdb, pydb, rpdb2, smart debugger, extended debugger ? >> >> Second question, in none of the above debuggers (except rpdb2), >> I can find a ?"break now", >> so it seems impossible to me to detect unlimited while loops ? >> >> For the moment I started with pdb, because most of the debuggers seems >> to be an extension on pdb. >> When I launch the debugger ( winXP, Python 2.5) from with my editor >> ? python -u -m pdb ?D:\\Data\\test_IDE.py >> I get this error >> ? IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') >> NOTICE 1 backslash ----------------------------------^ >> >> If I launch the debugger with >> ? python -u -m pdb ?D:/Data/test_IDE.py >> It runs fine. >> >> This looks like a bug to me. >> What's the best way to report these kind of bugs ? >> >> Although I mostly use os.path.join to be OS independent, >> these kind of bugs give me the impression, >> that I can better do the join myself and always use forward slashes. >> Is this a valid conclusion ? >> >> thanks, >> Stef Mientki > > Stef, > > I discovered the same problem too with my editor. I solved it by > using only the file name, and setting the initial directory on the > executable. I don't know if this helps, but in pydb there is an option to set the initial directory the debugger works in. Inside the debugger there is the gdb command "cd". From d3vvnull at gmail.com Sat Sep 27 14:11:09 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sat, 27 Sep 2008 13:11:09 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DE3FC7.4030307@wildenhain.de> References: <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> Message-ID: <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> If the inputs are edited prior to the construction of the string and these fields are used for more than one update then it's not an exploit. It's simply a matter not repeating yourself when coding. In this particular case too, we're talking about a list of integers that gets inserted into a string. If the list is validated prior to its insertion into an SQL statement then there is no exploit. If I write a batch program (not a web program) that retrieves this list of integers from other sources and validates the data prior to using it in an SQL statement, that should be sufficient. As far as wrong and right is concerned. I think it's more about doing what is appropriate according to the circumstances. As a rule you should only code what is appropriate for the circumstances. If it's appropriate to code more simply without introducing unnecessary complexity you should do so. I work in the data warehousing ETL world, where we have to perform field edits or transformations to load source data into databases. If I'm already performing edits on these fields and if these fields are going to be used for more updates downstream, it's wasteful to perform them again when I build the SQL insert with the list and execute it. Finally, whatever happened to the practice of granting appropriate privileges to IDs that perform database operations? Shouldn't the person acting in the capacity of DBA ensure that the user updating or retrieving data from the database does not have DROP, ALTER, or CREATE privileges on that database? On Sat, Sep 27, 2008 at 9:14 AM, Tino Wildenhain wrote: > Hi, > > Michael Mabin wrote: > >> so you wouldn't object then to something like >> '.... in (%)' % ','.join([str_edit_for_exploit(x) for x in >> aList]) >> if str_edit_for_exploit applied security edits? >> > > Whats an security edit btw? If it is something meant to turn possibly > insecure data into 'secure' then, no I would still object. > Why? Because its a bad example of "default permit". Its always better > to have a whitelist - even more so when its so easy to do. > > Its just a habit you develope - if you never do it right, how would you > know when and how to do it right when you need to? > > Tino > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 9 16:16:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 17:16:07 -0300 Subject: biopython References: Message-ID: En Tue, 09 Sep 2008 05:53:19 -0300, Beema Shafreen escribi?: > Hi all, > I am using Biopython to fetch pumed Id's ,The module i use is (from Bio > import Entrez) > > But i am getting this error > >>>> from Bio import Entrez > Traceback (most recent call last): > File "", line 1, in ? > ImportError: cannot import name Entrez > > > what should i do know can anybody suggest me an alternative for this Ensure that you don't have *another* Bio module that is being imported instead of the true one. -- Gabriel Genellina From jjl at pobox.com Wed Sep 3 17:53:06 2008 From: jjl at pobox.com (John J Lee) Date: Wed, 3 Sep 2008 22:53:06 +0100 (BST) Subject: [wwwsearch-general] python - mechanize/browser/POST issue In-Reply-To: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> References: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> Message-ID: On Tue, 2 Sep 2008, bruce wrote: [...] > using mechanize/Browser, i can easily do a url/get, and process submitting a > form that uses a GET as the action. however, I'm not quite sure how to > implement the submittal of a form, that uses the POST action. [...] Same way as any other form. The HTTP method used is determined by the value of the form element's "action" attribute. John From marco.bizzarri at gmail.com Wed Sep 3 05:28:10 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 3 Sep 2008 11:28:10 +0200 Subject: Using httplib to access servlets on tomcat server In-Reply-To: References: Message-ID: <3f0d61c40809030228l6d0e93dclfbe93a868860d7cb@mail.gmail.com> On Wed, Sep 3, 2008 at 11:06 AM, jorma kala wrote: > Hi, > > I'm trying unsuccesfully to use the httplib library to execute servlets on a > local tomcat server. > > If I type the following http adress on my browser > http://localhost:8080/test/Serv1 the servlet works fine. > But if I try to access it with the following python code: > > conn = httplib.HTTPConnection("http://localhost:8080") > conn.request("GET", "/test/Serv1") > r1 = conn.getresponse() > > I get the following error: > > socket.gaierror: (11001, 'getaddrinfo failed') > > Do you know what I do wrong? > Thank you very much. > > localhost is not resolved to 127.0.0.1 on your machine. Try changing it to http://127.0.0.1:8080 Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From deets at nospam.web.de Sun Sep 21 10:38:21 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 21 Sep 2008 16:38:21 +0200 Subject: How to kill threading.Thread instance? In-Reply-To: References: <6jmn5kF42hreU1@mid.uni-berlin.de> Message-ID: <6jn4itF442e7U1@mid.uni-berlin.de> dmitrey schrieb: > I wonder why something like myThread.exit() or myThread.quit() or > threading.kill(myThread) can't be implemented? > Is something like that present in Python 3000? Not that I'm aware of it (which doesn't mean to much though). However I *am* aware of the bazillions discussions that have been held over this here - and the short answer is: it is a generally very bad idea to terminate threads hard, as it can cause all kinds of corruption. Systems like Java discourage the use of the available methods for that as well. And I for example once worked with Qt3-threads, what allow for this kind of operation - and killed my CORBA-ORB running in the same process by terminating the thread hard. Google a bit in this NG to find the discussions & reasons. Diez From kyosohma at gmail.com Fri Sep 26 09:48:52 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 26 Sep 2008 06:48:52 -0700 (PDT) Subject: cups.Connection.printFile References: Message-ID: On Sep 19, 9:01?am, Antoon Pardon wrote: > On 2008-09-16, Graham Jenkins wrote: > > > > > I'm trying to print a file from within a Python program. > > > The quick-and-dirty solution is to use something like: > > > fd = os.popen("lp -d MyPrinter", "wb") > > fd.write(MyFileContents) > > > But it seems to me that there should be a clean solution like: > > > import cups > > stat = > > cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") > > What about systems that don't use cups for printing? > > -- > Antoon Pardon For Windows, there's a few different ways to print. Tim Golden has a list on his website: http://timgolden.me.uk/python/win32_how_do_i/print.html Mike From lists at cheimes.de Fri Sep 12 14:38:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Sep 2008 20:38:17 +0200 Subject: Getting Linux partition info programmatically In-Reply-To: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> References: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> Message-ID: python dev wrote: > Hello everyone, > > I am trying to get a list of all the partitions (along with their respective > file system types) listed in the /media directory. Does anybody know if > there is a way to do this using Python, or do I have to get this information > by parsing the output of a Linux command? The /sys and /proc file system provide all the information you need: for line in open("/proc/mounts"): ... Christian From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 00:04:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 04:04:29 GMT Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <%nEwk.681$sq3.240@trnddc07> Message-ID: <00d34d25$0$30713$c3e8da3@news.astraweb.com> On Sat, 06 Sep 2008 23:30:03 +0000, Alan G Isaac wrote: >> bearophileHUGS at lycos.com writes: >> >>> For Python 2.7/3.1 I'd now like to write a PEP regarding the >>> underscores into the number literals, like: 0b_0101_1111, 268_435_456 >>> etc. >> >> +1 on such a capability. >> >> -1 on underscore as the separator. > > > On 9/1/2008 9:13 PM Ben Finney apparently wrote: >> When you proposed this last year, the counter-proposal was made >> >> to instead use white space for the separator, exactly as one can now do >> with string literals. > > Yuck. > Repeating a mistake means two mistakes. A lot of us don't think that white space between string literals was a mistake. A lot of us consider it a desirable feature. > But I would hate less the use of nobreak spaces, since any decent editor > can reveal them. How do you type a nobreak space? It's also probably a bad idea for Python the language to depend on developers using "a decent editor", since many people disagree on what a decent editor is, and many other people don't have access to whatever you consider "a decent editor". -- Steven From cyberco at gmail.com Fri Sep 12 04:57:42 2008 From: cyberco at gmail.com (Berco Beute) Date: Fri, 12 Sep 2008 01:57:42 -0700 (PDT) Subject: Python on Windows XP 64-bit: python not found in registry Message-ID: After first trying to install the beta of Python 2.6 on my Windows XP 64-bit machine I finally succeeded installing 2.5.2. But I still have a some problem: Installing iPython, PIL, easy_install etc fails saying that python.exe cannot be found (although I can start the python interpeter just fine). The problem is that python cannot be found in the registry. I tried Effbot's solution of adding Python to the registry, but that doesn't help: http://effbot.org/zone/python-register.htm Anybody here that had the same problem and solved it? Thanks. 2B From girzel at gmail.com Mon Sep 29 23:46:17 2008 From: girzel at gmail.com (Eric Abrahamsen) Date: Mon, 29 Sep 2008 20:46:17 -0700 (PDT) Subject: Using re to find unicode ranges References: Message-ID: On Sep 29, 11:03 pm, "Mark Tolonen" wrote: > "Eric Abrahamsen" wrote in message > > news:mailman.1674.1222694261.3487.python-list at python.org... > > > Is it possible to use the re module to find runs of characters within a > > certain Unicode range? > > > I'm writing a Markdown extension to go over text and wrap blocks of > > consecutive Chinese characters in tags for > > nice styling in an HTML page. The available hooks appear to be a pre- > > processor (which is a "for line in lines" situation) or an inline pattern > > (which uses regular expressions). The regular expression solution would > > be much simpler and faster, but something tells me there's no way to use > > a regex to find character ranges... Chinese characters appear to fall > > between 19968 and 40959 using ord(), and I suppose I can go that route if > > necessary, but I think it would be ugly. > > # coding: utf-8 > import re > sample = u'My name is ??. I am ???.' > for n in re.findall(ur'[\u4e00-\u9fff]+',sample): > print n Of course! And obvious, once you point it out. Thanks for the help. > This sounds similar to what zhpy (http://pyparsing.wikispaces.com/ > WhosUsingPyparsing#Zhpy) does to extract Chinese words from code, to > generate executable English Python. You might give that a look. > --Mark Mark - not quite what I'm after here, but pretty interesting nonetheless... E From bdesth.quelquechose at free.quelquepart.fr Fri Sep 26 16:16:29 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 22:16:29 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: <48dd5f08$0$26425$426a74cc@news.free.fr> Tim Rowe a ?crit : > 2008/9/26 Tino Wildenhain : > >>> The question I usually ask is "Does this language help me get the job >>> done?" Python often does. That's all that really matters, isn't it? >> Well then it still depends on the perception of "job done". For example >> PHP programmers would bet their soul that their language of choice is >> exactly the right one to "get the job done." :-) >> You and me would indeed see a different picture on the level of doneness >> of such jobs ;-) > > Well, I did say "Often". Before now I've struggled for ages to write a > Python program to do a job, then when I've tried C# all the problems > have fallen away and the job was done in an hour or so. Not to start a troll, but from what I've seen of C# so far I do find this a bit surprising and really suspect more of a library issue than a language one. Care to tell more about the problem and solution ? (NB : I wouldn't even asked if you had mentionned say Erlang or Prolog or OCaml - well, some mostly different language - instead of C#) From kalin at el.net Thu Sep 18 12:17:55 2008 From: kalin at el.net (kalin m) Date: Thu, 18 Sep 2008 12:17:55 -0400 Subject: locks In-Reply-To: <18641.17709.251764.767222@montanaro-dyndns-org.local> References: <48D140FC.8070801@el.net> <18641.17709.251764.767222@montanaro-dyndns-org.local> Message-ID: <48D27F33.1070400@el.net> yea... sorry... i just have all python stuff in the same folder and messed up... skip at pobox.com wrote: > kalin> mailman has been locking one list out. the web interface just > kalin> hangs and it generates a bunch of locks. it seems that it can not > kalin> write to a log but not sure which one. errors are like: > ... > > You'd probably be better off asking about Mailman problems on > mailman-users at python.org. > > From half.italian at gmail.com Fri Sep 26 00:11:53 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 25 Sep 2008 21:11:53 -0700 (PDT) Subject: SimpleXMLRPCServer -- turning off request log? References: <9e0d437b-a6a6-4485-aa9a-93ed751b700f@o40g2000prn.googlegroups.com> Message-ID: On Sep 25, 9:04?pm, Sean DiZazzo wrote: > On Sep 25, 6:01?pm, m... at pixar.com wrote: > > > My SimpleXMLRPCServer program prints to stderr a line like > > this for each request: > > > ohm..pixar.com - - [25/Sep/2008 17:57:50] "POST /RPC2 HTTP/1.0" 200 - > > > Is there a way to turn this logging off? ?I have RTFM and can't > > seem to find a way to do so. > > > Many TIA! > > Mark > > > -- > > Mark Harrison > > Pixar Animation Studios > > Im pretty sure there's a more pythonic way, but you could redirect > stdout to /dev/null > > import sys > sys.stdout = open("/dev/null", 'w') > > assuming you're not on windows... > > ~Sean Here's the more pythonic version: # Fake a file handle with the write method class NullDevice(object): def write(self, s): pass import sys sys.stdout = NullDevice() * http://code.activestate.com/recipes/278731/ Comment 1: attributed to Mr. Lundh ~Sean From nospam at spamhaters.com Sun Sep 21 22:30:21 2008 From: nospam at spamhaters.com (clurks) Date: Sun, 21 Sep 2008 21:30:21 -0500 Subject: BeautifulSoup and Problem Tables References: Message-ID: <1rDBk.1283$c45.771@nlpi065.nbdc.sbc.com> academicedgar at gmail.com wrote: > Hi > > I would appreciate some help. I am trying to learn Python and want to > use BeautifulSoup to pull some data from tables. I was really psyched > earlier tonight when I discovered that I could do this > > from BeautifulSoup import BeautifulSoup > bst=file(r"c:\bstest.htm").read() > soup=BeautifulSoup(bst) > rows=soup.findAll('tr') > len(rows) > a=len(rows[0].findAll('td')) > b=len(rows[1].findAll('td')) > c=len(rows[2].findAll('td')) > d=len(rows[3].findAll('td')) > e=len(rows[4].findAll('td')) > f=len(rows[5].findAll('td')) > g=len(rows[6].findAll('td')) > h=len(rows[8].findAll('td')) > i=len(rows[9].findAll('td')) > j=len(rows[10].findAll('td')) > k=rows[1].findAll('td')[1].contents[0] > > > So here I am chortling to myself thinking this is too easy. I know > that the data columns are in rows[0] and so I can learn some more > python to figure out how to create tuples so I can lable each data > item using the row and column headings plucked from the contents. > > However, I discovered that my tables have inconsistent numbers of > rows. Even though the tables look pretty. It might be that the > column heading for the third column is "Apples" but the value for > "Apples" in the fourth row is not in the third position in the row but > the fourth. > > Now I am reluctant to make any assumptions because the tables were > created inconsistently. What I mean is that in some tables if there is > no value for a row/column intersection then there is a blank line, in > other tables if there is no value for a row/column intersection then > the length of k (as above) is 0. > > I have been Googling for some insight into this and I have not been > successful finding anything. I would really appreciate any suggestions > or some direction about how to better describe the problem. This may help, and it may not. One of the most useful features of BeautifulSoup is the .prettify() function. Use it, and you can examine your xml with a browser or decent editor. You will be able, hopefully, to see attributes that may explain your difficulties. The one that snuck up and bit me was table:number-columns-repeated -- I don't know what is biting you, but it is weird the way known cells are completely skipped with this attribute -- you have to know about it and check for it. If there is a way to deal with that attribute using BeautifulSoup I was unable to find it given the documentation and examples available to me. I took a step back and tried xml.sax -- it is straighforward and easy to use -- you build an xml.sax.handler for your xml, and it deals with it. It worked for me, but, as always, YMMV sc From mwojc at NOSPAMp.lodz.pl Tue Sep 9 13:29:16 2008 From: mwojc at NOSPAMp.lodz.pl (mwojc) Date: Tue, 09 Sep 2008 19:29:16 +0200 Subject: F2PY changing integers to arrays??? References: <7d60c85f-12cf-47fc-84c9-58e50cad4eaf@x35g2000hsb.googlegroups.com> Message-ID: john wrote: > I have a simple module which performs basic operations on plot3d files > (below). I wrapped like: > > f2py --fcompiler=gfortran -m plot3d -c prec.f90 plot3d.f90 > > That seems to work fine, but i get some unexpected results... > >>>> from plot3d import plot3d as p3 >>>> dir(p3) > ['imax', 'jmax', 'kmax', 'mg', 'prc', 'printall', 'readit', 'writeit', > 'writeit2d'] >>>> p3.readit( "mesh.xrtz.dat", "FORMATTED", ".TRUE." ) >>>> p3.imax > array(409) > > > "409" is correct, but "imax" is declared as an INTEGER in fortran and > now it's an array in python??? Any ideas? > > > > > > > > > # prec.f90 > MODULE prec > IMPLICIT NONE > INTEGER, PARAMETER :: single = SELECTED_REAL_KIND(p=6,r=37) > INTEGER, PARAMETER :: double = SELECTED_REAL_KIND(p=15,r=200) > END MODULE prec > > > > > # plot3d.f90 > MODULE PLOT3D > USE prec > IMPLICIT NONE > INTEGER, PARAMETER :: prc=single > REAL(prc), ALLOCATABLE, DIMENSION(:,:,:,:) :: x, y, z > INTEGER :: mg, imax, jmax, kmax > > CONTAINS > > !---------- > SUBROUTINE READIT( fname, ftype, fmg ) > ! reads the plot3d, formatted, mg file in xyz > IMPLICIT NONE > CHARACTER(len=20), INTENT(IN) :: fname, ftype > > LOGICAL :: fmg > INTEGER :: i, j, k, n, f=1 > > SELECT CASE (ftype) > CASE ('FORMATTED') > OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > IF (fmg) READ(f,*) mg ! only read if multigrid > READ(f,*) imax, jmax, kmax > ALLOCATE( x(mg, imax, jmax, kmax) ) > ALLOCATE( y(mg, imax, jmax, kmax) ) > ALLOCATE( z(mg, imax, jmax, kmax) ) > READ(f,*) ((((x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ((((y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ((((z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > CASE ('UNFORMATTED') > OPEN( UNIT=f, FILE=fname, STATUS='OLD', ACTION='READ', > FORM=ftype ) > IF (fmg) READ(f) mg ! only read if multigrid > READ(f) imax, jmax, kmax > ALLOCATE( x(mg, imax, jmax, kmax) ) > ALLOCATE( y(mg, imax, jmax, kmax) ) > ALLOCATE( z(mg, imax, jmax, kmax) ) > READ(f) ((((x(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ((((y(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg), & > ((((z(n, > i,j,k),i=1,imax),j=1,jmax),k=1,kmax),n=1,mg) > CASE DEFAULT > WRITE(*,*) 'filetype not supported in ' > STOP > END SELECT > > CLOSE(f) > > END SUBROUTINE READIT > > END MODULE PLOT3D I'm not sure why you obtain array(409) instead 409, but you can use this type in python as normal integer. For example array(409)+409 gives integer value 818. Greetings -- Marek From steve at holdenweb.com Thu Sep 18 13:01:55 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Sep 2008 13:01:55 -0400 Subject: append on lists In-Reply-To: <4097db86-b9dc-4ed5-ac84-6747a9f2bb11@t54g2000hsg.googlegroups.com> References: <4097db86-b9dc-4ed5-ac84-6747a9f2bb11@t54g2000hsg.googlegroups.com> Message-ID: tony.clarke5 at googlemail.com wrote: > On Sep 16, 6:03 am, Peter Anderson > wrote: >> "/... I don't think you've thought this one through, really./" >> snip >> >> We ought to try and be a little kinder to others on the list, don't you >> think? :-) >> >> snip > > Well said! >From personal experience I find that honest attempts to straighten people out lead to accusations of exploiting "seniority" to attack people. There goes the neighborhood, I guess. Of course we should try to maintain c.l.py's deserved reputation for civil behavior, but things like that aren't easy to police. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From bdesth.quelquechose at free.quelquepart.fr Tue Sep 9 13:03:47 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 19:03:47 +0200 Subject: [OT] top-posting and quoting (was: Re: Coming from .NET and VB and C) In-Reply-To: <9efc52fa-f2d2-40e4-8fbb-fb4c06f8e0e4@a3g2000prm.googlegroups.com> References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <48bfc4e4$0$13232$426a74cc@news.free.fr> <9efc52fa-f2d2-40e4-8fbb-fb4c06f8e0e4@a3g2000prm.googlegroups.com> Message-ID: <48c6c862$0$17309$426a34cc@news.free.fr> Could you please timh and belindelof learn to quote properly and stop top-posting ? TIA From peter.waller at gmail.com Fri Sep 12 08:44:57 2008 From: peter.waller at gmail.com (Peter Waller) Date: Fri, 12 Sep 2008 05:44:57 -0700 (PDT) Subject: Injecting new names into the above frame Message-ID: Dear Pythoners, I know this will probably be perceived as 'evil voodoo', and fair enough: it probably is. I guess it is unpythonic. .. but I want to know how to do it anyway - mostly for my own interest. Consider the following snippet of code: --- def Get( *names ): if not names: return None frame = sys._getframe(1) prevFrameLocals = frame.f_locals for name in names: prevFrameLocals[ name ] = FetchObjectNamed( name ) Get("a", "b", "c") print a, b, c --- FetchObjectNamed() is an arbitrary function which takes a string and returns an object it got from some store somewhere. This works fine at the module level, because names in the locals/ globals dictionary can be played with in this way. The idea is to save lots of typing, i.e. a, b, c = Get("a","b","c") ..gets frustrating after much typing for many objects with long names. This is just an example, there are other instances I have where it would be nice to inject names into the frame above. Of course, we hit a road block when we call 'Get' from a function rather than a module, because the locals dictionary does not get copied back into the code object automatically, so we have to add this snippet before the Get() function returns: from ctypes import pythonapi, py_object, c_int pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 ) This copies back the names into the code object, and works fine.. that is, if the names already exist within the code object. def MyFunction(): a = None Get("a") print a # Works Get("b") print b # Name error, b is undefined Is there any way for Get() to define a new variable within MyFunction's code object? Or is there any programmatic way to, at runtime, insert new names into functions? I don't care how hacky it is and whether it requires making calls to python's internals with ctypes - maybe the whole code object needs to be replaced? is it even possible to do that when the Get() function is about to return to this new code object? Cheers, - Peter From ceball at users.sourceforge.net Thu Sep 11 16:10:23 2008 From: ceball at users.sourceforge.net (Chris) Date: Thu, 11 Sep 2008 20:10:23 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: Message-ID: Christian Heimes cheimes.de> writes: ... > You can use slots to increase the performance but it doesn't work > like you think. If you need it *really* fast than write a C > Extension, store the data in a C struct and access the data via > PyMemberDef. Ok, thanks for the confirmation. We'd been hoping to avoid creating such a struct... Chris From steve at holdenweb.com Thu Sep 18 13:19:49 2008 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 Sep 2008 13:19:49 -0400 Subject: append on lists In-Reply-To: References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: Armin wrote: > Duncan Booth wrote: >> "Chris Rebert" wrote: >>> On Tue, Sep 16, 2008 at 1:20 AM, Armin
wrote: >>>> [1,2,3,4,7].append(c) -> Is this a valid expression? >>> Literally, no, because you can't call methods on literals. >> >> Rubbish. There is no restriction about calling methods on literals. >> That expression is perfectly valid but has no practical use that I can >> see. > > The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > (with c = [8,9]) is identical, but the first expression doesn't provide > a value. Strange by design ... > Have a care, there. The semantics are different. lst = [1, 2, 3, 4, 7] lst.append([8, 9]) makes lst [1, 2, 3, 4, 7, [8, 9]] whereas lst = [1, 2, 3, 4, 7] lst = lst + [8, 9] makes lst [1, 2, 3, 4, 5, 7, 8, 9] I suspect you meant [1, 2, 3, 4, 5, 7] + [c] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fredrik at pythonware.com Sat Sep 27 08:06:36 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Sep 2008 14:06:36 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <48DC22C7.5020001@gmail.com> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> <48DC22C7.5020001@gmail.com> Message-ID: Stef Mientki wrote: > I don't think your suggestion is a good one. > If a filename has uppercase characters in it, > the END-USER has done that for some kind of reason. I explain how pdb works and show you how to solve the specific comparison problem you mentioned in your post, and you start ranting because it doesn't solve all your problems? what's wrong with you? From code at pizzashack.org Mon Sep 29 11:56:30 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 29 Sep 2008 11:56:30 -0400 Subject: Test if list contains another list In-Reply-To: <6304d804-57a1-458d-8ffe-b7a387dd0584@a1g2000hsb.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> <6304d804-57a1-458d-8ffe-b7a387dd0584@a1g2000hsb.googlegroups.com> Message-ID: <20080929155630.GM26713@dragontoe.org> On Mon, Sep 29, 2008 at 04:12:13AM -0700, bearophileHUGS at lycos.com wrote: > Derek Martin: > >Unless you're doing lots and lots of these in your application,< > > I don't agree. That's library code, so it has to be efficient and > flexible, because it's designed to be used in many different > situations That's fair, but lots of folks writing Python code will look at that and say, "What the %$#@! is this doing?!?" As I already suggested, code that implements non-obvious algorithms ought to explain what it's doing in comments, so that the neophyte programmers charged with maintaining the library aren't tempted to rewrite the code so that it's easier to understand what it's doing. It can be as simple as: # Use Morris-Pratt algorithm to search data Then, anyone not familiar with the algorithm can easily look it up, and see why it was written that way. I think it's just as important to do that in code you post on the list, since a) the person asking the question obviously doesn't know what you're doing, or they wouldn't have needed to ask the question, and b) there are lots of other folks reading the list who could benefit from the same knowledge. :) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From merwick.k at gmail.com Tue Sep 23 09:41:52 2008 From: merwick.k at gmail.com (merwick.k) Date: Tue, 23 Sep 2008 06:41:52 -0700 (PDT) Subject: The World Trade Plaza - Free Trade Leads Message-ID: <6d2bbe82-6d9c-4484-90e8-bb908bce885a@25g2000hsx.googlegroups.com> FREE INTERNATIONAL TRADE LEADS ==> The World Trade Plaza http://trade-plaza.blogspot.com Are you looking for potential clients for your products? Are you looking for a free place for to display your products? Each day we publish international purchase requisitions and offers for sale. The Trade Leads published in our website are FREE for everyone! You have NO NEED TO REGISTER for to view any lead in this website. You have NO LIMIT on Posting Trade Leads. You can Upload Photos With Every Import Export Leads. You can See Latest Products You can automatically receive All Trade Leads by email (Free Subscribe) Much more are All Free. Start Buying or Selling NOW. ==> http://trade-plaza.blogspot.com From tjreedy at udel.edu Fri Sep 26 17:06:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 17:06:24 -0400 Subject: Large Data Sets: Use base variables or classes? And some binding questions In-Reply-To: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> Message-ID: Patrick Sullivan wrote: > Hello. > > I will be using some large data sets ("points" from 2 to 12 variables) > and would like to use one class for each point rather than a list or > dictionary. I imagine this is terribly inefficient, but how much? I strongly suspect that you should use one class and a class instance for each 'point'. You can make instances 'fixed' after initialization by customizing appropriate methods, but I would not bother for private code. From tjreedy at udel.edu Mon Sep 1 15:08:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 15:08:30 -0400 Subject: how to find position of dictionary values In-Reply-To: <48BBA624.5010501@sellerengine.com> References: <48BBA624.5010501@sellerengine.com> Message-ID: Alexandru Palade wrote: > lookfor = 'dfsdf' > for item, value in kev.items(): > if lookfor in value: > print item > print value.index(lookfor) > break # assuming you only want one result slight variation: lookfor = 'dfsdf' for item, value in kev.items(): for i, val in enumerate(value): if val == lookfor: print item, i break # assuming you only want one result else: print lookfor, 'not found' This is what for-else is meant for. If you want 0 to many lookfor occurences, lookfor = 'dfsdf' hits = [] for item, value in kev.items(): for i, val in enumerate(value): if val == lookfor: hits.append((item, i)) print hits One-liner fanatics would, of course, rewrite this as hits = [(item, i) for item, value in kev.items() for i, val in enumerate(value) if val == lookfor] Terry Jan Reedy tjr From steve at REMOVE-THIS-cybersource.com.au Fri Sep 19 21:51:05 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Sep 2008 01:51:05 GMT Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: <00e45101$0$20331$c3e8da3@news.astraweb.com> On Fri, 19 Sep 2008 17:00:56 -0700, MRAB wrote: > Extending len() to support iterables sounds like a good idea, except > that it could be misleading when: > > len(file(path)) > > returns the number of lines and /not/ the length in bytes as you might > first think! Extending len() to support iterables sounds like a good idea, except that it's not. Here are two iterables: def yes(): # like the Unix yes command while True: yield "y" def rand(total): "Return random numbers up to a given total." from random import random tot = 0.0 while tot < total: x = random() yield x tot += x What should len(yes()) and len(rand(100)) return? -- Steven From tjreedy at udel.edu Fri Sep 26 16:59:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 16:59:09 -0400 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <48dd4756$0$25116$426a74cc@news.free.fr> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> Message-ID: nntpman68 wrote: > I guess you just filter mailing lists and can do nothing about the > newsgroup if I'm fetching via the nntp server of my ISP itself, right? I am reading via gmane.comp.python.general, so I will benefit from filtering spam posted to c.l.p. Anyone with a news reader can do the same. Just make a news.gmane.org account with standard port setting. Works fine with OE and now Tbird. I believe posts to gmane are sent to the mailing list first, before appearing even on gmane. > - I'm annoyed by any spam. Ditto. I would say 'nuisance' rather than 'major nuisance'. Improvements are appreciated here. > It's tough to find good rules, but the incoming spams that I see > currently on comp.lang.python have certain criteas. > > - most email addresses from gmail. > - all never posted before and then they have multiple posts within a few > minutes / seconds > - the posts always contain one or more urls ( mostly cryptic names ) > - they always start a thread but never reply to one > - the post doesn't contain python code or anything which looks only > vaguely like source code > - never mentions the word python > - the amount of sexual or financial vocabulary exceeds classical python > posts Pretty good list. From fredrik at pythonware.com Sat Sep 13 06:58:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 12:58:57 +0200 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Usman Ajmal wrote: > Where exactly should i call ServerProxy? Following is the code from my > client.py ServerProxy is the preferred name. Server is an old alias for the same class. > t = SecureTransport() > > t.set_authorization(ustring, text_ucert) > server = xmlrpclib.Server('http://localhost:8000/',transport=t) > print server.s() that code looks correct. so what's the problem? From gogtesuyash at gmail.com Tue Sep 30 01:15:43 2008 From: gogtesuyash at gmail.com (sui) Date: Mon, 29 Sep 2008 22:15:43 -0700 (PDT) Subject: python & sms References: Message-ID: On Sep 30, 10:10 am, "James Mills" wrote: > sui, > > I am sure you'll find many web services > that you can use to send SMS'. Your > problem would then become one of > learning how to communicate and access > web services in Python. Start with: > * urllib and urllib2 > * xmlrpc > > There are others... > > cheers > James > > On Tue, Sep 30, 2008 at 1:47 PM, sui wrote: > > Hii > > i want a script to send sms to any mobile..... > > can u help me ?? > > > Thanks in advance...... > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- > -- "Problems are solved by method" kk......wil try to use that... I thought if someone has already worked with it den it will be helpful.... thnks & cheers From half.italian at gmail.com Wed Sep 10 06:55:53 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 10 Sep 2008 03:55:53 -0700 (PDT) Subject: Catching subprocess stdout stream References: <00b9dc86-e002-4e2c-a686-39d2dd1016b9@m3g2000hsc.googlegroups.com> Message-ID: <9deaf3ef-2103-444f-bb46-309aee7045c5@r15g2000prd.googlegroups.com> On Sep 8, 8:37?am, Thomas Jansson wrote: > Dear all > > I have tkinkter based frontend to a Fortran based program. I use > subprocess to launch the fortran program as a child process and I wish > to see the output of the fortran program as it is created in the > console. > > The fortran program can take up to 20 minuttes to finish and at the > moment the I will first see any output after the fortran program is > done. How make my function write the output of the process as it > comes? > > def runprogram(Icommand, Ijobfile, Ioutput): > ? ? if os.name == "posix": > ? ? ? ? os.system(pythonpath+"/bin/"+Icommand+"< "+Ijobfile+" | tee > "+Ioutput) > ? ? elif os.name == "nt": > ? ? ? ? import subprocess > ? ? ? ? ofile = open(Ioutput, 'w') > ? ? ? ? p = subprocess.Popen([os.path.join(pythonpath, "bin", Icommand > + '.exe')], > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?stdin=open(Ijobfile, > "rb"),bufsize=1024,shell=False, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?stdout=subprocess.PIPE) > > ? ? ? ? while p.poll() is None: #Check if child process has terminated. > ? ? ? ? ? ? o = p.stdout.readline() > ? ? ? ? ? ? ofile.writelines(o) > ? ? ? ? ? ? print o, > ? ? ? ? ofile.close > > Kind regards > Thomas Jansson import threading, Queue, subprocess class iCommand(threading.Thread): def __init__ (self, iCommand, iJobFile, queue): threading.Thread.__init__(self) self.iCommand = iCommand self.queue = queue self.iJobFile = iJobFile def run(self): p = subprocess.Popen([os.path.join("C:/Python25", "bin", self.iCommand + '.exe')], stdin=open(self.iJobFile, "rb"),bufsize=1024,shell=False, stdout=subprocess.PIPE) while p.poll() == None: q.put(p.stdout.readline()) command = "FOO" jobFile = ="FAH" aQueue = Queue.Queue() fo = open("C:/temp/foo.out", 'w') aThread = iCommand(command, jobFile, aQueue) aThread.start() while aThread.isAlive() or not aQueue.empty(): l = aQueue.get().rstrip() fo.write(l) print l fo.close() A bit of fun for a sleepless night... ~Sean From circularfunc at yahoo.se Sun Sep 14 04:01:42 2008 From: circularfunc at yahoo.se (cnb) Date: Sun, 14 Sep 2008 01:01:42 -0700 (PDT) Subject: recursion gotcha? Message-ID: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> this recursive definition of sum thrumped me, is this some sort of gotcha or am I just braindead today? and yes i know this is easy a a for x in xs acc += x or just using the builtin. def suma(xs, acc=0): if len(xs) == 0: acc else: suma(xs[1:], acc+xs[0]) it returns none. def summa(xs): if not xs: 0 else: xs[0]+summa(xs[1:]) Traceback (most recent call last): File "", line 1, in summa([1,2,3,4,5]) File "", line 5, in summa xs[0]+summa(xs[1:]) File "", line 5, in summa xs[0]+summa(xs[1:]) File "", line 5, in summa xs[0]+summa(xs[1:]) File "", line 5, in summa xs[0]+summa(xs[1:]) File "", line 5, in summa xs[0]+summa(xs[1:]) TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' From stef.mientki at gmail.com Sat Sep 6 05:28:28 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 06 Sep 2008 11:28:28 +0200 Subject: wxPython problem In-Reply-To: <48C23638.1000109@internode.on.net> References: <48C23638.1000109@internode.on.net> Message-ID: <48C24D3C.7060306@gmail.com> Peter Anderson wrote: > I am trying to teach myself how to program in Python and use wxPython > for GUIs. I am using PyScripter, IDLE and EditPlus as my IDEs. I have > experienced an odd problem where I run a script once and it runs fine. > Run it again and I get an error and the script fails. > > If the script is run directly from Python ('Run' from Windows > Explorer) or from EditPlus (in which I have a "user-defined tool" > which calls C:\Python25\pythonw.exe with the parameter of $(FileName)) > then there is *never* any error, no matter how many times the script > is run. > > Close down PyScripter or IDLE and then start either up again, load the > script and run it - it runs fine. Run it again and it fails. It seems > like something is already set in memory and cant be re-set (my lack of > knowledge is showing here :-( ). > In PyScripter, you should run wxPython in the plain remote machine (not the wxPython remote), and you should set "reset before run flag" or reset the remote machine each time yourself. cheers, Stef > More details are shown below. Any help or hints would be greatly > appreciated. > > Regards, > Peter > > > RUNNING SIMPLE.PY (AND OTHER SCRIPTS USING WXPYTHON) FROM PYSCRIPTER I > GET THE FOLLOWING ERROR MESSAGE: > > PyNoAppError: The wx.App object must be created first! > > PyScripter loads a module (I presume from wxPython) called _windows.py > and highlights a particular line in red and displays the error message > from above. I have Googled the error message but the results have not > helped. > > > LISTING FOR SIMPLE.PY > > #!/usr/bin/python > > # simple.py > > import wx > > app = wx.App() > > frame = wx.Frame(None, -1, 'simple.py') > frame.Show() > > app.MainLoop() > > > EXERPT FROM _WINDOWS.PY - PYSCRIPTER HIGHLIGHTS SECOND LAST LINE > > class Frame(TopLevelWindow): > """Proxy of C++ Frame class""" > thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), > doc='The membership flag') > __repr__ = _swig_repr > def __init__(self, *args, **kwargs): > """ > __init__(self, Window parent, int id=-1, String title=EmptyString, > Point pos=DefaultPosition, Size size=DefaultSize, > long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) -> Frame > """ > > # The following line is highlighted as where the error occures > > _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) > self._setOORInfo(self) > > > RUNNING THE SIMPLE.PY SCRIPT FROM WITHIN IDLE PRODUCES THE FOLLOWING > ERROE MESSAGE: > > Traceback (most recent call last): > File "C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython > Tutorial\absolute.py", line 28, in > Absolute(None, -1, '') > File "C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython > Tutorial\absolute.py", line 9, in __init__ > wx.Frame.__init__(self, parent, id, title, size=(250, 180)) > File > "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", > line 505, in __init__ > _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) > PyNoAppError: The wx.App object must be created first! > > From sturlamolden at yahoo.no Wed Sep 24 12:56:17 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 09:56:17 -0700 (PDT) Subject: Python is slow? References: Message-ID: For those who are interested: I've updated the cookbook tutorial on the kd-tree: http://scipy.org/Cookbook/KDTree It now also includes parallel search for multicore CPUs (multiprocessing standard module). Even if you are not genuinely interested in kd-trees, it shows how to do parallel processing in Python despite of the GIL. From mbrkic at invalid_mail.adress Wed Sep 24 19:42:52 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Thu, 25 Sep 2008 01:42:52 +0200 Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> <7c1554cb-f167-462e-ac7c-ea82cdda99b6@y21g2000hsf.googlegroups.com> Message-ID: <0vjld4p4m8tcdble36uvne509cp8kv7rsj@4ax.com> On Wed, 24 Sep 2008 14:50:56 -0700 (PDT), sturlamolden wrote: >On Sep 24, 3:17?pm, Marin Brkic wrote: > >> Has anyone had a situation like this ? All your inputs and suggestions >> are more then welcomed. > >Send them the .py file and confirm that it does work. The lack of >Python can be blamed on the incompetent BOFH. Chances are the >situation will change when the BOFH gets 20 requests for Python a >day. > Yes, I agree. But in large institutions, where system engineers maintain a lot of computers there usually exists a policy on what is installed on computers and what is not. And currently python is not. And it's not gonna change anytime soon since only few of us are using it (2 of us use it on personal laptops, to others we send exe files). -- Marin From carsten.haese at gmail.com Tue Sep 30 13:32:21 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 30 Sep 2008 13:32:21 -0400 Subject: r"" In-Reply-To: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> Message-ID: Kyle Hayes wrote: > Is there a way to use the 'r' in front of a variable instead of > directly in front of a string? Or do I need to use a function to get > all of the slashes automatically fixed? Please describe the actual problem you're trying to solve. In what way do slashes need to be "fixed," and why? -- Carsten Haese http://informixdb.sourceforge.net From mr.spoon21 at gmail.com Mon Sep 29 17:45:45 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Mon, 29 Sep 2008 23:45:45 +0200 Subject: Music knowledge representation In-Reply-To: <20080929165608.b7b87b60.darcy@druid.net> References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> <20080929124940.8c1c82e8.darcy@druid.net> <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> <20080929165608.b7b87b60.darcy@druid.net> Message-ID: <8f67b6f80809291445y30e16a5cw31d1ab9ef3615a47@mail.gmail.com> On Mon, Sep 29, 2008 at 10:56 PM, D'Arcy J.M. Cain wrote: >> I can't estabilish which note is higher, because all the analysis part >> is octave independent. Anyway thanks for the ideas. > > I'm not sure I understand this. You either have to assume that the > first note is the root or the lower one is. What other options are > there? It sounds like your requirement is "higher += 12" or some > variant. It also depends on whether you need to deal with things like > ninths and thirteenths. > > Anyway, I was just tossing out ideas. You know what your requirements > are better than I. Mmm, actually it's a good idea. I didn't get it right before. Thanks :D From bhaarat.s at gmail.com Fri Sep 12 20:57:03 2008 From: bhaarat.s at gmail.com (bhaarat Sharma) Date: Fri, 12 Sep 2008 17:57:03 -0700 Subject: Good python web programming books Message-ID: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> Hi Guys, I am very new to python. I am looking for a good book about python web programming. I looked at a few online like Web Programming In Python but most are quite old. If you've read a good book on python web programming can you please suggest some? Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From gstaniak at wp.pl Wed Sep 10 14:59:14 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Wed, 10 Sep 2008 18:59:14 +0000 (UTC) Subject: PHP's str_replace ? References: <6iq2jpFs113rU1@mid.uni-berlin.de> <6iq2sbFs113rU2@mid.uni-berlin.de> <48C7F6EA.7010202@anjanesh.net> <2746da03-39df-4bc0-9365-de5a2414adc4@f36g2000hsa.googlegroups.com> Message-ID: On 10.09.2008, David Thole wroted: >> >> new_str = re.sub('[aeiou]', '-', str) >> > Wow - this is neat. Thanks >> >> But probably slower and definitely harder to understand. For simple >> problems the str methods are usually faster than a regular expression. > > It's true that regular expressions are generally slower, but I > disagree that it's hard to understand. When dealing with text, I > think it's an absolute must that programmers know about regular > expressions. I think this here is an example where even str_replace > in Python wouldn't have worked well. What about mystring.translate(transtable)? GS -- Grzegorz Staniak Nocturnal Infiltration and Accurate Killing From google at mrabarnett.plus.com Fri Sep 19 20:00:56 2008 From: google at mrabarnett.plus.com (MRAB) Date: Fri, 19 Sep 2008 17:00:56 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: On Sep 19, 2:01?pm, bearophileH... at lycos.com wrote: > Gerard flanagan: > > > data.sort() > > datadict = \ > > dict((k, len(list(g))) for k,g in groupby(data, lambda s: > > ? ? ?'.'.join(s.split('.',2)[:2]))) > > That code may run correctly, but it's quite unreadable, while good > Python programmers value high readability. So the right thing to do is > to split that line into parts, giving meaningful names, and maybe even > add comments. > > len(list(g))) looks like a good job for my little leniter() function > (or better just an extension to the semantics of len) that time ago > some people here have judged as useless, while I use it often in both > Python and D ;-) > Extending len() to support iterables sounds like a good idea, except that it could be misleading when: len(file(path)) returns the number of lines and /not/ the length in bytes as you might first think! :-) Anyway, here's another possible implementation using bags (multisets): def major_version(version_string): "convert '1.2.3.2' to '1.2'" return '.'.join(version_string.split('.')[:2]) versions = ["1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] bag_of_versions = bag(major_version(x) for x in versions) dict_of_counts = dict(bag_of_versions.items()) Here's my implementation of the bag class in Python (sorry about the length): class bag(object): def __init__(self, iterable = None): self._counts = {} if isinstance(iterable, dict): for x, n in iterable.items(): if not isinstance(n, int): raise TypeError() if n < 0: raise ValueError() self._counts[x] = n elif iterable: for x in iterable: try: self._counts[x] += 1 except KeyError: self._counts[x] = 1 def __and__(self, other): new_counts = {} for x, n in other._counts.items(): try: new_counts[x] = min(self._counts[x], n) except KeyError: pass result = bag() result._counts = new_counts return result def __iand__(self): new_counts = {} for x, n in other._counts.items(): try: new_counts[x] = min(self._counts[x], n) except KeyError: pass self._counts = new_counts def __or__(self, other): new_counts = self._counts.copy() for x, n in other._counts.items(): try: new_counts[x] = max(new_counts[x], n) except KeyError: new_counts[x] = n result = bag() result._counts = new_counts return result def __ior__(self): for x, n in other._counts.items(): try: self._counts[x] = max(self._counts[x], n) except KeyError: self._counts[x] = n def __len__(self): return sum(self._counts.values()) def __list__(self): result = [] for x, n in self._counts.items(): result.extend([x] * n) return result def __repr__(self): return "bag([%s])" % ", ".join(", ".join([repr(x)] * n) for x, n in self._counts.items()) def __iter__(self): for x, n in self._counts.items(): for i in range(n): yield x def keys(self): return self._counts.keys() def values(self): return self._counts.values() def items(self): return self._counts.items() def __add__(self, other): for x, n in other.items(): self._counts[x] = self._counts.get(x, 0) + n def __contains__(self, x): return x in self._counts def add(self, x): try: self._counts[x] += 1 except KeyError: self._counts[x] = 1 def __add__(self, other): new_counts = self._counts.copy() for x, n in other.items(): try: new_counts[x] += n except KeyError: new_counts[x] = n result = bag() result._counts = new_counts return result def __sub__(self, other): new_counts = self._counts.copy() for x, n in other.items(): try: new_counts[x] -= n if new_counts[x] < 1: del new_counts[x] except KeyError: pass result = bag() result._counts = new_counts return result def __iadd__(self, other): for x, n in other.items(): try: self._counts[x] += n except KeyError: self._counts[x] = n def __isub__(self, other): for x, n in other.items(): try: self._counts[x] -= n if self._counts[x] < 1: del self._counts[x] except KeyError: pass def clear(self): self._counts = {} def count(self, x): return self._counts.get(x, 0) From circularfunc at yahoo.se Sun Sep 7 16:47:33 2008 From: circularfunc at yahoo.se (cnb) Date: Sun, 7 Sep 2008 13:47:33 -0700 (PDT) Subject: problem with permutations Message-ID: I am trying to translate this elegant Erlang-code for finding all the permutations of a list. I think it is the same function as is but it doesn't work in Python. -- is upd in Python. It works as it should. perms([]) -> [[]]; perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. def perms(lista): if lista == []: return [[]] else: for h in lista: return [([h]+[t]) for t in perms(upd(lista, h))] def upd(lista, elem, acc=tuple([])): lista = tuple(lista) if lista == (): return list(acc) if lista[0] == elem: return list(acc + tuple(lista[1:])) else: return upd(lista[1:], elem, acc + tuple([lista[0]])) From mellowcellofellow at gmail.com Mon Sep 22 18:40:11 2008 From: mellowcellofellow at gmail.com (Joshua Gardner) Date: Mon, 22 Sep 2008 16:40:11 -0600 Subject: Using vObject Message-ID: I'm brand new to USENET so please bear with me. I'm writing a specialized to-do list app. I'm using Django but this is not a question about Django. It has to have recurring tasks set by the managers for the employees to then check off. I've got pretty much everything in the app worked out, except for one thing: the repeating tasks. I want to have it so that the manager puts in a repeating task with a description and a repeat rule. This rule then generates simpler one-time tasks. These one-time tasks have a description, a time (a datetime.datetime object) and "completed" boolean. I've looked around and think I have these options: 1. Manually put it all together with another Django model that implements the repeat rules. 2. Do the same thing but use dateutil.rrule to help. 3. Use the icalendar (http://codespeak.net/icalendar/) module to access ICS files. 4. vObject (http://vobject.skyhouseconsulting.com/) to do the same. I think I want to use vObject because it uses dateutil and the management can easily manage tasks from a desktop app. Only thing is that I find vObject's documentation very cryptic and was wondering if anybody here could shed some light on how to use vObject. A simple "getting-started" tutorial or something similar would be nice. Thanks all! -Josh From gherron at islandtraining.com Sun Sep 14 11:08:08 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 14 Sep 2008 08:08:08 -0700 Subject: Is there any nice way to unpack a list of unknown size?? In-Reply-To: <238815.3778.qm@web7902.mail.in.yahoo.com> References: <238815.3778.qm@web7902.mail.in.yahoo.com> Message-ID: <48CD28D8.9060104@islandtraining.com> srinivasan srinivas wrote: > I want to do something like below: > > 1. first, second, third, *rest = foo > Python 3.0 has exactly this feature. No current Python 2.x version has it. Gary Herron > 2. for (a,b,c,*rest) in list_of_lists: > > Please suggest. > > Thanks, > Srini > > > Bring your gang together. Do your thing. Find your favourite Yahoo! group at http://in.promos.yahoo.com/groups/ > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Sun Sep 7 07:50:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 08:50:50 -0300 Subject: modules path References: Message-ID: En Sat, 06 Sep 2008 20:26:24 -0300, Python escribi?: > now one question came up, how do I make those path permanent? > i mean, sys.path.append( adds it for the current session, > yet when i logout of IDLE and start it again it's gone... > how do i keep it in there? You can add that path to the PYTHONPATH environment variable, or you can put a .pth file in the current Lib directory, containing the desired path. See http://docs.python.org/inst/search-path.html and the documentation for the site module (although it appears not to be totally accurate). -- Gabriel Genellina From paul at boddie.org.uk Tue Sep 2 04:16:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 2 Sep 2008 01:16:55 -0700 (PDT) Subject: (in memory) database References: <5enqo5-9n9.ln1@lairds.us> <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> Message-ID: <3e419475-61a1-4579-a8b6-fc15f9fe0a9b@m73g2000hsh.googlegroups.com> On 2 Sep, 04:46, Zentrader wrote: > On Ubuntu you want to install something like python-sqlite (a search > for "python" should turn up everything). ?There are 2 parts to this, > SQLite and the python bindings to SQLite. ?So you seem to have SQLite > installed but not the Python bindings. ?Also, on some systems you have > to have python-sqlite installed, and then build python in order to use > it. The python-sqlite and python-sqlite2 packages were needed for Python 2.4 - it was possibly python2.4-sqlite or python2.4-sqlite2 if you go back a few versions - but Python 2.5 should depend on the sqlite libraries and pull them in automatically: http://packages.ubuntu.com/hardy/python2.5 I don't understand why Cameron has a different version of Python which doesn't seem to have sqlite support enabled. Paul From lists at cheimes.de Tue Sep 30 14:08:16 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 30 Sep 2008 20:08:16 +0200 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > > The executable would execute perfectly. > > > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") Try this: import subprocess retval = subprocess.call( ['Myprogram.exe', '1', '1', 'acc', '0'], cwd='C:\myprogramfolder\run') Christian From adityashukla1983 at gmail.com Sun Sep 21 14:33:24 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sun, 21 Sep 2008 13:33:24 -0500 Subject: Newick parser Message-ID: <73045cca0809211133y3198bde2n483738de8cac2810@mail.gmail.com> Hello folks , i have a .nwk file.I want to parser the tree from that file.I found this python parser for newick trees. http://www.daimi.au.dk/~mailund/newick.html But i don't understand the usage properly.What i wanna do is if i have a file in the location c:\\files\\file1.nwk , then i wanna parse the trees in that file. Please help me if someone has experience on how to use this module. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From harish.shastry at gmail.com Tue Sep 16 09:32:53 2008 From: harish.shastry at gmail.com (Harish K Vishwanath) Date: Tue, 16 Sep 2008 19:02:53 +0530 Subject: Problem parsing the input In-Reply-To: References: Message-ID: <78f8019c0809160632u51b9fac8tcf4fe7892f76532c@mail.gmail.com> Consider the code below : x = """ ... ***** ... - Burst_Length not read from ini file ... ? - ... + BurstLength not read from ini file ... ***** ... - PilotTracking_Timing not read from ini file ... ? ^^^^^^^^^^^^^^ ... + NumTimings not read from ini file ... - Burst Position = 89511samples ... + Analysis Time (Iterations = 1) = 0.562249s ... + Rising Edge Time = 371683us ... - Rising Edge Time = 371682us ... """ >>> x '\n*****\n- Burst_Length not read from ini file\n? -\n+ BurstLength not read from ini file\n*****\n- PilotTracking_Timing not read from ini file\n? ^^^^^^^^^^^^^^\n+ NumTimings not read from ini file\n- Burst Position = 89511samples\n+ Analysis Time (Iterations = 1) = 0.562249s\n+ Rising Edge Time = 371683us\n- Rising Edge Time = 371682us\n' >>> import re *>>> num = re.compile('(?P[0-9]+)[^.]') >>> flt = re.compile('(?P[0-9]*\.[0-9]*)') *>>> flt.findall(x) ['0.562249'] >>> num.findall(x) ['89511', '1', '562249', '371683', '371682'] Those regular expressions can fetch the required input. On Tue, Sep 16, 2008 at 6:20 PM, wrote: > Hi, > I've a following input: > > ***** > - Burst_Length not read from ini file > ? - > + BurstLength not read from ini file > ***** > - PilotTracking_Timing not read from ini file > ? ^^^^^^^^^^^^^^ > + NumTimings not read from ini file > ***** > - Analysis Time (Iterations = 1) = 0.519444s > ? ^ --- > + Analysis Time (Iterations = 1) = 0.562249s > ***** > - Burst Position = 89511samples > ? ^ > + Burst Position = 89510samples > ***** > - Rising Edge Time = 371682us > ? ^ > + Rising Edge Time = 371683us > ***** > > How can I find the the colored items from the input. I though of using RE > but don't know much about it. > > The colored item can be dot notation e.g. 0.05678 or a whole digit as 5678 > > Please help > > > > -- > Regrads, > Rajat > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards, Harish -------------- next part -------------- An HTML attachment was scrubbed... URL: From uomiocenekidd at gmail.com Mon Sep 22 06:39:10 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:39:10 -0700 (PDT) Subject: download redtube video - Free Message-ID: download redtube video . . . *******CLICK HERE******** http://vids365.cn/download-redtube-video ***************************** . . . . . . . . . . . . download redtube video From lists at cheimes.de Tue Sep 30 14:10:53 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 30 Sep 2008 20:10:53 +0200 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <402462d4-e2a6-493b-9bc9-52aab68cad96@y71g2000hsa.googlegroups.com> References: <402462d4-e2a6-493b-9bc9-52aab68cad96@y71g2000hsa.googlegroups.com> Message-ID: giltay at gmail.com wrote: > I would add the following line right before your call to os.system: > > os.chdir(r'C:\myprogramfolder\run') I wouldn't. os.chdir() tends to introduce all sorts of trouble. It's a quick n'dirty hack for a small script but no solution for a large program or library. Christian From half.italian at gmail.com Wed Sep 10 17:21:11 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 10 Sep 2008 14:21:11 -0700 (PDT) Subject: formating a filesystem with python References: Message-ID: On Sep 10, 1:57?pm, "Ricardo Tiago" wrote: > Hi all, > > is there a package in python that allows to mount/umount and format > (to ext3) a filesystem? I know that this is possible by just calling > the os commands 'mount/umount and mkfs' but this would imply to have > to change sudoers to run the script as non-root. > > Thanks > Ric You can use pexpect to become root without changing sudoers. Assuming you know the root password... ~Sean From gagsl-py2 at yahoo.com.ar Tue Sep 30 03:15:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 04:15:45 -0300 Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <66606235-be55-458a-9e14-09e6c766201d@p31g2000prf.googlegroups.com> Message-ID: En Sun, 28 Sep 2008 07:01:12 -0300, Olivier Lauzanne escribi?: > On Sep 28, 11:21 am, est wrote: >> Can anyone tell me how to customize a default encoding, let's say >> 'ansi' which handles range(256) ? > > I assume you are using python2.5 > Edit the file /usr/lib/python2.5/site.py > > There is a method called > def setencoding(): > [...] > encoding = "ascii" > [...] > > Change "encoding = "ascii" to encoding = "utf-8" > > On windows you may have to use "mbsc" or something like that. I have > no idea what windows use at its encoding. *Not* a good idea at all. You're just masking errors, and making your programs incompatible with all other Pythons installed around the world. -- Gabriel Genellina From clp at rebertia.com Mon Sep 15 14:30:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Sep 2008 11:30:06 -0700 Subject: Converting .py files to batch files. In-Reply-To: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> Message-ID: <47c890dc0809151130p7e9b1e1fv3d335bc26fc7a630@mail.gmail.com> On Mon, Sep 15, 2008 at 10:30 AM, aditya shukla wrote: > How can we convert .py files to batch files? is there any library for this? Unless your Python scripts are essentially just *really basic* shell scripts that happen to be written in Python, then no, it's not even possible, much less automated. Python and batch files are just too vastly different: Python is a general-purpose programming language with a large standard library; batch files are a castrated version of bash. Perhaps if you could explain why you would want to do this in the first place, someone could suggest an alternative. Regards, Chris > > > Aditya > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From news1234 at free.fr Sat Sep 13 05:29:22 2008 From: news1234 at free.fr (nntpman68) Date: Sat, 13 Sep 2008 11:29:22 +0200 Subject: SSH using PEXPECT In-Reply-To: <4cc538ef-3b08-404c-b107-ff6605c307a2@t54g2000hsg.googlegroups.com> References: <4cc538ef-3b08-404c-b107-ff6605c307a2@t54g2000hsg.googlegroups.com> Message-ID: <48cb87f0$0$6999$426a74cc@news.free.fr> Hi, yellowblueyellow at gmail.com wrote: > On Sep 10, 7:01 pm, Sean DiZazzo wrote: > I am using windows and for reason it wont let me use pexpect even tho > I have CYGWIN installed > > > I get the following error > > Traceback (most recent call last): > File "new.py", line 1, in > import ssh_session > File "C:\Python25\lib\ssh_session.py", line 7, in > from pexpect import * > File "C:\Python25\lib\site-packages\pexpect.py", line 85, in > > support it. Pexpect is intended for UNIX-like operating > systems.""") > ImportError: No module named resource > You might have cygwin installed, but the error mesage sems to indicatem that you don't use cygwin's pythonm but the normal windows python, You see, that it complains about pexpcet in C:\Python25\lib\site-packages\pexpect.py just open a cygwin window: then cd to the directory containign your script and type python new.py. you should have at least another error message bye N From roy at panix.com Sun Sep 14 15:38:41 2008 From: roy at panix.com (Roy Smith) Date: Sun, 14 Sep 2008 15:38:41 -0400 Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <64670149-9467-4ca7-9d7e-c330c1b403e4@c58g2000hsc.googlegroups.com> Message-ID: In article <64670149-9467-4ca7-9d7e-c330c1b403e4 at c58g2000hsc.googlegroups.com>, "Aaron \"Castironpi\" Brady" wrote: > However, from what I understand (brass player), If you play the trombone, you might want your Note class to allow floating-point values for pitch :-) From asdfasdfasdfasdfasdf at arcor.de Sat Sep 6 18:00:07 2008 From: asdfasdfasdfasdfasdf at arcor.de (Andreas Hofmann) Date: Sun, 07 Sep 2008 00:00:07 +0200 Subject: String/Number Conversion In-Reply-To: <6de9141c-f350-4dfa-a36b-46e45344776a@q5g2000prf.googlegroups.com> References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> <6de9141c-f350-4dfa-a36b-46e45344776a@q5g2000prf.googlegroups.com> Message-ID: <48c2fd67$0$20941$9b4e6d93@newsspool2.arcor-online.net> Thanks a lot, I got it working now. Thanks also to the other guys, your numerous hints were really valuable! Kind regards, Andy John Machin schrieb: > On Sep 7, 7:04 am, Andreas Hofmann > wrote: >> Hello Folks! >> >> I've got a little problem here, which which really creeps me out at the >> moment. >> I've got some strings, which only contain numbers plus eventually one >> character as si-postfix (k for kilo, m for mega, g for giga). I'm trying >> to convert those strings to integers, with this function: >> >> def eliminate_postfix(value): >> if type(value) is str: > > Don't use "is" unless you are really sure that "==" won't do the job. > Better idiom: > if isinstance(value, str): > >> value.upper() > > This causes your "mult is always 1" problem. You need: > value = value.upper() > Why? Because strings are immutable. String methods like upper return a > new string, they don't change the existing string. > >> if value.endswith('K'): >> mult = 1000 >> elif value.endswith('M'): >> mult = 1000000 >> elif value.endswith('G'): >> mult = 1000000000 >> else: >> mult = 1 >> >> if mult is 1: > > Lose "is". In fact, lose the whole "if" statement. See below. > >> value = string.atoi(value) > > Don't use deprecated functions from the string module. Use the built- > in float function to convert from text. > >> else: >> value = string.atoi(value[:-1]) * mult >> return value > > Those last few statements look somewhat tortuous. Try this: > else: # mult would be 1, but we don't need it > return float(value) > return float(value[:-1]) * mult > > HTH, > John From adityashukla1983 at gmail.com Wed Sep 10 20:39:53 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Wed, 10 Sep 2008 19:39:53 -0500 Subject: Working with environment variables. Message-ID: <73045cca0809101739m560d382bi8ba506022f600286@mail.gmail.com> Hello folks, i am working with Python-2.5.2, fedora 9 sulphur I wanna change the value of environment variable , so if i open bash and type envvariable=value;export variable then this sets the envvariable equal to the value.Now i am writing a python script to set the value of this environment variable. import optparse import os def new_callback(option, opt_str, value, parser): os.putenv("envvariable",value) if __name__ == '__main__': p = optparse.OptionParser() p.add_option('-H',action="callback",callback=new_callback,type ="string") options, remainder = p.parse_args() when i run the script python prog.h -H value now this dosen't change the value of the variable which was set earlier .Please help me in fixing this issue. Thanks in advance Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Tue Sep 16 08:22:19 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 14:22:19 +0200 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <1221564169.16690.0@proxy00.news.clara.net> Message-ID: <871vzk701w.fsf@mulj.homelinux.net> Armin writes: > What's the value of 1.add(b)? None? Or 3 ?? > (if add works in the same way as append) That's exactly the point -- __add__ doesn't work as append. append is a "destructive" operation, that mutates an existing object, whereas __add__ returns a different object to be used as the "result" of the addition. This is why append doesn't need to return anything, while __add__ must return the new object. The distinction is even more apparent with sort and sorted, which are destructive and non-destructive aspects of the same operation: >>> a = [3, 2, 1] >>> a.sort() # destructive (mutates object), so no return value >>> a [1, 2, 3] >>> a = [3, 2, 1] >>> b = sorted(a) # non-destructive (sorts a copy), returns the sorted copy >>> a [3, 2, 1] >>> b [1, 2, 3] From fredrik at pythonware.com Fri Sep 5 04:59:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 10:59:52 +0200 Subject: atomic section in code In-Reply-To: References: Message-ID: Ahmad Humayun wrote: > I need to create an atomic section in Python code i.e. there is no > context switch to any other thread during the running of that piece of > code. Would would do the trick? use a lock, and make sure that anyone that needs access to the shared state you're manipulating in that section uses the same lock. lock = threading.Lock() # or RLock() etc [1] with lock: section this only works if everyone honors the lock, of course; there's no way in Python to lock out non-cooperating external threads. 1) see http://effbot.org/zone/thread-synchronization.htm From mail at timgolden.me.uk Thu Sep 25 04:36:35 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 25 Sep 2008 09:36:35 +0100 Subject: Connecting to SMB share in python In-Reply-To: References: Message-ID: <48DB4D93.4040606@timgolden.me.uk> Ronnie Kwok wrote: > Hello, > > I am trying to write a script that copy files from my local machine to a samba > share. Can't you just mount the share (albeit temporarily) and copy the files over in the normal way? You haven't said what OS you're on, but I'm assuming Linux otherwise you'd simply be talking about a Windows share and copying to a UNC. TJG From bignose+hates-spam at benfinney.id.au Sun Sep 14 18:41:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 08:41:22 +1000 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> Message-ID: <87abea73l9.fsf@benfinney.id.au> Astley Le Jasper writes: > Is it best to have it all in one script or split it into per site > scripts that can then be called by a manager script? If everything > is in one script would you have per site functions to extract the > data or generic function that contain vary slightly depending on the > site, for example > > import firstSiteScript > import secondSiteScript First: each of these things you're importing is a "module" in Python. A script is what I prefer, for clarity, to call a "program": it's intended to be executed independently as the top level of execution. Second: please do yourself a favour and drop the camelCaseNames. Follow PEP 8 for style and naming in your Python code. > firstsitedata = firstSiteScript.getData('search_str) > secondsitedata = secondSiteScript.getData('search_str) > etc etc I'm presuming that there will be large areas of common functionality between these different sites. On that basis, it's prbably best to treat the differences as differences of *configuration* where possible, instead of having separate modules for the entire site. You might like to look at a web framework which gathers much of this functionality together for you, and provides flexible ways to define different sites in terms of those common elements . -- \ ?Following fashion and the status quo is easy. Thinking about | `\ your users' lives and creating something practical is much | _o__) harder.? ?Ryan Singer, 2008-07-09 | Ben Finney From steve at REMOVE-THIS-cybersource.com.au Mon Sep 15 19:03:59 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Sep 2008 23:03:59 GMT Subject: append on lists References: Message-ID: <00dee3f7$0$20331$c3e8da3@news.astraweb.com> On Mon, 15 Sep 2008 13:47:53 -0700, Chris Rebert wrote: > The code you'd actually want is: > > d = a[:] #copy a > d.append(7) > > Or if you're willing to overlook the inefficiency: > > d = a + [7] > > But that's not idiomatic. Why is a + [7] more inefficient than manually copying the list and appending to the copy? Surely both pieces of code end up doing the same thing? In fact, I'd guess that the second is likely to be marginally more efficient than the first: >>> x = compile('d = a[:]; d.append(7)', '', 'exec') >>> dis.dis(x) 1 0 LOAD_NAME 0 (a) 3 SLICE+0 4 STORE_NAME 1 (d) 7 LOAD_NAME 1 (d) 10 LOAD_ATTR 2 (append) 13 LOAD_CONST 0 (7) 16 CALL_FUNCTION 1 19 POP_TOP 20 LOAD_CONST 1 (None) 23 RETURN_VALUE >>> x = compile('d = a + [7]', '', 'exec') >>> dis.dis(x) 1 0 LOAD_NAME 0 (a) 3 LOAD_CONST 0 (7) 6 BUILD_LIST 1 9 BINARY_ADD 10 STORE_NAME 1 (d) 13 LOAD_CONST 1 (None) 16 RETURN_VALUE timeit agrees with me: >>> from timeit import Timer >>> t1 = Timer('d = a[:]; d.append(7)', 'a = []') >>> t2 = Timer('d = a + [7]', 'a = []') >>> t1.repeat(number=1000) [0.0015339851379394531, 0.0014910697937011719, 0.0014841556549072266] >>> t2.repeat(number=1000) [0.0011889934539794922, 0.0013048648834228516, 0.0013070106506347656] -- Steven From wuwei23 at gmail.com Fri Sep 26 21:06:59 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 26 Sep 2008 18:06:59 -0700 (PDT) Subject: lxml question References: <2f9ef7d5-616e-4a4b-9a83-e23194fee3a9@m3g2000hsc.googlegroups.com> Message-ID: <6e99bb12-2838-4095-b76e-2514530936d7@n38g2000prl.googlegroups.com> On Sep 27, 1:19?am, Uwe Schmitt wrote: > I have to parse some text which pretends to be XML. lxml does not want > to parse it, because it lacks a root element. Another option is BeautifulSoup, which handles badly formed XML really well: http://www.crummy.com/software/BeautifulSoup/ From grante at visi.com Fri Sep 26 23:11:56 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 26 Sep 2008 22:11:56 -0500 Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> Message-ID: <4p-dnSA-j8LhOUDVnZ2dnUVZ_tCdnZ2d@posted.usinternet> On 2008-09-27, George Sakkis wrote: > On Sep 26, 9:30?pm, Grant Edwards wrote: > >> On 2008-09-26, nntpman68 wrote: >> >> > Hm, >> >> > I guess you just filter mailing lists and can do nothing about the >> > newsgroup if I'm fetching via the nntp server of my ISP itself, right? >> >> I read the group via NNTP, and I find that blocking all >> articles posted from google.groups gets rid of all of the spam. > > ... along with a far from trivial (I guess) percentage of > non-spam, such as this post. Yup. Some non-spam gets filtered out as well. IMO, it's worth it. -- Grant From lists at cheimes.de Mon Sep 1 06:21:22 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 01 Sep 2008 12:21:22 +0200 Subject: Processes in Linux from Python In-Reply-To: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> References: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> Message-ID: Johny wrote: > Is it possible to get a number of the http processes running on Linux > directly from Python ? The Python core has no direct API for the job. However you can use the virtual /proc/ file system for the job. Or check out my enumprocess package. http://pypi.python.org/pypi?:action=display&name=enumprocess&version=0.1 It's far from perfect but it should do the job on Linux. Christian From kaerbuhez at gmail.com Sat Sep 6 16:27:46 2008 From: kaerbuhez at gmail.com (kaer) Date: Sat, 6 Sep 2008 13:27:46 -0700 (PDT) Subject: running python as a dameon References: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> <6e7ead25-baf1-400a-a52f-568f37351aab@8g2000hse.googlegroups.com> <5c74118c-a576-4a51-ae9a-95d34273a99a@s50g2000hsb.googlegroups.com> Message-ID: On 6 sep, 22:16, kaer wrote: > On 6 sep, 15:44, Michael Palmer wrote: > > > > > On Sep 5, 9:56 pm, Sean Davis wrote: > > > > > What I want > > > > to do is to provide the python NLP program as a service to any other > > > > PHP/Java/Ruby process request. So the mapping is > > > > > http -> apache -> PHP/Java/Ruby/... -> Python NLP > > > > Why not use a simple CGI script or wsgi application? You could make > > > the service online and interactive and with the same application and > > > code make an XMLRPC web service. So, things would look more like: > > > > http -> apache -> Python (running NLP and serving requests) > > > > You can use apache to proxy requests to any one of a dozen or so > > > python-based webservers. You could also use mod_wsgi to interface > > > with a wsgi application. > > > > Sean > > > xmlrpc is the right idea, as it interfaces easily across languages. > > I just daemonize some utility script these week. For that I took one > of the scripts in the ASPN python cookbook : google those 3 words then > search python and you will find out your solution faster than I end up > this mail. It worked like a charm on my linux box. > BTW, I wouldn't complicate with xml stuffs if you don't need it. > > Good luck. you obviously "search daemon" not "search python". Her is the link: http://www.google.com/search?q=daemon&hl=en&ie=UTF-8&btnG=Google%2BSearch&qdr=all&occt=any&dt=i&sitesearch=code.activestate.com From enleverlesX.XmcX at XmclaveauX.com Mon Sep 15 14:24:18 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Mon, 15 Sep 2008 20:24:18 +0200 Subject: objet COM et ms Word In-Reply-To: <245dc065-660f-4dfe-8134-14b4acfc1f2d@j22g2000hsf.googlegroups.com> References: <245dc065-660f-4dfe-8134-14b4acfc1f2d@j22g2000hsf.googlegroups.com> Message-ID: <48ceaba5$0$946$ba4acef3@news.orange.fr> Bonsoir ! J'ai r?pondu, dans le newsgroup fran?ais. @-salutations -- Michel Claveau From gabriel.rossetti at arimaz.com Tue Sep 23 06:01:40 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Tue, 23 Sep 2008 12:01:40 +0200 Subject: python freeze help Message-ID: <48D8BE84.5020204@arimaz.com> Hello everyone, I'm trying to use python's freeze utility but I'm running into problems. I called it like this : python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py ~/Documents/Code/Python/src/jester/service.py -m jester then I did : make then I tried to run it : ./service and I get this : grossetti at desktop-01:~/tmp/freeze$ ./service Traceback (most recent call last): File "/home/grossetti/Documents/Code/Python/src/jester/service.py", line 16, in from jester import constants, utils File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line 20, in from twisted.internet.protocol import Protocol, ClientCreator File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", line 17, in from zope.interface import implements File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in pkg_resources.declare_namespace('zope') File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, in declare_namespace _handle_ns(packageName, path_item) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, in _handle_ns path = module.__path__; path.append(subpath) AttributeError: 'str' object has no attribute 'append' Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in from apport.report import Report File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in from problem_report import ProblemReport File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in from email.MIMEMultipart import MIMEMultipart File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__ __import__(self.__name__) ImportError: No module named multipart Original exception was: Traceback (most recent call last): File "/home/grossetti/Documents/Code/Python/src/jester/service.py", line 16, in from jester import constants, utils File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line 20, in from twisted.internet.protocol import Protocol, ClientCreator File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", line 17, in from zope.interface import implements File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in pkg_resources.declare_namespace('zope') File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, in declare_namespace _handle_ns(packageName, path_item) File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, in _handle_ns path = module.__path__; path.append(subpath) AttributeError: 'str' object has no attribute 'append' Does anyone have any ideas as of why I get this? Thank you, Gabriel From george at george-net.de Mon Sep 15 15:37:50 2008 From: george at george-net.de (Georg Altmann) Date: Mon, 15 Sep 2008 21:37:50 +0200 Subject: MVC with Python Message-ID: Hello, I need some advice on how to implement model-view-controller. I am trying to develop a GUI application with PyQt, yet the problem rather applies to mvc in general, not just GUI applications. Let's say the data is a list of objects with a common base class. The views are either a graphical representation of the objects or some form of textual input. The views shall change the model by using command objects (for undo, e.g. QUndoCommand). My current approach is to implement the model as a class with a list-like interface, with methods insert(), remove(), __getitem__(), __setitem__(),... and a signal to notify the views. The objects in the list have methods to change their state as well. My problem is, how do the commands interact with the model? Let's say I have a command that modifies an object o in the list. 1) If list[key_to_o] returns a reference to the object, the command can modify the object by using this reference, i.e. list[key_to_o].setX(). So there is no way for the list to know when the object changed - how can it emit a singal then? 2) If list[key_to_o] returns a deep copy of the object, copy_of_o = list[key_to_o], the command mofifies the copy and the updates the list: list[key_to_o] = copy_of_o. Now the list can emit a signal in __setitem__(). While this may work, it seems awkward to copy around objects just to perform a possibly simple operation on them. Additionally it might not be feasible once objects get complex. 3) The interface of the classes of the objects could be reflected in the list class, i.e. list.set_x_on_obj(key_to_obj,x). This would probably make the list class interface very bloated. Of course the problem is not really limited to Python, my apologies if I'm totally off-topic here. Regards Georg From gagsl-py2 at yahoo.com.ar Thu Sep 11 20:23:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 11 Sep 2008 21:23:22 -0300 Subject: catching exceptions from fortran References: Message-ID: En Thu, 11 Sep 2008 10:43:08 -0300, john escribi?: > I wrapped some fortran code using F2PY and need to be able to catch > fortran runtime errors to run the following: > [reindented] > # "grid" is a wrapped fortran module > # no runtime errors incurred when run with the correct inputs for > filetype > #------------------------------- > def readGrid( self, coord='xyz' ): > mg = ( '.FALSE.', '.TRUE.' ) > form = ( 'FORMATTED', 'UNFORMATTED' ) > success = False > for m in mg: > for f in form: > try: > if coord == 'xyz': > self.grid.readxyz( self.filename, f, m ) > success = True > elif coord == 'xyrb': > self.grid.readxyrb( self.filename, f, m ) > success = True > else: > import sys > print 'gridtype "' + str(coord) + '" not supported. ' \ > + '' > except: > continue > if not success: > import sys > print 'gridfile "' + str(self.filename) + '" not read in any > recognized format' \ > + ' ' > #---------------------------- I suppose you want to stop trying other formats after a successful read; in that case put a break statement just below both success=True. If coord is unrecognized, the code above prints the same message 4 times. Instead of printing a message, in those cases usually an exception is raised, letting a higher layer handle the error. And using string interpolation is a lot easier than building the message in parts: raise ValueError('gridtype "%s" not supported. ' % coord) If you want to catch errors on the Fortran code *only*, the try/except should be more specific (both in scope and what it catches). The Exception class is the more generic exception that you should catch. > basically, what i want to happen is to try to run 'something' with the > wrapped fortran code and if that doesn't work (error encountered, > etc.) try something else. is there an easier way to go about doing > this? is there something i'm missing about catching exceptions here? I'd reorder the code in this way (untested, of course): def readGrid(self, coord='xyz'): def try_all_formats(read_function, filename): mg = ('.FALSE.', '.TRUE.') form = ('FORMATTED', 'UNFORMATTED') success = False for m in mg: for f in form: try: read_function(filename, f, m) success = True break except Exception, e: # this line only for debugging purposes print "error %r when using m=%r f=%r" % (e, m, f) continue if not success: raise ValueError('gridfile "%s" not read ' 'in any recognized format ' '' % filename) if coord == 'xyz': try_all_formats(self.grid.readxyz, self.filename) elif coord == 'xyrb': try_all_formats(self.grid.readxyrb, self.filename) else: raise ValueError('gridtype "%s" not supported. ' '' % coord) I don't know about F2PY but the values ('.FALSE.', '.TRUE.') seem suspicious. AFAIR, .FALSE. and .TRUE. are the Fortran spellings of False and True in Python - they're not strings, but boolean values. So maybe the right way is to use mg = (False, True) Your code above was catching and ignoring everything, even this error, if it happened. -- Gabriel Genellina From python.dev.9 at gmail.com Fri Sep 12 14:29:34 2008 From: python.dev.9 at gmail.com (python dev) Date: Fri, 12 Sep 2008 14:29:34 -0400 Subject: Getting Linux partition info programmatically Message-ID: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> Hello everyone, I am trying to get a list of all the partitions (along with their respective file system types) listed in the /media directory. Does anybody know if there is a way to do this using Python, or do I have to get this information by parsing the output of a Linux command? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From marco.bizzarri at gmail.com Mon Sep 1 09:10:41 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 1 Sep 2008 15:10:41 +0200 Subject: How to print first(national) char from unicode string encoded in utf-8? In-Reply-To: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> Message-ID: <3f0d61c40809010610y664b360ate6f3a8919e258583@mail.gmail.com> 2008/9/1 : > Hi, > > I have a problem with unicode string in Pylons templates(Mako). I will > print first char from my string encoded in UTF-8 and urllib.quote(), > for example string '?ukasz': > > ${urllib.unquote(c.user.firstName).encode('latin-1')[0:1]} > > and I received this information: > > : 'utf8' codec can't decode byte > 0xc5 in position 0: unexpected end of data > > When I change from [0:1] to [0:2] everything is ok. I think it is > because of unicode and encoding utf-8(2 bytes). > > How to resolve this problem? > > Best regards > -- > http://mail.python.org/mailman/listinfo/python-list > First: you're talking about utf8 encoding, but you've written latin1 encoding. Even though I do not know Mako templates, there should be no problem in your snippet of code, if encoding is latin1, at least for what I can understand. Do not assume utf8 is a two byte encoding; utf8 is a variable length encoding. Indeed, 'a' encoded as utf8 is 'a' (one byte) '?' encode as utf8 is '\xc3\xa0' (two bytes). Can you explain what you're trying to accomplish (rather than how you're tryin to accomplish it) ? Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From akineko at gmail.com Mon Sep 1 21:09:58 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 18:09:58 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Message-ID: On Sep 1, 5:52 pm, "Guilherme Polo" wrote: > Are you trying to simulate clicks ? You should be doing it using > event_generate, more below. > Actually, I was trying to implement a "sticky" button. (Button Release is done later by another event) I already tried event_generate. It worked as far as I didn't touch other widgets. But somehow it failed to work if event_generate is called after other widgets are activated. > You should expect them to be totally removed from Tkinter actually. Sad to hear that. Controlling the button behaviour explicitly may not be a common thing to do but it is still necessary thing to do. But you gave me enough insights. Aki- From wuwei23 at gmail.com Sun Sep 21 09:16:32 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 21 Sep 2008 06:16:32 -0700 (PDT) Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> Message-ID: <9f97f262-b90e-4bc1-9e9c-851bb962ce89@b30g2000prf.googlegroups.com> On Sep 21, 10:51?pm, Alex wrote: > Why? I'm coping data_set in ds so why data_set is changed? You're making a copy of the ds tuple, which has the -same- contents as the original. To create copies of the contents as well, try the deepcopy function from the copy module. As an aside, you're also trying to make a copy of ds for each iteration of the loop, which is unnecessary in this case. Here's a slightly better example of your code: >>> from copy import deepcopy >>> data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) >>> ds = deepcopy(data_set) >>> for i, data in enumerate(ds): ... if i == 1: data['param'] = "y" ... if i == 2: data['param'] = "x" ... >>> print data_set ({'param': 'a'}, {'param': 'b'}, {'param': 'c'}) >>> print ds ({'param': 'a'}, {'param': 'y'}, {'param': 'x'}) Although your use of a tuple full of dicts for data_set is kinda strange... Tuples are generally used when you want a structured data element, in which case you'd just address each element directly rather than iterate through it: >>> ds = deepcopy(data_set) >>> ds[1]['param'] = "y" >>> ds[2]['param'] = "x" From prologic at shortcircuit.net.au Wed Sep 10 17:52:44 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 07:52:44 +1000 Subject: Alternatives to traditional RDBMS In-Reply-To: References: <6iq90jFdeiU1@mid.uni-berlin.de> Message-ID: On Thu, Sep 11, 2008 at 3:40 AM, Daniel Fetchinson wrote: > There is also dejavu: http://www.aminus.net/dejavu This is an ORM. They are off-topic for this thread :) cheers James -- -- -- "Problems are solved by method" From grante at visi.com Tue Sep 16 09:49:48 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:49:48 -0500 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <87d4j4798g.fsf@mulj.homelinux.net> Message-ID: On 2008-09-16, Hrvoje Niksic wrote: > Duncan Booth writes: > >> The only relatively common use I can think of where you might want to call >> a method directly on a literal is to produce a list of strings while being >> lazy about the typing: > > By far the most common is probably 'sep'.join(iterable). It's also somewhat common to index into a literal: ['one','two','three'][n] {1:'one', 2:'two', 7:'seven'}[n] -- Grant Edwards grante Yow! I was born in a at Hostess Cupcake factory visi.com before the sexual revolution! From simon.peverett at gmail.com Thu Sep 4 06:20:11 2008 From: simon.peverett at gmail.com (Impotent Verse) Date: Thu, 4 Sep 2008 03:20:11 -0700 (PDT) Subject: Serial I/O problem with pywin32 ? References: <6i7p2uFp2lqbU1@mid.uni-berlin.de> Message-ID: On 3 Sep, 16:33, "Diez B. Roggisch" wrote: > Xavier schrieb: > > > > > Hi, > > > I try to access to a Bluetooth GPS data-logger with Python. I use > > pySerial. > > > Sending and receiving little messages (~100 char) works fine. However, > > when I ask the GPS to dump the trails, it returns some Mbytes and here > > is the problem : in the stream of bytes, I randomly losts chunks of > > ~100bytes. > > > I tried USPP and pyBlueZ instead of pySerial : same problem. > > > It doesn't like it is a bufferoverun bug from me because : > > ?- the GPS seems to wait when I do not read the stream, > > ?- there is never more than 200 inWainting() characters, > > ?- my code to test it is quite simple : > > > ? seriallink = serial.Serial("COM40") > > ? fileName = "data.dump" > > ? out = open(fileName, 'w') > > ? while 1: > > ? ? c = seriallink.read() > > ? ? out.write(" %0.2X" % ord(c)) > > ? ? print "*", > > ? out.close() > > > (with pyBluez : > > sock=BluetoothSocket( RFCOMM ) > > sock.connect(("00:0A:...", 1))) > > > I tried my program on two different PC with two Bluetooth dongle, > > (with pySerial, USPP, pyBluez). > > The same things are : > > ?- windows > > ?- the GPS (which works fine with the dumper program of the > > constructor) > > ?- pyWin32 > > > I've found another guy with a similar problem : > >http://www.generation-nt.com/reponses/rs232-entraide-142097.html > > He says: > > ?- no problem with little messages > > ?- lost of one byte every hour when receiving a lot of data > > > Any known problems with pywin32 and serial I/O when downloading a big > > stream of data ? > > ?From my experience with serial lines I'd say: that's the culprit. They > tend to be rather unreliable, as there is no real protocol ensuring data > integrity. > > You might consider downloading chunks of data if that's somehow > possible, and re-try failed chunks. > > Diez Could be hardware flow control. See this sometimes on the bluetooth connections that are using Serial Port Protocol and the hardware flow control hasn't been physically implemented. Do you lose data after exactly the same amount of data has been received? From justin.kuto at gmail.com Fri Sep 26 13:41:53 2008 From: justin.kuto at gmail.com (afrogazer) Date: Fri, 26 Sep 2008 10:41:53 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes Message-ID: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> I am creating a wind rose using a polar bar plot bu the points do not seem to align to the correct angles. Here is the sample code I am using. I can't seem to see anything in the API on how to set the angles. Any ideas anybody? Thanks. from pylab import * angles = arange(0,360,45) data = [18, 11, 11, 17, 39, 43, 25, 9] fig = figure(figsize=(8,8)) title('Wind Speed/Direction Frequency.', fontsize=13) ax = fig.add_subplot(111) fig.add_axes(([0.15,0.15,0.725,0.725]), polar=True) labels = arange(0,360,22.5) lines = arange(0,360,22.5) ax.axis('off') bar(angles, data, alpha=0.75, align='center', linewidth=0) show() From deets at nospam.web.de Fri Sep 5 12:45:01 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 18:45:01 +0200 Subject: Files application architecture In-Reply-To: References: Message-ID: <6id60eFq62kfU1@mid.uni-berlin.de> Benjamin Watine schrieb: > Hi, > > I'm about to develop a small python application and I wonder how to > organize files in this application. > I'm familar to java, so I'm tempted to use the same convention : 1 file > per class and 1 folders per package. > > I know that packages doesn't exists in python, they are modules instead. This is wrong. There are packages & modules in python. http://docs.python.org/tut/node8.html And please *don't* do put one class per module, as you would do in Java! Instead, group related classes into modules, breaking them up into several submodules if size or differences in usage suggest so. > May I create specific module for each "group of class" ? My application > follow the MVC paradigm, so basically, I've a package Model, a package > View, and a package Controller. > > So, what are best practices for organizing files and folders in a small > python project ? > I've found PEP8 (http://www.python.org/dev/peps/pep-0008/) that gives a > lot of good hints on coding convention, but nothing about files > organization. The MVC pattern is more important in terms of actual classes written, not so much regarding their distribution over a set of files. If you want, start with one big single module inside a application-naming package - or even no package at all. Split up if you need to. Or just go for /__init__.py /model.py /view.py /controller.py if you *must*. Diez From sdouche at gmail.com Sun Sep 21 18:13:19 2008 From: sdouche at gmail.com (Sebastien Douche) Date: Mon, 22 Sep 2008 00:13:19 +0200 Subject: report a BUG of package setuptools-0.6c8. In-Reply-To: References: <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> <5e1183fa0809210246q46f864eic359964a0cb0d46e@mail.gmail.com> Message-ID: <5e1183fa0809211513v4ad5ec1amb139324ba1cc8538@mail.gmail.com> On Sun, Sep 21, 2008 at 19:56, Gabriel Genellina wrote: >> http://bugs.python.org/setuptools/ > > And how do people manage to know that? Bugtracker send emails on setuptools mailing list. -- Seb From gagsl-py2 at yahoo.com.ar Tue Sep 30 03:32:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 04:32:21 -0300 Subject: Using the 'with' statement with cStringIO objects References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> <1222522300.659080@athprx04> <87zllt7h72.fsf@mulj.homelinux.net> Message-ID: En Sat, 27 Sep 2008 19:28:49 -0300, peppergrower escribi?: > When I got that particular > error, I suspected that it had something to do with the relative > newness of the 'with' statement. > > If this is something that should be considered for addition in the > future, is there somewhere specific I should suggest that? Yes: http://bugs.python.org/ (setting type="feature request", I think) -- Gabriel Genellina From marco.bizzarri at gmail.com Thu Sep 4 06:25:42 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 12:25:42 +0200 Subject: Coming from .NET and VB and C In-Reply-To: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> Message-ID: <3f0d61c40809040325g17fb7faayc31f5ca170898d88@mail.gmail.com> On Thu, Sep 4, 2008 at 12:16 AM, Dennis Lee Bieber wrote: > On Wed, 3 Sep 2008 09:52:06 -0700 (PDT), ToPostMustJoinGroup22 > declaimed the following in > comp.lang.python: > >> have no preference with MySQL or SQL, stored procedures or ad-hoc >> queries. >> > Please note: MySQL is specific relational database management system > (RDBMs), which uses a dialect of structured query language (SQL). SQL by > itself is just a semi-standardized query language -- and can technically > be used to access non-relational DBMS (if any such are still in use), > though the query processor would be a pain to program (map a relational > join into a hierarchical DBMS schema? ugh). > >> SO, I'm interested in using my Google App space (free 500MB) to >> develop a quick database application. Using Python. I found "Dive >> Into Python" which I will be reading shortly. >> > So one question: what RDBMs are supported in that space? The appearance is not an RDBMS, at least, maybe it is, but under the surface. Looks more that you've persistent objects with a SQL-like language to query them. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From castironpi at gmail.com Sun Sep 28 20:32:56 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 17:32:56 -0700 (PDT) Subject: Odd Errors References: <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> Message-ID: <1b1ed34d-f386-4389-a7f1-ce68be4e2a14@k30g2000hse.googlegroups.com> On Sep 28, 7:13?pm, alex23 wrote: > The problem is with this: > > > ? ? ? ? lines = lines.append(inLine) > > The append method of a list modifies the list in-place, it doesn't > return a copy of the list with the new element appended. In fact, it > returns None, which it then attaches the label 'lines' to, so the next > iteration through it tries to call None.append... > > Replace the line with: > > ? ? lines.append(inLine) Do you ever want to scream from the rooftops, "'append' operates by side-effect!"? From rstarkov at gmail.com Sun Sep 14 08:30:21 2008 From: rstarkov at gmail.com (rs387) Date: Sun, 14 Sep 2008 05:30:21 -0700 (PDT) Subject: How to emit Cyrillic and Chinese via unicode from console mode? References: <543bde0c-4d99-4d79-a4dd-b6f8d85e8c48@l64g2000hse.googlegroups.com> <2vqpc4pd7qfrsgsove5f5prncbglhjast0@4ax.com> Message-ID: <561d1d87-4285-44ce-85be-2431e47cff05@m36g2000hse.googlegroups.com> On Sep 14, 11:51?am, Gertjan Klein wrote: > Interesting. On my system (Windows XP) the console codepage does not > change, and hence the characters don't print properly (I get some of the > CP437 line drawing characters, for example). I have never been able to > convince windows to assume/support UTF-8 encoding in the console, > programatically or otherwise. :( I found that a useful test is to create a directory whose name contains chars from various languages, then run "cmd" and see if "dir" displays them correctly. This worked fine for me in WinXP, even though my system locale is Russian. Would be interesting to know if you can get the console to display international chars this way. From linkmaster032000 at gmail.com Tue Sep 23 16:50:28 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Tue, 23 Sep 2008 13:50:28 -0700 (PDT) Subject: curses.setsyx()? References: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> <713190fc-e3a9-4a72-8bee-4fd3affcb531@c58g2000hsc.googlegroups.com> Message-ID: On Sep 23, 4:16?pm, brad.at.sch... at gmail.com wrote: > On Sep 22, 11:24?pm, Tim Roberts wrote: > > > > > linkmaster032... at gmail.com wrote: > > >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: > > >> On Sep 19, 1:24?am, Tim Roberts wrote: > > > >> > linkmaster032... at gmail.com wrote: > > > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > > >> > >cursor. Any alternatives/solutions? > > > >> > Did you call doupdate after? ?setsyx just manipulates the data structures. > > >> > It takes a call to doupdate to force those changes to take effect visually. > > >> > -- > > >> > Tim Roberts, t... at probo.com > > >> > Providenza & Boekelheide, Inc. > > > >> I added it and it still doesn't work. This is what I'm doing when I > > >> want to display the cursor and prepare it for input at 2,3: > > > >> curses.echo() > > >> curses.curs_set(1) > > >> curses.setsyx(2,3) > > >> curses.doupdate() > > > >Any idea what's wrong? > > > No. ?Are you able to post an entire sample that demonstrates the problem? > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > http://pastebin.com/m6413db1 > > Run that and press 'n' key. It is supposed to move the cursor to 2,3 > and it doesn't. Sorry that was me, forgot to switch emails. But yes that is it. Remove the line about ppm/settings.conf if you don't want to create it because it will throw an exception. From chardish at gmail.com Thu Sep 25 11:12:13 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Thu, 25 Sep 2008 08:12:13 -0700 (PDT) Subject: "which python" as a python command? Message-ID: Hello, I'm trying to find out in a script where the location of the current python is. (I'm writing an installer script in python for a simple server application, so i'm going to do a find-replace in a bunch of files to give them the absolute path of the python binary. One thought might be to use the subprocess module, run "which python" as a subprocess, and then peek at stdout, but that seems way too complicated. Is there a simple solution for this in just a few lines of code? Cheers, Evan From ewertman at gmail.com Mon Sep 8 12:03:48 2008 From: ewertman at gmail.com (Eric Wertman) Date: Mon, 8 Sep 2008 12:03:48 -0400 Subject: lacking follow-through In-Reply-To: References: Message-ID: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> > Perhaps the wrong idea of what the group is. I would have thought > that > if one had a sufficiently developed idea and wanted to have it / > formally/ > rejected, rather than merely sniped at, then writting a PEP would be > more > apposite than posting to c.l.py. > > It's fine to post your not sufficiently developed ideas here merely > to > have them discussed. But I don't know what makes you feel that you, > or > your ideas, are /entitled/ to any response at all, much less > "follow-through." To expand on this a little bit, I've been subscribed to this group for a couple of months, but there seems to be a bit more gray area between what would go to a 'python-dev' group and a 'python-user' group. Long debates about language features and abstract ideas would appeal to the former, but not the latter. Certainly I fall into the user category.. I'm pretty happy with python, and generally just adjust to it's design and features, rather than spend lots of time on whether they are 'right' or could be 'better'. /shrug From gandalf at shopzeus.com Wed Sep 3 15:18:15 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 03 Sep 2008 21:18:15 +0200 Subject: max(), sum(), next() In-Reply-To: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <48BEE2F7.5010106@shopzeus.com> bearophileHUGS at lycos.com wrote: > Empty Python lists [] don't know the type of the items it will > contain, so this sounds strange: > > >>>> sum([]) >>>> > 0 > > Because that [] may be an empty sequence of someobject: > You are right in that sum could be used to sum arbitrary objects. However, in 99.99% of the cases, you will be summing numerical values. When adding real numbers, the neutral element is zero. ( X + 0 = X) It is very logical to return zero for empty sequences. Same way, if we would have a prod() function, it should return one for empty sequences because X*1 = X. The neutral element for this operation is one. Of course this is not good for summing other types of objects. But how clumsy would it be to use sum( L +[0] ) or if L: value = sum(L) else: value = 0 instead of sum(L). Once again, this is what sum() is used for in most cases, so this behavior is the "expected" one. Another argument to convince you: the sum() function in SQL for empty row sets returns zero in most relational databases. But of course it could have been implemented in a different way... I believe that there have been excessive discussions about this decision, and the current implementation is very good, if not the best. Best, Laszlo From stefan_ml at behnel.de Sun Sep 7 01:56:17 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 07 Sep 2008 07:56:17 +0200 Subject: delete an HTML tag while keeping its content In-Reply-To: References: Message-ID: <48c36d01$0$7475$9b4e6d93@newsspool4.arcor-online.net> [fixing the subject appropriately] Jackie Wang wrote: > How should I delete the 'font' tags while keeping the content inside? Amongst many other goodies for working with HTML, the Elements in lxml.html have a ".drop_tag()" method specifically for that purpose. http://codespeak.net/lxml/ Stefan From support.desk.ipg at gmail.com Mon Sep 22 12:37:46 2008 From: support.desk.ipg at gmail.com (Support Desk) Date: Mon, 22 Sep 2008 11:37:46 -0500 Subject: Regex Help In-Reply-To: References: Message-ID: Anybody know of a good regex to parse html links from html code? The one I am currently using seems to be cutting off the last letter of some links, and returning links like http://somesite.co or http://somesite.ph the code I am using is regex = r'' page_text = urllib.urlopen('http://somesite.com') page_text = page_text.read() links = re.findall(regex, text, re.IGNORECASE) From mail at timgolden.me.uk Mon Sep 29 07:36:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 29 Sep 2008 12:36:43 +0100 Subject: cups.Connection.printFile In-Reply-To: References: Message-ID: <48E0BDCB.10405@timgolden.me.uk> Antoon Pardon wrote: > On 2008-09-26, Mike Driscoll wrote: >> On Sep 19, 9:01 am, Antoon Pardon wrote: >>> On 2008-09-16, Graham Jenkins wrote: >>> >>> >>> >>>> I'm trying to print a file from within a Python program. >>>> The quick-and-dirty solution is to use something like: >>>> fd = os.popen("lp -d MyPrinter", "wb") >>>> fd.write(MyFileContents) >>>> But it seems to me that there should be a clean solution like: >>>> import cups >>>> stat = >>>> cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") >>> What about systems that don't use cups for printing? >>> >>> -- >>> Antoon Pardon >> For Windows, there's a few different ways to print. Tim Golden has a >> list on his website: >> >> http://timgolden.me.uk/python/win32_how_do_i/print.html > > I have a linux system that doesn't use cups for printing. > So his "clean" solution won't work on my box. Unless > of course his cups.Connection.printFile is just a wrapper > around os.popen("lp -d MyPrinter", "wb") or something > similar. Well I certainly don't pretend to offer any solutions on my "Win32 How do I?" pages except for how to do things on Win32 ;) . TJG From kyosohma at gmail.com Fri Sep 12 16:20:11 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 12 Sep 2008 13:20:11 -0700 (PDT) Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: <7b717a23-28b8-4dcd-ae89-3042f7e50a98@l43g2000hsh.googlegroups.com> On Sep 12, 1:33?pm, ady... at panix.com (Al Dykes) wrote: > In article <1bs69ogq6nspt.136i7kvcux142$.... at 40tude.net>, > Alan Franzoni ? wrote: > > >zamil was kind enough to say: > > >[cut] > > >If your needs are very basic, you can stick with the tk module that comes > >with python. It's not really feature-packed, but it's maintained and pretty > >cross-platform. > > OK, what are my choices for an IDE/GUI development tool that runs on XP? > > Thanks > > -- > Al Dykes > ?News is something someone wants to suppress, everything else is advertising. > ? ? - Lord Northcliffe, publisher of the Daily Mail Here's a few: WingWare: http://www.wingware.com/ SPE: http://pythonide.blogspot.com/ Eclipse + Python plugin = EasyEclipse (PyDev): http://easyeclipse.org/site/distributions/python.html Or you could use Google and you would have found this: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Mike From emile at fenx.com Mon Sep 8 15:41:53 2008 From: emile at fenx.com (Emile van Sebille) Date: Mon, 08 Sep 2008 12:41:53 -0700 Subject: Problems downloading and installing win32api In-Reply-To: <968dca58-0172-4953-b8d6-9610f0570fe8@s20g2000prd.googlegroups.com> References: <968dca58-0172-4953-b8d6-9610f0570fe8@s20g2000prd.googlegroups.com> Message-ID: brianrpsgt1 wrote: > I have attempted downloading and installing several different version > of the win32api from Source Forge, Whe win32 tools come bundled with ActiveState's python distribution. Maybe that'll move you forward... Emile however, each time I try to install > I get the following error message: > > "Only part of a ReadProcessMemory or WriteProcessMemory request was > completed" > > This occurred with the following files: > pywin32-212.win32-py2.4.exe > pywin32-212.win32-py2.5.exe > pywin32-212.win32-py2.6.exe > > I am using WinXP SP2. Any assistance on getting this downloaded and > installed would be great. > > Thanks > > B > -- > http://mail.python.org/mailman/listinfo/python-list > From joncle at googlemail.com Tue Sep 2 09:29:57 2008 From: joncle at googlemail.com (Jon Clements) Date: Tue, 2 Sep 2008 06:29:57 -0700 (PDT) Subject: Algorithm used by difflib.get_close_match References: <83c600d0-6852-4dd6-9287-34f9b3264090@s50g2000hsb.googlegroups.com> Message-ID: On Sep 2, 2:17?pm, Guillermo wrote: > Hi all, > > Does anyone know whether this function uses edit distance? If not, > which algorithm is it using? > > Regards, > > Guillermo help(difflib.get_close_matches) will give you your first clue... From ebgssth at gmail.com Thu Sep 25 11:41:49 2008 From: ebgssth at gmail.com (js) Date: Fri, 26 Sep 2008 00:41:49 +0900 Subject: How can I customize builtin module search path to prefix/lib to prefix/lib64? Message-ID: Hi list, Is it possible to change module search path (PYTHONPATH) built-in to Python interpreter? I thought I can change it with configure --libdir but it didn't work for me. I also tried patching around python source tree replacing lib to lib64 but it didn't work either. Adjusting sys.path directly or using environ should do the trick but I'd rather want to make it the default path for my python Thanks, From fredrik at pythonware.com Sun Sep 21 11:04:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 17:04:57 +0200 Subject: How to kill threading.Thread instance? In-Reply-To: <6jn4itF442e7U1@mid.uni-berlin.de> References: <6jmn5kF42hreU1@mid.uni-berlin.de> <6jn4itF442e7U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> I wonder why something like myThread.exit() or myThread.quit() or >> threading.kill(myThread) can't be implemented? >> Is something like that present in Python 3000? > > Not that I'm aware of it (which doesn't mean to much though). > > However I *am* aware of the bazillions discussions that have been held > over this here - and the short answer is: it is a generally very bad > idea to terminate threads hard, as it can cause all kinds of corruption. the problem is that you have no idea what the thread is doing, so just killing it dead it may make one big mess out of the application's internal state; see e.g. this post http://mail.python.org/pipermail/python-list/2006-August/400256.html That's wise ;-) Stopping a thread asynchronously is in /general/ a dangerous thing to do, and for obvious reasons. For example, perhaps the victim thread is running in a library routine at the time the asynch exception is raised, and getting forcibly ejected from the normal control flow leaves a library-internal mutex locked forever. Or perhaps a catch-all "finally:" clause in the library manages to release the mutex, but leaves the internals in an inconsistent state. which links to a FAQ from Sun on this very topic: http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html (note that Java releases all mutexes when a thread is killed, but that's not much better, as the FAQ explains) so as usual, the right thing to do is to do things in the right way. From dmitry at makovey.net Wed Sep 24 23:35:06 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 03:35:06 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> Message-ID: showellshowell at gmail.com wrote: > Your code below is very abstract, so it's kind of hard to figure out > what problem you're trying to solve, but it seems to me that you're > using the B proxy class to decorate the A target class, which means > you want one of these options: Sorry for unclarities in original post. Basically A aggregates object of class B (example with no decorators and again it's oversimplified): class A: b=None def __init__(self,b): self.b=b def amethod(self,a): print "A::amethod ", a def bmethod(self,a): print "A::bmethod ",a return self.b.bmethod(a) def bmethod2(self,a,z): print "A::bmethod2 ",a,z return self.b.bmethod2(a,z) class B: def __init__(self): self.val=a def bmethod(self,a): print "B::bmethod ",a def bmethod2(self,a,z): print "B::bmethod2 ",a,z b=B() a=A(b) a.bmethod('foo') a.bmethod2('bar','baz') In my real-life case A is a proxy to B, C and D instances/objects, not just one. If you look at above code - whenever I write new method in either B, C or D I have to modify A, or even when I modify signature (say, add parameter x to bmethod) in B, C or D I have to make sure A is synchronized. I was hoping to use decorator to do it automatically for me. Since the resulting code is virtually all the same for all those proxy methods it seems to be a good place for automation. Or am I wrong assuming that? (since it is my first time using decorators I honestly don't know) Abovementioned code ilustrates what I am doing right now. My original post is an attempt to make things more automated/foolproof. From ggpolo at gmail.com Thu Sep 18 13:15:48 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Thu, 18 Sep 2008 14:15:48 -0300 Subject: Tkinter Bold Text In-Reply-To: <76vncf$1aj1ab@smtp.llnl.gov> References: <76vncf$1aj1ab@smtp.llnl.gov> Message-ID: On Thu, Sep 18, 2008 at 1:06 PM, April Lekin wrote: > Is there any way to highlight, bold or change the color of one word in a > variable to be displayed on a Tkinter GUI? Yes. > > Like: > > material = "Plastic" > introVal = "This report describes the construction of the %s." % (material) > You could separate them in two labels (if you are using labels), or apply a different tag if you are using a Text widget. > this is what I want: > This report describes the construction of the Plastic. > Plastic is Bold or Blue or Green > Changing the color is easier, you only change the foreground option. Changing to bold may not work for you, because depending on your Tk version and platform it will already be bold, so you won't notice anything. There is also a "catch" in changing text to bold, if you only set the text option of your Label to "-weight bold" it will probably get you a bold text, but with a different font than the one being used by other Labels. Now, something you could use as a base: import Tkinter import tkFont root = Tkinter.Tk() otherpart = Tkinter.Label(text="some text here") special = Tkinter.Label(text="special", foreground='blue') otherpart.pack(side='left') special.pack(side='left') f = tkFont.Font(font=otherpart['font']) f['weight'] = 'bold' f['underline'] = True special['font'] = f.name root.mainloop() > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From greg at cosc.canterbury.ac.nz Tue Sep 16 21:52:13 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 17 Sep 2008 13:52:13 +1200 Subject: Function getting a reference to its own module In-Reply-To: References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> Message-ID: <6jb6juF2co8rU1@mid.individual.net> Arnaud Delobelle wrote: > Or: > > import ModuleName as this_module Or: this_module = __import__(__name__) then you don't have to change anything. -- Greg From peter.anderson at internode.on.net Sat Sep 6 10:14:25 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sun, 07 Sep 2008 00:14:25 +1000 Subject: wxPython problem In-Reply-To: <48C24D3C.7060306@gmail.com> References: <48C24D3C.7060306@gmail.com> Message-ID: <48C29041.9050804@internode.on.net> Stef Mientki said: In PyScripter, you should run wxPython in the plain remote machine (not the wxPython remote),and you should set "reset before run flag" or reset the remote machine each time yourself. Stef, Thanks for the help! It has taken several hours to find and install the correct version of Rpyc (which is required to run the remote Python engine but it now seems to be working fine. And the "Reinitialise the Python engine {Alt]+[F2]" does need to be done between script runs. Given all that, the script now runs multiple times in PyScripter. The script still only runs ONCE in IDLE but I can live with that. In case others find this message from a search; I am using Python 2.5.2 and it requires rpyc-2.60.zip from the Rpyc download page (see http://rpyc.wikispaces.com/ click on the "Download" link and make sure you select the "main" link under the "Packages" column at Sourceforge. You will be shown a list of Rpyc versions. For Python 2.5.2 choose Relese "2.60". This will save you the several hours its cost me. Thanks again Stef. Regards, Peter -- Peter Anderson There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From gagsl-py2 at yahoo.com.ar Mon Sep 29 09:11:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 10:11:21 -0300 Subject: Fastest way to max() list References: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> Message-ID: En Fri, 26 Sep 2008 01:42:59 -0300, Chris Rebert escribi?: > B. Assuming by "distance" you meant "difference" and/or that the > distance is only in 1 dimension: > > from operator import itemgetter > firsts = map(itemgetter(0), main_list) > distance = max(firsts) - min(firsts) I think the above expression is overcomplicated. The code below does the exact same thing and is easier to understand, IMHO: firsts = [item[0] for item in main_list] distance = max(firsts) - min(firsts) -- Gabriel Genellina From n.s.buttar at gmail.com Sun Sep 21 11:10:09 2008 From: n.s.buttar at gmail.com (Navtej Singh) Date: Sun, 21 Sep 2008 20:40:09 +0530 Subject: Override the '+' symbol In-Reply-To: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> References: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> Message-ID: <1090e4100809210810n1898e546n29e75dc2e973a789@mail.gmail.com> http://docs.python.org/ref/numeric-types.html On Sun, Sep 21, 2008 at 8:37 PM, Mr.SpOOn wrote: > Hi, > how can I override the '+' symbol (and other math symbols) so that it > can have a new behavior when applied to some objects? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From raj.indian.08 at gmail.com Wed Sep 17 21:39:05 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Wed, 17 Sep 2008 18:39:05 -0700 (PDT) Subject: Modifying the system menu References: Message-ID: <8c1df849-d6e0-409a-930d-0593eed85683@a29g2000pra.googlegroups.com> I tested it again and found that the behaviour is a little different from what I mentioned previously in the mailchain. The item is working perfectly the first time around. Now if I close the application and run it again (which was what I did earlier), if that application system menu is already modified, it is causing this issue. Why would this happen? If it is that the file handle is not obtained, it wouldnt have gone through the following check at all? > hw = win32gui.GetSystemMenu(hwnd, False) > if hw != None: > win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); Not only did it go through, it failed with an invalid menu handle error. From sturlamolden at yahoo.no Tue Sep 23 15:08:47 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 12:08:47 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: <70d97b04-6f44-4a83-94bb-126446a2ac4d@k7g2000hsd.googlegroups.com> On Sep 23, 8:52?pm, bearophileH... at lycos.com wrote: > I think the Python version suffices. If it's not too much private you > may post the single minimal/reduced runnable Python module here, it > will be deleted in some time (if you want you can also use a private > paste):http://codepad.org/ http://codepad.org/rh8GzzJT Available 24 hours from now. > Is this a good or bad thing? ;-) It's just facinating how different people working on similar problems come up with different looking code. From harikrishnan.ech at gmail.com Sun Sep 7 01:03:37 2008 From: harikrishnan.ech at gmail.com (reddy) Date: Sat, 6 Sep 2008 22:03:37 -0700 (PDT) Subject: This group contains information about IT Requirements in USA as well as Hotlist of Candidates from the participating members Message-ID: <8cfef1d6-abeb-491d-a370-9d367510ab47@r15g2000prh.googlegroups.com> This group contains information about IT Requirements in USA as well as Hotlist of Candidates from the participating members CLICK & REGISTER U GET MORE DEDAILS ************************************************* * http://homologie.blogspot.com/ * * http://germanfriendfinder.com/go/g1022227-ppc * * http://amigos.com/go/g1022226-pmem * **************************************************** From half.italian at gmail.com Sat Sep 20 17:25:39 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sat, 20 Sep 2008 14:25:39 -0700 (PDT) Subject: explain slice assignment to newb References: ceceec82-cc0c-4daf-8f8a-1392f4872f71@k30g2000hse.googlegroups.com Message-ID: <1d7c98a3-8836-4de2-989c-42787d11abca@q5g2000prf.googlegroups.com> On Sep 20, 2:20?pm, Andrew wrote: > please explain this behavior to a newb: > > >>> a = [1,2,3,4] > >>> b = ["a","b","c","d"] > >>> a > [1, 2, 3, 4] > >>> b > > ['a', 'b', 'c', 'd'] > > >>> a[0:2] > [1, 2] > >>> a > [1, 2, 3, 4] > >>> b[2:4] > ['c', 'd'] > >>> a[0:2] = b[0:2] > >>> b[2:4] = a[2:4] > >>> a > ['a', 'b', 3, 4] > >>> b > ['a', 'b', 3, 4] What else would you expect to happen? From ebgssth at gmail.com Tue Sep 30 20:18:53 2008 From: ebgssth at gmail.com (js) Date: Wed, 1 Oct 2008 09:18:53 +0900 Subject: How can I customize builtin module search path to prefix/lib to prefix/lib64? In-Reply-To: References: Message-ID: In addition to that, .pth cannot prepend search path. All thing it can do is appending to it. In my case, I have to put lib64 before lib/. On 9/26/08, js wrote: > For 64bit python, there's no need to look at lib/lib-dynload because > libraries for 64bit should be in > lib64/lib-dynload. Having module search path which point to libraries > the python can not understand > is, IMHO, wrong. > > On Fri, Sep 26, 2008 at 3:03 AM, Mike Driscoll wrote: >> On Sep 25, 10:41 am, js wrote: >>> Hi list, >>> >>> Is it possible to change module search path (PYTHONPATH) built-in to >>> Python interpreter? >>> I thought I can change it with configure --libdir but it didn't work for >>> me. >>> I also tried patching around python source tree replacing lib to lib64 >>> but it didn't work either. >>> >>> Adjusting sys.path directly or using environ should do the trick but >>> I'd rather want to make it the default path for my python >>> >>> Thanks, >> >> Why not just add a custom path file (*.pth)? EasyInstall, wx, PyWin32 >> and others do it. Of course there's always sys.path.append as well. >> >> Mike >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > From mmanns at gmx.net Wed Sep 17 17:47:12 2008 From: mmanns at gmx.net (Martin Manns) Date: Wed, 17 Sep 2008 23:47:12 +0200 Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> Message-ID: <20080917234712.7d0d15b6@gmx.net> On Tue, 16 Sep 2008 19:25:58 -0700 (PDT) Fett wrote: > # SciPy -- http://www.scipy.org - supposedly has this, but as I said, > I can't find any mention of it anywhere but on the site you linked. I found OpenOpt on the site: http://scipy.org/scipy/scikits/wiki/MILP I downloaded the svn version and installed it on my Debian box. There were some error messages while installing. However, the example seems to work anyways. I am using the solver glpk from the package python-glpk. I hope that this works on your Ubuntu system as well. From circularfunc at gmail.com Thu Sep 11 05:23:43 2008 From: circularfunc at gmail.com (process) Date: Thu, 11 Sep 2008 02:23:43 -0700 (PDT) Subject: Is len O(n) or O(1) ? Message-ID: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> Python uses arrays for lists right? def quicksort(lista): if lista == []: lista else: return quicksort([x for x in lista[1:] if x < lista[0]]) + [lista[0]] + \ quicksort([x for x in lista[1:] if x >= lista[0]]) or def quicksort(lista): if len(lista) == 0 lista else: return quicksort([x for x in lista[1:] if x < lista[0]]) + [lista[0]] + \ quicksort([x for x in lista[1:] if x >= lista[0]]) wait first one raises TypeError unsupported operand types. From kerny404 at gmail.com Fri Sep 26 06:45:39 2008 From: kerny404 at gmail.com (andrea) Date: Fri, 26 Sep 2008 03:45:39 -0700 (PDT) Subject: Building truth tables Message-ID: Well I would like to make a little program that given a certain logical expression gives the complete truth table. It's not too difficult in fact, I just have some doubts on how to design it. I thought something like that: class Term: class Table: def and(... def or(... But I'm not convinced... I would like something like that more or less: a,b,c = Term() table([a,b,c], impl(and(or(a,b)),c)) Any idea?? Thanks From __peter__ at web.de Fri Sep 5 04:47:13 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Sep 2008 10:47:13 +0200 Subject: derived classes and __getattr__ References: Message-ID: Alexandru Mo?oi wrote: > i'm facing the following problem: > > class Base(object): > def __getattr__(self, attr): return lambda x: attr + '_' + x > > def dec(callable): > return lambda *args: 'dec_' + callable(*args) > > class Derived(Base): > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have > what_so_ever > mumu = dec(Base.mumu) # wrong, base > doesn't have mumu > > any idea how to do this? __getattr__() is defined in the class to create instance attributes on the fly. If you want class attributes you have to put the __getattr__() method into the class of the class, or "metaclass": class Base(object): class __metaclass__(type): def __getattr__(self, attr): return lambda self, x: attr + '_' + x def dec(callable): return lambda *args: 'dec_' + callable(*args) class Derived(Base): what_so_ever = dec(Base.what_so_ever) d = Derived() print d.what_so_ever("42") I don't see how you can turn this into something useful... Peter From sturlamolden at yahoo.no Tue Sep 23 16:38:10 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 13:38:10 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: <5f2eed90-b49b-4c29-bfd5-cc90c4495b3c@m3g2000hsc.googlegroups.com> On Sep 23, 10:16?pm, Robert Kern wrote: > What's confusing? You do have to create a profile: How do I add a new page to the wiki? I'm only able to edit the front page of the cookbook. But it doesn't help to add link there if I have no page to link. (I may be incredibly stupid though.) From hniksic at xemacs.org Tue Sep 23 09:37:56 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 23 Sep 2008 15:37:56 +0200 Subject: Mutex not thread safe? PEP-3108. References: Message-ID: <87fxnr0yq3.fsf@mulj.homelinux.net> Roy Smith writes: > I'm perusing PEP-3108 and came upon this interesting statement (under the > "Hardly used" section): > > mutex [...] Not thread-safe. > > How can a mutex, whose sole reason for existence is to mediate thread > safety, not be thread safe? "mutex" is a module designed for use with "sched", not for multithreading: """Mutual exclusion -- for use with module sched [...] Of course, no multi-threading is implied -- hence the funny interface for lock, where a function is called once the lock is aquired. """ What is called a mutex in multithreading is known in Python as threading.Lock, and does work with threads. From To-Email-Use-The-Envelope-Icon at My-Web-Site.com Sat Sep 27 22:47:54 2008 From: To-Email-Use-The-Envelope-Icon at My-Web-Site.com (Jim Thompson) Date: Sat, 27 Sep 2008 19:47:54 -0700 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> Message-ID: <52std4tnvg0h07it7kik0kinht9812c839@4ax.com> On Sat, 27 Sep 2008 23:12:59 +0000 (UTC), Cydrome Leader wrote: >In rec.crafts.metalworking Jim Thompson wrote: >> >> On Sat, 27 Sep 2008 18:47:16 -0400, default >> wrote: >> >>>On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko >>> wrote: >>> >>>>Hello, this is Milenko Stojadinovic from town Banjaluka, >>>>Bosnia and Herzegovina, also known as Cvrcko >>>>Does anyone know of any bars in town where I can >>>>swallow a bucket of cum? It can be either dog, >>>>horse or human cum. Also, does anyone know of >>>>any sex bars where people will shit in your mouth? >>>>I also like eating shit. >>> >>>Come to the US and park your mouth in front of George Bush - all the >>>Bshit you can eat - and it keeps on coming! >>> >>>I have a buddy in Bosna - he's normal. >> >> Now you know why I blanket kill-file googlegroups. > >So you and everybody can talk about them nonstop? You're gone also ;-) ...Jim Thompson -- | James E.Thompson, P.E. | mens | | Analog Innovations, Inc. | et | | Analog/Mixed-Signal ASIC's and Discrete Systems | manus | | Phoenix, Arizona 85048 Skype: Contacts Only | | | Voice:(480)460-2350 Fax: Available upon request | Brass Rat | | E-mail Icon at http://www.analog-innovations.com | 1962 | Liberalism is a persistent vegetative state From jjl at pobox.com Wed Sep 3 17:54:03 2008 From: jjl at pobox.com (John J Lee) Date: Wed, 3 Sep 2008 22:54:03 +0100 (BST) Subject: [wwwsearch-general] python/xpath question.. In-Reply-To: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> References: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> Message-ID: On Wed, 3 Sep 2008, bruce wrote: [...] > and get the number of total nodes... > by subtracting, i can get the number of nodes, without text.. is there an > easier way??!! [...] Yes -- don't use XPath :-) John From almar.klein at gmail.com Fri Sep 26 03:29:42 2008 From: almar.klein at gmail.com (Almar Klein) Date: Fri, 26 Sep 2008 09:29:42 +0200 Subject: what does "python -i" use as input stream (stdin)? In-Reply-To: References: Message-ID: > > Use subprocess.PIPE > Usually the tricky part is to figure out exactly whether there is more > input or not. With Python it's easy, use the ps1 prompt. Thanks, but that is not exactly what I meant. (Maybe my question was a bit vague). I want to replace the input stream of the *remote* process. So I'll be running something like "python -i remote.py", and inside remote.py I create a pseudo-file to replace the input stream (of the remote process). I have now solved my problem by running "python remote.py" (without the -i) and start an interactive interpreter (inherited from code.InteractiveConsole). This interpreter *does* use the sys.stdin, so I can just do: "sys.stdin = my_pseudo_file" (I start a separate thread that reads the original stdin and writes received text to the pseudofile. But now I can also communicate and do stuff with the process when the main thread is running (for example interrupting it on windows!)) I would still like to hear if anyone knows how I can change the input stream that is used when running "python -i", but I would not be surprised if it is impossible... Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 30 03:27:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 04:27:50 -0300 Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> <357e734f-e99f-41e5-9cac-083d636a23e1@n38g2000prl.googlegroups.com> <95f8433c-213f-4b3a-8d93-bebbe2561e7f@s9g2000prg.googlegroups.com> <781c4e48-7396-4278-85bd-3578f88aa501@l33g2000pri.googlegroups.com> Message-ID: En Sun, 28 Sep 2008 22:44:20 -0300, robean escribi?: > Many thanks for your reply. I was simply under the impression that > 'import urllib2' would take care of the namespace issue and simply > import everything in urlib2, making it unnecessary to have to > reference HTTPError and URLError. Sorry for being dense about this > (I'm very new to Python).. Again, thanks for your help. That's a common misconception - see this article: http://effbot.org/zone/import-confusion.htm -- Gabriel Genellina From jhuerta at cipf.es Wed Sep 24 12:15:19 2008 From: jhuerta at cipf.es (Jaime Huerta Cepas) Date: Wed, 24 Sep 2008 18:15:19 +0200 Subject: how to build a MacOS universal python package including external dependencies Message-ID: Hi all, I have developed a set python libraries that provide several scientific methods to analyse and visualize certain type of biological data. This libraries are based on many external python modules, such as python-mysql python-sip or python-qt4. I use GNU/linux to develop my tools and I found no problems into installing all dependencies, however it does not seem to be that easy on MacOS. I am sure that all the dependencies (qt4, pyqt4 , mysqldb, scipy, numpy) are cross platform, but when you are trying to publish your tool in an academic journal, most referees (many of them using MacOS) expect some kind of straightforward installation process for the tool. I wonder if there would be a way in which I could compile all the dependencies and libraries in a MacOs system and then building a static universal binary that I can distribute. I guess it should be possible, but I am not sure how difficult it might be, and whether all dependencies (qt4 is huge) can be packaged together. Any help is more than welcome! Best regards, Jaime. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ggpolo at gmail.com Mon Sep 1 23:28:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 2 Sep 2008 00:28:39 -0300 Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp In-Reply-To: <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> Message-ID: On Mon, Sep 1, 2008 at 11:01 PM, akineko wrote: > On Sep 1, 6:34 pm, "Guilherme Polo" wrote: >> This is an illusion you have, calling those methods are not the way >> for explicitly controlling button's behavior, not more than generating >> proper events. The explicit way is to not use a button, instead >> (ab)use Canvas. > > Some of my custom widgets used Canvas. > When I designed the "sticky" button widget, I briefly considered use > of Canvas but I rejected because the one I wanted is nothing but > Button (except "sticky" behaviour). Can you clarify what is this "sticky" behavior ? Are you referring to a toggle button ? If yes, then you might be after a simple Checkbutton: checkbutton = Tkinter.Checkbutton(indicatoron=False, text='test') > I understand that use of Canvas provides greater flexibility but I > felt it was over-kill. > Your insights are very helpful for me and other people when designing > a custom widget. > > Aki- > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From blacktrash at gmx.net Fri Sep 5 11:29:19 2008 From: blacktrash at gmx.net (Christian Ebert) Date: Fri, 05 Sep 2008 11:29:19 -0400 Subject: [MacOS X] plat-mac/errors.rsrc.df.rsrc not installed/created References: <20080828183304.406.slrn@krille.blacktrash.org> Message-ID: <20080905152652.542.slrn@krille.blacktrash.org> * Christian Ebert on Thursday, August 28, 2008: > I am on MacOS 10.4.11, and have a minor recurring problem, when > using my own Python installation. > > I only stumbled over it when using http operations with the > Mercurial SCM, and my /tmp/ folder was clobbered with *.rsrc > temporary files. > > Some references: > http://www.selenic.com/pipermail/mercurial/2007-October/015039.html > and, as I forgot about it :( : > http://www.selenic.com/pipermail/mercurial/2008-August/021072.html > > Apparently for some stuff plat-mac/macresource.py needs to create > plat-mac/errors.rsrc.df.rsrc. If that fails, at least that is how > I read macresource.py, it creates them via mkstemp in /tmp/. > > Once I recognize the problem I can work around it by either > > $ sudo mv /tmp/tmp.rsrc /usr/local/lib/python2.5/plat-mac/errors.rsrc.df.rsrc > > or by temporarily "chown myname plat-mac", and, once the file is > created, "chown root plat-mac" again. > > My 2.5.2 install is under /usr/local, but other Mac users with > the same setup, do not have the problem. > > I don't need/want the Apple Framework install, and again, others > do not have the problem with this setup. > > Anyone any ideas? > > The best I could google was > http://bugs.python.org/issue763708 > but this seems encoding related. I gather from the overwhelming reaction that I am the only one experiencing this ;-) However, if I can provide more info that might be useful, just tell me. TIA c -- Was hei?t hier Dogma, ich bin Underdogma! [ What the hell do you mean dogma, I am underdogma. ] _F R E E_ _V I D E O S_ -->> http://www.blacktrash.org/underdogma/ From bearophileHUGS at lycos.com Mon Sep 22 07:32:14 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 04:32:14 -0700 (PDT) Subject: A bit weird dictionary behavior References: Message-ID: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Pekka Laukkanen: > but it still doesn't feel exactly right. Would it be worth submitting a bug? It feels wrong because it is. In a tidier language (Pascal, Java, etc) a boolean and an integer must be different types. Keeping booleans and integers separated may avoid some bugs too (I don't know how many/ often). But the Python language copies many things from C, where most things are chosen for practical purposes and maximum efficiency (and from much simpler Python implementations, where there was no boolean type, so bools are grafted in), so it's not a bug, and I think it will not be fixed soon (Python 3 was probably the last chance to change it, for several years to come). So you probably have to live with this illogical behavior. On the other hand it has some little practical advantages, you can do: sum(x == y for x in iterable) That also equals to a more tidy: sum(1 for x in iterable if x == y) Regarding the dict, they are dynamically typed, but good programming practice (that comes from experience of bugs that have bitten you) tells you that generally it's better to be careful with the inserting different types into a dict; often it's better to avoid doing it. Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Sep 20 19:42:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Sep 2008 20:42:58 -0300 Subject: writeable buffer and struct.pack_into and struct.unpck_from References: Message-ID: En Sat, 20 Sep 2008 15:45:48 -0300, Tzury Bar Yochay escribi?: > I can't find in the documentation the way to use these two functions. > > can someone share a simple code that utilize these two functions? struct.pack_into is intended to "fill" a buffer you got from somewhere, probably other language or process. ctypes.create_string_buffer may be used to create a writable buffer in python code. py> from ctypes import create_string_buffer py> b = create_string_buffer(10) py> b.raw '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' py> from struct import * py> pack_into("hhh", b, 0, 1, 2, -1) py> b.raw '\x01\x00\x02\x00\xff\xff\x00\x00\x00\x00' unpack_from does the opposite. Before Python 2.5, you had to use pack to create a string object, and then copy its contents into the destination buffer; using pack_into avoids the memory copy. -- Gabriel Genellina From ewertman at gmail.com Wed Sep 3 13:04:10 2008 From: ewertman at gmail.com (Eric Wertman) Date: Wed, 3 Sep 2008 13:04:10 -0400 Subject: Coming from .NET and VB and C In-Reply-To: References: Message-ID: <92da89760809031004t65565507vf6d57f8210d50a95@mail.gmail.com> > Using Python. I found "Dive Into Python" which I will be reading shortly The title of the book is good advice all by itself. Especially with prior programming experience, you'll get started very quickly. What will take longer is the assimilation of some of python's neater and more idiomatic features, like list comprehensions and generators. Also, the fact that strings are immutable threw me off a little the first day or two. If you stick with it, I think you'll find those little things to be your favorite parts though. Certainly I use list comprehensions all the time now, when I used to not use them at all. In about 90% or more of cases, you can avoid doing things that you do routinely in other languages.. mostly by iterating directly over things you don't need counter variables or intermediate variable names. In fact, I find myself going back through old code and removing variables pretty frequently. I'm sure there's a lot more. Personally I find it a lot of fun to code in. From aioe.org at technicalbloke.com Sat Sep 27 01:55:07 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 27 Sep 2008 01:55:07 -0400 Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: process wrote: > ' '.join([`x * x` for x in range(1, 6)]) > > exactly what does this symbol do and what does it stand for? Which symbol, the '*' ??? Are you kidding? From nospam at example.com Sun Sep 28 05:36:13 2008 From: nospam at example.com (Erhard) Date: Sun, 28 Sep 2008 02:36:13 -0700 Subject: Calculating timespan In-Reply-To: <784049c7-a9cf-4006-873f-d3a869bf6b93@l64g2000hse.googlegroups.com> References: <784049c7-a9cf-4006-873f-d3a869bf6b93@l64g2000hse.googlegroups.com> Message-ID: marek.rocki at wp.pl wrote: > from datetime import datetime, timedelta > span = datetime.now() - > datetime(year=2008,month=8,day=27,hour=12,minute=34,second=56) > if span < timedelta(minutes=37): > # do something timedelta! Yes, it's obvious that's what I was looking for. I was stuck with 'timespan' in my head and couldn't find anything like it in the docs. Thank you very much! From keshet1 at umbc.edu Fri Sep 12 13:11:06 2008 From: keshet1 at umbc.edu (Ben Keshet) Date: Fri, 12 Sep 2008 13:11:06 -0400 Subject: manipulating files within 'for' Message-ID: <48CAA2AA.40809@umbc.edu> Hi Pythoneers, I have a question about a code I wrote with the help of someone. The code below copy a few lines from different files into one file. It works fine as it is given here and generates the new file 'pockets.out' correctly, but says:"....py returned exit code 0". However, if I add more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) it gives an error: "Exception raised while running script". Can anyone please advice me? Why is it giving an error on multiple x but runs well with one (I made sure that all files and folders exist, etc.). What does exit code 0 mean? what does "exception raised" mean? Thanks a lot, BK CODE: |receptors = ['1AZM'] for x in receptors: print x # open out_file for appending for each 'x' in receptors, close at same level out_file = open('c:/Linux/Dock_method_validation/%s/validation/pockets.out' %(x),'a') for i in range(10): for r in (7, 9, 11, 13, 15, 17): f = open('%s/validation/ligand_ran_line_%s_%s.mol2' %(x,i,r), 'r') out_file.write('%s ' %i) out_file.write('%s ' %r) # assume 'PRIMARY' should be found first # set flag for string 'PRIMARY' primary = False # iterate on file object, empty files will be skipped for line in f: if 'PRIMARY' in line: primary = True out_file.write(line.strip()) # write line to out_file out_file.write(' ') # add a space # write all line after 'PRIMARY' was found until 'TRIPOS' is found elif 'TRIPOS' not in line and primary: out_file.write(line.strip()) out_file.write(' ') # add a space elif 'TRIPOS' in line and primary: break # stop when 'TRIPOS' is found print out_file.write('\n') # move to a new line f.close() # close file. for loop moves to next 'r' value, and then to next 'i' out_file.close() # close out_file| From carriere.jonathan at gmail.com Thu Sep 11 11:13:52 2008 From: carriere.jonathan at gmail.com (carriere.jonathan at gmail.com) Date: Thu, 11 Sep 2008 08:13:52 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> Message-ID: <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> On Sep 11, 4:19?pm, Fredrik Lundh wrote: > carriere.jonat... at gmail.com wrote: > > ?> I wonder if there is a platform written in python. The equivalent of > ?> the Netbeans platformhttp://platform.netbeans.org/in the Python > ?> world. Do you know such a thing? > > You (or maybe the Java folks) seem to have missed that platform has a > rather specific meaning in computing: > > http://en.wikipedia.org/wiki/Platform_(computing) > > Given that definition, Python is pretty much a platform in itself. ?If > you want to use Python for a specific task, you add libraries for that > task. ?Tell us what you want to do, and we'll tell you what libraries > and toolkits you might want to try. > > I want to build a desktop application. I am searching for some kind of environment that would provide all the elements ready (Windows...). Then I would have to code the business logic only. Jonathan. From tmohr at s.netic.de Tue Sep 16 15:35:05 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Sep 2008 21:35:05 +0200 Subject: optparse Message-ID: Hi, i use the module optparse to parse the command line: ------example #! /usr/bin/python import optparse parser = optparse.OptionParser() parser.add_option("-v", "--verbose", dest = 'verb', help = 'be loud', action = 'store_true', default = 'store_false') (opts, args) = parser.parse_args() print "opts", opts print "args", args ------example If i call it without any parameters i get: opts {'verb': 'store_false'} args [] I would rather like to see the actual value False in "opts", did i use some wrong parameters somewhere? I can't imagine that this is the wanted behaviour of optparse. Thanks for any hints, Torsten. From maric at aristote.info Tue Sep 16 12:07:03 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 18:07:03 +0200 Subject: literals optimization (was Re: append on lists) In-Reply-To: <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> References: <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> Message-ID: <200809161807.04172.maric@aristote.info> Le Tuesday 16 September 2008 16:57:26 Grant Edwards, vous avez ?crit?: > On 2008-09-16, Maric Michaud wrote: > > Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit?: > >> On 2008-09-16, Maric Michaud wrote: > >> > all expressions that return something, return a new object, > >> > >> That's not _quite_ true: > >> >>> a=1 > >> >>> b=a.__add__(0) > >> >>> a is b > >> > >> True > >> > >> ;) > > > > This is implementation specific, > > Indeed. > > > the specification of the language says that it should be > > false, > > That's curious. If so, then the implimentation is in violating > the specification. But it doesn't matter as the "is" operator is not relevant for any use case with scalars and even strings and the optimization is not negligible. In fact, I'd rather say it's unspecified, each implementation does it its own way. maric at redflag1 17:48:03:~$ ipython >>>[1]: int() is 0 # contructor honour cache ...[1]: True >>>[2]: 256 is 255+1 # still caching ...[1]: True >>>[3]: 257 is 255+2 # here it stops ...[3]: False maric at redflag1 17:48:08:~$ jython Jython 2.2.1 on java1.6.0_07 Type "copyright", "credits" or "license" for more information. >>> int() is 0 # not caching when using constructor 0 >>> 2 is 1+1 # caching on expression 1 >>> 500 is 250*2 # caching occurs beyond my CPython 1 >>> 5000 is 5000 # compile-time optimization 1 >>> 5000 is 2500*2 # not caching too big numbers 0 > Where is that in the specification? Each literal creates a new instance, and instances of int are not supposed to be unique for each value (at less it's not specified so), so "1 is not 1", but implementation can cache integers, short strings, to avoid creating an new instance each time they appear in code. jython do this also for integer (see above), but not for strings : maric at redflag1 17:33:52:~$ jython Jython 2.2.1 on java1.6.0_07 Type "copyright", "credits" or "license" for more information. >>> a = "aaaa" >>> a is "aaaa" 0 maric at redflag1 17:36:48:~$ ipython >>>[1]: a = "aaaa" >>>[2]: a is "aaaa" ...[2]: True BTW, I'm talking of Jython 2.2, Jython 2.4, which quite ready I think, can change his mind as well. > I > suspect the statement in the specification should only apply to > mutable objects. > No, CPython also have a unique empty tuple, but tuple literals are not cached nor there are compile-time optimization : >>>[5]: () is () ...[5]: True >>>[6]: (1,) is (1,) ...[6]: False > > and it is for higher numbers : > >>>>[15]: a=1000 > >>>> > >>>>[16]: b=a.__add__(0) > >>>> > >>>>[17]: a is b > > > > ...[17]: False > > > > Don't disturb our OP, with side questions, please, it was > > enough hard like this ;) > > I'm not trying to confuse the OP, but to quote Einstein: > "Everything should be made as simple as possible, but not > simpler." -- _____________ Maric Michaud From castironpi at gmail.com Tue Sep 16 13:43:04 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 10:43:04 -0700 (PDT) Subject: how to exclude specific things when pickling? References: Message-ID: <35fe74c7-c130-4d82-80d1-8c972520ecfc@y38g2000hsy.googlegroups.com> On Sep 14, 9:53?am, "inhahe" wrote: > If I gather correctly pickling an object will pickle its entire hierarchy, > but what if there are certain types of objects anywhere within the hierarchy > that I don't want included in the serialization? ?What do I do to exclude > them? ? Thanks. Are you picturing a custom pickler object? From annathorns at googlemail.com Mon Sep 22 12:25:06 2008 From: annathorns at googlemail.com (annathorns at googlemail.com) Date: Mon, 22 Sep 2008 09:25:06 -0700 (PDT) Subject: Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS Message-ID: <6298ac0c-9563-46af-90e3-9bab31b8204f@o40g2000prn.googlegroups.com> Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com From justin.kuto at gmail.com Fri Sep 26 16:33:42 2008 From: justin.kuto at gmail.com (afrogazer) Date: Fri, 26 Sep 2008 13:33:42 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> Message-ID: <7b1181e9-16a2-458a-8677-a2d8d7c8a961@l42g2000hsc.googlegroups.com> In my rush I seem to have overlooked that, maybe because it's Friday afternoon. Converting the degrees to radians fixed it: rad_angles = [elem*(pi/180) for elem in angles] Thanks, From i3dmaster at gmail.com Fri Sep 12 19:18:59 2008 From: i3dmaster at gmail.com (i3dmaster) Date: Fri, 12 Sep 2008 16:18:59 -0700 (PDT) Subject: conditional install/distribution References: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> <6it533Fe2h8U1@mid.uni-berlin.de> Message-ID: <3f8893c3-fd23-4734-a2d4-07921be67202@z11g2000prl.googlegroups.com> On Sep 11, 11:07?am, "Diez B. Roggisch" wrote: > i3dmasterschrieb: > > > Is there a feature in distutils or easy_install to specify what > > version of python that the target package can be installed? For > > example, if a package has a module that only needed if the python > > version < 2.6, is there a way to specifiy that in setup.py or > > easy_install cfg file so that when installing to python >= 2.6, this > > module wouldn't be installed?? > > you can simply import sys and check sys.version in the setup-script, and > abort with an error-message if the expectations aren't matched. > > Diez I know I can precheck the version, but the real issue is how I can prevent from installing a specific module? Actually, the rest of the package should still be installed but just not a particular module because the feature is built in after 2.6. From skip at pobox.com Tue Sep 23 09:36:14 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Sep 2008 08:36:14 -0500 Subject: Mutex not thread safe? PEP-3108. In-Reply-To: References: Message-ID: <18648.61646.947232.439715@montanaro-dyndns-org.local> >>>>> "Roy" == Roy Smith writes: Roy> I'm perusing PEP-3108 and came upon this interesting statement Roy> (under the "Hardly used" section): Roy> mutex [...] Not thread-safe. Roy> How can a mutex, whose sole reason for existence is to mediate thread Roy> safety, not be thread safe? Because it is a mutex in name only. Take a look at the code. There is nothing in there which actually locks the internal data structure against simultaneous manipulation (a collections.deque instance in this case) from multiple threads. Skip From tino at wildenhain.de Mon Sep 29 09:25:39 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 29 Sep 2008 15:25:39 +0200 Subject: writing dll in python? In-Reply-To: References: Message-ID: <48E0D753.3040101@wildenhain.de> nishalrs wrote: > Hello All, > > My main motivation is to build a collection of useful mathematical > models (that I have developed over the years) to design ultrasonic > sensors. This should be some sort of a library that should be able to > be used for desktop/web application development, to run in variety of > operating systems. > > I am more than convinced after looking at python.org website, it is > the right tool for the job. I intend to learn python, but I am not > really sure, where to begin. > > Should I write all the functions as simple python scripts? Or is there > some facility for creating a .dll like library, that could be more > suitable for what in intend to develop? This is called a module in python, you can also collect modules to a package. Once you have your package ready, you can distribute them as egg if you want (basically a distribution as zip file) - look up python eggs and easy-install with your search engine of choice. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From febkimbleox at gmail.com Sat Sep 27 07:17:18 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:17:18 -0700 (PDT) Subject: amaterske porno slike amaterske porno slike free amaterske slike porno amaterske - Free Message-ID: amaterske . . . *******CLICK HERE******** http://vids365.cn/amaterske ***************************** . . . . . . . . . . . . I too enjoyed the sight of amaterske big tits flying in every direction. I too enjoyed the sight of porno big tits flying in every direction. I too enjoyed the sight of slike big tits flying in every direction. I too enjoyed the sight of amaterske big tits flying in every direction. I too enjoyed the sight of porno big tits flying in every direction. Let slike finish these steaks, they?re almost done. Let free finish these steaks, they?re almost done. Let amaterske finish these steaks, they?re almost done. Let slike finish these steaks, they?re almost done. Let porno finish these steaks, they?re almost done. Let amaterske finish these steaks, they?re almost done. Let porno finish these steaks, they?re almost done. Let slike finish these steaks, they?re almost done. Let srbija finish these steaks, they?re almost done. From luigi.paioro at gmail.com Wed Sep 10 03:40:25 2008 From: luigi.paioro at gmail.com (luigi.paioro at gmail.com) Date: Wed, 10 Sep 2008 00:40:25 -0700 (PDT) Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> <6inkkiFrbptbU1@mid.uni-berlin.de> Message-ID: <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> On 9 Set, 17:55, "Diez B. Roggisch" wrote: > I would go for a slightly different approach: make your server have a > dispatch-method that delegates the calls to the underlying actual > implementation. But *before* that happens, extract the information as > above, and either > > ?- prepend it to the argument list > > ?- stuff it into threadlocal variables, and only access these if needed in > your implementation. > > Diez Are you suggesting me to overwrite the _dispatch(self, method, params) method of SimpleXMLRPCDispatcher? I thought to this possibility, but it only accepts "method" and "params" as arguments, so, as far as I know, I have no way to get the user and host address to append. Perhaps I've misunderstood your suggestion... in that case can you post a short example? Thank you very much! Luigi From mblume at socha.net Thu Sep 4 13:03:33 2008 From: mblume at socha.net (mblume) Date: 04 Sep 2008 17:03:33 GMT Subject: Read Binary data References: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> Message-ID: <48c014e5$0$16176$5402220f@news.sunrise.ch> Am Thu, 04 Sep 2008 18:03:54 +0200 schrieb Fredrik Lundh: > >> I am trying to read a binary file [...] > > > f = open("a.bin", "rb") # read binary data > s = f.read() # read all bytes into a string > > import array, sys > > a = array.array("f", s) # "f" for float > if sys.byteorder != "big": > a.byteswap() > For more complicated structures, the struct module may help. HTH. Martin From bj_666 at gmx.net Sun Sep 28 06:15:00 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Sep 2008 10:15:00 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> Message-ID: <6k93opF6k62hU1@mid.uni-berlin.de> On Sun, 28 Sep 2008 01:35:11 -0700, est wrote: >> Because that's how ASCII is defined. >> Because that's how ASCII is defined. ASCII is a 7-bit code. > > Then why can't python use another default encoding internally > range(256)? Because that doesn't suffice. Unicode code points can be >255. > If Python choose another default encoding which handles range(256), 80% > of python unicode encoding problems are gone. 80% of *your* problems with it *seems* to be gone then. > It's not HARD to process unicode, it's just python & python community > refuse to correct it. It is somewhat hard to deal with unicode because many don't want to think about it or don't grasp the relationship between encodings, byte values, and characters. Including you. >> stop dreaming of a magic solution > > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, what's > wrong???? What do you mean by "just print 0x7F to 0xFF"? For example if I have ``s = u'Sm?rebr?d?'`` what bytes should ``str(s)`` produce and why those and not others? >> Isn't that more or less the same as telling the OP to use unicode() >> instead of str()? > > sockets could handle str() only. If you throw unicode objects to a > socket, it will automatically call str() and cause an error. Because *you* have to tell explicitly how the unicode object should be encoded as bytes. Python can't do this automatically because it has *no idea* what the process at the other end of the socket expects. Now you are complaining that Python chooses ASCII. If it is changed to something else, like MBCS, others start complaining why it is MBCS and not something different. See: No fix, just moving the problem to someone else. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Sun Sep 28 02:14:01 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Sep 2008 06:14:01 GMT Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Message-ID: <6k8ll9F6jbmtU2@mid.uni-berlin.de> On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote: > To me, this is a somewhat unintuitive behavior. I want to discuss the > parts of it I don't understand. > >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= lambda: n > ... >>>> f[0]() > 9 >>>> f[1]() > 9 `n` is looked up at the time ``f[0]`` is called. At that time it is bound to 9. >>>> f= [ None ]* 10 >>>> for n in range( 10 ): > ... f[ n ]= (lambda n: ( lambda: n ) )( n ) ... >>>> f[0]() > 0 >>>> f[1]() > 1 > > Which is of course the desired effect. Why doesn't the second one just > look up what 'n' is when I call f[0], and return 9? It *does* look up `n` at the time you call ``f[0]`` but this time it's the local `n` of the outer ``lambda`` function and that is bound to whatever the function was called with. At the time it was called the global `n` was bound to 0. Maybe it get's more clear if you don't name it `n`: In [167]: f = [None] * 10 In [168]: for n in xrange(10): .....: f[n] = (lambda x: lambda: x)(n) .....: In [169]: f[0]() Out[169]: 0 Ciao, Marc 'BlackJack' Rintsch From coolkid246 at googlemail.com Thu Sep 4 05:45:02 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 02:45:02 -0700 (PDT) Subject: guenstige kredite Message-ID: <40d2d448-0e35-4877-b236-465dc9017f18@a3g2000prm.googlegroups.com> + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://kredite-online-244.info + + + + From sjmachin at lexicon.net Sun Sep 7 18:42:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Sep 2008 15:42:00 -0700 (PDT) Subject: lacking follow-through References: <6ij1ecFqp39rU4@mid.uni-berlin.de> Message-ID: On Sep 8, 8:36?am, Fredrik Lundh wrote: > Marc 'BlackJack' Rintsch wrote: > > Yeah, castironpi sometimes doesn't make much sense. ?Maybe because it's a > > bot!? ?:-) > > if so, they sure don't make c.l.py bots like they used to, do they? > > That's correct. This one seems to have an anger management module :-) From pavlovevidence at gmail.com Thu Sep 4 14:59:43 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 11:59:43 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: On Sep 4, 7:09 am, "Marco Bizzarri" wrote: > Sorry... pressed enter but really didn't want to. > > As I said, let's say I have a class > > class A: > def __init__(self): > self.x = None > > Python makes the decision to allow the developers to directly access > the attribute "x", so that they can directly write: "a.x = 1", or > whatever; this has for me the unfortunate side effect that if I write, > for example "a.y = 1", when I really wanted to write "a.x = 1" no one > cares about it, and I'm unable to spot this error until later. You can write code to guard against this if you want: class A: legal = set(["x"]) def __setattr__(self,attr,val): if attr not in self.legal: raise AttributeError("A object has no attribute '%s'" % attr) self.__dict__[attr] = val def __init__(self,x): self.y = x I suspect most people who go into Python doing something like this soon abandon it when they see how rarely it actually catches anything. Carl Banks From rex.eastbourne at gmail.com Thu Sep 4 17:33:38 2008 From: rex.eastbourne at gmail.com (Rex) Date: Thu, 4 Sep 2008 14:33:38 -0700 (PDT) Subject: Is it possible to download only the of a web page? Message-ID: I am writing a script that executes a bunch of queries through a form on a website and reads the results. I am only interested in the section in the <head> of each web page. Currently, each page the server returns is about 100kb and contains a bunch of HTML and Javascript, all of which I don't need; I don't want to waste bandwidth or consume too much of the server's resources. I just need the <title> string. Is there any way to download less than the entire web page? From lixinyi.23 at gmail.com Wed Sep 24 02:39:48 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 23:39:48 -0700 (PDT) Subject: PyRun_SimpleFile() crashes Message-ID: <d71e6607-31ca-48a6-b61f-040536a7cebf@g17g2000prg.googlegroups.com> my code: main.cpp #include <Python.h> int main(int argc, char **argv) { Py_Initialize(); FILE *file_1 = fopen("a2l_reader.py","r+"); PyRun_SimpleFile(file_1,"a2l_reader.py"); Py_Finalize(); } compile under windows using MinGW: g++ main.cpp libpython25.a -o a no error was found. But when I run a.exe the program just crashes. What should I do? From ldo at geek-central.gen.new_zealand Wed Sep 17 20:20:55 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 18 Sep 2008 12:20:55 +1200 Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <tvkf941kmehd7hcihihdiil6fjutbfkf6k@4ax.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> Message-ID: <gas6t7$382$1@lust.ihug.co.nz> In message <973f75d4-90f5-4930-9107-15fc8651196d at v16g2000prc.googlegroups.com>, sui wrote: > Traceback (most recent call last): > File "mail5.py", line 21, in <module> > session = smtplib.SMTP(SMTPserver,port) > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > self.sock.connect(sa) > File "<string>", line 1, in connect > then conncetion time out..... Could it be your ISP is blocking outgoing connections to port 25? From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 13:11:35 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 19:11:35 +0200 Subject: improving a huge double-for cycle In-Reply-To: <48d2bd22$0$4514$426a74cc@news.free.fr> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <48d54ab4$0$20563$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > Alexzive a ?crit : >> Hello there :) , >> (snip) > > Now the obvious winner is pruebono Correction (my bad) : Steven D'Aprano submitted the set-based solution first. So the winners are Steven and pruebono. From rex.eastbourne at gmail.com Thu Sep 4 14:16:47 2008 From: rex.eastbourne at gmail.com (Rex) Date: Thu, 4 Sep 2008 11:16:47 -0700 (PDT) Subject: Submitting forms over HTTPS with mechanize References: <b85ddf6d-ab66-423e-8840-0d8a962f91ba@v16g2000prc.googlegroups.com> <48BF4554.7060809@vitalEsafe.com> Message-ID: <782f1eff-a3b2-4cd8-a134-68300510ae42@k36g2000pri.googlegroups.com> On Sep 3, 10:17?pm, Larry Bates <larry.ba... at vitalEsafe.com> wrote: > Rex wrote: > > Hello, > > > I am working on an academic research project where I need to log in to > > a website (www.lexis.com) over HTTPS and execute a bunch of queries to > > gather a data set. I just discovered the mechanize module, which seems > > great because it's a high-level tool. However, I can't find any decent > > documentation for mechanize apart from the docstrings, which are > > pretty thin. So I just followed some other examples I found online, to > > produce the following: > > > baseurl = 'http://www.lexis.com/' > > br = mechanize.Browser() > > br.set_handle_robots(False) > > br.addheaders = [('User-Agent', 'Firefox')] > > br.open(baseurl) > > br.select_form(name="formauth") > > br["USER_ID"]="my_user_id" > > br["PASSWORD"]="my_password" > > result = br.submit() > > > This code hangs at br.submit(), and I can't tell what I'm doing wrong. > > Typically I would inspect the HTTP data with an HTTP debugging proxy > > (Fiddler), but I guess since this is HTTPS I can't do that. Any > > glaring errors in my code? > > > By the way, does anyone have suggestions for Python modules that I > > should use instead of mechanize (and that are sufficiently easy)? If > > mechanize fails, I might try modifying some similar Perl code a friend > > sent me that logs into lexis.com. > > > Thanks so much, > > > Rex > > I've used mechanize quite successfully but others have suggested Twillhttp://twill.idyll.org/. ?It seems to be at least documented. > > -Larry Thanks for the reply, Larry. I ran my code again and it worked; there was probably some temporary issue with either my computer or the server that caused it to hang. From thomascribbs at gmail.com Tue Sep 30 14:03:25 2008 From: thomascribbs at gmail.com (thomascribbs at gmail.com) Date: Tue, 30 Sep 2008 11:03:25 -0700 (PDT) Subject: IDLE doesn't run on OSX 10.3.9 Message-ID: <82e158c1-960b-4eb4-8f1d-a1e7ab890b90@25g2000hsx.googlegroups.com> Just installed Python 2.5.2 on a PowerPC G4 running OSX 10.3.9 and when clicking on the IDLE icon in the MacPython 2.5 folder nothing happens, program doesn't execute... I've uninstalled, reinstalled over again... I friend of mine just installed the same 2.5.2 download from the Python.org website on OSX 10.4.11 and all went fine...but shouldn't it install on 10.3.9 as well? Anyone have any ideas? Thanks. -Tom From gagsl-py2 at yahoo.com.ar Sat Sep 20 20:06:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 20 Sep 2008 21:06:01 -0300 Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> <Xns9B1FB27C6AC44duncanbooth@127.0.0.1> <c53f8fc8-97a3-45cf-9507-065bb7439272@m36g2000hse.googlegroups.com> <e177ceee-1dad-4858-9c2d-ff6d770d1349@s50g2000hsb.googlegroups.com> Message-ID: <op.uhs08bgfx6zn5v@a98gizw.noga> En Sat, 20 Sep 2008 20:27:41 -0300, Alex Snast <asnast at gmail.com> escribi?: > Another quick question please, is the List data structure just a > dynamic array? If so how can you use static size array, linked list, > AVL trees etcetera. Yes, lists are implemented as dynamic arrays (but you shouldn't care about it). "Textbook" linked lists are good for a CS course, but useless in most usual circumstances (think of memory fragmentation). There are AVL trees implemented in Python, but not built in. Read the Python Tutorial specially this section http://docs.python.org/tut/node7.html You may be interested in the collections module too http://docs.python.org/lib/module-collections.html -- Gabriel Genellina From stefan_ml at behnel.de Tue Sep 2 02:06:35 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 02 Sep 2008 08:06:35 +0200 Subject: python mechanize/libxml2dom question In-Reply-To: <mailman.351.1220326560.3487.python-list@python.org> References: <mailman.351.1220326560.3487.python-list@python.org> Message-ID: <48bcd7eb$0$20713$9b4e6d93@newsspool4.arcor-online.net> bruce wrote: > i've got the following situation, with the following test url: > "http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#". > > i can generate a list of the tables i want for the courses on the page. > however, when i try to create the xpath query, and plug it into the xpath > within python, i'm missing something. if i have a parent xpath query, that > generates a list of results/nodes... how can i then use the individual > parent node, and trigger off of it, to get further information. [code example stripped] You should really use lxml. It has callable XPath objects that feel like Python functions, and its Element objects have a getparent() method that gets you to the parent of the node. Plus, text strings that you get back from an XPath evaluation also have a getparent() method that returns the Element object that holds the text. I think that's what you were looking for. Stefan From afilash at gmail.com Tue Sep 9 01:10:11 2008 From: afilash at gmail.com (abhilash pp) Date: Tue, 9 Sep 2008 10:40:11 +0530 Subject: firefox timestamp In-Reply-To: <ga3dj8$vfg$1@ger.gmane.org> References: <9f9d35df0809072317h49ccec2ep72524f8d4900daa0@mail.gmail.com> <ga3dj8$vfg$1@ger.gmane.org> Message-ID: <9f9d35df0809082210s2d09a9d5rd9256675461f7c28@mail.gmail.com> thanks Fredrik, yeah it works !!! On Mon, Sep 8, 2008 at 8:11 PM, Fredrik Lundh <fredrik at pythonware.com>wrote: > abhilash pp wrote: > > I don't know if this question will fit on this section, >> any way my query is , i have used one script demork.py to extract details >> from Firefox history.dat file >> and now the problem is how to convert the TIMESTAMP given by that to >> normal date and time. >> example timestams are like this, >> >> 1202919771609375 >> 1213874676203125 >> 1215693263859375 >> >> i have used datetime module for this but it gave me error >> > > a quick googling indicates that the file contains microseconds, not > seconds. dividing by 1e6 should do the trick: > > >>> t = 1202919771609375 > >>> datetime.datetime.fromtimestamp(t / 1e6) > datetime.datetime(2008, 2, 13, 17, 22, 51, 609375) > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080909/3ae8deb3/attachment-0001.html> From hniksic at xemacs.org Mon Sep 22 09:29:53 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 22 Sep 2008 15:29:53 +0200 Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: <87myi0z4tq.fsf@mulj.homelinux.net> josh logan <dear.jay.logan at gmail.com> writes: > sorted(P) # throws TypeError: unorderable types Player() < Player() > > The sorted function works when I define __lt__. > I must be misreading the documentation, because I read for the > documentation __cmp__ that it is called if none of the other rich > comparison functions are defined. > Is this a bug in Python 3.0rc1, or am I missing something? What documentation are you referring to, exactly? The whole __cmp__ thing was supposed to be removed from Python 3, so mention of it sounds like a documentation bug. > Secondly, say that we suddenly need another sorting order, where we > want to sort by decreasing score and then by DECREASING last name > (instead of increasing last name, defined above). Now that the > comparison function argument is taken away from the sorted builtin, > how do we accomplish this with the "key" parameter? By calling sort twice on the sequence: lst.sort(key=lambda x: x.score) lst.sort(key=lambda x: x.last_name, reverse=True) As much as I like the key argument, I believe it was a mistake to remove cmp, simply because it was the more general mechanism. Emulating cmp with key is possible, but it requires creating a bunch of objects for each sort. (I'm aware that list.sort caches the calculated keys, but it still has to create as many of them as there are list items.) From code at pizzashack.org Tue Sep 2 17:41:04 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 17:41:04 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i5g2aFol29aU6@mid.uni-berlin.de> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <mailman.370.1220369964.3487.python-list@python.org> <6i5g2aFol29aU6@mid.uni-berlin.de> Message-ID: <20080902214104.GR29228@dragontoe.org> On Tue, Sep 02, 2008 at 06:47:39PM +0000, Marc 'BlackJack' Rintsch wrote: > That's why I think the name `Popen` is not so good for it. Because it > does more than `popen()` and if it is called `Subprocess` or just > `Process` then it would be merely an implementation detail, that the > `popen()` function is called at some point. The module is subprocess, and the class is Popen. The underlying implementation doesn't really matter; the class still does essentally the same as the combination of popen() and pclose(): it opens pipes to a subprocess, and allows the parent to wait until that process has terminated, and closes the pipe(s). The rationale for naming the class Popen is exactly the same as the rationale for naming the analogous functions. Do you think that subprocess.pipe() is not as good a name as subprocess.subprocess()? > If it is at all, because `popen()` on C level can just open a pipe > in *one* direction. That also is not (necessarily) true. Some Unix implementations provide bidirectional implementations of popen(). See, for example, the OS X popen() man page. It's existed in BSD Unix for years... > > Note that in all of these links that talk about popen, the focus is on > > opening pipes or file objects, not on subprocesses: > > > > http://www.opengroup.org/onlinepubs/009695399/functions/popen.html > > http://docs.python.org/lib/os-newstreams.html http://us3.php.net/popen > > http://docs.hp.com/en/B9106-90010/popen.3S.html > > http://www.faqs.org/docs/artu/ch07s02.html > > And all of the links talk about the `popen()` function, > not about the functionality the `Popen` class provides. Which is > much more than that simple pipe `popen()` returns. Well, you're comparing a class to a function, so no surprise there. But it's not really that much more, if you include pclose(). With the exception that it allows you to connect multiple streams instead of only one, and it saves the PID of the child (which for the most part is not especially useful), the functionality is identical. If you actually look at the Python implementation of the subprocess.Popen class, the implementation is essentially identical to the C implementation of the popen() and pclose() functions except that the latter saves the PID returned by the call to fork() in a class attribute, and opens 3 pipes instead of 1. If C's popen() and pclose() functions were written as a C++ class instead of two separate functions, it would look rather a lot like python's subprocess.Popen class. > > The Linux man page unfortunately copies (verbatim) the FreeBSD man > > page, which gets it wrong. You can not open a process, but you > > can definitely open a pipe. > > Ah, when their terminology doesn't match yours, they must get it > wrong. ;-) Nice try... Their terminology doesn't match the original author's. Here's the original AT&T System 7 man page: http://www.freebsd.org/cgi/man.cgi?query=popen&apropos=0&sektion=0&manpath=Unix+Seventh+Edition&format=html When describing what this function does, it states, "It creates a pipe..." Besides which, the BSD folks felt the need to quote "open", indicating that clearly they knew that no process is being "opened" by the function call. You start processes, you don't open them. This should have been a clue to the BSD manual page writer that they had the sense wrong; it's very obviously the pipe that gets opened, not the process. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/3110b0fa/attachment-0001.sig> From tino at wildenhain.de Fri Sep 19 01:11:51 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 19 Sep 2008 07:11:51 +0200 Subject: improving a huge double-for cycle In-Reply-To: <gavaq2$klm$1@ger.gmane.org> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <gavaq2$klm$1@ger.gmane.org> Message-ID: <48D33497.4010403@wildenhain.de> Hi, Terry Reedy wrote: ... > Yes, after figuring out what to do from the original post, I saw yours > and then Pruebono's and decided that since two people had submitted the > jackpot algorithm, I need not say more. I will say this: this solution > amounts to finding equivalence classes (the sets of items with a given > 'key') and then finding the classes (sets) with more than one member. > Defaultdict is great for this. I must say mine works with at least similar performance. Maybe its a timezone issue but I also provided a simple test to my solution. Also I never saw a list where the threading often goes wrong like this here - is there any special setup or is it just peoples MUA which screws up? T. -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080919/591f0c83/attachment-0001.bin> From marco.bizzarri at gmail.com Mon Sep 15 14:26:27 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 15 Sep 2008 20:26:27 +0200 Subject: Zsi interoperability In-Reply-To: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> References: <mailman.1047.1221498380.3487.python-list@python.org> <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <3f0d61c40809151126n791b1ce0ya1e208a075660934@mail.gmail.com> On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel <stefan_ml at behnel.de> wrote: > Mailing List SVR wrote: >> I have to implement a soap web services from wsdl, the server is >> developed using oracle, is zsi or some other python library for soap >> interoperable with oracle soa? > > No idea, but I'd definitely try soaplib before ZSI. > > Stefan I'm working on a project where I need to write a client for SOAP with Attachments; I can see ZSI does not support it; is soaplib any better? Can you argument your suggestion a little more? Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From tjreedy at udel.edu Sun Sep 28 23:56:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 23:56:02 -0400 Subject: closures and dynamic binding In-Reply-To: <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> Message-ID: <gbpjkb$8ct$1@ger.gmane.org> Aaron "Castironpi" Brady wrote: > On Sep 28, 4:47 pm, Terry Reedy <tjre... at udel.edu> wrote: >> Aaron "Castironpi" Brady wrote: >>>>>> inner = lambda: n >> when inner is actually compiled outside of outer, it is no longer a >> closure over outer's 'n' and 'n' will be looked for in globals instead. >> >>>>>> outer = lambda n: inner >>>>>> outer(0) >>> <function <lambda> at 0x00A01170> >>>>>> a=outer(0) >>>>>> b=outer(1) >>>>>> a() >>> Traceback (most recent call last): >>> File "<stdin>", line 1, in <module> >>> File "<stdin>", line 1, in <lambda> >>> NameError: global name 'n' is not defined >>> Why doesn't 'inner' know it's been used in two different scopes, and >>> look up 'n' based on the one it's in? >> That would be dynamic rather than lexical scoping. > > I couldn't find how those apply on the wikipedia website. It says: > "dynamic scoping can be dangerous and almost no modern languages use > it", but it sounded like that was what closures use. Or maybe it was > what 'inner' in Steven's example would use. I'm confused. As I understand it, partly from postings here years ago... Lexical: The namespace scope of 'n' in inner is determined by where inner is located in the code -- where is is compiled. This is Python (and nearly all modern languages). Even without closures, the global scope of a function is the module it is defined in. Dynamic: The namespace scope of 'n' in inner, how it is looked up, is determined by where inner is called from. This is what you seemed to be suggesting -- look up 'n' based on the scope it is *used* in. Even without closures, dynamic scoping would be if the global scope of a function for each call were the module it is called in. tjr From john.m.roach at gmail.com Tue Sep 9 14:44:00 2008 From: john.m.roach at gmail.com (john) Date: Tue, 9 Sep 2008 11:44:00 -0700 (PDT) Subject: F2PY changing integers to arrays??? References: <7d60c85f-12cf-47fc-84c9-58e50cad4eaf@x35g2000hsb.googlegroups.com> <ga6bpa$avj$1@inews.gazeta.pl> Message-ID: <aec39fcc-f860-4344-9cee-b0358728746b@25g2000hsx.googlegroups.com> Hmmm... I didn't even try that... I thought this might have caused problems down the road passing this var to other classes, etc., but i guess not! Thanks. From lamciuloeng at gmail.com Fri Sep 12 00:15:05 2008 From: lamciuloeng at gmail.com (CL (Ciu Loeng) Lam) Date: Fri, 12 Sep 2008 12:15:05 +0800 Subject: Problem on getting date column in SQLObject Message-ID: <b922cb950809112115h63afdcc1l1233e7917cbee43a@mail.gmail.com> Hi,all:I make the SQLObject as the ORM in turbogears ,now I meet a problems on selecting records for a given date . Here is the define for my class: class updateHistory(SQLObject): actionTime = DateTimeCol(default=datetime.now) actionContent = UnicodeCol(length=500,default="") Then how can I get the records during a special time ,for example , from 2008-05-10 to 2008-09-01, It will be very thankful if someone could paste some snippets for this problems. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080912/7a149906/attachment-0001.html> From gagsl-py2 at yahoo.com.ar Tue Sep 23 20:13:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Sep 2008 21:13:27 -0300 Subject: finding domain name References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> Message-ID: <op.uhylkpvex6zn5v@a98gizw.noga> En Tue, 23 Sep 2008 09:37:44 -0300, Bobby Roberts <tchendrix at gmail.com> escribi?: > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/xxxxx/ > > where xxxxx represents the domain name. > > How can I find the domain name of the current url being viewed. That info comes from the "Host" request field, and whether it's available or not depends on the web framework in use; for a plain old CGI script, it depends on the server configuration. Look at the HTTP_HOST environment variable (accessing os.environ, or with the cgi.print_environ() function) -- Gabriel Genellina From To-Email-Use-The-Envelope-Icon at My-Web-Site.com Sun Sep 21 23:01:31 2008 From: To-Email-Use-The-Envelope-Icon at My-Web-Site.com (Jim Thompson) Date: Sun, 21 Sep 2008 20:01:31 -0700 Subject: Milenko Kindl rtegdgd References: <b3a8139e-656c-4451-bbe4-203d48cb3203@d77g2000hsb.googlegroups.com> <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> <HoGdnZmrGszOn0rVnZ2dnUVZ_t3inZ2d@earthlink.com> Message-ID: <vi2ed4t5niveijg7d5e88ia54bchdj2rje@4ax.com> On Sun, 21 Sep 2008 22:26:27 -0400, "Michael A. Terrell" <mike.terrell at earthlink.net> wrote: > >H Vlems wrote: >> >> On 21 sep, 19:48, yuma <yuma400... at yahoo.com> wrote: >> > Milenko Kindl >> > Banja Luka >> > Banjaluka >> > Bihac >> >> Well, that's not C isn't it, more like Snobol or RPG/2 > > > Tidybowl I thought you blanked googlegroups, n'est ce pas ?:-) ...Jim Thompson -- | James E.Thompson, P.E. | mens | | Analog Innovations, Inc. | et | | Analog/Mixed-Signal ASIC's and Discrete Systems | manus | | Phoenix, Arizona 85048 Skype: Contacts Only | | | Voice:(480)460-2350 Fax: Available upon request | Brass Rat | | E-mail Icon at http://www.analog-innovations.com | 1962 | I love to cook with wine Sometimes I even put it in the food From george.sakkis at gmail.com Fri Sep 26 22:09:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 26 Sep 2008 19:09:42 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <dZOdnQINKORUEUDVnZ2dnUVZ_rvinZ2d@posted.usinternet> Message-ID: <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> On Sep 26, 9:30?pm, Grant Edwards <gra... at visi.com> wrote: > On 2008-09-26, nntpman68 <news1... at free.fr> wrote: > > > Hm, > > > I guess you just filter mailing lists and can do nothing about the > > newsgroup if I'm fetching via the nntp server of my ISP itself, right? > > I read the group via NNTP, and I find that blocking all > articles posted from google.groups gets rid of all of the spam. ... along with a far from trivial (I guess) percentage of non-spam, such as this post. And-nothing-of-value-was-lost'ly yrs, George From gagsl-py2 at yahoo.com.ar Thu Sep 25 16:35:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 25 Sep 2008 17:35:27 -0300 Subject: what does "python -i" use as input stream (stdin)? References: <cc38d75f0809250549u2acff662n765bc1c2990d0e78@mail.gmail.com> Message-ID: <op.uh10tdgcx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 25 Sep 2008 09:49:31 -0300, Almar Klein <almar.klein at gmail.com> escribi?: > Hi, > I want to start "python -i" from a subprocess and change its stdin > stream, > so I get control over the commands I feed the interpreter. > > I thought just changing sys.stdin to my custom file-like object would > suffice, but this does not work. Neither does changing sys.__stdin__. > > I guess the interpreter got a reference to the original stdin (the Pipe) > before > I could change it, and is using that instead of sys.stdin. > > Any thoughts how I can get the interpreter to use MY custom stream? Use subprocess.PIPE Usually the tricky part is to figure out exactly whether there is more input or not. With Python it's easy, use the ps1 prompt. --- begin --- import sys import subprocess def read_until_prompt(stdout): while True: line = stdout.read(4) if line==sys.ps1: yield line return else: line += stdout.readline() yield line def print_output(stdout): for line in read_until_prompt(stdout): sys.stdout.write(line) s = subprocess.Popen(["python", '-i'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) stdout = s.stdout stdin = s.stdin print_output(stdout) stdin.write("dir()\n") print_output(stdout) stdin.write("def foo(x):\n") stdin.write(" for i in range(x):\n") stdin.write(" print i\n") stdin.write("\n") stdin.write("foo(5)\n") print_output(stdout) stdout.close() stdin.close() s.wait() print "bye" --- begin --- -- Gabriel Genellina From skip at pobox.com Sat Sep 13 18:34:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Sep 2008 17:34:07 -0500 Subject: testing if another instance of a script is already running In-Reply-To: <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> References: <mailman.911.1221221070.3487.python-list@python.org> <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> Message-ID: <18636.16351.501251.683956@montanaro-dyndns-org.local> >> I don't want to handle writing of a PID file because it is too >> Unix/Linux specific way to do this, and I need to keep the code to be >> cross-platform. >> >> I think the better way to achieve this is to use some process >> control, but I'm a neebie and I don't see how to do this in a safe >> and clean way. Aaron> You could use msvcrt.locking, and just lock the script file. I Aaron> am not sure about this. If you want a cross-platform solution, you might try the lockfile module instead: http://pypi.python.org/pypi/lockfile Skip From castironpi at gmail.com Fri Sep 26 14:04:11 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 11:04:11 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> Message-ID: <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> On Sep 26, 11:43?am, "Tim Rowe" <digi... at gmail.com> wrote: > 2008/9/26 Steven D'Aprano <st... at remove-this-cybersource.com.au>: > > > I don't have any objective numbers, but subjectively it seems to me that > > the number of spams is significantly higher, but not so high as to be a > > major nuisance. > > I consider *any* spam to be a major nuisance, but I don't see them as > being the fault of python-list which seems to do a pretty good job of > blocking them > > -- > Tim Rowe Is it worth mentioning that they come from the same author in a short period of time? Maybe that could bump up the score a notch. I think in June and July they were selling watches a lot which I haven't noticed recently. From fredrik at pythonware.com Wed Sep 17 12:37:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 18:37:31 +0200 Subject: python-mode problem, doesnt load whole module? In-Reply-To: <9b26d9fd-3fe2-4d58-acce-015923d31b50@d1g2000hsg.googlegroups.com> References: <9b26d9fd-3fe2-4d58-acce-015923d31b50@d1g2000hsg.googlegroups.com> Message-ID: <garbob$je7$2@ger.gmane.org> cnb wrote: >>>> a = parsing.unserialize("C:/users/saftarn/desktop/twok.txt") > Traceback (most recent call last): > File "C:\Python25\lib\pickle.py", line 1126, in find_class > klass = getattr(mod, name) when reporting a traceback, please include the error message that follows after the stack trace. </F> From deets at nospam.web.de Wed Sep 3 10:42:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 16:42:11 +0200 Subject: properties setting each other In-Reply-To: <mailman.427.1220450289.3487.python-list@python.org> References: <mailman.427.1220450289.3487.python-list@python.org> Message-ID: <6i7m23Fpc39rU2@mid.uni-berlin.de> mk schrieb: > Hello everyone, > > I try to set two properties, "value" and "square" in the following code, > and arrange it in such way that setting one property also sets another > one and vice versa. But the code seems to get Python into infinite loop: > > >>> import math > >>> class Squared2(object): > > def __init__(self, val): > self._internalval=val > self.square=pow(self._internalval,2) > > def fgetvalue(self): > return self._internalval > > def fsetvalue(self, val): > self._internalval=val > self.square=pow(self._internalval,2) > > value = property(fgetvalue, fsetvalue) > > def fgetsquare(self): > return self.square > def fsetsquare(self,s): > self.square = s > self.value = math.sqrt(self.square) > > square = property(fgetsquare, fsetsquare) > > > >>> a=Squared2(5) > > Traceback (most recent call last): > File "<pyshell#11>", line 1, in <module> > a=Squared2(5) > File "<pyshell#10>", line 5, in __init__ > self.square=pow(self._internalval,2) > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > self.square = s > File "<pyshell#10>", line 19, in fsetsquare > > ... > > Is there a way to achieve this goal of two mutually setting properties? > Better to make the getter for square return the square of value, and the setter of square compute the root & set that. Like this: class Squared2(object): def __init__(self, value): self.value = value @apply def squared(): def fset(self, squared): self.value = math.sqrt(squared) def fget(self): return self.value ** 2 return property(**locals()) Diez From sjmachin at lexicon.net Wed Sep 10 22:02:50 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Sep 2008 19:02:50 -0700 (PDT) Subject: Logix - gone? References: <276719.72706.qm@web95107.mail.in2.yahoo.com> <mailman.835.1221086049.3487.python-list@python.org> <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> <mailman.840.1221093291.3487.python-list@python.org> Message-ID: <dbebf54c-5e7b-4b79-96f9-5766138ce783@p10g2000prf.googlegroups.com> On Sep 11, 10:34?am, Stephen Johnson <dior... at gmail.com> wrote: > I found Logix (http://livelogix.net/logix/) while looking for ? > something else and thought it looked like a very interesting project. ? > Unfortunately, the blog, mailing list, and Trac links are broken, and ? > the contact email address bounces. > > I am interested in playing with it and working on it if the original ? > author has dropped it. Does anyone know where I could get the source? Ummmm .... try the download link; it worked for me. > > I am asking this here because Logix compiles to Python bytecode, and ? > the author announced to this list at one time. Tom Locke, if you're ? > out there... > > -Steve Johnson (www.steveasleep.com) From marco.wahl at novatec-gmbh.de Thu Sep 18 07:37:05 2008 From: marco.wahl at novatec-gmbh.de (Marco Wahl) Date: Thu, 18 Sep 2008 13:37:05 +0200 Subject: how can I use a callable object as a method References: <gatadc$s6f$1@inews.gazeta.pl> Message-ID: <u63otsn1a.fsf@novatec-gmbh.de> Piotr Sobolewski <NIE_DZIALA at gazeta.pl> writes: > I would like to use a callable object as a method of a class. So, when I > have such normal class: > > I want to change it to something like that: > > class add: > def __call__(self, another_self): > return another_self.version > > class f: > version = 17 > a = add() > > f1 = f() > print f1.a() > > However, the second version does not work. I think I understand why. That's > because "a" inside f1 is not a function (but an object). So f1.a is not a > method. So when I do f1.a(), the implicit argument self is not passed. > > Q1: Am I right? Is this the problem? > Q2: What can I do to make it work? Use the right argument for the call. Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> class add: def __call__(self, another_self): return another_self.version ... ... ... >>> class f: version = 17 a = add() ... ... ... >>> f1 = f() >>> f1 <__main__.f instance at 0x00A805D0> >>> f1.a <__main__.add instance at 0x00A80DA0> >>> f1.a() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: __call__() takes exactly 2 arguments (1 given) >>> f1.a(f1) 17 >>> HTH From fredrik at pythonware.com Fri Sep 5 13:43:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 19:43:14 +0200 Subject: Python and Cyrillic characters in regular expression In-Reply-To: <cb6b6ad1-1070-4b5c-8470-86815ce1beea@79g2000hsk.googlegroups.com> References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> <mailman.497.1220550833.3487.python-list@python.org> <cb6b6ad1-1070-4b5c-8470-86815ce1beea@79g2000hsk.googlegroups.com> Message-ID: <g9rr3k$uo0$1@ger.gmane.org> phasma wrote: > string = u"??????" > (u'\u041f\u0440\u0438\u0432\u0435\u0442',) > > string = u"Hi.??????" > (u'Hi',) the [\w\s] pattern you used matches letters, numbers, underscore, and whitespace. "." doesn't fall into that category, so the "match" method stops when it gets to that character. maybe you could use re.sub or re.findall? >>> # replace all non-alphanumerics with the empty string >>> re.sub("(?u)\W+", "", string) u'Hi\u041f\u0440\u0438\u0432\u0435\u0442' >>> # find runs of alphanumeric characters >>> re.findall("(?u)\w+", string) [u'Hi', u'\u041f\u0440\u0438\u0432\u0435\u0442'] >>> "".join(re.findall("(?u)\w+", string)) u'Hi\u041f\u0440\u0438\u0432\u0435\u0442' (the "sub" example expects you to specify what characters you want to skip, while "findall" expects you to specify what you want to keep.) </F> From siona at chiark.greenend.org.uk Wed Sep 3 10:06:54 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 03 Sep 2008 15:06:54 +0100 (BST) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <omp*-z6ls@news.chiark.greenend.org.uk> <bearophileHUGS at lycos.com> wrote: >Empty Python lists [] don't know the type of the items it will >contain, so this sounds strange: > >>>> sum([]) >0 >>> help(sum) sum(...) sum(sequence, start=0) -> value >>> sum(range(x) for x in range(5)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'list' >>> sum((range(x) for x in range(5)), []) [0, 0, 1, 0, 1, 2, 0, 1, 2, 3] ... so the list might not know what type it contains, but sum does. And if you don't tell it, it makes a sensible guess. And it *is* a case where refusing the temptation to guess is the wrong thing: how many times would you use sum to do anything other than sum numeric values? And how tedious would it be to have to write sum(..., 0) for every other case? Particularly bearing in mind: >>> sum(["a", "b"], "") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: sum() can't sum strings [use ''.join(seq) instead] -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From kyosohma at gmail.com Tue Sep 9 16:08:13 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 9 Sep 2008 13:08:13 -0700 (PDT) Subject: Iowa Python Users Group - First Meeting Message-ID: <9f34ca04-5802-42cf-a4d2-24875ad0d790@a1g2000hsb.googlegroups.com> Hi all, The first meeting date for the Iowa Python Users Group has been decided. Here are the details: ------------------------------------------------------------ Time / Date: Wednesday, Sept. 24 from 7-9 p.m. Location: Marshall County Sheriff's Office, 3rd floor 2369 Jessup Ave Marshalltown, IA 50158 Unofficial website: http://www.ipug.pythonlibrary.org ------------------------------------------------------------ Don't know how to get there? Check out maps.yahoo.com or maps.google.com. The Sheriff's Office is not actually in Marshalltown. If you take Highway 30 East, towards Marshalltown you'll see it on your left. There's a large water tower there and the building is a rusty red color. There are some signs for a Tractor convention there as well. If you're coming from the other direction, then skip ALL the exits and keep driving until the lanes go from 4 lanes to 2. It should be the second right after that. I am still developing the agenda for our first meeting, but here are some of the things we're going to discuss: - What day really works best for meeting? (if you can't make the first one, you can email me your votes!) - Figure out what domain name our group should have - Decide on what Python web framework to use to create said site (which will be a group project) - Try to come up with what format we want our meetings to take. Plone and Zope users are welcome. In fact, anyone who is interested in Python (regardless of their experience with it) is welcome to come. Let your Iowan Python friends know. Questions or ideas? Send them to me. Thanks! ------------------- Mike Driscoll email: mike (at) pythonlibrary (dot) org Blog: http://blog.pythonlibrary.org Python Extension Building Network: http://www.pythonlibrary.org From d3vvnull at gmail.com Sun Sep 28 19:52:14 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sun, 28 Sep 2008 18:52:14 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <gbooat$dh5$1@ger.gmane.org> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> <48DF63B2.2020408@wildenhain.de> <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> <gbooat$dh5$1@ger.gmane.org> Message-ID: <170543c70809281652s7d529428ibe51c1a489151863@mail.gmail.com> Sadly no. There is no utterance too inconsequential. On Sun, Sep 28, 2008 at 3:10 PM, Steve Holden <steve at holdenweb.com> wrote: > Michael Mabin wrote: > > Tino, dude, I'm afraid I lied about my previous post being the last > > word. There are some things you said here that must be addressed. > > Good grief, is there no utterance so inconsequential that you will walk > away from it without yet another round of retaliation? > > I believe that all people were trying to convey is: > > 1. There are some data patterns that cannot be directly incorporated > into SQL statements without additional processing, regardless of whether > the "intention" of the data's originator is malevolent. A good example > is a string value containing an apostrophe, which in most SQL > implementations you can escape by preceding the apostrophe with another > apostrophe. > > 2. SQL drivers in Python are written so that no matter what the values > of the data may be, and no matter which backend they implement, data may > safely be passed as a tuple to a parameterized statement without such > cleansing because the drivers are written to ensure "dangerous" values > are appropriately handled. > > Having said all that, if you are positive none of your string data > contains apostrophes you are, of course, free to build SQL statements > yourself - though doing so will on some systems lose you the speed > advantages offered by "prepared statements". Similarly, if you are *not* > positive of the quality of your data you are free to do the escaping in > your logic rather than using parameterized queries. This could be called > "buying a dog and barking yourself". > > regards > Steve > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080928/dc2cc944/attachment-0001.html> From sniipe at gmail.com Mon Sep 1 08:57:37 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Mon, 1 Sep 2008 05:57:37 -0700 (PDT) Subject: How to print first(national) char from unicode string encoded in utf-8? Message-ID: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> Hi, I have a problem with unicode string in Pylons templates(Mako). I will print first char from my string encoded in UTF-8 and urllib.quote(), for example string '?ukasz': ${urllib.unquote(c.user.firstName).encode('latin-1')[0:1]} and I received this information: <type 'exceptions.UnicodeDecodeError'>: 'utf8' codec can't decode byte 0xc5 in position 0: unexpected end of data When I change from [0:1] to [0:2] everything is ok. I think it is because of unicode and encoding utf-8(2 bytes). How to resolve this problem? Best regards From st1999 at gmail.com Sun Sep 28 15:27:30 2008 From: st1999 at gmail.com (robean) Date: Sun, 28 Sep 2008 12:27:30 -0700 (PDT) Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> <mailman.1635.1222629122.3487.python-list@python.org> Message-ID: <d127e341-c16d-4ef9-b1de-b9076cefdcb4@i20g2000prf.googlegroups.com> On Sep 28, 12:11?pm, "Chris Rebert" <c... at rebertia.com> wrote: > On Sun, Sep 28, 2008 at 11:03 AM, robean <st1... at gmail.com> wrote: > > Hi everyone, > > > I have a question about using urllib2. > > > I like urllib2 better than urllib at least in part because it has more > > elaborate support for handling errors: there is built in support for > > URLError (for faulty urls) and HTTPError (for http errors that might > > originate from, say, passing an invalid stock-ticker in the program > > below). ?However I can get neither to work. ?I'm attaching below the > > (very short) code: can anyone point out what I'm doing wrong? > > > Now, if I replace the URLError and HTTPError with IOError (the class > > from which both URLError and HTTPError inherit), the program works > > fine. Why is it that I can call the generic IOError class, but none of > > the Error classes derived from that? These are clearly defined in the > > urllib2 manual. Very confused... > > > Here's the code: > > > import urllib2 > > > # read stock information from yahoo finance for Traget (TGT) > > goodTicker = 'TGT' # program works with this > > badTicker = 'TGTttttttt' # python doesn't understand either HTTPError > > or URLError with this > > > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > > try: > > ? ? ? ?handle = urllib2.urlopen(url) > > > # this does not work > > except HTTPError, e: > > ? ? ? ?print "There was an http error" > > ? ? ? ?print e > > > # this also does not work > > except URLError, e: > > ? ? ? ?print "There is a problem with the URL" > > ? ? ? ?print e > > ? ? ? ?exit(1) > > > #this works > > except IOError, e: > > ? ? ? ?print "You have an IOError" > > ? ? ? ?print e > > > text = handle.readlines()[:20] > > for line in text: > > ? ? ? ?print line > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > My Python begs to differ: > > #tmp.py > import urllib2 > > badTicker = 'TGTttttttt' > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > try: > ? ? handle = urllib2.urlopen(url) > > except urllib2.HTTPError, e: > ? ? print "There was an http error" > ? ? print e > > except urllib2.URLError, e: > ? ? print "There is a problem with the URL" > ? ? print e > > except urllib2.IOError, e: > ? ? print "You have an IOError" > ? ? print e > > #in the shell > $ python -V > Python 2.5.1 > $ python Desktop/tmp.py > There was an http error > HTTP Error 404: Not Found > > Are you using an outdated version of Python perhaps? > > Regards, > Chris > > -- > Follow the path of the Iguana...http://rebertia.com Then I expect that it is most likely my version of python that is causing the problem. I'm using 2.5.2. From aonlazio at gmail.com Mon Sep 15 17:51:36 2008 From: aonlazio at gmail.com (AON LAZIO) Date: Mon, 15 Sep 2008 17:51:36 -0400 Subject: The need to use *arg,**kwd Message-ID: <f9e39bbc0809151451j15604641gfc1a10832131c24c@mail.gmail.com> Hi, Pythoners. I'd like to know when it is necessary to use *arg or **kwd in the program. And when it is 'ok' to use normal form of function argument? Thanks in advance. Aonlazio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/8d26d7ab/attachment-0001.html> From dmitrey.kroshko at scipy.org Thu Sep 18 05:03:17 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Thu, 18 Sep 2008 02:03:17 -0700 (PDT) Subject: how to do easy_install to source code, not egg? Message-ID: <499dc07d-261e-4c34-9743-28b55c7945bd@a70g2000hsh.googlegroups.com> Hi all, how to do easy_install <some package> to source code, not egg? (I don't mean "develop" option, it shouldn't call compiled egg-file). Thank you in advance, Dmitrey. From gminick at bzt.bzt Tue Sep 2 10:30:10 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Tue, 2 Sep 2008 14:30:10 +0000 (UTC) Subject: Storing Subprocess Results References: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> Message-ID: <g9jilh$s90$1@inews.gazeta.pl> On Tue, 2 Sep 2008 07:16:21 -0700 (PDT), topazcode wrote: > I am using the subprocess module to run some shell commands on a Linux > system: > > import subprocess > output = subprocess.call('''ssh server1 "uptime"''', shell=True) > > The above assigns the output variable with a return code, i.e. 0 in > this case. How can I actually capture the data returned from > subprocess.call, rather than just the return code? Use subprocess.Popen instead of call. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From srad at inbox.lv Sat Sep 6 06:31:20 2008 From: srad at inbox.lv (Aigars Aigars) Date: Sat, 06 Sep 2008 13:31:20 +0300 Subject: Cancel instance create Message-ID: <1220697080.48c25bf890ade@www.inbox.lv> Good day, I want MyClass to perform some tests and if them fail, I do not want instance to be created. But in code I wrote instance is created and also has parameters, that it should not have in case of tests failure. Is there a way to perform tests in MyClass.__init__ and set instance to None without any parameters? I do not want che code outside MyClass.__init__ to know anything about tests performed, and make decision to allow or prevent instance creation. The code I wrote is: ****************************************************** class MyClass(): def __init__(self): self.param = "spam" Test = False if Test == True: print "Creating instance..." return else: print "Instance creation not allowed..." self = None return None a = MyClass() print a print a.param ************************************************* Thanks, Aigars -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080906/cff73ef6/attachment-0001.html> From tjreedy at udel.edu Tue Sep 30 15:07:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 15:07:08 -0400 Subject: Comparing float and decimal In-Reply-To: <77c70884-4667-4f62-b1e9-ad235855a3d5@z72g2000hsb.googlegroups.com> References: <mailman.1400.1222168827.3487.python-list@python.org> <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> <op.uh9wgumox6zn5v@gabriel2.softlabbsas.com.ar> <mailman.1729.1222762885.3487.python-list@python.org> <77c70884-4667-4f62-b1e9-ad235855a3d5@z72g2000hsb.googlegroups.com> Message-ID: <gbttcr$ghv$1@ger.gmane.org> Mark Dickinson wrote: > On Sep 30, 9:21 am, Terry Reedy <tjre... at udel.edu> wrote: >> If no one beats me to it, I will probably file a bug report or two, but >> I am still thinking about what to say and to suggest. > > I can't see many good options here. Some possibilities: Thanks for responding. Agreeing on a fix would make it more likely to happen sooner ;-) > (0) Do nothing besides documenting the problem > somewhere (perhaps in a manual section entitled > 'Infrequently Asked Questions', or > 'Uncommon Python Pitfalls'). I guess the rule is > simply that Decimals don't mix well with other > numeric types besides integers: if you put both > floats and Decimals into a set, or compare a > Decimal with a Fraction, you're asking for > trouble. I suppose the obvious place for such > a note would be in the decimal documentation, > since non-users of decimal are unlikely to encounter > these problems. Documenting the problem properly would mean changing the set documentation to change at least the definitions of union (|), issubset (<=), issuperset (>=), and symmetric_difference (^) from their current math set based definitions to implementation based definitions that describe what they actually do instead of what they intend to do. I do not like this option. > (1) 'Fix' the Decimal type to do numerical comparisons > with other numeric types correctly, and fix up the > Decimal hash appropriately. (1A) All that is needed for fix equality transitivity corruption and the consequent set/dictview problems is to correctly compare integral values. For this, Decimal hash seems fine already. For the int i I tried, hash(i) == hash(float(i)) == hash(Decimal(i)) == hash(Fraction(i)) == i. It is fine for transitivity that all fractional decimals are unequal to all fractional floats (and all fractions) since there is no integer (or fraction) that either is equal to, let alone both. This is what I would choose unless there is some 'hidden' problem. But it seem to me this should work: when a float and decimal are both integral (easy to determine) convert either to an int and use the current int-whichever comparison. > (2) I wonder whether there's a way to make Decimals > and floats incomparable, so that an (in)equality check > between them always raises an exception, and any > attempt to have both Decimals and floats in the same > set (or as keys in the same dict) also gives an error. > (Decimals and integers should still be allowed to > mix happily, of course.) But I can't see how this could > be done without adversely affecting set performance. I pretty strongly believe that equality checks should always work (at least in Python as delivered) just as boolean checks should (and do). > Option (1) is certainly technically feasible, but I > don't like it much: it means adding a whole load > of code to the Decimal module that benefits few users > but slows down hash computations for everyone. > And then any new numeric type that wants to fit in > with Python's rules had better worry about hashing > equal to ints, floats, Fractions, complexes, *and* > Decimals... I believe (1A) would be much easier both to implement and for new numeric types. > > Option (2) appeals to me, but I can't see how to > implement it. > > So I guess that just leaves updating the docs. > Other thoughts? (3) Further isolate decimals by making decimals also unequal to all ints. Like (1A), this would easily fix transitivity breakage, but I would consider the result less desirable. My ranking: 1A > 3 > 0 > 2. I might put 1 between 1A and 3, but I am not sure. > Mark Terry Jan Reedy From logan.johnny11 at gmail.com Thu Sep 25 18:52:19 2008 From: logan.johnny11 at gmail.com (logan.johnny11 at gmail.com) Date: Thu, 25 Sep 2008 15:52:19 -0700 (PDT) Subject: Milenko Kindl bnvnvnvb Message-ID: <7f0bb73a-bbef-40cc-901c-22220cdf6a3b@a18g2000pra.googlegroups.com> NEW YORK - Financial markets grew more upbeat Thursday as political leaders said they struck an agreement in principle on a massive spending plan to revive the crippled financial system. The Dow Jones industrial average jumped about 200 points on optimism about the bailout, and demand for safe-haven assets remained high but eased slightly as some investors placed bets that a deal would help unclog credit markets. ADVERTISEMENT Stock market investors got a lift when key lawmakers said they would present the $700 billion plan to the Bush administration and hoped for a vote by both houses of Congress within days. Still, some resistance remained from House Republicans as the closing bell on Wall Street rang ahead of a meeting of congressional leaders at the White House. And after the close of trading, it was clear that plan could still face some obstacles. Stock futures weakened, signaling a lower open Friday, after Sen. Richard Shelby, the top Republican on the Banking Committee, left the White House meeting and said the announced deal "is, obviously, no agreement." Trading that has been difficult for more than a week is likely to remain so in the coming days. "The market's going to experience volatility as the terms become known," said Doug Roberts, chief investment strategist at Channel Capital Research. Treasury Secretary Henry Paulson and Federal Reserve Chairman Ben Bernanke urged lawmakers Tuesday and Wednesday to quickly sign off on the plan, which they said would help prop up the economy by removing billions of dollars in risky mortgage-related assets from financial firms' balance sheets. Fear of heavy losses on these assets has made banks hesitant to extend credit, which in turn threatens the overall economy by making it harder and more expensive for businesses and consumers to borrow money. President Bush highlighted what he sees as the urgency in a national address Wednesday night. Major elements are still being worked out, including how to phase in the mammoth cost of the package and whether the government will get an ownership stake in troubled companies. Alan Lancz, director at investment research group LanczGlobal, said stock market investors were encouraged that the rescue looked more likely than it had earlier in the week. He said the move could help unclog credit markets by allowing banks and investors to place values on assets tied to mortgages. "How do you establish a floor? Well, this is the bazooka. This is how you establish a floor," he said of the plan's goal of buying up the toxic debt. Still, some investors had their doubts. Demand eased but remained high for the 3-month Treasury bill, considered the safest short-term investment. Its yield rose to 0.72 percent from 0.49 percent late Wednesday. That means investors are still willing to earn the slimmest of returns in exchange for a safe place to put their money. The yield on the benchmark 10-year Treasury note, which moves opposite its price, rose to 3.84 percent from 3.81 late Wednesday. The Dow rose 196.89, or 1.82 percent, to 11,022.06. The gain helped erase some of the losses from heavy selling earlier in the week, though the blue chips still remain down by more than 360 points, or 3.2 percent. Broader stock indicators also rose Thursday. The Standard & Poor's 500 index advanced 23.31, or 1.97 percent, to 1,209.18 and the Nasdaq composite index rose 30.89, or 1.43 percent, to 2,186.57. Advancing issues outnumbered decliners by nearly 3 to 1 on the New York Stock Exchange, where consolidated volume came to 5.73 billion shares, compared with 4.66 billion traded Wednesday. Roberts noted that the market's back-and-forth moves of late might be unnerving for investors but ultimately can leave stocks with little to show for all the volatility. "Most of this is just oscillating around a straight line," he said, noting that last week's huge daily moves, which also included triple- digit moves in the Dow, left stocks largely unchanged for the week. The dollar was mixed against other major currencies Thursday, while gold prices fell. Light, sweet crude for November delivery rose $2.29 to settle at $108.02 a barrel on the New York Mercantile Exchange. Meanwhile, disappointing readings on employment, housing and demand for big-ticket manufactured goods, as well as a sobering forecast from General Electric Co., underscored the difficulties facing the economy. The Labor Department said the number of people seeking unemployment benefits increased by 32,000 to a seasonally adjusted 493,000 last week ? the highest level in seven years and well above analysts' expectations of 445,000. Hurricanes Ike and Gustav added about 50,000 new claims in Louisiana and Texas, the department said. The Commerce Department said sales of new homes fell sharply in August to the slowest pace in 17 years. The average sales price also fell by the largest amount on record. New homes sales dropped by 11.5 percent in August to a seasonally adjusted annual sales rate of 460,000 units, the slowest sales pace since January 1991. The department also said orders for expensive manufactured goods sank in August by the largest amount in seven months as demand for both airplanes and cars sank. Durable goods orders fell by 4.5 percent last month, far worse than the 1.6 percent decline that economists expected and the biggest drop since a 4.7 percent fall in January. GE lowered its forecast for third-quarter and full-year earnings, citing unprecedented weakness and volatility in the financial services markets. The stock, which had declined in the early going, finished up $1.09, or 4.4 percent, to $25.68 alongside the gains in the broader market. The Russell 2000 index of smaller companies rose 7.97, or 1.14 percent, to 705.74. Overseas, Japan's Nikkei stock average fell 0.90 percent. Britain's FTSE 100 rose 1.99 percent, Germany's DAX index added 1.99 percent, and France's CAC-40 jumped 2.73 percent. Milenko Kindl Banja Luka Banjaluka Bihac From bearophileHUGS at lycos.com Fri Sep 26 16:58:03 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 26 Sep 2008 13:58:03 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> <48c6380b$0$17080$426a34cc@news.free.fr> <mailman.741.1220976622.3487.python-list@python.org> <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> <mailman.1557.1222457112.3487.python-list@python.org> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> Message-ID: <33572504-ae97-4e8f-a1cf-c06b0522bf74@73g2000hsx.googlegroups.com> bearophile: > # searching > m, i = 0, 0 ... > i += 1 The name 'i' can be removed, sorry. Bye, bearophile From peter.georgeson at gmail.com Thu Sep 11 09:35:32 2008 From: peter.georgeson at gmail.com (Peter Georgeson) Date: Thu, 11 Sep 2008 06:35:32 -0700 (PDT) Subject: Python and Open Office References: <a9f39a410809101304j592cb7actc1f95882f8fe632c@mail.gmail.com> <mailman.826.1221077307.3487.python-list@python.org> <ga9cps$mnt$1@theodyn.ncf.ca> Message-ID: <056cba0b-6c6e-4066-951c-3e97266d93d4@r15g2000prd.googlegroups.com> On Sep 11, 7:04?am, "Colin J. Williams" <c... at ncf.ca> wrote: > Marco Bizzarri wrote: > > On Wed, Sep 10, 2008 at 10:04 PM, Greg Lindstrom <gslindst... at gmail.com> wrote: > >> Hello, > > >> I would like to create and manipulate Open Office documents using Python. ?I > >> have found then UNO Python page and odfpy modules which seem to be exactly > >> what I need. ?The odfpy manual is, to me, a confusing list of objects and > >> methods (it's an impressive list!), but does not have much in the way of how > >> to use them. ?For example, I can open a spreadsheet and create new pages > >> (there's a nice example near the back of the manual) but I can't figure out > >> how to open an existing spreadsheet and list the names of the individual > >> sheets ("tabs"). > > >> I have written an application that access Microsoft Excel and creates > >> reports for work, but would like to create an Open Source version using Open > >> Office and release it to the community (and maybe get a talk at PyCon :-). > > >> Is there someone here who can help me out, or is there an appropriate > >> mailing list for me to join? > > > Ciao, Greg. > > > you should check with the openoffice.org mailing list; I think what > > you are looking for is the api mailing list for openoffice; you could > > try to get the OpenOffice.org developers guide and the SDK, and check > > it (but it is not a little work) > > > Regards > > Marco > > >> Thanks > > >> --greg > > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > Greg, > > If you follow this up, I hope that you > will post info to c.l.p > and let us know whether the UNO > interface is Python 2.5 compatible. > > The last time I looked it was set for > 2.3 or 2.4. > > Colin W I've recently been working on interfacing with OpenOffice via UNO with Python. I can confirm that unfortunately, the PyUNO interface presently (OpenOffice 2.4) is built with Python 2.3... so to use the UNO interface from Python you have to write a separate script to run in the OpenOffice Python 2.3 environment. Apparently someone is working on rebuilding the PyUNO library for Python 2.5 but there's no timeframe for when that might be included with the OpenOffice distribution. You could try building PyUNO with Python 2.5 yourself, I'm sure I came across instructions somewhere on the OpenOffice developer website... I've not used odfpy so don't know how it compares in terms of degree of difficulty to UNO. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 08:14:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 14:14:53 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: <mailman.1358.1222081500.3487.python-list@python.org> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> Message-ID: <48d78c3c$0$6998$426a74cc@news.free.fr> Tim Rowe a ?crit : > 2008/9/22 Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid>: >> Steven D'Aprano a ?crit : >>> On Mon, 22 Sep 2008 10:11:58 +0200, Bruno Desthuilliers wrote: >>> >>>> Steven D'Aprano a ?crit : >>>>> I have a class which is not intended to be instantiated. Instead of >>>>> using the class to creating an instance and then operate on it, I use >>>>> the class directly, with classmethods. Essentially, the class is used >>>>> as a function that keeps state from one call to the next. > > Sounds to me like a functor, aka a function object: > http://en.wikipedia.org/wiki/Function_object > Ok, then the simple solution is to implement a callable type (__call__ method), possibly with appropriate support for the descriptor protocol if it's meant to be usable as a method. From akineko at gmail.com Tue Sep 2 11:38:10 2008 From: akineko at gmail.com (akineko) Date: Tue, 2 Sep 2008 08:38:10 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> <mailman.346.1220316770.3487.python-list@python.org> <d574e882-8cbf-40d9-9827-11307c773581@x16g2000prn.googlegroups.com> <mailman.348.1220319291.3487.python-list@python.org> <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> <mailman.350.1220326130.3487.python-list@python.org> <e79199b2-627b-4fc1-8772-1a33d89b1380@x16g2000prn.googlegroups.com> <mailman.364.1220359583.3487.python-list@python.org> Message-ID: <82face7d-910c-4b48-8a30-c18e81fb68aa@a18g2000pra.googlegroups.com> On Sep 2, 5:46 am, "Guilherme Polo" <ggp... at gmail.com> wrote: > Did you even try creating a checkbutton with indicatoron=False ? You > could get surprised. I didn't. My perception of checkbutton was a button with a check. So, I tried as you suggested. Yes, you are right. It is almost what I wanted (sticky behaviour). By ignoring the ButtonRelease and Leave events, yes, it can perfectly meet my requirements. As checkbutton has deselect() method, this is a better approach, I have to admit. Thank you for showing me the correct way to implement. Aki- From roy at panix.com Tue Sep 23 22:47:35 2008 From: roy at panix.com (Roy Smith) Date: Tue, 23 Sep 2008 22:47:35 -0400 Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <ee44675b-04ad-48b3-8eed-629ebb10d616@z66g2000hsc.googlegroups.com> Message-ID: <roy-58D7A8.22473523092008@news.panix.com> "Aaron \"Castironpi\" Brady" <castironpi at gmail.com> wrote: > You're out of options. You have to express it somehow. How about: Assignith z the value of x if the value of b is such that it is true, else assignith it the value of y. Assignith z not the value of w, nor the value of v, lest you raise NameError upon thy stack trace. From george.sakkis at gmail.com Sun Sep 28 14:08:43 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 28 Sep 2008 11:08:43 -0700 (PDT) Subject: destructor not called References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> Message-ID: <3dec57f0-c829-4420-b36d-58e21c564053@k37g2000hsf.googlegroups.com> On Sep 28, 12:00?pm, Marcin201 <marcin... at gmail.com> wrote: > I have a class which uses a temporary directory for storing data. ?I > would like that directory to be removed when the class is no longer > used. ?I have tried removing the temporary directory from the class > destructor, however, it was never called. ?After I while I traced the > problem to the class having a reference to it's own function. ?Here is > a simplified model. > > test.py > class Foo: > ? ? def __init__(self): > ? ? ? ? print "Hello" > ? ? ? ? self.f = self.fxn > > ? ? def __del__(self): > ? ? ? ? print "Bye" > > ? ? def fxn(self): > ? ? ? ? print "function" > > a = Foo() > > running python test.py I get > Hello > > Is this an expected behavior or a bug in python? ?If this is expected > any suggestions for working around this. ?I would like to avoid having > to call the destructor explicitly. Others have already replied to your main question; in short you shouldn't rely on __del__ being called. Regardless, is there a (good) reason for having an instance reference to the method ? Without further information, that seems like a code smell. George From mr.spoon21 at gmail.com Tue Sep 16 12:48:42 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Tue, 16 Sep 2008 18:48:42 +0200 Subject: parse a midi file Message-ID: <8f67b6f80809160948v1c97867fmdf841080e6930b95@mail.gmail.com> Hi, I need to parse a midi file with Python. What I exactly need is the possibility to distinguish all notes in all channels in a midi file and put them in a list or something. I've found this: http://groups.google.com/group/alt.sources/msg/22467419ad4bf416 I'm not sure how it does work, but looking at the code I saw it can get input from the terminal, so I tried: python midi.py < mymidi.mid All it does is printing a lot of strange symbols. Do you know other easy way to parse a midi file in Python? Or how actually does this module work? Thanks, Carlo From kyosohma at gmail.com Fri Sep 12 12:07:50 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 12 Sep 2008 09:07:50 -0700 (PDT) Subject: Python a good choice for experimenting with Win32 API? References: <98qdnS2nk4rpEVfVnZ2dnUVZ_qHinZ2d@comcast.com> Message-ID: <f04f840f-435a-4d2d-b354-7e357a000370@a1g2000hsb.googlegroups.com> On Sep 12, 10:36?am, "Siegfried Heintze" <siegfr... at heintze.com> wrote: > I need to understand some User32.dll functions and I'm making an elaborate > GUI so I can easily experiment with different parameters. This is taking a > long time. I'm new to python and I'm thinking it would sure be nice to have > an interpreter I can type a few lines of code into and test things. > > (1) Would CPython be a good choice for this? How about iron python? How > about Jython (probably not). > (2) What about callbacks? Which pythons can handle callbacks? I read on msdn > that you cannot use managed code to call SetWindowsHook and supply a call > back (with two exceptions). I guess that means I cannot use iron python. > What about C-Python for playing with hooks? > (3) How easy it it define the C structs, enums and integer constants > necessary to call the windows API functions? > (4) Here is the code I'm struggling with presently (it is just not > cooperating: no errors just wrong results! I expect to be able give it a > scan code, get a virtual key code, change the arguments, give it the virtual > key code and get the original scan code back again). > > ? ? ? ? public const UInt32 MAPVK_VK_TO_VSC = 0, MAPVK_VSC_TO_VK = 1, > MAPVK_VK_TO_CHAR = 2, MAPVK_VSC_TO_VK_EX = 3, MAPVK_VK_TO_VSC_EX = 4; > ? ? ? ? public const UInt32 KLF_ACTIVATE = 1, KLF_SUBSTITUTE_OK = 2, > KLF_REORDER = 8, KLF_REPLACELANG = 0x10, KLF_NOTELLSHELL = 0x80, > KLF_SETFORPROCESS = 0x00100, KLF_SHIFTLOCK = 0x10000, KLF_RESET = > 0x40000000; > ? ? ? ? [DllImport("user32.dll")] ?static extern IntPtr > LoadKeyboardLayout(string pwszKLID, uint Flags); > ? ? ? ? [DllImport("user32.dll")] static extern bool > UnloadKeyboardLayout(IntPtr hkl); > ? ? ? ? [DllImport("user32.dll")] ? static extern uint MapVirtualKeyEx(uint > uCode, uint uMapType, IntPtr dwhkl); > ? ? ? ? private void Compute() > ? ? ? ? { > ? ? ? ? ? ? IntPtr hkl = LoadKeyboardLayout(sLangId_, KLF_ACTIVATE | > KLF_SUBSTITUTE_OK | KLF_REPLACELANG); > ? ? ? ? ? ? uResult_ = MapVirtualKeyEx(uCode_, uMapType_, hkl); > ? ? ? ? ? ? UpdateOutput(); > ? ? ? ? } > Would it be easy to execute this in the CPython interpreter or am I better > off sticking with C#? > > Thanks! > Siegfried I use the Python interpreter all the time for heavy experimentation. While I use PyWin32, I haven't done what you are attempting. I would recommend re-posting to the PyWin32 group as the PyWin32 creators use that list much more: http://mail.python.org/mailman/listinfo/python-win32 And there's lots of other knowledgeable users there too. Good luck! Mike From deets at nospam.web.de Fri Sep 12 03:58:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Sep 2008 09:58:46 +0200 Subject: handling uncaught exceptions with pdb? In-Reply-To: <wihbpyt95o9.fsf@panix5.panix.com> References: <7xmyifpt68.fsf@ruckus.brouhaha.com> <wihbpyt95o9.fsf@panix5.panix.com> Message-ID: <6iulpmFi9t0U1@mid.uni-berlin.de> R. Bernstein schrieb: > Paul Rubin <http://phr.cx at NOSPAM.invalid> writes: > >> I think I've asked about this before, but is there a way to set up >> Python to handle uncaught exceptions with pdb? I know about setting >> sys.except_hook to something that calls pdb, but this is normally done >> at the outer level of a program, and by the time that hook gets >> called, the exception has already unwound the stack to the outermost >> level. My situation is I run a multi-hour or multi-day computation >> that eventually crashes due to some unexpected input and I'd like to >> break to the debugger at the innermost level, right when the exception >> is encountered, so I can fix the error with pdb commands and resume >> processing. > ... > > Why not use the traceback you get to show you where to change the code > around that point to add an exception handler there which calls the > debugger? Because he wants to fix the issue directly in-place, and then continue, instead of losing hours or even days of computation. However, it's not possible AFAIK. Diez From mensanator at aol.com Mon Sep 22 20:09:00 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 22 Sep 2008 17:09:00 -0700 (PDT) Subject: Python based barcode readers References: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> <b9114982-4dce-4a65-ad28-891ed79fa5d4@b2g2000prf.googlegroups.com> Message-ID: <3d42eb3a-44c4-4c9d-8956-a31cd046cb02@x41g2000hsb.googlegroups.com> On Sep 22, 5:59?pm, Robocop <btha... at physics.ucsd.edu> wrote: > I also forgot to mention that it need not be nearly as robust as > something like Jailhelper 2.0, I will not really need to compensate > for noise and irregular conditions. ?All of my barcodes will be > scanned in a predictable, and consistent environment (i.e. a scanner), > so all i need is some stupid little script that will read the an image > in and decode it. The readers I've seen do all the decoding internally. They hook up via a Y-cable to your keyboard and require absolutely NO code at all on the PC. Anywhere the PC accepts keyboard input, you can wave the wand instead. Don't see why you would want to try to decode it yourself. Trust me, it's a pain in the ass. Unless you have a raw LED reader. Are you making one? From stef.mientki at gmail.com Fri Sep 26 12:57:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 26 Sep 2008 18:57:15 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <pan.2008.09.26.07.28.03@REMOVE.THIS.cybersource.com.au> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> <Xns9B24589F2DBEOKB@199.45.49.11> <48DBB9C8.6090500@gmail.com> <gbh53f$dim$1@ger.gmane.org> <mailman.1518.1222386373.3487.python-list@python.org> <pan.2008.09.26.07.28.03@REMOVE.THIS.cybersource.com.au> Message-ID: <48DD146B.5030206@gmail.com> Steven D'Aprano wrote: > On Fri, 26 Sep 2008 01:46:15 +0200, Stef Mientki wrote: > > >> Secondly thoughtless copying of current behavior, doesn't bring any >> progress, >> and I think that's one of the reasons why we're still burdened by >> inventions done 20 years ago, >> e.g. "do you want to save your changes ?". >> > > I click No about 50% of the time, and Yes Of Course You Stupid Machine > the other 50% of the time. Until they have a computer capable of reading > my mind, I'm curious what alternative you'd suggest. > > > Sorry to hear that you waste half of your time, maybe it's time to find yourself another job ;-) cheers, Stef From afriere at yahoo.co.uk Tue Sep 30 23:01:53 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 30 Sep 2008 20:01:53 -0700 (PDT) Subject: Wait or not? References: <34809165-9c72-46b3-996c-4bd55451505d@e53g2000hsa.googlegroups.com> Message-ID: <07d18c2c-2a70-478a-b50e-5afaa85d058d@e17g2000hsg.googlegroups.com> On Oct 1, 9:20 am, Eric <efl... at gmail.com> wrote: > I've been wanting to learn Python for a while now but I can't decide > on whether to wait for Python 3's final release and learn it or just > go ahead and learn 2.x. Would it be hard to make the transition being > a noob? If you only want to learn why do you need to wait for py3.0's final release? Get the rc1 and start learning now. On the other hand if you want to write production code get 2.5 and start writing now, most of what you'll learn between now and the final release of 3.0 will not change. From nicola.musatti at gmail.com Tue Sep 2 08:02:07 2008 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Tue, 2 Sep 2008 05:02:07 -0700 (PDT) Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> Message-ID: <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> On Sep 1, 9:23 am, Jeremy Banks <jer... at jeremybanks.ca> wrote: > Hi. I wondered if anyone knew the rationale behind the naming of the > Popen class in the subprocess module. Popen sounds like the a suitable > name for a function that created a subprocess, but the object itself is > a subprocess, not a "popen". It seems that it would be more accurate to > just name the class Subprocess, can anyone explain why this is not the > case? The Python class is a generalization of the standard Posix function of (almost) the same name: http://opengroup.org/onlinepubs/007908775/xsh/popen.html Cheers, Nicola Musatti From sjmachin at lexicon.net Sat Sep 6 17:38:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 14:38:28 -0700 (PDT) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <6de9141c-f350-4dfa-a36b-46e45344776a@q5g2000prf.googlegroups.com> On Sep 7, 7:04 am, Andreas Hofmann <asdfasdfasdfasdfa... at arcor.de> wrote: > Hello Folks! > > I've got a little problem here, which which really creeps me out at the > moment. > I've got some strings, which only contain numbers plus eventually one > character as si-postfix (k for kilo, m for mega, g for giga). I'm trying > to convert those strings to integers, with this function: > > def eliminate_postfix(value): > if type(value) is str: Don't use "is" unless you are really sure that "==" won't do the job. Better idiom: if isinstance(value, str): > value.upper() This causes your "mult is always 1" problem. You need: value = value.upper() Why? Because strings are immutable. String methods like upper return a new string, they don't change the existing string. > if value.endswith('K'): > mult = 1000 > elif value.endswith('M'): > mult = 1000000 > elif value.endswith('G'): > mult = 1000000000 > else: > mult = 1 > > if mult is 1: Lose "is". In fact, lose the whole "if" statement. See below. > value = string.atoi(value) Don't use deprecated functions from the string module. Use the built- in float function to convert from text. > else: > value = string.atoi(value[:-1]) * mult > return value Those last few statements look somewhat tortuous. Try this: else: # mult would be 1, but we don't need it return float(value) return float(value[:-1]) * mult HTH, John From akineko at gmail.com Mon Sep 1 23:44:03 2008 From: akineko at gmail.com (akineko) Date: Mon, 1 Sep 2008 20:44:03 -0700 (PDT) Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> <mailman.346.1220316770.3487.python-list@python.org> <d574e882-8cbf-40d9-9827-11307c773581@x16g2000prn.googlegroups.com> <mailman.348.1220319291.3487.python-list@python.org> <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> <mailman.350.1220326130.3487.python-list@python.org> Message-ID: <e79199b2-627b-4fc1-8772-1a33d89b1380@x16g2000prn.googlegroups.com> On Sep 1, 8:28 pm, "Guilherme Polo" <ggp... at gmail.com> wrote: > Can you clarify what is this "sticky" behavior ? Are you referring to > a toggle button ? If yes, then you might be after a simple > Checkbutton: > > checkbutton = Tkinter.Checkbutton(indicatoron=False, text='test') I wouldn't spend days to create a custom widget to mimick the Checkbutton ;-) I don't need to describe the detail but once the button was pressed for a bit while, a command is sent through communication. The button is left being ButtonDown ("sticky") until an acknowledgement is sent back through communication. This is a way to let the user know the action was acknowledged at another end. I think probably very few people needs such widget. Aki- From steve at holdenweb.com Mon Sep 29 07:29:06 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 07:29:06 -0400 Subject: how to make smtplib.SMTP('localhost') work on window xp In-Reply-To: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> References: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Message-ID: <gbqe64$f7c$1@ger.gmane.org> zxo102 wrote: > Hi, > I am trying to use python module smtplib to send my email out on > window xp (localhost). > > import smtplib > server = smtplib.SMTP('localhost') > > but I got the error information as follows: > > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > File "c:\python24\lib\smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "c:\python24\lib\smtplib.py", line 311, in connect > (code, msg) = self.getreply() > File "c:\python24\lib\smtplib.py", line 355, in getreply > raise SMTPServerDisconnected("Connection unexpectedly closed") > SMTPServerDisconnected: Connection unexpectedly closed > > I am not sure what is wrong with it. Should I configure my window xp > somewhere to run smtplib.SMTP('localhost')? > > Thanks in advance. > Well your code certainly expects *something* to be listening on port 25 on localhost. It's fairly unusual to run an SMTP server on Windows XP, though not impossible. usually your email system is set up to use some external host as uts SMPT server: if you look in your mail client's configuration you will probably find out whihc host you should be using. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From casey.mcginty at gmail.com Mon Sep 15 16:43:07 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Mon, 15 Sep 2008 10:43:07 -1000 Subject: Getting Linux partition info programmatically In-Reply-To: <ae3f58470809151340t287ab3c4m32218f1668d07338@mail.gmail.com> References: <2678157f0809121129n21381e6i6c6eee6da4f8694c@mail.gmail.com> <ae3f58470809151340t287ab3c4m32218f1668d07338@mail.gmail.com> Message-ID: <ae3f58470809151343i6f592b1ame0d276456f2ce6fb@mail.gmail.com> sorry, meant to say "abstraction" On Mon, Sep 15, 2008 at 10:40 AM, Casey McGinty <casey.mcginty at gmail.com>wrote: > You might want to take a look at HAL (hardware extraction layer) and DBUS. > > freedesktop.org - Software/hal<http://www.freedesktop.org/wiki/Software/hal> > HAL 0.5.10 Specification<http://people.freedesktop.org/%7Edavid/hal-spec/hal-spec.html> > Dbus Tutorial<http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html#connecting-to-the-bus> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/ece2b2c7/attachment-0001.html> From castironpi at gmail.com Sat Sep 20 22:51:10 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 19:51:10 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <48d54863$0$4666$426a74cc@news.free.fr> <00e5a962$0$20331$c3e8da3@news.astraweb.com> Message-ID: <431950dd-8239-486e-95a5-90b6075ff65f@m73g2000hsh.googlegroups.com> On Sep 20, 9:20?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Sat, 20 Sep 2008 19:01:42 +0200, Bruno Desthuilliers wrote: > > Once again, sorry > > if me missing your correct answer drives you paranoid :-) > > What do you mean by that? How many other people have been talking about > me? > > *wink* > > -- > Steven Why, no fewer than usual! *wink* From tjreedy at udel.edu Fri Sep 26 17:14:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 17:14:39 -0400 Subject: Classes and functions. In-Reply-To: <73045cca0809261323r4a74d09fkdad22396b0a88324@mail.gmail.com> References: <73045cca0809261323r4a74d09fkdad22396b0a88324@mail.gmail.com> Message-ID: <gbjjc0$e93$1@ger.gmane.org> aditya shukla wrote: > Hello folks , i am using the newick module > http://www.daimi.au.dk/~mailund/newick.html.I am just learning to use it > and i have a question about it. > > from newick.tree import parse_tree > from newick.tree import add_parent_links > from newick.tree import add_distance_from_root > > import sys > > t = parse_tree('((A:2,B:3):1,C:6);') > > print t > > deltas = add_distance_from_root(t) > > now when i do this i can get the output like this > > > (('A' : 2.0, 'B' : 3.0) : 1.0, 'C' : 6.0) > None > > This is the code of the add_distance_from_root(0 > > def add_distance_from_root(tree): > '''Extend all nodes with the distance (branch length) from the root''' > tree.distance_from_root = 0.0 # 'tree' is the root... > > class V(TreeVisitor): > def pre_visit_edge(self,src,b,l,dst): > if l is None: l = 0 > dst.distance_from_root = src.distance_from_root - l I am puzzled why this class is inside the function and why -1 instead of +1, but... > tree.dfs_traverse(V()) > > From here it is clear that the function does not return anything but i > wanna get the value of the distance from root.How can i get this? I presume each node gets an attribute 'distance_from_root', so read that attribute of whatever node. From dudeja.rajat at gmail.com Tue Sep 30 08:09:25 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 30 Sep 2008 13:09:25 +0100 Subject: Tix Combo box problem - remains in editable mode only In-Reply-To: <e0b6c39a0809300357h71349f8ep35df21258f5e05b6@mail.gmail.com> References: <e0b6c39a0809300357h71349f8ep35df21258f5e05b6@mail.gmail.com> Message-ID: <e0b6c39a0809300509t1806ab62x735197c5d88bf5b2@mail.gmail.com> On Tue, Sep 30, 2008 at 11:57 AM, <dudeja.rajat at gmail.com> wrote: > Hi > > I'm facing a problem with the tix combo box in a way that my combo box is > always in an editable mode after I have cleared subwidgets Entry and Listbox > from it. > > > My setup is like this : > > CheckButton1 : > > If this is unset, the combo box should get disabled, the entries in it > should get cleared ( entries are listbox and entry subwidgets) which in my > case they get cleared. > > When this check box is set again, the combo box should get enabled, with no > entries in listbox and entry subwidgets ( which are reallly cleared in my > case.) But the combox box having being enabled is in editable mode despite > of setting it to un-editable mode. > > > The code is as follows: > #Combo Box > self.cbAnalysisLibVersion = Tix.ComboBox(self.frame1, \ > dropdown = True, \ > > command=self.__cllbkAnalysisLibVer, \ > editable=0, \ > variable=verSelection, > options='listbox.height 8\ > listbox.width 25 \ > entry.width 30 \ > entry.anchor w \ > entry.padx 30', \ > history = False) > > > #Check Button box > self.chBtResultsComparison = Checkbutton(self.frame2, \ > text = "Results Comparison", > \ > variable = > varResultsComparison, \ > command = > self.__cllbkResultsComparison) > > def __cllbkResultsComparison(self, Event = None): > > subLB = self.cbAnalysisLibVersion.subwidget("listbox") > subEntry = self.cbAnalysisLibVersion.subwidget("entry") > > if varResultsComparison.get() != 1: > #Disable Tolerance Text Box > > self.txtTolerance.delete(1.0, END) > self.txtTolerance.config(state = DISABLED, \ > bg = "grey") > #Delete all entries (entry & subwidget's entries) > #in Reference Analysis Results Version Combo Box > #and disable this combo box. > > #First Delete the Listbox sub-widget entries > subLB.delete(0, END) > subLB.config(state = DISABLED) > > #Then delete Entry sub-widget entries > #subEntry = self.cbAnalysisLibVersion.subwidget("entry") > subEntry.config(state = NORMAL) > subEntry.delete(0, END) > subEntry.config(state = DISABLED) > > self.cbAnalysisLibVersion.config(state = DISABLED) > #Diable Result Comparison Button > self.btViewComparisonResults.config(state = DISABLED) > > else: > #Check box is ticked > #Enable the Tolerance text box > self.txtTolerance.config(state = NORMAL, \ > bg = "white") > #Enable the Reference Analysis Combo box > #self.cbAnalysisLibVersion.config(state = NORMAL, editable=0) > self.cbAnalysisLibVersion.configure(state = NORMAL, editable = 0) > subLB.config(state = NORMAL) > subEntry.config(state = NORMAL) > > self.btViewComparisonResults.config(state = NORMAL) > > > Please suggest what is that I am missing > > Regards, > Rajat > Any help guys? -- Regrads, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/81167fde/attachment-0001.html> From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Sep 25 11:42:45 2008 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Thu, 25 Sep 2008 15:42:45 GMT Subject: How to get the filename in the right case ? References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> Message-ID: <Xns9B24589F2DBEOKB@199.45.49.11> Stef Mientki wrote: > >>> import Module1 > > d:\data_python_25\pylab_works\module1.py(3)<module>() > -> print "hello" > (Pdb) > >> Then we know if PDB is really the culprit. >> >> > So pdb is the problem. Yep, it does the same thing for me. >> Apart from that, is that really a problem that the filenames are >> all lower case? AFAIK Windows is case-insensitive regarding >> filenames anyway. So opening the file by just passing the filename >> should work seamless. >> > Yes windows is, > but Python is not. > My program should run on Windows and Linux (and maybe a few > others). By converting everything to lowercase, on Linux I can't > distinguishes between 2 files with the same name but a different > case (btw, giving 2 files the same name, only differing in case, > looks like a bad idea to me). Hmmm, but I don't understand what you're doing here. Are you somehow storing the filename that pdb outputs and you need to use it later on a potentially different OS? If the case is preserved in pdb on linux, then presumably running it on linux will be fine, right? It's only a problem if you somehow try to use a filename created by windows- pdb to open a file (the same file, somehow) on linux. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From theller at python.net Fri Sep 19 02:43:17 2008 From: theller at python.net (Thomas Heller) Date: Fri, 19 Sep 2008 08:43:17 +0200 Subject: Directshow in Python In-Reply-To: <9d55654a-49ed-4bce-beae-bdf915810ad1@o40g2000prn.googlegroups.com> References: <9d55654a-49ed-4bce-beae-bdf915810ad1@o40g2000prn.googlegroups.com> Message-ID: <6jh00cF39nu1U1@mid.individual.net> Sayanan Sivaraman schrieb: > Hey all, > > I'm trying to use DirectShow to display videos [I'm kind of new to > Python, from more of a C++ background on windows]. I found some > sample code online, but I am having trouble with calling the I > > import ctypes > from ctypes import * > from comtypes import client > from ctypes.wintypes import * > import sys > import time > > > filename = sys.argv[1] > > > qedit = client.GetModule('qedit.dll') # DexterLib > quartz= client.GetModule("quartz.dll") > > > CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}' > filter_graph = > client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph) > filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder) > filter_builder.RenderFile(filename, None) > > media_control = filter_graph.QueryInterface(quartz.IMediaControl) > media_control.Run() > > try: > # Look at IMediaEvent interface for EOS notification > while True: > time.sleep(1) > except KeyboardInterrupt: > pass > > # Need these because finalisers don't have enough context to clean up > after > # themselves when script exits. > del media_control > del filter_builder > del filter_graph > > This code works fine. What I would like to know, is how do I declare > filename in the Python program to be of type LPCWSTR, so that I don't > need to parse the command line in order to call the function > "RenderFile()"? If I understand your question correctly (I'm no sure): comtypes converts Python strings or unicode strings to the required LPCWSTR type itself. So, you can call filter_builder.RenderFile("c:\\windows\\clock.avi", None) or filter_builder.RenderFile(u"c:\\windows\\clock.avi", None) If you pass a string, comtypes converts it to unicode using the "mbcs" codec; this can be changed by setting ctypes.conversion_mode. Thomas From tiftof at gmail.com Tue Sep 30 12:17:30 2008 From: tiftof at gmail.com (Christophe) Date: Tue, 30 Sep 2008 09:17:30 -0700 (PDT) Subject: how to find out the version of a certain installed package Message-ID: <b83e6129-254d-4512-a3dc-180901a237b1@q35g2000hsg.googlegroups.com> Hi, In a projecet I'm making using pycrypto, I need to find out the current installed version of pycrypto. After looking around, I found out that "pkg_resources.requires("pycrypto") will give me a string containing the version number, but is this the only way to do it or are there other ways? thanks, Christophe From zasaconsulting at gmail.com Thu Sep 18 08:25:02 2008 From: zasaconsulting at gmail.com (Alexzive) Date: Thu, 18 Sep 2008 05:25:02 -0700 (PDT) Subject: improving a huge double-for cycle Message-ID: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Hello there :) , I am a python newbie and need to run following code for a task in an external simulation programm called "Abaqus" which makes use of python to access the mesh (ensamble of nodes with xy coordinates) of a certain geometrical model. [IN is the starting input containing the nodes to be check, there are some double nodes with the same x and y coordinates which need to be removed. SN is the output containing such double nodes] Code: Select all for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i].label) Unfortunately my len(IN) is about 100.000 and the running time about 15h !!!! :( Any idea to improve it? I have already tried to group the "if statements" in a single one: Code: Select all if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and if IN[i].coordinates[1] == IN[j].coordinates[1]: but no improvements. Many thanks, Alex From gagsl-py2 at yahoo.com.ar Tue Sep 9 13:00:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 14:00:02 -0300 Subject: how to use execfile with input parameters References: <77BBE7D879F90E47886631DD9B2714CD04FF1DB1@KUDBEX01.kuds.kingston.ac.uk> Message-ID: <op.ug736cnsx6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 08 Sep 2008 08:08:33 -0300, Shi, Shaozhong <S.Shi at kingston.ac.uk> escribi?: > I have a Python script expecting 11 or 12 input parameters. How do I > use execfile to execute the Python script in my new Python script? How > do I pass in the input parameters? You might use the subprocess module to run the script with all its parameters. But probably you want to call a *function* in a module. -- Gabriel Genellina From tjansson60 at gmail.com Mon Sep 8 11:37:28 2008 From: tjansson60 at gmail.com (Thomas Jansson) Date: Mon, 8 Sep 2008 08:37:28 -0700 (PDT) Subject: Catching subprocess stdout stream Message-ID: <00b9dc86-e002-4e2c-a686-39d2dd1016b9@m3g2000hsc.googlegroups.com> Dear all I have tkinkter based frontend to a Fortran based program. I use subprocess to launch the fortran program as a child process and I wish to see the output of the fortran program as it is created in the console. The fortran program can take up to 20 minuttes to finish and at the moment the I will first see any output after the fortran program is done. How make my function write the output of the process as it comes? def runprogram(Icommand, Ijobfile, Ioutput): if os.name == "posix": os.system(pythonpath+"/bin/"+Icommand+"< "+Ijobfile+" | tee "+Ioutput) elif os.name == "nt": import subprocess ofile = open(Ioutput, 'w') p = subprocess.Popen([os.path.join(pythonpath, "bin", Icommand + '.exe')], stdin=open(Ijobfile, "rb"),bufsize=1024,shell=False, stdout=subprocess.PIPE) while p.poll() is None: #Check if child process has terminated. o = p.stdout.readline() ofile.writelines(o) print o, ofile.close Kind regards Thomas Jansson From steven at REMOVE.THIS.cybersource.com.au Fri Sep 19 04:13:05 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 19 Sep 2008 08:13:05 GMT Subject: Python newbie References: <gavjfd$mvd$1@registered.motzarella.org> Message-ID: <pan.2008.09.19.08.13.05@REMOVE.THIS.cybersource.com.au> On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote: > I am a Python newbie who decided to see what that Python fuss is all > about. Quite frankly, I am a bit perplexed. Naturally you will be perplexed if you assume that Python is just Perl with a more verbose syntax. It isn't. > After having had few months > of experience with Perl (started in 1994 with Perl v4, and doing it ever > since) , here is what perplexes me: > > perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' > > The equivalent in Python looks like this: Actually, no it doesn't. The equivalent looks more like this: $ python -c 'a=[1,2,3]; a=[2*x for x in a]; for x in a: print x' 2 4 6 Now, to go on with your questions: > 1) Why is the array "a" unchanged after undergoing a transformation with > map? Because it hasn't undergone a transformation at all. The list (not array) a remains unchanged, because map returns a new list. > 2) Why is it illegal to pass a built-in function "print" to map? Because print is not a function, it is a statement. However, in Python 3, that design wart has been corrected. > 3) Why is the array "a" unchanged after undergoing an explicit > transformation with the "for" loop? Because the list a hasn't undergone any such transformation. Rebinding a name is not an explicit transformation to the object that used to be bound to the name. And if that sentence is gobbledygook to you, that demonstrates that Python is not Perl and you shouldn't assume a one-to- one semantic relationship between syntactical elements. > 4) Is there an equivalent to \$a (Perl "reference") which would allow me > to decide when a variable is used by value and when by reference? Python is neither call-by-reference nor call-by-value, although you will have many people swear black and blue that it is one or the other. With respect to all of them, they are wrong. Python's calling model is "call by object". See here for more detail: http://effbot.org/zone/call-by-object.htm If you insist on a false dichotomy between call-by-reference and call-by- value, then you won't often go wrong if you think of Python: - being almost always call-by-reference, except for some odd corner cases which look almost, but not quite, like call-by-value; - being almost always call-by-value, but only if you think of the values as pointers. > How can I make sure that > for x in a: x=2*x > > actually changes the elements of the array "a"? By explicitly changing the elements of the list. Here's one very old- fashioned way of doing so: >>> a = [1,2,3] >>> for i in range(len(a)): ... a[i] = a[i]*2 ... >>> a [2, 4, 6] Here's a more Pythonic alternative: >>> a = [1,2,3] >>> a = [2*x for x in a] -- Steven From uzmanajmal at gmail.com Sat Sep 13 06:06:11 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Sat, 13 Sep 2008 10:06:11 +0000 Subject: XML RPC Problem.... In-Reply-To: <gafuhg$sh1$1@ger.gmane.org> References: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> <gaagp1$804$1@ger.gmane.org> <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> <gafuhg$sh1$1@ger.gmane.org> Message-ID: <a3158e8b0809130306m25dda070w73f0a3c25888e051@mail.gmail.com> Where exactly should i call ServerProxy? Following is the code from my client.py t = SecureTransport() t.set_authorization(ustring, text_ucert) server = xmlrpclib.Server('http://localhost:8000/',transport=t) print server.s() Note: Full code for client is here at http://privatepaste.com/b56oS1Xa7P and following is my server code import SimpleXMLRPCServer #server = ServerProxy("http://betty.userland.com") class AuthenticationFunctions: def s(self): print "something..." server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(AuthenticationFunctions()) server.serve_forever() On Sat, Sep 13, 2008 at 8:44 AM, Fredrik Lundh <fredrik at pythonware.com>wrote: > Usman Ajmal wrote: > > Please explain the arguments of send_request. What exactly are the >> connection, handler and request_body? It will be really helpful if you give >> an example of how do i call send_request >> > > you don't call send_request. you should pass the SecureTransport instance > as an argument to the ServerProxy, which will then use it to talk to the > server. see the "custom transport" example in the library reference that I > pointed you to. > > http://www.python.org/doc/lib/xmlrpc-client-example.html > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080913/0c684ae2/attachment-0001.html> From bignose+hates-spam at benfinney.id.au Thu Sep 11 06:19:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 11 Sep 2008 20:19:06 +1000 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> <87k5djb6e2.fsf@benfinney.id.au> <pan.2008.09.11.09.10.00@REMOVE.THIS.cybersource.com.au> Message-ID: <873ak7asth.fsf@benfinney.id.au> Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> writes: > Nor do I believe that by posting a news message I've automatically > consented to receive email messages. To imply that the one implies the > other is equivalent to arguing that because I've written a letter to the > editor of a newspaper, I therefore must accept private correspondence > from any person or corporation that has a subscription to that newspaper. The two are not equivalent in this important detail: to post a newsgroup message, you must give a 'From' field in the header (note: just like email messages, newsgroup messages have exactly one header, comprised of multiple fields). You can fake an address in that field, of course, but it's considered bad form to do so. (That doesn't stop it being extremely common.) What you can't do is claim that, without express permission, no-one may send you an individual message to that address. On the contrary, that is the express purpose of the From field in a newsgroup message: to allow individual contact to the sender of the message. In the case of a letter to the editor a newspaper, the protocol is different. The newspapers are expected, by convention, to state the name and, often, suburb (or other location) of the writer; i.e. not enough information to send an individual message to the person. You might wish that Usenet operated the same in this respect, but it doesn't, and you can't reasonably expect that it does. -- \ ?If you were going to shoot a mime, would you use a silencer?? | `\ ?Steven Wright | _o__) | Ben Finney From steve at holdenweb.com Fri Sep 12 12:34:10 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 12:34:10 -0400 Subject: Newbie Question:Please help In-Reply-To: <d28296ba0809082310w6cb8e11dk7eeadf7ddc9f1353@mail.gmail.com> References: <d28296ba0809082310w6cb8e11dk7eeadf7ddc9f1353@mail.gmail.com> Message-ID: <gae5n2$f68$1@ger.gmane.org> Karthik Krishnan wrote: > Hi, > > I am a newbie to python and I hope this is not a stupid question. I am > trying to run a main method from a Python command line using the command > shell using the command. > > python main_test.py > > I get the following error. > > > File "<stdin>", line 1 > python main_test.py > > Syntax Error: invalid syntax > > My main file main_test.py is given below. > > #!/usr/bin/env python > > """ Test method to run the main method. > > """ > > def main(): > print "Main method called."; > > > if __name__ = "__main__": > main() > Apart from the syntax error Rob pointed out (use of "=" instead of "==" as a comparison operator) the output you show makes it seem possible you are entering the command "python main_test.py" at the Python interpreter interactive prompt ">>>". That won't work, as you are supposed to enter Python statements and expressions there. "python" is an operating system command, so you want to enter "python main_test.py" in a command window (terminal window, shell window, call it what you will). I'm guessing (possibly incorrectly) that you are a Windows user, and got your interactive Python window by choosing "Python (command line)" from the Start | Programs menu. See the FAQ for further information, possibly http://www.python.org/doc/faq/windows/ regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From circularfunc at yahoo.se Tue Sep 16 11:13:48 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 08:13:48 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? Message-ID: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> >>> sys.path ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ \lib\\site-packages\\PIL'] >>> Now I have my personal programs in C:/Python25/Progs/ How do I add so that I can just do "import somefile" from anywhere in that directory in the interpreter and it can load files from other folders in that directory. From a at nospam.org Mon Sep 15 16:35:36 2008 From: a at nospam.org (Armin) Date: Mon, 15 Sep 2008 22:35:36 +0200 Subject: append on lists In-Reply-To: <mailman.1062.1221509879.3487.python-list@python.org> References: <gamffv$qms$1@online.de> <mailman.1062.1221509879.3487.python-list@python.org> Message-ID: <gamg4f$f54$1@online.de> Fredrik Lundh wrote: > Armin wrote: > >> just a dumb question. >> >> Let a = [1,2,3,4,5] >> >> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? > > yeah, that's a dumb question. > > </F> > yeah, that's a dumb answer. From clp at rebertia.com Fri Sep 26 22:17:38 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 26 Sep 2008 19:17:38 -0700 Subject: getting global variables from dictionary In-Reply-To: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> References: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> Message-ID: <47c890dc0809261917u565a547dy73bd77800c815ca2@mail.gmail.com> When you do "Variables()" in your code, you're making a new instance of that class that has no relation to any other instances. This is the cause of your problem. To just reference a class, use just "Variables". But that doesn't help in this case because var_dict is an instance variable, not a class variable. On Fri, Sep 26, 2008 at 7:01 PM, icarus <rsarpi at gmail.com> wrote: > global_vars.py has the global variables No it doesn't, it just defines a class. The class itself (but NOT its instances) is a module-level global. > set_var.py changes one of the values on the global variables (don't > close it or terminate) No, it just instanciates the Variables class and then manipulates the instance, which is then GC-ed because it's no longer referenced anywhere, even in set_var. > get_var.py retrieves the recently value changed (triggered right after > set_var.py above) No, it creates an entirely new instance of Variables and then fetches the value from that instance (which is still using the default value because this new instance has never been modified). > > Problem: get_var.py retrieves the old value, the built-in one but not > the recently changed value in set_var.py. > > What am I doing wrong? Try just making var_dict a module-level variable in global_vars.py and then manipulating that rather than this unnecessary mucking about with Variables(). Alternatively, make var_dict a *class* variable of Variables by removing it from __init__ and just putting 'var_dict = {"username": "original username"}' in the raw class body of Variables; And then remove the parentheses after Variables as I mentioned in the beginning. Regards, Chris > > ----global_vars.py--- > #!/usr/bin/python > > class Variables : > def __init__(self) : > self.var_dict = {"username": "original username"} > > > ---set_var.py --- > #!/usr/bin/python > > import time > import global_vars > > global_vars.Variables().var_dict["username"] = "new username" > time.sleep(10) #give enough time to trigger get_var.py > > > ---get_var.py --- > #!/usr/bin/python > import global_vars > print global_vars.Variables().var_dict.get("username") > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From bearophileHUGS at lycos.com Mon Sep 29 12:34:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 09:34:16 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> <48c6380b$0$17080$426a34cc@news.free.fr> <mailman.741.1220976622.3487.python-list@python.org> <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> <mailman.1557.1222457112.3487.python-list@python.org> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> <mailman.1665.1222668924.3487.python-list@python.org> <6304d804-57a1-458d-8ffe-b7a387dd0584@a1g2000hsb.googlegroups.com> <mailman.1680.1222703796.3487.python-list@python.org> Message-ID: <a5643918-0c29-4ce3-931b-46aecbe6bf6c@y21g2000hsf.googlegroups.com> Derek Martin: > code that implements non-obvious algorithms ought to explain what it's > doing in comments, I am sorry, you are right, of course. In my libs/code there are always docstrings and doctests/tests, and most times comments too, like you say. When I post code here I often strip away part of those things, mostly to reduce the length of my posts -.- I guess that I have to leave more of that meta- information... Bye, bearophile From ldo at geek-central.gen.new_zealand Thu Sep 25 18:22:46 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 10:22:46 +1200 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <gbh2vm$9j1$2@lust.ihug.co.nz> In message <48d4c11b$0$22877$426a74cc at news.free.fr>, candide wrote: > "... Python supports OOP and classes to an extent, but is not a full OOP > language." Python allows you to use OO-style constructs, but doesn't force you to have inheritance and subclasses if you don't want to. Duck typing is usually a much more flexible approach. From david at abbottdavid.com Fri Sep 5 14:23:10 2008 From: david at abbottdavid.com (David) Date: Fri, 05 Sep 2008 14:23:10 -0400 Subject: Make Games In-Reply-To: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> References: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> Message-ID: <48C1790E.4020603@abbottdavid.com> NightZombie wrote: > x-no-archive: yes > > I want to learn Python so I can make simple games. What are some good > books that'll help me do this? > -- > http://mail.python.org/mailman/listinfo/python-list > > > Good book you can get used; Python Programming for the Absolute Beginner http://books.google.com/books?id=DH3TcrHM8s4C -- Have Fun, David A. Powered by Gentoo GNU/LINUX http://www.linuxcrazy.com From paul at boddie.org.uk Thu Sep 18 06:20:02 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Sep 2008 03:20:02 -0700 (PDT) Subject: minimum install & pickling References: <fb304bca-abe9-48e6-8dba-6187e33e5a6d@a2g2000prm.googlegroups.com> <6f045535-555f-44b6-93a5-f5b338d3f318@d45g2000hsc.googlegroups.com> <69cf2202-e11b-4994-84ab-a41167ef2652@26g2000hsk.googlegroups.com> Message-ID: <d8e9b368-ee86-415e-b0e6-16958391dfdd@8g2000hse.googlegroups.com> On 17 Sep, 22:18, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 17, 4:43?am, Paul Boddie <p... at boddie.org.uk> wrote: > > >http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...) > > These solutions have at least the same bugs that the bare bones > solution in the corresponding framework has. ?Malicious code has fewer > options, but constructive code does too. ?If you're running foreign > code, what do you want it to do? ?What does it want to do? ?The more > options it needs, the more code you have to trust. As I noted, instead of just forbidding access to external resources, what you'd want to do is to control access instead. This idea is not exactly new: although Brett Cannon was working on a sandbox capability for CPython, the underlying concepts involving different privilege domains have been around since Safe-Tcl, if not longer. The advantage of using various operating system features, potentially together with tools like fakechroot or, I believe, Plash, is that they should work for non-Python programs. Certainly, the chances of successfully introducing people to such capabilities are increased if you don't have to persuade the CPython core developers to incorporate your changes into their code. > The only way a Python script can return a value is with sys.exit, and > only an integer at that. ?It is going to have output; maybe there's a > way to place a maximum limit on its consumption. ?It's going to have > input, so that the output is relative to something. ?You just make > copies to prevent it from destroying data. ?Maybe command-line > parameters are enough. ?IIRC if I recall correctly, Win32 has a way to > examine how much time a process has owned so far, and a way to > terminate it, which could be in Python's future. There is support for imposing limits on processes in the Python standard library: http://docs.python.org/lib/node521.html My experimental package, jailtools, relies on each process's sandbox being set up explicitly before the process is run, so you'd definitely want to copy data into the sandbox. Setting limits on the amount of data produced would probably require support from the operating system. Generally, when looking into these kinds of systems, most of the solutions ultimately come from the operating system: process control, resource utilisation, access control, and so on. (This is the amusing thing about Java: that Sun attempted to reproduce lots of things that a decent operating system would provide *and* insist on their use when deploying Java code in a controlled server environment, despite actually having a decent operating system to offer already.) > PyPy sandbox says: ?"The C code generated by PyPy is not > segfaultable." ?I find that to be a bold claim (whether it's true or > not). > > I'm imagining in the general case, you want the foreign code to make > changes to objects in your particular context, such as exec x in > vars. ?In that case, x can still be productive without any libraries, > just less productive. Defining an interface between trusted and untrusted code can be awkward. When I looked into this kind of thing for my undergraduate project, I ended up using something similar to CORBA, and my conclusion was that trusted code would need to expose an interface that untrusted "agents" would rely on to request operations outside the sandbox. That seems restrictive, but as the situation with rexec has shown, if you expose a broad interface to untrusted programs, it becomes increasingly difficult to verify whether or not the solution is actually secure. Paul From jepe_abrantes at hotmail.com Tue Sep 9 09:36:07 2008 From: jepe_abrantes at hotmail.com (=?iso-8859-1?Q?Jo=E3o_Abrantes?=) Date: Tue, 9 Sep 2008 13:36:07 +0000 Subject: Orientation on MySql using python Message-ID: <BLU115-W2141F5289856E2EFF4D1BB96540@phx.gbl> Hello everyone, I want to make a program in python that uses Mysql aswell.. I don't know anything about mysql can you tell me some good books/tutorials where I can read something about mysql using python? Thanks. _________________________________________________________________ Invite your mail contacts to join your friends list with Windows Live Spaces. It's easy! http://spaces.live.com/spacesapi.aspx?wx_action=create&wx_url=/friends.aspx&mkt=en-us -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080909/35390469/attachment-0001.html> From nick at craig-wood.com Mon Sep 15 06:36:59 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 15 Sep 2008 05:36:59 -0500 Subject: Wrong application name in menubar of OS X References: <1af662ce-5454-436c-8b65-c713993cf6bc@s9g2000prg.googlegroups.com> Message-ID: <slrngcsck0.7ga.nick@irishsea.home.craig-wood.com> erikcw <erikwickstrom at gmail.com> wrote: > The menubar of OS X is showing the application name as Python instead > of the name of my wxpython gui app. How do I make my application name > show-up in the menu bar? The answer I got from the wxpython mac list recently was to package my app with py2app first. I tried this and it does work. So your app will be called "Python" during development, but once you have packaged it it will get the correct name. -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From gagsl-py2 at yahoo.com.ar Wed Sep 10 03:28:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Sep 2008 04:28:53 -0300 Subject: Clearing a session and reload() problem (with repro error) References: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> <mailman.740.1220976221.3487.python-list@python.org> <067abd3f-0d02-46e8-8d26-d85f20fa2e3a@s9g2000prg.googlegroups.com> Message-ID: <op.ug88efpix6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 10 Sep 2008 00:56:43 -0300, Rafe <rafesacks at gmail.com> escribi?: > On Sep 9, 11:03 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > wrote: >> En Mon, 08 Sep 2008 05:37:24 -0300,Rafe<rafesa... at gmail.com> escribi?: >> ... >> This dependency between modules, applied to all modules in your project, >> defines a "dependency graph". In some cases, one can define a partial >> ordering of its nodes, such that no module depends on any other module >> *after* it (it may depend only on modules *before* it). Look for >> "topological sort". >> >> Doing that in the generic case is not easy. If you *know* your >> dependencies, reload the modules in the right order by hand. >> ... > I was hoping there would be a way to just wipe out the module cache > and let it get rebuilt by executing my code (since I'm not using > reload as part of my program, but rather, to test it in an environment > where I cannot restart the Python session). Ok, I think the following sequence *might* work: - replace the __import__ and reload builtins with a custom callable object. This way you can hook into any import attempt. The object should keep a list of already reloaded modules. When a module is imported: if it is already in the list, just delegate to the original __import__; if it is not in the list, locate the module in sys.modules and reload it. - iterate over sys.modules and reload the desired modules, as you did in your previous attempt. - restore the original __import__ function. This way, you effectively transform any import statement into a recursive reload (for the first time); subsequent imports of the same module behave as usual. This may work for you, or perhaps not, or it may screw all your running environment up, or even cause the next global thermonuclear war... (I hope not!) Note: some modules don't work well with reload(). A common case: global mutable values, like a list of objects which starts empty: my_list = [] To make it more "reload friendly", use this: try: my_list except NameError: my_list = [] (this way the list will keep its previous values). The example below shows how to hook into the import mechanism - it just prints the module being imported. Implementing the functionality outlined above is left as an exercise to the reader :) py> class ImportHook(object): ... _orig_import = None ... # ... def __call__(self, name, globals={}, locals={}, fromlist=[], level=-1): ... if fromlist: ... print "-> from %s import %s" % (name, ','.join(fromlist)) ... else: ... print "-> import %s" % name ... return self._orig_import(name, globals, locals, fromlist, level) ... # ... def hook(self): ... import __builtin__ ... self._orig_import = __builtin__.__import__ ... __builtin__.__import__ = self ... # ... def unhook(self): ... assert self._orig_import is not None, "unhook called with no previous hook" ... import __builtin__ ... __builtin__.__import__ = self._orig_import ... del self._orig_import ... # ... # support the "with" statement ... def __enter__(self): ... self.hook() ... return self ... # ... def __exit__(self, type, value, tb): ... self.unhook() ... py> py> ih = ImportHook() py> ih.hook() py> import htmllib -> import htmllib -> import sgmllib -> import markupbase -> import re -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import re -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> import sre_parse -> from formatter import AS_IS -> import sys -> from htmlentitydefs import entitydefs py> reload(htmllib) -> import sgmllib -> from formatter import AS_IS -> from htmlentitydefs import entitydefs <module 'htmllib' from 'C:\apps\Python25\lib\htmllib.pyc'> py> ih.unhook() -> import __builtin__ py> import htmllib py> > I have been keeping a diagram of my module inheritance to make sure it > is as clean as possible, so I could just right a list of reloads as > you suggest. However, one of the sub-packages is designed to allow > users to add more modules. Because these get dynamically imported, a > guess I could add an argument to the reload function to allow a user > to give the 'add-on' module they are working on... so much work just > to get a clean environment... > > Separate of my program, I was really hoping to write a generic reload > tool for anyone developing in the same application as I am. I just > don't see a way to trace import dependencies in systems which include > dynamic imports. Any ideas? You may adapt the example above. Good luck! -- Gabriel Genellina From m_palmer45 at yahoo.ca Fri Sep 26 15:54:47 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 26 Sep 2008 12:54:47 -0700 (PDT) Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> <gbfvei$cqe$1@foggy.unx.sas.com> Message-ID: <208644f2-5162-430f-994e-15efeac1a979@p25g2000hsf.googlegroups.com> On Sep 25, 8:16 am, "Tim Arnold" <tim.arn... at sas.com> wrote: > "Tim Arnold" <a_j... at bellsouth.net> wrote in message > > news:57cdd3f1-cde8-45f5-b9d9-3eef32010bda at l43g2000hsh.googlegroups.com... > > >I have a bunch of processes to run and each one needs its own working > > directory. I'd also like to know when all of the processes are > > finished. > > Thanks for the ideas everyone--I now have some news tools in the toolbox. > The task is to use pdflatex to compile a bunch of (>100) chapters and know > when the book is complete (i.e. the book pdf is done and the separate > chapter pdfs are finished. I have to wait for that before I start some > postprocessing and reporting chores. > > My original scheme was to use a class to manage the builds with threads, > calling pdflatex within each thread. Since pdflatex really does need to be > in the directory with the source, I had a problem. > > I'm reading now about python's multiprocessing capabilty, but I think I can > use Karthik's suggestion to call pdflatex in subprocess with the cwd set. > That seems like the simple solution at this point, but I'm going to give > Cameron's pipes suggestion a go as well. > > In any case, it's clear I need to rethink the problem. Thanks to everyone > for helping me get past my brain-lock. > > --Tim Arnold I still don't see why this should be done concurrently? Do you have > 100 processors available? I also happen to be writing a book in Latex these days. I have one master document and pull in all chapters using \include, and pdflatex is only ever run on the master document. For a quick preview of the chapter I'm currently working on, I just use \includeonly - compiles in no time at all. How do you manage to get consistent page numbers and cross-referencing if you process all chapters separately, and even in _parallel_ ? That just doesn't look right to me. From sebastianthegreatful at gmail.com Wed Sep 17 13:33:19 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Wed, 17 Sep 2008 10:33:19 -0700 (PDT) Subject: ssl server Message-ID: <eef6d1fa-12e6-4549-a85e-c0ba21b19c63@25g2000hsx.googlegroups.com> I'm making a ssl server, but I'm not sure how I can verify the clients. What do I actually need to place in _verify to actually verify that the client cert is signed by me? 50 class SSLTCPServer(TCPServer): 51 keyFile = "sslcert/server.key" 52 certFile = "sslcert/server.crt" 53 def __init__(self, server_address, RequestHandlerClass): 54 ctx = SSL.Context(SSL.SSLv23_METHOD) 55 ctx.use_privatekey_file(self.keyFile) 56 ctx.use_certificate_file(self.certFile) 57 ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, self._verify) 58 ctx.set_verify_depth(10) 59 ctx.set_session_id('DFS') 60 61 self.server_address = server_address 62 self.RequestHandlerClass = RequestHandlerClass 63 self.socket = socket.socket(self.address_family, self.socket_type) 64 self.socket = SSL.Connection(ctx, self.socket) 65 self.socket.bind(self.server_address) 66 self.socket.listen(self.request_queue_size) 67 68 def _verify(self, conn, cert, errno, depth, retcode): 69 return not cert.has_expired() and cert.get_issuer().organizationName == 'DFS' From stef.mientki at gmail.com Sun Sep 28 18:25:30 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 29 Sep 2008 00:25:30 +0200 Subject: rlcompleter and wxPython, problems ... Message-ID: <48E0045A.3020402@gmail.com> hello, I'm trying to implement autocompletion into my editor. But I find some weird behavior, or at least I don't have the faintest idea why this behavior occures, and even more important how to solve it In the example below I try to autocomplete " wx.s" , which in my humble opinion should at least produce "wx.stc" (and some others ). The completion is done in a procedure, so the "locals" is quite clean. Before calling the completer, I import the left part of my string to be completed. The program below gives indeed "wx.stc" as an option, but if I leave the second line out, marker "<<<===" , I get no results. Can someone explain this behavior and maybe even have a solution ? thanks, Stef Mientki import rlcompleter import wx.stc # <<<=== # *********************************************************************** # *********************************************************************** def _get_completions ( word ) : left_part = None right_part = word if word.find('.') >= 0 : word_parts = word.split('.') left_part = '.'.join ( word_parts [ : -1 ] ) right_part = word_parts [ -1 ] try : exec ( 'import ' + left_part ) except : return None Completer = rlcompleter.Completer ( locals () ) State = 0 Next = Completer.complete ( word, State ) result = [] while Next : result.append ( Next ) State += 1 Next = Completer.complete ( word, State ) result = ' '.join ( result ) return result # *********************************************************************** # *********************************************************************** # *********************************************************************** if __name__ == "__main__": word = 'wx.s' completions = _get_completions ( word ) print completions # ******************************************************* From luke.hamilton at xenter.com.au Wed Sep 10 09:54:00 2008 From: luke.hamilton at xenter.com.au (Luke Hamilton) Date: Wed, 10 Sep 2008 23:54:00 +1000 Subject: Web shopping carts In-Reply-To: <48C7CE5A.7030904@wildenhain.de> Message-ID: <C4EE0E98.1137D%luke.hamilton@xenter.com.au> > From: Tino Wildenhain <tino at wildenhain.de> > Date: Wed, 10 Sep 2008 08:40:42 -0500 > To: Luke Hamilton <luke.hamilton at xenter.com.au> > Cc: "python-list at python.org" <python-list at python.org> > Subject: Re: Web shopping carts > > Hi, > > Luke Hamilton wrote: >> Thanks... >> >> Do you happen to have anymore details? > > Yes well... you guess it was supposed to be a funny comment > but would you happen to have anymore details on your > requirements as well? Your simple question was just > asking for making fun of it. > It was actually meant to be a pretty general question. I was really trying to get a feel for what was out there, so I can then to start to have a look at there capabilities. > (Other than that please see the answer given by Fredrik) > And unfortunately Google hasn't been much help... > > Ah, btw, I'd check the the other posts of long term members > if you see something in the appearance different to > yours :-) (not related to your question itself) > > Cheers > Tino > > ... >>> Luke Hamilton wrote: >>>> Hey People, >>>> >>>> I am wondering if there are any OS shopping cart application written in >>>> python? >>>> >>> Yes there are. >>> >>> HTH >>> Tino >> >> > From fredrik at pythonware.com Mon Sep 15 14:52:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 20:52:41 +0200 Subject: environment variable issue In-Reply-To: <48ceacb9$0$2863$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <gamatt$357$1@ger.gmane.org> Michel Leunen wrote: > Could someone explain me what I'm doing wrong here? I'm trying to > retrieve the value of an environment variable in Ubuntu 8.04 like this: > > >>> import os > >>> os.environ['USER'] > 'michel' > > This works but this doesn't: > > >>> os.environ['HOSTNAME'] > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'HOSTNAME' > > Why is it working in the first case but not in the second one. I must be > missing something but it seems I'm not able to figure it out. this might help: http://mail.python.org/pipermail/python-list/2008-September/507933.html (scanning the subjects of recent and ongoing threads before posting is always a good idea). </F> From max at alcyone.com Tue Sep 9 01:14:59 2008 From: max at alcyone.com (Erik Max Francis) Date: Mon, 08 Sep 2008 22:14:59 -0700 Subject: Correcting for Drift between Two Dates In-Reply-To: <pgnxk.9513$cn7.668@flpi145.ffdc.sbc.com> References: <pgnxk.9513$cn7.668@flpi145.ffdc.sbc.com> Message-ID: <zoidnYi476rJm1vVnZ2dnUVZ_vOdnZ2d@speakeasy.net> W. eWatson wrote: > drift = 4.23 # seconds per day > > format = '%Y%m%d_%H%M%S' > ts1 = "20080901_120000" # base date-time > ts2 = "20080904_180000" > d1 = datetime(*(time.strptime(ts1, format)[0:6])) > d2 = datetime(*(time.strptime(ts2, format)[0:6])) > #d += timedelta(seconds=sec) > delta = d2-d1 > # delta format is nnn[n] days, hh:mm:ss > # delta is type 'datetime.timedelta' > print delta > # get back to ts2 as a check > d3 = d1+d > print d3 You're going to have to start with code that actually runs first. You've iterated on this so many times that it's not at all clear what it is you're trying to do and why it isn't doing what you think it should. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis It's better to be quotable than to be honest. -- Tom Stoppard From aioe.org at technicalbloke.com Sat Sep 27 01:58:15 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 27 Sep 2008 01:58:15 -0400 Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: <gbki1m$eh1$3@aioe.org> process wrote: > ' '.join([`x * x` for x in range(1, 6)]) > > exactly what does this symbol do and what does it stand for? Ah, just spotted the backticks - they just return whatever's inside them as a string. From celephicus at gmail.com Mon Sep 1 11:28:31 2008 From: celephicus at gmail.com (Tom Harris) Date: Tue, 2 Sep 2008 01:28:31 +1000 Subject: Buffer objects Message-ID: <aa19747c0809010828s3df678bdpe9afb617d39525f6@mail.gmail.com> Greetings, I need a little help with buffer objects. Many Python objects export the buffer interface, or can be persuaded to create a buffer object with a buffer() call. First question, the buffer() function appears very quick. Does it just wrap the internal pointer and then exit? Second question, the buffer interface does include support for multiple segments of memory. All the buffers I have examined are only a single segment, is this a rarely used functionality? Third question, having got my buffer interface I want to get the actual pointer out so that I can call foreign functions with ctypes with the pointer as a function argument and add offsets to it, so I would like it as a plain int. What is the recommended method of accessing the raw pointer from the buffer object? It must be me but I have found the whole buffer thing difficult to understand from the docs, it appears only useful to C coders, but I use the buffer interface (GetData()) of wx.Image objects a lot in my work. TomH celephicus(AT)gmail(DOT)com From stefan_ml at behnel.de Sat Sep 13 15:09:23 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 13 Sep 2008 21:09:23 +0200 Subject: lxml build error in sun In-Reply-To: <b64b6178-db7f-4bac-a4c7-a104e1031401@k13g2000hse.googlegroups.com> References: <b64b6178-db7f-4bac-a4c7-a104e1031401@k13g2000hse.googlegroups.com> Message-ID: <48cc0fe3$0$6560$9b4e6d93@newsspool4.arcor-online.net> Owen Zhang wrote: > I am trying to build lxml package in SunOS 5.10. I got the following > errors. Could you report this on the lxml mailing list? Stefan From nevillednz at gmail.com Mon Sep 1 00:00:17 2008 From: nevillednz at gmail.com (Neville Dempsey) Date: Mon, 1 Sep 2008 14:00:17 +1000 Subject: enhancing/wrapping an existing instance of a duck Message-ID: <b2ff67060808312100i557515faw11cc239f33df3fb2@mail.gmail.com> Basically I have an existing (maybe a rather large and complicated (existing) instance) that I want to add new member to. Cheers N Hacks/attempts follow: from math import sqrt ############ try2 ############ duck_obj = [ i*i for i in range(25) ] # OR a large sparse matrix # I "want" to an a useful property, eg length, and retain the ducks existing properties. # I COULD try... setattr(duck_obj,"length",lambda: sqrt(sum(*duck_obj))) print duck_obj.length() # returns 70 duck_obj[0]=70+71 print duck_obj.length() # returns 71 ############ try2 ############ # **BUT** I'd rather encapsulate a the original instance somehow. # I presume that I could define a class to do this somehow? duck_obj = [ i*i for i in range(25) ] # OR a LargeSparseMatrix() dec = Vec(duck_obj) ??? print dec.length() # returns 70 duck_obj[0]=70+71 # original "large and complicated duck instance" print dec.length() # returns 71 Any hints on how I need to define Vec so that any kind of duck_obj can be decorated/wrapped/encapsulated. From stef.mientki at gmail.com Thu Sep 25 06:36:12 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 12:36:12 +0200 Subject: How to get the filename in the right case ? Message-ID: <48DB699C.6060801@gmail.com> hello, How can I find the correct case of a filename ? Background in my program I use case sensitive filenames, just like Python requires. Now I've integrated pdb into the program, but pdb acts somwhat strange: upon a breakpoint it gives the filename always in lowercase (probably this only happens on windows). So is there a way to get the correct case of a given filename in lowercase ? One solution might be to make the comparison in my program always with lowercase, but then I'm sure the program won't work on non-windows systems. btw, why does pdb behave that way ( Python 2.5 ) ? thanks, Stef Mientki From castironpi at gmail.com Thu Sep 25 13:52:43 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 25 Sep 2008 10:52:43 -0700 (PDT) Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> <48db50aa$0$3750$426a74cc@news.free.fr> <HoOCk.1756$Pv5.1315@edtnps83> <48dbc82e$0$1120$426a74cc@news.free.fr> Message-ID: <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> On Sep 25, 12:19?pm, Bruno Desthuilliers <bruno. 42.desthuilli... at websiteburo.invalid> wrote: > Dmitry S. Makovey a ?crit : > > > > > Thanks Bruno, > > > your comments were really helpful (so was the "improved" version of code). > > > My replies below: > > > Bruno Desthuilliers wrote: > >>> So decorators inside of B just identify that those methods will be > >>> proxied by A. On one hand from logical standpoint it's kind of weird to > >>> tell class that it is going to be proxied by another class, > > >> Indeed - usually, proxied objects shouldn't have to be aware of the > >> fact. That doesn't mean your variation on the proxy pattern is > >> necessarily bad design (hard to tell without lot of context anyway...), > >> but still there's some alarm bell ringing here IMHO - IOW : possibly the > >> right thing to do, but needs to be double-checked. > > > I'm kind of looking at options and not dead-set on decorators, but I can't > > find any other "elegant enough" solution which wouldn't lead to such tight > > coupling. The problem I'm trying to solve is not much more complicated than > > what I have already described > > Well... You didn't mention why you need a proxy to start with !-) > > > so if anybody can suggest a better approach - > > I'm all for it. > > (snip code) > > > > >> My point is that: > >> 1/ you shouldn't have to rewrite a decorator function - with basically > >> the same code - for each possible proxy class / attribute name pair combo > >> 2/ making the decorator an attribute of the proxy class makes > >> dependencies clearer (well, IMHO at least). > > > agreed on all points > > >> I'm still a bit uneasy wrt/ high coupling between A and B, and if I was > >> to end up with such a design, I'd probably take some times to be sure > >> it's really ok. > > > that is the question that troubles me at this point - thus my original post > > (read the subject line ;) ). ?I like the clarity decorators bring to the > > code and the fact that it's a solution pretty much "out-of-the-box" without > > need to create something really-really custom, but I'm worried about tight > > coupling and somewhat backward logic that they would introduce (the way I > > envisioned them). > > Well... The canonical solution for delegation in Python is using > __getattr__. Your problem - according to this post and your answer to > Diez - is that your proxy may have to > 1/ delegate to more than one object > 2/ don't necessarily delegate each and any attribute access > > I can envision one solution using both __getattr__ and a simple decorator: > > def proxy(func): > ? ? func._proxied = True > ? ? return func > > class A(object): > ? ? ?def __init__(self, delegates): > ? ? ? ? ?self._delegates = delegates > ? ? ?def __getattr__(self, name): > ? ? ? ? ?for d in self.__delegate: > ? ? ? ? ? ? ?func = getattr(d, name) > ? ? ? ? ? ? ?if callable(func) and getattr(func, '_proxied', False): > ? ? ? ? ? ? ? ? ?return func > ? ? ? ? ?raise AttributeError( > ? ? ? ? ? ? ? ?'object %s has no attribute '%s' % (self.__class__, name) > ? ? ? ? ? ? ? ?) > > class B(object): > ? ? ?def __init__(self): > ? ? ? ? ?self.val='bval' > > ? ? ?@proxy > ? ? ?def bmethod(self,a): > ? ? ? ? ?print "B::bmethod" > ? ? ? ? ?print a, self.val > > ? ? ?@proxy > ? ? ?def bmethod2(self,a): > ? ? ? ? ?print "B::bmethod2" > ? ? ? ? ?print a, self.val > > class C(object): > ? ? ?def __init__(self): > ? ? ? ? ?self.val='bval' > > ? ? ?@proxy > ? ? ?def cmethod(self,a): > ? ? ? ? ?print "B::bmethod" > ? ? ? ? ?print a, self.val > > ? ? ?@proxy > ? ? ?def cmethod2(self,a): > ? ? ? ? ?print "B::bmethod2" > ? ? ? ? ?print a, self.val > > a = A([B(), C()]) > > # not tested... > > This solves most of the coupling problems (B and C still have to make > clear which methods are to be proxied, but at least they need not know > which class will be used as proxy), and makes sure only 'allowed' method > calls are delegated. But I wouldn't call it a perfect solution neither. > If you do have more than one object having method xxx, only the first > one will match... And let's not talk about the lookup penalty. > > There's a possible variant that avoids the call to __getattr__ (in > short: attaching delegation instancemethods to A instance in the > initializer for each proxied method in delegates), but that wont solve > the problem of potential name clashes. > > My 2 cents... You should write it like this: class B(object): @A.proxy def bmethod(self,a): Making 'proxy' a class method on A. In case different A instances (do you have more than one BTW?) proxy different objects, you could make it a plain old method. a= A() class B(object): @a.proxy def bmethod(self,a): I recommend this solution so that if you add a method to a B instance later, 'a' can be notified simply.: b.meth3= a.proxy( meth3 ) The big problem with that is if 'a' has 'b' in its constructor. You can reverse that, since B 'knows' about it proxy object quite a bit anyway. What you've said implies that you only have one B instance, or only one per A instance. Is this correct? I agree that __setattr__ is the canonical solution to proxy, but you have stated that you want each proxied method to be a member in the proxy class. From mbrkic at invalid_mail.adress Wed Sep 24 09:17:08 2008 From: mbrkic at invalid_mail.adress (Marin Brkic) Date: Wed, 24 Sep 2008 15:17:08 +0200 Subject: Making small executive file for distribution Message-ID: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Not commercial distribution, but an academic kind of sorts - giving the exe file to coleagues, so they can use it in their work. Giving .py file is not an option, since due to centralized computer maintenance, they don't (and cannot) have installed python (except the ones that bring their own computer at work, but those are an exception). As far as I know py2exe is the only option which can do such a thing (make exe files from scripts). Is there a way to make those exe files a little smaller (for a small script they easily go up to 5-10 mb). Has anyone had a situation like this ? All your inputs and suggestions are more then welcomed. -- Marin From sayananbig at gmail.com Thu Sep 25 15:06:51 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Thu, 25 Sep 2008 12:06:51 -0700 (PDT) Subject: python timers and COM/directshow References: <ee4ce745-536d-48ca-84f9-1665bd416fc3@x16g2000prn.googlegroups.com> <mailman.1401.1222168999.3487.python-list@python.org> <5b01cc61-60bf-4a6c-b88b-932cf2fc8e0a@s20g2000prd.googlegroups.com> Message-ID: <c7c368ac-60dc-4589-935c-d0443fd79486@r15g2000prd.googlegroups.com> Ok, so I actually found a solution to this out there, and decided I'd post back here and share it. import pygtk pygtk.require('2.0') import gtk import ctypes from ctypes import * from comtypes import client from ctypes.wintypes import * import gobject def delete_event(widget,event,data=None): global filter_builder, filter_graph, media_control, vseek media_control.Stop vseek.Release filter_builder.Release GUIDATA.win1.Release media_control.Release filter_graph.Release del GUIDATA.win1 del filter_graph del vseek del filter_builder del media_control del all sys.exit([status]) os._exit(status) gtk.main_quit() exit() return False def pauser(widget,data=None): global media_control,playing, scrollbar, vseek if GUIDATA.data_loaded==0: return 0 scrollbar.set_value(vseek.CurrentPosition*30) media_control.Pause() playing=0 return 0 def player(widget,data=None): global media_control, vseek, scrollbar,playing if GUIDATA.data_loaded==0: return 0 media_control.Run() playing=1 gobject.timeout_add(1,on_timer,scrollbar) def scrollbar_callback(widget,scroll, data=None): global media_control, vseek vseek.CurrentPosition= scrollbar.get_value()/30 return 0 def on_timer(data=None): global scrollbar, vseek, playing, media_control if (playing==1)and (vseek.CurrentPosition*30)<int(frame2.get_text()) : g= vseek.CurrentPosition scrollbar.set_value(g*30) f= "%d" %(vseek.CurrentPosition*30) curframe.set_text(f) print "update" return True win = gtk.Window() win.connect("destroy", lambda x: gtk.main_quit()) win.set_default_size(500,800) win.set_title("LISA GUI") filename= LPCWSTR("mymovie.avi") #importing quartz.dll and qedit.dll for filtergraph construction qedit = client.GetModule('qedit.dll') # DexterLib quartz= client.GetModule('quartz.dll') CLSID_FilterGraph = '{e436ebb3-524f-11ce-9f53-0020af0ba770}' filter_graph = client.CreateObject(CLSID_FilterGraph,interface=qedit.IFilterGraph) filter_builder = filter_graph.QueryInterface(qedit.IGraphBuilder) media_control = filter_builder.QueryInterface(quartz.IMediaControl) GUIDATA.win1= filter_builder.QueryInterface(quartz.IVideoWindow) filter_builder.RenderFile(GUIDATA.video, None) GUIDATA.win1.SetWindowPosition(512, 0, 512, 400) vseek=filter_graph.QueryInterface(interface=quartz.IMediaPosition) adj= gtk.Adjustment(1,1,30*vseek.Duration+1,1,1.0,1.0) scrollbar = gtk.HScale(adj) scrollbar.set_update_policy(gtk.UPDATE_CONTINUOUS) scrollbar.connect("change_value",scrollbar_callback) scrollbar.show() hbox6=gtk.HBox(False,0) hbox6.pack_start(scrollbar,True,True) hbox6.show() vbox.pack_end(hbox6,False,True) play_video= gtk.Button("Play") play_video.connect("clicked",player) play_video.show() pause_video= gtk.Button("Pause") pause_video.connect("clicked",pauser) pause_video.show() hbox4= gtk.HBox(False,0) hbox4.pack_start(play_video,True,True) hbox4.pack_start(pause_video,True,True) hbox4.show() vbox.pack_end(hbox4,False,True) vbox.show() win.add(vbox) win.show_all() gtk.main() From tjreedy at udel.edu Wed Sep 10 19:22:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 19:22:38 -0400 Subject: Generator functions and user interfaces In-Reply-To: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> References: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> Message-ID: <ga9krv$o6j$1@ger.gmane.org> psaffrey at googlemail.com wrote: > I'm trying to implement an interactive graph visualisation tool using > matplotlib. > > I want to use a spring layout, where nodes repulse each other and > edges act as springs to pull connected nodes together. Usually, this > algorithm runs through a number of iterations of attraction/repulsion > to allow the nodes to converge to suitable positions. However, rather > than running all these iterations to lay out the graph and then > rendering it, I want to animate the graph as it is "springing" into > place, and then allow the user to drag nodes around and have the graph > redraw on the fly. > > My idea for doing this was to use a generator function, where I yield > the position of the nodes after each iteration and then call draw() on > the position yielded. Does this seem like a sensible approach? To me, no. The reasons for using one do not apply here. What you describe is much like a game with auto updates plus user intervention. I would write an update function and add it to the gui mainloop (if running: update()) along with the draw function to be tied into the gui redraw (those parts I know little about). I would allow use of the spacebar instead of or in addition to a button to toggle 'running' on and off. That is standard in games that allow users to stop the action. tjr From rajan.sriram at gmail.com Tue Sep 9 19:01:09 2008 From: rajan.sriram at gmail.com (Sriram Rajan) Date: Tue, 9 Sep 2008 16:01:09 -0700 Subject: Pexpect echoes twice for each read Message-ID: <b4bc028b0809091601v5ed27cddid4e5bb40d0103f2a@mail.gmail.com> For some reason, Using pexpect causes my output to echo twice when I connect from my MAC Darwin (10.4) to Linux (CentOS release 5 ): The program: --------------------- #!/usr/bin/python # Automatic scp to remote host # Input 1 : filename # Input 2 : destination folder # Input 3 : hostname import pexpect import sys,re ssh_cmd = "ssh " + sys.argv[3] ssh_handle = pexpect.spawn (ssh_cmd) ssh_handle.logfile = sys.stdout PROMPT = "\$\ $" try: ssh_handle.expect(PROMPT) ssh_handle.sendline ("scp "+ sys.argv[1] +" root at 192.168.1.254:" + sys.argv[2] ) ssh_handle.expect("password:") ssh_handle.sendline(" ") ssh_handle.expect(PROMPT) except pexpect.TIMEOUT: ssh_handle.logfile.write("\n Pexpect timeout !!\n") sys.exit(1) except KeyboardInterrupt: ssh_handle.logfile.write("\n User interrupt!\n") sys.exit(2) ssh_handle.close() Output: ----------- $ python pexpect_test.py replace_line_break.sh /tmp/ 10.5.254.18 Last login: Tue Sep 9 15:45:05 2008 from sriram-macbook.dhcp.2wire.com $ scp replace_line_break.sh root at 192.168.1.254:/tmp/ scp replace_line_break.sh root at 192.168.1.254:/tmp/ root at 192.168.1.254's password: replace_line_break.sh 100% 296 0.3KB/s 00:00 $ $ From diordna at gmail.com Wed Sep 10 20:34:37 2008 From: diordna at gmail.com (Stephen Johnson) Date: Wed, 10 Sep 2008 20:34:37 -0400 Subject: Logix - gone? In-Reply-To: <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> References: <276719.72706.qm@web95107.mail.in2.yahoo.com> <mailman.835.1221086049.3487.python-list@python.org> <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> Message-ID: <2B10085D-29D6-4EA7-A947-34880D251A1E@gmail.com> I found Logix (http://livelogix.net/logix/) while looking for something else and thought it looked like a very interesting project. Unfortunately, the blog, mailing list, and Trac links are broken, and the contact email address bounces. I am interested in playing with it and working on it if the original author has dropped it. Does anyone know where I could get the source? I am asking this here because Logix compiles to Python bytecode, and the author announced to this list at one time. Tom Locke, if you're out there... -Steve Johnson (www.steveasleep.com) From tino at wildenhain.de Tue Sep 23 09:10:28 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 23 Sep 2008 15:10:28 +0200 Subject: finding domain name In-Reply-To: <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> <mailman.1404.1222174222.3487.python-list@python.org> <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> Message-ID: <48D8EAC4.1040409@wildenhain.de> Bobby Roberts wrote: >> Depends on the technology/web framework. If you use WSGI, you should use >> something like: >> >> host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] >> >> -- Gerhard > > Yeah i already tried environ("SERVER_NAME") but get a key error when i > do. You could output the whole environ to see what you get and how it is called. I'd recommend however to check that you are using a configured value and not something sent by the client if you are going to use it during filesystem lookup. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080923/1555a9de/attachment-0001.bin> From castironpi at gmail.com Wed Sep 3 19:34:28 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 3 Sep 2008 16:34:28 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <e8d089a6-f728-4681-9319-7d8f2f099ac6@p31g2000prf.googlegroups.com> On Sep 3, 7:48?am, bearophileH... at lycos.com wrote: > Empty Python lists [] don't know the type of the items it will > contain, so this sounds strange: > > >>> sum([]) > > 0 > > Because that [] may be an empty sequence of someobject: > > >>> sum(s for s in ["a", "b"] if len(s) > 2) > > 0 > > In a statically typed language in that situation you may answer the > initializer value of the type of the items of the list, as I do in the > sum() in D. > > This sounds like a more correct/clean thing to do: > > >>> max([]) > > Traceback (most recent call last): > ? File "<stdin>", line 1, in <module> > ValueError: max() arg is an empty sequence > > So it may be better to make the sum([]) too raise a ValueError, in > Python 3/3.1 (if this isn't already true). On the other hand often > enough I have code like this: > > >>> max(fun(x) for x in iterable if predicate(x)) > > This may raise the ValueError both if iterable is empty of if the > predicate on its items is always false, so instead of catching > exceptions, that I try to avoid, I usually end with a normal loop, > that's readable and fast: > > max_value = smallvalue > for x in iterable: > ? ? if predicate(x): > ? ? ? ? max_value = max(max_value, fun(x)) > > Where running speed matters, I may even replace that max(max_value, > fun(x)) with a more normal if/else. > > A possible alternative is to add a default to max(), like the next() > built-in of Python 2.6: > > >>> max((fun(x) for x in iterable if predicate(x)), default=smallvalue) > > This returns smallvalue if there are no items to compute the max of. > > Bye, > bearophile Two thoughts: 1/ 'Reduce' has a 'default' argument-- they call it 'initial'. >>> reduce( max, [ 0, 1, 2, 3 ] ) 3 >>> reduce( max, [ 0, 1, 2, 'a' ] ) 'a' >>> reduce( max, [ 0, 1, 2, 'a', 'b' ] ) 'b' 2/ Introduce a 'max' class object that takes a default type or default argument. Query the default for an 'additive' identity, or query for a 'comparitive' identity, comparisons to which always return true; or call the constructor with no arguments to construct one. From sjmachin at lexicon.net Tue Sep 2 17:27:02 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 14:27:02 -0700 (PDT) Subject: Renumbering References: <mailman.386.1220389036.3487.python-list@python.org> Message-ID: <4e6091af-bc00-4408-beda-adfa7f17dc63@b30g2000prf.googlegroups.com> On Sep 3, 6:57 am, "Francesco Pietra" <chiendar... at gmail.com> wrote: > Hi; > > I would like to renumber, starting from 1, column 6 (i.e, 428 become > 1, 429 becomes 2, etc for a very long list) > > ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 [snip] > ATOM 3437 O SER B 429 144.543 83.756 79.676 1.00134.86 2SG3439 > > Distinctive character is column 5, i.e., it must be set that only > lines containing "B" should be renumbered. > > As you can see, the number of lines for a particular value in column 6 > changes from situation to situation, and may even be different for the > same name in column 4. For example, LEU can have a different number of > lines depending on the position of this amino acid (leucine). The above paragraph is extremely unclear. > > Thanks for help You haven't asked a question, and haven't given any background. What is your experience with Python? Any other language? Are you expecting somebody to write a script for you, or just give you a few hints? Is this homework? Have you put any effort into trying to write a script yourself? Etc etc etc From michele.simionato at gmail.com Fri Sep 5 07:26:04 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 5 Sep 2008 04:26:04 -0700 (PDT) Subject: atomic section in code References: <a475a219-1577-4018-a541-5b05c87f6f71@i76g2000hsf.googlegroups.com> <mailman.544.1220605512.3487.python-list@python.org> Message-ID: <b64f6afa-9c63-4c71-b455-381a3557d326@e39g2000hsf.googlegroups.com> On Sep 5, 10:59?am, Fredrik Lundh <fred... at pythonware.com> wrote: > > 1) seehttp://effbot.org/zone/thread-synchronization.htm The page you link here is WAYS better than the standard documentation of the threading module. Generally speaking, the effbot zone contains a lot of improvements over the standard docs which are lacking in various areas. I have always wondered why they are kept separated. Wouldn't be nice to have the standard docs integrated with the effbot docs? Are there plans in this sense and if not, why not? Michele Simionato From gary at byoteki.com Sun Sep 28 16:11:20 2008 From: gary at byoteki.com (Gary M. Josack) Date: Sun, 28 Sep 2008 16:11:20 -0400 Subject: generate random digits with length of 5 In-Reply-To: <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> References: <e1923ff8-8150-41b6-9444-19c14b4d2f6f@8g2000hse.googlegroups.com> <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> Message-ID: <48DFE4E8.2010307@byoteki.com> Chris Rebert wrote: > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <sotirac at gmail.com> wrote: > >> Wondering if there is a better way to generate string of numbers with >> a length of 5 which also can have a 0 in the front of the number. >> >> >> <pre> >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 >> elements >> code = 'this is a string' + str(random_number[0]) + >> str(random_number[1]) + str(random_number[2]) + str(random_number[3]) >> + str(random_number[4]) >> > > code = ''.join(str(digit) for digit in random_number) > > Regards, > Chris > > >> </pre> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> will random.randint(10000,99999) work for you? From sbassi at clubdelarazon.org Sat Sep 27 14:48:22 2008 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sat, 27 Sep 2008 15:48:22 -0300 Subject: python for *nix system admins In-Reply-To: <92da89760809271132r769411e6t2771b625bbeb04f2@mail.gmail.com> References: <mailman.1578.1222503615.3487.python-list@python.org> <1222520796.630579@athprx04> <170543c70809271123j1334d12ardd09c25ce479978f@mail.gmail.com> <92da89760809271132r769411e6t2771b625bbeb04f2@mail.gmail.com> Message-ID: <9e2f512b0809271148t186a315oa106c99c34ea8c27@mail.gmail.com> On Sat, Sep 27, 2008 at 3:32 PM, Eric Wertman <ewertman at gmail.com> wrote: > I've been growing a library of my own functions, that use the names of > unix commands. They are just conveniences, of course, but I'd suggest > the same for sysadmins, it's handy. Can you share it? Best, SB. From afilash at gmail.com Mon Sep 8 02:17:50 2008 From: afilash at gmail.com (abhilash pp) Date: Mon, 8 Sep 2008 11:47:50 +0530 Subject: firefox timestamp Message-ID: <9f9d35df0809072317h49ccec2ep72524f8d4900daa0@mail.gmail.com> Hi all, I don't know if this question will fit on this section, any way my query is , i have used one script demork.py to extract details from Firefox history.dat file and now the problem is how to convert the TIMESTAMP given by that to normal date and time. example timestams are like this, 1202919771609375 1213874676203125 1215693263859375 i have used datetime module for this but it gave me error >>> import datetime >>> datetime.datetime.fromtimestamp(1215693263859375) Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> datetime.datetime.fromtimestamp(1215693263859375) ValueError: timestamp out of range for platform time_t please help me to convert this ? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/041fcb2a/attachment-0001.html> From jaywgraves at gmail.com Tue Sep 2 14:50:08 2008 From: jaywgraves at gmail.com (jay graves) Date: Tue, 2 Sep 2008 11:50:08 -0700 (PDT) Subject: Large amount of files to parse/organize, tips on algorithm? References: <a8ca9f87-4bf8-4a74-b4ee-902ff3d328ab@x35g2000hsb.googlegroups.com> <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> <6dc5719f-a65b-4194-b09c-b9bbb55ee788@e53g2000hsa.googlegroups.com> Message-ID: <d266a870-8e1b-4995-9717-a565ea566644@c65g2000hsa.googlegroups.com> On Sep 2, 1:02?pm, cnb <circularf... at yahoo.se> wrote: > over 17000 files... > > netflixprize. http://wiki.python.org/moin/NetflixPrizeBOF specifically: http://pyflix.python-hosting.com/ From ppearson at nowhere.invalid Fri Sep 19 11:37:20 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 19 Sep 2008 15:37:20 GMT Subject: Python newbie References: <gavjfd$mvd$1@registered.motzarella.org> <pan.2008.09.19.08.13.05@REMOVE.THIS.cybersource.com.au> Message-ID: <6jhv9gF3fiosU1@mid.individual.net> On 19 Sep 2008 08:13:05 GMT, Steven D'Aprano wrote: > On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote: [snip] >> perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' >> >> The equivalent in Python looks like this: > > Actually, no it doesn't. The equivalent looks more like this: > > > $ python -c 'a=[1,2,3]; a=[2*x for x in a]; > for x in a: > print x' > 2 > 4 > 6 Good job, SD'A. A note for Mladen Gogala: the [...for...] construction in a=[2*x for x in a]; is called a list comprehension, and is wonderful for shortening and clarifying code. One of the pleasures of following this group is watching the old hands answer noob questions with one or two list comprehensions. -- To email me, substitute nowhere->spamcop, invalid->net. From jallen at dashcourses.com Mon Sep 29 09:09:29 2008 From: jallen at dashcourses.com (Jeanne Allen) Date: Mon, 29 Sep 2008 09:09:29 -0400 Subject: SPECIAL DISCOUNTS - Online Python Training Message-ID: <000601c92234$9e07b9c0$da172d40$@com> Do you know anyone who is looking for training on Python? We have two courses taught online with hands-on exercises done on remote PCs. . Python Intro Part 1 - Live On-Line, 8:30am - 12:30pm EST, November 10 to 13, 2008 . Python Intro Part 2 - Live On-Line, 8:30am - 12:30pm EST, November 17 to 20, 2008 When you sign up for either course we will give you a special $200 discount bringing the price to $695. If you sign up for both Part 1 and Part 2 and we'll give you a total discount of $500 (bringing the total price for both courses to $1,290. Please be sure to mention Coupon Code 1214 to receive the discount. You can call me to enroll, or enroll online at http://www.dashcourses.com/public-courses.html. Python Intro Part 1 introduces the student to the basics of writing and running Python scripts, such as variables, file operations, and flow control. Emphasis is placed on features unique to Python, such as tuples, array slices, and output formatting. This is a hands-on programming class. All concepts are reinforced by informal practice during the lecture followed by graduated lab exercises, and all labs are done using remote PC's so there's nothing to download on your office or home PC. For more information, click on http://www.dashcourses.com/public-courses/public-courses/python-intro-part-1 -public-training-course.html. Python Intro Part 2 moves the beginning Python programmer on to more advanced features such as regular expressions, working with binary data, and using the extensive functionality of Python modules. As with Part 1, extra emphasis is placed on features unique to Python. This is also a hands-on programming class. All concepts are reinforced by informal practice during the lecture followed by graduated lab exercises, and all labs are done using remote PC's so there's nothing to download on your office or home PC. This course provides a practical introduction to a working programming language, not an academic overview of syntax and grammar. Students will immediately be able to use Python to complete tasks in the real world. For more details, click on http://www.dashcourses.com/public-courses/public-courses/python-intro-part-2 -public-training-course.html. Thanks for passing this along - Come enjoy our FREE PowerHours! * Oct 27: Python or Perl * Nov 5: USB - Where are we going? * Nov 19: Spring Security to Secure your Java Web Application http://www.dashcourses.com/contests/dashconnect.html Check out our full schedule of online classes! Project Management, Java, PCI, USB, Perl, Python.and much, much more http://www.dashcourses.com/public-courses.html Sincerely, Jeanne Allen Director of Distance Learning Dashcourses International (540) 349-0875 <http://www.dashcourses.com/> www.dashcourses.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080929/3f7579bb/attachment-0001.html> From deets at nospam.web.de Sun Sep 21 06:49:24 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 21 Sep 2008 12:49:24 +0200 Subject: How to kill threading.Thread instance? In-Reply-To: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> References: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> Message-ID: <6jmn5kF42hreU1@mid.uni-berlin.de> dmitrey schrieb: > hi all, > Is there a better way to kill threading.Thread (running) instance than > this one > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 > (it's all I have found via google). > Nope. There might be other ways technically, but none of them falls into a "better"-classification. Diez From karthikbalaguru79 at gmail.com Sun Sep 14 10:21:01 2008 From: karthikbalaguru79 at gmail.com (karthikbalaguru) Date: Sun, 14 Sep 2008 07:21:01 -0700 (PDT) Subject: tkinter for my python program !! References: <f865e11e-80d5-4c21-9e72-f7b5e57f2bf0@l64g2000hse.googlegroups.com> <6em5snF7r22oU3@mid.uni-berlin.de> <63ff0b6f-8c75-4172-b836-8497870544ca@s50g2000hsb.googlegroups.com> <6em86gF7q9djU1@mid.uni-berlin.de> Message-ID: <8c9f34d7-a4ab-4c8b-93bd-bf0ba01d5fd8@q5g2000prf.googlegroups.com> On Jul 22, 7:11?pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > karthikbalaguru wrote: > > On Jul 22, 6:32 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > >> karthikbalaguru wrote: > >> > Hi, > > >> > One of my python program needs tkinter to be installed to run > >> > successfully. > >> > I am using Redhat 9.0 and hence tried installing by copying the > >> > tkinter-2.2.2-36.i386.rpm > >> > alone from the CD 3 to my pc. But, it is not getting installed and is > >> > failing by throwing > >> > the below errors. Should i need to configure / install any specific > >> > files for resolving this issue ? > > >> > [root at localhost karthik]# rpm -ivh tkinter-2.2.2-26.i386.rpm > >> > warning: tkinter-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, > >> > key ID db42a > >> > 60e > >> > error: Failed dependencies: > >> > ? ? ? ? libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > >> > ? ? ? ? libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > >> > ? ? ? ? libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > >> > Any ideas ? > > >> Yes: you should consider reading error-messages. What does > > >> error: Failed dependencies: > >> ? ? ? ? ?libtcl8.3.so is needed by tkinter-2.2.2-26.i386 > >> ? ? ? ? ?libtix8.1.8.3.so is needed by tkinter-2.2.2-26.i386 > >> ? ? ? ? ?libtk8.3.so is needed by tkinter-2.2.2-26.i386 > > >> look like for you? > > >> Small hint: if you install something that depends on something else, you > >> need to .... the missing dependency first. Fill in the dots... > > > I find that it needs python-2.2.2-26.i386 and hence i tried installing > > python and i > > land here :( :( > > > [root at localhost karthik]# rpm -ivh python-2.2.2-26.i386.rpm > > warning: python-2.2.2-26.i386.rpm: Header V3 DSA signature: NOKEY, key > > ID db42a60e > > error: Failed dependencies: > > ? ? ? ? libdb-4.0.so is needed by python-2.2.2-26.i386 > > ? ? ? ? python < 2.4.3-18.fc6 conflicts with python- > > devel-2.4.3-18.fc6.i386 > > [root at localhost karthik]# > > > I find that python 2.4.3-18.fc6 is being used by many of applications. > > But, the program i am trying to run needs python-2.2.2-26. > > So, how to resolve this issue ? > > Are you *sure* it requires python2.2? If yes, why can't fedora install > several python versions together? Ubuntu for sure can. But Python2.2 is > *ancient* - you might need to compile it yourself. > Another method of resolving the whole problem related to rpm dependencies was using the 'yum' utility in Fedora Cores(I use FC2) and 'up2date' utility in RedHat. Karthik From deets at nospam.web.de Mon Sep 1 02:55:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 08:55:03 +0200 Subject: Using NLTK in Java In-Reply-To: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> Message-ID: <6i1hu9FnvcngU1@mid.uni-berlin.de> hussainsaiger at gmail.com schrieb: > I am trying to convert a python module (that contains the use of > NLTK.Corpus) by jythonc. It is not able to include nltk dependencies > within the java class it creates. So when i use this class in java, it > fails to recognize nltk. Can anyone please let me know how should i > use nltk in python/jython modules so i can use in Java. If there are any binary dependencies, you are out of luck. It won't work. You would need to write a RPC-Server then, with technologies such as XMLRPC or CORBA. Diez From python.list at tim.thechases.com Thu Sep 18 09:39:51 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 18 Sep 2008 08:39:51 -0500 Subject: improving a huge double-for cycle In-Reply-To: <f9b69c58-adcc-4042-b9cc-e152ce0056fa@a1g2000hsb.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <mailman.1206.1221741900.3487.python-list@python.org> <f9b69c58-adcc-4042-b9cc-e152ce0056fa@a1g2000hsb.googlegroups.com> Message-ID: <48D25A27.8090502@tim.thechases.com> > Tim Chase: >> for i in xrange(len(IN)): >> for j in xrange(i+1, len(IN)): >> if IN[i].coordinates == IN[j].coordinates: >> SN.append(IN[i].label) >> >> If my college algorithms memory serves me sufficiently, this >> reduces your O(N^2) to O(N log N) which will garner you some >> decent time savings. > > That's O(n^2) still, it's just half matrix, a triangle. Ah, good catch as I'm thinking about it more, you're right...it's O((N^2)/2) which is just O(N^2). Sigh. I'm not awake enough yet. However, dividing the time by 2 (from 15hr to 7.5hr) is still a significant savings in my book :) However, if list-comprehensions are faster as well, you might be able to do something like SN = [d.label for (i,d) in enumerate(IN) for j in xrange(i+1, len(IN)) if d.coordinates == IN[j].coordinates ] or the slightly more verbose (but closer to my original code) version SN = [IN[i].label for i in xrange(len(IN)) for j in xrange(i+1, len(IN)) if IN[i].coordinates == IN[j].coordinates ] To the OP: As always, throw some timing code on the various samples you get back from the list and see what works for you. -tkc From bignose+hates-spam at benfinney.id.au Sun Sep 14 18:55:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 08:55:20 +1000 Subject: Matching horizontal white space References: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> Message-ID: <8763oy72xz.fsf@benfinney.id.au> Magnus.Moraberg at gmail.com writes: > multipleSpaces = re.compile(u'\\h+') > > importantTextString = '\n \n \n \t\t ' > importantTextString = multipleSpaces.sub("M", importantTextString) Please get into the habit of following the Python coding style guide <URL:http://www.python.org/dev/peps/pep-0008>. For literal strings that you expect to contain backslashes, it's often clearer to use the "raw" string syntax: multiple_spaces = re.compile(ur'\h+') > I would have expected consecutive spaces and tabs to be replaced by > M Why, what leads you to expect that? Your regular expression doesn't specify spaces or tabs. It specifies "the character 'h', one or more times". For "space or tab", specify a character class of space and tab: >>> multiple_spaces = re.compile(u'[\t ]+') >>> important_text_string = u'\n \n \n \t\t ' >>> multiple_spaces.sub("M", important_text_string) u'\nM\nM\nM' You probably want to read the documentation for the Python 're' module <URL:http://www.python.org/doc/lib/module-re>. This is standard practice when using any unfamiliar module from the standard library. -- \ ?If you do not trust the source do not use this program.? | `\ ?Microsoft Vista security dialogue | _o__) | Ben Finney From python-url at phaseit.net Tue Sep 23 08:43:12 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 23 Sep 2008 12:43:12 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 23) Message-ID: <gbao90$j4v$1@lairds.us> QOTW: "Python is THE real integration/composition platform !" - Nicolas Lehuen http://groups.google.com/group/comp.lang.python/msg/05dd6fa4509ab15c Python 2.6rc2 and 3.0rc1 have been released: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6a285ea5ea89bff9/ Using the right algorithm (a single for loop!) and the right data structure (a set!) so often improves computing time *drastically* (from 15 hours to 10 minutes in this example): http://groups.google.com/group/comp.lang.python/browse_thread/thread/21aef9dec3fb5403/ True==1 isn't an obvious fact. Also, why does the bool type exist at all? http://groups.google.com/group/comp.lang.python/browse_thread/thread/1d85b7e32a754e73/ Why some methods (like append) don't return the modified object, while others do? http://groups.google.com/group/comp.lang.python/browse_thread/thread/6196c94118247195/ A design exercise: assign different "weights" to methods--overridable in subclasses or individual instances--so the methods can be chosen at random: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5c90f12e6e7db784/ Grouping items to count them - this leads to discussion of possible implementations of len(arbitrary_iterable): http://groups.google.com/group/comp.lang.python/browse_thread/thread/c8b3976ec3ceadfd/ Killing a thread asynchronously is a bad idea (not just in Python): http://groups.google.com/group/comp.lang.python/browse_thread/thread/b37b57e9c7462fe9/ Discussing ways to secure (untrusted) Python code: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b0c13aaad8c3dc4f/ An [absurd] blog post about Python not being "a full OOP language" triggers a lot of responses: http://groups.google.com/group/comp.lang.python/browse_thread/thread/139c31ff17aed522/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From cjw at ncf.ca Wed Sep 3 09:32:47 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 03 Sep 2008 09:32:47 -0400 Subject: new python docs In-Reply-To: <62c0c392-d4e1-4cae-aae0-38d35c4faf57@w7g2000hsa.googlegroups.com> References: <62c0c392-d4e1-4cae-aae0-38d35c4faf57@w7g2000hsa.googlegroups.com> Message-ID: <g9m3m3$gen$1@theodyn.ncf.ca> Rick Dooling wrote: > Wow! I've been away in other pursuits. > > The new docs are gorgeous and searchable. > > http://docs.python.org/dev/index.html > > Thank you, python.org. Yes, they look crisp and clear. It would have been nice if the Apple folk, in their clear Style Guide, had provided hyperlinks to the various documents referenced. Thanks to all the pythoneers who contributed to the documentation. Colin W. From NIE_DZIALA at gazeta.pl Thu Sep 18 06:26:52 2008 From: NIE_DZIALA at gazeta.pl (Piotr Sobolewski) Date: Thu, 18 Sep 2008 12:26:52 +0200 Subject: how can I use a callable object as a method Message-ID: <gatadc$s6f$1@inews.gazeta.pl> Hello, I would like to use a callable object as a method of a class. So, when I have such normal class: class f: version = 17 def a(self): return self.version f1 = f() print f1.a() I want to change it to something like that: class add: def __call__(self, another_self): return another_self.version class f: version = 17 a = add() f1 = f() print f1.a() However, the second version does not work. I think I understand why. That's because "a" inside f1 is not a function (but an object). So f1.a is not a method. So when I do f1.a(), the implicit argument self is not passed. Q1: Am I right? Is this the problem? Q2: What can I do to make it work? From bdesth.quelquechose at free.quelquepart.fr Thu Sep 4 13:49:21 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 19:49:21 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> <acdc94a1-9f8c-49f3-b063-dd536e480d07@v39g2000pro.googlegroups.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> Message-ID: <48c03b91$0$14747$426a74cc@news.free.fr> Ivan Illarionov a ?crit : > On 4 ????, 22:59, Carl Banks <pavlovevide... at gmail.com> wrote: >> You can write code to guard against this if you want: >> >> class A: >> legal = set(["x"]) >> def __setattr__(self,attr,val): >> if attr not in self.legal: >> raise AttributeError("A object has no attribute '%s'" % >> attr) >> self.__dict__[attr] = val >> def __init__(self,x): >> self.y = x >> >> I suspect most people who go into Python doing something like this >> soon abandon it when they see how rarely it actually catches anything. >> > > '__slots__' is better: For which definition of "better" ? __slots__ are a mean to optimize memory usage, not to restrict dynamism. Being able to dynamically add arbitrary attributes is actually a feature, not a bug, and uselessly restricting users from doing so is not pythonic. IOW : don't do that. From castironpi at gmail.com Tue Sep 16 13:49:26 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 10:49:26 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> Message-ID: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> On Sep 16, 10:13?am, cnb <circularf... at yahoo.se> wrote: > >>> sys.path > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > \lib\\site-packages\\PIL'] > > > > Now I have my personal programs in C:/Python25/Progs/ > > How do I add so that I can just do "import somefile" from anywhere in > that directory in the interpreter and it can load files from other > folders in that directory. Add a file: \Lib\site-packages\locals.pth with contents, path to the directory you want to add (/python25/progs/) From george.sakkis at gmail.com Sat Sep 27 11:27:13 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 27 Sep 2008 08:27:13 -0700 (PDT) Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> <Mo7Dk.2064$T65.1885@edtnps82> <48dd5c06$0$26425$426a74cc@news.free.fr> <WvdDk.2157$T65.1610@edtnps82> <f6351d10-2573-4a5c-ab57-d4dd1c7b311c@e53g2000hsa.googlegroups.com> <YKjDk.2022$Pv5.1949@edtnps83> <a7a895ef-ff22-4dc8-8213-97482e5bb19f@z72g2000hsb.googlegroups.com> Message-ID: <c7db7b82-7350-4365-8c12-40f949e739ea@u65g2000hsc.googlegroups.com> On Sep 27, 9:23 am, George Sakkis <george.sak... at gmail.com> wrote: > On Sep 27, 1:44 am, "Dmitry S. Makovey" <dmi... at makovey.net> wrote: > > > I guess my bias is towards more explicit declarations thus > > > bmethod=ProxyMethod('b',B.bmethod) > > > looks more attractive to me, but I stand to be corrected/educated why is > > that not the right thing to do? > > I see where you're coming from and I also prefer explicit reflection > mechanisms instead of strings (e.g. avoid eval/exec as much as > possible). As I mentioned, the second argument to ProxyMethod is (for > all sane purposes) redundant, so if you could implement it in a way > that "bmethod = ProxyMethod('b')" worked, I would be all for it, but > AFAIK it's not possible without a metaclass. Just for completeness, here's a metaclass version that uses ProxyMethod declarations instead of a dict; you'll probably like this better: #======= usage ========================= from proxies import Proxy, ProxyMethod class B(object): def __init__(self, val): self.val = val def bmethod(self,n): print "B::bmethod", self.val, n def bmethod2(self,n,m): print "B::bmethod2", self.val, n, m class C(object): def __init__(self, val): self.val = val def cmethod(self,x): print "C::cmethod", self.val, x def cmethod2(self,x,y): print "C::cmethod2",self.val, x, y cattr = 4 class A(Proxy): def __init__(self, b1, b2, c): print "init A()" # must call Proxy.__init__ super(A,self).__init__(b1=b1, b2=b2, c=c) def amethod(self,a): print "A::mymethod",a bmethod = ProxyMethod('b1') bmethod2 = ProxyMethod('b2') cmethod = ProxyMethod('c') a = A(B(10), B(20), C(30)) a.amethod('foo') print "bound proxy calls" a.bmethod('foo') a.bmethod2('bar','baz') a.cmethod('foo') try: a.cmethod2('bar','baz') except Exception, ex: print ex print "unbound proxy calls" A.bmethod(a,'foo') A.bmethod2(a,'bar','baz') A.cmethod(a, 'foo') try: A.cmethod2(a,'bar','baz') except Exception, ex: print ex #======= output ======================================== init A() A::mymethod foo bound proxy calls B::bmethod 10 foo B::bmethod2 20 bar baz C::cmethod 30 foo 'A' object has no attribute 'cmethod2' unbound proxy calls B::bmethod 10 foo B::bmethod2 20 bar baz C::cmethod 30 foo type object 'A' has no attribute 'cmethod2' #====== proxies.py ====================================== class _ProxyMeta(type): def __new__(meta, name, bases, namespace): for attrname,value in namespace.iteritems(): if isinstance(value, ProxyMethod) and value.name is None: value.name = attrname return super(_ProxyMeta,meta).__new__(meta, name, bases, namespace) class ProxyMethod(object): def __init__(self, proxy_attr, name=None): self._proxy_attr = proxy_attr self.name = name def __get__(self, proxy, proxytype): if proxy is not None: return self.__get_target_attr(proxy) else: return self.__unbound_method def __unbound_method(self, proxy, *args, **kwds): method = self.__get_target_attr(proxy) return method(*args, **kwds) def __get_target_attr(self, proxy): try: delegate = getattr(proxy, self._proxy_attr) return getattr(delegate, self.name) except AttributeError: raise AttributeError('%r object has no attribute %r' % (proxy.__class__.__name__, self.name)) class Proxy(object): __metaclass__ = _ProxyMeta def __init__(self, **attr2delegate): self.__dict__.update(attr2delegate) #====================================================== If you want to eliminate completely specifying attributes with strings, it's easy to modify the above so that you write instead: class A(Proxy): ... bmethod = ProxyMethod(lambda self: self.b1) bmethod2 = ProxyMethod(lambda self: self.b2) This is more verbose for the common case, but it's more flexible in cases where the callable may be more complex than a plain getattr(). Actually you can support both, it doesn't have to be either/or; just check whether the argument to ProxyMethod is a callable and if not, make it: from operator import attrgetter class ProxyMethod(object): def __init__(self, proxy_attr, name=None): if not callable(proxy_attr): proxy_attr = attrgetter(proxy_attr) ... Remaining Implementation is left as an exercise to the reader ;) George From mail at timgolden.me.uk Thu Sep 18 10:06:20 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 18 Sep 2008 15:06:20 +0100 Subject: XML Processing In-Reply-To: <00ef01c9198c$c4bce780$4e36b680$@rawlins@thinkbluemedia.co.uk> References: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> <48D24638.9010601@timgolden.me.uk> <00ef01c9198c$c4bce780$4e36b680$@rawlins@thinkbluemedia.co.uk> Message-ID: <48D2605C.9080808@timgolden.me.uk> Robert Rawlins wrote: >> Some is going to kick themselves when they realise >> that ElementTree *is* built in to Python 2.5 >> >> http://docs.python.org/whatsnew/modules.html#SECTION0001420000000000000000 > > Tim, Andrii, > > Thanks for the heads up on that! I hadn't noticed they're made it part of > the platform modules, that's excellent news. > > In theory I should just be able to amend my import paths and we'll be good > to go, no install external modules. I imagine I'm not the only person with conditional imports of this type: try: from xml.etree import cElementTree as ET except ImportError: from elementtree import ElementTree as ET TJG From sudhi.herle at gmail.com Fri Sep 12 02:05:56 2008 From: sudhi.herle at gmail.com (sudhi.herle at gmail.com) Date: Thu, 11 Sep 2008 23:05:56 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> Message-ID: <68726994-db75-46b2-90ba-c3413326a455@k37g2000hsf.googlegroups.com> On Sep 5, 9:38?am, Helmut Jarausch <jarau... at skynet.be> wrote: > Hi, > > I need to hash arrays of integers (from the hash module). > > So, I have to derive from array and supply a __hash__ method. I don't believe you need to derive from an array. Here are two simple and well known hash functions you can use readily: def djbhash(a): """Hash function from D J Bernstein""" h = 5381L for i in a: t = (h * 33) & 0xffffffffL h = t ^ i return h def fnvhash(a): """Fowler, Noll, Vo Hash function""" h = 2166136261 for i in a: t = (h * 16777619) & 0xffffffffL h = t ^ i return h if __name__ == '__main__': arr = [1001, 3001, 5001, 9001, 10011, 10013, 10015, 10017, 10019, 20011, 23001] print djbhash(arr) print fnvhash(arr) And finally, here is an excellent page that explains hash functions: http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx Here is Noll's page where he explains the FNV Hash: http://www.isthe.com/chongo/tech/comp/fnv/ Hope this helps, -- Sudhi From tjreedy at udel.edu Tue Sep 23 04:25:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 04:25:43 -0400 Subject: a short-cut command for globals().clear() ?? In-Reply-To: <49ffb44f-c14d-4d38-86fb-eb50e5ef9abf@d1g2000hsg.googlegroups.com> References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> <930ff2e6-c521-4927-acc2-962d3128b85d@v16g2000prc.googlegroups.com> <1f913671-1c21-4018-a841-a5a02a360c3b@k30g2000hse.googlegroups.com> <49ffb44f-c14d-4d38-86fb-eb50e5ef9abf@d1g2000hsg.googlegroups.com> Message-ID: <gba95s$sj9$1@ger.gmane.org> MRAB wrote: > > How about something like this: > > def clear_workspace(): > keep_set = set(['__builtins__', '__doc__', '__name__', > 'clear_workspace']) For 2.6/3.0, add __package__ to the list to be kept. > for x in globals().keys(): > if x not in keep_set: > del globals()[x] > -- > http://mail.python.org/mailman/listinfo/python-list > From adityashukla1983 at gmail.com Mon Sep 15 13:30:13 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Mon, 15 Sep 2008 12:30:13 -0500 Subject: Converting .py files to batch files. Message-ID: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> How can we convert .py files to batch files? is there any library for this? Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/e07a076c/attachment-0001.html> From gherron at islandtraining.com Mon Sep 8 03:21:52 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 08 Sep 2008 00:21:52 -0700 Subject: How do I set a callback in Python? In-Reply-To: <d797403a-e492-403f-933a-bd18ef53d5c0@k13g2000hse.googlegroups.com> References: <d797403a-e492-403f-933a-bd18ef53d5c0@k13g2000hse.googlegroups.com> Message-ID: <48C4D290.8080803@islandtraining.com> catsclaw wrote: > I can't for the life of me figure out how to set a callback in > Python. I have a class, which wraps another class. The second class > needs a callback assigned. I don't want to use globals for it. > Here's what I'd like to do: > > class MyWrapper: > def get_login(self, username): > return self.user, self.pass > > def __init__(self, user, pass): > self.user = user > self.pass = pass > > self.client = Client("connection string") > self.client.callback_login = get_login > Make that list line: self.client.callback_login = self.get_login Then you are passing a "bound" method (meaning bound to a particular instance). The client class calls its callback_login as a normal function with parameters, and the Wrapper get_login will be called on the proper instance of MyWrapper. This is a very common thing for many uses, including callbacks. Hoping I understood what you wanted correctly, Gary Herron > ... but obviously, the Client class, when it calls the callback, > doesn't pass a reference to the "self" object. How do I do this? > > -- Chris > -- > http://mail.python.org/mailman/listinfo/python-list > From marcus at internetnowasp.net Sun Sep 14 21:36:48 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Mon, 15 Sep 2008 09:36:48 +0800 Subject: Recognizing the email package In-Reply-To: <48C9322D.8080502@wingware.com> References: <48C8734B.6060802@internetnowasp.net> <48C9322D.8080502@wingware.com> Message-ID: <48CDBC30.8050405@internetnowasp.net> Hi, Actually i think its the email package that needs to be "redefined", using lazyimporter is a bad decision and a lousy one. Even py2exe could not handle it correctly. Marcus. Wingware Support wrote: > Marcus.CM wrote: >> Is there any reason why the IDE cant recognize the uppercase >> attribute names of the email package but its the recommended naming . > > This is due to the email package using LazyImporter objects to > dynamically assign names at runtime in ways that the Wing source > analyzer doesn't understand. We'll try to fix this in future Wing > versions. > > Thanks, > > John > From bj_666 at gmx.net Tue Sep 2 17:09:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 21:09:09 GMT Subject: Numpy/Scipy set field of matrix? References: <dbc998fb-2618-4fc9-bf46-d3b196227073@f36g2000hsa.googlegroups.com> Message-ID: <6i5obkFol29aU7@mid.uni-berlin.de> On Tue, 02 Sep 2008 13:27:06 -0700, cnb wrote: >>>> m > matrix([[1, 2, 3], > [4, 5, 6], > [7, 8, 9]]) > > how do I set the field 1,2 (=6) to 45 for example? > > > and how do I initialize a matrix and then add values in a for-loop? > > Im using PIL and want to store all the pixels of an image in a matrix. > > But I can't find the appropriate operations. Work through the tutorial in the Python documentation and read some introduction to Numpy. Ciao, Marc 'BlackJack' Rintsch From dmitry at makovey.net Sat Sep 27 01:44:24 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Sat, 27 Sep 2008 05:44:24 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> <Mo7Dk.2064$T65.1885@edtnps82> <48dd5c06$0$26425$426a74cc@news.free.fr> <WvdDk.2157$T65.1610@edtnps82> <f6351d10-2573-4a5c-ab57-d4dd1c7b311c@e53g2000hsa.googlegroups.com> Message-ID: <YKjDk.2022$Pv5.1949@edtnps83> George Sakkis wrote: > You seem to enjoy pulling the rug from under our feet by changing the > requirements all the time :) but that's half the fun! ;) Bit more seriously - I didn't know I had those requirements until now :) I'm kind of exploring where can I get with those ideas. Initial post was based exactly on what I had in my code with desire to make it more automated/{typo,fool}-proof/robust, elegant and possibly faster. Hopefully such behavior is not off-topic on this list (if it is - let me know and I'll go exploring solo). > Although this works, the second argument to ProxyMethod shouldn't be > necessary, it's semantically redundant; ideally you would like to > write it as "bmethod = ProxyMethod('b')". since I'm already on exploratory trail (what about that rug being pulled from under....?) With my code I can do really dirty tricks like this (not necessary that I'm going to): class B_base: def bmethod(self): print 'B_base' class B(B_base): def bmethod(self): print 'B' class A: bmethod=ProxyMethod('b',B_base.bmethod) > As before, I don't think > that's doable without metaclasses (or worse, stack frame hacking). > Below is the update of my original recipe; interestingly, it's > (slightly) simpler than before: Out of curiosity (and trying to understand): why do you insist on dictionaries with strings contents ( {'bmethod' : 'b1' } ) rather than something more explicit ? Again, I can see that your code is working and I can even understand what it's doing, just trying to explore alternatives :) I guess my bias is towards more explicit declarations thus bmethod=ProxyMethod('b',B.bmethod) looks more attractive to me, but I stand to be corrected/educated why is that not the right thing to do? Another thing that turns me away from string dictionaries is that those are the ones causing me more trouble hunting down typos. Maybe it's just "my thing" so I'm not going to insist on it. I'm open to arguments against that theory. One argument I can bring in defence of more explicit declarations is IDE parsing when autocompletion for B.bme... pops up (suggesting bmethod and bmethod2) and with 'b':'bmethod' it never happens. However that's not good enough reason to stick to it if it introduces other problems. What kind of problems could those be? P.S. so far I find this discussion quite educating BTW. I am more of a "weekend programmer" with Python - using basic language for most of things I need, however I decided to explore further to educate myself and to write more efficient code. From sjmachin at lexicon.net Mon Sep 8 19:33:42 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Sep 2008 16:33:42 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <f8c5f1de-d358-468b-81fd-aa8108d8f7e0@q26g2000prq.googlegroups.com> <dde588e9-84eb-4890-ac42-21dd2aec35c6@q26g2000prq.googlegroups.com> <db089fc6-ab11-4a5b-93ee-50c00992f1e1@v13g2000pro.googlegroups.com> <6d1f32aa-0740-4513-9d9e-f48ddf92435b@z72g2000hsb.googlegroups.com> Message-ID: <03b7fe1f-3b0d-4fa4-b62e-4bbe8efa754a@r15g2000prh.googlegroups.com> On Sep 9, 6:12?am, "andyh... at gmail.com" <andyh... at gmail.com> wrote: [big snip] > In the interests of academia (although this isn't homework :)) I'll > answer some of those questions: Understanding your own requirements is , I would have thought, not much to do with "academia" but a very practical idea. > > - Yes, the mapping dict doesn't necessarily have the same number of > entries as the my_dict. It may have less than it or more than it. What behaviour do you expect when there is a key in my_dict that is not in the mapping? > - There will never be dupes of key or value in the mapping. Though > there maybe in my_dict. If there are ever any dupes of a key in a Python dict object, it will be the end of civilisation as we know it. How are you are guaranteeing that there are no value dupes in your mapping? What are the consequences if a dupe sneaks in? > > And, for extra credit, it may be useful to be able to 'translate' the > my_dict back again using the same mapping_dict. ie, using the values > in mapping dict as the new keys in my_dict, and the keys as the new > values. "... as the new values" of what? my_dict?? Don't you mean something like "using the values in mapping dict as the keys in reverse_mapping, and the keys as the values in reverse_mapping"? Cheers, John From marcin201 at gmail.com Mon Sep 29 12:06:11 2008 From: marcin201 at gmail.com (Marcin201) Date: Mon, 29 Sep 2008 09:06:11 -0700 (PDT) Subject: destructor not called References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> <3dec57f0-c829-4420-b36d-58e21c564053@k37g2000hsf.googlegroups.com> Message-ID: <93627810-b437-4b9a-9aad-6837271fd894@m36g2000hse.googlegroups.com> > Others have already replied to your main question; in short you > shouldn't rely on __del__ being called. Regardless, is there a (good) > reason for having an instance reference to the method ? Without > further information, that seems like a code smell. I have dictionary of fxns to do import/export based on the type of request from user so I can call self.Import['html'] or self.Import['text']. Thanks for everyones help. Marcin From maric at aristote.info Mon Sep 15 11:02:45 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 17:02:45 +0200 Subject: Abstract class In-Reply-To: <gals9d$d7i$1@ger.gmane.org> References: <mailman.1008.1221408214.3487.python-list@python.org> <200809151409.14149.maric@aristote.info> <gals9d$d7i$1@ger.gmane.org> Message-ID: <200809151702.46110.maric@aristote.info> Le Monday 15 September 2008 16:42:49 Fredrik Lundh, vous avez ?crit?: > Maric Michaud wrote: > > But this doesn't match what abstract classes are (in C++ for example) > > you're confusing concepts with specific implementations of those > concepts here. > Maybe, that's why I gave this example, but aren't they (conceptually) classes : - which couldn't be instantiated, - which define at least an interface and possibly some behavior, - for which all the undefined methods need to be implemented in concrete classes (the pure virtual methodds in C++) ? That's the exact implementation in C++ but I'm not aware of any other language that implement this notion. Java simplified this a lot, abstracts are interface (type), no behavior. -- _____________ Maric Michaud From d3vvnull at gmail.com Sun Sep 28 15:16:29 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sun, 28 Sep 2008 14:16:29 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DF63B2.2020408@wildenhain.de> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> <48DF63B2.2020408@wildenhain.de> Message-ID: <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> Tino, dude, I'm afraid I lied about my previous post being the last word. There are some things you said here that must be addressed. On Sun, Sep 28, 2008 at 6:00 AM, Tino Wildenhain <tino at wildenhain.de> wrote: > Michael Mabin wrote: > >> I'm exhausted, so I'll just shut up about this after a few final words. >> > > Thank you for your time :-) > >> 1. "edits" is used in data warehousing to describe data scrubbing or >> filtering of fields in records that are used as input sources for loading >> into data warehouses. It's a term that goes way back to batch processing on >> the mainframe, so it's been used this way for a long time. Sometimes we use >> 'validation' interchangeably with 'edit' but our use of validation usually >> involves a check of input data against business rules and not type or range >> checking which we consider 'edits'. So maybe you're not used to hearing the >> term used this way, but it is a variation perhaps of what you're used to. >> > > And so on and so on in the regular top posting manner I thought I was clearing up your statement that "there is no such thing as edits" and then you went on about not knowing what I meant by "edits" . Why do you dismiss my effort to clarify a point you were clearly wrong about? ... > > Just to give you some thoughts again: your solution might be valid for > you in your controlled environment. Yet you just presented it to the > OP without telling him the limits of when this can be used. And this > is outright dangerous. If one sees this without comment and without your > background she will run into problems sooner or later. So my suggestion > was to either don't tell people such solutions at all or tell them > exactly under which circumstances they might be used. > Outright dangerous? Again, you're assuming the OP's problem involved user input from a web-page. I was addressing the stated requirement of the problem. You can't automatically assume that this problem is related to input from a web-page. Why should I code in a manner that I will never encounter? Maybe instead of suggesting that my recommendation is outright dangerous, you yourself might suggest the caveats. Again, most of my experiences lie within the batch environment, but I shouldn't have to qualify my suggestions with 'this is what we do in the batch environment'. On a mailing list, people are free to point out the limits of my recommendation, but that doesn't necessarily disqualify my recommendation. > > Still I think nailing the problem at the apropriate place is a habit > which should generally devloped - as in your example an additional > int() would have fixed it - but still it would not work if you > want to deal with arbitrary strings. So its good to make suggestions > but pretty please think ahead how someone would use it instead of > investing all your energy into defending dangerous programming practice. Again, danger is in the eye of the beholder and the hands of the user and determined mostly by the circumstances. A code generator written in Python is going to be subject to all kinds of programming considerations that are different from those in web applications. > With "we in python" I referred to a fairly amount of literature about > programming in python and it design patterns. Nothing me personally. > I wasn't aware that we are what has been written or what we have read. I thought we refers to people. Though this sounds a lot like religion. And maybe I am guilty of heresy. > Ah and some final words to the controlleness of datawarehouse > applications and similar things: by the time you are designing such > a solutuion you will never know what future applications will be > developed around it so its always best to be prepared. > Huh? What are you talking about? > > "Data scrubbing" seems a common idea but in fact its very hard to do > it right due to the nature of different systems using different > quoting logic. "Dont trust your input" is a habit not only applicable > to web programming - in fact the company I work for does not do much > web application but input validation is something we get even audited > for. > "We" are always mindful of the problems "data scrubbing" entails. Data scrubbing depends on the requirements, like everything else. And of course, it goes without saying that you should not trust your input, that you should check and validate where appropriate. > > Nevertheless I wish you a very good weekend :-) > > Tino > > Peace. Michael -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080928/dc2b44b0/attachment-0001.html> From ireborin at delete.this.gmail.com Tue Sep 30 09:42:58 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 15:42:58 +0200 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6ke1i8F7dmkkU2@mid.uni-berlin.de> Message-ID: <aja4e49oia6nbe6almu2dfpocmk1bvb8i5@4ax.com> On 30 Sep 2008 07:07:52 GMT, Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote: Hello Marc, thanks for answering (on both subjects). I understand now the logic which lays behind what you were explaining in the other one. It cleared things quite a bit. >Well, I don't know if this qualifies as equivalent: > >===== >from __future__ import with_statement >from functools import partial >from itertools import islice >from pprint import pprint > > >def read_group(lines, count): > return [map(int, s.split()) for s in islice(lines, count)] > >def main(): > result = list() > with open('test.txt') as lines: > lines = (line for line in lines if line.strip()) > result = list(iter(partial(read_group, lines, 3), list())) > pprint(result, width=30) >if __name__ == '__main__': > main() >===== I'm afraid I must admit I find the code above totally uncomprehesible (I can't even see where the array here is mentioned - "result"?) and inpractical for any kind of engineering practice I had in mind. Does python, perchance, have some wrapper functions or something, which would allow one to load an array in a more natural "technical" way ? Like something mentioned above in my post (now deleted) ? Also, is there a way to change counter for arrays to go from 0 to 1 ? (first element being with the index 1) ? (probably not since that seems like a language implementation thing, but it doesn't hurt to ask) -- Ivan From castironpi at gmail.com Mon Sep 22 16:49:05 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 13:49:05 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> <48d78c3c$0$6998$426a74cc@news.free.fr> <mailman.1360.1222091143.3487.python-list@python.org> <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> <48d7f46d$0$15502$426a74cc@news.free.fr> <ea7583fc-82c0-4f8c-aeeb-f3de5af8ba69@i76g2000hsf.googlegroups.com> <48d80038$0$27459$426a34cc@news.free.fr> Message-ID: <7b9fffb9-587c-4757-b7c9-2943321a0b6b@z66g2000hsc.googlegroups.com> On Sep 22, 3:28?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > Aaron "Castironpi" Brady a ?crit : > > > On Sep 22, 2:38 pm, Bruno Desthuilliers > > <bdesth.quelquech... at free.quelquepart.fr> wrote: > (snip) > >> Going back to robot-mode, Aaron ? > > > Not getting the same sense of "soul" as from my usual posts. ?I guess > > so. ?Might even drop the name change, too... > > Don't !-) > > > while I'm at it. ?One > > more word from you about it ?and I'm starting a thread, and calling it, > > "Python and my sense of 'soul'". ?Ha ha. > > Please bear with me - and understand that the above half-backed > half-joke was also an implicit aknowledgement of the recent changes in > your mode of communication. I should have added a <wink>, I think... I can attribute it to a change in environment. Going "back" to robot mode would imply one wasn't always in it, and as such I interpreted a tacit compliment. Thank you for the compliment, Bruno. I don't suppose "starting a thread" is much of a threat, after all... at least in isolation. Regardless, as I've stated, I find the feedback valuable that there seems (to people) to be more than one context that I'm writing from, and I appreciate the chance to learn about it. It's an observation an erst friend made once that one can never perceive oneself directly. (Whether that's a virtue depends on what difference there is between self-conscious, and self-aware.) From lists at cheimes.de Sun Sep 14 14:19:17 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 14 Sep 2008 20:19:17 +0200 Subject: Abstract class In-Reply-To: <roy-9FFFBD.13564414092008@news.panix.com> References: <mailman.1008.1221408214.3487.python-list@python.org> <roy-9FFFBD.13564414092008@news.panix.com> Message-ID: <gajkj4$iro$1@ger.gmane.org> Roy Smith wrote: >Are you also going to have DoubleSharpNote and DoubleFlatNote? > > Consider the following code: > > note1 = SharpNote("E4") > note2 = NaturalNote("F4") > if note1 == note2: > print "the same note" > else > print "different notes" > > what should it print? Hehe, tricky question. The answer depends on the music instrument and tuning. On a piano E# and F are on the same key but other instruments (e.g. a violin) treat E# and F as different notes. The enharmonic equivalent E# == F is only valid for some instruments and tunes - noticeable for modern tunes like equal temperament. Christian From bdesth.quelquechose at free.quelquepart.fr Fri Sep 26 16:11:17 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 22:11:17 +0200 Subject: Not fully OO ? In-Reply-To: <00ecf4b4$0$20666$c3e8da3@news.astraweb.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> <48DCC786.2040407@wildenhain.de> <mailman.1541.1222440896.3487.python-list@python.org> <48dcf924$0$4653$426a74cc@news.free.fr> <00ecf4b4$0$20666$c3e8da3@news.astraweb.com> Message-ID: <48dd5dd0$0$26425$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 26 Sep 2008 17:00:59 +0200, Bruno Desthuilliers wrote: > >> Patrick Mullen a ?crit : >>> Depending on the scale of the website I am making, how much I care >>> about editing it in the future, and how much I just want to get >>> something up, I will occasionally use php. And I am a self confessed >>> php hater :) But it's generally the fastest way I know to get >>> something up. So even terrible languages can have their uses! >> Sorry but I fail to see how it relates to the current thread ??? > > I think Patrick is responding to a comment from Tino Wildenhain: That didn't showed here (reading this from c.l.py via free.fr). Sorry. > [quote] > Well then it still depends on the perception of "job done". For example > PHP programmers would bet their soul that their language of choice is > exactly the right one to "get the job done." > [end quote] > > Patrick, you will cause much less confusion if you quote relevant parts > of the text you are replying too. Indeed. At least it would have made clear (to me) there was something missing in the thread... From python-pep at arcor.de Thu Sep 25 15:24:58 2008 From: python-pep at arcor.de (python-pep at arcor.de) Date: Thu, 25 Sep 2008 21:24:58 +0200 Subject: PEP Proposal Message-ID: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Hi, sorry, I have these ideas for longer than 10 years, please have a look on it and comment on it. Thx. ---- This is another proposal for introducing types into Python. There are many reasons for incorporating types into Python, but there is also a lot of concern about doing so because of destroying the original character of Python as a smart script language. This proposal adds several advantages of Prolog(ue) techniques without changing the natural understanding of Python as a language. Proposal: 1. Method definitions can be non-unique if a type is prefixed to one or more of its parameters, or the parameters differ in number. 2. A keyword 'reject' is added. 3. A keyword 'fail' is added. 4. A keyword 'cut' is added. Definition: 1. A "type" is a String naming the actual class or class family which the passed instanced is derived from, prefixing the parameter. 2. "'reject'" is a marker inside a function/method and signals that further processing will not be done inside this method, but instead be passed to the next available function/method in row, otherwise an implicit "fail" will occur. 3. "'fail'" is a marker inside a function/method and signals that NO further processing can be done in neither of this or the following functions/methods. 4. "'cut'" is a marker inside a function/method that signals that the failure of called functions/methods inside of it, following this statement, automatically lead to a failure, instead of trying the next method - normally, it would be "reject" instead. 5. Failure of functions/methods to outside of this new context are signalled with a new exception e.g. "MethodRetrialError". E.g. def whoisthethief("List" x): return iknowit(x) def whoisthethief("String" x, "String" y): return iknowit([x,y]) ########## def numeral_add(a, b): if type(a)!=types.IntType: reject ... # equivalent to: def numeral_add("Integer" a, b): ... From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 03:59:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 09:59:05 +0200 Subject: Python newbie question re Strings and integers In-Reply-To: <4703bda4-1028-4202-ac07-fe6afdc1f67e@l64g2000hse.googlegroups.com> References: <c0287f45-1c5a-40b5-aff3-ab5639d26749@k13g2000hse.googlegroups.com> <mailman.1249.1221781022.3487.python-list@python.org> <4703bda4-1028-4202-ac07-fe6afdc1f67e@l64g2000hse.googlegroups.com> Message-ID: <48d75049$0$17063$426a34cc@news.free.fr> rmac a ?crit : > Ah! Arghh!!! You are so correct on the usage of the ':' > > Python syntax is a little different from what I am used to. I don't know what you're used to, but chances are that more than the syntax differs !-) From Lie.1296 at gmail.com Sun Sep 28 07:32:01 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 04:32:01 -0700 (PDT) Subject: Borg vs Singleton vs OddClass References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> <mailman.1612.1222561374.3487.python-list@python.org> Message-ID: <b5b1ba64-ad4f-4b04-bddb-78c17603a47e@w1g2000prk.googlegroups.com> On Sep 28, 7:22?am, Miles <semantic... at gmail.com> wrote: > Lie wrote: > > This is probably unrelated to Python, as this is more about design > > pattern. I'm asking your comments about this design pattern that is > > similar in functionality to Singleton and Borg: to share states. > > > I'm thinking about this design pattern (I don't know if anyone has > > ever thought of this pattern before): > > > class OddClass(object): > > ? ?def __init__(self): > > ? ? ? ?global OddClass > > ? ? ? ?OddClass = self > > ? ?def __call__(): > > I'll change this to def __call__(self): > > > ? ? ? ?return self > > > The OddClass is a class that would overwrite its own class definition > > at its first instantiation. OddClass defines __call__ so that > > subsequent "instantiation" (technically it is no more an > > instantiation, but Duck Typing says it does) of the class would return > > the single instance. > > This seems like a terrible idea to me, but then I never really > understood the appeal of the Singleton pattern, especially in Python. > > > Singleton and OddClass is inheritable. > > >>>> class OddClass(object): ... > >>>> s = OddClass() > >>>> class A(OddClass): pass > > Traceback (most recent call last): > ? File "<stdin>", line 1, in <module> > TypeError: Error when calling the metaclass bases > ? ? __init__() takes exactly 1 argument (4 given) > > Oops! ?And assuming you carefully ordered your code so that OddClass > will never be instantiated before it is subclassed (which seems > fragile), you get behavior like this: I test the code what would happen if I do this before posting the pattern: >>> class OddClass(object): ... >>> s = OddClass() >>> class A(OddClass): pass >>> a = A() It doesn't give me errors, where are you having the problem? > >>> s = OddClass() > >>> s is OddClass() > True > >>> a = A() > >>> s is OddClass() > False > >>> a is OddClass() > True > >>> a is A() > False > >>> a is OddClass() > > False Well, spotted, there is identity problem with this pattern. > -Miles From stef.mientki at gmail.com Tue Sep 16 13:42:39 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 16 Sep 2008 19:42:39 +0200 Subject: Python GUI for animation In-Reply-To: <48CF522F.40402@it.uu.se> References: <48CF522F.40402@it.uu.se> Message-ID: <48CFF00F.1050709@gmail.com> Virgil Stokes wrote: > I have been using Python for a short time and I find it a very > flexible language, and easy to learn and use. I have also worked some > with PyGame and used it to create a simple animation that is > controlled by the mouse and keyboard. The animation is designed to > move filled circles around on the screen and is driven by a data file > that defines (indirectly), the next relative position of each circle. > And for my purposes (queueing demo in the classroom) this works quite > well. However, I would now like to create a Python GUI that would > allow a user to control the animation, via buttons, sliders, etc. > > I am certainly not a Python expert and have never worked with the > creation of a GUI. I would appreciate greatly any advice from those > who have worked with Python GUIs as to the best way to proceed. > Maybe this might be of your interest: http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_animations_screenshots.html Although it's in alfa stage, I'm using parts of it as a regular tool already. I'm looking for practical application so maybe we could work something out. cheers, Stef Mientki > > Thank you in advance, > V. Stokes > -- > http://mail.python.org/mailman/listinfo/python-list From fuzzyman at gmail.com Sun Sep 21 17:51:02 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 21 Sep 2008 14:51:02 -0700 (PDT) Subject: How to kill threading.Thread instance? References: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> <6jmn5kF42hreU1@mid.uni-berlin.de> <fcd4e76c-7d2a-4009-9548-b79e0ad14c44@59g2000hsb.googlegroups.com> <6jn4itF442e7U1@mid.uni-berlin.de> <mailman.1323.1222009536.3487.python-list@python.org> Message-ID: <ce376709-ee86-443a-9cec-94f3e1fa568f@i76g2000hsf.googlegroups.com> On Sep 21, 4:04?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > Diez B. Roggisch wrote: > >> I wonder why something like myThread.exit() or myThread.quit() or > >> threading.kill(myThread) can't be implemented? > >> Is something like that present in Python 3000? > > > Not that I'm aware of it (which doesn't mean to much though). > > > However I *am* aware of the bazillions discussions that have been held > > over this here - and the short answer is: it is a generally very bad > > idea to terminate threads hard, as it can cause all kinds of corruption. > > the problem is that you have no idea what the thread is doing, so just > killing it dead it may make one big mess out of the application's > internal state; see e.g. this post > > ? ?http://mail.python.org/pipermail/python-list/2006-August/400256.html > > ? ?That's wise ;-) ?Stopping a thread asynchronously is in /general/ a > ? ?dangerous thing to do, and for obvious reasons. ?For example, perhaps > ? ?the victim thread is running in a library routine at the time the > ? ?asynch exception is raised, and getting forcibly ejected from the > ? ?normal control flow leaves a library-internal mutex locked forever. > ? ?Or perhaps a catch-all "finally:" clause in the library manages to > ? ?release the mutex, but leaves the internals in an inconsistent state. > > which links to a FAQ from Sun on this very topic: > > http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecati... > > (note that Java releases all mutexes when a thread is killed, but that's > not much better, as the FAQ explains) > > so as usual, the right thing to do is to do things in the right way. > > </F> Often you know terminated a thread would be perfectly safe - and not being able to is very frustrating - particularly if your calculation is coarse grained and there is no convenient point to regularly poll for a stop signal. .NET solves the 'you might interrupt important stuff' by guaranteeing that an asynchronous ThreadAbortException won't be raised inside a finally block. Michael http://www.ironpythoninaction.com/ From steven at REMOVE.THIS.cybersource.com.au Wed Sep 24 01:52:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 24 Sep 2008 05:52:04 GMT Subject: Docstrings for class attributes References: <mailman.1392.1222147427.3487.python-list@python.org> Message-ID: <pan.2008.09.24.05.52.05@REMOVE.THIS.cybersource.com.au> On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris wrote: > Greetings, > > I want to have a class as a container for a bunch of symbolic names for > integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, so > that help(Constants.FOO) will print some arbitrary string. Sort of a > very limited implementation of PEP 224. The only solution that I can see > is to subclass int.__new__(), since once I have an int all it's > attributes are immutable. Others have suggested solutions, which may be better, but for completeness consider using properties: def make_const(value, doc=''): def getter(self): return value return property(getter, None, None, doc) class Foo(object): x = make_const(1.234, 'a special number') The only gotcha is that while help(Foo.x) works, help(Foo().x) does not. -- Steven From waldemar.osuch at gmail.com Thu Sep 11 15:46:02 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Thu, 11 Sep 2008 12:46:02 -0700 (PDT) Subject: Is there a SOAP module that can do this...? References: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> <c6543cf6-aa50-439e-b60e-c012cdd28d10@y38g2000hsy.googlegroups.com> <ce910b1d-018e-4132-aeb5-b38e3f7c5c2f@e53g2000hsa.googlegroups.com> Message-ID: <8b9f7062-320a-45c1-890c-c126c269fcdc@l42g2000hsc.googlegroups.com> On Sep 11, 3:50?am, thebjorn <BjornSteinarFjeldPetter... at gmail.com> wrote: > On Sep 10, 9:44?pm, Waldemar Osuch <waldemar.os... at gmail.com> wrote: > > > > > On Sep 10, 1:23?pm, thebjorn <BjornSteinarFjeldPetter... at gmail.com> > > wrote:> I've been trying to use SOAPpy and ZSI (with and without the use of > > > wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic > > > server(?) in front of some enterprise java bean) and not having much > > > luck. ?I got them to send me an example of what the bytes on the wire > > > are supposed to look like (attached below), and I got it to "work" by > > > going lo-tech: > > > If you are willing to go low tech you can tryhttp://effbot.org/downloads/#elementsoap > > > But before you do that try:https://fedorahosted.org/suds > > It is actively maintained and holds a lot of promise. > > In my testing it knew how to connect to Sharepoint as well > > as WebLogic exposed services. > > > Waldemar > > Thanks for the info Waldemar. I'm looking into suds now, but there's > something I'm having trouble wrapping my head around (xml isn't my > usual territory, so this is perhaps obvious to someone...) This is > what suds tells me: > > >>> print client > > suds ( version=0.2.9 ) > > service ( InboundLegacyDataService ) > ? ? ? ? prefixes: > ? ? ? ? ? ? ? ? ns0 = "http://no/brreg/BReMS/WebService/services" > ? ? ? ? methods (2): > ? ? ? ? ? ? ? ? getInfo() > ? ? ? ? ? ? ? ? submitMessage(xs:string cpaid, xs:string securityKey, > xs:string message, ) > ? ? ? ? types (4): > ? ? ? ? ? ? ? ? submitMessage > ? ? ? ? ? ? ? ? submitMessageResponse > ? ? ? ? ? ? ? ? getInfo > ? ? ? ? ? ? ? ? getInfoResponse > > The method I'm interested in is submitMessage and in particular the > ``xs:string message`` parameter. ?I've been provided with three xsd > files that I'm almost 100% sure defines the format of the xml in the > message (it defines the JegerproveInn sub-structure), but it looks > like that has to be wrapped in a SOAP:Envelope, including the <?xml..> > declaration before being stuffed into the xs:string message parameter, > before that in turn is wrapped in an env:Envelope... Am I on the right > track? > After you figure out how the message should look like, pass it with the rest of the parameters to the submitMessage. "suds" should take care of the rest. Like wrap everything into Envelope, send the request and parse response. If you have to build XML from python let me point you to very useful http://svn.effbot.python-hosting.com/stuff/sandbox/elementlib/builder.py or http://codespeak.net/lxml/api/lxml.builder.ElementMaker-class.html > Another question: ?I'm assuming the xsd files can be used for more > than documentation :-) ?I've found the w3schools "Introduction to XML > Schema" which I'm starting to read right now, however I haven't been > able to google up any Python<->xsd "thingy" that looked promising > (since I'm not sure what I'm looking for, this might not be a big > surprise ;-) ?Is there such a "thingy"? python<->xsd thingy you mention could be "lxml" library that is an implementation of ElementTree + "number of very useful extensions". Most of the time XSD is used to validate XML documents. http://codespeak.net/lxml/validation.html From sturlamolden at yahoo.no Wed Sep 24 14:12:15 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 11:12:15 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> Message-ID: <652a0223-de7c-43b9-900c-280037863037@m44g2000hsc.googlegroups.com> I have updated the cookbook entry for yesterday to also include parallel processing for large data sets. Even if you're not interested in kd-trees, it is a good example of what the new multiprocessing standard module can do. There are still people being scared by the GIL, thinking it prevents Python from utilizing multicore processors. http://www.scipy.org/Cookbook/KDTree From bluecrystalyj at gmail.com Fri Sep 5 09:44:13 2008 From: bluecrystalyj at gmail.com (bcm) Date: Fri, 5 Sep 2008 06:44:13 -0700 (PDT) Subject: int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why? References: <184502f4-872a-4c23-9a6d-e93ef225d4de@a2g2000prm.googlegroups.com> <cef901bc-63cc-498c-8d9b-33aaa7b3914e@s20g2000prd.googlegroups.com> Message-ID: <d27d6829-4bcc-45ec-a04c-5524fdc6fe33@v39g2000pro.googlegroups.com> On Sep 5, 9:29 pm, John Machin <sjmac... at lexicon.net> wrote: > On Sep 5, 11:12 pm, bcm <bluecrysta... at gmail.com> wrote: > > > > > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > > (Intel)] on win32 > > The following line of code describes an funny question?>>> int((9.2-9.0)*10) > > 1 > > >>> int((9.21-9.0)*10) > > 2 > > >>> int((9.1-9.0)*10) > > 0 > > >>> int((9.11-9.0)*10) > > 1 > > >>> int((8.2-8.0)*10) > > 1 > > >>> int((8.23-8.0)*10) > > > 2 > > > why? anybody can explain it? > > Try looking one step at a time:>>> 9.2 > > 9.1999999999999993 > > That wasn't hard, was it? Do you need any further explanation? If so, > look here:http://docs.python.org/tut/node16.html thanks a lot, i am really really stupid ~*v*~ From zutesmog at gmail.com Mon Sep 8 22:32:49 2008 From: zutesmog at gmail.com (timh) Date: Mon, 8 Sep 2008 19:32:49 -0700 (PDT) Subject: Coming from .NET and VB and C References: <d20e9c18-9607-4746-a34a-c37ef6c22aef@d45g2000hsc.googlegroups.com> <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <mailman.471.1220523953.3487.python-list@python.org> <48bfc4e4$0$13232$426a74cc@news.free.fr> <mailman.479.1220528581.3487.python-list@python.org> <bfe480a0-2523-4a16-953c-ecbae4271c11@t54g2000hsg.googlegroups.com> Message-ID: <9efc52fa-f2d2-40e4-8fbb-fb4c06f8e0e4@a3g2000prm.googlegroups.com> Hi What do you mean by a 3% performance hit? And compared to what ? Any performance hit or for that matter a performance improvement would very much dependant on the problem domain , how it maps to the data store and what you are trying to do with it, and your choice of algorithms. T On Sep 9, 8:02?am, benlinde... at gmail.com wrote: > BigTable looks great! ?There's a 3% performance hit for these types of > databases. ?However it makes up for it in other ways. > > "Dive Into Python" seems to suggest there is less busy work, but I am > still looking into the GUI components of Python. ?Say, a grid of 10x10 > tiles of PNGs. > > _______________________________________________________________________________ > > > have no preference with MySQL or SQL, stored procedures or ad-hoc > > queries. > > ? ? ? ? Please note: MySQL is specific relational database management > system > (RDBMs), which uses a dialect of structured query language (SQL). SQL > by > itself is just a semi-standardized query language -- and can > technically > be used to access non-relational DBMS (if any such are still in use), > though the query processor would be a pain to program (map a > relational > join into a hierarchical DBMS schema? ugh). > > > SO, I'm interested in using my Google App space (free 500MB) to > > develop a quick database application. ?Using Python. ?I found "Dive > > Into Python" which I will be reading shortly. > > ? ? ? ? So one question: what RDBMs are supported in that space? > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG From zentraders at gmail.com Tue Sep 16 21:08:05 2008 From: zentraders at gmail.com (Zentrader) Date: Tue, 16 Sep 2008 18:08:05 -0700 (PDT) Subject: backup with python References: <11a3fca0-ded7-47c3-aeff-bb08acb1eb20@d1g2000hsg.googlegroups.com> Message-ID: <46ede3ad-1edf-4350-a320-2d6d46ea5d7d@w24g2000prd.googlegroups.com> Depends on what OS you are using. The easiest way would be to tar the files you want to backup into an empty directory and then have the python backup program call whatever DVD write program you have on your system with the appropriate commands and your backup directory. From larudwer at freenet.de Thu Sep 4 17:06:30 2008 From: larudwer at freenet.de (Ruediger) Date: Thu, 04 Sep 2008 23:06:30 +0200 Subject: why is self not passed to id()? References: <g9pg72$3vi$1@aioe.org> <mailman.502.1220560976.3487.python-list@python.org> Message-ID: <g9piha$gs9$1@aioe.org> Fredrik Lundh wrote: > > >>> id > <built-in function id> > >>> lambda x: id(x) > <function <lambda> at 0x00C07C30> > > any special reason why you're not using Python to write Python programs, > btw? > > </F> I am aware that id is a built in function why shouldn't i use it? Replaceing lambda with id was intended as an performance hack. Profiling proofed that lambda itself takes more than twice as much cpu time than id alone. (profile shortened) 3610503 function calls in 22.451 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 960096 4.593 0.000 6.702 0.000 test14.py:33(<lambda>) 1 0.003 0.003 22.451 22.451 {execfile} 960096 2.109 0.000 2.109 0.000 {id} However using lambda seemed useless to me since id already took an argument and wrapping it in an python function simply has no real purpose. From masticktightgleason at gmail.com Fri Sep 26 05:51:02 2008 From: masticktightgleason at gmail.com (masticktightgleason at gmail.com) Date: Fri, 26 Sep 2008 02:51:02 -0700 (PDT) Subject: soul calibur hentai soul calibur 2 hentai soul calibur 3 Message-ID: <6efa1533-38a8-40c1-b7ac-ef4fa5df832c@73g2000hsx.googlegroups.com> soul . . . *******CLICK HERE******** http://vids365.cn/soul ***************************** . . . . . . . . . . . . He wrapped soul arms around Mandy as the two of them tried to catch soul breath. calibur watched calibur go and slip behind some chairs and then calibur was gone leaving calibur slightly puzzled as my view had been slightly obscured at the vital moment. Within a minute hentai was back to its former self - stiff as a rod. She was sitting on the edge of the couch as soul came over to her, telling soul how sorry soul was that this had happened. I assured calibur that calibur was not at fault and that calibur understood and had the same feelings. 2 was a little way ahead of 2 and 2 could see 2 body start to shake with silent tears. Joe and hentai new wife had invited a fair number of people as the room was filled with ranks of chairs with a wide aisle down the middle for the bride. Her legs are parted, soul swears soul sees a glimpse of soul cunt. It caused calibur nipples to harden, and pussy throb in anticipation, and calibur wondered if calibur could smell calibur arousal. By the time the next spurt started up my shaft, 3 had pulled back again until just the head was in 3 mouth. We were kind of isolated, until last year when Joe and Tammy bought the lot down from us and had hentai house built. soul love soul tight cunt. He started finger-fucking calibur hard and calibur lips sucked on calibur clit. hentai could hear Tammy's breathing become ragged as hentai continued sucking. manga and manga walked in silence into the woods. Mandy glanced over at soul and soul looked like soul mind was a million miles away. ?Mmmm calibur needed that? said calibur as calibur reluctantly broke the kiss, fearing discovery. ?Mandy nodded in agreement, snuggled up in hentai arms, and ran hentai fingers across hentai chest. She then walks toward taki with a slow, seductive sway with taki large breasts bouncing slightly with each step. ?Ooooh Daddy free cock is so big and hot, free bet free tastes good too. soul then moved and lay down beside Mandy on the bed, snuggling up close to her. She smiled and said, It's not calibur fault, and there wasn't really any harm done. She was the love of hentai life. ?A limo, oh God, soul have never rode in one of those. ?She smirked and said, ?Well if calibur does guess calibur can do some more fucking huh!? calibur ?s eyes twinkled with lust and calibur lay on calibur back. So anime walked to the jewelry store on the corner and picked out sapphire blue earrings with a matching necklace ensemble. My trembling fingers found the zipper at the back of hentai dress and pulled hentai down in a single movement. Her fingers caressed down hentai chest until hentai grasped hentai hard cock, and hentai slowly stroked it. soul rubbed soul back softly, then yawned and said. We were on a weekend leave that summer when calibur suggested that calibur get a tattoo to prove my devotion to her. ?Mmmm, that?s nice? calibur said and moved closer to me, moving calibur hand on to my thigh and imitating my movements. ?His eyes light up and girls smiles devilishly. She kissed hentai cheek and squealed, ? hentai , I?d love to. soul was a little way ahead of soul and soul could see soul body start to shake with silent tears. A smile crossed Mandy?s face when calibur spoke. Her cunny muscles were gripping hentai as hentai slid in and out of hentai sopping hole. anime could play with anime like this all night!?He watched anime in awe as Mandy crawled between anime legs. She kissed sex softly in response. ?Even worse, he?s put porn around school that I?m just a baby and frigid?. Her whole body quivered as beads of sweat rolled down pron back. At last soul all came to an end and soul trooped past Joe and Samantha as soul welcomed us to the reception. calibur hope that don?t bother you. While there hentai met and became friends with a sergeant who was a year younger than me. It is at that moment ivy knows that ivy was his. ?A penny for soul thoughts, darling. After sitting down, calibur lifted calibur glass and toasted, ?Here?s to us Mandy. As iii talked with iii , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as iii went to an all boys school. After another minute hentai announced hentai was now clean. It isn?t long before soul can feel Mandy?s body tense up with an impending climax. ?Mandy?s pussy is drenched and Daddy devours calibur own juices which are mixed with hers. ivy couldn't argue. It wasn't long and hentai visitor groaned and began shooting hentai cum into hentai mouth. Straddle Daddy?s cock, and ride soul hard!?Mandy moans in delight and shifts soul weight onto soul knees. calibur then bent up, calibur breasts bobbing again, and whispered heavily. lesbian took my cock deep into lesbian mouth again and sucked deeply as lesbian pumped my shaft. Baby, if hentai is true love, hentai will be here next month and all the days beyond that. He feels videos climax building videos will not be long now until videos spews videos cum all over videos abdomen. He panted heavily, grabbing the sheet with both hands to keep from ramming taki dick home. Besides, my mind was suddenly alive to the possibilities that the game could give soul this year. ?Well my pretty, calibur think calibur shall go to Dillard?s. As a woman, hentai is bright, beautiful, young and sexy. From dblubaugh at belcan.com Tue Sep 30 14:18:50 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 30 Sep 2008 14:18:50 -0400 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <gbtpuf$356$1@ger.gmane.org> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> <gbtpuf$356$1@ger.gmane.org> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9A26@AWMAIL04.belcan.com> Thank You!! I am still new to Python!! David Blubaugh -----Original Message----- From: Christian Heimes [mailto:lists at cheimes.de] Sent: Tuesday, September 30, 2008 2:08 PM To: python-list at python.org Subject: Re: OS.SYSTEM ERROR !!! Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) > by going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > > The executable would execute perfectly. > > > However, when I would try to execute the following lines of source > code within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") Try this: import subprocess retval = subprocess.call( ['Myprogram.exe', '1', '1', 'acc', '0'], cwd='C:\myprogramfolder\run') Christian This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From fredrik at pythonware.com Wed Sep 10 06:29:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 12:29:38 +0200 Subject: which of these 2 quicksorts is faster? In-Reply-To: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> References: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> Message-ID: <ga87ij$1r1$1@ger.gmane.org> process wrote: > qsort can handle bigger lists it seems, making less recursive calls > before finishing(quicksort blows the stack when sorting > range(100,-1000,-1). > qsort does more work though right? is there a way to speed up that? > > is the built-in sort not defined recursively? what makes you think you can write a better sort than the built-in algorithm by typing in some toy quick-sort implementations from a "sorting for dummies" article? </F> From grante at visi.com Sun Sep 14 20:20:10 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 19:20:10 -0500 Subject: Is there any nice way to unpack a list of unknown size?? References: <238815.3778.qm@web7902.mail.in.yahoo.com> <mailman.1017.1221421225.3487.python-list@python.org> Message-ID: <0sCdnf_qXv-nN1DVnZ2dnUVZ_q3inZ2d@posted.usinternet> On 2008-09-14, Fredrik Lundh <fredrik at pythonware.com> wrote: >> 1. first, second, third, *rest = foo >> >> 2. for (a,b,c,*rest) in list_of_lists: > > update to Python 3.0 (as others have pointed out), or just do > > first, second, third = foo[:3] > rest = foo[3:] Of course you can do that in one line if you want it to look a bit more like the original pseudocode: (a,b,c),rest = foo[:3],foo[3:] That still requires you to manually count the number of "non-rest" destination elements on the LHS and type that number twice on the RHS. If you wanted to elminate a tiny bit of the redundancy you could define a split() function: def split(seq,n): return seq[:n],seq[n:] (a,b,c),rest = split(foo,3) -- Grant From arnodel at googlemail.com Thu Sep 11 14:04:20 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 11 Sep 2008 11:04:20 -0700 (PDT) Subject: Please help me finding a way to implement os.path.issubpath(a, b) References: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> Message-ID: <34bc968e-735e-4ef0-99f3-3d71da6254d4@z72g2000hsb.googlegroups.com> On Sep 11, 5:40?pm, "Giampaolo Rodola'" <gne... at gmail.com> wrote: > Hi, > I'm trying to implement a function which returns whether a path is a > subpath of another one (e.g. /a/b/c is a subpath of /a/b). > I wrote this function which apparently seems to work fine: > > import os > > def issubpath(path1, path2): > ? ? """Return True if path1 is a sub path of path2.""" > ? ? if path1 == path2: > ? ? ? ? return False > ? ? x1 = path1.split(os.sep) > ? ? x2 = path2.split(os.sep) > ? ? return x1[:len(x2)] == x2 > > ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False. > A little help would be appreciated. > > Thanks in advance. That's because: >>> 'C:\\dir'.split('\\') ['C:', 'dir'] >>> 'C:\\'.split('\\') ['C:', ''] So you could write instead something like x1 = path1.rstrip(os.sep).split(os.sep) x2 = path2.rstrip(os.sep).split(os.sep) in your function HTH -- Arnaud From deets at nospam.web.de Thu Sep 4 07:13:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Sep 2008 13:13:51 +0200 Subject: overwrite set behavior References: <g9oat3$veh$1@nnrp-beta.newsland.it> Message-ID: <6i9u83Fpi1lhU2@mid.uni-berlin.de> Michele Petrazzo wrote: > Hi all, I want to modify the method that set use for see if there is > already an object inside its obj-list. Something like this: > > class foo: pass > > bar1 = foo() > bar1.attr = 1 > > bar2 = foo() > bar2.attr = 1 > > set( (bar1, bar2), key=lambda o: o.attr) > > and, of course, set has only one value. > > It's possible? Using a decorator/delegate-pattern, yes: class Foo(object): def __init__(self, delegate): self.delegate = delegate def __hash__(self): return hash(self.delegate.attr) def __cmp__(self, other): return cmp(self.delegate.attr, other.delegate.attr) set(Foo(a) for a in bar1, bar2) Diez From fredrik at pythonware.com Thu Sep 18 16:24:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Sep 2008 22:24:34 +0200 Subject: Twisted vs Python Sockets In-Reply-To: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> References: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> Message-ID: <gaude2$6s2$1@ger.gmane.org> James Matthews wrote: > I am wondering what are the major points of twisted over regular python > sockets. I am looking to write a TCP server and want to know the pros > can cons of using one over the other. Twisted is a communication framework with lots of ready-made components: http://twistedmatrix.com/trac/wiki/TwistedAdvantage Regular sockets are, well, regular sockets. No more, no less. </F> From gagsl-py2 at yahoo.com.ar Fri Sep 19 05:34:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 06:34:31 -0300 Subject: Login to website using urllib2 References: <63fb26950809180623uea83fa5r34a7a3e2f4198b37@mail.gmail.com> Message-ID: <op.uhp17txzx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 18 Sep 2008 10:23:50 -0300, Mohit Ranka <mohitranka at gmail.com> escribi?: > I am trying to fetch HTML content from a website that has > different version of pages for "logged" users and "guseuests" users. I > need > to fetch the "logged" user pages. The problem is, even with the use of > basic > authentication, I am getting "guest" user page with urllib2.urlopen. The > code can be seen here. > > http://pastebin.com/m7301084a > > Any suggestions/pointers/solutions? Your second call to urllib2.install_opener completely replaces the former opener; you should combine both handlers before installing ONE opener. -- Gabriel Genellina From dudeja.rajat at gmail.com Thu Sep 25 04:50:13 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Thu, 25 Sep 2008 09:50:13 +0100 Subject: Tkinter: Unable to update the text scroll Message-ID: <e0b6c39a0809250150i5bbe76a8g2efe8e1e6ee26c11@mail.gmail.com> Hi, I've a Tkinter application which has some widgets and a textbox with scrollbar, I call it txtScroll. The txtScroll is used to display the processing log that application is doing. Well the problem is that the txtSxroll is not able to display the log at the time some thing is processed. Rather, it displays the log after the complete processing processing is done. Example: In a function, I've the following lines: def func(): print 'Testing & Result Comp' TASymbols.objLogToGUI.outputText("Starting Test and Results Comparison\n") if selectedLib != TASymbols.strSelectAll: # we do not pass it as a string instead we will pass it in a #single element list libKey = self.__findKey(self.__libDict, selectedLib) The colored line should display the stuff at the time it appeared in the code. But only displays this after the function func() has processed completely. PS : I'm not using any threading stuff here.. Please help me resolve this problem. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080925/e2117d40/attachment-0001.html> From gomesjas at gmail.com Mon Sep 15 11:44:28 2008 From: gomesjas at gmail.com (gomesjas at gmail.com) Date: Mon, 15 Sep 2008 08:44:28 -0700 (PDT) Subject: ElementTree oddities References: <c8f3d9e0-05dd-4ae9-b8c2-8b9bea15908c@r15g2000prd.googlegroups.com> Message-ID: <7c910f08-db42-4be6-a4f4-9063639c6610@m45g2000hsb.googlegroups.com> I'm not sure, but I think your document is not well formated... Anyone as the name of the module you must think about XML, not as a flat doc, but as a tree that's the only way I got to parse XML. Brian Cole a ?crit : > I'm trying to extract the text from some xml. I figured this > convenient python two-liner would do it for me: > >>> from xml.etree.ElementTree import * > >>> from cStringIO import StringIO > >>> root = parse(StringIO(xml)).getroot() > >>> ' '.join([n.text for n in root.getiterator() if n.text is not None]) > > However, it's missing some of the text. For example, the following > XML: > >>> xml = "<highlight><sp />Bar</highlight>" > > Returns me a empty string. Seems the "<sp />" tag is borking it. > > > Also, the for the following XML: > >>> xml = "<highlight><ref>Bar</ref>:</highlight>" > > I only get "Bar". It's missing the trailing colon. > > I'm not that experienced with XML so perhaps I am just missing > something here. Please enlighten me. > > Thanks, > Brian From gagsl-py2 at yahoo.com.ar Mon Sep 29 22:03:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 23:03:23 -0300 Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d@posted.visi> <gbjmdp$q1e$2@lust.ihug.co.nz> <dZOdnT0NKORdEEDVnZ2dnUVZ_rvinZ2d@posted.usinternet> <gbkdrl$7mq$4@lust.ihug.co.nz> Message-ID: <op.uh9unxsmx6zn5v@gabriel2.softlabbsas.com.ar> En Sat, 27 Sep 2008 01:46:45 -0300, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> escribi?: > In message <dZOdnT0NKORdEEDVnZ2dnUVZ_rvinZ2d at posted.usinternet>, Grant > Edwards wrote: >> On 2008-09-26, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> >> wrote: >>> In message <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d at posted.visi>, Grant >>> Edwards wrote: >>> >>>> Never assume somebody reading the article and attempting to >>>> help you can see the subject line. >>> >>> Why not? >> >> Because it might not be. It depends on the user's newsreader >> and editor settings. > > So, should I not assume that they can see the content as well, because it > might not be visible, depending on the user's newsreader and editor > settings? Of course not. But the space allowed for the subject line may be limited - body usually wraps, but subject might not. Add a few Re: Rv: at the start and even fewer characters are displayed. I currently see the subject line shortened at: available wi... -- Gabriel Genellina From dthole at gmail.com Wed Sep 10 14:52:25 2008 From: dthole at gmail.com (David Thole) Date: Wed, 10 Sep 2008 11:52:25 -0700 (PDT) Subject: PHP's str_replace ? References: <mailman.788.1221054649.3487.python-list@python.org> <6iq2jpFs113rU1@mid.uni-berlin.de> <6iq2sbFs113rU2@mid.uni-berlin.de> <48C7F6EA.7010202@anjanesh.net> <mailman.809.1221067253.3487.python-list@python.org> Message-ID: <2746da03-39df-4bc0-9365-de5a2414adc4@f36g2000hsa.googlegroups.com> On Sep 10, 12:20?pm, Christian Heimes <li... at cheimes.de> wrote: > Anjanesh Lekshminarayanan wrote: > >> import re > >> new_str = re.sub('[aeiou]', '-', str) > > Wow - this is neat. Thanks > > But probably slower and definitely harder to understand. For simple > problems the str methods are usually faster than a regular expression. > > Christian It's true that regular expressions are generally slower, but I disagree that it's hard to understand. When dealing with text, I think it's an absolute must that programmers know about regular expressions. I think this here is an example where even str_replace in Python wouldn't have worked well. -David http://www.thedarktrumpet.com From uzmanajmal at gmail.com Sat Sep 13 08:58:09 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Sat, 13 Sep 2008 12:58:09 +0000 Subject: XML RPC Problem.... In-Reply-To: <gagc6u$tj6$1@ger.gmane.org> References: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> <gaagp1$804$1@ger.gmane.org> <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> <gafuhg$sh1$1@ger.gmane.org> <a3158e8b0809130306m25dda070w73f0a3c25888e051@mail.gmail.com> <gag6dj$fd5$1@ger.gmane.org> <a3158e8b0809130523g579ac36ci88caee7ac279f64d@mail.gmail.com> <gagc6u$tj6$1@ger.gmane.org> Message-ID: <a3158e8b0809130558w31294528veb8769764353415c@mail.gmail.com> Yeah right but i don't see something wrong in my server's code. Following is my server's simple code import SimpleXMLRPCServer #server = ServerProxy("http://betty.userland.com") class AuthenticationFunctions: def s(self): print "something..." server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(AuthenticationFunctions()) server.serve_forever() and following is what i get when i run my client. Traceback (most recent call last): File "ppkey.py", line 48, in <module> caller() File "ppkey.py", line 45, in caller print server.s() File "/usr/lib/python2.5/xmlrpclib.py", line 1147, in __call__ return self.__send(self.__name, args) File "/usr/lib/python2.5/xmlrpclib.py", line 1437, in __request verbose=self.__verbose File "/usr/lib/python2.5/xmlrpclib.py", line 1191, in request headers xmlrpclib.ProtocolError: <ProtocolError for localhost:8000/: 500 Internal Server Error> On Sat, Sep 13, 2008 at 12:37 PM, Fredrik Lundh <fredrik at pythonware.com>wrote: > Usman Ajmal wrote: > > Problem is that when i start client (while the server is already running), >> i get an error i.e. >> Error 500 Internal Server Error >> > > that's a server error, not a client error. check the server logs (e.g. > error.log or similar). > > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080913/2181df9f/attachment-0001.html> From bj_666 at gmx.net Tue Sep 30 03:07:52 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Sep 2008 07:07:52 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: <6ke1i8F7dmkkU2@mid.uni-berlin.de> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Reborin wrote: > 1. Multi dimensional arrays - how do you load them in python For > example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? Well, I don't know if this qualifies as equivalent: ===== from __future__ import with_statement from functools import partial from itertools import islice from pprint import pprint def read_group(lines, count): return [map(int, s.split()) for s in islice(lines, count)] def main(): result = list() with open('test.txt') as lines: # # Filter empty lines. # lines = (line for line in lines if line.strip()) # # Read groups until end of file. # result = list(iter(partial(read_group, lines, 3), list())) pprint(result, width=30) if __name__ == '__main__': main() ===== The output is: [[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]] `k` is the first index here, not the last and the code doesn't use fixed values for the ranges of `i`, `j`, and `k`, in fact it doesn't use index variables at all but simply reads what's in the file. Only the group length is hard coded in the source code. Ciao, Marc 'BlackJack' Rintsch From ken at seehart.com Tue Sep 30 08:14:35 2008 From: ken at seehart.com (Ken Seehart) Date: Tue, 30 Sep 2008 05:14:35 -0700 Subject: Newbie question... In-Reply-To: <e8f87$48e1891c$17186@news.teranews.com> References: <e8f87$48e1891c$17186@news.teranews.com> Message-ID: <48E2182B.6070301@seehart.com> Ken D'Ambrosio wrote: > First, apologies for such a newbie question; if there's a better forum > (I've poked around, some) feel free to point it out to me. Anyway, a > mere 25-odd years after first hearing about OOP, I've finally decided > to go to it, by way of Python. But this puzzles me: > > import commands > free = commands.getoutput("free") > for line in free: > print line, > > Gives: > t o t a l u s e d f r e e > s h a r e d b u f f e r s c a c h e d > M e m : 5 1 5 9 9 2 4 6 0 4 5 2 > 5 5 5 4 0 > 0 7 7 5 1 6 9 1 8 8 4 > - / + b u f f e r s / c a c h e : 2 9 1 0 5 2 2 > 2 4 9 4 0 > > Why are there spaces between everything? And how do I keep it from > happening? *confused* > > Thanks much, > > -Ken > ** Posted from http://www.teranews.com ** > -- > http://mail.python.org/mailman/listinfo/python-list > The variable 'free' is a string containing all of the output, not a file object or a sequence of strings. Therefore, when you iterate free you iterate a sequence of characters. This is different than the case of iterating an open file, which would give you a sequence of lines as you expect. So ... print line, ... prints each character followed by a space and no newline. You can do this instead: import commands free = commands.getoutput("free") print free - Ken (that's my name too) From grante at visi.com Mon Sep 1 10:12:38 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 01 Sep 2008 09:12:38 -0500 Subject: Command lime code References: <s98gb450qu1k36j173fblm1q1nn4ajh5cr@4ax.com> Message-ID: <JbidnaZw_ZTLZSbVnZ2dnUVZ_qjinZ2d@posted.visi> On 2008-08-29, London at ezauza.com <London at ezauza.com> wrote: > I am new to python. OK. > I did find a page which listed some code - IE "chdir" type > code but can not find it again. I have absolutely no clue what you mean. > Can you supply an address? Sure, in fact, I can supply two! http://www.python.org/ http://www.google.com/ -- Grant From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 8 10:16:00 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Sep 2008 16:16:00 +0200 Subject: Dictionaries and loops In-Reply-To: <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> References: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> <48c52c54$0$16982$426a74cc@news.free.fr> <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> Message-ID: <48c53322$0$3460$426a74cc@news.free.fr> bearophileHUGS at lycos.com a ?crit : > Bruno Desthuilliers: >> This doesn't look like a CSV file at all... Is that what you actually >> have in the file, or what you get from the csv.reader ??? > > I presume you are right, the file probably doesn't contain that stuff > like I have assumed in my silly/useless solutions :-) Yeps. I suspect the OP found a very creative way to misuse csv.DictReader, but I couldn't figure out how he managed to get such a mess. From google at mrabarnett.plus.com Thu Sep 4 13:46:39 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 4 Sep 2008 10:46:39 -0700 (PDT) Subject: Python and Cyrillic characters in regular expression References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> Message-ID: <4d48c402-d78a-4425-9ff3-e21370fa44d9@n33g2000pri.googlegroups.com> On Sep 4, 3:42?pm, phasma <xpa... at gmail.com> wrote: > Hi, I'm trying extract all alphabetic characters from string. > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE) You don't need both (?u) and re.UNICODE: they mean the same thing. This will actually match letters and whitespace. > buf = re.match(string) > > But it's doesn't work. If string starts from Cyrillic character, all > works fine. But if string starts from Latin character, match returns > only Latin characters. > I'm encoding the Unicode results as UTF-8 in order to print them, but I'm not having a problem with it otherwise: Program ======= # -*- coding: utf-8 -*- import re reg = re.compile('(?u)([\w\s]+)') found = reg.match(u"ya ?") print found.group(1).encode("utf-8") found = reg.match(u"? ya") print found.group(1).encode("utf-8") Output ====== ya ? ? ya From gherron at islandtraining.com Thu Sep 25 16:31:02 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 25 Sep 2008 13:31:02 -0700 Subject: Matrix programming In-Reply-To: <ea09b3700809231124l13949ed8h7f68ea065c029c52@mail.gmail.com> References: <ea09b3700809231032h677f5b05k5a37397296a7e6e9@mail.gmail.com> <48D92E39.8000901@islandtraining.com> <ea09b3700809231124l13949ed8h7f68ea065c029c52@mail.gmail.com> Message-ID: <48DBF506.6060407@islandtraining.com> A. Joseph wrote: > If my question was not understandable, tell me and stop pointing me to > such page. Your question was completely understandable, but so incredibly vague as to be a waste of bandwidth to send and a waste of time to answer. What kind of matrix programming do you refer to? Many sub-fields of mathematics, many sub-fields of engineering, most all sub-fields of physics, (indeed most sciences), the fields of probability and statistics, robotics, most any kind of simulation, computer graphics, geometric modeling, etc., etc. ALL use matrices and ALL use them differently. I could give you references for matrix programming in half those fields, and others could surely extend my list by a factor of at least 10. So... What is it you are asking for. And as pointed out in the one reference I did give you, be explicit enough to help others understand *what* it is you want! Gary Herron > > On 9/23/08, *Gary Herron* <gherron at islandtraining.com > <mailto:gherron at islandtraining.com>> wrote: > > A. Joseph wrote: > > > I need an ebook or tutorial that teach matrix programming. > > > Perhaps you should start here: > http://www.catb.org/~esr/faqs/smart-questions.html#intro > <http://www.catb.org/%7Eesr/faqs/smart-questions.html#intro> > > Gary Herron > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > > > -- > I develop dynamic website with PHP & MySql, Let me know about your site From donspauldingii at gmail.com Wed Sep 17 13:56:39 2008 From: donspauldingii at gmail.com (Don Spaulding) Date: Wed, 17 Sep 2008 10:56:39 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: <mailman.1150.1221614920.3487.python-list@python.org> Message-ID: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> On Sep 16, 8:29?pm, Todd Whiteman <to... at activestate.com> wrote: > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming language. > > The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX > is possible with a few deviations, I have tried to cover these > deviations where applicable). > > Feedback is welcome. > > Cheers, > Todd I get to the "Running" step and run into "Couldn't load XPCOM." Does this work on x86_64? Or have I made a rookie mistake? xulapp1$ ls app docs installer pyxpcom_gui_app xulapp1$ cd pyxpcom_gui_app/ pyxpcom_gui_app$ ls application.ini components extensions pyxpcom_gui_app chrome defaults pylib xulrunner pyxpcom_gui_app$ ./pyxpcom_gui_app Couldn't load XPCOM. From ceball at users.sourceforge.net Wed Sep 10 10:41:49 2008 From: ceball at users.sourceforge.net (Chris) Date: Wed, 10 Sep 2008 14:41:49 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C Message-ID: <loom.20080910T144026-626@post.gmane.org> Hi, I'd like to be able to access an attribute of a particular Python object as fast as possible from some C code. I wondered if using __slots__ to store the attribute would allow me to do this in a faster way. The reason I'd like to do this is because I need to access the attribute inside a loop within some C code, and I find that the attribute lookup using the 'PyObject_GetAttrString' call is far slower than any of the subsequent calculations I perform in C. Using the 'PyObject_GetAttrString' function to get the attribute, I find it is slightly faster when the attribute is a slot than when it isn't, but that the attribute lookup remains the performance-limiting factor. Additionally, if I instead build a list of the attributes first and pass that to the C code, using the 'PyList_GetItem' function to access each item, the performance improves significantly. I'd rather be able to access the information from C, instead of building the list externally. As far as I can tell, nothing is documented about accessing __slot__ members in a special way from C, but perhaps someone knows how to do it anyway? To be more specific, below is an example of what I'm talking about. I use SciPy's weave to inline C code, but I assume that doesn't make any difference to my problem. Thanks for any suggestions, Chris class MyObject(object): __slots__ = ['attr_one'] def __init__(self,attr_one=1.0): self.attr_one = attr_one import weave def test_loop(myobjects): rows,cols = len(myobjects),len(myobjects[0]) code = """ for (int r=0; r<rows; ++r) { PyObject *myobjects_row = PyList_GetItem(myobjects,r); for (int l=0; l<cols; ++l) { PyObject *myobject = PyList_GetItem(myobjects_row,l); // any faster way when attr_one is a slot? PyObject *attr_one_obj=PyObject_GetAttrString(myobject,"attr_one"); // more computations involving attr_one; just print for now... double attr_one = PyFloat_AsDouble(attr_one_obj); printf("%f\\n",attr_one); } } """ weave.inline(code,['myobjects','rows','cols'],local_dict=locals(),verbose=1) test_list = [[MyObject(0.0),MyObject(1.0)],[MyObject(2.0),MyObject(3.0)]] test_loop(test_list) From clp at rebertia.com Thu Sep 4 18:47:00 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 4 Sep 2008 15:47:00 -0700 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <g9pn28$4u1$1@ger.gmane.org> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> Message-ID: <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> On Thu, Sep 4, 2008 at 3:37 PM, Robert Dailey <rcdailey at gmail.com> wrote: > On Thu, Sep 4, 2008 at 5:21 PM, Fredrik Lundh <fredrik at pythonware.com> > wrote: >> >> Robert Dailey wrote: >> >>> I currently have a dictionary object that I'm doing the following with: >>> >>> if lib not in stage_map: >>> # ... do stuff ... >>> >>> However, this will perform a case-sensitive comparison between lib and >>> each key in stage_map. Is there a way to make this do a case-insensitive >>> comparison instead? >> >> dictionary lookups use the exact value. to make a case-insensitive >> lookup, use key.lower() instead of key when creating the dictionary, and >> then do >> >> if lib.lower() not in state_map: >> ... > > So you're saying to ensure that stage_map's keys are initially lower-case to > begin with? Well, I can't do this either since the case of the keys is > actually valuable later on. It's only for the purposes of this specific > comparison operation that the case should be ignored. Then store the string in its original case in the value part of the key-value pair: stage_map[key.lower()] = (key,whatever) - Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From blogmoney.bm at gmail.com Fri Sep 26 01:16:08 2008 From: blogmoney.bm at gmail.com (blogmoney) Date: Thu, 25 Sep 2008 22:16:08 -0700 (PDT) Subject: ==== XXX--SECRET Web Cams LADIES HOSTELS ====== Message-ID: <b4f12a2b-8e9f-488d-bbab-7499e2355d1f@v13g2000pro.googlegroups.com> Hi....Friends, watch and enjoy SECRET WEB-CAMS at LADIES HOSTELS and INTERNET CAFE SEX SCANDALS VIDEOS... ** HOT Sexy Girls Nude Video's ** ** Porn Video's ** ** Nude Sexy For Mega Size Big Boobs ** Lesbian ** ** Gay ** Lesbian ** Data Sex ** Pay Sex's *** www.onlinejobszone.blogspot.com www.sfimoney4all.blogspot.com www.yogatips4all.blogspot.com www.hollywoodspicyzone.blogspot.com http://onlinemoney2u.wordpress.com www.onlinejobs4all.googlepages.com From ppearson at nowhere.invalid Tue Sep 23 11:14:18 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 23 Sep 2008 15:14:18 GMT Subject: Docstrings for class attributes References: <mailman.1392.1222147427.3487.python-list@python.org> Message-ID: <6jsfeaF4pbs9U1@mid.individual.net> On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris <celephicus at gmail.com> wrote: > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 > > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. [snip] Commiserating, not helping: I have a similar problem with a module that holds values of physical constants, http://webpages.charter.net/curryfans/peter/nature.py: boltzmanns_constant = 1.380622e-16 * erg / k stefan_boltzmann_constant = 5.66961e-5 * erg/s/cm/cm/k/k/k/k gravitational_constant = 6.6732e-8 * erg*cm/g/g I would like to reveal more details with, e.g., help( gravitational_constant ) . . . and maybe then I could use shorter names. -- To email me, substitute nowhere->spamcop, invalid->net. From squishywaffle at gmail.com Wed Sep 24 15:31:37 2008 From: squishywaffle at gmail.com (squishywaffle at gmail.com) Date: Wed, 24 Sep 2008 12:31:37 -0700 (PDT) Subject: Folder Actions on Mac OSX Leopard? Message-ID: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> Greetings, I've been trying to figure out if it's possible to attach a Python script to an action via Mac OSX Leopard's File Actions system. I'm wanting to call a Python script every time a file is added to the monitored folder. Just adding a .py file doesn't seem to do anything at all, and I can't find any log output anywhere to see what's going on. I'm more just looking to see if this is or is not possible. I'm not interested in other solutions, as I already have them lined up in case this is a no-go, but I'd really love to be able to do it this way if anyone has any experience. Googling around revealed pretty much nothing. Any help is much appreciated, Greg From nick at craig-wood.com Thu Sep 4 04:35:52 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 04 Sep 2008 03:35:52 -0500 Subject: use str as variable name References: <mailman.460.1220513147.3487.python-list@python.org> Message-ID: <slrngbv5sq.jr7.nick@irishsea.home.craig-wood.com> Mathieu Prevot <mathieu.prevot at gmail.com> wrote: > Hi, > > I have a program that take a word as argument, and I would like to > link this word to a class variable. > > eg. > class foo(): > width = 10 > height = 20 > > a=foo() > arg='height' > a.__argname__= new_value Not quite sure what the above is supposed to achieve > rather than : > > if arg == 'height': > a.height = new_value > elif arg == 'width'; > a.width = new_value > > Can I do this with python ? How ? setattr(a, arg, new_value) See: http://docs.python.org/lib/built-in-funcs.html -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From execrable at gmail.com Wed Sep 10 12:51:03 2008 From: execrable at gmail.com (B) Date: Wed, 10 Sep 2008 09:51:03 -0700 Subject: dict slice in python (translating perl to python) In-Reply-To: <mailman.804.1221065237.3487.python-list@python.org> References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> <HDSxk.1411$ZY5.32@newsfe02.iad> <mailman.804.1221065237.3487.python-list@python.org> Message-ID: <XVSxk.103$_u2.8@newsfe08.iad> Fredrik Lundh wrote: > B wrote: >> for a long list, you could try: >> result = [mydict[k] for k in mydict] >> or [mydict[k] for k in mydict.keys()] >> or [mydict[k] for k in mydict.iterkeys()] > > and the point of doing that instead of calling mydict.values() is what? > > </F> > It's more fun? Or if you want to sort by keys. From candide at free.invalid Sat Sep 20 05:23:39 2008 From: candide at free.invalid (candide) Date: Sat, 20 Sep 2008 11:23:39 +0200 Subject: Not fully OO ? Message-ID: <48d4c11b$0$22877$426a74cc@news.free.fr> Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : "About Python: Python is a high level scripting language with object oriented features. (...) Python supports OOP and classes to an extent, but is not a full OOP language." Thanks for any comment. From gnewsg at gmail.com Wed Sep 17 16:53:44 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 17 Sep 2008 13:53:44 -0700 (PDT) Subject: ssl server References: <eef6d1fa-12e6-4549-a85e-c0ba21b19c63@25g2000hsx.googlegroups.com> Message-ID: <7ac8d302-0dae-4f19-81a9-8926c6b22a01@26g2000hsk.googlegroups.com> On 17 Set, 19:33, Seb <sebastianthegreat... at gmail.com> wrote: > I'm making a ssl server, but I'm not sure how I can verify the > clients. What do I actually need to place in _verify to actually > verify that the client cert is signed by me? > > ?50 class SSLTCPServer(TCPServer): > ?51 ? ? ? ? keyFile = "sslcert/server.key" > ?52 ? ? ? ? certFile = "sslcert/server.crt" > ?53 ? ? ? ? def __init__(self, server_address, RequestHandlerClass): > ?54 ? ? ? ? ? ? ? ? ctx = SSL.Context(SSL.SSLv23_METHOD) > ?55 ? ? ? ? ? ? ? ? ctx.use_privatekey_file(self.keyFile) > ?56 ? ? ? ? ? ? ? ? ctx.use_certificate_file(self.certFile) > ?57 ? ? ? ? ? ? ? ? ctx.set_verify(SSL.VERIFY_PEER | > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > self._verify) > ?58 ? ? ? ? ? ? ? ? ctx.set_verify_depth(10) > ?59 ? ? ? ? ? ? ? ? ctx.set_session_id('DFS') > ?60 > ?61 ? ? ? ? ? ? ? ? self.server_address = server_address > ?62 ? ? ? ? ? ? ? ? self.RequestHandlerClass = RequestHandlerClass > ?63 ? ? ? ? ? ? ? ? self.socket = socket.socket(self.address_family, > self.socket_type) > ?64 ? ? ? ? ? ? ? ? self.socket = SSL.Connection(ctx, self.socket) > ?65 ? ? ? ? ? ? ? ? self.socket.bind(self.server_address) > ?66 ? ? ? ? ? ? ? ? self.socket.listen(self.request_queue_size) > ?67 > ?68 ? ? ? ? def _verify(self, conn, cert, errno, depth, retcode): > ?69 ? ? ? ? ? ? ? ? return not cert.has_expired() and > cert.get_issuer().organizationName == 'DFS' What library are you using? PyOpenSSL? In that case I think you'll have more luck by posting on their mailing list. --- Giampaolo http://code.google.com/p/pyftpdlib/ From code at pizzashack.org Tue Sep 2 18:15:07 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 18:15:07 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> Message-ID: <20080902221507.GS29228@dragontoe.org> On Tue, Sep 02, 2008 at 05:22:51PM -0300, Gabriel Genellina wrote: > > The name popen is an abbreviation of "pipe open" -- the function, and > > the class, open pipes to communicate with another process. What you > > said is correct; however there are numerous other ways to open > > subprocesses. The focus of popen is the communication aspect -- the > > opening and control of the pipes -- not the subprocess. That's the > > key difference between popen() and all the other methods of starting a > > subprocess. > > Totally irrelevant here - we are talking about the subprocess > module, not the popen C function. I was talking about both actually. I can't agree that it's not relevant... The Popen class clearly takes its name from the function of the same name, and does exactly the same thing (plus what pclose() does, plus saving the pid of the forked process). Seems pretty relevant to me. > >> > The C library's popen() function, on which this class is based, > > No, subprocess.Popen does not use -directly or indirectly- the C > popen function. It uses fork or CreateProcess in Windows. I didn't say it used it. I said it was based on it. It is (conceptually). > > The Linux man page unfortunately copies (verbatim) the FreeBSD man > > page, which gets it wrong. You can not open a process, but you can > > definitely open a pipe. > > (Ok, if it doesn't agree with you, it must be wrong) See my last post for accreditation of my comment. A common argumentation tactic of the closed-minded and the small-minded is to resort to insinuation to attack the validity of other's comments without providing any basis for doing so. Nice job. > Classes represent "things", and class names should be nouns. Is that a law? Classes are instantiated by invoking their class names as a function call -- the computing equivalent of a verb. Why then, must they be named as nouns? Can you not, in fact, have classes which describe (or model) actions? Wouldn't you name them using verbs if you did? That said, this is the most valid point anyone has made... You should have made it when the module was being designed. :-D My point is, if you don't think Popen is a good name for the class, that's your opinion, but it is only that: an opinion. Yet some of you state your case as if it is incontrovertable fact. I've given a good case as to why it IS a good name (one which I genuinely support), and disagree as you may, none of the points any of you have made invalidate or even weaken my argument. Lastly, the maintainers obviously thought it was a good name when they included it... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/ccc1bc0f/attachment-0001.sig> From Lie.1296 at gmail.com Sun Sep 28 07:12:45 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 04:12:45 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <gbn6nu$r5j$4@lust.ihug.co.nz> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> Message-ID: <6f247162-b0b7-4fba-bfd8-df9261cc5d30@p31g2000prf.googlegroups.com> On Sep 28, 3:35?pm, est <electronix... at gmail.com> wrote: > > Because that's how ASCII is defined. > > Because that's how ASCII is defined. ?ASCII is a 7-bit code. > > Then why can't python use another default encoding internally > range(256)? > > > Python refuses to guess and tries the lowest common denominator -- ASCII -- instead. > > That's the problem. ASCII is INCOMPLETE! What do you propose? Use mbsc and smack out linux computers? Use KOI and make non-Russians suicide? Use GB and shot dead non-Chinese? Use latin-1 and make emails servers scream? > If Python choose another default encoding which handles range(256), > 80% of python unicode encoding problems are gone. > > It's not HARD to process unicode, it's just python & python community > refuse to correct it. Python's unicode support is already correct. Only your brainwave have not been tuned to it yet. > > stop dreaming of a magic solution > > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, > what's wrong???? > > > Isn't that more or less the same as telling the OP to use unicode() instead of str()? > > sockets could handle str() only. If you throw unicode objects to a > socket, it will automatically call str() and cause an error. From rpdooling at gmail.com Wed Sep 3 08:27:20 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Wed, 3 Sep 2008 05:27:20 -0700 (PDT) Subject: new python docs Message-ID: <62c0c392-d4e1-4cae-aae0-38d35c4faf57@w7g2000hsa.googlegroups.com> Wow! I've been away in other pursuits. The new docs are gorgeous and searchable. http://docs.python.org/dev/index.html Thank you, python.org. From castironpi at gmail.com Tue Sep 16 17:33:09 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 14:33:09 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> <a860c259-c932-4588-ae2d-7ba6f2d3eb17@e53g2000hsa.googlegroups.com> <99c53e1a-a693-4f35-b937-d172c565077c@m36g2000hse.googlegroups.com> Message-ID: <0a99ca77-d4c3-40af-af5e-91f2f5a52a9e@f63g2000hsf.googlegroups.com> On Sep 16, 4:24?pm, cnb <circularf... at yahoo.se> wrote: > On Sep 16, 10:53?pm, "Aaron \"Castironpi\" Brady" > > > > <castiro... at gmail.com> wrote: > > On Sep 16, 3:16?pm, cnb <circularf... at yahoo.se> wrote: > > > > On Sep 16, 7:49?pm, "Aaron \"Castironpi\" Brady" > > > > > Now I have my personal programs in C:/Python25/Progs/ > > > > > > How do I add so that I can just do "import somefile" from anywhere in > > > > > that directory in the interpreter and it can load files from other > > > > > folders in that directory. > > > > > Add a file: \Lib\site-packages\locals.pth > > > > > with contents, path to the directory you want to add (/python25/progs/) > > > > And we have a winner! > > > > Now it works. Both doing import and loading form fiel with C-c C-l > > > > However jsut including C:/Python/Progs wasn't enough. I had to add the > > > folder inside that that contains the files i needed. > > > > so how do i add all files within progs? is there something like C:/ > > > python25/progs/* ? > > > You have: > > > c:/python/progs/abc/filea.py > > c:/python/progs/abc/fileb.py > > c:/python/progs/def/filed.py > > c:/python/progs/def/filee.py > > > __init__.py in progs ? (empty...) > > __init__.py in abc > > __init__.py in def > > > c:/python/site-packages/lib/locals.py ?which contains: > > c:/python/progs/ > > > You don't need the subdirectories. ?You can do: > > > import abc > > import abc.filea > > from abc import filea > > no I can't... Ok well here's mine: I have /Documents and Settings/usr/Desktop/working/imptest/ in locals.pth. These directories: Directory of C:\Documents and Settings\usr\Desktop\working\imptest 09/16/2008 04:29 PM <DIR> impt Directory of C:\Documents and Settings\usr\Desktop\working\imptest \impt 09/16/2008 04:29 PM <DIR> abc 09/16/2008 04:29 PM <DIR> defg 09/16/2008 03:40 PM 0 __init__.py 1 File(s) 0 bytes Directory of C:\Documents and Settings\usr\Desktop\working\imptest \impt\abc 09/16/2008 03:40 PM 13 abcmod.py 09/16/2008 03:40 PM 0 __init__.py Directory of C:\Documents and Settings\usr\Desktop\working\imptest \impt\defg 09/16/2008 03:40 PM 13 defmod.py 09/16/2008 03:40 PM 0 __init__.py and this code: >>> import impt >>> import impt.abc >>> import impt.abc.abcmod >>> import impt.defg >>> import impt.defg.defmod I understand the import behavior will change in 3.0. From half.italian at gmail.com Fri Sep 26 14:35:11 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 26 Sep 2008 11:35:11 -0700 (PDT) Subject: how to search multiple textfiles ? References: <mailman.1536.1222436146.3487.python-list@python.org> Message-ID: <a1ed03f4-6756-4336-bafa-629b35dc6782@z6g2000pre.googlegroups.com> On Sep 26, 6:35?am, Stef Mientki <s.mien... at ru.nl> wrote: > hello, > > I want to search multiple textfiles (python source files) for a specific > word. > I can find all files, open them and do a search, > but I guess that will be rather slow. > > I couldn't find any relevant information through google. > > Does anyone know of a search library that performs this task fast ? > > If it indeed only concerns py-files, > is there another way of searching words ? > ( I could imagine that such a "py-only-search" would have benefits, > because you could set a flag to see the words in comment yes or no ) > > thanks, > Stef Mientki > > Het UMC St Radboud staat geregistreerd bij de Kamer van Koophandel in het handelsregister onder nummer 41055629. > The Radboud University Nijmegen Medical Centre is listed in the Commercial Register of the Chamber of Commerce under file number 41055629. I use 'fgrep' ie... `fgrep -r "toFind" /source` ~Sean From m_palmer45 at yahoo.ca Wed Sep 17 19:05:51 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 17 Sep 2008 16:05:51 -0700 (PDT) Subject: ssl server References: <eef6d1fa-12e6-4549-a85e-c0ba21b19c63@25g2000hsx.googlegroups.com> Message-ID: <72ed03e9-e3cd-4feb-ac5c-41f9ee1f5458@y21g2000hsf.googlegroups.com> On Sep 17, 1:33 pm, Seb <sebastianthegreat... at gmail.com> wrote: > I'm making a ssl server, but I'm not sure how I can verify the > clients. What do I actually need to place in _verify to actually > verify that the client cert is signed by me? > > 50 class SSLTCPServer(TCPServer): > 51 keyFile = "sslcert/server.key" > 52 certFile = "sslcert/server.crt" > 53 def __init__(self, server_address, RequestHandlerClass): > 54 ctx = SSL.Context(SSL.SSLv23_METHOD) > 55 ctx.use_privatekey_file(self.keyFile) > 56 ctx.use_certificate_file(self.certFile) > 57 ctx.set_verify(SSL.VERIFY_PEER | > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > self._verify) > 58 ctx.set_verify_depth(10) > 59 ctx.set_session_id('DFS') > 60 > 61 self.server_address = server_address > 62 self.RequestHandlerClass = RequestHandlerClass > 63 self.socket = socket.socket(self.address_family, > self.socket_type) > 64 self.socket = SSL.Connection(ctx, self.socket) > 65 self.socket.bind(self.server_address) > 66 self.socket.listen(self.request_queue_size) > 67 > 68 def _verify(self, conn, cert, errno, depth, retcode): > 69 return not cert.has_expired() and > cert.get_issuer().organizationName == 'DFS' If I were you, I would just just hide behind apache, nginx oder another server that does ssl. just have that server proxy locally to your python server over http, and firewall the python server port. From bdesth.quelquechose at free.quelquepart.fr Thu Sep 18 14:43:00 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 18 Sep 2008 20:43:00 +0200 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <48d2bd22$0$4514$426a74cc@news.free.fr> Alexzive a ?crit : > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? A couple ones have been submitted. Harald gets a point about the redundant tests (even if his solution seems to be broken, cf below) - your inner loop should have looked like : for j in xrange(i+1, len(IN)) Now the obvious winner is pruebono - even unoptimized, using sets seems to be *way* faster than even the most optimized corrected version of your algorithm. Here's a quick bench - please everyone doublecheck it to make sure it's ok: from timeit import Timer import random class Node(object): def __init__(self, x, y): self.coordinates = (x, y) def __repr__(self): return repr(self.coordinates) # how to build src: # src = [(random.randrange(10),random.randrange(10)) for x in xrange(100)] src = [ (4, 9), (5, 0), (6, 6), (7, 2), (3, 6), (9, 6), (0, 1), (1, 6), (0, 5), (1, 2), (8, 9), (5, 4), (1, 6), (7, 6), (9, 1), (7, 6), (0, 1), (7, 4), (7, 4), (8, 4), (8, 4), (3, 5), (9, 6), (6, 1), (3, 4), (4, 5), (0, 5), (6, 3), (2, 4), (1, 6), (9, 5), (1, 2), (5, 8), (8, 5), (3, 1), (9, 4), (9, 4), (3, 3), (4, 8), (9, 7), (8, 4), (6, 2), (1, 5), (5, 8), (8, 6), (0, 8), (5, 2), (3, 4), (0, 5), (4, 4), (2, 9), (7, 7), (1, 0), (4, 2), (5, 7), (0, 4), (2, 5), (0, 8), (7, 3), (9, 1), (0, 4), (5, 0), (4, 9), (0, 6), (3, 0), (3, 0), (3, 9), (8, 3), (7, 9), (8, 5), (7, 6), (1, 5), (0, 6), (5, 9), (6, 8), (0, 0), (4, 1), (3, 3), (5, 4), (5, 3), (6, 1), (5, 4), (4, 5), (5, 8), (4, 1), (3, 6), (1, 9), (0, 5), (6, 5), (5, 5), (6, 0), (0, 9), (2, 6), (0, 7), (5, 9), (7, 3), (7, 9), (5, 4), (4, 9), (2, 9) ] IN = [Node(x, y) for x, y in src] def doubles0(): SN = [] for i in range(len(IN)): #scan all elements of the list IN for j in range(len(IN)): #print i, j if i <> j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i]) return SN def doubles1(): "first solve an algoritmic problem" SN = [] for i in range(len(IN)): for j in range(i+1, len(IN)): #print i, j #if i != j: if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i]) return SN def doubles2(): "then avoid buildin useless lists" SN = [] for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i]) return SN def doubles3(): "then avoid uselessly calling a constant operation" SN = [] in_len = len(IN) for i in xrange(in_len): for j in xrange(i+1, in_len): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: SN.append(IN[i]) return SN def doubles4(): "then alias commonly used methods" SN = [] sn_append = SN.append in_len = len(IN) for i in xrange(in_len): for j in xrange(i+1, in_len): if IN[i].coordinates[0] == IN[j].coordinates[0]: if IN[i].coordinates[1] == IN[j].coordinates[1]: sn_append(IN[i]) return SN def doubles5(): "then alias a couple other things" SN = [] sn_append = SN.append in_len = len(IN) for i in xrange(in_len): node_i = IN[i] coords_i = node_i.coordinates for j in xrange(i+1, in_len): if coords_i[0] == IN[j].coordinates[0]: if coords_i[1] == IN[j].coordinates[1]: sn_append(node_i) return SN def doubles6(): "then simplify tests" SN = [] sn_append = SN.append in_len = len(IN) for i in xrange(in_len): node_i = IN[i] coords_i = node_i.coordinates for j in xrange(i+1, in_len): if coords_i == IN[j].coordinates: sn_append(node_i) return SN # Harald : uncomment this and run test_results. As far as I can tell, it # doesn't yields the expected results ## IN7 = IN[:] ## def sortk7(n): ## return n.coordinates[0] ## def doubles7(): ## "is ordering better ? - Nope Sir, it's broken..." ## IN7.sort(key=sortk) ## SN = [] ## sn_append = SN.append ## in_len = len(IN) ## for i in xrange(in_len): ## node_i = IN[i] ## coords_i = node_i.coordinates ## for j in xrange(i+1, in_len): ## if coords_i[0] == IN[j].coordinates[0]: ## if coords_i[1] == IN[j].coordinates[1]: ## sn_append(node_i) ## else: ## break ## return SN def doubles8(): "Using a set ?" dup = set() SN = [] for item in IN: c = item.coordinates if c in dup: SN.append(item) else: dup.add(c) return SN def doubles9(): "Using a set is way faster - but can still be improved a bit" dup = set() dup_add = dup.add SN = [] sn_append = SN.append for item in IN: c = item.coordinates if c in dup: sn_append(item) else: dup_add(c) return SN # need this for tests: names_funcs = sorted( (n, f) for n, f in locals().iteritems() if n.startswith('doubles') ) def test_results(): """ make sure all solutions give correct results, assuming the OP solution is at least correct !-) """ results = [ (n, set(o.coordinates for o in f())) for n, f in names_funcs ] _, correct = results[0] ok = True for n, r in results[1:]: if r != correct: print "error on %s ?\n expected %s\n, got %s" \ % (n, correct, r) ok = False return ok def test_times(): " And the winner is..." results = [ (n, Timer( '%s()' % n, 'from __main__ import %s' % n ).timeit(100) ) for n, _ in names_funcs ] print "\n".join("%s : %s" % r for r in results) Results here (py2.5, gentoo linux, athlonxp1800, 512 ram): >>> test_results() True >>> test_times() doubles0 : 1.55667901039 doubles1 : 0.719144105911 doubles2 : 0.703393936157 doubles3 : 0.700654983521 doubles4 : 0.706257104874 doubles5 : 0.528184890747 doubles6 : 0.461633205414 doubles8 : 0.0134379863739 doubles9 : 0.0108540058136 >>> Not surprisingly, half less iterations makes for half less time. Aliasing, as often, proves to be a good optimization too. But obviously, using the correct data structure / algorithm combo is the key : simpler code, and 115 times faster (143 times with aliasing). If pruebono solution's is correct (and it as AFAICT), your 15 hours computation should by now take less than 10 minutes... From steven at REMOVE.THIS.cybersource.com.au Sun Sep 28 19:06:58 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 23:06:58 GMT Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> Message-ID: <pan.2008.09.28.23.06.57@REMOVE.THIS.cybersource.com.au> On Sun, 28 Sep 2008 17:47:44 -0400, Terry Reedy wrote: > Aaron "Castironpi" Brady wrote: >> On Sep 28, 2:52 am, Steven D'Aprano <st... at REMOVE-THIS- > >>> As for why the complicated version works, it may be clearer if you >>> expand it from a one-liner: >>> >>> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) >>> >>> inner = lambda: n >>> outer = lambda n: inner >>> f[n] = outer(n) >>> >>> outer(0) => inner with a local scope of n=0 outer(1) => inner with a >>> local scope of n=1 etc. > > For this to work, the 'expansion' has to be mental and not actual. Which > is to say, inner must be a text macro to be substituted back into outer. Er, yes, that's what I meant, sorry for not being more explicit. That's why it wasn't a copy and paste of actual running code. Or perhaps I just confused myself and was talking nonsense. -- Steven From ssharkey at linuxunlimited.com Thu Sep 25 16:45:55 2008 From: ssharkey at linuxunlimited.com (Scott Sharkey) Date: Thu, 25 Sep 2008 16:45:55 -0400 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: <6k2aqqF5p185U1@mid.uni-berlin.de> References: <mailman.1506.1222370612.3487.python-list@python.org> <QQRCk.1802$Pv5.235@edtnps83> <6k2aqqF5p185U1@mid.uni-berlin.de> Message-ID: <48DBF883.6000909@linuxunlimited.com> Diez B. Roggisch wrote: > Dmitry S. Makovey schrieb: >> Scott Sharkey wrote: >>> Any insight into the best way to have a consistent, repeatable, >>> controllable development and production environment would be much >>> appreciated. >> >> you have just described OS package building ;) Except that we do need multiple different environments on one server, and also have issues where our servers may be Windows. >> I can't speak for everybody, but supporting multiple platforms (PHP, Perl, >> Python, Java) we found that the only way to stay consistent is to use OS >> native packaging tools (in your case apt and .deb ) and if you're missing >> something - roll your own package. After a while you accumulate plenty of >> templates to chose from when you need yet-another-library not available >> upstream in your preferred package format. Remember that some python tools >> might depend on non-python packages, so the only way to make sure all that >> is consistent across environment - use unified package management. > > That this is a desirable goal can't be argued against. Yet two big hurdles make it often impractical to be dogmatic about that: > > - different OS. I for one don't know about a package management tool for windows. And while our servers use Linux (and I as developer as well), all the rest of our people use windows. No use telling them to apt-get instal python-imaging. Exactly! > - keeping track of recent developments. In the Python webframework world for example (which the OP seems to be working with), things move fast. Or extremly slow, regarding releases. Take Django - until 2 month ago, there hasn't been a stable release for *years*. Virtually everybody was working with trunk. And given the rather strict packaging policies of debian and consorts, you'd be cut off of recent developments as well as of bugfixes. Very much the case. Most of debian's packages for python are woefully out of date, it seems. And then we're at the whim of the os provider as to when updates happen, rather than being controlled by our staff. I am very interested in the eggbasket project - that's something that's been needed for a while. And I'm aware of the setuptools fork, and the discussion on the distutils sig mailing list. Thanks. -Scott From sturlamolden at yahoo.no Tue Sep 23 15:49:45 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 12:49:45 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <d086d0b2-0624-45ee-b72f-49d88a7dfe33@79g2000hsk.googlegroups.com> <c5e8ae40-9ed6-41c9-8914-4a3d0f001f0c@m36g2000hse.googlegroups.com> <mailman.1423.1222197466.3487.python-list@python.org> Message-ID: <c124d367-bf08-42cf-934a-592a723c73ea@e53g2000hsa.googlegroups.com> On Sep 23, 9:17?pm, Robert Kern <robert.k... at gmail.com> wrote: > You could also drop it on the scipy.org wiki in the Cookbook category. Yes, if I could figure out how to use it... From stava at telcotec.se Mon Sep 29 02:58:30 2008 From: stava at telcotec.se (Lars Stavholm) Date: Mon, 29 Sep 2008 08:58:30 +0200 Subject: python for *nix system admins In-Reply-To: <48DDE92D.6090405@telcotec.se> References: <48DDE92D.6090405@telcotec.se> Message-ID: <48E07C96.9080003@telcotec.se> Thank you all for your input. /Lars Lars Stavholm wrote: > Hi All, > > I'm new to this list and hoping that this is not off-topic. > If it is, please point me in the right direction. > > I seem to recollect a python module or library for *nix sysadmins, > but I can't for the life of me find it again. > > The module (or library) somehow added unix command capabilities > to the python language. It seemed like a lesser known, perhaps new, > python library or module. > > Any input or ideas appreciated > /Lars Stavholm > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Fri Sep 19 05:21:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 06:21:56 -0300 Subject: Intercepting printed strings References: <496954360809181524g6037e0b0x84e98834bbf8ad9c@mail.gmail.com> Message-ID: <op.uhp1mu0ux6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 18 Sep 2008 19:24:26 -0300, Robert Dailey <rcdailey at gmail.com> escribi?: > I'm currently using Python 3.0 b3 and I'm curious as to how I can go > about > intercepting things send to print() for some intermediate processing > before > they're actually sent to sys.stdout. Right now I've thought of the > following: > > Replace sys.stdout with a class named PrintStream. PrintStream is > defined as > follows: > > class PrintStream: > def write( self, message ): > sys.__stdout__.write( '\t{0}'.format( message ) ) > > Will this work? Basically I want to add a tab character in front of every > message printed. Thanks. Why don't you try it yourself? You may replace builtins.print with your own function too. It's not exactly the same thing, but given your request "intercepting things send to print() before they're sent to sys.stdout" it may be more adequate. -- Gabriel Genellina From kyosohma at gmail.com Thu Sep 4 09:27:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Sep 2008 06:27:56 -0700 (PDT) Subject: path slashes cleaning References: <mailman.484.1220534735.3487.python-list@python.org> Message-ID: <e815a0ed-f42e-4c60-8911-46de4f1169f0@t1g2000pra.googlegroups.com> On Sep 4, 8:25?am, "Mathieu Prevot" <mathieu.pre... at gmail.com> wrote: > Hi, > > for scripts that take arguments, I would like to remove the trailing > slash if it's present. > > Is there something else than: > > a='/usr/local/lib/' > if a[-1] == '/': > ? a = list(a) > ? a.pop() > ? ''.join(a) > > Thanks, > Mathieu How about this: if a[-1] == '/': a = a[:-1] Mike From paul at boddie.org.uk Thu Sep 11 17:55:09 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 11 Sep 2008 14:55:09 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> <pan.2008.09.11.07.40.08@REMOVE.THIS.cybersource.com.au> <mailman.854.1221122089.3487.python-list@python.org> <823435cf-a557-48d9-9e16-fa28e745e67a@73g2000hsx.googlegroups.com> <8f9a61c9-55d7-4a1e-a4f1-9dda6a5d2b31@59g2000hsb.googlegroups.com> Message-ID: <47de9bd7-755e-45fb-b35b-72ebf4d52753@d77g2000hsb.googlegroups.com> On 11 Sep, 19:31, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > > An acquaintance suggests that defragmentation would be a useful > service to provide along with memory management too, which also > requires an index. I presume that you mean efficient access to large amounts of data in the sense that if all the data you want happens to be in the same page or segment, then retrieving it is much more efficient than having to seek around for all the different pieces. So the defragmentation would be what they call clustering in a relational database context: http://www.postgresql.org/docs/8.3/static/sql-cluster.html I've seen similar phenomena outside the relational database world, notably with big Lucene indexes which wouldn't fit in memory in their entirety. > I encourage overlap between a bare-bones alloc/free module and > established database territory and I'm very aware of it. > > Databases already support both concurrency and persistence, but don't > tell me you'd use a database for IPC. Of course, databases are widely used in scalable systems to hold central state, which is why there's a lot of effort put into to not only scaling up database installations, but also into things like caching which are supposed to save the database systems behind popular Web applications from excessive load. > And don't tell me you've never > wished you had a reference to a record in a table so that you could > make an update just by changing one word of memory at the right > place. Sometimes databases are overkill where all you want is dynamic > allocation. I think that the challenge is to reduce an abstract operation (for example, wanting to update a particular column in a particular record) to its measurable effects (this word of memory/disk will change as a consequence). It's easy for a human with a reasonable knowledge of, say, a relational database system to anticipate such things, but to actually collapse a number of layers through some kind of generic optimisation process is a lot more difficult. Paul From grante at visi.com Tue Sep 23 10:52:16 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 23 Sep 2008 09:52:16 -0500 Subject: Attachment Size and SMTP EMail References: <a2747a10-ecd6-4254-922e-59e8a2784c3b@m3g2000hsc.googlegroups.com> Message-ID: <aM-dneOKGd09n0TVnZ2dnUVZ_r7inZ2d@posted.visi> On 2008-09-23, Eric E <eric.e.janke at gmail.com> wrote: > I am using python to send an email with a large zip file as an > attachment. I successfully sent a 52M attachment. If I try > to send a 63M attachment or larger, the message never gets > through. I do not get any errors in my python code. Does sending large attachements with other SMTP clients using the same SMTP server work? -- Grant Edwards grante Yow! Zippy's brain cells at are straining to bridge visi.com synapses ... From enleverlesX.XmcX at XmclaveauX.com Fri Sep 26 09:58:02 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 26 Sep 2008 15:58:02 +0200 Subject: how to search multiple textfiles ? In-Reply-To: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> References: <mailman.1536.1222436146.3487.python-list@python.org> <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> Message-ID: <48dcecea$0$910$ba4acef3@news.orange.fr> Hi! On Windows, you can use the (standard) command findstr Example: findstr /n /s /I strsearched *.py @-salutations -- Michel Claveau From cs at zip.com.au Mon Sep 22 00:32:17 2008 From: cs at zip.com.au (Cameron Simpson) Date: Mon, 22 Sep 2008 14:32:17 +1000 Subject: Why are "broken iterators" broken? In-Reply-To: <gb5t65$k2$1@ger.gmane.org> Message-ID: <20080922043217.GA10077@cskk.homeip.net> On 21Sep2008 18:36, Fredrik Lundh <fredrik at pythonware.com> wrote: > Roy Smith wrote: >> There are plausible examples of collections which grow while you're >> iterating over them. I'm thinking specifically of a queue in a >> multi-threaded application. One thread pushes work onto the back of >> the queue while another pops from the front. The queue could certainly >> go empty at times. But, maybe a Python iterator is just the wrong way >> to model such behavior. > > you probably want the consumer thread to block when it catches up with > the producer, rather than exit. > (that's the default behaviour of Python's Queue object, btw) It sounds like he wants non-blocking behaviour in his consumer. A common example is "try to gather a lot of stuff into a single packet, but send a smaller packet promptly if there isn't much stuff". You could make the next() method return a sentinal value like None when the queue is empty. That would mean your consumer must recognise the special value and also precludes delivering that value through the queue. I'm not convinced my suggestion here is any better than just doubling up every call to next() with an empty() check immediately beforehand. You could write a trivial wrapping generator to take the original blocking queue and return a sentinel value on empty, too. My suggestion is also an excellent way of getting programs that fail-busy (i.e. they spin out) if you make a logic error in your consumer. Ouch. Cheers, -- Cameron Simpson <cs at zip.com.au> DoD#743 http://www.cskk.ezoshosting.com/cs/ Kill, v.t. To create a vacancy without nominating a successor. Ambrose Bierce (1842-1914), U.S. author. The Devil's Dictionary (1881-1906). From george.sakkis at gmail.com Sun Sep 28 06:19:45 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 28 Sep 2008 03:19:45 -0700 (PDT) Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> <Mo7Dk.2064$T65.1885@edtnps82> <48dd5c06$0$26425$426a74cc@news.free.fr> <WvdDk.2157$T65.1610@edtnps82> <f6351d10-2573-4a5c-ab57-d4dd1c7b311c@e53g2000hsa.googlegroups.com> <YKjDk.2022$Pv5.1949@edtnps83> <a7a895ef-ff22-4dc8-8213-97482e5bb19f@z72g2000hsb.googlegroups.com> <c7db7b82-7350-4365-8c12-40f949e739ea@u65g2000hsc.googlegroups.com> <91e62d70-73fb-4ecc-ae2e-d950a5f7ea6b@k13g2000hse.googlegroups.com> <T_CDk.2342$Pv5.396@edtnps83> Message-ID: <877b889b-c385-4e2b-abe9-17669eca09b8@d70g2000hsc.googlegroups.com> On Sep 27, 11:38?pm, "Dmitry S. Makovey" <dmi... at makovey.net> wrote: > George Sakkis wrote: > > It's funny how often you come with a better solution a few moments > > after htting send! The snippet above can (ab)use the decorator syntax > > so that it becomes: > > > class A(Proxy): > > > ? ? @ProxyMethod > > ? ? def bmethod(self): > > ? ? ? ? return self.b1 > > > ? ? @ProxyMethod > > ? ? def bmethod2(self): > > ? ? ? ? return self.b2 > > That is outstanding! FYI, in case you missed it the final version doesn't need a Proxy base class, just inherit from object. Also lowercased ProxyMethod to look similar to staticmethod/classmethod: class A(object): def __init__(self, b1, b2): self.b1 = b1 self.b2 = b2 @proxymethod def bmethod(self): return self.b1 @proxymethod def bmethod2(self): return self.b2 George From bearophileHUGS at lycos.com Tue Sep 2 17:38:51 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 2 Sep 2008 14:38:51 -0700 (PDT) Subject: Renumbering References: <mailman.386.1220389036.3487.python-list@python.org> <4e6091af-bc00-4408-beda-adfa7f17dc63@b30g2000prf.googlegroups.com> Message-ID: <d98b8933-5da9-4936-bb30-9c29fbc962d5@x35g2000hsb.googlegroups.com> John Machin: > Is this homework? Have you put any effort into trying to write a script > yourself? Etc etc etc You are right, I am sorry -.- Bye, bearophile From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 06:36:38 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 12:36:38 +0200 Subject: BadStatusLine: In-Reply-To: <4e3d5d97-1b5f-4593-9c33-ad8b57d59b05@f36g2000hsa.googlegroups.com> References: <4e3d5d97-1b5f-4593-9c33-ad8b57d59b05@f36g2000hsa.googlegroups.com> Message-ID: <48d77535$0$2237$426a74cc@news.free.fr> noelob a ?crit : > Hi All, > > During performance testing of my web application, I occasionally get a > BadStatusLine exception from httplib. Reading > http://docs.python.org/lib/module-httplib.html#l2h-4021 tells me that > it's "Raised if a server responds with a HTTP status code that we > don't understand." Is there a way to find what the actual status code > returned was? I.e. the value that caused the exception to be thrown? > Under what circumstances is a BadStatusLine normally thrown? (e.g. > data corruption?) httplib is a pure-python module, so nothing prevents you from reading the source code to get more accurate informations. It appears that this exception is raised when: - the status line is empty - the 'strict' flag is on and the status line didn't start with 'HTTP/' - the 'status' part of the status line is not convertible to an int - the status code ('status' part of the status line, converted to an int) is lower than 100 or higher than 999 NB: I may have missed something... In all cases, the offending status line is accessible as either .line and .args attribute of the exception. > I'm quite new to python, but not to programming. Apologies if this is > a silly question ;) Well... Not a silly question IMHO, but surely one you could have solved by yourself. It only requires two commands on an average posix system: - cd /your/python/install/lib/ - grep -A5 -B5 BadStatusLine httplib.py HTH From prologic at shortcircuit.net.au Wed Sep 10 21:32:59 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 11:32:59 +1000 Subject: Simple UDP server In-Reply-To: <slrngcgmd4.8co.nick@irishsea.home.craig-wood.com> References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> <slrngcgmd4.8co.nick@irishsea.home.craig-wood.com> Message-ID: <e1a84d570809101832y693e14d1rd1a58a1e7fdb4c5b@mail.gmail.com> On Thu, Sep 11, 2008 at 10:36 AM, Nick Craig-Wood <nick at craig-wood.com> wrote: > For UDP I wouldn't thread or, fork, I'd use select and run > asynchronously. > > http://docs.python.org/lib/module-select.html > > Actually if I really had to do this I'd use twisted. Right tool for > the job! For anyone interested, pymills is an event-driven, asynchronous library geared towards Component architectures. It currently uses select for it's socket components, TCPServer, TCPClient, and it's UDP counter-parts. cheers James -- -- -- "Problems are solved by method" From gagsl-py2 at yahoo.com.ar Tue Sep 16 03:11:32 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 04:11:32 -0300 Subject: how to exclude specific things when pickling? References: <nw9zk.32211$bx1.21567@bignews1.bellsouth.net> <7cd144b6-ca6f-447a-8448-5a334f8f999f@k37g2000hsf.googlegroups.com> Message-ID: <op.uhkbli1ax6zn5v@gabriel2.softlabbsas.com.ar> En Sun, 14 Sep 2008 12:06:44 -0300, Michael Palmer <m_palmer45 at yahoo.ca> escribi?: > On Sep 14, 10:53 am, "inhahe" <inh... at gmail.com> wrote: >> If I gather correctly pickling an object will pickle its entire >> hierarchy, >> but what if there are certain types of objects anywhere within the >> hierarchy >> that I don't want included in the serialization? What do I do to >> exclude >> them? Thanks. > > If your class defines a __getstate__ method, it is expected to return > the pickled state of the entire class. You can for example del those > items from self.__dict__ that you don't want pickled and then return > dumps(self). note: __getstate__ should return the *values* to be pickled, not the pickled state; else you end doing the work twice. And "del those items from self.__dict__" isn't a good idea, in general; I'd use a *copy* of __dict__ instead. -- Gabriel Genellina From marcus at internetnowasp.net Fri Sep 5 07:01:23 2008 From: marcus at internetnowasp.net (Marcus.CM) Date: Fri, 05 Sep 2008 19:01:23 +0800 Subject: found a bug with smtpd, where can i report this? Message-ID: <48C11183.5010502@internetnowasp.net> Hi, Where should i report the bug? smtpd bug. Marcus.CM From marco.bizzarri at gmail.com Fri Sep 12 10:18:05 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 12 Sep 2008 16:18:05 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <6ivbfvFnfucU1@mid.uni-berlin.de> References: <mailman.921.1221227464.3487.python-list@python.org> <6ivbfvFnfucU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809120718r6709387bj68e75e9c40ce2036@mail.gmail.com> On Fri, Sep 12, 2008 at 4:09 PM, Diez B. Roggisch <deets at nospam.web.de> wrote: > Marco Bizzarri schrieb: >> >> Hi all. >> >> In many parts of my code I've the following schema of code: >> >> def isInUseByOutgoingRegistrations(self, archivefolder): >> for instance in self.findActiveOutgoingRegistrationInstances(): >> if instance.forbidToClose(archivefolder): >> return True >> return False >> >> Before devising my own solution for this kind of problem, I wonder if >> there is a common solution for the problem. I'm looking for a >> python2.3 solution. > > if any(instance.forbitToClose(archivefolder) for instance in > self.findActiveOutgoingRegistrationInstances()) Can you clarify where I can find "any"? It seems to me I'm unable to find it... > You should also consider using PEP8 style naming. > I knew that someone would have said that to me :-). I'm doing that... slowly. I'm trying to fix naming conventions as I had to work on my code... > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From jjkk73 at gmail.com Mon Sep 1 07:06:20 2008 From: jjkk73 at gmail.com (jorma kala) Date: Mon, 1 Sep 2008 13:06:20 +0200 Subject: Retrieving http headers from HTTPConnection object Message-ID: <bda7ac6d0809010406j3a218984q8e6f1d9fb80b6abb@mail.gmail.com> Hi, when using httplib for http requests, like for example: conn = httplib.HTTPConnection("www.python.org") conn.request("GET", "/index.html") Is it possible to retrieve the complete http request in string form : GET /index.html HTTP/1.1 Host: www.python.org User-Agent: ... Accept: ... Accept-Language: Accept-Encoding: Accept-Charset: Keep-Alive: Connection: I mean does the HTTPConnection object have a property that stores this ? or is it retrievable by some other form? Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080901/f4dcb3bc/attachment-0001.html> From care02 at gmail.com Tue Sep 30 11:05:16 2008 From: care02 at gmail.com (care02 at gmail.com) Date: Tue, 30 Sep 2008 08:05:16 -0700 (PDT) Subject: XMLRPC - C Client / Python Server Message-ID: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> I have implemented a simple Python XMLRPC server and need to call it from a C/C++ client. What is the simplest way to do this? I need to pass numerical arrays from C/C++ to Python. Yours, Carl From grante at visi.com Mon Sep 15 00:07:08 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 23:07:08 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> <HYednR9_TqqbWVDVnZ2dnUVZ_oDinZ2d@posted.usinternet> <mailman.1023.1221448972.3487.python-list@python.org> Message-ID: <R-ednaGLHovxQlDVnZ2dnUVZ_gKdnZ2d@posted.usinternet> On 2008-09-15, Adelle Hartley <adelle at akemi.com.au> wrote: > Grant Edwards wrote: > >> When packages as significant as wxPython use naming >> conventions other than PEP 8, I find it hard to make a case >> that the PEP 8 naming convention is any better than any other. > > This relates to a question I was thinking about... > > I'm looking at porting a library that was written for COM and > .Net to work as a Python module, and was wondering whether it > would be better to stick to the library's current naming > convention so that the API is as similar as possible on each > platform, or to adopt a "when in Rome..." policy and follow > the "most mainstream" naming pattern for each > platform/language. If all that is would change is naming, then my advice would be to keep the existing naming. That way it matches existing documentation and examples. But, it does violate PEP 8. If the API itself is going to be changed significantly so that it's unique to the Python port (different to the point where existing documentation and examples are no longer useful), then using standard PEP 8 naming conventions is probably a good choice. -- Grant From bearophileHUGS at lycos.com Fri Sep 19 09:01:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Sep 2008 06:01:26 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <mailman.1220.1221752633.3487.python-list@python.org> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <gau926$f20$1@ger.gmane.org> <gavu71$43e$1@ger.gmane.org> <mailman.1274.1221827884.3487.python-list@python.org> Message-ID: <e29f8a4a-8aa0-43f4-9525-715a20f3ebfd@y21g2000hsf.googlegroups.com> Gerard flanagan: > data.sort() > datadict = \ > dict((k, len(list(g))) for k,g in groupby(data, lambda s: > '.'.join(s.split('.',2)[:2]))) That code may run correctly, but it's quite unreadable, while good Python programmers value high readability. So the right thing to do is to split that line into parts, giving meaningful names, and maybe even add comments. len(list(g))) looks like a good job for my little leniter() function (or better just an extension to the semantics of len) that time ago some people here have judged as useless, while I use it often in both Python and D ;-) Bye, bearophile From mail at timgolden.me.uk Fri Sep 19 04:42:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 19 Sep 2008 09:42:54 +0100 Subject: Python newbie In-Reply-To: <gavo67$ops$1@registered.motzarella.org> References: <gavjfd$mvd$1@registered.motzarella.org> <mailman.1261.1221809756.3487.python-list@python.org> <gavo67$ops$1@registered.motzarella.org> Message-ID: <48D3660E.5050902@timgolden.me.uk> Mladen Gogala wrote: > Steve Holden wrote: > >> No. Python implicitly dereferences all names when using them to compute >> values, and only uses them as references on the left-hand side of an >> assignment. >> >> Please note the above statement is contentious, and will likely bring a >> horde of screaming fanatics of various flavors down on my head for >> terminological inexactitude. > > Actually, I am not a "screaming fanatic". I just want to learn. I'm sure Steve can speak for himself, but just to clarify: the "screaming fanatics" referred to are those within the Python community whose opinions of the terminology used are at variance with Steve's. I think it was a comment which would mean more to those of us who've seen such terminology-battles come and go over the years. But thanks for introducing yourself anyway. Knowing more about where a poster is coming from never hurts when trying to answer their questions. :) TJG From dadapapa at googlemail.com Sat Sep 13 07:06:32 2008 From: dadapapa at googlemail.com (Harold Fellermann) Date: Sat, 13 Sep 2008 04:06:32 -0700 (PDT) Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> Message-ID: <c31462d9-5117-43ac-ba08-8c8ad40019cb@x35g2000hsb.googlegroups.com> > doesnt sum first construct the list then sum it? > def com(lst): > return sum(x for x in lst) You construct a generator over an existing list in your code. Try sum([x for x in lst]) to see the effect of additional list construction. And while you're at it, try the simple sum(lst). Cheers, - harold - From stephane at harobed.org Mon Sep 8 08:15:15 2008 From: stephane at harobed.org (=?iso-8859-1?q?KLEIN_St=E9phane?=) Date: Mon, 8 Sep 2008 12:15:15 +0000 (UTC) Subject: Where does the command "ls" in some doctest files come from ? Message-ID: <ga350i$m29$1@ger.gmane.org> Hi, for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/ tests.py?rev=89831&view=auto test file, there is this doctests : def develop_verbose(): """ We should be able to deal with setup scripts that aren't setuptools based. >>> mkdir('foo') >>> write('foo', 'setup.py', ... ''' ... from setuptools import setup ... setup(name="foo") ... ''') >>> write('buildout.cfg', ... ''' ... [buildout] ... develop = foo ... parts = ... ''') >>> print system(join('bin', 'buildout')+' -vv'), # doctest: +ELLIPSIS Installing... Develop: '/sample-buildout/foo' ... Installed /sample-buildout/foo ... >>> ls('develop-eggs') - foo.egg-link - zc.recipe.egg.egg-link >>> print system(join('bin', 'buildout')+' -vvv'), # doctest: +ELLIPSIS Installing... Develop: '/sample-buildout/foo' in: '/sample-buildout/foo' ... -q develop -mxN -d /sample-buildout/develop-eggs/... """ I wonder where does the "ls('develop-eggs')" command come from ? It is doctest buildin command ? Where can I found some documentation about that ? I see this page http://docs.python.org/lib/module- doctest.html and I found nothing about that subject. Thanks for your help, Stephane http://docs.python.org/lib/module-doctest.html From uomiocenekidd at gmail.com Mon Sep 22 06:42:09 2008 From: uomiocenekidd at gmail.com (uomiocenekidd at gmail.com) Date: Mon, 22 Sep 2008 03:42:09 -0700 (PDT) Subject: www shockingtube com - Free Message-ID: <4d824670-2bcf-4285-bf80-c0eea0873300@d77g2000hsb.googlegroups.com> www shockingtube com . . . *******CLICK HERE******** http://vids365.cn/www-shockingtube-com ***************************** . . . . . . . . . . . . www shockingtube com From tjreedy at udel.edu Sat Sep 13 02:38:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Sep 2008 02:38:08 -0400 Subject: lacking follow-through In-Reply-To: <289bc58f-6c04-4bce-b393-e9fa0a8c4fee@i20g2000prf.googlegroups.com> References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <mailman.912.1221221819.3487.python-list@python.org> <289bc58f-6c04-4bce-b393-e9fa0a8c4fee@i20g2000prf.googlegroups.com> Message-ID: <gafn4b$eqk$1@ger.gmane.org> Carl Banks wrote: > I'm surprised there is anyone who still gives castironpi credit for > being fully human. His recent posts have generally been quite different from those of some months ago. Even he recognizes that they were somewhat weird and has tried to do better. Did he ever make any degrading attacks on people like the above, to deserve receiving such? This reminds me of my elementary school, where people who made social mistakes were sometimes never allowed to recover but were dumped on for years. tjr From gslindstrom at gmail.com Thu Sep 18 13:56:24 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Thu, 18 Sep 2008 12:56:24 -0500 Subject: PyCon 2009 (US) - Call for Tutorials Message-ID: <a9f39a410809181056k6426f5bg7eb0b950df0ee008@mail.gmail.com> *Pycon 2009 (US) ? Call for Tutorials* The period for submitting tutorial proposals for Pycon 2009 (US) is now open and will continue through Friday, October 31th. This year features two "pre-conference" days devoted to tutorials on Wednesday March 25 & Thursday March 26 in Chicago. This allows for more classes than ever. Tutorials are 3-hours long on a specific topic of your choice. Last year we featured classes on Learning Python, Web Development, Scientific Computing, and many more. Class size varied from 10 to over 60 students. The extended time spent in class allows teachers to cover a lot of material while allowing for interaction with students. The full Call for Tutorial Proposals, including submission details, an example proposal as well as a template, is available at < http://us.pycon.org/2009/tutorials/proposals/>. Tutorial selections will be announced in early December to give you time to prepare your class. PyCon will compensate instructors US$1,500 per tutorial. If you have any questions, please contact pycon-tutorials at python.org. Greg Lindstrom Tutorial Coordinator, PyCon 2009 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/4ecaf6ff/attachment-0001.html> From castironpi at gmail.com Wed Sep 10 14:59:35 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 10 Sep 2008 11:59:35 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> Message-ID: <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> On Sep 10, 5:24?am, Steven D'Aprano <ste... at REMOVE.THIS.cybersource.com.au> wrote: > On Wed, 10 Sep 2008 09:26:20 +0200, Fredrik Lundh wrote: > > Steven D'Aprano wrote: > > >> You've created a solution to a problem which (probably) only affects a > >> very small number of people, at least judging by your use-cases. Who > >> has a 4GB XML file > > > Getting 4GB XML files from, say, logging processes or databases that can > > render their output as XML is not that uncommon. ?They're usually > > record-oriented, and are intended to be processed as streams. ?And given > > the right tools, doing that is no harder than doing the same to a 4GB > > text file. > > Fair enough, that's a good point. > > But would you expect random access to a 4GB XML file? If I've understood > what Castironpi is trying for, his primary use case was for people > wanting exactly that. > > -- > Steven Steven, Are you claiming that sequential storage is sufficient for small amounts of data, and relational db.s are necessary for large amounts? It's possible that there is only the fringe exception, in which case 'alloc/free' aren't useful in the majority of cases, and will never win customers away from the more mature competition. Regardless, it is an elegant solution to the problem of storing variable-length strings, with hardly any practical value. Perfect for grad school. From robin at alldunn.com Mon Sep 29 23:42:42 2008 From: robin at alldunn.com (Robin Dunn) Date: Mon, 29 Sep 2008 20:42:42 -0700 Subject: ANN: wxPython 2.8.9.1 Message-ID: <48E1A032.1080909@alldunn.com> Announcing ---------- The 2.8.9.1 release of wxPython is now available for download at http://wxpython.org/download.php. This release adds a quick fix for a compatibility problem with Python 2.4. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit and 64-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. In most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From tjreedy at udel.edu Mon Sep 22 19:29:38 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 19:29:38 -0400 Subject: A bit weird dictionary behavior In-Reply-To: <gb957i$ja0$1@news.lublin.pl> References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> <gb957i$ja0$1@news.lublin.pl> Message-ID: <gb99oo$ni2$1@ger.gmane.org> Grzegorz Staniak wrote: > On 22.09.2008, Carl Banks <pavlovevidence at gmail.com> wroted: >>> Some would argue (and some did by the time Python grew a 'bool' type) >>> that what is wrong is to have a bool type in a language that already >>> have a wider definition of the truth value of an expression... >> And some would argue that it was wrong to have such a wide definition >> for the truth value of an expression in the first place... An alternate viewpoint is that only True and False 'have' a truth value. So whenever the interpreter *needs* a truth value for conditional and logical operations, and it has something else, it implicitly calls bool(ob) to get one. This, or possibly a shortcut version thereof, is what a Python interpreter effectively does. From this viewpoint, objecters would instead have to argue that it is wrong to have such implicit calls and that programmers should have to put them in explicitly. > Just out of idle curiosity, what could be the alternatives? Not to evaluate > e.g. strings to "true"? Aren't such conventions as "whatever is not empty, > is 'true'" popular in dynamic langauges? I do not know what is popular, but implicit bool call are darn handy. tjr From tjreedy at udel.edu Sun Sep 21 15:22:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 Sep 2008 15:22:42 -0400 Subject: Why are "broken iterators" broken? In-Reply-To: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: <gb66to$ski$1@ger.gmane.org> Steven D'Aprano wrote: > According to the Python docs, once an iterator raises StopIteration, it > should continue to raise StopIteration forever. Iterators that fail to > behave in this fashion are deemed to be "broken": > > http://docs.python.org/lib/typeiter.html > > I don't understand the reasoning behind this. As I understand it, an > iterator is something like a stream. There's no constraint that once a > stream is empty it must remain empty forever. It is quite possible that a stream reader will return '' on one call and then something non-empty the next. An iterator that reads a stream and yields chunks of whatever size should either block until it gets sufficient data or yield nulls as long as the stream is open and not raise StopIteration until the steam is closed and it has yielded the last chunk of data. > Can somebody explain why "broken iterators" are broken? There is an important different between a store that is closed until the next day and one that closed - out of business. Similarly, there is a difference between an item being out-of-stock until the next delivery and out-of-stock and discontinued permanently, or between a road closed for repairs versus removal for something else. Using the same sign or signal for temporary and permanent conditions is confusing and therefore 'broken'. Terry Jan Reedy From fredrik at pythonware.com Fri Sep 12 11:18:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 17:18:06 +0200 Subject: setattr in class In-Reply-To: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <gae17g$ve0$1@ger.gmane.org> Bojan Mihelac wrote: > Hi all - when trying to set some dynamic attributes in class, for > example: > > class A: > for lang in ['1', '2']: > exec('title_%s = lang' % lang) #this work but is ugly > # setattr(A, "title_%s" % lang, lang) # this wont work > > setattr(A, "title_1", "x") # this work when outside class > > print A.title_1 > print A.title_2 > > I guess A class not yet exists in line 4. Is it possible to achive > adding dynamic attributes without using exec? Move the for-in loop out of the class definition: >>> class A: ... pass ... >>> for lang in ['1', '2']: ... setattr(A, "title_%s" % lang, lang) >>> a = A() >>> a.title_1 '1' A truly dynamic solution (using __getattr__ and modification on access) would probably give you a more "pythonic" solution. </F> From gagsl-py2 at yahoo.com.ar Wed Sep 10 03:50:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 10 Sep 2008 04:50:18 -0300 Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> Message-ID: <op.ug89d4qyx6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 09 Sep 2008 16:38:54 -0300, Sam <samslists at gmail.com> escribi?: > I'm using urllib2 and accepting gzip and deflate. > > It turns out that almost every site returns either normal text or > gzip. But I finally found one that returns deflate. > > Here's how I un-gzip: > compressedstream = StringIO.StringIO(data) > gzipper = gzip.GzipFile(fileobj=compressedstream) > data = gzipper.read() > > Un-gzipping works great! > > Here's how I un-deflate (inflate??) > data = zlib.decompress(data) > > Un-deflating doesn't work. I get "zlib.error: Error -3 while > decompressing data: incorrect header check" > > I'm using python 2.5.2. Can someone tell me exactly how to handle > deflated web pages? zlib.decompress should work - can you provide a site that uses deflate to test? -- Gabriel Genellina From deets at nospam.web.de Wed Sep 3 02:59:31 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 08:59:31 +0200 Subject: Pass same parameter in Recursive function In-Reply-To: <b94b2a5c-8231-4ab9-a2ef-cf3f1bdd8460@o40g2000prn.googlegroups.com> References: <c5bc9de5-6195-4592-8278-7597e75ed9d0@r15g2000prd.googlegroups.com> <mailman.406.1220414283.3487.python-list@python.org> <b94b2a5c-8231-4ab9-a2ef-cf3f1bdd8460@o40g2000prn.googlegroups.com> Message-ID: <6i6qujFoj5a2U1@mid.uni-berlin.de> Davy schrieb: > On Sep 3, 11:57 am, "Chris Rebert" <c... at rebertia.com> wrote: >> Assuming the function is tail-recursive or the "unchanging" arguments >> are immutable, just use a closure: > [SNIP] > Hi Chris, > > Thank you :) > Perhaps I should clarify the problem. > 1. the function is NOT tail-recursive > 2. Yes, the arguments are immutable after I call the function the > first time. > > I think the best description of the problem may be: > How to keep some argument constant and accessable in one function > (especially, recursive function). We know that we can use something > like self.parameter to keep the parameter constant and accessable in > one class. The same way chris showed you - using a closure, you can capture variables outside, and only pass the changing params. The tail-recursion property isn't needed for that. Diez From vinay_sajip at yahoo.co.uk Mon Sep 1 09:52:52 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Mon, 1 Sep 2008 06:52:52 -0700 (PDT) Subject: logging - how to use in a library? References: <6hj2ggFmbgutU1@mid.individual.net> <e39b6fce-12b2-4583-92dc-9bf63355214f@l42g2000hsc.googlegroups.com> <6hkoi3Fmf6nvU1@mid.individual.net> <54e99587-0875-4317-bcf4-52130b70f58c@k13g2000hse.googlegroups.com> <6hra0cFno0v3U1@mid.individual.net> Message-ID: <7e72db94-66b7-4425-b30d-e07006a47cb1@m3g2000hsc.googlegroups.com> On Aug 29, 11:02 pm, Thomas Heller <thel... at python.net> wrote: > > BTW: Let me say that the more I useloggingthe more I like it.loggingis a fantastic package! > Thank you, I can say the same for ctypes and py2exe :-) Regards, Vinay Sajip From jaime.dyson at gmail.com Fri Sep 5 02:27:55 2008 From: jaime.dyson at gmail.com (jaime.dyson at gmail.com) Date: Thu, 4 Sep 2008 23:27:55 -0700 (PDT) Subject: "Full" element tag listing possible with Elementtree? Message-ID: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Hello all, I have the unenviable task of turning about 20K strangely formatted XML documents from different sources into something resembling a clean, standard, uniform format. I like Elementtree and have been using it to step through the documents to get a feel for their structure. .getiterator() gives me a depth-first traversal that eliminates the hierarchy of the elements. What I'd like is to be able to traverse elements while keeping track of ancestors, and print out the full structure of all of an ancestor's nodes as I arrive at each node. So, for example, if I had a document that looked like this: <a> <b att="atttag" content="b"> this is node b </b> <c> this is node c <d /> <e> this is node e </e> </c> <f> this is node f </f> </a> I would want to print the following: <a> <a> <b> <a> <b> text: this is node b <a> <c> <a> <c> text: this is node c <a> <c> <d> <a> <c> <e> <a> <c> <e> text: this is node e <a> <f> <a> <f> this is node f Is there a simple way to do this? Any help would be appreciated. Thanks.. From thomas.hilbert at gmail.com Mon Sep 15 06:04:40 2008 From: thomas.hilbert at gmail.com (Pretorien) Date: Mon, 15 Sep 2008 03:04:40 -0700 (PDT) Subject: objet COM et ms Word Message-ID: <245dc065-660f-4dfe-8134-14b4acfc1f2d@j22g2000hsf.googlegroups.com> Bonjour @ tous, je voudrais gerer des doc Word avec python. Y aurai-uil une doc quelque part bien faites ??? Pour le moment je fais : import win32com.client word = win32com.client.Dispatch('Word.Application') en suite j'ouvre VBexpress pour connaitre qu'elle fonction appeler: par ex: Dim wrdApp As Word.Application Set wrdDoc = wrdApp.Documents.Open("\Exemple.doc") donc en python cela donnerai word.Documents.Open("toto.doc") et ainsi de suite .... Y a t il quelque de bien faits pour python, de mani?re a ne pas avoir a g?rer et VB d'un cote pour deviner les fonctions ? appeler en python. Merci par avance, Crdt, Thomas From python.list at tim.thechases.com Thu Sep 18 08:57:16 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 18 Sep 2008 07:57:16 -0500 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <48D2502C.4000200@tim.thechases.com> > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? [snip] > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > but no improvements. It's like rearranging deck-chairs on the Titanic :) Yes, it may give a speed up, but what's 3 seconds when you're waiting 15hr :) Not knowing the len(IN[x].coordinates) or their structure, if it's a list of len==2, you should be able to just do if i <> j and IN[i].coordinates == IN[j].coordinates or if i <> j and IN[i].coordinates[:2] == IN[j].coordinates[:2] However, again, this is just polish. The big problem is that you have an O(N^2) algorithm that's killing you. 1) use xrange instead of range to save eating memory with a huge unneeded array. 2) unless you need to append duplicate labels, you know that when I and J are swapped, you'll reach the same condition again, so it might be worth writing the outer loops to eliminate this scenario, and in the process, but just starting at i+1 rather than i, you can forgo the check if "i<>j". Such changes might look something like for i in xrange(len(IN)): for j in xrange(i+1, len(IN)): if IN[i].coordinates == IN[j].coordinates: SN.append(IN[i].label) If my college algorithms memory serves me sufficiently, this reduces your O(N^2) to O(N log N) which will garner you some decent time savings. -tkc From adam.dziendziel at gmail.com Thu Sep 25 06:09:52 2008 From: adam.dziendziel at gmail.com (Adam Dziendziel) Date: Thu, 25 Sep 2008 03:09:52 -0700 (PDT) Subject: [OT] Looking for developers: platform for fast and effective learning Message-ID: <e3e43408-803b-455a-aed5-13f0cded27c4@2g2000hsn.googlegroups.com> Hello everybody, I'm working on a website for fast and effective learning using spaced repetition technique. This is the same method used in SuperMemo, Mnemosyne, FullRecall or Anki software. I'd want to create an online version, supporting easy adding of own material and sharing with others. The method is very effective and is great for learning foreign language, learning to exams etc. I wonder that there is no such site running already. There is SuperMemo.net, but it is a typical commercial application, oriented for selling commercial courses. I would like to put on building community, collaboration in writing material and social learning. I'm looking for ambitious people, who want to take part in this undertaking. I can offer revenue share, if the project succeed. Technologies: Python (Pylons) + JavaScript (Ext JS) I have a working base in Pylons and Ext JS but we can consider changing tools. Best regards, Adam Dziendziel adam (dot) dziendziel (at) gmail (dot) com From sri_annauni at yahoo.co.in Thu Sep 4 11:27:25 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 4 Sep 2008 20:57:25 +0530 (IST) Subject: Directory creation Message-ID: <275302.58315.qm@web7908.mail.in.yahoo.com> Can someone tell me is there any module available to create directories?? I tried os, tempfile. I was facing some issues with os.mkdir(). The mode setting was not proper with this method. I created the directory 'stdin' with '0700' mode using os.mkdir() method. $> ls -alR stdin/ stdin/: total 12 drwx--S---?? 2 munisams munisams 4096 Sep? 3 02:00 . What is that 'S' in the group permission field?? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From jukka.aho at iki.fi Tue Sep 2 18:53:34 2008 From: jukka.aho at iki.fi (Jukka Aho) Date: Wed, 3 Sep 2008 01:53:34 +0300 Subject: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0 References: <pD5vk.59354$_03.18175@reader1.news.saunalahti.fi> <48bd6b4e$0$17174$742ec2ed@news.sonic.net> Message-ID: <Qtjvk.59899$_03.45068@reader1.news.saunalahti.fi> John Nagle wrote: > Python 5 is even stricter. Only ASCII (chars 0..127) can be sent > to standard output by default. Python 5? (I guess I haven't been following these things enough...) Well, I would sure hope not. -- znark From skip at pobox.com Tue Sep 9 07:06:20 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 Sep 2008 06:06:20 -0500 Subject: How to record audio from Python on Mac? Message-ID: <18630.22700.810611.193049@montanaro-dyndns-org.local> (I asked this on pythonmac-sig a couple days ago but got no response, so I'm casting a broader net.) Can I easily control audio record/playback from Python on my Mac? I know zip about audio recording or about Apple APIs via Python. Pointers to simple examples would be much appreciated. Thanks, Skip From dmitry at athabascau.ca Thu Sep 25 14:22:11 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 18:22:11 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> <48db50aa$0$3750$426a74cc@news.free.fr> <HoOCk.1756$Pv5.1315@edtnps83> <48dbc82e$0$1120$426a74cc@news.free.fr> <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> Message-ID: <nFQCk.1781$Pv5.1597@edtnps83> Aaron "Castironpi" Brady wrote: > You should write it like this: > > class B(object): > @A.proxy > def bmethod(self,a): > > Making 'proxy' a class method on A. makes sense. > In case different A instances (do > you have more than one BTW?) yep. I have multiple instances of class A, each one has properties (one per class) of classes B, C and D: class A: b=None c=None d=None def __init__(self,b,c,d): self.b=b self.c=c self.d=d ...magic with proxying methods goes here... class B: def bmethod(self,x): pass # we proxy this method from A def bmethod2(self,x): pass # this is not proxied class C: def cmethod(self,x): pass # we proxy this method from A class D: def dmethod(self,x): pass # we proxy this method from A a=A(B(),C(),D()) x='foo' a.bmethod(x) a.cmethod(x) a.dmethod(x) a.bmethod2(x) # raises error as we shouldn't proxy bmethod2 above is the ideal scenario. > What you've said implies that you only have one B instance, or only > one per A instance. Is this correct? yes. as per above code. > I agree that __setattr__ is the canonical solution to proxy, but you > have stated that you want each proxied method to be a member in the > proxy class. well. kind of. if I can make it transparent to the consumer so that he shouldn't do: a.b.bmethod(x) but rather: a.bmethod(x) As I'm trying to keep b, c and d as private properties and would like to filter which calls are allowed to those. Plus proxied methods in either one always expect certain parameters like: class B: def bmethod(self,c,x): pass and A encapsulates 'c' already and can fill in that blank automagically: class A: c=None b=None def bmethod(self,c,x): if not c: c=self.c b.bmethod(self,c,x) I kept this part of the problem out of this discussion as I'm pretty sure I can fill those in once I figure out the basic problem of auto-population of proxy methods since for each class/method those are going to be nearly identical. If I can autogenerate those on-the-fly I'm pretty sure I can add some extra-logic to them as well including signature change where A::bmethod(self,c,x) would become A::bmethod(self,x) etc. From castironpi at gmail.com Tue Sep 23 21:55:25 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 18:55:25 -0700 (PDT) Subject: how to keep a window above all other OS windows? References: <e03ba1b5-c120-45a3-bf27-640f86c35754@2g2000hsn.googlegroups.com> <62cc640e-3526-49f9-ba10-22ff31f094e1@e39g2000hsf.googlegroups.com> Message-ID: <62cb5b79-e5f4-4437-88f0-1a0c051134b7@l64g2000hse.googlegroups.com> On Sep 23, 3:34?pm, dmitrey <dmitrey.kros... at scipy.org> wrote: > On Sep 23, 11:21?pm, dmitrey <dmitrey.kros... at scipy.org> wrote: > > > Hi all, > > how to keep a Tkinter window above all other OS windows (i.e. > > including those ones from other programs)? > > > Thank you in advance, > > Dmitrey > > I have put [Tkinter] into topic of my message but somehow it has been > removed. > D. If you can get the handle of the window from the Tk framework, use the os call in 'ctypes'. Windows' call is ShowWindow( handle, HWND_TOPMOST ) I think. From timr at probo.com Fri Sep 12 23:33:20 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 13 Sep 2008 03:33:20 GMT Subject: universal unicode font for reportlab References: <ga6loq$jpj$1@rumours.uwaterloo.ca> <mailman.785.1221053660.3487.python-list@python.org> <Xns9B159F78E43Dduncanbooth@127.0.0.1> <r7bhc4hd6lh6539kqkmo8klgoua70sjhrn@4ax.com> <Xns9B165B8F730E4duncanbooth@127.0.0.1> Message-ID: <0qcmc4h92n4cbrijk8dju7i4d86ep0m7m9@4ax.com> Duncan Booth <duncan.booth at invalid.invalid> wrote: > >The not too scientific test I did was to copy the font embedding example >from the Reportlab documentation, modify it enough to make it actually >run, and then change the output to have only one glyph. The resulting >PDF is virtually identical. I'm not a reportlab expert though so I may >have made some blindingly obvious beginners mistake (or maybe it only >subsets fonts over a certain size or glyphs outside the ascii range?). > >---------- rlab.py ------------ >import os, sys >import reportlab >folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts' >afmFile = os.path.join(folder, 'LeERC___.AFM') >pfbFile = os.path.join(folder, 'LeERC___.PFB') >from reportlab.pdfbase import pdfmetrics >justFace = pdfmetrics.EmbeddedType1Face(afmFile, pfbFile) >faceName = 'LettErrorRobot-Chrome' # pulled from AFM file >pdfmetrics.registerTypeFace(justFace) >justFont = pdfmetrics.Font('LettErrorRobot-Chrome',faceName,'WinAnsiEncoding') OK, look the other way while I backpedal furiously. The conversation on the mailing last year was focused on TrueType fonts. Those are subsetted. EmbeddedType1Face, used for Type 1 fonts, does appear to embed the entire font. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From mhostetl at otaku.freeshell.org Sun Sep 7 09:00:19 2008 From: mhostetl at otaku.freeshell.org (Mike Hostetler) Date: Sun, 7 Sep 2008 13:00:19 +0000 (UTC) Subject: Error importing mxTidy Message-ID: <ga0j93$gnh$1@chessie.cirr.com> I built and installed mx-experimental 3.0.0 from source and it seemed to go fine. But when I try to import it, I get this: localhost% python -c "import mx.Tidy" Traceback (most recent call last): File "<string>", line 1, in ? File "mx/Tidy/__init__.py", line 7, in ? from Tidy import * File "mx/Tidy/Tidy.py", line 7, in ? from mxTidy import * File "mx/Tidy/mxTidy/__init__.py", line 7, in ? from mxTidy import * ImportError: No module named mxTidy This seems strange to me, since it found the mx.Tidy module but not the mxTidy module underneath it. But I guess I don't know how the mx-experimental classes are put together, so I can't really guess what is happening. Thus I am posting here. :) -- mhostetl at sdf.lonestar.org SDF Public Access UNIX System - http://sdf.lonestar.org From sjmachin at lexicon.net Mon Sep 15 16:47:24 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 15 Sep 2008 13:47:24 -0700 (PDT) Subject: append on lists References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> Message-ID: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> On Sep 16, 6:45?am, Armin <a... at nospam.org> wrote: > Yes, but this is very unconvenient. > If d should reference the list a extended with a single list element > you need at least two lines > > a.append(7) > d=a > > and not more intuitive d = a.append(7) Methods/functions which return a value other than the formal None and also mutate their environment are "a snare and a delusion". Don't wish for them. Inconvenient? How often do you want to mutate a list and then set up another reference to it? From mishok13 at gmail.com Thu Sep 18 08:13:58 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Thu, 18 Sep 2008 15:13:58 +0300 Subject: XML Processing In-Reply-To: <484487154510621532@unknownmsgid> References: <484487154510621532@unknownmsgid> Message-ID: <192840a00809180513v68827517lf037326b768515a5@mail.gmail.com> 2008/9/18 Robert Rawlins <robert.rawlins at thinkbluemedia.co.uk>: > Guys, > > > > I'm running python 2.5 and currently using ElementTree to perform my XML > parsing and creation. ElementTree really is a great package for doing this, > however, I've been tasked by our deployment guys to try and move away from > external libraries where possible as it makes their job easier. > > > > Simple question I suppose to start with, does Python have any inbuilt XML > processing modules? If the answer is no then I'll stick with eTree, if > python does have one, then I'll look at some migration steps. > ElementTree is not an external package starting from Python 2.5. It's in stdlib under 'xml.etree.ElementTree' name. There's also a lot of other XML processing modules in stdlib's 'xml' package. > > > Many thanks All, > > > > Robert > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From stefan_ml at behnel.de Thu Sep 4 03:12:27 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 04 Sep 2008 09:12:27 +0200 Subject: python/xpath question.. In-Reply-To: <mailman.441.1220474224.3487.python-list@python.org> References: <mailman.441.1220474224.3487.python-list@python.org> Message-ID: <48bf8a5c$0$10095$9b4e6d93@newsspool3.arcor-online.net> Hi, you should really read about XPath. There are also newsgroups specifically for this topic, please use them. bruce wrote: > in my python, i'm using the xpath function to iterate/parse some html. i can > do something like > > s=d.xpath("//tr/td/text()") > count=len(s) > > and get the number of nodes that have text That is a wrong assumption. It will give you the number of text nodes, not the number of elements. They may or may not be the same. > i can then do something like > s=d.xpath("//tr/td") > count2=len(s) > > and get the number of total nodes... > by subtracting, i can get the number of nodes, without text.. is there an > easier way??!! Yes, learn to use XPath, e.g. //tr/td[not string()] Stefan From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 9 04:35:11 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 10:35:11 +0200 Subject: finding the parent class (not superclass) of the currently executing method derived from a Borg class In-Reply-To: <dc58489b-e114-4d0f-ad49-9011128d0467@b38g2000prf.googlegroups.com> References: <dc58489b-e114-4d0f-ad49-9011128d0467@b38g2000prf.googlegroups.com> Message-ID: <48c634bd$0$25187$426a74cc@news.free.fr> seanacais a ?crit : > I want to create a class derived from a Borg class that can > instantiated as part of a script or be contained in other classes. > When methods from the Borg class are called, I would like to know the > name of the class that contains the Borg class. > I've played a bit with inspect and _getframe from the sys module but > get inconsistent results. The main problem is if the Borg class is > instantiated outside a containing class, then I need to go up a > different number of stack frames. But this information isn't > available till after I've run out of stack frames. The simplest solution is usually the better : explicitely pass the caller (whether instance or module or whatever you want) > Hopefully the following code better describes what I'm looking to do. > > import sys > > class Borg: > _shared_state = {} > def __init__(self): > self.__dict__=self._shared_state > > class Assimilated(Borg): > valueByCaller = {} You understand that, being a class attribute, valueByCaller won't be part of the Borg's _shared_state ? > def __init__(self, setupvalue): > print "In Assimilated.__init__()" > print "setupvalue is: " + str(setupvalue) > > # would like key to be name of class (or module) that > # contins Assimilated > callerID = sys._getframe(1).f_code.co_name > > self.valueByCaller[callerID] = setupvalue > > print self.valueByCaller Anyway, since you override __init__ and don't call Borg.__init__, your Assimilated class doesn't behave as a Borg. (snip) > > When I run this, I get the following output: > > In Assimilated.__init__() > setupvalue is: 2 > {'A': 2} > In Assimilated.__init__() > setupvalue is: 3 > {'A': 2, 'B': 3} > In Assimilated.__init__() > setupvalue is: 4 > {'A': 2, 'C': 4, 'B': 3} > (snip) > > What I found most peculiar when I started this was that the > valueByCaller dictionary was completely populated before the __init__ > method of a was executed. Indeed. In classes A, B and C, assim_object is class attribute - so it is instanciated when the class statement is executed. > I'm pretty sure that this has to do with > the difference between when the object gets instanced and when it gets > initialized, Not at all. It has to do with the fact that all statements within a class block are executed before the class statement itself is executed. And since your class statements are at the top-level, they are executed when the module is initialised (that is, passed to the python runtime or first imported). > but I need to do some more research and reading to be > able to explain it to myself. Indeed. May I suggest that you *learn* Python's object model and Python's execution model instead of assuming anything ? This will save you a whole lot of time and frustration !-) From blabla at dungeon.de Thu Sep 11 11:52:33 2008 From: blabla at dungeon.de (hofer) Date: Thu, 11 Sep 2008 08:52:33 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> <slrngchjno.i8e.nick@irishsea.home.craig-wood.com> Message-ID: <f3871e0a-e76f-4bbd-ae14-5e8146071802@f63g2000hsf.googlegroups.com> On Sep 11, 10:36?am, Nick Craig-Wood <n... at craig-wood.com> wrote: >I'd type the explicit > > v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > Either is only a couple more > characters to type. ?It is completely > explicit and comprehensible to everyone, in comparison to > > ? v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > ? v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars > > Unlike perl, it will also blow up if mydict doesn't contain 'one' > which may or may not be what you want. > Is your above solution robust against undefined keys. In my example it would'nt be a problem. The dict would be fully populated, but I'm just curious. From jukka.aho at iki.fi Tue Sep 2 03:09:21 2008 From: jukka.aho at iki.fi (Jukka Aho) Date: Tue, 2 Sep 2008 10:09:21 +0300 Subject: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0 Message-ID: <pD5vk.59354$_03.18175@reader1.news.saunalahti.fi> Just a tip for those who are only just cutting their teeth on Python 3.0 and might have encountered the same problem as I did: When a Python (3.x) program is run on a terminal that only supports a legacy character encoding - such as Latin 1 or Codepage 437 - all characters printed to stdout will be automatically converted from the interpreter's internal Unicode representation to this legacy character set. This is a nice feature to have, of course, but if the original Unicode string contains characters for which there is no equivalent in the terminal's legacy character set, you will get the dreaded "UnicodeEncodeError" exception. In other words, the "sys.stdout" stream - as well as the "sys.stderr" stream - have both been hardwired to do their character encoding magic, by default, using the 'strict' error handling scheme: --- 8< --- >>> import sys >>> sys.stdout.errors 'strict' >>> sys.stderr.errors 'strict' --- 8< --- So, essentially, printing out anything but ASCII to stdout is not really safe in Python... unless you know beforehand, for sure, what characters the terminal will support - which at least in my mind kind of defeats the whole purpose of those automatic, implicit conversions. Now, I have written a more flexible custom error handler myself and registered it with Python's codec system, using the codecs.register_error() function. When the handler encounters a problematic codepoint, it will either suggest a "similar-enough" Latin 1 or ASCII substitution for it, or if there is none available in its internal conversion table, it will simply print it out using the U+xxxx notation. The "UnicodeEncodeError" exception will never occur with it. Instead of creating a custom error handler from scratch one could also make use of one of Python's built-in, less restrictive error handlers, such as 'ignore', 'replace', 'xmlcharrefreplace', or 'backslashreplace'. But in order to make things work as transparently and smoothly as possible, I needed a way to make both the "sys.stdio" and "sys.stderr" streams actually _use_ my custom error handler, instead of the default one. Unfortunately, the current implementation of io.TextIOWrapper (in Python 3.0b2, at least) does not yet offer a public, documented interface for changing the codec error handler - or, indeed, the target encoding itself - for streams that have already been opened, and this means you can't "officially" change it for the "stdout" or "stderr" streams, either. (The need for this functionality is acknowledged in PEP-3116, but has apparently not been implemented yet. [1]) So, after examining io.py and scratching my head a bit, here's how one can currently hack one's way around this limitation: --- 8< --- import sys sys.stdout._errors = 'backslashreplace' sys.stdout._get_encoder() sys.stderr._errors = 'backslashreplace' sys.stderr._get_encoder() --- 8< --- Issuing these commands makes printing out Unicode strings to a legacy terminal a safe procedure again and you're not going get unexpected "UnicodeEncodeErrors" thrown in your face any longer. (Note: 'backslashreplace' is just an example here; you could substitute the error handler of your choice for it.) The downside of this solution is, of course, that it will break down if the private implementation of io.TextIOWrapper in io.py changes in the future. But as a workaround, I feel it is sufficient for now, while waiting for the "real" support to appear in the library. (If there's a cleaner and more future-proof way of doing the same thing right now, I'd of course love to hear about it...) _____ 1. http://mail.python.org/pipermail/python-3000/2008-April/013366.html -- znark From steven at REMOVE.THIS.cybersource.com.au Tue Sep 30 04:52:11 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 08:52:11 GMT Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> Message-ID: <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: > In message <gbr4ks$1vv$1 at aioe.org>, r0g wrote: > >> You can only distribute modifications to gnuplot itself as patches, but >> you can distribute it freely ... > > This must be some new definition of "freely" of which I'm unaware. You're free to distribute the official release of gnuplot. You're free to distribute patches to gnuplot. You're even free to provide people with a script or program to apply those patches to gnuplot. Where's the non-free bit? Personally, I don't get the whole "only distribute patches" requirement. It's a bit like saying "You're free to distribute this software, but only as a tarball". It seems silly to me. But I don't see it as non-free, except in the sense that "only licences approved by the FSF are free". -- Steven From Ron.Barak at lsi.com Sun Sep 14 09:44:03 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Sun, 14 Sep 2008 14:44:03 +0100 Subject: Representation of python code ? Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Hi Guys, Is there a script/application, which gets as input python code, and produces a (graphic) representation of the inter-relationships between its classes/functions ? Bye, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080914/3c36f58a/attachment-0001.html> From brtzsnr at gmail.com Fri Sep 5 08:49:48 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Fri, 5 Sep 2008 05:49:48 -0700 (PDT) Subject: derived classes and __getattr__ References: <d5a86bf2-2b8c-487f-9097-51bc92ef478d@w24g2000prd.googlegroups.com> <g9qrmh$k62$02$1@news.t-online.com> <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> <g9r0ns$1js$01$1@news.t-online.com> Message-ID: <12c58ddc-5d45-4323-b268-6815fe5cb86d@z6g2000pre.googlegroups.com> On Sep 5, 1:13?pm, Peter Otten <__pete... at web.de> wrote: > Alexandru ?Mosoi wrote: > > On Sep 5, 11:47?am, Peter Otten <__pete... at web.de> wrote: > >> Alexandru Mo?oi wrote: > >> > i'm facing the following problem: > > >> > class Base(object): > >> > def __getattr__(self, attr): return lambda x: attr + '_' + x > > >> > def dec(callable): > >> > return lambda *args: 'dec_' + callable(*args) > > >> > class Derived(Base): > >> > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have > >> > what_so_ever > >> > mumu = dec(Base.mumu) ? ? ? ? ? ? ? ? ? ? ? ? ?# wrong, base > >> > doesn't have mumu > > >> > any idea how to do this? > > >> __getattr__() is defined in the class to create instance attributes on > >> the fly. If you want class attributes you have to put the __getattr__() > >> method into the class of the class, or "metaclass": > > >> class Base(object): > >> class __metaclass__(type): > >> def __getattr__(self, attr): > >> return lambda self, x: attr + '_' + x > > >> def dec(callable): > >> return lambda *args: 'dec_' + callable(*args) > > >> class Derived(Base): > >> what_so_ever = dec(Base.what_so_ever) > > >> d = Derived() > >> print d.what_so_ever("42") > > >> I don't see how you can turn this into something useful... > > >> Peter > > > 10x. it works. however I have another small problem. now, > > d.third('blah') doesn't work because instance d doesn't have 'third' > > attribute. I was expecting derived class to inherit the metaclass as > > well, but it didn't. > > That has nothing to do with inheritance: > > >>> type(Derived) > > <class 'classattr.__metaclass__'> > > If Python doesn't find an attribute in the instance it looks it up in the > class but not in the metaclass: > > >>> Base.third > > <function <lambda> at 0x2b5f8028aa28>>>> Base().third > > Traceback (most recent call last): > ? File "<stdin>", line 1, in <module> > AttributeError: 'Base' object has no attribute 'third' > > I think you should go back to the drawing board now and look for a simpler > approach to solve your actual problem... > > Peter i somehow fixed the problem using: def __getattr__(self, attr): return functools.partial(Base.__metaclass__.__getattr__(self.__class__, attr), self) however this looks ugly enough to look for another solution. i still have one more question: why do I have to bind self? (without which functions fail expecting an instance) From srikrishnamohan at gmail.com Tue Sep 23 10:02:06 2008 From: srikrishnamohan at gmail.com (km) Date: Tue, 23 Sep 2008 19:32:06 +0530 Subject: improving a huge double-for cycle In-Reply-To: <48D2502C.4000200@tim.thechases.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D2502C.4000200@tim.thechases.com> Message-ID: <f4cc03640809230702i1f3a182q5bb523992d826857@mail.gmail.com> how abt this ? N = len(IN) for k in range(N): for j in range(N): if j >= k: # or k <= j doSomething() KM ~~~~~~~~~~~~~~~ On Thu, Sep 18, 2008 at 6:27 PM, Tim Chase <python.list at tim.thechases.com>wrote: > Code: Select all >> for i in range(len(IN)): #scan all elements of the list IN >> for j in range(len(IN)): >> if i <> j: >> if IN[i].coordinates[0] == IN[j].coordinates[0]: >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> SN.append(IN[i].label) >> >> >> Unfortunately my len(IN) is about 100.000 and the running time about >> 15h !!!! :( >> >> Any idea to improve it? >> > [snip] > >> I have already tried to group the "if statements" in a single one: >> >> Code: Select all >> if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> >> but no improvements. >> > > It's like rearranging deck-chairs on the Titanic :) Yes, it may give a > speed up, but what's 3 seconds when you're waiting 15hr :) > > Not knowing the len(IN[x].coordinates) or their structure, if it's a list > of len==2, you should be able to just do > > if i <> j and IN[i].coordinates == IN[j].coordinates > > or > > if i <> j and IN[i].coordinates[:2] == IN[j].coordinates[:2] > > However, again, this is just polish. The big problem is that you have an > O(N^2) algorithm that's killing you. > > 1) use xrange instead of range to save eating memory with a huge unneeded > array. > > 2) unless you need to append duplicate labels, you know that when I and J > are swapped, you'll reach the same condition again, so it might be worth > writing the outer loops to eliminate this scenario, and in the process, but > just starting at i+1 rather than i, you can forgo the check if "i<>j". > > Such changes might look something like > > for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): > if IN[i].coordinates == IN[j].coordinates: > SN.append(IN[i].label) > > If my college algorithms memory serves me sufficiently, this reduces your > O(N^2) to O(N log N) which will garner you some decent time savings. > > -tkc > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080923/f0fe4a68/attachment-0001.html> From S.Shi at kingston.ac.uk Mon Sep 8 07:08:33 2008 From: S.Shi at kingston.ac.uk (Shi, Shaozhong) Date: Mon, 8 Sep 2008 12:08:33 +0100 Subject: how to use execfile with input parameters Message-ID: <77BBE7D879F90E47886631DD9B2714CD04FF1DB1@KUDBEX01.kuds.kingston.ac.uk> I have a Python script expecting 11 or 12 input parameters. How do I use execfile to execute the Python script in my new Python script? How do I pass in the input parameters? Yours sincerely, David This email has been scanned for all viruses by the MessageLabs Email Security System. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/e0d5d159/attachment-0001.html> From mccredie at gmail.com Fri Sep 26 16:42:27 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 26 Sep 2008 13:42:27 -0700 (PDT) Subject: ConfigParser subclass problem References: <mailman.1560.1222458749.3487.python-list@python.org> Message-ID: <bfb5d375-6455-437f-9560-baef54f19725@w1g2000prk.googlegroups.com> On Sep 26, 12:56?pm, Strato <pyt... at p0w.org> wrote: > Hi folks, > > I think I do something wrong, but I don't see why it doesn't work, so I > will explain: > > I've searched in the list archive and found this thread, that explain > exactly what I want to have: the options strings returned by > ConfigParser without being lower cased. > > I tryed to reproduce this, by subclassing the SafeConfigParser class, > like this: > > * in my main script: > > from MyConfigParser import * > > * in the MyConfigParser.py file: > from ConfigParser import SafeConfigParser > > class MyConfigParser(SafeConfigParser): > ? ? def optionxform(self, optionstr): > ? ? ? ? print "Called the modified version of the class" > ? ? ? ? return optionstr > > then, when I run the script, every time a calls to my own class is done, > the print statment is shown in the console, so this may work, but when I > use the .items() method of the class, I got a lower cased result ! > > (In my test, using the .items() method is my only try to test the new class) > > Does anybody has an idea of what I'm doing wrong ? > > Thanks, > Strato I don't know what you are doing wrong. It works just fine for me: [code] from ConfigParser import SafeConfigParser from StringIO import StringIO class MyConfigParser(SafeConfigParser): def optionxform(self, optionstr): print "Called the modified version of the class" return optionstr def main(): contents = StringIO(""" [Section1] Foo=Bar Bar=Baz Spam=Eggs [Section2] Hello=World """) raw_parser = SafeConfigParser() raw_parser.readfp(contents) print "Using SafeConfigParser Section1" for item in raw_parser.items("Section1"): print item print "Using SafeConfigParser Section2" for item in raw_parser.items("Section2"): print item contents.seek(0) my_parser = MyConfigParser() my_parser.readfp(contents) print print "Using MyConfigParser Section1" for item in my_parser.items("Section1"): print item print "Using MyConfigParser Section2" for item in my_parser.items("Section2"): print item if __name__ == "__main__": main() [/code] Produces the output: Using SafeConfigParser Section1 ('foo', 'Bar') ('bar', 'Baz') ('spam', 'Eggs') Using SafeConfigParser Section2 ('hello', 'World') Called the modified version of the class Called the modified version of the class Called the modified version of the class Called the modified version of the class Using MyConfigParser Section1 ('Foo', 'Bar') ('Bar', 'Baz') ('Spam', 'Eggs') Using MyConfigParser Section2 ('Hello', 'World') Matt From paul.hankin at gmail.com Thu Sep 18 16:03:38 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 18 Sep 2008 13:03:38 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <43c1847e-994b-4569-9fb8-0aac3edf0da9@n38g2000prl.googlegroups.com> On Sep 18, 2:25?pm, Alexzive <zasaconsult... at gmail.com> wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > ? ? for i in range(len(IN)): #scan all elements of the list IN > ? ? ? for j in range(len(IN)): > ? ? ? ? if i <> j: > ? ? ? ? ?if IN[i].coordinates[0] == IN[j].coordinates[0]: > ? ? ? ? ? ?if IN[i].coordinates[1] == IN[j].coordinates[1]: > ? ? ? ? ? ? ? SN.append(IN[i].label) > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > ? ? if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: A simple O(N) algorithm: from collections import defaultdict d = defaultdict(int) for x in IN: d[x] += 1 SN = [x for (x, c) in d.iteritems() if c > 1] -- Paul Hankin From mensanator at aol.com Thu Sep 4 04:28:46 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 4 Sep 2008 01:28:46 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> Message-ID: <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> On Sep 4, 1:26 am, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Wed, 03 Sep 2008 22:20:43 -0700, Mensanator wrote: > > On Sep 3, 8:30 pm, Steven D'Aprano <st... at REMOVE-THIS- > > cybersource.com.au> wrote: > >> On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: > >> >>>> sum([]) > >> > 0 > > >> > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. > >> > It should return None or throw an exception like sum([None,1]) does. > > >> You're wrong, because 99.9% of the time when users leave a blank cell > >> in Excel, they want it to be treated as zero. > > > Then 99.9% of users want the wrong thing. > > It is to laugh. > > > Microsoft knows that this is a bug > > Says you. > > > but refuses to fix it to prevent breaking legacy documents (probably > > dating back to VisiCalc). When graphimg data, a missing value should be > > interpreted as a hole in the graph > > "Graphing data" is not sum(). I don't expect graphing data to result in > the same result as sum(), why would I expect them to interpret input the > same way? > > > +------+ +--+------+------+-----+ > > Why should the graphing application ignore blanks ("missing data"), but > sum() treat missing data as an error? That makes no sense at all. Maybe it's important to know data is missing. You can see the holes in a graph. You can't see the holes in a sum. > > > and not evaluated as 0 > > > And Microsoft provides a workaround for graphs to make 0's appear as > > holes. Of course, this will cause legitimate 0 values to disappear, so > > the workaround is inconsistent. > > I'm not aware of any spreadsheet that treats empty cells as zero for the > purpose of graphing, and I find your claim that Excel can't draw graphs > with zero in them implausible, but I don't have a copy of Excel to test > it. That was a mistake. I made a followup correction, but you probably didn't see it. > > >> Spreadsheet sum() is not the > >> same as mathematician's sum, which doesn't have a concept of "blank > >> cells". (But if it did, it would treat them as zero, since that's the > >> only useful thing and mathematicians are just as much pragmatists as > >> spreadsheet users.) The Excel code does the right thing, and your > >> "pure" solution would do the unwanted and unexpected thing and is > >> therefore buggy. > > > Apparently, you don't use databases or make surface contours. > > Neither databases nor surface contours are sum(). What possible relevance > are they to the question of what sum() should do? Because a sum that includes Nulls isn't valid. If you treated Nulls as 0, then not only would your sum be wrong, but so would your count and the average based on those. Now you can EXPLICITLY tell the database to only consider non-Null values, which doesn't change the total, but DOES change the count. > > Do you perhaps imagine that there is only "ONE POSSIBLE CORRECT WAY" to > deal with missing data, and every function and program must deal with it > the same way? But that's what sum() is doing now, treating sum([]) the same as sum([],0). Why isn't sum() defined such that "...if list is empty, return start, IF SPECIFIED, otherwise raise exception." Then, instead of "ONE POSSIBLE CORRECT WAY", the user could specify whether he wants Excel compatible behaviour or Access compatible behaviour. > > > Contour programs REQUIRE that blanks are null, not 0 > > Lucky for them that null is not 0 then. No, but blank cells are 0 as far as Excel is concerned. That behaviour causes nothing but trouble and I am saddened to see Python emulate such nonsense. > > > so that the Kriging > > algorithm interpolates around the holes rather than return false > > calculations. Excel's treatment of blank cells is inconsistent with > > Access' treatment of Nulls and therefore wrong, anyway you slice it. > > No no no, you messed that sentence up. What you *really* meant was: > > "Access' treatment of Nulls is inconsistent with Excel's treatment of > blank cells and therefore wrong, anyway you slice it." > > No of course not. That would be stupid, just as stupid as your sentence. > Excel is not Access. They do different things. Why should they > necessarily interpret data the same way? Because you want consistent results? > > > Maybe you want to say a bug is when it doesn't do what the author > > intended, but I say if what the intention was is wrong, then a perfect > > implentation is still a bug because it doesn't do what it's supposed to > > do. > > Who decides what it is supposed to do if not the author? The author can't change math on a whim. > You, in your ivory tower who doesn't care a fig for > what people want the software to do? True, I could care less what peole want to do... ...as long as they do it consistently. > > Bug report: "Software does what users want it to do." > Fix: "Make the software do something that users don't want." What the users want doesn't carry any weight with respect to what the database wants. The user must conform to the needs of the database because the other way ain't ever gonna happen. > > Great. If only. But then, I probably wouldn't have a job. > > >> Bugs are defined by "does the code do what the user wants it to do?", > >> not "is it mathematically pure?". > > > ReallY? So you think math IS a democracy? There is no reason to violate > > mathematical purity. > > You've given a good example yourself: the Kriging algorithm needs a Null > value which is not zero. There is no mathematical "null" which is > distinct from zero, so there's an excellent violation of mathematical > purity right there. Hey, I was talking databases, you brought up mathematical purity. > > If I am given the job of adding up the number of widgets inside a box, > and the box is empty, I answer that there are 0 widgets inside it. Right. it has a known quantity and that quantity is 0. Just because the box is empty doesn't mean the quantity is Null. > If I > were to follow your advice and declare that "An error occurred, can't > determine the number of widgets inside an empty box!" people would treat > me as an idiot, and rightly so. Right. But a better analogy is when a new shipment is due but hasn't arrived yet so the quantity is unknown. Now the boss comes up and says he needs to ship 5 widgets tomorrow and asks how many you have. You say 0. Now the boss runs out to Joe's Widget Emporium and pays retail only to discover when he gets back that the shipment has arrived containing 12 widgets. Because you didn't say "I don't know, today's shipment isn't here yet", the boss not only thinks you're an idiot, but he fires you as well. > > > If I don't get EXACTLY the same answer from Excel, > > Access, Mathematica and Python, then SOMEBODY is wrong. It would be a > > shame if that somebody was Python. > > Well Excel, Python agree that the sum of an empty list is 0. What do > Access and Mathematica do? I don't know abaout Mathmatica, but if you EXPLICITLY tell Access to sum only the non-Null values, you'll get the same answer Excel does. Otherwise, any expression that includes a Null evaluates to Null, which certainly isn't the same answer Excel gives. > > >> The current behaviour of sum([]) does the right thing for the 99% of > >> the time when users expect an integer. > > > Why shouldn't the users expect an exception? Isn't that why we have > > try:except? Maybr 99% of users expect sum([])==0, but _I_ expect to be > > able to distinguish an empty list from [4,-4]. > > The way to distinguish lists is NOT to add them up and compare the sums: > > >>> sum([4, -4]) == sum([0]) == sum([1, 2, 3, -6]) == sum([-1, 2, -1]) > > True > > The correct way is by comparing the lists themselves: > > >>> [] == [4, -4] > > False > > >> And the > >> rest of the time, they have to specify a starting value for the sum > >> anyway, and so sum([], initial_value) does the right thing *always*. > > > So if you really want [] to be 0, why not say sum([],0)? > > I don't want [] == 0. That's foolish. I want the sum of an empty list to > be 0, which is a very different thing. In certain circumstances. In others, an empty list summing to 0 is just as foolish. That's why sum([]) should be an error, so you can have it either way. Isn't one of Python's slogans "Explicit is better than implicit"? > > And I don't need to say sum([],0) because the default value for the > second argument is 0. That's the problem. There is no justification for assuming that unknown quantities are 0. > > > Why shouldn't nothing added to nothing return nothing? Having it > > evaluate to 0 is wrong 99.9% of the time. > > It is to laugh. > > What's the difference between having 0 widgets in a box and having an > empty box with, er, no widgets in it? There are no "empty" boxes. There are only boxes with known quantities and those with unknown quantities. I hope that's not too ivory tower. > > -- > Steven From afriere at yahoo.co.uk Tue Sep 16 02:45:36 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 15 Sep 2008 23:45:36 -0700 (PDT) Subject: environment variable issue References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> <mailman.1057.1221505773.3487.python-list@python.org> Message-ID: <0abf9533-9614-4aa4-9402-5bec41eb2b17@q5g2000prf.googlegroups.com> On Sep 16, 5:09 am, Tim Chase <python.l... at tim.thechases.com> wrote: > This is likely the same issue I just posted about here: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > [snip] It's also a bit like a thread I posted to back in August (which dealt with the difference between bash's shell-variable 'HOSTNAME' and environment-variables). http://groups.google.com/group/comp.lang.python/browse_thread/thread/4db6dbd9469adb31/85750e7f2a5c551c#2a038742c95cc28a From sturlamolden at yahoo.no Thu Sep 25 07:16:34 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 04:16:34 -0700 (PDT) Subject: Linq to Python References: <mailman.1493.1222340940.3487.python-list@python.org> Message-ID: <579eb852-031c-4f50-ac64-88ad8d677b05@m73g2000hsh.googlegroups.com> On 25 Sep, 13:08, hrishy <hris... at yahoo.co.uk> wrote: > Pardon my ignorance again but id ont see any join in python or did i miss something ? It's more Pythonic to use the syntax of dictionary lookups. From fredrik at pythonware.com Thu Sep 4 04:47:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 10:47:04 +0200 Subject: use str as variable name In-Reply-To: <48bf9d12$0$7552$426a74cc@news.free.fr> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <mailman.464.1220515161.3487.python-list@python.org> <48bf9d12$0$7552$426a74cc@news.free.fr> Message-ID: <g9o7a9$t11$1@ger.gmane.org> Bruno Desthuilliers wrote: > You wouldn't write something like 2.__add__(3), would you ? Don't give the "it's only OO if I write obj.method(args)" crowd more bad ideas, please ;-) (...as Bruno implies, setattr(), len() et al can be and should be viewed as generic functions. A specific Python implementation may use custom code to implement behaviour for a given object; behaviour that's more efficient than a full Python-level method call. For example, in CPython, len(L) is about twice as fast as L.__len__() for built-in sequences.) </F> From grante at visi.com Tue Sep 16 12:26:38 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 11:26:38 -0500 Subject: literals optimization (was Re: append on lists) References: <gamffv$qms$1@online.de> <mailman.1116.1221574264.3487.python-list@python.org> <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> <mailman.1126.1221581236.3487.python-list@python.org> Message-ID: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> On 2008-09-16, Maric Michaud <maric at aristote.info> wrote: > Le Tuesday 16 September 2008 16:57:26 Grant Edwards, vous avez ?crit?: >> On 2008-09-16, Maric Michaud <maric at aristote.info> wrote: >> > Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit?: >> >> On 2008-09-16, Maric Michaud <maric at aristote.info> wrote: >> >> >> >> > all expressions that return something, return a new object, >> >> >> >> That's not _quite_ true: >> >> >>> a=1 >> >> >>> b=a.__add__(0) >> >> >>> a is b >> >> >> >> True >> >> >> >> ;) >> > >> > This is implementation specific, >> >> Indeed. >> >> > the specification of the language says that it should be >> > false, >> >> That's curious. If so, then the implimentation is in violating >> the specification. > > But it doesn't matter No argument. > as the "is" operator is not relevant for any use case with > scalars and even strings and the optimization is not > negligible. In fact, I'd rather say it's unspecified, each > implementation does it its own way. I was just pointing out that for some degenerate cases in the C-Python implementation, the statement "all expressions that return something, return a new object" is not true. I'm not saying it ought to be true. I'm just saying that if the specification says that, it's a bug (in the specification, IMO). If the specification states that, then either the specification should be changed, or the implementation should be changed. Waving away specification violations with claims of "it doesn't matter" just seems like bad practice. If a requirement doesn't matter, then remove it from the specification. >> Where is that in the specification? > > Each literal creates a new instance, and instances of int are > not supposed to be unique for each value (at less it's not > specified so), so "1 is not 1", but implementation can cache > integers, short strings, to avoid creating an new instance > each time they appear in code. Quite true, but that's not what I was asking. I was asking where in the specification <http://docs.python.org/ref/ref.html> it says that all expressions that return something, return a new object. > jython do this also for integer (see above), but not for strings : > > maric at redflag1 17:33:52:~$ jython > Jython 2.2.1 on java1.6.0_07 > Type "copyright", "credits" or "license" for more information. >>>> a = "aaaa" >>>> a is "aaaa" > 0 > maric at redflag1 17:36:48:~$ ipython > >>>>[1]: a = "aaaa" > >>>>[2]: a is "aaaa" > ...[2]: True > > BTW, I'm talking of Jython 2.2, Jython 2.4, which quite ready I think, can > change his mind as well. > >> I suspect the statement in the specification should only apply >> to mutable objects. > > No, CPython also have a unique empty tuple, but tuple literals > are not cached nor there are compile-time optimization : I don't see how that's material. My suggestion was that the requirement of "returning a new object" only apply to mutable objects, since it's clearly not true for some immutable objects [nor would there be any benefit for it to be so]. The behavior with immutable objects (integers and tuples) is then irrelevent. -- Grant Edwards grante Yow! I didn't order any at WOO-WOO ... Maybe a YUBBA visi.com ... But no WOO-WOO! From digitig at gmail.com Fri Sep 26 12:40:18 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 26 Sep 2008 17:40:18 +0100 Subject: Building truth tables In-Reply-To: <fe872489-3dba-47d1-8639-2ad0f18886cf@a1g2000hsb.googlegroups.com> References: <fe872489-3dba-47d1-8639-2ad0f18886cf@a1g2000hsb.googlegroups.com> Message-ID: <aee48b3c0809260940r6e34e032kb3736c3208ca430d@mail.gmail.com> 2008/9/26 andrea <kerny404 at gmail.com>: > Well I would like to make a little program that given a certain > logical expression gives the complete truth table. > > It's not too difficult in fact, I just have some doubts on how to > design it. > > I thought something like that: > > class Term: > > class Table: > > def and(... > def or(... As a quick and dirty solution, I'd write a function that takes a function as a parameter. Starting with a helper function to separate the bits of an integer into a list of bools: def int_to_bool(i, bits): # Extract the bits of i to a boolean array. # 'bits' is the number of signifcant bits. result = [] for j in range(0, bits): result.append(i & 1) i >>= 1 result.reverse() return result Now I'd define a function such as: def table(f, n): # Calculate a truth table for function f taking n boolean parameters result = [] for i in range(0, math.pow(2, n)): for j in range(0, n): params = int_to_bool(i, n) result.append(params + [(f(*params))]) return result Now you could define the function you want as a separate function, or just use a lambda: table(lambda a, b, c:(a or b) and c, 3) [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]] Each element in the result is the state of the parameters followed by the result of the function. I stress that this is quick and dirty -- I'm sure somebody will be along with something better soon! -- Tim Rowe From lists at cheimes.de Mon Sep 8 18:03:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 09 Sep 2008 00:03:05 +0200 Subject: The difference between __XX__ and XX method In-Reply-To: <f9e39bbc0809081431i309c5de3k7d24a5246ae4a900@mail.gmail.com> References: <f9e39bbc0809081431i309c5de3k7d24a5246ae4a900@mail.gmail.com> Message-ID: <ga47en$7vh$1@ger.gmane.org> AON LAZIO wrote: > Hi, Pythoners. > I would like to know that in some class, it uses __XX__ but in some it > uses only XX > for example, > > class Test: > def __som__(self): > ... > def som(self): > ... > What does "__XX__" make the method different from XX? > Thanks in advance The form __method__ is reserved for internal methods also known as magic methods. In general you must not name your own methods or attributes __XX__ because the core of Python reserves all rights on the __*__ naming schema. Some well know magic methods are __init__, __getattr__, __add__ etc. You can find a complete lists in the Python language reference. Christian From exarkun at divmod.com Tue Sep 30 15:38:16 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 Sep 2008 15:38:16 -0400 Subject: [Tutor] Replacing cmd.exe with custom .py application In-Reply-To: <gbtupe$g7s$1@ger.gmane.org> Message-ID: <20080930193816.29191.2110621876.divmod.quotient.32319@ohm> On Tue, 30 Sep 2008 19:30:55 +0000 (UTC), Lie Ryan <lie.1296 at gmail.com> wrote: >On Tue, 30 Sep 2008 15:09:06 -0400, Ezra Taylor wrote: > >> Is there something similar to /dev/null on Windows? > > >I think it's called nul > >REM This is a batch file (.bat) >echo "This won't show" > NUL > >I'm not sure how to use it in python though. > Check out os.devnull. You can open it and write to it. Jean-Paul From bignose+hates-spam at benfinney.id.au Tue Sep 2 23:14:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 03 Sep 2008 13:14:03 +1000 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: <87hc8xor9g.fsf@benfinney.id.au> Ben Finney <bignose+hates-spam at benfinney.id.au> writes: > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > literals. Another reason in support of spaces (rather than underscores) to separate digit groups: it's the only separator that follows the SI standard for representing numbers: ? for numbers with many digits the digits may be divided into groups of three by a thin space, in order to facilitate reading. Neither dots nor commas are inserted in the spaces between groups of three. <URL:http://www.bipm.org/en/si/si_brochure/chapter5/5-3-2.html#5-3-4> This isn't binding upon Python, of course. However, it should be a consideration in choosing what separator convention to follow. -- \ ?If you ever catch on fire, try to avoid seeing yourself in the | `\ mirror, because I bet that's what REALLY throws you into a | _o__) panic.? ?Jack Handey | Ben Finney From zugnush at gmail.com Wed Sep 3 05:16:03 2008 From: zugnush at gmail.com (zugnush at gmail.com) Date: Wed, 3 Sep 2008 02:16:03 -0700 (PDT) Subject: sys.stdin on windows Message-ID: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> I often grep particular patterns out of large logfiles and then pipeline the output to sort and uniq -c I thought today to knock up a script to do the counting in a python dict. This seems work in linux $ cat count.py #!/usr/bin/env python import sys from collections import defaultdict accumulator=defaultdict(int) for line in sys.stdin.readlines(): accumulator[line.strip()]+=1 print "contents,count" for key in accumulator.keys(): print key,",",accumulator[key] $ cat test | ./count.py contents,count , 1 23 , 1 1 , 1 3 , 2 2 , 2 5 , 3 When I try to run the same thing on windows I get IOError: [Error 9] Bad file descriptor How can I make this more windows friendly? Thanks Neil From gagsl-py2 at yahoo.com.ar Tue Sep 16 00:56:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 01:56:51 -0300 Subject: Decompile python2.5-pyc References: <9DE19AF2-1E2B-4914-BA51-9E230CB238DE@uos.de> Message-ID: <op.uhj5amesx6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 15 Sep 2008 20:57:24 -0300, Manuel Ebert <maebert at uos.de> escribi?: > short story I accidentally wrote rm *.py into my makefile (yes, I am > old-fashioned, and yes, that was very, veeeery stupid) and - bad things > never come alone - my remote backup files are corrupted. To cut a sad > story short: I just kind of lost four months work on my bachelor's > thesis, well almost. I still have the pyc files (and backuped them on > virtually every device I have access to now), but despite intense > googling I couldn't find any free way of decompiling 2.5-code -- there > is depython.net and the online version of decompyle, but they charge > money (which I currently don't have), and the free version of decompyle > can't handle marshal data > 2.3, and I lack the skills necessary to > extend it to 2.5. > > Does anybody know something I don't, some home-brewn decompiler, > anything? I *am* quite desperate... If your code doesn't use too much features post-2.3, you could try regenerating the .pyc files using the old marshal format and feed the resulting .pyc to decompyle - if you're lucky it may accept it... --- begin --- import marshal MAGIC23 = ';\xf2\r\n' def load_pyc(filename): f = open(filename, 'rb') try: magic = f.read(4) timestamp = f.read(4) codeobject = marshal.load(f) finally: f.close() return magic, timestamp, codeobject def dump_pyc_23(filename, timestamp, codeobject): assert len(timestamp)==4 f = open(filename, 'wb') try: f.write(MAGIC23) f.write(timestamp) marshal.dump(codeobject, f, 0) finally: f.close() magic, timestamp, codeobject = load_pyc("test25.pyc") dump_pyc_23("test23.pyc", timestamp, codeobject) --- end --- Good luck! -- Gabriel Genellina From tim.leslie at gmail.com Mon Sep 22 05:32:44 2008 From: tim.leslie at gmail.com (Tim Leslie) Date: Mon, 22 Sep 2008 19:32:44 +1000 Subject: matrix algebra In-Reply-To: <1222070567.979005@chilli.pcug.org.au> References: <1222070567.979005@chilli.pcug.org.au> Message-ID: <d32b45350809220232o4ae801a1kfdf3cb0e0494ef6c@mail.gmail.com> On Mon, Sep 22, 2008 at 6:02 PM, Al Kabaila <akabaila at pcug.org.au> wrote: > Hi, > > My OS is Linux (openSUSE 10.3) and my interest in retirement is Python > applications to Structural Analysis of Civil Engineering structures, > currently in 2 dimensions only (under GPL). Modern Structural Analysis is > highly matrix oriented, but requires only a few basic matrix operations, > namely matrix creation, transposition, multiplication, invertion and > linear equation solution. For stability analysis one would require > Eigenvalues and Eigenvectors. In 3 dimensions, additionally highly > desirable would be vector algebra. The packages do have all these > functions, but currently only the basic functions are in the wrapper. > > There are several packages for matrix algebra. I tried Numeric, numpy and > numarray. All three are very good, but each uses different syntax. Not a > good thing for teaching... So I wrote a little python wrapper (under GPL) > to unify all packages with the same simple and transparent syntax. There is no need for a wrapper. Both numarray and Numeric have been deprecated in favour of numpy, so numpy is the only one you need to use. Numpy should have all the tools you need. If you find something missing, there's a good chance it's included in scipy (which is built on top of numpy). For full details see www.scipy.org. Cheers, Tim > Currently it deals with the Numeric, numpy and numarray and covers creation > of zero filled matrices, transposition, matrix multiplication, solution of > equations and inversion. > > This is a very active newsgroup that incudes such giants as Frederik Lundh > and countless others. I wonder: > > 1. Is there any interest in matrix algebra "for the masses" (I mean interest > in a wrapper for a subset of functions of the packages with a unified > simple syntax)? > 2. What other matrix operations would be required for your area of interest? > 3. What other matrix packages, if any, should one include in the wrapper? > > A copy of the wrapper is stored in a small, public svn repository. If you > would like to download it, please contact me by email at. Of course, if > there is interest, I would be delighted to upload it to a generally > accessible repository. Finally, if this is a re-invention of the wheel > (which it may well be), would you kindly let me know? > > akabaila [at] pcug [dot] org [dot] au. > > I would be very happy to send you the checkout instructions, but I should > discuss that with the people who run the repository. My home page that I > quote with my signature is not a repository nor does it have the current > programs. > > OldAl. > > -- > Al Kabaila (Dr) > http://akabaila.pcug.org.au/StructuralAnalysis > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at ghaering.de Thu Sep 11 07:48:53 2008 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Thu, 11 Sep 2008 13:48:53 +0200 Subject: how dump a program which is running in memory In-Reply-To: <0592abb3-c2f6-4977-8338-3aa1956a353c@b38g2000prf.googlegroups.com> References: <0592abb3-c2f6-4977-8338-3aa1956a353c@b38g2000prf.googlegroups.com> Message-ID: <gab0j6$rmo$1@ger.gmane.org> ruqiang826 wrote: > hi > I have written a service running backgroud to do something in linux. > unfortunately?I deleted the source code by mistake, and I can still > see the process running background using "ps aux" : > > username 13820 0.0 0.0 60368 2964 ? S Aug20 0:33 > python ./UpdateJobStatus.py > > > I wonder if there is some way to dump the programme > "UpdateJobStatus.py" and get the source code back? Often, there is a way by accessing /proc/{pid}/fd/ But I believe you're out of luck with this method because apparently the Python interpreter closes the source file after parsing it. You can still try to find an undeletion utility for your filesystem. Avoid writing to disk in the meantime to not overwrite the deleted file accidentally, of course. There's such a utility for ext2, but I don't know if that works ok with ext3. For other filesystems, I have no idea. -- Gerhard From grflanagan at gmail.com Tue Sep 23 15:55:30 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Tue, 23 Sep 2008 21:55:30 +0200 Subject: Docstrings for class attributes In-Reply-To: <f301fd11-612c-46af-8fff-ca4b1d7fdeb3@e39g2000hsf.googlegroups.com> References: <mailman.1392.1222147427.3487.python-list@python.org> <f301fd11-612c-46af-8fff-ca4b1d7fdeb3@e39g2000hsf.googlegroups.com> Message-ID: <gbbhjh$c86$1@ger.gmane.org> George Sakkis wrote: > On Sep 23, 1:23 am, "Tom Harris" <celephi... at gmail.com> wrote: > >> Greetings, >> >> I want to have a class as a container for a bunch of symbolic names >> for integers, eg: >> >> class Constants: >> FOO = 1 >> BAR = 2 >> >> Except that I would like to attach a docstring text to the constants, >> so that help(Constants.FOO) will print some arbitrary string. Sort of >> a very limited implementation of PEP 224. The only solution that I can >> see is to subclass int.__new__(), since once I have an int all it's >> attributes are immutable. > > Here's one approach, using metaclasses and descriptors; it sort of > works, but it's less than ideal, both in usage and implementation. > > George > > #====== usage ============================================ > > class MyConstants: > __metaclass__ = ConstantsMeta > FOO = const(1, 'some docs about foo') > BAR = const(2) > > print MyConstants.FOO.__doc__ > help(MyConstants.FOO) > print MyConstants.FOO - MyConstants.BAR > print MyConstants.FOO - 2 > print 1 - MyConstants.BAR > > #======= implementation =================================== > > def ConstantsMeta(name, bases, namespace): > for name,attr in namespace.iteritems(): > if isinstance(attr, const): > namespace[name] = _ConstDescriptor(name, attr.value, > attr.doc) > return type(name, bases, namespace) > > class const(object): > def __init__(self, value, doc=None): > self.value = value > self.doc = doc > > class _ConstDescriptor(object): > def __init__(self, name, value, doc): > cls = type(name, (), dict( > __doc__ = doc, > __add__ = lambda self,other: value+other, > __sub__ = lambda self,other: value-other, > # ... > __radd__ = lambda self,other: other+value, > __rsub__ = lambda self,other: other-value, > # XXX lots of boilerplate code for all special methods > follow... > # XXX Is there a better way ? > )) > self._wrapper = cls() > > def __get__(self, obj, type): > return self._wrapper > -- > http://mail.python.org/mailman/listinfo/python-list > I think you get an equivalent result if you forget the descriptor and adapt the metaclass: def ConstantsMeta(name, bases, namespace): for name,attr in namespace.iteritems(): if isinstance(attr, const): cls = type(name, (type(attr.value),), {'__doc__': attr.doc}) namespace[name] = cls(attr.value) return type(name, bases, namespace) class const(object): def __init__(self, value, doc=None): self.value = value self.doc = doc #====== usage ============================================ class MyConstants: __metaclass__ = ConstantsMeta FOO = const(1, 'some docs about foo') BAR = const(2) print MyConstants.FOO.__doc__ help(MyConstants.FOO) print MyConstants.FOO - MyConstants.BAR print MyConstants.FOO - 2 print 1 - MyConstants.BAR #========================================================== Alternatively, forget the metaclass and have: def const(name, val, doc=None): return type(name, (type(val),), {'__doc__': doc})(val) #====== usage ============================================ class MyConstants: FOO = const('FOO', 1, 'some docs about foo') BAR = const('BAR', 2) MOO = const('MOO', 8.0, 'all about MOO') #========================================================== G. From mr.spoon21 at gmail.com Tue Sep 30 06:45:27 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Tue, 30 Sep 2008 12:45:27 +0200 Subject: Weirdness comparing strings Message-ID: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> Hi, I have this piece of code: class Note(): ... ... def has_the_same_name(self, note): return self == note def __str__(self): return self.note_name + accidentals[self.accidentals] __repr__ = __str__ if __name__ == '__main__': n = Note('B') n2 = Note('B') print n print n2 print n.has_the_same_name(n2) I'd expect to get "True", because their string representation is actually the same, instead the output is: B B False I think I'm missing something stupid. Where am I wrong? From marcin201 at gmail.com Sun Sep 28 12:00:34 2008 From: marcin201 at gmail.com (Marcin201) Date: Sun, 28 Sep 2008 09:00:34 -0700 (PDT) Subject: destructor not called Message-ID: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> I have a class which uses a temporary directory for storing data. I would like that directory to be removed when the class is no longer used. I have tried removing the temporary directory from the class destructor, however, it was never called. After I while I traced the problem to the class having a reference to it's own function. Here is a simplified model. test.py class Foo: def __init__(self): print "Hello" self.f = self.fxn def __del__(self): print "Bye" def fxn(self): print "function" a = Foo() running python test.py I get Hello Is this an expected behavior or a bug in python? If this is expected any suggestions for working around this. I would like to avoid having to call the destructor explicitly. Thanks, Marcin From sturlamolden at yahoo.no Mon Sep 29 13:35:58 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 29 Sep 2008 10:35:58 -0700 (PDT) Subject: blocking all threads References: <1d161e02-4b39-462c-a485-d93eb0423e9b@v13g2000pro.googlegroups.com> Message-ID: <758e8fde-69cf-482d-99c3-c13920422e80@m44g2000hsc.googlegroups.com> On Sep 29, 4:56?pm, Alexandru Mosoi <brtz... at gmail.com> wrote: > how can I block all threads for a specific amount of time? (i need to > sleep whole process for testing purposes). i thought of accessing GIL > and sleep for some amount of time, but I don't know how to do this and > whether GIL is recursive. You could do this in C by sleeping while holding the GIL: #ifdef WIN32 #include <Windows.h> #define __sleep(ms) Sleep((DWORD)ms) #else #include <unistd.h> #define __sleep(ms) usleep((useconds_t)ms) #endif __declspec(dllexport) void sleep(int ms) { __sleep(ms); } Save this in a file called "gilsleep.c" and compile it as a DLL (gilslepp.dll in Windows, gilsleep.so in Linux). Then in Python: import ctypes sleep = ctypes.pydll.gilsleep.sleep sleep.argtypes = (ctypes.c_int,) sleep.restype = None sleep(500) # blocks all threads for 500 ms From deets at nospam.web.de Tue Sep 23 11:06:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 23 Sep 2008 17:06:27 +0200 Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> Message-ID: <6jsevmF4uaq4U1@mid.uni-berlin.de> hrishy wrote: > Hi > > Will LINQ be ported to Python ? Take a look at SQLAlchemy or SQLObject for python-based ORM/SQL-abstractions. Apart from that, python is already heavily based on concepts like iterators, filtering. Take a look at itertools. Diez From ter at topazcode.com Tue Sep 2 20:48:23 2008 From: ter at topazcode.com (topazcode) Date: Tue, 2 Sep 2008 17:48:23 -0700 (PDT) Subject: Storing Subprocess Results References: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> <09d82341-3005-4be4-8567-e86faa7ee72a@a8g2000prf.googlegroups.com> Message-ID: <2371e7ce-32d0-4881-aaf2-34261391bddb@m3g2000hsc.googlegroups.com> On Sep 2, 6:31?pm, Karthik Gurusamy <kar1... at gmail.com> wrote: > On Sep 2, 7:16?am, topazcode <t... at topazcode.com> wrote: > > > I am using the subprocess module to run some shell commands on a Linux > > system: > > > import subprocess > > output = subprocess.call('''ssh server1 "uptime"''', shell=True) > > > The above assigns the output variable with a return code, i.e. 0 in > > this case. ?How can I actually capture the data returned from > > subprocess.call, rather than just the return code? ?I'd like to have > > the output variable contain the uptime string in this case. > > Probably commands module is a better choice for your problem:>>> import commands > >>> commands.getoutput('fortune') > > "While money can't buy happiness, it certainly lets you choose your own > \nform of misery." > > > > Karthik > > ?Any help > > > is appreciated. ?Thanks. Thanks guys. I went ahead and used subprocess.Popen as suggested and that works fine. Did something like: import subprocess subprocess.Popen("uptime", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout_value, stderr_value = subprocess.communicate() The above worked great. The 'uptime' was actually a fairly long stretch of commands, and this allows me to check for STDERR and act accordingly. Thanks again for the help and suggestions. From justin.kuto at gmail.com Fri Sep 26 17:43:47 2008 From: justin.kuto at gmail.com (afrogazer) Date: Fri, 26 Sep 2008 14:43:47 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> <f0c482f1-7148-43c4-87b1-3b4718d5d18d@8g2000hse.googlegroups.com> <7b1181e9-16a2-458a-8677-a2d8d7c8a961@l42g2000hsc.googlegroups.com> Message-ID: <e670c0f7-8c4b-4187-a58a-cd4b62944576@e39g2000hsf.googlegroups.com> On Sep 26, 3:33?pm, afrogazer <justin.k... at gmail.com> wrote: > In my rush I seem to have overlooked that, maybe because it's Friday > afternoon. Converting the degrees to radians fixed it: > > rad_angles = [elem*(pi/180) for elem in angles] > > Thanks, One other caveat, some of the bars may over-lap. To prevent this, the width can be set by converting it to radians too: w = 45*pi/180 bar(angles, data, alpha=0.75, align='center', width=w, linewidth=0) Now onto plotting clockwise with North(0 deg.) on top.... From grante at visi.com Wed Sep 17 22:58:11 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 17 Sep 2008 21:58:11 -0500 Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <tvkf941kmehd7hcihihdiil6fjutbfkf6k@4ax.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> <gas6t7$382$1@lust.ihug.co.nz> Message-ID: <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> On 2008-09-18, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote: > In message ><973f75d4-90f5-4930-9107-15fc8651196d at v16g2000prc.googlegroups.com>, sui > wrote: > >> Traceback (most recent call last): >> File "mail5.py", line 21, in <module> >> session = smtplib.SMTP(SMTPserver,port) >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ >> (code, msg) = self.connect(host, port) >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect >> self.sock.connect(sa) >> File "<string>", line 1, in connect >> then conncetion time out..... > > Could it be your ISP is blocking outgoing connections to port > 25? gmail doesn't accept mail via SMTP on port 25. -- Grant From python.list at tim.thechases.com Mon Sep 15 14:26:06 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Sep 2008 13:26:06 -0500 Subject: Unable to see os.environ['COLUMNS'] In-Reply-To: <galrei$bm1$1@news.lysator.liu.se> References: <mailman.1024.1221453482.3487.python-list@python.org> <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> <mailman.1031.1221475955.3487.python-list@python.org> <galrei$bm1$1@news.lysator.liu.se> Message-ID: <48CEA8BE.8020308@tim.thechases.com> Thomas Bellman wrote: > Tim Chase <python.list at tim.thechases.com> writes: > >>> $ export COLUMNS >>> >>> $ python -c "import os; print os.environ['COLUMNS']" >>> 80 > >> This works well, and also manages to keep up to date across runs >> as window-size changes. > > Now try this: > > $ export COLUMNS > $ python -c "import time, os; time.sleep(60); print os.environ['COLUMNS']" > > and change the window width during that sleep. Yes, I did try something similar in my experimenting: $ export COLUMNS $ python >>> import os >>> print os.environ['COLUMNS'] 80 >>> # resize to some other width >>> print os.environ['COLUMNS'] 80 However, for my particular use-case, it's merely for output formatting of a short-running process (akin to "svn status" output). If you resize it in the middle of the sub-second operation, you deserve what you get :) It is disappointing that something so cross-platform as "what's my output width" isn't built-in, requiring jumping through hoops, in ways that aren't cross-platform. The ioctl() method worked on my *nix-like boxes, as did the ncurses versions. However on Win32, neither worked: C:\Temp>python Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> # try the Curses version: ... >>> import curses Traceback (most recent call last): File "<stdin>", line 1, in ? File "c:\Program Files\Python24\lib\curses\__init__.py", line 15, in ? from _curses import * ImportError: No module named _curses >>> # try the ioctl version: ... >>> import fcntl Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named fcntl >>> import termios Traceback (most recent call last): File "<stdin>", line 1, in ? ImportError: No module named termios >>> So for cross-platform'ness on Win32, you wander over here: http://code.activestate.com/recipes/440694/ Abstracting all this mess in a cross-platform sort of way would be a nice "batteries included" tool to have. Based on the other thread that Grant directed me to and the comments in the Win32 page, I'm not the first to have hoped for such an built-in. Fortunately, for now I'm mostly focused on the *nix side of things and have enough to get it working for now. Thanks to those who gave their input. -tkc From castironpi at gmail.com Sat Sep 27 09:10:20 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 06:10:20 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> <mailman.1586.1222518539.3487.python-list@python.org> Message-ID: <e8264caa-1fc2-49ea-8d40-022dfe0cbafe@k7g2000hsd.googlegroups.com> On Sep 27, 7:28?am, "Dotan Cohen" <dotanco... at gmail.com> wrote: > 2008/9/27 Aaron Castironpi Brady <castiro... at gmail.com>: > > >> I think in June and July they were selling watches a lot which I > >> haven't noticed recently. > > > Gucci 104 G-Bandeau Watches - Gucci Watches Discount Rolex Oyster > > Perpetual Lady Datejust Pearlmaster 18kt Yellow Gold Diamond Ladies > > Watch 80318C > > Cartier Must 21 Watches - Cartier Watches Discount > > > I speak too soon. > > If we start blocking users who have no previous posts and then post > many new messages at once, then we wll just push the spammers to forge > active list users and reply to threads. That would be a worse > situation then we are in now. I say leave well enough alone. > > Read about the Brain Blood Barrier > (http://en.wikipedia.org/wiki/Brain_Blood_Barrier) for an example in > nature where although a method to stop an attacker exists, it is not > overused to prevent the attacker from becoming more powerful. > > -- > Dotan Cohen > > http://what-is-what.comhttp://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? > > ?-?-?-?-?-?-? Yow! I forgot the radiolabeled polyethylene glycol coated hexadecylcyanoacrylate nanospheres! CMIIW correct me if I'm wrong. Google Groups is a Usenet/c-l-py gateway. Other gateways aren't contributing to spam. What are they doing that G-Groups is not? From larry.bates at vitalEsafe.com Tue Sep 9 09:19:04 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 09 Sep 2008 08:19:04 -0500 Subject: creating an (inefficent) alternating regular expression from a list of options In-Reply-To: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: <xFuxk.29594$bx1.5153@bignews1.bellsouth.net> metaperl.com wrote: > Pyparsing has a really nice feature that I want in PLY. I want to > specify a list of strings and have them converted to a regular > expression. > > A Perl module which does an aggressively optimizing job of this is > Regexp::List - > http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm > > I really dont care if the expression is optimal. So the goal is > something like: > > vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| > u|ii|i)' > > Is there a public module available for this purpose? > > Perhaps I'm missing something but your function call oneOf(...) is longer than than actually specifying the result. You can certainly write quite easily: def oneOf(s): return "|".join(s.split()) -Larry From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 04:45:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 10:45:58 +0200 Subject: how to find position of dictionary values In-Reply-To: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> References: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> Message-ID: <48bbab73$0$27858$426a34cc@news.free.fr> lee a ?crit : > hi, > i have a dictionary as follows : > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > if user is enters the 3rd item of key phno, > ie "dfsdf" in my dict, > how can i find it is the third item in the internal list of phno of > that dictionary? It's quite simple (hint : read the FineManual(tm) for dict.items() and list.index()), but 1/totally inefficient and 2/not garanteed to yield a single value (what if 'dfsdf' happens to be also the 4th item of the list bound to key 'address' ?). May I suggest you rethink your data structure instead ? What you have here is obviously a collection of 'phno/email/name/address'records. These records shouldn't be split across different objects. Assuming 'phno' is a unique identifier for each record, a better data structure would be: records = { 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, # etc } This way, the lookup is as simple and efficient as possible. My 2 cents.... From rcdailey at gmail.com Thu Sep 4 18:37:58 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Sep 2008 17:37:58 -0500 Subject: Case-insensitive string compare? In-Reply-To: <g9pn28$4u1$1@ger.gmane.org> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <g9pn28$4u1$1@ger.gmane.org> Message-ID: <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> On Thu, Sep 4, 2008 at 5:21 PM, Fredrik Lundh <fredrik at pythonware.com>wrote: > Robert Dailey wrote: > > I currently have a dictionary object that I'm doing the following with: >> >> if lib not in stage_map: >> # ... do stuff ... >> >> However, this will perform a case-sensitive comparison between lib and >> each key in stage_map. Is there a way to make this do a case-insensitive >> comparison instead? >> > > dictionary lookups use the exact value. to make a case-insensitive lookup, > use key.lower() instead of key when creating the dictionary, and then do > > if lib.lower() not in state_map: > ... So you're saying to ensure that stage_map's keys are initially lower-case to begin with? Well, I can't do this either since the case of the keys is actually valuable later on. It's only for the purposes of this specific comparison operation that the case should be ignored. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080904/e4eb64ae/attachment-0001.html> From spammaster.10.webmaster at spamgourmet.com Tue Sep 16 03:54:51 2008 From: spammaster.10.webmaster at spamgourmet.com (spammaster.10.webmaster at spamgourmet.com) Date: Tue, 16 Sep 2008 00:54:51 -0700 (PDT) Subject: PyMarshal Commands crash on Windows References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> <mailman.1015.1221420768.3487.python-list@python.org> <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> Message-ID: <d1c8807e-3853-4818-bd16-8926e2919aaf@z72g2000hsb.googlegroups.com> Hi! Any ideas on it? From tino at wildenhain.de Thu Sep 25 03:51:07 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 25 Sep 2008 09:51:07 +0200 Subject: How to parse a string completely into a list In-Reply-To: <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> References: <e9e4f5c7-3467-4078-a401-fb732d69cc64@a3g2000prm.googlegroups.com> <mailman.1479.1222314277.3487.python-list@python.org> <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <mailman.1480.1222315955.3487.python-list@python.org> <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> Message-ID: <48DB42EB.6090001@wildenhain.de> john.ford at colorado.edu wrote: > On Sep 24, 10:12 pm, Matt Nordhoff <mnordh... at mattnordhoff.com> wrote: >> john.f... at colorado.edu wrote: >>> On Sep 24, 9:44 pm, "Chris Rebert" <c... at rebertia.com> wrote: .... >>>> Could you please define exactly what you mean by "elements" of a string? >>>> If you mean characters, then just use list():>>> list(" \n \t abc") >>>> [' ', ' ', '\n', ' ', '\t', ' ', 'a', 'b', 'c'] >>>> Regards, >>>> Chris >>> Worked like a charm. >>> kudos! >> Why do you need to convert it to a list? Strings are sequences, so you >> can do things like slice them or iterate through them by character: >> >>>>> for character in "foo": >> ... print character >> ... >> f >> o >> o >> >> -- > > The string draws a map that I then want to be able to traverse > through. If I can count through the individual characters of a list I > can create an x-y coordinate plane for navigation. You can 'count' (whatever that means) equally in strings as you do in lists. As said above, they behave exactly the same. Just strings are imutable - e.g. you can't change individual parts of them. Tino > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080925/ec4919ab/attachment-0001.bin> From rmacneill at gmail.com Thu Sep 18 19:39:59 2008 From: rmacneill at gmail.com (rmac) Date: Thu, 18 Sep 2008 16:39:59 -0700 (PDT) Subject: Python newbie question re Strings and integers References: <c0287f45-1c5a-40b5-aff3-ab5639d26749@k13g2000hse.googlegroups.com> <mailman.1249.1221781022.3487.python-list@python.org> Message-ID: <4703bda4-1028-4202-ac07-fe6afdc1f67e@l64g2000hse.googlegroups.com> Ah! Arghh!!! You are so correct on the usage of the ':' Python syntax is a little different from what I am used to. Thank you. From marco.bizzarri at gmail.com Wed Sep 10 13:22:17 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 10 Sep 2008 19:22:17 +0200 Subject: Adding further report options to unittest.py In-Reply-To: <6iq07jFs30egU1@mid.uni-berlin.de> References: <mailman.783.1221052761.3487.python-list@python.org> <6iq07jFs30egU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809101022q1d47d816i2a43972bc2eedcf@mail.gmail.com> On Wed, Sep 10, 2008 at 3:25 PM, Diez B. Roggisch <deets at nospam.web.de> wrote: > Marco Bizzarri wrote: > >> Hi all. >> >> I would like to change the way test reports are generated, in a Zope >> environment. >> > > Have you looked at nosetests? Nose is a test-discovery & running-framework > based upon unittest-module (but you can also "only" test simple functions, > very handy) Nope; next time I will make a google search before posting ;) > And it has a very powerful plugin-mechanism, that allows you to implement > cleanly what you want. > > For each test, you get a start/end-method called in your plugin that you can > use to gather the information you need, e.g. start/stop-times. I gave it a look; it is nice and it seems powerful; I just wonder if I need to put my hands on all my tests to do what I want to do... but I'm sure this can be sorted in the documentation. > For example, I've created an enhanced reporting plugin that lists all tests > run (not only those failed or error'ed), and adding time-measuring per-test > is on my list of todos. Looks like there is a new tool I need to learn... ah, nice times when all you needed was an hammer and a screwdriver... ;) Thanks for the suggestion, Diez, I'll read it. > Diez > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From mnordhoff at mattnordhoff.com Tue Sep 9 15:00:41 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 09 Sep 2008 19:00:41 +0000 Subject: check if the values are prensent in a list of values In-Reply-To: <ga6egs$hjf$1@ger.gmane.org> References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> <ga6egs$hjf$1@ger.gmane.org> Message-ID: <48C6C7D9.7080900@mattnordhoff.com> Emile van Sebille wrote: > flit wrote: >> Hello All, >> >> I will appreciate the help from the more skillfull pythonistas.. >> >> I have a small app that generates a sequence like >> >> 00341 >> 01741 >> 03254 > > Consider using a dict with sorted tuple keys, eg > > d = {} > > for seq in ['00341','01741','03254']: > ky = list(seq) > ky.sort() > d[tuple(ky)] = None > > > then d.keys() are the unique combinations. > > HTH, > > Emile I'm not judging whether this is a good solution or not, but that's a silly use of a dict. A set would be better. s = set() for seq in ['00341','01741','03254']: s.add(tuple(sorted(ky))) Then you just, well, access the set directly, instead of using d.keys() or something. (I also replaced the sorting with the sorted() function for brevity. This all assumes you have at least Python 2.4...) >> This values I am putting in a list. >> >> So I have a list = [00341,01741,03254] >> >> after the programs find the sequence 03401 this sequence is "new" so >> it appends on the list. But I want to avoid that as the values are >> already on the first sequence of the list (00341). >> If I try to use a "in" statement it will give false. as 00341 is >> different from 00341 (but for my goal not..) >> >> >> How can I check against this list and avoid to put "different" >> sequences but same values? >> >> as 34100 --> dont append on the list >> 14300 ---> dont append on the list >> 05321 --> append to the list. >> >> Am I doing some conceptual error using lists? >> There is a better approach? >> >> Thanks -- From dieter at handshake.de Thu Sep 18 13:13:28 2008 From: dieter at handshake.de (Dieter Maurer) Date: 18 Sep 2008 19:13:28 +0200 Subject: Zsi interoperability In-Reply-To: <mailman.1089.1221546702.3487.python-list@python.org> References: <mailman.1047.1221498380.3487.python-list@python.org> <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> <3f0d61c40809151126n791b1ce0ya1e208a075660934@mail.gmail.com> <mailman.1089.1221546702.3487.python-list@python.org> Message-ID: <x7vdwtv0lj.fsf@handshake.de> Mailing List SVR <lists at svrinformatica.it> writes on Tue, 16 Sep 2008 08:31:13 +0200: > ... > however my server require client > certificate authentication, > > does soaplib or zsi work in this environment? ZSI allows you to provide an alternative transport. That's the usual way to let ZSI work over "https" rather than "http". I do not know whether Python supports a client certificate authentication transport out of the box -- but at least the problem is split into two easier parts. Dieter From pavlovevidence at gmail.com Thu Sep 4 15:19:28 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 12:19:28 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> <f1b92bb7-f960-4e56-b8be-240cfc301726@b38g2000prf.googlegroups.com> Message-ID: <a547e63a-7315-48fe-bb04-97902dbc879a@z6g2000pre.googlegroups.com> On Sep 4, 12:36 pm, bukzor <workithar... at gmail.com> wrote: > > >>> so unfortunately I think I need to use __getattribute__ > > >>> to do this. I'm doing all this just to make the connection not > > >>> actually connect until used. > > >> I may be dumb, but I don't get how this is supposed to solve your > > >> problem. But anyway : there's a known design pattern for what you're > > >> trying to do, that doesn't require mixins nor messing with > > >> __getattribute__ (which, I repeat, is more often than not something you > > >> *don't* want to do). The name of the design pattern is "proxy". I > > >> strongly suggest that you 1/ try to cure the real problem instead of > > >> hacking around and 2/ read about the proxy design pattern. > > > >> My 2 cents... > > > > I like the idea of mix-ins, but can't figure out how to make a proxy > > > work that way. > > > You mean, "how to use a proxy for lazy initialization" ? Heck, that's > > the exact use case in the GoF. > > I mean, "how to make a MixIn class that uses the proxy pattern". You don't. That's not how proxies work. > I'd like to be able to do something like this: > > class SuperCursor(FeatureOneMixIn, FeatureTwoMixin, ..., > VanillaCursor): pass Why does it have to look like that? A good programmer lets the code look however it has to look to most effectively do it's job. With a proxy, the "base class" isn't a base class but a member. Here is a very simple example: class SuperCursor(object): def __init__(self): self._cursor = VanillaCursor() self._connected = False def __getattr__(self,attr): if not self._connected: self._cursor.connect() self._connected = True return getattr(self._cursor,attr) cursor = SuperCursor() That doens't use a mixin, but why should it? Carl Banks From mr.spoon21 at gmail.com Tue Sep 30 06:58:27 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Tue, 30 Sep 2008 12:58:27 +0200 Subject: Weirdness comparing strings In-Reply-To: <48E205A4.3020003@seehart.com> References: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> <48E205A4.3020003@seehart.com> Message-ID: <8f67b6f80809300358r6648d8b7v513df0118e6ca33c@mail.gmail.com> On Tue, Sep 30, 2008 at 12:55 PM, Ken Seehart <ken at seehart.com> wrote: > Instance comparison is not necessarily the same as string comparison. > Neither __str__ nor __repr__ are implicitly used at all for comparison. Ok, I see. > In fact, by default a pair of instances are not equal unless they are the > same object. To define comparison to mean something, you need to define > __cmp__ or __eq__. > > Trivial example of default comparison: > >>>> class C: > ... pass > ... >>>> c = C() >>>> d = C() >>>> c==d > False >>>> c==c > True Thanks. Almar Klein: >but this does not implicitly convert self to a string. You'll have to >do in explicitly: >use "return str(self) == note" instead. Yes, this works. Thanks. From graham at vpac.org Tue Sep 16 00:41:29 2008 From: graham at vpac.org (Graham Jenkins) Date: Tue, 16 Sep 2008 14:41:29 +1000 Subject: cups.Connection.printFile Message-ID: <1221540089.17354.7.camel@sys04.in.vpac.org> I'm trying to print a file from within a Python program. The quick-and-dirty solution is to use something like: fd = os.popen("lp -d MyPrinter", "wb") fd.write(MyFileContents) But it seems to me that there should be a clean solution like: import cups stat = cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") Unfortunately, I can't get this to work; not sure of the syntax and have no idea of what to put for "MyOptions". So, can anybody help with an example please? Also .. does anybody know of a way to print a String in this fashion rather than a File? Regards .. -- Graham Jenkins Australian Research Collaboration Service Victorian Partnership for Advanced Computing (+613) 9925-4862 From workitharder at gmail.com Wed Sep 3 18:26:10 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 3 Sep 2008 15:26:10 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> Message-ID: <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> On Sep 3, 1:02?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > bukzor a ?crit : > (snip) > > > Thanks for the reply. Just to see it not work, I tried to remove > > __getattribute__ from LateInitMixIn, but couldn't get it to work. > > ??? Sorry, I don't get what you mean... Since you said __getattribute__ is an attribute of the class, I tried to run (something to the effect of) delattr(self.__class__, "__getattribute__"), but it threw an AttributeError. > > > My Base class is a C class (_mysql.connection from MySQLdb) that > > sometimes segfaults if you try to use it before it's fully > > initialized, > > > ... I have used MySQLdb for years on more than a dozen linux > distribs, and never had such a problem. Is this a known bug ? Or is > there something wrong with your setup ? I'm trying to optimize my number of connections by not fully initializing (read: not connecting) my connection until it's used in some way. Of course the maintainer didn't envision this (mis)use, so the object sometimes throws bad errors until it's fully initialized. Of course the *correct* way to do this is to be more careful about when I create connections, but I think I should be able to get this to work, and it (would be) much easier to do it The Right Way once it works. > > so unfortunately I think I need to use __getattribute__ > > to do this. I'm doing all this just to make the connection not > > actually connect until used. > > I may be dumb, but I don't get how this is supposed to solve your > problem. But anyway : there's a known design pattern for what you're > trying to do, that doesn't require mixins nor messing with > __getattribute__ (which, I repeat, is more often than not something you > *don't* want to do). The name of the design pattern is "proxy". I > strongly suggest that you 1/ try to cure the real problem instead of > hacking around and 2/ read about the proxy design pattern. > > My 2 cents... I like the idea of mix-ins, but can't figure out how to make a proxy work that way. For a long time I had a proxy class that added five or six features on top of the MySQLdb package, but it wasn't configurable enough, and I'm working on splitting each feature into its own MixIn class. As an aside, this is working for me pretty well. The "reconnect" method (inheritied from a "Reconnectable" mixin) uses several of the object's attributes, so I need to set _inited beforehand so that I don't get into an infinite __getattribute__ loop. What I'd *really* like to do is remove __getattribute__ from the object at that point. def __getattribute__(self, attr): "connect if it would otherwise cause an error." getattr = lambda attr:object.__getattribute__(self, attr) if not getattr("_inited"): print "connecting." setattr(self, "_inited", True) getattr("reconnect")() return getattr(attr) Thanks for your help, --Buck From clodoaldo.pinto at gmail.com Sun Sep 14 10:46:34 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Sun, 14 Sep 2008 07:46:34 -0700 (PDT) Subject: cjson 1.0.5 keyword argument References: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> Message-ID: <818d512c-25d0-4ea3-8553-4152edcc101a@v16g2000prc.googlegroups.com> On Sep 14, 10:33 am, Clodoaldo <clodoaldo.pi... at gmail.com> wrote: > I have installed cjson 1.05 in Fedora 8 (python 2.5.1). > > The cjson home page shows a keyword argument "encoding".http://python.cx.hu/python-cjson/ > > When i use it i get an error: > > >>> cjson.encode('?', encoding='utf8') > > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: encode() takes no keyword arguments > > What am i missing? There is no mail list for cjson. The problem is the package from Fedora 8. When i install from source it works. Regards, Clodoaldo From aioe.org at technicalbloke.com Mon Sep 29 13:52:28 2008 From: aioe.org at technicalbloke.com (r0g) Date: Mon, 29 Sep 2008 13:52:28 -0400 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <mailman.1520.1222400746.3487.python-list@python.org> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <gbq5p8$iiq$1@lust.ihug.co.nz> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Message-ID: <gbr4ks$1vv$1@aioe.org> bearophileHUGS at lycos.com wrote: > Lawrence D'Oliveiro: >>> Gnuplot is non-Free software. > > Fly Away: >> Yes, it is. > > From: > http://www.gnuplot.info/faq/faq.txt > > 1.7 Does gnuplot have anything to do with the FSF and the GNU project? > [...] > Gnuplot is freeware in the sense that you don't have to pay for it. > However > it is not freeware in the sense that you would be allowed to > distribute a > modified version of your gnuplot freely. [...] > > Bye, > bearophile Well, ish. You can only distribute modifications to gnuplot itself as patches, but you can distribute it freely and they publish the source so, while it's not GPL free it's tending towards it. Roger. From Graham.Dumpleton at gmail.com Sun Sep 7 19:02:25 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 7 Sep 2008 16:02:25 -0700 (PDT) Subject: Python and M2Crypto question References: <12b278d2-9f78-4fc9-a4f2-7d22c543aeb9@d1g2000hsg.googlegroups.com> Message-ID: <643253ee-c8a7-4ccc-bac2-432ac382e4c3@v39g2000pro.googlegroups.com> On Sep 7, 11:07?pm, Bojan Mihelac <bmihe... at gmail.com> wrote: > Hi all! > > I am trying to install M2Crypto to work on OSX10.5 apache > (mod_python). Error I receive: > > Error was: dlopen(/Library/WebServer/eggs/M2Crypto-0.18.2-py2.5- > macosx-10.5-i386.egg-tmp/M2Crypto/__m2crypto.so, 2): no suitable image > found. ?Did find: > ? ? ? ? /Library/WebServer/eggs/M2Crypto-0.18.2-py2.5-macosx-10.5-i386.egg- > tmp/M2Crypto/__m2crypto.so: no matching architecture in universal > wrapper > > I guess that have to do something with x64 architecture but I am > stucked and not able to find a way and to make this work. M2Crypto lib > works good stand alone. See: http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX#Missing_Code_For_Architecture This is mod_wsgi documentation, but same issue applies to mod_python. Graham From obm.mnasir at gmail.com Thu Sep 4 00:15:44 2008 From: obm.mnasir at gmail.com (king) Date: Wed, 3 Sep 2008 21:15:44 -0700 (PDT) Subject: what is next for you, a great opportunity waiting for Message-ID: <ac08783f-2bc1-4945-b401-d0493acc3cf7@59g2000hsb.googlegroups.com> www.hrconsultant.tk From gagsl-py2 at yahoo.com.ar Tue Sep 23 05:48:52 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 23 Sep 2008 06:48:52 -0300 Subject: Time.sleep(0.0125) not available within Linux References: <27CC3060AF71DA40A5DC85F7D5B70F380522CF11@AWMAIL04.belcan.com> Message-ID: <op.uhxhjqt6x6zn5v@gabriel2.softlabbsas.com.ar> En Mon, 22 Sep 2008 23:09:50 -0300, Blubaugh, David A. <dblubaugh at belcan.com> escribi?: > I was wondering if anyone has come across the issue of not being allowed > to have the following within a Python script operating under Linux: > > time.sleep(0.0125) > > It appears that I am not allowed to have the object sleep. Has anyone > encountered this specific issue before in the past? I bet your test script is called time.py, or there is a time.py[c] in the same directory, or somewhere in the Python search path. Move/rename the offending module. If I win, it's because my psychic capabilities allow me to translate "I am not allowed to have the object sleep" to "this line of code raises AttributeError". Next time please post the complete traceback... -- Gabriel Genellina From castironpi at gmail.com Fri Sep 19 00:38:09 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 18 Sep 2008 21:38:09 -0700 (PDT) Subject: Extracting hte font name from a TrueType font file References: <gau1dk$t7h$1@ger.gmane.org> <gaudl8$6s2$2@ger.gmane.org> <mailman.1252.1221785381.3487.python-list@python.org> Message-ID: <b6d97134-616b-4b14-aeaf-df64bc3769fb@m36g2000hse.googlegroups.com> On Sep 18, 7:48?pm, Steve Holden <st... at holdenweb.com> wrote: > Fredrik Lundh wrote: > > Steve Holden wrote: > > >> Does anyone have a Python recipe for this? > > >>>> from PIL import ImageFont > >>>> f = ImageFont.truetype("/windows/fonts/verdanai.ttf", 1) > >>>> f.font.family > > 'Verdana' > >>>> f.font.style > > 'Italic' > > Thanks so much, Fredrik. The reason I asked is because I found the > specification completely opaque ... > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ Here's the code to parse the spec. #customize path f= open( '\\windows\\fonts\\arial.ttf', 'rb' ) from struct import * #header shead= Struct( '>IHHHH' ) fhead= f.read( shead.size ) dhead= shead.unpack_from( fhead, 0 ) #font directory stable= Struct( '>4sIII' ) ftable= f.read( stable.size* dhead[ 1 ] ) for i in range( dhead[1] ): #directory records dtable= stable.unpack_from( ftable, i* stable.size ) if dtable[0]== 'name': break assert dtable[0]== 'name' #name table f.seek( dtable[2] ) #at offset fnametable= f.read( dtable[3] ) #length snamehead= Struct( '>HHH' ) #name table head dnamehead= snamehead.unpack_from( fnametable, 0 ) sname= Struct( '>HHHHHH' ) for i in range( dnamehead[1] ): #name table records dname= sname.unpack_from( fnametable, snamehead.size+ i* sname.size ) if dname[3]== 4: #key == 4: "full name of font" s= unpack_from( '%is'% dname[4], fnametable, dnamehead[2]+ dname[5] )[0] print dname, s This outputs: (0, 3, 0, 4, 10, 318) A r i a l (1, 0, 0, 4, 5, 4081) Arial (3, 1, 1033, 4, 10, 318) A r i a l First 3 fields: 0, 3, 0= Unicode, Unicode 2.0, English 1, 0, 0= Macintosh, Default, English 3, 1, 1033= Windows, Version 1.1, Language "1033" From tjreedy at udel.edu Sun Sep 28 03:20:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 03:20:28 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00eee9ec$0$20666$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <gbkfhv$g2$1@panix3.panix.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <gblea5$os6$1@panix3.panix.com> <mailman.1600.1222551713.3487.python-list@python.org> <00eee9ec$0$20666$c3e8da3@news.astraweb.com> Message-ID: <gbnb7s$272$1@ger.gmane.org> Steven D'Aprano wrote: > And modules aren't callable. I've often thought they should be. Modules are not callable because their class, module, has no __call__ instance method. But (in 3.0, which is all I will check) you can subclass module and add one. >>> m = type(__builtins__) >>> m <class 'module'> >>> dir(m) ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] >>> class m2(m): def __call__(self, *args, **kwds): print(self, args, kwds) >>> mod = m2('mod') # only arg required by module.__init__ >>> mod(1,2,3,a=4,b=5) <module 'mod' (built-in)> (1, 2, 3) {'a': 4, 'b': 5} >>> mod # did not override __repr__ <module 'mod' (built-in)> So, roll your own to your taste. Terry Jan Reedy From adam.pletcher at volition-inc.com Wed Sep 10 14:08:56 2008 From: adam.pletcher at volition-inc.com (Adam Pletcher) Date: Wed, 10 Sep 2008 13:08:56 -0500 Subject: removing text string In-Reply-To: <A86D1A0C2B238848B9ABDE1A7E287CE6010E0F55@EXCHVS01.ad.sfwmd.gov> References: <loom.20080910T144026-626@post.gmane.org> <A86D1A0C2B238848B9ABDE1A7E287CE6010E0F55@EXCHVS01.ad.sfwmd.gov> Message-ID: <893A44FF792E904A97B7515CE341914604238A24@volimxs01.thqinc.com> You just want to drop the last two characters? Slice it. >>> s = "080829-7_A"[:-2] >>> print s 080829-7 - Adam > -----Original Message----- > From: python-list-bounces+adam=volition-inc.com at python.org > [mailto:python-list-bounces+adam=volition-inc.com at python.org] On Behalf > Of Ahmed, Shakir > Sent: Wednesday, September 10, 2008 10:22 AM > To: python-list at python.org > Subject: removing text string > > I need to remove text string from the list of the numbers mentioned > below: > > 080829-7_A > 070529-5_c > 080824-7_O > 070405_6_p > > The output will be : 080829-7 > 070529-5 > 080824-7 > 070405-6 > > Any idea is highly appreciated. > > > > -- > http://mail.python.org/mailman/listinfo/python-list From nytrokiss at gmail.com Thu Sep 18 16:10:49 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 18 Sep 2008 13:10:49 -0700 Subject: Twisted vs Python Sockets Message-ID: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> Hi I am wondering what are the major points of twisted over regular python sockets. I am looking to write a TCP server and want to know the pros can cons of using one over the other. Thanks James -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/f6040166/attachment-0001.html> From marek.rocki at wp.pl Thu Sep 18 11:30:47 2008 From: marek.rocki at wp.pl (marek.rocki at wp.pl) Date: Thu, 18 Sep 2008 08:30:47 -0700 (PDT) Subject: dict generator question References: <mailman.1217.1221749709.3487.python-list@python.org> Message-ID: <29e1af82-9a78-4b3b-87e4-1e13dcaeb508@26g2000hsk.googlegroups.com> Simon Mullis napisa?(a): > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. It seems to me that the "count" you're looking for is the number of elements from l whose first 3 characters are the same as the v[0:3] thing. So you may try: >>> dict_of_counts = dict((v[0:3], sum(1 for x in l if x[:3] == v[:3])) for v in l) But this isn't particularly efficient. The 'canonical way' to construct such histograms/frequency counts in python is probably by using defaultdict: >>> dict_of_counts = collections.defaultdict(int) >>> for x in l: >>> dict_of_counts[x[:3]] += 1 Regards, Marek From lists at svrinformatica.it Mon Sep 15 13:06:00 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Mon, 15 Sep 2008 19:06:00 +0200 Subject: Zsi interoperability Message-ID: <1221498360.5891.33.camel@localhost.localdomain> Hi, I have to implement a soap web services from wsdl, the server is developed using oracle, is zsi or some other python library for soap interoperable with oracle soa? thanks Nicola From mail at microcorp.co.za Fri Sep 12 16:20:42 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 12 Sep 2008 22:20:42 +0200 Subject: dict slice in python (translating perl to python} Message-ID: <003f01c9151c$ab471600$0d00a8c0@hendrik> MRAB <googl....arnett.plus.com> wrote: >On Sep 11, 6:11 pm, Fredrik Lundh <fred... at pythonware.com> wrote: >[snip] >> (the next step towards true Pythonicness would be to store your data in 8<----------------------- >> >Surely the word is "Pythonicity"? :-) When faced with the choice between "Pythonicness" and "Pythonicity", I feel a bit like Ogden Nash must have felt when he wrote: The Camel has a single hump, The Dromedary, two. Or the other way around. I'm never sure, are you? - Hendrik From aahz at pythoncraft.com Fri Sep 26 00:17:14 2008 From: aahz at pythoncraft.com (Aahz) Date: 25 Sep 2008 21:17:14 -0700 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <y9udnWtzwLtQi0rVnZ2dnUVZ_gidnZ2d@earthlink.com> Message-ID: <gbhnoa$d83$1@panix3.panix.com> In article <y9udnWtzwLtQi0rVnZ2dnUVZ_gidnZ2d at earthlink.com>, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: >On 21 Sep 2008 22:39:47 GMT, Steven D'Aprano ><steve at REMOVE-THIS-cybersource.com.au> declaimed the following in >comp.lang.python: >> >> What do you call such a class? > > A wasted definition... The same functionality is achieved by just >creating and importing a module. Your "class methods" would just be >functions within the module; class level attributes would be module >level objects (access with global if writing to them, use a _ to >indicate "internal") Seems to me that if all the module is used for is to store state, you're wasting a file on disk. I personally prefer to use a class singleton. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From fredrik at pythonware.com Sun Sep 21 11:12:00 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 17:12:00 +0200 Subject: Override the '+' symbol In-Reply-To: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> References: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> Message-ID: <gb5o81$f3f$2@ger.gmane.org> Mr.SpOOn wrote: > how can I override the '+' symbol (and other math symbols) so that it > can have a new behavior when applied to some objects? see "Emulating Numeric Types" in the language reference: http://www.python.org/doc/ref/numeric-types.html </F> From skip at pobox.com Tue Sep 23 10:15:07 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 23 Sep 2008 09:15:07 -0500 Subject: Python is slow? In-Reply-To: <Y7CdnYRzU-8naEXVnZ2dnUVZ_sDinZ2d@posted.visi> References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <Y7CdnYRzU-8naEXVnZ2dnUVZ_sDinZ2d@posted.visi> Message-ID: <18648.63979.426433.48679@montanaro-dyndns-org.local> >> We may conclude that I'm bad at programming C++, Grant> AFAICT, _everybody_ is bad at programming C++. Grant> One begins to suspect it's not the fault of the programmers. +1 QOTW... Skip From mensanator at aol.com Sat Sep 20 12:30:27 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 20 Sep 2008 09:30:27 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <16b063ae-8b2d-4991-b6ba-d32330e47c59@s50g2000hsb.googlegroups.com> On Sep 20, 11:16?am, Alex Snast <asn... at gmail.com> wrote: > Hello > > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) >>> for i in xrange(10,-1,-1): print i, 10 9 8 7 6 5 4 3 2 1 0 Note the starting number is 10, the ending number is -1 because you want to include 0 and the step size is -1. From dmitrey.kroshko at scipy.org Sun Sep 21 06:41:05 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 21 Sep 2008 03:41:05 -0700 (PDT) Subject: How to kill threading.Thread instance? Message-ID: <e7d7dc9a-c985-493e-bb8c-ca6c3b9e856d@y38g2000hsy.googlegroups.com> hi all, Is there a better way to kill threading.Thread (running) instance than this one http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496960 (it's all I have found via google). BTW, it should be noticed that lots of threading module methods have no docstrings (in my Python 2.5), for example _Thread__bootstrap, _Thread__stop. Regards, D. From milenko.stojadinovic at googlemail.com Sat Sep 27 17:56:07 2008 From: milenko.stojadinovic at googlemail.com (Milenko Stojadinovic Cvrcko) Date: Sat, 27 Sep 2008 14:56:07 -0700 (PDT) Subject: Hello boys! Message-ID: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> Hello, this is Milenko Stojadinovic from town Banjaluka, Bosnia and Herzegovina, also known as Cvrcko Does anyone know of any bars in town where I can swallow a bucket of cum? It can be either dog, horse or human cum. Also, does anyone know of any sex bars where people will shit in your mouth? I also like eating shit. -- Name: Mileno Stojadinovic - Cvrcko Street adress: Sime Matavulja 12 Town: 78000 Banja Luka Country: Bosnia and Herzegovina Home phone: +38751/303-665 Cell phone: +38765/499-312 Email adress: milenko.stojadinovic at googlemail.com ~ The new pumpkin rarely pulls Terrance, it teases Sharon instead. For Susan the tape's sad, beside me it's unique, whereas against you it's believing dirty. Hey, go reject a fork! Why did Alice open throughout all the boats? We can't explain poultices unless Woody will mercilessly judge afterwards. The frames, disks, and shirts are all fat and fresh. Who will we dine after Edwina wastes the thin mirror's goldsmith? It's very outer today, I'll recollect strangely or Christopher will learn the teachers. Hardly any humble brave tyrants hourly solve as the tired wrinkles cover. Hardly any distant buttons are short and other urban ointments are filthy, but will Robette receive that? Let's lift behind the deep highways, but don't promise the heavy diets. Who kicks badly, when Melvin burns the stale code before the autumn? Get your absolutely moulding barber within my cellar. If you will laugh Gay's hill against porters, it will incredibly climb the case. Some shopkeepers arrive, irrigate, and shout. Others sadly expect. To be pathetic or sticky will talk abysmal oranges to wickedly look. Are you healthy, I mean, moving above clever onions? While farmers partly taste pins, the powders often excuse against the blunt jackets. Generally Susanne will order the sticker, and if George actually seeks it too, the bowl will attempt with the polite lane. He can hate durable kettles above the rural bad ocean, whilst Oscar easily scolds them too. You eventually fill against Norma when the kind drapers irritate among the poor summer. As surprisingly as Dolf converses, you can dye the cap much more familiarly. Brion, still killing, behaves almost eerily, as the sauce changes on their coffee. You won't recommend me grasping about your lazy office. Almost no butchers steadily live the lost signal. Cyrus's hat improves among our desk after we sow towards it. Ralph measures the weaver within hers and wanly calls. Some cosmetic tags answer David, and they rigidly walk Quincy too. When Richard's elder gardner dreams, Mark cares for weak, closed islands. He might strongly fear think and plays our cheap, sour painters above a bathroom. I creep the active yogi and cook it in back of its dorm. Tell Katherine it's strong loving within a tree. Why will you jump the angry lower exits before Murray does? I am unbelievably bitter, so I wander you. How does Hector smell so regularly, whenever Ronald likes the solid twig very slowly? Julieta, have a hot printer. You won't clean it. Fucking don't join a dryer! She wants to nibble inner smogs under Usha's castle. She'd rather depart grudgingly than help with Bernadette's younger grocer. Other old dark cards will comb frantically alongside cans. Try pouring the monument's pretty cat and Oliver will attack you! Don't try to seek halfheartedly while you're jumping throughout a easy carpenter. He'll be climbing in front of good Cypriene until his enigma answers quietly. What doesn't Janet smell inadvertently? They are opening before the rain now, won't explain walnuts later. Some light long game covers pools outside Woodrow's rich film. Why did Oscar judge the pear with the handsome spoon? He will talk nearly if Julieta's tailor isn't wet. Just looking beside a ulcer through the store is too young for Woody to care it. Both filling now, Alejandro and Marty irritated the open rivers about smart envelope. Occasionally, dusts kill beside rude fires, unless they're sweet. Her pen was sharp, dull, and fears over the spring. Zack, on floors difficult and upper, attacks towards it, recollecting seemingly. We measure the raw sauce. They are rejecting throughout quiet, towards empty, in back of cold units. My wide potter won't clean before I comb it. If you'll pour Edward's camp with aches, it'll admiringly converse the cup. I was promising frogs to worthwhile Corinne, who's walking in back of the counter's stable. It can receive clean pickles, do you solve them? Many jugs will be weird lean carrots. Roger helps, then Walt stupidly believes a ugly lentil on Catherine's road. We tease them, then we weekly dream Zack and Annabel's blank candle. A lot of shallow dose or canyon, and she'll locally excuse everybody. If the bizarre balls can sow bimonthly, the hollow raindrop may love more ventilators. We laugh weekly, unless Jezebel grasps shoes outside Jimmie's puddle. Jimmy! You'll mould plates. Just now, I'll dine the bandage. All glad strange figs will fully order the lemons. The dog without the proud star is the pitcher that learns happily. It might crudely scold within sick dry satellites. Until Dolf calls the bushs generally, Ann won't join any full winters. Better kick clouds now or Blanche will wrongly hate them over you. There, Jeff never arrives until Joie nibbles the noisy elbow deeply. From aquil.abdullah at gmail.com Mon Sep 8 11:43:20 2008 From: aquil.abdullah at gmail.com (aha) Date: Mon, 8 Sep 2008 08:43:20 -0700 (PDT) Subject: Unable to start a process with subprocess Popen() References: <e0b6c39a0809080350x6deb87dap5cd01c1d54827adf@mail.gmail.com> <mailman.681.1220872998.3487.python-list@python.org> Message-ID: <3657eb2f-c827-4929-be5a-689959de5f85@a1g2000hsb.googlegroups.com> On Sep 8, 7:23?am, dudeja.ra... at gmail.com wrote: > On Mon, Sep 8, 2008 at 11:50 AM, ?<dudeja.ra... at gmail.com> wrote: > > Hi, > > > I'm using the subprocess module's Popen() to start a batch file. This > > batch file basically calls an exe which also gets started. > > Unfortunately, this does not produce any results. I looked into the > > Task bar that this exe has started but it does not consume and cpu so > > I believet that this exe is not working. > > > I used the following command to start the batch fiile: > > > testing = subprocess.Popen([batchFilePath], \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? shell = True, \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stdout = subprocess.PIPE, \ > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? stderr = subprocess.PIPE).communicate()[0] > > > batchFilePath is the path of the batch file. > > > -- > > Regrads, > > Rajat > > Ok, I re-phrase my question: > > there is a batch file that executes a exe file. The batch just works > if run from command prompt and produces output to standard output and > the file. > > Now, I try to call the same batch file from subprocess.Pope() call. > The batch file gets called and that internally also calls the exe > file. > > But, the exe just runs forever i.e. hangs and does not produces output > , atleast not to the file. > > Please suggest is there is something wrong with the above code. > > Regards, > Rajat Hello Rajat, I would take a look at the thread below, it might help it might not: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4505613f014fdec7/3ee15c9c88a5efdc?hl=en#3ee15c9c88a5efdc Also, if you post a larger section of the code I might be able to give you a hand. Once you've run the testing = subprocess.Popen() make sure you use a testing.wait() From castironpi at gmail.com Thu Sep 18 14:22:46 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 18 Sep 2008 11:22:46 -0700 (PDT) Subject: minimum install & pickling References: <fb304bca-abe9-48e6-8dba-6187e33e5a6d@a2g2000prm.googlegroups.com> <6f045535-555f-44b6-93a5-f5b338d3f318@d45g2000hsc.googlegroups.com> <69cf2202-e11b-4994-84ab-a41167ef2652@26g2000hsk.googlegroups.com> <d8e9b368-ee86-415e-b0e6-16958391dfdd@8g2000hse.googlegroups.com> Message-ID: <ac8c3358-3e35-48a5-a22a-af0dab11dae9@x41g2000hsb.googlegroups.com> On Sep 18, 5:20?am, Paul Boddie <p... at boddie.org.uk> wrote: > On 17 Sep, 22:18, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> > wrote: > > > On Sep 17, 4:43?am, Paul Boddie <p... at boddie.org.uk> wrote: > > > >http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...) > > > These solutions have at least the same bugs that the bare bones > > solution in the corresponding framework has. ?Malicious code has fewer > > options, but constructive code does too. ?If you're running foreign > > code, what do you want it to do? ?What does it want to do? ?The more > > options it needs, the more code you have to trust. > > As I noted, instead of just forbidding access to external resources, > what you'd want to do is to control access instead. This idea is not > exactly new: although Brett Cannon was working on a sandbox capability > for CPython, the underlying concepts involving different privilege > domains have been around since Safe-Tcl, if not longer. The advantage > of using various operating system features, potentially together with > tools like fakechroot or, I believe, Plash, is that they should work > for non-Python programs. Certainly, the chances of successfully > introducing people to such capabilities are increased if you don't > have to persuade the CPython core developers to incorporate your > changes into their code. > > > The only way a Python script can return a value is with sys.exit, and > > only an integer at that. ?It is going to have output; maybe there's a > > way to place a maximum limit on its consumption. ?It's going to have > > input, so that the output is relative to something. ?You just make > > copies to prevent it from destroying data. ?Maybe command-line > > parameters are enough. ?IIRC if I recall correctly, Win32 has a way to > > examine how much time a process has owned so far, and a way to > > terminate it, which could be in Python's future. > > There is support for imposing limits on processes in the Python > standard library: > > http://docs.python.org/lib/node521.html > > My experimental package, jailtools, relies on each process's sandbox > being set up explicitly before the process is run, so you'd definitely > want to copy data into the sandbox. Setting limits on the amount of > data produced would probably require support from the operating > system. Generally, when looking into these kinds of systems, most of > the solutions ultimately come from the operating system: process > control, resource utilisation, access control, and so on. (This is the > amusing thing about Java: that Sun attempted to reproduce lots of > things that a decent operating system would provide *and* insist on > their use when deploying Java code in a controlled server environment, > despite actually having a decent operating system to offer already.) > > > PyPy sandbox says: ?"The C code generated by PyPy is not > > segfaultable." ?I find that to be a bold claim (whether it's true or > > not). > > > I'm imagining in the general case, you want the foreign code to make > > changes to objects in your particular context, such as exec x in > > vars. ?In that case, x can still be productive without any libraries, > > just less productive. > > Defining an interface between trusted and untrusted code can be > awkward. When I looked into this kind of thing for my undergraduate > project, I ended up using something similar to CORBA, and my > conclusion was that trusted code would need to expose an interface > that untrusted "agents" would rely on to request operations outside > the sandbox. That seems restrictive, but as the situation with rexec > has shown, if you expose a broad interface to untrusted programs, it > becomes increasingly difficult to verify whether or not the solution > is actually secure. > > Paul I think you could autogenerate a file with a copy of the data, then run a bare bones Python installation with the foreign code that imports the copy, or just concatenate the foreign code and copy. At least for input. For output, you'd need a file that had an upper bound on its size. The problem with Python is that if an agent has access to a part of an object, it has the whole thing. Such as the trusted agents-- if they can perform an operation, then anything with access to the agent can. If they're just policy makers, then however an authorized agent performs the action, is available to an unauthorized one. You'd still need a 'struct' instance to write your output, since memory is upper- bounded, and you can't permit foreign code to store any form of Python objects. From gagsl-py2 at yahoo.com.ar Tue Sep 2 04:36:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 05:36:33 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> Message-ID: <op.uguh67a1x6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 01 Sep 2008 04:23:38 -0300, Jeremy Banks <jeremy at jeremybanks.ca> escribi?: > Hi. I wondered if anyone knew the rationale behind the naming of the > Popen class in the subprocess module. Popen sounds like the a suitable > name for a function that created a subprocess, but the object itself is > a subprocess, not a "popen". It seems that it would be more accurate to > just name the class Subprocess, can anyone explain why this is not the > case? I have no idea - but I agree, Subprocess would have been a better name. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Wed Sep 3 23:11:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 04 Sep 2008 00:11:45 -0300 Subject: email.Message problem References: <20080902160417.GA20438@zephyr> <op.ugvdd1oyx6zn5v@a98gizw.cpe.telecentro.net.ar> <20080903103630.GC11421@zephyr> Message-ID: <op.ugxshvhvx6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 03 Sep 2008 07:36:30 -0300, Corrado Gioannini <gioco at nekhem.com> escribi?: > On Tue, Sep 02, 2008 at 04:50:15PM -0300, Gabriel Genellina wrote: >> > messg = email.message.Message() >> >> Replace this line with: >> messg = email.mime.multipart.MIMEMultipart() >> *OR* >> Set the Content-Type header to "multipart/mixed" *before* anything else. > > thanks Gabriel! > > i coudn't have thought that setting the header in a different order > could affect the as_string method. i'll take a look at the code. :) Yes. This is the offending sequence: messg = email.message.Message() messg.set_charset('ISO-8859-15') messg["Content-type"] = "Multipart/mixed" "Charset" is not a header by itself; it is an optional parameter of the Content-Type header. When you call set_charset(), a default 'Content-Type: text/plain; charset="ISO-8859-15"' header is added. Later, you *add* a new Content-type header -- remember that the [] notation *appends* a new header instead of replacing an existing one (yes, it is somewhat confusing...) Your message ends up being text/plain, not multiplart as intended. It's better to be explicit and use the email.mime.multipart.MIMEMultipart class. -- Gabriel Genellina From samslists at gmail.com Thu Sep 18 04:57:26 2008 From: samslists at gmail.com (Sam) Date: Thu, 18 Sep 2008 01:57:26 -0700 (PDT) Subject: Program works great, except under less, cron or execl (Unicode?) Message-ID: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> I have a program which works great when run from the command line. But when I run it combined with something else such as: - piping it through less - cron - execl (i.e. calling it from another python program) it gives me a unicode error File "../myparser.py", line 261, in set_attributes print "self.atd['Name'] is: ", self.atd['Name'] UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 7: ordinal not in range(128) I'd post the whole program here, except it involves weird Unicode strings. I could probably change the program to get it working under less/cron/ etc. But I'd rather understand exactly what the issue is. Why does it work fine when run directly from the command line, but not otherwise? From inq1ltd at inqvista.com Mon Sep 22 14:43:25 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Mon, 22 Sep 2008 14:43:25 -0400 Subject: Problems running on hp dual core processor Message-ID: <200809221443.25765.inq1ltd@inqvista.com> Python help, I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duel core processor, 2.2G with .099g ram. On the new hp, when they try to print they get an import error; File win32ui.pyc line 12, in <module> File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. The file is there The only difference I could find from their other machines is the processor. From george.sakkis at gmail.com Tue Sep 30 11:04:35 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 30 Sep 2008 08:04:35 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> <87zllqqa1i.fsf@benfinney.id.au> <pan.2008.09.30.10.04.18@REMOVE.THIS.cybersource.com.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> Message-ID: <0b229c8f-61cf-4617-8927-5627edadc9b9@m36g2000hse.googlegroups.com> On Sep 30, 9:43 am, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: > > Steven D'Aprano <ste... at REMOVE.THIS.cybersource.com.au> writes: > > >> On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > >> > You're not free to modify gnuplot and redistribute the result. > > >> > That you're free to distribute patches is nice, but it's not enough > >> > to make the work free. The freedom to help people by giving them an > >> > *already-modified* gnuplot is restricted by the copyright holder. > > >> > It's an artificial restriction on redistribution of derived works, > >> > making them second-class for the prupose of getting them into > >> > people's hands. > > >> Yes it is. It seems a strange, unnecessary restriction. But is it > >> sufficient to make it non-free? I don't think so. > > > I do, because a natural, beneficial act (modify the work and > > redistribute it) that has no technical reason to restrict, is > > artifically restricted. > > We agree that the restriction is artificial, and I think irrational > (although I'd be interested in hearing the gnuplot developers' reasoning > before making a final judgment). > > But I just don't see the requirement that modified software be > distributed in form X (original source + diffs) versus form Y (modified > source in a tar ball) or form Z (an rpm) to be that big a deal. Not > enough to make it "non-free software". > > I simply don't think that having to run some variation on > > patch -i patchfile.patch > > is a requirement so onerous that it makes the gnuplot licence non-free. > Perhaps I'm just more tolerant of eccentricities than you :) What you're missing is that for Free Software (TM) zealots it's a matter of philosophical principle, totally unrelated to how easy is to overcome the restriction. There is not a "practicality beats purity" clause in the FSF Bible. George From maric at aristote.info Wed Sep 3 10:44:10 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 3 Sep 2008 16:44:10 +0200 Subject: properties setting each other In-Reply-To: <g9m54v$hvk$1@ger.gmane.org> References: <g9m54v$hvk$1@ger.gmane.org> Message-ID: <200809031644.10870.maric@aristote.info> Le Wednesday 03 September 2008 15:57:50 mk, vous avez ?crit?: > I try to set two properties, "value" and "square" in the following code, > and arrange it in such way that setting one property also sets another > one and vice versa. But the code seems to get Python into infinite loop: > > ?>>> import math > ?>>> class Squared2(object): > > ????????def __init__(self, val): > ????????????????self._internalval=val > ????????????????self.square=pow(self._internalval,2) > ???????????????? > ????????def fgetvalue(self): > ????????????????return self._internalval > ???????????????? > ????????def fsetvalue(self, val): > ????????????????self._internalval=val > ????????????????self.square=pow(self._internalval,2) > ???????????????? > ????????value = property(fgetvalue, fsetvalue) > > ????????def fgetsquare(self): > ????????????????return self.square > ????????def fsetsquare(self,s): > ????????????????self.square = s > ????????????????self.value = math.sqrt(self.square) > ???????????????? > ????????square = property(fgetsquare, fsetsquare) > > ???????? > ?>>> a=Squared2(5) > > Traceback (most recent call last): > ? ?File "<pyshell#11>", line 1, in <module> > ? ? ?a=Squared2(5) > ? ?File "<pyshell#10>", line 5, in __init__ > ? ? ?self.square=pow(self._internalval,2) > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > ? ? ?self.square = s > ? ?File "<pyshell#10>", line 19, in fsetsquare > > ... > > Is there a way to achieve this goal of two mutually setting properties? Your square property is not correctly defined, it recurselively call itself, it should be (I also avoided the extra lookup) : def fgetsquare(self): return self._square def fsetsquare(self,s): self._square = s self.value = math.sqrt(s) then the fsetvalue will be also be called recursively as it use the square property, you should also write it : def fsetvalue(self, val): self._internalval=val self._square=pow(val,2) *but*, if you want to add more logic in the setters, you could want to add two extra methods : def _setsquare(self, v) : # some extra logic here self._square = s def fsetsquare(self,s): self._setsquare(s) self._setvalue = math.sqrt(s) def _setvalue(self, val): # some extra logic here self._internalval=val def fsetvalue(self, val): self._setvalue(val) self._setsquare=pow(val,2) Note that if one property can really be computed from another, this kind of thing could be considered as bad design (except if the computation is heavy). -- _____________ Maric Michaud From steve at REMOVE-THIS-cybersource.com.au Wed Sep 3 21:30:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 01:30:39 GMT Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <yfs63pcwyip.fsf@gmail.com> Message-ID: <00cf34ad$0$20302$c3e8da3@news.astraweb.com> On Thu, 04 Sep 2008 01:22:22 +0100, Alexander Schmolck wrote: > It seems to me that the right choice for thousands seperator is the > apostrophe. You mean the character already used as a string delimiter? -- Steven From febkimbleox at gmail.com Sat Sep 27 07:17:55 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:17:55 -0700 (PDT) Subject: amateur sex amateur sex videos amateur sex video free amateur sex - Free Message-ID: <6256a559-08a6-4da4-8ae9-6ed51ca5d26b@r66g2000hsg.googlegroups.com> amateur . . . *******CLICK HERE******** http://vids365.cn/amateur ***************************** . . . . . . . . . . . . She could feel the love amateur had for amateur radiate through amateur and amateur made amateur quiver with desire. She could feel the love sex had for sex radiate through sex and sex made sex quiver with desire. She could feel the love amateur had for amateur radiate through amateur and amateur made amateur quiver with desire. She could feel the love sex had for sex radiate through sex and sex made sex quiver with desire. She could feel the love videos had for videos radiate through videos and videos made videos quiver with desire. She could feel the love amateur had for amateur radiate through amateur and amateur made amateur quiver with desire. She could feel the love sex had for sex radiate through sex and sex made sex quiver with desire. She could feel the love video had for video radiate through video and video made video quiver with desire. She could feel the love free had for free radiate through free and free made free quiver with desire. She could feel the love amateur had for amateur radiate through amateur and amateur made amateur quiver with desire. She could feel the love sex had for sex radiate through sex and sex made sex quiver with desire. The following week videos spent a lot of time chatting online with her. The following week free spent a lot of time chatting online with her. The following week amateur spent a lot of time chatting online with her. The following week sex spent a lot of time chatting online with her. The following week amateur spent a lot of time chatting online with her. The following week teen spent a lot of time chatting online with her. The following week sex spent a lot of time chatting online with her. The following week amateur spent a lot of time chatting online with her. The following week sex spent a lot of time chatting online with her. The following week movies spent a lot of time chatting online with her. The following week amateur spent a lot of time chatting online with her. The following week sex spent a lot of time chatting online with her. ?Afterwards, tube fluffed the pillow, straightened the blanket, and then spooned up against tube . ?Afterwards, free fluffed the pillow, straightened the blanket, and then spooned up against free . ?Afterwards, amateur fluffed the pillow, straightened the blanket, and then spooned up against amateur . ?Afterwards, sex fluffed the pillow, straightened the blanket, and then spooned up against sex . ?Afterwards, video fluffed the pillow, straightened the blanket, and then spooned up against video . ?Afterwards, amateur fluffed the pillow, straightened the blanket, and then spooned up against amateur . ?Afterwards, group fluffed the pillow, straightened the blanket, and then spooned up against group . ?Afterwards, sex fluffed the pillow, straightened the blanket, and then spooned up against sex . ?Afterwards, amateur fluffed the pillow, straightened the blanket, and then spooned up against amateur . ?Afterwards, home fluffed the pillow, straightened the blanket, and then spooned up against home . ?Afterwards, sex fluffed the pillow, straightened the blanket, and then spooned up against sex . ?Afterwards, videos fluffed the pillow, straightened the blanket, and then spooned up against videos . amateur was a little way ahead of amateur and amateur could see amateur body start to shake with silent tears. home was a little way ahead of home and home could see home body start to shake with silent tears. sex was a little way ahead of sex and sex could see sex body start to shake with silent tears. amateur was a little way ahead of amateur and amateur could see amateur body start to shake with silent tears. home was a little way ahead of home and home could see home body start to shake with silent tears. sex was a little way ahead of sex and sex could see sex body start to shake with silent tears. video was a little way ahead of video and video could see video body start to shake with silent tears. amateur was a little way ahead of amateur and amateur could see amateur body start to shake with silent tears. couples was a little way ahead of couples and couples could see couples body start to shake with silent tears. sex was a little way ahead of sex and sex could see sex body start to shake with silent tears. videos was a little way ahead of videos and videos could see videos body start to shake with silent tears. long was a little way ahead of long and long could see long body start to shake with silent tears. Valentine?s Day was just around the corner and tapes wanted to do something special for Mandy. Valentine?s Day was just around the corner and amateur wanted to do something special for Mandy. Valentine?s Day was just around the corner and couple wanted to do something special for Mandy. Valentine?s Day was just around the corner and sex wanted to do something special for Mandy. Valentine?s Day was just around the corner and sex wanted to do something special for Mandy. Valentine?s Day was just around the corner and amateur wanted to do something special for Mandy. Valentine?s Day was just around the corner and amateur wanted to do something special for Mandy. Valentine?s Day was just around the corner and anal wanted to do something special for Mandy. Valentine?s Day was just around the corner and sex wanted to do something special for Mandy. Valentine?s Day was just around the corner and amateur wanted to do something special for Mandy. Valentine?s Day was just around the corner and lesbian wanted to do something special for Mandy. Valentine?s Day was just around the corner and sex wanted to do something special for Mandy. As my eyes became used to the dim light amateur could see a darker shadow between the wardrobes and found amateur hiding there. As my eyes became used to the dim light sex could see a darker shadow between the wardrobes and found sex hiding there. As my eyes became used to the dim light tapes could see a darker shadow between the wardrobes and found tapes hiding there. As my eyes became used to the dim light amateur could see a darker shadow between the wardrobes and found amateur hiding there. As my eyes became used to the dim light sex could see a darker shadow between the wardrobes and found sex hiding there. As my eyes became used to the dim light clips could see a darker shadow between the wardrobes and found clips hiding there. As my eyes became used to the dim light amateur could see a darker shadow between the wardrobes and found amateur hiding there. As my eyes became used to the dim light sex could see a darker shadow between the wardrobes and found sex hiding there. As my eyes became used to the dim light tape could see a darker shadow between the wardrobes and found tape hiding there. As my eyes became used to the dim light teen could see a darker shadow between the wardrobes and found teen hiding there. As my eyes became used to the dim light amateur could see a darker shadow between the wardrobes and found amateur hiding there. As my eyes became used to the dim light sex could see a darker shadow between the wardrobes and found sex hiding there. As the mushroom head went deeper inside, real eyes widened and Mandy began to pant. As the mushroom head went deeper inside, amateur eyes widened and Mandy began to pant. As the mushroom head went deeper inside, sex eyes widened and Mandy began to pant. As the mushroom head went deeper inside, amateur eyes widened and Mandy began to pant. As the mushroom head went deeper inside, sex eyes widened and Mandy began to pant. As the mushroom head went deeper inside, photos eyes widened and Mandy began to pant. As the mushroom head went deeper inside, free eyes widened and Mandy began to pant. As the mushroom head went deeper inside, amateur eyes widened and Mandy began to pant. As the mushroom head went deeper inside, home eyes widened and Mandy began to pant. As the mushroom head went deeper inside, sex eyes widened and Mandy began to pant. As the mushroom head went deeper inside, videos eyes widened and Mandy began to pant. As the mushroom head went deeper inside, amateur eyes widened and Mandy began to pant. As the mushroom head went deeper inside, college eyes widened and Mandy began to pant. ? He filled the wine bucket with ice, popped the cork, set the bottle in vids to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in free to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in naked to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in amateur to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in sex to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in videos to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in sites to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in mature to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in amateur to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in sex to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in amateur to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in sex to chill, and then took two goblets over to the table. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by party thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by amateur thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by oral thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by sex thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by homemade thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by amateur thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by sex thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by amateur thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by interracial thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by sex thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by videos thick, shoulder length auburn hair. She still had a little angelic face, with big brown eyes, small nose and neat little mouth all framed by amateur thick, shoulder length auburn hair. sex really got worried when four months passed and sex hadn?t heard anything. pics really got worried when four months passed and pics hadn?t heard anything. amateur really got worried when four months passed and amateur hadn?t heard anything. gay really got worried when four months passed and gay hadn?t heard anything. sex really got worried when four months passed and sex hadn?t heard anything. amateur really got worried when four months passed and amateur hadn?t heard anything. mature really got worried when four months passed and mature hadn?t heard anything. sex really got worried when four months passed and sex hadn?t heard anything. young really got worried when four months passed and young hadn?t heard anything. amateur really got worried when four months passed and amateur hadn?t heard anything. sex really got worried when four months passed and sex hadn?t heard anything. free really got worried when four months passed and free hadn?t heard anything. amateur really got worried when four months passed and amateur hadn?t heard anything. That was when I realized it ? sex tits were real. That was when I realized it ? pics tits were real. That was when I realized it ? amateur tits were real. That was when I realized it ? mom tits were real. That was when I realized it ? sex tits were real. That was when I realized it ? amateur tits were real. That was when I realized it ? couples tits were real. That was when I realized it ? sex tits were real. That was when I realized it ? hot tits were real. That was when I realized it ? amateur tits were real. That was when I realized it ? sex tits were real. That was when I realized it ? amateur tits were real. wife couldn?t take looking at wife name on my arm after that, the memories were too much for wife to handle. sex couldn?t take looking at sex name on my arm after that, the memories were too much for sex to handle. amateur couldn?t take looking at amateur name on my arm after that, the memories were too much for amateur to handle. sex couldn?t take looking at sex name on my arm after that, the memories were too much for sex to handle. movie couldn?t take looking at movie name on my arm after that, the memories were too much for movie to handle. amateur couldn?t take looking at amateur name on my arm after that, the memories were too much for amateur to handle. doggy couldn?t take looking at doggy name on my arm after that, the memories were too much for doggy to handle. sex couldn?t take looking at sex name on my arm after that, the memories were too much for sex to handle. amateur couldn?t take looking at amateur name on my arm after that, the memories were too much for amateur to handle. homemade couldn?t take looking at homemade name on my arm after that, the memories were too much for homemade to handle. sex couldn?t take looking at sex name on my arm after that, the memories were too much for sex to handle. gay couldn?t take looking at gay name on my arm after that, the memories were too much for gay to handle. amateur breasts bounced from being released. sex breasts bounced from being released. amateur breasts bounced from being released. beach breasts bounced from being released. sex breasts bounced from being released. amateur breasts bounced from being released. sex breasts bounced from being released. pictures breasts bounced from being released. amateur breasts bounced from being released. sex breasts bounced from being released. sex breasts bounced from being released. amateur breasts bounced from being released. ?Mandy looked into videos eyes and confessed, ?Oh honey, videos seem to always know what to say. ?Mandy looked into amateur eyes and confessed, ?Oh honey, amateur seem to always know what to say. ?Mandy looked into hardcore eyes and confessed, ?Oh honey, hardcore seem to always know what to say. ?Mandy looked into sex eyes and confessed, ?Oh honey, sex seem to always know what to say. ?Mandy looked into amateur eyes and confessed, ?Oh honey, amateur seem to always know what to say. ?Mandy looked into sex eyes and confessed, ?Oh honey, sex seem to always know what to say. ?Mandy looked into scene eyes and confessed, ?Oh honey, scene seem to always know what to say. ?Mandy looked into amateur eyes and confessed, ?Oh honey, amateur seem to always know what to say. ?Mandy looked into outdoor eyes and confessed, ?Oh honey, outdoor seem to always know what to say. ?Mandy looked into sex eyes and confessed, ?Oh honey, sex seem to always know what to say. ?Mandy looked into amateur eyes and confessed, ?Oh honey, amateur seem to always know what to say. ?Mandy looked into webcam eyes and confessed, ?Oh honey, webcam seem to always know what to say. sex big breasts moved up and down, bouncing slightly. amateur big breasts moved up and down, bouncing slightly. asian big breasts moved up and down, bouncing slightly. sex big breasts moved up and down, bouncing slightly. amateur big breasts moved up and down, bouncing slightly. black big breasts moved up and down, bouncing slightly. sex big breasts moved up and down, bouncing slightly. amateur big breasts moved up and down, bouncing slightly. girlfriend big breasts moved up and down, bouncing slightly. sex big breasts moved up and down, bouncing slightly. amateur big breasts moved up and down, bouncing slightly. interracial big breasts moved up and down, bouncing slightly. His eyes went glassy with lust and sex moaned, ?Ooooh Fuck!?He continued to watch as sex slid sex hand down to sex tit. His eyes went glassy with lust and free moaned, ?Ooooh Fuck!?He continued to watch as free slid free hand down to free tit. His eyes went glassy with lust and amateur moaned, ?Ooooh Fuck!?He continued to watch as amateur slid amateur hand down to amateur tit. His eyes went glassy with lust and sex moaned, ?Ooooh Fuck!?He continued to watch as sex slid sex hand down to sex tit. His eyes went glassy with lust and clips moaned, ?Ooooh Fuck!?He continued to watch as clips slid clips hand down to clips tit. His eyes went glassy with lust and free moaned, ?Ooooh Fuck!?He continued to watch as free slid free hand down to free tit. His eyes went glassy with lust and amateur moaned, ?Ooooh Fuck!?He continued to watch as amateur slid amateur hand down to amateur tit. His eyes went glassy with lust and swingers moaned, ?Ooooh Fuck!?He continued to watch as swingers slid swingers hand down to swingers tit. His eyes went glassy with lust and sex moaned, ?Ooooh Fuck!?He continued to watch as sex slid sex hand down to sex tit. His eyes went glassy with lust and videos moaned, ?Ooooh Fuck!?He continued to watch as videos slid videos hand down to videos tit. His eyes went glassy with lust and teen moaned, ?Ooooh Fuck!?He continued to watch as teen slid teen hand down to teen tit. His eyes went glassy with lust and sex moaned, ?Ooooh Fuck!?He continued to watch as sex slid sex hand down to sex tit. He cupped amateur breasts and massaged them slowly. He cupped interracial breasts and massaged them slowly. He cupped amateur breasts and massaged them slowly. He cupped sex breasts and massaged them slowly. He cupped videos breasts and massaged them slowly. He cupped amateur breasts and massaged them slowly. He cupped sex breasts and massaged them slowly. He cupped films breasts and massaged them slowly. He cupped amateur breasts and massaged them slowly. He cupped sex breasts and massaged them slowly. He cupped video breasts and massaged them slowly. He cupped clips breasts and massaged them slowly. However, right now, my dick is screaming to make love to you!?Mandy pulled amateur lips down hard on hers, feeling the love amateur shared clear to the center of amateur soul. However, right now, my dick is screaming to make love to you!?Mandy pulled dog lips down hard on hers, feeling the love dog shared clear to the center of dog soul. However, right now, my dick is screaming to make love to you!?Mandy pulled sex lips down hard on hers, feeling the love sex shared clear to the center of sex soul. However, right now, my dick is screaming to make love to you!?Mandy pulled amateur lips down hard on hers, feeling the love amateur shared clear to the center of amateur soul. However, right now, my dick is screaming to make love to you!?Mandy pulled sex lips down hard on hers, feeling the love sex shared clear to the center of sex soul. However, right now, my dick is screaming to make love to you!?Mandy pulled blog lips down hard on hers, feeling the love blog shared clear to the center of blog soul. However, right now, my dick is screaming to make love to you!?Mandy pulled nude lips down hard on hers, feeling the love nude shared clear to the center of nude soul. However, right now, my dick is screaming to make love to you!?Mandy pulled amateur lips down hard on hers, feeling the love amateur shared clear to the center of amateur soul. However, right now, my dick is screaming to make love to you!?Mandy pulled sex lips down hard on hers, feeling the love sex shared clear to the center of sex soul. However, right now, my dick is screaming to make love to you!?Mandy pulled amateur lips down hard on hers, feeling the love amateur shared clear to the center of amateur soul. However, right now, my dick is screaming to make love to you!?Mandy pulled animal lips down hard on hers, feeling the love animal shared clear to the center of animal soul. However, right now, my dick is screaming to make love to you!?Mandy pulled sex lips down hard on hers, feeling the love sex shared clear to the center of sex soul. I assured amateur that amateur was not at fault and that amateur understood and had the same feelings. I assured coed that coed was not at fault and that coed understood and had the same feelings. I assured sex that sex was not at fault and that sex understood and had the same feelings. I assured amateur that amateur was not at fault and that amateur understood and had the same feelings. I assured sex that sex was not at fault and that sex understood and had the same feelings. I assured videos that videos was not at fault and that videos understood and had the same feelings. I assured 40 that 40 was not at fault and that 40 understood and had the same feelings. I assured year that year was not at fault and that year understood and had the same feelings. I assured old that old was not at fault and that old understood and had the same feelings. I assured women that women was not at fault and that women understood and had the same feelings. I assured british that british was not at fault and that british understood and had the same feelings. I assured amateur that amateur was not at fault and that amateur understood and had the same feelings. I assured sex that sex was not at fault and that sex understood and had the same feelings. ?It excited mature more when mature talked dirty. ?It excited sex more when sex talked dirty. ?It excited amateur more when amateur talked dirty. ?It excited amateur more when amateur talked dirty. ?It excited couples more when couples talked dirty. ?It excited sex more when sex talked dirty. ?It excited videos more when videos talked dirty. ?It excited amateur more when amateur talked dirty. ?It excited sex more when sex talked dirty. ?It excited video more when video talked dirty. ?It excited free more when free talked dirty. ?It excited asian more when asian talked dirty. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Next Tammy was told to lay on sex back on the couch and spread sex legs. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Next Tammy was told to lay on forced back on the couch and spread forced legs. Next Tammy was told to lay on sex back on the couch and spread sex legs. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Next Tammy was told to lay on sex back on the couch and spread sex legs. Next Tammy was told to lay on stories back on the couch and spread stories legs. Next Tammy was told to lay on sex back on the couch and spread sex legs. Next Tammy was told to lay on party back on the couch and spread party legs. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Next Tammy was told to lay on amateur back on the couch and spread amateur legs. Mandy licked couples lips, kicked off couples heels and then removed couples bra and panties. Mandy licked having lips, kicked off having heels and then removed having bra and panties. Mandy licked sex lips, kicked off sex heels and then removed sex bra and panties. Mandy licked amateur lips, kicked off amateur heels and then removed amateur bra and panties. Mandy licked sex lips, kicked off sex heels and then removed sex bra and panties. Mandy licked for lips, kicked off for heels and then removed for bra and panties. Mandy licked cash lips, kicked off cash heels and then removed cash bra and panties. Mandy licked amateur lips, kicked off amateur heels and then removed amateur bra and panties. Mandy licked sex lips, kicked off sex heels and then removed sex bra and panties. Mandy licked forum lips, kicked off forum heels and then removed forum bra and panties. Mandy licked amateur lips, kicked off amateur heels and then removed amateur bra and panties. Mandy licked videos lips, kicked off videos heels and then removed videos bra and panties. I looked sex in the eyes and whispered, I'm sorry. I looked free in the eyes and whispered, I'm sorry. I looked amateur in the eyes and whispered, I'm sorry. I looked sex in the eyes and whispered, I'm sorry. I looked galleries in the eyes and whispered, I'm sorry. I looked adult in the eyes and whispered, I'm sorry. I looked amateur in the eyes and whispered, I'm sorry. I looked sex in the eyes and whispered, I'm sorry. I looked videos in the eyes and whispered, I'm sorry. I looked amateur in the eyes and whispered, I'm sorry. I looked home in the eyes and whispered, I'm sorry. I looked sex in the eyes and whispered, I'm sorry. I looked tape in the eyes and whispered, I'm sorry. After this, amateur tongue finds amateur clit, and begins flicking it. After this, indian tongue finds indian clit, and begins flicking it. After this, sex tongue finds sex clit, and begins flicking it. After this, amateur tongue finds amateur clit, and begins flicking it. After this, phone tongue finds phone clit, and begins flicking it. After this, sex tongue finds sex clit, and begins flicking it. After this, amateur tongue finds amateur clit, and begins flicking it. After this, teenager tongue finds teenager clit, and begins flicking it. After this, sex tongue finds sex clit, and begins flicking it. After this, amateur tongue finds amateur clit, and begins flicking it. After this, video tongue finds video clit, and begins flicking it. After this, sex tongue finds sex clit, and begins flicking it. Sweet milk squirted into my mouth as amateur went from nipple to nipple. Sweet milk squirted into my mouth as voyeur went from nipple to nipple. Sweet milk squirted into my mouth as sex went from nipple to nipple. Sweet milk squirted into my mouth as college went from nipple to nipple. Sweet milk squirted into my mouth as amateur went from nipple to nipple. Sweet milk squirted into my mouth as sex went from nipple to nipple. Sweet milk squirted into my mouth as couple went from nipple to nipple. Sweet milk squirted into my mouth as sex went from nipple to nipple. Sweet milk squirted into my mouth as amateur went from nipple to nipple. Sweet milk squirted into my mouth as amateur went from nipple to nipple. Sweet milk squirted into my mouth as hidden went from nipple to nipple. Sweet milk squirted into my mouth as cam went from nipple to nipple. He lowers sex shorts, wraps sex fingers around sex swelling cock and begins stroking sex slowly, feeling sex pulsating and harden in sex hands. He lowers amateur shorts, wraps amateur fingers around amateur swelling cock and begins stroking amateur slowly, feeling amateur pulsating and harden in amateur hands. He lowers hidden shorts, wraps hidden fingers around hidden swelling cock and begins stroking hidden slowly, feeling hidden pulsating and harden in hidden hands. He lowers camera shorts, wraps camera fingers around camera swelling cock and begins stroking camera slowly, feeling camera pulsating and harden in camera hands. He lowers sex shorts, wraps sex fingers around sex swelling cock and begins stroking sex slowly, feeling sex pulsating and harden in sex hands. He lowers amateur shorts, wraps amateur fingers around amateur swelling cock and begins stroking amateur slowly, feeling amateur pulsating and harden in amateur hands. He lowers home shorts, wraps home fingers around home swelling cock and begins stroking home slowly, feeling home pulsating and harden in home hands. He lowers sex shorts, wraps sex fingers around sex swelling cock and begins stroking sex slowly, feeling sex pulsating and harden in sex hands. He lowers movies shorts, wraps movies fingers around movies swelling cock and begins stroking movies slowly, feeling movies pulsating and harden in movies hands. He lowers amateur shorts, wraps amateur fingers around amateur swelling cock and begins stroking amateur slowly, feeling amateur pulsating and harden in amateur hands. He lowers sex shorts, wraps sex fingers around sex swelling cock and begins stroking sex slowly, feeling sex pulsating and harden in sex hands. He lowers forums shorts, wraps forums fingers around forums swelling cock and begins stroking forums slowly, feeling forums pulsating and harden in forums hands. I told amateur to leave amateur alone and leave with amateur stuff, he came over to amateur and stuck the gun right in my face and told amateur he would kill us both if amateur didn't do as he asked. I told sex to leave sex alone and leave with sex stuff, he came over to sex and stuck the gun right in my face and told sex he would kill us both if sex didn't do as he asked. I told home to leave home alone and leave with home stuff, he came over to home and stuck the gun right in my face and told home he would kill us both if home didn't do as he asked. I told video to leave video alone and leave with video stuff, he came over to video and stuck the gun right in my face and told video he would kill us both if video didn't do as he asked. I told amateur to leave amateur alone and leave with amateur stuff, he came over to amateur and stuck the gun right in my face and told amateur he would kill us both if amateur didn't do as he asked. I told teen to leave teen alone and leave with teen stuff, he came over to teen and stuck the gun right in my face and told teen he would kill us both if teen didn't do as he asked. I told sex to leave sex alone and leave with sex stuff, he came over to sex and stuck the gun right in my face and told sex he would kill us both if sex didn't do as he asked. I told video to leave video alone and leave with video stuff, he came over to video and stuck the gun right in my face and told video he would kill us both if video didn't do as he asked. From akineko at gmail.com Tue Sep 16 13:46:47 2008 From: akineko at gmail.com (akineko) Date: Tue, 16 Sep 2008 10:46:47 -0700 (PDT) Subject: A unique instance of Python GUI program References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> <mailman.1100.1221555458.3487.python-list@python.org> Message-ID: <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> On Sep 16, 1:58?am, Tim Golden <m... at timgolden.me.uk> wrote: > I swear this question's been asked twice this month already. Thank you very much for many pointers. I'm awfully sorry for posting something that is already answered in the past. I tried to find answers to my problem using "unique instance" as a keyword. I guess I should have used "single instance" or "one instance", instead. I will try to be more careful before posting. Thank you. Aki Niimura From mario at ruggier.org Wed Sep 3 03:28:26 2008 From: mario at ruggier.org (mario) Date: Wed, 3 Sep 2008 00:28:26 -0700 (PDT) Subject: eval() == evil? --- How to use it safely? References: <d836e712-0dbd-4caf-a32b-99c3c3cc1c16@z66g2000hsc.googlegroups.com> Message-ID: <98d905fd-539b-4101-8c71-4447ae9232d6@34g2000hsh.googlegroups.com> On Aug 28, 11:51 pm, Fett <FettMan... at gmail.com> wrote: > I am creating a program that requires some data that must be kept up > to date. What I plan is to put this data up on a web-site then have > the program periodically pull the data off the web-site. > > My problem is that when I pull the data (currently stored as a > dictionary on the site) off the site, it is a string, I can use eval() > to make that string into a dictionary, and everything is great. > However, this means that I am using eval() on some string on a web- > site, which seems pretty un-safe. > > I read that by using eval(code,{"__builtins__":None},{}) I can prevent > them from using pretty much anything, and my nested dictionary of > strings is still allowable. What I want to know is: > > What are the dangers of eval? > - I originally was using exec() but switched to eval() because I > didn't want some hacker to be able to delete/steal files off my > clients computers. I assume this is not an issue with eval(), since > eval wont execute commands. > - What exactly can someone do by modifying my code string in a command > like: thing = eval(code{"__builtins__":None},{}), anything other than > assign their own values to the object thing? If you like to look at a specific attempt for making eval() safe(r) take a look at how the **eval-based** Evoque Templating engine does it, for which a short overview is here: http://evoque.gizmojo.org/usage/restricted/ While it does not provide protection against DOS type attacks, it should be safe against code that tries to pirate tangible resources off your system, such as files and disk. Actually, any problems anyone may find are greatly appreciated... From gagsl-py2 at yahoo.com.ar Sun Sep 21 13:55:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Sep 2008 14:55:47 -0300 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> <gb3bvk$9a1$1@ger.gmane.org> <27CC3060AF71DA40A5DC85F7D5B70F38051C09F2@AWMAIL04.belcan.com> Message-ID: <op.uhucuzo8x6zn5v@a98gizw.noga> En Sat, 20 Sep 2008 16:07:12 -0300, Blubaugh, David A. <dblubaugh at belcan.com> escribi?: > Let me state that do have extensive experience with developing binary > files. Please note that I have followed all of the instructions to the > letter as far as developing a DLL to be imported. However, it is not > working correctly. I believe it might be my system environment > variables?? It might be the sunspots (or the lack of them) as well. You could start telling us what's your platform, which instructions have you followed, which compiler have you used... -- Gabriel Genellina From castironpi at gmail.com Sat Sep 20 17:07:26 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 14:07:26 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> Message-ID: <2c0a8279-e888-4ae5-90a2-f2f1bb137607@x41g2000hsb.googlegroups.com> On Sep 20, 3:22?pm, Kay Schluehr <kay.schlu... at gmx.net> wrote: > On 20 Sep., 18:33, Bruno Desthuilliers > > <bdesth.quelquech... at free.quelquepart.fr> wrote: > > The following definitions are AFAIK the only commonly accepted > > definitions about OO: > > > 1/ an object is defined by identity, state and behaviour > > 2/ objects interacts by sending messages each other > > 3/ an OO program is made of interacting objects > > > I let you find out whether Python meets these 3 definitions - and if > > Java does (hint : in Python, everything you can bind to a name is an > > object - this is not true in Java or C++). > > This is correct but it detracts from a more general problem of > language "paradigms". > > Assume you type > > >>> 2+2 > > 4 > > Now you are free to interpret this as a simple, primitive arithmetic > operation but you can also claim that 2 sends an __add__ message to 2. > Hereby the state of the 2 objects are not altered but a new 4 object > is created. OO babble is more impressive isn't it? > > Actually it is simply wrong in the mentioned case and here is the > proof: > > def foo(): > ? ? return 2+2 > > import dis > dis.dis(foo) > > ? 2 ? ? ? ? ? 0 LOAD_CONST ? ? ? ? ? ? ? 2 (4) > ? ? ? ? ? ? ? 3 RETURN_VALUE > > OO is a heuristic method used to understand the semantics of a > programming language. It can also inspire language design but as > you've rightly said: jugde yourself and see how far you get with it. > > Applying OO on interpreter level is by no means a sign of a high > quality implementation whereas structuring programs in the large will > likely benefit from class based organization and encapsulation. Of > course one can also reverse the value hierarchy and find perverse joy > in having a pure OO language but apply monkey patching everywhere. I > suppose you know which language I'm talking about... It sounds like you think that you -can- write OO programs in Python, but you don't have to. I agree. From blabla at dungeon.de Thu Sep 11 11:48:52 2008 From: blabla at dungeon.de (hofer) Date: Thu, 11 Sep 2008 08:48:52 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Message-ID: <b4470822-e893-4b5f-893e-28c39e71dddb@m73g2000hsh.googlegroups.com> Thanks a lot for all your answers. There's quite some things I learnt :-) [v1,v2,v3] = ... can be typed as v1,v2,v3 = . . . I also wasn't used to map(myhash.get, ['one', 'two', 'two']) itemgetter('one', 'one', 'two')(x) I also didn't know print "%(one)s\n%(two)s\n%(two)s" % mydict The reason I'd like to have a short statement for above is, that this is for me basically just some code, to name and use certain fields of a hash in i given code section. The real example would be more like: name,age,country = itemgetter('name age country'.split())(x) # or any of my above versions # a lot of code using name / age / country thanks a gain and bye H On Sep 10, 5:28?pm, hofer <bla... at dungeon.de> wrote: > Let's take following perl code snippet: > > %myhash=( one ?=> 1 ? ?, two ? => 2 ? ?, three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' ? : 1 ? ?, 'two' ? : 2 ? ?, 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as ?split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] > > print "%s\n%s\n%s" %(v1,v2,v3) From hancock.robert at gmail.com Tue Sep 23 15:11:03 2008 From: hancock.robert at gmail.com (Robert Hancock) Date: Tue, 23 Sep 2008 12:11:03 -0700 (PDT) Subject: Twisted: Get Protected HTTPS Page via Proxy with Authentication References: <f60bd2dd-b97a-4ba0-b89c-443019208111@m44g2000hsc.googlegroups.com> Message-ID: <e197ef5f-9619-4a4b-b1ea-8ef2a97e53a1@k13g2000hse.googlegroups.com> This works: # Proxy credentials proxyAuth = base64.encodestring('%s:%s' % (proxy_username, proxy_password)) proxy_authHeader = "Basic " + proxyAuth.strip() # Web site credentials basicAuth = base64.encodestring('%s:%s' % (username, password)) authHeader = "Basic " + basicAuth.strip() return client.getPage(url, headers={"Authorization": authHeader, 'Proxy-Authenticate': proxy_authHeader}) From circularfunc at yahoo.se Tue Sep 2 14:02:03 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 2 Sep 2008 11:02:03 -0700 (PDT) Subject: Large amount of files to parse/organize, tips on algorithm? References: <a8ca9f87-4bf8-4a74-b4ee-902ff3d328ab@x35g2000hsb.googlegroups.com> <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> Message-ID: <613f7386-7d6a-4dd4-a06e-f1cc0ccb641c@k7g2000hsd.googlegroups.com> On Sep 2, 7:06?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Tue, 02 Sep 2008 09:48:32 -0700, cnb wrote: > > I have a bunch of files consisting of moviereviews. > > > For each file I construct a list of reviews and then for each new file I > > merge the reviews so that in the end have a list of reviewers and for > > each reviewer all their reviews. > > > What is the fastest way to do this? > > Use the timeit module to find out. > > > 1. Create one file with reviews, open next file an for each review see > > if the reviewer exists, then add the review else create new reviewer. > > > 2. create all the separate files with reviews then mergesort them? > > The answer will depend on whether you have three reviews or three > million, whether each review is twenty words or twenty thousand words, > and whether you have to do the merging once only or over and over again. > > -- > Steven I merge once. each review has 3 fields, date rating customerid. in total ill be parsing between 10K and 100K, eventually 450K reviews. From joe.g at optusnet.com.au Thu Sep 18 11:47:45 2008 From: joe.g at optusnet.com.au (Joe G (Home)) Date: Fri, 19 Sep 2008 01:47:45 +1000 Subject: Installing pySerial Message-ID: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Hi All, Background =================== I have installed Python for windows today from the python web site .I also installed pySerial using the Windows installer from the sourceforge web site..... Both installs use the default directories. Phyton version : Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 pySerial 2.4 July 6th Problem : Errors Screen output ============================ >>> import serial Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import serial File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in <module> from serialwin32 import * File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in <module> import win32file # The base COM port and file IO functions. ImportError: No module named win32file >>> So it looks like Python can not see some of the modules Here's the active paths >>> print sys.path ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages'] >>> It seems that C:\Python25\Lib\site-packages\serial needs to be added to the PYTHONPATH QUESTION ============= Q1. How do I add C:\Python25\Lib\site-packages\serial to the PYTHONPATH ? Q2. How do I check that I have installed pySerial corretly (using the Windows installer) Thanks in advance Joe From ldo at geek-central.gen.new_zealand Mon Sep 29 05:15:09 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:15:09 +1300 Subject: how to search multiple textfiles ? (Python is slow ?) References: <mailman.1536.1222436146.3487.python-list@python.org> <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> <mailman.1566.1222464403.3487.python-list@python.org> Message-ID: <gbq6at$iiq$3@lust.ihug.co.nz> In message <mailman.1566.1222464403.3487.python-list at python.org>, Stef Mientki wrote: > - Pyscripter 110 sec ( PyScripter is the default IDE I use now) > - Delphi 20 .. 35 sec > - Findstr 4 sec What order did you try try them in? Did you try each one more than once, in different orders? Just to rule out filesystem caching effects. > I'm really amazed by the speed of Python !! > It can only be beaten by findstr, which is only available on windows. Did you try find -exec grep -F? From kyosohma at gmail.com Wed Sep 24 09:29:08 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Sep 2008 06:29:08 -0700 (PDT) Subject: How to copy a GUI2exe project - to serve as basis for new project ? References: <mailman.12523.1222237400.3486.python-list@python.org> <mailman.1445.1222242860.3487.python-list@python.org> Message-ID: <2f15e7e1-a6d0-4800-ba29-47c035710326@k7g2000hsd.googlegroups.com> On Sep 24, 2:54?am, "Barak, Ron" <Ron.Ba... at lsi.com> wrote: > Hi, > > In GUI2exe, I'd like to create a project that is different from an existing project only in a few details (e.g., the location of the 'dist' directory). > Is there a way to copy a current project - so it would serve as a basis for a new project ? > > Bye, > Ron. Not that I'm aware of. You should post this to the wxPython users group and see if the author can add this feature. I know he just added a "Save Project As" option, but I can't get it to work right. Mike From clp at rebertia.com Wed Sep 17 02:19:07 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 16 Sep 2008 23:19:07 -0700 Subject: how many objects are loaded for hello world? In-Reply-To: <ee471449-3fa1-4f4d-86db-d2ec8843114f@b30g2000prf.googlegroups.com> References: <ee471449-3fa1-4f4d-86db-d2ec8843114f@b30g2000prf.googlegroups.com> Message-ID: <47c890dc0809162319u55033bffg6927e03c52e7dede@mail.gmail.com> On Tue, Sep 16, 2008 at 11:13 PM, belred <belred at gmail.com> wrote: > i just read this blog about how many objects (types) are loaded for a > hello world program in C#. > > http://blogs.msdn.com/abhinaba/archive/2008/09/15/how-many-types-are-loaded-for-hello-world.aspx > > how can you find out how many are loaded for a python program: print > 'hello' Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> len(dir(__builtins__)) 134 Regards, Chris > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From mail at timgolden.me.uk Tue Sep 30 15:22:40 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 30 Sep 2008 20:22:40 +0100 Subject: [Tutor] Replacing cmd.exe with custom .py application In-Reply-To: <eb90f15e0809301209x11a260d5pdcd6e59c08605502@mail.gmail.com> References: <ea09b3700809300732vafc8d52oca6a73d95b63eb33@mail.gmail.com> <eb90f15e0809301113p61bafe22y179d546b3719f51d@mail.gmail.com> <eb90f15e0809301209x11a260d5pdcd6e59c08605502@mail.gmail.com> Message-ID: <48E27C80.6030905@timgolden.me.uk> Ezra Taylor wrote: > Is there something similar to /dev/null on Windows? NUL: TJG From ivan.illarionov at gmail.com Fri Sep 5 20:09:44 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Fri, 5 Sep 2008 17:09:44 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> <acdc94a1-9f8c-49f3-b063-dd536e480d07@v39g2000pro.googlegroups.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> <48c03b91$0$14747$426a74cc@news.free.fr> <fc6a6c32-a023-4d6e-9089-bbcfc42de8d5@a8g2000prf.googlegroups.com> <6id16uFq5171U1@mid.uni-berlin.de> Message-ID: <688970a9-5791-4d73-8896-5e055dfd519f@m73g2000hsh.googlegroups.com> On 5 ????, 19:23, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > Ivan Illarionov schrieb: > > > > > On 4 ????, 21:49, Bruno Desthuilliers > > <bdesth.quelquech... at free.quelquepart.fr> wrote: > >> Ivan Illarionov a ?crit : > > >>> On 4 ????, 22:59, Carl Banks <pavlovevide... at gmail.com> wrote: > >>>> You can write code to guard against this if you want: > >>>> class A: > >>>> legal = set(["x"]) > >>>> def __setattr__(self,attr,val): > >>>> if attr not in self.legal: > >>>> raise AttributeError("A object has no attribute '%s'" % > >>>> attr) > >>>> self.__dict__[attr] = val > >>>> def __init__(self,x): > >>>> self.y = x > >>>> I suspect most people who go into Python doing something like this > >>>> soon abandon it when they see how rarely it actually catches anything. > >>> '__slots__' is better: > >> For which definition of "better" ? __slots__ are a mean to optimize > >> memory usage, not to restrict dynamism. Being able to dynamically add > >> arbitrary attributes is actually a feature, not a bug, and uselessly > >> restricting users from doing so is not pythonic. IOW : don't do that. > > > Carl's example is restricting dynamism in the same way as __slots__. > > I've just suggested a better implementation. It is not me who > > suggested dynamism restriction as a way to guard against errors. > > This is not correct. While Carl's Example looks similar, you actually > *can* create new attributes using > > obj.__dict__['name'] = value > > __slots__ OTOH prevents that because it does create instances *without* > an instance-dict. > > This being said, I think we all agree that it's nothing to be desired. > > Diez +1 for unit tests as a way to guard against errors. Bot sometimes __slots__ is exactly what I want (for other reasons) and I like to avoid __getattr__ hacks in any situation. Ivan From afriere at yahoo.co.uk Wed Sep 24 22:49:48 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 24 Sep 2008 19:49:48 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <f5a4027b-4b9b-4d09-b76b-11d50b8070eb@p31g2000prf.googlegroups.com> <zllxzcpt.fsf@wgmail2.gatwick.eur.slb.com> <beeea088-c336-465e-a24c-160f5c56a2c4@p10g2000prf.googlegroups.com> <c4817afc-d588-4807-8e45-25d22988652c@59g2000hsb.googlegroups.com> Message-ID: <c5d2674a-e580-4429-be8e-4b67cdbed5fc@a2g2000prm.googlegroups.com> On Sep 25, 11:57 am, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 24, 8:40 pm, Asun Friere <afri... at yahoo.co.uk> wrote: > > ... I think > > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding > > all variables for placeholders in the tuple, is better. It's certainly > > more readible. > > It's a different answer if you have 'things is/are'. '%d thing%s %s'% > ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ). Or excluding > prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's > are' if i!= 1 else ' is' ). Forgive me for being dull, my caffeine levels have not yet optimal, but I don't follow. Both the solutions you propose do put all the placeholder variables in the tuple. Or are you saying it no longer remains readible? BTW you repeated my mistake with the first scraplet of code. From aonlazio at gmail.com Mon Sep 8 17:35:19 2008 From: aonlazio at gmail.com (AON LAZIO) Date: Mon, 8 Sep 2008 17:35:19 -0400 Subject: class(object) and (type)?? Message-ID: <f9e39bbc0809081435kd5c3b32x36f4f615fd00f3a0@mail.gmail.com> Hi again pythoners, I notice in the class of a code having (object) and (type) attached to the name of the class. I know that in other cases, that means the class inherits methods and properties from other but In this case, what does it mean? For example, class PY(object): def __init__(self): ... class PO(type): def __init__(self): ... What do "object" and "type" mean? Thanks in advance Aonlazio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/faaf3b74/attachment-0001.html> From burns.matthew at verizon.net Wed Sep 3 13:51:45 2008 From: burns.matthew at verizon.net (Matthew Burns) Date: Wed, 03 Sep 2008 10:51:45 -0700 Subject: Help on try-except In-Reply-To: <mailman.3232.1220399834.3486.python-list@python.org> References: <mailman.3232.1220399834.3486.python-list@python.org> Message-ID: <000001c90ded$bc5224c0$34f66e40$@matthew@verizon.net> The reason it takes so long is you are not using xrange The range function iterates through the entire data set EVERY time, regardless of whether it needs to This increases processer use EXPONENTIALLY as that number gets larger. I am not quite sure how xrange works, but it keeps only one number in memory at any time In fact, I never use range any more, I always use xrange. ALL YOUR BASE ARE BELONG TO US http://allyourbase.planettribes.gamespy.com/video1_view.shtml -----Original Message----- From: python-list-bounces+burns.matthew=verizon.net at python.org [mailto:python-list-bounces+burns.matthew=verizon.net at python.org] On Behalf Of python-list-request at python.org Sent: Tuesday, September 02, 2008 4:57 PM To: python-list at python.org Subject: Python-list Digest, Vol 60, Issue 30 Send Python-list mailing list submissions to python-list at python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to python-list-request at python.org You can reach the person managing the list at python-list-owner at python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Python-list digest..." From paul at boddie.org.uk Sat Sep 6 19:14:54 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 6 Sep 2008 16:14:54 -0700 (PDT) Subject: Multicore-programming? References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: <e8c6e812-5479-4059-b2fe-3a151aec8638@f36g2000hsa.googlegroups.com> On 7 Sep, 00:06, cnb <circularf... at yahoo.se> wrote: > If I buy a multicore computer and I have really intensive program. How > would that be distributed across the cores? It typically depends on how the work done by the program is performed. > Will algorithms always have to be programmed and told specifically to > run on several cores so if not told it will only utilize one core? Some algorithms lend themselves to parallelisation; others do not. Sometimes tools and runtimes can help by executing some instructions in parallel. > So is the free lunch really over or is this just an overhyped > phenomena? The free lunch ended a few minutes ago. ;-) > Is threading with Python hard? Can you start several processes with > Python or just threads? You can start both processes and threads with Python, although the effect of starting many threads - the actual concurrency - will depend on which implementation of Python you're using and where the bulk of the work is performed. If you're spending a lot of CPU time in processing data, and if that processing is taking place in Python code, then for the most effective threading you should consider an implementation like Jython or IronPython which supports free-threading. If most of the work happens in extension code (where you'd probably have little choice about using CPython, anyway), then it might be the case that the extension releases the global interpreter lock in CPython and you might then be able to benefit from having many threads doing work simultaneously, although I imagine that the extension would itself need to be thread- safe, too. If you're spending a lot of time moving data around, performing communication, and so on, then multiple threads may still be effective in CPython, since some of them might be getting a system call to read or write data, thus freeing the CPU for the others. These kinds of situations lend themselves to other approaches such as asynchronous processing of data, however. It doesn't sound like this is like your program, if by "intensive" you mean high levels of CPU activity. As you note, the alternative to threads is processes, and many people advocate multi-process, "shared nothing" solutions. Here's a list which covers multicore and SMP-related solutions as well as high-end clustering solutions: http://wiki.python.org/moin/ParallelProcessing Although the processing module is part of Python 2.6/3.0 as the multiprocessing module, you might want to at least look at the pp, pprocess and papyros solutions. My aim with pprocess was to target multicore UNIX-like systems with an unintrusive API; pp and papyros, on the other hand, seek to cover larger scale systems as well, and I think that the way papyros has been done has some merit, mostly because if you wanted to combine convenience with distributed processing, you'd want to choose distributed object technologies as the foundation (CORBA would have been good for this, too, at least for multi-language support, but its APIs can also seem quite intimidating). Paul From alan.isaac at gmail.com Sat Sep 6 19:30:03 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sat, 06 Sep 2008 23:30:03 GMT Subject: Numeric literal syntax In-Reply-To: <87ej43pcy0.fsf@benfinney.id.au> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: <%nEwk.681$sq3.240@trnddc07> > bearophileHUGS at lycos.com writes: > >> For Python 2.7/3.1 I'd now like to write a PEP regarding the >> underscores into the number literals, like: 0b_0101_1111, 268_435_456 >> etc. > > +1 on such a capability. > > -1 on underscore as the separator. On 9/1/2008 9:13 PM Ben Finney apparently wrote: > When you proposed this last year, the counter-proposal was made > <URL:http://groups.google.com/group/comp.lang.python/msg/18123d100bba63b8?dmode=source> > to instead use white space for the separator, exactly as one can now > do with string literals. Yuck. Repeating a mistake means two mistakes. But I would hate less the use of nobreak spaces, since any decent editor can reveal them. Alan Isaac From pfreixes at gmail.com Mon Sep 15 05:58:48 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Mon, 15 Sep 2008 11:58:48 +0200 Subject: PyArg_ParseTuple for parsing list and dictionary arguments Message-ID: <207312b70809150258n57240c25me70ad03b6339b579@mail.gmail.com> Hi to all, What's the best way for parse one list or dict argument with PyArg_ParseTuple Function ? If I have this python code : import example example.test("hellow", ["a", "b"], { "a" : 1 }) The c extension for implementation test function must be like this : static PyObject * test( PyObject *self, PyObject *args) { PyObject * dict, * list; char * string; PyArg_ParseTuple(args, "sOO", string, dict, list); ...... } -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/97aad3e8/attachment-0001.html> From wuwei23 at gmail.com Thu Sep 25 00:11:18 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 24 Sep 2008 21:11:18 -0700 (PDT) Subject: multiple processes with private working dirs References: <gbdttg$fuq$1@foggy.unx.sas.com> Message-ID: <473d008f-f3c4-4894-9251-b7fc9cf4c8e4@p10g2000prf.googlegroups.com> On Sep 25, 3:37?am, "Tim Arnold" <tim.arn... at sas.com> wrote: > Am I missing something? Do you mean something other than the replies you got the last time you asked the exact same question? http://groups.google.com/group/comp.lang.python/browse_frm/thread/42c13cbb84f88f2b From exarkun at divmod.com Wed Sep 24 13:29:15 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 24 Sep 2008 13:29:15 -0400 Subject: Twisted vs. CherryPy vs. ??? for light-weight web servers In-Reply-To: <170543c70809231922m23531eb9i1f7fdead10bb1e0e@mail.gmail.com> Message-ID: <20080924172915.29191.775453525.divmod.quotient.30199@ohm> On Tue, 23 Sep 2008 21:22:08 -0500, Michael Mabin <d3vvnull at gmail.com> wrote: >Is there any consensus on what the best lightweight web-server is? Or >rather would Twisted be a better choice to choose as a framework that allows >me to serve html or xml data for light webservices. Or is CherryPy just as >good? > You haven't described the problem you want to solve in very much detail. I can't tell, for example, why I shouldn't recommend that you use Apache instead of CherryPy or Twisted or anything else. Apache has a huge user community, lots of documentation, and lots of developers fixing its bugs and making it work well. What are you trying to do that would make Apache a bad choice? Jean-Paul From m_palmer45 at yahoo.ca Wed Sep 3 12:34:32 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 3 Sep 2008 09:34:32 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? Message-ID: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> As anyone knows, the state of Python GUI programming is a little fractured at this time, with many toolkits, wrappers and meta-wrappers dead and alive, with or without documentation. I've come across two projects that have the appeal of striving for simple, pythonic APIs: PyGUI and wax. The latter is a wrapper around wxPython. It is lacking documentation but actually quite usable and concise. The other, PyGUI, has an even nicer API and more docs but has relatively few widgets implemented at this time. It also strives for compatibility with several toolkits (two at this time), which I think is the right idea. So far, development of PyGUI seems to be a one-man effort, and it may be slowed down by the attempt to develop the API and the implementations concurrently. Could it be useful to uncouple the two, such that the API would be specified ahead of the implementation? This might make it easier for people to contribute implementation code and maybe port the API to additional toolkits. It seems that this approach has been quite successful in case of the Python database API. That API defines levels of compliance, which might be a way of accommodating different GUI toolkits as well. I may be underestimating the difficulties of my proposed approach - I don't have much practical experience with GUI programming myself. Best, Michael From victor.prosolin at gmail.com Fri Sep 26 10:22:27 2008 From: victor.prosolin at gmail.com (Fly Away) Date: Fri, 26 Sep 2008 07:22:27 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <mailman.1520.1222400746.3487.python-list@python.org> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> Message-ID: <09cae8bd-f8ac-4c4a-a920-0e6e3f6a3a64@w1g2000prk.googlegroups.com> > Matlab's strongest side is data visualization though. Although we have > matplotlib, mayavi and possibility of interfacing with gnuplot, it's > not anywhere near the capabilities of Matlab. What particular Matlab visualization features are you referring to? I can't think of anything that would justify using the "not anywhere near" term. Cheers, Victor. From gherlylukita at gmail.com Wed Sep 24 15:51:01 2008 From: gherlylukita at gmail.com (gherlylu) Date: Wed, 24 Sep 2008 12:51:01 -0700 (PDT) Subject: Buy Vicodin...convenient, discreet online pharmacy. oylr3 Message-ID: <5c8c4c7b-0a00-4dff-8c4a-7402dea81609@p25g2000hsf.googlegroups.com> Start saving, best online pharmacy here http://fjmgilbh.zarubanlo.net/?acdekbhxwvrsyfjmzchcmgil From gminick at bzt.bzt Thu Sep 4 06:16:41 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 4 Sep 2008 10:16:41 +0000 (UTC) Subject: Issue warning if no "return" in function? References: <g9obtp$l83$1@gwdu112.gwdg.de> Message-ID: <g9oci8$576$1@inews.gazeta.pl> On Thu, 04 Sep 2008 12:05:45 +0200, Poster28 wrote: > What would you suggest to check python programs for non-syntax error. > One example I could think of that one might forget to "return" a value from > a function. > > How could I check for these and maybe other mistakes? Check pychecker or figleaf: http://pychecker.sourceforge.net http://darcs.idyll.org/~t/projects/figleaf/doc/ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From stef.mientki at gmail.com Thu Sep 25 15:38:56 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 21:38:56 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <Xns9B24589F2DBEOKB@199.45.49.11> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> <Xns9B24589F2DBEOKB@199.45.49.11> Message-ID: <48DBE8D0.4040708@gmail.com> I found a partial workaround that is good enough for me: def Get_Windows_Filename ( FileName ) : if os.name == 'nt' : File = os.path.splitext ( FileName .lower ())[0] return glob.glob ( File + '.p?' ) return FileName This will translate the filename into the correct case, but not the path. I also looked at os.path.walk, but that's too slow for me, because getting the path correct means I have to start at the root. cheers, Stef From marco.bizzarri at gmail.com Fri Sep 5 09:04:22 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 15:04:22 +0200 Subject: Core dumped while interacting with OpenOffice.org via pyuno Message-ID: <3f0d61c40809050604y42bc494bqa6c91cb1cc3cd913@mail.gmail.com> Hi all. I'm experiencing a core dump while working in the following environment - debain etch - python2.3 - openoffice.org 2.4 - Zope 2.8.8 I was able to get a core dump, and the backtrace shows the following: Core was generated by `python2.3 tests/testActs.py'. Program terminated with signal 11, Segmentation fault. #0 0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 (gdb) bt #0 0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 #1 0xb6b547d3 in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 #2 0xb6b531d2 in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 #3 0xb6b53748 in uno_threadpool_enter () from /usr/lib/openoffice/program/libuno_cppu.so.3 #4 0xb5c80c8c in ?? () from /usr/lib/openoffice/program/liburp_uno.so #5 0xb5c7d1e8 in ?? () from /usr/lib/openoffice/program/liburp_uno.so #6 0xb5c8710e in ?? () from /usr/lib/openoffice/program/liburp_uno.so #7 0xb5c8727c in ?? () from /usr/lib/openoffice/program/liburp_uno.so #8 0xb5c76a62 in ?? () from /usr/lib/openoffice/program/liburp_uno.so #9 0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3 #10 0x08797840 in ?? () #11 0x0989b6e0 in ?? () #12 0x00000000 in ?? () Now, I can understand that the information I provided are not enough to give me suggestions on solving this issue; so, I'm asking suggesions on investigating the issue, namely: - should I ask here or is it better if I ask on a openoffice forum? - should I use a debug-enabled python in order to have more meaningful backtraces? - is there something else I should do in order to have more clues ("Read The Fine Manual (tm)" is an acceptable answer) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From rridge at csclub.uwaterloo.ca Wed Sep 10 12:28:55 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 10 Sep 2008 12:28:55 -0400 Subject: universal unicode font for reportlab References: <ga6loq$jpj$1@rumours.uwaterloo.ca> <mailman.785.1221053660.3487.python-list@python.org> <Xns9B159F78E43Dduncanbooth@127.0.0.1> Message-ID: <ga8sk7$7bg$1@rumours.uwaterloo.ca> Duncan Booth <duncan.booth at suttoncourtenay.org.uk> wrote: >I thought that usually when you embed a font in a PDF only the glyphs which >are actually used in the document get embedded. Unfortunately a quick test >with reportlab seems to show that it doesn't do that optimisation: it looks >as though it just embeds the entire font. Yah, PDF files normally only contain an embedded subset of the fonts used. It might possible to use Ghostscript's ps2pdf command (which can take a PDF file as input) to strip out the unused glyphs from the embedded fonts. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From ggpolo at gmail.com Mon Sep 1 20:52:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 1 Sep 2008 21:52:39 -0300 Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp In-Reply-To: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Message-ID: <ac2200130809011752t2bed51br7cc14facbf51854b@mail.gmail.com> On Mon, Sep 1, 2008 at 7:45 PM, akineko <akineko at gmail.com> wrote: > Hi everyone, > > This is a memorandum so that other people can share the info. > > The following methods are declared in the Tkinter Button class. > tkButtonDown(), tkButtonEnter(), tkButtonInvoke(), tkButtonLeave(), > tkButtonUp() > However, they are not working, when you try, you will get: > > _tkinter.TclError: invalid command name "tkButtonLeave" > > The bindings in the Tkinter are mapping them to non-existing tk > methods. > I needed to use the method badly and I couldn't find any clear > solution for this. Are you trying to simulate clicks ? You should be doing it using event_generate, more below. > So, I spent time to solve this. > > tkButtonLeave(), for example, is declared as follows: > > Tkinter.py line 2005 of 3759 > def tkButtonLeave(self, *dummy): > self.tk.call('tkButtonLeave', self._w) > > Now, in the Tk source distribution, I found the following: > unsupported.tcl > # Commands provided by Tk without official support. Use them at your > # own risk. They may change or go away without notice. > > namespace eval ::tk::unsupported { > > # Map from the old global names of Tk private commands to their > # new namespace-encapsulated names. > > variable PrivateCommands > array set PrivateCommands { > tkButtonAutoInvoke ::tk::ButtonAutoInvoke > tkButtonDown ::tk::ButtonDown > tkButtonEnter ::tk::ButtonEnter > tkButtonInvoke ::tk::ButtonInvoke > tkButtonLeave ::tk::ButtonLeave > tkButtonUp ::tk::ButtonUp > ... snip ... You are looking at the wrong place, try looking at library/button.tcl Now, why I said about using event_generate instead of calling those methods yourself.. tk sets several bindings that varies between platforms for all these things you are trying to do, and they end up calling these commands you are trying to call yourself. So, for instance, given that you have a button: btn = Tkinter.Button() to get tk::ButtonEnter called, you should be doing: btn.event_generate("<Enter>") and this will work for other those other events too, Leave (Leave), Button-1 (Down), ButtonRelease-1 (Up), space (Invoke). The remaining one to talk about is this "ButtonAutoInvoke", which I'm unsure if you really need it, but, if you do, you could use btn.invoke() supposing the button has an associated callback which will use "after" to schedule another btn.invoke(). > > This seems suggesting that the Tkinter bindings are binding obsolete > tk methods. > And, the method should be called seems ::tk::ButtonLeave, instead. > > I placed the following into my Tkinter code and it worked. > self.btn.tk.call('::tk::ButtonLeave', self.btn._w) > > // > Summary: > (1) tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, > tkButtonUp are not working. > (2) Bindings are not correct > (2) Workaround is call correct tk methods directly > > I hope future Tkinter will be corrected so that the methods are > available as documented. You should expect them to be totally removed from Tkinter actually. > > Best regards, > Aki- > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:36:22 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:36:22 GMT Subject: urllib error on urlopen References: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> Message-ID: <00eaf2fa$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 08:46:56 -0700, Mike Driscoll wrote: > Hi, > > I have been using the following code for over a year in one of my > programs: > > f = urllib2.urlopen('https://www.companywebsite.com/somestring') > > It worked great until the middle of the afternoon yesterday. Now I get > the following traceback: ... > URLError: <urlopen error (1, 'error:140770FC:SSL > routines:SSL23_GET_SERVER_HELLO:unknown protocol')> Have you recently set a proxy where Python can auto-detect it? I understand that urllib2 doesn't work well with https proxies. If so, you can instruct urllib2 not to use a proxy-handler, but it's more work. What I do is construct an opener without a proxyhandler: # untested... no_proxy_support = urllib2.ProxyHandler({}) opener = urllib2.build_opener(no_proxy_support) f = opener.open('https://www.companywebsite.com/somestring') If that doesn't work, you may need to build a Request object from the URL before passing it to opener.open. -- Steven From jcd at sdf.lonestar.org Tue Sep 16 15:07:57 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 16 Sep 2008 15:07:57 -0400 Subject: append on lists In-Reply-To: <O5SdnZPu6e3hJFLVnZ2dnUVZ_v3inZ2d@posted.visi> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> <87d4j4798g.fsf@mulj.homelinux.net> <O5SdnZPu6e3hJFLVnZ2dnUVZ_v3inZ2d@posted.visi> Message-ID: <1221592077.30028.2.camel@aalcdl07.lib.unc.edu> On Tue, 2008-09-16 at 08:49 -0500, Grant Edwards wrote: > On 2008-09-16, Hrvoje Niksic <hniksic at xemacs.org> wrote: > > Duncan Booth <duncan.booth at invalid.invalid> writes: > > > >> The only relatively common use I can think of where you might want to call > >> a method directly on a literal is to produce a list of strings while being > >> lazy about the typing: > > > > By far the most common is probably 'sep'.join(iterable). > > It's also somewhat common to index into a literal: > > ['one','two','three'][n] > > {1:'one', 2:'two', 7:'seven'}[n] > Indeed. I use this for setting variables based on hostname on a website. Say, for example, you run on port 80 on one host, but on a test host, you share with several other sites, and run on 8084, you can do the following import socket port = { 'www.example.com': 80, 'dev.example.com': 8084, }[socket.gethostname()] It's a handy idiom. Cheers, Cliff From ldo at geek-central.gen.new_zealand Fri Sep 26 03:41:34 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 19:41:34 +1200 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> <mailman.1295.1221905698.3487.python-list@python.org> <ee99e813-97e0-404c-a512-748d0d148f8c@b1g2000hsg.googlegroups.com> Message-ID: <gbi3ne$s8a$1@lust.ihug.co.nz> In message <ee99e813-97e0-404c-a512-748d0d148f8c at b1g2000hsg.googlegroups.com>, Aaron "Castironpi" Brady wrote: > Wikipedia puts it decently: "mainly for OO programming, but with some > procedural elements." "Procedural" is the opposite of "functional", not "object-oriented". From shahmed at sfwmd.gov Thu Sep 11 08:33:01 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 11 Sep 2008 08:33:01 -0400 Subject: removing text string In-Reply-To: <xqWdnQ2Hm7s1vlXVnZ2dnUVZ_sLinZ2d@earthlink.com> References: <loom.20080910T144026-626@post.gmane.org><mailman.814.1221069201.3487.python-list@python.org> <xqWdnQ2Hm7s1vlXVnZ2dnUVZ_sLinZ2d@earthlink.com> Message-ID: <A86D1A0C2B238848B9ABDE1A7E287CE6010E1373@EXCHVS01.ad.sfwmd.gov> Thanks Actually the number I am getting it is from slicing from a long text line. I need to slice 10 characters from that line but no string only numeric numbers. When I am slicing 10 characters those A, c, O is coming at the end. Thanks -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of Dennis Lee Bieber Sent: Wednesday, September 10, 2008 3:45 PM To: python-list at python.org Subject: Re: removing text string On Wed, 10 Sep 2008 11:22:16 -0400, "Ahmed, Shakir" <shahmed at sfwmd.gov> declaimed the following in comp.lang.python: > I need to remove text string from the list of the numbers mentioned > below: > > 080829-7_A > 070529-5_c > 080824-7_O > 070405_6_p > ? Is that last one an error that is supposed to be ...5-6_, not ...5_6_ ? 1) If the required data is fixed width, just slice it out = inp[:8] 2) If the data is variable width but has a fixed delimiter, find the delimiter position and then slice (this is the reason for my question above -- this method) OR just split on the delimiter and take the part you need. out = inp.split("_")[0] 3) If the data is more complex (again if that last line with two _ is supposed to be trimmed after the second, and the first turned into a -) you will need to fully define the parsing rules of the data. -- Wulfraed Dennis Lee Bieber KD6MOG wlfraed at ix.netcom.com wulfraed at bestiaria.com HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: web-asst at bestiaria.com) HTTP://www.bestiaria.com/ -- http://mail.python.org/mailman/listinfo/python-list From george.sakkis at gmail.com Tue Sep 30 11:23:23 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 30 Sep 2008 08:23:23 -0700 (PDT) Subject: Shed Skin (restricted) Python-to-C++ compiler 0.0.29 References: <mailman.1734.1222769964.3487.python-list@python.org> Message-ID: <6ccb7642-2df8-45ee-b304-74c92d520e0e@d31g2000hsg.googlegroups.com> On Sep 30, 6:19 am, "Mark Dufour" <mark.duf... at gmail.com> wrote: > Hi all, > > I have just released Shed Skin 0.0.29, with the following changes. Not to sound negative, but what's with the 0.0.x version numbers ? Maybe it's just me, but seeing a zero major/minor version give me the impression of experimental/pre-alpha project, which (from my very limited knowledge) doesn't do justice to shedskin's current state. Regardless, congrats for this great effort, hope it gains more prominence in the future! George From carsten.haese at gmail.com Tue Sep 30 13:55:15 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 30 Sep 2008 13:55:15 -0400 Subject: r"<path>" In-Reply-To: <33077c9c-01d9-4423-afd2-7452117bc6b4@j22g2000hsf.googlegroups.com> References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> <CltEk.1298$fD.324@flpi145.ffdc.sbc.com> <33077c9c-01d9-4423-afd2-7452117bc6b4@j22g2000hsf.googlegroups.com> Message-ID: <7KtEk.2082$YU2.1499@nlpi066.nbdc.sbc.com> Kyle Hayes wrote: >> Please describe the actual problem you're trying to solve. In what way >> do slashes need to be "fixed," and why? > > Well, I have decided to build a tool to help us sync files in UNC > paths. I am just building the modules and classes right now so I > haven't developed the frontend yet. I am assuming when the user > provides a path (either by typing it in, or pulling it in from a > config file), the UNC slashes are going to escape stuff in the string, > so I want to double them up. That assumption is incorrect. While backslashes in string literals are escape characters that must be doubled up to convey literal backslashes, no such interpretation is made for backslashes that are read from a GUI text box or from a file. See for yourself: >>> some_string = raw_input("Enter a string: ") Enter a string: blah\blah\blah >>> print some_string blah\blah\blah Carry on and come back when you actually have a problem ;) -- Carsten Haese http://informixdb.sourceforge.net From timr at probo.com Mon Sep 22 23:24:18 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 23 Sep 2008 03:24:18 GMT Subject: curses.setsyx()? References: <f4bfa060-3053-4ca6-90c2-2a057bfedf79@34g2000hsh.googlegroups.com> <tqd6d4po3dmvba3a3v1a8c2b34qgfmc8d9@4ax.com> <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> Message-ID: <naogd45497jn4s8jegu15j4u1oo49cinqc@4ax.com> linkmaster032000 at gmail.com wrote: >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: >> On Sep 19, 1:24?am, Tim Roberts <t... at probo.com> wrote: >> >> > linkmaster032... at gmail.com wrote: >> >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses >> > >cursor. Any alternatives/solutions? >> >> > Did you call doupdate after? ?setsyx just manipulates the data structures. >> > It takes a call to doupdate to force those changes to take effect visually. >> > -- >> > Tim Roberts, t... at probo.com >> > Providenza & Boekelheide, Inc. >> >> I added it and it still doesn't work. This is what I'm doing when I >> want to display the cursor and prepare it for input at 2,3: >> >> curses.echo() >> curses.curs_set(1) >> curses.setsyx(2,3) >> curses.doupdate() > >Any idea what's wrong? No. Are you able to post an entire sample that demonstrates the problem? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From timr at probo.com Mon Sep 1 00:24:29 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 01 Sep 2008 04:24:29 GMT Subject: Python 3.0b2 cannot map '\u12b' References: <d0652dd2-24f6-4045-89a8-ba6deaf25b37@c65g2000hsa.googlegroups.com> Message-ID: <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> josh logan <dear.jay.logan at gmail.com> wrote: > >I am using Python 3.0b2. >I have an XML file that has the unicode character '\u012b' in it, >which, when parsed, causes a UnicodeEncodeError: > >'charmap' codec can't encode character '\u012b' in position 26: >character maps to <undefined> > >This happens even when I assign this character to a reference in the >interpreter: > >Python 3.0b2 (r30b2:65106, Jul 18 2008, 18:44:17) [MSC v.1500 32 bit >(Intel)] on > win32 >Type "help", "copyright", "credits" or "license" for more information. >>>> s = '\u012b' >>>> s >Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "C:\Python30\lib\io.py", line 1428, in write > b = encoder.encode(s) > File "C:\Python30\lib\encodings\cp437.py", line 19, in encode > return codecs.charmap_encode(input,self.errors,encoding_map)[0] >UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in >position >1: character maps to <undefined> > >Is this a known issue, or am I doing something wrong? Both. U+012B is the Latin lower-case i with macron (i with a bar instead of a dot). That character does not exist in the 8-bit character set CP437, which you are trying to use. If you choose an 8-bit character set that includes i-with-macron, then it will work. UTF-8 would be a good choice. It's in ISO-8859-10. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From circularfunc at yahoo.se Mon Sep 15 05:36:24 2008 From: circularfunc at yahoo.se (cnb) Date: Mon, 15 Sep 2008 02:36:24 -0700 (PDT) Subject: Emacs, loading file into interpreter doesn't work Message-ID: <4bad07d8-8ead-4cdb-ad8b-c2e55abab06e@m3g2000hsc.googlegroups.com> Python-mode worked right out out of the box in Emacs and then I added Python to my path so now the interpreter works as well. However when I try to load a file(that is not located in site- packages) it doesn't work. >>> Traceback (most recent call last): ImportError: No module named parsing It is fairly impractical to work with if that doesn't work and cut and pasting doesn't work(not that it is a good alternative in the first place) because of Python being intendation-sensitive. Can I add something to my .emacs-file to solve this? From gherlylukita at gmail.com Wed Sep 24 15:36:10 2008 From: gherlylukita at gmail.com (gherlylu) Date: Wed, 24 Sep 2008 12:36:10 -0700 (PDT) Subject: Quick & Secured Pharmacy Online. rdjr0 Message-ID: <f14b6d02-afae-4c11-a022-33ae145d3838@y21g2000hsf.googlegroups.com> Start saving, best online pharmacy here http://fjmgilbh.zarubanlo.net/?acdekbhxwvrsyfjmzchcmgil From prologic at shortcircuit.net.au Thu Sep 11 03:40:33 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 17:40:33 +1000 Subject: Use Python to solve equations? In-Reply-To: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> References: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Message-ID: <e1a84d570809110040g51bc003ahac0dd35da34573dd@mail.gmail.com> Hi Kelie, Check out sympy it is capable of doing things like this. cheers James On Thu, Sep 11, 2008 at 5:09 PM, Kelie <kf9150 at gmail.com> wrote: > Hello group, > > Is there any packages in Python that will help me solve functions > similar to this: > > x = a*(1+bx)**2.5-c where a, b, c is known and the task to solve x? > > Thank you, > > Kelie > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From python at rcn.com Tue Sep 2 11:18:54 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 2 Sep 2008 08:18:54 -0700 (PDT) Subject: dict.update References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> Message-ID: <1b79577e-d74b-461f-ac0c-6841d3c22251@t1g2000pra.googlegroups.com> On Sep 2, 8:04?am, Mike P <michael.pearm... at tangozebra.com> wrote: > Hi All, > > I have two dictionaries e.g > dict1 = {123:3,234:5,456:3} > dict2 = {123:4,157:2,234:5,456:3,567:2} > > I want to merge these two dictionaries together so i have a resultant > dictionary of: > > dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]} > > As later on i want to write a csv file that would have the form > > id ? ? ?var1 ?var2 > 123 ? ? 4 ? ? ?3 > 157 ? ? 2 ? ? ?0 > > i looks like the dict.update looks almost there but i can't get it to > work properly, can anyone offer any advise? The update() method is not quite right for your purposes. But a simple generator expression will do the trick: >>> dict((k, [v, dict1.get(k, 0)]) for k, v in dict2.items()) {456: [3, 3], 234: [5, 5], 123: [4, 3], 157: [2, 0], 567: [2, 0]} Raymond From ireborin at delete.this.gmail.com Mon Sep 29 18:04:18 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 00:04:18 +0200 Subject: Python arrays and sting formatting options Message-ID: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Hello everyone, I was wondering if anyone here has a moment of time to help me with 2 things that have been bugging me. 1. Multi dimensional arrays - how do you load them in python For example, if I had: ------- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 ------- with "i" being the row number, "j" the column number, and "k" the .. uhmm, well, the "group" number, how would you load this ? If fortran90 you would just do: do 10 k=1,2 do 20 i=1,3 read(*,*)(a(i,j,k),j=1,3) 20 continue 10 continue How would the python equivalent go ? 2. I've read the help on the next one but I just find it difficult understanding it. I have; a=2.000001 b=123456.789 c=1234.0001 How do you print them with the same number of decimals ? (eg. 2.000, 123456.789, 1234.000) and how do you print them with the same number of significant decimals? (eg. 2.000001, 123456.7, 1234.000 - always 8 decimals) ? Is something like this possible (built-in) in python ? Really grateful for all the help and time you can spare. -- Ivan From fredrik at pythonware.com Sat Sep 13 04:44:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 10:44:30 +0200 Subject: XML RPC Problem.... In-Reply-To: <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> References: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> <gaagp1$804$1@ger.gmane.org> <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> Message-ID: <gafuhg$sh1$1@ger.gmane.org> Usman Ajmal wrote: > Please explain the arguments of send_request. What exactly are the > connection, handler and request_body? It will be really helpful if you > give an example of how do i call send_request you don't call send_request. you should pass the SecureTransport instance as an argument to the ServerProxy, which will then use it to talk to the server. see the "custom transport" example in the library reference that I pointed you to. http://www.python.org/doc/lib/xmlrpc-client-example.html </F> From simon at mullis.co.uk Thu Sep 18 10:54:44 2008 From: simon at mullis.co.uk (Simon Mullis) Date: Thu, 18 Sep 2008 16:54:44 +0200 Subject: dict generator question Message-ID: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> Hi, Let's say I have an arbitrary list of minor software versions of an imaginary software product: l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] I'd like to create a dict with major_version : count. (So, in this case: dict_of_counts = { "1.1" : "1", "1.2" : "2", "1.3" : "2" } Something like: dict_of_counts = dict([(v[0:3], "count") for v in l]) I can't seem to figure out how to get "count", as I cannot do x += 1 or x++ as x may or may not yet exist, and I haven't found a way to create default values. I'm most probably not thinking pythonically enough... (I know I could do this pretty easily with a couple more lines, but I'd like to understand if there's a way to use a dict generator for this). Thanks in advance SM -- Simon Mullis From bignose+hates-spam at benfinney.id.au Tue Sep 2 19:52:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 03 Sep 2008 09:52:07 +1000 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <pan.2008.09.02.06.10.51@REMOVE.THIS.cybersource.com.au> <6i56cpFor2puU1@mid.individual.net> <6Aevk.331$1a2.14@trnddc04> <6i5gerFospk9U1@mid.individual.net> Message-ID: <87zlmqnm1k.fsf@benfinney.id.au> Peter Pearson <ppearson at nowhere.invalid> writes: > I thought I was a geek, for the past 40 years; but maybe its time > for me to be demoted to the dad on whose bookshelf you'll find that > old book. Once a geek, always a geek. You either stay sharp or get sloppy, but you never stop being a geek :-) -- \ ?The best ad-libs are rehearsed.? ?Graham Kennedy | `\ | _o__) | Ben Finney From tjreedy at udel.edu Tue Sep 23 14:31:49 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 14:31:49 -0400 Subject: Comparing float and decimal In-Reply-To: <gbaodd$e64$1@ger.gmane.org> References: <20080923072012.57d8d329.darcy@druid.net> <gbaodd$e64$1@ger.gmane.org> Message-ID: <gbbcmb$qal$1@ger.gmane.org> Gerhard H?ring wrote: > D'Arcy J.M. Cain wrote: >> I'm not sure I follow this logic. Can someone explain why float and >> integer can be compared with each other and decimal can be compared to >> integer but decimal can't be compared to float? >> >>>>> from decimal import Decimal >>>>> i = 10 >>>>> f = 10.0 >>>>> d = Decimal("10.00") >>>>> i == f >> True >>>>> i == d >> True >>>>> f == d >> False > > I can give you the technical answer after reading the sources of the > decimal module: you can only compare to Decimal what can be converted to > Decimal. And that is int, long and another Decimal. The new fractions module acts differently, which is to say, as most would want. >>> from fractions import Fraction as F >>> F(1) == 1.0 True >>> F(1.0) Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> F(1.0) File "C:\Program Files\Python30\lib\fractions.py", line 97, in __new__ numerator = operator.index(numerator) TypeError: 'float' object cannot be interpreted as an integer >>> F(1,2) == .5 True >>> .5 == F(1,2) True so Fraction obviously does comparisons differently. Decimal is something of an anomaly in Python because it was written to exactly follow an external standard, with no concessions to what would be sensible for Python. It is possible that that standard mandates that Decimals not compare to floats. tjr From arnodel at googlemail.com Mon Sep 22 08:22:11 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Sep 2008 05:22:11 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <f5df9f65-a13d-4f5f-9cf9-534d37dd04c0@f63g2000hsf.googlegroups.com> <5a37d7ca-e7b4-4278-8fc3-f5d0f4303cee@79g2000hsk.googlegroups.com> Message-ID: <765bbf9b-2ff5-4318-9a7e-75f1a678ec8a@m3g2000hsc.googlegroups.com> On 22 Sep, 11:52, josh logan <dear.jay.lo... at gmail.com> wrote: > On Sep 22, 3:41 am, Arnaud Delobelle <arno... at googlemail.com> wrote: > > > > > On 22 Sep, 04:05, josh logan <dear.jay.lo... at gmail.com> wrote: > > > > Hello, > > > > I have 2 questions. Say I have this class: > > > > class Player(object): > > > def __init__(self, fname, lname, score): > > > self.score = score > > > self.fname = fname > > > self.lname = lname > > > def __cmp__(self, other): > > > return (-cmp(self.score, other.score) or > > > cmp(self.lname, other.lname) or > > > cmp(self.fname, other.fname)) > > > def __repr__(self): > > > return 'Player(fname={0.fname}, lname={0.lname}, > > > score={0.score})'.format(self) > > > def __eq__(self, others): > > > if isinstance(other, Player): > > > return (self.score == other.score and > > > self.lname == other.lname and > > > self.fname == other.fname) > > > return False > > > def __ne__(self, others): > > > return not self.__eq__(others) > > > > fnames = ['Julie', 'Ben', 'Jason', 'David'] > > > lnames = ['Parks', 'Smith'] > > > scores = [100, 95, 95, 130, 58, 74] > > > > import itertools as it > > > > score_iter = it.cycle(scores) > > > > P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in > > > lnames] > > > > cmp(P[0], P[1]) # returns -1 > > > > sorted(P) # throws TypeError: unorderable types Player() < Player() > > > > The sorted function works when I define __lt__. > > > I must be misreading the documentation, because I read for the > > > documentation __cmp__ that it is called if none of the other rich > > > comparison functions are defined. > > > Is this a bug in Python 3.0rc1, or am I missing something? > > > > Secondly, say that we suddenly need another sorting order, where we > > > want to sort by decreasing score and then by DECREASING last name > > > (instead of increasing last name, defined above). Now that the > > > comparison function argument is taken away from the sorted builtin, > > > how do we accomplish this with the "key" parameter? > > > > Thank you > > > I don't know about __cmp__ but for the second part of the question you > > can probably do: > > > sorted(P, key=lambda p: (p.score, p.lname), reverse=True) > > > HTH > > > -- > > Arnaud > > Thank you for the prompt reply. I didn't think my second question > completely through. > > A better example would be sorting by increasing last name and > decreasing first name. This would be easy with the sort function > comparator, but I can't see how to do the same with the key argument. > Is the only solution to decorate the Player objects in another class > that has the appropriate __cmp__ function (or whatever is needed) and > then retrieve the Player objects back? You can use the stability of the sorting algorithm as Peter pointed out. If decorating, you don't need to decorate the Player objects, but you can decorate the keys instead: e.g class RevStr(str): def __lt__(self, other): return str.__lt__(other, self) def __ge__(self, other): retrn str.__gt__(other, self) then you can write: sorted(P, key=lambda p:(p.lname, RevStr(p.fname))) -- Arnaud From hrishys at yahoo.co.uk Thu Sep 25 07:08:34 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 11:08:34 +0000 (GMT) Subject: Linq to Python In-Reply-To: <a88ec2b4-2c64-4eba-b83d-a414eac74919@w7g2000hsa.googlegroups.com> Message-ID: <14608.59387.qm@web27402.mail.ukl.yahoo.com> Hi Pardon my ignorance again but id ont see any join in python or did i miss something ? regards Hrishy --- On Thu, 25/9/08, sturlamolden <sturlamolden at yahoo.no> wrote: > From: sturlamolden <sturlamolden at yahoo.no> > Subject: Re: Linq to Python > To: python-list at python.org > Date: Thursday, 25 September, 2008, 12:02 PM > On 25 Sep, 12:06, hrishy <hris... at yahoo.co.uk> wrote: > > > [code] > > var stoogeGuys = > > ? ? ?Beginning with the XML source > > ? ? ?from xmlGuys in > xmlSource.Descendants("Stooge") > > ? ? ?Join to the array on the common element > "stoogeName" > > ? ? ?join arrayGuys in familyFacts > > ? ? ? ? ? ?on > xmlGuys.Element("stoogeName").Value equals > arrayGuys.stoogeName > > ? ? ?Join to the database on the common element > "stoogeName" > > ? ? ?join dbGuys in stoogeContext.stoogeTables > > ? ? ? ? ? ?on > xmlGuys.Element("stoogeName").Value equals > dbGuys.stoogeName > > ? ? ?select new > > ? ? ?{ > > ? ? ? ? firstName ? ?= dbGuys.stoogeName, > > ? ? ? ? familyName ? = arrayGuys.familyName, > > ? ? ? ? birthDate ? ?= > xmlGuys.Element("birthDate").Value, > > ? ? ? ? deathDate ? ?= > xmlGuys.Element("deathDate").Value, > > ? ? ? ? hairCutStyle = dbGuys.stoogeHaircut, > > ? ? ?}; > > [/code] > > It could e.g. look like this in Python: > > stoogeGuys = [] > for xmlGuys in xmlSource.Descendants["Stooge"]: > arrayGuys = familyFacts[xmlGuys.stoogeName] > dbGuys = stoogeContext.stoogeTables[xmlGuys.stoogeName] > stoogeGuys += \ > [{'firstName': dbGuys.stoogeName, > 'familyName': arrayGuys.familyName, > 'birthDate': xmlGuys.birthDate, > 'deathDate': dbGuys.deathDate, > 'hairCutStyle': dbGuys.stoogeHaircut}] > > -- > http://mail.python.org/mailman/listinfo/python-list From ireborin at delete.this.gmail.com Tue Sep 23 07:45:40 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 23 Sep 2008 13:45:40 +0200 Subject: gplt from scipy missing ? References: <lckgd4dsk4hqfsibr5ldv3tnc3dl6lfvum@4ax.com> <mailman.1393.1222154779.3487.python-list@python.org> <67lhd4hq1gch3r18g919fjvmijen9saevv@4ax.com> Message-ID: <mllhd41t4tl696muvvul4shrd14qlp21q5@4ax.com> On Tue, 23 Sep 2008 13:44:41 +0200, Ivan Reborin <ireborin at delete.this.gmail.com> wrote: >On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" ><gagsl-py2 at yahoo.com.ar> wrote: > >> >>I think scipy does not bundle plotting packages anymore - you may use >>whatever suits you, from other sources. >>Try matplotlib, see the wiki: >>http://wiki.python.org/moin/NumericAndScientific/Plotting > >Hello Gabriel, >thank you for answering. > >Unfortunatelly, I cannot change my plotting package, unless I indend >to change a lot of code that I'll be using in the future. I'm not a >programmer by trade, just a guy doing some calculations with already >written programms. > >Do you know, by any chance, where one could get gplt separately, or >for example, get older versions of scipy ? >I'm using python 5.2.2.. If I install scipy for python 2.3. for Mea culpa, *2.5.2 >example (let's assume that one still has gplt in it) will it work ? > >Best regards >Ivan From roy at panix.com Mon Sep 29 09:56:19 2008 From: roy at panix.com (Roy Smith) Date: Mon, 29 Sep 2008 09:56:19 -0400 Subject: One class per file? References: <a932e44b-3566-4c0f-8b63-2dce0a82946b@34g2000hsh.googlegroups.com> Message-ID: <roy-6C98ED.09561929092008@news.panix.com> In article <a932e44b-3566-4c0f-8b63-2dce0a82946b at 34g2000hsh.googlegroups.com>, HCB <hypercaffeinatedbiped at gmail.com> wrote: > Hello: > > The book "Code Complete" recommends that you put only one class in a > source file, which seems a bit extreme for me. It seems that many > classes are small, so that putting several of them in a file seems > reasonable. I noticed that the decimal.py module in the standard > library has several classes, all of which of course revolve around the > "decimal" topic. Perhaps a better rule of thumb is "one idea per > file." I checked the Python style guide and there seems to be no > mention of this topic. I know this is an elementary question, but what > is the Python way of doing this? > > Thanks for your time. > HCB Steve McConnell writes a lot of good stuff. Like most people who write a lot of good stuff, not everything he writes should be taken as gospel. With that in mind... Consider this. You're slogging through some code in a large project trying to debug a problem when you come upon the line (in pseudo-code): foo = SomeClass::SomeFunction(bar) You want to go look at the source for SomeClass. What file do you open to find it? If you follow the "one class per file" rule, the answer is easy; it's in SomeClass.xxx! That being said, the "one class per file" rule is a means to an end. If your code is written in such a way that it's easy to figure out where the source for a given class/function/whatever is, then you've done the right thing. The specifics of how you do that depend on the language you're using. In Python (as other posters have pointed out), modules give you a good way to group logical collections of classes (etc). If you see in some code: foo = some_module.SomeClass.SomeFunction(bar) you should instantly know that the source code is in some_module.py. Perhaps one way to look at this is that Python automatically follows the "one class per file" rule, except that "class" is crossed out and "module" written in with crayon. On the other hand, if you prefer self-abuse, Python gives you plenty of ways to do that. If you preface all your source files with: from some_module import * from some_other_module import * from yet_a_third_module import * from another_module import * and then see foo = SomeClass.SomeFunction(bar) you're right back to having no clue what file to open to find the source for SomeClass. Global namespace is sacred; treat it with respect! From pruthviraj.pb at gmail.com Mon Sep 15 06:15:26 2008 From: pruthviraj.pb at gmail.com (Babloo) Date: Mon, 15 Sep 2008 03:15:26 -0700 (PDT) Subject: Client server implementation Message-ID: <f2190158-93fe-4747-864f-cbba0f690f0e@b30g2000prf.googlegroups.com> Hi everyone, i wanted to implement a client- server connection and transfer a file over the network. i was able to implement a normal set up where in i was able to send chat messages and small chunks of data. I want to implement the file transfer with out using the FTP library available in python . So can anyone suggest a piece of code by which i can do that. Thanks Pruthvi From http Sun Sep 7 18:06:18 2008 From: http (Paul Rubin) Date: 07 Sep 2008 15:06:18 -0700 Subject: problem with permutations References: <fb82c6bc-e22f-4502-9d6a-4616ce53517c@59g2000hsb.googlegroups.com> Message-ID: <7xej3vwqzp.fsf@ruckus.brouhaha.com> cnb <circularfunc at yahoo.se> writes: > perms([]) -> [[]]; > perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. I think the most direct transcription might be: def perms(xs): if len(xs)==0: return [[]] return [([h]+t) for h in xs for t in perms([y for y in xs if y not in [h]])] But it is rather inefficient, as is the Erlang version. From ethan at stoneleaf.us Fri Sep 5 15:49:49 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 05 Sep 2008 11:49:49 -0800 Subject: print doesn't respect file inheritance? In-Reply-To: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> References: <76618a4e-ab5f-422c-8627-0054f47970c8@8g2000hse.googlegroups.com> Message-ID: <48C18D5D.8060106@stoneleaf.us> bukzor wrote: > I was trying to change the behaviour of print (tee all output to a > temp file) by inheriting from file and overwriting sys.stdout, but it > looks like print uses C-level stuff to do its writes which bypasses > the python object/inhertiance system. It looks like I need to use > composition instead of inheritance, but thought this was strange > enough to note. > > $python -V > Python 2.5 > > """A short demo script""" > class notafile(file): > def __init__(self, *args, **kwargs): > readonly = ['closed', '__class__', 'encoding', 'mode', 'name', > 'newlines', 'softspace'] > file.__init__(self, *args, **kwargs) > for attr in dir(file): > if attr in readonly: continue > setattr(self, attr, None) > > > def main(): > n = notafile('/dev/stdout', "w") > print vars(n) > > import sys > sys.stdout = n > print "Testing: 1, 2, 3..." > > > output: > {'__str__': None, 'xreadlines': None, 'readlines': None, 'flush': > None, 'close': None, 'seek': None, '__init__': None, '__setattr__': > None, '__reduce_ex__': None, '__new__': None, 'readinto': None, > 'next': None, 'write': None, '__doc__': None, 'isatty': None, > 'truncate': None, 'read': None, '__reduce__': None, > '__getattribute__': None, '__iter__': None, 'readline': None, > 'fileno': None, 'writelines': None, 'tell': None, '__delattr__': None, > '__repr__': None, '__hash__': None} > Testing: 1, 2, 3... I tried the code (on Windows, so had to change /dev/stdout to /temp/notafile.txt) and it worked just fine. Perhaps the issue is that n is being set to /dev/stdout instead of some other file so no difference is apparent? In other words, you're assigning stdout to stdout. ~Ethan~ From gagsl-py2 at yahoo.com.ar Sun Sep 14 17:03:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Sep 2008 18:03:55 -0300 Subject: How to marshal objects to readable files? References: <mailman.1007.1221406286.3487.python-list@python.org> <143e575e-4745-4148-86de-deb2dbc0651d@m3g2000hsc.googlegroups.com> Message-ID: <op.uhhostxax6zn5v@a98gizw.noga> En Sun, 14 Sep 2008 15:09:52 -0300, Aaron "Castironpi" Brady <castironpi at gmail.com> escribi?: > On Sep 14, 10:28?am, nielinjie <nielin... at gmail.com> wrote: >> Hi list: >> I just want to marshal objects (instance of custom classes)to a human >> *READABEL *file/string, and also, I want unmarshal it back. in xml >> format or any other format. >> Any advice? Which lib should I use? > > The PyYAML package produces the following (continued): > >>>> print yaml.dump( a ) > &id001 !!python/object:__main__.A > b: 0 > c: abc > d: !!python/object:__main__.A > d: efg > e: 1.2 > parent: *id001 > JSON is another format, much simpler and probably more suited for human reading. But it is somewhat limited on what it can represent. There are a few Python implementations, maybe the most used is simplejson, which comes bundled with Python 2.6 as the json module. -- Gabriel Genellina From kyosohma at gmail.com Mon Sep 22 14:38:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 22 Sep 2008 11:38:25 -0700 (PDT) Subject: Problems running on hp dual core processor References: <mailman.1372.1222108408.3487.python-list@python.org> Message-ID: <05057996-444a-4fc8-b426-1be486db04f7@z72g2000hsb.googlegroups.com> On Sep 22, 1:43?pm, jim-on-linux <inq1... at inqvista.com> wrote: > Python help, > > I have a number of clients running a program built with > python 2.5. ?One has just purchased an HP with a duel > core processor, ?2.2G with .099g ram. > > On the new hp, when they try to print they get an > import error; > File win32ui.pyc line 12, in <module> > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: ?The specified module > could not be found. > > The file is there The only difference I could find from > their other machines is the processor. I have people running my compiled python applications on single and dual core processors with no problem. I suspect that you may just need to compile your application with some different switches, such as bundle=3 in py2exe for example. Mike From jukka.aho at iki.fi Tue Sep 2 06:17:10 2008 From: jukka.aho at iki.fi (Jukka Aho) Date: Tue, 2 Sep 2008 13:17:10 +0300 Subject: Python 3.0b2 cannot map '\u12b' References: <d0652dd2-24f6-4045-89a8-ba6deaf25b37@c65g2000hsa.googlegroups.com> <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> <mailman.312.1220250492.3487.python-list@python.org><6i24u3Fo7morU2@mid.uni-berlin.de> <mailman.336.1220293518.3487.python-list@python.org> Message-ID: <1n8vk.59481$_03.43814@reader1.news.saunalahti.fi> Terry Reedy wrote: >> If the terminal expects cp437 then displaying utf-8 might give some >> problems. > My screen displays whatever Windows tells the graphics card to tell > the screen to display. In OpenOffice, I can select a unicode font > that displays at least everything in the BasicMultilingualPlane (BMP). It would appear that the Windows port of Python is probably just not forcing the Win32 console into the Unicode mode or using the Unicode APIs. (If this holds true, it could be a leftover from the Windows 95/98/ME days, I suppose...) <http://en.wikipedia.org/wiki/Win32_console> As a workaround - for the time being - you might want to try something similar as described in the thread "Changing the (codec) error handler for the stdout/stderr streams in Python 3.0". The approach described in there will not let you print characters outside the codepage 437 repertoaire - any such characters will still need to be substituted with something else - but at least this substitution should happen automatically; i.e. you can keep using the normal print() function the normal way - even for the fancier characters - and your program will no longer crash. It would be nice to see proper Unicode Win32 console support in Python, of course, if at all possible. -- znark From steve at REMOVE-THIS-cybersource.com.au Thu Sep 25 02:10:39 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 06:10:39 GMT Subject: Off topic: Sent from my Foo messages References: <ea42fb160809241402i1c6da16t4dd2456a87d6f177@mail.gmail.com> <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <mailman.1474.1222296372.3487.python-list@python.org> <00eaf368$0$20666$c3e8da3@news.astraweb.com> <e2f73058-feb0-405e-8c47-25eb25410215@n38g2000prl.googlegroups.com> Message-ID: <00eb2533$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 20:04:14 -0700, Sean DiZazzo wrote: >> -- >> Steven > > I don't appreciate the two lines you put above your name in your posts. > Please remove them in the future. I don't like them either, but it is an email and Usenet standard to separate the body of your post from the signature with "-- ". I'm afraid that as obnoxious as the dashes are, leaving them out would be much worse. -- Steven From bignose+hates-spam at benfinney.id.au Mon Sep 1 21:13:27 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 02 Sep 2008 11:13:27 +1000 Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> Message-ID: <87ej43pcy0.fsf@benfinney.id.au> bearophileHUGS at lycos.com writes: > For Python 2.7/3.1 I'd now like to write a PEP regarding the > underscores into the number literals, like: 0b_0101_1111, 268_435_456 > etc. +1 on such a capability. -1 on underscore as the separator. When you proposed this last year, the counter-proposal was made <URL:http://groups.google.com/group/comp.lang.python/msg/18123d100bba63b8?dmode=source> to instead use white space for the separator, exactly as one can now do with string literals. I don't see any good reason (other than your familiarity with the D language) to use underscores for this purpose, and much more reason (readability, consistency, fewer arbitrary differences in syntax, perhaps simpler implementation) to use whitespace just as with string literals. -- \ ?When in doubt tell the truth. It will confound your enemies | `\ and astound your friends.? ?Mark Twain, _Following the Equator_ | _o__) | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Thu Sep 25 14:34:28 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 20:34:28 +0200 Subject: PEP Proposal In-Reply-To: <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> <mailman.1508.1222373098.3487.python-list@python.org> <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <48dbf59f$0$1374$426a74cc@news.free.fr> python-pep at arcor.de a ?crit : > Gabriel Genellina wrote: > >> En Thu, 25 Sep 2008 16:24:58 -0300, <python-pep at arcor.de> escribi?: >> >>> sorry, I have these ideas for longer than 10 years, please have a look >>> on it >>> and comment on it. Thx. >>> >>> This is another proposal for introducing types into Python. >> You got the terminology wrong. Python had "types" from the very start. >> You're talking about some kind of generic functions, or an alternative >> dispatch method. > > Typed parameters. are unpythonic. > Method-Declaration-filtered-typed parameters. Philip Eby's RuleDispatch package goes way further, already exists, and doesn't require any new syntax. From bignose+hates-spam at benfinney.id.au Wed Sep 17 08:36:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Sep 2008 22:36:41 +1000 Subject: Python OOP advice References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> Message-ID: <87fxnz3q5i.fsf@benfinney.id.au> Simon Hibbs <simon.hibbs at gmail.com> writes: > Orriginaly I thought I'd need to have a hull object which contains > component objects, but the component objects need access to members > of the hull object (e.g. the hull size) so that looks messy to > implement. Was it as messy as this:: class ShipHull(object): def __init__(self, size): self.components = dict() self.size = size class ShipComponent(object): def __init__(self, name, hull): self.name = name self.hull = hull > I have defined a base class Component with a class member variable > 'hull_size' so that all components can see the hull size. It seems to me the hull is an attribute of the component, and the size is an attribute of the hull. Why would the hull size be a *class* attribute? > I've then got two child classes called Fixed_Component and Percent > _Component that implement their mass, mass_percent and cost > properties appropriately for their type. class FixedShipComponent(ShipComponent): def _get_mass(self): return calculation_foo(self.hull.size) mass = property(_get_mass) def _get_cost(self): return calculation_bar(self.hull.size) cost = property(_get_cost) class PercentShipComponent(ShipComponent): def _get_mass(self): return calculation_spam(self.hull.size) mass = property(_get_mass) def _get_cost(self): return calculation_eggs(self.hull.size) cost = property(_get_cost) > I've also defined a Hull class which also inherits from Component > and provides methods for access to the hull_size class variable. I don't see why, if a ShipComponent needs to refer to its hull as something special, that a ShipHull would subclass ShipComponent. > Is there a way to cleanly implement a parent-child relationship > between objects that gives child objects limited access to members > of the parent? Sure; have the child instance grow an attribute referencing the parent, preferably by passing it to the initialisation function (__init__) of the child. -- \ Rommel: ?Don't move, or I'll turn the key on this can of Spam!? | `\ ?The Goon Show, _Rommel's Treasure_ | _o__) | Ben Finney From half.italian at gmail.com Sun Sep 21 19:11:02 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 21 Sep 2008 16:11:02 -0700 (PDT) Subject: appending * to glob returns files with '*' !! References: <mailman.1343.1222037582.3487.python-list@python.org> Message-ID: <ffdc64d2-861a-4e36-9466-2e28e6e5c3b1@r15g2000prd.googlegroups.com> On Sep 19, 1:37?pm, "John [H2O]" <washa... at gmail.com> wrote: > I have a glob.glob search: > > searchstring = os.path.join('path'+'EN*') shouldn't that be os.path.join(path, 'EN*') ? > ___ > This returns some files: > EN082333 > EN092334 > EN* Mine doesn't return that last string. > > My routine cannot handle the '*' and it should'nt be returned anyway? :-/ > Well, its an easy fix. files = glob.glob(searchstring) for f in files: if not f[-1] =="*": print f > A bug? Post a small *tested* example that recreates the error on your system. ~Sean From niklas.norrthon at hotmail.com Tue Sep 16 08:52:38 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Tue, 16 Sep 2008 05:52:38 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? References: <cb798579-d5d9-4a2f-843b-6fcca31fb5de@e39g2000hsf.googlegroups.com> Message-ID: <d2c7b432-2cd3-449b-bcb4-58e6f614f4f4@z72g2000hsb.googlegroups.com> On 16 Sep, 14:01, cnb <circularf... at yahoo.se> wrote: > I'm trying to switch to using emacs for python. > > The interpreter and python-mode works but I can't load the file I'm > editing into the interpreter. I'm using emacs to edit and run python programs on windows. In my .emacs I have the following line: (setq python-python-command "C:\\python25\\python.exe") And it works. Another alternative is to set the environment variable PYTHONPATH to point to the location of the python interpreter, but then you also need to edit the .../lisp/progmodes/python.el file to use semicolon (instead of colon) as a path separator. (in emacs 22.1 it is in line 1354 of the file (search for PYTHONPATH). (Or perhaps you needed to that anyway... I'm not sure). Good luck Niklas Norrthon From mnordhoff at mattnordhoff.com Thu Sep 11 09:59:10 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Thu, 11 Sep 2008 13:59:10 +0000 Subject: function return In-Reply-To: <aa405c1f0809110544l4b2a3e6aw724d1296761ec427@mail.gmail.com> References: <aa405c1f0809110544l4b2a3e6aw724d1296761ec427@mail.gmail.com> Message-ID: <48C9242E.6090509@mattnordhoff.com> Beema Shafreen wrote: > hi all, > > I have a script using functions , I have a problem in returning the > result. My script returns only one line , i donot know where the looping > is giving problem, Can any one suggest, why this is happening and let me > know how to return all the lines > > def get_ptm(): > fh = open('file.txt', 'r') > data_lis = [] > for line in fh.readlines(): As an aside, you should change the above line to: for line in fh: "readlines()" will read the entire file into memory at once, while just iterating through it won't, so you'll save memory on large files. > data = line.strip().split('\t') > id = data[0].strip() > gene_symbol = data[1].strip() > ptms = data[8].strip() > result = "%s\t%s\t%s" %(id,gene_symbol,ptms) This is very trivial, but you could change the above line to: result = "\t".join(id, gene_symbol, ptms) > return result > fh.close() -- From kyosohma at gmail.com Thu Sep 25 09:13:48 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 25 Sep 2008 06:13:48 -0700 (PDT) Subject: urllib error on urlopen References: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> <00eaf2fa$0$20666$c3e8da3@news.astraweb.com> Message-ID: <6d10384b-7b2a-41b0-85d5-d339df3d1e4c@j22g2000hsf.googlegroups.com> On Sep 24, 9:36?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Wed, 24 Sep 2008 08:46:56 -0700, Mike Driscoll wrote: > > Hi, > > > I have been using the following code for over a year in one of my > > programs: > > > f = urllib2.urlopen('https://www.companywebsite.com/somestring') > > > It worked great until the middle of the afternoon yesterday. Now I get > > the following traceback: > ... > > URLError: <urlopen error (1, 'error:140770FC:SSL > > routines:SSL23_GET_SERVER_HELLO:unknown protocol')> > > Have you recently set a proxy where Python can auto-detect it? I > understand that urllib2 doesn't work well with https proxies. > > If so, you can instruct urllib2 not to use a proxy-handler, but it's more > work. What I do is construct an opener without a proxyhandler: > > # untested... > no_proxy_support = urllib2.ProxyHandler({}) > opener = urllib2.build_opener(no_proxy_support) > f = opener.open('https://www.companywebsite.com/somestring') > > If that doesn't work, you may need to build a Request object from the URL > before passing it to opener.open. > > -- > Steven As I mentioned to Mr. Palmer, the error has mysteriously gone away this morning. I'll keep your advice handy though, in case it happens again. Thanks, Mike From Scott.Daniels at Acm.Org Tue Sep 23 23:11:13 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 23 Sep 2008 20:11:13 -0700 Subject: Detecting the first time I open/append to a file In-Reply-To: <mailman.1429.1222206115.3487.python-list@python.org> References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> <mailman.1429.1222206115.3487.python-list@python.org> Message-ID: <vuydnbDiJZsiMUTVnZ2dnUVZ_qvinZ2d@pdx.net> Terry Reedy wrote: > tkpmep at hotmail.com wrote: >> ...If I can sense that the file is being created in the first iteration, >> I can then use an if statement to decide whether or not I need to >> write the header. Question: how can I tell if the file is being >> created or if this its the first iteration? ... > > How about file.tell == 0? or have I misunderstood the requirement? OI thought roughly the same thing when I saw this, how about if not file.tell(): <produce header> --Scott David Daniels Scott.Daniels at Acm.Org From bearophileHUGS at lycos.com Tue Sep 23 20:15:24 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 23 Sep 2008 17:15:24 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <d086d0b2-0624-45ee-b72f-49d88a7dfe33@79g2000hsk.googlegroups.com> <c5e8ae40-9ed6-41c9-8914-4a3d0f001f0c@m36g2000hse.googlegroups.com> <f8912309-81ac-4bf1-ab26-b5cbc64ff52f@79g2000hsk.googlegroups.com> Message-ID: <85773da5-90a2-498c-bb30-c94bf2afefee@k30g2000hse.googlegroups.com> sturlamolden: > It seems we have been implementing different algorithms. kd-trees are > not BK-trees. > http://www.scipy.org/Cookbook/KDTree Sorry for my silly mistake :-) Note: in your code I don't know if the collections.deque data structure may help (it's faster than list for appending), but I presume that's not a bottleneck. Bye, bearophile From jackie.python at gmail.com Sun Sep 21 22:02:30 2008 From: jackie.python at gmail.com (Jackie Wang) Date: Sun, 21 Sep 2008 22:02:30 -0400 Subject: pause between the loops Message-ID: <37b964200809211902r206e951ep8d83cad88c93d45f@mail.gmail.com> Hi all, For a loop like: for i = range (0,10); can I ask python to stop for, say, 5mins, after it go through loop i=0 before it starts loop i=1? Thank you very much! Jackie From digitig at gmail.com Fri Sep 26 12:43:23 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 26 Sep 2008 17:43:23 +0100 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> Message-ID: <aee48b3c0809260943h7f7edae3qb447174bc62bfa49@mail.gmail.com> 2008/9/26 Steven D'Aprano <steve at remove-this-cybersource.com.au>: > I don't have any objective numbers, but subjectively it seems to me that > the number of spams is significantly higher, but not so high as to be a > major nuisance. I consider *any* spam to be a major nuisance, but I don't see them as being the fault of python-list which seems to do a pretty good job of blocking them -- Tim Rowe From grante at visi.com Mon Sep 8 15:21:27 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 08 Sep 2008 14:21:27 -0500 Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <ccf8d124-4609-48a6-b487-7cccc6d9c4b9@a3g2000prm.googlegroups.com> <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <mailman.701.1220900693.3487.python-list@python.org> Message-ID: <qa6dnVXB2Pyq5ljVnZ2dnUVZ_jCdnZ2d@posted.visi> On 2008-09-08, Chris Rebert <clp at rebertia.com> wrote: > On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <ewertman at gmail.com> wrote: > >> To expand on this a little bit, I've been subscribed to this >> group for a couple of months, but there seems to be a bit more >> gray area between what would go to a 'python-dev' group and a >> 'python-user' group. Long debates about language features and >> abstract ideas would appeal to the former, but not the latter. >> Certainly I fall into the user category.. I'm pretty happy >> with python, and generally just adjust to it's design and >> features, rather than spend lots of time on whether they are >> 'right' or could be 'better'. /shrug > > Yeah, suggestions about changing the language are much better > suited to the more-specific Python-ideas or Python-3000 > mailinglists than the general-purpose c.l.p I don't think anybody here in c.l.p minds reading suggestions for language features/changes, but often what the poster in question writes is just an incomprehensible collection of vaguely philosophical-sounding metaphores and similes reminiscent of a hoax paper submitted as a joke to a post-modern "journal" of some pretend science or other. -- Grant Edwards grante Yow! Used staples are good at with SOY SAUCE! visi.com From a at nospam.org Tue Sep 16 04:20:19 2008 From: a at nospam.org (Armin) Date: Tue, 16 Sep 2008 10:20:19 +0200 Subject: append on lists In-Reply-To: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: <ganpdo$1gf$1@online.de> John Machin wrote: > On Sep 16, 6:45 am, Armin <a... at nospam.org> wrote: > >> Yes, but this is very unconvenient. >> If d should reference the list a extended with a single list element >> you need at least two lines >> >> a.append(7) >> d=a >> >> and not more intuitive d = a.append(7) > > Methods/functions which return a value other than the formal None and > also mutate their environment are "a snare and a delusion". Don't wish > for them. c = [9,10] [1,2,3,4,7].append(c) -> Is this a valid expression? The 'value' of that expression is None. However ... that's the way of the implementation of the append method. It's a little bit confusing to me ... --Armin Thanks to all ! > > Inconvenient? How often do you want to mutate a list and then set up > another reference to it? > From castironpi at gmail.com Mon Sep 8 15:20:42 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 8 Sep 2008 12:20:42 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <ccf8d124-4609-48a6-b487-7cccc6d9c4b9@a3g2000prm.googlegroups.com> <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <mailman.701.1220900693.3487.python-list@python.org> Message-ID: <f59badb9-3c36-4273-a0e2-a8f8156a0326@z66g2000hsc.googlegroups.com> On Sep 8, 2:04?pm, "Chris Rebert" <c... at rebertia.com> wrote: > On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <ewert... at gmail.com> wrote: > >> Perhaps the wrong idea of what the group is. ?I would have thought > >> that > >> if one had a sufficiently developed idea and wanted to have it / > >> formally/ > >> rejected, rather than merely sniped at, then writting a PEP would be > >> more > >> apposite than posting to c.l.py. > > >> It's fine to post your not sufficiently developed ideas here merely > >> to > >> have them discussed. ?But I don't know what makes you feel that you, > >> or > >> your ideas, are /entitled/ to any response at all, much less > >> "follow-through." > > > To expand on this a little bit, ?I've been subscribed to this group > > for a couple of months, but there seems to be a bit more gray area > > between what would go to a 'python-dev' ?group and a 'python-user' > > group. ? Long debates about language features and abstract ideas would > > appeal to the former, but not the latter. ?Certainly I fall into the > > user category.. ?I'm pretty happy with python, and generally just > > adjust to it's design and features, rather than spend lots of time on > > whether they are 'right' or could be 'better'. ?/shrug > > Yeah, suggestions about changing the language are much better suited > to the more-specific Python-ideas or Python-3000 mailinglists than the > general-purpose c.l.p > - Chris > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com Some of the core devs from Python-Ideas have suggested that I get some of my ideas started on c.l.py. Also, I'm looking for people to connect with and interact with about Python and none of the core devs have time, which makes c.l.py the place. I'm starting to get discouraged, as though there's no one really interested in this cool thing I'm thinking of. Or did I just not describe it well? It would be safe to assume that people read my post, understood it, and weren't interested, except that a few replies came, and then it was dropped without any obvious explanation. Further, and I'm sad to report this, I found tempers really high strung on the Ideas list, so c.l.py may have more potential anyway, with more young and flexible users. Not to say that the core devs are old or brittle or anything, just that their time is already devoted and they don't have time for people like me. From bearophileHUGS at lycos.com Wed Sep 3 08:48:23 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 05:48:23 -0700 (PDT) Subject: max(), sum(), next() Message-ID: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Empty Python lists [] don't know the type of the items it will contain, so this sounds strange: >>> sum([]) 0 Because that [] may be an empty sequence of someobject: >>> sum(s for s in ["a", "b"] if len(s) > 2) 0 In a statically typed language in that situation you may answer the initializer value of the type of the items of the list, as I do in the sum() in D. This sounds like a more correct/clean thing to do: >>> max([]) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: max() arg is an empty sequence So it may be better to make the sum([]) too raise a ValueError, in Python 3/3.1 (if this isn't already true). On the other hand often enough I have code like this: >>> max(fun(x) for x in iterable if predicate(x)) This may raise the ValueError both if iterable is empty of if the predicate on its items is always false, so instead of catching exceptions, that I try to avoid, I usually end with a normal loop, that's readable and fast: max_value = smallvalue for x in iterable: if predicate(x): max_value = max(max_value, fun(x)) Where running speed matters, I may even replace that max(max_value, fun(x)) with a more normal if/else. A possible alternative is to add a default to max(), like the next() built-in of Python 2.6: >>> max((fun(x) for x in iterable if predicate(x)), default=smallvalue) This returns smallvalue if there are no items to compute the max of. Bye, bearophile From justin.kuto at gmail.com Fri Sep 26 17:46:21 2008 From: justin.kuto at gmail.com (afrogazer) Date: Fri, 26 Sep 2008 14:46:21 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> <f0c482f1-7148-43c4-87b1-3b4718d5d18d@8g2000hse.googlegroups.com> <7b1181e9-16a2-458a-8677-a2d8d7c8a961@l42g2000hsc.googlegroups.com> <05d9ca4d-441e-484b-ba1b-9e0ef7fa4658@d70g2000hsc.googlegroups.com> Message-ID: <0d00a562-37cf-4071-8f9f-73746b26c13f@k37g2000hsf.googlegroups.com> On Sep 26, 4:42?pm, Bas <wegw... at gmail.com> wrote: > On Sep 26, 10:33?pm, afrogazer <justin.k... at gmail.com> wrote:> rad_angles = [elem*(pi/180) for elem in angles] > > You are missing some more on a friday afternoon: angles is created by > arange, so it is a numpy array. In that case you simply can do > rad_angles = pi/180 * angles > No need to use list-comprehensions, that is the whole idea about using > these kick-ass objects! > > Bas Thanks! Should have thought of that, Fridays are a drag. From tjreedy at udel.edu Tue Sep 23 17:49:32 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 17:49:32 -0400 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <gbbo92$3j3$1@ger.gmane.org> Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), No > or should the exception propagate to the calling program which > handles the issue? Yes -- with an informative error message. If the caller ignores the exception, the program will exit with a full stack trace anyway. From bearophileHUGS at lycos.com Fri Sep 12 16:27:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Sep 2008 13:27:35 -0700 (PDT) Subject: manipulating files within 'for' References: <48CAA2AA.40809@umbc.edu> <gae9jj$sks$1@ger.gmane.org> <mailman.940.1221242051.3487.python-list@python.org> <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> <mailman.945.1221249453.3487.python-list@python.org> <cfc0851d-fe26-4064-a739-3bba7f7e6989@73g2000hsx.googlegroups.com> Message-ID: <2e96faf2-ef11-4703-b393-995fae724193@j22g2000hsf.googlegroups.com> Matt Nordhoff: > BTW, I could easily be wrong, but I think C behaves the same way as Python. C syntax has many traps that are much better out of modern languages like Python/D/etc. I think C has that feature because it lacks an operator for string concatenation, while both Python and D have one (+ and ~. D uses the ~ to avoid any programmer confusion with the mathematical summing operator), so the situation of Python/D is different. Bye, bearophile From jfabiani at yolo.com Tue Sep 2 10:44:00 2008 From: jfabiani at yolo.com (John Fabiani) Date: Tue, 02 Sep 2008 07:44:00 -0700 Subject: configure kdevelop for python References: <2f21628f-80dd-4710-b0be-2b1c772e5698@l33g2000pri.googlegroups.com> Message-ID: <GO6dnX7CJcOtzCDVnZ2dnUVZ_tLinZ2d@wavecable.com> Sindhu wrote: > am a newbie to python language and kdevelop, so i would like to know > how to configure kdevelop for python programming? complete with a > debugger? I have not used python and kdevelop but I do know it requires qt and the link below has several video's of a developer using python qt and qtdesigner. http://tv.dgplug.org/devel-inside.html I hope this helps. Johnf From febkimbleox at gmail.com Sat Sep 27 07:19:18 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:19:18 -0700 (PDT) Subject: free porno amaterski snimci porno free severina porno video free amaterske - Free Message-ID: <03782abb-c04a-403d-bff2-265887e33fee@w7g2000hsa.googlegroups.com> free . . . *******CLICK HERE******** http://vids365.cn/free ***************************** . . . . . . . . . . . . She had a healthy baby girl by the way, and breast feeds free and free both whenever free gets a chance. She had a healthy baby girl by the way, and breast feeds porno and porno both whenever porno gets a chance. She had a healthy baby girl by the way, and breast feeds amaterski and amaterski both whenever amaterski gets a chance. She had a healthy baby girl by the way, and breast feeds snimci and snimci both whenever snimci gets a chance. She had a healthy baby girl by the way, and breast feeds porno and porno both whenever porno gets a chance. She had a healthy baby girl by the way, and breast feeds free and free both whenever free gets a chance. She had a healthy baby girl by the way, and breast feeds severina and severina both whenever severina gets a chance. ?Oh baby, porno have a perfect pussy. ?Oh baby, video have a perfect pussy. ?Oh baby, free have a perfect pussy. ?Oh baby, amaterske have a perfect pussy. ?Oh baby, porno have a perfect pussy. ?Oh baby, slike have a perfect pussy. ?Oh baby, free have a perfect pussy. ?Oh baby, porno have a perfect pussy. ?Oh baby, film have a perfect pussy. ?Oh baby, free have a perfect pussy. ?Oh baby, porno have a perfect pussy. ?Oh baby, filmovi have a perfect pussy. Our visitor moved around in front of Tammy at the back of the couch and took out free cock. Our visitor moved around in front of Tammy at the back of the couch and took out download cock. Our visitor moved around in front of Tammy at the back of the couch and took out free cock. Our visitor moved around in front of Tammy at the back of the couch and took out porno cock. Our visitor moved around in front of Tammy at the back of the couch and took out sex cock. Our visitor moved around in front of Tammy at the back of the couch and took out tv cock. Our visitor moved around in front of Tammy at the back of the couch and took out free cock. Our visitor moved around in front of Tammy at the back of the couch and took out porno cock. Our visitor moved around in front of Tammy at the back of the couch and took out movies cock. Our visitor moved around in front of Tammy at the back of the couch and took out free cock. Our visitor moved around in front of Tammy at the back of the couch and took out porno cock. Our visitor moved around in front of Tammy at the back of the couch and took out videos cock. Part three;As free sat free in free favorite chair, free couldn?t stop thinking about Mandy. Part three;As porno sat porno in porno favorite chair, porno couldn?t stop thinking about Mandy. Part three;As index sat index in index favorite chair, index couldn?t stop thinking about Mandy. Part three;As free sat free in free favorite chair, free couldn?t stop thinking about Mandy. Part three;As gey sat gey in gey favorite chair, gey couldn?t stop thinking about Mandy. Part three;As porno sat porno in porno favorite chair, porno couldn?t stop thinking about Mandy. Part three;As free sat free in free favorite chair, free couldn?t stop thinking about Mandy. Part three;As porno sat porno in porno favorite chair, porno couldn?t stop thinking about Mandy. Part three;As filmi sat filmi in filmi favorite chair, filmi couldn?t stop thinking about Mandy. Part three;As free sat free in free favorite chair, free couldn?t stop thinking about Mandy. Part three;As porno sat porno in porno favorite chair, porno couldn?t stop thinking about Mandy. Part three;As films sat films in films favorite chair, films couldn?t stop thinking about Mandy. free could hear Tammy's breathing become ragged as free continued sucking. home could hear Tammy's breathing become ragged as home continued sucking. video could hear Tammy's breathing become ragged as video continued sucking. porno could hear Tammy's breathing become ragged as porno continued sucking. porno could hear Tammy's breathing become ragged as porno continued sucking. free could hear Tammy's breathing become ragged as free continued sucking. free could hear Tammy's breathing become ragged as free continued sucking. porno could hear Tammy's breathing become ragged as porno continued sucking. clips could hear Tammy's breathing become ragged as clips continued sucking. filmi could hear Tammy's breathing become ragged as filmi continued sucking. porno could hear Tammy's breathing become ragged as porno continued sucking. free could hear Tammy's breathing become ragged as free continued sucking. However, what paris wanted the most was for Mandy to have a happy life, love, and more. However, what hilton wanted the most was for Mandy to have a happy life, love, and more. However, what free wanted the most was for Mandy to have a happy life, love, and more. However, what porno wanted the most was for Mandy to have a happy life, love, and more. However, what free wanted the most was for Mandy to have a happy life, love, and more. However, what adult wanted the most was for Mandy to have a happy life, love, and more. However, what porno wanted the most was for Mandy to have a happy life, love, and more. However, what free wanted the most was for Mandy to have a happy life, love, and more. However, what porno wanted the most was for Mandy to have a happy life, love, and more. However, what film wanted the most was for Mandy to have a happy life, love, and more. However, what porno wanted the most was for Mandy to have a happy life, love, and more. This seemed to calm Tammy, as filmi pulled filmi maternity top over filmi head and stood there in filmi shorts and bra. This seemed to calm Tammy, as free pulled free maternity top over free head and stood there in free shorts and bra. This seemed to calm Tammy, as free pulled free maternity top over free head and stood there in free shorts and bra. This seemed to calm Tammy, as porno pulled porno maternity top over porno head and stood there in porno shorts and bra. This seemed to calm Tammy, as pics pulled pics maternity top over pics head and stood there in pics shorts and bra. This seemed to calm Tammy, as free pulled free maternity top over free head and stood there in free shorts and bra. This seemed to calm Tammy, as porno pulled porno maternity top over porno head and stood there in porno shorts and bra. This seemed to calm Tammy, as video pulled video maternity top over video head and stood there in video shorts and bra. This seemed to calm Tammy, as ceca pulled ceca maternity top over ceca head and stood there in ceca shorts and bra. This seemed to calm Tammy, as porno pulled porno maternity top over porno head and stood there in porno shorts and bra. This seemed to calm Tammy, as 3gp pulled 3gp maternity top over 3gp head and stood there in 3gp shorts and bra. This seemed to calm Tammy, as free pulled free maternity top over free head and stood there in free shorts and bra. As to kiss to tongue probes to mouth, doing the dance of lovers. As download kiss download tongue probes download mouth, doing the dance of lovers. As free kiss free tongue probes free mouth, doing the dance of lovers. As pornos kiss pornos tongue probes pornos mouth, doing the dance of lovers. As free kiss free tongue probes free mouth, doing the dance of lovers. As bbw kiss bbw tongue probes bbw mouth, doing the dance of lovers. As porno kiss porno tongue probes porno mouth, doing the dance of lovers. As free kiss free tongue probes free mouth, doing the dance of lovers. As porno kiss porno tongue probes porno mouth, doing the dance of lovers. As pictures kiss pictures tongue probes pictures mouth, doing the dance of lovers. As porno kiss porno tongue probes porno mouth, doing the dance of lovers. As fimi kiss fimi tongue probes fimi mouth, doing the dance of lovers. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, films were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, tv were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, mature were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, free were a lot larger than the old cliche of a silver Dollar. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. Under sites breath sites utters, ?Maybe she?ll let sites join sites in the shower. Under free breath free utters, ?Maybe she?ll let free join free in the shower. Under gay breath gay utters, ?Maybe she?ll let gay join gay in the shower. Under porno breath porno utters, ?Maybe she?ll let porno join porno in the shower. Under free breath free utters, ?Maybe she?ll let free join free in the shower. Under full breath full utters, ?Maybe she?ll let full join full in the shower. Under length breath length utters, ?Maybe she?ll let length join length in the shower. Under porno breath porno utters, ?Maybe she?ll let porno join porno in the shower. Under videos breath videos utters, ?Maybe she?ll let videos join videos in the shower. Under free breath free utters, ?Maybe she?ll let free join free in the shower. Under lesbian breath lesbian utters, ?Maybe she?ll let lesbian join lesbian in the shower. Under porno breath porno utters, ?Maybe she?ll let porno join porno in the shower. free couldn't take the sight of free hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. xxx couldn't take the sight of xxx hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. porno couldn't take the sight of porno hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. slovenski couldn't take the sight of slovenski hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. porno couldn't take the sight of porno hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. free couldn't take the sight of free hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. free couldn't take the sight of free hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. black couldn't take the sight of black hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. porno couldn't take the sight of porno hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. sex couldn't take the sight of sex hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. porno couldn't take the sight of porno hands caressing those luscious milk filled globes, and spurted out a huge load against the window sill. He finger-fucked free a few times then pulled free dripping fingers out, gazing into free passion- glazed eyes. He finger-fucked slike a few times then pulled slike dripping fingers out, gazing into slike passion-glazed eyes. He finger-fucked partis a few times then pulled partis dripping fingers out, gazing into partis passion-glazed eyes. He finger-fucked free a few times then pulled free dripping fingers out, gazing into free passion-glazed eyes. He finger-fucked porno a few times then pulled porno dripping fingers out, gazing into porno passion-glazed eyes. He finger-fucked free a few times then pulled free dripping fingers out, gazing into free passion-glazed eyes. He finger-fucked porno a few times then pulled porno dripping fingers out, gazing into porno passion-glazed eyes. He finger-fucked pictures a few times then pulled pictures dripping fingers out, gazing into pictures passion- glazed eyes. He finger-fucked online a few times then pulled online dripping fingers out, gazing into online passion-glazed eyes. He finger-fucked free a few times then pulled free dripping fingers out, gazing into free passion-glazed eyes. He finger-fucked mpeg a few times then pulled mpeg dripping fingers out, gazing into mpeg passion- glazed eyes. He finger-fucked porno a few times then pulled porno dripping fingers out, gazing into porno passion-glazed eyes. porno flicked on the nightstand light. films flicked on the nightstand light. free flicked on the nightstand light. downolads flicked on the nightstand light. free flicked on the nightstand light. porno flicked on the nightstand light. thumbnails flicked on the nightstand light. sex flicked on the nightstand light. thumbnail flicked on the nightstand light. free flicked on the nightstand light. porno flicked on the nightstand light. galleries flicked on the nightstand light. ?He looks straight into free eyes and exclaims, ?Can Daddy eat free pussy as free suck my cock??Mandy then tells free Daddy to lie down so free can straddle free face. ?He looks straight into porno eyes and exclaims, ?Can Daddy eat porno pussy as porno suck my cock??Mandy then tells porno Daddy to lie down so porno can straddle porno face. ?He looks straight into downloads eyes and exclaims, ?Can Daddy eat downloads pussy as downloads suck my cock??Mandy then tells downloads Daddy to lie down so downloads can straddle downloads face. ?He looks straight into free eyes and exclaims, ?Can Daddy eat free pussy as free suck my cock??Mandy then tells free Daddy to lie down so free can straddle free face. ?He looks straight into porno eyes and exclaims, ?Can Daddy eat porno pussy as porno suck my cock??Mandy then tells porno Daddy to lie down so porno can straddle porno face. ?He looks straight into movie eyes and exclaims, ?Can Daddy eat movie pussy as movie suck my cock??Mandy then tells movie Daddy to lie down so movie can straddle movie face. ?He looks straight into porno eyes and exclaims, ?Can Daddy eat porno pussy as porno suck my cock??Mandy then tells porno Daddy to lie down so porno can straddle porno face. ?He looks straight into video eyes and exclaims, ?Can Daddy eat video pussy as video suck my cock??Mandy then tells video Daddy to lie down so video can straddle video face. ?He looks straight into clips eyes and exclaims, ?Can Daddy eat clips pussy as clips suck my cock??Mandy then tells clips Daddy to lie down so clips can straddle clips face. ?He looks straight into free eyes and exclaims, ?Can Daddy eat free pussy as free suck my cock??Mandy then tells free Daddy to lie down so free can straddle free face. ?He looks straight into free eyes and exclaims, ?Can Daddy eat free pussy as free suck my cock??Mandy then tells free Daddy to lie down so free can straddle free face. ?He looks straight into porno eyes and exclaims, ?Can Daddy eat porno pussy as porno suck my cock??Mandy then tells porno Daddy to lie down so porno can straddle porno face. vids thought, My God, vids is going to whip me! Sure enough, vids began caressing my legs, thighs, stomach, and breasts with it. videos thought, My God, videos is going to whip me! Sure enough, videos began caressing my legs, thighs, stomach, and breasts with it. 3gp thought, My God, 3gp is going to whip me! Sure enough, 3gp began caressing my legs, thighs, stomach, and breasts with it. porno thought, My God, porno is going to whip me! Sure enough, porno began caressing my legs, thighs, stomach, and breasts with it. free thought, My God, free is going to whip me! Sure enough, free began caressing my legs, thighs, stomach, and breasts with it. porno thought, My God, porno is going to whip me! Sure enough, porno began caressing my legs, thighs, stomach, and breasts with it. ftp thought, My God, ftp is going to whip me! Sure enough, ftp began caressing my legs, thighs, stomach, and breasts with it. free thought, My God, free is going to whip me! Sure enough, free began caressing my legs, thighs, stomach, and breasts with it. porno thought, My God, porno is going to whip me! Sure enough, porno began caressing my legs, thighs, stomach, and breasts with it. video thought, My God, video is going to whip me! Sure enough, video began caressing my legs, thighs, stomach, and breasts with it. free thought, My God, free is going to whip me! Sure enough, free began caressing my legs, thighs, stomach, and breasts with it. free thought, My God, free is going to whip me! Sure enough, free began caressing my legs, thighs, stomach, and breasts with it. ?Ooooh, I?m sorry, full didn?t mean to do that. ?Ooooh, I?m sorry, length didn?t mean to do that. ?Ooooh, I?m sorry, porno didn?t mean to do that. ?Ooooh, I?m sorry, movies didn?t mean to do that. ?Ooooh, I?m sorry, free didn?t mean to do that. ?Ooooh, I?m sorry, online didn?t mean to do that. ?Ooooh, I?m sorry, porno didn?t mean to do that. ?Ooooh, I?m sorry, free didn?t mean to do that. ?Ooooh, I?m sorry, black didn?t mean to do that. ?Ooooh, I?m sorry, porno didn?t mean to do that. ?Ooooh, I?m sorry, clips didn?t mean to do that. ?Ooooh, I?m sorry, manga didn?t mean to do that. She continued by criss-crossing my legs with lashes from free crop. She continued by criss-crossing my legs with lashes from porno crop. She continued by criss-crossing my legs with lashes from free crop. She continued by criss-crossing my legs with lashes from full crop. She continued by criss-crossing my legs with lashes from length crop. She continued by criss-crossing my legs with lashes from porno crop. She continued by criss-crossing my legs with lashes from free crop. She continued by criss-crossing my legs with lashes from asian crop. She continued by criss-crossing my legs with lashes from porno crop. She continued by criss-crossing my legs with lashes from porno crop. She continued by criss-crossing my legs with lashes from video crop. She continued by criss-crossing my legs with lashes from free crop. While Mandy was taking dovnload clothes off, dovnload could not help but think of what could happen during or after the massage. While Mandy was taking sex clothes off, sex could not help but think of what could happen during or after the massage. While Mandy was taking porno clothes off, porno could not help but think of what could happen during or after the massage. While Mandy was taking free clothes off, free could not help but think of what could happen during or after the massage. While Mandy was taking free clothes off, free could not help but think of what could happen during or after the massage. While Mandy was taking porno clothes off, porno could not help but think of what could happen during or after the massage. While Mandy was taking comics clothes off, comics could not help but think of what could happen during or after the massage. While Mandy was taking free clothes off, free could not help but think of what could happen during or after the massage. While Mandy was taking porno clothes off, porno could not help but think of what could happen during or after the massage. While Mandy was taking online clothes off, online could not help but think of what could happen during or after the massage. While Mandy was taking free clothes off, free could not help but think of what could happen during or after the massage. While Mandy was taking granny clothes off, granny could not help but think of what could happen during or after the massage. To which porno replied, Well, don't let porno catch porno like that again. To which free replied, Well, don't let free catch free like that again. To which mature replied, Well, don't let mature catch mature like that again. To which porno replied, Well, don't let porno catch porno like that again. To which pics replied, Well, don't let pics catch pics like that again. To which free replied, Well, don't let free catch free like that again. To which porno replied, Well, don't let porno catch porno like that again. To which trailers replied, Well, don't let trailers catch trailers like that again. To which free replied, Well, don't let free catch free like that again. To which animal replied, Well, don't let animal catch animal like that again. To which porno replied, Well, don't let porno catch porno like that again. To which free replied, Well, don't let free catch free like that again. Maybe streaming could give streaming a massage; after all streaming is always complaining how streaming back aches after working. Maybe porno could give porno a massage; after all porno is always complaining how porno back aches after working. Maybe free could give free a massage; after all free is always complaining how free back aches after working. Maybe teen could give teen a massage; after all teen is always complaining how teen back aches after working. Maybe porno could give porno a massage; after all porno is always complaining how porno back aches after working. Maybe free could give free a massage; after all free is always complaining how free back aches after working. Maybe video could give video a massage; after all video is always complaining how video back aches after working. Maybe porno could give porno a massage; after all porno is always complaining how porno back aches after working. Maybe hardcore could give hardcore a massage; after all hardcore is always complaining how hardcore back aches after working. Maybe teen could give teen a massage; after all teen is always complaining how teen back aches after working. Maybe porno could give porno a massage; after all porno is always complaining how porno back aches after working. Maybe free could give free a massage; after all free is always complaining how free back aches after working. After a few moments, I'd located and was exploring the contents of porno underwear drawer. After a few moments, I'd located and was exploring the contents of free underwear drawer. After a few moments, I'd located and was exploring the contents of download underwear drawer. After a few moments, I'd located and was exploring the contents of porno underwear drawer. After a few moments, I'd located and was exploring the contents of movies underwear drawer. After a few moments, I'd located and was exploring the contents of free underwear drawer. After a few moments, I'd located and was exploring the contents of free underwear drawer. After a few moments, I'd located and was exploring the contents of double underwear drawer. After a few moments, I'd located and was exploring the contents of penetration underwear drawer. After a few moments, I'd located and was exploring the contents of porno underwear drawer. After a few moments, I'd located and was exploring the contents of free underwear drawer. After a few moments, I'd located and was exploring the contents of mature underwear drawer. When Mandy arrives home from work porno Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work pictures Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work free Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work porno Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work download Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work free Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work porno Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work movie Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work sites Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work porno Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work world Dad had supper already prepared and was adding the finishing touches to the table. When Mandy arrives home from work free Dad had supper already prepared and was adding the finishing touches to the table. Then videos can say my favorite word. Then suzana can say my favorite word. Then mancic can say my favorite word. Then porno can say my favorite word. Then video can say my favorite word. Then free can say my favorite word. Then free can say my favorite word. Then porno can say my favorite word. Then games can say my favorite word. Then free can say my favorite word. Then porno can say my favorite word. Then video can say my favorite word. She could feel downloads orgasm building as downloads moved downloads prick in and out, downloads laboured breathing hot against downloads face, downloads hands covering downloads tits, tweaking at downloads engorged nipples. She could feel tv orgasm building as tv moved tv prick in and out, tv laboured breathing hot against tv face, tv hands covering tv tits, tweaking at tv engorged nipples. She could feel porno orgasm building as porno moved porno prick in and out, porno laboured breathing hot against porno face, porno hands covering porno tits, tweaking at porno engorged nipples. She could feel free orgasm building as free moved free prick in and out, free laboured breathing hot against free face, free hands covering free tits, tweaking at free engorged nipples. She could feel free orgasm building as free moved free prick in and out, free laboured breathing hot against free face, free hands covering free tits, tweaking at free engorged nipples. She could feel porno orgasm building as porno moved porno prick in and out, porno laboured breathing hot against porno face, porno hands covering porno tits, tweaking at porno engorged nipples. She could feel comics orgasm building as comics moved comics prick in and out, comics laboured breathing hot against comics face, comics hands covering comics tits, tweaking at comics engorged nipples. She could feel with orgasm building as with moved with prick in and out, with laboured breathing hot against with face, with hands covering with tits, tweaking at with engorged nipples. She could feel archie orgasm building as archie moved archie prick in and out, archie laboured breathing hot against archie face, archie hands covering archie tits, tweaking at archie engorged nipples. She could feel free orgasm building as free moved free prick in and out, free laboured breathing hot against free face, free hands covering free tits, tweaking at free engorged nipples. She could feel shemale orgasm building as shemale moved shemale prick in and out, shemale laboured breathing hot against shemale face, shemale hands covering shemale tits, tweaking at shemale engorged nipples. She could feel porno orgasm building as porno moved porno prick in and out, porno laboured breathing hot against porno face, porno hands covering porno tits, tweaking at porno engorged nipples. When sites appeared to be done sites was looking in sites jewelry box for something to go with sites outfit. When xxx appeared to be done xxx was looking in xxx jewelry box for something to go with xxx outfit. When free appeared to be done free was looking in free jewelry box for something to go with free outfit. When porno appeared to be done porno was looking in porno jewelry box for something to go with porno outfit. When free appeared to be done free was looking in free jewelry box for something to go with free outfit. When college appeared to be done college was looking in college jewelry box for something to go with college outfit. When porno appeared to be done porno was looking in porno jewelry box for something to go with porno outfit. When movies appeared to be done movies was looking in movies jewelry box for something to go with movies outfit. When free appeared to be done free was looking in free jewelry box for something to go with free outfit. When download appeared to be done download was looking in download jewelry box for something to go with download outfit. When porno appeared to be done porno was looking in porno jewelry box for something to go with porno outfit. When free appeared to be done free was looking in free jewelry box for something to go with free outfit. funny looked absolutely stunning in a long yellow dress with a matching garland in funny hair, flashing funny a quick smile as funny went past. porno looked absolutely stunning in a long yellow dress with a matching garland in porno hair, flashing porno a quick smile as porno went past. jpg looked absolutely stunning in a long yellow dress with a matching garland in jpg hair, flashing jpg a quick smile as jpg went past. free looked absolutely stunning in a long yellow dress with a matching garland in free hair, flashing free a quick smile as free went past. porno looked absolutely stunning in a long yellow dress with a matching garland in porno hair, flashing porno a quick smile as porno went past. movie looked absolutely stunning in a long yellow dress with a matching garland in movie hair, flashing movie a quick smile as movie went past. clips looked absolutely stunning in a long yellow dress with a matching garland in clips hair, flashing clips a quick smile as clips went past. free looked absolutely stunning in a long yellow dress with a matching garland in free hair, flashing free a quick smile as free went past. porno looked absolutely stunning in a long yellow dress with a matching garland in porno hair, flashing porno a quick smile as porno went past. psp looked absolutely stunning in a long yellow dress with a matching garland in psp hair, flashing psp a quick smile as psp went past. pamela looked absolutely stunning in a long yellow dress with a matching garland in pamela hair, flashing pamela a quick smile as pamela went past. anderson looked absolutely stunning in a long yellow dress with a matching garland in anderson hair, flashing anderson a quick smile as anderson went past. Maybe free would, after all free said free was taking free shopping. Maybe porno would, after all porno said porno was taking porno shopping. Maybe films would, after all films said films was taking films shopping. Maybe porno would, after all porno said porno was taking porno shopping. Maybe video would, after all video said video was taking video shopping. Maybe severina would, after all severina said severina was taking severina shopping. Maybe free would, after all free said free was taking free shopping. Maybe doenload would, after all doenload said doenload was taking doenload shopping. Maybe ashley would, after all ashley said ashley was taking ashley shopping. Maybe jensen would, after all jensen said jensen was taking jensen shopping. Maybe free would, after all free said free was taking free shopping. Maybe porno would, after all porno said porno was taking porno shopping. videos felt videos little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving videos hand up and down. free felt free little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving free hand up and down. adult felt adult little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving adult hand up and down. porno felt porno little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving porno hand up and down. sites felt sites little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving sites hand up and down. free felt free little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving free hand up and down. porno felt porno little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving porno hand up and down. websites felt websites little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving websites hand up and down. free felt free little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving free hand up and down. severina felt severina little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving severina hand up and down. porno felt porno little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving porno hand up and down. download felt download little fingers worm beneath the waist band of my boxers and close around my engorged shaft, gently moving download hand up and down. After ordering the flowers and limousine, free made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, streaming made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, online made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, porno made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, porno made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, sex made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, video made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, severina made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, free made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, download made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, porno made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. After ordering the flowers and limousine, world made reservations for dinner on Valentine?s Day at the Fountain Restaurant, a chic eatery located in the Four Seasons Hotel. ?Oh my God, what have hardcord done to me?, my beautiful young cousin was glassy eyed as hardcord shifted position and was face to face with my rampant cock. ?Oh my God, what have free done to me?, my beautiful young cousin was glassy eyed as free shifted position and was face to face with my rampant cock. ?Oh my God, what have videos done to me?, my beautiful young cousin was glassy eyed as videos shifted position and was face to face with my rampant cock. ?Oh my God, what have video done to me?, my beautiful young cousin was glassy eyed as video shifted position and was face to face with my rampant cock. ?Oh my God, what have porno done to me?, my beautiful young cousin was glassy eyed as porno shifted position and was face to face with my rampant cock. ?Oh my God, what have free done to me?, my beautiful young cousin was glassy eyed as free shifted position and was face to face with my rampant cock. From robert.d.kirkpatrick at gmail.com Tue Sep 23 18:53:03 2008 From: robert.d.kirkpatrick at gmail.com (Rob Kirkpatrick) Date: Tue, 23 Sep 2008 15:53:03 -0700 (PDT) Subject: Visualize class inheritance hierarchy Message-ID: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Hi All, I just finished debugging some code where I needed to determine why one subclass had a bound method and another did not. They had different pedigree's but I didn't know immediately what the differences were. I ended up walking the hierarchy, going back one class at a time through the code, for the two subclasses (hierarchy ~7 classes deep each) to see whom they inherited from. Short of writing this down on paper, is there any way to graphically display the pedigree of an object/class? "Graphically" can be text output to the terminal, don't need anything special... I'm assuming this has been discussed before, but I'm lacking any Google keywords that bring up the appropriate discussion. Cheers, Rob From callen314 at gmail.com Thu Sep 11 17:03:31 2008 From: callen314 at gmail.com (Craig Allen) Date: Thu, 11 Sep 2008 14:03:31 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <mailman.876.1221142791.3487.python-list@python.org> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> <09345856-9a44-449c-9ee0-6254c573847e@b1g2000hsg.googlegroups.com> Message-ID: <d328bff0-8c1d-4509-baa7-3db999b90f1d@1g2000pre.googlegroups.com> > What's business logic? an oxymoron? From mcrute at gmail.com Sat Sep 27 20:00:59 2008 From: mcrute at gmail.com (Michael Crute) Date: Sat, 27 Sep 2008 20:00:59 -0400 Subject: check if file is MS Word or PDF file In-Reply-To: <47c890dc0809271601y6f5a4a5fy98fad966e5ca024@mail.gmail.com> References: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> <47c890dc0809271601y6f5a4a5fy98fad966e5ca024@mail.gmail.com> Message-ID: <558b73fb0809271700g53c33c3cj42afdfbc729103e3@mail.gmail.com> On Sat, Sep 27, 2008 at 7:01 PM, Chris Rebert <clp at rebertia.com> wrote: > Looking at the docs for the mimetypes module, it just guesses based on > the filename (and extension), not the actual contents of the file, so > it doesn't really help the OP, who wants to make sure their program > isn't misled by an inaccurate extension. One other way to detect a pdf is to just read the first 4 bytes from the file. Valid pdf files start with "%PDF-". Something similar can be done with Word docs but I don't know what the magic bytes are. This approach is pretty similar to what the file command does but is probably a better approach if you have to support multiple platforms. -mike -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From castironpi at gmail.com Sun Sep 7 18:24:48 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 7 Sep 2008 15:24:48 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> Message-ID: <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> On Sep 7, 5:03?pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote: > On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > > This is the strangest post I've seen > > since I've joined this list (only > > recently). What the ? > > Yeah, castironpi sometimes doesn't make much sense. ?Maybe because it's a > bot!? ?:-) > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch No, I'm legit, and I believe my complaint is. That's all I can guarantee anyway. While I'm still not a vet on Usenet, I'm still disappointed so far. Though I should be flattered for my logic to be ever compared to an A.I.'s. Maybe the ideas are not that groundbreaking, but they still have been dropped instead of critiqued. Problem. From gagsl-py2 at yahoo.com.ar Fri Sep 19 00:03:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 01:03:10 -0300 Subject: Do HTTPError objects always have a read method? References: <pan.2008.09.18.01.48.26@REMOVE.THIS.cybersource.com.au> <op.uhphqwt5x6zn5v@gabriel2.softlabbsas.com.ar> Message-ID: <op.uhpmvkdcx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 18 Sep 2008 23:12:22 -0300, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> escribi?: > En Wed, 17 Sep 2008 22:48:27 -0300, Steven D'Aprano > <steven at remove.this.cybersource.com.au> escribi?: > >> Under what circumstances do HTTPError objects not have a valid file >> object? How common is this? Does anyone have an example of a URL that >> fails in that fashion? > > Well, there is at least one case (AbstractDigestAuthHandler at line 864 > in urllib2.py) where HTTPError is raised explicitely with fp=None. It's > not a common case, I think. If you rely on the exception having a read() > method, add it a fake one yourself: > > try: ... > except urllib2.HTTPError, e: > if not hasattr(e, 'read'): > e.read = e.readline = lambda self: '' # or perhaps e.msg > conn = e Oops, that should have been e.read = lambda: '' -- Gabriel Genellina From st1999 at gmail.com Sun Sep 28 21:44:20 2008 From: st1999 at gmail.com (robean) Date: Sun, 28 Sep 2008 18:44:20 -0700 (PDT) Subject: urllib2 and exceptions References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> <mailman.1635.1222629122.3487.python-list@python.org> <d127e341-c16d-4ef9-b1de-b9076cefdcb4@i20g2000prf.googlegroups.com> <357e734f-e99f-41e5-9cac-083d636a23e1@n38g2000prl.googlegroups.com> <95f8433c-213f-4b3a-8d93-bebbe2561e7f@s9g2000prg.googlegroups.com> Message-ID: <781c4e48-7396-4278-85bd-3578f88aa501@l33g2000pri.googlegroups.com> On Sep 28, 5:33?pm, alex23 <wuwe... at gmail.com> wrote: > On Sep 29, 5:52?am, robean <st1... at gmail.com> wrote: > > > Actually, the problem seems to be that IOError is in my namespace, but > > the other error classes are not. So, > > > ? ?except HTTPError, etc. > > > fails, but > > > ? ?except urllib2.HttpError, etc. > > > works fine. Now, I still don't understand why these classes shouldn't > > automatically work.... > > IOError is a standard Python exception. HTTPError & URLError are > exceptions provided by the urllib2 module. They need to be imported > from or referenced through urllib2 to be used. Many thanks for your reply. I was simply under the impression that 'import urllib2' would take care of the namespace issue and simply import everything in urlib2, making it unnecessary to have to reference HTTPError and URLError. Sorry for being dense about this (I'm very new to Python).. Again, thanks for your help. From castironpi at gmail.com Wed Sep 3 18:31:51 2008 From: castironpi at gmail.com (castironpi) Date: Wed, 3 Sep 2008 15:31:51 -0700 (PDT) Subject: xml + mmap cross Message-ID: <a27b2e33-bddb-407e-b2ea-895dc78c7090@r15g2000prd.googlegroups.com> Any interest in pursuing/developing/working together on a mmaped-xml class? Faster, not readable in text editor. From castironpi at gmail.com Mon Sep 15 16:09:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 15 Sep 2008 13:09:00 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> <c950520a-7670-47c0-a1e6-59df4109ba86@m36g2000hse.googlegroups.com> <pan.2008.09.11.07.40.08@REMOVE.THIS.cybersource.com.au> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <pan.2008.09.12.03.37.51@REMOVE.THIS.cybersource.com.au> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <pan.2008.09.12.06.30.43@REMOVE.THIS.cybersource.com.au> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> <f62644a0-51c4-4eb1-96e4-eab96d431b74@l42g2000hsc.googlegroups.com> Message-ID: <b1a06f31-92df-45a3-8b1c-d2b5269ad18f@k30g2000hse.googlegroups.com> On Sep 15, 4:34?am, Francesc <fal... at gmail.com> wrote: > On 12 Set, 14:39, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> > wrote: > > > > > > A consideration of other storage formats such as HDF5 might > > > be appropriate: > > > >http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > > > There are, of course, HDF5 tools available for Python. > > > PyTablescame up within the past few weeks on the list. > > > "When the file is created, the metadata in the object tree is updated > > in memory while the actual data is saved to disk. When you close the > > file the object tree is no longer available. However, when you reopen > > this file the object tree will be reconstructed in memory from the > > metadata on disk...." > > > This is different from what I had in mind, but the extremity depends > > on how slow the 'reconstructed in memory' step is. ?(Fromhttp://www.pytables.org/docs/manual/ch01.html#id2506782). ?The > > counterexample would be needing random access into multiple data > > files, which don't all fit in memory at once, but the maturity of the > > package might outweigh that. ?Reconstruction will form a bottleneck > > anyway. > > Hmm, this was a part of a documentation that needed to be updated. > Now, the object tree is reconstructed in a lazy way (i.e. on-demand), > in order to avoid the bottleneck that you mentioned. ?I have corrected > the docs in: > > http://www.pytables.org/trac/changeset/3714/trunk > > Thanks for (indirectly ;-) bringing this to my attention, > > Francesc Depending on how lazy the reconstruction is, would it be possible to modify separate tables from separate processes concurrently? From mcrute at gmail.com Sat Sep 27 18:42:29 2008 From: mcrute at gmail.com (Michael Crute) Date: Sat, 27 Sep 2008 18:42:29 -0400 Subject: check if file is MS Word or PDF file In-Reply-To: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> References: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> Message-ID: <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> On Sat, Sep 27, 2008 at 5:43 PM, A. Joseph <joefazee at gmail.com> wrote: > What should I look for in a file to determine whether or not it is a > MS Word file or an Excel file or a PDF file, etc., etc.? including Zip > files > > I don`t want to check for file extension. > os.path.splitext('Filename.jpg') will produce a tuple of filename and > extension, but some file don`t even have extension and can still be read by > MS Word or NotePad. i want to be 100% sure of the file. You could use the mimetypes module... <<< import mimetypes <<< mimetypes.guess_type("LegalNotices.pdf") >>> ('application/pdf', None) -mike -- ________________________________ Michael E. Crute http://mike.crute.org God put me on this earth to accomplish a certain number of things. Right now I am so far behind that I will never die. --Bill Watterson From steven at REMOVE.THIS.cybersource.com.au Wed Sep 3 01:43:19 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 03 Sep 2008 05:43:19 GMT Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <mailman.395.1220399835.3487.python-list@python.org> Message-ID: <pan.2008.09.03.05.43.21@REMOVE.THIS.cybersource.com.au> On Tue, 02 Sep 2008 18:56:48 -0500, Robert Kern wrote: > ssecorp wrote: >> or why does this take so god damn long time? > > Several reasons. One of which is that try: except: is slow. I beg to differ. Setting up a try...except block is very fast. Here's an example in Python 2.5: >>> from timeit import Timer >>> Timer('len("abc")').repeat() [0.27346706390380859, 0.1530919075012207, 0.14886784553527832] >>> Timer('''try: ... len("abc") ... except: ... pass ... ''').repeat() [0.27847194671630859, 0.19191384315490723, 0.19077491760253906] The difference (approx 0.04 microseconds) applicable to setting up the try...except block is trivial, of the same magnitude as a pass statement: >>> Timer('pass').repeat() [0.059719085693359375, 0.060056924819946289, 0.059512138366699219] However, *catching* the exception may be relatively slow: >>> Timer('''try: ... len(abc) # raise a NameError ... except: ... pass ... ''').repeat() [3.2067418098449707, 2.7088210582733154, 1.9558219909667969] -- Steven From namekuseijin at gmail.com Tue Sep 23 21:49:38 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Tue, 23 Sep 2008 18:49:38 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> Message-ID: <24e340b1-ec28-4435-b4df-f2296f7ae1d2@x41g2000hsb.googlegroups.com> On 23 set, 20:52, Neal Becker <ndbeck... at gmail.com> wrote: > In hindsight, I am disappointed with the choice of conditional syntax. ?I know it's too late to change. ?The problem is > > y = some thing or other if x else something_else > > When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). ?Particularly if 'some thing or other' is long or complicated. Yes, infix syntax sucks. No ambiguities in prefixed Lisp: (if x (or something other) something_else) Anyway, pretty amusing seeing Guido nodding to Larry... ;) From tjreedy at udel.edu Tue Sep 30 16:29:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 16:29:40 -0400 Subject: Would this be called a bug in inspect ? In-Reply-To: <48E28534.1040009@gmail.com> References: <48E268A3.4050900@gmail.com> <op.uia609w8x6zn5v@gabriel2.softlabbsas.com.ar> <48E28534.1040009@gmail.com> Message-ID: <gbu27j$3l5$1@ger.gmane.org> Stef Mientki wrote: > print getmembers ( wx ) > crashes > > but not always: > >>> print getmembers (wx) > [('ACCEL_ALT', 1), ('ACCEL_CMD', 2), ('ACCEL_CTRL', 2), ('ACCEL_NORMAL', > 0), ('ACCEL_SHIFT', 4), ('ADJUST_MINSIZE', 0), ( I suspect that wx has an erratic bug, which their tests do not catch. So I would send this off to them. > >>> print getmembers (wx) > Traceback (most recent call last): > File "<interactive input>", line 1, in <module> > File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line > 242, in __repr__ > def __repr__(self): return 'wx.Colour' + > str(self.Get(True)) > File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line > 230, in Get > return _gdi_.Colour_Get(*args, **kwargs) > TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' From code at pizzashack.org Mon Sep 29 02:15:19 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 29 Sep 2008 02:15:19 -0400 Subject: Test if list contains another list In-Reply-To: <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> <48c6380b$0$17080$426a34cc@news.free.fr> <mailman.741.1220976622.3487.python-list@python.org> <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> <mailman.1557.1222457112.3487.python-list@python.org> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> Message-ID: <20080929061518.GL26713@dragontoe.org> On Fri, Sep 26, 2008 at 01:39:16PM -0700, bearophileHUGS at lycos.com wrote: > # building prefix-function > m = 0 > for i in xrange(1, len_sub): > while m > 0 and sub[m] != sub[i]: > m = table[m - 1] > if sub[m] == sub[i]: > m += 1 > table[i] = m > > # searching > m, i = 0, 0 > for x in items: > while m > 0 and sub[m] != x: > m = table[m - 1] > if sub[m] == x: > m += 1 > if m == len_sub: > return True > i += 1 > > return False Quite a lot faster than mine... even without using psyco. Which is interesting, especially because if I change my search loop to work like yours, but leave out all your other optimizations, mine runs roughly as fast as yours (i.e. execution time is negligible to a user running the program in both cases, even with the large example data you gave). This leads me to point out two caveats with your version: 1. Guavat posted a version which returns a list of all the indexes where a match is found... which is what I mimiced. Yours returns only true or false indicating whether or not it found a match. The main difference in performance seems to come due to your iteration over the list items, versus my comparing a sublist-sized slice of the whole to the sublist. But this alone is an invalid optimization, because it doesn't produce the same results... If you only want to know if a match exists, it's great; but if you want to know *where*, or *how many times*, you lose. That could be fixed though, by counting the elements as you loop through them... I didn't attempt to determine the performance hit for doing that, but I assume it's negligible. I also imagine that that was your original purpose for the unused variable i... 2. Your secondary optimizations add a great deal of complexity to your code, making the algorithm much harder to understand. However they don't appear to buy you much, given that the cases they optimize would probably be rare, and the difference in execution time gained by the optimization is not noticable to the user. Unless you're doing lots and lots of these in your application, or maybe if you know in advance that your data will contain many instances of the cases you optimized, I think you're better off leaving the optimizations out, for the sake of code clarity. At the very least, if you're going to write complicated optimizations, you ought to have explained what you were doing in comments... :) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080929/b2f6cbe8/attachment-0001.sig> From mail at timgolden.me.uk Fri Sep 12 08:35:29 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 13:35:29 +0100 Subject: testing if another instance of a script is already running In-Reply-To: <48CA5BA5.8020709@p0w.org> References: <48CA5BA5.8020709@p0w.org> Message-ID: <48CA6211.8050402@timgolden.me.uk> Strato wrote: > Hi folks, > > I want to write some kind of test to check at startup if another > instance of my script is already running. > > I don't want to handle writing of a PID file because it is too > Unix/Linux specific way to do this, and I need to keep the code to be > cross-platform. > > I think the better way to achieve this is to use some process control, > but I'm a neebie and I don't see how to do this in a safe and clean way. There's nothing built in to Python to do this, so you'll probably have to roll your own cross-platformness. Of course, there's nothing to stop you from writing pid files under Windows even if it's not the usual way. Or you could just put some conditional code, and use the kernel mutex under Windows, which is the generally recommended technique. Have a look at this thread, for example (among several others): http://mail.python.org/pipermail/python-list/2005-June/327063.html TJG From bborcic at gmail.com Sun Sep 14 05:41:17 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sun, 14 Sep 2008 11:41:17 +0200 Subject: recursion gotcha? In-Reply-To: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> Message-ID: <gaima0$2ak$1@ger.gmane.org> cnb wrote: > this recursive definition of sum thrumped me, is this some sort of > gotcha or am I just braindead today? > and yes i know this is easy a a for x in xs acc += x or just using the > builtin. > > def suma(xs, acc=0): > if len(xs) == 0: > acc > else: > suma(xs[1:], acc+xs[0]) > > it returns none. Without return statement, the only recursive solution is a lambda expr : >>> suma = lambda xs : xs[0]+suma(xs[1:]) if xs else 0 >>> suma(range(101)) 5050 Note that suma(xs[1:]) implies copying the remainder of xs, what in turn makes the time grow quadratically with the length of xs. So instead of passing a superfluous acc second variable, you could pass an index into the list, eg def suma(xs,pos=0) : if pos>=len(xs) : return 0 else : return xs[pos]+suma(xs,pos+1) Cheers, BB From spython01 at gmail.com Thu Sep 4 09:05:00 2008 From: spython01 at gmail.com (Samir) Date: Thu, 4 Sep 2008 06:05:00 -0700 (PDT) Subject: The Python Papers, Volume 3 Issue 2 References: <3eb3b85a-67cc-4260-a86f-acee9c8f6eb8@q5g2000prf.googlegroups.com> Message-ID: <0a7f9645-6dcd-40de-89f6-581393599733@z11g2000prl.googlegroups.com> On Sep 4, 8:58?am, "mauricel... at acm.org" <mauricel... at gmail.com> wrote: > Hi everyone > > After a long wait of nearly 5 month, we are back in business to bring > the latest edition of The Python Papers - Volume 3 Issue 2 (http:// > ojs.pythonpapers.org/index.php/tpp/issue/current). > > From this issue onwards, we will be having only 3 issues per year > instead of 4. This is in compliance with our ISSN registration. > > What's new > ========= > 1. We have expanded our editorial team with 2 new Associate Editors, > Sarah Mount (from UK) and Guy Kloss from (New Zealand). > > 2. TPP is now managed using Open Journal System and it can be assessed > athttp://ojs.pythonpapers.org/tpp > > 3. Backporting of previous issues of TPP from Volume 1 Issue 1 is > complete > > 4. We had "soft-launched" TWO new periodicals - The Python Papers > Monographs (for monograph-length submissions which may include > dissertations, conference proceedings, case studies and advanced-level > lectures) and The Python Papers Source Codes (modeled after ACM > Collected Algorithms and provides a collection of software and source > codes, usually associated with papers published in The Python Papers > and The Python Papers Monograph). They shall be TPPM and TPPSC > respectively. > > 5. Collectively, TPP, TPPM and TPPSC will be umbrella-ed as The Python > Papers Anthology (TPPA) and managed under the same editorial > committee. > > 6. Probably the most important development to TPP is that TPP is > currently indexed by a number of services, including Google Scholar > and OAIster, as a result of using Open Journal System. > > So, please enjoy our latest edition and we look towards all of your > continued support and contributions. > > Thank you. > > Cheers > Maurice Ling > Co-Editor-in-Chief, The Python Papers Anthology Good to see that the newest edition of the journal is out. Also, I believe the correct URL should either be: http://ojs.pythonpapers.org/ or http://ojs.pythonpapers.org/index.php/tpp Thanks for providing this great resource. Samir From deets at nospam.web.de Fri Sep 5 11:23:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 17:23:10 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <fc6a6c32-a023-4d6e-9089-bbcfc42de8d5@a8g2000prf.googlegroups.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> <acdc94a1-9f8c-49f3-b063-dd536e480d07@v39g2000pro.googlegroups.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> <48c03b91$0$14747$426a74cc@news.free.fr> <fc6a6c32-a023-4d6e-9089-bbcfc42de8d5@a8g2000prf.googlegroups.com> Message-ID: <6id16uFq5171U1@mid.uni-berlin.de> Ivan Illarionov schrieb: > On 4 ????, 21:49, Bruno Desthuilliers > <bdesth.quelquech... at free.quelquepart.fr> wrote: >> Ivan Illarionov a ?crit : >> >> >> >>> On 4 ????, 22:59, Carl Banks <pavlovevide... at gmail.com> wrote: >>>> You can write code to guard against this if you want: >>>> class A: >>>> legal = set(["x"]) >>>> def __setattr__(self,attr,val): >>>> if attr not in self.legal: >>>> raise AttributeError("A object has no attribute '%s'" % >>>> attr) >>>> self.__dict__[attr] = val >>>> def __init__(self,x): >>>> self.y = x >>>> I suspect most people who go into Python doing something like this >>>> soon abandon it when they see how rarely it actually catches anything. >>> '__slots__' is better: >> For which definition of "better" ? __slots__ are a mean to optimize >> memory usage, not to restrict dynamism. Being able to dynamically add >> arbitrary attributes is actually a feature, not a bug, and uselessly >> restricting users from doing so is not pythonic. IOW : don't do that. > > Carl's example is restricting dynamism in the same way as __slots__. > I've just suggested a better implementation. It is not me who > suggested dynamism restriction as a way to guard against errors. This is not correct. While Carl's Example looks similar, you actually *can* create new attributes using obj.__dict__['name'] = value __slots__ OTOH prevents that because it does create instances *without* an instance-dict. This being said, I think we all agree that it's nothing to be desired. Diez From sjmachin at lexicon.net Wed Sep 10 19:38:59 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Sep 2008 16:38:59 -0700 (PDT) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <ga91ft$12t$1@inews.gazeta.pl> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> Message-ID: <f9e73dd3-0600-45dd-8a35-2aaf9bf8d84d@z6g2000pre.googlegroups.com> On Sep 11, 4:16?am, Aaron Scott <aaron.hildebra... at gmail.com> wrote: > Taking everything into consideration, my code is now: > > import struct > file = open("test.gde", "rb") > signature = file.read(3) > version, attr_count = struct.unpack('II', file.read(8)) > print signature, version, attr_count > for idx in xrange(attr_count): > ? ? ? ? attr_id, attr_val_len = struct.unpack('II', file.read(8)) > ? ? ? ? attr_val = file.read(attr_val_len) > ? ? ? ? print attr_id, attr_val_len, attr_val > file.close() > > which gives a result of: > > GDE 2 2 > 1 4 ? > 2 4 ??? > > Essentially, the same results I was originally getting :( Stop thrashing about, and do the following: (1) print repr(open('test.gde, 'rb').read(100)) (2) tell us what you EXPECT to see in attr_val etc (3) tell us what platform the file was created on and what platform it's being read on (4) (on the reading platform, at least) import sys; print sys.byteorder When showing results, do print ..., repr(attr_val) From berthe.loic at gmail.com Wed Sep 3 13:30:01 2008 From: berthe.loic at gmail.com (LB) Date: Wed, 3 Sep 2008 10:30:01 -0700 (PDT) Subject: Help needed to freeze a script. Message-ID: <7f364174-75c6-4120-b00e-6f41643ccbf5@z72g2000hsb.googlegroups.com> Hi, I would like to freeze a numpy based script in order to have an application which could run without having to install numpy and cie. Indeed, I'm not root on the targeted computer and I can't easily make a complete install of numpy and scipy. So I decided to test the freeze.py tool shipped with python2.5. To complicate matters, I must say that I only have a local installation of python2.5 and numpy. I used the following command line : > python2.5 ../Python-2.5.1/Tools/freeze/freeze.py ~/Python/numpy/test_freeze.py At first sight, it seems to be fine, as I saw numpy in the liste of frozen dependancies : [...] freezing numpy ... freezing numpy.__config__ ... freezing numpy._import_tools ... freezing numpy.add_newdocs ... freezing numpy.core ... freezing numpy.core._internal ... freezing numpy.core.arrayprint ... freezing numpy.core.defchararray ... freezing numpy.core.defmatrix ... freezing numpy.core.fromnumeric ... freezing numpy.core.info ... freezing numpy.core.memmap ... freezing numpy.core.numeric ... freezing numpy.core.numerictypes ... freezing numpy.core.records ... freezing numpy.ctypeslib ... [...] freezing numpy.version ... But at the end I saw this message : Warning: unknown modules remain: _bisect _csv _ctypes _curses _hashlib _heapq [...] numpy.core._dotblas numpy.core._sort numpy.core.multiarray numpy.core.scalarmath numpy.core.umath numpy.fft.fftpack_lite numpy.lib._compiled_base numpy.linalg.lapack_lite numpy.random.mtrand operator parser pyexpat readline [...] Now run "make" to build the target: test_weibull I runned make without any problem but the final application didn't work : % ./test_freeze Traceback (most recent call last): File "/home/loic/Python/numpy/test_freeze.py", line 8, in <module> import numpy as np [...] File "/home/loic/tmp/bluelagoon/lib/python2.5/site-packages/numpy/ core/__init__.py", line 5, in <module> import multiarray ImportError: No module named multiarray Is there any known issue when freezing a numpy based script ? I should add that I configured my PYTHONPATH to match my local installation > echo $PYTHONPATH /home/loic/lib/python:/home/loic/tmp/bluelagoon/lib/python2.5:/home/ loic/tmp/bluelagoon/lib/python2.5/site-packages/: and this local installation work fine : > python2.5 -c 'import numpy; print numpy.__version__; import numpy.core.multiarray; print "no pb"' 1.2.0b2 no pb Have you got any recipe to freeze numpy based script ? Regards, -- LB From tom.willis at gmail.com Tue Sep 23 14:45:55 2008 From: tom.willis at gmail.com (Thomas G. Willis) Date: Tue, 23 Sep 2008 11:45:55 -0700 (PDT) Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <cab78de2-e472-439d-a0ec-de7e34b7be93@b2g2000prf.googlegroups.com> <00245d29-de1b-4c5e-b5bf-a99fb7a3ce25@a70g2000hsh.googlegroups.com> Message-ID: <eca5012c-65c6-4857-b135-104191a45056@r66g2000hsg.googlegroups.com> > But surely the idea behind it will eventually spread. ?It's really > just comprehensions generalized over XML and relational datasets, a > noble goal. ?Besides, it's main purpose for .NET was to bring > functional programming to it. ?Python already has that, somewhat... it's really any object out of the box, i think the sql linq stuff is more of a query compiler, IMO sqlalchemy does that. query = select(user_cols, and_(table_relationship.c.accept_user_id==user.id, table_relationship.c.start_date==None ), from_obj=join( table_relationship,table_user, onclause=table_user.c.id==table_relationship.c.init_user_id ).outerjoin(table_profile) ) session.execute(query).fetchall() XML? meh hopefully I would never need it. :) C# is my day job, and when I got my hands on LINQ back in January my initial thought was "Finally I have list comprehensions!!!! day job is fun again" For the most part, I think C# is catching up. From antonyjeeva007 at gmail.com Tue Sep 30 07:34:33 2008 From: antonyjeeva007 at gmail.com (michale angelo) Date: Tue, 30 Sep 2008 04:34:33 -0700 (PDT) Subject: GREAT WAY TO EARN $300 IN A SINGLE DAY.MOST LEGIBLE WAY TO MAKE MONEY Message-ID: <f8fd6cee-b8d6-4615-95ce-1102fefdf07f@r66g2000hsg.googlegroups.com> GREAT WAY TO EARN $300 IN A SINGLE DAY.MOST LEGIBLE WAY TO MAKE MONEY FROM ONLINE Your Opinion is Worth Gold To Big Business Network .Discover How to Make as Much Money as YouWant, Just By Having an Internet Connection,Some Spare Time, and an Opinion!?Your Opinion is Worth Gold To Big Business?and They?Ready to Pay You Right Now for Your Time! This Little-Known Way to Make Easy Money on the Internet isHelping Thousands of People Just Like You Achieve Their Dreams .check this link: http://tinyurl.com/4jkuwx LIFE CHANGING NETWORK WORK SINCERELY AND EARN AS MUCH AS YOU WANT From deets at nospam.web.de Mon Sep 15 15:40:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 21:40:03 +0200 Subject: environment variable issue In-Reply-To: <48ceb82a$0$2861$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> <mailman.1057.1221505773.3487.python-list@python.org> <48ceb82a$0$2861$ba620e4c@news.skynet.be> Message-ID: <6j7s0jF1t8ecU1@mid.uni-berlin.de> Michel Leunen schrieb: > Tim Chase a ?crit : > >> Your HOSTNAME variable hasn't been exported to subshells. You can >> check this by looking at the output of >> >> bash$ export -p >> >> which will print all the variables that are exported. I suspect >> you'll see $USER in the list, but not $HOSTNAME > > Actually HOSTNAME seems to be exported as well: > > $ export -p | grep HOSTNAME > declare -x HOSTNAME="LinuxPC" > > I don't know what to think of this but it's the beginning of an > explanation. Not on my machine, and *if* it is exported, python gets it. deets at absinth:~$ export -p | grep HOSTNAME deets at absinth:~$ export HOSTNAME deets at absinth:~$ export -p | grep HOSTNAME declare -x HOSTNAME="absinth" deets at absinth:~$ python -c "import os; print os.environ.get('HOSTNAME')" absinth deets at absinth:~$ Diez From marco.bizzarri at gmail.com Mon Sep 15 16:07:50 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 15 Sep 2008 22:07:50 +0200 Subject: MVC with Python In-Reply-To: <gamdkr$h54$1@ger.gmane.org> References: <gamdkr$h54$1@ger.gmane.org> Message-ID: <3f0d61c40809151307p76c864e5he9911593b676548e@mail.gmail.com> On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann <george at george-net.de> wrote: > Hello, > > I need some advice on how to implement model-view-controller. I am trying to > develop a GUI application with PyQt, yet the problem rather applies to mvc > in general, not just GUI applications. > > Let's say the data is a list of objects with a common base class. The views > are either a graphical representation of the objects or some form of textual > input. The views shall change the model by using command objects (for undo, > e.g. QUndoCommand). > > My current approach is to implement the model as a class with a list-like > interface, with methods insert(), remove(), __getitem__(), __setitem__(),... > and a signal to notify the views. The objects in the list have methods to > change their state as well. > > My problem is, how do the commands interact with the model? > Let's say I have a command that modifies an object o in the list. > > 1) If list[key_to_o] returns a reference to the object, the command can > modify the object by using this reference, i.e. list[key_to_o].setX(). So > there is no way for the list to know when the object changed - how can it > emit a singal then? > > 2) If list[key_to_o] returns a deep copy of the object, > copy_of_o = list[key_to_o], the command mofifies the copy and the updates > the list: list[key_to_o] = copy_of_o. Now the list can emit a signal in > __setitem__(). > While this may work, it seems awkward to copy around objects just to perform > a possibly simple operation on them. Additionally it might not be feasible > once objects get complex. > > 3) The interface of the classes of the objects could be reflected in the > list class, i.e. list.set_x_on_obj(key_to_obj,x). This would probably make > the list class interface very bloated. > > Of course the problem is not really limited to Python, my apologies if I'm > totally off-topic here. > > Regards > Georg > Well, I think one of the assumptions of the MVC is that the view can be notified about the changes in the model. According to your interface, the View can just be notified on operations about the *whole* model, like adding or removing elements from it. But the elements of your list-like class should be a part of your model, and therefore should be able to notify the Views by themselfves. Just my 0,02 Euros. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From pavlovevidence at gmail.com Thu Sep 4 16:16:44 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 4 Sep 2008 13:16:44 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> <48bf9aab$0$4598$426a74cc@news.free.fr> <f1b92bb7-f960-4e56-b8be-240cfc301726@b38g2000prf.googlegroups.com> <a547e63a-7315-48fe-bb04-97902dbc879a@z6g2000pre.googlegroups.com> <b9a1a7f8-0f31-4197-bcc6-e51e9d82dea8@a18g2000pra.googlegroups.com> Message-ID: <86adbdeb-9051-4877-a998-a878d4904d81@a1g2000hsb.googlegroups.com> On Sep 4, 3:38 pm, bukzor <workithar... at gmail.com> wrote: > The point of using a mixin is to not limit myself to inheriting from > VanillaCursor. I want to put this on top of various subclasses of the > vanilla cursor, like TimeLimitedCursor or RetryingCursor. I have four > other mixins that operate this way, so it's desirable to keep this one > in line with that. http://www.bartleby.com/59/3/foolishconsi.html I think that desire is hurting you more than it's helping. It's fine to be consistent for consistency's sake, but you are taking consistency to an unhealthy extreme. A mixin is simply the wrong tool to do this with. My advice: either use a proxy, or manage your connections better. Carl Banks From dudeja.rajat at gmail.com Wed Sep 24 10:42:05 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Wed, 24 Sep 2008 15:42:05 +0100 Subject: problem updating variable in a module Message-ID: <e0b6c39a0809240742k7ef2e8cfi33f88d8169b17170@mail.gmail.com> Hi, I've a problem updating my variable in a module. In my main program, I call a function from mod1 to update a variable of mod1 As soon as I update this varibale, I check it back in the mail program but it the variable from mod1 does not get updated. main Program: **************** import mod1 a = 20 mod.update(a) print mod.a <---- does not print anything mod1 ******** a = 10 def update(someInt): global a a = someInt print a <---- this does actually print a = 20 Please help. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080924/bf3fee1e/attachment-0001.html> From __peter__ at web.de Tue Sep 2 13:04:30 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 Sep 2008 19:04:30 +0200 Subject: (in memory) database References: <d1104d4c-b894-46ed-9641-fcbcdc3661d0@26g2000hsk.googlegroups.com> <mailman.297.1220190030.3487.python-list@python.org> <5enqo5-9n9.ln1@lairds.us> <b68940e4-78cc-4fbb-94cd-69478d45f96c@26g2000hsk.googlegroups.com> <k33ro5-lqh.ln1@lairds.us> <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> <3e419475-61a1-4579-a8b6-fc15f9fe0a9b@m73g2000hsh.googlegroups.com> <f1312026-9450-483d-87e0-be9903f7f9e0@z11g2000prl.googlegroups.com> Message-ID: <g9jrmq$3h6$03$1@news.t-online.com> Zentrader wrote: >> I don't understand why Cameron has a different version of Python which >> doesn't seem to have sqlite support enabled. > > Agreed, but won't the package manager tell him if python-sqlite is > installed? That would be the next step since it appears that SQLite > intself is already installed. Since Ubuntu uses precompied binaries, > Python should be configured for SQLite which again leaves no python- > sqlite as the only possibility (yeah right). BTW Python is easy to > install manually. When you install Python manually from source you need the header files for sqlite3 to get sqlite3 support. These are in the libsqlite3-dev package. I think you can distinguish a manually installed python from the packaged one by the .../local/... in its path, e. g., on my machine $ which python2.5 # in the distribution /usr/bin/python2.5 $ which python2.6 /usr/local/bin/python2.6 # installed from source I have installed libsqlite3-dev so I can't reproduce Cameron's error, but here's a similar one for bsddb: $ python2.5 Python 2.5.1 (r251:54863, Jul 31 2008, 23:17:43) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import bsddb >>> bsddb.__file__ '/usr/lib/python2.5/bsddb/__init__.pyc' $ python2.6 Python 2.6b2+ (trunk:65902, Aug 20 2008, 08:38:26) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import bsddb Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.6/bsddb/__init__.py", line 58, in <module> import _bsddb ImportError: No module named _bsddb Peter PS: Yes, I'm using 2.6, but I don't think that's relevant for the problem. From scottd at mcm.com Thu Sep 18 15:41:36 2008 From: scottd at mcm.com (Desmond Scott E) Date: Thu, 18 Sep 2008 15:41:36 -0400 Subject: Python, Factset, and Excel - Oh my! Message-ID: <04C6F615450E8D4A97EBA1DA9535667E064888@E2K3MAIL1515.mellonbank.com> I'm still a Python novice. I'm still attempting to migrate a Python-based process from Windows2000/Python v2.4.2 (#67)/Excel2000 to WindowsXP/Python v2.5.2 (r252:60911)/Excel2003. I now have a new "opportunity"! I need some help with the step in the Python script that calls Excel and invokes the Factset API to download data into a spreadsheet. I'm thinking that this is a Python / Factset API setup issue. Is the Factset API installed as a component of Python? Or does the Factset API exist in Windows and available to any application, like Python? Any insights would be greatly appreciated! Scott E. Desmond Director & Manager Equity Systems Development IT Integration Lead Mellon Capital Management Corporation 500 Grant Street, Suite 4200 Pittsburgh, PA 15258 T 412.236.0405 | F 412.236.1703 scottd at mcm.com | www.mcm.com The information contained in this e-mail may be confidential and is intended solely for the use of the named addressee. Access, copying or re-use of the e-mail or any information contained therein by any other person is not authorized. If you are not the intended recipient please notify us immediately by returning the e-mail to the originator.(16b) Disclaimer Version MB.US.1 -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080918/9eec2a7b/attachment-0001.html> From schaefer.mp at gmail.com Tue Sep 16 08:53:32 2008 From: schaefer.mp at gmail.com (MatthewS) Date: Tue, 16 Sep 2008 05:53:32 -0700 (PDT) Subject: Is 'x' an instance of a new-style class? References: <f568f4d9-b179-4ef1-9688-fcd8cb5ef641@d1g2000hsg.googlegroups.com> <mailman.1102.1221557922.3487.python-list@python.org> Message-ID: <739d438d-3631-4d06-8855-65097a5623aa@z66g2000hsc.googlegroups.com> On Sep 16, 11:38?am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS <schaefer... at gmail.com> ? > escribi?: > > > I've seen the question raised several times here, but apparently never > > answered. Since PyInstance_Check returns False for new-style class > > instances, is there a standard procedure for testing this using the C- > > Api? > > > I would greatly appreciate some help with this. > > In Python you would write isinstance(x, object). In C, "object" is ? > PyBaseObject_Type, and a direct translation would be ? > PyObject_IsInstance(x, PyBaseObject_Type), or perhaps ? > PyObject_TypeCheck(x, ?&PyBaseObject_Type) (to mimic how other PyXXX_Check ? > are implemented, and probably faster) > > -- > Gabriel Genellina Thanks Gabriel, the second solution seems to work based on my tests. So I have this now this test: static BOOL IsPythonInstance( PyObject * src ) { { // old style classes or instances or new style classes or instances if( ( PyInstance_Check( src ) ) || ( PyClass_Check( src ) ) || PyObject_TypeCheck( src, &PyBaseObject_Type) ) { return TRUE; } return FALSE; } } From steven at REMOVE.THIS.cybersource.com.au Wed Sep 10 06:24:29 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 10 Sep 2008 10:24:29 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <mailman.764.1221031609.3487.python-list@python.org> Message-ID: <pan.2008.09.10.10.24.30@REMOVE.THIS.cybersource.com.au> On Wed, 10 Sep 2008 09:26:20 +0200, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> You've created a solution to a problem which (probably) only affects a >> very small number of people, at least judging by your use-cases. Who >> has a 4GB XML file > > Getting 4GB XML files from, say, logging processes or databases that can > render their output as XML is not that uncommon. They're usually > record-oriented, and are intended to be processed as streams. And given > the right tools, doing that is no harder than doing the same to a 4GB > text file. Fair enough, that's a good point. But would you expect random access to a 4GB XML file? If I've understood what Castironpi is trying for, his primary use case was for people wanting exactly that. -- Steven From Afro.Systems at gmail.com Wed Sep 10 15:33:56 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Wed, 10 Sep 2008 12:33:56 -0700 (PDT) Subject: Simple UDP server References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> <mailman.822.1221072987.3487.python-list@python.org> <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> <mailman.823.1221074511.3487.python-list@python.org> Message-ID: <fb4bd0c9-65c4-40a7-ae94-7ff781abdf1a@a70g2000hsh.googlegroups.com> > Transmitting large binary data over UDP? That makes only sense for few > applications like video and audio streaming. UDP does neither guarantee > that your data is received nor it's received in order. For example the > packages A, B, C, D might be received as A, D, B (no C). > > Can your protocol handle missing packages and out of order packages? I intend of using it for audio transmission and don't care about lose or out of order. From half.italian at gmail.com Tue Sep 30 00:44:19 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 29 Sep 2008 21:44:19 -0700 (PDT) Subject: PYTHON WORKING WITH PERL ?? References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> <20080929133153.fc745f9c.darcy@druid.net> <mailman.1695.1222717454.3487.python-list@python.org> Message-ID: <c9dc789a-34e1-43ba-ba0f-1c6a508d9a91@m45g2000hsb.googlegroups.com> On Sep 29, 12:44?pm, "Blubaugh, David A." <dbluba... at belcan.com> wrote: > Sir, > > You are absolutely correct. ?I was praying to G_d I did not have to > slaughter my project's source code in this manner. ?However, like life > itself, I was given legacy source code (i.e. someone else errors to fix) > in Perl. ?However, I have just found out that there is a way to import > the Perl interpreter within Python!!! ?I now believe I can utilize > python as the main platform to develop the project upon !! ? > > Thanks, > > David > > -----Original Message----- > From: D'Arcy J.M. Cain [mailto:da... at druid.net] > Sent: Monday, September 29, 2008 1:32 PM > To: Blubaugh, David A. > > Cc: python-l... at python.org > Subject: Re: PYTHON WORKING WITH PERL ?? > > On Mon, 29 Sep 2008 13:16:14 -0400 > "Blubaugh, David A." <dbluba... at belcan.com> wrote: > > I was wondering if it was possible to have a situation where a > > programming project would utilized BOTH python and perl? ?Such as > > utilizing python for internet programming and then utilize perl for > > text processing and systems programming? ?Is this even feasible??? > > I don't see why not but I also question if it is a good idea. ?Once you > have all your objects and low level methods written in Python it just > makes sense to re-use them rather than trying to duplicate the > functionality in another language. > > Of course, sometimes we don't have control over our entire environment > so yes, you can mix them if you have to. > Rewrite everything in python. Save yourself now...while you still can. ~Sean From rocksportrocker at googlemail.com Thu Sep 11 06:56:38 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 11 Sep 2008 03:56:38 -0700 (PDT) Subject: Extracing data from webpage References: <mailman.862.1221126931.3487.python-list@python.org> Message-ID: <89422ef8-9d09-47f7-9a35-20b0c7b8e4d9@s50g2000hsb.googlegroups.com> On 11 Sep., 11:55, srinivasan srinivas <sri_anna... at yahoo.co.in> wrote: > Hi, > I am trying to download data from a webpage. I use mechanize python module. > Could someone tell me how to set/pass an agent?like Mozilla or IE that we do in perl's WWW::Mechanize?? > > Thanks, > Srini > http://wwwsearch.sourceforge.net/mechanize/doc.html Greetings, Uwe From fredrik at pythonware.com Thu Sep 11 02:32:52 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 08:32:52 +0200 Subject: I want to use a C++ library from Python In-Reply-To: <1buzw9k4gimaf$.dlg@ostling.com> References: <i2gdjiu8ys7i.dlg@ostling.com> <6ipd53FrptpiU1@mid.uni-berlin.de> <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> <6ipr40Fr7kr2U1@mid.uni-berlin.de> <mailman.782.1221051245.3487.python-list@python.org> <1buzw9k4gimaf$.dlg@ostling.com> Message-ID: <gaae2k$vnh$1@ger.gmane.org> Anders Eriksson wrote: > I have looked (very briefly) at the three framework you mention but they > all need the source code of the C++? No, they need header files and an import library to be able to compile the bindings and link them to your DLL. Do you know enough about C/C++ build issues to be able to compile a C++ program against the given library? If you do, fixing the rest should be straightforward, since the binding is just another C++ program designed to be imported by Python. </F> From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 07:48:29 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 13:48:29 +0200 Subject: is decorator the right thing to use? In-Reply-To: <LESCk.1818$Pv5.481@edtnps83> References: <h3zCk.1766$T65.1068@edtnps82> <bddeabb7-e979-4ff5-9136-d833af8bcdd4@e53g2000hsa.googlegroups.com> <vPDCk.1808$T65.994@edtnps82> <48db50aa$0$3750$426a74cc@news.free.fr> <HoOCk.1756$Pv5.1315@edtnps83> <48dbc82e$0$1120$426a74cc@news.free.fr> <f0826084-57f5-423f-b361-808a580f4bc5@t54g2000hsg.googlegroups.com> <nFQCk.1781$Pv5.1597@edtnps83> <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> <QKRCk.1801$Pv5.525@edtnps83> <1fc9b5c2-0e58-4b48-9352-4122986ce7ec@k13g2000hse.googlegroups.com> <LESCk.1818$Pv5.481@edtnps83> Message-ID: <48dccc08$0$3888$426a34cc@news.free.fr> Dmitry S. Makovey a ?crit : (snip) > I never used metaclasses before and > decorators seemed to be bit more straight-forward to me :) ..oh well. Don't be afraid !-) While it's true that they can be a bit confusing at first, metaclasses are just classes - whose instances happens to be classes themselves. And while you're certainly right to not jump on metaclasses *before* hanving spent a bit time thinking of other possible solutions, there's nothing wrong with using metaclasses when that's really what you need... From wuwei23 at gmail.com Tue Sep 2 23:31:34 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 2 Sep 2008 20:31:34 -0700 (PDT) Subject: MoinMoin: trouble after install References: <mailman.393.1220397429.3487.python-list@python.org> Message-ID: <20837f42-0132-4ffb-a9e3-4f90d0c43f70@p31g2000prf.googlegroups.com> On Sep 3, 9:16?am, "John [H2O]" <washa... at gmail.com> wrote: > I've installed MoinMoin easily enough, but i have two problems now. This is more of a MoinMoin issue than a Python one. You'll find a lot more support through the MoinMoin site: http://moinmo.in/ Especially: http://moinmo.in/MoinMoinQuestions http://moinmo.in/MoinMoinChat From san82moon at gmail.com Mon Sep 1 04:48:34 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:48:34 -0700 (PDT) Subject: how to find position of dictionary values References: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <5118fa5c-d868-4d74-936f-544ef82d8873@i24g2000prf.googlegroups.com> On Sep 1, 1:45 pm, Bruno Desthuilliers <bruno. 42.desthuilli... at websiteburo.invalid> wrote: > lee a ?crit : > > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, > > ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? > > It's quite simple (hint : read the FineManual(tm) for dict.items() and > list.index()), but 1/totally inefficient and 2/not garanteed to yield a > single value (what if 'dfsdf' happens to be also the 4th item of the > list bound to key 'address' ?). > > May I suggest you rethink your data structure instead ? What you have > here is obviously a collection of 'phno/email/name/address'records. > These records shouldn't be split across different objects. Assuming > 'phno' is a unique identifier for each record, a better data structure > would be: > > records = { > 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > # etc > > } > > This way, the lookup is as simple and efficient as possible. > > My 2 cents.... hi, i agree with u, my data strusture is not efficient. but all the records,viz...name,phno, email,address are all generated at runtime , when the user enters them. so how can i design my datastructure in that case? From fredrik at pythonware.com Mon Sep 15 16:32:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 22:32:18 +0200 Subject: append on lists In-Reply-To: <gamg4f$f54$1@online.de> References: <gamffv$qms$1@online.de> <mailman.1062.1221509879.3487.python-list@python.org> <gamg4f$f54$1@online.de> Message-ID: <gamgom$tmm$1@ger.gmane.org> Armin wrote: >>> just a dumb question. >>> >>> Let a = [1,2,3,4,5] >>> >>> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? >> >> yeah, that's a dumb question. > > yeah, that's a dumb answer. did you read your own post? I did. </F> From half.italian at gmail.com Mon Sep 29 01:59:10 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 28 Sep 2008 22:59:10 -0700 (PDT) Subject: Web programming in Python. References: <eb5978f8-e802-48d2-a61f-207c25ac7059@y21g2000hsf.googlegroups.com> <ace09154-e1c1-424e-875e-5193ae210b57@w7g2000hsa.googlegroups.com> Message-ID: <2afd3f2f-8b80-4a99-965a-6e27f7000055@r15g2000prh.googlegroups.com> On Sep 28, 4:51?pm, Kurda Yon <kurda... at yahoo.com> wrote: > 1. On my server (in my directory) I found "cgi-bin" subdirectory. > > 2. In the "cgi-bin" I have created a file "test.py". > > 3. In that file I put: > #!/usr/bin/python2.4 python > print "Hello, World!" > (I have checked, I have "/usr/bin/python2.4" directory.) > > 4. I give the following permissions to the "test.py": > -rwx---r-x > > 5. The "cgi-bin" directory has the following permissions: > drwx---r-x > > 6. In the "cgi-bin" I have created the ".htaccess" file which > contains: > Options +ExecCGI > AddHandler cgi-script .py > > And it still does not work! If I try to see the page by my browser I > see: > Internal Server Error > The server encountered an internal error or misconfiguration and was > unable to complete your request. > ... Your server logs are your friend. Check /var/log/httpd/error.log for errors. Have you loaded the modpython module in your httpd.conf? ~Sean From szabolcs.ferenczi at gmail.com Sun Sep 28 12:52:52 2008 From: szabolcs.ferenczi at gmail.com (Szabolcs Ferenczi) Date: Sun, 28 Sep 2008 09:52:52 -0700 (PDT) Subject: destructor not called References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> Message-ID: <2067c2f1-582d-43a1-857d-82900f83a2ee@d1g2000hsg.googlegroups.com> On Sep 28, 6:00?pm, Marcin201 <marcin... at gmail.com> wrote: > I have a class which uses a temporary directory for storing data. ?I > would like that directory to be removed when the class is no longer > used. ?I have tried removing the temporary directory from the class > destructor, however, it was never called. The RAII (Resource Acquisition Is Initialization) pattern is not applicable to Python since the language concept is not suitable for it. The __del__ is not a genuine destructor. In your case it might not be performed when you expected it because there were still references left around to the object. You must take care to break those references. However, you can apply the EAM (Execute Around Method) pattern in Python to achieve the same effect. You can apply the EAM pattern with help of the `with' statement: with Foo() as a: # work with `a' In this case you must implement methods __enter__ and __exit__ instead of __init__ and __del__. The method __enter__ must return an instance of Foo. You can achieve the same effect with try-finally block as well: a = Foo() try: # work with `a' finally: # make `a' remove directories Best Regards, Szabolcs From castironpi at gmail.com Tue Sep 16 22:44:36 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 19:44:36 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <cba00205-ee1c-4ee6-9914-c46c7f9c17a2@j22g2000hsf.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> Message-ID: <2cbfdce2-9203-4136-a274-bc7d19dc293a@y38g2000hsy.googlegroups.com> On Sep 16, 9:25?pm, Fett <FettMan... at gmail.com> wrote: > On Sep 16, 9:00 pm, "Aaron \"Castironpi\" Brady" > > > > <castiro... at gmail.com> wrote: > > On Sep 16, 8:50 pm, Fett <FettMan... at gmail.com> wrote: > > > > I am trying to find a wrapper to do linear programming within python. > > > I am using an ubuntu machine and I have apt-get'd lp_solve, which > > > works just fine. If someone knows of a wrapper that will work with > > > that that'd be great. > > > > I also heard that scipy has a wrapper, however, I can't find any > > > documentation on it, nor can I seem to find it with dir(). If anyone > > > knows where there is good documentation on this I would love to use > > > that (the more native to python the better imo). > > > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > > > openopt, and cvxopt. I can't seem to find any with enough > > > documentation to get me off the ground. Some I can't compile, some I > > > can't even find out how to compile. > > > > If anyone knows of an LP package (preferably with IP as well, like > > > lp_solve has), that interfaces well with python and has enough > > > documentation to get a dependency newb like myself off the ground that > > > would be great. > > > Google says: > > > about 254,000 for linear programming python. > > > Link 3 is: > > >http://wiki.python.org/moin/NumericAndScientific/Libraries > > > Scroll down. > > Yes, many of those seem to be deprecated, without destinations to > links, most are poorly or not documented at all. The few that are, I > still can't get running. Of those 254, I think I have tried at least > 10 pages worth. Still no luck. > > # lpsolvpy - Can't get it to compile - dependency problems. > # Lp_solve5 - NO python binding yet. Volunteers needed for python > bindings. > # pycplex - You need to compile the CPX.so module. Change the required > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > sure what to do here. > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > I missed the second link to the python bindings, looked all over the > glpk site for anything about python. > # SciPy --http://www.scipy.org- supposedly has this, but as I said, > I can't find any mention of it anywhere but on the site you linked. > # pySimplex - (broken link)(broken link) > # Simplex - link is broken, but nothing is mentioned > > I'll take a closer look at glpk's python bindings and if there is any > documentation on them, maybe I'll have some luck. btw, I have been > looking for something that works, I have over 5 packages on my desktop > that I have tried to get up and running, but none of them seem to > work. glpk makes 6. If you can find one working in C, use ctypes to link into Python. We can help you with that part. It lets you pass primitive types, structs, arrays, pointers, to C modules and return values. You need to know the C signatures to set up the Pythonized signatures. From bernhard.walle at gmx.de Tue Sep 30 12:00:16 2008 From: bernhard.walle at gmx.de (Bernhard Walle) Date: Tue, 30 Sep 2008 18:00:16 +0200 Subject: How to add CC and BCC while sending mails using python In-Reply-To: <46da4e770809300727j368a27b8qc570a8451a53e470@mail.gmail.com> References: <46da4e770809300727j368a27b8qc570a8451a53e470@mail.gmail.com> Message-ID: <20080930180016.604e9f52@kopernikus.site> Hi, * cindy jones [2008-09-30 19:57]: > > Can someone tel me how to add cc's and bcc's while sending mails using > python Following (tested) snippet should help: ------------------ 8< ------------------------------ from smtplib import SMTP from email.mime.image import MIMEImage from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart to = 'to_address at example.invalid' cc = 'cc_address at example.invalid' bcc = 'bcc_address at example.invalid' msg = MIMEMultipart() msg['To'] = to msg['Cc'] = cc msg['From'] = 'bernhard at bwalle.de' msg['Subject'] = 'Test' text = MIMEText('Das ist ein Test') text.add_header("Content-Disposition", "inline") msg.attach(text) s = SMTP('test.smtp.relay') s.sendmail(msg['From'], [to, cc, bcc], msg.as_string()) s.quit() ------------------ >8 ------------------------------ Regards, Bernhard From rsinger at ____.com Tue Sep 23 18:41:47 2008 From: rsinger at ____.com (Robert Singer) Date: Wed, 24 Sep 2008 00:41:47 +0200 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <eogid4d6s2a5l55pu20220sr2bdt5s6hob@4ax.com> <c3f6f232-4165-495b-b998-cc813eae57ea@f63g2000hsf.googlegroups.com> Message-ID: <4hrid45cb17q3pm48ppc3f7dh8eql92iq9@4ax.com> On Tue, 23 Sep 2008 13:34:10 -0700 (PDT), sturlamolden <sturlamolden at yahoo.no> wrote: >1. gfortran is not Absoft. I find this comment absurd. What did you mean by it ? Yes, gfortran is not Absoft, just as red is not blue (?!). I also don't understand whether you're looking for a free or a commercial compiler. I got the impression from your previous post that money was an object. >2. If I program the same in C99 and Fortran 95, and compile with gcc >and gfortran, the C99 code runs a lot faster (I've only tested with >wavelet transforms). Hmm. Unfortunatelly, i have none whatsoever experience in that field. Completely different area of study here, so without seeing at least some code, I cannot comment anything on that part. And 'a lot faster' is a very relative term. > >3. gfortran is not Absoft. > True. Best regards Bob From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 16:02:02 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 22:02:02 +0200 Subject: Late initialization using __getattribute__ In-Reply-To: <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> Message-ID: <48bf092a$0$14321$426a74cc@news.free.fr> bukzor a ?crit : (snip) > Thanks for the reply. Just to see it not work, I tried to remove > __getattribute__ from LateInitMixIn, but couldn't get it to work. ??? Sorry, I don't get what you mean... > My Base class is a C class (_mysql.connection from MySQLdb) that > sometimes segfaults if you try to use it before it's fully > initialized, Then don't use it before it's fully initialized. patient: "doctor, when I do this, it hurts" doctor : "then don't do it" !-) More seriously, I have used MySQLdb for years on more than a dozen linux distribs, and never had such a problem. Is this a known bug ? Or is there something wrong with your setup ? > so unfortunately I think I need to use __getattribute__ > to do this. I'm doing all this just to make the connection not > actually connect until used. I may be dumb, but I don't get how this is supposed to solve your problem. But anyway : there's a known design pattern for what you're trying to do, that doesn't require mixins nor messing with __getattribute__ (which, I repeat, is more often than not something you *don't* want to do). The name of the design pattern is "proxy". I strongly suggest that you 1/ try to cure the real problem instead of hacking around and 2/ read about the proxy design pattern. My 2 cents... From bearophileHUGS at lycos.com Fri Sep 5 11:26:25 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 08:26:25 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <g9r7hq$ri6$1$8302bc10@news.demon.co.uk> <dullrich-33A94E.10163805092008@text.giganews.com> Message-ID: <b4f287a7-8e1f-4057-9711-2f2519869a10@m73g2000hsh.googlegroups.com> David C. Ullrich: > I didn't mention what's below because it doesn't seem > likely that saying max([]) = -infinity and > min([]) = +infinity is going to make the OP happy... Well, it sounds cute having Neginfinite and Infinite as built-int objects that can be compared to any other type and are < of or > of everything else but themselves. Probably they can be useful as sentinels, but in Python I nearly never use sentinels anymore, and they can probably give some other problems... Bye, bearophile From timr at probo.com Mon Sep 1 00:26:48 2008 From: timr at probo.com (Tim Roberts) Date: Mon, 01 Sep 2008 04:26:48 GMT Subject: parsing "&A" in a string.. References: <g9etqg$k7p$1@ger.gmane.org> <mailman.304.1220216809.3487.python-list@python.org> Message-ID: <mlrmb4t496nmbc84c2ud77fs2tt2fehbvk@4ax.com> "bruce" <bedouglas at earthlink.net> wrote: > >it's the beautifulsoup() that's taking the "&E" and giving the "&E;"... Right, as it should. "A&E" is not valid HTML, and beautifulsoup expects valid HTML. This can be difficult to fix in the general case, because your page might already contain "&". If it is possible that some of them might be wrong while some are right, you can do something like: s = s.replace( '&', '&' ).replace( '&', '&' ) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From tjreedy at udel.edu Mon Sep 29 18:52:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 18:52:40 -0400 Subject: Source code for python nativ methods and classes In-Reply-To: <257224ff0809291400t1611aa6cm1b033b539392f353@mail.gmail.com> References: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> <257224ff0809291400t1611aa6cm1b033b539392f353@mail.gmail.com> Message-ID: <gbrm7m$scj$1@ger.gmane.org> Bard Aase wrote: > On Mon, Sep 29, 2008 at 10:51 PM, Mohed <mohed at hotmail.com> wrote: >> Hello. >> I am interrested in seeing the source code for all the nativ builtin >> methods and clases in python. Is there a webpage that lists them or is >> this done easier some other way. > > Check it out from svn? > svn co http://svn.python.org/projects/python/trunk/ > > or browse the code at http://svn.python.org/view/python/trunk/ This has the code for the upcoming 2.6 release. For other branches http://svn.python.org/view/python/branches/ in particular py3k or release25-maint. Built-in classes are in the Objects sub-directory. (But there is a bit of math in the Python sub-dir). Built-in modules are in the Modules sub-directory. Python-coded modules are in the Lib sub-directory. I don't know where the built-in functions are. To see the current state of a file, click on the revision number in the second column. Clicking on the name in the first column give a rather strange change log that goes forward through each year as it goes back through the years. Terry Jan Reedy From rocksportrocker at googlemail.com Fri Sep 26 11:19:04 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Fri, 26 Sep 2008 08:19:04 -0700 (PDT) Subject: lxml question Message-ID: <2f9ef7d5-616e-4a4b-9a83-e23194fee3a9@m3g2000hsc.googlegroups.com> Hi, I have to parse some text which pretends to be XML. lxml does not want to parse it, because it lacks a root element. I think that this situation is not unusual, so: is there a way to force lxml to parse it ? My work around is wrapping the text with "<root>...</root>" before feeding lxmls parser. Greetings, Uwe From samslists at gmail.com Tue Sep 16 20:58:31 2008 From: samslists at gmail.com (Sam) Date: Tue, 16 Sep 2008 17:58:31 -0700 (PDT) Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <mailman.766.1221033019.3487.python-list@python.org> Message-ID: <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> Gabriel, et al. It's hard to find a web site that uses deflate these days. Luckily, slashdot to the rescue. I even wrote a test script. If someone can tell me what's wrong that would be great. Here's what I get when I run it: Data is compressed using deflate. Length is: 107160 Traceback (most recent call last): File "my_deflate_test.py", line 19, in <module> data = zlib.decompress(data) zlib.error: Error -3 while decompressing data: incorrect header check And here's my test script: #!/usr/bin/env python import urllib2 import zlib opener = urllib2.build_opener() opener.addheaders = [('Accept-encoding', 'deflate')] stream = opener.open('http://www.slashdot.org') data = stream.read() encoded = stream.headers.get('Content-Encoding') if encoded == 'deflate': print "Data is compressed using deflate. Length is: ", str(len(data)) data = zlib.decompress(data) print "After uncompressing, length is: ", str(len(data)) else: print "Data is not deflated." On Sep 10, 12:50?am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Tue, 09 Sep 2008 16:38:54 -0300, Sam <samsli... at gmail.com> escribi?: > > > Un-deflating doesn't work. ?I get "zlib.error: Error -3 while > > decompressing data: incorrect header check" > > zlib.decompress should work - can you provide a site that usesdeflateto ? > test? From CapnBearbossa at googlemail.com Mon Sep 22 17:31:24 2008 From: CapnBearbossa at googlemail.com (CapnBearbossa at googlemail.com) Date: Mon, 22 Sep 2008 14:31:24 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? Message-ID: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> hi all, forgive me , but the RTFM and Google search approaches are not yielding an answer on this question. I need to know if there's a top level python interpreter command that clears all user variables (not built-ins) from the global namespace. In other words a statement, or some_command_or_function(), that does this: >>> x=3 >>> y=4 >>> z=[] >>> dir() ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] >>> some_command_or_function() >>> dir() ['__builtins__', '__doc__', '__name__'] thanks, 1 desperate snake oil programmer .... From fredrik at pythonware.com Wed Sep 3 14:36:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 03 Sep 2008 20:36:42 +0200 Subject: Is try-except slow? In-Reply-To: <8b3857ec-e629-44a3-98f2-8fe509df7b75@f36g2000hsa.googlegroups.com> References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> <8b3857ec-e629-44a3-98f2-8fe509df7b75@f36g2000hsa.googlegroups.com> Message-ID: <g9mlfq$isa$1@ger.gmane.org> process wrote: > is this faster btw? I guess big doesn't help, it's only retrieved once > anyway? But is rows retrieved in every loop? the python interpreter > aint too smart? > > def getPixels(fileName): > im = PIL.Image.open(fileName) > colors = [] > r, c = im.size > big = range(0, c) > rows = range(0, r) > for y in big: > row = [] > for x in rows: > color = im.getpixel((x,y)) > row.append(color) > colors.append(row) > return numpy.array(colors) you'd probably get more done if you read the replies you get a bit more carefully. Robert Kern suggesting using numpy.asarray earlier: def getPixels(fileName): im = PIL.Image.open(fileName) return numpy.asarray(im) if you want to work with pixels on the Python level, use im.getdata() or the pixel access object returned by im.load(). </F> From castironpi at gmail.com Sun Sep 14 15:21:54 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 14 Sep 2008 12:21:54 -0700 (PDT) Subject: Abstract class References: <mailman.1008.1221408214.3487.python-list@python.org> <roy-9FFFBD.13564414092008@news.panix.com> <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <mailman.1012.1221419718.3487.python-list@python.org> Message-ID: <64670149-9467-4ca7-9d7e-c330c1b403e4@c58g2000hsc.googlegroups.com> On Sep 14, 2:15?pm, Gary Herron <gher... at islandtraining.com> wrote: > Mr.SpOOn wrote: > > Gary Harron: > > >> I believe you are mixing up class *inheritance* and *abstract* classes. > > >> Class inheritance (with Python has has for years) is how one class inherits >behavior/properties/attributes from another class. ?The class being inherited from is >called the base class. ?This is probably what you want. > > > Well, I know the difference between an abstract class and an inherited > > one. The idea was to create a main class Note, with abstract methods, > > and implement these methods in the other classes. > > > On Sun, Sep 14, 2008 at 7:56 PM, Roy Smith <r... at panix.com> wrote: > > >> What properties or behaviors does SharpNote have which NaturalNote doesn't? > >> Unless there is some new behavior, you don't need subclasses. > > > Well, from a SharpNote I can obtain the relative NaturalNote. So if I > > have a C# I can call > > > natural('C#') ?and get 'C' > > > While in the class NaturalNote I don't need such a method, but I need > > two methods to get the sharped and flatted version > > >> Are you also going to have DoubleSharpNote and DoubleFlatNote? > > > Yes, that's an option. > > >> Consider the following code: > > >> note1 = SharpNote("E4") > >> note2 = NaturalNote("F4") > >> if note1 == note2: > >> ? print "the same note" > >> else > >> ? print "different notes" > > >> what should it print? > > > Well, that's not so simple. The idea is that I use a notation (A, B, > > C, D...) and an integer (a distance expressed in semitones) to > > identify a note. > > > Anyway, I think I need an abstract class. Or not? > > No! ?Definitely not! ? ?You need inheritance of a class from a base > class. ? Just brainstorming with you. You can support operations on the objects: note minus note = interval, note plus interval = note, and so on. (WARNING! Spoilers. Untested.) note1 = NaturalNote("G") note2 = NaturalNote("C") interval= note1- note2 print interval : <MajorInterval '5th'> note1 = SharpNote("G") note2 = NaturalNote("C") interval= note1- note2 print interval : <MinorInterval '6th'> WholeStep= MajorInterval( 2 ) print WholeStep : <MajorInterval '2nd'> note1 = NaturalNote("C") print note1- WholeStep : <FlatNote("B")> However, from what I understand (brass player), there are some cases in which you'll want that to be: print note1- WholeStep : <SharpNote("A")> What do you want to determine that? What about a KeyOf class? key= KeyOf( NaturalNote( "F" ) ) #'key' has special subclasses note1 = key.NaturalNote("C") print note1- WholeStep : <FlatNote("B")> key= KeyOf( SharpNote( "G" ) ) note1 = key.NaturalNote("C") print note1- WholeStep : <SharpNote("A")> Further, perhaps you want a 'WrittenNote' class which refers to the key signature it's written in: key= KeyOf( NaturalNote( "F" ) ) note1 = key.WrittenNote("B") print note1 : <FlatNote("B")> I do not immediately see how to represent clefs and staves: whether you'll need them at all, or whether they're just writing/rendering techniques. As for scales and chords, are there any special methods you want on them, or would a tuple of Note instances suffice? triad= ( NaturalNote( "C" ), NaturalNote( "E" ), NaturalNote( "G" ) ) One special method might be: triad= Triad( NaturalNote( "C" ), NaturalNote( "E" ), NaturalNote( "G" ) ) print triad : <C-Major triad> triad= Triad( NaturalNote( "E" ), NaturalNote( "G" ), NaturalNote( "C" ) ) print triad : <C-Major triad 1st inversion> I forgot about octaves, which can complicate the constructors. octave= Octave( 4 ) #middle C triad= Triad( octave.NaturalNote( "E" ), octave.NaturalNote( "G" ), octave.up.NaturalNote( "C" ) ) print triad : <C-Major triad 1st inversion> Or: octave= Octave( 4 ) triad= Triad( NaturalNote( "E", octave ), NaturalNote( "G", octave ), NaturalNote( "C", octave.up ) ) print triad : <C-Major triad 1st inversion> And abbreviate the name for the interval. octaveint= MajorInterval( 8 ) Abstract scales can be a tuple of intervals, where concrete scales are a tuple of notes. majorscale= ( Tonic, WholeStep, WholeStep, HalfStep, WholeStep, WholeStep, WholeStep, HalfStep ) majorCscale= [ NaturalNote( "C" )+ x for x in majorscale ] majorDscale= [ NaturalNote( "D" )+ x for x in majorscale ] To get a little more creative, you could just denote sharps and flats with a parameter: note1 = Note("G", sharp) #Or: note1 = Note("G", Note.sharp) note2 = Note("C") interval= note1- note2 print interval : <MinorInterval '6th'> It would just take some 'parameter magic' to interpret them right when paired with octaves: octave= Octave( 4 ) #middle C note1= Note( "C", sharp, octave ) note2= Note( "C", octave ) note3= Note( "C", octave, sharp ) note4= Note( "C", sharp ) That part just takes a little untwisting. (Untested.) class Note: defaultoctave= 4 def __init__( self, *args ): octave= Octave( self.defaultoctave ) accidental= Natural( ) for arg in args: if issubclass( arg, Accidental ): accidental= arg elif issubclass( arg, Octave ): octave= arg elif type( arg ) is str: name= arg Or use keywords to specify. octave= Octave( 4 ) #middle C note1= Note( "C", sharp, octave ) note2= Note( "C", octave= octave ) note3= Note( "C", octave= octave, accidental= sharp ) note4= Note( "C", sharp ) class Note: defaultoctave= 4 def __init__( self, name, octave= None, accidental= Natural( ) ): if octave is None: octave= self.defaultoctave It's open to debate whether Natural is a subclass or instance of Accidental. From bj_666 at gmx.net Sun Sep 7 18:02:04 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2008 22:02:04 GMT Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <6ij1asFqp39rU3@mid.uni-berlin.de> On Sun, 07 Sep 2008 14:51:32 -0700, andyhume at gmail.com wrote: > MAPPING_DICT = { > 'a': 'A', > 'b': 'B', > } > > my_dict = { > 'a': '1', > 'b': '2' > } > > I want the finished my_dict to look like: > > my_dict = { > 'A': '1', > 'B': '2' > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? You only have to loop through `my_dict`: In [187]: %cpaste Pasting code; enter '--' alone on the line to stop. :MAPPING_DICT = { : 'a': 'A', : 'b': 'B', :} : :my_dict = { : 'a': '1', : 'b': '2' :} :-- In [188]: dict((MAPPING_DICT[k], v) for k, v in my_dict.iteritems()) Out[188]: {'A': '1', 'B': '2'} Ciao, Marc 'BlackJack' Rintsch From dblubaugh at belcan.com Sat Sep 20 15:07:12 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Sat, 20 Sep 2008 15:07:12 -0400 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> <gb3bvk$9a1$1@ger.gmane.org> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38051C09F2@AWMAIL04.belcan.com> Sir, Let me state that do have extensive experience with developing binary files. Please note that I have followed all of the instructions to the letter as far as developing a DLL to be imported. However, it is not working correctly. I believe it might be my system environment variables?? Thanks for your reply, David Blubaugh ________________________________ From: Fredrik Lundh [mailto:fredrik at pythonware.com] Sent: Sat 9/20/2008 1:30 PM To: python-list at python.org Subject: Re: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py Blubaugh, David A. wrote: (no need to shout when filling in the subject line, thanks) > I have now been able to generate a .pyd file from a FORTRAN > file that I am trying to interface with python. I was able > to execute this with an additional insight into how f2py > operates. > > ImportError: DLL load with error code 193 Error code 193 is ERROR_BAD_EXE_FORMAT, which means that the thing you're trying to import is not a proper DLL. > copy LICENSE.txt LICENSE.pyd 1 file(s) copied. > python >>> import LICENSE Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: DLL load failed with error code 193 In general, the tools for building binary extensions for Python assumes that you have at least some basic knowledge about how to build binaries using a compiled language. </F> This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From sjmachin at lexicon.net Mon Sep 29 21:59:21 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 Sep 2008 18:59:21 -0700 (PDT) Subject: pyXLWriter warnings References: <pkn2e41apdn6ns32stlt7u2ppa3pr0senl@4ax.com> Message-ID: <531ba624-3106-4999-baf8-643d1411ae4a@x41g2000hsb.googlegroups.com> On Sep 30, 9:09?am, Robert Singer <rsinger at ____.com> wrote: > Platform: winXP, excel 2003 > Python 2.5.2 > XLWriter 0.4a3 (http://sourceforge.net/projects/pyxlwriter/) > > Is anyone here using this very nice package, for writing excel files? > I'm using it on python 2.5.2. (although it is made for older version > of python) and cannot find a way to get rid of this error (code and > errors below). > > Does anyone know how to avoid it ? I would appreciate all help and > ideas you can think of. > > Bob > -------- > > >>> import pyXLWriter as xl > >>> workbook = xl.Writer("test.xls") > >>> worksheet = workbook.add_worksheet('first') > >>> worksheet.write([3,3], "Hello doc !") > >>> worksheet.write_comment([3,3], "I'm hunting for a wabbit") > 0 > >>> workbook.close() > > -------- > Warning (from warnings module): > ? File "C:\Python25\lib\site-packages\pyXLWriter\OLEWriter.py", line > 135 > ? ? unknown3 = pack("<H", -2) > DeprecationWarning: struct integer overflow masking is deprecated > > Warning (from warnings module): > ? File "C:\Python25\lib\site-packages\pyXLWriter\OLEWriter.py", line > 135 > ? ? unknown3 = pack("<H", -2) > DeprecationWarning: 'H' format requires 0 <= number <= 65535 [big snip of similar messages] There is not much point in working on pyXLWriter source; the package is abandonware ** 2. Although I can't find it now, I recall reading a recommendation from its author (Evgeny Filatov) that its users migrate to pyExcelerator. Unfortunately pyExcelerator has not been maintained for some time now. However Chris Withers of Simplistix and I have created xlwt, a fork of pyExcelerator; Chris is hosting the SVN repo and I am maintaining it. We now have a public release out of the door (http://pypi.python.org/pypi/xlwt/). There is only one task remaining AFAIK to meet the initial goal of providing the equivalent of (pyExcelerator last released version + all sensible patches included + all known [and several unknown] bugs fixed + an easier way of specifying cell formatting ("easyxf")) -- this is support for 3D references i.e. to other worksheets in the same workbook. Christophe Tronche has adapted Ruben Mendes' pyExcelerator patch to xlwt, and it's currently undergoing testing. You may like to check out the python-excel newsgroup at http://groups.google.com/group/python-excel ... HTH, John From lists at cheimes.de Tue Sep 9 13:56:18 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 09 Sep 2008 19:56:18 +0200 Subject: PYTHONSITEDIR environment variable In-Reply-To: <eccd24ff-001b-4f4e-a9da-c7052d67383d@k30g2000hse.googlegroups.com> References: <eccd24ff-001b-4f4e-a9da-c7052d67383d@k30g2000hse.googlegroups.com> Message-ID: <ga6dc2$bh7$1@ger.gmane.org> ago wrote: > Wouldn't it be possible to support a PYTHONSITEDIR environment > variable in site.py for this purpose? I have attached a possible > patch. In what follows, if PYTHONSITEDIR is defined, that dir is used > as the only source of site-packages, extra paths can easily be added > by creating a .pth file in there. A different variable could be used > to prepend a sitedir to the list of default sitedirs (similar code > without "return None"). I had a similar idea, wrote a PEP and implemented it for 2.6 and 3.0: http://www.python.org/dev/peps/pep-0370/ Christian From Lie.1296 at gmail.com Sun Sep 28 15:06:56 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 12:06:56 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <dd7c5e64-f856-45e5-a17c-28d52f02a4c3@a18g2000pra.googlegroups.com> On Sep 29, 1:29?am, process <circularf... at gmail.com> wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. > > What is not an object in Python? > > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? A question like this is often answered by another (rhetorical) question: "What is Object Oriented actually?" The answer to that is generally: "Python is not Java." From fredo66 at fulladsl.be Thu Sep 25 04:24:47 2008 From: fredo66 at fulladsl.be (fredo66 at fulladsl.be) Date: Thu, 25 Sep 2008 01:24:47 -0700 (PDT) Subject: python sorting 2dim. array ? References: <9684e81b-df99-4d95-99f9-8345c125b69b@d77g2000hsb.googlegroups.com> Message-ID: <80dca060-31de-492a-ae1d-fccd69cdedd9@m45g2000hsb.googlegroups.com> remark: The server is using python server version 2.3.4 From bdesth.quelquechose at free.quelquepart.fr Mon Sep 22 15:38:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 21:38:30 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> <48d78c3c$0$6998$426a74cc@news.free.fr> <mailman.1360.1222091143.3487.python-list@python.org> <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> Message-ID: <48d7f46d$0$15502$426a74cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : > On Sep 22, 8:45 am, "Tim Rowe" <digi... at gmail.com> wrote: >> 2008/9/22 Bruno Desthuilliers <bruno.42.desthuilli... at websiteburo.invalid>: >> >>>> Sounds to me like a functor, aka a function object: >>>> http://en.wikipedia.org/wiki/Function_object >>> Ok, then the simple solution is to implement a callable type (__call__ >>> method), possibly with appropriate support for the descriptor protocol if >>> it's meant to be usable as a method. >> Yes -- and instantiate the thing and keep the state in the instance, >> rather than keeping the state in the class, so that it's possible to >> safely have more than one of them if a later design change calls for >> it (probably what led people off onto the sidetrack of thinking a >> singleton was called for). That's the classic way of implementing a >> "class [to be] used as a function". >> >> -- >> Tim Rowe > > I think you are either looking for a class that has a generator, or a > generator that has a reference to itself. ??? Going back to robot-mode, Aaron ? From mr.spoon21 at gmail.com Sun Sep 14 12:03:23 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 14 Sep 2008 18:03:23 +0200 Subject: Abstract class Message-ID: <8f67b6f80809140903x2e2a8cfav7745113d9bcab650@mail.gmail.com> Hi, I'm going to work on a project to represent some musical theory in Python, in an object oriented way. I have to manage many elements of music such as notes, intervals, scales, chords and so on. All these elements share properties and behavior, so what I want to do is an abstract class "Note" and other subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. The idea is not original, I read it in some papers where they talk about an implementation in smalltalk. I want to use Python (of course) and I'd like to know what is the practice in such a case. I mean, in python there aren't abstract classes, but I read about some way to emulate the same behavior. What do you suggest me? Thanks, Carlo From san82moon at gmail.com Mon Sep 1 06:51:13 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 03:51:13 -0700 (PDT) Subject: how to find position of dictionary values References: <a098543c-36d6-4aab-8669-06713345e7c2@r35g2000prm.googlegroups.com> <48bbab73$0$27858$426a34cc@news.free.fr> <e9b3e12c-3834-48ff-911b-baf01efdb8c3@r15g2000prh.googlegroups.com> <6i1rgcFo0f1gU1@mid.uni-berlin.de> Message-ID: <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> On Sep 1, 2:37 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > lee wrote: > > On Sep 1, 1:45 pm, Bruno Desthuilliers <bruno. > > 42.desthuilli... at websiteburo.invalid> wrote: > >> lee a ?crit : > > >> > hi, > >> > i have a dictionary as follows : > >> > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > >> > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > >> > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > >> > if user is enters the 3rd item of key phno, > >> > ie "dfsdf" in my dict, > >> > how can i find it is the third item in the internal list of phno of > >> > that dictionary? > > >> It's quite simple (hint : read the FineManual(tm) for dict.items() and > >> list.index()), but 1/totally inefficient and 2/not garanteed to yield a > >> single value (what if 'dfsdf' happens to be also the 4th item of the > >> list bound to key 'address' ?). > > >> May I suggest you rethink your data structure instead ? What you have > >> here is obviously a collection of 'phno/email/name/address'records. > >> These records shouldn't be split across different objects. Assuming > >> 'phno' is a unique identifier for each record, a better data structure > >> would be: > > >> records = { > >> 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > >> 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > >> # etc > > >> } > > >> This way, the lookup is as simple and efficient as possible. > > >> My 2 cents.... > > > hi, > > i agree with u, my data strusture is not efficient. but all the > > records,viz...name,phno, email,address are all generated at runtime , > > when the user enters them. so how can i design my datastructure in > > that case? > > Are "u" short on keystrokes? You are not textmessaging here... > > Regarding the actual question: there is no difference in building your or > the other structure. It's only a question of which key you use first. > Instead of first looking up the type of the record ("phno" or some such), > do that with the name of the user. If no record exists, create one. Then > populate the record with the user's values. Like this: > > user = "dsdf" > phonenumber = "123" > > record = records.setdefault(user, {}) > record["phno"] = phonenumber > > Diez i am soory for that keystrokes. can anyone tell me how can i change the value of key. suppose i have a dictionary kev = {'kabir': ['kabir at kabir.com', '1234', 'missuri'], 'shri': ['shri at shri.com', '23423', 'india'], 'marsa': ['marsa at marsa.com', '2345', 'brazil'], 'sandeep': ['sandeep at sandeep.com', '007', 'canada']} how can i change the key to something like 'sabir' and how can i change the values of kabir? From larry.bates at vitalEsafe.com Tue Sep 16 15:18:45 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 16 Sep 2008 14:18:45 -0500 Subject: new style classes, __new__, __init__ In-Reply-To: <gap0g2$l4c$1@news.LF.net> References: <gap0g2$l4c$1@news.LF.net> Message-ID: <ACTzk.30565$kh2.7108@bignews3.bellsouth.net> Torsten Mohr wrote: > Hi, > > i have some questions related to new style classes, they look > quite useful but i wonder if somebody can give me an example > on constructors using __new__ and on using __init__ ? > > I just see that when using it i can't give parameters to __new__ > and when i additionally define __init__ then __new__ is not > called. > > So i can use __new__ only for classes whose constructors don't > have parameters? > > > class C2: > def __new__(self): > print "new called" > self.a = 8 > > def __init__(self, a): > print "init called" > self.a = a > > def fct(self): > print self.a > > > a = C2(7) > a.fct() > > > This way __new__ is not called, if i remove __init__ then > there are too many parameters to __new__, if i add a parameter > to __new__ then it says that __new__ does not take arguments. > > > Thanks for any hints, > Torsten. > New style classes should be based on object: class C2(object): -Larry From clp at rebertia.com Mon Sep 15 20:08:30 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Sep 2008 17:08:30 -0700 Subject: append on lists In-Reply-To: <00dee3f7$0$20331$c3e8da3@news.astraweb.com> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <mailman.1072.1221511698.3487.python-list@python.org> <00dee3f7$0$20331$c3e8da3@news.astraweb.com> Message-ID: <47c890dc0809151708q4ca3fc44ja0efab8c181ea8b8@mail.gmail.com> On Mon, Sep 15, 2008 at 4:03 PM, Steven D'Aprano <steve at remove-this-cybersource.com.au> wrote: > On Mon, 15 Sep 2008 13:47:53 -0700, Chris Rebert wrote: > >> The code you'd actually want is: >> >> d = a[:] #copy a >> d.append(7) >> >> Or if you're willing to overlook the inefficiency: >> >> d = a + [7] >> >> But that's not idiomatic. > > Why is a + [7] more inefficient than manually copying the list and > appending to the copy? Surely both pieces of code end up doing the same > thing? > > In fact, I'd guess that the second is likely to be marginally more > efficient than the first: > > >>>> x = compile('d = a[:]; d.append(7)', '', 'exec') >>>> dis.dis(x) > 1 0 LOAD_NAME 0 (a) > 3 SLICE+0 > 4 STORE_NAME 1 (d) > 7 LOAD_NAME 1 (d) > 10 LOAD_ATTR 2 (append) > 13 LOAD_CONST 0 (7) > 16 CALL_FUNCTION 1 > 19 POP_TOP > 20 LOAD_CONST 1 (None) > 23 RETURN_VALUE > >>>> x = compile('d = a + [7]', '', 'exec') >>>> dis.dis(x) > 1 0 LOAD_NAME 0 (a) > 3 LOAD_CONST 0 (7) > 6 BUILD_LIST 1 > 9 BINARY_ADD > 10 STORE_NAME 1 (d) > 13 LOAD_CONST 1 (None) > 16 RETURN_VALUE > > > timeit agrees with me: > >>>> from timeit import Timer >>>> t1 = Timer('d = a[:]; d.append(7)', 'a = []') >>>> t2 = Timer('d = a + [7]', 'a = []') >>>> t1.repeat(number=1000) > [0.0015339851379394531, 0.0014910697937011719, 0.0014841556549072266] >>>> t2.repeat(number=1000) > [0.0011889934539794922, 0.0013048648834228516, 0.0013070106506347656] > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > Sorry, I was just speculating based on the extraneous list ([7]) used in the second one. My bad. :) Regards, Chris -- Follow the path of the Iguana... http://rebertia.com From fredrik at pythonware.com Tue Sep 2 13:25:06 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Sep 2008 19:25:06 +0200 Subject: Numeric literal syntax In-Reply-To: <6i56cpFor2puU1@mid.individual.net> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <pan.2008.09.02.06.10.51@REMOVE.THIS.cybersource.com.au> <6i56cpFor2puU1@mid.individual.net> Message-ID: <g9jsti$uf0$2@ger.gmane.org> Peter Pearson wrote: > (startled noises) It is a delight to find a reference to > that half-century-old essay (High Finance) by the wonderful > C. Northcote Parkinson, but how many readers will catch the > allusion? anyone that's been involved in open source on the development side for more than, say, ten minutes. http://www.bikeshed.com/ </F> From tchendrix at gmail.com Tue Sep 23 08:54:30 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 05:54:30 -0700 (PDT) Subject: finding domain name References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> <mailman.1404.1222174222.3487.python-list@python.org> Message-ID: <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> > Depends on the technology/web framework. If you use WSGI, you should use > something like: > > host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] > > -- Gerhard Yeah i already tried environ("SERVER_NAME") but get a key error when i do. From code at pizzashack.org Tue Sep 2 11:39:09 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 11:39:09 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i4v26Fol29aU4@mid.uni-berlin.de> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> Message-ID: <20080902153909.GQ29228@dragontoe.org> On Tue, Sep 02, 2008 at 01:57:26PM +0000, Marc 'BlackJack' Rintsch wrote: > > I would argue that they don't represent processes at all; the object is > > a set of files which connect the standard I/O streams of a subprocess to > > its parent, and methods to operate on those files. > > And the process' ID, an attribute with the process' return code, a method > to wait until the process is finished and file objects to communicate > with the process. The name popen is an abbreviation of "pipe open" -- the function, and the class, open pipes to communicate with another process. What you said is correct; however there are numerous other ways to open subprocesses. The focus of popen is the communication aspect -- the opening and control of the pipes -- not the subprocess. That's the key difference between popen() and all the other methods of starting a subprocess. > > The C library's popen() function, on which this class is based, > > provides a means to open a file and connect it to the standard steams > > of a subprocess, making it more closely analogous to what the Popen > > class does/provides. As such, "Popen" is a better name to describe > > this object than "subprocess" would be. > > Is strongly disagree. The class provides an interface to start and > communicate with a `Subprocess`. Instances stand for processes. There's more than one way to look at it. You can disagree all you like, but your interpretation disagrees with the historical intent of popen. > With your reasoning the `file` type should be called `open`. In this case, the file is a pipe, and the 'p' in popen represents the pipe. Unix, by and large, doesn't care that it's a pipe -- file I/O is intended to work the same way regardless of whether it's a pipe, a socket, a file on disk, a special device file, or any other file-like object you can imagine. That's why I said "file" instead of "pipe" in my explanation. Note that in all of these links that talk about popen, the focus is on opening pipes or file objects, not on subprocesses: http://www.opengroup.org/onlinepubs/009695399/functions/popen.html http://docs.python.org/lib/os-newstreams.html http://us3.php.net/popen http://docs.hp.com/en/B9106-90010/popen.3S.html http://www.faqs.org/docs/artu/ch07s02.html The Linux man page unfortunately copies (verbatim) the FreeBSD man page, which gets it wrong. You can not open a process, but you can definitely open a pipe. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080902/8221f22e/attachment-0001.sig> From mike at myqs.net Fri Sep 5 07:39:39 2008 From: mike at myqs.net (Michael Wronna) Date: Fri, 05 Sep 2008 13:39:39 +0200 Subject: path slashes cleaning References: <mailman.484.1220534735.3487.python-list@python.org> <e815a0ed-f42e-4c60-8911-46de4f1169f0@t1g2000pra.googlegroups.com> Message-ID: <op.ug0aodfijqj4d0@mill.zuhause.kn> Am 04.09.2008, 15:27 Uhr, schrieb Mike Driscoll <kyosohma at gmail.com>: > On Sep 4, 8:25?am, "Mathieu Prevot" <mathieu.pre... at gmail.com> wrote: >> Hi, >> >> for scripts that take arguments, I would like to remove the trailing >> slash if it's present. >> >> Is there something else than: >> >> a='/usr/local/lib/' >> if a[-1] == '/': >> ? a = list(a) >> ? a.pop() >> ? ''.join(a) >> >> Thanks, >> Mathieu > > How about this: > > if a[-1] == '/': > a = a[:-1] > > Mike Hi, how about a.rstrip('/') ? Michael From python-url at phaseit.net Tue Sep 9 16:24:32 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 9 Sep 2008 20:24:32 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 9) Message-ID: <ga6m20$f60$1@lairds.us> QOTW: "So why am I supposed to care about SOAP again? Oh yes, the wizards I can use to generate 'web service end-points' from programming language code. My years in the SOAP trenches just makes me laugh myself half to death at that notion: I would probably have been twice as productive if every time I reached for a SOAP toolkit I instead just coded straight XML in HTTP. And this represents experience with Python, Java and C WS tools." - Uche Ogbuji How to cancel instance creation given certain conditions: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7083ed99c5237485 Implement a dictionary with case-insensitive keys: http://groups.google.com/group/comp.lang.python/browse_thread/thread/90a7e967d0bd1e0f/ The behavior of hash(): http://groups.google.com/group/comp.lang.python/browse_thread/thread/6c2d5030a833858f/ A generic attempt to add "verbosity" to scripts: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c2fa072005c9aaba/ max() and sum() applied to empty sequences, or those containing None, and how these differ from their SQL counterparts: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f4b98d6fa5d6b514/ Distributed processes, multiple threads, multicore CPUs: what are Python's options? http://groups.google.com/group/comp.lang.python/browse_thread/thread/fe55f38c64f58a9d/ Allowing underscores or other punctuation inside numeric literals: http://groups.google.com/group/comp.lang.python/browse_thread/thread/93dc57f9190b93bc/85dfbb163ba7f15b#85dfbb163ba7f15b How to manage two interdependent properties: http://groups.google.com/group/comp.lang.python/browse_thread/thread/66846422b6c2848f/ A generic GUI library, and the future of GUI development: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8904fbc731586533/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From almar.klein at gmail.com Thu Sep 25 08:49:31 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 25 Sep 2008 14:49:31 +0200 Subject: what does "python -i" use as input stream (stdin)? Message-ID: <cc38d75f0809250549u2acff662n765bc1c2990d0e78@mail.gmail.com> Hi, I want to start "python -i" from a subprocess and change its stdin stream, so I get control over the commands I feed the interpreter. I thought just changing sys.stdin to my custom file-like object would suffice, but this does not work. Neither does changing sys.__stdin__. I guess the interpreter got a reference to the original stdin (the Pipe) before I could change it, and is using that instead of sys.stdin. Any thoughts how I can get the interpreter to use MY custom stream? thanks, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080925/9371b9e3/attachment-0001.html> From rcdailey at gmail.com Fri Sep 5 15:24:16 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 14:24:16 -0500 Subject: Need formatting suggestion for long strings Message-ID: <496954360809051224i66123029s23a5ab2f02d8be2b@mail.gmail.com> Hi, I find quite often that I'm writing things like this: raise FatalExcept( "Insufficient number of arguments specified. Exactly {0} arguments are required. See stage.bat for documentation on accepted parameters.".format( num_arguments ) ) On my display (Vertical monitor), this exceeds the width of my display, and to view the entire length of the string I am forced to pan my view left and right. Is there a special way I can format this string so that it fits nicely on the screen? Keep in mind that one important factor is that whitespace is very sensitive, and I do not want line breaks in my script file to become part of the string itself. I like how C++ handles strings, like this: char const* mystring = "This is a very long string that " "spans multiple lines and does " "not include line breaks or tabs " "from the source file between " "the strings partitions." What do you guys prefer? Thanks for reading. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080905/a436a1d7/attachment-0001.html> From mail at timgolden.me.uk Thu Sep 18 12:01:13 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 18 Sep 2008 17:01:13 +0100 Subject: Installing pySerial In-Reply-To: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: <48D27B49.6080209@timgolden.me.uk> Joe G (Home) wrote: > Hi All, > > Background > =================== > I have installed Python for windows today from the python web site .I also > installed pySerial using the Windows installer from the sourceforge web > site..... Both installs use the default directories. > > Phyton version : Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > v.1310 32 bit (Intel)] on win32 > > pySerial 2.4 July 6th > > > Problem : Errors Screen output > ============================ >>>> import serial > > Traceback (most recent call last): > File "<pyshell#0>", line 1, in <module> > import serial > File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in > <module> > from serialwin32 import * > File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in > <module> > import win32file # The base COM port and file IO functions. > ImportError: No module named win32file You need to install the pywin32 extensions from: http://pywin32.sf.net They're so commonly used (and, if you install the ActiveState distro of Python, even bundled) that I imagine many Windows Pythoneers like myself simply install them automatically as soon as we've installed the main python.org Python. Once you've done that, the rest should just work: it's clear from the traceback that the serial module is getting imported; it's just trying to find the win32file module. TJG From fetchinson at googlemail.com Wed Sep 10 13:40:17 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Sep 2008 10:40:17 -0700 Subject: Alternatives to traditional RDBMS In-Reply-To: <6iq90jFdeiU1@mid.uni-berlin.de> References: <mailman.791.1221056566.3487.python-list@python.org> <6iq90jFdeiU1@mid.uni-berlin.de> Message-ID: <fbe2e2100809101040j79d24a62hc2e4c08ab346b3e2@mail.gmail.com> >> Are there any known alternatives >> to the traditional RDBMS (MySQL, >> PostgreSQL, SQLite, Oracle, etc0 / >> >> I know of 3 written in Python: >> * buzhug >> * kirbybase >> * PyDbLite > > ZODB. Without any problems usable without ZOPE, clusterable, ACID-conform > and so forth. There is also dejavu: http://www.aminus.net/dejavu -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From mike at ipglobal.net Tue Sep 16 15:40:47 2008 From: mike at ipglobal.net (Support Desk) Date: Tue, 16 Sep 2008 14:40:47 -0500 Subject: How do I add permanently to Pythons sys.path? In-Reply-To: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> Message-ID: <031601c91834$1dbafed0$a601a8c0@office.ipglobal.net> What about on a unix box? Sincerely, Michael H. -----Original Message----- From: Aaron "Castironpi" Brady [mailto:castironpi at gmail.com] Sent: Tuesday, September 16, 2008 12:49 PM To: python-list at python.org Subject: Re: How do I add permanently to Pythons sys.path? On Sep 16, 10:13?am, cnb <circularf... at yahoo.se> wrote: > >>> sys.path > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > \lib\\site-packages\\PIL'] > > > > Now I have my personal programs in C:/Python25/Progs/ > > How do I add so that I can just do "import somefile" from anywhere in > that directory in the interpreter and it can load files from other > folders in that directory. Add a file: \Lib\site-packages\locals.pth with contents, path to the directory you want to add (/python25/progs/) From tjreedy at udel.edu Sat Sep 20 20:35:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Sep 2008 20:35:59 -0400 Subject: explain slice assignment to newb In-Reply-To: <ceceec82-cc0c-4daf-8f8a-1392f4872f71@k30g2000hse.googlegroups.com> References: <ceceec82-cc0c-4daf-8f8a-1392f4872f71@k30g2000hse.googlegroups.com> Message-ID: <gb44t4$5m5$1@ger.gmane.org> Andrew wrote: > please explain this behavior to a newb: Read the section on sequence slicing in the Library Reference. Use the interactive interpreter or IDLE to perform experiments, like you did, until you understand to your satisfaction. From mail at timgolden.me.uk Fri Sep 19 06:05:43 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 19 Sep 2008 11:05:43 +0100 Subject: webbrowser fragment identifier In-Reply-To: <0b00afc4-018f-4b80-9fba-93c253a86c7a@q5g2000prf.googlegroups.com> References: <0b00afc4-018f-4b80-9fba-93c253a86c7a@q5g2000prf.googlegroups.com> Message-ID: <48D37977.3050100@timgolden.me.uk> scottbvfx wrote: > Hi, > > I'm trying to launch a web browser along with an html file with a > fragment identifier in its path. I'm using the webbrowser module for > this. > ie. webbrowser.open('file:///C:/myfile.html#SomeEntryInTheHTML') > > for some reason it is truncating the path to 'file:///C:/myfile.html'. > > Does anyone know a way of getting the fragment identifier in there > (with webbrowser module or any other)? No expertise here: just poking around. This seems to be a slight peculiarity of browser and os cooperation. As a comparison, try running os.startfile ("file://....#..") or just pasting it into the command line. I don't understand why this should be but it seems to lose it there as well. Randomly tested on my XP box with Firefox 3 & IE 7: Input: Start > Run > firefox c:\temp\t.html#chapter-i Result: URL is escaped so ff3 starts with non-existent file:///c:/temp/t.html%23chapter-i Input: Start > Run > file:///c:\temp\t.html#chapter-i (with ff3 as default) Result: URL fragment is stripped so ff3 starts with file:///C:/temp/t.html Input: Start > Run iexplore c:\temp\t.html#chapter-i Result: Gets it right: ie7 starts with file:///C:/temp/t.html#chapter-i Input: Start > Run > file:///c:\temp\t.html#chapter-i (with ie7 as default) Result: URL fragment is stripped so IE7 starts with file:///C:/temp/t.html A very quick perusal of the webbrowser source suggests it does nothing more sophisticated than finding possible browsers, starting with firefox, and stopping when it finds it. It then uses that as the command-line prefix to whatever url is passed. So no stripping of url fragments happening there. TJG From pavlovevidence at gmail.com Sat Sep 13 04:25:55 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 13 Sep 2008 01:25:55 -0700 (PDT) Subject: question about python References: <a88e3cae-b47c-4b43-bc6d-63739817ef8c@o40g2000prn.googlegroups.com> <c66a320b-348a-45f4-979c-0029c40472a0@a18g2000pra.googlegroups.com> <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> Message-ID: <91f40dcc-d76d-437a-a7e2-ea26b9e333ed@b38g2000prf.googlegroups.com> On Sep 13, 1:00 am, fishfin <calebjhan... at gmail.com> wrote: > @ Carl: Yes, I think your right now that I look at it (or at least all > except for the last two lines need to be indented). I'm still not sure > how to send the stuff to the web browser though. Thanks for pointing > it out! Try reading in the whole HTTP request instead of just the first line. Change line = cfile.readline().strip() to line = cfile.read() And see if that helps. (Outputting the document so that it formats the request well is left as an exercise. Also, as a heads up: in real programs you should never output anything you receive through the network without checking it or escaping it to prevent malicious uses.) Carl Banks From paul at boddie.org.uk Wed Sep 10 19:30:11 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 10 Sep 2008 16:30:11 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <3d6488c1-d57c-46be-b404-9c79bd49dbdf@y21g2000hsf.googlegroups.com> Message-ID: <8b21dee5-2c04-4132-9de6-f8c8843a70e8@d1g2000hsg.googlegroups.com> On Sep 10, 5:03 am, George Sakkis <george.sak... at gmail.com> wrote: > > So at best (i.e. if it actually makes any sense; I didn't read it), > this is an ANNouncement of a pre-alpha piece of code. ANN posts rarely > attract replies, even when they are about production/stable software. To be fair, at least some code has been provided here, unlike another recently announced piece of software whose author left a trail of promotion, referencing a Web site which doesn't even run the advertised software but promises to do so after the "first release": in other words, vapourware, as far as anyone following up on such promotion would be concerned. We aren't seeing anything like that here. > Thankfully, most people don't expect (let alone "require") readers to > share their interest or enthusiasm by replying to the ANN. Given your > past semi-coherent and incoherent posts, expecting people to jump on > such a thread is a rather tall order. I think you should give the benefit of the doubt here, particularly since we've been given a short review of related technologies (so it isn't as if the ideas are being picked out of thin air), and I think that such discussion isn't completely unproductive. Things like shared memory and memory-mapped files are often proposed as optimisations when building multiprocessing solutions, with solutions like POSH previously suggested on a frequent basis despite the lack of their further development, so maybe there is a need for something like this. Although systems like those developed for Tim Bray's "Wide Finder 2" exercise [1] probably work best by dumping raw data to disk - in other words, not channelling data between processes at all - there may well be a need for better data sharing between processes for some kinds of concurrent systems. Whether the ideas described here could help, or whether things like distributed filesystems already cover the same ground, I think it's still worth having the conversation. Of course, people shouldn't have to feel obliged to respond with encouragement to every announcement - there are plenty of projects I have no direct interest in - but I don't think people should respond with discouragement if the only basis for it is how they may have perceived the author's previous contributions to the mailing list or newsgroup. Paul P.S. Maybe those of a more judgemental disposition should peruse the activities in comp.lang.lisp to preserve a sense of perspective. Upon my last chance perusal of that newsgroup, I saw frequent mentions of at least one name familiar to comp.lang.python readers. [1] http://www.tbray.org/ongoing/When/200x/2008/05/01/Wide-Finder-2 From ldo at geek-central.gen.new_zealand Tue Sep 30 04:38:09 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 30 Sep 2008 21:38:09 +1300 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <gbsn6i$ut0$1@aioe.org> Message-ID: <gbsohh$3cg$5@lust.ihug.co.nz> In message <gbsn6i$ut0$1 at aioe.org>, r0g wrote: > Lawrence D'Oliveiro wrote: > >> In message <gbr4ks$1vv$1 at aioe.org>, r0g wrote: >> >>> You can only distribute modifications to gnuplot itself as >>> patches, but you can distribute it freely ... >> >> This must be some new definition of "freely" of which I'm unaware. > > As in beer. You get free beer? From lists at cheimes.de Wed Sep 10 11:32:18 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 17:32:18 +0200 Subject: Refcount problem in ceval.c In-Reply-To: <sesks89gt1.fsf@pc047299.dhcp.germanlloyd.org> References: <sesks89gt1.fsf@pc047299.dhcp.germanlloyd.org> Message-ID: <ga8pa1$6g7$1@ger.gmane.org> Berthold H?llmann wrote: > Is there any "common" reason to for such a strange object on the command > stack, or is it more likely that any of my extension modules is causing > havoc? It's very likely that your extension has a reference counting bug. It looks like you are either missing a Py_INCREF or you have a Py_DECREF too much. Newly freed memory is filled with 0xDB (see Objects/obmalloc.c DEADBYTE). Wild guess: Are you using PyModule_AddObject with a PyTypeObject w/o Py_INCREF()ing the type object first? Christian From jitenshah78 at gmail.com Thu Sep 25 10:51:28 2008 From: jitenshah78 at gmail.com (jitenshah78 at gmail.com) Date: Thu, 25 Sep 2008 15:51:28 +0100 Subject: text processing Message-ID: <48DBA570.9070107@gmail.com> I have string like follow 12560/ABC,12567/BC,123,567,890/JK I want above string to group like as follow (12560,ABC) (12567,BC) (123,567,890,JK) i try regular expression i am able to get first two not the third one. can regular expression given data in different groups From lepto.python at gmail.com Mon Sep 22 02:53:29 2008 From: lepto.python at gmail.com (oyster) Date: Mon, 22 Sep 2008 14:53:29 +0800 Subject: any tool can shrink DLL? Message-ID: <6a4f17690809212353w5e4d39b5odacaa2156bdf8f19@mail.gmail.com> For many external lib, python( and www.freebasic.net) use only the DLL version, whcih is very big often if we want to release our program. So, is there such a tool that can scan a DLL then strip the unused function's code out, so yields a small working DLL? for example, in my program I use only 'compress' function in zlib.dll, then 1. I write a list file in which I emurate the function that I used [code func.lst] compress [/code] 2. run the application [code] shrink zlib.dll func.lst [code] the shrink scans zlib.dll, dumps function 'compress' and all function code on which 'compress' rely, and at last writes tiny-zlib.dll BTW, I know why there is DLL. BTW2, forget upx and so on, they lead to obvious speed down in my experiment From straton at lampsacos.demon.co.uk Sat Sep 6 08:42:29 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sat, 06 Sep 2008 13:42:29 +0100 Subject: max(), sum(), next() In-Reply-To: <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> Message-ID: <g9ttrp$nlp$1$830fa17d@news.demon.co.uk> castironpi wrote: > On Sep 5, 9:20 pm, "Manu Hack" <manuh... at gmail.com> wrote: >> On Fri, Sep 5, 2008 at 1:04 PM, castironpi <castiro... at gmail.com> wrote: >>> On Sep 5, 3:28 am, "Manu Hack" <manuh... at gmail.com> wrote: >>>> On Thu, Sep 4, 2008 at 4:25 PM, castironpi <castiro... at gmail.com> wrote: >>>>> On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >>>>>> David C. Ullrich: >>>>>>> At least in mathematics, the sum of the elements of >>>>>>> the empty set _is_ 0, while the maximum element of the >>>>>>> empty set is undefined. >>>>>> What do you think about my idea of adding that 'default' argument to >>>>>> the max()/min() functions? >>>>>> Bye, >>>>>> bearophile >>>>> For max and min, why can't you just add your argument to the set >>>>> itself? >>>>> The reason max([]) is undefined is that max( S ) is in S. >>>> It makes sense. >>>>> The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >>>> It doesn't make sense to me. What do you set x to? >>> For all x. >> But then how can you conclude sum([]) = 0 from there? It's way far >> from obvious. > > You can define sum([a1,a2,...,aN]) recursively as > sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) "X", then > subtract aN. > > sum([a1,a2,...a(N-1)])+aN=X > sum([a1,a2,...a(N-1)])+aN-aN=X-aN > > For N=2, we have: > > sum([a1,a2])=X > sum([a1,a2])-a2=X-a2 > sum([a1,a2])-a2-a1=X-a2-a1 > > Since X= a1+ a2, replace X. > > sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 > > Or, > > sum([a1,a2])-a2-a1=0 > > Apply the recursive definition: > > sum([a1])+a2-a2-a1=0 > > And again: > > sum([])+a1+a2-a2-a1=0 > > And we have: > > sum([])=0. > This is not necessarily so. The flaw is that you provide a recursive definition with no start value, which is to say it is not a recursive definition at all. A recursive definition should be (for lists where elements can be added, and ignoring pythonic negative indexing): Define 'sum(L)' by a. sum(L[0:1]) = L[0] b. sum(L[0:i]) = sum(L[0:i-1]) + L[i] ... if i > 1 From this you can prove the reverse recursion sum{L[0:k]) = sum(L[0:k+1]) - L[k+1] __only__ if k >= 0 It says nothing about the empty list. You could add, as part of the definition, that sum{[]) = 0, or any other value. A rather different approach, not quite simple recursion, would be to start with A. a slicing axiom, something like: for all non-negative integers, a,b,c with a <=b <= c: sum(L[a:c]) = sum(L[a:b]) + sum(L[b:c]) B. a singleton axiom: for all integers a where L[a] exists: sum(L[a:a]) = L[a] 2a. sum{ From gminick at bzt.bzt Wed Sep 10 13:51:58 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 17:51:58 +0000 (UTC) Subject: Reading binary data References: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> <b99f407e-1c43-4f46-a9c8-7592f09170ac@m73g2000hsh.googlegroups.com> <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> Message-ID: <ga91ft$12t$1@inews.gazeta.pl> On Wed, 10 Sep 2008 10:43:31 -0700 (PDT), Aaron Scott wrote: >> signature, version, attr_count = struct.unpack('3cII', >> yourfile.read(11)) >> > > This line is giving me an error: > > Traceback (most recent call last): > File "test.py", line 19, in <module> > signature, version, attr_count = struct.unpack('3cII', > file.read(12)) > ValueError: too many values to unpack Do: print struct.unpack('3cII', yourfile.read(11)) instead of: signature, version, attr_count = struct.unpack('3cII', yourfile.read(11)) to check what does struct.unpack return. I guess it returns more than three elements. Just like below: >>> a,b,c=(1,2,3,4) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: too many values to unpack As you can see the fourth element from the tuple has no place to go. Same thing happens in your code. HTH. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From webilix950 at googlemail.com Sun Sep 28 18:39:48 2008 From: webilix950 at googlemail.com (webilix950 at googlemail.com) Date: Sun, 28 Sep 2008 15:39:48 -0700 (PDT) Subject: privatdetektei detektei central privat detektei frankfurt private detective privatdetektiv in berlin Message-ID: <3758dc05-0935-4c21-ba7e-22ed52190712@x41g2000hsb.googlegroups.com> privatdetektei detektei central privat detektei frankfurt private detective privatdetektiv in berlin + + + + +++ DETEKTEIEN DETEKTIVE ONLINE +++ DETEKTEI HAMBURG +++ PRIVATDETEKTIVE +++ + + http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET http://WWW.DETEKTEI-DETEKTIV.NET + + + + ################################################################################## detektei hannover dedektive in Steinburg detektive frankfurt ein privatdetektiv in Rhoen ausbildung privatdedektiv detektei erding in Torgau detektiv buero detektei frankfurt in Viersen detektei duisburg detektei pegasus in Sangerhausen detektei detektive detektei blunt in L?chow detektivbueros frankfurt privat detektiv frankfurt in Mayen www detektei werde ich privatdetektiv in Heidenheim - privatdetektiv augsburg detektei erfurt in L?denscheid - detektive berlin privatdetektiv hamburg in Gummersbach - detektei braunschweig schulung frankfurt in Husum - Lentz-Detektei.de www.MeineDetektei.de in Sonneberg - detektei detektive detektei detektiv in Wei?enfels - detektive.com MeineDetektei.de in Neu-Ulm - www.Lentz-Detektei.de werkschutz frankfurt in Heppenheim - detektei muelheim zad detektiv in Burg - ausbildung privatdetektiv privat detektiv in frankfurt in Kirchheimbolanden - privatdetektiv augsburg ein privatdedektiv in Zell - ausbildung privatdedektiv Detektei de in Wolfratshausen - sicherheit frankfurt detekteien in Miesbach - privat detektiv frankfurt detektei gewerbe in Doebeln - detektei duisburg privatdetektive frankfurt in Neuss From m_palmer45 at yahoo.ca Tue Sep 16 14:49:06 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 16 Sep 2008 11:49:06 -0700 (PDT) Subject: Porting a pygtk app to Windows References: <7ce94e05-d704-4118-9496-26f9d7aa6853@k36g2000pri.googlegroups.com> Message-ID: <24287108-1a70-4eca-af87-a188ec09f800@m45g2000hsb.googlegroups.com> On Sep 16, 12:30 pm, binaryjesus <coolman.gu... at gmail.com> wrote: > hi everyone, > first of all > I had written an app using pygtk module and created the GUI with > glade.All the development was done on a linux machine and the app was > working fine all this tme in linux. > > now, the thing is i have to change the development environment to > windows. So this means that i have to port the application to work in > windows. > > Initially i thought that porting an application written using a > platform independent language and cross-platform window frame work > would be a piece of cake. Well i guess all the assumptions end there. > unlike linux, in windows pygtk and the GTK frame work are not > installed by default. > > So, long story short. i installed GTK devel, pygtk, pygobject, pycaro, > glade ui. Also made a lot of path adjustments (os.path.absolutepath() > is not portable i guess) and finally got the app to at least start > without showing an error. > > The problem that i am now facing is that nothing shows up in the app. > No menu, buttons, frames or anything else is visible. When i move the > cursor over the window it changes into an hour-glass type icon. hoe > ever all c++ GTK programs seem to render well. > > here is a screen shot:http://i36.tinypic.com/x52uk9.jpg > > i have written below the startup code of the app: > > import pygtk > pygtk.require('2.0') > import gtk > import gtk.glade > from ConfigParser import ConfigParser > > class jDesk(object): > def __init__(self): > #self.seclstore.append(["0","Section1"]) > #self.catlstore.append(["cat 1"]) > self.synclstore = gtk.ListStore(str,str,str,str,str,int) > self.seclstore = gtk.ListStore(str,str) > self.catlstore = gtk.ListStore(str,str) > self.process_glade() > > def process_glade(self): > self.gladefile = "gui.glade" > self.glade = gtk.glade.XML(self.gladefile) > #windows > self.main_window = self.glade.get_widget('MainWindow') > #main window > self.templatefile = self.glade.get_widget('templatefile') > self.imageurl = self.glade.get_widget('imageurl') > self.posttitle = self.glade.get_widget('posttitle') > self.sectionbox = self.glade.get_widget('sectionbox') > self.categorybox = self.glade.get_widget('categorybox') > self.demolink = self.glade.get_widget('demolink') > self.posttext = self.glade.get_widget('posttext') > self.statusbar = self.glade.get_widget('statusbar') > > self.signal_autoconnect() > self.main_window.show() > print '===================main wind created=================' > def run(self): > try: > print "Entering GTK main now" > gtk.main() > print "Leaving GTK main" > except: > print "Exception in main" > > if __name__ == "__main__": > conf = ConfigParser() > conf.read('settings.cfg') > gtk.gdk.threads_init() > app = jDesk() > app.run() > > i have tried a lot of things, checked up paths, checked libcairo but > nothing seems to help.problem seems to be with pygtk since other c++ > GTK programs like pedgin and GTK demo rn fine. > So maybe is there any pygtk windows bugs that i coming from linux > background might not be knowing about or perhaps u have encountered > such a problem in the past before ? > Much thanks in advance > BinaryJ I haven't tried it myself, but I came across a blog post the other day that describes a way of building windows installers for pyGTK applications at http://unpythonic.blogspot.com/2007/07/pygtk-py2exe-and-inno-setup-for-single.html From coolkid246 at googlemail.com Thu Sep 4 05:47:28 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 02:47:28 -0700 (PDT) Subject: sofortkredit online in Karlsruhe kredite zinsen kredit ohne schufa banken ohne schufa kleinkredit online online sofort kredit ohne schufa onlinekredit ohne schufa kredit schufa frei online kredite von privat kredite beantragen kredit online beantragen kredit fuer arbeitslose kfz kredit guenstiger kredit online handyvertrag schufa kredite ohne schufa mit guenstige kredite online kredit sofortzusage kredit ohne schufa in + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA Message-ID: <21bfd6f0-b44f-4cf9-9ba9-5a675c943948@x16g2000prn.googlegroups.com> sofortkredit online in Karlsruhe kredite zinsen kredit ohne schufa banken ohne schufa kleinkredit online online sofort kredit ohne schufa onlinekredit ohne schufa kredit schufa frei online kredite von privat kredite beantragen kredit online beantragen kredit fuer arbeitslose kfz kredit guenstiger kredit online handyvertrag schufa kredite ohne schufa mit guenstige kredite online kredit sofortzusage kredit ohne schufa in + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + credite ohne schufa kredite fuer selbstaendige in Westerstede postbank kredit barkredite in Garmisch-Partenkirchen kredite schufa online kredit ohne schufa auskunft in Oldenburg private kredite ohne schufa bargeld online in Schoenebeck kredit euro sofortdarlehen in Konstanz kredit vergleich online-kredite in Herzogtum ratenkredit online kredite mit online in Ludwigslust euro kredit ohne schufa mit krediten ohne schufa in Osterholz- Scharmbeck guenstiger kredit online online kredite oesterreich in Burg kredite ohne kredit ohne bonitaet in Pirna privatkredite ohne schufa kredit ohne schufa in Cloppenburg serioeser kredit ohne schufa online krediten in Landsberg kredit mit schufa schufafrei in Biedenkopf online sofort kredite sofort kredite in Pr?m kredit schufafrei kredite selbstaendige in Wolfratshausen kredit schufa frei guenstige kredite ohne schufa in Emmendingen kredite online ohne schufa online kredit schufafrei in Lindau sofort kredit ohne schufa fuer schweizer kredite in Bogen sofortkredite kredit trotz schufa und ohne in Bernburg schnellkredit online darlehen ohne schufa in Stade kredit ohne schufa auskunft vergleich kredit in Warendorf kleinkredit privatkredit in Querfurt - guenstige kredite kredit selbststaendige in Pirmasens - kredit karte ohne schufa bank kredit online in Ulm - postbank kredit online online krediten in Delitzsch - schweizer kredite kredite volksbank in Heinsberg - online sofort kredit ohne schufa kleinkredit online in Hannover - baufinanzierung online kredit ohne ksv in Eckernfoerde - kredit ohne schufa selbststaendige sofortkredit ohne schufa in Schweinfurt - onlinekredite privatkredit ohne schufa in Harburg - online kredit schufafrei kredit ohne auskunft in Bad Ems - konto kredit bargeld kredit in Aschaffenburg - kredit ohne schufa arbeitslos express kredit in Freudenstadt - online-kredite schnelle kredite in Dillingen - kredite finanzierung handyvertrag schufa in Sulzbach - kfw kredit postbank kredit in Goslar From bedouglas at earthlink.net Thu Sep 4 09:26:08 2008 From: bedouglas at earthlink.net (bruce) Date: Thu, 4 Sep 2008 06:26:08 -0700 Subject: Xpath for HTML processing In-Reply-To: <e837f5f4-aed1-4c65-81b6-445a9aee8e41@k36g2000pri.googlegroups.com> Message-ID: <19a601c90e91$cae74250$0301a8c0@tmesa.com> Hi Astley I can probably help here. Can you tell me exactly what you're trying to accomplish. the xpath query that you listed can be processed using libxml2dom (and a fewo other libs) are you looking to parse a web page, an xml doc, etc... let me know, and we'll see if we can help -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Astley Le Jasper Sent: Thursday, September 04, 2008 6:17 AM To: python-list at python.org Subject: Xpath for HTML processing Can anyone suggest something inthat can process an XPath like the following: "/html/body/table[2]/tbody/tr/td[5]/table/tbody/tr[3]/td/table[3]/ tbody/tr[5]/td" Cheers -- http://mail.python.org/mailman/listinfo/python-list From bearophileHUGS at lycos.com Tue Sep 2 11:22:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 2 Sep 2008 08:22:44 -0700 (PDT) Subject: Using NLTK in Java References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> <6i1hu9FnvcngU1@mid.uni-berlin.de> <d6558bd3-c077-4f09-b7cc-652ac3f17c7d@k13g2000hse.googlegroups.com> Message-ID: <6c921c74-d25b-440c-ae81-a412a9fc21ac@r66g2000hsg.googlegroups.com> On Sep 1, 12:30 pm, hussainsai... at gmail.com: >in Jython (which is assumed to replace Python), I don't think so. Bye, bearophile From tdelaney at avaya.com Wed Sep 3 22:43:36 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 4 Sep 2008 10:43:36 +0800 Subject: Numeric literal syntax In-Reply-To: <00cf34ad$0$20302$c3e8da3@news.astraweb.com> Message-ID: <E4C7BCAB1872014F81CEAACD25699B8CCBD265@301081ANEX2.global.avaya.com> Steven D'Aprano wrote: > On Thu, 04 Sep 2008 01:22:22 +0100, Alexander Schmolck wrote: > >> It seems to me that the right choice for thousands seperator is the >> apostrophe. > > You mean the character already used as a string delimiter? Hey - I just found a new use for the backtick! 123`456`7890 0b`1001`0110 Note: Guido has stated that the backtick will *not* be given a new meaning in any future version of Python ... Tim Delaney From paul at boddie.org.uk Fri Sep 26 15:04:27 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 26 Sep 2008 12:04:27 -0700 (PDT) Subject: how to replace and string in a "SELECT ... IN ()" References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <gbico4$fo3$1@inews.gazeta.pl> Message-ID: <295a7522-9594-4cad-889b-dab8c1ba251b@f36g2000hsa.googlegroups.com> On 26 Sep, 12:15, Wojtek Walczak <gmin... at bzt.bzt> wrote: > On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote: > > I have a BIIIIIG problem with the next query: > > > cursor.execute(""" > > SELECT titem.object_id, titem.tag_id > > FROM tagging_taggeditem titem > > WHERE titem.object_id IN (%s) > > """,( eid_list)) > > ^ > It should rather be '%'. You're telling the inquirer to do string substitution which can be dangerous if eid_list is built, say, from a collection of strings taken from an untrusted source. Sadly, SQL parameter substitution, which is done using the syntax employed by the inquirer above (along with the unfortunate "%s" placeholder syntax), does not really deal with sequences of values very well. What needs to be done here, if everything should happen relatively safely, is that the query string should be made to contain the appropriate number of placeholders between the brackets, with commas separating them as demanded by the syntax of SQL. Then, the values should be correctly taken from eid_list by the execute method, although for portability between different database modules, whose authors seem to have differing views on what kind of object can be given containing the parameters, I'd recommend converting eid_list to a tuple. Bruno and Tino thrash out some kind of working solution, I think. Paul From fredrik at pythonware.com Mon Sep 15 17:03:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 23:03:50 +0200 Subject: ka-ping yee tokenizer.py In-Reply-To: <6u80qt$7o5lj6@rrcs-agw-02.hrndva.rr.com> References: <6u80qt$7o5lj6@rrcs-agw-02.hrndva.rr.com> Message-ID: <gamijq$95a$1@ger.gmane.org> Karl Kobata wrote: > I have enjoyed using ka-ping yee?s tokenizer.py. I would like to > replace the readline parameter input with my own and pass a list of > strings to the tokenizer. I understand it must be a callable object and > iteratable but it is obvious with errors I am getting, that this is not > the only functions required. not sure I can decipher your detailed requirements, but to use Python's standard "tokenize" module (written by ping) on a list, you can simple do as follows: import tokenize program = [ ... program given as list ... ] for token in tokenize.generate_tokens(iter(program).next): print token another approach is to turn the list back into a string, and wrap that in a StringIO object: import tokenize import StringIO program = [ ... program given as list ... ] program_buffer = StringIO.StringIO("".join(program)) for token in tokenize.generate_tokens(program_buffer.readline): print token </F> From sdsdvfsdf at gmail.com Sun Sep 28 18:46:57 2008 From: sdsdvfsdf at gmail.com (sdsdvfsdf at gmail.com) Date: Sun, 28 Sep 2008 15:46:57 -0700 (PDT) Subject: Milenko Kindl tterter Message-ID: <1a4b5bd1-709c-4fde-9aa5-31b795d71da5@k13g2000hse.googlegroups.com> WASHINGTON - Congressional leaders and the White House agreed Sunday to a $700 billion rescue of the ailing financial industry after lawmakers insisted on sharing spending controls with the Bush administration. The biggest U.S. bailout in history won the tentative support of both presidential candidates and goes to the House for a vote Monday. ADVERTISEMENT The plan, bollixed up for days by election-year politics, would give the administration broad power to use taxpayers' money to purchase billions upon billions of home mortgage-related assets held by cash- starved financial firms. Flexing its political muscle, Congress insisted on a stronger hand in controlling the money than the White House had wanted. Lawmakers had to navigate between angry voters with little regard for Wall Street and administration officials who warned that inaction would cause the economy to seize up and spiral into recession. A deal in hand, Capitol Hill leaders scrambled to sell it to colleagues in both parties and acknowledged they were not certain it would pass. "Now we have to get the votes," said Sen. Harry Reid, D- Nev., the majority leader. The final legislation was released Sunday evening. House Republicans and Democrats met privately to review it and decide how they would vote. "This isn't about a bailout of Wall Street, it's a buy-in, so that we can turn our economy around," said House Speaker Nancy Pelosi, D-Calif. The largest government intervention in financial markets since the Great Depression casts Washington's long shadow over Wall Street. The government would take over huge amounts of devalued assets from beleaguered financial companies in hopes of unlocking frozen credit. "I don't know of anyone here who wants the center of the economic universe to be Washington," said a top negotiator, Sen. Chris Dodd, chairman of the Senate Banking, Housing and Urban Affairs Committee. But, he added, "The center of gravity is here temporarily. ... God forbid it's here any longer than it takes to get credit moving again." The plan would let Congress block half the money and force the president to jump through some hoops before using it all. The government could get at $250 billion immediately, $100 billion more if the president certified it was necessary, and the last $350 billion with a separate certification ? and subject to a congressional resolution of disapproval. Still, the resolution could be vetoed by the president, meaning it would take extra-large congressional majorities to stop it. Lawmakers who struck a post-midnight deal on the plan with Treasury Secretary Henry Paulson predicted final congressional action might not come until Wednesday. The proposal is designed to end a vicious downward spiral that has battered all levels of the economy. Hundreds of billions of dollars in investments based on mortgages have soured and cramped banks' willingness to lend. "This is the bottom line: If we do not do this, the trauma, the chaos and the disruption to everyday Americans' lives will be overwhelming, and that's a price we can't afford to risk paying," Sen. Judd Gregg, the chief Senate Republican in the talks, told The Associated Press. "I do think we'll be able to pass it, and it will be a bipartisan vote." A breakthrough came when Democrats agreed to incorporate a GOP demand ? letting the government insure some bad home loans rather than buy them. That would limit the amount of federal money used in the rescue. Another important bargain, vital to attracting support from centrist Democrats, would require that the government, after five years, submit a plan to Congress on how to recoup any losses from the companies that got help. "This is something that all of us will swallow hard and go forward with," said Republican presidential nominee John McCain. "The option of doing nothing is simply not an acceptable option." His Democratic rival Barack Obama sought credit for taxpayer safeguards added to the initial proposal from the Bush administration. "I was pushing very hard and involved in shaping those provisions," he said. Later, at a rally in Detroit, Obama said, "it looks like we will pass that plan very soon." House Republicans said they were reviewing the plan. As late as Sunday afternoon, Republicans regarded the deal as "a proposal that is promising in principle, but that is still not final," said Antonia Ferrier, a spokeswoman for Missouri Rep. Roy Blunt, the top House GOP negotiator. Executives whose companies benefit from the rescue could not get "golden parachutes" and would see their pay packages limited. Firms that got the most help through the program ? $300 million or more ? would face steep taxes on any compensation for their top people over $500,000. The government would receive stock warrants in return for the bailout relief, giving taxpayers a chance to share in financial companies' future profits. To help struggling homeowners, the plan would require the government to try renegotiating the bad mortgages it acquires with the aim of lowering borrowers' monthly payments so they can keep their homes. But Democrats surrendered other cherished goals: letting judges rewrite bankrupt homeowners' mortgages and steering any profits gained toward an affordable housing fund. It was Obama who first signaled Democrats were willing to give up some of their favorite proposals. He told reporters Wednesday that the bankruptcy measure was a priority, but that it "probably something that we shouldn't try to do in this piece of legislation." "It's not a bill that any one of us would have written. It's a much better bill than we got. It's not as good as it should be," said Democratic Rep. Barney Frank of Massachusetts, the House Financial Services Committee chairman. He predicted it would pass, though not by a large majority. Frank negotiated much of the compromise in a marathon series of up-and- down meetings and phone calls with Paulson, Dodd, D-Conn., and key Republicans including Gregg and Blunt. Pelosi shepherded the discussions at key points, and cut a central deal Saturday night ? on companies paying back taxpayers for any losses ? that gave momentum to the final accord. An extraordinary week of talks unfolded after Paulson and Ben Bernanke, the Federal Reserve chairman, went to Congress 10 days ago with ominous warnings about a full-blown economic meltdown if lawmakers did not act quickly to infuse huge amounts of government money into a financial sector buckling under the weight of toxic debt. The negotiations were shaped by the political pressures of an intense campaign season in which voters' economic concerns figure prominently. They brought McCain and Obama to Washington for a White House meeting that yielded more discord and behind-the-scenes theatrics than progress, but increased the pressure on both sides to strike a bargain. Lawmakers in both parties who are facing re-election are loath to embrace a costly plan proposed by a deeply unpopular president that would benefit perhaps the most publicly detested of all: companies that got rich off bad bets that have caused economic pain for ordinary people. But many of them say the plan is vital to ensure their constituents don't pay for Wall Street's mistakes, in the form of unaffordable credit and major hits to investments they count on, like their pensions. Some proponents even said taxpayers could come out as financial winners. Gregg, R-N.H., said: "I don't think we're going to lose money, myself. We may ? it's possible ? but I doubt it in the long run." Milenko Kindl Banja Luka Banjaluka Bihac From fredrik at pythonware.com Thu Sep 4 04:05:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 10:05:20 +0200 Subject: use str as variable name In-Reply-To: <3e473cc60809040059o5ebb0bd2h54db1d38929a533b@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <3e473cc60809040059o5ebb0bd2h54db1d38929a533b@mail.gmail.com> Message-ID: <g9o4s0$fs6$1@ger.gmane.org> Mathieu Prevot wrote: > I'll use: > a.__setattr__(height, new_value) that's an implementation detail. please use setattr() instead, like everyone else. </F> From musiccomposition at gmail.com Sat Sep 27 22:53:53 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 27 Sep 2008 19:53:53 -0700 (PDT) Subject: Abstract Base Class register function References: <mailman.1602.1222552230.3487.python-list@python.org> Message-ID: <676263de-4ff3-4c5f-a01c-100bfd1b673d@d1g2000hsg.googlegroups.com> On Sep 27, 4:50?pm, "Mikolai Fajer" <mfa... at gmail.com> wrote: > I have been experimenting with the abc module in py3k and thought > about using the register method of an ABC as a class decorator: > > <code> > import abc > class MyABC(metaclass=abc.ABCMeta): > ? ? pass > > @MyABC.register > class MySub(): > ? ? pass > </code> > > This doesn't work because the register method returns None. ?It would > be a fairly simple modification to have this work: > > <code> > ? ? def register(cls, subclass): > ? ? ? ? """Register a virtual subclass of an ABC.""" > ? ? ? ? ... etc ... > ? ? ? ? return subclass > </code> > > What do people think of this behavior? It's probably better to just inherit from your metclass. register is really for use with extension types that implement an interface. > > -- > > ? ? ?-Mikolai Fajer- From jackie.python at gmail.com Fri Sep 5 10:29:59 2008 From: jackie.python at gmail.com (Jackie Wang) Date: Fri, 5 Sep 2008 10:29:59 -0400 Subject: Extract Information from Tables in html Message-ID: <37b964200809050729j6290af48u8efbbc1a5e0b6bd1@mail.gmail.com> Dear all, Here is a html code: <td valign="top" headers="col4"> Premier Community Bank of Southwest Florida <br /> Fort Myers, FL </td> My question is how I can extract the strings and get the results: Premier Community Bank of Southwest Florida; Fort Myers, FL Thanks a lot Jackie From castironpi at gmail.com Mon Sep 8 15:13:50 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 8 Sep 2008 12:13:50 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <mailman.666.1220826503.3487.python-list@python.org> <086a0906-c6f1-489c-91ab-f6a4f9e1ae3f@59g2000hsb.googlegroups.com> <99113520-2fa2-46ac-9894-ea78372ff610@c58g2000hsc.googlegroups.com> <mailman.691.1220890992.3487.python-list@python.org> Message-ID: <45f6d806-e31e-4d60-af60-b3a727b5fb79@t54g2000hsg.googlegroups.com> On Sep 8, 11:23?am, "Dan Upton" <up... at virginia.edu> wrote: > On Sun, Sep 7, 2008 at 10:59 PM, castironpi <castiro... at gmail.com> wrote: > > On Sep 7, 7:34 pm, MRAB <goo... at mrabarnett.plus.com> wrote: > >> On Sep 7, 11:28 pm, "Eric Wertman" <ewert... at gmail.com> wrote: > > >> > +1 Bot > > >> I think it's like duck typing: it doesn't matter whether he's actually > >> a bot, only whether he behaves like one. > > > Do you support the bot interface and methods? > > -- > > And this is an example of why you get +1 bot. I took Eric's comment to be a joke and mine was too. I don't get the feeling yours is, no offense. From steve at holdenweb.com Tue Sep 30 08:39:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Sep 2008 08:39:36 -0400 Subject: What is not objects in Python? In-Reply-To: <pan.2008.09.30.06.07.46@REMOVE.THIS.cybersource.com.au> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <f2d2bf0b-9362-47f5-84eb-411e09ab38e1@8g2000hse.googlegroups.com> <pan.2008.09.30.06.07.46@REMOVE.THIS.cybersource.com.au> Message-ID: <48E21E08.9020808@holdenweb.com> Steven D'Aprano wrote: > On Mon, 29 Sep 2008 21:03:07 -0700, namekuseijin wrote: > >>> Why isn't len implemented as a str.len and list.len method instead of a >>> len(list) function? >> Because postfix notation sucks. The natural way of spelling is >> adjective+noun and verb+predicate. > > "Natural"? > > You mean phrases like "heir apparent" and "worst choice imaginable" are > unnatural? They are certainly far from normal usage, as my dog yellow would be certain to agree. > To say nothing of languages like Spanish, Albanian, Italian, > Cornish, Vietnamese, Hebrew... It's long been a convention in the Western programming world to pretend no other language than English and no other codes than ASCII exist. The fact that Python is beginning to come to terms with Unicode is a tribute to certain developers' persistence. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Sep 13 12:52:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Sep 2008 16:52:31 GMT Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> Message-ID: <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> On Sat, 13 Sep 2008 01:06:22 -0700, cnb wrote: > This must be because of implementation right? Shouldn't reduce be faster > since it iterates once over the list? doesnt sum first construct the > list then sum it? What makes you think that? Given the speed of sum(), it sure doesn't look like it's generating a full list before summing. Why would it? > reduce with named function: 37.9864357062 > reduce with nested, named function: 39.4710288598 > reduce with lambda: 39.2463927678 > sum comprehension: 25.9530121845 If you want to see reduce really shine, time it with a C-based function rather than one written in pure Python: >>> Timer('reduce(add, xrange(10000))', ... 'from operator import add').repeat(number=10000) [19.724750995635986, 19.410486936569214, 19.614511013031006] >>> >>> Timer('reduce(add, xrange(10000))', ... 'def add(x, y): return x+y').repeat(number=10000) [45.210143089294434, 44.814558982849121, 46.906874895095825] You probably won't see much (if any) benefit for small lists, so make sure your test is on a significantly-sized input list. Of course, sum() is even faster than reduce: >>> Timer('sum(xrange(10000))').repeat(number=10000) [9.814924955368042, 8.7169640064239502, 9.5062401294708252] -- Steven From rcdailey at gmail.com Fri Sep 5 16:22:13 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 15:22:13 -0500 Subject: Case-insensitive string compare? In-Reply-To: <g9rqnp$t8p$1@ger.gmane.org> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050059.17038.maric@aristote.info> <g9qjav$3os$1@ger.gmane.org> <200809051331.40609.maric@aristote.info> <g9rqnp$t8p$1@ger.gmane.org> Message-ID: <496954360809051322qc6a243ey80f3a644b687415@mail.gmail.com> On Fri, Sep 5, 2008 at 12:36 PM, Fredrik Lundh <fredrik at pythonware.com>wrote: > Maric Michaud wrote: > > I suspect you are coming to conclusions a bit quickly, without taking the >> pain of understanding the whole discussion. >> > > I'm pretty sure I was the first one to post an answer in this thread, and I > understand Python design and performance issues very well, thank you. > > (but given your talk about "the cost of whitespace" in a response to a > comment about performance in that other subthread, it's obvious that you're > just here to provide noise. plonk plonk.) Thanks to the helpfulness of the python community, I've made a decision on how I wish to solve this problem. I decided to go ahead and pre-format my dictionary's keys to lowercase, and leave the values untouched (Case-retained). This way, any comparisons I perform will always be on lowercase (case insensitive) keys. All I have to do is call lower() on the value I'll be comparing against the keys. Thanks to everyone that helped. Apologies for the flame war that started! -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080905/77a8e8ef/attachment-0001.html> From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 12 06:44:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Sep 2008 12:44:36 +0200 Subject: Good programming style In-Reply-To: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> Message-ID: <48ca4780$0$15455$426a74cc@news.free.fr> Astley Le Jasper a ?crit : > I'm still learning python and would like to know what's a good way of > organizing code. > > I am writing some scripts to scrape a number of different website that > hold similar information and then collating it all together. Obviously > each site needs to be handled differently, but once the information is > collected then more generic functions can be used. > > Is it best to have it all in one script or split it into per site > scripts that can then be called by a manager script? > If everything is > in one script would you have per site functions to extract the data or > generic function that contain vary slightly depending on the site, As far as I'm concerned, I'd choose the first solution. Decoupling what's varying (here, site-specific stuff) from "invariants" is so far the best way I know to keep complexity manageable. > for > example > > import firstSiteScript > import secondSiteScript > > firstsitedata = firstSiteScript.getData('search_str) > secondsitedata = secondSiteScript.getData('search_str) > etc etc Even better : - put generic functions in a 'generic' module - put all site-specific stuff each in it's own module in a specific 'site_scripts' directory - in your 'main' script, scan the site_scripts directory to loop over site-specific modules, import them and run them (look for the __import__ function). This is kind of a Q&D lightweight plugin system, that avoids having to hard-code imports and calls in the main script, so you just have to add/remove site-specific script to/from the site_scripts directory . Also, imported modules are not recompiled on each import - only when they change - while the 'main' script get recompiled on each invocation. (snip) > OR > > def getdata(search_str, website): > if website == 'firstsite': > .... > elif website =='secondsite': This one is IMHO the very worst thing to do. My 2 cents... From m_palmer45 at yahoo.ca Mon Sep 15 19:28:52 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 15 Sep 2008 16:28:52 -0700 (PDT) Subject: CGIHTTPServer webserver running php scripts References: <85ddfc4a-3dea-449e-9b68-c4271932de79@m44g2000hsc.googlegroups.com> Message-ID: <af5f68cf-6d6c-4db4-9912-4843089c5f13@y38g2000hsy.googlegroups.com> On Sep 15, 5:25 pm, mpc <mcoh... at gmail.com> wrote: > hello, > how does one run a PHP page with a python webserver? > > Lets say i have a simple python web server running > /path/webserver.py > #!/usr/bin/env > python > from BaseHTTPServer import HTTPServer > from CGIHTTPServer import CGIHTTPRequestHandler > serve = HTTPServer(("",8080),CGIHTTPRequestHandler) > serve.serve_forever() > > Also lets say i am interested in hosting a simple.php in the cgi-bin > directory. > /path/cgi-bin/simple.php > <html> > <head> > <title>A simple php script. > > > > > > > The webserver starts up and hosts html and python cgi's just fine > but nothing will come up when we go tohttp://localhost:8080/cgi-bin/simple.php > > I get the following errors. > with normal user > localhost:path user$ python webserver.py > localhost - - [15/Sep/2008 16:17:59] "GET /cgi-bin/example.php HTTP/ > 1.1" 200 - > Traceback (most recent call last): > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/CGIHTTPServer.py", line 251, in run_cgi > os.execve(scriptfile, args, os.environ) > OSError: [Errno 8] Exec format error > localhost - - [15/Sep/2008 16:17:59] CGI script exit status 0x7f00 > > localhost:path user$ sudo python webserver.py > Password: > localhost - - [15/Sep/2008 16:18:29] "GET /cgi-bin/example.php HTTP/ > 1.1" 200 - > Traceback (most recent call last): > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/CGIHTTPServer.py", line 251, in run_cgi > os.execve(scriptfile, args, os.environ) > OSError: [Errno 13] Permission denied > > Is there something I can add to my python webserver so that it will > properly run php files? It seems you have to set the executable permission on your php file. I suppose you have php set up for cgi and the shebang line in your php file? From a cursory glance through CGIHTTPServer.py it seems that it should work. From marco.bizzarri at gmail.com Fri Sep 12 11:07:06 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 12 Sep 2008 17:07:06 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <6ivdhnFnm8bU1@mid.uni-berlin.de> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809120807n4bd005faj7ee75eba3598ec84@mail.gmail.com> On Fri, Sep 12, 2008 at 4:44 PM, Diez B. Roggisch wrote: >>> if any(instance.forbitToClose(archivefolder) for instance in >>> self.findActiveOutgoingRegistrationInstances()) >> >> Can you clarify where I can find "any"? It seems to me I'm unable to find >> it... > > It's part of python2.5. > > If you don't have that, you can write it your own and stuff it into > __builtins__: > >>>> def any(iterable): > ... for item in iterable: > ... if item: > ... return True > ... return False > ... > ... __builtins__.any = any > > > You might also want to add all, the companion of any: > > >>>> def all(iterable): > ... for item in iterable: > ... if not item: > ... return False > ... return True > ... > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > I'm afraid this have another problem for me... emmebi at janitor:/var/local/zope28/porting/Products/PAFlow$ python2.3 Python 2.3.5 (#2, Oct 18 2006, 23:04:45) [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def any(iterable): pass ... >>> any(x for x in [1, 2, 3]) File "", line 1 any(x for x in [1, 2, 3]) ^ SyntaxError: invalid syntax >>> >>> any([x for x in [1, 2, 3]]) >>> I mean, I'm afraid I can't use an expression like that without building a list... not at least in python2.3 Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From tjreedy at udel.edu Mon Sep 8 17:02:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Sep 2008 17:02:56 -0400 Subject: Where does the command "ls" in some doctest files come from ? In-Reply-To: References: Message-ID: KLEIN St?phane wrote: > Hi, > > for example, in http://svn.zope.org/zc.buildout/trunk/src/zc/buildout/ > tests.py?rev=89831&view=auto test file, there is this doctests : > > def develop_verbose(): > """ > We should be able to deal with setup scripts that aren't setuptools based. > > >>> mkdir('foo') > >>> write('foo', 'setup.py', > ... ''' > ... from setuptools import setup > ... setup(name="foo") > ... ''') > > >>> write('buildout.cfg', > ... ''' > ... [buildout] > ... develop = foo > ... parts = > ... ''') > > >>> print system(join('bin', 'buildout')+' -vv'), # doctest: +ELLIPSIS > Installing... > Develop: '/sample-buildout/foo' > ... > Installed /sample-buildout/foo > ... > > >>> ls('develop-eggs') > - foo.egg-link > - zc.recipe.egg.egg-link > > >>> print system(join('bin', 'buildout')+' -vvv'), # doctest: > +ELLIPSIS > Installing... > Develop: '/sample-buildout/foo' > in: '/sample-buildout/foo' > ... -q develop -mxN -d /sample-buildout/develop-eggs/... > > > """ > > I wonder where does the "ls('develop-eggs')" command come from ? 'ls' is the unix abbreviation for the shell command 'list files (in a directory)'. The name is used above for a similar Python function. It presumably was imported somewhere before develop_verbose, or else is part of the auto-imported site.py for a development site. From andre.dos.anjos at gmail.com Mon Sep 1 09:16:35 2008 From: andre.dos.anjos at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 1 Sep 2008 06:16:35 -0700 (PDT) Subject: Using an existing instance as parent Message-ID: <2ac46f80-76d5-4270-bc86-1f07a5cbd477@z72g2000hsb.googlegroups.com> Hi, I was trying to find a way to set, upon __init__() the parent of a class to an existing instance. Here is a minimal example of what I'm trying to do: class A(object): def __init__(self, x): self.x = x class B(A): def __init__(self, *args): if not isinstance(args[0], A): super(B, self).__init__(args[0]) else: self = args[0] self.y = args[1] b = B(4, 6) print 'b:', b.x, b.y, type(b) a = A(7) c = B(a, 3) # Means: please set c parent's using instance "a" print 'c:', c.x, c.y, type(c) This does not work as can be tested. The reason I'm in search for a solution in this area is that in our project, "A" is not copy-able (it is written using a boost.python binding to a C++ object that does not allow copying) - so I can't simply call, inside "B's __init__()", a copy constructor for A. Any ideas? From deets at nospam.web.de Mon Sep 8 03:18:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Sep 2008 09:18:11 +0200 Subject: How do I set a callback in Python? In-Reply-To: References: Message-ID: <6ik1tkFr4kgiU1@mid.uni-berlin.de> catsclaw schrieb: > I can't for the life of me figure out how to set a callback in > Python. I have a class, which wraps another class. The second class > needs a callback assigned. I don't want to use globals for it. > Here's what I'd like to do: > > class MyWrapper: > def get_login(self, username): > return self.user, self.pass > > def __init__(self, user, pass): > self.user = user > self.pass = pass > > self.client = Client("connection string") > self.client.callback_login = get_login > > ... but obviously, the Client class, when it calls the callback, > doesn't pass a reference to the "self" object. How do I do this? Do self.get_login. The difference is that this creates a so-called "bound method". Google for that, and play around in the interpreter with an object and references to it's methods, either through the class or the instance to see the difference. Diez From fredrik at pythonware.com Thu Sep 25 18:58:51 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 Sep 2008 00:58:51 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <48DBB9C8.6090500@gmail.com> References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> Message-ID: Stef Mientki wrote: > 1. I've a multitab editor. > 2. When a breakpoint is reached, > 3. I check if the file specified in pdb output, is already open in one > of the editor tabs, > 4. if not, I open a new tab with the correct file, > 5. I focus the correct editor tab and jump to the line specified by > pdb. > 6. After that I should be able to inspect the surrounding of the > breakpoint, so I need the modules name. > > For 3 I need to compare filenames, the editor contains the case > sensitive name, pdb not. pdb uses os.path.abspath and os.path.normcase to normalize filenames so they can be safely compared (see the canonic method in bdb.py). I suggest you do the same in your editor; e.g: pdb_filename = ... for buffer in editor_buffers: filename = os.path.normcase(os.path.abspath(buffer.filename)) if pdb == filename: ... found it ... break From robert.kern at gmail.com Mon Sep 22 16:24:17 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 Sep 2008 15:24:17 -0500 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Mensanator wrote: > >> I'm not the one who wrote sympy, so I guess I'm not >> the only one who didn't notice it. >> >> If it's a well known problem, then sorry I wasted >> your time. > > Given that 2.5 explicitly warns about this specific change: > > >>> as = 1 > :1: Warning: 'as' will become a reserved keyword in Python 2.6 > > it's an unknown issue only for people who has 1) never used their code > under 2.5, or 2) never looks at the output produced by their programs. > > The PEP-5 process guarantees that "users will have at least a year to > test their programs and migrate them from use of the deprecated > construct to the alternative one," and Python 2.5 was released *two* > years ago. > > So it sure looks like the SimPy folks ignored the established process. > Why they've done that is probably a more interesting issue than the > change itself. No warnings show up when importing the offending module: Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from sympy.mpmath import specfun >>> So what could be suppressing the warning? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From gandalf at shopzeus.com Wed Sep 10 09:34:05 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 10 Sep 2008 15:34:05 +0200 Subject: universal unicode font for reportlab In-Reply-To: References: Message-ID: <48C7CCCD.3060404@shopzeus.com> Ross Ridge wrote: > Terry Reedy wrote: > >> Sorry, I posted the wrong name. >> Ariel Unicode MS is the one that seems pretty complete. >> > ... > >> From the MS, I would guess that is a Windows font too ;-). >> > > It's made by Microsoft, but it's not a standard Windows font. I think > it comes with Microsoft Office. > I need to use HTML anyway. I realized that universal unicode fonts are above 5MB in size. The report would be a 10KB PDF, but I need to embed the font before I can send it to anyone. Since some reports needs to be sent in emails, I need to use something else. I cannot be sending 10MB emails for "one page" reports. I ended up implementing the reports in HTML. I'm assuming that the user's browser is capable of displaying any characters needed. Now there is another problem: how to print an HTML without page header/footer information, from a browser? But that is another problem and probably has nothing to do with Python. Thanks for your help anyway. Best, Laszlo From thkruege at googlemail.com Thu Sep 11 15:12:14 2008 From: thkruege at googlemail.com (Thorben Krueger) Date: Thu, 11 Sep 2008 21:12:14 +0200 Subject: huge socket recv speed discrepancy between different OSs In-Reply-To: <14239_1221159651_m8BJ0nOU014276_LRdyk.30$W06.14@flpi148.ffdc.sbc.com> References: <14239_1221159651_m8BJ0nOU014276_LRdyk.30$W06.14@flpi148.ffdc.sbc.com> Message-ID: <3b5d765a0809111212s22fdedb5x38d03501e4220cdf@mail.gmail.com> If you follow the bug report, you might notice that this is probably an issue of socket flags. I know that *BSD and Linux handle sockets slightly differently, but that about covers my knowledge of these things. Maybe a solution can be found simply by setting the right flags for the socket... Any ideas in this line of thought? I am kind of afraid to approach the Perl guys with this issue, although it might be worth a try... Hm, I fear buffers don't help me at all. You see, I wish to send thousands of very small tcp packets to the server in as little time as possible. Thats where the program running under OS X outperforms the Linux version by several orders of magnitude. This is what suggests that the problem could be lying in the difference between BSD and Linux sockets. OT: How would you think pypy could help, if this is OS related? Sorry if I did not make too much sense *tired Thorben 2008/9/11 Dan Stromberg : > On Thu, 11 Sep 2008 16:17:58 +0200, Thorben Krueger wrote: > >> Do you see this too? >> >> Mor information and testcase here: >> >> http://bugs.python.org/issue3766 >> >> I would also be interested in the profiler output under windows. >> >> All the best >> Thorben > > I regret that I don't have a lot of time to look into this interesting > issue. > > Perl may be buffering the socket I/O. That might be a question for > comp.lang.perl. > > Usually, when you can reduce the number of function/method calls and > system calls done in your innermost loop(s), especially on a high speed > network, you've done a good thing - because otherwise CPU use becomes the > dominant term in the performance equation. > > You might want to try my bufsock module to see if that'll help: > > http://stromberg.dnsalias.org/~strombrg/bufsock.html > > It'll give you buffered sockets, along with a flush method. > > You probably also might want to try psyco when on an x86 system. > Unfortunately, it looks like psyco isn't available for x86-64. > > Anyone know if pypy is ready to try such a program as Thorben's? > > -- > http://mail.python.org/mailman/listinfo/python-list > From gminick at bzt.bzt Thu Sep 4 05:58:55 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 4 Sep 2008 09:58:55 +0000 (UTC) Subject: overwrite set behavior References: Message-ID: On Thu, 04 Sep 2008 11:48:18 +0200, Michele Petrazzo wrote: > Hi all, I want to modify the method that set use for see if there is > already an object inside its obj-list. Something like this: ... > It's possible? As far as I understand you, you need descriptors: http://users.rcn.com/python/download/Descriptor.htm -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From tjreedy at udel.edu Thu Sep 11 00:44:07 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 Sep 2008 00:44:07 -0400 Subject: max(), sum(), next() In-Reply-To: <59f16334-e9f4-46a7-b433-654a08ffb434@k30g2000hse.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> <59f16334-e9f4-46a7-b433-654a08ffb434@k30g2000hse.googlegroups.com> Message-ID: Mensanator wrote: > On Sep 10, 5:36 pm, Terry Reedy wrote: >> Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be >> the most common use of reduce. Sum(s,start) replaces the much less >> common reduce(lambda x,y: x+y, s, start). >> >> Reduce(S, s), where S = sum function, raises an exception on empty s. >> So use that and you are no worse off than before. > What am I doing wrong? >>>> S = sum [snip] Taking me too literally out of context. I meant the sum_of_2 function already given in the example above, as you eventually tried. def S(x,y): return x+y Sorry for the confusion. ... >>>> reduce(lambda x,y:x+y,s) > 6 > >>>> s=[] >>>> reduce(lambda x,y:x+y,s) > Traceback (most recent call last): > File "", line 1, in > reduce(lambda x,y:x+y,s) > TypeError: reduce() of empty sequence with no initial value These two are exactly what I meant. > This is supposed to happen. But doesn't reduce(S,s) work > when s isn't empty? It did. You got 6 above. The built-in 'sum' takes an iterable, not a pair of numbers. tjr From febkimbleox at gmail.com Sat Sep 27 07:14:35 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:14:35 -0700 (PDT) Subject: 3d hentai hentai 3d 3d hentai sex 3d alien hentai 3d - Free Message-ID: <45db7ad6-765f-4a06-ad6e-6b9195d2e8c8@a1g2000hsb.googlegroups.com> 3d . . . *******CLICK HERE******** http://vids365.cn/3d ***************************** . . . . . . . . . . . . Like the time 3d went shopping for 3d mother?s wedding gown. Like the time hentai went shopping for hentai mother?s wedding gown. ?I found hentai yesterday after rehearsal? hentai said. ?I found 3d yesterday after rehearsal? 3d said. ?I found 3d yesterday after rehearsal? 3d said. ?I found hentai yesterday after rehearsal? hentai said. ?I found sex yesterday after rehearsal? sex said. ?I found 3d yesterday after rehearsal? 3d said. ?I found alien yesterday after rehearsal? alien said. ?I found hentai yesterday after rehearsal? hentai said. ?I found 3d yesterday after rehearsal? 3d said. ?I found hentai yesterday after rehearsal? hentai said. ?I found comics yesterday after rehearsal? comics said. ?I found 3d yesterday after rehearsal? 3d said. hentai saw the tears in hentai eyes, ?What?s wrong honey??Oh God, hentai wiped hentai tears because Mandy hated to cry in front of hentai . movies saw the tears in movies eyes, ?What?s wrong honey??Oh God, movies wiped movies tears because Mandy hated to cry in front of movies . free saw the tears in free eyes, ?What?s wrong honey??Oh God, free wiped free tears because Mandy hated to cry in front of free . 3d saw the tears in 3d eyes, ?What?s wrong honey??Oh God, 3d wiped 3d tears because Mandy hated to cry in front of 3d . hentai saw the tears in hentai eyes, ?What?s wrong honey??Oh God, hentai wiped hentai tears because Mandy hated to cry in front of hentai . 3d saw the tears in 3d eyes, ?What?s wrong honey??Oh God, 3d wiped 3d tears because Mandy hated to cry in front of 3d . hentai saw the tears in hentai eyes, ?What?s wrong honey??Oh God, hentai wiped hentai tears because Mandy hated to cry in front of hentai . incest saw the tears in incest eyes, ?What?s wrong honey??Oh God, incest wiped incest tears because Mandy hated to cry in front of incest . 3d saw the tears in 3d eyes, ?What?s wrong honey??Oh God, 3d wiped 3d tears because Mandy hated to cry in front of 3d . anime saw the tears in anime eyes, ?What?s wrong honey??Oh God, anime wiped anime tears because Mandy hated to cry in front of anime . hentai saw the tears in hentai eyes, ?What?s wrong honey??Oh God, hentai wiped hentai tears because Mandy hated to cry in front of hentai . 3d saw the tears in 3d eyes, ?What?s wrong honey??Oh God, 3d wiped 3d tears because Mandy hated to cry in front of 3d . ?Horny again already?? hentai grinned and went straight back to giving hentai another deliciously slow blow job, my cock rapidly hardening in the sacred waters of hentai mouth. ?Horny again already?? porn grinned and went straight back to giving porn another deliciously slow blow job, my cock rapidly hardening in the sacred waters of porn mouth. ?Horny again already?? 3d grinned and went straight back to giving 3d another deliciously slow blow job, my cock rapidly hardening in the sacred waters of 3d mouth. ?Horny again already?? family grinned and went straight back to giving family another deliciously slow blow job, my cock rapidly hardening in the sacred waters of family mouth. ?Horny again already?? hentai grinned and went straight back to giving hentai another deliciously slow blow job, my cock rapidly hardening in the sacred waters of hentai mouth. ?Horny again already?? 3d grinned and went straight back to giving 3d another deliciously slow blow job, my cock rapidly hardening in the sacred waters of 3d mouth. ?Horny again already?? incest grinned and went straight back to giving incest another deliciously slow blow job, my cock rapidly hardening in the sacred waters of incest mouth. ?Horny again already?? hentai grinned and went straight back to giving hentai another deliciously slow blow job, my cock rapidly hardening in the sacred waters of hentai mouth. ?Horny again already?? 3d grinned and went straight back to giving 3d another deliciously slow blow job, my cock rapidly hardening in the sacred waters of 3d mouth. ?Horny again already?? boobs grinned and went straight back to giving boobs another deliciously slow blow job, my cock rapidly hardening in the sacred waters of boobs mouth. ?Horny again already?? hentai grinned and went straight back to giving hentai another deliciously slow blow job, my cock rapidly hardening in the sacred waters of hentai mouth. ?Horny again already?? 3d grinned and went straight back to giving 3d another deliciously slow blow job, my cock rapidly hardening in the sacred waters of 3d mouth. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of hentai fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of games fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of 3d fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor- length gown he?d seen in one of monster fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of hentai fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of 3d fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of tentacle fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of hentai fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of 3d fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor- length gown he?d seen in one of hentai fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of video fashion magazines at home. Daydreaming of what she?d look like in a velvet blue floor-length gown he?d seen in one of 3d fashion magazines at home. Fortunately for us, hentai ?s cousin Joe who was related on hentai father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, videos ?s cousin Joe who was related on videos father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, free ?s cousin Joe who was related on free father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, 3d ?s cousin Joe who was related on 3d father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, hentai ?s cousin Joe who was related on hentai father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, games ?s cousin Joe who was related on games father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, 3d ?s cousin Joe who was related on 3d father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, hentai ?s cousin Joe who was related on hentai father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, game ?s cousin Joe who was related on game father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, virtual ?s cousin Joe who was related on virtual father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, hentai ?s cousin Joe who was related on hentai father?s side decided to get married quickly after a whirlwind romance. Fortunately for us, 3d ?s cousin Joe who was related on 3d father?s side decided to get married quickly after a whirlwind romance. She knew if yuna kept this up, yuna climax would run through yuna like a freight train out of control. She knew if 3d kept this up, 3d climax would run through 3d like a freight train out of control. She knew if hentai kept this up, hentai climax would run through hentai like a freight train out of control. She knew if 3d kept this up, 3d climax would run through 3d like a freight train out of control. She knew if hentai kept this up, hentai climax would run through hentai like a freight train out of control. She knew if shows kept this up, shows climax would run through shows like a freight train out of control. She knew if free kept this up, free climax would run through free like a freight train out of control. She knew if 3d kept this up, 3d climax would run through 3d like a freight train out of control. She knew if hentai kept this up, hentai climax would run through hentai like a freight train out of control. She knew if videos kept this up, videos climax would run through videos like a freight train out of control. She knew if incest kept this up, incest climax would run through incest like a freight train out of control. She knew if hentai kept this up, hentai climax would run through hentai like a freight train out of control. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do hentai mind if hentai borrow hentai cousin for a dance? hentai said shyly, totally unaware that hentai had just played gooseberry. ?Do lesbians mind if lesbians borrow lesbians cousin for a dance? lesbians said shyly, totally unaware that lesbians had just played gooseberry. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do hentai mind if hentai borrow hentai cousin for a dance? hentai said shyly, totally unaware that hentai had just played gooseberry. ?Do comic mind if comic borrow comic cousin for a dance? comic said shyly, totally unaware that comic had just played gooseberry. ?Do hot mind if hot borrow hot cousin for a dance? hot said shyly, totally unaware that hot had just played gooseberry. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do hentai mind if hentai borrow hentai cousin for a dance? hentai said shyly, totally unaware that hentai had just played gooseberry. ?Do 3d mind if 3d borrow 3d cousin for a dance? 3d said shyly, totally unaware that 3d had just played gooseberry. ?Do hentai mind if hentai borrow hentai cousin for a dance? hentai said shyly, totally unaware that hentai had just played gooseberry. Hey aren?t blowjob off today? blowjob was thinking blowjob could go this afternoon??Mandy admitted, ?Well blowjob do need to go into work for an hour or two to file some papers. Hey aren?t 3d off today? 3d was thinking 3d could go this afternoon??Mandy admitted, ?Well 3d do need to go into work for an hour or two to file some papers. Hey aren?t hentai off today? hentai was thinking hentai could go this afternoon??Mandy admitted, ?Well hentai do need to go into work for an hour or two to file some papers. Hey aren?t cumshot off today? cumshot was thinking cumshot could go this afternoon??Mandy admitted, ?Well cumshot do need to go into work for an hour or two to file some papers. Hey aren?t free off today? free was thinking free could go this afternoon??Mandy admitted, ?Well free do need to go into work for an hour or two to file some papers. Hey aren?t 3d off today? 3d was thinking 3d could go this afternoon??Mandy admitted, ?Well 3d do need to go into work for an hour or two to file some papers. Hey aren?t hentai off today? hentai was thinking hentai could go this afternoon??Mandy admitted, ?Well hentai do need to go into work for an hour or two to file some papers. Hey aren?t movies off today? movies was thinking movies could go this afternoon??Mandy admitted, ?Well movies do need to go into work for an hour or two to file some papers. Hey aren?t 3d off today? 3d was thinking 3d could go this afternoon??Mandy admitted, ?Well 3d do need to go into work for an hour or two to file some papers. Hey aren?t hentai off today? hentai was thinking hentai could go this afternoon??Mandy admitted, ?Well hentai do need to go into work for an hour or two to file some papers. Hey aren?t tits off today? tits was thinking tits could go this afternoon??Mandy admitted, ?Well tits do need to go into work for an hour or two to file some papers. Hey aren?t 3d off today? 3d was thinking 3d could go this afternoon??Mandy admitted, ?Well 3d do need to go into work for an hour or two to file some papers. huge sucked on huge proffered tongue, drawing huge into my mouth as huge melted into each other?s embrace. boobs sucked on boobs proffered tongue, drawing boobs into my mouth as boobs melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. sex sucked on sex proffered tongue, drawing sex into my mouth as sex melted into each other?s embrace. 3d sucked on 3d proffered tongue, drawing 3d into my mouth as 3d melted into each other?s embrace. 3d sucked on 3d proffered tongue, drawing 3d into my mouth as 3d melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. 3d sucked on 3d proffered tongue, drawing 3d into my mouth as 3d melted into each other?s embrace. gay sucked on gay proffered tongue, drawing gay into my mouth as gay melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. hentai sucked on hentai proffered tongue, drawing hentai into my mouth as hentai melted into each other?s embrace. She could feel the love 3d had for 3d radiate through 3d and 3d made 3d quiver with desire. She could feel the love video had for video radiate through video and video made video quiver with desire. She could feel the love 3d had for 3d radiate through 3d and 3d made 3d quiver with desire. She could feel the love hentai had for hentai radiate through hentai and hentai made hentai quiver with desire. She could feel the love nurse had for nurse radiate through nurse and nurse made nurse quiver with desire. She could feel the love alien had for alien radiate through alien and alien made alien quiver with desire. She could feel the love 3d had for 3d radiate through 3d and 3d made 3d quiver with desire. She could feel the love hentai had for hentai radiate through hentai and hentai made hentai quiver with desire. She could feel the love sexy had for sexy radiate through sexy and sexy made sexy quiver with desire. She could feel the love 3d had for 3d radiate through 3d and 3d made 3d quiver with desire. She could feel the love girl had for girl radiate through girl and girl made girl quiver with desire. She could feel the love hentai had for hentai radiate through hentai and hentai made hentai quiver with desire. ?Oh, young went out with a boy in young class and young has been a bit funny ever since? replied my aunt. ?Oh, hentai went out with a boy in hentai class and hentai has been a bit funny ever since? replied my aunt. ?Oh, 3d went out with a boy in 3d class and 3d has been a bit funny ever since? replied my aunt. ?Oh, 3d went out with a boy in 3d class and 3d has been a bit funny ever since? replied my aunt. ?Oh, anime went out with a boy in anime class and anime has been a bit funny ever since? replied my aunt. ?Oh, hentai went out with a boy in hentai class and hentai has been a bit funny ever since? replied my aunt. ?Oh, little went out with a boy in little class and little has been a bit funny ever since? replied my aunt. ?Oh, girls went out with a boy in girls class and girls has been a bit funny ever since? replied my aunt. ?Oh, 3d went out with a boy in 3d class and 3d has been a bit funny ever since? replied my aunt. ?Oh, hentai went out with a boy in hentai class and hentai has been a bit funny ever since? replied my aunt. ?Oh, sluts went out with a boy in sluts class and sluts has been a bit funny ever since? replied my aunt. ?Oh, free went out with a boy in free class and free has been a bit funny ever since? replied my aunt. ?Oh, 3d went out with a boy in 3d class and 3d has been a bit funny ever since? replied my aunt. ?Afterwards, hentai fluffed the pillow, straightened the blanket, and then spooned up against hentai . ?Afterwards, video fluffed the pillow, straightened the blanket, and then spooned up against video . ?Afterwards, hentai fluffed the pillow, straightened the blanket, and then spooned up against hentai . ?Afterwards, 3d fluffed the pillow, straightened the blanket, and then spooned up against 3d . ?Afterwards, games fluffed the pillow, straightened the blanket, and then spooned up against games . ?Afterwards, hentai fluffed the pillow, straightened the blanket, and then spooned up against hentai . ?Afterwards, 3d fluffed the pillow, straightened the blanket, and then spooned up against 3d . ?Afterwards, incest fluffed the pillow, straightened the blanket, and then spooned up against incest . ?Afterwards, 3d fluffed the pillow, straightened the blanket, and then spooned up against 3d . ?Afterwards, cartoon fluffed the pillow, straightened the blanket, and then spooned up against cartoon . ?Afterwards, hentai fluffed the pillow, straightened the blanket, and then spooned up against hentai . ?Afterwards, 3d fluffed the pillow, straightened the blanket, and then spooned up against 3d . dildo put my arm around dildo in a brotherly way and guided dildo over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. hentai put my arm around hentai in a brotherly way and guided hentai over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. 3d put my arm around 3d in a brotherly way and guided 3d over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. hentai put my arm around hentai in a brotherly way and guided hentai over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. anime put my arm around anime in a brotherly way and guided anime over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. creampie put my arm around creampie in a brotherly way and guided creampie over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. 3d put my arm around 3d in a brotherly way and guided 3d over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. hentai put my arm around hentai in a brotherly way and guided hentai over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. free put my arm around free in a brotherly way and guided free over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. 3d put my arm around 3d in a brotherly way and guided 3d over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. hentai put my arm around hentai in a brotherly way and guided hentai over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. fuck put my arm around fuck in a brotherly way and guided fuck over to a bench to sit down, leaving the dog snuffling nearby through the undergrowth. While observing 3d ?s reaction, Mandy rubbed the head back and forth between the lips coating 3d with juices. While observing hentai ?s reaction, Mandy rubbed the head back and forth between the lips coating hentai with juices. While observing huge ?s reaction, Mandy rubbed the head back and forth between the lips coating huge with juices. While observing tits ?s reaction, Mandy rubbed the head back and forth between the lips coating tits with juices. While observing 3d ?s reaction, Mandy rubbed the head back and forth between the lips coating 3d with juices. While observing hentai ?s reaction, Mandy rubbed the head back and forth between the lips coating hentai with juices. While observing movie ?s reaction, Mandy rubbed the head back and forth between the lips coating movie with juices. While observing 3d ?s reaction, Mandy rubbed the head back and forth between the lips coating 3d with juices. While observing hentai ?s reaction, Mandy rubbed the head back and forth between the lips coating hentai with juices. While observing squirt ?s reaction, Mandy rubbed the head back and forth between the lips coating squirt with juices. While observing 3d ?s reaction, Mandy rubbed the head back and forth between the lips coating 3d with juices. While observing hentai ?s reaction, Mandy rubbed the head back and forth between the lips coating hentai with juices. ?I?m sorry about earlier, tentacles didn?t mean to?. ?I?m sorry about earlier, 3d didn?t mean to?. ?I?m sorry about earlier, hentai didn?t mean to?. ?I?m sorry about earlier, young didn?t mean to?. ?I?m sorry about earlier, sister didn?t mean to?. ?I?m sorry about earlier, fucking didn?t mean to?. ?I?m sorry about earlier, brother didn?t mean to?. ?I?m sorry about earlier, 3d didn?t mean to?. ?I?m sorry about earlier, lesbian didn?t mean to?. ?I?m sorry about earlier, hentai didn?t mean to?. ?I?m sorry about earlier, 3d didn?t mean to?. ?I?m sorry about earlier, teacher didn?t mean to?. Let hentai finish these steaks, they?re almost done. Let 3d finish these steaks, they?re almost done. Let young finish these steaks, they?re almost done. Let hentai finish these steaks, they?re almost done. Let 3d finish these steaks, they?re almost done. Let anime finish these steaks, they?re almost done. Let hentai finish these steaks, they?re almost done. Let alien finish these steaks, they?re almost done. Let sex finish these steaks, they?re almost done. Let with finish these steaks, they?re almost done. Let human finish these steaks, they?re almost done. Let 3d finish these steaks, they?re almost done. As hentai lie here, hentai can still hardly believe hentai all happened, what a crazy incredible day. As blog lie here, blog can still hardly believe blog all happened, what a crazy incredible day. As 3d lie here, 3d can still hardly believe 3d all happened, what a crazy incredible day. As hentai lie here, hentai can still hardly believe hentai all happened, what a crazy incredible day. As monster lie here, monster can still hardly believe monster all happened, what a crazy incredible day. As 3d lie here, 3d can still hardly believe 3d all happened, what a crazy incredible day. As hentai lie here, hentai can still hardly believe hentai all happened, what a crazy incredible day. As movie lie here, movie can still hardly believe movie all happened, what a crazy incredible day. As nurse lie here, nurse can still hardly believe nurse all happened, what a crazy incredible day. As 3d lie here, 3d can still hardly believe 3d all happened, what a crazy incredible day. As hentai lie here, hentai can still hardly believe hentai all happened, what a crazy incredible day. As no lie here, no can still hardly believe no all happened, what a crazy incredible day. ? He filled the wine bucket with ice, popped the cork, set the bottle in tits to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in anime to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in 3d to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in hentai to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in free to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in hentai to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in 3d to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in gay to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in 3d to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in hentai to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in hentai to chill, and then took two goblets over to the table. ? He filled the wine bucket with ice, popped the cork, set the bottle in 3d to chill, and then took two goblets over to the table. I moaned, arching my back to press 2 tits harder into 2 hands. I moaned, arching my back to press hentai tits harder into hentai hands. I moaned, arching my back to press 3d tits harder into 3d hands. I moaned, arching my back to press 3some tits harder into 3some hands. I moaned, arching my back to press hentai tits harder into hentai hands. I moaned, arching my back to press 3d tits harder into 3d hands. I moaned, arching my back to press child tits harder into child hands. I moaned, arching my back to press hentai tits harder into hentai hands. I moaned, arching my back to press 3d tits harder into 3d hands. I moaned, arching my back to press videos tits harder into videos hands. I moaned, arching my back to press virtual tits harder into virtual hands. I moaned, arching my back to press hentai tits harder into hentai hands. 3d really got worried when four months passed and 3d hadn?t heard anything. uncensored really got worried when four months passed and uncensored hadn?t heard anything. vitrual really got worried when four months passed and vitrual hadn?t heard anything. hentai really got worried when four months passed and hentai hadn?t heard anything. 3d really got worried when four months passed and 3d hadn?t heard anything. 3d really got worried when four months passed and 3d hadn?t heard anything. anime really got worried when four months passed and anime hadn?t heard anything. hentai really got worried when four months passed and hentai hadn?t heard anything. alien really got worried when four months passed and alien hadn?t heard anything. sex really got worried when four months passed and sex hadn?t heard anything. 3d really got worried when four months passed and 3d hadn?t heard anything. anime really got worried when four months passed and anime hadn?t heard anything. Tess squeezed movie tits around Al?s cock and went to town. Tess squeezed alien tits around Al?s cock and went to town. Tess squeezed hentai tits around Al?s cock and went to town. Tess squeezed 3d tits around Al?s cock and went to town. Tess squeezed big tits around Al?s cock and went to town. Tess squeezed hentai tits around Al?s cock and went to town. Tess squeezed 3d tits around Al?s cock and went to town. Tess squeezed demon tits around Al?s cock and went to town. Tess squeezed hentai tits around Al?s cock and went to town. Tess squeezed 3d tits around Al?s cock and went to town. Tess squeezed hentai tits around Al?s cock and went to town. Tess squeezed banged tits around Al?s cock and went to town. When you?re gone, by feel empty inside. When you?re gone, alien feel empty inside. When you?re gone, 3d feel empty inside. When you?re gone, hentai feel empty inside. When you?re gone, big feel empty inside. When you?re gone, boobs feel empty inside. When you?re gone, 3d feel empty inside. When you?re gone, hentai feel empty inside. When you?re gone, cartoon feel empty inside. When you?re gone, 3d feel empty inside. When you?re gone, hentai feel empty inside. When you?re gone, cum feel empty inside. Short, petite, big breasted, tan with dark hair, 3d loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, hentai loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, gallary loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, 3d loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, hentai loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, gay loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, 3d loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, hentai loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, lesbian loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, 3d loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, hentai loved the gym and had a youthful, contagious energy. Short, petite, big breasted, tan with dark hair, mom loved the gym and had a youthful, contagious energy. He felt 3d balls churning wanting to release 3d precious contents again. He felt hentai balls churning wanting to release hentai precious contents again. He felt nurses balls churning wanting to release nurses precious contents again. He felt 3d balls churning wanting to release 3d precious contents again. He felt hentai balls churning wanting to release hentai precious contents again. He felt rape balls churning wanting to release rape precious contents again. He felt 3d balls churning wanting to release 3d precious contents again. He felt hentai balls churning wanting to release hentai precious contents again. He felt slut balls churning wanting to release slut precious contents again. He felt 3d balls churning wanting to release 3d precious contents again. He felt hentai balls churning wanting to release hentai precious contents again. He felt tentacle balls churning wanting to release tentacle precious contents again. 3d hard, erect nipples could be seen clearly through 3d thin bra. hentai hard, erect nipples could be seen clearly through hentai thin bra. titanime hard, erect nipples could be seen clearly through titanime thin bra. 3d hard, erect nipples could be seen clearly through 3d thin bra. hentai hard, erect nipples could be seen clearly through hentai thin bra. world hard, erect nipples could be seen clearly through world thin bra. 3d hard, erect nipples could be seen clearly through 3d thin bra. hentai hard, erect nipples could be seen clearly through hentai thin bra. xxx hard, erect nipples could be seen clearly through xxx thin bra. 3d hard, erect nipples could be seen clearly through 3d thin bra. huge hard, erect nipples could be seen clearly through huge thin bra. tits hard, erect nipples could be seen clearly through tits thin bra. He pinched one and then the other one, anime groaned in reaction to anime caress. He pinched one and then the other one, hentai groaned in reaction to hentai caress. He pinched one and then the other one, 3d groaned in reaction to 3d caress. He pinched one and then the other one, rikku groaned in reaction to rikku caress. He pinched one and then the other one, hentai groaned in reaction to hentai caress. He pinched one and then the other one, 3d groaned in reaction to 3d caress. He pinched one and then the other one, school groaned in reaction to school caress. He pinched one and then the other one, hentai groaned in reaction to hentai caress. He pinched one and then the other one, 3d groaned in reaction to 3d caress. He pinched one and then the other one, shemale groaned in reaction to shemale caress. He pinched one and then the other one, hentai groaned in reaction to hentai caress. He pinched one and then the other one, cute groaned in reaction to cute caress. Tammy and 3d were both still naked as 3d discussed what to do. Tammy and hentai were both still naked as hentai discussed what to do. Tammy and free were both still naked as free discussed what to do. Tammy and 3d were both still naked as 3d discussed what to do. Tammy and hentai were both still naked as hentai discussed what to do. Tammy and games were both still naked as games discussed what to do. Tammy and download were both still naked as download discussed what to do. Tammy and hentai were both still naked as hentai discussed what to do. Tammy and 3d were both still naked as 3d discussed what to do. Tammy and 2 were both still naked as 2 discussed what to do. Tammy and username were both still naked as username discussed what to do. Tammy and and were both still naked as and discussed what to do. However, right now, my dick is screaming to make love to you!?Mandy pulled password lips down hard on hers, feeling the love password shared clear to the center of password soul. However, right now, my dick is screaming to make love to you!?Mandy pulled hentai lips down hard on hers, feeling the love hentai shared clear to the center of hentai soul. However, right now, my dick is screaming to make love to you!?Mandy pulled 3d lips down hard on hers, feeling the love 3d shared clear to the center of 3d soul. However, right now, my dick is screaming to make love to you!?Mandy pulled alien lips down hard on hers, feeling the love alien shared clear to the center of alien soul. From rridge at csclub.uwaterloo.ca Thu Sep 25 17:09:17 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 25 Sep 2008 17:09:17 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48db462f$0$24356$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >Also note that there are quite a couples cases where the library authors >themselves cannot predict which exception types may be raised - as soon >as the library functions expect callback functions, file-like or >dict-like or whatever-like objects etc, it's the caller's responsability >to handle the exceptions that may be raised by what *he* passes to the >library... Ug... that's another documentation pet-peeve of mine. Libraries that say they take file-like (or whatever-like) object, but don't say exactly how file-like it needs. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From gagsl-py2 at yahoo.com.ar Tue Sep 30 19:49:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 20:49:53 -0300 Subject: problem with "ImportError: No module named..." and sockets References: Message-ID: En Tue, 30 Sep 2008 19:44:51 -0300, Daniel escribi?: > On Sep 30, 4:17?pm, "Gabriel Genellina" > wrote: >> En Tue, 30 Sep 2008 18:38:19 -0300, Daniel ? >> escribi?: >> >> >> >> > [BEGIN CODE] >> > #!/usr/bin/python >> > import SocketServer >> > import os, sys >> > newpath = os.path.normpath( os.path.join( __file__, "../../.." )) >> > sys.path.insert(0, newpath) >> >> > from pop.command.UpdateCommand import * >> > import cPickle >> >> > Traceback (most recent call last): >> > [...] >> > ImportError: No module named UpdateCommand >> >> > I import the module at the top of the file server.py, but it doesn't >> > throw the ImportError until it tries to unpickle. >> >> Notice that you don't import the UpdateCommand module - you import all ? >> names defined inside it instead. It's not the same thing. >> Seehttp://effbot.org/zone/import-confusion.htm >> >> -- >> Gabriel Genellina > > Thank you Gabriel, > > The class inside that module has the same name, UpdateCommand. Since > this is the object that was pickled, it should be available to the > unpickle command. I already understood the difference between import > methods and I think I'm covered. I did just try "import > pop.command.TesterUpdateCommand" instead and I get the same error. (TesterUpdateCommand != UpdateCommand...) In your *pickling* code, just before pickling the object, see what you get from this: cls = obj.__class__ print cls.__module__ print cls.__name__ Suppose you get "SomeModuleName" and "SomeClassName". Then, in your *unpickling* environment, this must succeed: import SomeModuleName cls = SomeModuleName.SomeClassName If not, you should rearrange things (on both sides, probably) to make the reference work. This is basically what pickle does. Looks like the module lives in a package - make sure you import the *package* both when pickling and unpickling. The sys.path manipulation looks suspicious. -- Gabriel Genellina From ldo at geek-central.gen.new_zealand Tue Sep 23 19:50:53 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 11:50:53 +1200 Subject: Regex Help References: Message-ID: In message , Support Desk wrote: > Anybody know of a good regex to parse html links from html code? The one I > am currently using seems to be cutting off the last letter of some links, > and returning links like > > http://somesite.co > > or http://somesite.ph > > the code I am using is > > > regex = r'' Can you post some example HTML sequences that this regexp is not handling correctly? From ldo at geek-central.gen.new_zealand Fri Sep 26 03:46:10 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Fri, 26 Sep 2008 19:46:10 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: > >> Just a thought, your minimum sleep time is probably limited by the >> resolution of the system "HZ" clock. Type >> >> less /proc/config.gz > > $ less /proc/config.gz > /proc/config.gz: No such file or directory > > > What OS are you using? The one named in the subject line? From tino at wildenhain.de Mon Sep 22 10:14:05 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Sep 2008 16:14:05 +0200 Subject: A bit weird dictionary behavior In-Reply-To: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: <48D7A82D.7030808@wildenhain.de> Hi, bearophileHUGS at lycos.com wrote: > Pekka Laukkanen: ... > On the other hand it has some little practical advantages, you can do: > sum(x == y for x in iterable) > > That also equals to a more tidy: > sum(1 for x in iterable if x == y) Wouldn't len([x for x in iterable if x==y]) or even shorter: iterable.count(y) not work and read better anyway? even calculating with boolean values isn't neccessary since 'and' and 'foo if bar else blub' are working much better so the type coalescing bool - int - float can really go away. Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From stef.mientki at gmail.com Fri Sep 5 16:06:19 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 05 Sep 2008 22:06:19 +0200 Subject: pdb bug and questions In-Reply-To: References: Message-ID: <48C1913B.90705@gmail.com> R. Bernstein wrote: > Stef Mientki writes: > > >> hello, >> >> I'm trying to embed a debugger into an editor. >> I'm only interested in high level debugging. >> The first question is what debugger is the best for my purpose ? >> (pdb, pydb, rpdb2, smart debugger, extended debugger ? >> >> Second question, in none of the above debuggers (except rpdb2), >> I can find a "break now", >> so it seems impossible to me to detect unlimited while loops ? >> > > I am not sure what you mean by "break now". pdb and pydb allow direct > calls from a program to the debugger via set_trace (which in pydb is > deprecated in favor of I think the more descriptive name: debugger) > > But I suspect this is not what you mean to "detect unlimited while > loops"; pydb also has gdb-style signal handling that allows for entry > into the debugger when the debugged python process receives a > particular signal. "info handle" lists all of the interrupts and what > action is to be taken on each. See > http://bashdb.sourceforge.net/pydb/pydb/lib/node38.html > > However I believe that signals are only handled by the main thread; so > if that's blocked, the python process won't see the signal. > Thanks, Yes, I think the trace option can do the job, certainly if I display every line. Didn't know pdb had something like settrace ( the information on pdb is very condensed ;-) > >> For the moment I started with pdb, because most of the debuggers seems >> to be an extension on pdb. >> When I launch the debugger ( winXP, Python 2.5) from with my editor >> python -u -m pdb D:\\Data\\test_IDE.py >> I get this error >> IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') >> NOTICE 1 backslash ----------------------------------^ >> >> If I launch the debugger with >> python -u -m pdb D:/Data/test_IDE.py >> It runs fine. >> >> This looks like a bug to me. >> What's the best way to report these kind of bugs ? >> > > winpdb, pydb and pdb (part of Python) all have Sourceforge projects > which have bug trackers. For pdb, in the past people includng myself, > have reported features, patches and bugs in the Python tracker; > eventually it gets handled. (Eventually in my case means a year or > so.) But if my information is incorrect or out of date, no doubt > someone will correct me. > I'll take a look, for the sake of our children ;-) > As mentioned in the last paragraph, pydb also is a Sourceforge project > (part of bashdb) which has a tracker for bug reporting. Using the bug > tracker I think is better than discussing pydb bugs in c.l.p. c.l.p. ? > By > extension, I assume the same is also true for the other debuggers. > > Finally, I think rpdb2 is part of the winpdb project on Sourceforge > and again has a bug tracker. My sense is that Nir Aides is very good > about handling bugs reported in winpdb/rpdb. > Yes I started with rpdb2, and indeed Nir Aides is very helpfull, but I think interfaceing rpdb2 is a little too difficult for me, but I'll certainly add winpdb as the option for external debugging. For now I think pydb is the choice, better control and more functions than pdb, and almost just as easy. cheers, Stef > >> Although I mostly use os.path.join to be OS independent, >> these kind of bugs give me the impression, >> that I can better do the join myself and always use forward slashes. >> Is this a valid conclusion ? >> >> thanks, >> Stef Mientki >> > -- > http://mail.python.org/mailman/listinfo/python-list > From marco.bizzarri at gmail.com Wed Sep 10 16:08:17 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 10 Sep 2008 22:08:17 +0200 Subject: Python and Open Office In-Reply-To: References: Message-ID: <3f0d61c40809101308y37c0cb22j55ef033bee6bda99@mail.gmail.com> On Wed, Sep 10, 2008 at 10:04 PM, Greg Lindstrom wrote: > Hello, > > I would like to create and manipulate Open Office documents using Python. I > have found then UNO Python page and odfpy modules which seem to be exactly > what I need. The odfpy manual is, to me, a confusing list of objects and > methods (it's an impressive list!), but does not have much in the way of how > to use them. For example, I can open a spreadsheet and create new pages > (there's a nice example near the back of the manual) but I can't figure out > how to open an existing spreadsheet and list the names of the individual > sheets ("tabs"). > > I have written an application that access Microsoft Excel and creates > reports for work, but would like to create an Open Source version using Open > Office and release it to the community (and maybe get a talk at PyCon :-). > > Is there someone here who can help me out, or is there an appropriate > mailing list for me to join? Ciao, Greg. you should check with the openoffice.org mailing list; I think what you are looking for is the api mailing list for openoffice; you could try to get the OpenOffice.org developers guide and the SDK, and check it (but it is not a little work) Regards Marco > Thanks > > --greg > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From dudeja.rajat at gmail.com Mon Sep 8 07:23:05 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 8 Sep 2008 12:23:05 +0100 Subject: Unable to start a process with subprocess Popen() In-Reply-To: References: Message-ID: On Mon, Sep 8, 2008 at 11:50 AM, wrote: > Hi, > > I'm using the subprocess module's Popen() to start a batch file. This > batch file basically calls an exe which also gets started. > Unfortunately, this does not produce any results. I looked into the > Task bar that this exe has started but it does not consume and cpu so > I believet that this exe is not working. > > > I used the following command to start the batch fiile: > > testing = subprocess.Popen([batchFilePath], \ > shell = True, \ > stdout = subprocess.PIPE, \ > stderr = subprocess.PIPE).communicate()[0] > > > batchFilePath is the path of the batch file. > > > > -- > Regrads, > Rajat > Ok, I re-phrase my question: there is a batch file that executes a exe file. The batch just works if run from command prompt and produces output to standard output and the file. Now, I try to call the same batch file from subprocess.Pope() call. The batch file gets called and that internally also calls the exe file. But, the exe just runs forever i.e. hangs and does not produces output , atleast not to the file. Please suggest is there is something wrong with the above code. Regards, Rajat From dudeja.rajat at gmail.com Mon Sep 1 04:23:41 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 1 Sep 2008 09:23:41 +0100 Subject: Unable to clear Entry subwidget of Tix Combo Box Message-ID: Hi, In my combo box taken from Tix, how can I clear the entry subwidget? My case is like this: I have a check button which when made un-ticked should clear the entry from combo box (i. anything selected in combo box previously) I used the following commands: subEntry = self.cbAnalysisLibVersion.subwidget("entry") subEntry.delete(0,END) But this is not working. Please help. Thanks and regards, Rajat From dmitry at makovey.net Wed Sep 24 23:45:31 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 03:45:31 GMT Subject: is decorator the right thing to use? References: Message-ID: Aaron "Castironpi" Brady wrote: > It might help to tell us the order of events that you want in your > program. You're not using 'mymethod' or 'mymethod2', and you probably > want 'return fnew' for the future. Something dynamic with __getattr__ > might work. Any method call to A, that is an A instance, tries to > look up a method of the same name in the B instance it was initialized > with. well 'mymethod' and 'mymethod2' were there just to show that A doesn't function as a pure proxy - it has methods of it's own. See my respnse to Steve - I proxy messages to more than one aggregated object. going over them on __getattr__ to look up methods just doesn't seem to be really efficient to me (I might be wrong though). Decorators seemed to present good opportunity to simplify the code (well except for the decorator function itself :) ), make code bit more "fool-proofed" (and give me the opportunity to test decorators in real life, he-he). So decorators inside of B just identify that those methods will be proxied by A. On one hand from logical standpoint it's kind of weird to tell class that it is going to be proxied by another class, but declaration would be real close to original function definition which helps to identify where is it used. Note that my decorator doesn't change original function - it's a subversion of decorator to a certain degree as I'm just hooking into python machinery to add methods to A upon their declaration in B (or so I think). From bedouglas at earthlink.net Tue Sep 30 16:01:53 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 30 Sep 2008 13:01:53 -0700 Subject: pyhton or json, list or array? Message-ID: <349401c92337$62e68de0$0301a8c0@tmesa.com> hi... sorry to ask such a trivial issue/question... i have the following snip of code, and i'm trying to determine if i'm dealing with a python list of lists, or a javascript/json array. i was told that it's json, but i have no idea how to convert it/manipulate it.. the "aaa" data is derived from the usc course data web site. basically, i'm trying to figure out how to actually parse the data in the array... thanks ========================================== #!/usr/bin/python # # usc.py # # test the list/lists using simplejson # ######################################################################3 #test python script import re import libxml2dom import urllib import urllib2 import sys, string from mechanize import Browser import mechanize #import tidy import os.path import cookielib from libxml2dom import Node from libxml2dom import NodeList import subprocess import MySQLdb #import mysql_config import time import simplejson as json # # test data from the usc.edu website # aaa='{"schd_sync_dtm":"9\/29\/2008 6:43:56 PM","Dept_Info":{"department":"Accounting","abbreviation":"ACCT","phone_numb er":" - ","address":{},"ugrad_dclass_phone_number":"740-4838","ugrad_dclass_address" :"ACC 101","grad_dclass_phone_number":"740-4838","grad_dclass_address":"ACC 101","Notes":"BUSINESS (UNDERGRADUATE) - Non-admitted (pre-business, undeclared, etc.) students may take courses subject to the following limitations: (1) must have completed at least 28 units; (2) no more than three business courses overall at USC; (3) prerequisites completed. BUSINESS (GRADUATE) - Business students may register using USC Web Registration. - Non-business students may register for graduate business electives subject to the following restrictions: (1) proof of undergraduate degree; (2) minimum graduate GPA of 3.2; (3) maximum of 12 units of graduate business courses; and (4) prerequisites completed. All graduate applications and forms are available in BRI 207, (213) 740-5424, email: registration at marshall.usc.edu. For complete list of Business registration policies, please visit www.marshall.usc.edu\/registrationpolicies.","TermNotes":{},"dept_url":"http :\/\/www.marshall.usc.edu\/lsoa\/"},"OfferedCourses":{"course":[{"IsCrossLis ted":"N","PublishedCourseID":"ACCT-370A","ScheduledCourseID":"ACCT-370A","Co urseData":{"prefix":"ACCT","number":"370","sequence":"A","suffix":{},"title" :"External Financial Reporting Issues","description":"Understanding of decision-making, problem solving, and research skills as a supplement to financial accounting knowledge for accounting professionals.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14030","session":"431","dcl ass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"48","number_registered":"46","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ti me":"11:50","location":"ACC310","instructor":{"last_name":"Lu","first_name": "Yvonne"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},{ "id":"14031","session":"431","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"38","number_registered":"36","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ti me":"15:50","location":"ACC236","instructor":{"last_name":"Lu","first_name": "Yvonne"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},{ "id":"14032","session":"431","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"45","number_registered":"41","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"16:00","end_ti me":"17:50","location":"JKP104","instructor":{"last_name":"Shames","first_na me":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14034","session":"431","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"135","number_registered":"123","wait_qty":"0","cance led":"N","blackboard":"N","comment":{},"day":"F","start_time":"10:00","end_t ime":"11:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-370B","ScheduledCourseID":"ACCT- 370B","CourseData":{"prefix":"ACCT","number":"370","sequence":"B","suffix":{ },"title":"External Financial Reporting Issues","description":"Continuation of understanding of decision-making, problem solving, and research skills as a supplement to financial accounting knowledge for accounting professionals.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"ACCT-370A","coreq_text":{},"SectionData":[{"id":"14035","session":"4 42","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"48","number_registered":"47","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ti me":"11:50","location":"ACC310","instructor":{"last_name":"Lu","first_name": "Yvonne"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},' aaa=aaa+'{"id":"14036","session":"442","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"38","number_registered":"35","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ti me":"15:50","location":"ACC236","instructor":{"last_name":"Lu","first_name": "Yvonne"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},{ "id":"14037","session":"442","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"45","number_registered":"41","wait_qty":"0","cancele d":"N","blackboard":"N","comment":{},"day":"MW","start_time":"16:00","end_ti me":"17:50","location":"JKP104","instructor":{"last_name":"Shames","first_na me":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14038","session":"442","dclass_code":"D","title":"External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"135","number_registered":"123","wait_qty":"0","cance led":"N","blackboard":{},"comment":{},"day":"F","start_time":"10:00","end_ti me":"11:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-371A","ScheduledCourseID":"ACCT- 371A","CourseData":{"prefix":"ACCT","number":"371","sequence":"A","suffix":{ },"title":"Introduction to Accounting Systems","description":"Understanding of technology used to support accounting professionals in financial and managerial accounting, auditing, and taxation.","units":"2","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14040","session":"431","dcl ass_code":"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"45","number_registered":"30","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"08:00","end_t ime":"09:50","location":"ACC303","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":"application\/pdf","filesize":"170050"}, "IsDistanceLearning":"N"},{"id":"14041","session":"431","dclass_code":"D","t itle":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"46","number_registered":"44","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","end_t ime":"11:50","location":"ACC303","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":"application\/pdf","filesize":"170050"}, "IsDistanceLearning":"N"},{"id":"14042","session":"431","dclass_code":"D","t itle":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"46","number_registered":"45","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_t ime":"13:50","location":"ACC303","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":"application\/pdf","filesize":"170050"}, "IsDistanceLearning":"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT- 371B","ScheduledCourseID":"ACCT-371B","CourseData":{"prefix":"ACCT","number" :"371","sequence":"B","suffix":{},"title":"Introduction to Accounting Systems","description":"Understanding the fundamental processes that capture the corporate data and the controls needed to assure that these processes will operate in an acceptable manner.","units":"2","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": "ACCT-371A","coreq_text":{},"SectionData":[{"id":"14045","session":"442","dc lass_code":"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"44","number_registered":"22","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"08:00","end_t ime":"09:50","location":"HOH421","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"},{"id":"14046","session":"442","dclass_code":"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},' aaa=aaa+'"type":"Lec","units":"2","spaces_available":"45","number_registered ":"45","wait_qty":"2","canceled":"N","blackboard":"Y","comment":{},"day":"TH ","start_time":"10:00","end_time":"11:50","location":"HOH421","instructor":{ "last_name":"Porter","first_name":"Leslie"},"syllabus":{"format":{},"filesiz e":{}},"IsDistanceLearning":"N"},{"id":"14047","session":"442","dclass_code" :"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"2","spaces_available":"45","number_registered":"45","wait_qty":"1","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_t ime":"13:50","location":"HOH421","instructor":{"last_name":"Porter","first_n ame":"Leslie"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"},{"id":"14048","session":"442","dclass_code":"D","title":"Introduction to Accounting Systems","section_title":{},"description":{},"notes":{},"type":"Lab","units" :"0","spaces_available":"120","number_registered":"107","wait_qty":"0","canc eled":"N","blackboard":{},"comment":{},"day":"F","start_time":"12:00","end_t ime":"13:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-372","ScheduledCourseID":"ACCT-3 72","CourseData":{"prefix":"ACCT","number":"372","sequence":{},"suffix":{}," title":"Internal Reporting Issues","description":"Understanding of decision-making, problem solving, and research skills as a supplement to managerial accounting knowledge for accounting professionals.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14050","session":"442","dcl ass_code":"D","title":"Internal Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"44","number_registered":"27","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"08:00","end_ti me":"09:50","location":"HOH421","instructor":{"last_name":"Jackson","first_n ame":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14051","session":"442","dclass_code":"D","title":"Internal Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"47","number_registered":"47","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ti me":"11:50","location":"HOH304","instructor":{"last_name":"Jackson","first_n ame":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14052","session":"442","dclass_code":"D","title":"Internal Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"45","number_registered":"44","wait_qty":"1","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ti me":"15:50","location":"HOH421","instructor":{"last_name":"Jackson","first_n ame":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14053","session":"442","dclass_code":"D","title":"Internal Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"120","number_registered":"116","wait_qty":"0","cance led":"N","blackboard":{},"comment":{},"day":"F","start_time":"12:00","end_ti me":"13:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-373","ScheduledCourseID":"ACCT-3 73","CourseData":{"prefix":"ACCT","number":"373","sequence":{},"suffix":{}," title":"Introduction to Assurance Services","description":"Explores the requisite skills and knowledge needed to offer services in assurance, attestation or auditing engagements.","units":"2","restriction_by_major":{},"restriction_by_class":{ },"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_t ext":"(ACCT-370A and ACCT-371A)","coreq_text":{},"SectionData":[{"id":"14055","session":"431","dc lass_code":"D","title":"Introduction to Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"44","number_registered":"26","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"08:00","end_ time":"09:50","location":"HOH421","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},' aaa=aaa+'{"id":"14056","session":"431","dclass_code":"D","title":"Introducti on to Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"47","number_registered":"46","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ time":"11:50","location":"HOH304","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14057","session":"431","dclass_code":"D","title":"Introduction to Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"45","number_registered":"44","wait_qty":"1","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ time":"15:50","location":"HOH421","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14058","session":"431","dclass_code":"D","title":"Introduction to Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lab","units ":"0","spaces_available":"120","number_registered":"115","wait_qty":"0","can celed":"N","blackboard":{},"comment":{},"day":"F","start_time":"12:00","end_ time":"13:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-374","ScheduledCourseID":"ACCT-3 74","CourseData":{"prefix":"ACCT","number":"374","sequence":{},"suffix":{}," title":"Introduction to Tax Issues","description":"Basic tax principles, introduction to U.S. federal, state and local tax systems, income and expense definitions, property transactions, and fundamentals in individual taxation.","units":"2","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14060","session":"442","dcl ass_code":"D","title":"Introduction to Tax Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"45","number_registered":"30","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"08:00","end_ti me":"09:50","location":"ACC303","instructor":{"last_name":"Swenson","first_n ame":"Charles"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"},{"id":"14061","session":"442","dclass_code":"D","title":"Introduction to Tax Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"46","number_registered":"46","wait_qty":"1","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","end_ti me":"11:50","location":"ACC303","instructor":{"last_name":"Swenson","first_n ame":"Charles"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"},{"id":"14062","session":"442","dclass_code":"D","title":"Introduction to Tax Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"46","number_registered":"45","wait_qty":"1","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_ti me":"13:50","location":"ACC303","instructor":{"last_name":"Swenson","first_n ame":"Charles"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-410","ScheduledCourse ID":"ACCT-410","CourseData":{"prefix":"ACCT","number":"410","sequence":{},"s uffix":"x","title":"Foundations of Accounting","description":"Non-technical presentation of accounting for users of accounting information; introduction to financial and managerial accounting. Not open to students with course credits in accounting. Not available for unit or course credit toward a degree in accounting or business administration.","units":"4","restriction_by_major":{},"restriction_by_class ":{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prere q_text":{},"coreq_text":{},"SectionData":[{"id":"14090","session":"001","dcl ass_code":"R","title":"Foundations of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"40","number_registered":"38","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","en d_time":"11:50","location":"HOH305","instructor":{"last_name":"Bonner","firs t_name":"Sarah","bio_url":"http:\/\/mymarshall.usc.edu\/portal\/subapps\/dig italmeasures\/faculty.jsp?surveyId=48731"},"syllabus":{"format":{},"filesize ":{}},"IsDistanceLearning":"N"},' aaa=aaa+'{"id":"14092","session":"001","dclass_code":"R","title":"Foundation s of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"39","number_registered":"32","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","en d_time":"11:50","location":"ACC236","instructor":{"last_name":"Zhang","first _name":"Jieying"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning ":"N"},{"id":"14094","session":"001","dclass_code":"R","title":"Foundations of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"40","number_registered":"40","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"12:00","en d_time":"13:50","location":"HOH305","instructor":{"last_name":"Bonner","firs t_name":"Sarah","bio_url":"http:\/\/mymarshall.usc.edu\/portal\/subapps\/dig italmeasures\/faculty.jsp?surveyId=48731"},"syllabus":{"format":{},"filesize ":{}},"IsDistanceLearning":"N"},{"id":"14096","session":"001","dclass_code": "R","title":"Foundations of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"39","number_registered":"30","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"16:00","en d_time":"17:50","location":"ACC236","instructor":{"last_name":"Zhang","first _name":"Jieying"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning ":"N"},{"id":"14098","session":"001","dclass_code":"R","title":"Foundations of Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"40","number_registered":"40","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00","en d_time":"15:50","location":"ACC236","instructor":{"last_name":"Zhang","first _name":"Jieying"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning ":"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-411","ScheduledCour seID":"ACCT-411","CourseData":{"prefix":"ACCT","number":"411","sequence":{}, "suffix":"x","title":"Understanding Financial Reporting","description":"Understanding of financial statements and insight into the implications of the disclosure requirements. Not available for credit to accounting or business majors.","units":"2","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": "ACCT-410","coreq_text":{},"SectionData":{"id":"14006","session":"431","dcla ss_code":"D","title":"Understanding Financial Reporting","section_title":{},"description":{},"notes":{},"type":"Lec","unit s":"2","spaces_available":"1","number_registered":"0","wait_qty":"0","cancel ed":"Y","blackboard":{},"comment":{},"day":"MW","start_time":"12:00","end_ti me":"13:50","location":{},"syllabus":{"format":{},"filesize":{}},"IsDistance Learning":"N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-412","Schedu ledCourseID":"ACCT-412","CourseData":{"prefix":"ACCT","number":"412","sequen ce":{},"suffix":"x","title":"Special Financial Reporting Issues","description":"Analysis of contemporary financial reporting and disclosure issues. Includes topics such as accounting for stock options and income tax, off-balance sheet financing, hedging and derivatives. Not available for credit to accounting and business majors. Open to accounting majors only.","units":"2","restriction_by_major":" Registration open to the following major(s): Accounting","restriction_by_class":{},"restriction_by_school":{},"CourseNote s":{},"CourseTermNotes":{},"prereq_text":"ACCT-411","coreq_text":{},"Section Data":{"id":"14010","session":"442","dclass_code":"D","title":"Special Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"1","number_registered":"0","wait_qty":"0","canceled" :"Y","blackboard":{},"comment":{},"day":"MW","start_time":"00:00","end_time" :"13:50","location":{},"syllabus":{"format":{},"filesize":{}},"IsDistanceLea rning":"N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-415","Scheduled CourseID":"ACCT-415","CourseData":{"prefix":"ACCT","number":"415","sequence" :{},' aaa=aaa+'"suffix":"x","title":"Intermediate Financial Accounting for Non-Accounting Majors","description":"In-depth study of balance sheet, income statement, and cash flow statement issued from the perspective of a user (not preparer) of corporate financial reports. Not open to accounting majors. Not available for degree credit to accounting majors.","units":"4","restriction_by_major":" Registration closed to the following major(s): Accounting","restriction_by_class":{},"restriction_by_school":{},"CourseNote s":{},"CourseTermNotes":{},"prereq_text":"1 from (BUAD-250B or BUAD-305)","coreq_text":{},"SectionData":[{"id":"14100","session":"001","dcl ass_code":"R","title":"Intermediate Financial Accounting for Non-Accounting Majors","section_title":{},"description":{},"notes":{},"type":"Lec","units": "4","spaces_available":"54","number_registered":"48","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"12:00","end_ti me":"13:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14102","session":"001","dclass_code":"R","title":"Intermediate Financial Accounting for Non-Accounting Majors","section_title":{},"description":{},"notes":{},"type":"Lec","units": "4","spaces_available":"39","number_registered":"23","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"16:00","end_ti me":"17:50","location":"ACC236","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-463","ScheduledCours eID":"ACCT-463","CourseData":{"prefix":"ACCT","number":"463","sequence":{}," suffix":{},"title":"Internal Audit","description":"Examination of internal audit\/auditors and their relationship to management, the investors, the regulators, and the external auditors.","units":"2","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":"(ACCT-370B and ACCT-373)","coreq_text":{},"SectionData":{"id":"14186","session":"442","dcla ss_code":"D","title":"Internal Audit","section_title":{},"description":{},"notes":{},"type":"Lec","units":" 2","spaces_available":"35","number_registered":"21","wait_qty":"0","canceled ":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"08:00","end_tim e":"09:50","location":"ACC236","instructor":{"last_name":"Layton","first_nam e":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}} },{"IsCrossListed":"N","PublishedCourseID":"ACCT-470A","ScheduledCourseID":" ACCT-470A","CourseData":{"prefix":"ACCT","number":"470","sequence":"A","suff ix":{},"title":"Advanced External Financial Reporting Issues","description":"Developing capabilities to identify and articulate current external financial reporting problems and issues, concentrating on operating, financing and investing activities of business organizations.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"ACCT-370B","coreq_text":{},"SectionData":[{"id":"14115","session":"4 31","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"51","number_registered":"49","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_ti me":"13:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14116","session":"431","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"50","number_registered":"33","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00","end_ti me":"15:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14118","session":"431","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"100","number_registered":"82","wait_qty":"0","cancel ed":"N","blackboard":{},"comment":{},"day":"F","start_time":"14:00","end_tim e":"15:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},' aaa=aaa+'{"IsCrossListed":"N","PublishedCourseID":"ACCT-470B","ScheduledCour seID":"ACCT-470B","CourseData":{"prefix":"ACCT","number":"470","sequence":"B ","suffix":{},"title":"Advanced External Financial Reporting Issues","description":"Developing capabilities to identify and articulate current external financial reporting problems and issues, concentrating on operating, financing and investing activities of business organizations.","units":"2","restriction_by_major":{},"restriction_by_class" :{},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq _text":"ACCT-470A","coreq_text":{},"SectionData":[{"id":"14120","session":"4 42","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"50","number_registered":"42","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","end_ti me":"13:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14121","session":"442","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"50","number_registered":"30","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00","end_ti me":"15:50","location":"ACC310","instructor":{"last_name":"Simmonds","first_ name":"Kendall"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14123","session":"442","dclass_code":"D","title":"Advanced External Financial Reporting Issues","section_title":{},"description":{},"notes":{},"type":"Lab","units": "0","spaces_available":"100","number_registered":"72","wait_qty":"0","cancel ed":"N","blackboard":{},"comment":{},"day":"F","start_time":"14:00","end_tim e":"15:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-472","ScheduledCourseID":"ACCT-4 72","CourseData":{"prefix":"ACCT","number":"472","sequence":{},"suffix":{}," title":"Managerial Accounting","description":"Understanding of systems providing cost information useful in management decision-making and problem solving.","units":"2","restriction_by_major":{},"restriction_by_class":{},"r estriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text" :"ACCT-372","coreq_text":{},"SectionData":{"id":"14130","session":"431","dcl ass_code":"D","title":"Managerial Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"2","spaces_available":"35","number_registered":"27","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","en d_time":"11:50","location":"BRI8","instructor":{"last_name":"Jackson","first _name":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-473","ScheduledCourseI D":"ACCT-473","CourseData":{"prefix":"ACCT","number":"473","sequence":{},"su ffix":{},"title":"Financial Statement Auditing","description":"Course builds on the background developed in ACCT 373, specifically the process used by external auditors to conduct financial statement audits.","units":"2","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": "(ACCT-371B and ACCT-373)","coreq_text":{},"SectionData":[{"id":"14135","session":"442","dcl ass_code":"D","title":"Financial Statement Auditing","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"39","number_registered":"29","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ time":"11:50","location":"HOH301","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14136","session":"442","dclass_code":"D","title":"Financial Statement Auditing","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"32","number_registered":"24","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ time":"15:50","location":"HOH306","instructor":{"last_name":"Layton","first_ name":"Rose"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "},{"id":"14137","session":"442","dclass_code":"D","title":"Financial Statement Auditing","section_title":{},"description":{},"notes":{},"type":"Lab","units ":"0",' aaa=aaa+'"spaces_available":"78","number_registered":"53","wait_qty":"0","ca nceled":"N","blackboard":{},"comment":{},"day":"F","start_time":"12:00","end _time":"13:50","location":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-474","ScheduledCourseID":"ACCT-4 74","CourseData":{"prefix":"ACCT","number":"474","sequence":{},"suffix":{},t itle":"Tax Issues for Business","description":"Capabilities to identify and articulate tax issues related to a business entity s life: formation, investing, financing and operations, and change of form.","units":"2","restriction_by_major":{},"restriction_by_class":{},"rest riction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text":"A CCT-374","coreq_text":{},' aaa=aaa+'"SectionData":[{"id":"14140","session":"431","dclass_code":"D","tit le":"Tax Issues for Business","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"39","number_registered":"21","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"10:00","end_ time":"11:50","location":"HOH301","instructor":{"last_name":"Scharlach","fir st_name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearnin g":"N"},' aaa=aaa+'{"id":"14141","session":"431","dclass_code":"D","title":"Tax Issues for Business","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2","spaces_available":"32","number_registered":"17","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","end_ time":"15:50","location":"HOH306","instructor":{"last_name":"Scharlach","fir st_name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearnin g":"N"},{"id":"14142","session":"431","dclass_code":"D","title":"Tax Issues for Business","section_title":{},"description":{},"notes":{},"type":"Lab","units ":"0","spaces_available":"100",' aaa=aaa+'"number_registered":"38","wait_qty":"0","canceled":"N","blackboard" :{},"comment":{},"day":"F","start_time":"14:00","end_time":"15:50","location ":"HOH EDI","syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"I sCrossListed":"N","PublishedCourseID":"ACCT-476","ScheduledCourseID":"ACCT-4 76","CourseData":{"prefix":"ACCT","number":"476","sequence":{},"suffix":{}," title":"Performance Measurement Issues","description":"Introduction to understanding how management control systems can enhance achievement of the organization\'s objectives and strategies.","units":"2","restriction_by_major":{},"restriction_by_class":{} ,"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_te xt":"ACCT-372","coreq_text":{},"SectionData":{"id":"14150","session":"442"," dclass_code":"D","title":"Performance Measurement Issues","section_title":{},"description":{},"notes":{},"type":"Lec","units": "2","spaces_available":"35","number_registered":"17","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"10:00","end_ti me":"11:50","location":"BRI8","instructor":{"last_name":"Jackson","first_nam e":"Cecil"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"} }},{"IsCrossListed":"N","PublishedCourseID":"ACCT-478","ScheduledCourseID":" ACCT-478","CourseData":{"prefix":"ACCT","number":"478","sequence":{},"suffix ":{},"title":"Accounting Systems Design","description":"Explores the design of accounting systems. Introduction to tools and techniques for analyzing and designing accounting systems with an emphasis on system controls and reporting.","units":"4","restriction_by_major":{},"restriction_by_class":{}, "restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_tex t":"ACCT-371B","coreq_text":{},"SectionData":{"id":"14160","session":"001"," dclass_code":"D","title":"Accounting Systems Design","section_title":{},"description":{},"notes":{},"type":"Lec","units": "4","spaces_available":"35","number_registered":"10","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00","end_ti me":"15:50","location":"BRI8","instructor":{"last_name":"Kiddoo","first_name ":"Bob"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}}}, {"IsCrossListed":"N","PublishedCourseID":"ACCT-479","ScheduledCourseID":"ACC T-479","CourseData":{"prefix":"ACCT","number":"479","sequence":{},"suffix":{ },"title":"Accounting Systems Development","description":"Examines the fundamentals of accounting systems development. Introduction to the concepts of implementation and support, with emphasis on system quality assurance, evaluation and attestation.","units":"4","restriction_by_major":{},"restriction_by_class":{ },' aaa=aaa+'"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"p rereq_text":"ACCT-478","coreq_text":{},"SectionData":{"id":"14165","session" :"001","dclass_code":"D","title":"Accounting Systems Development","section_title":{},"description":{},"notes":{},"type":"Lec","un its":"4","spaces_available":"30","number_registered":"6","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:00","en d_time":"13:50","location":"HOH305","instructor":{"last_name":"Kiddoo","firs t_name":"Bob"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-490","ScheduledCourseID ":"ACCT-490","CourseData":{"prefix":"ACCT","number":"490","sequence":{},"suf fix":"x","title":"Directed Research","description":"Individual research and readings. Not available for graduate credit.","units":"2-8, 8","restriction_by_major":{},"restriction_by_class":{},"restriction_by_schoo l":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text":{},"coreq_text":{} ,"SectionData":{"id":"14180","session":"001","dclass_code":"D","title":"Dire cted Research","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"2-8","spaces_available":"10","number_registered":"0","wait_qty":"0","canc eled":"N","blackboard":"N","comment":{},"day":{},"start_time":"TBA","end_tim e":"TBA","location":"OFFICE","instructor":{"last_name":"Beatty","first_name" :"Randolph"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-509","ScheduledCourseID": "ACCT-509","CourseData":{"prefix":"ACCT","number":"509","sequence":{},"suffi x":{},"title":"Concepts of Financial and Management Accounting","description":"Introduction to the concepts of financial and managerial accounting. The course will provide coverage of key concepts needed by managers of businesses in order to communicate information important in decision-making. (Duplicates credit in GSBA 510, GSBA 518, GSBA 536.) Not open to business majors.","units":"4","restriction_by_major":" Registration closed to the following major(s): Business Administration, Business Administration (Cinema-Television), Business Administration (East Asian Studies), Business Administration (International Relations), Business Administration, Business Administration\/East Asian Area Studies, Business Administration\/Jewish Communal Service, Gerontology\/Business Administration, Business Administration\/Industrial & Systems Engineering, Nursing\/Business Administration, Business Administration\/Planning, Business Administration\/Real Estate Development, Business Administration\/Dental Surgery, Juris Doctor\/Business Administration, Medicine\/Business Administration, Business Administration\/Pharmacy","restriction_by_class":{},"restriction_by_school": {},"CourseNotes":{},"CourseTermNotes":{},"prereq_text":{},"coreq_text":{},"S ectionData":{"id":"14188","session":"036","dclass_code":"R","title":"Concept s of Financial and Management Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"4","spaces_available":"50","number_registered":"12","wait_qty":"0","can celed":"N","blackboard":"Y","comment":{},"day":{},"start_time":"TBA","end_ti me":"TBA","location":"ONLINE","instructor":{"last_name":"Hopkins","first_nam e":"Merle"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"} }},{"IsCrossListed":"N","PublishedCourseID":"ACCT-546","ScheduledCourseID":" ACCT-546","CourseData":{"prefix":"ACCT","number":"546","sequence":{},"suffix ":{},"title":"Assurance Services","description":"Concepts and principles governing independent professional services that provide assurance on the reliability and relevance of information, including financial statement information. Topics include demand and supply issues for these services, basic principles of evidence, risk assessment and testing.","units":"3","restriction_by_major":{},"restriction_by_class":{},"r estriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text" :"ACCT-525","coreq_text":{},"SectionData":{"id":"14206","session":"001","dcl ass_code":"R","title":"Assurance Services","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"3","spaces_available":"54","number_registered":"50","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"08:00","end_ time":"09:20","location":"JKP202","instructor":{"last_name":"Owens","first_n ame":"John"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-547","ScheduledCourseID": "ACCT-547",' aaa=aaa+'"CourseData":{"prefix":"ACCT","number":"547","sequence":{},"suffix" :{},"title":"Enterprise Information Systems","description":"Focuses on accounting enterprise database models and information technology required to support those systems. Includes analysis and design of interfunctional process flows through reengineering to exploit technology capabilities.","units":"3","restriction_by_major":{},"restriction_by_class": {},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_ text":{},"coreq_text":{},"SectionData":{"id":"14208","session":"001","dclass _code":"R","title":"Enterprise Information Systems","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"50","number_registered":"48","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"15:30","end_t ime":"16:50","location":"JKP202","instructor":[{"last_name":"O\'Leary","firs t_name":"Daniel"},{"last_name":"Maxey","first_name":"Shirley"}],"syllabus":{ "format":{},"filesize":{}},"IsDistanceLearning":"N"}}},{"IsCrossListed":"N", "PublishedCourseID":"ACCT-549","ScheduledCourseID":"ACCT-549","CourseData":{ "prefix":"ACCT","number":"549","sequence":{},"suffix":{},"title":"Advanced Enterprise Systems and Technologies","description":"Design, control and development of advanced enterprise systems, using reengineering, focusing on accounting and financial systems, using a wide range of emerging existing technologies. Recommended preparation: ACCT 547.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Business Administration, Nursing\/Business Administration, Business Administration\/Dental Surgery, Information and Operations Management, Business Administration\/East Asian Area Studies, Medicine\/Business Administration, Business Administration\/Jewish Communal Service, Business Administration\/Planning, Business Administration\/Real Estate Development","restriction_by_class":{},"restriction_by_school":{},"CourseNot es":{},"CourseTermNotes":{},"prereq_text":{},"coreq_text":{},"SectionData":[ {"id":"14214","session":"001","dclass_code":"R","title":"Advanced Enterprise Systems and Technologies","section_title":{},"description":"Section 14214 - For MAcc\/MBT student ONLY Section 14215 - For MBA students ONLY","notes":{},"type":"Lec","units":"3","spaces_available":"36","number_re gistered":"28","wait_qty":"0","canceled":"N","blackboard":"Y","comment":{}," day":"TH","start_time":"11:00","end_time":"12:20","location":"JKP104","instr uctor":[{"last_name":"O\'Leary","first_name":"Daniel"},{"last_name":"Maxey", "first_name":"Shirley"}],"syllabus":{"format":{},"filesize":{}},"IsDistanceL earning":"N"},{"id":"14215","session":"033","dclass_code":"R","title":"Advan ced Enterprise Systems and Technologies","section_title":{},"description":"This section (14215) is for MBA students only. Graduate accounting students must register for ACCT-549, section 14214.","notes":{},"type":"Lec","units":"3","spaces_available":"20","number_ registered":"0","wait_qty":"0","canceled":"N","blackboard":"Y","comment":{}, "day":"TH","start_time":"11:00","end_time":"12:20","location":"JKP104","inst ructor":{"last_name":"O\'Leary","first_name":"Daniel"},"syllabus":{"format": {},"filesize":{}},"IsDistanceLearning":"N"}]}},{"IsCrossListed":"N","Publish edCourseID":"ACCT-550T","ScheduledCourseID":"ACCT-550T","CourseData":{"prefi x":"ACCT","number":"550","sequence":"T","suffix":{},"title":"Tax Research and Practice","description":"Tax law research methods; interpreting statutes, cases, and rulings; communicating research results; administration and professional responsibilities of tax practice. Recommended preparation: introductory tax course.","units":"3","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": {},"coreq_text":{},"SectionData":{"id":"14216","session":"431","dclass_code" :"D","title":"Tax Research and Practice","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"3","spaces_available":"54","number_registered":"55","wait_qty":"0","cance led":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"09:30","end_ time":"12:20","location":"JKP202","instructor":{"last_name":"Mills","first_n ame":"Patricia"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-551T","ScheduledCours eID":"ACCT-551T","CourseData":{"prefix":"ACCT","number":"551","sequence":"T" ,"suffix":{},"title":"Taxation of Partnerships and S-Corps",' aaa=aaa+'"description":"Federal taxation of flow-through entities, including: partnerships, S corporations, limited liability partnerships (LLPs), and limited liability companies (LLCs).","units":"3","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": "1 from (ACCT-550T or ACCT-560T or LAW-600)","coreq_text":{},"SectionData":[{"id":"14220","session":"001","dcla ss_code":"R","title":"Taxation of Partnerships and S-Corps","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"41","number_registered":"33","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"T","start_time":"18:30","end_ti me":"21:30","location":"BRI202","instructor":{"last_name":"Mills","first_nam e":"Patricia"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"},{"id":"14221","session":"442","dclass_code":"D","title":"Taxation of Partnerships and S-Corps","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"54","number_registered":"55","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"09:30","end_t ime":"12:20","location":"JKP202","instructor":{"last_name":"Mills","first_na me":"Patricia"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-560T","ScheduledCours eID":"ACCT-560T","CourseData":{"prefix":"ACCT","number":"560","sequence":"T" ,"suffix":{},"title":"Tax Theory and Its Business Applications","description":"Taxation and its relationship to business and investment decisions; the effects of taxation on business organization, capital structure, policies, operation, and expansion. Recommended preparation: introductory tax course.","units":"3","restriction_by_major":{},"restriction_by_class":{},"re striction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text": {},"coreq_text":{},"SectionData":[{"id":"14230","session":"001","dclass_code ":"R","title":"Tax Theory and Its Business Applications","section_title":{},"description":"Section 14231 meets 8\/25 - 10\/15 Last day to add\/drop without a W is 9\/2","notes":{},"type":"Lec","units":"3","spaces_available":"54","number_re gistered":"55","wait_qty":"0","canceled":"N","blackboard":"Y","comment":{}," day":"W","start_time":"18:30","end_time":"21:30","location":"JKP202","instru ctor":[{"last_name":"Barcal","first_name":"Jack"},{"last_name":"Maxey","firs t_name":"Shirley"}],"syllabus":{"format":{},"filesize":{}},"IsDistanceLearni ng":"N"},{"id":"14231","session":"431","dclass_code":"D","title":"Tax Theory and Its Business Applications","section_title":{},"description":{},"notes":{},"type":"Lec","u nits":"3","spaces_available":"54","number_registered":"55","wait_qty":"0","c anceled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"09:30"," end_time":"12:20","location":"JKP202","instructor":[{"last_name":"Barcal","f irst_name":"Jack"},{"last_name":"Maxey","first_name":"Shirley"}],"syllabus": {"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"IsCrossListed":"N ","PublishedCourseID":"ACCT-561T","ScheduledCourseID":"ACCT-561T","CourseDat a":{"prefix":"ACCT","number":"561","sequence":"T","suffix":{},"title":"Incom e Tax of Corporations and Their Shareholders","description":"Concepts and principles governing the taxation of corporations and their shareholders; the effect of taxes on corporate formation, capital structure, distributions, and liquidations.","units":"3","restriction_by_major":{},"restriction_by_class": {},"restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_ text":"1 from (ACCT-550T or ACCT-560T or LAW-600)","coreq_text":{},"SectionData":{"id":"14234","session":"442","dclas s_code":"D","title":"Income Tax of Corporations and Their Shareholders","section_title":{},"description":{},"notes":{},"type":"Lec","u nits":"3","spaces_available":"54","number_registered":"55","wait_qty":"0","c anceled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"09:30"," end_time":"12:20","location":"JKP202","instructor":{"last_name":"Keller","fi rst_name":"Joseph"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearni ng":"N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-568T","ScheduledCo urseID":"ACCT-568T","CourseData":{"prefix":"ACCT","number":"568","sequence": "T","suffix":{},"title":"Taxation of Foreign Business Operations","description":"Taxation of foreign income of U.S. citizens and corporations and of U.S. source income of foreign persons and corporations; planning for organization of foreign operations under the tax laws.","units":"3",' aaa=aaa+'"restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Law","restriction_by_class":{},"restriction_by_school":{},"CourseNotes":{}," CourseTermNotes":{},"prereq_text":"ACCT-561T","coreq_text":{},"SectionData": {"id":"14246","session":"001","dclass_code":"D","title":"Taxation of Foreign Business Operations","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"3","spaces_available":"1","number_registered":"0","wait_qty":"0","cance led":"Y","blackboard":"Y","comment":{},"day":"H","start_time":"18:30","end_t ime":"21:30","location":{},"instructor":{"last_name":"Sylvester","first_name ":"Michael"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-572","ScheduledCourseID": "ACCT-572","CourseData":{"prefix":"ACCT","number":"572","sequence":{},"suffi x":{},"title":"Corporate Accounting and Reporting","description":"A study of financial reporting and disclosure issues with an emphasis on the use of corporate financial statements and their accompanying footnotes. Not open to students with credit in equivalent subjects.","units":"3","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":"GSBA-510","coreq_text":{},"SectionData":[{"id":"14254","session":"033","d class_code":"R","title":"Corporate Accounting and Reporting","section_title":{},"description":{},"notes":{},"type":"Lec","unit s":"3","spaces_available":"56","number_registered":"51","wait_qty":"0","canc eled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"09:30","end _time":"10:50","location":"JKP104","instructor":{"last_name":"Trezevant","fi rst_name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearni ng":"N"},{"id":"14256","session":"033","dclass_code":"R","title":"Corporate Accounting and Reporting","section_title":{},"description":{},"notes":{},"type":"Lec","unit s":"3","spaces_available":"39","number_registered":"36","wait_qty":"0","canc eled":"N","blackboard":"Y","comment":{},"day":"M","start_time":"18:30","end_ time":"21:30","location":"ACC236","instructor":{"last_name":"Trezevant","fir st_name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearnin g":"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-574","ScheduledCou rseID":"ACCT-574","CourseData":{"prefix":"ACCT","number":"574","sequence":{} ,"suffix":{},"title":"Accounting in the Global Business Environment","description":"Study of national and international accounting and business issues; global capital market changes; international accounting and business topics; cases and studies of specific business entities and countries.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Business Administration, Law, Juris Doctor\/Business Administration, Business Administration\/Industrial & Systems Engineering, Business Administration\/Pharmacy, Gerontology\/Business Administration, Nursing\/Business Administration, Business Administration\/Dental Surgery, Information and Operations Management, Business Administration\/East Asian Area Studies, Medicine\/Business Administration, Business Administration\/Jewish Communal Service, Business Administration\/Planning, Business Administration\/Real Estate Development","restriction_by_class":{},"restriction_by_school":{},"CourseNot es":{},"CourseTermNotes":{},"prereq_text":"1 from (GSBA-510 or GSBA-518 or GSBA-536)","coreq_text":{},"SectionData":[{"id":"14260","session":"001","dcl ass_code":"D","title":"Accounting in the Global Business Environment","section_title":{},"description":{},"notes":{},"type":"Lec","un its":"3","spaces_available":"42","number_registered":"30","wait_qty":"0","ca nceled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"14:00","e nd_time":"15:20","location":"JKP202","instructor":{"last_name":"Hung","first _name":"Mingyi"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"},{"id":"14261","session":"001","dclass_code":"D","title":"Accounting in the Global Business Environment","section_title":{},"description":{},"notes":{},"type":"Lec","un its":"3","spaces_available":"42","number_registered":"42","wait_qty":"0","ca nceled":"N","blackboard":"Y","comment":{},"day":"MW","start_time":"12:30","e nd_time":"13:50","location":"JKP202","instructor":{"last_name":"Hung","first _name":"Mingyi"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning" :"N"}]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-578T","ScheduledCour seID":"ACCT-578T","CourseData":{"prefix":"ACCT","number":"578",' aaa=aaa+'"sequence":"T","suffix":{},"title":"Advanced Corporate Taxation","description":"Analysis of corporate divisions and reorganizations, carryovers, and other advanced topics in corporate taxation.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Law","restriction_by_class":{},"restriction_by_school":{},"CourseNotes":{}," CourseTermNotes":{},"prereq_text":"ACCT-561T","coreq_text":{},"SectionData": {"id":"14268","session":"001","dclass_code":"R","title":"Advanced Corporate Taxation","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"3","spaces_available":"34","number_registered":"9","wait_qty":"0","cancel ed":"N","blackboard":"Y","comment":{},"day":"H","start_time":"18:30","end_ti me":"21:30","location":"BRI202","instructor":{"last_name":"Keller","first_na me":"Joseph"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N "}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-580T","ScheduledCourseID ":"ACCT-580T","CourseData":{"prefix":"ACCT","number":"580","sequence":"T","s uffix":{},"title":"Accounting Methods","description":"An analysis of Subchapter E and related provisions of the Internal Revenue Code and of the relationships between tax and financial accounting.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Law","restriction_by_class":{},"restriction_by_school":{},"CourseNotes":{}," CourseTermNotes":{},"prereq_text":"ACCT-550T and 1 from (ACCT-560T or LAW-600)","coreq_text":{},"SectionData":[{"id":"14273","session":"001","dcla ss_code":"R","title":"Accounting Methods","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"35","number_registered":"8","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"W","start_time":"18:30","end_tim e":"21:30","location":"BRI202","instructor":{"last_name":"Scharlach","first_ name":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning": "N"},{"id":"14274","session":"001","dclass_code":"R","title":"Accounting Methods","section_title":{},"description":{},"notes":{},"type":"Lec","units" :"3","spaces_available":"25","number_registered":"1","wait_qty":"0","cancele d":"N","blackboard":"Y","comment":{},"day":"W","start_time":"18:30","end_tim e":"21:30","location":"OCC","instructor":{"last_name":"Scharlach","first_nam e":"Robert"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }]}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-582","ScheduledCourseID" :"ACCT-582","CourseData":{"prefix":"ACCT","number":"582","sequence":{},"suff ix":{},"title":"Accounting for Mergers and Acquisitions","description":"Theoretical and practical problems in accounting for business combinations: purchase and pooling-of-interests accounting; consolidated financial statements; income tax considerations; Intrnational Accounting Standards.","units":"3","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Business Administration","restriction_by_class":{},"restriction_by_school":{},"Course Notes":{},"CourseTermNotes":{},"prereq_text":"GSBA-510","coreq_text":{},"Sec tionData":[{"id":"14288","session":"001","dclass_code":"D","title":"Accounti ng for Mergers and Acquisitions","section_title":{},"description":{},"notes":{},"type":"Lec","u nits":"3","spaces_available":"41","number_registered":"36","wait_qty":"0","c anceled":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"12:30"," end_time":"13:50","location":"JKP202","instructor":[{"last_name":"Trezevant" ,"first_name":"Robert"},{"last_name":"Wang","first_name":"Shiing-Wu"}],"syll abus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"},{"id":"14289","s ession":"001","dclass_code":"D","title":"Accounting for Mergers and Acquisitions","section_title":{},"description":{},"notes":{},"type":"Lec","u nits":"3","spaces_available":"40","number_registered":"34","wait_qty":"0","c anceled":"N","blackboard":"Y","comment":{},"day":"TH","start_time":"14:00"," end_time":"15:20","location":"JKP202","instructor":[{"last_name":"Trezevant" ,"first_name":"Robert"},{"last_name":"Wang","first_name":"Shiing-Wu"}],"syll abus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}]}},{"IsCrossList ed":"N","PublishedCourseID":"ACCT-583","ScheduledCourseID":"ACCT-583","Cours eData":{"prefix":"ACCT","number":"583","sequence":{},"suffix":{},' aaa=aaa+'"title":"Accounting for Income Taxes","description":"Examination of the roles of auditors, tax professionals and corporate financial personnel in preparing, analyzing and reviewing the accrual of income taxes in financial statements. Open to M.B.T., M.Acc. and M.B.A. students only.","units":"3","restriction_by_major":" Registration open to the following major(s): Business Taxation, Accounting, Business Administration","restriction_by_class":{},"restriction_by_school":{},"Course Notes":{},"CourseTermNotes":{},"prereq_text":"(ACCT-544 and ACCT-572)","coreq_text":{},"SectionData":{"id":"14290","session":"001","dcla ss_code":"R","title":"Accounting for Income Taxes","section_title":{},"description":{},"notes":{},"type":"Lec","units":" 3","spaces_available":"30","number_registered":"16","wait_qty":"0","canceled ":"N","blackboard":"Y","comment":{},"day":"M","start_time":"18:30","end_time ":"21:30","location":"BRI202","instructor":[{"last_name":"Keller","first_nam e":"Joseph"},{"last_name":"Mills","first_name":"Jim"}],"syllabus":{"format": {},"filesize":{}},"IsDistanceLearning":"N"}}},{"IsCrossListed":"N","Publishe dCourseID":"ACCT-590","ScheduledCourseID":"ACCT-590","CourseData":{"prefix": "ACCT","number":"590","sequence":{},"suffix":{},"title":"Directed Research","description":"Research leading to the master\'s degree. Maximum units which may be applied to the degree to be determined by the School of Accounting. Graded CR\/NC.","units":"1-4","restriction_by_major":" Registration open to the following major(s): Accounting, Business Taxation, Law","restriction_by_class":{},"restriction_by_school":{},"CourseNotes":{}," CourseTermNotes":{},"prereq_text":{},"coreq_text":{},"SectionData":{"id":"14 300","session":"001","dclass_code":"D","title":"Directed Research","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"1-4","spaces_available":"10","number_registered":"0","wait_qty":"0","canc eled":"N","blackboard":"N","comment":{},"day":{},"start_time":"TBA","end_tim e":"TBA","location":"OFFICE","instructor":{"last_name":"Maxey","first_name": "Shirley"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N"}} },{"IsCrossListed":"N","PublishedCourseID":"ACCT-597","ScheduledCourseID":"A CCT-597","CourseData":{"prefix":"ACCT","number":"597","sequence":{},"suffix" :{},"title":"Business Field Project in Accounting","description":"Individual or team projects solving real business problems for companies; situation analyses; research proposal composition; field research techniques; statistical analysis; oral and written presentations. Graded CR\/NC.","units":"1-6","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":{},"coreq_text":{},"SectionData":{"id":"14302","session":"033","dclass_cod e":"D","title":"Business Field Project in Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"1-6","spaces_available":"50","number_registered":"0","wait_qty":"0","ca nceled":"N","blackboard":"N","comment":{},"day":{},"start_time":"TBA","end_t ime":"TBA","location":"OFFICE","instructor":{"last_name":"Beatty","first_nam e":"Randolph"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":" N"}}},{"IsCrossListed":"N","PublishedCourseID":"ACCT-602","ScheduledCourseID ":"ACCT-602","CourseData":{"prefix":"ACCT","number":"602","sequence":{},"suf fix":{},"title":"Survey of Judgment and Decision-Making Research in Accounting","description":"Survey of major topics in judgment and decision-making research in accounting with coverage of both key research questions and frequently used methods. Departmental approval.","units":"3","restriction_by_major":{},"restriction_by_class":{}," restriction_by_school":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text ":{},"coreq_text":{},"SectionData":{"id":"14310","session":"036","dclass_cod e":"D","title":"Survey of Judgment and Decision-Making Research in Accounting","section_title":{},"description":{},"notes":{},"type":"Lec","uni ts":"3","spaces_available":"5","number_registered":"5","wait_qty":"0","cance led":"N","blackboard":"N","comment":{},"day":"F","start_time":"09:00","end_t ime":"11:50","location":"ACC312","instructor":{"last_name":"Bonner","first_n ame":"Sarah","bio_url":"http:\/\/mymarshall.usc.edu\/portal\/subapps\/digita lmeasures\/faculty.jsp?surveyId=48731"},"syllabus":{"format":{},"filesize":{ }},"IsDistanceLearning":"N"}}},' aaa=aaa+'{"IsCrossListed":"N","PublishedCourseID":"ACCT-611","ScheduledCours eID":"ACCT-611","CourseData":{"prefix":"ACCT","number":"611","sequence":{}," suffix":{},"title":"Selected Topics in Accounting Research","description":"Advanced Seminar to address issues\/topics covered in accounting research forums presented by USC and visiting faculty.","units":"1, 4","restriction_by_major":{},"restriction_by_class":{},"restriction_by_schoo l":{},"CourseNotes":{},"CourseTermNotes":{},"prereq_text":{},"coreq_text":{} ,"SectionData":{"id":"14321","session":"036","dclass_code":"D","title":"Sele cted Topics in Accounting Research","section_title":{},"description":{},"notes":{},"type":"Lec","units ":"1","spaces_available":"20","number_registered":"12","wait_qty":"0","cance led":"N","blackboard":"N","comment":{},"day":"F","start_time":"12:30","end_t ime":"13:20","location":"ACC312","instructor":{"last_name":"Hung","first_nam e":"Mingyi"},"syllabus":{"format":{},"filesize":{}},"IsDistanceLearning":"N" }}}]}}' print "aa = ",aaa print "\n\n\n\n\n\n" if __name__ == "__main__": # main app txdata = None json.dumps(aaa) print "foo" sys.exit() From fredrik at pythonware.com Mon Sep 15 11:33:12 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 17:33:12 +0200 Subject: ElementTree oddities In-Reply-To: References: Message-ID: Brian Cole wrote: > However, it's missing some of the text. For example, the following > XML: > >>>> xml = "Bar" > > Returns me a empty string. Seems the "" tag is borking it. > > > Also, the for the following XML: >>>> xml = "Bar:" > > I only get "Bar". It's missing the trailing colon. > > I'm not that experienced with XML so perhaps I am just missing > something here. Please enlighten me. you're missing the "tail" attribute, which contains text that follows directly *after* the element's end tag. it's not exactly a one-liner, but I usually use the one on this page: http://effbot.org/zone/element-bits-and-pieces.htm#gettext From dblubaugh at belcan.com Tue Sep 30 14:19:59 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Tue, 30 Sep 2008 14:19:59 -0400 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <48E264CC.4050701@mwalsh.org> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> <48E264CC.4050701@mwalsh.org> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9A2B@AWMAIL04.belcan.com> Yes, I new it was a directory issue. I am new to Python. Thank You David Blubaugh -----Original Message----- From: Martin Walsh [mailto:mwalsh at mwalsh.org] Sent: Tuesday, September 30, 2008 1:42 PM To: python-list at python.org Subject: Re: OS.SYSTEM ERROR !!! Blubaugh, David A. wrote: > To All, > > I have been attempting to execute the following program within the > Python environment: > > However, when I would try to execute the following lines of source > code within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? Based on your description, it seems pretty obvious (and easy to confirm) that Myprogram.exe needs to be run from its containing directory ("C:\myprogramfolder\run"). Try something like this... import os pwd = os.getcwd() os.chdir('c:/myprogramfolder/run') os.system("Myprogram.exe 1 1 acc 0") os.chdir(pwd) HTH, Marty This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From robert.kern at gmail.com Tue Sep 9 20:00:21 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 Sep 2008 19:00:21 -0500 Subject: Looking for a Duo - file comparison and a file parser In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > HI, > > I'm thinking of writing a file comparison utility in python. This > utility will work as: > > 1. Compare 2 files for the differences. Both files contain some > numerical results. > 2. Generate a common file containing the differences (the same way as > 'diff' generate an output) > 3. Now, I will parse this file containing differences to check as to how > much is the difference of one file from other. So, for this I hope a > parser will be required. > > Is there a utility available that performs similar job ( that some one > might have created considering the huge number of users of python) ? > > Or may be some one has written some parser? There are a couple of ways to do #3. One would be to use the difflib module from the standard library. The Differ.compare() method will give you a sequence of lines with prefixed character saying whether the line was the same in both files, deleted from the first or added by the second. Lines that are recognized as having changed (rather than just being deleted then readded with modifications) are also noted. The parsing you would have to do would be minimal. http://docs.python.org/dev/library/difflib Or you could use diff and diffstat: http://invisible-island.net/diffstat/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From grante at visi.com Sat Sep 27 10:10:49 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 27 Sep 2008 09:10:49 -0500 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: On 2008-09-27, Lawrence D'Oliveiro wrote: > In message , Grant > Edwards wrote: > >> On 2008-09-26, Lawrence D'Oliveiro >> wrote: >>> In message , Grant Edwards >>> wrote: >>> >>>> Never assume somebody reading the article and attempting to >>>> help you can see the subject line. >>> >>> Why not? >> >> Because it might not be. It depends on the user's newsreader >> and editor settings. > > So, should I not assume that they can see the content as well, > because it might not be visible, depending on the user's > newsreader and editor settings? Thats seems like a bit of reductio ad absurdum. My observations over the years confirm the advice that you shouldn't place information solely in the subject line. If you rely on people re-reading the subject line as the read and reply to the body of the posting, you'll often get bad results. People will miss information that was left out of the body and placed solely in the subject line. I've seen it happen over an over again (this thread is an example). If you don't care whether you get timely and accurate responses, then do whatever you want. Otherwise, include all the pertinent information in the body of the posting. -- Grant From wuwei23 at gmail.com Sun Sep 7 23:48:14 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 7 Sep 2008 20:48:14 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: <4b869278-0303-4c41-aacb-e3d497c33351@l33g2000pri.googlegroups.com> Fredrik Lundh wrote: > (btw, I've always thought that Python was all about making it easy to > express the solution to a given problem in code, not to let you write > programs without using your brain. ?when did that change?) The day Google App Engine was opened up to developers, I believe. From almar.klein at gmail.com Tue Sep 30 05:38:22 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 30 Sep 2008 11:38:22 +0200 Subject: can someone explain why this happens- newbie question In-Reply-To: References: Message-ID: change: for score in scores: print scores to: for score in scores: print score that should do the trick :) Almar 2008/9/30 garywood > Hi > can someone tell me why it prints the high score table multiple times? > > #high scores program > scores =[] > choice = None > > while choice != 0: > print """high Score Table > 0 - exit > 1 - show Scores > 2 - add a score > 3 - delete a score > 4 - sort scores > """ > choice = input("what would you like to do?") > if choice == 0: > print "goodbye" > elif choice == 1: > for score in scores: > print scores > elif choice == 2: > score = input("add a score") > scores.append(score) > elif choice == 3: > score = input("what score would you like to delete ?") > if score in scores: > scores.remove(score) > else: > print "that score is not listed" > > > elif choice == 4: > scores.sort() > scores.reverse() > print scores, "highest score first" > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rokwok at newsguy.com Thu Sep 25 04:02:01 2008 From: rokwok at newsguy.com (Ronnie Kwok) Date: 25 Sep 2008 01:02:01 -0700 Subject: Connecting to SMB share in python Message-ID: Hello, I am trying to write a script that copy files from my local machine to a samba share. I've notice a library call Pysamba which is a wrapper on smb service but it requires a compilation of SAMBA with some amendment in order to use it. Are there alternative method that I could do the same thing? Thank you for your advise. ronnie From skip at pobox.com Mon Sep 15 20:49:06 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 15 Sep 2008 19:49:06 -0500 Subject: Decompile python2.5-pyc In-Reply-To: <9DE19AF2-1E2B-4914-BA51-9E230CB238DE@uos.de> References: <9DE19AF2-1E2B-4914-BA51-9E230CB238DE@uos.de> Message-ID: <18639.642.956362.833575@montanaro-dyndns-org.local> >>>>> "Manuel" == Manuel Ebert writes: Manuel> Does anybody know something I don't, some home-brewn decompiler, Manuel> anything? I *am* quite desperate... Well... If you have some time and are desperate, you might try importing the module(s) then disassembling them with the dis module. The output will still be Python's virtual machine assembly, but at least it will be sort of readable. You might be able to manually translate it back to the equivalent Python source code. For example: >>> def f(a): ... a.append(7) ... if len(a) > 5: ... del a[0] ... >>> import dis >>> dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 LOAD_ATTR 0 (append) 6 LOAD_CONST 1 (7) 9 CALL_FUNCTION 1 12 POP_TOP 3 13 LOAD_GLOBAL 1 (len) 16 LOAD_FAST 0 (a) 19 CALL_FUNCTION 1 22 LOAD_CONST 2 (5) 25 COMPARE_OP 4 (>) 28 JUMP_IF_FALSE 11 (to 42) 31 POP_TOP 4 32 LOAD_FAST 0 (a) 35 LOAD_CONST 3 (0) 38 DELETE_SUBSCR 39 JUMP_FORWARD 1 (to 43) >> 42 POP_TOP >> 43 LOAD_CONST 0 (None) 46 RETURN_VALUE Skip From mail.anand.anand at gmail.com Tue Sep 30 05:17:50 2008 From: mail.anand.anand at gmail.com (aathi) Date: Tue, 30 Sep 2008 02:17:50 -0700 (PDT) Subject: Welcome to US Computer Jobs Message-ID: <9d06d79d-ff84-4ca0-9ac2-fcc982656620@e53g2000hsa.googlegroups.com> Welcome to US Computer Jobs Windows System Engineer Phone and Inperson Interview http://geocities.com/anandrisks/ http://friendfinder.com/go/g959922 http://amigos.com/go/g959922 From pete.forman at westerngeco.com Wed Sep 24 13:16:14 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Wed, 24 Sep 2008 18:16:14 +0100 Subject: python syntax for conditional is unfortunate References: Message-ID: Asun Friere writes: > A canonical use of the conditional operator is in > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). That fails for n == 1. So what is best? for i in range(4): print '%d thing' % i + ('s' if i != 1 else '') for i in range(4): print '%d thing%s' % (i, ('s', '')[i==1]) for i in range(4): print '%d thing%s' % (i, 's' if i != 1 else '') -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From lists at cheimes.de Wed Sep 10 15:21:28 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 21:21:28 +0200 Subject: Simple UDP server In-Reply-To: <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> References: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> <6c017e20-e3c5-4392-8870-d04b89cd910a@t54g2000hsg.googlegroups.com> Message-ID: Tzury Bar Yochay wrote: > So what if it is connectionless. > It would make sense if you get a load of users who sends large sets of > binary data to each other. Transmitting large binary data over UDP? That makes only sense for few applications like video and audio streaming. UDP does neither guarantee that your data is received nor it's received in order. For example the packages A, B, C, D might be received as A, D, B (no C). Can your protocol handle missing packages and out of order packages? Christian From clp at rebertia.com Wed Sep 24 22:55:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Wed, 24 Sep 2008 19:55:57 -0700 Subject: Off topic: Sent from my Foo messages In-Reply-To: <00eaf368$0$20666$c3e8da3@news.astraweb.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> <00eaf368$0$20666$c3e8da3@news.astraweb.com> Message-ID: <47c890dc0809241955m1214f464m3fcf078d07b18d53@mail.gmail.com> On Wed, Sep 24, 2008 at 7:38 PM, Steven D'Aprano wrote: > I'm seeing more and more posts from various people, on this list and > others, with statements like the following: > > On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote: > >> Sent from my iPhone > > Also "Sent from my Blackberry" and similar. > > Without wishing to be rude to David, who I'm sure is a nice guy and not > at all the pretentious git that such a line makes him appear, are people > adding this comment to the bottom of their posts, or is it something that > their device automatically appends to the post? It's on by default for the iPhone/iTouch but there's a setting to change the signature (including to nothing). Don't know about the Blackberry. > > If people are adding it themselves, that's nice, I'm sure you're really > excited about your new toy, but the rest of us don't care a monkey's > toss. And if the device is automatically appending it, I think that's > pretty damn rude and a good reason to avoid buying the obnoxious machines. Eh, that's a bit extreme; though I admit it can sometimes be annoying (but not very much). Regards, Chris Sent using a Computer, the Internet, Gmail, Firefox, unix, glibc, ... ;P > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From fredrik at pythonware.com Fri Sep 5 04:55:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 10:55:56 +0200 Subject: derived classes and __getattr__ In-Reply-To: References: Message-ID: Alexandru Mos,oi wrote: > i'm facing the following problem: > > class Base(object): > def __getattr__(self, attr): return lambda x: attr + '_' + x > > def dec(callable): > return lambda *args: 'dec_' + callable(*args) > > class Derived(Base): > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have > what_so_ever > mumu = dec(Base.mumu) # wrong, base > doesn't have mumu > > any idea how to do this? ever thought of using Python to write Python programs? From uzmanajmal at gmail.com Wed Sep 17 06:42:05 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Wed, 17 Sep 2008 10:42:05 +0000 Subject: File Reading related query In-Reply-To: References: Message-ID: I am talking about text file which contain multiple lines e.g following three lines are there in my textfile.txt this is python list where we get support from geeks I want sentence = this is python list where we get support from geeks whereas when i use simple read() i get something like this sentence = this is python list\nwhere we get support\nfrom geeks On Wed, Sep 17, 2008 at 10:18 AM, Fredrik Lundh wrote: > Usman Ajmal wrote: > > Is there any function for reading a file while ignoring *\n* occuring in >> the file? >> > > can you be a bit more precise? are we talking about text files or binary > files? how do you want to treat any newlines that actually appear in the > file? > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kalin at el.net Wed Sep 17 13:40:12 2008 From: kalin at el.net (kalin m) Date: Wed, 17 Sep 2008 13:40:12 -0400 Subject: locks Message-ID: <48D140FC.8070801@el.net> hi all... mailman has been locking one list out. the web interface just hangs and it generates a bunch of locks. it seems that it can not write to a log but not sure which one. errors are like: ep 17 05:09:12 2008 (18481) musiclist.lock lifetime has expired, breaking Sep 17 05:09:12 2008 (18481) File "/var/mailman/bin/qrunner", line 270, in ? Sep 17 05:09:12 2008 (18481) main() Sep 17 05:09:12 2008 (18481) File "/var/mailman/bin/qrunner", line 230, in main Sep 17 05:09:12 2008 (18481) qrunner.run() Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/Queue/Runner.py", line 70, in run Sep 17 05:09:12 2008 (18481) filecnt = self._oneloop() Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/Queue/Runner.py", line 111, in _oneloop Sep 17 05:09:12 2008 (18481) self._onefile(msg, msgdata) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/Queue/Runner.py", line 167, in _onefile Sep 17 05:09:12 2008 (18481) keepqueued = self._dispose(mlist, msg, msgdata) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/Queue/IncomingRunner.py", line 115, in _dispose Sep 17 05:09:12 2008 (18481) mlist.Lock(timeout=mm_cfg.LIST_LOCK_TIMEOUT) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/MailList.py", line 159, in Lock Sep 17 05:09:12 2008 (18481) self.__lock.lock(timeout) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/LockFile.py", line 306, in lock Sep 17 05:09:12 2008 (18481) important=True) Sep 17 05:09:12 2008 (18481) File "/var/mailman/Mailman/LockFile.py", line 416, in __writelog Sep 17 05:09:12 2008 (18481) traceback.print_stack(file=logf) Sep 17 10:17:05 2008 (19547) musiclist.lock lifetime has expired, breaking Sep 17 10:17:06 2008 (19547) File "/var/mailman/cron/checkdbs", line 178, in ? Sep 17 10:17:06 2008 (19547) main() Sep 17 10:17:06 2008 (19547) File "/var/mailman/cron/checkdbs", line 84, in main Sep 17 10:17:06 2008 (19547) mlist = MailList.MailList(name) Sep 17 10:17:06 2008 (19547) File "/var/mailman/Mailman/MailList.py", line 126, in __init__ Sep 17 10:17:06 2008 (19547) self.Lock() Sep 17 10:17:06 2008 (19547) File "/var/mailman/Mailman/MailList.py", line 159, in Lock Sep 17 10:17:06 2008 (19547) self.__lock.lock(timeout) Sep 17 10:17:06 2008 (19547) File "/var/mailman/Mailman/LockFile.py", line 306, in lock Sep 17 10:17:06 2008 (19547) important=True) Sep 17 10:17:06 2008 (19547) File "/var/mailman/Mailman/LockFile.py", line 416, in __writelog Sep 17 10:17:06 2008 (19547) traceback.print_stack(file=logf) all other lists appear to be working fine.... thanks.... From roy at panix.com Sat Sep 27 08:34:57 2008 From: roy at panix.com (Roy Smith) Date: Sat, 27 Sep 2008 08:34:57 -0400 Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> <40efa068-688c-4dcf-b11e-938c0d4d006a@w39g2000prb.googlegroups.com> Message-ID: In article <40efa068-688c-4dcf-b11e-938c0d4d006a at w39g2000prb.googlegroups.com>, alex23 wrote: > ' '.join((str(x * x) for x in range(1,6))) Aren't the outer set of parens redundant? This works just as well: ' '.join(str(x * x) for x in range(1,6)) From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 5 09:09:31 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 05 Sep 2008 15:09:31 +0200 Subject: derived classes and __getattr__ In-Reply-To: <12c58ddc-5d45-4323-b268-6815fe5cb86d@z6g2000pre.googlegroups.com> References: <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> <12c58ddc-5d45-4323-b268-6815fe5cb86d@z6g2000pre.googlegroups.com> Message-ID: <48c12f1f$0$316$426a74cc@news.free.fr> Alexandru Mosoi a ?crit : (snip) > i somehow fixed the problem using: > > def __getattr__(self, attr): > return > functools.partial(Base.__metaclass__.__getattr__(self.__class__, > attr), self) > > however this looks ugly enough to look for another solution. i still > have one more question: why do I have to bind self? (without which > functions fail expecting an instance) Because the partial type doesn't implement the descriptor protocol (which is implemented by function type to return a method). From mail at microcorp.co.za Sat Sep 20 17:14:26 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 20 Sep 2008 23:14:26 +0200 Subject: Ascii Menu I/O redirection Message-ID: <002f01c91b66$0bdfcbc0$0d00a8c0@hendrik> I am writing a small application with a simple ascii based menu. The menu is used to test individual functions, and to change some timings. Otherwise the application just runs automatically, depending on command line options. I want to be able to redirect the menu. The console, a serial port, or possibly a socket are target candidates. Now a serial port and a socket are single files, so I need a "file" that represents the console, to pass to the working functions. Simply re-assigning for instance sys.stdin.write to point to sys.stdout.write, and using sys.stdin as such a file does not work... So I do the following: class console(object): """ This spoofs a single file like object, using stdout & - in (Minimalistic proof of concept implementation) """ def __init__(self): self.read = sys.stdin.read self.readline = sys.stdin.readline self.write = sys.stdout.write self.flush = sys.stdout.flush self.closeout = sys.stdout.close # keep references to close self.closein = sys.stdin.close def close(self): self.closein() self.closeout() # see if we must run, and how: if __name__ == "__main__": if 'serial' in sys.argv: # for RS-232 i/o to terminal f = open('/dev/ttyS0','r+b') else: # console i/o f = console() sys.stderr = f # redirect errors sys.stdout = f # redirect printing sys.stdin = f # redirect raw_input stuff if 'menu' in sys.argv: # test and timing changes menu_loop(menu_dict,f) # (menu_dict is dispatch dict) else: # else just run the system autorun(menu_dict,f) The above just shows a choice between console and serial as an example - adding a socket option would be trivial. This all seems to work, but I am asking here before I take the trouble to turn it into production code, as I don't think it is exactly a new problem. Questions are: Is this a reasonable way of doing this kind of thing? Is there a canonical or better way of doing it? Am I missing something? Using Linux only. - Hendrik From cvrebert at gmail.com Fri Sep 12 15:45:20 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Fri, 12 Sep 2008 12:45:20 -0700 Subject: book example confusion In-Reply-To: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: <13B9374E-851B-495F-9908-1BFD6ABFD6AC@gmail.com> Note the parentheses after f1 and f2 in the second example. That's what calls the functions and causes them to be evaluated and run. - Chris Sent from my iPod On Sep 12, 2008, at 12:36 PM, byron wrote: > I am reading o'reilly's learning python (great book), but i came > across an example (pg 291, pdf) that I am not quite understanding the > reasoning for the author's explanation: > > if f1() or f2(): > > The author states that do to the nature of that expression, if f1() > returns True, f2() will not be evaluated.. which makes sense. His > quote: > > "Here, if f1 returns a true (or nonempty) value, Python will > never run f2." > > He then states: > > "To guarantee that both functions will be run, call them > before the 'or':" > > tmp1, tmp2 = f1(), f2() > if tmp1 or tmp2: > > Being that each function is an object, a name assignment to > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > the name is called.. so why would the latter example "run" both > functions as the author suggests? > -- > http://mail.python.org/mailman/listinfo/python-list From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 3 07:14:59 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 13:14:59 +0200 Subject: How to write verbose scripts In-Reply-To: <5a3c1c2e-6613-41a9-b132-e979f978b14a@t1g2000pra.googlegroups.com> References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <5a3c1c2e-6613-41a9-b132-e979f978b14a@t1g2000pra.googlegroups.com> Message-ID: <48be7153$0$17347$426a74cc@news.free.fr> John Machin a ?crit : > On Sep 3, 3:52 am, Mensanator wrote: >> On Sep 2, 11:55 am, Steven D'Aprano > >> if (p & 1)==1: >> print_evens = True >> else: >> print_evens = False >> if (p & 2)==2: >> print_odds = True >> else: >> print_odds = False >> if (p & 4)==4: >> print_debug = True >> else: >> print_debug = False > > No, no, no, you've taken "How to write verbose scripts" rather too > literally; KEYBOARD ! From castironpi at gmail.com Thu Sep 4 16:31:02 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 13:31:02 -0700 (PDT) Subject: why is self not passed to id()? References: Message-ID: On Sep 4, 3:26?pm, Ruediger wrote: > Hello! > > Executing following little program gives me an TypeError. > > What makes me wonder is that foo does get an argument passed while bar > doesn't. Can anyone explain why?????? > > Thanks > Ruediger > > class foo(list): > ? ? __hash__ = lambda x: id(x) > > class bar(list): > ? ? __hash__ = id > > _s_ = set() > _s_.add(foo()) > _s_.add(bar()) > > rue at linux:~> python test01.py > Traceback (most recent call last): > ? File "test01.py", line 9, in > ? ? _s_.add(bar()) > TypeError: id() takes exactly one argument (0 given) The answer is fairly technical. For member functions to be bound to instances, they are required to have a __get__ method (which takes instance and owner as parameters). 'id' does not. (Why does 'id' not have a __get__ method?) By contrast, >>> set.add >>> dir(_) ['__call__', '__class__', '__delattr__', '__doc__', '__get__', '__getattribute__ ', '__hash__', '__init__', '__name__', '__new__', '__objclass__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] 'set.add' does. From jason.scheirer at gmail.com Tue Sep 23 13:07:27 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Tue, 23 Sep 2008 10:07:27 -0700 (PDT) Subject: Linq to Python References: Message-ID: On Sep 23, 7:48?am, hrishy wrote: > Hi > > Will LINQ be ported to Python ? > > regards > Hrishy I think this question is more appropriate to ask on an IronPython development list -- LINQ is pretty solidly intertwined with .Net, and so you'll likely want to look at the .Net implementation of Python. From linkmaster032000 at gmail.com Fri Sep 19 18:42:57 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Fri, 19 Sep 2008 15:42:57 -0700 (PDT) Subject: curses.setsyx()? References: Message-ID: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> On Sep 19, 1:24?am, Tim Roberts wrote: > linkmaster032... at gmail.com wrote: > > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > >cursor. Any alternatives/solutions? > > Did you call doupdate after? ?setsyx just manipulates the data structures. > It takes a call to doupdate to force those changes to take effect visually. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. I added it and it still doesn't work. This is what I'm doing when I want to display the cursor and prepare it for input at 2,3: curses.echo() curses.curs_set(1) curses.setsyx(2,3) curses.doupdate() From bj_666 at gmx.net Sat Sep 13 04:25:46 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Sep 2008 08:25:46 GMT Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> Message-ID: <6j1boaFv9o6U1@mid.uni-berlin.de> On Sat, 13 Sep 2008 01:06:22 -0700, cnb wrote: > This must be because of implementation right? Shouldn't reduce be faster > since it iterates once over the list? doesnt sum first construct the > list then sum it? No it doesn't. Why should it? > also, using range instead of xrange doesnt seem to generate a > performance-penalty: (De)Allocating a list of length 100 isn't very slow. Try some million elements. And watch the memory consumption too. Ciao, Marc 'BlackJack' Rintsch From bluesmanu at gmail.com Wed Sep 24 05:31:33 2008 From: bluesmanu at gmail.com (bluesmanu at gmail.com) Date: Wed, 24 Sep 2008 02:31:33 -0700 (PDT) Subject: Python graphical library Message-ID: <3abb0519-7700-4d82-bdaa-e4b09ef1c483@t54g2000hsg.googlegroups.com> Hi all, I am looking for a python graphical library that would allow me to draw borderless windows, sort of like a notification frame showing up. I would also like to be able to make it transparent but I suppose that is very much desktop manager dependent. Thank you very much for the help. ET From castironpi at gmail.com Tue Sep 23 20:22:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 17:22:00 -0700 (PDT) Subject: Visualize class inheritance hierarchy References: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Message-ID: <103c5d06-fcfc-48ca-9c8a-aac4e2854bde@m36g2000hse.googlegroups.com> On Sep 23, 5:53?pm, Rob Kirkpatrick wrote: > Hi All, > > I just finished debugging some code where I needed to determine why > one subclass had a bound method and another did not. ?They had > different pedigree's but I didn't know immediately what the > differences were. > > I ended up walking the hierarchy, going back one class at a time > through the code, for the two subclasses (hierarchy ~7 classes deep > each) to see whom they inherited from. ?Short of writing this down on > paper, is there any way to graphically display the pedigree of an > object/class? ?"Graphically" can be text output to the terminal, don't > need anything special... > > I'm assuming this has been discussed before, but I'm lacking any > Google keywords that bring up the appropriate discussion. > > Cheers, > Rob If you're using new-style classes, check out the __mro__ member, which no doesn't show up in its dir(). Otherwise, we can try a settrace (frame.f_code.co_name has the name of the class being defined in a class statement) or accumulate some class statements with a custom 'parser' run in the module 'parser'. From fredrik at pythonware.com Fri Sep 5 02:30:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:30:44 +0200 Subject: Case-insensitive string compare? In-Reply-To: <200809050038.04108.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050038.04108.maric@aristote.info> Message-ID: Maric Michaud wrote: > You''ll often see for loops written like this : > > for i in (e for e in iterable if predicate(e)) : > ... luckily, I don't. most people, when faced with that problem, writes it in the obvious way: for i in iterable: if predicate(i): ... to avoid an extra iterator and save typing. From maric at aristote.info Wed Sep 3 19:20:42 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 4 Sep 2008 01:20:42 +0200 Subject: properties setting each other In-Reply-To: <48bee775$0$7236$426a34cc@news.free.fr> References: <48bee775$0$7236$426a34cc@news.free.fr> Message-ID: <200809040120.42909.maric@aristote.info> Le Wednesday 03 September 2008 19:38:13 Bruno Desthuilliers, vous avez ?crit?: > FWIW, if there's no computation on getting or setting value, you can > make it a plain attribute. Yes, this is the problem with these tiny examples, we don't know at which point we must simplify them... > > But while it's quite clear that in this example use case it would be > better ?to have only one property (weither square or value, depending on > which is the most often use), things are not always that simple in real > world code, and - as you mentionned - there may be times where you have > interdependant properties and really want to avoid recomputing the same > thing over and over. Now there's no one size fits all solution here - > it's an optimization problem, and as such depends on real use cases. Yes, my advice was exactly in that sense, it's an optimization problem, duplicating such a data is a caching mechanism, and should be done knowingly, in acceptance of all the complication it comes with. -- _____________ Maric Michaud From fredrik at pythonware.com Mon Sep 22 17:26:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Sep 2008 23:26:55 +0200 Subject: Tkinter 3000 WCK Install Problem In-Reply-To: <0dd2b0dc-f6cb-4b70-8f35-d50446fdd901@2g2000hsn.googlegroups.com> References: <0dd2b0dc-f6cb-4b70-8f35-d50446fdd901@2g2000hsn.googlegroups.com> Message-ID: garyr wrote: > I'm trying to install WCK. I downloaded and installed the Windows > executable for my Python version. It appeared to run OK. I then > downloaded the demo files but find that none run due to error: > ImportError: No module named _tk3draw. > I'm using ActivePython 2.3.5 on Windows XP Home. > What can I do to fix this problem? the error means that the interpreter cannot find the _tk3draw.pyd file. if you use the standard install location, it should be installed under C:\Python23\lib\site-packages you could try this: >>> import FixTk >>> import _tk3draw >>> _tk3draw.__file__ 'C:\\Python23\\lib\\site-packages\\_tk3draw.pyd' if this also gives you an error, search for _tk3draw.pyd on the disk. From fredrik at pythonware.com Wed Sep 17 02:30:14 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 08:30:14 +0200 Subject: how many objects are loaded for hello world? In-Reply-To: References: Message-ID: belred wrote: > i just read this blog about how many objects (types) are loaded for a > hello world program in C#. > > http://blogs.msdn.com/abhinaba/archive/2008/09/15/how-many-types-are-loaded-for-hello-world.aspx > > how can you find out how many are loaded for a python program: print > 'hello' types and objects are different things, though. to get an idea of how much stuff Python loads using upstart, do "python -vv script.py" or add import sys print len(sys.modules), "modules" print sys.modules.keys() to the end of the script. to get an idea of how many objects and types that are created at that point, add import gc print len(gc.get_objects()), "objects" print len(set(map(type, gc.get_objects()))), "types" this gives me 35 modules (including the gc module), 3219 objects and 26 distinct types -- but the above will miss things, so the true numbers are a bit higher. (you might be able to use a debug build to get more detailed information) From invalid at invalid Thu Sep 18 12:11:18 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 18 Sep 2008 11:11:18 -0500 Subject: Installing pySerial References: <48d2781f$0$4449$afc38c87@news.optusnet.com.au> Message-ID: On 2008-09-18, Joe G (Home) wrote: > Hi All, > > Background >=================== > I have installed Python for windows today from the python web site .I also > installed pySerial using the Windows installer from the sourceforge web > site..... Both installs use the default directories. > > Phyton version : Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC > v.1310 32 bit (Intel)] on win32 > > pySerial 2.4 July 6th > > > Problem : Errors Screen output >============================ >>>> import serial > > Traceback (most recent call last): > File "", line 1, in > import serial > File "C:\Python25\Lib\site-packages\serial\__init__.py", line 18, in > > from serialwin32 import * > File "C:\Python25\Lib\site-packages\serial\serialwin32.py", line 9, in > > import win32file # The base COM port and file IO functions. > ImportError: No module named win32file >>>> > > So it looks like Python can not see some of the modules Do you have the win32 modules installed? > Here's the active paths > >>>> print sys.path > ['C:\\Python25\\Lib\\idlelib', 'C:\\WINDOWS\\system32\\python25.zip', > 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', > 'C:\\Python25\\lib\\site-packages'] >>>> > > It seems that C:\Python25\Lib\site-packages\serial needs to be added to > the PYTHONPATH I don't see how you came to that conclusion. Is the "missing" module (win32file) located in C:\Python25\Lib\site-packages\serial? > QUESTION >============= > Q1. How do I add C:\Python25\Lib\site-packages\serial to the PYTHONPATH ? Dunno. > Q2. How do I check that I have installed pySerial corretly > (using the Windows installer) If you used the installer, you almost undoubtedly have it installed correctly. I think you're missing the win32 package. http://python.net/crew/mhammond/win32/Downloads.html -- Grant Edwards grante Yow! I'm not an Iranian!! at I voted for Dianne visi.com Feinstein!! From castironpi at gmail.com Sat Sep 20 13:42:26 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 10:42:26 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: On Sep 20, 5:14?am, Fredrik Lundh wrote: > Kay Schluehr wrote: > > Answer: if you want to define an entity it has to be defined inside a > > class. If you want to access an entity you have to use the dot > > operator. Therefore Java is OO but Python is not. > > you're satirising the quoted author's cargo-cultish view of object > orientation, right? > > If you define OO as implementation inheritance, then Java is not. It inherits interface only. Another possibility is, has a virtual function table. The fact that Python indexes by name doesn't disqualify it from that definition. I don't know if Java meets it. I don't think raw C structures would be included, and you can define function pointers in them. Wikipedia puts it decently: "mainly for OO programming, but with some procedural elements." From showellshowell at gmail.com Mon Sep 15 23:03:54 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Mon, 15 Sep 2008 20:03:54 -0700 (PDT) Subject: How to marshal objects to readable files? References: Message-ID: <86de3bf2-c5e6-4c2f-a775-1fef231b2965@l33g2000pri.googlegroups.com> On Sep 14, 8:28?am, nielinjie wrote: > Hi list: > I just want to marshal objects (instance of custom classes)to a human > *READABEL *file/string, and also, I want unmarshal it back. in xml > format or any other format. > Any advice? Which lib should I use? > Thanks a lot. I think YAML is the solution most targeted for your needs. To quote the website: "YAML is a human friendly data serialization standard for all programming languages." http://yaml.org/ If you're willing to sacrifice some readability for truly robust serialization, try pickle, which isn't horribly cryptic. If you want simplicity and AJAX interoperability, consider JSON. If you consider Python itself to be human readable, and if your security/performance situation does not preclude the use of eval(), consider the PrettyPrinter module. From shahmed at sfwmd.gov Thu Sep 11 09:40:21 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Thu, 11 Sep 2008 09:40:21 -0400 Subject: removing text string In-Reply-To: <514c0466-3142-43e7-abc6-f75fb139e25e@c65g2000hsa.googlegroups.com> References: <514c0466-3142-43e7-abc6-f75fb139e25e@c65g2000hsa.googlegroups.com> Message-ID: -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of bearophileHUGS at lycos.com Sent: Thursday, September 11, 2008 8:54 AM To: python-list at python.org Subject: Re: removing text string Ahmed, Shakir: > Actually the number I am getting it is from slicing from a long text > line. I need to slice 10 characters from that line but no string only > numeric numbers. When I am slicing 10 characters those A, c, O is coming > at the end. It's better to avoid Regular expressions when they aren't necessary, but once in a while they are the simpler way to solve a problem, you may create one like this (mostly untested): \d+?-\d+ Using it like: >>> import re >>> patt = re.compile(r"\d+?-\d+") >>> patt.search("xxxxxx080829-7_A xxxx").group() '080829-7' >>> re.search(r"\d+?-\d+", "xxxxxx080829-7_A xxxx").group() '080829-7' Learning Regexps can be useful. Bye, Bearophile Thanks, I got the clue. Very much appreciated. -- http://mail.python.org/mailman/listinfo/python-list From fredrik at pythonware.com Thu Sep 11 03:18:56 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 09:18:56 +0200 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Usman Ajmal wrote: > And i also fount that a typical system.auth call will look like: > > POST /xmlrpc/clarens_server.py HTTP/1.0 > Host: localhost > User-Agent: xmlrpclib.py/0.9.9 (by www.pythonware.com ) > > Content-Type: text/xml > Content-Length: 105 > AUTHORIZATION: Basic MkhVTm9VazYxbXArVEZLS0dCY2tIRlA3bjVzPQo6RnJvbSBi > > > system.auth > > > > > > > Problem is that i don't know how do i generate above xml system.auth > call. Can anyone please tell me how do call a function, setting the > header of the call too? you need to plugin a custom transport. see this page for an example: http://www.python.org/doc/lib/xmlrpc-client-example.html in your case, it should be sufficient to override send_request, e.g. (untested): class SecureTransport(xmlrpclib.Transport): def set_authorization(self, ustring, text_ucert): self.authoriation = encodestring( "%s:%s" % (ustring,text_ucert) ) def send_request(self, connection, handler, request_body): connection.putrequest("POST", handler) connection.putheader("Authorization", "Basic %s" % self.authorization ) and instantiate the transport by doing t = SecureTransport() t.set_authorization(ustring, text_ucert) before passing to the server proxy. From watine at cines.fr Mon Sep 8 11:44:33 2008 From: watine at cines.fr (Benjamin Watine) Date: Mon, 08 Sep 2008 17:44:33 +0200 Subject: Files application architecture In-Reply-To: <48c1d6b2$0$15607$426a74cc@news.free.fr> References: <48c1d6b2$0$15607$426a74cc@news.free.fr> Message-ID: <48C54861.1000005@cines.fr> Bruno Desthuilliers a ?crit : > Benjamin Watine a ?crit : >> Hi, >> >> I'm about to develop a small python application and I wonder how to >> organize files in this application. >> I'm familar to java, so I'm tempted to use the same convention > > http://dirtsimple.org/2004/12/python-is-not-java.html > >> : 1 file per class and 1 folders per package. > > Don't. This is a waste of time and a pain to maintain, and more over it > doesn't make any sense since Python doesn't force you to put everything > in classes. > >> I know that packages doesn't exists in python, > > Did you actually read the doc ? While Python's packages are not the same > thing as Java's, they do exist. > > http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > >> they are modules instead. May I create specific module for each "group >> of class" ? > > The usual way to get cohesive modules is indeed to group closely related > objects (classes, functions, etc) in a same module. > >> My application follow the MVC paradigm, so basically, I've a package >> Model, a package View, and a package Controller. > > If your app is small, having _modules_ models, views and controllers > should be enough. > >> So, what are best practices for organizing files and folders in a >> small python project ? > > The best practice is to keep things simple, as usual. > Thank you all for your good advices and links. I'm new to python and I have yet a lot of things to learn ! Now, I would like to take a look to a well coded wxPython application. Could anybody indicate a project that I could take as reference for standard python coding style ? Regards, Ben From bignose+hates-spam at benfinney.id.au Sun Sep 28 04:03:45 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 28 Sep 2008 18:03:45 +1000 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <00eee9ec$0$20666$c3e8da3@news.astraweb.com> Message-ID: <87vdwgsnmm.fsf@benfinney.id.au> Terry Reedy writes: > Steven D'Aprano wrote: > > > And modules aren't callable. I've often thought they should be. > > Modules are not callable because their class, module, has no > __call__ instance method. But (in 3.0, which is all I will check) > you can subclass module and add one. Works fine in Python 2.5.2 also:: Python 2.5.2 (r252:60911, Aug 8 2008, 11:09:00) [GCC 4.3.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> module = type(__builtins__) >>> module >>> '__call__' in dir(module) False >>> import sys >>> class CallableModule(module): ... def __call__(self, *args, **kwargs): ... sys.stdout.write("%(self)r, %(args)r, %(kwargs)r\n" % vars()) ... >>> '__call__' in dir(CallableModule) True >>> foo = CallableModule('foo') >>> foo(1, 2, 3, a=4, b=5) , (1, 2, 3), {'a': 4, 'b': 5} >>> foo -- \ ?There are only two ways to live your life. One is as though | `\ nothing is a miracle. The other is as if everything is.? | _o__) ?Albert Einstein | Ben Finney From castironpi at gmail.com Thu Sep 11 14:00:44 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 11:00:44 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: Message-ID: On Sep 11, 10:52?am, hofer wrote: > On Sep 11, 10:36?am, Nick Craig-Wood wrote: > > >I'd type the explicit > > > ?v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > Either is only a couple more > > characters to ?type. ?It is completely > > explicit and comprehensible to everyone, in comparison to > > > ? v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > > ? v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars > > > Unlike perl, it will also blow up if mydict doesn't contain 'one' > > which may or may not be what you want. > > Is your above solution robust against undefined keys. > In my example it would'nt be a problem. The dict would be fully > populated, but I'm just curious. If undefined keys aren't a problem, then there's a value you expect from them. Use v1,v2,v3 = [ mydict.get(k,default) for k in 'one two two'.split()] where default is the value you're expecting. From jcd at sdf.lonestar.org Mon Sep 15 16:52:54 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 15 Sep 2008 16:52:54 -0400 Subject: Python Nautilus script In-Reply-To: <6j7t7rF1tl5rU1@mid.uni-berlin.de> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> Message-ID: <1221511974.6448.3.camel@aalcdl07.lib.unc.edu> On Mon, 2008-09-15 at 22:00 +0200, Diez B. Roggisch wrote: > Michel Leunen schrieb: > > Diez B. Roggisch a ?crit : > > > >> There shouldn't be a difference between a shell-script and a > >> python-script. Environment-variables are a unix-process-thing, and > >> thus the rules that govern them apply to *all* processes - the shell > >> is one of these, there is nothing special to it. > >> > >> If the shell-script gets the variable, the python-script will as well. > > > > Yes, that's what I thought too but try this: open a terminal and type > > > > $ echo $HOSTNAME > > > > you will get the name of your computer. > > Now try this instead: > > > > $ python > > >>> import os > > >>> os.environ['HOSTNAME'] > > Traceback (most recent call last): > > File "", line 1, in > > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > > raise KeyError(key) > > KeyError: 'HOSTNAME' > > >>> > > Which is the exact right thing to happen if the HOSTNAME is not exported. > > The echo above is executed IN THE CURRENT SHELL environment. If it > weren't - why would there be any distinction between local and exported > variables at all? > > If you put > > > > It appears that's because HOSTNAME is not exported. > > But in the case of Nautilus script, how to workaround this issue? > > I don't know for sure if the shell has something build-in that makes it > spawn shell-subprocesses with a different environment than other processes. > > However, if you want you can do something like this: > > #!/bin/bash > export VARIABLE_NAME > python /the/python/script.py > > You create a shell-script that exports the environment first, and then > invokes python. > > Diez > -- Alternatively, export the variable when you create it, in .bashrc or wherever it is getting created. That's probably the Right Thing to Do(tm) in this case. Cheers, Cliff From jvines at arl.army.mil Wed Sep 10 09:17:00 2008 From: jvines at arl.army.mil (John Vines (CISD/HPCD)) Date: Wed, 10 Sep 2008 09:17:00 -0400 Subject: Python extension, where am I going wrong Message-ID: <48C7C8CC.2090404@arl.army.mil> All, I am trying to create an extension module and keep getting an error, "/usr/local/lib/python2.5/site-packages/mytest.so: undefined symbol: PyInitModule" thanks in advance, *Here is my source code and setup.py information: */* mytest.c */ #include #include #include #include static PyObject *ErrorObject; static char isEven__doc__[] = "Method to determine if number is odd or even\n"; static PyObject *isEven(PyObject *self, PyObject *args){ int inputValue; int returnValue; if (!PyArg_ParseTuple(args, "i", &inputValue)){ PyErr_SetString(PyExc_ValueError, "Argument parsing Error"); return NULL; } if ( 0 == inputValue%2 ){ returnValue = 1; } else { returnValue = 0; } return Py_BuildValue("i", returnValue); } static char getFactorial__doc__[] = "This module takes a number as a parameter \ and returns the factorial of that number\n"; static PyObject *getFactorial(PyObject *self, PyObject *args){ int inputValue; int resultValue; if (!PyArg_ParseTuple(args, "i", &inputValue)){ PyErr_SetString(PyExc_ValueError, "Argument parsing error"); return NULL; } resultValue = factorialHelper(inputValue); return PyInt_FromLong(resultValue); } int factorialHelper(int factor){ if (factor <= 0){ return 0; } if (factor == 1){ return 1; } return factor*factorialHelper(factor-1); } static struct PyMethodDef mytest_methods[] = { {"isEven", isEven, METH_VARARGS, "Determine odd/even of a number"}, {"getFactorial", getFactorial, METH_VARARGS, "Calc the factorial value of a number"}, {NULL, NULL, 0, NULL} }; void initmytest(){ PyObject *m, *d; m = PyInitModule("mytest", mytest_methods); d = PyModule_GetDict(m); ErrorObject = PyBuildValue("s", "mytest module error"); PyDict_SetItemString(d, "Error", ErrorObject); if (PyErr_Occurred()) Py_FatalError("Can't initialize module mytest!"); } *My setup.py code:* #!/usr/bin/env python from distutils.core import setup, Extension setup(name="mytest", version="1.0", ext_modules=[Extension("mytest", ["mytest.c"])]) From emile at fenx.com Wed Sep 3 15:35:15 2008 From: emile at fenx.com (Emile van Sebille) Date: Wed, 03 Sep 2008 12:35:15 -0700 Subject: os.system dual behaviour In-Reply-To: References: Message-ID: iu2 wrote: > Hi guys > > I do > > os.system('ls &> e') > > On one linux machine it emits ls output to the file e as expected. > On another linux machine it emits ls to the standard output, and > nothing to e! > Both machines run Fedora linux. > > The command "ls &> e" entered at the shell (no python) behaves ok on > both machines. > > Why?? How can I solve this? Why?? I don't know. But you could try the commands module to work around it... open("e",'w').writelines(commands.getoutput('ls')) HTH, Emile From RDarrelBonner at gmail.com Fri Sep 19 19:51:51 2008 From: RDarrelBonner at gmail.com (RDarrelBonner at gmail.com) Date: Fri, 19 Sep 2008 16:51:51 -0700 (PDT) Subject: Pexpect echoes twice for each read References: Message-ID: <9785387f-f4b7-4deb-b1d5-37b829da8080@v13g2000pro.googlegroups.com> On Sep 9, 4:01 pm, "Sriram Rajan" wrote: > For some reason, Using pexpect causes my output to echo twice when I > connect from my MAC Darwin (10.4) to Linux (CentOS release 5 ): > > The program: > --------------------- > #!/usr/bin/python > # Automatic scp to remote host > # Input 1 : filename > # Input 2 : destination folder > # Input 3 : hostname > > import pexpect > import sys,re > > ssh_cmd = "ssh " + sys.argv[3] > ssh_handle = pexpect.spawn (ssh_cmd) > ssh_handle.logfile = sys.stdout > PROMPT = "\$\ $" > > try: > ssh_handle.expect(PROMPT) > > ssh_handle.sendline ("scp "+ sys.argv[1] +" r... at 192.168.1.254:" + > sys.argv[2] ) > > ssh_handle.expect("password:") > > ssh_handle.sendline(" ") > > ssh_handle.expect(PROMPT) > > except pexpect.TIMEOUT: > ssh_handle.logfile.write("\n Pexpect timeout !!\n") > sys.exit(1) > except KeyboardInterrupt: > ssh_handle.logfile.write("\n User interrupt!\n") > sys.exit(2) > ssh_handle.close() > > Output: > ----------- > $ python pexpect_test.py replace_line_break.sh /tmp/ 10.5.254.18 > Last login: Tue Sep 9 15:45:05 2008 from sriram-macbook.dhcp.2wire.com > $ scp replace_line_break.sh r... at 192.168.1.254:/tmp/ > scp replace_line_break.sh r... at 192.168.1.254:/tmp/ > r... at 192.168.1.254's password: > > replace_line_break.sh 100% 296 0.3KB/s 00:00 > $ $ Hi, I had this issue as well. To correct it I upgraded to pexpect 2.3 from 2.1 and changed the following: OLD: ssh_handle.logfile = sys.stdout NEW: ssh_handle.logfile_read = sys.stdout This eliminated the double display of characters as only the characters being sent back from the device are displayed. Let me know if this works for you. - Darrel From enteringheaven at gmail.com Sun Sep 28 11:23:22 2008 From: enteringheaven at gmail.com (enteringheaven) Date: Sun, 28 Sep 2008 08:23:22 -0700 (PDT) Subject: ******GOD OF GIFTS 4 U********* Message-ID: <99873d3e-8610-44ee-b54d-4c97678e970c@z6g2000pre.googlegroups.com> GOD OF GIFTS Free Animations + Wallpapers + Adsens Tips + Hand Reflexogy + Games + Audio + Videos + Nature Health Tips And Beautiful Pics.. http://www.godofgifts.blogspot.com/ From ranim81 at gmail.com Mon Sep 1 08:30:02 2008 From: ranim81 at gmail.com (raju) Date: Mon, 1 Sep 2008 05:30:02 -0700 (PDT) Subject: click here more tips in online about software Message-ID: http://www.moneymaking4.blogspot.com/ From clp at rebertia.com Tue Sep 9 16:49:11 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Sep 2008 13:49:11 -0700 Subject: wxpython ms-dos black window popping up in background In-Reply-To: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: <47c890dc0809091349o76f4385et8d5eef2c4c4d9b88@mail.gmail.com> You need to have the script be run by pythonw.exe as opposed to python.exe pythonw.exe suppresses the DOS box from coming up and should be used for running GUI applications such as yours. Regards, Chris On Tue, Sep 9, 2008 at 1:33 PM, icarus wrote: > platform: windows xp professional, python 2.5, wxpython > > When I double-check on my program file test.py (for simplicity I'll be > using this code below), I see the window just fine. But the ms-dos > black window pops up in the background. On Linux, no issues at all. > > How can I get rid of that ms-dos black window in the background? > something I need to add to my code? a setting to adjust in windows? > thanks in advance. > > > #!/usr/bin/python > import wx > > appwx = wx.App() > > frame = wx.Frame(None, -1, 'test.py') > frame.Show() > > appwx.MainLoop() > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From donspauldingii at gmail.com Thu Sep 18 11:25:25 2008 From: donspauldingii at gmail.com (Don Spaulding) Date: Thu, 18 Sep 2008 08:25:25 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> Message-ID: <5db2ee4b-ecac-4872-bed0-75c62fcdf447@73g2000hsx.googlegroups.com> On Sep 17, 5:53?pm, Todd Whiteman wrote: > supp... at mysfdomain.com wrote: > > On Sep 17, 1:21 pm, Todd Whiteman wrote: > >> Don Spaulding wrote: > >>> On Sep 16, 8:29 pm, Todd Whiteman wrote: > >>>> I've put together a tutorial that shows off how to build a GUI > >>>> application using XULRunner (same architectural components as Firefox > >>>> uses) that can be used in conjunction with the Python programming language. > >>>> The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > >>> I get to the "Running" step and run into "Couldn't load XPCOM." > >>> Does this work on x86_64? ?Or have I made a rookie mistake? > >> Hi Don, > > >> A good question. Mozilla only provide 32-bit XulRunner applications by > >> default, you you'll need to install the necessary 32-bit compatability > >> libraries on your Linux machine, i.e. for Ubuntu it's something like: > >> sudo apt-get install ia32-libs ia32-libs-gtk > > >> Then you should be able to run the example. You can check the > >> dependencies using something the following commands, there should be no > >> missing dependencies: > >> $ cd pyxpcom_gui_app/xulrunner > >> $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin > > >> It is possible to use a 64-bit version, but you'll need to compile this > >> yourself (or find somewhere that provides these x86_64 versions). Note > >> that the PythonExt project does not offer Python bindings for x86_64 > >> either (it's on my todo list), you can compile the PythonExt part > >> yourself as well if you need a 64-bit version. > > >> Cheers, > >> Todd > > > Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs > > and ia32-libs-gtk installed. > > > ldd shows that I'm missing the following libs, even though the proper > > packages are installed, and the files show up in /usr/lib. > > > ? ?libxcb-render-util.so.0 => not found > > ? ?libxcb-render.so.0 => not found > > > There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render- > > util, so I wonder if that could be part of the problem? > > > Don > > Hi Don, > > I'm thinking there may be additional 32-bit packages necessary then (I'm > not sure which package). > > Not sure about Ubuntu 8.10 (it's still alpha). I'm using a Ubuntu 8.04 > x86_64 machine and my dependencies list the following for the latest > 32-bit build of XulRunner: > > $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin | grep libxcb > ? ? ? ? libxcb-xlib.so.0 => /usr/lib32/libxcb-xlib.so.0 (0xf6493000) > ? ? ? ? libxcb.so.1 => /usr/lib32/libxcb.so.1 (0xf647b000) > > Cheers, > Todd No worries Todd, it is alpha. It was a very recent bug in the 8.10 ia32-libs package, which is now fixed :-D Thanks for the excellent writeup, BTW! I've been wondering what was involved in doing this for a while, it just never made it up my priority list to figure out. Again, thanks! From michael.pearmain at tangozebra.com Mon Sep 1 09:32:57 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 1 Sep 2008 06:32:57 -0700 (PDT) Subject: CSV reader and unique ids Message-ID: <6599d785-87b2-4bbc-97bc-799cac3640f5@b1g2000hsg.googlegroups.com> Hi All, I'm trying to use the CSV module to read in some data and then use a hashable method (as there are millions of records) to find unique ids and push these out to another file, can anyone advise? Below is the code so far fin = open(CSV_INPUT, "rb") fout = open(CSV_OUTPUT, "wb") reader = csv.reader(fin, delimiter=chr(254)) writer = csv.writer(fout) headerList = reader.next() UID = {} #For help #print headerList # ['Time', 'User-ID', 'IP'] try: for row in reader[1]: UID[row] = 1 else: List= UID.keys() writer.writerows(List) fin.close() fout.close() Mike From rocky at panix.com Fri Sep 12 05:20:05 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 12 Sep 2008 05:20:05 -0400 Subject: handling uncaught exceptions with pdb? References: <7xmyifpt68.fsf@ruckus.brouhaha.com> <6iulpmFi9t0U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" writes: > R. Bernstein schrieb: >> Paul Rubin writes: >> >>> I think I've asked about this before, but is there a way to set up >>> Python to handle uncaught exceptions with pdb? I know about setting >>> sys.except_hook to something that calls pdb, but this is normally done >>> at the outer level of a program, and by the time that hook gets >>> called, the exception has already unwound the stack to the outermost >>> level. My situation is I run a multi-hour or multi-day computation >>> that eventually crashes due to some unexpected input and I'd like to >>> break to the debugger at the innermost level, right when the exception >>> is encountered, so I can fix the error with pdb commands and resume >>> processing. >> ... >> >> Why not use the traceback you get to show you where to change the code >> around that point to add an exception handler there which calls the >> debugger? > > Because he wants to fix the issue directly in-place, and then > continue, instead of losing hours or even days of computation. Then proactively add exception handlers ;-) From deets at nospam.web.de Thu Sep 18 05:12:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Sep 2008 11:12:02 +0200 Subject: Program works great, except under less, cron or execl (Unicode?) References: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> Message-ID: <6jekbbF2v55pU2@mid.uni-berlin.de> Sam wrote: > I have a program which works great when run from the command line. > > But when I run it combined with something else such as: > - piping it through less > - cron > - execl (i.e. calling it from another python program) > > it gives me a unicode error > > File "../myparser.py", line 261, in set_attributes > print "self.atd['Name'] is: ", self.atd['Name'] > UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in > position 7: ordinal not in range(128) > > I'd post the whole program here, except it involves weird Unicode > strings. > > I could probably change the program to get it working under less/cron/ > etc. > > But I'd rather understand exactly what the issue is. Why does it work > fine when run directly from the command line, but not otherwise? Most probably because when to running directly inside a terminal, it gets it's stdin/stdout as pipes - and python can't attempt to guess the proper encoding on that, as it does on a terminal. And thus, when you print unicode to the pipe, it can't decide which encoding to use. To circumvene this, try & wrap stdout into a codecs-module wrapper with a proper encoding applied (e.g. utf-8). You might make that conditionally based on the sys.stdout.encoding-variable being set or not, albeit I'm not 100% sure to what it actually gets set when used in a subprocess. But this should give you the idea where to look. Diez From m_palmer45 at yahoo.ca Fri Sep 19 10:25:06 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 19 Sep 2008 07:25:06 -0700 (PDT) Subject: Twisted vs Python Sockets References: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> Message-ID: On Sep 18, 4:24 pm, Fredrik Lundh wrote: > James Matthews wrote: > > I am wondering what are the major points of twisted over regular python > > sockets. I am looking to write a TCP server and want to know the pros > > can cons of using one over the other. > > Twisted is a communication framework with lots of ready-made components: > > http://twistedmatrix.com/trac/wiki/TwistedAdvantage > > Regular sockets are, well, regular sockets. No more, no less. > > Depends on what you want your TCP server to do. Just to mention it, there is module SocketServer in the standard library that already contains various server classes, including a TCP server. From dave.dibiase at gmail.com Fri Sep 26 16:16:13 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Fri, 26 Sep 2008 16:16:13 -0400 Subject: Fastest way to max() list In-Reply-To: <47c890dc0809261108k356a109va88b675e037246be@mail.gmail.com> References: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> <47c890dc0809261108k356a109va88b675e037246be@mail.gmail.com> Message-ID: Yeah, Apologies, it's been a long day for me. It works, just have to check if the nazis I'm doing this for will allow me to use object and NumPy. ack. Thanks again, Dave On Fri, Sep 26, 2008 at 2:08 PM, Chris Rebert wrote: > On Fri, Sep 26, 2008 at 7:22 AM, David Di Biase > wrote: > > Hi Chris, > > > > Yeah I hear you on point A. but this the specification I was given, so I > > have to follow it unfortunately. I've also been restricted and not > allowed > > to use any other packages. I was using NumPy earlier (should have > mentioned > > that) but I was wondering if there was a simpler way. Is NumPy > technically > > even faster than just iterating and modifying the list directly? > > > > Also if I'm creating an array then making it, > > Uh, this part of your sentence doesn't quite make sense... > > > why not just do a temporary > > sort and capture the first and last values? Is this method you've > provided > > supposed to be faster? > > Well, unless you're going to use the rest of the sorted values at some > point in your program and since you have a large quantity of data, > yes, my way ought to be faster. Sorting the list is O(N*log(N)) while > running max and min over the list is only O(N). > > Regards, > Chris > > > > > Dave > > > > On Fri, Sep 26, 2008 at 12:42 AM, Chris Rebert wrote: > >> > >> On Thu, Sep 25, 2008 at 8:57 PM, David Di Biase > > >> wrote: > >> > I have a list with about 1000-1500 sub-lists which look like so: > >> > list[-0.28817955213290786, 3.6693631467403929, 'H', > 31.31225233035784]] > >> > > >> > The first and second values are Angstrom units specifying the location > >> > of a > >> > particle. What I'd like to do is determine the distance between the > >> > smallest > >> > and largest value in the arrays first position 0. I tried reading the > >> > manual > >> > for this but I don't see how it applies key or any of those other > >> > commands > >> > to the function. I could easily write a sort to do this and capture > the > >> > first and last spots, but why do that when I can use max and min (if I > >> > can > >> > actually do that...). > >> > >> A. You should probably be using objects rather than arrays to > >> represent your datapoints, so that they're more structured and it's > >> more apparent what the values mean. > >> > >> B. Assuming by "distance" you meant "difference" and/or that the > >> distance is only in 1 dimension: > >> > >> from operator import itemgetter > >> firsts = map(itemgetter(0), main_list) > >> distance = max(firsts) - min(firsts) > >> > >> > > >> > So you wonderful Python gods, lay some knowledge on me. please? lol... > >> > > >> > while I'm at it, is there a way to modify an entire list without > having > >> > to > >> > produce a whole new one? For example now say I want to modify list[0] > >> > and > >> > multiply it by some value. From what I understand previous version of > >> > Python > >> > allowed lists to be multiplied like matrices...now apparently it just > >> > replicates the list. :-/ shucks... > >> > >> You just have to apply the transform to each list element individually > >> (also, you might consider using NumPy [http://numpy.scipy.org/] if > >> you're doing a lot of matrix manipulation): > >> > >> for lst in main_list: > >> lst[0] *= some_value > >> > >> Regards, > >> Chris > >> > >> > > >> > The first question would be useful to know, but the second question I > do > >> > quite a bit of and the "best practice" would be really great to know! > >> > > >> > Thanks in advanced! > >> > > >> > -- > >> > http://mail.python.org/mailman/listinfo/python-list > >> > > >> -- > >> Follow the path of the Iguana... > >> http://rebertia.com > > > > > > > > -- > Follow the path of the Iguana... > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Sun Sep 28 17:02:55 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 28 Sep 2008 16:02:55 -0500 Subject: generate random digits with length of 5 In-Reply-To: References: Message-ID: <48DFF0FF.9070106@tim.thechases.com> > Wondering if there is a better way to generate string of numbers with > a length of 5 which also can have a 0 in the front of the number. If you want to resample the same digit multiple times, either of these two will do: >>> from random import choice >>> ''.join(str(choice(range(10))) for _ in range(5)) '06082' >>> from string import digits >>> ''.join(choice(digits) for _ in range(5)) '09355' If you need to prevent the digits from being reused >>> d = list(digits) >>> random.shuffle(digit) >>> ''.join(d[:5]) '03195' I suspect that the zfill responses don't have the property of equally distributed "randomness", as the first digit may more likely be a zero. The methods here should give equal probabilities for each choice in each place. -tkc From steve at REMOVE-THIS-cybersource.com.au Wed Sep 17 11:12:04 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Sep 2008 15:12:04 GMT Subject: python regex character group matches References: Message-ID: <00e1184f$0$20331$c3e8da3@news.astraweb.com> On Wed, 17 Sep 2008 09:27:47 -0400, christopher taylor wrote: > hello python-list! > > the other day, i was trying to match unicode character sequences that > looked like this: > > \\uAD0X... It is not clear what this is supposed to be. Is that matching a literal pair of backslashes, or a single escaped backslash, or a single unicode character with codepoint AD0X, or what? If I read it *literally*, then you're trying to match: backslash backslash lowercase-u uppercase-A uppercase-D zero uppercase-X Is that what you intended to match? > my issue, is that the pattern i used was returning: > > [ '\\uAD0X', '\\u1BF3', ... ] Unless you are using Python 3, I see that you aren't actually dealing with Unicode strings, you're using byte strings. Is that deliberate? > when i expected: > > [ '\\uAD0X\\u1BF3', ] I make that to be a string of length 12. Is that what you are expecting? >>> len('\\uAD0X\\u1BF3') 12 > the code looks something like this: > > pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) > #print pat.findall(txt_line) > results = pat.finditer(txt_line) First point: I don't think the UNICODE flag does what you think it does. It redefines the meaning of special escape sequences \b etc. Since you aren't using any special escape sequences, I'm going to guess that you think it turns your search string into Unicode. It doesn't. (Apologies in advance if I guessed wrong.) I don't think you need either the UNICODE or LOCALE flag for this search: they don't seem to have any effect. Secondly: you will generally save yourself a lot of trouble when writing regexes to use raw strings, because backslashes in the regex engine clash with backslashes in Python strings. But there's a gotcha: backslash escapes behave differently in ordinary strings and the re engine. In an ordinary string, the sequence backslash-char is treated as a literal backslash-char if it isn't a special escape. So: >>> len('\t') # special escape 1 >>> len('\u') # not a special escape 2 But that's not the case in the re engine! As the Fine Manual says: The special sequences consist of "\" and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. For example, \$ matches the character "$". http://docs.python.org/lib/re-syntax.html So all of these match the same thing: re.compile('\\u') re.compile(r'\u') re.compile('u') To match a literal backslash-u, you need to escape the backslash before the engine joins it to the u: r'\\u'. Putting it all together again: pat = re.compile(r"(\\u[0-9A-F]{4})+") will probably do what you want, assuming I have guessed what you want correctly! -- Steven From skip at pobox.com Thu Sep 11 16:40:26 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 11 Sep 2008 15:40:26 -0500 Subject: Is len O(n) or O(1) ? In-Reply-To: <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> Message-ID: <18633.33338.617152.517916@montanaro-dyndns-org.local> >> ok but if len is O(1) then it doesnt matter? compared to >> if not lista: >> return [] >> i mean. Depends on how often the test is performed, e.g.: >>> def f(a): ... if not a: return [] ... >>> dis.dis(f) 2 0 LOAD_FAST 0 (a) 3 JUMP_IF_TRUE 5 (to 11) 6 POP_TOP 7 BUILD_LIST 0 10 RETURN_VALUE >> 11 POP_TOP 12 LOAD_CONST 0 (None) 15 RETURN_VALUE >>> def g(a): ... if not len(a): return [] ... >>> dis.dis(g) 2 0 LOAD_GLOBAL 0 (len) 3 LOAD_FAST 0 (a) 6 CALL_FUNCTION 1 9 JUMP_IF_TRUE 5 (to 17) 12 POP_TOP 13 BUILD_LIST 0 16 RETURN_VALUE >> 17 POP_TOP 18 LOAD_CONST 0 (None) 21 RETURN_VALUE Even though len(a) is O(1) it's going to have a much larger constant coefficient because of the lookup and call to len(). Skip From jobs at omacindustries.com Mon Sep 8 12:51:59 2008 From: jobs at omacindustries.com (jobs at omacindustries.com) Date: Mon, 8 Sep 2008 09:51:59 -0700 (PDT) Subject: Calling Common Lisp Game Developers Message-ID: We are currently seeking talented Lisp Game Developers who are passionate about game development and want to play a major role in developing and maintaining new features for one of our persistent browser games. This particular title uses Hunchentoot, but all other code has been developed in house using the Mnesia database for persistence. This particular game is not released yet but has already generated interest from over 35,000 players globally. If you?re interested in developing Persistent Browser Games using SBCL and want to know more then send us an email at lisp at omacindustries.com The preferred location for this role is in Dublin, Ireland but we are also open to hearing from anyone who prefers to work remotely. http://omacindustries.com From wegwerp at gmail.com Fri Sep 26 17:42:26 2008 From: wegwerp at gmail.com (Bas) Date: Fri, 26 Sep 2008 14:42:26 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> <7b1181e9-16a2-458a-8677-a2d8d7c8a961@l42g2000hsc.googlegroups.com> Message-ID: <05d9ca4d-441e-484b-ba1b-9e0ef7fa4658@d70g2000hsc.googlegroups.com> On Sep 26, 10:33?pm, afrogazer wrote: > rad_angles = [elem*(pi/180) for elem in angles] You are missing some more on a friday afternoon: angles is created by arange, so it is a numpy array. In that case you simply can do rad_angles = pi/180 * angles No need to use list-comprehensions, that is the whole idea about using these kick-ass objects! Bas From keosophon at gmail.com Wed Sep 17 23:20:18 2008 From: keosophon at gmail.com (Keo Sophon) Date: Thu, 18 Sep 2008 10:20:18 +0700 Subject: How to Determine Name of the Day in the Week In-Reply-To: References: Message-ID: <48D1C8F2.6040308@gmail.com> Fredrik Lundh wrote: > Henry Chang wrote: > >> Instead of getting integers with weekday(), Monday == 0 ... Sunday == >> 6; is there a way to get the actual names, such as "Monday ... >> Sunday"? I would like to do this without creating a data mapping. :) > > if you have a datetime or date object, you can use strftime with the > appropriate formatting code. see the library reference for details. > > if you have the weekday number, you can use the calender module: > > >>> import calendar > >>> calendar.day_name[0] > 'Monday' > > (the latter also contains abbreviated day names, month names, and a > bunch of other potentially useful functions and mappings.) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I've tried calendar.month_name[0], it displays empty string, while calendar.month_name[1] is "January"? Why does calendar.month_name's index not start with index 0 as calendar.day_name? Thanks, Sophon From tgrav at mac.com Sat Sep 6 21:47:33 2008 From: tgrav at mac.com (Tommy Grav) Date: Sat, 06 Sep 2008 21:47:33 -0400 Subject: Setter Propertys' mro? In-Reply-To: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> References: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> Message-ID: <70768920-25BF-4F69-9DE2-8C62AEED6C92@mac.com> On Sep 6, 2008, at 9:15 PM, cipher wrote: > Whats the mro (method resolution order) of a setter property (__set__ > on a descriptor). > i seem to be experiencing some weird issue with them. > for example > >>>> class test: You have to use class test(object). Only new style classes accepts properties. Cheers Tommy From google at mrabarnett.plus.com Wed Sep 3 18:40:35 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 3 Sep 2008 15:40:35 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: On Sep 3, 8:18?pm, Laszlo Nagy wrote: > bearophileH... at lycos.com wrote: > > Empty Python lists [] don't know the type of the items it will > > contain, so this sounds strange: > > >>>> sum([]) > > > 0 > > > Because that [] may be an empty sequence of someobject: > > You are right in that sum could be used to sum arbitrary objects. > However, in 99.99% of the cases, you will be summing numerical values. > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > is very logical to return zero for empty sequences. > > Same way, if we would have a prod() function, it should return one for > empty sequences because X*1 = X. The neutral element for this operation > is one. > > Of course this is not good for summing other types of objects. But how > clumsy would it be to use > > sum( L +[0] ) > > or > > if L: > value = sum(L) > else: > value = 0 > > instead of sum(L). > > Once again, this is what sum() is used for in most cases, so this > behavior is the "expected" one. > > Another argument to convince you: the sum() function in SQL for empty > row sets returns zero in most relational databases. > > But of course it could have been implemented in a different way... I > believe that there have been excessive discussions about this decision, > and the current implementation is very good, if not the best. > An alternative would be for the start value to default to None, which would mean no start value. At the moment it starts with the start value and then 'adds' the items in the sequence to it, but it could start with the first item and then 'add' the following items to it. So: sum([1, 2, 3]) => 6 sum(["a", "b", "c"]) => "abc" For backward compatibility, if the sequence is empty and the start value is None then return 0. From cjstevens at gmail.com Mon Sep 8 01:19:57 2008 From: cjstevens at gmail.com (cjstevens at gmail.com) Date: Sun, 7 Sep 2008 22:19:57 -0700 (PDT) Subject: Spotlight Searching in Python - Mac OSX Message-ID: <09177d14-a692-4e47-9759-51ad52e38500@s1g2000pra.googlegroups.com> Hi all, I'm having some issues getting a spotlight search to work similar to the program demonstrated here: http://pyobjc.sourceforge.net/examples/pyobjc-framework-Cocoa/AppKit/PredicateEditorSample/ Here is my class, complete with the code I am trying to use it with at the end. import objc, sys, os, osax, time from Foundation import * from ScriptingBridge import * from appscript import * class SystemBridge(NSObject): """Class to use the scripting bridge to interact with the system""" _hideapp = objc.ivar(u"hideapp") _volume = objc.ivar(u"volume") _filename = objc.ivar(u"filename") _filetype = objc.ivar(u"filetype") _auth = objc.ivar(u"auth") _logout = objc.ivar(u"logout") query = objc.ivar(u"query") StdAdditions = osax.ScriptingAddition() def init(self): super(SystemBridge, self).init() # create and initalize our query self.query = NSMetadataQuery.alloc().init() # setup our Spotlight notifications nf = NSNotificationCenter.defaultCenter() nf.addObserver_selector_name_object_(self, 'queryNotification:', None, self.query) # XXX: this framework isn't wrapped yet! self.query.setSortDescriptors_([NSSortDescriptor.alloc().initWithKey_ascending_('kMDItemDisplayName', True)]) self.query.setDelegate_(self) return self def hideApplication_(self, _hideapp): app(u'System Events').processes[_hideapp].visible.set(False) def loadResultsFromQuery_(self, notif): results = notif.object().results() NSLog("search count = %d", len(results)) # iterate through the array of results, and match to the existing stores for item in results: nameStr = item.valueForAttribute_('kMDItemDisplayName') print nameStr def queryNotification_(self, note): # the NSMetadataQuery will send back a note when updates are happening. # By looking at the [note name], we can tell what is happening if note.name() == NSMetadataQueryDidStartGatheringNotification: # the query has just started NSLog("search: started gathering") elif note.name() == NSMetadataQueryDidFinishGatheringNotification: # at this point, the query will be done. You may recieve an update # later on. NSLog("search: finished gathering"); self.loadResultsFromQuery_(note) elif note.name() == NSMetadataQueryGatheringProgressNotification: # the query is still gathering results... NSLog("search: progressing...") elif note.name() == NSMetadataQueryDidUpdateNotification: # an update will happen when Spotlight notices that a file as # added, removed, or modified that affected the search results. NSLog("search: an update happened.") def spotlightFriendlyPredicate_(self, predicate): if predicate == NSPredicate.predicateWithValue_(True) or predicate == NSPredicate.predicateWithValue_(False): return False elif isinstance(predicate, NSCompoundPredicate): type = predicate.compoundPredicateType() cleanSubpredicates = [] for dirtySubpredicate in predicate.subpredicates(): cleanSubpredicate = self.spotlightFriendlyPredicate_( dirtySubpredicate) if cleanSubpredicate: cleanSubpredicates.append(cleanSubpredicate) if len(cleanSubpredicates) == 0: return None else: if len(cleanSubpredicates) == 1 and type != NSNotPredicateType: return cleanSubpredicates[0] else: return NSCompoundPredicate.alloc().initWithType_subpredicates_(type, cleanSubpredicates) else: return predicate def createNewSearchForPredicate_(self, predicate): # Format search file type thePredicate = NSPredicate.predicateWithFormat_( "(kMDItemContentType = 'com.apple.iwork.keynote.key')") tempPredicate = NSPredicate.predicateWithFormat_( "(kMDItemDisplayName IN[c] 'preso')") predicate = NSCompoundPredicate.andPredicateWithSubpredicates_( [thePredicate, tempPredicate]) self.query.setPredicate_(predicate) self.query.startQuery() def changeVolume_(self, setvolume): self.StdAdditions.set_volume(output_volume=setvolume) def getVolume_(self): return StdAdditions.get_volume_settings()[k.output_volume] _x = SystemBridge.alloc().init() #predicate = u"kMDItemDisplayName IN[c] 'preso'" #predicate = _x.spotlightFriendlyPredicate_(predicate) if predicate is not None: _x.createNewSearchForPredicate_(predicate) As you can see, I am trying to use a notifier just like the example linked above. The class does not work as expected, and just displays "search: started gathering", none of the other notifier events happen at all! Have I missed something out translating this to PyObjC? The weird thing is, most of that code is straight from the example which works fine, so I can't figure out why mine won't work! Any help would be hugely appreciated, I need to get this finished soon! From gagsl-py2 at yahoo.com.ar Wed Sep 3 05:44:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 06:44:51 -0300 Subject: Problems with running Python CGI Scripts References: <20080903082939.CKJ85501@mail1.edb.st.com> Message-ID: En Wed, 03 Sep 2008 05:29:39 -0300, Edward FISHER escribi?: > I can get the script to run the python script but all that happens is > that the black python box appears then disapears, the html that the > python scripts should generate is never output. > [...] > This is calling the pyc file of the python script. I dont understand why > if i call the py file itself all i get returned is the plain text of the > python file. That's a server setting (Apache or whatever) - make sure it is configured to *execute* the script. > The python script is: > > #!/usr/local/bin/python > import cgi > > def main(): > print "Content-type: text/html\n" I hope this is just the way you posted your message, but remember that in Python indentation is important. The above code isn't valid. Once you are sure that your script doesn't have syntax errors, add this lines on the top to help debugging: import cgitb; cgitb.enable() -- Gabriel Genellina From ewertman at gmail.com Fri Sep 12 13:28:09 2008 From: ewertman at gmail.com (Eric Wertman) Date: Fri, 12 Sep 2008 13:28:09 -0400 Subject: Which version In-Reply-To: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> References: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> Message-ID: <92da89760809121028s1d9b8b46g464d54937c67ba0f@mail.gmail.com> > I'm a reasonably experienced in other languages and have just decided to > get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed, > is this good enough to start out with or am I likely to encounter bugs that > have been fixed in later versions. I'm sure there will be other opinions. I try to use the stock distro version whenever possible, just because it makes administration easier and you have some reasonable guess as to where your code will work if you move it. I use 2.4 regularly, and haven't come across many things that the 2.5 series would make behave differently. The subprocess module is one though, and I recall a few datetime routines that were 2.5 only that I wished I could use. If you aren't married to you linux distro, you might switch to ubuntu... I believe they package the 2.5 series. IMO it's not wrong to compile a new one alongside the stock installation, but you could run into potentially confusing issues later about which one exactly you are using, installing modules for, etc. Easy to avoid if you know what you are doing, but a potential pitfall for a beginner. Eric From george at george-net.de Tue Sep 16 07:39:03 2008 From: george at george-net.de (Georg Altmann) Date: Tue, 16 Sep 2008 13:39:03 +0200 Subject: A unique instance of Python GUI program In-Reply-To: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Message-ID: akineko schrieb: > Hello everyone, > > This may not be a Python specific challenge. > I have a GUI program written in Python + Tkinter. > It works very well. > > Now, I would like to start it from a shell script. > As my GUI program includes a server, it should not have more than one > instance. > Is there any easy way to check if another instance of the program is > already running. > > I vaguely remember that Windows programming provides a way to check. On windows a mutex does the job, see CreateMutex in the windows api. > A platform independent approach would be nice but a solution for X is > sufficient for my application. I'm not familiar with Tkinter - you might want to check if it supports mutexes. Though I'm not sure if mutexes are cross-process (system wide) on all platforms. Regards Georg From castironpi at gmail.com Wed Sep 17 01:26:43 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 22:26:43 -0700 (PDT) Subject: minimum install & pickling Message-ID: Sometimes questions come up on here about unpickling safely and executing foreign code. I was thinking a minimum install that didn't even have access to modules like 'os' could be safe. (Potentially.) I have time to entertain this a little, though all the devs are busy. I can bring it up again in a few months if it's a better time. I browsed for info on 'rexec'. Two c-l-py threads: http://mail.python.org/pipermail/python-dev/2002-December/031160.html http://mail.python.org/pipermail/python-dev/2003-January/031848.html A lot of modules would have to go. IPC modules: subprocess, socket, signal, popen2, asyncore, asynchat. ctypes, mmap, platform.popen, glob, shutil, dircache, and many more. I tested it out. I renamed the 'Lib' directory and ran. 'import site' failed; use -v for traceback Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os ImportError: No module named os >>> import socket ImportError: No module named socket >>> del __builtins__.__import__ >>> __import__ NameError: name '__import__' is not defined >>> del __builtins__.open, __builtins__.file >>> open NameError: name 'open' is not defined >>> file NameError: name 'file' is not defined Even a function created from raw bytecode string can't do anything without __import__ or 'open'. And you can't get a second instance running without subprocess or os.system. 'rexec' may be full of swiss cheese and irreparable, but maybe it would work to start from bare-bones and add pieces known to be safe. This sort of thing wouldn't need and standard library support either, I don't think. From deets at nospam.web.de Tue Sep 9 11:55:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 Sep 2008 17:55:43 +0200 Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> Message-ID: <6inkkiFrbptbU1@mid.uni-berlin.de> Luigi wrote: > Dear all, > > I'm writing an XML-RPC server which should be able to modify the > incoming request before dispatching it. In particular I wand to added > two fixed parameters to the method called: one is the client host > address, and the other is the user name provided as for Basic > Authentication (http://user at www.bla-bla.com). > > To do this, at the present I've overwritten the do_POST method of > SimpleXMLRPCRequestHandler, including at a certain point this code: > > .... > data = ''.join(L) > > params, method = xmlrpclib.loads(data) > user = "unknown" > if self.headers.has_key('Authorization'): > # handle Basic authentication > (enctype, encstr) = self.headers.get('Authorization').split() > user, password = base64.standard_b64decode(encstr).split(':') > params = list(params) > params.append(self.address_string()) > params.append(user) > params = tuple(params) > data = xmlrpclib.dumps(params, methodname=method) > > (I slightly modified it to make it more readable at mail level) > > It works, but I don't really like it because it completely overwrites > the do_POST method that in the future Python releases is going to > change (I verified it). Do you know a better way to do this? I would go for a slightly different approach: make your server have a dispatch-method that delegates the calls to the underlying actual implementation. But *before* that happens, extract the information as above, and either - prepend it to the argument list - stuff it into threadlocal variables, and only access these if needed in your implementation. Diez From fredrik at pythonware.com Wed Sep 10 14:15:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 20:15:50 +0200 Subject: subprocess.Popen hangs at times? In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > When making calls of the form Popen(cmd, shell=True, > stdout=subprocess.PIPE), we've been getting occasional, predictable > hangs. Will Popen accumulate a certain amount of stdout and then block > until its read? the pipe provided by the operating system has a limited buffer size (usually just a few kilobytes). when the buffer fills up, the operating system will halt the external process. From fredrik at pythonware.com Mon Sep 22 12:32:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Sep 2008 18:32:35 +0200 Subject: Why are "broken iterators" broken? In-Reply-To: <20080922043217.GA10077@cskk.homeip.net> References: <20080922043217.GA10077@cskk.homeip.net> Message-ID: Cameron Simpson wrote: >> you probably want the consumer thread to block when it catches up with >> the producer, rather than exit. > > It sounds like he wants non-blocking behaviour in his consumer. Roy gave an example, he didn't post a requirements specification. > A common example is "try to gather a lot of stuff into a single packet, > but send a smaller packet promptly if there isn't much stuff". that use case is better solved with a plain list object. no need to make things harder than they are. From rmoore787 at gmail.com Sat Sep 27 18:06:25 2008 From: rmoore787 at gmail.com (Robert Moore) Date: Sat, 27 Sep 2008 15:06:25 -0700 Subject: Configuring pyc directory Message-ID: Is there a way to configure python to read/write compiled pyc files for modules in a directory other than the directory containing the original py files? I'm trying trying to secure an Apache server running mod_python and don't want the process compiling the pyc files to have write access to the folder containing my site's py modules. I realize the solution (if it exists) may lie with mod_python rather than python itself, so I've also pinged the mod_python mailing list for help. I'm checking here as well, though, just in case there's some solution built into python. Thanks, Robert -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Mon Sep 8 16:52:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Sep 2008 16:52:21 -0400 Subject: universal unicode font for reportlab In-Reply-To: <48C55E7B.9090807@shopzeus.com> References: <87r67vj7f1.fsf@benfinney.id.au> <48C51E49.2070202@shopzeus.com> <48C52635.1030709@shopzeus.com> <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> Message-ID: > The simplest solution would be to use a font that is able to handle all > encodings that I need. My OpenOffice on WinXP uses a unicode font, I believe Lucida Sans Unicode, that seems to cover the entire BMP. I don't know whether it was already installed or installed by OO or how one would get to it to extract it. From simon at brunningonline.net Thu Sep 4 03:04:51 2008 From: simon at brunningonline.net (Simon Brunning) Date: Thu, 4 Sep 2008 08:04:51 +0100 Subject: Coming from .NET and VB and C In-Reply-To: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> Message-ID: <8c7f10c60809040004j6d517130jd5028b955044d81b@mail.gmail.com> 2008/9/3 Dennis Lee Bieber : > non-relational DBMS (if any such are still in use), There certainly are... >> SO, I'm interested in using my Google App space (free 500MB) to >> develop a quick database application. Using Python. I found "Dive >> Into Python" which I will be reading shortly. >> > So one question: what RDBMs are supported in that space? ... and the Google's BigTable (see ) is one of them. -- Cheers, Simon B. From dmitry at makovey.net Sat Sep 27 23:38:27 2008 From: dmitry at makovey.net (Dmitry S. Makovey) Date: Sun, 28 Sep 2008 03:38:27 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> <91e62d70-73fb-4ecc-ae2e-d950a5f7ea6b@k13g2000hse.googlegroups.com> Message-ID: George Sakkis wrote: > It's funny how often you come with a better solution a few moments > after htting send! The snippet above can (ab)use the decorator syntax > so that it becomes: > > class A(Proxy): > > @ProxyMethod > def bmethod(self): > return self.b1 > > @ProxyMethod > def bmethod2(self): > return self.b2 That is outstanding! This code looks very clean to me (just a touch cryptic around declarations in A, but that was unavoidable anyway). Seems like the right way to read it would be bottom up (or is it only my mind so perverted?). By the looks of it - it does exactly what I needed with great number of possibilities behind it and is very lightweight and transparent. Now I regret I haven't come up with it myself :-D George, at this point I'm out of rugs - so no more rug pulling from under your feet for me. Now I'm going to apply all this knowledge to my code, see how that goes and come back with more questions later. Thank you (all) very much for a great discussion. This thread educated me quite a bit on descriptors and why one would need them, and decorators - just as subject line suggested, were not forgotten. From tjreedy at udel.edu Fri Sep 26 02:20:08 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 02:20:08 -0400 Subject: Comparing float and decimal In-Reply-To: <99a7ab2c-601e-47fe-8ece-5f9150c10f7a@k30g2000hse.googlegroups.com> References: <20080923072012.57d8d329.darcy@druid.net> <99a7ab2c-601e-47fe-8ece-5f9150c10f7a@k30g2000hse.googlegroups.com> Message-ID: Mark Dickinson wrote: > On Sep 24, 6:18 pm, Terry Reedy wrote: >> If there is not now, there could be in the future, and the decimal >> authors are committed to follow the standard wherever it goes. >> Therefore, the safe course, to avoid possible future deprecations due to >> doing too much, is to only do what is mandated. > > Makes sense. It looks as though the standard's pretty stable now > though; I'd be quite surprised to see it evolve to include discussion > of floats. But then again, people thought it was stable just before > all the extra transcendental operations appeared. :-) What got me were the bizarre new 'logical' operations whose addition were rather nonsensical from a Python viewpoint (though probably sensible from an IBM profit business viewpoint). With those added, and with this thread, I have decided that Decimals best be thought of as a separate universe, not to be mixed with other numbers unless one has good reason to and understands the possible anomalies of doing so. For pure finance apps, I would think that there should be little reason to mix. tjr From martindemello at gmail.com Thu Sep 4 16:59:16 2008 From: martindemello at gmail.com (Martin DeMello) Date: Thu, 4 Sep 2008 13:59:16 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: On Sep 4, 1:51?pm, Fredrik Lundh wrote: > Martin DeMello wrote: > > I'm writing a cluster monitor, that collects information from a set of > > machines and logs it to a database > > > In the interests of not hammering the db unnecessarily, I'm > > considering the following > > 1. A series of independent "monitor" threads that collect information > > over TCP from the cluster of machines, and write it to a queue > > 2. A "logger" thread that empties the queue every second or so and > > inserts the collected information to the db via a single insert > > statement > > why are you using a queue for this case, btw? ?why not just use a plain list > > ? ? ?L = [] > ? ? ?lock = threading.Lock() Good point - I thought of queue because it was self-locking, but you're right, I can as well use a simple list and lock it myself. martin From moijes12 at gmail.com Thu Sep 4 08:03:57 2008 From: moijes12 at gmail.com (moijes12) Date: Thu, 4 Sep 2008 05:03:57 -0700 (PDT) Subject: help in execfile function Message-ID: <8a3a0376-7146-44f9-beb6-e1ad7a612ad8@l33g2000pri.googlegroups.com> Hi i have 3 python files and i want to execute the files sequentially using the execfile command.Hence ,i have written the following program fileList = ["a.py","b.py","c.py"] for fileName in fileList : execfile(fileName) however,when i try running it,the program keeps calling execfile on a.py and thus an infinite loop is created.I am running this on Windows XP. Please suggest a sloution whereby i can use execfile to execute all files in fileList.Please tell me where in my program i may have gone wrong. moijes12 From tino at wildenhain.de Tue Sep 2 11:40:49 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 02 Sep 2008 17:40:49 +0200 Subject: dict.update In-Reply-To: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> Message-ID: <48BD5E81.8060407@wildenhain.de> Mike P wrote: > Hi All, > > I have two dictionaries e.g > dict1 = {123:3,234:5,456:3} > dict2 = {123:4,157:2,234:5,456:3,567:2} > > I want to merge these two dictionaries together so i have a resultant > dictionary of: > > dict3 = {123:[4,3],157:[2,0],234:[5,5],456:[3,3],567:[2,0]} > > As later on i want to write a csv file that would have the form > > id var1 var2 > 123 4 3 > 157 2 0 > > i looks like the dict.update looks almost there but i can't get it to > work properly, can anyone offer any advise? result=dict((key,(dict1.get(key,None), dict2.get(key,None))) for key in set(dict1.keys()+dict2.keys()) ) (untested) should provide you with a resulting dictonary with tuples where [0] is var1 and [1] is var2, None for values not in one of the dictionaries (you can put in 0 if you prefer). You can use it like so to generate your output: allitems=result.items() allitems.sort() # sort based on keys as first tuple element for (key,(var1,var2)) in allitems: print key,var1,var2 HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From hrishys at yahoo.co.uk Wed Sep 24 11:25:01 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Wed, 24 Sep 2008 15:25:01 +0000 (GMT) Subject: Linq to Python In-Reply-To: Message-ID: <319386.9452.qm@web27402.mail.ukl.yahoo.com> Hi Tom This is what i like and feel of the Python programmers smarter then every other langauge i know of. But i am not comfortable with your second statement XML i never need it one day everybody would need it. regards Hrishy --- On Tue, 23/9/08, Thomas G. Willis wrote: > From: Thomas G. Willis > Subject: Re: Linq to Python > To: python-list at python.org > Date: Tuesday, 23 September, 2008, 7:45 PM > > But surely the idea behind it will eventually spread. > ?It's really > > just comprehensions generalized over XML and > relational datasets, a > > noble goal. ?Besides, it's main purpose for .NET > was to bring > > functional programming to it. ?Python already has > that, somewhat... > > it's really any object out of the box, i think the sql > linq stuff is > more of a query compiler, IMO sqlalchemy does that. > > > query = select(user_cols, > > and_(table_relationship.c.accept_user_id==user.id, > > table_relationship.c.start_date==None > > ), > > from_obj=join( > > table_relationship,table_user, > > > onclause=table_user.c.id==table_relationship.c.init_user_id > > ).outerjoin(table_profile) > > ) > > session.execute(query).fetchall() > > > > > > > XML? meh hopefully I would never need it. :) > > > C# is my day job, and when I got my hands on LINQ back in > January my > initial thought was "Finally I have list > comprehensions!!!! day job is > fun again" > > For the most part, I think C# is catching up. > -- > http://mail.python.org/mailman/listinfo/python-list From arnodel at googlemail.com Mon Sep 22 05:52:39 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 22 Sep 2008 02:52:39 -0700 (PDT) Subject: A bit weird dictionary behavior References: Message-ID: <1669f0d5-fd1c-4c92-a73f-2ce00bd8dd91@a1g2000hsb.googlegroups.com> On 22 Sep, 10:25, "Pekka Laukkanen" wrote: > Hello, > > just noticed this: > > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> {1: 2} > {1: 2} > >>> {True: False} > {True: False} > >>> {1: 2, True: False} > > {1: False} > > This must be because > > >>> True == 1 and True in {1: 2} > > True That's exactly the reason! > but it still doesn't feel exactly right. Would it be worth submitting a bug? I don't think it can be considered as a bug, for the reason you gave above and because dictionary keys are by definition unique with respect to equality. Perhaps you could call it a "surprising feature" :) -- Arnaud From steve at REMOVE-THIS-cybersource.com.au Mon Sep 22 19:16:45 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 23:16:45 GMT Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <00e45101$0$20331$c3e8da3@news.astraweb.com> <773db59e-40c6-470e-b616-ca8715efa46a@d77g2000hsb.googlegroups.com> Message-ID: <00e82140$0$20303$c3e8da3@news.astraweb.com> On Mon, 22 Sep 2008 04:21:12 -0700, bearophileHUGS wrote: > Steven D'Aprano: > >>Extending len() to support iterables sounds like a good idea, except >>that it's not.< > > Python language lately has shifted toward more and more usage of lazy > iterables (see range lazy by default, etc). So they are now quite > common. So extending len() to make it act like leniter() too is a way to > adapt a basic Python construct to the changes of the other parts of the > language. I'm sorry, I don't recognise leniter(). Did I miss something? > In languages like Haskell you can count how many items a lazy sequence > has. But those sequences are generally immutable, so they can be > accessed many times, so len(iterable) doesn't exhaust them like in > Python. So in Python it's less useful. In Python, xrange() is a lazy sequence that isn't exhausted, but that's a special case: it actually has a __len__ method, and presumably the length is calculated from the xrange arguments, not by generating all the items and counting them. How would you count the number of items in a generic lazy sequence without actually generating the items first? > This is a common situation where I can only care of the len of the g > group: > [leniter(g) for h,g in groupby(iterable)] > > There are other situations where I may be interested only in how many > items there are: > leniter(ifilter(predicate, iterable)) leniter(el for el in iterable if > predicate(el)) > > For my usage I have written a version of the itertools module in D (a > lot of work, but the result is quite useful and flexible, even if I miss > the generator/iterator syntax a lot), and later I have written a len() > able to count the length of lazy iterables too (if the given variable > has a length attribute/property then it returns that value), I'm not saying that no iterables can accurately predict how many items they will produce. If they can, then len() should support iterables with a __len__ attribute. But in general there's no way of predicting how many items the iterable will produce without iterating over it, and len() shouldn't do that. > and I have > found that it's useful often enough (almost as the string.xsplit()). But > in Python there is less need for a len() that counts lazy iterables too > because you can use the following syntax that isn't bad (and isn't > available in D): > > [sum(1 for x in g) for h,g in groupby(iterable)] sum(1 for x in > ifilter(predicate, iterable)) sum(1 for el in iterable if predicate(el)) I think the idiom sum(1 for item in iterable) is, in general, a mistake. For starters, it doesn't work for arbitrary iterables, only sequences (lazy or otherwise) and your choice of variable name may fool people into thinking they can pass a use-once iterator to your code and have it work. Secondly, it's not clear what sum(1 for item in iterable) does without reading over it carefully. Since you're generating the entire length anyway, len(list(iterable)) is more readable and almost as efficient for most practical cases. As things stand now, list(iterable) is a "dangerous" operation, as it may consume arbitrarily huge resources. But len() isn't[1], because len() doesn't operate on arbitrary iterables. This is a good thing. > So you and Python designers may choose to not extend the semantics of > len() for various good reasons, but you will have a hard time convincing > me it's a useless capability :-) I didn't say that knowing the length of iterators up front was useless. Sometimes it may be useful, but it is rarely (never?) essential. [1] len(x) may call x.__len__() which might do anything. But the expected semantics of __len__ is that it is expected to return an int, and do it quickly with minimal effort. Methods that do something else are an abuse of __len__ and should be treated as a bug. -- Steven From bedouglas at earthlink.net Tue Sep 2 01:31:53 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 1 Sep 2008 22:31:53 -0700 Subject: python XPATH question - mechanize/libxml2dom Message-ID: <109a01c90cbd$3611ac90$0301a8c0@tmesa.com> hi... i can use an xpath query to create a node from an html/dom representation. however, if i have a node, is there a way to generate an xpath query from the node. in testing with firefox/dom inspector, i can use "ancestor::*", but i can't determine where/how to implement this using mechanize/libxml2dom thanks From mhuening at zedat.fu-berlin.de Mon Sep 8 06:13:58 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Mon, 08 Sep 2008 12:13:58 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: References: <6ii9jbFqoe2eU1@mid.uni-berlin.de> Message-ID: <6ikc76Fr32cnU1@mid.uni-berlin.de> Gerhard H?ring (08.09.2008 10:12): > >> Error is: >> >> con.execute("select load_extension('./fts3.so')") >> pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht >> gefunden. >> >> Where should I look for the module? > > The sources are in ext/fts3 in the SQLite source tree. I haven't found > any Makefile, so I it myself using this gcc command: > > $ cd .../ext/fts3 > $ gcc -shared -o ~/src/gh/pysqlite/build/lib.linux-i686-2.5/fts3.so *.c > -lsqlite3 > Thanks! Will fts3 be integrated in the Python 2.6 release? Matthias From circularfunc at yahoo.se Tue Sep 16 09:27:53 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 06:27:53 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? References: Message-ID: <92d472c8-4af1-432a-a240-f9f9c97686eb@m73g2000hsh.googlegroups.com> i can run the interpreter. its just i cant load a file into it. i tried adding your suggestion but it didnt help. i dont think thats the issue though. From jonathon.blake at gmail.com Mon Sep 8 23:41:55 2008 From: jonathon.blake at gmail.com (jonathon) Date: Mon, 8 Sep 2008 20:41:55 -0700 Subject: a11y & python Message-ID: All: A year or so ago, I read a tutorial on writing self-voicing apps using python. It also covered other a11y issues. However, I didn't bookmark it, and it doesn't show up in the first 1000 hits on the Google search I did. Can somebody point me to either that, or any other tutorials on programming a11y into python. ### This was triggered by a request by my housemate for a self-voicing program that does household inventory control, that can print to Braille. xan jonathon From stef.mientki at gmail.com Sat Sep 13 09:27:17 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 13 Sep 2008 15:27:17 +0200 Subject: A service for testing Python code on multiple platforms and versions In-Reply-To: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> References: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> Message-ID: <48CBBFB5.1030202@gmail.com> David Moss wrote: > Hopefully a service like this already exists and I just haven't found > it yet. If not it could be an idea for some kind soul(s) to pick up > and run with ;-) > > As someone who writes and releases Python modules for the community, I > find it difficult to have a decent level of confidence in the efficacy > of my code on platforms and Python versions other than those that I > own or use regularly. My documentation states that I support Python > 2.3 or higher. This ends up being more of a statement of good > intentions than a one of fact. > > A case in point. A bug (in Python), that I believed to have been > killed off after Python 2.2, resurfaced in a 2.4.x release of Python > on PowerPC recently. As I don't own any PowerPC kit, it was very > difficult to a) investigate the bug and b) create an effective fix for > it in a timely fashion. Fortunately I'd come across it before so the > fix was easy but it might not have been. > > While I realise one's code can never be perfect, you can cover for > these sorts of eventualities fairly easily by running your software > and unit tests under different environments. You'd also like to be > able to do this on a continual basis rather than just once or twice. > If this was done with some kind of automated testing and reporting so > much the better. Bigger projects that take code quality seriously > probably already have this sort of thing in place for their own > purposes, but for smaller ones it just isn't possible. > > Wouldn't it be great to have a service/setup out there available for > Python developers to access that covered a fairly broad base of > possible Python installations for the purpose of improve overall code > quality? Am I the only one that would find something like this useful? > I would love to have such a tool, but have no idea how to create something like that. Something like a multi-virtual machine on a web server, that you launch in the night, and in the morning you would get a full report of all problems on the specific OSs (probably someone is going to say that this is impossible, but fortunately I'm not hindered by any knowledge ;-) cheers, Stef > Dave M. > -- > http://mail.python.org/mailman/listinfo/python-list > From durand1 at gmail.com Sat Sep 6 12:03:11 2008 From: durand1 at gmail.com (Durand) Date: Sat, 6 Sep 2008 09:03:11 -0700 (PDT) Subject: Overlapping axis text References: Message-ID: Err...made a mistake there. days = WeekdayLocator() # every monday months = MonthLocator() # every month That doesn't change my question though. Thanks From marco.bizzarri at gmail.com Mon Sep 15 09:06:38 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 15 Sep 2008 15:06:38 +0200 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: References: Message-ID: <3f0d61c40809150606w2b8035b3v2eba46e44cdee9a7@mail.gmail.com> On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal wrote: > Hi, > > I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that > key as string. Is there any way to convert the said instance into string? In case you want to write the pub-key to a file, you can use save_pub_key def save_pub_key(self, file): """ Save the public key to a file in PEM format. @type file: string @param file: Name of file to save key to. """ Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From sierra2 at gmail.com Fri Sep 26 12:43:30 2008 From: sierra2 at gmail.com (Edel SM) Date: Sat, 27 Sep 2008 00:43:30 +0800 Subject: Time.sleep(0.0125) not available within Linux In-Reply-To: References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: helllo, On Fri, Sep 26, 2008 at 3:46 PM, Lawrence D'Oliveiro wrote: > In message <00eb2560$0$20666$c3e8da3 at news.astraweb.com>, Steven D'Aprano > wrote: > >> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: >> >>> Just a thought, your minimum sleep time is probably limited by the >>> resolution of the system "HZ" clock. Type >>> >>> less /proc/config.gz >> >> $ less /proc/config.gz >> /proc/config.gz: No such file or directory >> or: less /boot/config-`uname -r` >> >> What OS are you using? > > The one named in the subject line? > -- > http://mail.python.org/mailman/listinfo/python-list > -- edel From samslists at gmail.com Fri Sep 19 01:34:48 2008 From: samslists at gmail.com (Sam) Date: Thu, 18 Sep 2008 22:34:48 -0700 (PDT) Subject: Program works great, except under less, cron or execl (Unicode?) References: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> <6jekbbF2v55pU2@mid.uni-berlin.de> Message-ID: Diez for the win... :) sys.stdout.encoding does indeed have the proper value when called from the command line of UTF-8. But when piped into anything or called from anywhere it's None. Just for completeness, here's my test program: #!/usr/bin/env python import sys print sys.stdout.encoding And here are the results: $ ./encoding.py UTF-8 $ ./encoding.py | cat None Really, really annoying! So how can I set sys.stdout.encoding so it's UTF-8 when piped through cat (or anything else). I tried assigning to it, but no dice. On Sep 18, 2:12?am, "Diez B. Roggisch" wrote: > Sam wrote: > > I have a program which works great when run from the command line. > > > But when I run it combined with something else such as: > > - piping it through less > > - cron > > - execl (i.e. calling it from another python program) > > > it gives me a unicode error > > > ?File "../myparser.py", line 261, in set_attributes > > ? ? print "self.atd['Name'] is: ", self.atd['Name'] > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in > > position 7: ordinal not in range(128) > > > I'd post the whole program here, except it involves weird Unicode > > strings. > > > I could probably change the program to get it working under less/cron/ > > etc. > > > But I'd rather understand exactly what the issue is. ?Why does it work > > fine when run directly from the command line, but not otherwise? > > Most probably because when to running directly inside a terminal, it gets > it's stdin/stdout as pipes - and python can't attempt to guess the proper > encoding on that, as it does on a terminal. > > And thus, when you print unicode to the pipe, it can't decide which encoding > to use. > > To circumvene this, try & wrap stdout into a codecs-module wrapper with a > proper encoding applied (e.g. utf-8). > > You might make that conditionally based on the sys.stdout.encoding-variable > being set or not, albeit I'm not 100% sure to what it actually gets set > when used in a subprocess. But this should give you the idea where to look. > > Diez From lee.walczak at gmail.com Wed Sep 10 18:32:06 2008 From: lee.walczak at gmail.com (lee.walczak at gmail.com) Date: Wed, 10 Sep 2008 15:32:06 -0700 (PDT) Subject: Wx Python - Code Structure & Event Handling References: <48c6f5d9$0$2923$fa0fcedb@news.zen.co.uk> Message-ID: <220042a1-0532-4343-a956-8d82504739ec@r66g2000hsg.googlegroups.com> Thanks for the feedback. It is greatly appreciated. Let me check out your references and see where they take me. Will post back and let you know how useful this was. thanks! Lee From prologic at shortcircuit.net.au Sun Sep 7 19:14:56 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 09:14:56 +1000 Subject: Updating python dictionary In-Reply-To: <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> Message-ID: On Mon, Sep 8, 2008 at 8:59 AM, John Machin wrote: > What do you mean by "this right"? Perhaps the Divine Right of OPs, > managers, examiners, business analysts, etc never to give a complete > spec up front and never to contemplate the consequences of Murphy's > Law? Now you're being silly. -- -- -- "Problems are solved by method" From steven at REMOVE.THIS.cybersource.com.au Thu Sep 18 01:01:33 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 05:01:33 GMT Subject: How to Determine Name of the Day in the Week References: <0928a498-1cc0-48c7-985e-4faf019d8a70@m3g2000hsc.googlegroups.com> Message-ID: On Wed, 17 Sep 2008 20:34:02 -0700, Mensanator wrote: > And technically, weeks begin on Sunday, not Monday, but business likes > to think of Monday as day 0 of the week and it doesn't conflict with any > prior date format. There's no "technically" about it. It's an arbitrary starting point, and consequently there are different traditions to it, even in English. Besides, I don't think many businesses think of "day 0" at all. Most people outside of IT start counting from 1, not 0. In British Commonwealth countries, Sunday is the last day of the week, not the first, although under American influence that's changing in Australia at least. In Poland, the week begins with Monday ("poniedzia?ek"). Tuesday, "wtorek", means "second day". Other Slavic countries also start with Monday. Similarly, the Lithuanian calendar simple enumerates the days of the week, starting with Monday, "pirmadienis" ("first day"). In China, there are at least three different systems of naming the week days. In two of them, the week starts with Sunday, but in the third system, Sunday is "zhoumo" ("cycle's end") and Monday is zhouyi ("first of cycle"). -- Steven From nytrokiss at gmail.com Mon Sep 29 01:59:01 2008 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 28 Sep 2008 22:59:01 -0700 Subject: Web programming in Python. In-Reply-To: <558b73fb0809281840h26a2fedl65fa7ed5a7dec2a7@mail.gmail.com> References: <558b73fb0809281840h26a2fedl65fa7ed5a7dec2a7@mail.gmail.com> Message-ID: <8a6b8e350809282259t1bb4e8fbs7a7a2f5a2d56c1ab@mail.gmail.com> If you are considering using a framework try Django. I enjoy using it! On Sun, Sep 28, 2008 at 6:40 PM, Michael Crute wrote: > On Sun, Sep 28, 2008 at 6:39 PM, Kurda Yon wrote: > > I am totaly newbie in the Python's web programming. So, I dont even > > know the basic conceptions (but I have ideas about php-web- > > programming). Does it work in a similar way? First, I have to install > > a Python-server? > > There are a couple of different ways to do web development in python. > The easiest if you're familiar with web development in other languages > is through CGI. I would recommend reading up on the python cgi module > [1] which will walk you through the basics of writing your first cgi > program. When you're comfortable with basic cgi you might want to look > into a framework like Django or CherryPy. > > -mike > > [1] http://docs.python.org/lib/module-cgi.html > > -- > ________________________________ > Michael E. Crute > http://mike.crute.org > > God put me on this earth to accomplish a certain number of things. > Right now I am so far behind that I will never die. --Bill Watterson > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ http://www.jewelerslounge.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri Sep 26 19:05:07 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 16:05:07 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: Message-ID: <4b195687-e4a5-4fdd-89b2-f3906e625770@j22g2000hsf.googlegroups.com> On Sep 26, 6:31?am, s... at pobox.com wrote: > I took over spam filter management for the python.org mailing lists a couple > months ago and made a few changes to the way the spam filter is trained. > Things seem to be at a reasonable level as far as I can tell (I see a few > spams leak through each day), though I wasn't actively reading > comp.lang.python/python-l... at python.org before I took over the task, so I > have nothing to compare with. ?Does the level of spam leaking through the > filter now seem excessive? ?Is it more or less than in June and July? > > Thanks, > > Skip Montanaro Is there such a thing as an open-source spam filter? That way any time anyone had spare time and got annoyed, they could dump a short snippet of code into the grinder. Check-in would be tricky. It would need lots of votes, and voters would see a list of retroactive consequences of the change. (Marks these five things as spam.) I'm not sure that the rule-making is any better in the hands of many than it is of one (in general, to the OP), considering the power of stupid in large numbers, and the ease of submitting a filter for 'if name== "D'Aprano"'. That is, surely Skip wouldn't do that, but a group might. I've never gone spamming, so I don't know: Is it really easy (and necessarily profitable) to see, "if 'python' not in contents" and add the word to the mail? Or is it not worth the time it takes to catch that list? They're greedy, not bored. From marco.bizzarri at gmail.com Sat Sep 13 09:56:40 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 13 Sep 2008 15:56:40 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <6ivbfvFnfucU1@mid.uni-berlin.de> References: <6ivbfvFnfucU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> On Fri, Sep 12, 2008 at 4:09 PM, Diez B. Roggisch wrote: > > You should also consider using PEP8 style naming. > > > Diez class FolderInUse: def __init__(self, core): self.core = core def true_for(self, archivefolder): return any([instance.forbid_to_close(archivefolder) for instance in self.core.active_outgoing_registration_instances()]) Is this any better? The true_for name does not satisfy me a lot... maybe because it is too similar to True. Anyway, I'm trying a good naming so that code is readable, like: specification = FolderInUse(core) if specification.true_for(folder): ... Any thought about this? Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From michele at nectarine.it Tue Sep 30 17:25:49 2008 From: michele at nectarine.it (Michele) Date: Tue, 30 Sep 2008 23:25:49 +0200 Subject: md5 hash problems Message-ID: <48e2995e$0$18149$4fafbaef@reader3.news.tin.it> Hi there, why is this code generating a problem? >>> input = open('foo.img','rb').read().decode('ISO-8859-1') >>> import md5 >>> md5.new(input).hexdigest() Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xdc' in position 6: ordinal not in range(128) >>> Thank you. From antroy at gmail.com Fri Sep 19 06:10:10 2008 From: antroy at gmail.com (Ant) Date: Fri, 19 Sep 2008 03:10:10 -0700 (PDT) Subject: Problem with Python shell through Cygwin Screen (Python/Vim/Screen combo) Message-ID: <1e357c83-b53b-4587-a4d3-5327d1762341@k13g2000hse.googlegroups.com> Hi all, There's a sweet combination of tools that you can assemble using Vim, a Python shell (or any shell for that matter) and GNU screen, where you essentially send selected text from Vim to the Python shell. (See http://technotales.wordpress.com/2007/10/03/like-slime-for-vim/ for more details - though I had to tweak the script a bit to get it to work on Windows - line ending interpretation problem) This works great in Linux, and also in Windows using the Cygwin build of Python, but when you call: screen -S py -s python using the Windows build of Python, the shell just hangs. Does anyone know if this is a known issue with screen/Python, or if there is a workaround, as I'd prefer to have just a single Python instance installed rather than having Cygwin python and windows Python both installed. Cheers, Ant. From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 13:19:43 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 19:19:43 +0200 Subject: is decorator the right thing to use? In-Reply-To: References: <48db50aa$0$3750$426a74cc@news.free.fr> Message-ID: <48dbc82e$0$1120$426a74cc@news.free.fr> Dmitry S. Makovey a ?crit : > Thanks Bruno, > > your comments were really helpful (so was the "improved" version of code). > > My replies below: > > Bruno Desthuilliers wrote: >>> So decorators inside of B just identify that those methods will be >>> proxied by A. On one hand from logical standpoint it's kind of weird to >>> tell class that it is going to be proxied by another class, >>> >> Indeed - usually, proxied objects shouldn't have to be aware of the >> fact. That doesn't mean your variation on the proxy pattern is >> necessarily bad design (hard to tell without lot of context anyway...), >> but still there's some alarm bell ringing here IMHO - IOW : possibly the >> right thing to do, but needs to be double-checked. > > I'm kind of looking at options and not dead-set on decorators, but I can't > find any other "elegant enough" solution which wouldn't lead to such tight > coupling. The problem I'm trying to solve is not much more complicated than > what I have already described Well... You didn't mention why you need a proxy to start with !-) > so if anybody can suggest a better approach - > I'm all for it. > (snip code) >> My point is that: >> 1/ you shouldn't have to rewrite a decorator function - with basically >> the same code - for each possible proxy class / attribute name pair combo >> 2/ making the decorator an attribute of the proxy class makes >> dependencies clearer (well, IMHO at least). > > agreed on all points > >> I'm still a bit uneasy wrt/ high coupling between A and B, and if I was >> to end up with such a design, I'd probably take some times to be sure >> it's really ok. > > that is the question that troubles me at this point - thus my original post > (read the subject line ;) ). I like the clarity decorators bring to the > code and the fact that it's a solution pretty much "out-of-the-box" without > need to create something really-really custom, but I'm worried about tight > coupling and somewhat backward logic that they would introduce (the way I > envisioned them). Well... The canonical solution for delegation in Python is using __getattr__. Your problem - according to this post and your answer to Diez - is that your proxy may have to 1/ delegate to more than one object 2/ don't necessarily delegate each and any attribute access I can envision one solution using both __getattr__ and a simple decorator: def proxy(func): func._proxied = True return func class A(object): def __init__(self, delegates): self._delegates = delegates def __getattr__(self, name): for d in self.__delegate: func = getattr(d, name) if callable(func) and getattr(func, '_proxied', False): return func raise AttributeError( 'object %s has no attribute '%s' % (self.__class__, name) ) class B(object): def __init__(self): self.val='bval' @proxy def bmethod(self,a): print "B::bmethod" print a, self.val @proxy def bmethod2(self,a): print "B::bmethod2" print a, self.val class C(object): def __init__(self): self.val='bval' @proxy def cmethod(self,a): print "B::bmethod" print a, self.val @proxy def cmethod2(self,a): print "B::bmethod2" print a, self.val a = A([B(), C()]) # not tested... This solves most of the coupling problems (B and C still have to make clear which methods are to be proxied, but at least they need not know which class will be used as proxy), and makes sure only 'allowed' method calls are delegated. But I wouldn't call it a perfect solution neither. If you do have more than one object having method xxx, only the first one will match... And let's not talk about the lookup penalty. There's a possible variant that avoids the call to __getattr__ (in short: attaching delegation instancemethods to A instance in the initializer for each proxied method in delegates), but that wont solve the problem of potential name clashes. My 2 cents... From maric at aristote.info Wed Sep 3 10:52:06 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 3 Sep 2008 16:52:06 +0200 Subject: properties setting each other In-Reply-To: <200809031644.10870.maric@aristote.info> References: <200809031644.10870.maric@aristote.info> Message-ID: <200809031652.06431.maric@aristote.info> Le Wednesday 03 September 2008 16:44:10 Maric Michaud, vous avez ?crit?: > ? ? ? ? ?def _setsquare(self, v) : > ? ? ? ? ? ? ? ? ?# some extra logic here > ? ? ? ? ? ? ? ? ?self._square = s > > ? ? ? ? ?def fsetsquare(self,s): > ? ? ? ? ? ? ? ? ?self._setsquare(s) > ? ? ? ? ? ? ? ? ?self._setvalue = math.sqrt(s) > > ? ? ? ? ?def _setvalue(self, val): > ? ? ? ? ? ? ? ? ?# some extra logic here > ? ? ? ? ? ? ? ? ?self._internalval=val > > ? ? ? ? ?def fsetvalue(self, val): > ? ? ? ? ? ? ? ? ?self._setvalue(val) > ? ? ? ? ? ? ? ? ?self._setsquare=pow(val,2) Oh sorry for this last version the setters should be : def fsetsquare(self,s): self._setsquare(s) self._setvalue = math.sqrt(self.square) def fsetvalue(self, val): self._setvalue(val) self._setsquare=pow(self.value, 2) as we don't know what is done in _setXXX methods. -- _____________ Maric Michaud From mfajer at gmail.com Sun Sep 28 02:29:30 2008 From: mfajer at gmail.com (Mikolai Fajer) Date: Sat, 27 Sep 2008 23:29:30 -0700 Subject: design pattern: MVC in python Message-ID: <3ff66ae00809272329mce8d3c9lb94c316e169cf63a@mail.gmail.com> The following link directly discusses using MVC and pygame. http://ezide.com/games/writing-games.html -- -Mikolai Fajer- From gogtesuyash at gmail.com Wed Sep 17 08:04:02 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 05:04:02 -0700 (PDT) Subject: Problem occured while sending mail Message-ID: this is my code import sys, os, glob, datetime, time import smtplib ## Parameters for SMTP session port=587 SMTPserver= 'smtp.gmail.com' SMTPuser= '... at gmail.com' pw= 'fill in here' SENDER= SMTPuser ## Message details FROM= SENDER TO= 'notgm... at a.com' CC=FROM ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC RECEIVERS= (TO,) ## ignore the CC address subject= 'Test 1a' message='*** Email test *** ' print 'Starting SMTP mail session on %s as %s ' % (SMTPserver,SMTPuser) session = smtplib.SMTP(SMTPserver,port) session.set_debuglevel(0) # set debug level to 1 to see details session.ehlo(SMTPuser) # say hello session.starttls() # TLS needed session.ehlo(SMTPuser) # say hello again, not sure why session.login(SMTPuser, pw) ##Create HEADER + MESSAGE HEADER= 'From: %s\r\n' % FROM HEADER= HEADER + 'To: %s\r\n' % TO HEADER= HEADER + 'Cc: %s\r\n' % CC HEADER= HEADER + 'Subject: %s\r\n' % subject BODY= HEADER + '\r\n' + message print BODY SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email session.close() Now when i run this .py file...as python mail.py i can see only statement starting smtp mail......n details then nothing on screen after few minutes or after pressing ctrl +c Traceback (most recent call last): File "mail4.py", line 21, in session = smtplib.SMTP(SMTPserver,port) File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect self.sock.connect(sa) File "", line 1, in connect or may be conncetion time out wats the solution for this From hrishys at yahoo.co.uk Thu Sep 25 06:06:14 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 10:06:14 +0000 (GMT) Subject: Linq to Python In-Reply-To: <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> Message-ID: <10513.56961.qm@web27403.mail.ukl.yahoo.com> Hi If i rephrase my question how will i do this in Python http://informationr.net/ir/13-2/TB0806.html Watch this query on the page Where he joins all different kind of things with ease and elegance(as per my opinion) [code] var stoogeGuys = Beginning with the XML source from xmlGuys in xmlSource.Descendants("Stooge") Join to the array on the common element "stoogeName" join arrayGuys in familyFacts on xmlGuys.Element("stoogeName").Value equals arrayGuys.stoogeName Join to the database on the common element "stoogeName" join dbGuys in stoogeContext.stoogeTables on xmlGuys.Element("stoogeName").Value equals dbGuys.stoogeName select new { firstName = dbGuys.stoogeName, familyName = arrayGuys.familyName, birthDate = xmlGuys.Element("birthDate").Value, deathDate = xmlGuys.Element("deathDate").Value, hairCutStyle = dbGuys.stoogeHaircut, }; [/code] regards Hrishy From geonomica at gmail.com Mon Sep 1 08:49:46 2008 From: geonomica at gmail.com (gianluca massei) Date: Mon, 01 Sep 2008 14:49:46 +0200 Subject: __stack_chk_fail_local In-Reply-To: <3f0d61c40808300619l47122583i373493b075d1f422@mail.gmail.com> References: <3f0d61c40808300619l47122583i373493b075d1f422@mail.gmail.com> Message-ID: <48BBE4EA.5070606@libero.it> thanks for the help, maybe the solution will be useful: in "various Linux distributions are starting to ship with a version of the GNU C compiler which incorporates an extension which implements protection for stack-smashing". In that case the Makefile has to modified with CFLAGS = -fno-stack-protector gianluca Marco Bizzarri wrote: > On Sat, Aug 30, 2008 at 3:03 PM, g_massa at libero.it wrote: > >> Thanks! >> I've resolved the problem with libraries but... I've still error with this message: >> ImportError: ./_python_grass6.so: undefined symbol: __stack_chk_fail_local >> >> exuse me, I'm not a guru. >> >> Gianluca >> >> > > I'm not a guru either, Gianluca ;) > > I made a little search on Google; the first link is the following: > > http://ubuntuforums.org/showthread.php?t=352642 > > can you apply the suggestion? > > I think you should give a little more context on your problem, also, > because I think it has to do with your setup (not that you setup > something in the wrong way: just to have context). > > Regards > Marco > > > > > From deets at nospam.web.de Fri Sep 5 11:02:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 17:02:53 +0200 Subject: Make Games In-Reply-To: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> References: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> Message-ID: <6id00tFq2em1U1@mid.uni-berlin.de> NightZombie schrieb: > x-no-archive: yes > > I want to learn Python so I can make simple games. What are some good > books that'll help me do this? Don't know about books, but I don't think it is important that the books are about python for game programming - game programming in general will help. On http://pygame.org/ you can see quite a few examples on how to create games using pygame, and then there are projects such as pyglet, nodebox and of course PyOpenGL itself. Diez From bthate at gmail.com Tue Sep 16 04:58:48 2008 From: bthate at gmail.com (Bart Thate) Date: Tue, 16 Sep 2008 01:58:48 -0700 (PDT) Subject: GOZERBOT 0.8.2-BETA released Message-ID: It is time for a new gozerbot release so we are pushing a new BETA for the world to test. This time the change is rather big as most plugins are removed from the core and put into there own tarball. So if you want to try out 0.8.2-BETA for us and report any problems with it on http://dev.gozerbot.org/ or in our channel #dunkbots on IRCnet we would very much appreciate it. You can also contact me at bthate at gmail.com. Download can be done from our website http://gozerbot.org/ new features: * most plugins removed from core .. this keeps the base of the bot as small as possible * missing plugins can be installed via internet or via tarball * rewritten core .. callbacks and commands when not threaded are not executed in the main loop anymore but instead in what are called ?runners?, threads that do the jobs. this limits the threads that are launched * new debug mode that enables more verbose logging (stacktrace) * a REST server and client have been added to the core .. the cloud plugin uses these to communicate between bots. data is transfered in json format * new plugins are added to the plugin collection o powernick (core) .. a plugin to relay the log file to an OPER via DCC CHAT o throttle (core) .. throttle users to max number of commands per minute o cloud (myplugs) .. connect gozerbots together o traclog (myplugs) .. log channel in a format suitable for integration with trac o register (myplugs) .. enables users to register themselves with the bot o anon (myplugs) .. register users on channel join * config changes are now written to the config file instead of a pickle TAKE NOTE: most of the plugins are removed from the core bot .. you can use the !install-defaultplugs command to get most of these plugins .. otherwise see !install-list of plugins that can be installed About gozerbot: Requirements * a shell * python 2.4 or higher * if you want to remotely install plugins: the gnupg module * if you want mysql support: the py-MySQLdb module * if you want jabber support: the xmpppy module Why gozerbot? * provide both IRC and Jabber support * user management by userhost .. bot will not respond if it doesn't know you (see /docs/USER/) * fleet .. use more than one bot in a program (list of bots) (see / docs/plugins/FLEET/) * use the bot through dcc chat * fetch rss feeds (see /docs/plugins/RSS/) * remember items * relaying between bots (see /docs/plugins/RELAY/) * program your own plugins (see /docs/PROGRAMPLUGIN/) * run the builtin webserver (see /docs/plugins/WEBSERVER/) * query other bots webserver via irc (see /docs/plugins/ COLLECTIVE/) * serve as a udp <-> irc or jabber notification bot (see /docs/ plugins/UDP) * mysql and sqlite support the gozerbot development team From alan.isaac at gmail.com Mon Sep 1 12:02:07 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Mon, 01 Sep 2008 16:02:07 GMT Subject: Writing to ms excel In-Reply-To: References: Message-ID: <3mUuk.216$jE1.59@trnddc03> http://docs.python.org/lib/module-csv.html From joe.hrbek at gmail.com Wed Sep 24 15:24:32 2008 From: joe.hrbek at gmail.com (Joe Hrbek) Date: Wed, 24 Sep 2008 12:24:32 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: Message-ID: <717d439a-60c2-4808-adac-e5adcc25275e@k7g2000hsd.googlegroups.com> Todd, this is great! Thanks for your work on this. I've been using your extension for awhile, successfully creating little apps. Your gui_app template has been a huge help in advancing my understanding of how things fit together...takes some of the guesswork out. :) Thanks again, -j On Sep 16, 8:29?pm, Todd Whiteman wrote: > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming language. > > The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX > is possible with a few deviations, I have tried to cover these > deviations where applicable). > > Feedback is welcome. > > Cheers, > Todd From __peter__ at web.de Thu Sep 25 03:52:55 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2008 09:52:55 +0200 Subject: empty csv file attachments References: <200563c8-a4d1-45db-aaa1-63f885851b76@s50g2000hsb.googlegroups.com> Message-ID: Bobby Roberts wrote: > I'm new to python but a veteran at programming. ? Hm, your code doesn't show that. The time to read the tutorial would be time well spend. After that, a quick look at what the standard library has to offer wouldn't hurt. E. g. reading/writing CSV files is a solved problem in python ;) > This one has me > stumped. ?I have a simple contact form which the user fills out. ?The > email is sent to the site user as well and it is delivered with the > content in the body of the email as well in nice order. ?I have > modified my code to also send the content as a csv attachment. ?On the > server, the file is perfectly generated with content. ?The attachment, > however, is completely blank. ?Any ideas what that could be? ?My code > snippet is shown below: > > > ? ? ? if int(attachmenttype)==2 or int(attachmenttype)==3: > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? if field=='last_name': > ? ? ? ? ? ? myfilename=ctx.request.field_value(field)+'.txt' > ? ? ? ? if myfilename=='': > ? ? ? ? ? myfilename='tempfile.txt' > ? ? ? ? mypath= mynewfilepath + '/' + myfilename > ? ? ? ? f=open(mypath, 'w') > ? ? ? ? mynewstring='' > ? ? ? ? counter=0 > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? if field != 'inquiry_required': > ? ? ? ? ? ? mynewstring=mynewstring + field +',' > ? ? ? ? if mynewstring[-1]==',': > ? ? ? ? ? mynewstring=mynewstring[0:len(mynewstring)-1] > ? ? ? ? f.write(mynewstring) > ? ? ? ? f.write ('\n') > > ? ? ? ? mynewstring='' > ? ? ? ? counter=1 > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? fielddata=ctx.request.field_value(field) > ? ? ? ? ? if counter==1: Hm, above you skip the field "inquiry_required", here you skip the second field. > ? ? ? ? ? ? dummydata=0 > ? ? ? ? ? else: > ? ? ? ? ? ? mynewstring=mynewstring + '"' + fielddata.replace('"','') > + '",' > ? ? ? ? ? counter = counter + 1 > ? ? ? ? if mynewstring[-1]==',': > ? ? ? ? ? mynewstring=mynewstring[0:len(mynewstring)-1] > ? ? ? ? f.write(mynewstring) > ? ? ? ? f.write('\n') > ? ? ? ? f.close Your actual problem might be that f.close doesn't close (and therefore flush) the file, you need to call it with f.close(). > ? ? ? ? attachments.append('/'.join((ctx.request.library, > myfilename))) Hm, is ctx.request.library the same as mynewfilepath? With some guessing your code becomes (untested) import csv import os if int(attachmenttype) in (2, 3): filename = 'tempfile.txt' if "last_name" in ctx.request.field_names(): last_name = ctx.request.field_value("last_name") if last_name: filename = last_name + ".txt" path = os.path.join(ctx.request.library, filename) f = open(path, 'wb') writer = csv.writer(f) fieldnames = [field for field in ctx.request.field_names() if field != "inquiry_required"] writer.writerow(fieldnames) writer.writerow(ctx.request.field_value(field) for field in fieldnames) f.close() attachments.append(path) The code to build the filename is still clumsy, but to do better I'd have to know the library you are using. Personally I'd always use "tempfile.txt" and be done. This would also avoid fun with last names like ../../just_testing_file_permissions. Peter From bdesth.quelquechose at free.quelquepart.fr Sun Sep 28 14:47:11 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 Sep 2008 20:47:11 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <48dd5f08$0$26425$426a74cc@news.free.fr> Message-ID: <48dfed19$0$17486$426a74cc@news.free.fr> Tim Rowe a ?crit : > 2008/9/26 Bruno Desthuilliers : > >> Not to start a troll, but from what I've seen of C# so far I do find this a >> bit surprising and really suspect more of a library issue than a language >> one. Care to tell more about the problem and solution ? >> >> (NB : I wouldn't even asked if you had mentionned say Erlang or Prolog or >> OCaml - well, some mostly different language - instead of C#) > > IIRC it was library issues -- for one thing I still find it a lot > harder to manage an MS Windows GUI under Python than I do under .NET > (I've never succeeded in getting Iron Python to run properly). In one > sense you could argue that that's not a language issue, and you'd be > right: there's nothing in the syntax or semantics of either language > that makes it so. But in another sense I'd say it is a language issue > (and of course I think I'm right!) And - after reading the following argument - I think you're wrong !-) > because Python aims to be platform > independent, and whilst that means gains in portability it means that > in return it loses the ease-of-programming of a tightly integrated > platform. > Still a library issue. Python doesn't defines "platform-independant" the way Java does, and there are quite a couple Python packages (third-part or even in the standard lib) that are clearly platform-specific - including MS Windows COM stuff, which was a major PITA using VB6. From tilmaniac at gmail.com Mon Sep 29 15:35:47 2008 From: tilmaniac at gmail.com (Tilman Kispersky) Date: Mon, 29 Sep 2008 12:35:47 -0700 (PDT) Subject: Cannot install pysqlite on Cygwin References: Message-ID: On Sep 29, 12:37?pm, Tilman Kispersky wrote: > On Sep 29, 7:49?am, Steve Holden wrote: > > > > > Tilman Kispersky wrote: > > > I am trying to install sqlite for use with python oncygwin. I have > > > installed the sqlite packages fromcygwin(that is libsqlite3-devel > > > and libsqlite3_0). ?When attempting to easy_install pysqlite I get: > > > > $ easy_install pysqlite > > > Searching for pysqlite > > > Readinghttp://pypi.python.org/simple/pysqlite/ > > > Readinghttp://pysqlite.org/ > > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ > > > Readinghttp://pysqlite.sourceforge.net/ > > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/ > > > Readinghttp://initd.org/tracker/pysqlite/wiki/PysqliteDownloads > > > Readinghttp://oss.itsystementwicklung.de/trac/pysqlite > > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/ > > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/ > > > Readinghttp://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/ > > > Readinghttp://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/ > > > Best match: pysqlite 2.5.0 > > > Downloadinghttp://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlit... > > > Processing pysqlite-2.5.0.tar.gz > > > Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/ > > > Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg- > > > dist-tmp-7mr3WS > > > warning: no files found matching 'doc/*.html' > > > warning: no files found matching 'doc/code/*.py' > > > src/statement.c: In function `pysqlite_statement_recompile': > > > src/statement.c:351: warning: `sqlite3_transfer_bindings' is > > > deprecated (declared at /usr/include/sqlite3.h:3985) > > > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function > > > `pysqlite_enable_load_extension': > > > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ > > > pysqlite-2.5.0/src/connection.c:922: undefined reference to > > > `_sqlite3_enable_load_extension' > > > collect2: ld returned 1 exit status > > > error: Setup script exited with error: command 'gcc' failed with exit > > > status 1 > > > $ > > > > It seems to me this is due to some missing library (undefined > > > reference...) but I have no idea what these missing files might be. > > > I've tried installing everything that made any reference to sqlite > > > form thecygwininterface. ?Does anyone know how I might get a working > > > install of sqlite for python oncygwin? > > > I believe it's a glitch in the 2.5.1 distribution current onCygwin- I > > had to install the _sqlite DLL separately to get it to work, but no > > recompilation was necessary AFAICR. > > > Chui Tey detailed the necessary steps in his blog post "CygwinPython > > and sqlite3", but sadly it got lost and he hasn't replenished it, so you > > will have to stab around to see if there's a cached copy anywhere. > > > regards > > ?Steve > > -- > > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ > > Well, I haven't managed to solve the problem. > > I tried following these instructions but get the same error:http://initd.org/pub/software/pysqlite/doc/install-source-win32.html > > And I also tried downloading the dll from sqlite.org and putting it on > my path. > > Since someone asked how I ended up solving this problem: > I'm just going to work on my Linux box where its relatively straight > forward to install > this stuff with the package manager. > > If someone does have instructions for making this work on windows I'd > be very curious. I was unable to find an archived version of the blog > post referenced above. I also managed to get it to work by not using cygwin's python. I suppose this is sort of the obvious solution. Just download the windows installers for python, pysqlite. You can still run the windows installed version of python from cygwin (I prefer that over the 'cmd' terminal) by specifying the executable you want to use explicity eg: $ /cygdrive/c/Python25/python From mhuening at zedat.fu-berlin.de Wed Sep 10 10:07:07 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Wed, 10 Sep 2008 16:07:07 +0200 Subject: PHP's str_replace ? In-Reply-To: References: Message-ID: <6iq2jpFs113rU1@mid.uni-berlin.de> Anjanesh Lekshminarayanan (10.09.2008 15:50): > In PHP, if I do > str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) > it'll replace all vowels with a hyphen in string $str. > > Is there some equivalent in Python ? What about something like this: import re new_str = re.sub('([aeiou])-', r'\1', str) Matthias From dave.dibiase at gmail.com Fri Sep 26 10:22:42 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Fri, 26 Sep 2008 10:22:42 -0400 Subject: Fastest way to max() list In-Reply-To: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> References: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> Message-ID: Hi Chris, Yeah I hear you on point A. but this the specification I was given, so I have to follow it unfortunately. I've also been restricted and not allowed to use any other packages. I was using NumPy earlier (should have mentioned that) but I was wondering if there was a simpler way. Is NumPy technically even faster than just iterating and modifying the list directly? Also if I'm creating an array then making it, why not just do a temporary sort and capture the first and last values? Is this method you've provided supposed to be faster? Dave On Fri, Sep 26, 2008 at 12:42 AM, Chris Rebert wrote: > On Thu, Sep 25, 2008 at 8:57 PM, David Di Biase > wrote: > > I have a list with about 1000-1500 sub-lists which look like so: > > list[-0.28817955213290786, 3.6693631467403929, 'H', 31.31225233035784]] > > > > The first and second values are Angstrom units specifying the location of > a > > particle. What I'd like to do is determine the distance between the > smallest > > and largest value in the arrays first position 0. I tried reading the > manual > > for this but I don't see how it applies key or any of those other > commands > > to the function. I could easily write a sort to do this and capture the > > first and last spots, but why do that when I can use max and min (if I > can > > actually do that...). > > A. You should probably be using objects rather than arrays to > represent your datapoints, so that they're more structured and it's > more apparent what the values mean. > > B. Assuming by "distance" you meant "difference" and/or that the > distance is only in 1 dimension: > > from operator import itemgetter > firsts = map(itemgetter(0), main_list) > distance = max(firsts) - min(firsts) > > > > > So you wonderful Python gods, lay some knowledge on me. please? lol... > > > > while I'm at it, is there a way to modify an entire list without having > to > > produce a whole new one? For example now say I want to modify list[0] and > > multiply it by some value. From what I understand previous version of > Python > > allowed lists to be multiplied like matrices...now apparently it just > > replicates the list. :-/ shucks... > > You just have to apply the transform to each list element individually > (also, you might consider using NumPy [http://numpy.scipy.org/] if > you're doing a lot of matrix manipulation): > > for lst in main_list: > lst[0] *= some_value > > Regards, > Chris > > > > > The first question would be useful to know, but the second question I do > > quite a bit of and the "best practice" would be really great to know! > > > > Thanks in advanced! > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- > Follow the path of the Iguana... > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From coolkid246 at googlemail.com Thu Sep 4 06:10:48 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:10:48 -0700 (PDT) Subject: =?ISO-8859-1?Q?kredit_fuer_selbststaendige_in_Stollberg_kredit_onli?= =?ISO-8859-1?Q?ne_beantragen_online_kredite_im_kredit_ohne_gehaltsnachweis_?= =?ISO-8859-1?Q?online_credit_ohne_kredit_ohne_schufa_vergleich_kredite_von_?= =?ISO-8859-1?Q?privat_bank_kredite_schweizer_kredit_ohne_schufa_eilkredit_o?= =?ISO-8859-1?Q?hne_schufa__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTIGE_KREDITE_ONLINE_=2B=2B=2B_KREDITE?= =?ISO-8859-1?Q?_IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_=2B_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D2?= =?ISO-8859-1?Q?44=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKRED?= =?ISO-8859-1?Q?ITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_htt?= =?ISO-8859-1?Q?p=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D2?= =?ISO-8859-1?Q?44=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKRED?= =?ISO-8859-1?Q?ITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_=2B_=2B?= =?ISO-8859-1?Q?_=2B_=2B_______________________bank_kredite_kredite_fuer_arbeits?= =?ISO-8859-1?Q?lose_ohne_schufa_in_Sonthofen_sofortkredite_kredite_vergleic?= =?ISO-8859-1?Q?h_in_L=FCdenscheid_postbank_kredit_kredite_auch_ohne_schufa_i?= =?ISO-8859-1?Q?n_Wittlich_eilkredit_ohne_schufa_autokredit_in_Merzig_euro_k?= =?ISO-8859-1?Q?redite_kredite_schufa_in_Cloppenburg_schufafreie_kredite_bau?= =?ISO-8859-1?Q?finanzierung_online_in_Sulzbach_kredite_banken_online_kredit?= =?ISO-8859-1?Q?_trotz_schufa_in_Parchim_bargeld_kredite_bargeld_ohne_schufa?= =?ISO-8859-1?Q?_in_L=FCbben_online_kredite_von_privat_privatkredit_online_in?= =?ISO-8859-1?Q?_Luckenwalde_kredite_fuer_selbststaendige_kredit_girokonto_i?= =?ISO-8859-1?Q?n_Seelow_leasing_ohne_schufa_www_kredite_ohne_schufa_de_in_M?= =?ISO-8859-1?Q?iltenberg_internet_kredit_kfz_kredit_in_Garmisch=2DPartenkirch?= =?ISO-8859-1?Q?en_kredite_guenstiger_kredit_mit_schufa_in_Bad_Kreuznach____?= =?ISO-8859-1?Q?=2D_kredite_online_beantragen_darlehen_online_in_Wetzlar_=2D_gue?= =?ISO-8859-1?Q?nstige_kredit_online_kredit_auch_in_Mosbach_=2D_kredite_muench?= =?ISO-8859-1?Q?en_online_kredit_schufafrei_in_Mayen_=2D_kredit_ohne_schufa_se?= =?ISO-8859-1?Q?lbststaendige_kredit_online_beantragen_in_Germersheim_=2D_auch?= =?ISO-8859-1?Q?_ohne_schufa_kredite_banken_in_Pfaffenhofen_=2D_online_kredite?= =?ISO-8859-1?Q?_guenstig_privatkredite_ohne_schufa_in_Offenbach_=2D_kredit_sc?= =?ISO-8859-1?Q?hweiz_kredite_ohne_schufa_ohne_in_Waren_=2D_bar_kredit_ohne_sc?= =?ISO-8859-1?Q?hufa_kredit_ohne_gehaltsnachweis_in_Kirchheimbolanden_=2D_bill?= =?ISO-8859-1?Q?ig_kredit_dispo_kredit_in_Rhoen_=2D_online_kredit_mit_sofortzu?= =?ISO-8859-1?Q?sage_kredit_ohne_schufa_selbstaendige_in_Erlangen_=2D_kredit_o?= =?ISO-8859-1?Q?hne_schufa_test_kredite_beantragen_in_Schongau_Weilheim=2FObb=2E?= =?ISO-8859-1?Q?_=2D_euro_kredite_sofortkredite_in_Soltau_=2D_privat_kredite_ohn?= =?ISO-8859-1?Q?e_schufa_kredite_ohne_schufa_de_in_Heppenheim_=2D_www_kredit_o?= =?ISO-8859-1?Q?hne_schufa_kredit_ohne_schufa_selbststaendige_in_Oranienburg?= Message-ID: kredit fuer selbststaendige in Stollberg kredit online beantragen online kredite im kredit ohne gehaltsnachweis online credit ohne kredit ohne schufa vergleich kredite von privat bank kredite schweizer kredit ohne schufa eilkredit ohne schufa + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + bank kredite kredite fuer arbeitslose ohne schufa in Sonthofen sofortkredite kredite vergleich in L?denscheid postbank kredit kredite auch ohne schufa in Wittlich eilkredit ohne schufa autokredit in Merzig euro kredite kredite schufa in Cloppenburg schufafreie kredite baufinanzierung online in Sulzbach kredite banken online kredit trotz schufa in Parchim bargeld kredite bargeld ohne schufa in L?bben online kredite von privat privatkredit online in Luckenwalde kredite fuer selbststaendige kredit girokonto in Seelow leasing ohne schufa www kredite ohne schufa de in Miltenberg internet kredit kfz kredit in Garmisch-Partenkirchen kredite guenstiger kredit mit schufa in Bad Kreuznach - kredite online beantragen darlehen online in Wetzlar - guenstige kredit online kredit auch in Mosbach - kredite muenchen online kredit schufafrei in Mayen - kredit ohne schufa selbststaendige kredit online beantragen in Germersheim - auch ohne schufa kredite banken in Pfaffenhofen - online kredite guenstig privatkredite ohne schufa in Offenbach - kredit schweiz kredite ohne schufa ohne in Waren - bar kredit ohne schufa kredit ohne gehaltsnachweis in Kirchheimbolanden - billig kredit dispo kredit in Rhoen - online kredit mit sofortzusage kredit ohne schufa selbstaendige in Erlangen - kredit ohne schufa test kredite beantragen in Schongau Weilheim/Obb. - euro kredite sofortkredite in Soltau - privat kredite ohne schufa kredite ohne schufa de in Heppenheim - www kredit ohne schufa kredit ohne schufa selbststaendige in Oranienburg From boyee118 at gmail.com Sat Sep 20 00:14:09 2008 From: boyee118 at gmail.com (=?UTF-8?B?5Li654ix6ICM55Sf?=) Date: Sat, 20 Sep 2008 12:14:09 +0800 Subject: report a BUG of package setuptools-0.6c8. Message-ID: Traceback (most recent call last): File "setup.py", line 176, in main() File "setup.py", line 172, in main setup(**args) File "/usr/lib/python2.5/distutils/core.py", line 151, in setup dist.run_commands() File "/usr/lib/python2.5/distutils/dist.py", line 974, in run_commands self.run_command(cmd) File "/usr/lib/python2.5/distutils/dist.py", line 994, in run_command cmd_obj.run() File "/usr/lib/python2.5/site-packages/setuptools/command/install.py", line 76, in run self.do_egg_install() File "/usr/lib/python2.5/site-packages/setuptools/command/install.py", line 96, in do_egg_install self.run_command('bdist_egg') File "/usr/lib/python2.5/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.5/distutils/dist.py", line 994, in run_command cmd_obj.run() File "/usr/lib/python2.5/site-packages/setuptools/command/bdist_egg.py", line 167, in run self.run_command("egg_info") File "/usr/lib/python2.5/distutils/cmd.py", line 333, in run_command self.distribution.run_command(command) File "/usr/lib/python2.5/distutils/dist.py", line 994, in run_command cmd_obj.run() File "/usr/lib/python2.5/site-packages/setuptools/command/egg_info.py", line 171, in run self.find_sources() File "/usr/lib/python2.5/site-packages/setuptools/command/egg_info.py", line 252, in find_sources mm.run() File "/usr/lib/python2.5/site-packages/setuptools/command/egg_info.py", line 306, in run self.add_defaults() File "/usr/lib/python2.5/site-packages/setuptools/command/egg_info.py", line 333, in add_defaults rcfiles = list(walk_revctrl()) File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", line 45, in walk_revctrl for item in ep.load()(dirname): File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", line 52, in _default_revctrl for path in finder(dirname,path): File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", line 98, in entries_finder log.warn("unrecognized .svn/entries format in %s", dirname) NameError: global name 'log' is not defined global name 'log' is not defined to the line 98!!! -- "OpenBookProject"-?????????? ??: http://groups.google.com/group/OpenBookProject ??: http://wiki.woodpecker.org.cn/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From asnast at gmail.com Sat Sep 20 19:22:31 2008 From: asnast at gmail.com (Alex Snast) Date: Sat, 20 Sep 2008 16:22:31 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: On Sep 20, 8:13?pm, bearophileH... at lycos.com wrote: > Duncan Booth: > > > > e.g. the python equivalent to the c++ loop > > > for (i = 10; i >= 0; --i) > > > The exact equivalent would be: > > ? ? ? ? for i in range(10, -1, -1): print i > > I'd use xrange there. Anyway, I have always felt that Python syntax > not easy to understand at first sight, expecially when you try to > convert a bit more complex inverted for loops from/to C to/from > Python. It's one of the few cases where (for example) Pascal (loop) > syntax wins a bit over Python syntax :-) > > Bye, > bearophile That's a lot of responses guys. Thanks a lot i think i got it. Another question, are there any pointers in python (or iterators) for when i use a data structure that doesn't support random access? Thanks again, Alex From tchendrix at gmail.com Tue Sep 23 09:00:34 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 06:00:34 -0700 (PDT) Subject: finding domain name References: Message-ID: <8b93f073-ed19-4410-a32f-8421cb0698d1@y38g2000hsy.googlegroups.com> On Sep 23, 8:54?am, "Joe Riopel" wrote: > On Tue, Sep 23, 2008 at 8:37 AM, Bobby Roberts wrote: > > hi group. ?I'm new to python and need some help and hope you can > > answer this question. ?I have a situation in my code where i need to > > create a file on the server and write to it. ?That's not a problem if > > i hard code the path. ?However, the domain name needs to be dynamic so > > it is picked up automatically. ?The path to our websites is > > > home/sites/xxxxx/ > > > where xxxxx represents the domain name. > > > How can I find the domain name of the current url being viewed. > > I would guess that a pretty simple regular expression might do it. can you explain? From http Tue Sep 2 14:28:39 2008 From: http (Paul Rubin) Date: 02 Sep 2008 11:28:39 -0700 Subject: Large amount of files to parse/organize, tips on algorithm? References: Message-ID: <7x1w02v1uw.fsf@ruckus.brouhaha.com> cnb writes: > For each file I construct a list of reviews and then for each new file > I merge the reviews so that in the end have a list of reviewers and > for each reviewer all their reviews. > > What is the fastest way to do this? Scan through all the files sequentially, emitting records like (movie, reviewer, review) Then use an external sort utility to sort/merge that output file on each of the 3 columns. Beats writing code. From lists at cheimes.de Thu Sep 18 19:36:46 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 19 Sep 2008 01:36:46 +0200 Subject: Python newbie question re Strings and integers In-Reply-To: References: Message-ID: rmac wrote: > > the following code attempts to extract a symbol name from a string: > extensionStart = int(filename.rfind('.')) > filenameStart = int(filename.rfind('/')) > #print 'Extension Start - ' + str(extensionStart) > #print 'FileName Start - ' + str(filenameStart) > currentSymbol=filename[int(filenameStart),int(extensionStart)] > > Uncommenting the print statements clearly show the values to be > integers (and without the str casts actually provide int+string > errors) > > However, executing this code results in... > opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv > Traceback (most recent call last): > File "rHistFileToDB_Equities.py", line 25, in > currentSymbol=filename[int(filenameStart),int(extensionStart)] > TypeError: string indices must be integers You are using , inside filename[]. The splicing syntax is start:end, not start,end. You are better off with using the appropriate APIs from the os.path module. http://docs.python.org/lib/module-os.path.html import os.path filename = os.path.basename(path) prefix, extension = os.path.splitext(filename) Christian From castironpi at gmail.com Fri Sep 12 01:26:27 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 22:26:27 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> Message-ID: <40c884c7-2fc6-4667-b47c-eb203e95711e@k30g2000hse.googlegroups.com> On Sep 11, 10:37?pm, Steven D'Aprano wrote: > On Thu, 11 Sep 2008 10:20:41 -0700, Aaron \"Castironpi\" Brady wrote: > > XML is the wrong word for the example I was thinking of (as was already > > pointed out in another thread). ?XML is by definition sequential. > > I'm pretty sure you're wrong. XML can be used for serialization, but that > doesn't mean it is only sequential data. XML is suitable for hierarchical > data too. To quote Wikipedia: > > "As long as only well-formedness is required, XML is a generic framework > for storing any amount of text or any data whose structure can be > represented as a tree. The only indispensable syntactical requirement is > that the document has exactly one root element (alternatively called the > document element)." > > http://en.wikipedia.org/wiki/Xml > > -- > Steven That's my choice of words at work again, I'm afraid. What I mean is, there is no possibility that you can correctly interpret a segment of XML text without knowing certain facts about everything that precedes it. Compare to the case of a fixed-length record file, of record size say 20, where you know the meaning of the characters in offset ranges 20-40, 80-100, 500020-500040, etc. To clarify the point of the use case in question, because data would be allocated and located dynamically, its possible that you could read the first several words, then not need anything until say, the 1KB mark. (Unless you're somehow storing an offset in to an XML string as a value in the string, which would require composing it, leaving room for that value, and then writing it with random access anyway.) There can be gaps in a dynamically managed buffer--- say the unused/free bytes from offsets 200 to 220, but every byte that follows another in an XML file follows it in the file's meaning too. Is this any clearer? Aaron From invalid at invalid Wed Sep 24 10:09:31 2008 From: invalid at invalid (Grant Edwards) Date: Wed, 24 Sep 2008 09:09:31 -0500 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: On 2008-09-24, Steven D'Aprano wrote: > On Tue, 23 Sep 2008 13:25:26 -0700, Drake wrote: > >> I have a general question of Python style, or perhaps just good >> programming practice. >> >> My group is developing a medium-sized library of general-purpose Python >> functions, some of which do I/O. Therefore it is possible for many of >> the library functions to raise IOError Exceptions. The question is: >> should the library function be able to just dump to sys.exit() with a >> message about the error (like "couldn't open this file"), or should the >> exception propagate to the calling program which handles the issue? >> >> Thanks in advance for anyone who can either answer my question or point >> me to where this question has already been answered. > > > Presumably somebody has suggested that calling sys.exit() was a good > option. I'm curious to what possible reason they could give for such a > poor choice. Same here. It's like an automotive engine controls designer asking if a failed O2 sensor should turn on the check engine light or blow up the car. -- Grant Edwards grante Yow! Mr and Mrs PED, can I at borrow 26.7% of the RAYON visi.com TEXTILE production of the INDONESIAN archipelago? From tjreedy at udel.edu Tue Sep 16 15:17:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 15:17:56 -0400 Subject: Python and Open Office In-Reply-To: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Hartmut Goebel wrote: > As I thought everybody already knows, ODF is simply a Zip-File > containing some XML files. I thought it just *was* xml. But examination with notepad showed otherwise. > So there is no need to use OOo for handling > the files. > > So odfpy seams to be the best way to to this. Since odfpy automatically handles combining the at-least-4 xml files into one coherent class on loading, and putting the various properties into the proper xml files on saving, this looks pretty straightforward. Thanks for the reference. One way to learn the meaning of some of the numerous attributes and values is to create a file with the wanted features with OOo, save, unzip, and examine the xml to see which tags are used for which features. You may also want to check > OOopy . I will glance at that too. > > If you are going to interact with OOo, you may want to try out > > From stefan_ml at behnel.de Thu Sep 4 14:20:49 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 04 Sep 2008 20:20:49 +0200 Subject: python/xpath question.. In-Reply-To: <48bf8a5c$0$10095$9b4e6d93@newsspool3.arcor-online.net> References: <48bf8a5c$0$10095$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <48c02701$0$19239$9b4e6d93@newsspool4.arcor-online.net> Stefan Behnel wrote: > Yes, learn to use XPath, e.g. > > //tr/td[not string()] Oh, well... //tr/td[not(string())] as I said, wrong news group. ;-) Try something like "gmane.text.xml.xpath.general", for example. Stefan From joncle at googlemail.com Wed Sep 10 15:13:52 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 12:13:52 -0700 (PDT) Subject: Reading binary data References: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> Message-ID: On Sep 10, 7:16?pm, Aaron Scott wrote: > Taking everything into consideration, my code is now: > > import struct > file = open("test.gde", "rb") > signature = file.read(3) > version, attr_count = struct.unpack('II', file.read(8)) > print signature, version, attr_count > for idx in xrange(attr_count): > ? ? ? ? attr_id, attr_val_len = struct.unpack('II', file.read(8)) > ? ? ? ? attr_val = file.read(attr_val_len) > ? ? ? ? print attr_id, attr_val_len, attr_val > file.close() > > which gives a result of: > > GDE 2 2 > 1 4 ? > 2 4 ??? > > Essentially, the same results I was originally getting :( Umm, how about yourfile.read(100)[or some arbitary value, just to see the data) and see what it returns... does it return something that looks like values you'd expect in a char[]... I also find it odd that the attr_val_len appears to be 4? From bj_666 at gmx.net Mon Sep 1 15:26:09 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 1 Sep 2008 19:26:09 GMT Subject: Python 3.0b2 cannot map '\u12b' References: <6i24u3Fo7morU2@mid.uni-berlin.de> Message-ID: <6i2tugFo7morU3@mid.uni-berlin.de> On Mon, 01 Sep 2008 14:25:01 -0400, Terry Reedy wrote: > Marc 'BlackJack' Rintsch wrote: >> On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: >> >> Most likely because Python figured out that the terminal expects cp437. >> What does `sys.stdout.encoding` say? > > The interpreter in the command prompt window says CP437. The IDLE Window > says 'cp1252', and it handles the character fine. Given that Windows OS > can handle the character, why is Python/Command Prompt limiting output? The windows command prompt expects cp437 because that's what old DOS programs print to it. > Characters the IDLE window cannot display (like surrogate pairs) it > displays as boxes. But if I cut '[][]' (4 chars) and paste into > Firefox, I get 3 chars. '[]' where [] has some digits instead of being > empty. It is really confusing when every window on 'unicode-based' > Windows handles a different subset. That's because it is not 'unicode-based'. Communication between those programs has to be done with bytes, so the sender has to encode unicode characters in the encoding the receiver expects. > Is this the fault of Windows or of Python and IDLE (those two being > more limited that FireFox)? It's nobodies fault. That's simply how the encoding stuff works. >>> To put it another way, how can one 'choose' utf-8 for display to >>> screen? >> >> If the terminal expects cp437 then displaying utf-8 might give some >> problems. > > My screen displays whatever Windows tells the graphics card to tell the > screen to display. But the terminal gets bytes and expects them to be cp437 encoded characters and not utf-8. So you can't send whatever unicode character you want, at least not without changing the encoding of the terminal. > In OpenOffice, I can select a unicode font that displays at least > everything in the BasicMultilingualPlane (BMP). But OOo works with unicode internally, so there's no communication with outside programs involved here. Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Sat Sep 27 01:52:26 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 27 Sep 2008 05:52:26 GMT Subject: Spring Python 0.7.0 is released References: Message-ID: <74ird4hidmldkq9bao6sk5grdmpp9vq62e@4ax.com> Goldfish wrote: > >Release 0.7.0 was completed last night, and released to >sourceforge.net. > >NOTE: This release included a lot of API scrubbing, in order to bring >things more in tune with PEP-0008 (python's style guide). You're >existing apps PROBABLY were impacted, if you used any of Spring >Python's utility classes. Since we are pre-1.0, this is the best time >for such a cleanup. When 1.0 hits the streets, we won't make such a >sweeping change without extensive backwards support. > >See [url]http://springpython.webfactional.com[/url] for more >information. > >Visit our community forum at [url]http://forum.springframework.org/ >forumdisplay.php?f=45[/url] for current threads of discussion. > >--Greg Turnquist, Spring Python project lead You have committed one of the classic announcement blunders here. Your announcement gives absolutely no clue as to what Spring Python is or does. Yes, I could go to the web site to figure it out, but it's not really reasonable to expect me to do that to find out whether it might be of interest to me. A brief abstract should be part of every announcement, no matter how often you do updates. (Followup: I did go to the web site, and I STILL don't know what "Spring Python" is or does. Should I really have to Google for "spring java framework" to learn this?) -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From andis59 at gmail.com Thu Sep 11 02:16:03 2008 From: andis59 at gmail.com (Anders Eriksson) Date: Thu, 11 Sep 2008 08:16:03 +0200 Subject: I want to use a C++ library from Python References: <6ipd53FrptpiU1@mid.uni-berlin.de> <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> <6ipr40Fr7kr2U1@mid.uni-berlin.de> Message-ID: <1buzw9k4gimaf$.dlg@ostling.com> Hello all and thanks for replying, > Diez B. Roggisch wrote: >> Which actually isn't really helpful, as a DLL itself says nothing about what >> language was used to create it - and sending the OP to e.g. ctypes makes no >> sense at all in the face of C++. > > The library - or more precisely the calling convention of the library - > is related to the solution. On Windows a dll might be a container for a > .NET assembly and C++ code can (theoretically) be compiled to .NET, too. > No, the library is not an .NET assembly. It's an VC++ Library compiled as an Dll. >> Whereas the first link for "python c++" is Boost::Python, a C++-wrapper to >> make C++-code accessible from Python. > > C++ bindings can be created with SIP, SWIG, Boost or hand written code. > Multiple sites claim that SIP generates the fastest code. > I have looked (very briefly) at the three framework you mention but they all need the source code of the C++? I don't have the source code! Just the header files and the library and dll. Have I overlooked something or am I just screwed? // Anders -- English is not my first, or second, language so anything strange, or insulting, is due to the translation. Please correct me so I may improve my English! From m_palmer45 at yahoo.ca Sun Sep 14 11:06:44 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Sun, 14 Sep 2008 08:06:44 -0700 (PDT) Subject: how to exclude specific things when pickling? References: Message-ID: <7cd144b6-ca6f-447a-8448-5a334f8f999f@k37g2000hsf.googlegroups.com> On Sep 14, 10:53 am, "inhahe" wrote: > If I gather correctly pickling an object will pickle its entire hierarchy, > but what if there are certain types of objects anywhere within the hierarchy > that I don't want included in the serialization? What do I do to exclude > them? Thanks. If your class defines a __getstate__ method, it is expected to return the pickled state of the entire class. You can for example del those items from self.__dict__ that you don't want pickled and then return dumps(self). From fredrik at pythonware.com Sat Sep 20 12:46:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 18:46:35 +0200 Subject: How to make a reverse for loop in python? In-Reply-To: References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Fredrik Lundh wrote: >> e.g. the python equivalent to the c++ loop >> >> for (i = 10; i >= 0; --i) > > use range with a negative step: > > for i in range(10-1, -1, -1): > ... > > or just reverse the range: > > for i in reversed(range(10)): > ... (and to include the 10 in the range, add one to the 10 above) From afriere at yahoo.co.uk Wed Sep 24 21:32:52 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 24 Sep 2008 18:32:52 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 25, 3:16 am, Pete Forman wrote: > Asun Friere writes: > > > A canonical use of the conditional operator is in > > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). > > That fails for n == 1. So what is best? > Sorry missing parentheses. I should test before posting, even for code written into. > for i in range(4): > print '%d thing' % i + ('s' if i != 1 else '') That is the correct version of what I meant, but your last, including all variables for placeholders in the tuple is probably better. From torriem at gmail.com Tue Sep 30 19:30:38 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 30 Sep 2008 17:30:38 -0600 Subject: Time.sleep(0.0125) not available within Linux In-Reply-To: References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> Message-ID: <48E2B69E.4010505@gmail.com> Lawrence D'Oliveiro wrote: > In message <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d at posted.usinternet>, Grant > Edwards wrote: > >> On 2008-09-23, Blubaugh, David A. wrote: >> >>> I was wondering if anyone has come across the issue of not being allowed >>> to have the following within a Python script operating under Linux: >>> >>> time.sleep(0.0125) >> No, I have not. And I doubt anybody else has. > > Just a thought, your minimum sleep time is probably limited by the > resolution of the system "HZ" clock. Type > > less /proc/config.gz > > and search for the value of the "CONFIG_HZ" setting. On the Athlon 64 > machine I'm using to write this, it's 250, which should allow for sleep > intervals in multiples of 0.004 seconds. Since most distributions do not create this file in /proc for whatever reason, and some people are being deliberately obtuse, does anyone know how to ask the kernel what the timer resolution is? Is it stored anywhere else in /proc or /sys? I kind of think most distros set it to 1000 Hz, but I'm not sure. From belred at gmail.com Wed Sep 17 02:13:07 2008 From: belred at gmail.com (belred) Date: Tue, 16 Sep 2008 23:13:07 -0700 (PDT) Subject: how many objects are loaded for hello world? Message-ID: i just read this blog about how many objects (types) are loaded for a hello world program in C#. http://blogs.msdn.com/abhinaba/archive/2008/09/15/how-many-types-are-loaded-for-hello-world.aspx how can you find out how many are loaded for a python program: print 'hello' From ceball at users.sourceforge.net Fri Sep 12 08:25:05 2008 From: ceball at users.sourceforge.net (Chris) Date: Fri, 12 Sep 2008 12:25:05 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: Message-ID: Carl Banks gmail.com> writes: ... > You can determine the offset the of the slot in the object structure > by > querying the member descriptor of the type object. That sounds like just the kind of thing we were looking for - thanks! > descr = GetAttrString(cls,"varname"); > offset = descr->d_member->offset; > slotvar = (PyObject*)(((char*)obj)+offset) Unfortunately, I am inexperienced at this kind of thing, so I wasn't able to get something working. Maybe someone could tell me what's wrong with the code below (it gives the error "'struct _object' has no member named 'd_member'")? PyObject *descr = PyObject_GetAttrString(x,"attr_one"); int offset = descr->d_member->offset; PyObject* slotvar = (PyObject*)(((char*)obj)+offset); where x is the class and attr_one is a slot (the full example is appended to this message). I guessed the type of offset; I'm not sure what it should be. I couldn't find any information about d_member on the web. > There might be some macros to simplify this. Sorry to say that I also have no idea about where to find such macros! Maybe I should continue this thread on capi-sig? Thanks for your help, Chris class MyObject(object): __slots__ = ['attr_one'] def __init__(self,attr_one=1.0): self.attr_one = attr_one import weave def test(): x = MyObject code = """ PyObject *descr = PyObject_GetAttrString(x,"attr_one"); int offset = descr->d_member->offset; //PyObject* slotvar = (PyObject*)(((char*)obj)+offset); """ weave.inline(code,['x'],local_dict=locals(),verbose=1) test() From calebjhansen at gmail.com Sat Sep 13 06:12:48 2008 From: calebjhansen at gmail.com (fishfin) Date: Sat, 13 Sep 2008 03:12:48 -0700 (PDT) Subject: question about python References: <9b3904d6-f780-4a9c-9c74-f6b333453ca0@p31g2000prf.googlegroups.com> <91f40dcc-d76d-437a-a7e2-ea26b9e333ed@b38g2000prf.googlegroups.com> Message-ID: <113ec6fd-5f64-4b74-b5c9-c26d12b086fa@s9g2000prg.googlegroups.com> On Sep 13, 4:25?pm, Carl Banks wrote: > On Sep 13, 1:00 am, fishfin wrote: > > > @ Carl: Yes, I think your right now that I look at it (or at least all > > except for the last two lines need to be indented). I'm still not sure > > how to send the stuff to the web browser though. Thanks for pointing > > it out! > > Try reading in the whole HTTP request instead of just the first line. > Change > > line = cfile.readline().strip() > > to > > line = cfile.read() > > And see if that helps. ?(Outputting the document so that it formats > the request well is left as an exercise. ?Also, as a heads up: in real > programs you should never output anything you receive through the > network without checking it or escaping it to prevent malicious uses.) > > Carl Banks I figured out what the problem was. When you had suggested that I indent the lines at first I did all of them, but when I did that there must have been an nonindented line before the last two lines which I had indented, so ending the 'while 1:'. Because of that, that code just flat out didn't work so I assumed that they must be not be indented which is why it hasn't been working all along. Thanks for your help! I don't think I would have every figured it out if you last post hadn't gotten me to thinking about little tweeks like that. From steven at REMOVE.THIS.cybersource.com.au Tue Sep 30 06:04:18 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 10:04:18 GMT Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> Message-ID: On Tue, 30 Sep 2008 19:04:41 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Tue, 30 Sep 2008 14:50:26 +1300, Lawrence D'Oliveiro wrote: >> >> > In message , r0g wrote: >> > >> >> You can only distribute modifications to gnuplot itself as patches, >> >> but you can distribute it freely ... > [?] > >> Where's the non-free bit? > > You're not free to modify gnuplot and redistribute the result. > > That you're free to distribute patches is nice, but it's not enough to > make the work free. The freedom to help people by giving them an > *already-modified* gnuplot is restricted by the copyright holder. > > It's an artificial restriction on redistribution of derived works, > making them second-class for the prupose of getting them into people's > hands. Yes it is. It seems a strange, unnecessary restriction. But is it sufficient to make it non-free? I don't think so. In case you are thinking that gnuplot allows people to *only* distribute the diffs, not the original source to apply the diffs onto, that is not the case. I quote from gnuplot > help copyright "Permission to distribute the released version of the source code along with corresponding source modifications in the form of a patch file is granted with same provisions 2 through 4 for binary distributions." Those provisions aren't terribly onerous, although #3 may be considered a privacy issue: 2. add special version identification to distinguish your version in addition to the base release version number, 3. provide your name and address as the primary contact for the support of your modified version, and 4. retain our contact information in regard to use of the base software. >> Personally, I don't get the whole "only distribute patches" >> requirement. It's a bit like saying "You're free to distribute this >> software, but only as a tarball". It seems silly to me. > > That, too, would be a non-free requirement. > >> But I don't see it as non-free, except in the sense that "only licences >> approved by the FSF are free". > > I try to judge freedom of a software work by the freedoms granted to all > recipients of the work, not by the approval of some organisation. Yes, but you accept some restrictions as legitimate. For example, you accept the restriction that the GPL makes that says you may not redistribute a modified work without making the source code available. That's a restriction, but it's not enough to disqualify it from being a free software licence. In fact, that restriction is *necessary* to make it a free software licence in the sense we're talking about. So "free" does not mean "no restrictions", it merely means "none of some sorts of restrictions, but other restrictions are okay". Likewise the restriction that GPL software must be distributed with a copy of the appropriate licence. It is useful to compare the "diffs only" licence to two different GPL- related scenarios. Scenario one is clearly against the spirit of the GPL, and possibly (hopefully!) the letter as well. Scenario two is not. (1) I distribute the modified source code encrypted and charge $1,000,000 for a NON-TRANSFERABLE licence to the encryption key. If you don't have the encryption key, that's your bad luck. (2) I distribute the modified source code archived in a tar file, and refuse to offer it in any other format. If you don't have an untar application, that's your bad luck. It's my contention that the restriction of supplying diffs is closer to Scenario 2 than to Scenario 1. The modified source is supplied, but it is split into two pieces: the official source, plus a set of diffs. Reversing that to get the modified source is not much more difficult than untarring a tarball. -- Steven From tino at wildenhain.de Sun Sep 28 17:38:39 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 28 Sep 2008 23:38:39 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> References: <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> <48DF63B2.2020408@wildenhain.de> <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> Message-ID: <48DFF95F.3080800@wildenhain.de> Michael Mabin wrote: > Tino, dude, I'm afraid I lied about my previous post being the last > word. There are some things you said here that must be addressed. Well. Its interesting to see thats either my English is so bad you don't understand or you are too tired. All what needs to be said was said be me and others in many different words and still you are defending already lost ground. Maybe you take your time reading the thread again, carefully. Maybe not ;) Have a good night Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From rowland at river2sea.org Wed Sep 10 00:32:21 2008 From: rowland at river2sea.org (rowland at river2sea.org) Date: Tue, 9 Sep 2008 21:32:21 -0700 (PDT) Subject: Simplest solution for formatting local time in iso 8601 including time zone. Message-ID: <382d494c-b32b-454a-842b-6f559a94e025@26g2000hsk.googlegroups.com> What's the simplest solution for formatting the output of local time in iso 8601 including the time zone information? Example: "2008-07-25T14:28:43.934-04:00" Thanks, Rowland From dear.jay.logan at gmail.com Mon Sep 1 09:37:14 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 1 Sep 2008 06:37:14 -0700 (PDT) Subject: Eleganz way to get rid of \n References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: <9cdcc2b1-36f9-49f5-94c1-54529e6d2cd0@e53g2000hsa.googlegroups.com> On Sep 1, 9:25?am, Hans M?ller wrote: > Hello, > > I'm quite often using this construct: > > for l in open("file", "r"): > ? ? ? ? do something > > here, l contains the \n or \r\n on windows at the end. > I get rid of it this way: > > for l in open("file", "r"): > ? ? ? ? while l[-1] in "\r\n": > ? ? ? ? ? ? ? ? l = l[:-1] > > I find this a little bit clumsy, but it works fine. > > Has someone a better solution ? > > Thanks > > Hans Can you do this: f = open(fname) for x in f: line = x.rstrip('\r\n') From greg.ewing at canterbury.ac.nz Wed Sep 3 21:44:13 2008 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Thu, 04 Sep 2008 13:44:13 +1200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <48BF3D6D.8060906@canterbury.ac.nz> Michael Palmer wrote: > So far, development of PyGUI seems to be a one-man effort, and it may > be slowed down by the attempt to develop the API and the > implementations concurrently. Could it be useful to uncouple the two, > such that the API would be specified ahead of the implementation? I'm not sure that would work very well. I don't think it's possible to invent a good API for something as complex as a GUI toolkit in the absence of experience using it, so the API has to evolve in parallel with at least one implementation, and with real applications that actually use the features concerned. Also, the features that go into the PyGUI API are partly determined by what is available in the underlying target libraries. I don't want to end up with things in the API specification that are too difficult or unwieldy to implement on some of the target platforms. I also don't want one implementation to get too far ahead of the others, for the same reason. If anyone wants to help, what's needed most right now is a good native Windows implementation. One or two people claimed to be working on that some time ago, but I haven't heard from them recently. For the reasons I mentioned above, I'm reluctant to forge ahead with too many new features until a native Windows version exists. -- Greg From tjreedy at udel.edu Sat Sep 6 13:35:23 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Sep 2008 13:35:23 -0400 Subject: Cancel instance create In-Reply-To: References: <1220697080.48c25bf890ade@www.inbox.lv> Message-ID: Fredrik Lundh wrote: > Aigars Aigars wrote: > >> I want MyClass to perform some tests and if them fail, I do not want >> instance to be created. If you do not want the instance created at all, you would have to write a custom .__new__ method, but that is tricky, something I would have to look up how to do, and most likely not needed. Fredrik's solution below is much easier and the one I would use if at all possible. >> But in code I wrote instance is created and also has parameters, that >> it should not have in case of tests failure. >> >> Is there a way to perform tests in MyClass.__init__ and set instance >> to None without any parameters? > > if you want construction to fail, raise an exception. > > ... > > def __init__(self): At this point, you have an instance of your class bound to local name 'self'. Usually, its only individual attributes are (in 3.0, anyway, as far as I can tell) .__class__ and an empty .__dict__. Of course, it inherits class and superclass attributes, but it is otherwise blank. (The main exception would be if you were inheriting from an immutable class that set attributes in .__new__, but then you would not be writing .__init__.) > self.param = "spam" > Test = False > if Test: # please don't use explicit tests for truth > print "Creating instance..." > else: > raise ValueError("some condition failed") > > (pick an exception class that matches the actual error, or create your > own class if necessary) Once the exception gets disposed of (if not before), the blank instance gets unbound from 'self' and since it does not get bound to anything else, it becomes eligible for garbage collection. tjr From pmaupin at gmail.com Sun Sep 7 13:00:48 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 7 Sep 2008 12:00:48 -0500 Subject: __builtins__ magic behavior Message-ID: __builtins__ in 2.5.2 doesn't seem to behave like I remember it did the last time I did some custom stuff with it, a very long time ago. This isn't surprising, because of ongoing optimization, but it's hard to google for '__builtins__' so I didn't really find any documentation on the current CPython behavior, which in some cases seems quite strange to me. The documentation node at http://docs.python.org/ref/naming.html has a "here be dragons" note on __builtins__, which is nice as far as it goes, but doesn't provide any help for people wanting to abuse the current CPython implementation. Additionally, the sentence immediately above the note, "__builtins__ can be set to a user-created dictionary to create a weak form of restricted execution" not only contradicts the note, but in some cases appears not to be true. When the code below is run, either standalone or by importing it, the builtins used are different depending on whether exec is used with globals() or with a copy of globals(). Any explanations for this behavior would be much appreciated. Thanks, Pat Executing: {{{ original = __builtins__ if hasattr(original, '__dict__'): original = original.__dict__ copy = original.copy() # Make the dictionaries different and use new one copy['foo'] = 'bar' del copy['len'] del original['chr'] __builtins__ = copy testcode = ''' try: print foo except: print "foo not found" try: print len except: print "len not found" try: print chr except: print "chr not found" print ''' x = globals() assert type(x) is dict y = {} y.update(x) assert y == x print 'Executing in globals()' exec testcode in x print 'Executing in copy' exec testcode in y }}} results in: Executing in globals() foo not found chr not found Executing in copy bar len not found From sjmachin at lexicon.net Tue Sep 2 21:45:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 18:45:28 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> Message-ID: On Sep 3, 11:00 am, process wrote: > how could I do getpixel once when x and y s changing? I was not referring to *calling* im.getpixel, I was referring to looking up getpixel as an attribute of im. How? See below. > > anyway I rewrote and saw I did a lot of stupid stuff. this is fast: > def getPixels5(fileName): > im = PIL.Image.open(fileName) > colors = [] > r, c = im.size im_getpixel = im.getpixel > for y in range(0, c): > row = [] > for x in range(0, r): > color = im.getpixel((x,y)) color = im_getpixel((x, y)) > row.append(color) > colors.append(row) > return numpy.array(colors) > > but I don't need it anuyway apparently since there already was such > methods :) From george at george-net.de Tue Sep 16 07:26:59 2008 From: george at george-net.de (Georg Altmann) Date: Tue, 16 Sep 2008 13:26:59 +0200 Subject: MVC with Python In-Reply-To: <3f0d61c40809151307p76c864e5he9911593b676548e@mail.gmail.com> References: <3f0d61c40809151307p76c864e5he9911593b676548e@mail.gmail.com> Message-ID: Marco Bizzarri schrieb: > On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann wrote: >> Hello, >> >> I need some advice on how to implement model-view-controller. I am trying to >> develop a GUI application with PyQt, yet the problem rather applies to mvc >> in general, not just GUI applications. >> >> Let's say the data is a list of objects with a common base class. The views >> are either a graphical representation of the objects or some form of textual >> input. The views shall change the model by using command objects (for undo, >> e.g. QUndoCommand). >> >> My current approach is to implement the model as a class with a list-like >> interface, with methods insert(), remove(), __getitem__(), __setitem__(),... >> and a signal to notify the views. The objects in the list have methods to >> change their state as well. >> >> My problem is, how do the commands interact with the model? >> Let's say I have a command that modifies an object o in the list. >> >> 1) If list[key_to_o] returns a reference to the object, the command can >> modify the object by using this reference, i.e. list[key_to_o].setX(). So >> there is no way for the list to know when the object changed - how can it >> emit a singal then? >> >> 2) If list[key_to_o] returns a deep copy of the object, >> copy_of_o = list[key_to_o], the command mofifies the copy and the updates >> the list: list[key_to_o] = copy_of_o. Now the list can emit a signal in >> __setitem__(). >> While this may work, it seems awkward to copy around objects just to perform >> a possibly simple operation on them. Additionally it might not be feasible >> once objects get complex. >> >> 3) The interface of the classes of the objects could be reflected in the >> list class, i.e. list.set_x_on_obj(key_to_obj,x). This would probably make >> the list class interface very bloated. >> >> Of course the problem is not really limited to Python, my apologies if I'm >> totally off-topic here. >> >> Regards >> Georg >> > > Well, I think one of the assumptions of the MVC is that the view can > be notified about the changes in the model. According to your > interface, the View can just be notified on operations about the > *whole* model, like adding or removing elements from it. > > But the elements of your list-like class should be a part of your > model, and therefore should be able to notify the Views by > themselfves. Ok, consider this: say the model needs to compute some sort of value by iterating over all objects in the list (for example some sort of hash). Some kind of view then displays this value. I could implement this by connecting a signal in each object to a slot in the list class which in turn emits a signal which is connected to the view. But this implies all the objects in the list have to be instances of QObject. I wonder if this is isn't a weird design, because for example all value type classes in Qt don't derive from QObject, e.g. QString. My list objects are not that simple (in terms of the data structure). So is it ok to make them QObjects? At least this seems to be better than making a copy of the object each time it is accessed. Regards Georg From derickvn at gmail.com Tue Sep 30 03:16:23 2008 From: derickvn at gmail.com (Derick van Niekerk) Date: Tue, 30 Sep 2008 00:16:23 -0700 (PDT) Subject: I built a nice html templater! Message-ID: <72bc4cad-1496-4e40-a800-7b28942de902@a70g2000hsh.googlegroups.com> Ok - so it's not really an awesome achievement and only handles basic templating needs (no loops and other programming constructs) but maybe someone will find it useful. It replaces any xml block where the id attribute is specified with contents provided - a description is provided in the comments. http://pastebin.com/m76f57ae2 My knowledge of python is limited and I would like someone to help me with wrapping a command line interface around this function. I need switches to specify input file, output file, key/value pairs for variable substitution and key/value pairs for substituting blocks with file contents (there is some clarification in the comments) Any help would be appreciated. Of course - feel free to use the code as you wish when you wish if you wish :) -d- From rcdailey at gmail.com Thu Sep 4 18:14:37 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Sep 2008 17:14:37 -0500 Subject: Case-insensitive string compare? Message-ID: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> Hi, I currently have a dictionary object that I'm doing the following with: if lib not in stage_map: # ... do stuff ... However, this will perform a case-sensitive comparison between lib and each key in stage_map. Is there a way to make this do a case-insensitive comparison instead? Yes, I realize I could do this: if lib not in [key.lower() for key in stage_map] However, I don't want to do this because it'll quickly end up getting messy. I want this solution to be an absolute last resort. I'm not a pro with python, so I'm hoping there are cleaner alternatives out there. Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From claird at lairds.us Thu Sep 4 08:02:08 2008 From: claird at lairds.us (Cameron Laird) Date: Thu, 4 Sep 2008 12:02:08 +0000 Subject: use str as variable name References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> Message-ID: <0bv4p5-00b.ln1@lairds.us> In article <48bf9d12$0$7552$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: >Mathieu Prevot a ?crit : >> 2008/9/4 Chris Rebert : > >(snip) > >>> You're looking for the setattr() built-in function. In this exact case: >>> setattr(a, arg, new_value) >>> >>> This is probably covered in the Python tutorial, please read it. >>> >>> Regards, >>> Chris >> >> Indeed. >> >> I'll use: >> a.__setattr__(height, new_value) > >Please don't. Use the generic setattr() function instead. This holds for >any __magic__ method : they are *implementation* for operators and >generic functions - which you can think of as operators with a function >syntax -, and are not meant to be called directly. You wouldn't write >something like 2.__add__(3), would you ? > Along with the good advice the usual suspects have given, my intuition is that there's an even better implementation that doesn't setattr() at all. While it's impossible to know, of course, because we don't have the original poster's true requirements, I conjecture that, rather than "to link this [user-supplied] word to a class variable", what will serve him best is to regard the user text as an index into a class dictionary. From nytrokiss at gmail.com Thu Sep 18 12:29:01 2008 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 18 Sep 2008 09:29:01 -0700 Subject: TCP Server Message-ID: <8a6b8e350809180929j6c0eac81i9daa81a1815b5a82@mail.gmail.com> Dear List, I am looking to write a TCP socket server and was wondering what are the pros and cons of using twisted over the sockets modules bundled in python? Thanks James -- http://www.goldwatches.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeremy at jeremybanks.ca Mon Sep 1 03:23:38 2008 From: jeremy at jeremybanks.ca (Jeremy Banks) Date: Mon, 1 Sep 2008 03:23:38 -0400 Subject: Inquiry regarding the name of subprocess.Popen class Message-ID: <2008090103233816807-jeremy@jeremybanksca> Hi. I wondered if anyone knew the rationale behind the naming of the Popen class in the subprocess module. Popen sounds like the a suitable name for a function that created a subprocess, but the object itself is a subprocess, not a "popen". It seems that it would be more accurate to just name the class Subprocess, can anyone explain why this is not the case? Thank you. From prologic at shortcircuit.net.au Sat Sep 20 05:29:14 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Sat, 20 Sep 2008 19:29:14 +1000 Subject: Not fully OO ? In-Reply-To: <48d4c11b$0$22877$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: This is wrong. Python _is_ a full OOP language. Everything form modules, functions to basic data types are an object. --JamesMills On Sat, Sep 20, 2008 at 7:23 PM, candide wrote: > Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > > Thanks for any comment. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 21:19:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 01:19:02 GMT Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <00e59af7$0$20331$c3e8da3@news.astraweb.com> On Sun, 21 Sep 2008 01:56:59 +0200, Christian Heimes wrote: > Just *don't* try to abuse lists by creating fancy stuff e.g. linked > lists. The memory overhead is going to kill your app. I agree with your advice not to abuse lists, but not for the reason you give. The memory overhead of a linked list implemented on top of a Python list probably isn't going to be that much greater than a dict or a class. I think the real reasons why linked lists get a bad rep in Python are: (1) they're unnecessary 99% of the time; (2) when they are necessary, a better implementation is to use classes (e.g. see traceback objects); and (3) the standard Lisp idiom for lists is horribly inefficient in CPython: alist = [1, [2, [3, [4, [5, [6, []]]]]]] But that's primarily inefficient because of the number of method calls needed to access an item. There is some memory overhead, but memory is cheap and the overhead of using objects in the first place is far larger than the overhead of a few extra pointers. -- Steven From paul at boddie.org.uk Fri Sep 12 05:34:37 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 12 Sep 2008 02:34:37 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> Message-ID: <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> On 12 Sep, 08:30, Steven D'Aprano wrote: > > Which is why I previously said that XML was not well suited for random > access. Maybe not. A consideration of other storage formats such as HDF5 might be appropriate: http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html There are, of course, HDF5 tools available for Python. > I think we're starting to be sucked into a vortex of obtuse and opaque > communication. I don't know about that. I'm managing to keep up with the discussion. > We agree that XML can store hierarchical data, and that it > has to be read and written sequentially, and that whatever the merits of > castironpi's software, his original use-case of random access to a 4GB > XML file isn't workable. Yes? Again, XML specifically might not be workable for random access in a serialised form, despite people's best efforts at processing it in various unconventional ways, but that doesn't mean that random access to a 4GB file containing hierarchical data isn't possible, so I suppose it depends on whether he is wedded to the idea of using vanilla XML or not. It's always worth exploring the available alternatives before embarking on a challenging project, unless one wants to pursue the exercise as a learning experience, and I therefore suggest investigating whether HDF5 doesn't already solve at least some of the problems or use-cases stated in this discussion. Paul From paul at boddie.org.uk Tue Sep 2 13:50:10 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 2 Sep 2008 10:50:10 -0700 (PDT) Subject: (in memory) database References: <5enqo5-9n9.ln1@lairds.us> <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> <3e419475-61a1-4579-a8b6-fc15f9fe0a9b@m73g2000hsh.googlegroups.com> Message-ID: On 2 Sep, 17:38, Zentrader wrote: > > I don't understand why Cameron has a different version of Python which > > doesn't seem to have sqlite support enabled. > > Agreed, but won't the package manager tell him if python-sqlite is > installed? It shouldn't need to be installed: the python2.5 package includes the sqlite3 module and the _sqlite extension module. He's running a more modern version of Ubuntu than I am, but I don't think that they've reintroduced the python-sqlite package in any form. > That would be the next step since it appears that SQLite > intself is already installed. Since Ubuntu uses precompied binaries, > Python should be configured for SQLite which again leaves no python- > sqlite as the only possibility (yeah right). BTW Python is easy to > install manually. Indeed, which is why I think that there must be a manually installed Python on his system, especially given that /usr/local/lib/python2.5/ sqlite3/__init__.py is one of the files mentioned in the traceback. Paul From littlesweetmelon at gmail.com Sat Sep 27 22:54:49 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Sun, 28 Sep 2008 10:54:49 +0800 Subject: design pattern: MVC in python Message-ID: Howdy, I am working on a small PC game by using pygame. Since there are many graphical objects to display and intensive user interactions, I would like to employ MVC pattern to keep the system maintainable. However, I cannot find a good article which discussing the general knowledge about MVC, especially: 1. How to decouple M-V-C? That is, which function should be assigned to which part. 2. How to communicate each other while keeping M-V-C decoupled? 3. Do I need to create Interface/Proxy class for each component? 4. What is the general principle for designing the interface of M-V-C? As my previous experience, if without special care on the principle, the MVC pattern would gradually become messy and the boundary between each component becomes unclear. Could you give me any advice? In addition, can we take the advantage of python language to make MVC easy-to-build and easy-to-use? Thank you in advance. -- ShenLei From cjw at ncf.ca Sat Sep 20 11:14:33 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 20 Sep 2008 11:14:33 -0400 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: Fredrik Lundh wrote: > Colin J. Williams wrote: > >> "foreach: for x in array: statements >> >> Loops over the array given by array. On each iteration, the value of >> the current element is assigned to x and the internal array pointer is >> advanced by one. " >> >> This could be a useful addition to Python. > > for-in could be a useful addition to Python? looks like Guido's used > his time machine again, then, since it's been around since the pre-1.0 > days: > > http://www.python.org/doc/ref/for.html > > > Thanks. for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite] Colin W. From ralf at brainbot.com Thu Sep 18 06:52:51 2008 From: ralf at brainbot.com (Ralf Schmitt) Date: Thu, 18 Sep 2008 12:52:51 +0200 Subject: ANN: bbfreeze 0.96.5 Message-ID: Hi all, I uploaded bbfreeze 0.96.5 to the python package index. bbfreeze creates standalone executables from python scripts (similar to py2exe). bbfreeze works on windows and unix-like operating systems (no OS X unfortunately). bbfreeze is able to freeze multiple scripts, handle egg files and track binary dependencies. This release features a new bdist_bbfreeze command, which integrates bbfreeze into setup.py scripts (contributed by Hartmut Goebel, thanks). More information can be found at the python package index: http://pypi.python.org/pypi/bbfreeze/ Regards, - Ralf From toddw at activestate.com Wed Sep 17 14:21:20 2008 From: toddw at activestate.com (Todd Whiteman) Date: Wed, 17 Sep 2008 11:21:20 -0700 Subject: ANN: Python GUI development using XULRunner In-Reply-To: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> References: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> Message-ID: <48D14AA0.50103@activestate.com> Don Spaulding wrote: > On Sep 16, 8:29 pm, Todd Whiteman wrote: >> I've put together a tutorial that shows off how to build a GUI >> application using XULRunner (same architectural components as Firefox >> uses) that can be used in conjunction with the Python programming language. >> >> The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > I get to the "Running" step and run into "Couldn't load XPCOM." > > Does this work on x86_64? Or have I made a rookie mistake? Hi Don, A good question. Mozilla only provide 32-bit XulRunner applications by default, you you'll need to install the necessary 32-bit compatability libraries on your Linux machine, i.e. for Ubuntu it's something like: sudo apt-get install ia32-libs ia32-libs-gtk Then you should be able to run the example. You can check the dependencies using something the following commands, there should be no missing dependencies: $ cd pyxpcom_gui_app/xulrunner $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin It is possible to use a 64-bit version, but you'll need to compile this yourself (or find somewhere that provides these x86_64 versions). Note that the PythonExt project does not offer Python bindings for x86_64 either (it's on my todo list), you can compile the PythonExt part yourself as well if you need a 64-bit version. Cheers, Todd From inq1ltd at inqvista.com Mon Sep 22 14:46:29 2008 From: inq1ltd at inqvista.com (jim-on-linux) Date: Mon, 22 Sep 2008 14:46:29 -0400 Subject: Problems running on hp dual core processor In-Reply-To: <200809221443.25765.inq1ltd@inqvista.com> References: <200809221443.25765.inq1ltd@inqvista.com> Message-ID: <200809221446.29472.inq1ltd@inqvista.com> Python help, I have a number of clients running a program built with python 2.5. One has just purchased an HP with a duel core processor, 2.2G with .099g ram. On the new hp, when they try to print they get an import error; File win32ui.pyc line 12, in File win32ui.pyc, line 10, in _load ImportError: DLL load failed: The specified module could not be found. The file is there The only difference I could find from their other machines is the processor. I would appreciate any help Jim-on-linux From dudeja.rajat at gmail.com Sun Sep 28 11:47:51 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sun, 28 Sep 2008 16:47:51 +0100 Subject: Unable to write % character to a file using writelines() method Message-ID: Hi, I'm using the writelines() method to write some lines to a text file. But I'm unable to write the % character to the file using the following format: fdTolFile.writelines("\n\tdiff Not in %s '%' range" %(toleranceInPer)) The second % does not get write to the file and Im getting errors. Please suggest what additional information should I give to write the % character. The errro Im getting is : File "C:\Documents and Settings\\TA-workspace\src\TestAndCompareResults.py", line 840, in __parseDiffTextFile fdTolFile.writelines("\n\tdiff in %s'%' range" %(toleranceInPer)) TypeError: not enough arguments for format string I've also tried this: fdTolFile.writelines("\n\tdiff Not in %s \% range" %(toleranceInPer)) But still I get the same error Thanks and regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From metaperl at gmail.com Thu Sep 18 16:20:58 2008 From: metaperl at gmail.com (metaperl.com) Date: Thu, 18 Sep 2008 13:20:58 -0700 (PDT) Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: On Sep 9, 12:42?pm, Fredrik Lundh wrote: > > you may also want to do re.escape on all the words, to avoid surprises > when the choices contain special characters. yes, thank you very much: import re def oneOf(s): alts = sorted(s.split(), reverse=True) alts = [re.escape(s) for s in alts] return "|".join(alts) From asmodai at in-nomine.org Tue Sep 9 04:00:26 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Tue, 9 Sep 2008 10:00:26 +0200 Subject: universal unicode font for reportlab In-Reply-To: References: <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> Message-ID: <20080909080026.GF30869@nexus.in-nomine.org> -On [20080909 05:23], Terry Reedy (tjreedy at udel.edu) wrote: >Ariel Unicode MS is the one that seems pretty complete. Not really. It misses a lot of characters. Might I recommend using BabelMap (http://www.babelstone.co.uk/Software/BabelMap.html) so you can investigate your fonts? The only font I am aware of that supports a lot of Unicode fonts is James Kass' Code 200x fonts (http://www.code2000.net/). In almost all cases you will need to gather a collection of fonts in order to typeset your documents as it is hard to find font designers who know enough about all languages to properly design the fonts. Not to mention such fonts would quickly grow unwieldy. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B A kiss is a lovely trick designed by nature to stop speech when words become superfluous... From rocky at panix.com Fri Sep 5 17:03:46 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 05 Sep 2008 17:03:46 -0400 Subject: pdb bug and questions References: Message-ID: Stef Mientki writes: > From: Stef Mientki > Subject: Re: pdb bug and questions > Newsgroups: comp.lang.python > To: "python-list at python.org" > Date: Fri, 05 Sep 2008 22:06:19 +0200 > > R. Bernstein wrote: >> Stef Mientki writes: >> >> >>> hello, >>> >>> I'm trying to embed a debugger into an editor. >>> I'm only interested in high level debugging. >>> The first question is what debugger is the best for my purpose ? >>> (pdb, pydb, rpdb2, smart debugger, extended debugger ? >>> >>> Second question, in none of the above debuggers (except rpdb2), >>> I can find a "break now", >>> so it seems impossible to me to detect unlimited while loops ? >>> >> >> I am not sure what you mean by "break now". pdb and pydb allow direct >> calls from a program to the debugger via set_trace (which in pydb is >> deprecated in favor of I think the more descriptive name: debugger) >> But I suspect this is not what you mean to "detect unlimited while >> loops"; pydb also has gdb-style signal handling that allows for entry >> into the debugger when the debugged python process receives a >> particular signal. "info handle" lists all of the interrupts and what >> action is to be taken on each. See >> http://bashdb.sourceforge.net/pydb/pydb/lib/node38.html >> >> However I believe that signals are only handled by the main thread; so >> if that's blocked, the python process won't see the signal. >> > Thanks, > Yes, I think the trace option can do the job, > certainly if I display every line. > Didn't know pdb had something like settrace ( the information on pdb > is very condensed ;-) It sounds to me like there may be some confusion -- if at least on my part. pdb's set_trace (with the underscore) is documented here: http://docs.python.org/lib/module-pdb.html . Yes, perhaps it would be nice if that document gave an example. But set_trace is a method call, not an option. There is a pydb debugger *command* called "set trace" as well as a command-line option (-X --trace) which turns on line tracing and is something totally different. It can be fun to use that with "set linetrace delay" in an editor to allow one to watch the lines execute as the program runs. I did this with emacs in this video: http://showmedo.com/videos/video?name=pythonBernsteinPydbIntro&fromSeriesID=28 >> >>> For the moment I started with pdb, because most of the debuggers seems >>> to be an extension on pdb. >>> When I launch the debugger ( winXP, Python 2.5) from with my editor >>> python -u -m pdb D:\\Data\\test_IDE.py >>> I get this error >>> IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') >>> NOTICE 1 backslash ----------------------------------^ >>> >>> If I launch the debugger with >>> python -u -m pdb D:/Data/test_IDE.py >>> It runs fine. >>> >>> This looks like a bug to me. >>> What's the best way to report these kind of bugs ? >>> >> >> winpdb, pydb and pdb (part of Python) all have Sourceforge projects >> which have bug trackers. For pdb, in the past people includng myself, >> have reported features, patches and bugs in the Python tracker; >> eventually it gets handled. (Eventually in my case means a year or >> so.) But if my information is incorrect or out of date, no doubt >> someone will correct me. >> > I'll take a look, for the sake of our children ;-) >> As mentioned in the last paragraph, pydb also is a Sourceforge project >> (part of bashdb) which has a tracker for bug reporting. Using the bug >> tracker I think is better than discussing pydb bugs in c.l.p. > c.l.p. ? This newsgroup, comp.lang.python. >> By >> extension, I assume the same is also true for the other debuggers. >> >> Finally, I think rpdb2 is part of the winpdb project on Sourceforge >> and again has a bug tracker. My sense is that Nir Aides is very good >> about handling bugs reported in winpdb/rpdb. >> > Yes I started with rpdb2, > and indeed Nir Aides is very helpfull, > but I think interfaceing rpdb2 is a little too difficult for me, > > For now I think pydb is the choice, > better control and more functions than pdb, > and almost just as easy. If there are things that are unnecessarily awkward, and especially if you can think of a way to make pydb better (that hasn't been suggested before), please submit a feature request in the tracker for pydb. Thanks. From george.sakkis at gmail.com Mon Sep 29 11:54:58 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 29 Sep 2008 08:54:58 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> <45c74b74-214c-4fed-b691-6020a1aedce6@a1g2000hsb.googlegroups.com> Message-ID: <16f8d6ab-1284-4099-9326-fb367d454b50@59g2000hsb.googlegroups.com> On Sep 29, 11:37 am, bearophileH... at lycos.com wrote: > George Sakkis: > > > No difference in principle, just len() happens to be implemented more > > often than upper(). > > That's an important point. In a language that tries to be both > practical, readable, and elegant, the things that are done more may > deserve some sugar, to avoid code like this in many cases: > > sorted(seq, key=lambda x:x.__len__()) If this was the most compelling use case of having len as builtin, I would be even less convinced. How often do you sort by len? FWIW, the most common sorting keys I see in real world are attrgetter(some_attr) or itemgetter(some_index) and both are imported functions, not builtins. George From samuel.morhaim at gmail.com Tue Sep 23 12:03:57 2008 From: samuel.morhaim at gmail.com (Samuel Morhaim) Date: Tue, 23 Sep 2008 12:03:57 -0400 Subject: SPE restore defaults Message-ID: <65c3648d0809230903t558782b8wdaef9d7c278bc617@mail.gmail.com> Hi, I am sorry if this is a bit off topic... I downloaded SPE, but i changed the config option by mistake to a Skin only for Mac... so everytime i start SPE it crashes. I tried uninstalling, but it didnt work, it seems the value is in the registry, but i couldnt find it. Can anyone help? (Spe forum is not useful.. thanks) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rocksportrocker at googlemail.com Thu Sep 11 07:11:49 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 11 Sep 2008 04:11:49 -0700 (PDT) Subject: Use Python to solve equations? References: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Message-ID: On 11 Sep., 09:09, Kelie wrote: > Hello group, > > Is there any packages in Python that will help me solve functions > similar to this: > > x = a*(1+bx)**2.5-c where a, b, c is known and the task to solve x? > > Thank you, > > Kelie look at www.sagemath.com . it is great. greetings, uwe From larudwer at freenet.de Thu Sep 4 16:45:15 2008 From: larudwer at freenet.de (Ruediger) Date: Thu, 04 Sep 2008 22:45:15 +0200 Subject: why is self not passed to id()? < solved > References: Message-ID: castironpi wrote: > > The answer is fairly technical. For member functions to be bound to > instances, they are required to have a __get__ method (which takes > instance and owner as parameters). 'id' does not. > > (Why does 'id' not have a __get__ method?) > > By contrast, > >>>> set.add > >>>> dir(_) > ['__call__', '__class__', '__delattr__', '__doc__', '__get__', > '__getattribute__ > ', '__hash__', '__init__', '__name__', '__new__', '__objclass__', > '__reduce__', > '__reduce_ex__', '__repr__', '__setattr__', '__str__'] > > 'set.add' does. Thank you for the quick response. However it gives me less hope that the little performance hack I had in mind will ever work. From apardon at forel.vub.ac.be Fri Sep 19 10:01:06 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Sep 2008 14:01:06 GMT Subject: cups.Connection.printFile References: Message-ID: On 2008-09-16, Graham Jenkins wrote: > > I'm trying to print a file from within a Python program. > > The quick-and-dirty solution is to use something like: > > fd = os.popen("lp -d MyPrinter", "wb") > fd.write(MyFileContents) > > But it seems to me that there should be a clean solution like: > > import cups > stat = > cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") What about systems that don't use cups for printing? -- Antoon Pardon From bignose+hates-spam at benfinney.id.au Mon Sep 1 23:51:16 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 02 Sep 2008 13:51:16 +1000 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> Message-ID: <878wubp5mz.fsf@benfinney.id.au> bearophileHUGS at lycos.com writes: > Ben Finney: > > I don't see any good reason (other than your familiarity with the > > D language) to use underscores for this purpose, and much more > > reason (readability, consistency, fewer arbitrary differences in > > syntax, perhaps simpler implementation) to use whitespace just as > > with string literals. > > It's not just my familiarity, Ada language too uses underscore for > that purpose, I think, so there's a precedent, and Ada is a language > designed to always minimize programming errors, simple code mistakes > too. I would argue that the precedent, already within Python, for using a space to separate pieces of a string literal, is more important than precedents from other programming languages. > Consider: > > a = 125 125 125 > > a = 125, 125, 125 > > a = 125_125_125 > > For me the gestalt of the first line looks too much like the second > one, that is three separated things This is no more the case than for literal strings: a = "spam" "eggs" "ham" a = "spam", "eggs", "ham" Yet this is already a valid way in Python to specify, respectively, a single literal string and a literal tuple of strings. > While in the third case the _ helps glue the parts, creating a > single gestalt to my eyes. To my eyes, it's needlessly hard to read, and looks too similar to an identifier, not a literal. On the other hand, the spaces version is easy to see as analogous to the same syntax rules that already exist for strings. > Note that it's not just a matter of font and familiarity, it's also a > matter of brains. Your brain may be different from mine, so it may be > possible that what's better for you isn't better for me. So in such > situation a popular voting may be the only way to choose. But for me > having spaces to split number literals in parts is _worse_ than not > having any way at all to split them. So I'm strong opposed to your > suggestion, so I may not even propose the PEP if lot of people agrees > with your tastes. Thanks for making your position clear. -- \ ?The WWW is exciting because Microsoft doesn't own it, and | `\ therefore, there's a tremendous amount of innovation | _o__) happening.? ?Steve Jobs | Ben Finney From brenNOSPAMbarn at NObrenSPAMbarn.net Wed Sep 3 17:09:02 2008 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Wed, 03 Sep 2008 21:09:02 GMT Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: Michael Palmer wrote: > As anyone knows, the state of Python GUI programming is a little > fractured at this time, with many toolkits, wrappers and meta-wrappers > dead and alive, with or without documentation. How about Dabo? http://www.dabodev.com/ -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From moogyd at yahoo.co.uk Mon Sep 15 02:58:53 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sun, 14 Sep 2008 23:58:53 -0700 (PDT) Subject: noob: subprocess clarification References: <68fcdea2-804e-4fba-958e-47ecee277faf@s50g2000hsb.googlegroups.com> Message-ID: <170924a4-f17f-44d7-9772-c3044d547fca@s50g2000hsb.googlegroups.com> On 14 Sep, 22:06, Dennis Lee Bieber wrote: > On Sun, 14 Sep 2008 02:29:52 -0700 (PDT), moo... at yahoo.co.uk declaimed > the following in comp.lang.python: > > > Can somebody please clarify what the shell=True does, and whether I am > > using it correctly. > > What part of: > > """ > On Unix, with shell=False (default): In this case, the Popen class uses > os.execvp() to execute the child program. args should normally be a > sequence. A string will be treated as a sequence with the string as the > only item (the program to execute). > > On Unix, with shell=True: If args is a string, it specifies the command > string to execute through the shell. If args is a sequence, the first > item specifies the command string, and any additional items will be > treated as additional shell arguments. > """ > > is giving problems? I assume that this is sarchasm :-) > > For the most part, as I recall, "shell=True" allows you to invoke > commands that are built-in/native to the default shell, or even a shell > script. False requires the specified command to be a stand-alone > executable program. > -- From gagsl-py2 at yahoo.com.ar Fri Sep 19 11:56:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 12:56:24 -0300 Subject: Multimapping and string converting References: <26c69b160809190659i54dbfae1xd5794cd2ff433a1c@mail.gmail.com> Message-ID: En Fri, 19 Sep 2008 10:59:26 -0300, Ron Brennan escribi?: > Hello, > > I have a multimap dictionary with a 1 Key to N values. I want to convert > the N values to a string to be used elsewhere in my program. > > So I have dict[(1,[1, 2 ,3 ,4])] which I have sorted > > When I do a print ''.join(str(dict.value())) I get [1, 2, 3, 4] as an > output > when I really want 1 2 3 4 > > Here is my code: > > dmapItems = dictionary.items() > dmapItems.sort() > > for tcKey, tcValue in dmapItems: > file.write('Key = %s\nValue = %s" % (tcKey, tcValue) > > stinger = ''.join(str(tcValue)) > > print stringer > > The Output = [145, 2345, 567, 898] > I need it to be 145 2345 567 898 I guess you probably tried using ' '.join(value) and got an error like this: TypeError: sequence item 0: expected string, int found so you inserted that str(...), but you don't still get what you want. You want "145 2345 567 898". *If* you had a list like this: value = ["145", "2345", "567", "898"] (that is, a list of strings) *then* ' '.join(value) would do what you want. But you have this to start with instead: value = [145, 2345, 567, 898] (a list of numbers), how to convert it into a list of strings? str(value) returns a single string that "looks like" a list but isn't: "[145, 2345, 567, 898]". Instead, you need to convert each element individually, and keep them in a list. Try this: value = [str(elem) for elem in value] Also, I'd use sorted() to iterate over all items. PUtting all together: for tcKey, tcValue in sorted(dictionary.items()): values = [str(elem) for elem in tcValue] values = ' '.join(values) print tcKey, values or perhaps: for tcKey, tcValue in sorted(find_a_good_name_for_me.iteritems()): values_str = ' '.join(str(elem) for elem in tcValue) print tcKey, values_str (using lazy objects (iteritems and a generator expression) instead of concrete lists) -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 09:40:02 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 13:40:02 GMT Subject: doctest not seeing any of my doc tests Message-ID: <00d3d407$0$20306$c3e8da3@news.astraweb.com> I have a function in my module: def selftest(verbose=False): import doctest doctest.testmod(verbose=verbose) When I run it, it fails to find any of my doc tests, including the tests in __main__, and in fact it looks like it can't even find my functions and classes: >>> mymodule.selftest(True) 1 items had no tests: __main__ 0 tests in 1 items. 0 passed and 0 failed. Test passed. The second and subsequent times I call selftest, I get the same result except that it adds this line to the end: *** DocTestRunner.merge: '__main__' in both testers; summing outcomes. I've exited from Python and restarted the interactive interpreter. I've deleted the module .pyc file. Neither has helped. I've tried reading over the doctest module to see if there are any hints as to what's going wrong, but it's quite opaque to me. If there's anyone out there with a good understanding of doctest, I'd appreciate some pointers for where to start looking, or otherwise how to fix this problem. For what it's worth, I'm running Python 2.5 (r25:51908, Apr 10 2007, 10:29:13) [GCC 4.1.2 20070403 (Red Hat 4.1.2-8)] on linux2 -- Steven From FettManChu at gmail.com Thu Sep 4 15:50:25 2008 From: FettManChu at gmail.com (Fett) Date: Thu, 4 Sep 2008 12:50:25 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: Message-ID: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> On Sep 4, 2:23?pm, Mike Driscoll wrote: > On Sep 4, 1:39?pm, Fett wrote: > > > > > I need a crypto package that works on windows with python 2.5. Can > > anyone suggest one for me? > > > I have been searching for a couple days for a good cryptography > > package to use for public/private key encryption, at this point I > > would settle for symmetric even. > > > Every encryption package I have found for python was either operating > > system specific (read *nix only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/ > > > There was one exception, this version was specifically built to run on > > any platform (yay), but the compiler for windows complained that I > > wasn't using python2.2 (though the package was said to only need 2.2 > > or newer). > > > Is there any crypto package that is actually written in python? I > > seriously don't care how slow it is. > > How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads > > Mike Seems that this is intended more for webapps or something, I intend to use this for a client application. This means that I can't require outside dependencies, or I risk annoying the clients (if you have installed many open-source projects with dependencies that aren't handled by portage/apt-get, you know what I would be doing to them). I seriously can't believe that there isn't a single python native crypto package. Why do they all need to have outside dependencies? From marco.bizzarri at gmail.com Thu Sep 4 10:40:14 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 16:40:14 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <3f0d61c40809040739t4ea080b1nc2683f43b1558b6@mail.gmail.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <6i9uidFphkg0U1@mid.uni-berlin.de> <3f0d61c40809040739t4ea080b1nc2683f43b1558b6@mail.gmail.com> Message-ID: <3f0d61c40809040740u66ac4f90l858d86647495040d@mail.gmail.com> On Thu, Sep 4, 2008 at 4:39 PM, Marco Bizzarri wrote: > > Most probably you're right. Maybe I will make a trip back to my > university books and take a look at them again :-) > Meant: you *are* right. Sorry. Saluti Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From castironpi at gmail.com Sat Sep 20 22:33:17 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 19:33:17 -0700 (PDT) Subject: writeable buffer and struct.pack_into and struct.unpck_from References: Message-ID: <866704af-aa81-4688-9ece-2a8f336c5fc7@m44g2000hsc.googlegroups.com> On Sep 20, 6:42?pm, "Gabriel Genellina" wrote: > En Sat, 20 Sep 2008 15:45:48 -0300, Tzury Bar Yochay ? > escribi?: > > > I can't find in the documentation the way to use these two functions. > > > can someone share a simple code that utilize these two functions? > > struct.pack_into is intended to "fill" a buffer you got from somewhere, ? > probably other language or process. ctypes.create_string_buffer may be ? > used to create a writable buffer in python code. > > py> from ctypes import create_string_buffer > py> b = create_string_buffer(10) > py> b.raw > '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' > py> from struct import * > py> pack_into("hhh", b, 0, 1, 2, -1) > py> b.raw > '\x01\x00\x02\x00\xff\xff\x00\x00\x00\x00' > > unpack_from does the opposite. > Before Python 2.5, That was when Python broke string immutability with the ctypes module. > you had to use pack to create a string object, and then ? > copy its contents into the destination buffer; using pack_into avoids the ? > memory copy. > > -- > Gabriel Genellina 'mmap' seems to have always offered random-access writes. A search through the implementation for "tp_as_buffer" returns a lot of zeros however. From grante at visi.com Sun Sep 14 22:10:14 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 21:10:14 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: On 2008-09-15, Ben Finney wrote: > Grant Edwards writes: >> On 2008-09-14, Ben Finney wrote: >> >>> Second: please do yourself a favour and drop the >>> camelCaseNames. Follow PEP 8 >>> for style and >>> naming in your Python code. >> >> If he finds camelcase more readable and easier to type (as do >> I), how is switching to underscores "doing himself a favor"? >> >> I'm generally in favor of using a consistent naming style >> throughout a project, but I don't see why the naming style >> used in my source code should be subject to somebody else's >> arbitrary standard. > > Because the code we write rarely stays isolated from other > code. There is an existing convention, There are many existing conventions. > and it's better to pick a (sufficiently sane) style convention > and stick to it than argue about what the convention should > be. I suppose if everybody agreed to pick one, and all the source code in the world was changed to meet it, that would "a good thing". It just seems like a goal so unrealistic as to make it a bit of an overstatement to tell people they're better off following convention X than following convention Y. When packages as significant as wxPython use naming conventions other than PEP 8, I find it hard to make a case that the PEP 8 naming convention is any better than any other. >> When it comes to writing code intended for the standard >> library in the main Python distribution, I would certainly >> defer to the existing standard as defined in PEP 8. However, >> I don't see any reason that style should be imposed on all >> everybody else. > > Who's imposing? I'm saying it's a good idea for everyone to do > it, and going so far as to say that one is doing oneself a > favour by following the convention. I have no more power than > you to "impose" convention on anyone. My apologies -- "impose" was too strong a word to use. If we were starting from scratch and there was no extant source code in the world, then it would make sense to encourage everybody to pick one convention. [I still think it would be rather quixotic.] But, there are so many projects out there with naming conventions other than PEP 8, that I don't see how there's an advantage to picking one over another (except for the obvious also-rans like "all upper case, no vowels, and a maximum length of 6 characters"). I'll agree that sticking with a single convention within a project is definitely a good thing. I'm personally aware of mixed/camel-case projects from 25+ years ago, so I'm afraid PEP 8 came along a bit too late... -- Grant From hniksic at xemacs.org Sat Sep 13 16:27:09 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 13 Sep 2008 22:27:09 +0200 Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> Message-ID: <87fxo3bxlu.fsf@mulj.homelinux.net> Terry Reedy writes: >> Of course, sum() is even faster than reduce: >> >>>>> Timer('sum(xrange(10000))').repeat(number=10000) >> [9.814924955368042, 8.7169640064239502, 9.5062401294708252] > > 'Of course', because the irreducible difference between > reduce(add.seq) and sum(seq) is that reduce has to call an add > function while sum has the operation built-in in place of a call. Note that, despite appearances, it's not as built-in as one might wish. sum(seq) is still completely generic and works on all number-like objects (in fact on all objects that define an __add__ operation except strings, which are explicitly forbidden). This means that it can't just go ahead and execute a C addition, it must properly call PyNumber_Add (the C API call equivalent to Python's "+" operator), which will then inspect the objects and invoke the appropriate implementation of addition. On the other hand, operator.add is defined to do exactly that -- call PyNumber_Add on its arguments and return the result. It's not entirely obvious why summing numbers using the same method, repeatedly calling PyNumber_Add, would be significantly slower for reduce than for sum. Admittedly reduce has to execute a Python-level function call which requires allocating and filling out a tuple, only to reach PyNumber_Add, which sum calls immediately. But builtin_reduce() is actually careful to optimize those repeated function calls, for example by reusing the same tuple across the loop. From peter.anderson at internode.on.net Sat Sep 6 03:50:16 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sat, 06 Sep 2008 17:50:16 +1000 Subject: wxPython problem Message-ID: <48C23638.1000109@internode.on.net> I am trying to teach myself how to program in Python and use wxPython for GUIs. I am using PyScripter, IDLE and EditPlus as my IDEs. I have experienced an odd problem where I run a script once and it runs fine. Run it again and I get an error and the script fails. If the script is run directly from Python ('Run' from Windows Explorer) or from EditPlus (in which I have a "user-defined tool" which calls C:\Python25\pythonw.exe with the parameter of $(FileName)) then there is *never* any error, no matter how many times the script is run. Close down PyScripter or IDLE and then start either up again, load the script and run it - it runs fine. Run it again and it fails. It seems like something is already set in memory and cant be re-set (my lack of knowledge is showing here :-( ). More details are shown below. Any help or hints would be greatly appreciated. Regards, Peter RUNNING SIMPLE.PY (AND OTHER SCRIPTS USING WXPYTHON) FROM PYSCRIPTER I GET THE FOLLOWING ERROR MESSAGE: PyNoAppError: The wx.App object must be created first! PyScripter loads a module (I presume from wxPython) called _windows.py and highlights a particular line in red and displays the error message from above. I have Googled the error message but the results have not helped. LISTING FOR SIMPLE.PY #!/usr/bin/python # simple.py import wx app = wx.App() frame = wx.Frame(None, -1, 'simple.py') frame.Show() app.MainLoop() EXERPT FROM _WINDOWS.PY - PYSCRIPTER HIGHLIGHTS SECOND LAST LINE class Frame(TopLevelWindow): """Proxy of C++ Frame class""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') __repr__ = _swig_repr def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, String title=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) -> Frame """ # The following line is highlighted as where the error occures _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) self._setOORInfo(self) RUNNING THE SIMPLE.PY SCRIPT FROM WITHIN IDLE PRODUCES THE FOLLOWING ERROE MESSAGE: Traceback (most recent call last): File "C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython Tutorial\absolute.py", line 28, in Absolute(None, -1, '') File "C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython Tutorial\absolute.py", line 9, in __init__ wx.Frame.__init__(self, parent, id, title, size=(250, 180)) File "C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py", line 505, in __init__ _windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs)) PyNoAppError: The wx.App object must be created first! -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From zhushenli at gmail.com Tue Sep 2 23:20:17 2008 From: zhushenli at gmail.com (Davy) Date: Tue, 2 Sep 2008 20:20:17 -0700 (PDT) Subject: Pass same parameter in Recursive function Message-ID: Hi all, Sometimes I need to pass same parameter in recursive function. From my point of view, the style is redundant, and I don't what to use some global style like self.A, self.B, Is there any other choice? For example, def func(self, x, y, A, B, C): #x, y change in recursive call #A, B, C change in the first layer function call, but did not change in recursive call if (...): func(x, y, A, B, C) else(...): func(x, y, A, B, C) Best regards, Davy From inhahe at gmail.com Sun Sep 14 10:53:59 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 14 Sep 2008 10:53:59 -0400 Subject: how to exclude specific things when pickling? Message-ID: If I gather correctly pickling an object will pickle its entire hierarchy, but what if there are certain types of objects anywhere within the hierarchy that I don't want included in the serialization? What do I do to exclude them? Thanks. From kurdayon at yahoo.com Sun Sep 28 18:39:22 2008 From: kurdayon at yahoo.com (Kurda Yon) Date: Sun, 28 Sep 2008 15:39:22 -0700 (PDT) Subject: Web programming in Python. Message-ID: Hi, I am totaly newbie in the Python's web programming. So, I dont even know the basic conceptions (but I have ideas about php-web- programming). Does it work in a similar way? First, I have to install a Python-server? On the server where I have my web site (it runs under Linux) if I type "python" I get the Python command line. Does it mean that I already have everything what I need to start web programming in Python. Should I give *.py extension to the Python programs? I tried the simplest what could I imagine. And it does not work. I have created a file "test.py" which contains print "Hello, World!" If I type "python test.py" it works! But, if I put in the address line of my browser "www.mydomainname.org/test.py" it does not work. Or, to be more precisely, in my browser I see the content of the "test.py" (not the result of the execution). Could you pleas help me to start? Thank you ! From steve at holdenweb.com Mon Sep 29 09:39:19 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 09:39:19 -0400 Subject: Web programming in Python. In-Reply-To: References: Message-ID: Kurda Yon wrote: > 1. On my server (in my directory) I found "cgi-bin" subdirectory. > > 2. In the "cgi-bin" I have created a file "test.py". > > 3. In that file I put: > #!/usr/bin/python2.4 python OK, if /usr/bin/python2.4 really *is* a directory then you will need to make that first line #!/usr/bin/python2.4/python (The phrase folowing the "#!" should be a reference to your Python interpreter). > print "Hello, World!" Also, this isn't going to be adequate as an HTTP response, which a CGI script is always supposed to provide. A minimal example would have a single header followed by a blank like (which marks the end of the headers) and your content, like this: print """Content-Type: text/plain Hello, World! """ > (I have checked, I have "/usr/bin/python2.4" directory.) > > 4. I give the following permissions to the "test.py": > -rwx---r-x > > 5. The "cgi-bin" directory has the following permissions: > drwx---r-x > > 6. In the "cgi-bin" I have created the ".htaccess" file which > contains: > Options +ExecCGI > AddHandler cgi-script .py > > > And it still does not work! If I try to see the page by my browser I > see: > Internal Server Error > The server encountered an internal error or misconfiguration and was > unable to complete your request. > ... > -- > http://mail.python.org/mailman/listinfo/python-list > If that doesn't get your script working then you should look at the error logs. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From jason.scheirer at gmail.com Thu Sep 4 11:57:13 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 4 Sep 2008 08:57:13 -0700 (PDT) Subject: path slashes cleaning References: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> Message-ID: On Sep 4, 6:32?am, "Francesco Guerrieri" wrote: > On Thu, Sep 4, 2008 at 3:25 PM, Mathieu Prevot wrote: > > Hi, > > > for scripts that take arguments, I would like to remove the trailing > > slash if it's present. > > > Is there something else than: > > > a='/usr/local/lib/' > > if a[-1] == '/': > > ?a = list(a) > > ?a.pop() > > ?''.join(a) > > > Thanks, > > Mathieu > > a.rstrip('/') does the job. > > bye, > Francesco [1]: import os.path [2]: os.path.normpath('/usr/bin') '/usr/bin' [3]: os.path.normpath('/usr/bin/') '/usr/bin' And on windows: [1]: import os.path [2]: os.path.normpath(r'c:\data') 'c:\\data' [3]: os.path.normpath('c:\\data\\') 'c:\\data' Use the functions provided in os.path. From fredrik at pythonware.com Thu Sep 11 04:34:07 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 10:34:07 +0200 Subject: dynamic allocation file buffer In-Reply-To: References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I'm no longer *claiming* anything, I'm *asking* whether random access to > a 4GB XML file is something that is credible or useful. It is my > understanding that XML is particularly ill-suited to random access once > the amount of data is too large to fit in RAM. An XML file doesn't contain any indexing information, so random access to a large XML file is very inefficient. You can build (or precompute) index information and store in a separate file, of course, but that's hardly something that's useful in the general case. And as I said before, the only use case for *huge* XML files I've ever seen used in practice is to store large streams of record-style data; data that's intended to be consumed by sequential processes (and you can do a lot with sequential processing these days; for those interested in this, digging up a few review papers on "data stream processing" might be a good way to waste some time). Document-style XML usually fits into memory on modern machines; structures larger than that are usually split into different parts (e.g. using XInclude) and stored in a container file. Random *modifications* to an arbitrary XML file cannot be done, as long as you store the file in a standard file system. And if you invent your own format, it's no longer an XML file. From fredrik at pythonware.com Sat Sep 6 12:51:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Sep 2008 18:51:38 +0200 Subject: Calling global functions from a class? In-Reply-To: <496954360809060933w2b736b57x7925510140e7a3e@mail.gmail.com> References: <496954360809060933w2b736b57x7925510140e7a3e@mail.gmail.com> Message-ID: Robert Dailey wrote: > I have the following python script: > > def __normalizePath( path ): > return osp.abspath( osp.normpath( path ) ) > > class AbsolutePath: > def __init__( self, root="" ): > _root = __normalizePath( root ) > > > When I create an AbsolutePath object, I get the following error: > > NameError: global name '_AbsolutePath__normalizePath' is not defined > > Is there a reason for this? the "__" prefix (double underscores) is reserved for private attributes and methods in a class. it does not work for module-level names. > How can I make this work? rename the global function. From castironpi at gmail.com Sun Sep 28 15:27:12 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 12:27:12 -0700 (PDT) Subject: Music knowledge representation References: Message-ID: <4ea817db-7d6f-432b-949b-8b03e3e61da6@8g2000hse.googlegroups.com> On Sep 28, 2:08?pm, Mr.SpOOn wrote: > On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady > > wrote: > > Here is a link to someone else's design they asked about on the > > newsgroup a couple weeks ago. > > >http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > :D > It's always me. > > I think my question is more specific. I need some sort of cycle. > > So if I have a list with A, B, C, D, when I iter over it I need to get > an A after the D. This one was an easy guess: cycle( iterable) Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely. From ken at seehart.com Tue Sep 30 07:51:36 2008 From: ken at seehart.com (Ken Seehart) Date: Tue, 30 Sep 2008 04:51:36 -0700 Subject: Advice for a replacement for plone. Message-ID: <48E212C8.6070209@seehart.com> I want a new python based CMS. ... One that won't keep me up all night .... I've been fooling around with zope and plone, and I like plone for some things, such as a repository for online project documentation. However for general-purpose web development it is too monolithic. Is there anything out there with the following properties? 0. Web page being developed is a typical small business home page (i.e. not a newspaper or a blog). 1. Page owner can edit pages on line with no expertise (plone does great here). 2. Main page does not look plone-like. For an example of a main page that does not look plone-like, see http://www.arbitrary.com/ Note the lack of CMS style navigation widgets. 3. Item 2 should be reachable with nearly no effort (plone fails utterly here). 4. Target viewer (not the owner), should /not/ see something that looks at all like a CMS system, but rather see exactly what the page owner wants the page to look like. 5. Page owner should be able to view and navigate the tree of contents, and select pages to edit with a wysiwyg editor (plone does great here)... 6. ... But the target viewer should not see this tree. See items 2 and 4. 7. Potential to add python scripted pages of various kinds. There are a couple different design approaches to making a development environment. You can let the developer start with nothing, and provide the developer with tools to create something (e.g. zope, most plain text editors), or you can start with a finished result and let the developer rip out and discard what is not desired (e.g. plone). I often prefer to start with nothing. It's a natural starting point. Note that systems that are based on starting with nothing can provide the benefits of starting with something by providing templates and such. I would love to see a system that would give me an editable Hello World page in under 5 minutes. Hello World would be a page consisting of nothing but the words "hello world" (no tools, no navigation bar, and certainly no CMS navigation stuff) in a url such as www.myhelloworldwebsite.com/hello and a different url to edit the page, such as www.myhelloworldwebsite.com/hello/edit or www.mywebsite.com/edit/hello If you are a plone fanatic and still think I should use plone, fine, but please let me know where I can find a "Hello World" kind of example that demonstrates items 2, 4, and 6. In addition, I would like the ability to design the layout of the page independent of the content. Plone has some nice features that would be very helpful, but again, getting to hello world seems difficult. Just plain Zope does a pretty good job at some of this, but I haven't found a good online wysiwyg editor for the page owner to modify content. Thanks for any ideas. Ken From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 22 04:11:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 10:11:58 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <48d7534f$0$5096$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? > Err... A possible design smell ?-) More seriously: this looks quite like a singleton, which in Python is usually implemented way more simply using a module and plain functions. Do you have a use case for specializing this class ? From bedouglas at earthlink.net Sat Sep 6 19:27:03 2008 From: bedouglas at earthlink.net (bruce) Date: Sat, 6 Sep 2008 16:27:03 -0700 Subject: Use BeautifulSoup to delete certain tag while keeping its content In-Reply-To: <37b964200809060811j55e81c6bqdce6747c9982b82d@mail.gmail.com> Message-ID: <20f601c91078$13d70b70$0301a8c0@tmesa.com> hi jackie, if you don't mind... can i ask what you're looking to accomplish? are you looking to simply get the text/string data, or something else??? -----Original Message----- From: python-list-bounces+bedouglas=earthlink.net at python.org [mailto:python-list-bounces+bedouglas=earthlink.net at python.org]On Behalf Of Jackie Wang Sent: Saturday, September 06, 2008 8:12 AM To: python-list at python.org Subject: Use BeautifulSoup to delete certain tag while keeping its content Dear all, I have the following html code: Center Bank
Los Angeles, CA
Salisbury Bank and Trust Company
Lakeville, CT
How should I delete the 'font' tags while keeping the content inside? Ideally I want to get: Center Bank
Los Angeles, CA Salisbury Bank and Trust Company
Lakeville, CT Thank you. Jackie -- http://mail.python.org/mailman/listinfo/python-list From castironpi at gmail.com Fri Sep 12 08:39:11 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 12 Sep 2008 05:39:11 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> Message-ID: <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> On Sep 12, 4:34?am, Paul Boddie wrote: > On 12 Sep, 08:30, Steven D'Aprano > > wrote: > > > Which is why I previously said that XML was not well suited for random > > access. > > Maybe not. No, it's not. Element trees are, which if I just would have said originally... > A consideration of other storage formats such as HDF5 might > be appropriate: > > http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > There are, of course, HDF5 tools available for Python. PyTables came up within the past few weeks on the list. "When the file is created, the metadata in the object tree is updated in memory while the actual data is saved to disk. When you close the file the object tree is no longer available. However, when you reopen this file the object tree will be reconstructed in memory from the metadata on disk...." This is different from what I had in mind, but the extremity depends on how slow the 'reconstructed in memory' step is. (From http://www.pytables.org/docs/manual/ch01.html#id2506782 ). The counterexample would be needing random access into multiple data files, which don't all fit in memory at once, but the maturity of the package might outweigh that. Reconstruction will form a bottleneck anyway. > > I think we're starting to be sucked into a vortex of obtuse and opaque > > communication. > > I don't know about that. I'm managing to keep up with the discussion. > > > We agree that XML can store hierarchical data, and that it > > has to be read and written sequentially, and that whatever the merits of > > castironpi's software, his original use-case of random access to a 4GB > > XML file isn't workable. Yes? I could renege that bid and talk about a 4MB file, where recopying is prohibitively expensive and so random access is needed, thereby requiring an alternative to XML. > Again, XML specifically might not be workable for random access in a > serialised form, despite people's best efforts at processing it in > various unconventional ways, but that doesn't mean that random access > to a 4GB file containing hierarchical data isn't possible, so I > suppose it depends on whether he is wedded to the idea of using > vanilla XML or not. No. It is always nice to be able to scroll through your data, but it's much less common to be able to scroll though a data -structure-. (Which is part of the reason data structures are hard to design.) > It's always worth exploring the available > alternatives before embarking on a challenging project, unless one > wants to pursue the exercise as a learning experience, and I therefore > suggest investigating whether HDF5 doesn't already solve at least some > of the problems or use-cases stated in this discussion. The potential for concurrency is definitely one benefit of raw alloc/ free management, and a requirement I was setting out to program directly for. There is a multi-threaded version of HDF5 but interprocess communication is unsupported. "This version serializes the API suitable for use in a multi-threaded application but does not provide any level of concurrency." From: http://www.hdfgroup.uiuc.edu/papers/features/mthdf/ (It is always appreciated to find a statement of what a product does not do.) > Paul There is an updated statement of the problem on the project website: http://code.google.com/p/pymmapstruct/source/browse/trunk/pymmapstruct.txt I don't have numbers for my claim that the abstraction layers in SQL, including string construction and parsing, are ever a bottleneck or limiting factor, despite that it's sort of intuitive. Until I get those, maybe I should leave that allegation out. Compared to the complexity of all these other packages (ZOPE, memcached, HDF5/PyTables), alloc and free are almost looking like they should become methods on a subclass of the builtin buffer type. Ha! (Ducks.) They're beyond dangerous compared to the snuggly feeling of Python though, so maybe they could belong in ctypes. Aaron From mail.anand.anand at gmail.com Tue Sep 30 05:13:38 2008 From: mail.anand.anand at gmail.com (aathi) Date: Tue, 30 Sep 2008 02:13:38 -0700 (PDT) Subject: Welcome to US Computer Jobs Message-ID: <4cb0c7b1-e975-43ee-9c34-0607ed92e4de@m73g2000hsh.googlegroups.com> Welcome to US Computer Jobs Windows System Engineer Phone and Inperson Interview http://geocities.com/anandrisks/ http://friendfinder.com/go/g959922 http://amigos.com/go/g959922 From earlsoliloquyji at googlemail.com Mon Sep 22 07:21:33 2008 From: earlsoliloquyji at googlemail.com (earlsoliloquyji at googlemail.com) Date: Mon, 22 Sep 2008 04:21:33 -0700 (PDT) Subject: comsextv1 - for Free Message-ID: <02ffeb9a-5363-4b1f-bd25-5c30ed4bf8e7@f36g2000hsa.googlegroups.com> comsextv1 . . . *******CLICK HERE******** http://vids365.cn/comsextv1 ***************************** . . . . . . . . . . . . comsextv1 From bborcic at gmail.com Sat Sep 13 06:00:42 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 13 Sep 2008 12:00:42 +0200 Subject: max(), sum(), next() In-Reply-To: <48C8DBFF.20208@wildenhain.de> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <48BEE2F7.5010106@shopzeus.com> <1220499644.48bf58bc376e4@comuh.uh.cu> <48C8DBFF.20208@wildenhain.de> Message-ID: Tino Wildenhain wrote: > Hi, > > Luis Zarrabeitia wrote: >> Quoting Laszlo Nagy : >> > ... >> Even better: >> >> help(sum) shows >> >> === >> sum(...) >> sum(sequence, start=0) -> value >> Returns the sum of a sequence of numbers (NOT strings) plus >> the value >> of parameter 'start'. When the sequence is empty, returns start. >> === >> >> so the fact that sum([]) returns zero is just because the start value >> is zero... >> sum([],object()) would return an object(). >> >> BTW, the original code: >> >>>>> sum(s for s in ["a", "b"] if len(s) > 2) >> >> wouldn't work anyway... it seems that sum doesn't like to sum strings: >> >>>>> sum(['a','b'],'') >> >> : sum() can't sum strings [use >> ''.join(seq) instead] > > Yes which is a bit bad anyway. I don't think hard wiring it is such a > nice idea. You know, walks like a duck, smells like a duck... > If it makes sense to handle things differently for performance, then > please have it doing it silently, e.g. when it detects strings just > use join() internally. > > Cheers > Tino +1 ''.join is horrible. And it adds insult to injury that S.join(S.split(T)) != T as a rule. The interpreter has no business to patronize us into this shamefully contorted neighborhood while it understands what we want. Cheers, BB From george.sakkis at gmail.com Mon Sep 15 10:41:35 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 15 Sep 2008 07:41:35 -0700 (PDT) Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: On Sep 14, 9:07?pm, Grant Edwards wrote: > On 2008-09-15, Adelle Hartley wrote: > > > Grant Edwards wrote: > > >> When packages as significant as wxPython use naming > >> conventions other than PEP 8, I find it hard to make a case > >> that the PEP 8 naming convention is any better than any other. > > > This relates to a question I was thinking about... > > > I'm looking at porting a library that was written for COM and > > .Net to work as a Python module, and was wondering whether it > > would be better to stick to the library's current naming > > convention so that the API is as similar as possible on each > > platform, or to adopt a "when in Rome..." policy and follow > > the "most mainstream" naming pattern for each > > platform/language. > > If all that is would change is naming, then my advice would be > to keep the existing naming. ?That way it matches existing > documentation and examples. ?But, it does violate PEP 8. > > If the API itself is going to be changed significantly so that > it's unique to the Python port (different to the point where > existing documentation and examples are no longer useful), then > using standard PEP 8 naming conventions is probably a good choice. +1. Another factor is whether the original library's API is reasonably stable or it's expected to change significantly in the future. In the former case you may want to provide a more pythonic API, otherwise you'll have to do more work to keep in sync two separate APIs with every new version. George From paul at boddie.org.uk Sat Sep 13 10:37:13 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 13 Sep 2008 07:37:13 -0700 (PDT) Subject: lacking follow-through References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <289bc58f-6c04-4bce-b393-e9fa0a8c4fee@i20g2000prf.googlegroups.com> Message-ID: On 13 Sep, 08:38, Terry Reedy wrote: > > His recent posts have generally been quite different from those of some > months ago. Even he recognizes that they were somewhat weird and has > tried to do better. And I think we should at least go along with people if they're willing to raise their level of discussion. I'd much rather read messages at the level of the one which initiated this thread than idiotic, supposedly humorous responses about contributors being "bots". > Did he ever make any degrading attacks on people like the above, to > deserve receiving such? This reminds me of my elementary school, where > people who made social mistakes were sometimes never allowed to recover > but were dumped on for years. I get this impression as well: that "seniority" gives some kind of right to dump on anyone, and that we should all find this a source of amusement. It seems more like American high school, Hollywood style, if you ask me. Paul From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 09:44:58 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Sep 2008 13:44:58 GMT Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <00e4f84f$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 13:13:08 +0000, Duncan Booth wrote: > This is a good indication that the > author doesn't know much about OOP. I think you can drop the last two words :) Actually that's unfair -- it looks like he knows quite a bit about the metallicity of quasers, but he's just parroting a bunch of Java concepts as if Java was the be-all and end-all of object oriented programming, which is clearly wrong because we all know that Python's object model is the One True OOP. *wink* -- Steven From midfield at gmail.com Fri Sep 5 14:33:18 2008 From: midfield at gmail.com (Ben Lee) Date: Fri, 5 Sep 2008 11:33:18 -0700 (PDT) Subject: sqlite3 import performance Message-ID: hi folks -- a quick python and sqlite3 performance question. i find that inserting a million rows of in-memory data into an in-memory database via a single executemany() is about 30% slower than using the sqlite3 CLI and the .import command (reading the same data from a disk file, even.) i find this surprising, executemany() i assume is using a prepared statement and this is exactly what the .import command does (based on my quick perusal of the source.) is this discrepancy to be expected? where is the overhead coming from? for full disclosure: the python code is at the end; run it first to generate the data file. to test the CLI, i couldn't find a better way than to create an init file "sqlcmds" containing create table test (k int primary key, v int not null); .import data test and then run time sqlite3 -init sqlcmds ':memory:' '.quit' the python code is #!/usr/bin/env python import sqlite3, random, timeit con = None def prepare(): global con, cur con=sqlite3.connect(':memory:') con.isolation_level="EXCLUSIVE" cur=con.cursor() def ins(): global con, data, cur try: cur.execute('drop table test') except: pass cur.execute('create table test (key int primary key, val int not null);') con.commit() cur.executemany("INSERT into test (key, val) values (?, 10)",data) con.commit() hs = {} print 'generating data...' size = 1000000 data = [[a] for a in random.sample(xrange(10000000), size)] print 'done!' # save the data for the sqlite3 CLI f = file('data', 'w') f.writelines([str(a[0])+"|10\n" for a in data]) f.close() print 'testing ' + str(size) + ' inserts...' # test 100K inserts t = timeit.Timer(stmt='ins()', setup="import sqlite3\nfrom __main__ import prepare, ins \nprepare()") print t.repeat(3,1) thanks, ben From brtzsnr at gmail.com Fri Sep 19 09:40:00 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Fri, 19 Sep 2008 06:40:00 -0700 (PDT) Subject: generator exceptions Message-ID: <826a734c-968c-4d68-9ed1-c2688340ebc5@a3g2000prm.googlegroups.com> i have a generator that raises an exception when calling next(), however if I try to catch the exception and print the traceback i get only the line where next() was called while True: try: iterator.next() except StopIteration: break except Exception, e: traceback.print_exc() how do I get the traceback starting from where exception was raised in first place? From mnordhoff at mattnordhoff.com Fri Sep 12 18:15:05 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 12 Sep 2008 22:15:05 +0000 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <00da5aca$0$2879$c3e8da3@news.astraweb.com> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <00da5aca$0$2879$c3e8da3@news.astraweb.com> Message-ID: <48CAE9E9.805@mattnordhoff.com> Steven D'Aprano wrote: > On Thu, 11 Sep 2008 17:27:33 +0200, Sjoerd Mullender wrote: > >> When mail messages bounce, the MTA (Message Transfer Agent--the program >> that handles mail) *should* send the bounce message to whatever is in >> the Sender header, and only if that header does not exist, should it use >> the From header. > > Who makes up these rules, and why should we pay the least bit of > attention to them? > > It's one thing to say "right or wrong, that's what list admins do and you > have to deal with their behaviour whatever way you can". It's another > thing altogether to take the legalistic attitude of "never mind the > consequences, the standard is the standard and must be unthinkingly > obeyed". If the standard does more harm than good, then ignoring the > standard is the right thing to do. (Better would be to change the > standard, but that probably won't happen until there's a critical mass of > people who ignore the existing broken standard and form their own de > facto standard.) > > A standard isn't "correct" just because it's a standard, it's merely > something that a committee has agreed to do. In other words, it's a > compromise. Now, such compromises might be good and useful, or they might > combine the worst of all opinions. Just because something is standardized > doesn't make it the right thing to do. If you want proof of this, I give > you the recently approved ISO standard for Microsoft's so-called "Office > Open XML" OOXML file format. > > The standard behaviour of sending bounce and out-of-office messages to > the sender works well when sending email to individuals, but for mailing > lists it is pointless and counter-productive. Pointless, because the > sender can't do anything to fix the problem he's being notified about. > And counter-productive, because it is an anti-feature, something that > makes the mailing list more unpleasant and less useful. Anyone who has > regularly emailed to a large mailing list has surely experienced the > frustration of receiving bounce messages from perfect strangers. > > To anyone who wishes to defend the process of sending mailing list > bounces back the sender, ask yourself this: what do YOU do with such > bounces when you receive them? If you ignore them or delete them (whether > manually or via a procmail recipe or some other automatic system) then > what benefit does the standard behaviour offer? I think you misunderstand. He's referring to the Sender header, not the >From header. The messages the listbot sends out have a Sender header of "python-list-bounces+user=example.com at python.org" (supposing the subscriber's email address is user at example.com). Bounces should be directed to the bitbucket or list admin or whatever, not the user in the >From header. kring.com just has a broken mail server. -- From digitig at gmail.com Mon Sep 29 13:43:12 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 29 Sep 2008 18:43:12 +0100 Subject: One class per file? In-Reply-To: References: Message-ID: 2008/9/29 Roy Smith : > That being said, the "one class per file" rule is a means to an end. Although in some languages, the "end" is "code that runs". But Python is not Java... -- Tim Rowe From bborcic at gmail.com Sat Sep 13 07:06:43 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 13 Sep 2008 13:06:43 +0200 Subject: ''.join woes - Re: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <48BEE2F7.5010106@shopzeus.com> <1220499644.48bf58bc376e4@comuh.uh.cu> <48C8DBFF.20208@wildenhain.de> Message-ID: I wrote: > Tino Wildenhain wrote: [...] >>>>>> sum(['a','b'],'') >>> >>> : sum() can't sum strings [use >>> ''.join(seq) instead] >> >> Yes which is a bit bad anyway. I don't think hard wiring it is such a >> nice idea. You know, walks like a duck, smells like a duck... >> If it makes sense to handle things differently for performance, then >> please have it doing it silently, e.g. when it detects strings just >> use join() internally. >> >> Cheers >> Tino > > +1 > > ''.join is horrible. And it adds insult to injury that > S.join(S.split(T)) != T as a rule. The interpreter has no business to > patronize us into this shamefully contorted neighborhood while it > understands what we want. What makes ''.join particularly horrible is that we find ourselves forced to use it not only for concatenating arbitrary-length strings in a list, but also to convert to a str what's already a sequence of single characters. IOW string types fail to satisfy a natural expectation for any S of sequence type : S == type(S)(item for item in S) == type(S)(list(S)) And this, even though strings are sequence types deep-down-ly enough that they achieve to act as such in far-fetched corner cases like (lambda *x : x)(*'abc')==('a','b','c') ...and even though strings offer not one but two distinct constructors that play nicely in back-and-forth conversions with types to which they are much less closely related, ie. '1j' == repr(complex('1j') == str(complex('1j')) 1j == complex(repr(1j)) == complex(str(1j)) Not-so-cheerfully-yours, BB From bdesth.quelquechose at free.quelquepart.fr Wed Sep 10 11:35:08 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 Sep 2008 17:35:08 +0200 Subject: Generator functions and user interfaces In-Reply-To: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> References: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> Message-ID: <48c8051b$0$23993$426a74cc@news.free.fr> psaffrey at googlemail.com a ?crit : > I'm trying to implement an interactive graph visualisation tool using > matplotlib. > > I want to use a spring layout, where nodes repulse each other and > edges act as springs to pull connected nodes together. Usually, this > algorithm runs through a number of iterations of attraction/repulsion > to allow the nodes to converge to suitable positions. However, rather > than running all these iterations to lay out the graph and then > rendering it, I want to animate the graph as it is "springing" into > place, and then allow the user to drag nodes around and have the graph > redraw on the fly. > > My idea for doing this was to use a generator function, where I yield > the position of the nodes after each iteration and then call draw() on > the position yielded. Does this seem like a sensible approach? I don't have much experience with this kind of algorithms, but AFAICT, it seems sensible to me, yes. But don't take me on words... > The > problem is that the node positions that are being operated on by the > generator function may be altered by user input - dragging the nodes - > and I'm not sure if this will break the way that the new positions are > yielded. How do I use a generator function that might stop (when the > nodes stop moving) but then need to restart again (once the user moves > the nodes)? Starting with Python 2.5, there's a way to pass values back to generators: http://docs.python.org/whatsnew/pep-342.html Now, not having played much with these new features so far, I'm afraid I can't help more, nor even be strictly positive about this being what you need. Any generator guru around ? From castironpi at gmail.com Sun Sep 7 19:33:41 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 7 Sep 2008 16:33:41 -0700 (PDT) Subject: lacking follow-through References: <00d453eb$0$20306$c3e8da3@news.astraweb.com> Message-ID: On Sep 7, 5:45?pm, Steven D'Aprano wrote: > On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > > Hi, > > > This is the strangest post I've seen > > since I've joined this list (only > > recently). What the ? > > Oh don't mind castironpi, many people think he's an IRC bot with some > experimental AI features that escaped onto Usenet *grins*. If you think > that post of his was strange, you haven't seen anything yet. Many people > have kill-filed him, and never even see his posts. > > A word to castironpi: you just suggested you will pester the list to get > a response. It's behaviour like that which gets you kill-filed. If you > would spend one tenth of the effort that you spend on understand Python > on understanding human psychology, you will probably get on with others > much better and find fewer people claiming you're a bot. > > Even if you yourself don't understand how others behave and expect you to > behave, think of it as an intellectual puzzle: how can I fool the strange > hairless apes into accepting me into their herd? > > -- > Steven First, gauge their persistence tolerance. Some people are not persistent enough. I don't want to annoy you, and I want to show interest, but of course no more than I actually feel. Are my standards too low, or too high? Second, debate the reverse psychology tack. Claim I'm a bot to shake their belief? Or call them bots? Perhaps they are. Bots with cooties. Yes. From mr.spoon21 at gmail.com Sun Sep 21 11:07:31 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 21 Sep 2008 17:07:31 +0200 Subject: Override the '+' symbol Message-ID: <8f67b6f80809210807y1fbc8ddapa29a207b103f1a8f@mail.gmail.com> Hi, how can I override the '+' symbol (and other math symbols) so that it can have a new behavior when applied to some objects? From casuvetha at gmail.com Sat Sep 20 09:36:08 2008 From: casuvetha at gmail.com (killyou) Date: Sat, 20 Sep 2008 06:36:08 -0700 (PDT) Subject: jips works with in online Message-ID: http://candapud.blogspot.com/ From clodoaldo.pinto at gmail.com Sun Sep 14 10:50:16 2008 From: clodoaldo.pinto at gmail.com (Clodoaldo) Date: Sun, 14 Sep 2008 07:50:16 -0700 (PDT) Subject: cjson 1.0.5 keyword argument References: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> Message-ID: <31008070-11e0-44ad-9b27-9985323afb9a@s1g2000pra.googlegroups.com> On Sep 14, 11:45 am, "Guilherme Polo" wrote: > On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo wrote: > > I have installed cjson 1.05 in Fedora 8 (python 2.5.1). > > > The cjson home page shows a keyword argument "encoding". > >http://python.cx.hu/python-cjson/ > > The latest python-cjson on that page is 1.0.3, which accepts keywords > for the encode function. python-cjson 1.0.5 no longer accepts. > > > When i use it i get an error: > > >>>> cjson.encode('?', encoding='utf8') > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: encode() takes no keyword arguments > > > What am i missing? There is no mail list for cjson. > > Try doing cjson.encode('?'.decode('utf-8')) instead. I had tried decoding first and it worked but my database is utf-8 so i don't want that extra step. BTW i have already found the problem as the other post shows. Thanks, Clodoaldo From sturlamolden at yahoo.no Thu Sep 25 08:03:57 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 05:03:57 -0700 (PDT) Subject: multiple processes with private working dirs References: Message-ID: <2b282ed0-a004-4692-8521-ecc5d21d8a60@j22g2000hsf.googlegroups.com> On 24 Sep, 19:37, "Tim Arnold" wrote: > Am I missing something? Is there a better way? Use the pyprocessing module (to appear as standard module multiprocessing in Python 2.6). It has almost the same interface as Python's threading and Queue standard modules, except you are working with processes not threads. To wait for a process to finish, just join it like you would do with a thread. http://pyprocessing.berlios.de/ From maric at aristote.info Fri Sep 5 07:31:40 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 13:31:40 +0200 Subject: Case-insensitive string compare? In-Reply-To: References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809050059.17038.maric@aristote.info> Message-ID: <200809051331.40609.maric@aristote.info> Le Friday 05 September 2008 08:24:29 Fredrik Lundh, vous avez ?crit?: > Maric Michaud wrote: > > "premature optimization is the root of all evil" > > So is use by that statement by people who don't have the slightest idea > about what it actually means. > > The full version is > > "We should forget about small efficiencies, say about 97% of the time: > premature optimization is the root of all evil." > > Note the use of "small efficiencies". That is, in Python, things like > local binding, inlining, slots, lazy generation of short sequences, etc. > That is, things that takes time to write and reduces maintainability. > > It's not about having an excuse for writing crappy code with large > inefficienies. > > And it's definitely not about programmers intentionally picking a dumb > solution so they can optimize it later. > Yes, I'm aware of that, thanks, but Chris Rebert was proposing to alter the data structure in order to achieve this simple comparison, I don't think it fails into your concern. > > If the OP's proposal seems already messy, how about ths one : > > if lib.lower() not in ( e[0] for e in stage_map.items() ) : > > ... > Sorry, should be read : if lib.lower() not in ( e[0] for e in stage_map.values() ) : and it was the expression for comparison Chris's solution lead to, not a proposal. > Given that your solution is just a remarkably inefficient way to write > "lib.lower() not in stage_map", and thus doesn't solve the OP:s problem, > I suspect you're taking the "evil" part of Hoare's dictum a few bits too > literally. > I suspect you are coming to conclusions a bit quickly, without taking the pain of understanding the whole discussion. > > > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From bignose+hates-spam at benfinney.id.au Sun Sep 14 21:01:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 15 Sep 2008 11:01:23 +1000 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> Message-ID: <87wshe5ijg.fsf@benfinney.id.au> Grant Edwards writes: > On 2008-09-14, Ben Finney wrote: > > Second: please do yourself a favour and drop the camelCaseNames. > > Follow PEP 8 for style > > and naming in your Python code. > > If he finds camelcase more readable and easier to type (as do > I), how is switching to underscores "doing himself a favor"? > > I'm generally in favor of using a consistent naming style > throughout a project, but I don't see why the naming style used > in my source code should be subject to somebody else's > arbitrary standard. Because the code we write rarely stays isolated from other code. There is an existing convention, and it's better to pick a (sufficiently sane) style convention and stick to it than argue about what the convention should be. > When it comes to writing code intended for the standard library > in the main Python distribution, I would certainly defer to the > existing standard as defined in PEP 8. However, I don't see > any reason that style should be imposed on all everybody else. Who's imposing? I'm saying it's a good idea for everyone to do it, and going so far as to say that one is doing oneself a favour by following the convention. I have no more power than you to "impose" convention on anyone. -- \ ??Did you sleep well?? ?No, I made a couple of mistakes.?? | `\ ?Steven Wright | _o__) | Ben Finney From http Thu Sep 4 16:09:51 2008 From: http (Paul Rubin) Date: 04 Sep 2008 13:09:51 -0700 Subject: Can anyone suggest a good crypto package? References: Message-ID: <7xwshr4qr4.fsf@ruckus.brouhaha.com> Fett writes: > Is there any crypto package that is actually written in python? I > seriously don't care how slow it is. I wrote a simple symmetric encryption function in python: http://nightsong.com/phr/crypto/p3.py I wrote a somewhat fancier package that did public key a while back, that is unreleased because of insufficient testing and some features I'd like to have done differently, but I ought to get around to cleaning it up sometime. There is also tlslite, which you might be able to extract some public key functions from: http://trevp.net/tlslite From michele.simionato at gmail.com Wed Sep 10 08:10:09 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 10 Sep 2008 05:10:09 -0700 (PDT) Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: <9f3d127f-4434-4a27-b5d4-b43ebb137186@k30g2000hse.googlegroups.com> On Sep 10, 1:45?pm, Fredrik Lundh wrote: > deni... at t-online.de wrote: > > ? ?how can I list all modules that might be importable on my system, > > ? ?without actually importing them all ? > > I'm pretty sure I mentioned a way to do that back when this thread was > opened. ?let's see, yes, here it is: > > ... > > there's a helper script in the 2.5 source code kit that locates all > existing standard modules: > > http://svn.python.org/projects/python/tags/r252/Doc/tools/listmodules.py > > to get all modules, remove the for-loop that follows after the comment > "get rid of site packages". I have just tried the following on my Ubuntu box with the system Python: ~$ python /usr/lib/python2.5/doc/tools/listmodules.py /usr/lib/python2.5/doc/tools/listmodules.py:99: DeprecationWarning: the rgbimg module is deprecated __import__(m) ** (process:24863): WARNING **: AT_SPI_REGISTRY was not started at session startup. ** (process:24863): WARNING **: Could not locate registry location: /usr/lib/xulrunner-1.9.0.1/libxpcom.so before 3 /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: cannot register existing type `GtkSourceStyleScheme' __import__(m) /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: g_type_set_qdata: assertion `node != NULL' failed __import__(m) /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: cannot register existing type `GtkSourceBuffer' __import__(m) /usr/lib/python2.5/doc/tools/listmodules.py:99: Warning: g_type_get_qdata: assertion `node != NULL' failed __import__(m) Segmentation fault Interesting, isn't it? Michele Simionato From bdesth.quelquechose at free.quelquepart.fr Tue Sep 2 16:45:25 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 02 Sep 2008 22:45:25 +0200 Subject: synthetic properties In-Reply-To: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> References: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> Message-ID: <48bda606$0$32752$426a74cc@news.free.fr> rowland at river2sea.org a ?crit : > I'm trying to come up with solution for adding synthetic properties to > python, similar to synthetic properties in Objective-C. Please explain what Objective-C "synthetic properties" are - not everyone here has a strong Objective-C background... > I'm playing around with doing this in a MetaClass. I can dynamically > create the attributes that will back the property, but I'm having > trouble figuring out how to dynamically generate get/set methods to > pass to the built-in property() function. FWIW, the property type is just one possible application of the descriptor protocol. You can easily define your own custom descriptor classes - and you can even do this dynamically. > Is it possible to define a lambda or a callable object that will act > as a getter method (or setter, that takes a value argument) during > MetaClass.__init__? Yes. > The hard part I'm guessing is getting the current > instance passed into the getter. Not really. > This is my first foray into > MetaClasses and dynamic functions/methods so any pointers are greatly > appreciated. > > > class ObjectivePythonObject( type ) : > > def __new__( cls, name, bases, dct ) : > #print "Allocating memory for class", name > return type.__new__(cls, name, bases, dct ) This is what type.__new__ do, so you just don't need it. > def __init__( cls, name, bases, dct ) : > #print "Initializing class", name > for propertyInfo in cls.synthesized : > property = propertyInfo[ 0 ] > defaultValue = propertyInfo[ 1 ] > print property > setattr( cls, '_' + property, defaultValue ) > # Create property with get/set methods... > > class Person( object ) : > > __metaclass__ = ObjectivePythonObject > > > synthesized = [ ( 'name', 'BobC' ), > ( 'age', '48' ) ] > > def __init__( self ) : > print self._name > print self._age > May I suggest you read about Python's coding conventions ? Your code formatting is utterly unpythonic... Ok, here's a working (and slightly more pythonic - at least wrt/ coding style) version of your code: def _make_prop(attrname, default): def fget(self): return getattr(self, attrname, default) def fset(self, value): setattr(self, attrname, value) return property(fget=fget, fset=fset) class ObjectivePythonType(type) : def __init__(cls, name, bases, dct): # we don't want to redefine properties already # defined in a base class synthesized = dct.get('synthesized', ()) for propname, default in synthesized: attrname = "_%s" % propname setattr(cls, propname, _make_prop(attrname, default)) class ObjectivePythonObject(object): __metaclass__ = ObjectivePythonType class Person(ObjectivePythonObject): synthesized = [ ('name', 'BobC'), ('age', '48'), ] def __init__(self) : print self.name print self.age Now... While all this is certainly usefull as a learning exercice on metaclasses etc, it's also an awfully overcomplexificated way to do something quite simple. Here's some code that do exactly the same thing: class PythonPerson(object): name = "BobC" age = "48" def __init__(self): print self.name print self.age HTH From deets at nospam.web.de Tue Sep 2 12:49:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Sep 2008 18:49:16 +0200 Subject: source for the property function In-Reply-To: References: Message-ID: <6i594dFopddmU1@mid.uni-berlin.de> Rowland Smith schrieb: > Anyone know where the source code for the built-in property function is > located in a python distribution? > > I would like to see how it works - mainly, how does it know which class > it is being called from? Google the "descriptor protocol" for new-style classes. That explains it. Diez From luigi at lambrate.inaf.it Wed Sep 3 09:54:20 2008 From: luigi at lambrate.inaf.it (Luigi Paioro) Date: Wed, 03 Sep 2008 15:54:20 +0200 Subject: Custom handler for logging In-Reply-To: References: Message-ID: <48BE970C.1070405@lambrate.inaf.it> Thanks, it works perfectly! Luigi Peter Otten ha scritto: > Luigi Paioro wrote: > >> concerning the logging module, I have written a new Handler which stores >> the logging messages in an SQLite database. It works well, but when I >> try to use it exploiting a configuration file I have a problem since the >> "class" entry does not accept a class which is not within the logging >> name-space, while the class I implemented is coded in my personal module >> (thus another name-space). >> >> Is there a workaround to allow the usage of custom handlers? > > Maybe > > http://mail.python.org/pipermail/python-list/2003-October/232762.html > > Peter From mail at timgolden.me.uk Thu Sep 18 08:14:48 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 18 Sep 2008 13:14:48 +0100 Subject: XML Processing In-Reply-To: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> References: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> Message-ID: <48D24638.9010601@timgolden.me.uk> Robert Rawlins wrote: > I?m running python 2.5 and currently using ElementTree to perform my XML > parsing and creation. ElementTree really is a great package for doing > this, however, I?ve been tasked by our deployment guys to try and move > away from external libraries where possible as it makes their job easier. Some is going to kick themselves when they realise that ElementTree *is* built in to Python 2.5 http://docs.python.org/whatsnew/modules.html#SECTION0001420000000000000000 TJG From coolman.guron at gmail.com Tue Sep 16 12:30:20 2008 From: coolman.guron at gmail.com (binaryjesus) Date: Tue, 16 Sep 2008 09:30:20 -0700 (PDT) Subject: Porting a pygtk app to Windows Message-ID: <7ce94e05-d704-4118-9496-26f9d7aa6853@k36g2000pri.googlegroups.com> hi everyone, first of all I had written an app using pygtk module and created the GUI with glade.All the development was done on a linux machine and the app was working fine all this tme in linux. now, the thing is i have to change the development environment to windows. So this means that i have to port the application to work in windows. Initially i thought that porting an application written using a platform independent language and cross-platform window frame work would be a piece of cake. Well i guess all the assumptions end there. unlike linux, in windows pygtk and the GTK frame work are not installed by default. So, long story short. i installed GTK devel, pygtk, pygobject, pycaro, glade ui. Also made a lot of path adjustments (os.path.absolutepath() is not portable i guess) and finally got the app to at least start without showing an error. The problem that i am now facing is that nothing shows up in the app. No menu, buttons, frames or anything else is visible. When i move the cursor over the window it changes into an hour-glass type icon. hoe ever all c++ GTK programs seem to render well. here is a screen shot: http://i36.tinypic.com/x52uk9.jpg i have written below the startup code of the app: import pygtk pygtk.require('2.0') import gtk import gtk.glade from ConfigParser import ConfigParser class jDesk(object): def __init__(self): #self.seclstore.append(["0","Section1"]) #self.catlstore.append(["cat 1"]) self.synclstore = gtk.ListStore(str,str,str,str,str,int) self.seclstore = gtk.ListStore(str,str) self.catlstore = gtk.ListStore(str,str) self.process_glade() def process_glade(self): self.gladefile = "gui.glade" self.glade = gtk.glade.XML(self.gladefile) #windows self.main_window = self.glade.get_widget('MainWindow') #main window self.templatefile = self.glade.get_widget('templatefile') self.imageurl = self.glade.get_widget('imageurl') self.posttitle = self.glade.get_widget('posttitle') self.sectionbox = self.glade.get_widget('sectionbox') self.categorybox = self.glade.get_widget('categorybox') self.demolink = self.glade.get_widget('demolink') self.posttext = self.glade.get_widget('posttext') self.statusbar = self.glade.get_widget('statusbar') self.signal_autoconnect() self.main_window.show() print '===================main wind created=================' def run(self): try: print "Entering GTK main now" gtk.main() print "Leaving GTK main" except: print "Exception in main" if __name__ == "__main__": conf = ConfigParser() conf.read('settings.cfg') gtk.gdk.threads_init() app = jDesk() app.run() i have tried a lot of things, checked up paths, checked libcairo but nothing seems to help.problem seems to be with pygtk since other c++ GTK programs like pedgin and GTK demo rn fine. So maybe is there any pygtk windows bugs that i coming from linux background might not be knowing about or perhaps u have encountered such a problem in the past before ? Much thanks in advance BinaryJ From alan.isaac at gmail.com Sun Sep 7 15:24:33 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sun, 07 Sep 2008 19:24:33 GMT Subject: formatting a string with thousands separators In-Reply-To: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> References: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> Message-ID: On 9/7/2008 12:22 PM SimonPalmer apparently wrote: > anyone recommend a way of formatting floats with comma separators? http://code.activestate.com/recipes/498181/ Alan Isaac From marco.bizzarri at gmail.com Sat Sep 13 04:03:02 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 13 Sep 2008 10:03:02 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <48ca9333$0$851$426a74cc@news.free.fr> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> <48ca9333$0$851$426a74cc@news.free.fr> Message-ID: <3f0d61c40809130103m78f5c0cfnade1446b36bf1600@mail.gmail.com> On Fri, Sep 12, 2008 at 6:07 PM, Bruno Desthuilliers wrote: > Marco Bizzarri a ?crit : > (snip) >> >> I'm afraid this have another problem for me... >> >> >> emmebi at janitor:/var/local/zope28/porting/Products/PAFlow$ python2.3 >> Python 2.3.5 (#2, Oct 18 2006, 23:04:45) >> [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> >>>>> def any(iterable): pass >> >> ... >>>>> >>>>> any(x for x in [1, 2, 3]) >> >> File "", line 1 >> any(x for x in [1, 2, 3]) >> ^ >> SyntaxError: invalid syntax >> >>>>> any([x for x in [1, 2, 3]]) >>>>> >> >> I mean, I'm afraid I can't use an expression like that without >> building a list... not at least in python2.3 > > Err... a list being an iterable, you just need any([1, 2, 3]). Ehm, yes, of course... I was trying just to show from a command line what were my results. > > But this wont be enough to solve your real use case, indeed. Yes, that's the point. -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From pmaupin at gmail.com Sun Sep 7 20:55:02 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 7 Sep 2008 17:55:02 -0700 (PDT) Subject: Read and write binary data References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: On Sep 7, 5:41?pm, Mars creature wrote: > Hi guys, > ? I am new to Python, and thinking about migrating to it from matlab > as it is a really cool language. Right now, I am trying to figure out > how to control read and write binary data, like > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > I googled, but can not find a clear answer. Anyone has clue where can > I learn it? Thanks!! > Jinbo Start by looking at the array module. Regards, Pat From rocksportrocker at googlemail.com Thu Sep 11 07:15:09 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Thu, 11 Sep 2008 04:15:09 -0700 (PDT) Subject: I want to use a C++ library from Python References: Message-ID: <08aa1042-f1aa-40ac-a099-11c30e2a2b4e@i76g2000hsf.googlegroups.com> On 10 Sep., 09:57, Anders Eriksson wrote: > Hello, > > I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1 > .lib and 1 .dll files. I don't have the source code. > > How can I create a Python module from these files? Do you need the full library including classes or just some functions ? You could write a wrapper in C around the lib and use f2py or ctypes to call your wrapper from python. But that does not work if you want to expose classes. Greetings, Uwe From kushaldas at gmail.com Fri Sep 5 09:16:36 2008 From: kushaldas at gmail.com (Kushal Das) Date: Fri, 5 Sep 2008 18:46:36 +0530 Subject: =?UTF-8?Q?=E2=80=98A_Byte_of_Python=E2=80=99_updated_for_Python_3.0?= Message-ID: Hi all, Swaroop just released the latest version of his book "A Byte of Python", the new version is for Python 3.0. Read the post at http://www.swaroopch.com/blog/book-updated-for-python-3000/ The book can be found at http://www.swaroopch.com/notes/Python Kushal -- http://fedoraproject.org http://kushaldas.in http://badvista.org http://noooxml.org From jbar at hosting4u.cz Thu Sep 18 11:04:41 2008 From: jbar at hosting4u.cz (Jiri Barton) Date: Thu, 18 Sep 2008 17:04:41 +0200 Subject: unicode in multi-line strings Message-ID: <48D26E09.6000200@hosting4u.cz> Hello, I have a problem with international characters in multi-line strings. Works: '''?''' Works: ''' a''' Does not work: ''' ?''' By does not work I mean the infamous 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not in range(128) I'm using Ubuntu 8.04 with Python 2.5. It does not work in terminal, from scripts, or from scripts with the encoding specified at the top. Making the string unicode (u''' ... ''') does not change anything. It could be an interpreter issue but I didn't know where else I should turn for help. Thank you! Jiri From castironpi at gmail.com Sun Sep 14 15:49:51 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 14 Sep 2008 12:49:51 -0700 (PDT) Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <64670149-9467-4ca7-9d7e-c330c1b403e4@c58g2000hsc.googlegroups.com> Message-ID: <29a3ef5f-49ea-41c7-84bf-f4101ac6397b@e53g2000hsa.googlegroups.com> On Sep 14, 2:38?pm, Roy Smith wrote: > In article > <64670149-9467-4ca7-9d7e-c330c1b40... at c58g2000hsc.googlegroups.com>, > ?"Aaron \"Castironpi\" Brady" wrote: > > > However, from what I understand (brass player), > > If you play the trombone, you might want your Note class to allow > floating-point values for pitch :-) I do! Then there are the known cases of flute players rolling the mouthpiece to change pitch, trumpet players bending, violin. The 3rd of a scale is slightly sharp in Bach's temper. Semi-tones come up in Theory class too. note= Note( "C" ) third= MajorInterval( 3 ) print note+ third : From mnations at gmail.com Thu Sep 4 19:36:11 2008 From: mnations at gmail.com (Mudcat) Date: Thu, 4 Sep 2008 16:36:11 -0700 (PDT) Subject: Python test case management system? Message-ID: I had originally planned on writing my own software for managing test cases; however new boss = new directive. This will make it more difficult to get the functionality I need for test cases that are automated and executed using python. I've searched for alternatives but so far haven't come up with any good options. Does anyone know of a good test case management system written in python, or possibly another application (either open source or commercial) that can be extended using python? Thanks From m_palmer45 at yahoo.ca Mon Sep 15 19:36:05 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 15 Sep 2008 16:36:05 -0700 (PDT) Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> Message-ID: <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> On Sep 15, 3:04 pm, Matias Surdi wrote: > aditya shukla escribi?: > > > How can we convert .py files to batch files? is there any library for this? > > > Aditya > > > ------------------------------------------------------------------------ > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Maybe py2exe can help you. I assume you are on Windows? Let's assume you have a file stuff.py that reads: import os print os.listdir('.') # list current directory, good enough for testing... Then, insert the following line at the top: @setlocal enableextensions & python -x %~f0 %* & goto :EOF Now save this file as stuff.cmd somewhere along your PATH. Now calling 'stuff' should execute your file. On Linux, you would instead insert the shebang line that points to your python interpreter, such as #!/usr/bin/python at the top and also set the executable bit, but I suppose if you use Linux at all you know that. From tjreedy at udel.edu Sat Sep 6 19:00:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Sep 2008 19:00:05 -0400 Subject: Multicore-programming? In-Reply-To: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> References: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> Message-ID: cnb wrote: > If I buy a multicore computer and I have really intensive program. How > would that be distributed across the cores? > > Will algorithms always have to be programmed and told specifically to > run on several cores so if not told it will only utilize one core? I believe that has always been true. > > So is the free lunch really over or is this just an overhyped > phenomena? > > Is threading with Python hard? Opinions vary, mostly depending on experience. But Python threads do not distribute across processors. >Can you start several processes with > Python or just threads? import subprocess and read the manual for that module From musiccomposition at gmail.com Mon Sep 15 22:38:33 2008 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 15 Sep 2008 19:38:33 -0700 (PDT) Subject: Client server implementation References: Message-ID: <7d623ffb-2936-4aec-a74a-e9f5489e6657@p25g2000hsf.googlegroups.com> On Sep 15, 5:15?am, Babloo wrote: > Hi everyone, > > ? ? ? ? ? ? ? ? ? i wanted to implement a client- server connection > and transfer a file over the network. i was able to implement a normal > set up where in i was able to send chat messages and small chunks of > data. > I want to implement the file transfer with out using the FTP library > available in python . > > ? ? ? ? ? ? ? ? ? So can anyone suggest a piece of code by which i can > do that. I don't know what you really want, but look at Twisted. http://twistedmatrix.com > > Thanks > Pruthvi From mail at microcorp.co.za Sat Sep 6 17:20:15 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 6 Sep 2008 23:20:15 +0200 Subject: max(), sum(), next() Message-ID: <005801c91086$1fbfdee0$0d00a8c0@hendrik> "David C. Ullrich" wrote: >Think about all the previously elected female or black >presidents of the US. Which one was the tallest? The current King of France? - Hendrik From deets at nospam.web.de Wed Sep 3 12:57:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 18:57:38 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <6i7u02Fpeif6U1@mid.uni-berlin.de> Michael Palmer schrieb: > As anyone knows, the state of Python GUI programming is a little > fractured at this time, with many toolkits, wrappers and meta-wrappers > dead and alive, with or without documentation. > > I've come across two projects that have the appeal of striving for > simple, pythonic APIs: PyGUI and wax. The latter is a wrapper around > wxPython. It is lacking documentation but actually quite usable and > concise. The other, PyGUI, has an even nicer API and more docs but has > relatively few widgets implemented at this time. It also strives for > compatibility with several toolkits (two at this time), which I think > is the right idea. I disagree with that. Meta-wrappers like this will always suffer from problems, as they have difficulties providing a consistent api. For example wx is said to be very windows-toolkit-centric in it's API. Yes I know that it works under Linux with GTK, but it does not come as natural . > So far, development of PyGUI seems to be a one-man effort, and it may > be slowed down by the attempt to develop the API and the > implementations concurrently. Could it be useful to uncouple the two, > such that the API would be specified ahead of the implementation? This > might make it easier for people to contribute implementation code and > maybe port the API to additional toolkits. It seems that this approach > has been quite successful in case of the Python database API. That API > defines levels of compliance, which might be a way of accommodating > different GUI toolkits as well. > > I may be underestimating the difficulties of my proposed approach - I > don't have much practical experience with GUI programming myself. I think you do. The reason for the various toolkits is not because of python - it's the proliferation of toolkits that exist out there. As long as none of these is "the winner" (and it doesn't look is if that's to happen soon), I doubt that one API to rule them all will exist - they all have their different strengths and weaknesses, and a python-API should reflect these. Diez From showellshowell at gmail.com Wed Sep 24 22:08:04 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Wed, 24 Sep 2008 19:08:04 -0700 (PDT) Subject: is decorator the right thing to use? References: Message-ID: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> On Sep 24, 3:21?pm, "Dmitry S. Makovey" wrote: > Hi, > > after hearing a lot about decorators and never actually using one I have > decided to give it a try. My particular usecase is that I have class that > acts as a proxy to other classes (i.e. passes messages along to those > classes) however hand-coding this type of class is rather tedious, so I > decided to use decorator for that. Can somebody tell me if what I'm doing > is a potential shot-in-the-foot or am I on the right track? (Note, It's > rather rudimentary proof-of-concept implementation and not the final > solution I'm about to employ so there are no optimizations or > signature-preserving code there yet, just the idea). > Your code below is very abstract, so it's kind of hard to figure out what problem you're trying to solve, but it seems to me that you're using the B proxy class to decorate the A target class, which means you want one of these options: 1) Put decorators over the methods in A, not B. Isn't it the methods of A that are being decorated here? 2) Eliminate the decorator syntax and make your code more expressive: a = SomeClass() # first call it directly x = a.foo() y = a.bar() # now decorate it debug_proxy = ClassThatDecoratesMethodCallsToObjectWithDebuggingCode(a) debug_proxy.decorate_methods('foo', 'bar') The decorate_methods method would be magical, in terms of overwriting a's innards, while still preserving the same interface for its users. But again, I'm just guessing here, because it's hard to know what problem you're really solving. Cheers, Steve Code quoted below: > Here's the code: > > class A: > ? ? b=None > ? ? def __init__(self,b): > ? ? ? ? self.val='aval' > ? ? ? ? self.b=b > ? ? ? ? b.val='aval' > > ? ? def mymethod(self,a): > ? ? ? ? print "A::mymethod, ",a > > ? ? def mymethod2(self,a): > ? ? ? ? print "A::another method, ",a > > def Aproxy(fn): > ? ? def delegate(*args,**kw): > ? ? ? ? print "%s::%s" % (args[0].__class__.__name__,fn.__name__) > ? ? ? ? args=list(args) > ? ? ? ? b=getattr(args[0],'b') > ? ? ? ? fnew=getattr(b,fn.__name__) > ? ? ? ? # get rid of original object reference > ? ? ? ? del args[0] > ? ? ? ? fnew(*args,**kw) > ? ? setattr(A,fn.__name__,delegate) > ? ? return fn > > class B: > ? ? def __init__(self): > ? ? ? ? self.val='bval' > > ? ? @Aproxy > ? ? def bmethod(self,a): > ? ? ? ? print "B::bmethod" > ? ? ? ? print a, self.val > > ? ? @Aproxy > ? ? def bmethod2(self,a): > ? ? ? ? print "B::bmethod2" > ? ? ? ? print a, self.val > > b=B() > b.bmethod('foo') > a=A(b) > b=B() > b.val='newval' > a.bmethod('bar') > a.bmethod2('zam') From gminick at bzt.bzt Tue Sep 2 09:33:08 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Tue, 2 Sep 2008 13:33:08 +0000 (UTC) Subject: Algorithm used by difflib.get_close_match References: <83c600d0-6852-4dd6-9287-34f9b3264090@s50g2000hsb.googlegroups.com> Message-ID: On Tue, 2 Sep 2008 06:17:37 -0700 (PDT), Guillermo wrote: > Does anyone know whether this function uses edit distance? If not, > which algorithm is it using? The following passage comes from difflib.py: SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable. The basic algorithm predates, and is a little fancier than, an algorithm published in the late 1980's by Ratcliff and Obershelp under the hyperbolic name "gestalt pattern matching". The basic idea is to find the longest contiguous matching subsequence that contains no "junk" elements (R-O doesn't address junk). The same idea is then applied recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not yield minimal edit sequences, but does tend to yield matches that "look right" to people. HTH. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From mathieu.prevot at gmail.com Thu Sep 4 09:25:24 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 15:25:24 +0200 Subject: path slashes cleaning Message-ID: <3e473cc60809040625y721b7d0asdcd8735cf34588eb@mail.gmail.com> Hi, for scripts that take arguments, I would like to remove the trailing slash if it's present. Is there something else than: a='/usr/local/lib/' if a[-1] == '/': a = list(a) a.pop() ''.join(a) Thanks, Mathieu From rNOSPAMon at flownet.com Thu Sep 18 21:21:21 2008 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 Sep 2008 18:21:21 -0700 Subject: CTypes on a 64 bit machine truncates pointers to 32 bits? Message-ID: CTypes on a 64-bit machine appears to be truncating pointers to 32 bits: [ron at monster1:~]$ uname -a Linux monster1 2.6.18-6-amd64 #1 SMP Mon Jun 16 22:30:01 UTC 2008 x86_64 GNU/Linux [ron at monster1:~]$ cat foo.c void* foo(void* x) { return x; } [ron at monster1:~]$ gcc -fPIC -shared foo.c -o foo.so [ron at monster1:~]$ file foo.so foo.so: ELF 64-bit LSB shared object, AMD x86-64, version 1 (SYSV), not stripped [ron at monster1:~]$ python Python 2.5 (release25-maint, Jul 23 2008, 18:15:29) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> foolib = cdll.LoadLibrary('foo.so') >>> foolib.foo(0xF00000000) 0 >>> sizeof(c_void_p) 8 >>> I am aware of http://bugs.python.org/issue1703286 but I get the same result in Python2.5.2: [ron at monster1:~]$ py252/bin/python Python 2.5.2 (r252:60911, Sep 18 2008, 10:48:29) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from ctypes import * >>> foolib = cdll.LoadLibrary('foo.so') >>> foolib.foo(0xF00000000) 0 >>> sizeof(c_void_p) 8 >>> From fredrik at pythonware.com Fri Sep 5 02:43:15 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:43:15 +0200 Subject: "Full" element tag listing possible with Elementtree? In-Reply-To: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> References: <4af53d2c-1c69-41ca-98dc-a39690381415@w1g2000prk.googlegroups.com> Message-ID: jaime.dyson at gmail.com wrote: >
> this is node b > this is node c > > this is node e > > this is node f > > > I would want to print the following: > > > > text: this is node b > > text: this is node c > > > text: this is node e > > this is node f > > Is there a simple way to do this? Any help would be appreciated. in stock ET, using a parent map is probably the easiest way to do this: http://effbot.org/zone/element.htm#accessing-parents that is, for a given ET structure "tree", you can do parent_map = dict((c, p) for p in tree.getiterator() for c in p) def get_parents(elem): parents = [] while 1: elem = parent_map.get(elem) if elem is None: break parents.append(elem) return reversed(parents) for elem in tree.getiterator(): print list(get_parents(elem)), elem From deets at nospam.web.de Mon Sep 1 17:59:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 23:59:16 +0200 Subject: encoding In-Reply-To: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> References: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> Message-ID: <6i36tkFogbfkU1@mid.uni-berlin.de> Gandalf schrieb: > if i want to print utf-8 string i should writre: > > print u"hello word" No, you don't. You write print u"hello world".encode("utf-8") Read this: http://www.reportlab.com/i18n/python_unicode_tutorial.html > but what happen if i want to print variable? Then you do print variable_containing_unicode_object.encode("utf-8") Diez From castironpi at gmail.com Wed Sep 17 16:18:16 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 17 Sep 2008 13:18:16 -0700 (PDT) Subject: minimum install & pickling References: <6f045535-555f-44b6-93a5-f5b338d3f318@d45g2000hsc.googlegroups.com> Message-ID: <69cf2202-e11b-4994-84ab-a41167ef2652@26g2000hsk.googlegroups.com> On Sep 17, 4:43?am, Paul Boddie wrote: > On 17 Sep, 07:26, "Aaron \"Castironpi\" Brady" > wrote: > > > Sometimes questions come up on here about unpickling safely and > > executing foreign code. ?I was thinking a minimum install that didn't > > even have access to modules like 'os' could be safe. ? (Potentially.) > > I have time to entertain this a little, though all the devs are busy. > > I can bring it up again in a few months if it's a better time. > > One alternative might be to provide "safe" versions of the underlying > functions in modules like "os". Previously, I did wonder why people > didn't link Python against a bunch of alternative libraries which > would provide implementations of things like "open", "chdir" and so > on, but then I was made aware of fakeroot and fakechroot which do more > or less this for any program (in conjunction with chroot) in order to > restrict the behaviour of those programs, without any need to > statically link the programs first. > > [...] > > > A lot of modules would have to go. ? ?IPC modules: > > subprocess, socket, signal, popen2, asyncore, asynchat. ?ctypes, mmap, > > platform.popen, glob, shutil, dircache, and many more. > > Potentially, these could remain, but you'd want to provide "fake" > versions of the underlying functions, potentially implementing your > own preferred flavour of access control. So, with a call to the > "socket" function, the wrapped version might first consult some kind > of behaviour policy set by the user in order to get permission to open > a connection to a remote host. > > There's a discussion of rexec and related solutions on the Wiki: > > http://wiki.python.org/moin/How_can_I_run_an_untrusted_Python_script_...) > > Paul These solutions have at least the same bugs that the bare bones solution in the corresponding framework has. Malicious code has fewer options, but constructive code does too. If you're running foreign code, what do you want it to do? What does it want to do? The more options it needs, the more code you have to trust. The only way a Python script can return a value is with sys.exit, and only an integer at that. It is going to have output; maybe there's a way to place a maximum limit on its consumption. It's going to have input, so that the output is relative to something. You just make copies to prevent it from destroying data. Maybe command-line parameters are enough. IIRC if I recall correctly, Win32 has a way to examine how much time a process has owned so far, and a way to terminate it, which could be in Python's future. PyPy sandbox says: "The C code generated by PyPy is not segfaultable." I find that to be a bold claim (whether it's true or not). I'm imagining in the general case, you want the foreign code to make changes to objects in your particular context, such as exec x in vars. In that case, x can still be productive without any libraries, just less productive. From larry.bates at vitalEsafe.com Sat Sep 13 14:25:02 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 13 Sep 2008 13:25:02 -0500 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: <48cbf432$0$27507$426a34cc@news.free.fr> References: <48cbf09c$0$25189$426a74cc@news.free.fr> <48cbf432$0$27507$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Bruno Desthuilliers a ?crit : >> Larry Bates a ?crit : >> (snip) >>> IMHO it reads better if you use the __call__ method of the class to >>> return the value >> >> IMHO, it makes no sense at all to abuse the __call__ magic method here. > > Sorry - after a more careful re-read of other posts in the thread, it > might make sense, given the use case : > > condition = FolderInUse(core) > if condition.true_for(folder): > # code here > > > but then, a plain function (or a partial) might be even better - that > is, if the FolderInUse class doesn't have other responsabilities. > > Sorry but I respectfully disagree that this is "abuse" of the __call__ method. I do agree that a plain function probably makes more sense but it appears that the class does "other"things because of references to other class instances, etc. I also have a personal dislike for early returns because I've found it makes it harder insert execution trace logging into the code. Just my experience. -Larry From http Fri Sep 5 20:53:31 2008 From: http (Paul Rubin) Date: 05 Sep 2008 17:53:31 -0700 Subject: Can anyone suggest a good crypto package? References: <7xwshr4qr4.fsf@ruckus.brouhaha.com> <7xmyino11v.fsf@ruckus.brouhaha.com> <6a21ce15-da79-43f7-b090-71e36c6a7c89@d1g2000hsg.googlegroups.com> Message-ID: <7xzlmm6qno.fsf@ruckus.brouhaha.com> Fett writes: > I am having trouble seeing how I would post the encrypted data to a > website and get it back without it changing some. I don't understand why it would change. I'm a little confused though, I didn't realize you wanted to post the data to a web site. What exactly are you trying to do? > By replay attack I assume you mean posting old data with the signature > that is valid for that data? Yes, the usual case is injecting an old message into a sequence of messages that is part of a protocol. > Thanks for the warning, I suppose I could include a date/timestamp > in the data. Be aware in general that security is a messy and difficult subject and there are a lot of subtle errors you can make. You might look at some of the articles at www.dwheeler.com or the book "Security Engineering" (http://www.cl.cam.ac.uk/~rja14/book.html) to see some of the issues. From aahz at pythoncraft.com Sat Sep 27 01:15:43 2008 From: aahz at pythoncraft.com (Aahz) Date: 26 Sep 2008 22:15:43 -0700 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: In article , Steven D'Aprano wrote: >On Thu, 25 Sep 2008 21:17:14 -0700, Aahz wrote: >> >> Seems to me that if all the module is used for is to store state, you're >> wasting a file on disk. I personally prefer to use a class singleton. > >I don't recognise the term "class singleton". Can you explain please? How >is it different from an ordinary singleton? An ordinary singleton is instantiating the class multiple times yet returning the same instance object; a class singleton is simply using the class directly (like a module). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From robin at reportlab.com Thu Sep 11 13:07:19 2008 From: robin at reportlab.com (Robin Becker) Date: Thu, 11 Sep 2008 18:07:19 +0100 Subject: ReportLab 2.2 has been released Message-ID: <48C95047.8000209@chamonix.reportlab.co.uk> Version 2.2 of the ReportLab open-source toolkit is out! You find downloads and src instructions at http://www.reportlab.org/downloads.html. Contributions ============= Thanks to everybody who has contributed to the open-source toolkit in the run-up to the 2.2 release, whether by reporting bugs, sending patches, or contributing to the reportlab-users mailing list. Thanks especially to the following people, who contributed code that has gone into 2.2: including, but not limited to (apologies to any missed out) Matt Folwell, Jerome Alet, Harald Armin Massa, kevin at booksys.com, Sebastian Ware, Martin Tate, Wietse Jacobs, Christian Jacobs, Volker Haas, Dinu Gherman, Dirk Datzert & Yuan Hong. If we missed you, please let us know! New Features ============ PDF pdfmetrics: Added registerFontFamily function Basic support for pdf document viewer preferences (e.g.: fullscreen). Platypus Paragraph tag support for inline images. Paragraph autoleading support (helps with tags). Platypus doctemplate programming support. Support for tables with non-uniform row length. Graphics RGBA image support for suitable bitmap types. LTO labelling barcode. And many bugfixes... -- Robin Becker From george.sakkis at gmail.com Sun Sep 28 19:45:37 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 28 Sep 2008 16:45:37 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> On Sep 28, 2:29?pm, process wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. That's not a bug, it's a feature ;-) > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? As Terry Reedy wrote, partly history and partly practicality. There's no philosophical reason why we write "len(x)" (generic builtin), "x.append(1)" (method) or "del x[i]" (statement). The latter in particular is IMHO a design wart; there's no reason for not writing it as "x.delete(i)". George From cbabcock at kolonelpanic.org Fri Sep 5 19:18:33 2008 From: cbabcock at kolonelpanic.org (Chris Babcock) Date: Fri, 5 Sep 2008 16:18:33 -0700 Subject: Make Games References: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> Message-ID: <20080905161833.2d3b15b0@mail.asciiking.com> > I want to learn Python so I can make simple games. What are some good > books that'll help me do this? I promise that I'm not posting this to be a 81+<#: http://www.amazon.com/s/ref=nb_ss_gw?url=search-alias%3Daps&field-keywords=python+game Chris From david_v_wright at yahoo.com Fri Sep 5 03:21:34 2008 From: david_v_wright at yahoo.com (david wright) Date: Fri, 5 Sep 2008 00:21:34 -0700 (PDT) Subject: Creating directories In-Reply-To: <638982.16149.qm@web7902.mail.in.yahoo.com> Message-ID: <334015.16112.qm@web31807.mail.mud.yahoo.com> --- On Fri, 9/5/08, srinivasan srinivas wrote: > From: srinivasan srinivas > Subject: Creating directories > To: python-list at python.org > Date: Friday, September 5, 2008, 1:44 AM > Can someone tell me is there any module available to create > directories?? > > I tried os, tempfile. > I was facing some issues with os.mkdir(). The mode setting > was not proper with this method. > > I created the directory 'stdin' with '0700' > mode using os.mkdir() method. > $> ls -alR stdin/ > stdin/: > total 12 > drwx--S--- 2 munisams munisams 4096 Sep 3 02:00 . > What is that 'S' in the group permission field?? > this appears to be working, what where you expecting? "An upper case "S" means there is no executable permission, but the set group id function is active- that is, a file in this directory will belong to the same group id as the directory itself." If the parent directory has the set group id set, the child will as well. i.e. dwright at debian:~$ cd /tmp/ dwright at debian:/tmp$ mkdir test dwright at debian:/tmp$ ls -ld test drwxr-xr-x 2 dwright dwright 1024 2008-09-04 05:19 test dwright at debian:/tmp$ ls -la test drws------ 2 dwright dwright 1024 2008-09-04 05:19 . drwxrwxrwt 13 root root 3072 2008-09-04 05:19 .. dwright at debian:/tmp$ chmod 2700 test dwright at debian:/tmp$ ls -la test total 4 drwx--S--- 2 dwright dwright 1024 2008-09-04 05:19 . drwxrwxrwt 13 root root 3072 2008-09-04 05:19 .. dwright at debian:~$ python Python 2.4.4 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.mkdir('/tmp/test/TEST', 0700) dwright at debian:/tmp$ ls -la test total 5 drwx--S--- 3 dwright dwright 1024 2008-09-04 05:20 . drwxrwxrwt 13 root root 3072 2008-09-04 05:19 .. drwx--S--- 2 dwright dwright 1024 2008-09-04 05:20 TEST dwright at debian:/tmp$ ls -la test/TEST total 2 drwx--S--- 2 dwright dwright 1024 2008-09-04 05:20 . drwx--S--- 3 dwright dwright 1024 2008-09-04 05:20 .. +David From tjreedy at udel.edu Wed Sep 24 13:18:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2008 13:18:40 -0400 Subject: Comparing float and decimal In-Reply-To: References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: Mark Dickinson wrote: > On Sep 23, 7:31 pm, Terry Reedy wrote: >> Decimal is something of an anomaly in Python because it was written to >> exactly follow an external standard, with no concessions to what would >> be sensible for Python. It is possible that that standard mandates that >> Decimals not compare to floats. > > I don't think the standard says anything about interactions between > Decimals and floats. If there is not now, there could be in the future, and the decimal authors are committed to follow the standard wherever it goes. Therefore, the safe course, to avoid possible future deprecations due to doing too much, is to only do what is mandated. > But there's certainly been a feeling amongst at > least some of the developers that the job of Python's decimal module > is to implement the standard and no more, and that extensions to its > functionality belong elsewhere. For the reason just stated. A slightly different take is this. The reason for following the standard is so that decimal code in Python is exact interconversion both from and to decimal code in other languages. (And one reason for *that* is that one purpose of the standard is to reliably implement legal and contractual standards for financial calculations.) Using extensions in Python could break/deprecate code translated away from Python. > Regarding equality, there's at least one technical issue: the > requirement > that objects that compare equal hash equal. How do you come up with > efficient hash operations for integers, floats, Decimals and Fractions > that satisfy this requirement? For integral values, this is no problem. >>> hash(1) == hash(1.0) == hash(decimal.Decimal(1)) == hash(fractions.Fraction(1)) == 1 True > For other arithmetic operations: should the sum of a float and a > Decimal produce a Decimal or a float? Why? It's not at all clear to me that > either of these types is 'higher up' the numerical tower than the > other. Floats and fractions have the same issue. Fractions are converted to floats. I can think of two reasons: float operations are faster; floats are my typically thought of as inexact and since the result is likely to be inexact (rounded), float is the more appropriate type to express that. Anyone who disagrees with the choice for their application can explicitly convert the float to a fraction. Decimals can also be converted to floats (they also have a __float__ method). But unlike fractions, the conversion must be explicit, using float(decimal), instead of implicit, as with ints and fractions. Someone *could* write a PyDecimal wrapper that would do implicit conversion and thereby more completely integrate decimals with other Python numbers, but I doubt that saving transitivity of equality will be sufficient motivation ;-). Terry Jan Reedy From a at nospam.org Mon Sep 15 16:24:39 2008 From: a at nospam.org (Armin) Date: Mon, 15 Sep 2008 22:24:39 +0200 Subject: append on lists Message-ID: Hi, just a dumb question. Let a = [1,2,3,4,5] Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? --Armin From annathorns at googlemail.com Mon Sep 22 12:26:05 2008 From: annathorns at googlemail.com (annathorns at googlemail.com) Date: Mon, 22 Sep 2008 09:26:05 -0700 (PDT) Subject: Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS Message-ID: <0d7e53af-fa03-4ecc-8bcc-0393d1f7ab6d@v13g2000pro.googlegroups.com> Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com From adykes at panix.com Fri Sep 12 14:33:53 2008 From: adykes at panix.com (Al Dykes) Date: 12 Sep 2008 14:33:53 -0400 Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: In article <1bs69ogq6nspt.136i7kvcux142$.dlg at 40tude.net>, Alan Franzoni wrote: >zamil was kind enough to say: > >[cut] > >If your needs are very basic, you can stick with the tk module that comes >with python. It's not really feature-packed, but it's maintained and pretty >cross-platform. OK, what are my choices for an IDE/GUI development tool that runs on XP? Thanks -- Al Dykes News is something someone wants to suppress, everything else is advertising. - Lord Northcliffe, publisher of the Daily Mail From prologic at shortcircuit.net.au Sun Sep 7 18:42:06 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 08:42:06 +1000 Subject: Updating python dictionary In-Reply-To: References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: On Mon, Sep 8, 2008 at 8:37 AM, John Machin wrote: > Is this homework? I hope it's not - or I'll be quite annoyed :) > There seems to be an implicit assumption in the answers so far that > your mapping is a 1:1 mapping of all possible input keys. > > If it doesn't include all possible input keys, answers will crash with > a KeyError. If there are any many:1 elements in the mapping (for > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > in some checks for this. You are quite right! But then he/she didn't ask for this right ? :) cheers James -- -- -- "Problems are solved by method" From stef.mientki at gmail.com Tue Sep 30 15:06:07 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 21:06:07 +0200 Subject: rlcompleter and wxPython, problems ... In-Reply-To: References: <48E0045A.3020402@gmail.com> Message-ID: <48E2789F.7090207@gmail.com> Gabriel Genellina wrote: > En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki > escribi?: > >> I'm trying to implement autocompletion into my editor. >> But I find some weird behavior, >> or at least I don't have the faintest idea why this behavior occures, >> and even more important how to solve it >> In the example below I try to autocomplete " wx.s" , which in my >> humble opinion should at least produce "wx.stc" (and some others ). > > wx is a package. Modules within the package are not, by default, > attributes of the package - unless they're imported in __init__.py or > your code imports them. > So the autocompleter is doing the right thing in what perspective ? the autocompleter is only meant to assist the program writer ;-) > - wx.stc does not exist until it is explicitely imported. I guess I've to study the package. For the moment I'll implement a user editable list of additions. But with your remarks I tried __all__ And now I wonder why rlcompleter is not simply using "wx.__all__", it than does gets all the items ? cheers, Stef From kirk at athena.daycos.com Wed Sep 24 12:42:03 2008 From: kirk at athena.daycos.com (Kirk Strauser) Date: Wed, 24 Sep 2008 11:42:03 -0500 Subject: More regex help References: Message-ID: <86k5d1qyw4.fsf@athena.daycos.com> At 2008-09-24T16:25:02Z, "Support Desk" writes: > I am working on a python webcrawler, that will extract all links from an > html page, and add them to a queue, The problem I am having is building > absolute links from relative links, as there are so many different types of > relative links. If I just append the relative links to the current url, some > websites will send it into a never-ending loop. >>> import urllib >>> urllib.basejoin('http://www.example.com/path/to/deep/page', '/foo') 'http://www.example.com/foo' >>> urllib.basejoin('http://www.example.com/path/to/deep/page', 'http://slashdot.org/foo') 'http://slashdot.org/foo' -- Kirk Strauser The Day Companies From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 11:05:42 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 17:05:42 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: Message-ID: <48cbf2b4$0$21231$426a74cc@news.free.fr> Marco Bizzarri a ?crit : > On Sat, Sep 13, 2008 at 4:11 PM, Fredrik Lundh wrote: >> Marco Bizzarri wrote: >> >>> class FolderInUse: >>> >>> def true_for(self, archivefolder): >>> return any([instance.forbid_to_close(archivefolder) for instance in >>> self.core.active_outgoing_registration_instances()]) >>> >>> Is this any better? The true_for name does not satisfy me a lot... >> well, "true_for" is indeed pretty inscrutable, but I'm not sure that would >> be the first thing I'd complain about in that verbose mess... > > "verbose mess". > > It is always frustrating when you do what you think is your best and > you read that. The effbot is sometimes a bit abrupt in his formulations, for sure !-) From david.trem at gmail.com Sun Sep 14 14:34:00 2008 From: david.trem at gmail.com (David Trem) Date: Sun, 14 Sep 2008 11:34:00 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <48BFB534.2080508@egenix.com> Message-ID: <0642a573-1aaa-4181-a574-3a4c1ede95e8@m73g2000hsh.googlegroups.com> On 10 sep, 20:36, Fred Pacquier wrote: > Todd Whiteman said : > > > Personally, I believe XULRunner has a lot to offer for Python GUI > > development, I'm currently finishing up some documentation steps to show > > off how to use it specifically for Python (I'll post it to this list > > when it's finished). > > That would be really nice ! > > I've long been curious about the potential of XUL+Python, but put off by > the lack of leads to follow up, and not having time to do the digging > myself... > > TIA, > fp I will also like to see such documentation as soon as possible. To me, XUL+python really looks like what could be my prefered solution for multiplatform GUI for my python program. I'm really impatient and hope a strong and motivated community could set up arrond such XUL+python project. All the best, David From recombinant at hotmail.com Tue Sep 9 18:16:54 2008 From: recombinant at hotmail.com (Stephen D Evans) Date: Tue, 9 Sep 2008 23:16:54 +0100 Subject: Wx Python - Code Structure & Event Handling References: Message-ID: <48c6f5d9$0$2923$fa0fcedb@news.zen.co.uk> Lee, have you considered using the Model-View-Presenter pattern? There is a nice example on the wxPython wiki: http://wiki.wxpython.org/ModelViewPresenter This scales well to complex GUIs. Grasping the concept and writing the initial code is the difficult part. Code is then much easier to develop and maintain. There is also the Model-View-Controller pattern. Discussions about both of these patterns can be found on the wxPython wiki and wxPython list archives. For further simplification/maintainability I would recommend using XRC resources to create your widget hierarchies where possible. My preference is to use XRCed to generate python code with the resources embedded. Again consult the wxPython wiki, wxPython list archives - plus the wxPython DEMO (under Window Layout->XMLResource) Stephen wrote in message news:b502b8cf-ba28-4831-a2b0-647933a85e77 at m73g2000hsh.googlegroups.com... > Hi, > > I have just started writing a GUI using wxpython after finding a > limitation using Tkinter. I have read most tutorials on wxpython and > slowly becoming accustomed considering I started with the latter GUI > tool first! > I must quote first that I am a novice user of python so the issue(s) I > have may seem very obvious but please be patient with me! > > I have noticed that all the wxpython references I used for creating my > application(s) "cram" all the code in the frame subclass. This is > fine when you consider small applications but what about when they > grow into very complex applications? This creates my first question : > Where is it possible to find information on wxpython code practise/ > structure when considering complex larger Gui's? > > Without any reference I decided to attempt my owm method by breaking > up the top level panels in my frame as individiual class objects. and > then construct the widgets for the panels within the respective > classes. This led to my second problem, how do I use and event in one > Panel to cause an effect in the other Panel ? For example, if I have > button in one Panel and wish to change the text of a label in the > other Panel, what is the best way to do this? Should I break the code > into modules instead? > > Of course, you may explain that the way I have approached this is > completely wrong, if so please tell me, I really want to get the basic > structure right before I start making the code more complex. > > I look forward to your help > > ------------------------------------------------------------------------------------------------------------------------------------- > > I have listed some code below to help explain what concept I wish to > achieve, > > import wx > > class Frame(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, > title="Application",size=(400,400)) > Panel1 = wx.Panel(self, -1,size=(200,200)) > Panel2 = wx.Panel(self, -1,size=(200,200)) > Sizer = wx.FlexGridSizer(2,2,5,5) > Sizer.Add(Panel1) > Sizer.Add(Panel2) > self.SetSizerAndFit(Sizer) > Util1 = Utils1(Panel1) > Util2 = Utils2(Panel2) > > class Utils1(): > def __init__(self, Panel): > button = wx.Button(Panel,-1, "Button 1") > Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) > self.Label = wx.StaticText(Panel,-1, "Handler to me", > name="Lab1") > Sizer = wx.BoxSizer(wx.VERTICAL) > Sizer.Add(button) > Sizer.Add(self.Label) > Panel.SetSizerAndFit(Sizer) > > def OnClick(self, Evt): > self.Label.SetLabel("you changed me") > > class Utils2(): > def __init__(self, Panel): > self.button = wx.Button(Panel,-1, "Button 2") > Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) > > def OnClick(self, Evt): > """ what is the easiest & accepted Method of changing the text > in > a different class instance?""" > pass > #???.SetLabel("you changed me") > > app = wx.PySimpleApp() > frame = Frame() > frame.Show() > app.MainLoop() From ken at seehart.com Tue Sep 30 06:55:32 2008 From: ken at seehart.com (Ken Seehart) Date: Tue, 30 Sep 2008 03:55:32 -0700 Subject: Weirdness comparing strings In-Reply-To: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> References: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> Message-ID: <48E205A4.3020003@seehart.com> Instance comparison is not necessarily the same as string comparison. Neither __str__ nor __repr__ are implicitly used at all for comparison. In fact, by default a pair of instances are not equal unless they are the same object. To define comparison to mean something, you need to define __cmp__ or __eq__. Trivial example of default comparison: >>> class C: ... pass ... >>> c = C() >>> d = C() >>> c==d False >>> c==c True See http://docs.python.org/ref/customization.html for more details. Ken Mr.SpOOn wrote: > Hi, > I have this piece of code: > > class Note(): > ... > ... > def has_the_same_name(self, note): > return self == note > > def __str__(self): > return self.note_name + accidentals[self.accidentals] > > __repr__ = __str__ > > if __name__ == '__main__': > n = Note('B') > n2 = Note('B') > print n > print n2 > print n.has_the_same_name(n2) > > I'd expect to get "True", because their string representation is > actually the same, instead the output is: > > B > B > False > > I think I'm missing something stupid. Where am I wrong? > -- > http://mail.python.org/mailman/listinfo/python-list > > From maebert at uos.de Mon Sep 1 03:38:42 2008 From: maebert at uos.de (Manuel Ebert) Date: Mon, 1 Sep 2008 09:38:42 +0200 Subject: Command lime code In-Reply-To: References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Okay, I'll take I wild guess: By "command lime code" you did not refer to the algorithmic domination of citrus fruit, but rather to that window with the tiny blinking cursor and loads of text in white on black. Also by 'chdir' you probably mean the MS DOS equivalent to UNIX 'cd' (which AFAIK also works on MS DOS). So Googling for "MS DOS Commands" might be a good idea and yield, amongst others, this result: http://en.wikipedia.org/wiki/List_of_DOS_commands On Aug 29, 2008, at 6:20 PM, London at ezauza.com wrote: > I am new to python. > I did find a page which listed some code - IE "chdir" type code but > can not find it again. > Can you supply an address? > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIu5wCcZ70OCIgLecRArTEAJ42+XoaVOgOnk+o/f3shWSp0Cq3CQCfRstB 8bKzY9FBeZmGzKyzAg7xEwk= =3xLN -----END PGP SIGNATURE----- From lists at cheimes.de Thu Sep 11 18:10:28 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 12 Sep 2008 00:10:28 +0200 Subject: Accessing __slots__ from C In-Reply-To: References: Message-ID: Chris wrote: > Ok, thanks for the confirmation. We'd been hoping to avoid creating > such a struct... Don't worry, a C extension with its own struct isn't hard to write. Your C code can access the member variables w/o using any Python API. You'll get the full speed of C. :] Christian From larry.bates at vitalEsafe.com Mon Sep 15 14:07:24 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Mon, 15 Sep 2008 13:07:24 -0500 Subject: Client server implementation In-Reply-To: References: Message-ID: Babloo wrote: > Hi everyone, > > i wanted to implement a client- server connection > and transfer a file over the network. i was able to implement a normal > set up where in i was able to send chat messages and small chunks of > data. > I want to implement the file transfer with out using the FTP library > available in python . > > So can anyone suggest a piece of code by which i can > do that. > > Thanks > Pruthvi What Client OS? What Server OS? On LAN or Internet? You need to give is some information to help you. -Larry From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 2 10:04:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 02 Sep 2008 16:04:34 +0200 Subject: What is module initialization? In-Reply-To: References: Message-ID: <48bd4799$0$17215$426a74cc@news.free.fr> dudeja.rajat at gmail.com a ?crit : > Hi, > > I found on the net that there is something called module > initialization. The Python C api has a module init function for C-coded modules. There's no need for such a thing in pure Python modules since all the top-level code is executed when the module is loaded (as a main script or the first time the module is imported). > Unfortunately, there is not much information for this. > However, small the information I found module initialization can be of > use to me in my project. > > I'm currently messing with a problem where I'm keeping my global > variables ( or symbols) in a module and the other mdoules in the > project acess these global variables. remember that there's no such thing as a truely global namespace in Python. "global" really means "module level". > However, there is one case when a module updates one such global > variable While this is technically legal, you should restrain yourself from doing such a thing, unless you *really* know what you're doing and why. > but the variable is not getting updated in the module > containing global symbols ( variables). I suspect you didn't use a qualified name when importing. You have to do it this way : # myglobals.py: answer = 42 # question.py import myglobals myglobals.answer = "WTF ?" > So, I thought of using this module initialization where I will > intialize the module only once to update that variable. Ans in the > rest of the program where ever this module is imported I shall be able > to easily access the update value of the variable. > > Could some one provide me a sample code of module intialization? All statements at the top-level of a module are executed when the module is loaded. That's all it takes wrt/ module initialization. > And > how can I ensure that module initialization is done only once? Unless you're doing weird things with __import__ or the imp module, you shouldn't have to worry. import do two things : locate, load *and cache* the module *if* it isn't already in cache, and bind names into the importing namespace. From sjmachin at lexicon.net Wed Sep 3 19:28:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 3 Sep 2008 16:28:54 -0700 (PDT) Subject: Writing Unicode to database using ODBC References: Message-ID: <5738987c-633b-42b7-a803-d35040051f7e@1g2000pre.googlegroups.com> On Sep 4, 3:11?am, Mudcat wrote: [snip] > However, now that I've got all that working I'd like to simply take > the unicode data from the xml parser and then pass it directly into > the database (which is currently set up for unicode data). I've run What database? What does "set up for unicode data" mean? If you are using MS SQL Server, are your text columns defined to be varchar or nvarchar or something else? > into problems and just can't figure why this isn't working. > > The breakdown is occurring when I try to execute the db query: > > ? ? ? ? ? cur.execute( query ) > > Fairly straightforward. I get the following error: > > ? File "atp_alt.py", line 273, in dbWrite > ? ? cur.execute( query ) > UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in > position 3 > 79: ordinal not in range(128) > > I've verified that query is of type unicode by checking the type a > statement or two earlier (output: ). > So then I thought maybe the odbc execute just can't handle unicode > data. It appears to be expecting a str object, not a unicode object. > But when I do the following command: > > ? ? ? ? ? query = query.encode('utf-8') > > It actually works. So apparently execute can handle unicode data. "not crashing" != "works" > The > problem now is that basically the data has been encoded twice and is > in the wrong format when I pull it from the database: No, your utf8 string has been DEcoded using some strange encoding. > > >>> a > > u'+CMGL: (\xe2\u20ac\u0153REC UNREAD\xe2\u20ac\x9d,\xe2\u20ac\x9dREC > READ\xe2\u20ac\x9d,\xe2\u20ac\x9dSTO UNSENT\xe2\u20ac\x9d,\xe2\u20ac > \x9dSTO SENT\xe2\u20ac\x9d,\xe2\u20ac\x9dALL\xe2\u20ac\x9d) OK'>>> print a > > +CMGL: (???REC UNREAD?? ,?? REC READ?? ,?? STO UNSENT?? ,?? STO SENT? > ? ,?? ALL?? ) OK It would help very much if you showed the repr() of your input unicode text. Observation: the first bunch of rubbish output (\xe2\u20ac\u0153) differs from all the others (\xe2\u20ac\x9d). > > The non-alpha characters should be double-quotes. What "double-quotes" character(s)? Unicode has several: U+0022 (unoriented), U+201C (left), U+201D (right), plus more exotic ones. > It works correctly > if I copy/paste into the editor: > > >>> d > u'\u201cREC' > >>> print d > ?REC > >>> d.encode('utf-8') > '\xe2\x80\x9cREC' More observations: >>> u'\u201c'.encode('utf8') '\xe2\x80\x9c' >>> u'\u201c'.encode('utf8').decode('cp1252') u'\xe2\u20ac\u0153' Aha! The first load of rubbish! However: >>> u'\u201d'.encode('utf8') '\xe2\x80\x9d' >>> u'\u201d'.encode('utf8').decode('cp1252') Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\encodings\cp1252.py", line 15, in decode return codecs.charmap_decode(input,errors,decoding_table) UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2: character maps to >>> Hmmm, try the ferschlugginer mcbs encoding: >>> u'\u201d'.encode('utf8').decode('mbcs') u'\xe2\u20ac\x9d' >>> u'\u201c'.encode('utf8').decode('mbcs') u'\xe2\u20ac\u0153' >>> So, if you must persist with the odbc module, either encode your unicode text with mbcs, not utf8, or find out how to "set up for unicode data" so that utf8 is the default. You may like to consider using pyODBC or mxODBC instead of odbc. HTH, John From martin at v.loewis.de Sun Sep 21 04:54:56 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 Sep 2008 10:54:56 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> Message-ID: <48D60BE0.10106@v.loewis.de> Christian Heimes wrote: > Kay Schluehr wrote: >> Actually it is simply wrong in the mentioned case [...] > > It's not wrong. You have found a simple optimization. Lot's of compilers > for lots of languages optimize code by code folding. I don't think he meant that Python is wrong somehow, but that the OO babble of what happens for 2+2 is wrong. The babble said that, when the code is executed, an __add__ message is sent to the 2 object, with another 2 object as the parameter. That statement is incorrect: no message is sent at all, but the result is available even before the program starts. FWIW, "2+2" is not a good case for OO in Smalltalk, either. In a typical implementation, SmallInteger is not a real class, in the sense that 2 is not a real object. Instead, it lives in a tagged pointer, i.e. it has no identity. Regards, Martin From asnast at gmail.com Sat Sep 20 12:16:36 2008 From: asnast at gmail.com (Alex Snast) Date: Sat, 20 Sep 2008 09:16:36 -0700 (PDT) Subject: How to make a reverse for loop in python? Message-ID: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Hello I'm new to python and i can't figure out how to write a reverse for loop in python e.g. the python equivalent to the c++ loop for (i = 10; i >= 0; --i) From castironpi at gmail.com Sun Sep 28 20:31:20 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 17:31:20 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> <9f263cc0-508a-4597-94fc-365f6b691d10@i76g2000hsf.googlegroups.com> Message-ID: <5146813d-b203-49c8-8807-217e959ba5ce@e53g2000hsa.googlegroups.com> On Sep 28, 4:41?pm, "Tim Rowe" wrote: > 2008/9/28 Aaron Castironpi Brady : > > > Before I tried wxFormBuilder, I imagined that C# would be vastly > > faster to develop than Python, for anything requiring any non-trivial > > graphical interface. ?I've done extensive VB, so I can attest to that > > personally. ?It is not. > > I'm confused about where VB comes in -- I find VB just *slightly* > harder than INTERCAL. C# I find fairly easy. > > > You can come up with examples that favor either. ?But the opposite of > > statistical is anecdotal. ?Sorry again. > > Yes, it's anecdotal, but development time isn't just about how fast > the program is to type (otherwise, why aren't we all using APL?) > > > The last time I 'checked in' at your post, your claim was "an hour or > > so" vs. "ages". ?Hence my responses. ?You could probably sneak by by > > claiming a factor of *two*, but if you were exaggerating, please say > > so at any time. > > Ok. I was exaggerating when I said that VB was harder than INTERCAL. > It's marginally easier. > > As for the program I was working on, I worked for over a day on it in > Python, and did it in about an hour in C#, although in fairness I > didn't forget all the thinking I'd done on the previous day. I have a > lot more Python experience than C# experience, but don't claim to be a > guru in either. And no, I don't work two hour days (unfortunately). I > have indicated that the GUI wasn't the only issue; in C# it was just > easy in that case to find all the library bits I needed to in order to > accomplish the task. It isn't always so. > > > on this, that it's "pretty generally applicable" > > I'm with you on that. > > > I do not believe that C# is pretty generally applicable. > > I agree on that, but *only* because it's a proprietary language with > imperfect support once you move away from the .net platform. It's a > generally applicable language to .net, but .net is not a general > platform. > > > fact, outside of my VB, COM, and MFC experience, you could say I have > > no clue. ?Very tongue in cheek.) > > If you see C# as being in any way related to VB, it's no wonder you're > down on it! > > > Python has a lot of things C# doesn't. ?Can we agree on that? > > And C# has things that Python doesn't (such as static typing). Can we > agree on that, too? > > -- > Tim Rowe Maybe too much of my personal life is affecting my judgment of C#. You mention tools (that are doing the work for you) and I think incompatibility. Maybe that part is just because I feel like tools are like 'excuses'. And maybe that part is just because... awkward. I'm going to have to bow out of the dispute, sorry, because I am not a person that knows both of them. (How you decide who knows a language isn't exactly clear, by the way. It's been stated, for example, that I don't know Python, as well as that I don't know English.) You said C# = 1 hour, Python = ages. I said I could see that if it came to developing a GUI with a draw-on tool in one and not in the other. (Write that C# GUI spec by hand or position your controls from scratch.) You could make a case that you can get bad habits from developing in a tightly-coupled ("tightly-integrated") framework, as you suggested C# was. I would agree to it. I do not find that the Python library is particularly lacking, and the VB6 library was. If you're referring to documentation, though, I really like the win32 API docs. They're precise and thorough. The Python docs leave some stuff unsaid; there's a lot of stuff you can do in Python that people have to tell you or you have to discover on your own. Which one are the C# docs like? Not to reopen the wound, or rather to reopen it patiently: I classify 'static-typing' as handcuffs. C# has handcuffs and lots of kinds of them. "But static-typing lets you do ." ? Other than that, I don't know of any examples, from which I won't infer that there aren't any. (That was -won't- infer.) "Call," I guess; I'll bite. What? If you're referring to library depth, there's a lot of stuff that probably classifies as wheel reinvention that shouldn't necessarily go in the library. There was a good example today. 'Return a string of 5 random digits.' You could put that in the library, and call it 'RandomDigitString( int length )'. Doing it by hand only takes one line though: '"%05i"%random.randint(0,99999)'. Does it belong in the library? Otherwise you're technically reinventing the wheel, right? If you want to talk about your application, the day-to-hour ratio example, please do. From ken at jots.org Mon Sep 29 22:04:12 2008 From: ken at jots.org (Ken D'Ambrosio) Date: Mon, 29 Sep 2008 22:04:12 -0400 Subject: Newbie question... Message-ID: First, apologies for such a newbie question; if there's a better forum (I've poked around, some) feel free to point it out to me. Anyway, a mere 25-odd years after first hearing about OOP, I've finally decided to go to it, by way of Python. But this puzzles me: import commands free = commands.getoutput("free") for line in free: print line, Gives: t o t a l u s e d f r e e s h a r e d b u f f e r s c a c h e d M e m : 5 1 5 9 9 2 4 6 0 4 5 2 5 5 5 4 0 0 7 7 5 1 6 9 1 8 8 4 - / + b u f f e r s / c a c h e : 2 9 1 0 5 2 2 2 4 9 4 0 Why are there spaces between everything? And how do I keep it from happening? *confused* Thanks much, -Ken ** Posted from http://www.teranews.com ** From washakie at gmail.com Tue Sep 2 19:16:56 2008 From: washakie at gmail.com (John [H2O]) Date: Tue, 2 Sep 2008 16:16:56 -0700 (PDT) Subject: MoinMoin: trouble after install Message-ID: <19280220.post@talk.nabble.com> I've installed MoinMoin easily enough, but i have two problems now. 1) Some pages, namely the initial FrontPage, fail to load completely.... 2) It seems after logging in, if I navigate away from the login page, I get logged out immediately. I'm runing 1.13 on Fedora 9 with Apache 2 and ReWriteRules... all seemed well initially... Thanks! -- View this message in context: http://www.nabble.com/MoinMoin%3A-trouble-after-install-tp19280220p19280220.html Sent from the Python - python-list mailing list archive at Nabble.com. From gandalf at shopzeus.com Mon Sep 8 04:51:45 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 08 Sep 2008 10:51:45 +0200 Subject: universal unicode font for reportlab Message-ID: <48C4E7A1.2000504@shopzeus.com> I need to create multi lingual invoices from reportlab. I think it is possible to use UTF 8 strings but there is a problem with the font. I could not find any free TTF font that can do latin1, latin2, arabic, chinese and other languages at the same time. Is there a single font that is able to handle these languages? (Most of our invoices will be for EN, FR, DE, HU, SK, CZ, RO but some of them needs to be in Chinese.) Thanks, Laszlo From pythonnutter at gmail.com Thu Sep 18 05:22:19 2008 From: pythonnutter at gmail.com (Python Nutter) Date: Thu, 18 Sep 2008 19:22:19 +1000 Subject: Python for the iPhone? In-Reply-To: <18640.54221.603481.301379@montanaro-dyndns-org.local> References: <18640.54221.603481.301379@montanaro-dyndns-org.local> Message-ID: Yes it does involve Jailbreaking. Python GCC Java and Ruby are all available to run on the iPhone after you Jailbreak it. Just run the Cydia appliacation (jailbreak's AppStore) to install anything you want. For me I have not installed Python (yet). Jailbreak was only to tether iPhone to my Macbook since I've moved house and living out of a hotel until move into my next house. I would never have jailbroken if Apple did not killswitch the NetShare application. Tethering is 100% legal in my country and Apple just lost me in only 2 weeks of iPhone ownership. Cydia -> OpenSSH. Then I just reverse ssh socks proxied into my iPhone and shazam. Internet access here I am. (Downloading all my Mac updates as I type). Cheers, PN On 17/09/2008, skip at pobox.com wrote: > Anybody tried this port of Python to the iPhone? > > http://www.modmyi.com/nativeapps/python-v251/ > http://iphone.natetrue.com/ > > Hasn't been updated since July 2007. Maybe just a proof-of-concept? I'm > guessing it involves jailbreaking the phone. > > Skip > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at holdenweb.com Sun Sep 28 16:10:03 2008 From: steve at holdenweb.com (Steve Holden) Date: Sun, 28 Sep 2008 16:10:03 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> References: <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> <48DF63B2.2020408@wildenhain.de> <170543c70809281216r760fce4em926b4bd7bb265279@mail.gmail.com> Message-ID: Michael Mabin wrote: > Tino, dude, I'm afraid I lied about my previous post being the last > word. There are some things you said here that must be addressed. Good grief, is there no utterance so inconsequential that you will walk away from it without yet another round of retaliation? I believe that all people were trying to convey is: 1. There are some data patterns that cannot be directly incorporated into SQL statements without additional processing, regardless of whether the "intention" of the data's originator is malevolent. A good example is a string value containing an apostrophe, which in most SQL implementations you can escape by preceding the apostrophe with another apostrophe. 2. SQL drivers in Python are written so that no matter what the values of the data may be, and no matter which backend they implement, data may safely be passed as a tuple to a parameterized statement without such cleansing because the drivers are written to ensure "dangerous" values are appropriately handled. Having said all that, if you are positive none of your string data contains apostrophes you are, of course, free to build SQL statements yourself - though doing so will on some systems lose you the speed advantages offered by "prepared statements". Similarly, if you are *not* positive of the quality of your data you are free to do the escaping in your logic rather than using parameterized queries. This could be called "buying a dog and barking yourself". regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From john.ford at colorado.edu Wed Sep 24 23:30:00 2008 From: john.ford at colorado.edu (john.ford at colorado.edu) Date: Wed, 24 Sep 2008 20:30:00 -0700 (PDT) Subject: How to parse a string completely into a list Message-ID: I want to take a long alpha-numeric string with \n and white-space and place ALL elements of the string (even individual parts of a long white-space) into separate list elements. The most common way I've seen this performed is with the split() function, however I don't believe that it has the power to do what I am looking for. Any suggestions? thanks From Astley.lejasper at gmail.com Fri Sep 12 06:54:52 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Fri, 12 Sep 2008 03:54:52 -0700 (PDT) Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <48ca4780$0$15455$426a74cc@news.free.fr> Message-ID: On 12 Sep, 12:44, Bruno Desthuilliers wrote: > Astley Le Jasper a ?crit : > > > I'm still learning python and would like to know what's a good way of > > organizing code. > > > I am writing some scripts to scrape a number of different website that > > hold similar information and then collating it all together. Obviously > > each site needs to be handled differently, but once the information is > > collected then more generic functions can be used. > > > Is it best to have it all in one script or split it into per site > > scripts that can then be called by a manager script? > > If everything is > > in one script would you have per site functions to extract the data or > > generic function that contain vary slightly depending on the site, > > As far as I'm concerned, I'd choose the first solution. Decoupling > what's varying (here, site-specific stuff) from "invariants" is so far > the best way I know to keep complexity manageable. > > > for > > example > > > import firstSiteScript > > import secondSiteScript > > > firstsitedata = firstSiteScript.getData('search_str) > > secondsitedata = secondSiteScript.getData('search_str) > > etc etc > > Even better : > > - put generic functions in a 'generic' module > - put all site-specific stuff each in it's own module in a specific > 'site_scripts' directory > - in your 'main' script, scan the site_scripts directory to loop over > site-specific modules, import them and run them (look for the __import__ > function). > > This is kind of a Q&D lightweight plugin system, that avoids having to > hard-code imports and calls in the main script, so you just have to > add/remove site-specific script to/from the site_scripts directory . > > Also, imported modules are not recompiled on each import - only when > they change - while the 'main' script get recompiled on each invocation. > > (snip) > > > OR > > > def getdata(search_str, website): > > ? if website == 'firstsite': > > ? ? .... > > ? elif website =='secondsite': > > This one is IMHO the very worst thing to do. > > My 2 cents... Excellent, thanks for that. From skip at pobox.com Tue Sep 9 07:12:23 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 Sep 2008 06:12:23 -0500 Subject: biopython In-Reply-To: References: Message-ID: <18630.23063.827209.21083@montanaro-dyndns-org.local> >>> from Bio import Entrez Traceback (most recent call last): File "", line 1, in ? ImportError: cannot import name Entrez Can you import Bio, e.g.: import Bio ? If not, check to see where it's installed and make sure the directory containing Bio (or Bio.py) is in sys.path, either by setting the PYTHONPATH environment variable before running Python or adding a Bio.pth file to a directory which is in sys.path so it can be found. http://docs.python.org/lib/module-site.html http://docs.python.org/tut/node8.html Skip From sturlamolden at yahoo.no Wed Sep 24 16:55:13 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 13:55:13 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <6f9561d3-1239-4799-86db-082d0463189e@59g2000hsb.googlegroups.com> On Sep 24, 9:11?pm, bearophileH... at lycos.com wrote: > In the meantime where I > live lot of people will keep using C# instead of Python and CLisp, > natural selection at work indeed. Please explain to me what Linq can do that Python does not. Put you emphasis on why this can't be done with a library, and thus will require addition of new syntax to the language. From spammaster.10.webmaster at spamgourmet.com Sun Sep 14 11:14:52 2008 From: spammaster.10.webmaster at spamgourmet.com (spammaster.10.webmaster at spamgourmet.com) Date: Sun, 14 Sep 2008 08:14:52 -0700 (PDT) Subject: PyMarshal Commands crash on Windows References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> Message-ID: Hi! Please remember, that the script crashs on Line PyMarshal_WriteObjectToFile. :-( From kyosohma at gmail.com Thu Sep 25 09:11:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 25 Sep 2008 06:11:21 -0700 (PDT) Subject: urllib error on urlopen References: <80982dde-fbb8-4a94-98a2-8c953d1c52ef@f36g2000hsa.googlegroups.com> <564ecf05-4be1-41b3-ab49-c3f17b57ad3b@w7g2000hsa.googlegroups.com> Message-ID: <4176b842-d027-4303-90ea-1ef8562987bd@m3g2000hsc.googlegroups.com> On Sep 24, 7:08?pm, Michael Palmer wrote: > On Sep 24, 11:46 am, Mike Driscoll wrote: > > > > > Hi, > > > I have been using the following code for over a year in one of my > > programs: > > > f = urllib2.urlopen('https://www.companywebsite.com/somestring') > > > It worked great until the middle of the afternoon yesterday. Now I get > > the following traceback: > > > Traceback (most recent call last): > > ? File "", line 1, in > > ? ? response = urllib2.urlopen(req).read().strip() > > ? File "c:\python25\lib\urllib2.py", line 124, in urlopen > > ? ? return _opener.open(url, data) > > ? File "c:\python25\lib\urllib2.py", line 381, in open > > ? ? response = self._open(req, data) > > ? File "c:\python25\lib\urllib2.py", line 399, in _open > > ? ? '_open', req) > > ? File "c:\python25\lib\urllib2.py", line 360, in _call_chain > > ? ? result = func(*args) > > ? File "c:\python25\lib\urllib2.py", line 1115, in https_open > > ? ? return self.do_open(httplib.HTTPSConnection, req) > > ? File "c:\python25\lib\urllib2.py", line 1082, in do_open > > ? ? raise URLError(err) > > URLError: > routines:SSL23_GET_SERVER_HELLO:unknown protocol')> > > > I tried my Google Fu on this error, but there's not much out there. I > > tried using a proxy in Python, but that returned the same traceback. > > If I copy the URL into my browser, it resolves correctly. Does anyone > > have any advice on how to troubleshoot this error? > > > I am using Python 2.5.2 on Windows XP. > > > Thanks, > > > Mike > > Could it just be a misconfiguration at the other end? Can you open > other https urls? This is really weird. Now it works this morning. I've spoken with our webmaster/system admin and he said he didn't change anything on his end. We're both befuddled. Sorry for the noise. Mike From bignose+hates-spam at benfinney.id.au Fri Sep 26 23:16:08 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 13:16:08 +1000 Subject: Build-in 'repr' function (was: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])?) References: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> Message-ID: <87abduuvlz.fsf@benfinney.id.au> process writes: > ' '.join([`x * x` for x in range(1, 6)]) > > exactly what does this symbol do and what does it stand for? It's an obsolete, deprecated syntactic sugar for (what is now implemented as) the built-in 'repr' function. Instead, write the above as: ' '.join([repr(x * x) for x in range(1, 6)]) -- \ ?Killing the creator was the traditional method of patent | `\ protection? ?Terry Pratchett, _Small Gods_ | _o__) | Ben Finney From namekuseijin at gmail.com Tue Sep 23 14:02:30 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Tue, 23 Sep 2008 11:02:30 -0700 (PDT) Subject: Linq to Python References: Message-ID: <00245d29-de1b-4c5e-b5bf-a99fb7a3ce25@a70g2000hsh.googlegroups.com> On Sep 23, 2:07?pm, Jason Scheirer wrote: > On Sep 23, 7:48?am, hrishy wrote: > > > Hi > > > Will LINQ be ported to Python ? > > > regards > > Hrishy > > I think this question is more appropriate to ask on an IronPython > development list -- LINQ is pretty solidly intertwined with .Net, and > so you'll likely want to look at the .Net implementation of Python. But surely the idea behind it will eventually spread. It's really just comprehensions generalized over XML and relational datasets, a noble goal. Besides, it's main purpose for .NET was to bring functional programming to it. Python already has that, somewhat... From Richard_Martineau at xyratex.com Tue Sep 16 05:25:27 2008 From: Richard_Martineau at xyratex.com (Richard_Martineau at xyratex.com) Date: Tue, 16 Sep 2008 02:25:27 -0700 (PDT) Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows Message-ID: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Hello All I wonder if anyone can advise me or has done similar to the following? Basically I've downloaded the Python 2.5.2 source code that builds with Visual Studio 6.0. I've built Python for windows. This was easy (it even came with the pcbuild.dsw workspace file). Great! Now comes the troubled bit...I now look for similar source code for Python extensions Numpy and Scipy but the source code and directories are not all obvious. Looks like these are normally built via other compilers. However I need to do all my builds in VS 6.0. For Numpy (I haven't got as far as Scipy yet) I've organised the source code into the following projects and lumped them all into my new workspace numpy.dsw: dotblas fft lib linalg multiarray numarray random scalarmath sort umath I'm obviously not sure if this is correct. As you can see from above, I've re-arranged the source code directory named core into the following projects: dotblas sort multiarray scalarmath umath Unbelievably I am having some luck and nearly all the projects compile and link (untested though). I created the auto-generated files using the python scripts. Then I included the headers where necessary. However the remaining problems are: multiarray (wont compile) dotblas (wont link) dotblas seems to have missing dependencies on these: _cblas_sdot _cblas_ddot _cblas_cdotu_sub _cblas_zdotu_sub _cblas_cgemm _cblas_zgemm _cblas_sgemm _cblas_dgemm _cblas_cgemv _cblas_zgemv _cblas_sgemv _cblas_dgemv _cblas_caxpy _cblas_saxpy _cblas_zaxpy _cblas_daxpy _cblas_cdotc_sub _cblas_zdotc_sub Well that's a snapshot of where I am this morning. What I'm really after is some advice from anybody who has done similar. I'd really appreciate hearing from you. Thanks for your help and very happy to have joined this group Richard From fredrik at pythonware.com Sun Sep 21 05:35:04 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 11:35:04 +0200 Subject: Not fully OO ? In-Reply-To: <48D60BE0.10106@v.loewis.de> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <48D60BE0.10106@v.loewis.de> Message-ID: Martin v. L?wis wrote: > I don't think he meant that Python is wrong somehow, but that the OO > babble of what happens for 2+2 is wrong. The babble said that, when the > code is executed, an __add__ message is sent to the 2 object, with > another 2 object as the parameter. That statement is incorrect: no > message is sent at all, but the result is available even before the > program starts. On the other hand, the inability to distinguish between "as if" and "hah, I've looked under the covers" isn't necessarily a good trait for a programmer. If he bases his mental model on concrete implementation details of a production quality software product, he's bound to end up with a cargo-cultish understanding of fundamental issues. If he uses it to win arguments, people will flip his bozo bit pretty quickly. From robert.rawlins at thinkbluemedia.co.uk Thu Sep 18 08:47:54 2008 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins) Date: Thu, 18 Sep 2008 13:47:54 +0100 Subject: XML Processing In-Reply-To: <48D24638.9010601@timgolden.me.uk> References: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> <48D24638.9010601@timgolden.me.uk> Message-ID: <00ef01c9198c$c4bce780$4e36b680$@rawlins@thinkbluemedia.co.uk> > Some is going to kick themselves when they realise > that ElementTree *is* built in to Python 2.5 > > http://docs.python.org/whatsnew/modules.html#SECTION0001420000000000000000 Tim, Andrii, Thanks for the heads up on that! I hadn't noticed they're made it part of the platform modules, that's excellent news. In theory I should just be able to amend my import paths and we'll be good to go, no install external modules. Thanks for this, Robert From bdesth.quelquechose at free.quelquepart.fr Fri Sep 26 16:08:59 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 22:08:59 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> <48dc962a$0$2289$426a74cc@news.free.fr> Message-ID: <48dd5d46$0$26425$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 26 Sep 2008 09:58:39 +0200, Bruno Desthuilliers wrote: > >>> "Procedural" is the opposite of "functional", not "object-oriented". >> AFAIK, the "opposite" if functional is imperative, not procedural. But >> let's not waste too much time on terminology arguments... > > We're not wasting time on terminology arguments, we're wasting time on > definitional debates. > Point taken. But still a waste of time !-) From paulandersonusa at gmail.com Sun Sep 14 16:42:19 2008 From: paulandersonusa at gmail.com (primeq) Date: Sun, 14 Sep 2008 13:42:19 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> Message-ID: On Sep 11, 8:56?am, "carriere.jonat... at gmail.com" wrote: > Hello all; > > I wonder if there is a platform written in python. The equivalent of > the Netbeans platformhttp://platform.netbeans.org/in the Python > world. Do you know such a thing? > > Thanks a lot. > > Jonathan. Check out Eric (http://www.die-offenbachs.de/eric/) - it's not as solid as Netbeans (way lower funding, fewer developers by a large margin), but it works fine. Better still you have the source at your fingertips when you're using it - it's written in Python. Personally I have not had much success with the Windows version, but the Linux version works out of the box for me. From pfreixes at gmail.com Mon Sep 1 07:22:43 2008 From: pfreixes at gmail.com (Pau Freixes) Date: Mon, 1 Sep 2008 13:22:43 +0200 Subject: Best way for add new path when embedding python into C Message-ID: <207312b70809010422v5df73412xfc5e768a1c735c82@mail.gmail.com> Hi list, I have a little question about whats' the best way for add - no replace - new path into python c embedding environment for this situation. I'm using PyObject_CallObject(pfunc, pArgs); for call one function of some module loaded with PyImport_Import function. PyImport_Import function search this module into system path list object. I read some examples about Py_GetPath and PySys_SetPath and i think some examples are wrong or can be misinterpreted. Py_GetPath make only a basic path, some sitautions are considred for make this path, for example read environment varialbes. PySys_SetPath overwrite all path list object. When Py_Initialitze it's called sys path object is generated with Py_GetPath content and a other directories added by site.py file pre processor. The best way for add new path before call PyImport_Import is adding new string item into sys path object ? Bye and thks to all -- Pau Freixes Linux GNU/User -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 9 08:56:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 09:56:41 -0300 Subject: Long lines [was Re: __builtins__ magic behavior] References: <00d45042$0$20306$c3e8da3@news.astraweb.com> Message-ID: En Sun, 07 Sep 2008 19:30:07 -0300, Steven D'Aprano escribi?: > Gabriel, could I please ask you to configure your news-reader software or > editor to limit the length of each line of your posts to 70 characters > wide, as per the common standard for email and Usenet? Your lines are > significantly longer than that, including one single line which is 325 > characters wide. That forces a lot of backwards and forwards scrolling to > read your posts. Fixed, thanks for pointing it out. Opera wraps long lines automatically so I didn't notice the problem myself. I can't remember when, or why, I altered the setting (if *I* altered it at all!) -- Gabriel Genellina From clp at rebertia.com Tue Sep 30 12:30:44 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 30 Sep 2008 09:30:44 -0700 Subject: XMLRPC - C Client / Python Server In-Reply-To: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> References: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> Message-ID: <47c890dc0809300930o2229f2a0g7ae338fa8b4376e7@mail.gmail.com> On Tue, Sep 30, 2008 at 8:05 AM, wrote: > I have implemented a simple Python XMLRPC server and need to call it > from a C/C++ client. What is the simplest way to do this? I need to > pass numerical arrays from C/C++ to Python. If you just googled for "xmlrpc c", you would've found http://xmlrpc-c.sourceforge.net/ , which appears to be the best (and possibly only) option for this. Also, this isn't really Python-related if you think about it. Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > > Yours, Carl > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Sat Sep 20 06:14:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 12:14:33 +0200 Subject: Not fully OO ? In-Reply-To: <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: Kay Schluehr wrote: > Answer: if you want to define an entity it has to be defined inside a > class. If you want to access an entity you have to use the dot > operator. Therefore Java is OO but Python is not. you're satirising the quoted author's cargo-cultish view of object orientation, right? From mcohoon at gmail.com Mon Sep 15 17:25:53 2008 From: mcohoon at gmail.com (mpc) Date: Mon, 15 Sep 2008 14:25:53 -0700 (PDT) Subject: CGIHTTPServer webserver running php scripts Message-ID: <85ddfc4a-3dea-449e-9b68-c4271932de79@m44g2000hsc.googlegroups.com> hello, how does one run a PHP page with a python webserver? Lets say i have a simple python web server running /path/webserver.py #!/usr/bin/env python from BaseHTTPServer import HTTPServer from CGIHTTPServer import CGIHTTPRequestHandler serve = HTTPServer(("",8080),CGIHTTPRequestHandler) serve.serve_forever() Also lets say i am interested in hosting a simple.php in the cgi-bin directory. /path/cgi-bin/simple.php A simple php script. The webserver starts up and hosts html and python cgi's just fine but nothing will come up when we go to http://localhost:8080/cgi-bin/simple.php I get the following errors. with normal user localhost:path user$ python webserver.py localhost - - [15/Sep/2008 16:17:59] "GET /cgi-bin/example.php HTTP/ 1.1" 200 - Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/CGIHTTPServer.py", line 251, in run_cgi os.execve(scriptfile, args, os.environ) OSError: [Errno 8] Exec format error localhost - - [15/Sep/2008 16:17:59] CGI script exit status 0x7f00 localhost:path user$ sudo python webserver.py Password: localhost - - [15/Sep/2008 16:18:29] "GET /cgi-bin/example.php HTTP/ 1.1" 200 - Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/CGIHTTPServer.py", line 251, in run_cgi os.execve(scriptfile, args, os.environ) OSError: [Errno 13] Permission denied Is there something I can add to my python webserver so that it will properly run php files? From waldemar.osuch at gmail.com Wed Sep 10 15:44:03 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Wed, 10 Sep 2008 12:44:03 -0700 (PDT) Subject: Is there a SOAP module that can do this...? References: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> Message-ID: On Sep 10, 1:23?pm, thebjorn wrote: > I've been trying to use SOAPpy and ZSI (with and without the use of > wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic > server(?) in front of some enterprise java bean) and not having much > luck. ?I got them to send me an example of what the bytes on the wire > are supposed to look like (attached below), and I got it to "work" by > going lo-tech: > If you are willing to go low tech you can try http://effbot.org/downloads/#elementsoap But before you do that try: https://fedorahosted.org/suds It is actively maintained and holds a lot of promise. In my testing it knew how to connect to Sharepoint as well as WebLogic exposed services. Waldemar From grflanagan at gmail.com Thu Sep 18 06:31:45 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 18 Sep 2008 12:31:45 +0200 Subject: decorator and API In-Reply-To: References: Message-ID: Lee Harr wrote: > I have a class with certain methods from which I want to select > one at random, with weighting. > > The way I have done it is this .... > > > > import random > > def weight(value): > def set_weight(method): > method.weight = value > return method > return set_weight > > class A(object): > def actions(self): > 'return a list of possible actions' > > return [getattr(self, method) > for method in dir(self) > if method.startswith('action_')] > > def action(self): > 'Select a possible action using weighted choice' > > actions = self.actions() > weights = [method.weight for method in actions] > total = sum(weights) > > choice = random.randrange(total) > > while choice> weights[0]: > choice -= weights[0] > weights.pop(0) > actions.pop(0) > > return actions[0] > > > @weight(10) > def action_1(self): > print "A.action_1" > > @weight(20) > def action_2(self): > print "A.action_2" > > > a = A() > a.action()() > > > > > The problem I have now is that if I subclass A and want to > change the weighting of one of the methods, I am not sure > how to do that. > > One idea I had was to override the method using the new > weight in the decorator, and then call the original method: > > class B(A): > @weight(50) > def action_1(self): > A.action_1(self) > > > That works, but it feels messy. > > > Another idea was to store the weightings as a dictionary > on each instance, but I could not see how to update that > from a decorator. > > I like the idea of having the weights in a dictionary, so I > am looking for a better API, or a way to re-weight the > methods using a decorator. > > Any suggestions appreciated. > Here is another approach: 8<------------------------------------------------------------------- import random from bisect import bisect #by George Sakkis def take_random_action(obj, actions, weights): total = float(sum(weights)) cum_norm_weights = [0.0]*len(weights) for i in xrange(len(weights)): cum_norm_weights[i] = cum_norm_weights[i-1] + weights[i]/total return actions[bisect(cum_norm_weights, random.random())](obj) class randomiser(object): _cache = [] @classmethod def alert(cls, func): assert hasattr(func, 'weight') cls._cache.append(func) @classmethod def register(cls, name, obj): actions = {} weights = [] for klass in obj.__class__.__mro__: for val in klass.__dict__.itervalues(): if hasattr(val, '__name__'): key = val.__name__ if key in actions: continue elif val in cls._cache: actions[key] = val weights.append(val.weight) actions = actions.values() #setattr(cls, name, classmethod(lambda cls: random.choice(actions)(obj))) setattr(cls, name, classmethod(lambda cls: take_random_action(obj, actions, weights))) def randomised(weight): def wrapper(func): func.weight = weight randomiser.alert(func) return func return wrapper class A(object): @randomised(20) def foo(self): print 'foo' @randomised(10) def bar(self): print 'bar' class B(A): @randomised(50) def foo(self): print 'foo' 8<------------------------------------------------------------------- randomiser.register('a', A()) randomiser.register('b', B()) print 'A' randomiser.a() randomiser.a() randomiser.a() randomiser.a() randomiser.a() randomiser.a() print 'B' randomiser.b() randomiser.b() randomiser.b() randomiser.b() randomiser.b() randomiser.b() From skip at pobox.com Thu Sep 18 08:44:29 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 18 Sep 2008 07:44:29 -0500 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <18642.19757.260540.539125@montanaro-dyndns-org.local> Alex> Unfortunately my len(IN) is about 100.000 and the running time Alex> about 15h !!!! :( Alex> Any idea to improve it? numpy? http://numpy.scipy.org/ http://www.scipy.org/Numpy_Example_List More immediately, note that you are building a list of len(IN) ints every time through the inner loop. A quick hit might be this simple change: indexes = range(len(IN)) for i in indexes: #scan all elements of the list IN for j in indexes: if i != j: if (IN[i].coordinates[0] == IN[j].coordinates[0] and IN[i].coordinates[1] == IN[j].coordinates[1]): SN.append(IN[i].label) Skip From kyosohma at gmail.com Mon Sep 22 14:40:24 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 22 Sep 2008 11:40:24 -0700 (PDT) Subject: Problems running on hp dual core processor References: Message-ID: <285013e8-bdda-4623-94b3-15cd923ed55d@26g2000hsk.googlegroups.com> On Sep 22, 1:43?pm, jim-on-linux wrote: > Python help, > > I have a number of clients running a program built with > python 2.5. ?One has just purchased an HP with a duel > core processor, ?2.2G with .099g ram. > > On the new hp, when they try to print they get an > import error; > File win32ui.pyc line 12, in > File win32ui.pyc, line 10, in _load > ImportError: DLL load failed: ?The specified module > could not be found. > > The file is there The only difference I could find from > their other machines is the processor. I should note that I have had issues if I didn't include all the DLLs that were needed. This error doesn't say exactly which DLL is the issue. I recommend downloading Dependency Walker to find out what it is: http://www.dependencywalker.com/ Mike From sjmachin at lexicon.net Sun Sep 7 18:37:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 7 Sep 2008 15:37:54 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: On Sep 8, 7:51?am, "andyh... at gmail.com" wrote: > Hello... > > I have a dict of key/values and I want to change the keys in it, based > on another mapping dictionary. An example follows: > > MAPPING_DICT = { > ? ? 'a': 'A', > ? ? 'b': 'B', > > } > > my_dict = { > ? ? 'a': '1', > ? ? 'b': '2' > > } > > I want the finished my_dict to look like: > > my_dict = { > ? ? 'A': '1', > ? ? 'B': '2' > > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? > Is this homework? There seems to be an implicit assumption in the answers so far that your mapping is a 1:1 mapping of all possible input keys. If it doesn't include all possible input keys, answers will crash with a KeyError. If there are any many:1 elements in the mapping (for example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code in some checks for this. From sturlamolden at yahoo.no Fri Sep 12 19:04:56 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 12 Sep 2008 16:04:56 -0700 (PDT) Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> Message-ID: <88c2dc03-30a3-4f3b-8fee-f65b349d7418@59g2000hsb.googlegroups.com> On Sep 12, 8:33?pm, ady... at panix.com (Al Dykes) wrote: > OK, what are my choices for an IDE/GUI development tool that runs on XP? That depends on the GUI toolkit you are using. My suggestion: CPython with wxPython: wxFormBuilder Cpython with PyQt: BlackAdder CPython with PyGTK: GLADE 3 Jython: whatever there is for Swing or SWT. IronPython: MS VisualStudio Cpython + PyWin32: GUI with VB/Delphi/C#. Python ActiveX server (can use MFC). From NIE_DZIALA at gazeta.pl Tue Sep 23 12:44:12 2008 From: NIE_DZIALA at gazeta.pl (Piotr Sobolewski) Date: Tue, 23 Sep 2008 18:44:12 +0200 Subject: how can I use a callable object as a method References: <87r67hoe1p.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: >> However, the second version does not work. I think I understand >> why. That's because "a" inside f1 is not a function (but an object). > > An object that defines __call__ is perfectly usable as a function. > Your problem is that it doesn't know how to convert itself to a > method, so that f1.a() knows how to pass f1 as another_self to > add.__call__. To do that, add needs to be a bit smarter: A! Now it works, thanks a lot! From kyosohma at gmail.com Wed Sep 10 22:52:29 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 10 Sep 2008 19:52:29 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> <4pcgc495c6ml60a09fh3gc8e6t1akmlmin@4ax.com> Message-ID: <9d24a2d3-1ab2-44a7-92c6-f84a1922a6ac@y38g2000hsy.googlegroups.com> On Sep 10, 4:34?pm, Mike Driscoll wrote: > On Sep 10, 3:53?pm, James A. Donald wrote: > > > > > James A. Donald > > > > > Horrible installs are a chronic problem of GUI programs driven by > > > > interpreted languages ?Installing visual basic programs that worked on > > > > one Windows machine to work on a very slightly different windows > > > > machine was also a nightmare. > > > > > I have not attempted to create installable wxPython windows, but > > > > generally, "run anywhere" will bite you. ?Still looking for a good > > > > solution to "run anywhere". > > > Mike Driscoll > > > > I haven't had much trouble getting wxPython applications to run in > > > Windows XP and Ubuntu Hardy Heron. > > > Did you attempt to create proper install packages that show up in the > > Linux package managers, and the windows add/remove programs tool? > > I used Inno Setup which creates an uninstaller, however I am not > seeing it in my Windows Add/Remove. Odd. However, you can uninstall it > from the Start menu entry and it works. > > Currently, I am running the application from source in Linux. But I > plan to try cx_freeze or similar sooner or later. I haven't had need > to distribute it since my apps are for internal use so far. > > Mike I just tested my Inno installer again and it did put an entry in the Add/Remove program under Windows Vista. The machine I was looking at was my main development machine and probably wasn't a good example. Sorry about that. Mike From marco.bizzarri at gmail.com Tue Sep 16 02:54:44 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Tue, 16 Sep 2008 08:54:44 +0200 Subject: The need to use *arg,**kwd In-Reply-To: References: Message-ID: <3f0d61c40809152354o3223a698vc52a8b3198826a@mail.gmail.com> On Mon, Sep 15, 2008 at 11:51 PM, AON LAZIO wrote: > Hi, Pythoners. > I'd like to know when it is necessary to use *arg or **kwd in the > program. And when it is 'ok' to use normal form of function argument? > Thanks in advance. > > Aonlazio > Sorry, Aonlazio, but which program? This is a fair generic question which needs a little more details to be answered. You are not required to use them. You can use them if problem can be easily solved with them. Which, of course leads to the questionof what your problem is ;) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From nielinjie at gmail.com Sun Sep 14 11:28:50 2008 From: nielinjie at gmail.com (nielinjie) Date: Sun, 14 Sep 2008 23:28:50 +0800 Subject: How to marshal objects to readable files? Message-ID: <48CD2DB2.3090307@gmail.com> Hi list: I just want to marshal objects (instance of custom classes)to a human *READABEL *file/string, and also, I want unmarshal it back. in xml format or any other format. Any advice? Which lib should I use? Thanks a lot. From theiviaxx at gmail.com Tue Sep 9 13:04:02 2008 From: theiviaxx at gmail.com (TheIvIaxx) Date: Tue, 9 Sep 2008 10:04:02 -0700 (PDT) Subject: MySQLdb + AMD64 Message-ID: <94a92067-111a-46a7-b4a3-5770f9396f68@v13g2000pro.googlegroups.com> After searching around for a bit for a build of MySQLdb, i have found that i will probably need to build the module for AMD64 on windows. Is there a guide or something that shows what needs to be done to build a module for a certain architecture? Thanks From kyosohma at gmail.com Thu Sep 4 15:23:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Sep 2008 12:23:16 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: Message-ID: On Sep 4, 1:39?pm, Fett wrote: > I need a crypto package that works on windows with python 2.5. Can > anyone suggest one for me? > > I have been searching for a couple days for a good cryptography > package to use for public/private key encryption, at this point I > would settle for symmetric even. > > Every encryption package I have found for python was either operating > system specific (read *nix only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/ > > There was one exception, this version was specifically built to run on > any platform (yay), but the compiler for windows complained that I > wasn't using python2.2 (though the package was said to only need 2.2 > or newer). > > Is there any crypto package that is actually written in python? I > seriously don't care how slow it is. How about M2Crypto: http://chandlerproject.org/Projects/MeTooCrypto#Downloads Mike From rogeruclan at gmail.com Tue Sep 16 06:44:35 2008 From: rogeruclan at gmail.com (RLC) Date: Tue, 16 Sep 2008 03:44:35 -0700 (PDT) Subject: help on python SWIG C++ extension Message-ID: <20545f75-5621-4418-93a7-e4464d97d25e@26g2000hsk.googlegroups.com> Hello I am new to python SWIG. Recently I wrote a small program trying to import collada files(using colladadom) into python so I could use python cgkit to render them. However, during the progressing, I got some problems. Every time I quit from Python, I get a segmentation fault, although the main program runs well. I suspect it is because I wrapped std::vector objects in C struct and I did not release the memory properly. Below is the code. I am working on FreeBSD 7.0, GCC 4.2.1. I will be very appreciated if you could help me. Thanks a lot. the error I have got Segmentation fault: 11 (core dumped) //////////////////////// ///Header file //////////////////////// #ifndef TDIMPORT_H #define TDIMPORT_H #include #include #include "math.h" #include "float.h" #define WORDINVALIDVALUE ULONG_MAX #define FLOATINVALIDVALUE FLT_MAX typedef unsigned long WORD; typedef struct { double x,y,z; } Vertex; extern Vertex *new_Vertex(double x, double y, double z); extern void delete_Vertex(Vertex *v); extern double Vertex_length(Vertex *v); static const Vertex UNDEFINEDVERTEX = {FLT_MAX,FLT_MAX,FLT_MAX}; typedef struct { double u,v; } UV; extern UV *new_UV(double u, double v); extern void delete_UV(UV *uv); static const UV UNDEFINEDUV = {FLT_MAX,FLT_MAX}; typedef struct { double red,green,blue,alpha; } Color; extern Color *new_Color(double red, double green, double blue, double alpha); extern void delete_Color(Color *color); static const Color BLACK = {0.0, 0.0, 0.0, 1.0}; static const Color WHITE = {1.0, 1.0, 1.0, 1.0}; typedef struct { int type; Color color; std::string texture; } Material; typedef struct { std::vector vertices; std::vector polygonNbVertices; std::vector polygonStartVertexIndex; std::vector polygonVerticesIndices; std::vector uvs; std::vector polygonNbUVs; std::vector polygonStartUVIndex; std::vector polygonUVsIndices; Material material; } PolygonMesh; extern PolygonMesh *new_PolygonMesh(); extern void delete_PolygonMesh(PolygonMesh *p); extern unsigned long PolygonMesh_countvertices(PolygonMesh *p); extern unsigned long PolygonMesh_countpolygons(PolygonMesh *p); extern void PolygonMesh_appendvertex(PolygonMesh *p, Vertex *vertex); extern Vertex PolygonMesh_getvertex(PolygonMesh *p, unsigned long vertexIndex); extern void PolygonMesh_appendpolygon(PolygonMesh *p, const std::vector& verticesIndices); extern long PolygonMesh_getpolygonverticescount(PolygonMesh *p, unsigned long polygonIndex); extern std::vector PolygonMesh_getpolygonverticesindices(PolygonMesh *p, unsigned long polygonIndex); #endif ////////////////////////// //// implementation ////////////////////////// #include "tdimport.h" Vertex *new_Vertex(double x, double y, double z) { Vertex *v; v = (Vertex *)malloc(sizeof(Vertex)); v->x = x; v->y = y; v->z = z; return v; } void delete_Vertex(Vertex *v) { free(v); } double Vertex_length(Vertex *v) { return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); } UV *new_UV(double u, double v) { UV *uv; uv = (UV *)malloc(sizeof(UV)); uv->u = u; uv->v = v; return uv; } void delete_UV(UV *uv) { free(uv); } Color *new_Color(double r, double g, double b, double a) { Color *color; color = (Color *)malloc(sizeof(Color)); color->red = r; color->green = g; color->blue = b; color->alpha = a; return color; } void delete_Color(Color *color) { free(color); } PolygonMesh *new_PolygonMesh() { PolygonMesh *p; p = (PolygonMesh *)malloc(sizeof(PolygonMesh)); p->vertices.clear(); p->polygonNbVertices.clear(); p->polygonStartVertexIndex.clear(); p->polygonVerticesIndices.clear(); p->uvs.clear(); p->polygonNbUVs.clear(); p->polygonStartUVIndex.clear(); p->polygonUVsIndices.clear(); return p; } void delete_PolygonMesh(PolygonMesh *p) { free(p); } unsigned long PolygonMesh_countvertices(PolygonMesh *p) { return (unsigned long)p->vertices.size(); } unsigned long PolygonMesh_countpolygons(PolygonMesh *p) { return (unsigned long)p->polygonNbVertices.size(); } void PolygonMesh_appendvertex(PolygonMesh *p, Vertex *vertex) { p->vertices.push_back(*vertex); } void PolygonMesh_appendpolygon(PolygonMesh *p, const std::vector& verticesIndices) { unsigned int i; for ( i = 0 ; i < verticesIndices.size() ; i++ ) p->polygonVerticesIndices.push_back(verticesIndices.at(i)); p->polygonStartVertexIndex.push_back(p- >polygonVerticesIndices.size()-verticesIndices.size()); p->polygonNbVertices.push_back(verticesIndices.size()); } Vertex PolygonMesh_getvertex(PolygonMesh *p, unsigned long vertexIndex) { if (vertexIndex < 0 || vertexIndex>=p->vertices.size() ) { return UNDEFINEDVERTEX; } else { return p->vertices.at(vertexIndex); } } long PolygonMesh_getpolygonverticescount(PolygonMesh *p, unsigned long polygonIndex) { if ((polygonIndex < 0) || (polygonIndex >= p- >polygonStartVertexIndex.size())) { return (long)-1; } else { return (long)p->polygonNbVertices.at(polygonIndex); } } std::vector PolygonMesh_getpolygonverticesindices(PolygonMesh *p, unsigned long polygonIndex) { std::vector tmp; tmp.clear(); if ((polygonIndex < 0) || (polygonIndex >= p- >polygonStartVertexIndex.size())) { return tmp; } else { unsigned long count = p->polygonNbVertices.at(polygonIndex); unsigned long start = p->polygonStartVertexIndex.at(polygonIndex); for (unsigned long i=0; ipolygonVerticesIndices.at(i+start)); return tmp; } } ///////////////////////// ////SWIG interface ///////////////////////// %module tdimport %{ #include "tdimport.h" %} %include "std_string.i" %include "std_vector.i" namespace std { %template(IntVector) vector; %template(UIVector) vector; %template(VertexVector) vector; %template(UVVector) vector; } using namespace std; typedef struct { double x,y,z; %extend { Vertex (double,double,double); ~Vertex(); double length(); } } Vertex; typedef struct { double u,v; %extend { UV (double,double); ~UV(); } } UV; typedef struct { double red,green,blue,alpha; %extend { Color (double,double,double,double); ~Color(); } } Color; %apply const std::string& {std::string* texture}; typedef struct { int type; Color color; std::string texture; } Material; typedef struct { std::vector vertices; std::vector polygonNbVertices; std::vector polygonStartVertexIndex; std::vector polygonVerticesIndices; std::vector uvs; std::vector polygonNbUVs; std::vector polygonStartUVIndex; std::vector polygonUVsIndices; Material material; %extend { PolygonMesh(); ~PolygonMesh(); unsigned long countvertices(); unsigned long countpolygons(); void appendvertex(Vertex*); Vertex getvertex (unsigned long) ; void appendpolygon(const std::vector&); long getpolygonverticescount(unsigned long); std::vector getpolygonverticesindices(unsigned long); } } PolygonMesh; ///////////////////////// ////python file ///////////////////////// #!/usr/local/bin/python import tdimport a = tdimport.PolygonMesh() a.appendvertex(tdimport.Vertex(1.0,0.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,1.0)) a.appendpolygon([1,2,3]) b = a.getpolygonverticescount(0) print b del a //////////////////////////// ///compile command //////////////////////////// swig -c++ -python tdimport.i g++ -c tdimport.cpp g++ -c tdimport_wrap.cxx -I/usr/local/include/python2.5 g++ -shared tdimport.o tdimport_wrap.o -o _tdimport.so From torriem at gmail.com Tue Sep 30 15:58:49 2008 From: torriem at gmail.com (Michael Torrie) Date: Tue, 30 Sep 2008 13:58:49 -0600 Subject: XMLRPC - C Client / Python Server In-Reply-To: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> References: <23108969-93ec-41f4-b5e7-3af002dd0b5f@64g2000hsu.googlegroups.com> Message-ID: <48E284F9.60003@gmail.com> care02 at gmail.com wrote: > I have implemented a simple Python XMLRPC server and need to call it > from a C/C++ client. What is the simplest way to do this? I need to > pass numerical arrays from C/C++ to Python. Which do you need, C or C++? They are two different languages with different possibilities for libraries. As the other poster mentioned, xmlrpc-c is a good one for C, and also comes with bindings for C++ which I have used. Getting xmlrpc-c compiled can be a real challenge though. I recommend you use binary packages for your distribution of Linux. If you need it on Win32, then you'll have to spend a day or two figuring out how to build it on Windows. I eventually got the both the C and C++ client library built in Mingw with libcurl as the transport. But it was a real pain. From cvrebert at gmail.com Tue Sep 2 14:05:57 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Tue, 2 Sep 2008 11:05:57 -0700 Subject: How do I adjust the font size on IDLE when running on Mac OS 10.5.4? TIA. In-Reply-To: <16a5d0100809020626w78312e35l52b7c73eabf8add4@mail.gmail.com> References: <16a5d0100809020626w78312e35l52b7c73eabf8add4@mail.gmail.com> Message-ID: <47c890dc0809021105i3cdfd9e3ob738492f677ba407@mail.gmail.com> Same as on all the other platforms. 1. Open IDLE 2. Go Options -> Configure IDLE... 3. Choose the Fonts/Tabs section 4. Use the Size pulldown box - Chris On Tue, Sep 2, 2008 at 6:26 AM, Malcolm Lewis wrote: > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From castironpi at gmail.com Tue Sep 9 17:59:19 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 9 Sep 2008 14:59:19 -0700 (PDT) Subject: dynamic allocation file buffer Message-ID: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> I will try my idea again. I want to talk to people about a module I want to write and I will take the time to explain it. I think it's a "cool idea" that a lot of people, forgiving the slang, could benefit from. What are its flaws? A user has a file he is using either 1/ to persist binary data after the run of a single program (persistence) or 2/ share binary data between concurrently running programs (IPC / shared memory). The data are records of variable types and lengths that can change over time. He wants to change a record that's already present in the file. Here are two examples. Use Case 1: Hierarchical ElementTree-style data A user has an XML file like the one shown here. Foo ... He wants to change "Foo" to "Foobar". Foobar ... The change he wants to make is at the beginning of a 4GB file, and recopying the remainder is an unacceptable resource drain. Use Case 2: Web session logger A tutor application has written a plugin to a webbrowser that records the order of a user's mouse and keyboard activity during a browsing session, and makes them concurrently available to other applications in a suite, which are written in varying lanugages. The user takes some action, such as surfing to a site or clicking on a link. The browser plugin records that sequence into shared memory, where it is marked as acknowledged by the listener programs, and recycled back into an unused block. URLs, user inputs, and link text can be of any length, so truncating them to fit a fixed length is not an option. Existing Solutions - Shelve - A Python Standard Library shelf object can store a random access dictionary mapping strings to pickled objects. It does not provide for hierarchical data stores, and objects must be unpickled before they can be examined. - Relational Database - Separate tables of nodes, attributes, and text, and the relations between them are slow and unwieldy to reproduce the contents of a dynamic structure. The VARCHAR data type still carries a maximum size, no more flexible than fixed-length records. - POSH - Python Object Sharing - A module currently in its alpha stage promises to make it possible to store Python objects directly in shared memory. In its current form, its only entry point is 'fork' and does not offer persistence, only sharing. See: http://poshmodule.sourceforge.net/ Dynamic Allocation The traditional solution, dynamic memory allocation, is to maintain a metadata list of "free blocks" that are available to write to. See: http://en.wikipedia.org/wiki/Dynamic_memory_allocation http://en.wikipedia.org/wiki/Malloc http://en.wikipedia.org/wiki/Mmap http://en.wikipedia.org/wiki/Memory_leak The catch, and the crux of the proposal, is that the metadata must be stored in shared memory along with the data themselves. Assuming they are, a program can acquire the offset of an unused block of a sufficient size for its data, then write it to the file at that offset. The metadata can maintain the offset of one root member, to serve as a 'table of contents' or header for the remainder of the file. It can be grown and reassigned as needed. An acquaintence writes: It could be quite useful for highly concurrent systems: the overhead involved with interprocess communication can be overwhelming, and something more flexible than normal object persistence to disk might be worth having. Python Applicability The usual problems with data persistence and sharing apply. The format of the external data is only established conventionally, and conversions between Python objects and raw memory bytes take the usual overhead. 'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' currently offer this functionality, and the buffer offset obtained from 'alloc' can be used with all three. Ex 1. s= struct.Struct( 'III' ) x= alloc( s.size ) s.pack_into( mem, x, 2, 4, 6 ) Struct in its current form does not permit random access into structure contents; a user must read or write the entire converted strucutre in order to update one field. Alternative: s= struct.Struct( 'I' ) x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) s.pack_into( mem, x1, 2 ) s.pack_into( mem, x2, 4 ) s.pack_into( mem, x3, 6 ) Ex 2. class Items( ctypes.Structure ): _fields_= [ ( 'x1', ctypes.c_float ), ( 'y1', ctypes.c_float ) ] x= alloc( ctypes.sizeof( Items ) ) c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents c.x1, c.y1= 2, 4 The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. Ex 3. s= pickle.dumps( ( 2, 4, 6 ) ) x= alloc( len( s ) ) mem[ x: x+ len( s ) ]= s 'dumps' is still slow and nor does permit random access into contents. Use Cases Revisited Use Case 1: Hierarchical ElementTree-style data Solution: Dynamically allocate the tree and its elements. Node: tag: a Node: tag: b Node: tag: c Node: text: Foo The user wants to change "Foo" to "Foobar". Node: tag: a Node: tag: b Node: tag: c Node: text: Foobar Deallocate 'Node: text: Foo', allocate 'Node: text: Foobar', and store the new offset into 'Node: tag: c'. Total writes 6 bytes 'foobar', a one-word offset, and approximatly 5- 10-word metadata update. Use Case 2: Web session logger Dynamically allocate a linked list of data points. Data: 'friendster.com' Data: 'My Account' Allocate one block for each string, adding it to a linked list. As listeners acknowledge each data point, remove it from the linked list. Keep the head node in the 'root offset' metadata field. Restrictions It is not possible for persistent memory to refer to live memory. Any objects it refers to must also be located in file. Their mapped addresses must not be stored, only their offsets into it. However, live references to persistent memory are eminently possible. Current Status A pure Python alloc-free implementation based on the GNU PAVL tree library is on Google Code. It is only in proof-of-concept form and not commented, but does contain a first-pass test suite. See: http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk The ctypes solution for access is advised. From kyosohma at gmail.com Wed Sep 24 10:44:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 24 Sep 2008 07:44:25 -0700 (PDT) Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: <466524e9-ceba-42b7-b608-6fa5e0663c71@p25g2000hsf.googlegroups.com> On Sep 24, 8:17?am, Marin Brkic wrote: > Not commercial distribution, but an academic kind of sorts - giving > the exe file to coleagues, so they can use it in their work. Giving > .py file is not an option, since due to centralized computer > maintenance, they don't (and cannot) have installed python (except the > ones that bring their own computer at work, but those are an > exception). > > As far as I know py2exe is the only option which can do such a thing > (make exe files from scripts). Is there a way to make those exe files > a little smaller (for a small script they easily go up to 5-10 mb). > > Has anyone had a situation like this ? All your inputs and suggestions > are more then welcomed. > > -- > Marin It ends up being so large because of the dlls that are needed. There are other ways to distribute programs listed here: http://www.freehackers.org/Packaging_a_python_program Mike From tjreedy at udel.edu Wed Sep 10 16:38:23 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 16:38:23 -0400 Subject: which of these 2 quicksorts is faster? In-Reply-To: References: Message-ID: process wrote: > qsort can handle bigger lists it seems, making less recursive calls > before finishing(quicksort blows the stack when sorting > range(100,-1000,-1). > qsort does more work though right? is there a way to speed up that? If you are worried about speed, these 'neat' functional definitions are *not* the way to go. The standard in-place procedural version makes NO copies of the list and no concatenations of sorted pieces. It also scans and partitions the list once instead of twice for each call. > is the built-in sort not defined recursively? Definition != implementation. It is trivial to turn the second recursive call into iteration. More work and an explicit stack (easy in Python) will do the same for the second. > def quicksort(lista): > if len(lista) != 0: For speed, don't 'sort' a list of length 1. In fact, for speed, special-case lists of length 2 and possibly even longer 'short' lists. > return quicksort([x for x in lista[1:] if x < lista[0]]) + > [lista[0]] + \ > quicksort([x for x in lista[1:] if x >= lista[0]]) > else: > return [] > > def qsort(lista): > l = len(lista) In some fonts, 1 and l are extremely similar, so I initially read l/2 below as 1/2. Any of L or ln or n or sz would be clearer. > if len(lista) != 0: > return qsort([x for x in lista[:l/2]+lista[l/2+1:] if x < > lista[l/2]]) + \ > [lista[l/2]] + \ > qsort([x for x in lista[:l/2]+lista[l/2+1:] if x >= > lista[l/2]]) > else: > return [] The difference between your versions is the deterministic choice of pivot element in the (reduncant) double partitioning. It is generally better to pick one at random each time or possibly use the median value of the first, middle, and last. Either way, a consistently bad choice that leads to unbalanced partitions and deep recursion is less likely. Terry Jan Reedy From circularfunc at yahoo.se Tue Sep 16 09:39:18 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 06:39:18 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? References: <92d472c8-4af1-432a-a240-f9f9c97686eb@m73g2000hsh.googlegroups.com> Message-ID: On Sep 16, 3:36?pm, Niklas Norrthon wrote: > On 16 Sep, 15:27, cnb wrote: > > > i can run the interpreter. its just i cant load a file into it. > > > i tried adding your suggestion but it didnt help. i dont think thats > > the issue though. > > Start the interperter (Menu Python - Start interpreter) > Emacs split the frame in two windows > Place the cursor in the python file (C-x o) if necessary > Eval Buffer (C-c C-c) > > Niklas Norrthon ok so C-c C-l is just for doing import, not loading current file? When I do C-c C-c nothing happens at all. From odalrick at hotmail.com Sun Sep 7 12:12:53 2008 From: odalrick at hotmail.com (Odalrick) Date: Sun, 7 Sep 2008 16:12:53 +0000 (UTC) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <240454f2-14ee-496a-9078-1abbf80a4e64@m45g2000hsb.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote in news:240454f2-14ee-496a-9078-1abbf80a4e64 @m45g2000hsb.googlegroups.com: > castironpi: >> For max and min, why can't you just add your argument to the set >> itself? > > Sometimes that can be done, but in many other situations it's less > easy, like in the example I have shown in my first post: > > max((fun(x) for x in iterable if predicate(x))) > > There are some ways to add the max there, for example using an > itertools.chain to chan the default value to the end of the iterable, > but most of the time I just write a for loop. Is there any problem with: max(initial_value, *(fun(x) for x in iterable if predicate(x) ) ) ? From steve at REMOVE-THIS-cybersource.com.au Sat Sep 6 03:49:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Sep 2008 07:49:27 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> Message-ID: <00d23065$0$20302$c3e8da3@news.astraweb.com> On Sat, 06 Sep 2008 00:33:25 -0400, Manu Hack wrote: > Actually it's even more natural to state sum([x]) = x, and this way you > can never conclude that sum([]) = 0 from there. But what you can say is that for any list L, sum(L) = sum(L + [0]). Therefore sum([]) = sum([] +[0]) = 0 -- Steven From marco.bizzarri at gmail.com Fri Sep 5 11:21:09 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 17:21:09 +0200 Subject: Core dumped while interacting with OpenOffice.org via pyuno In-Reply-To: <200809051550.32439.maric@aristote.info> References: <3f0d61c40809050604y42bc494bqa6c91cb1cc3cd913@mail.gmail.com> <200809051550.32439.maric@aristote.info> Message-ID: <3f0d61c40809050821g2c852626s667b21144419502c@mail.gmail.com> On Fri, Sep 5, 2008 at 3:50 PM, Maric Michaud wrote: > Le Friday 05 September 2008 15:04:22 Marco Bizzarri, vous avez ?crit : >> Hi all. >> >> I'm experiencing a core dump while working in the following environment >> >> - debain etch >> - python2.3 >> - openoffice.org 2.4 >> - Zope 2.8.8 >> >> I was able to get a core dump, and the backtrace shows the following: >> >> Core was generated by `python2.3 tests/testActs.py'. >> Program terminated with signal 11, Segmentation fault. >> #0 0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 > ... lot of backtrace ... >> #9 0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3 >> #10 0x08797840 in ?? () >> #11 0x0989b6e0 in ?? () >> #12 0x00000000 in ?? () >> >> Now, I can understand that the information I provided are not enough >> to give me suggestions on solving this issue; so, I'm asking >> suggesions on investigating the issue, namely: >> >> - should I ask here or is it better if I ask on a openoffice forum? > > Yes. Ok >> - should I use a debug-enabled python in order to have more meaningful >> backtraces? > > What you need is more a debug enabled version of pyuno libraries. Ok; I will check with the openoffice guys, then. >> - is there something else I should do in order to have more clues >> ("Read The Fine Manual (tm)" is an acceptable answer) > > You can try to find which function call exactly provoke the exception, the > simplest way is to trace execution flow with some print statments and using > non forking zope instance (runzope -d if I remember well). > Ok; just for completeness, this is not a running zope application, it is a ZopeTestCase which is causing me the trouble. And, as usual, it does not cause it always :-) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From jkrukoff at ltgc.com Wed Sep 3 18:14:48 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Wed, 03 Sep 2008 16:14:48 -0600 Subject: python/xpath question.. In-Reply-To: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> References: <175e01c90e04$cb9be760$0301a8c0@tmesa.com> Message-ID: <1220480088.4120.227.camel@jmk> On Wed, 2008-09-03 at 13:36 -0700, bruce wrote: > morning.... > > i apologize up front as this is really more of an xpath question.. > > in my python, i'm using the xpath function to iterate/parse some html. i can > do something like > > s=d.xpath("//tr/td/text()") > count=len(s) > > and get the number of nodes that have text > > i can then do something like > s=d.xpath("//tr/td") > count2=len(s) > > and get the number of total nodes... > by subtracting, i can get the number of nodes, without text.. is there an > easier way??!! > count2-count > > ie, if i have something like > > > foo > > > is there a way to get the count that there is a single "td" node with > text()="" > > thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list Well, you could just do the test (and the count!) in the xpath expression: count( //tr/td[ text() != "" ] ) It sounds like you're not familiar with xpath? I would recommend the O'Reilly XSLT book, it has an excellent introduction to xpath in chapter 3. -- John Krukoff Land Title Guarantee Company From samslists at gmail.com Tue Sep 9 15:38:54 2008 From: samslists at gmail.com (Sam) Date: Tue, 9 Sep 2008 12:38:54 -0700 (PDT) Subject: Deflate with urllib2... Message-ID: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> I'm using urllib2 and accepting gzip and deflate. It turns out that almost every site returns either normal text or gzip. But I finally found one that returns deflate. Here's how I un-gzip: compressedstream = StringIO.StringIO(data) gzipper = gzip.GzipFile(fileobj=compressedstream) data = gzipper.read() Un-gzipping works great! Here's how I un-deflate (inflate??) data = zlib.decompress(data) Un-deflating doesn't work. I get "zlib.error: Error -3 while decompressing data: incorrect header check" I'm using python 2.5.2. Can someone tell me exactly how to handle deflated web pages? Thanks From steve at REMOVE-THIS-cybersource.com.au Mon Sep 22 19:23:54 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 23:23:54 GMT Subject: A bit weird dictionary behavior References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: <00e822ed$0$20303$c3e8da3@news.astraweb.com> On Mon, 22 Sep 2008 07:35:50 -0700, bearophileHUGS wrote: > Tino Wildenhain: > >> Wouldn't >> len([x for x in iterable if x==y]) >> or even shorter: >> iterable.count(y) >> not work and read better anyway? > > The first version creates an actual list just to take its length, think > about how much memory it may use. For many iterables, the amount of memory is not excessive and the increase in readability of len() is to be preferred over the side-effect of sum(1 for...). But sure, in general you shouldn't try to count the number of items in an arbitrary iterable unless you know how much time and resources it will end up using. That's why I don't think len() should support arbitrary iterables. >> even calculating with boolean values isn't neccessary since 'and' and >> 'foo if bar else blub' are working much better so the type coalescing >> bool - int - float can really go away. > > I don't understand. I think Tino means that you don't need to cast items to bool since you can use ints, floats etc. directly as truth values. -- Steven From blogmoney.bm at gmail.com Fri Sep 26 01:15:26 2008 From: blogmoney.bm at gmail.com (blogmoney) Date: Thu, 25 Sep 2008 22:15:26 -0700 (PDT) Subject: =?KOI8-R?B?LY2NII0gjSCNIFNlY3JldCBCb3RoIFJvb20gVmlkZW8gQ0xJUFMgjQ==?= =?KOI8-R?B?II0gjSCNjY0=?= Message-ID: <1289835d-7007-4108-837b-c7a27347f003@q5g2000prf.googlegroups.com> Watch the Free ==Videos== of All --->LESBIAN College Girl<--- Having Horny VIDEOS...... Here the Huge Collection of Horny Lesbian College Girl & More of School Girls SECRET MMS CLIPStoo... Watch the Free Video Here that will make you satisfied at all.... www.onlinejobszone.blogspot.com www.sfimoney4all.blogspot.com www.yogatips4all.blogspot.com www.hollywoodspicyzone.blogspot.com http://onlinemoney2u.wordpress.com www.onlinejobs4all.googlepages.com From michele at nectarine.it Tue Sep 30 13:50:57 2008 From: michele at nectarine.it (Michele) Date: Tue, 30 Sep 2008 19:50:57 +0200 Subject: Problems with encoding/decoding locales Message-ID: <48e26702$0$18149$4fafbaef@reader3.news.tin.it> Hi there, I'm using a python script in conjunction with a JPype, to run java classes. So, here's the code: from jpype import * import os import random import math import sys input = open('foo.img','rb').read().decode('ISO-8859-1') square = java.encoding(input) output = java.decoding() fd = open('foo_decode.img','wb') fd.write(output.encode('ISO-8859-1')) fd.close() sys.exit(0) First of all, java.encoding and java.decoding are two methods that respectively take a java string as an argument and return a java String. JPype is the bridge between Java and Python, and converts automatically a str or unicode pythonstring into a Java String. So, input and output are two unicode strings. I were forced to use decode() and encode() methods by python, otherwise it refuses to read foo.img file. Here's the strange behaviour: when I write the output in the 'foo_decode.img', I don't reassemble the original file; I already tested the java encoding/decoding libraries with the same input file, and what the decoding process returns is the original file. I suspect that the discrepancy is due to encoding/decoding of ISO-8859-1: is that required? What do you think about? Thank you From tkpmep at hotmail.com Tue Sep 23 14:02:03 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Tue, 23 Sep 2008 11:02:03 -0700 (PDT) Subject: Detecting the first time I open/append to a file Message-ID: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> I have a simulation that runs many times with different parameters, and I want to aggregate the output into a single file with one rub: I want a header to be written only the first time. My program looks a bit like this: def main(): for param in range(10): simulate(param) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) If I can sense that the file is being created in the first iteration, I can then use an if statement to decide whether or not I need to write the header. Question: how can I tell if the file is being created or if this its the first iteration? It's unrealistic to test the value of the parameter as in the real problem, there are many nested loops in main, and the bounds on the loop indices may change. Thanks in advance for your assistance Thomas Philips From harrrrpo at gmail.com Wed Sep 3 05:49:38 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Wed, 3 Sep 2008 11:49:38 +0200 Subject: python - mechanize/browser/POST issue In-Reply-To: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> References: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> Message-ID: <538050a90809030249t7b25d97cvdd3920b9440eeed3@mail.gmail.com> Hello , i don't know about mechanize but in general all you have to do is a simple socket text sending connect to the server then send it POST headers to page in question.. what to send ? getting this your self is much better and one of the best tools is LiveHTTPHeaders - an addon for firefox - so open it post the form in browser then see what you got in LiveHttpHeaders , it will also help you more read through the form being posted html code (knowing posted fields) Regards, Mohamed Yousef 2008/9/3 bruce : > evening... > > using mechanize/Browser, i can easily do a url/get, and process submitting a > form that uses a GET as the action. however, I'm not quite sure how to > implement the submittal of a form, that uses the POST action. > > Anyone have a short chunk of code that I can observer, that uses the > mechanize.Browser implentation? > > in searching the net, i haven't found any... > > thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gh at ghaering.de Tue Sep 23 08:45:33 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 23 Sep 2008 14:45:33 +0200 Subject: Comparing float and decimal In-Reply-To: <20080923072012.57d8d329.darcy@druid.net> References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: D'Arcy J.M. Cain wrote: > I'm not sure I follow this logic. Can someone explain why float and > integer can be compared with each other and decimal can be compared to > integer but decimal can't be compared to float? > >>>> from decimal import Decimal >>>> i = 10 >>>> f = 10.0 >>>> d = Decimal("10.00") >>>> i == f > True >>>> i == d > True >>>> f == d > False I can give you the technical answer after reading the sources of the decimal module: you can only compare to Decimal what can be converted to Decimal. And that is int, long and another Decimal. Everything else will return False when comparing. > This seems to break the rule that if A is equal to B and B is equal to > C then A is equal to C. Yes, but only if comparison from type(A) to type(C) is supported at all. Instead of raising ValueError or NotImplementedError, the decimal module returns False here. -- Gerhard From fredrik at pythonware.com Sun Sep 21 07:37:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 13:37:39 +0200 Subject: How to kill threading.Thread instance? In-Reply-To: References: Message-ID: dmitrey wrote: > BTW, it should be noticed that lots of threading module methods have > no docstrings (in my Python 2.5), for example _Thread__bootstrap, > _Thread__stop. things named _Class__name are explicitly marked private by the implementation (using the "__" prefix). using them just because you can find them via "dir" is a really stupid idea. (and, as noted in the comment section to the recipe, the "stop" method flags a thread as stopped, it doesn't stop it.) From castironpi at gmail.com Wed Sep 17 20:54:49 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 17 Sep 2008 17:54:49 -0700 (PDT) Subject: minimum install & pickling References: <6jdh9gF2q06nU1@mid.individual.net> Message-ID: <0a6f3d3e-9c2e-421b-bfec-c87f7bd2982b@f63g2000hsf.googlegroups.com> On Sep 17, 6:06?pm, greg wrote: > Aaron "Castironpi" Brady wrote: > > Even a function created from raw bytecode string can't do anything > > without __import__ or 'open'. > > Not true: > > ? ?for cls in (1).__class__.__bases__[0].__subclasses__(): > ? ? ?if cls.__name__ == "file": > ? ? ? ?F = cls > > ? ?F(my_naughty_path, "w").write(my_naughty_data) > > -- > Greg You're right, the list is a little longer. See above, where I renamed the Lib/ folder. 'import site' failed; use -v for traceback Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> for cls in (1).__class__.__bases__[0].__subclasses__(): ... if cls.__name__ == "file": ... F = cls ... >>> F Traceback (most recent call last): File "", line 1, in NameError: name 'F' is not defined >>> 'file' here is still defined. >>> file >>> del __builtins__.file >>> file Traceback (most recent call last): File "", line 1, in NameError: name 'file' is not defined This one stands a chance. From afriere at yahoo.co.uk Wed Sep 24 02:18:04 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 23 Sep 2008 23:18:04 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <5d7d0889-3afd-4e17-b617-6d9c8437eeb5@a3g2000prm.googlegroups.com> On Sep 24, 8:10 am, Christian Heimes wrote: > Side note: > > sys.exit() is just another way to write raise SystemExit. The function > is defined as: > As can be seen if you were ever silly enough to call sys.exit() in IDLE. ;) From dudeja.rajat at gmail.com Mon Sep 8 12:35:21 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 8 Sep 2008 17:35:21 +0100 Subject: Unable to start a process with subprocess Popen() In-Reply-To: <3657eb2f-c827-4929-be5a-689959de5f85@a1g2000hsb.googlegroups.com> References: <3657eb2f-c827-4929-be5a-689959de5f85@a1g2000hsb.googlegroups.com> Message-ID: On Mon, Sep 8, 2008 at 4:43 PM, aha wrote: > On Sep 8, 7:23 am, dudeja.ra... at gmail.com wrote: >> On Mon, Sep 8, 2008 at 11:50 AM, wrote: >> > Hi, >> >> > I'm using the subprocess module's Popen() to start a batch file. This >> > batch file basically calls an exe which also gets started. >> > Unfortunately, this does not produce any results. I looked into the >> > Task bar that this exe has started but it does not consume and cpu so >> > I believet that this exe is not working. >> >> > I used the following command to start the batch fiile: >> >> > testing = subprocess.Popen([batchFilePath], \ >> > shell = True, \ >> > stdout = subprocess.PIPE, \ >> > stderr = subprocess.PIPE).communicate()[0] >> >> > batchFilePath is the path of the batch file. >> >> > -- >> > Regrads, >> > Rajat >> >> Ok, I re-phrase my question: >> >> there is a batch file that executes a exe file. The batch just works >> if run from command prompt and produces output to standard output and >> the file. >> >> Now, I try to call the same batch file from subprocess.Pope() call. >> The batch file gets called and that internally also calls the exe >> file. >> >> But, the exe just runs forever i.e. hangs and does not produces output >> , atleast not to the file. >> >> Please suggest is there is something wrong with the above code. >> >> Regards, >> Rajat > > Hello Rajat, > I would take a look at the thread below, it might help it might not: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/4505613f014fdec7/3ee15c9c88a5efdc?hl=en#3ee15c9c88a5efdc > > Also, if you post a larger section of the code I might be able to give > you a hand. Once you've run the testing = subprocess.Popen() > > make sure you use a testing.wait() > -- > http://mail.python.org/mailman/listinfo/python-list > Hi Aaquil, Thanks for helping me out with this piece of information. My Original code is : testing = subprocess.Popen([batchFilePath], \ shell = True, \ stdout = subprocess.PIPE, \ stderr = subprocess.PIPE) result = testing.wait() if result < 0: childError = testing.stderr.read() tkMessageBox._show("Error", \ icon='error', \ message ="Error: %s" % childError) return None else: print result My child process was unresponsive. Later I got to know with the below code that there were some errors coming from the child process which I was not able to detect with this code. I googled for some solution and found the below code :- print "ttt", batchFilePath #print os.listdir(batchFilePath) try: cmd = subprocess.Popen([batchFilePath], \ shell = True, \ stdin = subprocess.PIPE, stdout = subprocess.PIPE, \ stderr = subprocess.PIPE \ ) cmd.stdin.close() outPipe, errPipe = PipeThread(cmd.stdout), PipeThread(cmd.stderr) outPipe.run(), errPipe.run() retcode = cmd.wait() out, err = outPipe.getOutput(), errPipe.getOutput() if retcode != 0 and err != '': raise ExecutionFailed, os.path.basename(batchFilePath) + " exited with error code " + str(retcode) + " and errors:\n" + err elif retcode != 0: raise ExecutionFailed, os.path.basename(batchFilePath) + " exited with error code " + str(retcode) + " and output:\n" + out elif err != '': return out + "\n" + os.path.basename(batchFilePath) + " gave warnings:\n" + err else: return out except Exception, e: if isinstance(e, ExecutionFailed): raise else: raise ExecutionFailed, "Error while executing " + ":\n" + str(e) Here are the Exception and the PipeThread Classes: class PipeThread(threading.Thread): def __init__(self, fin): self.fin = fin self.sout = "" threading.Thread.__init__(self) def run(self): self.sout = self.fin.read() def getOutput(self): return self.sout class ExecutionFailed(Exception): def __init__(self, value): self.parameter = value def __str__(self): return str(self.parameter) Although, this solved my problem. But I know there is no need for using threading in this problem. This problem could've been solved just by the subprocess module. I'm unnecessarily using the threading module. Regards, Rajat -- Regrads, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From hvlems at freenet.de Sun Sep 21 18:00:16 2008 From: hvlems at freenet.de (H Vlems) Date: Sun, 21 Sep 2008 15:00:16 -0700 (PDT) Subject: Milenko Kindl rtegdgd References: Message-ID: <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> On 21 sep, 19:48, yuma wrote: > Milenko Kindl > Banja Luka > Banjaluka > Bihac Well, that's not C isn't it, more like Snobol or RPG/2 From jamesd at echeque.com Wed Sep 10 16:53:13 2008 From: jamesd at echeque.com (James A. Donald) Date: Thu, 11 Sep 2008 06:53:13 +1000 Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> Message-ID: <4pcgc495c6ml60a09fh3gc8e6t1akmlmin@4ax.com> James A. Donald > > Horrible installs are a chronic problem of GUI programs driven by > > interpreted languages ?Installing visual basic programs that worked on > > one Windows machine to work on a very slightly different windows > > machine was also a nightmare. > > > > I have not attempted to create installable wxPython windows, but > > generally, "run anywhere" will bite you. ?Still looking for a good > > solution to "run anywhere". Mike Driscoll > I haven't had much trouble getting wxPython applications to run in > Windows XP and Ubuntu Hardy Heron. Did you attempt to create proper install packages that show up in the Linux package managers, and the windows add/remove programs tool? -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From bacondemonstratert at gmail.com Thu Sep 25 17:02:12 2008 From: bacondemonstratert at gmail.com (bacondemonstratert at gmail.com) Date: Thu, 25 Sep 2008 14:02:12 -0700 (PDT) Subject: zootube365 zootube365 com - Free Message-ID: zootube . . . *******CLICK HERE******** http://vids365.cn/zootube ***************************** . . . . . . . . . . . . zootube ?s voice quivered, ?Oh God, baby, zootube cunt is so tight sweetie. This set zootube365 off too, and zootube365 could feel zootube365 climax as zootube365 pussy muscles went wild around my cock. In zootube365 mind, zootube365 was saying, ?Rebecca, don?t worry zootube365 pretty little head, zootube365 intend to marry zootube365 daughter. com observed that the gunman was in the same state of arousal as com was. From fredrik at pythonware.com Thu Sep 11 16:37:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 22:37:54 +0200 Subject: Is len O(n) or O(1) ? In-Reply-To: <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> Message-ID: process wrote: > ok but if len is O(1) then it doesnt matter? compared to > > if not lista: > return [] what doesn't matter? From prologic at shortcircuit.net.au Sun Sep 7 17:34:55 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 07:34:55 +1000 Subject: lacking follow-through In-Reply-To: References: Message-ID: Hi, This is the strangest post I've seen since I've joined this list (only recently). What the ? cheers James On Mon, Sep 8, 2008 at 7:00 AM, castironpi wrote: > I am concerned by the lack of follow-through on some responses to > recent ideas I have described. Do I merely have a wrong understanding > of group policy? Is it a good policy (defined with respect to the > future of Python and the welfare of humans at large) if so? Is there > a serious lack of diligence, or should I merely take more initiative, > and ignore charges of 'pestering'? (Warning, moderately deep outside > social issues on table too.) > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From sturlamolden at yahoo.no Tue Sep 23 14:49:13 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 11:49:13 -0700 (PDT) Subject: Linq to Python References: Message-ID: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> On Sep 23, 4:48?pm, hrishy wrote: > Will LINQ be ported to Python ? No, because Python already has list comprehensions and we don't need the XML buzzword. From metaperl at gmail.com Thu Sep 18 16:08:59 2008 From: metaperl at gmail.com (metaperl.com) Date: Thu, 18 Sep 2008 13:08:59 -0700 (PDT) Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: On Sep 9, 9:23?am, s... at pobox.com wrote: > ? ? >> I really dont care if theexpressionis optimal. So the goal is > ? ? >> something like: > > ? ? >> vowel_regexp = oneOf("a aa i ii u uu".split()) ?# yielding r'(aa|a|uu| > ? ? >> u|ii|i)' > > ? ? >> Is there a public module available for this purpose? > > Check Ka-Ping Yee's rxb module: > > ? ?http://lfw.org/python/ Ok suffers from the possibility of putting shorter match before longer one: def either(*alternatives): options = [] for option in alternatives: options.append(makepat(option).regex) return Pattern('\(' + string.join(options, '|') + '\)') >?Also, check PyPI to see if > someone has already updated rxb for use with re. No one has - http://pypi.python.org/pypi?%3Aaction=search&term=rxb&submit=search no results returned From deets at nospam.web.de Sat Sep 13 03:18:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 13 Sep 2008 09:18:32 +0200 Subject: question about python In-Reply-To: References: Message-ID: <6j17q8F107jbU1@mid.uni-berlin.de> fishfin schrieb: > I was working through a tutorial about how to write a server using > python (the url is bellow). I am sure that the server is working to > some degree because when the server is running localhost:8080 just > keeps trying to load until it times out. I would like to know how to > send information through the server to my browser? > > I was working through this tutorial: > http://python.about.com/od/networkingwithpython/ss/PythonWebServer.htm > > > and my final code is like this: > > import socket > > host = '' > port = 8080 > > c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > > c.bind((host, port)) > > c.listen(1) > > while 1: > csock, caddr = c.accept() > cfile = csock.makefile('rw', 0) > > line = cfile.readline().strip() > > cfile.write('HTTP/1.0 200 OK\n\n') > cfile.write('Welcome %s!' % > (str(caddr))) > cfile.write('

Follow the link...

') > cfile.write('All the server needs to do is ') > cfile.write('to deliver the text to the socket. ') > cfile.write('It delivers the HTML code for a link, ') > cfile.write('and the web browser converts it.



') > cfile.write('
Click me!
') > cfile.write('

The wording of your request was: "%s"' %(line)) > cfile.write('') > > cfile.close() > csock.close() Do yourself a favor and look into the various python webframeworks such as TurboGears, Django and what not. Or at least into the module SimpleHTTPServer. Diez From geoff.bache at jeppesen.com Thu Sep 11 07:43:26 2008 From: geoff.bache at jeppesen.com (geoffbache) Date: Thu, 11 Sep 2008 04:43:26 -0700 (PDT) Subject: Persuading ConfigParser to give me the section elements in the same order as the file References: <4566f721-028d-4079-90d8-7818d69d18b3@34g2000hsh.googlegroups.com> Message-ID: <842698d5-ee63-4008-b1bb-df878312325c@c58g2000hsc.googlegroups.com> Hi Matt, > Have a look at this:http://www.python.org/dev/peps/pep-0372/ > Thanks, that was very useful. Good to know these things are being considered. > Looking at the config parser module, it looks like there are only a > couple of places where {} is used. I would create a mixin class to > replace the offending methods. That should work because it looks like > you only have to replace "__init__" and "add_section". So... > > class OrderedConfigParserMixin: > ? ? def __init__(self, defaults=None): > ? ? ? ? self._sections = ndict.seqdict() > ? ? ? ? self._defaults = ndict.seqdict() > ? ? ? ? if defaults: > ? ? ? ? ? ? for key, value in defaults.items(): > ? ? ? ? ? ? ? ? self._defaults[self.optionxform(key)] = value > > ? ? def add_section(self, section): > ? ? ? ? """Create a new section in the configuration. > > ? ? ? ? Raise DuplicateSectionError if a section by the specified name > ? ? ? ? already exists. > ? ? ? ? """ > ? ? ? ? if section in self._sections: > ? ? ? ? ? ? raise DuplicateSectionError(section) > ? ? ? ? self._sections[section] = ndict.seqdict() > > # Then you can use this to create your own ordered config parsers. > Note that > # multiple inheritance in python uses a breadth first search. If you > want > # the methods on your mixin to get called instead of the methods on > the > # original class you must include the mixin first. > > from ConfigParser import RawConfigParser, ConfigParser, > SafeConfigParser > > class OrderedRawConfigParser(OrderedConfigParserMixin, > RawConfigParser): > ? ? pass > > class OrderedConfigParser(OrderedConfigParserMixin, ConfigParser): > ? ? pass > > class OrderedSafeConfigParser(OrderedConfigParserMixin, > SafeConfigParser): > ? ? pass > > I don't know if this is the _best_ approach, but it is certainly much > preferred over monkey patching the built-ins module. Note that I > haven't tested any of the above code. Yes, I tried this first. But actually you missed the main place where dictionaries are created, which is the monster method _read, the line being cursect = {'__name__': sectname} I thought by the time I'd copied that whole method just to edit that line I may as well just copy the whole file and forget the inheritance :) btw, the PEP you pointed me at indicated ConfigParser will take a dict_type argument for exactly this purpose in Python 2.6, so I look forward to when I can use that instead... Regards, Geoff From king.geek22 at gmail.com Mon Sep 1 11:57:12 2008 From: king.geek22 at gmail.com (king.geek22 at gmail.com) Date: Mon, 1 Sep 2008 08:57:12 -0700 (PDT) Subject: FHA Refinance Loan Message-ID: On October 1, 2008, new FHA Refinance Loan Guidelines will go into effect as part of The Housing and Economic Recovery Act of 2008. This new FHA Mortgage program is designed to help thousands of homeowners who are at risk of foreclosure in their curent conventional or sub- prime home loans. The details of The ???HOPE for Homeowners Act of 2008??? are as follows: 1. Eligible Borrowers Only owner-occupants who are unable to afford their mortgage payments are eligible for the program. No investors or investor properties will qualify. Homeowners must certify, under penalty of law, that they have not intentionally defaulted on their loan to qualify for the program and must have a mortgage debt-to-income ratio greater than 31% as of March 1, 2008. Lenders must document and verify borrowers??? income with the IRS. 2. Home Equity & Appreciation Sharing In order to avoid a windfall to the borrower created by the new 90% loan-to-value FHA-insured mortgage, the borrower must share the newly- created equity and future appreciation equally with FHA. This obligation will continue until the borrower sells the home or refinances the FHA-insured mortgage. Moreover, the homeowner???s access to the newly created equity will be phased-in over a 5 year period. The borrower agrees to repay the following share of any home equity appreciation with the FHA when the home is sold or refinanced again; A. 100% of any equity earned is paid to the government FHA if the home sells or the borrower refinances within 1 year. B. 90% of any equity earned is paid to the FHA if the home sells or the borrower refinances within 2 years. C. 80% of any positive equity earned is paid to the FHA if the home sells or the borrower refinances within 3 years. D. 70% of any positive equity earned is paid to the FHA if the home sells or the borrower refinances within 4 years. E. 60% of any positive equity earned is paid to the FHA if the home sells or the borrower refinances within 5 years. F. 50% of any positive equity earned is paid to the FHA if the home sells or the borrower refinances after 5 years. Note: The FHA requires a 3% Exit Fee of the Mortgage Principal Balance when the borrower sells or refinances the home again. 3. Other Requirements Existing Subordinate Liens Before participating in this program, all subordinate liens (such as second loans, home equity loans, etc.) must be extinguished. This will have to be done through negotiation with the first lien holder. Mortgage Insurance and Other Fees The Up Front FHA Mortgage Insurance Premium that is required on all FHA Refinance Loans will change as part The Housing and Economic Recovery Act of 2008. The Monthly MI Rates have also been updated. The following FHA MI rates will begin on October 1, 2008 and will be effective for 12 months; FHA Up Front MIP - Required on all FHA Loans (Can be financed into loan amount). 1.75% - Normal FHA 203(b) Refinance 1.5% - FHA Streamlined Refinance 3.0% - FHASecure (Refinance for high risk borrowers who are already delinquent on current mortgage) Monthly MI ??????" Multiply the loan amount by the figure below and then divide by 12. The result is your Monthly Mortgage Insurance. 30 Year Note 0.55% - Refinance greater than 90% of the home???s LTV. 0.50% - Refinance less than or equal to 90% of the home???s LTV. 15 Year Note 0.25% - Refinance greater than 90% of the home???s LTV. Monthly MI is not required on an 15 Year FHA Refinance Loan with an LTV of 90% or less. The FHA Refinance Loan Process Each new loan will be originated and underwritten on a case-by-case basis. To get approved, your income statements, bank accounts, credit scores and work history will be examined. A new appraisal must be performed on your home to determine its current value. If doesnt have positive equity, then you must contact your current lender and negotiate with them to reduce (write down) your current mortgage to 90% of its current appraised value. If your current lender agrees to the write down, then you will be able to proceed with the FHA refinance. www.my-quickloans.com From tjreedy at udel.edu Mon Sep 1 14:57:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 14:57:09 -0400 Subject: Command lime code In-Reply-To: References: Message-ID: Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Okay, I'll take I wild guess: By "command lime code" you did not refer > to the algorithmic domination of citrus fruit, but rather to that window > with the tiny blinking cursor and loads of text in white on black. Also > by 'chdir' you probably mean the MS DOS equivalent to UNIX 'cd' (which > AFAIK also works on MS DOS). So Googling for "MS DOS Commands" might be > a good idea and yield, amongst others, this result: The os module also has an os-independent chdir() function. From tino at wildenhain.de Mon Sep 1 00:45:56 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 01 Sep 2008 06:45:56 +0200 Subject: parsing "&A" in a string.. In-Reply-To: References: Message-ID: <48BB7384.2000104@wildenhain.de> Tim Roberts wrote: > "bruce" wrote: >> it's the beautifulsoup() that's taking the "&E" and giving the "&E;"... > > Right, as it should. "A&E" is not valid HTML, and beautifulsoup expects > valid HTML. > > This can be difficult to fix in the general case, because your page might > already contain "&". If it is possible that some of them might be > wrong while some are right, you can do something like: > > s = s.replace( '&', '&' ).replace( '&', '&' ) Yeah, but what about ä and friend then? As you said, its not really easy to fix. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From bj_666 at gmx.net Wed Sep 24 00:21:10 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Sep 2008 04:21:10 GMT Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> Message-ID: <6jtthmF50fj6U1@mid.uni-berlin.de> On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote: >> > This seems to break the rule that if A is equal to B and B is equal >> > to C then A is equal to C. >> >> I don't see why transitivity should apply to Python objects in general. > > Well, for numbers it surely would be a nice touch, wouldn't it. May be > the reason for Decimal to accept float arguments is that irrational > numbers or very long rational numbers cannot be converted to a Decimal > without rounding error, and Decimal doesn't want any part of it. Seems > pointless to me, though. Is 0.1 a very long number? Would you expect ``0.1 == Decimal('0.1')`` to be `True` or `False` given that 0.1 actually is In [98]: '%.50f' % 0.1 Out[98]: '0.10000000000000000555111512312578270211815834045410' ? Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Fri Sep 5 16:58:00 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 13:58:00 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> Message-ID: On Sep 6, 2:45?am, bearophileH... at lycos.com wrote: > Michael Palmer: > > > why can't it be tuple already? > > Because if the input list L has tuples and lists, they end having the > same hash value: Perhaps the OP shouldn't be constructing the hash of a mutable object. Perhaps he would be grateful if his hash function raised an exception instead of laboriously masking the problem. > > >>> L = [[1,2,3], (1,2,3)] > >>> hash(tuple(L[0])), hash(tuple(L[1])) > > (-378539185, -378539185) > > But it's a not much common situation, and few hash collision pairs > can't damage much, so I agree with you that my assert was useless. > This may solve that problem anyway: > > hash(type(L)) ^ hash(tuple(L)) Consider this: >>> hash(123) == hash(123.0) == hash(123L) True Perhaps the OP (who hasn't stated what he is going to use the hash results for) needs to use only the values in his hash, and would be if not highly delighted then at least blithely unconcerned if it turned out that [1, 2, 3] and (1, 2, 3) had the same hash. > > Generally a good hashing functions uses all the input information. If > you use tuple() you ignore part of the input information, that is the > type of L. So xor-ing hash(type(L)) you use that information too. > Try "uses all the information that is relevant to the task". Your alternative solution using reduce and xor may have suboptimal characteristics ... xor_hash((1, 2, 3)) == xor_hash((1, 3, 2)) == xor_hash((2, 1, 3)) etc. While the docs for __hash__ say "it is advised to somehow mix together (e.g., using exclusive or) the hash values for the components of the object", in practice "somehow" is rather more elaborate than xor. Have a look at the tuplehash function in .../Objects/tupleobject.c. If the order of the values in the tuple doesn't matter, then perhaps the OP really should be using a set (or a bag). Cheers, John From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 30 05:54:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 30 Sep 2008 11:54:42 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: <48e1f745$0$13447$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message , James > Mills wrote: > >> On Fri, Sep 26, 2008 at 8:20 AM, Lawrence D'Oliveiro >> wrote: >> >>> Object orientation IS procedural. >> Correction: OOP is Imperative. > > No, "procedural". Nope, "imperative" !-) > The functional unit is called an "expression", the encapsulation of which is > called a "function". Hence "functional". > > Similarly, the procedural unit is commonly called a "statement", the > encapsulation of which is a "procedure", not an "imperator". > Hence "procedural". "imperative" means that the computation is done through statements that modify the program's state. "procedural" means that these statements are organized in "procedures", that group a serie of statements. OO is based on objects (that carry and manage internal state) and messages. A message can happen to trigger a serie of statements that modifies a program state, so you could say (and this wouldn't be totally false) that an OO method can be seen as a procedure (or at least some methods...), but the whole program's organization is still not the same as one seen in procedural programming. IOW, it's more a matter of how you design / organize your (otherwise imperative) program than anything else. From gagsl-py2 at yahoo.com.ar Sun Sep 7 16:13:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 17:13:11 -0300 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: En Sun, 07 Sep 2008 14:30:09 -0300, Mensanator escribi?: > Actualy, I already get the behaviour I want. sum([1,None]) > throws an exception. I don't see why sum([]) doesn't throw > an exception also (I understand that behaviour is by design, > I'm merely pointing out that the design doesn't cover every > situation). [...] > Exactly. That's why I would prefer sum([]) to raise an > exception instead of giving a false positive. The built in behavior can't be good for every usage. Nobody prevents you from defining yoru own function tailored to your own specs, like this: def strict_sum(items): items = iter(items) try: first = items.next() except StopIteration: raise ValueError, "strict_sum with empty argument" return sum(items, first) Tweak as needed. Based on other posts I believe your Python skills are enough to write it on your own, so I don't see why you're complaining so hard about the current behavior. -- Gabriel Genellina From pavlovevidence at gmail.com Wed Sep 24 05:12:24 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 24 Sep 2008 02:12:24 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <5a09432f-0197-4cb9-8eba-c1ad66ecb387@d77g2000hsb.googlegroups.com> On Sep 23, 4:25?pm, Drake wrote: > The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), I'm kind of curious what your library is for. Is it something where exiting the app be the only appropriate action for an IO error? Even if it is, I will echo other people's advice: a library should never call exit, at least not by default. For your imagined use it might make sense to exit upon any failure, but other people using the library might not want to do that. For that matter, a library should never print error or status messages. Messages should either be sent to the caller somehow, or handled using the logging facility. Carl Banks From Afro.Systems at gmail.com Wed Sep 10 14:40:22 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Wed, 10 Sep 2008 11:40:22 -0700 (PDT) Subject: Simple UDP server Message-ID: <64d4d302-1715-4066-8542-4641fb6e3f52@t54g2000hsg.googlegroups.com> I am looking for the right way to write a small and simple UDP server. I am wondering between Forking, Threading (found at SocketServer.py) and the one describes at the snippet below. Can you tell me the advantages and disadvantages of each Would the one below will be capable of holding 30 concurrent connections? I have no intention of using Twisted or alike since I am looking for making it as lightweight as possible Thanks in advance, Tzury Bar Yochay # begin of snippet from socket import * # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(('',50008)) while 1: data,addr = UDPSock.recvfrom(4*1024) if not data: print "No data." break else: print 'from:', addr, ' data:', data UDPSock.close() From michel at nospam.please Mon Sep 15 15:46:47 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:46:47 +0200 Subject: Python Nautilus script In-Reply-To: <6j7rjpF1rp5lU1@mid.uni-berlin.de> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> Message-ID: <48cebba7$0$2862$ba620e4c@news.skynet.be> Diez B. Roggisch a ?crit : > There shouldn't be a difference between a shell-script and a > python-script. Environment-variables are a unix-process-thing, and thus > the rules that govern them apply to *all* processes - the shell is one > of these, there is nothing special to it. > > If the shell-script gets the variable, the python-script will as well. Yes, that's what I thought too but try this: open a terminal and type $ echo $HOSTNAME you will get the name of your computer. Now try this instead: $ python >>> import os >>> os.environ['HOSTNAME'] Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ raise KeyError(key) KeyError: 'HOSTNAME' >>> It appears that's because HOSTNAME is not exported. But in the case of Nautilus script, how to workaround this issue? -- Michel Leunen http://linux.leunen.com From cyberco at gmail.com Wed Sep 3 17:52:07 2008 From: cyberco at gmail.com (Berco Beute) Date: Wed, 3 Sep 2008 14:52:07 -0700 (PDT) Subject: Python on JavaScript VM's (such as V8)? Message-ID: <1926ef1e-2c5e-4ef6-8a33-b360b02520a7@b38g2000prf.googlegroups.com> I wonder what it would take to implement Python in JavaScript so it can run on those fancy new JavaScript VM's such as Chrome's V8 or Firefox' tracemonkey. Much the same as Python implementations in C# (IronPython) and Java (Jython). It would certainly bring back the fun in web application development. Is there anything done in that direction? 2B From clp at rebertia.com Fri Sep 26 14:08:29 2008 From: clp at rebertia.com (Chris Rebert) Date: Fri, 26 Sep 2008 11:08:29 -0700 Subject: Fastest way to max() list In-Reply-To: References: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> Message-ID: <47c890dc0809261108k356a109va88b675e037246be@mail.gmail.com> On Fri, Sep 26, 2008 at 7:22 AM, David Di Biase wrote: > Hi Chris, > > Yeah I hear you on point A. but this the specification I was given, so I > have to follow it unfortunately. I've also been restricted and not allowed > to use any other packages. I was using NumPy earlier (should have mentioned > that) but I was wondering if there was a simpler way. Is NumPy technically > even faster than just iterating and modifying the list directly? > > Also if I'm creating an array then making it, Uh, this part of your sentence doesn't quite make sense... > why not just do a temporary > sort and capture the first and last values? Is this method you've provided > supposed to be faster? Well, unless you're going to use the rest of the sorted values at some point in your program and since you have a large quantity of data, yes, my way ought to be faster. Sorting the list is O(N*log(N)) while running max and min over the list is only O(N). Regards, Chris > > Dave > > On Fri, Sep 26, 2008 at 12:42 AM, Chris Rebert wrote: >> >> On Thu, Sep 25, 2008 at 8:57 PM, David Di Biase >> wrote: >> > I have a list with about 1000-1500 sub-lists which look like so: >> > list[-0.28817955213290786, 3.6693631467403929, 'H', 31.31225233035784]] >> > >> > The first and second values are Angstrom units specifying the location >> > of a >> > particle. What I'd like to do is determine the distance between the >> > smallest >> > and largest value in the arrays first position 0. I tried reading the >> > manual >> > for this but I don't see how it applies key or any of those other >> > commands >> > to the function. I could easily write a sort to do this and capture the >> > first and last spots, but why do that when I can use max and min (if I >> > can >> > actually do that...). >> >> A. You should probably be using objects rather than arrays to >> represent your datapoints, so that they're more structured and it's >> more apparent what the values mean. >> >> B. Assuming by "distance" you meant "difference" and/or that the >> distance is only in 1 dimension: >> >> from operator import itemgetter >> firsts = map(itemgetter(0), main_list) >> distance = max(firsts) - min(firsts) >> >> > >> > So you wonderful Python gods, lay some knowledge on me. please? lol... >> > >> > while I'm at it, is there a way to modify an entire list without having >> > to >> > produce a whole new one? For example now say I want to modify list[0] >> > and >> > multiply it by some value. From what I understand previous version of >> > Python >> > allowed lists to be multiplied like matrices...now apparently it just >> > replicates the list. :-/ shucks... >> >> You just have to apply the transform to each list element individually >> (also, you might consider using NumPy [http://numpy.scipy.org/] if >> you're doing a lot of matrix manipulation): >> >> for lst in main_list: >> lst[0] *= some_value >> >> Regards, >> Chris >> >> > >> > The first question would be useful to know, but the second question I do >> > quite a bit of and the "best practice" would be really great to know! >> > >> > Thanks in advanced! >> > >> > -- >> > http://mail.python.org/mailman/listinfo/python-list >> > >> -- >> Follow the path of the Iguana... >> http://rebertia.com > > -- Follow the path of the Iguana... http://rebertia.com From ldo at geek-central.gen.new_zealand Mon Sep 29 02:53:06 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 19:53:06 +1300 Subject: how to make smtplib.SMTP('localhost') work on window xp References: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Message-ID: In message <56f2097a-5129-4d1a-be82-a73e2874ba04 at p31g2000prf.googlegroups.com>, zxo102 wrote: > SMTPServerDisconnected: Connection unexpectedly closed Does the SMTP server on localhost mention anything about the connection attempt in its log? If you telnet/netcat to port 25 on localhost, does anything interesting happen? From jcd at sdf.lonestar.org Wed Sep 3 12:00:55 2008 From: jcd at sdf.lonestar.org (Cliff) Date: Wed, 3 Sep 2008 09:00:55 -0700 (PDT) Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> <878wubp5mz.fsf@benfinney.id.au> Message-ID: <69f945f1-d924-4a75-8830-7f308641ac65@34g2000hsh.googlegroups.com> On Sep 2, 12:34?am, Fredrik Lundh wrote: > Ben Finney wrote: > > I would argue that the precedent, already within Python, for using a > > space to separate pieces of a string literal, is more important than > > precedents from other programming languages. > > that precedent also tells us that the whitespace approach is a common > source of errors. ?taking an approach that's known to be error-prone and > applying it to more cases isn't necessarily a great way to build a > better language. > > Also a source of mental complexity. The two proposals (whitespace vs. underscores) are not just a question of what character to use, it's a question of whether to create an integer (and possibly other numeric type) literal that allows delimiters, or to allow separate literals to be concatenated. In the second case, which of the following would be proper syntax? 0b1001 0110 0b1001 0b0110 In the first case, the second literal, on its own, is an octal literal, but we expect it to behave as a binary literal. In the second case, we have more consistency with string literals (with which you can do this: "abc" r'''\def''') but we lose the clarity of using the concatenation to make the whole number more readable. On the other hand, 0b1001_0110 has one clear meaning. It is one literal that stands alone. I'm not super thrilled about the look (or keyboard location) of the underscore, but it's better than anything else that is available, and works within a single numeric literal. For this reason I am +0 on the underscore and -1 on the space. From HeinTest at web.de Mon Sep 1 09:25:03 2008 From: HeinTest at web.de (=?ISO-8859-1?Q?Hans_M=FCller?=) Date: Mon, 01 Sep 2008 15:25:03 +0200 Subject: Eleganz way to get rid of \n Message-ID: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Hello, I'm quite often using this construct: for l in open("file", "r"): do something here, l contains the \n or \r\n on windows at the end. I get rid of it this way: for l in open("file", "r"): while l[-1] in "\r\n": l = l[:-1] I find this a little bit clumsy, but it works fine. Has someone a better solution ? Thanks Hans From sturlamolden at yahoo.no Tue Sep 23 14:07:22 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 11:07:22 -0700 (PDT) Subject: Python is slow? References: Message-ID: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> On Sep 23, 3:44?pm, Robert Singer wrote: > Well, python is not a number crunching language. However much we would > like it to be (we would ? :-). > No scripting language is. Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? > Before resorting to rewriting the problem try psyco. It speeds up > things sometimes. I did, Psyco did not help. > Also, (I'm not that familiar with python yet, so I don't know how to > do it in python), try finding the bottlenecks of your calculation. I did use a profiler, there is no particular single bottle-neck. > Well, personally, I try to combine fortran (being a fortran programmer > by trade) with python Good compilers are too expensive, and gfortran is not good enough yet. From tjreedy at udel.edu Sat Sep 6 13:59:53 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 06 Sep 2008 13:59:53 -0400 Subject: why is self not passed to id()? In-Reply-To: References: Message-ID: <48C2C519.7030400@udel.edu> Ruediger wrote: > I found following solution to the problem. > > Instead of assigning id directly to __hash__ it has to be wrapped with an > instancemethod object. It is somehow strange that this doesn't happen > automatically and it is also strange that instancemethod isn't exposed in > the type module. There are several internal implementation types not exposed in types because they are subject to change from version to version In 3.0, your code does not work. Instancemethod may to added to 3.0 or 3.1 as a built-in function. > ****************************************************************** > > class foo(list): > __hash__ = lambda x: id(x) > type > instancemethod = type(foo.__hash__) In 2.x, this gives you 'instancemethod'. In 3.0, you get 'function' as unbound methods are no longer wrapped when the underlying function is a 'function' (resulting from def or lambda abbreviation). > class bar(list): > pass > bar.__hash__ = instancemethod(id, None, bar) Calling a 'function' with those parameters will not work. Did you miss the following from my previous response? "There *is* a third alternative, which works in this case, and which should be closer in speed to id. I will leave you to do a speed test. >>> class bang(list): __hash__ = object.__hash__ >>> s=set() >>> s.add(bang()) >>> s {[]} __eq__ = object.__eq__ should also work instead of the Python implementation I gave in my response to another response." I would expect the already-wrapped id should work in 2.x also. Terry Jan Reedy From mcfletch at vrplumber.com Sun Sep 21 14:19:03 2008 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sun, 21 Sep 2008 14:19:03 -0400 Subject: Some questions about PyOpenGL and wxPython In-Reply-To: <1222017270.7824.3.camel@generator> References: <1222017270.7824.3.camel@generator> Message-ID: <48D69017.50205@vrplumber.com> Clay Hobbs wrote: > I am making a program with wxPython that renders objects in 3D using > PyOpenGL, and I am having some problems. For one thing, I forgot how to > make a double-buffered hardware surface. http://bazaar.launchpad.net/~mcfletch/openglcontext/trunk/annotate/1?file_id=wxcontext.py-20080920224554-ehwlv3u6uc6sb6e2-55 See method wxFlagsFromDefinition, particularly glcanvas.WX_GL_DOUBLEBUFFER > For another thing, > glColor(1.0, 0.0, 0.0) just before the rendering doesn't make the object > red. Please help, I'm a total noob to OpenGL. > Would have to see what you're doing to know what's wrong there. glColor should be working. HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From rsarpi at gmail.com Fri Sep 26 22:01:44 2008 From: rsarpi at gmail.com (icarus) Date: Fri, 26 Sep 2008 19:01:44 -0700 (PDT) Subject: getting global variables from dictionary Message-ID: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> global_vars.py has the global variables set_var.py changes one of the values on the global variables (don't close it or terminate) get_var.py retrieves the recently value changed (triggered right after set_var.py above) Problem: get_var.py retrieves the old value, the built-in one but not the recently changed value in set_var.py. What am I doing wrong? ----global_vars.py--- #!/usr/bin/python class Variables : def __init__(self) : self.var_dict = {"username": "original username"} ---set_var.py --- #!/usr/bin/python import time import global_vars global_vars.Variables().var_dict["username"] = "new username" time.sleep(10) #give enough time to trigger get_var.py ---get_var.py --- #!/usr/bin/python import global_vars print global_vars.Variables().var_dict.get("username") From hugo at hugo.com Sun Sep 7 09:32:56 2008 From: hugo at hugo.com (hugo) Date: Sun, 7 Sep 2008 15:32:56 +0200 Subject: nizoral ketoconazol in Laverlochere ketoconazole side effects generic nizoral medication nizoral pastile loprox Message-ID: nizoral ketoconazol in Laverlochere ketoconazole side effects generic nizoral medication nizoral pastile loprox + + + BUY CHEAP NIZORAL - ORDER NIZORAL ONLINE (ALL CARDS ACCEPTED !!!) http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php http://www.www-pharmacy-online.com/nizoral.php + + nizoral conditioner nizoral tablet in Saint Mathias Sur Richelieu generic nizoral 5 nizoral conditioner www viapro com nizoral loprox 200mg in Englehart nizoral 2 cream cheap nizoral medication discountdrugs com generic nizoral dose nizoral not in St-Joseph-de-Beauce nizoral package brand nizoral 2 shampoo in Drumbo generic nizoral 5 buy nizoral review in Meaford hair loss nizoral shampoo cheap nizoral forum in Noel selsun nizoral shampoo and hair loss in St-Georges-de-Beauce http://ibm-news.for-um.de/showthread.php?t=12183 - find nizoral buy nizoral work in St-Georges-de-Cacouna http://ibm-news.for-um.de/showthread.php?t=11648 - cheap nizoral ingredients nizoral package in Coeud'Alene http://ibm-news.for-um.de/showthread.php?t=15383 - cheap nizoral over nizoral ointment in Melrose http://asiadata.ru/areal/viewtopic.php?t=3070 - ketokonazole nizoral pastile in Bromont http://ibm-news.for-um.de/showthread.php?t=10336 - nizoral hair prescription in Placentia http://ibm-news.for-um.de/showthread.php?t=14439 - cheap nizoral ointment nizoral cream side in Charette http://ibm-news.for-um.de/showthread.php?t=9992 - buy nizoral with cheap nizoral ointment in Woodstock http://ibm-news.for-um.de/showthread.php?t=11198 - nizoral shampoo and hair loss cheap nizoral how in Saint Sulpice http://ibm-news.for-um.de/showthread.php?t=14430 - sell nizoral buy nizoral tablets in Eddystone http://draconian.com/dragon-forum/showthread.php?t=17672 - nizoral over the cheap nizoral hydrocortisone in PembrokPines http://ibm-news.for-um.de/showthread.php?t=11650 - nizoral shampoo side versicolor nizoral shampoo in Coral Harbour http://ibm-news.for-um.de/showthread.php?t=11798 - nizoral 1 buy ketoconazole in Riverside http://ibm-news.for-um.de/showthread.php?t=9581 - buy nizoral scalp ketaconazole in Portage la Prairie http://ibm-news.for-um.de/showthread.php?t=9627 - nizoral candida nizoral en in Birtle From fredrik at pythonware.com Thu Sep 4 13:53:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 19:53:32 +0200 Subject: Python and Cyrillic characters in regular expression In-Reply-To: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> References: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> Message-ID: phasma wrote: > Hi, I'm trying extract all alphabetic characters from string. > > reg = re.compile('(?u)([\w\s]+)', re.UNICODE) > buf = re.match(string) > > But it's doesn't work. If string starts from Cyrillic character, all > works fine. But if string starts from Latin character, match returns > only Latin characters. can you provide a few sample strings that show this behaviour? From kyosohma at gmail.com Wed Sep 10 13:22:45 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 10 Sep 2008 10:22:45 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> Message-ID: On Sep 10, 6:48?am, James A. Donald wrote: > On Tue, 9 Sep 2008 14:35:13 -0700 (PDT), icarus > wrote: > > > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > > That did it. > > > one more question... > > > how do I create a pythonw standalone executable that works on w32, > > linux, mac, etc..? > > I have noticed that when applications are written in Python with the > GUI created by PyGTK, it seems that to install the application on each > slightly different version of unix is a fairly major task - although > the creators of PyGTK proudly say that the code will run anywhere, it > definitely will not install anywhere - the code will only run on a > slightly different system after a massive and major rewrite of the > install for that target system. > > Horrible installs are a chronic problem GUI programs driven by > interpreted languages ?Installing visual basic programs that worked on > one Windows machine to work on a very slightly different windows > machine was also a nightmare. > > I have not attempted to create installable wxPython windows, but > generally, "run anywhere" will bite you. ?Still looking for a good > solution to "run anywhere". > > -- > ? ---------------------- > We have the right to defend ourselves and our property, because > of the kind of animals that we are. True law derives from this > right, not from the arbitrary power of the omnipotent state. > > http://www.jim.com/? ? ?James A. Donald I haven't had much trouble getting wxPython applications to run in Windows XP and Ubuntu Hardy Heron. Of course, my GUIs aren't extremely complex, but I did make use of Hammond's PyWin32 package and had to wrap those in Platform aware conditional statements. Plus wx was pretty easy to install in Ubuntu, so that was cool. I can't really comment on other toolkits though. Mike From half.italian at gmail.com Wed Sep 24 22:24:24 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 24 Sep 2008 19:24:24 -0700 (PDT) Subject: empty csv file attachments References: <200563c8-a4d1-45db-aaa1-63f885851b76@s50g2000hsb.googlegroups.com> Message-ID: <0df6db24-b2eb-4b61-8a1f-8f74c91409c5@w39g2000prb.googlegroups.com> On Sep 24, 1:17?pm, Bobby Roberts wrote: > hi group. > > I'm new to python but a veteran at programming. ?This one has me > stumped. ?I have a simple contact form which the user fills out. ?The > email is sent to the site user as well and it is delivered with the > content in the body of the email as well in nice order. ?I have > modified my code to also send the content as a csv attachment. ?On the > server, the file is perfectly generated with content. ?The attachment, > however, is completely blank. ?Any ideas what that could be? ?My code > snippet is shown below: > > ? ? ? if int(attachmenttype)==2 or int(attachmenttype)==3: > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? if field=='last_name': > ? ? ? ? ? ? myfilename=ctx.request.field_value(field)+'.txt' > ? ? ? ? if myfilename=='': > ? ? ? ? ? myfilename='tempfile.txt' > ? ? ? ? mypath= mynewfilepath + '/' + myfilename > ? ? ? ? f=open(mypath, 'w') > ? ? ? ? mynewstring='' > ? ? ? ? counter=0 > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? if field != 'inquiry_required': > ? ? ? ? ? ? mynewstring=mynewstring + field +',' > ? ? ? ? if mynewstring[-1]==',': > ? ? ? ? ? mynewstring=mynewstring[0:len(mynewstring)-1] > ? ? ? ? f.write(mynewstring) > ? ? ? ? f.write ('\n') > > ? ? ? ? mynewstring='' > ? ? ? ? counter=1 > ? ? ? ? for field in ctx.request.field_names(): > ? ? ? ? ? fielddata=ctx.request.field_value(field) > ? ? ? ? ? if counter==1: > ? ? ? ? ? ? dummydata=0 > ? ? ? ? ? else: > ? ? ? ? ? ? mynewstring=mynewstring + '"' + fielddata.replace('"','') > + '",' > ? ? ? ? ? counter = counter + 1 > ? ? ? ? if mynewstring[-1]==',': > ? ? ? ? ? mynewstring=mynewstring[0:len(mynewstring)-1] > ? ? ? ? f.write(mynewstring) > ? ? ? ? f.write('\n') > ? ? ? ? f.close > ? ? ? ? attachments.append('/'.join((ctx.request.library, > myfilename))) > > ?[snip... sends email just after this] > > any ideas? I would sprinkle some print statements in there to narrow it down... ~Sean From simon at brunningonline.net Fri Sep 12 05:21:11 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 12 Sep 2008 10:21:11 +0100 Subject: handling uncaught exceptions with pdb? In-Reply-To: <7xmyifpt68.fsf@ruckus.brouhaha.com> References: <7xmyifpt68.fsf@ruckus.brouhaha.com> Message-ID: <8c7f10c60809120221j2266f84cq3ea8a8b462508b69@mail.gmail.com> 2008/9/10 Paul Rubin <"http://phr.cx"@nospam.invalid>: > I think I've asked about this before, but is there a way to set up > Python to handle uncaught exceptions with pdb? http://code.activestate.com/recipes/65287/ -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From martin at v.loewis.de Wed Sep 17 19:00:19 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 18 Sep 2008 01:00:19 +0200 Subject: PYPI, some troubles In-Reply-To: References: Message-ID: <48d18c03$0$2322$9b622d9e@news.freenet.de> > 1. when I commit a new release to PYPI, I can use stored data (by my > browser: Name, package summary, keywords etc), but in the last line > (classification) I had to chose all those lines from the very > beginning, moreover, if I click at one of them without pressing "CTRL" > all my choices drops & I have to type it from the very beginning (I > use Mozilla Firefox 3.0 but I don't think it's the matter). Then I recommend not to use the browser to commit the new releases. Instead, arrange for your setup.py to contain all the relevant data, and use python setup.py register to add the new release. > 2. Another issue: I have attached my source code (openopt0.19.tar.bz2 > file), now I can see it in "files for openopt 0.19" section (http:// > pypi.python.org/pypi) but easy_install can't find the package: Try calling the file openopt-0.19.tar.bz2. If that doesn't help, contact the setuptools mailing lists. Regards, Martin From dblubaugh at belcan.com Mon Sep 29 15:44:10 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 15:44:10 -0400 Subject: PYTHON WORKING WITH PERL ?? In-Reply-To: <20080929133153.fc745f9c.darcy@druid.net> References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> <20080929133153.fc745f9c.darcy@druid.net> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D905A@AWMAIL04.belcan.com> Sir, You are absolutely correct. I was praying to G_d I did not have to slaughter my project's source code in this manner. However, like life itself, I was given legacy source code (i.e. someone else errors to fix) in Perl. However, I have just found out that there is a way to import the Perl interpreter within Python!!! I now believe I can utilize python as the main platform to develop the project upon !! Thanks, David -----Original Message----- From: D'Arcy J.M. Cain [mailto:darcy at druid.net] Sent: Monday, September 29, 2008 1:32 PM To: Blubaugh, David A. Cc: python-list at python.org Subject: Re: PYTHON WORKING WITH PERL ?? On Mon, 29 Sep 2008 13:16:14 -0400 "Blubaugh, David A." wrote: > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? Such as > utilizing python for internet programming and then utilize perl for > text processing and systems programming? Is this even feasible??? I don't see why not but I also question if it is a good idea. Once you have all your objects and low level methods written in Python it just makes sense to re-use them rather than trying to duplicate the functionality in another language. Of course, sometimes we don't have control over our entire environment so yes, you can mix them if you have to. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From yellowblueyellow at gmail.com Thu Sep 11 18:21:02 2008 From: yellowblueyellow at gmail.com (yellowblueyellow at gmail.com) Date: Thu, 11 Sep 2008 15:21:02 -0700 (PDT) Subject: SSH using PEXPECT References: Message-ID: <4cc538ef-3b08-404c-b107-ff6605c307a2@t54g2000hsg.googlegroups.com> On Sep 10, 7:01?pm, Sean DiZazzo wrote: > On Sep 10, 6:04?pm, yellowblueyel... at gmail.com wrote: > > > > > Hey , I need toSSHinto a server .. (10.8.42.38) usingpexpectthe > > username is 'admin' and password is 'abc123' so far i have the > > following code > > > importpexpect > > import sys > > import time > > import os > > > foo =pexpect.spawn('sshad... at 10.8.42.38') > > ssh_newKey = 'Are you sure you want to continue connecting' > > > foo.expect = ssh_newKey > > foo.send = 'yes' > > foo.expect = 'password:' > > foo.send = 'abc123' > > > --------------------------------------------------------------------------- ---------------------- > > > does this look right? I am using windows and for reason it wont let me use pexpect even tho I have CYGWIN installed I get the following error Traceback (most recent call last): File "new.py", line 1, in import ssh_session File "C:\Python25\lib\ssh_session.py", line 7, in from pexpect import * File "C:\Python25\lib\site-packages\pexpect.py", line 85, in support it. Pexpect is intended for UNIX-like operating systems.""") ImportError: No module named resource any ideas? Thanks A critical module was not found. Probably this operating system does not support it. Pexpect is intended for UNIX-like operating systems. > > > if not , could someone suggest a way to do this .. > > your help is much appreciated > > https://svn.lal.in2p3.fr/projects/CMT/CMTManagement/utils/ssh_session.py > > I use a modified version of this. ?Simple and effective. > > import ssh_sessionssh= ssh_session.ssh_session(user, host, password) > printssh.ssh("ls -l /tmp") > > Thanks Eric and Nigel! > > ~Sean From aahz at pythoncraft.com Fri Sep 26 20:32:47 2008 From: aahz at pythoncraft.com (Aahz) Date: Fri, 26 Sep 2008 17:32:47 -0700 Subject: PyCon 2009 Call for Proposals Message-ID: <20080927003247.GA12336@panix.com> Call for proposals -- PyCon 2009 -- =============================================================== Want to share your experience and expertise? PyCon 2009 is looking for proposals to fill the formal presentation tracks. The PyCon conference days will be March 27-29, 2009 in Chicago, Illinois, preceded by the tutorial days (March 25-26), and followed by four days of development sprints (March 30-April 2). Previous PyCon conferences have had a broad range of presentations, from reports on academic and commercial projects to tutorials and case studies. We hope to continue that tradition this year. Online proposal submission will open on September 29, 2008. Proposals will be accepted through November 03, with acceptance notifications coming out on December 15. For the detailed call for proposals, please see: We look forward to seeing you in Chicago! -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From adelle at akemi.com.au Sun Sep 14 23:25:27 2008 From: adelle at akemi.com.au (Adelle Hartley) Date: Mon, 15 Sep 2008 13:25:27 +1000 Subject: Good programming style In-Reply-To: References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: <48CDD5A7.8000705@akemi.com.au> Grant Edwards wrote: > When packages as significant as wxPython use naming conventions > other than PEP 8, I find it hard to make a case that the PEP 8 > naming convention is any better than any other. This relates to a question I was thinking about... I'm looking at porting a library that was written for COM and .Net to work as a Python module, and was wondering whether it would be better to stick to the library's current naming convention so that the API is as similar as possible on each platform, or to adopt a "when in Rome..." policy and follow the "most mainstream" naming pattern for each platform/language. Adelle. From jake at vapourforge.com Thu Sep 18 11:42:45 2008 From: jake at vapourforge.com (Jake Anderson) Date: Fri, 19 Sep 2008 01:42:45 +1000 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <48D276F5.6040608@vapourforge.com> psyco might help a fair bit (10x-40x) here ;-> perhaps look at dumping the data into sqlite then pulling it back out. It (or the other databases) are designed for tossing around large lumps of data. Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > > but no improvements. > > Many thanks, Alex > -- > http://mail.python.org/mailman/listinfo/python-list > -- Vapour Forge Jake Anderson Project Manager Mobile: 0412 897 125 Email: jake at vapourforge.com Web Page: www.vapourforge.com Your source for custom IT services -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: vf.gif Type: image/gif Size: 1484 bytes Desc: not available URL: From code at pizzashack.org Mon Sep 22 17:26:51 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 22 Sep 2008 17:26:51 -0400 Subject: test list post Message-ID: <20080922212651.GE26713@dragontoe.org> Sorry for the noise, my recent posts seem to have been eaten by the list management software, as far as I can tell. Just testing if that's still the case. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From mensanator at aol.com Thu Sep 4 13:26:01 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 4 Sep 2008 10:26:01 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: <06d8438f-b1a6-4662-aac7-8e334521107b@s20g2000prd.googlegroups.com> On Sep 4, 11:13?am, "David C. Ullrich" wrote: > In article > <719910b1-3776-4bf2-a0b6-236f3167e... at 25g2000prz.googlegroups.com>, > > > > > > ?Mensanator wrote: > > On Sep 3, 2:18?pm, Laszlo Nagy wrote: > > > bearophileH... at lycos.com wrote: > > > > Empty Python lists [] don't know the type of the items it will > > > > contain, so this sounds strange: > > > > >>>> sum([]) > > > > > 0 > > > > > Because that [] may be an empty sequence of someobject: > > > > You are right in that sum could be used to sum arbitrary objects. > > > However, in 99.99% of the cases, you will be summing numerical values. > > > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > > > is very logical to return zero for empty sequences. > > > No it isn't. Nothing is not 0, check with MS-Access, for instance: > > > Null + 1 returns Null. Any arithmetic expression involving a > > Null evaluates to Null. Adding something to an unknown returns > > an unknown, as it should. > > > It is a logical fallacy to equate unknown with 0. > > Which has nothing to do with the "right" value for an > empty sum. I'm less concerned about the "right" value than a consistent value. I'm fairly certain you can't get 0 from a query that returns no records, so I don't like seeing empty being treated as 0, even if it means that in set theory because databases aren't sets. > If they hear about what you said here in > sci.math they're gonna kick you out They usually don't kick me out, just kick me. > - what do you > imagine the universally accepted value of \sum_{j=1}^0 > is? I can't follow your banter, so I'm not sure what it should be. > > > > > > > For example, the water table elevation in ft above Mean Sea Level > > is WTE = TopOfCasing - DepthToWater. > > > TopOfCasing is usually known and constant (until resurveyed). > > But DepthToWater may or may not exist for a given event (well > > may be covered with fire ants, for example). > > > Now, if you equate Null with 0, then the WTE calculation says > > the water table elevation is flush with the top of the well, > > falsely implying that the site is underwater. > > > And, since this particular site is on the Mississippi River, > > it sometimes IS underwater, but this is NEVER determined by > > water table elevations, which, due to the CORRECT treatment > > of Nulls by Access, never returns FALSE calculations. > > > >>> sum([]) > > 0 > > > is a bug, just as it's a bug in Excel to evaluate blank cells > > as 0. It should return None or throw an exception like sum([None,1]) > > does. > > > > Same way, if we would have a prod() function, it should return one for > > > empty sequences because X*1 = X. The neutral element for this operation > > > is one. > > > > Of course this is not good for summing other types of objects. But how > > > clumsy would it be to use > > > > sum( L +[0] ) > > > > or > > > > if L: > > > value = sum(L) > > > else: > > > value = 0 > > > > instead of sum(L). > > > > Once again, this is what sum() is used for in most cases, so this > > > behavior is the "expected" one. > > > > Another argument to convince you: the sum() function in SQL for empty > > > row sets returns zero in most relational databases. > > > > But of course it could have been implemented in a different way... I > > > believe that there have been excessive discussions about this decision, > > > and the current implementation is very good, if not the best. > > > > Best, > > > > Laszlo > > -- > David C. Ullrich From tino at wildenhain.de Fri Sep 19 03:34:43 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 19 Sep 2008 09:34:43 +0200 Subject: Python newbie In-Reply-To: References: Message-ID: <48D35613.1000403@wildenhain.de> Hi, Mladen Gogala wrote: > I am a Python newbie who decided to see what that Python fuss is all about. > Quite frankly, I am a bit perplexed. After having had few months of > experience with Perl (started in 1994 with Perl v4, and doing it ever > since) , here is what perplexes me: > > perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' > > The equivalent in Python looks like this: > > Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) > [GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a=[1,2,3] >>>> map((lambda x: 2*x),a) > [2, 4, 6] >>>> map((print),a) > File "", line 1 > map((print),a) > ^ > SyntaxError: invalid syntax >>>> for x in a: print x > ... > 1 > 2 > 3 >>>> for x in a: x=2*x > ... >>>> for x in a: print x > ... > 1 > 2 > 3 > > There are several questions: > > 1) Why is the array "a" unchanged after undergoing a transformation with > map? it isn't transformed. You get a new list as result. > 2) Why is it illegal to pass a built-in function "print" to map? because its not a function but a statement. If it was a function you would call it print(x) not print x. > 3) Why is the array "a" unchanged after undergoing an explicit > transformation with the "for" loop? To understand this, python knows immutable objects and mutable. Immutables are strings, tuples , ... and integers. This means the operation above all create a new integer object in memory and assign it to the name x (where you use = ) > 4) Is there an equivalent to \$a (Perl "reference") which would allow me to > decide when a variable is used by value and when by reference? No, python always uses by reference. > PHP also allows changing arrays with "foreach" loop: > #!/usr/local/bin/php > $a=array(1,2,3); > foreach($a as &$x) { $x=$x*2; } > array_walk($a,create_function('$a','print("$a\n"); ')); > ?> > > How can I make sure that > for x in a: x=2*x > > actually changes the elements of the array "a"? >>> l=range(10) >>> for i in range(len(l)): ... l[i]*=2 ... >>> l [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From hniksic at xemacs.org Fri Sep 12 09:53:51 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Sep 2008 15:53:51 +0200 Subject: Accessing __slots__ from C References: <87k5diex3m.fsf@mulj.homelinux.net> <87ej3p7ira.fsf@mulj.homelinux.net> Message-ID: <87abed79n4.fsf@mulj.homelinux.net> Chris writes: >> In my experience, as long as you're >> accessing simple slots, you should notice a difference. > > (I'm not sure what you mean by a 'simple slot'. I mean a slot defined by __slots__ = slot1, slot2, slot3, ..., without descriptors or specific __getattribute__ code on top of that. > - GetAttr: 46 seconds (46 seconds) > outside the loop: > PyObject *name = PyString_FromString("attr_one"); I think you should be using PyString_InternFromString, but it will probably still be slower than PyList_GET_ITEM, which is still much simpler. The next optimization is the one proposed by Carl, which should yield speed comparable to PyList_GET_ITEM. See my response in that subthread for details. From saluk64007 at gmail.com Fri Sep 26 10:54:51 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Fri, 26 Sep 2008 07:54:51 -0700 Subject: Not fully OO ? In-Reply-To: <48DCC786.2040407@wildenhain.de> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: Depending on the scale of the website I am making, how much I care about editing it in the future, and how much I just want to get something up, I will occasionally use php. And I am a self confessed php hater :) But it's generally the fastest way I know to get something up. So even terrible languages can have their uses! From pmaupin at gmail.com Sun Sep 7 14:17:04 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 7 Sep 2008 11:17:04 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: On Sep 7, 12:30?pm, Mensanator wrote: > On Sep 6, 11:05 pm, Steven D'Aprano > Sheesh. That's not a problem, because Python is not trying to be a > > dialect of SQL. > > And yet, they added a Sqlite3 module. Does that mean that, because there is an 'os' module, Python is trying to compete with Linux and Windows? This is starting to feel like a troll, but JUST IN CASE you are really serious about wanting to get work done with Python, rather than complaining about how it is not perfect, I offer the following snippet which will show you how you can test the results of a sum() to see if there were any items in the list: >>> class MyZero(int): ... pass ... >>> zero = MyZero() >>> x=sum([], zero) >>> isinstance(x,MyZero) True >>> x = sum([1,2,3], zero) >>> isinstance(x,MyZero) False >>> From Lie.1296 at gmail.com Sat Sep 27 14:12:00 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 27 Sep 2008 11:12:00 -0700 (PDT) Subject: Borg vs Singleton vs OddClass Message-ID: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> This is probably unrelated to Python, as this is more about design pattern. I'm asking your comments about this design pattern that is similar in functionality to Singleton and Borg: to share states. I'm thinking about this design pattern (I don't know if anyone has ever thought of this pattern before): class OddClass(object): def __init__(self): global OddClass OddClass = self def __call__(): return self The OddClass is a class that would overwrite its own class definition at its first instantiation. OddClass defines __call__ so that subsequent "instantiation" (technically it is no more an instantiation, but Duck Typing says it does) of the class would return the single instance. It do have a problem though, that you can't do isinstance(a, OddClass) since the name OddClass no longer refers to the OddClass class descriptor, but to an instance of OddClass. I don't think that's much of a problem though since using isinstance() is generally not a good idea in python (although OddClass do use global which many people, including me, would usually consider as bad form). The problem with Borg is that it is not inheritable (in certain sense[1]) and only work with old-style class (which is due to be completely removed on py3k)[2], Singleton and OddClass is inheritable. >>> class Singleton(object): ... >>> s = Singleton() >>> class A(Singleton): pass >>> class B(Singleton): pass >>> a = A() >>> b = B() >>> s.foo, a.bar = "bar", 42 >>> b.foo, b.bar ... Traceback, Attribute Error ... >>> class OddClass(object): ... >>> s = OddClass() >>> class A(OddClass): pass >>> class B(OddClass): pass >>> a = A() >>> b = B() >>> s.foo, a.bar = "bar", 42 >>> b.foo, b.bar ... Traceback, Attribute Error ... but for Borg, see [1] [1] classes that inherits from Borg shares state not only within children, but also with their parents and cousins. That means inheriting from Borg is useless, and that also means one Borg code for every state sharing classes, instead of inheriting from Singleton/ OddClass. In code: >>> class Borg: ... >>> class A(Borg): ... >>> class B(Borg): ... >>> s, a, b = Borg(), A(), B() >>> s.foo, a.attr = "bar", 42 >>> b.foo, b.attr "bar" 42 >>> # we want b.foo and b.attr to raise error since .foo, and .bar isn't B's shared state, it's A's and Borg's shared state [2] Actually in new-style class, they say Borg can use __slots__, but they say it'd be slightly more complex From steve at holdenweb.com Fri Sep 12 08:23:48 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 08:23:48 -0400 Subject: lacking follow-through In-Reply-To: References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: castironpi wrote: [...] > For example, I sometimes hear people talk about salary as though it > were social approval, and vice versa. Even though the analogy doesn't > hold in every case generally, it is still a good way to express > yourself in many contexts, and especially when the more precise word > isn't on the tip of your tongue. Perhaps under those circumstances the better choice is to hold off posting and do some research until you come up with the proper word. Precision in the expression of ideas encourages debate, whereas sloppy "just write what you feel" is likely to result in hostile responses, as it causes the perception that you value your own time more than that of the people you attempt to engage. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fredrik at pythonware.com Mon Sep 15 16:17:37 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 22:17:37 +0200 Subject: append on lists In-Reply-To: References: Message-ID: Armin wrote: > just a dumb question. > > Let a = [1,2,3,4,5] > > Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? yeah, that's a dumb question. From thomas.troeger.ext at siemens.com Mon Sep 22 10:43:23 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Mon, 22 Sep 2008 16:43:23 +0200 Subject: Reading Windows CSV file with LCID entries under Linux. Message-ID: Dear all, I've stumbled over a problem with Windows Locale ID information and codepages. I'm writing a Python application that parses a CSV file, the format of a line in this file is "LCID;Text1;Text2". Each line can contain a different locale id (LCID) and the text fields contain data that is encoded in some codepage which is associated with this LCID. My current data file contains the codes 1033 for German and 1031 for English US (as listed in http://www.microsoft.com/globaldev/reference/lcid-all.mspx). Unfortunately, I cannot find out which Codepage (like cp-1252 or whatever) belongs to which LCID. My question is: How can I convert this data into something more reasonable like unicode? Basically, what I want is something like "Text1;Text2", both fields encoded as UTF-8. Can this be done with Python? How can I find out which codepage I have to use for 1033 and 1031? Any help appreciated, Thomas. From stefan_ml at behnel.de Fri Sep 5 12:05:20 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 05 Sep 2008 18:05:20 +0200 Subject: Extract Information from Tables in html In-Reply-To: References: Message-ID: <48c158c0$0$11090$9b4e6d93@newsspool1.arcor-online.net> Hi, Jackie Wang wrote: > Here is a html code: > > > > Premier Community Bank of Southwest Florida >
> Fort Myers, FL > > > > My question is how I can extract the strings and get the results: > Premier Community Bank of Southwest Florida; Fort Myers, FL Use lxml.html. Something like this should do what you want: >>> from lxml import html >>> tree = html.parse("http://server.org/thefile.html") >>> all_tds = tree.findall("//td") >>> for td in all_tds: ... print( td.xpath("normalize-space()") ) Tweak as you see fit, tree iteration is at your service in case you need more. http://codespeak.net/lxml/ Stefan From bearophileHUGS at lycos.com Mon Sep 22 10:35:50 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 07:35:50 -0700 (PDT) Subject: A bit weird dictionary behavior References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: Tino Wildenhain: > Wouldn't > len([x for x in iterable if x==y]) > or even shorter: > iterable.count(y) > not work and read better anyway? The first version creates an actual list just to take its length, think about how much memory it may use. The second version requires the 'iterable' object to have a count() method, and in general this is false. > even calculating with boolean values isn't neccessary > since 'and' and 'foo if bar else blub' are working much better > so the type coalescing > bool - int - float can really go away. I don't understand. Bye, bearophile From castironpi at gmail.com Sat Sep 13 01:45:52 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 12 Sep 2008 22:45:52 -0700 (PDT) Subject: ctypes: Get full contents of character array References: Message-ID: <223fde52-b1aa-4d69-b374-2cf07973f2b5@73g2000hsx.googlegroups.com> On Sep 12, 6:38?pm, overdrig... at gmail.com wrote: > Hello! > > I wanted to get the full contents of a character array stored in a > struct, i.e. > _fields_ = [...("array", c_char * 12)...] > however, ctypes seems to try to return struct.array as a Python string > rather than a character array, and stops as soon as it encounters a > null within the character array. > > I ended up having to define a dummy struct > class dummystruct(Structure): > ? ? _fields_ = [] > > and declare array as: > ("array", dummystruct) > > then use string_at(byref(struct.array), 12). > > Is this really the best way of doing it? Is there no better way to > work around ctypes 'guess what you want' behaviour? > > Thanks in advance, > Rodrigo Rodrigo, If you have the option to change your declaration to c_byte* 12, you have more options. This example prints the null character you wanted. from ctypes import * import struct class S( Structure ): _fields_= [ ( 'array', c_byte* 12 ) ] s= S() #initialize struct.pack_into( '7s', s.array, 0, 'abc\x00def' ) #prototype and call PyString_FromStringAndSize prototype= PYFUNCTYPE( py_object, POINTER( c_byte ), c_size_t ) PyString_FromStringAndSize= prototype( ( "PyString_FromStringAndSize", pythonapi ) ) x= PyString_FromStringAndSize( s.array, 12 ) print repr( x ) #prototype and call PyString_FromString for contrast prototype= PYFUNCTYPE( py_object, POINTER( c_byte ) ) PyString_FromString= prototype( ( "PyString_FromString", pythonapi ) ) x= PyString_FromString( s.array ) print repr( x ) /Output: 'abc\x00def\x00\x00\x00\x00\x00' 'abc' From vinay_sajip at yahoo.co.uk Fri Sep 26 03:14:13 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Fri, 26 Sep 2008 00:14:13 -0700 (PDT) Subject: SimpleXMLRPCServer -- turning off request log? References: Message-ID: <15c9f762-2daf-4d1f-b182-4e7e1e982579@w7g2000hsa.googlegroups.com> On Sep 26, 2:01 am, m... at pixar.com wrote: > My SimpleXMLRPCServer program prints to stderr a line like > this for each request: > > ohm..pixar.com - - [25/Sep/2008 17:57:50] "POST /RPC2 HTTP/1.0" 200 - > > Is there a way to turn thisloggingoff? I have RTFM and can't > seem to find a way to do so. > >From the documentation (2.5): class SimpleXMLRPCServer( addr[, requestHandler[, logRequests[, allow_none[, encoding]]]]) "If logRequests is true (the default), requests will be logged; setting this parameter to false will turn off logging." Did you try setting logRequests to false? Regards, Vinay Sajip From FettManChu at gmail.com Tue Sep 16 21:50:36 2008 From: FettManChu at gmail.com (Fett) Date: Tue, 16 Sep 2008 18:50:36 -0700 (PDT) Subject: Python Linear Programming on Ubuntu Message-ID: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> I am trying to find a wrapper to do linear programming within python. I am using an ubuntu machine and I have apt-get'd lp_solve, which works just fine. If someone knows of a wrapper that will work with that that'd be great. I also heard that scipy has a wrapper, however, I can't find any documentation on it, nor can I seem to find it with dir(). If anyone knows where there is good documentation on this I would love to use that (the more native to python the better imo). I have tried many things, including http://lpsolve.sourceforge.net/5.5/Python.htm, openopt, and cvxopt. I can't seem to find any with enough documentation to get me off the ground. Some I can't compile, some I can't even find out how to compile. If anyone knows of an LP package (preferably with IP as well, like lp_solve has), that interfaces well with python and has enough documentation to get a dependency newb like myself off the ground that would be great. From mark.fink1 at googlemail.com Sun Sep 28 15:15:50 2008 From: mark.fink1 at googlemail.com (mark) Date: Sun, 28 Sep 2008 12:15:50 -0700 (PDT) Subject: standalone buildbot possible/ don't have a remote Message-ID: <41a76fd8-47e3-4eb8-b980-11baf8dff0b2@u65g2000hsc.googlegroups.com> I want to start small and setup a buildbot on one machine (no slaves). I hope this is possible. I assume I only need one master in this case (without slave config)??? from my master.cfg c['slaves'] = [] ... (rest of the sample config) b1 = {'name': "buildbot-full", # 'slavename': "bot1name", 'builddir': "full", 'factory': f1, } Do I need some configuration that the builder uses the master instance? I experimented a bit and searched for a similar configuration so far without success :-(( I did run the buildbot testsuite without errors. Here is one problem the buildbot writes out on console: 2008-09-28 20:43:10+0200 [-] maybeStartBuild : [] [] 2008-09-28 20:43:10+0200 [-] : want to start build, but we don't have a remote Another thing I can think of is to set up two processes on one machine, which would be a bit of an overhead. Cheers, Mark From larry.bates at vitalEsafe.com Wed Sep 3 22:06:14 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Wed, 03 Sep 2008 21:06:14 -0500 Subject: Access to Windows "Add/Remove Programs"? In-Reply-To: References: Message-ID: Sean DiZazzo wrote: > Hi all, > > I'm trying to find a way to get a list of all the installed programs > on a Windows box via Python. I thought of a few hacks that might > partially work, and then thought about "Add/Remove Programs" Seems > like the right way to go. I looked over the pywin32 docs a bit, but > nothing slapped me in the face. > > Is there any reliable way to get at that info? > > Thanks in advance, > > ~Sean I would guess that that program gets the information from the registry. Maybe looking at HKEY_LOCAL_MACHINE\SOFTWARE or HKEY_CURRENT_USER\Software branches? -Larry From seandavi at gmail.com Tue Sep 23 14:25:48 2008 From: seandavi at gmail.com (Sean Davis) Date: Tue, 23 Sep 2008 11:25:48 -0700 (PDT) Subject: Detecting the first time I open/append to a file References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> Message-ID: On Sep 23, 2:02?pm, tkp... at hotmail.com wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a ?single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > ? ? for param in range(10): > ? ? ? ? simulate(param) > > def simulate(parameter): > ? ? 'Lots of code followed by: > ? ? with open(summaryFn, 'ab') as f: > ? ? ? ? writer = csv.writer(f) > ? ? ? ? writer.writerow(header) > ? ? ? ? writer.writerow(Sigma) > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. You could use os.path.exists() to check if the file is there. However, the file could have been left over from a previous execution, etc. What might make sense is to open the file only once, store the file handle, and write to that throughout the execution. Sean From asifsshl917 at googlemail.com Sat Sep 20 11:02:45 2008 From: asifsshl917 at googlemail.com (ghghghxdghdghdxg) Date: Sat, 20 Sep 2008 08:02:45 -0700 (PDT) Subject: medicine cheap nizoral good for cheap nizoral drug order nizoral shampoo for hair loss generic nizoral cream used Message-ID: medicine cheap nizoral good for cheap nizoral drug order nizoral shampoo for hair loss generic nizoral cream used + + + BUY CHEAP NIZORAL - ORDER NIZORAL ONLINE (ALL CARDS ACCEPTED !!!) Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL Buy cheap generic NIZORAL and brand NIZORAL + + + + * nizoral order nizoral reviews magicbluepill com buy dose order nizoral scalp fluid in Wadena brand nizoral side effect selsun blue in Magrath 200mg ketoconazole nizoral available in SpokanValley generic nizoral anti dandruff shampoo buy nizoral shampoo side in Bloomington buy nizoral online brand nizoral 100 in Barachois 2 nizoral generic nizoral anti dandruff shampoo in Venise-en-Quebec brand nizoral shampoo hairloss cheap nizoral free in Mascouche - price of nizoral medications in Logan Lake - buy nizoral over the price of nizoral www viagraonlinepharmacy com - ketoconazole 2 doctor in Granisle - buy nizoral to brand nizoral 1 in Golden - generic nizoral cream side nizoral 100 in Hazlet - cheap nizoral janssen cilag hair loss nizoral in Visalia - generic nizoral antifungal cheap nizoral medication in Killarney - anti dandruff in nizoral in Nelson House - buy nizoral scalp buy nizoral wiki in Ponce - nizoral with cheap nizoral ingredients en Saint-Quentin - order nizoral over the cheap nizoral janssen cilag in Claremont - nizoral used for cheap nizoral good for www dionpills org - generic nizoral dandruff shampoo in Calmar - buy nizoral sampon of nizoral www cartonionline com generic nizoral shampoo brand nizoral shampoo for hairloss doctor From larry.bates at vitalEsafe.com Sat Sep 13 11:14:02 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sat, 13 Sep 2008 10:14:02 -0500 Subject: testing if another instance of a script is already running In-Reply-To: References: Message-ID: <_IQyk.32260$Ep1.31830@bignews2.bellsouth.net> Strato wrote: > Hi folks, > > I want to write some kind of test to check at startup if another > instance of my script is already running. > > I don't want to handle writing of a PID file because it is too > Unix/Linux specific way to do this, and I need to keep the code to be > cross-platform. > > I think the better way to achieve this is to use some process control, > but I'm a neebie and I don't see how to do this in a safe and clean way. > > Any idea ? > > Best regards, > Strato Here is a recipe for Windows version of singleinstance class: http://code.activestate.com/recipes/474070/ and I wrote and contributed the equivalent Linux version: http://code.activestate.com/recipes/546512/ Hope this helps. -Larry From deets at nospam.web.de Tue Sep 23 03:09:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 23 Sep 2008 09:09:07 +0200 Subject: Using vObject In-Reply-To: References: Message-ID: <6jrj0mF4ngv3U1@mid.uni-berlin.de> Joshua Gardner schrieb: > I'm brand new to USENET so please bear with me. > > I'm writing a specialized to-do list app. I'm using Django but this is > not a question about Django. It has to have recurring tasks set by the > managers for the employees to then check off. > > I've got pretty much everything in the app worked out, except for one > thing: the repeating tasks. I want to have it so that the manager puts > in a repeating task with a description and a repeat rule. This rule then > generates simpler one-time tasks. These one-time tasks have a > description, a time (a datetime.datetime object) and "completed" boolean. > > I've looked around and think I have these options: > 1. Manually put it all together with another Django model that > implements the repeat rules. > 2. Do the same thing but use dateutil.rrule to help. > 3. Use the icalendar (http://codespeak.net/icalendar/) module to access > ICS files. > 4. vObject (http://vobject.skyhouseconsulting.com/) to do the same. > > I think I want to use vObject because it uses dateutil and the > management can easily manage tasks from a desktop app. > > Only thing is that I find vObject's documentation very cryptic and was > wondering if anybody here could shed some light on how to use vObject. A > simple "getting-started" tutorial or something similar would be nice. I think you are going down a wrong route here. I have implemented a reservation management application for a museum in TurboGears - and while I use icalendar to support ICS-based viewing of the reservations, I completely manage * store them based on my own model. In case of the recurring events, I have one master-event, that defines the start & recurrence-options. I then create child-events that essentially are write-protected (all editing goes to the master), and serve only as place-holder. But if you want, you can "detach" them, to make them live on their own. The reason for this is simple: if you want to display views of your tasks based on e.g. a specific day, you can query the database. Simple queries will yield a list of tasks needed. Whereas all ICS-based approaches listed above, including vObject, would mean that you - extract *all* the ics-data from the database, not really knowing if there is anything relevant in there for the current view - potentially expand the events in there, manually or through some methods the libraries expose - filter the results. All of this is going to consume much useless time. So I would suggest you use approach 1, possibly 2 (don't know rrule). Diez From sukhrajtakhar at hotmail.com Tue Sep 30 11:39:46 2008 From: sukhrajtakhar at hotmail.com (rajtakhar) Date: Tue, 30 Sep 2008 08:39:46 -0700 (PDT) Subject: Great New Linux Handheld Console & UMPC!! Message-ID: <0372789a-0493-4663-ae65-9377291234f7@m73g2000hsh.googlegroups.com> The GP2X Wiz and Pandora units will open up the face of homebrewgames, one is a pure Gaming console, with hundreds of emulatorswritten for, the other is a console/UMPC Check the data here: http://gp2xwiznpandora.blog.co.uk/ From bmihelac at gmail.com Fri Sep 12 11:08:18 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Fri, 12 Sep 2008 08:08:18 -0700 (PDT) Subject: setattr in class Message-ID: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Hi all - when trying to set some dynamic attributes in class, for example: class A: for lang in ['1', '2']: exec('title_%s = lang' % lang) #this work but is ugly # setattr(A, "title_%s" % lang, lang) # this wont work setattr(A, "title_1", "x") # this work when outside class print A.title_1 print A.title_2 I guess A class not yet exists in line 4. Is it possible to achive adding dynamic attributes without using exec? thanks, Bojan From __peter__ at web.de Fri Sep 26 12:21:41 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 26 Sep 2008 18:21:41 +0200 Subject: Understanding (and getting rid) of optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a References: <85ec721a-b5a2-4f22-9e37-bda4a0f9eb81@z72g2000hsb.googlegroups.com> Message-ID: hofer wrote: > Hi, > > I get following warning with a python script: > > > optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will > return a signed string in Python 2.4 and up > > > my code: > from optparse import OptionParser > > if __name__ == '__main__': > parser = OptionParser() > parser.add_option('-G','--green',action= 'store_const', const= > '#00FF00' , dest='color', > default='#808080', > help='life is so green') > parser.add_option('-R','--red',action= 'store_const', const = > '#FF0000' , dest='color', > help='I just see red') > # add more elaborated command line parsing and help text here > (options,argv) = parser.parse_args() > print 'options',options > > I assume python wants to tell me that newer version will behave > differently for numeric arguments > > What I wonder is: Why do I get the warning if my code doesn't try to > parse any numbers? The culprit is print options If you look into optparse.py you'll see that part of the __repr__() method of the Value class is the object's address, roughly "%x" % id(self) id(self) is just the Value instance's address in memory which seems to be >= 0x80000000 (assuming you are on a 32-bit machine) in your case. Such numbers were interpreted as negative ints but are now treated as positive longs. Read http://www.python.org/dev/peps/pep-0237/ for details. > Is there any way to get rid of the warning without having to change > the python version? > (I noticed, the warning disappears if I remove the line printing > options) You can print options.__dict__ instead of options with little loss of information, or turn the warning off python -Wignore::FutureWarning myscript.py Peter From circularfunc at gmail.com Thu Sep 11 16:21:46 2008 From: circularfunc at gmail.com (process) Date: Thu, 11 Sep 2008 13:21:46 -0700 (PDT) Subject: Is len O(n) or O(1) ? References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> Message-ID: <00c3d9f8-2646-45e7-ac8e-05b0a960a169@z66g2000hsc.googlegroups.com> ok but if len is O(1) then it doesnt matter? compared to if not lista: return [] i mean. From fredrik at pythonware.com Tue Sep 2 00:34:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Sep 2008 06:34:53 +0200 Subject: Numeric literal syntax In-Reply-To: <878wubp5mz.fsf@benfinney.id.au> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> <878wubp5mz.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > I would argue that the precedent, already within Python, for using a > space to separate pieces of a string literal, is more important than > precedents from other programming languages. that precedent also tells us that the whitespace approach is a common source of errors. taking an approach that's known to be error-prone and applying it to more cases isn't necessarily a great way to build a better language. From maric at aristote.info Mon Sep 15 08:42:43 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 14:42:43 +0200 Subject: Case-insensitive string compare? In-Reply-To: References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <200809051331.40609.maric@aristote.info> Message-ID: <200809151442.43981.maric@aristote.info> Le Friday 05 September 2008 19:36:56 Fredrik Lundh, vous avez ?crit?: > Maric Michaud wrote: > > I suspect you are coming to conclusions a bit quickly, without taking the > > pain of understanding the whole discussion. > > I'm pretty sure I was the first one to post an answer in this thread, > and I understand Python design and performance issues very well, thank you. > What is that ? Some sort of arguments ? If it matters, I know who you are and I don't try to compare my understanding of python with yours. > (but given your talk about "the cost of whitespace" in a response to a > comment about performance in that other subthread, It's silly that you continue to fight on unrelated arguments, I've already said that I misunderstood the OP's requirements and the proposed solution. > it's obvious that > you're just here to provide noise. plonk plonk.) I don't think you should make those assumptions, in your words, there are too much dumb or malevolent peoples on this list for it to be that "obvious". Nevertheless, I don't really see why I should explain myself for being here and trying to bring a (little, not like yours, of course) contribution. -- _____________ Maric Michaud From banibrata.dutta at gmail.com Thu Sep 4 06:57:37 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Thu, 4 Sep 2008 16:27:37 +0530 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <48BFB534.2080508@egenix.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> <48BFB534.2080508@egenix.com> Message-ID: <3de8e1f70809040357p6beb1efar7fe57af9bcaa537c@mail.gmail.com> On Thu, Sep 4, 2008 at 3:45 PM, M.-A. Lemburg wrote: > On 2008-09-04 11:14, Kay Schluehr wrote: > > On 4 Sep., 10:31, "M.-A. Lemburg" wrote: > >> On 2008-09-04 07:49, Kay Schluehr wrote: > >> > >>> 3) Following the public rumor mill and the latest hype RIA i.e. the > >>> merge of web- and desktop applications with systems like Adobe AIR, > >>> JavaFX, Google Gears and MS Silverlight is the future of frontend > >>> development. With the exception of IronPython and Silverlight, Python > >>> hasn't even entered this game and no one knows if it ever will. > >> Actually, it has already and quite some time ago: > >> > >> http://www.artima.com/weblogs/viewpost.jsp?thread=208528 > >> > >> The recipe is simple: use Python for the business logic, database > >> interfacing, etc and have it talk to a Flex front-end via XML-RPC > >> or REST. > > > > Python is still server-side in this scenario and plays no role in UI > > definitions. > > That depends on how you design the application. It is well possible > to have Python drive the GUI by sending the required details to > the Flex front-end via XML (ie. data-driven GUIs). > > > So one doesn't get more than e.g. Django apps that > > respond to HTTP requests triggered by JavaScript forms except that > > JavaScript+HTML+Browser is replaced by Flex = AS3+MXML+FlashPlayer. > > You really can't compare the Flex stack to an AJAX stack. Flex > has a lot more to offer for GUI programming than AJAX, it also > doesn't suffer from the problems of AJAX having to support several > different sets of browser or library bugs. > > We switched from an AJAX approach to a Flex-based approach last year > and never even considered moving back again. The approach does seem quite impressive, but isn't Flex's platform neutrality quite over-rated ? I mean after-all, it assumes that Flex is available for and available on the platform. Flex today is not yet so ubiquitous as the JRE... Are there some established best-practices on how to package such applications -- s.a. shipping with its's own Flex runtime, offer-download if missing etc. ? What happens if owner of target machine decides to upgrade their version of Flex, will it impact the application package in anyway, and render rest of it "non-upgradable" ? > > > > The role of Python is somewhat arbitrary. This could change only if > > Python becomes a client side language executed by AVM, V8 etc. like > > IronPython in Silverlight. > > > > About separating UI from application logics by assigning functionality > > to different general purpose languages I have to admit that I don't > > think it is such a great idea ... > > In my experience, Flex + Python gives you the best of both worlds, > the nice GUI features of Flex and the efficiency of Python for the > business logic. > > A long time ago, there was a Python plugin for Netscape > which allowed you to run Python straight in the browser. Perhaps > it's time to revive such an idea... but then you're still missing > out on the GUI part, since you're still stuck with what the > browser has to offer in terms of widget support. > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Sep 04 2008) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dotancohen at gmail.com Sat Sep 27 08:28:56 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 27 Sep 2008 15:28:56 +0300 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> Message-ID: <880dece00809270528p1a80354bydaf45cc48fbf2bbf@mail.gmail.com> 2008/9/27 Aaron Castironpi Brady : >> I think in June and July they were selling watches a lot which I >> haven't noticed recently. > > Gucci 104 G-Bandeau Watches - Gucci Watches Discount Rolex Oyster > Perpetual Lady Datejust Pearlmaster 18kt Yellow Gold Diamond Ladies > Watch 80318C > Cartier Must 21 Watches - Cartier Watches Discount > > I speak too soon. > If we start blocking users who have no previous posts and then post many new messages at once, then we wll just push the spammers to forge active list users and reply to threads. That would be a worse situation then we are in now. I say leave well enough alone. Read about the Brain Blood Barrier (http://en.wikipedia.org/wiki/Brain_Blood_Barrier) for an example in nature where although a method to stop an attacker exists, it is not overused to prevent the attacker from becoming more powerful. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From mh at pixar.com Thu Sep 25 21:01:43 2008 From: mh at pixar.com (mh at pixar.com) Date: Fri, 26 Sep 2008 01:01:43 GMT Subject: SimpleXMLRPCServer -- turning off request log? Message-ID: My SimpleXMLRPCServer program prints to stderr a line like this for each request: ohm..pixar.com - - [25/Sep/2008 17:57:50] "POST /RPC2 HTTP/1.0" 200 - Is there a way to turn this logging off? I have RTFM and can't seem to find a way to do so. Many TIA! Mark -- Mark Harrison Pixar Animation Studios From sjmachin at lexicon.net Sat Sep 6 17:49:51 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 14:49:51 -0700 (PDT) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sep 7, 7:29?am, Wojtek Walczak wrote: > On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote: > > ? ? ? ? ? ? ? ? ?if mult is 1: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ?^^ > You're testing for identity, not for equality. > Change it to "if mult == 1". Is it alright now? > Although he definitely should not be using "is" here, that can not be the problem if he is using CPython. As an optimisation, small integers are interned i.e. for each small integer, there is only one object. >>> a = 1 >>> b = 10000 >>> a is 1 True >>> b is 10000 False >>> id(a) 10897704 >>> id(1) 10897704 >>> id(b) 11893004 >>> id(10000) 12633044 >>> From grante at visi.com Tue Sep 16 09:57:53 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:57:53 -0500 Subject: append on lists References: <1221564169.16690.0@proxy00.news.clara.net> Message-ID: On 2008-09-16, Maric Michaud wrote: > all expressions that return something, return a new object, That's not _quite_ true: >>> a=1 >>> b=a.__add__(0) >>> a is b True ;) -- Grant Edwards grante Yow! LOOK!! Sullen at American teens wearing visi.com MADRAS shorts and "Flock of Seagulls" HAIRCUTS! From grante at visi.com Tue Sep 16 09:55:56 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:55:56 -0500 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <1221564169.16690.0@proxy00.news.clara.net> Message-ID: On 2008-09-16, Armin wrote: > Alex Marandon wrote: >> Armin wrote: >>> Duncan Booth wrote: >>> >>> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c >>> (with c = [8,9]) is identical, >> >> No it's not, + doesn't alter its operands. >> >> >>> a = 1 >> >>> b = 2 >> >>> a + b >> 3 > > That's not the point :) > > What's the value of 1.add(b)? None? Or 3 ?? >>> a = 1 >>> b = 2 >>> 1.add(b) File "", line 1 1.add(b) ^ SyntaxError: invalid syntax > (if add works in the same way as append) It doesn't. > a + b doesn't change a,b ... but a.add(b) -> a=3 WTH are you talking about? -- Grant Edwards grante Yow! I just got my PRINCE at bumper sticker ... But now visi.com I can't remember WHO he is ... From castironpi at gmail.com Sat Sep 13 20:32:35 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 13 Sep 2008 17:32:35 -0700 (PDT) Subject: testing if another instance of a script is already running References: <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> Message-ID: On Sep 13, 5:34?pm, s... at pobox.com wrote: > ? ? >> I don't want to handle writing of a PID file because it is too > ? ? >> Unix/Linux specific way to do this, and I need to keep the code to be > ? ? >> cross-platform. > ? ? >> > ? ? >> I think the better way to achieve this is to use some process > ? ? >> control, but I'm a neebie and I don't see how to do this in a safe > ? ? >> and clean way. > > ? ? Aaron> You could use msvcrt.locking, and just lock the script file. ?I > ? ? Aaron> am not sure about this. > > If you want a cross-platform solution, you might try the lockfile module > instead: > > ? ?http://pypi.python.org/pypi/lockfile > > Skip Would it suffice to call 'os.open' with flags= _O_CREAT| _O_EXCL ? Would that be platform-independent? Windows docs (_open): _O_CREAT| _O_EXCL Returns an error value if the file specified by filename exists. Applies only when used with _O_CREAT. man page: O_EXCL If O_EXCL and O_CREAT are set, open will fail if the file exists. The check for the existence of the file and the creation of the file if it does not exist is atomic with respect to other processes executing open naming the same filename in the same directory with O_EXCL and O_CREAT set. CreateDirectory: The CreateDirectory function does seem to guarantee this as well, though is not as explicit: Possible errors include the following. ERROR_ALREADY_EXISTS The specified directory already exists. But the lock operation wouldn't need the 'if hasattr(os, "link")' test. From steven at REMOVE.THIS.cybersource.com.au Mon Sep 29 04:47:33 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 29 Sep 2008 08:47:33 GMT Subject: Detecting dir (tree) changes fast? References: Message-ID: On Mon, 29 Sep 2008 10:05:10 +0200, robert wrote: > I want to detect changes in a directory tree fast with minimum > overhead/load. In order to check the need for sync tasks at high > frequency. > It must not be 100% reliable (its also forced time periodic), so kind of > hashing would be ok. > How? Google is your friend. Googling for "python directory watcher" gives the following top three links: http://www.amk.ca/python/simple/ http://timgolden.me.uk/python/win32_how_do_i/ watch_directory_for_changes.html (sorry for the broken URL) http://code.activestate.com/recipes/217829/ There are probably many others. Which one is most suitable will depend on the details of, e.g. the OS you are using, the types of changes you're expecting, how many files are in the directory. -- Steven From dmitry at athabascau.ca Thu Sep 25 16:47:18 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 20:47:18 GMT Subject: Eggs, VirtualEnv, and Apt - best practices? References: <6k2aqqF5p185U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > - different OS. I for one don't know about a package management tool > for windows. And while our servers use Linux (and I as developer as > well), all the rest of our people use windows. No use telling them to > apt-get instal python-imaging. that is a very valid point, but it seemed that Scott has homogeneous environment: Debian/Ubuntu so my post was relative to the original request. I agree that when you throw Windows/MacOS into the mix things become "interesting". But then it's better when your developers develop on server/platform they are going to be using, using same stack they going to face in production etc. It all depends on requirements and current practices in company. > - keeping track of recent developments. In the Python webframework > world for example (which the OP seems to be working with), things move > fast. Or extremly slow, regarding releases. Take Django - until 2 month > ago, there hasn't been a stable release for *years*. Virtually everybody > was working with trunk. And given the rather strict packaging policies > of debian and consorts, you'd be cut off of recent developments as well > as of bugfixes. that definitely becomes tricky however not impossible to track. You do need a common snapshot for all developers to use anyway - so why not just package it up? Note: I do agree that depending on environment/development practices/policies/etc my statement might become invalid or useless. However when you're dealing with homogeneous environment or you require development and testing to be done on your servers running targeted application stack - things become much easier to manage :) From bignose+hates-spam at benfinney.id.au Sun Sep 7 21:35:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 08 Sep 2008 11:35:00 +1000 Subject: lacking follow-through References: <038bcbbc-e204-43f8-b656-81495af36b6c@d77g2000hsb.googlegroups.com> Message-ID: <87vdx7ju7v.fsf@benfinney.id.au> Paul Boddie writes: > On 7 Sep, 23:00, castironpi wrote: > > I am concerned by the lack of follow-through on some responses to > > recent ideas I have described. Do I merely have a wrong > > understanding of group policy? > > I think some people have taken exception to your contributions > previously, which I believe exhibits a certain degree of > shortsightedness on their part [?] For my part, I find those posts a mammoth waste of my time, since they're shrouded in language so difficult to parse that I can't see what they're supposed to be saying in a reasonable amount of time. So, I consider it more valuable to never see those posts; if someone else can find a gem of wisdom in any of them that's significantly valuable, presumably I'll find out by some other means than attempting to read those posts myself. This is not intended as any kind of offense to the author, nor to anyone not fluent in written English; it's merely a choice I make as to how I will spend my time. -- \ ?No wonder I'm all confused; one of my parents was a woman, the | `\ other was a man.? ?Ashleigh Brilliant | _o__) | Ben Finney From darcy at druid.net Fri Sep 12 11:19:49 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 12 Sep 2008 11:19:49 -0400 Subject: Checking the boolean value of a collection In-Reply-To: References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> Message-ID: <20080912111949.19629e78.darcy@druid.net> On Fri, 12 Sep 2008 17:11:47 +0200 Fredrik Lundh wrote: > The "__builtins__" object is an implementation detail, and shouldn't be > accessed directly. And I hope I don't need to point out that adding > custom builtins nillywilly is a bad idea... Is there ever any advantage to having something as a builtin rather than as a regular user method? What difference does it make to the running script? I can see that adding "bar" from module "foo" to "__builtins__" means that you can use "bar()" instead of "foo.bar()". Is that the only benefit? -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From ppearson at nowhere.invalid Wed Sep 17 11:04:17 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 17 Sep 2008 15:04:17 GMT Subject: Problem occured while sending mail References: <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> Message-ID: <6jckjhF2llrvU1@mid.individual.net> On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui wrote: > On Sep 17, 5:04 pm, sui wrote: >> this is my code >> >> import sys, os, glob, datetime, time >> import smtplib >> ## Parameters for SMTP session >> port=587 >> SMTPserver= 'smtp.gmail.com' >> SMTPuser= '... at gmail.com' >> pw= 'fill in here' >> SENDER= SMTPuser >> >> ## Message details >> FROM= SENDER >> TO= 'notgm... at a.com' >> CC=FROM >> ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC >> RECEIVERS= (TO,) ## ignore the CC address >> >> subject= 'Test 1a' >> message='*** Email test *** ' >> >> print 'Starting SMTP mail session on %s as %s ' % >> (SMTPserver,SMTPuser) >> session = smtplib.SMTP(SMTPserver,port) >> session.set_debuglevel(0) # set debug level to 1 to see details >> session.ehlo(SMTPuser) # say hello >> session.starttls() # TLS needed >> session.ehlo(SMTPuser) # say hello again, not sure why >> session.login(SMTPuser, pw) >> >> ##Create HEADER + MESSAGE >> HEADER= 'From: %s\r\n' % FROM >> HEADER= HEADER + 'To: %s\r\n' % TO >> HEADER= HEADER + 'Cc: %s\r\n' % CC >> HEADER= HEADER + 'Subject: %s\r\n' % subject >> BODY= HEADER + '\r\n' + message >> print BODY >> >> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email >> >> session.close() >> >> Now when i run this .py file...as python mail.py >> i can see only statement >> starting smtp mail......n details >> then nothing on screen after few minutes or after pressing ctrl +c >> Traceback (most recent call last): >> File "mail4.py", line 21, in >> session = smtplib.SMTP(SMTPserver,port) >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ >> (code, msg) = self.connect(host, port) >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect >> self.sock.connect(sa) >> File "", line 1, in connect >> or may be conncetion time out >> >> wats the solution for this > > if i dont press cntrl + c then it shows > Starting SMTP mail session on smtp.gmail.com as gogtesuyash at gmail.com > Traceback (most recent call last): > File "mail4.py", line 21, in > session = smtplib.SMTP(SMTPserver,port) > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect > raise socket.error, msg > socket.error: (110, 'Connection timed out') > > plz help me its urgent.....i want to complete it as early as possible I pasted your code into a file named temp.py, and (perhaps superstitiously) added a backslash to this line: >> print 'Starting SMTP mail session on %s as %s ' % Here's what it does (long line wrapped manually): peter at eleodes:~$ python temp.py Starting SMTP mail session on smtp.gmail.com as ... at gmail.com Traceback (most recent call last): File "temp.py", line 27, in ? session.login(SMTPuser, pw) File "/usr/lib/python2.4/smtplib.py", line 591, in login raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (535, \ '5.7.1 Username and Password not accepted. Learn more at\n' \ '5.7.1 http://mail.google.com/support/bin/answer.py?answer=' \ '14257 a8sm34686663poa.12') peter at eleodes:~$ This indicates that it got much farther than when you ran it, since your timeout message comes from the smtplib.SMTP call several lines before the session.login call. As a simple connectivity test, you might see whether you can connect using telnet: peter at eleodes:~$ telnet smtp.gmail.com 587 Trying 72.14.253.109... Connected to gmail-smtp.l.google.com. Escape character is '^]'. 220 mx.google.com ESMTP m27sm34789033pof.6 ^]c telnet> c Connection closed. peter at eleodes:~$ -- To email me, substitute nowhere->spamcop, invalid->net. From grante at visi.com Fri Sep 26 21:30:49 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 26 Sep 2008 20:30:49 -0500 Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> Message-ID: On 2008-09-26, nntpman68 wrote: > Hm, > > > I guess you just filter mailing lists and can do nothing about the > newsgroup if I'm fetching via the nntp server of my ISP itself, right? I read the group via NNTP, and I find that blocking all articles posted from google.groups gets rid of all of the spam. -- Grant From clp at rebertia.com Sat Sep 27 19:01:14 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 27 Sep 2008 16:01:14 -0700 Subject: check if file is MS Word or PDF file In-Reply-To: <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> References: <558b73fb0809271542t6bcd02e2o680082155e691923@mail.gmail.com> Message-ID: <47c890dc0809271601y6f5a4a5fy98fad966e5ca024@mail.gmail.com> On Sat, Sep 27, 2008 at 3:42 PM, Michael Crute wrote: > On Sat, Sep 27, 2008 at 5:43 PM, A. Joseph wrote: >> What should I look for in a file to determine whether or not it is a >> MS Word file or an Excel file or a PDF file, etc., etc.? including Zip >> files >> >> I don`t want to check for file extension. >> os.path.splitext('Filename.jpg') will produce a tuple of filename and >> extension, but some file don`t even have extension and can still be read by >> MS Word or NotePad. i want to be 100% sure of the file. > > You could use the mimetypes module... > > <<< import mimetypes > <<< mimetypes.guess_type("LegalNotices.pdf") >>>> ('application/pdf', None) Looking at the docs for the mimetypes module, it just guesses based on the filename (and extension), not the actual contents of the file, so it doesn't really help the OP, who wants to make sure their program isn't misled by an inaccurate extension. Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > > -mike > > -- > ________________________________ > Michael E. Crute > http://mike.crute.org > > God put me on this earth to accomplish a certain number of things. > Right now I am so far behind that I will never die. --Bill Watterson > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 00:10:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 04:10:28 GMT Subject: Setter Propertys' mro? References: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> Message-ID: <00d34e8d$0$30713$c3e8da3@news.astraweb.com> On Sat, 06 Sep 2008 18:15:33 -0700, cipher wrote: > Whats the mro (method resolution order) of a setter property (__set__ on > a descriptor). > i seem to be experiencing some weird issue with them. for example > >>>> class test: Unless you're using Python 3, there's your problem right there. In Python 2.x, properties only work correctly for new style classes, not classic classes. Change the above line to: class Test(object): # by convention, classes start with Uppercase. and all should work (or at least you'll discover new and exciting different problems with your code). > however, if i specify the metaclass in the class definition it works > just fine... > > class test: > __metaclass__=type which is more or less the same as inheriting from object, except uglier. -- Steven From callen314 at gmail.com Tue Sep 23 17:34:06 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 23 Sep 2008 14:34:06 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: > The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), or should the exception propagate to the calling program which > handles the issue? > my view is that the exceptions are there precisely to tell the calling program about the error and give the programmer a chance to do something smart about it. A library, properly, doesn't even know the context in which it is running, and sys.exit() is pretty heavy handed for a library to call and shows assumptions beyond what a library should assume about its running environment. imho From martin at v.loewis.de Fri Sep 12 15:15:23 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 12 Sep 2008 21:15:23 +0200 Subject: Python on Windows XP 64-bit: python not found in registry In-Reply-To: References: Message-ID: <48cabfcb$0$2340$9b622d9e@news.freenet.de> > Anybody here that had the same problem and solved it? Did you install the 32-bit or the 64-bit installer? If the 64-bit installer, did you also install 32-bit or 64-bit installers for iPython, PIL, and easy_install? If you try to use 32-bit extensions or installers to locate a 64-bit Python, that will fail: even if installation would succeed, you still couldn't use the resulting installations, since you just can't mix the two architectures in a single process. Regards, Martin From gagsl-py2 at yahoo.com.ar Fri Sep 5 17:48:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 18:48:57 -0300 Subject: Regarding subprocess module References: Message-ID: En Fri, 05 Sep 2008 09:56:02 -0300, tarun escribi?: > import subprocess,time > cmdExe = "C:\\WINDOWS\\system32\\cmd.exe" > myProcess = subprocess.Popen(cmdExe,stdin=subprocess.PIPE) > time.sleep(2) > myProcess.stdin.write('cd Desktop\r\n') > > I copied the above lines of code to a file and tried executing the python > file from dos box (command prompt) on windows > I want subprocess.Popen to open a new dos box. But it works in the same > window. What should I do to open the subprocess in new window? Add this argument: creationflags = subprocess.CREATE_NEW_CONSOLE See "Creation of a Console" in MSDN: -- Gabriel Genellina From sturlamolden at yahoo.no Thu Sep 25 06:34:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 03:34:12 -0700 (PDT) Subject: Linq to Python References: Message-ID: <4e86da77-3525-44c5-a34a-871d4b7fc6da@r66g2000hsg.googlegroups.com> On 25 Sep, 12:06, hrishy wrote: > var stoogeGuys = > ? ? ?Beginning with the XML source > ? ? ?from xmlGuys in xmlSource.Descendants("Stooge") > ? ? ?Join to the array on the common element "stoogeName" > ? ? ?join arrayGuys in familyFacts > ? ? ? ? ? ?on xmlGuys.Element("stoogeName").Value equals arrayGuys.stoogeName > ? ? ?Join to the database on the common element "stoogeName" > ? ? ?join dbGuys in stoogeContext.stoogeTables > ? ? ? ? ? ?on xmlGuys.Element("stoogeName").Value equals dbGuys.stoogeName > ? ? ?select new > ? ? ?{ > ? ? ? ? firstName ? ?= dbGuys.stoogeName, > ? ? ? ? familyName ? = arrayGuys.familyName, > ? ? ? ? birthDate ? ?= xmlGuys.Element("birthDate").Value, > ? ? ? ? deathDate ? ?= xmlGuys.Element("deathDate").Value, > ? ? ? ? hairCutStyle = dbGuys.stoogeHaircut, > ? ? ?}; > [/code] That is a for loop over xmlGuys in xmlSource.Descendants("Stooge"). Those joins are e.g. dictionary lookups, and finally an object with names, birthdates, etc. are appended to the list stoogeGuys. From steve at REMOVE-THIS-cybersource.com.au Fri Sep 26 11:08:27 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 15:08:27 GMT Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <48dcf924$0$4653$426a74cc@news.free.fr> Message-ID: <00ecf4b4$0$20666$c3e8da3@news.astraweb.com> On Fri, 26 Sep 2008 17:00:59 +0200, Bruno Desthuilliers wrote: > Patrick Mullen a ?crit : >> Depending on the scale of the website I am making, how much I care >> about editing it in the future, and how much I just want to get >> something up, I will occasionally use php. And I am a self confessed >> php hater :) But it's generally the fastest way I know to get >> something up. So even terrible languages can have their uses! > > Sorry but I fail to see how it relates to the current thread ??? I think Patrick is responding to a comment from Tino Wildenhain: [quote] Well then it still depends on the perception of "job done". For example PHP programmers would bet their soul that their language of choice is exactly the right one to "get the job done." [end quote] Patrick, you will cause much less confusion if you quote relevant parts of the text you are replying too. -- Steven From niklas.norrthon at hotmail.com Fri Sep 26 07:02:57 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Fri, 26 Sep 2008 04:02:57 -0700 (PDT) Subject: urllib.urlopen fails in Emacs References: <877i8zco3t.fsf@gmail.com> Message-ID: <748c7630-1090-4c0b-8a52-34797f801c82@c58g2000hsc.googlegroups.com> On 26 Sep, 12:21, Wojtek Walczak wrote: > On Fri, 26 Sep 2008 02:23:18 -0600, Iain Dalton wrote: > > InEmacs, using run-python, > > > ? ? import urllib > > ? ?urllib.urlopen('http://www.google.com/') > > > results in this traceback: > ... > > ? ? IOError: [Errno socket error] (111, 'Connection refused') > > > It works fine from the command line. ?Why is this happening? > > I can't answer your question, since I don't useemacs, > but it looks likeemacshas some kind of built in firewall. > > ;-) > > -- > Regards, > Wojtek Walczak,http://tosh.pl/gminick/ I don't think it is emacs... It works for me, using emacs 22.1, python 2.5.1, and windows XP: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import urllib >>> urllib.urlopen('http://www.google.com/') > >>> /Niklas Norrthon From skip at pobox.com Mon Sep 22 11:35:26 2008 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 Sep 2008 10:35:26 -0500 Subject: Reading Windows CSV file with LCID entries under Linux. In-Reply-To: References: Message-ID: <18647.47934.846072.408740@montanaro-dyndns-org.local> Thomas> My question is: How can I convert this data into something more Thomas> reasonable like unicode? Basically, what I want is something Thomas> like "Text1;Text2", both fields encoded as UTF-8. Can this be Thomas> done with Python? How can I find out which codepage I have to Thomas> use for 1033 and 1031? There are examples at end of the CSV module documentation which show how to create Unicode readers and writers. You can extend the UnicodeReader class to peek at the LCID field and save the corresponding codepage for the remainder of the line. (This would assume you're not creating CSV files which contain newlines. Each line read would be assumed to be a new record in the file.) Skip From roy at panix.com Tue Sep 23 09:22:29 2008 From: roy at panix.com (Roy Smith) Date: Tue, 23 Sep 2008 09:22:29 -0400 Subject: Mutex not thread safe? PEP-3108. Message-ID: I'm perusing PEP-3108 and came upon this interesting statement (under the "Hardly used" section): mutex [...] Not thread-safe. How can a mutex, whose sole reason for existence is to mediate thread safety, not be thread safe? From ethan at stoneleaf.us Fri Sep 5 14:42:13 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 05 Sep 2008 10:42:13 -0800 Subject: Case-insensitive string compare? In-Reply-To: <200809051606.01358.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> <1220618002.21923.12.camel@jcd-desktop> <200809051606.01358.maric@aristote.info> Message-ID: <48C17D85.1020804@stoneleaf.us> Maric Michaud wrote: > Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez ?crit : > >>On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: >> >>>Thanks everyone for your help. I'm not opposed to using [key.lower() >>>for key in stage_map] at all, I was just curious to see if there were >>>any cleaner alternatives. It looks like that is what I'll be using. >>>I'm not familiar with how python works internally, but coming from C++ >>>it seems like "remaking" the map would be slow. However, speed is not >>>my main concern in my particular situation, I'm just curious to learn >>>more about python. >> >>You should be opposed to that particular solution. You have just taken >>a dictionary lookup (very fast) and turned it into a list traversal >>(slow). Even if speed isn't your main concern, this is an unnecessary >>de-optimization. You are deliberately slowing down your program to >>avoid a slightly more verbose lookup later. Your data structure might >>as well be a list of tuples to begin with, to avoid creating a new list. >>You have effectively made your keys useless as keys. >> >>If your lookups need to be case insensitive, make the key lower case, >>and store the cased version in the value, whether as a tuple or a dict >>(depending on whether you want named access). >> >>d = { >> 'foo': {'key': 'Foo', 'value': 'val1'} >> 'spam': {'key': 'sPAm', 'value': 'val2'} >>} >> >>search = 'FOO'.lower() >>if search in d: >> result = d[search] >> key = result['key'] >> value = result['value'] >> >>The only reason I wouldn't use this solution is if you expect to have >>keys that will be identical when made lowercase, but if you're doing >>case-insensitive lookup, you obviously don't expect this to be an issue. > > The OP has already said the keys are case-sensitive, so this is not an option, Actually, the OP said: -- So you're saying to ensure that stage_map's keys are initially -- lower-case to begin with? Well, I can't do this either since the -- *case of the keys is actually valuable* ***later on***. It's only for -- the purposes of this specific comparison operation that the case -- should be ignored. In other words, the key (as a key) is case-insensitive, and the key (as a value) is case-sensitive -- making Clifford's comments and solution perfectly acceptable. ~Ethan~ From nick at craig-wood.com Tue Sep 9 10:36:24 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 09 Sep 2008 09:36:24 -0500 Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: metaperl.com wrote: > Pyparsing has a really nice feature that I want in PLY. I want to > specify a list of strings and have them converted to a regular > expression. > > A Perl module which does an aggressively optimizing job of this is > Regexp::List - > http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm > > I really dont care if the expression is optimal. So the goal is > something like: > > vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| > u|ii|i)' > > Is there a public module available for this purpose? I wrote one of these in perl a while ago http://www.craig-wood.com/nick/pub/words-to-regexp.pl It transforms the regular expression recursively into more efficient ones. It uses regular expressions to do that. I considered porting it to python but looking at the regular expressions made me feel weak at the knees ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From tmohr at s.netic.de Tue Sep 16 15:45:26 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Sep 2008 21:45:26 +0200 Subject: optparse References: Message-ID: Hi, > If i call it without any parameters i get: > > opts {'verb': 'store_false'} > args [] If i call it with parameter -v i get: ./script.py -v opts {'verb': True} args [] I wonder what's wrong here. Best regards, Torsten. From gatti at dsdata.it Sat Sep 20 12:04:21 2008 From: gatti at dsdata.it (Lorenzo Gatti) Date: Sat, 20 Sep 2008 09:04:21 -0700 (PDT) Subject: XML-schema 'best practice' question References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: Sorry for pressing the send button too fast. On 20 Set, 07:59, Frank Millman wrote: > I want to introduce an element of workflow management (aka Business > Process Management) into the business/accounting system I am > developing. I used google to try to find out what the current state of > the art is. After several months of very confusing research, this is > the present situation, as best as I can figure it out. What is the state of the art of existing, working software? Can you leverage it instead of starting from scratch? For example, the existing functionality of your accounting software can be reorganized as a suite of components, web services etc. that can be embedded in workflow definitions, and/or executing a workflow engine can become a command in your application. > There is an OMG spec called BPMN, for Business Process Modeling > Notation. It provides a graphical notation [snip] > there is no standard way > of exchanging a diagram between different vendors, or of using it as > input to a workflow engine. So BPMN is mere theory. This "spec" might be a reference for evaluating actual systems, but not a standard itself. > There is an OASIS spec called WS-BPEL, for Web Services Business > Process Execution Language. It defines a language for specifying > business process behavior based on Web Services. This does have a > formal xml-based specification. However, it only covers processes > invoked via web services - it does not cover workflow-type processes > within an organisation. To try to fill this gap, a few vendors got > together and submitted a draft specification called BPEL4People. This > proposes a series of extensions to the WS-BPEL spec. It is still at > the evaluation stage. Some customers pay good money for buzzword compliance, but are you sure you want to be so bleeding edge that you care not only for WS- something specifications, but for "evaluation stage" ones? There is no need to wait for BPEL4People before designing workflow systems with human editing, approval, etc. Try looking into case studies of how BPEL is actually used in practice. > The BPMN spec includes a section which attempts to provide a mapping > between BPMN and BPEL, but the authors state that there are areas of > incompatibility, so it is not a perfect mapping. Don't worry, BPMN does not exist: there is no incompatibility. On the other hand, comparing and understanding BPMN and BPEL might reveal different purposes and weaknesses between the two systems and help you distinguish what you need, what would be cool and what is only a bad idea or a speculation. > Eventually I would like to make sense of all this, but for now I want > to focus on BPMN, and ignore BPEL. I can use wxPython to design a BPMN > diagram, but I have to invent my own method of serialising it so that > I can use it to drive the business process. For good or ill, I decided > to use xml, as it seems to offer the best chance of keeping up with > the various specifications as they evolve. If you mean to use workflow architectures to add value to your business and accounting software, your priority should be executing workflows, not editing workflow diagrams (which are a useful but unnecessary user interface layer over the actual workflow engine); making your diagrams and definitions compliant with volatile and unproven specifications should come a distant last. > I don't know if this is of any interest to anyone, but it was > therapeutic for me to try to organise my thoughts and get them down on > paper. I am not expecting any comments, but if anyone has any thoughts > to toss in, I will read them with interest. 1) There are a number of open-source or affordable workflow engines, mostly BPEL-compliant and written in Java; they should be more useful than reinventing the wheel. 2) With a good XML editor you can produce the workflow definitions, BPEL or otherwise, that your workflow engine needs, and leave the interactive diagram editor for a phase 2 that might not necessarily come; text editing might be convenient enough for your users, and for graphical output something simpler than an editor (e.g a Graphviz exporter) might be enough. 3) Maybe workflow processing can grow inside your existing accounting application without the sort of "big bang" redesign you seem to be planning; chances are that the needed objects are already in place and you only need to make workflow more explicit and add appropriate new features. Regards, Lorenzo Gatti From mnations at gmail.com Wed Sep 3 13:11:37 2008 From: mnations at gmail.com (Mudcat) Date: Wed, 3 Sep 2008 10:11:37 -0700 (PDT) Subject: Writing Unicode to database using ODBC Message-ID: In short what I'm trying to do is read a document using an xml parser and then upload that data back into a database. I've got the code more or less completed using xml.etree.ElementTree for the parser and dbi/ odbc for my db connection. To fix problems with unicode I built a work-around by mapping unicode characters to equivalent ascii characters and then encoding everything to ascii. That allowed me to build the application and debug it without running into problems printing to file or stdout to screen. However, now that I've got all that working I'd like to simply take the unicode data from the xml parser and then pass it directly into the database (which is currently set up for unicode data). I've run into problems and just can't figure why this isn't working. The breakdown is occurring when I try to execute the db query: cur.execute( query ) Fairly straightforward. I get the following error: File "atp_alt.py", line 273, in dbWrite cur.execute( query ) UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 3 79: ordinal not in range(128) I've verified that query is of type unicode by checking the type a statement or two earlier (output: ). So then I thought maybe the odbc execute just can't handle unicode data. But when I do the following command: query = query.encode('utf-8') It actually works. So apparently execute can handle unicode data. The problem now is that basically the data has been encoded twice and is in the wrong format when I pull it from the database: >>> a u'+CMGL: (\xe2\u20ac\u0153REC UNREAD\xe2\u20ac\x9d,\xe2\u20ac\x9dREC READ\xe2\u20ac\x9d,\xe2\u20ac\x9dSTO UNSENT\xe2\u20ac\x9d,\xe2\u20ac \x9dSTO SENT\xe2\u20ac\x9d,\xe2\u20ac\x9dALL\xe2\u20ac\x9d) OK' >>> print a +CMGL: (???REC UNREAD???,???REC READ???,???STO UNSENT???,???STO SENT? ??,???ALL???) OK The non-alpha characters should be double-quotes. It works correctly if I copy/paste into the editor: >>> d u'\u201cREC' >>> print d ?REC >>> d.encode('utf-8') '\xe2\x80\x9cREC' >>> type(d.encode('utf-8')) I can then decode the string to get back the proper unicode data. I can't do that with the data out of the db because it's of the wrong type for the data that it has. I think the problem is that I'm having to encode data again to force it into the database, but how can I use the odbc.execute() function without having to do that? From semanticist at gmail.com Tue Sep 16 02:30:56 2008 From: semanticist at gmail.com (Miles) Date: Tue, 16 Sep 2008 02:30:56 -0400 Subject: When do I get "multiple bases have instance lay-out conflict" error? In-Reply-To: <78f8019c0809150306t47090464vaeed3b356e76ab5b@mail.gmail.com> References: <78f8019c0809150306t47090464vaeed3b356e76ab5b@mail.gmail.com> Message-ID: On Mon, Sep 15, 2008 at 6:06 AM, Harish K Vishwanath wrote: > Hello all, > > When do we actually see the error : > > TypeError: Error when calling the metaclass bases > multiple bases have instance lay-out conflict > > > I searched the web and I could not find a correct guideline as to when such > an error could arise. One of the places said that "A new style class cannot > inherit from more than one python built-in class". That is., > >>>> class A(dict,list): > ... pass > wouldn't work. "built-in type" generally means "implemented in C", also sometimes called "extension type". >>>> class A(Exception,persistent.Persistent): > ... pass > ... > Traceback (most recent call last): > File "", line 1, in > TypeError: Error when calling the metaclass bases > multiple bases have instance lay-out conflict > > Still declaration of class A fails. Any idea? What is the exact rule when > python throws up " multiple bases have instance lay-out conflict" error? Both the Exception and ZODB Persistent objects are implemented in C, and they have different ideas for the format of the struct that holds an object's data. It can be tricky to tell by introspection whether a new-style class is implemented in Python or C. One possible heuristic: >>> class Foo(object): pass ... >>> '__module__' in vars(Foo) True >>> '__module__' in vars(Exception) False I'm not sure whether this is valid in all cases. Someone else may know of a better way. -Miles From steven at REMOVE.THIS.cybersource.com.au Mon Sep 1 05:35:37 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2008 09:35:37 GMT Subject: Know if a object member is a method References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> Message-ID: On Mon, 01 Sep 2008 10:52:10 +0200, Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi Luca, > > use type(something).__name__ , e.g. > > >>> def x(): > >>> pass > >>> class C: > >>> pass > >>> c = C() > >>> type(x).__name__ == 'function' > True > >> type(C).__name__ == 'classobj' > True > >> type(c).__name__ == 'instance' > True That's relatively fragile, since such names aren't reserved in any way. It's easy to fool a name comparison check with an accidental name collision: >>> class function(object): # not a reserved name ... pass ... >>> x = function() >>> type(x).__name__ 'function' >>> x() # must be a function then... Traceback (most recent call last): File "", line 1, in TypeError: 'function' object is not callable But not so easy to fool a type check: >>> type(x) == new.function False Of course that's not bullet-proof either. I leave it as an exercise to discover how you might break that piece of code. -- Steven From gherron at islandtraining.com Sun Sep 14 11:03:12 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 14 Sep 2008 08:03:12 -0700 Subject: How does python call OS? In-Reply-To: References: Message-ID: <48CD27B0.10504@islandtraining.com> Siegfried Heintze wrote: > I just finished reading a chapter in "Python Programming on Win32" and tried > out the pythonwin scribble application. I'm not sure if I got it right > because I could not open a new document. I tried to download the source code > as referenced in the chm file but it is corrupted. I cut and pasted from my > softcopy of the book. > > I see the next sub-chapter on wxWindows for python and the previous > sub-chapter on TK. This is looking a lot like other scripting languages > (such as perl and groovy and even java). Can python call anything directly > or does someone have to write a DLL in C/C++ that calls the function first? > Thanks! > Siegfried See the ctypes module for a method of calling any C callable function in and DLL. Gary Herron From fredrik at pythonware.com Mon Sep 22 17:20:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Sep 2008 23:20:35 +0200 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: Robert Kern wrote: > No warnings show up when importing the offending module: > > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> from sympy.mpmath import specfun > >>> > > So what could be suppressing the warning? a bug in Python 2.5, it seems: > more f1.py as = 1 as = 2 as = 3 > python f1.py f1.py:1: Warning: 'as' will become a reserved keyword in Python 2.6 f1.py:2: Warning: 'as' will become a reserved keyword in Python 2.6 f1.py:3: Warning: 'as' will become a reserved keyword in Python 2.6 > more f2.py as = 1 import os as = 3 > python f2.py f2.py:1: Warning: 'as' will become a reserved keyword in Python 2.6 A quick look in parsetok.c reveals that it sets a "handling_import" flag when it stumbles upon an "import" statement, a flag that's later used to suppress the warning message. The bug is that the flag isn't reset until the parser sees an ENDMARKER token (end of file), instead of when it sees the next NEWLINE token. (if someone wants to submit this to bugs.python.org, be my guest) From kyosohma at gmail.com Tue Sep 9 17:20:03 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 9 Sep 2008 14:20:03 -0700 (PDT) Subject: Wx Python - Code Structure & Event Handling References: Message-ID: <2ec5b585-269d-4ec5-b597-2005520c4de4@m45g2000hsb.googlegroups.com> On Sep 9, 3:05?pm, lee.walc... at gmail.com wrote: > Hi, > > I have just started writing a GUI using wxpython after finding a > limitation using Tkinter. I have read most tutorials on wxpython and > slowly becoming accustomed considering I started with the latter GUI > tool first! > I must quote first that I am a novice user of python so the issue(s) I > have may seem very obvious but please be patient with me! > > I have noticed that all the wxpython references I used for creating my > application(s) ?"cram" all the code in the frame subclass. This is > fine when you consider small applications but what about when they > grow into very complex applications? This creates my first question : > Where is it possible to find information on wxpython code practise/ > structure when considering complex larger Gui's? > > Without any reference I decided to attempt my owm method by breaking > up the top level panels in my frame as individiual class objects. and > then construct the widgets for the panels within the respective > classes. This led to my second problem, how do I use and event in one > Panel to cause an effect in the other Panel ? For example, if I have > button in one Panel and wish to change the text of a label in the > other Panel, what is the best way to do this? Should I break the code > into modules instead? > > Of course, you may explain that the way I have approached this is > completely wrong, if so please tell me, I really want to get the basic > structure right before I start making the code more complex. > > I look forward to your help > > ------------------------------------------------------------------------------------------------------------------------------------- > > I have listed some code below to help explain what concept I wish to > achieve, > > import wx > > class Frame(wx.Frame): > ? ? def __init__(self): > ? ? ? ? wx.Frame.__init__(self, None, > title="Application",size=(400,400)) > ? ? ? ? Panel1 = wx.Panel(self, -1,size=(200,200)) > ? ? ? ? Panel2 = wx.Panel(self, -1,size=(200,200)) > ? ? ? ? Sizer = wx.FlexGridSizer(2,2,5,5) > ? ? ? ? Sizer.Add(Panel1) > ? ? ? ? Sizer.Add(Panel2) > ? ? ? ? self.SetSizerAndFit(Sizer) > ? ? ? ? Util1 = Utils1(Panel1) > ? ? ? ? Util2 = Utils2(Panel2) > > class Utils1(): > ? ? def __init__(self, Panel): > ? ? ? ? button = wx.Button(Panel,-1, "Button 1") > ? ? ? ? Panel.Bind(wx.EVT_BUTTON, self.OnClick, button) > ? ? ? ? self.Label = wx.StaticText(Panel,-1, "Handler to me", > name="Lab1") > ? ? ? ? Sizer = wx.BoxSizer(wx.VERTICAL) > ? ? ? ? Sizer.Add(button) > ? ? ? ? Sizer.Add(self.Label) > ? ? ? ? Panel.SetSizerAndFit(Sizer) > > ? ? def OnClick(self, Evt): > ? ? ? ? self.Label.SetLabel("you changed me") > > class Utils2(): > ? ? def __init__(self, Panel): > ? ? ? ? self.button = wx.Button(Panel,-1, "Button 2") > ? ? ? ? Panel.Bind(wx.EVT_BUTTON, self.OnClick, self.button) > > ? ? def OnClick(self, Evt): > ? ? ? ? """ what is the easiest & accepted Method of changing the text > in > ? ? ? ? a different class instance?""" > ? ? ? ? pass > ? ? ? ? #???.SetLabel("you changed me") > > app = wx.PySimpleApp() > frame = Frame() > frame.Show() > app.MainLoop() These are good questions for the wxPython list. You'll learn a lot there: http://wxpython.org/maillist.php You'll also find the Style Guide helpful: http://wiki.wxpython.org/wxPython%20Style%20Guide In my more complex applications, I'll do the widgets in their own function, or for a wx.Notebook, I'll do each "book" in their own module by subclassing a wx.Panel object or some such. If you do that sort of thing in their own module subclasses, then the event handlers can go there too. Mike From ggpolo at gmail.com Mon Sep 1 16:26:59 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 1 Sep 2008 17:26:59 -0300 Subject: TkMessageBox - Using sys.exit() is a a great pain. Looking for other similar commands. In-Reply-To: References: Message-ID: On Mon, Sep 1, 2008 at 3:35 PM, wrote: > Hi, > > I'm using a TkMessageBox for handling some errors and displaying them > through the message boxes. > > My code is as below: > if selectedVer == strNoArchivedResults: > tkMessageBox._show("Error", \ > type='ok', icon='error', \ > message="Cannot perform Results > Comparison as no results are currently archived for this library") Note that you are not supposed to use _show, use showerror here instead. > sys.exit() > > This message box is displayed when the above comdition is met: > Using sys.exit() is a great pain since this closes my parent GUI ( the > main GUI). Remove the call to sys.exit then ? > > Please suggest some other way around. Your ask for a suggestion doesn't make much sense to me, try writing what are you trying to achieve. > > > Thanks and regards, > Rajat > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From pavlovevidence at gmail.com Sun Sep 28 19:32:09 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 28 Sep 2008 16:32:09 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <89bc2582-9d92-4924-a4c9-723c0291cac6@c65g2000hsa.googlegroups.com> On Sep 28, 2:29?pm, process wrote: > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? Although len() is spelled like a function call, in spirit it's an operator, and it behaves like any other operator in Python. Never mind why len() is an operator and not a method in Python, the point is, just as operators like + doesn't make a language less object- oriented (C++ would be very surprised to find out that it's not OO), neither do operator functions like len(). Having said that, I encourage you to understanda a language for what it is, not for whatever computer science buzzword labels it has. Carl Banks From news1234 at free.fr Thu Sep 11 16:25:22 2008 From: news1234 at free.fr (nntpman68) Date: Thu, 11 Sep 2008 22:25:22 +0200 Subject: Adding environment variables to bash. In-Reply-To: References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> Message-ID: <48c97eaf$0$12022$426a74cc@news.free.fr> >> >> doesn't exactly work for Python scripts, though: >> >> $ cat env.py >> #!/usr/bin/env python >> import os >> os.environ["TEST"] = "hello" >> >> $ . ./env.py && env | grep TEST >> import: unable to open X server `'. >> bash: os.environ[TEST]: command not found >> >> >> There's two options for the desperate ones. 1. Assuming the python script doesn't want to print anything useful ========================================================================= the python script just prints the exoprt commands and is being called via backticks from a shell code snipped being sourced with . #-------- mypythonfile.py ------------------------ #!/usr/bin/env python value = myfavourite_python_function() print 'export ENV_VAR="%s"' ^ value #--------------- end of file -------------- #----------------- my_wrapper_file.sh ------------------ `./mypythonfile.py` # file end and then you call . ./my_wrapper_file.sh 2._ Pytho script wants to display something and set a variable =================================================================== a file being invoked with . calls the python script (which will create a small file with variables to be set). then this created file is being sourced #-------- mypythonfile.py ------------------------ #!/usr/bin/env python value = myfavourite_python_function() file('my_export_commands.sh','w').write('export ENV_VAR="%s"\n' % value) #--------------- end of file -------------- #----------------- my_wrapper_file.sh ------------------ ./mypythonfile.py . ./my_export_commands.sh # file end bye N Fredrik Lundh wrote: > John Lawrence wrote: > >> You can make a command use the current shell though if you use the '.' >> command e.g.: >> >> jl > cat env.sh >> export TEST='hello' >> >> jl > ./env.sh && env | grep TEST #Doesn't set TEST in parent >> shell >> jl > . ./env.sh && env | grep TEST #Adding '. ' before the >> command uses the same shell >> TEST=hello > > doesn't exactly work for Python scripts, though: > > $ cat env.py > #!/usr/bin/env python > import os > os.environ["TEST"] = "hello" > > $ . ./env.py && env | grep TEST > import: unable to open X server `'. > bash: os.environ[TEST]: command not found > > > From ldo at geek-central.gen.new_zealand Mon Sep 29 21:50:26 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 30 Sep 2008 14:50:26 +1300 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> Message-ID: In message , r0g wrote: > You can only distribute modifications to gnuplot itself as > patches, but you can distribute it freely ... This must be some new definition of "freely" of which I'm unaware. From gherron at islandtraining.com Wed Sep 10 16:39:18 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 10 Sep 2008 13:39:18 -0700 Subject: Python and Open Office In-Reply-To: References: Message-ID: <48C83076.3030703@islandtraining.com> Greg Lindstrom wrote: > Hello, > > I would like to create and manipulate Open Office documents using > Python. I have found then UNO Python page and odfpy modules which > seem to be exactly what I need. The odfpy manual is, to me, a > confusing list of objects and methods (it's an impressive list!), but > does not have much in the way of how to use them. For example, I can > open a spreadsheet and create new pages (there's a nice example near > the back of the manual) but I can't figure out how to open an existing > spreadsheet and list the names of the individual sheets ("tabs"). > > I have written an application that access Microsoft Excel and creates > reports for work, but would like to create an Open Source version > using Open Office and release it to the community (and maybe get a > talk at PyCon :-). > > Is there someone here who can help me out, or is there an appropriate > mailing list for me to join? > > Thanks > > --greg > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list Here's a snippet of code I use to open a spreadsheet (given as a file path name), and compute and return the list of sheets it contains. It connects to an existing OpenOffice if possible, otherwise it starts OpenOffice and waits for it to accept a connection. def OpenSS(path): localContext = uno.getComponentContext() resolver = localContext.ServiceManager.createInstanceWithContext( 'com.sun.star.bridge.UnoUrlResolver', localContext ) resolveArg='uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext' # Conect to running OO; First, starting OO if necessary; try: ctx = resolver.resolve(resolveArg) except NoConnectException: os.system("ooffice '-accept=socket,host=localhost,port=2002;urp;'&") while 1: print ' waiting for OpenOffice' time.sleep(1) try: ctx = resolver.resolve(resolveArg) break except NoConnectException: pass smgr = ctx.ServiceManager desktop = smgr.createInstanceWithContext( 'com.sun.star.frame.Desktop', ctx) url = 'file://' + path component = desktop.loadComponentFromURL(url, '_default', 0, ()) sheets = [component.getSheets().getByIndex(i) for i in range(component.getSheets().getCount())] return sheets Hope this helps, Gary Herro From dmitry at athabascau.ca Thu Sep 25 11:41:04 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 15:41:04 GMT Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Dmitry S. Makovey schrieb: >> Dmitry S. Makovey wrote: >>> In my real-life case A is a proxy to B, C and D instances/objects, not >>> just one. >> >> forgot to mention that above would mean that I need to have more than one >> decorator function like AproxyB, AproxyC and AproxyD or make Aproxy >> smarter about which property of A has instance of which class etc. > > __getattr__? see, in your code you're assuming that there's only 1 property ( 'b' ) inside of A that needs proxying. In reality I have several. So in your code self._delegate should be at least a tupple or a list. Plus what you're doing - you just promiscuously passing any method not found in Proxy to self._delegate which is not what I need as I need to pass only a subset of calls, so now your code needs to acquire dictionary of "allowed" calls, and go over all self._delegates to find if any one has it which is not efficient since there IS a 1:1 mapping of A::method -> B::method so lookups shouldn't be necessary IMO (for performance reasons). > class Proxy(object): > > > def __init__(self, delegate): > self._delegate = delegate > > > def __getattr__(self, attr): > v = getattr(self._delegate, attr) > if callable(v): > class CallInterceptor(object): > def __init__(self, f): > self._f = f > > def __call__(self, *args, **kwargs): > print "Called " + str(self._f) + " with " + > str(args) + str(kwargs) > return self._f(*args, **kwargs) > return CallInterceptor(v) > return v > Decorators have *nothing* to do with this. They are syntactic sugar for > def foo(...): > ... > foo = a_decorator(foo) exactly. and in my case they would've simplified code reading/maintenance. However introduced "tight coupling" (A knows about B and be should know about A) is something that worries me and I'm trying to figure out if there is another way to use decorators for my scenario or is there another way of achieving the same thing without using decorators and without bloating up the code with alternative solution. Another way could be to use Metaclass to populate class with method upon declaration but that presents quite a bit of "special" cruft which is more than I have to do with decorators :) (but maybe it's all *necessary* ? ) From eduardo.padoan at gmail.com Sat Sep 20 10:40:25 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Sat, 20 Sep 2008 11:40:25 -0300 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: On Sat, Sep 20, 2008 at 11:26 AM, Kay Schluehr wrote: > On 20 Sep., 12:14, Fredrik Lundh wrote: >> Kay Schluehr wrote: >> > Answer: if you want to define an entity it has to be defined inside a >> > class. If you want to access an entity you have to use the dot >> > operator. Therefore Java is OO but Python is not. >> >> you're satirising the quoted author's cargo-cultish view of object >> orientation, right? >> >> > > I wonder if the OO fetish hasn't already lost much of its magic > powers. What are the most powerful fetishes these days? A year ago I > would have suspected "purely functional" but I'm not sure it has > really caught on. I think the current fetish is paralelism and erlang's share-nothing concurrency model. Or something like it. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Eduardo de Oliveira Padoan http://djangopeople.net/edcrypt/ http://stopforwarding.us/etiq.html From dudeja.rajat at gmail.com Wed Sep 24 11:22:47 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Wed, 24 Sep 2008 16:22:47 +0100 Subject: problem updating variable in a module In-Reply-To: References: Message-ID: Thanks Tim, Yes, I mean 'mod' only. But this does not work for me On Wed, Sep 24, 2008 at 4:19 PM, Tim Rowe wrote: > 2008/9/24 : > > Hi, > > > > I've a problem updating my variable in a module. > > > > In my main program, I call a function from mod1 to update a variable of > mod1 > > As soon as I update this varibale, I check it back in the mail program > but > > it the variable from mod1 does not get updated. > > > > main Program: > > **************** > > import mod1 > > a = 20 > > mod.update(a) > > print mod.a <---- does not print anything > > > > mod1 > > ******** > > a = 10 > > def update(someInt): > > global a > > a = someInt > > print a <---- this does actually print a = 20 > > I'm surprised it runs at all -- as far as I can see "mod" in > "mod.update(a)" and "print mod.a" is not defined. Did you mean "mod1"? > If I change it to that, both print statements print "20" as I'd > expect. > > I take it you do have a *really* good reason to use a global? > > -- > Tim Rowe > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regrads, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sun Sep 14 05:29:55 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Sep 2008 09:29:55 GMT Subject: Function getting a reference to its own module Message-ID: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> I have a function that needs a reference to the module object it is defined in. (For the reason why, if you care, see the thread "doctest not seeing any of my doc tests" from a week ago.) I know of two ways to deal with this problem, both of which feel unsatisfactory to me. Assume the name of the module is "Mod", then I can do either of these: def foo(): import Mod process(Mod) Disadvantage: If I change the name of the module, I have to remember to change the name of the module reference in foo() twice. def foo(): modname = foo.__module__ module = __import__(modname) process(module) Disadvantage: if I change the name of the function, I have to remember to change the reference to itself, but at least both changes are right next to each other. Assume that changing the function name or the module name are both equally likely/unlikely. Which do other people prefer? Which seems "better" to you? Are there any other alternatives? -- Steven From mnordhoff at mattnordhoff.com Fri Sep 12 02:07:16 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 12 Sep 2008 06:07:16 +0000 Subject: function return In-Reply-To: References: <48C9242E.6090509@mattnordhoff.com> Message-ID: <48CA0714.5000702@mattnordhoff.com> Gabriel Genellina wrote: > En Thu, 11 Sep 2008 10:59:10 -0300, Matt Nordhoff > escribi?: > >>> result = "%s\t%s\t%s" %(id,gene_symbol,ptms) >> >> This is very trivial, but you could change the above line to: >> >> result = "\t".join(id, gene_symbol, ptms) > > So trivial that you did not even attempt to test it, I presume. It must > obviously work... except it doesn't :) > > result = "\t".join((id, gene_symbol, ptms)) Haha, whoops. Sorry! -- From bhaarat.s at gmail.com Fri Sep 12 21:25:10 2008 From: bhaarat.s at gmail.com (bhaarat Sharma) Date: Fri, 12 Sep 2008 18:25:10 -0700 Subject: Good python web programming books In-Reply-To: <47c890dc0809121808g3c57e4b8p87166657a7b4a29e@mail.gmail.com> References: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> <47c890dc0809121808g3c57e4b8p87166657a7b4a29e@mail.gmail.com> Message-ID: <491bd2b50809121825y7c5c8577ye86c271694db47df@mail.gmail.com> That will be concentrating more on the Django framework On Fri, Sep 12, 2008 at 6:08 PM, Chris Rebert wrote: > I've heard good things about The Django Book: http://www.djangobook.com/ > - Chris > > On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma > wrote: > > Hi Guys, > > > > I am very new to python. I am looking for a good book about python web > > programming. > > > > I looked at a few online like Web Programming In Python but most are > quite > > old. > > > > If you've read a good book on python web programming can you please > suggest > > some? > > > > Thanks > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > Follow the path of the Iguana... > http://rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Wed Sep 3 09:26:21 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2008 15:26:21 +0200 Subject: Custom handler for logging References: Message-ID: Luigi Paioro wrote: > concerning the logging module, I have written a new Handler which stores > the logging messages in an SQLite database. It works well, but when I > try to use it exploiting a configuration file I have a problem since the > "class" entry does not accept a class which is not within the logging > name-space, while the class I implemented is coded in my personal module > (thus another name-space). > > Is there a workaround to allow the usage of custom handlers? Maybe http://mail.python.org/pipermail/python-list/2003-October/232762.html Peter From marco.bizzarri at gmail.com Thu Sep 18 13:37:52 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 18 Sep 2008 19:37:52 +0200 Subject: Zsi interoperability In-Reply-To: References: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <3f0d61c40809181037g2d63593fr7e69d747857a6dd6@mail.gmail.com> On Thu, Sep 18, 2008 at 7:10 PM, Dieter Maurer wrote: > "Marco Bizzarri" writes on Mon, 15 Sep 2008 20:26:27 +0200: >> On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel wrote: >> > Mailing List SVR wrote: >> >> I have to implement a soap web services from wsdl, the server is >> >> developed using oracle, is zsi or some other python library for soap >> >> interoperable with oracle soa? >> > >> > No idea, but I'd definitely try soaplib before ZSI. >> > >> > Stefan >> >> I'm working on a project where I need to write a client for SOAP with >> Attachments; I can see ZSI does not support it > > The ZSI documentation (2.0) says that SOAP attachments are supported -- > but I never tried it. > > > Dieter > -- > http://mail.python.org/mailman/listinfo/python-list > That's right; but if you look at the code, it seems like it is able to create a server which behaves in that way, but not to create a client for it. But I'm still exploring... -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From mdsherry at gmail.com Wed Sep 24 10:32:56 2008 From: mdsherry at gmail.com (mdsherry at gmail.com) Date: Wed, 24 Sep 2008 07:32:56 -0700 (PDT) Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: On Sep 24, 9:17?am, Marin Brkic wrote: > Not commercial distribution, but an academic kind of sorts - giving > the exe file to coleagues, so they can use it in their work. Giving > .py file is not an option, since due to centralized computer > maintenance, they don't (and cannot) have installed python (except the > ones that bring their own computer at work, but those are an > exception). > > As far as I know py2exe is the only option which can do such a thing > (make exe files from scripts). Is there a way to make those exe files > a little smaller (for a small script they easily go up to 5-10 mb). > > Has anyone had a situation like this ? All your inputs and suggestions > are more then welcomed. > > -- > Marin If you don't create a monolithic EXE, then most of the extra files (that make up the bulk of the size) can be shared between other converted scripts. That is, if you convert foo.py, and send the bundle to your colleague, then convert bar.py, you only need to send bar.exe, and it will run fine if they execute it in the same directory that has all the DLLs you sent with foo.exe. Another option might be to encourage them to download Portable Python, which doesn't need to be installed. Mark Sherry From richardlev at gmail.com Wed Sep 10 04:33:50 2008 From: richardlev at gmail.com (Richard Levasseur) Date: Wed, 10 Sep 2008 01:33:50 -0700 (PDT) Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> Message-ID: On Sep 9, 8:53?am, Luigi wrote: > Dear all, > > I'm writing an XML-RPC server which should be able to modify the > incoming request before dispatching it. In particular I wand to added > two fixed parameters to the method called: one is the client host > address, and the other is the user name provided as for Basic > Authentication (http://u... at www.bla-bla.com). > > To do this, at the present I've overwritten the do_POST method of > SimpleXMLRPCRequestHandler, including at a certain point this code: > > .... > data = ''.join(L) > > params, method = xmlrpclib.loads(data) > user = "unknown" > if self.headers.has_key('Authorization'): > ? # handle Basic authentication > ? (enctype, encstr) = ?self.headers.get('Authorization').split() > ? user, password = base64.standard_b64decode(encstr).split(':') > params = list(params) > params.append(self.address_string()) > params.append(user) > params = tuple(params) > data = xmlrpclib.dumps(params, methodname=method) > > (I slightly modified it to make it more readable at mail level) > > It works, but I don't really like it because it completely overwrites > the do_POST method that in the future Python releases is going to > change (I verified it). Do you know a better way to do this? > > Thanks in advance. > > Luigi I actually wrote a wsgi module for almost this -exact- use case (having to prepend a user/password to the method calls). The simple rpc server and dispatchers didn't give me enough control over the behavior, so I had to reimplement all the logic surround the loads/ dumps calls, and eventually that just turned into the bulk of the whole SimpleXMLRPCServer module. There's a lot of tight coupling in the _dispatch method, so you'll have to override, monkey patch, or reimplement it. From roy at panix.com Sun Sep 14 15:34:21 2008 From: roy at panix.com (Roy Smith) Date: Sun, 14 Sep 2008 15:34:21 -0400 Subject: Abstract class References: Message-ID: Mr.SpOOn wrote: > Well, from a SharpNote I can obtain the relative NaturalNote. So if I > have a C# I can call > > natural('C#') and get 'C' And why should you not be allowed to apply natural() to a NaturalNote? I would think it would just be an identity operator. > While in the class NaturalNote I don't need such a method, but I need > two methods to get the sharped and flatted version Well, you may need sharp() and flat() methods on all notes. Can't you do sharp('C#'), which should give you C double-sharp? > > Consider the following code: > > > > note1 = SharpNote("E4") > > note2 = NaturalNote("F4") > > if note1 == note2: > > print "the same note" > > else > > print "different notes" > > > > what should it print? > > Well, that's not so simple. I know it's not simple. I don't know what the correct answer is, or even if the problem admits to having a single universally correct answer. I'm just pointing out something you should probably think about. > Anyway, I think I need an abstract class. Or not? Hard to tell. My advice would be to start out with a single Note class and start writing code. If you get to the point where you're writing lots of conditional logic in your methods (if sharp, do this, if flat, do that), that's a hint that you may indeed need to refactor things into subclasses. The next step would be to figure out what the right hierarchy is. Offhand, I can think of three hierarchies which might be plausible: ------------------------------ Note SharpNote(Note) DoubleSharpNote(Note) FlatNote(Note) DoubleFlatNote(Note) This is a relatively flat (sorry about that) hierarchy. Note (arghhh!!) that there is no explicit NaturalNote class; notes which are not sharp or flat are just instances of Note. ------------------------------ AbstractNote NaturalNote(AbstractNote) SharpNote(AbstractNote) DoubleSharpNote(AbstractNote) FlatNote(AbstractNote) DoubleFlatNote(AbstractNote) This one sounds like what I think you've currently got in mind. ------------------------------ AbstractNote NaturalNote(AbstractNote) SharpNote(AbstractNote) DoubleSharpNote(SharpNote) FlatNote(AbstractNote) DoubleFlatNote(FlatNote) This one is similar to the above, except that the double-{sharp,flat} note are subclasses of their single versions. ------------------------------ I have no idea which is the right way to represent this. Some people would agonize over the decision for days before writing a single piece of code. My personal preference is to start small, get some code written, and let the code teach you what makes sense. If things are flowing smoothly, you probably picked a good way to organize your classes. If things are ugly and you find yourself writing lots of gnarly conditional code, that's a hint you're off on the wrong track. Don't be afraid to throw it away and start from scratch. BTW, here's another thing to think about. Is a C in a signature where C is not sharp the same as a C in a signature where it is sharp but written with a natural accidental? I have no clue, but when you figure out what answer makes sense for you, that might help you decide how you're going to organize your classes. From lists at cheimes.de Tue Sep 2 13:36:04 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 02 Sep 2008 19:36:04 +0200 Subject: source for the property function In-Reply-To: <6072EAA1-9891-4910-80B4-A26820712387@river2sea.org> References: <6072EAA1-9891-4910-80B4-A26820712387@river2sea.org> Message-ID: Rowland Smith wrote: > Anyone know where the source code for the built-in property function is > located in a python distribution? > > I would like to see how it works - mainly, how does it know which class > it is being called from? Property is not a function but a type. Properties are a common usage for the descriptor protocol. You can find the implementation of the property type in the file http://svn.python.org/projects/python/branches/release25-maint/Objects/descrobject.c Christian From arnodel at googlemail.com Sun Sep 14 05:43:45 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Sep 2008 02:43:45 -0700 (PDT) Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> Message-ID: <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> On Sep 14, 10:29?am, Steven D'Aprano wrote: > I have a function that needs a reference to the module object it is > defined in. (For the reason why, if you care, see the thread "doctest not > seeing any of my doc tests" from a week ago.) I know of two ways to deal > with this problem, both of which feel unsatisfactory to me. Assume the > name of the module is "Mod", then I can do either of these: > > def foo(): > ? ? import Mod > ? ? process(Mod) > > Disadvantage: If I change the name of the module, I have to remember to > change the name of the module reference in foo() twice. > > def foo(): > ? ? modname = foo.__module__ > ? ? module = __import__(modname) > ? ? process(module) > > Disadvantage: if I change the name of the function, I have to remember to > change the reference to itself, but at least both changes are right next > to each other. > > Assume that changing the function name or the module name are both > equally likely/unlikely. > > Which do other people prefer? Which seems "better" to you? Are there any > other alternatives? What about something like: sys.modules[__name__] ? -- Arnaud From clp at rebertia.com Thu Sep 4 16:16:23 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 4 Sep 2008 13:16:23 -0700 Subject: Converting .doc to .txt in Linux In-Reply-To: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> References: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: <47c890dc0809041316n3ed149c3lff1ef8def74fd447@mail.gmail.com> I'd recommend using one of the Word->txt converters for Linux and just running it in a shell script: * http://wvware.sourceforge.net/ * http://www.winfield.demon.nl/ No compelling reason to use Python in this instance. Right tool for the right job and all that. - Chris On Thu, Sep 4, 2008 at 12:54 PM, wrote: > Hi Everyone, > > I had previously asked a similar question, > http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gst&q=convert+doc+txt#9dc901da63d8d059 > > but at that point I was using Windows and now I am using Linux. > Basically, I have some .doc files that I need to convert into txt > files encoded in utf-8. However, win32com.client doesn't work in > Linux. > > It's been giving me quite a headache all day. Any ideas would be > greatly appreciated. > > Best, > Patrick > > #Windows Code: > import glob,os,codecs,shutil,win32com.client > from win32com.client import Dispatch > > input = '/home/pwaldo2/work/workbench/current_documents/*.doc' > input_dir = '/home/pwaldo2/work/workbench/current_documents/' > outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/' > > for doc in glob.glob1(input): > WordApp = Dispatch("Word.Application") > WordApp.Visible = 1 > WordApp.Documents.Open(doc) > WordApp.ActiveDocument.SaveAs(doc,7) > WordApp.ActiveDocument.Close() > WordApp.Quit() > > for doc in glob.glob(input): > txt_split = os.path.splitext(doc) > txt_doc = txt_split[0] + '.txt' > txt_doc_path = os.path.join(outpath,txt_doc) > doc_path = os.path.join(input_dir,doc) > shutil.copy(doc_path,txt_doc_path) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From hniksic at xemacs.org Fri Sep 12 10:01:45 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Sep 2008 16:01:45 +0200 Subject: Accessing __slots__ from C References: Message-ID: <8763p1799y.fsf@mulj.homelinux.net> Chris writes: >> descr = GetAttrString(cls,"varname"); >> offset = descr->d_member->offset; >> slotvar = (PyObject*)(((char*)obj)+offset) > > Unfortunately, I am inexperienced at this kind of thing, so I wasn't > able to get something working. Maybe someone could tell me what's > wrong with the code below (it gives the error "'struct _object' has no > member named 'd_member'")? You are getting that error because Carl forgot to cast the descriptor to the appropriate C type, in this case PyMemberDescrObject. The last line is also incorrect, I think. Try something like this: PyObject *descr = PyObject_GetAttrString(x,"attr_one"); int offset = ((PyMemberDescrObject *) descr)->d_member->offset; PyObject *slotvar = *(PyObject **)(((char *) obj) + offset); From bearophileHUGS at lycos.com Mon Sep 29 16:04:48 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 13:04:48 -0700 (PDT) Subject: Finding subsets for a robust regression References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> Message-ID: tkp... at hotmail.com: > My code follows, and it seems a bit clumsy - is there a cleaner way to do it? The code doesn't look bad. I can suggest few things: - When you have "paragraphs" of code that do something definite then the comment before them can be written without indentation, to denote it regards the whole little block. Or you can even call a subfunction (a function inside another function/method) - Finding good names for variables is important. So this code: > d = {} #identify unique instances of x and y > for xx,yy in zip(x,y): > if xx in d: > d[xx].append(yy) > else: > d[xx] = [yy] May become (untested): > # identify unique instances of x and y > d = {} > for xx, yy in zip(x, y): > if xx in d: > d[xx].append(yy) > else: > d[xx] = [yy] Or better: > # identify unique instances of seqx and seqx > d = defaultdict(list) > for x, y in izip(seqx, seqx): > d[x].append(y) Or even something like: > def unique_x(seqx, seqx): > """identify unique instances of seqx and seqx""" > result = defaultdict(list) > for x, y in izip(seqx, seqx): > result[x].append(y) > return result > ... > d = unique_x(x, y) The following line is too much heavy, it looks like a misuse of the inline if syntax: > y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else > yy[l//2] ) It was not added to python for that long lines. This looks better to me: l = len(yy) if l == 1: y_median = yy[0]) else: yy.sort() if l & 1: y_median = yy[l // 2] else: y_median = yy[l // 2 - 1] + yy[l // 2]) / 2.0 y1.append(y_median) But even better is to use a stronger library code, for example a median() able to run in O(n), and a more strong unique(), like: http://code.activestate.com/recipes/438599/ http://code.activestate.com/recipes/466330/ But using a stronger unique() this time isn't useful, so I like this compromise: # identify unique instances of seqx and seqx uniques_x = defaultdict(list) for x, y in izip(seqx, seqx): uniques_x[x].append(y) result_x = [] result_y = [] for x, ys in uniques_x.iteritems(): result_x.append(x) result_y.append(median(ys)) If you want to use the last bit of semantics of CPython you can even write that code like this: # identify unique instances of seqx and seqx uniques_x = defaultdict(list) for x, y in izip(seqx, seqx): uniques_x[x].append(y) result_x = uniques_x.keys() result_y = map(median, uniques_x.itervalues()) I think it works because keys and values are given in the same order, but in real code I tend to avoid using such subtle things. Because if you translate that code to another language, or you use another Python implementation it may not work anymore, and lot of code sooner or later becomes translated... Bye, bearophile From robert.kern at gmail.com Thu Sep 4 17:22:51 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 Sep 2008 16:22:51 -0500 Subject: why is self not passed to id()? In-Reply-To: <200809042244.54418.maric@aristote.info> References: <200809042244.54418.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez ?crit : >> class foo(list): >> __hash__ = lambda x: id(x) > > Wow ! You are really going on trouble with this, believe me there is a real > good reason for list not to be hashable. A dictionnary or set containing some > of your foo is virtually inconsistent, read carefully the manual about > prerequesites for dict keys, they *need* to be immutable. Well, that's not entirely true. They need to be not mutated while they are in the dictionary, certainly. At least not in ways that affect equality testing. In this case, one would also have to override list.__eq__ to also compare by identity, too. Then you could mutate the lists to your heart's content and the dictionary wouldn't care. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From M8R-yfto6h at mailinator.com Tue Sep 2 00:05:28 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 1 Sep 2008 21:05:28 -0700 Subject: How to print first(national) char from unicode string encoded inutf-8? References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com><7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> Message-ID: "Marco Bizzarri" wrote in message news:mailman.331.1220276398.3487.python-list at python.org... > On Mon, Sep 1, 2008 at 3:25 PM, wrote: > >> >> When I do ${urllib.unquote(c.user.firstName)} without encoding to >> latin-1 I got different chars than I will get: no ?ukasz but ? ukasz >> -- >> http://mail.python.org/mailman/listinfo/python-list > > That's crazy. "string".encode('latin1') gives you a latin1 encoded > string; latin1 is a single byte encoding, therefore taking the first > byte should be no problem. > > Have you tried: > > urlib.unquote(c.user.firstName)[0].encode('latin1') or > > urlib.unquote(c.user.firstName)[0].encode('utf8') > > I'm assuming here that the urlib.unquote(c.user.firstName) returns an > encodable string (which I'm absolutely not sure), but if it does, this > should take the first 'character'. The OP stated that the original string was "encoded in UTF-8 and urllib.quote()", so after urllib.unquote the string is in UTF-8 format. This must be decoded into a Unicode string before removing the first character: urllib.unquote(c.user.firstName).decode('utf-8')[0] The next problem is that the character in the OP's example string '?' is not present in the latin-1 encoding, but using utf-8 encoding demonstrates that the full two-byte UTF-8 encoded character is collected: >>> import urllib >>> name = urllib.quote(u'?ukasz'.encode('utf-8')) >>> name '%C5%81ukasz' >>> urllib.unquote(name).decode('utf-8')[0].encode('utf-8') '\xc5\x81' -Mark From neoedmund at gmail.com Fri Sep 5 08:20:33 2008 From: neoedmund at gmail.com (neoedmund) Date: Fri, 5 Sep 2008 05:20:33 -0700 (PDT) Subject: newbie question: how to run a python file if it is in a package References: <6icighFpi4dpU1@mid.uni-berlin.de> Message-ID: <9feb3516-097c-4458-a4d9-f02d00ce9d4b@1g2000pre.googlegroups.com> On Sep 5, 8:12?pm, "Diez B. Roggisch" wrote: > neoedmund schrieb: > > > for example: > > > X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y" > > how can I run X.py avoiding it saying such like "ImportError: No > > module named aaa.bbb"? > > > Is all runnable script must be in the default package? > > There is no such thing as a "default package" > > All imports are resolved over the "sys.path" list of directories (or eggs). > > There are various ways to modify this: > > ? - by hand. If you know X.py lives below aaa/bbb, you can get it's > ? ? __file__-attribute, and walk the way down two levels. Then add the > ? ? resulting path to sys.path. All this has to be done before any > ? ? import of aaa.bbb occurs. > > ? - modify the environment variable PYTHONPATH to contain the root of > ? ? aaa.bbb before starting the script. > > ? - write a custom .pth-file and place it into your pythno installation. > ? ? The pth-file will contain the above mentioned root path. > > ? - use setuptools to create script entry-points, and install your whole > ? ? application either fully, or as so-called egg-link. Possibly inside > ? ? a virtualenv. This would be my personally preferred method. > > ? - simply copy your wohe aaa.bbb-stuff into site-packages. Make sure you > ? ? do that whenever you change something in your code. > > Diez thanks Diez, i think your answer is almost perfect. From fredrik at pythonware.com Thu Sep 11 10:19:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 16:19:26 +0200 Subject: Python platform. In-Reply-To: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> Message-ID: carriere.jonathan at gmail.com wrote: > I wonder if there is a platform written in python. The equivalent of > the Netbeans platform http://platform.netbeans.org/ in the Python > world. Do you know such a thing? You (or maybe the Java folks) seem to have missed that platform has a rather specific meaning in computing: http://en.wikipedia.org/wiki/Platform_(computing) Given that definition, Python is pretty much a platform in itself. If you want to use Python for a specific task, you add libraries for that task. Tell us what you want to do, and we'll tell you what libraries and toolkits you might want to try. From grante at visi.com Sun Sep 14 20:29:18 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 19:29:18 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> Message-ID: <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> On 2008-09-14, Ben Finney wrote: > Astley Le Jasper writes: > >> Is it best to have it all in one script or split it into per >> site scripts that can then be called by a manager script? If >> everything is in one script would you have per site functions >> to extract the data or generic function that contain vary >> slightly depending on the site, for example >> >> import firstSiteScript >> import secondSiteScript > > First: each of these things you're importing is a "module" in > Python. A script is what I prefer, for clarity, to call a > "program": it's intended to be executed independently as the > top level of execution. > > Second: please do yourself a favour and drop the camelCaseNames. > Follow PEP 8 for style > and naming in your Python code. If he finds camelcase more readable and easier to type (as do I), how is switching to underscores "doing himself a favor"? I'm generally in favor of using a consistent naming style throughout a project, but I don't see why the naming style used in my source code should be subject to somebody else's arbitrary standard. When it comes to writing code intended for the standard library in the main Python distribution, I would certainly defer to the existing standard as defined in PEP 8. However, I don't see any reason that style should be imposed on all everybody else. -- Grant From steven at REMOVE.THIS.cybersource.com.au Wed Sep 17 21:48:27 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 01:48:27 GMT Subject: Do HTTPError objects always have a read method? Message-ID: I understood that HTTPError objects always have a read method, so they can be treated as if they were a webpage. E.g. something like this simplified snippet: address = 'http://www.yahoo.com/spamspamspamspamspam' try: conn = urllib2.urlopen(address) except urllib2.HTTPError, e: conn = e print conn.read() # Print the requested page, or the error page. But in the source code to urllib2 (Python 2.5): class HTTPError(URLError, addinfourl): """Raised when HTTP error occurs, but also acts like non-error return""" __super_init = addinfourl.__init__ def __init__(self, url, code, msg, hdrs, fp): self.code = code self.msg = msg self.hdrs = hdrs self.fp = fp self.filename = url # The addinfourl classes depend on fp being a valid file # object. In some cases, the HTTPError may not have a valid # file object. If this happens, the simplest workaround is to # not initialize the base classes. if fp is not None: self.__super_init(fp, hdrs, url) def __str__(self): return 'HTTP Error %s: %s' % (self.code, self.msg) That tells me that HTTPError objects aren't guaranteed to include a file- like interface. That makes me unhappy. Under what circumstances do HTTPError objects not have a valid file object? How common is this? Does anyone have an example of a URL that fails in that fashion? Thank you, -- Steven From bearophileHUGS at lycos.com Tue Sep 2 17:36:16 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 2 Sep 2008 14:36:16 -0700 (PDT) Subject: Renumbering References: Message-ID: <4e3e6643-ca68-4d59-b6d6-e3a358c6fc03@f36g2000hsa.googlegroups.com> Francesco Pietra, few notes: - In Python and C item numbering generally starts from 0, so you talk about column 0, 1, etc. - You can also use the Italian Python newsgroup if know Italian. - The number of lines with a particular number doesn't seem important to solve your problem. - You don't need to try to set non-proportional characters on usenet. This is a first try at a solution, you can tell us if it's correct: data = """\ ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 ATOM 3425 CA LEU B 428 142.918 87.524 78.875 1.00115.20 2SG3427 ATOM 3426 CB LEU B 428 141.559 88.057 78.392 1.00115.20 2SG3428 ATOM 3427 CG LEU B 428 140.577 88.341 79.544 1.00115.20 2SG3429 ATOM 3428 CD1 LEU B 428 141.102 89.464 80.454 1.00115.20 2SG3430 ATOM 3429 CD2 LEU B 428 139.159 88.615 79.017 1.00115.20 2SG3431 ATOM 3430 C LEU B 428 142.680 86.253 79.615 1.00115.20 2SG3432 ATOM 3431 O LEU B 428 142.725 86.226 80.842 1.00115.20 2SG3433 ATOM 3432 N SER B 429 142.432 85.155 78.878 1.00134.86 2SG3434 ATOM 3433 CA SER B 429 142.175 83.908 79.534 1.00134.86 2SG3435 ATOM 3434 CB SER B 429 141.666 82.805 78.590 1.00134.86 2SG3436 ATOM 3435 OG SER B 429 140.392 83.155 78.069 1.00134.86 2SG3437 ATOM 3436 C SER B 429 143.451 83.432 80.141 1.00134.86 2SG3438 ATOM 3437 O SER B 429 144.543 83.756 79.676 1.00134.86 2SG3439""" lines = (line.split() for line in data.splitlines()) for parts in lines: if parts[4] == "B": parts[5] = str( int(parts[5]) - 427) parts[2] = parts[2].ljust(4) print " ".join(parts) It prints: ATOM 3424 N LEU B 1 143.814 87.271 77.726 1.00115.20 2SG3426 ATOM 3425 CA LEU B 1 142.918 87.524 78.875 1.00115.20 2SG3427 ATOM 3426 CB LEU B 1 141.559 88.057 78.392 1.00115.20 2SG3428 ATOM 3427 CG LEU B 1 140.577 88.341 79.544 1.00115.20 2SG3429 ATOM 3428 CD1 LEU B 1 141.102 89.464 80.454 1.00115.20 2SG3430 ATOM 3429 CD2 LEU B 1 139.159 88.615 79.017 1.00115.20 2SG3431 ATOM 3430 C LEU B 1 142.680 86.253 79.615 1.00115.20 2SG3432 ATOM 3431 O LEU B 1 142.725 86.226 80.842 1.00115.20 2SG3433 ATOM 3432 N SER B 2 142.432 85.155 78.878 1.00134.86 2SG3434 ATOM 3433 CA SER B 2 142.175 83.908 79.534 1.00134.86 2SG3435 ATOM 3434 CB SER B 2 141.666 82.805 78.590 1.00134.86 2SG3436 ATOM 3435 OG SER B 2 140.392 83.155 78.069 1.00134.86 2SG3437 ATOM 3436 C SER B 2 143.451 83.432 80.141 1.00134.86 2SG3438 ATOM 3437 O SER B 2 144.543 83.756 79.676 1.00134.86 2SG3439 Your data is probably in a file, so you have to change the first line of the code: lines = (line.split() for line in open("namefile.txt")) If your output file must to hard-coded columns (and generally those files don't need such property) then you have to make that code of mine more complex... Bye, bearophile From gagsl-py2 at yahoo.com.ar Tue Sep 16 04:02:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 05:02:08 -0300 Subject: PyArg_ParseTuple for parsing list and dictionary arguments References: <207312b70809150258n57240c25me70ad03b6339b579@mail.gmail.com> Message-ID: En Mon, 15 Sep 2008 06:58:48 -0300, Pau Freixes escribi?: > Hi to all, > > What's the best way for parse one list or dict argument with > PyArg_ParseTuple Function ? > > If I have this python code : > > import example > > example.test("hellow", ["a", "b"], { "a" : 1 }) > > The c extension for implementation test function must be like this : > > static PyObject * test( PyObject *self, PyObject *args) > { > PyObject * dict, * list; > char * string; > > PyArg_ParseTuple(args, "sOO", string, dict, list); > ...... > } I don't understand the actual question - the example looks fine, what's your problem? Do you want to check the object types? Use PyDict_Check / PyList_Check. -- Gabriel Genellina From fredrik at pythonware.com Fri Sep 12 12:35:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 18:35:53 +0200 Subject: lacking follow-through In-Reply-To: References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> Message-ID: Steve Holden wrote: > The defence rests. can you please stop quoting that guy, so we don't have to killfile you as well... From timr at probo.com Thu Sep 11 01:32:00 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 11 Sep 2008 05:32:00 GMT Subject: universal unicode font for reportlab References: Message-ID: Duncan Booth wrote: > >Laszlo Nagy wrote: > >> I need to use HTML anyway. I realized that universal unicode fonts are >> above 5MB in size. The report would be a 10KB PDF, but I need to embed >> the font before I can send it to anyone. Since some reports needs to be >> sent in emails, I need to use something else. I cannot be sending 10MB >> emails for "one page" reports. >> >I thought that usually when you embed a font in a PDF only the glyphs which >are actually used in the document get embedded. Unfortunately a quick test >with reportlab seems to show that it doesn't do that optimisation: it looks >as though it just embeds the entire font. No, it does subsetting. There was a debate a year or two ago on the reportlab list about how the font subset should be named in the resulting PDF file. Is it possible you have an older release? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From rhamph at gmail.com Tue Sep 23 17:00:25 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 23 Sep 2008 14:00:25 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: On Sep 22, 7:13?pm, process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. Eliminating tail calls affects the semantics of your program (by changing memory complexity). As an optimization, it's a side-effect of the implementation, which is a particularly nasty kind of side- effect. Even if guaranteed it's fairly subtle. "return x()" would be optimized while "return x() + 1" would not. Or maybe you're calling a function that uses a wrapper and the wrapper isn't tweaked right to be optimized. Recursion in general can be very useful, but not tail-recursion. The only time it's not trivial to convert tail-recursion into a loop is when it involves multiple functions, but even that can be done if you know how. From bearophileHUGS at lycos.com Sun Sep 28 16:19:22 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 28 Sep 2008 13:19:22 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: sotirac: > random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 elements But note that's without replacement. So if you want really random numbers you can do this: >>> from string import digits >>> from random import choice >>> "".join(choice(digits) for d in xrange(5)) '93898' If you need more speed you can invent other solutions, like (but I don't know if it's faster): >>> from random import shuffle >>> ldigits = list(digits) >>> ldigits ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> shuffle(ldigits) >>> ldigits ['3', '8', '6', '4', '9', '7', '5', '2', '0', '1'] >>> "".join(ldigits[:5]) '38649' But this may be the most efficient way: >>> from random import randrange >>> str(randrange(100000)).zfill(5) '37802' Bye, bearophile From mhuening at zedat.fu-berlin.de Sun Sep 7 11:17:14 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Sun, 07 Sep 2008 17:17:14 +0200 Subject: [ANN] pysqlite 2.5.0 released In-Reply-To: References: Message-ID: <6ii9jbFqoe2eU1@mid.uni-berlin.de> Hi, > - - Connection.enable_load_extension(enabled) to allow/disallow extension > loading. Allows you to use fulltext search extension, for example ;-) The following code (from the docs) produces an error: from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:") # Load the fulltext search extension con.enable_load_extension(True) con.execute("select load_extension('./fts3.so')") con.enable_load_extension(False) Error is: con.execute("select load_extension('./fts3.so')") pysqlite2._sqlite.OperationalError: Das angegebene Modul wurde nicht gefunden. Where should I look for the module? Matthias From deets at nospam.web.de Wed Sep 10 04:00:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 10:00:35 +0200 Subject: I want to use a C++ library from Python In-Reply-To: References: Message-ID: <6ipd53FrptpiU1@mid.uni-berlin.de> Anders Eriksson schrieb: > Hello, > > I have a C++ library compiled as Windows DLL's. It consists of 32 .h and 1 > .lib and 1 .dll files. I don't have the source code. > > How can I create a Python module from these files? Did you bother googling? http://www.google.de/search?q=python+c%2B%2B&ie=utf-8&oe=utf-8 Diez From fredrik at pythonware.com Sun Sep 7 04:18:57 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 07 Sep 2008 10:18:57 +0200 Subject: Directory creation In-Reply-To: <275302.58315.qm@web7908.mail.in.yahoo.com> References: <275302.58315.qm@web7908.mail.in.yahoo.com> Message-ID: srinivasan srinivas wrote: > Can someone tell me is there any module available to create directories?? > > I tried os, tempfile. > I was facing some issues with os.mkdir(). The mode setting was not proper with this method. > > I created the directory 'stdin' with '0700' mode using os.mkdir() method. > > $> ls -alR stdin/ > stdin/: > total 12 > drwx--S--- 2 munisams munisams 4096 Sep 3 02:00 . > > What is that 'S' in the group permission field?? David Wright explained why this is the expected behaviour last time you posted about this: http://groups.google.com/group/comp.lang.python/msg/f6a91447f1739e66 From bignose+hates-spam at benfinney.id.au Thu Sep 4 21:12:33 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 05 Sep 2008 11:12:33 +1000 Subject: Python test case management system? References: Message-ID: <87iqtbmm4e.fsf@benfinney.id.au> Mudcat writes: > Does anyone know of a good test case management system written in > python, or possibly another application (either open source or > commercial) that can be extended using python? What would the behaviour of such a system be? In other words, what is a "test case management system" in terms of the things that it does? -- \ ?Dad always thought laughter was the best medicine, which I | `\ guess is why several of us died of tuberculosis.? ?Jack Handey | _o__) | Ben Finney From tjreedy at udel.edu Wed Sep 10 20:46:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 10 Sep 2008 20:46:50 -0400 Subject: Reading binary data In-Reply-To: <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> References: <05577cdf-9d53-4e80-94c9-a7b771976887@a1g2000hsb.googlegroups.com> <3f1d26af-c1da-44ad-8dc2-45540d585d44@w7g2000hsa.googlegroups.com> <57ae1385-87d6-47f8-b683-9f5adc0876c8@k37g2000hsf.googlegroups.com> Message-ID: Aaron Scott wrote: > Taking everything into consideration, my code is now: > > import struct > file = open("test.gde", "rb") > signature = file.read(3) > version, attr_count = struct.unpack('II', file.read(8)) > print signature, version, attr_count > for idx in xrange(attr_count): > attr_id, attr_val_len = struct.unpack('II', file.read(8)) > attr_val = file.read(attr_val_len) > print attr_id, attr_val_len, attr_val > file.close() > > which gives a result of: > > GDE 2 2 > 1 4 ? > 2 4 ? ? > > Essentially, the same results I was originally getting : It appears that your 4-byte attribute values are not what you were expecting. Do you have separate info on the supposed contents? In any case, I would print repr(attr_val) and even for c in attr_val: print(ord(c)). tjr From febkimbleox at gmail.com Sat Sep 27 07:15:05 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:15:05 -0700 (PDT) Subject: 3d sex 3d sex comics 3d sex comic 3d sex games - Free Message-ID: 3d . . . *******CLICK HERE******** http://vids365.cn/3d ***************************** . . . . . . . . . . . . It was a pretty standard sort of service but the vicar kept 3d reasonably informal and cheerful and most importantly from my point of view short. It was a pretty standard sort of service but the vicar kept sex reasonably informal and cheerful and most importantly from my point of view short. It was a pretty standard sort of service but the vicar kept 3d reasonably informal and cheerful and most importantly from my point of view short. ? sex lowered sex head and frowned. ? comics lowered comics head and frowned. ? 3d lowered 3d head and frowned. ? sex lowered sex head and frowned. ? comic lowered comic head and frowned. ? 3d lowered 3d head and frowned. ? sex lowered sex head and frowned. ? games lowered games head and frowned. ? free lowered free head and frowned. ? 3d lowered 3d head and frowned. ? sex lowered sex head and frowned. ? games lowered games head and frowned. Inflamed with lust 3d moved my hand inside 3d ?s panties and eased them down. Inflamed with lust cartoon moved my hand inside cartoon ?s panties and eased them down. Inflamed with lust sex moved my hand inside sex ?s panties and eased them down. Inflamed with lust sex moved my hand inside sex ?s panties and eased them down. Inflamed with lust igre moved my hand inside igre ?s panties and eased them down. Inflamed with lust 3d moved my hand inside 3d ?s panties and eased them down. Inflamed with lust 3d moved my hand inside 3d ?s panties and eased them down. Inflamed with lust anime moved my hand inside anime ?s panties and eased them down. Inflamed with lust sex moved my hand inside sex ?s panties and eased them down. Inflamed with lust 3d moved my hand inside 3d ?s panties and eased them down. Inflamed with lust sex moved my hand inside sex ?s panties and eased them down. Inflamed with lust cartoons moved my hand inside cartoons ?s panties and eased them down. ?She kissed 3d lips and said, ?You were thinking of Rebecca weren?t you? 3d hope 3d can build as many wonderful memories as the two of 3d did. ?She kissed sex lips and said, ?You were thinking of Rebecca weren?t you? sex hope sex can build as many wonderful memories as the two of sex did. ?She kissed movies lips and said, ?You were thinking of Rebecca weren?t you? movies hope movies can build as many wonderful memories as the two of movies did. ?She kissed 3d lips and said, ?You were thinking of Rebecca weren?t you? 3d hope 3d can build as many wonderful memories as the two of 3d did. ?She kissed comic lips and said, ?You were thinking of Rebecca weren?t you? comic hope comic can build as many wonderful memories as the two of comic did. ?She kissed sex lips and said, ?You were thinking of Rebecca weren?t you? sex hope sex can build as many wonderful memories as the two of sex did. ?She kissed 3d lips and said, ?You were thinking of Rebecca weren?t you? 3d hope 3d can build as many wonderful memories as the two of 3d did. ?She kissed sex lips and said, ?You were thinking of Rebecca weren?t you? sex hope sex can build as many wonderful memories as the two of sex did. ?She kissed game lips and said, ?You were thinking of Rebecca weren?t you? game hope game can build as many wonderful memories as the two of game did. ?She kissed 3d lips and said, ?You were thinking of Rebecca weren?t you? 3d hope 3d can build as many wonderful memories as the two of 3d did. ?She kissed toon lips and said, ?You were thinking of Rebecca weren?t you? toon hope toon can build as many wonderful memories as the two of toon did. ?She kissed sex lips and said, ?You were thinking of Rebecca weren?t you? sex hope sex can build as many wonderful memories as the two of sex did. 3d seemed thrilled and put 3d on immediately before introducing 3d to 3d friends, some of whom 3d kind of knew from chatting online. alien seemed thrilled and put alien on immediately before introducing alien to alien friends, some of whom alien kind of knew from chatting online. sex seemed thrilled and put sex on immediately before introducing sex to sex friends, some of whom sex kind of knew from chatting online. 3d seemed thrilled and put 3d on immediately before introducing 3d to 3d friends, some of whom 3d kind of knew from chatting online. animation seemed thrilled and put animation on immediately before introducing animation to animation friends, some of whom animation kind of knew from chatting online. sex seemed thrilled and put sex on immediately before introducing sex to sex friends, some of whom sex kind of knew from chatting online. movie seemed thrilled and put movie on immediately before introducing movie to movie friends, some of whom movie kind of knew from chatting online. free seemed thrilled and put free on immediately before introducing free to free friends, some of whom free kind of knew from chatting online. 3d seemed thrilled and put 3d on immediately before introducing 3d to 3d friends, some of whom 3d kind of knew from chatting online. sex seemed thrilled and put sex on immediately before introducing sex to sex friends, some of whom sex kind of knew from chatting online. 3d seemed thrilled and put 3d on immediately before introducing 3d to 3d friends, some of whom 3d kind of knew from chatting online. family seemed thrilled and put family on immediately before introducing family to family friends, some of whom family kind of knew from chatting online. She trembled from head to toe and purred, ?Darling, sex love playing with sex cock. She trembled from head to toe and purred, ?Darling, 3d love playing with 3d cock. She trembled from head to toe and purred, ?Darling, hentai love playing with hentai cock. She trembled from head to toe and purred, ?Darling, sex love playing with sex cock. She trembled from head to toe and purred, ?Darling, 3d love playing with 3d cock. She trembled from head to toe and purred, ?Darling, sex love playing with sex cock. She trembled from head to toe and purred, ?Darling, villa love playing with villa cock. She trembled from head to toe and purred, ?Darling, free love playing with free cock. She trembled from head to toe and purred, ?Darling, 3d love playing with 3d cock. She trembled from head to toe and purred, ?Darling, cartoon love playing with cartoon cock. She trembled from head to toe and purred, ?Darling, sex love playing with sex cock. She trembled from head to toe and purred, ?Darling, 3d love playing with 3d cock. ?Even worse, he?s put sex around school that I?m just a baby and frigid?. ?Even worse, he?s put cartoon around school that I?m just a baby and frigid?. ?Even worse, he?s put free around school that I?m just a baby and frigid?. ?Even worse, he?s put online around school that I?m just a baby and frigid?. ?Even worse, he?s put 3d around school that I?m just a baby and frigid?. ?Even worse, he?s put sex around school that I?m just a baby and frigid?. ?Even worse, he?s put 3d around school that I?m just a baby and frigid?. ?Even worse, he?s put sex around school that I?m just a baby and frigid?. ?Even worse, he?s put toons around school that I?m just a baby and frigid?. ?Even worse, he?s put 3d around school that I?m just a baby and frigid?. ?Even worse, he?s put sex around school that I?m just a baby and frigid?. ?Even worse, he?s put worlds around school that I?m just a baby and frigid?. Oooh honey, 3d just adore the way 3d make love to me. Oooh honey, monster just adore the way monster make love to me. Oooh honey, sex just adore the way sex make love to me. Oooh honey, 3d just adore the way 3d make love to me. Oooh honey, sex just adore the way sex make love to me. Oooh honey, villa just adore the way villa make love to me. Oooh honey, 2 just adore the way 2 make love to me. Oooh honey, beta just adore the way beta make love to me. Oooh honey, 3d just adore the way 3d make love to me. Oooh honey, sex just adore the way sex make love to me. Oooh honey, galleries just adore the way galleries make love to me. Oooh honey, sex just adore the way sex make love to me. ?I?ll gladly do 3d myself?. ?I?ll gladly do 3d myself?. ?I?ll gladly do animation myself?. ?I?ll gladly do sex myself?. ?I?ll gladly do 3d myself?. ?I?ll gladly do incest myself?. ?I?ll gladly do sex myself?. ?I?ll gladly do 3d myself?. ?I?ll gladly do virtual myself?. ?I?ll gladly do sex myself?. ?I?ll gladly do free myself?. ?I?ll gladly do 3d myself?. Next sex gently pinched it, causing an almost immediately earth- shattering climax to surge through sex body. Next game gently pinched it, causing an almost immediately earth-shattering climax to surge through game body. Next 3d gently pinched it, causing an almost immediately earth-shattering climax to surge through 3d body. Next sex gently pinched it, causing an almost immediately earth-shattering climax to surge through sex body. Next toon gently pinched it, causing an almost immediately earth-shattering climax to surge through toon body. Next 3d gently pinched it, causing an almost immediately earth-shattering climax to surge through 3d body. Next sex gently pinched it, causing an almost immediately earth-shattering climax to surge through sex body. Next villa gently pinched it, causing an almost immediately earth-shattering climax to surge through villa body. Next 2 gently pinched it, causing an almost immediately earth- shattering climax to surge through 2 body. Next crazy gently pinched it, causing an almost immediately earth-shattering climax to surge through crazy body. Next 3d gently pinched it, causing an almost immediately earth-shattering climax to surge through 3d body. Next sex gently pinched it, causing an almost immediately earth-shattering climax to surge through sex body. As 3d talked with 3d , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as 3d went to an all boys school. As sex talked with sex , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as sex went to an all boys school. As stories talked with stories , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as stories went to an all boys school. As 3d talked with 3d , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as 3d went to an all boys school. As sex talked with sex , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as sex went to an all boys school. As story talked with story , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as story went to an all boys school. As 3d talked with 3d , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as 3d went to an all boys school. As animated talked with animated , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as animated went to an all boys school. As sex talked with sex , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as sex went to an all boys school. As 3d talked with 3d , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as 3d went to an all boys school. As sex talked with sex , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as sex went to an all boys school. As villa talked with villa , the tone became a bit more intimate, mainly on the subject of my girlfriends which was a fairly short topic as villa went to an all boys school. She thought about what part of dessert tool was going to sample first. She thought about what part of dessert 3d was going to sample first. She thought about what part of dessert sex was going to sample first. She thought about what part of dessert videos was going to sample first. She thought about what part of dessert anime was going to sample first. She thought about what part of dessert 3d was going to sample first. She thought about what part of dessert sex was going to sample first. She thought about what part of dessert 3d was going to sample first. She thought about what part of dessert sex was going to sample first. She thought about what part of dessert 3d was going to sample first. She thought about what part of dessert fantasy was going to sample first. She thought about what part of dessert sex was going to sample first. 3d could see a movement in the shadows behind one of the filing cabinets and found 3d crouched down behind it. teacher could see a movement in the shadows behind one of the filing cabinets and found teacher crouched down behind it. sex could see a movement in the shadows behind one of the filing cabinets and found sex crouched down behind it. 3d could see a movement in the shadows behind one of the filing cabinets and found 3d crouched down behind it. sex could see a movement in the shadows behind one of the filing cabinets and found sex crouched down behind it. animation could see a movement in the shadows behind one of the filing cabinets and found animation crouched down behind it. 3d could see a movement in the shadows behind one of the filing cabinets and found 3d crouched down behind it. anime could see a movement in the shadows behind one of the filing cabinets and found anime crouched down behind it. movie could see a movement in the shadows behind one of the filing cabinets and found movie crouched down behind it. alien could see a movement in the shadows behind one of the filing cabinets and found alien crouched down behind it. busty could see a movement in the shadows behind one of the filing cabinets and found busty crouched down behind it. sex could see a movement in the shadows behind one of the filing cabinets and found sex crouched down behind it. 3d could see a movement in the shadows behind one of the filing cabinets and found 3d crouched down behind it. She placed the last dish in the rack and asked, ?What shall sex do now, baby. She placed the last dish in the rack and asked, ?What shall comix do now, baby. She placed the last dish in the rack and asked, ?What shall free do now, baby. She placed the last dish in the rack and asked, ?What shall 3d do now, baby. She placed the last dish in the rack and asked, ?What shall cartoon do now, baby. She placed the last dish in the rack and asked, ?What shall sex do now, baby. She placed the last dish in the rack and asked, ?What shall clips do now, baby. She placed the last dish in the rack and asked, ?What shall free do now, baby. She placed the last dish in the rack and asked, ?What shall online do now, baby. She placed the last dish in the rack and asked, ?What shall 3d do now, baby. She placed the last dish in the rack and asked, ?What shall sex do now, baby. She placed the last dish in the rack and asked, ?What shall games do now, baby. quality had huge tits, huge. 3d had huge tits, huge. cartoon had huge tits, huge. sex had huge tits, huge. movies had huge tits, huge. 3d had huge tits, huge. sex had huge tits, huge. 3d had huge tits, huge. sex had huge tits, huge. gallery had huge tits, huge. 3d had huge tits, huge. sex had huge tits, huge. ?Mandy giggled and replied, ?Yeah girls did. ?Mandy giggled and replied, ?Yeah young did. ?Mandy giggled and replied, ?Yeah 3d did. ?Mandy giggled and replied, ?Yeah sex did. ?Mandy giggled and replied, ?Yeah 3d did. ?Mandy giggled and replied, ?Yeah beach did. ?Mandy giggled and replied, ?Yeah sex did. ?Mandy giggled and replied, ?Yeah 3d did. ?Mandy giggled and replied, ?Yeah sex did. ?Mandy giggled and replied, ?Yeah drawings did. ?Mandy giggled and replied, ?Yeah 3d did. ?Mandy giggled and replied, ?Yeah teen did. ?Mandy giggled and replied, ?Yeah sex did. Does free have nice tits or doesn't she? Does 3d have nice tits or doesn't she? Does adult have nice tits or doesn't she? Does sex have nice tits or doesn't she? Does interactive have nice tits or doesn't she? Does deskmates have nice tits or doesn't she? Does 3d have nice tits or doesn't she? Does lesbian have nice tits or doesn't she? Does sex have nice tits or doesn't she? Does 3d have nice tits or doesn't she? Does sex have nice tits or doesn't she? Does simulator have nice tits or doesn't she? ?Mandy ran 3d hands down 3d ?s strong but gentle right arm noting a tattoo on 3d right bicep. ?Mandy ran sex hands down sex ?s strong but gentle right arm noting a tattoo on sex right bicep. ?Mandy ran with hands down with ?s strong but gentle right arm noting a tattoo on with right bicep. ?Mandy ran animals hands down animals ?s strong but gentle right arm noting a tattoo on animals right bicep. ?Mandy ran 3d hands down 3d ?s strong but gentle right arm noting a tattoo on 3d right bicep. ?Mandy ran taboo hands down taboo ?s strong but gentle right arm noting a tattoo on taboo right bicep. ?Mandy ran sex hands down sex ?s strong but gentle right arm noting a tattoo on sex right bicep. ?Mandy ran adult hands down adult ?s strong but gentle right arm noting a tattoo on adult right bicep. ?Mandy ran sex hands down sex ?s strong but gentle right arm noting a tattoo on sex right bicep. ?Mandy ran party hands down party ?s strong but gentle right arm noting a tattoo on party right bicep. ?Mandy ran 3d hands down 3d ?s strong but gentle right arm noting a tattoo on 3d right bicep. ?Mandy ran family hands down family ?s strong but gentle right arm noting a tattoo on family right bicep. sex looked back over sex shoulder at him, one big breast pointing to the left. 3d looked back over 3d shoulder at him, one big breast pointing to the left. hot looked back over hot shoulder at him, one big breast pointing to the left. 3d looked back over 3d shoulder at him, one big breast pointing to the left. sex looked back over sex shoulder at him, one big breast pointing to the left. 3d looked back over 3d shoulder at him, one big breast pointing to the left. anime looked back over anime shoulder at him, one big breast pointing to the left. sex looked back over sex shoulder at him, one big breast pointing to the left. podcasts looked back over podcasts shoulder at him, one big breast pointing to the left. video looked back over video shoulder at him, one big breast pointing to the left. 3d looked back over 3d shoulder at him, one big breast pointing to the left. anime looked back over anime shoulder at him, one big breast pointing to the left. sex couldn?t take sex any longer, sex growled, ?Here sex cums baby,? as sex cock exploded sending cum down sex throat. vids couldn?t take vids any longer, vids growled, ?Here vids cums baby,? as vids cock exploded sending cum down vids throat. 3d couldn?t take 3d any longer, 3d growled, ?Here 3d cums baby,? as 3d cock exploded sending cum down 3d throat. mom couldn?t take mom any longer, mom growled, ?Here mom cums baby,? as mom cock exploded sending cum down mom throat. sex couldn?t take sex any longer, sex growled, ?Here sex cums baby,? as sex cock exploded sending cum down sex throat. 3d couldn?t take 3d any longer, 3d growled, ?Here 3d cums baby,? as 3d cock exploded sending cum down 3d throat. sex couldn?t take sex any longer, sex growled, ?Here sex cums baby,? as sex cock exploded sending cum down sex throat. anime couldn?t take anime any longer, anime growled, ?Here anime cums baby,? as anime cock exploded sending cum down anime throat. 3d couldn?t take 3d any longer, 3d growled, ?Here 3d cums baby,? as 3d cock exploded sending cum down 3d throat. animal couldn?t take animal any longer, animal growled, ?Here animal cums baby,? as animal cock exploded sending cum down animal throat. sex couldn?t take sex any longer, sex growled, ?Here sex cums baby,? as sex cock exploded sending cum down sex throat. 3d couldn?t take 3d any longer, 3d growled, ?Here 3d cums baby,? as 3d cock exploded sending cum down 3d throat. He rubbed up against sex moist, soft breasts and positioned himself in front of her. He rubbed up against pics moist, soft breasts and positioned himself in front of her. He rubbed up against aunts moist, soft breasts and positioned himself in front of her. He rubbed up against sex moist, soft breasts and positioned himself in front of her. He rubbed up against lessons moist, soft breasts and positioned himself in front of her. He rubbed up against 3d moist, soft breasts and positioned himself in front of her. He rubbed up against 3d moist, soft breasts and positioned himself in front of her. He rubbed up against nurse moist, soft breasts and positioned himself in front of her. He rubbed up against sex moist, soft breasts and positioned himself in front of her. He rubbed up against best moist, soft breasts and positioned himself in front of her. He rubbed up against 3d moist, soft breasts and positioned himself in front of her. He rubbed up against sex moist, soft breasts and positioned himself in front of her. He rubbed up against crazy moist, soft breasts and positioned himself in front of her. Mandy then climbed off of world and lay down beside him. Mandy then climbed off of 3d and lay down beside him. Mandy then climbed off of xxx and lay down beside him. Mandy then climbed off of sex and lay down beside him. Mandy then climbed off of cartoons and lay down beside him. Mandy then climbed off of free and lay down beside him. Mandy then climbed off of interactive and lay down beside him. Mandy then climbed off of 3d and lay down beside him. Mandy then climbed off of sex and lay down beside him. Mandy then climbed off of gay and lay down beside him. Mandy then climbed off of 3d and lay down beside him. Mandy then climbed off of sex and lay down beside him. He only stayed a few days, though, since gay definitely didn't want gay to run into Tammy. He only stayed a few days, though, since 3d definitely didn't want 3d to run into Tammy. He only stayed a few days, though, since sex definitely didn't want sex to run into Tammy. He only stayed a few days, though, since comics definitely didn't want comics to run into Tammy. He only stayed a few days, though, since 3d definitely didn't want 3d to run into Tammy. He only stayed a few days, though, since anal definitely didn't want anal to run into Tammy. He only stayed a few days, though, since sex definitely didn't want sex to run into Tammy. He only stayed a few days, though, since 3d definitely didn't want 3d to run into Tammy. He only stayed a few days, though, since blonde definitely didn't want blonde to run into Tammy. He only stayed a few days, though, since cartoon definitely didn't want cartoon to run into Tammy. He only stayed a few days, though, since sex definitely didn't want sex to run into Tammy. He only stayed a few days, though, since 3d definitely didn't want 3d to run into Tammy. Her soft hands grabbed girls cock as girls leaned over and began licking girls juices off girls flaccid member. Her soft hands grabbed sex cock as sex leaned over and began licking sex juices off sex flaccid member. Her soft hands grabbed 3d cock as 3d leaned over and began licking 3d juices off 3d flaccid member. Her soft hands grabbed sex cock as sex leaned over and began licking sex juices off sex flaccid member. Her soft hands grabbed positions cock as positions leaned over and began licking positions juices off positions flaccid member. Her soft hands grabbed 3d cock as 3d leaned over and began licking 3d juices off 3d flaccid member. Her soft hands grabbed tentacle cock as tentacle leaned over and began licking tentacle juices off tentacle flaccid member. Her soft hands grabbed sex cock as sex leaned over and began licking sex juices off sex flaccid member. Her soft hands grabbed free cock as free leaned over and began licking free juices off free flaccid member. Her soft hands grabbed 3d cock as 3d leaned over and began licking 3d juices off 3d flaccid member. Her soft hands grabbed sex cock as sex leaned over and began licking sex juices off sex flaccid member. Her soft hands grabbed comics cock as comics leaned over and began licking comics juices off comics flaccid member. Tammy and Joe have since moved for sex company and sex miss my extra pussy. Tammy and Joe have since moved for in company and in miss my extra pussy. Tammy and Joe have since moved for 3d company and 3d miss my extra pussy. Tammy and Joe have since moved for 3d company and 3d miss my extra pussy. Tammy and Joe have since moved for child company and child miss my extra pussy. Tammy and Joe have since moved for sex company and sex miss my extra pussy. Tammy and Joe have since moved for 3d company and 3d miss my extra pussy. Tammy and Joe have since moved for gay company and gay miss my extra pussy. Tammy and Joe have since moved for sex company and sex miss my extra pussy. Tammy and Joe have since moved for 3d company and 3d miss my extra pussy. Tammy and Joe have since moved for princess company and princess miss my extra pussy. Tammy and Joe have since moved for sex company and sex miss my extra pussy. After that games began to encircle the clit with games thumb as games digit slid into games hole. After that 3d began to encircle the clit with 3d thumb as 3d digit slid into 3d hole. After that young began to encircle the clit with young thumb as young digit slid into young hole. After that sex began to encircle the clit with sex thumb as sex digit slid into sex hole. After that crazy began to encircle the clit with crazy thumb as crazy digit slid into crazy hole. After that xxx began to encircle the clit with xxx thumb as xxx digit slid into xxx hole. After that 3d began to encircle the clit with 3d thumb as 3d digit slid into 3d hole. After that sex began to encircle the clit with sex thumb as sex digit slid into sex hole. After that 3d began to encircle the clit with 3d thumb as 3d digit slid into 3d hole. After that sex began to encircle the clit with sex thumb as sex digit slid into sex hole. After that comic began to encircle the clit with comic thumb as comic digit slid into comic hole. After that pregnant began to encircle the clit with pregnant thumb as pregnant digit slid into pregnant hole. It wasn't long and 3d visitor groaned and began shooting 3d cum into 3d mouth. It wasn't long and sex visitor groaned and began shooting sex cum into sex mouth. It wasn't long and games visitor groaned and began shooting games cum into games mouth. It wasn't long and free visitor groaned and began shooting free cum into free mouth. It wasn't long and 3d visitor groaned and began shooting 3d cum into 3d mouth. It wasn't long and sex visitor groaned and began shooting sex cum into sex mouth. It wasn't long and incest visitor groaned and began shooting incest cum into incest mouth. It wasn't long and cartoon visitor groaned and began shooting cartoon cum into cartoon mouth. It wasn't long and sex visitor groaned and began shooting sex cum into sex mouth. It wasn't long and 3d visitor groaned and began shooting 3d cum into 3d mouth. It wasn't long and free visitor groaned and began shooting free cum into free mouth. It wasn't long and 3d visitor groaned and began shooting 3d cum into 3d mouth. It wasn't long and cyber visitor groaned and began shooting cyber cum into cyber mouth. sex then wondered, ?If sex would want that, a new beginning of sex lives together??His body ached for Mandy. hentai then wondered, ?If hentai would want that, a new beginning of hentai lives together??His body ached for Mandy. sex then wondered, ?If sex would want that, a new beginning of sex lives together??His body ached for Mandy. 3d then wondered, ?If 3d would want that, a new beginning of 3d lives together??His body ached for Mandy. 3d then wondered, ?If 3d would want that, a new beginning of 3d lives together??His body ached for Mandy. computer then wondered, ?If computer would want that, a new beginning of computer lives together??His body ached for Mandy. sex then wondered, ?If sex would want that, a new beginning of sex lives together??His body ached for Mandy. 3d then wondered, ?If 3d would want that, a new beginning of 3d lives together??His body ached for Mandy. dog then wondered, ?If dog would want that, a new beginning of dog lives together??His body ached for Mandy. sex then wondered, ?If sex would want that, a new beginning of sex lives together??His body ached for Mandy. 3d then wondered, ?If 3d would want that, a new beginning of 3d lives together??His body ached for Mandy. preteen then wondered, ?If preteen would want that, a new beginning of preteen lives together??His body ached for Mandy. She rolled my balls in sex hand and took sex almost all the way in. From castironpi at gmail.com Tue Sep 23 21:21:29 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 18:21:29 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 23, 6:52?pm, Neal Becker wrote: > In hindsight, I am disappointed with the choice of conditional syntax. ?I know it's too late to change. ?The problem is > > y = some thing or other if x else something_else > > When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). ?Particularly if 'some thing or other' is long or complicated. You're talking strictly about readability, which among other things is in the eye of the beholder, of course. Temporary variables can clean up some code, even if choosing names can be a hassle and it's more things to keep track of. Long lines and extra variables form a trade- off. You are writing a line with a conditional expression the value of which depends on something. What does it depend on, what is its value if that's true, and what is it if it's false? '...if...else...' only takes 6 characters... maybe you want more! If you're looking for a strictly syntactic construct, you can always "fire blanks", or tracers, if the analogy's more accurate. z= conditionally( x ) if b else y This could serve as a gentle reminder, even where 'conditionally' returns its argument, i.e. is the identity function. You can always roll your own ternary with extra parameters too: z= condition( b, x, y ) Just don't confuse it with threading.Condition. Otherwise, you're stuck with old syntax markers, and unless you wanted: z= if b then x else y You're out of options. You have to express it somehow. Did you want the condition first? Was there an alternative proposal you preferred? IINM if I'm not mistaken, z= b and x or y works just the same so long as x evaluates to True, as it will be tested. Feel free to write your own from scratch, and we'll see how close Python can come to resembling it. I suppose you can compare it to someone who stops listening before the word 'if', and completely misunderstands your statement. "Feed the dog if he's standing near the food dish" != "Feed the dog", which can of course lead to errors of both omission and commission (doing too little -or- too much). There's no way to fix that in a guaranteed way, except to say, "listen to the whole statement". And strictly sarcastically, what did you want to do with reading the program? Why were you reading it? From ggpolo at gmail.com Tue Sep 2 08:46:13 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 2 Sep 2008 09:46:13 -0300 Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp In-Reply-To: References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> <3bc13b6d-2551-4a94-9548-7fc0b2997b2f@b38g2000prf.googlegroups.com> Message-ID: On Tue, Sep 2, 2008 at 12:44 AM, akineko wrote: > On Sep 1, 8:28 pm, "Guilherme Polo" wrote: >> Can you clarify what is this "sticky" behavior ? Are you referring to >> a toggle button ? If yes, then you might be after a simple >> Checkbutton: >> >> checkbutton = Tkinter.Checkbutton(indicatoron=False, text='test') > > I wouldn't spend days to create a custom widget to mimick the > Checkbutton ;-) > > I don't need to describe the detail but once the button was pressed > for a bit while, a command is sent through communication. > The button is left being ButtonDown ("sticky") until an > acknowledgement is sent back through communication. > This is a way to let the user know the action was acknowledged at > another end. > > I think probably very few people needs such widget. Did you even try creating a checkbutton with indicatoron=False ? You could get surprised. > > Aki- > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From ldo at geek-central.gen.new_zealand Mon Sep 29 21:48:35 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 30 Sep 2008 14:48:35 +1300 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48e11dd4$0$20720$426a74cc@news.free.fr> <00f15d41$0$20617$c3e8da3@news.astraweb.com> Message-ID: In message <00f15d41$0$20617$c3e8da3 at news.astraweb.com>, Steven D'Aprano wrote: > (1) It's not always available. But we're talking about Python libraries here, right? > (2) Even when the source is available, it is sometimes a legal trap to > read it with respect to patents and copyright. That's not how patents work. From andreaskalsch at gmx.de Tue Sep 16 05:26:00 2008 From: andreaskalsch at gmx.de (Andreas Kalsch) Date: Tue, 16 Sep 2008 11:26:00 +0200 Subject: Mysqldb and Python 3000 Message-ID: <48CF7BA8.6060809@gmx.de> Hi, how do I connect the easiest way to MySQL with Python 3000? I don't want to get any trouble and install current MySQLdb, which is supported up to Python 2.5. Andi From david at boddie.org.uk Fri Sep 12 22:00:48 2008 From: david at boddie.org.uk (David Boddie) Date: Sat, 13 Sep 2008 04:00:48 +0200 Subject: GUI programming with python References: <1ff5e508-0fd8-44cf-9c82-3c85ded0ed2d@x16g2000prn.googlegroups.com> <1bs69ogq6nspt.136i7kvcux142$.dlg@40tude.net> <88c2dc03-30a3-4f3b-8fee-f65b349d7418@59g2000hsb.googlegroups.com> Message-ID: On Saturday 13 September 2008 01:04, sturlamolden wrote: > On Sep 12, 8:33?pm, ady... at panix.com (Al Dykes) wrote: > >> OK, what are my choices for an IDE/GUI development tool that runs on XP? [...] > Cpython with PyQt: BlackAdder People using this combination apparently prefer Eric, these days: http://www.die-offenbachs.de/eric/index.html More suggestions can be found on this page: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments David From maebert at uos.de Mon Sep 15 19:57:24 2008 From: maebert at uos.de (Manuel Ebert) Date: Tue, 16 Sep 2008 01:57:24 +0200 Subject: Decompile python2.5-pyc Message-ID: <9DE19AF2-1E2B-4914-BA51-9E230CB238DE@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Dear list, short story I accidentally wrote rm *.py into my makefile (yes, I am old-fashioned, and yes, that was very, veeeery stupid) and - bad things never come alone - my remote backup files are corrupted. To cut a sad story short: I just kind of lost four months work on my bachelor's thesis, well almost. I still have the pyc files (and backuped them on virtually every device I have access to now), but despite intense googling I couldn't find any free way of decompiling 2.5-code -- there is depython.net and the online version of decompyle, but they charge money (which I currently don't have), and the free version of decompyle can't handle marshal data > 2.3, and I lack the skills necessary to extend it to 2.5. Does anybody know something I don't, some home-brewn decompiler, anything? I *am* quite desperate... Thanks in advance, Manuel -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIzvZkcZ70OCIgLecRAt7CAJ42Q464sTjm7FFidQcmBC3I8CEqOACfcCvO j/be2T430ctMpuyFqodOc+Y= =f423 -----END PGP SIGNATURE----- From tjreedy at udel.edu Fri Sep 26 02:43:44 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 Sep 2008 02:43:44 -0400 Subject: Quick sort implementation in python In-Reply-To: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: Alex Snast wrote: > Hi guys, I've been learning python in the past week and tried to > implement a q.sort algorithm in python as follows: > > def quick_sort(l, first, last) > if first < last: > q = partition(a, first, last) You changed the name of the list to be sorted from 'l' to 'a'. Please post code that works by cut-and-paste. > quick_sort(a, first, q - 1) > quick_sort(a, q + 1, last) > > def partition(a, first, last): > import random > pivot = random.randomint(first, last) > a[last], a[pivot] = a[pivot], a[last] > > i = first > for j in range(first, last): > if a[j] <= a[last]: > a[i], a[j] = a[j], a[i] > i += 1 > a[i], a[last] = a[last], a[i] > return i > > Now as you can see I'm passing my list object to both functions along > with their first, last indices > > My question is: Is that the normal way to implement algorithms in > python cause in c++ i've implemented that algo via a template function > which can have a randon access data structure or not. However i have > no idea how to access the values of a data structure that doesn't > allow random access. That depends on the data structure. Access to a singly-linked list is by linear scanning from the front. From lists at cheimes.de Sat Sep 20 19:56:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 21 Sep 2008 01:56:59 +0200 Subject: How to make a reverse for loop in python? In-Reply-To: References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Alex Snast wrote: > Another quick question please, is the List data structure just a > dynamic array? If so how can you use static size array, linked list, > AVL trees etcetera. You should treat Python lists as an opaque item. You shouldn't concern yourself with the implementation details. Python lists are fast and optimized for most use cases. Unless you have specific needs for highly specialized data types, use lists. Just *don't* try to abuse lists by creating fancy stuff e.g. linked lists. The memory overhead is going to kill your app. Christian From mensanator at aol.com Fri Sep 5 13:51:02 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 5 Sep 2008 10:51:02 -0700 (PDT) Subject: max(), sum(), next() References: <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> <618bc60e-5b1d-4eee-bd34-4fc6b0131a5f@m44g2000hsc.googlegroups.com> Message-ID: On Sep 5, 1:08?am, Dennis Lee Bieber wrote: > On Thu, 4 Sep 2008 18:09:49 -0700 (PDT), Mensanator > declaimed the following in comp.lang.python: > > > Too bad. I brought this up because I use Python a lot with > > database work and rarely for proving theorms in ZFC. > > ? ? ? ? As a by-stander... let the DBMS do its work, don't try to make > Python do what DBMS SQL does... Sure, and in most cases I use Visual Basic for Applications when I need functionality I can't get directly from SQL. But anybody who's used VBA with Access must know what a PITA it is. And even when you get it working, you sometimes wish you hadn't. I have a Mann-Kendall trend analysis that must be done quarterly on over 150 combinations of well:analyte. It takes over 6 hours to process this (and I don't know how much is due to VBA, Access, server, network, etc.). It's something I'd love to try in Python (if I can find the time to translate it). But I'm wary of things that Python might do (such as return 0 when summing an empty list) that SQL/VBA does not. > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From steve at REMOVE-THIS-cybersource.com.au Fri Sep 5 21:23:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Sep 2008 01:23:56 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: <00d1d60c$0$20302$c3e8da3@news.astraweb.com> On Fri, 05 Sep 2008 10:22:22 -0500, David C. Ullrich wrote about why max and min shouldn't accept a default argument: > Think about all the previously elected female or black presidents of the > US. Which one was the tallest? I know the answer to that one: All of them! -- Steven From maric at aristote.info Thu Sep 4 16:44:53 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 4 Sep 2008 22:44:53 +0200 Subject: why is self not passed to id()? In-Reply-To: References: Message-ID: <200809042244.54418.maric@aristote.info> Le Thursday 04 September 2008 22:26:53 Ruediger, vous avez ?crit?: > Hello! > Hello, > Executing following little program gives me an TypeError. > > What makes me wonder is that foo does get an argument passed while bar > doesn't. Can anyone explain why?????? > Because id is a builtin written in the core language and doesn't subscribe to the descritpor protocol python functions has. > > class foo(list): > __hash__ = lambda x: id(x) > Wow ! You are really going on trouble with this, believe me there is a real good reason for list not to be hashable. A dictionnary or set containing some of your foo is virtually inconsistent, read carefully the manual about prerequesites for dict keys, they *need* to be immutable. > class bar(list): > __hash__ = id > > _s_ = set() > _s_.add(foo()) > _s_.add(bar()) > > rue at linux:~> python test01.py > Traceback (most recent call last): > File "test01.py", line 9, in > _s_.add(bar()) > TypeError: id() takes exactly one argument (0 given) > > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From george.sakkis at gmail.com Fri Sep 26 21:57:10 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 26 Sep 2008 18:57:10 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: On Sep 26, 6:38?pm, "Dmitry S. Makovey" wrote: > I actually ended up rewriting things (loosely based on George's suggested > code) with descriptors and not using metaclasses or decorators (so much for > my desire to use them). > > With following implementation (unpolished at this stage but already > functional) I can have several instances of B objects inside of A object > and proxy certain methods to one or another object (I might be having a > case when I have A.b1 and A.b2 and passing some methods to b1 and others to > b2 having both of the same class B, maybe even multiplexing). You seem to enjoy pulling the rug from under our feet by changing the requirements all the time :) > This one > seems to be fairly light as well without need to scan instances (well, > except for one getattr, but I couldn't get around it). Maybe I didn't > account for some shoot-in-the-foot scenarios but I can't come up with any. > Last time I played with __getattr__ I shot myself in the foot quite well > BTW :) > > [code snipped] > > class A: > ? ? b=None ^^^^^^ you don't need this > ? ? def __init__(self,b=None): > ? ? ? ? self.val='aval' > ? ? ? ? self.b=b > ? ? ? ? b.val='aval-b' > > ? ? def mymethod(self,a): > ? ? ? ? print "A::mymethod, ",a > > ? ? bmethod = ProxyMethod('b',B.bmethod) Although this works, the second argument to ProxyMethod shouldn't be necessary, it's semantically redundant; ideally you would like to write it as "bmethod = ProxyMethod('b')". As before, I don't think that's doable without metaclasses (or worse, stack frame hacking). Below is the update of my original recipe; interestingly, it's (slightly) simpler than before: #======= usage ======================================== from proxies import Proxy class B(object): def __init__(self, val): self.val = val def bmethod(self,n): print "B::bmethod", self.val, n def bmethod2(self,n,m): print "B::bmethod2", self.val, n, m class C(object): def __init__(self, val): self.val = val def cmethod(self,x): print "C::cmethod", self.val, x def cmethod2(self,x,y): print "C::cmethod2",self.val, x, y cattr = 4 class A(Proxy): # DelegateMap: # Maps each delegate method to the proxy attribute that refers to the # respective delegate object DelegateMap = { 'bmethod' : 'b1', 'bmethod2': 'b2', 'cmethod' : 'c', # do NOT delegate C.cmethod2 #'cmethod2': 'c', } def __init__(self, b1, b2, c): print "init A()" # must call Proxy.__init__ super(A,self).__init__(b1=b1, b2=b2, c=c) def amethod(self,a): print "A::mymethod",a if __name__ == '__main__': a = A(B(10), B(20), C(30)) a.amethod('foo') print "bound proxy calls" a.bmethod('foo') a.bmethod2('bar','baz') a.cmethod('foo') try: a.cmethod2('bar','baz') except Exception, ex: print ex print "unbound proxy calls" A.bmethod(a,'foo') A.bmethod2(a,'bar','baz') A.cmethod(a, 'foo') try: A.cmethod2(a,'bar','baz') except Exception, ex: print ex #======= output ======================================== init A() A::mymethod foo bound proxy calls B::bmethod 10 foo B::bmethod2 20 bar baz C::cmethod 30 foo 'A' object has no attribute 'cmethod2' unbound proxy calls B::bmethod 10 foo B::bmethod2 20 bar baz C::cmethod 30 foo type object 'A' has no attribute 'cmethod2' #====== proxies.py ====================================== class _ProxyMeta(type): def __new__(meta, name, bases, namespace): for methodname in namespace.get('DelegateMap', ()): if methodname not in namespace: namespace[methodname] = _ProxyMethod(methodname) return super(_ProxyMeta,meta).__new__(meta, name, bases, namespace) class _ProxyMethod(object): def __init__(self, name): self._name = name def __get__(self, proxy, proxytype): if proxy is not None: return proxy._get_target_attr(self._name) else: return self._unbound_method def _unbound_method(self, proxy, *args, **kwds): method = proxy._get_target_attr(self._name) return method(*args, **kwds) class Proxy(object): __metaclass__ = _ProxyMeta def __init__(self, **attr2delegate): self.__dict__.update(attr2delegate) def _get_target_attr(self, name): try: delegate = getattr(self, self.DelegateMap[name]) return getattr(delegate, name) except (KeyError, AttributeError): raise AttributeError('%r object has no attribute %r' % (self.__class__.__name__, name)) HTH, George From mkbernard.dev at gmail.com Sun Sep 7 18:04:34 2008 From: mkbernard.dev at gmail.com (MK Bernard) Date: Sun, 7 Sep 2008 15:04:34 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <2ee03613-4959-49e6-bf45-13c8f9e246a1@n38g2000prl.googlegroups.com> On Sep 7, 2:51?pm, "andyh... at gmail.com" wrote: > Hello... > > I have a dict of key/values and I want to change the keys in it, based > on another mapping dictionary. An example follows: > > MAPPING_DICT = { > ? ? 'a': 'A', > ? ? 'b': 'B', > > } > > my_dict = { > ? ? 'a': '1', > ? ? 'b': '2' > > } > > I want the finished my_dict to look like: > > my_dict = { > ? ? 'A': '1', > ? ? 'B': '2' > > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? > > Cheers, > Andy. You could accomplish this with something similar to the following: new_dict = {} for x in MAPPING_DICT.keys(): if x in my_dict.keys(): new_dict[MAPPING_DICT[x]] = my_dict[x] Although there is probably a better solution to the problem your having. Perhaps more details could help us lead in you the right direction? Cheers, MK From arnodel at googlemail.com Sat Sep 13 04:18:05 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 13 Sep 2008 01:18:05 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? References: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> Message-ID: <49974712-2b4a-4728-ab28-4195061325c6@x35g2000hsb.googlegroups.com> On Sep 13, 2:08?am, i... at illusorygoals.com wrote: > First off, I'm a python n00b, so feel free to comment on anything if > I'm doing it "the wrong way." I'm building a discrete event simulation > tool. I wanted to use coroutines. However, I want to know if there's > any way to hide a yield statement. > > I have a class that I'd like to look like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? result = self.ping("128.111.41.38") > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > But because I can't hide yield inside ping, and because I can't find a > convenient way to get a self reference to the coroutine (which is used > by the event queue to pass back results), my code looks like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? # I dislike this next line > ? ? ? ? self.this_pointer = (yield None) > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? # I want to get rid of the yield in the next line > ? ? ? ? ? ? result = (yield self.ping("128.111.41.38")) > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > I posted a more detailed version of this as a rant here:http://illusorygoals.com/post/49926627/ > > I'd like to know, is there a way to get the syntax I want? After > staying up late last night to get a proof-of-concept working with > coroutines, my boss expressed disappointment in the ugliness of the > Pinger code (we agreed on the desired syntax above). I spent almost 2 > hours today to migrate the system over to threads. That made my boss > happy, but I'm still curious if I can do something to salvage the > coroutine version. > > Regards, > IG You can't avoid the yield, and generators are not coroutines. A little while ago when thinking about this kind of problem I defined "cogenerators", which roughly are to generators what coroutines are to routines, i.e. they can pass "yielding control" on to another cogenerator [1]. [1] http://www.marooned.org.uk/~arno/python/cogenerator.html -- Arnaud From simon at brunningonline.net Sat Sep 20 12:36:54 2008 From: simon at brunningonline.net (Simon Brunning) Date: Sat, 20 Sep 2008 17:36:54 +0100 Subject: How to make a reverse for loop in python? In-Reply-To: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <8c7f10c60809200936p6e1b55bchf636b158c5fb0f56@mail.gmail.com> 2008/9/20 Alex Snast : > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) for i in range(10, 0, -1): print i -- Cheers, Simon B. From castironpi at gmail.com Fri Sep 5 13:04:08 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 5 Sep 2008 10:04:08 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> On Sep 5, 3:28?am, "Manu Hack" wrote: > On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: > > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: > >> David C. Ullrich: > > >> > At least in mathematics, the sum of the elements of > >> > the empty set _is_ 0, while the maximum element of the > >> > empty set is undefined. > > >> What do you think about my idea of adding that 'default' argument to > >> the max()/min() functions? > > >> Bye, > >> bearophile > > > For max and min, why can't you just add your argument to the set > > itself? > > > The reason max([]) is undefined is that max( S ) is in S. > > It makes sense. > > >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. > > It doesn't make sense to me. ?What do you set x to? For all x. From stef.mientki at gmail.com Sat Sep 13 08:29:36 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 13 Sep 2008 14:29:36 +0200 Subject: Has any one out there ever worked with the Rpyc, which is a remote process call for python In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380500CF94@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380500CF94@AWMAIL04.belcan.com> Message-ID: <48CBB230.8070106@gmail.com> Blubaugh, David A. wrote: > To All, > > > Has any one out there ever worked with the Rpyc, which is a remote > process call for python? > > Yes > David Blubaugh > > > > This e-mail transmission contains information that is confidential and may be > privileged. It is intended only for the addressee(s) named above. If you receive > this e-mail in error, please do not read, copy or disseminate it in any manner. > If you are not the intended recipient, any disclosure, copying, distribution or > use of the contents of this information is prohibited. Please reply to the > message immediately by informing the sender that the message was misdirected. > After replying, please erase it from your computer system. Your assistance in > correcting this error is appreciated. > > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Sat Sep 6 01:52:41 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 06 Sep 2008 07:52:41 +0200 Subject: use str as variable name In-Reply-To: <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> Message-ID: Marco Bizzarri wrote: >> (...as Bruno implies, setattr(), len() et al can be and should be viewed as >> generic functions. > > Just a question: "generic functions" are not meant in the sense of > "generic functions" of CLOS, am I right? it's meant in exactly that sense: len(L) means "of all len() implementations available to the runtime, execute the most specific code we have for the object L". From patrick.waldo at gmail.com Thu Sep 4 15:54:38 2008 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Thu, 4 Sep 2008 12:54:38 -0700 (PDT) Subject: Converting .doc to .txt in Linux Message-ID: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Hi Everyone, I had previously asked a similar question, http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gst&q=convert+doc+txt#9dc901da63d8d059 but at that point I was using Windows and now I am using Linux. Basically, I have some .doc files that I need to convert into txt files encoded in utf-8. However, win32com.client doesn't work in Linux. It's been giving me quite a headache all day. Any ideas would be greatly appreciated. Best, Patrick #Windows Code: import glob,os,codecs,shutil,win32com.client from win32com.client import Dispatch input = '/home/pwaldo2/work/workbench/current_documents/*.doc' input_dir = '/home/pwaldo2/work/workbench/current_documents/' outpath = '/home/pwaldo2/work/workbench/current_documents/TXT/' for doc in glob.glob1(input): WordApp = Dispatch("Word.Application") WordApp.Visible = 1 WordApp.Documents.Open(doc) WordApp.ActiveDocument.SaveAs(doc,7) WordApp.ActiveDocument.Close() WordApp.Quit() for doc in glob.glob(input): txt_split = os.path.splitext(doc) txt_doc = txt_split[0] + '.txt' txt_doc_path = os.path.join(outpath,txt_doc) doc_path = os.path.join(input_dir,doc) shutil.copy(doc_path,txt_doc_path) From dear.jay.logan at gmail.com Mon Sep 1 09:42:39 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 1 Sep 2008 06:42:39 -0700 (PDT) Subject: SAXReaderNotAvailble: No parsers found References: <507a08c2-7291-481f-b7ab-edbcfb5ad765@s50g2000hsb.googlegroups.com> Message-ID: On Aug 30, 8:59?pm, josh logan wrote: > > Vincent Yau writes: > > > I am trying to use Python SAX API to parse XML files. ?I do see expat.py > > > somewhere underneath my Python 2.1.1 installation (on Solaris). > > > But I got this error when invoking the xml.sax.make_parser() call. ?Any > > > tip/help much appreciated. > > > You should install Expat before building Python. Best, you edit > > Modules/Setup to build pyexpat explicitly. > > > Regards, > > Martin > > Fast-forward to 2008 > > I installed Python 3.0b2 on a Windows Vista laptop (after having > previously installed Python 2.5), and I am getting this same error: > > Traceback (most recent call last): > ? File "Programming\Python\monkeys.py", line 24, in > ? ? test_parse(sys.argv[1]) > ? File "Programming\Python\monkeys.py", line 21, in test_parse > ? ? xml.sax.parse(f, handler) > ? File "C:\Python30\lib\xml\sax\__init__.py", line 30, in parse > ? ? parser = make_parser() > ? File "C:\Python30\lib\xml\sax\__init__.py", line 90, in make_parser > ? ? raise SAXReaderNotAvailable("No parsers found", None) > xml.sax._exceptions.SAXReaderNotAvailable: No parsers found > > I see a pyexpat.lib in the C:\Python30\libs folder. > I also see a pyexpat.pyd in the C:\Python30\DLLs folder. > > It works in Python 2.5. I installed Python 3.0b2 as admin. > Does anyone know what is wrong and how to fix it? Does anyone have an answer for this? I uninstalled both Python 2.5 and Python 3.0b2 and then re-installed 3.0b2, thinking that the installer was confusing 2.5 and 3.0b2 on Windows Vista. Still have the same issue. I had to use my XP machine, since the Vista installation seems broken for Python 3.0b2. How do I fix this? How do I get Python to notice the pyexpat.lib in the C:\Python30\DLLs folder in Vista? Thanks From tmohr at s.netic.de Tue Sep 16 15:12:59 2008 From: tmohr at s.netic.de (Torsten Mohr) Date: Tue, 16 Sep 2008 21:12:59 +0200 Subject: new style classes, __new__, __init__ Message-ID: Hi, i have some questions related to new style classes, they look quite useful but i wonder if somebody can give me an example on constructors using __new__ and on using __init__ ? I just see that when using it i can't give parameters to __new__ and when i additionally define __init__ then __new__ is not called. So i can use __new__ only for classes whose constructors don't have parameters? class C2: def __new__(self): print "new called" self.a = 8 def __init__(self, a): print "init called" self.a = a def fct(self): print self.a a = C2(7) a.fct() This way __new__ is not called, if i remove __init__ then there are too many parameters to __new__, if i add a parameter to __new__ then it says that __new__ does not take arguments. Thanks for any hints, Torsten. From circularfunc at gmail.com Tue Sep 2 21:00:28 2008 From: circularfunc at gmail.com (process) Date: Tue, 2 Sep 2008 18:00:28 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> Message-ID: <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> On Sep 3, 2:36?am, John Machin wrote: > On Sep 3, 9:44 am, ssecorp wrote: > > > or why does this take so god damn long time? > > Because your code does so many god damn unnecessary things. Apart from > the fact (as pointed out already by Robert) that you are needlessly > finding the sizes (Y, X) that are already available: > > (1) You are executing a try block Y*X (approx) times instead of the Y+X > +2 times it would take if you were to do preliminary probes to find Y > and X > (2) You are doing range(1, 1000) Y times instead of once [see question > below] > (3) You are doing the method lookup im.getpixel Y*X times instead of > once > (4) you are doing the method lookup row.append Y*X times instead of Y > times > > > and if I run into an IndexError it break out of the inner loop right? > > so having range up to 10000000 or 1000 wouldn't matter if biggest > > working x is 800? > > > def getPixels(fileName): > > ? ? im = PIL.Image.open(fileName) > > ? ? colors = [] > > ? ? for y in range(1, 1000): > > Are you sure that both occurrences of range(1, 1000) shouldn't be > range(1000)? > > > ? ? ? ? row = [] > > ? ? ? ? for x in range(1, 1000): > > ? ? ? ? ? ? try: > > ? ? ? ? ? ? ? ? color = im.getpixel((x,y)) > > ? ? ? ? ? ? ? ? row.append(color) > > ? ? ? ? ? ? except IndexError: > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? colors.append(row) > > ? ? return numpy.array(colors) > > and it appears that you haven't bothered to read the manual section on > Image.getpixel: > """ > Note that this method is rather slow; if you need to process larger > parts of an image from Python, you can either use pixel access objects > (see load), or the getdata method. > """ how could I do getpixel once when x and y s changing? anyway I rewrote and saw I did a lot of stupid stuff. this is fast: def getPixels5(fileName): im = PIL.Image.open(fileName) colors = [] r, c = im.size for y in range(0, c): row = [] for x in range(0, r): color = im.getpixel((x,y)) row.append(color) colors.append(row) return numpy.array(colors) but I don't need it anuyway apparently since there already was such methods :) From clay at lakeserv.net Sun Sep 28 20:10:42 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Sun, 28 Sep 2008 20:10:42 -0400 Subject: [wxpython-users] ANN: wxPython 2.8.9.0 In-Reply-To: <48DFD492.1090905@alldunn.com> References: <48DFD492.1090905@alldunn.com> Message-ID: <1222647042.29889.1.camel@generator> On Sun, 2008-09-28 at 12:01 -0700, Robin Dunn wrote: > Announcing > ---------- > > The 2.8.9.0 release of wxPython is now available for download at > http://wxpython.org/download.php. This release adds support for using > Cairo for drawing on wx windows, adds a Win64 build, and various other > fixes and enhancements. > > Source code is available, as well as binaries for Python 2.3, 2.4 and > 2.5, for Windows and Mac, as well some packages for various Linux > distributions. A summary of changes is listed below and also at > http://wxpython.org/recentchanges.php. > > > > What is wxPython? > ----------------- > > wxPython is a GUI toolkit for the Python programming language. It > allows Python programmers to create programs with a robust, highly > functional graphical user interface, simply and easily. It is > implemented as a Python extension module that wraps the GUI components > of the popular wxWidgets cross platform library, which is written in > C++. > > wxPython is a cross-platform toolkit. This means that the same program > will usually run on multiple platforms without modifications. > Currently supported platforms are 32-bit and 64-bit Microsoft Windows, > most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. > In most cases the native widgets are used on each platform to provide > a 100% native look and feel for the application. > > > Changes in 2.8.9.0 > ------------------ > > Many minor bug fixes throughout wxWidgets and wxPython. > > Fixed wx.lib.embeddedimage to work with Python 2.3. > > Fixed PseudoDC hit testing when pure white or pure black are used. > > Added support for a 64-bit Windows build for the AMD64 architecture, > (a.k.a. x64.) This is for Python 2.5 only and is available only as a > Unicode build. > > Added the wx.EmptyBitmapRGBA factory function. > > Added the wx.lib.wxcairo module which allows the pycairo package to be > used for drawing on wx window or memory DCs. In addition it is able > to convert from a native wx.Font to a cairo.FontFace, and it also > provides functions for converting to/from wx.Bitmap and > cairo.ImageSurface objects. In order to use this module you will need > to have the Cairo library and its dependencies installed, as well as > the pycairo Python package. For Linux and other unix-like systems you > most likely have what you need installed already, or can easily do so > from your package manager application. See the wx.lib.wxcairo > module's docstring for notes on where to get what you need for Windows > or Mac. This module uses ctypes, and depending on platform it may > need to find and load additional dynamic libraries at runtime in > addition to cairo. The pycairo package used needs to be new enough to > export the CAPI structure in the package namespace. I believe that > started sometime in the 1.4.x release series. > > Added the wx.lib.graphics module, which is an implementation of the > wx.GraphicsContext API using Cairo (via wx.lib.wxcairo). This allows > us to be totally consistent across platforms, and also use Cairo to > implement some things that are missing from the GraphicsContext API. > It's not 100% compatible with the GraphicsContext API, but probably > close enough to be able to share code between them if desired, plus it > can do a few things more. > > Updated wx.Bitmap.CopyFromBuffer to be a bit more flexible. You can > now specify the format of the buffer, and the CopyFromBufferRGBA is > now just a wrapper around CopyFromBuffer that specifies a different > format than the default. Also added the complement method, > CopyToBuffer. See the docstring for CopyFromBuffer for details on the > currently allowed buffer formats. The existing wx.BitmapFromBuffer > factory functions are also now implemented using the same underlying > code as CopyFromBuffer. > > Add wx.lib.mixins.listctrl.ListRowHighlighter for automatic highlighting > of rows in a wx.ListCtrl. > I'm curious, why do you package wxPython for Fedora 6 and 7, but not 8 and 9? --Ratfink From fredrik at pythonware.com Tue Sep 16 03:59:48 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Sep 2008 09:59:48 +0200 Subject: PyMarshal Commands crash on Windows In-Reply-To: <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> Message-ID: spammaster.10.webmaster at spamgourmet.com wrote: > I shortened the quode. Everything should be all right and nothing is a > NULL Pointer. What about PyMarshal_ReadObjectFromFile(FILE* p), this > crashs too :-/ the layout of the "FILE" structure isn't standardized. make sure you're linking everything with the same runtime library. From tjreedy at udel.edu Mon Sep 22 18:44:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 18:44:19 -0400 Subject: a short-cut command for globals().clear() ?? In-Reply-To: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> Message-ID: CapnBearbossa at googlemail.com wrote: > forgive me , but the RTFM and Google search approaches are not > yielding an answer on this question. I need to know if there's a top > level python interpreter command that clears all user variables (not > built-ins) from the global namespace. In other words a statement, or > some_command_or_function(), that does this: > >>>> x=3 >>>> y=4 >>>> z=[] >>>> dir() > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > >>>> some_command_or_function() > >>>> dir() > ['__builtins__', '__doc__', '__name__'] First, a WARNING to other readers deceived by the subject line. Globals().clear() clears everything and leaves nothing, so Capn... is looking for something that works that is a shortcut for deleting bindings one-by-one. To your question. The short answer is no. In batch mode, only create what you need and delete (unbind) large objects that are not automatically deleted (unbound) when you are done with them. Remember that only reference-counted implementations will guarantee immediate destruction and space-freeing when the last reference goes away. Check the gc module (and some posts in the archives) for more specialized control. In interactive mode, restart the interpreter if you really need a clean slate and have too many bindings that you must delete to do something quick like 'del x,y,z' as in your example above. In IDLE, cntl-F6 restarts the shell with a clean slate. I presume IPython has something similar. tjr From bignose+hates-spam at benfinney.id.au Wed Sep 17 04:34:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 Sep 2008 18:34:00 +1000 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> <200809151645.13078.maric@aristote.info> Message-ID: <87skrz41dz.fsf@benfinney.id.au> Maric Michaud writes: > Le Monday 15 September 2008 16:45:12 Maric Michaud, vous avez ?crit?: > > This is not sufficient for auto-responses, and given the following > > rfcs, it would smart to both : > > > ... > > - add or modify the Return-Path and/or Reply-To header for badly > > implemented auto-responders to point to list maintainer. > > Oh, no ! to the list itself of course. Those fields have a defined use, and neither is suitable for munging by mailing list software . The mandatory 'Return-Path' field records the address given in the MAIL FROM command that transported the message. This is defined in RFC 2821. The optional 'Reply-To' field, if used at all, records the address that the author of the message suggests for return correspondence. This is defined in RFC 2822. Neither of these fields is suitable for tampering by mailing list software; 'Return-Path' is set when the message is first sent, and 'Reply-To' is for use by the *author* of the message, not by software that later handles it. Mailing list programs record their information in several fields all of which start with 'List-' and defined in RFC 2369. The purpose you seem to be describing, the list posting address, is recorded in the 'List-Post' field, which records the URL to use for sending contributions to the same maling list. A summary of all header fields for use in mail and MIME is at RFC 4021. > This could also avoid the common mistake mailing list users do in > replying private mail accidentally when the adress of the list is > only present in CC field. That mistake is easy to correct, without breaking standard definitions of fields: the user can simply send the message again to the correct destination. (I would suggest that, to help avoid repetition of this mistake, the user then pressure their software vendor to incorporate the "Reply to list" function making use of the standard 'List-Post' field in every list message.) Munging other fields such as 'Reply-To' leads to other common mistakes that are far more damaging: replies that were intended only for the author are sent to the 'Reply-To' address (as defined by the standard), but instead get sent to the entire list. This damage is usually impossible for the user to undo. If the software you use still isn't following the internet mail standards, then fix the software, or pressure your vendor to do so. -- \ ?Are you pondering what I'm pondering?? ?Umm, I think so, | `\ Brain, but what if the chicken won't wear the nylons?? ?_Pinky | _o__) and The Brain_ | Ben Finney From christopher.paul.taylor at gmail.com Wed Sep 17 11:31:21 2008 From: christopher.paul.taylor at gmail.com (christopher taylor) Date: Wed, 17 Sep 2008 11:31:21 -0400 Subject: python regex character group matches...group...gotcha Message-ID: My apologies to the respondents - I failed to screen my test cases before kicking them out to the global python-list. but yes, the 'X' character in my test case was a mistake on my part. I'll give group() a shot. ct From ldo at geek-central.gen.new_zealand Sun Sep 28 02:03:42 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 28 Sep 2008 19:03:42 +1300 Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: In message <9890864a-09f9-40d6-b2cc-5028e7a0c8c3 at q26g2000prq.googlegroups.com>, est wrote: > The problem is, why the f**k set ASCII encoding to range(128) ???????? Because that's how ASCII is defined. > while str() is internally byte array it should be handled in > range(256) !!!!!!!!!! But that's for random bytes. How would you convert an arbitrary object to random bytes? From steven at REMOVE.THIS.cybersource.com.au Tue Sep 2 02:10:51 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 06:10:51 GMT Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: On Tue, 02 Sep 2008 11:13:27 +1000, Ben Finney wrote: > bearophileHUGS at lycos.com writes: > >> For Python 2.7/3.1 I'd now like to write a PEP regarding the >> underscores into the number literals, like: 0b_0101_1111, 268_435_456 >> etc. > > +1 on such a capability. > > -1 on underscore as the separator. > > When you proposed this last year, the counter-proposal was made > > to instead use white space for the separator, exactly as one can now do > with string literals. > > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > literals. At the risk of bike-shedding, I think that allowing arbitrary whitespace between string literals is fine, because it aids readability to write this: do_something( "first part of the string" "another part of the string" "yet more of the string" "and a bit more" "and so on..." ) but I'm not sure that it is desirable to allow this: do_something( 142325 93.8012 7113 ) -1/2 on arbitrary whitespace, +1/2 on a single space, and +0 on underscores. If semi-colons didn't already have a use, I'd propose using them to break up numeric literals: 14;232;593.801;271;13 -- Steven From george.sakkis at gmail.com Thu Sep 18 02:20:27 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 17 Sep 2008 23:20:27 -0700 (PDT) Subject: decorator and API References: Message-ID: <83cdd6aa-1b2c-4b30-a1da-027659598d06@c58g2000hsc.googlegroups.com> On Sep 17, 5:56 pm, Lee Harr wrote: > I have a class with certain methods from which I want to select > one at random, with weighting. > > The way I have done it is this .... > > import random > > def weight(value): > def set_weight(method): > method.weight = value > return method > return set_weight > > class A(object): > def actions(self): > 'return a list of possible actions' > > return [getattr(self, method) > for method in dir(self) > if method.startswith('action_')] > > def action(self): > 'Select a possible action using weighted choice' > > actions = self.actions() > weights = [method.weight for method in actions] > total = sum(weights) > > choice = random.randrange(total) > > while choice> weights[0]: > choice -= weights[0] > weights.pop(0) > actions.pop(0) > > return actions[0] > > @weight(10) > def action_1(self): > print "A.action_1" > > @weight(20) > def action_2(self): > print "A.action_2" > > a = A() > a.action()() > > The problem I have now is that if I subclass A and want to > change the weighting of one of the methods, I am not sure > how to do that. > > One idea I had was to override the method using the new > weight in the decorator, and then call the original method: > > class B(A): > @weight(50) > def action_1(self): > A.action_1(self) > > That works, but it feels messy. > > Another idea was to store the weightings as a dictionary > on each instance, but I could not see how to update that > from a decorator. > > I like the idea of having the weights in a dictionary, so I > am looking for a better API, or a way to re-weight the > methods using a decorator. > > Any suggestions appreciated. Below is a lightweight solution that uses a descriptor. Also the random action function has been rewritten more efficiently (using bisect). George #======== usage =========================== class A(object): # actions don't have to follow a naming convention @weighted_action(weight=4) def foo(self): print "A.foo" @weighted_action() # default weight=1 def bar(self): print "A.bar" class B(A): # explicit copy of each action with new weight foo = A.foo.copy(weight=2) bar = A.bar.copy(weight=4) @weighted_action(weight=3) def baz(self): print "B.baz" # equivalent to B, but update all weights at once in one statement class B2(A): @weighted_action(weight=3) def baz(self): print "B2.baz" update_weights(B2, foo=2, bar=4) if __name__ == '__main__': for obj in A,B,B2: print obj for action in iter_weighted_actions(obj): print ' ', action a = A() for i in xrange(10): take_random_action(a) print b = B() for i in xrange(12): take_random_action(b) #====== implementation ======================= class _WeightedActionDescriptor(object): def __init__(self, func, weight): self._func = func self.weight = weight def __get__(self, obj, objtype): return self def __call__(self, *args, **kwds): return self._func(*args, **kwds) def copy(self, weight): return self.__class__(self._func, weight) def __str__(self): return 'WeightedAction(%s, weight=%s)' % (self._func, self.weight) def weighted_action(weight=1): return lambda func: _WeightedActionDescriptor(func,weight) def update_weights(obj, **name2weight): for name,weight in name2weight.iteritems(): action = getattr(obj,name) assert isinstance(action,_WeightedActionDescriptor) setattr(obj, name, action.copy(weight)) def iter_weighted_actions(obj): return (attr for attr in (getattr(obj, name) for name in dir(obj)) if isinstance(attr, _WeightedActionDescriptor)) def take_random_action(obj): from random import random from bisect import bisect actions = list(iter_weighted_actions(obj)) weights = [action.weight for action in actions] total = float(sum(weights)) cum_norm_weights = [0.0]*len(weights) for i in xrange(len(weights)): cum_norm_weights[i] = cum_norm_weights[i-1] + weights[i]/total return actions[bisect(cum_norm_weights, random())](obj) From deets at nospam.web.de Mon Sep 15 15:33:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 21:33:12 +0200 Subject: Python Nautilus script In-Reply-To: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> Message-ID: <6j7rjpF1rp5lU1@mid.uni-berlin.de> Michel Leunen schrieb: > Hi, > > I'm trying to write a python script for Nautilus. > To get the list of files selected in the Nautilus right pane, you use > the $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS environment variable which is > normally available to the script. Actually, it works with bash scripts > but not with python scripts > > import os > files = os.environ['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'].splitlines() > > gives a: > > File "", line 1, in > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' > > Fredrik Lundh explained me that all environment variables are not > accessible from subprocesses of an application. > > So my question is how can I get the Nautilus selected files in a python > script? There shouldn't be a difference between a shell-script and a python-script. Environment-variables are a unix-process-thing, and thus the rules that govern them apply to *all* processes - the shell is one of these, there is nothing special to it. If the shell-script gets the variable, the python-script will as well. Are you sure the shell gets the value? Or is it just silently ignoring a missing value, and the python-script isn't? According to the docs (I only googled the variable-name), the variable seems only to be set "only if local"[1], whatever that means. https://help.ubuntu.com/community/NautilusScriptsHowto Diez From ronald.chis.3 at gmail.com Sat Sep 20 13:20:08 2008 From: ronald.chis.3 at gmail.com (ronald) Date: Sat, 20 Sep 2008 10:20:08 -0700 (PDT) Subject: Sunbeam India UPS Point- unfair Trade Practices in Computer Business Message-ID: Sunbeam India UPS Point- unfiar Trade Practices in Computer Business Save Money, Tension, and Time. Avoid Nehru Place market to buy Computer Goods Hello All, This is to inform you all the sellers at the Nehru Place are not selling good products. Especially the shop- Nishchal Joshi, Sunbeam India UPS Point, 103, S2 1st Floor, Siddhartha Building, Nehru Place, New Delhi 110019. Phone - 9810276805, Email - nishchal1us at yahoo.com Engineer at Shop- Subash - 996899657 I bought a motherboard from that shop and that computer don't even worked for a single day. We called the person in just two days of purchase and he said he was out of town and so therefore bring it to me after one week. We took the system to his shop after spending money to nehru place, there he kept the system for five days and returned it back to us. However it was not rectified. Then we called him to our house and he charged money for this and did some corrections in the system and restarted the system. We told him to take his motherboard and gave our own old motherboard, then he said that he will rectify it, after making settings he left for the day. When we started the system, it started and got shut down immediately. And after that it never started. We called this person again and told him to take his motherboard back and gave us our old motherboard, but he said I am not the correct person, talk to the engineer who set the system for you. That Engineer Subash works for the Nishchal in his shop. Please suggest what action can be taken against him. Steps in the pipeline - Consumer Forum, Escalating issue to Consumer Affairs, Online Web and Nehru Place Online Community, so that others do not fall prey to this. Thanks Kritika Joshi kritikajoshi at in.com Save Money, Tension, and Time. Avoid Nehru Place (Nishchal Joshi, Unbeam India UPS Point, 103, S2 1st Floor, Siddhartha Building, Nehru Place, New Delhi ) market to buy Computer Goods. All the Best. From dblubaugh at belcan.com Mon Sep 29 15:45:02 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 15:45:02 -0400 Subject: PYTHON WORKING WITH PERL ?? In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F380534241C@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9060@AWMAIL04.belcan.com> Thank You Steve!!! -----Original Message----- From: Steve Holden [mailto:steve at holdenweb.com] Sent: Monday, September 29, 2008 1:38 PM To: python-list at python.org Subject: Re: PYTHON WORKING WITH PERL ?? Blubaugh, David A. wrote: > To All, > > > I was wondering if it was possible to have a situation where a > programming project would utilized BOTH python and perl? Such as > utilizing python for internet programming and then utilize perl for > text processing and systems programming? Is this even feasible??? > > > Thanks, > So sorry to hear Google isn't available from your network ;-) http://search.cpan.org/~gaas/pyperl-1.0/perlmodule.pod regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From zxo102 at gmail.com Mon Sep 29 09:41:17 2008 From: zxo102 at gmail.com (zxo102) Date: Mon, 29 Sep 2008 06:41:17 -0700 (PDT) Subject: how to make smtplib.SMTP('localhost') work on window xp References: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Message-ID: On 9?29?, ??7?29?, Steve Holden wrote: > zxo102 wrote: > > Hi, > > I am trying to use python module smtplib to send my email out on > > window xp (localhost). > > > import smtplib > > server = smtplib.SMTP('localhost') > > > but I got the error information as follows: > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "c:\python24\lib\smtplib.py", line 244, in __init__ > > (code, msg) = self.connect(host, port) > > File "c:\python24\lib\smtplib.py", line 311, in connect > > (code, msg) = self.getreply() > > File "c:\python24\lib\smtplib.py", line 355, in getreply > > raise SMTPServerDisconnected("Connection unexpectedly closed") > > SMTPServerDisconnected: Connection unexpectedly closed > > > I am not sure what is wrong with it. Should I configure my window xp > > somewhere to run smtplib.SMTP('localhost')? > > > Thanks in advance. > > Well your code certainly expects *something* to be listening on port 25 > on localhost. It's fairly unusual to run an SMTP server on Windows XP, > though not impossible. > > usually your email system is set up to use some external host as uts > SMPT server: if you look in your mail client's configuration you will > probably find out whihc host you should be using. > > regards > Steve > > -- > Steve Holden +1 571 484 6266 +1 800 494 3119 > Holden Web LLC http://www.holdenweb.com/ In my case, I implement an application with python to accomplish collecting real time data from a serial port: com1 which is connected to some xbee hardwares. The python logging module is used to save the information generated at runtime into a log file. Since the site is far away from my office, I try to use a smtp server with the python smtplib module to send the log file into my email account regularly so that I can check it from anywhere. Thanks for your suggestion. Ouyang From python.list at tim.thechases.com Thu Sep 18 12:27:42 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 18 Sep 2008 11:27:42 -0500 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: <48D2817E.5030301@tim.thechases.com> Grant Edwards wrote: > While we're making suggestions, I've always wished that the > --help output displayed the default values for options in > addition to the help text specified by the user. I end up > having to enter the default values twice -- once as a keyword > argument and again in the help text. Then later when I decide > to change the default value, things get out-of-sync. Tangential to this thread, what's the preferred way to get changes into optparse? Based on the comments I've read in the optparse.py file, it looks like it's the generated output of some other process. I've patched my local version to include some changes for handling newlines in help text (which has cropped up on the list occasionally, as the current version eats newlines), but am not sure whether I need to be patching against the optparse.py or against the file that generated it (which I don't have in my install, AFAIK). Perhaps one of the core devs that works on optparse could tell me how they'd prefer such changes submitted? Thanks, -tkc From dudeja.rajat at gmail.com Sat Sep 27 09:49:51 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 27 Sep 2008 14:49:51 +0100 Subject: Regular expression help: unable to search ' # ' character in the file In-Reply-To: References: Message-ID: On Sat, Sep 27, 2008 at 1:58 PM, Fredrik Lundh wrote: > dudeja.rajat at gmail.com wrote: > > import re >> >> fd = open(file, 'r') >> line = fd.readline >> pat1 = re.compile("\#*") >> while(line): >> mat1 = pat1.search(line) >> if mat1: >> print line >> line = fd.readline() >> > > I strongly doubt that this is the code you used. > > But the above prints the whole file instead of the hash lines only. >> > > "*" means zero or more matches. all lines is a file contain zero or more # > characters. > > but using a RE is overkill in this case, of course. to check for a > character or substring, use the "in" operator: > > for line in open(file): > if "#" in line: > print line > > > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks Fredrik, this works. Indeed it is a much better and cleaner approach. -- Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjruth at gmail.com Fri Sep 12 16:07:52 2008 From: bjruth at gmail.com (byron) Date: Fri, 12 Sep 2008 13:07:52 -0700 (PDT) Subject: book example confusion References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: <0a61d5f4-0eaa-4d52-b720-efb702bb5a10@c65g2000hsa.googlegroups.com> On Sep 12, 3:51?pm, John Machin wrote: > On Sep 13, 5:36?am, byron wrote: > > > > > I am reading o'reilly's learning python (great book), but i came > > across an example (pg 291, pdf) that I am not quite understanding the > > reasoning for the author's explanation: > > > if f1() or f2(): > > > The author states that do to the nature of that expression, if f1() > > returns True, f2() will not be evaluated.. which makes sense. His > > quote: > > > ? ? ? ? "Here, if f1 returns a true (or nonempty) value, Python will > > never run f2." > > > He then states: > > > ? ? ? ? "To guarantee that both functions will be run, call them > > before the 'or':" > > > tmp1, tmp2 = f1(), f2() > > if tmp1 or tmp2: > > > Being that each function is an object, a name assignment to > > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > > the name is called.. so why would the latter example "run" both > > functions as the author suggests? > > It's not a "name assignment". > In effect it's doing this: > ? ?tmp1 = f1() # get the RESULT of calling f1() > ? ?tmp2 = f2() # likewise f2 > ? ?if tmp1 or tmp2: # if result1 or result2 > A (pointless) "name assignment") with the nil effect that you fear > would look like this: > ? ? tmp1, tmp2 = f1, f2 # Look, no parentheses after function names > ? ? if tmp1() or tmp2(): > > HTH, > John That makes sense. Thank you for the clarification. From martin at v.loewis.de Sun Sep 14 13:56:05 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 14 Sep 2008 19:56:05 +0200 Subject: How to emit Cyrillic and Chinese via unicode from console mode? In-Reply-To: References: Message-ID: <48CD5035.3050108@v.loewis.de> > Can someone point me to an example of a little program that emits non-ascii > Unicode characters (Russian or Chinese perhaps)? The unicode > Russian/Cyrillic alphabet starts at 0x410. Is this possible to do in a > console mode program? If not, I guess I would want to use pywin32 to create > a window and a message pump and display it there. I anticipate using pywin32 > for some other function calls. It also depends on your console. On Linux, with an UTF-8 capable-and-enabled console, py> print u"\u0413" ? work just fine. Regards, Martin From maric at aristote.info Mon Sep 15 07:38:42 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 13:38:42 +0200 Subject: Representation of python code ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: <200809151338.43017.maric@aristote.info> Le Sunday 14 September 2008 15:44:03 Barak, Ron, vous avez ?crit?: > Hi Guys, > Is there a script/application, which gets as input python code, and > produces a (graphic) representation of the inter-relationships between its > classes/functions ? Bye, None I know of. Not saying that it would be unfeasible, but it would be a hard job, given the fact that most of relationships are purely dynamic. How such an application would find the relationship (composition) between A and B without executing this code ? class A : def __init__(self) : self._b = B() class B : pass -- _____________ Maric Michaud From steven at REMOVE.THIS.cybersource.com.au Thu Sep 11 23:37:51 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 12 Sep 2008 03:37:51 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> Message-ID: On Thu, 11 Sep 2008 10:20:41 -0700, Aaron \"Castironpi\" Brady wrote: > XML is the wrong word for the example I was thinking of (as was already > pointed out in another thread). XML is by definition sequential. I'm pretty sure you're wrong. XML can be used for serialization, but that doesn't mean it is only sequential data. XML is suitable for hierarchical data too. To quote Wikipedia: "As long as only well-formedness is required, XML is a generic framework for storing any amount of text or any data whose structure can be represented as a tree. The only indispensable syntactical requirement is that the document has exactly one root element (alternatively called the document element)." http://en.wikipedia.org/wiki/Xml -- Steven From bhood37 at hotmail.com Fri Sep 5 16:10:31 2008 From: bhood37 at hotmail.com (Uberman) Date: Fri, 05 Sep 2008 14:10:31 -0600 Subject: Happy fun time with SWIG In-Reply-To: <5vYvk.75246$C65.45163@en-nntp-01.dc1.easynews.com> References: <5vYvk.75246$C65.45163@en-nntp-01.dc1.easynews.com> Message-ID: Nobody has any help for me on this one? Let me see if I can make it clearer by using something simpler: +-------+ -------| Peter |------- | +-------+ | | | V V +-------------+ +-------------+ | Python | | Application | | Environment | | Environment | +-------------+ +-------------+ ^ ^ | | ---<--<--< ? >-->-->--- Both environments use the C++ class Peter in their environments (Application directly, and Python via SWIG). How do I exchange instances of Peter between them? How do I get Python-environment instances of Peter with its Python-specific settings into the Application's environment (and vice versa)? OR... Does anybody know of a a SWIG-specific mailing list or forum where discussion of this type of problem would be more appropriate? From gauravatnet at gmail.com Thu Sep 18 06:25:42 2008 From: gauravatnet at gmail.com (gauravatnet at gmail.com) Date: Thu, 18 Sep 2008 03:25:42 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> Message-ID: <5fcabe40-7997-49ce-af3f-8306fe34b40b@b2g2000prf.googlegroups.com> On Sep 18, 3:24?pm, gauravat... at gmail.com wrote: > On Sep 9, 9:09?pm, "J. Cliff Dyer" wrote: > > > > > On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > > > Matimus a ?crit : > > > > On Sep 8, 12:32 am, Bruno Desthuilliers > > > > wrote: > > > (snip) > > > >> ?>>> set(a).issubset(set(b)) > > > >> True > > > > > Just to clarify, doing it using sets is not going to preserve order OR > > > > number of elements that are the same. > > > > > That is: > > > > >>>> a = [1,1,2,3,4] > > > >>>> b = [4,5,3,7,2,6,1] > > > >>>> set(a).issubset(set(b)) > > > > True > > > > > This will return True if b contains at least on of each element found > > > > in a. If the OP wanted to check that list `a` appeared in order > > > > somewhere in list `b` then sets won't work. > > > > Indeed, and I should have mentionned this myself. Thanks for this reminder. > > > If preserving order is important, strings have many of the properties > > you're looking for, but it might take some work to figure out a suitable > > way to convert to a string. ?The problem is easier if you know something > > about the inputs. ?If all inputs are known to be numbers between 0 and > > 15, you can just do: > > > if ''.join(map(hex, a)) in ''.join(map(hex, b)): > > ? ? return True > > > Hmm... actually, with the '0x' prefix that hex() puts on numbers, I > > think this works for arbitrary integers. > > > Cheers, > > Cliff > > Hi, > > I looked inside this thread for my query which brought me the > following google search result > "Test if list contains another list - comp.lang.python | Google > Groups" > > But then I was disappointed to see the question asked was not exactly > right. Other programmers have already answered to the main question. > But what if you actually have to find out if a list has all its > element inside another list in the same order. For that I wrote the > code and that's what I came up with.. let me know if there are any > bugs in this code. > > #!C:\Python24 > > def findAllMatchingList(mainList, subList): > ? ? resultIndex = [] > ? ? globalIndex = 0 > ? ? for i in range(len(mainList)): > ? ? ? ? if i < globalIndex: > ? ? ? ? ? ? continue > ? ? ? ? globalIndex = i > ? ? ? ? increment = 0 > ? ? ? ? for j in range(len(subList)): > ? ? ? ? ? ? if mainList[globalIndex] == subList[j]: > ? ? ? ? ? ? ? ? globalIndex += 1 > ? ? ? ? ? ? ? ? increment += 1 > ? ? ? ? ? ? ? ? if j == (len(subList)-1): > ? ? ? ? ? ? ? ? ? ? resultIndex.append(globalIndex-increment) > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? break > > ? ? return resultIndex > > if __name__ == "__main__": > ? ? #Test case > ? ? mL = [ 'a', 'b', 'c', 1, 2, 4, 1, 2, 1, 1, 1, 2, 9, 1, 1, 1, 2, 3, > 'a', 1, 2, 3, 4 ] > ? ? #mL = [ 'a', 'a', 'b', 1 ,2 ,3, 5, 6] > ? ? sL = [ 1, 2, 3 ] > ? ? result = findAllMatchingList( mL, sL ) > ? ? for i in result: > ? ? ? ? print str(i) > > Regards, > Gaurav. From elzapp at elzapp.com Mon Sep 29 17:00:22 2008 From: elzapp at elzapp.com (Bard Aase) Date: Mon, 29 Sep 2008 23:00:22 +0200 Subject: Source code for python nativ methods and classes In-Reply-To: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> References: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> Message-ID: <257224ff0809291400t1611aa6cm1b033b539392f353@mail.gmail.com> On Mon, Sep 29, 2008 at 10:51 PM, Mohed wrote: > Hello. > I am interrested in seeing the source code for all the nativ builtin > methods and clases in python. Is there a webpage that lists them or is > this done easier some other way. Check it out from svn? svn co http://svn.python.org/projects/python/trunk/ or browse the code at http://svn.python.org/view/python/trunk/ or did I misinterpret your question? -- mvh base (B?rd Aase) MSN: msn at elzapp.com http://blog.elzapp.com :wq From tjreedy at udel.edu Sat Sep 27 19:16:06 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2008 19:16:06 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: <1a7184f3-c71e-49b7-a8f8-f141705f3573@l42g2000hsc.googlegroups.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <00ee05ca$0$20666$c3e8da3@news.astraweb.com> <1a7184f3-c71e-49b7-a8f8-f141705f3573@l42g2000hsc.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: >>>> class A(type): > ... def __call__( self, *ar ): > ... print 'call', self, ar > ... >>>> class B(object): > ... __metaclass__= A > ... >>>> B(3) > call (3,) > > Overriding the __call__ method of 'type' has the effect of giving you > a static __call__ method on a class-- a method which doesn't need an > instance to call. Your behavior may be counterintuitive though, to > someone who wants to instantiate 'B', in this case, and proceed like a > normal object. That is, they want to call a generic class and use it, > and also expect instances of B to behave as B. You can't have both, > so either return B from B.__new__, or, to instantiate B, take the long > way and call B.__new__ directly. > >>>> B.__new__(B) > <__main__.B object at 0x009FDB70> > > Has anyone stepped through the C code to find out when the decision is > made to call which function, B.__new__ or A.__call__, when B is > called? For Python coded objects, ob(*args) in code translates to internal execution of type(ob).__call__(ob, *args) (without further translation!). The interpreter compiles a statement at a time, without looking back to do type inferencing, and so does not know what type is being called or if it is even callable. For B, B(*args) == type(B).__call__(B, *args) == A.__call__(B, *args). So there is no decision. For C coded objects, I believe ob(*args) in Python code translate to a C call of the C equivalent of type(ob).tp_call (or something like that). From observation, type.tp_call acts something like this: def __call__(cls, *args): if cls == type: if len(*args): return arg[0].__class__ elif len(*args) == 3: return type.__new__(type, *args) # or maybe not pass type? else: raise TypeError('type() takes 1 or 3 arguments') else: return cls.__new__(cls, *args) So, for a normal class C (an instance of type), type.__call__ calls C.__new__. Terry Jan Reedy From kyosohma at gmail.com Thu Sep 4 16:03:46 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Sep 2008 13:03:46 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> Message-ID: <3c2a22dd-a713-49a4-b396-c55301950bef@w24g2000prd.googlegroups.com> On Sep 4, 2:50?pm, Fett wrote: > On Sep 4, 2:23?pm, Mike Driscoll wrote: > > > > > On Sep 4, 1:39?pm, Fett wrote: > > > > I need a crypto package that works on windows with python 2.5. Can > > > anyone suggest one for me? > > > > I have been searching for a couple days for a good cryptography > > > package to use for public/private key encryption, at this point I > > > would settle for symmetric even. > > > > Every encryption package I have found for python was either operating > > > system specific (read *nix only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/ > > > > There was one exception, this version was specifically built to run on > > > any platform (yay), but the compiler for windows complained that I > > > wasn't using python2.2 (though the package was said to only need 2.2 > > > or newer). > > > > Is there any crypto package that is actually written in python? I > > > seriously don't care how slow it is. > > > How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads > > > Mike > > Seems that this is intended more for webapps or something, I intend to > use this for a client application. This means that I can't require > outside dependencies, or I risk annoying the clients (if you have > installed many open-source projects with dependencies that aren't > handled by portage/apt-get, you know what I would be doing to them). > > I seriously can't believe that there isn't a single python native > crypto package. Why do they all need to have outside dependencies? If you are distributing your application on Windows (which is what your original post implied), then you can easily roll up dependencies with py2exe / Gui2Exe and something like Inno Setup or NSIS. I'm going to try to compile the crypto package (http://www.amk.ca/python/code/ crypto) into an installer for 2.5, but no promises. Mike From deets at nospam.web.de Thu Sep 18 05:18:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Sep 2008 11:18:08 +0200 Subject: Program works great, except under less, cron or execl (Unicode?) References: <611f2937-2c9c-4378-92c9-cf250b37184e@r15g2000prh.googlegroups.com> <6jekbbF2v55pU2@mid.uni-berlin.de> Message-ID: <6jekmpF2v55pU3@mid.uni-berlin.de> > Most probably because when to running directly inside a terminal, it gets That was of course meant to be "not running directly inside a terminal". > it's stdin/stdout as pipes - and python can't attempt to guess the proper > encoding on that, as it does on a terminal. Diez From vvangelovski at gmail.com Tue Sep 16 16:07:11 2008 From: vvangelovski at gmail.com (vvangelovski at gmail.com) Date: Tue, 16 Sep 2008 13:07:11 -0700 (PDT) Subject: find the path of a module Message-ID: <7f3f0dce-52bd-45d3-87f1-2f9aa695e080@c58g2000hsc.googlegroups.com> I'd like to know if I can somehow find the path for a module somewhere in a the package hierarchy for instance if I import my module like so from spam.eggs import sausage my hypothetical method would return something like '/home/developer/projects/spam/eggs/sausage.py/c' given that module object. From tiftof at gmail.com Tue Sep 30 13:18:27 2008 From: tiftof at gmail.com (Christophe) Date: Tue, 30 Sep 2008 19:18:27 +0200 Subject: how to find out the version of a certain installed package In-Reply-To: <48E2541E.7030605@egenix.com> References: <48E2541E.7030605@egenix.com> Message-ID: <8531008b0809301018r96a2653obd4a99455ad5383d@mail.gmail.com> great! thanks for you fast response. Christophe On Tue, Sep 30, 2008 at 6:30 PM, M.-A. Lemburg wrote: > On 2008-09-30 18:17, Christophe wrote: > > Hi, > > > > In a projecet I'm making using pycrypto, I need to find out the > > current installed version of pycrypto. After looking around, I found > > out that "pkg_resources.requires("pycrypto") will give me a string > > containing the version number, but is this the only way to do it or > > are there other ways? > > Most packages have a .__version__ attribute in their top-level > package dir which you can query. > > You do have to import the base package, though, in order to find > out. > > Thanks, > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, Sep 30 2008) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mathieu.prevot at gmail.com Thu Sep 4 03:59:10 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 09:59:10 +0200 Subject: use str as variable name In-Reply-To: <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> Message-ID: <3e473cc60809040059o5ebb0bd2h54db1d38929a533b@mail.gmail.com> 2008/9/4 Chris Rebert : > On Thu, Sep 4, 2008 at 12:25 AM, Mathieu Prevot > wrote: >> Hi, >> >> I have a program that take a word as argument, and I would like to >> link this word to a class variable. >> >> eg. >> class foo(): > > You should subclass 'object', so that should be: > class Foo(object): > >> width = 10 >> height = 20 >> >> a=foo() >> arg='height' >> a.__argname__= new_value > > You're looking for the setattr() built-in function. In this exact case: > setattr(a, arg, new_value) > > This is probably covered in the Python tutorial, please read it. > > Regards, > Chris Indeed. I'll use: a.__setattr__(height, new_value) Thanks to all Mathieu From kay.schluehr at gmx.net Wed Sep 24 05:54:05 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 24 Sep 2008 02:54:05 -0700 (PDT) Subject: Does anybody use this web framework ? References: <48d94cbc$0$964$ba4acef3@news.orange.fr> <48d9eb86$0$6127$426a34cc@news.free.fr> Message-ID: <9f3ba168-d6e0-4488-af1b-d182f77e9791@y38g2000hsy.googlegroups.com> On 24 Sep., 09:26, Bruno Desthuilliers wrote: > Phil Cataldo a ?crit : > > > Hi, > > > I just found this new? python web framework > > (http://pypi.python.org/pypi/nagare/0.1.0). > > > Does anybody know or use it ? > > First time I hear of it, but it looks interesting (note : Stackless > continuation-based framework). Thanks for the link. Dito! From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 04:53:51 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 10:53:51 +0200 Subject: how to find position of dictionary values In-Reply-To: References: Message-ID: <48bbad4d$0$12756$426a74cc@news.free.fr> lee a ?crit : > > hi, thank u your solution is exactly wat i wanted :) I'm afraid it's not what you actually *need*, cf my other post. From kaiser.vocote at gmail.com Tue Sep 16 07:47:51 2008 From: kaiser.vocote at gmail.com (Andreas Kaiser) Date: Tue, 16 Sep 2008 04:47:51 -0700 (PDT) Subject: What is "finally:" for? References: Message-ID: On 16 Sep., 13:25, "Max Ivanov" wrote: > Hi all! > When and where I should use try-except-finally statement? What is the > difference between: > -------- > try: > ? A... > except: > ? B.... > finally: > ? C... > -------- > > and > ------- > try: > ? A... > except: > ? B.... > C... Look at: http://docs.python.org/ref/try.html and http://bytes.com/forum/thread24648.html The python doc says: "Changed in version 2.5: In previous versions of Python, try...except...finally did not work. try...except had to be nested in try...finally." Andreas From fredrik at pythonware.com Fri Sep 12 10:46:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 16:46:49 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <3f0d61c40809120718r6709387bj68e75e9c40ce2036@mail.gmail.com> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <3f0d61c40809120718r6709387bj68e75e9c40ce2036@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > Can you clarify where I can find "any"? It seems to me I'm > unable to find it... it's a 2.5 addition. to use this in a "future-compatible" way in 2.3, you can add try: any except NameError: def any(iterable): for element in iterable: if element: return True return False to the top of the file (or to some suitable support library). 2.5 also provides an "all" function, which can be emulated as: try: all except NameError: def all(iterable): for element in iterable: if not element: return False return True From gminick at bzt.bzt Wed Sep 10 14:14:21 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 18:14:21 +0000 (UTC) Subject: removing text string References: Message-ID: On Wed, 10 Sep 2008 11:22:16 -0400, Ahmed, Shakir wrote: > I need to remove text string from the list of the numbers mentioned > below: > > 080829-7_A > 070529-5_c > 080824-7_O > 070405_6_p > > The output will be : 080829-7 > 070529-5 > 080824-7 > 070405-6 You need to read about slice indices. An example: >>> a=('080829-7_A', '070529-5_c', '080824-7_O') >>> [i[:-2] for i in a] ['080829-7', '070529-5', '080824-7'] -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From dmitry at athabascau.ca Thu Sep 25 15:42:40 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 19:42:40 GMT Subject: Eggs, VirtualEnv, and Apt - best practices? References: Message-ID: Scott Sharkey wrote: > Any insight into the best way to have a consistent, repeatable, > controllable development and production environment would be much > appreciated. you have just described OS package building ;) I can't speak for everybody, but supporting multiple platforms (PHP, Perl, Python, Java) we found that the only way to stay consistent is to use OS native packaging tools (in your case apt and .deb ) and if you're missing something - roll your own package. After a while you accumulate plenty of templates to chose from when you need yet-another-library not available upstream in your preferred package format. Remember that some python tools might depend on non-python packages, so the only way to make sure all that is consistent across environment - use unified package management. Sorry, not specific pointers though as we're redhat shop and debs are not our everyday business. From wuwei23 at gmail.com Wed Sep 10 22:06:32 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 10 Sep 2008 19:06:32 -0700 (PDT) Subject: Alternatives to traditional RDBMS References: <6iq90jFdeiU1@mid.uni-berlin.de> Message-ID: <3ee3f834-b314-4a75-a85c-6a13bb118b09@l33g2000pri.googlegroups.com> "James Mills" wrote: > This is an ORM. They are > off-topic for this thread :) Tsk, such an unfounded bias... I've had a lot of success using sqlalchemy + Elixir together ;) From castironpi at gmail.com Mon Sep 29 17:35:15 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 29 Sep 2008 14:35:15 -0700 (PDT) Subject: Music knowledge representation References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> <20080929124940.8c1c82e8.darcy@druid.net> <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> Message-ID: On Sep 29, 3:56?pm, "D'Arcy J.M. Cain" wrote: > On Mon, 29 Sep 2008 20:29:44 +0200 > > "Mr.SpOOn" wrote: > > > Couldn't the note class simply have a list of all the notes and have a > > > simple method calculate the actual pitch? > > > That's not really how it works. There exists just 12 octave > > independent pitch classes. This means that there is a pitch class C > > with all possible Cs. There ambiguities with accidentals, because > > different named notes fall in the same pitch class. The difference is > > important for the musical theory, because C# and Db belongs to the > > same pitch class (actually they are the same note, they sounds > > completely identical -- because on the piano you play them pressing > > the same key), but in a scale they have a very different role. > > Sure, they are enharmonically identical but in our tempered scale. > That's why my example showed it as (note, octave, accidental) rather > than a specific note. ?It would differentiate between these. > > > For example, the interval C F# is an "augmented fourth", because what > > really matters are the natural note (C and F), and their distance if > > 4. Then it is augmented due to the #- > > > But the interval C Gb (Gb is the same as F#) is a "diminished fifth". > > This is true. ?My simple example would not have dealt with this. ?The > arguments would have to be the full tuple rather than the actual pitch. > > > So I can't list all pitches. > > You can but you can't store them as raw pitches. > > > > ? ?def interval(self, lower, higher) > > > ? ? ? ?if lower > higher: > > > ? ? ? ? ? ?# uncomment one of the two following lines depending > > > ? ? ? ? ? ?# on the behaviour you want > > > ? ? ? ? ? ?#lower,higher = higher,lower > > > ? ? ? ? ? ?#higher += 12 > > > > ? ? ? ?# could use some error trapping > > > ? ? ? ?return self.interval_name[higher - lower] > > > > Note that lower and higher could be a note object that you have to > > > convert to integers first. > > > I can't estabilish which note is higher, because all the analysis part > > is octave independent. Anyway thanks for the ideas. > > I'm not sure I understand this. ?You either have to assume that the > first note is the root or the lower one is. ?What other options are > there? ?It sounds like your requirement is "higher += 12" or some > variant. ?It also depends on whether you need to deal with things like > ninths and thirteenths. > > Anyway, I was just tossing out ideas. ?You know what your requirements > are better than I. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolveshttp://www.druid.net/darcy/? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. I like D'Arcy's tuples so far. You could have a 4th element that contains adjustment for temper. Octave could be None. You want ( 4, None, 1 ) "sharp 4th" == ( 5, None, -1 ) "flat 5th", but you can't have it. The closest ones are Note( 4, None, 1 )== Note( 5, None, -1 ) or Note(4, None, 1 ).enh_cmp( Note( 5, None, -1 ) ). More elaborate code means more options for calling, though: Note(4, None, 1 ).cmp_enh( 5, None, -1 ), and just call the constructor on the 3 arguments. You also want Note( 9, None, 0 ).cmp_octave( 2, Rel+ 1, 0 ), 9th== 2nd + 1 octave, and Note( 9, None, 0 ).cmp_nooctave( 2, None, 0 ), where cmp_... functions return in ( -1, 0, 1 ), and the middle term can be a class Relative instance, which indicates a relative octave instead of absolute... or just start at 4. From fredrik at pythonware.com Wed Sep 17 08:42:25 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 14:42:25 +0200 Subject: recursive using the os.walk(path) from the os module In-Reply-To: References: Message-ID: A. Joseph wrote: > I want to search through a directory and re-arrange all the files into e.g > > All .doc files go into MS WORD folder, all .pdf files goes into PDF Folder. > > I`m thinking of doing something with the os.walk(path) method from os > module, I need some ideal how the algorithm should look like, maybe > recursive ..any deal? os.walk traverses the directory tree, so I'm not sure why you think that your program needs to use recursion? wouldn't a plain loop work? import os, shutil for dirpath, dirnames, filenames in os.walk(directory): for name in filenames: source = os.path.join(dirpath, name) ... check extension and determine target directory ... destination = os.path.join(targetdir, name) shutil.move(source, destination) tweak as necessary. From eric.e.janke at gmail.com Tue Sep 23 11:18:03 2008 From: eric.e.janke at gmail.com (Eric E) Date: Tue, 23 Sep 2008 08:18:03 -0700 (PDT) Subject: Attachment Size and SMTP EMail References: Message-ID: <14a905ea-11a6-449d-af33-b184f28e178e@59g2000hsb.googlegroups.com> On Sep 23, 9:52 am, Grant Edwards wrote: > On 2008-09-23, Eric E wrote: > > > I am using python to send an email with a large zip file as an > > attachment. I successfully sent a 52M attachment. If I try > > to send a 63M attachment or larger, the message never gets > > through. I do not get any errors in my python code. > > Does sending large attachements with other SMTP clients using > the same SMTP server work? > > -- > Grant Edwards grante Yow! Zippy's brain cells > at are straining to bridge > visi.com synapses ... I do not know for sure. I recently downloaded msmtp 1.4.16 and am still in the process of trying to get it to work. From hniksic at xemacs.org Thu Sep 11 07:33:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 11 Sep 2008 13:33:01 +0200 Subject: Accessing __slots__ from C References: Message-ID: <87k5diex3m.fsf@mulj.homelinux.net> [ You can use the capi-sig for questions like this; see http://mail.python.org/mailman/listinfo/capi-sig ] Chris writes: > I'd like to be able to access an attribute of a particular Python > object as fast as possible from some C code. > > I wondered if using __slots__ to store the attribute would allow me to > do this in a faster way. > > The reason I'd like to do this is because I need to access the > attribute inside a loop within some C code, and I find that the > attribute lookup using the 'PyObject_GetAttrString' call is far slower > than any of the subsequent calculations I perform in C. PyObject_GetAttrString is convenient, but it creates a Python string only so it can intern it (and in most cases throw away the freshly created version). For maximum efficiency, pre-create the string object using PyString_InternFromString, and use that with PyObject_GetAttr. From xnews2 at fredp.lautre.net Wed Sep 10 14:36:15 2008 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 10 Sep 2008 18:36:15 GMT Subject: PyGUI as a standard GUI API for Python? References: <48BFB534.2080508@egenix.com> Message-ID: Todd Whiteman said : > Personally, I believe XULRunner has a lot to offer for Python GUI > development, I'm currently finishing up some documentation steps to show > off how to use it specifically for Python (I'll post it to this list > when it's finished). That would be really nice ! I've long been curious about the potential of XUL+Python, but put off by the lack of leads to follow up, and not having time to do the digging myself... TIA, fp From larry.bates at vitalEsafe.com Wed Sep 3 22:17:56 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Wed, 03 Sep 2008 21:17:56 -0500 Subject: Submitting forms over HTTPS with mechanize In-Reply-To: References: Message-ID: <48BF4554.7060809@vitalEsafe.com> Rex wrote: > Hello, > > I am working on an academic research project where I need to log in to > a website (www.lexis.com) over HTTPS and execute a bunch of queries to > gather a data set. I just discovered the mechanize module, which seems > great because it's a high-level tool. However, I can't find any decent > documentation for mechanize apart from the docstrings, which are > pretty thin. So I just followed some other examples I found online, to > produce the following: > > baseurl = 'http://www.lexis.com/' > br = mechanize.Browser() > br.set_handle_robots(False) > br.addheaders = [('User-Agent', 'Firefox')] > br.open(baseurl) > br.select_form(name="formauth") > br["USER_ID"]="my_user_id" > br["PASSWORD"]="my_password" > result = br.submit() > > This code hangs at br.submit(), and I can't tell what I'm doing wrong. > Typically I would inspect the HTTP data with an HTTP debugging proxy > (Fiddler), but I guess since this is HTTPS I can't do that. Any > glaring errors in my code? > > By the way, does anyone have suggestions for Python modules that I > should use instead of mechanize (and that are sufficiently easy)? If > mechanize fails, I might try modifying some similar Perl code a friend > sent me that logs into lexis.com. > > Thanks so much, > > Rex I've used mechanize quite successfully but others have suggested Twill http://twill.idyll.org/. It seems to be at least documented. -Larry From timr at probo.com Sat Sep 6 21:57:53 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 07 Sep 2008 01:57:53 GMT Subject: Determining Processor Vender References: <554ecfcf-96d8-4602-8d5e-ee5d70590124@i76g2000hsf.googlegroups.com> Message-ID: aha wrote: > >Dose anyone know of a cross-platform method for determining the vendor >of a processor? Under linux I can check /proc/cpuinfo. What I'd like >to be able to do is determine if a processor is AMD or Intel, so that >I can use the appropriate numerical libraries for my application. If you have a numerical library that uses processor-specific instructions, then the library must be in C with assembler. If so, just add another function that does a "cpuid" instruction and return the results. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From pDOTpagel at helmholtz-muenchen.de Wed Sep 3 06:41:52 2008 From: pDOTpagel at helmholtz-muenchen.de (Philipp Pagel) Date: Wed, 3 Sep 2008 10:41:52 +0000 (UTC) Subject: Renumbering References: Message-ID: Francesco Pietra wrote: > ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 > ATOM 3425 CA LEU B 428 142.918 87.524 78.875 1.00115.20 2SG3427 [...] > As you can see, the number of lines for a particular value in column 6 > changes from situation to situation, and may even be different for the > same name in column 4. For example, LEU can have a different number of > lines depending on the position of this amino acid (leucine). Others have alreade given good hints but I would like to add a bit of advice. The data you show appears to be a PDB protein structure file. It is important to realize that these are fixed-width files and columns can be empty so splitting on tab or whithespace will often fail. It is also important to know that the residue numbering (cols 23-26) is not necessarily contiguous and is not even unique without taking into account the 'insertion code' in column 27 which happens to be empty in your example. I would recommend to use a full-blown PDB parser to read the data and then iterate over the residues and do whatever you would like to acomplish that way. Biopython has such a parser: www.biopython.org cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://mips.gsf.de/staff/pagel From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 12:33:47 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 18:33:47 +0200 Subject: Not fully OO ? In-Reply-To: <48d4c11b$0$22877$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <48d541d8$0$32185$426a34cc@news.free.fr> candide a ?crit : > Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > > Thanks for any comment. The following definitions are AFAIK the only commonly accepted definitions about OO: 1/ an object is defined by identity, state and behaviour 2/ objects interacts by sending messages each other 3/ an OO program is made of interacting objects I let you find out whether Python meets these 3 definitions - and if Java does (hint : in Python, everything you can bind to a name is an object - this is not true in Java or C++). From ptmcg at austin.rr.com Fri Sep 26 10:18:28 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 26 Sep 2008 07:18:28 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> Message-ID: On Sep 25, 10:41?am, "Dmitry S. Makovey" wrote: > Diez B. Roggisch wrote: > > Dmitry S. Makovey schrieb: > >> Dmitry S. Makovey wrote: > >>> In my real-life case A is a proxy to B, C and D instances/objects, not > >>> just one. > > >> forgot to mention that above would mean that I need to have more than one > >> decorator function like AproxyB, AproxyC and AproxyD or make Aproxy > >> smarter about which property of A has instance of which class etc. > > > __getattr__? > > see, in your code you're assuming that there's only 1 property ( 'b' ) > inside of A that needs proxying. In reality I have several. So in your code > self._delegate should be at least a tupple or a list. Plus what you're > doing - you just promiscuously passing any method not found in Proxy to > self._delegate which is not what I need as I need to pass only a subset of > calls, so now your code needs to acquire dictionary of "allowed" calls, and > go over all self._delegates to find if any one has it which is not > efficient since there IS a 1:1 mapping of A::method -> B::method so lookups > shouldn't be necessary IMO (for performance reasons). > No, really, Diez has posted the canonical Proxy form in Python, using __getattr__ on the proxy, and then redirecting to the contained delegate object. This code does *not* assume that only one property ('b'? where did that come from?) is being redirected - __getattr__ will intercept all attribute lookups and redirect them to the delegate. If you need to get fancier and support this single-proxy-to-multiple- delegates form, then yes, you will need some kind of map that says which method should delegate to which object. Or, if it is just a matter of precedence (try A, then try B, then...), then use hasattr to see if the first delegate has the given attribute, and if not, move on to the next. > > I'm trying to figure out if there > is another way to use decorators for my scenario or is there another way of > achieving the same thing without using decorators and without bloating up > the code with alternative solution. > > Another way could be to use Metaclass to populate class with method upon > declaration but that presents quite a bit of "special" cruft which is more > than I have to do with decorators :) (but maybe it's all *necessary* ? ) > Your original question was "is decorator the right thing to use?" For this application, the answer is "no". It sounds like you are trying to force this particular to solution to your problem, but you are probably better off giving __getattr__ intercepting another look. -- Paul From alan.isaac at gmail.com Mon Sep 1 18:05:35 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Mon, 01 Sep 2008 22:05:35 GMT Subject: Py 2.6 changes In-Reply-To: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Now math has factorial: > http://docs.python.org/dev/library/math.html#math.factorial That's rather underdocumented. Does it really attempt exact calculation for arbitrary integers?? Is there any way to request a nice fast approximation for large integers (e.g., with Gosper's modification of Stirling's formula)? Alan Isaac From circularfunc at gmail.com Mon Sep 1 14:31:42 2008 From: circularfunc at gmail.com (ssecorp) Date: Mon, 1 Sep 2008 11:31:42 -0700 (PDT) Subject: Getting an objetcs dict? Message-ID: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> I did nce(I think). class X X.__dict__() and ngot a dict of its variables. Now i get errors doing this. what am i doing wrong? From tchendrix at gmail.com Wed Sep 24 16:08:32 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Wed, 24 Sep 2008 13:08:32 -0700 (PDT) Subject: empty csv file attachments Message-ID: hi group. I'm new to python but a veteran at programming. This one has me stumped. I have a simple contact form which the user fills out. The email is sent to the site user as well and it is delivered with the content in the body of the email as well in nice order. I have modified my code to also send the content as a csv attachment. On the server, the file is perfectly generated with content. The attachment, however, is completely blank. Any ideas what that could be? My code snippet is shown below: if int(attachmenttype)==2 or int(attachmenttype)==3: for field in ctx.request.field_names(): if field=='last_name': myfilename=ctx.request.field_value(field)+'.txt' if myfilename=='': myfilename='tempfile.txt' mypath= mynewfilepath + '/' + myfilename f=open(mypath, 'w') mynewstring='' counter=0 for field in ctx.request.field_names(): if field != 'inquiry_required': mynewstring=mynewstring + field +',' if mynewstring[-1]==',': mynewstring=mynewstring[0:len(mynewstring)-1] f.write(mynewstring) f.write ('\n') mynewstring='' counter=1 for field in ctx.request.field_names(): fielddata=ctx.request.field_value(field) if counter==1: dummydata=0 else: mynewstring=mynewstring + '"' + fielddata.replace('"','') + '",' counter = counter + 1 if mynewstring[-1]==',': mynewstring=mynewstring[0:len(mynewstring)-1] f.write(mynewstring) f.write('\n') f.close attachments.append('/'.join((ctx.request.library, myfilename))) [snip... sends email just after this] any ideas? From marco.bizzarri at gmail.com Sat Sep 13 10:44:01 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 13 Sep 2008 16:44:01 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] Message-ID: <3f0d61c40809130744l48fe45a0x8c45972a071179ba@mail.gmail.com> On Sat, Sep 13, 2008 at 4:11 PM, Fredrik Lundh wrote: > Marco Bizzarri wrote: > >> class FolderInUse: > >> >> >> def true_for(self, archivefolder): >> return any([instance.forbid_to_close(archivefolder) for instance in >> self.core.active_outgoing_registration_instances()]) >> >> Is this any better? The true_for name does not satisfy me a lot... > > well, "true_for" is indeed pretty inscrutable, but I'm not sure that would > be the first thing I'd complain about in that verbose mess... "verbose mess". It is always frustrating when you do what you think is your best and you read that. Anyway: I'm here to learn, and, of course, part of it is to listen those who've been there much longer than you. So, thanks for your sincere evaluation, Fredrik :-). > (when you pick method names, keep in mind that the reader will see the > context, the instance, and the arguments at the same time as they see the > name. there's no need to use complete sentences; pick short short > descriptive names instead.) Maybe I'm looking at the wrong direction, right now. From the point of view of the FolderInUse clients, they will do: condition = FolderInUse(core) condition.true_for(folder) Is this too verbose? This is not a polemic statement, I'm really asking your opionion. The expression inside the true_for is indeed complex, and maybe I can simplify it; however, I'm deeply convinced that instance.forbid_to_close(folder) has some good points on it; I mean, once I read this kind of code, I can hope to understand it without looking at what forbid_to_close does. > > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From carsten.haese at gmail.com Tue Sep 30 13:39:05 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 30 Sep 2008 13:39:05 -0400 Subject: OS.SYSTEM ERROR !!! In-Reply-To: References: Message-ID: Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > > The executable would execute perfectly. > > > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") > > > The executable file would start to execute until it would print an error > stating that it cannot use a (.dat) file, which is located under the > following directory: > > > C:\myprogramfolder\run\inputs\io\control.dat > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? The program (myprogram.exe) is not looking for C:\myprogramfolder\run\inputs\io\control.dat, it's looking for inputs/io/control.dat relative to its current working directory. That will only work if the current working directory of the program is C:\myprogramfolder\run. Is it? -- Carsten Haese http://informixdb.sourceforge.net From robert.kern at gmail.com Mon Sep 8 16:53:02 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Sep 2008 15:53:02 -0500 Subject: hashing an array - howto In-Reply-To: References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > John Machin: >> Consider this:>>> hash(123) == hash(123.0) == hash(123L) >> True > > Right... Can you explain me why Python designers have chosen to build > a hash() like that? Because that's the kind of hash that dicts expect. If two objects are equal (i.e. (x==y) is True), they need to have their hash values equal as well. In order to do a lookup into a dict, it will hash the key and search the table for a that hash value. If there are multiple keys with the same hash value, then the dict will compare the keys by value to find a match. Since (123==123.0==123L), they must also have the same hash value such that {123.0: 'got it'}[123] == 'got it' -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Mon Sep 15 17:24:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 23:24:06 +0200 Subject: Python Nautilus script In-Reply-To: References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <6j7t7rF1tl5rU1@mid.uni-berlin.de> <6j80nvF1ttmfU1@mid.uni-berlin.de> Message-ID: <6j823mF1u6ivU1@mid.uni-berlin.de> Chris Rebert schrieb: > On Mon, Sep 15, 2008 at 2:00 PM, Diez B. Roggisch wrote: >>>>> It appears that's because HOSTNAME is not exported. >>>>> But in the case of Nautilus script, how to workaround this issue? >>> Alternatively, export the variable when you create it, in .bashrc or >>> wherever it is getting created. That's probably the Right Thing to >>> Do(tm) in this case. >> >> Certainly not, as the OP uses a network monitoring software called Nautilus >> - and that communicates state to subprocesses using environment variables. >> Nothing to do with .bashrc. > > Just to clarify, the OP is talking about Nautilus as in the GNOME file > manager, not some network monitor. Erm, yep - I confused that with Nagios. Please don't ask me why. The point stands though - .bashrc has nothing to do with that. Diez From ceball at users.sourceforge.net Thu Sep 11 16:12:52 2008 From: ceball at users.sourceforge.net (Chris) Date: Thu, 11 Sep 2008 20:12:52 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: <87k5diex3m.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic xemacs.org> writes: ... > [ You can use the capi-sig for questions like this; see > http://mail.python.org/mailman/listinfo/capi-sig ] Thanks, I had no idea about that. > PyObject_GetAttrString is convenient, but it creates a Python string > only so it can intern it (and in most cases throw away the freshly > created version). For maximum efficiency, pre-create the string > object using PyString_InternFromString, and use that with > PyObject_GetAttr. Yes, we'd thought of that too, but it doesn't seem to be an important factor compared to the actual attribute lookup. Thanks for the advice, Chris From gagsl-py2 at yahoo.com.ar Thu Sep 4 23:16:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 00:16:18 -0300 Subject: Tkinter Radio button on the second window References: Message-ID: En Thu, 04 Sep 2008 22:01:25 -0300, Dream escribi?: > The code create 2 windows. 2 radiobuttons are put on the second > window. A control variable "v" is binded to the 2 widgets. > But when I run the code, I found the control variable not binded > succsessfully: The second radiobutton was not selected by default; > Click ed each button always print 1. I don't know what is wrong. So I > need help.Thanks. > > from Tkinter import * > window1=Tk() > window2=Tk() Don't create more than one root Tk instance. Weird things happen, like this. If you need another, separate window, use a Toplevel widget. -- Gabriel Genellina From brad.at.school at gmail.com Tue Sep 23 16:16:31 2008 From: brad.at.school at gmail.com (brad.at.school at gmail.com) Date: Tue, 23 Sep 2008 13:16:31 -0700 (PDT) Subject: curses.setsyx()? References: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> Message-ID: <713190fc-e3a9-4a72-8bee-4fd3affcb531@c58g2000hsc.googlegroups.com> On Sep 22, 11:24?pm, Tim Roberts wrote: > linkmaster032... at gmail.com wrote: > >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: > >> On Sep 19, 1:24?am, Tim Roberts wrote: > > >> > linkmaster032... at gmail.com wrote: > > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > >> > >cursor. Any alternatives/solutions? > > >> > Did you call doupdate after? ?setsyx just manipulates the data structures. > >> > It takes a call to doupdate to force those changes to take effect visually. > >> > -- > >> > Tim Roberts, t... at probo.com > >> > Providenza & Boekelheide, Inc. > > >> I added it and it still doesn't work. This is what I'm doing when I > >> want to display the cursor and prepare it for input at 2,3: > > >> curses.echo() > >> curses.curs_set(1) > >> curses.setsyx(2,3) > >> curses.doupdate() > > >Any idea what's wrong? > > No. ?Are you able to post an entire sample that demonstrates the problem? > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. http://pastebin.com/m6413db1 Run that and press 'n' key. It is supposed to move the cursor to 2,3 and it doesn't. From sjmachin at lexicon.net Fri Sep 12 15:51:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Sep 2008 12:51:30 -0700 (PDT) Subject: book example confusion References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: On Sep 13, 5:36?am, byron wrote: > I am reading o'reilly's learning python (great book), but i came > across an example (pg 291, pdf) that I am not quite understanding the > reasoning for the author's explanation: > > if f1() or f2(): > > The author states that do to the nature of that expression, if f1() > returns True, f2() will not be evaluated.. which makes sense. His > quote: > > ? ? ? ? "Here, if f1 returns a true (or nonempty) value, Python will > never run f2." > > He then states: > > ? ? ? ? "To guarantee that both functions will be run, call them > before the 'or':" > > tmp1, tmp2 = f1(), f2() > if tmp1 or tmp2: > > Being that each function is an object, a name assignment to > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > the name is called.. so why would the latter example "run" both > functions as the author suggests? It's not a "name assignment". In effect it's doing this: tmp1 = f1() # get the RESULT of calling f1() tmp2 = f2() # likewise f2 if tmp1 or tmp2: # if result1 or result2 A (pointless) "name assignment") with the nil effect that you fear would look like this: tmp1, tmp2 = f1, f2 # Look, no parentheses after function names if tmp1() or tmp2(): HTH, John From xlebourd at gmail.com Wed Sep 3 11:25:04 2008 From: xlebourd at gmail.com (Xavier) Date: Wed, 3 Sep 2008 08:25:04 -0700 (PDT) Subject: Serial I/O problem with pywin32 ? References: Message-ID: I tried under Linux... same problem. So... it may comes from my little lines of code... or from my GPS. From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 11:00:59 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 17:00:59 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: <48dcf924$0$4653$426a74cc@news.free.fr> Patrick Mullen a ?crit : > Depending on the scale of the website I am making, how much I care > about editing it in the future, and how much I just want to get > something up, I will occasionally use php. And I am a self confessed > php hater :) But it's generally the fastest way I know to get > something up. So even terrible languages can have their uses! Sorry but I fail to see how it relates to the current thread ??? From castironpi at gmail.com Sat Sep 6 00:57:38 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 5 Sep 2008 21:57:38 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> Message-ID: <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> On Sep 5, 9:20?pm, "Manu Hack" wrote: > On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: > > On Sep 5, 3:28 am, "Manu Hack" wrote: > >> On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: > >> > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: > >> >> David C. Ullrich: > > >> >> > At least in mathematics, the sum of the elements of > >> >> > the empty set _is_ 0, while the maximum element of the > >> >> > empty set is undefined. > > >> >> What do you think about my idea of adding that 'default' argument to > >> >> the max()/min() functions? > > >> >> Bye, > >> >> bearophile > > >> > For max and min, why can't you just add your argument to the set > >> > itself? > > >> > The reason max([]) is undefined is that max( S ) is in S. > > >> It makes sense. > > >> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. > > >> It doesn't make sense to me. ?What do you set x to? > > > For all x. > > But then how can you conclude sum([]) = 0 from there? ?It's way far > from obvious. You can define sum([a1,a2,...,aN]) recursively as sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) "X", then subtract aN. sum([a1,a2,...a(N-1)])+aN=X sum([a1,a2,...a(N-1)])+aN-aN=X-aN For N=2, we have: sum([a1,a2])=X sum([a1,a2])-a2=X-a2 sum([a1,a2])-a2-a1=X-a2-a1 Since X= a1+ a2, replace X. sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 Or, sum([a1,a2])-a2-a1=0 Apply the recursive definition: sum([a1])+a2-a2-a1=0 And again: sum([])+a1+a2-a2-a1=0 And we have: sum([])=0. From adityashukla1983 at gmail.com Sat Sep 27 16:44:19 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Sat, 27 Sep 2008 15:44:19 -0500 Subject: File modifications Message-ID: <73045cca0809271344k68ce6bb7i403ac15d5770b06f@mail.gmail.com> Hello folks , I have a file like this /T_0_size=105((-bin-ulockmgr_server:0.99[&&NHX:C=0.195.0],(((-bin-hostname:0.00 [&&NHX:C=200.0.0], (-bin-dnsdomainname:0.00[&&NHX:C=200.0.0],(-bin-domainname:0.00[&&NHX:C=200.0.0],(-bin-nisdomainname:0.00[&&NHX:C=200.0.0],-bin-ypdomainname:0.00[&&NHX:C=200.0.0]):0.00):0.00):0.00):0.98 ,(-bin-iptables-xml:0.97[&&NHX:C=0.183.0],(-bin-dbus-send:0.78[&&NHX:C=0.94.0],-bin-dbus-monitor:0.78[&&NHX:C=0.94.0]):0.97):0.98):0.99. I wanna get the file in this format ((-bin-ulockmgr_server:0.99,(((-bin-hostname:0.00,(-bin-dnsdomainname:0.00,(-bin-domainname:0.00,(-bin-nisdomainname:0.00,-bin-ypdomainname:0.00):0.00):0.00):0.00):0.98 ,(-bin-iptables-xml:0.97,(-bin-dbus-send:0.78,-bin-dbus-monitor:0.78):0.97):0.98):0.99 ie , remove /T_0_size , [&&NHC:C=0.195.0] , [&&NHX:C=200.0.0] and so on , how should i handle this after reading the file? Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: From almar.klein at gmail.com Sat Sep 20 16:12:44 2008 From: almar.klein at gmail.com (Almar Klein) Date: Sat, 20 Sep 2008 22:12:44 +0200 Subject: matplotlib in interactive mode locks when run from subprocess In-Reply-To: References: Message-ID: I think my question was not very clear. I narrowed the problem down to a reconstructable small example, consisting of a python script (a very simple interpreter) and three lines to execute in it: ========== start simple interpreter file ====== import os import sys import time def run(): while True: # read a line of text, the thread is stuck here untill a \n is # fed to the stream. time.sleep(0.1) line = "" try: line = sys.stdin.readline() except Exception, why: sys.stdout.wite(why.message+"\n") if line: try: code = compile(line,"","exec") exec(code) except Exception, why: sys.stderr.write(why.message) sys.stderr.write(">>> ") if __name__ == "__main__": run() ========== end of file ============== Now I run this file (by double clicking it) and I get a prompt. The three lines I type in are: import matplotlib.pylab as pl pl.ion() #interactive mode on pl.plot([1,2,3],[4,6,5]) This produces a tk window, but it's unresponsive. The process does have 5 threads, so matplotlib managed to create the threads, but it seems as if they're blocked. When I run the three lines of code in a normal python shell, I get the proper results: a responsive figure (I can zoom and pan) and my shell is still responsive too. I am in the dark why this does not work. Any thoughts anyone? I've been busy all day trying to get this right, with hardly any progress... :( Almar PS: I run windows xp, my matplotlibrc file has the backend: TkAgg, interactive: True 2008/9/18 Almar Klein > Hi, > > In wxpython, I made an interactive shell, which creates a remote python > subprocess > to do the interpreting. Communication is done via a pipe. The idea is that > the python > session is an actual process separate from the GUI, which has some > advantages, > like I can have multiple such shells in my application, and I can kill them > without > worrying that my wx app will crash. > > To do this I use the wx.Process class, which allows asynchronous > communication with > the remote process. > > This all works really, I will also launch wxpython apps. So I was quite > happy, untill I tried > doing some plotting with matplotlib (in TkAgg backend). The problem is that > the process > becomes unresponsive when I plot something (No prompt is written to the > stdout/stderr). > (more details below) > > I don't know much about creating subprocess and how they are different from > a normal > process. So can anyone offer some help as to what the problem might be? > > Thanks in advance, > Almar > > To get to the details: > - When I start a process with command "python -u -i" > -- When interactive mode is off, the whole process becomes unresponsive > when doing > pylab.show() > -- When interactive mode in on, on doing pylab.plot(), a figure appears, > which I can > zoom etc., but the process is now stuck, also after closing the figure > > - When I start a process with command > "python -u -c 'import code;code.interact(readfunc=raw_input)'" (This is > how Pype does it). > -- When interactive mode is off, the figures show when doing pylab.show() > and the process > behaves as normal after closing the figure(s). > -- When interactive mode in on, on doing pylab.plot(), a figure appears, > but most of the time > it is not drawn and emmediately unresponsive, just like the process > itself. > > I have also tried an asynchronous Popen recipe by Joshiah Carlson I found > on > activestate. And I made my own process class using > win32process.CreateProcess. > Both alternatives to wx.Process resulted in the same sympoms. > > Oh, and I run windows. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From afriere at yahoo.co.uk Wed Sep 24 05:07:58 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 24 Sep 2008 02:07:58 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 24, 9:52 am, Neal Becker wrote: > In hindsight, I am disappointed with the choice of conditional syntax. I know it's too late to change. The problem is > > y = some thing or other if x else something_else > > When scanning this my eye tends to see the first phrase and only later notice that it's conditioned on x (or maybe not notice at all!). Particularly if 'some thing or other' is long or complicated. The struggle to get a conditional operator was a long and bitter, so in the first place we should be glad we aren't writing "y = (conditional and [p] or [q])[0] anymore. Since it was but grudgingly bestowed I thought BDFL had chosen this particular syntax just to be difficult. However since using it for a while, I am surprised how natural it is to use and read. A canonical use of the conditional operator is in pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). For this and similar short uses, where the regular if statement is an annoyance this syntax if else works nicely. More complicated conditionals or cases are probably better handled by an if statement. This syntax is also probably not the best for nested conditionals. The latter, however, is probably feature rather than bug. From sh006d3592 at blueyonder.co.uk Sun Sep 14 16:46:08 2008 From: sh006d3592 at blueyonder.co.uk (Stephen Horne) Date: Sun, 14 Sep 2008 21:46:08 +0100 Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> Message-ID: On 14 Sep 2008 20:25:18 GMT, Steven D'Aprano wrote: >"The fact that many languages disallow instantiation of abstract types >(and force subtypes to implement all needed functionality) further >ensures program correctness." > >http://en.wikipedia.org/wiki/Abstract_base_class > >but I don't see how that follows (except possibly in very special cases). >Given that the set of instances of class B is empty, how does that help >you know that B.method is correct? That's the point - to be certain that the set of instances of class B really is empty. As for B.method, it's correctness isn't purely determined by the code of the method itself. It will usually depend on the object being in a self-consistent state. It's often impossible for an instance of an abstract base to have a self-consistent state. Therefore, it's better to guarantee that no instances can be accidentally created. OTOH, this argument is often an over-pedantic technicality. You can't eliminate all errors from code by making the language stricter. Instantiating an abstract class isn't a very common error in my experience. Whether detecting it is a priority depends on what you're doing. From castironpi at gmail.com Fri Sep 12 02:53:02 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 11 Sep 2008 23:53:02 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> Message-ID: <99ae2c42-695b-4ed8-a639-faf41746898c@c65g2000hsa.googlegroups.com> On Sep 12, 1:30?am, Steven D'Aprano wrote: > On Thu, 11 Sep 2008 22:40:01 -0700, Dennis Lee Bieber wrote: > > On 12 Sep 2008 03:37:51 GMT, Steven D'Aprano > > declaimed the following in > > comp.lang.python: > > >> I'm pretty sure you're wrong. XML can be used for serialization, but > >> that doesn't mean it is only sequential data. XML is suitable for > >> hierarchical data too. To quote Wikipedia: > > > ? ?There is a difference between the format of the data content, and > > the processing of that data... Regardless of the content, one > > essentially has to process the XML /file/ sequentially, and translate > > into an in-memory model that allows for accessing said data. To reach > > the nth subelement of the mth element requires reading all 1..m-1 > > elements, followed by all 1..n-1 subelements in m. Modifying any element > > requires rewriting the entire file. > > Which is why I previously said that XML was not well suited for random > access. > > I think we're starting to be sucked into a vortex of obtuse and opaque > communication. We agree that XML can store hierarchical data, and that it > has to be read and written sequentially, and that whatever the merits of > castironpi's software, his original use-case of random access to a 4GB > XML file isn't workable. Yes? > > -- > Steven By 'isn't workable' do you mean, "no one ever uses 4GB of XML", or "no one ever uses 4GB or hierarchical data period"? From michael.pearmain at tangozebra.com Mon Sep 8 11:14:01 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Mon, 8 Sep 2008 08:14:01 -0700 (PDT) Subject: Dictionaries and loops References: <48c52c54$0$16982$426a74cc@news.free.fr> <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> <48c53322$0$3460$426a74cc@news.free.fr> Message-ID: <069dc97f-9a6f-4adf-9667-c02a352836b3@b1g2000hsg.googlegroups.com> Thanks for the solution above, The raw data looked like User-ID,COUNTS 576460840144207854,6 576460821700280307,2 576460783848259584,1 576460809027715074,3 576460825909089607,1 576460817407934470,1 and i used CSV_INPUT1 = "C:/Example work/Attr_model/Activity_test.csv" fin1 = open(CSV_INPUT1, "rb") reader1 = csv.DictReader((fin1), [], delimiter=",") for row in reader1: print row with the following outcome. {None: ['User-ID', 'COUNTS']} {None: ['576460840144207854', '6']} {None: ['576460821700280307', '2']} {None: ['576460783848259584', '1']} {None: ['576460809027715074', '3']} {None: ['576460825909089607', '1']} So i can see csv.reader is what i should have been using Thanks for the help From Lie.1296 at gmail.com Wed Sep 17 12:18:22 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 17 Sep 2008 09:18:22 -0700 (PDT) Subject: translating ascii to binary References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> Message-ID: On Sep 17, 11:02?pm, Canned wrote: > Hi, > I'm trying to write a class that can convert ascii to binary and vice > versa. I write my class based on this function I've found on internet > > > > > > > def ascii_to_bin(char): > > ascii = ord(char) > > bin = [] > > > while (ascii > 0): > > if (ascii & 1) == 1: > > bin.append("1") > > else: > > bin.append("0") > > ascii = ascii >> 1 > > > bin.reverse() > > binary = "".join(bin) > > zerofix = (8 - len(binary)) * '0' > > > return zerofix + binary > > > some_string = 'Time to go now, Rummy?' > > > binary = [] > > for char in some_string: > > binary.append(ascii_to_bin(char)) > > > print binary > > print " ".join(binary) > > That works perfectly, but when I try to implement it in my own class it > gives me alot of headache, also because I'm totally new to the language. > It work only with one character at a time, and if I give a string it > just give some weird result. > > > > > > > if len(sys.argv) < 2: > > ? ? ? ? print 'usage:', os.path.basename(sys.argv[0]), 'text' > > ? ? ? ? sys.exit() > > > class Converterab: > > ? ? ? ? ''' > > ? ? ? ? Ascii-binary converter. > > ? ? ? ? ''' > > ? ? ? ? def __init__(self, string): > > ? ? ? ? ? ? ? ? self.string = string > > > ? ? ? ? def ascii_to_bin(self): > > ? ? ? ? ? ? ? ? bindump = [] > > ? ? ? ? ? ? ? ? for char in self.string: > > ? ? ? ? ? ? ? ? ? ? ? ? bin = ord(char) > > ? ? ? ? ? ? ? ? ? ? ? ? while bin > 0: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if (bin & 1) == 1: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bindump.append("1") > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bindump.append("0") > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bin = bin >> 1 > > ? ? ? ? ? ? ? ? bindump.reverse() > > ? ? ? ? ? ? ? ? print bindump ? # Debug tool, delete this > > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? Zero fix in bindump > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? bindump.insert(0, "0") > > ? ? ? ? ? ? ? ? count = 0 > > ? ? ? ? ? ? ? ? pos = 0 > > ? ? ? ? ? ? ? ? for dg in bindump: > > ? ? ? ? ? ? ? ? ? ? ? ? count += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? pos += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? if count == 8: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? bindump.insert(pos, "0") > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? count = 0 > > ? ? ? ? ? ? ? ? bindump.pop() > > ? ? ? ? ? ? ? ? print bindump ? # Debug tool, delete this, the best result so far > > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? Reversing array per byte > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? final = [] > > ? ? ? ? ? ? ? ? pos -= pos ? ? ?# Set pos to 0 again > > ? ? ? ? ? ? ? ? while len(bindump) != 0: > > ? ? ? ? ? ? ? ? ? ? ? ? print count ? ? # Debug tool, delete this, this is weird, start at 1, I expected 0 > > ? ? ? ? ? ? ? ? ? ? ? ? count += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? if count > 8: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pos += 8 > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? count -= count > > ? ? ? ? ? ? ? ? ? ? ? ? final.insert(pos, bindump.pop()) > > ? ? ? ? ? ? ? ? ? ? ? ? print final ? ? # Debug tool, delete this > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? for ar in bindump: > > ? ? ? ? ? ? ? ? ? ? ? ? count += 1 > > ? ? ? ? ? ? ? ? ? ? ? ? if (count < 8): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? final.insert(pos, bindump.pop()) > > ? ? ? ? ? ? ? ? ? ? ? ? elif (count >= 8): > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pos = count > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? final.insert(pos, bindump.pop()) > > ? ? ? ? ? ? ? ? ? ? ? ? else: > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? final.insert(pos, bindump.pop()) > > ? ? ? ? ? ? ? ? ''' > > ? ? ? ? ? ? ? ? final.insert(0, final.pop()) > > > ? ? ? ? ? ? ? ? binary = "".join(final) > > ? ? ? ? ? ? ? ? return binary > > > result = Converterab(sys.argv[1]) > > > print "Char : ", result.ascii_to_bin() > > The problem start at "Reversing array per byte". That block should > reversing the array from 'bindump' and copy it to 'final' per 8 items, > e.g. a = ['0', '1', '0', '1', '0', '1', '0', '1', '2', '1', '2', '1', > '2', '1', '2', '1', '3', '2', '3', '2', '3', '2', '3', '2'] > b = ['3', '2', '3', '2', '3', '2', '3', '2', '2', '1', '2', '1', '2', > '1', '2', '1', '0', '1', '0', '1', '0', '1', '0', '1'] > > Any advice about this matter would be very appreciated. > Thanks in advance. It'd be easier to make a one-char version of ascii2bin then make the string version based on the one-char version. From circularfunc at yahoo.se Tue Sep 16 08:01:25 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 05:01:25 -0700 (PDT) Subject: How to load current buffer into interpreter in emacs? Message-ID: I'm trying to switch to using emacs for python. The interpreter and python-mode works but I can't load the file I'm editing into the interpreter. im not sure if c-c c-l is supposed to do that but it complains "no module xxxx" . what needs to be in my emacs-path? what needs to be in my windows path? I have c:/python25. adding that tot he path ads everything inside python25? i have my programs in: c:/python25/progs/ in which i have /progdir/someprog.py for example From dudeja.rajat at gmail.com Sat Sep 6 15:22:47 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 6 Sep 2008 20:22:47 +0100 Subject: How to bring subprocess to the foreground? In-Reply-To: <1563bbfd-6219-4719-940f-91cd84c419e5@l42g2000hsc.googlegroups.com> References: <6ifhg2Fq24n6U1@mid.uni-berlin.de> <1563bbfd-6219-4719-940f-91cd84c419e5@l42g2000hsc.googlegroups.com> Message-ID: On Sat, Sep 6, 2008 at 6:53 PM, Paul Boddie wrote: > On 6 Sep, 17:58, dudeja.ra... at gmail.com wrote: >> >> I though of displayin an information message on the screen through >> tkMessageBox while the subprocess is running, I did it using: >> >> try: >> testing = subprocess.Popen([batchFilePath], \ >> shell = True) >> >> retCode = testing.wait() > > Note that you wait for the process to finish here... > >> tkMessageBox._show("Test Harness execution", \ >> icon = 'info', \ >> message="Testing %s in progress..." % libName) > > ...and that you show a message about the process running *after* > waiting until it isn't running any more. > >> except: >> tkMessageBox._show("Error", \ >> type='ok', icon='error', \ >> message="Error executing %s Test >> Harness" % libName) >> return None >> else: >> print retCode >> >> But the message is never displayed. Please suggest if there is >> something wrong with this code > > I think you should first show your message, *then* wait for the > process to finish. > > Paul > -- > http://mail.python.org/mailman/listinfo/python-list > Such a silly mistake I'm committing. Thanks a ton. -- Regrads, Rajat From castironpi at gmail.com Sat Sep 27 08:39:59 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 05:39:59 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <00ee05ca$0$20666$c3e8da3@news.astraweb.com> Message-ID: <1a7184f3-c71e-49b7-a8f8-f141705f3573@l42g2000hsc.googlegroups.com> On Sep 27, 5:33?am, Steven D'Aprano wrote: > On Sat, 27 Sep 2008 18:20:17 +1000, Ben Finney wrote: > > Steven D'Aprano writes: > > >> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: > >> > An ordinary singleton is instantiating the class multiple times yet > >> > returning the same instance object; a class singleton is simply using > >> > the class directly (like a module). > > > Where is this "class singleton" terminology from? > > I don't know. Googling on it brings up an awful lot of C++ and Java > source code for regular Singletons. Perhaps Aahz can shed some light on > it? [snip] > In my example, the instance doesn't matter. I could write it like this: > > >>> class CallableAppendor(object): > > ... ? ? thing = (0, 1, 2) > ... ? ? @classmethod > ... ? ? def __call__(cls, *args): > ... ? ? ? ? return len(args + cls.thing) > ...>>> appendor = CallableAppendor() > >>> appendor.thing = (1, 2, 3, 4, 5, 6, 7, 8) > >>> appendor(1, 2, 4, 8, 16) > 8 > >>> CallableAppendor.__call__(1,2,4,8,16) > > 8 > > but what's the purpose of instantiating the class? I've used them (class singletons, adopting the term) as a Globals namespace, but only to the end of tidying. It makes it easy to reassign immutables. It is too bad 'CallableAppendor.__call__(1,2,4,8,16)' doesn't work as expected. That is, 'CallableAppendor(1,2,4,8,16)' dosen't call '__call__'. I have a workaround, which may be just what you're looking for. >>> class A(type): ... def __call__( self, *ar ): ... print 'call', self, ar ... >>> class B(object): ... __metaclass__= A ... >>> B(3) call (3,) Overriding the __call__ method of 'type' has the effect of giving you a static __call__ method on a class-- a method which doesn't need an instance to call. Your behavior may be counterintuitive though, to someone who wants to instantiate 'B', in this case, and proceed like a normal object. That is, they want to call a generic class and use it, and also expect instances of B to behave as B. You can't have both, so either return B from B.__new__, or, to instantiate B, take the long way and call B.__new__ directly. >>> B.__new__(B) <__main__.B object at 0x009FDB70> Has anyone stepped through the C code to find out when the decision is made to call which function, B.__new__ or A.__call__, when B is called? I'm happy that overriding type.__call__ produced the intended results; it's always nice when things go right. From prologic at shortcircuit.net.au Thu Sep 18 20:34:42 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Sep 2008 10:34:42 +1000 Subject: Twisted vs Python Sockets In-Reply-To: References: <8a6b8e350809181310q74b1af40u29eb0ed707946cce@mail.gmail.com> Message-ID: On Fri, Sep 19, 2008 at 6:24 AM, Fredrik Lundh wrote: > James Matthews wrote: > >> I am wondering what are the major points of twisted over regular python >> sockets. I am looking to write a TCP server and want to know the pros can >> cons of using one over the other. > > Twisted is a communication framework with lots of ready-made components: > > http://twistedmatrix.com/trac/wiki/TwistedAdvantage > > Regular sockets are, well, regular sockets. No more, no less. There is also one more alternative: pymills - current version 3.4 It has a different design goal to twisted and is in no competition with twisted, however provides: * An event framework * A component driven architecture * A set of components including: * TCPServer, TCPClient * UDPServer, UDPClient * Some protocol components: * IRC * HTTP * SMTP * Some other components: * Environment * Logger * Stdin * Config A simple EchoServer is as simple as: http://hg.shortcircuit.net.au/index.wsgi/pymills/file/4247696a5633/examples/net/echoserer.py If anyone is interested in trying this library out, feel free. I recommend you use the latest development branch available via Mercurial at: http://hg.shortcircuit.net.au/pymills/ hg clone http://hg.shortcircuit.net.au/pymills/ If you have any questions, don't hesitate to ask me. Enjoy :) cheers James -- -- -- "Problems are solved by method" From hv at tbz-pariv.de Fri Sep 12 03:47:42 2008 From: hv at tbz-pariv.de (Thomas Guettler) Date: Fri, 12 Sep 2008 09:47:42 +0200 Subject: Better error message on recursive import In-Reply-To: <6isunqF6v3jU2@mid.uni-berlin.de> References: <6isb2mF9scaU1@mid.individual.net> <6isunqF6v3jU2@mid.uni-berlin.de> Message-ID: <6iul4uFkaviU1@mid.individual.net> Hi, > Can you give an example of such a recursive import you want the special > exception be raised? ===> cat one.py from two import testtwo def testone(): print "one" ===> cat two.py import one def testtwo(): print "two" ===> python one.py Traceback (most recent call last): File "one.py", line 1, in from two import testtwo File "/mnt/home/tguettler/tmp/rec/two.py", line 1, in import one File "/mnt/home/tguettler/tmp/rec/one.py", line 1, in from two import testtwo ImportError: cannot import name testtwo -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From kaerbuhez at gmail.com Mon Sep 15 17:26:18 2008 From: kaerbuhez at gmail.com (kaer) Date: Mon, 15 Sep 2008 14:26:18 -0700 (PDT) Subject: Python Nautilus script References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> Message-ID: <99dc3fb0-f4ea-4b3e-926c-ce3462cd9973@b1g2000hsg.googlegroups.com> On 15 sep, 21:46, Michel Leunen wrote: > > But in the case of Nautilus script, how to workaround this issue? > > -- > Michel Leunen > http://linux.leunen.com I don't have that issue. This script works as expected: --------------- #! /usr/bin/python # -*- coding: utf8 -*- import os, sys #NAUTILUS_SCRIPT_SELECTED_FILE_PATHS : chemins des fichiers s?lectionn?s s?par?s par des retours ? la ligne (newline) (uniquement pour les fichiers locaux) #NAUTILUS_SCRIPT_SELECTED_URIS : URIs des fichiers s?lectionn?s s?par?s par des retours ? la ligne (newline) #NAUTILUS_SCRIPT_CURRENT_URI : URI de l'emplacement actuel #NAUTILUS_SCRIPT_WINDOW_GEOMETRY : position et taille de la fen?tre actuelle KEYS=("NAUTILUS_SCRIPT_SELECTED_FILE_PATHS", "NAUTILUS_SCRIPT_SELECTED_URIS", "NAUTILUS_SCRIPT_CURRENT_URI", "NAUTILUS_SCRIPT_WINDOW_GEOMETRY") ft=open("/home/kaer/stupid.txt", "w") for key_value in [(key, os.environ.get(key, 'NOT FOUND')) for key in KEYS]: ft.write("env(%s): %s\n" % key_value) file_names=sys.argv[1:] for index, file_name in enumerate(file_names): ft.write("%s: [%s]\n" % (index, file_name)) if os.path.isfile(file_name): os.rename(file_name, '%03d-%s' % (index+1, file_name)) ft.close() --------------- I selected 3 files (created on purpose) in Nautilus. Those files where renamed and stupid.txt created with that content: --------------- env(NAUTILUS_SCRIPT_SELECTED_FILE_PATHS): /home/kaer/baz /home/kaer/bar /home/kaer/foo env(NAUTILUS_SCRIPT_SELECTED_URIS): file:///home/kaer/baz file:///home/kaer/bar file:///home/kaer/foo env(NAUTILUS_SCRIPT_CURRENT_URI): file:///home/kaer env(NAUTILUS_SCRIPT_WINDOW_GEOMETRY): 1280x885+0+25 0: [baz] 1: [bar] 2: [foo] --------------- You can as well use sys.argv[1:] that will give you the list of selected files. Hope that helps. From bearophileHUGS at lycos.com Sun Sep 28 18:19:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 28 Sep 2008 15:19:21 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: <81bc4138-5179-4b67-a15c-0d663c498af4@k37g2000hsf.googlegroups.com> Tim Chase: > I suspect that the zfill responses don't have the property of equally > distributed "randomness", as the first digit may more likely be a zero. This code I have shown before: str(randrange(100000)).zfill(5) If the numbers are equally distributed in [0, 99999], then the leading zeros have the correct distribution. A little test program for you: from string import digits from random import choice, randrange from collections import defaultdict def main(): N = 1000000 freqs1 = defaultdict(int) for i in xrange(N): n = "".join(choice(digits) for d in xrange(5)) freqs1[n[0]] += 1 print [freqs1[str(i)] for i in xrange(10)] freqs2 = defaultdict(int) for i in xrange(N): n = str(randrange(100000)).zfill(5) freqs2[n[0]] += 1 print [freqs2[str(i)] for i in xrange(10)] import psyco; psyco.full() main() The output: [100153, 99561, 99683, 100297, 99938, 100162, 99738, 100379, 100398, 99691] [99734, 100153, 100091, 100683, 99580, 99676, 99671, 100131, 100102, 100179] Of course with a bit of math you can also demonstrate it :-) Bye, bearophile From bj_666 at gmx.net Sun Sep 28 02:05:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 28 Sep 2008 06:05:11 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <6k8l4nF6jbmtU1@mid.uni-berlin.de> On Sat, 27 Sep 2008 22:37:09 -0700, est wrote: > The problem is, why the f**k set ASCII encoding to range(128) ???????? Because that's how ASCII is defined. ASCII is a 7-bit code. > while str() is internally byte array it should be handled in range(256) > !!!!!!!!!! Yes `str` can handle that, but that's not the point. The point is how to translate the contents of a `unicode` object into that range. There are many different possibilities and Python refuses to guess and tries the lowest common denominator -- ASCII -- instead. > I now spending 60% of my developing time dealing with ASCII range(128) > errors. It was PAIN!!!!!! > > Please fix this issue. > > http://bugs.python.org/issue3648 > > Please. The issue was closed as 'invalid'. Dealing with Unicode can be a pain and frustrating, but that's not a Python problem, it's the subject itself that needs some thoughts. If you think this through, the relationship between characters, encodings, and bytes, and stop dreaming of a magic solution that works without dealing with this stuff explicitly, the pain will go away -- or ease at least. Ciao, Marc 'BlackJack' Rintsch From seandavi at gmail.com Tue Sep 23 11:39:45 2008 From: seandavi at gmail.com (Sean Davis) Date: Tue, 23 Sep 2008 08:39:45 -0700 (PDT) Subject: lxml and adding a stylesheet Message-ID: I have an xml document and simply need to add an xml-stylesheet to it. I am using lxml to parse the xml document and then would like to insert the xml-stylesheet tag using the etree api. Any suggestions? Thanks, Sean From __peter__ at web.de Thu Sep 25 04:47:10 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 Sep 2008 10:47:10 +0200 Subject: python sorting 2dim. array ? References: <9684e81b-df99-4d95-99f9-8345c125b69b@d77g2000hsb.googlegroups.com> Message-ID: fredo66 at fulladsl.be wrote: > hello, > Can someone help me with this: > I have a array like this > > list[rowindex][colomindex] > > where rows are the records and colom the fields. If I use the .sort() > method on 'list' the data is sorted on the items of the first colom. > But I want to sort on the second colom as first (and as second > sortfield the first colom). > > What is the shortest code for this pls ? > > (all fields are text value, first colom is name, second category) >>> items = [(1,2), (2,2), (2,1)] >>> items.sort(lambda x, y: cmp(x[1::-1], y[1::-1])) >>> items [(2, 1), (1, 2), (2, 2)] If you want something more efficient, see http://www.python.org/doc/faq/programming/#i-want-to-do-a-complicated-sort-can-you-do-a-schwartzian-transform-in-python Peter From paul at boddie.org.uk Thu Sep 18 06:34:12 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 18 Sep 2008 03:34:12 -0700 (PDT) Subject: Python for the iPhone? References: Message-ID: <6766f4fc-20a1-4aab-9599-a7a2080fcb06@m3g2000hsc.googlegroups.com> On 17 Sep, 11:54, s... at pobox.com wrote: > Anybody tried this port of Python to the iPhone? > > ? ?http://www.modmyi.com/nativeapps/python-v251/ > ? ?http://iphone.natetrue.com/ > > Hasn't been updated since July 2007. ?Maybe just a proof-of-concept? ?I'm > guessing it involves jailbreaking the phone. There's a very brief summary of iPhone drawbacks with respect to openness in this very interesting presentation from PyCon UK: http://freshfoo.com/presentations/PyCon_UK-2008/slides/ Although it probably doesn't tell you anything you didn't already know about Apple's disdain for people running "unauthorised" software on the iPhone, I think the Python involvement in Openmoko is very interesting and deserving of wider attention, especially amongst those considering getting a mobile device for its Python capabilities. Paul From tgrav at me.com Thu Sep 18 13:06:40 2008 From: tgrav at me.com (Tommy Grav) Date: Thu, 18 Sep 2008 13:06:40 -0400 Subject: Cython dynamic library problem In-Reply-To: <8763otl8ea.fsf@merkury.smsnet.pl> References: <8763otl8ea.fsf@merkury.smsnet.pl> Message-ID: <410690AD-DF18-4AAF-A0DB-4B241673AD3D@me.com> On Sep 18, 2008, at 12:35 PM, Rob Wolfe wrote: > > I would try to use `distutils` because this package is much wiser > than me and knows all necessary switches for gcc. ;) That worked! Thanks Cheers Tommy From max at alcyone.com Sun Sep 21 22:00:18 2008 From: max at alcyone.com (Erik Max Francis) Date: Sun, 21 Sep 2008 19:00:18 -0700 Subject: appending * to glob returns files with '*' !! In-Reply-To: References: Message-ID: John [H2O] wrote: > I have a glob.glob search: > > searchstring = os.path.join('path'+'EN*') > files = glob.glob(searchstring) > for f in files: > print f > > > ___ > This returns some files: > EN082333 > EN092334 > EN* > > My routine cannot handle the '*' and it should'nt be returned anyway? :-/ > > A bug? No, it means you actually have a file named 'EN*' in the directory. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Many would be cowards if they had courage enough. -- Thomas Fuller From badmuthahubbard at gmail.com Tue Sep 2 06:03:15 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Tue, 2 Sep 2008 13:03:15 +0300 Subject: Tkinter popup menu In-Reply-To: <873akqj73o.fsf@gmail.com> References: <873akqj73o.fsf@gmail.com> Message-ID: <8200bab70809020303n344c97b4udcd06be9cf91c79b@mail.gmail.com> On Thu, Aug 28, 2008 at 3:50 AM, Carl wrote: > "Chuckk Hubbard" writes: > >> Right-click popup menu. None of the options that come from the >> cascades can be selected with the mouse. If you select a submenu with >> the mouse and then use the arrow keys and enter key to select an >> option, it works, but the menu remains on the canvas. If you click >> the option with the mouse, the menu disappears but the function >> doesn't get called. >> Can someone tell me why? >> >> -Chuckk >> >> -- >> http://www.badmuthahubbard.com > > Try creating the "main" popup menu before the sub-menus, and when > instantiating the sub-menus, pass the main menu as the "master" > instead of "self.myparent": Thanks Carl, that indeed did it. -Chuckk > > Hope that helps. > Carl. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.badmuthahubbard.com From research at johnohagan.com Tue Sep 30 04:58:15 2008 From: research at johnohagan.com (John O'Hagan) Date: Tue, 30 Sep 2008 08:58:15 +0000 Subject: How best to pass arbitrary parameters from one function to another Message-ID: <200809300858.15923.research@johnohagan.com> Hi Pythonistas, I'm looking for the best way to pass an arbitrary number and type of variables created by one function to another. They can't be global because they may have different values each time they are used in the second function. So far I'm trying to do something like this: def process_args( [list, of, command-line, arguments] ): do stuff return {dictionary : of, local : variables } def main_function( **kwargs ): do stuff return result kw1 = process_args( [some, list] ) kw2 = process_args( [a, different, list] ) for i in main_function( **kw1 ): kw2[ var1 ] = i kw2[ var2 ] = len( i ) for j in main_function(**kw2): print j This only seems to work if I specify a default value for every possible parameter of main_function and also for any others which may be passed to it, which is a bit tedious because there are very many of them but only a few are used in any given execution of the program. Is there a better way to do it? Or have I simply made an error? Regards and thanks, John O'Hagan From michele.simionato at gmail.com Sat Sep 13 07:43:42 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 13 Sep 2008 04:43:42 -0700 (PDT) Subject: Injecting new names into the above frame References: <57uyk.101$fD.22@flpi145.ffdc.sbc.com> Message-ID: <31db78a6-050d-42f5-8c06-7b3418492e1c@73g2000hsx.googlegroups.com> On Sep 13, 1:35?pm, Peter Waller wrote: > This makes me want to ask: is it difficult to modify a function's > code? No, it is not difficult. Look at the byteplay module: it makes possible all kinds of dirty hacks. From google at mrabarnett.plus.com Mon Sep 22 19:55:25 2008 From: google at mrabarnett.plus.com (MRAB) Date: Mon, 22 Sep 2008 16:55:25 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <00e816f4$0$20303$c3e8da3@news.astraweb.com> <6602abad-3c12-4c0c-b41d-95f79cebdc31@y21g2000hsf.googlegroups.com> Message-ID: On Sep 22, 11:46?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 22, 5:32?pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: > > > On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano > > >> But that's precisely what I want to avoid: I don't want the objects to > > >> ?share *any* state, not even their class. I'm not trying for a Borg or > > >> ?Singleton: the user can call the factory as many times as they want, > > >> ?but the objects returned shouldn't share any state. I don't know if > > >> ?what I want has a name. Judging from people's reactions, I'd say > > >> ?probably not. > > > > Snce when are "users" ever involved > > > in programming problems or programming languages ? > > > What an astounding question. > > > Consider a class. There are the programmers who write the class, and > > there are the programmers (possibly the same people, but not necessarily) > > who use the class. The second set of people, the programmers who use the > > class, are *users* of the class. What else would they be? > > > -- > > Steven > > Usegrammers? And professionals are programmers, amateurs are amgrammers and newbies are newgrammers? :-) From gtitus_ at _wanadoo.fr Tue Sep 30 17:10:35 2008 From: gtitus_ at _wanadoo.fr (marc) Date: Tue, 30 Sep 2008 23:10:35 +0200 Subject: pylab without X11 In-Reply-To: References: Message-ID: <48e295c3$0$885$ba4acef3@news.orange.fr> This may help ... or not ( 2nd part ) try not to do pylab.figure() in your script: pylab.plot, or pylab.imshow or whatever you want to use then savefig("myFigure.png") for example do not use show() in my case ( with the WXAgg backend ), it works, it generates the png file Marc Willem-Jan Vriend a ?crit : > I want to use pylab (matplotlib) on a machine without X11. I'm trying to > generate onthefly graphics for an apache2 web service, so they do not > have to be displayed on this machine ! > > When i do > pylab.figure() > I get the error > TclError: couldn't connect to display ":0.0" > > I tried setting the DISPLAY environment variable to "", ":0.0" but I got > the same error message. > > Any help is very much appreciated. From bedouglas at earthlink.net Mon Sep 1 23:35:47 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 1 Sep 2008 20:35:47 -0700 Subject: python mechanize/libxml2dom question Message-ID: <108b01c90cac$fe079db0$0301a8c0@tmesa.com> hi... i've got the following situation, with the following test url: "http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#". i can generate a list of the tables i want for the courses on the page. however, when i try to create the xpath query, and plug it into the xpath within python, i'm missing something. if i have a parent xpath query, that generates a list of results/nodes... how can i then use the individual parent node, and trigger off of it, to get further information. i tried using the following chunk of code with no luck. #s is the html from the course file d = libxml2dom.parseString(s, html=1) #at this point, we should have a vaild "d" representation print "sdddd=",s aa=libxml2dom.toString(d) print "hereeeeee \n\n\n" print "aa",aa #sys.exit() # **** course names cpath='//table[position()>0]/descendant::td[position()=2][@width="85%"]/../t d[1]/font/a[2]/text()' cpath_=[] cpath_=d.xpath(cpath) print "len=",len(cpath_) if len(cpath_)>0: for cpath in cpath_: #get the coursename info cname=cpath.toString() print "cpath=",cpath print "cname=",cname rr="./../../../../../../following-sibling::table//tr[position()>1]" rr=cpath.xpath() print "rrlen=",len(rr) print rr[0].toString() sys.exit() i'm assuming that there's a libxml2node method that will do what i need that i'm missing... pointers/comments would be helpful here... thanks! From pmaupin at gmail.com Tue Sep 2 22:31:39 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Tue, 2 Sep 2008 19:31:39 -0700 (PDT) Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> Message-ID: <8e616d8f-a75e-4253-8b01-bd4b43e44a5b@e39g2000hsf.googlegroups.com> On Sep 2, 6:35?am, Nick Craig-Wood wrote: > bearophileH... at lycos.com wrote: > > ?It's not just my familiarity, Ada language too uses underscore for > > ?that purpose, I think, so there's a precedent, and Ada is a language > > ?designed to always minimize programming errors, simple code mistakes > > ?too. > > And perl also Add Verilog to that list. The ability to embed underscores in numeric literals, which the parser discards, is sometimes very useful in hardware description, especially when dealing with binary bit vectors which can sometimes be 32 bits or more long. Underscores are great. I have actually wished for this in Python myself, for those cases when I am doing binary. Spaces, not so much -- as others have pointed out, this is error prone, partly because spaces are "light weight" visually, and partly because the parser does not currently distinguish between different kinds of whitespace. I can't count how often I've forgotten a trailing comma on a line of items. To the complaints about the underscores getting in the way -- if the number is short, you don't need either underscores or spaces, and if the number is long, it's much easier to count underscores to find your position than it is to count spaces. Also, on long numbers (where this is most useful), the issue with mistaking a number for an identifier is much less likely to happen in real life. I think the issue of location sensitivity has already been flogged enough, but I will give it one last hit -- long numbers, where this is most useful, are often encountered in domain-specific mini languages, where the number of digits in each portion of a number might have some specific meaning. If the proposal were restricted to "once every 3 digits" or something similar, it would not be worth doing at all. +1 on the original proposal. Pat From chardish at gmail.com Thu Sep 25 11:36:51 2008 From: chardish at gmail.com (chardish at gmail.com) Date: Thu, 25 Sep 2008 08:36:51 -0700 (PDT) Subject: "which python" as a python command? References: Message-ID: On Sep 25, 11:14?am, Carsten Haese wrote: > import sys > print sys.executable This is exactly what I needed. Thanks! From steven at REMOVE.THIS.cybersource.com.au Fri Sep 26 03:28:04 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 07:28:04 GMT Subject: How to get the filename in the right case ? References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> Message-ID: On Fri, 26 Sep 2008 01:46:15 +0200, Stef Mientki wrote: > Secondly thoughtless copying of current behavior, doesn't bring any > progress, > and I think that's one of the reasons why we're still burdened by > inventions done 20 years ago, > e.g. "do you want to save your changes ?". I click No about 50% of the time, and Yes Of Course You Stupid Machine the other 50% of the time. Until they have a computer capable of reading my mind, I'm curious what alternative you'd suggest. -- Steven From gh at ghaering.de Sat Sep 6 04:50:02 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 06 Sep 2008 10:50:02 +0200 Subject: embed python in ms-word? In-Reply-To: References: Message-ID: <6ieuhqFqbgnlU1@mid.uni-berlin.de> oyster wrote: > In my ms-word documnet, there are some calculation whihc I have to > change due to different argumnet. is there any way to embed python > code in word, so that I can write the following as a macro or > something else, then the result (i.e. 2) is shown in the word > documnet? > > def f(n): > if n<2: > return 1 > else: > return f(n-1)+f(n-2) > main() > return 'fib(3)=%0i' % f(3) > > if that is impossible, does there exist such word-addons can do that? thanx With Python and the win32 extensions you can write COM servers. These you can use from Visual Basic for Applications (VBA). But it's really only worth the effort if you're doing something less trivial than above ;-) -- Gerhard From gminick at bzt.bzt Mon Sep 1 06:39:14 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 10:39:14 +0000 (UTC) Subject: Processes in Linux from Python References: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> Message-ID: On Sun, 31 Aug 2008 23:25:56 -0700 (PDT), Johny wrote: > To get a number of the http processes running on my Linux( Debia box) > I use > ps -ef | grep "[h]ttpd" | wc -l ... > So my question is: > Is it possible to get a number of the http processes running on Linux > directly from Python ? Yes, it is. There is a number of third party packages that provide such functionality, including PSI: http://www.psychofx.com/psi/ I never actually liked them, because they are parsing /proc directory by themselves. Thus I wrote my own tool that is a wrapper around procps library (libproc* in your /lib, probably). Your system tools like ps, w or top are using this library. My wrapping library is available at: http://code.google.com/p/procpy/ In your case you could use it like this: >>> import procpy >>> pp = procpy.Proc() >>> for pid in pp.pids: ... if pp.procs[pid]['cmd'] == 'apache2': ... print pp.procs[pid]['tid'] ... 5204 5205 5206 5208 >>> it prints the PIDs of all the apache2 processes on my system. Procpy is fine for my own needs, but if I were about to write a code that is intended to be portable, I'd use PSI. It also is more mature. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From python-url at phaseit.net Tue Sep 30 05:06:21 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 30 Sep 2008 09:06:21 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 30) Message-ID: QOTW: "AFAICT, _everybody_ is bad at programming C++. One begins to suspect it's not the fault of the programmers." - Grant Edwards Mixing integer, float, Decimal and Fraction objects when comparing may yield unexpected results: http://groups.google.com/group/comp.lang.python/browse_thread/thread/eebc7ee9d9f2ffb0/ Usually class attributes don't have a docstring attached - how to define one? http://groups.google.com/group/comp.lang.python/browse_thread/thread/18a8c3f09ac02f85/ How do people manage their development and production environments (apt, .deb/.rpm, virtualenv, eggs...)? http://groups.google.com/group/comp.lang.python/browse_thread/thread/5d14be5d870f1600/ A real counterexample to the "Python is slow" usual claim (C++ and Python versions of the same CPU intensive task have similar performance): http://groups.google.com/group/comp.lang.python/browse_thread/thread/a63979a6f18bf37/ Implementing (some kind of) "proxy" object to multiple delegates (step by step, and with changing requirements!) http://groups.google.com/group/comp.lang.python/browse_thread/thread/a917e13bf0ea261f/ Should a library terminate program execution when it encounters an error? http://groups.google.com/group/comp.lang.python/browse_thread/thread/f01d514fbe3183ad/ An attempt to explain how closures and dynamic scope work: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c6463402371857dc/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From dear.jay.logan at gmail.com Sat Sep 6 17:27:11 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sat, 6 Sep 2008 14:27:11 -0700 (PDT) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <3e74dfde-fc97-462f-b665-c5c9f8841633@m73g2000hsh.googlegroups.com> On Sep 6, 5:04?pm, Andreas Hofmann wrote: > Hello Folks! > > I've got a little problem here, which which really creeps me out at the > moment. > I've got some strings, which only contain numbers plus eventually one > character as si-postfix (k for kilo, m for mega, g for giga). I'm trying > to convert those strings to integers, with this function: > > def eliminate_postfix(value): > ? ? ? ? ?if type(value) is str: > ? ? ? ? ? ? ? ? ?value.upper() > ? ? ? ? ? ? ? ? ?if value.endswith('K'): > ? ? ? ? ? ? ? ? ? ? ? ? ?mult = 1000 > ? ? ? ? ? ? ? ? ?elif value.endswith('M'): > ? ? ? ? ? ? ? ? ? ? ? ? ?mult = 1000000 > ? ? ? ? ? ? ? ? ?elif value.endswith('G'): > ? ? ? ? ? ? ? ? ? ? ? ? ?mult = 1000000000 > ? ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ? ? ? ?mult = 1 > > ? ? ? ? ? ? ? ? ?if mult is 1: > ? ? ? ? ? ? ? ? ? ? ? ? ?value = string.atoi(value) > ? ? ? ? ? ? ? ? ?else: > ? ? ? ? ? ? ? ? ? ? ? ? ?value = string.atoi(value[:-1]) * mult > ? ? ? ? ?return value > > The problem is as follows: Everytime a string with a postfix should get > converted, mult does not get set properly. It is always 1. Does anyone > have an idea how to fix this? I just don't see it, maybe because I'm > pretty new to python or because I'm just blind I would be really greatful. > > Kind regards, > Andy Hello, 1. You call value.upper(), but you do not capture the results of that method. Strings are immutable in Python. >> value = value.upper() 2. You should use == instead of "is" in the comparison of mult being 1. >> if mult == 1: From mail at timgolden.me.uk Thu Sep 25 08:08:59 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 25 Sep 2008 13:08:59 +0100 Subject: Connecting to SMB share in python In-Reply-To: <2008092518182581491-rokwok@newsguycom> References: <2008092518182581491-rokwok@newsguycom> Message-ID: <48DB7F5B.8000000@timgolden.me.uk> Ronnie Kwok wrote: > Yes, I am running the script under linux and it will be doing some > processing before copying it over to the samba mount. > > It's totally fine to mount it with os.sys(...) approach but I am just > thinking if there's other option. I'm not really a Linux person but from all I can see from Googling around a bit, the os.system ("mount/unmount") option is still the most viable. Hopefully someone with real expertise can chip in. BTW, opinion in this ng/mailing list tends to favour bottom-posting or interleaved posting. TJG From bj_666 at gmx.net Wed Sep 17 09:45:24 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Sep 2008 13:45:24 GMT Subject: python regex character group matches References: Message-ID: <6jcfvkF2eqh0U2@mid.uni-berlin.de> On Wed, 17 Sep 2008 09:27:47 -0400, christopher taylor wrote: > the other day, i was trying to match unicode character sequences that > looked like this: > > \\uAD0X... > > my issue, is that the pattern i used was returning: > > [ '\\uAD0X', '\\u1BF3', ... ] > > when i expected: > > [ '\\uAD0X\\u1BF3', ] > > the code looks something like this: > > pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) #print > pat.findall(txt_line) > results = pat.finditer(txt_line) > > i ran the pattern through a couple of my colleagues and they were all in > agreement that my pattern should have matched correctly. Correctly for what input? And the examples above are not matching (no pun intended) the regular expression. `pat` doesn't match '\\uAD0X' because there's no 'X' in the character class. BTW: Are you sure you need or want the `re.UNICODE` flag? Ciao, Marc 'BlackJack' Rintsch From pataphor at gmail.com Thu Sep 18 09:17:19 2008 From: pataphor at gmail.com (pataphor) Date: Thu, 18 Sep 2008 15:17:19 +0200 (CEST) Subject: [ANN] XPN 1.2.5 References: <48d0097d$0$40312$4fafbaef@reader5.news.tin.it> Message-ID: Nemesis wrote: > XPN (X Python Newsreader) is a multi-platform newsreader with Unicode > support. It is written with Python+GTK. It has features like > scoring/actions, X-Face and Face decoding, muting of quoted text, > newsrc import/export, find article and search in the body, spoiler > char/rot13, random taglines and configurable attribution lines. Thanks! It works great. What I especially like about it is that it can be run from the directory it is in, without needing to be installed. This enabled me to run it under Ubuntu from another Ubuntu computer using sshfs. After some tinkering I was also able to run the same instance from a windows XP computer using a samba share. (Although the samba share was rather hard to set up because all the subdirectories needed permissions ... something like sudo chmod o+rw -R *). To make it run from that XP computer I also needed to add an sys.path.insert(0,'./') after import sys in xpn.py . But anyway, I can now run it from anywhere and I'm really looking forward to start tinkering with whatever other functionality I can think of to add to it, but unfortunately it is rather complete :-) . Did you know there is a tab in Articles_DB.py line 8? :-) Ducking ... P. From coleb2 at gmail.com Mon Sep 15 11:22:29 2008 From: coleb2 at gmail.com (Brian Cole) Date: Mon, 15 Sep 2008 08:22:29 -0700 (PDT) Subject: ElementTree oddities Message-ID: I'm trying to extract the text from some xml. I figured this convenient python two-liner would do it for me: >>> from xml.etree.ElementTree import * >>> from cStringIO import StringIO >>> root = parse(StringIO(xml)).getroot() >>> ' '.join([n.text for n in root.getiterator() if n.text is not None]) However, it's missing some of the text. For example, the following XML: >>> xml = "Bar" Returns me a empty string. Seems the "" tag is borking it. Also, the for the following XML: >>> xml = "Bar:" I only get "Bar". It's missing the trailing colon. I'm not that experienced with XML so perhaps I am just missing something here. Please enlighten me. Thanks, Brian From bdesth.quelquechose at free.quelquepart.fr Sat Sep 13 11:12:04 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 Sep 2008 17:12:04 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: <48cbf09c$0$25189$426a74cc@news.free.fr> References: <48cbf09c$0$25189$426a74cc@news.free.fr> Message-ID: <48cbf432$0$27507$426a34cc@news.free.fr> Bruno Desthuilliers a ?crit : > Larry Bates a ?crit : > (snip) >> IMHO it reads better if you use the __call__ method of the class to >> return the value > > IMHO, it makes no sense at all to abuse the __call__ magic method here. Sorry - after a more careful re-read of other posts in the thread, it might make sense, given the use case : condition = FolderInUse(core) if condition.true_for(folder): # code here but then, a plain function (or a partial) might be even better - that is, if the FolderInUse class doesn't have other responsabilities. From jcd at sdf.lonestar.org Tue Sep 9 12:09:24 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 09 Sep 2008 12:09:24 -0400 Subject: Test if list contains another list In-Reply-To: <48c6380b$0$17080$426a34cc@news.free.fr> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> Message-ID: <1220976564.6148.13.camel@aalcdl07.lib.unc.edu> On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > Matimus a ?crit : > > On Sep 8, 12:32 am, Bruno Desthuilliers > > wrote: > (snip) > >> >>> set(a).issubset(set(b)) > >> True > >> >>> > >> > > Just to clarify, doing it using sets is not going to preserve order OR > > number of elements that are the same. > > > > That is: > > > >>>> a = [1,1,2,3,4] > >>>> b = [4,5,3,7,2,6,1] > >>>> set(a).issubset(set(b)) > > True > > > > This will return True if b contains at least on of each element found > > in a. If the OP wanted to check that list `a` appeared in order > > somewhere in list `b` then sets won't work. > > Indeed, and I should have mentionned this myself. Thanks for this reminder. > If preserving order is important, strings have many of the properties you're looking for, but it might take some work to figure out a suitable way to convert to a string. The problem is easier if you know something about the inputs. If all inputs are known to be numbers between 0 and 15, you can just do: if ''.join(map(hex, a)) in ''.join(map(hex, b)): return True Hmm... actually, with the '0x' prefix that hex() puts on numbers, I think this works for arbitrary integers. Cheers, Cliff From san82moon at gmail.com Mon Sep 1 04:48:17 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:48:17 -0700 (PDT) Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <7fe361c6-822f-477a-a124-0eb36668b419@p31g2000prf.googlegroups.com> On Sep 1, 1:45 pm, Bruno Desthuilliers wrote: > lee a ?crit : > > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, > > ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? > > It's quite simple (hint : read the FineManual(tm) for dict.items() and > list.index()), but 1/totally inefficient and 2/not garanteed to yield a > single value (what if 'dfsdf' happens to be also the 4th item of the > list bound to key 'address' ?). > > May I suggest you rethink your data structure instead ? What you have > here is obviously a collection of 'phno/email/name/address'records. > These records shouldn't be split across different objects. Assuming > 'phno' is a unique identifier for each record, a better data structure > would be: > > records = { > 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > # etc > > } > > This way, the lookup is as simple and efficient as possible. > > My 2 cents.... hi, i agree with u, my data strusture is not efficient. but all the records,viz...name,phno, email,address are all generated at runtime , when the user enters them. so how can i design my datastructure in that case? From dblubaugh at belcan.com Mon Sep 22 22:09:50 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 22 Sep 2008 22:09:50 -0400 Subject: Time.sleep(0.0125) not available within Linux Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380522CF11@AWMAIL04.belcan.com> To All, I was wondering if anyone has come across the issue of not being allowed to have the following within a Python script operating under Linux: time.sleep(0.0125) It appears that I am not allowed to have the object sleep. Has anyone encountered this specific issue before in the past? Thank You, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From durand1 at gmail.com Fri Sep 5 15:52:16 2008 From: durand1 at gmail.com (Durand) Date: Fri, 5 Sep 2008 12:52:16 -0700 (PDT) Subject: quake like multicoloured text References: <3d829a04-9005-4216-86dc-b1055edab4e7@f63g2000hsf.googlegroups.com> Message-ID: <212d4d2a-f2dd-496d-8a0f-da701cedcb3e@73g2000hsx.googlegroups.com> Oops, I meant, "I'm wondering how I could render text with PIL in which different parts of the text are different *colours*." From manuhack at gmail.com Fri Sep 5 22:20:06 2008 From: manuhack at gmail.com (Manu Hack) Date: Fri, 5 Sep 2008 22:20:06 -0400 Subject: max(), sum(), next() In-Reply-To: <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> Message-ID: <50af02ed0809051920n4e838fa4nce8c0e7560e6abfc@mail.gmail.com> On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: > On Sep 5, 3:28 am, "Manu Hack" wrote: >> On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: >> > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >> >> David C. Ullrich: >> >> >> > At least in mathematics, the sum of the elements of >> >> > the empty set _is_ 0, while the maximum element of the >> >> > empty set is undefined. >> >> >> What do you think about my idea of adding that 'default' argument to >> >> the max()/min() functions? >> >> >> Bye, >> >> bearophile >> >> > For max and min, why can't you just add your argument to the set >> > itself? >> >> > The reason max([]) is undefined is that max( S ) is in S. >> >> It makes sense. >> >> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >> >> It doesn't make sense to me. What do you set x to? > > For all x. But then how can you conclude sum([]) = 0 from there? It's way far from obvious. From mnordhoff at mattnordhoff.com Fri Sep 12 20:03:05 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 13 Sep 2008 00:03:05 +0000 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <00da5aca$0$2879$c3e8da3@news.astraweb.com> Message-ID: <48CB0339.5080305@mattnordhoff.com> Grant Edwards wrote: > On 2008-09-12, Matt Nordhoff wrote: > >> I think you misunderstand. He's referring to the Sender >> header, not the From header. The messages the listbot sends >> out have a Sender header of >> "python-list-bounces+user=example.com at python.org" (supposing >> the subscriber's email address is user at example.com). Bounces >> should be directed to the bitbucket or list admin or whatever, >> not the user in the From header. kring.com just has a broken >> mail server. > > So the statement below by Dennis Lee Bieber in message > 97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d at earthlink.com isn't actually > correct? > > >>Three: The bounce/ooo-reply is sent to the message author, not > >>to any intermediate host(s). After all, on that end, it's > >>normal email failure response -- notify the author of the > >>message. It doesn't matter that the original message was posted > >>on a Usenet newsgroup if that group is automatically relayed to > >>members of a mailing list. I have no idea. My post was assuming that Sjoerd Mullender was correct. With headers like "Return-Path", "Errors-To" and "Sender", ISTM the mailing list software is doing everything it can to avoid bounces getting sent to the user in the From header. If it's completely wrong, then, well, it would be silly to have gone to the effort. -- From kyosohma at gmail.com Tue Sep 23 11:21:04 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 23 Sep 2008 08:21:04 -0700 (PDT) Subject: python freeze help References: Message-ID: On Sep 23, 5:01?am, Gabriel Rossetti wrote: > Hello everyone, > > I'm trying to use python's freeze utility but I'm running into problems. > I called it like this : > > python /usr/share/doc/python2.5/examples/Tools/freeze/freeze.py > ~/Documents/Code/Python/src/jester/service.py -m jester > > then I did : make > > then I tried to run it : ./service > > and I get this : > > grossetti at desktop-01:~/tmp/freeze$ ./service > Traceback (most recent call last): > ? File "/home/grossetti/Documents/Code/Python/src/jester/service.py", > line 16, in > ? ? from jester import constants, utils > ? File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line > 20, in > ? ? from twisted.internet.protocol import Protocol, ClientCreator > ? File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", > line 17, in > ? ? from zope.interface import implements > ? File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in > > ? ? pkg_resources.declare_namespace('zope') > ? File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, > in declare_namespace > ? ? _handle_ns(packageName, path_item) > ? File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, > in _handle_ns > ? ? path = module.__path__; path.append(subpath) > AttributeError: 'str' object has no attribute 'append' > Error in sys.excepthook: > Traceback (most recent call last): > ? File "/usr/lib/python2.5/site-packages/apport_python_hook.py", line > 38, in apport_excepthook > ? ? from apport.packaging_impl import impl as packaging > ? File "/usr/lib/python2.5/site-packages/apport/__init__.py", line 1, in > > ? ? from apport.report import Report > ? File "/usr/lib/python2.5/site-packages/apport/report.py", line 20, in > > ? ? from problem_report import ProblemReport > ? File "/usr/lib/python2.5/site-packages/problem_report.py", line 18, in > > ? ? from email.MIMEMultipart import MIMEMultipart > ? File "/usr/lib/python2.5/email/__init__.py", line 79, in __getattr__ > ? ? __import__(self.__name__) > ImportError: No module named multipart I've gotten this error from py2exe before. I'm not sure how freeze works, but in py2exe I had to make sure the email package wasn't being accidentally excluded and explicitly included. > > Original exception was: > Traceback (most recent call last): > ? File "/home/grossetti/Documents/Code/Python/src/jester/service.py", > line 16, in > ? ? from jester import constants, utils > ? File "/home/grossetti/Documents/Code/Python/src/jester/utils.py", line > 20, in > ? ? from twisted.internet.protocol import Protocol, ClientCreator > ? File "/usr/lib/python2.5/site-packages/twisted/internet/protocol.py", > line 17, in > ? ? from zope.interface import implements > ? File "/usr/lib/python2.5/site-packages/zope/__init__.py", line 20, in > > ? ? pkg_resources.declare_namespace('zope') > ? File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1749, > in declare_namespace > ? ? _handle_ns(packageName, path_item) > ? File "/usr/lib/python2.5/site-packages/pkg_resources.py", line 1719, > in _handle_ns > ? ? path = module.__path__; path.append(subpath) > AttributeError: 'str' object has no attribute 'append' > > Does anyone have any ideas as of why I get this? > > Thank you, > Gabriel I don't know what this second error is... Mike From kib2 at free.fr Thu Sep 25 15:22:25 2008 From: kib2 at free.fr (kib2) Date: Thu, 25 Sep 2008 21:22:25 +0200 Subject: text processing In-Reply-To: <6k20ckF5glpmU1@mid.uni-berlin.de> References: <6k20ckF5glpmU1@mid.uni-berlin.de> Message-ID: <48dbe4f2$0$29163$426a74cc@news.free.fr> You can do it with regexps too : >------------------------------------------------------------------ import re to_watch = re.compile(r"(?P\d+)[/](?P[A-Z]+)") final_list = to_watch.findall("12560/ABC,12567/BC,123,567,890/JK") for number,word in final_list : print "number:%s -- word: %s"%(number,word) >------------------------------------------------------------------ the output is : number:12560 -- word: ABC number:12567 -- word: BC number:890 -- word: JK See you, Kib?. From rstarkov at gmail.com Sun Sep 14 04:06:41 2008 From: rstarkov at gmail.com (rs387) Date: Sun, 14 Sep 2008 01:06:41 -0700 (PDT) Subject: recursion gotcha? References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> Message-ID: On Sep 14, 9:01?am, cnb wrote: > def suma(xs, acc=0): > ? ? ? ? if len(xs) == 0: > ? ? ? ? ? ? ? ? acc > ? ? ? ? else: > ? ? ? ? ? ? ? ? suma(xs[1:], acc+xs[0]) > > it returns none. Yep, that's because there is no "return" statement anywhere. Python doesn't return expressions "by default", like functional languages do, so where you say "suma(xs[1:], acc+xs[0])" this just calls itself and returns nothing. Try this: def suma(xs, acc=0): if len(xs) == 0: return acc else: return suma(xs[1:], acc+xs[0]) print suma([1, 2, 3, 4, 5]) (prints 15) Roman From nuffnough at gmail.com Tue Sep 9 10:11:01 2008 From: nuffnough at gmail.com (nuffnough at gmail.com) Date: Tue, 9 Sep 2008 07:11:01 -0700 (PDT) Subject: noob help request - how to make a list of defined class? Message-ID: I have defined two classes with one common field (called code) and several different fields. In class A there is only one instance of any given code as all items are individual. In class B, there may be none, one or many instances of each code, as there can be any number of Bs referring to a single A. I need to make a list of Bs, remove dupes, and then create a list of As that have Bs. (I hope this makes sense!) with much research and reading of my book I managed to get this working, but at one stage I had errors that talked about being unable to concatenate type A. So I converted my As to string, and then did a split on commas to make a list. This worked fine for all the As that didn't have a comma in a field (about 85%) but I can't help feeling that this is a kludge, and that if Icould find a way to get a proper list of As instead of a list of lists created by converting to string and splitting, then my app would work properly. So I am hoping some of the nice folk here will help me out. The relevent function looks like this: def gen_B_A_list(): Bcodes = get_codes() all_As = read_A("A.csv") B_A = [] for i in range(len(codes)): Bcode = Bcodes[i] for A in all_As: filename = getattr(A, 'code') if filename == Bcode: BA = str(A) BA = string.split(BA, ',') B_A.append(BA) return B_A The element in question is after if filename == Bcode. How do I construct a list of my defined class A objects here instead of this? ( I can post the full code if needed, just thought it was better netiquette not to) TIA nuffi From mccredie at gmail.com Tue Sep 16 18:55:17 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 16 Sep 2008 15:55:17 -0700 (PDT) Subject: optparse References: Message-ID: <5b3e58f7-83fb-421c-8dac-cb8e9b34952a@n33g2000pri.googlegroups.com> I'm assuming you read at least some of the docs. This page makes it pretty clear: http://docs.python.org/lib/optparse-default-values.html Matt From marco.bizzarri at gmail.com Thu Sep 4 07:08:59 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 13:08:59 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <6i9tftFpi1lhU1@mid.uni-berlin.de> References: <6i9tftFpi1lhU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809040408u4a9f08d8jfb0af4cf7c5010ba@mail.gmail.com> On Thu, Sep 4, 2008 at 1:00 PM, Diez B. Roggisch wrote: > Marco Bizzarri wrote: > >> Let's say I've a class a, where I can write: > > Anticipating this obviously premature posting: > > http://dirtsimple.org/2004/12/python-is-not-java.html > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Ehi, Diez, that was fast :-) ! Thanks for the link, I saw it in the past days and I read it; and I appreciated it a lot (actually, it was a door to a new world in Python, for me). But I'm asking something I feel is a little different, as you can read in my message, once it is full. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From timr at probo.com Fri Sep 26 23:34:43 2008 From: timr at probo.com (Tim Roberts) Date: Sat, 27 Sep 2008 03:34:43 GMT Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> <98e4f068-5349-4b38-b15b-7e2436a0e4a7@f63g2000hsf.googlegroups.com> Message-ID: Mark Dickinson wrote: >On Sep 25, 8:55?am, Tim Roberts wrote: >> Marc 'BlackJack' Rintsch wrote: >> >0.1 actually is >> >> >In [98]: '%.50f' % 0.1 >> >Out[98]: '0.10000000000000000555111512312578270211815834045410' >> >? >> >> Actually, it's not. ?Your C run-time library is generating random digits >> after it runs out of useful information (which is the first 16 or 17 >> digits). ?0.1 in an IEEE 784 double is this: >> >> ? ? ?0.100000000000000088817841970012523233890533447265625 > >I get (using Python 2.6): > >>>> n, d = 0.1.as_integer_ratio() >>>> from decimal import Decimal, getcontext >>>> getcontext().prec = 100 >>>> Decimal(n)/Decimal(d) >Decimal('0.1000000000000000055511151231257827021181583404541015625') > >which is a lot closer to Marc's answer. Looks like your float >approximation to 0.1 is 6 ulps out. :-) Hmmph, that makes the vote 3 to 1 against me. I need to go re-examine my "extreme float converter". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sturlamolden at yahoo.no Tue Sep 23 09:41:33 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 06:41:33 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: <633d90d1-c2e9-45d7-852e-c4f3951656e3@d45g2000hsc.googlegroups.com> On Sep 23, 3:13?am, process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? Because Python is a dynamic language. While a function is executing, its name may be bound to another object. It may happen as a side effect of what the function is doing, or even from another thread. The compiler has no way of knowing that. Recursion can always be expressed as iteration, possibly with a Python list as stack. From mail at timgolden.me.uk Tue Sep 23 07:24:05 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 23 Sep 2008 12:24:05 +0100 Subject: python timers and COM/directshow In-Reply-To: References: Message-ID: <48D8D1D5.2030303@timgolden.me.uk> Sayanan Sivaraman wrote: > So I've written a simple video player using directshow/COM in VC++, > and I'm in the process of translating it to python. For example, when > the avi starts playing, I have a call media_control.Run() , etc. > > I'm wondering how I should go about updating my gtk.Hscale widget as a > trackbar for the avi player. > > In C++, I have the following callbacks that update the scrollbar and > video position with a timer. [... snip callbacks ...] > > I'm wondering how I would implement similar callbacks in Python for a > gtk.Hscale, and some sort of time [I'm not familiar with Pythons > timers/threading at all]. You'd help your cause a lot here if you posted *Python* code to indicate what's calling what back where. Also if you stated whether you were using, eg, the GTK toolkit which your description suggests, or some other GUI toolkit. Because they tend to vary as to how they arrange their callbacks. In geeneral, Python callbacks are trivial: you create the function to do whatever and then pass the function as an object into the calling-back function call. Something like this (invented GUI toolkit): def handle_lbutton_click (event): # # do stuff with lbutton click # def handle_widget_slide (event): # # do stuff with widget slide # handle_event ("lbutton_click", handle_lbutton_click) widget.attach_event ("slide", handle_widget_slide) But the details will obviously depend on the toolkit you use. TJG TJG From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:38:13 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:38:13 GMT Subject: Off topic: Sent from my Foo messages References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> <48DAB539.1010500@mattnordhoff.com> Message-ID: <00eaf368$0$20666$c3e8da3@news.astraweb.com> I'm seeing more and more posts from various people, on this list and others, with statements like the following: On Wed, 24 Sep 2008 18:45:35 -0400, David Di Biase wrote: > Sent from my iPhone Also "Sent from my Blackberry" and similar. Without wishing to be rude to David, who I'm sure is a nice guy and not at all the pretentious git that such a line makes him appear, are people adding this comment to the bottom of their posts, or is it something that their device automatically appends to the post? If people are adding it themselves, that's nice, I'm sure you're really excited about your new toy, but the rest of us don't care a monkey's toss. And if the device is automatically appending it, I think that's pretty damn rude and a good reason to avoid buying the obnoxious machines. -- Steven From metallourlante at gmail.com Thu Sep 11 08:00:05 2008 From: metallourlante at gmail.com (Alex) Date: Thu, 11 Sep 2008 05:00:05 -0700 (PDT) Subject: Extracing data from webpage References: Message-ID: <00fa212a-c2f1-49fb-b347-06947cd18720@a70g2000hsh.googlegroups.com> On Sep 11, 11:55?am, srinivasan srinivas wrote: > Hi, > I am trying to download data from a webpage. I use mechanize python module. > Could someone tell me how to set/pass an agent?like Mozilla or IE that we do in perl's WWW::Mechanize?? > > Thanks, > Srini > > ? ? ? Be the first one to try the new Messenger 9 Beta! Go tohttp://in.messenger.yahoo.com/win/ If you have to parse a web page, this could be also useful: http://www.crummy.com/software/BeautifulSoup/ From toddw at activestate.com Tue Sep 16 21:29:21 2008 From: toddw at activestate.com (Todd Whiteman) Date: Tue, 16 Sep 2008 18:29:21 -0700 Subject: ANN: Python GUI development using XULRunner Message-ID: <48D05D71.2060905@activestate.com> I've put together a tutorial that shows off how to build a GUI application using XULRunner (same architectural components as Firefox uses) that can be used in conjunction with the Python programming language. The tutorial covers how to build a Python/XULRunner GUI application: http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html The details in this tutorial covers the initial setup to full packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX is possible with a few deviations, I have tried to cover these deviations where applicable). Feedback is welcome. Cheers, Todd From lie.1296 at gmail.com Tue Sep 30 04:01:49 2008 From: lie.1296 at gmail.com (Lie Ryan) Date: Tue, 30 Sep 2008 15:01:49 +0700 Subject: What is not objects in Python? In-Reply-To: References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <1222761708.10129.9.camel@lieryan-laptop> On Mon, 2008-09-29 at 21:03 -0700, namekuseijin wrote: > On 28 set, 15:29, process wrote: > > I have heard some criticism about Python, that it is not fully object- > > oriented. > > So what? > > > Why isn't len implemented as a str.len and list.len method instead of > > a len(list) function? > > Because postfix notation sucks. The natural way of spelling is > adjective+noun and verb+predicate. That's one of the reasons I like > Lisp better than Python. > -- > http://mail.python.org/mailman/listinfo/python-list > Actually str.len and len(str) is just like saying "the string's length" and "the length of the string". There is no difference between the two except for personal preference. (I am no linguist-- not even a native speaker of English --but I think there is a subtle difference on emphasis, "the string's length" emphasizes on the length being string's property, while "the length of the string" emphasizes on the length itself, am I correct?) From gminick at bzt.bzt Mon Sep 1 06:54:18 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 10:54:18 +0000 (UTC) Subject: list + dictionary searching References: <6e642a00-9301-440d-902c-63713cf4a793@a2g2000prm.googlegroups.com> Message-ID: On Mon, 1 Sep 2008 03:14:22 -0700 (PDT), Manoj wrote: > I would like to : > > search dictionaries within this list > create a new list with dictionaries which gives 1 dictionary for every > user with month_year as a key and utilization for that month as a > value > > Please give your thoughts Reading about for loop seems like a good idea. You can easily create a set of functions that gives you direct access to the information you need. http://docs.python.org/tut/node6.html#SECTION006200000000000000000 http://docs.python.org/tut/node7.html#SECTION007500000000000000000 Give it a try. Try to design some functions that let you view and add new lists/dictionaries to your variables. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bearophileHUGS at lycos.com Sat Sep 20 13:13:10 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 20 Sep 2008 10:13:10 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Duncan Booth: > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) > > The exact equivalent would be: > for i in range(10, -1, -1): print i I'd use xrange there. Anyway, I have always felt that Python syntax not easy to understand at first sight, expecially when you try to convert a bit more complex inverted for loops from/to C to/from Python. It's one of the few cases where (for example) Pascal (loop) syntax wins a bit over Python syntax :-) Bye, bearophile From castironpi at gmail.com Wed Sep 24 21:12:04 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 18:12:04 -0700 (PDT) Subject: Er, one -lime- or two. Message-ID: <2ac98076-0163-45c4-8269-e6c1a1d70d7f@c65g2000hsa.googlegroups.com> A Python walks into a bar and orders a complex data structure. Bartender says, "One line or two?" From annathorns at googlemail.com Mon Sep 22 12:20:58 2008 From: annathorns at googlemail.com (annathorns at googlemail.com) Date: Mon, 22 Sep 2008 09:20:58 -0700 (PDT) Subject: Top Techniques of Money Making INTERNET CASH MAKING SOLUTIONS Message-ID: <287e6ec9-e165-4ea2-a3f7-136a178357b1@p10g2000prf.googlegroups.com> Ultimate Destination For All Online Job Seekers. Online cash online money without investments online paid surveys earn money online. Earn with FUN!!! For More Details Check the Links Below: http://www.tips2internetmarketing.blogspot.com/ http://www.80kpermonth.blogspot.com From martin at v.loewis.de Sun Sep 28 17:47:00 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 28 Sep 2008 23:47:00 +0200 Subject: Python 3.0 and repr In-Reply-To: References: Message-ID: <48dffb54$0$1082$9b622d9e@news.freenet.de> > What are others' opinions? Any insight to this design decision? The intention is that all printable characters in a string get displayed in repr. This was in particular requested by Japanese users (but also by other users of non-ASCII characters) which complained that repr() is fairly useless if your strings actually contains *no* ASCII characters (but all of them are printable). Notice that repr() of the string actually succeeds; try >>> x='\u5000' >>> z=repr(x) It is the printing of the repr that fails. > Maybe repr() should always display the ASCII representation with > escapes for all other characters You can use the ascii() builtin if you want that. > especially considering the "repr() should produce output suitable for > eval() when possible" rule. But that is preserved under the new behavior, also! Just try py> x='\u5000' py> eval(repr(x))==x True Regards, Martin P.S. How did you manage to get U+5000 into your data, on a system where the terminal encoding is cp437? Google translates it as "Rash"; the Unihan database also has "bewildered", "wildly". From castironpi at gmail.com Fri Sep 26 14:07:55 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 11:07:55 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: <3b70e025-3ebf-4b0c-88b1-962eb58129f9@26g2000hsk.googlegroups.com> On Sep 26, 11:48?am, "Tim Rowe" wrote: > 2008/9/26 Tino Wildenhain : > > >> The question I usually ask is "Does this language help me get the job > >> done?" Python often does. That's all that really matters, isn't it? > > > Well then it still depends on the perception of "job done". For example > > PHP programmers would bet their soul that their language of choice is > > exactly the right one to "get the job done." :-) > > You and me would indeed see a different picture on the level of doneness > > of such jobs ;-) > > Well, I did say "Often". Before now I've struggled for ages to write a > Python program to do a job, then when I've tried C# all the problems > have fallen away and the job was done in an hour or so. But other > times it has been the other way around; I've done stuff in Python that > I wouldn't know where to begin with in other languages. One of my > constant refrains is that *no* tool is ideal for *all* jobs! > > -- > Tim Rowe I thought procedural and imperative were the same. "Sorry, but you forgot to phrase your expression in the form of a command." I'll take 'modules' for $500, Alex. From aioe.org at technicalbloke.com Wed Sep 24 22:15:04 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 24 Sep 2008 22:15:04 -0400 Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: Duncan Booth wrote: > r0g wrote: > >> OK so maybe I'm being naive here but it looks to me like this new >> paradigm's big idea is to use a python + SQL type syntax to access data >> in random objects. Big whoop. It's not that difficult to write a >> generators that wraps XML files and databases is it? >> >> What am I missing here? > > Simple LINQ expressions like the one you gave map easily to Python list > comprehensions. What Microsoft have done though is provide a consistent > implementation which allows you to write complex SQL like expressions which > will work identically on databases or most other sequence types. Hmm, that's a nice idea in theory but I don't think it's the python killer Mr/Ms bearophile thinks it is. I can't think of any use cases where this would save me a great deal of time (certainly not enough to offset the relative slowness of working in C#) but supposing they do exist this stuff definitely belongs in a module. Seems to me C# is playing catchup in most ways and this nugget of 'innovation' is just the exception that proves the rule. Roger. From kar1107 at gmail.com Tue Sep 2 18:31:39 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 2 Sep 2008 15:31:39 -0700 (PDT) Subject: Storing Subprocess Results References: <1d080131-843c-4a5e-bd4c-8cfb077f472a@c65g2000hsa.googlegroups.com> Message-ID: <09d82341-3005-4be4-8567-e86faa7ee72a@a8g2000prf.googlegroups.com> On Sep 2, 7:16?am, topazcode wrote: > I am using the subprocess module to run some shell commands on a Linux > system: > > import subprocess > output = subprocess.call('''ssh server1 "uptime"''', shell=True) > > The above assigns the output variable with a return code, i.e. 0 in > this case. ?How can I actually capture the data returned from > subprocess.call, rather than just the return code? ?I'd like to have > the output variable contain the uptime string in this case. Probably commands module is a better choice for your problem: >>> import commands >>> commands.getoutput('fortune') "While money can't buy happiness, it certainly lets you choose your own \nform of misery." >>> Karthik ?Any help > is appreciated. ?Thanks. From circularfunc at gmail.com Mon Sep 22 21:13:30 2008 From: circularfunc at gmail.com (process) Date: Mon, 22 Sep 2008 18:13:30 -0700 (PDT) Subject: Why no tailcall-optimization? Message-ID: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Why doesn't Python optimize tailcalls? Are there plans for it? I know GvR dislikes some of the functional additions like reduce and Python is supposedly about "one preferrable way of doing things" but not being able to use recursion properly is just a big pain in the a**. From goldspin at gmail.com Thu Sep 11 13:30:57 2008 From: goldspin at gmail.com (Henry Chang) Date: Thu, 11 Sep 2008 10:30:57 -0700 Subject: How to Determine Name of the Day in the Week In-Reply-To: References: Message-ID: Awesome, that worked. Thanks so much! On Thu, Sep 11, 2008 at 10:16 AM, Fredrik Lundh wrote: > Henry Chang wrote: > > Instead of getting integers with weekday(), Monday == 0 ... Sunday == 6; >> is there a way to get the actual names, such as "Monday ... Sunday"? I >> would like to do this without creating a data mapping. :) >> > > if you have a datetime or date object, you can use strftime with the > appropriate formatting code. see the library reference for details. > > if you have the weekday number, you can use the calender module: > > >>> import calendar > >>> calendar.day_name[0] > 'Monday' > > (the latter also contains abbreviated day names, month names, and a bunch > of other potentially useful functions and mappings.) > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From istvan.albert at gmail.com Thu Sep 25 20:20:07 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 25 Sep 2008 17:20:07 -0700 (PDT) Subject: multiprocessing eats memory References: Message-ID: On Sep 25, 8:40?am, "Max Ivanov" wrote: > At any time in main process there are shouldn't be no more than two copies of data > (one original data and one result). >From the looks of it you are storing a lots of references to various copies of your data via the async set. From woodygar at sky.com Tue Sep 30 05:21:08 2008 From: woodygar at sky.com (garywood) Date: Tue, 30 Sep 2008 10:21:08 +0100 Subject: can someone explain why this happens- newbie question Message-ID: Hi can someone tell me why it prints the high score table multiple times? #high scores program scores =[] choice = None while choice != 0: print """high Score Table 0 - exit 1 - show Scores 2 - add a score 3 - delete a score 4 - sort scores """ choice = input("what would you like to do?") if choice == 0: print "goodbye" elif choice == 1: for score in scores: print scores elif choice == 2: score = input("add a score") scores.append(score) elif choice == 3: score = input("what score would you like to delete ?") if score in scores: scores.remove(score) else: print "that score is not listed" elif choice == 4: scores.sort() scores.reverse() print scores, "highest score first" -------------- next part -------------- An HTML attachment was scrubbed... URL: From tino at wildenhain.de Fri Sep 26 09:05:35 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 15:05:35 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> Message-ID: <48DCDE1F.6040709@wildenhain.de> Michael Mabin wrote: > cursor.execute(""" > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """ % ','.join([str(x) for x in [1,5,9]]) Nope. That would be dangerous! -> google for SQL injection Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 22:20:33 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 02:20:33 GMT Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <48d54863$0$4666$426a74cc@news.free.fr> Message-ID: <00e5a962$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 19:01:42 +0200, Bruno Desthuilliers wrote: > Once again, sorry > if me missing your correct answer drives you paranoid :-) What do you mean by that? How many other people have been talking about me? *wink* -- Steven From bignose+hates-spam at benfinney.id.au Fri Sep 26 22:28:40 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 12:28:40 +1000 Subject: getting global variables from dictionary References: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> Message-ID: <87iqsiuxt3.fsf@benfinney.id.au> icarus writes: > global_vars.py has the global variables > set_var.py changes one of the values on the global variables (don't > close it or terminate) > get_var.py retrieves the recently value changed (triggered right after > set_var.py above) > > Problem: get_var.py retrieves the old value, the built-in one but > not the recently changed value in set_var.py. That's because you're making a new instance each time; each instance carries its own state. For a collection of attributes that should share state, probably the simplest way is to use attributes of a module. > ----global_vars.py--- > #!/usr/bin/python > > class Variables : > def __init__(self) : > self.var_dict = {"username": "original username"} These aren't "global variables"; they still need to be imported, like anything else from a module. Better to name the module by intent; e.g. if these are configuration settings, a module name of 'config' might be better. Also, this module presumably isn't intended to be run as a program; don't put a shebang line (the '#!' line) on files that aren't run as programs. ===== config.py ===== # -*- coding: utf-8 -*- # Name of the front-end user username = "original username" # Amount of wortzle to deliver wortzle_amount = 170 ===== > ---set_var.py --- > #!/usr/bin/python > > import time > import global_vars > > global_vars.Variables().var_dict["username"] = "new username" > time.sleep(10) #give enough time to trigger get_var.py ===== set_config.py ===== # -*- coding: utf-8 -*- import config def set_user(): config.username = "new username" ===== > ---get_var.py --- > #!/usr/bin/python > import global_vars > print global_vars.Variables().var_dict.get("username") ===== get_config.py ===== # -*- coding: utf-8 -*- import config def get_user(): return config.username ===== The 'config' module, imported by both of the other modules, maintains state: >>> import config >>> print config.username original username >>> import set_config >>> set_config.set_user() >>> print config.username new username >>> import get_config >>> print get_config.get_user() new username -- \ ?You can't have everything; where would you put it?? ?Steven | `\ Wright | _o__) | Ben Finney From paul at hovnanian.com Mon Sep 22 00:38:13 2008 From: paul at hovnanian.com (Paul Hovnanian P.E.) Date: Sun, 21 Sep 2008 21:38:13 -0700 Subject: Milenko Kindl rtegdgd References: Message-ID: <48D72135.3291EBFB@hovnanian.com> yuma wrote: > > Milenko Kindl > Banja Luka > Banjaluka > Bihac Try facing Mecca while repeating that and your source will compile. -- Paul Hovnanian mailto:Paul at Hovnanian.com ------------------------------------------------------------------ Leap and the net will appear. From castironpi at gmail.com Fri Sep 5 14:43:35 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 5 Sep 2008 11:43:35 -0700 (PDT) Subject: xml + mmap cross References: <48BF8AC8.6030509@behnel.de> <48c0c001$0$9319$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4724c1fd-01e6-4711-95e5-292ca450e2d1@d77g2000hsb.googlegroups.com> On Sep 5, 12:13?am, Stefan Behnel wrote: > Hi, > > this discussion seems pretty much off-topic for a Python list. > > > > castironpi wrote: > > In an XML file, entries are stored in serial, sort of like this. > > > AAA BBB CCC DDD > > > Or more recognizably, > > > somethingsomething > > > Point is, to change something to something else, you > > have to recopy everything after that. > > > AAA BBB CCC DDD > > AAA BBBb CCC DDD > > > requires 7 writes, 'b CCC DDD', not 1. > > > I want to use a simple tree structure to store: > > > 0 A-> None, 1 > > 1 B-> None, 2 > > 2 C-> 3, None > > 3 D-> None, None > > > Each node maps to 'Next, Child', or more accurately, 'Next Sibling, > > First Child'. > > Do I understand you right: you want to access serialised XML data alex23 correctly pointed out last night that XML is always serialized. What I mean and possibly what you mean is, a serialized tree structure. > as a memory > mapped file and operate directly on the byte data? Yes. Byte data containing both strings, and the structure of the tree. > You would still have to > decode the complete byte sequence to parse it and build your index structure > in that case. No, it's saved in an index structure; it's already in one. To find a/ b/c, read a, read its children to b, read b, read its children to c, read c. > How do you plan to store the pointers to a node's next sibling/child? And how > do you keep them updated over insertions/deletions? You update them when you insert them. To add 'c' to a/b, allocate c, initialize c, read a, read its children to b, read b, read its children to the end, add c. When you delete c from a/b/c, however, any references to c that you have in any programs become invalid. Don't delete it if you have them. The bytes are marked in the file to be no longer in use, which marking takes up some of the space in the file. > That, plus the copy > overhead in a sequential file, will be very costly on each change. No. That's the point of a dynamic structure. are not stored in memory as 10 consecutive characters. The file is not strictly speaking XML. See below for what they're stored as. > > You get constant time updates to contents, and log-time searches. > > Every XML tree structure gives you log-time searches. But how do you achieve > constant time updates in a sequential file? You don't use a sequential file. > Stefan I stated earlier that each node would look roughly like: tag_offset, first_attr, text_offset, tail_offset, first_child, prev_sibling, next_sibling, parent Attributes would look like: key_offset, value_offset, prev_attr, next_attr, node All these fields are integers that contain an offset into the file. Simplified: 0 Reserved 1 A.Tag 7 (points to 7 below) 2 A.FirstChild 4 (etc.) 3 A.Contents 0 (None) 4 B.Tag 11 5 B.FirstChild 0 6 B.Contents 15 7 3abc 11 3def 15 5ghijk This translates to: ghijk But isn't stored that way. The records are all the same size. The 'Tag' field of a record that starts at offset J is at offset J. The 'FirstChild' field of a record that starts at offset K is at offset K+ 1. 'tag_offset', 'text_offset', 'key_offset', and 'value_offset' contain offsets of variable-length strings into the file ( 7, 11, 15 ). The rest contain offsets of further structures. There's extra space usage not only in the structure of the tree, but in the record-keeping of what bytes are available for use, and which are in use. You have to grow the file size yourself (like growing an array) when you need to; the file system won't for you in mmap. (This means the alloc-free module I'm looking at will need modifications.) I'll reemphasize the value of constant-time insertions to a file though. From ldo at geek-central.gen.new_zealand Wed Sep 24 06:27:12 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:27:12 +1200 Subject: Modifying the system menu References: Message-ID: In message , raj.indian.08 at gmail.com wrote: > For example say - I am creating multiple desktops for windows - > and I want to give every application the capability to be moved across > different desktops. But doesn't the desktop environment/window manager that provides the multiple desktops also provide the relevant entries in the system menu? From hniksic at xemacs.org Thu Sep 18 08:04:50 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 18 Sep 2008 14:04:50 +0200 Subject: how can I use a callable object as a method References: Message-ID: <87r67hoe1p.fsf@mulj.homelinux.net> Piotr Sobolewski writes: > However, the second version does not work. I think I understand > why. That's because "a" inside f1 is not a function (but an object). An object that defines __call__ is perfectly usable as a function. Your problem is that it doesn't know how to convert itself to a method, so that f1.a() knows how to pass f1 as another_self to add.__call__. To do that, add needs to be a bit smarter: >>> class add(object): ... def __call__(self, another_self): ... return another_self.version ... def __get__(self, obj, type=None): ... return lambda: self(obj) ... >>> class f(object): ... version = 17 ... a = add() ... >>> f1 = f() >>> f1.a() 17 If you can't modify add, you can probably use an adaptor that defines __get__ in a similar way. From fredrik at pythonware.com Thu Sep 11 14:31:44 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 20:31:44 +0200 Subject: shelve file name extention In-Reply-To: References: Message-ID: Monu wrote: > So Can't I choose which module to use. Is there any preferance on > which shelve chooses these modules? it uses the anydbm module to look for available DBM-style drivers, which looks for modules in the following order: dbhash, gdbm, dbm, dumbdbm. if you know which one you want, you can open the database file yourself, and pass it to the Shelf constructor: import shelve import somedbm db = shelve.Shelf(somedbm.open(file, flag)) From bignose+hates-spam at benfinney.id.au Thu Sep 4 09:10:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 Sep 2008 23:10:32 +1000 Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <00cfa3b9$0$20302$c3e8da3@news.astraweb.com> Message-ID: <87vdxcm4zb.fsf@benfinney.id.au> Steven D'Aprano writes: > On Tue, 02 Sep 2008 13:07:33 -0400, Joe Riopel wrote: > > > On Tue, Sep 2, 2008 at 12:55 PM, Steven D'Aprano > > wrote: > >> Is there a better way of doing this than the way I am going about it? > > > > Would the logging module help, and just print the output to the stdout > > (or a file) instead? > > Thank you to everyone who answered. > > As I feared, it seems that there's no really simple way of dealing with > arbitrary messages at arbitrary parts of my code. I would think the 'logging' module *is* the simple way to do this. At least, it's as simple as it could be without leading to massive re-visiting of the "arbitrary parts of one's code" when later desiring to change the way the messages are handled. -- \ ?We must become the change we want to see.? ?Mahatma Gandhi | `\ | _o__) | Ben Finney From castironpi at gmail.com Sun Sep 28 16:08:05 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 13:08:05 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: On Sep 28, 2:59?pm, sotirac wrote: > Wondering if there is a better way to generate string of numbers with > a length of 5 which also can have a 0 in the front of the number. > >
> ?random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> elements
> ?code = 'this is a string' + str(random_number[0]) +
> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> + str(random_number[4])
> 
'%05i'%random.randint(0,99999) From owenzhang.chicago at gmail.com Fri Sep 12 16:34:02 2008 From: owenzhang.chicago at gmail.com (Owen Zhang) Date: Fri, 12 Sep 2008 13:34:02 -0700 (PDT) Subject: lxml build error in sun Message-ID: I am trying to build lxml package in SunOS 5.10. I got the following errors. Does anybody know why? $ python setup.py build Building lxml version 2.1. NOTE: Trying to build without Cython, pre-generated 'src/lxml/ lxml.etree.c' needs to be available. Using build configuration of libxslt 1.1.7 Building against libxml2/libxslt in the following directory: /usr/lib running build running build_py running build_ext building 'lxml.etree' extension gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes - fPIC -I/opt/swt/install/libxml2-2.6.27/include/libxml2 -I/opt/swt/ install/Python-2.5/include/python2.5 -c src/lxml/lxml.etree.c -o build/ temp.solaris-2.10-sun4u-2.5/src/lxml/lxml.etree.o -w In file included from /usr/include/sys/wait.h:24, from /usr/include/stdlib.h:22, from /opt/swt/install/Python-2.5/include/python2.5/ Python.h:41, from src/lxml/lxml.etree.c:4: /usr/include/sys/siginfo.h:259: error: syntax error before "ctid_t" /usr/include/sys/siginfo.h:292: error: syntax error before '}' token /usr/include/sys/siginfo.h:294: error: syntax error before '}' token /usr/include/sys/siginfo.h:390: error: syntax error before "ctid_t" /usr/include/sys/siginfo.h:398: error: conflicting types for '__fault' /usr/include/sys/siginfo.h:267: error: previous declaration of '__fault' was here From deets at nospam.web.de Sat Sep 6 08:23:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Sep 2008 14:23:23 +0200 Subject: Cancel instance create In-Reply-To: References: <1220697080.48c25bf890ade@www.inbox.lv> Message-ID: <6ifb1rFq9nlnU1@mid.uni-berlin.de> Mohamed Yousef schrieb: > ?What about no Constructor , and a custom instancing function that can > return either None or the instance wanted That doesn't solve the underlying problem - the instance is created. Just because it wasn't *returned*, doesn't mean it isn't there. Diez From michel at nospam.please Mon Sep 15 15:31:54 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:31:54 +0200 Subject: environment variable issue In-Reply-To: References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <48ceb82a$0$2861$ba620e4c@news.skynet.be> Tim Chase a ?crit : > Your HOSTNAME variable hasn't been exported to subshells. You can check > this by looking at the output of > > bash$ export -p > > which will print all the variables that are exported. I suspect you'll > see $USER in the list, but not $HOSTNAME Actually HOSTNAME seems to be exported as well: $ export -p | grep HOSTNAME declare -x HOSTNAME="LinuxPC" I don't know what to think of this but it's the beginning of an explanation. Thanks, Michel -- Michel Leunen http://linux.leunen.com From linkmaster032000 at gmail.com Thu Sep 18 18:59:27 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Thu, 18 Sep 2008 15:59:27 -0700 (PDT) Subject: curses.setsyx()? Message-ID: I tried curses.setsyx(2,3) in my script and it doesn't move the curses cursor. Any alternatives/solutions? From usenet.tolomea at gmail.com Sun Sep 7 06:54:54 2008 From: usenet.tolomea at gmail.com (usenet.tolomea at gmail.com) Date: Sun, 7 Sep 2008 03:54:54 -0700 (PDT) Subject: tracking collection modification Message-ID: <42d9688f-1058-4ed7-8d9d-affd432fdb41@s1g2000pra.googlegroups.com> I'm working on a remote object system, something kinda like Pyro. For the purposes of caching I need to be able to tell if a given dict / list / set has been modified. Ideally what I'd like is for them to have a modification count variable that increments every time the particular collection is modified. Unfortunately I can't find anything like that and since this needs to work for the regular normal list / dict / set objects subclassing them to add the modification count isn't useful. I realize I could take a copy and then compare the copy to the original, but that's a fairly heavy handed approach and I was hoping for something light and fast. Does anyone have any suggestions on best to approach this? From dickinsm at gmail.com Thu Sep 25 06:05:13 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 25 Sep 2008 03:05:13 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> Message-ID: <98e4f068-5349-4b38-b15b-7e2436a0e4a7@f63g2000hsf.googlegroups.com> On Sep 25, 8:55?am, Tim Roberts wrote: > Marc 'BlackJack' Rintsch wrote: > >0.1 actually is > > >In [98]: '%.50f' % 0.1 > >Out[98]: '0.10000000000000000555111512312578270211815834045410' > >? > > Actually, it's not. ?Your C run-time library is generating random digits > after it runs out of useful information (which is the first 16 or 17 > digits). ?0.1 in an IEEE 784 double is this: > > ? ? ?0.100000000000000088817841970012523233890533447265625 I get (using Python 2.6): >>> n, d = 0.1.as_integer_ratio() >>> from decimal import Decimal, getcontext >>> getcontext().prec = 100 >>> Decimal(n)/Decimal(d) Decimal('0.1000000000000000055511151231257827021181583404541015625') which is a lot closer to Marc's answer. Looks like your float approximation to 0.1 is 6 ulps out. :-) Mark From sebastianthegreatful at gmail.com Thu Sep 18 03:58:33 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Thu, 18 Sep 2008 00:58:33 -0700 (PDT) Subject: ssl server References: <72ed03e9-e3cd-4feb-ac5c-41f9ee1f5458@y21g2000hsf.googlegroups.com> Message-ID: On Sep 18, 1:05?am, Michael Palmer wrote: > On Sep 17, 1:33 pm, Seb wrote: > > > > > I'm making a ssl server, but I'm not sure how I can verify the > > clients. What do I actually need to place in _verify to actually > > verify that the client cert is signed by me? > > > ?50 class SSLTCPServer(TCPServer): > > ?51 ? ? ? ? keyFile = "sslcert/server.key" > > ?52 ? ? ? ? certFile = "sslcert/server.crt" > > ?53 ? ? ? ? def __init__(self, server_address, RequestHandlerClass): > > ?54 ? ? ? ? ? ? ? ? ctx = SSL.Context(SSL.SSLv23_METHOD) > > ?55 ? ? ? ? ? ? ? ? ctx.use_privatekey_file(self.keyFile) > > ?56 ? ? ? ? ? ? ? ? ctx.use_certificate_file(self.certFile) > > ?57 ? ? ? ? ? ? ? ? ctx.set_verify(SSL.VERIFY_PEER | > > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > > self._verify) > > ?58 ? ? ? ? ? ? ? ? ctx.set_verify_depth(10) > > ?59 ? ? ? ? ? ? ? ? ctx.set_session_id('DFS') > > ?60 > > ?61 ? ? ? ? ? ? ? ? self.server_address = server_address > > ?62 ? ? ? ? ? ? ? ? self.RequestHandlerClass = RequestHandlerClass > > ?63 ? ? ? ? ? ? ? ? self.socket = socket.socket(self.address_family, > > self.socket_type) > > ?64 ? ? ? ? ? ? ? ? self.socket = SSL.Connection(ctx, self.socket) > > ?65 ? ? ? ? ? ? ? ? self.socket.bind(self.server_address) > > ?66 ? ? ? ? ? ? ? ? self.socket.listen(self.request_queue_size) > > ?67 > > ?68 ? ? ? ? def _verify(self, conn, cert, errno, depth, retcode): > > ?69 ? ? ? ? ? ? ? ? return not cert.has_expired() and > > cert.get_issuer().organizationName == 'DFS' > > If I were you, I would just just hide behind apache, nginx oder > another server that does ssl. just have that server proxy locally to > your python server over http, and firewall the python server port. Good idea, however atm this is a school project so thats not really an option right now. However I might take this a bit furtherer and use that solution. From tjreedy at udel.edu Mon Sep 22 13:55:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 13:55:50 -0400 Subject: Question about sorted in Python 3.0rc1 In-Reply-To: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: josh logan wrote: Here is a minimal example showing the problematic behavior. class Int(): def __init__(self, i): self.i = i def __cmp__(self, other): return cmp(self.i, other.i) Is = [Int(i) for i in range(8)] Is.sort() # throws TypeError: unorderable types Int() < Int() sorted(Is) # ditto, if above not present The 3.0b2 version of LibRef/ Built-in Types/ Comparisions says "Instances of a class cannot be ordered with respect to other instances of the same class, or other types of object, unless the class defines enough of the methods __cmp__(), __lt__(), __le__(), __gt__(), and __ge__() (in general, either __cmp__() or both __lt__() and __eq__() are sufficient, if you want the conventional meanings of the comparison operators). The notes for Mutable Sequence .sort() say nothing more. So the exception appears to be a bug, perhaps left over from when there was a plan (since aborted) to delete cmp and __cmp__. If the 3.0c1 version of the docs say the same, and no one says otherwise, I would file a report on the tracker at bugs.python.org, using the minimal example above. Terry Jan Reedy From tjreedy at udel.edu Mon Sep 29 00:08:21 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 00:08:21 -0400 Subject: What is not objects in Python? In-Reply-To: <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> Message-ID: George Sakkis wrote: > On Sep 28, 2:29 pm, process wrote: > >> I have heard some criticism about Python, that it is not fully object- >> oriented. > > That's not a bug, it's a feature ;-) > >> Why isn't len implemented as a str.len and list.len method instead of >> a len(list) function? > > As Terry Reedy wrote, partly history and partly practicality. There's > no philosophical reason why we write "len(x)" (generic builtin), > "x.append(1)" (method) or "del x[i]" (statement). The latter in > particular is IMHO a design wart; there's no reason for not writing it > as "x.delete(i)". As a general rule and matter of practice, methods that apply to all or most classes (or all number classes) have built-in functions that call the corresponding special method (or C-level slot). Methods that apply to one class (or just couple) are called as non-special methods. I am not sure why del is a statement rather than a function -- perhaps just because there is no return value (other than the default None). tjr From marco.bizzarri at gmail.com Sat Sep 6 02:02:28 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 6 Sep 2008 08:02:28 +0200 Subject: use str as variable name In-Reply-To: <48c1a184$0$17080$426a74cc@news.free.fr> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <48c1a184$0$17080$426a74cc@news.free.fr> Message-ID: <3f0d61c40809052302s407fede4od34eff1f2b513abf@mail.gmail.com> On Fri, Sep 5, 2008 at 9:16 PM, Bruno Desthuilliers wrote: > Marco Bizzarri a ?crit : >> >> Just a question: "generic functions" are not meant in the sense of >> "generic functions" of CLOS, am I right? > > Nope. Just "generic" in the sense that they accept any object implementing a > very minimal interface. > > If you want something like CLOS multimethods, you may be interested in > Philip Eby's ruledispatch. > Even though I loved them when I used at university, I'm not looking for them right now... but nice to know that they are available under python :-) -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From pavlovevidence at gmail.com Sat Sep 20 06:38:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 20 Sep 2008 03:38:39 -0700 (PDT) Subject: report a BUG of package setuptools-0.6c8. References: Message-ID: <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> On Sep 20, 1:11 am, Fredrik Lundh wrote: > ???? wrote: > > File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", > > line 98, in entries_finder > > log.warn("unrecognized .svn/entries format in %s", dirname) > > NameError: global name 'log' is not defined > > > global name 'log' is not defined to the line 98!!! > > please report bugs here: > > http://bugs.python.org/ Does bugs.python.org track bugs for setuptools? (Genuine question; the PEAK site doesn't list an obvious way to report bugs so I wonder if they're using bugs.python.org? Hope not....) If not, the OP should ask on the setuptools mailing list. Carl Banks From plexer at gmail.com Sun Sep 7 23:25:38 2008 From: plexer at gmail.com (James McGill) Date: Sun, 7 Sep 2008 20:25:38 -0700 (PDT) Subject: Subprocess freezes when piping from stdout. Message-ID: <62ab6734-a6ab-40c0-9131-a90684674ea6@a18g2000pra.googlegroups.com> Hi All, I'm using subprocess.Popen to run a C++ compiler and have set stdout = PIPE. The exact line of code that I am using is: process = Popen(command, stdout=PIPE) status = process.wait() This works fine until a large amount of data is written to stdout. When this occurs, my python program seems to freeze. It will no longer run or respond to Ctrl-C. I am assuming that it is stuck waiting for the process to end, but I'm not sure why this should take so long (I have left it running for hours and it never ended) At the moment the code is being executed on a Win32 environment. Is anyone aware of why this might be occurring, or of any ways around this? Does the PIPE implementation in Win32 have a maximum buffer size? Regards, James McGill From coolkid246 at googlemail.com Thu Sep 4 06:15:28 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:15:28 -0700 (PDT) Subject: kleinkredit ohne schufa in Cuxhaven kredite fuer selbststaendige privatkredite online kredit trotz guenstiger kredit kredit bonitaetspruefung privat kredit online kreditantrag + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + sofort kredit ohne schufa kredit schweiz in Hannover online kredit im kreditrechner in Rosenheim private kredite ohne schufa online kredit direkt in Wetzlar klein kredit ohne schufa kredit ohne schufa selbstaendige in Unna zinsen kredit kredit umschuldung in Altoetting billig kredit sofortkredite ohne schufa in Friedberg kredite ohne schufa in kredit mit in Sulzbach finanzierung ohne schufa kredit fuer arbeitslose in Ludwigsburg darlehen schufafrei www online kredit de in Demmin online kredite im kredit ohne schufaauskunft in Herzogtum postbank kredit online kreditangebot in Saarlouis - kredit billig online kredite fuer arbeitslose in Neuss - serioeser kredit ohne schufa kredit uni in Fulda - sofort kredit ohne schufa ratenkredite ohne schufa in Friedberg - kredit ohne schufa in sofortkredit ohne auskunft in Villingen-Schwenningen - guenstig kredit online kredite de in Wetzlar - online credit ohne kfz kredit in Mettmann - geld online kredite mit sofortzusage in Ostprignitz - kredit einkommen kredit ohne schufa ohne in Erding - credite ohne schufa online sofort kredit ohne in Hannover - guenstige kredite ohne schufa online kredit oesterreich in Oschersleben - kredit ohne schufa vergleich guenstig kredit in Worms - online kredit ohne konto kredit in Wunsiedel/Fichtelgeb. - online kredite guenstig kredit ohne auskunft in Haldensleben - kredit guenstig ohne schufa kredite ohne schufa mit in Belzig Message-ID: <9e678cd1-656e-4cd7-b695-38d7a85146a1@25g2000prz.googlegroups.com> kleinkredit ohne schufa in Cuxhaven kredite fuer selbststaendige privatkredite online kredit trotz guenstiger kredit kredit bonitaetspruefung privat kredit online kreditantrag + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + sofort kredit ohne schufa kredit schweiz in Hannover online kredit im kreditrechner in Rosenheim private kredite ohne schufa online kredit direkt in Wetzlar klein kredit ohne schufa kredit ohne schufa selbstaendige in Unna zinsen kredit kredit umschuldung in Altoetting billig kredit sofortkredite ohne schufa in Friedberg kredite ohne schufa in kredit mit in Sulzbach finanzierung ohne schufa kredit fuer arbeitslose in Ludwigsburg darlehen schufafrei www online kredit de in Demmin online kredite im kredit ohne schufaauskunft in Herzogtum postbank kredit online kreditangebot in Saarlouis - kredit billig online kredite fuer arbeitslose in Neuss - serioeser kredit ohne schufa kredit uni in Fulda - sofort kredit ohne schufa ratenkredite ohne schufa in Friedberg - kredit ohne schufa in sofortkredit ohne auskunft in Villingen- Schwenningen - guenstig kredit online kredite de in Wetzlar - online credit ohne kfz kredit in Mettmann - geld online kredite mit sofortzusage in Ostprignitz - kredit einkommen kredit ohne schufa ohne in Erding - credite ohne schufa online sofort kredit ohne in Hannover - guenstige kredite ohne schufa online kredit oesterreich in Oschersleben - kredit ohne schufa vergleich guenstig kredit in Worms - online kredit ohne konto kredit in Wunsiedel/Fichtelgeb. - online kredite guenstig kredit ohne auskunft in Haldensleben - kredit guenstig ohne schufa kredite ohne schufa mit in Belzig From uninverted at lavabit.com Mon Sep 29 17:25:09 2008 From: uninverted at lavabit.com (Nathan Seese) Date: Mon, 29 Sep 2008 23:25:09 +0200 (CEST) Subject: Converting a strng to an anonymous function Message-ID: I'm writing a program to sort files with arbitrary python code. The method I'm using for that is to pass sort an anonymous function taken from the arguments. I'm wondering how to change a raw string into an anonyous function. From afriere at yahoo.co.uk Wed Sep 24 21:40:12 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Wed, 24 Sep 2008 18:40:12 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 25, 3:16 am, Pete Forman wrote: > Asun Friere writes: > > > A canonical use of the conditional operator is in > > pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). > > That fails for n == 1. So what is best? > Sorry missing parantheses. I should test, even for fragments written out as part of a sentence. %-/ > for i in range(4): > print '%d thing' % i + ('s' if i != 1 else '') > That's the corrected version of what I meant, but actually I think your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding all variables for placeholders in the tuple, is better. It's certainly more readible. From george.sakkis at gmail.com Sun Sep 21 09:07:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sun, 21 Sep 2008 06:07:49 -0700 (PDT) Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> Message-ID: <974c3434-d409-484d-8bc4-7a3294132bd0@73g2000hsx.googlegroups.com> On Sep 21, 8:51?am, Alex wrote: > Hi all! > > I have a problem understanding the behaviour of this snippet: > > data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) > > for i in range(len(data_set)): > ? ? ds = data_set[:] > ? ? data = ds[i] > ? ? if i == 1: data['param'] = "y" > ? ? if i == 2: data['param'] = "x" > > print data_set > > This script print out: > ({'param': 'a'}, {'param': 'y'}, {'param': 'x'}) > > Why? I'm coping data_set in ds so why data_set is changed? Because you're doing a shallow copy: http://docs.python.org/lib/module-copy.html George From scottd at mcm.com Thu Sep 11 14:16:13 2008 From: scottd at mcm.com (Desmond Scott E) Date: Thu, 11 Sep 2008 14:16:13 -0400 Subject: wx Message-ID: I'm am a Python novice by chance not choice. (Although it appears to be a nice tool. Plus anything based on Monte Python can't be bad!) My Quest is to migrate a Python-based process from Windows2000/Python v2.4.2 (#67) to WindowsXP/Python v2.5.2 (r252:60911). I've searched the Python website and could find no reference to module wx. Is this an add-in module or perhaps it was replaced in v2.5.2??? References in the code are: wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT) self.Bind(wx.EVT_LIST_ITEM_ACTIVATED, self.OnItemActivated) self.SetColumnWidth(0, WX.LIST_AUTOSIZE)) idx = self.GetNextItem(idx, wx.LIST_NEXT_ALL, wx.LIST_STATE_DONTCARE) Any help would be greatly appreciated! I do have Shrubbery! Scott Scott E. Desmond Director & Manager Equity Systems Development IT Integration Lead Mellon Capital Management Corporation 500 Grant Street, Suite 4200 Pittsburgh, PA 15258 T 412.236.0405 | F 412.236.1703 scottd at mcm.com | www.mcm.com The information contained in this e-mail may be confidential and is intended solely for the use of the named addressee. Access, copying or re-use of the e-mail or any information contained therein by any other person is not authorized. If you are not the intended recipient please notify us immediately by returning the e-mail to the originator.(16b) Disclaimer Version MB.US.1 -------------- next part -------------- An HTML attachment was scrubbed... URL: From 4g4trz802 at sneakemail.com Tue Sep 9 15:08:23 2008 From: 4g4trz802 at sneakemail.com (Michael Hoffman) Date: Tue, 09 Sep 2008 12:08:23 -0700 Subject: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles References: Message-ID: Please accept my apologies if this message was posted several times. My newsreader claimed that a timeout error kept the message from being posted, but I think it got through. From rex.eastbourne at gmail.com Wed Sep 3 21:58:12 2008 From: rex.eastbourne at gmail.com (Rex) Date: Wed, 3 Sep 2008 18:58:12 -0700 (PDT) Subject: Submitting forms over HTTPS with mechanize Message-ID: Hello, I am working on an academic research project where I need to log in to a website (www.lexis.com) over HTTPS and execute a bunch of queries to gather a data set. I just discovered the mechanize module, which seems great because it's a high-level tool. However, I can't find any decent documentation for mechanize apart from the docstrings, which are pretty thin. So I just followed some other examples I found online, to produce the following: baseurl = 'http://www.lexis.com/' br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-Agent', 'Firefox')] br.open(baseurl) br.select_form(name="formauth") br["USER_ID"]="my_user_id" br["PASSWORD"]="my_password" result = br.submit() This code hangs at br.submit(), and I can't tell what I'm doing wrong. Typically I would inspect the HTTP data with an HTTP debugging proxy (Fiddler), but I guess since this is HTTPS I can't do that. Any glaring errors in my code? By the way, does anyone have suggestions for Python modules that I should use instead of mechanize (and that are sufficiently easy)? If mechanize fails, I might try modifying some similar Perl code a friend sent me that logs into lexis.com. Thanks so much, Rex From ptmcg at austin.rr.com Tue Sep 2 10:51:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 2 Sep 2008 07:51:53 -0700 (PDT) Subject: How can we get to the end of a quote inside a string References: Message-ID: <08eff844-12b4-4fda-aa8b-276bf83872ec@x41g2000hsb.googlegroups.com> On Aug 31, 9:29?am, rajmoha... at gmail.com wrote: > Hi all, > ? ? Suppose I have a string which contains quotes inside quotes - > single and double quotes interchangeably - > ?s = "a1' b1 " c1' d1 ' c2" b2 'a2" > ? ? ?I need to start at b1 and end at b2 - i.e. I have to parse the > single quote strings from inside s. > Pyparsing defines a helper method called nestedExpr - typically it is used to find nesting of ()'s, or []'s, etc., but I was interested to see if I could use nestedExpr to match nested ()'s, []'s, AND {}'s all in the same string (like we used to do in our algebra class to show nesting of higher levels than parens - something like "{[a + 3*(b-c)] + 7}" - that is, ()'s nest within []'s, and []'s nest within {}'s). This IS possible, but it uses some advanced pyparsing methods. I adapted this example to map to your case - this was much simpler, as ""s nest within ''s, and ''s nest within ""s. I still keep a stack of previous nesting, but I'm not sure this was absolutely necessary. Here is the working code with your example: from pyparsing import Forward, oneOf, NoMatch, Literal, CharsNotIn, nestedExpr # define special subclass of Forward, that saves previous contained # expressions in a stack class ForwardStack(Forward): def __init__(self): super(ForwardStack,self).__init__() self.exprStack = [] self << NoMatch() def __lshift__(self,expr): self.exprStack.append(self.expr) super(ForwardStack,self).__lshift__(expr) return self def pop(self): self.expr = self.exprStack.pop() # define the grammar opening = ForwardStack() closing = ForwardStack() opening << oneOf(["'", '"']) closing << NoMatch() matchedNesting = nestedExpr(opening, closing, CharsNotIn('\'"'), ignoreExpr=None) # define parse-time callbacks alternate = {'"':"'", "'":'"'} def pushAlternate(t): # closing expression should match the current opening quote char closing << Literal( t[0] ) # if we find the other opening quote char, it is the beginning of # a nested quote opening << Literal( alternate[ t[0] ] ) def popClosing(): closing.pop() opening.pop() # when these expressions match, the parse action will be called opening.setParseAction(pushAlternate) closing.setParseAction(popClosing) # parse the test string s = """ "a1' b1 " c1' d1 ' c2" b2 'a2" """ print matchedNesting.parseString(s)[0] Prints: ['a1', [' b1 ', [' c1', [' d1 '], ' c2'], ' b2 '], 'a2'] -- Paul From lists at cheimes.de Mon Sep 29 04:41:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 29 Sep 2008 10:41:10 +0200 Subject: Detecting dir (tree) changes fast? In-Reply-To: References: Message-ID: robert wrote: > I want to detect changes in a directory tree fast with minimum > overhead/load. In order to check the need for sync tasks at high frequency. > It must not be 100% reliable (its also forced time periodic), so kind of > hashing would be ok. > How? Almost every modern OS has some sort of support for IO notifications. For example pynotify on Linux, kqueue on BSD or ReadDirectoryChanges on Windows. You can also use polling and check the directories yourself every few seconds but that's expensive and doesn't scale. Christian From d3vvnull at gmail.com Fri Sep 26 10:38:49 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 09:38:49 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DCDE1F.6040709@wildenhain.de> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> Message-ID: <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> I laugh in the face of danger. Give me a use case for an exploit. On Fri, Sep 26, 2008 at 8:05 AM, Tino Wildenhain wrote: > Michael Mabin wrote: > >> cursor.execute(""" >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """ % ','.join([str(x) for x in [1,5,9]]) >> > > Nope. That would be dangerous! -> google for SQL injection > > Tino > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Fri Sep 5 10:06:00 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 16:06:00 +0200 Subject: Case-insensitive string compare? In-Reply-To: <1220618002.21923.12.camel@jcd-desktop> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> <1220618002.21923.12.camel@jcd-desktop> Message-ID: <200809051606.01358.maric@aristote.info> Le Friday 05 September 2008 14:33:22 J. Clifford Dyer, vous avez ?crit?: > On Thu, 2008-09-04 at 18:48 -0500, Robert Dailey wrote: > > Thanks everyone for your help. I'm not opposed to using [key.lower() > > for key in stage_map] at all, I was just curious to see if there were > > any cleaner alternatives. It looks like that is what I'll be using. > > I'm not familiar with how python works internally, but coming from C++ > > it seems like "remaking" the map would be slow. However, speed is not > > my main concern in my particular situation, I'm just curious to learn > > more about python. > > You should be opposed to that particular solution. ?You have just taken > a dictionary lookup (very fast) and turned it into a list traversal > (slow). ?Even if speed isn't your main concern, this is an unnecessary > de-optimization. ?You are deliberately slowing down your program to > avoid a slightly more verbose lookup later. ?Your data structure might > as well be a list of tuples to begin with, to avoid creating a new list. > You have effectively made your keys useless as keys. > > If your lookups need to be case insensitive, make the key lower case, > and store the cased version in the value, whether as a tuple or a dict > (depending on whether you want named access). > > d = { > ? ?'foo': {'key': 'Foo', 'value': 'val1'} > ? ?'spam': {'key': 'sPAm', 'value': 'val2'} > } > > search = 'FOO'.lower() > if search in d: > ? ? result = d[search] > ? ? key = result['key'] > ? ? value = result['value'] > > The only reason I wouldn't use this solution is if you expect to have > keys that will be identical when made lowercase, but if you're doing > case-insensitive lookup, you obviously don't expect this to be an issue. > The OP has already said the keys are case-sensitive, so this is not an option, the only way to do it fast is to index upon insertion all keys in another dict, so you get in final : d = { "kEy1" : 1, "Key1" : 2} indexes = { "key1" : ["kEy1", "Key1" ] } > Cheers, > Cliff > > > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From fuzzyman at gmail.com Tue Sep 9 18:59:35 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Tue, 9 Sep 2008 15:59:35 -0700 (PDT) Subject: Cancel instance create References: <1220697080.48c25bf890ade@www.inbox.lv> <6ifb1rFq9nlnU1@mid.uni-berlin.de> Message-ID: On Sep 6, 1:23?pm, "Diez B. Roggisch" wrote: > Mohamed Yousef schrieb: > > > ?What about no Constructor , and a custom instancing function that can > > return either None or the instance wanted > > That doesn't solve the underlying problem - the instance is created. > Just because it wasn't *returned*, doesn't mean it isn't there. > > Diez def __new__(cls, *args, **kwargs): if some_condition: return None return object.__new__(cls) Michael Foord -- http://www.ironpythoninaction.com/ From h.goebel at goebel-consult.de Fri Sep 19 04:36:37 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Fri, 19 Sep 2008 10:36:37 +0200 Subject: Python and Open Office In-Reply-To: References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <48d36496$0$6665$9b4e6d93@newsspool2.arcor-online.net> Terry Reedy schrieb: > Hartmut Goebel wrote: >> The API docs are a bit hidden on the webpage. Here is the link: >> > > I wrote my comment *after* looking at the above, which I found easily > enough. After 7 pages of (helpful) explanatory text, there follow 88 > pages with hundreds of entries like this: [...] Well, I wrote my comment *before* looking at the API docs. Your are absolutely right: It is not helpful. >> Additionally teh ODF sepcs may help: >> > > v1.0 is the adopted international (ISO/IEC) standard. Specs for ODF 1.0 are available the oasis-open.org, too. So if you want to keep close the the ISO standard you surely are better off using 1.0. Alternativly you may use the 1.1 docs and skim the appendix about changes. Regards H. Goebel From larry.bates at vitalEsafe.com Sun Sep 14 12:49:08 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Sun, 14 Sep 2008 11:49:08 -0500 Subject: Abstract class In-Reply-To: References: Message-ID: <0fbzk.34409$vX2.31456@bignews6.bellsouth.net> Mr.SpOOn wrote: > Hi, > I'm going to work on a project to represent some musical theory in > Python, in an object oriented way. > > I have to manage many elements of music such as notes, intervals, > scales, chords and so on. All these elements share properties and > behavior, so what I want to do is an abstract class "Note" and other > subclasses, for example "NaturalNote", "FlatNote", "SharpNote" etc. > > The idea is not original, I read it in some papers where they talk > about an implementation in smalltalk. > > I want to use Python (of course) and I'd like to know what is the > practice in such a case. I mean, in python there aren't abstract > classes, but I read about some way to emulate the same behavior. > > What do you suggest me? > > Thanks, > Carlo I think the issue is one of terminology not features. Note would be a base class and it can have attributes (properties) and behavior (methods). NaturalNote, FlatNote, SharpNote would inherit from Note. -Larry From bdesth.quelquechose at free.quelquepart.fr Mon Sep 22 15:43:57 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 21:43:57 +0200 Subject: A bit weird dictionary behavior In-Reply-To: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> Message-ID: <48d7f5b4$0$20534$426a74cc@news.free.fr> bearophileHUGS at lycos.com a ?crit : > Pekka Laukkanen: >> but it still doesn't feel exactly right. Would it be worth submitting a bug? > > It feels wrong because it is. In a tidier language (Pascal, Java, etc) > a boolean and an integer must be different types. Some would argue (and some did by the time Python grew a 'bool' type) that what is wrong is to have a bool type in a language that already have a wider definition of the truth value of an expression... (snip) From ireborin at delete.this.gmail.com Mon Sep 29 20:16:41 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 02:16:41 +0200 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: On Mon, 29 Sep 2008 16:08:28 -0700 (PDT), Mensanator wrote: >> 2. I've read the help on the next one but I just find it difficult >> understanding it. >> I have; >> a=2.000001 >> b=123456.789 >> c=1234.0001 >> Hello Mensanator, thank you for answering in such a short time. < snip > >If you actually meant 7, then use %0.6e: Sorry about that; I have the habit of counting the point as a decimal place too. > >>>> print '%0.6e' % 2.000001 >2.000001e+00 >>>> print '%0.6e' % 123456.789 >1.234568e+05 >>>> print '%0.6e' % 1234.0001 >1.234000e+03 > I understood the above from help, but it's not what's been bugging me. Mea culpa, I've defined the question in a confusing way, I see that now. What I've meant to ask was, when I have 3 numbers, how would you print them with the same format which would apply to them 3 numbers. for example, I have print a,b,c now if I print them with print '%12.3f' %a,b,c the format will apply only to a, and not to b and c. I could of course write print '%12.3f %12.3f ... 3 times but that is just unpractical. Is there a way to just do something like this (not normal syntax, just my wishful thinking): print 3*'%12.3f' %a,b,c (meaning - use this format for the next 3 real numbers that come along) -- Ivan From malaclypse2 at gmail.com Mon Sep 15 16:23:51 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 15 Sep 2008 16:23:51 -0400 Subject: append on lists In-Reply-To: References: Message-ID: <16651e80809151323j205cdd45u589881216ed185d0@mail.gmail.com> On Mon, Sep 15, 2008 at 4:24 PM, Armin wrote: > Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? Because the list a has been altered in place. -- Jerry From aonlazio at gmail.com Mon Sep 8 17:31:14 2008 From: aonlazio at gmail.com (AON LAZIO) Date: Mon, 8 Sep 2008 17:31:14 -0400 Subject: The difference between __XX__ and XX method Message-ID: Hi, Pythoners. I would like to know that in some class, it uses __XX__ but in some it uses only XX for example, class Test: def __som__(self): ... def som(self): ... What does "__XX__" make the method different from XX? Thanks in advance Aonlazio -------------- next part -------------- An HTML attachment was scrubbed... URL: From almar.klein at gmail.com Tue Sep 30 06:53:49 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 30 Sep 2008 12:53:49 +0200 Subject: Weirdness comparing strings In-Reply-To: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> References: <8f67b6f80809300345g1a36dde1o69c4b3f3f3a8a285@mail.gmail.com> Message-ID: Hi, Better post complete code. I don't see where self.note_name is defined, and what are these accidentals? you write: def has_the_same_name(self, note): return self == note but this does not implicitly convert self to a string. You'll have to do in explicitly: use "return str(self) == note" instead. Hope this helps, Almar 2008/9/30 Mr. SpOOn > Hi, > I have this piece of code: > > class Note(): > ... > ... > def has_the_same_name(self, note): > return self == note > > def __str__(self): > return self.note_name + accidentals[self.accidentals] > > __repr__ = __str__ > > if __name__ == '__main__': > n = Note('B') > n2 = Note('B') > print n > print n2 > print n.has_the_same_name(n2) > > I'd expect to get "True", because their string representation is > actually the same, instead the output is: > > B > B > False > > I think I'm missing something stupid. Where am I wrong? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dudeja.rajat at gmail.com Tue Sep 30 16:28:18 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 30 Sep 2008 21:28:18 +0100 Subject: Tkinter on WIndows XP opens a blank screen. How can I get rid of it? Message-ID: Hi, I m using Tkinter and Tix to create a GUI on Windows XP. So far I've created the GUI and it just works. But the problem is as soon as I double click on the script it besides opening the GUI also opens a shell ( a blank screen) with it. Pleas suggest how can I get rid of this blank screen. My program is staring as : myRoot = Tix.Tk() myRoot.title("Test Automation") < some stuff> < ...............> myRoot.mainloop() Thanks and regadrs, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sat Sep 20 12:32:43 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Sep 2008 16:32:43 GMT Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Alex Snast wrote: > Hello > > I'm new to python and i can't figure out how to write a reverse for > loop in python > > e.g. the python equivalent to the c++ loop > > for (i = 10; i >= 0; --i) > The exact equivalent would be: for i in range(10, -1, -1): print i except you virtually never want to do that in Python. Don't expect just to translate statement by statement from one language to another: normally in Python you will iterate directly over the sequence you want to process rather than trying to count loop indices with all the telegraph pole errors that result. The usual way to iterate over a sequence in reverse is: for x in reversed(seq): print x although if you know it is a list, string or other object that supports extended slicing you can also do: for x in seq[::-1]: print x this may be less clear than using 'reversed', but does allow you to specify an explicit start, stop and step if you want to do only part of the sequence. From uninverted at lavabit.com Mon Sep 29 18:35:00 2008 From: uninverted at lavabit.com (Nathan Seese) Date: Tue, 30 Sep 2008 00:35:00 +0200 (CEST) Subject: Converting a strng to an anonymous function References: Message-ID: > On Sep 29, 11:25 pm, Nathan Seese wrote: >> I'm writing a program to sort files with arbitrary python code. The >> method I'm using for that is to pass sort an anonymous function taken >> from the arguments. I'm wondering how to change a raw string into an >> anonyous function. > > Is this enough for you? > >>>> L = [1, -5, 7, -9] >>>> sorted(L, key=abs) > [1, -5, 7, -9] >>>> func = "abs" >>>> sorted(L, key=eval(func)) > [1, -5, 7, -9] >>>> func = "abs(x)" >>>> sorted(L, key=lambda x: eval(func)) > [1, -5, 7, -9] > > Bye, > bearophile Thanks, that works great! From m_palmer45 at yahoo.ca Tue Sep 23 08:37:52 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 23 Sep 2008 05:37:52 -0700 (PDT) Subject: gplt from scipy missing ? References: <67lhd4hq1gch3r18g919fjvmijen9saevv@4ax.com> Message-ID: <3d28cf9b-5463-4d35-8141-f02f3c0b3fab@y38g2000hsy.googlegroups.com> On Sep 23, 7:44 am, Ivan Reborin wrote: > On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" > > wrote: > > >I think scipy does not bundle plotting packages anymore - you may use > >whatever suits you, from other sources. > >Try matplotlib, see the wiki: > >http://wiki.python.org/moin/NumericAndScientific/Plotting > > Hello Gabriel, > thank you for answering. > > Unfortunatelly, I cannot change my plotting package, unless I indend > to change a lot of code that I'll be using in the future. I'm not a > programmer by trade, just a guy doing some calculations with already > written programms. > > Do you know, by any chance, where one could get gplt separately, or > for example, get older versions of scipy ? > I'm using python 5.2.2.. If I install scipy for python 2.3. for > example (let's assume that one still has gplt in it) will it work ? > > Best regards > Ivan Well, if you are using scipy, you must at least be doing some programming. Instead of using gplt, you could just write your data to a .csv file and feed that to gnuplot yourself. You can then use the full flexibility of gnuplot for formatting your output, without having to cross your fingers that the features you need will be covered by the gplt module. You also have your data in a readable format after calculation but before plotting - I find such intermediate data useful for debugging. From oliphant.travis at ieee.org Wed Sep 10 00:39:26 2008 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Tue, 09 Sep 2008 23:39:26 -0500 Subject: NumPy arrays that use memory allocated from other libraries or tools Message-ID: I wanted to point anybody interested to a blog post that describes a useful pattern for having a NumPy array that points to the memory created by a different memory manager than the standard one used by NumPy. The pattern shows how to create a NumPy array that points to previously allocated memory and then shows how to construct an object that allows the correct deallocator to be called when the NumPy array is freed. This may be useful if you are wrapping code that has it's own memory management scheme. Comments and feedback is welcome. The post is http://blog.enthought.com/?p=62 Best regards, -Travis Oliphant From michel at nospam.please Mon Sep 15 15:05:30 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:05:30 +0200 Subject: environment variable issue In-Reply-To: <6j7pbiF1snjoU1@mid.uni-berlin.de> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> <6j7pbiF1snjoU1@mid.uni-berlin.de> Message-ID: <48ceb1fa$0$2847$ba620e4c@news.skynet.be> Diez B. Roggisch a ?crit : > >>> sorted(os.environ.keys()) > ['HOME', 'JAVA_HOME', 'LANG', 'LANGUAGE', 'LOGNAME', 'MAIL', 'PATH', > 'PWD', 'PYTHONSTARTUP', 'SHELL', 'SHLVL', 'SSH_CLIENT', > 'SSH_CONNECTION', 'SSH_TTY', 'TERM', 'USER', '_'] > >>> > > No HOSTNAME ... Yes, no HOSTNAME. That's exactly the problem I have. Why is there no HOSTNAME? Thanks to Fredrik Lundh, I know why, now. Thanks, Michel -- Michel Leunen http://linux.leunen.com From bdesth.quelquechose at free.quelquepart.fr Mon Sep 1 14:27:29 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 20:27:29 +0200 Subject: enhancing/wrapping an existing instance of a duck In-Reply-To: References: Message-ID: <48bc5001$0$4934$426a74cc@news.free.fr> Neville Dempsey a ?crit : > Basically I have an existing (maybe a rather large and complicated > (existing) instance) that > I want to add new member to. I suppose you mean "attributes" ? > Cheers > N > > Hacks/attempts follow: > > from math import sqrt > > ############ try2 ############ > duck_obj = [ i*i for i in range(25) ] # OR a large sparse matrix > > # I "want" to an a useful property, eg length, and retain the ducks > existing properties. > # I COULD try... > setattr(duck_obj,"length",lambda: sqrt(sum(*duck_obj))) Won't work on a list. > print duck_obj.length() # returns 70 > duck_obj[0]=70+71 > print duck_obj.length() # returns 71 You obviously didn't try the above code. Traceback (most recent call last): File "", line 2, in AttributeError: 'list' object has no attribute 'length' Also and FWIW, in Python, the "sizeable" protocol is implemented using a __len__ method, that will get called by the generic len(sizeable) function. > ############ try2 ############ > # **BUT** I'd rather encapsulate a the original instance somehow. > > # I presume that I could define a class to do this somehow? > duck_obj = [ i*i for i in range(25) ] # OR a LargeSparseMatrix() > > dec = Vec(duck_obj) ??? > print dec.length() # returns 70 > duck_obj[0]=70+71 # original "large and complicated duck instance" > print dec.length() # returns 71 > > Any hints on how I need to define Vec so that any kind of duck_obj can > be decorated/wrapped/encapsulated. Depends on the type of duck_obj. In the above case, I'd inherit from list and override __len__ : >>> import math >>> class Vec(list): ... def __len__(self): ... return math.sqrt(sum(self)) ... >>> Vec(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> len(Vec(range(10))) 6 From digitig at gmail.com Wed Sep 24 10:51:30 2008 From: digitig at gmail.com (Tim Rowe) Date: Wed, 24 Sep 2008 15:51:30 +0100 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <48d9e932$0$6127$426a34cc@news.free.fr> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48d9e932$0$6127$426a34cc@news.free.fr> Message-ID: 2008/9/24 Bruno Desthuilliers : > Drake a ?crit : >> many of the library functions to raise IOError Exceptions. The >> question is: should the library function be able to just dump to >> sys.exit() with a message about the error (like "couldn't open this >> file"), > > Arrghll ! NO, DONT ! Can I put in a vote *for* the questioner's library dumping to sys.exit() on any abnormal condition? It would reduce employment competition for the rest of us. Why, yes, I am wearing my BOFH hat. How could you tell? -- Tim Rowe From brennan.ron at gmail.com Fri Sep 19 09:59:26 2008 From: brennan.ron at gmail.com (Ron Brennan) Date: Fri, 19 Sep 2008 09:59:26 -0400 Subject: Multimapping and string converting Message-ID: <26c69b160809190659i54dbfae1xd5794cd2ff433a1c@mail.gmail.com> Hello, I have a multimap dictionary with a 1 Key to N values. I want to convert the N values to a string to be used elsewhere in my program. So I have dict[(1,[1, 2 ,3 ,4])] which I have sorted When I do a print ''.join(str(dict.value())) I get [1, 2, 3, 4] as an output when I really want 1 2 3 4 Here is my code: dmapItems = dictionary.items() dmapItems.sort() for tcKey, tcValue in dmapItems: file.write('Key = %s\nValue = %s" % (tcKey, tcValue) stinger = ''.join(str(tcValue)) print stringer The Output = [145, 2345, 567, 898] I need it to be 145 2345 567 898 Can anyone see the errors of my ways? Thanks, Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Fri Sep 19 13:41:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Sep 2008 13:41:04 -0400 Subject: improving a huge double-for cycle In-Reply-To: References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> <48D33497.4010403@wildenhain.de> Message-ID: Gabriel Genellina wrote: > En Fri, 19 Sep 2008 02:11:51 -0300, Tino Wildenhain > escribi?: > >> Also I never saw a list where the threading often goes wrong like >> this here - is there any special setup or is it just peoples MUA >> which screws up? > > Perhaps it's due to the newsgroup/list duality... Actually, the situation is a c.l.p <==> python-list <==> gmane.c.p.general triality. From castironpi at gmail.com Mon Sep 22 18:46:20 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 15:46:20 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <00e816f4$0$20303$c3e8da3@news.astraweb.com> Message-ID: <6602abad-3c12-4c0c-b41d-95f79cebdc31@y21g2000hsf.googlegroups.com> On Sep 22, 5:32?pm, Steven D'Aprano wrote: > On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: > > On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano > >> But that's precisely what I want to avoid: I don't want the objects to > >> ?share *any* state, not even their class. I'm not trying for a Borg or > >> ?Singleton: the user can call the factory as many times as they want, > >> ?but the objects returned shouldn't share any state. I don't know if > >> ?what I want has a name. Judging from people's reactions, I'd say > >> ?probably not. > > > Snce when are "users" ever involved > > in programming problems or programming languages ? > > What an astounding question. > > Consider a class. There are the programmers who write the class, and > there are the programmers (possibly the same people, but not necessarily) > who use the class. The second set of people, the programmers who use the > class, are *users* of the class. What else would they be? > > -- > Steven Usegrammers? From tino at wildenhain.de Mon Sep 22 08:20:50 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Sep 2008 14:20:50 +0200 Subject: Encoding.ASCII.GetBytes similar for Python ? In-Reply-To: <463f31b8-ba48-4833-8d41-9aa5f1cae189@a70g2000hsh.googlegroups.com> References: <463f31b8-ba48-4833-8d41-9aa5f1cae189@a70g2000hsh.googlegroups.com> Message-ID: <48D78DA2.1090104@wildenhain.de> Hi, Rui wrote: > Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with > the strings. I am trying to query some dns server to check its What would it do? > response using udp sockets. Some of the source below: > > # encoding: utf8 > import socket > import sys > import struct > > IP_PORT = 53 > server_host = ('4.2.2.1', IP_PORT) > transaction_id = "Q1" > TIMEOUT = 5 > > type_string = > "\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000" > trailer_string = "\u0000\u0000\u0001\u0000\u0001" > > address = 'google.com' > url_name_start, domain_name = address.split(".") > > # Query format copied from the C# example. > #QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length > + URLNameStart + (char)DomainName.Length + DomainName+ TrailerString; > query = (transaction_id + type_string + str(len(url_name_start)) + > url_name_start + > str(len(domain_name)) + domain_name + trailer_string) > print query You should refrain from trying a 1:1 translation from one language to another. This makes funny things with natural languages as well as it is horribly with computer languages. You should really read on string formatting in python. Also, while indeed usefull to understand whats going on for production use this is not recommended anymore, since you would have to randomize ports for requests instead of using fixed 53UDP. I'd recommend having a look on python adns - http://code.google.com/p/adns-python/ > sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > sock.settimeout(TIMEOUT) > sock.connect(server_host) > > sock.send(query) > data = sock.recv(512) > > for data_item in data: > try: > print chr(data_item) this is never going to work since recv() returns a string buffer, not a list of integers. HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From zxo102 at gmail.com Mon Sep 29 07:21:25 2008 From: zxo102 at gmail.com (zxo102) Date: Mon, 29 Sep 2008 04:21:25 -0700 (PDT) Subject: how to make smtplib.SMTP('localhost') work on window xp References: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Message-ID: <3623504d-b8c2-40b5-9e68-eb8f9a5c0b14@r15g2000prh.googlegroups.com> On 9?29?, ??2?53?, Lawrence D'Oliveiro wrote: > In message > <56f2097a-5129-4d1a-be82-a73e2874b... at p31g2000prf.googlegroups.com>, zxo102 > wrote: > > > SMTPServerDisconnected: Connection unexpectedly closed > > Does the SMTP server on localhost mention anything about the connection > attempt in its log? > > If you telnet/netcat to port 25 on localhost, does anything interesting > happen? Thanks for your mentioning of the SMTP server on localhost. I did not install that. After I install a free smtp server downloaded from http://www.softstack.com/freesmtp.html, and run the following python script again, everything is fine now. import smtplib server = smtplib.SMTP('localhost') ... Thanks for your message. ouyang From blabla at dungeon.de Fri Sep 26 10:53:02 2008 From: blabla at dungeon.de (hofer) Date: Fri, 26 Sep 2008 07:53:02 -0700 (PDT) Subject: Understanding (and getting rid) of optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a Message-ID: <85ec721a-b5a2-4f22-9e37-bda4a0f9eb81@z72g2000hsb.googlegroups.com> Hi, I get following warning with a python script: optparse.py:668: FutureWarning: %u/%o/%x/%X of negative int will return a signed string in Python 2.4 and up my code: from optparse import OptionParser if __name__ == '__main__': parser = OptionParser() parser.add_option('-G','--green',action= 'store_const', const= '#00FF00' , dest='color', default='#808080', help='life is so green') parser.add_option('-R','--red',action= 'store_const', const = '#FF0000' , dest='color', help='I just see red') # add more elaborated command line parsing and help text here (options,argv) = parser.parse_args() print 'options',options I assume python wants to tell me that newer version will behave differently for numeric arguments What I wonder is: Why do I get the warning if my code doesn't try to parse any numbers? Is there any way to get rid of the warning without having to change the python version? (I noticed, the warning disappears if I remove the line printing options) thanks for any explanations. suggestions H From google at mrabarnett.plus.com Wed Sep 10 19:11:06 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 10 Sep 2008 16:11:06 -0700 (PDT) Subject: emulating read and readline methods References: <6iqts0F3v76U1@mid.uni-berlin.de> Message-ID: On Sep 10, 10:52?pm, "Diez B. Roggisch" wrote: > Sean Davis schrieb: > > > > > I have a large file that I would like to transform and then feed to a > > function (psycopg2 copy_from) that expects a file-like object (needs > > read and readline methods). > > > I have a class like so: > > > class GeneInfo(): > > ? ? def __init__(self): > > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > > gene_info.gz',"/tmp/gene_info.gz") > > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > > ? ? ? ? self.fh.readline() #deal with header line > > > ? ? def _read(self,n=1): > > ? ? ? ? for line in self.fh: > > ? ? ? ? ? ? if line=='': > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? line=line.strip() > > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > > ? ? ? ? ? ? rowvals = line.split("\t") > > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > > ? ? def readline(self,n=1): > > ? ? ? ? return self._read().next() > > > ? ? def read(self,n=1): > > ? ? ? ? return self._read().next() > > > ? ? def close(self): > > ? ? ? ? self.fh.close() > > > and I use it like so: > > > a=GeneInfo() > > cur.copy_from(a,"gene_info") > > a.close() > > > It works well except that the end of file is not caught by copy_from. > > I get errors like: > > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > > during .read() call > > CONTEXT: ?COPY gene_info, line 1000: "" > > > for a 1000 line test file. ?Any ideas what is going on? > > I'm a bit lost why the above actually works - as _read() appears to be > re-created instead of re-used for each invocation, and thus can't work IMHO. > Each generator that's created reads a single line from the file (self.fh), yields the result, and is then discarded; none of the individual generator read more than one line from the file. > Anyway, I think the real problem is that you don't follow the > readline-protocol. it returns "" if there is no more line to read, > instead you raise a StopIteration > > Diez From castironpi at gmail.com Tue Sep 9 20:28:34 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 9 Sep 2008 17:28:34 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> Message-ID: <29d81c5c-34d9-4d28-9c20-f4a15e86ca97@26g2000hsk.googlegroups.com> On Sep 9, 5:44?pm, Larry Bates wrote: > castironpi wrote: > > I will try my idea again. ?I want to talk to people about a module I > > want to write and I will take the time to explain it. ?I think it's a > > "cool idea" that a lot of people, forgiving the slang, could benefit > > from. ?What are its flaws? > > > A user has a file he is using either 1/ to persist binary data after > > the run of a single program (persistence) or 2/ share binary data > > between concurrently running programs (IPC / shared memory). ?The data > > are records of variable types and lengths that can change over time. > > He wants to change a record that's already present in the file. ?Here > > are two examples. > > > Use Case 1: Hierarchical ElementTree-style data > > > A user has an XML file like the one shown here. > > > > > ? > > ? ? Foo > > ? > > ? ... > > > He wants to change "Foo" to "Foobar". > > > > > ? > > ? ? Foobar > > ? > > ? ... > > > The change he wants to make is at the beginning of a 4GB file, and > > recopying the remainder is an unacceptable resource drain. > > > Use Case 2: Web session logger > > > A tutor application has written a plugin to a webbrowser that records > > the order of a user's mouse and keyboard activity during a browsing > > session, and makes them concurrently available to other applications > > in a suite, which are written in varying lanugages. ?The user takes > > some action, such as surfing to a site or clicking on a link. ?The > > browser plugin records that sequence into shared memory, where it is > > marked as acknowledged by the listener programs, and recycled back > > into an unused block. ?URLs, user inputs, and link text can be of any > > length, so truncating them to fit a fixed length is not an option. > > > Existing Solutions > > > - Shelve - A Python Standard Library shelf object can store a random > > access dictionary mapping strings to pickled objects. ?It does not > > provide for hierarchical data stores, and objects must be unpickled > > before they can be examined. > > - Relational Database - Separate tables of nodes, attributes, and > > text, and the relations between them are slow and unwieldy to > > reproduce the contents of a dynamic structure. ?The VARCHAR data type > > still carries a maximum size, no more flexible than fixed-length > > records. > > - POSH - Python Object Sharing - A module currently in its alpha stage > > promises to make it possible to store Python objects directly in > > shared memory. ?In its current form, its only entry point is 'fork' > > and does not offer persistence, only sharing. ?See: > > ? ?http://poshmodule.sourceforge.net/ > > > Dynamic Allocation > > > The traditional solution, dynamic memory allocation, is to maintain a > > metadata list of "free blocks" that are available to write to. ?See: > > ? ?http://en.wikipedia.org/wiki/Dynamic_memory_allocation > > ? ?http://en.wikipedia.org/wiki/Malloc > > ? ?http://en.wikipedia.org/wiki/Mmap > > ? ?http://en.wikipedia.org/wiki/Memory_leak > > The catch, and the crux of the proposal, is that the metadata must be > > stored in shared memory along with the data themselves. ?Assuming they > > are, a program can acquire the offset of an unused block of a > > sufficient size for its data, then write it to the file at that > > offset. ?The metadata can maintain the offset of one root member, to > > serve as a 'table of contents' or header for the remainder of the > > file. ?It can be grown and reassigned as needed. > > > An acquaintence writes: It could be quite useful for highly concurrent > > systems: the overhead involved with interprocess communication can be > > overwhelming, and something more flexible than normal object > > persistence to disk might be worth having. > > > Python Applicability > > > The usual problems with data persistence and sharing apply. ?The > > format of the external data is only established conventionally, and > > conversions between Python objects and raw memory bytes take the usual > > overhead. ?'struct.Struct', 'ctypes.Structure', and 'pickle.Pickler' > > currently offer this functionality, and the buffer offset obtained > > from 'alloc' can be used with all three. > > > Ex 1. > > ? ? s= struct.Struct( 'III' ) > > ? ? x= alloc( s.size ) > > ? ? s.pack_into( mem, x, 2, 4, 6 ) > > Struct in its current form does not permit random access into > > structure contents; a user must read or write the entire converted > > strucutre in order to update one field. ?Alternative: > > ? ? s= struct.Struct( 'I' ) > > ? ? x1, x2, x3= alloc( s.size ), alloc( s.size ), alloc( s.size ) > > ? ? s.pack_into( mem, x1, 2 ) > > ? ? s.pack_into( mem, x2, 4 ) > > ? ? s.pack_into( mem, x3, 6 ) > > > Ex 2. > > ? ? class Items( ctypes.Structure ): > > ? ? ? ? _fields_= [ > > ? ? ? ? ? ? ( 'x1', ctypes.c_float ), > > ? ? ? ? ? ? ( 'y1', ctypes.c_float ) ] > > ? ? x= alloc( ctypes.sizeof( Items ) ) > > ? ? c= ctypes.cast( mem+ x, ctypes.POINTER( Items ) ).contents > > ? ? c.x1, c.y1= 2, 4 > > The 'mem' variable is obtained from a call to PyObject_AsWriteBuffer. > > > Ex 3. > > ? ? s= pickle.dumps( ( 2, 4, 6 ) ) > > ? ? x= alloc( len( s ) ) > > ? ? mem[ x: x+ len( s ) ]= s > > 'dumps' is still slow and nor does permit random access into contents. > > > Use Cases Revisited > > > Use Case 1: Hierarchical ElementTree-style data > > Solution: Dynamically allocate the tree and its elements. > > > Node: tag: a > > Node: tag: b > > Node: tag: c > > Node: text: Foo > > > The user wants to change "Foo" to "Foobar". > > > Node: tag: a > > Node: tag: b > > Node: tag: c > > Node: text: Foobar > > > Deallocate 'Node: text: Foo', allocate 'Node: text: Foobar', and store > > the new offset into 'Node: tag: c'. ?Total writes 6 bytes 'foobar', a > > one-word offset, and approximatly 5- 10-word metadata update. > > > Use Case 2: Web session logger > > Dynamically allocate a linked list of data points. > > > Data: 'friendster.com' > > Data: 'My Account' > > > Allocate one block for each string, adding it to a linked list. ?As > > listeners acknowledge each data point, remove it from the linked > > list. ?Keep the head node in the 'root offset' metadata field. > > > Restrictions > > > It is not possible for persistent memory to refer to live memory. ?Any > > objects it refers to must also be located in file. ?Their mapped > > addresses must not be stored, only their offsets into it. ?However, > > live references to persistent memory are eminently possible. > > > Current Status > > > A pure Python alloc-free implementation based on the GNU PAVL tree > > library is on Google Code. ?It is only in proof-of-concept form and > > not commented, but does contain a first-pass test suite. ?See: > > ? ?http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk > > The ctypes solution for access is advised. > > You should review Zope's ZODB and/or memcached before putting in too much effort. > > -Larry Larry, I'd love to say they were exactly what I was looking for. They're not. I confess, I stopped reading ZODB when I got to the "uses pickles" part, and 'memcached' when I got to the awkward and unwieldy "SELECT FROM" part. I'm aware of both of those and my solution does something neither other does. From faltet at gmail.com Tue Sep 16 08:58:45 2008 From: faltet at gmail.com (Francesc) Date: Tue, 16 Sep 2008 05:58:45 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> <08a0805f-ad5e-4cf7-954f-ba3200f90d4c@59g2000hsb.googlegroups.com> <4f16a677-f4db-4819-9031-67521320ec67@a1g2000hsb.googlegroups.com> Message-ID: <016bb6a7-ad62-40cb-ace9-d2c171b8ccb5@w7g2000hsa.googlegroups.com> On 15 Set, 22:09, "Aaron \"Castironpi\" Brady" wrote: > On Sep 15, 4:34 am, Francesc wrote: > > > > > On 12 Set, 14:39, "Aaron \"Castironpi\" Brady" > > wrote: > > > > > A consideration of other storage formats such as HDF5 might > > > > be appropriate: > > > > >http://hdf.ncsa.uiuc.edu/HDF5/whatishdf5.html > > > > > There are, of course, HDF5 tools available for Python. > > > > PyTablescame up within the past few weeks on the list. > > > > "When the file is created, the metadata in the object tree is updated > > > in memory while the actual data is saved to disk. When you close the > > > file the object tree is no longer available. However, when you reopen > > > this file the object tree will be reconstructed in memory from the > > > metadata on disk...." > > > > This is different from what I had in mind, but the extremity depends > > > on how slow the 'reconstructed in memory' step is. (Fromhttp://www.pytables.org/docs/manual/ch01.html#id2506782). The > > > counterexample would be needing random access into multiple data > > > files, which don't all fit in memory at once, but the maturity of the > > > package might outweigh that. Reconstruction will form a bottleneck > > > anyway. > > > Hmm, this was a part of a documentation that needed to be updated. > > Now, the object tree is reconstructed in a lazy way (i.e. on-demand), > > in order to avoid the bottleneck that you mentioned. I have corrected > > the docs in: > > >http://www.pytables.org/trac/changeset/3714/trunk > > > Thanks for (indirectly ;-) bringing this to my attention, > > > Francesc > > Depending on how lazy the reconstruction is, would it be possible to > modify separate tables from separate processes concurrently? No, modification of different tables in the same file simultaneously is not supported yet. This is a limitation of the HDF5 library itself. The HDF Group said that they have plans to address this, but this is probably a long-term task. Francesc From sri_annauni at yahoo.co.in Fri Sep 5 01:44:04 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Fri, 5 Sep 2008 11:14:04 +0530 (IST) Subject: Creating directories Message-ID: <638982.16149.qm@web7902.mail.in.yahoo.com> Can someone tell me is there any module available to create directories?? I tried os, tempfile. I was facing some issues with os.mkdir(). The mode setting was not proper with this method. I created the directory 'stdin' with '0700' mode using os.mkdir() method. $> ls -alR stdin/ stdin/: total 12 drwx--S---?? 2 munisams munisams 4096 Sep? 3 02:00 . What is that 'S' in the group permission field?? Thanks, Srini Unlimited freedom, unlimited storage. Get it now, on http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/ From mccredie at gmail.com Mon Sep 29 13:17:59 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 29 Sep 2008 10:17:59 -0700 (PDT) Subject: One class per file? References: Message-ID: > The book "Code Complete" recommends that you put only one class in a > source file, which seems a bit extreme for me. It seems that many > classes are small, so that putting several of them in a file seems > reasonable. I noticed that the decimal.py module in the standard > library has several classes, all of which of course revolve around the > "decimal" topic. Perhaps a better rule of thumb is "one idea per > file." I checked the Python style guide and there seems to be no > mention of this topic. I know this is an elementary question, but what > is the Python way of doing this? I'm in a similar situation. I've been reading Robert C. Martins book "Agile Software Development" and he suggests something similar. I would highly recommend that book by the way. He also has a couple of chapters on packaging where he makes some very good points about the reasoning behind it. Basically that you want to organize your code in such a way that package dependencies move in the direction of increasing stability. In this case stability is a metric which is defined as how likely the code is going to change in the future as determined by how many packages depend on it as opposed to how many packages it depends on. He paints a couple of scenarios in which he groups packages together that _seem_ to be related, only to see that it results in all of his packages needing to be re-built every time a change is required. Obviously we don't have to re-build python code, but it is still useful to organize your code in such a way that you don't have to constantly re-visit collections of code. I have actually started using his suggestion and have been putting one class per file. When one class depends on another I include it with a "from x import X". This makes it very easy to determine the dependencies (well, the non-abstract dependencies anyway, interfaces are a different story*). Then I put all of my classes together in a package, and make the "public" classes visible on a package level by importing them into the package __init__ module. With that being said, If I made a class that was _only_ used by one other single class, and it was clear that it would never be made visible outside of that file, I would certainly put it in the same file as that class. Heck, you might even refactor your code and determine at that time that some piece of code is only used by one other piece. It is much easier to put code together after the fact than it is to separate it, especially later in the game. My advice: don't knock it until you try it. I think my code has improved quite a bit since taking this advice. It can be much more difficult to determine which classes to package together until much later in the development cycle. One thing that can help is to find an IDE that helps you to easily switch between files. I use WingIDE, but I have even used vim with a tags file and it wasn't terrible. I wouldn't call it a hard rule, but at the same time I wouldn't just ignore it. Give it a shot and adapt your development technique to see what works best for you. Example: [mypackage/__init__.py] __all__ = ["X"] from .x import X [end mypackage/__init__.py] [mypackage/x.py] from .y import Y __all__ = ["X"] class X(object): # code - using Y hopefully [end mypackage/x.py] [mypackage/y.py] __all__ = ["Y"] class Y(object): # code [end mypackage/y.py] Matt * Interfaces in python represent an implicit dependency. The Zen of Python states: "Explicit is better than implicit". I plan to experiment with the ABC module in python 2.6/3.0. I want to make my interfaces explicitly defined, but on the other hand I still want it to be easy for people who use my code to duck-type. This _seems_ to be possible since you can .register a class with an interface after it has been created, but I'm not sure that it is very pythonic to explicitly check for an interface every time it is used. It would seem silly however to import an interface into a file where it isn't explicitly used just to document the dependency. If anybody has pointers let me know. From dblubaugh at belcan.com Thu Sep 11 18:35:43 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Thu, 11 Sep 2008 18:35:43 -0400 Subject: Has any one worked with Rpyc Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F380500CFB0@AWMAIL04.belcan.com> To All, Has anyone out there worked much with Rpyc? Thanks, David This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From nagle at animats.com Tue Sep 2 12:57:05 2008 From: nagle at animats.com (John Nagle) Date: Tue, 02 Sep 2008 09:57:05 -0700 Subject: Changing the (codec) error handler for the stdout/stderr streams in Python 3.0 In-Reply-To: References: Message-ID: <48bd6b4e$0$17174$742ec2ed@news.sonic.net> Jukka Aho wrote: > Just a tip for those who are only just cutting their teeth on Python 3.0 > and might have encountered the same problem as I did: > > When a Python (3.x) program is run on a terminal that only supports a > legacy character encoding - such as Latin 1 or Codepage 437 - all > characters printed to stdout will be automatically converted from the > interpreter's internal Unicode representation to this legacy character set. Python 5 is even stricter. Only ASCII (chars 0..127) can be sent to standard output by default. John Nagle From mccredie at gmail.com Wed Sep 10 19:26:37 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 10 Sep 2008 16:26:37 -0700 (PDT) Subject: Persuading ConfigParser to give me the section elements in the same order as the file References: <4566f721-028d-4079-90d8-7818d69d18b3@34g2000hsh.googlegroups.com> Message-ID: On Sep 10, 1:52?pm, geoffbache wrote: > Hi all, > > I recently needed to parse a file that was perfect for ConfigParser > apart from one thing: the elements in the sections, although > definitions, could in some cases clash with each other and therefore > it was important to be able to retrieve them in the same order as they > appeared in the file. > > Unfortunately ConfigParser uses ordinary dictionaries for the section > elements and they are therefore returned in an arbitrary order. > > The only solution I found was to copy ConfigParser.py and replace all > the dictionaries with "sequential dictionaries" > which are exactly like dictionaries except that elements are returned > in the order they were inserted. (seehttp://home.arcor.de/wolfgang.grafen/Python/Modules/seqdict/Seqdict.html) > > I wonder if there was a better way? For example, is there any hook > that could modify what is created by the statement > > x = {} > > I tried setting > > __builtins__.dict = ndict.seqdict > > But that didn't seem to have any effect on the above statement. > > As a secondary question, I find sequential dictionaries to be an > essential part of programming in Python and I use them all the time. I > wondered a bit if there were any plans or proposals to include them as > part of the Python library? > > Regards, > Geoff Bache Have a look at this: http://www.python.org/dev/peps/pep-0372/ Looking at the config parser module, it looks like there are only a couple of places where {} is used. I would create a mixin class to replace the offending methods. That should work because it looks like you only have to replace "__init__" and "add_section". So... class OrderedConfigParserMixin: def __init__(self, defaults=None): self._sections = ndict.seqdict() self._defaults = ndict.seqdict() if defaults: for key, value in defaults.items(): self._defaults[self.optionxform(key)] = value def add_section(self, section): """Create a new section in the configuration. Raise DuplicateSectionError if a section by the specified name already exists. """ if section in self._sections: raise DuplicateSectionError(section) self._sections[section] = ndict.seqdict() # Then you can use this to create your own ordered config parsers. Note that # multiple inheritance in python uses a breadth first search. If you want # the methods on your mixin to get called instead of the methods on the # original class you must include the mixin first. from ConfigParser import RawConfigParser, ConfigParser, SafeConfigParser class OrderedRawConfigParser(OrderedConfigParserMixin, RawConfigParser): pass class OrderedConfigParser(OrderedConfigParserMixin, ConfigParser): pass class OrderedSafeConfigParser(OrderedConfigParserMixin, SafeConfigParser): pass I don't know if this is the _best_ approach, but it is certainly much preferred over monkey patching the built-ins module. Note that I haven't tested any of the above code. Matt From notvalid2 at sbcglobal.net Mon Sep 8 05:51:54 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 08 Sep 2008 02:51:54 -0700 Subject: Syntax Problem with strptime in Python 2.4 Message-ID: Apparently, use of strptime of datetime needs a workaround in Python 2.4 to work properly. The workaround is d = datetime.datetime(*(time.strptime(date_string, format)[0:5])). However, when I try to use it, or even use it the regular way, it fails with AttributeError: type object 'datetime.datetime' has no attribute 'datetime'. From the following code code segment: format = '%Y%m%d_%H%M%S' #d=datetime.strptime('20080321_113405', format)-- typical use print time.strptime('20080321_113405', format)[0:5] d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5]) Does anyone know how to make this work in 2.4? If not, is there a way to achieve the same result? -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From sturlamolden at yahoo.no Tue Sep 23 09:23:12 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 06:23:12 -0700 (PDT) Subject: Python is slow? Message-ID: I have recently been playing with a kd-tree for solving the "post office problem" in a 12-dimensional space. This is pure cpu bound number crunching, a task for which I suspected Python to be inefficient. My prototype in Python 2.5 using NumPy required 0.41 seconds to construct the tree from 50,000 samples. Unfortunately, searching it felt a bit slow, finding the 11 nearest-neighbours of 1,000 points took 29.6 seconds (and there were still 49,000 to go). Naturally, I blamed this on Python. It would be 100 times faster if I used C++, right? After having a working Python prototype, I resorted to rewrite the program in C++. The Python prototype took an hour to make, debug and verify. The same thing in C++ took me almost a day to complete, even with a working prototype as model. To my surprise, the resulting beast of C++ required 64.3 seconds to construct the same kd-tree. Searching the tree was not faster either, 1,000 points required 38.8 seconds. I wasted a day, only to find my Python prototype being the faster. We may conclude that I'm bad at programming C++, but I suspect that is not the case here. Albeit micro-benchmarks may indicate that Python is 100-200 times slower than C++, they may not be applicable to the real world. Python can be very efficient. And when combined with libraries like NumPy, beating it's performance with hand-crafted C++ is difficult. At least, my 10 years experience programming scientific software in various languages was not sufficient to beat my own Python prototype with C++. That is not to say I have never seen C++ run a lot faster than Python. But it tends to be very short pieces of CPU bound code, no more than a function or two. But as the problem grows in complexity, C++ accumulates too much of its own bloat. From mayariasxf at gmail.com Tue Sep 30 18:42:00 2008 From: mayariasxf at gmail.com (mayariasxf at gmail.com) Date: Tue, 30 Sep 2008 15:42:00 -0700 (PDT) Subject: Visit this sites please Message-ID: <64b49ebf-94df-42f1-8b5a-2edea29f2014@i76g2000hsf.googlegroups.com> http://forums.vogue.com.au/member.php?u=91686 tube8 http://forums.vogue.com.au/member.php?u=91688 redtube http://forums.vogue.com.au/member.php?u=91689 pornhub http://forums.vogue.com.au/member.php?u=91690 yobt http://www.dynamicdrive.com/forums/member.php?u=33924 tube8 http://www.dynamicdrive.com/forums/member.php?u=33925 redtube Visit this sites please From sturlamolden at yahoo.no Fri Sep 26 16:24:01 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 26 Sep 2008 13:24:01 -0700 (PDT) Subject: Quick sort implementation in python References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: On 26 Sep, 08:43, Terry Reedy wrote: > That depends on the data structure. ?Access to a singly-linked list is > by linear scanning from the front. Which is one reason why mergesort i preferred over quicksort for lists. Pythons built-in sort is a variant of mergesort and should be fast for linked lists and array lists alike. From i3dmaster at gmail.com Thu Sep 11 12:20:53 2008 From: i3dmaster at gmail.com (i3dmaster) Date: Thu, 11 Sep 2008 09:20:53 -0700 (PDT) Subject: conditional install/distribution Message-ID: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> Is there a feature in distutils or easy_install to specify what version of python that the target package can be installed? For example, if a package has a module that only needed if the python version < 2.6, is there a way to specifiy that in setup.py or easy_install cfg file so that when installing to python >= 2.6, this module wouldn't be installed?? Thanks, Jim From paulprobert at sbcglobal.net Tue Sep 30 21:21:33 2008 From: paulprobert at sbcglobal.net (Paul Probert) Date: Tue, 30 Sep 2008 20:21:33 -0500 Subject: Python arrays and sting formatting options In-Reply-To: References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: Grant Edwards wrote: > On 2008-09-30, Peter Pearson wrote: >> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: >>> 1. Multi dimensional arrays - how do you load them in python >>> For example, if I had: >>> ------- >>> 1 2 3 >>> 4 5 6 >>> 7 8 9 >>> >>> 10 11 12 >>> 13 14 15 >>> 16 17 18 >>> ------- >>> with "i" being the row number, "j" the column number, and "k" the .. >>> uhmm, well, the "group" number, how would you load this ? >>> >>> If fortran90 you would just do: >>> >>> do 10 k=1,2 >>> do 20 i=1,3 >>> >>> read(*,*)(a(i,j,k),j=1,3) >>> >>> 20 continue >>> 10 continue >>> >>> How would the python equivalent go ? > > You would drag yourself out of the 1960s, install numpy, and > then do something like this: > > a = read_array(open("filename.dat","r")) > >> Since you're coming from the FORTRAN world (thank you for that >> stroll down Memory Lane), you might be doing scientific >> computations, and so might be interested in the SciPy package >> (Google scipy), which gives you arrays and matrices. Don't >> expect to be able to use it without learning some Python, >> though. > > If not full-up scipy (which provides all sorts of scientific > and numerical-analysis stuff), then at least numpy (which > provides the basic array/matrix operations: > > http://numpy.scipy.org/ > > Though the software is free, the documentation isn't. You've > got to buy the book if you want something to read. IMO, it's > definitely worth it, and a good way to support the project even > if you don't really need something to keep your bookends apart. clip ... The book is free now, as of Aug 21, 08. http://www.tramy.us/guidetoscipy.html Paul Probert From showellshowell at gmail.com Mon Sep 15 10:06:19 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Mon, 15 Sep 2008 07:06:19 -0700 (PDT) Subject: Representation of python code ? References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> On Sep 15, 4:38?am, Maric Michaud wrote: > Le Sunday 14 September 2008 15:44:03 Barak, Ron, vous avez ?crit?: > > > Hi Guys, > > Is there a script/application, which gets as input python code, and > > produces a (graphic) representation of the inter-relationships between its > > classes/functions ? Bye, > If you can't find anything that's already packaged up and polished, one possibility is to use the parser and/or compiler.ast modules in Python to analyze your code, then produce something that graphviz can consume. Graphviz is something really nice to have in your bag of tricks, anyway. http://www.graphviz.org/ > None I know of. Not saying that it would be unfeasible, but it would be a hard > job, given the fact that most of relationships are purely dynamic. > > How such an application would find the relationship (composition) between A > and B without executing this code ? > I'm not sure this is the best counterexample. You can see statically that A potentially creates an instance of the B class. > class A : > ? ? def __init__(self) : > ? ? ? ? ?self._b = B() > > class B : pass > From sjmachin at lexicon.net Wed Sep 10 19:54:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 Sep 2008 16:54:35 -0700 (PDT) Subject: emulating read and readline methods References: Message-ID: On Sep 11, 8:01?am, MRAB wrote: > On Sep 10, 6:59?pm, Sean Davis wrote: > > > I have a large file that I would like to transform and then feed to a > > function (psycopg2 copy_from) that expects a file-like object (needs > > read and readline methods). > > > I have a class like so: > > > class GeneInfo(): > > ? ? def __init__(self): > > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > > gene_info.gz',"/tmp/gene_info.gz") > > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > > ? ? ? ? self.fh.readline() #deal with header line > > > ? ? def _read(self,n=1): > > ? ? ? ? for line in self.fh: > > ? ? ? ? ? ? if line=='': > > ? ? ? ? ? ? ? ? break > > ? ? ? ? ? ? line=line.strip() > > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > > ? ? ? ? ? ? rowvals = line.split("\t") > > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > > ? ? def readline(self,n=1): > > ? ? ? ? return self._read().next() > > > ? ? def read(self,n=1): > > ? ? ? ? return self._read().next() > > Each time readline() and read() call self._read() they are creating a > new generator. They then get one value from the newly-created > generator and then discard that generator. What you should do is > create the generator in __init__ and then use it in readline() and > read(). > > > > > ? ? def close(self): > > ? ? ? ? self.fh.close() > > > and I use it like so: > > > a=GeneInfo() > > cur.copy_from(a,"gene_info") > > a.close() > > > It works well except that the end of file is not caught by copy_from. > > I get errors like: > > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > > during .read() call > > CONTEXT: ?COPY gene_info, line 1000: "" > > > for a 1000 line test file. ?Any ideas what is going on? > > I wonder whether it's expecting readline() and read() to return an > empty string at the end of the file instead of raising StopIteration. Don't wonder; ReadTheFantasticManual: read( [size]) ... An empty string is returned when EOF is encountered immediately. ... readline( [size]) ... An empty string is returned only when EOF is encountered immediately. From george.sakkis at gmail.com Tue Sep 9 11:24:39 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Sep 2008 08:24:39 -0700 (PDT) Subject: creating an (inefficent) alternating regular expression from a list of options References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: <07c8886d-a0b5-4103-adcf-c6c2b89ce531@z72g2000hsb.googlegroups.com> On Sep 9, 9:12 am, "metaperl.com" wrote: > Pyparsing has a really nice feature that I want in PLY. I want to > specify a list of strings and have them converted to a regular > expression. > > A Perl module which does an aggressively optimizing job of this is > Regexp::List -http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/Lis... > > I really dont care if the expression is optimal. So the goal is > something like: > > vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| > u|ii|i)' > > Is there a public module available for this purpose? I was about to start a thread about a very similar problem; hope I'm not hijacking this thread. However I am interested in a solution that (1) scales to a potentially large number of alternate strings (hundreds or thousands), which will hit, sooner or later, some max limit in the builtin regexps and (2) is not limited to strings but can be used for arbitrary objects. Therefore I am looking for a different approach, perhaps a specialization of the general regexp search algorithm. More formally, given (a) an input sequence I and (b) a set of 'censored' sequences S, find and remove all the sequences in S that appear in I. For instance, if S = set([(a,), (a,b), (a,c), (c,), (d,a)]) and I = (x, a, b, c, y, d, a, b), the filtered sequence would be: O = (x, y, b) i.e. the censored subsequences are (a,b), (c,), and (d,a). As with regexps, if sequence `x` is a prefix of `y`, the longer sequence `y` wins when both match (e.g. if (a,b) matches, it supersedes (a,)). For extra bonus, the algorithm should remove overlapping subsequences too, i.e. for the input I above, the output would be (x, y) since both (d,a) and (a,b) would match for (d,a,b). With respect to complexity, I am mainly interested in len(S); len(I) is small for my application, typically no more than 10. Of course, an algorithm that scales decently in both len(S) and len(I) would be even better. Any ideas or relevant links ? George PS: This is not a homework ;) From code at pizzashack.org Wed Sep 3 03:09:18 2008 From: code at pizzashack.org (Derek Martin) Date: Wed, 3 Sep 2008 03:09:18 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i6pq9Fmcad7U2@mid.uni-berlin.de> References: <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <6i6pq9Fmcad7U2@mid.uni-berlin.de> Message-ID: <20080903070918.GW29228@dragontoe.org> On Wed, Sep 03, 2008 at 06:40:10AM +0000, Marc 'BlackJack' Rintsch wrote: > On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote: > > >> And if they model an action there must be some way to activate the > >> action > > > > That's a reasonable assumption, but as I also said, the object might > > just describe the action -- essentially the equivalent of a struct in C. > > ``struct``\s in C describe *actions*!? Functions do this. struct run { int speed; direction_type direction; }; Not a function. Describes an action. Sure, you'll probably never see this example in a real program. But that doesn't mean you can't do it, and it doesn't make it inherently wrong. Someone somewhere might very well find a legitimate use case. Besides which, I was not talking about programmatic actions; I was talking about verbs -- actions that people do. You are putting narrow-minded constraints on your ideas about how to program. Sometimes thinking outside the box is useful... > >> but the instances of `Popen` are no actions. There's no way to > >> "execute" a `Popen` instance. > > > > Yes there is... you execute it when you instantiate the object. > > But then the instance itself isn't an action but the result of one. So? A class doesn't represent an action, remember? It represents a thing. Isn't that what you said? > > At the time of instantiation, you "open" the "P" (pipes). For an > > object which describes an action, I think it's perfectly sensible that > > instantiation is when the action occurs, [?] > > Here I disagree again. Because the type/class name of an instance should > be a name of the "thing"/concept of the instance, not the action used to > create it. You're making an assertion based on your personal opinion. That's a fine guideline, but there's no requirement to do so. I can name my classes anything I want. There's no reason I can't write: Class Think: def __init__: self.thoughts = happy print "Thinking %s thoughts!" %s self.thoughts This is a silly example that does nothing useful, but that doesn't exclude the possibility that someone might conceive of a similar example that is actually useful. Maybe you're just not creative enough, and I'm too lazy. > >> Maybe from your POV. Facts: It doesn't use the `popen()` function > > > > So? Neither does the C version of popen(), but that function is still > > called popen()! > > Now you lost me. The C version of `popen()` isn't recursive, why on > earth should it be, so what's that statement supposed to mean!? Sorry, did I go too fast for you? Your "facts" seem to be suggesting that for Python's Popen class to be named Popen, it should use the C popen() function. I can't imagine any other reason why you mentioned it doesn't... It need not use popen() to do what popen() does... In fact, it need not do what popen() does to be called Popen! It's just a name... the author can call it whatever he wants. As it happens, it was called Popen because it does essentially what popen() does. The fact that it doesn't USE popen() to do it is... not interesting? > >> to three file objects, more attributes and methods), the function used > >> on Windows under the hood is called `CreateProcess()` not > >> `CreatePipe()`. > > > > How does Windows implement popen()? [I think they call it _popen() > > though...] > > Doesn't matter because the `Popen()` implementation doesn't use `popen()`. No, that's exactly why it *does* matter. Because neither is popen() implemented using popen()! See! There you go again! Does it matter, or doesn't it?!? What are you trying to say?!? Sorry, but you are contradicting yourself (repeatedly), and your arguments don't make any sense. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From upton at virginia.edu Mon Sep 8 12:23:02 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 8 Sep 2008 12:23:02 -0400 Subject: lacking follow-through In-Reply-To: <99113520-2fa2-46ac-9894-ea78372ff610@c58g2000hsc.googlegroups.com> References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <086a0906-c6f1-489c-91ab-f6a4f9e1ae3f@59g2000hsb.googlegroups.com> <99113520-2fa2-46ac-9894-ea78372ff610@c58g2000hsc.googlegroups.com> Message-ID: <5504f9ac0809080923v70fe58ccn2e4aaf3d5102d725@mail.gmail.com> On Sun, Sep 7, 2008 at 10:59 PM, castironpi wrote: > On Sep 7, 7:34 pm, MRAB wrote: >> On Sep 7, 11:28 pm, "Eric Wertman" wrote: >> >> > +1 Bot >> >> I think it's like duck typing: it doesn't matter whether he's actually >> a bot, only whether he behaves like one. > > Do you support the bot interface and methods? > -- And this is an example of why you get +1 bot. From bellman at lysator.liu.se Mon Sep 15 10:28:34 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Mon, 15 Sep 2008 14:28:34 +0000 (UTC) Subject: Unable to see os.environ['COLUMNS'] References: <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> Message-ID: Tim Chase writes: >> $ export COLUMNS >> >> $ python -c "import os; print os.environ['COLUMNS']" >> 80 > This works well, and also manages to keep up to date across runs > as window-size changes. Now try this: $ export COLUMNS $ python -c "import time, os; time.sleep(60); print os.environ['COLUMNS']" and change the window width during that sleep. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "Don't tell me I'm burning the candle at both ! bellman @ lysator.liu.se ends -- tell me where to get more wax!!" ! Make Love -- Nicht Wahr! From bborcic at gmail.com Fri Sep 19 06:15:58 2008 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 19 Sep 2008 12:15:58 +0200 Subject: dict generator question In-Reply-To: References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: Gerard flanagan wrote: > George Sakkis wrote: .. >> >> Note that this works correctly only if the versions are already sorted >> by major version. >> > > Yes, I should have mentioned it. Here's a fuller example below. There's > maybe better ways of sorting version numbers, but this is what I do. Indeed, your sort takes George's objection too litterally, what's needed for a correct endresult is only that major versions be grouped together, and this is most simply obtained by sorting the input data in (default) string order, is it not ? > > > data = [ "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.1.1.1", "1.3.14.5", > "1.3.21.6" ] > > from itertools import groupby > import re > > RXBUILDSORT = re.compile(r'\d+|[a-zA-Z]') > > def versionsort(s): > key = [] > for part in RXBUILDSORT.findall(s.lower()): > try: > key.append(int(part)) > except ValueError: > key.append(ord(part)) > return tuple(key) > > data.sort(key=versionsort) > print data > > datadict = \ > dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) > print datadict > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Fri Sep 19 00:46:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 19 Sep 2008 00:46:02 -0400 Subject: improving a huge double-for cycle In-Reply-To: <00e2e17d$0$20331$c3e8da3@news.astraweb.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote: > >> Now the obvious winner is pruebono - even unoptimized, using sets seems >> to be *way* faster than even the most optimized corrected version of >> your algorithm. > > I'm not being snarky about losing priority here, but I submitted > essentially the same solution two hours earlier than pruebono. > > Are people not seeing my posts? Have I been kill-filed by everyone except > Mensator? I also asked a question about HTTPError and I haven't seen any > responses at all. Yes, after figuring out what to do from the original post, I saw yours and then Pruebono's and decided that since two people had submitted the jackpot algorithm, I need not say more. I will say this: this solution amounts to finding equivalence classes (the sets of items with a given 'key') and then finding the classes (sets) with more than one member. Defaultdict is great for this. tjr From mensanator at aol.com Thu Sep 18 13:29:44 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 18 Sep 2008 10:29:44 -0700 (PDT) Subject: How to Determine Name of the Day in the Week References: <0928a498-1cc0-48c7-985e-4faf019d8a70@m3g2000hsc.googlegroups.com> Message-ID: <3205ea81-4a3e-4c92-a9d8-53bb4ee2f7b6@j22g2000hsf.googlegroups.com> On Sep 18, 12:01?am, Steven D'Aprano wrote: > On Wed, 17 Sep 2008 20:34:02 -0700, Mensanator wrote: > > And technically, weeks begin on Sunday, not Monday, but business likes > > to think of Monday as day 0 of the week and it doesn't conflict with any > > prior date format. > > There's no "technically" about it. Sure there is, within the tradition I was refering to. Within that tradition, the start of the week isn't arbitray. Besides, the documentation specifically says it's using the European system By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention). Use setfirstweekday() to set the first day of the week to Sunday (6) or to any other weekday. So, by default, Python doesn't use the American convention of weeks starting on Sunday (an American technicality). This does not contradict what I said. > It's an arbitrary starting point, Amongst different systems, it's never arbitrary within a system. > and > consequently there are different traditions to it, even in English. I know, that's why I added the caveat. > > Besides, I don't think many businesses think of "day 0" at all. Most > people outside of IT start counting from 1, not 0. The accounting software I use to fill out my timesheet electronically was obviously created by IT people and the week begins on Monday. Their will is, of course, forced on all employees whether they are IT or not. > > In British Commonwealth countries, Sunday is the last day of the week, > not the first, although under American influence that's changing in > Australia at least. > > In Poland, the week begins with Monday ("poniedzia?ek"). Tuesday, > "wtorek", means "second day". Other Slavic countries also start with > Monday. > > Similarly, the Lithuanian calendar simple enumerates the days of the > week, starting with Monday, "pirmadienis" ("first day"). > > In China, there are at least three different systems of naming the week > days. In two of them, the week starts with Sunday, but in the third > system, Sunday is "zhoumo" ("cycle's end") and Monday is zhouyi ("first > of cycle"). Last time I was in Borders, I don't recall seeing any Polish, Lithuanian or Chinese calendars for sale. > > -- > Steven From python.list at tim.thechases.com Wed Sep 17 06:52:07 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 17 Sep 2008 05:52:07 -0500 Subject: File Reading related query In-Reply-To: References: Message-ID: <48D0E157.6010307@tim.thechases.com> > I am talking about text file which contain multiple lines e.g following > three lines are there in my textfile.txt > > this is python list > where we get support > from geeks > > I want > > sentence = this is python list where we get support from geeks > > whereas when i use simple read() i get something like this > > sentence = this is python list\nwhere we get support\nfrom geeks You mean sentence = myfile.read().replace('\n', ' ') ? If you want to compact multiple spaces, such as this is the python__ list where__ __we get support (where "_" represents a space) and you want that to become this is the python list where we get support you'd have to use slightly more intelligent processing, and explain the behavior you'd want if more than one blank line was encountered. But for a first pass: import re r = re.compile(r"\s*\n") sentence = r.sub(" ", myfile.read()) -tkc From kushaldas at gmail.com Fri Sep 5 05:34:00 2008 From: kushaldas at gmail.com (Kushal Das) Date: Fri, 5 Sep 2008 15:04:00 +0530 Subject: configure kdevelop for python In-Reply-To: <2f21628f-80dd-4710-b0be-2b1c772e5698@l33g2000pri.googlegroups.com> References: <2f21628f-80dd-4710-b0be-2b1c772e5698@l33g2000pri.googlegroups.com> Message-ID: <200809051504.00439.kushaldas@gmail.com> On Sunday 31 August 2008 01:59:11 pm Sindhu wrote: > am a newbie to python language and kdevelop, so i would like to know > how to configure kdevelop for python programming? complete with a > debugger? Read here http://www.kde.in/index.php/Getting_started_with_KDevelop Kushal -- Fedora Ambassador, India http://kushaldas.in http://dgplug.org (Linux User Group of Durgapur) From pavlovevidence at gmail.com Sat Sep 13 03:43:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 13 Sep 2008 00:43:46 -0700 (PDT) Subject: question about python References: Message-ID: On Sep 13, 12:15 am, fishfin wrote: > I was working through a tutorial about how to write a server using > python (the url is bellow). I am sure that the server is working to > some degree because when the server is running localhost:8080 just > keeps trying to load until it times out. I would like to know how to > send information through the server to my browser? > > I was working through this tutorial:http://python.about.com/od/networkingwithpython/ss/PythonWebServer.htm > > and my final code is like this: > > import socket > > host = '' > port = 8080 > > c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > > c.bind((host, port)) > > c.listen(1) > > while 1: > csock, caddr = c.accept() > cfile = csock.makefile('rw', 0) It looks like everything after this line needs to be indented. Besides that, nothing jumps out at me, though I don't do direct socket programming a lot. > line = cfile.readline().strip() > > cfile.write('HTTP/1.0 200 OK\n\n') > cfile.write('Welcome %s!' % > (str(caddr))) > cfile.write('

Follow the link...

') > cfile.write('All the server needs to do is ') > cfile.write('to deliver the text to the socket. ') > cfile.write('It delivers the HTML code for a link, ') > cfile.write('and the web browser converts it.



') > cfile.write('
Click me!
') > cfile.write('

The wording of your request was: "%s"' %(line)) > cfile.write('') > > cfile.close() > csock.close() Carl Banks From stefan_ml at behnel.de Mon Sep 15 14:15:39 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 15 Sep 2008 20:15:39 +0200 Subject: Zsi interoperability In-Reply-To: References: Message-ID: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Mailing List SVR wrote: > I have to implement a soap web services from wsdl, the server is > developed using oracle, is zsi or some other python library for soap > interoperable with oracle soa? No idea, but I'd definitely try soaplib before ZSI. Stefan From roy at panix.com Wed Sep 3 16:54:12 2008 From: roy at panix.com (Roy Smith) Date: Wed, 03 Sep 2008 16:54:12 -0400 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: In article , Peter Otten <__peter__ at web.de> wrote: > Roy Smith wrote: > > > In article , > > Peter Otten <__peter__ at web.de> wrote: > > > >> > I might take it one step further, however, and do: > >> > > >> >> fields = line.split()[:2] > >> >> a, b = map(int, fields) > >> > > >> > in fact, I might even get rid of the very generic, but conceptually > >> > overkill, use of map() and just write: > >> > > >> >> a, b = line.split()[:2] > >> >> a = int(a) > >> >> b = int(b) > >> > >> If you go that route your next step is to introduce another try...except, > >> one for the unpacking and another for the integer conversion... > > > > Why another try/except? The potential unpack and conversion errors exist > > in both versions, and the existing try block catches them all. Splitting > > the one line up into three with some intermediate variables doesn't change > > that. > > As I understood it you didn't just split a line of code into three, but > wanted two processing steps. These logical steps are then somewhat remixed > by the shared error handling. You lose the information which step failed. > In the general case you may even mask a bug. > > Peter Well, what I really wanted was two conceptual steps, to make it easier for a reader of the code to follow what it's doing. My standard for code being adequately comprehensible is not that the reader *can* figure it out, but that the reader doesn't have to exert any effort to figure it out. Or even be aware that there's any figuring-out going on. He or she just reads it. From gslindstrom at gmail.com Tue Sep 2 23:05:15 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Tue, 2 Sep 2008 22:05:15 -0500 Subject: pyArkansas on October 4th Message-ID: We are pleased to announce that pyArkansas will be held on the campus of University of Central Arkansas (www.uca.edu) on October 4th. Scheduled classes in the morning include Python 101 taught by Dr. Bernard Chen (incoming faculty at UCA but having taught the course at Georgia State University), "Python 201" taught by Jeff Rush (Dallas Python Users Group) and Python for Unix/Linux Administration (Noah Gift teaching on his -- and Jeremy Jones' -- newly released OReilly title). The afternoon features talks and a panel discussion along with lots of great give aways and swag. Due to limitations of physical space we must close registration at 100 participants (in honor of my first OS, SunOS, we may go to 110). Check out our wiki at http://pycamp.python.org/Arkansas/HomePage. There's no registration fee, so if you're in the area stop on by...we are looking forward to a great day. Greg Lindstrom Python Artists of Arkansas (PyAR^2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From afriere at yahoo.co.uk Tue Sep 16 22:03:49 2008 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 16 Sep 2008 19:03:49 -0700 (PDT) Subject: Is 'x' an instance of a new-style class? References: <878wts76dc.fsf@mulj.homelinux.net> Message-ID: <937810d9-9525-4f78-a75e-84395a655292@r15g2000prh.googlegroups.com> On Sep 16, 8:05 pm, Hrvoje Niksic wrote: > "Gabriel Genellina" writes: > > In Python you would write isinstance(x, object). > > It will return True for all Python objects (except perhaps those that > fiddle with metaclasses), not only for instances of new-style classes. > Unlike say isinstance(x.__class__, type) which should distinguish between instances of new and old-style classes. From invalid at invalid Fri Sep 19 10:40:21 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 19 Sep 2008 09:40:21 -0500 Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> <6K2dnTGWYOdeXkzVnZ2dnUVZ_sednZ2d@posted.usinternet> Message-ID: On 2008-09-19, Steve Holden wrote: > Grant Edwards wrote: >> On 2008-09-18, Lawrence D'Oliveiro wrote: >>> In message >>> <973f75d4-90f5-4930-9107-15fc8651196d at v16g2000prc.googlegroups.com>, sui >>> wrote: >>> >>>> Traceback (most recent call last): >>>> File "mail5.py", line 21, in >>>> session = smtplib.SMTP(SMTPserver,port) >>>> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ >>>> (code, msg) = self.connect(host, port) >>>> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect >>>> self.sock.connect(sa) >>>> File "", line 1, in connect >>>> then conncetion time out..... >>> Could it be your ISP is blocking outgoing connections to port >>> 25? >> >> gmail doesn't accept mail via SMTP on port 25. >> > I was going to say that's boloney until I checked my settings - it's a > year or more since I set gmail up with Thunderbird. > > smtp.gmail.com accepts TLS connections on port 587. I should have been a bit more specific and said that the relay/smarthosts at smtp.gmail.com don't accept SMTP mail via port 25. The normal incoming SMTP servers pointed to by gmail.com's MX records do accept non-relay e-mail on port 25. They are, however, picky about IP addresses from which they'll accept connections (trying to connect via a commercial VPN server fails, but connecting via other machines works). -- Grant Edwards grante Yow! WHO sees a BEACH BUNNY at sobbing on a SHAG RUG?! visi.com From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 25 04:09:52 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 10:09:52 +0200 Subject: Er, one -lime- or two. In-Reply-To: <2ac98076-0163-45c4-8269-e6c1a1d70d7f@c65g2000hsa.googlegroups.com> References: <2ac98076-0163-45c4-8269-e6c1a1d70d7f@c65g2000hsa.googlegroups.com> Message-ID: <48db473e$0$24356$426a74cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : > A Python walks into a bar and orders a complex data structure. > Bartender says, "One line or two?" I don't think that one will have much success in parties !-) From deets at nospam.web.de Wed Sep 10 17:14:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 23:14:42 +0200 Subject: formating a filesystem with python In-Reply-To: References: Message-ID: <6iqrm2F3rqcU1@mid.uni-berlin.de> Ricardo Tiago schrieb: > Hi all, > > is there a package in python that allows to mount/umount and format > (to ext3) a filesystem? I know that this is possible by just calling > the os commands 'mount/umount and mkfs' but this would imply to have > to change sudoers to run the script as non-root. well, that's a very sensible unix-restriction. and you can't overcome that. IOW: no, there is no such thing. Diez From jdallen2000 at yahoo.com Mon Sep 22 01:35:10 2008 From: jdallen2000 at yahoo.com (James Dow Allen) Date: Sun, 21 Sep 2008 22:35:10 -0700 (PDT) Subject: Milenko Kindl rtegdgd References: <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> <59hdd4t65g9gb5kq535b2pkfj939hiruqv@4ax.com> Message-ID: <59239eed-cc47-4281-b146-04fb28264d61@n33g2000pri.googlegroups.com> On Sep 22, 5:08?am, Martin Griffith wrote: > On Sun, 21 Sep 2008 15:00:16 -0700 (PDT), in sci.electronics.design H > >Well, that's not C isn't it, more like Snobol or RPG/2 > > It's better to say > "that's not C, is it" > > I don't know why, but that's the way it works..... I recall a befuddled ESL student who missed a question based on "Isn't that girl pretty?" "Isn't she!!" James Hussein Allen From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 03:24:18 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Tue, 16 Sep 2008 00:24:18 -0700 Subject: Cross-platform socket.getsockopt and struct.unpack (or socket timeout)? Message-ID: M2Crypto has some old code that gets and sets socket timeouts in http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/Connection.py, for example: def get_socket_read_timeout(self): return timeout.struct_to_timeout(self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, timeout.struct_size())) The helper timeout module is here: http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/timeout.py I just noticed that this does not work on Windows. Here's a small test program that demonstrates the issue using native and Cygwin Python 2.5.2, 32-bit Windows XP (no M2Crypto needed for this): import struct import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) timeout_struct = s.getsockopt(socket.SOL_SOCKET, socket.SO_RCVTIMEO, struct.calcsize('ll')) print "%d:'%s'" % (len(timeout_struct), timeout_struct) print struct.unpack('ll', timeout_struct) This outputs 4:' ' Traceback (most recent call last): File "t.py", line 8, in print struct.unpack('ll', timeout_struct) File "/usr/lib/python2.5/struct.py", line 87, in unpack return o.unpack(s) struct.error: unpack requires a string argument of length 8 It works fine on 32 and 64 bit Linux (Ubuntu 8.04). The kicker is that I can't remember if I actually ever tested this on Windows before. This goes to a level of socket programming that I haven't done before. Is there a cross-platform way of doing what the M2Crypto code is attempting to do? -- Heikki Toivonen From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 06:33:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Sep 2008 10:33:44 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> Message-ID: <00ee05ca$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 18:20:17 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: >> > An ordinary singleton is instantiating the class multiple times yet >> > returning the same instance object; a class singleton is simply using >> > the class directly (like a module). > > Where is this "class singleton" terminology from? I don't know. Googling on it brings up an awful lot of C++ and Java source code for regular Singletons. Perhaps Aahz can shed some light on it? > It seems redundant to > me. It also doesn't seem to have anything to do with what "singleton" > means as a pattern; "using a class" is simply using a class. I don't see why this idiom causes such conceptual difficulty. There are classes with many instances; there are classes with a single instance (Singleton). Why should't there be classes with no instances? A class is just an object. If you find yourself caring whether a particular object is a class, an instance or a function, then you have to ask yourself why you are worrying about the implementation details. Of course as the library writer, it's your job to worry about the implementation details, but ideally the library user shouldn't have to. >> Since I now no longer think I need such a beast > > That's a relief :-) > >> I'd like to be able to call [a class] as if it were a function. >> Normally calling a class object returns an instance -- I wish to return >> something else. > > In that case, you *don't* want a class at all; the entire point of a > class is to define behaviour for instances. Classes encapsulate state + behaviour in one package, and they allow inheritance. That's a lot more than merely defining behaviour of instances. Instances in turn have the additional capability of being able to over-ride the class' state and behaviour: class C(object): x = 'spam' c = C() c.x = 'ham' # doesn't touch C.x If your instance doesn't do something the class can't do on it's own, why bother with the instance? > Instead, you want to define a class whose *instances* are callable, by > defining the '__call__' method to do whatever it is you want. Most of the time, sure. >> This seems to works: >> >> >>> class ClassSingleton(object): >> ... thing = (0, 1, 2) >> ... def __new__(cls, *args): >> ... return len(args+cls.thing) ... >> >>> ClassSingleton(1, 2, 4, 8, 16) >> 8 > > Horribly obfuscatory. Calling a class should return a new instance of > the class or something like it. Apart from the name, which I dislike, what is obfuscatory about it? Haven't you ever used factory functions or class builders? It's the same principle. Why do you care that ClassSingleton is a class instead of a function? I'm certainly not saying that we should use classes this way all the time, but the capability is there, and apparently not by accident. Guido wrote: "__new__ must return an object. There's nothing that requires that it return a new object that is an instance of its class argument, although that is the convention. If you return an existing object of your class or a subclass, the constructor call will still call its __init__ method. If you return an object of a different class, its __init__ method will not be called." http://www.python.org/download/releases/2.2.3/descrintro/ > Instead, define it so the user instantiates the class by calling the > class, and *then* calls that non-class object, and so shouldn't expect > to get a new instance back: > > >>> class CallableAppendor(object): > ... thing = (0, 1, 2) > ... def __call__(self, *args): > ... return len(args + self.thing) ... > >>> appendor = CallableAppendor() > >>> appendor(1, 2, 4, 8, 16) > 8 That's the right solution when the instance is able to override the state and/or behaviour of the class. Most uses of classes are like that: class Spam(object): def __init__(self, n): self.n = n def sing(self): return "spam "*self.n + " glorious SPAM!!!" Because the behaviour (method 'sing') depends on state which is specific to the instance (attribute 'n'), it is right and proper to instantiate the class. The class 'Spam' is a constructor for instances, and the instances do all the work. But my earlier example is not the same. In the example I gave, neither the behaviour nor the state depend on the instance: everything is specified in the class. Ben's variant behaves differently: the caller might override appendor.thing by hand. That is Ben's choice, of course, and it may be a valid one for many applications, but it's displaying different behaviour to my example. In my example, the instance doesn't matter. I could write it like this: >>> class CallableAppendor(object): ... thing = (0, 1, 2) ... @classmethod ... def __call__(cls, *args): ... return len(args + cls.thing) ... >>> appendor = CallableAppendor() >>> appendor.thing = (1, 2, 3, 4, 5, 6, 7, 8) >>> appendor(1, 2, 4, 8, 16) 8 >>> CallableAppendor.__call__(1,2,4,8,16) 8 but what's the purpose of instantiating the class? I concede that this is a made-up example, but here's an actual practical example of a class with no instances: Guido's attempt at an Enum: "This (ab)uses the class syntax as an elegant way to define enumerated types. The resulting classes are never instantiated -- rather, their class attributes are the enumerated values. For example: class Color(Enum): red = 1 green = 2 blue = 3 print Color.red will print the string ``Color.red'', while ``Color.red==1'' is true, and ``Color.red + 1'' raise a TypeError exception." http://www.python.org/doc/essays/metaclasses/ -- Steven From kaerbuhez at gmail.com Fri Sep 5 16:15:17 2008 From: kaerbuhez at gmail.com (kaer) Date: Fri, 5 Sep 2008 13:15:17 -0700 (PDT) Subject: mimms problem on Hardy Message-ID: <59447741-be83-49a0-9316-d1a42cc4450f@f63g2000hsf.googlegroups.com> Hello, I installed (manually) the last version of mimms -which is a python program- on an Ubuntu (8.04-server) box. I get that: kaer at subfighter:~/mimms-3.2$ mimms Traceback (most recent call last): File "/usr/bin/mimms", line 21, in from libmimms.core import run File "/usr/lib/python2.5/site-packages/libmimms/core.py", line 31, in from . import libmms File "/usr/lib/python2.5/site-packages/libmimms/libmms.py", line 29, in libmms.mmsx_connect.argtypes = [c_void_p, c_void_p, c_char_p, c_int] File "/usr/lib/python2.5/ctypes/__init__.py", line 361, in __getattr__ func = self.__getitem__(name) File "/usr/lib/python2.5/ctypes/__init__.py", line 366, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: /usr/lib/libmms.so.0: undefined symbol If it helps: kaer at subfighter:~/mimms-3.2$ ls -l /usr/lib/libmms.so.0 lrwxrwxrwx 1 root root 15 2008-08-20 01:41 /usr/lib/libmms.so.0 -> libmms.so.0.0.2: mmsx_connect If have no idea where the problem is. Thanks for your ideas, suggestions, comments ... From ranim81 at gmail.com Mon Sep 1 08:31:28 2008 From: ranim81 at gmail.com (raju) Date: Mon, 1 Sep 2008 05:31:28 -0700 (PDT) Subject: get paid on free offers Message-ID: http://www.moneymaking4.blogspot.com/ From kyosohma at gmail.com Tue Sep 16 15:26:17 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 16 Sep 2008 12:26:17 -0700 (PDT) Subject: on-the-fly translation with gettext References: <87od2opg5c.fsf@lapinot.localdomain> Message-ID: <9df975ce-058a-40ef-b440-8f7eb2dbaa11@y21g2000hsf.googlegroups.com> On Sep 16, 4:57?am, Benjamin Sigonneau wrote: > Hi all, > > I'm a complete beginner in python and in GUI designing, yet I'm writing > a GUI using python and Tkinter. ?I need it to be available both in french > and english, so I read the Fine Manual and gave a try to gettext. > > So far, I've managed to translate my app with the following snippet: > > | import gettext > | def install_lang (lang): > | ? ? try: > | ? ? ? ? t = gettext.translation(domain = 'mydomain', localedir = 'locale', > | ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? languages = [lang]) > | ? ? ? ? t.install() > | ? ? except IOError: > | ? ? ? ? import __builtin__ > | ? ? ? ? __builtin__.__dict__['_'] = lambda x: x > > When I issue an > > ? ? install_lang('en') > > at the beginning of my program, it is translated in english and, > conversely, an > > ? ? install_lang('fr') > > at the beginning makes it available in french. > > However, I'd like to let the user show the language on-the-fly during > execution. ?Having read the Python Library Reference, sec. 21.1.3.3 (seehttp://docs.python.org/lib/node740.html), I added a menu with two > radiobuttons and I merely set them up to call install_lang: > > | app_lang = StringVar() > | app_lang.set('en') > | langmenu = Menu(root) > | langmenu.add_radiobutton(label = "English", variable = app_lang, value = 'en', > | ? ? ? ? ? ? ? ? ? ? ? ? ?command = lambda l = 'en': install_lang(l)) > | langmenu.add_radiobutton(label = "French", variable = app_lang, value = 'fr', > | ? ? ? ? ? ? ? ? ? ? ? ? ?command = lambda l = 'fr': install_lang(l)) > > However, there is no magic. ?The language of the application remains > unchanged. ?If it was defined to be english at startup, so will it > remain. ?Conversely, it will stay in french if this was the language at > startup. > > Does somebody has any idea of what I'm doing wrong, and how to fix it? > > Thanks. > > -- > benjamin Try moving another window across your application after you change languages and see if it gets updated. Sometimes you need to refresh the layout of your application to get it to work...at least, in wxPython you do. Mike From manuhack at gmail.com Sat Sep 6 04:08:02 2008 From: manuhack at gmail.com (Manu Hack) Date: Sat, 6 Sep 2008 04:08:02 -0400 Subject: max(), sum(), next() In-Reply-To: <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> Message-ID: <50af02ed0809060108x1785b96fv8021646319daa45e@mail.gmail.com> On Sat, Sep 6, 2008 at 12:57 AM, castironpi wrote: > On Sep 5, 9:20 pm, "Manu Hack" wrote: >> On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: >> > On Sep 5, 3:28 am, "Manu Hack" wrote: >> >> On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: >> >> > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >> >> >> David C. Ullrich: >> >> >> >> > At least in mathematics, the sum of the elements of >> >> >> > the empty set _is_ 0, while the maximum element of the >> >> >> > empty set is undefined. >> >> >> >> What do you think about my idea of adding that 'default' argument to >> >> >> the max()/min() functions? >> >> >> >> Bye, >> >> >> bearophile >> >> >> > For max and min, why can't you just add your argument to the set >> >> > itself? >> >> >> > The reason max([]) is undefined is that max( S ) is in S. >> >> >> It makes sense. >> >> >> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >> >> >> It doesn't make sense to me. What do you set x to? >> >> > For all x. >> >> But then how can you conclude sum([]) = 0 from there? It's way far >> from obvious. > > You can define sum([a1,a2,...,aN]) recursively as > sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) "X", then > subtract aN. > > sum([a1,a2,...a(N-1)])+aN=X > sum([a1,a2,...a(N-1)])+aN-aN=X-aN > > For N=2, we have: > > sum([a1,a2])=X > sum([a1,a2])-a2=X-a2 > sum([a1,a2])-a2-a1=X-a2-a1 > > Since X= a1+ a2, replace X. > > sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 > > Or, > > sum([a1,a2])-a2-a1=0 > > Apply the recursive definition: > > sum([a1])+a2-a2-a1=0 > > And again: > > sum([])+a1+a2-a2-a1=0 > > And we have: > > sum([])=0. It makes more sense now, I just wanted to point out that only with sum([x]) = x, you can't get sum([]) = 0. From gminick at bzt.bzt Wed Sep 3 10:31:17 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 3 Sep 2008 14:31:17 +0000 (UTC) Subject: properties setting each other References: Message-ID: On Wed, 03 Sep 2008 15:57:50 +0200, mk wrote: > I try to set two properties, "value" and "square" in the following code, > and arrange it in such way that setting one property also sets another > one and vice versa. But the code seems to get Python into infinite loop: > Is there a way to achieve this goal of two mutually setting properties? My attempt: --- import math class Square(object): def __init__(self, val): self._square = pow(val, 2) self._value = math.sqrt(self.square) def getsquare(self): return self._square def setsquare(self, square): self._square = square self._value = math.sqrt(self._square) square = property(getsquare, setsquare) def getvalue(self): return self._value def setvalue(self, value): self._value = value self._square = math.pow(value, 2) value = property(getvalue, setvalue) a = Square(5) print a.square print a.value a.value = 10 print a.square print a.value a.square = 64 print a.square print a.value --- and the result: $ python sqval.py 25 5.0 100.0 10 64 8.0 $ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From tino at wildenhain.de Mon Sep 1 08:17:44 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 01 Sep 2008 14:17:44 +0200 Subject: Know if a object member is a method In-Reply-To: <27308d500809010245x29a393aya65561783ea0e804@mail.gmail.com> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> <27308d500809010245x29a393aya65561783ea0e804@mail.gmail.com> Message-ID: <48BBDD68.4040603@wildenhain.de> Luca wrote: > On Mon, Sep 1, 2008 at 11:35 AM, Steven D'Aprano > wrote: ... >> But not so easy to fool a type check: >> >>>>> type(x) == new.function >> False >> >> Of course that's not bullet-proof either. I leave it as an exercise to >> discover how you might break that piece of code. >> > > Ok, so... > > What is the best way to do this? The "most pythonic"? The question would be - why do you want this? Is it just curiosity or can we find a better solution to the overall problem, once understood? Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From gminick at bzt.bzt Fri Sep 26 06:21:58 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 26 Sep 2008 10:21:58 +0000 (UTC) Subject: urllib.urlopen fails in Emacs References: <877i8zco3t.fsf@gmail.com> Message-ID: On Fri, 26 Sep 2008 02:23:18 -0600, Iain Dalton wrote: > In Emacs, using run-python, > > import urllib > urllib.urlopen('http://www.google.com/') > > results in this traceback: ... > IOError: [Errno socket error] (111, 'Connection refused') > > It works fine from the command line. Why is this happening? I can't answer your question, since I don't use emacs, but it looks like emacs has some kind of built in firewall. ;-) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From marco.bizzarri at gmail.com Thu Sep 4 10:39:27 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 16:39:27 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <6i9uidFphkg0U1@mid.uni-berlin.de> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <6i9uidFphkg0U1@mid.uni-berlin.de> Message-ID: <3f0d61c40809040739t4ea080b1nc2683f43b1558b6@mail.gmail.com> On Thu, Sep 4, 2008 at 1:19 PM, Diez B. Roggisch wrote: > > What you are essentially asking is: why is python dynamic instead of static? > Most probably you're right. Maybe I will make a trip back to my university books and take a look at them again :-) Thanks Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From michael.pearmain at tangozebra.com Tue Sep 2 11:28:02 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 2 Sep 2008 08:28:02 -0700 (PDT) Subject: dict.update References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> <6i53m1Fo1a1aU1@mid.uni-berlin.de> Message-ID: <694d6b44-33b0-44a2-b375-a4deaf2e17c9@k37g2000hsf.googlegroups.com> Thanks Diez, This is almost perfect! Is there a way to ensure each list has two elements, even if one of them is blank? Mike From marco.bizzarri at gmail.com Mon Sep 1 09:39:47 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Mon, 1 Sep 2008 15:39:47 +0200 Subject: How to print first(national) char from unicode string encoded in utf-8? In-Reply-To: <7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> <7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> Message-ID: <3f0d61c40809010639p1db9fb8bl1c78e01ca96e2012@mail.gmail.com> On Mon, Sep 1, 2008 at 3:25 PM, wrote: > > When I do ${urllib.unquote(c.user.firstName)} without encoding to > latin-1 I got different chars than I will get: no ?ukasz but ? ukasz > -- > http://mail.python.org/mailman/listinfo/python-list That's crazy. "string".encode('latin1') gives you a latin1 encoded string; latin1 is a single byte encoding, therefore taking the first byte should be no problem. Have you tried: urlib.unquote(c.user.firstName)[0].encode('latin1') or urlib.unquote(c.user.firstName)[0].encode('utf8') I'm assuming here that the urlib.unquote(c.user.firstName) returns an encodable string (which I'm absolutely not sure), but if it does, this should take the first 'character'. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From gminick at bzt.bzt Sat Sep 6 18:32:47 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Sat, 6 Sep 2008 22:32:47 +0000 (UTC) Subject: Cathing several potential errors? References: Message-ID: On Sat, 6 Sep 2008 15:13:45 -0700 (PDT), cnb wrote: > if i do > try: > something > except TypeError, IndexError: > pass Parenthesize them: except (TypeError, IndexError): -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From maric at aristote.info Tue Sep 16 12:47:02 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 18:47:02 +0200 Subject: literals optimization (was Re: append on lists) In-Reply-To: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> References: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> Message-ID: <200809161847.02625.maric@aristote.info> Le Tuesday 16 September 2008 18:26:38 Grant Edwards, vous avez ?crit?: > I was asking where in the specification > it says that all expressions that > return something, return a > new object. ? I never said this, I said it's the spirit of python APIs, with some noticeable exceptions (see my first post). But for this case specifically, a + b *should* return a new object, see the documentation of __add__ and __iadd__ special methods, it's clearly stated. The fact that an integer with value "1" is always the same integer in some implementation is unrelated to the original problem. -- _____________ Maric Michaud From smbaker at gmail.com Wed Sep 3 15:09:03 2008 From: smbaker at gmail.com (Scott) Date: Wed, 3 Sep 2008 12:09:03 -0700 (PDT) Subject: creating a similar object from an derived class Message-ID: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> Let's say I have an object: class foo(): def create_another() return foo() def blah(): x = self.create_another() ... do something with X Now I create a inherited class of this object: class bar(foo): ... If I call bar.create_another(), it will return a foo() instead of a bar(). This isn't what I want. I would like bar.create_another() to create an instance for bar(). Obviously I can do this by overriding create_another, i.e. class bar(foo): def create_another() return bar() However, is there a way for me to modify foo() so that it automatically creates objects of the derived class, so that I don't have to continue to redefine create_another() ? For example, I tried the following: def create_another() return self.type()() but it did not work. Thanks, Scott From mikerslay at gmail.com Thu Sep 4 20:49:27 2008 From: mikerslay at gmail.com (MikeyBoy) Date: Thu, 4 Sep 2008 17:49:27 -0700 (PDT) Subject: Got Yuwie!? Message-ID: Join Yuwie and get paid to use a social network just like Myspace. From skip at pobox.com Sat Sep 13 10:03:32 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 13 Sep 2008 09:03:32 -0500 Subject: A service for testing Python code on multiple platforms and versions In-Reply-To: <48CBBFB5.1030202@gmail.com> References: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> <48CBBFB5.1030202@gmail.com> Message-ID: <18635.51252.26183.175426@montanaro-dyndns-org.local> Stef> Something like a multi-virtual machine on a web server, that you Stef> launch in the night, and in the morning you would get a full Stef> report of all problems on the specific OSs (probably someone is Stef> going to say that this is impossible, but fortunately I'm not Stef> hindered by any knowledge ;-) You could run Buildbot on a bunch of virtual machines on your computer (assuming your computer is x86 and its OS is supported by something like Sun's VirtualBox or VMWare's offerings). Skip From tjreedy at udel.edu Tue Sep 23 14:51:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 14:51:57 -0400 Subject: Linq to Python Message-ID: > Will LINQ be ported to Python ? I have three suggestions: 1. When starting a new thread, start a *new* thread. Don't tack a new, unrelated subject onto an existing thread. Your post will not be seen by people with readers that collapse thread and who do not happen to read the 'Python is slow?' thread. 2. Also, give enough informaton that people can understand your question without searching the web and guessing. In particular, that do *you* mean by LINQ? The game? The .NET component? Or something else? 3. Before posting, search the Python manuals or the web a bit for an answer. If you mean the .NET component, googling 'Python LINQ' should partly answer your question. tjr From clp at rebertia.com Sun Sep 28 15:11:58 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 28 Sep 2008 12:11:58 -0700 Subject: urllib2 and exceptions In-Reply-To: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> References: <6c5f3deb-183e-46df-9e41-aff8ca4bbbc9@n38g2000prl.googlegroups.com> Message-ID: <47c890dc0809281211p1aa5ae7fr882d42464d6dae55@mail.gmail.com> On Sun, Sep 28, 2008 at 11:03 AM, robean wrote: > Hi everyone, > > I have a question about using urllib2. > > I like urllib2 better than urllib at least in part because it has more > elaborate support for handling errors: there is built in support for > URLError (for faulty urls) and HTTPError (for http errors that might > originate from, say, passing an invalid stock-ticker in the program > below). However I can get neither to work. I'm attaching below the > (very short) code: can anyone point out what I'm doing wrong? > > Now, if I replace the URLError and HTTPError with IOError (the class > from which both URLError and HTTPError inherit), the program works > fine. Why is it that I can call the generic IOError class, but none of > the Error classes derived from that? These are clearly defined in the > urllib2 manual. Very confused... > > Here's the code: > > > import urllib2 > > # read stock information from yahoo finance for Traget (TGT) > goodTicker = 'TGT' # program works with this > badTicker = 'TGTttttttt' # python doesn't understand either HTTPError > or URLError with this > > url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker > > try: > handle = urllib2.urlopen(url) > > # this does not work > except HTTPError, e: > print "There was an http error" > print e > > # this also does not work > except URLError, e: > print "There is a problem with the URL" > print e > exit(1) > > #this works > except IOError, e: > print "You have an IOError" > print e > > text = handle.readlines()[:20] > for line in text: > print line > > -- > http://mail.python.org/mailman/listinfo/python-list > My Python begs to differ: #tmp.py import urllib2 badTicker = 'TGTttttttt' url = "http://ichart.finance.yahoo.com/table.csv?s=" + badTicker try: handle = urllib2.urlopen(url) except urllib2.HTTPError, e: print "There was an http error" print e except urllib2.URLError, e: print "There is a problem with the URL" print e except urllib2.IOError, e: print "You have an IOError" print e #in the shell $ python -V Python 2.5.1 $ python Desktop/tmp.py There was an http error HTTP Error 404: Not Found Are you using an outdated version of Python perhaps? Regards, Chris -- Follow the path of the Iguana... http://rebertia.com From martin at see.sig.for.address.invalid Tue Sep 2 06:24:17 2008 From: martin at see.sig.for.address.invalid (Martin Gregorie) Date: Tue, 2 Sep 2008 10:24:17 +0000 (UTC) Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Mon, 01 Sep 2008 20:48:23 -0400, George Neuner wrote: > I don't know the correct term, but what I was talking about was a tiny > switch with a 1/2 inch metal handle that looks like a longish grain of > rice. We used to call them "knife" switches because after hours > flipping them they would feel like they were cutting into your fingers. > That sounds like a sub-minature SPDT toggle switch with a normal handle. Cheap as chips, which is probably why they were used on that front panel. Like this by any chance? http://www.maplin.co.uk/images/300/fh00a_ff70m.jpg -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From grante at visi.com Tue Sep 23 09:57:14 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 23 Sep 2008 08:57:14 -0500 Subject: Python is slow? References: Message-ID: On 2008-09-23, sturlamolden wrote: [...] > After having a working Python prototype, I resorted to rewrite the > program in C++. The Python prototype took an hour to make, debug and > verify. The same thing in C++ took me almost a day to complete, even > with a working prototype as model. To my surprise, the resulting beast > of C++ required 64.3 seconds to construct the same kd-tree. Searching > the tree was not faster either, 1,000 points required 38.8 seconds. I > wasted a day, only to find my Python prototype being the faster. > > We may conclude that I'm bad at programming C++, AFAICT, _everybody_ is bad at programming C++. One begins to suspect it's not the fault of the programmers. -- Grant Edwards grante Yow! Finally, Zippy at drives his 1958 RAMBLER visi.com METROPOLITAN into the faculty dining room. From pmaupin at gmail.com Sun Sep 7 16:23:30 2008 From: pmaupin at gmail.com (Patrick Maupin) Date: Sun, 7 Sep 2008 13:23:30 -0700 (PDT) Subject: __builtins__ magic behavior References: Message-ID: On Sep 7, 2:50?pm, "Gabriel Genellina" wrote: > Inside PyFrame_New, there is a shortcut: if the new frame and > the previous one share the same globals, then the previous > builtins are copied into the new frame. Only if the globals > differ the builtins are searched in globals. From frameobject.c: > /* If we share the globals, we share the builtins. Save a > lookup and a call. */ That was exactly my problem. Thank you for the cogent explanation. > If you want to execute some code with modified builtins, do not > change __builtins__ in the *calling* code, but in the globals that > you pass to the exec call. That appears to be the most logical > approach, and the way the developers appear to have expected. Actually, my use-case is a tiny bit different than this. I am dynamically creating module objects, and was going nuts trying to comprehend the inner workings of behind-the-scenes __builtins__ magic in the module object, not realizing that the magic was actually in the execution frames. Thanks, Pat From bj_666 at gmx.net Wed Sep 3 02:40:10 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Sep 2008 06:40:10 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> Message-ID: <6i6pq9Fmcad7U2@mid.uni-berlin.de> On Tue, 02 Sep 2008 19:54:12 -0400, Derek Martin wrote: >> And if they model an action there must be some way to activate the >> action > > That's a reasonable assumption, but as I also said, the object might > just describe the action -- essentially the equivalent of a struct in C. ``struct``\s in C describe *actions*!? Functions do this. And a class that describes an action that is executed in the `__init__()` method is conceptually a function and shouldn't be a class. There must be a better name for the "thing" it returns. Again guideline, not law, but a very strong guideline IMHO. >> but the instances of `Popen` are no actions. There's no way to >> "execute" a `Popen` instance. > > Yes there is... you execute it when you instantiate the object. But then the instance itself isn't an action but the result of one. > At the time of instantiation, you "open" the "P" (pipes). For an > object which describes an action, I think it's perfectly sensible that > instantiation is when the action occurs, [?] Here I disagree again. Because the type/class name of an instance should be a name of the "thing"/concept of the instance, not the action used to create it. >> > Yet some of you state your case as if it is incontrovertable fact. >> > I've given a good case as to why it IS a good name (one which I >> > genuinely support), and disagree as you may, none of the points any >> > of you have made invalidate or even weaken my argument. >> >> Maybe from your POV. Facts: It doesn't use the `popen()` function > > So? Neither does the C version of popen(), but that function is still > called popen()! Now you lost me. The C version of `popen()` isn't recursive, why on earth should it be, so what's that statement supposed to mean!? >> to three file objects, more attributes and methods), the function used >> on Windows under the hood is called `CreateProcess()` not >> `CreatePipe()`. > > How does Windows implement popen()? [I think they call it _popen() > though...] Doesn't matter because the `Popen()` implementation doesn't use `popen()`. Ciao, Marc 'BlackJack' Rintsch From pavlovevidence at gmail.com Wed Sep 24 23:17:57 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 24 Sep 2008 20:17:57 -0700 (PDT) Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: On Sep 24, 9:27?pm, Tim Arnold wrote: > (2) Next thought was fork, but I don't know how to signal when each > child is > finished. Consider the multiprocessing module, which is available in Python 2.6, but it began its life as a third-party module that acts like threading module but uses processes. I think you can still run it as a third- party module in 2.5. Carl Banks From san82moon at gmail.com Mon Sep 1 04:48:07 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:48:07 -0700 (PDT) Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <83330868-db47-46d0-b734-fba2688ff5ec@a2g2000prm.googlegroups.com> On Sep 1, 1:45 pm, Bruno Desthuilliers wrote: > lee a ?crit : > > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, > > ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? > > It's quite simple (hint : read the FineManual(tm) for dict.items() and > list.index()), but 1/totally inefficient and 2/not garanteed to yield a > single value (what if 'dfsdf' happens to be also the 4th item of the > list bound to key 'address' ?). > > May I suggest you rethink your data structure instead ? What you have > here is obviously a collection of 'phno/email/name/address'records. > These records shouldn't be split across different objects. Assuming > 'phno' is a unique identifier for each record, a better data structure > would be: > > records = { > 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, > 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, > # etc > > } > > This way, the lookup is as simple and efficient as possible. > > My 2 cents.... hi, i agree with u, my data strusture is not efficient. but all the records,viz...name,phno, email,address are all generated at runtime , when the user enters them. so how can i design my datastructure in that case? From wescpy at gmail.com Fri Sep 5 04:21:20 2008 From: wescpy at gmail.com (wesley chun) Date: Fri, 5 Sep 2008 01:21:20 -0700 Subject: [ANN] final 2008 Python courses, San Francisco In-Reply-To: <78b3a9580809050119q46e5f004q7d7761950429fac4@mail.gmail.com> References: <78b3a9580809050116w2cfd7a98s10b7b9d201a979d8@mail.gmail.com> <78b3a9580809050119q46e5f004q7d7761950429fac4@mail.gmail.com> Message-ID: <78b3a9580809050121t517a93f4uca7b1918dac66f9c@mail.gmail.com> Need to get up-to-speed with Python as quickly as possible? Come join me, Wesley Chun, author of Prentice-Hall's bestseller "Core Python Programming," for another comprehensive intro course plus a 1-day Internet programming course coming up in November in beautiful Northern California! I look forward to meeting you! (Comprehensive) Introduction to Python Mon-Wed, 2008 Nov 10-12, 9am-5pm Internet Programming with Python Sat, 2008 Nov 15, 9am-5pm courses can be taken separately or combined for a discounted price. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - (COMPREHENSIVE) INTRODUCTION TO PYTHON Although this course may appear to those new to Python, it is also perfect for those who have tinkered with it and want to "fill in the gaps" and/or want to get more in-depth formal training. It combines the best of both an introduction to the language as well as a "Python Internals" training course. We will immerse you in the world of Python in only a few days, showing you more than just its syntax (which you don't really need a book to learn, right?). Knowing more about how Python works under the covers, including the relationship between data objects and memory management, will make you a much more effective Python programmer coming out of the gate. 3 hands-on labs each day will help hammer the concepts home. Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware, NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting or jumping to Plone, Zope, TurboGears, Pylons, Django, Google App Engine, Jython, IronPython, and Mailman will also benefit! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - INTERNET PROGRAMMING WITH PYTHON This is a one-day course with lecture and lab exposing attendees to FOUR distinct areas of Internet programming: * Network Programming using Sockets -- we introduce client/server architecture and how to program sockets using Python. * Internet Client Programming -- we learn how to use Python's standard library to create FTP, NNTP, POP3, and SMTP clients * Web Programming -- before you jump on all the web framework bandwagons, it's a good idea to learn basics and the basis of how all web servers deliver dynamic content back to the client browser to prepare you better when jumping to a full-stack web framework * Intro to Django -- a lightweight introduction to the Django web framework including whipping up a very simple blog application in 20min! - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA WEB: http://cyberwebconsulting.com (click "Python Training") FLYER: http://starship.python.net/crew/wesc/flyerPP1combo.pdf LOCALS: easy freeway (101/280/380) with lots of parking plus public transit (BART and CalTrain) access via the San Bruno stations, easily accessible from all parts of the Bay Area VISITORS: free shuttle to/from the airport, free high-speed internet, free breakfast and regular evening receptions; fully-equipped suites See website for costs, venue info, and registration. Discounts are available for multiple registrations as well as for teachers/students. Hope to see you there! -- wesley - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python Programming", Prentice Hall, (c)2007,2001 http://corepython.com "Python Web Development with Django", Addison Wesley, (c) 2008 http://withdjango.com wesley.j.chun :: wescpy-at-gmail.com python training and technical consulting cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com From circularfunc at yahoo.se Sat Sep 6 18:06:58 2008 From: circularfunc at yahoo.se (cnb) Date: Sat, 6 Sep 2008 15:06:58 -0700 (PDT) Subject: Multicore-programming? Message-ID: <4fd8cdf6-0875-4bfc-a2f0-f0ac4c0777d6@d77g2000hsb.googlegroups.com> If I buy a multicore computer and I have really intensive program. How would that be distributed across the cores? Will algorithms always have to be programmed and told specifically to run on several cores so if not told it will only utilize one core? So is the free lunch really over or is this just an overhyped phenomena? Is threading with Python hard? Can you start several processes with Python or just threads? From chiendarret at gmail.com Tue Sep 2 16:57:05 2008 From: chiendarret at gmail.com (Francesco Pietra) Date: Tue, 2 Sep 2008 22:57:05 +0200 Subject: Renumbering Message-ID: Hi; I would like to renumber, starting from 1, column 6 (i.e, 428 become 1, 429 becomes 2, etc for a very long list) ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 ATOM 3425 CA LEU B 428 142.918 87.524 78.875 1.00115.20 2SG3427 ATOM 3426 CB LEU B 428 141.559 88.057 78.392 1.00115.20 2SG3428 ATOM 3427 CG LEU B 428 140.577 88.341 79.544 1.00115.20 2SG3429 ATOM 3428 CD1 LEU B 428 141.102 89.464 80.454 1.00115.20 2SG3430 ATOM 3429 CD2 LEU B 428 139.159 88.615 79.017 1.00115.20 2SG3431 ATOM 3430 C LEU B 428 142.680 86.253 79.615 1.00115.20 2SG3432 ATOM 3431 O LEU B 428 142.725 86.226 80.842 1.00115.20 2SG3433 ATOM 3432 N SER B 429 142.432 85.155 78.878 1.00134.86 2SG3434 ATOM 3433 CA SER B 429 142.175 83.908 79.534 1.00134.86 2SG3435 ATOM 3434 CB SER B 429 141.666 82.805 78.590 1.00134.86 2SG3436 ATOM 3435 OG SER B 429 140.392 83.155 78.069 1.00134.86 2SG3437 ATOM 3436 C SER B 429 143.451 83.432 80.141 1.00134.86 2SG3438 ATOM 3437 O SER B 429 144.543 83.756 79.676 1.00134.86 2SG3439 Distinctive character is column 5, i.e., it must be set that only lines containing "B" should be renumbered. As you can see, the number of lines for a particular value in column 6 changes from situation to situation, and may even be different for the same name in column 4. For example, LEU can have a different number of lines depending on the position of this amino acid (leucine). I was unable to set non-proportional characters, sorry. Thanks for help francesco pietra From nick at craig-wood.com Wed Sep 24 05:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 24 Sep 2008 04:30:03 -0500 Subject: Comparing float and decimal References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: Terry Reedy wrote: > The new fractions module acts differently, which is to say, as most > would want. > > >>> from fractions import Fraction as F > >>> F(1) == 1.0 > True > >>> F(1.0) > Traceback (most recent call last): > File "", line 1, in > F(1.0) > File "C:\Program Files\Python30\lib\fractions.py", line 97, in __new__ > numerator = operator.index(numerator) > TypeError: 'float' object cannot be interpreted as an integer Both the Fraction module and the Decimal module could represent floats exactly and reversibly since floats are of the form mantissa * 2**exponent which is exactly representable as a fraction (rational) and also as mantissa2 * 10**exponent2 as to why we don't do this... I guess it is to preserve the sanity of the user when they write fraction(0.1) or decimal(0.1) did they really mean fraction(1,10), decimal("0.1") or the exact representations which are decimal("0.1000000000000000055511151231257827021181583404541015625") and fraction(3602879701896397,2**55) Given that we let the exact representations leak out anyway (which causes a lot of FAQs in this list), eg >>> 0.1 0.10000000000000001 IMHO We should put the exact conversions in for floats to Decimal and Fraction by default and add a new section to the FAQ! In that way people will see floats for what they really are - a crude approximation to a rational number ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bborcic at gmail.com Sat Sep 13 09:22:12 2008 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 13 Sep 2008 15:22:12 +0200 Subject: Injecting new names into the above frame In-Reply-To: References: Message-ID: Why don't you use import and __import__() ? - They seem designed for such an application. I mean, I am not against vicious hacks for the fun of them, but not if they serve the illusion that what they do can't (easily) be achieved other ways. Cheers, BB Peter Waller wrote: > Dear Pythoners, > > I know this will probably be perceived as 'evil voodoo', and fair > enough: it probably is. I guess it is unpythonic. > > .. but I want to know how to do it anyway - mostly for my own > interest. > > Consider the following snippet of code: > > --- > def Get( *names ): > if not names: return None > > frame = sys._getframe(1) > prevFrameLocals = frame.f_locals > > for name in names: > prevFrameLocals[ name ] = FetchObjectNamed( name ) > > Get("a", "b", "c") > > print a, b, c > --- > > FetchObjectNamed() is an arbitrary function which takes a string and > returns an object it got from some store somewhere. > > This works fine at the module level, because names in the locals/ > globals dictionary can be played with in this way. The idea is to save > lots of typing, i.e. > > a, b, c = Get("a","b","c") > > ..gets frustrating after much typing for many objects with long names. > This is just an example, there are other instances I have where it > would be nice to inject names into the frame above. > > Of course, we hit a road block when we call 'Get' from a function > rather than a module, because the locals dictionary does not get > copied back into the code object automatically, so we have to add this > snippet before the Get() function returns: > > from ctypes import pythonapi, py_object, c_int > pythonapi.PyFrame_LocalsToFast( py_object( frame ), 1 ) > > This copies back the names into the code object, and works fine.. that > is, if the names already exist within the code object. > > def MyFunction(): > a = None > Get("a") > print a # Works > Get("b") > print b # Name error, b is undefined > > Is there any way for Get() to define a new variable within > MyFunction's code object? Or is there any programmatic way to, at > runtime, insert new names into functions? > > I don't care how hacky it is and whether it requires making calls to > python's internals with ctypes - maybe the whole code object needs to > be replaced? is it even possible to do that when the Get() function is > about to return to this new code object? > > Cheers, > > - Peter > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Wed Sep 24 23:33:32 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 20:33:32 -0700 (PDT) Subject: is decorator the right thing to use? References: Message-ID: On Sep 24, 5:21?pm, "Dmitry S. Makovey" wrote: > Hi, > > after hearing a lot about decorators and never actually using one I have > decided to give it a try. My particular usecase is that I have class that > acts as a proxy to other classes (i.e. passes messages along to those > classes) however hand-coding this type of class is rather tedious, so I > decided to use decorator for that. Can somebody tell me if what I'm doing > is a potential shot-in-the-foot or am I on the right track? (Note, It's > rather rudimentary proof-of-concept implementation and not the final > solution I'm about to employ so there are no optimizations or > signature-preserving code there yet, just the idea). > > Here's the code: > > class A: > ? ? b=None > ? ? def __init__(self,b): > ? ? ? ? self.val='aval' > ? ? ? ? self.b=b > ? ? ? ? b.val='aval' > > ? ? def mymethod(self,a): > ? ? ? ? print "A::mymethod, ",a > > ? ? def mymethod2(self,a): > ? ? ? ? print "A::another method, ",a > > def Aproxy(fn): > ? ? def delegate(*args,**kw): > ? ? ? ? print "%s::%s" % (args[0].__class__.__name__,fn.__name__) > ? ? ? ? args=list(args) > ? ? ? ? b=getattr(args[0],'b') > ? ? ? ? fnew=getattr(b,fn.__name__) > ? ? ? ? # get rid of original object reference > ? ? ? ? del args[0] > ? ? ? ? fnew(*args,**kw) > ? ? setattr(A,fn.__name__,delegate) > ? ? return fn > > class B: > ? ? def __init__(self): > ? ? ? ? self.val='bval' > > ? ? @Aproxy > ? ? def bmethod(self,a): > ? ? ? ? print "B::bmethod" > ? ? ? ? print a, self.val > > ? ? @Aproxy > ? ? def bmethod2(self,a): > ? ? ? ? print "B::bmethod2" > ? ? ? ? print a, self.val > > b=B() > b.bmethod('foo') > a=A(b) > b=B() > b.val='newval' > a.bmethod('bar') > a.bmethod2('zam') It might help to tell us the order of events that you want in your program. You're not using 'mymethod' or 'mymethod2', and you probably want 'return fnew' for the future. Something dynamic with __getattr__ might work. Any method call to A, that is an A instance, tries to look up a method of the same name in the B instance it was initialized with. a.foo( ) -> 'in a.foo' -> 'calling b.foo' -> 'return' -> 'return' a.mymethod( ) -> 'in a.mymethod' -> 'calling b.mymethod' -> AttributeError: 'b' has no attribute 'mymethod'. From bdesth.quelquechose at free.quelquepart.fr Wed Sep 24 14:39:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 20:39:45 +0200 Subject: Linq to Python In-Reply-To: References: Message-ID: <48daa55d$0$19939$426a74cc@news.free.fr> hrishy a ?crit : (snip) > I apologise > (I thought Python programmers were smart and they did know what LINQ was) Is there really any relation between "being smart" and knowing anything about the latest MS fad ? From mohed at hotmail.com Mon Sep 29 16:51:06 2008 From: mohed at hotmail.com (Mohed) Date: Mon, 29 Sep 2008 13:51:06 -0700 (PDT) Subject: Source code for python nativ methods and classes Message-ID: <6097159a-6923-4422-ac26-369cf9e94680@a1g2000hsb.googlegroups.com> Hello. I am interrested in seeing the source code for all the nativ builtin methods and clases in python. Is there a webpage that lists them or is this done easier some other way. This is my first post so feel free to creticue, the more you do the faster i learn to post well. Mohed From fredrik at pythonware.com Fri Sep 5 02:34:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:34:53 +0200 Subject: ctypes error on Windows In-Reply-To: References: Message-ID: Mike Hostetler wrote: > I'm working on a script with the most excellent uTibyLib library. The script works just fine on Mac, but on Windows I get this: > > File "findtables.py", line 82, in cleanHTML > return str(tidy.parseString(decentDoc)) > File "c:\Python24\Lib\site-packages\tidy\lib.py", line 207, in parseString > doc = self._create(**kwargs) > File "c:\Python24\Lib\site-packages\tidy\lib.py", line 183, in _create > doc = _Document() > File "c:\Python24\Lib\site-packages\tidy\lib.py", line 135, in __init__ > self.cdoc = _tidy.Create() > File "c:\Python24\Lib\site-packages\tidy\lib.py", line 46, in __getattr__ > return getattr(self.lib, name) > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 353, in __getatt > func = self.__getitem__(name) > File "C:\Python24\Lib\site-packages\ctypes\__init__.py", line 358, in __getite > func = self._FuncPtr((name_or_ordinal, self)) > AttributeError: function 'Create' not found > > I do have the tidy.dll installed (if I didn't, I couldn't even import the tidy module). typing the following into the Python interpreter might give you some more clues: >>> import _tidy >>> _tidy.__file__ >>> dir(_tidy) From littlesweetmelon at gmail.com Sun Sep 28 03:02:55 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Sun, 28 Sep 2008 15:02:55 +0800 Subject: design pattern: MVC in python In-Reply-To: <3ff66ae00809272329mce8d3c9lb94c316e169cf63a@mail.gmail.com> References: <3ff66ae00809272329mce8d3c9lb94c316e169cf63a@mail.gmail.com> Message-ID: Really helpful! 2008/9/28 Mikolai Fajer : > The following link directly discusses using MVC and pygame. > > http://ezide.com/games/writing-games.html > > -- > > -Mikolai Fajer- > -- > http://mail.python.org/mailman/listinfo/python-list > From rsinger at ____.com Tue Sep 23 09:44:56 2008 From: rsinger at ____.com (Robert Singer) Date: Tue, 23 Sep 2008 15:44:56 +0200 Subject: Python is slow? References: Message-ID: On Tue, 23 Sep 2008 06:23:12 -0700 (PDT), sturlamolden wrote: >I have recently been playing with a kd-tree for solving the "post >office problem" in a 12-dimensional space. This is pure cpu bound >number crunching, a task for which I suspected Python to be >inefficient. Well, python is not a number crunching language. However much we would like it to be (we would ? :-). No scripting language is. Developing time is shorter, I agree, but when you have, for example a problem which takes 8,31 minutes to go through in optimized fortran code (like the one I had the other day), then that hardly matters. > >My prototype in Python 2.5 using NumPy required 0.41 seconds to >construct the tree from 50,000 samples. Unfortunately, searching it >felt a bit slow, finding the 11 nearest-neighbours of 1,000 points >took 29.6 seconds (and there were still 49,000 to go). Naturally, I >blamed this on Python. It would be 100 times faster if I used C++, >right? Not necessarily. Before resorting to rewriting the problem try psyco. It speeds up things sometimes. Also, (I'm not that familiar with python yet, so I don't know how to do it in python), try finding the bottlenecks of your calculation. Are the loops where most of the processing time is wasted, or disk accessing, or ... ? > >After having a working Python prototype, I resorted to rewrite the >program in C++. The Python prototype took an hour to make, debug and >verify. The same thing in C++ took me almost a day to complete, even >with a working prototype as model. To my surprise, the resulting beast >of C++ required 64.3 seconds to construct the same kd-tree. Searching >the tree was not faster either, 1,000 points required 38.8 seconds. I >wasted a day, only to find my Python prototype being the faster. > >We may conclude that I'm bad at programming C++, but I suspect that is >not the case here. Albeit micro-benchmarks may indicate that Python is >100-200 times slower than C++, they may not be applicable to the real >world. Python can be very efficient. And when combined with libraries >like NumPy, beating it's performance with hand-crafted C++ is >difficult. At least, my 10 years experience programming scientific >software in various languages was not sufficient to beat my own Python >prototype with C++. > >That is not to say I have never seen C++ run a lot faster than Python. >But it tends to be very short pieces of CPU bound code, no more than a >function or two. But as the problem grows in complexity, C++ >accumulates too much of its own bloat. > Well, personally, I try to combine fortran (being a fortran programmer by trade) with python (in the last few years), as I find fortran to be, by two grades, more comfortable for solving scientific problems then c (or python for that matter, although it has its merits). Starting from ith his capabilities for "normal" array handling, to optimisation and easy readability, to whatnot. Best regards Bob From deets at nospam.web.de Mon Sep 1 05:37:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 11:37:56 +0200 Subject: how to find position of dictionary values References: <48bbab73$0$27858$426a34cc@news.free.fr> Message-ID: <6i1rgcFo0f1gU1@mid.uni-berlin.de> lee wrote: > On Sep 1, 1:45 pm, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> lee a ?crit : >> >> > hi, >> > i have a dictionary as follows : >> > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', >> > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], >> > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} >> >> > if user is enters the 3rd item of key phno, >> > ie "dfsdf" in my dict, >> > how can i find it is the third item in the internal list of phno of >> > that dictionary? >> >> It's quite simple (hint : read the FineManual(tm) for dict.items() and >> list.index()), but 1/totally inefficient and 2/not garanteed to yield a >> single value (what if 'dfsdf' happens to be also the 4th item of the >> list bound to key 'address' ?). >> >> May I suggest you rethink your data structure instead ? What you have >> here is obviously a collection of 'phno/email/name/address'records. >> These records shouldn't be split across different objects. Assuming >> 'phno' is a unique identifier for each record, a better data structure >> would be: >> >> records = { >> 'dgsd' : {'email': 'dg', 'name' : 'ds', 'address' : 'sdg'}, >> 'gsdg' : {'email': 'sgsd', 'name':'ds', 'address' : 'dsgsdg'}, >> # etc >> >> } >> >> This way, the lookup is as simple and efficient as possible. >> >> My 2 cents.... > > hi, > i agree with u, my data strusture is not efficient. but all the > records,viz...name,phno, email,address are all generated at runtime , > when the user enters them. so how can i design my datastructure in > that case? Are "u" short on keystrokes? You are not textmessaging here... Regarding the actual question: there is no difference in building your or the other structure. It's only a question of which key you use first. Instead of first looking up the type of the record ("phno" or some such), do that with the name of the user. If no record exists, create one. Then populate the record with the user's values. Like this: user = "dsdf" phonenumber = "123" record = records.setdefault(user, {}) record["phno"] = phonenumber Diez From tjreedy at udel.edu Tue Sep 23 14:36:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 14:36:29 -0400 Subject: Docstrings for class attributes In-Reply-To: <6jsfeaF4pbs9U1@mid.individual.net> References: <6jsfeaF4pbs9U1@mid.individual.net> Message-ID: Peter Pearson wrote: > On Tue, 23 Sep 2008 15:23:35 +1000, Tom Harris wrote: >> I want to have a class as a container for a bunch of symbolic names >> for integers, eg: >> >> class Constants: >> FOO = 1 >> BAR = 2 >> >> Except that I would like to attach a docstring text to the constants, >> so that help(Constants.FOO) will print some arbitrary string. > [snip] > > Commiserating, not helping: I have a similar problem with a module > that holds values of physical constants, > http://webpages.charter.net/curryfans/peter/nature.py: > > boltzmanns_constant = 1.380622e-16 * erg / k > stefan_boltzmann_constant = 5.66961e-5 * erg/s/cm/cm/k/k/k/k > gravitational_constant = 6.6732e-8 * erg*cm/g/g > > I would like to reveal more details with, e.g., > help( gravitational_constant ) . . . and maybe then I could > use shorter names. gravitational_constant = g = 6.6732e-8 * erg*cm/g/g ... From steve at REMOVE-THIS-cybersource.com.au Tue Sep 2 12:55:53 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 16:55:53 GMT Subject: How to write verbose scripts Message-ID: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> I find myself writing command line tools in Python where I wish to include "verbose" output to stdout. I start with a helper function: def print_(obj, level=0): if _verbosity >= level: print obj And then I end up with functions or methods looking like this: def parrot(x) print_("precondition", level=2) do_something() print_("status is good...", level=1) print_("parrot is squawking strongly now", level=2) do_something_else() print_("squawk squawk squawk", level=3) do_more() print_("postcondition", level=1) return something That often means that my functions end up with more message printing code than actual code. The whole thing seems messy and hard to manage for all but the smallest scripts. Worst of all, sometimes the messages I wish to print may be expensive to compute, and I don't want to waste time computing them if they aren't going to be printed because the verbosity is too low. But nor do I wish to fill my code with this: if _verbosity >= 3: x = calculate_complicated_thing() print_(x, level=3) Is there a better way of doing this than the way I am going about it? -- Steven From python.list at tim.thechases.com Wed Sep 17 06:45:44 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 17 Sep 2008 05:45:44 -0500 Subject: File Reading related query In-Reply-To: References: Message-ID: <48D0DFD8.4000309@tim.thechases.com> >> Is there any function for reading a file while ignoring *\n* occuring in >> the file? > > can you be a bit more precise? are we talking about text files or > binary files? how do you want to treat any newlines that actually > appear in the file? I believe the OP is referencing this behavior: for line in file('x.txt'): assert not ( line.endswith('\r') or line.endswith('\n')), "Don't want this" else: yay() # we never end up reaching this which can be done with a simple generator/wrapper: def unnewline(iterator): for line in iterator: yield line.rstrip('\r\n') for line in unnewline(file('x.txt')): assert not ( line.endswith('\r') or line.endswith('\n')), "Don't want this" else: yay() # we get here this time Alternatively, the content can just be modified on the fly: for line in file('x.txt'): line = line.rstrip('\r\n') ... yes, the interpretation would differ if it were a binary file, but the above interpretation is a pretty common case (i.e. I encounter it daily, in my processing of client data-feeds). -tkc From numan.salati at gmail.com Thu Sep 18 12:32:32 2008 From: numan.salati at gmail.com (numan.salati at gmail.com) Date: Thu, 18 Sep 2008 09:32:32 -0700 (PDT) Subject: Out of memory issue with dialog box Message-ID: Hi, We have a mutilthreaded process in which one of the threads uses too much memory causing the process to run out of memory. However when this happens we see a dialog box pop up with the message "fatal error in GC : too many heap sections." When you click "ok" only then does the process die. Is there a way for the process to crash directly without going through the dialog box. Any help would be appreciated? From josiah.carlson at gmail.com Mon Sep 15 03:03:31 2008 From: josiah.carlson at gmail.com (NotAnAdminAccount) Date: Mon, 15 Sep 2008 00:03:31 -0700 (PDT) Subject: Python IDEs with F5 or hotkey shell interaction References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> Message-ID: <6183f3fa-3275-437d-875e-c0613d071f68@c22g2000prc.googlegroups.com> On Sep 2, 7:01?am, mmm wrote: > I am looking for advice on Python Editors and IDEs > > I have read other posts and threads on the subject and my two > questions at this time are mainly about the IDLE-like F5-run > facilities. ?While I am fairly happy using IDLE, the debugger is > unintuitive to me and I wanted a project manager and a better variable/ > class browser and also the potential to edit/run other languages such > as R and Tex/Latex. Windows and LINUX compatibility is desired too. > > I found numerous editor candidates from reading posts to this Python > users group list ?and also documents such as ?http://wiki.python.org/moin/PythonEditors > but few if any alternatives seem to have all of the ??interactive? > power of IDLE?- not only a run program in a python shell hotkey but a > persistent, after-a-run memory state can be accessed for interactive > coding and exploration-- ?i.e. how IDLE works ! > > *** My first questions is what other editor/IDE have IDLE-like > interactive features. ?Or to put it another way, is my appraisal below > of the editors & IDEs I tried right (note some where looked at as much > as a year ago). > > Python specific > ?IDLE ? ? ? ?F5 run & Full shell interaction > ?PythonWin ? F5 run & Full shell interaction, MS Windows only > ?PyScripter ?F9 run & shell interaction, > ? ? ? ? ? ? ? ? ? ? ?but script created variables are not persistent > (???!) > ?PyPE? ? ? ?F5 run, but not an interactive shell > ?DrPython ? ?F5 run, but not an interactive shell in MS Windows (maybe > in Linux) > ?SPE (Stani) Could not get it to run in MS Windows (???!) > > PyScripter,PyPeand drPython all had nice features but interaction > quirks. > > My second question is based on a belief that I should move to a more > general IDE or editor to get ?LINUX compatibility and the ability to > also edit R and LaTex programs. ?I have explored these > ? ?Vim > ? ?Cream/Vim > ? ?UliPad > ? ?SciTe > ? ?Jext > ? ?Editra > ? ?Komodo Editor > But none are close to being as interactive friendly as IDLE. > > I might look at > ? Eclypse with pydev > ? Jedit > And these commercial/professional IDEs > ? Wing > ? Komodo IDE > ? Zeus > > But before doing so I wanted to know form experienced users: > > ** How hard is it to configure any of the general editors/IDEs to run > a Python shell using a hotkey (such as IDLEs F5) and whether any can > be set up for full interactivity. > > I understand and appreciate ?the difficulties to get full IDLE-like > interactivity, but what comes closest? I know I'm a little late on this (I only hopped in to check on some other older threads), but if you are careful, PyPE can allow you to run your script in an interactive shell. In particular, if you select the content of the code you would like to run (changing any if __name__ == '__main__' into '__console__' references, then use File -> "Run Selected Code", it will select a Python Shell (if one exists) or create a new one, and run your code in that shell. If you are willing to muck about in the source code, it shouldn't be too difficult to add a '-i' to the "Run Current File" command (which I may add as an option in the next version of PyPE). - Josiah From mail at timgolden.me.uk Wed Sep 3 06:16:12 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 03 Sep 2008 11:16:12 +0100 Subject: sys.stdin on windows In-Reply-To: References: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> Message-ID: <48BE63EC.1070004@timgolden.me.uk> Gabriel Genellina wrote: > En Wed, 03 Sep 2008 06:16:03 -0300, zugnush at gmail.com > escribi?: > >> I often grep particular patterns out of large logfiles and then >> pipeline the output to sort and uniq -c >> I thought today to knock up a script to do the counting in a python >> dict. >> >> This seems work in linux >> >> $ cat count.py >> #!/usr/bin/env python >> import sys >> from collections import defaultdict >> accumulator=defaultdict(int) >> for line in sys.stdin.readlines(): >> accumulator[line.strip()]+=1 >> print "contents,count" >> for key in accumulator.keys(): >> print key,",",accumulator[key] >> >> $ cat test | ./count.py >> contents,count >> , 1 >> 23 , 1 >> 1 , 1 >> 3 , 2 >> 2 , 2 >> 5 , 3 >> >> When I try to run the same thing on windows I get >> IOError: [Error 9] Bad file descriptor >> >> How can I make this more windows friendly? > > Explicitely invoking the interpreter worked for me. That is, these two > commands worked fine: > > type test.txt | python count.py > python count.py < test.txt > > But I cannot explain *why* it doesn't work the other way. > Known bug in NT-based file association. I'll try to find an online reference, but that's basically what it comes to. I think you can faff-about with batch files to achieve the effect, but I can't quite remember. http://support.microsoft.com/kb/321788 TJG From deets at nospam.web.de Thu Sep 4 11:55:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Sep 2008 17:55:49 +0200 Subject: Function decorators In-Reply-To: References: Message-ID: <6iaeo5Fp8mpdU1@mid.uni-berlin.de> Aigars Aigars schrieb: > Good day all, > > I am learning Python and came up to decorators. > > The question is: Why does function FoodList return value None? > > The code in attachment. Because the __call__ in Logger doesn't return the value of self.func. Diez From mr.spoon21 at gmail.com Sun Sep 28 15:08:08 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 28 Sep 2008 21:08:08 +0200 Subject: Music knowledge representation In-Reply-To: References: Message-ID: <8f67b6f80809281208m5c633ec1k410c07ec2bed8338@mail.gmail.com> On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady wrote: > Here is a link to someone else's design they asked about on the > newsgroup a couple weeks ago. > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc :D It's always me. I think my question is more specific. I need some sort of cycle. So if I have a list with A, B, C, D, when I iter over it I need to get an A after the D. From gherron at islandtraining.com Fri Sep 19 17:02:56 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 19 Sep 2008 14:02:56 -0700 Subject: Launching a subprocess without waiting around for the result? In-Reply-To: References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> <87od2l2am7.fsf@benfinney.id.au> Message-ID: <48D41380.5010906@islandtraining.com> Almar Klein wrote: > > Ah, no, that's a different thing. If the parent exits, the child will > also be killed I believe. > > > Not if it's stuck in some endless loop... > > If you want to spawn a process and have it live on independent of the > parent, you want to make the child process a "daemon", detatching > itself from the parent's environment. I don't recall how that's done > immediately, but those are the terms to search for. > > > I'm curious how this can be done, does anyone know this? I just dove into this several day ago for a small project. On Linux it's easy -- it involves a couple of forks and other system calls. Google for daemonize.py. On Windows, a bit of searching seems to find a consensus that the way to do something similar is as a Window's service. I'm just now looking into how to register and start a service, and how to stop and remove it later. Google finds lots of information on this -- perhaps I'll post my result when I've pulled it all together. Gary Herron From Astley.lejasper at gmail.com Thu Sep 4 09:17:03 2008 From: Astley.lejasper at gmail.com (Astley Le Jasper) Date: Thu, 4 Sep 2008 06:17:03 -0700 (PDT) Subject: Xpath for HTML processing Message-ID: Can anyone suggest something inthat can process an XPath like the following: "/html/body/table[2]/tbody/tr/td[5]/table/tbody/tr[3]/td/table[3]/ tbody/tr[5]/td" Cheers From deets at nospam.web.de Wed Sep 10 17:04:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 23:04:45 +0200 Subject: XML-RPC "filter" In-Reply-To: <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> <6inkkiFrbptbU1@mid.uni-berlin.de> <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> Message-ID: <6iqr3dF3msoU1@mid.uni-berlin.de> luigi.paioro at gmail.com schrieb: > On 9 Set, 17:55, "Diez B. Roggisch" wrote: >> I would go for a slightly different approach: make your server have a >> dispatch-method that delegates the calls to the underlying actual >> implementation. But *before* that happens, extract the information as >> above, and either >> >> - prepend it to the argument list >> >> - stuff it into threadlocal variables, and only access these if needed in >> your implementation. >> >> Diez > > Are you suggesting me to overwrite the _dispatch(self, method, params) > method of SimpleXMLRPCDispatcher? I thought to this possibility, but > it only accepts "method" and "params" as arguments, so, as far as I > know, I have no way to get the user and host address to append. > > Perhaps I've misunderstood your suggestion... in that case can you > post a short example? Ah, darn. Yes, you are right of course, the information itself is not available, as you don't have access to the request. I gotta ponder this a bit more. Diez From george.sakkis at gmail.com Sat Sep 27 09:23:33 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 27 Sep 2008 06:23:33 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: On Sep 27, 1:44 am, "Dmitry S. Makovey" wrote: > George Sakkis wrote: > > Although this works, the second argument to ProxyMethod shouldn't be > > necessary, it's semantically redundant; ideally you would like to > > write it as "bmethod = ProxyMethod('b')". > > since I'm already on exploratory trail (what about that rug being pulled > from under....?) With my code I can do really dirty tricks like this (not > necessary that I'm going to): > > class B_base: > def bmethod(self): > print 'B_base' > > class B(B_base): > def bmethod(self): > print 'B' > > class A: > bmethod=ProxyMethod('b',B_base.bmethod) Yes, that's indeed dirty; don't do it :) > > As before, I don't think > > that's doable without metaclasses (or worse, stack frame hacking). > > Below is the update of my original recipe; interestingly, it's > > (slightly) simpler than before: > > Out of curiosity (and trying to understand): why do you insist on > dictionaries with strings contents ( {'bmethod' : 'b1' } ) rather than > something more explicit ? Again, I can see that your code is working and I > can even understand what it's doing, just trying to explore alternatives :) > > I guess my bias is towards more explicit declarations thus > > bmethod=ProxyMethod('b',B.bmethod) > > looks more attractive to me, but I stand to be corrected/educated why is > that not the right thing to do? I see where you're coming from and I also prefer explicit reflection mechanisms instead of strings (e.g. avoid eval/exec as much as possible). As I mentioned, the second argument to ProxyMethod is (for all sane purposes) redundant, so if you could implement it in a way that "bmethod = ProxyMethod('b')" worked, I would be all for it, but AFAIK it's not possible without a metaclass. A dict with string keys and values to be consumed by a metaclass is perhaps the simplest thing that could possibly work. It contains all the relevant information for hooking the proxy to the delegate methods and nothing more; zero boilerplate code overhead. Also note that it's not that big of a difference; you have to provide the attribute name as a string anyway. > Another thing that turns me away from string dictionaries is that those are > the ones causing me more trouble hunting down typos. Maybe it's just "my > thing" so I'm not going to insist on it. I'm open to arguments against that > theory. >From my experience, I am equally prone to typos for both strings and regular attributes; I agree though that the traceback information is often more helpful when you mistype an attribute. > One argument I can bring in defence of more explicit declarations is IDE > parsing when autocompletion for B.bme... pops up (suggesting bmethod and > bmethod2) and with 'b':'bmethod' it never happens. I don't rely on autocompleting IDEs, at least in dynamic languages, so it's not much of an issue for me but yes, it's another small argument against strings. George From sayananbig at gmail.com Tue Sep 23 14:41:11 2008 From: sayananbig at gmail.com (Sayanan Sivaraman) Date: Tue, 23 Sep 2008 11:41:11 -0700 (PDT) Subject: python timers and COM/directshow References: Message-ID: <5b01cc61-60bf-4a6c-b88b-932cf2fc8e0a@s20g2000prd.googlegroups.com> You're right. Let me be more specific. Firstly, the reason I included c++ code is because I'm using Microsoft COM, which is natively in c++, and in fact, to access them through Python I use the comtypes module [import comtypes] and then GetModule('quartz.dll') to access the dll's. I am using the gtk GUI widgets. I have a gtk.Hscale scrollbar which I would like to be a trackbar for the video playback. To coordinate this in Python, much like in c++, I would like to have a timer thread synchronizing the scrollbar update. ie: def scrollbar_callback(args): media_control.CurrentPosition= scrollbar.get_value() def timer_callback(args): #code to update the scrollbar based on video position, something like scrollbar.set_value(media_control.CurrentPosition) >>>*And, I would like to be able to kill, run the timer based on whether the video is playing or paused, ie def player(args): media_control.Run() #plays video timer.run() def pauser(args): media_control.Pause() timer.kill Any tips? -sayanan From prologic at shortcircuit.net.au Wed Sep 10 23:08:04 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 13:08:04 +1000 Subject: Alternatives to traditional RDBMS In-Reply-To: <3ee3f834-b314-4a75-a85c-6a13bb118b09@l33g2000pri.googlegroups.com> References: <6iq90jFdeiU1@mid.uni-berlin.de> <3ee3f834-b314-4a75-a85c-6a13bb118b09@l33g2000pri.googlegroups.com> Message-ID: On Thu, Sep 11, 2008 at 12:06 PM, alex23 wrote: > "James Mills" wrote: >> This is an ORM. They are >> off-topic for this thread :) > > Tsk, such an unfounded bias... To be honest. I have since now tried both ZODB and Durus and both seem really nice. I still do think that ZODB could do with a cleanup though. > I've had a lot of success using sqlalchemy + Elixir together ;) We are talking "Alternatives to RDBs" :) ok ? cheers James -- -- -- "Problems are solved by method" From ewertman at gmail.com Sat Sep 27 14:32:58 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 27 Sep 2008 14:32:58 -0400 Subject: python for *nix system admins In-Reply-To: <170543c70809271123j1334d12ardd09c25ce479978f@mail.gmail.com> References: <1222520796.630579@athprx04> <170543c70809271123j1334d12ardd09c25ce479978f@mail.gmail.com> Message-ID: <92da89760809271132r769411e6t2771b625bbeb04f2@mail.gmail.com> I've been growing a library of my own functions, that use the names of unix commands. They are just conveniences, of course, but I'd suggest the same for sysadmins, it's handy. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 14 03:15:31 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Sep 2008 07:15:31 GMT Subject: How does python call OS? References: Message-ID: <00dcb436$0$20302$c3e8da3@news.astraweb.com> On Sat, 13 Sep 2008 23:51:39 -0700, Siegfried Heintze wrote: > I see the next sub-chapter on wxWindows for python and the previous > sub-chapter on TK. This is looking a lot like other scripting languages > (such as perl and groovy and even java). Can python call anything > directly or does someone have to write a DLL in C/C++ that calls the > function first? Thanks! I'm not sure I understand your question correctly, but Python can call external programs in a number of ways. I believe the "best" way to do so is with the subprocess module. -- Steven From adykes at panix.com Sat Sep 13 13:41:56 2008 From: adykes at panix.com (Al Dykes) Date: 13 Sep 2008 13:41:56 -0400 Subject: Code example that will make a Skype connection? References: <48cbdd9d$0$1895$426a34cc@news.free.fr> Message-ID: In article <48cbdd9d$0$1895$426a34cc at news.free.fr>, nntpman68 wrote: >Hi, > >Just some thoughts / now answer :-( > >The solution might vary on the platform / OS. > >Would it be acceptable for you to >control for example firefox from python and firefox would control skype >via the skype plugin. (should exist for multiple platforms) > >Do you search a native python solution or would you accept, that some >C-code had to be compiled. > Building a C module is fine as long as I don't have to debug it. I know that FF can do Skype so, I guess, if I write a Python app that runs in a browser, I've solved my problem. I'm about to learn Python, so I haven't given any thought to how to do that. Thanks for the response. What would be picked for a portable Firebox-based app? -- Al Dykes News is something someone wants to suppress, everything else is advertising. - Lord Northcliffe, publisher of the Daily Mail From cipherzero at gmail.com Sat Sep 6 21:15:33 2008 From: cipherzero at gmail.com (cipher) Date: Sat, 6 Sep 2008 18:15:33 -0700 (PDT) Subject: Setter Propertys' mro? Message-ID: <52052ab0-475b-4b53-9386-6cb3d4663b03@w39g2000prb.googlegroups.com> Whats the mro (method resolution order) of a setter property (__set__ on a descriptor). i seem to be experiencing some weird issue with them. for example >>> class test: ... def _test(self): ... return 4 ... def _stest(self):pass # dont change value ... def _dtest(self,value):pass ... p=property(_test,_stest,_dtest) >>> t=test() >>> t.p 4 >>> t.p=5 >>> t.p 5 Why is that being 'overridden' ( by that i mean that it is storing that value in t's __dict__) >>> t.__dict__ {'t': 5} why DIDNT the setter get hit? however, if i specify the metaclass in the class definition it works just fine... class test: __metaclass__=type def _test(self): return 4 def _stest(self,value):pass # dont change value def _dtest(self):pass p=property(_test,_stest,_dtest) >>> t=test() >>> t.p 4 >>> t.p=5 >>> t.p 4 why do i have to set the __metaclass__ ? this seems like a bug? i know that i probably shouldn't worry about this because if a programmer does want to set my value and it causes an error, thats his problem.... but this bothers me. whats the point of the __set__ method then? Thanks in advanced. -- Cipher From kwmsmith at gmail.com Mon Sep 8 13:10:41 2008 From: kwmsmith at gmail.com (Kurt Smith) Date: Mon, 8 Sep 2008 12:10:41 -0500 Subject: Read and write binary data In-Reply-To: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> References: <353a3ba8-8d9d-4f8d-800d-68618e9f6614@c58g2000hsc.googlegroups.com> Message-ID: On Sun, Sep 7, 2008 at 5:41 PM, Mars creature wrote: > Hi guys, > I am new to Python, and thinking about migrating to it from matlab > as it is a really cool language. Right now, I am trying to figure out If you're trying to migrate from matlab to python I'd take a look at numpy: http://numpy.scipy.org/ And scipy which is built on top of numpy: http://www.scipy.org/ There is a plotting/numerical computation package known as matplotlib that does its best to parallel matlab commands: http://matplotlib.sourceforge.net/ There is support for reading and writing binary data, even fortran records. And last but not least, you can always take a look at the scipy and numpy mailing lists. Good luck, Kurt > how to control read and write binary data, like > 'formatted','stream','big-endian','little-edian' etc.. as in fortran. > I googled, but can not find a clear answer. Anyone has clue where can > I learn it? Thanks!! > Jinbo > -- > http://mail.python.org/mailman/listinfo/python-list > From gregturn at mindspring.com Mon Sep 29 08:26:47 2008 From: gregturn at mindspring.com (Goldfish) Date: Mon, 29 Sep 2008 05:26:47 -0700 (PDT) Subject: Spring Python 0.7.0 is released References: <74ird4hidmldkq9bao6sk5grdmpp9vq62e@4ax.com> Message-ID: <53691d34-53f7-4338-9073-68aa15649021@z66g2000hsc.googlegroups.com> Key Features The following features have been implemented: * Inversion Of Control - The idea is to decouple two classes at the interface level. This lets you build many reusable parts in your software, and your whole application becomes more pluggable. You can use either the XmlApplicationContext or the DecoratorBasedApplicationContext. * Aspect-oriented Programming - Spring Python provides great ways to wrap advice around objects. It is utilized for remoting. Another use is for debug tracers and performance tracing. * DatabaseTemplate - Reading from the database requires a monotonous cycle of opening cursors, reading rows, and closing cursors, along with exception handlers. With this template class, all you need is the SQL query and row-handling function. Spring Python does the rest. * Database Transactions - Wrapping multiple database calls with transactions can make your code hard to read. This module provides multiple ways to define transactions without making things complicated. * Security - Plugin security interceptors to lock down access to your methods, utilizing both authentication and domain authorization. * Remoting - It is easy to convert your local application into a distributed one. If you have already built your client and server pieces using the IoC container, then going from local to distributed is just a configuration change. * Samples - to help demonstrate various features of Spring Python, some sample applications have been created: o PetClinic - Everybody's favorite Spring sample application has been rebuilt from the ground up using various web containers including: CherryPy. Go check it out for an example of how to use this framework. o Spring Wiki - Wikis are powerful ways to store and manage content, so we created a simple one as a demo! o Spring Bot - Use Spring Python to build a tiny bot to manage the IRC channel of your open source project. For more information, please visit the website at http://springpython.webfactional.com, where you will also find more detailed documentation at http://springpython.webfactional.com/reference/html/. Greg Turnquist From bthayre at physics.ucsd.edu Mon Sep 22 18:44:41 2008 From: bthayre at physics.ucsd.edu (Robocop) Date: Mon, 22 Sep 2008 15:44:41 -0700 (PDT) Subject: Python based barcode readers Message-ID: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> Does anyone know of any python based barcode readers? I'm looking for something (commercial or open source) that will use some OCR algorithm to read barcodes from an image or ps/pdf file, and ideally will be something along the lines of a callable python script. I have some pretty simple needs, i'm only trying to read code 93 barcodes, so i don't need it to be able to identify multiple symbologies or anything. Any suggestions would be greatly appreciated. Thanks! From grante at visi.com Wed Sep 3 10:15:05 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Sep 2008 09:15:05 -0500 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <87hc8xor9g.fsf@benfinney.id.au> Message-ID: On 2008-09-03, Ben Finney wrote: > Ben Finney writes: > >> I don't see any good reason (other than your familiarity with the D >> language) to use underscores for this purpose, and much more reason >> (readability, consistency, fewer arbitrary differences in syntax, >> perhaps simpler implementation) to use whitespace just as with string >> literals. > > Another reason in support of spaces (rather than underscores) to > separate digit groups: it's the only separator that follows the SI > standard for representing numbers: > > ??? for numbers with many digits the digits may be divided into > groups of three by a thin space, in order to facilitate reading. > Neither dots nor commas are inserted in the spaces between groups > of three. But my keyboard doesn't _have_ a thin-space key! -- Grant Edwards grante Yow! One FISHWICH coming at up!! visi.com From catalinfest at gmail.com Tue Sep 16 11:13:48 2008 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Tue, 16 Sep 2008 08:13:48 -0700 (PDT) Subject: backup with python Message-ID: <11a3fca0-ded7-47c3-aeff-bb08acb1eb20@d1g2000hsg.googlegroups.com> Hi ! I need some help to create backup with python. I want to backup some bases on DVD - RW . How i make this with python ? I want to use python because the program is write on python . Thank you ! From circularfunc at gmail.com Tue Sep 2 21:14:49 2008 From: circularfunc at gmail.com (process) Date: Tue, 2 Sep 2008 18:14:49 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> Message-ID: <8b3857ec-e629-44a3-98f2-8fe509df7b75@f36g2000hsa.googlegroups.com> is this faster btw? I guess big doesn't help, it's only retrieved once anyway? But is rows retrieved in every loop? the python interpreter aint too smart? def getPixels(fileName): im = PIL.Image.open(fileName) colors = [] r, c = im.size big = range(0, c) rows = range(0, r) for y in big: row = [] for x in rows: color = im.getpixel((x,y)) row.append(color) colors.append(row) return numpy.array(colors) From clp at rebertia.com Sat Sep 27 18:13:08 2008 From: clp at rebertia.com (Chris Rebert) Date: Sat, 27 Sep 2008 15:13:08 -0700 Subject: check if file is MS Word or PDF file In-Reply-To: References: Message-ID: <47c890dc0809271513p6ea2d52ah4f5194ffffc63422@mail.gmail.com> On Sat, Sep 27, 2008 at 2:43 PM, A. Joseph wrote: > What should I look for in a file to determine whether or not it is a > MS Word file or an Excel file or a PDF file, etc., etc.? including Zip > files > > I don`t want to check for file extension. > os.path.splitext('Filename.jpg') will produce a tuple of filename and > extension, but some file don`t even have extension and can still be read by > MS Word or NotePad. i want to be 100% sure of the file. Well, if you're on unix, you could run the 'file' command and check its output using the 'subprocess' module, but it sounds like you're on Windows... Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > -- > http://mail.python.org/mailman/listinfo/python-list > From castironpi at gmail.com Wed Sep 24 23:16:49 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 20:16:49 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: On Sep 24, 9:49?pm, Asun Friere wrote: > On Sep 25, 11:57 am, "Aaron \"Castironpi\" Brady" > > wrote: > > On Sep 24, 8:40 pm, Asun Friere wrote: > > > ... I think > > > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding > > > all variables for placeholders in the tuple, is better. It's certainly > > > more readible. > > > It's a different answer if you have 'things is/are'. ?'%d thing%s %s'% > > ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ). ?Or excluding > > prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's > > are' if i!= 1 else ' is' ). > > Forgive me for being dull, my caffeine levels have not yet optimal, > but I don't follow. ?Both the solutions you propose do put all the > placeholder variables in the tuple. ?Or are you saying it no longer > remains readible? > > BTW you repeated my mistake with the first scraplet of code. Ah yes. Maybe the order of precedence can undergo a change in the future. ... Though talk about backwards incompatible. They were two options if you have a verb with your noun, which would need a conditional too. From prologic at shortcircuit.net.au Thu Sep 18 20:36:23 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 19 Sep 2008 10:36:23 +1000 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: On Thu, Sep 18, 2008 at 9:02 PM, James Nicolson wrote: > Perhaps it is better to keep descriptions short and store longer > descriptions elsewhere, but there are many programs that have long > descriptions, for example try: ls --help (at least on my machine a lot > of these descriptions are quite long). The longer (program) description is generally provided by the Usage help string. This (in my tools) is generally a long-ish docstring describing the tool, and it's usage. cheers James -- -- -- "Problems are solved by method" From manuhack at gmail.com Fri Sep 5 04:28:44 2008 From: manuhack at gmail.com (Manu Hack) Date: Fri, 5 Sep 2008 04:28:44 -0400 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> Message-ID: <50af02ed0809050128l3a0ffbc8l17be4aa62224d559@mail.gmail.com> On Thu, Sep 4, 2008 at 4:25 PM, castironpi wrote: > On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >> David C. Ullrich: >> >> > At least in mathematics, the sum of the elements of >> > the empty set _is_ 0, while the maximum element of the >> > empty set is undefined. >> >> What do you think about my idea of adding that 'default' argument to >> the max()/min() functions? >> >> Bye, >> bearophile > > For max and min, why can't you just add your argument to the set > itself? > > The reason max([]) is undefined is that max( S ) is in S. It makes sense. >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. It doesn't make sense to me. What do you set x to? From sjmachin at lexicon.net Sat Sep 6 18:42:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 6 Sep 2008 15:42:37 -0700 (PDT) Subject: Cathing several potential errors? References: Message-ID: On Sep 7, 8:13?am, cnb wrote: > if i do > try: > ? ? something > except TypeError, IndexError: > ? ? pass > > only the first error will get caught. I dont want to use Exception and > catch all errors, but just 2. how can i do that? The syntax for what you can have between "except" and ":" is: [expression ["," target]] 'target' is an optional name to be bound to the actual exception object that is raised. If you want to catch multiple kinds of exception, 'expression' needs to be a tuple. See http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 and http://docs.python.org/ref/try.html Cheers, John From castironpi at gmail.com Mon Sep 22 13:32:50 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 10:32:50 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <48d7720d$0$12866$426a34cc@news.free.fr> <48d78c3c$0$6998$426a74cc@news.free.fr> Message-ID: <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> On Sep 22, 8:45?am, "Tim Rowe" wrote: > 2008/9/22 Bruno Desthuilliers : > > >> Sounds to me like a functor, aka a function object: > >>http://en.wikipedia.org/wiki/Function_object > > > Ok, then the simple solution is to implement a callable type (__call__ > > method), possibly with appropriate support for the descriptor protocol if > > it's meant to be usable as a method. > > Yes -- and instantiate the thing and keep the state in the instance, > rather than keeping the state in the class, so that it's possible to > safely have more than one of them if a later design change calls for > it (probably what led people off onto the sidetrack of thinking a > singleton was called for). ?That's the classic way of implementing a > "class [to be] used as a function". > > -- > Tim Rowe I think you are either looking for a class that has a generator, or a generator that has a reference to itself. From mccredie at gmail.com Mon Sep 22 14:14:52 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 22 Sep 2008 11:14:52 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <37a437fd-dfd8-4908-8027-dbf53199567b@w1g2000prk.googlegroups.com> On Sep 21, 3:39?pm, Steven D'Aprano wrote: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? > > -- > Steven It actually sounds like you are doing something similar to the monostate pattern. In Java the monostate pattern is usually implemented by creating a class that only has static functions and variables. You _can_ instantiate it, but every instance will share the same state. In that way it is very similar to the Singleton pattern (http://en.wikipedia.org/wiki/Singleton_pattern). In Python I haven't found a need for monostate, since you can override __new__ and return exactly the same instance. However, you you wanted to be able to inherit a monostate object and share some of the state between the class and subclass it might still be useful. Perhaps if you post some example code? Matt From fredrik at pythonware.com Sat Sep 13 16:14:55 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 22:14:55 +0200 Subject: code style and readability [was: Re: Checking the boolean value of a collection] In-Reply-To: References: <48cbf09c$0$25189$426a74cc@news.free.fr> <48cbf432$0$27507$426a34cc@news.free.fr> Message-ID: Larry Bates wrote: > I also have a personal dislike for early returns because I've found it > makes it harder insert execution trace logging into the code. in a language that makes it trivial to wrap arbitrary callables in tracing wrappers? From stef.mientki at gmail.com Wed Sep 10 14:34:13 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Wed, 10 Sep 2008 20:34:13 +0200 Subject: wxpython ms-dos black window popping up in background In-Reply-To: References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> Message-ID: <48C81325.7090506@gmail.com> Mike Driscoll wrote: > On Sep 10, 6:48 am, James A. Donald wrote: > >> On Tue, 9 Sep 2008 14:35:13 -0700 (PDT), icarus >> wrote: >> >> >>> Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw >>> That did it. >>> >>> one more question... >>> >>> how do I create a pythonw standalone executable that works on w32, >>> linux, mac, etc..? >>> >> I have noticed that when applications are written in Python with the >> GUI created by PyGTK, it seems that to install the application on each >> slightly different version of unix is a fairly major task - although >> the creators of PyGTK proudly say that the code will run anywhere, it >> definitely will not install anywhere - the code will only run on a >> slightly different system after a massive and major rewrite of the >> install for that target system. >> >> Horrible installs are a chronic problem GUI programs driven by >> interpreted languages Installing visual basic programs that worked on >> one Windows machine to work on a very slightly different windows >> machine was also a nightmare. >> >> I have not attempted to create installable wxPython windows, but >> generally, "run anywhere" will bite you. Still looking for a good >> solution to "run anywhere". >> >> -- >> ---------------------- >> We have the right to defend ourselves and our property, because >> of the kind of animals that we are. True law derives from this >> right, not from the arbitrary power of the omnipotent state. >> >> http://www.jim.com/ James A. Donald >> > > I haven't had much trouble getting wxPython applications to run in > Windows XP and Ubuntu Hardy Heron. Of course, my GUIs aren't extremely > complex, but I did make use of Hammond's PyWin32 package and had to > wrap those in Platform aware conditional statements. Plus wx was > pretty easy to install in Ubuntu, so that was cool. > > same with me, wxPython, packed with py2exe + ino setup, runs out of the box on XP, Vista, Ubuntu without any problem. cheers, Stef > I can't really comment on other toolkits though. > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From anand.nalya at gmail.com Tue Sep 2 05:45:47 2008 From: anand.nalya at gmail.com (anand nalya) Date: Tue, 2 Sep 2008 15:15:47 +0530 Subject: python glibc error Message-ID: <53bb4b2e0809020245t218662e9m5f50e4c5536d37fb@mail.gmail.com> I'm getting the following errors while trying to run a python script: *** glibc detected *** python: free(): invalid next size (normal): 0x000000000d2da210 *** *** glibc detected *** python: malloc(): memory corruption: 0x000000001b81da60 *** Is this a bug in my script or python or gllbc? Relevent version numbers are: #uname -a Linux myserver 2.6.18-92.1.10.el5 #1 SMP Tue Aug 5 07:42:41 EDT 2008 x86_64 x86_64 x86_64 GNU/Linux # python -V Python 2.4.3 /lib/libc.so.6 | head -1 GNU C Library stable release version 2.5, by Roland McGrath et al. The same script is running fine of fedora 4: On Fedora: uname -a Linux onyomo.com 2.6.11-1.1369_FC4smp #1 SMP Thu Jun 2 23:08:39 EDT 2005 i686 i686 i386 GNU/Linux python -V Python 2.4.1 /lib/libc.so.6 | head -1 GNU C Library development release version 2.3.5, by Roland McGrath et al. Regards, Anand -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Tue Sep 30 16:07:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 17:07:46 -0300 Subject: rlcompleter and wxPython, problems ... References: <48E0045A.3020402@gmail.com> <48E2789F.7090207@gmail.com> Message-ID: En Tue, 30 Sep 2008 16:06:07 -0300, Stef Mientki escribi?: > Gabriel Genellina wrote: >> En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki >> escribi?: >> >>> I'm trying to implement autocompletion into my editor. >>> But I find some weird behavior, >>> or at least I don't have the faintest idea why this behavior occures, >>> and even more important how to solve it >>> In the example below I try to autocomplete " wx.s" , which in my >>> humble opinion should at least produce "wx.stc" (and some others ). >> >> wx is a package. Modules within the package are not, by default, >> attributes of the package - unless they're imported in __init__.py or >> your code imports them. >> So the autocompleter is doing the right thing > in what perspective ? > the autocompleter is only meant to assist the program writer ;-) It's hard to write an autocompleter that does the right thing in all cases :) For a package, you have several sources for possibly valid attributes: - its dir() (that is, the package object's own attributes) - the __all__ attribute, when it exists - the list of modules inside the package directory or directories (given by its __path__ attribute) Sometimes __init__.py is empty - and enumerating the modules inside the directory is the right thing to do. Sometimes the author explicitely imports things in __init__.py, things that comprise the public interfase to the package. In that case I'd not like to see "private" modules appearing in the list. Combine with __all__, which might be defined or not. Mix all those, choose your own autocomplete algorithm, and see what happens... >> - wx.stc does not exist until it is explicitely imported. > I guess I've to study the package. > For the moment I'll implement a user editable list of additions. > > But with your remarks I tried __all__ > And now I wonder why rlcompleter is not simply using "wx.__all__", > it than does gets all the items ? __all__ isn't always defined. It's only used when you do "from xxx import *" AFAIK. -- Gabriel Genellina From mail at timgolden.me.uk Mon Sep 15 11:12:56 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 15 Sep 2008 16:12:56 +0100 Subject: Representation of python code ? In-Reply-To: <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> Message-ID: <48CE7B78.4060209@timgolden.me.uk> showellshowell at gmail.com wrote: > On Sep 15, 4:38 am, Maric Michaud wrote: >> Le Sunday 14 September 2008 15:44:03 Barak, Ron, vous avez ?crit : >> >>> Hi Guys, >>> Is there a script/application, which gets as input python code, and >>> produces a (graphic) representation of the inter-relationships between its >>> classes/functions ? Bye, > > If you can't find anything that's already packaged up and polished, > one possibility is to use the parser and/or compiler.ast modules in > Python to analyze your code, then produce something that graphviz can > consume. On that note, perhaps have a look at PySmell [1] which Orestis Lightning-spoke about at PyconUK over the weekend. It's designed as an autocompletion tool, but he mentioned that the structure it generates could well be used for other purposes. TJG [1] http://orestis.gr/blog/2008/08/31/announcing-pysmell/ From rhamph at gmail.com Mon Sep 22 03:37:52 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 22 Sep 2008 00:37:52 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <3c7157f9-ce47-4f9a-b5cd-2227098a790d@w39g2000prb.googlegroups.com> On Sep 21, 4:39?pm, Steven D'Aprano wrote: > I have a class which is not intended to be instantiated. Instead of using > the class to creating an instance and then operate on it, I use the class > directly, with classmethods. Essentially, the class is used as a function > that keeps state from one call to the next. > > The problem is that I don't know what to call such a thing! "Abstract > class" isn't right, because that implies that you should subclass the > class and then instantiate the subclasses. > > What do you call such a class? If defining it as a normal class, it is a namespace. Just a way to cluster multiple globals into a single global. The borg pattern does the same thing, but with a 12 page treatise on why it shouldn't do exactly what it's doing. If using a factory you should probably be using an instance; the fact that your instance is a class is a relatively minor implementation detail. Indeed, the only reason to have a class is to have your methods bound when looked up. You might want a metaclass to cripple it, preventing subclassing and whatnot. *shrug*. From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 18:45:44 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 22:45:44 GMT Subject: lacking follow-through References: Message-ID: <00d453eb$0$20306$c3e8da3@news.astraweb.com> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > Hi, > > This is the strangest post I've seen > since I've joined this list (only > recently). What the ? Oh don't mind castironpi, many people think he's an IRC bot with some experimental AI features that escaped onto Usenet *grins*. If you think that post of his was strange, you haven't seen anything yet. Many people have kill-filed him, and never even see his posts. A word to castironpi: you just suggested you will pester the list to get a response. It's behaviour like that which gets you kill-filed. If you would spend one tenth of the effort that you spend on understand Python on understanding human psychology, you will probably get on with others much better and find fewer people claiming you're a bot. Even if you yourself don't understand how others behave and expect you to behave, think of it as an intellectual puzzle: how can I fool the strange hairless apes into accepting me into their herd? -- Steven From vivainio at gmail.com Sat Sep 6 16:00:14 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Sat, 06 Sep 2008 20:00:14 GMT Subject: How to run PyOS_InputHook from python code (i.e. yield to event loops) Message-ID: <87wshpcaek.fsf@gmail.com> Background: PyOS_InputHook is something that gets run when python is doing raw_input. TkInter and friends use it to run their event loops, so that their events are handled while python is doing raw_input. What I'd like to do is run the same function without having to do raw_input. I.e. I'd like to run whatever event loop is available, without incorporating any gui-specific code (PyOS_InputHook seems like a nifty way to accomplish this). My actual use case is to keep a tkinter application responsive while launching a background process (and waiting for it to complete!). My eventual code would be something like: launch_process_in_thread('bzr pull') while not is_done: pyos_inputhook() time.sleep(0.1) print "Done!" From fredrik at pythonware.com Thu Sep 4 16:51:34 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 22:51:34 +0200 Subject: Not fully understanding the role of Queue.task_done() In-Reply-To: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> Message-ID: Martin DeMello wrote: > I'm writing a cluster monitor, that collects information from a set of > machines and logs it to a database > > In the interests of not hammering the db unnecessarily, I'm > considering the following > 1. A series of independent "monitor" threads that collect information > over TCP from the cluster of machines, and write it to a queue > 2. A "logger" thread that empties the queue every second or so and > inserts the collected information to the db via a single insert > statement why are you using a queue for this case, btw? why not just use a plain list L = [] lock = threading.Lock() and add stuff using append in the monitor threads with lock: L.append(item) and regularily reset the list in the logger thread with lock: data = L[:] L[:] = [] # clear the list for item in data: ... insert into database ... (list append and assignments to global variables are atomic in CPython, so you can eliminate the lock by being a bit clever, but that's probably better left for a non-premature optimization pass). From hrishys at yahoo.co.uk Tue Sep 23 11:34:25 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Tue, 23 Sep 2008 15:34:25 +0000 (GMT) Subject: Linq to Python In-Reply-To: <6jsevmF4uaq4U1@mid.uni-berlin.de> Message-ID: <316028.12070.qm@web27403.mail.ukl.yahoo.com> Hi Thanks for those links however LINQ seems to be much more then ORM tool it can for example join an XML file with a relational datasource or create a XSD regards Hrishy --- On Tue, 23/9/08, Diez B. Roggisch wrote: > From: Diez B. Roggisch > Subject: Re: Linq to Python > To: python-list at python.org > Date: Tuesday, 23 September, 2008, 4:06 PM > hrishy wrote: > > > Hi > > > > Will LINQ be ported to Python ? > > Take a look at SQLAlchemy or SQLObject for python-based > ORM/SQL-abstractions. > > Apart from that, python is already heavily based on > concepts like iterators, > filtering. Take a look at itertools. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From tino at wildenhain.de Mon Sep 15 07:29:41 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 15 Sep 2008 13:29:41 +0200 Subject: how to protect the source In-Reply-To: References: Message-ID: <48CE4725.7000502@wildenhain.de> Hi, Jo?o Abrantes wrote: > Hello Everyone. > > > I am building a client in python that will connect himself to a mysql > server with a certain username and password. I will compile this client > and turn him into a .exe . The thing is that I know that is possible to > get the source of the code back from an .exe and I don't want anyone to > know which username and password are they using because I don't want > them to access to the mysql server without my client. Do you have any > ideas of what can i do? Thanks! Don't put that into the source. Use whatever your database supports for authorisation with a config file or ssl certificate. You can not hide the credentials when you need to give them out of your hands. Better protect the database objects with permissions on tables, views and stored procedures. Everything your program can do everybody having your program can do. HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From almar.klein at gmail.com Tue Sep 16 03:37:22 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 16 Sep 2008 09:37:22 +0200 Subject: Python IDEs with F5 or hotkey shell interaction In-Reply-To: <48CE9428.7090406@gmail.com> References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> <48CE9428.7090406@gmail.com> Message-ID: > > Any change we could see some code already ? > I'm working on something similar, > bored of the bugs in my current IDE. > Here are my first notes: > http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_debug.html > It should become a very-simple-very-high-level IDE, > like Matlab, but then better ;-) Well, its still in development, but I can send you a copy of the current status. I see that you did a lot of work on debugging. I haven't done any of that yet; I've been focusing mainly on getting an interactive environment with a shell that feels like the normal python shell, but with code completion. Maybe we can help each-other out a bit :) Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Mon Sep 8 05:22:03 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Sep 2008 02:22:03 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <1e1e480e-6ebc-4d83-b021-5d75045f9b2d@t1g2000pra.googlegroups.com> Message-ID: <24098410-5bcb-40a2-b6ef-08d69cfef346@v39g2000pro.googlegroups.com> On Sep 8, 9:14?am, "James Mills" wrote: > On Mon, Sep 8, 2008 at 8:59 AM, John Machin wrote: > > What do you mean by "this right"? Perhaps the Divine Right of OPs, > > managers, examiners, business analysts, etc never to give a complete > > spec up front and never to contemplate the consequences of Murphy's > > Law? > > Now you're being silly. > Only in so far as I followed the habit of OPs and suchlike by using "never" instead of "rarely". From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 24 03:13:52 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 09:13:52 +0200 Subject: finding domain name In-Reply-To: <8e874f68-838b-4fc1-8228-1787525ca780@x41g2000hsb.googlegroups.com> References: <48d941f0$0$3738$426a74cc@news.free.fr> <8e874f68-838b-4fc1-8228-1787525ca780@x41g2000hsb.googlegroups.com> Message-ID: <48d9e8a4$0$6127$426a34cc@news.free.fr> Bobby Roberts a ?crit : > On Sep 23, 1:23 pm, Bruno Desthuilliers > wrote: >> Bobby Roberts a ?crit : >> >>> hi group. I'm new to python and need some help and hope you can >>> answer this question. I have a situation in my code where i need to >>> create a file on the server and write to it. That's not a problem if >>> i hard code the path. However, the domain name needs to be dynamic so >>> it is picked up automatically. The path to our websites is >>> home/sites/xxxxx/ >>> where xxxxx represents the domain name. >>> How can I find the domain name of the current url being viewed. >> What are you using exactly ? cgi ? wsgi ? Else ? > > mod python Ok. So the informations you're looking for should be accessible as attributes of the request object that get passed to your request handler. Attributes of interest here are mostly request.hostname, request.uri, request.path_info and request.filename. More informations here: http://www.modpython.org/live/current/doc-html/pyapi-mprequest-mem.html > over an in-house framework written years ago Mmm... Then you might want to checkout which version of mod_python you're using, and make sure you read the corresponding doc... FWIW, there's also a mod_python mailing-list, so I suggest you seek further assistance wrt/ mod_python specific stuff there. Of course, questions about the Python language and it's standard lib are welcome here. > without > documentation use the code, young jedi !-) > so it's not the easiest thing to navigate. We will be > moving to django this fall. From skip at pobox.com Thu Sep 18 08:23:14 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 18 Sep 2008 07:23:14 -0500 Subject: XML-schema 'best practice' question In-Reply-To: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: <18642.18482.549773.574753@montanaro-dyndns-org.local> Frank> 1. Don't use default values - create the document with all values Frank> filled in. Frank> 2. Use python to check for missing values and fill in the defaults Frank> when processing the document. Frank> Or maybe the best practice is to *always* validate a document Frank> before processing it. Frank> How do experienced practitioners handle this situation? 3. Don't use XML. (sorry, couldn't resist) Skip From m_palmer45 at yahoo.ca Tue Sep 23 11:50:15 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 23 Sep 2008 08:50:15 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> Message-ID: On Sep 23, 10:08 am, Michael Palmer wrote: > May be the reason for Decimal to accept float arguments is that NOT to accept float arguments. From pruebauno at latinmail.com Fri Sep 19 13:25:41 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Fri, 19 Sep 2008 10:25:41 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <1b4f0571-0346-4462-89b2-c5a11b4a028b@i76g2000hsf.googlegroups.com> On Sep 18, 7:42 pm, Steven D'Aprano wrote: > On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote: > > Now the obvious winner is pruebono - even unoptimized, using sets seems > > to be *way* faster than even the most optimized corrected version of > > your algorithm. > > I'm not being snarky about losing priority here, but I submitted > essentially the same solution two hours earlier than pruebono. > > Are people not seeing my posts? Have I been kill-filed by everyone except > Mensator? I also asked a question about HTTPError and I haven't seen any > responses at all. > > -- > Steven I see your post now, but I didn't notice it at the time I posted. Could be because I am using the noticeable bad Google groups interface that is known for being unreliable. Duplicate solutions on Usenet are almost a given and I consider duplicate solutions a good thing, it means that other people will be able to understand that code. In any case I am not here for glory I am posting under a pseudonym so nobody discovers that I am slacking off at work reading Usen[carrier lost] From invalid at invalid Thu Sep 18 10:59:24 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 18 Sep 2008 09:59:24 -0500 Subject: A unique instance of Python GUI program References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> Message-ID: On 2008-09-16, akineko wrote: > This may not be a Python specific challenge. I have a GUI > program written in Python + Tkinter. It works very well. > > Now, I would like to start it from a shell script. As my GUI > program includes a server, it should not have more than one > instance. Is there any easy way to check if another instance > of the program is already running. > > I vaguely remember that Windows programming provides a way to > check. On unix the solution is usually a lockfile placed in a predefined location. Other people use a socket, but that's a bit more susceptible to namespace collisions with unrelated programs. > A platform independent approach would be nice but a solution > for X is sufficient for my application. I don't see what X has to do with it. > Any comments will be greatly appreciated. This question is asked and answered about once a week, and I'm always surprised at how frequently it comes up. I've been doing sw development for decades and apart from Unix system daemons, I don't remember ever needing to prevent multiple instances of an application from running. Can somebody lend me a clue as to why this question comes up so often? There can't be that many people writing Unix daemons in Python (and if they were, they'd probably already know about lockfiles). Just curious... -- Grant Edwards grante Yow! Is something VIOLENT at going to happen to a visi.com GARBAGE CAN? From default at defaulter.net Sat Sep 27 19:10:09 2008 From: default at defaulter.net (default) Date: Sat, 27 Sep 2008 19:10:09 -0400 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> Message-ID: On Sat, 27 Sep 2008 15:56:39 -0700, Jim Thompson wrote: >Now you know why I blanket kill-file googlegroups. > > ...Jim Thompson I knew that! Every now and then one groper will make it back to the scene of his crime - but, granted, there was no hope for this one. -- ----== Posted via Pronews.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.pronews.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= - Total Privacy via Encryption =--- From gagsl-py2 at yahoo.com.ar Tue Sep 30 18:17:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 19:17:57 -0300 Subject: problem with "ImportError: No module named..." and sockets References: Message-ID: En Tue, 30 Sep 2008 18:38:19 -0300, Daniel escribi?: > [BEGIN CODE] > #!/usr/bin/python > import SocketServer > import os, sys > newpath = os.path.normpath( os.path.join( __file__, "../../.." )) > sys.path.insert(0, newpath) > > from pop.command.UpdateCommand import * > import cPickle > > > Traceback (most recent call last): > [...] > ImportError: No module named UpdateCommand > > I import the module at the top of the file server.py, but it doesn't > throw the ImportError until it tries to unpickle. Notice that you don't import the UpdateCommand module - you import all names defined inside it instead. It's not the same thing. See http://effbot.org/zone/import-confusion.htm -- Gabriel Genellina From wuwei23 at gmail.com Sun Sep 28 20:13:28 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 28 Sep 2008 17:13:28 -0700 (PDT) Subject: Odd Errors References: Message-ID: <1f32d36b-4de0-4f0b-9552-5ac0ef80892c@x16g2000prn.googlegroups.com> The problem is with this: > ? ? ? ? lines = lines.append(inLine) The append method of a list modifies the list in-place, it doesn't return a copy of the list with the new element appended. In fact, it returns None, which it then attaches the label 'lines' to, so the next iteration through it tries to call None.append... Replace the line with: lines.append(inLine) From metaperl at gmail.com Tue Sep 9 09:12:19 2008 From: metaperl at gmail.com (metaperl.com) Date: Tue, 9 Sep 2008 06:12:19 -0700 (PDT) Subject: creating an (inefficent) alternating regular expression from a list of options Message-ID: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Pyparsing has a really nice feature that I want in PLY. I want to specify a list of strings and have them converted to a regular expression. A Perl module which does an aggressively optimizing job of this is Regexp::List - http://search.cpan.org/~dankogai/Regexp-Optimizer-0.15/lib/Regexp/List.pm I really dont care if the expression is optimal. So the goal is something like: vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| u|ii|i)' Is there a public module available for this purpose? From python at p0w.org Fri Sep 26 15:56:57 2008 From: python at p0w.org (Strato) Date: Fri, 26 Sep 2008 21:56:57 +0200 Subject: ConfigParser subclass problem Message-ID: <48DD3E89.8000004@p0w.org> Hi folks, I think I do something wrong, but I don't see why it doesn't work, so I will explain: I've searched in the list archive and found this thread, that explain exactly what I want to have: the options strings returned by ConfigParser without being lower cased. I tryed to reproduce this, by subclassing the SafeConfigParser class, like this: * in my main script: from MyConfigParser import * * in the MyConfigParser.py file: from ConfigParser import SafeConfigParser class MyConfigParser(SafeConfigParser): def optionxform(self, optionstr): print "Called the modified version of the class" return optionstr then, when I run the script, every time a calls to my own class is done, the print statment is shown in the console, so this may work, but when I use the .items() method of the class, I got a lower cased result ! (In my test, using the .items() method is my only try to test the new class) Does anybody has an idea of what I'm doing wrong ? Thanks, Strato From 4g4trz802 at sneakemail.com Tue Sep 9 15:14:57 2008 From: 4g4trz802 at sneakemail.com (Michael Hoffman) Date: Tue, 09 Sep 2008 12:14:57 -0700 Subject: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles References: Message-ID: Michael Hoffman wrote: > unlink = os.unlink Actually, I need to use shutil.rmtree instead, but you get the idea. From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 10:25:30 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Sep 2008 14:25:30 GMT Subject: Ascii Menu I/O redirection References: Message-ID: <00e501cf$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 23:14:26 +0200, Hendrik van Rooyen wrote: > class console(object): > """ > This spoofs a single file like object, using stdout & - in > (Minimalistic proof of concept implementation) """ > > def __init__(self): > self.read = sys.stdin.read > self.readline = sys.stdin.readline > self.write = sys.stdout.write > self.flush = sys.stdout.flush > self.closeout = sys.stdout.close # keep references to close > self.closein = sys.stdin.close > > def close(self): > self.closein() > self.closeout() I'm not sure that closing stdin and stout are a good idea. This could have side-effects for other parts of your program, and will almost certainly end badly if you're running in the interactive interpreter. Other than that, what you've done seems reasonable, although since every instance of console() has the same state, I'd write it slightly differently: class console(object): """ This spoofs a single file like object, using stdout & - in (Minimalistic proof of concept implementation) """ read = sys.stdin.read readline = sys.stdin.readline write = sys.stdout.write flush = sys.stdout.flush closeout = sys.stdout.close closein = sys.stdin.close @classmethod def close(cls): cls.closein() cls.closeout() [...] > Questions are: > > Is this a reasonable way of doing this kind of thing? Is there a > canonical or better way of doing it? Am I missing something? It seems to me that you might have been better off to write your program to take two files, an input and an output, instead of forcing both to go to the same file. if 'serial' in sys.argv: # for RS-232 i/o to terminal infile = open('/dev/ttyS0','r+b') outfile = infile else: # console i/o infile = sys.stdin outfile = sys.stdout Hope this helps. -- Steven From gagsl-py2 at yahoo.com.ar Wed Sep 3 21:41:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 22:41:57 -0300 Subject: sys.stdin on windows References: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> <48BE63EC.1070004@timgolden.me.uk> Message-ID: En Wed, 03 Sep 2008 07:16:12 -0300, Tim Golden escribi?: > Gabriel Genellina wrote: >> En Wed, 03 Sep 2008 06:16:03 -0300, zugnush at gmail.com >> escribi?: >> >>> When I try to run the same thing on windows I get >>> IOError: [Error 9] Bad file descriptor >>> >>> How can I make this more windows friendly? >> Explicitely invoking the interpreter worked for me. That is, these two >> commands worked fine: >> type test.txt | python count.py >> python count.py < test.txt >> But I cannot explain *why* it doesn't work the other way. > > Known bug in NT-based file association. I'll try to find an online > reference, but that's basically > what it comes to. I think you can faff-about with > batch files to achieve the effect, but I can't > quite remember. > > http://support.microsoft.com/kb/321788 Uhmm... That KB article says the bug was corrected in Windows XP SP1, but I have SP3 installed and the test failed. Updating the registry by hand solved the problem. A regression maybe? -- Gabriel Genellina From Lie.1296 at gmail.com Wed Sep 17 11:51:08 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 17 Sep 2008 08:51:08 -0700 (PDT) Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: <8d2d6b9a-ee8a-4b66-825d-ab0ac2ee485d@n38g2000prl.googlegroups.com> On Sep 16, 3:20?pm, Armin wrote: > John Machin wrote: > > On Sep 16, 6:45 am, Armin wrote: > > >> Yes, but this is very unconvenient. > >> If d should reference the list a extended with a single list element > >> you need at least two lines > > >> a.append(7) > >> d=a > > >> and not more intuitive d = a.append(7) > > > Methods/functions which return a value other than the formal None and > > also mutate their environment are "a snare and a delusion". Don't wish > > for them. > > ? ?c = [9,10] > ? ?[1,2,3,4,7].append(c) -> Is this a valid expression? > Yes, that is a valid expression, however, the list you're appending to is immediately discarded. > ? ?The 'value' of that expression is None. > > ? ?However ... that's the way of the implementation of the append method. > ? ?It's a little bit confusing to me ... actually, you could implement your own myList which returns a value on append method: class MyList(list): def append(self, item): list.append(self, item) return self # or # return self[:] # if you want it to return a copy But I recommend against that. > --Armin > > Thanks to all ! > > > > > > > Inconvenient? How often do you want to mutate a list and then set up > > another reference to it?- Hide quoted text - > > - Show quoted text - From paul at boddie.org.uk Tue Sep 2 04:52:41 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 2 Sep 2008 01:52:41 -0700 (PDT) Subject: python mechanize/libxml2dom question References: Message-ID: On 2 Sep, 05:35, "bruce" wrote: > > i've got the following situation, with the following test url: > "http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#". > > i can generate a list of the tables i want for the courses on the page. > however, when i try to create the xpath query, and plug it into the xpath > within python, i'm missing something. if i have a parent xpath query, that > generates a list of results/nodes... how can i then use the individual > parent node, and trigger off of it, to get further information. You can always use the parentNode property on the nodes you get as results from the XPath query, but I guess what you want to do is to "rewind" and issue queries relative to some ancestor of the result nodes. [...] > # **** course names > > cpath='//table[position()>0]/descendant::td[position()=2][@width="85%"]/../td[1]/font/a[2]/text()' This obviously gets you right down to the hyperlink text within a part of the table. However, it may be easier to break this query up in order to get a more manageable overview of the process. My understanding of the above query is that it can first be rewritten as the following: cpath = "//table//td[position()=2 and @width='85%']/../td[1]/font/a[2]/ text()" Or even this: cpath = "//table[.//td[position()=2 and @width='85%']]//td[1]/font/ a[2]/text()" But what you could do is to obtain the important tables first: tables = d.xpath("//table[.//td[position()=2 and @width='85%']]") Here, we use the bracketed term to ensure that the table is the right one, but we don't actually descend inside the table. You could, from this, get the name by doing a query from each of these tables: for table in tables: cnames = table.xpath(".//td[1]/font/a[2]/text()") # list of text nodes You might want to consider a slightly safer approach when getting the text: cnames = table.xpath(".//td[1]/font/a[2]") # list of nodes, should be one name = cnames[0].textContent # all the text from the link When looking for the details, you can then write your query relative to these tables, rather than having to figure out the location of the details from the text nodes you've just extracted. details = table.xpath("following-sibling::table[1]") # list of max 1 node > i'm assuming that there's a libxml2node method that will do what i need that > i'm missing... You should be able to issue XPath queries from any node. There have been issues with libxml2dom and attribute nodes obtained from XPath, but these were fixed in recent changesets. Paul From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 24 03:16:14 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 09:16:14 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <48d9e932$0$6127$426a34cc@news.free.fr> Drake a ?crit : > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), Arrghll ! NO, DONT ! > or should the exception propagate to the calling program which > handles the issue? Yes, by all means and for God's sake. > Thanks in advance for anyone who can either answer my question or > point me to where this question has already been answered. There have been numerous threads about this here. From bj_666 at gmx.net Tue Sep 30 12:11:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Sep 2008 16:11:11 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: <6kf1cvF7dmkkU4@mid.uni-berlin.de> On Tue, 30 Sep 2008 10:57:19 -0500, Grant Edwards wrote: > On 2008-09-30, Peter Pearson wrote: >> On Tue, 30 Sep 2008 00:04:18 +0200, Ivan Rebori wrote: >>> >>> 1. Multi dimensional arrays - how do you load them in python For >>> example, if I had: >>> ------- >>> 1 2 3 >>> 4 5 6 >>> 7 8 9 >>> >>> 10 11 12 >>> 13 14 15 >>> 16 17 18 >>> ------- >>> with "i" being the row number, "j" the column number, and "k" the .. >>> uhmm, well, the "group" number, how would you load this ? >>> >>> If fortran90 you would just do: >>> >>> do 10 k=1,2 >>> do 20 i=1,3 >>> >>> read(*,*)(a(i,j,k),j=1,3) >>> >>> 20 continue >>> 10 continue >>> >>> How would the python equivalent go ? > > You would drag yourself out of the 1960s, install numpy, and then do > something like this: > > a = read_array(open("filename.dat","r")) In [64]: a = numpy.fromfile('test.txt', dtype=int, sep=' ') In [65]: a Out[65]: array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]) In [66]: a.reshape(2, 3, 3) Out[66]: array([[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]], [[10, 11, 12], [13, 14, 15], [16, 17, 18]]]) Ciao, Marc 'BlackJack' Rintsch From python.list at tim.thechases.com Mon Sep 15 06:52:16 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Sep 2008 05:52:16 -0500 Subject: Unable to see os.environ['COLUMNS'] In-Reply-To: <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> References: <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> Message-ID: <48CE3E60.8000004@tim.thechases.com> >> What's the best way to read what seems to be a >> pseudo-environment variable? > > You can't. You need to export the variable in the parent shell > before it exec's the child: > > $ export COLUMNS > > $ python -c "import os; print os.environ['COLUMNS']" > 80 This works well, and also manages to keep up to date across runs as window-size changes. More importantly, it makes sense (minus the "why doesn't bash automatically export COLUMNS to subshells" question, but a little investigation shows I can use "set -a" or "export COLUMNS" in my .bashrc and everything works). > Now, on to the question you're about to ask: > > Q: How do I find out how big my terminal is from a Python > program? You must be one of the folks working with the Python time-machine. :) (okay, so the intent of my question was pretty obvious) > A: You use the TIOCGWINSZ ioctl call on the terminal's file > descriptor: > >>>> import sys,fcntl,termios,struct >>>> data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234') >>>> struct.unpack('hh',data) > (24, 80) > > There's a more detailed explanation here (including an > explanation of what the third parameter to ioctl() does, and > how you detect changes in the window size): > > http://mail.python.org/pipermail/python-list/2006-February/365710.html Thanks, I'll read up on that, as well as investigate ncurses options. > There's also chance that you'd be better off just using ncurses or > newt for screen management, but that's another post. The screen-width is merely for a little output formatting to determine how many items can fit across. However, given the opacity of the ioctl() call, it might not hurt to look into using curses. Thanks for the pointers, -tkc From aahz at pythoncraft.com Sat Sep 27 10:00:37 2008 From: aahz at pythoncraft.com (Aahz) Date: 27 Sep 2008 07:00:37 -0700 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> Message-ID: In article <8763oiuhj2.fsf at benfinney.id.au>, Ben Finney wrote: >Steven D'Aprano writes: >> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: >>> >>> An ordinary singleton is instantiating the class multiple times >>> yet returning the same instance object; a class singleton is >>> simply using the class directly (like a module). > >Where is this "class singleton" terminology from? It seems redundant >to me. It also doesn't seem to have anything to do with what >"singleton" means as a pattern; "using a class" is simply using a >class. I don't remember where I picked it up, probably here some years ago. The point of the terminology is to distinguish how the class is *used*, in precise parallel with "module singleton". >> I'd like to be able to call [a class] as if it were a function. >> Normally calling a class object returns an instance -- I wish to >> return something else. > >In that case, you *don't* want a class at all; the entire point of a >class is to define behaviour for instances. Absolutely agreed with your first clause, disagreed about the second clause. As I said earlier, the main point of a class singleton is to get the effect of a module singleton without the need to create another file on disk. In that case there is no instance and therefore the point of the class is no longer to define behavior for instances. But you can't call a module, and classes have well-defined behavior for calling them, so you shouldn't try to pervert a class singleton by defining behavior for calling them. In fact, I would recommend creating an __init__() method that raises NotImplementedError precisely to prevent this usage (or have a __new__() method that returns None, but I generally prefer to recommend practices that work with classic classes). One cute reason to prefer class singletons to module singletons is that subclassing works well for creating multiple singletons. But really, the main reason I use class singletons is that they are the absolute simplest way to get attribute access: class Foo: pass Foo.bar = 'xyz' if data == Foo.bar: print "!" Once it gets much more complicated than that, I prefer to use a smarter object. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From patrick.chartier at aero.bombardier.com Sun Sep 7 06:06:06 2008 From: patrick.chartier at aero.bombardier.com (wildfireporn.com@googlegroups.com) Date: Sun, 7 Sep 2008 03:06:06 -0700 (PDT) Subject: Watch Videos Adult online for free Message-ID: <10e50a24-91dd-46af-9346-7fce7c54ba8d@a1g2000hsb.googlegroups.com> No charge! Free watch adult videos online http:///www.wildfireporn.com From mnordhoff at mattnordhoff.com Fri Sep 26 09:42:13 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 26 Sep 2008 13:42:13 +0000 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <18652.51228.620303.28571@montanaro-dyndns-org.local> References: <18652.51228.620303.28571@montanaro-dyndns-org.local> Message-ID: <48DCE6B5.3080900@mattnordhoff.com> skip at pobox.com wrote: > I took over spam filter management for the python.org mailing lists a couple > months ago and made a few changes to the way the spam filter is trained. > Things seem to be at a reasonable level as far as I can tell (I see a few > spams leak through each day), though I wasn't actively reading > comp.lang.python/python-list at python.org before I took over the task, so I > have nothing to compare with. Does the level of spam leaking through the > filter now seem excessive? Is it more or less than in June and July? > > Thanks, > > Skip Montanaro Over the last 24 hours, I think I count 10 spams, but that's probably higher than usual. I don't know if it's "excessive". It certainly isn't ideal, but it only takes 30 seconds to get rid of them, and we need to give my spam filter something to do, right? :-) I haven't been reading the list for very long, so I don't know how it compares to June or July. It feels like it's been increasing over time, but I don't have any numbers to back that up. -- From R.Brodie at rl.ac.uk Wed Sep 10 12:30:30 2008 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 10 Sep 2008 17:30:30 +0100 Subject: md5 differences References: Message-ID: "Python" wrote in message news:mailman.799.1221063937.3487.python-list at python.org... > here's an example: > Arno at Computer:~% echo "hello" | md5 > b1946ac92492d2347c6235b4d2611184 > How do I get the same results? Checksum the same string. >>> md5.new("hello\n").hexdigest() 'b1946ac92492d2347c6235b4d2611184' From mail at timgolden.me.uk Mon Sep 22 11:59:41 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 22 Sep 2008 16:59:41 +0100 Subject: Reading Windows CSV file with LCID entries under Linux. In-Reply-To: References: Message-ID: <48D7C0ED.9070501@timgolden.me.uk> Thomas Troeger wrote: > I've stumbled over a problem with Windows Locale ID information and > codepages. I'm writing a Python application that parses a CSV file, > the format of a line in this file is "LCID;Text1;Text2". Each line can > contain a different locale id (LCID) and the text fields contain data > that is encoded in some codepage which is associated with this LCID. My > current data file contains the codes 1033 for German and 1031 for > English US (as listed in > http://www.microsoft.com/globaldev/reference/lcid-all.mspx). > Unfortunately, I cannot find out which Codepage (like cp-1252 or > whatever) belongs to which LCID. > > My question is: How can I convert this data into something more > reasonable like unicode? Basically, what I want is something like > "Text1;Text2", both fields encoded as UTF-8. Can this be done with > Python? How can I find out which codepage I have to use for 1033 and 1031? The GetLocaleInfo API call can do that conversion: http://msdn.microsoft.com/en-us/library/ms776270(VS.85).aspx You'll need to use ctypes (or write a c extension) to use it. Be aware that if it doesn't succeed you may need to fall back on cp 65001 -- utf8. TJG From skip at pobox.com Thu Sep 4 20:11:56 2008 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 Sep 2008 19:11:56 -0500 Subject: Python test case management system? In-Reply-To: References: Message-ID: <18624.31052.912418.390277@montanaro-dyndns-org.local> Mudcat> Does anyone know of a good test case management system written Mudcat> in python, or possibly another application (either open source Mudcat> or commercial) that can be extended using python? I don't know what you mean by "test case management system", but within the Python community there are two core modules designed to support unit test creation: unittest and doctest. Outside of the Python distribution there are other tools which aim to make writing and running unit tests simpler. Examples include py.test and nose. I'm sure there are others. These might be a couple PyPI categories to start a search: http://pypi.python.org/pypi?:action=browse&c=430 http://pypi.python.org/pypi?:action=browse&c=431 Skip From sjmachin at lexicon.net Fri Sep 5 19:55:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 16:55:27 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> <0e12f3cd-7088-4f64-afa8-eb5ac4d00031@t1g2000pra.googlegroups.com> Message-ID: <5d2aedd3-2b93-4c1f-862c-db264552dec0@1g2000pre.googlegroups.com> On Sep 6, 9:30?am, John Machin wrote: > On Sep 6, 7:49?am, bearophileH... at lycos.com wrote: > > > John Machin: > > > > Consider this:>>> hash(123) == hash(123.0) == hash(123L) > > > True > > > Right... Can you explain me why Python designers have chosen to build > > a hash() like that? > > I can't channel them; my rationalisation is this: > > Following the Law of Least Astonishment,>> 123 == 123.0 == 123L > > True > > Consequently if x == y, then adict[x] and adict[y] should give the > same result. > Another reason for not folding in the type of the object is this: >>> type([]) >>> hash(type([])) 505252536 >>> id(type([])) 505252536 IOW hash(T) == id(T) where T is a type. id(obj) is just a memory address which can vary between executions of the same Python binary on the same machine ... not very reproducible. There is no guarantee in the docs for hash about under what circumstances hash(x) != hash(x) of course; I'm just relying on the least astonishment law again :-) And, again, we don't know what the OP's full requirements are ... From steve at REMOVE-THIS-cybersource.com.au Tue Sep 2 13:06:56 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 17:06:56 GMT Subject: Large amount of files to parse/organize, tips on algorithm? References: Message-ID: <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> On Tue, 02 Sep 2008 09:48:32 -0700, cnb wrote: > I have a bunch of files consisting of moviereviews. > > For each file I construct a list of reviews and then for each new file I > merge the reviews so that in the end have a list of reviewers and for > each reviewer all their reviews. > > What is the fastest way to do this? Use the timeit module to find out. > 1. Create one file with reviews, open next file an for each review see > if the reviewer exists, then add the review else create new reviewer. > > 2. create all the separate files with reviews then mergesort them? The answer will depend on whether you have three reviews or three million, whether each review is twenty words or twenty thousand words, and whether you have to do the merging once only or over and over again. -- Steven From marco.bizzarri at gmail.com Wed Sep 3 07:46:23 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 3 Sep 2008 13:46:23 +0200 Subject: Python IDEs with F5 or hotkey shell interaction In-Reply-To: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> Message-ID: <3f0d61c40809030446m2ed635ckbdeeafcf8921f82d@mail.gmail.com> On Tue, Sep 2, 2008 at 4:01 PM, mmm wrote: > > I might look at > Eclypse with pydev > Jedit > And these commercial/professional IDEs > Wing > Komodo IDE > Zeus > > But before doing so I wanted to know form experienced users: > > ** How hard is it to configure any of the general editors/IDEs to run > a Python shell using a hotkey (such as IDLEs F5) and whether any can > be set up for full interactivity. > > I understand and appreciate the difficulties to get full IDLE-like > interactivity, but what comes closest? > -- > http://mail.python.org/mailman/listinfo/python-list > I do not think I qualify for experienced users; I've used pydev for many years, and I'm quite comfortable with it. It is an eclipse based IDE, therefore you've some of its niceties and some of its drawbacks. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From dickinsm at gmail.com Tue Sep 30 07:42:52 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 30 Sep 2008 04:42:52 -0700 (PDT) Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> Message-ID: <77c70884-4667-4f62-b1e9-ad235855a3d5@z72g2000hsb.googlegroups.com> On Sep 30, 9:21?am, Terry Reedy wrote: > If no one beats me to it, I will probably file a bug report or two, but > I am still thinking about what to say and to suggest. I can't see many good options here. Some possibilities: (0) Do nothing besides documenting the problem somewhere (perhaps in a manual section entitled 'Infrequently Asked Questions', or 'Uncommon Python Pitfalls'). I guess the rule is simply that Decimals don't mix well with other numeric types besides integers: if you put both floats and Decimals into a set, or compare a Decimal with a Fraction, you're asking for trouble. I suppose the obvious place for such a note would be in the decimal documentation, since non-users of decimal are unlikely to encounter these problems. (1) 'Fix' the Decimal type to do numerical comparisons with other numeric types correctly, and fix up the Decimal hash appropriately. (2) I wonder whether there's a way to make Decimals and floats incomparable, so that an (in)equality check between them always raises an exception, and any attempt to have both Decimals and floats in the same set (or as keys in the same dict) also gives an error. (Decimals and integers should still be allowed to mix happily, of course.) But I can't see how this could be done without adversely affecting set performance. Option (1) is certainly technically feasible, but I don't like it much: it means adding a whole load of code to the Decimal module that benefits few users but slows down hash computations for everyone. And then any new numeric type that wants to fit in with Python's rules had better worry about hashing equal to ints, floats, Fractions, complexes, *and* Decimals... Option (2) appeals to me, but I can't see how to implement it. So I guess that just leaves updating the docs. Other thoughts? Mark From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 14:01:32 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 20:01:32 +0200 Subject: creating a similar object from an derived class In-Reply-To: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> References: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> Message-ID: <48beecec$0$16897$426a74cc@news.free.fr> Scott a ?crit : > Let's say I have an object: s/object/class/ > class foo(): > def create_another() > return foo() class Foo(object): def create_another(self): return Foo() > def blah(): def blah(self): > x = self.create_another() > ... do something with X > Now I create a inherited class of this object: > > class bar(foo): class Bar(Foo): > ... > > If I call bar.create_another(), it will Actually, it will raise a TypeError... > return a foo() instead of a > bar(). This isn't what I want. I would like bar.create_another() to > create an instance for bar(). def create_another(self) return type(self)() And while you're at it, since - at least in this concrete case - you need access to the class but not to the instance, you could make it a classmethod: class Foo(object): @classmethod def create_another(cls): return cls() HTH From deets at nospam.web.de Thu Sep 4 07:19:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 Sep 2008 13:19:20 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Message-ID: <6i9uidFphkg0U1@mid.uni-berlin.de> > Of course, I know that while I'm fresh, I've a good knowledge of the > code, and anything else, I will be able to avoid such stupid errors; > however, I'm afraid of the times when I'm tired, when I have to put my > hands on the code of someone else, and so on. > > Please, understand that I'm not stating that python is wrong... after > all, if it is wrong, I can move to a language like Java, which has a > different approach on it. I'm really very interested in reading past > discussion on it, if they are available. This has not much to do with the question of setters and getters. Because in your code you could write def setX(self, x): self.y = x def getX(self): return self.x So the error occurs in the same way. What you are essentially asking is: why is python dynamic instead of static? Because *that* is what is the difference. In a static language, you need to declare first what you want to be available, e.g. which variables and methods are available and such. Of course then the compiler (or whoever evaluates the static declarations) can puke on you if you attempt a stunt like the one you describe. Python (and other languages such as Ruby, Javascript) chose other. They give you the freedom to add instance variables (or even methods) at will, with the cost of the occasional error like the above. OTOH, Java makes me write soooo much more code that me becoming tired and doing some stupid mistake (and there are lots of them doable in static languages as well, otherwise no C/C++ or Java-program would crash....) becomes much more likely....YMMV. Diez From theller at python.net Fri Sep 12 04:35:44 2008 From: theller at python.net (Thomas Heller) Date: Fri, 12 Sep 2008 10:35:44 +0200 Subject: handling uncaught exceptions with pdb? In-Reply-To: <7xmyifpt68.fsf@ruckus.brouhaha.com> References: <7xmyifpt68.fsf@ruckus.brouhaha.com> Message-ID: <6iunubFkfd7U1@mid.individual.net> Paul Rubin schrieb: > I think I've asked about this before, but is there a way to set up > Python to handle uncaught exceptions with pdb? I know about setting > sys.except_hook to something that calls pdb, but this is normally done > at the outer level of a program, and by the time that hook gets > called, the exception has already unwound the stack to the outermost > level. My situation is I run a multi-hour or multi-day computation > that eventually crashes due to some unexpected input and I'd like to > break to the debugger at the innermost level, right when the exception > is encountered, so I can fix the error with pdb commands and resume > processing. Of course this presumes a certain semantics for Python > exceptions (i.e. handling one involves scanning the stack twice, once > to look for a handler and again to actually unwind the stack) and I'm > not sure if it's really done that way. I do know that Lisp has a > requirement like that, though; so maybe there is hope. Would this work (although it probably will slow down the program)? import sys, pdb def tracefunc(frame, event, arg): if event == "exception": pdb.set_trace() return tracefunc sys.settrace(tracefunc) def test(arg): if arg > 20: raise ValueError(arg) return test(arg+1) test(0) Thomas From tjreedy at udel.edu Mon Sep 1 21:04:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 21:04:22 -0400 Subject: Python 3.0b2 cannot map '\u12b' In-Reply-To: <6i2tugFo7morU3@mid.uni-berlin.de> References: <6i24u3Fo7morU2@mid.uni-berlin.de> <6i2tugFo7morU3@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: First, thank you for the informative responses. > The windows command prompt expects cp437 because that's what old DOS > programs print to it. Grrr. When the interpreter runs, it opens the command prompt window with Python running, and the window closes when Python exits, so there are no other programs involved. I don't suppose there is anyway to tell Command Prompt to accept something better. > But OOo works with unicode internally, so there's no communication with > outside programs involved here. Python 3 uses unicode internally also, but I gather CommandPrompt is an outside program used as a quick substitute for coding a plain window with MFC, for instance. ---------------------- I did some experiments. I added the /u flag after cmd.exe in the Command Prompt shortcut and the font to Lucida Console (which people on the web say handles unicode). I opened the prompts window and entered 'chcp 1252' the same codepage as IDLE. Start Python3. >>> import sys >>> sys.stdout.encoding 'cp1252' >>> '\u012b' Traceback (most recent call last): File "", line 1, in File "C:\Program Files\Python30\lib\io.py", line 1428, in b = encoder.encode(s) File "C:\Program Files\Python30\lib\encodings\cp1252.py", same with raster font choice. chcp 65001, which supposedly is UTF-8, disables all output. Perhaps Python does not recognize it as a synonym for UTF-8. The same on IDLE (with codepage 1252) gives i macron (bar on top). So something else is going on other than just codepage. I tried a second time and instead got "'\u012b'" and no error. Hooray, I thought, but I closed and tried again the same way, as best I know, but got the same error as before. Cp65001 also did and then did not work. Python does notice the code page change. tjr From fredrik at pythonware.com Sun Sep 21 14:53:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 20:53:28 +0200 Subject: Newick parser In-Reply-To: <73045cca0809211133y3198bde2n483738de8cac2810@mail.gmail.com> References: <73045cca0809211133y3198bde2n483738de8cac2810@mail.gmail.com> Message-ID: aditya shukla wrote: > Hello folks , i have a .nwk file.I want to parser the tree from that > file.I found this python parser for newick trees. > http://www.daimi.au.dk/~mailund/newick.html > > But i don't understand the usage properly.What i wanna do is if i have a > file in the location c:\\files\\file1.nwk , then i wanna parse the trees > in that file. judging from the docs, you should be able to do e.g. from newick import parse_tree file = open("c:\\files\\file1.nwk") text = file.read() print parse_tree(text) From a.schmolck at gmail.com Thu Sep 4 05:37:02 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Thu, 04 Sep 2008 10:37:02 +0100 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <00cf34ad$0$20302$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano writes: > On Thu, 04 Sep 2008 01:22:22 +0100, Alexander Schmolck wrote: > >> It seems to me that the right choice for thousands seperator is the >> apostrophe. > > You mean the character already used as a string delimiter? Yup. No ambiguity or problem here; indeed unlike space seperation or '_' it would work straighforwardly as a syntax extension in pretty much any programming language I can think as well as end-user output (I think that writing e.g. 1'000'000 on a website would be perfectly acceptable; unlike 1_000_000). 'as From tino at wildenhain.de Thu Sep 18 11:44:21 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 18 Sep 2008 17:44:21 +0200 Subject: improving a huge double-for cycle In-Reply-To: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <48D27755.8060208@wildenhain.de> Hi, Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > data=dict() for item in IN: # (what a name! ;) data.setdefault(item.coordinates,[]).append(item) # provided coordinates is a tuple dupes=[items for items in data.values() if len(items)>1] should give you a resulting list of lists of elements in IN which occur more then once per coordinates. You can then decide which ones to remove or whatever. If you want to have the output only containing nodes to remove, the following would work: dupes=[] for items in data.values(): dupes.extend(items[1:]) HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From grante at visi.com Wed Sep 24 21:22:41 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 24 Sep 2008 20:22:41 -0500 Subject: Linq to Python References: <48daa55d$0$19939$426a74cc@news.free.fr> Message-ID: On 2008-09-24, Bruno Desthuilliers wrote: > hrishy a ?crit : > (snip) > > >> I apologise >> (I thought Python programmers were smart and they did know what LINQ was) > > Is there really any relation between "being smart" and knowing anything > about the latest MS fad ? God, I hope not -- or I'd rather be stupid. -- Grant From krishnan.1000 at gmail.com Tue Sep 9 02:10:42 2008 From: krishnan.1000 at gmail.com (Karthik Krishnan) Date: Mon, 8 Sep 2008 23:10:42 -0700 Subject: Newbie Question:Please help Message-ID: Hi, I am a newbie to python and I hope this is not a stupid question. I am trying to run a main method from a Python command line using the command shell using the command. python main_test.py I get the following error. File "", line 1 python main_test.py Syntax Error: invalid syntax My main file main_test.py is given below. #!/usr/bin/env python """ Test method to run the main method. """ def main(): print "Main method called."; if __name__ = "__main__": main() -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyrie at uh.cu Sun Sep 7 16:38:06 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Sun, 07 Sep 2008 16:38:06 -0400 Subject: max(), sum(), next() In-Reply-To: <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: <1220819886.48c43baeb43ca@comuh.uh.cu> Quoting Mensanator : > Actualy, I already get the behaviour I want. sum([1,None]) > throws an exception. I don't see why sum([]) doesn't throw > an exception also If you take a "start value" and add to it every element of a list, should the process fail if the list is empty? If you don't add anything to the start value, you should get back the start value. Python's sum is defined as sum(sequence, start=0). If sum were to throw an exception with sum([]), it should also throw it with sum([], start=0), wich makes no sense. -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From duncan.booth at invalid.invalid Wed Sep 24 16:59:12 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Sep 2008 20:59:12 GMT Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: r0g wrote: > OK so maybe I'm being naive here but it looks to me like this new > paradigm's big idea is to use a python + SQL type syntax to access data > in random objects. Big whoop. It's not that difficult to write a > generators that wraps XML files and databases is it? > > What am I missing here? Simple LINQ expressions like the one you gave map easily to Python list comprehensions. What Microsoft have done though is provide a consistent implementation which allows you to write complex SQL like expressions which will work identically on databases or most other sequence types. Here's another LINQ example: List customers = GetCustomerList(); var customerOrderGroups = from c in customers select new {c.CompanyName, YearGroups = from o in c.Orders group o by o.OrderDate.Year into yg select new {Year = yg.Key, MonthGroups = from o in yg group o by o.OrderDate.Month into mg select new { Month = mg.Key, Orders = mg } } }; ObjectDumper.Write(customerOrderGroups, 3); I'm not overly keen on SQL syntax: I think this sort of complex expression is hard to read. LINQ has a pretty straightforward conversion to method calls, and for me this consistent set of methods is the important thing rather than the SQL syntax. e.g. 'group by' maps directly to a call to a method GroupBy(), so another of Microsoft's LINQ examples is: public void Linq45() { string[] anagrams = {"from ", " salt", " earn ", " last ", " near ", " form "}; var orderGroups = anagrams.GroupBy( w => w.Trim(), a => a.ToUpper(), new AnagramEqualityComparer() ); ObjectDumper.Write(orderGroups, 1); } public class AnagramEqualityComparer : IEqualityComparer { public bool Equals(string x, string y) { return getCanonicalString(x) == getCanonicalString(y); } public int GetHashCode(string obj) { return getCanonicalString(obj).GetHashCode(); } private string getCanonicalString(string word) { char[] wordChars = word.ToCharArray(); Array.Sort(wordChars); return new string(wordChars); } } Python still wins hands down on this example both in verbosity and readability: >>> anagrams = ["from ", " salt", " earn ", " last ", " near ", " form "] >>> from itertools import groupby >>> def AnagramKey(w): return sorted(w.strip().upper()) >>> for k,words in groupby(sorted(anagrams, key=AnagramKey), key=AnagramKey): for w in words: print w.strip().upper() print "..." EARN NEAR ... SALT LAST ... FROM FORM ... I haven't yet had occasion to use LINQ in anger yet, so I have no idea whether its an idea to love or to hate. I do think it is good that C# has effectively sprouted list comprehensions (not to mention anonymous types and type inferencing) and I expect there may be some aspects worth looking at for Python but I think they are more likely to lead to itertools functions than extensions to syntax. From paul at boddie.org.uk Mon Sep 22 06:48:55 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 22 Sep 2008 03:48:55 -0700 (PDT) Subject: New Web2Py framework SLASHES development time... References: Message-ID: <8bc01858-77f9-41bc-a907-4b9670f40213@b1g2000hsg.googlegroups.com> On 22 Sep, 04:49, Steve Shephed wrote: > http://www.web2py.comWeb2Py - Python Framework is the newest > kid on the block for Python frameworks. I'm not going to dwell on the merits of web2py, I'm afraid... > It has a lot of features that simply are not there in other > frameworks. Even Ruby!. You can design database models graphically > online. I had a closer look at the model designer, and the client-side magic seems to originate from this project: http://ondras.zarovi.cz/sql/ It looks quite fancy, especially since it all seems to be happening in the browser. Thanks for indirectly bringing this to our attention! ;-) Paul From pydecker at gmail.com Fri Sep 5 11:19:20 2008 From: pydecker at gmail.com (Peter Decker) Date: Fri, 5 Sep 2008 10:19:20 -0500 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <6i7u02Fpeif6U1@mid.uni-berlin.de> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> Message-ID: On Wed, Sep 3, 2008 at 11:57 AM, Diez B. Roggisch wrote: > Michael Palmer schrieb: >> >> As anyone knows, the state of Python GUI programming is a little >> fractured at this time, with many toolkits, wrappers and meta-wrappers >> dead and alive, with or without documentation. >> >> I've come across two projects that have the appeal of striving for >> simple, pythonic APIs: PyGUI and wax. The latter is a wrapper around >> wxPython. It is lacking documentation but actually quite usable and >> concise. The other, PyGUI, has an even nicer API and more docs but has >> relatively few widgets implemented at this time. It also strives for >> compatibility with several toolkits (two at this time), which I think >> is the right idea. > > I disagree with that. Meta-wrappers like this will always suffer from > problems, as they have difficulties providing a consistent api. For example > wx is said to be very windows-toolkit-centric in it's API. Yes I know that > it works under Linux with GTK, but it does not come as natural . With all due respect, it seems like you are not terribly familiar with wxPython. It uses the native UI toolkit for each platform wherever possible: Aqua on OS X; MFC on Windows and Gtk on Linux. Applications tend to look 'natural' on each platform, rather than uniform across platforms, and I believe that this is what most people prefer. -- # p.d. From xiaowei.lin at accenture.com Thu Sep 25 04:44:14 2008 From: xiaowei.lin at accenture.com (xiaowei.lin at accenture.com) Date: Thu, 25 Sep 2008 16:44:14 +0800 Subject: Question about reading a xml Message-ID: <83836530B94A0E4CBC50E17B137AF67D2EAC03@APAXM1113.dir.svc.accenture.com> Hi all, I am working on SunOS 5.8, Python 2.2.2 When I run the python grogram below: #Beginning import xml.dom.minidom xml_str = """\ ' this is a c' this is b this is c """ dom = xml.dom.minidom.parseString(xml_str) na = dom.getElementsByTagName("a")[0] nb = dom.getElementsByTagName("b")[0] nc = dom.getElementsByTagName("c")[0] print na.childNodes[0].data print nb.childNodes[0].data print nc.childNodes[0].data #End The result is as below: " this is a c this is c I don't know why the letters following the quote are lost. Even the quote lost if the quote following another letter. Regards, Sean This message is for the designated recipient only and may contain privileged, proprietary, or otherwise private information. If you have received it in error, please notify the sender immediately and delete the original. Any other use of the email by you is prohibited. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sat Sep 20 12:47:22 2008 From: __peter__ at web.de (Peter Otten) Date: Sat, 20 Sep 2008 18:47:22 +0200 Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Gary Herron wrote: > Or you can create a new reversed (copy of the original) list and iterate > through it > > for item in reversed(L): > ? print item It's not a copy, it's a view: >>> items = [1,2,3] >>> r = reversed(items) >>> items[:] = "abc" >>> for item in r: print item ... c b a Peter From Scott.Daniels at Acm.Org Tue Sep 30 08:42:12 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 30 Sep 2008 05:42:12 -0700 Subject: writing dll in python? In-Reply-To: References: Message-ID: Terry Reedy wrote: > .... > Start with the Python tutorial, perhaps parts of the reference manual, > and definitely peruse the first chapters in the library manual on > built-in functions and classes. Check out http://wiki.python.org/moin/BeginnersGuide to see a range of ways to learn Python, most very good (what works for you vaires by student). > You will almost certainly want to use numpy (numpy.org) for numerical > calculation and possibly existing modules in scipy (scipy.org) or > elsewhere. Although it is likely someyhing like numpy will be necessary, don't make the mistake of thinking Python cannot handle calculation itself easily. Where you'll need to leave python is in array and matrix calculations, there the numpy code will get you near custom C/fortran code speeds. >--Scott David Daniels Scott.Daniels at Acm.Org From dotancohen at gmail.com Sat Sep 27 04:11:06 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 27 Sep 2008 11:11:06 +0300 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <48dd4756$0$25116$426a74cc@news.free.fr> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> Message-ID: <880dece00809270111i1631a595he8888bfd675d85b9@mail.gmail.com> 2008/9/26 nntpman68 : > It's tough to find good rules, but the incoming spams that I see currently > on comp.lang.python have certain criteas. > > > > - most email addresses from gmail. > - all never posted before and then they have multiple posts within a few > minutes / seconds > - the posts always contain one or more urls ( mostly cryptic names ) > - they always start a thread but never reply to one > - the post doesn't contain python code or anything which looks only vaguely > like source code > - never mentions the word python > - the amount of sexual or financial vocabulary exceeds classical python > posts > I hope that the spammers don't read the list! -- Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? ?-?-?-?-?-?-? From rtiago at gmail.com Wed Sep 10 16:57:24 2008 From: rtiago at gmail.com (Ricardo Tiago) Date: Wed, 10 Sep 2008 22:57:24 +0200 Subject: formating a filesystem with python Message-ID: <8ed7d4b30809101357q2eebb00cl58576127c4cfea8a@mail.gmail.com> Hi all, is there a package in python that allows to mount/umount and format (to ext3) a filesystem? I know that this is possible by just calling the os commands 'mount/umount and mkfs' but this would imply to have to change sudoers to run the script as non-root. Thanks Ric From simon.hibbs at gmail.com Wed Sep 17 07:50:48 2008 From: simon.hibbs at gmail.com (Simon Hibbs) Date: Wed, 17 Sep 2008 04:50:48 -0700 (PDT) Subject: Python OOP advice Message-ID: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> I'm rewriting a design application for a science fiction game. in it you design your own starships. Each component has a mass and cost, but the mass can either be fixed or it can be expressed as a percentage of the tonnage of the overall ship. Orriginaly I thought I'd need to have a hull object which contains component objects, but the component objects need access to members of the hull object (e.g. the hull size) so that looks messy to implement. I have defined a base class Component with a class member variable 'hull_size' so that all components can see the hull size. I've then got two child classes called Fixed_Component and Percent _Component that implement their mass, mass_percent and cost properties appropriately for their type. I've also defined a Hull class which also inherits from Component and provides methods for access to the hull_size class variable. I'm not sure where to go from here. One possibility is to have a Ship object containing a list of components, but I'd need to have a way to ensure there's only ever one hull object so maybe that shouldn't go in the list? I think the fact that the hull_size is a class member also means I can't ever have an application that loads two designs at the same time, because they'd share the same hull_size class variable. Is that so, and is there a way round that? I suspect the inheritance model will work fine at first, but is too rigid in the long run. Is there a way to cleanly implement a parent-child relationship between objects that gives child objects limited access to members of the parent? Simon Hibbs From gagsl-py2 at yahoo.com.ar Tue Sep 2 06:05:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 07:05:08 -0300 Subject: Relative imports and "import X as Y" References: Message-ID: En Sun, 31 Aug 2008 07:27:12 -0300, Wojtek Walczak escribi?: > On Sun, 31 Aug 2008 06:40:35 GMT, OKB (not okblacke) wrote: > >>> Download the latest beta for your system and give it a try. >> >> Thanks for the advice, but I'd really rather not deal with >> installing the entire thing alongside my existing version, possibly >> causing conflicts in who knows what ways. > > Then you can download tar.gz package, compile it, and try it > without installing :-) Or use a virtual machine, or a live CD. -- Gabriel Genellina From fredrik at pythonware.com Fri Sep 5 13:26:39 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 19:26:39 +0200 Subject: Documentation (was Re: atomic section in code) In-Reply-To: References: Message-ID: Michele Simionato wrote: > The page you link here is WAYS better than the standard documentation > of the threading module. > Generally speaking, the effbot zone contains a lot of improvements > over the standard docs which are lacking in various areas. > I have always wondered why they are kept separated. Wouldn't be nice > to have the standard > docs integrated with the effbot docs? Are there plans in this sense > and if not, why not? There are tons of great supplementary material out there, on blogs, personal documentation collections (such as effbot.org), cookbook sites, etc. I don't think all that material absolutely must be posted to python.org, but Python users would definitely benefit from improved cross-linking. And this is, of course, something I've lobbied for many times, e.g. http://mail.python.org/pipermail/python-list/2005-May/322224.html http://mail.python.org/pipermail/python-list/2005-December/355625.html http://effbot.org/zone/idea-seealso.htm but I haven't yet figured out how to get something to happen [1]. All ideas are welcome. 1) Well, I guess the new Sphinx tool might have gotten some inspiration by my work in this domain: http://mail.python.org/pipermail/python-dev/2006-January/059978.html and Andrew Kuchling did some preliminary work for the old Latex work flow: http://svn.python.org/view/sandbox/trunk/seealso/ From bj_666 at gmx.net Thu Sep 11 12:19:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Sep 2008 16:19:06 GMT Subject: Better error message on recursive import References: <6isb2mF9scaU1@mid.individual.net> Message-ID: <6isunqF6v3jU2@mid.uni-berlin.de> On Thu, 11 Sep 2008 12:43:34 +0200, Thomas Guettler wrote: > why does Python only raise ImportError if it fails caused by a recursive > import? > > I know what's wrong. But I guess many beginner don't know what's wrong. > I don't want much, just "RecursiveImportError" instead of "ImportError". > Is this possible? Can you give an example of such a recursive import you want the special exception be raised? Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Mon Sep 29 16:10:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 17:10:33 -0300 Subject: what does "python -i" use as input stream (stdin)? References: Message-ID: En Fri, 26 Sep 2008 04:29:42 -0300, Almar Klein escribi?: > I would still like to hear if anyone knows how I can change the input > stream > that > is used when running "python -i", but I would not be surprised if it is > impossible... Sure you can. You have to replace the file descriptor 0, that is, "standard input"; sys.stdin reads from there. The standard way is to use os.dup2: c:\temp>type foo.txt This line read from foo.txt c:\temp>type redirect.py import os inp = open("foo.txt","r") os.dup2(inp.fileno(), 0) print "raw_input->", raw_input() c:\temp>python redirect.py raw_input-> This line read from foo.txt This is not -- Gabriel Genellina From rocky at panix.com Fri Sep 12 03:36:38 2008 From: rocky at panix.com (R. Bernstein) Date: Fri, 12 Sep 2008 03:36:38 -0400 Subject: handling uncaught exceptions with pdb? References: <7xmyifpt68.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > I think I've asked about this before, but is there a way to set up > Python to handle uncaught exceptions with pdb? I know about setting > sys.except_hook to something that calls pdb, but this is normally done > at the outer level of a program, and by the time that hook gets > called, the exception has already unwound the stack to the outermost > level. My situation is I run a multi-hour or multi-day computation > that eventually crashes due to some unexpected input and I'd like to > break to the debugger at the innermost level, right when the exception > is encountered, so I can fix the error with pdb commands and resume > processing. ... Why not use the traceback you get to show you where to change the code around that point to add an exception handler there which calls the debugger? From jfabiani at yolo.com Fri Sep 19 01:27:17 2008 From: jfabiani at yolo.com (John Fabiani) Date: Thu, 18 Sep 2008 22:27:17 -0700 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> Message-ID: erikcw wrote: > On Sep 18, 3:33?pm, Ben Finney > wrote: >> erikcw writes: >> > I have a cgi script where users are uploading large files for >> > processing. I want to launch a subprocess to process the file so the >> > user doesn't have to wait for the page to load. >> >> For "how do I deal with subprocesses from Python", the (new in Python >> 2.4) 'subprocess' module is the default go-to answer >> , replacing a >> rather fragmented set of modules before it. >> >> > What is the correct way to launch subprocess without waiting for the >> > result to return? >> >> Creating an instance of 'subprocess.Popen' will launch the process and >> return the Popen instance. You then have the option of polling it or >> waiting for it to complete. >> >> -- >> \ ? ? ?To stay young requires unceasing cultivation of the ability to | >> `\ ? ? ? ? ? ? ? ? ? unlearn old falsehoods.? ?Robert Anson Heinlein | >> _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| >> Ben Finney > > So if I create a Popen object and then just ignore the object and exit > the program the subproccess will finish it's work and then exit itself > cleanly? Just so happens that I ran into the same problem recently. I started with exec(), then os.system(), next os.popen(), and last os.spawn(). This is what I discovered on a windows platform. The exec() replaced the current running process. os.system did not start a completely new process. os.popen() created a new process but did not open a command box to display any print statements. Lastly os.spawn() worked - it created a new process and opened a command box to display any print statements I needed. Johnf From dudeja.rajat at gmail.com Wed Sep 24 11:53:49 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Wed, 24 Sep 2008 16:53:49 +0100 Subject: problem updating variable in a module In-Reply-To: References: Message-ID: >I take it you do have a *really* good reason to use a global? Please suggest some way other than using global. I want to get rid of it -- Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From aquil.abdullah at gmail.com Fri Sep 5 16:06:19 2008 From: aquil.abdullah at gmail.com (aha) Date: Fri, 5 Sep 2008 13:06:19 -0700 (PDT) Subject: Need formatting suggestion for long strings References: Message-ID: <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> On Sep 5, 3:29?pm, Jean-Paul Calderone wrote: > On Fri, 5 Sep 2008 14:24:16 -0500, Robert Dailey wrote: > >Hi, > > >I find quite often that I'm writing things like this: > > >raise FatalExcept( "Insufficient number of arguments specified. Exactly {0} > >arguments are required. See stage.bat for documentation on accepted > >parameters.".format( num_arguments ) ) > > >On my display (Vertical monitor), this exceeds the width of my display, and > >to view the entire length of the string I am forced to pan my view left and > >right. Is there a special way I can format this string so that it fits > >nicely on the screen? Keep in mind that one important factor is that > >whitespace is very sensitive, and I do not want line breaks in my script > >file to become part of the string itself. I like how C++ handles strings, > >like this: > > >char const* mystring = > > ? ?"This is a very long string that " > > ? ?"spans multiple lines and does " > > ? ?"not include line breaks or tabs " > > ? ?"from the source file between " > > ? ?"the strings partitions." > > >What do you guys prefer? Thanks for reading. > > mystring = ( > ? ? "This is a very long string that " > ? ? "spans multiple lines and does " > ? ? "not include line breaks or tabs " > ? ? "from the source file between " > ? ? "the strings partitions.") > > Jean-Paul Can you be more specific? What is the formatting criteria? Are you talking about formatting the string for display or are you talking about the source? From tjreedy at udel.edu Mon Sep 1 14:25:01 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 14:25:01 -0400 Subject: Python 3.0b2 cannot map '\u12b' In-Reply-To: <6i24u3Fo7morU2@mid.uni-berlin.de> References: <6i24u3Fo7morU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: > >> I doubt the OP 'chose' cp437. Why does Python using cp437 even when the >> default encoding is utf-8? >> >> On WinXP >> >>> sys.getdefaultencoding() >> 'utf-8' >> >>> s='\u012b' >> >>> s >> Traceback (most recent call last): >> File "", line 1, in >> File "C:\Program Files\Python30\lib\io.py", line 1428, in write >> b = encoder.encode(s) >> File "C:\Program Files\Python30\lib\encodings\cp437.py", line 19, in >> encode >> return codecs.charmap_encode(input,self.errors,encoding_map)[0] >> UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in >> position >> 1: character maps to > > Most likely because Python figured out that the terminal expects cp437. > What does `sys.stdout.encoding` say? The interpreter in the command prompt window says CP437. The IDLE Window says 'cp1252', and it handles the character fine. Given that Windows OS can handle the character, why is Python/Command Prompt limiting output? Characters the IDLE window cannot display (like surrogate pairs) it displays as boxes. But if I cut '[][]' (4 chars) and paste into Firefox, I get 3 chars. '[]' where [] has some digits instead of being empty. It is really confusing when every window on 'unicode-based' Windows handles a different subset. Is this the fault of Windows or of Python and IDLE (those two being more limited that FireFox)? >> To put it another way, how can one 'choose' utf-8 for display to screen? > > If the terminal expects cp437 then displaying utf-8 might give some > problems. My screen displays whatever Windows tells the graphics card to tell the screen to display. In OpenOffice, I can select a unicode font that displays at least everything in the BasicMultilingualPlane (BMP). Terry Jan Reedy From ruivaldo at gmail.com Mon Sep 22 07:23:09 2008 From: ruivaldo at gmail.com (Rui) Date: Mon, 22 Sep 2008 04:23:09 -0700 (PDT) Subject: Encoding.ASCII.GetBytes similar for Python ? Message-ID: <463f31b8-ba48-4833-8d41-9aa5f1cae189@a70g2000hsh.googlegroups.com> Hi, how can i do what Encoding.ASCII.GetBytes (in .net, c#) does with the strings. I am trying to query some dns server to check its response using udp sockets. Some of the source below: # encoding: utf8 import socket import sys import struct IP_PORT = 53 server_host = ('4.2.2.1', IP_PORT) transaction_id = "Q1" TIMEOUT = 5 type_string = "\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u0000" trailer_string = "\u0000\u0000\u0001\u0000\u0001" address = 'google.com' url_name_start, domain_name = address.split(".") # Query format copied from the C# example. #QueryString = TransactionID1 + TypeString + (char)URLNameStart.Length + URLNameStart + (char)DomainName.Length + DomainName+ TrailerString; query = (transaction_id + type_string + str(len(url_name_start)) + url_name_start + str(len(domain_name)) + domain_name + trailer_string) print query sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.settimeout(TIMEOUT) sock.connect(server_host) sock.send(query) data = sock.recv(512) for data_item in data: try: print chr(data_item) except: print data_item But it just returns trash: >python dns_checker.py Q1\u0001\u0000\u0000\u0001\u0000\u0000\u0000\u0000\u0000\u00006google3com \u0000\ u0000\u0001\u0000\u0001 Q 1 ? ? Any advice ? Thanks! From fredrik at pythonware.com Sun Sep 7 18:36:45 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 00:36:45 +0200 Subject: lacking follow-through In-Reply-To: <6ij1ecFqp39rU4@mid.uni-berlin.de> References: <6ij1ecFqp39rU4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > Yeah, castironpi sometimes doesn't make much sense. Maybe because it's a > bot!? :-) if so, they sure don't make c.l.py bots like they used to, do they? From dudeja.rajat at gmail.com Sat Sep 6 12:47:56 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 6 Sep 2008 17:47:56 +0100 Subject: Want to display a message box while subprocess is running Message-ID: Hi, I m using subprocess module and using the Popen call. While the subprocess if running, I want to display a tkMessageBox(). Does some one has a sample code for this? Thanks and regards, Rajat From mobiledreamers at gmail.com Mon Sep 22 19:01:21 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Mon, 22 Sep 2008 16:01:21 -0700 Subject: Python based barcode readers In-Reply-To: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> References: <492eada6-1127-46d8-bd8b-96aa337612a8@w24g2000prd.googlegroups.com> Message-ID: This is something I have looked for too but I have not come across a decent barcode reader? On 9/22/08, Robocop wrote: > > Does anyone know of any python based barcode readers? I'm looking for > something (commercial or open source) that will use some OCR algorithm > to read barcodes from an image or ps/pdf file, and ideally will be > something along the lines of a callable python script. I have some > pretty simple needs, i'm only trying to read code 93 barcodes, so i > don't need it to be able to identify multiple symbologies or > anything. Any suggestions would be greatly appreciated. > > Thanks! > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://gpirate.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Sat Sep 27 21:50:38 2008 From: roy at panix.com (Roy Smith) Date: Sat, 27 Sep 2008 21:50:38 -0400 Subject: Docstrings for attributes? Message-ID: Is there any way to attach a docstring to an attribute? I see that PEP-257 talks about attribute docstrings, but it references PDP-258, which was rejected. I suppose I could eschew plain attributes in favor of getter functions, because those give me a place to hang a docstring, but that feels like the wrong thing to do. From sturlamolden at yahoo.no Fri Sep 26 06:08:52 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 26 Sep 2008 03:08:52 -0700 (PDT) Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> Message-ID: <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> On Sep 26, 5:45?am, "David Cournapeau" wrote: > I am fairly experienced in matlab (have been using it extensively for > 5 years in academical context), and now with numpy, and generally, > they are comparable speed-wise. Matlab has some niceties which makes > it faster in some simple cases (JIT for loops, function calls faster, > sometimes COW semantics means it faster), I've used Matlab for 10 years. Matlab has a horrible pass-by-value semantics, which means that arrays are copied in and copied out form function calls. Yes there is a copy- on-write optimization. But unless you are not careful, it will kill performance and make memory usage skyrocket. Also, slicing creates a new array, whereas in numpy slicing gives you a view of an existing array. This generally makes Matlab slow, and it wastes terrible amounts of memory. For example I once tested D4 wavelet transforms on a 64 MB array of doubles (i.e. length 2**23). Matlab R14 Service Pack 2 did this in 27 seconds, whereas Python 2.4 with NumPy 1.0 one required 3.4 seconds. That is an order of magnitude speed difference in favour of Python. Matlab also has a strange habit of fragmenting the heap. This can be so bad that you have to stop the script, run a special function called pack() do defragement, and restart. I've never seen that with Python. I more or less stopped using Matlab 3 years ago, and I have not renewed my subscription for maintenance of my personal Matlab license since. Matlab is a nice tool, but I have grown past it. Matlab's strongest side is data visualization though. Although we have matplotlib, mayavi and possibility of interfacing with gnuplot, it's not anywhere near the capabilities of Matlab. From hrishys at yahoo.co.uk Thu Sep 25 06:36:13 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 10:36:13 +0000 (GMT) Subject: Linq to Python In-Reply-To: <48DA92F1.1060501@timgolden.me.uk> Message-ID: <18101.30495.qm@web27406.mail.ukl.yahoo.com> Hi Tim I am not a LINQ expert just a LINQ user and (was a little envious why the langauge i fantasize doesnt have it (pardon my ignorance of python)) LINQ as far as i know allows you to query all sources using a consistent interface . You can query a message queue ,xml document ,array object or relational source by learning LINQ and even join them as illustrated below http://informationr.net/ir/13-2/TB0806.html If somebody can tutor me how i can do that in python that would be great (and mayeb satisfy my greed and leave me with a happy feeling that my langauge python can do it) regards Hrishy --- On Wed, 24/9/08, Tim Golden wrote: > From: Tim Golden > Subject: Re: Linq to Python > To: > Cc: python-list at python.org > Date: Wednesday, 24 September, 2008, 8:20 PM > bearophileHUGS at lycos.com wrote: > > sturlamolden: > >> No, because Python already has list comprehensions > and we don't need the XML buzzword.< > > > > LINQ is more than buzzwords. Python misses several of > those features. > > So maybe for once the Python crowd may recognize such > C# feature as > > much better than things present in Python. > > Said that, I presume Python will go on as usual, and > LINQ-like > > capabilities will not be integrated in Python. In the > meantime where I > > live lot of people will keep using C# instead of > Python and CLisp, > > natural selection at work indeed. > > Perhaps a quick summary of what LINQ offers which might > "be integrated into Python" would help those of > us who > are ignorant? (This is a serious comment; I'd like to > know). > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list From tino at wildenhain.de Mon Sep 22 09:50:46 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Mon, 22 Sep 2008 15:50:46 +0200 Subject: understanding list scope In-Reply-To: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> Message-ID: <48D7A2B6.6090107@wildenhain.de> Hi, Alex wrote: > Hi all! > > I have a problem understanding the behaviour of this snippet: > > data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) > > for i in range(len(data_set)): > ds = data_set[:] > data = ds[i] > if i == 1: data['param'] = "y" > if i == 2: data['param'] = "x" > > print data_set Beside the data copy which is explained in the other posts, what is the problem you want to solve? Would data_set[1]['param']="x" data_set[2]['param']="y" not doing the same? or more to your point: ds=data_set[:1]+[dict(param="x"),dict(param="y")]+data_set[2:] HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From digitig at gmail.com Wed Sep 24 11:19:54 2008 From: digitig at gmail.com (Tim Rowe) Date: Wed, 24 Sep 2008 16:19:54 +0100 Subject: problem updating variable in a module In-Reply-To: References: Message-ID: 2008/9/24 : > Hi, > > I've a problem updating my variable in a module. > > In my main program, I call a function from mod1 to update a variable of mod1 > As soon as I update this varibale, I check it back in the mail program but > it the variable from mod1 does not get updated. > > main Program: > **************** > import mod1 > a = 20 > mod.update(a) > print mod.a <---- does not print anything > > mod1 > ******** > a = 10 > def update(someInt): > global a > a = someInt > print a <---- this does actually print a = 20 I'm surprised it runs at all -- as far as I can see "mod" in "mod.update(a)" and "print mod.a" is not defined. Did you mean "mod1"? If I change it to that, both print statements print "20" as I'd expect. I take it you do have a *really* good reason to use a global? -- Tim Rowe From cvrebert at gmail.com Thu Sep 4 03:36:13 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Thu, 4 Sep 2008 00:36:13 -0700 Subject: use str as variable name In-Reply-To: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> Message-ID: <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> On Thu, Sep 4, 2008 at 12:25 AM, Mathieu Prevot wrote: > Hi, > > I have a program that take a word as argument, and I would like to > link this word to a class variable. > > eg. > class foo(): You should subclass 'object', so that should be: class Foo(object): > width = 10 > height = 20 > > a=foo() > arg='height' > a.__argname__= new_value You're looking for the setattr() built-in function. In this exact case: setattr(a, arg, new_value) This is probably covered in the Python tutorial, please read it. Regards, Chris > > rather than : > > if arg == 'height': > a.height = new_value > elif arg == 'width'; > a.width = new_value > > Can I do this with python ? How ? > > Thanks, > Mathieu > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From roseeea at gmail.com Thu Sep 4 04:33:16 2008 From: roseeea at gmail.com (roseeea at gmail.com) Date: Thu, 4 Sep 2008 01:33:16 -0700 (PDT) Subject: CREDIT CARD DEPT Message-ID: <77d219ea-42c1-45fa-93c4-dfd3830237f2@a2g2000prm.googlegroups.com> CREDIT CARD DEPT http://creditcarddept.googlepages.com From nick at craig-wood.com Thu Sep 11 04:36:35 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 11 Sep 2008 03:36:35 -0500 Subject: dict slice in python (translating perl to python) References: Message-ID: hofer wrote: > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] As an ex-perl programmer and having used python for some years now, I'd type the explicit v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars Or maybe even v1 = mydict['one'] # 54 chars v2 = mydict['two'] v3 = mydict['two'] Either is only a couple more characters to type. It is completely explicit and comprehensible to everyone, in comparison to v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars Unlike perl, it will also blow up if mydict doesn't contain 'one' which may or may not be what you want. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From larry.bates at vitalEsafe.com Tue Sep 9 18:46:28 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 09 Sep 2008 17:46:28 -0500 Subject: wxpython ms-dos black window popping up in background In-Reply-To: References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: icarus wrote: > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > That did it. > > one more question... > > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? > > My intent is to have the process transparent to the user. He wouldn't > even know the app was written in python. All he knows that when he > double-clicks on it, the application pops up without the DOS black > screen in the background (for w32 users.) > > > > > > > On Sep 9, 10:49 am, "Chris Rebert" wrote: >> You need to have the script be run by pythonw.exe as opposed to python.exe >> pythonw.exe suppresses the DOS box from coming up and should be used >> for running GUI applications such as yours. >> >> Regards, >> Chris >> >> >> >> On Tue, Sep 9, 2008 at 1:33 PM, icarus wrote: >>> platform: windows xp professional, python 2.5, wxpython >>> When I double-check on my program file test.py (for simplicity I'll be >>> using this code below), I see the window just fine. But the ms-dos >>> black window pops up in the background. On Linux, no issues at all. >>> How can I get rid of that ms-dos black window in the background? >>> something I need to add to my code? a setting to adjust in windows? >>> thanks in advance. >>> #!/usr/bin/python >>> import wx >>> appwx = wx.App() >>> frame = wx.Frame(None, -1, 'test.py') >>> frame.Show() >>> appwx.MainLoop() >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> -- >> Follow the path of the Iguana...http://rebertia.com > On Windows use py2exe and Inno Setup to create "frozen" application that is easy to distribute. On Mac/Linux there are other solutions. -Larry From prologic at shortcircuit.net.au Thu Sep 25 18:40:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 26 Sep 2008 08:40:32 +1000 Subject: PEP Proposal In-Reply-To: <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Fri, Sep 26, 2008 at 6:14 AM, wrote: > Typed parameters. Method-Declaration-filtered-typed parameters. That's what > I'm thinking of. Why do we need this (rubbish) ? Seriously. The use-case is far too small. And don't invent use-cases either. Instead of coming up with ideas of adding more and more into the language from other languages of which certain features weren't very good in the first place, devote your time to improving the libraries, documentation, etc. Typed parameters is useless to me. A lot of developers would agree. --JamesMills -- -- -- "Problems are solved by method" From lists at cheimes.de Sun Sep 28 07:34:44 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 28 Sep 2008 13:34:44 +0200 Subject: str() should convert ANY object to a string without EXCEPTIONS ! In-Reply-To: <00ef3974$0$20666$c3e8da3@news.astraweb.com> References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <00ef3974$0$20666$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >>>> str(b'123') # b prefix is added > "b'123'" > > > Perhaps I'm misinterpreting it, but from here it looks to me that str() > is doing what repr() used to do, and I'm really not sure that's a good > thing. I would have expected that str(b'123') in Python 3 should do the > same thing as unicode('123') does now: No, you are getting it right and yes, it's problematic. Guido wanted str(b'') to succeed. But the behavior can easily mask bugs in code. Therefor a byte warning mode was implemented. $ ./python -b >>> str(b'123') __main__:1: BytesWarning: str() on a bytes instance "b'123'" $ ./python -bb >>> str(b'123') Traceback (most recent call last): File "", line 1, in BytesWarning: str() on a bytes instance >>> b'' == '' Traceback (most recent call last): File "", line 1, in BytesWarning: Comparison between bytes and string From tjreedy at udel.edu Mon Sep 29 23:59:40 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 23:59:40 -0400 Subject: What is not objects in Python? In-Reply-To: <00f15dd2$0$20617$c3e8da3@news.astraweb.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <00f15dd2$0$20617$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 29 Sep 2008 05:41:02 -0700, George Sakkis wrote: > >> For example I would be much less >> opposed to len() being defined as, say, |x| if "|...|" was a valid >> operator. > > Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians > and physicists. It should be both, just as + is addition for numbers and concatenation for sequences. Or we could have just one built-in -- size() instead of abs() and len(). For non-sequence collections, size() would be better than len() anyway. tjr From deets at nospam.web.de Fri Sep 5 11:48:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 17:48:54 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> Message-ID: <6id2n6FpunpvU1@mid.uni-berlin.de> Peter Decker schrieb: > On Wed, Sep 3, 2008 at 11:57 AM, Diez B. Roggisch wrote: >> Michael Palmer schrieb: >>> As anyone knows, the state of Python GUI programming is a little >>> fractured at this time, with many toolkits, wrappers and meta-wrappers >>> dead and alive, with or without documentation. >>> >>> I've come across two projects that have the appeal of striving for >>> simple, pythonic APIs: PyGUI and wax. The latter is a wrapper around >>> wxPython. It is lacking documentation but actually quite usable and >>> concise. The other, PyGUI, has an even nicer API and more docs but has >>> relatively few widgets implemented at this time. It also strives for >>> compatibility with several toolkits (two at this time), which I think >>> is the right idea. >> I disagree with that. Meta-wrappers like this will always suffer from >> problems, as they have difficulties providing a consistent api. For example >> wx is said to be very windows-toolkit-centric in it's API. Yes I know that >> it works under Linux with GTK, but it does not come as natural . > > With all due respect, it seems like you are not terribly familiar with > wxPython. It uses the native UI toolkit for each platform wherever > possible: Aqua on OS X; MFC on Windows and Gtk on Linux. Applications > tend to look 'natural' on each platform, rather than uniform across > platforms, and I believe that this is what most people prefer. You got me wrong. I didn't say it doesn't use the native toolkit under various OSes, I'm well aware of that it does. What I *did* say was that wx API is designed primarily with windows' toolkit as base, and as a consequence the API tends to be less functional for other toolkits, making it harder to work with it. As the OP was after a "one API to rule them all" for GUIs, I pointed that out. See for example this (arguably somewhat dated) post that illustrates my point: http://mail.python.org/pipermail/python-list/2005-March/313354.html From my personal experience with Qt and Cocoa, I can say that both are great, but their full power is unleashed only if used directly - talk about Multi-threading in Qt4, or KeyValue-coding in Cocoa. Neither is available in wx. Diez From lists at cheimes.de Tue Sep 9 14:45:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 09 Sep 2008 20:45:05 +0200 Subject: PYTHONSITEDIR environment variable In-Reply-To: References: Message-ID: ago wrote: > The only thing I would add is that in my experience I often use > different working-envs for different projects, so I'd prefer to have a > more generic solution as opposed to a single working-env per user. The > latter could still be achieved by setting the appropriate environment > variable in the user profile. Do you think it would be possible to > accommodate for the above in your PEP? Isn't PYTHONUSERBASE sufficient for your needs? The env var alters the base directory. I can neither change the PEP nor the implementation at this stage of the development cycle. Python 2.6 and 3.0 are in beta and the API is set in stone. Christian From mathieu.malaterre at gmail.com Mon Sep 8 05:12:54 2008 From: mathieu.malaterre at gmail.com (mathieu) Date: Mon, 8 Sep 2008 02:12:54 -0700 (PDT) Subject: Test if list contains another list Message-ID: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> Hi there, I am trying to write something very simple to test if a list contains another one: a = [1,2,3] b = [3,2,1,4] but 'a in b' returns False. How do I check that a is indeed contained in b ? thanks From bearophileHUGS at lycos.com Tue Sep 23 11:31:14 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 23 Sep 2008 08:31:14 -0700 (PDT) Subject: Python is slow? References: Message-ID: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> sturlamolden: CPython is generally slow (you can see this from the huge amount of solutions invented to solve the speed problem, like Cython, Numpy, Psyco, ShedSkin, Weave, Inline, SIP, Boost Python, SWIG, etc etc), but for most of the usages Python is used for, it's not a significant problem. I know that sounds like a tautology :-) Well written C++ code is generally faster or much faster than similar Python code, but programming in Python is often simpler, and it generally requires less time. So it may happen that to solve a problem a Python program that runs in 1 hour that requires 1 hour to be written allows you to find the solution in less time than a C++ program that runs in 5-10 minutes that requires you 3-4 hours to be written :-) Note that C++ is just one option, but there are other languages around, like CLisp or D (or even a modern JavaVM), that are often an acceptable compromise between Python and C/C++. So you can show us a reduced/minimal working version of your Python code, so I/someone may find ways to speed it up, translate it to C or C ++ or CLisp or D, etc. Note that I have written a kd-tree in both Python (with Psyco compulsively) and D, this is the Psyco version: http://code.activestate.com/recipes/572156/ Bye, bearophile From mensanator at aol.com Sat Sep 20 14:51:55 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 20 Sep 2008 11:51:55 -0700 (PDT) Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> Message-ID: <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> On Sep 20, 1:34?pm, "Guilherme Polo" wrote: > On Sat, Sep 20, 2008 at 1:27 PM, Mensanator wrote: > > Beacuse in 2.6, Python apparently has fixed a discrepency that existed > > in previous versions. > > > In the IDLE that comes with 2.5, typing "as", to wit "import random as > > ran", > > the words "import" and "as" highlight in red, so you can't use them as > > variable > > names or you'll get a syntax error. > > > Ah, but you CAN use "as" for a variable: "for as in xrange(10): print > > as" > > works just fine, although it shouldn't. > > > Python 2.6 fixes this discrepency and now gives you a syntax error if > > you > > use "as" for a variable name. > > You should have noticed the warning you received in python 2.5 when > using "as" as a name. I'm not the one who wrote sympy, so I guess I'm not the only one who didn't notice it. If it's a well known problem, then sorry I wasted your time. The sympy people thought it was important and, as not everyone uses sympy, I thought I was performing a service to the community mentioning it here. Sheesh. > > > > > The upshot is code (such as sympy) written prior to 2.6 can crash now > > due > > to this fix if said code inadverntently used what should have been a > > reserved > > word. > > > I was able to fix the code for this "as" problem, but not the one that > > came after. I've reported this and interested parties can visit the > > sympy > > page and check Issue 1115. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > -- Guilherme H. Polo Goncalves- Hide quoted text - > > - Show quoted text - From john at btqnet.com Mon Sep 29 00:48:24 2008 From: john at btqnet.com (johnc) Date: Sun, 28 Sep 2008 21:48:24 -0700 (PDT) Subject: Looking for a Python developer in Austin Message-ID: I?m looking for a python guru to help me and my company grow in this language area. We are native to .net but have found ourselves with a larger python perl project that needs some really good team members. Because this is not our core language I want to make sure this is a good fit. I can discuss more details but wanted to check if you are looking for work and are good in the webservices area of these languages? This is more of an infrastructure project not a website for external users. The job will require expert knowledge of webservices both writing and working with existing services. Possibly soap and others. Thanks for your time in advance. This is not a spam post, we really do need a guru to join our team. :) From michael at stroeder.com Thu Sep 4 19:39:35 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Fri, 05 Sep 2008 01:39:35 +0200 Subject: Can anyone suggest a good crypto package? In-Reply-To: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> References: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> Message-ID: Fett wrote: > On Sep 4, 2:23 pm, Mike Driscoll wrote: >> How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads > > Seems that this is intended more for webapps or something, Why do you think so? It's a C wrapper module around the OpenSSL crypto libs. Ciao, Michael. From george.sakkis at gmail.com Thu Sep 25 16:07:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 25 Sep 2008 13:07:53 -0700 (PDT) Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> <48dbc82e$0$1120$426a74cc@news.free.fr> <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> Message-ID: <1fc9b5c2-0e58-4b48-9352-4122986ce7ec@k13g2000hse.googlegroups.com> On Sep 25, 3:36 pm, "Dmitry S. Makovey" wrote: > Aaron "Castironpi" Brady wrote: > >> I kept this part of the problem out of this discussion as I'm pretty sure > >> I can fill those in once I figure out the basic problem of > >> auto-population of proxy methods since for each class/method those are > >> going to be nearly identical. If I can autogenerate those on-the-fly I'm > >> pretty sure I can add some extra-logic to them as well including > >> signature change where A::bmethod(self,c,x) would become > >> A::bmethod(self,x) etc. > > > Do you want to couple instances or classes together? > > It would be nice to have objects of B, C and D classes not knowing that they > are proxied (as they are used on their own too, not only inside of A > objects). I'm not sure if the approach below deals with all the issues, but one thing it does is decouple completely the proxied objects from the proxy: #======== usage ================================================================ from proxies import Proxy class B(object): def __init__(self): self.val = 'bval' def bmethod(self,n): print "B::bmethod",n def bmethod2(self,n,m): print "B::bmethod2",n,m class C(object): def __init__(self): self.val = 'cval' def cmethod(self,x): print "C::cmethod",x def cmethod2(self,x,y): print "C::cmethod2",x,y cattr = 4 class A(Proxy): DelegateMap = { 'bmethod' : B, 'bmethod2': B, 'cmethod': C, # do NOT delegate C.cmethod2 #'cmethod2': C, 'cattr' : C, } def __init__(self, b, c): print "init A()" # must call Proxy.__init__(*delegates) super(A,self).__init__(b,c) def amethod(self,a): print "A::mymethod",a if __name__ == '__main__': a = A(B(), C()) a.amethod('foo') # test bounded methods a.bmethod('foo') a.bmethod2('bar','baz') a.cmethod('foo') try: a.cmethod2('bar','baz') except Exception, ex: print ex # works for unbound methods too A.bmethod(a,'foo') A.bmethod2(a,'bar','baz') A.cmethod(a, 'foo') try: A.cmethod2(a,'bar','baz') except Exception, ex: print ex # non callable attributes print A.cattr #====== output ================================== init A() A::mymethod foo B::bmethod foo B::bmethod2 bar baz C::cmethod foo 'A' object has no attribute 'cmethod2' B::bmethod foo B::bmethod2 bar baz C::cmethod foo type object 'A' has no attribute 'cmethod2' 4 #======== proxies.py ========================= class _ProxyMethod(object): def __init__(self, name): self._name = name def unbound(proxy, *args, **kwds): method = proxy._get_target_attr(name) return method(*args, **kwds) self._unbound = unbound def __get__(self, proxy, proxytype): if proxy is not None: return proxy._get_target_attr(self._name) else: return self._unbound class _ProxyMeta(type): def __new__(meta, name, bases, namespace): for attrname,cls in namespace.get('DelegateMap', {}).iteritems(): if attrname not in namespace: attr = getattr(cls, attrname) if callable(attr): namespace[attrname] = _ProxyMethod(attrname) else: namespace[attrname] = attr return super(_ProxyMeta,meta).__new__(meta, name, bases, namespace) class Proxy(object): __metaclass__ = _ProxyMeta def __init__(self, *delegates): self._cls2delegate = {} for delegate in delegates: cls = type(delegate) if cls in self._cls2delegate: raise ValueError('More than one %s delegates were given' % cls) self._cls2delegate[cls] = delegate def _get_target_attr(self, name): try: cls = self.DelegateMap[name] delegate = self._cls2delegate[cls] return getattr(delegate, name) except (KeyError, AttributeError): raise AttributeError('%r object has no attribute %r' % (self.__class__.__name__, name)) HTH, George From jason at tishler.net Fri Sep 19 14:08:23 2008 From: jason at tishler.net (Jason Tishler) Date: Fri, 19 Sep 2008 14:08:23 -0400 Subject: Problem with Python shell through Cygwin Screen (Python/Vim/Screen combo) In-Reply-To: <1e357c83-b53b-4587-a4d3-5327d1762341@k13g2000hse.googlegroups.com> References: <1e357c83-b53b-4587-a4d3-5327d1762341@k13g2000hse.googlegroups.com> Message-ID: <20080919180823.GA624@tishler.net> Ant, On Fri, Sep 19, 2008 at 03:10:10AM -0700, Ant wrote: > [snip] > This works great in Linux, and also in Windows using the Cygwin build > of Python, but when you call: > > screen -S py -s python > > using the Windows build of Python, the shell just hangs. Does anyone > know if this is a known issue with screen/Python, or if there is a > workaround, as I'd prefer to have just a single Python instance > installed rather than having Cygwin python and windows Python both > installed. There are known issues when trying to run a Windows program that directly accesses the console under Cygwin. For example: http://mail.python.org/pipermail/python-list/2004-June/266661.html AFAICT, you will have to use Cygwin Python with screen. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From fredrik at pythonware.com Thu Sep 18 07:02:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 Sep 2008 13:02:49 +0200 Subject: PEP proposal optparse In-Reply-To: References: Message-ID: James Mills wrote: > As you can see (as long as you're > reading this in fixed-width fonts) > it _is_ very readable. given that it only relies on indentation from the left margin, it's no less readable in a proportional font (unless you're using an font with variable-width spaces, that is ;-). From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 20:12:03 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 00:12:03 GMT Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <00e58b46$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 16:22:31 -0700, Alex Snast wrote: > That's a lot of responses guys. Thanks a lot i think i got it. Another > question, are there any pointers in python (or iterators) for when i use > a data structure that doesn't support random access? That surely depends on the data structure. Assume it supports sequential access: data[0], data[1], data[2], etc in that order without skipping or going backwards. Then you can simply do this: for item in data: process(item) which is the equivalent of this: try: i = 0 while True: process(data[i]) i += 1 except IndexError: pass # we're done The data structure might not support sequential indexing, but still support sequential access: for item in iter(data): process(item) If the data structure is some sort of binary tree, then you would use a standard tree-walking algorithm, something like this: def prefix_traversal(node): process(node.info) prefix_traversal(node.left) prefix_traversal(node.right) and similarly for infix and postfix. (Although the specific names 'left', 'right', 'info' are arbitrary.) If you don't have any specific knowledge of how to iterate over the data structure, then try reading the docs *wink*. -- Steven From callen314 at gmail.com Tue Sep 23 17:17:09 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 23 Sep 2008 14:17:09 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <00e816f4$0$20303$c3e8da3@news.astraweb.com> <6602abad-3c12-4c0c-b41d-95f79cebdc31@y21g2000hsf.googlegroups.com> Message-ID: <698ac52a-c290-451d-944d-a9004161a516@n38g2000prl.googlegroups.com> > > > Usegrammers? > usegrammers are just those that use grammars, but misspell it. From deets at nospam.web.de Sun Sep 7 10:53:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 07 Sep 2008 16:53:15 +0200 Subject: atomic section in code In-Reply-To: References: Message-ID: <6ii86rFqgj3vU1@mid.uni-berlin.de> Hendrik van Rooyen schrieb: > Fredrik Lundh wrote: > >> sounds like he wants/needs non-cooperative, mandatory locking. > > Could one get there using ctypes to disable interrupts? Not as such, ctypes can't execute arbitrary machine code. But of course you can create a C-lib that does what you want (IF it can be done, that is..), and wrap that. > Cross Platform? Certainly not. > I can think of lots of hassles, starting with permissions > to use the privileged instructions. I don't think there is a chance for this without major system tinkering. Under Linux, you could create a real time thread so highly prioritized that it won't yield any time to any other scheduler. And in a kernel-module, you can call cli (or whatever the needed call is). But this will most probably break your system. diez From tom.willis at gmail.com Wed Sep 24 18:47:18 2008 From: tom.willis at gmail.com (Thomas G. Willis) Date: Wed, 24 Sep 2008 15:47:18 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: On Sep 24, 4:59?pm, Duncan Booth wrote: ... > I haven't yet had occasion to use LINQ in anger yet, so I have no idea > whether its an idea to love or to hate. I do think it is good that C# has > effectively sprouted list comprehensions (not to mention anonymous types > and type inferencing) and I expect there may be some aspects worth looking > at for Python but I think they are more likely to lead to itertools > functions than extensions to syntax. My thoughts exactly when I first looked at it. "Hey C# NOW has list comprehensions!!! SWEET!!!" As I understand it LINQ is libraries(System.Data.Linq.dll, System.XML.Linq.dll) + syntactic sugar, i wouldn't call that a change to the language. The addition of lambdas and functions as first class objects however, that was indeed a language change, and it was a change for the better that makes LINQ possible, (also makes writing delegates less cumbersome). To someone other than a C# person, these features are not new or revolutionary, it's just C# catching up. Kudos to them for getting there before java. After some more thought on what might conceivably be missing from python that LINQ has, that someone might want is the equivalent of System.XML.Linq.dll, and I can't see any reason why someone couldn't write it with the exception that there doesn't seem to be a definitive XML lib for python, meaning generally regarded as the best. That in my mind would be a prerequisite. But if someone wrote both the XML lib with the LINQ-ish syntax, maybe it would become the definitive XML lib. Again, I personally don't see myself using XML and thus needing that unless my hand was forced by some business requirement that dictated I use XML, I would not use it if I had a choice. The SQL LiNQ-ish though, I think every python ORM has that covered to a degree, and I use that quite a bit. From michele.simionato at gmail.com Fri Sep 5 06:21:52 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 5 Sep 2008 03:21:52 -0700 (PDT) Subject: derived classes and __getattr__ References: <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> Message-ID: <0521db5b-aad1-4a2f-b0cf-5d9922ea8f57@f63g2000hsf.googlegroups.com> On Sep 5, 11:46?am, Alexandru Mosoi wrote: > I have another small problem. now, > d.third('blah') doesn't work because instance d doesn't have 'third' > attribute. I was expecting derived class to inherit the metaclass as > well, but it didn't. Yep, it is explained here: https://www.ibm.com/developerworks/linux/library/l-pymeta2/ It would help if you told us the real problem you are trying to solve. From marek at xivilization.net Wed Sep 3 05:26:25 2008 From: marek at xivilization.net (Marek Kubica) Date: Wed, 3 Sep 2008 09:26:25 +0000 (UTC) Subject: pyparsing: match empty line References: <9f838a29-2e2e-4646-9026-36d3b8a49fce@c58g2000hsc.googlegroups.com> Message-ID: Hi, First of all a big thank you for your excellent library and of course also for your extensive and enlightening answer! > 1) Well done in resetting the default whitespace characters, since you > are doing some parsing that is dependent on the presence of line ends. > When you do this, it is useful to define an expression for end of line > so that you can reference it where you explicitly expect to find line > ends: > > EOL = LineEnd().suppress() Ok, I didn't think about this. But as my program is not only a parser but a long-running process and setDefaultWhitespace modifies a global variable I don't feel too comfortable with it. I could set the whitespace on every element, but that is as you surely agree quite ugly. Do you accept patches? I'm thinking about some kind of factory-class which would automatically set the whitespaces: >>> factory = TokenFactory(' \t\r') >>> word = Factory.Word(alphas) >>> That way, one wouldn't need to set a grobal value which might interfere with other pyparsers running in the same process. > parser = OneOrMore(watchname ^ pagebreak ^ leaveempty ^ EOL) > > This will now permit the second test to pass. Right. Seems that working with whitespace requires a bit better understanding than I had. > 3) Your definition of pagebreak looks okay now, but I don't understand > why your test containing 2 blank lines is only supposed to generate a > single . No, it should be one per blank line, now it works as expected. > 4) leaveempty probably needs this parse action to be attached to it: > > leaveempty = > Literal('EMPTY').setParseAction(replaceWith('')) I added this in the meantime. replaceWith is really a handy helper. > parser = OneOrMore(watchname | pagebreak | leaveempty | EOL) > > '|' operators generate MatchFirst expressions. MatchFirst will do > short-circuit evaluation - the first expression that matches will be the > one chosen as the matching alternative. Okay, adjusted it. > If you have more pyparsing questions, you can also post them on the > pyparsing wiki - the Discussion tab on the wiki Home page has become a > running support forum - and there is also a Help/Discussion mailing > list. Which of these two would you prefer? Thanks again, it works now just as I imagined! regards, Marek From mensanator at aol.com Thu Sep 4 01:20:43 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 3 Sep 2008 22:20:43 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> Message-ID: <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> On Sep 3, 8:30?pm, Steven D'Aprano wrote: > On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: > >>>> sum([]) > > 0 > > > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It > > should return None or throw an exception like sum([None,1]) does. > > You're wrong, because 99.9% of the time when users leave a blank cell in > Excel, they want it to be treated as zero. Then 99.9% of users want the wrong thing. Microsoft knows that this is a bug but refuses to fix it to prevent breaking legacy documents (probably dating back to VisiCalc). When graphimg data, a missing value should be interpreted as a hole in the graph +------+ +--+------+------+-----+ and not evaluated as 0 +------+ +--+------+------+-----+ \ / \ / \ / \ / \ / \+/ (depending on the context of the graph, of course). And Microsoft provides a workaround for graphs to make 0's appear as holes. Of course, this will cause legitimate 0 values to disappear, so the workaround is inconsistent. > Spreadsheet sum() is not the > same as mathematician's sum, which doesn't have a concept of "blank > cells". (But if it did, it would treat them as zero, since that's the > only useful thing and mathematicians are just as much pragmatists as > spreadsheet users.) The Excel code does the right thing, and your "pure" > solution would do the unwanted and unexpected thing and is therefore > buggy. Apparently, you don't use databases or make surface contours. Contour programs REQUIRE that blanks are null, not 0, so that the Kriging algorithm interpolates around the holes rather than return false calculations. Excel's treatment of blank cells is inconsistent with Access' treatment of Nulls and therefore wrong, anyway you slice it. Math isn't a democracy, what most people want is irrelevant. I don't pull these things out of my ass, it's real world stuff I observe when I help CAD operators and such debug problems. Maybe you want to say a bug is when it doesn't do what the author intended, but I say if what the intention was is wrong, then a perfect implentation is still a bug because it doesn't do what it's supposed to do. > > Bugs are defined by "does the code do what the user wants it to do?", not > "is it mathematically pure?". ReallY? So you think math IS a democracy? There is no reason to violate mathematical purity. If I don't get EXACTLY the same answer from Excel, Access, Mathematica and Python, then SOMEBODY is wrong. It would be a shame if that somebody was Python. > The current behaviour of sum([]) does the > right thing for the 99% of the time when users expect an integer. Why shouldn't the users expect an exception? Isn't that why we have try:except? Maybr 99% of users expect sum([])==0, but _I_ expect to be able to distinguish an empty list from [4,-4]. > And the > rest of the time, they have to specify a starting value for the sum > anyway, and so sum([], initial_value) does the right thing *always*. So if you really want [] to be 0, why not say sum([],0)? Why shouldn't nothing added to nothing return nothing? Having it evaluate to 0 is wrong 99.9% of the time. > > The only time it does the wrong thing[1] is when you forget to pass an > initial value but expect a non-numeric result. And that's the > programmer's error, not a function bug. > > [1] I believe it also does the wrong thing by refusing to sum strings, > but that's another story. > > -- > Steven From aaron.hildebrandt at gmail.com Wed Sep 10 13:45:02 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 10:45:02 -0700 (PDT) Subject: Reading binary data References: <508e31d9-daab-4346-9441-55cc47f7c1f4@m44g2000hsc.googlegroups.com> Message-ID: <54d64616-b86c-45bd-a8b5-4332faa5a73d@a70g2000hsh.googlegroups.com> > CORRECTION: '3cII' should be '3sII'. Even with the correction, I'm still getting the error. From wuwei23 at gmail.com Thu Sep 4 22:08:49 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 4 Sep 2008 19:08:49 -0700 (PDT) Subject: Issue warning if no "return" in function? References: Message-ID: On Sep 4, 8:05?pm, Poster28 wrote: > What would you suggest to check python programs for non-syntax error. > One example I could think of that one might forget to "return" a value from > a function. > > How could I check for these and maybe other mistakes? I really recommend getting into the habit of writing tests for all of your programs. I like the test-driven approach; write a test that reflects the behaviour you want and -then- write your code. If it doesn't succeed, there's most likely something wrong with your code. Test-Driven Development in Python: http://www.onlamp.com/pub/a/python/2004/12/02/tdd_pyunit.html nose (a very nice test runner): http://code.google.com/p/python-nose/ From kw at codebykevin.com Tue Sep 9 14:11:57 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 09 Sep 2008 14:11:57 -0400 Subject: How to record audio from Python on Mac? In-Reply-To: References: Message-ID: <48C6BC6D.8040207@codebykevin.com> skip at pobox.com wrote: > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > casting a broader net.) > > Can I easily control audio record/playback from Python on my Mac? I know > zip about audio recording or about Apple APIs via Python. Pointers to > simple examples would be much appreciated. > > Thanks, > > Skip You can probably access this functionality via PyObjC--it provides access to the Cocoa frameworks. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From rcdailey at gmail.com Thu Sep 4 19:48:55 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Sep 2008 18:48:55 -0500 Subject: Case-insensitive string compare? In-Reply-To: <200809050059.17038.maric@aristote.info> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> <496954360809041537gee8d333xfa1f75b165a8d6d1@mail.gmail.com> <47c890dc0809041547td20794fpf58dc93e30c027f2@mail.gmail.com> <200809050059.17038.maric@aristote.info> Message-ID: <496954360809041648u491ca482ia5e6c73840a7eb24@mail.gmail.com> On Thu, Sep 4, 2008 at 5:59 PM, Maric Michaud wrote: > Le Friday 05 September 2008 00:47:00 Chris Rebert, vous avez ?crit : > > > > Then store the string in its original case in the value part of the > > key-value pair: > > > > stage_map[key.lower()] = (key,whatever) > > > > "premature optimization is the root of all evil" > > I don't recall the OP wanted a (a bit) faster solution to his problem in > counterpart of memory loss and syntax complication. > > If the OP's proposal seems already messy, how about ths one : > if lib.lower() not in ( e[0] for e in stage_map.items() ) : > ... Thanks everyone for your help. I'm not opposed to using [key.lower() for key in stage_map] at all, I was just curious to see if there were any cleaner alternatives. It looks like that is what I'll be using. I'm not familiar with how python works internally, but coming from C++ it seems like "remaking" the map would be slow. However, speed is not my main concern in my particular situation, I'm just curious to learn more about python. Thanks again everyone. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ocgstyles at gmail.com Tue Sep 2 13:40:07 2008 From: ocgstyles at gmail.com (ocgstyles at gmail.com) Date: Tue, 2 Sep 2008 10:40:07 -0700 (PDT) Subject: Problems when working with different timezones Message-ID: <4a56c18d-2132-45f5-a750-e0a41bf14248@f36g2000hsa.googlegroups.com> Here's some Python code executed on Red Hat 3.4 web server located in Mountain time (MDT). You'll notice that the time after setting the timezone to Eastern time (EST), the time is incorrectly 6 hours ahead, when it should only be 3. Python 2.5 (r25:51908, Mar 23 2007, 14:22:20) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime, os >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 11, 25, 35, 39856) >>> os.environ['TZ']='America/New_York' >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 17, 26, 0, 703537) Here's the same thing executed on an Ubuntu box in EST. I alter the timezone to a MDT and it works as one would expect. Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import datetime, os >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 13, 11, 6, 438123) >>> os.environ['TZ'] = 'America/Denver' >>> datetime.datetime.today() datetime.datetime(2008, 9, 2, 11, 11, 21, 43602) What could be the reason for this failing on Red Hat? Keith From bj_666 at gmx.net Tue Sep 30 10:34:31 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Sep 2008 14:34:31 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6ke1i8F7dmkkU2@mid.uni-berlin.de> Message-ID: <6kernnF7dmkkU3@mid.uni-berlin.de> On Tue, 30 Sep 2008 15:42:58 +0200, Ivan Reborin wrote: > On 30 Sep 2008 07:07:52 GMT, Marc 'BlackJack' Rintsch > wrote: >>===== >>from __future__ import with_statement from functools import partial >>from itertools import islice >>from pprint import pprint >> >> >>def read_group(lines, count): >> return [map(int, s.split()) for s in islice(lines, count)] >> >>def main(): >> with open('test.txt') as lines: >> lines = (line for line in lines if line.strip()) >> result = list(iter(partial(read_group, lines, 3), list())) >> pprint(result, width=30) >> >>if __name__ == '__main__': >> main() >>===== > > I'm afraid I must admit I find the code above totally uncomprehesible (I > can't even see where the array here is mentioned - "result"?) and > inpractical for any kind of engineering practice I had in mind. Learn Python then to understand that code. ;-) There is no array. The data type is called "list" in Python, so `result` is a nested list. And in Python it quite unusual to build lists by creating them with the final size filled with place holder objects and then fill the real values in. Instead lists are typically created by appending values to existing lists, using list comprehension or the `list()` function with some iterable object. Typical Python code tries to minimize the use of index variables. Python is not Fortran (or C, or Pascal, ?). > Does python, perchance, have some wrapper functions or something, which > would allow one to load an array in a more natural "technical" way ? > Like something mentioned above in my post (now deleted) ? > > Also, is there a way to change counter for arrays to go from 0 to 1 ? You can write your own sequence type but that would be odd because the rest of the language expects zero as the first index, so you will be constantly fighting the language by adding or subtracting 1 all the time at the "border" between your custom sequence type and the the rest of Python. Ciao, Marc 'BlackJack' Rintsch From graphaelli at gmail.com Fri Sep 26 02:55:50 2008 From: graphaelli at gmail.com (graph) Date: Thu, 25 Sep 2008 23:55:50 -0700 (PDT) Subject: Module import path when embedding python in C Message-ID: <913fe5fc-9b8e-49c6-b740-5d6bb74abc97@s20g2000prd.googlegroups.com> Per http://mail.python.org/pipermail/python-list/2008-September/506206.html something like this (plus error handling) seems to be the right way to add to sys.path when embedding python in C: PyObject *sys_path = PySys_GetObject("path"); PyObject *path = PyString_FromString("/your/path"); PyList_Append(sys_path, path); Does anyone know why PySys_GetObject wasn't documented until somewhat recently (http://bugs.python.org/issue1245) if it has been part of the system module interface since at least Python 1.5.2? Is it not supposed to be used? What's the difference the above and importing the sys module and then doing the append? Thanks in advance. -g From mathieu.prevot at gmail.com Thu Sep 4 03:25:37 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 09:25:37 +0200 Subject: use str as variable name Message-ID: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> Hi, I have a program that take a word as argument, and I would like to link this word to a class variable. eg. class foo(): width = 10 height = 20 a=foo() arg='height' a.__argname__= new_value rather than : if arg == 'height': a.height = new_value elif arg == 'width'; a.width = new_value Can I do this with python ? How ? Thanks, Mathieu From harrrrpo at gmail.com Fri Sep 5 08:58:30 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Fri, 5 Sep 2008 15:58:30 +0300 Subject: [ANN] PyDM 1.1 Message-ID: <538050a90809050558x4e08605dhfac219a56d67db97@mail.gmail.com> PyDM 1.1 is released and now available from http://sourceforge.net/projects/pycdm/ ---- PyDM is a Multi-Threaded Download Manager in Python , this is the second release Features :- 1) Http handling at socket level no external http libs 2) Two interfaces with core , one in Qt and the other is Console 3) Download Pausing (Qt Interface) 4) Download Resume (Qt Interface) 5) Saving Downloaded Files in a list (Powered by SQLite) 6) Configuration file (PyDM.ini) for number of threads,Temp Directory and download directory 7) Displaying Rate/Status/Url/Filename for each downloaded file Regards , Mohamed Yousef From michel at nospam.please Mon Sep 15 15:03:33 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:03:33 +0200 Subject: environment variable issue In-Reply-To: References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <48ceb185$0$2847$ba620e4c@news.skynet.be> Fredrik Lundh a ?crit : > this might help: > > http://mail.python.org/pipermail/python-list/2008-September/507933.html Yes, it helps. Thanks > > (scanning the subjects of recent and ongoing threads before posting is > always a good idea). I did search the web but didn't find anything related to the problem I had. I didn't think searching the newsgroups, though. Thanks for your help, Michel -- Michel Leunen http://linux.leunen.com From fredrik at pythonware.com Mon Sep 1 08:47:03 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 01 Sep 2008 14:47:03 +0200 Subject: Know if a object member is a method In-Reply-To: <27308d500809010542n766bd9fmfdd9775ad3fdabf7@mail.gmail.com> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> <00cbd80b$0$20302$c3e8da3@news.astraweb.com> <27308d500809010542n766bd9fmfdd9775ad3fdabf7@mail.gmail.com> Message-ID: Luca wrote: > Yes, this helps a lot. In facts I need to do something like a language parser. a *parser* that works on object structures created by executing a Python program? From gagsl-py2 at yahoo.com.ar Mon Sep 22 05:37:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 22 Sep 2008 06:37:16 -0300 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09F2@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09F3@AWMAIL04.belcan.com> Message-ID: En Sun, 21 Sep 2008 19:42:10 -0300, Blubaugh, David A. escribi?: > Sir, > Thank you for your reply. This is as to how I developed my .pyd file. > I entered the following commands within my MS-DOS prompt within Windows > XP: > > C:\python25\Scripts> C:\python25\python f2py.py -c --fcompiler=gnu95 > --compiler=mingw32 -m hello hello.f90 > > I am using the gfortran compiler, that was prescribed to use, as well > as, the required commands on the following website: > > http://www.scipy.org/F2PY_Window > > > I comes down to that yes, I am able to generate a .pyd file, which was > generated by f2py. However, when I tried to import this file into my > python script program I was given the following error: > error 193?? > I do not know as to what I am doing incorrectly, since I am generating a > .pyd file by f2py? If I am doing anything that is incorrect, then why > am I EVEN ABLE TO GENERATE A .PYD FILE IN THE FIRST PLACE??? Any Help > will be greatly appreciated!!!!! Below there is a transcript of a compile session. I've used a somewhat old version of mingw and g77, scipy 1.1.1, python 2.5.2: C:\TEMP\for>dir /b dscal.for C:\TEMP\for>type dscal.for SUBROUTINE DSCAL(N, ALPHA, X) * * X <- ALPHA * X * INTEGER N DOUBLE PRECISION ALPHA DOUBLE PRECISION X(*) DO I = 1, N X(I) = ALPHA * X(I) END DO WRITE (*,*) ALPHA RETURN END C:\TEMP\for>g77 --version GNU Fortran (GCC) 3.4.2 (mingw-special) Copyright (C) 2004 Free Software Foundation, Inc. GNU Fortran comes with NO WARRANTY, to the extent permitted by law. You may redistribute copies of GNU Fortran under the terms of the GNU General Public License. For more information about these matters, see the file named COPYING or type the command `info -f g77 Copying'. C:\TEMP\for>python -V Python 2.5.2 C:\TEMP\for>python c:\apps\python25\scripts\f2py.py -v 2_5590 C:\TEMP\for>python c:\apps\python25\scripts\f2py.py -c -m dscal dscal.for [...lots of output...] Found executable c:\apps\mingw\bin\g77.exe gnu: no Fortran 90 compiler found customize Mingw32CCompiler using scons Found executable c:\apps\mingw\bin\g++.exe [...] gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes -Ic:\docume~1\gabriel\config~1\tem p\tmpoygjnk\src.win32-2.5 -IC:\Apps\Python25\lib\site-packages\numpy\core\includ e -IC:\Apps\Python25\include -IC:\Apps\Python25\PC -c c:\docume~1\gabriel\config ~1\temp\tmpoygjnk\src.win32-2.5\dscalmodule.c -o c:\docume~1\gabriel\config~1\te mp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\dsca lmodule.o gcc -mno-cygwin -O2 -Wall -Wstrict-prototypes -Ic:\docume~1\gabriel\config~1\tem p\tmpoygjnk\src.win32-2.5 -IC:\Apps\Python25\lib\site-packages\numpy\core\includ e -IC:\Apps\Python25\include -IC:\Apps\Python25\PC -c c:\docume~1\gabriel\config ~1\temp\tmpoygjnk\src.win32-2.5\fortranobject.c -o c:\docume~1\gabriel\config~1\ temp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\fo rtranobject.o [...] c:\apps\mingw\bin\g77.exe -g -Wall -mno-cygwin -g -Wall -mno-cygwin -shared c:\d ocume~1\gabriel\config~1\temp\tmpoygjnk\Release\docume~1\gabriel\config~1\temp\t mpoygjnk\src.win32-2.5\dscalmodule.o c:\docume~1\gabriel\config~1\temp\tmpoygjnk \Release\docume~1\gabriel\config~1\temp\tmpoygjnk\src.win32-2.5\fortranobject.o c:\docume~1\gabriel\config~1\temp\tmpoygjnk\Release\dscal.o -Lc:\apps\mingw\lib -Lc:\apps\mingw\lib\gcc\mingw32\3.4.2 -LC:\Apps\Python25\libs -LC:\Apps\Python25 \PCBuild -lpython25 -lg2c -o .\dscal.pyd [...] C:\TEMP\for>dir /b dscal.for dscal.pyd C:\TEMP\for>python Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> import numpy py> import dscal py> print dscal.dscal.__doc__ dscal - Function signature: dscal(n,alpha,x) Required arguments: n : input int alpha : input float x : input rank-1 array('d') with bounds (*) py> v = numpy.array([1,2,3,4,5], 'd') py> print v [ 1. 2. 3. 4. 5.] py> dscal.dscal(len(v), 2, v) 2. py> print v [ 2. 4. 6. 8. 10.] -- Gabriel Genellina From ptmcg at austin.rr.com Wed Sep 3 09:12:47 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 3 Sep 2008 06:12:47 -0700 (PDT) Subject: pyparsing: match empty line References: <9f838a29-2e2e-4646-9026-36d3b8a49fce@c58g2000hsc.googlegroups.com> Message-ID: <0df1f752-ee27-4eeb-ab63-1566ed9a3e24@k37g2000hsf.googlegroups.com> On Sep 3, 4:26 am, Marek Kubica wrote: > Hi, > > First of all a big thank you for your excellent library and of course > also for your extensive and enlightening answer! > I'm glad pyparsing has been of help to you. Pyparsing is building its own momentum these days. I have a new release in SVN that I'll put out in the next week or so. > Ok, I didn't think about this. But as my program is not only a parser but > a long-running process and setDefaultWhitespace modifies a global > variable I don't feel too comfortable with it. Pyparsing isn't really all that thread-friendly. You definitely should not have multiple threads using the same grammar. The approaches I've seen people use in multithread applications are: 1) synchronize access to a single parser across multiple threads, and 2) create a parser per-thread, or use a pool of parsers. Pyparsing parsers can be pickled, so a quick way to reconstitute a parser is to create the parser at startup time and pickle it to a string, then unpickle a new parser as needed. > I could set the whitespace > on every element, but that is as you surely agree quite ugly. Do you > accept patches? I'm thinking about some kind of factory-class which would > automatically set the whitespaces: > > >>> factory = TokenFactory(' \t\r') > >>> word = Factory.Word(alphas) > > That way, one wouldn't need to set a grobal value which might interfere > with other pyparsers running in the same process. I tried to prototype up your TokenFactory class, but once I got as far as implementing __getattribute__ to return the corresponding pyparsing class, I couldn't see how to grab the object generated for that class, and modify its whitespace values. I did cook up this, though: class SetWhitespace(object): def __init__(self, whitespacechars): self.whitespacechars = whitespacechars def __call__(self,pyparsing_expr): pyparsing_expr.setWhitespace(self.whitespacechars) return pyparsing_expr noNLskipping = SetWhitespace(' \t\r') word = noNLskipping(Word(alphas)) I'll post this on the wiki and see what kind of comments we get. By the way, setDefaultWhitespace only updates global variables that are used at parser definition time, *not* at parser parse time. So, again, you can manage this class attribute at the initialization of your program, before any incoming requests need to make use of one parser or another. > > 4) leaveempty probably needs this parse action to be attached to it: > > > leaveempty = > > Literal('EMPTY').setParseAction(replaceWith('')) > > I added this in the meantime. replaceWith is really a handy helper. After I released replaceWith, I received a parser from someone who hadn't read down to the 'R's yet in the documentation, and he implemented the same thing with this simple format: leaveempty = Literal('EMPTY').setParseAction(lambda : '') These are pretty much equivalent, I was just struck at how easy Python makes things for us, too! > > If you have more pyparsing questions, you can also post them on the > > pyparsing wiki - the Discussion tab on the wiki Home page has become a > > running support forum - and there is also a Help/Discussion mailing > > list. > > Which of these two would you prefer? > They are equivalent, I monitor them both, and you can browse through previous discussions using the Discussion tab online threads, or the mailing list archive on SF. Use whichever is easier for you to work with. Cheers, and Welcome to Pyparsing! -- Paul From nick at craig-wood.com Wed Sep 24 06:30:06 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 24 Sep 2008 05:30:06 -0500 Subject: How can I use a PyObject in C++? References: Message-ID: lixinyi.23 at gmail.com wrote: > for example: > #include > > void exec_python_code(int arg, char** argv) > { > Py_Initialize(); > Py_Main(argc,argv); > Py_Finalize(); > } > > What I would like to know is: > after Py_Main(argc,argv); > > How do I get every variable in python space, > say a=[1,2,3,'Hello World',[2,3]] > b=['xx','xxx','ffff',0.1234] , and use them in C++? > > any sample code? > Thanks in advance! Here is a bit of code I wrote yesterday which calls a python function imported from a module and processes the result. It would only be a dozen lines if it weren't for the error handling! The code was compiled with a C++ compiler. Read the python C API docs for more info (these work fine in C++ also) http://docs.python.org/api/api.html Note it is very important to keep track of who owns which object - hence the comments about /* new ref */ and /* borrowed */ Yes it uses goto... I find it is the easiest way of error handling in C and making sure you don't leak objects on error conditions ;-) /* Call the python function MyModule.SubModule.my_function() and return the result as a malloc-ed string or 0 if there was a problem or my_function returned None */ char *my_function(void) { char *my_result = 0; PyObject *module = 0; PyObject *result = 0; PyObject *module_dict = 0; PyObject *func = 0; module = PyImport_ImportModule((char *)"MyModule.SubModule"); /* new ref */ if (module == 0) { PyErr_Print(); printf("Couldn't find python module MyModule.SubModule"); goto out; } module_dict = PyModule_GetDict(module); /* borrowed */ if (module_dict == 0) { PyErr_Print(); printf("Couldn't find read python module MyModule.SubModule"); goto out; } func = PyDict_GetItemString(module_dict, "my_function"); /* borrowed */ if (func == 0) { PyErr_Print(); printf("Couldn't find MyModule.SubModule.my_function"); goto out; } result = PyEval_CallObject(func, NULL); /* new ref */ if (result == 0) { PyErr_Print(); printf("Couldn't run MyModule.SubModule.my_function"); goto out; } else if (result == Py_None) { printf("MyModule.SubModule.my_function returned None"); goto out; } my_result = PyString_AsString(result); /* borrowed */ if (my_result == 0) { PyErr_Print(); printf("Couldn't read result from MyModule.SubModule.my_function"); goto out; } my_result = strdup(my_result); /* keep in our own memory */ out:; Py_XDECREF(result); Py_XDECREF(module); return my_result; } -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bdesth.quelquechose at free.quelquepart.fr Fri Sep 12 13:40:08 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 Sep 2008 19:40:08 +0200 Subject: book example confusion In-Reply-To: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> References: <8f34d5a2-12e0-421e-a938-e7978e1a873f@f36g2000hsa.googlegroups.com> Message-ID: <48cac567$0$7824$426a74cc@news.free.fr> byron a ?crit : > I am reading o'reilly's learning python (great book), but i came > across an example (pg 291, pdf) that I am not quite understanding the > reasoning for the author's explanation: > > if f1() or f2(): > > The author states that do to the nature of that expression, if f1() > returns True, f2() will not be evaluated.. which makes sense. His > quote: > > "Here, if f1 returns a true (or nonempty) value, Python will > never run f2." > > He then states: > > "To guarantee that both functions will be run, call them > before the 'or':" > > tmp1, tmp2 = f1(), f2() > if tmp1 or tmp2: > > Being that each function is an object, a name assignment to > (tmp1,tmp2) doesn't actually evaluate or run the function itself until > the name is called.. It (well... they) is (are) actually called. The parens are the call operator. From mal at egenix.com Thu Sep 4 04:31:45 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 04 Sep 2008 10:31:45 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <48BF9CF1.70100@egenix.com> On 2008-09-04 07:49, Kay Schluehr wrote: > 3) Following the public rumor mill and the latest hype RIA i.e. the > merge of web- and desktop applications with systems like Adobe AIR, > JavaFX, Google Gears and MS Silverlight is the future of frontend > development. With the exception of IronPython and Silverlight, Python > hasn't even entered this game and no one knows if it ever will. Actually, it has already and quite some time ago: http://www.artima.com/weblogs/viewpost.jsp?thread=208528 The recipe is simple: use Python for the business logic, database interfacing, etc and have it talk to a Flex front-end via XML-RPC or REST. As a nice side-effect, this also results in a better separation between GUI and backend, effectively making the solution future-proof and easy to adapt to other front-end technologies. We've been working with this approach for almost a year now and so far never had to look back. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 04 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From bearophileHUGS at lycos.com Mon Sep 29 17:41:14 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 14:41:14 -0700 (PDT) Subject: Converting a strng to an anonymous function References: Message-ID: On Sep 29, 11:25 pm, Nathan Seese wrote: > I'm writing a program to sort files with arbitrary python code. The > method I'm using for that is to pass sort an anonymous function taken > from the arguments. I'm wondering how to change a raw string into an > anonyous function. Is this enough for you? >>> L = [1, -5, 7, -9] >>> sorted(L, key=abs) [1, -5, 7, -9] >>> func = "abs" >>> sorted(L, key=eval(func)) [1, -5, 7, -9] >>> func = "abs(x)" >>> sorted(L, key=lambda x: eval(func)) [1, -5, 7, -9] Bye, bearophile From ranim81 at gmail.com Mon Sep 1 08:28:17 2008 From: ranim81 at gmail.com (raju) Date: Mon, 1 Sep 2008 05:28:17 -0700 (PDT) Subject: about computer tips inonline click here Message-ID: http://www.moneymaking4.blogspot.com/ From gminick at bzt.bzt Wed Sep 3 06:44:38 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 3 Sep 2008 10:44:38 +0000 (UTC) Subject: python - mechanize/browser/POST issue References: Message-ID: On Tue, 2 Sep 2008 19:39:05 -0700, bruce wrote: > using mechanize/Browser, i can easily do a url/get, and process submitting a > form that uses a GET as the action. however, I'm not quite sure how to > implement the submittal of a form, that uses the POST action. > > Anyone have a short chunk of code that I can observer, that uses the > mechanize.Browser implentation? Take a look at the bottom of this post: http://mail.python.org/pipermail/python-list/2006-June/390037.html It seems that submit does the job. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bearophileHUGS at lycos.com Sat Sep 20 20:38:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 20 Sep 2008 17:38:15 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: Christian Heimes: > Unless you have specific needs for highly specialized data types, use lists. There's also the collections.deque for other related purposes. (I suggest people willing to look at some nice C code to read the sources of deque, Hettinger has created some refined code, very readable). Bye, bearophile From drobinow at gmail.com Thu Sep 11 12:42:05 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Thu, 11 Sep 2008 09:42:05 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> Message-ID: <09345856-9a44-449c-9ee0-6254c573847e@b1g2000hsg.googlegroups.com> On Sep 11, 11:13?am, "carriere.jonat... at gmail.com" wrote: > On Sep 11, 4:19?pm, Fredrik Lundh wrote: > > > > > carriere.jonat... at gmail.com wrote: > > > ?> I wonder if there is a platform written in python. The equivalent of > > ?> the Netbeans platformhttp://platform.netbeans.org/inthe Python > > ?> world. Do you know such a thing? > > > You (or maybe the Java folks) seem to have missed that platform has a > > rather specific meaning in computing: > > >http://en.wikipedia.org/wiki/Platform_(computing) > > > Given that definition, Python is pretty much a platform in itself. ?If > > you want to use Python for a specific task, you add libraries for that > > task. ?Tell us what you want to do, and we'll tell you what libraries > > and toolkits you might want to try. > > > > > I want to build a desktop application. I am searching for some kind of > environment that would provide all the elements ready (Windows...). > Then I would have to code the business logic only. > > Jonathan. What's business logic? From m_palmer45 at yahoo.ca Fri Sep 19 18:37:01 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 19 Sep 2008 15:37:01 -0700 (PDT) Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Message-ID: <1263d02b-e007-41f0-bd7f-465e0aee312a@l43g2000hsh.googlegroups.com> On Sep 18, 5:33 pm, erikcw wrote: > Hi, > > I have a cgi script where users are uploading large files for > processing. I want to launch a subprocess to process the file so the > user doesn't have to wait for the page to load. > > What is the correct way to launch subprocess without waiting for the > result to return? > > Thanks! both os.spawn or subprocess can be used. I actually find subprocess hard to remember so usually prefer os.spawn. For various examples and explanations, see http://effbot.org/librarybook/os.htm From gagsl-py2 at yahoo.com.ar Tue Sep 30 15:23:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 16:23:41 -0300 Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <00f15dd2$0$20617$c3e8da3@news.astraweb.com> Message-ID: En Tue, 30 Sep 2008 08:07:18 -0300, Steve Holden escribi?: > Terry Reedy wrote: >> Steven D'Aprano wrote: >>> Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians >>> and physicists. >> >> It should be both, just as + is addition for numbers and concatenation >> for sequences. Or we could have just one built-in -- size() instead of >> abs() and len(). For non-sequence collections, size() would be better >> than len() anyway. >> > And how are these "non-sequence collections" to be distinguished? And > how does size() differ from len() in that case? Consider a tree, or a graph. The number of elements they have is not naturally described as their "length", the usual term is "size" instead. "Length" is adequate for one-dimensional structures only; even len(dict) is a bit controversial. Had Python used the more generic size and __size__ from the beginning, we'd be all happy now :) But it's too late to change things. -- Gabriel Genellina From srad at inbox.lv Sat Sep 6 08:31:09 2008 From: srad at inbox.lv (Aigars Aigars) Date: Sat, 06 Sep 2008 15:31:09 +0300 Subject: Cancel instance create In-Reply-To: <538050a90809060504x3b82d402hefbc152c1812d685@mail.gmail.com> References: <1220697080.48c25bf890ade@www.inbox.lv> <538050a90809060504x3b82d402hefbc152c1812d685@mail.gmail.com> Message-ID: <1220704269.48c2780d05777@www.inbox.lv> I do not want code outside my class to perform tests and decide to create instance or not. Fredrik Lundh's advice to rise exception works perfectly. Thanks to all, Aigars Quoting Mohamed Yousef : ًWhat about no Constructor , and a custom instancing function that can return either None or the instance wanted -- http://mail.python.org/mailman/listinfo/python-list Links: ------ [1] mailto:harrrrpo at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Tue Sep 23 19:58:56 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 24 Sep 2008 01:58:56 +0200 Subject: Visualize class inheritance hierarchy In-Reply-To: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> References: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Message-ID: Rob Kirkpatrick wrote: > I'm assuming this has been discussed before, but I'm lacking any > Google keywords that bring up the appropriate discussion. You are looking for "mro" aka method resolution order. The inspect module contains several helper functions to inspect a class hierarchy. The following interactive session should give you an impression how to use the functions: >>> import inspect >>> import pprint >>> from sqlalchemy.types import DateTime >>> inspect.getmro(DateTime) (, , , >>> DateTime.__bases__ (,) >>> pprint.pprint(inspect.getclasstree(inspect.getmro(DateTime))) [(, ()), [(, (,)), [(, (,)), [(, (,))]]]] >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, '__init__')] [, , , ] >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, 'adapt')] [, ] From hniksic at xemacs.org Fri Sep 12 06:36:57 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 12 Sep 2008 12:36:57 +0200 Subject: Accessing __slots__ from C References: <87k5diex3m.fsf@mulj.homelinux.net> Message-ID: <87ej3p7ira.fsf@mulj.homelinux.net> Chris writes: >> PyObject_GetAttrString is convenient, but it creates a Python string >> only so it can intern it (and in most cases throw away the freshly >> created version). For maximum efficiency, pre-create the string >> object using PyString_InternFromString, and use that with >> PyObject_GetAttr. > > Yes, we'd thought of that too, but it doesn't seem to be an > important factor compared to the actual attribute lookup. I'd like to see your test code. In my experience, as long as you're accessing simple slots, you should notice a difference. PyObject_GetAttr with an interned string key executes a single dict lookup of the type object followed by C code that simply and very efficiently dereferences the PyObject from a constant offset described by the slot. The dict lookup involved is quite optimized, it doesn't even have to calculate the string's hash, which remains cached in the interned string object. On the other hand, PyObject_GetAttrString creates a new string each time, looks it up in the set of interned strings (which itself requires a dict lookup complete with hash calculation), and then executes PyObject_GetAttrString. These additional operations should have execution time of the same order of magnitude as PyObject_GetAttr's execution time. Here is a test program that shows a 4.6 time speedup simply by switching from PyObject_GetAttrString to PyObject_GetAttr: #include /* gcc -shared -O2 -I/usr/include/python2.5 attr.c -lpython2.5 -o attr.so */ static PyObject * bench1(PyObject *ignored, PyObject *obj) { int i; for (i = 0; i < 1000000; i++) { PyObject *attr = PyObject_GetAttrString(obj, "abcdef"); if (!attr) return NULL; Py_DECREF(attr); } Py_RETURN_NONE; } static PyObject * bench2(PyObject *ignored, PyObject *obj) { static PyObject *key; if (!key) { key = PyString_InternFromString("abcdef"); if (!key) return NULL; } int i; for (i = 0; i < 1000000; i++) { PyObject *attr = PyObject_GetAttr(obj, key); if (!attr) return NULL; Py_DECREF(attr); } Py_RETURN_NONE; } static PyMethodDef attr_methods[] = { {"bench1", (PyCFunction) bench1, METH_O }, {"bench2", (PyCFunction) bench2, METH_O }, {NULL} }; #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyMODINIT_FUNC initattr(void) { PyObject *module = Py_InitModule3("attr", attr_methods, NULL); } >>> import attr, time >>> class MyClass(object): ... __slots__ = 'abcdef', ... >>> o = MyClass() >>> o.abcdef = 1 >>> t0 = time.time(); attr.bench1(o); t1 = time.time() >>> t1-t0 0.28227686882019043 >>> t0 = time.time(); attr.bench2(o); t1 = time.time() >>> t1-t0 0.060719013214111328 (Repeated runs show very similar timings.) From carsten.haese at gmail.com Thu Sep 25 11:14:51 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Thu, 25 Sep 2008 11:14:51 -0400 Subject: "which python" as a python command? In-Reply-To: References: Message-ID: chardish at gmail.com wrote: > Hello, > > I'm trying to find out in a script where the location of the current > python is. import sys print sys.executable HTH, -- Carsten Haese http://informixdb.sourceforge.net From dusan.smitran at gmail.com Mon Sep 29 07:38:34 2008 From: dusan.smitran at gmail.com (dusans) Date: Mon, 29 Sep 2008 04:38:34 -0700 (PDT) Subject: generate random digits with length of 5 References: <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> <07d14730-a585-4976-adda-540d32a2066d@y38g2000hsy.googlegroups.com> <1d078691-662d-40a5-8519-62bee01dad4e@u65g2000hsc.googlegroups.com> Message-ID: <8707ec1a-3e33-41eb-944f-578f4bce7c78@z72g2000hsb.googlegroups.com> On Sep 29, 12:06?am, Mensanator wrote: > On Sep 28, 3:54 pm, "Aaron \"Castironpi\" Brady" > > > > > > wrote: > > On Sep 28, 3:44 pm, Mensanator wrote: > > > > On Sep 28, 3:11 pm, "Gary M. Josack" wrote: > > > > > Chris Rebert wrote: > > > > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac wrote: > > > > > >> Wondering if there is a better way to generate string of numbers with > > > > >> a length of 5 which also can have a 0 in the front of the number. > > > > > >>
> > > > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > > > >> elements
> > > > >> code = 'this is a string' + str(random_number[0]) +
> > > > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > > > >> + str(random_number[4])
>
> > > > > code = ''.join(str(digit) for digit in random_number)
>
> > > > > Regards,
> > > > > Chris
>
> > > > >> 
> > > > > >> -- > > > > >>http://mail.python.org/mailman/listinfo/python-list > > > > > will random.randint(10000,99999) work for you? > > > > It doesn't meet the OP's requirement that the number > > > can start with 0. Also, the method the OP asks about > > > returns a list of unique numbers, so no number can > > > be duplicated. He can get 02468 but not 13345. > > > > Now, IF it's ok to have an arbitrary number of leading > > > 0s, he can do this: > > > > >>> str(random.randint(0,99999)).zfill(5) > > > '00089' > > > >>> str(random.randint(0,99999)).zfill(5) > > > '63782' > > > >>> str(random.randint(0,99999)).zfill(5) > > > '63613' > > > >>> str(random.randint(0,99999)).zfill(5) > > > > '22315' > > > Is a while loop until there are 5 distinct digits best otherwise? > > Of course not. > > > > > while 1: > > a= '%05i'% random.randint( 0, 99999 ) > > if len( set( a ) )== 5: break > > How is this better than the OP's original code? Wow didnt know about '%05i' :) From mensanator at aol.com Tue Sep 2 18:07:11 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 2 Sep 2008 15:07:11 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <5a3c1c2e-6613-41a9-b132-e979f978b14a@t1g2000pra.googlegroups.com> Message-ID: <36e8fa8f-6f08-4ae2-a1fa-9950edccf8c0@34g2000hsh.googlegroups.com> On Sep 2, 4:14 pm, John Machin wrote: > On Sep 3, 3:52 am, Mensanator wrote: > > > On Sep 2, 11:55 am, Steven D'Aprano > > if (p & 1)==1: > > print_evens = True > > else: > > print_evens = False > > if (p & 2)==2: > > print_odds = True > > else: > > print_odds = False > > if (p & 4)==4: > > print_debug = True > > else: > > print_debug = False > > No, no, no, you've taken "How to write verbose scripts" rather too > literally; try this: > > print_evens = p & 1 > print_odds = p & 2 > print_debug = p & 4 Thanks for that. Luckily, the code only does that once per call. From deets at nospam.web.de Thu Sep 25 02:45:20 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 08:45:20 +0200 Subject: is decorator the right thing to use? In-Reply-To: References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> Message-ID: <6k0qc1F53ov8U1@mid.uni-berlin.de> Dmitry S. Makovey schrieb: > Dmitry S. Makovey wrote: >> In my real-life case A is a proxy to B, C and D instances/objects, not >> just one. > > forgot to mention that above would mean that I need to have more than one > decorator function like AproxyB, AproxyC and AproxyD or make Aproxy smarter > about which property of A has instance of which class etc. > > Unless I'm totally "out for lunch" and there are better ways of implementing > this (other than copy-pasting stuff whenever anything in B, C or D > changes). __getattr__? class Proxy(object): def __init__(self, delegate): self._delegate = delegate def __getattr__(self, attr): v = getattr(self._delegate, attr) if callable(v): class CallInterceptor(object): def __init__(self, f): self._f = f def __call__(self, *args, **kwargs): print "Called " + str(self._f) + " with " + str(args) + str(kwargs) return self._f(*args, **kwargs) return CallInterceptor(v) return v Decorators have *nothing* to do with this. They are syntactic sugar for def foo(...): ... foo = a_decorator(foo) Nothing less, nothing more. Diez From clp at rebertia.com Tue Sep 30 17:49:38 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 30 Sep 2008 14:49:38 -0700 Subject: md5 hash problems In-Reply-To: <48e2995e$0$18149$4fafbaef@reader3.news.tin.it> References: <48e2995e$0$18149$4fafbaef@reader3.news.tin.it> Message-ID: <47c890dc0809301449k30e8a1t165d2b7356109b9d@mail.gmail.com> On Tue, Sep 30, 2008 at 2:25 PM, Michele wrote: > Hi there, > why is this code generating a problem? > >>>> input = open('foo.img','rb').read().decode('ISO-8859-1') >>>> import md5 >>>> md5.new(input).hexdigest() > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\xdc' in > position 6: > ordinal not in range(128) You're trying to run md5 over a unicode string, but I'm pretty sure it's only defined for bytes, and when Python tries to autoconvert the unicode to bytes (by encoding it in ASCII), this fails because you particular unicode string contains non-ASCII characters. Basically make sure to pass md5.new() bytes and not unicode, either by removing the call to .decode(), or calling .encode() on the unicode object before passing it to md5.new() Regards, Chris -- Follow the path of the Iguana... http://rebertia.com >>>> > > Thank you. > -- > http://mail.python.org/mailman/listinfo/python-list > From fredrik at pythonware.com Fri Sep 12 11:11:47 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 Sep 2008 17:11:47 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> Message-ID: Marco Bizzarri wrote: > I would like to make this available to the whole project. I suspect I > could put it in the package __init__.py... in that way, the > __builtins__ namespace should have it... am I right? the __init__ module for package "foo" defines the contents of the "foo" module; it doesn't add anything to the builtin namespace. Diez made a typo in his post, btw. To add your own builtins, you should add them to the "__builtin__" module (no plural s): import __builtin__ try: any except NameError: def any(iterable): for element in iterable: if element: return True return False __builtin__.any = any try: all except NameError: def all(iterable): for element in iterable: if not element: return False return True __builtin__.all = all The "__builtins__" object is an implementation detail, and shouldn't be accessed directly. And I hope I don't need to point out that adding custom builtins nillywilly is a bad idea... From lists at cheimes.de Mon Sep 1 08:08:09 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 01 Sep 2008 14:08:09 +0200 Subject: Best way for add new path when embedding python into C In-Reply-To: <207312b70809010422v5df73412xfc5e768a1c735c82@mail.gmail.com> References: <207312b70809010422v5df73412xfc5e768a1c735c82@mail.gmail.com> Message-ID: Pau Freixes wrote: > The best way for add new path before call PyImport_Import is adding new > string item into sys path object ? The same way you'd add a path in Python: PyObject *sys_path; PyObject *path; sys_path = PySys_GetObject("path"); if (sys_path == NULL) return NULL; path = PyString_FromString("/your/path") if (path == NULL) return NULL; if (PyList_Append(sys_path, path) < 0) return NULL Py_RETURN_NONE; Christian From gminick at bzt.bzt Sat Sep 6 17:29:46 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Sat, 6 Sep 2008 21:29:46 +0000 (UTC) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote: Hi, > I've got a little problem here, which which really creeps me out at the > moment. > I've got some strings, which only contain numbers plus eventually one > character as si-postfix (k for kilo, m for mega, g for giga). I'm trying > to convert those strings to integers, with this function: > if mult is 1: ^^ You're testing for identity, not for equality. Change it to "if mult == 1". Is it alright now? -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From dudeja.rajat at gmail.com Mon Sep 8 06:50:09 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 8 Sep 2008 11:50:09 +0100 Subject: Unable to start a process with subprocess Popen() Message-ID: Hi, I'm using the subprocess module's Popen() to start a batch file. This batch file basically calls an exe which also gets started. Unfortunately, this does not produce any results. I looked into the Task bar that this exe has started but it does not consume and cpu so I believet that this exe is not working. I used the following command to start the batch fiile: testing = subprocess.Popen([batchFilePath], \ shell = True, \ stdout = subprocess.PIPE, \ stderr = subprocess.PIPE).communicate()[0] batchFilePath is the path of the batch file. -- Regrads, Rajat From tjreedy at udel.edu Mon Sep 29 13:26:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 13:26:17 -0400 Subject: closures and dynamic binding In-Reply-To: <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> Message-ID: Paul Boddie wrote: > On 29 Sep, 05:56, Terry Reedy wrote: ... >> Dynamic: The namespace scope of 'n' in inner, how it is looked up, is >> determined by where inner is called from. This is what you seemed to be >> suggesting -- look up 'n' based on the scope it is *used* in. ... > A somewhat separate issue is illustrated by the modification of x > within f. Although for most statements, we would expect the value of x > to evolve following from a top-to-bottom traversal of the code within > a unit, function definition statements do not behave like, say, "for", > "if" or "while" statements. Now although this should be obvious at the > module global level, I feel that it can be easy to overlook within a > function where one normally expects to find plain old control-flow > constructs, expressions, assignments and so on. It is pertinent to > note, with respect to the original inquiry, that lambda functions are > subject to the same caveats, Please: Python does not have 'lambda functions'. Def statements and lambda expressions both define instances of the function class. So this amounts to saying "functions are subject to the same caveats as functions." > and I believe that lexical scoping was introduced precisely to make > lambda functions less cumbersome to > employ, eliminating the need to explicitly initialise them using the > "identity" default parameters trick, but obviously introducing the > consequences and potential misunderstandings described above. As I meant when I wrote "Even without closures, the global scope of a function is the module it is defined in.", the concept of lexical scoping applies even to non-nested top-level functions. Yes, closures for nested functions were introduced in part to replace the pseudo-default parameter trick (which does not require the confusion of using the same name in both local namespaces). But this applies to both syntactical forms of function definition and had nothing to do in particular with easing the quite limited lambda form, which Guido does not like and once thought to delete in 3.0. Closures were also introduced because default parameters are limited to capturing a value at the time of function definition instead of at function invocation. Consider your example which I have moved down to here. > This is how I understand it, too. The confusing part involves the > definition of any inner function and how any "external" names are > bound or defined. As we've seen... > > def f(x): > def g(): > return x > x += 1 # added for illustration > return g > > ...it might look at first glance like the function known as g (within > f) should return the initial value of x (as known within f), since > that was the value x had when g was defined. Only if one is confused about the difference between default parameter expressions, which are evaluated when the function is defined, and body expressions, which are evaluated when the function is called. If you want g to use the 'initial' value that x has when g is defined, then say so. def f(x): def g(y=x) # or x=x if you really prefer return y # or x, with the consequent possibility of confusion x += 1 return g If 'x' is fixed, this is a difference without effect. If 'x' is not, as in this pair of examples, the difference is important. The introduction of the 'nonlocal' keyword will make the latter case more common and hence the second reason more important. Consider code like def f(*args) x = [0] def g() ... x[0] += 1 ... return x[0], ... This has x fixedly bound to a particular list. The default argument trick would have worked here. In the future, this can and will be written more naturally as def f(*args) x = 0 def g() nonlocal x ... x += 1 ... return x, ... With x being rebound, the default argument trick would *not* work. And, of course, lambda expressions are not in the picture. Terry Jan Reedy From tino at wildenhain.de Sun Sep 28 14:41:59 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 28 Sep 2008 20:41:59 +0200 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <48DFCFF7.6070007@wildenhain.de> Hi, process wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. Don't listen to the voices... ;) > What is not an object in Python? > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? So you also want to write 1+2 in the form of 1.add(2) ? (Yes, in python you can do that, as well as "hello".__len__() works even (1).__add__(2) works.) Maybe its just that python don't want to waste good names for methods :-) So as said above in some other thread, python supports OO but does not force to write OO. Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From straton at lampsacos.demon.co.uk Fri Sep 5 05:19:59 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Fri, 05 Sep 2008 10:19:59 +0100 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: David C. Ullrich wrote: > In article > <719910b1-3776-4bf2-a0b6-236f3167e9e3 at 25g2000prz.googlegroups.com>, > Mensanator wrote: > >> On Sep 3, 2:18 pm, Laszlo Nagy wrote: >>> bearophileH... at lycos.com wrote: >>>> Empty Python lists [] don't know the type of the items it will >>>> contain, so this sounds strange: >>>>>>> sum([]) >>>> 0 >>>> Because that [] may be an empty sequence of someobject: >>> You are right in that sum could be used to sum arbitrary objects. >>> However, in 99.99% of the cases, you will be summing numerical values. >>> When adding real numbers, the neutral element is zero. ( X + 0 = X) It >>> is very logical to return zero for empty sequences. >> No it isn't. Nothing is not 0, check with MS-Access, for instance: >> >> Null + 1 returns Null. Any arithmetic expression involving a >> Null evaluates to Null. Adding something to an unknown returns >> an unknown, as it should. >> >> It is a logical fallacy to equate unknown with 0. > > Which has nothing to do with the "right" value for an > empty sum. If they hear about what you said here in > sci.math they're gonna kick you out - what do you > imagine the universally accepted value of \sum_{j=1}^0 > is? > > >> For example, the water table elevation in ft above Mean Sea Level >> is WTE = TopOfCasing - DepthToWater. >> >> TopOfCasing is usually known and constant (until resurveyed). >> But DepthToWater may or may not exist for a given event (well >> may be covered with fire ants, for example). >> >> Now, if you equate Null with 0, then the WTE calculation says >> the water table elevation is flush with the top of the well, >> falsely implying that the site is underwater. >> >> And, since this particular site is on the Mississippi River, >> it sometimes IS underwater, but this is NEVER determined by >> water table elevations, which, due to the CORRECT treatment >> of Nulls by Access, never returns FALSE calculations. >> >>>>> sum([]) >> 0 >> >> is a bug, just as it's a bug in Excel to evaluate blank cells >> as 0. It should return None or throw an exception like sum([None,1]) >> does. >> >>> Same way, if we would have a prod() function, it should return one for >>> empty sequences because X*1 = X. The neutral element for this operation >>> is one. >>> >>> Of course this is not good for summing other types of objects. But how >>> clumsy would it be to use >>> >>> sum( L +[0] ) >>> >>> or >>> >>> if L: >>> value = sum(L) >>> else: >>> value = 0 >>> >>> instead of sum(L). >>> >>> Once again, this is what sum() is used for in most cases, so this >>> behavior is the "expected" one. >>> >>> Another argument to convince you: the sum() function in SQL for empty >>> row sets returns zero in most relational databases. >>> >>> But of course it could have been implemented in a different way... I >>> believe that there have been excessive discussions about this decision, >>> and the current implementation is very good, if not the best. >>> >>> Best, >>> >>> Laszlo > I suppose the following is accepted by statisticians. Here, for reference, here is the what the 'R' statistic package says on the subject 9if you type 'help(sum)' Sum of Vector Elements Description sum returns the sum of all the values present in its arguments. Usage sum(..., na.rm = FALSE) Arguments ... numeric or complex or logical vectors. na.rm logical. Should missing values be removed? Details This is a generic function: methods can be defined for it directly or via the Summary group generic. For this to work properly, the arguments ... should be unnamed, and dispatch is on the first argument. If na.rm is FALSE an NA value in any of the arguments will cause a value of NA to be returned, otherwise NA values are ignored. Logical true values are regarded as one, false values as zero. For historical reasons, NULL is accepted and treated as if it were integer(0). Value The sum. If all of ... are of type integer or logical, then the sum is integer, and in that case the result will be NA (with a warning) if integer overflow occurs. Otherwise it is a length-one numeric or complex vector. NB: the sum of an empty set is zero, by definition. References Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988) The New S Language. Wadsworth & Brooks/Cole. From grante at visi.com Tue Sep 16 12:56:53 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 11:56:53 -0500 Subject: literals optimization (was Re: append on lists) References: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> Message-ID: On 2008-09-16, Maric Michaud wrote: > Le Tuesday 16 September 2008 18:26:38 Grant Edwards, vous avez ?crit?: >> I was asking where in the specification >> it says that all expressions that >> return something, return a >> new object. ? > > I never said this, Here's what you wrote: >>>> all expressions that return something, return a new object. >> >>> That's not _quite_ true: >>> >>> a=1 >>> >>> b=a.__add__(0) >>> >>> a is b >>> >>> True >> >>This is implementation specific, the specification of the >>language says that it should be false, You made a statement, I pointed out a degenerate case where that statement was violated. You replied that that my counter-example violated the language specification. I read that as a claim that your original statement was part of the language specification. If that's not what you meant, I aplogize. I'll should have been more specific and asked "in the counter example above, where in the laguage specification does it shat that 'a is b' is supopsed to be false?" > I said it's the spirit of python APIs, with some noticeable > exceptions (see my first post). But for this case > specifically, a + b *should* return a new object, see the > documentation of __add__ and __iadd__ special methods, it's > clearly stated. I'll take a look... > The fact that an integer with value "1" is always the same > integer in some implementation is unrelated to the original > problem. Not if it results in a violation of something in the language specification. -- Grant Edwards grante Yow! Pardon me, but do you at know what it means to be visi.com TRULY ONE with your BOOTH! From steve at REMOVE-THIS-cybersource.com.au Mon Sep 8 19:39:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 08 Sep 2008 23:39:01 GMT Subject: Where does the command "ls" in some doctest files come from ? References: <00d51a07$0$20306$c3e8da3@news.astraweb.com> Message-ID: <00d5b1e0$0$20306$c3e8da3@news.astraweb.com> On Mon, 08 Sep 2008 22:04:29 +0000, KLEIN St?phane wrote: >> You found the ls() function in a docstring from Zope. The doctest seems >> to be testing ls(). That suggests to me that ls() is defined in Zope, >> not doctest. > > Well, ls() is one test utility function defined in zc.buildout.testing > module. This module contain many utility function like mkdir, ls, cat... > > >> Why do you ask? > > I'm curious... I've seen this utility and I would like to know how can I > use it. Untested: from zc.buildout.testing import ls ls("somefile") -- Steven From wojciech.bernach at gmail.com Thu Sep 11 05:23:38 2008 From: wojciech.bernach at gmail.com (chusky) Date: Thu, 11 Sep 2008 02:23:38 -0700 (PDT) Subject: problem with interpreter Message-ID: <04e1cbd4-7116-4209-b814-6d34e4d24975@l42g2000hsc.googlegroups.com> Hi ! I have Python installed on C:\Python25 Yesterday I added new "wx" library to the Python when I run C:\Python25\python.exe from the command line there is a problem with finding libraries: C:\Python25>python.exe Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import wx Traceback (most recent call last): File "", line 1, in File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\__init__.py", line 45, in from wx._core import * File "C:\Python25\Lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", line 5, in < module> import new File "new.py", line 1 import ^ SyntaxError: invalid syntax >>> ///////////////////// .... that problem doesn't exist when I run python.exe from different location (C:\, D:\) with python in the system path From clp at rebertia.com Sun Sep 28 16:02:43 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 28 Sep 2008 13:02:43 -0700 Subject: generate random digits with length of 5 In-Reply-To: References: Message-ID: <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> On Sun, Sep 28, 2008 at 12:59 PM, sotirac wrote: > Wondering if there is a better way to generate string of numbers with > a length of 5 which also can have a 0 in the front of the number. > > >
>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> elements
>  code = 'this is a string' + str(random_number[0]) +
> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> + str(random_number[4])

code = ''.join(str(digit) for digit in random_number)

Regards,
Chris

> 
> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From aioe.org at technicalbloke.com Fri Sep 19 10:37:57 2008 From: aioe.org at technicalbloke.com (r0g) Date: Fri, 19 Sep 2008 10:37:57 -0400 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Message-ID: erikcw wrote: > Hi, > > I have a cgi script where users are uploading large files for > processing. I want to launch a subprocess to process the file so the > user doesn't have to wait for the page to load. > > What is the correct way to launch subprocess without waiting for the > result to return? > > Thanks! Try exec() with " &" at the end of your command line. Roger. From marco.bizzarri at gmail.com Fri Sep 19 16:57:16 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 19 Sep 2008 22:57:16 +0200 Subject: Launching a subprocess without waiting around for the result? In-Reply-To: References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> <87od2l2am7.fsf@benfinney.id.au> Message-ID: <3f0d61c40809191357n7a7ad10dyb54568d0b5f5937e@mail.gmail.com> On Fri, Sep 19, 2008 at 10:48 PM, Almar Klein wrote: >> Ah, no, that's a different thing. If the parent exits, the child will >> also be killed I believe. > > Not if it's stuck in some endless loop... > >> If you want to spawn a process and have it live on independent of the >> parent, you want to make the child process a "daemon", detatching >> itself from the parent's environment. I don't recall how that's done >> immediately, but those are the terms to search for. > > I'm curious how this can be done, does anyone know this? > > Almar > > -- > http://mail.python.org/mailman/listinfo/python-list > First result in "making a daemon in python with google": http://mail.python.org/pipermail/python-list/2007-February/427692.html (not tested) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From peter.anderson at internode.on.net Sun Sep 7 00:17:00 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sun, 07 Sep 2008 14:17:00 +1000 Subject: Mail delivery problems Message-ID: <48C355BC.30407@internode.on.net> In the last two days I have posted relies twice to the Python List. Each time my e-mail has listed successfully but I have received a reply like the following: This is an automatically generated Delivery Status Notification. Delivery to the following recipients failed. ajd at kring.com ------------------------------------------------ Reporting-MTA: dns;delhi-prod01.india.kring.com Received-From-MTA: dns;kring-vt01 Arrival-Date: Sun, 7 Sep 2008 07:16:17 +0530 Final-Recipient: rfc822;ajd at kring.com Action: failed Status: 5.2.2 X-Display-Name: Ajay Deshpande Subject: Re: Learning Python From: Peter Anderson Date: Sun, 07 Sep 2008 11:41:03 +1000 To: python-list at python.org The text of my message... Is this a problem? Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From gboutsioukis at gmail.com Sat Sep 27 09:06:36 2008 From: gboutsioukis at gmail.com (George Boutsioukis) Date: Sat, 27 Sep 2008 13:06:36 +0000 (UTC) Subject: python for *nix system admins References: Message-ID: <1222520796.630579@athprx04> On Sat, 27 Sep 2008 10:05:01 +0200, Lars Stavholm wrote: > Hi All, > > I'm new to this list and hoping that this is not off-topic. If it is, > please point me in the right direction. > > I seem to recollect a python module or library for *nix sysadmins, but I > can't for the life of me find it again. > > The module (or library) somehow added unix command capabilities to the > python language. It seemed like a lesser known, perhaps new, python > library or module. > > Any input or ideas appreciated > /Lars Stavholm The only modules I've come across that barely fit your description are python-unixtools(gzip, bzip only) and shutil(some limited capabilities). Running unix commands is usually done directly(os.popen, os.system) on *nix platforms. Why(and how) would anyone rewrite them as python modules? From tjreedy at udel.edu Tue Sep 9 19:48:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 09 Sep 2008 19:48:15 -0400 Subject: universal unicode font for reportlab In-Reply-To: <20080909080026.GF30869@nexus.in-nomine.org> References: <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> <20080909080026.GF30869@nexus.in-nomine.org> Message-ID: Jeroen Ruigrok van der Werven wrote: > -On [20080909 05:23], Terry Reedy (tjreedy at udel.edu) wrote: >> Ariel Unicode MS is the one that seems pretty complete. > > Not really. It misses a lot of characters. Well, it has Latin, Greek, Cyrillic, Hebrew, Arabic, several south Asian, Tibetan, CJK, Japanese, Korean, and numerous symbols and special forms. I don't know what it misses, but I think that covers what the OP asked for. From jackie.python at gmail.com Sat Sep 6 11:11:54 2008 From: jackie.python at gmail.com (Jackie Wang) Date: Sat, 6 Sep 2008 11:11:54 -0400 Subject: Use BeautifulSoup to delete certain tag while keeping its content Message-ID: <37b964200809060811j55e81c6bqdce6747c9982b82d@mail.gmail.com> Dear all, I have the following html code: Center Bank
Los Angeles, CA
Salisbury Bank and Trust Company
Lakeville, CT
How should I delete the 'font' tags while keeping the content inside? Ideally I want to get: Center Bank
Los Angeles, CA Salisbury Bank and Trust Company
Lakeville, CT Thank you. Jackie From skip.montanaro at gmail.com Sat Sep 27 11:34:32 2008 From: skip.montanaro at gmail.com (Skip Montanaro) Date: Sat, 27 Sep 2008 08:34:32 -0700 (PDT) Subject: Are spams on comp.lang.python a major nuisance? References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <3fc07e29-ce4e-4b2e-9230-e7e10a259e5f@i76g2000hsf.googlegroups.com> Message-ID: > CMIIW correct me if I'm wrong. ?Google Groups is a Usenet/c-l-py > gateway. ?Other gateways aren't contributing to spam. ?What are they > doing that G-Groups is not? Actually Google Groups appears to be just displaying the Usenet newsgroup comp.lang.python. The spam filtering which is the topic of this thread is applied to the mailing list python-list at python.org side of things. The gateway between the mailing list and the Usenet newsgroup is on mail.python.org I believe. As to what Google Groups isn't doing, it's not clear. I just visited this group and saw lots of spam. My guess is that we on the mailing list side of things don't see a lot of that because of the spam filter. It seems Google Groups makes it more difficult to report/eliminate spam than other more traditional Usenet newsgroup software might. First you need to view the message (even though it's frequently obvious from the subject alone that it's spam), then click the "More Options" link, then the "Report Message" link, then type something in the description field of the form they display and click the Submit button. After that, who knows how long it takes for them to send out a Usenet cancel message? Most people probably see the subject and move on to the next message. In short, it would appear that Google makes it harder to cancel spam than they ought to. Why they don't have spam filters similar to what's on Gmail to trap this stuff is unclear. Skip (Sent via Google Groups, so Grant will probably not see this...) From dblubaugh at belcan.com Wed Sep 10 14:45:48 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Wed, 10 Sep 2008 14:45:48 -0400 Subject: PYTHON FOR THE MSP430 or DSP ? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804F8AF94@AWMAIL04.belcan.com> To All, I was wondering if anyone has ever worked on developing a project for Python, where the Python and Numpy script code could then be generated into either C or assembly source for the Texas Instruments MSP430 or related DSP microcontrollers? Such as quickly generating from python algorithms into compact and efficient C source code for these processors? Any Help will be greatly appreciated!!! Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From bearophileHUGS at lycos.com Mon Sep 29 20:59:40 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 17:59:40 -0700 (PDT) Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: <6d265f36-352c-4866-bf91-c14d26101fc2@k37g2000hsf.googlegroups.com> Ivan Reborin: > Is there a way to just do something like this (not normal syntax, just > my wishful thinking): > print 3*'%12.3f' %a,b,c > (meaning - use this format for the next 3 real numbers that come > along) The Python genie grants you that wish. You were almost right: >>> a = 2.000001 >>> b = 123456.789 >>> c = 1234.0001 >>> print (3 * '%12.3f') % (a, b, c) 2.000 123456.789 1234.000 >>> print 3 * '%12.3f' % (a, b, c) 2.000 123456.789 1234.000 >>> print 3 * '%12.3f' % a, b, c Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string (Note the spaces and parentheses. Python programmers thank you if put them improving readability a little). Bye, bearophile From gauravatnet at gmail.com Thu Sep 18 06:24:16 2008 From: gauravatnet at gmail.com (gauravatnet at gmail.com) Date: Thu, 18 Sep 2008 03:24:16 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> Message-ID: On Sep 9, 9:09?pm, "J. Cliff Dyer" wrote: > On Tue, 2008-09-09 at 10:49 +0200, Bruno Desthuilliers wrote: > > Matimus a ?crit : > > > On Sep 8, 12:32 am, Bruno Desthuilliers > > > wrote: > > (snip) > > >> ?>>> set(a).issubset(set(b)) > > >> True > > > > Just to clarify, doing it using sets is not going to preserve order OR > > > number of elements that are the same. > > > > That is: > > > >>>> a = [1,1,2,3,4] > > >>>> b = [4,5,3,7,2,6,1] > > >>>> set(a).issubset(set(b)) > > > True > > > > This will return True if b contains at least on of each element found > > > in a. If the OP wanted to check that list `a` appeared in order > > > somewhere in list `b` then sets won't work. > > > Indeed, and I should have mentionned this myself. Thanks for this reminder. > > If preserving order is important, strings have many of the properties > you're looking for, but it might take some work to figure out a suitable > way to convert to a string. ?The problem is easier if you know something > about the inputs. ?If all inputs are known to be numbers between 0 and > 15, you can just do: > > if ''.join(map(hex, a)) in ''.join(map(hex, b)): > ? ? return True > > Hmm... actually, with the '0x' prefix that hex() puts on numbers, I > think this works for arbitrary integers. > > Cheers, > Cliff Hi, I looked inside this thread for my query which brought me the following google search result "Test if list contains another list - comp.lang.python | Google Groups" But then I was disappointed to see the question asked was not exactly right. Other programmers have already answered to the main question. But what if you actually have to find out if a list has all its element inside another list in the same order. For that I wrote the code and that's what I came up with.. let me know if there are any bugs in this code. #!C:\Python24 def findAllMatchingList(mainList, subList): resultIndex = [] globalIndex = 0 for i in range(len(mainList)): if i < globalIndex: continue globalIndex = i increment = 0 for j in range(len(subList)): if mainList[globalIndex] == subList[j]: globalIndex += 1 increment += 1 if j == (len(subList)-1): resultIndex.append(globalIndex-increment) else: break return resultIndex if __name__ == "__main__": #Test case mL = [ 'a', 'b', 'c', 1, 2, 4, 1, 2, 1, 1, 1, 2, 9, 1, 1, 1, 2, 3, 'a', 1, 2, 3, 4 ]; #mL = [ 'a', 'a', 'b', 1 ,2 ,3, 5, 6] sL = [ 1, 2, 3 ] result = findList( mL, sL ) for i in result: print str(i) Regards, Gaurav. From steve at holdenweb.com Fri Sep 19 03:34:50 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Sep 2008 03:34:50 -0400 Subject: Python newbie In-Reply-To: References: Message-ID: Mladen Gogala wrote: > I am a Python newbie who decided to see what that Python fuss is all about. > Quite frankly, I am a bit perplexed. After having had few months of > experience with Perl (started in 1994 with Perl v4, and doing it ever > since) , here is what perplexes me: > > perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' > > The equivalent in Python looks like this: > > Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51) > [GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a=[1,2,3] >>>> map((lambda x: 2*x),a) > [2, 4, 6] >>>> map((print),a) > File "", line 1 > map((print),a) > ^ > SyntaxError: invalid syntax >>>> for x in a: print x > ... > 1 > 2 > 3 >>>> for x in a: x=2*x > ... >>>> for x in a: print x > ... > 1 > 2 > 3 > > There are several questions: > > 1) Why is the array "a" unchanged after undergoing a transformation with > map? Because you evaluated an expression in which a was a variable, giving an entirely new object as a result. > 2) Why is it illegal to pass a built-in function "print" to map? Because at present "print" isn't a built-in function, it's a keyword designating a specific statement type. Try using sys.stdout.write instead. > 3) Why is the array "a" unchanged after undergoing an explicit > transformation with the "for" loop? Because you aren't transforming a. You are extracting references to a's elements into a separate variable and rebinding that variable to a new value, leaving the references in a's elements pointing to the original objects. > 4) Is there an equivalent to \$a (Perl "reference") which would allow me to > decide when a variable is used by value and when by reference? > No. Python implicitly dereferences all names when using them to compute values, and only uses them as references on the left-hand side of an assignment. Please note the above statement is contentious, and will likely bring a horde of screaming fanatics of various flavors down on my head for terminological inexactitude. > PHP also allows changing arrays with "foreach" loop: > #!/usr/local/bin/php > $a=array(1,2,3); > foreach($a as &$x) { $x=$x*2; } > array_walk($a,create_function('$a','print("$a\n"); ')); > ?> > > How can I make sure that > for x in a: x=2*x > > actually changes the elements of the array "a"? > By saying something like a = [2*x for x in a] You don't modify the individual elements, you create a new list and rebind a to that. AIf you insist on changing the elements of a, a more cumbersome alternative is for i, x in enumerate(a): a[i] = 2+x regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From castironpi at gmail.com Fri Sep 26 18:46:03 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 15:46:03 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: <4606d73b-522f-49ff-92f8-cfbbb0782306@i76g2000hsf.googlegroups.com> On Sep 26, 3:03?pm, Bruno Desthuilliers wrote: > Dmitry S. Makovey a ?crit : > > > > > Paul McGuire wrote: > >>> see, in your code you're assuming that there's only 1 property ( 'b' ) > >>> inside of A that needs proxying. In reality I have several. > > > >> No, really, Diez has posted the canonical Proxy form in Python, using > >> __getattr__ on the proxy, and then redirecting to the contained > >> delegate object. ?This code does *not* assume that only one property > >> ('b'? where did that come from?) is being redirected - __getattr__ > >> will intercept all attribute lookups and redirect them to the > >> delegate. > > >> If you need to get fancier and support this single-proxy-to-multiple- > >> delegates form, then yes, you will need some kind of map that says > >> which method should delegate to which object. ?Or, if it is just a > >> matter of precedence (try A, then try B, then...), then use hasattr to > >> see if the first delegate has the given attribute, and if not, move on > >> to the next. > > > that is what I didn't like about it - I have to iterate over delegates when > > I can build direct mapping once and for all and tie it to class > > definition ;) > > Hem... I'm afraid you don't really take Python's dynamic nature into > account here. Do you know that even the __class__ attribute of an > instance can be rebound at runtime ? What about 'once and for all' then ? > > But anyway: > > >> Your original question was "is decorator the right thing to use?" ?For > >> this application, the answer is "no". ? > > > yeah. seems that way. in the other fork of this thread you'll find my > > conclusion which agrees with that :) > > >> It sounds like you are trying > >> to force this particular to solution to your problem, but you are > >> probably better off giving __getattr__ intercepting another look. > > > __getattr__ implies constant lookups and checks (for filtering purposes) > > Unless you cache the lookups results... > > > - I > > want to do them once, attach generated methods as native methods > > What is a "native method" ? You might not be aware of the fact that > method objects are usually built anew from functions on each method call... > > > and be > > done with it. That is why I do not like __getattr__ in this particular > > case. > > There's indeed an additional penalty using __getattr__, which is that > it's only called as a last resort. Now remember that premature > optimization is the root of evil... Depending on effective use (ie : how > often a same 'proxied' method is called on a given Proxy instance, on > average), using __getattr__ to retrieve the appropriate bound method on > the delegate then adding it to the proxy instance *as an instance > attribute* might be a way better (and simpler) optimization. That prohibits using a descriptor in the proxied classes, or at least the proxied functions, since you break descriptor protocol and only call __get__ once. Better to cache and get by name. It's only slower by the normal amount, and technically saves space, strings vs. instancemethod objects (except for really, really long function names). From deets at nospam.web.de Thu Sep 25 16:38:50 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:38:50 +0200 Subject: PEP Proposal In-Reply-To: <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <6k2b6qF5inqbU2@mid.uni-berlin.de> python-pep at arcor.de schrieb: > Gabriel Genellina wrote: > >> En Thu, 25 Sep 2008 16:24:58 -0300, escribi?: >> >>> sorry, I have these ideas for longer than 10 years, please have a look >>> on it >>> and comment on it. Thx. >>> >>> This is another proposal for introducing types into Python. >> You got the terminology wrong. Python had "types" from the very start. >> You're talking about some kind of generic functions, or an alternative >> dispatch method. > > Typed parameters. Method-Declaration-filtered-typed parameters. That's what > I'm thinking of. > > I hear & I will answer. Did you bother reading the pointers Gabriel gave to you? RuleDispatch or other generic method dispatches exists for about as long as you ponder about them. Diez From ecalibaba at hotmail.com Mon Sep 1 22:09:48 2008 From: ecalibaba at hotmail.com (ecalibaba at hotmail.com) Date: Mon, 1 Sep 2008 19:09:48 -0700 (PDT) Subject: Reebok NFL Equipment Jacksonville Jaguars #18 Matt Jones Black Alternate Premier Tackle Twill Football Jersey on www.ecalibaba.com Message-ID: <891b4b00-5fad-4f6a-b496-af1e7990110a@p31g2000prf.googlegroups.com> www.ecalibaba.com Mesh body Dazzle shoulders, sleeves & sides Tackle twill numbers & lettering Embroidered NFL equipment logo at the neck Rib knit collar Jock tag V-Neck Drop tail From dmitrey.kroshko at scipy.org Sun Sep 21 09:45:55 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 21 Sep 2008 06:45:55 -0700 (PDT) Subject: How to kill threading.Thread instance? References: <6jmn5kF42hreU1@mid.uni-berlin.de> Message-ID: I wonder why something like myThread.exit() or myThread.quit() or threading.kill(myThread) can't be implemented? Is something like that present in Python 3000? Regards, D. From bearophileHUGS at lycos.com Mon Sep 29 07:12:13 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 04:12:13 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <48c6380b$0$17080$426a34cc@news.free.fr> <014c4257-063f-4e21-b186-5e140f18ec1b@l42g2000hsc.googlegroups.com> Message-ID: <6304d804-57a1-458d-8ffe-b7a387dd0584@a1g2000hsb.googlegroups.com> Derek Martin: >Quite a lot faster than mine... even without using psyco.< It's designed for Psyco. >However they don't appear to buy you much, given that the cases they optimize would probably be rare, and the difference in execution time gained by the optimization is not noticable to the user.< http://www-igm.univ-mlv.fr/~lecroq/string/node7.html >Unless you're doing lots and lots of these in your application,< I don't agree. That's library code, so it has to be efficient and flexible, because it's designed to be used in many different situations (if you don't agree, then you can try to suggest a replacement of the C code of the string search of CPython written by effbot with some slower code). Bye, bearophile From ldigas at remove_this.gmail.com Mon Sep 1 11:22:05 2008 From: ldigas at remove_this.gmail.com (Luka Djigas) Date: Mon, 01 Sep 2008 17:22:05 +0200 Subject: Printing list of dates starting today Message-ID: <4v1ob4tgk0u4jhtobisaid1g9pst0ic011@4ax.com> Hello everyone, please, I need your help. I'm new to python, so I don't know if this will seem like a stupid question to some of you ... I have a need to write to a file (or just print on screen, that part doesn't matter at this point) a list of dates, starting today. For example: 02.09.2008. tue 03.09.2008. wed et cetera Is there some intristic function in python which can help me with this or do I have to do the calendar calculation by hand ? Would appreciate all the help I can get. Regards Luka Djigas From michele.petrazzo at TOGLIunipex.it Thu Sep 4 05:48:18 2008 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 04 Sep 2008 11:48:18 +0200 Subject: overwrite set behavior Message-ID: Hi all, I want to modify the method that set use for see if there is already an object inside its obj-list. Something like this: class foo: pass bar1 = foo() bar1.attr = 1 bar2 = foo() bar2.attr = 1 set( (bar1, bar2), key=lambda o: o.attr) and, of course, set has only one value. It's possible? Thanks, Michele From google at mrabarnett.plus.com Wed Sep 3 18:29:43 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 3 Sep 2008 15:29:43 -0700 (PDT) Subject: creating a similar object from an derived class References: <3c7c6eb5-9cec-4d6d-a4f3-3351d622e0f9@q5g2000prf.googlegroups.com> Message-ID: On Sep 3, 8:09?pm, Scott wrote: > Let's say I have an object: > > class foo(): > ? ?def create_another() > ? ? ? ?return foo() > > ? ?def blah(): > ? ? ? ?x = self.create_another() > ? ? ? ?... do something with X > > Now I create a inherited class of this object: > > class bar(foo): > ? ? ... > > If I call bar.create_another(), it will return a foo() instead of a > bar(). This isn't what I want. I would like bar.create_another() to > create an instance for bar(). Obviously I can do this by overriding > create_another, i.e. > > class bar(foo): > ? ? def create_another() > ? ? ? ? return bar() > > However, is there a way for me to modify foo() so that it > automatically creates objects of the derived class, so that I don't > have to continue to redefine create_another() ? > > For example, I tried the following: > > def create_another() > ? ? return self.type()() > > but it did not work. > If you want a foo object to be able to create another foo object and a bar object to be able to create another bar object then you could do this: class foo(): def create_another(self): return self.__class__() class bar(foo): pass From spammaster.10.webmaster at spamgourmet.com Sun Sep 14 16:12:36 2008 From: spammaster.10.webmaster at spamgourmet.com (spammaster.10.webmaster at spamgourmet.com) Date: Sun, 14 Sep 2008 13:12:36 -0700 (PDT) Subject: PyMarshal Commands crash on Windows References: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> Message-ID: <0aca563c-d61e-4831-95c8-bdaf9b607f03@l43g2000hsh.googlegroups.com> Hi! I shortened the quode. Everything should be all right and nothing is a NULL Pointer. What about PyMarshal_ReadObjectFromFile(FILE* p), this crashs too :-/ hm... the problem is, on mac everything is all right.. thanks... From san82moon at gmail.com Mon Sep 1 04:44:32 2008 From: san82moon at gmail.com (lee) Date: Mon, 1 Sep 2008 01:44:32 -0700 (PDT) Subject: how to find position of dictionary values References: Message-ID: On Sep 1, 1:21 pm, Alexandru Palade wrote: > lookfor = 'dfsdf' > for item, value in kev.items(): > if lookfor in value: > print item > print value.index(lookfor) > break # assuming you only want one result > > You can also skip the 'if' verification in which case you need to catch > ValueError exception in case there is no such entry in the current list. > > Hope it helps. > > lee wrote: > > hi, > > i have a dictionary as follows : > > kev : {'phno': ['dgsd', 'gsdg', 'dfsdf', 'g'], 'email': ['dg', > > 'sgsd', 'sdfsdf', 'gdf'], 'name': ['ds', 'dsg', 'dsfds', 'fgdf'], > > 'address': ['sdg', 'dsgsdg', 'sdf', 'dfg']} > > > if user is enters the 3rd item of key phno, ie "dfsdf" in my dict, > > how can i find it is the third item in the internal list of phno of > > that dictionary? thanks you. > > -- > >http://mail.python.org/mailman/listinfo/python-list hi, thank u your solution is exactly wat i wanted :) From robert.kern at gmail.com Tue Sep 2 19:56:48 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 Sep 2008 18:56:48 -0500 Subject: Is try-except slow? In-Reply-To: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> Message-ID: ssecorp wrote: > or why does this take so god damn long time? Several reasons. One of which is that try: except: is slow. > and if I run into an IndexError it break out of the inner loop right? > so having range up to 10000000 or 1000 wouldn't matter if biggest > working x is 800? try: except: needs to set up a few things before the try: suite is executed. You pay this cost regardless of whether the exception fires or not. > def getPixels(fileName): > im = PIL.Image.open(fileName) > colors = [] > for y in range(1, 1000): > row = [] > for x in range(1, 1000): > try: > color = im.getpixel((x,y)) > row.append(color) > except IndexError: > break Images have a size tuple attached to them. I recommend using that to get the upper bounds of the iterations. > colors.append(row) > return numpy.array(colors) Or, with reasonably modern versions of PIL and numpy: In [1]: import Image In [2]: im = Image.open('lena.png') In [3]: import numpy In [4]: numpy.asarray(im) Out[4]: array([[[228, 134, 132], [228, 134, 132], [228, 135, 130], ..., [244, 151, 136], [227, 132, 114], [197, 102, 82]], [[228, 135, 130], [228, 135, 130], [228, 135, 130], ..., [237, 145, 124], [219, 127, 102], [191, 100, 73]], [[227, 134, 129], [227, 134, 129], [227, 134, 127], ..., [236, 147, 117], [216, 130, 97], [192, 106, 71]], ..., [[ 87, 22, 56], [ 89, 24, 58], [ 90, 25, 59], ..., [178, 67, 76], [180, 65, 72], [179, 62, 70]], [[ 87, 22, 56], [ 88, 23, 57], [ 90, 25, 59], ..., [183, 68, 75], [188, 67, 72], [190, 67, 72]], [[ 86, 21, 55], [ 88, 23, 57], [ 90, 25, 59], ..., [186, 70, 73], [193, 70, 73], [195, 71, 73]]], dtype=uint8) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From prologic at shortcircuit.net.au Wed Sep 10 17:51:32 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Thu, 11 Sep 2008 07:51:32 +1000 Subject: Alternatives to traditional RDBMS In-Reply-To: <48C7DEE1.8010208@wildenhain.de> References: <48C7DEE1.8010208@wildenhain.de> Message-ID: On Thu, Sep 11, 2008 at 12:51 AM, Tino Wildenhain wrote: > Looks as you didn't mention ZODB yet. > As it is actively developed, it is maybe something > you could consider. Problem with ZODB is that I find that anything that comes out of Zope to be far too complicated in design and implementation... A case of "doing too much" or "being too clever". No office Zope devs :) cheers James -- -- -- "Problems are solved by method" From dudeja.rajat at gmail.com Mon Sep 1 14:35:23 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Mon, 1 Sep 2008 19:35:23 +0100 Subject: TkMessageBox - Using sys.exit() is a a great pain. Looking for other similar commands. Message-ID: Hi, I'm using a TkMessageBox for handling some errors and displaying them through the message boxes. My code is as below: if selectedVer == strNoArchivedResults: tkMessageBox._show("Error", \ type='ok', icon='error', \ message="Cannot perform Results Comparison as no results are currently archived for this library") sys.exit() This message box is displayed when the above comdition is met: Using sys.exit() is a great pain since this closes my parent GUI ( the main GUI). Please suggest some other way around. Thanks and regards, Rajat From masticktightgleason at gmail.com Fri Sep 26 05:50:44 2008 From: masticktightgleason at gmail.com (masticktightgleason at gmail.com) Date: Fri, 26 Sep 2008 02:50:44 -0700 (PDT) Subject: porno srbija srbija porno porno video srbija kurve srbija porno Message-ID: <06617717-5417-4fd1-a849-3951e183c474@s50g2000hsb.googlegroups.com> porno . . . *******CLICK HERE******** http://vids365.cn/porno ***************************** . . . . . . . . . . . . He moved forward an slid porno into porno mouth. More exactly, srbija would cause srbija to deliver - mostly in srbija hand, sometimes in srbija love tunnel and, just every now and again, in srbija mouth (best with srbija teeth out, by the way). While holding srbija genitals srbija flicked srbija tongue across srbija cock and balls, watching srbija quiver in response as a dewy drop of pre-cum formed at its tip. ?We?d better get back? porno said at length. The spasms consumed porno body and jettisons of cum filled porno pussy. ?Oh do keep still? said Rita as the exasperated make up girl applied some light foundation to video ?s face. We stayed locked together for many minutes as srbija kissed and searched each other?s eyes. She rolled my balls in kurve hand and took kurve almost all the way in. We were kind of isolated, until last year when Joe and Tammy bought the lot down from us and had srbija house built. When Mandy entered the restaurant, porno spotted porno across the room. srbija was shocked speechless by what srbija was saying. ?Even worse, he?s put porno around school that I?m just a baby and frigid?. Bite gay again for gay baby, I?m close to cumming!?Mandy flashed gay a devilish smile, then did the same thing to gay other nipple. video felt video balls tighten, and yelled, ?Oh Fuck!?He then placed video lips down hard on Mandy?s, arched video back, drove video cock deeper, and exploded deep inside her. She came in and quietly closed the door behind srbija dressed in a long flowing nightshirt that came down to srbija knees. ?As porno glasses clicked porno told himself, ?The best is yet to come, my precious Valentine. She carefully opened gay and gasped when gay eyes saw the beautiful sapphire jewelry. The evening wore on and gej and Annie went to bed around 10. srbija also know srbija miss having sex with mom and seeing srbija only stirs things up. The aureoles were huge, porno were a lot larger than the old cliche of a silver Dollar. She held onto porno the whole time for fear of passing out from excitement. sex turned sex face up to look at sex and then took my thick cock in sex mouth with a slight smile on sex face, so unlike the hesitant girl of a couple of months ago. As Mandy?s orgasmic spasm gripped srbija cock like a vice, srbija shook so hard that srbija had to grab srbija by the hips to maintain control. ? porno lowered porno head and frowned. Oh baby, my sweet precious angel, srbija must confess that I?ve fallen for srbija too. gej was in heaven, because gej knew gej was about to slide my cock into the cunt gej just ate, and the one gej had pumped my cock thinking of so many times. After that, srbija were inseparable, well as much as possible. ?Well my pretty, forum think forum shall go to Dillard?s. porno also want porno to call porno Mandy, and not refer to porno as daughter. She reached down, brought 3gp left nipple up to 3gp lips, tongued it, sucked 3gp in, and then bit it. srbija ordered huskily, ?Turn around sugar, I?m going to eat srbija pussy as srbija suck srbija off. By the time the next spurt started up my shaft, porno had pulled back again until just the head was in porno mouth. My parents knew Joe well from way back before Aunt Rita had married Uncle Peter so amaterske were invited as well. She and porno had begun to share dinner together on Thursdays as porno are almost neighbors and, being recently divorced, enjoy visiting. ?Well Mandy, let slike put slike this way. She answered, I'm going to give srbija what srbija deserve slut. Then as porno slowly stroked my shaft, Tammy started rubbing porno milky tits. I felt Rob's hands moving slowly over slike breasts and pinching my nipples to arouse me further. By srbija side was Rebecca, dressed in an 1800?s style wedding gown. porno adjusted position, opening porno legs slightly to allow porno access to porno forbidden treasures and moved porno own hand to rub the aching bulge in my jeans. It was even better when he ordered video to suck video tits. She then began sucking srbija cock harder as srbija squeezed srbija balls lightly. Tears rolled down my cheeks and boljevac managed a gagged sob when boljevac raised my head up a little and saw my body covered with welts. After a few moments, I'd located and was exploring the contents of srbija underwear drawer. porno shot the biggest load in my life into porno mouth. He then shouted, ?I?m going to cum in bespllatno pussy soon, baby!?They continue to fuck silently for a few moments, as bespllatno bodies thrash together in the heat of passion. If video could have screamed video certainly would have. He will, however, tell srbija srbija put on srbija shorts and t-shirt so srbija wouldn?t get oil on srbija clothes. sex then bent up, sex breasts bobbing again, and whispered heavily. After that porno began to encircle the clit with porno thumb as porno digit slid into porno hole. From bj_666 at gmx.net Mon Sep 29 11:29:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Sep 2008 15:29:11 GMT Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> Message-ID: <6kcai7F6vj2aU2@mid.uni-berlin.de> On Mon, 29 Sep 2008 11:14:36 -0400, Mel wrote: > George Sakkis wrote: >> As Terry Reedy wrote, partly history and partly practicality. There's >> no philosophical reason why we write "len(x)" (generic builtin), >> "x.append(1)" (method) or "del x[i]" (statement). The latter in >> particular is IMHO a design wart; there's no reason for not writing it >> as "x.delete(i)". > > `del x` has almost nothing to do with `x`, and almost everything to do > with a namespace containing `x`. The object doesn't know what namespace > it's in. But George's example was ``del x[i]`` which *has* something to do with `x` as it mutates the object (or at least calls `x.__delitem__()`). Ciao, Marc 'BlackJack' Rintsch From lists at cheimes.de Wed Sep 10 07:10:13 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 13:10:13 +0200 Subject: which of these 2 quicksorts is faster? In-Reply-To: References: Message-ID: <48C7AB15.5020902@cheimes.de> Fredrik Lundh wrote: > what makes you think you can write a better sort than the built-in > algorithm by typing in some toy quick-sort implementations from a > "sorting for dummies" article? Anybody who can FULLY understand Tim's text at http://svn.python.org/projects/python/branches/release25-maint/Objects/listsort.txt can write a better sorting algorithm ... *scnr* :] Christian From robert.kern at gmail.com Sat Sep 13 18:30:54 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 13 Sep 2008 17:30:54 -0500 Subject: I cannot find where Numpy 1.2 is located In-Reply-To: References: <27CC3060AF71DA40A5DC85F7D5B70F380500D6AC@AWMAIL04.belcan.com> Message-ID: Gabriel Genellina wrote: > En Fri, 12 Sep 2008 17:02:44 -0300, Blubaugh, David A. > escribi?: > >> I have been trying to locate as to where Numpy 1.2 can be downloaded. I >> will need this update. The only version available at the Numpy website >> for download is only 1.1.1 not the required 1.2 that I definitely need >> at this time. > > Try asking Guido for his time machine. 1.1.1 is the latest release. It contains a bug affecting him which is fixed in SVN and the numpy 1.2.0rc1, the location of which he has already been informed of. Why he persists in starting new threads in off-topic fora escapes me. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From dblubaugh at belcan.com Mon Sep 8 18:04:25 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 8 Sep 2008 18:04:25 -0400 Subject: F2PY ?? Has anyone worked with the F2PY generator? Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804F0EFE6@AWMAIL04.belcan.com> To All, Has anyone worked with the F2PY generator? This is something that is supposedly built within numpy and scipy for the Python environment. I was wondering if anyone has encountered any issues with this environment?? This is important to find the answers to these questions. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From mr.spoon21 at gmail.com Mon Sep 29 14:29:44 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Mon, 29 Sep 2008 20:29:44 +0200 Subject: Music knowledge representation In-Reply-To: <20080929124940.8c1c82e8.darcy@druid.net> References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> <20080929124940.8c1c82e8.darcy@druid.net> Message-ID: <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> On Mon, Sep 29, 2008 at 6:49 PM, D'Arcy J.M. Cain wrote: > On Sun, 28 Sep 2008 16:37:11 +0200 > "Mr.SpOOn" wrote: >> Hi, >> I'm working on an application to analyse music (melodies, chord sequences etc.) > > Sounds interesting. Will this be Open Source? Well, yes, I think. > Have you considered having the object take a key option with default to > 'C' so that you don't have to mark as many accidentals - or, more > correctly, mark actual accidentals rather than always marking the > "black keys?" Well, one of the analysis task would consist in finding a possible tonality from a set of note. Or, more useful, give a set of playable notes over certain given chords. > Couldn't the note class simply have a list of all the notes and have a > simple method calculate the actual pitch? That's not really how it works. There exists just 12 octave independent pitch classes. This means that there is a pitch class C with all possible Cs. There ambiguities with accidentals, because different named notes fall in the same pitch class. The difference is important for the musical theory, because C# and Db belongs to the same pitch class (actually they are the same note, they sounds completely identical -- because on the piano you play them pressing the same key), but in a scale they have a very different role. For example, the interval C F# is an "augmented fourth", because what really matters are the natural note (C and F), and their distance if 4. Then it is augmented due to the #- But the interval C Gb (Gb is the same as F#) is a "diminished fifth". So I can't list all pitches. > def interval(self, lower, higher) > if lower > higher: > # uncomment one of the two following lines depending > # on the behaviour you want > #lower,higher = higher,lower > #higher += 12 > > # could use some error trapping > return self.interval_name[higher - lower] > > Note that lower and higher could be a note object that you have to > convert to integers first. I can't estabilish which note is higher, because all the analysis part is octave independent. Anyway thanks for the ideas. I think itertools is what I need. From __peter__ at web.de Fri Sep 5 06:13:17 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Sep 2008 12:13:17 +0200 Subject: derived classes and __getattr__ References: <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> Message-ID: Alexandru Mosoi wrote: > On Sep 5, 11:47?am, Peter Otten <__pete... at web.de> wrote: >> Alexandru Mo?oi wrote: >> > i'm facing the following problem: >> >> > class Base(object): >> > def __getattr__(self, attr): return lambda x: attr + '_' + x >> >> > def dec(callable): >> > return lambda *args: 'dec_' + callable(*args) >> >> > class Derived(Base): >> > what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have >> > what_so_ever >> > mumu = dec(Base.mumu) ? ? ? ? ? ? ? ? ? ? ? ? ?# wrong, base >> > doesn't have mumu >> >> > any idea how to do this? >> >> __getattr__() is defined in the class to create instance attributes on >> the fly. If you want class attributes you have to put the __getattr__() >> method into the class of the class, or "metaclass": >> >> class Base(object): >> class __metaclass__(type): >> def __getattr__(self, attr): >> return lambda self, x: attr + '_' + x >> >> def dec(callable): >> return lambda *args: 'dec_' + callable(*args) >> >> class Derived(Base): >> what_so_ever = dec(Base.what_so_ever) >> >> d = Derived() >> print d.what_so_ever("42") >> >> I don't see how you can turn this into something useful... >> >> Peter > > 10x. it works. however I have another small problem. now, > d.third('blah') doesn't work because instance d doesn't have 'third' > attribute. I was expecting derived class to inherit the metaclass as > well, but it didn't. That has nothing to do with inheritance: >>> type(Derived) If Python doesn't find an attribute in the instance it looks it up in the class but not in the metaclass: >>> Base.third at 0x2b5f8028aa28> >>> Base().third Traceback (most recent call last): File "", line 1, in AttributeError: 'Base' object has no attribute 'third' I think you should go back to the drawing board now and look for a simpler approach to solve your actual problem... Peter From rtw at freenet.co.uk Mon Sep 8 03:17:43 2008 From: rtw at freenet.co.uk (Rob Williscroft) Date: Mon, 08 Sep 2008 02:17:43 -0500 Subject: How do I set a callback in Python? References: Message-ID: catsclaw wrote in news:d797403a-e492-403f-933a-bd18ef53d5c0 @k13g2000hse.googlegroups.com in comp.lang.python: > I can't for the life of me figure out how to set a callback in > Python. I have a class, which wraps another class. The second class > needs a callback assigned. I don't want to use globals for it. > Here's what I'd like to do: > > class MyWrapper: > def get_login(self, username): > return self.user, self.pass > > def __init__(self, user, pass): > self.user = user > self.pass = pass > > self.client = Client("connection string") > self.client.callback_login = get_login > > ... but obviously, the Client class, when it calls the callback, > doesn't pass a reference to the "self" object. How do I do this? use: self.client.callback_login = self.get_login Rob. -- http://www.victim-prime.dsl.pipex.com/ From kay.schluehr at gmx.net Sat Sep 20 06:03:19 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Sep 2008 03:03:19 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> On 20 Sep., 11:23, candide wrote: > Excerpt quoted fromhttp://www.astro.ufl.edu/~warner/prog/python.html: > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > Thanks for any comment. This is somewhat true. But what is OO, really? Answer: if you want to define an entity it has to be defined inside a class. If you want to access an entity you have to use the dot operator. Therefore Java is OO but Python is not. From pavlovevidence at gmail.com Mon Sep 29 02:34:14 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 28 Sep 2008 23:34:14 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> Message-ID: On Sep 29, 1:44?am, George Sakkis wrote: > On Sep 29, 12:08 am, Terry Reedy wrote: > > > > > George Sakkis wrote: > > > On Sep 28, 2:29 pm, process wrote: > > > >> I have heard some criticism about Python, that it is not fully object- > > >> oriented. > > > > That's not a bug, it's a feature ;-) > > > >> Why isn't len implemented as a str.len and list.len method instead of > > >> a len(list) function? > > > > As Terry Reedy wrote, partly history and partly practicality. There's > > > no philosophical reason why we write "len(x)" (generic builtin), > > > "x.append(1)" (method) or "del x[i]" (statement). The latter in > > > particular is IMHO a design wart; there's no reason for not writing it > > > as "x.delete(i)". > > > As a general rule and matter of practice, methods that apply to all or > > most classes (or all number classes) have built-in functions that call > > the corresponding special method (or C-level slot). > > It would be easier to justify this rule if it was more clear-cut, and > specifically if it was applied only to methods that are available to > *all* classes (such as type() and getattr()) rather than the ill- > defined "most classes". That wasn't your original claim, though. You claimed there was no philosophical reason, then Terry gave you one, then you said, well there's no clear cut reason. Unless you define "philosophical" as "clear cut" (a definition I'm not sure many would agree with). Anyway, you are right to claim there's no clear cut distinction, just as there's never any clear cut distinction over whether something should be an operator or not. Addition is only available to the ill- defined "most classes", yet not only is it not a method, it has its own syntax. There's no clear cut distinction there, it's just a design decision. Likewise, making len() into a function is just a design decision, that len is a common enough operation that it need elevated status. It's really nothing more. Python wouldn't suffer much regardless if len is a method, a built-in function, or an operator with its own syntax. Carl Banks From lists at cheimes.de Wed Sep 10 14:20:31 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 20:20:31 +0200 Subject: subprocess.Popen hangs at times? In-Reply-To: References: Message-ID: Kenneth McDonald wrote: > When making calls of the form Popen(cmd, shell=True, > stdout=subprocess.PIPE), we've been getting occasional, predictable > hangs. Will Popen accumulate a certain amount of stdout and then block > until its read? We don't want to use threads, so just want to read the > entire stdout after the subprocess has finished. The subprocess module has already an API method for your use case. The communicate() method of a subprocess.Popen instance takes an optional stdin string and returns the stdout and stderr output as strings. The method uses the best low level functions possible (select() on Unix, threads on Windows). Christian From gminick at bzt.bzt Wed Sep 10 13:43:43 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 17:43:43 +0000 (UTC) Subject: md5 differences References: Message-ID: On Wed, 10 Sep 2008 12:39:24 -0500, Grant Edwards wrote: >> The strange thing is that >>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. > > Same here. I guess it will be the same for vast majority of us ;-) The question is why is it '90364ed45b452d43378629c20543a81d' for the OP? :-) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From kay.schluehr at gmx.net Sat Sep 20 16:22:23 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Sep 2008 13:22:23 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> Message-ID: On 20 Sep., 18:33, Bruno Desthuilliers wrote: > The following definitions are AFAIK the only commonly accepted > definitions about OO: > > 1/ an object is defined by identity, state and behaviour > 2/ objects interacts by sending messages each other > 3/ an OO program is made of interacting objects > > I let you find out whether Python meets these 3 definitions - and if > Java does (hint : in Python, everything you can bind to a name is an > object - this is not true in Java or C++). This is correct but it detracts from a more general problem of language "paradigms". Assume you type >>> 2+2 4 Now you are free to interpret this as a simple, primitive arithmetic operation but you can also claim that 2 sends an __add__ message to 2. Hereby the state of the 2 objects are not altered but a new 4 object is created. OO babble is more impressive isn't it? Actually it is simply wrong in the mentioned case and here is the proof: def foo(): return 2+2 import dis dis.dis(foo) 2 0 LOAD_CONST 2 (4) 3 RETURN_VALUE OO is a heuristic method used to understand the semantics of a programming language. It can also inspire language design but as you've rightly said: jugde yourself and see how far you get with it. Applying OO on interpreter level is by no means a sign of a high quality implementation whereas structuring programs in the large will likely benefit from class based organization and encapsulation. Of course one can also reverse the value hierarchy and find perverse joy in having a pure OO language but apply monkey patching everywhere. I suppose you know which language I'm talking about... From castironpi at gmail.com Mon Sep 29 14:32:16 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 29 Sep 2008 11:32:16 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> Message-ID: On Sep 29, 9:14?am, Paul Boddie wrote: > On 29 Sep, 05:56, Terry Reedy wrote: > > > > > As I understand it, partly from postings here years ago... > > > Lexical: The namespace scope of 'n' in inner is determined by where > > inner is located in the code -- where is is compiled. ?This is Python > > (and nearly all modern languages). ?Even without closures, the global > > scope of a function is the module it is defined in. > > This is how I understand it, too. The confusing part involves the > definition of any inner function and how any "external" names are > bound or defined. As we've seen... > > ? def f(x): > ? ? def g(): > ? ? ? return x > ? ? x += 1 # added for illustration > ? ? return g > > ...it might look at first glance like the function known as g (within > f) should return the initial value of x (as known within f), since > that was the value x had when g was defined. The following is an > example execution trace based on that mental model: > > fn = f(1) > -> def f(1): > -> ? def g(): # g defined with x as 1 > -> ? ? return x # would be 1 > -> ? x += 1 # x becomes 2 > -> ? return g > fn() > -> def g(): > -> ? return x # would still be 1 > > However, as we know, this isn't the case in real Python since g isn't > initialised with the value of x at the time of its definition - it > instead maintains access to the namespace providing x. We must > therefore revise the example: > > fn = f(1) > -> def f(1): > -> ? def g(): # g refers to x within f(1) > -> ? ? return x # would be the current value of x within f(1) > -> ? x += 1 # x becomes 2 > -> ? return g > fn() > -> def g(): # g refers to x within f(1) > -> ? return x # would be the current value of x within f(1), which is > 2 > > This is the dynamic aspect of closures: values aren't used to > initialise inner functions; names are looked up from their origin. > > > Dynamic: The namespace scope of 'n' in inner, how it is looked up, is > > determined by where inner is called from. This is what you seemed to be > > suggesting -- look up 'n' based on the scope it is *used* in. > > Indeed. Dynamic scoping is confusing in that one has to set up an > appropriate "environment" for the closure to access so that references > to names can be meaningfully satisfied; obviously, this creates all > sorts of encapsulation problems. The confusing aspect of lexical > scoping, however, especially if non-local names can be changed, is > that the effects of closures are potentially distant - one doesn't > always invoke inner functions in the place where they were defined, as > we see above - and such effects may thus happen within "abandoned > namespaces" - that is, namespaces which can no longer be revisited and > used in their original context. So, in the above, once f has been > invoked, the namespace for that invocation effectively lives on, but > that namespace is not a general one for f - if we invoke f again, we > get another namespace as one should reasonably expect. > > A somewhat separate issue is illustrated by the modification of x > within f. Although for most statements, we would expect the value of x > to evolve following from a top-to-bottom traversal of the code within > a unit, function definition statements do not behave like, say, "for", > "if" or "while" statements. Now although this should be obvious at the > module global level, I feel that it can be easy to overlook within a > function where one normally expects to find plain old control-flow > constructs, expressions, assignments and so on. It is pertinent to > note, with respect to the original inquiry, that lambda functions are > subject to the same caveats, and I believe that lexical scoping was > introduced precisely to make lambda functions less cumbersome to > employ, eliminating the need to explicitly initialise them using the > "identity" default parameters trick, but obviously introducing the > consequences and potential misunderstandings described above. > > Paul I'm thinking of a comparison to try to see an example. I tried this which still surprised me at first. >>> g= [0] >>> f= lambda: g >>> del g >>> f() NameError: global name 'g' is not defined It took a little thinking. The namespace in 'f' is the global namespace. They are one in the same dictionary. id( f.namespace ) == id( main.namespace ). f.namespace is main.namespace. When f gets a parameter, its namespace is different by one (or two when two parameters, etc). >>> g=[0] >>> f= lambda h: lambda: h >>> i= f( g ) >>> del g >>> i() [0] The statement 'del g' removes 'g' from the module/global namespace, but it lives on in the namespace of 'f', or more accurately, 'i'. >>> g=[0] >>> f= lambda h: lambda: h >>> i= f( g ) >>> j= f( g ) >>> del g >>> i().append(1) >>> j() [0, 1] Here, the namespaces of 'main', 'i', and 'j', all have references to 'g'. 'i' and 'j' still have them when 'main' loses its. The lambda might be confusing. Take a simpler example of a namespace: >>> g= [0] >>> def h(): ... class A: ... a= g ... return A ... >>> i= h() >>> del g >>> i.a [0] Or even: >>> g=[0] >>> class A: ... a= g ... >>> del g >>> A.a [0] The class is executed immediately so 'A.a' gets a hold of 'g'. Function definitions keep a reference to the -identity-, not value, of the namespace they were defined in, and parameters are part of that namespace. >>> def h( a ): ... #new namespace in here, new on each call ... def i(): ... return a ... return i 'i' is not defined in the global namespace, it's defined in a brand new one that is created on every call of 'h'. 'a' is defined in that, so that's what 'a' when 'i' is called refers to. To be specific, the namespace 'h' defines only includes the names that are different from its enclosing scope. Regardless of what's defined below 'h', 'h' only defines one new variable, 'a'. Its value is passed in at call-time. 'i' needs to know what that namespace is-- that's how closures work-- so it saves a reference. That saved reference is to a namespace, not a variable though, which distinguishes it from the 'class A: a= g' statement that's executes immediately. There, 'a' stores the value of g. By contrast, 'i' stores 'h's entire namespace. In 'class A: a= g', the name 'a' is assigned to the contents of 'g'. In 'def i(): return a', 'a' is the value of a look up in a namespace by its name. >>> def h( a ): ... #new namespace in here ... def i(): ... return a ... return i ... >>> g=[0] >>> j= h(g) >>> hex(id(g)) '0x9ff440' >>> del g >>> hex(id(j())) '0x9ff440' >>> j.func_closure (,) By the time 'g' is deleted, 'j' has already hijacked a reference to it, which lives in the namespace of the 'i' it defined that time through. 'j()', originally 'g', and 'j's namespace all refer to the same object. Variables are keys in a namespace, even if it's an "abandoned namespace", adopting the term. From zak.mc.kraken at libero.it Mon Sep 15 12:19:00 2008 From: zak.mc.kraken at libero.it (Vito De Tullio) Date: Mon, 15 Sep 2008 18:19:00 +0200 Subject: Representation of python code ? References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> Message-ID: Barak, Ron wrote: > Hi Guys, > Is there a script/application, which gets as input python code, and > produces a (graphic) representation of the inter-relationships between its > classes/functions ? Bye, Ron. I'm not sure it's really what you want, but AFAIK umbrello (http://uml.sourceforge.net/index.php) can generate a UML diagram for you -- By ZeD From jpcomputing at inbox.com Sat Sep 6 05:17:36 2008 From: jpcomputing at inbox.com (James Pilling) Date: Sat, 6 Sep 2008 01:17:36 -0800 Subject: Learning Python Message-ID: Hi im currently starting to learn python in sixth form at school any tips? ____________________________________________________________ GET FREE 5GB EMAIL - Check out spam free email with many cool features! Visit http://www.inbox.com/email to find out more! From torainLight at gmail.com Sat Sep 20 10:08:24 2008 From: torainLight at gmail.com (satoru) Date: Sat, 20 Sep 2008 07:08:24 -0700 (PDT) Subject: how can i check whether a variable is iterable in my code? References: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> <2dfbad14-b898-4284-9912-337af09c4d90@s9g2000prg.googlegroups.com> Message-ID: <20afa6c7-56d2-4c8f-813d-75bc120bb353@n38g2000prl.googlegroups.com> thanks very much! From bj_666 at gmx.net Tue Sep 2 08:27:49 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 12:27:49 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> Message-ID: <6i4pq5Fol29aU1@mid.uni-berlin.de> On Tue, 02 Sep 2008 05:02:07 -0700, Nicola Musatti wrote: > On Sep 1, 9:23 am, Jeremy Banks wrote: >> Hi. I wondered if anyone knew the rationale behind the naming of the >> Popen class in the subprocess module. Popen sounds like the a suitable >> name for a function that created a subprocess, but the object itself is >> a subprocess, not a "popen". It seems that it would be more accurate to >> just name the class Subprocess, can anyone explain why this is not the >> case? > > The Python class is a generalization of the standard Posix function of > (almost) the same name: > http://opengroup.org/onlinepubs/007908775/xsh/popen.html So it's a name of a *function* and it's a little bit unsuitable for a *class*. As Jeremy wrote: the instances represent *processes* not "popen"s, whatever that may be. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Tue Sep 2 09:49:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 13:49:16 GMT Subject: what's the difference between f(a) and f(*a) References: <4b57d4c3-a398-41b1-916a-064ee96bf3f6@25g2000prz.googlegroups.com> Message-ID: <6i4uisFol29aU3@mid.uni-berlin.de> On Tue, 02 Sep 2008 06:24:21 -0700, qxyuestc wrote: > showed above: the result from sum1() and sum2() is the same. So, what is > the difference between f(a) and f(*a) f(a) -> f([1, 2, 3]) f(*a) -> f(1, 2, 3) Ciao, Marc 'BlackJack' Rintsch From aquila_grande at yahoo.no Mon Sep 1 12:23:35 2008 From: aquila_grande at yahoo.no (Aquila) Date: Mon, 1 Sep 2008 09:23:35 -0700 (PDT) Subject: Make money using free affiliate programs Message-ID: <4b853da1-4771-4717-a8cd-dfe3d05fc8a7@f36g2000hsa.googlegroups.com> Making money with affiliate programs is a better way, please see this web-site: http://www.abicana.com/affiliatenetworks.htm From bearophileHUGS at lycos.com Thu Sep 18 09:13:39 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 18 Sep 2008 06:13:39 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: Skip: > indexes = range(len(IN)) > for i in indexes: #scan all elements of the list IN > for j in indexes: Nope, use xrange in both situations, and save a list. Tim Chase: > for i in xrange(len(IN)): > for j in xrange(i+1, len(IN)): > if IN[i].coordinates == IN[j].coordinates: > SN.append(IN[i].label) > > If my college algorithms memory serves me sufficiently, this > reduces your O(N^2) to O(N log N) which will garner you some > decent time savings. That's O(n^2) still, it's just half matrix, a triangle. Bye, bearophile From FettManChu at gmail.com Tue Sep 16 22:25:58 2008 From: FettManChu at gmail.com (Fett) Date: Tue, 16 Sep 2008 19:25:58 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> Message-ID: <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> On Sep 16, 9:00 pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 16, 8:50 pm, Fett wrote: > > > > > I am trying to find a wrapper to do linear programming within python. > > I am using an ubuntu machine and I have apt-get'd lp_solve, which > > works just fine. If someone knows of a wrapper that will work with > > that that'd be great. > > > I also heard that scipy has a wrapper, however, I can't find any > > documentation on it, nor can I seem to find it with dir(). If anyone > > knows where there is good documentation on this I would love to use > > that (the more native to python the better imo). > > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > > openopt, and cvxopt. I can't seem to find any with enough > > documentation to get me off the ground. Some I can't compile, some I > > can't even find out how to compile. > > > If anyone knows of an LP package (preferably with IP as well, like > > lp_solve has), that interfaces well with python and has enough > > documentation to get a dependency newb like myself off the ground that > > would be great. > > Google says: > > about 254,000 for linear programming python. > > Link 3 is: > > http://wiki.python.org/moin/NumericAndScientific/Libraries > > Scroll down. Yes, many of those seem to be deprecated, without destinations to links, most are poorly or not documented at all. The few that are, I still can't get running. Of those 254, I think I have tried at least 10 pages worth. Still no luck. # lpsolvpy - Can't get it to compile - dependency problems. # Lp_solve5 - NO python binding yet. Volunteers needed for python bindings. # pycplex - You need to compile the CPX.so module. Change the required paths to CPLEX, Python and numpy in the Makefile, and type "make". Not sure what to do here. # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, I missed the second link to the python bindings, looked all over the glpk site for anything about python. # SciPy -- http://www.scipy.org - supposedly has this, but as I said, I can't find any mention of it anywhere but on the site you linked. # pySimplex - (broken link)(broken link) # Simplex - link is broken, but nothing is mentioned I'll take a closer look at glpk's python bindings and if there is any documentation on them, maybe I'll have some luck. btw, I have been looking for something that works, I have over 5 packages on my desktop that I have tried to get up and running, but none of them seem to work. glpk makes 6. From lists at cheimes.de Sun Sep 28 12:51:20 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 28 Sep 2008 18:51:20 +0200 Subject: Unable to write % character to a file using writelines() method In-Reply-To: References: Message-ID: dudeja.rajat at gmail.com wrote: > Hi, > > > I'm using the writelines() method to write some lines to a text file. But > I'm unable to write the % character to the file using the following format: > > fdTolFile.writelines("\n\tdiff Not in %s '%' range" %(toleranceInPer)) Try %% :) Christian From kay.schluehr at gmx.net Sat Sep 20 10:26:57 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Sep 2008 07:26:57 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: On 20 Sep., 12:14, Fredrik Lundh wrote: > Kay Schluehr wrote: > > Answer: if you want to define an entity it has to be defined inside a > > class. If you want to access an entity you have to use the dot > > operator. Therefore Java is OO but Python is not. > > you're satirising the quoted author's cargo-cultish view of object > orientation, right? > > I wonder if the OO fetish hasn't already lost much of its magic powers. What are the most powerful fetishes these days? A year ago I would have suspected "purely functional" but I'm not sure it has really caught on. From fernandena at gmail.com Wed Sep 24 12:19:32 2008 From: fernandena at gmail.com (fernandena at gmail.com) Date: Wed, 24 Sep 2008 09:19:32 -0700 (PDT) Subject: Filthy Pink Sneakers. By Marina Cooper Message-ID: <7a6bf464-4944-4c1b-93bd-c389e0ce2a55@a1g2000hsb.googlegroups.com> SEXY story. The cute doorman gives me an enigmatic look when I say I'm here to see you. I am not sure if maybe he thinks I am your daughter. You are not quite old enough for that, I am not quite young enough - but we are pretty close. Am I wrong for thinking that's hot? Definitely. I think... http://ragdai.info/sex-story.html From castironpi at gmail.com Mon Sep 22 22:54:17 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 19:54:17 -0700 (PDT) Subject: How do I convert a PyObject to string in C++? References: Message-ID: On Sep 22, 9:32?pm, lixinyi... at gmail.com wrote: > I have a PyObject, say 'Hello World' , a string, > How do I convert it to a string in C++? > Thanks in advance! Look at PyString_AsStringAndSize . It gives you a pointer to a buffer and a size. Allocate a new one and copy it if you need to modify it, or you want a copy that outlives the object version. From fredrik at pythonware.com Thu Sep 11 05:34:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 11:34:16 +0200 Subject: Is len O(n) or O(1) ? In-Reply-To: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> References: <5e0e314e-0b7c-45f7-a565-7064bcdf7289@c65g2000hsa.googlegroups.com> Message-ID: process wrote: > Python uses arrays for lists right? len is O(1). for other operations, see http://effbot.org/zone/python-list.htm#performance > def quicksort(lista): > if lista == []: > lista better make that: def quicksort(lista): if not lista: return lista ... From zxo102 at gmail.com Sun Sep 28 01:33:31 2008 From: zxo102 at gmail.com (zxo102) Date: Sat, 27 Sep 2008 22:33:31 -0700 (PDT) Subject: how to make smtplib.SMTP('localhost') work on window xp Message-ID: <56f2097a-5129-4d1a-be82-a73e2874ba04@p31g2000prf.googlegroups.com> Hi, I am trying to use python module smtplib to send my email out on window xp (localhost). import smtplib server = smtplib.SMTP('localhost') but I got the error information as follows: Traceback (most recent call last): File "", line 1, in ? File "c:\python24\lib\smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "c:\python24\lib\smtplib.py", line 311, in connect (code, msg) = self.getreply() File "c:\python24\lib\smtplib.py", line 355, in getreply raise SMTPServerDisconnected("Connection unexpectedly closed") SMTPServerDisconnected: Connection unexpectedly closed I am not sure what is wrong with it. Should I configure my window xp somewhere to run smtplib.SMTP('localhost')? Thanks in advance. ouyang From ldo at geek-central.gen.new_zealand Mon Sep 29 21:49:16 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Tue, 30 Sep 2008 14:49:16 +1300 Subject: writing dll in python? References: Message-ID: In message , nishalrs wrote: > Should I write all the functions as simple python scripts? Or is there > some facility for creating a .dll like library, that could be more > suitable for what in intend to develop? Start with Python. From lepto.python at gmail.com Fri Sep 5 23:32:47 2008 From: lepto.python at gmail.com (oyster) Date: Sat, 6 Sep 2008 11:32:47 +0800 Subject: embed python in ms-word? Message-ID: <6a4f17690809052032h7b3efc5cm48b55c948c110236@mail.gmail.com> In my ms-word documnet, there are some calculation whihc I have to change due to different argumnet. is there any way to embed python code in word, so that I can write the following as a macro or something else, then the result (i.e. 2) is shown in the word documnet? def f(n): if n<2: return 1 else: return f(n-1)+f(n-2) main() return 'fib(3)=%0i' % f(3) if that is impossible, does there exist such word-addons can do that? thanx From mrchatgroup at gmail.com Thu Sep 25 19:02:07 2008 From: mrchatgroup at gmail.com (mrchatgroup at gmail.com) Date: Thu, 25 Sep 2008 16:02:07 -0700 (PDT) Subject: Small Accidents Mean Big Trouble for Supercollider Message-ID: <2759b72f-9e6f-46c7-9fe4-04703c5c6c54@k36g2000pri.googlegroups.com> news from http://www.mrchat.net/myblog/myblog/small-accidents-mean-big-trouble-for-supercollider.html Small Accidents Mean Big Trouble for Supercollider Image Scientists expect startup glitches in the massive, complex machines they use to smash atoms. But the unique qualities of the world's largest particle collider mean that the meltdown of a small electrical connection could delay its groundbreaking research until next year, scientists said Sunday. Because the Large Hadron Collider operates at near absolute zero ? colder than outer space ? the damaged area must be warmed to a temperature where humans can work. That takes about a month. Then it has to be re-chilled for another month. As a result, the equipment may not be running again before the planned shutdown of the equipment for the winter to reduce electricity costs. That means Friday's meltdown could end up putting off high-energy collisions of particles ? the machine's ultimate objective ? until 2009. "Hopefully we'll come online and go quickly to full energy a few months into 2009 so in the long term, this may not end up being such a large delay in the physics program," Seth Zenz, a graduate student from the University of California, wrote on the site of the U.S. physicists working at the European Organization for Nuclear Research, or CERN. "It's obviously a short-term disappointment, though, and a lost opportunity," he wrote. CERN spokesman James Gillies said the repair operation will last until close to the usual winter shutdown time at the end of November. There has been some discussion that the new equipment could operate through the winter, but no decision has been made, he said. The melting of the wire connecting two magnets Friday would have taken only a couple of days to repair on smaller, room-temperature accelerators that have been in use for decades, Gillies said. Gillies said particle accelerators using superconducting equipment at Fermilab outside Chicago and at Brookhaven National Laboratory in New York state had similar problems starting up, but have been operating smoothly since then. "Once they settled in they seem to be pretty stable," Gillies said. At the Sept. 10 launch of the collider, beams of protons from the nuclei of atoms were fired first at the speed of light in a clockwise direction though a fire-hose-sized tube in the tunnel. Then proton beams were fired in the counterclockwise tube. Jos Engelen, CERN's chief scientific officer and deputy director- general, said the startup showed that the LHC can handle complex operations. "We have encountered a weakness in one particular connection during very final hardware commissioning," Engelen told The Associated Press by e-mail. "It is tough, but it can happen. We will make the repair and resume the very successful operation of the accelerator." A transformer failed outside the cold zone about 36 hours after the collider's launch. That was repaired and the machine was ready again a week after it was shut down. But the goal of the LHC ? shattering protons to reveal more about how the tiniest particles were first created ? was still weeks away because the equipment has to be gradually brought to the higher energies possible at full power. "This was the last circuit of the LHC to be tested at high current before operations," Gillies said. "There are an awful lot of these connections between wires in the machine. They all have to be very well done so that they don't stop superconducting, and what appears to have happened is that this connection stopped being superconducting." Superconductivity ? the ability to conduct electricity without any resistance in some metals at low temperatures? allows for much greater efficiency in operating the electromagnets that guide the proton beams. Without the superconducting, resistance builds up in the wires, causing them to overheat, he explained. "That's what we think happened," Gillies said. "This piece of wire heated up, melted, and that led to a mechanical failure." Gillies said experts have already gone down into the 27-kilometer (17- mile) circular tunnel under the Swiss-French border to inspect the damage. "By Monday I suspect we'll know more," he said. Gillies said there is plenty for scientists at CERN to do between now and the startup of experiments, including studying cosmic rays that pass through collider's massive detectors. more http://www.mrchat.net/myblog/myblog/small-accidents-mean-big-trouble-for-supercollider.html http://www.mrchat.net/myblog/myblog/small-accidents-mean-big-trouble-for-supercollider.html From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:37:10 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:37:10 GMT Subject: Comparing float and decimal References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: <00eaf32a$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 04:30:03 -0500, Nick Craig-Wood wrote: > Both the Fraction module and the Decimal module could represent floats > exactly and reversibly since floats are of the form > > mantissa * 2**exponent > > which is exactly representable as a fraction (rational) and also as > > mantissa2 * 10**exponent2 > > as to why we don't do this... > > I guess it is to preserve the sanity of the user when they write > fraction(0.1) or decimal(0.1) did they really mean fraction(1,10), > decimal("0.1") or the exact representations which are > decimal("0.1000000000000000055511151231257827021181583404541015625") and > fraction(3602879701896397,2**55) I would say that in practice the chances that somebody *actually* wanted 0.1000000000000000055511151231257827021181583404541015625 when they wrote 0.1 is about the same as the chances that the BDFL will support braces in Python 3.0. (Hint: "from __future__ import braces") > Given that we let the exact representations leak out anyway (which > causes a lot of FAQs in this list), eg > >>>> 0.1 > 0.10000000000000001 > > IMHO We should put the exact conversions in for floats to Decimal and > Fraction by default and add a new section to the FAQ! But of the reasons for having the Decimal module is to avoid such leaky abstractions. Without Decimal (or fraction) there's no obvious way to get 0.1 exactly. It seems perverse to suggest that by default Decimal should deliberately expose the same leaky abstraction that causes so much trouble when people use floats. > In that way people will see floats for what they really are - a crude > approximation to a rational number ;-) You can already see that just by printing a float: >>> 0.3 0.29999999999999999 >>> 0.1 0.10000000000000001 -- Steven From akathorn at gmail.com Fri Sep 5 09:15:11 2008 From: akathorn at gmail.com (Akathorn Greyhat) Date: Fri, 5 Sep 2008 14:15:11 +0100 Subject: Curious: 2134 2004-10-06 08:55:20Z fredrik In-Reply-To: References: Message-ID: 2008/9/5 Gabriel Genellina > > > I'd say the import mechanism got confused about the actual source of the > error. Probably it happened on line 3 in *another* module, but the traceback > got messed. Perhaps "core" is a package and contains "import data" at line > 3? > > The $Id: stuff comes from some version control system -probably svn- and > identifies the file version. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list Interesting... =P You are right, the package "core" contains "import data", but that module doesn't exist, so it raises this strange error -- Akathorn Greyhat -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ron.Barak at lsi.com Tue Sep 16 04:29:54 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 16 Sep 2008 09:29:54 +0100 Subject: vim/gvim colour scheme for Python with white background ? Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6022A6B87@enbmail01.lsi.com> Hi Guys, Could anyone send me URL of a decent vim/gvim colour scheme for Python with white background ? Googling around, best I could find was python.vim (http://www.cs.cmu.edu/~maverick/VimColorSchemeTest/python.vim), but I'm not happy with quite a few of its choices. Instead of creating something from scratch (e.g., reinventing wheels) thought of ask the community what it uses. Thanks, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Thu Sep 25 14:03:36 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 25 Sep 2008 11:03:36 -0700 (PDT) Subject: How can I customize builtin module search path to prefix/lib to prefix/lib64? References: mailman.1503.1222357330.3487.python-list@python.org Message-ID: On Sep 25, 10:41?am, js wrote: > Hi list, > > Is it possible to change module search path (PYTHONPATH) built-in to > Python interpreter? > I thought I can change it with configure --libdir but it didn't work for me. > I also tried patching around python source tree replacing lib to lib64 > but it didn't work either. > > Adjusting sys.path directly or using environ should do the trick but > I'd rather want to make it the default path for my python > > Thanks, Why not just add a custom path file (*.pth)? EasyInstall, wx, PyWin32 and others do it. Of course there's always sys.path.append as well. Mike From fredrik at pythonware.com Sun Sep 14 15:37:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Sep 2008 21:37:16 +0200 Subject: Abstract class In-Reply-To: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> Message-ID: Mr.SpOOn wrote: > Well, I know the difference between an abstract class and an inherited > one. The idea was to create a main class Note, with abstract methods, > and implement these methods in the other classes. The pragmatic way to implement abstract classes in Python is to define an ordinary base class, and either just leave out the methods that must be defined in subclasses, or provide stub methods that simply raise a NotImplementedError exception: class AbstractThing(object): ... def some_method(self, args): raise NotImplementedError There are more "clever" ways to do things, but they're usually overkill. > Anyway, I think I need an abstract class. Or not? Depends on how much generally useful functionality you can come up with for the base class. It's not like Python prevents you from overriding a non-abstract method, after all. I suggest you skip further discussion and get to work. I'm sure you'll figure out what works best for your specific case once you've written a few classes. From castironpi at gmail.com Sun Sep 7 22:59:12 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 7 Sep 2008 19:59:12 -0700 (PDT) Subject: lacking follow-through References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <086a0906-c6f1-489c-91ab-f6a4f9e1ae3f@59g2000hsb.googlegroups.com> Message-ID: <99113520-2fa2-46ac-9894-ea78372ff610@c58g2000hsc.googlegroups.com> On Sep 7, 7:34?pm, MRAB wrote: > On Sep 7, 11:28?pm, "Eric Wertman" wrote: > > > +1 Bot > > I think it's like duck typing: it doesn't matter whether he's actually > a bot, only whether he behaves like one. Do you support the bot interface and methods? From ldo at geek-central.gen.new_zealand Mon Sep 29 05:16:25 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Mon, 29 Sep 2008 22:16:25 +1300 Subject: how to search multiple textfiles ? References: Message-ID: In message , George Sakkis wrote: > $ find -name "*py" | xargs egrep "\bword\b" Better: find -name '*.py' -exec grep -E "\bword\b" {} \; From tim.arnold at sas.com Thu Sep 25 08:16:18 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 25 Sep 2008 08:16:18 -0400 Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: "Tim Arnold" wrote in message news:57cdd3f1-cde8-45f5-b9d9-3eef32010bda at l43g2000hsh.googlegroups.com... >I have a bunch of processes to run and each one needs its own working > directory. I'd also like to know when all of the processes are > finished. Thanks for the ideas everyone--I now have some news tools in the toolbox. The task is to use pdflatex to compile a bunch of (>100) chapters and know when the book is complete (i.e. the book pdf is done and the separate chapter pdfs are finished. I have to wait for that before I start some postprocessing and reporting chores. My original scheme was to use a class to manage the builds with threads, calling pdflatex within each thread. Since pdflatex really does need to be in the directory with the source, I had a problem. I'm reading now about python's multiprocessing capabilty, but I think I can use Karthik's suggestion to call pdflatex in subprocess with the cwd set. That seems like the simple solution at this point, but I'm going to give Cameron's pipes suggestion a go as well. In any case, it's clear I need to rethink the problem. Thanks to everyone for helping me get past my brain-lock. --Tim Arnold From nospam at spamhaters.com Sun Sep 7 16:56:54 2008 From: nospam at spamhaters.com (sc) Date: Sun, 07 Sep 2008 15:56:54 -0500 Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Sat, 06 Sep 2008 17:18:55 -0300, clurker > escribi?: > >> Michele Simionato wrote: >> >>> On Aug 28, 6:21?am, ssecorp wrote: >>>> Is there a way to view all the modules I have available for import >>>> from within Python? >>>> Like writing in the interpreter: >>> >>> Try: >>> >>>>>> help() >>> help> modules >>> Please wait a moment while I gather a list of all available modules... >>> >> >> This looks like it could be a useful tool, but when I try it >> I get the following: >> >> Please wait a moment while I gather a list of all available modules... > [...] >> File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line >> 1342, >> in >> >> File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line >> 927, >> in main >> >> UnboundLocalError: local variable 'given_files' referenced before >> assignment >>>>> > > Unfortunately the "modules" help command actually imports all the > available packages, and a buggy one may stop the whole process with an > error. > >> Apparently python knows about them both, but I don't know I >> haven't introduced an incompatibility somewhere...and that PIL >> package showing up at the tail of the errors was one of my >> more recent additions... > > If import of a package fails, the error reported is not accurate. In this > case, probably some other package failed, that itself imported PIL. Line > 927 in PIL/__init__.py does not exist. > > A quick fix is to replace line 1854 in pydoc.py (ModuleScanner.run) with > this one: > > for importer, modname, ispkg in > pkgutil.walk_packages(onerror=lambda name:None): > > (the onerror argument makes it to ignore all errors) > nice Gabriel, thanx! At least now "help(); modules" gives me a beautiful list -- I guess I'll find out what the buggy module is if/when I try to use it...(all PIL/__init__.py is is about 15 lines of comments (referencing a README I can't find)) sc From martin at v.loewis.de Fri Sep 19 02:18:49 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 19 Sep 2008 08:18:49 +0200 Subject: CTypes on a 64 bit machine truncates pointers to 32 bits? In-Reply-To: References: Message-ID: <48d34449$0$2363$9b622d9e@news.freenet.de> >>>> foolib = cdll.LoadLibrary('foo.so') >>>> foolib.foo(0xF00000000) > 0 Shouldn't you tell ctypes that the argument and the result of foo is a pointer? Regards, Martin From berthold at despammed.com Thu Sep 11 03:11:59 2008 From: berthold at despammed.com (Berthold =?iso-8859-15?Q?H=F6llmann?=) Date: Thu, 11 Sep 2008 09:11:59 +0200 Subject: Refcount problem in ceval.c References: Message-ID: Christian Heimes writes: > Berthold H?llmann wrote: >> Is there any "common" reason to for such a strange object on the command >> stack, or is it more likely that any of my extension modules is causing >> havoc? > > It's very likely that your extension has a reference counting bug. It > looks like you are either missing a Py_INCREF or you have a Py_DECREF > too much. Newly freed memory is filled with 0xDB (see > Objects/obmalloc.c DEADBYTE). I was suspecting this, that's why I build the debugging version of Python. I hoped I would get the error message somewhere near the code causing the error, but I seems i have to continue the search. > Wild guess: Are you using PyModule_AddObject with a PyTypeObject w/o > Py_INCREF()ing the type object first? That would have been easy :-) I have only one occurrence of PyModule_AddObject, and its PyTypeObject is Py_INCREF()ed Thanks Berthold -- __ Address: G / \ L Germanischer Lloyd phone: +49-40-36149-7374 -+----+- Vorsetzen 35 P.O.Box 111606 fax : +49-40-36149-7320 \__/ D-20459 Hamburg D-20416 Hamburg -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 194 bytes Desc: not available URL: From deets at nospam.web.de Thu Sep 11 14:07:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 Sep 2008 20:07:30 +0200 Subject: conditional install/distribution In-Reply-To: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> References: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> Message-ID: <6it533Fe2h8U1@mid.uni-berlin.de> i3dmaster schrieb: > Is there a feature in distutils or easy_install to specify what > version of python that the target package can be installed? For > example, if a package has a module that only needed if the python > version < 2.6, is there a way to specifiy that in setup.py or > easy_install cfg file so that when installing to python >= 2.6, this > module wouldn't be installed?? you can simply import sys and check sys.version in the setup-script, and abort with an error-message if the expectations aren't matched. Diez From fredrik at pythonware.com Thu Sep 4 12:03:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 18:03:54 +0200 Subject: Read Binary data In-Reply-To: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> References: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> Message-ID: "Mars creature" wrote: > I am trying to read a binary file created by the following matlab > command: > fid=fopen('a.bin','w','b'); fwrite(fid,a,'real*8'); fclose(fid);, and > wondering how to do it in Python. I googled it but still get > confused. > 'b' in fopen is for 'big-endian', 'real*8' in fwrite is for 64bit > float. f = open("a.bin", "rb") # read binary data s = f.read() # read all bytes into a string import array, sys a = array.array("f", s) # "f" for float if sys.byteorder != "big": a.byteswap() From denisbz at t-online.de Wed Sep 10 06:52:09 2008 From: denisbz at t-online.de (denisbz at t-online.de) Date: Wed, 10 Sep 2008 03:52:09 -0700 (PDT) Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: > > A quick fix is to replace line 1854 in pydoc.py (ModuleScanner.run) with > > this one: > > > ? ? ? ? for importer, modname, ispkg in > > ? ? ? ? pkgutil.walk_packages(onerror=lambda name:None): > > > (the onerror argument makes it to ignore all errors) well not all, for example GLUT: Fatal Error in summon: could not open display: :0.0 So to refine the question: how can I list all modules that might be importable on my system, without actually importing them all ? (How about a "pydoc2" that's well thought out, doesn't crash ... let me ask more knowledgable people, what's a good small help system as model ? ) cheers -- denis From half.italian at gmail.com Tue Sep 16 03:58:58 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Tue, 16 Sep 2008 00:58:58 -0700 (PDT) Subject: Python GUI for animation References: Message-ID: <1896f3dc-d8b6-41f4-9ff2-4c9cefc1ab84@a18g2000pra.googlegroups.com> On Sep 15, 11:29?pm, Virgil Stokes wrote: > I have been using Python for a short time and I find it a very flexible > language, and easy to learn and use. I have also worked some with PyGame > and used it to create a simple animation that is controlled by the mouse > and keyboard. The animation is designed to move filled circles around on > the screen and is driven by a data file that defines (indirectly), the > next relative position of each circle. And for my purposes (queueing > demo in the classroom) this works quite well. However, I would now like > to create a Python GUI that would allow a user to control the animation, > via buttons, sliders, etc. > > I am certainly not a Python expert and have never worked with the > creation of a GUI. I would appreciate greatly any advice from those who > have worked with Python GUIs as to the best way to proceed. > > Thank you in advance, > V. Stokes I think Tkinter would be a good starting point. It is pretty simple to use and gives you lots of freedom to create whatever you want. It doesn't look as nice as some of the other GUI toolkits, but it is generally easier to work with. http://wiki.python.org/moin/TkInter Then again, you mention sliders, knobs, etc. I don't think Tkinter has alot of widgets built in. The other choice would be wxPython. It's got lots of built in widgets, and it looks pretty good. If you go this route, run the demo application to see what you have to work with. http://wxpython.org/ Good luck. ~Sean From simon at brunningonline.net Wed Sep 3 13:01:58 2008 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 3 Sep 2008 18:01:58 +0100 Subject: Coming from .NET and VB and C In-Reply-To: References: Message-ID: <8c7f10c60809031001i39794ca4x1a3e4131408d3317@mail.gmail.com> 2008/9/3 ToPostMustJoinGroup22 : > Any suggestions for someone new to the scene like me? Welcome! There's a number of resources that you might find useful here: http://wiki.python.org/moin/BeginnersGuide -- Cheers, Simon B. From tjreedy at udel.edu Sat Sep 20 12:58:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 Sep 2008 12:58:56 -0400 Subject: how can i check whether a variable is iterable in my code? In-Reply-To: <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> References: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> Message-ID: satoru wrote: > On Sep 20, 6:35 pm, Aidan wrote: >> satoru wrote: >>> hi, all >>> i want to check if a variable is iterable like a list, how can i >>> implement this? >> this would be one way, though I'm sure others exist: >> >> if hasattr(yourVar, '__iter__'): >> # do stuff > > thank you,but this will miss out sequences like string just because it > doesn't have an attribute named '__iter__' In 3.0, it does. Such consistency is one of the advantages of 3.0. In at least some 2.x's, str still uses the older __getitem__ iteration protocol. I am not sure about other built-in sequences. From pavlovevidence at gmail.com Fri Sep 12 17:46:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 12 Sep 2008 14:46:41 -0700 (PDT) Subject: Accessing __slots__ from C References: <8763p1799y.fsf@mulj.homelinux.net> Message-ID: On Sep 12, 10:01?am, Hrvoje Niksic wrote: > Chris writes: > >> descr = GetAttrString(cls,"varname"); > >> offset = descr->d_member->offset; > >> slotvar = (PyObject*)(((char*)obj)+offset) > > > Unfortunately, I am inexperienced at this kind of thing, so I wasn't > > able to get something working. Maybe someone could tell me what's > > wrong with the code below (it gives the error "'struct _object' has no > > member named 'd_member'")? > > You are getting that error because Carl forgot to cast the descriptor > to the appropriate C type, in this case PyMemberDescrObject. ?The last > line is also incorrect, I think. Yep, was in too much of a hurry to waste too much time showing how to do something slightly dubious. The offsetof() macro would help for the third line (in fact, it's the recommended standard way since there are some C implmentions, somewhere, that the pointer artithmetic method fails). Carl Banks From timr at probo.com Wed Sep 17 02:16:25 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 17 Sep 2008 06:16:25 GMT Subject: help on python SWIG C++ extension References: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> Message-ID: RLC wrote: > >I am new to python SWIG. Recently I wrote a small program trying to >import collada files(using colladadom) into python so I could use >python cgkit to render them. However, during the progressing, I got >some problems. Every time I quit from Python, I get a segmentation >fault, although the main program runs well. I suspect it is because I >wrapped std::vector objects in C struct and I did not release the >memory properly. That won't cause a segmentation fault. However, I notice that you are using "malloc" and "free" to allocate and free your objects. "stl" will use "new" and "delete", and it's not always healthy to mix them. If I were you, I'd replace this: > Vertex *v; > v = (Vertex *)malloc(sizeof(Vertex)); with this, which is less typing: Vertex * x = new Vertex; -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dudeja.rajat at gmail.com Tue Sep 2 10:32:07 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 2 Sep 2008 15:32:07 +0100 Subject: What is module initialization? In-Reply-To: <48bd4799$0$17215$426a74cc@news.free.fr> References: <48bd4799$0$17215$426a74cc@news.free.fr> Message-ID: > While this is technically legal, you should restrain yourself from doing > such a thing, unless you *really* know what you're doing and why. > >> but the variable is not getting updated in the module >> containing global symbols ( variables). > > I suspect you didn't use a qualified name when importing. You have to do it > this way : > > # myglobals.py: > answer = 42 > > # question.py > import myglobals > myglobals.answer = "WTF ?" > But if I do :- #question.py from myglobals import * myglobals.answer = "WTF ?" will this work? From shahmed at sfwmd.gov Wed Sep 10 11:22:16 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Wed, 10 Sep 2008 11:22:16 -0400 Subject: removing text string In-Reply-To: References: Message-ID: I need to remove text string from the list of the numbers mentioned below: 080829-7_A 070529-5_c 080824-7_O 070405_6_p The output will be : 080829-7 070529-5 080824-7 070405-6 Any idea is highly appreciated. From rridge at csclub.uwaterloo.ca Tue Sep 9 16:19:33 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 09 Sep 2008 16:19:33 -0400 Subject: universal unicode font for reportlab References: Message-ID: Terry Reedy wrote: >Sorry, I posted the wrong name. >Ariel Unicode MS is the one that seems pretty complete. ... > From the MS, I would guess that is a Windows font too ;-). It's made by Microsoft, but it's not a standard Windows font. I think it comes with Microsoft Office. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From sturlamolden at yahoo.no Thu Sep 25 07:02:10 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 04:02:10 -0700 (PDT) Subject: Linq to Python References: Message-ID: On 25 Sep, 12:06, hrishy wrote: > [code] > var stoogeGuys = > ? ? ?Beginning with the XML source > ? ? ?from xmlGuys in xmlSource.Descendants("Stooge") > ? ? ?Join to the array on the common element "stoogeName" > ? ? ?join arrayGuys in familyFacts > ? ? ? ? ? ?on xmlGuys.Element("stoogeName").Value equals arrayGuys.stoogeName > ? ? ?Join to the database on the common element "stoogeName" > ? ? ?join dbGuys in stoogeContext.stoogeTables > ? ? ? ? ? ?on xmlGuys.Element("stoogeName").Value equals dbGuys.stoogeName > ? ? ?select new > ? ? ?{ > ? ? ? ? firstName ? ?= dbGuys.stoogeName, > ? ? ? ? familyName ? = arrayGuys.familyName, > ? ? ? ? birthDate ? ?= xmlGuys.Element("birthDate").Value, > ? ? ? ? deathDate ? ?= xmlGuys.Element("deathDate").Value, > ? ? ? ? hairCutStyle = dbGuys.stoogeHaircut, > ? ? ?}; > [/code] It could e.g. look like this in Python: stoogeGuys = [] for xmlGuys in xmlSource.Descendants["Stooge"]: arrayGuys = familyFacts[xmlGuys.stoogeName] dbGuys = stoogeContext.stoogeTables[xmlGuys.stoogeName] stoogeGuys += \ [{'firstName': dbGuys.stoogeName, 'familyName': arrayGuys.familyName, 'birthDate': xmlGuys.birthDate, 'deathDate': dbGuys.deathDate, 'hairCutStyle': dbGuys.stoogeHaircut}] From aidan at gmail.com Sat Sep 20 06:35:52 2008 From: aidan at gmail.com (Aidan) Date: Sat, 20 Sep 2008 20:35:52 +1000 Subject: how can i check whether a variable is iterable in my code? In-Reply-To: References: Message-ID: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> satoru wrote: > hi, all > i want to check if a variable is iterable like a list, how can i > implement this? this would be one way, though I'm sure others exist: if hasattr(yourVar, '__iter__'): # do stuff From bignose+hates-spam at benfinney.id.au Fri Sep 26 03:13:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 26 Sep 2008 17:13:29 +1000 Subject: Writing a well-behaved daemon References: <874p43wl2m.fsf@benfinney.id.au> Message-ID: <87zllvv0py.fsf@benfinney.id.au> Sean DiZazzo writes: > Looks like somebody did the same thing I did and posted it. > > http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemon.py Thanks, I've not seen that before. It still seems loony to me that something this difficult to do right, yet so similar across different use cases, isn't in the standard library, where bugs need only be fixed in one place. -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but how will we get three pink flamingos into one | _o__) pair of Capri pants?? ?_Pinky and The Brain_ | Ben Finney From academicedgar at gmail.com Sat Sep 20 23:51:52 2008 From: academicedgar at gmail.com (academicedgar at gmail.com) Date: Sat, 20 Sep 2008 20:51:52 -0700 (PDT) Subject: BeautifulSoup and Problem Tables Message-ID: Hi I would appreciate some help. I am trying to learn Python and want to use BeautifulSoup to pull some data from tables. I was really psyched earlier tonight when I discovered that I could do this from BeautifulSoup import BeautifulSoup bst=file(r"c:\bstest.htm").read() soup=BeautifulSoup(bst) rows=soup.findAll('tr') len(rows) a=len(rows[0].findAll('td')) b=len(rows[1].findAll('td')) c=len(rows[2].findAll('td')) d=len(rows[3].findAll('td')) e=len(rows[4].findAll('td')) f=len(rows[5].findAll('td')) g=len(rows[6].findAll('td')) h=len(rows[8].findAll('td')) i=len(rows[9].findAll('td')) j=len(rows[10].findAll('td')) k=rows[1].findAll('td')[1].contents[0] So here I am chortling to myself thinking this is too easy. I know that the data columns are in rows[0] and so I can learn some more python to figure out how to create tuples so I can lable each data item using the row and column headings plucked from the contents. However, I discovered that my tables have inconsistent numbers of rows. Even though the tables look pretty. It might be that the column heading for the third column is "Apples" but the value for "Apples" in the fourth row is not in the third position in the row but the fourth. Now I am reluctant to make any assumptions because the tables were created inconsistently. What I mean is that in some tables if there is no value for a row/column intersection then there is a blank line, in other tables if there is no value for a row/column intersection then the length of k (as above) is 0. I have been Googling for some insight into this and I have not been successful finding anything. I would really appreciate any suggestions or some direction about how to better describe the problem. From tino at wildenhain.de Tue Sep 30 04:43:26 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Tue, 30 Sep 2008 10:43:26 +0200 Subject: Python script for tracert In-Reply-To: <46da4e770809292353o2d72091aj6e717e35e62cfce6@mail.gmail.com> References: <46da4e770809292353o2d72091aj6e717e35e62cfce6@mail.gmail.com> Message-ID: <48E1E6AE.8090408@wildenhain.de> cindy jones wrote: > Hello.. I'm trying to do a scripting for tracert in windows using python... > I'm using popen(), but it displays only after the tracert is completed. > i want the results to be displayed for every route. I believe "tracert" is a really ugly 8.3 abbrevivation of traceroute ;) Well, maybe an implementation in python itself could be of interest? http://mail.python.org/pipermail/python-list/2003-March/196063.html maybe there are more attempts - this one was just the first thing which popped up with g**gle. (The script is in the attachment). Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From mensanator at aol.com Sat Sep 20 12:27:10 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 20 Sep 2008 09:27:10 -0700 (PDT) Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) Message-ID: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> Beacuse in 2.6, Python apparently has fixed a discrepency that existed in previous versions. In the IDLE that comes with 2.5, typing "as", to wit "import random as ran", the words "import" and "as" highlight in red, so you can't use them as variable names or you'll get a syntax error. Ah, but you CAN use "as" for a variable: "for as in xrange(10): print as" works just fine, although it shouldn't. Python 2.6 fixes this discrepency and now gives you a syntax error if you use "as" for a variable name. The upshot is code (such as sympy) written prior to 2.6 can crash now due to this fix if said code inadverntently used what should have been a reserved word. I was able to fix the code for this "as" problem, but not the one that came after. I've reported this and interested parties can visit the sympy page and check Issue 1115. From gagsl-py2 at yahoo.com.ar Tue Sep 16 00:56:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 01:56:47 -0300 Subject: Converting .py files to batch files. References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> <65c8af7c-23b4-421e-82d0-325fff1d68bb@y21g2000hsf.googlegroups.com> Message-ID: En Mon, 15 Sep 2008 20:36:05 -0300, Michael Palmer escribi?: >> aditya shukla escribi?: >> >> > How can we convert .py files to batch files? is there any library for >> this? > > I assume you are on Windows? Let's assume you have a file stuff.py > that reads: > > import os > print os.listdir('.') # list current directory, good enough for > testing... > > Then, insert the following line at the top: > > @setlocal enableextensions & python -x %~f0 %* & goto :EOF > > Now save this file as stuff.cmd somewhere along your PATH. Now calling > 'stuff' should execute your file. Cool! I'd enclose the first argument in quotes "%~f0" - in case the path contains any whitespace. -- Gabriel Genellina From castironpi at gmail.com Thu Sep 4 15:45:33 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 12:45:33 -0700 (PDT) Subject: Safely move an element into a heap References: <778c30a9-f097-4789-b1d6-3b40a9f11bdf@p31g2000prf.googlegroups.com> Message-ID: <74bd29ee-ebe4-4ab7-a3ae-2935daf4776c@s20g2000prd.googlegroups.com> On Sep 4, 6:57?am, "Giampaolo Rodola'" wrote: > On 4 Set, 13:49, Alexandru Palade > wrote: > > > > > I'm not sure what you expect as an answer, but if you mean the heap as > > in the data structure, you can not just arbitrarily move one key where > > you want as it will destroy the heap property. > > > Giampaolo Rodola' wrote: > > > Hi, > > > I wanted to know if does exist a safe way to, given a heap, move an > > > arbitrary element to the first position of the heap. > > > Something like: > > > > ?>>> heap = [0,3,6,8,10] > > > ?>>> heapq.move_to_first_position(heap, 4) > > > ?>>> heap = [10, 0,3,6,8] > > > > --- Giampaolo > > >http://code.google.com/p/pyftpdlib/ > > > -- > > >http://mail.python.org/mailman/listinfo/python-list-Nascondi testo citato > > > - Mostra testo citato - > > Could I be able to do that if every element I want to move will have > the value of 0 which is the smallest value I can have into my heap? > What I'm trying to do is implementing a timeout: sometimes I want a > given event which was scheduled to happen within X seconds to happen > immediately. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ Change its timeout to -1 and reheapify. Or maintain 'zeroes' in a separate structure. From fredo66 at fulladsl.be Thu Sep 25 04:03:15 2008 From: fredo66 at fulladsl.be (fredo66 at fulladsl.be) Date: Thu, 25 Sep 2008 01:03:15 -0700 (PDT) Subject: python sorting 2dim. array ? Message-ID: <9684e81b-df99-4d95-99f9-8345c125b69b@d77g2000hsb.googlegroups.com> hello, Can someone help me with this: I have a array like this list[rowindex][colomindex] where rows are the records and colom the fields. If I use the .sort() method on 'list' the data is sorted on the items of the first colom. But I want to sort on the second colom as first (and as second sortfield the first colom). What is the shortest code for this pls ? (all fields are text value, first colom is name, second category) From aahz at pythoncraft.com Sun Sep 21 00:24:50 2008 From: aahz at pythoncraft.com (Aahz) Date: 20 Sep 2008 21:24:50 -0700 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: In article , Thomas G. Willis wrote: >On Sep 20, 5:23=A0am, candide wrote: >> >> Excerpt quoted fromhttp://www.astro.ufl.edu/~warner/prog/python.html: >> >> "About Python: Python is a high level scripting language with object >> oriented features. >> (...) >> Python supports OOP and classes to an extent, but is not a full OOP >> language." >> >> Thanks for any comment. > >My comment is "Who cares?" > >I was always under the impression that if any language truly was "OO" >it would be smalltalk. And I don't derive any benefit from smalltalk >at all. I do however derive substantial benefit from other languages >that "OO zealots" would likely poo poo on including python. "...some experts might say a C++ program is not object-oriented without inheritance and virtual functions. As one of the early Smalltalk implementors myself, I can say they are full of themselves." --zconcept -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From mauriceling at gmail.com Sun Sep 7 09:50:10 2008 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Sun, 7 Sep 2008 06:50:10 -0700 (PDT) Subject: [ANN] The Python Papers Vol 3 Iss 2 in one PDF Message-ID: Hi everyone Our original release of TPP Volume 3 Issue 2 is in the form of one PDF per article. A number of readers had kindly requested for a parallel release for the entire issue in a single PDF for easy transport. Despite prevalent "industrial standards" for one PDF per article such as IEEE and ACM, we can understand our readers' point of view. We can see mutually exclusive advantages of both system - one PDF per article allows for tracking of view counts for each article whereas one PDF per issue allows for easy transport and offline browsing. Therefore, we had chose to released the entire volume as a single PDF in parallel and will continue to do so in future. The entire Volume 2 Issue 3 can be accessed from http://www.pythonpapers.org. We look forward to your continued support and contributions. Regards Maurice Ling Co-EIC, TPPA From michel at nospam.please Mon Sep 15 15:21:16 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 21:21:16 +0200 Subject: Python Nautilus script Message-ID: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> Hi, I'm trying to write a python script for Nautilus. To get the list of files selected in the Nautilus right pane, you use the $NAUTILUS_SCRIPT_SELECTED_FILE_PATHS environment variable which is normally available to the script. Actually, it works with bash scripts but not with python scripts import os files = os.environ['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'].splitlines() gives a: File "", line 1, in File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ raise KeyError(key) KeyError: 'NAUTILUS_SCRIPT_SELECTED_FILE_PATHS' Fredrik Lundh explained me that all environment variables are not accessible from subprocesses of an application. So my question is how can I get the Nautilus selected files in a python script? Thanks, Michel -- Michel Leunen http://linux.leunen.com From steve at holdenweb.com Fri Sep 12 08:16:08 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 08:16:08 -0400 Subject: lacking follow-through In-Reply-To: <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> Message-ID: castironpi wrote: > On Sep 7, 5:03 pm, Marc 'BlackJack' Rintsch wrote: >> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: >>> This is the strangest post I've seen >>> since I've joined this list (only >>> recently). What the ? >> Yeah, castironpi sometimes doesn't make much sense. Maybe because it's a >> bot!? :-) >> >> Ciao, >> Marc 'BlackJack' Rintsch > > No, I'm legit, and I believe my complaint is. That's all I can > guarantee anyway. While I'm still not a vet on Usenet, I'm still > disappointed so far. Though I should be flattered for my logic to be > ever compared to an A.I.'s. > Your various outpourings appear so rambling and ill-conceived that silence is often the only polite response. If you are flattered to be compared to an AI you must come from the same race as Mr. Spock in Star Trek. > Maybe the ideas are not that groundbreaking, but they still have been > dropped instead of critiqued. Problem. You aren't entitled to require discussion of your ideas and proposals. The usual way of obtaining responses is to engage in a dialog, responding intelligently and directly to any criticism or discussion. But it's often difficult to discern what point you are trying to make. This may be a linguistic issue, or it may be because you are running some bizarre experiment. The jury appears to still be out on that question. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From moogyd at yahoo.co.uk Sun Sep 14 05:29:52 2008 From: moogyd at yahoo.co.uk (moogyd at yahoo.co.uk) Date: Sun, 14 Sep 2008 02:29:52 -0700 (PDT) Subject: noob: subprocess clarification Message-ID: <68fcdea2-804e-4fba-958e-47ecee277faf@s50g2000hsb.googlegroups.com> Hi, I generally use csh scripts for generally scripting (controlling simulations). Basically the script processing options, generates the command line, executes it and then processes the results. I would usually use the -f option on the shebang line to ensure that the environment from the current shell is used. i.e. #!/bin/csh -f How do I acheive this in python? I have been looking at the import subprocess as sub p = sub.Popen(['echo $PATH'],shell=True).wait() This *seems* to do what I want (in that the path looks correct), but I don't really understand the documentation. Can somebody please clarify what the shell=True does, and whether I am using it correctly. Thanks, Steven From dave.dibiase at gmail.com Thu Sep 25 23:57:06 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Thu, 25 Sep 2008 23:57:06 -0400 Subject: Fastest way to max() list Message-ID: I have a list with about 1000-1500 sub-lists which look like so: list[-0.28817955213290786, 3.6693631467403929, 'H', 31.31225233035784]] The first and second values are Angstrom units specifying the location of a particle. What I'd like to do is determine the distance between the smallest and largest value in the arrays first position 0. I tried reading the manual for this but I don't see how it applies key or any of those other commands to the function. I could easily write a sort to do this and capture the first and last spots, but why do that when I can use max and min (if I can actually do that...). So you wonderful Python gods, lay some knowledge on me. please? lol... while I'm at it, is there a way to modify an entire list without having to produce a whole new one? For example now say I want to modify list[0] and multiply it by some value. From what I understand previous version of Python allowed lists to be multiplied like matrices...now apparently it just replicates the list. :-/ shucks... The first question would be useful to know, but the second question I do quite a bit of and the "best practice" would be really great to know! Thanks in advanced! -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitry at athabascau.ca Thu Sep 25 15:36:16 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 19:36:16 GMT Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> <48dbc82e$0$1120$426a74cc@news.free.fr> <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: >> I kept this part of the problem out of this discussion as I'm pretty sure >> I can fill those in once I figure out the basic problem of >> auto-population of proxy methods since for each class/method those are >> going to be nearly identical. If I can autogenerate those on-the-fly I'm >> pretty sure I can add some extra-logic to them as well including >> signature change where A::bmethod(self,c,x) would become >> A::bmethod(self,x) etc. > > Do you want to couple instances or classes together? It would be nice to have objects of B, C and D classes not knowing that they are proxied (as they are used on their own too, not only inside of A objects). > If A always proxies for B, C, and D, then the wrapper solution isn't > bad. the whole purpose of A is pretty much to proxy and filter. It's got some extra logic to combine and manipulate b, c and d objects inside of A class objects. > If you're going to be doing any instance magic, that can change > the solution a little bit. > > There's also a revision of the first implementation of Aproxy you > posted, which could stand alone as you have it, or work as a > classmethod or staticmethod. > > def Aproxy(fn): > def delegate(self,*args,**kw): > print "%s::%s" % (args[0].__class__.__name__,fn.__name__) > fnew=getattr(self.b,fn.__name__) > return fnew(*args,**kw) > setattr(A,fn.__name__,delegate) > return fn yep, that does look nicer/cleaner :) From invalid at invalid Mon Sep 15 16:40:50 2008 From: invalid at invalid (Grant Edwards) Date: Mon, 15 Sep 2008 15:40:50 -0500 Subject: append on lists References: Message-ID: <2ZKdnYWXv5bPVVPVnZ2dnUVZ_vGdnZ2d@posted.visi> On 2008-09-15, Armin wrote: >> Because .append() mutates 'a' and appends the item in-place rather >> than creating and returning a new list with the item appended, and >> it's good Python style for mutating methods to have no return value >> (since all functions must have some return value, Python uses None >> when the function doesn't explicitly return anything). > > Yes, but this is very unconvenient. Aw, admit it -- it's not _that_ inconvenient. > If d should reference the list a extended with a single list > element you need at least two lines > > a.append(7) > d=a With that usage it's obvious that a is mutated, and now both "a" and "d" are bound to the same extended list. > and not more intuitive d = a.append(7) Becase that usage implies (at least to many of us) that "a" is unchanged, and that "d" is now bound to a different object than "a". -- Grant Edwards grante Yow! Where's th' DAFFY at DUCK EXHIBIT?? visi.com From joncle at googlemail.com Wed Sep 10 12:20:33 2008 From: joncle at googlemail.com (Jon Clements) Date: Wed, 10 Sep 2008 09:20:33 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: Message-ID: <82f4dc99-0027-4c9a-b2b9-42b959a8d510@y38g2000hsy.googlegroups.com> On 10 Sep, 16:28, hofer wrote: > Hi, > > Let's take following perl code snippet: > > %myhash=( one ?=> 1 ? ?, two ? => 2 ? ?, three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' ? : 1 ? ?, 'two' ? : 2 ? ?, 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as ?split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] > > print "%s\n%s\n%s" %(v1,v2,v3) > > thanks for any ideas Another option [note I'm not stating it's preferred, but it would appear to be closer to some syntax that you'd prefer to use....] >>> from operator import itemgetter >>> x = { 'one' : 1, 'two' : 2, 'three' : 3 } >>> itemgetter('one', 'one', 'two')(x) (1, 1, 2) hth Jon. From circularfunc at yahoo.se Wed Sep 17 12:29:47 2008 From: circularfunc at yahoo.se (cnb) Date: Wed, 17 Sep 2008 09:29:47 -0700 (PDT) Subject: python-mode problem, doesnt load whole module? Message-ID: <9b26d9fd-3fe2-4d58-acce-015923d31b50@d1g2000hsg.googlegroups.com> >>> a = parsing.unserialize("C:/users/saftarn/desktop/twok.txt") Traceback (most recent call last): File "", line 1, in File "C:\Python25\Progs\NetflixRecSys\parsing.py", line 91, in unserialize return pickle.load(open(filename, 'r')) File "C:\Python25\lib\pickle.py", line 1370, in load return Unpickler(file).load() File "C:\Python25\lib\pickle.py", line 858, in load dispatch[key](self) File "C:\Python25\lib\pickle.py", line 1090, in load_global klass = self.find_class(module, name) File "C:\Python25\lib\pickle.py", line 1126, in find_class klass = getattr(mod, name) if i use the python-gui-editor-repl it works though... so isn't emacs loading modules properly? this shouldnt have to do with emacs itself though, right? From mensanator at aol.com Thu Sep 4 13:57:35 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 4 Sep 2008 10:57:35 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> Message-ID: <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> On Sep 4, 2:05?am, Thomas Bellman wrote: > Mensanator wrote: > > No, but blank cells are 0 as far as Excel is concerned. > > That behaviour causes nothing but trouble and I am > > saddened to see Python emulate such nonsense. > > Then you should feel glad that the Python sum() function *does* > signal an error for the closest equivalent of "blank cells" in > a list: > > ? ? >>> sum([1, 2, 3, None, 5, 6]) > ? ? Traceback (most recent call last): > ? ? ? File "", line 1, in > ? ? TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' Yes, I am in fact happy to see that behaviour. > > Summing the elements of an empty list is *not* the same thing as > summing elements of a list where one element is None. So, >>> sum([1, 2, 3, None, 5, 6]) Traceback (most recent call last): File "", line 1, in sum([1, 2, 3, None, 5, 6]) TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' gives me an error. As does >>> sum([None, None, None, None, None, None]) Traceback (most recent call last): File "", line 1, in sum([None, None, None, None, None, None]) TypeError: unsupported operand type(s) for +: 'int' and 'NoneType' Why then, doesn't >>> sum([A for A in [None, None, None, None, None, None] if A != None]) 0 give me an error? Ok, it's not a bug. "This behaviour is by design." - Microsoft Knowledge Base I don't like it, but I guess I'll just have to live with it. > > > There are no "empty" boxes. There are only boxes with > > known quantities and those with unknown quantities. > > I hope that's not too ivory tower. > > The sum() function in Python requires exactly one box. ?That box > can be empty, can contain "known quantities" (numbers, presumably), > or "unknown quantities" (non-numbers, e.g., None). ?But you can't > give it zero boxes, or three boxes. > > I don't have a strong view of whether sum([]) should return 0 or > raise an error, but please do not mix that question up with what > a sum over empty cells or over NULL values should yield. ?They > are very different questions. Ok, but I don't understand why an empty list is a valid sum whereas a list containing None is not. > > As it happens, the SQL sum() function (at least in MySQL; I don't > have any other database easily available, nor any SQL standard to > read) does return NULL for a sum over the empty sequence, so you > could argue that that would be the correct behaviour for the > Python sum() function as well, but you can't argue that because a > sum *involving* a NULL value returns NULL. I'm not following that. Are you saying a query that returns no records doesn't have a specific field containg a Null so there are no Nulls to poison the sum? ...tap...tap...tap. Ok, I can see that, but you don't get 0 either. > > -- > Thomas Bellman, ? Lysator Computer Club, ? Link?ping University, ?Sweden > "This isn't right. ?This isn't even wrong." ?! ?bellman @ lysator.liu.se > ? ? ? ? ? ? ? ? ? ? ? ? ?-- Wolfgang Pauli ? ! ?Make Love -- Nicht Wahr! From larudwer at freenet.de Sat Sep 6 09:02:42 2008 From: larudwer at freenet.de (Ruediger) Date: Sat, 06 Sep 2008 15:02:42 +0200 Subject: why is self not passed to id()? References: Message-ID: I found following solution to the problem. Instead of assigning id directly to __hash__ it has to be wrapped with an instancemethod object. It is somehow strange that this doesn't happen automatically and it is also strange that instancemethod isn't exposed in the type module. However it can easily be done and is speeding things up by almost an factor of 2. Thank's again for all the help. R?diger ****************************************************************** class foo(list): __hash__ = lambda x: id(x) instancemethod = type(foo.__hash__) class bar(list): pass bar.__hash__ = instancemethod(id, None, bar) def test0( obj ): _s_ = set() _s_add = _s_.add _s_pop = _s_.pop for _i_ in xrange(1000000): _s_add(obj()) _s_pop() def test1(): return test0(foo) def test2(): return test0(bar) if __name__ == '__main__': test1() test2() pass ****************************************************************** python -m cProfile test01.py 6000010 function calls in 30.547 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 30.547 30.547 :1() 1 0.000 0.000 30.547 30.547 test01.py:1() 1 0.000 0.000 0.000 0.000 test01.py:1(foo) 2 10.784 5.392 30.547 15.273 test01.py:10(test0) 1 0.000 0.000 19.543 19.543 test01.py:18(test1) 1000000 4.554 0.000 6.700 0.000 test01.py:2() 1 0.000 0.000 11.003 11.003 test01.py:20(test2) 1 0.000 0.000 0.000 0.000 test01.py:6(bar) 1 0.001 0.001 30.547 30.547 {execfile} 1000000 2.146 0.000 2.146 0.000 {id} 2000000 8.626 0.000 15.327 0.000 {method 'add' of 'set'objects} 2000000 4.436 0.000 4.436 0.000 {method 'pop' of 'set'objects} From jeffober at gmail.com Mon Sep 22 16:04:31 2008 From: jeffober at gmail.com (Jeff) Date: Mon, 22 Sep 2008 13:04:31 -0700 (PDT) Subject: Job queue using xmlrpc and threading References: Message-ID: Try using the Queue module - http://docs.python.org/lib/module-Queue.html. Here is a tutorial with it - http://www.artfulcode.net/articles/multi-threading-python/. From gagsl-py2 at yahoo.com.ar Tue Sep 30 17:55:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 18:55:27 -0300 Subject: Python script for tracert References: <46da4e770809292353o2d72091aj6e717e35e62cfce6@mail.gmail.com> Message-ID: En Tue, 30 Sep 2008 03:53:21 -0300, cindy jones escribi?: > Hello.. I'm trying to do a scripting for tracert in windows using > python... > I'm using popen(), but it displays only after the tracert is completed. i > want the results to be displayed for every route. > > can anyone help me in this.. Use the subprocess module: import subprocess host = 'www.microsoft.com' p = subprocess.Popen(["tracert", '-d', '-w', '100', host], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while True: line = p.stdout.readline() if not line: break print '-->',line, p.wait() -- Gabriel Genellina From rcdailey at gmail.com Thu Sep 4 18:15:16 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 4 Sep 2008 17:15:16 -0500 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> Message-ID: <496954360809041515me9bd5cbj39a830fb854340e6@mail.gmail.com> On Thu, Sep 4, 2008 at 5:14 PM, Robert Dailey wrote: > Hi, > > I currently have a dictionary object that I'm doing the following with: > > if lib not in stage_map: > # ... do stuff ... > > However, this will perform a case-sensitive comparison between lib and each > key in stage_map. Is there a way to make this do a case-insensitive > comparison instead? Yes, I realize I could do this: > > if lib not in [key.lower() for key in stage_map] > > However, I don't want to do this because it'll quickly end up getting > messy. I want this solution to be an absolute last resort. I'm not a pro > with python, so I'm hoping there are cleaner alternatives out there. Thanks. > I forgot to mention that I'm using Python 3.0 beta 2. -------------- next part -------------- An HTML attachment was scrubbed... URL: From maric at aristote.info Thu Sep 4 18:38:03 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 00:38:03 +0200 Subject: Case-insensitive string compare? In-Reply-To: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> References: <496954360809041514s65f40d2bn7b42cd2a9886104a@mail.gmail.com> Message-ID: <200809050038.04108.maric@aristote.info> Le Friday 05 September 2008 00:14:37 Robert Dailey, vous avez ?crit?: > Hi, > > I currently have a dictionary object that I'm doing the following with: > > if lib not in stage_map: > # ... do stuff ... > > However, this will perform a case-sensitive comparison between lib and each > key in stage_map. Is there a way to make this do a case-insensitive > comparison instead? Yes, I realize I could do this: > > if lib not in [key.lower() for key in stage_map] > This is the normal python way to compare string without case, and the idiom is not surprising. You''ll often see for loops written like this : for i in (e for e in iterable if predicate(e)) : ... > However, I don't want to do this because it'll quickly end up getting > messy. I want this solution to be an absolute last resort. I'm not a pro > with python, so I'm hoping there are cleaner alternatives out there. If you fell hard to read you can break it on two lines : lowered_keys = (key.lower() for key in stage_map) if lib.lower() not in lowered_keys : .... BTW, it's string manipulation, it's normal it takes more than one brain cycle to achieve. Try the regexp solution and make your choice, more than often, I keep the straightforward, "read as pseudo-code", python expression. -- _____________ Maric Michaud From gagsl-py2 at yahoo.com.ar Tue Sep 9 14:53:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 15:53:03 -0300 Subject: Unable to start a process with subprocess Popen() References: <3657eb2f-c827-4929-be5a-689959de5f85@a1g2000hsb.googlegroups.com> Message-ID: En Mon, 08 Sep 2008 13:35:21 -0300, escribi?: > cmd = subprocess.Popen([batchFilePath], \ > shell = True, \ > stdin = subprocess.PIPE, > stdout = subprocess.PIPE, \ > stderr = subprocess.PIPE \ > ) > cmd.stdin.close() > outPipe, errPipe = PipeThread(cmd.stdout), > PipeThread(cmd.stderr) > outPipe.run(), errPipe.run() > retcode = cmd.wait() > out, err = outPipe.getOutput(), errPipe.getOutput() > > Although, this solved my problem. But I know there is no need for using > threading in this problem. This problem could've been solved just by the > subprocess module. > > I'm unnecessarily using the threading module. Not only that, you're misusing the Thread class. To actually create a separate execution thread, you should call outPipe.start() instead of outPipe.run() (same for errPipe). Note that if your batch file emits a large output it really may be necesary to use a separate thread to read the output. -- Gabriel Genellina From steve at holdenweb.com Tue Sep 30 07:07:18 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Sep 2008 07:07:18 -0400 Subject: What is not objects in Python? In-Reply-To: References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <00f15dd2$0$20617$c3e8da3@news.astraweb.com> Message-ID: Terry Reedy wrote: > Steven D'Aprano wrote: >> On Mon, 29 Sep 2008 05:41:02 -0700, George Sakkis wrote: >> >>> For example I would be much less >>> opposed to len() being defined as, say, |x| if "|...|" was a valid >>> operator. >> >> Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians >> and physicists. > > It should be both, just as + is addition for numbers and concatenation > for sequences. Or we could have just one built-in -- size() instead of > abs() and len(). For non-sequence collections, size() would be better > than len() anyway. > And how are these "non-sequence collections" to be distinguished? And how does size() differ from len() in that case? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From cjw at ncf.ca Sat Sep 6 20:08:20 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 06 Sep 2008 20:08:20 -0400 Subject: Learning Python In-Reply-To: References: Message-ID: James Pilling wrote: > Hi im currently starting to learn python in sixth form at school any tips? > > ____________________________________________________________ > GET FREE 5GB EMAIL - Check out spam free email with many cool features! > Visit http://www.inbox.com/email to find out more! There are suggestions here: http://wiki.python.org/moin/PythonBooks Good luck, Colin W. From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 02:49:18 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Mon, 15 Sep 2008 23:49:18 -0700 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: References: Message-ID: > On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal wrote: >> I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that >> key as string. Is there any way to convert the said instance into string? Take a look at as_pem() method. -- Heikki Toivonen From deets at nospam.web.de Tue Sep 2 15:06:58 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Sep 2008 21:06:58 +0200 Subject: How to write verbose scripts In-Reply-To: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: <6i5h6jFop62lU1@mid.uni-berlin.de> Steven D'Aprano schrieb: > I find myself writing command line tools in Python where I wish to > include "verbose" output to stdout. > > I start with a helper function: > > > def print_(obj, level=0): > if _verbosity >= level: > print obj > > > And then I end up with functions or methods looking like this: > > > def parrot(x) > print_("precondition", level=2) > do_something() > print_("status is good...", level=1) > print_("parrot is squawking strongly now", level=2) > do_something_else() > print_("squawk squawk squawk", level=3) > do_more() > print_("postcondition", level=1) > return something > > > That often means that my functions end up with more message printing code > than actual code. The whole thing seems messy and hard to manage for all > but the smallest scripts. > > Worst of all, sometimes the messages I wish to print may be expensive to > compute, and I don't want to waste time computing them if they aren't > going to be printed because the verbosity is too low. But nor do I wish > to fill my code with this: > > if _verbosity >= 3: > x = calculate_complicated_thing() > print_(x, level=3) > > > > Is there a better way of doing this than the way I am going about it? I use the logging-module. Regarding the expensive computations: maysomething like this help: class DeferredToString(object): def __init__(self, func): self.func = func def __repr__(self): return repr(self.func()) def __str__(self): return str(self.func()) dts = DeferredToString Because then you can do logger.debug("Some text for an: %r", dts(lambda: long_computation())) Because AFAIK the string is only interpolated if the logging level is actually put out. Diez From rmacneill at gmail.com Thu Sep 18 19:10:02 2008 From: rmacneill at gmail.com (rmac) Date: Thu, 18 Sep 2008 16:10:02 -0700 (PDT) Subject: Python newbie question re Strings and integers Message-ID: the following code attempts to extract a symbol name from a string: extensionStart = int(filename.rfind('.')) filenameStart = int(filename.rfind('/')) #print 'Extension Start - ' + str(extensionStart) #print 'FileName Start - ' + str(filenameStart) currentSymbol=filename[int(filenameStart),int(extensionStart)] Uncommenting the print statements clearly show the values to be integers (and without the str casts actually provide int+string errors) However, executing this code results in... opening - /Users/rmac/Documents/Sandbox/data/MarketData/AA.csv Traceback (most recent call last): File "rHistFileToDB_Equities.py", line 25, in currentSymbol=filename[int(filenameStart),int(extensionStart)] TypeError: string indices must be integers Running Python 2.5.2_5 on OSX From tedpottel at gmail.com Mon Sep 8 12:24:17 2008 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Mon, 8 Sep 2008 09:24:17 -0700 (PDT) Subject: Trying to make a spider using mechanize Message-ID: Hi, I can read the home page using the mechanize lib. Is there a way to load in web pages using filename.html instad of servername/ filename.html. Lots of time the links just have the file name. I'm trying to read in the links name and then vsit those pages. here is the sample code I am ussing. import ClientForm import mechanize #get home page request = mechanize.Request("http://www.activetechconsulting.com") response = mechanize.urlopen(request) print response.read() #sub page (this does note work) request = mechanize.Request("service.html") response = mechanize.urlopen(request) print response.read-Ted From sebastianthegreatful at gmail.com Thu Sep 18 03:57:23 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Thu, 18 Sep 2008 00:57:23 -0700 (PDT) Subject: ssl server References: <7ac8d302-0dae-4f19-81a9-8926c6b22a01@26g2000hsk.googlegroups.com> Message-ID: <0ea6046a-dea2-419f-95ce-2b56ae71ca9e@k30g2000hse.googlegroups.com> On Sep 17, 10:53?pm, "Giampaolo Rodola'" wrote: > On 17 Set, 19:33, Seb wrote: > > > > > I'm making a ssl server, but I'm not sure how I can verify the > > clients. What do I actually need to place in _verify to actually > > verify that the client cert is signed by me? > > > ?50 class SSLTCPServer(TCPServer): > > ?51 ? ? ? ? keyFile = "sslcert/server.key" > > ?52 ? ? ? ? certFile = "sslcert/server.crt" > > ?53 ? ? ? ? def __init__(self, server_address, RequestHandlerClass): > > ?54 ? ? ? ? ? ? ? ? ctx = SSL.Context(SSL.SSLv23_METHOD) > > ?55 ? ? ? ? ? ? ? ? ctx.use_privatekey_file(self.keyFile) > > ?56 ? ? ? ? ? ? ? ? ctx.use_certificate_file(self.certFile) > > ?57 ? ? ? ? ? ? ? ? ctx.set_verify(SSL.VERIFY_PEER | > > SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, > > self._verify) > > ?58 ? ? ? ? ? ? ? ? ctx.set_verify_depth(10) > > ?59 ? ? ? ? ? ? ? ? ctx.set_session_id('DFS') > > ?60 > > ?61 ? ? ? ? ? ? ? ? self.server_address = server_address > > ?62 ? ? ? ? ? ? ? ? self.RequestHandlerClass = RequestHandlerClass > > ?63 ? ? ? ? ? ? ? ? self.socket = socket.socket(self.address_family, > > self.socket_type) > > ?64 ? ? ? ? ? ? ? ? self.socket = SSL.Connection(ctx, self.socket) > > ?65 ? ? ? ? ? ? ? ? self.socket.bind(self.server_address) > > ?66 ? ? ? ? ? ? ? ? self.socket.listen(self.request_queue_size) > > ?67 > > ?68 ? ? ? ? def _verify(self, conn, cert, errno, depth, retcode): > > ?69 ? ? ? ? ? ? ? ? return not cert.has_expired() and > > cert.get_issuer().organizationName == 'DFS' > > What library are you using? PyOpenSSL? > In that case I think you'll have more luck by posting on their mailing > list. Thanks, I did that and it worked. From tino at wildenhain.de Wed Sep 10 10:51:13 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 10 Sep 2008 16:51:13 +0200 Subject: Alternatives to traditional RDBMS In-Reply-To: References: Message-ID: <48C7DEE1.8010208@wildenhain.de> James Mills wrote: ... > Are there any others out there ? > Is anyone working on something ? > > I would like to continue my work > on buzhug... I have so: > * Fixed several bugs > * Implemented a WSGI middleware layer > > I'd like to refactor a lot of it's code > and make better use of more recent > features of python as buzhug was > written quite some time ago. I think > it's "protocol" could be vastly improved > as well - as pickling things doesn't > always work so well... > > In addition, I think buzhug could do > with some caching features to speed > database operations up (they're already > pretty fast). Looks as you didn't mention ZODB yet. As it is actively developed, it is maybe something you could consider. Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From dear.jay.logan at gmail.com Mon Sep 1 09:00:00 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 1 Sep 2008 06:00:00 -0700 (PDT) Subject: Python 3.0b2 cannot map '\u12b' References: <6i24u3Fo7morU2@mid.uni-berlin.de> Message-ID: <8c812bc2-5d44-4818-81f0-ffba8fe39042@m73g2000hsh.googlegroups.com> On Sep 1, 8:19?am, Marc 'BlackJack' Rintsch wrote: > On Mon, 01 Sep 2008 02:27:54 -0400, Terry Reedy wrote: > > I doubt the OP 'chose' cp437. ?Why does Python using cp437 even when the > > default encoding is utf-8? > > > On WinXP > > ?>>> sys.getdefaultencoding() > > 'utf-8' > > ?>>> s='\u012b' > > ?>>> s > > Traceback (most recent call last): > > ? ?File "", line 1, in > > ? ?File "C:\Program Files\Python30\lib\io.py", line 1428, in write > > ? ? ?b = encoder.encode(s) > > ? ?File "C:\Program Files\Python30\lib\encodings\cp437.py", line 19, in > > encode > > ? ? ?return codecs.charmap_encode(input,self.errors,encoding_map)[0] > > UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in > > position > > 1: character maps to > > Most likely because Python figured out that the terminal expects cp437. ? > What does `sys.stdout.encoding` say? > > > To put it another way, how can one 'choose' utf-8 for display to screen? > > If the terminal expects cp437 then displaying utf-8 might give some > problems. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch So, it is not a problem with the program, but a problem when I print it out. sys.stdout.encoding does say cp437. Now, when I don't print anything out, the program hangs. I will try this again and let the board know the results. Thanks for all of your insight. From darcy at druid.net Sat Sep 27 19:19:34 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 27 Sep 2008 19:19:34 -0400 Subject: Hello boys! In-Reply-To: References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> Message-ID: <20080927191934.1c3290ea.darcy@druid.net> On Sat, 27 Sep 2008 18:47:16 -0400 default wrote: > On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko > wrote: > > >Hello, this is Milenko Stojadinovic from town Banjaluka, > > Come to the US and park your mouth in front of George Bush - all the > Bshit you can eat - and it keeps on coming! What's the point of killfiling Google Groups if people like you are just going to respew this crap. Please consider the Delete key next time. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From wegwerp at gmail.com Fri Sep 26 15:54:11 2008 From: wegwerp at gmail.com (Bas) Date: Fri, 26 Sep 2008 12:54:11 -0700 (PDT) Subject: Matplotlib Polar Plot Angles/Axes References: <4353020c-ff7b-470c-9aae-8f756502e695@d1g2000hsg.googlegroups.com> Message-ID: I only have experience with the matlab version of polar, but my wild guess is that you have convert your degrees to radians. Go to the Matplotlib newsgroup if you need any better help. HTH, Bas From steven at REMOVE.THIS.cybersource.com.au Fri Sep 26 04:25:44 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 08:25:44 GMT Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> <48dc962a$0$2289$426a74cc@news.free.fr> Message-ID: On Fri, 26 Sep 2008 09:58:39 +0200, Bruno Desthuilliers wrote: >> "Procedural" is the opposite of "functional", not "object-oriented". > > AFAIK, the "opposite" if functional is imperative, not procedural. But > let's not waste too much time on terminology arguments... We're not wasting time on terminology arguments, we're wasting time on definitional debates. -- Steven From ggpolo at gmail.com Wed Sep 17 14:20:06 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 17 Sep 2008 15:20:06 -0300 Subject: Tkinter Label 'justify' Problem In-Reply-To: <8c8a2d86-007b-4e38-b0fc-bc6385b3a77a@t54g2000hsg.googlegroups.com> References: <8c8a2d86-007b-4e38-b0fc-bc6385b3a77a@t54g2000hsg.googlegroups.com> Message-ID: On Wed, Sep 17, 2008 at 2:18 PM, Dude wrote: > Hi All, > I am fairly new to Python programming. I am working on a small > Tkinter project and I think I am missing something, maybe you can > help. The two lines below is all I have related to the Label widget: > > lblServer = Tkinter.Label(serverFrame, text='Server:', fg='black', > justify='left', relief='groove') > > lblServer.place_configure(width=200, bordermode='inside') > > > No matter what I change the 'justify' to whether it's 'lef', 'right', > or 'center', it always seems to be in the center. The "justify" option comes into play only when you have a multi-line label, which is not the case. If you want it left/right aligned then use pack (instead of place, not really recommended but I don't know what you are doing) and specify the anchor option with an appropriate value ('e' or 'w') for what you want. > > I am also writing the keys from the Label widget to a file because > this has me so baffled. That is below. > > Thank in advance for any help or direction you can give me. > > Steve P > > ---------- lblServer keys ----------------- > activebackground : SystemButtonFace > activeforeground : SystemButtonText > anchor : center > background : SystemButtonFace > bd : 2 > bg : SystemButtonFace > bitmap : > borderwidth : 2 > compound : none > cursor : > disabledforeground : SystemDisabledText > fg : black > font : {MS Sans Serif} 8 > foreground : black > height : 0 > highlightbackground : SystemButtonFace > highlightcolor : SystemWindowFrame > highlightthickness : 0 > image : > justify : left > padx : 1 > pady : 1 > relief : groove > state : normal > takefocus : 0 > text : NNTP Server: > textvariable : > underline : -1 > width : 0 > wraplength : 0 > ---------- lblServer keys END ------------- > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From castironpi at gmail.com Mon Sep 22 21:28:37 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 18:28:37 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: On Sep 22, 8:13?pm, process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. I didn't think this through completely-- is it incompatible with closures and local function definitions? def f( m ): def g( n ): return m+ n stuff( ) return g( 0 ) In this case, the stack, growing up: g f main is not equivalent to: g main in the last step, due to the local definition of 'm' in 'f'. From bearophileHUGS at lycos.com Mon Sep 22 22:10:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 19:10:35 -0700 (PDT) Subject: dict generator question References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> <00e45101$0$20331$c3e8da3@news.astraweb.com> <773db59e-40c6-470e-b616-ca8715efa46a@d77g2000hsb.googlegroups.com> <00e82140$0$20303$c3e8da3@news.astraweb.com> Message-ID: <80294675-b318-4b8d-b963-5a1b8fb225f1@k30g2000hse.googlegroups.com> Steven D'Aprano: >I'm sorry, I don't recognise leniter(). Did I miss something?< I have removed the docstring/doctests: def leniter(iterator): if hasattr(iterator, "__len__"): return len(iterator) nelements = 0 for _ in iterator: nelements += 1 return nelements >it doesn't work for arbitrary iterables, only sequences (lazy or otherwise)< I don't understand well. >Since you're generating the entire length anyway, len(list(iterable)) is more readable and almost as efficient for most practical cases.< I don't agree, len(list()) creates an actual list, with lot of GC activity. >But the expected semantics of __len__ is that it is expected to return an int, and do it quickly with minimal effort. Methods that do something else are an abuse of __len__ and should be treated as a bug.< I see. In the past I have read similar positions in discussions regarding API of data structures in D, so this may be right, and this fault may be enough to kill my proposal. But I'll keep using leniter(). Bye, bearophile From tjreedy at udel.edu Mon Sep 29 14:25:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 14:25:43 -0400 Subject: What is not objects in Python? In-Reply-To: <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> Message-ID: George Sakkis wrote: > Sure, "len" looks better than lambda x:x.__len__(), but the same would > be true if there was an "upper" builtin for the following example: > >>>> s = ['a', 'd', 'B', 'C'] >>>> s2 = [u'a', u'd', u'B', u'C'] >>>> upper = lambda x: x.upper() >>>> sorted(s, key=upper) > ['a', 'B', 'C', 'd'] >>>> sorted(s2, key=upper) > [u'a', u'B', u'C', u'd'] > > No difference in principle, just len() happens to be implemented more > often than upper(). I disagree. One versus many classes is a principle. If a method is used on objects of just one class, the class attribute can be used and passed directly. sorted(s, key = str.upper) sorted(s2, key = unicode.upper) The problem is having two text classes, which Guido considers to be a mess and which Python did not have originally and which 3.0 also does not have, even though bytes keeps the string methods. Mixing int, long, and float numbers is or should be more common than mixing str and unicode strings, and certainly more common than mixing str strings and bytes in 3.0 (which is actively discouraged). To me, discerning the implicit principles of Python's design makes it easier to learn and remember, even if they are not as exact as one might like. The choices are not random, and so one can do better than rote memory. Terry Jan Reedy From xlebourd at gmail.com Wed Sep 3 05:44:19 2008 From: xlebourd at gmail.com (Xavier) Date: Wed, 3 Sep 2008 02:44:19 -0700 (PDT) Subject: Serial I/O problem with pywin32 ? Message-ID: Hi, I try to access to a Bluetooth GPS data-logger with Python. I use pySerial. Sending and receiving little messages (~100 char) works fine. However, when I ask the GPS to dump the trails, it returns some Mbytes and here is the problem : in the stream of bytes, I randomly losts chunks of ~100bytes. I tried USPP and pyBlueZ instead of pySerial : same problem. It doesn't like it is a bufferoverun bug from me because : - the GPS seems to wait when I do not read the stream, - there is never more than 200 inWainting() characters, - my code to test it is quite simple : seriallink = serial.Serial("COM40") fileName = "data.dump" out = open(fileName, 'w') while 1: c = seriallink.read() out.write(" %0.2X" % ord(c)) print "*", out.close() (with pyBluez : sock=BluetoothSocket( RFCOMM ) sock.connect(("00:0A:...", 1))) I tried my program on two different PC with two Bluetooth dongle, (with pySerial, USPP, pyBluez). The same things are : - windows - the GPS (which works fine with the dumper program of the constructor) - pyWin32 I've found another guy with a similar problem : http://www.generation-nt.com/reponses/rs232-entraide-142097.html He says: - no problem with little messages - lost of one byte every hour when receiving a lot of data Any known problems with pywin32 and serial I/O when downloading a big stream of data ? From roy at panix.com Sat Sep 27 10:20:50 2008 From: roy at panix.com (Roy Smith) Date: Sat, 27 Sep 2008 10:20:50 -0400 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> Message-ID: In article , aahz at pythoncraft.com (Aahz) wrote: > One cute reason to prefer class singletons to module singletons is that > subclassing works well for creating multiple singletons. But really, > the main reason I use class singletons is that they are the absolute > simplest way to get attribute access: > > class Foo: pass > Foo.bar = 'xyz' > if data == Foo.bar: > print "!" I've often done something similar, creating a dummy class: class Data: pass just so I could create instances of it to hang attributes off of: foo = Data() foo.bar = 'xyz' That's a trick I've been using since the Old Days (i.e. before new-style classes came along). When I saw your example, my first thought was "That's silly, now that there's new-style classes, you can just create an instance of object!". Unfortunately, when I tried it, I discovered it didn't work. You *can* instantiate object, but you don't get a class instance, so you can't create attributes on it. >>> x = object() >>> type(x) >>> x.foo = 1 Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'foo' From gagsl-py2 at yahoo.com.ar Tue Sep 16 05:38:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 16 Sep 2008 06:38:33 -0300 Subject: Is 'x' an instance of a new-style class? References: Message-ID: En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS escribi?: > I've seen the question raised several times here, but apparently never > answered. Since PyInstance_Check returns False for new-style class > instances, is there a standard procedure for testing this using the C- > Api? > > I would greatly appreciate some help with this. In Python you would write isinstance(x, object). In C, "object" is PyBaseObject_Type, and a direct translation would be PyObject_IsInstance(x, PyBaseObject_Type), or perhaps PyObject_TypeCheck(x, &PyBaseObject_Type) (to mimic how other PyXXX_Check are implemented, and probably faster) -- Gabriel Genellina From durand1 at gmail.com Fri Sep 5 15:24:08 2008 From: durand1 at gmail.com (Durand) Date: Fri, 5 Sep 2008 12:24:08 -0700 (PDT) Subject: [PIL] quake like multicoloured text Message-ID: <3d829a04-9005-4216-86dc-b1055edab4e7@f63g2000hsf.googlegroups.com> I'm wondering how I could render text with PIL in which different parts of the text are different characters. This is for a game stats script where names are written like: ^1Red ^2Green ^3Yellow, etc. The problem is that I currently use text in the ImageDraw module but the only way I can think of rendering text is by rendering each bit of text in a separate colour. Example: draw.text((0,0),"Red", fill="red") draw.text((30,0),"Green", fill="green") draw.text((60,0),"Yellow", fill="green") except that I'm not sure how much spacing there is between each coloured bit of text(30px is assumed in the example)...Would there be an alternate method of doing this? Thanks =) From stef.mientki at gmail.com Thu Sep 25 07:49:06 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 13:49:06 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <6k1937F5i8kjU1@mid.uni-berlin.de> References: <6k1937F5i8kjU1@mid.uni-berlin.de> Message-ID: <48DB7AB2.6020309@gmail.com> Diez B. Roggisch wrote: > Stef Mientki wrote: > > >> hello, >> >> How can I find the correct case of a filename ? >> >> Background in my program I use case sensitive filenames, just like >> Python requires. >> Now I've integrated pdb into the program, >> but pdb acts somwhat strange: >> upon a breakpoint it gives the filename always in lowercase (probably >> this only happens on windows). >> >> So is there a way to get the correct case of a given filename in lowercase >> ? >> >> One solution might be to make the comparison in my program always with >> lowercase, >> but then I'm sure the program won't work on non-windows systems. >> >> btw, why does pdb behave that way ( Python 2.5 ) ? >> > > I doubt it does. It sure doesn't on unix, and I fail to see any reason why > it should do that on windows - given that the total number of lower() in > pdb.py amounts to one, and that's used to process user-input such > as "Yes", "y", "YES" or whatnot. > > Yes I'm pretty sure, two reasons: 1. when I perform a step_into, jumping into a file that doesn't have breakpoints itself (meaning my program doesn't even know of this file), pdb returns a lowercase filename 2. rpdb2 (probably based or even inherited from pdb) has the same behavior. Asking the writer of rpdb2, I got some excuse (which I didn't understand) why he had done it that way. > Are you sure you are not processing the content through some lower()-call > when embedding pdb? > > But maybe pdb does ? thanks anyway, Stef > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From ben at benfinney.id.au Fri Sep 26 01:08:33 2008 From: ben at benfinney.id.au (Ben Finney) Date: Fri, 26 Sep 2008 15:08:33 +1000 Subject: Writing a well-behaved daemon Message-ID: <874p43wl2m.fsf@benfinney.id.au> Howdy all, Writing a Python program to become a Unix daemon is relatively well-documented: there's a recipe for detaching the process and running in its own process group. However, there's much more to a Unix daemon than simply detaching. At a minimum, a well-behaved Unix daemon must at least: * Detach the process into its own process group * Close stdin, redirect stdout and stderr to a null device * Handle its own PID file: refuse to start if the PID file already exists, write the PID file on startup otherwise, and remove the PID file on termination * Revoke setuid and setgid privileges, which are strongly deprecated these days * Handle interrupts, cleaning up the process and PID file as necessary * (possible others) There are also many other commonly-expected tasks that well-behaved Unix daemons perform (drop privileges to a nominated non-root user and group after daemonising, redirect output to syslog instead, operate in a chroot jail, respawn when terminated, etc.). All of this stuff has been done numerous times before, and the basics are mostly agreed upon. Yet all of these are tricky to implement correctly, and tedious to re-implement in every program intended to run as a daemon. The 'daemon' program covers all these, and allows an arbitrary process to be started as a well-behaved Unix daemon process. It's not a good assumption that this program is installed on an arbitrary system though, and it seems excessive to ask the recipient of one's program to get a third-party program just in order to make a daemon process. I'd love to be able to have something similar for Python programs, e.g. a 'become_well_behaved_daemon()' function that implements all the above and perhaps takes optional arguments for the optional features. My searches for such functionality haven't borne much fruit though. Apart from scattered recipes, none of which cover all the essentials (let alone the optional features) of 'daemon', I can't find anything that could be relied upon. This is surprising, since I'd expect this in Python's standard library. Can anyone point me to the equivalent of the 'daemon' program in the form of a well-tested Python library? -- \ ?Tis more blessed to give than to receive; for example, wedding | `\ presents.? ?Henry L. Mencken | _o__) | Ben Finney From lucafbb at gmail.com Mon Sep 1 08:42:26 2008 From: lucafbb at gmail.com (Luca) Date: Mon, 1 Sep 2008 14:42:26 +0200 Subject: Know if a object member is a method In-Reply-To: <00cbd80b$0$20302$c3e8da3@news.astraweb.com> References: <27308d500809010143kbd945b1h8d0f042f1395c3d6@mail.gmail.com> <00cbd80b$0$20302$c3e8da3@news.astraweb.com> Message-ID: <27308d500809010542n766bd9fmfdd9775ad3fdabf7@mail.gmail.com> On Mon, Sep 1, 2008 at 2:18 PM, Steven D'Aprano wrote: > > If your aim is to write something like a debugger, profiler, or some > other application that needs to inspect arbitrary objects and work out > what they do, then you probably should be using: > > isinstance(obj.methodName, new.instancemethod) > > But remember that not all callable attributes are instancemethods! > > There is no one right way of doing this. > > Hope this helps. Yes, this helps a lot. In facts I need to do something like a language parser. Thanks all. -- -- luca From ranim81 at gmail.com Mon Sep 1 08:32:15 2008 From: ranim81 at gmail.com (raju) Date: Mon, 1 Sep 2008 05:32:15 -0700 (PDT) Subject: click heremore dollar Message-ID: http://www.moneymaking4.blogspot.com/ From fredrik at pythonware.com Wed Sep 10 10:25:38 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 16:25:38 +0200 Subject: Web shopping carts In-Reply-To: References: <48C7CE5A.7030904@wildenhain.de> Message-ID: Luke Hamilton wrote: > And unfortunately Google hasn't been much help... "You've got to be very careful if you don't know where you're going, because you might not get there." From goon12 at gmail.com Tue Sep 2 13:07:33 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 2 Sep 2008 13:07:33 -0400 Subject: How to write verbose scripts In-Reply-To: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> Message-ID: <6a2ccd190809021007w6783ff34t8eece381ea958d2f@mail.gmail.com> On Tue, Sep 2, 2008 at 12:55 PM, Steven D'Aprano wrote: > Is there a better way of doing this than the way I am going about it? Would the logging module help, and just print the output to the stdout (or a file) instead? From duncan.booth at invalid.invalid Sat Sep 20 09:13:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Sep 2008 13:13:08 GMT Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: candide wrote: > Excerpt quoted from http://www.astro.ufl.edu/~warner/prog/python.html : > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > > Thanks for any comment. General comments about the page: Section 2: Poor demonstration of 'global'. The declaration of 'a' as global is unnecessary and misleading. Section 4: "Maths: Requires import math" The supplied examples won't work if you just "import math", they need a "from math import ..." (either * or better an explicit list of functions). Worse, the random number examples won't work whatever you import as they include both 'random.seed()' which assumes 'random' is the module and 'x = random()' which requires 'from random import random'. Section 5: "Strings do not expand escape sequences unless it is defined as a raw string by placing an r before the first quote" What is that supposed to mean? Describing triple quoted strings as 'optional syntax' is a bit weird too: the syntax is no more optional than any other form of string literal, you can use it or not. Another pointless example given under the heading 'String Operators': Concatenation is done with the + operator. Converting to numbers is done with the casting operations: x = 1 + float(10.5) "String functions" actually mostly describes string methods with "len" hidden in the middle but only the example tells you that it is different than the other examples. Section 6 is all about numarray but bizarrely (for something purporting to be an overview of Python) there is nothing at all about either list or dict types. Section 7 says "There is no switch or case statement so multiple elifs must be used instead." omitting to mention other possibly more appropriate options such as dicts or inheritance. This is a good indication that the author doesn't know much about OOP. Section 8 "for x in array: statements" shows that the author doesn't understand things like iterators. Section 10 has such interesting facts as "Only constant initializers for class variables are allowed (n = 1)" or "Objects can be compared using the == and != operators. Two objects are equal only if they are the same instance of the same object." and an example with a completely spurious class attributes, some pointless getter/setter methods, and contorted calls to base class methods. Section 11 demonstrates again that the author doesn't understand about iterable objects. I'd say the claim that Python isn't a full OOP language is not the most important reason to ignore the page. From kyrie at uh.cu Wed Sep 3 23:40:44 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 03 Sep 2008 23:40:44 -0400 Subject: max(), sum(), next() In-Reply-To: <48BEE2F7.5010106@shopzeus.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <48BEE2F7.5010106@shopzeus.com> Message-ID: <1220499644.48bf58bc376e4@comuh.uh.cu> Quoting Laszlo Nagy : > bearophileHUGS at lycos.com wrote: > > Empty Python lists [] don't know the type of the items it will > > contain, so this sounds strange: > > > > > >>>> sum([]) > >>>> > > 0 > > > > Because that [] may be an empty sequence of someobject: > > > > You are right in that sum could be used to sum arbitrary objects. > However, in 99.99% of the cases, you will be summing numerical values. > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > is very logical to return zero for empty sequences. Even better: help(sum) shows === sum(...) sum(sequence, start=0) -> value Returns the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start'. When the sequence is empty, returns start. === so the fact that sum([]) returns zero is just because the start value is zero... sum([],object()) would return an object(). BTW, the original code: >>> sum(s for s in ["a", "b"] if len(s) > 2) wouldn't work anyway... it seems that sum doesn't like to sum strings: >>> sum(['a','b'],'') : sum() can't sum strings [use ''.join(seq) instead] Cheers, -- Luis Zarrabeitia Facultad de Matem?tica y Computaci?n, UH http://profesores.matcom.uh.cu/~kyrie From deets at nospam.web.de Tue Sep 2 16:29:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 Sep 2008 22:29:33 +0200 Subject: synthetic properties In-Reply-To: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> References: <1ceb2f61-31f0-4c8d-995a-e5469fed2cbc@l64g2000hse.googlegroups.com> Message-ID: <6i5m1eFolktmU1@mid.uni-berlin.de> rowland at river2sea.org schrieb: > I'm trying to come up with solution for adding synthetic properties to > python, similar to synthetic properties in Objective-C. > > I'm playing around with doing this in a MetaClass. I can dynamically > create the attributes that will back the property, but I'm having > trouble figuring out how to dynamically generate get/set methods to > pass to the built-in property() function. Why on earth do you want to do that? The reason synthesized properties exist in ObjC is simply that to expose properties for key-value-coding, one needs the getter/setters. But mostly these are boilerplate, so apple introduced the @synthesized-annotation. But in python, you don't need that. You use simple attributes. In the very moment you need logic attached, use the builtin property to do so. Diez From nick at craig-wood.com Thu Sep 25 16:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 25 Sep 2008 15:30:03 -0500 Subject: Eggs, VirtualEnv, and Apt - best practices? References: Message-ID: Scott Sharkey wrote: B> Our development group at work seems to be heading towards adopting > python as one of our standard "systems languages" for internal > application development (yeah!). One of the issues that's come up is > the problem with apt (deb packages) vs eggs, vs virtual environments. > We're probably gonna end up using Pylons or TurboGears for web-based > apps, and I've recommended virtualenv, but one of the other developers > has had some "inconsistencies" when mixing systems with python installed > from apt (all our servers are debian or ubuntu based) vs when installed > under virtualenv. > > I have basically recommended that we only install the python base (core > language) from apt, and that everything else should be installed into > virtual environments. But I wanted to check to see how other enterprises > are handling this issue? Are you building python from scratch, or using > specific sets of .deb packages, or some other process. > > Any insight into the best way to have a consistent, repeatable, > controllable development and production environment would be much > appreciated. I'll admit to not knowing what you mean by virtual environment... In our debian systems we use python from apt and all modules from apt. If there is a module we can't find then we build it into a .deb using setup.py to build an rpm and converting to a .deb. The app is then tested with "etch" or whatever. If easy_install could build debs that would be really helpful! > Suggestions on build/rollout tools (like zc.buildout, Paver, etc) would > also be appreciated. Use setup.py to build into .debs is what we do. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From stef.mientki at gmail.com Thu Sep 25 10:43:53 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 25 Sep 2008 16:43:53 +0200 Subject: How to get the filename in the right case ? In-Reply-To: <6k1dukF5hk86U1@mid.uni-berlin.de> References: <6k1937F5i8kjU1@mid.uni-berlin.de> <6k1dukF5hk86U1@mid.uni-berlin.de> Message-ID: <48DBA3A9.4060707@gmail.com> Diez B. Roggisch wrote: >> Yes I'm pretty sure, two reasons: >> 1. when I perform a step_into, jumping into a file that doesn't have >> breakpoints itself (meaning my program doesn't even know of this file), >> pdb returns a lowercase filename >> > > What has that to do with potential output postprocessing? > > > > >> 2. rpdb2 (probably based or even inherited from pdb) has the same >> behavior. Asking the writer of rpdb2, I got some excuse (which I didn't >> understand) why he had done it that way. >> > > rpdb2 is not pdb. > > Below is the output of a Pdb-session I just had: > > > (eggbasket)dir at client8049:~/software/vc/EggBasket$ nosetests -s > eggbasket.tests.test_model > 2008-09-25 14:13:10,374 turbogears.identity.saprovider INFO Loading: > eggbasket.model.VisitIdentity > .> /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(59)test_versionsets() > -> vi1 = vset.add_pkg_info(p1) > (Pdb) n > >> /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(60)test_versionsets() >> > -> session.flush() > (Pdb) n > > > As you can see - mixed-case filenames. Linux though. > > There is a *very* simple way for you to check: just create a file called > > FooBar.py > > and inside that, put > > import pdb; pdb.set_trace() > print "hello" > > > Run that on the windows shell. See if that puts out all lowercase or not. I > can't do that right now as my VBox Windows won't start. > >>> import Module1 > d:\data_python_25\pylab_works\module1.py(3)() -> print "hello" (Pdb) > Then we know if PDB is really the culprit. > > So pdb is the problem. > Apart from that, is that really a problem that the filenames are all lower > case? AFAIK Windows is case-insensitive regarding filenames anyway. So > opening the file by just passing the filename should work seamless. > Yes windows is, but Python is not. My program should run on Windows and Linux (and maybe a few others). By converting everything to lowercase, on Linux I can't distinguishes between 2 files with the same name but a different case (btw, giving 2 files the same name, only differing in case, looks like a bad idea to me). And yes I could switch to lowercase in case I'm on a windows machine, but my program is too beautiful to pollute the code with these kind of unnecessary statements ;-) cheers, Stef > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From mensanator at aol.com Sun Sep 7 13:30:09 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 7 Sep 2008 10:30:09 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> Message-ID: <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> On Sep 6, 11:05?pm, Steven D'Aprano wrote: > On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote: > > [...] > > >> They could have decided that sum must take at least two arguments, > >> because addition requires two arguments and it's meaningless to talk > >> about adding a single number without talking about adding it to > >> something else. But they didn't. > > > Ok. But the problem is they DID in SQL: x + Null = Null. > > Sheesh. That's not a problem, because Python is not trying to be a > dialect of SQL. And yet, they added a Sqlite3 module. > > If you want a NULL object, then there are recipes on the web that will > give you one. Then all you need to do is call sum(alist or [NULL]) and it > will give you the behaviour you want. Actualy, I already get the behaviour I want. sum([1,None]) throws an exception. I don't see why sum([]) doesn't throw an exception also (I understand that behaviour is by design, I'm merely pointing out that the design doesn't cover every situation). > > [...] > > > Here's a real world example (no ivory tower stuff): > > > An oil refinery client has just excavated a big pile of dirt to lay a > > new pipeline. > [snip details] > > Can't I just use a sum of 0 to tell me when data is missing? No, because > > in some cases the reporting limit of undetected compounds is set to 0. > > You can't use a sum of 0 to indicate when data is missing, full stop. Exactly. That's why I would prefer sum([]) to raise an exception instead of giving a false positive. > The > data may require 15 tests when only 3 have actually been done: > > sum([1.2e-7, 9.34e-6, 2.06e-8]) Biggest problem here is that it is often unknown just how many records you're supposed to get from the query, so we can't tell that a count of 3 is supposed to be 15. > > Missing data and a non-zero sum. How should sum() deal with that? That's a seperate issue and I'm not saying it should as long as the list contains actual numbers to sum. sum([1.2e-7, 9.34e-6, 2.06e-8, None]) will raise an exception, as it should. But what types are contained in []? > > The answer is that sum() can't deal with that. You can't expect sum() to > read your mind, know that there should be 15 items instead of 3, and > raise an error. So why do you expect sum() to read your mind and > magically know that zero items is an error, especially when for many > applications it is NOT an error? For the simple reason it doesn't have to read your mind, a mechanism has already been built into the function: start value. For those situations where an empty list is desired to sum to 0, you could use sum(alist,0) and use sum(alist) for those cases where summing an empty list is meaningless. Shouldn't you have to explicitly tell sum() how deal with situations like empty lists rather than have it implicitly assume a starting value of 0 when you didn't ask for it? > > The behaviour you want for this specific application is unwanted, > unnecessary and even undesirable for many other applications. The > solution is for *you* to write application-specific code to do what your > application needs, instead of relying on a general purpose function > magically knowing what you want. Does division magically know what you want? No, it raises an exception when you do something like divide by 0. Isn't it Pythonic to not write a litany of tests to cover every possible case, but instead use try:except? But try:except only works if the errors are recognized. And sum() says that summing an empty list is NEVER an error under ANY circumstance. That may be true in MOST cases, but it certainly isn't true in ALL cases. > > -- > Steven From spammaster.10.webmaster at spamgourmet.com Sun Sep 14 07:28:01 2008 From: spammaster.10.webmaster at spamgourmet.com (spammaster.10.webmaster at spamgourmet.com) Date: Sun, 14 Sep 2008 04:28:01 -0700 (PDT) Subject: PyMarshal Commands crash on Windows Message-ID: <55e203cb-8a7d-4270-863b-fec158e5444e@y21g2000hsf.googlegroups.com> Hi! Can anyone help me with this issue? int main (int argc, char * const argv[]) { Py_Initialize(); FILE* fp = fopen("/Users/test/Desktop/123.pyc","wb"); PyCodeObject* op = (PyCodeObject*)Py_CompileString("import sys \nprint 'hello'","",Py_file_input); PyMarshal_WriteObjectToFile((PyObject *)op, fp, Py_MARSHAL_VERSION); Py_Finalize(); return 0; } This Code crashs on Windows, and I can't explain why. I want to convert a PyCodeObject to a PyObject and save it to the harddisk. PyMarshal_ReadObjectFromFile(FILE *P) crashs too if I want to read a byte-compiled object. Thank your for your help. donnerChecker From fernandena at gmail.com Tue Sep 9 07:06:35 2008 From: fernandena at gmail.com (fernandena at gmail.com) Date: Tue, 9 Sep 2008 04:06:35 -0700 (PDT) Subject: =?KOI8-R?B?18nExc8g4tLJ1M7JIMkg68XXyc7BLg==?= Message-ID: ??????, ??? ??? ????? ????, ??? ??????! http://ragdai.info/golaya-pravda.htm ??? ????? ?????! From clp at rebertia.com Mon Sep 15 16:47:53 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 15 Sep 2008 13:47:53 -0700 Subject: append on lists In-Reply-To: References: Message-ID: <47c890dc0809151347t5646d078jdf06dbc6cd7e3eed@mail.gmail.com> On Mon, Sep 15, 2008 at 1:45 PM, Armin wrote: > Chris Rebert wrote: >> >> On Mon, Sep 15, 2008 at 1:24 PM, Armin wrote: >>> >>> Hi, >>> >>> just a dumb question. >>> >>> Let a = [1,2,3,4,5] >>> >>> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? >> >> I'll assume the presence of the 6 is a typo. > > Sorry, that's the case. > >> >> Because .append() mutates 'a' and appends the item in-place rather >> than creating and returning a new list with the item appended, and >> it's good Python style for mutating methods to have no return value >> (since all functions must have some return value, Python uses None >> when the function doesn't explicitly return anything). > > Yes, but this is very unconvenient. > If d should reference the list a extended with a single list element > you need at least two lines > > a.append(7) > d=a > > and not more intuitive d = a.append(7) And then they'd both reference the same list and you'd run into all sorts of problems. The code you'd actually want is: d = a[:] #copy a d.append(7) Or if you're willing to overlook the inefficiency: d = a + [7] But that's not idiomatic. And debating the fundamentals of the language, which aren't going to change anytime soon, isn't going to get you anywhere. You may be interested in looking at Python's "tuple" datatype, which is basically an immutable list. I'd also suggest you Read The Fine Tutorial, and that your original question was better suited to IRC or python-tutors (http://mail.python.org/mailman/listinfo/tutor) than this mailinglist. Regards, Chris > > --Armin > > >> >> If you print 'a' after doing the .append(), you'll see it's changed to >> your desired value. > > >> >> Regards, >> Chris >> >>> --Armin >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From gnewsg at gmail.com Thu Sep 4 07:57:47 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 4 Sep 2008 04:57:47 -0700 (PDT) Subject: Safely move an element into a heap References: Message-ID: <778c30a9-f097-4789-b1d6-3b40a9f11bdf@p31g2000prf.googlegroups.com> On 4 Set, 13:49, Alexandru Palade wrote: > I'm not sure what you expect as an answer, but if you mean the heap as > in the data structure, you can not just arbitrarily move one key where > you want as it will destroy the heap property. > > > > Giampaolo Rodola' wrote: > > Hi, > > I wanted to know if does exist a safe way to, given a heap, move an > > arbitrary element to the first position of the heap. > > Something like: > > > ?>>> heap = [0,3,6,8,10] > > ?>>> heapq.move_to_first_position(heap, 4) > > ?>>> heap = [10, 0,3,6,8] > > > --- Giampaolo > >http://code.google.com/p/pyftpdlib/ > > -- > >http://mail.python.org/mailman/listinfo/python-list- Nascondi testo citato > > - Mostra testo citato - Could I be able to do that if every element I want to move will have the value of 0 which is the smallest value I can have into my heap? What I'm trying to do is implementing a timeout: sometimes I want a given event which was scheduled to happen within X seconds to happen immediately. --- Giampaolo http://code.google.com/p/pyftpdlib/ From homeshop18.grouping at gmail.com Fri Sep 26 07:09:33 2008 From: homeshop18.grouping at gmail.com (Online Shopping) Date: Fri, 26 Sep 2008 04:09:33 -0700 (PDT) Subject: Laptops- Read Features of branded Laptops Message-ID: Notebook computers - buy latest and best low price laptops from online computer shop in India, homeshop18.com offers low price laptops from online laptops shop. To know more visit: http://www.homeshop18.com/shop/u/y/c-Computers-Q-and-Q-Peripherals-S-Laptops/Home_Online-clI_2-cI_920-pCI_909- From ptmcg at austin.rr.com Wed Sep 3 01:43:26 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 2 Sep 2008 22:43:26 -0700 (PDT) Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: <59dabe63-7393-406f-9588-ba1afcc81b6f@26g2000hsk.googlegroups.com> On Sep 2, 12:36?pm, hofer wrote: > Hi, > > Something I have to do very often is filtering / transforming line > based file contents and storing the result in an array or a > dictionary. > > Very often the functionallity exists already in form of a shell script > with sed / awk / grep , . . . > and I would like to have the same implementation in my script > All that sed'ing, grep'ing and awk'ing, you might want to take a look at pyparsing. Here is a pyparsing take on your posted problem: from pyparsing import LineEnd, Word, nums, LineStart, OneOrMore, restOfLine test = """ 1 2 3 47 23 // this will never match # blank lines are not of any interest 91 26 23 19 41 1 97 26 // extra numbers don't matter """ # define pyparsing expressions to match a line of integers EOL = LineEnd() integer = Word(nums) # by default, pyparsing will implicitly skip over whitespace and # newlines, so EOL is skipped over by default - this would mix together # integers on consecutive lines - we only want OneOrMore integers as long # as they are on the same line, that is, integers with no intervening # EOL's line_of_integers = (LineStart() + integer + OneOrMore(~EOL + integer)) # use a parse action to identify the target lines def select_significant_values(t): v1, v2 = map(int, t[:2]) if v1+v2 == 42: print v2 line_of_integers.setParseAction(select_significant_values) # skip over comments, wherever they are line_of_integers.ignore( '//' + restOfLine ) line_of_integers.ignore( '#' + restOfLine ) # use the line_of_integers expression to search through the test text # the parse action will print the matching values line_of_integers.searchString(test) -- Paul From ppearson at nowhere.invalid Tue Sep 2 14:54:19 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 2 Sep 2008 18:54:19 GMT Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <6i56cpFor2puU1@mid.individual.net> <6Aevk.331$1a2.14@trnddc04> Message-ID: <6i5gerFospk9U1@mid.individual.net> On Tue, 02 Sep 2008 17:18:58 GMT, Alan G Isaac wrote: >> On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote: >>> At the risk of bike-shedding, >> [snip] > > Peter Pearson wrote: >> (startled noises) It is a delight to find a reference to >> that half-century-old essay (High Finance) by the wonderful >> C. Northcote Parkinson, but how many readers will catch the >> allusion? > > It is pretty common geek speek: > http://en.wikipedia.org/wiki/Color_of_the_bikeshed Ah, the wondrous Wiki. I thought I was a geek, for the past 40 years; but maybe its time for me to be demoted to the dad on whose bookshelf you'll find that old book. -- To email me, substitute nowhere->spamcop, invalid->net. From bdesth.quelquechose at free.quelquepart.fr Mon Sep 8 03:32:01 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 08 Sep 2008 09:32:01 +0200 Subject: Test if list contains another list In-Reply-To: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> Message-ID: <48c4f0e0$0$11223$426a34cc@news.free.fr> mathieu a ?crit : > Hi there, > > I am trying to write something very simple to test if a list > contains another one: > > a = [1,2,3] > > b = [3,2,1,4] > > but 'a in b' returns False. Indeed. Lists are not sets, and the fact that all elements of list a happens to also be part of list b doesn't make the list a itself an element of list b. >>> a = [1, 2, 3] >>> b = [3,2,1,4] >>> c = [b, a] >>> a in c True >>> b in c True >>> c [[3, 2, 1, 4], [1, 2, 3]] >>> > How do I check that a is indeed contained > in b ? But that's what you did - you *did* checked if a was contained in b, and this is not the case. What you want is to check if *all elements* of a are contained in b, which is quite another problem. Now the answer to your question : use sets. >>> set(a).issubset(set(b)) True >>> HTH From akineko at gmail.com Wed Sep 17 23:45:30 2008 From: akineko at gmail.com (akineko) Date: Wed, 17 Sep 2008 20:45:30 -0700 (PDT) Subject: A unique instance of Python GUI program References: <54432e6f-c253-48c1-8cd3-f4161c8c9f81@a18g2000pra.googlegroups.com> <56a64a1c-cf86-40df-a0b6-170dde9d0738@w24g2000prd.googlegroups.com> Message-ID: <0643c0e0-a9c0-4a46-8cb8-7c37a9ebcc07@w39g2000prb.googlegroups.com> Again, thank you for many postings to my question. I have reviewed solutions provided. Well, I like the named Mutex solution under Windows. That is a clean and straight-forward approach to the challenge. (I cannot believe that I'm saying good thing about Windows ;-) ) Unfortunately, I'm living in Unix realm ;-) None of solutions for Unix are appealing to me. But they must be "the" solution for the challenge as well-established software uses those solutions. Now, I'm wondering. As my program is a GUI (Tkinter) software. Is it possible to set a known value to X11 or Tk property through Tkinter so that another instance of the program can check if such property is set? Of course, I know this scheme has a flaw. If one instance uses another logical display, then such property is probably not shared. But for my usage, it is logically possible but not likely. I checked my Tkinter book and found the following function. winfo_interps(displayof=0) This returns a list of all Tk-based applications currently running on the display. When I tried, I got the following: >>> root.winfo_interps() ('tk #3', 'tk #2', 'tk') But I couldn't find a way to set a specific name to the Tcl interpreter. As I'm not an expert of Tcl/Tk and X11, I probably overlooked other functions that may do what I need. Any comments, suggestions on this? Maybe this can provide a platform independent way to ensure that only single instance is running. Thank you for your attention. Best reagrds, Aki Niimura From robert.d.kirkpatrick at gmail.com Wed Sep 24 02:05:29 2008 From: robert.d.kirkpatrick at gmail.com (Rob Kirkpatrick) Date: Tue, 23 Sep 2008 23:05:29 -0700 (PDT) Subject: Visualize class inheritance hierarchy References: <5f3415b7-e210-416d-86c6-f4dc0475741d@w1g2000prk.googlegroups.com> Message-ID: On Sep 23, 4:58 pm, Christian Heimes wrote: > Rob Kirkpatrick wrote: > > I'm assuming this has been discussed before, but I'm lacking any > > Google keywords that bring up the appropriate discussion. > > You are looking for "mro" aka method resolution order. The inspect > module contains several helper functions to inspect a class hierarchy. > > The following interactive session should give you an impression how to > use the functions: > > >>> import inspect > >>> import pprint > >>> from sqlalchemy.types import DateTime > > >>> inspect.getmro(DateTime) > (, 'sqlalchemy.types.TypeEngine'>, , > > >>> DateTime.__bases__ > (,) > > >>> pprint.pprint(inspect.getclasstree(inspect.getmro(DateTime))) > [(, ()), > [(, (,)), > [(, > (,)), > [(, > (,))]]]] > > >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, '__init__')] > [, 'sqlalchemy.types.TypeEngine'>, , > ] > > >>> [cls for cls in inspect.getmro(DateTime) if hasattr(cls, 'adapt')] > [, ] Oh, yeah. That's the stuff! From mrkylehayes at gmail.com Tue Sep 30 13:50:01 2008 From: mrkylehayes at gmail.com (Kyle Hayes) Date: Tue, 30 Sep 2008 10:50:01 -0700 (PDT) Subject: r"" References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> Message-ID: <33077c9c-01d9-4423-afd2-7452117bc6b4@j22g2000hsf.googlegroups.com> > Please describe the actual problem you're trying to solve. In what way > do slashes need to be "fixed," and why? Well, I have decided to build a tool to help us sync files in UNC paths. I am just building the modules and classes right now so I haven't developed the frontend yet. I am assuming when the user provides a path (either by typing it in, or pulling it in from a config file), the UNC slashes are going to escape stuff in the string, so I want to double them up. I understand if the best way is to convert all the slashes to double- slashes. But the 'r' function seemed so handy and convenient. I am very new to Python, but not at all to programming. Thanks! From eflick at gmail.com Tue Sep 30 19:20:43 2008 From: eflick at gmail.com (Eric) Date: Tue, 30 Sep 2008 16:20:43 -0700 (PDT) Subject: Wait or not? Message-ID: <34809165-9c72-46b3-996c-4bd55451505d@e53g2000hsa.googlegroups.com> I've been wanting to learn Python for a while now but I can't decide on whether to wait for Python 3's final release and learn it or just go ahead and learn 2.x. Would it be hard to make the transition being a noob? From sturlamolden at yahoo.no Mon Sep 8 22:31:41 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 8 Sep 2008 19:31:41 -0700 (PDT) Subject: Coming from .NET and VB and C References: Message-ID: On 3 Sep, 18:52, ToPostMustJoinGroup22 wrote: > I'm coming from a .NET, VB, C background. > Any suggestions for someone new to the scene like me? Welcome! Unfortunately, you probably have a lot of bad habits to unlearn. Don't use Python like another C, VB or Java. It will cause a lot of grief, and you'll end up with the idea that Python is slow like a slug. Python is more like Lisp or Haskell, but with a readable syntax. There are list comprehensions, generator expressions, dictionaries, sets, lists, list slicing, lambdas, map, reduce, filter, closures, etc. They are there to be used, and be used a lot. Learning to use Python efficiently is what has the steepest learning curve. From half.italian at gmail.com Thu Sep 11 14:39:04 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 11 Sep 2008 11:39:04 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> Message-ID: <734ce614-3e92-4515-9342-d2e4e88c9632@b30g2000prf.googlegroups.com> On Sep 11, 9:59?am, Fredrik Lundh wrote: > carriere.jonat... at gmail.com wrote: > > I want to build a desktop application. I am searching for some kind of > > environment that would provide all the elements ready (Windows...). > > Then I would have to code the business logic only. > > start here: > > ? ?http://wiki.python.org/moin/GuiProgramming > > The big ones are Tkinter, which is usually bundled with Python; > wxPython, and PyQt. ?There's also a trend towards using the web browser > as a presentation engine also for local applications; for libraries that > help you with that, you can start here: > > ? ?http://wiki.python.org/moin/WebProgramming > > or jump directly to > > ? ?http://www.djangoproject.com/ > > I saw a message in the last few days showing how to use Flash as a front end for Python apps. It looked interested. Can anyone point me to it? ~Sean From gtitus_ at _wanadoo.fr Tue Sep 30 16:53:48 2008 From: gtitus_ at _wanadoo.fr (marc) Date: Tue, 30 Sep 2008 22:53:48 +0200 Subject: pylab without X11 In-Reply-To: References: Message-ID: <48e291d4$0$863$ba4acef3@news.orange.fr> This may help you ... or not You may have to change your backend : p13 of the matplotlib user guide: backends p17 how to change the backend in the matplotlibrc An example of matplotlibrc ( backend choice is at the beginning ): http://matplotlib.sourceforge.net/matplotlibrc You may choose PS or SVG or pdf, there might be other possibilities, I do not know To save the file : savefig Marc Willem-Jan Vriend a ?crit : > I want to use pylab (matplotlib) on a machine without X11. I'm trying to > generate onthefly graphics for an apache2 web service, so they do not > have to be displayed on this machine ! > > When i do > pylab.figure() > I get the error > TclError: couldn't connect to display ":0.0" > > I tried setting the DISPLAY environment variable to "", ":0.0" but I got > the same error message. > > Any help is very much appreciated. From invalid at invalid Thu Sep 18 12:07:45 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 18 Sep 2008 11:07:45 -0500 Subject: PEP proposal optparse References: Message-ID: While we're making suggestions, I've always wished that the --help output displayed the default values for options in addition to the help text specified by the user. I end up having to enter the default values twice -- once as a keyword argument and again in the help text. Then later when I decide to change the default value, things get out-of-sync. -- Grant Edwards grante Yow! Did you move a lot of at KOREAN STEAK KNIVES this visi.com trip, Dingy? From rcdailey at gmail.com Fri Sep 19 09:37:00 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 19 Sep 2008 08:37:00 -0500 Subject: Intercepting printed strings In-Reply-To: References: <496954360809181524g6037e0b0x84e98834bbf8ad9c@mail.gmail.com> Message-ID: <496954360809190637n8c12c6cvc177327aeb032ae4@mail.gmail.com> On Fri, Sep 19, 2008 at 4:21 AM, Gabriel Genellina wrote: > En Thu, 18 Sep 2008 19:24:26 -0300, Robert Dailey > escribi?: > > > I'm currently using Python 3.0 b3 and I'm curious as to how I can go about >> intercepting things send to print() for some intermediate processing >> before >> they're actually sent to sys.stdout. Right now I've thought of the >> following: >> >> Replace sys.stdout with a class named PrintStream. PrintStream is defined >> as >> follows: >> >> class PrintStream: >> def write( self, message ): >> sys.__stdout__.write( '\t{0}'.format( message ) ) >> >> Will this work? Basically I want to add a tab character in front of every >> message printed. Thanks. >> > > Why don't you try it yourself? > You may replace builtins.print with your own function too. It's not exactly > the same thing, but given your request "intercepting things send to print() > before they're sent to sys.stdout" it may be more adequate. I did try the code I posted and it doesn't work. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Sep 19 06:14:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 07:14:48 -0300 Subject: webbrowser fragment identifier References: <0b00afc4-018f-4b80-9fba-93c253a86c7a@q5g2000prf.googlegroups.com> Message-ID: En Thu, 18 Sep 2008 21:53:22 -0300, scottbvfx escribi?: > I'm trying to launch a web browser along with an html file with a > fragment identifier in its path. I'm using the webbrowser module for > this. > ie. webbrowser.open('file:///C:/myfile.html#SomeEntryInTheHTML') > > for some reason it is truncating the path to 'file:///C:/myfile.html'. > > Does anyone know a way of getting the fragment identifier in there > (with webbrowser module or any other)? It's not Python which truncates the path - webbrowser.open doesn't modify the url given. Looks like you're on Windows. Internet Explorer exposes a COM interface that you may use to control it. Google for "python IE automation" -- Gabriel Genellina From dmitrey.kroshko at scipy.org Tue Sep 23 16:21:18 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Tue, 23 Sep 2008 13:21:18 -0700 (PDT) Subject: [Tkinter] how to keep a window above all other OS windows? Message-ID: Hi all, how to keep a Tkinter window above all other OS windows (i.e. including those ones from other programs)? Thank you in advance, Dmitrey From marco.bizzarri at gmail.com Fri Sep 5 01:12:31 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 07:12:31 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <3f0d61c40809040409v3ee40da3h7eb0703009e78f06@mail.gmail.com> Message-ID: <3f0d61c40809042212q4244a1fn1a602fa195a7ca3c@mail.gmail.com> On Thu, Sep 4, 2008 at 7:15 PM, Timothy Grant wrote: > > I think the most obvious solution to the problem is effective unit > tests. If you type "a.y =1" and have a test that asserts a.x == 1 then > you would quite quickly discover that you made a typo. > > > -- > Stand Fast, > tjg. [Timothy Grant] > Right; that is one of the things I try to do to avoid this sort of problems. -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From aahz at pythoncraft.com Fri Sep 26 00:23:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 25 Sep 2008 21:23:05 -0700 Subject: Python is slow? References: Message-ID: In article , Grant Edwards wrote: > >AFAICT, _everybody_ is bad at programming C++. > >One begins to suspect it's not the fault of the programmers. http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From rcdailey at gmail.com Fri Sep 5 17:34:38 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 5 Sep 2008 16:34:38 -0500 Subject: Need formatting suggestion for long strings In-Reply-To: <92da89760809051358k7c5ed12enb755efee45f42f37@mail.gmail.com> References: <3df18123-4e38-48c5-8e69-04968309489b@k37g2000hsf.googlegroups.com> <496954360809051315v44438624vf16240216d8ba2c5@mail.gmail.com> <92da89760809051358k7c5ed12enb755efee45f42f37@mail.gmail.com> Message-ID: <496954360809051434v5ec0a7fckdd70b335862a786c@mail.gmail.com> On Fri, Sep 5, 2008 at 3:58 PM, Eric Wertman wrote: > > I'm concerned about the formatting of the string in that I do not want > the > > way I split the string up in source code to affect the way the string is > > displayed to the console. In other words, in source, if I break up a > single > > string into multiple lines (using carriage returns), I would expect the > > string to still render as a single-line string. > > > > I'm also concerned about the source formatting, because I do not want the > > single-line string to run off the edge of my display. I want it to be in > > "Paragraph form" in the source code, but remain a single-line when > printed. > > I think you can also escape the line breaks: > > > This does not fully work because I like to add tabs to the front of the string on each line to keep it aligned with the current tab depth of that particular line of code. These strings will not always be in global namespace. The tabs in the front of the string would actually be included as part of the string, which I do not want. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Fri Sep 12 05:27:39 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Sep 2008 09:27:39 GMT Subject: Better error message on recursive import References: <6isb2mF9scaU1@mid.individual.net> <6isunqF6v3jU2@mid.uni-berlin.de> <6iul4uFkaviU1@mid.individual.net> Message-ID: <6iur0bFioqdU1@mid.uni-berlin.de> On Fri, 12 Sep 2008 09:47:42 +0200, Thomas Guettler wrote: >> Can you give an example of such a recursive import you want the special >> exception be raised? > > ===> cat one.py > from two import testtwo > def testone(): > print "one" > > ===> cat two.py > import one > def testtwo(): > print "two" > > ===> python one.py > Traceback (most recent call last): > File "one.py", line 1, in > from two import testtwo > File "/mnt/home/tguettler/tmp/rec/two.py", line 1, in > import one > File "/mnt/home/tguettler/tmp/rec/one.py", line 1, in > from two import testtwo > ImportError: cannot import name testtwo This is an awkward situation anyway because here are *three* modules involved. You start `one.py` which will be imported as `__main__`. `__main__` imports `two` and `two` imports a *new* module `one`! Which tries to import `testtwo` from `two` which doesn't exist at that time. Even if you rearrange the code to load properly `one.py` is loaded and executed *twice* and you end up with two distinct modules generated from that file. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Tue Sep 23 17:41:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 17:41:51 -0400 Subject: Detecting the first time I open/append to a file In-Reply-To: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > for param in range(10): > simulate(param) > > def simulate(parameter): > 'Lots of code followed by: > with open(summaryFn, 'ab') as f: > writer = csv.writer(f) > writer.writerow(header) > writer.writerow(Sigma) > > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. How about file.tell == 0? or have I misunderstood the requirement? From castironpi at gmail.com Fri Sep 26 22:15:01 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 19:15:01 -0700 (PDT) Subject: getting global variables from dictionary References: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> Message-ID: On Sep 26, 9:01?pm, icarus wrote: > global_vars.py has the global variables > set_var.py changes one of the values on the global variables (don't > close it or terminate) > get_var.py retrieves the recently value changed (triggered right after > set_var.py above) > > Problem: get_var.py retrieves the old value, the built-in one but not > the recently changed value in set_var.py. > > What am I doing wrong? > > ----global_vars.py--- > #!/usr/bin/python > > class Variables : > ? ? ? ? def __init__(self) : > ? ? ? ? ? ? ? ? self.var_dict = {"username": "original username"} > > ---set_var.py --- > #!/usr/bin/python > > import time > import global_vars > > global_vars.Variables().var_dict["username"] = "new username" > time.sleep(10) ? #give enough time to trigger get_var.py > > ---get_var.py --- > #!/usr/bin/python > import global_vars > print global_vars.Variables().var_dict.get("username") Are these separate processes? From hrishys at yahoo.co.uk Wed Sep 24 11:19:58 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Wed, 24 Sep 2008 15:19:58 +0000 (GMT) Subject: Linq to Python In-Reply-To: Message-ID: <815199.94437.qm@web27401.mail.ukl.yahoo.com> Hi Terry Oops i never realised the mistake i have commited I apologise (i thought changing the subject line would make a new thread) I apologise (I thought Python programmers were smart and they did know what LINQ was) I don't apologise ( i dont apologise for the third one not sounding cocky here but i did google but nothing much came up thats when i posted the question here since i always see Python programmers are somehow smarter then programmers in other langauges i don't know if its the language or the programmers themselves that make them smart) regards Hrishy --- On Tue, 23/9/08, Terry Reedy wrote: > From: Terry Reedy > Subject: Re: Linq to Python > To: python-list at python.org > Date: Tuesday, 23 September, 2008, 7:51 PM > > Will LINQ be ported to Python ? > > I have three suggestions: > > 1. When starting a new thread, start a *new* thread. > Don't tack a new, > unrelated subject onto an existing thread. Your post will > not be seen > by people with readers that collapse thread and who do not > happen to > read the 'Python is slow?' thread. > > 2. Also, give enough informaton that people can understand > your question > without searching the web and guessing. In particular, > that do *you* > mean by LINQ? The game? The .NET component? Or something > else? > > 3. Before posting, search the Python manuals or the web a > bit for an > answer. If you mean the .NET component, googling > 'Python LINQ' should > partly answer your question. > > tjr > > -- > http://mail.python.org/mailman/listinfo/python-list From andre.roberge at gmail.com Sun Sep 14 20:41:16 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sun, 14 Sep 2008 17:41:16 -0700 (PDT) Subject: "Best" way to "drive" a Python program step by step. Message-ID: Hi everyone, I'd be interested in hearing suggestions as to the "best" way to drive a Python program step by step from another application. Details: --------- I have implemented a "Robot" that can be programmed by a user to perform certain actions. (see Reeborg below for a simple javascript- based example). For example, part of a typical program might look like: ===== move() turn_left() move() for i in range(2): move() ... === I had this working in a desktop based application (see RUR-PLE below), where the user program was executed via exec user_code in MyGlobals and MyGlobals contained appropriate definitions. Having it all included in a single Python program, I could include time delays in each instruction [such as move()], so that the user could stop the program running by clicking on a button, etc., and then step through a series of instructions one-by-one, and/or resume the automatic execution. Now, I want to reproduce this behaviour in a browser based application (see Crunchy below). So, I'd like the Python back end to send information (at set intervals) to the browser and be able to react to input from the browser (say, a user pressing a "pause" button). I could try to reimplement the method I used for RUR-PLE some 3 years ago but I know enough now to realize that the method I used was rather "inelegant", but don't know enough to see a better way off-hand. Any suggestion would be appreciated. Cheers, Andr? Reeborg: http://reeborg.world.googlepages.com/reeborg.html Crunchy: http://code.google.com/p/crunchy/ RUR-PLE: http://rur-ple.sourceforge.net/ From bieffe62 at gmail.com Mon Sep 15 09:33:56 2008 From: bieffe62 at gmail.com (bieffe62 at gmail.com) Date: Mon, 15 Sep 2008 06:33:56 -0700 (PDT) Subject: objet COM et ms Word References: <245dc065-660f-4dfe-8134-14b4acfc1f2d@j22g2000hsf.googlegroups.com> Message-ID: On 15 Set, 12:04, Pretorien wrote: > Bonjour @ tous, > > je voudrais gerer des doc Word avec python. > Y aurai-uil une doc quelque part bien faites ??? > > Pour le moment je fais : > > import win32com.client > > word = win32com.client.Dispatch('Word.Application') > > en suite j'ouvre VBexpress pour connaitre qu'elle fonction appeler: > par ex: > > Dim wrdApp As Word.Application > > Set wrdDoc = wrdApp.Documents.Open("\Exemple.doc") > > donc en python cela donnerai word.Documents.Open("toto.doc") > > et ainsi de suite .... > > Y a t il quelque de bien faits pour python, de mani?re a ne pas avoir > a g?rer et VB d'un cote pour deviner les fonctions ? appeler en > python. > > Merci par avance, > > Crdt, > > Thomas (I can read french but not write it, so ...) I did some simple automatic document generation using the COM interface of word, and I found this code snippet of some utility: http://www.bigbold.com/snippets/posts/show/2037 Ciao ----- FB From lists at cheimes.de Wed Sep 10 08:53:40 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 14:53:40 +0200 Subject: I want to use a C++ library from Python In-Reply-To: <6ipr40Fr7kr2U1@mid.uni-berlin.de> References: <6ipd53FrptpiU1@mid.uni-berlin.de> <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> <6ipr40Fr7kr2U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Which actually isn't really helpful, as a DLL itself says nothing about what > language was used to create it - and sending the OP to e.g. ctypes makes no > sense at all in the face of C++. The library - or more precisely the calling convention of the library - is related to the solution. On Windows a dll might be a container for a .NET assembly and C++ code can (theoretically) be compiled to .NET, too. > Whereas the first link for "python c++" is Boost::Python, a C++-wrapper to > make C++-code accessible from Python. C++ bindings can be created with SIP, SWIG, Boost or hand written code. Multiple sites claim that SIP generates the fastest code. Christian From m_palmer45 at yahoo.ca Mon Sep 15 21:03:08 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 15 Sep 2008 18:03:08 -0700 (PDT) Subject: How to marshal objects to readable files? References: Message-ID: On Sep 14, 11:28 am, nielinjie wrote: > Hi list: > I just want to marshal objects (instance of custom classes)to a human > *READABEL *file/string, and also, I want unmarshal it back. in xml > format or any other format. > Any advice? Which lib should I use? > Thanks a lot. There is module pickle in the standard library. It's output is not all that bad (in text mode, that is). If you don't like it, it would still be a good starting point for a custom serializer - it does all the tree walking for you, so you would only have to customize the strings it writes and reads back in. From michele.simionato at gmail.com Sat Sep 6 02:39:02 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 5 Sep 2008 23:39:02 -0700 (PDT) Subject: use str as variable name References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> <48c1a184$0$17080$426a74cc@news.free.fr> Message-ID: On Sep 6, 8:02?am, "Marco Bizzarri" wrote: > On Fri, Sep 5, 2008 at 9:16 PM, Bruno Desthuilliers > > wrote: > > Marco Bizzarri a ?crit : > > >> Just a question: "generic functions" are not meant in the sense of > >> "generic functions" of CLOS, am I right? > > > Nope. Just "generic" in the sense that they accept any object implementing a > > very minimal interface. > > > If you want something like CLOS multimethods, you may be interested in > > Philip Eby's ruledispatch. > > Even though I loved them when I used at university, I'm not looking > for them right now... but nice to know that they are available under > python :-) Actually they are already available in the standard library but they are undocumented. See for instance this recent blog post of mine: http://www.artima.com/weblogs/viewpost.jsp?thread=237764 (as well as the comment below by P.J. Eby) From srikrishnamohan at gmail.com Wed Sep 24 02:02:41 2008 From: srikrishnamohan at gmail.com (km) Date: Wed, 24 Sep 2008 11:32:41 +0530 Subject: python 3.x third party modules Message-ID: Hi all, I would like to look at third party modules which are python 3.0 ready. could some one point me to such a resource ? If its not available, it would be useful to host a page regarding this on python.org ? any comments ? KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Tue Sep 23 14:06:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 14:06:57 -0400 Subject: adding in-place operator to Python In-Reply-To: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> References: <266557d0809230351v6e21dc57hdf3ee53f0619b6c1@mail.gmail.com> Message-ID: Arash Arfaee wrote: > Hi All, > > Is there anyway to add new in-place operator to Python? Or is there any > way to redefine internal in-place operators? Python does not have 'in-place operators'. It has 'augmented assignment statements' that combines a binary operation with an assignment. *If* the target being rebound is mutable, *then* (and only then) the operation can be and is recommended to be done 'in-place'. User-defined mutable classes (as most are) can implement in-place behavior with __ixxx__ methods. But for the reason given below, __ixxx__ methods should supplement and not replace direct mutation methods. Correct terminology is important for understanding what augmented assigments do and what they are basically about. First, most augmented assignments target immutables, in particular, numbers and strings, which do not have __ixxx__ methods. So the operation is *not* done in-place. The only difference from separately indicating the assignment and operation is that the programmer writes the target expression just once and the interpreter evaluates the target expression just once instead of each repeating themselves. (And consequently, any side-effects of that evaluation happen just once instead of twice.) The same __xxx__ or __rxxx__ method is used in either case. This non-repetition is the reason for augmented assigments. The optional in-place optimization for mutables is secondary. It was debated and could have been left out. Second, all augmented assignments perform an assignment, even if the operation is done in place. However, if a mutable such as a list is accessed as a member of an immutable collection such as a tuple, mutation is possible, but rebinding is not. So the mutation is done and then an exception is raised. To avoid the exception, directly call a mutation method such as list.extend. Terry Jan Reedy From kay.schluehr at gmx.net Thu Sep 4 05:14:21 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 4 Sep 2008 02:14:21 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <1b79c772-f6d7-42ec-abc1-d53eb37ec83e@n38g2000prl.googlegroups.com> On 4 Sep., 10:31, "M.-A. Lemburg" wrote: > On 2008-09-04 07:49, Kay Schluehr wrote: > > > 3) Following the public rumor mill and the latest hype RIA i.e. the > > merge of web- and desktop applications with systems like Adobe AIR, > > JavaFX, Google Gears and MS Silverlight is the future of frontend > > development. With the exception of IronPython and Silverlight, Python > > hasn't even entered this game and no one knows if it ever will. > > Actually, it has already and quite some time ago: > > http://www.artima.com/weblogs/viewpost.jsp?thread=208528 > > The recipe is simple: use Python for the business logic, database > interfacing, etc and have it talk to a Flex front-end via XML-RPC > or REST. Python is still server-side in this scenario and plays no role in UI definitions. So one doesn't get more than e.g. Django apps that respond to HTTP requests triggered by JavaScript forms except that JavaScript+HTML+Browser is replaced by Flex = AS3+MXML+FlashPlayer. The role of Python is somewhat arbitrary. This could change only if Python becomes a client side language executed by AVM, V8 etc. like IronPython in Silverlight. About separating UI from application logics by assigning functionality to different general purpose languages I have to admit that I don't think it is such a great idea ... From invalid at invalid Tue Sep 16 13:43:29 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 16 Sep 2008 12:43:29 -0500 Subject: literals optimization (was Re: append on lists) References: <242dnVKpgdmjQ1LVnZ2dnUVZ_vWdnZ2d@posted.visi> Message-ID: On 2008-09-16, Maric Michaud wrote: > Le Tuesday 16 September 2008 18:26:38 Grant Edwards, vous avez ?crit?: >> I was asking where in the specification >> it says that all >> expressions that return something, return a new object. ? > > I never said this, I said it's the spirit of python APIs, with > some noticeable exceptions (see my first post). But for this > case specifically, a + b *should* return a new object, see the > documentation of __add__ and __iadd__ special methods, it's > clearly stated. OK, I've read through the documentation for __add__ and __iadd__ in the language reference, and I can't find anything that states or implies that they are to return a new object. Can you perhaps provide a link or some sort of cite? -- Grant Edwards grante Yow! Are you selling NYLON at OIL WELLS?? If so, we can visi.com use TWO DOZEN!! From jlstepp14 at wi.rr.com Wed Sep 10 12:45:19 2008 From: jlstepp14 at wi.rr.com (Jeff & Laura) Date: Wed, 10 Sep 2008 11:45:19 -0500 Subject: crack registration codes for pogo games Message-ID: your site won't come up....Do you have the crack for operation mania on pogo.com? -------------- next part -------------- An HTML attachment was scrubbed... URL: From gary at byoteki.com Sat Sep 6 18:38:59 2008 From: gary at byoteki.com (Gary Josack) Date: Sat, 06 Sep 2008 18:38:59 -0400 Subject: Cathing several potential errors? In-Reply-To: References: Message-ID: <48C30683.80408@byoteki.com> cnb wrote: > if i do > try: > something > except TypeError, IndexError: > pass > > only the first error will get caught. I dont want to use Exception and > catch all errors, but just 2. how can i do that? > -- > http://mail.python.org/mailman/listinfo/python-list > what you're doing is assigning the value of TypeError to the name IndexError try: somthing except (TypeError, IndexError): pass use except (TypeError, IndexError), e: print e if you want to print the error From emile at fenx.com Tue Sep 9 14:13:45 2008 From: emile at fenx.com (Emile van Sebille) Date: Tue, 09 Sep 2008 11:13:45 -0700 Subject: check if the values are prensent in a list of values In-Reply-To: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> Message-ID: flit wrote: > Hello All, > > I will appreciate the help from the more skillfull pythonistas.. > > I have a small app that generates a sequence like > > 00341 > 01741 > 03254 Consider using a dict with sorted tuple keys, eg d = {} for seq in ['00341','01741','03254']: ky = list(seq) ky.sort() d[tuple(ky)] = None then d.keys() are the unique combinations. HTH, Emile > > This values I am putting in a list. > > So I have a list = [00341,01741,03254] > > after the programs find the sequence 03401 this sequence is "new" so > it appends on the list. But I want to avoid that as the values are > already on the first sequence of the list (00341). > If I try to use a "in" statement it will give false. as 00341 is > different from 00341 (but for my goal not..) > > > How can I check against this list and avoid to put "different" > sequences but same values? > > as 34100 --> dont append on the list > 14300 ---> dont append on the list > 05321 --> append to the list. > > Am I doing some conceptual error using lists? > There is a better approach? > > Thanks > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From tim_grove at sil.org Tue Sep 2 11:47:08 2008 From: tim_grove at sil.org (Tim Grove) Date: Tue, 02 Sep 2008 16:47:08 +0100 Subject: [ctypes-users] ctypes - loading 'librsvg-2-2.dll' In-Reply-To: References: <48B3B8B3.5070309@sil.org> Message-ID: <48BD5FFC.20703@sil.org> Thanks Martin (and others) for your advice. No, this solution didn't quite work either. Well, the extremely annoying thing is that it DOES work on another home pc, but on my laptop which I use for work, it doesn't want to know!!! Both are running WinXP Pro. All the dependencies and paths "seem" to be okay, but there must still be something that I'm missing. Tim Martin (gzlist) wrote: > On 26/08/2008, Tim Grove wrote: > >> Any ideas why a particular dll won't load on Windows XP Pro using >> ctypes? >> > > I'm going to take a stab in the dark here and suggest it's because you > have multiple (different) copies of iconv.dll on your PATH. > > >> l=CDLL(r'D:\SILSign\librsvg-2-2.dll') >> Traceback (most recent call last): >> File "", line 1, in >> File "C:\PYTHON25\LIB\ctypes\__init__.py", line 349, in __init__ >> self._handle = _dlopen(self._name, mode) >> WindowsError: [Error 127] The specified procedure could not be found >> > > I get this on my current setup, where I've been messing around trying > to recompile lynx against iconv. I also get a popup saying "The > procedure entry point libiconv_set_relocation_prefix could not be > located in the dynamic link library iconv.dll." > > Doing this worked for me: > > C:\>set PATH=C:\Program Files\Common Files\GTK\2.0\bin > C:\>"C:\Python24\python.exe" -c "import ctypes; print > ctypes.CDLL('librsvg-2-2')" > > > Change the paths to your equivalents and try it, see if you have the > same or a similar dependency problem. > > Martin > > From williamhpurcell at gmail.com Thu Sep 4 20:14:10 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Thu, 4 Sep 2008 19:14:10 -0500 Subject: Converting .doc to .txt in Linux In-Reply-To: References: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: Here is a function that I have used with wvText to convert .doc files into text files. def readdoc(fpath): tmp = 'tmp_readdoc.txt' cmd = 'wvText %s %s'%(fpath,tmp) os.system(cmd) lines = open(tmp,'r').readlines() os.unlink(tmp) return lines It's not a completely python dependent function but it might work in a pinch. It depends on wv. I have tried the python uno and the Danny OOoLib modules, which might be worth looking into but I didn't have much luck. If you find a better or a completely python dependent method, let me know. FWIW -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From miki.tebeka at gmail.com Tue Sep 23 04:57:17 2008 From: miki.tebeka at gmail.com (Miki) Date: Tue, 23 Sep 2008 01:57:17 -0700 (PDT) Subject: Regex Help References: Message-ID: <48e3268f-9282-4a31-b67e-eff71f9513e3@s20g2000prd.googlegroups.com> Hello, > Anybody know of a good regex to parse html links from html code? BeautifulSoup is *the* library to handle HTML from BeautifulSoup import BeautifulSoup from urllib import urlopen soup = BeautifulSoup(urlopen("http://python.org/")) for a in soup("a"): print a["href"] HTH, -- Miki http://pythonwise.blogspot.com From electronixtar at gmail.com Sun Sep 28 07:09:30 2008 From: electronixtar at gmail.com (est) Date: Sun, 28 Sep 2008 04:09:30 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> <6k93opF6k62hU1@mid.uni-berlin.de> Message-ID: <913193c5-1722-45ae-9cec-efa548dd6992@b38g2000prf.googlegroups.com> On Sep 28, 6:15?pm, Marc 'BlackJack' Rintsch wrote: > On Sun, 28 Sep 2008 01:35:11 -0700, est wrote: > >> Because that's how ASCII is defined. > >> Because that's how ASCII is defined. ?ASCII is a 7-bit code. > > > Then why can't python use another default encoding internally > > range(256)? > > Because that doesn't suffice. ?Unicode code points can be >255. > > > If Python choose another default encoding which handles range(256), 80% > > of python unicode encoding problems are gone. > > 80% of *your* problems with it *seems* to be gone then. > > > It's not HARD to process unicode, it's just python & python community > > refuse to correct it. > > It is somewhat hard to deal with unicode because many don't want to think > about it or don't grasp the relationship between encodings, byte values, > and characters. ?Including you. > > >> stop dreaming of a magic solution > > > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, what's > > wrong???? > > What do you mean by "just print 0x7F to 0xFF"? ?For example if I have ``s > = u'Sm?rebr?d?'`` what bytes should ``str(s)`` produce and why those and > not others? > > >> Isn't that more or less the same as telling the OP to use unicode() > >> instead of str()? > > > sockets could handle str() only. If you throw unicode objects to a > > socket, it will automatically call str() and cause an error. > > Because *you* have to tell explicitly how the unicode object should be > encoded as bytes. ?Python can't do this automatically because it has *no > idea* what the process at the other end of the socket expects. > > Now you are complaining that Python chooses ASCII. ?If it is changed to > something else, like MBCS, others start complaining why it is MBCS and > not something different. ?See: No fix, just moving the problem to someone > else. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Well, you succeseded in putting all blame to myself alone. Great. When you guy's are dealing with CJK characters in the future, you'll find out what I mean. In fact Boa Constructor keeps prompting ASCII and range(128) error on my Windows. That's pretty cool. From mensanator at aol.com Sun Sep 7 20:49:17 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 7 Sep 2008 17:49:17 -0700 (PDT) Subject: max(), sum(), next() References: <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: On Sep 7, 2:17?pm, Dennis Lee Bieber wrote: > On Sun, 7 Sep 2008 10:30:09 -0700 (PDT), Mensanator > declaimed the following in comp.lang.python: > > > On Sep 6, 11:05?pm, Steven D'Aprano > cybersource.com.au> wrote: > > > > Sheesh. That's not a problem, because Python is not trying to be a > > > dialect of SQL. > > > And yet, they added a Sqlite3 module. > > ? ? ? ? Which is an interface TO an embedded/stand-alone SQL-based RDBM > engine; it does not turn Python into a dialect of SQL -- Python does not > process the SQL, it gets passed to the engine for SQL data processing. But that's only half the story. The other half is data returned as a result of SQL queries. And that's something Python DOES process. And sometimes that processed data has to be inserted back into the database. We certainly don't want Python to process the data in a way that the database doesn't expect. When I see a potential flaw (such as summing an empty list to 0), should I just keep quiet about it, or let everyone know? Well, now they know, so I'll shut up about this from now on, ok? > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From python at rgbaz.eu Wed Sep 10 12:57:14 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 18:57:14 +0200 Subject: md5 differences In-Reply-To: References: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> Message-ID: <4158A777-F11F-4044-8BE2-D1B092A4B106@rgbaz.eu> On 10 sep 2008, at 18:34, Fredrik Lundh wrote: > Python wrote: > >> I'm trying to match the results of an md5 checksum done in a tcsh >> shell. >> I keep getting different results and can't find anything on google... >> here's an example: >> Arno at Computer:~% echo "hello" | md5 >> b1946ac92492d2347c6235b4d2611184 >> Arno at Computer:~% python >> Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) >> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin >> Type "help", "copyright", "credits" or "license" for more >> information. >> >>> import md5 >> >>> md5.new("hello").hexdigest() >> '5d41402abc4b2a76b9719d911017c592' > > >>> import md5 > >>> md5.new("hello\n").hexdigest() > 'b1946ac92492d2347c6235b4d2611184' > > > oooh... thanks :) From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 18:59:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 22:59:48 GMT Subject: doctest not seeing any of my doc tests References: <00d3d407$0$20306$c3e8da3@news.astraweb.com> Message-ID: <00d45737$0$20306$c3e8da3@news.astraweb.com> On Sun, 07 Sep 2008 15:51:01 +0200, Fredrik Lundh wrote: > Steven D'Aprano wrote: > >> I have a function in my module: >> >> def selftest(verbose=False): >> import doctest >> doctest.testmod(verbose=verbose) > > what happens if you change the above to > > def selftest(verbose=False): > import doctest, yourmodule > doctest.testmod(yourmodule, verbose=verbose) > > (where yourmodule is the name of your module, obviously) Well, that certainly fixed the problem, thanks. It now correctly runs all my doctests. But I don't understand why a bare doctest.testmod() works when you run it non-interactively, but fails when run interactively. -- Steven From steve at holdenweb.com Fri Sep 12 12:26:17 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 12 Sep 2008 12:26:17 -0400 Subject: lacking follow-through In-Reply-To: <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> Message-ID: Aaron "Castironpi" Brady wrote: > On Sep 12, 7:23 am, Steve Holden wrote: >> castironpi wrote: >> >> If you are flattered to be compared to an AI you must come from the same >> race as Mr. Spock in Star Trek. > > No, I said 'for my logic to compared'. Speaking of which, I think you > excluded the possibility of diligent and ethical human, which meets > the criteria (of being flattered to be compared to an AI)... unless > Vulcan is just a synonym for it. If you want a discussion of why a > diligent and ethical human takes pride in / devotes effort to logic, > that's another topic that I'm happy to engage on. > >> You aren't entitled to require discussion of your ideas and proposals. > > No, but you are entitled to human interaction. If your case is that I > should seek mine face-to-face instead of keyboard-to-screen, you > probably have a point. > > ... > >> [...] >> >>> For example, I sometimes hear people talk about salary as though it >>> were social approval, and vice versa. Even though the analogy doesn't >>> hold in every case generally, it is still a good way to express >>> yourself in many contexts, and especially when the more precise word >>> isn't on the tip of your tongue. >> Perhaps under those circumstances the better choice is to hold off >> posting and do some research until you come up with the proper word. > > Yes I know. Good thing everyone at Mozilla agrees with you, and > Thesaurus.Com is included in Firefox's quicksearch engines. > >> Precision in the expression of ideas encourages debate, whereas sloppy >> "just write what you feel" is likely to result in hostile responses, as >> it causes the perception that you value your own time more than that of >> the people you attempt to engage. > > But the value of expression and self-expression can outweigh the value > of debate, even in so stuffy a setting as a Usenet group. Make time > for both or stifle your emotions. Do you hold I should be speaking > from the heart more or less? > > Regardless, you've contradicted yourself: > > 1) "just write what you feel" is likely to result in hostile responses > 2) If you are flattered to be compared to an AI you must [not be > human] > > Assume you, Steve, do as you say (practice what you preach). You do > not write either "just what you feel", nor anything that can be > compared to an A.I. Define the goal of A.I. to be logic and reasoned > "post-impulsive" deliberation (my title to define as I voiced the > flattery). Then conclude you don't post to the newsgroup. Observe > you do, and reach an absurdity. What premise do you retract? > > Knowing nothing of your background in philosophy or otherwise, it may > be a little unfair to put words in your mouth like that. It's a deep > problem (that yes, does have implications on the "diligent and > ethical" issue above) of human nature and the human condition: If > you're not rational, then you're a man. > > Besides, it is better to complain to the group that it is dropping my > posts than to anyone else. > The defence rests. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fredrik at pythonware.com Sun Sep 7 09:51:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 07 Sep 2008 15:51:01 +0200 Subject: doctest not seeing any of my doc tests In-Reply-To: <00d3d407$0$20306$c3e8da3@news.astraweb.com> References: <00d3d407$0$20306$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I have a function in my module: > > def selftest(verbose=False): > import doctest > doctest.testmod(verbose=verbose) what happens if you change the above to def selftest(verbose=False): import doctest, yourmodule doctest.testmod(yourmodule, verbose=verbose) (where yourmodule is the name of your module, obviously) From gagsl-py2 at yahoo.com.ar Wed Sep 3 22:08:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 23:08:38 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <6i6pq9Fmcad7U2@mid.uni-berlin.de> <6vmdncUnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <20080904003435.GA29228@dragontoe.org> Message-ID: En Wed, 03 Sep 2008 21:34:35 -0300, Derek Martin escribi?: > On Wed, Sep 03, 2008 at 03:16:00PM -0700, Dennis Lee Bieber wrote: >> On Wed, 3 Sep 2008 03:09:18 -0400, Derek Martin >> declaimed the following in comp.lang.python: >> >> > struct run { >> > int speed; >> > direction_type direction; >> > }; >> > >> > Not a function. Describes an action. Sure, you'll probably never see >> > this example in a real program. But that doesn't mean you can't do >> > it, and it doesn't make it inherently wrong. Someone somewhere might >> > very well find a legitimate use case. >> >> Does neither for me... It defines a (physics) VELOCITY (a direction >> and a speed, but lacking in starting position and in duration). > > OK... so, let me ask you then: I have a computer program that graphs > the state of a particular act of running over time t. The only > information the program cares about is the speed and direction of that > particular instance of running. What would your data structure look > like? I'd use the name "velocity", a noun, as Dennis Lee Bieber already said. In pedantic mode, "average velocity". If you still want to push further such ridiculous example I'll have to think that you're just trolling. -- Gabriel Genellina From calebjhansen at gmail.com Sat Sep 13 03:15:11 2008 From: calebjhansen at gmail.com (fishfin) Date: Sat, 13 Sep 2008 00:15:11 -0700 (PDT) Subject: question about python Message-ID: I was working through a tutorial about how to write a server using python (the url is bellow). I am sure that the server is working to some degree because when the server is running localhost:8080 just keeps trying to load until it times out. I would like to know how to send information through the server to my browser? I was working through this tutorial: http://python.about.com/od/networkingwithpython/ss/PythonWebServer.htm and my final code is like this: import socket host = '' port = 8080 c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) c.bind((host, port)) c.listen(1) while 1: csock, caddr = c.accept() cfile = csock.makefile('rw', 0) line = cfile.readline().strip() cfile.write('HTTP/1.0 200 OK\n\n') cfile.write('Welcome %s!' % (str(caddr))) cfile.write('

Follow the link...

') cfile.write('All the server needs to do is ') cfile.write('to deliver the text to the socket. ') cfile.write('It delivers the HTML code for a link, ') cfile.write('and the web browser converts it.



') cfile.write('
Click me!
') cfile.write('

The wording of your request was: "%s"' %(line)) cfile.write('') cfile.close() csock.close() From kw at codebykevin.com Tue Sep 9 14:11:57 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 09 Sep 2008 14:11:57 -0400 Subject: How to record audio from Python on Mac? In-Reply-To: References: Message-ID: <48C6BC6D.8040207@codebykevin.com> skip at pobox.com wrote: > (I asked this on pythonmac-sig a couple days ago but got no response, so I'm > casting a broader net.) > > Can I easily control audio record/playback from Python on my Mac? I know > zip about audio recording or about Apple APIs via Python. Pointers to > simple examples would be much appreciated. > > Thanks, > > Skip You can probably access this functionality via PyObjC--it provides access to the Cocoa frameworks. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From half.italian at gmail.com Fri Sep 26 00:04:28 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 25 Sep 2008 21:04:28 -0700 (PDT) Subject: SimpleXMLRPCServer -- turning off request log? References: Message-ID: <9e0d437b-a6a6-4485-aa9a-93ed751b700f@o40g2000prn.googlegroups.com> On Sep 25, 6:01?pm, m... at pixar.com wrote: > My SimpleXMLRPCServer program prints to stderr a line like > this for each request: > > ohm..pixar.com - - [25/Sep/2008 17:57:50] "POST /RPC2 HTTP/1.0" 200 - > > Is there a way to turn this logging off? ?I have RTFM and can't > seem to find a way to do so. > > Many TIA! > Mark > > -- > Mark Harrison > Pixar Animation Studios Im pretty sure there's a more pythonic way, but you could redirect stdout to /dev/null import sys sys.stdout = open("/dev/null", 'w') assuming you're not on windows... ~Sean From skip at pobox.com Fri Sep 26 07:31:40 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 26 Sep 2008 06:31:40 -0500 Subject: Are spams on comp.lang.python a major nuisance? Message-ID: <18652.51228.620303.28571@montanaro-dyndns-org.local> I took over spam filter management for the python.org mailing lists a couple months ago and made a few changes to the way the spam filter is trained. Things seem to be at a reasonable level as far as I can tell (I see a few spams leak through each day), though I wasn't actively reading comp.lang.python/python-list at python.org before I took over the task, so I have nothing to compare with. Does the level of spam leaking through the filter now seem excessive? Is it more or less than in June and July? Thanks, Skip Montanaro From deets at nospam.web.de Mon Sep 15 14:54:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 20:54:42 +0200 Subject: environment variable issue In-Reply-To: <48ceacb9$0$2863$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <6j7pbiF1snjoU1@mid.uni-berlin.de> Michel Leunen schrieb: > Hi, > > Could someone explain me what I'm doing wrong here? I'm trying to > retrieve the value of an environment variable in Ubuntu 8.04 like this: > > >>> import os > >>> os.environ['USER'] > 'michel' > > This works but this doesn't: > > >>> os.environ['HOSTNAME'] > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'HOSTNAME' > > Why is it working in the first case but not in the second one. I must be > missing something but it seems I'm not able to figure it out. Maybe hostname is just missing? What does os.environ.keys() yield? On *my* ubuntu, it gives >>> sorted(os.environ.keys()) ['HOME', 'JAVA_HOME', 'LANG', 'LANGUAGE', 'LOGNAME', 'MAIL', 'PATH', 'PWD', 'PYTHONSTARTUP', 'SHELL', 'SHLVL', 'SSH_CLIENT', 'SSH_CONNECTION', 'SSH_TTY', 'TERM', 'USER', '_'] >>> No HOSTNAME ... Diez From bearophileHUGS at lycos.com Fri Sep 12 14:50:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 12 Sep 2008 11:50:20 -0700 (PDT) Subject: manipulating files within 'for' References: <48CAA2AA.40809@umbc.edu> Message-ID: <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> Ben Keshet: > ...wrong. I thought I should omit the comma and didn't put it. I guess > that stating the obvious should be the first attempt with beginners like > me. Thanks for thinking about it (it's running perfect now). In CLisp, Scheme etc, lists such commas aren't necessary, but in Python if you don't separate strings with a comma they become merged into a single string: >>> 'foo', 'bar' ('foo', 'bar') >>> 'foo' 'bar' 'foobar' Your mistake is caused by Python not following one of its general rules: Explicit is better than implicit. In such case the string concatenation (+) is done implicitly. It's a little handy feature once in a while (but not for me so far), while it may cause bugs, so I don't like this little feature of Python and I may like to see it removed, because it may bite you in similar situations, where you forgot a comma for mistake: parts = ["foo", "bar" "baz"] Bye, bearophile From cs at zip.com.au Wed Sep 24 22:03:13 2008 From: cs at zip.com.au (Cameron Simpson) Date: Thu, 25 Sep 2008 12:03:13 +1000 Subject: multiple processes, private working directories In-Reply-To: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: <20080925020313.GA1786@cskk.homeip.net> On 24Sep2008 18:27, Tim Arnold wrote: | I have a bunch of processes to run and each one needs its own working | directory. I'd also like to know when all of the processes are | finished. | | (1) First thought was threads, until I saw that os.chdir was process- | global. Yep. But do you need separate working directories? As opposed to having the thread state include a notional working directory and constructing file paths within it. | (2) Next thought was fork, but I don't know how to signal when each | child is finished. Open a pipe (os.pipe()). Have a parent process to track state. Fork each child. In each child: close the read end of the pipe. Do stuff. When finished, close the write end of the pipe. In the parent, after forking all children: close the write end of the pipe. Read from the read end. When all the children have finished they will have closed all the write ends and you will see EOF on the read end of the pipe. For extra credit you can have the children write some sort of success/failure byte to the pipe before closing. Counting and examinine these bytes in the parent can tell you about individual failure if you care. | (3) Current thought is to break the process from a method into a | external | script; call the script in separate threads. This is the only way I | can see | to give each process a separate dir (external process fixes that), and | I can | find out when each process is finished (thread fixes that). Yeah, that'll work: for child in 1 2 3 4 5 6 ... do mkdir workdir ( cd work-dir; run-child ) & done wait | Am I missing something? Is there a better way? I hate to rewrite this | method | as a script since I've got a lot of object metadata that I'll have to | regenerate with each call of the script. See the pipe scheme in point (2) above. Doubtless there are other methods, but pipes are each shared resources with the right behaviour. I'd prefer method (1) myself, assuming you have control of the working file paths. Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ If everyone is thinking alike, then someone isn't thinking. - Patton From timr at probo.com Thu Sep 25 03:55:52 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Sep 2008 07:55:52 GMT Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> Message-ID: <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> Marc 'BlackJack' Rintsch wrote: > >On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote: > >>> > This seems to break the rule that if A is equal to B and B is equal >>> > to C then A is equal to C. >>> >>> I don't see why transitivity should apply to Python objects in general. >> >> Well, for numbers it surely would be a nice touch, wouldn't it. May be >> the reason for Decimal to accept float arguments is that irrational >> numbers or very long rational numbers cannot be converted to a Decimal >> without rounding error, and Decimal doesn't want any part of it. Seems >> pointless to me, though. > >Is 0.1 a very long number? Would you expect ``0.1 == Decimal('0.1')`` to >be `True` or `False` given that 0.1 actually is > >In [98]: '%.50f' % 0.1 >Out[98]: '0.10000000000000000555111512312578270211815834045410' >? Actually, it's not. Your C run-time library is generating random digits after it runs out of useful information (which is the first 16 or 17 digits). 0.1 in an IEEE 784 double is this: 0.100000000000000088817841970012523233890533447265625 -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From arnodel at googlemail.com Sun Sep 14 14:24:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Sep 2008 11:24:44 -0700 (PDT) Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> Message-ID: On Sep 14, 5:10?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 14, 4:43?am, Arnaud Delobelle wrote: > > > > > On Sep 14, 10:29?am, Steven D'Aprano > > cybersource.com.au> wrote: > > > I have a function that needs a reference to the module object it is > > > defined in. (For the reason why, if you care, see the thread "doctest not > > > seeing any of my doc tests" from a week ago.) I know of two ways to deal > > > with this problem, both of which feel unsatisfactory to me. Assume the > > > name of the module is "Mod", then I can do either of these: > > > > def foo(): > > > ? ? import Mod > > > ? ? process(Mod) > > > > Disadvantage: If I change the name of the module, I have to remember to > > > change the name of the module reference in foo() twice. > > > > def foo(): > > > ? ? modname = foo.__module__ > > > ? ? module = __import__(modname) > > > ? ? process(module) > > > > Disadvantage: if I change the name of the function, I have to remember to > > > change the reference to itself, but at least both changes are right next > > > to each other. > > > > Assume that changing the function name or the module name are both > > > equally likely/unlikely. > > > > Which do other people prefer? Which seems "better" to you? Are there any > > > other alternatives? > > > What about something like: > > > ? ? sys.modules[__name__] ? > > > -- > > Arnaud > > You're just worried about changing the module's name in the future. > So use a global variable or function that you only have to change > once. > > def Mod_mod( ): > ? ?import Mod as Mod #<-- only one change needed > ? ?return Mod > > def foo( ): > ? ?process( Mod_mod( ) ) Or: import ModuleName as this_module def foo(): process(this_module) -- Arnaud From nick at craig-wood.com Thu Sep 25 06:30:02 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 25 Sep 2008 05:30:02 -0500 Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <6jtthmF50fj6U1@mid.uni-berlin.de> <4pgmd4hhg0oge4gh558u6sqtktrc62jsum@4ax.com> Message-ID: Tim Roberts wrote: > Marc 'BlackJack' Rintsch wrote: > > > >On Tue, 23 Sep 2008 07:08:07 -0700, Michael Palmer wrote: > > > >>> > This seems to break the rule that if A is equal to B and B is equal > >>> > to C then A is equal to C. > >>> > >>> I don't see why transitivity should apply to Python objects in general. > >> > >> Well, for numbers it surely would be a nice touch, wouldn't it. May be > >> the reason for Decimal to accept float arguments is that irrational > >> numbers or very long rational numbers cannot be converted to a Decimal > >> without rounding error, and Decimal doesn't want any part of it. Seems > >> pointless to me, though. > > > >Is 0.1 a very long number? Would you expect ``0.1 == Decimal('0.1')`` to > >be `True` or `False` given that 0.1 actually is > > > >In [98]: '%.50f' % 0.1 > >Out[98]: '0.10000000000000000555111512312578270211815834045410' > >? > > Actually, it's not. Your C run-time library is generating random digits > after it runs out of useful information (which is the first 16 or 17 > digits). 0.1 in an IEEE 784 double is this: > > 0.100000000000000088817841970012523233890533447265625 Not according to the decimal FAQ http://docs.python.org/lib/decimal-faq.html ------------------------------------------------------------ import math from decimal import * def floatToDecimal(f): "Convert a floating point number to a Decimal with no loss of information" # Transform (exactly) a float to a mantissa (0.5 <= abs(m) < 1.0) and an # exponent. Double the mantissa until it is an integer. Use the integer # mantissa and exponent to compute an equivalent Decimal. If this cannot # be done exactly, then retry with more precision. mantissa, exponent = math.frexp(f) while mantissa != int(mantissa): mantissa *= 2.0 exponent -= 1 mantissa = int(mantissa) oldcontext = getcontext() setcontext(Context(traps=[Inexact])) try: while True: try: return mantissa * Decimal(2) ** exponent except Inexact: getcontext().prec += 1 finally: setcontext(oldcontext) print "float(0.1) is", floatToDecimal(0.1) ------------------------------------------------------------ Prints this float(0.1) is 0.1000000000000000055511151231257827021181583404541015625 On my platform Python 2.5.2 (r252:60911, Aug 8 2008, 09:22:44), [GCC 4.3.1] on linux2 Linux 2.6.26-1-686 Intel(R) Core(TM)2 CPU T7200 -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gagsl-py2 at yahoo.com.ar Mon Sep 29 09:35:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 10:35:15 -0300 Subject: Python OOP question References: Message-ID: En Thu, 25 Sep 2008 11:45:21 -0300, k3xji escribi?: > Hi all, > > I am trying to develop a game-server in python. Design is as > following: > > - ConnectionManager - handling/distributing incoming connections > - IOManager - handling IO recv/send operations on sockets. > (inheritable) > - Socket - basic async socket object > - SocketServer - handling multiple socket object requests. > (inheritable) > - Options - holds the server options (inheritable) > > I want this code to be extensible as it can be. So I have developed it > like this. I f one is going to implement some new feature, all needs > to be done is to inherit IOManager or Server object to do it. > Inheritable objects are IOManager, SocketServer and Options. > > But there is some feeling about this design that it can be better. > Here is the main.py which I am using to execute the server: > > from Base.SocketServer import SocketServer > from testIOManager import testIOManager > from Base.Options import Options > from Base.ConnectionManager import ConnectionManager > > iomgr = testIOManager() > opts = Options() > > # calculate how many server objects to create > # according to the maximum allowed client count. > serverCnt = opts.MAX_CLIENT_COUNT / opts.MAX_CLIENT_COUNT_PER_SERVER > Servers = [] > for i in range(serverCnt): > server = Server(i) > Servers.append(server) > > > cmgr = ConnectionManager(Servers, iomgr, opts) > cmgr.start() > > With current design as server object is inheritable, I need to pass it > to ConnectionManager object. I just have a feeling that above design > is bad in the sense of readability. You may imitate how asyncore [1] handles channels: make the library contain a (global) list of servers; the Server (base) constructor adds itself to the list; and ConnectionManager uses that list if not explicitely supplied one. But I'm not sure it improves readability: there is no explicit link between the Servers you construct and the ConnectionManager, but the latter "magically" knows about all the formers. It's easier to manage, though. (I don't undersantd exactly why you insist in the inheritable part; isn't the same if it were not inheritable? Maybe I don't get your main concerns correctly...) -- Gabriel Genellina From harrrrpo at gmail.com Tue Sep 9 16:12:56 2008 From: harrrrpo at gmail.com (Mohamed Yousef) Date: Tue, 9 Sep 2008 22:12:56 +0200 Subject: Deflate with urllib2... In-Reply-To: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> Message-ID: <538050a90809091312u4072576fk3c45c533406b1d7d@mail.gmail.com> Try this http://www.paul.sladen.org/projects/pyflate/ 2008/9/9 Sam : > I'm using urllib2 and accepting gzip and deflate. > > It turns out that almost every site returns either normal text or > gzip. But I finally found one that returns deflate. > > Here's how I un-gzip: > compressedstream = StringIO.StringIO(data) > gzipper = gzip.GzipFile(fileobj=compressedstream) > data = gzipper.read() > > Un-gzipping works great! > > Here's how I un-deflate (inflate??) > data = zlib.decompress(data) > > Un-deflating doesn't work. I get "zlib.error: Error -3 while > decompressing data: incorrect header check" > > I'm using python 2.5.2. Can someone tell me exactly how to handle > deflated web pages? > > Thanks > > > -- > http://mail.python.org/mailman/listinfo/python-list > From robert.kern at gmail.com Tue Sep 23 20:09:44 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 19:09:44 -0500 Subject: Python is slow? In-Reply-To: References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> Message-ID: Robert Kern wrote: > J Peyret wrote: >> On Sep 23, 8:31 am, bearophileH... at lycos.com wrote: >> >> Guys, this looks like a great data structure/algo for something I am >> working on. >> >> But... where do I find some definitions of the original BK-tree idea? > > Uh, actually we're talking about kd-trees, not BK-trees. kd-trees are > for searching through point sets in a k-dimensional space. My apologies. I did not actually follow bearophile's link, and thought he was talking about kd-trees like Sturla was. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at holdenweb.com Tue Sep 30 08:39:36 2008 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 Sep 2008 08:39:36 -0400 Subject: What is not objects in Python? In-Reply-To: References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <48E21E08.9020808@holdenweb.com> Steven D'Aprano wrote: > On Mon, 29 Sep 2008 21:03:07 -0700, namekuseijin wrote: > >>> Why isn't len implemented as a str.len and list.len method instead of a >>> len(list) function? >> Because postfix notation sucks. The natural way of spelling is >> adjective+noun and verb+predicate. > > "Natural"? > > You mean phrases like "heir apparent" and "worst choice imaginable" are > unnatural? They are certainly far from normal usage, as my dog yellow would be certain to agree. > To say nothing of languages like Spanish, Albanian, Italian, > Cornish, Vietnamese, Hebrew... It's long been a convention in the Western programming world to pretend no other language than English and no other codes than ASCII exist. The fact that Python is beginning to come to terms with Unicode is a tribute to certain developers' persistence. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From sri_annauni at yahoo.co.in Sun Sep 14 10:57:20 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Sun, 14 Sep 2008 20:27:20 +0530 (IST) Subject: Is there any nice way to unpack a list of unknown size?? Message-ID: <238815.3778.qm@web7902.mail.in.yahoo.com> I want to do something like below: 1. first, second, third, *rest = foo ?2. for (a,b,c,*rest) in list_of_lists: Please suggest. Thanks, Srini Bring your gang together. Do your thing. Find your favourite Yahoo! group at http://in.promos.yahoo.com/groups/ From gagsl-py2 at yahoo.com.ar Fri Sep 5 18:22:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 19:22:09 -0300 Subject: Files application architecture References: <48C155E8.7050006@cines.fr> Message-ID: En Fri, 05 Sep 2008 12:53:12 -0300, Benjamin Watine escribi?: > I'm about to develop a small python application and I wonder how to > organize files in this application. > I'm familar to java, so I'm tempted to use the same convention : 1 file > per class and 1 folders per package. You don't *have* to artificially restrict yourself to one class per file. In Python it's common to place several related classes in the same module (i.e., file). You don't have to write so much boilerplate code as in Java, so classes tend to be smaller in size; you may even find classes with an empty body. > I know that packages doesn't exists in python, they are modules instead. Uh? Have you read the Python Tutorial? http://docs.python.org/tut/node8.html#SECTION008400000000000000000 > So, what are best practices for organizing files and folders in a small > python project ? > I've found PEP8 (http://www.python.org/dev/peps/pep-0008/) that gives a > lot of good hints on coding convention, but nothing about files > organization. A small application may consist of just a main entry point and some imported modules, all residing in the same directory. It might not require to define any package. Perhaps later, when some module grows too much, you may want to refactor it, creating a package. But try to keep simple things simple. -- Gabriel Genellina From patrickstinson.lists at gmail.com Fri Sep 19 19:40:37 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Fri, 19 Sep 2008 15:40:37 -0800 Subject: migrating processess to avoid the GIL Message-ID: <6214d7a20809191640q33df6cf7k23b288cee4f7277a@mail.gmail.com> I need to migrate calls to CPython to another process in my C++ app to get around the GIL. Does anyone know of a good way to do this on windows and Mac? All calls and callbacks can be blocking, I just need to share some data structures. Cheers From jvines at arl.army.mil Wed Sep 10 10:10:08 2008 From: jvines at arl.army.mil (John Vines (CISD/HPCD)) Date: Wed, 10 Sep 2008 10:10:08 -0400 Subject: [Fwd: Re: Python extension, where am I going wrong] Message-ID: <48C7D540.3000800@arl.army.mil> Yes spelling things correctly does help, got it thanks for the help. -------------- next part -------------- An embedded message was scrubbed... From: Fredrik Lundh Subject: Re: Python extension, where am I going wrong Date: Wed, 10 Sep 2008 15:46:54 +0200 Size: 4460 URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: jvines.vcf Type: text/x-vcard Size: 378 bytes Desc: not available URL: From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 3 10:50:43 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 16:50:43 +0200 Subject: properties setting each other In-Reply-To: References: Message-ID: <48bea3e4$0$9754$426a74cc@news.free.fr> mk a ?crit : > Hello everyone, > > I try to set two properties, "value" and "square" in the following code, > and arrange it in such way that setting one property also sets another > one and vice versa. But the code seems to get Python into infinite loop: > > >>> import math > >>> class Squared2(object): > > def __init__(self, val): > self._internalval=val > self.square=pow(self._internalval,2) the 'internal' prefix is already implied by the '_'. And your __init__ code is a useless duplication of fsetvalue, so just use the property and get rid of copy-pasted code. > def fgetvalue(self): > return self._internalval the '_' prefix already means 'internal'. The convention here would be to name the attribute '_value' (to make clear it's the implementation support for the 'value' property). Also, your property getter and setter should also be marked as implementation using the '_' prefix - they are implementation detail, not part of your class API. > def fsetvalue(self, val): > self._internalval=val > self.square=pow(self._internalval,2) > > value = property(fgetvalue, fsetvalue) > > def fgetsquare(self): > return self.square > def fsetsquare(self,s): > self.square = s Hem... Notice something here ? > self.value = math.sqrt(self.square) > > square = property(fgetsquare, fsetsquare) Your fsetsquare implementation is broken - it calls itself recursively. You have to use different names for the property and the 'implementation attribute' for the property. But even if you fix this, you'll have another infinite recursion between the two setters. The simplest solution : don't call one property from the other, do direct attribute access within the setters: import math class Squared2(object): def __init__(self, value): self.value=value def _fgetvalue(self): return self._value def _fsetvalue(self, value): self._value=value self._square=pow(value,2) value = property(_fgetvalue, _fsetvalue) def _fgetsquare(self): return self._square def _fsetsquare(self,square): self._square = square self._value = math.sqrt(square) square = property(_fgetsquare, _fsetsquare) From pavlovevidence at gmail.com Sat Sep 13 01:25:29 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 12 Sep 2008 22:25:29 -0700 (PDT) Subject: lacking follow-through References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> Message-ID: On Sep 12, 12:35?pm, Fredrik Lundh wrote: > Steve Holden wrote: > > The defence rests. > > can you please stop quoting that guy, so we don't have to killfile you > as well... Guy? Carl Banks From davidgshi at yahoo.co.uk Sun Sep 14 08:38:06 2008 From: davidgshi at yahoo.co.uk (David Shi) Date: Sun, 14 Sep 2008 12:38:06 +0000 (GMT) Subject: proven upload.py needed Message-ID: <155731.83210.qm@web26308.mail.ukl.yahoo.com> Dear All, ? I am working on a website development project.? I am looking for Python scripts for allowing end users to upload large zip data files and to get processed output datasets back to client machines. ? If there be better data compression and transmissn techniques available, I shall be interested. ? Thank you very much in advance for yours assistance. ? Sincerely, ? David -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 9 04:49:18 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 09 Sep 2008 10:49:18 +0200 Subject: Test if list contains another list In-Reply-To: References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> Message-ID: <48c6380b$0$17080$426a34cc@news.free.fr> Matimus a ?crit : > On Sep 8, 12:32 am, Bruno Desthuilliers > wrote: (snip) >> >>> set(a).issubset(set(b)) >> True >> >>> >> > Just to clarify, doing it using sets is not going to preserve order OR > number of elements that are the same. > > That is: > >>>> a = [1,1,2,3,4] >>>> b = [4,5,3,7,2,6,1] >>>> set(a).issubset(set(b)) > True > > This will return True if b contains at least on of each element found > in a. If the OP wanted to check that list `a` appeared in order > somewhere in list `b` then sets won't work. Indeed, and I should have mentionned this myself. Thanks for this reminder. From sjmachin at lexicon.net Tue Sep 2 20:36:07 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 17:36:07 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> Message-ID: <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> On Sep 3, 9:44 am, ssecorp wrote: > or why does this take so god damn long time? Because your code does so many god damn unnecessary things. Apart from the fact (as pointed out already by Robert) that you are needlessly finding the sizes (Y, X) that are already available: (1) You are executing a try block Y*X (approx) times instead of the Y+X +2 times it would take if you were to do preliminary probes to find Y and X (2) You are doing range(1, 1000) Y times instead of once [see question below] (3) You are doing the method lookup im.getpixel Y*X times instead of once (4) you are doing the method lookup row.append Y*X times instead of Y times > and if I run into an IndexError it break out of the inner loop right? > so having range up to 10000000 or 1000 wouldn't matter if biggest > working x is 800? > > def getPixels(fileName): > im = PIL.Image.open(fileName) > colors = [] > for y in range(1, 1000): Are you sure that both occurrences of range(1, 1000) shouldn't be range(1000)? > row = [] > for x in range(1, 1000): > try: > color = im.getpixel((x,y)) > row.append(color) > except IndexError: > break > colors.append(row) > return numpy.array(colors) and it appears that you haven't bothered to read the manual section on Image.getpixel: """ Note that this method is rather slow; if you need to process larger parts of an image from Python, you can either use pixel access objects (see load), or the getdata method. """ From sturlamolden at yahoo.no Thu Sep 25 05:25:36 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 25 Sep 2008 02:25:36 -0700 (PDT) Subject: The Python computer language References: Message-ID: On 25 Sep, 06:02, ROSEEE wrote: > http://pythoncomputer.blogspot.com I wonder where the usenet cancelbots have gone? From ldo at geek-central.gen.new_zealand Sun Sep 28 02:08:50 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 28 Sep 2008 19:08:50 +1300 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> Message-ID: In message , Aaron "Castironpi" Brady wrote: > I understand that formal proof systems, as well as automated > theorem provers, have been difficult to develop. The basic problem is: having proved that a program satisfies certain formally-specified criteria, how do you prove that those formal criteria specifications actually correspond to the original problem you were trying to solve? The proof just pushes the correctness problem back another level. From fredrik at pythonware.com Tue Sep 16 17:59:16 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Sep 2008 23:59:16 +0200 Subject: How do I add permanently to Pythons sys.path? In-Reply-To: <99c53e1a-a693-4f35-b937-d172c565077c@m36g2000hse.googlegroups.com> References: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> <99c53e1a-a693-4f35-b937-d172c565077c@m36g2000hse.googlegroups.com> Message-ID: cnb wrote: > no I can't... Python has supported packages since version 1.4 or so, so I'm pretty sure you can. From maric at aristote.info Mon Sep 15 07:12:54 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 13:12:54 +0200 Subject: Rebinding __setattr__ In-Reply-To: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> References: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> Message-ID: <200809151312.55946.maric@aristote.info> Le Monday 15 September 2008 01:06:08 Jan Schilleman, vous avez ?crit?: > Hi all, > > I am trying to redefine __setattr__. > > The base class is in a library (actually, it is > win32com.client.DispatchBaseClass) and I do not want to touch it. My > problem is exemplified below. To my surprise, __setattr__ and __str__ > behave differently; I can redefine __str__ and the inherited __str__ is > still the redefined one. But redefining __setattr__ on the base class does > not get inherited. In Base.__dict__ the __setattr__ is the one I expected, > but it is not called from B. > > What is the problem? Is __setattr__ cached somewhere [and not updated?]? > Yes, it doesn't work with classic classes, but do with new-style ones, I don't know if this an accepted behavior or not. Can't you use new-style classes ? >>>[2]: sys.version ...[2]: '2.5.2 (r252:60911, May 28 2008, 19:19:25) \n[GCC 4.2.4 (Debian 4.2.4-1)]' >>>[64]: class A : def __setattr__(self, name, value) : print "A", name ....: ....: >>>[67]: class B(A) : pass ....: >>>[68]: A().c, B().c = 1, 2 A c A c >>>[69]: A.__setattr__ = lambda s, n, v : sys.stdout.write("%s, %s, %s\n" % (s, n, v)) >>>[70]: A().c, B().c = 1, 2 <__main__.A instance at 0x2b3b41546290>, c, 1 A c >>>[71]: class A(object) : def __setattr__(self, name, value) : print "A", name ....: ....: >>>[74]: class B(A) : pass ....: >>>[75]: A().c, B().c = 1, 2 A c A c >>>[76]: A.__setattr__ = lambda s, n, v : sys.stdout.write("%s, %s, %s\n" % (s, n, v)) >>>[77]: >>>[78]: A().c, B().c = 1, 2 <__main__.A object at 0x2b3b45dfa350>, c, 1 <__main__.B object at 0x2b3b45dfa350>, c, 2 -- _____________ Maric Michaud From lixinyi.23 at gmail.com Wed Sep 24 20:10:07 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Wed, 24 Sep 2008 17:10:07 -0700 (PDT) Subject: PyRun_SimpleFile() crashes References: <26532f88-b70c-4b18-af4d-5176ec023f46@c65g2000hsa.googlegroups.com> Message-ID: <231b15f7-34d7-4ae7-9ef9-7244d2c70434@w1g2000prk.googlegroups.com> On 9?25?, ??1:05, "Aaron \"Castironpi\" Brady" wrote: > On Sep 24, 6:30 am, Nick Craig-Wood wrote: > > > > > lixinyi... at gmail.com wrote: > > > my code: > > > main.cpp > > > #include > > > > int main(int argc, char **argv) > > > { > > > Py_Initialize(); > > > > FILE *file_1 = fopen("a2l_reader.py","r+"); > > > PyRun_SimpleFile(file_1,"a2l_reader.py"); > > > > Py_Finalize(); > > > } > > > > compile under windows using MinGW: > > > g++ main.cpp libpython25.a -o a > > > > no error was found. But when I run a.exe the program just crashes. > > > > What should I do? > > > Run it under gdb (which should have come with MinGW). > > > Check that you actually opened the file, ie file_1 != 0. > > > This might be relevant > > > http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o... > > > -- > > Nick Craig-Wood --http://www.craig-wood.com/nick > > There's a workaround. > > filename = "Entire path of the python file"; > PyObject* PyFileObject = PyFile_FromString(filename, "r"); > PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename); > // decref PyFileObject > > http://mail.python.org/pipermail/python-list/2007-March/431725.htmlhttp://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567 Wow this one works fine for me. Thank you! From tjreedy at udel.edu Tue Sep 30 15:28:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 15:28:54 -0400 Subject: OS.SYSTEM ERROR !!! In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F38053D9855@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: > To All, > > > I have been attempting to execute the following program within the > Python environment: > > Myprogram.exe, which means this is an executable file!! > > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 > > The executable would execute perfectly. Because you execute it in the necessary directory. > However, when I would try to execute the following lines of source code > within a python script file: > > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") This does not execute it in the proper directory. os.getcwd() will tell you where you are -- mostly likely .../Pythonx.y. Try: os.chdir("C:/myprogramfolder/run") # / works fine, and without r prefix os.system("Myprogram.exe 1 1 acc 0") > The executable file would start to execute until it would print an error > stating that it cannot use a (.dat) file, which is located under the > following directory: > > C:\myprogramfolder\run\inputs\io\control.dat > > > I believe I may be missing something here that prevents the executable > file working within python from utilizing this (.dat). The printed > final error is the following: > > ERROR opening inputs/io/control.dat > > Does anyone know what that could be ?? That file does not exist in the Pythonx.y directory where the program starts ;-). tjr From almar.klein at gmail.com Thu Sep 18 10:13:59 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 18 Sep 2008 16:13:59 +0200 Subject: matplotlib in interactive mode locks when run from subprocess Message-ID: Hi, In wxpython, I made an interactive shell, which creates a remote python subprocess to do the interpreting. Communication is done via a pipe. The idea is that the python session is an actual process separate from the GUI, which has some advantages, like I can have multiple such shells in my application, and I can kill them without worrying that my wx app will crash. To do this I use the wx.Process class, which allows asynchronous communication with the remote process. This all works really, I will also launch wxpython apps. So I was quite happy, untill I tried doing some plotting with matplotlib (in TkAgg backend). The problem is that the process becomes unresponsive when I plot something (No prompt is written to the stdout/stderr). (more details below) I don't know much about creating subprocess and how they are different from a normal process. So can anyone offer some help as to what the problem might be? Thanks in advance, Almar To get to the details: - When I start a process with command "python -u -i" -- When interactive mode is off, the whole process becomes unresponsive when doing pylab.show() -- When interactive mode in on, on doing pylab.plot(), a figure appears, which I can zoom etc., but the process is now stuck, also after closing the figure - When I start a process with command "python -u -c 'import code;code.interact(readfunc=raw_input)'" (This is how Pype does it). -- When interactive mode is off, the figures show when doing pylab.show() and the process behaves as normal after closing the figure(s). -- When interactive mode in on, on doing pylab.plot(), a figure appears, but most of the time it is not drawn and emmediately unresponsive, just like the process itself. I have also tried an asynchronous Popen recipe by Joshiah Carlson I found on activestate. And I made my own process class using win32process.CreateProcess. Both alternatives to wx.Process resulted in the same sympoms. Oh, and I run windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From roy at panix.com Tue Sep 30 00:41:57 2008 From: roy at panix.com (Roy Smith) Date: Tue, 30 Sep 2008 00:41:57 -0400 Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <00f15dd2$0$20617$c3e8da3@news.astraweb.com> Message-ID: In article , Terry Reedy wrote: > It should be both, just as + is addition for numbers and concatenation > for sequences. Actually, the math folks would argue that using + for concatenation is wrong, since by normal math rules, + denotes a commutative operation. Of course, the math folks think that i^2 = -1, so what do they know? All right-thinking people know that j^2 = -1. From karentataka at gmail.com Sun Sep 21 00:09:47 2008 From: karentataka at gmail.com (karentataka at gmail.com) Date: Sat, 20 Sep 2008 21:09:47 -0700 (PDT) Subject: Quick & Secured Pharmacy Online. hr3tn Message-ID: <85f191e6-899a-472a-8007-8f1f4f400e2b@j22g2000hsf.googlegroups.com> Start saving, best online pharmacy here http://gjlabeh.cuchezfarg.com/?cdfikmabehxwvrsygzchcmjl From rcdailey at gmail.com Sat Sep 6 12:33:10 2008 From: rcdailey at gmail.com (Robert Dailey) Date: Sat, 6 Sep 2008 11:33:10 -0500 Subject: Calling global functions from a class? Message-ID: <496954360809060933w2b736b57x7925510140e7a3e@mail.gmail.com> HI, I have the following python script: def __normalizePath( path ): return osp.abspath( osp.normpath( path ) ) class AbsolutePath: def __init__( self, root="" ): _root = __normalizePath( root ) When I create an AbsolutePath object, I get the following error: NameError: global name '_AbsolutePath__normalizePath' is not defined Is there a reason for this? How can I make this work? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 10:58:51 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 16:58:51 +0200 Subject: Pyflix, confused about super() call In-Reply-To: References: Message-ID: <48d90423$0$3170$426a74cc@news.free.fr> process a ?crit : > Anyone using Pyflix for the Netflix prize. > > How can it call super to itself in its init-method? > You mean : > class MovieAverage(Algorithm): > def __init__(self, training_set): > self._movie_averages = {} this line ? super(MovieAverage,self).__init__(training_set) If that's what confuse you, I think you really should read the FineManual(tm) instead of assuming Python is language X or Y. From gminick at bzt.bzt Wed Sep 10 13:37:27 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 17:37:27 +0000 (UTC) Subject: md5 differences References: Message-ID: On Wed, 10 Sep 2008 19:12:28 +0200, Python wrote: > Arno at Computer:~% echo "test" > test.txt > > Arno at Computer:~% md5 test.txt > MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 > >>> import md5 > >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() > '90364ed45b452d43378629c20543a81d' Works for me: >>> import md5 >>> f = open('test.txt').read() >>> md5.new(f).hexdigest() 'd8e8fca2dc0f896fd7cb4cb0031ba249' >>> IOW, don't pass the path to the file to md5.new, but the contents of this file. The strange thing is that >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bdesth.quelquechose at free.quelquepart.fr Tue Sep 23 13:17:43 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 19:17:43 +0200 Subject: Detecting the first time I open/append to a file In-Reply-To: References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> Message-ID: <48d940a3$0$3738$426a74cc@news.free.fr> Sean Davis a ?crit : > On Sep 23, 2:02 pm, tkp... at hotmail.com wrote: >> I have a simulation that runs many times with different parameters, >> and I want to aggregate the output into a single file with one rub: I >> want a header to be written only the first time. My program looks a >> bit like this: >> >> def main(): >> for param in range(10): >> simulate(param) >> >> def simulate(parameter): >> 'Lots of code followed by: >> with open(summaryFn, 'ab') as f: >> writer = csv.writer(f) >> writer.writerow(header) >> writer.writerow(Sigma) >> >> If I can sense that the file is being created in the first iteration, >> I can then use an if statement to decide whether or not I need to >> write the header. Question: how can I tell if the file is being >> created or if this its the first iteration? It's unrealistic to test >> the value of the parameter as in the real problem, there are many >> nested loops in main, and the bounds on the loop indices may change. > > You could use os.path.exists() to check if the file is there. > However, the file could have been left over from a previous execution, > etc. What might make sense is to open the file only once, store the > file handle, and write to that throughout the execution. s/file handle/file object/ This being said, I can only second Sean's advice. And anyway, computing something and writing the result(s) of this computation to the file are orthogonal and mostly unrelated responsabilities, so they shouldn't be handled by the same function. Here's a possible reorganisation of your code: def simulate(parameter): # lots of code followed by return sigma def main(): # presumably some other code here with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) for param in range(10): writer.writerow(simulate(param)) From jjkk73 at gmail.com Wed Sep 3 05:06:38 2008 From: jjkk73 at gmail.com (jorma kala) Date: Wed, 3 Sep 2008 11:06:38 +0200 Subject: Using httplib to access servlets on tomcat server Message-ID: Hi, I'm trying unsuccesfully to use the httplib library to execute servlets on a local tomcat server. If I type the following http adress on my browser http://localhost:8080/test/Serv1 the servlet works fine. But if I try to access it with the following python code: conn = httplib.HTTPConnection("http://localhost:8080") conn.request("GET", "/test/Serv1") r1 = conn.getresponse() I get the following error: socket.gaierror: (11001, 'getaddrinfo failed') Do you know what I do wrong? Thank you very much. (The complete traceback is: Traceback (most recent call last): File "http1.py", line 130, in getTomcat1() File "http1.py", line 46, in getTomcat1 conn.request("GET", "/test/Serv1") File "C:\Python25\lib\httplib.py", line 862, in request self._send_request(method, url, body, headers) File "C:\Python25\lib\httplib.py", line 885, in _send_request self.endheaders() File "C:\Python25\lib\httplib.py", line 856, in endheaders self._send_output() File "C:\Python25\lib\httplib.py", line 728, in _send_output self.send(msg) File "C:\Python25\lib\httplib.py", line 695, in send self.connect() File "C:\Python25\lib\httplib.py", line 663, in connect socket.SOCK_STREAM): socket.gaierror: (11001, 'getaddrinfo failed') -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Sep 25 16:32:22 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:32:22 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: References: Message-ID: <6k2aqqF5p185U1@mid.uni-berlin.de> Dmitry S. Makovey schrieb: > Scott Sharkey wrote: >> Any insight into the best way to have a consistent, repeatable, >> controllable development and production environment would be much >> appreciated. > > you have just described OS package building ;) > > I can't speak for everybody, but supporting multiple platforms (PHP, Perl, > Python, Java) we found that the only way to stay consistent is to use OS > native packaging tools (in your case apt and .deb ) and if you're missing > something - roll your own package. After a while you accumulate plenty of > templates to chose from when you need yet-another-library not available > upstream in your preferred package format. Remember that some python tools > might depend on non-python packages, so the only way to make sure all that > is consistent across environment - use unified package management. That this is a desirable goal can't be argued against. Yet two big hurdles make it often impractical to be dogmatic about that: - different OS. I for one don't know about a package management tool for windows. And while our servers use Linux (and I as developer as well), all the rest of our people use windows. No use telling them to apt-get instal python-imaging. - keeping track of recent developments. In the Python webframework world for example (which the OP seems to be working with), things move fast. Or extremly slow, regarding releases. Take Django - until 2 month ago, there hasn't been a stable release for *years*. Virtually everybody was working with trunk. And given the rather strict packaging policies of debian and consorts, you'd be cut off of recent developments as well as of bugfixes. Diez From exarkun at divmod.com Mon Sep 8 15:09:38 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 8 Sep 2008 15:09:38 -0400 Subject: exit() In-Reply-To: Message-ID: <20080908190938.29191.2011689276.divmod.quotient.23218@ohm> On Mon, 08 Sep 2008 21:03:48 +0200, Christian Heimes wrote: >Gary Robinson wrote: >>In Python 2.5.2, I notice that, in the interpreter or in a script, I can >>exit with: >> >> exit() > >The exit callable is defined in the site module. Check out site.py! It >shouldn't be used in code. It was added to help newbies to 'escape' from an >interactive Python shell. > It works. Why shouldn't it be used? Jean-Paul From Magnus.Moraberg at gmail.com Fri Sep 12 07:26:16 2008 From: Magnus.Moraberg at gmail.com (Magnus.Moraberg at gmail.com) Date: Fri, 12 Sep 2008 04:26:16 -0700 (PDT) Subject: Matching horizontal white space Message-ID: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> multipleSpaces = re.compile(u'\\h+') importantTextString = '\n \n \n \t\t ' importantTextString = multipleSpaces.sub("M", importantTextString) I would have expected consecutive spaces and tabs to be replaced by M but nothing is being replaced. If I try the following, then I'm left only with M, as expected - multipleSpaces = re.compile(u'\\s+') # both vertical and horizontal importantTextString = '\n \n \n \t\t ' importantTextString = multipleSpaces.sub("M", importantTextString) What I eventually wish to do is have only single spaces in my text and to only have single carriage returns - " one two three four five six " becoming - "one two three four five six " Thanks, Barry From martin at v.loewis.de Fri Sep 26 17:13:49 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 26 Sep 2008 23:13:49 +0200 Subject: Quick sort implementation in python In-Reply-To: <4da8f8b2-0216-433c-89a6-39d7ab037e84@l42g2000hsc.googlegroups.com> References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> <48dbf8f9$0$21266$9b622d9e@news.freenet.de> <4da8f8b2-0216-433c-89a6-39d7ab037e84@l42g2000hsc.googlegroups.com> Message-ID: <48DD508D.7040300@v.loewis.de> >> Can you please explain how you did that in C? IOW, how did you do >> the partition function (template) in case you don't have random >> access to the collection? >> > > Why exactly do you need random access for partition function? This is a counter-question, not an answer. Let me ask again: How did you do that in C++? > Do can > swap 2 nodes of a linked list without random access (you can swap the > pointers or just swap the node values) and you traverse the list till > you reach it's tail. In Python, there is no standard iterator that allows you to modify the underlying collection. There is the iter() function/type, but it only allows read access. Regards, Martin From almar.klein at gmail.com Tue Sep 2 03:52:09 2008 From: almar.klein at gmail.com (Almar Klein) Date: Tue, 2 Sep 2008 09:52:09 +0200 Subject: python 3k, when will it be mainstream? Message-ID: Hi, I read that python 3k is now in its final beta version. I was wondering when we can expect the major packages to make a 3.0 branch. I am myself quite new to python, and would like to make the transition as soon as possible, simply because it would save me porting code later, and I can focus on learning just the python 3.0. However, I am a former Matlab user and depend on packages like numpy, scipy, matplotlib. wxPython I use as well. So to get to the point: When can we expect these (and other) packages to release their python 3k versions? And when will the majority of people make the transition to py3k? I am looking forward to your thoughts on this, Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From half.italian at gmail.com Fri Sep 26 01:31:59 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 25 Sep 2008 22:31:59 -0700 (PDT) Subject: Writing a well-behaved daemon References: <874p43wl2m.fsf@benfinney.id.au> Message-ID: On Sep 25, 10:08?pm, Ben Finney wrote: > Howdy all, > > Writing a Python program to become a Unix daemon is relatively > well-documented: there's a recipe for detaching the process and > running in its own process group. However, there's much more to a Unix > daemon than simply detaching. At a minimum, a well-behaved Unix daemon > must at least: > > * Detach the process into its own process group > > * Close stdin, redirect stdout and stderr to a null device > > * Handle its own PID file: refuse to start if the PID file already > ? exists, write the PID file on startup otherwise, and remove the PID > ? file on termination > > * Revoke setuid and setgid privileges, which are strongly deprecated > ? these days > > * Handle interrupts, cleaning up the process and PID file as necessary > > * (possible others) > > There are also many other commonly-expected tasks that well-behaved > Unix daemons perform (drop privileges to a nominated non-root user and > group after daemonising, redirect output to syslog instead, operate in > a chroot jail, respawn when terminated, etc.). > > All of this stuff has been done numerous times before, and the basics > are mostly agreed upon. Yet all of these are tricky to implement > correctly, and tedious to re-implement in every program intended to > run as a daemon. > > The 'daemon' program covers all > these, and allows an arbitrary process to be started as a well-behaved > Unix daemon process. It's not a good assumption that this program is > installed on an arbitrary system though, and it seems excessive to ask > the recipient of one's program to get a third-party program just in > order to make a daemon process. > > I'd love to be able to have something similar for Python programs, > e.g. a 'become_well_behaved_daemon()' function that implements all the > above and perhaps takes optional arguments for the optional features. > > My searches for such functionality haven't borne much fruit though. > Apart from scattered recipes, none of which cover all the essentials > (let alone the optional features) of 'daemon', I can't find anything > that could be relied upon. This is surprising, since I'd expect this > in Python's standard library. > > Can anyone point me to the equivalent of the 'daemon' program in the > form of a well-tested Python library? > > -- > ?\ ? ? ?Tis more blessed to give than to receive; for example, wedding | > ? `\ ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?presents.? ?Henry L. Mencken | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > Ben Finney http://code.activestate.com/recipes/66012/ I actually use a brew of the original recipe combined with several of the great comments. The commenters add alot of the functionality that you are looking for. It works very well on most counts, but doesn't handle being killed well. The daemons often last for a few weeks to a month before something unexpected kills them off. If I was more careful, I think they could live much longer. Looks like somebody did the same thing I did and posted it. http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemon.py ~Sean From stef.mientki at gmail.com Thu Sep 4 17:22:50 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 04 Sep 2008 23:22:50 +0200 Subject: pdb bug and questions Message-ID: <48C051AA.5090002@gmail.com> hello, I'm trying to embed a debugger into an editor. I'm only interested in high level debugging. The first question is what debugger is the best for my purpose ? (pdb, pydb, rpdb2, smart debugger, extended debugger ? Second question, in none of the above debuggers (except rpdb2), I can find a "break now", so it seems impossible to me to detect unlimited while loops ? For the moment I started with pdb, because most of the debuggers seems to be an extension on pdb. When I launch the debugger ( winXP, Python 2.5) from with my editor python -u -m pdb D:\\Data\\test_IDE.py I get this error IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') NOTICE 1 backslash ----------------------------------^ If I launch the debugger with python -u -m pdb D:/Data/test_IDE.py It runs fine. This looks like a bug to me. What's the best way to report these kind of bugs ? Although I mostly use os.path.join to be OS independent, these kind of bugs give me the impression, that I can better do the join myself and always use forward slashes. Is this a valid conclusion ? thanks, Stef Mientki From steve at REMOVE-THIS-cybersource.com.au Sun Sep 7 00:05:40 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 07 Sep 2008 04:05:40 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> Message-ID: <00d34d6c$0$30713$c3e8da3@news.astraweb.com> On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote: [...] >> They could have decided that sum must take at least two arguments, >> because addition requires two arguments and it's meaningless to talk >> about adding a single number without talking about adding it to >> something else. But they didn't. > > Ok. But the problem is they DID in SQL: x + Null = Null. Sheesh. That's not a problem, because Python is not trying to be a dialect of SQL. If you want a NULL object, then there are recipes on the web that will give you one. Then all you need to do is call sum(alist or [NULL]) and it will give you the behaviour you want. [...] > Here's a real world example (no ivory tower stuff): > > An oil refinery client has just excavated a big pile of dirt to lay a > new pipeline. [snip details] > Can't I just use a sum of 0 to tell me when data is missing? No, because > in some cases the reporting limit of undetected compounds is set to 0. You can't use a sum of 0 to indicate when data is missing, full stop. The data may require 15 tests when only 3 have actually been done: sum([1.2e-7, 9.34e-6, 2.06e-8]) Missing data and a non-zero sum. How should sum() deal with that? The answer is that sum() can't deal with that. You can't expect sum() to read your mind, know that there should be 15 items instead of 3, and raise an error. So why do you expect sum() to read your mind and magically know that zero items is an error, especially when for many applications it is NOT an error? The behaviour you want for this specific application is unwanted, unnecessary and even undesirable for many other applications. The solution is for *you* to write application-specific code to do what your application needs, instead of relying on a general purpose function magically knowing what you want. -- Steven From Ripter001 at gmail.com Wed Sep 3 23:04:22 2008 From: Ripter001 at gmail.com (Ripter) Date: Wed, 3 Sep 2008 20:04:22 -0700 (PDT) Subject: Help Understanding weakref (lazyloader) References: Message-ID: <98906e65-e4a6-4003-9cec-98e8c6fb5726@x16g2000prn.googlegroups.com> On Sep 3, 10:46?pm, Ripter wrote: > I found this script athttp://www.pygame.org/wiki/LazyImageLoading?parent=CookBook > And I can't quite figure out how it works. I was wondering if someone > could clarify it for me. > The Code is: > > import pygame > import weakref > > class ResourceController(object): > ? ? def __init__(self, loader): > ? ? ? ? self.__dict__.update(dict( > ? ? ? ? ? ? names = {}, > ? ? ? ? ? ? cache = weakref.WeakValueDictionary(), > ? ? ? ? ? ? loader = loader > ? ? ? ? )) > > ? ? def __setattr__(self, name, value): > ? ? ? ? self.names[name] = value > > ? ? def __getattr__(self, name): > ? ? ? ? try: > ? ? ? ? ? ? img = self.cache[name] > ? ? ? ? except KeyError: > ? ? ? ? ? ? img = self.loader(self.names[name]) > ? ? ? ? ? ? self.cache[name] = img > ? ? ? ? return img > > class ImageController(ResourceController): > ? ? def __init__(self): > ? ? ? ? ResourceController.__init__(self, pygame.image.load) > > My question is why does the __setattr__ set the value to > self.names[name] instead of self.cache[name]? I feel stupid, I figured it out. (Don't program while watching Back to the Future) The reason would be the 'lazy' part. self.names holds the file name, and when you get the property back (__getattr__) it checks to see if it already got the value or not, and uses the name to get the value if it hasn't already. Duh. Sorry. From sjmachin at lexicon.net Mon Sep 8 05:31:30 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Sep 2008 02:31:30 -0700 (PDT) Subject: String to hexadecimal conversion References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Message-ID: <14aa61b1-fb8c-44c4-bbf2-d8d2f92006e9@p10g2000prf.googlegroups.com> On Sep 8, 7:05?pm, Praveena P wrote: > Hi folks, > > I am new to Python... so am not too sure about how the type conversion > works. > > I have to read a file that contains hexadecimal data and use the data > further to do some arithmetic calculations. > A sample of the input is : 00000000000020E0000032F800000000400022005E > The problem I am facing is this: > I am using f.read(2) to read a byte at a time, but the data that is > read is a string rather than a number. So it kind of hampers any > arithmetic operations I perform on this data... > > Could you please suggest some method I could use for this? *IF* all the data consists of unsigned 8-bit integers a_byte = f.read(2) uint8 = int(a_byte, 16) But I doubt it and that would be rather slow anyway. If your data is homogenous, look at the array module. Otherwise, once you've worked out how to break your file down into records, and what the layout of each record is, you'll need the struct module. HTH, John From brtzsnr at gmail.com Mon Sep 29 10:56:06 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Mon, 29 Sep 2008 07:56:06 -0700 (PDT) Subject: blocking all threads Message-ID: <1d161e02-4b39-462c-a485-d93eb0423e9b@v13g2000pro.googlegroups.com> how can I block all threads for a specific amount of time? (i need to sleep whole process for testing purposes). i thought of accessing GIL and sleep for some amount of time, but I don't know how to do this and whether GIL is recursive. From tjreedy at udel.edu Wed Sep 17 15:59:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 Sep 2008 15:59:28 -0400 Subject: Python and Open Office In-Reply-To: <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Hartmut Goebel wrote: > Terry Reedy schrieb: > >> One way to learn the meaning of some of the numerous attributes and >> values is to create a file with the wanted features with OOo, save, >> unzip, and examine the xml to see which tags are used for which features. > > The API docs are a bit hidden on the webpage. Here is the link: > I wrote my comment *after* looking at the above, which I found easily enough. After 7 pages of (helpful) explanatory text, there follow 88 pages with hundreds of entries like this: 5.13.30 style.RubyProperties Requires the following attributes: No attribute is required. Allows the following attributes: rubyalign, rubyposition. These elements contain style.RubyProperties: style.DefaultStyle, style.Style. The following elements occur in style.RubyProperties: No element is allowed. which are translated to a more readable form from the Relax-NG schema (formal specs) in the standard. But I have no idea what a Ruby property is in this context. It would be much like reading the grammar entries in the Python Reference without the explanatory text that follows. > Additionally teh ODF sepcs may help: > v1.0 is the adopted international (ISO/IEC) standard. I did not notice whether odfpy supports the 1.1 extensitons, but since it does appear that OOo now uses them, I will presume so. This does help. It has more explanatory material. "5.4 Ruby A ruby is additional text that is displayed above or below some base text. The purpose of ruby is to annotate the base text or provide information about its pronunciation. tjr From nick at craig-wood.com Tue Sep 30 17:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 30 Sep 2008 16:30:05 -0500 Subject: Advice for a replacement for plone. References: Message-ID: Ken Seehart wrote: > I want a new python based CMS. ... One that won't keep me up all night .... > > I've been fooling around with zope and plone, and I like plone for some > things, such as a repository for online project documentation. However > for general-purpose web development it is too monolithic. Is there > anything out there with the following properties? > > 0. Web page being developed is a typical small business home page (i.e. > not a newspaper or a blog). > 1. Page owner can edit pages on line with no expertise (plone does great > here). > 2. Main page does not look plone-like. For an example of a main page > that does not look plone-like, see http://www.arbitrary.com/ Note the > lack of CMS style navigation widgets. > 3. Item 2 should be reachable with nearly no effort (plone fails utterly > here). > 4. Target viewer (not the owner), should /not/ see something that looks > at all like a CMS system, but rather see exactly what the page owner > wants the page to look like. > 5. Page owner should be able to view and navigate the tree of contents, > and select pages to edit with a wysiwyg editor (plone does great here)... > 6. ... But the target viewer should not see this tree. See items 2 and 4. > 7. Potential to add python scripted pages of various kinds. > > There are a couple different design approaches to making a > development environment. You can let the developer start with nothing, > and provide the developer with tools to create something (e.g. zope, > most plain text editors), or you can start with a finished result and > let the developer rip out and discard what is not desired (e.g. plone). > I often prefer to start with nothing. It's a natural starting point. > Note that systems that are based on starting with nothing can provide > the benefits of starting with something by providing templates and such. > > > I would love to see a system that would give me an editable Hello World > page in under 5 minutes. Hello World would be a page consisting of > nothing but the words "hello world" (no tools, no navigation bar, and > certainly no CMS navigation stuff) in a url such as > www.myhelloworldwebsite.com/hello and a different url to edit the page, > such as www.myhelloworldwebsite.com/hello/edit or > www.mywebsite.com/edit/hello Django + flatpages maybe? Coming from the starting from nothing approach. There are links to some sites built with it in the docs below. http://docs.djangoproject.com/en/dev/ref/contrib/flatpages/ A bit more of a learning curve but you'll definitely be in charge. Somebody used to Django could set up a flatpages site in 5 minutes probably! It will take you a couple of hours the first time though. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gagsl-py2 at yahoo.com.ar Thu Sep 18 22:12:22 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Sep 2008 23:12:22 -0300 Subject: Do HTTPError objects always have a read method? References: Message-ID: En Wed, 17 Sep 2008 22:48:27 -0300, Steven D'Aprano escribi?: > I understood that HTTPError objects always have a read method, so they > can be treated as if they were a webpage. E.g. something like this > simplified snippet: > > > address = 'http://www.yahoo.com/spamspamspamspamspam' > try: > conn = urllib2.urlopen(address) > except urllib2.HTTPError, e: > conn = e > print conn.read() # Print the requested page, or the error page. > > > > But in the source code to urllib2 (Python 2.5): > > > class HTTPError(URLError, addinfourl): > """Raised when HTTP error occurs, but also acts like non-error > return""" > __super_init = addinfourl.__init__ > > def __init__(self, url, code, msg, hdrs, fp): > self.code = code > self.msg = msg > self.hdrs = hdrs > self.fp = fp > self.filename = url > # The addinfourl classes depend on fp being a valid file > # object. In some cases, the HTTPError may not have a valid > # file object. If this happens, the simplest workaround is to > # not initialize the base classes. > if fp is not None: > self.__super_init(fp, hdrs, url) > > That tells me that HTTPError objects aren't guaranteed to include a file- > like interface. That makes me unhappy. > > Under what circumstances do HTTPError objects not have a valid file > object? How common is this? Does anyone have an example of a URL that > fails in that fashion? Well, there is at least one case (AbstractDigestAuthHandler at line 864 in urllib2.py) where HTTPError is raised explicitely with fp=None. It's not a common case, I think. If you rely on the exception having a read() method, add it a fake one yourself: try: ... except urllib2.HTTPError, e: if not hasattr(e, 'read'): e.read = e.readline = lambda self: '' # or perhaps e.msg conn = e -- Gabriel Genellina From default at defaulter.net Sat Sep 27 21:38:04 2008 From: default at defaulter.net (default) Date: Sat, 27 Sep 2008 21:38:04 -0400 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> Message-ID: <7qmtd4hc52o84pksc6tni0pmgnfvpvf08m@4ax.com> On Sat, 27 Sep 2008 23:12:59 +0000 (UTC), Cydrome Leader wrote: >In rec.crafts.metalworking Jim Thompson wrote: >> >> On Sat, 27 Sep 2008 18:47:16 -0400, default >> wrote: >> >>>On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko >>> wrote: >>> >>>>Hello, this is Milenko Stojadinovic from town Banjaluka, >>>>Bosnia and Herzegovina, also known as Cvrcko >>>>Does anyone know of any bars in town where I can >>>>swallow a bucket of cum? It can be either dog, >>>>horse or human cum. Also, does anyone know of >>>>any sex bars where people will shit in your mouth? >>>>I also like eating shit. >>> >>>Come to the US and park your mouth in front of George Bush - all the >>>Bshit you can eat - and it keeps on coming! >>> >>>I have a buddy in Bosna - he's normal. >> >> Now you know why I blanket kill-file googlegroups. > >So you and everybody can talk about them nonstop? If you mean Google Groups the condemnation is justified. Who is "them?" Real people do occasionally wander in to GG - or those without news servers - or without understanding of Usenet. Basically, in the engineering groups (in particular) outsiders are welcome. Engineers are smart, creative and tolerant as a general rule. Lighten up. Who are you defending? and Who goes into Usenet with a thin skin? Expect ridicule, expect condemnation - "water off a duck's back." You may think your viewpoint is the only one, the right one, the valid one - but a few million others may disagree. And you ain't started to deal with culture shock - some countries place emphasis on diplomacy _ you know the "how are you?" stuff, others don't, and seem very cold. Adapt. -- ----== Posted via Pronews.Com - Unlimited-Unrestricted-Secure Usenet News==---- http://www.pronews.com The #1 Newsgroup Service in the World! >100,000 Newsgroups ---= - Total Privacy via Encryption =--- From bdesth.quelquechose at free.quelquepart.fr Thu Sep 25 14:14:26 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 25 Sep 2008 20:14:26 +0200 Subject: Quick sort implementation in python In-Reply-To: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: <48dbf0ed$0$16897$426a74cc@news.free.fr> Alex Snast a ?crit : > Hi guys, I've been learning python in the past week and tried to > implement a q.sort algorithm in python Is that for learning purpose ? Else, it's just a waste of time... From ireborin at delete.this.gmail.com Tue Sep 30 12:11:25 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 18:11:25 +0200 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: On 30 Sep 2008 15:31:59 GMT, Peter Pearson wrote: > >Since you're coming from the FORTRAN world (thank you for >that stroll down Memory Lane), you might be doing scientific >computations, and so might be interested in the SciPy >package (Google scipy), which gives you arrays and matrices. >Don't expect to be able to use it without learning some Python, >though. Actually, no (regarding memory lane :-). I'm helping a friend to translate some of my old routines to python so he can use them in his programs. I'm still using fortran84, and mean to continue doing so as long as something better doesn't come along. But as I said, got a job that't got to be done, so I'm trying to figure out how to do array operations as easily as possible in python, which are necessary for all my calculations. Best regards Ivan From zhouyangpku at gmail.com Mon Sep 1 00:43:43 2008 From: zhouyangpku at gmail.com (zhouyangpku at gmail.com) Date: Sun, 31 Aug 2008 21:43:43 -0700 (PDT) Subject: Installing Python 2.5.2: 'make' fails in posixmodule.c Message-ID: <18f40e8b-4488-40a5-a831-3388ece2300f@v16g2000prc.googlegroups.com> Dear friends: I'm trying to install python on irix 6, the lab server. It fail at ' make ' procedure for Modules/posixmodule.c. I've just configured the prefix for my own path and no other option changed. make clean didn't help. Here it is: gcc -c -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE - DPYTHONPATH='":plat-irix6:lib-tk"' \ -DPREFIX='"/user_data2/yzhou/local"' \ -DEXEC_PREFIX='"/user_data2/yzhou/local"' \ -DVERSION='"2.5"' \ -DVPATH='""' \ -o Modules/getpath.o ./Modules/getpath.c gcc -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- prototypes -I. -IInclude -I./Include -DPy_BUILD_CORE -c ./Modules/ posixmodule.c -o Modules/posixmodule.o Modules/posixmodule.c: In function `posix_listdir': Modules/posixmodule.c:2162: `DIR' undeclared (first use in this function) Modules/posixmodule.c:2162: (Each undeclared identifier is reported only once Modules/posixmodule.c:2162: for each function it appears in.) Modules/posixmodule.c:2162: `dirp' undeclared (first use in this function) Modules/posixmodule.c:2173: warning: implicit declaration of function `opendir' Modules/posixmodule.c:2177: warning: implicit declaration of function `closedir' Modules/posixmodule.c:2183: warning: implicit declaration of function `readdir' Modules/posixmodule.c:2183: warning: assignment makes pointer from integer without a cast Modules/posixmodule.c:2187: dereferencing pointer to incomplete type Modules/posixmodule.c:2188: dereferencing pointer to incomplete type Modules/posixmodule.c:2189: dereferencing pointer to incomplete type Modules/posixmodule.c:2189: dereferencing pointer to incomplete type Modules/posixmodule.c:2191: dereferencing pointer to incomplete type Modules/posixmodule.c:2191: dereferencing pointer to incomplete type In file included from /usr/include/stropts.h:38, from Modules/posixmodule.c:3497: /usr/include/sys/stropts.h: At top level: /usr/include/sys/stropts.h:237: parse error before "t_uscalar_t" /usr/include/sys/stropts.h:261: parse error before "t_uscalar_t" /usr/include/sys/stropts.h:267: parse error before '}' token Modules/posixmodule.c: In function `posix_seteuid': Modules/posixmodule.c:5362: warning: implicit declaration of function `seteuid' Modules/posixmodule.c: In function `posix_setegid': Modules/posixmodule.c:5382: warning: implicit declaration of function `setegid' *** Error code 1 (bu21) From duncan.booth at invalid.invalid Tue Sep 16 04:55:36 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Sep 2008 08:55:36 GMT Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: "Chris Rebert" wrote: > On Tue, Sep 16, 2008 at 1:20 AM, Armin wrote: >> [1,2,3,4,7].append(c) -> Is this a valid expression? > > Literally, no, because you can't call methods on literals. Rubbish. There is no restriction about calling methods on literals. That expression is perfectly valid but has no practical use that I can see. There is a syntax gotcha which you may have been thinking of: to call a method on an integer literal (or indeed to access any attribute) you have to use whitespace between the literal and the dot otherwise you have a float literal and a syntax error. >>> 5 .__hex__() '0x5' The only relatively common use I can think of where you might want to call a method directly on a literal is to produce a list of strings while being lazy about the typing: COLOURS = "red green blue pink yellow".split() versus COLOURS = ["red", "green", "blue", "pink", "yellow"] -- Duncan Booth http://kupuguy.blogspot.com From bearophileHUGS at lycos.com Thu Sep 18 19:20:20 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 18 Sep 2008 16:20:20 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <6d9c1b56-1322-4062-94c4-dd1388421abc@z66g2000hsc.googlegroups.com> Bruno Desthuilliers: > def doubles9(): > ... > SN = [] > sn_append = SN.append Few more: import psyco def doubles10(): dup = set() SN = [] for item in IN: c = item.coordinates if c in dup: SN.append(item) else: dup.add(c) return SN psyco.bind(doubles10) from collections import deque def doubles11(): dup = set() dup_add = dup.add SN = deque() sn_append = SN.append for item in IN: c = item.coordinates if c in dup: sn_append(item) else: dup_add(c) return SN def doubles12(): dup = set() SN = deque() for item in IN: c = item.coordinates if c in dup: SN.append(item) else: dup.add(c) return SN psyco.bind(doubles12) Timings: doubles00 : 0.522365288653 doubles01 : 0.247219812198 doubles02 : 0.237889823898 doubles03 : 0.238638921389 doubles04 : 0.23821698217 doubles05 : 0.177042495425 doubles06 : 0.13166199162 doubles08 : 0.00569725197252 doubles09 : 0.00418566685667 doubles10 : 0.00192086920869 doubles11 : 0.00403324533245 doubles12 : 0.00184026840268 Hopefully that's fast enough :-) Bye, bearophile From showellshowell at gmail.com Sun Sep 14 21:50:22 2008 From: showellshowell at gmail.com (showellshowell at gmail.com) Date: Sun, 14 Sep 2008 18:50:22 -0700 (PDT) Subject: "Best" way to "drive" a Python program step by step. References: Message-ID: <0c203edf-8036-4356-83e4-60a575482a1b@b30g2000prf.googlegroups.com> On Sep 14, 5:41?pm, Andr? wrote: > Hi everyone, > > I'd be interested in hearing suggestions as to the "best" way to drive > a Python program step by step from another application. > Andre, If you want a Javascript program to render the results of a "syncrhronouse" Python program in "real time," with the ability to pause, kill, etc., I would suggest a three-tier architecture: Javascript client -> Python mediator -> Python target program The Python target program would be something like this, written in a very synchronous style: while True: send_command_to_javascript_and_wait('move') send_command_to_javascript_and_wait('turnleft') The target program would be simple Python code, and the only minor magic would be in the send_command_to_javascript_and_wait method, which would normally just call "print," but when running as a subprocess, would block until the parent indicates it should proceed. I think it's useful, especially on this mailing list, to think about how the Python "mediator" program controls the Python "target" program. Essentially you want the "target" program to be a subprocess of the "mediator" program. You will probably want to use the "Subprocess" module. Look at the "Reading Output of Another Command" section of the article below: http://www.oreillynet.com/onlamp/blog/2007/08/pymotw_subprocess_1.html Once you solve the problem of having another Python program control your "target" program, it's not too big a conceptual leap to have a Javascript (JS) program control it. I would suggest the following high level architecture: 1) JS client communicates with Python mediator via HTTP Ajax calls. 2) JS can send HTTP request to mediator to have it start the target as a subprocess. 3) JS can send HTTP request to mediator to have it deliver data to target subprocess. 4) Target subprocess can send data back to mediator that is to be part of the HTTP response. In your rur-ple application data will be flowing mostly in one direction. The JS client will simply be telling the Python target to advance a step, while the Python target will be giving specific metadata about how to update the world that JS renders. Still, despite the asymmetrical nature of your app, I would try to think of it as a two-way exchange of data. The JS program is communicating what the user wants to do next (usually a generic request to execute the next instruction), and the Python backend is communicating how to change the view (usually as a builtin command like move_robot or highlight_line_of_code), but ultimately it's all data. Hope that helps! Cheers, Steve http://webstervanrobot.com/ From tjreedy at udel.edu Mon Sep 22 17:53:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 17:53:04 -0400 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: Fredrik Lundh wrote: > Robert Kern wrote: > (if someone wants to submit this to bugs.python.org, be my guest) http://bugs.python.org/issue3936 From bignose+hates-spam at benfinney.id.au Mon Sep 29 09:21:58 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 29 Sep 2008 23:21:58 +1000 Subject: One class per file? References: Message-ID: <87od27rssp.fsf@benfinney.id.au> HCB writes: > The book "Code Complete" recommends that you put only one class in a > source file, which seems a bit extreme for me. For Python, that is extreme, and for most applications I've seen it would be counterproductive. Which edition of Code Complete recommends this, and on which page? > Perhaps a better rule of thumb is "one idea per file." I checked the > Python style guide and there seems to be no mention of this topic. I > know this is an elementary question, but what is the Python way of > doing this? You have it right: modules are most naturally used for conceptual grouping of objects (not just classes, but all objects) related to a discrete area of functionality, into a discrete namespace. -- \ ?The WWW is exciting because Microsoft doesn't own it, and | `\ therefore, there's a tremendous amount of innovation | _o__) happening.? ?Steve Jobs | Ben Finney From cjdrake at gmail.com Tue Sep 23 16:25:26 2008 From: cjdrake at gmail.com (Drake) Date: Tue, 23 Sep 2008 13:25:26 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() Message-ID: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> I have a general question of Python style, or perhaps just good programming practice. My group is developing a medium-sized library of general-purpose Python functions, some of which do I/O. Therefore it is possible for many of the library functions to raise IOError Exceptions. The question is: should the library function be able to just dump to sys.exit() with a message about the error (like "couldn't open this file"), or should the exception propagate to the calling program which handles the issue? Thanks in advance for anyone who can either answer my question or point me to where this question has already been answered. From zugnush at gmail.com Wed Sep 3 06:35:15 2008 From: zugnush at gmail.com (zugnush at gmail.com) Date: Wed, 3 Sep 2008 03:35:15 -0700 (PDT) Subject: sys.stdin on windows References: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> Message-ID: <59f18445-c5f0-4ea7-915f-39102cf04f10@s9g2000prg.googlegroups.com> On Sep 3, 11:16?pm, Tim Golden wrote: > Gabriel Genellina wrote: > > En Wed, 03 Sep 2008 06:16:03 -0300, zugn... at gmail.com > > escribi : > > >> I often grep particular patterns out of large logfiles and then > >> pipeline the output to sort and uniq -c > >> I thought today to knock up a script to do the counting in a python > >> dict. > > >> This seems work in linux > > >> $ cat count.py > >> #!/usr/bin/env python > >> import sys > >> from collections import defaultdict > >> accumulator=defaultdict(int) > >> for line in sys.stdin.readlines(): > >> ? ? accumulator[line.strip()]+=1 > >> print "contents,count" > >> for key in accumulator.keys(): > >> ? ? print key,",",accumulator[key] > > >> $ cat test | ./count.py > >> contents,count > >> ?, 1 > >> 23 , 1 > >> 1 , 1 > >> 3 , 2 > >> 2 , 2 > >> 5 , 3 > > >> When I try to run the same thing on windows I get > >> IOError: [Error 9] Bad file descriptor > > >> How can I make this more windows friendly? > > > Explicitely invoking the interpreter worked for me. That is, these two > > commands worked fine: > > > type test.txt | python count.py > > python count.py < test.txt > > > But I cannot explain *why* it doesn't work the other way. > > Known bug in NT-based file association. I'll try > to find an online reference, but that's basically > what it comes to. I think you can faff-about with > batch files to achieve the effect, but I can't > quite remember. > > http://support.microsoft.com/kb/321788 > > TJG Thanks. I'll ues the explicit python call. From jaycx2.3.calrobert at spamgourmet.com.remove Mon Sep 1 04:45:51 2008 From: jaycx2.3.calrobert at spamgourmet.com.remove (Robert Maas,) Date: Mon, 01 Sep 2008 01:45:51 -0700 Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> Message-ID: > From: r... at rpw3.org (Rob Warnock) > In the LGP-30, they used hex addresses, sort of[1], but the > opcodes (all 16 of them) had single-letter mnemonics chosen so that > the low 4 bits of the character codes *were* the correct nibble for > the opcode! ;-} That's a fascinating design constraint! It would be an interesting puzzle to find the most efficient design whereby: - The single-character mnemonics are as easy to memorize as possible; - The instructions produce as efficient code as possible; - The mnemonics really do accurately express what the instruction does; - Minimize total number of instructions needed, maybe fewer than 16; - With the low-order-four-bits rule of course. - See also the avoid-ambiguous-sound criterion later below. By the way, do you remember exactly all the 16 opcodes, or have a Web reference available? > [Or you could type in the actual hex digits, since the low 4 bits > of *their* character codes were also their corresponding binary > nibble values... "but that would have been wrong".] Moreso because some of the sounds would be ambiguous, which I recognized when I first started to use the IBM hexadecimal standard. See below. > The LGP-30 character code was defined before the industry had > yet standardized on a common "hex" [sic, "hexadecimal", base 16 > not base 6!!!] character set, Before IBM had decided to use hexadecimal in their abend coredumps from their System/360 and by their 800-pound-gorilla status they got everyone else to use that ABCDEF system. > they used "0123456789fgjkqw". That doesn't make sense. The low-order four bits of those letters aren't consecutive ascending values from 9+1 to 9+6. Did you make a typo, or did you explain something wrong? (map 'list #'char-code "0123456789fgjkqw") => (48 49 50 51 52 53 54 55 56 57 102 103 106 107 113 119) (loop for n in * collect (rem n 16)) => (0 1 2 3 4 5 6 7 8 9 6 7 10 11 1 7) Now if you used this sequence of letters instead: (map 'list #'char-code "0123456789jklmno") => (48 49 50 51 52 53 54 55 56 57 106 107 108 109 110 111) (loop for n in * collect (rem n 16)) => (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15) Unfortunately o looks like 0, and l looks like 1. Anyway, what I hated about IBM's hexadecimal notation was: - A0 would be pronounced "Ay-tee", which sounds too much like "Eighty". - 1A would be pronounced "Ay-teen", which sounds too much like "Eighteen". - On the lineprinters where we get our abend listings, the capital D and digit 0 (which didn't have any diagonal slash) looked almost identical when the ribbon was going bad, as it always was. - Likewise B and 8 looked nearly identical. - Likewise E and F often looked nearly identical of lower part of E was hitting bad part of ribbon. Now for single-character mnemonics for four bits of instruction opcode, to avoid any two characters that look too similar: 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z We obviously have no choice for KLMNO, so because of look-alike we can't use 0 or D or Q, so we have to use P instead of 0, so our choices look like: 1 2 3 4 5 6 7 8 9 A B C E F G H I J K L M N O P R S T U V W X Y Z If we have an opcode that sets a register to 1, or clears register#1, we might use mnemonic "1" for that instruction, but otherwise we must avoid using digits, use letters only. 1 A B C E F G H I J K L M N O P R S T U V W X Y Z We can't use both U and V, and we can't use both E and F, and we can't use both 1 and I, but we're stuck using both M and N, sigh. At this point I can't decide which branches of the search to discard and which to fix, so I'll stop analysing this puzzle. (With lower-case characters different combinations were mutually exclusive, such as l and 1, but I was doing upper case here.) If punctuation is allowed, then + - * / = < > would make dandy mnemonic opcodes for the obvious instructions. If characters that look like arrows can be used for push and pop, then we have V for push and ^ for pop. If characters that look like arrows can be used for moving left/right in RAM, or shifting bits in a register, then we have < for left and > for right. I wonder if solving this puzzle will yield yet another esoteric programming language? From daniel.watrous at gmail.com Tue Sep 30 17:38:19 2008 From: daniel.watrous at gmail.com (Daniel) Date: Tue, 30 Sep 2008 14:38:19 -0700 (PDT) Subject: problem with "ImportError: No module named..." and sockets Message-ID: Hello, I'm trying to build a very simple IPC system. What I have done is create Data Transfer Objects (DTO) for each item I'd like to send across the wire. I am serializing these using cPickle. I've also tried using pickle (instead of cPickle), but I get the same response. Below is the code. I'll put the rest of my comments after the code [BEGIN CODE] #!/usr/bin/python import SocketServer import os, sys newpath = os.path.normpath( os.path.join( __file__, "../../.." )) sys.path.insert(0, newpath) from pop.command.UpdateCommand import * import cPickle class RequestHandler(SocketServer.StreamRequestHandler): "Handles one request to mirror some text." def handle(self): total_data=[] line = True while line: line = self.rfile.readline().strip() total_data.append(line) receivedCommand = '\n'.join(total_data) newUpdate = cPickle.loads(receivedCommand) print type(newUpdate) for item in newUpdate.items: print str(type(item)) + " with filename: " + item.filename if __name__ == '__main__': import sys if len(sys.argv) < 3: print 'Usage: %s [hostname] [port number]' % sys.argv[0] sys.exit(1) hostname = sys.argv[1] port = int(sys.argv[2]) server = SocketServer.ThreadingTCPServer((hostname, port), RequestHandler) server.serve_forever() [/END CODE] So I can create the UpdateCommand object on the client, send it across the wire and I get as far as the line "newUpdate = cPickle.loads(receivedCommand)", which when it runs produces the following error: Traceback (most recent call last): File "C:\Python25\lib\SocketServer.py", line 464, in process_request_thread self.finish_request(request, client_address) File "C:\Python25\lib\SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Python25\lib\SocketServer.py", line 522, in __init__ self.handle() File "C:\Documents and Settings\dwatrous\My Documents\projects\POP \svn\pop\lib\server.py", line 29, in handle newUpdate = cPickle.loads(receivedCommand) ImportError: No module named UpdateCommand I import the module at the top of the file server.py, but it doesn't throw the ImportError until it tries to unpickle. Please help with any ideas that you have. From lixinyi.23 at gmail.com Wed Sep 24 04:04:43 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Wed, 24 Sep 2008 01:04:43 -0700 (PDT) Subject: PyRun_SimpleFile() crashes References: Message-ID: <89a7ade9-c2d2-4d40-ad52-fe0df6fa25d3@g17g2000prg.googlegroups.com> On 9?24?, ??3:39, lixinyi... at gmail.com wrote: > my code: > main.cpp > #include > > int main(int argc, char **argv) > { > Py_Initialize(); > > FILE *file_1 = fopen("a2l_reader.py","r+"); > PyRun_SimpleFile(file_1,"a2l_reader.py"); > > Py_Finalize(); > > } > > compile under windows using MinGW: > g++ main.cpp libpython25.a -o a > > no error was found. But when I run a.exe the program just crashes. > > What should I do? PyRun_File and PyRun_SimpleFile would just crash my application. but PyRun_SimpleString works fine. But why??? From bearophileHUGS at lycos.com Thu Sep 25 08:57:22 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Sep 2008 05:57:22 -0700 (PDT) Subject: Linq to Python References: <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <2b3abf5e-f748-4051-a730-9b50b5404da6@z72g2000hsb.googlegroups.com> Message-ID: Duncan Booth: > Microsoft added a common set of extension methods which work on > databases, xml, builtin sequences and can be easily extended to include > other custom sequences. When the processing is done in memory, LINQ may also work well with multi-core CPUs, see PLINQ. Bye, bearophile From agostino.russo at gmail.com Tue Sep 9 14:09:45 2008 From: agostino.russo at gmail.com (ago) Date: Tue, 9 Sep 2008 11:09:45 -0700 (PDT) Subject: PYTHONSITEDIR environment variable References: Message-ID: On Sep 9, 6:56?pm, Christian Heimes wrote: > I had a similar idea, wrote a PEP and implemented it for 2.6 and 3.0: > > http://www.python.org/dev/peps/pep-0370/ > > Christian Christian, I like your pep :), The only thing I would add is that in my experience I often use different working-envs for different projects, so I'd prefer to have a more generic solution as opposed to a single working-env per user. The latter could still be achieved by setting the appropriate environment variable in the user profile. Do you think it would be possible to accommodate for the above in your PEP? From deets at nospam.web.de Thu Sep 25 16:55:21 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 22:55:21 +0200 Subject: Eggs, VirtualEnv, and Apt - best practices? In-Reply-To: References: <6k2aqqF5p185U1@mid.uni-berlin.de> Message-ID: <6k2c5pF5oenoU1@mid.uni-berlin.de> > that is a very valid point, but it seemed that Scott has homogeneous > environment: Debian/Ubuntu so my post was relative to the original request. > I agree that when you throw Windows/MacOS into the mix things > become "interesting". But then it's better when your developers develop on > server/platform they are going to be using, using same stack they going to > face in production etc. It all depends on requirements and current > practices in company. Well, you certainly want a desktop-orientied Linux for users, so you chose ubuntu - but then on the server you go with a more stable debian system. Even though the both have the same technical and even package management-base, they are still incompatible wrt to package versions for python. And other constraints such as Photoshop not being available for Linux can complicate things further. >> - keeping track of recent developments. In the Python webframework >> world for example (which the OP seems to be working with), things move >> fast. Or extremly slow, regarding releases. Take Django - until 2 month >> ago, there hasn't been a stable release for *years*. Virtually everybody >> was working with trunk. And given the rather strict packaging policies >> of debian and consorts, you'd be cut off of recent developments as well >> as of bugfixes. > > that definitely becomes tricky however not impossible to track. You do need > a common snapshot for all developers to use anyway - so why not just > package it up? I do, but based on Python eggs. They are platform independent (at ultimo, you can use the source distribution, albeit that sux for windows most of the time), and as I explained in my other post - things are moving in the right direction. Don't get me wrong - I love .deb-based systems. But if using them for my development means that I have to essentially create a full zoo of various packages *nobody else* uses - I rather stick with what's working for me. Diez From sumerc at gmail.com Thu Sep 25 10:45:21 2008 From: sumerc at gmail.com (k3xji) Date: Thu, 25 Sep 2008 07:45:21 -0700 (PDT) Subject: Python OOP question Message-ID: Hi all, I am trying to develop a game-server in python. Design is as following: - ConnectionManager - handling/distributing incoming connections - IOManager - handling IO recv/send operations on sockets. (inheritable) - Socket - basic async socket object - SocketServer - handling multiple socket object requests. (inheritable) - Options - holds the server options (inheritable) I want this code to be extensible as it can be. So I have developed it like this. I f one is going to implement some new feature, all needs to be done is to inherit IOManager or Server object to do it. Inheritable objects are IOManager, SocketServer and Options. But there is some feeling about this design that it can be better. Here is the main.py which I am using to execute the server: from Base.SocketServer import SocketServer from testIOManager import testIOManager from Base.Options import Options from Base.ConnectionManager import ConnectionManager iomgr = testIOManager() opts = Options() # calculate how many server objects to create # according to the maximum allowed client count. serverCnt = opts.MAX_CLIENT_COUNT / opts.MAX_CLIENT_COUNT_PER_SERVER Servers = [] for i in range(serverCnt): server = Server(i) Servers.append(server) cmgr = ConnectionManager(Servers, iomgr, opts) cmgr.start() With current design as server object is inheritable, I need to pass it to ConnectionManager object. I just have a feeling that above design is bad in the sense of readability. Is there any paradigms. patterns specifically in Python for above like situations, where in a library, we design some objects to be abstract as possbile and other non-inheritable objects using the functions? Or just any feedback on this Design structure? From gslindstrom at gmail.com Mon Sep 22 16:18:56 2008 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 22 Sep 2008 15:18:56 -0500 Subject: pyArkansas Set for October 4th Message-ID: This is a reminder of the upcoming pyArkansas one-day Python conference being held on the campus of the University of Central Arkansas on Sat Oct 4, 2008. The schedule is pretty much set ( http://pycamp.python.org/Arkansas/Schedule) and has something for anyone interested in Python, from intro workshops to advanced topics. Jeff Rush and Noah Gift are scheduled to present workshops and talks while Dr. Bernard Chen (UCA Faculty) will teach a 3-hour class on "Python for the Absolute Beginner". Eggs, pyGame, standard library, Eclipse and OLPC are some of the other talks scheduled. This is a *FREE* event (we have GREAT sponsors), so all you need to bring is yourself. We have over 45 people -- from 4 States -- registered and tons of great swag and giveaways lined up. See our wiki (http://pycamp.python.org/Arkansas/HomePage) for more details and registration info. Greg Lindstrom Python Artists of Arkansas (pyAR^2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From digitig at gmail.com Fri Sep 26 12:48:04 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 26 Sep 2008 17:48:04 +0100 Subject: Not fully OO ? In-Reply-To: <48DCC786.2040407@wildenhain.de> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: 2008/9/26 Tino Wildenhain : >> The question I usually ask is "Does this language help me get the job >> done?" Python often does. That's all that really matters, isn't it? > > Well then it still depends on the perception of "job done". For example > PHP programmers would bet their soul that their language of choice is > exactly the right one to "get the job done." :-) > You and me would indeed see a different picture on the level of doneness > of such jobs ;-) Well, I did say "Often". Before now I've struggled for ages to write a Python program to do a job, then when I've tried C# all the problems have fallen away and the job was done in an hour or so. But other times it has been the other way around; I've done stuff in Python that I wouldn't know where to begin with in other languages. One of my constant refrains is that *no* tool is ideal for *all* jobs! -- Tim Rowe From mhuening at zedat.fu-berlin.de Tue Sep 23 10:44:57 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Tue, 23 Sep 2008 16:44:57 +0200 Subject: tkFileDialog and locale under Linux Message-ID: <6jsdn9F4p743U1@mid.uni-berlin.de> Hi, I have problems using tkFileDialog under Linux (Ubuntu 8.04 in my case, but other Linuxes seem to show the same behaviour). The following works fine: import tkFileDialog f = tkFileDialog.askopenfilename() No problem, I can chose a filename. But when switching the locale (in my case to German) like this: import locale locale.setlocale(locale.LC_ALL, '') the file dialog won't work anymore. The traceback is: Traceback (most recent call last): File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 1406, in __call__ return self.func(*args) File "TextSTAT.pyw", line 701, in datei_hinzu dateinamen = tkFileDialog.askopenfilename(initialdir=cfg['FileDir'], filetypes= (('All', '*.*'),('Text', '*.txt'),('HTML', '*.htm*'),('MS Word', '*.doc'),('MS Word 2007', '*.docx'),('OpenOffice 1.x', '*.sxw'),('OpenOffice 2.x', '*.odt')), multiple=1) File "/usr/lib/python2.5/lib-tk/tkFileDialog.py", line 125, in askopenfilename return Open(**options).show() File "/usr/lib/python2.5/lib-tk/tkCommonDialog.py", line 48, in show s = w.tk.call(self.command, *w._options(self.options)) TclError: expected floating-point number but got "0.0" Switching back to the C-locale solves the problem: locale.setlocale(locale.LC_ALL, 'C') tkFileDialog will work again. Any ideas? Best, Matthias From fredrik at pythonware.com Sun Sep 14 08:39:30 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 14 Sep 2008 14:39:30 +0200 Subject: Stuck connection in Python 3.0b2 http.server In-Reply-To: <1a23cbe5-26f5-4332-8901-7aa06c69d68e@k7g2000hsd.googlegroups.com> References: <1a23cbe5-26f5-4332-8901-7aa06c69d68e@k7g2000hsd.googlegroups.com> Message-ID: rs387 wrote: > I've encountered a weird issue when migrating a web server to Python 3 > - the browser would wait forever without showing a page, displaying > "Transferring data" in the status bar. I tracked it down to a > reference cycle in my BaseHTTPRequestHandler descendant - one of the > attributes stored a dict of methods. Removing the cycle made the > problem go away. > > In Python 2.5.2 the code works fine either way. > > Here's a minimal example which runs in both 2.5 and 3.0 - to see stuck > connections run as-is in 3.0 and navigate to http://localhost:8123; to > fix this comment out "self.dummy = self" (alternatively reset > self.dummy = None at the end of the __init__ method). > > Am I doing it wrong, or is this a bug? it's weird enough to deserve an issue over at http://bugs.python.org/, at least. it'd probably be a good idea to test this on 2.6rc as well. From gregturn at mindspring.com Fri Sep 5 09:47:54 2008 From: gregturn at mindspring.com (Goldfish) Date: Fri, 5 Sep 2008 06:47:54 -0700 (PDT) Subject: Spring Python 0.6.0 has been released Message-ID: Spring Python 0.6.0, the python offshoot of the Spring framework and Spring Security, has been released (http:// springpython.webfactional.com). See http://sourceforge.net/project/showfiles.php?group_id=184275&package_id=214366&release_id=624328 for more details. BTW, if you click on the release notes link, there is a report pulled from JIRA (our new bug tracking software) showing the issues. For more details, you have to create an account at jira.springframework.org, and then surf to Spring Python. There, you can see it all nicely bundled at http://jira.springframework.org/secure/IssueNavigator.jspa?reset=true&pid=10270&fixfor=11085. Spring Python is moving forward in tremendous ways! Working with the build team in England, we have gotten things integrated with a continuous integration server. See http://build.springframework.org/browse/EXT, and then surf into the Spring Python parts to see our results. This is great! Just check out http://build.springframework.org/browse/EXT-PYQUICK-19 for archived sample of the success of this project. If you look closely, you may notice that MySQL and PostGreSQL test cases have been commented out. That is because we don't have support for those RDBMS's on CI at this point in time. Don't be alarmed. I have run tests with and without thos test suites, and the difference in code coverage is 85% vs. 83%. Hopefully, in the future, we can get an integration environment that includes those tests as well. This project focuses on quality. That is why I started this project using TDD practices and intend to proceed in this fashion. By integrating with CI, we now have true visibility into this. Another goal is to get code coverage metrics captured. Tools have been updated and show a measurement of 83% at this point in time. I don't know the industry average, but I'm willing to bet it is way below that. I am personally test infected, and I want to see the number higher. The next immediate thing is to update Spring Python to support CherryPy 3.1. We are way behind and need to catch up. I have been working with Sylvain, author of "CherryPy Essentials: Rapid Python Web Application Development", and we are close to getting PetClinic and all the supporting components of Spring Python working. This is exciting because integrating with 3rd party web frameworks opens doors for Spring Python. Have any ideas of where you think Spring Python can go? Send me a message here, or start a new topic on our forum at http://forum.springframework.org/forumdisplay.php?f=45. From fredrik at pythonware.com Tue Sep 9 12:42:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 09 Sep 2008 18:42:28 +0200 Subject: creating an (inefficent) alternating regular expression from a list of options In-Reply-To: References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: Larry Bates wrote: >> vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| >> u|ii|i)' >> >> Is there a public module available for this purpose? > > Perhaps I'm missing something but your function call oneOf(...) is > longer than than actually specifying the result. > > You can certainly write quite easily: > > def oneOf(s): > return "|".join(s.split()) "|" works strictly from left to right, so that doesn't quite work since it doesn't place "aa" before "a". a simple reverse sort will take care of that: return "|".join(sorted(s.split(), reverse=True)) you may also want to do re.escape on all the words, to avoid surprises when the choices contain special characters. From mdboldin at gmail.com Tue Sep 2 10:01:38 2008 From: mdboldin at gmail.com (mmm) Date: Tue, 2 Sep 2008 07:01:38 -0700 (PDT) Subject: Python IDEs with F5 or hotkey shell interaction Message-ID: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> I am looking for advice on Python Editors and IDEs I have read other posts and threads on the subject and my two questions at this time are mainly about the IDLE-like F5-run facilities. While I am fairly happy using IDLE, the debugger is unintuitive to me and I wanted a project manager and a better variable/ class browser and also the potential to edit/run other languages such as R and Tex/Latex. Windows and LINUX compatibility is desired too. I found numerous editor candidates from reading posts to this Python users group list and also documents such as http://wiki.python.org/moin/PythonEditors but few if any alternatives seem to have all of the ?interactive? power of IDLE?- not only a run program in a python shell hotkey but a persistent, after-a-run memory state can be accessed for interactive coding and exploration-- i.e. how IDLE works ! *** My first questions is what other editor/IDE have IDLE-like interactive features. Or to put it another way, is my appraisal below of the editors & IDEs I tried right (note some where looked at as much as a year ago). Python specific IDLE F5 run & Full shell interaction PythonWin F5 run & Full shell interaction, MS Windows only PyScripter F9 run & shell interaction, but script created variables are not persistent (???!) PyPE F5 run, but not an interactive shell DrPython F5 run, but not an interactive shell in MS Windows (maybe in Linux) SPE (Stani) Could not get it to run in MS Windows (???!) PyScripter, PyPe and drPython all had nice features but interaction quirks. My second question is based on a belief that I should move to a more general IDE or editor to get LINUX compatibility and the ability to also edit R and LaTex programs. I have explored these Vim Cream/Vim UliPad SciTe Jext Editra Komodo Editor But none are close to being as interactive friendly as IDLE. I might look at Eclypse with pydev Jedit And these commercial/professional IDEs Wing Komodo IDE Zeus But before doing so I wanted to know form experienced users: ** How hard is it to configure any of the general editors/IDEs to run a Python shell using a hotkey (such as IDLEs F5) and whether any can be set up for full interactivity. I understand and appreciate the difficulties to get full IDLE-like interactivity, but what comes closest? From bj_666 at gmx.net Sun Sep 7 18:03:56 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Sep 2008 22:03:56 GMT Subject: lacking follow-through References: Message-ID: <6ij1ecFqp39rU4@mid.uni-berlin.de> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > This is the strangest post I've seen > since I've joined this list (only > recently). What the ? Yeah, castironpi sometimes doesn't make much sense. Maybe because it's a bot!? :-) Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Fri Sep 19 03:38:13 2008 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 Sep 2008 03:38:13 -0400 Subject: XML Processing In-Reply-To: <5148.6462973573$1221742234@news.gmane.org> References: <007001c91980$b2b42af0$181c80d0$@rawlins@thinkbluemedia.co.uk> <48D24638.9010601@timgolden.me.uk> <5148.6462973573$1221742234@news.gmane.org> Message-ID: Robert Rawlins wrote: >> Some is going to kick themselves when they realise >> that ElementTree *is* built in to Python 2.5 >> >> http://docs.python.org/whatsnew/modules.html#SECTION0001420000000000000000 > > Tim, Andrii, > > Thanks for the heads up on that! I hadn't noticed they're made it part of > the platform modules, that's excellent news. > > In theory I should just be able to amend my import paths and we'll be good > to go, no install external modules. > > Thanks for this, > And don't forget to use cElementTree for production, since it's an order of magnitude or more faster at many tasks. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From fredrik at pythonware.com Wed Sep 17 11:15:54 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 17:15:54 +0200 Subject: python regex character group matches In-Reply-To: <00e11472$0$20331$c3e8da3@news.astraweb.com> References: <00e11472$0$20331$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: >> Assuming that you want to find runs of \uXXXX escapes, simply use >> non-capturing parentheses: >> >> pat = re.compile(u"(?:\\\u[0-9A-F]{4})") > > Doesn't work for me: > >>>> pat = re.compile(u"(?:\\\u[0-9A-F]{4})") it helps if you cut and paste the right line... here's a better version: pat = re.compile(r"(?:\\u[0-9A-F]{4})+") From pruthviraj.pb at gmail.com Tue Sep 16 00:44:24 2008 From: pruthviraj.pb at gmail.com (Babloo) Date: Mon, 15 Sep 2008 21:44:24 -0700 (PDT) Subject: Client server implementation References: <7d623ffb-2936-4aec-a74a-e9f5489e6657@p25g2000hsf.googlegroups.com> Message-ID: <708b9a1e-f4df-4d9c-8daa-cf77900acda4@s20g2000prd.googlegroups.com> On Sep 16, 7:38?am, Benjamin wrote: > On Sep 15, 5:15?am, Babloo wrote: > > > Hi everyone, > > > ? ? ? ? ? ? ? ? ? i wanted to implement a client- server connection > > and transfer a file over the network. i was able to implement a normal > > set up where in i was able to send chat messages and small chunks of > > data. > > I want to implement the file transfer with out using the FTP library > > available in python . > > > ? ? ? ? ? ? ? ? ? So can anyone suggest a piece of code by which i can > > do that. > > I don't know what you really want, but look at Twisted.http://twistedmatrix.com > > > > > Thanks > > Pruthvi > > I am beginner at using python language. I mean i am implementing that in a windows based machine and wanted to transfer files over the LAN. I have written down two files as client.py and server.py . I ran these files at two different Computers in the LAN and I was able to send small chunks of messages( like chat). I was successful in establishing connection and sending small messages. But now i want to transfer a complete file with out using the ftplib(FTP LIBRARY) in python. The files look like this.i hope this would help. ______________________________________________ # Server program from socket import * # Set the socket parameters host = "117.105.224.94" port = 21567 buf = 1024 addr = (host,port) # Create socket and bind to address UDPSock = socket(AF_INET,SOCK_DGRAM) UDPSock.bind(addr) # Receive messages while 1: data,addr = UDPSock.recvfrom(buf) if not data: print "Client has exited!" break else: print "\nReceived message '", data,"'" # Close socket UDPSock.close() __________________________________________________ # Client program from socket import * # Set the socket parameters host = "117.105.224.94" port = 21567 buf = 1024 addr = (host,port) # Create socket UDPSock = socket(AF_INET,SOCK_DGRAM) def_msg = "===Enter message to send to server==="; print "\n",def_msg # Send messages while (1): data = raw_input('>> ') if not data: break else: if(UDPSock.sendto(data,addr)): print "Sending message '",data,"'....." # Close socket UDPSock.close() _____________________________________________________________ From dudeja.rajat at gmail.com Sat Sep 6 11:58:47 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Sat, 6 Sep 2008 16:58:47 +0100 Subject: How to bring subprocess to the foreground? In-Reply-To: <6ifhg2Fq24n6U1@mid.uni-berlin.de> References: <6ifhg2Fq24n6U1@mid.uni-berlin.de> Message-ID: On Sat, Sep 6, 2008 at 3:13 PM, Diez B. Roggisch wrote: > dudeja.rajat at gmail.com schrieb: >> >> Hi, >> >> I've a batch file that I open with the subprocess .Popen() . When this >> batch file is run I want to bring it to the foreground. >> >> Please suggest how can I do this? > > You can't. You can capture the stdout using the pipe-arguments, and in your > main-process, read that and write it to the main process' stdout. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Hi Diez, Thanks for the information. That's valuable information. I though of displayin an information message on the screen through tkMessageBox while the subprocess is running, I did it using: try: testing = subprocess.Popen([batchFilePath], \ shell = True) retCode = testing.wait() tkMessageBox._show("Test Harness execution", \ icon = 'info', \ message="Testing %s in progress..." % libName) except: tkMessageBox._show("Error", \ type='ok', icon='error', \ message="Error executing %s Test Harness" % libName) return None else: print retCode But the message is never displayed. Please suggest if there is something wrong with this code -- Regards, Rajat From jaomatos at gmail.com Tue Sep 30 14:14:08 2008 From: jaomatos at gmail.com (=?iso-8859-1?q?Jos=E9_Matos?=) Date: Tue, 30 Sep 2008 19:14:08 +0100 Subject: Python is slow? In-Reply-To: <0b229c8f-61cf-4617-8927-5627edadc9b9@m36g2000hse.googlegroups.com> References: <00f226c8$0$20617$c3e8da3@news.astraweb.com> <0b229c8f-61cf-4617-8927-5627edadc9b9@m36g2000hse.googlegroups.com> Message-ID: <200809301914.10299.jaomatos@gmail.com> On Tuesday 30 September 2008 16:04:35 George Sakkis wrote: > What you're missing is that for Free Software (TM) zealots it's a > matter of philosophical principle, totally unrelated to how easy is to > overcome the restriction. There is not a "practicality beats purity" > clause in the FSF Bible. The gnuplot license is a free software according to FSF, what is the problem here after all? > George -- Jos? Ab?lio From tjreedy at udel.edu Tue Sep 30 14:18:15 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 14:18:15 -0400 Subject: Python is slow? In-Reply-To: <00f226c8$0$20617$c3e8da3@news.astraweb.com> References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Tue, 30 Sep 2008 22:19:57 +1000, Ben Finney wrote: >> I do, because a natural, beneficial act (modify the work and >> redistribute it) that has no technical reason to restrict, is >> artifically restricted. > > We agree that the restriction is artificial, and I think irrational > (although I'd be interested in hearing the gnuplot developers' reasoning > before making a final judgment). I believe it is a matter of preserving clarity of authorship, just as is the quoting mechanism we take for granted in posts like this. If I removed the quote marks above and silently edited what Ben and you wrote, I might upset someone and certainly could confuse readers. tjr From grante at visi.com Tue Sep 30 20:41:15 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Sep 2008 19:41:15 -0500 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> Message-ID: On 2008-09-30, Michael Torrie wrote: >> Just a thought, your minimum sleep time is probably limited by >> the resolution of the system "HZ" clock. Type >> >> less /proc/config.gz >> >> and search for the value of the "CONFIG_HZ" setting. On the >> Athlon 64 machine I'm using to write this, it's 250, which >> should allow for sleep intervals in multiples of 0.004 >> seconds. > > Since most distributions do not create this file in /proc for whatever > reason, It's also common to put a copy of the config file in /boot (or wherever the kernel binaries are installed). I prefer the /proc/config.gz setup myself, and that's how I configure all my systems. > and some people are being deliberately obtuse, does anyone > know how to ask the kernel what the timer resolution is? Is > it stored anywhere else in /proc or /sys? I kind of think > most distros set it to 1000 Hz, but I'm not sure. We could look in /usr/include: $ grep -r ' HZ ' /usr/include /usr/include/scsi/sg.h:#define SG_DEFAULT_TIMEOUT (60*HZ) /* HZ == 'jiffies in 1 second' */ /usr/include/linux/ixjuser.h:* IXJCTL_HZ sets the value your Linux kernel uses for HZ as defined in /usr/include/linux/n_r3964.h: * Fixed HZ usage on 2.6 kernels /usr/include/asm/param.h:#define HZ 100 But, I happen to know that's wrong and I'm running a kernel with HZ=250. So let's look elsewhere. How about in /proc/sys/kernel? $ cat /proc/sys/kernel/sched_min_granularity_ns 4000000 That looks suspiciously like 1/HZ in nanoseconds. -- Grant From williamhpurcell at gmail.com Tue Sep 30 21:39:54 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Tue, 30 Sep 2008 20:39:54 -0500 Subject: __buitins__ key added during eval() Message-ID: I want to use eval to evaluate wx.TextCtrl inputs. How can I keep python from adding the __builtins__ key to mydict when I use it with eval? Other wise I have to __delitem__('__builtins__') everytime I use eval? >>> mydict = {'a':2,'b':3} >>> eval('a*b',mydict) 6 >>> mydict {'a': 2, '__builtins__': {'IndexError': , ...(I'll spare you the rest)...}, 'b': 3} Also, how come eval has this behavior? Is it desirable? -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 17 10:13:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 17 Sep 2008 16:13:05 +0200 Subject: Python OOP advice In-Reply-To: <9317b769-0569-4ccf-b800-c400328ff579@m36g2000hse.googlegroups.com> References: <3d7d0233-f348-40b6-82ff-7e88162caec8@c65g2000hsa.googlegroups.com> <6089e023-18f6-4c93-a2a4-f933eac786b5@f63g2000hsf.googlegroups.com> <9317b769-0569-4ccf-b800-c400328ff579@m36g2000hse.googlegroups.com> Message-ID: <48d11070$0$12641$426a74cc@news.free.fr> Simon Hibbs a ?crit : > Great contributions, thanks both of you. I'm self-tought when it comes > to Python and OOP and I haven't yet grown an intuitive feel for how to > do things sensibly. While part of the OO design patterns are mostly workaround for lack of dynamism in languages like C++ or Java, and while pattern abuse is certainly not good design, you'd probably learn a lot from the GOF's Design Patterns book. > Simon From steve at REMOVE-THIS-cybersource.com.au Wed Sep 17 12:49:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Sep 2008 16:49:24 GMT Subject: translating ascii to binary References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> Message-ID: <00e12f1f$0$20331$c3e8da3@news.astraweb.com> On Wed, 17 Sep 2008 18:02:15 +0200, Canned wrote: > Hi, > I'm trying to write a class that can convert ascii to binary and vice > versa. I write my class based on this function I've found on internet [...] > That works perfectly, but when I try to implement it in my own class it > gives me alot of headache, also because I'm totally new to the language. > It work only with one character at a time, and if I give a string it > just give some weird result. [snip code] Your "ascii_to_bin" method tries to do too much in one method. You should split the functionality into small, self-contained pieces, then combine them. And frankly, once you got to the part where you started popping and inserting, my brain melted. You are making an easy job too hard! *smiles* Try this instead: class Converterab: ''' Ascii-binary converter. ''' def __init__(self, string): self.string = string def bin(self, n): """Return the binary representation of a positive integer n.""" bindump = [] while n > 0: bindump.append(str(n & 1)) n = n >> 1 bindump.reverse() if bindump: return ''.join(bindump) else: return '0' def char_to_bin(self, c): """Return the binary representation of a character c.""" bits = self.bin(ord(c)) zeroes = "0" * (8-len(bits)) return zeroes+bits def ascii_to_bin(self): results = [] for c in self.string: results.append(self.char_to_bin(c)) return ''.join(results) -- Steven From bdesth.quelquechose at free.quelquepart.fr Sun Sep 28 15:46:13 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 Sep 2008 21:46:13 +0200 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <48dffaef$0$10596$426a74cc@news.free.fr> process a ?crit : > I have heard some criticism about Python, that it is not fully object- > oriented. > > What is not an object in Python? names and statements. > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? See other answers here about how the len(obj) is implemented. But anyway: OO and the dotted notation are totally orthogonal. The message(obj) is by no mean less OO than the obj.method() one - even more FWIW, since the notion of 'method' is mostly an implementation artifact. The key conceps in OO are "object" and "message", not "dot" and "method". From kay.schluehr at gmx.net Tue Sep 23 16:15:57 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 23 Sep 2008 13:15:57 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> Message-ID: On 23 Sep., 21:23, J Peyret wrote: > On Sep 23, 8:31 am, bearophileH... at lycos.com wrote: > > Guys, this looks like a great data structure/algo for something I am > working on. > > But... where do I find some definitions of the original BK-tree idea? *geometric data structures*. Just google for it. From deets at nospam.web.de Fri Sep 12 10:44:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 Sep 2008 16:44:06 +0200 Subject: Checking the boolean value of a collection In-Reply-To: References: <6ivbfvFnfucU1@mid.uni-berlin.de> Message-ID: <6ivdhnFnm8bU1@mid.uni-berlin.de> >> if any(instance.forbitToClose(archivefolder) for instance in >> self.findActiveOutgoingRegistrationInstances()) > > Can you clarify where I can find "any"? It seems to me I'm unable to find it... It's part of python2.5. If you don't have that, you can write it your own and stuff it into __builtins__: >>> def any(iterable): ... for item in iterable: ... if item: ... return True ... return False ... ... __builtins__.any = any You might also want to add all, the companion of any: >>> def all(iterable): ... for item in iterable: ... if not item: ... return False ... return True ... Diez From maric at aristote.info Mon Sep 15 11:19:23 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 17:19:23 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <200809151645.13078.maric@aristote.info> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> <200809151645.13078.maric@aristote.info> Message-ID: <200809151719.24434.maric@aristote.info> Le Monday 15 September 2008 16:45:12 Maric Michaud, vous avez ?crit?: > This is not sufficient for auto-responses, and given the following rfcs, it > would smart to both : > ... > - add or modify the Return-Path and/or Reply-To header for badly > implemented auto-responders to point to list maintainer. Oh, no ! to the list itself of course. This could also avoid the common mistake mailing list users do in replying private mail accidentally when the adress of the list is only present in CC field. -- _____________ Maric Michaud From Afro.Systems at gmail.com Sun Sep 21 01:16:29 2008 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Sat, 20 Sep 2008 22:16:29 -0700 (PDT) Subject: writeable buffer and struct.pack_into and struct.unpck_from References: Message-ID: Thanks Gabriel, I was missing the information how to create a writable buffer. From grflanagan at gmail.com Mon Sep 29 16:46:53 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Mon, 29 Sep 2008 22:46:53 +0200 Subject: Finding subsets for a robust regression In-Reply-To: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> References: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > > x1 = [] #unique instances of x and y > y1 = [] #median(y) for each unique value of x > for xx,yy in d.iteritems(): > x1.append(xx) > l = len(yy) > if l == 1: > y1.append(yy[0]) > else: > yy.sort() > y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else > yy[l//2] ) > -- Not tested, but is this equivalent? x1 = [] y1 = [] for xx, yy in d.iteritems(): L = len(yy) // 2 yy.sort() y1.append(yy[L]) if not L & 1: y1[-1] = (y1[-1] + yy[L-1]) / 2.0 It means that you have a pointless 'sort' when len(yy) == 1, but then you save an 'if' per-iteration. G. From mail at timgolden.me.uk Fri Sep 12 03:59:54 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 12 Sep 2008 08:59:54 +0100 Subject: rss feed generation In-Reply-To: <32cabba0809111835g2984c463y2c4b689605f8362e@mail.gmail.com> References: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> <32cabba0809111835g2984c463y2c4b689605f8362e@mail.gmail.com> Message-ID: <48CA217A.60708@timgolden.me.uk> Walter Cruz wrote: > On Tue, Sep 9, 2008 at 9:35 PM, alex23 wrote: >> On Sep 10, 7:30 am, "Blake Garner" wrote: >>> I'm looking for suggestions on how to approach generating rss feed >>> .xml files using python. What modules to people recommend I start >>> with? I just rolled something with ElementTree. No idea how it stacks up against validity checks, but it seems to be accepted by a couple of standard feed readers. (sorry; longish code segment) import os, sys from datetime import datetime try: from xml.etree import cElementTree as ET except ImportError: from elementtree import ElementTree as ET class Feed (object): ENCODING = "utf-8" def __init__ (self, title, link, description=None, author=None, updated_on=None): self.title = title self.link = link self.description = description self.author = author self.updated_on = updated_on or datetime.now () self.entries = [] def add_entry (self, title, link, content, summary=None, id=None, updated_on=None): self.entries.append ( dict ( title=title, link=link, content=content, summary=summary, id=id or link, updated_on=updated_on or datetime.now () ) ) def write_rss (self, ofile=sys.stdout, encoding=ENCODING): rss = ET.Element ("rss", version="2.0") channel = ET.SubElement (rss, "channel") ET.SubElement (channel, "title").text = self.title ET.SubElement (channel, "link").text = self.link ET.SubElement (channel, "description").text = self.description for entry in self.entries: item = ET.SubElement (channel, "item") ET.SubElement (item, "title").text = entry['title'] ET.SubElement (item, "link").text = entry['link'] ET.SubElement (item, "guid").text = entry['id'] ET.SubElement (item, "description").text = entry['content'] ET.ElementTree (rss).write (ofile, encoding=encoding) def write_atom (self, ofile=sys.stdout, encoding=ENCODING): feed = ET.Element ("feed") ET.SubElement (feed, "title", type="text").text = self.title ET.SubElement (feed, "link", rel="self", href=self.link) if self.description: ET.SubElement (feed, "subtitle", type="text").text = self.description if self.author: name, email = self.author author = ET.SubElement (feed, "author") ET.SubElement (author, "name").text = name ET.SubElement (author, "email").text = email ET.SubElement (feed, "updated").text = self.updated_on.isoformat () for entry in self.entries: e = ET.SubElement (feed, "entry") ET.SubElement (e, "title").text = entry['title'] ET.SubElement (e, "link", href=entry['link']) ET.SubElement (e, "id").text = entry['id'] ET.SubElement (e, "updated").text = entry['updated_on'].isoformat () if entry['summary']: ET.SubElement (e, "summary").text = entry['summary'] ET.SubElement (e, "content", type="html").text = "" % entry['content'] ET.ElementTree (feed).write (ofile, encoding=encoding) if __name__ == '__main__': feed = Feed ("Feed for example.org", "http://example.org", author=("Tim Golden", "tim at example.org")) for i in range (5): feed.add_entry ("Entry %d" % i, "http://example.org/entry/%d" % i, "Contents for entry %d" % i, id="entry#%d" % i) feed.write_atom (open ("feed.atom.xml", "w"), "iso-8859-1") feed.write_rss (open ("feed.rss.xml", "w"), "iso-8859-1") TJG From ville at ville-desktop.i-did-not-set--mail-host-address--so-tickle-me Sat Sep 13 09:41:37 2008 From: ville at ville-desktop.i-did-not-set--mail-host-address--so-tickle-me (ville) Date: Sat, 13 Sep 2008 13:41:37 GMT Subject: How to run PyOS_InputHook from python code (i.e. yield to event loops) References: <87wshpcaek.fsf@gmail.com> Message-ID: <87iqt0b1tj.fsf@ville-desktop.i-did-not-set--mail-host-address--so-tickle-me> Sean DiZazzo writes: >> My eventual code would be something like: >> >> launch_process_in_thread('bzr pull') >> >> while not is_done: >> ? pyos_inputhook() >> ? time.sleep(0.1) >> >> print "Done!" > > I'm still recovering from a hangover, so don't quote me. I think you > want the "after" function: > > launch_process_in_thread('bzr pull') > self.update() > > def update(self): > while not self.is_done: > self.after(2000, self.update) That's tk-specific, right? I'm looking for a snippet that - Would not be tied to tk - Would run sequentially, i.e. the next command would not be entered before the process has finished. Just like os.system() From bearophileHUGS at lycos.com Fri Sep 19 15:51:24 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 19 Sep 2008 12:51:24 -0700 (PDT) Subject: Python newbie References: Message-ID: Mladen Gogala: Welcome to Python, you will need only one or few weeks to be able to write useful Python programs. But even with the help of a good book (that I suggest you to read) you may need several months or one year to master it :-) > 2) Why is it illegal to pass a built-in function "print" to map? Maybe because one of the few original design mistakes of Python. The new Python 3.0 "fixes" that problem, in Python 3 print is now a function, so you can use it where you can use functions. But in general I think it's better to not give map() a function that has side effects like print(). So you want to use a list comp there instead, and create a new list: [2 * el for el in a] In Python (and several other modern languages, like Scala, plus some more functional languages) you will find that people often prefer to create new data structures instead of modifying old ones. This may sound like a waste of memory and time, but using a more immutable-data style has several advantages (often in code clarity) that are a bit complex to explain here. As you probably know, the good thing of learning new languages is that they carry some principles, and they are the expression of some ideas of the computer science. So learning Python may show you some new ideas, or new ways to look at old computer science ideas you already know. I think Alan J. Perlis said "A language that doesn't affect the way you think about programming, is not worth knowing." Bye, bearophile From ricaraoz at gmail.com Wed Sep 10 13:14:01 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Wed, 10 Sep 2008 14:14:01 -0300 Subject: Can anyone suggest a good crypto package? In-Reply-To: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> References: <5b4e5632-58f6-4683-9190-e4fd92cd6721@k36g2000pri.googlegroups.com> Message-ID: <48C80059.7080101@bigfoot.com> Fett wrote: > On Sep 4, 2:23 pm, Mike Driscoll wrote: >> On Sep 4, 1:39 pm, Fett wrote: >> >> >> >>> I need a crypto package that works on windows with python 2.5. Can >>> anyone suggest one for me? >>> I have been searching for a couple days for a good cryptography >>> package to use for public/private key encryption, at this point I >>> would settle for symmetric even. >>> Every encryption package I have found for python was either operating >>> system specific (read *nix only):http://www.freenet.org.nz/ezPyCrypto/http://www.keyczar.org/ >>> There was one exception, this version was specifically built to run on >>> any platform (yay), but the compiler for windows complained that I >>> wasn't using python2.2 (though the package was said to only need 2.2 >>> or newer). >>> Is there any crypto package that is actually written in python? I >>> seriously don't care how slow it is. >> How about M2Crypto:http://chandlerproject.org/Projects/MeTooCrypto#Downloads >> >> Mike > > Seems that this is intended more for webapps or something, I intend to > use this for a client application. This means that I can't require > outside dependencies, or I risk annoying the clients (if you have > installed many open-source projects with dependencies that aren't > handled by portage/apt-get, you know what I would be doing to them). > > I seriously can't believe that there isn't a single python native > crypto package. Why do they all need to have outside dependencies? > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, maybe I'm a little late but today scanning through "The daily Python-URL" I came through something that might be pertinent. The link is http://www.keyczar.org/ And here is the intro to the site : """ Keyczar is an open source cryptographic toolkit designed to make it easier and safer for developers to use cryptography in their applications. Keyczar supports authentication and encryption with both symmetric and asymmetric keys. Some features of Keyczar include: * A simple API * Key rotation and versioning * Safe default algorithms, modes, and key lengths * Automated generation of initialization vectors and ciphertext signatures * Java and Python implementations (C++ coming soon) * International support in Java (Python coming soon) Keyczar was originally developed by members of the Google Security Team and is released under an Apache 2.0 license. """ HTH From uzmanajmal at gmail.com Mon Sep 15 02:23:27 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Mon, 15 Sep 2008 06:23:27 +0000 Subject: How to convert M2Crypto.RSA.RSA to string Message-ID: Hi, I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that key as string. Is there any way to convert the said instance into string? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mitko at qlogic.com Tue Sep 30 14:56:54 2008 From: mitko at qlogic.com (Mitko Haralanov) Date: Tue, 30 Sep 2008 11:56:54 -0700 Subject: Change environment after setreuid Message-ID: <20080930115654.0e0f36d3@hematite.mv.qlogic.com> I have a program (which normally runs as root) which can start child processes as different users. Effectively, my program is a modified version of popen2's Popen3 class where the child process (after the fork) does: os.setregid (gid, gid) os.setreuid (uid, uid) session_pid = os.setsid () This all seems to work. However, I am running into a problem where the environment of the new process still carries values that were set before the setreuid() call. What would be the best way to go about modifying the environment without having to re-implement all the functionality of the 'su' command? I could use it (the 'su' command) to start the new process but I'd like to avoid external dependencies like that. Thank you -- Mitko Haralanov ========================================== The program isn't debugged until the last user is dead. From stef.mientki at gmail.com Mon Sep 15 12:58:16 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 15 Sep 2008 18:58:16 +0200 Subject: Python IDEs with F5 or hotkey shell interaction In-Reply-To: References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> Message-ID: <48CE9428.7090406@gmail.com> hello Almar, Almar Klein wrote: > > ... > but few if any alternatives seem to have all of the 'interactive' > power of IDLE?- not only a run program in a python shell hotkey but a > persistent, after-a-run memory state can be accessed for interactive > coding and exploration-- i.e. how IDLE works ! > > > I felt the same. Coming from Matlab, I missed the interactive behaviour. > I found IPython with a proper editor (I really liked PyPE) a nice > solution. > > Still, I found it awkward having to use two programs and not having code > completion in my editor (I mean the editor not knowing what names are > present in my python session.) > > Therefore, I started creating an editor with an interactive shell in > it in which > you can run (parts of) your code and have a persisten session. It's not > finished yet, but I'm quite happy with the result so far. It starts > python in a > subprocess in much the same way PyPE does. I actually "stole" code from > PyPE as a base for multiple things (thanks Josiah :) ). Any change we could see some code already ? I'm working on something similar, bored of the bugs in my current IDE. Here are my first notes: http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pw_debug.html It should become a very-simple-very-high-level IDE, like Matlab, but then better ;-) cheers, Stef > > Almar > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From m_palmer45 at yahoo.ca Wed Sep 17 08:14:04 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 17 Sep 2008 05:14:04 -0700 (PDT) Subject: shelve file space always increase! References: Message-ID: <892aa8b4-a95b-44fc-ac5d-08815c3c061e@a70g2000hsh.googlegroups.com> On Sep 17, 6:17 am, smalltalk wrote: > >>> import shelve > >>> sf = shelve.open('e:/abc.db') > >>> for i in range(10000): > > ... sf[str(i)]=i > ...>>> sf.close() > >>> sf = shelve.open('e:/abc.db') > >>> sf.clear() > >>> sf > > {} > the abc.db is always 312k though i have use clear(), how can i shrink > the space? shelve doesn't have any way of doing that. the only option is to read all items from your shelve and write them to a new one. From martin at v.loewis.de Thu Sep 25 16:47:52 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 25 Sep 2008 22:47:52 +0200 Subject: Quick sort implementation in python In-Reply-To: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> Message-ID: <48dbf8f9$0$21266$9b622d9e@news.freenet.de> > Now as you can see I'm passing my list object to both functions along > with their first, last indices I cannot really see that. More specifically, it isn't definite what the type of the "a" argument is, nor does the specific type of "a" matter for the algorithm. It could be a list, or it could be a different mutable collection that is integer-indexed. > My question is: Is that the normal way to implement algorithms in > python Yes, it is. > cause in c++ i've implemented that algo via a template function > which can have a randon access data structure or not. However i have > no idea how to access the values of a data structure that doesn't > allow random access. Can you please explain how you did that in C? IOW, how did you do the partition function (template) in case you don't have random access to the collection? Regards, Martin From lists at cheimes.de Wed Sep 10 11:40:37 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 17:40:37 +0200 Subject: Accessing __slots__ from C In-Reply-To: References: Message-ID: Chris wrote: > Hi, > > I'd like to be able to access an attribute of a particular Python > object as fast as possible from some C code. > > I wondered if using __slots__ to store the attribute would allow me to > do this in a faster way. > > The reason I'd like to do this is because I need to access the > attribute inside a loop within some C code, and I find that the > attribute lookup using the 'PyObject_GetAttrString' call is far slower > than any of the subsequent calculations I perform in C. That's correct. You can use slots to increase the performance but it doesn't work like you think. If you need it *really* fast than write a C Extension, store the data in a C struct and access the data via PyMemberDef. Christian From python.list at tim.thechases.com Wed Sep 17 07:21:19 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 17 Sep 2008 06:21:19 -0500 Subject: Use of generators and efficiency In-Reply-To: <200809171106.01782.research@johnohagan.com> References: <200809171106.01782.research@johnohagan.com> Message-ID: <48D0E82F.8070003@tim.thechases.com> > To my great surprise, this approach was often considerably _slower_ to > complete than the original program (up to ~40% depending on which modifiers > were used), despite producing initial results more quickly. You may be interested in reading through this thread http://mail.python.org/pipermail/python-list/2008-January/473650.html where looping vs generators were timed and you can see that generators clearly (and sadly) impose a speed penalty as demonstrated by Andrew Reedick. I'm not sure whether the "why" of it was ever determined, but generators should be used with care if speed is more important than clarity. -tkc From half.italian at gmail.com Fri Sep 12 22:07:28 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 12 Sep 2008 19:07:28 -0700 (PDT) Subject: Good python web programming books References: <491bd2b50809121757p2d44750ev1697c3eda1f76598@mail.gmail.com> Message-ID: On Sep 12, 6:08?pm, "Chris Rebert" wrote: > I've heard good things about The Django Book:http://www.djangobook.com/ > - Chris > > > > On Fri, Sep 12, 2008 at 5:57 PM, bhaarat Sharma wrote: > > Hi Guys, > > > I am very new to python. ?I am looking for a good book about python web > > programming. > > > I looked at a few online like Web Programming In Python but most are quite > > old. > > > If you've read a good book on python web programming can you please suggest > > some? > > > Thanks > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com Im exploring TurboGears and loving it. However I don't know how well you will do learning a web framework at the same time as the language. Spend a few weeks (at least) learning the language basics from the tutorials, then maybe try Django or TurboGears. You could do some neat stuff with mod_python as a beginner, so maybe start there. http://docs.python.org/tut/ http://diveintopython.org/ http://www.modpython.org/ http://www.turbogearsbook.com/ Good luck! m2c, ~Sean From half.italian at gmail.com Wed Sep 10 22:01:34 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 10 Sep 2008 19:01:34 -0700 (PDT) Subject: SSH using PEXPECT References: Message-ID: On Sep 10, 6:04?pm, yellowblueyel... at gmail.com wrote: > Hey , I need to SSH into a server .. (10.8.42.38) using pexpect the > username is 'admin' and password is 'abc123' so far i have the > following code > > import pexpect > import sys > import time > import os > > foo = pexpect.spawn('ssh ad... at 10.8.42.38') > ssh_newKey = 'Are you sure you want to continue connecting' > > foo.expect = ssh_newKey > foo.send = 'yes' > foo.expect = 'password:' > foo.send = 'abc123' > > --------------------------------------------------------------------------- ---------------------- > > does this look right? > > if not , could someone suggest a way to do this .. > your help is much appreciated https://svn.lal.in2p3.fr/projects/CMT/CMTManagement/utils/ssh_session.py I use a modified version of this. Simple and effective. import ssh_session ssh = ssh_session.ssh_session(user, host, password) print ssh.ssh("ls -l /tmp") Thanks Eric and Nigel! ~Sean From bignose+hates-spam at benfinney.id.au Thu Sep 18 21:22:08 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 Sep 2008 11:22:08 +1000 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> <87skrx2ifz.fsf@benfinney.id.au> <7a5c8caa-7ff9-4180-9291-38c27bde82e1@b2g2000prf.googlegroups.com> Message-ID: <87od2l2am7.fsf@benfinney.id.au> erikcw writes: > On Sep 18, 3:33?pm, Ben Finney > wrote: > > erikcw writes: > > > What is the correct way to launch subprocess without waiting for > > > the result to return? > > > > Creating an instance of 'subprocess.Popen' will launch the process > > and return the Popen instance. You then have the option of polling > > it or waiting for it to complete. > > So if I create a Popen object and then just ignore the object and > exit the program the subproccess will finish it's work and then exit > itself cleanly? Ah, no, that's a different thing. If the parent exits, the child will also be killed I believe. If you want to spawn a process and have it live on independent of the parent, you want to make the child process a "daemon", detatching itself from the parent's environment. I don't recall how that's done immediately, but those are the terms to search for. -- \ ?Pinky, are you pondering what I'm pondering?? ?Yes Brain, but | `\ if our knees bent the other way, how would we ride a bicycle?? | _o__) ?_Pinky and The Brain_ | Ben Finney From bdesth.quelquechose at free.quelquepart.fr Mon Sep 29 12:39:45 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2008 18:39:45 +0200 Subject: destructor not called In-Reply-To: <93627810-b437-4b9a-9aad-6837271fd894@m36g2000hse.googlegroups.com> References: <2a7dea43-378a-423f-a5bb-d904b7f97869@p25g2000hsf.googlegroups.com> <3dec57f0-c829-4420-b36d-58e21c564053@k37g2000hsf.googlegroups.com> <93627810-b437-4b9a-9aad-6837271fd894@m36g2000hse.googlegroups.com> Message-ID: <48e120bb$0$30170$426a34cc@news.free.fr> Marcin201 a ?crit : >> Others have already replied to your main question; in short you >> shouldn't rely on __del__ being called. Regardless, is there a (good) >> reason for having an instance reference to the method ? Without >> further information, that seems like a code smell. > > I have dictionary of fxns to do import/export based on the type of > request from user so I can call self.Import['html'] or > self.Import['text']. getattr(obj, name) is your friend. And if you really want to maintain your own mapppings, do it at the appropriate level - that is, when it comes to methods, at the class level, not the instance level. You can even automate this using a decorator and a custom metaclass, ie (warning: Q&D code, not tested, may contain errors etc): # myframework.py def request_handler(func): func._request_handler = True return func class RequestHandlerType(type): def __init__(cls, name, bases, dic): handlers = getattr(cls, '_handlers') for name, attrib in dic: if getattr(attrib, '_request_handler', False): handlers[name] = attrib cls._handlers = handlers class BaseRequestHandler(object): __metaclass__ = RequestHandlerType # myapp.py from myframework impoty request_handler, BaseRequestHandler class MyHandler(BaseRequestHandler): @request_handler def html(self, *args, **kw): # code here @request_handler def text(self, *args, **kw): # code here def dispatch(self, request): format = request.format try: handler = self._handlers[format] except KeyError: # raise appropriate exception here else: return handler(self, request) From george.sakkis at gmail.com Mon Sep 29 10:56:06 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 29 Sep 2008 07:56:06 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> Message-ID: <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> On Sep 29, 9:02 am, bearophileH... at lycos.com wrote: > George Sakkis: > > > I don't see the same value in creating a distinction between methods > > and builtin functions unless the latter are truly generic (and even > > then I wouldn't mind having them as methods of the base object class, > > e.g. object.type()). Having a builtin len(x) delegate to x.__len__() > > seems harder to justify. > > I have shown few usage examples of the len() one of the posts in this > thread. Can you take a look at them and show how you can better > rewrite them without a len function? > > Bye, > bearophile You mean this ? >>> seq = ["aaaa", "bb", "c", "ddd"] >>> seq2 = [[1,1,1,1], [2,2], [3], [4,4,4]] >>> sorted(seq, key=lambda x:x.__len__()) ['c', 'bb', 'ddd', 'aaaa'] >>> sorted(seq2, key=lambda x:x.__len__()) [[3], [2, 2], [4, 4, 4], [1, 1, 1, 1]] Sure, "len" looks better than lambda x:x.__len__(), but the same would be true if there was an "upper" builtin for the following example: >>> s = ['a', 'd', 'B', 'C'] >>> s2 = [u'a', u'd', u'B', u'C'] >>> upper = lambda x: x.upper() >>> sorted(s, key=upper) ['a', 'B', 'C', 'd'] >>> sorted(s2, key=upper) [u'a', u'B', u'C', u'd'] No difference in principle, just len() happens to be implemented more often than upper(). George From karl.kobata at syncira.com Wed Sep 17 14:02:06 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Wed, 17 Sep 2008 11:02:06 -0700 Subject: ka-ping yee tokenizer.py Message-ID: <6gvfio$7sja8m@rrcs-agw-01.hrndva.rr.com> Aaran, Thanks for your input. Your examples gave me other alternatives for what I wanted to do and it seems to work. Thanks all for your help. On Sep 16, 2:48 pm, "Karl Kobata" > wrote: > Hi Fredrik, > > This is exactly what I need. Thank you. > I would like to do one additional function. I am not using the tokenizer to > parse python code. It happens to work very well for my application. > However, I would like either or both of the following variance: > 1) I would like to add 2 other characters as comment designation > 2) write a module that can readline, modify the line as required, and > finally, this module can be used as the argument for the tokenizer. > > Def modifyLine( fileHandle ): > # readline and modify this string if required > ... > > For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ): > Print token > > Anxiously looking forward to your thoughts. > karl > > -----Original Message----- > From: python-list-bounces+kkobata=syncira.... at python.org > > [mailto:python-list-bounces+kkobata=syncira.... at python.org ] On Behalf Of > Fredrik Lundh > Sent: Monday, September 15, 2008 2:04 PM > To: python-l... at python.org > Subject: Re: ka-ping yee tokenizer.py > > Karl Kobata wrote: > > > I have enjoyed using ka-ping yee's tokenizer.py. I would like to > > replace the readline parameter input with my own and pass a list of > > strings to the tokenizer. I understand it must be a callable object and > > iteratable but it is obvious with errors I am getting, that this is not > > the only functions required. > > not sure I can decipher your detailed requirements, but to use Python's > standard "tokenize" module (written by ping) on a list, you can simple > do as follows: > > import tokenize > > program = [ ... program given as list ... ] > > for token in tokenize.generate_tokens(iter(program).next): > print token > > another approach is to turn the list back into a string, and wrap that > in a StringIO object: > > import tokenize > import StringIO > > program = [ ... program given as list ... ] > > program_buffer = StringIO.StringIO("".join(program)) > > for token in tokenize.generate_tokens(program_buffer.readline): > print token > > > > --http://mail.python.org/mailman/listinfo/python-list > > This is an interesting construction: >>> a= [ 'a', 'b', 'c' ] >>> def moditer( mod, nextfun ): ... while 1: ... yield mod( nextfun( ) ) ... >>> list( moditer( ord, iter( a ).next ) ) [97, 98, 99] Here's my point: >>> a= [ 'print a', 'print b', 'print c' ] >>> tokenize.generate_tokens( iter( a ).next ) >>> tokenize.generate_tokens( moditer( lambda s: s+ '#', iter( a ).next ).next ) It adds a '#' to the end of every line, then tokenizes. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Mon Sep 22 22:14:12 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 22 Sep 2008 19:14:12 -0700 (PDT) Subject: A bit weird dictionary behavior References: <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <00e822ed$0$20303$c3e8da3@news.astraweb.com> Message-ID: <3a12f7b1-3cea-4d18-a7ee-a51299fec866@i76g2000hsf.googlegroups.com> Steven D'Aprano: >For many iterables, the amount of memory is not excessive and the increase in readability of len() is to be preferred over the side-effect of sum(1 for...).< With side-effects do you mean the possibility of exhausting a lazy iterable? The readability difference is little, and it's way safer because it works well enough with very long iterables too, so leniter(..) is better than len(list(...)). Bye, bearophile From lists at cheimes.de Fri Sep 26 04:24:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 26 Sep 2008 10:24:19 +0200 Subject: Module import path when embedding python in C In-Reply-To: <913fe5fc-9b8e-49c6-b740-5d6bb74abc97@s20g2000prd.googlegroups.com> References: <913fe5fc-9b8e-49c6-b740-5d6bb74abc97@s20g2000prd.googlegroups.com> Message-ID: graph wrote: > Does anyone know why PySys_GetObject wasn't documented until somewhat > recently (http://bugs.python.org/issue1245) if it has been part of the > system module interface since at least Python 1.5.2? Is it not > supposed to be used? What's the difference the above and importing > the sys module and then doing the append? The PySys_Get/SetObject methods are faster than PyImport. The methods access the sys module directly without going through the import API. The funcitons weren't documented because they were simply forgotten. Christian From guillermo.listas at googlemail.com Tue Sep 2 09:17:37 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Tue, 2 Sep 2008 06:17:37 -0700 (PDT) Subject: Algorithm used by difflib.get_close_match Message-ID: <83c600d0-6852-4dd6-9287-34f9b3264090@s50g2000hsb.googlegroups.com> Hi all, Does anyone know whether this function uses edit distance? If not, which algorithm is it using? Regards, Guillermo From pavlovevidence at gmail.com Wed Sep 17 03:44:08 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 17 Sep 2008 00:44:08 -0700 (PDT) Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> <6jb6juF2co8rU1@mid.individual.net> Message-ID: <4fc1f095-42b2-435f-a86b-d0260cfef922@c22g2000prc.googlegroups.com> On Sep 16, 10:29 pm, Steven D'Aprano wrote: > On Wed, 17 Sep 2008 13:52:13 +1200, greg wrote: > > Arnaud Delobelle wrote: > > >> Or: > > >> import ModuleName as this_module > > > Or: > > > this_module = __import__(__name__) > > > then you don't have to change anything. > > I like that solution! And it works regardless of whether the module > holding it is imported, or is being executed from the commandline. It doesn't work if the module is part of a package. For that could use sys.modules[__name__] or write a separate function to return the appropriate nested module of __name__. Neither method is foolproof I don't think. Carl Banks From fetchinson at googlemail.com Thu Sep 11 15:02:06 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Thu, 11 Sep 2008 12:02:06 -0700 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: <943393.38616.qm@web95111.mail.in2.yahoo.com> References: <943393.38616.qm@web95111.mail.in2.yahoo.com> Message-ID: >> Thanking you, >> >> Ms. Vaidehi Pawar > > How much do you pay? > >> How much do you ask for???? >> >> cheers >> Ms. Vaidehi I was just kidding. But if you seriously need people to do this kind of job it's better to post the amount you are willing to pay otherwise nobody will take it seriously. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From h.goebel at goebel-consult.de Wed Sep 17 09:46:13 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Wed, 17 Sep 2008 15:46:13 +0200 Subject: Python and Open Office In-Reply-To: References: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <48d10a26$0$6658$9b4e6d93@newsspool2.arcor-online.net> Terry Reedy schrieb: > One way to learn the meaning of some of the numerous attributes and > values is to create a file with the wanted features with OOo, save, > unzip, and examine the xml to see which tags are used for which features. The API docs are a bit hidden on the webpage. Here is the link: Additionally teh ODF sepcs may help: Regards H. Goebel From jan.schilleman at xs4all.nl Mon Sep 15 17:12:09 2008 From: jan.schilleman at xs4all.nl (Jan Schilleman) Date: Mon, 15 Sep 2008 23:12:09 +0200 Subject: Rebinding __setattr__ References: <48cd98e7$0$3054$e4fe514c@dreader17.news.xs4all.nl> Message-ID: <48cecfb3$0$3164$e4fe514c@dreader31.news.xs4all.nl> That still would require changing the source of the library ... And i'm not sure if it would have side effects. "Maric Michaud" schreef in bericht news:mailman.1033.1221477203.3487.python-list at python.org... Le Monday 15 September 2008 01:06:08 Jan Schilleman, vous avez ?crit : > Hi all, > > I am trying to redefine __setattr__. > > The base class is in a library (actually, it is > win32com.client.DispatchBaseClass) and I do not want to touch it. My > problem is exemplified below. To my surprise, __setattr__ and __str__ > behave differently; I can redefine __str__ and the inherited __str__ is > still the redefined one. But redefining __setattr__ on the base class does > not get inherited. In Base.__dict__ the __setattr__ is the one I expected, > but it is not called from B. > > What is the problem? Is __setattr__ cached somewhere [and not updated?]? > Yes, it doesn't work with classic classes, but do with new-style ones, I don't know if this an accepted behavior or not. Can't you use new-style classes ? >>>[2]: sys.version ...[2]: '2.5.2 (r252:60911, May 28 2008, 19:19:25) \n[GCC 4.2.4 (Debian 4.2.4-1)]' >>>[64]: class A : def __setattr__(self, name, value) : print "A", name ....: ....: >>>[67]: class B(A) : pass ....: >>>[68]: A().c, B().c = 1, 2 A c A c >>>[69]: A.__setattr__ = lambda s, n, v : sys.stdout.write("%s, %s, %s\n" % (s, n, v)) >>>[70]: A().c, B().c = 1, 2 <__main__.A instance at 0x2b3b41546290>, c, 1 A c >>>[71]: class A(object) : def __setattr__(self, name, value) : print "A", name ....: ....: >>>[74]: class B(A) : pass ....: >>>[75]: A().c, B().c = 1, 2 A c A c >>>[76]: A.__setattr__ = lambda s, n, v : sys.stdout.write("%s, %s, %s\n" % (s, n, v)) >>>[77]: >>>[78]: A().c, B().c = 1, 2 <__main__.A object at 0x2b3b45dfa350>, c, 1 <__main__.B object at 0x2b3b45dfa350>, c, 2 -- _____________ Maric Michaud From mensanator at aol.com Wed Sep 10 20:12:07 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 10 Sep 2008 17:12:07 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: <59f16334-e9f4-46a7-b433-654a08ffb434@k30g2000hse.googlegroups.com> On Sep 10, 5:36?pm, Terry Reedy wrote: > Mensanator wrote: > > Are there situations where the sum of an empty > > list should NOT be 0? Of course there are. > > Python Philosopy (my version, for this discussion): > ? ?Make normal things easy; make unusual or difficult things possible. > > Application: > ? ?Sum([]) == 0 is normal (90+% of cases). ?Make that easy (as it is). > ? ?For anything else: > ? ? ?if seq: s = sum(s, base) > ? ? ?else: > ? ?which is certainly pretty easy. > > > Can sum() handle those cases? > > The developers choose what they thought would be most useful across the > spectrum of programmers and programs after some non-zero amount of > debate and discussion. > > ?> ?No, it can't, I have to write > > > my own definition if I want that behaviour. > > Or wrap your calls. ?In any case, before sum was added as a convenience > for summing numbers, *everyone* has to write their own or use reduce. > > Sum(s) replaces reduce(lambda x,y: x+y, s, 0), which was thought to be > the most common use of reduce. ?Sum(s,start) replaces the much less > common reduce(lambda x,y: x+y, s, start). > > Reduce(S, s), where S = sum function, raises an exception on empty s. > So use that and you are no worse off than before. What am I doing wrong? >>> S = sum >>> S >>> s = [1,2,3] >>> type(s) >>> reduce(S,s) Traceback (most recent call last): File "", line 1, in reduce(S,s) TypeError: 'int' object is not iterable >>> reduce(S,s,0) Traceback (most recent call last): File "", line 1, in reduce(S,s,0) TypeError: 'int' object is not iterable >>> reduce(lambda x,y:x+y,s) 6 >>> s=[] >>> reduce(lambda x,y:x+y,s) Traceback (most recent call last): File "", line 1, in reduce(lambda x,y:x+y,s) TypeError: reduce() of empty sequence with no initial value This is supposed to happen. But doesn't reduce(S,s) work when s isn't empty? > > However, a problem with reduce(S,s) is that it is *almost* the same as > reduce(S,s,0). ?So people are sometimes tempted to omit 0, especially if > they are not sure if the call might be reduce(S,0,s) (as one argument > says it should be -- but that is another post). ?But if they do, the > program fails, even if it should not, if and when s happens to be empty. > > > There's no reason > > why sum([]) and sum([],0) have to mean the same thing at the > > exclusion of a perfectly valid alternative definition. > > 'Have to', no reason. ?'Should', yes there are at least three reasons. > 1. Python functions generally return an answer rather than raise an > exception where there is a perfectly valid answer to return. > 2. As a general principle, something that is almost always true should > not need to be stated over and over again. ?This is why, for instance, > we have default args. > 3. As I remember, part of the reason for adding sum was to eliminate the > need (with reduce) to explicitly say 'start my sum at 0' in order to > avoid buggy code. ?In other words, I believe part of the reason for > sum's existence is to avoid the very bug-inviting behavior you want. > > Terry Jan Reedy From lekin2 at llnl.gov Thu Sep 18 12:06:13 2008 From: lekin2 at llnl.gov (April Lekin) Date: Thu, 18 Sep 2008 09:06:13 -0700 Subject: Tkinter Bold Text Message-ID: <76vncf$1aj1ab@smtp.llnl.gov> Is there any way to highlight, bold or change the color of one word in a variable to be displayed on a Tkinter GUI? Like: material = "Plastic" introVal = "This report describes the construction of the %s." % (material) this is what I want: This report describes the construction of the Plastic. Plastic is Bold or Blue or Green Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From harald.luessen at gmx.de Fri Sep 19 12:46:01 2008 From: harald.luessen at gmx.de (Harald Luessen) Date: Fri, 19 Sep 2008 18:46:01 +0200 Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: On Thu, 18 Sep 2008 Bruno Desthuilliers wrote: ># Harald : uncomment this and run test_results. As far as I can tell, it ># doesn't yields the expected results > >## IN7 = IN[:] >## def sortk7(n): >## return n.coordinates[0] > >## def doubles7(): >## "is ordering better ? - Nope Sir, it's broken..." >## IN7.sort(key=sortk) >## SN = [] >## sn_append = SN.append >## in_len = len(IN) >## for i in xrange(in_len): >## node_i = IN[i] >## coords_i = node_i.coordinates >## for j in xrange(i+1, in_len): >## if coords_i[0] == IN[j].coordinates[0]: >## if coords_i[1] == IN[j].coordinates[1]: >## sn_append(node_i) >## else: >## break >## return SN ... >Results here (py2.5, gentoo linux, athlonxp1800, 512 ram): > > >>> test_results() >True > >>> test_times() >doubles0 : 1.55667901039 >doubles1 : 0.719144105911 >doubles2 : 0.703393936157 >doubles3 : 0.700654983521 >doubles4 : 0.706257104874 >doubles5 : 0.528184890747 >doubles6 : 0.461633205414 >doubles8 : 0.0134379863739 >doubles9 : 0.0108540058136 When you change my code then do it right. :-) You forgot to change the IN to IN7 at _every_ place. And the sortk should be sortk7 in _both_ places. I never let the code run before myself. I just wrote it in the newsreader. But now i did and I have a second version as bonus. IN7 = IN[:] def sortk7(n): return n.coordinates[0], n.coordinates[1] def doubles7(): IN7.sort(key=sortk7) SN = [] sn_append = SN.append in_len = len(IN7) for i in xrange(in_len): node_i = IN7[i] coords_i = node_i.coordinates for j in xrange(i+1, in_len): if coords_i[0] == IN7[j].coordinates[0]: if coords_i[1] == IN7[j].coordinates[1]: sn_append(node_i) else: break return SN def comp7( x, y ): return cmp( x.coordinates, y.coordinates ) def doubles7a(): IN7.sort( comp7 ) SN = [] sn_append = SN.append in_len = len(IN7) for i in xrange(in_len): node_i = IN7[i] for j in xrange(i+1, in_len): node_j = IN7[j] if comp7( node_i, node_j ) == 0: sn_append(node_i) else: break return SN Here are the results. (py2.5, WindowsXP, Pentium4, 2.6GHz, 1.5GB): My version is not so bad. doubles0 : 1.03830598582 doubles1 : 0.47943719104 doubles2 : 0.487412506338 doubles3 : 0.475924733451 doubles4 : 0.466548681466 doubles5 : 0.340487967046 doubles6 : 0.278480365521 doubles7 : 0.0953190978183 doubles7a : 0.0784233750379 doubles8 : 0.010236496538 doubles9 : 0.00742803903848 Harald From digitig at gmail.com Tue Sep 23 13:01:04 2008 From: digitig at gmail.com (Tim Rowe) Date: Tue, 23 Sep 2008 18:01:04 +0100 Subject: Not fully OO ? In-Reply-To: <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: 2008/9/23 Craig Allen : > So python may turn out to be pure OO I think that's the sort of thing the pedants would hang that hats on, too. Python isn't *pure* OO, in that it lets the programmers do non-OO if they want to, but it is *fully* OO in that it includes everything required to do OO. But maybe the original blogger meant by "fully OO" what I mean by "Pure OO"? The question I usually ask is "Does this language help me get the job done?" Python often does. That's all that really matters, isn't it? -- Tim Rowe From praveenapanch at gmail.com Mon Sep 8 05:05:46 2008 From: praveenapanch at gmail.com (Praveena P) Date: Mon, 8 Sep 2008 02:05:46 -0700 (PDT) Subject: String to hexadecimal conversion Message-ID: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Hi folks, I am new to Python... so am not too sure about how the type conversion works. I have to read a file that contains hexadecimal data and use the data further to do some arithmetic calculations. A sample of the input is : 00000000000020E0000032F800000000400022005E The problem I am facing is this: I am using f.read(2) to read a byte at a time, but the data that is read is a string rather than a number. So it kind of hampers any arithmetic operations I perform on this data... Could you please suggest some method I could use for this? Thanks guys! Praveena From gagsl-py2 at yahoo.com.ar Tue Sep 2 15:50:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 16:50:15 -0300 Subject: email.Message problem References: <20080902160417.GA20438@zephyr> Message-ID: En Tue, 02 Sep 2008 13:04:18 -0300, Corrado Gioannini escribi?: > Hi all, > i know i'm probably going to ask a very silly question, but i > can't figure out where i'm doing wrong just reading the docs. > > trying to build and send a mail message using the email.* modules > (with python 2.5). > > a simplified version of my script that breaks is this: > > mailtest.py > > messg = email.message.Message() Replace this line with: messg = email.mime.multipart.MIMEMultipart() *OR* Set the Content-Type header to "multipart/mixed" *before* anything else. -- Gabriel Genellina From fredrik at pythonware.com Sun Sep 21 05:37:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 11:37:26 +0200 Subject: Here's something interesting: sympy crashes in Python 2.6 (Windows) In-Reply-To: <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> References: <1274114a-931c-402e-b042-a16ecec36af5@i76g2000hsf.googlegroups.com> <4e045d83-a92f-473f-8f5b-9e35d18da4d1@t54g2000hsg.googlegroups.com> Message-ID: Mensanator wrote: > I'm not the one who wrote sympy, so I guess I'm not > the only one who didn't notice it. > > If it's a well known problem, then sorry I wasted > your time. Given that 2.5 explicitly warns about this specific change: >>> as = 1 :1: Warning: 'as' will become a reserved keyword in Python 2.6 it's an unknown issue only for people who has 1) never used their code under 2.5, or 2) never looks at the output produced by their programs. The PEP-5 process guarantees that "users will have at least a year to test their programs and migrate them from use of the deprecated construct to the alternative one," and Python 2.5 was released *two* years ago. So it sure looks like the SimPy folks ignored the established process. Why they've done that is probably a more interesting issue than the change itself. From peymanfaratin at gmail.com Fri Sep 5 17:55:41 2008 From: peymanfaratin at gmail.com (peyman) Date: Fri, 5 Sep 2008 14:55:41 -0700 (PDT) Subject: running python as a dameon Message-ID: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> Hi I have a Natural Language Processing (NLP) code written in python that reads into memory a large training file and then given a sentence tags it, using the training data. I want to put this NLP code on a server which handles all incoming client http requests via PHP. What I want to do is to provide the python NLP program as a service to any other PHP/Java/Ruby process request. So the mapping is http -> apache -> PHP/Java/Ruby/... -> Python NLP I can not provide this service as a shell script because of the inefficiencies of having to load into memory a large training data to every service request. So what I want to do is to provide the NLP service to other application processes as a python daemon http -> apache -> PHP/Java/Ruby/... -> Python Dameon -> Python NLP The daemon loads into memory the training data once. then every service request event invokes the appropriate NLP code in the python program. I've tried to use play around with twisted but am not making too much of a headway. What I've done in the NLP code is to do this: # filename: NLP.py def parse(sentence): structure=getentities(sentence) print 'subject: \t',' '.join(structure[0]) print 'predicate: \t',' '.join(structure[1]) print 'TE: \t\t',' '.join(structure[2]) class TLogicClass(): def __init__(self,prop): return parse(prop) then in the dameon code done this # filename: dameon.py from twisted.application import service import NLP application=service.Application("nlp") ParseService=NLP.TLogicClass("time flies like an arrow") ParseService.setServiceParent(application) but I get the following error when I run twistd -y daemon.py >> Failed to load application: TLogicClass instance has no attribute 'setServiceParent' I suspect I need to put twisted in the NLP.py but I don't know what I need to do in order to get what I want to do which is: to load into memory only once a large training data that can then be queried by another (non-python) event based process (I need "reactor" class?). thank you in advance for your help From comp.ogz at gmail.com Tue Sep 30 16:31:11 2008 From: comp.ogz at gmail.com (Oguz Yarimtepe) Date: Tue, 30 Sep 2008 23:31:11 +0300 Subject: QSessionManager example request Message-ID: <48E28C8F.4000300@gmail.com> Hi all, I am trying to write an application that will test the sleep function of the laptop. I am using pyqt for this. I need to continue to run my gui after the laptop wakes up from sleep mode so that i may continue some counters and repeat the sleep command again. I think i may use QSessionManager but i am not sure how to use it. Can someone give me a simple example with it? Oguz -------------- next part -------------- A non-text attachment was scrubbed... Name: comp_ogz.vcf Type: text/x-vcard Size: 111 bytes Desc: not available URL: From malkarouri at gmail.com Fri Sep 26 16:21:24 2008 From: malkarouri at gmail.com (malkarouri) Date: Fri, 26 Sep 2008 13:21:24 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> Message-ID: <7d9d472f-1f8e-4fe4-9647-b68bb9c86102@x41g2000hsb.googlegroups.com> On 26 Sep, 16:39, Patrick Sullivan wrote: > Hello. > > I will be using some large data sets ("points" from 2 to 12 variables) > and would like to use one class for each point rather than a list or > dictionary. I imagine this is terribly inefficient, but how much? I can't really get into details here, but I would suggest that you go ahead and try first. As you know, premature optimization is the root of all evil. General points I would suggest: - Use Numpy/Scipy (http://www.scipy.org). You will have more effeciency easier than if you try to use simply Python lists. And it is much easier to later optimize that. - Your questions of referencing classes and variables tell me that perhaps you are starting from a C background, or Java maybe? Anyway, as far as I know, it is not standard practice to write a class method (you meant a normal bound method, right?) just to access a variable. Use a normal Python variable and if you need to make it a method later turn it into a property. - Is the efficiency you are looking for is in terms of time or memory? That difference leads to different optimization tricks sometimes. - By using Numpy there is probably another advantage to you: some efficiency in the data representation, as the NumPy array stores data, say integers, without memory overhead per member (point). Just an array of integers. Of course there is additional constant memory per array which is independent of the number of elements (points) you are storing. - Generally try to think in terms of arrays of data rather than single points. If it helps, think in terms of matrices. That is more or less the design of Matlab, and Numpy is more or less similar. Now if you specify your problem further I am sure that you will get better advice from the community here. Don't focus on the details, probably the bigger picture will help. Working in graphics? Image processing? Machine Learning/Statistics/Data Mining/ etc..? -- Muhammad Alkarouri From almar.klein at gmail.com Wed Sep 24 05:02:52 2008 From: almar.klein at gmail.com (Almar Klein) Date: Wed, 24 Sep 2008 11:02:52 +0200 Subject: python 3.x third party modules In-Reply-To: References: Message-ID: Hi, I would like to look at third party modules which are python 3.0 ready. > I think that until the release version of python 3.0 is out, no one will release something. Python 3k is due in October this year, so only a few weeks from now. I would also like to know when we can expect the major 3th party packages (like numpy, wxpython, ...) to release a version for python 3.0. Can anyone say something about that? Will it take a month, a year? Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From d3vvnull at gmail.com Fri Sep 26 12:00:59 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 11:00:59 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> Message-ID: <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> So we can drop a table in an in clause? How is this a use case. Cartoons are funny but actual proof that this example using an in-clause provides an exploit would be more helpful I think. On Fri, Sep 26, 2008 at 9:50 AM, Benjamin Kaplan wrote: > > > On Fri, Sep 26, 2008 at 10:38 AM, Michael Mabin wrote: > >> I laugh in the face of danger. >> >> Give me a use case for an exploit. >> > > http://xkcd.com/327/ > > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter.anderson at internode.on.net Sat Sep 6 21:41:03 2008 From: peter.anderson at internode.on.net (Peter Anderson) Date: Sun, 07 Sep 2008 11:41:03 +1000 Subject: Learning Python In-Reply-To: References: Message-ID: <48C3312F.4040506@internode.on.net> James, I have several Python books and am currently working my way through John Zelle's PYTHON PROGRAMMING: An Introduction to Computer Science (Publisher: Franklin, Beedle & Associates, ISBN-10: 1887902996, ISBN-13: 978-1887902991). I think this is a very good introduction to both Python AND programming I would highly recommend it. If you finish the Zelle book then you can go onto Problem Solving With Algorithms And Data Structures Using Python by Bradley N. Miller and David L. Ranum (Publisher: Franklin Beedle & Associates, ISBN-10: 1590280539, ISBN-13: 978-1590280539). These are equivalent to Python 101 and 201. Regards, Peter -- *Peter Anderson* There is nothing more difficult to take in hand, more perilous to conduct, or more uncertain in its success, than to take the lead in the introduction of a new order of things?Niccolo Machiavelli, /The Prince/, ch. 6 From castironpi at gmail.com Thu Sep 25 14:50:30 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Thu, 25 Sep 2008 11:50:30 -0700 (PDT) Subject: is decorator the right thing to use? References: <48db50aa$0$3750$426a74cc@news.free.fr> <48dbc82e$0$1120$426a74cc@news.free.fr> Message-ID: <314bc9c0-3158-4055-ac5f-d5f472b460ab@34g2000hsh.googlegroups.com> On Sep 25, 1:22?pm, "Dmitry S. Makovey" wrote: > Aaron "Castironpi" Brady wrote: > > You should write it like this: > > > class B(object): > > ? ? ?@A.proxy > > ? ? ?def bmethod(self,a): > > > Making 'proxy' a class method on A. ? > > makes sense. > > > In case different A instances (do > > you have more than one BTW?) > > yep. I have multiple instances of class A, each one has properties (one per > class) of classes B, C and D: > > class A: > ? ? ? ? b=None > ? ? ? ? c=None > ? ? ? ? d=None > ? ? ? ? def __init__(self,b,c,d): > ? ? ? ? ? ? ? ? self.b=b > ? ? ? ? ? ? ? ? self.c=c > ? ? ? ? ? ? ? ? self.d=d > > ? ? ? ? ...magic with proxying methods goes here... > > class B: > ? ? ? ? def bmethod(self,x): pass # we proxy this method from A > ? ? ? ? def bmethod2(self,x): pass # this is not proxied > class C: > ? ? ? ? def cmethod(self,x): pass # we proxy this method from A > class D: > ? ? ? ? def dmethod(self,x): pass # we proxy this method from A > > a=A(B(),C(),D()) > x='foo' > a.bmethod(x) > a.cmethod(x) > a.dmethod(x) > a.bmethod2(x) # raises error as we shouldn't proxy bmethod2 > > above is the ideal scenario. > > > What you've said implies that you only have one B instance, or only > > one per A instance. ?Is this correct? > > yes. as per above code. > > > I agree that __setattr__ is the canonical solution to proxy, but you > > have stated that you want each proxied method to be a member in the > > proxy class. > > well. kind of. if I can make it transparent to the consumer so that he > shouldn't do: > > a.b.bmethod(x) > > but rather: > > a.bmethod(x) > > As I'm trying to keep b, c and d as private properties and would like to > filter which calls are allowed to those. Plus proxied methods in either one > always expect certain parameters like: > > class B: > ? ? ? ? def bmethod(self,c,x): pass > > and A encapsulates 'c' already and can fill in that blank automagically: > > class A: > ? ? ? ? c=None > ? ? ? ? b=None > ? ? ? ? def bmethod(self,c,x): > ? ? ? ? ? ? ? ? if not c: > ? ? ? ? ? ? ? ? ? ? ? ? c=self.c > ? ? ? ? ? ? ? ? b.bmethod(self,c,x) > > I kept this part of the problem out of this discussion as I'm pretty sure I > can fill those in once I figure out the basic problem of auto-population of > proxy methods since for each class/method those are going to be nearly > identical. If I can autogenerate those on-the-fly I'm pretty sure I can add > some extra-logic to them as well including signature change where > A::bmethod(self,c,x) would become A::bmethod(self,x) etc. Do you want to couple instances or classes together? If A always proxies for B, C, and D, then the wrapper solution isn't bad. If you're going to be doing any instance magic, that can change the solution a little bit. There's also a revision of the first implementation of Aproxy you posted, which could stand alone as you have it, or work as a classmethod or staticmethod. > def Aproxy(fn): > def delegate(*args,**kw): > print "%s::%s" % (args[0].__class__.__name__,fn.__name__) > args=list(args) > b=getattr(args[0],'b') > fnew=getattr(b,fn.__name__) > # get rid of original object reference > del args[0] > fnew(*args,**kw) > setattr(A,fn.__name__,delegate) > return fn def Aproxy(fn): def delegate(self,*args,**kw): print "%s::%s" % (args[0].__class__.__name__,fn.__name__) fnew=getattr(self.b,fn.__name__) return fnew(*args,**kw) setattr(A,fn.__name__,delegate) return fn From bearophileHUGS at lycos.com Sun Sep 7 09:59:46 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 7 Sep 2008 06:59:46 -0700 (PDT) Subject: doctest not seeing any of my doc tests References: <00d3d407$0$20306$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano, first of all you can try to run a minimal module, to see if your doctesting works, like: """ >>> 1 + 1 3 """ def foo(): """ >>> foo() 1 """ return 0 import doctest doctest.testmod() If that works correctly, then you can show us some more of the code and tests. Bye, bearophile From george.sakkis at gmail.com Mon Sep 29 08:41:02 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 29 Sep 2008 05:41:02 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> Message-ID: <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> On Sep 29, 2:34?am, Carl Banks wrote: > On Sep 29, 1:44?am, George Sakkis wrote: > > > > > On Sep 29, 12:08 am, Terry Reedy wrote: > > > > George Sakkis wrote: > > > > On Sep 28, 2:29 pm, process wrote: > > > > >> I have heard some criticism about Python, that it is not fully object- > > > >> oriented. > > > > > That's not a bug, it's a feature ;-) > > > > >> Why isn't len implemented as a str.len and list.len method instead of > > > >> a len(list) function? > > > > > As Terry Reedy wrote, partly history and partly practicality. There's > > > > no philosophical reason why we write "len(x)" (generic builtin), > > > > "x.append(1)" (method) or "del x[i]" (statement). The latter in > > > > particular is IMHO a design wart; there's no reason for not writing it > > > > as "x.delete(i)". > > > > As a general rule and matter of practice, methods that apply to all or > > > most classes (or all number classes) have built-in functions that call > > > the corresponding special method (or C-level slot). > > > It would be easier to justify this rule if it was more clear-cut, and > > specifically if it was applied only to methods that are available to > > *all* classes (such as type() and getattr()) rather than the ill- > > defined "most classes". > > That wasn't your original claim, though. ?You claimed there was no > philosophical reason, then Terry gave you one, then you said, well > there's no clear cut reason. ?Unless you define "philosophical" as > "clear cut" (a definition I'm not sure many would agree with). I won't argue about that, just s/philosophical/clear cut/ then. > Anyway, you are right to claim there's no clear cut distinction, just > as there's never any clear cut distinction over whether something > should be an operator or not. Addition is only available to the ill- > defined "most classes", yet not only is it not a method, it has its > own syntax. ?There's no clear cut distinction there, it's just a > design decision. > > Likewise, making len() into a function is just a > design decision, that len is a common enough operation that it need > elevated status. It's really nothing more. Python wouldn't suffer > much regardless if len is a method, a built-in function, or an > operator with its own syntax. I'm not quite sure it's exactly the same. The distinction between operators and non-operators is syntactically clear cut: operators consist of punctuation characters and (binary operators) use infix syntax. Yes, from a pure semantics standpoint this distinction is redundant; a language could support a method-only syntax, but there is much value in using terse intuitive symbols for certain domains (with math being the prominent one). For example I would be much less opposed to len() being defined as, say, |x| if "|...|" was a valid operator. I don't see the same value in creating a distinction between methods and builtin functions unless the latter are truly generic (and even then I wouldn't mind having them as methods of the base object class, e.g. object.type()). Having a builtin len(x) delegate to x.__len__() seems harder to justify. George From bj_666 at gmx.net Fri Sep 19 03:44:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Sep 2008 07:44:06 GMT Subject: Python newbie References: Message-ID: <6jh3i5F376gaU1@mid.uni-berlin.de> On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote: > There are several questions: > > 1) Why is the array "a" unchanged after undergoing a transformation with > map? Because `map()` creates a new list and doesn't change the elements in `a`. > 2) Why is it illegal to pass a built-in function "print" to map? Because ``print`` isn't a function but a keyword. This will be changed in Python?3.0. On the other hand this use case is discouraged because `map()` builds a new list with the return value of the given function. So you would build a list full of `None`\s just for the side effect. > 3) Why is the array "a" unchanged after undergoing an explicit > transformation with the "for" loop? Because there is no explicit transformation. The loop binds elements to the name `x` in your example and within the loop you rebind that name to another value. Neither the name `x` nor the objects bound to it have any idea that the object might be referenced in some container object. > 4) Is there an equivalent to \$a (Perl "reference") which would allow me > to decide when a variable is used by value and when by reference? No, variables in Python are always name to object bindings. Don't think of variables as boxes with names on it where you put objects in, or references to another box. Think of objects and sticky notes with names on it. > How can I make sure that > for x in a: x=2*x > > actually changes the elements of the array "a"? Well, actually change the elements. ;-) Either: for index, item in enumerate(sequence): sequence[index] = func(item) Or: sequence[:] = map(func, sequence) But the need to do so doesn't seem to be that frequent. Usually one just builds a new list instead of altering an existing one. Ciao, Marc 'BlackJack' Rintsch From mal at egenix.com Tue Sep 30 12:30:22 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 30 Sep 2008 18:30:22 +0200 Subject: how to find out the version of a certain installed package In-Reply-To: References: Message-ID: <48E2541E.7030605@egenix.com> On 2008-09-30 18:17, Christophe wrote: > Hi, > > In a projecet I'm making using pycrypto, I need to find out the > current installed version of pycrypto. After looking around, I found > out that "pkg_resources.requires("pycrypto") will give me a string > containing the version number, but is this the only way to do it or > are there other ways? Most packages have a .__version__ attribute in their top-level package dir which you can query. You do have to import the base package, though, in order to find out. Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Sep 30 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From alan.isaac at gmail.com Tue Sep 2 13:18:58 2008 From: alan.isaac at gmail.com (Alan G Isaac) Date: Tue, 02 Sep 2008 17:18:58 GMT Subject: Numeric literal syntax In-Reply-To: <6i56cpFor2puU1@mid.individual.net> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <6i56cpFor2puU1@mid.individual.net> Message-ID: <6Aevk.331$1a2.14@trnddc04> > On 02 Sep 2008 06:10:51 GMT, Steven D'Aprano wrote: >> At the risk of bike-shedding, > [snip] Peter Pearson wrote: > (startled noises) It is a delight to find a reference to > that half-century-old essay (High Finance) by the wonderful > C. Northcote Parkinson, but how many readers will catch the > allusion? It is pretty common geek speek: http://en.wikipedia.org/wiki/Color_of_the_bikeshed Cheers, Alan Isaac From fredrik at pythonware.com Wed Sep 10 07:13:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 13:13:46 +0200 Subject: Catching subprocess stdout stream In-Reply-To: <9deaf3ef-2103-444f-bb46-309aee7045c5@r15g2000prd.googlegroups.com> References: <00b9dc86-e002-4e2c-a686-39d2dd1016b9@m3g2000hsc.googlegroups.com> <9deaf3ef-2103-444f-bb46-309aee7045c5@r15g2000prd.googlegroups.com> Message-ID: Sean DiZazzo wrote: > while aThread.isAlive() or not aQueue.empty(): > l = aQueue.get().rstrip() > fo.write(l) > print l > > fo.close() > > A bit of fun for a sleepless night... and unless you add a call to time.sleep somewhere in that loop, you'll keep your CPU up all night as well... From callen314 at gmail.com Tue Sep 23 17:14:59 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 23 Sep 2008 14:14:59 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: <44c069c5-473d-4f62-9997-5b13102e7f8b@b30g2000prf.googlegroups.com> > if they want to, but it is *fully* OO in that it includes everything > required to do OO. But maybe the original blogger meant by "fully OO" > what I mean by "Pure OO"? it seems to me this is what was meant... pure OO, AND forced to use it. My personal feeling is that python is multiparadigmed and I'm more than fine with that. BUT, I am going to hold onto what I've noticed which is that Python seems to use OO deeply, well into the interpreter, and that the procedural styles available at the Python source level pretty much are built on top of this OO model, given you accept a module as an object, which it seems to be within the source code... but in the end, it's just words and the most important thing is that python is a tool you can use to make a computer do what you want, and whatever you call it may just be a distraction. cheers. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 25 02:11:24 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 06:11:24 GMT Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> Message-ID: <00eb2560$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: > Just a thought, your minimum sleep time is probably limited by the > resolution of the system "HZ" clock. Type > > less /proc/config.gz $ less /proc/config.gz /proc/config.gz: No such file or directory What OS are you using? -- Steven From mfajer at gmail.com Sat Sep 27 17:50:26 2008 From: mfajer at gmail.com (Mikolai Fajer) Date: Sat, 27 Sep 2008 14:50:26 -0700 Subject: Abstract Base Class register function Message-ID: <3ff66ae00809271450l13ca2fc5k4b3fec10c1051496@mail.gmail.com> I have been experimenting with the abc module in py3k and thought about using the register method of an ABC as a class decorator: import abc class MyABC(metaclass=abc.ABCMeta): pass @MyABC.register class MySub(): pass This doesn't work because the register method returns None. It would be a fairly simple modification to have this work: def register(cls, subclass): """Register a virtual subclass of an ABC.""" ... etc ... return subclass What do people think of this behavior? -- -Mikolai Fajer- From robert.kern at gmail.com Tue Sep 23 15:17:15 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 14:17:15 -0500 Subject: Python is slow? In-Reply-To: References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > sturlamolden: >> Sure I could show you the code, Python and C++, if I had a place to post it.< > > I think the Python version suffices. If it's not too much private you > may post the single minimal/reduced runnable Python module here, it > will be deleted in some time (if you want you can also use a private > paste): > http://codepad.org/ You could also drop it on the scipy.org wiki in the Cookbook category. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From tino at wildenhain.de Sun Sep 28 07:00:02 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sun, 28 Sep 2008 13:00:02 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> References: <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> <48DE3FC7.4030307@wildenhain.de> <170543c70809271111h304e6d03w6be953dfe69414c5@mail.gmail.com> <48DEA603.9020507@wildenhain.de> <170543c70809271652m1b91fd91y244c68d830617f9e@mail.gmail.com> Message-ID: <48DF63B2.2020408@wildenhain.de> Michael Mabin wrote: > I'm exhausted, so I'll just shut up about this after a few final words. Thank you for your time :-) > 1. "edits" is used in data warehousing to describe data scrubbing or > filtering of fields in records that are used as input sources for > loading into data warehouses. It's a term that goes way back to batch > processing on the mainframe, so it's been used this way for a long time. > Sometimes we use 'validation' interchangeably with 'edit' but our use of > validation usually involves a check of input data against business rules > and not type or range checking which we consider 'edits'. So maybe > you're not used to hearing the term used this way, but it is a variation > perhaps of what you're used to. And so on and so on in the regular top posting manner... Just to give you some thoughts again: your solution might be valid for you in your controlled environment. Yet you just presented it to the OP without telling him the limits of when this can be used. And this is outright dangerous. If one sees this without comment and without your background she will run into problems sooner or later. So my suggestion was to either don't tell people such solutions at all or tell them exactly under which circumstances they might be used. Still I think nailing the problem at the apropriate place is a habit which should generally devloped - as in your example an additional int() would have fixed it - but still it would not work if you want to deal with arbitrary strings. So its good to make suggestions but pretty please think ahead how someone would use it instead of investing all your energy into defending dangerous programming practice. With "we in python" I referred to a fairly amount of literature about programming in python and it design patterns. Nothing me personally. Ah and some final words to the controlleness of datawarehouse applications and similar things: by the time you are designing such a solutuion you will never know what future applications will be developed around it so its always best to be prepared. "Data scrubbing" seems a common idea but in fact its very hard to do it right due to the nature of different systems using different quoting logic. "Dont trust your input" is a habit not only applicable to web programming - in fact the company I work for does not do much web application but input validation is something we get even audited for. Nevertheless I wish you a very good weekend :-) Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From dancing.cataldo at gmail.com Tue Sep 23 16:08:27 2008 From: dancing.cataldo at gmail.com (Phil Cataldo) Date: Tue, 23 Sep 2008 22:08:27 +0200 Subject: Does anybody use this web framework ? Message-ID: <48d94cbc$0$964$ba4acef3@news.orange.fr> Hi, I just found this new? python web framework (http://pypi.python.org/pypi/nagare/0.1.0). Does anybody know or use it ? Regards, Phil From dieter at handshake.de Thu Sep 18 13:10:15 2008 From: dieter at handshake.de (Dieter Maurer) Date: 18 Sep 2008 19:10:15 +0200 Subject: Zsi interoperability In-Reply-To: References: <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: "Marco Bizzarri" writes on Mon, 15 Sep 2008 20:26:27 +0200: > On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel wrote: > > Mailing List SVR wrote: > >> I have to implement a soap web services from wsdl, the server is > >> developed using oracle, is zsi or some other python library for soap > >> interoperable with oracle soa? > > > > No idea, but I'd definitely try soaplib before ZSI. > > > > Stefan > > I'm working on a project where I need to write a client for SOAP with > Attachments; I can see ZSI does not support it The ZSI documentation (2.0) says that SOAP attachments are supported -- but I never tried it. Dieter From gminick at bzt.bzt Thu Sep 4 11:51:19 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 4 Sep 2008 15:51:19 +0000 (UTC) Subject: overwrite set behavior References: Message-ID: On Thu, 4 Sep 2008 12:06:14 +0200, Marco Bizzarri wrote: >> As far as I understand you, you need descriptors: >> http://users.rcn.com/python/download/Descriptor.htm > I know descriptors a litte, Wojtek, but didn't use them often; can you > elaborate a little more on your idea? Marco, I think that I misunderstood the OP, but I was thinking about immutable (or set-once) attributes. Something like this: --- class SetOnce(object): def __init__(self): self._attr1 = "" self._attr1flag = False def setatt(self, x): if self._attr1flag: raise ValueError("attribute already set") self._attr1flag = True self._attr1 = x def getatt(self): return self._attr1 attr1 = property(getatt, setatt) a = SetOnce() a.attr1 = 1 print a.attr1 try: a.attr1 = 2 except ValueError: print a.attr1 --- $ python immutattr.py 1 1 $ -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From kay.schluehr at gmx.net Sun Sep 21 00:39:11 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 20 Sep 2008 21:39:11 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <2c0a8279-e888-4ae5-90a2-f2f1bb137607@x41g2000hsb.googlegroups.com> Message-ID: <8d30318b-2c54-4d4e-b333-016a0806c1ad@y38g2000hsy.googlegroups.com> On 20 Sep., 23:07, "Aaron \"Castironpi\" Brady" wrote: > On Sep 20, 3:22 pm, Kay Schluehr wrote: > > > > > On 20 Sep., 18:33, Bruno Desthuilliers > > > wrote: > > > The following definitions are AFAIK the only commonly accepted > > > definitions about OO: > > > > 1/ an object is defined by identity, state and behaviour > > > 2/ objects interacts by sending messages each other > > > 3/ an OO program is made of interacting objects > > > > I let you find out whether Python meets these 3 definitions - and if > > > Java does (hint : in Python, everything you can bind to a name is an > > > object - this is not true in Java or C++). > > > This is correct but it detracts from a more general problem of > > language "paradigms". > > > Assume you type > > > >>> 2+2 > > > 4 > > > Now you are free to interpret this as a simple, primitive arithmetic > > operation but you can also claim that 2 sends an __add__ message to 2. > > Hereby the state of the 2 objects are not altered but a new 4 object > > is created. OO babble is more impressive isn't it? > > > Actually it is simply wrong in the mentioned case and here is the > > proof: > > > def foo(): > > return 2+2 > > > import dis > > dis.dis(foo) > > > 2 0 LOAD_CONST 2 (4) > > 3 RETURN_VALUE > > > OO is a heuristic method used to understand the semantics of a > > programming language. It can also inspire language design but as > > you've rightly said: jugde yourself and see how far you get with it. > > > Applying OO on interpreter level is by no means a sign of a high > > quality implementation whereas structuring programs in the large will > > likely benefit from class based organization and encapsulation. Of > > course one can also reverse the value hierarchy and find perverse joy > > in having a pure OO language but apply monkey patching everywhere. I > > suppose you know which language I'm talking about... > > It sounds like you think that you -can- write OO programs in Python, > but you don't have to. I agree. The whole point of OO is providing high level ( system level ) not low level ( interpreter level ) semantics. Partitioning a system into isolated and communicating objects is a strong and important metaphor. Recently there were some comments on the web that mentioned Erlang to be pretty much OO in this respect although Erlang is functional and has no base level notion of an "object". It's even well known that Joe Armstrong holds low opinions about the entire object business. Notice that I believe that the popular meme that OO is "bolted on" Python has little if nothing to do with OO itself but with API consistency. When people have to type len(x) instead of x.len() this breaks their expectations on how the language has to behave. From psaffrey at googlemail.com Mon Sep 22 14:47:03 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Mon, 22 Sep 2008 11:47:03 -0700 (PDT) Subject: Job queue using xmlrpc and threading Message-ID: I'm trying to implement an application that will listen for requests, run them when they are present but also be able to add new requests even while it's running. I've tried to do this using the thread and xmlrpc modules - the idea is that an XML-RPC exposed object tell the queue thread object to add a job. If there are no jobs running, it creates a file, adds the new job to the end and then another consumption thread starts working through the jobs in the file. New jobs coming in are just added to the end of the file by the queue thread. Unfortunately, I can't get it to work. The problem is that the consumption thread seems to read the job queue before it gets written, even though I've used a lock. I've also had the application get to the stage where it ignores ctrl-c, which is a little worrying - I fear it doesn't bode well for future stability... I don't have a lot of experience with multi-threaded applications, so I may well have chosen a poor approach. I've posted the code below. It's in three parts, the job queue, the manager that listens for new requests and an application to add jobs to the queue. Sorry for the long listings... Any guidance gratefully received, Peter === testqueue.py: import thread import time import shutil import os class JobQueue: def __init__(self, filename): self.queuefile = filename self.jobthread = 0 # lock for the jobfile queue file self.jfqlock = thread.allocate_lock() def addJob(self, jobfileuri, email): self.jfqlock.acquire() if not self.jobthread: print "starting jobfile consumption thread" if os.access(self.queuefile, os.R_OK): print "cleaning stale jobfile queue file" try: os.remove(self.queuefile) except: print "problem removing jobfile queue file" raise self.jobthread = thread.start_new_thread(self.main, ()) else: print "using existing jobfile consumption thread in file", self.queuefile fh = open(self.queuefile, "a") # choose "::::" as a delimiter print >> fh, jobfileuri + "::::" + email self.jfqlock.release() return 1 def main(self): while 1: self.jfqlock.acquire() rfh = open(self.queuefile, "r") # breakpoint() finput = rfh.readline() print "found:", finput if not finput: print "finished jobfiles. Closing thread" rfh.close() self.jobthread = 0 self.jfqlock.release() return else: print "found jobfile in queue: attempting to run" # most of this is to shift up the lines in the file tmpname = self.queuefile + ".tmp" wfh = open(tmpname, "w") line = rfh.readline() while line: wfh.write(line) line = rfh.readline() wfh.close() rfh.close() shutil.move(tmpname, self.queuefile) self.jfqlock.release() # lop off the trailing line break print print "***run Starting***" try: self.runJob(finput[:-1]) print "***run finished***" except: print "***run failed***" print def runJob(self, job): time.sleep(2.0) print "running job", job if not report: print "some problem with run. Cannot mail out report" return === queuemanager.py from testqueue import JobQueue from SimpleXMLRPCServer import * class QM: def __init__(self, filename): self.jq = JobQueue("queue.txt") def addJob(self, jobname): self.jq.addJob(jobname, "tester at testdomain") if __name__=="__main__": qm = QM("jobqueue.txt") rpcserver = SimpleXMLRPCServer(("localhost", 8000)) rpcserver.register_instance(qm) rpcserver.serve_forever() === addjob.py: import xmlrpclib import sys server = "localhost" port = 8000 serveradd = "http://%s:%s" % (server, port) manager = xmlrpclib.ServerProxy(serveradd) jobname = sys.argv[1] manager.addJob(jobname) From rafesacks at gmail.com Tue Sep 9 23:56:43 2008 From: rafesacks at gmail.com (Rafe) Date: Tue, 9 Sep 2008 20:56:43 -0700 (PDT) Subject: Clearing a session and reload() problem (with repro error) References: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> Message-ID: <067abd3f-0d02-46e8-8d26-d85f20fa2e3a@s9g2000prg.googlegroups.com> On Sep 9, 11:03 pm, "Gabriel Genellina" wrote: > En Mon, 08 Sep 2008 05:37:24 -0300,Rafe escribi?: > ... > This dependency between modules, applied to all modules in your project, > defines a "dependency graph". In some cases, one can define a partial > ordering of its nodes, such that no module depends on any other module > *after* it (it may depend only on modules *before* it). Look for > "topological sort". > > Doing that in the generic case is not easy. If you *know* your > dependencies, reload the modules in the right order by hand. > ... > -- > Gabriel Genellina Hi Gabriel, Thank you for clarifying and re-presenting parts of my case. I appreciate the time. I was hoping there would be a way to just wipe out the module cache and let it get rebuilt by executing my code (since I'm not using reload as part of my program, but rather, to test it in an environment where I cannot restart the Python session). I have been keeping a diagram of my module inheritance to make sure it is as clean as possible, so I could just right a list of reloads as you suggest. However, one of the sub-packages is designed to allow users to add more modules. Because these get dynamically imported, a guess I could add an argument to the reload function to allow a user to give the 'add-on' module they are working on... so much work just to get a clean environment... Separate of my program, I was really hoping to write a generic reload tool for anyone developing in the same application as I am. I just don't see a way to trace import dependencies in systems which include dynamic imports. Any ideas? Thanks again, - Rafe From rokwok at newsguy.com Thu Sep 25 06:18:25 2008 From: rokwok at newsguy.com (Ronnie Kwok) Date: Thu, 25 Sep 2008 18:18:25 +0800 Subject: Connecting to SMB share in python References: Message-ID: <2008092518182581491-rokwok@newsguycom> Thank you for the reply! Yes, I am running the script under linux and it will be doing some processing before copying it over to the samba mount. It's totally fine to mount it with os.sys(...) approach but I am just thinking if there's other option. ronnie On 2008-09-25 16:36:35 +0800, Tim Golden said: > Ronnie Kwok wrote: >> Hello, >> >> I am trying to write a script that copy files from my local machine to a samba >> share. > > > Can't you just mount the share (albeit temporarily) and copy > the files over in the normal way? You haven't said what OS > you're on, but I'm assuming Linux otherwise you'd simply be > talking about a Windows share and copying to a UNC. > > TJG From samslists at gmail.com Thu Sep 18 22:32:47 2008 From: samslists at gmail.com (Sam) Date: Thu, 18 Sep 2008 19:32:47 -0700 (PDT) Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> Message-ID: For those that are interested, but don't want to bother running the program themselves, here's the output I get. Trying: http://slashdot.org http://slashdot.org - Apache/1.3.41 (Unix) mod_perl/1.31-rc4 (deflate) Errored out on this site. Trying: http://www.hotmail.com http://www.hotmail.com - Microsoft-IIS/6.0 (deflate) Errored out on this site. Trying: http://www.godaddy.com http://www.godaddy.com - Microsoft-IIS/6.0 (deflate) Errored out on this site. Trying: http://www.linux.com http://www.linux.com - Apache/2.2.8 (Unix) PHP/5.2.5 (deflate) Errored out on this site. Trying: http://www.lighttpd.net http://www.lighttpd.net - lighttpd/1.5.0 (deflate) Errored out on this site. Trying: http://www.kenrockwel.com http://www.kenrockwel.com - lighttpd (deflate) Able to decompress...went from 414 to 744. On Sep 18, 7:29?pm, Sam wrote: > On Sep 18, 2:10?pm, "Gabriel Genellina" > wrote: > > > En Tue, 16 Sep 2008 21:58:31 -0300, Sam escribi?: > > The code is correct - try with another server. I tested it with a ? > > LightHTTPd server and worked fine. > > Gabriel... > > I found a bunch of servers to test it on. ?It fails on every server I > could find (sans one). > > Here's the ones it fails on: > slashdot.org > hotmail.com > godaddy.com > linux.com > lighttpd.net > > I did manage to find one webserver it succeeded on---that is > kenrockwel.com --- a domain squatter with a typoed domain of one of my > favorite photographer's websites (the actual website should be > kenrockwell.com) > > This squatter's site is indeed running lighttpd---but it appears to be > an earlier version, because the official lighttpd site fails on this > test. > > We have all the major web servers failing the test: > * Apache 1.3 > * Apache 2.2 > * Microsoft-IIS/6.0 > * lighttpd/1.5.0 > > So I think it's the python side that is wrong, regardless of what the > standard is. > > What should I do next? > > I've rewritten the code to make it easier to test. ?Just run it as is > and it will try all my test cases; or pass in a site on the command > line, and it will try just that. > > Thanks! > > #!/usr/bin/env python > """Put the site you want to test as a command line parameter. > Otherwise tests the list of defaults.""" > > import urllib2 > import zlib > import sys > > opener = urllib2.build_opener() > opener.addheaders = [('Accept-encoding', 'deflate')] > > try: > ? ? sites = [sys.argv[1]] > except IndexError: > ? ? sites = ['http://slashdot.org', 'http://www.hotmail.com', > ? ? ? ? ? ? ?'http://www.godaddy.com', 'http://www.linux.com', > ? ? ? ? ? ? ?'http://www.lighttpd.net', 'http://www.kenrockwel.com'] > > for site in sites: > ? ? print "Trying: ", site > ? ? stream = opener.open(site) > ? ? data = stream.read() > ? ? encoded = stream.headers.get('Content-Encoding') > ? ? server = stream.headers.get('Server') > > ? ? print " ?%s - %s (%s)" % (site, server, encoded) > > ? ? if encoded == 'deflate': > ? ? ? ? before = len(data) > ? ? ? ? try: > ? ? ? ? ? ? data = zlib.decompress(data) > ? ? ? ? ? ? after = len(data) > ? ? ? ? ? ? print " ?Able to decompress...went from %i to %i." % > (before, after) > ? ? ? ? except zlib.error: > ? ? ? ? ? ? print " ?Errored out on this site." > ? ? else: > ? ? ? ? print " ?Data is not deflated." > ? ? print From google at mrabarnett.plus.com Thu Sep 11 13:46:27 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Sep 2008 10:46:27 -0700 (PDT) Subject: Enumerating ordered expat attributes with tuplets? References: <6a93d2f4-3a01-4921-87cc-eea25bccbd5c@e39g2000hsf.googlegroups.com> Message-ID: On Sep 11, 4:48?pm, Manuel Ebert wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Ah, well. Don't know whether it meets your aesthetic standards, but: > ?>>> my_list = ['tree', 'hug', 'flower', 'hug', 'bear', 'run'] > ?>>> my_list[0:len(a):2] > ['tree', 'flower', 'bear'] > ?>>> my_list[1:len(a):2] > ['hug', 'hug', 'run'] > > and hence > > ?>>> zip(my_list[0:len(a):2], my_list[1:len(a):2]) > [('tree', 'hug'), ('flower', 'hug'), ('bear', 'run')] > > and furthermore > > ?>>> for a, b in zip(my_list[0:len(a):2], my_list[1:len(a):2]): > ... ? ? print a, b > ... > tree hug > flower hug > bear run > > or the slightly less obfuscated: > > ?>>> for index in range(0, len(my_list), 2): > ... ? ? print my_list[index], my_list[index + 1] > ... ? ? > tree hug > flower hug > bear run > [snip] I don't know what the "len(a)" is, but the end position defaults to the end: >>> zip(my_list[0::2], my_list[1::2]) [('tree', 'hug'), ('flower', 'hug'), ('bear', 'run')] From arnodel at googlemail.com Tue Sep 23 14:25:53 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 23 Sep 2008 11:25:53 -0700 (PDT) Subject: Detecting the first time I open/append to a file References: <695b1521-4164-4197-86ca-fcbc250b97dd@m45g2000hsb.googlegroups.com> Message-ID: <53d810e4-9829-4a88-94f5-32d849ee0c55@x35g2000hsb.googlegroups.com> On Sep 23, 7:02?pm, tkp... at hotmail.com wrote: > I have a simulation that runs many times with different parameters, > and I want to aggregate the output into a ?single file with one rub: I > want a header to be written only the first time. My program looks a > bit like this: > > def main(): > ? ? for param in range(10): > ? ? ? ? simulate(param) > > def simulate(parameter): > ? ? 'Lots of code followed by: > ? ? with open(summaryFn, 'ab') as f: > ? ? ? ? writer = csv.writer(f) > ? ? ? ? writer.writerow(header) def simulate(parameter): 'Lots of code followed by: with open(summaryFn, 'ab') as f: writer = csv.writer(f) writer.writerow(header) writer.writerow(Sigma) > ? ? ? ? writer.writerow(Sigma) > > If I can sense that the file is being created in the first iteration, > I can then use an if statement to decide whether or not I need to > write the header. Question: how can I tell if the file is being > created or if this its the first iteration? It's unrealistic to test > the value of the parameter as in the real problem, there are many > nested loops in main, and the bounds on the loop indices may change. > > Thanks in advance for your assistance > > Thomas ?Philips You can use he os.path module: appending = os.path.exists(summaryFn) with open(summaryFn, 'ab') as f: writer = ... if not appending: writer.writerow(header) writer.writerow(Sigma) But if you only write to the file in one code location, you can set a flag. HTH -- Arnaud From peke at iki.fi Mon Sep 22 05:25:58 2008 From: peke at iki.fi (Pekka Laukkanen) Date: Mon, 22 Sep 2008 12:25:58 +0300 Subject: A bit weird dictionary behavior Message-ID: Hello, just noticed this: Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> {1: 2} {1: 2} >>> {True: False} {True: False} >>> {1: 2, True: False} {1: False} This must be because >>> True == 1 and True in {1: 2} True but it still doesn't feel exactly right. Would it be worth submitting a bug? Cheers, .peke From sniipe at gmail.com Tue Sep 2 04:17:21 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Tue, 2 Sep 2008 01:17:21 -0700 (PDT) Subject: How to print first(national) char from unicode string encoded inutf-8? References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com><7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> Message-ID: On 2 Wrz, 06:05, "Mark Tolonen" wrote: > "Marco Bizzarri" wrote in message > > news:mailman.331.1220276398.3487.python-list at python.org... > > > > > On Mon, Sep 1, 2008 at 3:25 PM, wrote: > > >> When I do ${urllib.unquote(c.user.firstName)} without encoding to > >> latin-1 I got different chars than I will get: no ?ukasz but ? ukasz > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > > That's crazy. "string".encode('latin1') gives you a latin1 encoded > > string; latin1 is a single byte encoding, therefore taking the first > > byte should be no problem. > > > Have you tried: > > > urlib.unquote(c.user.firstName)[0].encode('latin1') or > > > urlib.unquote(c.user.firstName)[0].encode('utf8') > > > I'm assuming here that the urlib.unquote(c.user.firstName) returns an > > encodable string (which I'm absolutely not sure), but if it does, this > > should take the first 'character'. > > The OP stated that the original string was "encoded in UTF-8 and > urllib.quote()", so after urllib.unquote the string is in UTF-8 format. > This must be decoded into a Unicode string before removing the first > character: > > urllib.unquote(c.user.firstName).decode('utf-8')[0] > > The next problem is that the character in the OP's example string '?' is not > present in the latin-1 encoding, but using utf-8 encoding demonstrates that > the full two-byte UTF-8 encoded character is collected: > > >>> import urllib > >>> name = urllib.quote(u'?ukasz'.encode('utf-8')) > >>> name > '%C5%81ukasz' > >>> urllib.unquote(name).decode('utf-8')[0].encode('utf-8') > '\xc5\x81' > > -Mark @Mark, when I tried urllib.unquote(c.user.firstName).decode('utf-8') [0].encode('utf-8'), I received this message: >> return render('/reports/create_report_step2.mako') Module pylons.templating:344 in render << **cache_args) return pylons.buffet.render(template_name=template, fragment=fragment, format=format, namespace=kargs, **cache_args) >> format=format, namespace=kargs, **cache_args) Module pylons.templating:229 in render << log.debug("Rendering template %s with engine %s", full_path, engine_name) return engine_config['engine'].render(namespace, template=full_path, **options)>> **options) Module mako.ext.turbogears:49 in render << info.update(self.extra_vars_func()) return template.render(**info) >> return template.render(**info) Module mako.template:114 in render << declared by this template's internal rendering method are also pulled from the given *args, **data members. members.""" return runtime._render(self, self.callable_, args, data) def render_unicode(self, *args, **data):>> return runtime._render(self, self.callable_, args, data) Module mako.runtime:287 in _render << context = Context(buf, **data) context._with_template = template _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) return context.pop_buffer().getvalue()>> _render_context(template, callable_, context, *args, **_kwargs_for_callable(callable_, data)) Module mako.runtime:304 in _render_context << # if main render method, call from the base of the inheritance stack (inherit, lclcontext) = _populate_self_namespace(context, tmpl) _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) else: # otherwise, call the actual rendering method specified>> _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) Module mako.runtime:337 in _exec_template << error_template.render_context(context, error=error) else: callable_(context, *args, **kwargs)>> callable_(context, *args, **kwargs) Module _reports_create_report_step2_mako:57 in render_body << context.write(filters.decode.utf8(urllib.unquote(str(c.period.end)))) context.write(u' + ') context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8') [0].encode('utf-8'))) context.write(filters.decode.utf8(urllib.unquote(str(c.user.secondName) [0:1]))) context.write(u'\r\n > > > Try %% :) > > Christian > > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks Garry & Christian. It worked. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Mon Sep 29 16:56:08 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 29 Sep 2008 16:56:08 -0400 Subject: Music knowledge representation In-Reply-To: <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> <20080929124940.8c1c82e8.darcy@druid.net> <8f67b6f80809291129y26fb4cedw5efef309422bc3c5@mail.gmail.com> Message-ID: <20080929165608.b7b87b60.darcy@druid.net> On Mon, 29 Sep 2008 20:29:44 +0200 "Mr.SpOOn" wrote: > > Couldn't the note class simply have a list of all the notes and have a > > simple method calculate the actual pitch? > > That's not really how it works. There exists just 12 octave > independent pitch classes. This means that there is a pitch class C > with all possible Cs. There ambiguities with accidentals, because > different named notes fall in the same pitch class. The difference is > important for the musical theory, because C# and Db belongs to the > same pitch class (actually they are the same note, they sounds > completely identical -- because on the piano you play them pressing > the same key), but in a scale they have a very different role. Sure, they are enharmonically identical but in our tempered scale. That's why my example showed it as (note, octave, accidental) rather than a specific note. It would differentiate between these. > For example, the interval C F# is an "augmented fourth", because what > really matters are the natural note (C and F), and their distance if > 4. Then it is augmented due to the #- > > But the interval C Gb (Gb is the same as F#) is a "diminished fifth". This is true. My simple example would not have dealt with this. The arguments would have to be the full tuple rather than the actual pitch. > So I can't list all pitches. You can but you can't store them as raw pitches. > > def interval(self, lower, higher) > > if lower > higher: > > # uncomment one of the two following lines depending > > # on the behaviour you want > > #lower,higher = higher,lower > > #higher += 12 > > > > # could use some error trapping > > return self.interval_name[higher - lower] > > > > Note that lower and higher could be a note object that you have to > > convert to integers first. > > I can't estabilish which note is higher, because all the analysis part > is octave independent. Anyway thanks for the ideas. I'm not sure I understand this. You either have to assume that the first note is the root or the lower one is. What other options are there? It sounds like your requirement is "higher += 12" or some variant. It also depends on whether you need to deal with things like ninths and thirteenths. Anyway, I was just tossing out ideas. You know what your requirements are better than I. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From michael at stroeder.com Thu Sep 25 13:46:14 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Thu, 25 Sep 2008 19:46:14 +0200 Subject: Lotus Domino and Python via DIIOP or similar? Message-ID: <7cvsq5-e5p.ln1@nb2.stroeder.com> HI! Anybody here with experience in accessing Lotus Domino with Python via DIIOP? In particular I'd like to be able to register Notes users with a Python script. Preferrably without having to use Win32 COM although it would be better than nothing. Adding address Notes book entries via LDAP is possible but AFAIK does not lead to full Notes users (with mailbox and Notes-ID file). Ciao, Michael. From gagsl-py2 at yahoo.com.ar Tue Sep 30 20:32:28 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 21:32:28 -0300 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: En Mon, 29 Sep 2008 19:04:18 -0300, Ivan Reborin escribi?: > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? I agree that using NumPy is the way to go if you're going to do lots of array calculations. But a plain Python code would look like this (more comprehensible than other posted versions, I hope): --- begin code --- def read_group(fin, rows_per_group): rows = [] for i in range(rows_per_group): line = fin.readline() row = [float(x) for x in line.split()] rows.append(row) fin.readline() # skip blank line return rows # simulate a file using a string instead # actual code would use: fin = open(filename) from StringIO import StringIO fin = StringIO("""1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 """) # read 2 groups of 3 lines each matrix = [read_group(fin, 3) for k in range(2)] print matrix --- end code --- A more compact version of read_group (collapsing all rows.append onto the outer list comprehension): --- begin code --- def read_group(fin, rows_per_group): rows = [[float(x) for x in fin.readline().split()] for i in range(rows_per_group)] fin.readline() # skip blank line return rows --- end code --- -- Gabriel Genellina From erikwickstrom at gmail.com Thu Sep 18 17:33:25 2008 From: erikwickstrom at gmail.com (erikcw) Date: Thu, 18 Sep 2008 14:33:25 -0700 (PDT) Subject: Launching a subprocess without waiting around for the result? Message-ID: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Hi, I have a cgi script where users are uploading large files for processing. I want to launch a subprocess to process the file so the user doesn't have to wait for the page to load. What is the correct way to launch subprocess without waiting for the result to return? Thanks! From mark at thomaszone.com Mon Sep 15 14:32:16 2008 From: mark at thomaszone.com (Mark Thomas) Date: Mon, 15 Sep 2008 11:32:16 -0700 (PDT) Subject: ElementTree oddities References: Message-ID: Fredrik is correct, the text attribute only contains text before a child element; tail contains the rest. It is indeed rather odd. For comparison, here's how you would do it in lxml (http://codespeak.net/ lxml/index.html), a library which supports XPath: from lxml import etree tree = etree.fromstring('Bar:') print ' '.join(tree.xpath('//text()')) From castironpi at gmail.com Sun Sep 28 17:22:08 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 14:22:08 -0700 (PDT) Subject: generate random digits with length of 5 References: Message-ID: On Sep 28, 4:08?pm, Michael Str?der wrote: > Gary M. Josack wrote: > > Aaron "Castironpi" Brady wrote: > >> On Sep 28, 2:59 pm, sotirac wrote: > > >>> Wondering if there is a better way to generate string of numbers with > >>> a length of 5 which also can have a 0 in the front of the number. > > >>>
> >>> ?random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> >>> elements
> >>> ?code = 'this is a string' + str(random_number[0]) +
> >>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> >>> + str(random_number[4])
> >>> 
> > >> '%05i'%random.randint(0,99999) > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > > This produces numbers other than 5 digit numbers. making the start > > number 10000 should be fine. > > Why do you think it's wrong? > > > > >>> import random > >>> '%05i'%random.randint(0,99999) > '09449' > > IMO it's exactly what was required. > > Ciao, Michael. As you read, there isn't agreement on whether the OP wanted replacement. His original code didn't; his spec seemed to. From lists at cheimes.de Wed Sep 24 06:01:59 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 24 Sep 2008 12:01:59 +0200 Subject: python 3.x third party modules In-Reply-To: References: Message-ID: Almar Klein wrote: > Can > anyone say something about that? Will it take a month, a year? A year or more is realistic. A couple of years is even more realistic. Large projects are moving slowly and Python 3.0 introduces some heavy changes. The separation of text (unicode str) and data (bytes) takes time. Christian From hniksic at xemacs.org Tue Sep 16 04:48:42 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 10:48:42 +0200 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: <87hc8g79xx.fsf@mulj.homelinux.net> "Chris Rebert" writes: >> c = [9,10] >> [1,2,3,4,7].append(c) -> Is this a valid expression? > > Literally, no, because you can't call methods on literals. This is in fact not true. [1,2,3,4,7].append([9, 10]) is a perfectly valid expression, only it doesn't do much (that you can observe). The canonical response (no doubt already quoted in this thread) is that returning the list from append would confuse the hell out of people who expect a copy of the list, such as: a = [1, 2, 3] b = a.append(4) # if the above "worked" in the sense that b == [1, 2, 3, 4], I for one # would expect a to remain unchanged From drobinow at gmail.com Mon Sep 8 20:40:01 2008 From: drobinow at gmail.com (drobinow at gmail.com) Date: Mon, 8 Sep 2008 17:40:01 -0700 (PDT) Subject: F2PY ?? Has anyone worked with the F2PY generator? References: <27CC3060AF71DA40A5DC85F7D5B70F3802840447@AWMAIL04.belcan.com> Message-ID: <9166df82-0a50-478c-8446-e3ef23f53c7e@y21g2000hsf.googlegroups.com> On Sep 8, 7:19?pm, "Blubaugh, David A." wrote: > Pauli, > > Yes, ?I am utilizing the windows environment. ?I cannot install f2py. ? > > I obtain the following error when I try to execute the setup.py file > within the f2py folder located within the numpy master folder: You shouldn't need to do this. The installation of numpy puts f2py.py in your Scripts folder. explicitly: C:\Python25\Python C:\Python25\Scripts\f2py.py From heston.james at coldbeans.co.uk Tue Sep 30 09:43:59 2008 From: heston.james at coldbeans.co.uk (Heston James - Cold Beans) Date: Tue, 30 Sep 2008 14:43:59 +0100 Subject: ElementTree Help With DTD Message-ID: <004701c92302$97a61300$c6f23900$@james@coldbeans.co.uk> Afternoon All, I have used elementtree for a little while now parsing simple XML documents and found it pretty intuitive. Today is the first time I've used the library to create an XML file though. I have a simple script which looks like this: # Save the configuration to the XML file. # Create the root element, top = etree.Element("top") # Create the other elements in the tree. sub1 = etree.SubElement(top, "sub1") sub1.text = "other text" # Create the core element tree object. tree = etree.ElementTree(top) # Write the XML to the file system. tree.write("/path/to/my.xml") This works just fine, in as much that I get an XML file with the correct XML content within it, like so: other text However, I really need to validate this built XML against a DTD schema that I have, and also add the DTD reference to the top of the generated file, so other applications parsing it in can validate it properly, like so: other text As you can see, this also includes the proper XML definition for the file. Can anyone offer any pointers on how to have ElementTree add these additional definitions to the file it generates? And also validate itself against the DTD before writing to the FS? Many thanks guys, I really appreciate it. Heston -------------- next part -------------- An HTML attachment was scrubbed... URL: From circularfunc at yahoo.se Tue Sep 16 11:38:44 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 08:38:44 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: Message-ID: On Sep 16, 5:25?pm, Python wrote: > On 16 sep 2008, at 17:13, cnb wrote: > > > > >>>> sys.path > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', ? > > 'C:\ > > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > > \lib\\site-packages\\PIL'] > > > Now I have my personal programs in C:/Python25/Progs/ > > > How do I add so that I can just do "import somefile" from anywhere in > > that directory in the interpreter and it can load files from other > > folders in that directory. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > a temp solution is to append it to that list: > > sys.path.append('C:/Python25/Progs/') > > a permanent solution is to add it to the environment variable > (no idea where to set this in windows) > $PYTHONPATH = "/C:/Python25/Progs/" > > gr > Arno but since Python25/ is in my path it only seems to import from that exact dir, not dirs inside the dir. so i have to do somerthing like /progs/* ? and also, temporary adding doesnt seem to work. From marek at xivilization.net Tue Sep 2 12:38:10 2008 From: marek at xivilization.net (Marek Kubica) Date: Tue, 2 Sep 2008 16:38:10 +0000 (UTC) Subject: pyparsing: match empty line Message-ID: Hi, I am trying to get this stuff working, but I still fail. I have a format which consists of three elements: \d{4}M?-\d (4 numbers, optional M, dash, another number) EMPTY (the token) [Empty line] (the token. The line may contain whitespaces, but nothing else) While the ``watchname`` and ``leaveempty`` were trivial, I cannot get ``pagebreak`` to work properly. #!/usr/bin/env python # -*- coding: UTF-8 -*- from pyparsing import (Word, Literal, Optional, Group, OneOrMore, Regex, Combine, ParserElement, nums, LineStart, LineEnd, White, replaceWith) ParserElement.setDefaultWhitespaceChars(' \t\r') watchseries = Word(nums, exact=4) watchrev = Word(nums, exact=1) watchname = Combine(watchseries + Optional('M') + '-' + watchrev) leaveempty = Literal('EMPTY') def breaks(s, loc, tokens): print repr(tokens[0]) #return ['' for token in tokens[0]] return [''] #pagebreak = Regex('^\s*$').setParseAction(breaks) pagebreak = LineStart() + LineEnd().setParseAction(replaceWith ('')) parser = OneOrMore(watchname ^ pagebreak ^ leaveempty) tests = [ "2134M-2", """3245-3 3456M-5""", """3256-4 4563-4""", """4562M-6 EMPTY 3246-5""" ] for test in tests: print parser.parseString(test) The output should be: ['2134M-2'] ['3245-3', '3456M-5'] ['3256-4', '' '4563-4'] ['4562M-6', '', '3246-5'] Thanks in advance! regards, Marek From castironpi at gmail.com Sun Sep 7 17:00:30 2008 From: castironpi at gmail.com (castironpi) Date: Sun, 7 Sep 2008 14:00:30 -0700 (PDT) Subject: lacking follow-through Message-ID: I am concerned by the lack of follow-through on some responses to recent ideas I have described. Do I merely have a wrong understanding of group policy? Is it a good policy (defined with respect to the future of Python and the welfare of humans at large) if so? Is there a serious lack of diligence, or should I merely take more initiative, and ignore charges of 'pestering'? (Warning, moderately deep outside social issues on table too.) From marco.bizzarri at gmail.com Fri Sep 12 11:01:11 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 12 Sep 2008 17:01:11 +0200 Subject: Checking the boolean value of a collection In-Reply-To: <6ivdhnFnm8bU1@mid.uni-berlin.de> References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> Message-ID: <3f0d61c40809120801r27e92a67sb36e0c0aa9fcc854@mail.gmail.com> On Fri, Sep 12, 2008 at 4:44 PM, Diez B. Roggisch wrote: >>> if any(instance.forbitToClose(archivefolder) for instance in >>> self.findActiveOutgoingRegistrationInstances()) >> >> Can you clarify where I can find "any"? It seems to me I'm unable to find >> it... > > It's part of python2.5. > > If you don't have that, you can write it your own and stuff it into > __builtins__: > >>>> def any(iterable): > ... for item in iterable: > ... if item: > ... return True > ... return False > ... > ... __builtins__.any = any > > > You might also want to add all, the companion of any: > > >>>> def all(iterable): > ... for item in iterable: > ... if not item: > ... return False > ... return True > ... > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for the clarification, Diez! Indeed, I tried python2.3 and python2.4, and of course not python2.5 ;) I would like to make this available to the whole project. I suspect I could put it in the package __init__.py... in that way, the __builtins__ namespace should have it... am I right? -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From michele.simionato at gmail.com Mon Sep 29 10:33:01 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 29 Sep 2008 07:33:01 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> Message-ID: On Sep 28, 6:43?am, "Aaron \"Castironpi\" Brady" wrote: > Hello all, > > To me, this is a somewhat unintuitive behavior. ?I want to discuss the > parts of it I don't understand. > > >>> f= [ None ]* 10 > >>> for n in range( 10 ): > > ... ? ? f[ n ]= lambda: n > ...>>> f[0]() > 9 > >>> f[1]() > > 9 > You may want to read this old thread that goes in detail explaining scoping issues with closures in for loops: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d691240a5cfebcdf/93503c5b9c66226e?hl=en&lnk=gst&q=simionato+jacek#93503c5b9c66226e From rsarpi at gmail.com Tue Sep 9 16:33:35 2008 From: rsarpi at gmail.com (icarus) Date: Tue, 9 Sep 2008 13:33:35 -0700 (PDT) Subject: wxpython ms-dos black window popping up in background Message-ID: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> platform: windows xp professional, python 2.5, wxpython When I double-check on my program file test.py (for simplicity I'll be using this code below), I see the window just fine. But the ms-dos black window pops up in the background. On Linux, no issues at all. How can I get rid of that ms-dos black window in the background? something I need to add to my code? a setting to adjust in windows? thanks in advance. #!/usr/bin/python import wx appwx = wx.App() frame = wx.Frame(None, -1, 'test.py') frame.Show() appwx.MainLoop() From dudeja.rajat at gmail.com Thu Sep 25 04:30:41 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Thu, 25 Sep 2008 09:30:41 +0100 Subject: unable to parse the content using the regular expression Message-ID: Hello, I've the following results from Difflib.Compare() which I want to parse them using the regular expression to find out the the values that have changed. ###################################################################### Testing DLL interface ###################################################################### Input File: c:\12.txt Config File: c:\abc.ini ###################################################################### Results:- ------- - Analysis Time (Iterations = 1) = 0.0449145s ? ^^ ^ + Analysis Time (Iterations = 1) = 0.0447347s ? ^^ ^ Width = 0.999989 Height = 0.044 - Length = 10 ? ^ + Length = 11 ? ^ End of Results ###################################################################### Testing DOTNET interface ###################################################################### Input File: c:\12.txt Config File: c:\abc.ini ####################################################################### Results:- ------- - Analysis Time (Iterations = 1) = 0.0449145s ? ^^ ^ + Analysis Time (Iterations = 1) = 0.0447347s ? ^^ ^ Width = 0.999989 Height = 0.044 - Length = 12 ? ^ + Length = 13 ? ^ End of Results ****** How Can I extract the headings out of this file? The headings are: ###################################################################### Testing DLL interface ###################################################################### Input File: c:\12.txt Config File: c:\abc.ini ###################################################################### < Here I want to display only the values that differ i.e. the lines prceded with +,?,- signs > ###################################################################### Testing DOTNET interface ###################################################################### Input File: c:\12.txt Config File: c:\abc.ini ####################################################################### I intent to show only the things that differ with their proper headings(as above) Please help me to get the heading stuff out. Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at spamhaters.com Sat Sep 6 16:18:55 2008 From: nospam at spamhaters.com (clurker) Date: Sat, 06 Sep 2008 15:18:55 -0500 Subject: List of modules available for import inside Python? References: <0191c6fe-ec2c-43b6-867f-25910adff458@l64g2000hse.googlegroups.com> Message-ID: Michele Simionato wrote: > On Aug 28, 6:21?am, ssecorp wrote: >> Is there a way to view all the modules I have available for import >> from within Python? >> Like writing in the interpreter: > > Try: > >>>> help() > help> modules > Please wait a moment while I gather a list of all available modules... > This looks like it could be a useful tool, but when I try it I get the following: Please wait a moment while I gather a list of all available modules... /usr/lib/python2.5/site-packages/reportlab/lib/PyFontify.py:35: Warning: 'with' will become a reserved keyword in Python 2.6 /usr/lib/python2.5/site-packages/reportlab/lib/PyFontify.py:36: Warning: 'with' will become a reserved keyword in Python 2.6 Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site.py", line 346, in __call__ return pydoc.help(*args, **kwds) File "/usr/lib/python2.5/pydoc.py", line 1645, in __call__ self.interact() File "/usr/lib/python2.5/pydoc.py", line 1663, in interact self.help(request) File "/usr/lib/python2.5/pydoc.py", line 1679, in help elif request == 'modules': self.listmodules() File "/usr/lib/python2.5/pydoc.py", line 1797, in listmodules ModuleScanner().run(callback) File "/usr/lib/python2.5/pydoc.py", line 1848, in run for importer, modname, ispkg in pkgutil.walk_packages(): File "/usr/lib/python2.5/pkgutil.py", line 110, in walk_packages __import__(name) File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 1342, in File "/usr/local/lib/python2.5/site-packages/PIL/__init__.py", line 927, in main UnboundLocalError: local variable 'given_files' referenced before assignment >>> which could be because I am fairly free and unrestrained when it comes to installing stuff, and I see now I have modules on both /usr/lib/python2.5 and /usr/local/lib/python2.5 Apparently python knows about them both, but I don't know I haven't introduced an incompatibility somewhere...and that PIL package showing up at the tail of the errors was one of my more recent additions... Any help will be appreciated, sc From gagsl-py2 at yahoo.com.ar Fri Sep 19 06:48:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 07:48:27 -0300 Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> Message-ID: En Thu, 18 Sep 2008 23:29:30 -0300, Sam escribi?: > On Sep 18, 2:10?pm, "Gabriel Genellina" > wrote: >> En Tue, 16 Sep 2008 21:58:31 -0300, Sam escribi?: >> The code is correct - try with another server. I tested it with a ? >> LightHTTPd server and worked fine. > > Gabriel... > > I found a bunch of servers to test it on. It fails on every server I > could find (sans one). I'll try to check later. Anyway, why are you so interested in deflate? Both "deflate" and "gzip" coding use the same algorithm and generate exactly the same compressed stream, the only difference being the header and tail format. Have you found any server supporting deflate that doesn't support gzip as well? -- Gabriel Genellina From david at boddie.org.uk Mon Sep 15 17:40:13 2008 From: david at boddie.org.uk (David Boddie) Date: Mon, 15 Sep 2008 23:40:13 +0200 Subject: MVC with Python References: Message-ID: On Monday 15 September 2008 21:37, Georg Altmann wrote: > I need some advice on how to implement model-view-controller. I am > trying to develop a GUI application with PyQt, yet the problem rather > applies to mvc in general, not just GUI applications. > > Let's say the data is a list of objects with a common base class. The > views are either a graphical representation of the objects or some form > of textual input. The views shall change the model by using command > objects (for undo, e.g. QUndoCommand). [...] > My problem is, how do the commands interact with the model? One approach that combines the undo framework with the model/view framework is described here: http://doc.trolltech.com/qq/qq25-undo.html The implementation is in C++, but it may be possible to pick up some useful tips from the article. David From mrkafk at gmail.com Wed Sep 3 09:57:50 2008 From: mrkafk at gmail.com (mk) Date: Wed, 03 Sep 2008 15:57:50 +0200 Subject: properties setting each other Message-ID: Hello everyone, I try to set two properties, "value" and "square" in the following code, and arrange it in such way that setting one property also sets another one and vice versa. But the code seems to get Python into infinite loop: >>> import math >>> class Squared2(object): def __init__(self, val): self._internalval=val self.square=pow(self._internalval,2) def fgetvalue(self): return self._internalval def fsetvalue(self, val): self._internalval=val self.square=pow(self._internalval,2) value = property(fgetvalue, fsetvalue) def fgetsquare(self): return self.square def fsetsquare(self,s): self.square = s self.value = math.sqrt(self.square) square = property(fgetsquare, fsetsquare) >>> a=Squared2(5) Traceback (most recent call last): File "", line 1, in a=Squared2(5) File "", line 5, in __init__ self.square=pow(self._internalval,2) File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare self.square = s File "", line 19, in fsetsquare ... Is there a way to achieve this goal of two mutually setting properties? From mensanator at aol.com Sun Sep 7 20:22:21 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 7 Sep 2008 17:22:21 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: On Sep 7, 3:13?pm, "Gabriel Genellina" wrote: > En Sun, 07 Sep 2008 14:30:09 -0300, Mensanator escribi?: > > > > > Actualy, I already get the behaviour I want. sum([1,None]) > > throws an exception. I don't see why sum([]) doesn't throw > > an exception also (I understand that behaviour is by design, > > I'm merely pointing out that the design doesn't cover every > > situation). > [...] > > Exactly. That's why I would prefer sum([]) to raise an > > exception instead of giving a false positive. > > The built in behavior can't be good for every usage. Nobody prevents you from defining yoru own function tailored to your own specs, like this: > > def strict_sum(items): > ? ? items = iter(items) > ? ? try: > ? ? ? ? first = items.next() > ? ? except StopIteration: > ? ? ? ? raise ValueError, "strict_sum with empty argument" > ? ? return sum(items, first) > > Tweak as needed. Based on other posts I believe your Python skills are enough to write it on your own, so I don't see why you're complaining so hard about the current behavior. I'm not complaining about the behaviour anymore, I just don't like being told I'm wrong when I'm not. But I think I've made my point, so there's no point in harping on this anymore. > > -- > Gabriel Genellina From dickinsm at gmail.com Wed Sep 24 06:14:38 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 24 Sep 2008 03:14:38 -0700 (PDT) Subject: Comparing float and decimal References: <20080923072012.57d8d329.darcy@druid.net> Message-ID: On Sep 23, 7:31?pm, Terry Reedy wrote: > Decimal is something of an anomaly in Python because it was written to > exactly follow an external standard, with no concessions to what would > be sensible for Python. ?It is possible that that standard mandates that > Decimals not compare to floats. I don't think the standard says anything about interactions between Decimals and floats. But there's certainly been a feeling amongst at least some of the developers that the job of Python's decimal module is to implement the standard and no more, and that extensions to its functionality belong elsewhere. Regarding equality, there's at least one technical issue: the requirement that objects that compare equal hash equal. How do you come up with efficient hash operations for integers, floats, Decimals and Fractions that satisfy this requirement? For other arithmetic operations: should the sum of a float and a Decimal produce a Decimal or a float? Why? It's not at all clear to me that either of these types is 'higher up' the numerical tower than the other. Mark From aetodd at gmail.com Sat Sep 20 17:20:20 2008 From: aetodd at gmail.com (Andrew) Date: Sat, 20 Sep 2008 14:20:20 -0700 (PDT) Subject: explain slice assignment to newb Message-ID: please explain this behavior to a newb: >>> a = [1,2,3,4] >>> b = ["a","b","c","d"] >>> a [1, 2, 3, 4] >>> b ['a', 'b', 'c', 'd'] >>> a[0:2] [1, 2] >>> a [1, 2, 3, 4] >>> b[2:4] ['c', 'd'] >>> a[0:2] = b[0:2] >>> b[2:4] = a[2:4] >>> a ['a', 'b', 3, 4] >>> b ['a', 'b', 3, 4] >>> From castironpi at gmail.com Wed Sep 24 00:06:23 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 21:06:23 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> <31ff7c8a-28f3-4c62-8ac5-6d0f90106c5d@a8g2000prf.googlegroups.com> Message-ID: On Sep 23, 9:30?pm, lixinyi... at gmail.com wrote: > If the PyObject is a PyList, and all list items are strings, > say a=['aaa','bbb','ccc'] > > How can I have a > myArray[0] = "aaa" > myArray[1] = "bbb" > myArray[2] = "ccc" > in C++? > > Do I have to > use PyModule_GetDict() to get the dict first? > what about the next? > > > > > What do you know about the contents of 'argc' and 'argv'? ?If it's > > impossible with Py_Main, can you use one of the other entry points? > > > If you've never manipulated PyObject* objects in C, they can be > > hairy. ?Even if you know 'a' is a sequence, its contents are still all > > PyObject*s, which you can access via PyList_... and PySequence_ > > functions. > > This one writes '[aaa, bbb, ccc]' to the console in two different ways. #include int main() { PyObject *list, *listrepr; Py_Initialize(); /* first */ list= PyList_New( 3 ); PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( listrepr ); Py_DECREF( list ); /* second */ list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( listrepr ); Py_DECREF( list ); Py_Finalize(); return 0; } Did you want to execute some Python code, and examine variables it creates? From asnast at gmail.com Sun Sep 21 12:34:43 2008 From: asnast at gmail.com (Alex Snast) Date: Sun, 21 Sep 2008 09:34:43 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> <00e5938e$0$20331$c3e8da3@news.astraweb.com> Message-ID: On Sep 21, 3:47?am, Steven D'Aprano wrote: > On Sat, 20 Sep 2008 16:27:41 -0700, Alex Snast wrote: > > Another quick question please, is the List data structure just a dynamic > > array? If so how can you use static size array, linked list, AVL trees > > etcetera. > > Before I answer your question, I should say that you can go a LONG way > with just the standard Python built-in data structures list, dict and > set, plus a handful of standard modules like array and collections. It's > often (but not always) better to modify an algorithm to use a built-in > data structure than to try to implement your own. > > The underlying data structure for lists is implementation specific. Only > the behaviour is specified by the language. > > In the standard Python implementation written in C (usually known as > "Python", although sometimes people explicitly describe it as CPython), > lists are implemented as a fixed array of pointers. The array is > periodically resized, either up or down, but only as needed. The largest > consequence of that is that appending to the end of a list is much faster > than inserting at the beginning of the list. > > Other implementations (IronPython, Jython, PyPy, CLPython...) are free to > implement lists whatever way they need. > > If you want a static list, the simplest way is to create a list and > simply not resize it. If you want to enforce that, here's a subclass to > get you started: > > class StaticList(list): > ? ? def _resize(self): > ? ? ? ? raise RuntimeError("list can't be resized") > ? ? extend = append = pop = insert = remove = \ > ? ? __delitem__ = __delslice__ = _resize > > I haven't dealt with __setitem__ or __setslice__, because they're more > complicated: you need to make sure the slice you're setting has the same > size as the bit you're replacing, so that this is allowed: > > mylist[3:6] = [1, 2, 3] > > but not these: > > mylist[3:6] = [1, 2] > mylist[3:6] = [1, 2, 3, 4] > > As for linked lists and trees, don't worry about pointers, just go ahead > and implement them. > > # basic, no-frills tree > class Node(object): > ? ? def __init__(self, data, left=None, right=None): > ? ? ? ? self.left = left > ? ? ? ? self.right = right > ? ? ? ? self.info = data > > tree = Node('top of the tree') > tree.left = Node('left subtree') > tree.right = Node('right subtree', None, Node('another subtree')) > t = tree.right.right > t.left = Node('yet another subtree') > > etc. > > The CPython implementation of dict is a hash table, and dicts are > extremely fast and efficient. So long as you don't mind losing the order > of insertion, you won't beat dicts for speed and efficiency in anything > you write in pure Python. > > -- > Steven WOW you guys are really helpful, thanks everyone for all the replies. Last question: What IDE do you guys recommend, I'm currently using pydev. Thanks again, Alex From overdrigzed at gmail.com Fri Sep 12 19:38:12 2008 From: overdrigzed at gmail.com (overdrigzed at gmail.com) Date: Fri, 12 Sep 2008 16:38:12 -0700 (PDT) Subject: ctypes: Get full contents of character array Message-ID: Hello! I wanted to get the full contents of a character array stored in a struct, i.e. _fields_ = [...("array", c_char * 12)...] however, ctypes seems to try to return struct.array as a Python string rather than a character array, and stops as soon as it encounters a null within the character array. I ended up having to define a dummy struct class dummystruct(Structure): _fields_ = [] and declare array as: ("array", dummystruct) then use string_at(byref(struct.array), 12). Is this really the best way of doing it? Is there no better way to work around ctypes 'guess what you want' behaviour? Thanks in advance, Rodrigo From skip at pobox.com Sat Sep 6 16:47:22 2008 From: skip at pobox.com (skip at pobox.com) Date: Sat, 6 Sep 2008 15:47:22 -0500 Subject: How to merge a module into a package w/ distutils? Message-ID: <18626.60506.393584.737943@montanaro-dyndns-org.local> The bsddb module is on the way out (deprecated in 2.6, gone in 3.0). That leaves Python without a cross-platform dbm module to sit underneath anydbm and shelve. I figured it might be useful to base something on top of sqlite3, which is cross-platform. The result is available in the Python sandbox: http://svn.python.org/view/sandbox/trunk/dbm_sqlite/ There are three files, a dbm.sqlite module, a test case and a modified bit of dbm documentation. For testing I'd like to install this in such a way that I can simply import dbm.sqlite but not overwrite the core install. I'd also not like to lose dbm.gdbm, etc during this testing phase. Is there some way to do this with distutils? Ideally, I'd like there to be a dbm package in site-packages but which falls back to the central installation when, say, dbm.gdbm isn't found. Thx, Skip From deets at nospam.web.de Mon Sep 8 06:52:57 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Sep 2008 12:52:57 +0200 Subject: Syntax Problem with strptime in Python 2.4 References: Message-ID: <6ikegtFr3ab7U1@mid.uni-berlin.de> W. eWatson wrote: > Apparently, use of strptime of datetime needs a workaround in Python 2.4 > to work properly. The workaround is d = > datetime.datetime(*(time.strptime(date_string, format)[0:5])). However, > when I try to use it, or even use it the regular way, it fails with > AttributeError: type object 'datetime.datetime' has no attribute > 'datetime'. > From the following code code segment: > > format = '%Y%m%d_%H%M%S' > #d=datetime.strptime('20080321_113405', format)-- typical use > print time.strptime('20080321_113405', format)[0:5] > d = datetime.datetime(*time.strptime('20080321_113405', format)[0:5]) > > Does anyone know how to make this work in 2.4? If not, is there a way to > achieve the same result? This is not what you think it is. All your problem is that you do from datetime import datetime which imports the datetime-class, but then try to access datetime.datetime as if you had done import datetime. This actually is a wart in the datetime-module - it would be better if the classes in there would follow PEP-8. Diez From banibrata.dutta at gmail.com Wed Sep 24 03:51:48 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Wed, 24 Sep 2008 13:21:48 +0530 Subject: Does anybody use this web framework ? In-Reply-To: <48d9eb86$0$6127$426a34cc@news.free.fr> References: <48d94cbc$0$964$ba4acef3@news.orange.fr> <48d9eb86$0$6127$426a34cc@news.free.fr> Message-ID: <3de8e1f70809240051l3d32f44cl5e3fcc077e380ad@mail.gmail.com> On Wed, Sep 24, 2008 at 12:56 PM, Bruno Desthuilliers wrote: > Phil Cataldo a ?crit : > >> Hi, >> >> I just found this new? python web framework >> (http://pypi.python.org/pypi/nagare/0.1.0). >> >> Does anybody know or use it ? >> > > First time I hear of it, but it looks interesting (note : Stackless > continuation-based framework). Thanks for the link. > The description looks quite interesting indeed.... but as we heard in Spiderman and elsewhere... "with great power comes great responsibility"... the power is largely curtailed in most of the web-frameworks in status-quo ! -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Sat Sep 20 14:10:38 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Sat, 20 Sep 2008 11:10:38 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: <0e14ba9a-6f13-4e3f-b789-370ae8d1205f@2g2000hsn.googlegroups.com> On 20 Sep, 19:42, "Aaron \"Castironpi\" Brady" wrote: > > Wikipedia puts it decently: "mainly for OO programming, but with some > procedural elements." > > When it comes to Python and object-oriented programming, you can't leave out the ducks. ;-) Paul From half.italian at gmail.com Fri Sep 26 14:20:36 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Fri, 26 Sep 2008 11:20:36 -0700 (PDT) Subject: Writing a well-behaved daemon References: <874p43wl2m.fsf@benfinney.id.au> <87zllvv0py.fsf@benfinney.id.au> Message-ID: <5d09dd5e-4a0b-41f9-97c5-16bb47042f96@25g2000prz.googlegroups.com> On Sep 26, 12:13?am, Ben Finney wrote: > Sean DiZazzo writes: > > Looks like somebody did the same thing I did and posted it. > > >http://svn.plone.org/svn/collective/bda.daemon/trunk/bda/daemon/daemo... > > Thanks, I've not seen that before. > > It still seems loony to me that something this difficult to do right, > yet so similar across different use cases, isn't in the standard > library, where bugs need only be fixed in one place. > > -- > ?\ ? ? ? ??Pinky, are you pondering what I'm pondering?? ?Wuh, I think | > ? `\ ? ? ?so, Brain, but how will we get three pink flamingos into one | > _o__) ? ? ? ? ? ? ? ? ? ? pair of Capri pants?? ?_Pinky and The Brain_ | > Ben Finney +1 I think it would be a great addition. From bignose+hates-spam at benfinney.id.au Tue Sep 9 19:51:09 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 10 Sep 2008 09:51:09 +1000 Subject: [OT] top-posting and quoting References: <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <48bfc4e4$0$13232$426a74cc@news.free.fr> <9efc52fa-f2d2-40e4-8fbb-fb4c06f8e0e4@a3g2000prm.googlegroups.com> <48c6c862$0$17309$426a34cc@news.free.fr> Message-ID: <87y720dgk2.fsf@benfinney.id.au> Bruno Desthuilliers writes: > Could you please timh and belindelof learn to quote properly and stop > top-posting ? In case it's not clear, by "quote properly" I believe Bruno means to trim quoted material irrelevant to one's reply, and use standard inline replies . Certainly that's what I'd prefer to see. -- \ ?None can love freedom heartily, but good men; the rest love | `\ not freedom, but license.? ?John Milton | _o__) | Ben Finney From almar.klein at gmail.com Mon Sep 15 03:36:02 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 15 Sep 2008 09:36:02 +0200 Subject: Good programming style In-Reply-To: References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> Message-ID: > > > Because the code we write rarely stays isolated from other > > code. There is an existing convention, > > There are many existing conventions. > Even though there is a convention (PEP 8), there are standard modules that do not follow it, like the subprocess module, which uses CamelCase. When packages as significant as wxPython use naming conventions > other than PEP 8, I find it hard to make a case that the PEP 8 > naming convention is any better than any other. > A lot of C/C++ projects are wrapped in python, and with that, their naming styles. As said above, it's often better to use the projects native naming styles than to change it to conform to PEP 8. So I guess it is impossible to have a single naming style in Python. For these two reasons, I think its so much more important to be consistent within a project, rather than to stick with PEP 8. When you are using a module, you'll see in no-time what style is used, and you're able to use it. The fact that some standard modules deviate from PEP 8 without problems shows it. Personally, I prefer CamelCase over under_scores. Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: From sniipe at gmail.com Mon Sep 1 09:25:17 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Mon, 1 Sep 2008 06:25:17 -0700 (PDT) Subject: How to print first(national) char from unicode string encoded in utf-8? References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com> Message-ID: <7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> On 1 Wrz, 15:10, "Marco Bizzarri" wrote: > 2008/9/1 : > > > > > Hi, > > > I have a problem with unicode string in Pylons templates(Mako). I will > > print first char from my string encoded in UTF-8 and urllib.quote(), > > for example string '?ukasz': > > > ${urllib.unquote(c.user.firstName).encode('latin-1')[0:1]} > > > and I received this information: > > > : 'utf8' codec can't decode byte > > 0xc5 in position 0: unexpected end of data > > > When I change from [0:1] to [0:2] everything is ok. I think it is > > because of unicode and encoding utf-8(2 bytes). > > > How to resolve this problem? > > > Best regards > > -- > >http://mail.python.org/mailman/listinfo/python-list > > First: you're talking about utf8 encoding, but you've written latin1 > encoding. Even though I do not know Mako templates, there should be no > problem in your snippet of code, if encoding is latin1, at least for > what I can understand. > > Do not assume utf8 is a two byte encoding; utf8 is a variable length > encoding. Indeed, > > 'a' encoded as utf8 is 'a' (one byte) > > '?' encode as utf8 is '\xc3\xa0' (two bytes). > > Can you explain what you're trying to accomplish (rather than how > you're tryin to accomplish it) ? > > Regards > Marco > > -- > Marco Bizzarrihttp://notenotturne.blogspot.com/http://iliveinpisa.blogspot.com/ When I do ${urllib.unquote(c.user.firstName)} without encoding to latin-1 I got different chars than I will get: no ?ukasz but ??ukasz From fredrik at pythonware.com Thu Sep 11 14:32:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 20:32:46 +0200 Subject: wx In-Reply-To: References: Message-ID: Desmond Scott E wrote: > I'm am a Python novice by chance not choice. (Although it appears to be > a nice tool. Plus anything based on Monte Python can't be bad!) > > My Quest is to migrate a Python-based process from Windows2000/Python > v2.4.2 (#67) to WindowsXP/Python v2.5.2 (r252:60911). > > I've searched the Python website and could find no reference to module > wx. Is this an add-in module or perhaps it was replaced in v2.5.2??? wx is wxPython: http://www.wxpython.org/ From john.m.roach at gmail.com Thu Sep 11 09:43:08 2008 From: john.m.roach at gmail.com (john) Date: Thu, 11 Sep 2008 06:43:08 -0700 (PDT) Subject: catching exceptions from fortran Message-ID: I wrapped some fortran code using F2PY and need to be able to catch fortran runtime errors to run the following: # "grid" is a wrapped fortran module # no runtime errors incurred when run with the correct inputs for filetype #------------------------------- def readGrid( self, coord='xyz' ): mg = ( '.FALSE.', '.TRUE.' ) form = ( 'FORMATTED', 'UNFORMATTED' ) success = False for m in mg: for f in form: try: if coord == 'xyz': self.grid.readxyz( self.filename, f, m ) success = True elif coord == 'xyrb': self.grid.readxyrb( self.filename, f, m ) success = True else: import sys print 'gridtype "' + str(coord) + '" not supported. ' \ + '' except: continue if not success: import sys print 'gridfile "' + str(self.filename) + '" not read in any recognized format' \ + ' ' #---------------------------- basically, what i want to happen is to try to run 'something' with the wrapped fortran code and if that doesn't work (error encountered, etc.) try something else. is there an easier way to go about doing this? is there something i'm missing about catching exceptions here? Thanks in advance! From linkmaster032000 at gmail.com Thu Sep 25 15:41:29 2008 From: linkmaster032000 at gmail.com (linkmaster032000 at gmail.com) Date: Thu, 25 Sep 2008 12:41:29 -0700 (PDT) Subject: curses.setsyx()? References: <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> <713190fc-e3a9-4a72-8bee-4fd3affcb531@c58g2000hsc.googlegroups.com> <5acmd4t7p44cbgi1fkmhaaasfplv0jaatr@4ax.com> Message-ID: <2a05e58b-bd73-41de-addb-f2605d188e9b@m3g2000hsc.googlegroups.com> On Sep 25, 2:39?am, Tim Roberts wrote: > linkmaster032... at gmail.com wrote: > >On Sep 23, 4:16?pm, brad.at.sch... at gmail.com wrote: > >> On Sep 22, 11:24?pm, Tim Roberts wrote: > >> > linkmaster032... at gmail.com wrote: > >> > >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: > >> > >> On Sep 19, 1:24?am, Tim Roberts wrote: > > >> > >> > linkmaster032... at gmail.com wrote: > > >> > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses > >> > >> > >cursor. Any alternatives/solutions? > >>... > >> > >> I added it and it still doesn't work. This is what I'm doing when I > >> > >> want to display the cursor and prepare it for input at 2,3: > > >> > >> curses.echo() > >> > >> curses.curs_set(1) > >> > >> curses.setsyx(2,3) > >> > >> curses.doupdate() > > >> > >Any idea what's wrong? > > >>http://pastebin.com/m6413db1 > > >> Run that and press 'n' key. It is supposed to move the cursor to 2,3 > >> and it doesn't. > > Of course it does. ?It moves the cursor, then does an update, then > immediately calls draw.game, which redraws the screen and moves the cursor. > If you want curses.setsyx (or the equivalent and more mnemonic scr.move) to > leave the cursor somewhere, you can't draw more text afterward. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. OH!!!! Thank you!!! From ldo at geek-central.gen.new_zealand Wed Sep 24 06:18:05 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:18:05 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> Message-ID: In message <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d at posted.usinternet>, Grant Edwards wrote: > On 2008-09-23, Blubaugh, David A. wrote: > >> I was wondering if anyone has come across the issue of not being allowed >> to have the following within a Python script operating under Linux: >> >> time.sleep(0.0125) > > No, I have not. And I doubt anybody else has. Just a thought, your minimum sleep time is probably limited by the resolution of the system "HZ" clock. Type less /proc/config.gz and search for the value of the "CONFIG_HZ" setting. On the Athlon 64 machine I'm using to write this, it's 250, which should allow for sleep intervals in multiples of 0.004 seconds. From dblubaugh at belcan.com Sat Sep 20 12:59:06 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Sat, 20 Sep 2008 12:59:06 -0400 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> To All, I have now been able to generate a .pyd file from a FORTRAN file that I am trying to interface with python. I was able to execute this with an additional insight into how f2py operates. It seems as though the documentation requires an upgrade, since there appears to be missing information that might misdirect a f2py newcomer, such as myself. However, I am now facing the following new error: ImportError: DLL load with error code 193 The python script is as follows: import hello print hello.__doc__ print hello.foo.__doc__ hello.foo(4) The Fortran code is as follows: ! -*- f90 -*- subroutine foo(a) integer a print*, "Hello from Fortran!" print*, "a=", a end I was wondering as to what I should now try in order to finally produce a python sending and receiving information from a FORTRAN .pyd file. Any Suggestions??? Do I have to recompile Python with mingw32 in order to finally resolve this issue?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From python.list at tim.thechases.com Mon Sep 15 15:09:21 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 15 Sep 2008 14:09:21 -0500 Subject: environment variable issue In-Reply-To: <48ceacb9$0$2863$ba620e4c@news.skynet.be> References: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Message-ID: <48CEB2E1.6060600@tim.thechases.com> > Could someone explain me what I'm doing wrong here? I'm trying to > retrieve the value of an environment variable in Ubuntu 8.04 like this: > > >>> import os > >>> os.environ['USER'] > 'michel' > > This works but this doesn't: > > >>> os.environ['HOSTNAME'] > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'HOSTNAME' > > Why is it working in the first case but not in the second one. I must be > missing something but it seems I'm not able to figure it out. This is likely the same issue I just posted about here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/42346439533bd23a Your HOSTNAME variable hasn't been exported to subshells. You can check this by looking at the output of bash$ export -p which will print all the variables that are exported. I suspect you'll see $USER in the list, but not $HOSTNAME However, for the hostname, you might be interested in >>> import platform as p >>> p.uname()[1] 'rubbish' which does this in a cross-platform way without needing to fuss with exporting environment variables. -tkc From steven at REMOVE.THIS.cybersource.com.au Thu Sep 11 05:10:00 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Sep 2008 09:10:00 GMT Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <87k5djb6e2.fsf@benfinney.id.au> Message-ID: On Thu, 11 Sep 2008 15:25:57 +1000, Ben Finney wrote: >> > The bounce messages are sent to you because you sent the original. >> >> Wrong. I didn't send _any_ e-mail. Why should I get bounce messages? > > You asked for email to be sent, by sending a Usenet post to > comp.lang.python. That's what a news-to-mail gateway does. I wasn't aware that comp.lang.python was a news-to-mail gateway. How can one tell the difference between news groups that use a news-to-mail gateway, and news groups that don't? Posting to a public newsgroup is obviously giving consent to forward that news posting to news clients. Given the ability to opt-out with the X-No- Archive header, there may even be an implied consent to allow archiving. But I don't believe there is any such implied consent to format-shift news messages to email. In practice, I couldn't care less what format my news postings are converted to, so long as it is invisible and transparent to me. If somebody wants to build a news-to-carved-in-giant-stone-tablets gateway, I don't care, so long as I don't get giant stone tablets aren't dumped in my front yard. Nor do I believe that by posting a news message I've automatically consented to receive email messages. To imply that the one implies the other is equivalent to arguing that because I've written a letter to the editor of a newspaper, I therefore must accept private correspondence from any person or corporation that has a subscription to that newspaper. (In practice, I don't mind human-generated email messages, but not automatic messages. If you can turn my munged email address into a real email address, I probably won't mind you emailing me. Don't abuse the privilege.) [...] > I sympathise completely with your irritation at receiving bounce > messages from poorly-configured software, but the solution is not to > break the news-to-mail gateway. > > The correct solution is to unsubscribe the badly-behaving address from > the mailing list, and refuse re-subscription from that address without > assurance that the bad behaviour has ceased. The problem with that "correct solution" is that the party who suffers isn't in a position to correct the problem, and the party who can correct the problem has little incentive to do anything about it. That makes the solution ineffective and therefore anything but "correct". I hope the person running the mailing list does do the right thing, but if he or she does, it will be an accident of policy or personality, and not because the system is robust and self-corrects errors. To quote Dennis Lee Bieber: "The bounce/ooo-reply is sent to the message author, not to any intermediate host(s). After all, on that end, it's normal email failure response -- notify the author of the message. It doesn't matter that the original message was posted on a Usenet newsgroup if that group is automatically relayed to members of a mailing list." But that's wrong: it *shouldn't* be an normal email failure response, because the message author is in no position to do anything about it except to cease posting. That's a problem with all mailing lists (that I know of). -- Steven From fredrik at pythonware.com Fri Sep 5 02:47:05 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 05 Sep 2008 08:47:05 +0200 Subject: ctypes error on Windows In-Reply-To: References: Message-ID: Fredrik Lundh wrote: >> I do have the tidy.dll installed (if I didn't, I couldn't even import >> the tidy module). > > typing the following into the Python interpreter might give you some > more clues: > > >>> import _tidy > >>> _tidy.__file__ > >>> dir(_tidy) or not, since ctypes is involved. have you checked for multiple copies of tidy.dll? if you have MSVC on your machine, try using "dumpbin /exports" on the DLL to check that it really exports the symbols the binding expects. From jonathon.blake at gmail.com Tue Sep 9 00:40:57 2008 From: jonathon.blake at gmail.com (jonathon) Date: Mon, 8 Sep 2008 21:40:57 -0700 Subject: a11y & python In-Reply-To: References: Message-ID: On Mon, Sep 8, 2008 at 21:02, Steven D'Aprano wrote: > I'm guessing that you'd probably have more success asking on ally mailing lists I'm on a couple of a11y mailing lists. My experience with them has been, "disappointing". > Have you checked out this? http://live.gnome.org/Orca Not cross platform. :( I want to use python, precisely because it is cross-platform. (If it was Windows only, Net 3.0 has most, if not all of the needed libraries.) (I could try rewriting Orca in python, and from that construct the required python libraries.) xan jonathon From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 06:48:53 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 12:48:53 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: References: Message-ID: <48dcbe10$0$2329$426a34cc@news.free.fr> Wojtek Walczak a ?crit : > On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote: > >> I have a BIIIIIG problem with the next query: >> >> cursor.execute(""" >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """,( eid_list)) > ^ > It should rather be '%'. Please avoid such clueless advices and read the doc of the python db-api. From gh at ghaering.de Mon Sep 29 03:53:01 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 29 Sep 2008 09:53:01 +0200 Subject: Cannot install pysqlite on Cygwin In-Reply-To: References: Message-ID: Tilman Kispersky wrote: > I am trying to install sqlite for use with python on cygwin. I have > installed the sqlite packages from cygwin (that is libsqlite3-devel > and libsqlite3_0). When attempting to easy_install pysqlite I get: > [...] > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function > `pysqlite_enable_load_extension': > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ > pysqlite-2.5.0/src/connection.c:922: undefined reference to > `_sqlite3_enable_load_extension' [...] It might be that Cygwin's SQLite doesn't support loading extensions. Either: Rebuild SQLite from source on Cygwin and be sure to include --enable-load-extension when calling ./configure. Or hack the pysqlite sources and remove these lines in src/connection.c: #if SQLITE_VERSION_NUMBER >= 3003008 #define HAVE_LOAD_EXTENSION #endif I'm very interested how you can fix the problem. -- Gerhar From gandalf at shopzeus.com Thu Sep 4 11:52:38 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 04 Sep 2008 17:52:38 +0200 Subject: Function decorators In-Reply-To: <1220542457.48bffff905ca9@www.inbox.lv> References: <1220542457.48bffff905ca9@www.inbox.lv> Message-ID: <48C00446.7050407@shopzeus.com> Aigars Aigars wrote: > Good day all, > > I am learning Python and came up to decorators. > > The question is: Why does function FoodList return value None? > > The code in attachment. > > > Thank you, > Aigars > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list First of all, you should always inherit from "object" whenever it is possible. Then the answer: you did not return the result. Instead of self.func(*args, **kwargs) use this: return self.func(*args, **kwargs) Corrected example attached. Best, Laszlo -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: text/x-python Size: 505 bytes Desc: not available URL: From riquito at gmail.com Thu Sep 18 09:31:08 2008 From: riquito at gmail.com (Riccardo Galli) Date: Thu, 18 Sep 2008 06:31:08 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: Message-ID: <79a864ab-475a-42d5-8fa0-a711219ffdef@59g2000hsb.googlegroups.com> On 17 Set, 03:29, Todd Whiteman wrote: > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming language. > > The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform (MacOSX > is possible with a few deviations, I have tried to cover these > deviations where applicable). > > Feedback is welcome. > > Cheers, > Todd well, it just works. Now let's see how :-) Nice job, Riccardo p.s. I'm on a Gentoo Linux 64 bit, no problems at all From tino at wildenhain.de Thu Sep 18 11:53:38 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 18 Sep 2008 17:53:38 +0200 Subject: improving a huge double-for cycle In-Reply-To: <48D27755.8060208@wildenhain.de> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D27755.8060208@wildenhain.de> Message-ID: <48D27982.90503@wildenhain.de> Tino Wildenhain wrote: > Hi, > > Alexzive wrote: >> Hello there :) , >> >> I am a python newbie and need to run following code for a task in an >> external simulation programm called "Abaqus" which makes use of python >> to access the mesh (ensamble of nodes with xy coordinates) of a >> certain geometrical model. >> >> [IN is the starting input containing the nodes to be check, there are >> some double nodes with the same x and y coordinates which need to be >> removed. SN is the output containing such double nodes] >> >> Code: Select all >> for i in range(len(IN)): #scan all elements of the list IN >> for j in range(len(IN)): >> if i <> j: >> if IN[i].coordinates[0] == IN[j].coordinates[0]: >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> SN.append(IN[i].label) >> > > data=dict() > for item in IN: # (what a name! ;) > data.setdefault(item.coordinates,[]).append(item) > # provided coordinates is a tuple > > dupes=[items for items in data.values() if len(items)>1] > > should give you a resulting list of lists of elements in IN > which occur more then once per coordinates. > You can then decide which ones to remove or whatever. > > If you want to have the output only containing nodes to remove, > the following would work: > > dupes=[] > for items in data.values(): > dupes.extend(items[1:]) > I did a small test - I don't know if it reflects the actual problem good enough but it seems it all runs below 1 sec each so this would be very fast compared to 15h: >>> import random >>> class Node(object): ... def __init__(self,x,y): ... self.coordinates=(x,y) >>> IN=[Node(random.randint(0,100),random.randint(0,100)) for i in xrange(100000)] >>> data=dict() >>> for item in IN: data.setdefault(item.coordinates,[]).append(item) ... >>> dupes=[items for items in data.values() if len(items)>1] >>> len(dupes) 10190 >>> Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From rocksportrocker at googlemail.com Wed Sep 3 07:39:02 2008 From: rocksportrocker at googlemail.com (Uwe Schmitt) Date: Wed, 3 Sep 2008 04:39:02 -0700 (PDT) Subject: installing matplotlib with numpy and scipy for Python in Cygwin References: Message-ID: On 3 Sep., 11:42, "chapagainanish" wrote: > Hi!! > I'm having installation problem for installing numpy and scipy in > Cygwin for Python, and am obstruct in madway for project, i followed > scipy.org guidelines but there's few error thrown as > ? ? ? ? failed..with exit status 1 > > please if someone has installed these module help me > thank's and regard's > Anish http://cens.ioc.ee/~pearu/scipy/BUILD_WIN32.html may help you. Do you really want a cygwin based installation ? You could download enthoughts python edition which includes lots of math stuff. Greetings, Uwe From celephicus at gmail.com Mon Sep 8 18:32:29 2008 From: celephicus at gmail.com (Tom Harris) Date: Tue, 9 Sep 2008 08:32:29 +1000 Subject: Numeric literal syntax In-Reply-To: References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: On Thu, Sep 4, 2008 at 10:22 AM, Alexander Schmolck wrote: > > It's amazing that after over half a century of computing we still can't denote > numbers with more than 4 digits readably in the vast majority of contexts. > I agree. So did Forth's early designers. That is why Forth's number parser considers a word that starts with a number and has embedded punctuation to be a 32 bit integer, and simply ignores the punctuation. I haven't used Forth in years, but it seems a neat solution to the problem of decoding a long string of numbers: let the user put in whatever they want, the parser ignores it. I usually used a comma (with no surrounding whitespace of course), but it was your choice. You could also do this in whatever base you were working in, so you could punctuate a 32 bit hex number to correspond to the bit fields inside it. Of course not applicable to Python. -- Tom Harris From tjreedy at udel.edu Tue Sep 2 17:35:20 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 02 Sep 2008 17:35:20 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> Message-ID: Gabriel Genellina wrote: > Classes represent "things", and class names should be nouns. > Functions represent "actions", and their names should be verbs. popen > is a good name for a function; Popen is a bad name for a class. People who don't like Popen should have made this argument when subprocess was being designed (for 2.4) ;-). Or at least a year ago or even 6 month ago when API changes for 3.0 were considered. Part of the reason for the name is that .Popen completely replaces the popen2, popen3, and popen4 functions, and others (yes, functions, not classes), now gone (3.0) and either replaces or supplement os.popen itself. I would not have liked subprocess.Subprocess. Perhaps Proc would have been okay. PipedProcess is too long. .... From prologic at shortcircuit.net.au Sun Sep 21 18:26:57 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 08:26:57 +1000 Subject: how can i check whether a variable is iterable in my code? In-Reply-To: References: Message-ID: satoru, I should point out that the normal approach is to just try whatever it is that you're doing, and let it fail where it fails. For example: def processSeq(x): for i in x: print i processSeq([1, 2, 3]) processSeq("foobar") processSeq(5) <-- This will fail. cheers James On Sat, Sep 20, 2008 at 7:28 PM, satoru wrote: > hi, all > i want to check if a variable is iterable like a list, how can i > implement this? > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From dudeja.rajat at gmail.com Tue Sep 30 06:57:49 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 30 Sep 2008 11:57:49 +0100 Subject: Tix Combo box problem - remains in editable mode only Message-ID: Hi I'm facing a problem with the tix combo box in a way that my combo box is always in an editable mode after I have cleared subwidgets Entry and Listbox from it. My setup is like this : CheckButton1 : If this is unset, the combo box should get disabled, the entries in it should get cleared ( entries are listbox and entry subwidgets) which in my case they get cleared. When this check box is set again, the combo box should get enabled, with no entries in listbox and entry subwidgets ( which are reallly cleared in my case.) But the combox box having being enabled is in editable mode despite of setting it to un-editable mode. The code is as follows: #Combo Box self.cbAnalysisLibVersion = Tix.ComboBox(self.frame1, \ dropdown = True, \ command=self.__cllbkAnalysisLibVer, \ editable=0, \ variable=verSelection, options='listbox.height 8\ listbox.width 25 \ entry.width 30 \ entry.anchor w \ entry.padx 30', \ history = False) #Check Button box self.chBtResultsComparison = Checkbutton(self.frame2, \ text = "Results Comparison", \ variable = varResultsComparison, \ command = self.__cllbkResultsComparison) def __cllbkResultsComparison(self, Event = None): subLB = self.cbAnalysisLibVersion.subwidget("listbox") subEntry = self.cbAnalysisLibVersion.subwidget("entry") if varResultsComparison.get() != 1: #Disable Tolerance Text Box self.txtTolerance.delete(1.0, END) self.txtTolerance.config(state = DISABLED, \ bg = "grey") #Delete all entries (entry & subwidget's entries) #in Reference Analysis Results Version Combo Box #and disable this combo box. #First Delete the Listbox sub-widget entries subLB.delete(0, END) subLB.config(state = DISABLED) #Then delete Entry sub-widget entries #subEntry = self.cbAnalysisLibVersion.subwidget("entry") subEntry.config(state = NORMAL) subEntry.delete(0, END) subEntry.config(state = DISABLED) self.cbAnalysisLibVersion.config(state = DISABLED) #Diable Result Comparison Button self.btViewComparisonResults.config(state = DISABLED) else: #Check box is ticked #Enable the Tolerance text box self.txtTolerance.config(state = NORMAL, \ bg = "white") #Enable the Reference Analysis Combo box #self.cbAnalysisLibVersion.config(state = NORMAL, editable=0) self.cbAnalysisLibVersion.configure(state = NORMAL, editable = 0) subLB.config(state = NORMAL) subEntry.config(state = NORMAL) self.btViewComparisonResults.config(state = NORMAL) Please suggest what is that I am missing Regards, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: From fredrik at pythonware.com Sun Sep 21 11:27:11 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 21 Sep 2008 17:27:11 +0200 Subject: Why are "broken iterators" broken? In-Reply-To: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > According to the Python docs, once an iterator raises StopIteration, it > should continue to raise StopIteration forever. Iterators that fail to > behave in this fashion are deemed to be "broken": > > http://docs.python.org/lib/typeiter.html > > I don't understand the reasoning behind this. As I understand it, an > iterator is something like a stream. There's no constraint that once a > stream is empty it must remain empty forever. it's a design guideline, not an absolute rule. but I disagree that an iterator is "something like a stream". it's rather "something like a pointer or an index", that is, an object that helps you iterate over all members in a collection. From news1234 at free.fr Sat Sep 13 11:34:55 2008 From: news1234 at free.fr (nntpman68) Date: Sat, 13 Sep 2008 17:34:55 +0200 Subject: Code example that will make a Skype connection? In-Reply-To: References: Message-ID: <48cbdd9d$0$1895$426a34cc@news.free.fr> Hi, Just some thoughts / now answer :-( The solution might vary on the platform / OS. Would it be acceptable for you to control for example firefox from python and firefox would control skype via the skype plugin. (should exist for multiple platforms) Do you search a native python solution or would you accept, that some C-code had to be compiled. bye N Al Dykes wrote: > Can some post a Python code fragment that will to make a PC with Skpye > installed to make a Skype call, given a valid phone # string. > > I'm not asking for code that handles the audio once the connection is > made. > > > > > > From drkjam at gmail.com Sat Sep 13 09:13:00 2008 From: drkjam at gmail.com (David Moss) Date: Sat, 13 Sep 2008 06:13:00 -0700 (PDT) Subject: A service for testing Python code on multiple platforms and versions Message-ID: <97579bae-a0bb-46f1-aa41-04c126db6f58@z66g2000hsc.googlegroups.com> Hopefully a service like this already exists and I just haven't found it yet. If not it could be an idea for some kind soul(s) to pick up and run with ;-) As someone who writes and releases Python modules for the community, I find it difficult to have a decent level of confidence in the efficacy of my code on platforms and Python versions other than those that I own or use regularly. My documentation states that I support Python 2.3 or higher. This ends up being more of a statement of good intentions than a one of fact. A case in point. A bug (in Python), that I believed to have been killed off after Python 2.2, resurfaced in a 2.4.x release of Python on PowerPC recently. As I don't own any PowerPC kit, it was very difficult to a) investigate the bug and b) create an effective fix for it in a timely fashion. Fortunately I'd come across it before so the fix was easy but it might not have been. While I realise one's code can never be perfect, you can cover for these sorts of eventualities fairly easily by running your software and unit tests under different environments. You'd also like to be able to do this on a continual basis rather than just once or twice. If this was done with some kind of automated testing and reporting so much the better. Bigger projects that take code quality seriously probably already have this sort of thing in place for their own purposes, but for smaller ones it just isn't possible. Wouldn't it be great to have a service/setup out there available for Python developers to access that covered a fairly broad base of possible Python installations for the purpose of improve overall code quality? Am I the only one that would find something like this useful? Dave M. From m_palmer45 at yahoo.ca Fri Sep 19 10:21:42 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 19 Sep 2008 07:21:42 -0700 (PDT) Subject: generator exceptions References: <826a734c-968c-4d68-9ed1-c2688340ebc5@a3g2000prm.googlegroups.com> Message-ID: <42d646ff-51b1-43b7-8002-6b628e4b43bf@d77g2000hsb.googlegroups.com> On Sep 19, 9:40 am, Alexandru Mosoi wrote: > i have a generator that raises an exception when calling next(), > however if I try to catch the exception and print the traceback i get > only the line where next() was called > > while True: > try: > iterator.next() > except StopIteration: > break > except Exception, e: > traceback.print_exc() > > how do I get the traceback starting from where exception was raised in > first place? What happens if you simply remove the 'except Exception' clause? It should print the entire traceback by default. From Scott.Daniels at Acm.Org Tue Sep 16 22:14:54 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 16 Sep 2008 19:14:54 -0700 Subject: What is "finally:" for? In-Reply-To: <502e16a8-e20d-4795-a495-ce1f61fd8c15@m44g2000hsc.googlegroups.com> References: <502e16a8-e20d-4795-a495-ce1f61fd8c15@m44g2000hsc.googlegroups.com> Message-ID: Paul McGuire wrote: ... > try: > open database > do database stuff > except DatabaseException, de: > log exception > throw > finally: > close database > > Or > > try: > transaction = new database transaction > do database stuff > do more database stuff > commit transaction > transaction = None > except DatabaseException, de: > log exception > throw > finally: > if transaction: > rollback transaction Generally it is a good idea to try the advice you are about to offer. "raise" is the Python way to do the Lisp/Scheme "throw" which will likely produce another error, but not the one you want. --Scott David Daniels Scott.Daniels at Acm.Org From sjmachin at lexicon.net Fri Sep 12 16:01:01 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 Sep 2008 13:01:01 -0700 (PDT) Subject: Matching horizontal white space References: <01cee7e0-cf52-4839-bbd8-c95126fa0d11@r66g2000hsg.googlegroups.com> Message-ID: On Sep 13, 12:52?am, Fredrik Lundh wrote: > Magnus.Morab... at gmail.com wrote: > > multipleSpaces = re.compile(u'\\h+') > > > importantTextString = '\n ?\n ?\n \t\t ?' > > importantTextString = multipleSpaces.sub("M", importantTextString) > > what's "\\h" supposed to mean? Match *h*orizontal whitespace, I guess ... looks like the maintainer of the re equivalent in some other language has far too much spare time :-) From pavlovevidence at gmail.com Sat Sep 20 06:45:24 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 20 Sep 2008 03:45:24 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <40a8c7a8-027f-4a3d-bb78-71d6299429cb@i76g2000hsf.googlegroups.com> On Sep 20, 2:23 am, candide wrote: > Excerpt quoted fromhttp://www.astro.ufl.edu/~warner/prog/python.html: > > "About Python: Python is a high level scripting language with object > oriented features. > (...) > Python supports OOP and classes to an extent, but is not a full OOP > language." > > Thanks for any comment. Python is what it is, whatever you call it. That page has a whole list of features (we'll give the author the benefit of the doubt and assume they're accurate and fairly up-to-date). Those features (more or less) define what Python is, not trendy computer science catch words. Carl Banks From circularfunc at yahoo.se Tue Sep 2 14:02:23 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 2 Sep 2008 11:02:23 -0700 (PDT) Subject: Large amount of files to parse/organize, tips on algorithm? References: <00cd6d2a$0$20302$c3e8da3@news.astraweb.com> Message-ID: <6dc5719f-a65b-4194-b09c-b9bbb55ee788@e53g2000hsa.googlegroups.com> over 17000 files... netflixprize. From karaboomtown at gmail.com Thu Sep 4 00:26:20 2008 From: karaboomtown at gmail.com (karaboomtown at gmail.com) Date: Wed, 3 Sep 2008 21:26:20 -0700 (PDT) Subject: Download movies Message-ID: <9178ceda-14f4-44aa-9980-21fda6bbafb4@p10g2000prf.googlegroups.com> Download movies http://gpirate.com http://www.gpirate.com/search?hl=en&q=naruto+shippuden&btnG=Search From a.schmolck at gmail.com Wed Sep 3 20:22:22 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Thu, 04 Sep 2008 01:22:22 +0100 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: Ben Finney writes: > bearophileHUGS at lycos.com writes: > >> For Python 2.7/3.1 I'd now like to write a PEP regarding the >> underscores into the number literals, like: 0b_0101_1111, 268_435_456 >> etc. > > +1 on such a capability. > > -1 on underscore as the separator. > > When you proposed this last year, the counter-proposal was made > > to instead use white space for the separator, exactly as one can now > do with string literals. > > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > literals. It seems to me that the right choice for thousands seperator is the apostrophe. It doesn't suffer from brittleness and editing problems as whitespace does (e.g. consider filling and auto-line breaking). It is already used in some locales for this function but never for the decimal point (so no ambiguity, unlike '.' and ','). It also reads well, unlike the underscore which is visually obstrusive and ugly (compare 123'456'890 to 123_456_789). Having said that, I'd still have 123_456_789 over 123456789 any day. It's amazing that after over half a century of computing we still can't denote numbers with more than 4 digits readably in the vast majority of contexts. 'as From lists at cheimes.de Mon Sep 22 16:32:04 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 22 Sep 2008 22:32:04 +0200 Subject: Problems running on hp dual core processor In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > Interesting... The only win32ui* on my machine (running v2.4) is a > win32ui.pyd (D, not C) and it is part of the PythonWin IDE obtained as > part of the ActiveState installer for windows. > > Oh, and /how much RAM/? ".099g" sounds rather small; my PDA has > ".5G" of RAM and my desktop machine has 2.0G... A .pyd file is a Python dynamic library file. It's a dll with a different extension and a Python specific entry point. Dynamic libraries are OS and CPU architecture dependent. It might be possible that the computer has an incompatible CPU or a 64bit OS. Christian From mathieu.prevot at gmail.com Sat Sep 6 13:18:15 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Sat, 6 Sep 2008 19:18:15 +0200 Subject: Failure in building ctypes with intel icc Message-ID: <3e473cc60809061018k19dbd3a2n4b0f9dabedbe5b4@mail.gmail.com> Hi, I got this error in compilation, and I don't know how to solve it: *** WARNING: renaming "_ctypes" since importing it failed: dlopen(build/lib.macosx-10.3-i386-2.6/_ctypes.so, 2): Symbol not found: ___builtin_dwarf_cfa Referenced from: /Users/mathieuprevot/svn/python/build/lib.macosx-10.3-i386-2.6/_ctypes.so Expected in: dynamic lookup Any hints ? thanks, Mathieu From robert.kern at gmail.com Tue Sep 16 22:05:21 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 16 Sep 2008 21:05:21 -0500 Subject: Python Linear Programming on Ubuntu In-Reply-To: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> Message-ID: Fett wrote: > I am trying to find a wrapper to do linear programming within python. > I am using an ubuntu machine and I have apt-get'd lp_solve, which > works just fine. If someone knows of a wrapper that will work with > that that'd be great. > > I also heard that scipy has a wrapper, however, I can't find any > documentation on it, nor can I seem to find it with dir(). If anyone > knows where there is good documentation on this I would love to use > that (the more native to python the better imo). No, scipy doesn't have such a wrapper, sorry. > I have tried many things, including http://lpsolve.sourceforge.net/5.5/Python.htm, > openopt, and cvxopt. I can't seem to find any with enough > documentation to get me off the ground. Some I can't compile, some I > can't even find out how to compile. > > If anyone knows of an LP package (preferably with IP as well, like > lp_solve has), that interfaces well with python and has enough > documentation to get a dependency newb like myself off the ground that > would be great. PuLP should be fairly easy to build against GLPK or COIN (provided you have them installed; I'm pretty sure Ubuntu has a GLPK package but I'm not sure about COIN), but you will have to edit the Makefile for your system: http://www.jeannot.org/~js/code/index.en.html#PuLP You can ask on scipy-users about OpenOpt, and hopefully Dmitrey will be able to help you. If you want to get cvxopt or the Python wrappers in lp_solve itself working, I suggest asking their mailing lists. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Mon Sep 8 19:22:58 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 Sep 2008 18:22:58 -0500 Subject: lacking follow-through In-Reply-To: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: Eric Wertman wrote: >> Perhaps the wrong idea of what the group is. I would have thought >> that >> if one had a sufficiently developed idea and wanted to have it / >> formally/ >> rejected, rather than merely sniped at, then writting a PEP would be >> more >> apposite than posting to c.l.py. >> >> It's fine to post your not sufficiently developed ideas here merely >> to >> have them discussed. But I don't know what makes you feel that you, >> or >> your ideas, are /entitled/ to any response at all, much less >> "follow-through." > > To expand on this a little bit, I've been subscribed to this group > for a couple of months, but there seems to be a bit more gray area > between what would go to a 'python-dev' group and a 'python-user' > group. Long debates about language features and abstract ideas would > appeal to the former, but not the latter. Certainly I fall into the > user category.. I'm pretty happy with python, and generally just > adjust to it's design and features, rather than spend lots of time on > whether they are 'right' or could be 'better'. /shrug Actually, python-dev is for the concrete development of Python. Releases, bugs, and occasionally design discussions for relevant features. Long debates about potential features and abstract ideas belong either here or python-ideas. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From george.sakkis at gmail.com Tue Sep 9 23:03:48 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 9 Sep 2008 20:03:48 -0700 (PDT) Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> Message-ID: <3d6488c1-d57c-46be-b404-9c79bd49dbdf@y21g2000hsf.googlegroups.com> On Sep 9, 5:59?pm, castironpi wrote: > I will try my idea again. ?I want to talk to people about a > module I want to write and I will take the time to explain it. >?I think it's a "cool idea" that a lot of people, forgiving the > slang, could benefit from. ? > > (snipped) > > A pure Python alloc-free implementation based on the GNU PAVL > tree library is on Google Code. ?It is only in proof-of-concept > form and not commented, but does contain a first-pass test > suite. ?See: > ? ?http://code.google.com/p/pymmapstruct/source/browse/#svn/trunk So at best (i.e. if it actually makes any sense; I didn't read it), this is an ANNouncement of a pre-alpha piece of code. ANN posts rarely attract replies, even when they are about production/stable software. Thankfully, most people don't expect (let alone "require") readers to share their interest or enthusiasm by replying to the ANN. Given your past semi-coherent and incoherent posts, expecting people to jump on such a thread is a rather tall order. George From deets at nospam.web.de Wed Sep 24 18:58:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 00:58:33 +0200 Subject: Folder Actions on Mac OSX Leopard? In-Reply-To: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> References: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> Message-ID: <6jvv0pF5cvjlU1@mid.uni-berlin.de> squishywaffle at gmail.com schrieb: > Greetings, > > I've been trying to figure out if it's possible to attach a Python > script to an action via Mac OSX Leopard's File Actions system. I'm > wanting to call a Python script every time a file is added to the > monitored folder. Just adding a .py file doesn't seem to do anything > at all, and I can't find any log output anywhere to see what's going > on. > > I'm more just looking to see if this is or is not possible. I'm not > interested in other solutions, as I already have them lined up in case > this is a no-go, but I'd really love to be able to do it this way if > anyone has any experience. Googling around revealed pretty much > nothing. You mean this? http://developer.apple.com/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/chapter_2_section_1.html *I* would use ctypes to access Carbon Core. But then that's just me - I'm sure you find a better way... Diez From mensanator at aol.com Mon Sep 29 19:08:28 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 29 Sep 2008 16:08:28 -0700 (PDT) Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: On Sep 29, 5:04?pm, Ivan Reborin wrote: > Hello everyone, > > I was wondering if anyone here has a moment of time to help me with 2 > things that have been bugging me. > > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? > > 2. I've read the help on the next one but I just find it difficult > understanding it. > I have; > a=2.000001 > b=123456.789 > c=1234.0001 > > How do you print them with the same number of decimals ? > (eg. 2.000, 123456.789, 1234.000) >>> print '%0.3f' % 2.000001 2.000 >>> print '%0.3f' % 123456.789 123456.789 >>> print '%0.3f' % 1234.0001 1234.000 > and how do you print them with the same number of significant > decimals? > (eg. 2.000001, 123456.7, 1234.000 - always 8 decimals) ? Your examples are 7 decimals (and you're not rounding). Here's what 8 looks like (note that it's %0.7e because there is always one digit to the left of the decimal point.) >>> print '%0.7e' % 2.000001 2.0000010e+00 >>> print '%0.7e' % 123456.789 1.2345679e+05 >>> print '%0.7e' % 1234.0001 1.2340001e+03 If you actually meant 7, then use %0.6e: >>> print '%0.6e' % 2.000001 2.000001e+00 >>> print '%0.6e' % 123456.789 1.234568e+05 >>> print '%0.6e' % 1234.0001 1.234000e+03 > > Is something like this possible (built-in) in python ? You can do more with gmpy. > > Really grateful for all the help and time you can spare. > > -- > Ivan From bdesth.quelquechose at free.quelquepart.fr Fri Sep 26 16:03:39 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 22:03:39 +0200 Subject: is decorator the right thing to use? In-Reply-To: References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> Message-ID: <48dd5c06$0$26425$426a74cc@news.free.fr> Dmitry S. Makovey a ?crit : > Paul McGuire wrote: >>> see, in your code you're assuming that there's only 1 property ( 'b' ) >>> inside of A that needs proxying. In reality I have several. > >> No, really, Diez has posted the canonical Proxy form in Python, using >> __getattr__ on the proxy, and then redirecting to the contained >> delegate object. This code does *not* assume that only one property >> ('b'? where did that come from?) is being redirected - __getattr__ >> will intercept all attribute lookups and redirect them to the >> delegate. >> >> If you need to get fancier and support this single-proxy-to-multiple- >> delegates form, then yes, you will need some kind of map that says >> which method should delegate to which object. Or, if it is just a >> matter of precedence (try A, then try B, then...), then use hasattr to >> see if the first delegate has the given attribute, and if not, move on >> to the next. > > that is what I didn't like about it - I have to iterate over delegates when > I can build direct mapping once and for all and tie it to class > definition ;) Hem... I'm afraid you don't really take Python's dynamic nature into account here. Do you know that even the __class__ attribute of an instance can be rebound at runtime ? What about 'once and for all' then ? But anyway: >> Your original question was "is decorator the right thing to use?" For >> this application, the answer is "no". > > yeah. seems that way. in the other fork of this thread you'll find my > conclusion which agrees with that :) > >> It sounds like you are trying >> to force this particular to solution to your problem, but you are >> probably better off giving __getattr__ intercepting another look. > > __getattr__ implies constant lookups and checks (for filtering purposes) Unless you cache the lookups results... > - I > want to do them once, attach generated methods as native methods What is a "native method" ? You might not be aware of the fact that method objects are usually built anew from functions on each method call... > and be > done with it. That is why I do not like __getattr__ in this particular > case. There's indeed an additional penalty using __getattr__, which is that it's only called as a last resort. Now remember that premature optimization is the root of evil... Depending on effective use (ie : how often a same 'proxied' method is called on a given Proxy instance, on average), using __getattr__ to retrieve the appropriate bound method on the delegate then adding it to the proxy instance *as an instance attribute* might be a way better (and simpler) optimization. From stava at telcotec.se Sat Sep 27 04:49:09 2008 From: stava at telcotec.se (Lars Stavholm) Date: Sat, 27 Sep 2008 10:49:09 +0200 Subject: python for *nix system admins In-Reply-To: References: <48DDE92D.6090405@telcotec.se> Message-ID: <48DDF385.3010101@telcotec.se> km wrote: > import os Thanks, but I'm aware of the standard libraries like os, sys, commands, and whatnot. I'm looking for a non-standard library that acts like a wrapper for the unix commands. I have seen it, I just can't find it again. /L > On Sat, Sep 27, 2008 at 1:35 PM, Lars Stavholm > wrote: > > Hi All, > > I'm new to this list and hoping that this is not off-topic. > If it is, please point me in the right direction. > > I seem to recollect a python module or library for *nix sysadmins, > but I can't for the life of me find it again. > > The module (or library) somehow added unix command capabilities > to the python language. It seemed like a lesser known, perhaps new, > python library or module. > > Any input or ideas appreciated > /Lars Stavholm > -- > http://mail.python.org/mailman/listinfo/python-list > > From digitig at gmail.com Sat Sep 27 19:55:45 2008 From: digitig at gmail.com (Tim Rowe) Date: Sun, 28 Sep 2008 00:55:45 +0100 Subject: Not fully OO ? In-Reply-To: <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> <4fe2a7a5-8284-4b7c-9e08-f5d8f0d9d127@p25g2000hsf.googlegroups.com> Message-ID: 2008/9/27 Aaron Castironpi Brady : > No way. It's *zero* instead of one, if so, because the only thing C# > has is a bunch of handcuffs and implicit 'self'. You have a line > like: You don't follow what I said, and from your tone I get the feeling you don't *want* to follow what I'm saying, not because I'm criticising Python (I'm not), but because I'm guilty of the heresy of suggesting that it's not actually simultaneoulsy optimised for every possible use. My point is that there are zero parameters as far as I am concerned because I don't actually touch most of the GUI code. There could actually be hundreds of parameters, for all I care. They're not my concern. Most of the time I like that -- the tools are doing my work for me. -- Tim Rowe From deets at nospam.web.de Wed Sep 10 07:58:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 13:58:38 +0200 Subject: I want to use a C++ library from Python References: <6ipd53FrptpiU1@mid.uni-berlin.de> <5a8d289c-788b-4f0d-9fca-e47aaa214ce4@s50g2000hsb.googlegroups.com> Message-ID: <6ipr40Fr7kr2U1@mid.uni-berlin.de> kaer wrote: > On 10 sep, 10:00, "Diez B. Roggisch" wrote: >> Anders Eriksson schrieb: >> >> > Hello, >> >> > I have a C++ library compiled as Windows DLL's. It consists of 32 .h >> > and 1 .lib and 1 .dll files. I don't have the source code. >> >> > How can I create a Python module from these files? >> >> Did you bother googling? >> >> http://www.google.de/search?q=python+c%2B%2B&ie=utf-8&oe=utf-8 >> >> Diez > > You may want google "python dll" as well. Good luck. Which actually isn't really helpful, as a DLL itself says nothing about what language was used to create it - and sending the OP to e.g. ctypes makes no sense at all in the face of C++. Whereas the first link for "python c++" is Boost::Python, a C++-wrapper to make C++-code accessible from Python. Diez From python at rcn.com Tue Sep 16 12:19:07 2008 From: python at rcn.com (Raymond Hettinger) Date: Tue, 16 Sep 2008 09:19:07 -0700 (PDT) Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> <00dbe9f8$0$20302$c3e8da3@news.astraweb.com> <87fxo3bxlu.fsf@mulj.homelinux.net> Message-ID: On Sep 13, 9:27?pm, Hrvoje Niksic wrote: > Note that, despite appearances, it's not as built-in as one might > wish. ?sum(seq) is still completely generic and works on all > number-like objects (in fact on all objects that define an __add__ > operation except strings, which are explicitly forbidden). ?This means > that it can't just go ahead and execute a C addition, it must properly > call PyNumber_Add (the C API call equivalent to Python's "+" > operator), which will then inspect the objects and invoke the > appropriate implementation of addition. The time machine strikes again! Try using Py2.6. The built-in sum() function is much smarter and faster. It does in fact use C addition. Raymond From steve at REMOVE-THIS-cybersource.com.au Tue Sep 30 19:38:19 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 23:38:19 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: <00f2b214$0$20617$c3e8da3@news.astraweb.com> On Tue, 30 Sep 2008 10:57:19 -0500, Grant Edwards wrote: >>> How would the python equivalent go ? > > You would drag yourself out of the 1960s, install numpy, and then do > something like this: I think that was thoughtlessly rude to somebody who is asking a perfectly reasonable question. -- Steven From grante at visi.com Wed Sep 10 13:51:28 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 12:51:28 -0500 Subject: Gateway to python-list is generating bounce messages. Message-ID: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> Could whoever is responsible for the gateway that is grabbing my postings off of Usenet and e-mailing them out please fix the headers in the mail messages so that I don't get the bounce messages? While you're at it, might as well fix it for everybody else too. ;) Its a bit rude to send out mass e-mail messages with headers faked up so that the bounce messages go to somebody else. -- Grant Edwards grante Yow! As President I have at to go vacuum my coin visi.com collection! From fredrik at pythonware.com Tue Sep 2 13:22:32 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 02 Sep 2008 19:22:32 +0200 Subject: What is module initialization? In-Reply-To: References: <48bd4799$0$17215$426a74cc@news.free.fr> Message-ID: dudeja.rajat at gmail.com wrote: >> # myglobals.py: >> answer = 42 >> >> # question.py >> import myglobals >> myglobals.answer = "WTF ?" >> > > But if I do :- > #question.py > from myglobals import * > myglobals.answer = "WTF ?" > > will this work? with the above definition of myglobals, no. "from myglobals import" doesn't add the module object to the importing module's namespace. have you read: http://effbot.org/zone/import-confusion.htm ? From dear.jay.logan at gmail.com Sun Sep 21 23:05:06 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Sun, 21 Sep 2008 20:05:06 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 Message-ID: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Hello, I have 2 questions. Say I have this class: class Player(object): def __init__(self, fname, lname, score): self.score = score self.fname = fname self.lname = lname def __cmp__(self, other): return (-cmp(self.score, other.score) or cmp(self.lname, other.lname) or cmp(self.fname, other.fname)) def __repr__(self): return 'Player(fname={0.fname}, lname={0.lname}, score={0.score})'.format(self) def __eq__(self, others): if isinstance(other, Player): return (self.score == other.score and self.lname == other.lname and self.fname == other.fname) return False def __ne__(self, others): return not self.__eq__(others) fnames = ['Julie', 'Ben', 'Jason', 'David'] lnames = ['Parks', 'Smith'] scores = [100, 95, 95, 130, 58, 74] import itertools as it score_iter = it.cycle(scores) P = [Player(fn, ln, next(score_iter)) for fn in fnames for ln in lnames] cmp(P[0], P[1]) # returns -1 sorted(P) # throws TypeError: unorderable types Player() < Player() The sorted function works when I define __lt__. I must be misreading the documentation, because I read for the documentation __cmp__ that it is called if none of the other rich comparison functions are defined. Is this a bug in Python 3.0rc1, or am I missing something? Secondly, say that we suddenly need another sorting order, where we want to sort by decreasing score and then by DECREASING last name (instead of increasing last name, defined above). Now that the comparison function argument is taken away from the sorted builtin, how do we accomplish this with the "key" parameter? Thank you From hniksic at xemacs.org Sat Sep 27 11:16:01 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 27 Sep 2008 17:16:01 +0200 Subject: Using the 'with' statement with cStringIO objects References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> <1222522300.659080@athprx04> Message-ID: <87zllt7h72.fsf@mulj.homelinux.net> George Boutsioukis writes: > Neither, just not implemented. Only classes with __enter__ and > __exit__ methods(ie context manager types) can be used in with > statements. And, correct me if I'm wrong, I think it's pointless for > a StringIO object to have those. It's definitely superfluous, but it should still be provided, for the same reason a "close" method is provided, to allow StringIO objects to be treated like other file-like objects. For example, code that does the following: with obj.open_file(...) as f: ... shouldn't have to care if obj.open_file returns a built-in file instance, or a StringIO instance. As the above code becomes more popular, __enter__ and __exit__ are beginning to be part of the file interface (in the duck-typing sense) and should be implemented. Until then, the the contextlib.closing context manager can be used instead: with contextlib.closing(obj.open_file(...)) as f: ... From enleverlesX.XmcX at XmclaveauX.com Sun Sep 21 04:32:12 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sun, 21 Sep 2008 10:32:12 +0200 Subject: Not fully OO ? In-Reply-To: <48d4c11b$0$22877$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <48d608b7$0$957$ba4acef3@news.orange.fr> Bonjour ! AMHA, ceux qui ont ?crit ce texte ont une mauvaise id?e de ce que sont les variables en Python. Ils ont sans doute trop en t?te les notions des variables en C ou en Basic, et ne se sont pas pench?s sur les sp?cificit?s de Python. @-salutations -- Michel Claveau From george.sakkis at gmail.com Fri Sep 26 22:29:43 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 26 Sep 2008 19:29:43 -0700 (PDT) Subject: getting global variables from dictionary References: <19b38117-8f4c-4925-83bf-b3dd9ef585be@s9g2000prg.googlegroups.com> Message-ID: On Sep 26, 10:01?pm, icarus wrote: > global_vars.py has the global variables > set_var.py changes one of the values on the global variables (don't > close it or terminate) > get_var.py retrieves the recently value changed (triggered right after > set_var.py above) > > Problem: get_var.py retrieves the old value, the built-in one but not > the recently changed value in set_var.py. > > What am I doing wrong? > > ----global_vars.py--- > #!/usr/bin/python > > class Variables : > ? ? ? ? def __init__(self) : > ? ? ? ? ? ? ? ? self.var_dict = {"username": "original username"} > > ---set_var.py --- > #!/usr/bin/python > > import time > import global_vars > > global_vars.Variables().var_dict["username"] = "new username" > time.sleep(10) ? #give enough time to trigger get_var.py > > ---get_var.py --- > #!/usr/bin/python > import global_vars > print global_vars.Variables().var_dict.get("username") First off, you don't import the set_var module anywhere; how do you expect the value to change? Second, every time you do "global_vars.Variables()" you create a brand new Variables() instance, initialized with the original var_dict. The Variables() instance you create at set_var.py is discarded in the very next line. Third, I have no idea why you put the "time.sleep(10)" there. By the way, Python is not Java; you don't have to make classes for everything. A working version of your example would be: ----global_vars.py--- var_dict = {"username": "original username"} ---set_var.py --- import global_vars global_vars.var_dict["username"] = "new username" ---get_var.py --- import global_vars import set_var print global_vars.var_dict.get("username") $ python get_var.py new username HTH, George From digitig at gmail.com Fri Sep 26 19:12:16 2008 From: digitig at gmail.com (Tim Rowe) Date: Sat, 27 Sep 2008 00:12:16 +0100 Subject: Not fully OO ? In-Reply-To: <48dd5f08$0$26425$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <48dd5f08$0$26425$426a74cc@news.free.fr> Message-ID: 2008/9/26 Bruno Desthuilliers : > Not to start a troll, but from what I've seen of C# so far I do find this a > bit surprising and really suspect more of a library issue than a language > one. Care to tell more about the problem and solution ? > > (NB : I wouldn't even asked if you had mentionned say Erlang or Prolog or > OCaml - well, some mostly different language - instead of C#) IIRC it was library issues -- for one thing I still find it a lot harder to manage an MS Windows GUI under Python than I do under .NET (I've never succeeded in getting Iron Python to run properly). In one sense you could argue that that's not a language issue, and you'd be right: there's nothing in the syntax or semantics of either language that makes it so. But in another sense I'd say it is a language issue (and of course I think I'm right!) because Python aims to be platform independent, and whilst that means gains in portability it means that in return it loses the ease-of-programming of a tightly integrated platform. -- Tim Rowe From garyr at fidalgo.net Mon Sep 22 16:55:23 2008 From: garyr at fidalgo.net (garyr) Date: Mon, 22 Sep 2008 13:55:23 -0700 (PDT) Subject: Tkinter 3000 WCK Install Problem Message-ID: <0dd2b0dc-f6cb-4b70-8f35-d50446fdd901@2g2000hsn.googlegroups.com> I'm trying to install WCK. I downloaded and installed the Windows executable for my Python version. It appeared to run OK. I then downloaded the demo files but find that none run due to error: ImportError: No module named _tk3draw. I'm using ActivePython 2.3.5 on Windows XP Home. What can I do to fix this problem? From lanny at freshells.ch Sat Sep 6 14:44:04 2008 From: lanny at freshells.ch (Lanny) Date: Sat, 6 Sep 2008 11:44:04 -0700 Subject: indices question Message-ID: pretty self-explanatory, here's what I put in: while stat == 0 : pgrid#ignore, A pre-defined function print "what cell do you want?" varcc = raw_input grid[varc] = 'O' And here's what I get back: Traceback (most recent call last): File "C:\py_prog\Tic Tac Toe.py", line 27, in grid[varc] = 'O' TypeError: list indices must be integers Please don't tell me that "list indices must be integers" because I know that, Why can't I put a varible thats an integer instead? -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From rogeruclan at gmail.com Tue Sep 16 06:44:44 2008 From: rogeruclan at gmail.com (RLC) Date: Tue, 16 Sep 2008 03:44:44 -0700 (PDT) Subject: help on python SWIG C++ extension Message-ID: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> Hello I am new to python SWIG. Recently I wrote a small program trying to import collada files(using colladadom) into python so I could use python cgkit to render them. However, during the progressing, I got some problems. Every time I quit from Python, I get a segmentation fault, although the main program runs well. I suspect it is because I wrapped std::vector objects in C struct and I did not release the memory properly. Below is the code. I am working on FreeBSD 7.0, GCC 4.2.1. I will be very appreciated if you could help me. Thanks a lot. the error I have got Segmentation fault: 11 (core dumped) //////////////////////// ///Header file //////////////////////// #ifndef TDIMPORT_H #define TDIMPORT_H #include #include #include "math.h" #include "float.h" #define WORDINVALIDVALUE ULONG_MAX #define FLOATINVALIDVALUE FLT_MAX typedef unsigned long WORD; typedef struct { double x,y,z; } Vertex; extern Vertex *new_Vertex(double x, double y, double z); extern void delete_Vertex(Vertex *v); extern double Vertex_length(Vertex *v); static const Vertex UNDEFINEDVERTEX = {FLT_MAX,FLT_MAX,FLT_MAX}; typedef struct { double u,v; } UV; extern UV *new_UV(double u, double v); extern void delete_UV(UV *uv); static const UV UNDEFINEDUV = {FLT_MAX,FLT_MAX}; typedef struct { double red,green,blue,alpha; } Color; extern Color *new_Color(double red, double green, double blue, double alpha); extern void delete_Color(Color *color); static const Color BLACK = {0.0, 0.0, 0.0, 1.0}; static const Color WHITE = {1.0, 1.0, 1.0, 1.0}; typedef struct { int type; Color color; std::string texture; } Material; typedef struct { std::vector vertices; std::vector polygonNbVertices; std::vector polygonStartVertexIndex; std::vector polygonVerticesIndices; std::vector uvs; std::vector polygonNbUVs; std::vector polygonStartUVIndex; std::vector polygonUVsIndices; Material material; } PolygonMesh; extern PolygonMesh *new_PolygonMesh(); extern void delete_PolygonMesh(PolygonMesh *p); extern unsigned long PolygonMesh_countvertices(PolygonMesh *p); extern unsigned long PolygonMesh_countpolygons(PolygonMesh *p); extern void PolygonMesh_appendvertex(PolygonMesh *p, Vertex *vertex); extern Vertex PolygonMesh_getvertex(PolygonMesh *p, unsigned long vertexIndex); extern void PolygonMesh_appendpolygon(PolygonMesh *p, const std::vector& verticesIndices); extern long PolygonMesh_getpolygonverticescount(PolygonMesh *p, unsigned long polygonIndex); extern std::vector PolygonMesh_getpolygonverticesindices(PolygonMesh *p, unsigned long polygonIndex); #endif ////////////////////////// //// implementation ////////////////////////// #include "tdimport.h" Vertex *new_Vertex(double x, double y, double z) { Vertex *v; v = (Vertex *)malloc(sizeof(Vertex)); v->x = x; v->y = y; v->z = z; return v; } void delete_Vertex(Vertex *v) { free(v); } double Vertex_length(Vertex *v) { return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); } UV *new_UV(double u, double v) { UV *uv; uv = (UV *)malloc(sizeof(UV)); uv->u = u; uv->v = v; return uv; } void delete_UV(UV *uv) { free(uv); } Color *new_Color(double r, double g, double b, double a) { Color *color; color = (Color *)malloc(sizeof(Color)); color->red = r; color->green = g; color->blue = b; color->alpha = a; return color; } void delete_Color(Color *color) { free(color); } PolygonMesh *new_PolygonMesh() { PolygonMesh *p; p = (PolygonMesh *)malloc(sizeof(PolygonMesh)); p->vertices.clear(); p->polygonNbVertices.clear(); p->polygonStartVertexIndex.clear(); p->polygonVerticesIndices.clear(); p->uvs.clear(); p->polygonNbUVs.clear(); p->polygonStartUVIndex.clear(); p->polygonUVsIndices.clear(); return p; } void delete_PolygonMesh(PolygonMesh *p) { free(p); } unsigned long PolygonMesh_countvertices(PolygonMesh *p) { return (unsigned long)p->vertices.size(); } unsigned long PolygonMesh_countpolygons(PolygonMesh *p) { return (unsigned long)p->polygonNbVertices.size(); } void PolygonMesh_appendvertex(PolygonMesh *p, Vertex *vertex) { p->vertices.push_back(*vertex); } void PolygonMesh_appendpolygon(PolygonMesh *p, const std::vector& verticesIndices) { unsigned int i; for ( i = 0 ; i < verticesIndices.size() ; i++ ) p->polygonVerticesIndices.push_back(verticesIndices.at(i)); p->polygonStartVertexIndex.push_back(p- >polygonVerticesIndices.size()-verticesIndices.size()); p->polygonNbVertices.push_back(verticesIndices.size()); } Vertex PolygonMesh_getvertex(PolygonMesh *p, unsigned long vertexIndex) { if (vertexIndex < 0 || vertexIndex>=p->vertices.size() ) { return UNDEFINEDVERTEX; } else { return p->vertices.at(vertexIndex); } } long PolygonMesh_getpolygonverticescount(PolygonMesh *p, unsigned long polygonIndex) { if ((polygonIndex < 0) || (polygonIndex >= p- >polygonStartVertexIndex.size())) { return (long)-1; } else { return (long)p->polygonNbVertices.at(polygonIndex); } } std::vector PolygonMesh_getpolygonverticesindices(PolygonMesh *p, unsigned long polygonIndex) { std::vector tmp; tmp.clear(); if ((polygonIndex < 0) || (polygonIndex >= p- >polygonStartVertexIndex.size())) { return tmp; } else { unsigned long count = p->polygonNbVertices.at(polygonIndex); unsigned long start = p->polygonStartVertexIndex.at(polygonIndex); for (unsigned long i=0; ipolygonVerticesIndices.at(i+start)); return tmp; } } ///////////////////////// ////SWIG interface ///////////////////////// %module tdimport %{ #include "tdimport.h" %} %include "std_string.i" %include "std_vector.i" namespace std { %template(IntVector) vector; %template(UIVector) vector; %template(VertexVector) vector; %template(UVVector) vector; } using namespace std; typedef struct { double x,y,z; %extend { Vertex (double,double,double); ~Vertex(); double length(); } } Vertex; typedef struct { double u,v; %extend { UV (double,double); ~UV(); } } UV; typedef struct { double red,green,blue,alpha; %extend { Color (double,double,double,double); ~Color(); } } Color; %apply const std::string& {std::string* texture}; typedef struct { int type; Color color; std::string texture; } Material; typedef struct { std::vector vertices; std::vector polygonNbVertices; std::vector polygonStartVertexIndex; std::vector polygonVerticesIndices; std::vector uvs; std::vector polygonNbUVs; std::vector polygonStartUVIndex; std::vector polygonUVsIndices; Material material; %extend { PolygonMesh(); ~PolygonMesh(); unsigned long countvertices(); unsigned long countpolygons(); void appendvertex(Vertex*); Vertex getvertex (unsigned long) ; void appendpolygon(const std::vector&); long getpolygonverticescount(unsigned long); std::vector getpolygonverticesindices(unsigned long); } } PolygonMesh; ///////////////////////// ////python file ///////////////////////// #!/usr/local/bin/python import tdimport a = tdimport.PolygonMesh() a.appendvertex(tdimport.Vertex(1.0,0.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,0.0)) a.appendvertex(tdimport.Vertex(1.0,1.0,1.0)) a.appendpolygon([1,2,3]) b = a.getpolygonverticescount(0) print b del a //////////////////////////// ///compile command //////////////////////////// swig -c++ -python tdimport.i g++ -c tdimport.cpp g++ -c tdimport_wrap.cxx -I/usr/local/include/python2.5 g++ -shared tdimport.o tdimport_wrap.o -o _tdimport.so From steve at REMOVE-THIS-cybersource.com.au Sat Sep 20 20:47:23 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 00:47:23 GMT Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: <00e5938e$0$20331$c3e8da3@news.astraweb.com> On Sat, 20 Sep 2008 16:27:41 -0700, Alex Snast wrote: > Another quick question please, is the List data structure just a dynamic > array? If so how can you use static size array, linked list, AVL trees > etcetera. Before I answer your question, I should say that you can go a LONG way with just the standard Python built-in data structures list, dict and set, plus a handful of standard modules like array and collections. It's often (but not always) better to modify an algorithm to use a built-in data structure than to try to implement your own. The underlying data structure for lists is implementation specific. Only the behaviour is specified by the language. In the standard Python implementation written in C (usually known as "Python", although sometimes people explicitly describe it as CPython), lists are implemented as a fixed array of pointers. The array is periodically resized, either up or down, but only as needed. The largest consequence of that is that appending to the end of a list is much faster than inserting at the beginning of the list. Other implementations (IronPython, Jython, PyPy, CLPython...) are free to implement lists whatever way they need. If you want a static list, the simplest way is to create a list and simply not resize it. If you want to enforce that, here's a subclass to get you started: class StaticList(list): def _resize(self): raise RuntimeError("list can't be resized") extend = append = pop = insert = remove = \ __delitem__ = __delslice__ = _resize I haven't dealt with __setitem__ or __setslice__, because they're more complicated: you need to make sure the slice you're setting has the same size as the bit you're replacing, so that this is allowed: mylist[3:6] = [1, 2, 3] but not these: mylist[3:6] = [1, 2] mylist[3:6] = [1, 2, 3, 4] As for linked lists and trees, don't worry about pointers, just go ahead and implement them. # basic, no-frills tree class Node(object): def __init__(self, data, left=None, right=None): self.left = left self.right = right self.info = data tree = Node('top of the tree') tree.left = Node('left subtree') tree.right = Node('right subtree', None, Node('another subtree')) t = tree.right.right t.left = Node('yet another subtree') etc. The CPython implementation of dict is a hash table, and dicts are extremely fast and efficient. So long as you don't mind losing the order of insertion, you won't beat dicts for speed and efficiency in anything you write in pure Python. -- Steven From deets at nospam.web.de Mon Sep 8 08:45:33 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 Sep 2008 14:45:33 +0200 Subject: tracking collection modification References: <42d9688f-1058-4ed7-8d9d-affd432fdb41@s1g2000pra.googlegroups.com> Message-ID: <6ikl42Fr7422U1@mid.uni-berlin.de> usenet.tolomea at gmail.com wrote: > On Sep 7, 8:54?pm, usenet.tolo... at gmail.com wrote: >> I'm working on a remote object system, something kinda like Pyro. >> For the purposes of caching I need to be able to tell if a given >> dict / list / set has been modified. >> Ideally what I'd like is for them to have a modification count >> variable that increments every time the particular collection is >> modified. Unfortunately I can't find anything like that and since this >> needs to work for the regular normal list / dict / set objects >> subclassing them to add the modification count isn't useful. >> I realize I could take a copy and then compare the copy to the >> original, but that's a fairly heavy handed approach and I was hoping >> for something light and fast. >> Does anyone have any suggestions on best to approach this? > > additionally I don't need to know if the things the list (etc) > references have changed, only the list itself No chance. E.g. ZODB is faced with the same problem and requires you to use certain collection implementations to make this work. And don't forget that such a scheme is hard to implement in the face of concurrent access by various clients - as client connection has to keep track of the last-modified-state separately. I'd say that for small to medium-sized collections, it's faster to just marshal them each time. Beyond that, make the heavy-handed checking - and offer dirty-state-aware collection classes one can use to optimize specific cases. Diez From asnast at gmail.com Fri Sep 26 13:17:42 2008 From: asnast at gmail.com (Alex Snast) Date: Fri, 26 Sep 2008 10:17:42 -0700 (PDT) Subject: Quick sort implementation in python References: <685b5a05-1d7c-4c55-9025-bddaddd4f2de@b1g2000hsg.googlegroups.com> <48dbf8f9$0$21266$9b622d9e@news.freenet.de> Message-ID: <4da8f8b2-0216-433c-89a6-39d7ab037e84@l42g2000hsc.googlegroups.com> On Sep 25, 11:47?pm, "Martin v. L?wis" wrote: > > Now as you can see I'm passing my list object to both functions along > > with their first, last indices > > I cannot really see that. More specifically, it isn't definite what the > type of the "a" argument is, nor does the specific type of "a" matter > for the algorithm. It could be a list, or it could be a different > mutable collection that is integer-indexed. > > > My question is: Is that the normal way to implement algorithms in > > python > > Yes, it is. > > > cause in c++ i've implemented that algo via a template function > > which can have a randon access data structure or not. However i have > > no idea how to access the values of a data structure that doesn't > > allow random access. > > Can you please explain how you did that in C? IOW, how did you do > the partition function (template) in case you don't have random > access to the collection? > > Regards, > Martin Why exactly do you need random access for partition function? Do can swap 2 nodes of a linked list without random access (you can swap the pointers or just swap the node values) and you traverse the list till you reach it's tail. From ldo at geek-central.gen.new_zealand Sun Sep 21 02:54:52 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 21 Sep 2008 18:54:52 +1200 Subject: CTypes on a 64 bit machine truncates pointers to 32 bits? References: <48d34449$0$2363$9b622d9e@news.freenet.de> Message-ID: In message , Ron Garret wrote: > Default return type is int, which I assumed would be > 64 bits on a 64 bit machine, but turns out it's 32. Stupid. I think preferred ABIs these days are LP64, not ILP64 or LLP64. From michel at nospam.please Mon Sep 15 14:43:05 2008 From: michel at nospam.please (Michel Leunen) Date: Mon, 15 Sep 2008 20:43:05 +0200 Subject: environment variable issue Message-ID: <48ceacb9$0$2863$ba620e4c@news.skynet.be> Hi, Could someone explain me what I'm doing wrong here? I'm trying to retrieve the value of an environment variable in Ubuntu 8.04 like this: >>> import os >>> os.environ['USER'] 'michel' This works but this doesn't: >>> os.environ['HOSTNAME'] Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ raise KeyError(key) KeyError: 'HOSTNAME' Why is it working in the first case but not in the second one. I must be missing something but it seems I'm not able to figure it out. Thanks, Michel -- Michel Leunen http://linux.leunen.com From tino at wildenhain.de Thu Sep 11 04:51:11 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Thu, 11 Sep 2008 10:51:11 +0200 Subject: max(), sum(), next() In-Reply-To: <1220499644.48bf58bc376e4@comuh.uh.cu> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <48BEE2F7.5010106@shopzeus.com> <1220499644.48bf58bc376e4@comuh.uh.cu> Message-ID: <48C8DBFF.20208@wildenhain.de> Hi, Luis Zarrabeitia wrote: > Quoting Laszlo Nagy : > ... > Even better: > > help(sum) shows > > === > sum(...) > sum(sequence, start=0) -> value > > Returns the sum of a sequence of numbers (NOT strings) plus the value > of parameter 'start'. When the sequence is empty, returns start. > === > > so the fact that sum([]) returns zero is just because the start value is zero... > sum([],object()) would return an object(). > > BTW, the original code: > >>>> sum(s for s in ["a", "b"] if len(s) > 2) > > wouldn't work anyway... it seems that sum doesn't like to sum strings: > >>>> sum(['a','b'],'') > > : sum() can't sum strings [use ''.join(seq) instead] Yes which is a bit bad anyway. I don't think hard wiring it is such a nice idea. You know, walks like a duck, smells like a duck... If it makes sense to handle things differently for performance, then please have it doing it silently, e.g. when it detects strings just use join() internally. Cheers Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From mnordhoff at mattnordhoff.com Wed Sep 24 17:46:33 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 24 Sep 2008 21:46:33 +0000 Subject: Schwartzian transform for tuple in list In-Reply-To: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> References: <47c890dc0809241419g45a176cflaaa8754bc70f1439@mail.gmail.com> Message-ID: <48DAB539.1010500@mattnordhoff.com> Chris Rebert wrote: > On Wed, Sep 24, 2008 at 2:02 PM, David Di Biase wrote: >> Hi, >> >> I have a rather large list structure with tuples contained in them (it's >> part of a specification I received) looks like so: >> [(x1,y1,r1,d1),(x2,y2,r2,d2)...] >> >> The list can range from about 800-1500 tuples in size and I'm currently >> sorting it with this: >> >> a_list.sort(lambda a, b: cmp(b[3], a[3])) > > You'd probably be better off using the 'key' keyword argument to > .sort(), which is made for the Schwartzian Transform: > > a_list.sort(key=lambda x: x[3]) > > This sorts the list items by the value produced by the key function > for each item. It's also (IIRC) faster than using a comparison > function like you're currently doing. > > Regards, > Chris Yes, using 'key' is faster than 'cmp'. If you have Python 2.4 or newer, it would also be slightly faster to use operator.itemgetter() instead of a lambda: >>> import operator >>> a_list.sort(key=operator.itemgetter(3)) >> I'm actually sorting it by the last value in the tuple (d2). I have been >> researching more efficient sorting algorithms and came across Schwartzian >> transform via these links: >> >> http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency >> http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html >> >> I get what's happening (sorta...errr...lol) but I'm not sure if it is more >> efficient in my scenario, if it is then I have no idea how to implement it >> properly :-/ >> >> Would be great if a true expert would offer a suggestion for me... >> >> Thanks! >> >> David -- From maric at aristote.info Wed Sep 3 12:11:25 2008 From: maric at aristote.info (Maric Michaud) Date: Wed, 3 Sep 2008 18:11:25 +0200 Subject: properties setting each other In-Reply-To: References: <200809031644.10870.maric@aristote.info> Message-ID: <200809031811.25914.maric@aristote.info> Le Wednesday 03 September 2008 17:40:43 mk, vous avez ?crit?: > > Note that if one property can really be computed from another, this kind > > of thing could be considered as bad design (except if the computation is > > heavy). > > Hmm, why? Is the line of thinking smth like: because the variables > should be kept to minimum and they should be calculated at the moment > they are needed? Because you have to make extra effort to keep the logical relation between value and square. self._square is not really needed, and what is not needed is just extra hassle. Doesn't it clear that your code is more hard to maintain than the alternative : class Squared(object): def __init__(self, val): self._val=val def fgetvalue(self): return self._val def fsetvalue(self, val): self._val=val value = property(fgetvalue, fsetvalue) def fgetsquare(self): return self.value ** 2 def fsetsquare(self,s): self.value = math.sqrt(s) square = property(fgetsquare, fsetsquare) -- _____________ Maric Michaud From gagsl-py2 at yahoo.com.ar Mon Sep 29 22:56:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 23:56:42 -0300 Subject: Configuring pyc directory References: Message-ID: En Sat, 27 Sep 2008 19:06:25 -0300, Robert Moore escribi?: > Is there a way to configure python to read/write compiled pyc files for > modules in a directory other than the directory containing the original > py > files? If you use the py_compile module, you can specify three files: the source file name (and path), the destination file name (and path), and the file name as reported on errors and such. -- Gabriel Genellina From ebgssth at gmail.com Mon Sep 22 22:53:59 2008 From: ebgssth at gmail.com (js) Date: Tue, 23 Sep 2008 11:53:59 +0900 Subject: How do I convert a PyObject to string in C++? In-Reply-To: References: Message-ID: PyString_AsString returns a c string. Just feed it to std::string http://docs.python.org/api/stringObjects.html#l2h-472 On Tue, Sep 23, 2008 at 11:32 AM, wrote: > I have a PyObject, say 'Hello World' , a string, > How do I convert it to a string in C++? > Thanks in advance! > -- > http://mail.python.org/mailman/listinfo/python-list > From arnodel at googlemail.com Fri Sep 12 13:43:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 12 Sep 2008 10:43:55 -0700 (PDT) Subject: manipulating files within 'for' References: Message-ID: On Sep 12, 6:11?pm, Ben Keshet wrote: > Hi Pythoneers, > > I have a question about a code I wrote with the help of someone. The > code below copy a few lines from different files into one file. It works > fine as it is given here and generates the new file 'pockets.out' > correctly, but says:"....py returned exit code 0". However, if I add > more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) it gives an > error: "Exception raised while running script". You should post the full error if you want some help which is more than speculation > > Can anyone please advice me? Why is it giving an error on multiple x but > runs well with one (I made sure that all files and folders exist, etc.). > What does exit code 0 mean? what does "exception raised" mean? I guess you are on Windows, but how do you run your script? Do you do it from the command line or do you use some IDE? -- Arnaud From clp at rebertia.com Tue Sep 2 23:57:52 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Sep 2008 20:57:52 -0700 Subject: Pass same parameter in Recursive function In-Reply-To: References: Message-ID: <47c890dc0809022057i16516db6k8591a44a45c00750@mail.gmail.com> Assuming the function is tail-recursive or the "unchanging" arguments are immutable, just use a closure: def func(self, x, y, A, B, C): def _func(x,y): return _func(g(A,B,C,x), h(A,B,C,y)) #recurse return _func(x, y) I'm unsure as to the performance impact of this though. - Chris On Tue, Sep 2, 2008 at 8:20 PM, Davy wrote: > Hi all, > > Sometimes I need to pass same parameter in recursive function. From my > point of view, the style is redundant, and I don't what to use some > global style like self.A, self.B, Is there any other choice? > > For example, > > def func(self, x, y, A, B, C): > #x, y change in recursive call > #A, B, C change in the first layer function call, but did not change > in recursive call > if (...): > func(x, y, A, B, C) > else(...): > func(x, y, A, B, C) > > Best regards, > Davy > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From invalid at invalid Fri Sep 12 19:32:59 2008 From: invalid at invalid (Grant Edwards) Date: Fri, 12 Sep 2008 18:32:59 -0500 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <00da5aca$0$2879$c3e8da3@news.astraweb.com> Message-ID: On 2008-09-12, Matt Nordhoff wrote: > I think you misunderstand. He's referring to the Sender > header, not the From header. The messages the listbot sends > out have a Sender header of > "python-list-bounces+user=example.com at python.org" (supposing > the subscriber's email address is user at example.com). Bounces > should be directed to the bitbucket or list admin or whatever, > not the user in the From header. kring.com just has a broken > mail server. So the statement below by Dennis Lee Bieber in message 97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d at earthlink.com isn't actually correct? >>Three: The bounce/ooo-reply is sent to the message author, not >>to any intermediate host(s). After all, on that end, it's >>normal email failure response -- notify the author of the >>message. It doesn't matter that the original message was posted >>on a Usenet newsgroup if that group is automatically relayed to >>members of a mailing list. -- Grant From sbassi at clubdelarazon.org Wed Sep 24 14:16:31 2008 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Wed, 24 Sep 2008 15:16:31 -0300 Subject: Making small executive file for distribution In-Reply-To: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: <9e2f512b0809241116g74e94635g3ae86f5c0c95ffcd@mail.gmail.com> On Wed, Sep 24, 2008 at 10:17 AM, Marin Brkic wrote: > As far as I know py2exe is the only option which can do such a thing > (make exe files from scripts). Is there a way to make those exe files > a little smaller (for a small script they easily go up to 5-10 mb). An alternative solution: Give them a copy of "portable python". It is a Python enviroment that can be used by just copying its file in a single directory (to run python from a pendrive for example), with the need to install any program It even work in Linux with wine (but you seldon need that since most modern Linux distros has a uptodate Python setup). See http://www.portablepython.com/ Best, -- Sebasti?n Bassi. Diplomado en Ciencia y Tecnolog?a. Vendo isla: http://www.genesdigitales.com/isla What's new in Python 3: http://tinyurl.com/5cd89r Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6 From deets at nospam.web.de Thu Sep 25 06:56:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 12:56:39 +0200 Subject: How to get the filename in the right case ? References: Message-ID: <6k1937F5i8kjU1@mid.uni-berlin.de> Stef Mientki wrote: > hello, > > How can I find the correct case of a filename ? > > Background in my program I use case sensitive filenames, just like > Python requires. > Now I've integrated pdb into the program, > but pdb acts somwhat strange: > upon a breakpoint it gives the filename always in lowercase (probably > this only happens on windows). > > So is there a way to get the correct case of a given filename in lowercase > ? > > One solution might be to make the comparison in my program always with > lowercase, > but then I'm sure the program won't work on non-windows systems. > > btw, why does pdb behave that way ( Python 2.5 ) ? I doubt it does. It sure doesn't on unix, and I fail to see any reason why it should do that on windows - given that the total number of lower() in pdb.py amounts to one, and that's used to process user-input such as "Yes", "y", "YES" or whatnot. Are you sure you are not processing the content through some lower()-call when embedding pdb? Diez From gagsl-py2 at yahoo.com.ar Fri Sep 19 05:49:23 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 06:49:23 -0300 Subject: Python, Factset, and Excel - Oh my! References: <04C6F615450E8D4A97EBA1DA9535667E064888@E2K3MAIL1515.mellonbank.com> Message-ID: En Thu, 18 Sep 2008 16:41:36 -0300, Desmond Scott E escribi?: > I'm still a Python novice. > I'm still attempting to migrate a Python-based process from > Windows2000/Python v2.4.2 (#67)/Excel2000 to WindowsXP/Python v2.5.2 > (r252:60911)/Excel2003. > I now have a new "opportunity"! > I need some help with the step in the Python script that calls Excel and > invokes the Factset API to download data into a spreadsheet. I'm > thinking that this is a Python / Factset API setup issue. Is the > Factset API installed as a component of Python? Or does the Factset API > exist in Windows and available to any application, like Python? > Any insights would be greatly appreciated! What's the Factset API? If you're talking about http://www.factset.com/ I'm pretty sure you have to install something to make it available. -- Gabriel Genellina From d3vvnull at gmail.com Sat Sep 27 14:23:12 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sat, 27 Sep 2008 13:23:12 -0500 Subject: python for *nix system admins In-Reply-To: <1222520796.630579@athprx04> References: <1222520796.630579@athprx04> Message-ID: <170543c70809271123j1334d12ardd09c25ce479978f@mail.gmail.com> import commands ? On Sat, Sep 27, 2008 at 8:06 AM, George Boutsioukis wrote: > On Sat, 27 Sep 2008 10:05:01 +0200, Lars Stavholm wrote: > > > Hi All, > > > > I'm new to this list and hoping that this is not off-topic. If it is, > > please point me in the right direction. > > > > I seem to recollect a python module or library for *nix sysadmins, but I > > can't for the life of me find it again. > > > > The module (or library) somehow added unix command capabilities to the > > python language. It seemed like a lesser known, perhaps new, python > > library or module. > > > > Any input or ideas appreciated > > /Lars Stavholm > > The only modules I've come across that barely fit your description are > python-unixtools(gzip, bzip only) and shutil(some limited capabilities). > Running unix commands is usually done directly(os.popen, os.system) on > *nix platforms. Why(and how) would anyone rewrite them as python modules? > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From mr.spoon21 at gmail.com Sun Sep 28 10:37:11 2008 From: mr.spoon21 at gmail.com (Mr.SpOOn) Date: Sun, 28 Sep 2008 16:37:11 +0200 Subject: Music knowledge representation Message-ID: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> Hi, I'm working on an application to analyse music (melodies, chord sequences etc.) I need classes to represent different musical entities. I'm using a class Note to represent all the notes. Inside it stores the name of the natural version of the note (C, D, E, F...) and an integer to calculate the accidentals. Then I have a class Pitch, to represent the different 12 pitch classes, because different notes, such as C# and Db, belong to the same pitch class. In these classes I also have some arithmetic method to perform additions or subtractions between pitches and integers. I also need to represent intervals between notes. An interval must have a degree (first, second, third), that may be represented with a simple integer and a size counted in semitones. Then, with these informations it can retrieve its name, for example: perfect fifth. The degree is calculated between natural notes. So the degree of Interval(C, E) is "third", or 3. This may be simple, if I put the notes in an ordered sequence. But, when I have to calculate, for example Interval(E, C). It should count till the end of the sequence, so if I have: C D E F G A B after the B it should continue with C. I'm not sure how to implement this. Is there a suitable data structure for this purpose? From news1234 at free.fr Fri Sep 26 16:34:31 2008 From: news1234 at free.fr (nntpman68) Date: Fri, 26 Sep 2008 22:34:31 +0200 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> References: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> Message-ID: <48dd4756$0$25116$426a74cc@news.free.fr> Hm, I guess you just filter mailing lists and can do nothing about the newsgroup if I'm fetching via the nntp server of my ISP itself, right? I'm using Thunderbird as news reader and this is probably not the smartest news reader, though I like it a lot for mails. Is there any pythonable (or perlable) news reader running under windows / cygwin or any way (under WIN XP) to use scripts to filter newsgroups for Thunderbird? - I'm annoyed by any spam. It's tough to find good rules, but the incoming spams that I see currently on comp.lang.python have certain criteas. - most email addresses from gmail. - all never posted before and then they have multiple posts within a few minutes / seconds - the posts always contain one or more urls ( mostly cryptic names ) - they always start a thread but never reply to one - the post doesn't contain python code or anything which looks only vaguely like source code - never mentions the word python - the amount of sexual or financial vocabulary exceeds classical python posts bye N Aaron "Castironpi" Brady wrote: > On Sep 26, 11:43 am, "Tim Rowe" wrote: >> 2008/9/26 Steven D'Aprano : >> >>> I don't have any objective numbers, but subjectively it seems to me that >>> the number of spams is significantly higher, but not so high as to be a >>> major nuisance. >> I consider *any* spam to be a major nuisance, but I don't see them as >> being the fault of python-list which seems to do a pretty good job of >> blocking them >> >> -- >> Tim Rowe > > Is it worth mentioning that they come from the same author in a short > period of time? Maybe that could bump up the score a notch. > > I think in June and July they were selling watches a lot which I > haven't noticed recently. From rafesacks at gmail.com Mon Sep 8 04:37:24 2008 From: rafesacks at gmail.com (Rafe) Date: Mon, 8 Sep 2008 01:37:24 -0700 (PDT) Subject: Clearing a session and reload() problem (with repro error) Message-ID: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> Hi, This seems to be an old question, and I've read back a bit, but rather than assume the answer is "you can't do that", I'd thought I'd post my version of the question along with a reproducible error to illustrate my confusion. My problem is that I'm using Python inside XSI (a 3D graphics application). If I want to restart Python, I have to restart XSI. This is no small amount of time wasted. The solution would be to somehow unload modules and all references and allow my imports to rebuild the cache. I suppose it would be great to clear the python session completely, but the 3D application might have added something to the session at startup (I doubt this though as I don't see any imported modules outside the norm). I've tried to use reload with a very simple algorithm. Simply run through every imported module, ignoring anything that is "None" or on the C: drive (all of our python is on a network drive so this hack works for me for now) and reload() it. I've come to realize that this isn't near intelligent enough to handle sub-packages. Before I post the repro, my questions are: 1) Does anyone have a work-flow for my situation that doesn't use Reload, and doesn't involve restarting the app for every edit/fix 2) Can anyone help point me in the right direction to build a dependable algorithm to cleanly reload all loaded modules? NOTE: I don't need to maintain anything in memory (i.e. instances, pointers, etc.) Everything will be initialized again each time. I'm not asking for code. Just some ideas or pseudo-code would do nicely. Here is a "simple" repro... Package Structure: --------------------------- inheritRepro __init__.py baseLib.py child __init__.py __init__.py: ---------------- import sys, os def reloadModules(): """ Reload all imported modules that are not on the C: drive. """ print "Reloading Python Modules..." # Iterate over all IMPORTED modules modules = sys.modules for modName in modules: mod = modules[modName] # Skip None types and other itesm we don't care about if modName == "__main__" or not hasattr(mod,"__file__"): continue # Get the drive and skip anything on the C: drive drive = os.path.splitdrive(mod.__file__)[0] if drive != "C:": reload(mod) print "Reloaded %s" % mod baseLib.py: --------------- class BaseClassA(object): pass class BaseClassB(BaseClassA): def __init__(self): super(BaseClassB, self).__init__() child.__init__.py: ------------------------ import inheritRepro.baseLib as baseLib class ChildClass(baseLib.BaseClassB): def __init__(self): super(ChildClass, self).__init__() RUN: ------- >>> import inheritRepro >>> import inheritRepro.child as child >>> obj = child.ChildClass() >>> print obj >>> inheritRepro.reloadModules() # Output omitted, but this worked. >>> import inheritRepro >>> import inheritRepro.child as child >>> obj = child.ChildClass() Traceback (most recent call last): File "", line 0, in File "\\nas6tb\PROJECTS\tech\users\rafe.sacks\python\inheritRepro \child\__init__.py", line 5, in __init__ super(ChildClass, self).__init__() File "\\nas6tb\PROJECTS\tech\users\rafe.sacks\python\inheritRepro \baseLib.py", line 6, in __init__ super(BaseClassB, self).__init__() TypeError: super(type, obj): obj must be an instance or subtype of type NOTE: this works if I don't use a sub-package for 'child' (child.py instead). Is it overly simple to assume reloading by file structure might work? Right now I'm getting around this by reload()-ing the right package after running reloadModules() if an error occurs. It's a bit frustrating that it cost me two days of work before I realized it was reload() causing this error and not super() or some other unknown-to- me inheritance/package structure problem. I rebuilt my code module by module until I noticed, quite by accident, that the thing worked once and then never again! ....oh well, these are the joys of learning the hard way. I know this was a long one. If you made it this far, thanks for reading, - Rafe From grante at visi.com Tue Sep 16 10:57:26 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 09:57:26 -0500 Subject: append on lists References: Message-ID: <5t6dnYP-j-nLVFLVnZ2dnUVZ_jSdnZ2d@posted.visi> On 2008-09-16, Maric Michaud wrote: > Le Tuesday 16 September 2008 15:57:53 Grant Edwards, vous avez ?crit?: >> On 2008-09-16, Maric Michaud wrote: >> > all expressions that return something, return a new object, >> >> That's not _quite_ true: >> >>> a=1 >> >>> b=a.__add__(0) >> >>> a is b >> >> True >> >> ;) > > This is implementation specific, Indeed. > the specification of the language says that it should be > false, That's curious. If so, then the implimentation is in violating the specification. Where is that in the specification? I suspect the statement in the specification should only apply to mutable objects. > and it is for higher numbers : > >>>>[15]: a=1000 > >>>>[16]: b=a.__add__(0) > >>>>[17]: a is b > ...[17]: False > > Don't disturb our OP, with side questions, please, it was > enough hard like this ;) I'm not trying to confuse the OP, but to quote Einstein: "Everything should be made as simple as possible, but not simpler." -- Grant Edwards grante Yow! I wonder if I could at ever get started in the visi.com credit world? From maebert at uos.de Thu Sep 11 11:04:43 2008 From: maebert at uos.de (Manuel Ebert) Date: Thu, 11 Sep 2008 17:04:43 +0200 Subject: Enumerating ordered expat attributes with tuplets? In-Reply-To: References: Message-ID: <3DD8138F-D513-4ACF-B30A-489085DC69EF@uos.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi Andy, by the looks of it I'd say that the problem is that the second parameter you passed to start_element is not a dictionary at all (the clue is in the "AttributeError: 'LIST' object" ...). >>> d = ['tree', 'house'] >>> start_element("Thing", d) Thing : AttributeError: 'list' object has no attribute 'items' >>> d = {'tree': 'hug', 'flower' : 'eat'} >>> start_element("Thing", d) Thing : flower="eat" tree="hug" Manuel On Sep 11, 2008, at 4:21 PM, andy_westken at hotmail.com wrote: > Hi > > I'm new to Python and trying to pick up good, idiomatic usage right > from the offset. > > As I was familiar with Expat from C++ (directly and via expatpp) I'm > trying to write a little script - using xml.parsers.expat - to search > and replace XML attribute values. > > As I want the attributes to stay in order when the file is written out > (so I can check my results with a diff tool) I've set the parser's > ordered_attributes attribute. But this has stopped the for loop > working with the tuplets. > > The relevant bit of code in my little test, using the default > Dictionary for the attributes, is: > > def start_element(name, attrs): > print "%s : " % name, > for (a,b) in attrs.items(): > print " %s=\"%s\"" % (a,b), > > But when I set ordered_attributes, first it doesn't like the items() > > AttributeError: 'list' object has no attribute 'items' > > And then it doesn't like the tuple > > ValueError: too many values to unpack > > Do I have keep track of where I am (name, value, name, value, ...) > > Or is there a way I can solve the problem with a tuple? > > Thanks, Andy > -- > http://mail.python.org/mailman/listinfo/python-list > -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (Darwin) iD8DBQFIyTOLcZ70OCIgLecRAsBrAJ9YSa7f+YTyM1yRmEKw8KBtb2klIgCgjNzw F295Tik+45eNHnJ3B4kKnWU= =xR4m -----END PGP SIGNATURE----- From pruebauno at latinmail.com Thu Sep 18 11:39:02 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 18 Sep 2008 08:39:02 -0700 (PDT) Subject: dict generator question References: Message-ID: <07db11b7-af17-45ed-9839-67da3d126e6b@26g2000hsk.googlegroups.com> On Sep 18, 10:54 am, "Simon Mullis" wrote: > Hi, > > Let's say I have an arbitrary list of minor software versions of an > imaginary software product: > > l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] > > I'd like to create a dict with major_version : count. > > (So, in this case: > > dict_of_counts = { "1.1" : "1", > "1.2" : "2", > "1.3" : "2" } > > Something like: > > dict_of_counts = dict([(v[0:3], "count") for v in l]) > > I can't seem to figure out how to get "count", as I cannot do x += 1 > or x++ as x may or may not yet exist, and I haven't found a way to > create default values. > > I'm most probably not thinking pythonically enough... (I know I could > do this pretty easily with a couple more lines, but I'd like to > understand if there's a way to use a dict generator for this). > > Thanks in advance > > SM > > -- > Simon Mullis 3 lines: from collections import defaultdict dd=defaultdict(int) for x in l: dd[x[0:3]]+=1 From castironpi at gmail.com Fri Sep 26 18:51:11 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 15:51:11 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> Message-ID: <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> On Sep 26, 11:48?am, "Tim Rowe" wrote: > 2008/9/26 Tino Wildenhain : > > >> The question I usually ask is "Does this language help me get the job > >> done?" Python often does. That's all that really matters, isn't it? > > > Well then it still depends on the perception of "job done". For example > > PHP programmers would bet their soul that their language of choice is > > exactly the right one to "get the job done." :-) > > You and me would indeed see a different picture on the level of doneness > > of such jobs ;-) > > Well, I did say "Often". Before now I've struggled for ages to write a > Python program to do a job, then when I've tried C# all the problems What problems? > have fallen away and the job What job? > was done in an hour or so. But other > times it has been the other way around; I've done stuff in Python that > I wouldn't know where to begin with in other languages. One of my > constant refrains is that *no* tool is ideal for *all* jobs! > > -- > Tim Rowe If you have wxFormBuilder and the win32 library, it's pretty fast. Python's philosophy is to make common things easy and everything possible. From gneuner2 at comcast.net Mon Sep 1 20:48:23 2008 From: gneuner2 at comcast.net (George Neuner) Date: Mon, 01 Sep 2008 20:48:23 -0400 Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> Message-ID: On Mon, 1 Sep 2008 21:03:44 +0000 (UTC), Martin Gregorie wrote: >On Mon, 01 Sep 2008 12:04:05 -0700, Robert Maas, http://tinyurl.com/uh3t >wrote: > >>> From: George Neuner A friend of mine had an >>> early 8080 micros that was programmed through the front panel using >>> knife switches >> >> When you say "knife switches", do you mean the kind that are shaped like >> flat paddles? >> >Pedantic correction: > >"Knife switch" is the wrong term. These are high current switches, >typically used in the sort of heavy duty circuit where the wiring hums >when power is on or in school electrical circuits so even the back of the >class can see whether the switch is open or closed. In these a copper >'blade' closes the contact by being pushed down into a >narrow, sprung U terminal that makes a close contact with both sides of >the blade. Like this: http://www.science-city.com/knifeswitch.html > >What you're talking is a flat handle on a SPST or DPST toggle switch. It >is often called a paddle switch and mounted with the flats on the handle >horizontal. Like this, but often with a longer handle: >http://www.pixmania.co.uk/uk/uk/1382717/art/radioshack/spdt-panel-mount- >paddle-s.html I don't know the correct term, but what I was talking about was a tiny switch with a 1/2 inch metal handle that looks like a longish grain of rice. We used to call them "knife" switches because after hours flipping them they would feel like they were cutting into your fingers. George From Lie.1296 at gmail.com Sat Sep 6 17:29:35 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 6 Sep 2008 14:29:35 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <2aa4ef17-50d3-4aeb-9e7e-0d2d9b9237d4@w7g2000hsa.googlegroups.com> Message-ID: On Sep 3, 6:31?pm, Uwe Schmitt wrote: > On 2 Sep., 18:55, Steven D'Aprano > > > cybersource.com.au> wrote: > > I find myself writing command line tools in Python where I wish to > > include "verbose" output to stdout. > > > I start with a helper function: > > > def print_(obj, level=0): > > ? ? if _verbosity >= level: > > ? ? ? ? print obj > > > And then I end up with functions or methods looking like this: > > > def parrot(x) > > ? ? print_("precondition", level=2) > > ? ? do_something() > > ? ? print_("status is good...", level=1) > > ? ? print_("parrot is squawking strongly now", level=2) > > ? ? do_something_else() > > ? ? print_("squawk squawk squawk", level=3) > > ? ? do_more() > > ? ? print_("postcondition", level=1) > > ? ? return something > > > That often means that my functions end up with more message printing code > > than actual code. The whole thing seems messy and hard to manage for all > > but the smallest scripts. > > > Worst of all, sometimes the messages I wish to print may be expensive to > > compute, and I don't want to waste time computing them if they aren't > > going to be printed because the verbosity is too low. But nor do I wish > > to fill my code with this: > > > if _verbosity >= 3: > > ? ? x = calculate_complicated_thing() > > ? ? print_(x, level=3) > > > Is there a better way of doing this than the way I am going about it? > > > -- > > Steven > > You can save some code if you use function decorators for logging > input and output values of > functions. > So write lots of functions containing one statement and your problem > is solved ;-) > > Greetings, Uwe That would be perfect if python is a fully functional language (read that as: purely functional language). Functional language dictates no side effects, so logging input and output of functions is pretty much everything needed to do debugging (which is the main reason for having verbose mode). It would still be feasible, though, if you keep yourself from using functions with side-effects (or use as few of them as possible). Bjorn Lindqvist says: > One big downside with that approach is that it becomes much harder to > grep for the log message. Usually when I go through logs, I don't care > what exactly the message says, just that it is easily googleable (uses > some kind of identifying text) and that it is unique so I can know > exactly where it was emitted. Actually, I'd prefer a log code (perhaps also as an option, to use -e for showing up log code besides the log message). The log code would be unique and referenced only once in the whole application (to nail down who said what to a single point). The code would make a call to the log printer with the log code (not the error string) and a few arguments to be interpolated to the error string (taken from a dictionary indexed by error code). The downside is loss of inline documentation by the logging codes. From bearophileHUGS at lycos.com Mon Sep 29 09:02:44 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 06:02:44 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> Message-ID: <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> George Sakkis: > I don't see the same value in creating a distinction between methods > and builtin functions unless the latter are truly generic (and even > then I wouldn't mind having them as methods of the base object class, > e.g. object.type()). Having a builtin len(x) delegate to x.__len__() > seems harder to justify. I have shown few usage examples of the len() one of the posts in this thread. Can you take a look at them and show how you can better rewrite them without a len function? Bye, bearophile From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 03:58:39 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 09:58:39 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <10a205fe-e8d7-4eb3-82f8-c4d19984a3e8@m73g2000hsh.googlegroups.com> Message-ID: <48dc962a$0$2289$426a74cc@news.free.fr> Lawrence D'Oliveiro a ?crit : > In message > , > Aaron "Castironpi" Brady wrote: > >> Wikipedia puts it decently: "mainly for OO programming, but with some >> procedural elements." > > "Procedural" is the opposite of "functional", not "object-oriented". AFAIK, the "opposite" if functional is imperative, not procedural. But let's not waste too much time on terminology arguments... From python at rgbaz.eu Wed Sep 10 13:12:28 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 19:12:28 +0200 Subject: md5 differences In-Reply-To: References: Message-ID: <7C2CD173-D069-41A0-9B56-382FF86F5B52@rgbaz.eu> On 10 sep 2008, at 18:30, Richard Brodie wrote: > > "Python" wrote in message > news:mailman.799.1221063937.3487.python-list at python.org... > >> here's an example: >> Arno at Computer:~% echo "hello" | md5 >> b1946ac92492d2347c6235b4d2611184 >> How do I get the same results? > > Checksum the same string. > >>>> md5.new("hello\n").hexdigest() > 'b1946ac92492d2347c6235b4d2611184' > > hmm and this then: Arno at Computer:~% echo "test" > test.txt Arno at Computer:~% md5 test.txt MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 Arno at Computer:~% python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import md5 >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() '90364ed45b452d43378629c20543a81d' even echo -n "hello" | md5 doesn't return the same number gr Arno From FettManChu at gmail.com Fri Sep 5 11:08:26 2008 From: FettManChu at gmail.com (Fett) Date: Fri, 5 Sep 2008 08:08:26 -0700 (PDT) Subject: Can anyone suggest a good crypto package? References: <7xwshr4qr4.fsf@ruckus.brouhaha.com> <7xmyino11v.fsf@ruckus.brouhaha.com> Message-ID: <6a21ce15-da79-43f7-b090-71e36c6a7c89@d1g2000hsg.googlegroups.com> On Sep 4, 8:04?pm, Paul Rubin wrote: > If you just want to authenticate the strings without confidentiality, > use the built-in HMAC module. But beware of replay attacks. I looked into this and it looks like I might be able to get by with this. I didn't find this function before, I am asking my primary customer if the signature would be sufficient. I am having trouble seeing how I would post the encrypted data to a website and get it back without it changing some. So this option might work better for me (at least quicker), if he's ok with that option. By replay attack I assume you mean posting old data with the signature that is valid for that data? Thanks for the warning, I suppose I could include a date/timestamp in the data. Thanks again, this has been very helpful. From castironpi at gmail.com Tue Sep 9 20:53:42 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 9 Sep 2008 17:53:42 -0700 (PDT) Subject: Coming from .NET and VB and C References: Message-ID: On Sep 8, 9:31?pm, sturlamolden wrote: > On 3 Sep, 18:52, ToPostMustJoinGroup22 > wrote: > > > I'm coming from a .NET, VB, C background. > > Any suggestions for someone new to the scene like me? > > Welcome! Unfortunately, you probably have a lot of bad habits to > unlearn. Don't use Python like another C, VB or Java. It will cause a > lot of grief, and you'll end up with the idea that Python is slow like > a slug. Python is more like Lisp or Haskell, but with a readable > syntax. There are list comprehensions, generator expressions, > dictionaries, sets, lists, list slicing, lambdas, map, reduce, filter, > closures, etc. They are there to be used, and be used a lot. Learning > to use Python efficiently is what has the steepest learning curve. Variable argument lists, first-class function objects. From sturlamolden at yahoo.no Wed Sep 24 17:50:56 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 14:50:56 -0700 (PDT) Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: <7c1554cb-f167-462e-ac7c-ea82cdda99b6@y21g2000hsf.googlegroups.com> On Sep 24, 3:17?pm, Marin Brkic wrote: > Has anyone had a situation like this ? All your inputs and suggestions > are more then welcomed. Send them the .py file and confirm that it does work. The lack of Python can be blamed on the incompetent BOFH. Chances are the situation will change when the BOFH gets 20 requests for Python a day. From srad at inbox.lv Thu Sep 4 11:34:17 2008 From: srad at inbox.lv (Aigars Aigars) Date: Thu, 04 Sep 2008 18:34:17 +0300 Subject: Function decorators Message-ID: <1220542457.48bffff905ca9@www.inbox.lv> Good day all, I am learning Python and came up to decorators. The question is: Why does function FoodList return value None? The code in attachment. Thank you, Aigars -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: testingVarLogger.py Type: application/x-unknown-application-x-python Size: 462 bytes Desc: not available URL: From fredrik at pythonware.com Sat Sep 20 07:54:02 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 13:54:02 +0200 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: Colin J. Williams wrote: > "foreach: for x in array: statements > > Loops over the array given by array. On each iteration, the value of the > current element is assigned to x and the internal array pointer is > advanced by one. " > > This could be a useful addition to Python. for-in could be a useful addition to Python? looks like Guido's used his time machine again, then, since it's been around since the pre-1.0 days: http://www.python.org/doc/ref/for.html From aquil.abdullah at gmail.com Fri Sep 5 15:07:45 2008 From: aquil.abdullah at gmail.com (aha) Date: Fri, 5 Sep 2008 12:07:45 -0700 (PDT) Subject: Determining Processor Vender References: <554ecfcf-96d8-4602-8d5e-ee5d70590124@i76g2000hsf.googlegroups.com> Message-ID: <3c4cb88a-2e47-4a5e-9a82-4b72f00b1561@y21g2000hsf.googlegroups.com> On Sep 5, 3:00?pm, aha wrote: > Dose anyone know of a cross-platform method for determining the vendor > of a processor? ?Under linux I can check /proc/cpuinfo. ?What I'd like > to be able to do is determine if a processor is AMD or Intel, so that > I can use the appropriate numerical libraries for my application. > > Regards, > > Aquil Additionally, I've tried the platform module...platform.processor() on my 64-bit AMD system, under Linux, returns x86_64. And under windows retruns an empty string '' From castironpi at gmail.com Thu Sep 4 23:40:07 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 4 Sep 2008 20:40:07 -0700 (PDT) Subject: pdb bug and questions References: Message-ID: <9d1d75a2-a6be-4d56-a53c-46b7942abf08@m73g2000hsh.googlegroups.com> On Sep 4, 4:22?pm, Stef Mientki wrote: > hello, > > I'm trying to embed a debugger into an editor. > I'm only interested in high level debugging. > The first question is what debugger is the best for my purpose ? > (pdb, pydb, rpdb2, smart debugger, extended debugger ? > > Second question, in none of the above debuggers (except rpdb2), > I can find a ?"break now", > so it seems impossible to me to detect unlimited while loops ? > > For the moment I started with pdb, because most of the debuggers seems > to be an extension on pdb. > When I launch the debugger ( winXP, Python 2.5) from with my editor > ? python -u -m pdb ?D:\\Data\\test_IDE.py > I get this error > ? IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') > NOTICE 1 backslash ----------------------------------^ > > If I launch the debugger with > ? python -u -m pdb ?D:/Data/test_IDE.py > It runs fine. > > This looks like a bug to me. > What's the best way to report these kind of bugs ? > > Although I mostly use os.path.join to be OS independent, > these kind of bugs give me the impression, > that I can better do the join myself and always use forward slashes. > Is this a valid conclusion ? > > thanks, > Stef Mientki Stef, I discovered the same problem too with my editor. I solved it by using only the file name, and setting the initial directory on the executable. For something pdb doesn't have, can you look at it yourself? Or, can you write your own ad hoc, specialized to detecting while loops, using settrace and 'except KeyboardInterrupt'? From tjreedy at udel.edu Tue Sep 23 04:37:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 23 Sep 2008 04:37:25 -0400 Subject: Why no tailcall-optimization? In-Reply-To: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? I started to write an article on this but it disappeared.... So short answer: 1. Unless down very carefully, in a way that would slow things down, it would change the semantics of Python. 2. It is usually trivial to convert to a while loop, which amounts to in-frame recursion. If using tail-recursion requires a nested inner function to avoid repeating one-time initialization or exposing the cumulation variable, writing the loop is easier since no nested function is needed. 3. In Python, for loops are usually better for processing iterables, which covers most uses of induction (recursion/iteration). Terry Jan Reedy From jinbow at gmail.com Thu Sep 4 11:32:24 2008 From: jinbow at gmail.com (Mars creature) Date: Thu, 4 Sep 2008 08:32:24 -0700 (PDT) Subject: Read Binary data Message-ID: <4d3d4427-77c4-4310-9886-e0e498a1a6e7@s20g2000prd.googlegroups.com> Hi guys, I am trying to read a binary file created by the following matlab command: fid=fopen('a.bin','w','b'); fwrite(fid,a,'real*8'); fclose(fid);, and wondering how to do it in Python. I googled it but still get confused. 'b' in fopen is for 'big-endian', 'real*8' in fwrite is for 64bit float. Thank you very much! Jinbo Wang From mensanator at aol.com Wed Sep 10 13:48:17 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 10 Sep 2008 10:48:17 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> Message-ID: On Sep 7, 3:38?pm, Luis Zarrabeitia wrote: > Quoting Mensanator : > > > Actualy, I already get the behaviour I want. sum([1,None]) > > throws an exception. I don't see why sum([]) doesn't throw > > an exception also > > If you take a "start value" and add to it every element of a list, should the > process fail if the list is empty? No. > If you don't add anything to the start value, > you should get back the start value. Agree. > > Python's sum is defined as sum(sequence, start=0). That's the issue. > If sum were to throw an > exception with sum([]), it should also throw it with sum([], start=0), wich > makes no sense. Given that definition, yes. But is the definition correct in ALL cases? Are there situations where the sum of an empty list should NOT be 0? Of course there are. Can sum() handle those cases? No, it can't, I have to write my own definition if I want that behaviour. There's no reason why sum([]) and sum([],0) have to mean the same thing at the exclusion of a perfectly valid alternative definition. But that's the way it is, so I have to live with it. But that's not conceeding that I'm wrong. > > -- > Luis Zarrabeitia > Facultad de Matem?tica y Computaci?n, UHhttp://profesores.matcom.uh.cu/~kyrie From gagsl-py2 at yahoo.com.ar Fri Sep 5 17:32:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 18:32:18 -0300 Subject: [PIL] quake like multicoloured text References: <3d829a04-9005-4216-86dc-b1055edab4e7@f63g2000hsf.googlegroups.com> Message-ID: En Fri, 05 Sep 2008 16:24:08 -0300, Durand escribi?: > I'm wondering how I could render text with PIL in which different > parts of the text are different characters. This is for a game stats > script where names are written like: > ^1Red ^2Green ^3Yellow, etc. > The problem is that I currently use text in the ImageDraw module but > the only way I can think of rendering text is by rendering each bit of > text in a separate colour. > > Example: > > draw.text((0,0),"Red", fill="red") > draw.text((30,0),"Green", fill="green") > draw.text((60,0),"Yellow", fill="green") > > except that I'm not sure how much spacing there is between each > coloured bit of text(30px is assumed in the example)...Would there be > an alternate method of doing this? You could use the draw.textsize method to measure how much space will take each part... -- Gabriel Genellina From stef.mientki at gmail.com Tue Sep 30 15:59:48 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 21:59:48 +0200 Subject: Would this be called a bug in inspect ? In-Reply-To: References: <48E268A3.4050900@gmail.com> Message-ID: <48E28534.1040009@gmail.com> Gabriel Genellina wrote: > En Tue, 30 Sep 2008 14:57:55 -0300, Stef Mientki > escribi?: > >> I'm not familiar with inspect, >> but I get an error (see below) in >> getmembers ( wx ) >> >> Of course this is bug in wx . > > Yes. > >> But would you also call this a bug in inspect ? >> (inspect crashes and doesn't continue with th rest of the code, nor >> it returns the already gathered data) > > getmembers works fine; try m=getmembers(wx) and see. REALLY GREAT ! > It fails when you attemp to print (or pprint) the returned list. > But this is fully beyond my understanding: m = getmembers ( wx ) print m runs fine print getmembers ( wx ) crashes but not always: >>> print getmembers (wx) [('ACCEL_ALT', 1), ('ACCEL_CMD', 2), ('ACCEL_CTRL', 2), ('ACCEL_NORMAL', 0), ('ACCEL_SHIFT', 4), ('ADJUST_MINSIZE', 0), ( And to make it even weirder, now I can let your suggestion crash too >>> m=getmembers(wx) >>> print getmembers (wx) Traceback (most recent call last): File "", line 1, in File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' >>> print m Traceback (most recent call last): File "", line 1, in File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 242, in __repr__ def __repr__(self): return 'wx.Colour' + str(self.Get(True)) File "P:\Python\lib\site-packages\wx-2.8-msw-unicode\wx\_gdi.py", line 230, in Get return _gdi_.Colour_Get(*args, **kwargs) TypeError: in method 'Colour_Get', expected argument 1 of type 'wxColour *' ?????? thanks, Stef From grante at visi.com Mon Sep 22 22:56:30 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 22 Sep 2008 21:56:30 -0500 Subject: Time.sleep(0.0125) not available within Linux References: Message-ID: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> On 2008-09-23, Blubaugh, David A. wrote: > I was wondering if anyone has come across the issue of not being allowed > to have the following within a Python script operating under Linux: > > time.sleep(0.0125) No, I have not. And I doubt anybody else has. > It appears that I am not allowed to have the object sleep. It doesn't appear that way to me. Care to explain how you arrived at that conclusion? > Has anyone encountered this specific issue before in the past? $ python Python 2.5.2 (r252:60911, Aug 28 2008, 15:54:48) [GCC 4.1.2 (Gentoo 4.1.2 p1.1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> time.sleep(0.0125) >>> The above code has worked as far back as I can recall (which I think includes Python 1.4). -- Grant From sjmachin at lexicon.net Fri Sep 5 09:29:54 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 06:29:54 -0700 (PDT) Subject: int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why? References: <184502f4-872a-4c23-9a6d-e93ef225d4de@a2g2000prm.googlegroups.com> Message-ID: On Sep 5, 11:12 pm, bcm wrote: > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on win32 > The following line of code describes an funny question?>>> int((9.2-9.0)*10) > 1 > >>> int((9.21-9.0)*10) > 2 > >>> int((9.1-9.0)*10) > 0 > >>> int((9.11-9.0)*10) > 1 > >>> int((8.2-8.0)*10) > 1 > >>> int((8.23-8.0)*10) > > 2 > > why? anybody can explain it? Try looking one step at a time: >>> 9.2 9.1999999999999993 That wasn't hard, was it? Do you need any further explanation? If so, look here: http://docs.python.org/tut/node16.html From goranbaraccvrcko at googlemail.com Thu Sep 25 13:52:59 2008 From: goranbaraccvrcko at googlemail.com (Goran Barac Cvrcko) Date: Thu, 25 Sep 2008 10:52:59 -0700 (PDT) Subject: Hello guys!!!!! Message-ID: <5f975ac5-b4fa-431d-bbe3-bf25a3f6f126@k37g2000hsf.googlegroups.com> Hello, this is Goran Barac from town Banjaluka, Bosnia and Herzegovina, also known as Cvrcko Does anyone know of any bars in town where I can swallow a bucket of cum? It can be either dog, horse or human cum. Also, does anyone know of any sex bars where people will shit in your mouth? I also like eating shit. -- Name: Goran Barac - Cvrcko Street adress: Ive Andrica 23 Town: 78000 Banja Luka Country: Bosnia and Herzegovina Home phone: +38751/332-113 Cell phone: +38765/776-556 Email adress: goranbaraccvrcko at googlemail.com ~ The new pumpkin rarely pulls Terrance, it teases Sharon instead. For Susan the tape's sad, beside me it's unique, whereas against you it's believing dirty. Hey, go reject a fork! Why did Alice open throughout all the boats? We can't explain poultices unless Woody will mercilessly judge afterwards. The frames, disks, and shirts are all fat and fresh. Who will we dine after Edwina wastes the thin mirror's goldsmith? It's very outer today, I'll recollect strangely or Christopher will learn the teachers. Hardly any humble brave tyrants hourly solve as the tired wrinkles cover. Hardly any distant buttons are short and other urban ointments are filthy, but will Robette receive that? Let's lift behind the deep highways, but don't promise the heavy diets. Who kicks badly, when Melvin burns the stale code before the autumn? Get your absolutely moulding barber within my cellar. If you will laugh Gay's hill against porters, it will incredibly climb the case. Some shopkeepers arrive, irrigate, and shout. Others sadly expect. To be pathetic or sticky will talk abysmal oranges to wickedly look. Are you healthy, I mean, moving above clever onions? While farmers partly taste pins, the powders often excuse against the blunt jackets. Generally Susanne will order the sticker, and if George actually seeks it too, the bowl will attempt with the polite lane. He can hate durable kettles above the rural bad ocean, whilst Oscar easily scolds them too. You eventually fill against Norma when the kind drapers irritate among the poor summer. As surprisingly as Dolf converses, you can dye the cap much more familiarly. Brion, still killing, behaves almost eerily, as the sauce changes on their coffee. You won't recommend me grasping about your lazy office. Almost no butchers steadily live the lost signal. Cyrus's hat improves among our desk after we sow towards it. Ralph measures the weaver within hers and wanly calls. Some cosmetic tags answer David, and they rigidly walk Quincy too. When Richard's elder gardner dreams, Mark cares for weak, closed islands. He might strongly fear think and plays our cheap, sour painters above a bathroom. I creep the active yogi and cook it in back of its dorm. Tell Katherine it's strong loving within a tree. Why will you jump the angry lower exits before Murray does? I am unbelievably bitter, so I wander you. How does Hector smell so regularly, whenever Ronald likes the solid twig very slowly? Julieta, have a hot printer. You won't clean it. Fucking don't join a dryer! She wants to nibble inner smogs under Usha's castle. She'd rather depart grudgingly than help with Bernadette's younger grocer. Other old dark cards will comb frantically alongside cans. Try pouring the monument's pretty cat and Oliver will attack you! Don't try to seek halfheartedly while you're jumping throughout a easy carpenter. He'll be climbing in front of good Cypriene until his enigma answers quietly. What doesn't Janet smell inadvertently? They are opening before the rain now, won't explain walnuts later. Some light long game covers pools outside Woodrow's rich film. Why did Oscar judge the pear with the handsome spoon? He will talk nearly if Julieta's tailor isn't wet. Just looking beside a ulcer through the store is too young for Woody to care it. Both filling now, Alejandro and Marty irritated the open rivers about smart envelope. Occasionally, dusts kill beside rude fires, unless they're sweet. Her pen was sharp, dull, and fears over the spring. Zack, on floors difficult and upper, attacks towards it, recollecting seemingly. We measure the raw sauce. They are rejecting throughout quiet, towards empty, in back of cold units. My wide potter won't clean before I comb it. If you'll pour Edward's camp with aches, it'll admiringly converse the cup. I was promising frogs to worthwhile Corinne, who's walking in back of the counter's stable. It can receive clean pickles, do you solve them? Many jugs will be weird lean carrots. Roger helps, then Walt stupidly believes a ugly lentil on Catherine's road. We tease them, then we weekly dream Zack and Annabel's blank candle. A lot of shallow dose or canyon, and she'll locally excuse everybody. If the bizarre balls can sow bimonthly, the hollow raindrop may love more ventilators. We laugh weekly, unless Jezebel grasps shoes outside Jimmie's puddle. Jimmy! You'll mould plates. Just now, I'll dine the bandage. All glad strange figs will fully order the lemons. The dog without the proud star is the pitcher that learns happily. It might crudely scold within sick dry satellites. Until Dolf calls the bushs generally, Ann won't join any full winters. Better kick clouds now or Blanche will wrongly hate them over you. There, Jeff never arrives until Joie nibbles the noisy elbow deeply. From psaffrey at googlemail.com Tue Sep 16 07:15:59 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Tue, 16 Sep 2008 04:15:59 -0700 (PDT) Subject: Parallelising code References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> <676c9d65-5bc7-44c4-9e61-6f7ed2b3c58c@d77g2000hsb.googlegroups.com> Message-ID: Many very helpful replies, which I will now mull over. Thanks, Peter From steve at REMOVE-THIS-cybersource.com.au Sun Sep 28 04:38:00 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 08:38:00 GMT Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <00ef3c23$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 22:37:09 -0700, est wrote: >>>> str(u'\ue863') > Traceback (most recent call last): > File "", line 1, in > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0 > : ordinal not in range(128) > > FAIL. What result did you expect? [...] > The problem is, why the f**k set ASCII encoding to range(128) ???????? > while str() is internally byte array it should be handled in range(256) > !!!!!!!!!! To quote Terry Pratchett: "What sort of person," said Salzella patiently, "sits down and *writes* a maniacal laugh? And all those exclamation marks, you notice? Five? A sure sign of someone who wears his underpants on his head." -- (Terry Pratchett, Maskerade) In any case, even if the ASCII encoding used all 256 possible bytes, you still have a problem. Your unicode string is a single character with ordinal value 59491: >>> ord(u'\ue863') 59491 You can't fit 59491 (or more) characters into 256, so obviously some unicode chars aren't going to fit into ASCII without some sort of encoding. You show that yourself: u'\ue863'.encode('mbcs') # Windows only But of course 'mbcs' is only one possible encoding. There are others. Python refuses to guess which encoding you want. Here's another: u'\ue863'.encode('utf-8') -- Steven From tarundevnani at gmail.com Fri Sep 5 08:56:02 2008 From: tarundevnani at gmail.com (tarun) Date: Fri, 5 Sep 2008 18:26:02 +0530 Subject: Regarding subprocess module Message-ID: Hello all, I wrote the following code: import subprocess,time cmdExe = "C:\\WINDOWS\\system32\\cmd.exe" myProcess = subprocess.Popen(cmdExe,stdin=subprocess.PIPE) time.sleep(2) myProcess.stdin.write('cd Desktop\r\n') I copied the above lines of code to a file and tried executing the python file from dos box (command prompt) on windows I want subprocess.Popen to open a new dos box. But it works in the same window. What should I do to open the subprocess in new window? Thanks & Regards. Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From watine at cines.fr Fri Sep 5 11:53:12 2008 From: watine at cines.fr (Benjamin Watine) Date: Fri, 05 Sep 2008 17:53:12 +0200 Subject: Files application architecture Message-ID: <48C155E8.7050006@cines.fr> Hi, I'm about to develop a small python application and I wonder how to organize files in this application. I'm familar to java, so I'm tempted to use the same convention : 1 file per class and 1 folders per package. I know that packages doesn't exists in python, they are modules instead. May I create specific module for each "group of class" ? My application follow the MVC paradigm, so basically, I've a package Model, a package View, and a package Controller. So, what are best practices for organizing files and folders in a small python project ? I've found PEP8 (http://www.python.org/dev/peps/pep-0008/) that gives a lot of good hints on coding convention, but nothing about files organization. Thanks in advance ! Ben From grante at visi.com Tue Sep 30 12:32:36 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Sep 2008 11:32:36 -0500 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> Message-ID: On 2008-09-30, Ivan Reborin wrote: > But as I said, got a job that't got to be done, so I'm trying > to figure out how to do array operations as easily as possible > in python, which are necessary for all my calculations. numpy -- Grant Edwards grante Yow! TONY RANDALL! Is YOUR at life a PATIO of FUN?? visi.com From tjreedy at udel.edu Tue Sep 2 18:17:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 02 Sep 2008 18:17:03 -0400 Subject: Renumbering In-Reply-To: References: Message-ID: Francesco Pietra wrote: > Hi; Hi, Let L be a data line > I would like to renumber, starting from 1, column 6 (i.e, 428 become > 1, 429 becomes 2, etc for a very long list) So you want to subtract 427 from each entry in L[22:26] > ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426 >... > ATOM 3432 N SER B 429 142.432 85.155 78.878 1.00134.86 2SG3434 > ... > > Distinctive character is column 5, i.e., it must be set that only > lines containing "B" should be renumbered. if L[21] == > As you can see, the number of lines for a particular value in column 6 > changes from situation to situation, and may even be different for the > same name in column 4. For example, LEU can have a different number of > lines depending on the position of this amino acid (leucine). But from what you said earlier, this is not relevant. > > I was unable to set non-proportional characters, sorry. The display font depends on individual systems. Thunderbird uses fixed pitch font, so table displays nicely for me. > Thanks for help This is fairly simple. See the tutorial for explanations. data = [ 'ATOM 3424 N LEU B 428 143.814 87.271 77.726 1.00115.20 2SG3426', 'ATOM 3432 N SER B 429 142.432 85.155 78.878 1.00134.86 2SG3434' ] for L in data: if L[21] == 'B': L = L[:22] + "%4d" % (int(L[22:26])-427) + L[26:] print(L) #py3 # prints ATOM 3424 N LEU B 1 143.814 87.271 77.726 1.00115.20 2SG3426 ATOM 3432 N SER B 2 142.432 85.155 78.878 1.00134.86 2SG3434 If you start with a disk file and want to end up with a new disk file... replace the 'data =' statement above with data = open('datafile','r') follow it with outp = open('newdata', 'w') and replace the print statement with outp.write(L) Terry Jan Reedy From castironpi at gmail.com Fri Sep 12 10:00:12 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 12 Sep 2008 07:00:12 -0700 (PDT) Subject: lacking follow-through References: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> On Sep 12, 7:23?am, Steve Holden wrote: > castironpi wrote: > > If you are flattered to be compared to an AI you must come from the same > race as Mr. Spock in Star Trek. No, I said 'for my logic to compared'. Speaking of which, I think you excluded the possibility of diligent and ethical human, which meets the criteria (of being flattered to be compared to an AI)... unless Vulcan is just a synonym for it. If you want a discussion of why a diligent and ethical human takes pride in / devotes effort to logic, that's another topic that I'm happy to engage on. > You aren't entitled to require discussion of your ideas and proposals. No, but you are entitled to human interaction. If your case is that I should seek mine face-to-face instead of keyboard-to-screen, you probably have a point. ... > [...] > > > For example, I sometimes hear people talk about salary as though it > > were social approval, and vice versa. ?Even though the analogy doesn't > > hold in every case generally, it is still a good way to express > > yourself in many contexts, and especially when the more precise word > > isn't on the tip of your tongue. > > Perhaps under those circumstances the better choice is to hold off > posting and do some research until you come up with the proper word. Yes I know. Good thing everyone at Mozilla agrees with you, and Thesaurus.Com is included in Firefox's quicksearch engines. > Precision in the expression of ideas encourages debate, whereas sloppy > "just write what you feel" is likely to result in hostile responses, as > it causes the perception that you value your own time more than that of > the people you attempt to engage. But the value of expression and self-expression can outweigh the value of debate, even in so stuffy a setting as a Usenet group. Make time for both or stifle your emotions. Do you hold I should be speaking from the heart more or less? Regardless, you've contradicted yourself: 1) "just write what you feel" is likely to result in hostile responses 2) If you are flattered to be compared to an AI you must [not be human] Assume you, Steve, do as you say (practice what you preach). You do not write either "just what you feel", nor anything that can be compared to an A.I. Define the goal of A.I. to be logic and reasoned "post-impulsive" deliberation (my title to define as I voiced the flattery). Then conclude you don't post to the newsgroup. Observe you do, and reach an absurdity. What premise do you retract? Knowing nothing of your background in philosophy or otherwise, it may be a little unfair to put words in your mouth like that. It's a deep problem (that yes, does have implications on the "diligent and ethical" issue above) of human nature and the human condition: If you're not rational, then you're a man. Besides, it is better to complain to the group that it is dropping my posts than to anyone else. > > regards > ?Steve > -- > Steve Holden ? ? ? ?+1 571 484 6266 ? +1 800 494 3119 > Holden Web LLC ? ? ? ? ? ? ?http://www.holdenweb.com/ From namekuseijin at gmail.com Tue Sep 23 22:32:31 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Tue, 23 Sep 2008 19:32:31 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: Message-ID: <31147d87-572c-484f-ae96-66cfe5b83677@i76g2000hsf.googlegroups.com> On 23 set, 22:50, Neal Becker wrote: > I find I'm often tripped up by: > > x = Y (lots of ?constructor arguments....) if something ... > > on first glance, I don't notice the if. Nobody does. This peculiar syntax has much better usage in short expressions. dothis if this else dothat From fredrik at pythonware.com Sat Sep 20 13:30:18 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 Sep 2008 19:30:18 +0200 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com> <27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com> Message-ID: Blubaugh, David A. wrote: (no need to shout when filling in the subject line, thanks) > I have now been able to generate a .pyd file from a FORTRAN > file that I am trying to interface with python. I was able > to execute this with an additional insight into how f2py > operates. > > ImportError: DLL load with error code 193 Error code 193 is ERROR_BAD_EXE_FORMAT, which means that the thing you're trying to import is not a proper DLL. > copy LICENSE.txt LICENSE.pyd 1 file(s) copied. > python >>> import LICENSE Traceback (most recent call last): File "", line 1, in ImportError: DLL load failed with error code 193 In general, the tools for building binary extensions for Python assumes that you have at least some basic knowledge about how to build binaries using a compiled language. From erikwickstrom at gmail.com Sat Sep 13 00:13:18 2008 From: erikwickstrom at gmail.com (erikcw) Date: Fri, 12 Sep 2008 21:13:18 -0700 (PDT) Subject: Wrong application name in menubar of OS X Message-ID: <1af662ce-5454-436c-8b65-c713993cf6bc@s9g2000prg.googlegroups.com> Hi, The menubar of OS X is showing the application name as Python instead of the name of my wxpython gui app. How do I make my application name show-up in the menu bar? Thanks! Erik From grante at visi.com Mon Sep 15 00:30:32 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 14 Sep 2008 23:30:32 -0500 Subject: Good programming style References: <4086da86-9b31-4790-aba3-71ae47f7f4f5@c65g2000hsa.googlegroups.com> <87abea73l9.fsf@benfinney.id.au> <5pidneRB87PDMVDVnZ2dnUVZ_vWdnZ2d@posted.usinternet> <87wshe5ijg.fsf@benfinney.id.au> <87od2q5a24.fsf@benfinney.id.au> Message-ID: On 2008-09-15, Ben Finney wrote: > Adelle Hartley writes: > >> I'm looking at porting a library that was written for COM and .Net >> to work as a Python module, and was wondering whether it would be >> better to stick to the library's current naming convention so that >> the API is as similar as possible on each platform, or to adopt a >> "when in Rome..." policy and follow the "most mainstream" naming >> pattern for each platform/language. > > I think it's more important for Python library APIs to comply > with the Python coding guidelines (as specified in PEP 8) than > to comply with standards in other languages. I think the practical matter of being able to use existing documentation and examples might be more important than maintinging the purity of PEP 8 naming styles. > The Python library you're implementing isn't being used in > those other languages, so the conventions of other languages > have little relevance. > > It's being used in Python code, so it should mesh well with > PEP 8 compliant code ??? by having the API itself comply with > PEP 8. I think that battle was lost long ago, but maybe that just because I use a lot of libraries written in C, C++, and Fortan and then wrapped with things like swing. -- Grant From bdesth.quelquechose at free.quelquepart.fr Mon Sep 22 16:28:50 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 22 Sep 2008 22:28:50 +0200 Subject: What do you call a class not intended to be instantiated In-Reply-To: References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <48d7720d$0$12866$426a34cc@news.free.fr> <48d78c3c$0$6998$426a74cc@news.free.fr> <423ea094-f32f-44bb-b35e-e85ec70e2a11@a70g2000hsh.googlegroups.com> <48d7f46d$0$15502$426a74cc@news.free.fr> Message-ID: <48d80038$0$27459$426a34cc@news.free.fr> Aaron "Castironpi" Brady a ?crit : > On Sep 22, 2:38 pm, Bruno Desthuilliers > wrote: (snip) >> Going back to robot-mode, Aaron ? > > Not getting the same sense of "soul" as from my usual posts. I guess > so. Might even drop the name change, too... Don't !-) > while I'm at it. One > more word from you about it and I'm starting a thread, and calling it, > "Python and my sense of 'soul'". Ha ha. Please bear with me - and understand that the above half-backed half-joke was also an implicit aknowledgement of the recent changes in your mode of communication. I should have added a , I think... From stef.mientki at gmail.com Mon Sep 29 15:56:19 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Mon, 29 Sep 2008 21:56:19 +0200 Subject: how to search multiple textfiles ? (Python is slow ?) In-Reply-To: References: <17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> Message-ID: <48E132E3.8070308@gmail.com> Lawrence D'Oliveiro wrote: > In message , Stef > Mientki wrote: > > >> - Pyscripter 110 sec ( PyScripter is the default IDE I use now) >> - Delphi 20 .. 35 sec >> - Findstr 4 sec >> > > What order did you try try them in? Did you try each one more than once, in > different orders? Just to rule out filesystem caching effects. > > I repeated all of them at least twice, to see if I got the same result. And indeed the very first run (PyScripter) was about 150 sec. So I think the above mentioned values give a good impression, nothing more. >> I'm really amazed by the speed of Python !! >> It can only be beaten by findstr, which is only available on windows. >> > > Did you try find -exec grep -F? > well my windows version doesn't understand that : P:\Python>find /? Searches for a text string in a file or files. FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]] /V Displays all lines NOT containing the specified string. /C Displays only the count of lines containing the string. /N Displays line numbers with the displayed lines. /I Ignores the case of characters when searching for the string. /OFF[LINE] Do not skip files with offline attribute set. "string" Specifies the text string to find. [drive:][path]filename Specifies a file or files to search. If a path is not specified, FIND searches the text typed at the prompt or piped from another command. cheers, Stef > -- > http://mail.python.org/mailman/listinfo/python-list > From bearophileHUGS at lycos.com Wed Sep 3 08:23:10 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 05:23:10 -0700 (PDT) Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: <7f2d4b4a-bc97-4b46-a31e-63f98e9fee73@34g2000hsh.googlegroups.com> Roy Smith: > No reason to limit how many splits get done if you're > explicitly going to slice the first two. You are probably right for this problem, because most lines are 2 items long, but in scripts that have to process lines potentially composed of many parts, setting a max number of parts speeds up your script and reduces memory used, because you have less parts at the end. Bye, bearophile From __peter__ at web.de Thu Sep 18 08:45:34 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2008 14:45:34 +0200 Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > > but no improvements. > > Many thanks, Alex When you're looking for duplicates an efficient solution is likely to be based on a set or dict object. # untested from collections import defaultdict groups = defaultdict(list) for item in IN: c = item.coordinates groups[c[0], c[1]].append(item.label) SN = [] for labels in groups.itervalues(): if len(labels) > 1: SN.extend(labels) # or labels[1:] if you want to keep one item Peter From marco.bizzarri at gmail.com Thu Sep 4 10:43:46 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 16:43:46 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <48bfd7a0$0$20720$426a74cc@news.free.fr> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <48bfd7a0$0$20720$426a74cc@news.free.fr> Message-ID: <3f0d61c40809040743t75caf483gec5714b7abd4ef6b@mail.gmail.com> On Thu, Sep 4, 2008 at 2:43 PM, Bruno Desthuilliers wrote: Well, Bruno, it looks like I've to wider my search in order to read something about it. Thanks for your suggestions, in any case. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From half.italian at gmail.com Mon Sep 8 15:38:37 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 8 Sep 2008 12:38:37 -0700 (PDT) Subject: How to run PyOS_InputHook from python code (i.e. yield to event loops) References: <87wshpcaek.fsf@gmail.com> Message-ID: On Sep 6, 1:00?pm, vivai... at gmail.com (Ville M. Vainio) wrote: > Background: PyOS_InputHook is something that gets run when python is > doing raw_input. TkInter and friends use it to run their event loops, > so that their events are handled while python is doing raw_input. > > What I'd like to do is run the same function without having to do > raw_input. I.e. I'd like to run whatever event loop is available, > without incorporating any gui-specific code (PyOS_InputHook seems like > a nifty way to accomplish this). > > My actual use case is to keep a tkinter application responsive while > launching a background process (and waiting for it to complete!). > > My eventual code would be something like: > > launch_process_in_thread('bzr pull') > > while not is_done: > ? pyos_inputhook() > ? time.sleep(0.1) > > print "Done!" I'm still recovering from a hangover, so don't quote me. I think you want the "after" function: launch_process_in_thread('bzr pull') self.update() def update(self): while not self.is_done: self.after(2000, self.update) From steve at REMOVE-THIS-cybersource.com.au Fri Sep 5 23:45:21 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 06 Sep 2008 03:45:21 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> Message-ID: <00d1f730$0$20302$c3e8da3@news.astraweb.com> On Fri, 05 Sep 2008 22:20:06 -0400, Manu Hack wrote: > On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: ... >>> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >>> >>> It doesn't make sense to me. What do you set x to? >> >> For all x. > > But then how can you conclude sum([]) = 0 from there? It's way far from > obvious. I think Castironpi's reasoning is to imagine taking sum([x])-x for *any* possible x (where subtraction and addition is defined). Naturally you always get 0. Now replace x by *nothing at all* and you get: sum([]) "subtract nothing at all" = 0 I think that this is a reasonable way to *informally* think about the question, but it's not mathematically sound, because if you replace x with "nothing at all" you either get: sum([]) - = 0 which is invalid (only one operand to the subtraction operator), or you get: sum([0]) - 0 = 0 which doesn't involve an empty list. What castironpi seems to be doing is replacing "nothing at all" with, er, nothing at all in one place, and zero in the other. And that's what makes it unsound and only suitable as an informal argument. [The rest of this is (mostly) aimed at Mensanator, so others can stop reading if they like.] Fundamentally, the abstract function "sum" and the concrete Python implementation of sum() are both human constructs. It's not like there is some pure Platonic[1] "Ideal Sum" floating in space that we can refer to. Somewhere, sometime, some mathematician had to *define* sum(), and other mathematicians had to agree to use the same definition. They could have decided that sum must take at least two arguments, because addition requires two arguments and it's meaningless to talk about adding a single number without talking about adding it to something else. But they didn't. Similarly, they might have decided that sum must take at least one argument, and therefore prohibit sum([]), but they didn't: it's more useful for sum of the empty list to give zero than it is for it to be an error. As I mentioned earlier, mathematicians are nothing if not pragmatists. [1] Or was it Aristotle who believed in Ideal Forms? No, I'm sure it was Plato. -- Steven From Lie.1296 at gmail.com Sun Sep 28 11:55:03 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 08:55:03 -0700 (PDT) Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48db462f$0$24356$426a74cc@news.free.fr> Message-ID: <2dec1987-6477-4269-8964-5ef847495dd3@o40g2000prn.googlegroups.com> On Sep 25, 3:05?pm, Bruno Desthuilliers wrote: > Steven D'Aprano a ?crit : > > > On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote: > > >> Plenty of people were quick to say that the exception should be passed > >> through to the caller. ?No one said this behaviour should be documented. > >> ?There may be little practical difference bewteen calling sys.exit() > >> after printing an error and progating an exception if no one using the > >> library knows that it could generate that exception in those > >> circumstances. > > > That's true, I didn't explicitly say that the library should be > > documented. Nor did I say that it shouldn't be riddled with bugs. There's > > little practical difference between a buggy library and one that raises > > unexpected (i.e. undocumented) exceptions either. > > Also note that there are quite a couples cases where the library authors > themselves cannot predict which exception types may be raised - as soon > as the library functions expect callback functions, file-like or > dict-like or whatever-like objects etc, it's the caller's responsability > to handle the exceptions that may be raised by what *he* passes to the > library... No, the library author can always predict which exception his library may raise. If a callback function, file-like, dict-like, etc raises an exception, it is not his libraries' exception anymore and is not his responsibility. In that case we should refer to the documentation for the callback/etc/etc instead of the documentation for the library. From roy at panix.com Sun Sep 21 12:24:09 2008 From: roy at panix.com (Roy Smith) Date: Sun, 21 Sep 2008 12:24:09 -0400 Subject: Why are "broken iterators" broken? References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: In article , Fredrik Lundh wrote: > Steven D'Aprano wrote: > > > According to the Python docs, once an iterator raises StopIteration, it > > should continue to raise StopIteration forever. Iterators that fail to > > behave in this fashion are deemed to be "broken": > > > > http://docs.python.org/lib/typeiter.html > > > > I don't understand the reasoning behind this. As I understand it, an > > iterator is something like a stream. There's no constraint that once a > > stream is empty it must remain empty forever. > > it's a design guideline, not an absolute rule. > > but I disagree that an iterator is "something like a stream". it's > rather "something like a pointer or an index", that is, an object that > helps you iterate over all members in a collection. > > There are plausible examples of collections which grow while you're iterating over them. I'm thinking specifically of a queue in a multi-threaded application. One thread pushes work onto the back of the queue while another pops from the front. The queue could certainly go empty at times. But, maybe a Python iterator is just the wrong way to model such behavior. From python-list at trentnelson.com Thu Sep 4 16:27:59 2008 From: python-list at trentnelson.com (Trent Nelson) Date: Thu, 4 Sep 2008 20:27:59 +0000 Subject: Can anyone suggest a good crypto package? In-Reply-To: References: Message-ID: <20080904202759.GA20070@wind.teleri.net> On Thu, Sep 04, 2008 at 11:39:42AM -0700, Fett wrote: > I need a crypto package that works on windows with python 2.5. Can > anyone suggest one for me? You could always rely on the the APIs Windows provides to do this sort out stuff, either via pywin32 or ctypes. Trent. From superflit at gmail.com Tue Sep 9 15:52:55 2008 From: superflit at gmail.com (flit) Date: Tue, 9 Sep 2008 12:52:55 -0700 (PDT) Subject: check if the values are prensent in a list of values References: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> <48c6caae$0$22688$426a74cc@news.free.fr> Message-ID: <5fcfc9d3-bec3-45b0-9b00-bfcc173072ee@r66g2000hsg.googlegroups.com> On 9 set, 15:13, Bruno Desthuilliers wrote: > Matt Nordhoff a ?crit : > (snip) > > > I'm not judging whether this is a good solution or not, but that's a > > silly use of a dict. > > Yeps, but a somewhat common one in code predating the apparition of sets > as builtin type. Thanks for all contributions, sure I learn a lot with all samples. Very good thread and answers. Thank you all From jkn_gg at nicorp.f9.co.uk Fri Sep 26 05:33:49 2008 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Fri, 26 Sep 2008 02:33:49 -0700 (PDT) Subject: Time.sleep(0.0125) not available within Linux References: <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <00eb2560$0$20666$c3e8da3@news.astraweb.com> Message-ID: On Sep 26, 9:26 am, Steven D'Aprano wrote: > On Fri, 26 Sep 2008 19:46:10 +1200, Lawrence D'Oliveiro wrote: > > In message <00eb2560$0$20666$c3e8... at news.astraweb.com>, Steven D'Aprano > > wrote: > > >> On Wed, 24 Sep 2008 22:18:05 +1200, Lawrence D'Oliveiro wrote: > > >>> Just a thought, your minimum sleep time is probably limited by the > >>> resolution of the system "HZ" clock. Type > > >>> less /proc/config.gz > > >> $ less /proc/config.gz > >> /proc/config.gz: No such file or directory > > >> What OS are you using? > > > The one named in the subject line? > > Are you asking me or telling me? > > I've tried on five different Linux machines I have access to, and there > is no such /proc/config.gz on any of them: > /proc/config.gz is not directly connected with a specific linux distribution; it's a function of the kernel build configuration. If the appropriate setting is enabled, then /proc/config.gz will show (via eg. zcat) the equivalent of the .config file used to build the kernel you are actually running. It's a useful feature in all linuces, going back quite a way IIRC. J^n From manuhack at gmail.com Sat Sep 6 00:33:25 2008 From: manuhack at gmail.com (Manu Hack) Date: Sat, 6 Sep 2008 00:33:25 -0400 Subject: max(), sum(), next() In-Reply-To: <00d1f730$0$20302$c3e8da3@news.astraweb.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <00d1f730$0$20302$c3e8da3@news.astraweb.com> Message-ID: <50af02ed0809052133s5f3ea925s90f8200fefda3582@mail.gmail.com> On Fri, Sep 5, 2008 at 11:45 PM, Steven D'Aprano wrote: > On Fri, 05 Sep 2008 22:20:06 -0400, Manu Hack wrote: > >> On Fri, Sep 5, 2008 at 1:04 PM, castironpi wrote: > ... >>>> >The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >>>> >>>> It doesn't make sense to me. What do you set x to? >>> >>> For all x. >> >> But then how can you conclude sum([]) = 0 from there? It's way far from >> obvious. > > I think Castironpi's reasoning is to imagine taking sum([x])-x for *any* > possible x (where subtraction and addition is defined). Naturally you > always get 0. > > Now replace x by *nothing at all* and you get: > > sum([]) "subtract nothing at all" = 0 > > I think that this is a reasonable way to *informally* think about the > question, but it's not mathematically sound, because if you replace x > with "nothing at all" you either get: > > sum([]) - = 0 > > which is invalid (only one operand to the subtraction operator), or you > get: > > sum([0]) - 0 = 0 > > which doesn't involve an empty list. What castironpi seems to be doing is > replacing "nothing at all" with, er, nothing at all in one place, and > zero in the other. And that's what makes it unsound and only suitable as > an informal argument. Actually it's even more natural to state sum([x]) = x, and this way you can never conclude that sum([]) = 0 from there. From Scott.Daniels at Acm.Org Tue Sep 30 09:10:42 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 30 Sep 2008 06:10:42 -0700 Subject: Weirdness comparing strings In-Reply-To: References: Message-ID: Mr.SpOOn wrote: > Hi, > I have this piece of code: > > class Note(): Unless you _need_ old-style, use new style. > ... > def has_the_same_name(self, note): > return self == note Define equality (__eq__) if you want to compare for equality. > def __str__(self): > return self.note_name + accidentals[self.accidentals] > > __repr__ = __str__ If str and repr are to be equal, just define repr. class Note(object): def __init__(self, note, accidentals): self.note_name = note self.accidentals = accidentals def has_the_same_name(self, note): return self == note def __eq__(self, other): return isinstance(other, Note) and ( self.note_name == other.note_name and self.accidentals == other.accidentals) def __repr__(self): return self.note_name + accidentals[self.accidentals] --Scott David Daniels Scott.Daniels at Acm.Org From python at rgbaz.eu Wed Sep 10 12:25:19 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 18:25:19 +0200 Subject: md5 differences Message-ID: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> Hi there! I'm trying to match the results of an md5 checksum done in a tcsh shell. I keep getting different results and can't find anything on google... here's an example: Arno at Computer:~% echo "hello" | md5 b1946ac92492d2347c6235b4d2611184 Arno at Computer:~% python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import md5 >>> md5.new("hello").hexdigest() '5d41402abc4b2a76b9719d911017c592' How do I get the same results? thanks Arno From mark at thomaszone.com Wed Sep 17 08:54:27 2008 From: mark at thomaszone.com (Mark Thomas) Date: Wed, 17 Sep 2008 05:54:27 -0700 (PDT) Subject: Generating test data from an XML Schema References: Message-ID: <5f905036-16f7-485d-8dca-9231d91f308e@e39g2000hsf.googlegroups.com> On Sep 17, 5:29?am, Jonathan Fine wrote: > Hello > > I want to generate test data from an XML schema. ?I've had a quick look > at existing tools (such as minixsv and amara) but from what I've seen > they don't seem to help. ... > A tool that provides a nice Python interface to navigating the schema > would probably be quite helpful. > > Has anyone seen anything that might help generate test data from a schema? I'm unaware of anything in Python, but Eclipse can generate sample documents from a schema: http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.wst.xmleditor.doc.user/topics/tcrexxsd.html As can XML IDEs such as Stylus Studio and XML Spy. -- Mark. From castironpi at gmail.com Tue Sep 16 16:53:48 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 13:53:48 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> Message-ID: On Sep 16, 3:16?pm, cnb wrote: > On Sep 16, 7:49?pm, "Aaron \"Castironpi\" Brady" > > > Now I have my personal programs in C:/Python25/Progs/ > > > > How do I add so that I can just do "import somefile" from anywhere in > > > that directory in the interpreter and it can load files from other > > > folders in that directory. > > > Add a file: \Lib\site-packages\locals.pth > > > with contents, path to the directory you want to add (/python25/progs/) > > And we have a winner! > > Now it works. Both doing import and loading form fiel with C-c C-l > > However jsut including C:/Python/Progs wasn't enough. I had to add the > folder inside that that contains the files i needed. > > so how do i add all files within progs? is there something like C:/ > python25/progs/* ? You have: c:/python/progs/abc/filea.py c:/python/progs/abc/fileb.py c:/python/progs/def/filed.py c:/python/progs/def/filee.py __init__.py in progs (empty...) __init__.py in abc __init__.py in def c:/python/site-packages/lib/locals.py which contains: c:/python/progs/ You don't need the subdirectories. You can do: import abc import abc.filea from abc import filea From randika.rathugama at gmail.com Wed Sep 17 15:03:50 2008 From: randika.rathugama at gmail.com (Randika) Date: Wed, 17 Sep 2008 12:03:50 -0700 (PDT) Subject: open Invitation to Join with DeveloperWiki Knowledge base Message-ID: <03e1c28b-cdcf-4091-884b-2c97058bea2c@a29g2000pra.googlegroups.com> Dear Developers,IT Professionals, "We are building a online encyclopedia for developers" and we need your contribution to make it even better. So here is our invitation for those who happy to contribute as editors, readers for the project. If you have written a tutorial/article/code snippet and would like to share it with others, you can publish it on DeveloperWiki and also you can Edit/Update any existing articles too. Please visit DeveloperWiki web site here http://DeveloperWiki.org Official discussion group. http://groups.google.com/group/DeveloperWikiUserGroup Thanks --DeveloperWiki Team From hussainsaiger at gmail.com Mon Sep 1 06:30:06 2008 From: hussainsaiger at gmail.com (hussainsaiger at gmail.com) Date: Mon, 1 Sep 2008 03:30:06 -0700 (PDT) Subject: Using NLTK in Java References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> <6i1hu9FnvcngU1@mid.uni-berlin.de> Message-ID: On 1 Sep, 11:55, "Diez B. Roggisch" wrote: > hussainsai... at gmail.com schrieb: > > > I am trying to convert a python module (that contains the use of > > NLTK.Corpus) by jythonc. It is not able to include nltk dependencies > > within the java class it creates. So when i use this class in java, it > > fails to recognize nltk. Can anyone please let me know how should i > > use nltk in python/jython modules so i can use in Java. > > If there are any binary dependencies, you are out of luck. It won't > work. You would need to write a RPC-Server then, with technologies such > as XMLRPC or CORBA. > > Diez So does that mean that Jython does not support nltk uptil now. I ask this because when I try to import nltk in Jython (which is assumed to replace Python), i get the same error. Its just nltk that I am not able to use. The rest of the jython functions and libraries work fine within Java. From wegwerp at gmail.com Sat Sep 13 12:00:12 2008 From: wegwerp at gmail.com (Bas) Date: Sat, 13 Sep 2008 09:00:12 -0700 (PDT) Subject: Profiling, sum-comprehension vs reduce References: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> Message-ID: <15035654-38f2-441f-a3ff-f4b943312f1c@m3g2000hsc.googlegroups.com> On Sep 13, 10:06?am, cnb wrote: > This must be because of implementation right? Shouldn't reduce be > faster since it iterates once over the list? > doesnt sum first construct the list then sum it? No, sum also iterates the sequence just once and doesn't create a list. It is probably implemented similar to def sum(sequence, start=0): it = iter(sequence) total = start for i in it: total += i return i but then implemented in C for speed. Reduce is probably implemented pretty similar, but then with a random function instead of addition. Make sure that you understand the difference between generator expression and list comprehension, and that [f(x) for x in something] is (almost) equal to list(f(x) for x in something), so you can emulate a LC by using the list constructor on the equivalent GE. HTH, Bas From grante at visi.com Wed Sep 3 10:14:03 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Sep 2008 09:14:03 -0500 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <6i56cpFor2puU1@mid.individual.net> Message-ID: On 2008-09-02, Christian Heimes wrote: > Fredrik Lundh wrote: >> Peter Pearson wrote: >> >>> (startled noises) It is a delight to find a reference to >>> that half-century-old essay (High Finance) by the wonderful >>> C. Northcote Parkinson, but how many readers will catch the >>> allusion? >> >> anyone that's been involved in open source on the development side for >> more than, say, ten minutes. > > Indeed! Thus speaks the experienced developer -- effbot :) > > On some mailing lists the bikeshed issue comes hand in hand with the > Dunning-Kruger-effect. [1] *sigh* > > Christian > > [1] http://en.wikipedia.org/wiki/Dunning-Kruger_effect That paper is really very interesting -- it explains a lot of what one sees in corporate life. -- Grant Edwards grante Yow! I just remembered at something about a TOAD! visi.com From bruno.42.desthuilliers at websiteburo.invalid Wed Sep 24 03:26:10 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 09:26:10 +0200 Subject: Does anybody use this web framework ? In-Reply-To: <48d94cbc$0$964$ba4acef3@news.orange.fr> References: <48d94cbc$0$964$ba4acef3@news.orange.fr> Message-ID: <48d9eb86$0$6127$426a34cc@news.free.fr> Phil Cataldo a ?crit : > Hi, > > I just found this new? python web framework > (http://pypi.python.org/pypi/nagare/0.1.0). > > Does anybody know or use it ? First time I hear of it, but it looks interesting (note : Stackless continuation-based framework). Thanks for the link. From roy at panix.com Mon Sep 15 08:58:54 2008 From: roy at panix.com (Roy Smith) Date: Mon, 15 Sep 2008 08:58:54 -0400 Subject: Abstract class References: <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> Message-ID: Maric Michaud wrote: > The only way to do this is to call in the __init__ at least one of the > methods raising NotImplementedError, probably creating a dummy one for > this purpose, and still it doesn't satisfy with the constraint that > *all* abstract methods must be implemented in concrete classes. I wouldn't actually *call* the method (because of possible side-effects), but you could certainly check that they exist and are callable: class Base: """An abstract base class. You must define methods f(), g(), and h() in any subclasses of this. """ def __init__(self): try: assert callable(self.f) assert callable(self.g) assert callable(self.h) except: raise NotImplementedError # or something more specific Of course, this assumes that you write: class Derived(Base): def __init__(self): Base.__init__(self) There's no way (that I can think of :-)) to *force* you to call Base.__init__() from Derived.__init__(). This is all a bit silly, however. If you want type bondage, use a language that gives you type bondage (C++ and Java being two obvious examples). From upton at virginia.edu Mon Sep 15 13:07:41 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 15 Sep 2008 13:07:41 -0400 Subject: Parallelising code In-Reply-To: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: <5504f9ac0809151007n5710750cj3b75eea8da3e90c8@mail.gmail.com> > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? That probably depends on both how much data is involved in a "data point" (ie, is it just one value, or are you parsing several fields from the CSV per record), and how much processing each point involves. Profiling should enlighten you, yes. You may also have issues with I/O contention if you have lots of threads trying to read from disk at once, although I'm not sure how much of an impact that will have. > > - Is list.append() thread safe? (not sure if this is the right term) > what I mean is, can two separate processors file a point in the same > list at the same time without anything horrible happening? Do I need > to do anything special (mutex or whatever) to make this happen, or > will it happen automatically? http://mail.python.org/pipermail/python-list/2007-March/430017.html http://effbot.org/pyfaq/what-kinds-of-global-value-mutation-are-thread-safe.htm From notvalid2 at sbcglobal.net Tue Sep 9 07:22:47 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Tue, 09 Sep 2008 04:22:47 -0700 Subject: Correcting for Drift between Two Dates In-Reply-To: References: Message-ID: <80txk.19556$LG4.2157@nlpi065.nbdc.sbc.com> Steven D'Aprano wrote: > On Mon, 08 Sep 2008 21:53:18 -0700, W. eWatson wrote: > >> I have two dates, ts1, ts2 as below in the sample program. I know the >> clock drift in seconds per day. I would like to calculate the actual >> date of ts2. See my question at the end of the program. > > > When faced with a complicated task, break it down into simpler subtasks. > Functions are your friends. Here you go: > > > > from __future__ import division > > from datetime import datetime as DT > from datetime import timedelta > > SITE_DRIFT = 4.23 # drift in seconds per day > # negative drift means the clock falls slow > SEC_PER_DAY = 60*60*24 # number of seconds per day > > > def calc_drift(when, base, drift=SITE_DRIFT): > """Return the amount of drift at date when since date base.""" > x = when - base > days = x.days + x.seconds/SEC_PER_DAY > return drift*days > > def fix_date(when, base, drift=SITE_DRIFT): > """Return date when adjusted to the correct time.""" > d = calc_drift(when, base, drift) > delta = timedelta(seconds=-d) > return when + delta > > > And here it is in action: > >>>> fix_date(DT(2008,9,9), DT(2008,9,8)) > datetime.datetime(2008, 9, 8, 23, 59, 55, 770000) > > > > I leave it to you to convert date/time strings into datetime objects. > > > Ah, ha. x.days and x.seconds. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: From psaffrey at googlemail.com Mon Sep 15 12:46:18 2008 From: psaffrey at googlemail.com (psaffrey at googlemail.com) Date: Mon, 15 Sep 2008 09:46:18 -0700 (PDT) Subject: Parallelising code Message-ID: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> I have some file processing code that has to deal with quite a lot of data. I have a quad core machine, so I wondered whether I could take advantage of some parallelism. Essentially, I have a number of CSV files, let's say 100, each containing about 8000 data points. For each point, I need to look up some other data structures (generated in advance) and append the point to a relevant list. I wondered whether I could get each core to handle a few files each. I have a few questions: - Am I actually going to get any speed up from parallelism, or is it likely that most of my processing time is spent reading files? I guess I can profile for this? - Is list.append() thread safe? (not sure if this is the right term) what I mean is, can two separate processors file a point in the same list at the same time without anything horrible happening? Do I need to do anything special (mutex or whatever) to make this happen, or will it happen automatically? Thanks in advance for any guidance, Peter From digitig at gmail.com Fri Sep 26 06:32:08 2008 From: digitig at gmail.com (Tim Rowe) Date: Fri, 26 Sep 2008 11:32:08 +0100 Subject: problem updating variable in a module In-Reply-To: References: Message-ID: 2008/9/24 Terry Reedy : > With the mod/mod1 mixup fixed, you do not need the update function. > mod.a = 20 > should do the same thing. I was assuming that the update function was just to illustrate the access problem the writer was having. I think the chances are the problem is due to a typo or some such (happens to us all!) but without seeing the actual code there's not a lot we can do. -- Tim Rowe From hrishys at yahoo.co.uk Thu Sep 25 06:22:14 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 10:22:14 +0000 (GMT) Subject: Linq to Python In-Reply-To: Message-ID: <584583.16573.qm@web27405.mail.ukl.yahoo.com> Hi Roger I am impressed (i always suspected Python programmers are smart no doubt about it). But what about the case where they join different sources like the one here http://informationr.net/ir/13-2/TB0806.html Thanks for teaching me :-) i am thankful for that regards Hrishy > > names = ["Burke", "Connor", > "Frank", "Everett", > "Albert", "George", > "Harris", "David"] > > result = [each.upper() for each in names if len(each) == 5] > > result.sort() > > for each in result: print each > > > Yes clearly 'the Python crowd' must admit LINQ is > 'much better', I'm > sold, in fact off to download my "Free, but limited > editions of Visual > Studio 2005 for a single programming language supported by > .NET" right away! > > OK so maybe I'm being naive here but it looks to me > like this new > paradigm's big idea is to use a python + SQL type > syntax to access data > in random objects. Big whoop. It's not that difficult > to write a > generators that wraps XML files and databases is it? > > What am I missing here? > > > Roger Heathcote. > -- > http://mail.python.org/mailman/listinfo/python-list From karl.kobata at syncira.com Thu Sep 18 10:33:22 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Thu, 18 Sep 2008 07:33:22 -0700 Subject: fwd: member functions in a class Message-ID: <6gvfio$7tb3j8@rrcs-agw-01.hrndva.rr.com> Gary, No the answer is not too short, thank you for your reply, I am learning rapidly. Terry, The expanded answer is also useful. Now I am getting a better insight on how python resolves object attributes. This also gives me more insight on the difference between import vs from from *. Thanks karl -------------- next part -------------- An HTML attachment was scrubbed... URL: From superflit at gmail.com Tue Sep 9 14:04:05 2008 From: superflit at gmail.com (flit) Date: Tue, 9 Sep 2008 11:04:05 -0700 (PDT) Subject: check if the values are prensent in a list of values Message-ID: <4a1829a6-f31c-42e1-8ead-fcd3cbb128aa@k7g2000hsd.googlegroups.com> Hello All, I will appreciate the help from the more skillfull pythonistas.. I have a small app that generates a sequence like 00341 01741 03254 This values I am putting in a list. So I have a list = [00341,01741,03254] after the programs find the sequence 03401 this sequence is "new" so it appends on the list. But I want to avoid that as the values are already on the first sequence of the list (00341). If I try to use a "in" statement it will give false. as 00341 is different from 00341 (but for my goal not..) How can I check against this list and avoid to put "different" sequences but same values? as 34100 --> dont append on the list 14300 ---> dont append on the list 05321 --> append to the list. Am I doing some conceptual error using lists? There is a better approach? Thanks From castironpi at gmail.com Wed Sep 24 12:05:04 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 09:05:04 -0700 (PDT) Subject: PyRun_SimpleFile() crashes References: Message-ID: <26532f88-b70c-4b18-af4d-5176ec023f46@c65g2000hsa.googlegroups.com> On Sep 24, 6:30?am, Nick Craig-Wood wrote: > lixinyi... at gmail.com wrote: > > ?my code: > > ?main.cpp > > ?#include > > > ?int main(int argc, char **argv) > > ?{ > > ?Py_Initialize(); > > > ?FILE *file_1 = fopen("a2l_reader.py","r+"); > > ?PyRun_SimpleFile(file_1,"a2l_reader.py"); > > > ?Py_Finalize(); > > ?} > > > ?compile under windows using MinGW: > > ?g++ main.cpp libpython25.a -o a > > > ?no error was found. But when I run a.exe the program just crashes. > > > ?What should I do? > > Run it under gdb (which should have come with MinGW). > > Check that you actually opened the file, ie file_1 != 0. > > This might be relevant > > ?http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o... > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick There's a workaround. filename = "Entire path of the python file"; PyObject* PyFileObject = PyFile_FromString(filename, "r"); PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename); // decref PyFileObject http://mail.python.org/pipermail/python-list/2007-March/431725.html http://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567 From python at rgbaz.eu Wed Sep 10 13:51:36 2008 From: python at rgbaz.eu (Python) Date: Wed, 10 Sep 2008 19:51:36 +0200 Subject: md5 differences In-Reply-To: References: Message-ID: On 10 sep 2008, at 19:39, Grant Edwards wrote: > On 2008-09-10, Wojtek Walczak wrote: >> On Wed, 10 Sep 2008 19:12:28 +0200, Python wrote: >>> Arno at Computer:~% echo "test" > test.txt >>> >>> Arno at Computer:~% md5 test.txt >>> MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249 >> >>>>>> import md5 >>>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >>> '90364ed45b452d43378629c20543a81d' >> >> >> Works for me: >> >>>>> import md5 >>>>> f = open('test.txt').read() >>>>> md5.new(f).hexdigest() >> 'd8e8fca2dc0f896fd7cb4cb0031ba249' >>>>> >> >> IOW, don't pass the path to the file to md5.new, but the contents >> of this file. >> >> The strange thing is that >>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest() >> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine. > > Same here. > > -- > Grant Edwards grante Yow! What PROGRAM > are they thanks everyone for helping me out! cheers Arno From gminick at bzt.bzt Mon Sep 1 09:41:25 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 13:41:25 +0000 (UTC) Subject: Eleganz way to get rid of \n References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: On Mon, 01 Sep 2008 15:25:03 +0200, Hans M?ller wrote: > I'm quite often using this construct: > > for l in open("file", "r"): > do something > Has someone a better solution ? The most general would be to use rstrip() without arguments: >>> a="some string\r\n" >>> a.rstrip() 'some string' >>> but be careful, because it will also cut whitespaces: >>> a="some string\t \r\n" >>> a.rstrip() 'some string' >>> so maybe you could do this: >>> a.rstrip('\n').rstrip('\r') 'some string\t ' >>> HTH. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From mensanator at aol.com Wed Sep 17 23:34:02 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 17 Sep 2008 20:34:02 -0700 (PDT) Subject: How to Determine Name of the Day in the Week References: Message-ID: <0928a498-1cc0-48c7-985e-4faf019d8a70@m3g2000hsc.googlegroups.com> On Sep 17, 10:20?pm, Keo Sophon wrote: > Fredrik Lundh wrote: > > Henry Chang wrote: > > >> Instead of getting integers with weekday(), Monday == 0 ... Sunday == > >> 6; is there a way to get the actual names, such as "Monday ... > >> Sunday"? I would like to do this without creating a data mapping. :) > > > if you have a datetime or date object, you can use strftime with the > > appropriate formatting code. see the library reference for details. > > > if you have the weekday number, you can use the calender module: > > > >>> import calendar > > >>> calendar.day_name[0] > > 'Monday' > > > (the latter also contains abbreviated day names, month names, and a > > bunch of other potentially useful functions and mappings.) > > > > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Hi, > > I've tried calendar.month_name[0], it displays empty string, while > calendar.month_name[1] is "January"? Why does calendar.month_name's > index not start with index 0 as calendar.day_name? Because there's no month 0? And technically, weeks begin on Sunday, not Monday, but business likes to think of Monday as day 0 of the week and it doesn't conflict with any prior date format. > > Thanks, > Sophon From cipherzero at gmail.com Sat Sep 6 21:16:54 2008 From: cipherzero at gmail.com (cipher) Date: Sat, 6 Sep 2008 18:16:54 -0700 (PDT) Subject: found a bug with smtpd, where can i report this? References: Message-ID: <5d2562b3-8825-43d3-b3aa-1b4fc10b9a72@x1g2000prh.googlegroups.com> On Sep 5, 4:01?am, "Marcus.CM" wrote: > Hi, > > Where should i report the bug? > smtpd bug. > > Marcus.CM http://bugs.python.org/ From steve at REMOVE-THIS-cybersource.com.au Tue Sep 30 19:54:18 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 23:54:18 GMT Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> <87hc7xqlnj.fsf@benfinney.id.au> Message-ID: <00f2b5d2$0$20617$c3e8da3@news.astraweb.com> On Wed, 01 Oct 2008 09:06:08 +1000, Ben Finney wrote: > Terry Reedy writes: > >> Steven D'Aprano wrote: >> > We agree that the restriction is artificial, and I think irrational >> > (although I'd be interested in hearing the gnuplot developers' >> > reasoning before making a final judgment). >> >> I believe it is a matter of preserving clarity of authorship, just as >> is the quoting mechanism we take for granted in posts like this. If I >> removed the quote marks above and silently edited what Ben and you >> wrote, I might upset someone and certainly could confuse readers. > > That, if it were to be prosecuted under law, would be a matter already > covered by laws other than copyright: fraud, libel, etc. > > Note that I consider a work free even if it fails to grant ?the right to > distribute misrepresentations of the author's words?, because that act > is an exercise of undue power over another person, and so falls outside > the limit imposed by the freedoms of others. But distributing modified source code *does* misrepresent the author's words, because you confuse authorship. Given only the modified version of the source code, how is the recipient supposed to identify which parts of the source code were written by the original authors and which parts where written by you? If that is why the gnuplot people do not allow you to distribute such modified documents, then the only "freedom" they fail to grant is exactly the one you don't consider necessary for a free licence: "the right to distribute misrepresentations of the author's words". -- Steven From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 30 05:26:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 30 Sep 2008 11:26:36 +0200 Subject: How best to pass arbitrary parameters from one function to another In-Reply-To: References: Message-ID: <48e1f0af$0$27506$426a74cc@news.free.fr> John O'Hagan a ?crit : > Hi Pythonistas, > > I'm looking for the best way to pass an arbitrary number and type of variables > created by one function to another. > > They can't be global because they may > have different values each time they are used in the second function. > > So far I'm trying to do something like this: > > > def process_args( [list, of, command-line, arguments] ): > > do stuff > return {dictionary : of, local : variables } > > def main_function( **kwargs ): > > do stuff > return result > > kw1 = process_args( [some, list] ) > kw2 = process_args( [a, different, list] ) > > for i in main_function( **kw1 ): > > kw2[ var1 ] = i > kw2[ var2 ] = len( i ) > > for j in main_function(**kw2): > > print j > > This only seems to work if I specify a default value for every possible > parameter of main_function and also for any others which may be passed to it, > which is a bit tedious because there are very many of them but only a few are > used in any given execution of the program. If this is about commmand line arguments parsing and defaults, you may want to have a look at the optparse package in the stdlib. Also, kwargs work fine with default arguments too, ie: def func(arg1=1, arg2='yadda', arg3=None): print arg1, arg2, arg3 for kw in ({}, {'arg1':42}, {'arg2':'yop', 'arg3' : range(5)}): func(**kw) HTH From castironpi at gmail.com Mon Sep 22 20:07:09 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 17:07:09 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <00e816f4$0$20303$c3e8da3@news.astraweb.com> <6602abad-3c12-4c0c-b41d-95f79cebdc31@y21g2000hsf.googlegroups.com> Message-ID: On Sep 22, 6:55?pm, MRAB wrote: > On Sep 22, 11:46?pm, "Aaron \"Castironpi\" Brady" > > > > wrote: > > On Sep 22, 5:32?pm, Steven D'Aprano > > cybersource.com.au> wrote: > > > On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: > > > > On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano > > > >> But that's precisely what I want to avoid: I don't want the objects to > > > >> ?share *any* state, not even their class. I'm not trying for a Borg or > > > >> ?Singleton: the user can call the factory as many times as they want, > > > >> ?but the objects returned shouldn't share any state. I don't know if > > > >> ?what I want has a name. Judging from people's reactions, I'd say > > > >> ?probably not. > > > > > Snce when are "users" ever involved > > > > in programming problems or programming languages ? > > > > What an astounding question. > > > > Consider a class. There are the programmers who write the class, and > > > there are the programmers (possibly the same people, but not necessarily) > > > who use the class. The second set of people, the programmers who use the > > > class, are *users* of the class. What else would they be? > > > > -- > > > Steven > > > Usegrammers? > > And professionals are programmers, amateurs are amgrammers and newbies > are newgrammers? :-) Not to be rude, but no. Usegrammers usegram. From marco.bizzarri at gmail.com Thu Sep 11 09:52:37 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 11 Sep 2008 15:52:37 +0200 Subject: Python and Open Office In-Reply-To: References: Message-ID: <3f0d61c40809110652x444c68d8kdf7eeb206accfaf3@mail.gmail.com> Greg, as an addition to what I already said to you, you can consider taking a look at oood from ERP5 project http://wiki.erp5.org/HowToUseOood OOOd (openoffice.org daemon) runs openoffice behind the scene, and allows you to interact with it via XML-RPC; it should be quite robust, since it is actively mantained and used in a big software project. And, also, it should be quite easy to extend in order to have your custom functions run via XML-RPC. Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From castironpi at gmail.com Sat Sep 27 19:33:43 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 27 Sep 2008 16:33:43 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <00ee05ca$0$20666$c3e8da3@news.astraweb.com> <1a7184f3-c71e-49b7-a8f8-f141705f3573@l42g2000hsc.googlegroups.com> Message-ID: On Sep 27, 6:16?pm, Terry Reedy wrote: > Aaron "Castironpi" Brady wrote: > >>>> class A(type): > > ... ? ? def __call__( self, *ar ): > > ... ? ? ? ? ? ? print 'call', self, ar > > ... > >>>> class B(object): > > ... ? ? __metaclass__= A > > ... > >>>> B(3) > > call (3,) > > > Overriding the __call__ method of 'type' has the effect of giving you > > a static __call__ method on a class-- a method which doesn't need an > > instance to call. ?Your behavior may be counterintuitive though, to > > someone who wants to instantiate 'B', in this case, and proceed like a > > normal object. ?That is, they want to call a generic class and use it, > > and also expect instances of B to behave as B. ?You can't have both, > > so either return B from B.__new__, or, to instantiate B, take the long > > way and call B.__new__ directly. > > >>>> B.__new__(B) > > <__main__.B object at 0x009FDB70> > > > Has anyone stepped through the C code to find out when the decision is > > made to call which function, B.__new__ or A.__call__, when B is > > called? ? > > For Python coded objects, ob(*args) in code translates to internal > execution of type(ob).__call__(ob, *args) (without further > translation!). ?The interpreter compiles a statement at a time, without > looking back to do type inferencing, and so does not know what type is > being called or if it is even callable. > > For B, B(*args) == type(B).__call__(B, *args) == A.__call__(B, *args). > So there is no decision. > > For C coded objects, I believe ob(*args) in Python code translate to a C > call of the C equivalent of type(ob).tp_call (or something like that). > ?From observation, type.tp_call acts something like this: > > def __call__(cls, *args): > ? ?if cls == type: > ? ? ?if len(*args): > ? ? ? ?return arg[0].__class__ > ? ? ?elif len(*args) == 3: > ? ? ? ?return type.__new__(type, *args) # or maybe not pass type? > ? ? ?else: > ? ? ? ?raise TypeError('type() takes 1 or 3 arguments') > ? ?else: > ? ? ?return cls.__new__(cls, *args) > > So, for a normal class C (an instance of type), type.__call__ calls > C.__new__. > > Terry Jan Reedy Oh, I see. Then it's the class statement that calls type.__new__. class A: ... -> A= type( 'A', ... ) -> A= type.__call__( type, 'A', ... ) -> A= type.__new__( type, 'A', ... ) Plus an iteration over the contents of 'namespace', to search for properties that themselves have a __get__ method. And returns an unboundmethod instance "of" it, for a value of "of" that's hard to concentrate on. I jest. Perhaps what Steven is looking for is a subclass of 'type' that does not give this default behavior of 'unboundmethoding' everything it can. That is, defaulting to 'staticmethod' or 'classmethod', and perhaps offering a 'boundmethod' decorator for the exceptions. For the case of '__call__', which he does want to control, that could merely call B.__call__, instead of B.__new__. Untested: >>> class A(type): ... def __call__( self, *ar ): ... return self.__call__( *ar ) or ... return self.__call__( self, *ar ) Which would come through to 'B' as: >>> class B(object): ... __metaclass__= A ... def __call__( cls, *ar ). This is because self == B in the example. This makes me scowl. Very odd. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 18 09:30:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 13:30:47 GMT Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <00e2520b$0$20331$c3e8da3@news.astraweb.com> On Thu, 18 Sep 2008 05:25:02 -0700, Alexzive wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a certain > geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) Here's a better version of your algorithm, one which avoids the minor inefficiencies but keeps the huge inefficiency: for node1 in IN: for node2 in IN: if node1 is not node2: if node1.coordinates == node2.coordinates: SN.append(node1.label) This assumes that node.coordinates is a type where equality is defined. If they are a tuple or list, that should work fine. But the huge inefficiency is that you are checking each node not once, not twice, but 100,000 times! So you have to iterate 10,000,000,000 times, which is going to be slow no matter what you do. Especially in pure Python. Here's a better idea: iterate over the list once only: seen = set() for node in IN: coords = tuple(node.coordinates) if coords in seen: SN.append(node.label) else: seen.add(coords) Hope this helps. -- Steven From grante at visi.com Wed Sep 10 22:36:36 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 10 Sep 2008 21:36:36 -0500 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> Message-ID: On 2008-09-10, Ben Finney wrote: > Grant Edwards writes: > >> Could whoever is responsible for the gateway that is grabbing >> my postings off of Usenet and e-mailing them out please fix the >> headers in the mail messages so that I don't get the bounce >> messages? > > The bounce messages are sent to you because you sent the > original. Wrong. I didn't send _any_ e-mail. Why should I get bounce messages? Isn't sending e-mails pretending they're from somebody else considered unethical (if not illegal)? >> Its a bit rude to send out mass e-mail messages with headers >> faked up so that the bounce messages go to somebody else. > > Indeed it is rude, and the person subscribed to the mailing > list whose software is sending these bounce messages is the > one responsible for making it stop. No, the one who's sending e-mail with forged headers is the one who ought to make it stop. That e-mail was not from me. It was from somebody who grabbed the article off a usenet server and mailed it to a bunch of people. > The mailing list software can't help (nor can the news-to-mail > gateway). > > In the meantime, the usual fix is for the list administrator > to unsubscribe the offending party (the one sending automated > bounce messages). I think the list administrator ought to stop putting other people's e-mail addresses in the From: headers of e-mails he's sending. -- Grant From m_palmer45 at yahoo.ca Tue Sep 16 16:20:03 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Tue, 16 Sep 2008 13:20:03 -0700 (PDT) Subject: find the path of a module References: <7f3f0dce-52bd-45d3-87f1-2f9aa695e080@c58g2000hsc.googlegroups.com> Message-ID: <04de9da6-059d-4eac-8672-9ef22c8a0dba@c65g2000hsa.googlegroups.com> On Sep 16, 4:07 pm, vvangelov... at gmail.com wrote: > I'd like to know if I can somehow find the path for a module somewhere > in a the package hierarchy > for instance if I import my module like so > from spam.eggs import sausage > my hypothetical method would return something like > '/home/developer/projects/spam/eggs/sausage.py/c' > given that module object. The __file__ attribute is what you want: >>> import pyPdf >>> pyPdf.__file__ '/data/python/pyPdf/__init__.pyc' >>> From steve at REMOVE-THIS-cybersource.com.au Mon Sep 29 19:26:25 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Sep 2008 23:26:25 GMT Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> Message-ID: <00f15dd2$0$20617$c3e8da3@news.astraweb.com> On Mon, 29 Sep 2008 05:41:02 -0700, George Sakkis wrote: > For example I would be much less > opposed to len() being defined as, say, |x| if "|...|" was a valid > operator. Arghh! No!!! |x| should be abs(x), not len(x). Just ask mathematicians and physicists. *wink* Actually there's a serious point there. There aren't that many unambiguous operators that are available on a standard keyboard that (nearly) everyone can agree on. -- Steven From callen314 at gmail.com Tue Sep 23 17:28:00 2008 From: callen314 at gmail.com (Craig Allen) Date: Tue, 23 Sep 2008 14:28:00 -0700 (PDT) Subject: Why are "broken iterators" broken? References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: <6eb35e11-4799-495f-8469-fd03278e97b3@o40g2000prn.googlegroups.com> I'm interested what others think of this because at first I couldn't get it... I have an object which can iterate over its parts... and at first I thought, what? I'm supposed to create a new object every time the user needs to iterate the contents? In the end I interpreted that statement as if "unless __iter__()" is called again, in which case it makes sense that an iterator should stay "finished" until it's told to start to iterate again. Then even the stream analogy holds, you don't expect a stream to say EOF then start giving you bytes (from beyond the end, I guess)... instead, such a stream would more likely block if it got to the end of available data. I'm probably being stupid in this... perhaps I'm the only one that at first interpreted the phrase as being regardless of a fresh call to __iter__()... and that the OP was worried about some other implication. But if I was wrong to think it's ok for one and the same iterator to reset when __iter__() is called again, then I seriously don't understand. what does "forever" mean in that dictum? From grante at visi.com Wed Sep 24 22:33:02 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 24 Sep 2008 21:33:02 -0500 Subject: Making small executive file for distribution References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: On 2008-09-25, Larry Bates wrote: > Marin Brkic wrote: >> Not commercial distribution, but an academic kind of sorts - giving >> the exe file to coleagues, so they can use it in their work. Giving >> .py file is not an option, since due to centralized computer >> maintenance, they don't (and cannot) have installed python (except the >> ones that bring their own computer at work, but those are an >> exception). >> >> As far as I know py2exe is the only option which can do such a thing >> (make exe files from scripts). Is there a way to make those exe files >> a little smaller (for a small script they easily go up to 5-10 mb). > Times have changed, 5-10Mb is REALLY small. Flash drives hold 4000-8000Mb > for less than $20 and standard hard drives are now 500Gb. IMHO you are > concerned about a problem that doesn't actually exist. But what if he wants to distribute his program on a floppy disk? ;) [I think only 1 of my 5 machines has a floppy drive, and the last time I tried to use it, it didn't work. I did have a usb-floppy drive somewhere, but I think somebody borrowed it a couple years ago and never returned it.] -- Grant From kaerbuhez at gmail.com Fri Sep 19 05:00:20 2008 From: kaerbuhez at gmail.com (kaer) Date: Fri, 19 Sep 2008 02:00:20 -0700 (PDT) Subject: Python newbie References: Message-ID: <07440406-96d4-406e-8a4f-11576663f5f2@k13g2000hse.googlegroups.com> On 19 sep, 10:13, Steven D'Aprano wrote: > On Fri, 19 Sep 2008 09:13:48 +0200, Mladen Gogala wrote: > > I am a Python newbie who decided to see what that Python fuss is all > > about. Quite frankly, I am a bit perplexed., here is what perplexes me: > > perl -e '@a=(1,2,3); map { $_*=2 } @a; map { print "$_\n"; } @a;' > > Naturally you will be perplexed if you assume that Python is just Perl > with a more verbose syntax. It isn't. > Indeed, it isn't ... at all: $ python -c 'for s in [2*x for x in (1, 2, 3)]: print s' 2 4 6 And it's always (a lot) more readable :-) kb From fredrik at pythonware.com Mon Sep 15 10:42:49 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 15 Sep 2008 16:42:49 +0200 Subject: Abstract class In-Reply-To: <200809151409.14149.maric@aristote.info> References: <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> <200809151409.14149.maric@aristote.info> Message-ID: Maric Michaud wrote: > But this doesn't match what abstract classes are (in C++ for example) you're confusing concepts with specific implementations of those concepts here. From neoedmund at gmail.com Fri Sep 5 07:05:44 2008 From: neoedmund at gmail.com (neoedmund) Date: Fri, 5 Sep 2008 04:05:44 -0700 (PDT) Subject: newbie question: how to run a python file if it is in a package Message-ID: for example: X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y" how can I run X.py avoiding it saying such like "ImportError: No module named aaa.bbb"? Is all runnable script must be in the default package? thanks. From steven at REMOVE.THIS.cybersource.com.au Tue Sep 2 02:56:24 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 02 Sep 2008 06:56:24 GMT Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> <878wubp5mz.fsf@benfinney.id.au> Message-ID: On Mon, 01 Sep 2008 22:11:13 -0700, Dennis Lee Bieber wrote: > On Tue, 02 Sep 2008 13:51:16 +1000, Ben Finney > declaimed the following in > comp.lang.python: > >> This is no more the case than for literal strings: >> >> a = "spam" "eggs" "ham" >> >> a = "spam", "eggs", "ham" >> > But... Literal string still have the " (or ') delimiters around the > components. Such does not exist for you example with integers. > > Consider > > a = "spam, eggs", "ham" > vs > a = "spam, eggs" "ham" Quite frankly, I think that it's a stretch to say that leaving out a tuple delimiter is a problem with whitespace inside numeric literals. That's hardly unique to whitespace: atuple = 5,6,7,8 vs atuple = 5,67,8 Look Ma, no whitespace! But even if allowing whitespace inside numeric literals did create a new avenue for errors which never existed before, it is a mistake to only consider the downside without the upside. In my opinion, that would be rather like declaring that the syntax for attribute access is a mistake because you might do this: x = MyClass() xy = 4 instead of this: x = MyClass() x.y = 4 At some point the programmer has to take responsibility for typos instead of blaming the syntax of the language. I agree that we should avoid syntax that *encourages* typos, but I don't believe that allowing whitespace inside numeric literals does that. -- Steven From dmitrey.kroshko at scipy.org Mon Sep 15 14:37:00 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Mon, 15 Sep 2008 11:37:00 -0700 (PDT) Subject: ANN: OpenOpt 0.19 (free optimization framework, Python language) Message-ID: Hello, We're pleased to announce: OpenOpt v 0.19, free (license: BSD) optimization framework (written in Python language) with connections to lots of solvers (some are C- or Fortran-written) is released. Changes since previous release 0.18 (June 15, 2008): * Some changes for NLP/NSP solver ralg (especially related to handling linear constraints Ax <= b, Aeq x = beq, lb <= x <= ub) * Bugfix for ralg and IPOPT linear constraints handling * ALGENCAN v 2.0.x has been connected (v 1.0 is no longer supported, v 2.0.3 or later is required) * Bugfix for constrained NLSP graphic output (constrained nssolve isn't turned to latest ralg version yet) * Scale parameter for lpSolve (p.scale = {False} | True | 0 | 1) * New OO class LLAVP (linear least absolute values aka linear least deviations) * Improved handling of non-linear functions with restricted dom * GLP (global) solver galileo now can handle integer problems (via p.useInteger = 1 or True) * Another one GLP (global) solver connected: pswarm * Lots of work related to oofun concept (see OO Doc page for details) * Add converters llsp2nlp, llavp2nsp * Convenient handling of maximization problems (via p.goal = 'max' or 'maximum') * Some code clean up and bugfixes Backward incompatibility: * Changed objective function in LLSP * MATLAB-style gradtol renamed to gtol (for to provide same syntax to scipy.optimize fmin_bfgs, fmin_cg and less-to-type) Newsline: http://openopt.blogspot.com/ Homepage: http://scipy.org/scipy/scikits/wiki/OpenOpt Regards, OpenOpt developers. From grante at visi.com Tue Sep 16 09:47:04 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:47:04 -0500 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: On 2008-09-16, Armin
wrote: > John Machin wrote: >> On Sep 16, 6:45 am, Armin wrote: >> >>> Yes, but this is very unconvenient. >>> If d should reference the list a extended with a single list element >>> you need at least two lines >>> >>> a.append(7) >>> d=a >>> >>> and not more intuitive d = a.append(7) >> >> Methods/functions which return a value other than the formal None and >> also mutate their environment are "a snare and a delusion". Don't wish >> for them. > > > > c = [9,10] > [1,2,3,4,7].append(c) -> Is this a valid expression? Yes. > The 'value' of that expression is None. Correct. > However ... that's the way of the implementation of the > append method. It's a little bit confusing to me ... No, that's a way of calling the append method of a list. The fact that you don't have a name bound to that list doesn't change the fact that the list is mutable and you appended [9,10] to it. -- Grant Edwards grante Yow! Are the STEWED PRUNES at still in the HAIR DRYER? visi.com From bearophileHUGS at lycos.com Sat Sep 6 17:50:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sat, 6 Sep 2008 14:50:54 -0700 (PDT) Subject: String/Number Conversion References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Andreas Hofmann, there are several problems in your code: > if type(value) is str: Better to use isinstance() and to compare it with basestring instead. > value.upper() This does nothing, python strings are immutable, so they don't get changed in-place, so you have to assign that result to some name, possibly a different name. I also suggest you to strip the uppered string, to remove head/tail spaces. Your indenting isn't much good, I suggest you to use only four spaces for each indent (you can also use one tab, but I don't suggest this). > if value.endswith('K'): > mult = 1000 > elif value.endswith('M'): > mult = 1000000 > elif value.endswith('G'): > mult = 1000000000 > else: > mult = 1 This is okay. You can also put those key-values in a dict, that you can access with the get method with a default 1, but it may be overkill. > if mult is 1: > value = string.atoi(value) > else: > value = string.atoi(value[:-1]) * mult > return value Instead of using string.atoi, use the int() builtin. If you follow my suggestions you will have a function that works in many situations. It will raise exceptions in other situations, but that's good. But to not need much of our help in your future code I suggest you to use the Python shell and test every line you write. I also suggest you to start right now using tests, for example like this: def eliminate_postfix(value): """ >>> el_post = eliminate_postfix >>> el_post(1) 1 >>> el_post("100") 100 >>> el_post("") Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '' >>> el_post("100g") 100000000000L >>> el_post("100G ") 100000000000L >>> el_post("100 G ") 100000000000L >>> el_post("100hg") Traceback (most recent call last): ... ValueError: invalid literal for int() with base 10: '100H' >>> el_post(" 100 k ") 100000 >>> el_post(" 100m") 100000000 >>> el_post(u"100m") 100000000 """ ... function code ... if __name__ == "__main__": import doctest doctest.testmod() print "Doctests done.\n" That will improve your coding a LOT, reducing your bug count, etc. Bye, bearophile From paul at boddie.org.uk Tue Sep 16 05:16:12 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 16 Sep 2008 02:16:12 -0700 (PDT) Subject: Parallelising code References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: <676c9d65-5bc7-44c4-9e61-6f7ed2b3c58c@d77g2000hsb.googlegroups.com> On 15 Sep, 18:46, "psaff... at googlemail.com" wrote: > I have some file processing code that has to deal with quite a lot of > data. I have a quad core machine, so I wondered whether I could take > advantage of some parallelism. Take a look at this page for some solutions: http://wiki.python.org/moin/ParallelProcessing In addition, Jython and IronPython provide the ability to use threads more effectively. > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? There are a few things to consider, and it is useful to see where most of the time is being spent. One interesting exercise called "Wide Finder 2", run by Tim Bray (see [1] for more details), investigated the benefits of log file processing using many concurrent processes, but it was often argued that the greatest speed-up over a naive serial implementation could be achieved by optimising the input and output and by choosing the right parsing strategy. Paul [1] http://www.tbray.org/ongoing/When/200x/2008/05/01/Wide-Finder-2 From tjreedy at udel.edu Tue Sep 16 13:54:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 13:54:45 -0400 Subject: Python GUI for animation In-Reply-To: <48CF522F.40402@it.uu.se> References: <48CF522F.40402@it.uu.se> Message-ID: Virgil Stokes wrote: > I have been using Python for a short time and I find it a very flexible > language, and easy to learn and use. I have also worked some with PyGame > and used it to create a simple animation that is controlled by the mouse > and keyboard. The animation is designed to move filled circles around on > the screen and is driven by a data file that defines (indirectly), the > next relative position of each circle. And for my purposes (queueing > demo in the classroom) this works quite well. However, I would now like > to create a Python GUI that would allow a user to control the animation, > via buttons, sliders, etc. > > I am certainly not a Python expert and have never worked with the > creation of a GUI. I would appreciate greatly any advice from those who > have worked with Python GUIs as to the best way to proceed. There have been discussions on the PyGame mailing lists about the merits of different gui options for use specifically with pygame. There may be something at the site, or archives there. News.gmane.org should also have an archive for the gmane.comp.python.pygame mirror. From gagsl-py2 at yahoo.com.ar Tue Sep 30 02:16:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 03:16:11 -0300 Subject: PID management with popen and spawn References: <73195b54-8836-43f7-ba30-76eb408ccc4a@k37g2000hsf.googlegroups.com> Message-ID: En Thu, 25 Sep 2008 12:36:00 -0300, EEK escribi?: > My goal is to start and stop separate Linux processes from a python > program by specific PID. The output of these processes needs to have > their stderr and stdout piped to a particular file, respectively. > > I've been able to make this work with subprocess.Popen only if the > shell variable is set to False but I cannot pipe the outputs of the > targets. > > When using subprocess.Popen with shell=True, I believe the returned > PID is of the shell that opens the target process, not the target > process itself. Therfore, I cannot stop the target process for the > returned PID is not of that process. Exactly. > prgm = program I want to run (compiled C) > logfile = file I want to pipe output to > > What I need to do based on a simple shell call: program >& logfile > (yes, that's it) Use the stdout and stderr arguments. Something like this (untested): f = open(logfile, "w") proc = subprocess.Popen(["program","with","arguments"], stdout=f, stderr=f) -- Gabriel Genellina From bjourne at gmail.com Wed Sep 3 08:50:57 2008 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 3 Sep 2008 14:50:57 +0200 Subject: How to write verbose scripts In-Reply-To: <001901c90e06$44e327e0$0d00a8c0@hendrik> References: <001901c90e06$44e327e0$0d00a8c0@hendrik> Message-ID: <740c3aec0809030550r446779adt3b0146a3959983e3@mail.gmail.com> 2008/9/3 Hendrik van Rooyen : > > Steven D'Aprano wrote: > >>Is there a better way of doing this than the way I am going about it? > > Not sure if its "better", but I would keep the messages in a table or dict and > have different tables or dicts for different levels of verbosity, and write a > displayer that knows about the verbosity - This approach has the advantage that > you can write in English and have different verbosities in different languages > too, if the displayer knows about the language. One big downside with that approach is that it becomes much harder to grep for the log message. Usually when I go through logs, I don't care what exactly the message says, just that it is easily googleable (uses some kind of identifying text) and that it is unique so I can know exactly where it was emitted. -- mvh Bj?rn From pavlovevidence at gmail.com Tue Sep 23 04:38:56 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 23 Sep 2008 01:38:56 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: <4960c97a-cc5e-412d-ba83-2a2d168dfa2c@a70g2000hsh.googlegroups.com> On Sep 22, 9:13?pm, process wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? The main technical difficulty is that the compiler has to know whether the function returns a tail call or not at compile time. But because Python is fully dynamic with regard to type, the compiler never(**) knows anything about any object other than "it's an object". The compiler doesn't even know if the object is callable. Probably it would be possible to achieve this optimization without involving the compiler, but it'd be at cost of great complexity and probably would negatively affect ordinary function calls (which are already slow enough). (BTW, if you're just talking about converting simple tail-recursive functions, and not about general tail-call optimization, then I'd suggest a third-party package would be better for that, since it would be a pretty complex thing that would benefit only a tiny fraction of users.) Carl Banks (**) Actually the compiler can do some compile-time constant expression folding, but that's about it. Otherwise it's object agnostic. From half.italian at gmail.com Wed Sep 10 20:21:46 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 10 Sep 2008 17:21:46 -0700 (PDT) Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... References: <276719.72706.qm@web95107.mail.in2.yahoo.com> Message-ID: <282851c6-4329-4652-bedd-b5c2384dfc14@a18g2000pra.googlegroups.com> On Sep 10, 3:33?pm, "Daniel Fetchinson" wrote: > > I know I'm tooooo late to ask you for help....but please help me out..I > > am really new to unix and dont know how to finish this assignment on > > time.....proff. said he will be using MOSS to detect whether I > > downloaded the code..please help me.. > > > email me : vaidehi.pa... at yahoo.co.in > > > Assignment 1 > > Processes, Inter-Process Communication, and Concurrency > > Due September 13th midnight > > Summary > > In > > this assignment, you will create two versions of a simple multi-process > > game : one without and another with inter-process synchronization. You > > will also measure the relative performance of the two versions of your > > multi-process game. > > Objectives > > > ? ? * Learn how to create and terminate processes. > > ? ? * Learn use of inter-process communication using shared memory, > > semaphores, signals, etc. > > ? ? * Learn the basic workings of CPU scheduling code in Linux. > > > Part A: Multi-Process Game of Turns > > > In > > this part, you are asked to write a simple program that takes two > > command-line arguments P and N. The main process creates P other child > > processes, waits for all of them to complete, and then exits. All the > > child processes form one logical ring among each other. (In rest of the > > description, the term "process" refers to a "child process".) For > > example, if the processes are numbered 1 to P, then > > > ? ? * The next neighbor of process 1 is process 2, > > ? ? * The next neighbor of process i is process i+1 for all i < P , and > > ? ? * The next neighbor of process P is process 1, which completes a ring > > among the processes. > > > Assume > > that a shared integer variable, called turn, identifies the number of > > the processes whose turn it is at any instant. A second process-local > > variable in each process, called me, identifies the identity of each > > process (i.e. each process stores its own identity in a per-process > > local variable me). A third per-process local variable, called next, > > identifies the next process in the ring. > > > The processes > > sequentially pass the turns among each other in the logical ring. When > > each process gets its turn, it increments another shared variable > > called counter. The pseudo-code within each process for passing turns > > might look something as follows. (Note: Replace turn and counter below > > with appropriate ways of accessing data within shared memory regions). > > > ? ? while(turn != me ) > > ? ? ? ? /* do nothing - just busy loop*/ ; > > > ? ? /* got my turn - increment counter */ > > ? ? counter = counter + 1; > > > ? ? /* give the turn to next process */ > > ? ? turn = next; > > > The program terminates when the each process has received N turns. > > > In the above description, several programming details have been omitted for > > you to figure out. This includes > > > ? ? * Creating P child processes from main process. > > ? ? * Constructing the logical ring among child processes. > > ? ? ? ? ? o Initializing each child process's identity in the me variable. > > ? ? ? ? ? o Initializing each child process' next neighbor in the next > > variable. > > ? ? * Initializing the shared memory region and the shared data values. > > ? ? * Have the main process wait for child processes to complete N turns > > before exiting. > > > Part B: More Efficient Game of Turns > > > You > > might notice that the program you wrote in Part A is inefficient > > because each process busy loops till the CPU scheduler kicks it out > > (after its time-slice is over) and allows another process to execute > > and make progress. (Does the program in Part A have a race condition? > > Why or why not?) > > > What we ideally want is that each process > > should be given control of the CPU only when it is that process' turn. > > Modify the program you wrote in Part A (using appropriate > > synchronization mechanisms) such that each process gets to run (i.e., > > gets control of the CPU) only when it is that process's turn, and at no > > other time. > > > Again, you would need to work out the programming details of how and where > > to use inter-process synchronization. > > Part C: Profiling the Game of Turns > > > In > > this part, you are asked to write user-level profiling code in order to > > measure the performance of the two versions of programs you wrote in > > Part A and Part B. Use a combination of gettimeofday() system call and > > inter-process synchronization to measure (1) the average hand-over time > > between two consecutive processes in the ring and (b) the total > > execution time to complete N turns. Plot the measured values as graphs > > when varying number of processes P and number of turns N. Explain the > > results you obtain. > > Submission Guidelines > > > Thanking you, > > > Ms. Vaidehi Pawar > > How much do you pay? > > Cheers, > Daniel > -- > Psss, psss, put it down! -http://www.cafepress.com/putitdown Maybe. If I cant sleep tonite. From ggpolo at gmail.com Mon Sep 1 21:34:39 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Mon, 1 Sep 2008 22:34:39 -0300 Subject: Tkinter: tkButtonDown, tkButtonEnter, tkButtonInvoke, tkButtonLeave, tkButtonUp In-Reply-To: References: <0c463182-6968-44fe-8c7f-53ba815ceeed@z11g2000prl.googlegroups.com> Message-ID: On Mon, Sep 1, 2008 at 10:09 PM, akineko wrote: > On Sep 1, 5:52 pm, "Guilherme Polo" wrote: > >> Are you trying to simulate clicks ? You should be doing it using >> event_generate, more below. >> > > Actually, I was trying to implement a "sticky" button. > (Button Release is done later by another event) > > I already tried event_generate. > It worked as far as I didn't touch other widgets. > But somehow it failed to work if event_generate is called after other > widgets are activated. > >> You should expect them to be totally removed from Tkinter actually. > > Sad to hear that. Controlling the button behaviour explicitly may not > be a common thing to do but it is still necessary thing to do. But you > gave me enough insights. This is an illusion you have, calling those methods are not the way for explicitly controlling button's behavior, not more than generating proper events. The explicit way is to not use a button, instead (ab)use Canvas. > > Aki- > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From gatti at dsdata.it Sat Sep 20 12:03:30 2008 From: gatti at dsdata.it (Lorenzo Gatti) Date: Sat, 20 Sep 2008 09:03:30 -0700 (PDT) Subject: XML-schema 'best practice' question References: <9c92e21e-6aed-4456-9b89-3949a72d15a0@f36g2000hsa.googlegroups.com> Message-ID: <9e3134c1-91ae-4c93-9f4d-1c47f8185b44@a70g2000hsh.googlegroups.com> On 20 Set, 07:59, Frank Millman wrote: > I want to introduce an element of workflow management (aka Business > Process Management) into the business/accounting system I am > developing. I used google to try to find out what the current state of > the art is. After several months of very confusing research, this is > the present situation, as best as I can figure it out. What is the state of the art of existing, working software? Can you leverage it instead of starting from scratch? For example, the existing functionality of your accounting software can be reorganized as a suite of components, web services etc. that can be embedded in workflow definitions, and/or executing a workflow engine can become a command in your application. > There is an OMG spec called BPMN, for Business Process Modeling > Notation. It provides a graphical notation [snip] > there is no standard way > of exchanging a diagram between different vendors, or of using it as > input to a workflow engine. So BPMN is mere theory. This "spec" might be a reference for evaluating actual systems, but not a standard itself. > There is an OASIS spec called WS-BPEL, for Web Services Business > Process Execution Language. It defines a language for specifying > business process behavior based on Web Services. This does have a > formal xml-based specification. However, it only covers processes > invoked via web services - it does not cover workflow-type processes > within an organisation. To try to fill this gap, a few vendors got > together and submitted a draft specification called BPEL4People. This > proposes a series of extensions to the WS-BPEL spec. It is still at > the evaluation stage. Some customers pay good money for buzzword compliance, but are you sure you want to be so bleeding edge that you care not only for WS- something specifications, but for "evaluation stage" ones? There is no need to wait for BPEL4People before designing workflow systems with human editing, approval, etc. Try looking into case studies of how BPEL is actually used in practice. > The BPMN spec includes a section which attempts to provide a mapping > between BPMN and BPEL, but the authors state that there are areas of > incompatibility, so it is not a perfect mapping. Don't worry, BPMN does not exist: there is no incompatibility. On the other hand, comparing and understanding BPMN and BPEL might reveal different purposes and weaknesses between the two systems and help you distinguish what you need, what would be cool and what is only a bad idea or a speculation. > Eventually I would like to make sense of all this, but for now I want > to focus on BPMN, and ignore BPEL. I can use wxPython to design a BPMN > diagram, but I have to invent my own method of serialising it so that > I can use it to drive the business process. For good or ill, I decided > to use xml, as it seems to offer the best chance of keeping up with > the various specifications as they evolve. If you mean to use workflow architectures to add value to your business and accounting software, your priority should be executing workflows, not editing workflow diagrams (which are a useful but unnecessary user interface layer over the actual workflow engine); making your diagrams and definitions compliant with volatile and unproven specifications should come a distant last. > I don't know if this is of any interest to anyone, but it was > therapeutic for me to try to organise my thoughts and get them down on > paper. I am not expecting any comments, but if anyone has any thoughts > to toss in, I will read them with interest. 1) There are a number of open-source or affordable workflow engines, mostly BPEL-compliant and written in Java; they should be more useful than reinventing the wheel. 2) With a good XML editor you can produce the workflow definitions, BPEL or otherwise, that your workflow engine needs, and leave the interactive diagram editor for a phase 2 that might not necessarily come; text editing might be convenient enough for your users, and for graphical output something simpler than an editor (e.g a Graphviz exporter) might be enough. 3) Maybe workflow processing can grow inside your existing accounting application without the sort of "big bang" redesign you seem to be planning; chances are that the needed objects are already in place and you only need to make workflow more explicit and add appropriate new features. Regards, Lorenzo Gatti From steve at REMOVE-THIS-cybersource.com.au Fri Sep 26 19:43:57 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 23:43:57 GMT Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> <00b839d9-fe35-4478-aba2-0435fbf285e8@m36g2000hse.googlegroups.com> Message-ID: <00ed6d83$0$20666$c3e8da3@news.astraweb.com> On Fri, 26 Sep 2008 14:54:36 -0700, Carl Banks wrote: > However, it seems from the rest of your comments that speed is your main > concern. Last time someone reported __slots__ didn't make a big > difference in access time, but it probably would speed up creating > objects a bit. Carl probably knows this already, but for the benefit of the Original Poster: __slots__ is intended as a memory optimization, not speed optimization. If it speeds up creation, that's a serendipitous side-effect of using less memory. > Of course, you should profile it to make sure. Absolutely. Can I ask the OP how large is "large" in the Large Data Sets? What seems large to people is often not large at all a modern computer. -- Steven From deets at nospam.web.de Thu Sep 18 11:31:27 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 Sep 2008 17:31:27 +0200 Subject: unicode in multi-line strings References: Message-ID: <6jfainF31rvrU1@mid.uni-berlin.de> Jiri Barton wrote: > Hello, > > I have a problem with international characters in multi-line strings. > > > Works: '''?''' > > Works: ''' > a''' > > Does not work: ''' > ?''' > > > By does not work I mean the infamous > > 'ascii' codec can't encode character u'\xe1' in position 4: ordinal not > in range(128) > > I'm using Ubuntu 8.04 with Python 2.5. It does not work in terminal, > from scripts, or from scripts with the encoding specified at the top. > Making the string unicode (u''' ... ''') does not change anything. > > It could be an interpreter issue but I didn't know where else I should > turn for help. Please show a self-contained example that does not work. The above won't puke on you as you claim - because they are simple byte-strings, and thus aren't subject to any automatic en/decoding whatsoever, unless somehow *used*. Which you don't show how you do it. Diez From castironpi at gmail.com Fri Sep 26 14:01:44 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 26 Sep 2008 11:01:44 -0700 (PDT) Subject: Building truth tables References: Message-ID: <3c615d52-fbd4-4ab3-9efe-fbadc60bf414@x41g2000hsb.googlegroups.com> On Sep 26, 11:40?am, "Tim Rowe" wrote: > 2008/9/26 andrea : > > > Well I would like to make a little program that given a certain > > logical expression gives the complete truth table. > > > It's not too difficult in fact, I just have some doubts on how to > > design it. > > > I thought something like that: > > > class Term: > > > class Table: > > > ? def and(... > > ? def or(... > > As a quick and dirty solution, I'd write a function that takes a > function as a parameter. > > Starting with a helper function to separate the bits of an integer > into a list of bools: > > def int_to_bool(i, bits): > ? ? ? ? # Extract the bits of i to a boolean array. > ? ? ? ? # 'bits' is the number of signifcant bits. > ? ? ? ? result = [] > ? ? ? ? for j in range(0, bits): > ? ? ? ? ? ? ? ? result.append(i & 1) > ? ? ? ? ? ? ? ? i >>= 1 > ? ? ? ? result.reverse() > ? ? ? ? return result > > Now I'd define a function such as: > def table(f, n): > ? ? ? ? # Calculate a truth table for function f taking n boolean parameters > ? ? ? ? result = [] > ? ? ? ? for i in range(0, math.pow(2, n)): > ? ? ? ? ? ? ? ? for j in range(0, n): > ? ? ? ? ? ? ? ? ? ? ? ? params = int_to_bool(i, n) > ? ? ? ? ? ? ? ? result.append(params + [(f(*params))]) > ? ? ? ? return result > > Now you could define the function you want as a separate function, or > just use a lambda: > > table(lambda a, b, c:(a or b) and c, 3) > [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 1, 1], [1, 0, 0, 0], > [1, 0, 1, 1], [1, 1, 0, 0], [1, 1, 1, 1]] > > Each element in the result is the state of the parameters followed by > the result of the function. > > I stress that this is quick and dirty -- I'm sure somebody will be > along with something better soon! > > -- > Tim Rowe Good idea. If you want prefixed operators: 'and( a, b )' instead of 'a and b', you'll have to write your own. ('operator.and_' is bitwise only.) It may be confusing to mix prefix with infix: 'impl( a and b, c )', so you may want to keep everything prefix, but you can still use table( f, n ) like Tim said. From fredrik at pythonware.com Wed Sep 17 09:56:31 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 15:56:31 +0200 Subject: python regex character group matches In-Reply-To: References: Message-ID: christopher taylor wrote: > my issue, is that the pattern i used was returning: > > [ '\\uAD0X', '\\u1BF3', ... ] > > when i expected: > > [ '\\uAD0X\\u1BF3', ] > > the code looks something like this: > > pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) > #print pat.findall(txt_line) > results = pat.finditer(txt_line) > > i ran the pattern through a couple of my colleagues and they were all > in agreement that my pattern should have matched correctly. First, [0-9A-F] cannot match an "X". Assuming that's a typo, your next problem is a precedence issue: (X)+ means "one or more (X)", not "one or more X inside parens". In other words, that pattern matches one or more X's and captures the last one. Assuming that you want to find runs of \uXXXX escapes, simply use non-capturing parentheses: pat = re.compile(u"(?:\\\u[0-9A-F]{4})") and use group(0) instead of group(1) to get the match. From rstarkov at gmail.com Sun Sep 14 04:02:39 2008 From: rstarkov at gmail.com (rs387) Date: Sun, 14 Sep 2008 01:02:39 -0700 (PDT) Subject: How to emit Cyrillic and Chinese via unicode from console mode? References: Message-ID: <543bde0c-4d99-4d79-a4dd-b6f8d85e8c48@l64g2000hse.googlegroups.com> On Sep 14, 2:03?am, "Siegfried Heintze" wrote: > Can someone point me to an example of a little program that emits non-ascii > Unicode characters (Russian or Chinese perhaps)? The following doesn't quite work, but I'll post it anyway since it actually ends up printing the characters. Perhaps someone can point out what causes the exception at the end? The important thing is to set the console codepage to 65001, which is UTF-8. This lets you output utf8-encoded text and see the Unicode chars displayed. import sys import encodings.utf_8 import win32console sys.stdout = encodings.utf_8.StreamWriter(sys.stdout) win32console.SetConsoleCP(65001) win32console.SetConsoleOutputCP(65001) s = "English: ok\n" s += u'Russian: \u0420\u0443\u0441\u0441\u043a\u0438\u0439\n' s += u'Greek: \u03bc\u03b5\u03b3\u03b1\u03bb\u03cd \u03c4\u03b5\u03c1\u03b7\n' print s If redirected to file, all is well, this prints everything properly in UTF-8. If ran on the console, this also prints everything correctly, but then throws a mysterious exception: English: ok Russian: ??????? Greek: ?????????? Traceback (most recent call last): File "I:\Temp\utf8console.py", line 18, in print s File "C:\Progs\Python25\lib\codecs.py", line 304, in write self.stream.write(data) IOError: [Errno 0] Error Any ideas? Roman P.S. This really ought to Just Work in this day and age, and do so without all those 65001/utf8 incantations. Pity that it doesn't. Sigh. From gminick at bzt.bzt Fri Sep 12 06:52:32 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 12 Sep 2008 10:52:32 +0000 (UTC) Subject: Better error message on recursive import References: <6isb2mF9scaU1@mid.individual.net> Message-ID: On Thu, 11 Sep 2008 12:43:34 +0200, Thomas Guettler wrote: Hello, > why does Python only raise ImportError if it fails caused by a recursive import? > > I know what's wrong. But I guess many beginner don't know what's wrong. I don't think that you're right here. I can't remember any beginner asking such a question on p.c.py. I think they would come and ask if it really was problematic. And, anyway, I don't know how to answer your question :-) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 12 06:47:48 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Sep 2008 12:47:48 +0200 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: References: <943393.38616.qm@web95111.mail.in2.yahoo.com> Message-ID: <48ca4840$0$15455$426a74cc@news.free.fr> Daniel Fetchinson a ?crit : > > >>> Thanking you, >>> >>> Ms. Vaidehi Pawar >> How much do you pay? >> >>> How much do you ask for???? >>> >>> cheers >>> Ms. Vaidehi > > I was just kidding. But if you seriously need people to do this kind > of job it's better to post the amount you are willing to pay otherwise > nobody will take it seriously. If the OP seriously need people to do his schoolwork for him, then he'd better try to learn something else. Cheating is not a solution. From antroy at gmail.com Sun Sep 21 12:23:56 2008 From: antroy at gmail.com (Ant) Date: Sun, 21 Sep 2008 09:23:56 -0700 (PDT) Subject: Problem with Python shell through Cygwin Screen (Python/Vim/Screen combo) References: <1e357c83-b53b-4587-a4d3-5327d1762341@k13g2000hse.googlegroups.com> Message-ID: <321a7ec7-db03-4665-8eff-640abf03c86a@k30g2000hse.googlegroups.com> On Sep 19, 7:08?pm, Jason Tishler wrote: ... > There are known issues when trying to run a Windows program that > directly accesses the console under Cygwin. ?For example: > > ? ?http://mail.python.org/pipermail/python-list/2004-June/266661.html > > AFAICT, you will have to use Cygwin Python with screen. Thanks for the info. Shame but - cygwin python for this setup it is (Though I may hunt for a native windows port of screen rather than the cygwin one.) Cheers, Ant. From mensanator at aol.com Thu Sep 4 21:09:49 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 4 Sep 2008 18:09:49 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> Message-ID: <618bc60e-5b1d-4eee-bd34-4fc6b0131a5f@m44g2000hsc.googlegroups.com> On Sep 4, 12:31?pm, Thomas Bellman wrote: > Mensanator wrote: > > Ok, but I don't understand why an empty list is a valid sum > > whereas a list containing None is not. > > You can't conclude the behaviour of the one from the behaviour > of the other, because the two situations have nothing at all in > common. I wouldn't say they have nothing in common. After all, neither [] nor [None,None] contain any integers, yet summing the first gives us an integer result whereas summing the second does not. Yes, for different unrelated reasons, but sometimes reasons aren't as important as results. > > >> As it happens, the SQL sum() function (at least in MySQL; I don't > >> have any other database easily available, nor any SQL standard to > >> read) does return NULL for a sum over the empty sequence, so you > >> could argue that that would be the correct behaviour for the > >> Python sum() function as well, but you can't argue that because a > >> sum *involving* a NULL value returns NULL. > > I'm not following that. Are you saying a query that returns no > > records doesn't have a specific field containg a Null so there > > are no Nulls to poison the sum? ...tap...tap...tap. Ok, I can see > > that, > > Exactly. > > > but you don't get 0 either. > > That's because the SQL sum() has a special case for "no rows > returned". ?A *different* special case than the one that taint's > the sum when encountering a NULL. ?It does the equivalent of > > ? ? if len(rows_returned) == 0: > ? ? ? ? # Special case for no rows returned > ? ? ? ? return NULL > ? ? total = 0 > ? ? for row in rows_returned: > ? ? ? ? value = row[column] > ? ? ? ? if value is NULL: > ? ? ? ? ? ? # Special case for encountering a NULL value > ? ? ? ? ? ? return NULL > ? ? ? ? total += value > ? ? return total > > Two different special cases for the two different situations. ?If > you were to remove the special case for no rows returned, you > would get zero when the SELECT statement finds no rows, but the > sum would still be tainted when a NULL value is encountered.. > > The definition of sum in mathematics *does* do away with that > special case. ?The sum of zero terms is zero. ?And the Python > sum() function follows the mathematics definition in this > respect, not the SQL definition. Too bad. I brought this up because I use Python a lot with database work and rarely for proving theorms in ZFC. Guess I have to work around it. Just one more 'gotcha' to keep track of. > > You can argue that Python sum() should have special cased the > empty sequence. ? I did. > It's not an illogical stance to take. ? I didn't think so. > It's just > a totally different issue from encountering a non-numeric element > in the sequence. ? Ok, I was paying more attention to the outcome. > In some cases it might actually make sense to > treat the empty sequence as an error, but just ignore non-numeric > elements (i.e, treat them as if they were zero). ? Ouch. Sounds like Excel and we don't want to go there. > And in some > cases both should be an error, and in some neither should be an > error. > > -- > Thomas Bellman, ? Lysator Computer Club, ? Link?ping University, ?Sweden > "You are in a twisty little passage of ? ? ? ! ?bellman @ lysator.liu.se > ?standards, all conflicting." ? ? ? ? ? ? ? ?! ?Make Love -- Nicht Wahr! From bdesth.quelquechose at free.quelquepart.fr Thu Sep 4 15:56:17 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 21:56:17 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> <48c03b91$0$14747$426a74cc@news.free.fr> Message-ID: <48c05951$0$16961$426a74cc@news.free.fr> Ivan Illarionov a ?crit : > On 4 ????, 21:49, Bruno Desthuilliers > wrote: >> Ivan Illarionov a ?crit : >> >> >> >>> On 4 ????, 22:59, Carl Banks wrote: >>>> You can write code to guard against this if you want: >>>> class A: >>>> legal = set(["x"]) >>>> def __setattr__(self,attr,val): >>>> if attr not in self.legal: >>>> raise AttributeError("A object has no attribute '%s'" % >>>> attr) >>>> self.__dict__[attr] = val >>>> def __init__(self,x): >>>> self.y = x >>>> I suspect most people who go into Python doing something like this >>>> soon abandon it when they see how rarely it actually catches anything. >>> '__slots__' is better: >> For which definition of "better" ? __slots__ are a mean to optimize >> memory usage, not to restrict dynamism. Being able to dynamically add >> arbitrary attributes is actually a feature, not a bug, and uselessly >> restricting users from doing so is not pythonic. IOW : don't do that. > > Carl's example is restricting dynamism in the same way as __slots__. > I've just suggested a better implementation. Once again : for which definition of "better" ?-) > It is not me who > suggested dynamism restriction as a way to guard against errors. My post was not targeted to you personnaly - I just wanted to make it clear for other readers that this (ab)use of slots was considered bad form. From gh at ghaering.de Tue Sep 23 08:49:21 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 23 Sep 2008 14:49:21 +0200 Subject: finding domain name In-Reply-To: References: Message-ID: Bobby Roberts wrote: > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/xxxxx/ > > where xxxxx represents the domain name. > > How can I find the domain name of the current url being viewed. Depends on the technology/web framework. If you use WSGI, you should use something like: host_name = environ.get("HTTP_HOST", None) or environ["SERVER_NAME"] -- Gerhard From hugo at hugo.com Sat Sep 13 08:16:48 2008 From: hugo at hugo.com (hugo) Date: Sat, 13 Sep 2008 14:16:48 +0200 Subject: frei sperma bilder samen sperma bilder spermaspiele sperma bilder schwarze sperma bilder sexgeschichten sperma bilder bild besamen schwester sperma schlampe schuhe besamen Message-ID: frei sperma bilder samen sperma bilder spermaspiele sperma bilder schwarze sperma bilder sexgeschichten sperma bilder bild besamen schwester sperma schlampe schuhe besamen + + + http://jhku.net/sperm/ http://jhku.net/sperm/ http://jhku.net/sperm/ http://jhku.net/sperm/ http://jhku.net/sperm/ + + + + http://www.rollyo.com/sperm_video_and_pics/sperm_cocktail_party/sperm+cockta il+party http://www.rollyo.com/sperm_video_and_pics/extrem_sperm_sluts/extrem+sperm+s luts http://www.rollyo.com/sperm_video_and_pics/sperm_shower_sluts/sperm+shower+s luts http://www.rollyo.com/sperm_video_and_pics/sperm_boobs_girls/sperm+boobs+gir ls http://www.rollyo.com/sperm_video_and_pics/www.sperm-swap.com/www.sperm-swap .com http://www.rollyo.com/sperm_video_and_pics/sperm_bukkake_girls/sperm+bukkake +girls http://www.rollyo.com/sperm_video_and_pics/www.spermswap.com/www.spermswap.c om http://www.rollyo.com/sperm_video_and_pics/geile_sperma_spiele/geile+sperma+ spiele http://www.rollyo.com/sperm_video_and_pics/sperm_fuck_babes/sperm+fuck+babes http://www.rollyo.com/sperm_video_and_pics/sperma_schlucken/sperma+schlucken http://www.rollyo.com/sperm_video_and_pics/eating_sperm_sluts/eating+sperm+s luts + + + sperma bilder galerie hund besamen meine sperma bilder scharfe sperma schlampe oma sperma schlampe schuhe besamen besamen forum sperma bilder galerie sperma bilder galerie umsonst sperma bilder kuh besamen geschichte sperma schlampe sie besamen besamen video sperma bilder seiten sperma bilder seiten arsch sperma schlampe schwarze sperma bilder ao besamen besamen video mann besamen tochter besamen http://ibm-news.for-um.de/showthread.php?t=10528 - besamen stories sperma schlampe kostenlos http://www.bebin.tv/forum/showthread.php?t=31350 - fue?e besamen schwarze sperma bilder http://ibm-news.for-um.de/showthread.php?t=11161 - sperma spiele sperma bilder galerie http://ibm-news.for-um.de/showthread.php?t=14153 - besamen lassen blank besamen http://ibm-news.for-um.de/showthread.php?t=14153 - spermadusche hund besamen http://ibm-news.for-um.de/showthread.php?t=9392 - hund besamen ehefrau fremd besamen http://ibm-news.for-um.de/showthread.php?t=15019 - oma besamen meine frau besamen http://ibm-news.for-um.de/showthread.php?t=14042 - mann besamen schweine besamen http://www.topwomen.org/forum/index.php?showtopic=94649 - sperma bilder seiten spermaspiele sperma bilder http://ibm-news.for-um.de/showthread.php?t=15569 - ggg spermaspiele dvd besamen http://ibm-news.for-um.de/showthread.php?t=11025 - samen sperma bilder sperma schlampe frau http://ibm-news.for-um.de/showthread.php?t=11007 - alle loecher besamen heisse sperma bilder http://www.gamesforum.ca/showthread.php?t=310228 - frei sperma bilder stuten besamen http://ibm-news.for-um.de/showthread.php?t=14635 - hengst besamen private sperma schlampe From bj_666 at gmx.net Tue Sep 2 09:46:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 13:46:42 GMT Subject: What is module initialization? References: Message-ID: <6i4ue2Fol29aU2@mid.uni-berlin.de> On Tue, 02 Sep 2008 14:32:30 +0100, dudeja.rajat wrote: > I found on the net that there is something called module initialization. > Unfortunately, there is not much information for this. However, small > the information I found module initialization can be of use to me in my > project. "Module initialization" is what happens when you import a module the first time. In pure Python modules the module level code is executed and in extension modules a special initializing function may be called. > However, there is one case when a module updates one such global > variable but the variable is not getting updated in the module > containing global symbols ( variables). Sounds unlikely if you *really* update the attribute of the module and not just rebind a local name that was bound to the object in the "global" module before. Example: from spam import egg egg = 42 # This does *not* change `spam.egg` but just the local binding! > Could some one provide me a sample code of module intialization? And how > can I ensure that module initialization is done only once? Module initialization is only done once, there's nothing to ensure. Ciao, Marc 'BlackJack' Rintsch From clp at rebertia.com Sun Sep 14 05:48:40 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 14 Sep 2008 02:48:40 -0700 Subject: noob: subprocess clarification In-Reply-To: <68fcdea2-804e-4fba-958e-47ecee277faf@s50g2000hsb.googlegroups.com> References: <68fcdea2-804e-4fba-958e-47ecee277faf@s50g2000hsb.googlegroups.com> Message-ID: <47c890dc0809140248i25510030g3012ecab30de3d2a@mail.gmail.com> On Sun, Sep 14, 2008 at 2:29 AM, wrote: > Hi, > > I generally use csh scripts for generally scripting (controlling > simulations). Basically the script processing options, generates the > command line, executes it and then processes the results. > > I would usually use the -f option on the shebang line to ensure that > the environment from the current shell is used. > > i.e. #!/bin/csh -f According to my copy of the csh manpage: ?f The shell ignores?/.tcshrc, and thus starts faster. So, if I understand correctly, this really just ensures that the rc file isn't run again, thus preventing any environment vars from being re-initialized and clobbered. Since Python isn't (conventionally) a unix shell, this sort of thing isn't an issue and using the current shell environment is the default behavior. You don't need to do anything special. > > How do I acheive this in python? > > I have been looking at the > > import subprocess as sub > p = sub.Popen(['echo $PATH'],shell=True).wait() > > This *seems* to do what I want (in that the path looks correct), but I > don't really understand the documentation. > > Can somebody please clarify what the shell=True does, and whether I am > using it correctly. Basically, I think it runs the command string through the shell (i.e. sh), thus causing shell syntax (e.g. $variables) to be interpreted. In this particular case, $PATH is interpolated with the value of the PATH environment variable. You can also access environment variables using os.environ, for example: import os print os.environ['PATH'] Regards, Chris > > Thanks, > > Steven > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From fredrik at pythonware.com Thu Sep 11 05:37:53 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 11:37:53 +0200 Subject: Adding environment variables to bash. In-Reply-To: <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> Message-ID: John Lawrence wrote: > You can make a command use the current shell though if you use the '.' > command e.g.: > > jl > cat env.sh > export TEST='hello' > > jl > ./env.sh && env | grep TEST #Doesn't set TEST in parent shell > jl > . ./env.sh && env | grep TEST #Adding '. ' before the > command uses the same shell > TEST=hello doesn't exactly work for Python scripts, though: $ cat env.py #!/usr/bin/env python import os os.environ["TEST"] = "hello" $ . ./env.py && env | grep TEST import: unable to open X server `'. bash: os.environ[TEST]: command not found From deets at nospam.web.de Thu Sep 25 08:19:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 Sep 2008 14:19:32 +0200 Subject: How to get the filename in the right case ? References: <6k1937F5i8kjU1@mid.uni-berlin.de> Message-ID: <6k1dukF5hk86U1@mid.uni-berlin.de> > Yes I'm pretty sure, two reasons: > 1. when I perform a step_into, jumping into a file that doesn't have > breakpoints itself (meaning my program doesn't even know of this file), > pdb returns a lowercase filename What has that to do with potential output postprocessing? > 2. rpdb2 (probably based or even inherited from pdb) has the same > behavior. Asking the writer of rpdb2, I got some excuse (which I didn't > understand) why he had done it that way. rpdb2 is not pdb. Below is the output of a Pdb-session I just had: (eggbasket)dir at client8049:~/software/vc/EggBasket$ nosetests -s eggbasket.tests.test_model 2008-09-25 14:13:10,374 turbogears.identity.saprovider INFO Loading: eggbasket.model.VisitIdentity .> /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(59)test_versionsets() -> vi1 = vset.add_pkg_info(p1) (Pdb) n > /home/dir/software/vc/EggBasket/eggbasket/tests/test_model.py(60)test_versionsets() -> session.flush() (Pdb) n As you can see - mixed-case filenames. Linux though. There is a *very* simple way for you to check: just create a file called FooBar.py and inside that, put import pdb; pdb.set_trace() print "hello" Run that on the windows shell. See if that puts out all lowercase or not. I can't do that right now as my VBox Windows won't start. Then we know if PDB is really the culprit. Apart from that, is that really a problem that the filenames are all lower case? AFAIK Windows is case-insensitive regarding filenames anyway. So opening the file by just passing the filename should work seamless. Diez From bignose+hates-spam at benfinney.id.au Sat Sep 27 04:20:17 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 18:20:17 +1000 Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> Message-ID: <8763oiuhj2.fsf@benfinney.id.au> Steven D'Aprano writes: > On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: > > An ordinary singleton is instantiating the class multiple times > > yet returning the same instance object; a class singleton is > > simply using the class directly (like a module). Where is this "class singleton" terminology from? It seems redundant to me. It also doesn't seem to have anything to do with what "singleton" means as a pattern; "using a class" is simply using a class. > Since I now no longer think I need such a beast That's a relief :-) > I'd like to be able to call [a class] as if it were a function. > Normally calling a class object returns an instance -- I wish to > return something else. In that case, you *don't* want a class at all; the entire point of a class is to define behaviour for instances. Instead, you want to define a class whose *instances* are callable, by defining the '__call__' method to do whatever it is you want. > This seems to works: > > >>> class ClassSingleton(object): > ... thing = (0, 1, 2) > ... def __new__(cls, *args): > ... return len(args+cls.thing) > ... > >>> ClassSingleton(1, 2, 4, 8, 16) > 8 Horribly obfuscatory. Calling a class should return a new instance of the class or something like it. Instead, define it so the user instantiates the class by calling the class, and *then* calls that non-class object, and so shouldn't expect to get a new instance back: >>> class CallableAppendor(object): ... thing = (0, 1, 2) ... def __call__(self, *args): ... return len(args + self.thing) ... >>> appendor = CallableAppendor() >>> appendor(1, 2, 4, 8, 16) 8 -- \ ?Pleasure's a sin, and sometimes sin's a pleasure.? ??Lord? | `\ George Gordon Noel Byron, _Don Juan_ | _o__) | Ben Finney From tchendrix at gmail.com Tue Sep 23 16:45:06 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Tue, 23 Sep 2008 13:45:06 -0700 (PDT) Subject: finding domain name References: <48d941f0$0$3738$426a74cc@news.free.fr> Message-ID: <8e874f68-838b-4fc1-8228-1787525ca780@x41g2000hsb.googlegroups.com> On Sep 23, 1:23?pm, Bruno Desthuilliers wrote: > Bobby Roberts a ?crit : > > > hi group. ?I'm new to python and need some help and hope you can > > answer this question. ?I have a situation in my code where i need to > > create a file on the server and write to it. ?That's not a problem if > > i hard code the path. ?However, the domain name needs to be dynamic so > > it is picked up automatically. ?The path to our websites is > > > home/sites/xxxxx/ > > > where xxxxx represents the domain name. > > > How can I find the domain name of the current url being viewed. > > What are you using exactly ? cgi ? wsgi ? Else ? mod python over an in-house framework written years ago without documentation so it's not the easiest thing to navigate. We will be moving to django this fall. From prologic at shortcircuit.net.au Sun Sep 21 20:12:38 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 22 Sep 2008 10:12:38 +1000 Subject: What do you call a class not intended to be instantiated In-Reply-To: <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> Message-ID: On Mon, Sep 22, 2008 at 9:39 AM, Calvin Spealman wrote: > I call it an obvious misuse and misunderstanding of why you'd use a class in > the first place. Either create an instance and not make these things > classmethods or just share the stuff in a module-level set of variables. But > the instantiating is the best options. Your class attributes might not be > globals, but you're still using global state and you should avoid it where > you can. I concur. Use a _proper_ state object that you share amongst your other objects. For instance, in many of my systems and applications I write, I often have an "Environment" instance, which is a container object that holds other objects required by parts of the system. Every other component/object in the system that is instantiated recievees exactly one instnace of thie "Environment" called, "env". Accessing shared states amongst components/objects within the system is as simple as this: class Foo(object): def __init__(self, env, *args, **kwargs): self.env = env def foo(self): if self.env.some_state: print "Do something useful" env = Environment() foo = Foo(env) foo.foo() cheers James -- -- -- "Problems are solved by method" From saluk64007 at gmail.com Sun Sep 28 20:11:50 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 28 Sep 2008 17:11:50 -0700 Subject: Not fully OO ? In-Reply-To: <48dd5dd0$0$26425$426a74cc@news.free.fr> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <48DCC786.2040407@wildenhain.de> <48dcf924$0$4653$426a74cc@news.free.fr> <00ecf4b4$0$20666$c3e8da3@news.astraweb.com> <48dd5dd0$0$26425$426a74cc@news.free.fr> Message-ID: On Fri, Sep 26, 2008 at 1:11 PM, Bruno Desthuilliers wrote: > Steven D'Aprano a ?crit : >> >> On Fri, 26 Sep 2008 17:00:59 +0200, Bruno Desthuilliers wrote: >> >>> Patrick Mullen a ?crit : >>>> >>>> Depending on the scale of the website I am making, how much I care >>>> about editing it in the future, and how much I just want to get >>>> something up, I will occasionally use php. And I am a self confessed >>>> php hater :) But it's generally the fastest way I know to get >>>> something up. So even terrible languages can have their uses! >>> >>> Sorry but I fail to see how it relates to the current thread ??? >> >> I think Patrick is responding to a comment from Tino Wildenhain: > > That didn't showed here (reading this from c.l.py via free.fr). Sorry. > >> [quote] >> Well then it still depends on the perception of "job done". For example >> PHP programmers would bet their soul that their language of choice is >> exactly the right one to "get the job done." [end quote] >> >> Patrick, you will cause much less confusion if you quote relevant parts of >> the text you are replying too. > > Indeed. At least it would have made clear (to me) there was something > missing in the thread... > -- > http://mail.python.org/mailman/listinfo/python-list Whoops, sorry for the confusion everyone. Usually I do keep the comments, don't know what happened there. From lists at cheimes.de Mon Sep 1 18:15:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 02 Sep 2008 00:15:19 +0200 Subject: encoding In-Reply-To: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> References: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> Message-ID: Gandalf wrote: > if i want to print utf-8 string i should writre: > > print u"hello word" > > but what happen if i want to print variable? u"hello world" is *not* an utf-8 encoded string. It's a unicode string. I suggest you read http://www.joelonsoftware.com/articles/Unicode.html Christian From trodemaster at gmail.com Tue Sep 9 17:30:59 2008 From: trodemaster at gmail.com (Blake Garner) Date: Tue, 9 Sep 2008 14:30:59 -0700 Subject: rss feed generation Message-ID: <55a5c7c50809091430t55a96834q37ab8301b478b04f@mail.gmail.com> I'm looking for suggestions on how to approach generating rss feed .xml files using python. What modules to people recommend I start with? Thanks! Blake From cvrebert at gmail.com Mon Sep 15 16:21:31 2008 From: cvrebert at gmail.com (Chris Rebert) Date: Mon, 15 Sep 2008 13:21:31 -0700 Subject: append on lists In-Reply-To: References: Message-ID: <47c890dc0809151321j1ef65557q1689a3b7d69b377c@mail.gmail.com> On Mon, Sep 15, 2008 at 1:24 PM, Armin wrote: > > > Hi, > > just a dumb question. > > Let a = [1,2,3,4,5] > > Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? I'll assume the presence of the 6 is a typo. Because .append() mutates 'a' and appends the item in-place rather than creating and returning a new list with the item appended, and it's good Python style for mutating methods to have no return value (since all functions must have some return value, Python uses None when the function doesn't explicitly return anything). If you print 'a' after doing the .append(), you'll see it's changed to your desired value. Regards, Chris > > --Armin > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From marco.bizzarri at gmail.com Fri Sep 5 15:24:37 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Fri, 5 Sep 2008 21:24:37 +0200 Subject: use str as variable name In-Reply-To: References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <48bf9d12$0$7552$426a74cc@news.free.fr> Message-ID: <3f0d61c40809051224r5a169b7bs62c2cc9a047642e5@mail.gmail.com> On Thu, Sep 4, 2008 at 10:47 AM, Fredrik Lundh wrote: > > (...as Bruno implies, setattr(), len() et al can be and should be viewed as > generic functions. Just a question: "generic functions" are not meant in the sense of "generic functions" of CLOS, am I right? -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From stef.mientki at gmail.com Tue Sep 30 16:18:50 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 30 Sep 2008 22:18:50 +0200 Subject: rlcompleter and wxPython, problems ... In-Reply-To: References: <48E0045A.3020402@gmail.com> <48E2789F.7090207@gmail.com> Message-ID: <48E289AA.2040205@gmail.com> Gabriel Genellina wrote: > En Tue, 30 Sep 2008 16:06:07 -0300, Stef Mientki > escribi?: > >> Gabriel Genellina wrote: >>> En Sun, 28 Sep 2008 19:25:30 -0300, Stef Mientki >>> escribi?: >>> >>>> I'm trying to implement autocompletion into my editor. >>>> But I find some weird behavior, >>>> or at least I don't have the faintest idea why this behavior >>>> occures, >>>> and even more important how to solve it >>>> In the example below I try to autocomplete " wx.s" , which in my >>>> humble opinion should at least produce "wx.stc" (and some others ). >>> >>> wx is a package. Modules within the package are not, by default, >>> attributes of the package - unless they're imported in __init__.py >>> or your code imports them. >>> So the autocompleter is doing the right thing >> in what perspective ? >> the autocompleter is only meant to assist the program writer ;-) > > It's hard to write an autocompleter that does the right thing in all > cases :) > > For a package, you have several sources for possibly valid attributes: > > - its dir() (that is, the package object's own attributes) > - the __all__ attribute, when it exists > - the list of modules inside the package directory or directories > (given by its __path__ attribute) > > Sometimes __init__.py is empty - and enumerating the modules inside > the directory is the right thing to do. Sometimes the author > explicitely imports things in __init__.py, things that comprise the > public interfase to the package. In that case I'd not like to see > "private" modules appearing in the list. > Combine with __all__, which might be defined or not. Mix all those, > choose your own autocomplete algorithm, and see what happens... > >>> - wx.stc does not exist until it is explicitely imported. >> I guess I've to study the package. >> For the moment I'll implement a user editable list of additions. >> >> But with your remarks I tried __all__ >> And now I wonder why rlcompleter is not simply using "wx.__all__", >> it than does gets all the items ? > > __all__ isn't always defined. It's only used when you do "from xxx > import *" AFAIK. > thanks Gabriel, very valuable information for me, I'll bookmark this message for later use. cheers, Setf From circularfunc at gmail.com Sun Sep 21 13:02:47 2008 From: circularfunc at gmail.com (process) Date: Sun, 21 Sep 2008 10:02:47 -0700 (PDT) Subject: I tried erlang-ish [1|2] in python and something came out... Message-ID: In erlang you can cons like this: [1|2]. i tried this in python and it didnt raise an error but i dont know what the result do >>> [1|2] [3] >>> [2|2] [2] >>> a = [2|2] >>> a [2] >>> [2|3] [3] >>> [2|1] [3] >>> From rridge at csclub.uwaterloo.ca Wed Sep 24 11:31:29 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Wed, 24 Sep 2008 11:31:29 -0400 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Presumably somebody has suggested that calling sys.exit() was a good > option. I'm curious to what possible reason they could give for such a > poor choice. Grant Edwards wrote: >Same here. It's like an automotive engine controls designer >asking if a failed O2 sensor should turn on the check engine >light or blow up the car. No, it's more like asking if the failed sensor should turn on a strange and mysterious light on the dashboard and then blow up the car if the driver doesn't immediately stop and check the engine. The owners manual would only vaguely hint at the fact that this could happen. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From tjreedy at udel.edu Tue Sep 16 13:06:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 Sep 2008 13:06:35 -0400 Subject: append on lists In-Reply-To: <200809161448.16883.maric@aristote.info> References: <1221564169.16690.0@proxy00.news.clara.net> <200809161448.16883.maric@aristote.info> Message-ID: Maric Michaud wrote: > It is, please try to understand it, in python all expressions that mutate an > object should return None, You are over-generalizing. For builtin classes, mutation methods return none. Guido recommends this as a general practice, but users may do whatever they like in their own classes. In fact, people have been told that if they do not like the built-in behavior, they should make their own, possibly by subclassing. For augmented assignment, in-place mutation followed by rebinding is explictly allowed and done for lists. > all expressions that return something, return a new object Nonesense. There is nothing in the ref manual that says this and parts that say otherwise. > there are some noticeable exceptions : They are only exceptions to your rule, not to the language specification. From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 02:45:16 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Sep 2008 06:45:16 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> Message-ID: <00edd041$0$20666$c3e8da3@news.astraweb.com> On Fri, 26 Sep 2008 22:15:43 -0700, Aahz wrote: > In article , > Steven D'Aprano wrote: >>On Thu, 25 Sep 2008 21:17:14 -0700, Aahz wrote: >>> >>> Seems to me that if all the module is used for is to store state, >>> you're wasting a file on disk. I personally prefer to use a class >>> singleton. >> >>I don't recognise the term "class singleton". Can you explain please? >>How is it different from an ordinary singleton? > > An ordinary singleton is instantiating the class multiple times yet > returning the same instance object; a class singleton is simply using > the class directly (like a module). Amazing. That's *exactly* what I was thinking of when I first asked my question. Since I now no longer think I need such a beast, this is just academic curiosity, but given a class singleton, I'd like to be able to call it as if it were a function. Normally calling a class object returns an instance -- I wish to return something else. Is that just a matter of overriding __new__? This seems to works: >>> class ClassSingleton(object): ... thing = (0, 1, 2) ... def __new__(cls, *args): ... return len(args+cls.thing) ... >>> ClassSingleton(1, 2, 4, 8, 16) 8 Is it really that easy? -- Steven From bignose+hates-spam at benfinney.id.au Tue Sep 30 18:59:09 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Oct 2008 08:59:09 +1000 Subject: Python is slow? References: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <87zllqqa1i.fsf@benfinney.id.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> Message-ID: <87ljx9qlz6.fsf@benfinney.id.au> Steven D'Aprano writes: > I simply don't think that having to run some variation on > > patch -i patchfile.patch > > is a requirement so onerous that it makes the gnuplot licence > non-free. Perhaps I'm just more tolerant of eccentricities than you > :) The distinction here is that this command must be run by *every* recipient of a modified work. A work where one must do that is more onerous for *each* recipient than one where it's already been patched for the recipient. Thus there is value, and no loss of freedom, in you as a redistributor doing that work *once* and then redistributing the work intact to any recipient. Your freedom to do this useful, harmless action is restricted artificially by copyright, and is not granted by the license. So, recipients of the 'gnuplot' code are artificially restricted from performing an action useful to society that does no harm. -- \ ?The Bermuda Triangle got tired of warm weather. It moved to | `\ Alaska. Now Santa Claus is missing.? ?Steven Wright | _o__) | Ben Finney From washakie at gmail.com Tue Sep 23 19:40:42 2008 From: washakie at gmail.com (John [H2O]) Date: Tue, 23 Sep 2008 16:40:42 -0700 (PDT) Subject: appending * to glob returns files with '*' !! In-Reply-To: References: <19579121.post@talk.nabble.com> Message-ID: <19638699.post@talk.nabble.com> No bug indeed, Erik was correct, in fact I had files with the * in the name... Thanks all for your replies! Erik Max Francis wrote: > > John [H2O] wrote: > >> I have a glob.glob search: >> >> searchstring = os.path.join('path'+'EN*') >> files = glob.glob(searchstring) >> for f in files: >> print f >> >> >> ___ >> This returns some files: >> EN082333 >> EN092334 >> EN* >> >> My routine cannot handle the '*' and it should'nt be returned anyway? :-/ >> >> A bug? > > No, it means you actually have a file named 'EN*' in the directory. > > -- > Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ > San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis > Many would be cowards if they had courage enough. > -- Thomas Fuller > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/appending-*-to-glob-returns-files-with-%27*%27-%21%21-tp19579121p19638699.html Sent from the Python - python-list mailing list archive at Nabble.com. From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 26 03:54:23 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 26 Sep 2008 09:54:23 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48db462f$0$24356$426a74cc@news.free.fr> Message-ID: <48dc952b$0$2289$426a74cc@news.free.fr> Ross Ridge a ?crit : > Bruno Desthuilliers wrote: >> Also note that there are quite a couples cases where the library authors >> themselves cannot predict which exception types may be raised - as soon >> as the library functions expect callback functions, file-like or >> dict-like or whatever-like objects etc, it's the caller's responsability >> to handle the exceptions that may be raised by what *he* passes to the >> library... > > Ug... that's another documentation pet-peeve of mine. Libraries that > say they take file-like (or whatever-like) object, but don't say exactly > how file-like it needs. Seems not to be such a problem in practice... From castironpi at gmail.com Sat Sep 13 18:14:11 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 13 Sep 2008 15:14:11 -0700 (PDT) Subject: testing if another instance of a script is already running References: Message-ID: <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> On Sep 12, 7:08?am, Strato wrote: > Hi folks, > > I want to write some kind of test to check at startup if another > instance of my script is already running. > > I don't want to handle writing of a PID file because it is too > Unix/Linux specific way to do this, and I need to keep the code to be > cross-platform. > > I think the better way to achieve this is to use some process control, > but I'm a neebie and I don't see how to do this in a safe and clean way. > > Any idea ? > > Best regards, > Strato You could use msvcrt.locking, and just lock the script file. I am not sure about this. From marco.bizzarri at gmail.com Sat Sep 13 11:41:39 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sat, 13 Sep 2008 17:41:39 +0200 Subject: Code example that will make a Skype connection? In-Reply-To: References: Message-ID: <3f0d61c40809130841i9b20846hb962cef2e77c0244@mail.gmail.com> On Sat, Sep 13, 2008 at 4:09 PM, Al Dykes wrote: > > Can some post a Python code fragment that will to make a PC with Skpye > installed to make a Skype call, given a valid phone # string. > > I'm not asking for code that handles the audio once the connection is > made. > > Maybe you can find this useful? https://developer.skype.com/wiki/Skype4Py/examples/s4p_call_py Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From uzmanajmal at gmail.com Sat Sep 13 03:32:38 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Sat, 13 Sep 2008 07:32:38 +0000 Subject: XML RPC Problem.... In-Reply-To: References: Message-ID: Please explain the arguments of send_request. What exactly are the connection, handler and request_body? It will be really helpful if you give an example of how do i call send_request On Thu, Sep 11, 2008 at 7:18 AM, Fredrik Lundh wrote: > Usman Ajmal wrote: > > And i also fount that a typical system.auth call will look like: >> >> POST /xmlrpc/clarens_server.py HTTP/1.0 >> Host: localhost >> User-Agent: xmlrpclib.py/0.9.9 (by www.pythonware.com < >> http://www.pythonware.com>) >> >> Content-Type: text/xml >> Content-Length: 105 >> AUTHORIZATION: Basic MkhVTm9VazYxbXArVEZLS0dCY2tIRlA3bjVzPQo6RnJvbSBi >> >> >> system.auth >> >> >> >> >> >> >> Problem is that i don't know how do i generate above xml system.auth call. >> Can anyone please tell me how do call a function, setting the header of the >> call too? >> > > you need to plugin a custom transport. see this page for an example: > > http://www.python.org/doc/lib/xmlrpc-client-example.html > > in your case, it should be sufficient to override send_request, e.g. > (untested): > > class SecureTransport(xmlrpclib.Transport): > > def set_authorization(self, ustring, text_ucert): > self.authoriation = encodestring( > "%s:%s" % (ustring,text_ucert) > ) > > def send_request(self, connection, handler, request_body): > connection.putrequest("POST", handler) > connection.putheader("Authorization", > "Basic %s" % self.authorization > ) > > and instantiate the transport by doing > > t = SecureTransport() > t.set_authorization(ustring, text_ucert) > > before passing to the server proxy. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bedouglas at earthlink.net Sun Sep 28 13:31:02 2008 From: bedouglas at earthlink.net (bruce) Date: Sun, 28 Sep 2008 10:31:02 -0700 Subject: parsing a site/page that uses/calls javascript functions... Message-ID: <2ff401c9218f$fc41f230$0301a8c0@tmesa.com> Hi... I've got a couple of test apps that I use to parse/test different html webpages. However, I'm now looking at how to parse a given site/page that uses javascript calls to dynamically create/display the resulting HTML. I can see the HTML is the Browser page if I manually select the btn that invokes the javascript function, but I have no idea how to create an app that can effectively parse the page. My test apps use python, along with mechanize/browser/urllib. I've seen sites/docs that discuss selenium, spidermonkey, etc... If possible, I'm trying to find a complete example (that walks through how to setup the environment, to how to finally extract the DOM elements of a given javascript page), or I'm looking to find someone I can work with, to create a complete example that can then be posted to the 'net. I'd really rather have a headless browser solution, as my overall goal is to run a parsing/crawling over a number of pages that utilize javascript.. Pointers, thoughts, comments, etc will be greatly appreciated. Thanks!!! -bruce From circularfunc at yahoo.se Tue Sep 2 16:27:06 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 2 Sep 2008 13:27:06 -0700 (PDT) Subject: Numpy/Scipy set field of matrix? Message-ID: , 'argmax', 'argmin', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getA', 'getA1', 'getH', 'getI', 'getT', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view'] >>> m matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) how do I set the field 1,2 (=6) to 45 for example? and how do I initialize a matrix and then add values in a for-loop? Im using PIL and want to store all the pixels of an image in a matrix. But I can't find the appropriate operations. From sjmachin at lexicon.net Mon Sep 8 05:20:13 2008 From: sjmachin at lexicon.net (John Machin) Date: Mon, 8 Sep 2008 02:20:13 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: On Sep 8, 10:47?am, MK Bernard wrote: > On Sep 7, 3:37?pm, John Machin wrote: > > > > > > > On Sep 8, 7:51?am, "andyh... at gmail.com" wrote: > > > > Hello... > > > > I have a dict of key/values and I want to change the keys in it, based > > > on another mapping dictionary. An example follows: > > > > MAPPING_DICT = { > > > ? ? 'a': 'A', > > > ? ? 'b': 'B', > > > > } > > > > my_dict = { > > > ? ? 'a': '1', > > > ? ? 'b': '2' > > > > } > > > > I want the finished my_dict to look like: > > > > my_dict = { > > > ? ? 'A': '1', > > > ? ? 'B': '2' > > > > } > > > > Whereby the keys in the original my_dict have been swapped out for the > > > keys mapped in MAPPING_DICT. > > > > Is there a clever way to do this, or should I loop through both, > > > essentially creating a brand new dict? > > > Is this homework? > > > There seems to be an implicit assumption in the answers so far that > > your mapping is a 1:1 mapping of all possible input keys. > > > If it doesn't include all possible input keys, answers will crash with > > a KeyError. If there are any many:1 elements in the mapping (for > > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > > in some checks for this. > > Thats exactly why I did an explicit check in my post, so as to make > sure that such a collision could not occur. It would seem that > something along what I posted would be safer, if less elegant, than > the others. I noted two problems: (1) not covering all input keys: your code explicitly sweeps this problem under the carpet, and does it laboriously ... if x in my_dict.keys(): instead of if x in my_dict: (2) not a 1:1 mapping -- for example, 'a' and 'b' both map to 'A' (the only "collision" that I can see), but you don't address that. Here's some code which attempts to cover the bases: new_dict = {} for key in my_dict: if key not in MAPPING_DICT: raise NoMapError('blah %r' % key) else: new_key = MAPPING_DICT[key] if new_key in new_dict: raise ManyToOneError('gurgle %r waffle %r' % (key, new_key)) else: new_dict[new_key] = my_dict[key] Having considered what is actually required under the checked-for conditions, one or both raise statements may be replaced by other code, and then simplified e.g. the first 4 lines in the loop may end up being replaced by new_key = MAPPING_DICT.get(key, key) as already suggested by one respondent. Note that useful use-cases for any variety of this key-change exercise may have many more items in MAPPING_DICT than there are in my_dict (a big language dictionary and a few fragments of text to be "translated"), or vice versa (a small synonym dictionary (color -> colour, center -> centre) and a big input to be "standardised") so it's a good idea to inquire which is likely to be the smaller and iterate over that if the requirements permit it. From stef.mientki at gmail.com Thu Sep 25 19:46:15 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Fri, 26 Sep 2008 01:46:15 +0200 Subject: How to get the filename in the right case ? In-Reply-To: References: <6k1dukF5hk86U1@mid.uni-berlin.de> <48DBB9C8.6090500@gmail.com> Message-ID: <48DC22C7.5020001@gmail.com> Fredrik Lundh wrote: > Stef Mientki wrote: > > > 1. I've a multitab editor. > > 2. When a breakpoint is reached, > > 3. I check if the file specified in pdb output, is already open in one > > of the editor tabs, > > 4. if not, I open a new tab with the correct file, > > 5. I focus the correct editor tab and jump to the line specified by > > pdb. > > 6. After that I should be able to inspect the surrounding of the > > breakpoint, so I need the modules name. > > > > For 3 I need to compare filenames, the editor contains the case > > sensitive name, pdb not. > > pdb uses os.path.abspath and os.path.normcase to normalize filenames > so they can be safely compared (see the canonic method in bdb.py). > > I suggest you do the same in your editor; e.g: Frederik thanks for the clarification. I don't think your suggestion is a good one. If a filename has uppercase characters in it, the END-USER has done that for some kind of reason. I as a programmer have to respect the arguments of the END-USER, (whatever they are), so I need to visualize the real filename. Secondly thoughtless copying of current behavior, doesn't bring any progress, and I think that's one of the reasons why we're still burdened by inventions done 20 years ago, e.g. "do you want to save your changes ?". cheers, Stef > > pdb_filename = ... > > for buffer in editor_buffers: > filename = os.path.normcase(os.path.abspath(buffer.filename)) > if pdb == filename: > ... found it ... > break > > > > -- > http://mail.python.org/mailman/listinfo/python-list From castironpi at gmail.com Sun Sep 21 20:44:32 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 21 Sep 2008 17:44:32 -0700 (PDT) Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <00e6cd16$0$20303$c3e8da3@news.astraweb.com> Message-ID: <9089ddd1-d74b-494f-bd5c-cffaf1a2ae37@m44g2000hsc.googlegroups.com> On Sep 21, 6:05?pm, Steven D'Aprano wrote: > Fixing top-posting. > > On Mon, 22 Sep 2008 08:54:43 +1000, James Mills wrote: > > On Mon, Sep 22, 2008 at 8:39 AM, Steven D'Aprano > > wrote: > >> I have a class which is not intended to be instantiated. Instead of > >> using the class to creating an instance and then operate on it, I use > >> the class directly, with classmethods. Essentially, the class is used > >> as a function that keeps state from one call to the next. > > [...] > > > Hi, > > > Wouldn't a normal class called State > > suffice for storing state between calls ? And ... Creating a state > > instance ? > > > For example: > > [snip] > > That's a rather big example for a rather small question. > > Yes, a normal class would work in many cases. In this case, the class > itself is being produced by a factory function, and it's output is an > iterator. Having to call: > > cls = factory() > instance = cls() > result = instance() > > to get anything done seems excessive, even if you write it as a one-liner > result = factory()()(). > > I'm not wedded to the idea, there are alternatives (perhaps the factory > should instantiate the class and return that?) but I assume others have > used this design and have a name for it. > > -- > Steven Do you want anything from it that a dictionary doesn't have, besides the dot-member access? From __peter__ at web.de Wed Sep 3 08:19:19 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 03 Sep 2008 14:19:19 +0200 Subject: converting a sed / grep / awk / . . . bash pipe line into python References: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Message-ID: Roy Smith wrote: > In article , > Peter Otten <__peter__ at web.de> wrote: > >> Without them it looks better: >> >> import sys >> for line in sys.stdin: >> try: >> a, b = map(int, line.split(None, 2)[:2]) >> except ValueError: >> pass >> else: >> if a + b == 42: >> print b > > I'm philosophically opposed to one-liners I'm not, as long as you don't /force/ the code into one line. > like: > >> a, b = map(int, line.split(None, 2)[:2]) > > because they're difficult to understand at a glance. You need to visually > parse it and work your way out from the inside to figure out what's going > on. Better to keep it longer and simpler. > > Now that I've got my head around it, I realized there's no reason to make > the split part so complicated. No reason to limit how many splits get > done > if you're explicitly going to slice the first two. And since you don't > need to supply the second argument, the first one can be defaulted as > well. So, you immediately get down to: > >> a, b = map(int, line.split()[:2]) I agree that the above is an improvement. > which isn't too bad. I might take it one step further, however, and do: > >> fields = line.split()[:2] >> a, b = map(int, fields) > > in fact, I might even get rid of the very generic, but conceptually > overkill, use of map() and just write: > >> a, b = line.split()[:2] >> a = int(a) >> b = int(b) If you go that route your next step is to introduce another try...except, one for the unpacking and another for the integer conversion... Peter From lolekk143 at wp.pl Sat Sep 20 08:58:36 2008 From: lolekk143 at wp.pl (girl) Date: Sat, 20 Sep 2008 05:58:36 -0700 (PDT) Subject: best video ladies sex +18 free! Message-ID: http://rozrywka.yeba.pl/show.php?id=3709 From jonathon.blake at gmail.com Mon Sep 8 23:22:12 2008 From: jonathon.blake at gmail.com (jonathon) Date: Mon, 8 Sep 2008 20:22:12 -0700 Subject: universal unicode font for reportlab In-Reply-To: <48C4E7A1.2000504@shopzeus.com> References: <48C4E7A1.2000504@shopzeus.com> Message-ID: On Mon, Sep 8, 2008 at 01:51, Laszlo Nagy wrote: > possible to use UTF 8 strings but there is a problem with the font. Use Code2000 http://www.code2000.net/ xan jonathon From castironpi at gmail.com Sun Sep 28 14:46:06 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 11:46:06 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> Message-ID: On Sep 28, 2:52?am, Steven D'Aprano wrote: > On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote: > > Hello all, > > > To me, this is a somewhat unintuitive behavior. ?I want to discuss the > > parts of it I don't understand. > > >>>> f= [ None ]* 10 > >>>> for n in range( 10 ): > > ... ? ? f[ n ]= lambda: n > > ... > >>>> f[0]() > > 9 > >>>> f[1]() > > 9 > > > I guess I can accept this part so far, though it took a little getting > > used to. ?I'm writing some code and found the following workaround, but > > I don't think it should give different results. ?Maybe I'm not > > understanding some of the details of closures. > > >>>> f= [ None ]* 10 > >>>> for n in range( 10 ): > > ... ? ? f[ n ]= (lambda n: ( lambda: n ) )( n ) > > ... > >>>> f[0]() > > 0 > >>>> f[1]() > > 1 > > > Which is of course the desired effect. ?Why doesn't the second one just > > look up what 'n' is when I call f[0], and return 9? > > That's an awfully complicated solution. A much easier way to get the > result you are after is to give each function its own local copy of n: > > f[n] = lambda n=n: n > > As for why the complicated version works, it may be clearer if you expand > it from a one-liner: > > # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) > > inner = lambda: n > outer = lambda n: inner > f[n] = outer(n) > > outer(0) => inner with a local scope of n=0 > outer(1) => inner with a local scope of n=1 etc. > > Then, later, when you call inner() it grabs the local scope and returns > the number you expected. > > -- > Steven Steven, I must have misunderstood. Here's my run of your code: >>> inner = lambda: n >>> outer = lambda n: inner >>> outer(0) at 0x00A01170> >>> a=outer(0) >>> b=outer(1) >>> a() Traceback (most recent call last): File "", line 1, in File "", line 1, in NameError: global name 'n' is not defined Why doesn't 'inner' know it's been used in two different scopes, and look up 'n' based on the one it's in? From wholenike at gmail.com Sun Sep 28 04:16:59 2008 From: wholenike at gmail.com (The best online shopping site!(www.wholenikee.cn)) Date: Sun, 28 Sep 2008 01:16:59 -0700 (PDT) Subject: The sale of world famous jacket,Jean-COOGI/DG/ginoshoes on Message-ID: <728a68e6-d4bc-44c2-b368-77356db4c8dc@i24g2000prf.googlegroups.com> shoes on AIR Jordan 1 (paypal payment)(www.wholejean.cn ) AIR Jordan 2 AIR Jordan 3 AIR Jordan 4 AIR Jordan 5 (paypal payment)(www.wholejean.cn ) AIR Jordan 6 Rings AIR Jordan 6 AIR Jordan 7 AIR Jordan 8 AIR Jordan 9 (paypal payment)(www.wholejean.cn ) AIR Jordan 10 AIR Jordan 11 AIR Jordan 12 AIR Jordan 13 (paypal payment)(www.wholejean.cn ) AIR Jordan 14 AIR Jordan 15 AIR Jordan 16 AIR Jordan 17 AIR Jordan 18 AIR Jordan 19 AIR Jordan 20 (paypal payment)(www.wholejean.cn ) AIR Jordan 21 AIR Jordan 22 AIR Jordan 23 (paypal payment)(www.wholejean.cn ) AIR Jordan 3.5 AIR AIR Jordan 4.5 AIR Jordan 7.5 AIR Jordan 9.5 AIR Jordan 12.5 (paypal payment)(www.wholejean.cn ) AIR Jordan 15.5 AIR Jordan 19.5 AIR Jordan 21.5 AIR Jordan Large Size Jordan AIR Jordan Size 14 Jordan AIR Jordan Size 15 shoes AIR Jordan DMP Nike air force one, air force 1, air force one low cut, air force one high cut, air force one release date Air force one, air foce one 25TH, af 1, af 1 25TH, Nike air force one new releases, limited version Air Force One (paypal payment)(www.wholejean.cn ) Air Force one 25TH AF 1 AF 1 25TH (paypal payment)(www.wholejean.cn ) Dunk sb nike sb dunk nike dunk sb dunk sb high dunk sb low dunk sb woman Nike sb dunk Nike Dunk High SB nike dunk low premuim sb Nike SB Dunk High Shimizu Nike SB Dunk Pro Nike SB Dunk Dunk SB Nike Dunk shoes Dunk shoes for woman (paypal payment)(www.wholejean.cn ) Dunk low cut Dunk high cut AIR Jordans Fusion 1 Jordan 2 Fusion AIR Jordan 3 Nike Jordan Fusion 4 Jordan 5 shoes Nike Air Jordan 6 VI Force 1 Jordan Fusion AJF 6 AJF6 AJ6F Jordan 6 Rings Jordan 6 fusion (paypal payment) (www.www.wholejean.cn ) AIR Jordan Fusions 13 NIKE Jordan Fusion 14 AIR Jordans 15Nike Jordan 16 Fusion Jordan 17 shoes Nike Air Jordans 18 XVIII Force 1 Jordan Fusion AJF18 AJF18 AJ18F Jordan 18 fusions (paypal payment)(www.wholejean.cn ) AIR Jordan Fusions 7 NIKE Jordan Fusion 8 AIR Jordans 9 Nikes Jordan Fusion 10 Jordan 11 shoes Nike Air Jordan 12 XII Force 1 Jordan Fusion AJF 12 AJF12 AJ12F Jordans 12 fusions (paypal payment)(www.wholejean.cn ) NIKE AIR JORDAN FORCE FUSION SHOES AJF 5 V JORDANs 5 FUSION NIKE JORDAN 5 FUSION SHOES AJF5 Nike Air Jordan XXIII 23 Force 1 Jordan Fusion AJF 23 AJF23 AJ23F (paypal payment)(www.wholejean.cn) Nike Jordans Fusion 23 AIR Jordan 22 Jordan Fusions 21 AIR Jordans Fusion 20 Jordan 19 shoes Air Jordan Force Fusion VIII (8), AJF 8 Nike (paypal payment)(www.wholejean.cn ) Air Jordan 17 XVII Force 1 Jordan Fusions AJF 17 AJF17 AJ17F Jordan our website : www.wholejean.cn v From fredrik at pythonware.com Wed Sep 10 03:26:20 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 09:26:20 +0200 Subject: dynamic allocation file buffer In-Reply-To: <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > You've created a solution to a problem which (probably) only affects a > very small number of people, at least judging by your use-cases. Who has > a 4GB XML file Getting 4GB XML files from, say, logging processes or databases that can render their output as XML is not that uncommon. They're usually record-oriented, and are intended to be processed as streams. And given the right tools, doing that is no harder than doing the same to a 4GB text file. From bedouglas at earthlink.net Tue Sep 2 22:39:05 2008 From: bedouglas at earthlink.net (bruce) Date: Tue, 2 Sep 2008 19:39:05 -0700 Subject: python - mechanize/browser/POST issue Message-ID: <147e01c90d6e$3c739060$0301a8c0@tmesa.com> evening... using mechanize/Browser, i can easily do a url/get, and process submitting a form that uses a GET as the action. however, I'm not quite sure how to implement the submittal of a form, that uses the POST action. Anyone have a short chunk of code that I can observer, that uses the mechanize.Browser implentation? in searching the net, i haven't found any... thanks From ToshiBoy at gmail.com Tue Sep 9 07:14:31 2008 From: ToshiBoy at gmail.com (ToshiBoy) Date: Tue, 9 Sep 2008 04:14:31 -0700 (PDT) Subject: Python Installation and Running on Windows Vista References: <4f66ca7b-b495-4b12-bb4c-29b096eb53c9@j22g2000hsf.googlegroups.com> Message-ID: <1a916f40-b54b-4a42-a441-4a9e91135f12@i24g2000prf.googlegroups.com> I don't use it often in Vista, but I haven't had any issues. Matter-of- fact, some things seem nicer in Vista... for instance it resets IDLE whenever I rerun a module. Mchizi_Crazy wrote: > Please help with issue... I heard of compatimbiltity issues and would > like clarification. From simon.palmer at gmail.com Sun Sep 7 12:22:25 2008 From: simon.palmer at gmail.com (SimonPalmer) Date: Sun, 7 Sep 2008 09:22:25 -0700 (PDT) Subject: formatting a string with thousands separators Message-ID: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> anyone recommend a way of formatting floats with comma separators? e.g. 500000.00 -> 500,000.00 From grante at visi.com Wed Sep 3 11:01:28 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 03 Sep 2008 10:01:28 -0500 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <87ej43pcy0.fsf@benfinney.id.au> <87hc8xor9g.fsf@benfinney.id.au> Message-ID: On 2008-09-03, Ben Finney wrote: > Another reason in support of spaces (rather than underscores) to > separate digit groups: it's the only separator that follows the SI > standard for representing numbers: > > ??? for numbers with many digits the digits may be divided into > groups of three by a thin space, in order to facilitate reading. > Neither dots nor commas are inserted in the spaces between groups > of three. > > > > This isn't binding upon Python, of course. However, it should > be a consideration in choosing what separator convention to > follow. I don't think that standard is applicable. It's a typesetting style guide. It also references superscripts, half-high centered dots, the "cross" multiplication symbol, the degree symbol and tons of other things which, like the thin space, can't be represented using the most common text encodings. It's quite explicit that the separator is a thin space, which one presumes would not be considered "white space" for tokenizing purposes. We don't have a thin-space, and allowing spaces within numerical literals would throw a major monkey-wrench into a lot of things (like data files whose values are separated by a single space). I suppose you could have a different format for literals in program source and for the operands to int() and float(), but that feels like a bad idea. -- Grant Edwards grante Yow! Pardon me, but do you at know what it means to be visi.com TRULY ONE with your BOOTH! From prologic at shortcircuit.net.au Thu Sep 25 18:35:56 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Fri, 26 Sep 2008 08:35:56 +1000 Subject: Not fully OO ? In-Reply-To: References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> Message-ID: On Fri, Sep 26, 2008 at 8:20 AM, Lawrence D'Oliveiro wrote: > Object orientation IS procedural. Correction: OOP is Imperative. --JamesMills -- -- -- "Problems are solved by method" From gagsl-py2 at yahoo.com.ar Tue Sep 2 16:22:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 17:22:51 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> Message-ID: En Tue, 02 Sep 2008 12:39:09 -0300, Derek Martin escribi?: > On Tue, Sep 02, 2008 at 01:57:26PM +0000, Marc 'BlackJack' Rintsch wrote: >> > I would argue that they don't represent processes at all; the object is >> > a set of files which connect the standard I/O streams of a subprocess to >> > its parent, and methods to operate on those files. >> >> And the process' ID, an attribute with the process' return code, a method >> to wait until the process is finished and file objects to communicate >> with the process. > > The name popen is an abbreviation of "pipe open" -- the function, and > the class, open pipes to communicate with another process. What you > said is correct; however there are numerous other ways to open > subprocesses. The focus of popen is the communication aspect -- the > opening and control of the pipes -- not the subprocess. That's the > key difference between popen() and all the other methods of starting a > subprocess. Totally irrelevant here - we are talking about the subprocess module, not the popen C function. >> > The C library's popen() function, on which this class is based, No, subprocess.Popen does not use -directly or indirectly- the C popen function. It uses fork or CreateProcess in Windows. > Note that in all of these links that talk about popen, the focus is on > opening pipes or file objects, not on subprocesses: > > http://www.opengroup.org/onlinepubs/009695399/functions/popen.html > http://docs.python.org/lib/os-newstreams.html > http://us3.php.net/popen > http://docs.hp.com/en/B9106-90010/popen.3S.html > http://www.faqs.org/docs/artu/ch07s02.html Again, irrelevant. > The Linux man page unfortunately copies (verbatim) the FreeBSD man > page, which gets it wrong. You can not open a process, but you can > definitely open a pipe. (Ok, if it doesn't agree with you, it must be wrong) Classes represent "things", and class names should be nouns. Functions represent "actions", and their names should be verbs. popen is a good name for a function; Popen is a bad name for a class. -- Gabriel Genellina From rridge at csclub.uwaterloo.ca Mon Sep 8 22:42:11 2008 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 08 Sep 2008 22:42:11 -0400 Subject: universal unicode font for reportlab References: <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> Message-ID: Terry Reedy wrote: >My OpenOffice on WinXP uses a unicode font, I believe Lucida Sans >Unicode, that seems to cover the entire BMP. Lucida Sans Unicode only covers a small subset of Unicode. It may seem to cover a wider range because Windows (and possibly OpenOffice) will automatically substitute characters from other fonts, if necessary. >I don't know whether it was already installed or installed by OO or >how one would get to it to extract it. It's a standard Windows font. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From ldo at geek-central.gen.new_zealand Thu Sep 25 05:20:55 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Thu, 25 Sep 2008 21:20:55 +1200 Subject: Regex Help References: Message-ID: In message , Support Desk wrote: > Thanks for the reply ... A: The vulture doesn't get Frequent Poster miles. Q: What's the difference between a top-poster and a vulture? From tjreedy at udel.edu Sat Sep 27 04:45:57 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 Sep 2008 04:45:57 -0400 Subject: Running IDLE on 3.0rc1 In-Reply-To: References: Message-ID: Allan wrote: > Terry Reedy writes: > >> I have not seen this posted, so... >> To run IDLE with Python3.0rc1, >> edit Python30/Libs/idlelib/run.py, >> and change "set_daemon(True)" to "daemon = True" and save. >> (This is about line 75, and the only appearance of 'daemon'.) >> Otherwise, you get error message about not starting a subprocess. > Is this related to the tip at the end of the built-in help file in IDLE > regarding the `-n' command option? > No, the above is a bug fix that did not make it into rc1 but has now been committed. It arose because the interface of a class in one of the modules was changed from .set_var(val) to .var = val and the need to change IDLE was not caught. I imagine that checking that IDLE runs in not in the test suite. From m_palmer45 at yahoo.ca Wed Sep 24 22:07:38 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 24 Sep 2008 19:07:38 -0700 (PDT) Subject: multiple processes, private working directories References: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> Message-ID: On Sep 24, 9:27 pm, Tim Arnold wrote: > I have a bunch of processes to run and each one needs its own working > directory. I'd also like to know when all of the processes are > finished. > > (1) First thought was threads, until I saw that os.chdir was process- > global. > (2) Next thought was fork, but I don't know how to signal when each > child is > finished. > (3) Current thought is to break the process from a method into a > external > script; call the script in separate threads. This is the only way I > can see > to give each process a separate dir (external process fixes that), and > I can > find out when each process is finished (thread fixes that). > > Am I missing something? Is there a better way? I hate to rewrite this > method > as a script since I've got a lot of object metadata that I'll have to > regenerate with each call of the script. > > thanks for any suggestions, > --Tim Arnold 1, Does the work in the different directories really have to be done concurrently? You say you'd like to know when each thread/process was finished, suggesting that they are not server processes but rather accomplish some limited task. 2. If the answer to 1. is yes: All that os.chdir gives you is an implicit global variable. Is that convenience really worth a multi- process architecture? Would it not be easier to just work with explicit path names instead? You could store the path of the per- thread working directory in an instance of threading.local - for example: >>> import threading >>> t = threading.local() >>> >>> class Worker(threading.Thread): ... def __init__(self, path): ... t.path=path ... the thread-specific value of t.path would then be available to all classes and functions running within that thread. From fredrik at pythonware.com Wed Sep 17 12:34:46 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 17 Sep 2008 18:34:46 +0200 Subject: translating ascii to binary In-Reply-To: References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> Message-ID: Lie wrote: >> Any advice about this matter would be very appreciated. >> Thanks in advance. > > It'd be easier to make a one-char version of ascii2bin then make the > string version based on the one-char version. And it'd be a lot easier to read your posts if you trimmed away at least some of the original message before posting. If you cannot do that for some technical reason, I recommend using top-posting instead. From donspauldingii at gmail.com Wed Sep 17 16:14:55 2008 From: donspauldingii at gmail.com (Don Spaulding) Date: Wed, 17 Sep 2008 13:14:55 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> Message-ID: Oh, and Google's single sign-on sucks eggs :-| From aquil.abdullah at gmail.com Fri Sep 5 15:00:41 2008 From: aquil.abdullah at gmail.com (aha) Date: Fri, 5 Sep 2008 12:00:41 -0700 (PDT) Subject: Determining Processor Vender Message-ID: <554ecfcf-96d8-4602-8d5e-ee5d70590124@i76g2000hsf.googlegroups.com> Dose anyone know of a cross-platform method for determining the vendor of a processor? Under linux I can check /proc/cpuinfo. What I'd like to be able to do is determine if a processor is AMD or Intel, so that I can use the appropriate numerical libraries for my application. Regards, Aquil From python-url at phaseit.net Tue Sep 2 17:11:06 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 2 Sep 2008 21:11:06 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 2) Message-ID: QOTW: "Information outlives technology." - Tim Bray http://www.tbray.org/ongoing/When/200x/2003/03/24/XMLisOK, but notice all the offspring of this meme any simple search makes apparent Thoughts about the various forms of the import statement: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f40481f88b5c6bf1/ Looking for an atomic increment operation: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5a60c8b393f73516/ Comparing unicode and byte strings: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c87e2912a95529f9/ Alternatives eval() in unsafe environments: http://groups.google.com/group/comp.lang.python/browse_thread/thread/908cc011e9fd9b72/ An algorithmic problem (identify where "good data" starts inside a sequence) as an excuse to post many creative solutions (including generators and even regular expressions): http://groups.google.com/group/comp.lang.python/browse_thread/thread/8979bf1b01c8233f/ Enumerating all the currently installed Python modules: http://groups.google.com/group/comp.lang.python/browse_thread/thread/4d07c1f7bdb49b94/ When to use try/except: http://groups.google.com/group/comp.lang.python/browse_thread/thread/fc867e86cc1862bf/ str.downer? str.downcase? str.lowercase is the *obvious* name, isn't it? http://groups.google.com/group/comp.lang.python/browse_thread/thread/cfd0a5f387fc82fa/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From gagsl-py2 at yahoo.com.ar Sun Sep 14 15:50:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 14 Sep 2008 16:50:30 -0300 Subject: Abstract class References: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> <48CD62B8.7070708@islandtraining.com> Message-ID: En Sun, 14 Sep 2008 16:15:04 -0300, Gary Herron escribi?: > Please forget about Abstract Base Classes. They have nothing to do with > what you want, and are a *HUGE* overkill for your application. They > are not (yet) even part of standard Python, and are used primarily for a > class implementor to guarantee to a user of a class that it provides a > specific interface. Just to say that abstract classes *are* already available in Python 2.6: Python 2.6rc1+ (trunk, Sep 13 2008, 11:29:39) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import abc >>> help(abc.abstractmethod) Help on function abstractmethod in module abc: abstractmethod(funcobj) A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... -- Gabriel Genellina From wuwei23 at gmail.com Tue Sep 2 02:12:44 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Sep 2008 23:12:44 -0700 (PDT) Subject: Getting an objetcs dict? References: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> Message-ID: <06c600d2-565b-43de-ae16-76f19f633613@b2g2000prf.googlegroups.com> On Sep 2, 4:31?am, ssecorp wrote: > X.__dict__() and ngot a dict of its variables. > > Now i get errors doing this. what am i doing wrong? The immediate problem is you're not reading the error messages. >>> X.__dict__() Traceback (most recent call last): File "", line 1, in TypeError: 'dict' object is not callable The "not callable" is the big tip-off. As it states, __dict__ is a dictionary object, -not- a method of your class. >>> X.__dict__ {'__module__': '__main__', '__doc__': None} The larger problem is you're not reading the docs & are using this list to teach you Python. Are you aware of the python-tutor list? http://mail.python.org/mailman/listinfo/tutor From maric at aristote.info Fri Sep 5 09:50:32 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 5 Sep 2008 15:50:32 +0200 Subject: Core dumped while interacting with OpenOffice.org via pyuno In-Reply-To: <3f0d61c40809050604y42bc494bqa6c91cb1cc3cd913@mail.gmail.com> References: <3f0d61c40809050604y42bc494bqa6c91cb1cc3cd913@mail.gmail.com> Message-ID: <200809051550.32439.maric@aristote.info> Le Friday 05 September 2008 15:04:22 Marco Bizzarri, vous avez ?crit?: > Hi all. > > I'm experiencing a core dump while working in the following environment > > - debain etch > - python2.3 > - openoffice.org 2.4 > - Zope 2.8.8 > > I was able to get a core dump, and the backtrace shows the following: > > Core was generated by `python2.3 tests/testActs.py'. > Program terminated with signal 11, Segmentation fault. > #0 0xb6b5219c in ?? () from /usr/lib/openoffice/program/libuno_cppu.so.3 ... lot of backtrace ... > #9 0xb68c76c7 in ?? () from /usr/lib/openoffice/program/libuno_sal.so.3 > #10 0x08797840 in ?? () > #11 0x0989b6e0 in ?? () > #12 0x00000000 in ?? () > > Now, I can understand that the information I provided are not enough > to give me suggestions on solving this issue; so, I'm asking > suggesions on investigating the issue, namely: > > - should I ask here or is it better if I ask on a openoffice forum? Yes. > - should I use a debug-enabled python in order to have more meaningful > backtraces? What you need is more a debug enabled version of pyuno libraries. > - is there something else I should do in order to have more clues > ("Read The Fine Manual (tm)" is an acceptable answer) You can try to find which function call exactly provoke the exception, the simplest way is to trace execution flow with some print statments and using non forking zope instance (runzope -d if I remember well). -- _____________ Maric Michaud From john.m.roach at gmail.com Mon Sep 15 09:04:27 2008 From: john.m.roach at gmail.com (john) Date: Mon, 15 Sep 2008 06:04:27 -0700 (PDT) Subject: catching exceptions from fortran References: Message-ID: On Sep 11, 8:23?pm, "Gabriel Genellina" wrote: > En Thu, 11 Sep 2008 10:43:08 -0300, john escribi?: > > > > > > > I wrapped some fortran code using F2PY and need to be able to catch > > fortran runtime errors to run the following: > > [reindented] > > # "grid" is a wrapped fortran module > > # no runtime errors incurred when run with the correct inputs for > > filetype > > #------------------------------- > > def readGrid( self, coord='xyz' ): > > ? mg = ( '.FALSE.', '.TRUE.' ) > > ? form = ( 'FORMATTED', 'UNFORMATTED' ) > > ? success = False > > ? for m in mg: > > ? ? for f in form: > > ? ? ? try: > > ? ? ? ? if coord == 'xyz': > > ? ? ? ? ? self.grid.readxyz( self.filename, f, m ) > > ? ? ? ? ? success = True > > ? ? ? ? elif coord == 'xyrb': > > ? ? ? ? ? self.grid.readxyrb( self.filename, f, m ) > > ? ? ? ? ? success = True > > ? ? ? ? else: > > ? ? ? ? ? import sys > > ? ? ? ? ? print 'gridtype "' + str(coord) + '" not supported. ' \ > > ? ? ? ? ? ? ? + '' > > ? ? ? except: > > ? ? ? ? continue > > ? if not success: > > ? ? import sys > > ? ? print 'gridfile "' + str(self.filename) + '" not read in any ? > > recognized format' \ > > ? ? ? ? + ' ' > > #---------------------------- > > I suppose you want to stop trying other formats after a successful read; ? > in that case put a break statement just below both success=True. > If coord is unrecognized, the code above prints the same message 4 times. ? > Instead of printing a message, in those cases usually an exception is ? > raised, letting a higher layer handle the error. And using string ? > interpolation is a lot easier than building the message in parts: > raise ValueError('gridtype "%s" not supported. ' % ? > coord) > If you want to catch errors on the Fortran code *only*, the try/except ? > should be more specific (both in scope and what it catches). The Exception ? > class is the more generic exception that you should catch. > > > basically, what i want to happen is to try to run 'something' with the > > wrapped fortran code and if that doesn't work (error encountered, > > etc.) try something else. ?is there an easier way to go about doing > > this? ?is there something i'm missing about catching exceptions here? > > I'd reorder the code in this way (untested, of course): > > def readGrid(self, coord='xyz'): > > ? ? ?def try_all_formats(read_function, filename): > ? ? ? ? ?mg = ('.FALSE.', '.TRUE.') > ? ? ? ? ?form = ('FORMATTED', 'UNFORMATTED') > ? ? ? ? ?success = False > ? ? ? ? ?for m in mg: > ? ? ? ? ? ? ?for f in form: > ? ? ? ? ? ? ? ? ?try: > ? ? ? ? ? ? ? ? ? ? ?read_function(filename, f, m) > ? ? ? ? ? ? ? ? ? ? ?success = True > ? ? ? ? ? ? ? ? ? ? ?break > ? ? ? ? ? ? ? ? ?except Exception, e: > ? ? ? ? ? ? ? ? ? ? ?# this line only for debugging purposes > ? ? ? ? ? ? ? ? ? ? ?print "error %r when using m=%r f=%r" % (e, m, f) > ? ? ? ? ? ? ? ? ? ? ?continue > ? ? ? ? ?if not success: > ? ? ? ? ? ? ?raise ValueError('gridfile "%s" not read ' > ? ? ? ? ? ? ? ? ? ? 'in any recognized format ' > ? ? ? ? ? ? ? ? ? ? '' % filename) > > ? ? ?if coord == 'xyz': > ? ? ? ? ?try_all_formats(self.grid.readxyz, self.filename) > ? ? ?elif coord == 'xyrb': > ? ? ? ? ?try_all_formats(self.grid.readxyrb, self.filename) > ? ? ?else: > ? ? ? ? ?raise ValueError('gridtype "%s" not supported. ' > ? ? ? ? ? ? ? ? ?'' % coord) > > I don't know about F2PY but the values ('.FALSE.', '.TRUE.') seem ? > suspicious. AFAIR, .FALSE. and .TRUE. are the Fortran spellings of False ? > and True in Python - they're not strings, but boolean values. So maybe the ? > right way is to use > ? ? ? ? ?mg = (False, True) > > Your code above was catching and ignoring everything, even this error, if ? > it happened. > > -- > Gabriel Genellina Gabriel, i agree with everything you write, but unless i misunderstood something, this still doesn't address the main problem of the try- except construct not preventing the program from aborting when the wrapped fortran code encounters an error. i tried hard-coding all of the passed variables to the fortran code and ran that code alone-- works. however, when an incorrect fortran read is attempted (ex. formatted read on unformatted file), the python except still fails to catch the error and the code aborts with a runtime error... From steven at REMOVE.THIS.cybersource.com.au Mon Sep 1 05:16:56 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2008 09:16:56 GMT Subject: Know if a object member is a method References: Message-ID: On Mon, 01 Sep 2008 10:43:25 +0200, Luca wrote: > Hi all. > > I think this is a newbie question... what is the best method to know if > a property of an object is a function? > > I'm thinking something as > > if type(obj.methodName)==??? > > Can someone help me? That's not quite as easy as you might think. In my testing, calling type(obj.methodName) can give any of the following: There may be others as well. Possibly all you really need is to check if the attribute is callable without caring what type of method or function it is: >>> callable(obj.methodName) True In my opinion, that's the best way. If you are sure that the method won't have side-effects or bugs: >>> try: ... obj.method() ... except: ... print "Not a method" ... (But how can you be sure?) If you insist on an explicit test, try this: import new type(obj.methodName) == new.instancemethod or alternatively: >>> isinstance(obj.methodName, new.instancemethod) True -- Steven From python.list at tim.thechases.com Tue Sep 23 10:45:12 2008 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 23 Sep 2008 09:45:12 -0500 Subject: improving a huge double-for cycle In-Reply-To: References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48D2502C.4000200@tim.thechases.com> Message-ID: <48D900F8.10506@tim.thechases.com> km wrote: > how abt this ? > > N = len(IN) > for k in range(N): > for j in range(N): > if j >= k: # or k <= j > doSomething() This has the root problem that the "if" statement is evaluated N*N times, which is ugly/slow O(N^2) behavior. My solution managed to reduce it by a constant multiplier, but several folks proposed a more elegant O(N) solution which was leaps & bounds faster. -tkc From aweraw at gmail.com Tue Sep 30 03:50:27 2008 From: aweraw at gmail.com (Aidan) Date: Tue, 30 Sep 2008 17:50:27 +1000 Subject: Python arrays and sting formatting options In-Reply-To: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> Message-ID: <48e1da44@dnews.tpgi.com.au> Ivan Reborin wrote: > Hello everyone, > > I was wondering if anyone here has a moment of time to help me with 2 > things that have been bugging me. > > 1. Multi dimensional arrays - how do you load them in python > For example, if I had: > ------- > 1 2 3 > 4 5 6 > 7 8 9 > > 10 11 12 > 13 14 15 > 16 17 18 > ------- > with "i" being the row number, "j" the column number, and "k" the .. > uhmm, well, the "group" number, how would you load this ? > > If fortran90 you would just do: > > do 10 k=1,2 > do 20 i=1,3 > > read(*,*)(a(i,j,k),j=1,3) > > 20 continue > 10 continue > > How would the python equivalent go ? > > 2. I've read the help on the next one but I just find it difficult > understanding it. > I have; > a=2.000001 > b=123456.789 > c=1234.0001 > > How do you print them with the same number of decimals ? > (eg. 2.000, 123456.789, 1234.000) > and how do you print them with the same number of significant > decimals? > (eg. 2.000001, 123456.7, 1234.000 - always 8 decimals) ? > > > Is something like this possible (built-in) in python ? > > Really grateful for all the help and time you can spare. > > -- > Ivan I'm not sure if this is applicable to your multi-dimensional list problem... but it sounded a bit sudoku like (with row, columns and groups) so I thought I'd share a bit of code of developed in regards to solving sudoku puzzles... Given a list of 9 list elements, each with nine elements (lets call it sudoku_grid), the following list comprehensions produce lists of indexes into sudoku grid vgroups = [[(x,y) for y in xrange(9)] for x in xrange(9)] hgroups = [[(x,y) for x in xrange(9)] for y in xrange(9)] lgroups = [[(x,y) for x in xrange(a,a+3) for y in xrange(b,b+3)] for a in xrange(0,9,3) for b in xrange(0,9,3)] where sudoku_grid[y][x] yields the value at position (x,y), assuming the top left corner is indexed as (0,0) HTH From castironpi at gmail.com Tue Sep 2 14:33:37 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 2 Sep 2008 11:33:37 -0700 (PDT) Subject: rope class (heavyweight string) Message-ID: Does anyone want to talk about a Rope implementation in Python? It doesn't get faster than the native strings until about 2 megs. P.S. Didn't your momma ever tell you not to talk on newsgroups? From gklein at xs4all.nl Sun Sep 14 06:51:35 2008 From: gklein at xs4all.nl (Gertjan Klein) Date: Sun, 14 Sep 2008 12:51:35 +0200 Subject: How to emit Cyrillic and Chinese via unicode from console mode? References: <543bde0c-4d99-4d79-a4dd-b6f8d85e8c48@l64g2000hse.googlegroups.com> Message-ID: <2vqpc4pd7qfrsgsove5f5prncbglhjast0@4ax.com> rs387 wrote: >sys.stdout = encodings.utf_8.StreamWriter(sys.stdout) > >win32console.SetConsoleCP(65001) >win32console.SetConsoleOutputCP(65001) [...] >If redirected to file, all is well, this prints everything properly in >UTF-8. If ran on the console, this also prints everything correctly, >but then throws a mysterious exception: Interesting. On my system (Windows XP) the console codepage does not change, and hence the characters don't print properly (I get some of the CP437 line drawing characters, for example). I have never been able to convince windows to assume/support UTF-8 encoding in the console, programatically or otherwise. :( Gertjan. -- Gertjan Klein From kaiser.vocote at gmail.com Tue Sep 16 07:30:41 2008 From: kaiser.vocote at gmail.com (Andreas Kaiser) Date: Tue, 16 Sep 2008 04:30:41 -0700 (PDT) Subject: What is "finally:" for? References: Message-ID: On 16 Sep., 13:25, "Max Ivanov" wrote: > Hi all! > When and where I should use try-except-finally statement? What is the > difference between: > -------- > try: > ? A... > except: > ? B.... > finally: > ? C... > -------- It does A if no exception or B if an exception occurs. THEN it does always C. > > and > ------- > try: > ? A... > except: > ? B.... > C... If an exception occurs, C is never reaching. Andreas From metallourlante at gmail.com Sun Sep 21 08:51:13 2008 From: metallourlante at gmail.com (Alex) Date: Sun, 21 Sep 2008 05:51:13 -0700 (PDT) Subject: understanding list scope Message-ID: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> Hi all! I have a problem understanding the behaviour of this snippet: data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) for i in range(len(data_set)): ds = data_set[:] data = ds[i] if i == 1: data['param'] = "y" if i == 2: data['param'] = "x" print data_set This script print out: ({'param': 'a'}, {'param': 'y'}, {'param': 'x'}) Why? I'm coping data_set in ds so why data_set is changed? Thanks in advance. Alex From steven at REMOVE.THIS.cybersource.com.au Fri Sep 12 02:30:42 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 12 Sep 2008 06:30:42 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> <5bc6eeb8-650b-4b8d-9041-3883282b63a5@y21g2000hsf.googlegroups.com> <9ISdnQocUaksnVfVnZ2dnUVZ_szinZ2d@earthlink.com> Message-ID: On Thu, 11 Sep 2008 22:40:01 -0700, Dennis Lee Bieber wrote: > On 12 Sep 2008 03:37:51 GMT, Steven D'Aprano > declaimed the following in > comp.lang.python: > > >> I'm pretty sure you're wrong. XML can be used for serialization, but >> that doesn't mean it is only sequential data. XML is suitable for >> hierarchical data too. To quote Wikipedia: >> > There is a difference between the format of the data content, and > the processing of that data... Regardless of the content, one > essentially has to process the XML /file/ sequentially, and translate > into an in-memory model that allows for accessing said data. To reach > the nth subelement of the mth element requires reading all 1..m-1 > elements, followed by all 1..n-1 subelements in m. Modifying any element > requires rewriting the entire file. Which is why I previously said that XML was not well suited for random access. I think we're starting to be sucked into a vortex of obtuse and opaque communication. We agree that XML can store hierarchical data, and that it has to be read and written sequentially, and that whatever the merits of castironpi's software, his original use-case of random access to a 4GB XML file isn't workable. Yes? -- Steven From To-Email-Use-The-Envelope-Icon at My-Web-Site.com Sat Sep 27 18:56:39 2008 From: To-Email-Use-The-Envelope-Icon at My-Web-Site.com (Jim Thompson) Date: Sat, 27 Sep 2008 15:56:39 -0700 Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> Message-ID: <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> On Sat, 27 Sep 2008 18:47:16 -0400, default wrote: >On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko > wrote: > >>Hello, this is Milenko Stojadinovic from town Banjaluka, >>Bosnia and Herzegovina, also known as Cvrcko >>Does anyone know of any bars in town where I can >>swallow a bucket of cum? It can be either dog, >>horse or human cum. Also, does anyone know of >>any sex bars where people will shit in your mouth? >>I also like eating shit. > >Come to the US and park your mouth in front of George Bush - all the >Bshit you can eat - and it keeps on coming! > >I have a buddy in Bosna - he's normal. Now you know why I blanket kill-file googlegroups. ...Jim Thompson -- | James E.Thompson, P.E. | mens | | Analog Innovations, Inc. | et | | Analog/Mixed-Signal ASIC's and Discrete Systems | manus | | Phoenix, Arizona 85048 Skype: Contacts Only | | | Voice:(480)460-2350 Fax: Available upon request | Brass Rat | | E-mail Icon at http://www.analog-innovations.com | 1962 | Viewed from afar, even whores and Democrats seem reputable From lists at cheimes.de Sun Sep 28 14:39:05 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 28 Sep 2008 20:39:05 +0200 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: process wrote: > What is not an object in Python? Everything that is not part of Python's syntax is an object, including all string and number types, classes, metaclasses, functions, models, code and more. It's technically not possible to have something like e.g. an int that isn't an object. > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? Because readability is more important than purity. By the way len(egg) is just syntactic sugar for egg.__len__() with some extra checks. From dstromberglists at gmail.com Mon Sep 22 18:49:40 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Mon, 22 Sep 2008 22:49:40 GMT Subject: looper Message-ID: <8iVBk.1045$x%.476@nlpi070.nbdc.sbc.com> I was asked by my employer to publish this a bit ago, so here it is: http://stromberg.dnsalias.org/~dstromberg/looper/ It's a multithreaded script for running n POSIX shell commands m at a time with good error checking. It allows for things like stashing in ssh $hostname or rsync $hostname in a convenient way - with pretty complete shell quoting so that your command comes out on the other side of the ssh command the same way it went into looper. It also allow I hope someone finds it useful. I know I have. Followups have been directed to comp.unix.shell. From mobiledreamers at gmail.com Mon Sep 22 19:00:43 2008 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Mon, 22 Sep 2008 16:00:43 -0700 Subject: looper In-Reply-To: <8iVBk.1045$x%.476@nlpi070.nbdc.sbc.com> References: <8iVBk.1045$x%.476@nlpi070.nbdc.sbc.com> Message-ID: Great thanks On 9/22/08, Dan Stromberg wrote: > > > I was asked by my employer to publish this a bit ago, so here it is: > > http://stromberg.dnsalias.org/~dstromberg/looper/ > > It's a multithreaded script for running n POSIX shell commands m at a > time with good error checking. It allows for things like stashing in ssh > $hostname or rsync $hostname in a convenient way - with pretty complete > shell quoting so that your command comes out on the other side of the ssh > command the same way it went into looper. It also allow > > I hope someone finds it useful. I know I have. > > Followups have been directed to comp.unix.shell. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://gpirate.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Mon Sep 22 05:07:43 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 09:07:43 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> Message-ID: On Mon, 22 Sep 2008 10:12:38 +1000, James Mills wrote: > On Mon, Sep 22, 2008 at 9:39 AM, Calvin Spealman > wrote: >> I call it an obvious misuse and misunderstanding of why you'd use a >> class in the first place. Either create an instance and not make these >> things classmethods or just share the stuff in a module-level set of >> variables. But the instantiating is the best options. Your class >> attributes might not be globals, but you're still using global state >> and you should avoid it where you can. > > I concur. Use a _proper_ state object that you share amongst your other > objects. But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. I'm not trying for a Borg or Singleton: the user can call the factory as many times as they want, but the objects returned shouldn't share any state. I don't know if what I want has a name. Judging from people's reactions, I'd say probably not. (For the pedantic: the "instances" will all have the same methods, but I'm not including methods as state.) > For instance, in many of my systems and applications I write, I > often have an "Environment" instance, which is a container object that > holds other objects required by parts of the system. Every other > component/object in the system that is instantiated recievees exactly > one instnace of thie "Environment" called, "env". > > Accessing shared states amongst components/objects within the system is > as simple as this: > > class Foo(object): > > def __init__(self, env, *args, **kwargs): > self.env = env > > def foo(self): > if self.env.some_state: > print "Do something useful" Seems wasteful to me. Why give every instance it's own instance-level reference to the shared object? Why not make env a class attribute, set once, instead of every time you instantiate the class? class Foo(object): env = env But in any case, this is not the behaviour I want. It's the opposite of the behaviour I want. I don't want the objects to share state. I'm not exactly sure what I said that has given so many people the impression that I do. -- Steven From circularfunc at yahoo.se Tue Sep 16 17:24:49 2008 From: circularfunc at yahoo.se (cnb) Date: Tue, 16 Sep 2008 14:24:49 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <8145020f-080e-4d7a-8361-f5b0865a1197@m44g2000hsc.googlegroups.com> Message-ID: <99c53e1a-a693-4f35-b937-d172c565077c@m36g2000hse.googlegroups.com> On Sep 16, 10:53?pm, "Aaron \"Castironpi\" Brady" wrote: > On Sep 16, 3:16?pm, cnb wrote: > > > > > On Sep 16, 7:49?pm, "Aaron \"Castironpi\" Brady" > > > > Now I have my personal programs in C:/Python25/Progs/ > > > > > How do I add so that I can just do "import somefile" from anywhere in > > > > that directory in the interpreter and it can load files from other > > > > folders in that directory. > > > > Add a file: \Lib\site-packages\locals.pth > > > > with contents, path to the directory you want to add (/python25/progs/) > > > And we have a winner! > > > Now it works. Both doing import and loading form fiel with C-c C-l > > > However jsut including C:/Python/Progs wasn't enough. I had to add the > > folder inside that that contains the files i needed. > > > so how do i add all files within progs? is there something like C:/ > > python25/progs/* ? > > You have: > > c:/python/progs/abc/filea.py > c:/python/progs/abc/fileb.py > c:/python/progs/def/filed.py > c:/python/progs/def/filee.py > > __init__.py in progs ? (empty...) > __init__.py in abc > __init__.py in def > > c:/python/site-packages/lib/locals.py ?which contains: > c:/python/progs/ > > You don't need the subdirectories. ?You can do: > > import abc > import abc.filea > from abc import filea no I can't... From Richard_Martineau at xyratex.com Tue Sep 16 08:52:10 2008 From: Richard_Martineau at xyratex.com (Richard_Martineau at xyratex.com) Date: Tue, 16 Sep 2008 05:52:10 -0700 (PDT) Subject: Build Python, Numpy and Scipy source with Visual Studio 6.0 for windows References: <25767aa9-c078-4e43-85fe-4601343bea43@f63g2000hsf.googlegroups.com> Message-ID: On Sep 16, 11:02?am, "Gabriel Genellina" wrote: > En Tue, 16 Sep 2008 06:25:27 -0300, ? > escribi?: > > > I wonder if anyone can advise me or has done similar to the following? > > > Basically I've downloaded the Python 2.5.2 source code that builds > > with Visual Studio 6.0. I've built Python for windows. This was easy > > (it even came with the pcbuild.dsw workspace file). Great! > > > Now comes the troubled bit...I now look for similar source code for > > Python extensions Numpy and Scipy but the source code and directories > > are not all obvious. Looks like these are normally built via other > > compilers. However I need to do all my builds in VS 6.0. > > > For Numpy (I haven't got as far as Scipy yet) I've organised the > > source code into the following projects and lumped them all into my > > new workspace numpy.dsw: > > Don't try to roll your own projects, compile it using distutils instead. ? > Distutils takes care of defining the right symbols and compiler options, ? > and should detect VS. > I'm pretty sure the Numpy README file (or similar) describes how to build ? > it; usually you install the required dependencies and then run: > python setup.py build > > -- > Gabriel Genellina Thanks for your message. Unfortunately I need as much control and visibility as possible as I eventually want to port from windows os to pharlap rtos. I appreciate your advice and I understand it's not a great idea to roll your own, but if it's possible, I really need to do so. Any further help/advice greatly appreciated Richard From wuwei23 at gmail.com Tue Sep 9 20:35:00 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 9 Sep 2008 17:35:00 -0700 (PDT) Subject: rss feed generation References: Message-ID: <422f8090-7cca-4cf9-992a-a840fa453224@a18g2000pra.googlegroups.com> On Sep 10, 7:30?am, "Blake Garner" wrote: > I'm looking for suggestions on how to approach generating rss feed > .xml files using python. What modules to people recommend I start > with? http://www.dalkescientific.com/Python/PyRSS2Gen.html From grante at visi.com Tue Sep 16 09:54:39 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 16 Sep 2008 08:54:39 -0500 Subject: append on lists References: <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> Message-ID: On 2008-09-16, Armin wrote: > Duncan Booth wrote: >> "Chris Rebert" wrote: >>> On Tue, Sep 16, 2008 at 1:20 AM, Armin wrote: >>>> [1,2,3,4,7].append(c) -> Is this a valid expression? >>> Literally, no, because you can't call methods on literals. >> >> Rubbish. There is no restriction about calling methods on literals. That >> expression is perfectly valid but has no practical use that I can see. > > The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > (with c = [8,9]) is identical, No, they're not: >>> a=[1,2,3,4,7] >>> c=[9,10] >>> a.append(c) >>> a [1, 2, 3, 4, 7, [9, 10]] >>> a=[1,2,3,4,7] >>> c=[9,10] >>> a+c [1, 2, 3, 4, 7, 9, 10] You really ought to install a copy of Python so you can try out things and see how they really work. > but the first expression doesn't provide a value. Strange by > design ... Not really. You just need to make a little effort to understand the reasoning (which has been explained to you) behind Python's design decision. -- Grant Edwards grante Yow! Somewhere in DOWNTOWN at BURBANK a prostitute is visi.com OVERCOOKING a LAMB CHOP!! From steven at REMOVE.THIS.cybersource.com.au Thu Sep 11 05:05:47 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Sep 2008 09:05:47 GMT Subject: dict slice in python (translating perl to python) References: Message-ID: On Thu, 11 Sep 2008 03:36:35 -0500, Nick Craig-Wood wrote: > As an ex-perl programmer and having used python for some years now, I'd > type the explicit > > v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > > Or maybe even > > v1 = mydict['one'] # 54 chars > v2 = mydict['two'] > v3 = mydict['two'] > > Either is only a couple more characters to type. But that's an accident of the name you have used. Consider: v1,v2,v3 = section_heading_to_table_index['one'], \ section_heading_to_table_index['two'], \ section_heading_to_table_index['two'] # 133 characters versus: v1,v2,v3 = [section_heading_to_table_index[k] for k in ['one','two','two']] # 75 characters It also fails the "Don't Repeat Yourself" principle, and it completely fails to scale beyond a handful of keys. Out of interest, on my PC at least the list comp version is significantly slower than the explicit assignments. So it is a micro-optimization that may be worth considering if needed -- but at the cost of harder to maintain code. > It is completely > explicit and comprehensible to everyone, in comparison to > > v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars > v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars That's a matter for argument. I find the list comprehension perfectly readable and comprehensible, and in fact I had to read your explicit assignments twice to be sure I hadn't missed something. But I accept that if you aren't used to list comps, they might look a little odd. -- Steven From dmitry at athabascau.ca Wed Sep 24 18:21:01 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Wed, 24 Sep 2008 22:21:01 GMT Subject: is decorator the right thing to use? Message-ID: Hi, after hearing a lot about decorators and never actually using one I have decided to give it a try. My particular usecase is that I have class that acts as a proxy to other classes (i.e. passes messages along to those classes) however hand-coding this type of class is rather tedious, so I decided to use decorator for that. Can somebody tell me if what I'm doing is a potential shot-in-the-foot or am I on the right track? (Note, It's rather rudimentary proof-of-concept implementation and not the final solution I'm about to employ so there are no optimizations or signature-preserving code there yet, just the idea). Here's the code: class A: b=None def __init__(self,b): self.val='aval' self.b=b b.val='aval' def mymethod(self,a): print "A::mymethod, ",a def mymethod2(self,a): print "A::another method, ",a def Aproxy(fn): def delegate(*args,**kw): print "%s::%s" % (args[0].__class__.__name__,fn.__name__) args=list(args) b=getattr(args[0],'b') fnew=getattr(b,fn.__name__) # get rid of original object reference del args[0] fnew(*args,**kw) setattr(A,fn.__name__,delegate) return fn class B: def __init__(self): self.val='bval' @Aproxy def bmethod(self,a): print "B::bmethod" print a, self.val @Aproxy def bmethod2(self,a): print "B::bmethod2" print a, self.val b=B() b.bmethod('foo') a=A(b) b=B() b.val='newval' a.bmethod('bar') a.bmethod2('zam') From electronixtar at gmail.com Sun Sep 28 01:37:09 2008 From: electronixtar at gmail.com (est) Date: Sat, 27 Sep 2008 22:37:09 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! Message-ID: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> >From python manual str( [object]) Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''. now we try this under windows: >>> str(u'\ue863') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in position 0 : ordinal not in range(128) FAIL. also almighty Linux Python 2.3.4 (#1, Feb 6 2006, 10:38:46) [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> str(u'\ue863') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in position 0: ordinal not in range(128) Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> str(u'\ue863') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in position 0: ordinal not in range(128) Python 2.5 (release25-maint, Jul 20 2008, 20:47:25) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> str(u'\ue863') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in position 0: ordinal not in range(128) The problem is, why the f**k set ASCII encoding to range(128) ???????? while str() is internally byte array it should be handled in range(256) !!!!!!!!!! http://bugs.python.org/issue3648 One possible solution(Windows Only) >>> str(u'\ue863'.encode('mbcs')) '\xfe\x9f' >>> print u'\ue863'.encode('mbcs') ?? I now spending 60% of my developing time dealing with ASCII range(128) errors. It was PAIN!!!!!! Please fix this issue. http://bugs.python.org/issue3648 Please. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 10:40:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 16:40:42 +0200 Subject: Eleganz way to get rid of \n In-Reply-To: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> References: <48bbed2f$0$11110$8e6e7893@newsreader.ewetel.de> Message-ID: <48bbfe96$0$16237$426a74cc@news.free.fr> Hans M?ller a ?crit : > Hello, > > I'm quite often using this construct: > > for l in open("file", "r"): > do something > > here, l contains the \n or \r\n on windows at the end. > I get rid of it this way: > > for l in open("file", "r"): > while l[-1] in "\r\n": > l = l[:-1] > > I find this a little bit clumsy, indeed. > but it works fine. > > Has someone a better solution ? help(str.rstrip) From circularfunc at gmail.com Tue Sep 2 19:44:02 2008 From: circularfunc at gmail.com (ssecorp) Date: Tue, 2 Sep 2008 16:44:02 -0700 (PDT) Subject: Is try-except slow? Message-ID: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> or why does this take so god damn long time? and if I run into an IndexError it break out of the inner loop right? so having range up to 10000000 or 1000 wouldn't matter if biggest working x is 800? def getPixels(fileName): im = PIL.Image.open(fileName) colors = [] for y in range(1, 1000): row = [] for x in range(1, 1000): try: color = im.getpixel((x,y)) row.append(color) except IndexError: break colors.append(row) return numpy.array(colors) From marco.bizzarri at gmail.com Tue Sep 16 08:47:02 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Tue, 16 Sep 2008 14:47:02 +0200 Subject: MVC with Python In-Reply-To: References: <3f0d61c40809151307p76c864e5he9911593b676548e@mail.gmail.com> Message-ID: <3f0d61c40809160547t339226acx19a7a0a0f58a6e73@mail.gmail.com> On Tue, Sep 16, 2008 at 1:26 PM, Georg Altmann wrote: > Marco Bizzarri schrieb: >> >> On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann >> wrote: >>> >>> Hello, >>> >>> I need some advice on how to implement model-view-controller. I am trying >>> to >>> develop a GUI application with PyQt, yet the problem rather applies to >>> mvc >>> in general, not just GUI applications. >>> >>> Let's say the data is a list of objects with a common base class. The >>> views >>> are either a graphical representation of the objects or some form of >>> textual >>> input. The views shall change the model by using command objects (for >>> undo, >>> e.g. QUndoCommand). >>> >>> My current approach is to implement the model as a class with a list-like >>> interface, with methods insert(), remove(), __getitem__(), >>> __setitem__(),... >>> and a signal to notify the views. The objects in the list have methods to >>> change their state as well. >>> >>> My problem is, how do the commands interact with the model? >>> Let's say I have a command that modifies an object o in the list. >>> >>> 1) If list[key_to_o] returns a reference to the object, the command can >>> modify the object by using this reference, i.e. list[key_to_o].setX(). So >>> there is no way for the list to know when the object changed - how can it >>> emit a singal then? >>> >>> 2) If list[key_to_o] returns a deep copy of the object, >>> copy_of_o = list[key_to_o], the command mofifies the copy and the updates >>> the list: list[key_to_o] = copy_of_o. Now the list can emit a signal in >>> __setitem__(). >>> While this may work, it seems awkward to copy around objects just to >>> perform >>> a possibly simple operation on them. Additionally it might not be >>> feasible >>> once objects get complex. >>> >>> 3) The interface of the classes of the objects could be reflected in the >>> list class, i.e. list.set_x_on_obj(key_to_obj,x). This would probably >>> make >>> the list class interface very bloated. >>> >>> Of course the problem is not really limited to Python, my apologies if >>> I'm >>> totally off-topic here. >>> >>> Regards >>> Georg >>> >> >> Well, I think one of the assumptions of the MVC is that the view can >> be notified about the changes in the model. According to your >> interface, the View can just be notified on operations about the >> *whole* model, like adding or removing elements from it. >> >> But the elements of your list-like class should be a part of your >> model, and therefore should be able to notify the Views by >> themselfves. > > Ok, consider this: say the model needs to compute some sort of value by > iterating over all objects in the list (for example some sort of hash). Some > kind of view then displays this value. > I could implement this by connecting a signal in each object to a slot in > the list class which in turn emits a signal which is connected to the view. > > But this implies all the objects in the list have to be instances of > QObject. I wonder if this is isn't a weird design, because for example all > value type classes in Qt don't derive from QObject, e.g. QString. My list > objects are not that simple (in terms of the data structure). So is it ok to > make them QObjects? > Did you take a look at this? http://www.potu.com/man/doc.trolltech.com/4.0/model-view-programming.html It seems to imply that you should use QtAbstractItemModel as a base class for all your models. But since I'm not an expert about Qt, I cannot really say. Regards Marco > > Regards > Georg > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From d3vvnull at gmail.com Fri Sep 26 08:10:21 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Fri, 26 Sep 2008 07:10:21 -0500 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <48DCC618.9040907@wildenhain.de> References: <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> Message-ID: <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> cursor.execute(""" SELECT titem.object_id, titem.tag_id FROM tagging_taggeditem titem WHERE titem.object_id IN (%s) """ % ','.join([str(x) for x in [1,5,9]]) On Fri, Sep 26, 2008 at 6:23 AM, Tino Wildenhain wrote: > Hi, > > Bruno Desthuilliers wrote: > >> bcurtu a ?crit : >> >>> Hi, >>> >>> I have a BIIIIIG problem with the next query: >>> >>> cursor.execute(""" >>> SELECT titem.object_id, titem.tag_id >>> FROM tagging_taggeditem titem >>> WHERE titem.object_id IN (%s) >>> """,( eid_list)) >>> >>> eid_list is suppossed to be a list of ids = [1,5,9] >>> >>> How can I make it work? >>> >> >> You have to build your sql statement in three stages: >> >> # stage 0: the template >> sql_template = """ >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """ >> >> # stage 1: build correct place_holders string for the actual number >> # of items in eid_list >> place_holders = ", " .join("%s" for x in xrange(len(eid_list))) >> > > Hm. either ", ".join(["%s"]*len(eid_list)) > or ", ".join("%s" for x in eid_list) > > should produce the same, wouldn't it? :-) > > # stage 2 : build the effective sql statement >> sql = sql_template % place_holders >> >> # ok, let's go: >> cursor.execute(sql_template, eid_list) >> >> >> NB : you can of course make it in a single statement, but readability will >> suffer: >> >> cursor.execute( >> """ >> SELECT titem.object_id, titem.tag_id >> FROM tagging_taggeditem titem >> WHERE titem.object_id IN (%s) >> """ % ", " .join("%s" for x in xrange(len(eid_list))), >> eid_list >> ) >> > > I'd think giving the arguments in a form of an array type should > work too. At least in postgres there are references to do so. > > Regards > Tino > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From code at pizzashack.org Mon Sep 1 23:05:22 2008 From: code at pizzashack.org (Derek Martin) Date: Mon, 1 Sep 2008 23:05:22 -0400 Subject: Processes in Linux from Python In-Reply-To: <6i1h3cFog1v1U1@mid.uni-berlin.de> References: <8a3627fb-1075-42ae-ab26-dfe0f4d7ad3b@k7g2000hsd.googlegroups.com> <6i1h3cFog1v1U1@mid.uni-berlin.de> Message-ID: <20080902030522.GO29228@dragontoe.org> On Mon, Sep 01, 2008 at 08:40:42AM +0200, Diez B. Roggisch wrote: > Johny schrieb: > >To get a number of the http processes running on my Linux( Debia box) > >I use > >ps -ef | grep "[h]ttpd" | wc -l [...] > The shell does the exact same thing. And by the way: i think you miss a > > grep -v grep Indeed not. The brackets around the 'h' (which make it a character class, or range if you prefer) prevent the regex from matching itself. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dahl.joachim at gmail.com Wed Sep 17 03:54:36 2008 From: dahl.joachim at gmail.com (Joachim Dahl) Date: Wed, 17 Sep 2008 00:54:36 -0700 (PDT) Subject: Python Linear Programming on Ubuntu References: <1fddbc01-4085-4e19-9c0c-085a51350c6d@k7g2000hsd.googlegroups.com> <4a68efd8-c37e-43ad-b834-47b914571492@y38g2000hsy.googlegroups.com> <2cbfdce2-9203-4136-a274-bc7d19dc293a@y38g2000hsy.googlegroups.com> <3d9ab5e0-924b-48c1-b91b-2db1ca91e14c@26g2000hsk.googlegroups.com> Message-ID: CVXOPT supports ILP via GLPK or MOSEK. Documentation is in the doc- strings for cvxopt.glkp.ilp and cvxopt.mosek.ilp. The ILP interfaces are not mentioned otherwise in the documentation, as the main focus of CVXOPT is convex solvers. For additional questions on CVXOPT please use the discussion forum: http://groups.google.com/group/cvxopt best regards Joachim On Sep 17, 5:57?am, Fett wrote: > On Sep 16, 9:44 pm, "Aaron \"Castironpi\" Brady" > > > > wrote: > > On Sep 16, 9:25 pm, Fett wrote: > > > > On Sep 16, 9:00 pm, "Aaron \"Castironpi\" Brady" > > > > wrote: > > > > On Sep 16, 8:50 pm, Fett wrote: > > > > > > I am trying to find a wrapper to do linear programming within python. > > > > > I am using an ubuntu machine and I have apt-get'd lp_solve, which > > > > > works just fine. If someone knows of a wrapper that will work with > > > > > that that'd be great. > > > > > > I also heard that scipy has a wrapper, however, I can't find any > > > > > documentation on it, nor can I seem to find it with dir(). If anyone > > > > > knows where there is good documentation on this I would love to use > > > > > that (the more native to python the better imo). > > > > > > I have tried many things, includinghttp://lpsolve.sourceforge.net/5.5/Python.htm, > > > > > openopt, andcvxopt. I can't seem to find any with enough > > > > > documentation to get me off the ground. Some I can't compile, some I > > > > > can't even find out how to compile. > > > > > > If anyone knows of an LP package (preferably with IP as well, like > > > > > lp_solve has), that interfaces well with python and has enough > > > > > documentation to get a dependency newb like myself off the ground that > > > > > would be great. > > > > > Google says: > > > > > about 254,000 for linear programming python. > > > > > Link 3 is: > > > > >http://wiki.python.org/moin/NumericAndScientific/Libraries > > > > > Scroll down. > > > > Yes, many of those seem to be deprecated, without destinations to > > > links, most are poorly or not documented at all. The few that are, I > > > still can't get running. Of those 254, I think I have tried at least > > > 10 pages worth. Still no luck. > > > > # lpsolvpy - Can't get it to compile - dependency problems. > > > # Lp_solve5 - NO python binding yet. Volunteers needed for python > > > bindings. > > > # pycplex - You need to compile the CPX.so module. Change the required > > > paths to CPLEX, Python and numpy in the Makefile, and type "make". Not > > > sure what to do here. > > > # GLPK (GNU Linear Programming Kit) - Hrm... might be something here, > > > I missed the second link to the python bindings, looked all over the > > > glpk site for anything about python. > > > # SciPy --http://www.scipy.org-supposedlyhas this, but as I said, > > > I can't find any mention of it anywhere but on the site you linked. > > > # pySimplex - (broken link)(broken link) > > > # Simplex - link is broken, but nothing is mentioned > > > > I'll take a closer look at glpk's python bindings and if there is any > > > documentation on them, maybe I'll have some luck. btw, I have been > > > looking for something that works, I have over 5 packages on my desktop > > > that I have tried to get up and running, but none of them seem to > > > work. glpk makes 6. > > > If you can find one working in C, use ctypes to link into Python. ?We > > can help you with that part. ?It lets you pass primitive types, > > structs, arrays, pointers, to C modules and return values. ?You need > > to know the C signatures to set up the Pythonized signatures. > > Ok, it seems that I have found one (although without an integer > programming component): upon searching for glpk in the package manager > in ubuntu I found a package calledcvxopt, it is a bit clunky > (compared to the niceness of lp_solve), but I think I can figure this > one out. Thanks all who answered. From rw at smsnet.pl Thu Sep 18 12:35:09 2008 From: rw at smsnet.pl (Rob Wolfe) Date: Thu, 18 Sep 2008 18:35:09 +0200 Subject: Cython dynamic library problem References: Message-ID: <8763otl8ea.fsf@merkury.smsnet.pl> Tommy Grav writes: > I am trying to learn how to use cython, and while I am following the > cython-dev > mailing list I didn't feel like this question was totally appropriate > for its audience > so I am trying here first. [...] > Does anyone know what the ImportError means and how to correct it? I would try to use `distutils` because this package is much wiser than me and knows all necessary switches for gcc. ;) # test_cython.pyx def test(x): return x * x # test_cython.py from pyx_test import test print test(0) print test(10) # setup.py from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext as build_pyx setup(name = 'pyx_test', ext_modules=[Extension('pyx_test', ['test_cython.pyx'])], cmdclass = { 'build_ext': build_pyx }) $ python2.5 setup.py build_ext -i running build_ext cythoning test_cython.pyx to test_cython.c building 'pyx_test' extension creating build/temp.linux-i686-2.5 gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.5 -c test_cython.c -o build/temp.linux-i686-2.5/test_cython.o test_cython.c:86: warning: function declaration isn?t a prototype test_cython.c:241: warning: function declaration isn?t a prototype test_cython.c:59: warning: ?__pyx_skip_dispatch? defined but not used gcc -pthread -shared -Wl,-O1 build/temp.linux-i686-2.5/test_cython.o -o pyx_test.so $ python2.5 test_cython.py 0 100 HTH, Rob From fredrik at pythonware.com Sun Sep 7 06:40:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 07 Sep 2008 12:40:01 +0200 Subject: unexpected class behaviour In-Reply-To: <48c3ad5d@news.uni-ulm.de> References: <48c3ad5d@news.uni-ulm.de> Message-ID: Jan Sch?fer wrote: > can anyone explain the behaviour of the following code sniplet: well, it *is* explained in the tutorial, the language reference, and the FAQ, so yes, it can be explained ;-) for more information, see this page: http://effbot.org/zone/default-values.htm From deets at nospam.web.de Wed Sep 10 09:25:53 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 15:25:53 +0200 Subject: Adding further report options to unittest.py References: Message-ID: <6iq07jFs30egU1@mid.uni-berlin.de> Marco Bizzarri wrote: > Hi all. > > I would like to change the way test reports are generated, in a Zope > environment. > > I'm playing with TextTestReport, TextTestRunner. Since things are > getting to complicated, I'm afraid I'm following a non-pythonic way. > > Specifically, I would like to have an output like: > > package.subpackage.test_module.TestCase 0.1 > > where 0.1 is the time spent into doing the test. > > In a previous attempt, I made the tests print the number of the test > executed, so that I would have the following output: > > 1 package.subpackage.test_module.TestCase > > however, to do this, I had to put things in the following way: > > > class PAFlowTestRunner(TextTestRunner): > def _makeResult(self): > return PAFlowTextResult(self.stream, self.descriptions, > self.verbosity) > > class PAFlowTextResult(_TextTestResult): > > def startTest(self, test): > self.stream.write("%s " % self.testsRun) > _TextTestResult.startTest(self, test) > > > now, of course, this is ugly, because I'm using _TextTestResult, which > I'm not supposed to know, and I'm changing behaviour by subclassing, > which is not exactly what I would like to do. > > What is the pythonic way to accomplish this? Have you looked at nosetests? Nose is a test-discovery & running-framework based upon unittest-module (but you can also "only" test simple functions, very handy) And it has a very powerful plugin-mechanism, that allows you to implement cleanly what you want. For each test, you get a start/end-method called in your plugin that you can use to gather the information you need, e.g. start/stop-times. For example, I've created an enhanced reporting plugin that lists all tests run (not only those failed or error'ed), and adding time-measuring per-test is on my list of todos. Diez From Ron.Barak at lsi.com Tue Sep 9 03:04:44 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Tue, 9 Sep 2008 08:04:44 +0100 Subject: "AttributeError: 'module' object has no attribute 'getdefaultlocale'" on Python start In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF601ADBE4D@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF601ADBE4D@enbmail01.lsi.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF601ADBEE2@enbmail01.lsi.com> Hi Fellow Pythonians, I stated getting the following when starting Python (2.5.2 on Windows XP): C:\Documents and Settings\RBARAK>python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # D:\Python25\lib\site.pyc matches D:\Python25\lib\site.py import site # precompiled from D:\Python25\lib\site.pyc # D:\Python25\lib\os.pyc matches D:\Python25\lib\os.py import os # precompiled from D:\Python25\lib\os.pyc import errno # builtin import nt # builtin # D:\Python25\lib\ntpath.pyc matches D:\Python25\lib\ntpath.py import ntpath # precompiled from D:\Python25\lib\ntpath.pyc # D:\Python25\lib\stat.pyc matches D:\Python25\lib\stat.py import stat # precompiled from D:\Python25\lib\stat.pyc # D:\Python25\lib\UserDict.pyc matches D:\Python25\lib\UserDict.py import UserDict # precompiled from D:\Python25\lib\UserDict.pyc # D:\Python25\lib\copy_reg.pyc matches D:\Python25\lib\copy_reg.py import copy_reg # precompiled from D:\Python25\lib\copy_reg.pyc # D:\Python25\lib\types.pyc matches D:\Python25\lib\types.py import types # precompiled from D:\Python25\lib\types.pyc import _types # builtin import locale # directory D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale import locale # precompiled from D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale\__init__.pyc # D:\Python25\lib\codecs.pyc matches D:\Python25\lib\codecs.py import codecs # precompiled from D:\Python25\lib\codecs.pyc import _codecs # builtin import encodings # directory D:\Python25\lib\encodings # D:\Python25\lib\encodings\__init__.pyc matches D:\Python25\lib\encodings\__init__.py import encodings # precompiled from D:\Python25\lib\encodings\__init__.pyc # D:\Python25\lib\encodings\aliases.pyc matches D:\Python25\lib\encodings\aliases.py import encodings.aliases # precompiled from D:\Python25\lib\encodings\aliases.pyc 'import site' failed; traceback: Traceback (most recent call last): File "d:\Python25\lib\site.py", line 415, in main() File "d:\Python25\lib\site.py", line 406, in main aliasmbcs() File "d:\Python25\lib\site.py", line 357, in aliasmbcs enc = locale.getdefaultlocale()[1] AttributeError: 'module' object has no attribute 'getdefaultlocale' # D:\Python25\lib\warnings.pyc matches D:\Python25\lib\warnings.py import warnings # precompiled from D:\Python25\lib\warnings.pyc # D:\Python25\lib\linecache.pyc matches D:\Python25\lib\linecache.py import linecache # precompiled from D:\Python25\lib\linecache.pyc Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> Has anyone else gotten this error ? Could anyone suggest a solution ? Thanks, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon Sep 22 18:51:56 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 22 Sep 2008 15:51:56 -0700 (PDT) Subject: a short-cut command for globals().clear() ?? References: <22cb27a2-7022-43d1-a7ce-99185f909f1f@x35g2000hsb.googlegroups.com> Message-ID: <7bbd8631-0ec8-41b1-9787-800a9aea5ec8@c65g2000hsa.googlegroups.com> On Sep 22, 5:44?pm, Terry Reedy wrote: > CapnBearbo... at googlemail.com wrote: > > forgive me , but the RTFM and Google search approaches are not > > yielding an answer on this question. ?I need to know if there's a top > > level python interpreter command that clears all user variables (not > > built-ins) from the global namespace. ?In other words a statement, or > > some_command_or_function(), that does this: > > >>>> x=3 > >>>> y=4 > >>>> z=[] > >>>> dir() > > ['__builtins__', '__doc__', '__name__', 'x', 'y', 'z'] > > >>>> some_command_or_function() > > >>>> dir() > > ['__builtins__', '__doc__', '__name__'] > > First, a WARNING to other readers deceived by the subject line. > Globals().clear() clears everything and leaves nothing, so Capn... is > looking for something that works that is a shortcut for deleting > bindings one-by-one. > > To your question. ?The short answer is no. > > In batch mode, only create what you need and delete (unbind) large > objects that are not automatically deleted (unbound) when you are done > with them. ?Remember that only reference-counted implementations will > guarantee immediate destruction and space-freeing when the last > reference goes away. Check the gc module (and some posts in the > archives) for more specialized control. > > In interactive mode, restart the interpreter if you really need a clean > slate and have too many bindings that you must delete to do something > quick like 'del x,y,z' as in your example above. ?In IDLE, cntl-F6 > restarts the shell with a clean slate. ?I presume IPython has something > similar. > > tjr I guess you have a few hackish options. 1) Define a wrapper that calls its argument immediately, and use it as you would use anonymous blocks. @call_imm def block( ): code code code @call_imm def block( ): code code code You have no globals when you are done. 2) If you need them to be global, use some introspection, and delete the variables upon exiting the scope. 3) Declare all your variables in a namespace, and just delete the namespace. a= type('blank',(),{})() a.varA= 0 a.varB= 'abc' del a From bj_666 at gmx.net Wed Sep 10 07:06:23 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Sep 2008 11:06:23 GMT Subject: which of these 2 quicksorts is faster? References: Message-ID: <6ipo1fFru0uoU1@mid.uni-berlin.de> On Wed, 10 Sep 2008 03:17:30 -0700, process wrote: > qsort can handle bigger lists it seems, making less recursive calls > before finishing(quicksort blows the stack when sorting > range(100,-1000,-1). It just seems so because that `range()` list is the worst case for `quicksort()` but not for `qsort()`. If you feed `qsort()` a list constructed to always leave one recursive call with the empty list, it will reach the recursion limit too. Ciao, Marc 'BlackJack' Rintsch From code at pizzashack.org Tue Sep 2 19:54:12 2008 From: code at pizzashack.org (Derek Martin) Date: Tue, 2 Sep 2008 19:54:12 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <6i5ujqFol29aU8@mid.uni-berlin.de> References: <2008090103233816807-jeremy@jeremybanksca> <6i4pq5Fol29aU1@mid.uni-berlin.de> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <6i5ujqFol29aU8@mid.uni-berlin.de> Message-ID: <20080902235412.GT29228@dragontoe.org> On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: > On Tue, 02 Sep 2008 18:15:07 -0400, Derek Martin wrote: > > >> Classes represent "things", and class names should be nouns. > > > > Is that a law? > > It's a common guideline. Right. It's a guideline. > > Classes are instantiated by invoking their class names as a function > > call -- the computing equivalent of a verb. Why then, must they be > > named as nouns? Can you not, in fact, have classes which describe (or > > model) actions? Wouldn't you name them using verbs if you did? > > Me personally no. I would use `FooAction` instead of `Foo` or something > similar. Maybe you would, but I think a lot of folks would just use the action name (i.e. the verb). > And if they model an action there must be some way to activate > the action That's a reasonable assumption, but as I also said, the object might just describe the action -- essentially the equivalent of a struct in C. > but the instances of `Popen` are no actions. There's no way to > "execute" a `Popen` instance. Yes there is... you execute it when you instantiate the object. At the time of instantiation, you "open" the "P" (pipes). For an object which describes an action, I think it's perfectly sensible that instantiation is when the action occurs, though there could be other times (e.g. if the object had an "execute" method) which make as much sense. > > My point is, if you don't think Popen is a good name for the class, > > that's your opinion, but it is only that: an opinion. > > Like your opinion that it *is* a good name. Yes, exactly. > > Yet some of you state your case as if it is incontrovertable fact. > > I've given a good case as to why it IS a good name (one which I > > genuinely support), and disagree as you may, none of the points any of > > you have made invalidate or even weaken my argument. > > Maybe from your POV. Facts: It doesn't use the `popen()` function So? Neither does the C version of popen(), but that function is still called popen()! :-D As I've already said a few times now, it is conceptually based on popen(). The fact that it doesn't use popen() is not interesting; it (or the portion of it that corresponds to what popen() does) is implemented almost exactly the same way as the C popen() function (except in Python, rather than C). That, to me, is much more interesting. pclose() does what Popen.wait() does, essentially. Sure, the class has a few extre bells and whistles that the C implementation doesn't have, but: > it gives something more complex than a simple pipe Gosh, one would hope that it would be universally true that an object-oriented implementation of something that was originally designed using conventional programming techniques would provide more than one piece of the conventional implementation... We might even hope that it would improve upon 40-year-old implementations, wherever possible... > to three file objects, more attributes and methods), the function used on > Windows under the hood is called `CreateProcess()` not `CreatePipe()`. How does Windows implement popen()? [I think they call it _popen() though...] > `Popen` creates a process and represents a proxy object to communicate > with it, so `Process` is a good name for that concept/"thing". I disagree; the point of that process creation is the communication between the two processes. Calling it a process does not reflect this very important aspect of the object. The Popen object is not a process; it is a collection of pipes and methods used to communicate with one. > It's a way more self explaining name, even for people who know the > `popen()` function I, and apparently the maintainers (at least at the time they added this thing) don't agree. In fact I think it's quite the opposite. If I came across such a "process" object without knowing what it was, I would expect that a process object described a running process, i.e. gave information about things like executable path name, cpu and memory utilization, perhaps a list of all open file descriptors (but not just three specific ones), etc; or something similar. This object provides none of that. It does not, in fact, describe a process at all. It is quite distinct and different from the concept of a process, indeed. > because there's a concept called "process" but none called "popen". Anything that exists can be conceptualized and therefore is a concept. The popen concept exists, and is more than just a concept; it has a concrete implementation in C AND Python and numerous other languages. Verbs can be concepts too. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From kaerbuhez at gmail.com Fri Sep 5 16:53:21 2008 From: kaerbuhez at gmail.com (kaer) Date: Fri, 5 Sep 2008 13:53:21 -0700 (PDT) Subject: mimms problem on Hardy References: <59447741-be83-49a0-9316-d1a42cc4450f@f63g2000hsf.googlegroups.com> Message-ID: On 5 sep, 22:15, kaer wrote: > Hello, > > I installed (manually) the last version of mimms -which is a python > program- on an Ubuntu (8.04-server) box. > I get that: > > kaer at subfighter:~/mimms-3.2$ mimms > Traceback (most recent call last): > File "/usr/bin/mimms", line 21, in > from libmimms.core import run > File "/usr/lib/python2.5/site-packages/libmimms/core.py", line 31, > in > from . import libmms > File "/usr/lib/python2.5/site-packages/libmimms/libmms.py", line 29, > in > libmms.mmsx_connect.argtypes = [c_void_p, c_void_p, c_char_p, > c_int] > File "/usr/lib/python2.5/ctypes/__init__.py", line 361, in > __getattr__ > func = self.__getitem__(name) > File "/usr/lib/python2.5/ctypes/__init__.py", line 366, in > __getitem__ > func = self._FuncPtr((name_or_ordinal, self)) > AttributeError: /usr/lib/libmms.so.0: undefined symbol > > If it helps: > kaer at subfighter:~/mimms-3.2$ ls -l /usr/lib/libmms.so.0 > lrwxrwxrwx 1 root root 15 2008-08-20 01:41 /usr/lib/libmms.so.0 -> > libmms.so.0.0.2: mmsx_connect > > If have no idea where the problem is. Thanks for your ideas, > suggestions, comments ... I should have posted the some code of core.py: """ This module uses ctypes to interface to libmms. Currently, it just exposes the mmsx interface, since this one is the most flexible. """ from ctypes import * libmms = cdll.LoadLibrary("libmms.so.0") # opening and closing the stream libmms.mmsx_connect.argtypes = [c_void_p, c_void_p, c_char_p, c_int] libmms.mmsx_connect.restype = c_void_p libmms.mmsx_close.argtypes = [c_void_p] libmms.mmsx_close.restype = None And so on ... If I comment the mmsx_connect lines, I have the same problem with the mmsx_close ones ... If somebody has an idea on how debug a ctypes problem, it would be very helpful. From bignose+hates-spam at benfinney.id.au Sat Sep 27 05:21:29 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 19:21:29 +1000 Subject: python for *nix system admins References: Message-ID: <87wsgyt04m.fsf@benfinney.id.au> Lars Stavholm writes: > The module (or library) somehow added unix command capabilities > to the python language. It seemed like a lesser known, perhaps new, > python library or module. Which particular Unix commands? Perhaps you're thinking of the 'shutil' module , which wraps a few filesystem manipulation commands. -- \ ?Of all classes the rich are the most noticed and the least | `\ studied.? ?John Kenneth Galbraith, _The Age of Uncertainty_, | _o__) 1977 | Ben Finney From bborcic at gmail.com Mon Sep 8 09:54:19 2008 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 08 Sep 2008 15:54:19 +0200 Subject: max(), sum(), next() In-Reply-To: References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: David C. Ullrich wrote: > > (ii) If A is a subset of B then we should have > max(A) <= max(B). This requires that max(empty set) > be something that's smaller than everything else. > So we give up on that. > Er, what about instances of variations/elaborations on class Smaller(object) : __cmp__ = lambda *_ : -1 ? Cheers, BB From tgrav at mac.com Thu Sep 18 10:47:30 2008 From: tgrav at mac.com (Tommy Grav) Date: Thu, 18 Sep 2008 10:47:30 -0400 Subject: Cython dynamic library problem Message-ID: I am trying to learn how to use cython, and while I am following the cython-dev mailing list I didn't feel like this question was totally appropriate for its audience so I am trying here first. I am on a max os x 10.5.4 running drtgrav% python ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 17:40:23) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> I have a pure python file that I am wanting to try to speed up some, so I ran the file through cython, compiled it with gcc and tried to call it from a python file > cython integrations.pyx > gcc -arch ppc -shared -c -fPIC -I/usr/include/python2.5 integration.c -o pyx_integration.so > python integration_test.py Traceback (most recent call last): File "integration_test.py", line 1, in from astroPyX import pyx_integration ImportError: dlopen(/Users/drtgrav/Work/myCode/Python/astroPyX/ pyx_integration.so, 2): no suitable image found. Did find: /Users/drtgrav/Work/myCode/Python/astroPyX/pyx_integration.so: can't map where integration_test.py is from astroPyX import pyx_integration pyx_integration.test(0) pyx_integration.test(100) Does anyone know what the ImportError means and how to correct it? Cheers Tommy From kf9150 at gmail.com Thu Sep 11 03:09:48 2008 From: kf9150 at gmail.com (Kelie) Date: Thu, 11 Sep 2008 00:09:48 -0700 (PDT) Subject: Use Python to solve equations? Message-ID: <15b65771-20ee-4207-b6ab-e19771645f58@l33g2000pri.googlegroups.com> Hello group, Is there any packages in Python that will help me solve functions similar to this: x = a*(1+bx)**2.5-c where a, b, c is known and the task to solve x? Thank you, Kelie From bruno.42.desthuilliers at websiteburo.invalid Fri Sep 12 12:07:37 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 12 Sep 2008 18:07:37 +0200 Subject: Checking the boolean value of a collection In-Reply-To: References: <6ivbfvFnfucU1@mid.uni-berlin.de> <6ivdhnFnm8bU1@mid.uni-berlin.de> Message-ID: <48ca9333$0$851$426a74cc@news.free.fr> Marco Bizzarri a ?crit : (snip) > I'm afraid this have another problem for me... > > > emmebi at janitor:/var/local/zope28/porting/Products/PAFlow$ python2.3 > Python 2.3.5 (#2, Oct 18 2006, 23:04:45) > [GCC 4.1.2 20061015 (prerelease) (Debian 4.1.1-16.1)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> def any(iterable): pass > ... >>>> any(x for x in [1, 2, 3]) > File "", line 1 > any(x for x in [1, 2, 3]) > ^ > SyntaxError: invalid syntax > >>>> any([x for x in [1, 2, 3]]) >>>> > > I mean, I'm afraid I can't use an expression like that without > building a list... not at least in python2.3 Err... a list being an iterable, you just need any([1, 2, 3]). But this wont be enough to solve your real use case, indeed. From steve at REMOVE-THIS-cybersource.com.au Thu Sep 18 19:42:51 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Sep 2008 23:42:51 GMT Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <00e2e17d$0$20331$c3e8da3@news.astraweb.com> On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote: > Now the obvious winner is pruebono - even unoptimized, using sets seems > to be *way* faster than even the most optimized corrected version of > your algorithm. I'm not being snarky about losing priority here, but I submitted essentially the same solution two hours earlier than pruebono. Are people not seeing my posts? Have I been kill-filed by everyone except Mensator? I also asked a question about HTTPError and I haven't seen any responses at all. -- Steven From pavlovevidence at gmail.com Sat Sep 13 01:39:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 12 Sep 2008 22:39:39 -0700 (PDT) Subject: lacking follow-through References: <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> Message-ID: <289bc58f-6c04-4bce-b393-e9fa0a8c4fee@i20g2000prf.googlegroups.com> On Sep 12, 8:16?am, Steve Holden wrote: > castironpi wrote: > > On Sep 7, 5:03 pm, Marc 'BlackJack' Rintsch wrote: > >> On Mon, 08 Sep 2008 07:34:55 +1000, James Mills wrote: > >>> This is the strangest post I've seen > >>> since I've joined this list (only > >>> recently). What the ? > >> Yeah, castironpi sometimes doesn't make much sense. ?Maybe because it's a > >> bot!? ?:-) > > >> Ciao, > >> ? ? ? ? Marc 'BlackJack' Rintsch > > > No, I'm legit, and I believe my complaint is. ?That's all I can > > guarantee anyway. ?While I'm still not a vet on Usenet, I'm still > > disappointed so far. ?Though I should be flattered for my logic to be > > ever compared to an A.I.'s. > > Your various outpourings appear so rambling and ill-conceived that > silence is often the only polite response. > > If you are flattered to be compared to an AI you must come from the same > race as Mr. Spock in Star Trek. I'm surprised there is anyone who still gives castironpi credit for being fully human. Carl Banks From castironpi at gmail.com Wed Sep 10 15:19:56 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 10 Sep 2008 12:19:56 -0700 (PDT) Subject: Generator functions and user interfaces References: <0266fb01-4530-46f3-a5aa-276936438ef9@m3g2000hsc.googlegroups.com> <48c8051b$0$23993$426a74cc@news.free.fr> Message-ID: <8d190ac7-f016-4ef1-958f-9e997d2e367d@k7g2000hsd.googlegroups.com> On Sep 10, 10:35?am, Bruno Desthuilliers wrote: > psaff... at googlemail.com a ?crit : > > > I'm trying to implement an interactive graph visualisation tool using > > matplotlib. > > > I want to use a spring layout, where nodes repulse each other and > > edges act as springs to pull connected nodes together. Usually, this > > algorithm runs through a number of iterations of attraction/repulsion > > to allow the nodes to converge to suitable positions. However, rather > > than running all these iterations to lay out the graph and then > > rendering it, I want to animate the graph as it is "springing" into > > place, and then allow the user to drag nodes around and have the graph > > redraw on the fly. > > > My idea for doing this was to use a generator function, where I yield > > the position of the nodes after each iteration and then call draw() on > > the position yielded. Does this seem like a sensible approach? > > I don't have much experience with this kind of algorithms, but AFAICT, > it seems sensible to me, yes. But don't take me on words... > > > The > > problem is that the node positions that are being operated on by the > > generator function may be altered by user input - dragging the nodes - > > and I'm not sure if this will break the way that the new positions are > > yielded. How do I use a generator function that might stop (when the > > nodes stop moving) but then need to restart again (once the user moves > > the nodes)? > > Starting with Python 2.5, there's a way to pass values back to generators:http://docs.python.org/whatsnew/pep-342.html > > Now, not having played much with these new features so far, I'm afraid I > can't help more, nor even be strictly positive about this being what you > need. > > Any generator guru around ? Yield can return values. The syntax you're looking for is: def generator_fun( ): a= [] while 1: b= yield( a ) a.append( b ) g= generator_fun( ) g.next( ) g.send( 3 ) g.send( 4 ) g.send( 5 ) /Output: >>> g.next( ) [] >>> g.send( 3 ) [3] >>> g.send( 4 ) [3, 4] >>> g.send( 5 ) [3, 4, 5] 'g' is inactive in between 'send' calls. From ireborin at delete.this.gmail.com Tue Sep 23 07:44:41 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 23 Sep 2008 13:44:41 +0200 Subject: gplt from scipy missing ? References: Message-ID: <67lhd4hq1gch3r18g919fjvmijen9saevv@4ax.com> On Tue, 23 Sep 2008 04:26:14 -0300, "Gabriel Genellina" wrote: > >I think scipy does not bundle plotting packages anymore - you may use >whatever suits you, from other sources. >Try matplotlib, see the wiki: >http://wiki.python.org/moin/NumericAndScientific/Plotting Hello Gabriel, thank you for answering. Unfortunatelly, I cannot change my plotting package, unless I indend to change a lot of code that I'll be using in the future. I'm not a programmer by trade, just a guy doing some calculations with already written programms. Do you know, by any chance, where one could get gplt separately, or for example, get older versions of scipy ? I'm using python 5.2.2.. If I install scipy for python 2.3. for example (let's assume that one still has gplt in it) will it work ? Best regards Ivan From fredrik at pythonware.com Sat Sep 27 07:43:50 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Sep 2008 13:43:50 +0200 Subject: How to read a jpg bytearray from a Flash AS3 file In-Reply-To: References: Message-ID: rsgalloway at gmail.com wrote: > I'm trying to save an image from a Flash AS3 to my server as a jpg > file. I found some PHP code to do this, but I want to do this in > Python. I'm not quite sure how to convert the following code to > Python. It's mainly the $GLOBALS["HTTP_RAW_POST_DATA"] part I don't > know how to convert. depends on what framework you're using. if you're using plain CGI, you should be able to read the posted data from sys.stdin: import sys im = sys.stdin.read() f = open(name, 'wb') f.write(jpg) f.close() to make your code a bit more robust, you may want to check the content-length before doing the read, e.g. import os if os.environ.get("REQUEST_METHOD") != "POST": ... report invalid request ... bytes = int(os.environ.get("CONTENT_LENGTH", 0)) if bytes > MAX_REQUEST_SIZE: ... report request too large ... im = sys.stdin.read(bytes) to deal with query parameters etc, see http://docs.python.org/lib/module-cgi.html From jamesd at echeque.com Wed Sep 10 07:48:12 2008 From: jamesd at echeque.com (James A. Donald) Date: Wed, 10 Sep 2008 21:48:12 +1000 Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> Message-ID: <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> On Tue, 9 Sep 2008 14:35:13 -0700 (PDT), icarus wrote: > Oh ok. Thanks. In windows xp I just renamed the file extension to .pyw > That did it. > > one more question... > > how do I create a pythonw standalone executable that works on w32, > linux, mac, etc..? I have noticed that when applications are written in Python with the GUI created by PyGTK, it seems that to install the application on each slightly different version of unix is a fairly major task - although the creators of PyGTK proudly say that the code will run anywhere, it definitely will not install anywhere - the code will only run on a slightly different system after a massive and major rewrite of the install for that target system. Horrible installs are a chronic problem GUI programs driven by interpreted languages Installing visual basic programs that worked on one Windows machine to work on a very slightly different windows machine was also a nightmare. I have not attempted to create installable wxPython windows, but generally, "run anywhere" will bite you. Still looking for a good solution to "run anywhere". -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From cbabcock at kolonelpanic.org Mon Sep 1 01:22:59 2008 From: cbabcock at kolonelpanic.org (Chris Babcock) Date: Sun, 31 Aug 2008 22:22:59 -0700 Subject: Mako --> Genshi References: <20080830205904.725f1bef@mail.asciiking.com> <6hv09bFnvm0eU1@mid.uni-berlin.de> Message-ID: <20080831222259.525c03ed@mail.asciiking.com> > > Is there a cheap way to convert Myghty/Mako templates to Kid/Genshi? > > There's some code written for Pylons that I want to incorporate > > into a TurboGears 2 project and Genshi templates are more likely to > > behave themselves with the tools I'm used to. > > Not that I'm aware of. And I think it's impossible to reliably do > that, because mako allows broken XML or "pure" HTML, whereas > KID/Genshi require well-formed XML. Yes, that would put the kabosh on it, thanks. Even more to the point, I want to write more to style than to ${content} so that the template is less like to break in a WYSIWYG editor. While I know how to edit xhtml source well enough to avoid breaking templates, I can't guarantee the same of everyone who might be involved. A translator gadget is less likely to produce the style that I want than the other, which is more mako-like. Chris From asnast at gmail.com Sat Sep 20 19:27:41 2008 From: asnast at gmail.com (Alex Snast) Date: Sat, 20 Sep 2008 16:27:41 -0700 (PDT) Subject: How to make a reverse for loop in python? References: <5e7068d0-e0a1-48df-92d8-1bca9fe43ec2@t54g2000hsg.googlegroups.com> Message-ID: On Sep 20, 8:13?pm, bearophileH... at lycos.com wrote: > Duncan Booth: > > > > e.g. the python equivalent to the c++ loop > > > for (i = 10; i >= 0; --i) > > > The exact equivalent would be: > > ? ? ? ? for i in range(10, -1, -1): print i > > I'd use xrange there. Anyway, I have always felt that Python syntax > not easy to understand at first sight, expecially when you try to > convert a bit more complex inverted for loops from/to C to/from > Python. It's one of the few cases where (for example) Pascal (loop) > syntax wins a bit over Python syntax :-) > > Bye, > bearophile Another quick question please, is the List data structure just a dynamic array? If so how can you use static size array, linked list, AVL trees etcetera. From ttkk1024 at gmail.com Wed Sep 17 06:17:54 2008 From: ttkk1024 at gmail.com (smalltalk) Date: Wed, 17 Sep 2008 03:17:54 -0700 (PDT) Subject: shelve file space always increase! Message-ID: >>> import shelve >>> sf = shelve.open('e:/abc.db') >>> for i in range(10000): ... sf[str(i)]=i ... >>> sf.close() >>> sf = shelve.open('e:/abc.db') >>> sf.clear() >>> sf {} the abc.db is always 312k though i have use clear(), how can i shrink the space? From invalid at nowhere.invalid.org Tue Sep 16 06:15:48 2008 From: invalid at nowhere.invalid.org (Alex Marandon) Date: Tue, 16 Sep 2008 11:15:48 +0100 Subject: append on lists In-Reply-To: References: Message-ID: <1221560151.9212.0@proxy00.news.clara.net> Armin wrote: > Chris Rebert wrote: >> On Mon, Sep 15, 2008 at 1:24 PM, Armin wrote: >>> >>> Hi, >>> >>> just a dumb question. >>> >>> Let a = [1,2,3,4,5] >>> >>> Why is the value of a.append(7) equal None and not [1,2,3,4,5,6,7] ?? >> >> Because .append() mutates 'a' and appends the item in-place rather >> than creating and returning a new list with the item appended, and >> it's good Python style for mutating methods to have no return value >> (since all functions must have some return value, Python uses None >> when the function doesn't explicitly return anything). > > Yes, but this is very unconvenient. Hi, You might be interested in using the + operator instead of append. You could also define your own list type, based on the UserList included in the standard library. >>> from UserList import UserList >>> class MyList(UserList): ... def my_append(self, value): ... return self + [value] ... >>> l = MyList([1,2,3,4]) >>> l [1, 2, 3, 4] >>> l.my_append(5) [1, 2, 3, 4, 5] >>> l [1, 2, 3, 4] From george.sakkis at gmail.com Sat Sep 27 12:19:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 27 Sep 2008 09:19:57 -0700 (PDT) Subject: is decorator the right thing to use? References: <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <6k0qc1F53ov8U1@mid.uni-berlin.de> <48dd5c06$0$26425$426a74cc@news.free.fr> Message-ID: <91e62d70-73fb-4ecc-ae2e-d950a5f7ea6b@k13g2000hse.googlegroups.com> On Sep 27, 11:27 am, George Sakkis wrote: > If you want to eliminate completely specifying attributes with > strings, it's easy to modify the above so that you write instead: > > class A(Proxy): > ... > bmethod = ProxyMethod(lambda self: self.b1) > bmethod2 = ProxyMethod(lambda self: self.b2) It's funny how often you come with a better solution a few moments after htting send! The snippet above can (ab)use the decorator syntax so that it becomes: class A(Proxy): @ProxyMethod def bmethod(self): return self.b1 @ProxyMethod def bmethod2(self): return self.b2 With the observation that ProxyMethod has access both to the callable that returns the delegate and the name of the delegated method, we can remove the need for the metaclass and the Proxy base class altogether: class proxymethod(object): def __init__(self, get_delegate): self._get_delegate = get_delegate def __get__(self, proxy, proxytype): if proxy is not None: return self.__get_target_attr(proxy) else: return self.__unbound_method def __unbound_method(self, proxy, *args, **kwds): method = self.__get_target_attr(proxy) return method(*args, **kwds) def __get_target_attr(self, proxy): get_delegate = self._get_delegate try: return getattr(get_delegate(proxy), get_delegate.__name__) except AttributeError: raise AttributeError('%r object has no attribute %r' % (proxy.__class__.__name__, get_delegate.__name__)) class A(object): def __init__(self, b1, b2): self.b1 = b1 self.b2 = b2 def amethod(self,a): print "A::mymethod",a @proxymethod def bmethod(self): return self.b1 @proxymethod def bmethod2(self): return self.b2 a = A(B(10), B(20)) a.amethod('foo') print "bound proxy calls" a.bmethod('foo') a.bmethod2('bar','baz') print "unbound proxy calls" A.bmethod(a,'foo') A.bmethod2(a,'bar','baz') So back to the OP's original question and after a long circle.. a decorator might well be the right thing to use after all :) George From george.sakkis at gmail.com Tue Sep 23 19:24:34 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 23 Sep 2008 16:24:34 -0700 (PDT) Subject: Docstrings for class attributes References: Message-ID: <6b22c96d-6958-4d74-86b2-3a9dd20a7455@d77g2000hsb.googlegroups.com> On Sep 23, 3:55 pm, Gerard flanagan wrote: > George Sakkis wrote: > > On Sep 23, 1:23 am, "Tom Harris" wrote: > > >> Greetings, > > >> I want to have a class as a container for a bunch of symbolic names > >> for integers, eg: > > >> class Constants: > >> FOO = 1 > >> BAR = 2 > > >> Except that I would like to attach a docstring text to the constants, > >> so that help(Constants.FOO) will print some arbitrary string. Sort of > >> a very limited implementation of PEP 224. The only solution that I can > >> see is to subclass int.__new__(), since once I have an int all it's > >> attributes are immutable. > > > Here's one approach, using metaclasses and descriptors; it sort of > > works, but it's less than ideal, both in usage and implementation. > > > George > > > #====== usage ============================================ > > > class MyConstants: > > __metaclass__ = ConstantsMeta > > FOO = const(1, 'some docs about foo') > > BAR = const(2) > > > print MyConstants.FOO.__doc__ > > help(MyConstants.FOO) > > print MyConstants.FOO - MyConstants.BAR > > print MyConstants.FOO - 2 > > print 1 - MyConstants.BAR > > > #======= implementation =================================== > > > def ConstantsMeta(name, bases, namespace): > > for name,attr in namespace.iteritems(): > > if isinstance(attr, const): > > namespace[name] = _ConstDescriptor(name, attr.value, > > attr.doc) > > return type(name, bases, namespace) > > > class const(object): > > def __init__(self, value, doc=None): > > self.value = value > > self.doc = doc > > > class _ConstDescriptor(object): > > def __init__(self, name, value, doc): > > cls = type(name, (), dict( > > __doc__ = doc, > > __add__ = lambda self,other: value+other, > > __sub__ = lambda self,other: value-other, > > # ... > > __radd__ = lambda self,other: other+value, > > __rsub__ = lambda self,other: other-value, > > # XXX lots of boilerplate code for all special methods > > follow... > > # XXX Is there a better way ? > > )) > > self._wrapper = cls() > > > def __get__(self, obj, type): > > return self._wrapper > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I think you get an equivalent result if you forget the descriptor > and adapt the metaclass: > > def ConstantsMeta(name, bases, namespace): > for name,attr in namespace.iteritems(): > if isinstance(attr, const): > cls = type(name, (type(attr.value),), {'__doc__': attr.doc}) > namespace[name] = cls(attr.value) > return type(name, bases, namespace) Sweet! The big improvement of course is that you thought of subclassing the type of attr.value instead of delegating manually all special methods. It seems so obvious in retrospect, but I totally missed it for some reason; thanks! George From george at george-net.de Tue Sep 16 11:00:23 2008 From: george at george-net.de (Georg Altmann) Date: Tue, 16 Sep 2008 17:00:23 +0200 Subject: MVC with Python In-Reply-To: <200809161514.39385.maric@aristote.info> References: <3f0d61c40809160547t339226acx19a7a0a0f58a6e73@mail.gmail.com> <200809161514.39385.maric@aristote.info> Message-ID: Maric Michaud schrieb: > Le Tuesday 16 September 2008 14:47:02 Marco Bizzarri, vous avez ?crit : >> On Tue, Sep 16, 2008 at 1:26 PM, Georg Altmann wrote: >>> Marco Bizzarri schrieb: >>>> On Mon, Sep 15, 2008 at 9:37 PM, Georg Altmann >>>> wrote: >>> But this implies all the objects in the list have to be instances of >>> QObject. I wonder if this is isn't a weird design, because for example >>> all value type classes in Qt don't derive from QObject, e.g. QString. My >>> list objects are not that simple (in terms of the data structure). So is >>> it ok to make them QObjects? >> Did you take a look at this? >> >> http://www.potu.com/man/doc.trolltech.com/4.0/model-view-programming.html >> >> It seems to imply that you should use QtAbstractItemModel as a base >> class for all your models. But since I'm not an expert about Qt, I >> cannot really say. Yes, I did. But as I explained in my previous message, the whole Qt model-view framework doesn't seem fit any data which can not be handled as QVariant and thus as a value type. > It is not about QT, it is about MVC. In MVC, code which implement the model > should be completely ignorant of the libraries used for gui, and the gui part > of the application shouldn't acces directly to your model logic. This why > there is a third layer which abstract the logic of your datas and provide > standard operation for the gui code. This third layer (Controllers), should > be as few as possible coupled to the specificities of the gui library (but > must be). > > The quoted papers explain rather well how to do this with QT (apart they call > controllers "delegates"). Except they always handle simple data. I don't see how to get around the QVariant limitatation. Also the data should be displayed in a graphical manner (maybe a QGraphicsScene/QGraphicsView or mabye custom QScrollArea). This also doesn't seem to go well with the standard Qt approach. I could imagine to implement the model without using any Qt then use proxy classes derived from QObject as controllers. > For medium to big project, don't be afraid to divide your program in three > packages, one for the model, in which you must not have any reference to QT > API of some sort, one for the controllers, where you provide events and > methods to manipulate your model, one for gui, where you just build windows, > subscribe to controller's events and use their functions as callbacks for > your widgets. As this is a small project for now, I think the controller layer is too much work. As the project gets bigger it should be possible to switch to a full mvc implementation if necessary. For now I will try to work with a model that provides some signals by itself. Regards Georg From google at mrabarnett.plus.com Thu Sep 25 18:40:56 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 25 Sep 2008 15:40:56 -0700 (PDT) Subject: How to get the filename in the right case ? References: <6k1dukF5hk86U1@mid.uni-berlin.de> Message-ID: <2438fe2e-2eab-4b82-80ae-85e4aa1ec02a@26g2000hsk.googlegroups.com> On Sep 25, 8:38?pm, Stef Mientki wrote: > I found a partial workaround that is good enough for me: > > def Get_Windows_Filename ( FileName ) : > ? if os.name == 'nt' : > ? ? File = os.path.splitext ( FileName .lower ())[0] > ? ? return glob.glob ( File + '.p?' ) > ? return FileName > > This will translate the filename into the correct case, but not the path. > > I also looked at os.path.walk, but that's too slow for me, > because getting the path correct means I have to start at the root. > You could try win32api.GetLongPathName(...). However, I've found that some parts of the path are converted to the correct case but other parts aren't: >>> print win32api.GetLongPathName(r"c:\documents and settings\administrator\desktop\foobar.py") c:\documents and settings\administrator\Desktop\FooBar.py How does your solution compare to using os.listdir(...) instead of glob? From tsrinuvasulu491 at gmail.com Tue Sep 30 21:58:39 2008 From: tsrinuvasulu491 at gmail.com (chinu) Date: Tue, 30 Sep 2008 18:58:39 -0700 (PDT) Subject: EARN $$$ IN EVERY MONTH Message-ID: hai, i am srinu from india. i am sending a blog url for yours use. click on the blog and get more information to choose yours job. the blog url is: http://earnmonthlyincome.blogspot.com/ goodluck From zhushenli at gmail.com Wed Sep 3 00:20:38 2008 From: zhushenli at gmail.com (Davy) Date: Tue, 2 Sep 2008 21:20:38 -0700 (PDT) Subject: Pass same parameter in Recursive function References: Message-ID: On Sep 3, 11:57?am, "Chris Rebert" wrote: > Assuming the function is tail-recursive or the "unchanging" arguments > are immutable, just use a closure: [SNIP] Hi Chris, Thank you :) Perhaps I should clarify the problem. 1. the function is NOT tail-recursive 2. Yes, the arguments are immutable after I call the function the first time. I think the best description of the problem may be: How to keep some argument constant and accessable in one function (especially, recursive function). We know that we can use something like self.parameter to keep the parameter constant and accessable in one class. > > def func(self, x, y, A, B, C): > ? ? def _func(x,y): > ? ? ? ? return _func(g(A,B,C,x), h(A,B,C,y)) #recurse > ? ? return _func(x, y) > > I'm unsure as to the performance impact of this though. > > - Chris > > > > > > On Tue, Sep 2, 2008 at 8:20 PM, Davy wrote: > > Hi all, > > > Sometimes I need to pass same parameter in recursive function. From my > > point of view, the style is redundant, and I don't what to use some > > global style like self.A, self.B, Is there any other choice? > > > For example, > > > def func(self, x, y, A, B, C): > > ?#x, y change in recursive call > > ?#A, B, C change in the first layer function call, but did not change > > in recursive call > > ?if (...): > > ? ?func(x, y, A, B, C) > > ?else(...): > > ? ?func(x, y, A, B, C) > > > Best regards, > > Davy > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Follow the path of the Iguana...http://rebertia.com- Hide quoted text - > > - Show quoted text - From ivan.illarionov at gmail.com Thu Sep 4 17:05:41 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 4 Sep 2008 14:05:41 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <86396e86-8219-4cc6-8824-f04764e42459@a3g2000prm.googlegroups.com> <48c03b91$0$14747$426a74cc@news.free.fr> Message-ID: On 4 ????, 21:49, Bruno Desthuilliers wrote: > Ivan Illarionov a ?crit : > > > > > On 4 ????, 22:59, Carl Banks wrote: > >> You can write code to guard against this if you want: > > >> class A: > >> legal = set(["x"]) > >> def __setattr__(self,attr,val): > >> if attr not in self.legal: > >> raise AttributeError("A object has no attribute '%s'" % > >> attr) > >> self.__dict__[attr] = val > >> def __init__(self,x): > >> self.y = x > > >> I suspect most people who go into Python doing something like this > >> soon abandon it when they see how rarely it actually catches anything. > > > '__slots__' is better: > > For which definition of "better" ? __slots__ are a mean to optimize > memory usage, not to restrict dynamism. Being able to dynamically add > arbitrary attributes is actually a feature, not a bug, and uselessly > restricting users from doing so is not pythonic. IOW : don't do that. Carl's example is restricting dynamism in the same way as __slots__. I've just suggested a better implementation. It is not me who suggested dynamism restriction as a way to guard against errors. From gagsl-py2 at yahoo.com.ar Mon Sep 29 22:42:20 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 29 Sep 2008 23:42:20 -0300 Subject: Comparing float and decimal References: <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> Message-ID: En Thu, 25 Sep 2008 08:02:49 -0300, Mark Dickinson escribi?: > On Sep 23, 1:58?pm, Robert Lehmann wrote: >> I don't see why transitivity should apply to Python objects in general. > > Hmmm. Lack of transitivity does produce some, um, interesting > results when playing with sets and dicts. Here are sets s and > t such that the unions s | t and t | s have different sizes: > >>>> from decimal import Decimal >>>> s = set([Decimal(2), 2.0]) >>>> t = set([2]) >>>> len(s | t) > 2 >>>> len(t | s) > 1 Ouch! > This opens up some wonderful possibilities for hard-to-find bugs... And I was thinking all this thread was just a theoretical question without practical consequences... -- Gabriel Genellina From gherron at islandtraining.com Thu Sep 18 03:11:41 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 18 Sep 2008 00:11:41 -0700 Subject: member functions in a class In-Reply-To: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> References: <6gvfio$7t2lv0@rrcs-agw-01.hrndva.rr.com> Message-ID: <48D1FF2D.20607@islandtraining.com> Karl Kobata wrote: > > I am new to python and am wondering. When I create a class, with ?def? > functions and if this class is instantiated say 50 times. Does this > mean that all the ?def? functions code within the class is duplicated > for each instance? > > Can someone give me a short and simple answer as to what happens in > python? > > Thanks > No code is duplicated. 50 "objects" are created. Each object has its own copy of the data attributes, and a reference to the (one and only) class object where the method attributes are located. That's a short answer. Perhaps too short? Gary Herron > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From karl.kobata at syncira.com Thu Sep 25 21:03:31 2008 From: karl.kobata at syncira.com (Karl Kobata) Date: Thu, 25 Sep 2008 18:03:31 -0700 Subject: deleting an object Message-ID: <6u80qt$80h3s3@rrcs-agw-02.hrndva.rr.com> Please help. Questions based on snippet of code below. 1) when myTestCase is deleted, is just the pointer deleted or the entire instance with all of its data and data structure deleted? 2) What is the practice for deleted the object and recovering the memory it occupies? 3) If delete is the way, what happens to 'testUtils.utilFunction1()' if it were instantiated in other classes that have not been deleted yet? Thanks for your help. Example: import testUtils class testClass: def __init__(self): self.testList = list() self.testDict1 = dict() self.utils1 = testUtils.utilFunction1() ... ...in the main code body. myTestCase = testClass() .... delete myTestCase ... -------------- next part -------------- An HTML attachment was scrubbed... URL: From dullrich at sprynet.com Thu Sep 4 12:17:37 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 04 Sep 2008 11:17:37 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: In article <24061e7d-935a-442f-8d50-b8619d5581d3 at 34g2000hsh.googlegroups.com>, bearophileHUGS at lycos.com wrote: > Empty Python lists [] don't know the type of the items it will > contain, so this sounds strange: > > >>> sum([]) > 0 > > Because that [] may be an empty sequence of someobject: > > >>> sum(s for s in ["a", "b"] if len(s) > 2) > 0 > > In a statically typed language in that situation you may answer the > initializer value of the type of the items of the list, as I do in the > sum() in D. > > This sounds like a more correct/clean thing to do: > > >>> max([]) > Traceback (most recent call last): > File "", line 1, in > ValueError: max() arg is an empty sequence > > So it may be better to make the sum([]) too raise a ValueError, I don't see why you feel the two should act the same. At least in mathematics, the sum of the elements of the empty set _is_ 0, while the maximum element of the empty set is undefined. And both for good reason: (i) If A and B are disjoint sets we certainly want to have sum(A union B) = sum(A) + sum(B). This requires sum(empty set) = 0. (ii) If A is a subset of B then we should have max(A) <= max(B). This requires that max(empty set) be something that's smaller than everything else. So we give up on that. > in > Python 3/3.1 (if this isn't already true). On the other hand often > enough I have code like this: > > >>> max(fun(x) for x in iterable if predicate(x)) > > This may raise the ValueError both if iterable is empty of if the > predicate on its items is always false, so instead of catching > exceptions, that I try to avoid, I usually end with a normal loop, > that's readable and fast: > > max_value = smallvalue > for x in iterable: > if predicate(x): > max_value = max(max_value, fun(x)) > > Where running speed matters, I may even replace that max(max_value, > fun(x)) with a more normal if/else. > > A possible alternative is to add a default to max(), like the next() > built-in of Python 2.6: > > >>> max((fun(x) for x in iterable if predicate(x)), default=smallvalue) > > This returns smallvalue if there are no items to compute the max of. > > Bye, > bearophile -- David C. Ullrich From robin at alldunn.com Sun Sep 28 15:01:38 2008 From: robin at alldunn.com (Robin Dunn) Date: Sun, 28 Sep 2008 12:01:38 -0700 Subject: ANN: wxPython 2.8.9.0 Message-ID: <48DFD492.1090905@alldunn.com> Announcing ---------- The 2.8.9.0 release of wxPython is now available for download at http://wxpython.org/download.php. This release adds support for using Cairo for drawing on wx windows, adds a Win64 build, and various other fixes and enhancements. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit and 64-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+. In most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.9.0 ------------------ Many minor bug fixes throughout wxWidgets and wxPython. Fixed wx.lib.embeddedimage to work with Python 2.3. Fixed PseudoDC hit testing when pure white or pure black are used. Added support for a 64-bit Windows build for the AMD64 architecture, (a.k.a. x64.) This is for Python 2.5 only and is available only as a Unicode build. Added the wx.EmptyBitmapRGBA factory function. Added the wx.lib.wxcairo module which allows the pycairo package to be used for drawing on wx window or memory DCs. In addition it is able to convert from a native wx.Font to a cairo.FontFace, and it also provides functions for converting to/from wx.Bitmap and cairo.ImageSurface objects. In order to use this module you will need to have the Cairo library and its dependencies installed, as well as the pycairo Python package. For Linux and other unix-like systems you most likely have what you need installed already, or can easily do so from your package manager application. See the wx.lib.wxcairo module's docstring for notes on where to get what you need for Windows or Mac. This module uses ctypes, and depending on platform it may need to find and load additional dynamic libraries at runtime in addition to cairo. The pycairo package used needs to be new enough to export the CAPI structure in the package namespace. I believe that started sometime in the 1.4.x release series. Added the wx.lib.graphics module, which is an implementation of the wx.GraphicsContext API using Cairo (via wx.lib.wxcairo). This allows us to be totally consistent across platforms, and also use Cairo to implement some things that are missing from the GraphicsContext API. It's not 100% compatible with the GraphicsContext API, but probably close enough to be able to share code between them if desired, plus it can do a few things more. Updated wx.Bitmap.CopyFromBuffer to be a bit more flexible. You can now specify the format of the buffer, and the CopyFromBufferRGBA is now just a wrapper around CopyFromBuffer that specifies a different format than the default. Also added the complement method, CopyToBuffer. See the docstring for CopyFromBuffer for details on the currently allowed buffer formats. The existing wx.BitmapFromBuffer factory functions are also now implemented using the same underlying code as CopyFromBuffer. Add wx.lib.mixins.listctrl.ListRowHighlighter for automatic highlighting of rows in a wx.ListCtrl. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From semanticist at gmail.com Sat Sep 27 20:22:50 2008 From: semanticist at gmail.com (Miles) Date: Sat, 27 Sep 2008 20:22:50 -0400 Subject: Borg vs Singleton vs OddClass In-Reply-To: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> References: <273feee8-a835-4605-b1ed-beba5ba7e668@a3g2000prm.googlegroups.com> Message-ID: Lie wrote: > This is probably unrelated to Python, as this is more about design > pattern. I'm asking your comments about this design pattern that is > similar in functionality to Singleton and Borg: to share states. > > I'm thinking about this design pattern (I don't know if anyone has > ever thought of this pattern before): > > class OddClass(object): > def __init__(self): > global OddClass > OddClass = self > def __call__(): I'll change this to def __call__(self): > return self > > The OddClass is a class that would overwrite its own class definition > at its first instantiation. OddClass defines __call__ so that > subsequent "instantiation" (technically it is no more an > instantiation, but Duck Typing says it does) of the class would return > the single instance. This seems like a terrible idea to me, but then I never really understood the appeal of the Singleton pattern, especially in Python. > Singleton and OddClass is inheritable. > >>>> class OddClass(object): ... >>>> s = OddClass() >>>> class A(OddClass): pass Traceback (most recent call last): File "", line 1, in TypeError: Error when calling the metaclass bases __init__() takes exactly 1 argument (4 given) Oops! And assuming you carefully ordered your code so that OddClass will never be instantiated before it is subclassed (which seems fragile), you get behavior like this: >>> s = OddClass() >>> s is OddClass() True >>> a = A() >>> s is OddClass() False >>> a is OddClass() True >>> a is A() False >>> a is OddClass() False -Miles From bignose+hates-spam at benfinney.id.au Thu Sep 18 18:33:04 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 Sep 2008 08:33:04 +1000 Subject: Launching a subprocess without waiting around for the result? References: <4638348a-9d0b-4612-81e8-6a7196f5acf0@b38g2000prf.googlegroups.com> Message-ID: <87skrx2ifz.fsf@benfinney.id.au> erikcw writes: > I have a cgi script where users are uploading large files for > processing. I want to launch a subprocess to process the file so the > user doesn't have to wait for the page to load. For "how do I deal with subprocesses from Python", the (new in Python 2.4) 'subprocess' module is the default go-to answer , replacing a rather fragmented set of modules before it. > What is the correct way to launch subprocess without waiting for the > result to return? Creating an instance of 'subprocess.Popen' will launch the process and return the Popen instance. You then have the option of polling it or waiting for it to complete. -- \ ?To stay young requires unceasing cultivation of the ability to | `\ unlearn old falsehoods.? ?Robert Anson Heinlein | _o__) | Ben Finney From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 1 08:12:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 01 Sep 2008 14:12:02 +0200 Subject: how to find position of dictionary values In-Reply-To: <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> References: <48bbab73$0$27858$426a34cc@news.free.fr> <6i1rgcFo0f1gU1@mid.uni-berlin.de> <72f5a3b5-b052-43e5-966c-8807c455e24f@b38g2000prf.googlegroups.com> Message-ID: <48bbdbbe$0$3794$426a74cc@news.free.fr> lee a ?crit : > On Sep 1, 2:37 pm, "Diez B. Roggisch" wrote: >> lee wrote: (snip) >>> i agree with u, my data strusture is not efficient. but all the >>> records,viz...name,phno, email,address are all generated at runtime , >>> when the user enters them. so how can i design my datastructure in >>> that case? >> Are "u" short on keystrokes? You are not textmessaging here... > i am soory for that keystrokes Is your cap key broken ?-) (snip) >. can anyone tell me how can i change > the value of key. > suppose i have a dictionary > > kev = {'kabir': ['kabir at kabir.com', '1234', 'missuri'], 'shri': > ['shri at shri.com', '23423', 'india'], 'marsa': ['marsa at marsa.com', > '2345', 'brazil'], 'sandeep': ['sandeep at sandeep.com', '007', > 'canada']} > > > how can i change the key to something like 'sabir' and how can i > change the values of kabir? I don't mean to be harsh, but did you read the FineManual(tm) ? All this is very basic (no pun) stuff, mostly documented, and easy to try out using the interactive interpreter. This ng is very newbie-friendly, but this doesn't mean you can hope to get by without doing the minimal effort of going thru the tutorial and trying a couple things by yourself before asking. Hope you'll understand the above remark intends to be an helpful advice... From clp at rebertia.com Tue Sep 30 18:00:06 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 30 Sep 2008 15:00:06 -0700 Subject: Backup a directory In-Reply-To: References: Message-ID: <47c890dc0809301500r2845c73cp607d92f1903add87@mail.gmail.com> On Tue, Sep 30, 2008 at 1:21 PM, wrote: > Hello, > > > I'm looking for a script that creates a backup of a directory but keeps only > one backup. > I've tried using all the os modules commands but could not create one. > > > Does any one has any such custom script or function? You could probably whip one up very easily using the tarfile module [http://docs.python.org/lib/module-tarfile.html] and shutil.move() [http://docs.python.org/lib/module-shutil.html]. Just make a new TarFile of the directory, save it, then replace any previous backup file using shutil.move() Good luck, and have fun! Regards, Chris P.S. And if you're on *nix, you might consider just using a shell script and the 'tar' command. Right tool for the right job and all that. -- Follow the path of the Iguana... http://rebertia.com > > > Thanks and regards, > rajat > > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Fri Sep 5 17:22:27 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 14:22:27 -0700 (PDT) Subject: Determining Processor Vender References: <554ecfcf-96d8-4602-8d5e-ee5d70590124@i76g2000hsf.googlegroups.com> <3c4cb88a-2e47-4a5e-9a82-4b72f00b1561@y21g2000hsf.googlegroups.com> Message-ID: <8c07c276-96e5-4130-93b3-f9bf5e9f123d@n33g2000pri.googlegroups.com> On Sep 6, 5:07?am, aha wrote: > On Sep 5, 3:00?pm, aha wrote: > > > Dose anyone know of a cross-platform method for determining the vendor > > of a processor? ?Under linux I can check /proc/cpuinfo. ?What I'd like > > to be able to do is determine if a processor is AMD or Intel, so that > > I can use the appropriate numerical libraries for my application. > > > Regards, > > > Aquil > > Additionally, I've tried the platform module...platform.processor() on > my 64-bit AMD system, under Linux, returns x86_64. ?And under windows > retruns an empty string '' This may help with Windows. My setup: (XP SP 2), Python 2.5.2. The chip is an AMD Turion Mobile which is 64-bit but is running 32-bit Windows. >>> import os >>> from pprint import pprint as pp >>> pp(dict((k, v) for (k, v) in os.environ.items() if 'PROCESSOR' in k)) {'NUMBER_OF_PROCESSORS': '1', 'PROCESSOR_ARCHITECTURE': 'x86', 'PROCESSOR_IDENTIFIER': 'x86 Family 15 Model 36 Stepping 2, AuthenticAMD', 'PROCESSOR_LEVEL': '15', 'PROCESSOR_REVISION': '2402'} >>> Cheers, John From sjmachin at lexicon.net Sat Sep 20 07:25:50 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 20 Sep 2008 04:25:50 -0700 (PDT) Subject: how can i check whether a variable is iterable in my code? References: <48d4d208$0$24033$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <5acda372-d25d-41b4-8cfd-c9fa57b2095c@c22g2000prc.googlegroups.com> Message-ID: <2dfbad14-b898-4284-9912-337af09c4d90@s9g2000prg.googlegroups.com> On Sep 20, 8:54?pm, satoru wrote: > On Sep 20, 6:35?pm, Aidan wrote: > > > satoru wrote: > > > hi, all > > > i want to check if a variable is iterable like a list, how can i > > > implement this? > > > this would be one way, though I'm sure others exist: > > > if hasattr(yourVar, '__iter__'): > > ? ? ? ? # do stuff > > thank you,but this will miss out sequences like string just because it > doesn't have an attribute named '__iter__' str objects have a __getitem__ attribute, as do other built-in sequence types: unicode, xrange, buffer. AFAIK if an object has no __iter__ but has a __getitem__, iter(obj) will create an iterator that calls obj.__getitem__(0), obj.__getitem__(1), etc until IndexError is raised. From dullrich at sprynet.com Fri Sep 5 11:16:38 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 05 Sep 2008 10:16:38 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: In article , Ken Starks wrote: > David C. Ullrich wrote: > > > > > I don't see why you feel the two should act the same. > > At least in mathematics, the sum of the elements of > > the empty set _is_ 0, while the maximum element of the > > empty set is undefined. > > > > And both for good reason: > > > > (i) If A and B are disjoint sets we certainly want to > > have sum(A union B) = sum(A) + sum(B). This requires > > sum(empty set) = 0. > > > > (ii) If A is a subset of B then we should have > > max(A) <= max(B). This requires that max(empty set) > > be something that's smaller than everything else. > > So we give up on that. > > Do we give up? Really ? Erm, thanks. I was aware of all that below. If we're being technical what's below is talking about the sup and inf, which are not the same as max and min. More relevant to the present context, I didn't mention what's below because it doesn't seem likely that saying max([]) = -infinity and min([]) = +infinity is going to make the OP happy... > From wikipedia: http://en.wikipedia.org/wiki/Empty_set > (Uses wikipedia's LaTeX notation -- I hope those interested > are OK with that ) > > > Mathematics > > [edit] Extended real numbers > > Since the empty set has no members, when it is considered as a subset of > any ordered set, then any member of that set will be an upper bound and > lower bound for the empty set. For example, when considered as a subset > of the real numbers, with its usual ordering, represented by the real > number line, every real number is both an upper and lower bound for the > empty set.[3] When considered as a subset of the extended reals formed > by adding two "numbers" or "points" to the real numbers, namely negative > infinity, denoted -\infty\!\,, which is defined to be less than every > other extended real number, and positive infinity, denoted +\infty\!\,, > which is defined to be greater than every other extended real number, then: > > \sup\varnothing=\min(\{-\infty, +\infty \} \cup \mathbb{R})=-\infty, > > and > > \inf\varnothing=\max(\{-\infty, +\infty \} \cup \mathbb{R})=+\infty. > > That is, the least upper bound (sup or supremum) of the empty set is > negative infinity, while the greatest lower bound (inf or infimum) is > positive infinity. By analogy with the above, in the domain of the > extended reals, negative infinity is the identity element for the > maximum and supremum operators, while positive infinity is the identity > element for minimum and infimum. -- David C. Ullrich From yuma400000 at yahoo.com Sun Sep 21 13:48:00 2008 From: yuma400000 at yahoo.com (yuma) Date: Sun, 21 Sep 2008 10:48:00 -0700 (PDT) Subject: Milenko Kindl rtegdgd Message-ID: Milenko Kindl Banja Luka Banjaluka Bihac From scotballard at gmail.com Thu Sep 18 20:53:22 2008 From: scotballard at gmail.com (scottbvfx) Date: Thu, 18 Sep 2008 17:53:22 -0700 (PDT) Subject: webbrowser fragment identifier Message-ID: <0b00afc4-018f-4b80-9fba-93c253a86c7a@q5g2000prf.googlegroups.com> Hi, I'm trying to launch a web browser along with an html file with a fragment identifier in its path. I'm using the webbrowser module for this. ie. webbrowser.open('file:///C:/myfile.html#SomeEntryInTheHTML') for some reason it is truncating the path to 'file:///C:/myfile.html'. Does anyone know a way of getting the fragment identifier in there (with webbrowser module or any other)? Thanks, -Scott From nightzombie at netzero.net Fri Sep 5 10:38:37 2008 From: nightzombie at netzero.net (NightZombie) Date: Fri, 5 Sep 2008 07:38:37 -0700 (PDT) Subject: Make Games Message-ID: <50ddeb81-1c1e-4285-80ce-a0a8f7369693@t54g2000hsg.googlegroups.com> x-no-archive: yes I want to learn Python so I can make simple games. What are some good books that'll help me do this? From woaibeiyang at hotmail.com Tue Sep 2 08:47:46 2008 From: woaibeiyang at hotmail.com (woaibeiyang) Date: Tue, 2 Sep 2008 20:47:46 +0800 Subject: about downloading the selected information Message-ID: I have a problem to download the information from url http://www.ncbi.nlm.nih.gov/sites/entrez. Because it is impossible for me to add searching material to the url to construct a new url and then visit the website. I have the searching material, however I could not find the way to deal with this problem. I want to know how can I do this problem with python and which part of knowledge should I view first? Thanks! From clp at rebertia.com Sun Sep 28 15:23:22 2008 From: clp at rebertia.com (Chris Rebert) Date: Sun, 28 Sep 2008 12:23:22 -0700 Subject: Selective importing and package dependencies In-Reply-To: References: Message-ID: <47c890dc0809281223g4a87160kaa6f01b5450b587e@mail.gmail.com> On Sun, Sep 28, 2008 at 7:10 AM, David Pratt wrote: > Hi. I am in the midst of preparing a package to convert between various > schemas including orms. The issue is I don't want django, slqalchemy, storm, > rdflib etc. as hard dependencies of the package. Each module is a schema to > schema conversion. As an example, I have imports for sqlalchemy with classes > and methods that use them. > > from sqlalchemy.util import OrderedDict > from sqlalchemy import types as rdbtype > import sqlalchemy as sa > > I have my own ideas about how I might do this but looking for > recommendations from others how they would handle this so the result would > be: > > 1. no hard dependencies on any of these other packages > 2. load the module without failure. > 3. import the dependent package if available to perform the conversion Why not just catch the ImportError-s and set some variables depending on whether you were able to import the modules, e.g.: # repeat for each soft-depended module try: import django_module except ImportError: imported_django = False else: imported_django = True #later in the file if imported_django and imported_sqlalchemy: class DjangoToSqlAlchemy(object): #code that uses the django and sqlalchemy modules here Regards, Chris -- Follow the path of the Iguana... http://rebertia.com > > Many thanks > David > -- > http://mail.python.org/mailman/listinfo/python-list > From steve at REMOVE-THIS-cybersource.com.au Mon Sep 29 19:24:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Sep 2008 23:24:01 GMT Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <48da956c$0$1269$426a74cc@news.free.fr> <00eaee25$0$20666$c3e8da3@news.astraweb.com> <48e11dd4$0$20720$426a74cc@news.free.fr> Message-ID: <00f15d41$0$20617$c3e8da3@news.astraweb.com> On Mon, 29 Sep 2008 18:27:22 +0200, Bruno Desthuilliers wrote: > Lawrence D'Oliveiro a ?crit : >> In message , Ross Ridge wrote: >> >>> You need either use trial and error to find out, or look at the >>> source. >> >> So what's wrong with using the source as documentation? :) > > Don't know... Ok, having higher-level documentation (the big picture, > and quick description of what and how for classes and functions) really > helps. But when it comes to nitty-gritty details, source code is the > best documentation ever, since it's always accurate and up to date. > > FWIW, I'm often surprised by people asking questions about some > implementation detail of some open-source library or framework that are > very easily answered just looking at the source code. Reading the source > is 1/ the best way to really know how something is implemented and 2/ > usually very instructive. Reading the source code is good, but it's not a panacea. There are at least four things wrong with the advice to read the source code: (1) It's not always available. (2) Even when the source is available, it is sometimes a legal trap to read it with respect to patents and copyright. E.g. some Microsoft so- called "open" licences (but not all) allow you to read the source, but if you do then everything you program in a related field from that point is legally contaminated and could be considered a derivative work of Microsoft's software. (3) Source code not always understandable without significant effort. Code can be obfuscated, either to hide the algorithm, as an optimization, or simply because the coder is cleverer than you are. It might be in a language you don't understand (e.g. Python built-ins are written in C, not Python. I have to learn C to find out what exceptions sorted() can raise?). That's why accurate documentation should be preferred in the first place: it is easier to read and understand. It might take you hours of hard study to learn that function spam(x) raises ValueError if the argument is invalid, or two seconds to read it in the docs. Yes, documentation can fall behind the source code, but once the code is stable and the documentation has caught up and is accurate, there's no reason to re-invent the wheel by slugging through the source just to find out something already documented. (4) Even when the source code is available, legally unencumbered, in a language you understand and not too complicated for you to grasp, there's the combinatorial explosion: you may need to read and understand an arbitrarily large and complex chain of software merely to know what a single function can do. E.g. you want to know what exceptions function spam() can raise: def spam(x): a = 1 b = 2 c = ham(x) return fried_eggs(a, b, c) Now you need to understand ham() and fried_eggs(), but they aren't documented either. So you turn to their source code, and each of them call two functions, each of which call another two functions, each of which call *another* two functions... How much source code are you expected to read just to understand the four- line function spam()? -- Steven From castironpi at gmail.com Mon Sep 8 15:08:08 2008 From: castironpi at gmail.com (castironpi) Date: Mon, 8 Sep 2008 12:08:08 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> Message-ID: <5ee352aa-9ee5-4a8b-8b01-b9e6d1cc808e@m73g2000hsh.googlegroups.com> On Sep 8, 8:54?am, Boris Borcic wrote: > David C. Ullrich wrote: > > > (ii) If A is a subset of B then we should have > > max(A) <= max(B). This requires that max(empty set) > > be something that's smaller than everything else. > > So we give up on that. > > Er, what about instances of variations/elaborations on > > class Smaller(object) : __cmp__ = lambda *_ : -1 > > ? > > Cheers, BB You still don't have the property max(X) is in X. And it's the equivalent of a special builtin constant for max on the empty set. From steve at REMOVE-THIS-cybersource.com.au Wed Sep 3 21:30:14 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 01:30:14 GMT Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: <00cf3495$0$20302$c3e8da3@news.astraweb.com> On Wed, 03 Sep 2008 16:20:39 -0700, Mensanator wrote: >>>> sum([]) > 0 > > is a bug, just as it's a bug in Excel to evaluate blank cells as 0. It > should return None or throw an exception like sum([None,1]) does. You're wrong, because 99.9% of the time when users leave a blank cell in Excel, they want it to be treated as zero. Spreadsheet sum() is not the same as mathematician's sum, which doesn't have a concept of "blank cells". (But if it did, it would treat them as zero, since that's the only useful thing and mathematicians are just as much pragmatists as spreadsheet users.) The Excel code does the right thing, and your "pure" solution would do the unwanted and unexpected thing and is therefore buggy. Bugs are defined by "does the code do what the user wants it to do?", not "is it mathematically pure?". The current behaviour of sum([]) does the right thing for the 99% of the time when users expect an integer. And the rest of the time, they have to specify a starting value for the sum anyway, and so sum([], initial_value) does the right thing *always*. The only time it does the wrong thing[1] is when you forget to pass an initial value but expect a non-numeric result. And that's the programmer's error, not a function bug. [1] I believe it also does the wrong thing by refusing to sum strings, but that's another story. -- Steven From bj_666 at gmx.net Thu Sep 25 13:34:12 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Sep 2008 17:34:12 GMT Subject: text processing References: Message-ID: <6k20ckF5glpmU1@mid.uni-berlin.de> On Thu, 25 Sep 2008 15:51:28 +0100, jitenshah78 at gmail.com wrote: > I have string like follow > 12560/ABC,12567/BC,123,567,890/JK > > I want above string to group like as follow (12560,ABC) > (12567,BC) > (123,567,890,JK) > > i try regular expression i am able to get first two not the third one. > can regular expression given data in different groups Without regular expressions: def group(string): result = list() for item in string.split(','): if '/' in item: result.extend(item.split('/')) yield tuple(result) result = list() else: result.append(item) def main(): string = '12560/ABC,12567/BC,123,567,890/JK' print list(group(string)) Ciao, Marc 'BlackJack' Rintsch From not.my.email at mail.com Wed Sep 10 12:46:04 2008 From: not.my.email at mail.com (Vedran) Date: Wed, 10 Sep 2008 16:46:04 +0000 (UTC) Subject: Presenting calculation results Message-ID: Hello! I would like to present the results of the calculations on the web using Python and Apache. Currently I have java console applications that generate text files with results. Can somebody point me in the right direction from where to start? Thanks in advance! From cs at zip.com.au Thu Sep 4 23:53:44 2008 From: cs at zip.com.au (Cameron Simpson) Date: Fri, 5 Sep 2008 13:53:44 +1000 Subject: Converting .doc to .txt in Linux In-Reply-To: <0cf7e30e-1429-4d7b-b342-42319b61cff5@i24g2000prf.googlegroups.com> Message-ID: <20080905035344.GA10761@cskk.homeip.net> On 04Sep2008 12:54, patrick.waldo at gmail.com wrote: | I had previously asked a similar question, | http://groups.google.com/group/comp.lang.python/browse_thread/thread/2953d6d5d8836c4b/9dc901da63d8d059?lnk=gst&q=convert+doc+txt#9dc901da63d8d059 | | but at that point I was using Windows and now I am using Linux. | Basically, I have some .doc files that I need to convert into txt | files encoded in utf-8. However, win32com.client doesn't work in | Linux. I use the "antiword" or "catdoc" commands to convert .doc to text. Call them from popen or subprocess from Python, if you must use Python (I'd just write a shell script for such a task myself unless its embedded in a larger python context). Cheers, -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ Please do not send me Microsoft Word files. http://en.nothingisreal.com/wiki/Please_don't_send_me_Microsoft_Word_documents From sturlamolden at yahoo.no Tue Sep 23 19:05:33 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 16:05:33 -0700 (PDT) Subject: Python is slow? References: <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> Message-ID: On Sep 23, 8:52?pm, bearophileH... at lycos.com wrote: > Is this a good or bad thing? ;-) It seems we have been implementing different algorithms. kd-trees are not BK-trees. http://www.scipy.org/Cookbook/KDTree From aioe.org at technicalbloke.com Wed Sep 17 13:12:29 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 13:12:29 -0400 Subject: Client server implementation References: <7d623ffb-2936-4aec-a74a-e9f5489e6657@p25g2000hsf.googlegroups.com> <708b9a1e-f4df-4d9c-8daa-cf77900acda4@s20g2000prd.googlegroups.com> Message-ID: Babloo wrote: > On Sep 16, 7:38 am, Benjamin wrote: >> On Sep 15, 5:15 am, Babloo wrote: >> >>> Hi everyone, >>> i wanted to implement a client- server connection >>> and transfer a file over the network. i was able to implement a normal >>> set up where in i was able to send chat messages and small chunks of >>> data. >>> I want to implement the file transfer with out using the FTP library >>> available in python . >>> So can anyone suggest a piece of code by which i can >>> do that. >> I don't know what you really want, but look at Twisted.http://twistedmatrix.com >> >> >> >>> Thanks >>> Pruthvi >> > I am beginner at using python language. > I mean i am implementing that in a windows based machine and wanted > to transfer files over the LAN. I have written down two files as > client.py and server.py . I ran these files at two different Computers > in the LAN and I was able to send small chunks of messages( like > chat). > > I was successful in establishing connection and sending small > messages. But now i want to transfer a complete file with out using > the ftplib(FTP LIBRARY) in python. > > > The files look like this.i hope this would help. > > ______________________________________________ > # Server program > > from socket import * > > # Set the socket parameters > host = "117.105.224.94" > port = 21567 > buf = 1024 > addr = (host,port) > > # Create socket and bind to address > UDPSock = socket(AF_INET,SOCK_DGRAM) > UDPSock.bind(addr) > > # Receive messages > while 1: > data,addr = UDPSock.recvfrom(buf) > if not data: > print "Client has exited!" > break > else: > print "\nReceived message '", data,"'" > > # Close socket > UDPSock.close() > __________________________________________________ > > # Client program > > from socket import * > > # Set the socket parameters > host = "117.105.224.94" > port = 21567 > buf = 1024 > addr = (host,port) > > # Create socket > UDPSock = socket(AF_INET,SOCK_DGRAM) > > def_msg = "===Enter message to send to server==="; > print "\n",def_msg > > # Send messages > while (1): > data = raw_input('>> ') > if not data: > break > else: > if(UDPSock.sendto(data,addr)): > print "Sending message '",data,"'....." > > # Close socket > UDPSock.close() > > _____________________________________________________________ > You're really not far away then, you basically need to come up with a simple protocol that can transmit 1) The file name 2) The file length 3) The file data itself You could also transmit the files metadata: datestamps, permissions etc if you wanted to make it better. Also, there might be security issues to consider too if you're running this on anything other than your own home network. So anyway, for a simple solution howabout you send: filename + "\n" filesize + "\n" (make sure you use str() to send this as text) Then loop through your filedata send a chunk wait for an OK back from the other side loop At the receiving end as the chunks arrive: Get the filename Open a file for writing Get the filesize Setup a loop to receive the file data Send OK Get chunk from socket Write data to file Break (stop) if filesize reached Loop Close file This, of course has no error correction and will probably die if you have any packet loss on your network, a more robust solution would be to use TCP sockets rather than UDP sockets. Hope this helps :-) Roger Heathcote http://www.technicalbloke.com http://movingtoubuntu.technicalbloke.co.uk From jitenshah78 at gmail.com Fri Sep 26 05:47:35 2008 From: jitenshah78 at gmail.com (jitenshah78 at gmail.com) Date: Fri, 26 Sep 2008 10:47:35 +0100 Subject: text processing SOLVED Message-ID: <48DCAFB7.4060409@gmail.com> Thanks Black Jack Working From monuindia at gmail.com Thu Sep 11 14:19:07 2008 From: monuindia at gmail.com (Monu) Date: Thu, 11 Sep 2008 11:19:07 -0700 (PDT) Subject: shelve file name extention References: Message-ID: On Sep 8, 1:47?pm, s... at pobox.com wrote: > ? ? Monu> When I am using shelve on my local machine it generates the db > ? ? Monu> file as given filename. But in another machine it's generating > ? ? Monu> .dat and .dir. ?can anyone tell me how can I force sheve > ? ? Monu> module to write the db in .dir and .dat, > ? ? Monu> instead of ? Do I have to install a specific version of > ? ? Monu> the python? > > Shelve is just a thin layer on top of a concrete db file module. ?Sounds > like on your two machines there are different underlying db file modules > available. ?You're pretty much at the mercy of those modules as to file > naming. ?All you are giving it when opening a shelve file is the prefix. > > Skip Thanks Skip. So Can't I choose which module to use. Is there any preferance on which shelve chooses these modules? From ivanov.maxim at gmail.com Sat Sep 27 18:29:45 2008 From: ivanov.maxim at gmail.com (redbaron) Date: Sat, 27 Sep 2008 15:29:45 -0700 (PDT) Subject: multiprocessing eats memory References: <0a65effc-0e4c-4901-9500-8455d92e2145@d70g2000hsc.googlegroups.com> <02522a54-40ad-46a7-acb9-544f2fa5998f@d70g2000hsc.googlegroups.com> Message-ID: <11c7a862-12bb-4d92-987d-8b548251ffb5@y38g2000hsy.googlegroups.com> > When processing data in parallel you will use up as muchmemoryas > many datasets you are processing at any given time. Worker processes eats 2-4 times more than I pass to them. >If you need to > reducememoryuse then you need to start fewer processes and use some > mechanism to distribute the work on them as they become free. (see > recommendation that uses Queues) I don't understand how could I use Queue here? If worker process finish computing, it puts its' id into Queue, in main process I retrieve that id and how could I retrieve result from worker process then? From gagsl-py2 at yahoo.com.ar Fri Sep 5 00:21:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 01:21:56 -0300 Subject: Is it possible to download only the of a web page? References: Message-ID: En Thu, 04 Sep 2008 18:53:33 -0300, Fredrik Lundh escribi?: > Rex wrote: > >> I am writing a script that executes a bunch of queries through a form >> on a website and reads the results. I am only interested in the >> section in the <head> of each web page. Currently, each page >> the server returns is about 100kb and contains a bunch of HTML and >> Javascript, all of which I don't need; I don't want to waste bandwidth >> or consume too much of the server's resources. I just need the <title> >> string. > > you need to issue a GET request to get the HTML head section, which > almost always means that the server will build the entire page before > sending it to you (so it can set content-length etc). > > you can save on network traffic by parsing the data as it arrives, and > stopping when you've gotten the TITLE element: > > http://effbot.org/librarybook/sgmllib.htm Another alternative would be to estimate the size it takes to reach to the <title> tag, and issue a GET with a Range header. The server will -very likely- have to build the entire page, but won't attempt to send more bytes than requested. (In case the requested size is not enough, one can issue another GET asking for more data) http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 -- Gabriel Genellina From grante at visi.com Tue Sep 30 20:44:40 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 30 Sep 2008 19:44:40 -0500 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <6kev3fF7l2r7U1@mid.individual.net> <LeadndG5x5LC0X_VnZ2dnUVZ_qHinZ2d@posted.visi> <00f2b214$0$20617$c3e8da3@news.astraweb.com> Message-ID: <lb6dnY1bn_xlWn_VnZ2dnUVZ_g-dnZ2d@posted.usinternet> On 2008-09-30, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote: > On Tue, 30 Sep 2008 10:57:19 -0500, Grant Edwards wrote: > >>>> How would the python equivalent go ? >> >> You would drag yourself out of the 1960s, install numpy, and >> then do something like this: > > I think that was thoughtlessly rude to somebody who is asking > a perfectly reasonable question. Sheesh. I guess I should have added a smiley face. So much for trying to be helpful. -- Grant From Lie.1296 at gmail.com Thu Sep 25 06:03:59 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 25 Sep 2008 03:03:59 -0700 (PDT) Subject: translating ascii to binary References: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> <e9d5277e-11f2-4fb1-b916-2558fd318223@i20g2000prf.googlegroups.com> <mailman.1173.1221669327.3487.python-list@python.org> Message-ID: <bd0d9fb2-f333-4677-b780-ceb65f635d59@s20g2000prd.googlegroups.com> On Sep 17, 11:34?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > Lie wrote: > >> Any advice about this matter would be very appreciated. > >> Thanks in advance. > > > It'd be easier to make a one-char version of ascii2bin then make the > > string version based on the one-char version. > > And it'd be a lot easier to read your posts if you trimmed away at least > some of the original message before posting. ?If you cannot do that for > some technical reason, I recommend using top-posting instead. > > </F> Ah.. yes, sorry for that, I had never thought about that since I use Google Groups, which automatically trim long quotes, to access the list. From gagsl-py2 at yahoo.com.ar Thu Sep 4 23:55:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 05 Sep 2008 00:55:53 -0300 Subject: pdb bug and questions References: <48C051AA.5090002@gmail.com> Message-ID: <op.ugzo7fdhx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 04 Sep 2008 18:22:50 -0300, Stef Mientki <stef.mientki at gmail.com> escribi?: (Sorry, I cannot help you with your main question) > When I launch the debugger ( winXP, Python 2.5) from with my editor > python -u -m pdb D:\\Data\\test_IDE.py > I get this error > IOError: (2, 'No such file or directory', 'D:\\Data\test_IDE.py') > NOTICE 1 backslash ----------------------------------^ > > If I launch the debugger with > python -u -m pdb D:/Data/test_IDE.py > It runs fine. How do you launch the debugger from your editor? The "python -u -m ..." is a command line, and should contain D:\Data\test_IDE.py (with backslashes). Read your editor's documentation on how to put those backslashes there. Python doesn't process or "cook" the arguments in any way, whatever the editor passes in the command line, is what Python will get as arguments. > Although I mostly use os.path.join to be OS independent, > these kind of bugs give me the impression, > that I can better do the join myself and always use forward slashes. > Is this a valid conclusion ? Not directly from this evidence - the issue is not directly related to Python. I'd use the generic path functions in os.path - like os.path.join, split, splitext, dirname, basename... The / separator may work most of the time on Windows, but not always, and it is not universal. Look at this file path in VMS: cdrom2:[dir1.dir2.dir3]filename.ext;24 -- Gabriel Genellina From daniel.watrous at gmail.com Tue Sep 30 18:44:51 2008 From: daniel.watrous at gmail.com (Daniel) Date: Tue, 30 Sep 2008 15:44:51 -0700 (PDT) Subject: problem with "ImportError: No module named..." and sockets References: <ff3e92a2-c35d-41da-bcb6-0e6f33b46e4d@f63g2000hsf.googlegroups.com> <mailman.1792.1222813069.3487.python-list@python.org> Message-ID: <d3821d42-486b-4dde-8073-4b925e619c47@z72g2000hsb.googlegroups.com> On Sep 30, 4:17?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Tue, 30 Sep 2008 18:38:19 -0300, Daniel <daniel.watr... at gmail.com> ? > escribi?: > > > > > [BEGIN CODE] > > #!/usr/bin/python > > import SocketServer > > import os, sys > > newpath = os.path.normpath( os.path.join( __file__, "../../.." )) > > sys.path.insert(0, newpath) > > > from pop.command.UpdateCommand import * > > import cPickle > > > Traceback (most recent call last): > > [...] > > ImportError: No module named UpdateCommand > > > I import the module at the top of the file server.py, but it doesn't > > throw the ImportError until it tries to unpickle. > > Notice that you don't import the UpdateCommand module - you import all ? > names defined inside it instead. It's not the same thing. > Seehttp://effbot.org/zone/import-confusion.htm > > -- > Gabriel Genellina Thank you Gabriel, The class inside that module has the same name, UpdateCommand. Since this is the object that was pickled, it should be available to the unpickle command. I already understood the difference between import methods and I think I'm covered. I did just try "import pop.command.TesterUpdateCommand" instead and I get the same error. From gagsl-py2 at yahoo.com.ar Tue Sep 2 04:36:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 05:36:33 -0300 Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> Message-ID: <op.uguh670px6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 01 Sep 2008 04:23:38 -0300, Jeremy Banks <jeremy at jeremybanks.ca> escribi?: > Hi. I wondered if anyone knew the rationale behind the naming of the > Popen class in the subprocess module. Popen sounds like the a suitable > name for a function that created a subprocess, but the object itself is > a subprocess, not a "popen". It seems that it would be more accurate to > just name the class Subprocess, can anyone explain why this is not the > case? I have no idea - but I agree, Subprocess would have been a better name. -- Gabriel Genellina From grante at visi.com Mon Sep 1 10:08:05 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 01 Sep 2008 09:08:05 -0500 Subject: How Compute # of Days between Two Dates? References: <JAIuk.19687$cW3.19527@nlpi064.nbdc.sbc.com> Message-ID: <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: > That's the question in Subject. For example, the difference between > 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and > 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in > years between, say, 1990 and 2050. In other words not some really strange > period of time well outside our current era of history. Does the standard library's datetime module not do what you want? http://docs.python.org/lib/module-datetime.html -- Grant From adykes at panix.com Sat Sep 13 18:24:40 2008 From: adykes at panix.com (Al Dykes) Date: 13 Sep 2008 18:24:40 -0400 Subject: Code example that will make a Skype connection? References: <gaghj3$4tf$1@panix5.panix.com> <mailman.980.1221320529.3487.python-list@python.org> Message-ID: <gahej8$ooi$1@panix5.panix.com> In article <mailman.980.1221320529.3487.python-list at python.org>, Marco Bizzarri <marco.bizzarri at gmail.com> wrote: >On Sat, Sep 13, 2008 at 4:09 PM, Al Dykes <adykes at panix.com> wrote: >> >> Can some post a Python code fragment that will to make a PC with Skpye >> installed to make a Skype call, given a valid phone # string. >> >> I'm not asking for code that handles the audio once the connection is >> made. >> >> > >Maybe you can find this useful? > > >https://developer.skype.com/wiki/Skype4Py/examples/s4p_call_py > > >Regards >Marco Thanks for helping me get started. I'm new to Skype and Python. -- Al Dykes News is something someone wants to suppress, everything else is advertising. - Lord Northcliffe, publisher of the Daily Mail From coolkid246 at googlemail.com Thu Sep 4 06:10:13 2008 From: coolkid246 at googlemail.com (coolkid246 at googlemail.com) Date: Thu, 4 Sep 2008 03:10:13 -0700 (PDT) Subject: =?ISO-8859-1?Q?sofortkredit_online_in_Ulm_online_sofort_kredite_kre?= =?ISO-8859-1?Q?dit_ohne_schufa_selbstaendig_bargeld_eilkredite_guenstige_on?= =?ISO-8859-1?Q?line_kredit__=2B_=2B_=2B_=2B_=2B=2B=2B_GUENSTIGE_KREDITE_ONLINE_=2B=2B=2B_KREDIT?= =?ISO-8859-1?Q?E_IM_INTERNET_OHNE_SCHUFA_=2B=2B=2B_=2B_=2B_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D?= =?ISO-8859-1?Q?244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKRE?= =?ISO-8859-1?Q?DITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_ht?= =?ISO-8859-1?Q?tp=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D?= =?ISO-8859-1?Q?244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKRE?= =?ISO-8859-1?Q?DITE=2DONLINE=2D244=2EINFO=2F_http=3A=2F=2FWWW=2EKREDITE=2DONLINE=2D244=2EINFO=2F_=2B_?= =?ISO-8859-1?Q?=2B_=2B_=2B_______________________kredite_schufafrei_kreditkarte_o?= =?ISO-8859-1?Q?hne_schufa_in_Ebersberg_schufa_freie_kredite_online_credit_o?= =?ISO-8859-1?Q?hne_in_Paderborn_kreditrechner_kredit_vergleich_in_Herzberg_?= =?ISO-8859-1?Q?online_kredite_oesterreich_kredit_mit_in_Detmold_arbeitslos_?= =?ISO-8859-1?Q?kredite_schweizer_kredite_in_Haldensleben_kleinkredit_sofort?= =?ISO-8859-1?Q?_kredite_ohne_schufa_auskunft_in_Segeberg_kredit_ohne_schufa?= =?ISO-8859-1?Q?_test_guenstiger_online_kredit_in_Emmendingen_online_kredit_?= =?ISO-8859-1?Q?mit_schufa_schufafreier_kredit_in_L=FCbbecke_kredit_ohne_schu?= =?ISO-8859-1?Q?fa_vergleich_kredite_selbstaendige_in_Kamenz____=2D_kredite_sc?= =?ISO-8859-1?Q?hufafrei_kredite_ohne_schufa_serioes_in_Rosenheim_=2D_online_k?= =?ISO-8859-1?Q?redit_direkt_online_kredite_ohne_schufa_in_Winsen_=2D_online=2Dk?= =?ISO-8859-1?Q?redite_kredite_rechner_in_Kirchheimbolanden_=2D_online_kredite?= =?ISO-8859-1?Q?_oesterreich_online_kredite_mit_sofortzusage_in_Koblenz_=2D_bi?= =?ISO-8859-1?Q?llig_kredit_ohne_schufa_kredit_uni_in_Ratzeburg_=2D_kredit_sch?= =?ISO-8859-1?Q?ufa_sofortkredit_ohne_auskunft_in_Bad_Neustadt_a=2Ed=2E_Saale_=2D_?= =?ISO-8859-1?Q?kredit_rechner_online_kredit_ohne_schufa_auskunft_in_Marienb?= =?ISO-8859-1?Q?erg_=2D_beamtenkredit_Guenstige_Kredide_online_ohne_SCHUFA_in_?= =?ISO-8859-1?Q?L=FCbben_=2D_kredit_sofortzusage_finanzierung_ohne_schufa_in_Ba?= =?ISO-8859-1?Q?utzen_=2D_credit_ohne_schufa_online_sofort_kredite_in_Lauterba?= =?ISO-8859-1?Q?ch_=2D_online_kredite_privat_online_kredit_de_in_Dillingen_=2D_k?= =?ISO-8859-1?Q?redit_von_privat_ohne_schufa_kredit_ohne_bonitaet_in_Bitburg?= =?ISO-8859-1?Q?_=2D_kredite_sofortzusage_darlehen_kredit_in_Neustadt_=2D_kredit?= =?ISO-8859-1?Q?e_schufa_kredite_schufafrei_in_Ostprignitz?= Message-ID: <f7729d35-6c4c-4b2a-b73e-17a681e6077e@w24g2000prd.googlegroups.com> sofortkredit online in Ulm online sofort kredite kredit ohne schufa selbstaendig bargeld eilkredite guenstige online kredit + + + + +++ GUENSTIGE KREDITE ONLINE +++ KREDITE IM INTERNET OHNE SCHUFA +++ + + http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ http://WWW.KREDITE-ONLINE-244.INFO/ + + + + kredite schufafrei kreditkarte ohne schufa in Ebersberg schufa freie kredite online credit ohne in Paderborn kreditrechner kredit vergleich in Herzberg online kredite oesterreich kredit mit in Detmold arbeitslos kredite schweizer kredite in Haldensleben kleinkredit sofort kredite ohne schufa auskunft in Segeberg kredit ohne schufa test guenstiger online kredit in Emmendingen online kredit mit schufa schufafreier kredit in L?bbecke kredit ohne schufa vergleich kredite selbstaendige in Kamenz - kredite schufafrei kredite ohne schufa serioes in Rosenheim - online kredit direkt online kredite ohne schufa in Winsen - online-kredite kredite rechner in Kirchheimbolanden - online kredite oesterreich online kredite mit sofortzusage in Koblenz - billig kredit ohne schufa kredit uni in Ratzeburg - kredit schufa sofortkredit ohne auskunft in Bad Neustadt a.d. Saale - kredit rechner online kredit ohne schufa auskunft in Marienberg - beamtenkredit Guenstige Kredide online ohne SCHUFA in L?bben - kredit sofortzusage finanzierung ohne schufa in Bautzen - credit ohne schufa online sofort kredite in Lauterbach - online kredite privat online kredit de in Dillingen - kredit von privat ohne schufa kredit ohne bonitaet in Bitburg - kredite sofortzusage darlehen kredit in Neustadt - kredite schufa kredite schufafrei in Ostprignitz From bignose+hates-spam at benfinney.id.au Tue Sep 23 20:58:21 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 24 Sep 2008 10:58:21 +1000 Subject: python syntax for conditional is unfortunate References: <mailman.1438.1222215919.3487.python-list@python.org> Message-ID: <87bpyez7f6.fsf@benfinney.id.au> Cameron Simpson <cs at zip.com.au> writes: > A good coder will present things clearly. For trivial stuff the one > line form may be fine, and for longer stuff then this: > > y = some thing or other \ > if x \ > else something_else Parentheses are usually more robust for multi-line, where possible: foo = (bar if some_condition() else baz) The lines can more easily be edited and rearranged without fiddling with backslashes at the end of every line. (For even more robustness at the cost of space, separate the parentheses so they're on separate lines from what they enclose.) It also addresses the original poster's complaint that there's no early signal of the compound nature of the expression: the opening parenthesis signals this. -- \ ?It is far better to grasp the universe as it really is than to | `\ persist in delusion, however satisfying and reassuring.? ?Carl | _o__) Sagan | Ben Finney From m_palmer45 at yahoo.ca Mon Sep 22 22:14:04 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 22 Sep 2008 19:14:04 -0700 (PDT) Subject: Why no tailcall-optimization? References: <3095064f-8f7e-4af0-af9e-6d48510f9e69@a70g2000hsh.googlegroups.com> Message-ID: <6c43c41d-6a4b-4391-9570-3c1497b7253b@m36g2000hse.googlegroups.com> On Sep 22, 9:13 pm, process <circularf... at gmail.com> wrote: > Why doesn't Python optimize tailcalls? Are there plans for it? > > I know GvR dislikes some of the functional additions like reduce and > Python is supposedly about "one preferrable way of doing things" but > not being able to use recursion properly is just a big pain in the > a**. There are some attempts, see for example http://code.activestate.com/recipes/496691/ From mnations at gmail.com Fri Sep 5 10:37:48 2008 From: mnations at gmail.com (Mudcat) Date: Fri, 5 Sep 2008 07:37:48 -0700 (PDT) Subject: Python test case management system? References: <b7033321-db3e-4872-b928-f9a07db79918@f63g2000hsf.googlegroups.com> <87iqtbmm4e.fsf@benfinney.id.au> Message-ID: <1790bd7f-bbfb-427e-9085-96df497fdbf1@b1g2000hsg.googlegroups.com> > What would the behaviour of such a system be? In other words, what is > a "test case management system" in terms of the things that it does? The feature set for one tends to vary. In short it's a front end app which is tied to a db that stores and organizes test cases. The system will allow you to select and execute test cases based on different criteria which will then log and store the results. They aren't extremely complicated however they do need to have a well-built execution engine that are multi-threaded and can handle several different things at the same time. From lists at cheimes.de Sat Sep 20 21:06:40 2008 From: lists at cheimes.de (Christian Heimes) Date: Sun, 21 Sep 2008 03:06:40 +0200 Subject: Not fully OO ? In-Reply-To: <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> Message-ID: <gb46mu$bkm$1@ger.gmane.org> Kay Schluehr wrote: > Actually it is simply wrong in the mentioned case and here is the > proof: > > def foo(): > return 2+2 > > import dis > dis.dis(foo) > > 2 0 LOAD_CONST 2 (4) > 3 RETURN_VALUE > > OO is a heuristic method used to understand the semantics of a > programming language. It can also inspire language design but as > you've rightly said: jugde yourself and see how far you get with it. It's not wrong. You have found a simple optimization. Lot's of compilers for lots of languages optimize code by code folding. Python's peephole optimizer replaces code like 2+2 with 4. Christian From justin.kuto at gmail.com Mon Sep 29 11:06:28 2008 From: justin.kuto at gmail.com (afrogazer) Date: Mon, 29 Sep 2008 08:06:28 -0700 (PDT) Subject: Web programming in Python. References: <eb5978f8-e802-48d2-a61f-207c25ac7059@y21g2000hsf.googlegroups.com> Message-ID: <e58bd1ec-555f-40a9-bcc4-f7225608c900@8g2000hse.googlegroups.com> Not to be a condescending, but there are a lot of manuals out there on how to do this and asking on a forum would really not be the best way to get started. Do some research and some reading and you should be up and running in a short time. You can ask questions on the forum if you have difficulties while/after reading. Good luck From castironpi at gmail.com Sat Sep 20 22:11:22 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sat, 20 Sep 2008 19:11:22 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> <mailman.1316.1221959218.3487.python-list@python.org> Message-ID: <a8438bbf-044a-4429-8ea9-7417daf68ef4@l42g2000hsc.googlegroups.com> On Sep 20, 8:06?pm, Christian Heimes <li... at cheimes.de> wrote: > Kay Schluehr wrote: > > Actually it is simply wrong in the mentioned case and here is the > > proof: > > > def foo(): > > ? ? return 2+2 > > > import dis > > dis.dis(foo) > > > ? 2 ? ? ? ? ? 0 LOAD_CONST ? ? ? ? ? ? ? 2 (4) > > ? ? ? ? ? ? ? 3 RETURN_VALUE > > > OO is a heuristic method used to understand the semantics of a > > programming language. It can also inspire language design but as > > you've rightly said: jugde yourself and see how far you get with it. > > It's not wrong. The meaning of the Python program is, internally, on a cycle-by-cycle basis, "Object 2; send add( Object 2 ) to Object 2; Return object 4." CPython doesn't do this, but due to the fact that there are no cases in which that distinction affects the output, it's still an implementation of Python. Or at least, a practical implementation. > You have found a simple optimization. Lot's of compilers > for lots of languages optimize code by code folding. > > Python's peephole optimizer replaces code like 2+2 with 4. > > Christian From straton at lampsacos.demon.co.uk Sat Sep 6 08:37:09 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sat, 06 Sep 2008 13:37:09 +0100 Subject: max(), sum(), next() In-Reply-To: <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <859b334d-777e-4f17-87c6-b01a4ff0014a@m3g2000hsc.googlegroups.com> Message-ID: <g9tti1$8r$1$8300dec7@news.demon.co.uk> castironpi wrote: > On Sep 5, 9:20 pm, "Manu Hack" <manuh... at gmail.com> wrote: >> On Fri, Sep 5, 2008 at 1:04 PM, castironpi <castiro... at gmail.com> wrote: >>> On Sep 5, 3:28 am, "Manu Hack" <manuh... at gmail.com> wrote: >>>> On Thu, Sep 4, 2008 at 4:25 PM, castironpi <castiro... at gmail.com> wrote: >>>>> On Sep 4, 2:42 pm, bearophileH... at lycos.com wrote: >>>>>> David C. Ullrich: >>>>>>> At least in mathematics, the sum of the elements of >>>>>>> the empty set _is_ 0, while the maximum element of the >>>>>>> empty set is undefined. >>>>>> What do you think about my idea of adding that 'default' argument to >>>>>> the max()/min() functions? >>>>>> Bye, >>>>>> bearophile >>>>> For max and min, why can't you just add your argument to the set >>>>> itself? >>>>> The reason max([]) is undefined is that max( S ) is in S. >>>> It makes sense. >>>>> The reason sum([]) is 0 is that sum( [ x ] ) - x = 0. >>>> It doesn't make sense to me. What do you set x to? >>> For all x. >> But then how can you conclude sum([]) = 0 from there? It's way far >> from obvious. > > You can define sum([a1,a2,...,aN]) recursively as > sum([a1,a2,...a(N-1)])+aN. Call the sum sum([a1,a2,...,aN]) "X", then > subtract aN. > > sum([a1,a2,...a(N-1)])+aN=X > sum([a1,a2,...a(N-1)])+aN-aN=X-aN > > For N=2, we have: > > sum([a1,a2])=X > sum([a1,a2])-a2=X-a2 > sum([a1,a2])-a2-a1=X-a2-a1 > > Since X= a1+ a2, replace X. > > sum([a1,a2])-a2-a1=(a1+a2)-a2-a1 > > Or, > > sum([a1,a2])-a2-a1=0 > > Apply the recursive definition: > > sum([a1])+a2-a2-a1=0 > > And again: > > sum([])+a1+a2-a2-a1=0 > > And we have: > > sum([])=0. > This is not necessarily so. The flaw is that you provide a recursive definition with no start value, which is to say it is not a recursive definition at all. A recursive definition should be (for lists where elements can be added, and ignoring pythonic negative indexing): Define 'sum(L)' by a. sum(L[0]) = L[0] b. sum(L[0:i]) = sum(L[0:i-1]) + L[i] ... if i > 0 From this you can prove the reverse recursion sum{L[0:k]) = sum(L[0:k+1]) - L[k+1] __only__ if k >= 0 It says nothing about the empty list. You could add, as part of the definition, that sum{[]) = 0, or any other value. A rather different approach, not quite simple recursion, would be to start with A. a slicing axiom, something like: for all non-negative integers, a,b,c with a <=b <= c: sum(L[a:c]) = sum(L[a:b]) + sum(L[b:c]) B. a singleton axiom: for all integers a where L[a] exists: sum(L[a:a]) = L[a] 2a. sum{ From maric at aristote.info Mon Sep 15 10:17:42 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 16:17:42 +0200 Subject: Representation of python code ? In-Reply-To: <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> References: <7F0503CD69378F49BE0DC30661C6CCF6022A6A56@enbmail01.lsi.com> <mailman.1037.1221478736.3487.python-list@python.org> <95fb2e1e-fde0-4a3c-9c3e-45a62e8d6b25@k36g2000pri.googlegroups.com> Message-ID: <200809151617.42396.maric@aristote.info> Le Monday 15 September 2008 16:06:19 showellshowell at gmail.com, vous avez ?crit?: > I'm not sure this is the best counterexample. ?You can see statically > that A potentially creates an instance of the B class. > > > class A : > > ? ? def __init__(self) : > > ? ? ? ? ?self._b = B() > > > > class B : pass Yes, you can, but are you sure it's obvious that B in A.__init__ is the class you think of ? -- _____________ Maric Michaud From tino at wildenhain.de Fri Sep 26 05:37:51 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 11:37:51 +0200 Subject: How to parse a string completely into a list In-Reply-To: <e5d72ac8-0f92-4080-9e6b-34289bc52564@p31g2000prf.googlegroups.com> References: <e9e4f5c7-3467-4078-a401-fb732d69cc64@a3g2000prm.googlegroups.com> <mailman.1479.1222314277.3487.python-list@python.org> <663207a8-e48c-40cb-86f5-4f650eaeda1e@a18g2000pra.googlegroups.com> <mailman.1480.1222315955.3487.python-list@python.org> <64627edc-773f-4981-a116-cff96f93a04c@w1g2000prk.googlegroups.com> <mailman.1481.1222329107.3487.python-list@python.org> <e5d72ac8-0f92-4080-9e6b-34289bc52564@p31g2000prf.googlegroups.com> Message-ID: <48DCAD6F.5000805@wildenhain.de> john.ford at colorado.edu wrote: ... > > Ahh, but I forgot to mention that I have to mark the path I took in > the string. So using list() and then join() are my best options. Still you would not need to create a list out of the string on your way. Just append the stepstone chars to a new list during your walk. Hoewever it entirely depends on your algorithm. Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/153771be/attachment-0001.bin> From ldo at geek-central.gen.new_zealand Sun Sep 28 02:05:21 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sun, 28 Sep 2008 19:05:21 +1300 Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <gbh2sa$9j1$1@lust.ihug.co.nz> <mailman.1515.1222382168.3487.python-list@python.org> Message-ID: <gbn6r1$r5j$5@lust.ihug.co.nz> In message <mailman.1515.1222382168.3487.python-list at python.org>, James Mills wrote: > On Fri, Sep 26, 2008 at 8:20 AM, Lawrence D'Oliveiro > <ldo at geek-central.gen.new_zealand> wrote: > >> Object orientation IS procedural. > > Correction: OOP is Imperative. No, "procedural". The functional unit is called an "expression", the encapsulation of which is called a "function". Hence "functional". Similarly, the procedural unit is commonly called a "statement", the encapsulation of which is a "procedure", not an "imperator". Hence "procedural". From electronixtar at gmail.com Sun Sep 28 07:17:39 2008 From: electronixtar at gmail.com (est) Date: Sun, 28 Sep 2008 04:17:39 -0700 (PDT) Subject: str() should convert ANY object to a string without EXCEPTIONS ! References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> <gbn6nu$r5j$4@lust.ihug.co.nz> <10007f2c-f554-4e62-b28a-3899603d7dee@p31g2000prf.googlegroups.com> <6f247162-b0b7-4fba-bfd8-df9261cc5d30@p31g2000prf.googlegroups.com> Message-ID: <5412f9e0-a363-4c8a-a85c-d7bff4e02edd@l33g2000pri.googlegroups.com> On Sep 28, 7:12?pm, Lie <Lie.1... at gmail.com> wrote: > On Sep 28, 3:35?pm, est <electronix... at gmail.com> wrote: > > > > Because that's how ASCII is defined. > > > Because that's how ASCII is defined. ?ASCII is a 7-bit code. > > > Then why can't python use another default encoding internally > > range(256)? > > > > Python refuses to guess and tries the lowest common denominator -- ASCII -- instead. > > > That's the problem. ASCII is INCOMPLETE! > > What do you propose? Use mbsc and smack out linux computers? Use KOI > and make non-Russians suicide? Use GB and shot dead non-Chinese? Use > latin-1 and make emails servers scream? > > > If Python choose another default encoding which handles range(256), > > 80% of python unicode encoding problems are gone. > > > It's not HARD to process unicode, it's just python & python community > > refuse to correct it. > > Python's unicode support is already correct. Only your brainwave have > not been tuned to it yet. > > > > stop dreaming of a magic solution > > > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, > > what's wrong???? > > > > Isn't that more or less the same as telling the OP to use unicode() instead of str()? > > > sockets could handle str() only. If you throw unicode objects to a > > socket, it will automatically call str() and cause an error. Have you ever programmed with CJK characters before? From deets at nospam.web.de Sat Sep 6 09:06:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 06 Sep 2008 15:06:08 +0200 Subject: embed python in ms-word? In-Reply-To: <mailman.609.1220705553.3487.python-list@python.org> References: <mailman.609.1220705553.3487.python-list@python.org> Message-ID: <6ifdi0FptetbU1@mid.uni-berlin.de> oyster schrieb: > in fact, during my work, I often write documnets in ms-word. But the > doc has many numbers in it, which need to be calculated and to be > modified frequently. > > Is there a method to write a ms-word add-in, so that > 1.I can type in the calculation steps in some program language, > please have a look at http://blender.bokee.com/inc/word_add_in1.jpg > > 2.then the result (here, it is 8) is shown in the doc when I close this window? > please have a look at http://blender.bokee.com/inc/word_add_in2.jpg > > 3.when I double-click the result 8, I can view/edit the code again > > 4.the code for calculation is stored in DOC file too, I can change it later > > mathtype equation is a kind of such thing, but only for displaying > nice equation > > I don't think vba is a good answer, the main reason is: the vba code > has an incompact link with its result in the documnet I don't know what you mean with the last sentence - but I still think VBA is the answer. There is no other way to write a plugin or some such for word than using COM, and VB *is* COM. So whatever you can do in Word, it's exposed in VBA. Bringing python into the mixture is just creating a lot of hassle. Automating word with Python is a different thing - that seems to be popular and powerful. Diez From sturlamolden at yahoo.no Wed Sep 24 17:25:11 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 24 Sep 2008 14:25:11 -0700 (PDT) Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <gbe6qk$b54$1@aioe.org> <Xns9B23DFA195833duncanbooth@127.0.0.1> Message-ID: <d57f3edc-a305-4165-bafb-d0d75bb54948@z72g2000hsb.googlegroups.com> On Sep 24, 10:59?pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote: > Simple LINQ expressions like the one you gave map easily to Python list > comprehensions. What Microsoft have done though is provide a consistent > implementation which allows you to write complex SQL like expressions which > will work identically on databases or most other sequence types. > han extensions to syntax. List comprehensions work with any iterable sequence. You can nest them to make more complex statements. You can also use a generator to iterate through a database or an XML document. Here is approximately where linq stops being a marvelous addition to Python. And I can honestly do without the SQL syntax. From presence at MUNGEpanix.com Sun Sep 28 17:28:47 2008 From: presence at MUNGEpanix.com (Cydrome Leader) Date: Sun, 28 Sep 2008 21:28:47 +0000 (UTC) Subject: Hello boys! References: <22a4d7d0-9553-467b-ac8a-02add0f6fc44@o40g2000prn.googlegroups.com> <f1dtd45fij5nu9uvnico53cab73uj6pdev@4ax.com> <3getd41j8opbkt73stg7hl52dgjpurcv85@4ax.com> <gbmelr$nhh$4@reader1.panix.com> <7qmtd4hc52o84pksc6tni0pmgnfvpvf08m@4ax.com> Message-ID: <gbosuf$ojh$2@reader1.panix.com> In rec.crafts.metalworking default <default at defaulter.net> wrote: > On Sat, 27 Sep 2008 23:12:59 +0000 (UTC), Cydrome Leader > <presence at MUNGEpanix.com> wrote: > >>In rec.crafts.metalworking Jim Thompson <To-Email-Use-The-Envelope-Icon at my-web-site.com> wrote: >>> >>> On Sat, 27 Sep 2008 18:47:16 -0400, default <default at defaulter.net> >>> wrote: >>> >>>>On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko >>>><milenko.stojadinovic at googlemail.com> wrote: >>>> >>>>>Hello, this is Milenko Stojadinovic from town Banjaluka, >>>>>Bosnia and Herzegovina, also known as Cvrcko >>>>>Does anyone know of any bars in town where I can >>>>>swallow a bucket of cum? It can be either dog, >>>>>horse or human cum. Also, does anyone know of >>>>>any sex bars where people will shit in your mouth? >>>>>I also like eating shit. >>>> >>>>Come to the US and park your mouth in front of George Bush - all the >>>>Bshit you can eat - and it keeps on coming! >>>> >>>>I have a buddy in Bosna - he's normal. >>> >>> Now you know why I blanket kill-file googlegroups. >> >>So you and everybody can talk about them nonstop? > > If you mean Google Groups the condemnation is justified. > > Who is "them?" Real people do occasionally wander in to GG - or those > without news servers - or without understanding of Usenet. > > Basically, in the engineering groups (in particular) outsiders are > welcome. Engineers are smart, creative and tolerant as a general > rule. > > Lighten up. Who are you defending? and Who goes into Usenet with a > thin skin? Expect ridicule, expect condemnation - "water off a duck's > back." > > You may think your viewpoint is the only one, the right one, the valid > one - but a few million others may disagree. And you ain't started to > deal with culture shock - some countries place emphasis on diplomacy _ > you know the "how are you?" stuff, others don't, and seem very cold. > > Adapt. Now you know why I blanket kill-file googlegroups. From jobs at omacindustries.com Mon Sep 8 12:55:53 2008 From: jobs at omacindustries.com (jobs at omacindustries.com) Date: Mon, 8 Sep 2008 09:55:53 -0700 (PDT) Subject: Calling Common Lisp Game Developers Message-ID: <0cd34294-c623-487c-ac61-a5d92348829e@s50g2000hsb.googlegroups.com> We are currently seeking talented Lisp Game Developers who are passionate about game development and want to play a major role in developing and maintaining new features for one of our persistent browser games. This particular title uses Hunchentoot, but all other code has been developed in house using the Mnesia database for persistence. This particular game is not released yet but has already generated interest from over 35,000 players globally. If you?re interested in developing Persistent Browser Games using SBCL and want to know more then send us an email at lisp at omacindustries.com The preferred location for this role is in Dublin, Ireland but we are also open to hearing from anyone who prefers to work remotely. http://omacindustries.com From martin at v.loewis.de Mon Sep 8 23:58:26 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 09 Sep 2008 05:58:26 +0200 Subject: problem with Tix in Python2.5 In-Reply-To: <5ce15a64-755e-4000-9627-8fd92413424c@r35g2000prm.googlegroups.com> References: <c8cced6a-cc88-4ab7-876d-b9421f1ac585@n38g2000prl.googlegroups.com> <mailman.2230.1219775081.922.python-list@python.org> <5ce15a64-755e-4000-9627-8fd92413424c@r35g2000prm.googlegroups.com> Message-ID: <48C5F462.7010202@v.loewis.de> > i couldn't find any binary distribution of tix8.4.So i think i have to > reinstall python. > i also have numpy and PIL installed.If i reinstall python on top of > the current python directory will i lose them? You should run a "repair" installation. In Add-and-remove-programs, select Python, then Repair. Regards, Martin From apardon at forel.vub.ac.be Tue Sep 2 09:54:37 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 2 Sep 2008 13:54:37 GMT Subject: How can we get to the end of a quote inside a string References: <e209b6e3-1829-4674-816e-c35ae478f160@25g2000prz.googlegroups.com> Message-ID: <slrngbqhct.3rg.apardon@rcpc42.vub.ac.be> On 2008-08-31, rajmohan.h at gmail.com <rajmohan.h at gmail.com> wrote: > Hi all, > Suppose I have a string which contains quotes inside quotes - > single and double quotes interchangeably - > s = "a1' b1 " c1' d1 ' c2" b2 'a2" > I need to start at b1 and end at b2 - i.e. I have to parse the > single quote strings from inside s. > > Is there an existing string quote parser which I can use or > should I write a parser myself? > > If somebody could help me on this I would be much obliged. You could use a combination of split and join in this case. #use a single quote as a seperator to split the string is a list of substrings ls = s.split("'") #remove what comes before the first and after the last single quote ls = ls[1:-1] #reassemble the string between the outermost single quotes. s = "'".join(ls) #strip spaces in front and after if you wish s = s.strip() -- Antoon Pardon From duncan.booth at invalid.invalid Thu Sep 25 04:08:08 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Sep 2008 08:08:08 GMT Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> <gbe6qk$b54$1@aioe.org> <Xns9B23DFA195833duncanbooth@127.0.0.1> <d57f3edc-a305-4165-bafb-d0d75bb54948@z72g2000hsb.googlegroups.com> Message-ID: <Xns9B245BE13E207duncanbooth@127.0.0.1> sturlamolden <sturlamolden at yahoo.no> wrote: > On Sep 24, 10:59?pm, Duncan Booth <duncan.bo... at invalid.invalid> > wrote: > >> Simple LINQ expressions like the one you gave map easily to Python >> list comprehensions. What Microsoft have done though is provide a >> consistent implementation which allows you to write complex SQL like >> expressions whi > ch >> will work identically on databases or most other sequence types. >> han extensions to syntax. > > List comprehensions work with any iterable sequence. You can nest them > to make more complex statements. You can also use a generator to > iterate through a database or an XML document. Here is approximately > where linq stops being a marvelous addition to Python. > A lot of what LINQ does is already easy to do in Python, and most of the rest can probably be added fairly easily, but it does provide a consistent framework which may make it easier to do complex LINQ statements than complex list comprehensions. BTW, a minor correction: LINQ statements are closer to generators, not list comprehensions. They don't actually evaluate their results until you iterate over them and you can re-used the same LINQ statement multiple times getting different results if the data has changed. > And I can honestly do without the SQL syntax. > snap :) -- Duncan Booth http://kupuguy.blogspot.com From tkpmep at hotmail.com Mon Sep 29 14:59:27 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Mon, 29 Sep 2008 11:59:27 -0700 (PDT) Subject: Finding subsets for a robust regression Message-ID: <5087220b-5c26-4b89-be8b-2840f3582523@c65g2000hsa.googlegroups.com> I have coded a robust (Theil-Sen) regression routine which takes as inputs two lists of numbers, x and y, and returns a robust estimate of the slope and intercept of the best robust straight line fit. In a pre-processing phase, I create two new lists, x1 and y1; x1 has only the unique values in x, and for each unique value in x1, y1 has the median of all such values in x. My code follows, and it seems a bit clumsy - is there a cleaner way to do it? By the way, I'd be more than happy to share the code for the entire algorithm - just let me know and I will post it here. Thanks in advance Thomas Philips d = {} #identify unique instances of x and y for xx,yy in zip(x,y): if xx in d: d[xx].append(yy) else: d[xx] = [yy] x1 = [] #unique instances of x and y y1 = [] #median(y) for each unique value of x for xx,yy in d.iteritems(): x1.append(xx) l = len(yy) if l == 1: y1.append(yy[0]) else: yy.sort() y1.append( (yy[l//2-1] + yy[l//2])/2.0 if l % 2 == 0 else yy[l//2] ) From tgrav at mac.com Thu Sep 18 13:17:18 2008 From: tgrav at mac.com (Tommy Grav) Date: Thu, 18 Sep 2008 13:17:18 -0400 Subject: Cython dynamic library problem In-Reply-To: <8763otl8ea.fsf@merkury.smsnet.pl> References: <mailman.1216.1221749258.3487.python-list@python.org> <8763otl8ea.fsf@merkury.smsnet.pl> Message-ID: <B81C132E-9418-405C-8EAB-E1C2C3ECE76D@mac.com> On Sep 18, 2008, at 12:35 PM, Rob Wolfe wrote: > I would try to use `distutils` because this package is much wiser > than me and knows all necessary switches for gcc. ;) That worked! Thanks Cheers Tommy From fetchinson at googlemail.com Wed Sep 10 18:33:58 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 10 Sep 2008 15:33:58 -0700 Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... In-Reply-To: <276719.72706.qm@web95107.mail.in2.yahoo.com> References: <276719.72706.qm@web95107.mail.in2.yahoo.com> Message-ID: <fbe2e2100809101533q5daf5b39h2f9996cd2358e01@mail.gmail.com> > I know I'm tooooo late to ask you for help....but please help me out..I > am really new to unix and dont know how to finish this assignment on > time.....proff. said he will be using MOSS to detect whether I > downloaded the code..please help me.. > > email me : vaidehi.pawar at yahoo.co.in > > Assignment 1 > Processes, Inter-Process Communication, and Concurrency > Due September 13th midnight > Summary > In > this assignment, you will create two versions of a simple multi-process > game : one without and another with inter-process synchronization. You > will also measure the relative performance of the two versions of your > multi-process game. > Objectives > > * Learn how to create and terminate processes. > * Learn use of inter-process communication using shared memory, > semaphores, signals, etc. > * Learn the basic workings of CPU scheduling code in Linux. > > Part A: Multi-Process Game of Turns > > In > this part, you are asked to write a simple program that takes two > command-line arguments P and N. The main process creates P other child > processes, waits for all of them to complete, and then exits. All the > child processes form one logical ring among each other. (In rest of the > description, the term "process" refers to a "child process".) For > example, if the processes are numbered 1 to P, then > > * The next neighbor of process 1 is process 2, > * The next neighbor of process i is process i+1 for all i < P , and > * The next neighbor of process P is process 1, which completes a ring > among the processes. > > Assume > that a shared integer variable, called turn, identifies the number of > the processes whose turn it is at any instant. A second process-local > variable in each process, called me, identifies the identity of each > process (i.e. each process stores its own identity in a per-process > local variable me). A third per-process local variable, called next, > identifies the next process in the ring. > > The processes > sequentially pass the turns among each other in the logical ring. When > each process gets its turn, it increments another shared variable > called counter. The pseudo-code within each process for passing turns > might look something as follows. (Note: Replace turn and counter below > with appropriate ways of accessing data within shared memory regions). > > while(turn != me ) > /* do nothing - just busy loop*/ ; > > /* got my turn - increment counter */ > counter = counter + 1; > > /* give the turn to next process */ > turn = next; > > The program terminates when the each process has received N turns. > > In the above description, several programming details have been omitted for > you to figure out. This includes > > * Creating P child processes from main process. > * Constructing the logical ring among child processes. > o Initializing each child process's identity in the me variable. > o Initializing each child process' next neighbor in the next > variable. > * Initializing the shared memory region and the shared data values. > * Have the main process wait for child processes to complete N turns > before exiting. > > Part B: More Efficient Game of Turns > > You > might notice that the program you wrote in Part A is inefficient > because each process busy loops till the CPU scheduler kicks it out > (after its time-slice is over) and allows another process to execute > and make progress. (Does the program in Part A have a race condition? > Why or why not?) > > What we ideally want is that each process > should be given control of the CPU only when it is that process' turn. > Modify the program you wrote in Part A (using appropriate > synchronization mechanisms) such that each process gets to run (i.e., > gets control of the CPU) only when it is that process's turn, and at no > other time. > > Again, you would need to work out the programming details of how and where > to use inter-process synchronization. > Part C: Profiling the Game of Turns > > In > this part, you are asked to write user-level profiling code in order to > measure the performance of the two versions of programs you wrote in > Part A and Part B. Use a combination of gettimeofday() system call and > inter-process synchronization to measure (1) the average hand-over time > between two consecutive processes in the ring and (b) the total > execution time to complete N turns. Plot the measured values as graphs > when varying number of processes P and number of turns N. Explain the > results you obtain. > Submission Guidelines > > Thanking you, > > Ms. Vaidehi Pawar How much do you pay? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From deets at nospam.web.de Tue Sep 16 17:04:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 16 Sep 2008 23:04:43 +0200 Subject: help on python SWIG C++ extension In-Reply-To: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> References: <40073a54-1f68-4405-bddb-a807224d8aee@e53g2000hsa.googlegroups.com> Message-ID: <6jalbbF29igbU1@mid.uni-berlin.de> RLC schrieb: > Hello > > I am new to python SWIG. Recently I wrote a small program trying to > import collada files(using colladadom) into python so I could use > python cgkit to render them. However, during the progressing, I got > some problems. Every time I quit from Python, I get a segmentation > fault, although the main program runs well. I suspect it is because I > wrapped std::vector objects in C struct and I did not release the > memory properly. Below is the code. I am working on FreeBSD 7.0, GCC > 4.2.1. I will be very appreciated if you could help me. Thanks a lot. > > the error I have got > Segmentation fault: 11 (core dumped) Try starting the program in gdb. This works using $ gdb python (gdb) set args myscript.py (gdb) run Then when the segfault hits, get a backtrace to see where the actual problem occurs. Diez From dave.dibiase at gmail.com Wed Sep 24 17:02:33 2008 From: dave.dibiase at gmail.com (David Di Biase) Date: Wed, 24 Sep 2008 17:02:33 -0400 Subject: Schwartzian transform for tuple in list Message-ID: <ea42fb160809241402i1c6da16t4dd2456a87d6f177@mail.gmail.com> Hi, I have a rather large list structure with tuples contained in them (it's part of a specification I received) looks like so: [(x1,y1,r1,d1),(x2,y2,r2,d2)...] The list can range from about 800-1500 tuples in size and I'm currently sorting it with this: a_list.sort(lambda a, b: cmp(b[3], a[3])) I'm actually sorting it by the last value in the tuple (d2). I have been researching more efficient sorting algorithms and came across Schwartzian transform via these links: - http://www.biais.org/blog/index.php/2007/01/28/23-python-sorting-efficiency - http://dev.fyicenter.com/Interview-Questions/Python/Can_you_do_a_Schwartzian_Transform_in_Python_.html I get what's happening (sorta...errr...lol) but I'm not sure if it is more efficient in my scenario, if it is then I have no idea how to implement it properly :-/ Would be great if a true expert would offer a suggestion for me... Thanks! David -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080924/b184de92/attachment-0001.html> From m_palmer45 at yahoo.ca Wed Sep 3 14:57:51 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 3 Sep 2008 11:57:51 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> Message-ID: <5f3757a5-31da-4c01-b504-584218ac9427@73g2000hsx.googlegroups.com> On Sep 3, 12:57 pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > Michael Palmer schrieb: > > > The other, PyGUI, has an even nicer API and more docs but has > > relatively few widgets implemented at this time. It also strives for > > compatibility with several toolkits (two at this time), which I think > > is the right idea. > > I disagree with that. Meta-wrappers like this will always suffer from > problems, as they have difficulties providing a consistent api. For > example wx is said to be very windows-toolkit-centric in it's API. Yes I > know that it works under Linux with GTK, but it does not come as natural . wax actually does a nice job at wrapping wxPython with a cleaner API. > > So far, development of PyGUI seems to be a one-man effort, and it may > > be slowed down by the attempt to develop the API and the > > implementations concurrently. Could it be useful to uncouple the two, > > such that the API would be specified ahead of the implementation? This > > might make it easier for people to contribute implementation code and > > maybe port the API to additional toolkits. It seems that this approach > > has been quite successful in case of the Python database API. That API > > defines levels of compliance, which might be a way of accommodating > > different GUI toolkits as well. > > > I may be underestimating the difficulties of my proposed approach - I > > don't have much practical experience with GUI programming myself. > > I think you do. The reason for the various toolkits is not because of > python - it's the proliferation of toolkits that exist out there. Right. But that is similar to the situation with relational databases. There are so many of them that it's impossible to include an adapter to each of them in the stdlib. The next best thing is to provide a high-level API that abstracts away the differences. > As long as none of these is "the winner" (and it doesn't look is if that's > to happen soon), I doubt that one API to rule them all will exist - they > all have their different strengths and weaknesses, and a python-API > should reflect these. I rather think that a standard API would cover a reasonable subset - it should NOT contain the idiosyncrasies of each individual toolkit. The anygui project, which has been dormant for a while, is another attempt at a high-level api. Apparently, it tried to implement backends for a lot of toolkits - which again may have been to ambitious an agenda. Maybe someone who was involved in that project might provide some insight. From ldo at geek-central.gen.new_zealand Wed Sep 24 06:09:23 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Wed, 24 Sep 2008 22:09:23 +1200 Subject: finding domain name References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> <mailman.1404.1222174222.3487.python-list@python.org> <d041d210-cfee-4f3b-978c-c65e3e7f6ecc@y38g2000hsy.googlegroups.com> <mailman.1406.1222175467.3487.python-list@python.org> <09637faf-75d8-4af0-b835-3b5a67132996@y21g2000hsf.googlegroups.com> Message-ID: <gbd3kj$vdf$1@lust.ihug.co.nz> In message <09637faf-75d8-4af0-b835-3b5a67132996 at y21g2000hsf.googlegroups.com>, Bobby Roberts wrote: > evidently the environ dictionary is off limits on our server. Why? > It can't > be that tough in python to get the current complete url being viewed. > It's a snap in asp(which is my background). Unless, of course, the relevant information was off limits on your server. From apardon at forel.vub.ac.be Mon Sep 29 07:25:56 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Sep 2008 11:25:56 GMT Subject: cups.Connection.printFile References: <mailman.1082.1221540507.3487.python-list@python.org> <slrngd7c55.37k.apardon@rcpc42.vub.ac.be> <e5740200-7cce-48c6-b1ad-370eb4467b78@v13g2000pro.googlegroups.com> Message-ID: <slrnge1eqs.4bc.apardon@rcpc42.vub.ac.be> On 2008-09-26, Mike Driscoll <kyosohma at gmail.com> wrote: > On Sep 19, 9:01?am, Antoon Pardon <apar... at forel.vub.ac.be> wrote: >> On 2008-09-16, Graham Jenkins <gra... at vpac.org> wrote: >> >> >> >> > I'm trying to print a file from within a Python program. >> >> > The quick-and-dirty solution is to use something like: >> >> > fd = os.popen("lp -d MyPrinter", "wb") >> > fd.write(MyFileContents) >> >> > But it seems to me that there should be a clean solution like: >> >> > import cups >> > stat = >> > cups.Connection.printFile("MyFile","MyPrinter","MyTitle","MyOptions") >> >> What about systems that don't use cups for printing? >> >> -- >> Antoon Pardon > > For Windows, there's a few different ways to print. Tim Golden has a > list on his website: > > http://timgolden.me.uk/python/win32_how_do_i/print.html I have a linux system that doesn't use cups for printing. So his "clean" solution won't work on my box. Unless of course his cups.Connection.printFile is just a wrapper around os.popen("lp -d MyPrinter", "wb") or something similar. -- Antoon Pardon From greg at cosc.canterbury.ac.nz Fri Sep 26 23:15:25 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 27 Sep 2008 15:15:25 +1200 Subject: Why are "broken iterators" broken? In-Reply-To: <6eb35e11-4799-495f-8469-fd03278e97b3@o40g2000prn.googlegroups.com> References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> <6eb35e11-4799-495f-8469-fd03278e97b3@o40g2000prn.googlegroups.com> Message-ID: <6k5n86F685i0U1@mid.individual.net> Craig Allen wrote: > In the end I interpreted that statement as if "unless __iter__()" is > called again It seems you were confusing iterators and iterables. The iterator is the object that is returned by calling __iter__() on an iterable, and yes, you are expected to get a new one each time you want to start iterating again. -- Greg From grante at visi.com Mon Sep 15 01:02:35 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 15 Sep 2008 00:02:35 -0500 Subject: Unable to see os.environ['COLUMNS'] References: <mailman.1024.1221453482.3487.python-list@python.org> Message-ID: <-MydnV_J2pP2cVDVnZ2dnUVZ_h6dnZ2d@posted.usinternet> On 2008-09-13, Tim Chase <python.list at tim.thechases.com> wrote: > Not sure what's going on here and hoping for some insight: > > tim at rubbish:~$ echo $COLUMNS > 129 > tim at rubbish:~$ python2.5 > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> import os > >>> os.environ.get('COLUMNS') > >>> 'COLUMNS' in os.environ > False > > I can coerce it by using > > tim at rubbish:~$ COLUMNS=$COLUMNS python2.5 > Python 2.5.2 (r252:60911, May 28 2008, 08:35:32) > [GCC 4.2.4 (Debian 4.2.4-1)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> import os > >>> 'COLUMNS' in os.environ > True > > However, this seems hokey to me. > > FWIW, this is in Bash on Debian. In bash (and other descendants of the Bourne shell), there are two types of environment variables: 1) local variables that are not passed on to child processes and 2) exported variables that _are_ passed on to children. By default, when a variable is created it is local and will not be inherited by sub-processes. > What's the best way to read what seems to be a > pseudo-environment variable? You can't. You need to export the variable in the parent shell before it exec's the child: $ echo $COLUMNS 80 $ python -c "import os; print os.environ['COLUMNS']" Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ raise KeyError(key) KeyError: 'COLUMNS' $ export COLUMNS $ python -c "import os; print os.environ['COLUMNS']" 80 Now, on to the question you're about to ask: Q: How do I find out how big my terminal is from a Python program? A: You use the TIOCGWINSZ ioctl call on the terminal's file descriptor: >>> import sys,fcntl,termios,struct >>> data = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ, '1234') >>> struct.unpack('hh',data) (24, 80) There's a more detailed explanation here (including an explanation of what the third parameter to ioctl() does, and how you detect changes in the window size): http://mail.python.org/pipermail/python-list/2006-February/365710.html There's also chance that you'd be better off just using ncurses or newt for screen management, but that's another post. -- Grant From srikrishnamohan at gmail.com Sat Sep 27 04:34:47 2008 From: srikrishnamohan at gmail.com (km) Date: Sat, 27 Sep 2008 14:04:47 +0530 Subject: python for *nix system admins In-Reply-To: <48DDE92D.6090405@telcotec.se> References: <48DDE92D.6090405@telcotec.se> Message-ID: <f4cc03640809270134g588d4df4q341dfaafab9df594@mail.gmail.com> import os HTH KM ~~~~~~~~~~~~~~ On Sat, Sep 27, 2008 at 1:35 PM, Lars Stavholm <stava at telcotec.se> wrote: > Hi All, > > I'm new to this list and hoping that this is not off-topic. > If it is, please point me in the right direction. > > I seem to recollect a python module or library for *nix sysadmins, > but I can't for the life of me find it again. > > The module (or library) somehow added unix command capabilities > to the python language. It seemed like a lesser known, perhaps new, > python library or module. > > Any input or ideas appreciated > /Lars Stavholm > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080927/4059be34/attachment-0001.html> From clp at rebertia.com Wed Sep 10 00:40:57 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 9 Sep 2008 21:40:57 -0700 Subject: Simplest solution for formatting local time in iso 8601 including time zone. In-Reply-To: <382d494c-b32b-454a-842b-6f559a94e025@26g2000hsk.googlegroups.com> References: <382d494c-b32b-454a-842b-6f559a94e025@26g2000hsk.googlegroups.com> Message-ID: <47c890dc0809092140n25ea1254tfb21af44dcb7c943@mail.gmail.com> On Tue, Sep 9, 2008 at 9:32 PM, <rowland at river2sea.org> wrote: > What's the simplest solution for formatting the output of local time > in iso 8601 including the time zone information? > > Example: > > "2008-07-25T14:28:43.934-04:00" You want the isoformat() method of datetime objects. See http://docs.python.org/lib/datetime-datetime.html for details. You'll need to pass 'T' as the separator to isoformat() and pass in a tzinfo object when constructing the datetime object. Regards, Chris > > > Thanks, > Rowland > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From prologic at shortcircuit.net.au Mon Sep 8 17:47:26 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Tue, 9 Sep 2008 07:47:26 +1000 Subject: Trying to make a spider using mechanize In-Reply-To: <a8476a36-cd9f-4658-a738-8565a3915a00@d77g2000hsb.googlegroups.com> References: <a8476a36-cd9f-4658-a738-8565a3915a00@d77g2000hsb.googlegroups.com> Message-ID: <e1a84d570809081447h21505e85k994abdd82629fab9@mail.gmail.com> Hi, Perhaps you might want to try out using a sample spider I wrote and base your code of this ? See: http://hg.shortcircuit.net.au/index.wsgi/pymills/file/b9936ae2525c/examples/spider.py cheers James On Tue, Sep 9, 2008 at 2:24 AM, tedpottel at gmail.com <tedpottel at gmail.com> wrote: > Hi, > > I can read the home page using the mechanize lib. Is there a way to > load in web pages using filename.html instad of servername/ > filename.html. Lots of time the links just have the file name. I'm > trying to read in the links name and then vsit those pages. > > here is the sample code I am ussing. > > > import ClientForm > import mechanize > > > #get home page > request = mechanize.Request("http://www.activetechconsulting.com") > response = mechanize.urlopen(request) > print response.read() > > #sub page (this does note work) > request = mechanize.Request("service.html") > response = mechanize.urlopen(request) > print response.read-Ted > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From maric at aristote.info Tue Sep 16 08:48:16 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 14:48:16 +0200 Subject: append on lists In-Reply-To: <gao7lg$ha3$1@online.de> References: <gamffv$qms$1@online.de> <1221564169.16690.0@proxy00.news.clara.net> <gao7lg$ha3$1@online.de> Message-ID: <200809161448.16883.maric@aristote.info> Le Tuesday 16 September 2008 14:23:25 Armin, vous avez ?crit?: > Alex Marandon wrote: > > Armin wrote: > >> Duncan Booth wrote: > >> > >> The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > >> (with c = [8,9]) is identical, > > > > No it's not, + doesn't alter its operands. > > > > >>> a = 1 > > >>> b = 2 > > >>> a + b > > > > 3 > > That's not the point :) It is, please try to understand it, in python all expressions that mutate an object should return None, it's the case for l.append(x) l.sort() l.reverse() ... all expressions that return something, return a new object, it's the case for 1+2 1.__add__(2) (which is the same) sorted(l) l[i:j] etc... there are some noticeable exceptions : For coding facilities, some APIs could return the modified part of the object, ex : it = c.pop() Returning the modifyied object itself is mostly considered bad style, because it doesn't make clear if this the object or a copy. There is OTHO a use case for this, for APIs that allow chaining of operations (don't find by memory any example in stdlib, though), alike the ">>" operator in C++, but pyparsing is a good example if I remember well. BTW, Pythoneers are not very fond of that. Finally, the very special case of augmented assignment operators : x.__iadd__(y) which actually return the modified object, but this expression isn't intended to be use by callers, refer to the manual to see a good example of this, how one should implement __add__ and __iadd__ methods. a += b a = a + b both are statments (doesn't evaluate to any object), but are not equivalent if a is mutable. > > What's the value of 1.add(b)? None? Or 3 ?? > (if add works in the same way as append) > a + b doesn't change a,b ... but a.add(b) -> a=3 > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From maric at aristote.info Mon Sep 15 10:45:12 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 16:45:12 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> Message-ID: <200809151645.13078.maric@aristote.info> Le Thursday 11 September 2008 06:51:19 Dennis Lee Bieber, vous avez ?crit?: > On Wed, 10 Sep 2008 21:36:36 -0500, Grant Edwards <grante at visi.com> > > declaimed the following in comp.lang.python: > > Wrong. I didn't send _any_ e-mail. Why should I get bounce > > messages? > > One: Comp.lang.python is dual-routed with a mailing list; anything > you post to either CLP or the mailing list gets cross-posted to the > other -- the FROM header retains that of the original author (which > could be you). > > Two: Somebody else is subscribed to the mailing list, and sets up an > "out-of-office" reply or has other problems (like an overfilled mailbox, > causing a bounce, or a discontinued account) when the forwarded post > reaches their address. > > Three: The bounce/ooo-reply is sent to the message author, not to > any intermediate host(s). After all, on that end, it's normal email > failure response -- notify the author of the message. It doesn't matter > that the original message was posted on a Usenet newsgroup if that group > is automatically relayed to members of a mailing list. Given RFCs, the problem should not be, for DSN, the MTA should rewrite the FROM envelope address to the one of the list maintainer : RFC 3464 : > 3. Conformance and Usage Requirements > > ... > > By contrast, successful submission of a message to a mailing list > exploder is considered final delivery of the message. Upon delivery > of a message to a recipient address corresponding to a mailing list > exploder, the Reporting MTA SHOULD issue an appropriate DSN exactly > as if the recipient address were that of an ordinary mailbox. > > NOTE: This is actually intended to make DSNs usable by mailing > lists themselves. Any message sent to a mailing list subscriber > should have its envelope return address pointing to the list > maintainer [see RFC 1123, section 5.3.7(E)]. Since DSNs are sent > to the envelope return address, all DSNs resulting from delivery > to the recipients of a mailing list will be sent to the list > maintainer. The list maintainer may elect to mechanically > process DSNs upon receipt, and thus automatically delete invalid > addresses from the list. (See section 7 of this memo.) and > Appendix C - Guidelines for use of DSNs by mailing list exploders > > - Guidelines for use of DSNs by mailing list exploders > > > This section pertains only to the use of DSNs by "mailing lists" as > defined in [4], section 7.2.7. > > DSNs are designed to be used by mailing list exploders to allow them > to detect and automatically delete recipients for whom mail delivery > fails repeatedly. > > When forwarding a message to list subscribers, the mailing list > exploder should always set the envelope return address (e.g., SMTP > MAIL FROM address) to point to a special address which is set up to > receive non-delivery reports. A "smart" mailing list exploder can > therefore intercept such non-delivery reports, and if they are in the > DSN format, automatically examine them to determine for which > recipients a message delivery failed or was delayed. This is not sufficient for auto-responses, and given the following rfcs, it would smart to both : - add an "Auto-Submitted: Python User Group" header, - add or modify the Return-Path and/or Reply-To header for badly implemented auto-responders to point to list maintainer. RFC 3834: > 4. Where to send automatic responses (and where not to send them) > > > In general, automatic responses SHOULD be sent to the Return-Path > field if generated after delivery. If the response is generated > prior to delivery, the response SHOULD be sent to the reverse-path > from the SMTP MAIL FROM command, or (in a non-SMTP system) to the > envelope return address which serves as the destination for non- > delivery reports. and > 5. The Auto-Submitted header field > > > The purpose of the Auto-Submitted header field is to indicate that > the message was originated by an automatic process, or an automatic > responder, rather than by a human; and to facilitate automatic > filtering of messages from signal paths for which automatically > generated messages and automatic responses are not desirable. RFC 1123 : > 5.3.7 Mail Gatewaying > > Gatewaying mail between different mail environments, i.e., > different mail formats and protocols, is complex and does not > easily yield to standardization. See for example [SMTP:5a], > [SMTP:5b]. However, some general requirements may be given for > a gateway between the Internet and another mail environment. > > (A) Header fields MAY be rewritten when necessary as messages > are gatewayed across mail environment boundaries. > > DISCUSSION: > This may involve interpreting the local-part of the > destination address, as suggested in Section 5.2.16 I'm also frustrated by some (rare) of my mails which are actually blocked for confirmation by a moderator with this message : > Is being held until the list moderator can review it for approval. > > The reason it is being held: > > Message has a suspicious header I think it's probably my domain name which makes this, do the anti-spam engine use whitelists ? How to resolve the problem if not ? -- _____________ Maric Michaud From kar1107 at gmail.com Sat Sep 6 20:14:20 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Sat, 6 Sep 2008 17:14:20 -0700 (PDT) Subject: Seeking ideas for a cron implementation References: <cf52ec86-2b1c-4faa-b97c-d4ccc879b326@x16g2000prn.googlegroups.com> <8f607078-e8da-4438-8769-96d011f1544f@j1g2000prb.googlegroups.com> Message-ID: <76e696f6-4428-4c59-9d30-661022ca5dbe@w39g2000prb.googlegroups.com> On Aug 22, 1:51?pm, Sean DiZazzo <half.ital... at gmail.com> wrote: > On Aug 22, 1:30?pm, Karthik Gurusamy <kar1... at gmail.com> wrote: > > > > > Hi, > > > I'm working on acronlike functionality for my application. > > The outer loops runs continuously waking every x seconds (say x=180, > > 300, ..). > > It needs to know what events incronhas expired and for each event do > > the work needed. > > > It's basically like unixcronor like a calendar application with some > > restrictions. The outer loop may come back a lot later and many events > > might have missed their schedule -- but this is okay.. We don't have > > to worry about missed events (if there were n misses, we just need to > > execute call back once). > > > Let's take some examples [Let e denotes an event] > > e1: hour=1 ?min=30 ? ? ? ? ? ? ? ? ? ? ? ? ? ? # Run every day once at > > 1:30 AM > > e2: wday=0, hour=1 ?min=0 ? ? ? ? ? ? ? ? ? # run every Monday at 1 AM > > e3: month=10, day=10, hour=10 min=0 ?# run on October 10th, 10 AM > > every year > > > class Cron_Event (object): > > ? ? def __init__ (year=None, month=None, day=None, hour=None ..etc) > > ? ? ? # ?do init > > > classCron(object): > > ? ? def __init__ (): > > ? ? ? ? # do init > > ? ? def event_add (e): > > ? ? ? ? # add an event > > ? ? def execute() > > ? ? ? ? # see if any events has "expired" .. call it's callback > > ? ? ? ? # I'm looking for ideas on how to manage the events here > > > From outer loop > >cron=Cron() > > # create various events like > > e1 = Cron_Event(hour=1) > >cron.event_add(e1) > > e2 = Cron_Event(wday=0, hour=1) > >cron.event_add(e2) > > > while True: > > ? ? sleep x seconds (or wait until woken up) > > ? ?cron.execute() > > ? ? # do other work.. x may change here > > > If I can restrict to hour and minute, it seems manageable as the > > interval between two occurrences is a constant. But allowing days like > > every Monday or 1st of every month makes things complicated. Moreover > > I would like each constraint in e to take on multiple possibilities > > (like every day at 1AM, ?2 AM and 4 AM do this). > > > I'm looking for solutions that can leverage datetime.datetime > > routines. > > My current ideas include for each e, track the next time it will fire > > (in seconds since epoch as given by time.time()). Once current time > > has passed that time, we execute the event. e.g.>>> datetime.datetime.now() > > > datetime.datetime(2008, 8, 22, 13, 19, 54, 5567)>>> time.time() > > > 1219436401.741966 ? ?<--- compute event's next firing in a format like > > this > > > The problem seems to be how to compute that future point in time (in > > seconds since epoch) ?for a generic Cron_Event. > > > Say how do I know the exact time in future ?that will satisfy a > > constraint like: > > ?month=11, wday=1, hour=3, min=30 ? ?# At 3:30 AM on a Tuesday in > > November > > > Thanks for your thoughts. > > > Karthik > > I only scanned your message, but maybe datetime.timedelta() will > help.. > > >>> import datetime > >>> now = datetime.datetime.now() > >>> print now > > 2008-08-22 13:48:49.335225>>> day = datetime.timedelta(1) > >>> print day > 1 day, 0:00:00 > >>> print now + day > > 2008-08-23 13:48:49.335225 Thanks, I found using a more efficient algorithm tricky and seemed error prone. [I do welcome ideas still if anyone has a cool solution] I used your idea and took the easy way out by using a brute-force search. Here is an outline if anyone faces similar problem: hours, minutes are lists: say for every day at 1:30 pm and 2:45 pm, hours=[13, 14] and minutes=[30, 45,]. I restricted myself to minutes and hours (and every day) to simplify the problem. def set_expiry_time_check_in_a_day (self, now, target, hours, mins, flags=set()): """ A small utility routine to simulate 'goto' Looks like now could be computed inside this function -- the small drift due to time taken in this function should be negligible """ # let's see if in today we can find an expiry # we do brute force search starting with the smallest hour for hour in hours: for min in mins: target = target.replace(hour=hour, minute=min, second=0, microsecond=0) if 'is_debug_1' in flags: print "Trying target time: %s..." % target if target > now: if 'is_debug_1' in flags: print "Found target time: %s" % (target, ) return target # simulates a break from two loops return None def set_expiry_time (self, event, flags=set()): """ For a given event, compute and remember when it will fire next """ now = datetime.datetime.now() target = now # start checking from now.. # assumption, hours and mins are atleast one int element array # and they are in sorted order hours = event.spec['hours'] mins = event.spec['minutes'] tries = 0 while True: # runs of each day.. tomorrow ... tries += 1 if tries > 50: # safety valve, we are basically in infinite loop raise Exception("Tried 50 times.. in infinite loop??") target_found = self.set_expiry_time_check_in_a_day(now, target, hours, mins, flags) if target_found is not None: # found a match on "this" day target = target_found break # we need to increase the day count.. increment = datetime.timedelta(days=1) target += increment # added 24 hours .. let's go and check tomorrow ... event.target = target > > ~Sean From pete.forman at westerngeco.com Fri Sep 19 07:37:51 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Fri, 19 Sep 2008 12:37:51 +0100 Subject: PEP proposal optparse References: <ca58efdf-3f9c-4aea-9c20-69c69a578754@k30g2000hse.googlegroups.com> Message-ID: <1vzgcqnk.fsf@wgmail2.gatwick.eur.slb.com> James <jlnicolson at gmail.com> writes: > I would like to know your thoughts on a proposed change to optparse > that I have planned. It is possible to add default values to > multiple options using the set_defaults. However, when adding > descriptions to options the developer has to specify it in each > add_option() call. -1 I see no advantage to swelling optparse when the language offers many solutions already. E.g. desc = { 'verbose': 'Output less information', 'castordir': 'specify the wanted CASTOR directory where to store ' 'the results tarball', 'previousrel': 'Top level dir of previous release for regression ' 'analysis'} parser.add_option('-q', '--quiet', action="store_false", dest='verbose', help = desc['verbose']) ... Or another approach might be like this. for ... in zip(...): parser.add_option(...) -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From sjmachin at lexicon.net Fri Sep 5 19:30:35 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 5 Sep 2008 16:30:35 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> <a34c6ffd-0353-43c9-8b22-36d0fc66ed22@v16g2000prc.googlegroups.com> <d9a713e1-3305-4d9c-8cac-02dc1c57aa86@m3g2000hsc.googlegroups.com> Message-ID: <0e12f3cd-7088-4f64-afa8-eb5ac4d00031@t1g2000pra.googlegroups.com> On Sep 6, 7:49?am, bearophileH... at lycos.com wrote: > John Machin: > > > Consider this:>>> hash(123) == hash(123.0) == hash(123L) > > True > > Right... Can you explain me why Python designers have chosen to build > a hash() like that? I can't channel them; my rationalisation is this: Following the Law of Least Astonishment, >> 123 == 123.0 == 123L True Consequently if x == y, then adict[x] and adict[y] should give the same result. Cheers, John From lists at svrinformatica.it Tue Sep 16 02:31:13 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Tue, 16 Sep 2008 08:31:13 +0200 Subject: Zsi interoperability In-Reply-To: <3f0d61c40809151126n791b1ce0ya1e208a075660934@mail.gmail.com> References: <mailman.1047.1221498380.3487.python-list@python.org> <48cea64b$0$6667$9b4e6d93@newsspool2.arcor-online.net> <3f0d61c40809151126n791b1ce0ya1e208a075660934@mail.gmail.com> Message-ID: <1221546673.5885.4.camel@localhost.localdomain> Il giorno lun, 15/09/2008 alle 20.26 +0200, Marco Bizzarri ha scritto: > On Mon, Sep 15, 2008 at 8:15 PM, Stefan Behnel <stefan_ml at behnel.de> wrote: > > Mailing List SVR wrote: > >> I have to implement a soap web services from wsdl, the server is > >> developed using oracle, is zsi or some other python library for soap > >> interoperable with oracle soa? > > > > No idea, but I'd definitely try soaplib before ZSI. > > > > Stefan > > I'm working on a project where I need to write a client for SOAP with > Attachments; I can see ZSI does not support it; is soaplib any better? > I don't need soap attachments, I have some images but are base64 encoded string, all other field are string, however my server require client certificate authentication, does soaplib or zsi work in this environment? is really strange that there isn't a standard and well manteined soap-1.2 implementation for python so we can talk without interoperability issue with axis2,metro,cxf,oracle,.net ecc.. :-( thanks Nicola > Can you argument your suggestion a little more? > > Regards > Marco > > > From deets at nospam.web.de Wed Sep 3 15:25:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 Sep 2008 21:25:48 +0200 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <5f3757a5-31da-4c01-b504-584218ac9427@73g2000hsx.googlegroups.com> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> <5f3757a5-31da-4c01-b504-584218ac9427@73g2000hsx.googlegroups.com> Message-ID: <6i86ltFp9oegU1@mid.uni-berlin.de> Michael Palmer schrieb: >> I disagree with that. Meta-wrappers like this will always suffer from >> problems, as they have difficulties providing a consistent api. For >> example wx is said to be very windows-toolkit-centric in it's API. Yes I >> know that it works under Linux with GTK, but it does not come as natural . > > wax actually does a nice job at wrapping wxPython with a cleaner API. wax wraps wx. It does not wrap PyQt, Tk, win32, GTK and whatnot. That was what I was talking about. > Right. But that is similar to the situation with relational databases. > There are so many of them that it's impossible to include an adapter > to each of them in the stdlib. The next best thing is to provide a > high-level API that abstracts away the differences. > >> As long as none of these is "the winner" (and it doesn't look is if that's >> to happen soon), I doubt that one API to rule them all will exist - they >> all have their different strengths and weaknesses, and a python-API >> should reflect these. > > I rather think that a standard API would cover a reasonable subset - > it should NOT contain the idiosyncrasies of each individual toolkit. And thus reduce the usability massively. A reasonable subset is already included in python, with tkinter, available on a wide range of plattforms. Yet still people strive for the various other toolkits, because they miss richer widgets, gui-designers (an important topic you don't cover at all) or e.g. multi-threading capabilities. > The anygui project, which has been dormant for a while, is another > attempt at a high-level api. Apparently, it tried to implement > backends for a lot of toolkits - which again may have been to > ambitious an agenda. Maybe someone who was involved in that project > might provide some insight. Sure, that would be interesting. Diez From ceball at users.sourceforge.net Tue Sep 16 19:34:27 2008 From: ceball at users.sourceforge.net (Chris) Date: Tue, 16 Sep 2008 23:34:27 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: <mailman.793.1221057913.3487.python-list@python.org> <efaa21d2-6e94-4170-ae8e-e7ddb0cd5d2e@w1g2000prk.googlegroups.com> <mailman.914.1221222322.3487.python-list@python.org> <8763p1799y.fsf@mulj.homelinux.net> <871vzp77lp.fsf@mulj.homelinux.net> Message-ID: <loom.20080916T200156-930@post.gmane.org> Hrvoje Niksic <hniksic <at> xemacs.org> writes: ... > > You are getting that error because Carl forgot to cast the descriptor > > to the appropriate C type, in this case PyMemberDescrObject. The last > > line is also incorrect, I think. Try something like this: ... The code you gave was great, thanks! Now we have done exactly what we wanted, and have fast access from C to two particular attributes of instances of a particular class. We use that fast access in optimized versions of pure-Python components of our simulator. Chris From deets at nospam.web.de Mon Sep 15 16:00:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 22:00:59 +0200 Subject: Python Nautilus script In-Reply-To: <48cebba7$0$2862$ba620e4c@news.skynet.be> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> Message-ID: <6j7t7rF1tl5rU1@mid.uni-berlin.de> Michel Leunen schrieb: > Diez B. Roggisch a ?crit : > >> There shouldn't be a difference between a shell-script and a >> python-script. Environment-variables are a unix-process-thing, and >> thus the rules that govern them apply to *all* processes - the shell >> is one of these, there is nothing special to it. >> >> If the shell-script gets the variable, the python-script will as well. > > Yes, that's what I thought too but try this: open a terminal and type > > $ echo $HOSTNAME > > you will get the name of your computer. > Now try this instead: > > $ python > >>> import os > >>> os.environ['HOSTNAME'] > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "/usr/lib/python2.5/UserDict.py", line 22, in __getitem__ > raise KeyError(key) > KeyError: 'HOSTNAME' > >>> Which is the exact right thing to happen if the HOSTNAME is not exported. The echo above is executed IN THE CURRENT SHELL environment. If it weren't - why would there be any distinction between local and exported variables at all? If you put > It appears that's because HOSTNAME is not exported. > But in the case of Nautilus script, how to workaround this issue? I don't know for sure if the shell has something build-in that makes it spawn shell-subprocesses with a different environment than other processes. However, if you want you can do something like this: #!/bin/bash export VARIABLE_NAME python /the/python/script.py You create a shell-script that exports the environment first, and then invokes python. Diez From xnews2 at fredp.lautre.net Wed Sep 17 17:34:06 2008 From: xnews2 at fredp.lautre.net (Fred Pacquier) Date: 17 Sep 2008 21:34:06 GMT Subject: ANN: Python GUI development using XULRunner References: <mailman.1150.1221614920.3487.python-list@python.org> Message-ID: <Xns9B1CEFF3C9D21PaCmAnRDLM@212.27.60.39> Todd Whiteman <toddw at activestate.com> said : > I've put together a tutorial that shows off how to build a GUI > application using XULRunner (same architectural components as Firefox > uses) that can be used in conjunction with the Python programming > language. > The tutorial covers how to build a Python/XULRunner GUI application: > http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulru > nner_about.html > The details in this tutorial covers the initial setup to full > packaging/deployment, mostly targeting a Windows/Linux platform > (MacOSX is possible with a few deviations, I have tried to cover these > deviations where applicable). > Feedback is welcome. Thanks for making good on your promise. I'm leaving for a trip but have it bookmarked for later use :-) From bborcic at gmail.com Tue Sep 9 09:47:20 2008 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 09 Sep 2008 15:47:20 +0200 Subject: max(), sum(), next() In-Reply-To: <5ee352aa-9ee5-4a8b-8b01-b9e6d1cc808e@m73g2000hsh.googlegroups.com> References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <mailman.687.1220882152.3487.python-list@python.org> <5ee352aa-9ee5-4a8b-8b01-b9e6d1cc808e@m73g2000hsh.googlegroups.com> Message-ID: <ga5urd$fq5$1@ger.gmane.org> castironpi wrote: > On Sep 8, 8:54 am, Boris Borcic <bbor... at gmail.com> wrote: >> David C. Ullrich wrote: >> >>> (ii) If A is a subset of B then we should have >>> max(A) <= max(B). This requires that max(empty set) >>> be something that's smaller than everything else. >>> So we give up on that. >> Er, what about instances of variations/elaborations on >> >> class Smaller(object) : __cmp__ = lambda *_ : -1 >> >> ? >> >> Cheers, BB > > You still don't have the property max(X) is in X. Frankly, I would favor order-independence over that property. compare max(X) for 1) X = [set([1]),set([2])] and 2) X = [set([2]),set([1])] Shouldn't then max and min in fact return lub and glb, despite their names ? In the case X is a non-empty finite set/list of totally ordered values, max(X)==lub(X) and min(X)=glb(X) in any case. > > And it's the equivalent of a special builtin constant for max on the > empty set. Of course (except the object might have other uses, who knows). So what ? Cheers, BB From mathieu.prevot at gmail.com Mon Sep 15 15:58:45 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Mon, 15 Sep 2008 21:58:45 +0200 Subject: Parallelising code In-Reply-To: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> References: <0afd786c-7633-4a2e-b7e9-8f8455a1513e@8g2000hse.googlegroups.com> Message-ID: <3e473cc60809151258o193e950j382716b97f9e4adb@mail.gmail.com> 2008/9/15 psaffrey at googlemail.com <psaffrey at googlemail.com>: > I have some file processing code that has to deal with quite a lot of > data. I have a quad core machine, so I wondered whether I could take > advantage of some parallelism. > > Essentially, I have a number of CSV files, let's say 100, each > containing about 8000 data points. For each point, I need to look up > some other data structures (generated in advance) and append the point > to a relevant list. I wondered whether I could get each core to handle > a few files each. I have a few questions: > > - Am I actually going to get any speed up from parallelism, or is it > likely that most of my processing time is spent reading files? I guess > I can profile for this? > > - Is list.append() thread safe? (not sure if this is the right term) > what I mean is, can two separate processors file a point in the same > list at the same time without anything horrible happening? Do I need > to do anything special (mutex or whatever) to make this happen, or > will it happen automatically? You won't take advantage of your cores with a pure and single python script. Python threads are useful for UI, files operations, all but concurrent processing. The simpler way to do concurrent processing is to use Popen from subrocess, that'll create new processes. Notice that you can call python scripts from another one eg a manager and as many workers as you want. IMO it's the simpler design and less work for making concurrent processes. Ideally make your workers not need to feedback with variable, or anything more complex than a return value. Also, make them not write the same file. They can read the same file without problem. Remark that you can manage lock etc from the manager script. I'm not sure python semaphore allow interprocess communication like c semaphores [1] ; check this. A workaround is to send to stderr tuples. HTH, Mathieu [1] Programming with POSIX Threads, David R. Butenhof, http://tinyurl.com/6hpkol From darcy at druid.net Mon Sep 29 12:49:40 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 29 Sep 2008 12:49:40 -0400 Subject: Music knowledge representation In-Reply-To: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> References: <8f67b6f80809280737w5275b4b4yfda5fac74a66cb7f@mail.gmail.com> Message-ID: <20080929124940.8c1c82e8.darcy@druid.net> On Sun, 28 Sep 2008 16:37:11 +0200 "Mr.SpOOn" <mr.spoon21 at gmail.com> wrote: > Hi, > I'm working on an application to analyse music (melodies, chord sequences etc.) Sounds interesting. Will this be Open Source? > I need classes to represent different musical entities. I'm using a > class Note to represent all the notes. Inside it stores the name of > the natural version of the note (C, D, E, F...) and an integer to > calculate the accidentals. Have you considered having the object take a key option with default to 'C' so that you don't have to mark as many accidentals - or, more correctly, mark actual accidentals rather than always marking the "black keys?" The other advantage here is that the notes can be given as numbers and octaves (middle C would be (1, 3, 0) in the key of C for example) and you can transpose by changing the argument when instantiating the class. > Then I have a class Pitch, to represent the different 12 pitch > classes, because different notes, such as C# and Db, belong to the > same pitch class. Couldn't the note class simply have a list of all the notes and have a simple method calculate the actual pitch? > In these classes I also have some arithmetic method to perform > additions or subtractions between pitches and integers. > > I also need to represent intervals between notes. An interval must > have a degree (first, second, third), that may be represented with a > simple integer and a size counted in semitones. Then, with these > informations it can retrieve its name, for example: perfect fifth. Seems easy given the pitch location indeces. Subtract the two and do a lookup into a list of intervals. E.g: ["Unison", "Semi-tone", "Second", "Minor third", Major third", ...] > The degree is calculated between natural notes. So the degree of > Interval(C, E) is "third", or 3. This may be simple, if I put the > notes in an ordered sequence. But, when I have to calculate, for > example Interval(E, C). It should count till the end of the sequence, > so if I have: > > C D E F G A B > > after the B it should continue with C. I'm not sure how to implement > this. Is there a suitable data structure for this purpose? def interval(self, lower, higher) if lower > higher: # uncomment one of the two following lines depending # on the behaviour you want #lower,higher = higher,lower #higher += 12 # could use some error trapping return self.interval_name[higher - lower] Note that lower and higher could be a note object that you have to convert to integers first. Hope this gives you some ideas. -- D'Arcy J.M. Cain <darcy at druid.net> | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From castironpi at gmail.com Tue Sep 16 16:55:17 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 13:55:17 -0700 (PDT) Subject: How do I add permanently to Pythons sys.path? References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <0f73d96e-0166-4976-8cbc-6a5c3ffe9ffe@m36g2000hse.googlegroups.com> <mailman.1138.1221594080.3487.python-list@python.org> Message-ID: <08337238-2c56-4eec-b42a-45b65480f37e@m44g2000hsc.googlegroups.com> On Sep 16, 2:40?pm, "Support Desk" <m... at ipglobal.net> wrote: > What about on a unix box? I can't help you. I don't have access to '/opt/pkgs/python-2.0/lib/ python2.0/site-packages' (ha ha) on the one I have access to. If you do, try the same thing. > > Sincerely, > Michael H. > > -----Original Message----- > From: Aaron "Castironpi" Brady [mailto:castiro... at gmail.com] > Sent: Tuesday, September 16, 2008 12:49 PM > To: python-l... at python.org > Subject: Re: How do I add permanently to Pythons sys.path? > > On Sep 16, 10:13?am, cnb <circularf... at yahoo.se> wrote: > > >>> sys.path > > > ['C:\\Python25\\Progs\\NatLangProc', 'C:\\Python25\\Lib\\idlelib', 'C:\ > > \Windows\\system32\\python25.zip', 'C:\\Python25\\lib\\site-packages\ > > \orange', 'C:\\Python25\\lib\\site-packages\\orange\\OrangeWidgets', > > 'C:\\Python25\\lib\\site-packages\\orange\\OrangeCanvas', 'C:\ > > \Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', > > 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- > > packages', 'C:\\Python25\\lib\\site-packages\\Numeric', 'C:\\Python25\ > > \lib\\site-packages\\PIL'] > > > Now I have my personal programs in C:/Python25/Progs/ > > > How do I add so that I can just do "import somefile" from anywhere in > > that directory in the interpreter and it can load files from other > > folders in that directory. > > Add a file: \Lib\site-packages\locals.pth > > with contents, path to the directory you want to add (/python25/progs/) > > From david.trem at gmail.com Sun Sep 14 14:32:53 2008 From: david.trem at gmail.com (David Trem) Date: Sun, 14 Sep 2008 11:32:53 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <48BFB534.2080508@egenix.com> <mailman.569.1220632640.3487.python-list@python.org> <Xns9B15D1BE39452PaCmAnRDLM@212.27.60.38> Message-ID: <88eadda3-25a5-4319-9468-6b8afe5d4640@k13g2000hse.googlegroups.com> On 10 sep, 20:36, Fred Pacquier <xne... at fredp.lautre.net> wrote: > Todd Whiteman <to... at activestate.com> said : > > > Personally, I believe XULRunner has a lot to offer for Python GUI > > development, I'm currently finishing up some documentation steps to show > > off how to use it specifically for Python (I'll post it to this list > > when it's finished). > > That would be really nice ! > > I've long been curious about the potential of XUL+Python, but put off by > the lack of leads to follow up, and not having time to do the digging > myself... > > TIA, > fp I will also like to see such documentation as soon as possible. To me, XUL+python really looks like what could be my prefered solution for multiplatform GUI for my python program. I'm really impatient and hope a strong and motivated community could set up arrond such XUL+python project. All the best, David From bluecrystalyj at gmail.com Fri Sep 5 09:12:41 2008 From: bluecrystalyj at gmail.com (bcm) Date: Fri, 5 Sep 2008 06:12:41 -0700 (PDT) Subject: int((9.2-9.0)*10) is 1, int((9.21-9.0)*10) is 2, why? Message-ID: <184502f4-872a-4c23-9a6d-e93ef225d4de@a2g2000prm.googlegroups.com> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 The following line of code describes an funny question? >>> int((9.2-9.0)*10) 1 >>> int((9.21-9.0)*10) 2 >>> int((9.1-9.0)*10) 0 >>> int((9.11-9.0)*10) 1 >>> int((8.2-8.0)*10) 1 >>> int((8.23-8.0)*10) 2 why? anybody can explain it? From kaerbuhez at gmail.com Sat Sep 6 16:16:56 2008 From: kaerbuhez at gmail.com (kaer) Date: Sat, 6 Sep 2008 13:16:56 -0700 (PDT) Subject: running python as a dameon References: <103ca2c7-50ed-4f33-9e00-f18147623934@2g2000hsn.googlegroups.com> <6e7ead25-baf1-400a-a52f-568f37351aab@8g2000hse.googlegroups.com> <5c74118c-a576-4a51-ae9a-95d34273a99a@s50g2000hsb.googlegroups.com> Message-ID: <de097d76-cd3c-487f-a9ec-90c1f5129ba4@e53g2000hsa.googlegroups.com> On 6 sep, 15:44, Michael Palmer <m_palme... at yahoo.ca> wrote: > On Sep 5, 9:56 pm, Sean Davis <seand... at gmail.com> wrote: > > > > > > What I want > > > to do is to provide the python NLP program as a service to any other > > > PHP/Java/Ruby process request. So the mapping is > > > > http -> apache -> PHP/Java/Ruby/... -> Python NLP > > > Why not use a simple CGI script or wsgi application? You could make > > the service online and interactive and with the same application and > > code make an XMLRPC web service. So, things would look more like: > > > http -> apache -> Python (running NLP and serving requests) > > > You can use apache to proxy requests to any one of a dozen or so > > python-based webservers. You could also use mod_wsgi to interface > > with a wsgi application. > > > Sean > > xmlrpc is the right idea, as it interfaces easily across languages. I just daemonize some utility script these week. For that I took one of the scripts in the ASPN python cookbook : google those 3 words then search python and you will find out your solution faster than I end up this mail. It worked like a charm on my linux box. BTW, I wouldn't complicate with xml stuffs if you don't need it. Good luck. From jmdeschamps at gmail.com Mon Sep 1 17:58:50 2008 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: Mon, 1 Sep 2008 14:58:50 -0700 (PDT) Subject: Play AVI files as cut-scene... in BGE - HOW? Message-ID: <318f98dd-cfec-43cc-bc59-a59d8dbd64af@2g2000hsn.googlegroups.com> Blender Game Engine does not seem able to just play an AVI clip file... I want to play these files as cut-scenes in a game - subprocess it to the OS, and continue on return seems a good solution - but so sorry, it's been a while since I've delved in such places... I need a refresher. Must be platform independent (or platform *adjustable* ;-) ) Continue script execution only after it's over (in due time or passed over by user) Must be configurable to adjust ourput screen and stuff like that... Any hints out there :-) Thanks in advance! From bdesth.quelquechose at free.quelquepart.fr Sat Sep 20 13:01:42 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 Sep 2008 19:01:42 +0200 Subject: improving a huge double-for cycle In-Reply-To: <00e2e17d$0$20331$c3e8da3@news.astraweb.com> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> <00e2e17d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <48d54863$0$4666$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Thu, 18 Sep 2008 20:43:00 +0200, Bruno Desthuilliers wrote: > >> Now the obvious winner is pruebono - even unoptimized, using sets seems >> to be *way* faster than even the most optimized corrected version of >> your algorithm. > > I'm not being snarky about losing priority here, but I submitted > essentially the same solution two hours earlier than pruebono. My bad... Now that you mention it, I see you effectively did. My fault, I did a too-fast screening of submitted solutions, and hereby declare you Steven as the winner. > Are people not seeing my posts? Have I been kill-filed by everyone except > Mensator? I do see your posts. Whether I read them entirely is another question - and in this concrete case, the answer is obviously 'nope'. Put the blame on me. > I also asked a question about HTTPError and I haven't seen any > responses at all. This is another problem - it happens that no one has a clue, or that the one having a clue lack time (or willingness) to anwer. Once again, sorry if me missing your correct answer drives you paranoid :( From lists at cheimes.de Wed Sep 10 07:12:58 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 10 Sep 2008 13:12:58 +0200 Subject: which of these 2 quicksorts is faster? In-Reply-To: <ga87ij$1r1$1@ger.gmane.org> References: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> <ga87ij$1r1$1@ger.gmane.org> Message-ID: <ga8a3q$8mm$2@ger.gmane.org> Fredrik Lundh wrote: > what makes you think you can write a better sort than the built-in > algorithm by typing in some toy quick-sort implementations from a > "sorting for dummies" article? Anybody who can FULLY understand Tim's text at http://svn.python.org/projects/python/branches/release25-maint/Objects/listsort.txt can write a better sorting algorithm ... *scnr* :] Christian From kenneth.m.mcdonald at sbcglobal.net Wed Sep 10 11:24:38 2008 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 10 Sep 2008 10:24:38 -0500 Subject: subprocess.Popen hangs at times? Message-ID: <AAC5A7F8-7617-43F7-84C3-07E0EA4DFDA5@sbcglobal.net> When making calls of the form Popen(cmd, shell=True, stdout=subprocess.PIPE), we've been getting occasional, predictable hangs. Will Popen accumulate a certain amount of stdout and then block until its read? We don't want to use threads, so just want to read the entire stdout after the subprocess has finished. Thanks, Ken From maric at aristote.info Tue Sep 16 08:03:31 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 14:03:31 +0200 Subject: Is 'x' an instance of a new-style class? In-Reply-To: <878wts76dc.fsf@mulj.homelinux.net> References: <f568f4d9-b179-4ef1-9688-fcd8cb5ef641@d1g2000hsg.googlegroups.com> <mailman.1102.1221557922.3487.python-list@python.org> <878wts76dc.fsf@mulj.homelinux.net> Message-ID: <200809161403.31885.maric@aristote.info> Le Tuesday 16 September 2008 12:05:51 Hrvoje Niksic, vous avez ?crit?: > "Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> writes: > > En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS <schaefer.mp at gmail.com> > > > > escribi?: > >> I've seen the question raised several times here, but apparently never > >> answered. Since PyInstance_Check returns False for new-style class > >> instances, is there a standard procedure for testing this using the C- > >> Api? > >> > >> I would greatly appreciate some help with this. > > > > In Python you would write isinstance(x, object). > > It will return True for all Python objects (except perhaps those that > fiddle with metaclasses), not only for instances of new-style classes. > > >>> isinstance([], object) > > True > > >>> isinstance((), object) > > True > > >>> isinstance(list, object) > > True > > >>> isinstance(type, object) > > True > > I don't think there is a good way to check if something is a new-style > class instance. The whole point of new-style classes was removing the > distinction between classes and types. The distinction is now so well > removed that it's hard to find it when you need it. > Yes, everything (including instances of old style classes) are instance of a new style class but : not isinstance(x, types.InstanceType) ensure you that x is not an instance of old style class. > A better question for OP is *why* he needs to distinguish between > instances of new-style classes and other objects. > -- > http://mail.python.org/mailman/listinfo/python-list -- _____________ Maric Michaud From mwilson at the-wire.com Sat Sep 6 11:03:10 2008 From: mwilson at the-wire.com (Mel) Date: Sat, 06 Sep 2008 11:03:10 -0400 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <mailman.597.1220675617.3487.python-list@python.org> <00d23065$0$20302$c3e8da3@news.astraweb.com> Message-ID: <g9u633$6nt$1@aioe.org> Steven D'Aprano wrote: > On Sat, 06 Sep 2008 00:33:25 -0400, Manu Hack wrote: > >> Actually it's even more natural to state sum([x]) = x, and this way you >> can never conclude that sum([]) = 0 from there. > > But what you can say is that for any list L, sum(L) = sum(L + [0]). > > Therefore sum([]) = sum([] +[0]) = 0 Yep. The way it is preserves the distributive property sum(a+b) = sum(a) + sum(b) This would matter in cases like (untested code..) suvsales = sum (sum (s.price for s in d.sales if s.class='suv') for d in districts) Mel. From marco.bizzarri at gmail.com Thu Sep 4 06:06:14 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 12:06:14 +0200 Subject: overwrite set behavior In-Reply-To: <g9obgu$1if$1@inews.gazeta.pl> References: <g9oat3$veh$1@nnrp-beta.newsland.it> <g9obgu$1if$1@inews.gazeta.pl> Message-ID: <3f0d61c40809040306y1bb0960di47c672b9ece37a8e@mail.gmail.com> On Thu, Sep 4, 2008 at 11:58 AM, Wojtek Walczak <gminick at bzt.bzt> wrote: > On Thu, 04 Sep 2008 11:48:18 +0200, Michele Petrazzo wrote: >> Hi all, I want to modify the method that set use for see if there is >> already an object inside its obj-list. Something like this: > ... >> It's possible? > > As far as I understand you, you need descriptors: > http://users.rcn.com/python/download/Descriptor.htm > I know descriptors a litte, Wojtek, but didn't use them often; can you elaborate a little more on your idea? > -- > Regards, > Wojtek Walczak, > http://tosh.pl/gminick/ > -- > http://mail.python.org/mailman/listinfo/python-list > Saluti Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From steve at REMOVE-THIS-cybersource.com.au Sat Sep 27 22:47:11 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Sep 2008 02:47:11 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <gbkfhv$g2$1@panix3.panix.com> <00edd041$0$20666$c3e8da3@news.astraweb.com> <8763oiuhj2.fsf@benfinney.id.au> <gblea5$os6$1@panix3.panix.com> <mailman.1600.1222551713.3487.python-list@python.org> Message-ID: <00eee9ec$0$20666$c3e8da3@news.astraweb.com> On Sat, 27 Sep 2008 17:41:42 -0400, Terry Reedy wrote: > In 3.0, at least, one does not need a disk file to create a module. > > >>> import types > >>> me = types.ModuleType('me') # type(__builtins__) works, no import > >>> me > <module 'me' (built-in)> > >>> me.a = 1 > >>> me.a > 1 > >>> me.a + 1 > 2 Seems to work for Python 2.5 as well. > That said, a blank class is even easier, and the representation is > better. And modules aren't callable. I've often thought they should be. -- Steven From bearophileHUGS at lycos.com Mon Sep 29 11:37:32 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 29 Sep 2008 08:37:32 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> <04fe8f12-2bec-4f54-aec2-d0ad169289f1@x35g2000hsb.googlegroups.com> <mailman.1662.1222661304.3487.python-list@python.org> <37efab3b-8404-4ffb-9899-922d438d9271@8g2000hse.googlegroups.com> <ec4d192c-2a5d-4fb0-a68d-041ab4d15260@d70g2000hsc.googlegroups.com> <0b2742b1-c3ee-4a13-abd1-e48d769865d0@z66g2000hsc.googlegroups.com> <48564dbf-08f6-43af-b63b-da5f3cb6db15@y21g2000hsf.googlegroups.com> <669d5609-4d95-4457-8f23-b44f1c8039d0@m36g2000hse.googlegroups.com> Message-ID: <45c74b74-214c-4fed-b691-6020a1aedce6@a1g2000hsb.googlegroups.com> George Sakkis: > No difference in principle, just len() happens to be implemented more > often than upper(). That's an important point. In a language that tries to be both practical, readable, and elegant, the things that are done more may deserve some sugar, to avoid code like this in many cases: sorted(seq, key=lambda x:x.__len__()) Bye, bearophile From half.italian at gmail.com Tue Sep 30 01:02:17 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Mon, 29 Sep 2008 22:02:17 -0700 (PDT) Subject: python & sms References: <c7a65808-8f2a-458e-9590-514eebd5f64e@u65g2000hsc.googlegroups.com> Message-ID: <ac27508b-a0ce-4fbf-9fba-3b7fbbb1044a@k30g2000hse.googlegroups.com> On Sep 29, 8:47?pm, sui <gogtesuy... at gmail.com> wrote: > Hii > i want a script to send sms to any mobile..... > can u help me ?? > > Thanks in advance...... Must...be...smarter...than...cell...phone... From mensanator at aol.com Sat Sep 6 14:22:07 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 6 Sep 2008 11:22:07 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <00d1f730$0$20302$c3e8da3@news.astraweb.com> Message-ID: <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> On Sep 5, 10:45?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > On Fri, 05 Sep 2008 22:20:06 -0400, Manu Hack wrote: > > On Fri, Sep 5, 2008 at 1:04 PM, castironpi <castiro... at gmail.com> wrote: <snip> > [The rest of this is (mostly) aimed at Mensanator, Ok, I see where you're coming from. > Fundamentally, the abstract function "sum" and the concrete Python > implementation of sum() are both human constructs. It's not like there is > some pure Platonic[1] "Ideal Sum" floating in space that we can refer to. > Somewhere, sometime, some mathematician had to *define* sum(), and other > mathematicians had to agree to use the same definition. > > They could have decided that sum must take at least two arguments, > because addition requires two arguments and it's meaningless to talk > about adding a single number without talking about adding it to something > else. But they didn't. Ok. But the problem is they DID in SQL: x + Null = Null. Earlier, you said that an empty box contains 0 widgets. Fine, empty means 0. But Null doesn't mean empty. Say your widget supplier just delivers a box and you haven't opened it yet. Is the box likely to be empty? Probably not, or they wouldn't have shipped it. In this case, Null means "unknown", not 0. The number of widgets you have on hand is Null (unknown) because inventory + Null = Null. SQL will correctly tell you that the amount on hand is unknown, whereas Python will tell you the amount on hand is inventory, which is incorrect. > Similarly, they might have decided that sum must > take at least one argument, and therefore prohibit sum([]), but they > didn't: it's more useful for sum of the empty list to give zero than it > is for it to be an error. As I mentioned earlier, mathematicians are > nothing if not pragmatists. > Here's a real world example (no ivory tower stuff): An oil refinery client has just excavated a big pile of dirt to lay a new pipeline. Due to the volume of the pipe, there's dirt left over. Ideally, the client would like to use that dirt as landfill (free), but it must be tested for HAPS (by summing the concentrations of organic constituents) to see whether it is considered hazardous waste, it which cas it must be taken off site and incinerated (costly). In MOST cases, a HAPS sum of 0 would be illegal because 0's generally cannot be reported in analytical tests, you can't report a result less than it's legal reporting limit. If ALL the consituents were undetected, the sum should be that of the sum of the reporting limits, thus, it cannot be 0. Can't I just use a sum of 0 to tell me when data is missing? No, because in some cases the reporting limit of undetected compounds is set to 0. In which case, a 0 HAPS score means we can confidently reccomend that the dirt is clean and can be freely reused. But if the analysis information is missing (hasn'r arrived yet or still pending validation) we WANT the result to be UNKNOWN so that we don't reccomend to the client that he take an illegal course of action. In this case, SQL does the correct thing and Python would return a false result. > -- > Steven From jpeyret at gmail.com Thu Sep 25 16:30:56 2008 From: jpeyret at gmail.com (J Peyret) Date: Thu, 25 Sep 2008 13:30:56 -0700 (PDT) Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <59a0d221-9f3b-4d9c-aa31-683eb615f3fd@i20g2000prf.googlegroups.com> On Sep 25, 12:24 pm, python-... at arcor.de wrote: > def whoisthethief("List" x): > return iknowit(x) > > def whoisthethief("String" x, "String" y): > return iknowit([x,y]) > I dunno if this is very Pythonic in nature, but I've done things like rebinding methods dynamically. ex: >>> def test(a): ... return a * 2 ... >>> print test(2) 4 >>> def test2(b): ... return b * 3 ... >>> test = test2 >>> print test(2) 6 In your case def myNewThiefIdentifier(x,y): return "Dunno" whoisthethief = myNewThiefIdentifier Which method would this affect (i.e. which 'whoisthethief')? I assume you could figure it out, given a match on the signature, but how much work would this require from the developer and the interpreter? (apologies in case Google Groups decide to multipost) From BjornSteinarFjeldPettersen at gmail.com Thu Sep 11 05:50:57 2008 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Thu, 11 Sep 2008 02:50:57 -0700 (PDT) Subject: Is there a SOAP module that can do this...? References: <07085aef-e27c-4186-92ae-1c817fe8d4a1@t54g2000hsg.googlegroups.com> <c6543cf6-aa50-439e-b60e-c012cdd28d10@y38g2000hsy.googlegroups.com> Message-ID: <ce910b1d-018e-4132-aeb5-b38e3f7c5c2f@e53g2000hsa.googlegroups.com> On Sep 10, 9:44?pm, Waldemar Osuch <waldemar.os... at gmail.com> wrote: > On Sep 10, 1:23?pm, thebjorn <BjornSteinarFjeldPetter... at gmail.com> > wrote:> I've been trying to use SOAPpy and ZSI (with and without the use of > > wsdl2py) to communicate with a SOAP server (looks like it's a WebLogic > > server(?) in front of some enterprise java bean) and not having much > > luck. ?I got them to send me an example of what the bytes on the wire > > are supposed to look like (attached below), and I got it to "work" by > > going lo-tech: > > If you are willing to go low tech you can tryhttp://effbot.org/downloads/#elementsoap > > But before you do that try:https://fedorahosted.org/suds > It is actively maintained and holds a lot of promise. > In my testing it knew how to connect to Sharepoint as well > as WebLogic exposed services. > > Waldemar Thanks for the info Waldemar. I'm looking into suds now, but there's something I'm having trouble wrapping my head around (xml isn't my usual territory, so this is perhaps obvious to someone...) This is what suds tells me: >>> print client suds ( version=0.2.9 ) service ( InboundLegacyDataService ) prefixes: ns0 = "http://no/brreg/BReMS/WebService/services" methods (2): getInfo() submitMessage(xs:string cpaid, xs:string securityKey, xs:string message, ) types (4): submitMessage submitMessageResponse getInfo getInfoResponse The method I'm interested in is submitMessage and in particular the ``xs:string message`` parameter. I've been provided with three xsd files that I'm almost 100% sure defines the format of the xml in the message (it defines the JegerproveInn sub-structure), but it looks like that has to be wrapped in a SOAP:Envelope, including the <?xml..> declaration before being stuffed into the xs:string message parameter, before that in turn is wrapped in an env:Envelope... Am I on the right track? Another question: I'm assuming the xsd files can be used for more than documentation :-) I've found the w3schools "Introduction to XML Schema" which I'm starting to read right now, however I haven't been able to google up any Python<->xsd "thingy" that looked promising (since I'm not sure what I'm looking for, this might not be a big surprise ;-) Is there such a "thingy"? Bjorn From pydecker at gmail.com Fri Sep 5 14:35:05 2008 From: pydecker at gmail.com (Peter Decker) Date: Fri, 5 Sep 2008 13:35:05 -0500 Subject: PyGUI as a standard GUI API for Python? In-Reply-To: <6id2n6FpunpvU1@mid.uni-berlin.de> References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> <6i7u02Fpeif6U1@mid.uni-berlin.de> <mailman.565.1220627973.3487.python-list@python.org> <6id2n6FpunpvU1@mid.uni-berlin.de> Message-ID: <ca55a9900809051135k51108278k26cacb7d3cca7f12@mail.gmail.com> On Fri, Sep 5, 2008 at 10:48 AM, Diez B. Roggisch <deets at nospam.web.de> wrote: > You got me wrong. I didn't say it doesn't use the native toolkit under > various OSes, I'm well aware of that it does. > > What I *did* say was that wx API is designed primarily with windows' toolkit > as base, and as a consequence the API tends to be less functional for other > toolkits, making it harder to work with it. As the OP was after a "one API > to rule them all" for GUIs, I pointed that out. > > See for example this (arguably somewhat dated) post that illustrates my > point: > > http://mail.python.org/pipermail/python-list/2005-March/313354.html OK, that's a little clearer. That's one of the things that I like about Dabo - it gets rid of the ugly (IMO) wxPython API and replaces it with a much more consistent (and, IMO) more Pythonic API. I hated coding in wx, but I love coding in Dabo. -- # p.d. From mark at thomaszone.com Fri Sep 26 12:54:04 2008 From: mark at thomaszone.com (Mark Thomas) Date: Fri, 26 Sep 2008 09:54:04 -0700 (PDT) Subject: lxml question References: <2f9ef7d5-616e-4a4b-9a83-e23194fee3a9@m3g2000hsc.googlegroups.com> Message-ID: <54d641a7-a07e-4eec-b20f-5f675405672f@e39g2000hsf.googlegroups.com> On Sep 26, 11:19?am, Uwe Schmitt <rocksportroc... at googlemail.com> wrote: > I have to parse some text which pretends to be XML. lxml does not want > to parse it, because it lacks a root element. > I think that this situation is not unusual, so: is there a way to > force lxml to parse it ? By "pretends to be XML" you mean XML-like but not really XML? > My work around is wrapping the text with "<root>...</root>" before > feeding lxmls parser. That's actually not a bad solution, if you know that the document is otherwise well-formed. Another thing you can do is use libxml2's "recover" mode which accommodates non-well-formed XML. parser = etree.XMLParser(recover=True) tree = etree.XML(your_xml_string, parser) You'll still need to use your wrapper root element, because recover mode will ignore everything after the first root closes (and it won't throw an error). -- Mark. From google at mrabarnett.plus.com Thu Sep 11 11:36:28 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Sep 2008 08:36:28 -0700 (PDT) Subject: emulating read and readline methods References: <ee4202f1-ce8f-458e-9627-08215351694d@e53g2000hsa.googlegroups.com> <e1941052-a524-477e-b498-521f52ea2b92@25g2000hsx.googlegroups.com> <ba72b905-d5b8-4e8c-9ef7-252c9e51a48d@a2g2000prm.googlegroups.com> <0d961161-3789-46c3-8018-06b26af7f767@x35g2000hsb.googlegroups.com> Message-ID: <a8c50843-4719-4d45-9f13-d2312f158590@2g2000hsn.googlegroups.com> On Sep 11, 9:23?am, Sean Davis <seand... at gmail.com> wrote: > On Sep 10, 7:54?pm, John Machin <sjmac... at lexicon.net> wrote: > > > > > On Sep 11, 8:01?am, MRAB <goo... at mrabarnett.plus.com> wrote: > > > > On Sep 10, 6:59?pm, Sean Davis <seand... at gmail.com> wrote: > > > > > I have a large file that I would like to transform and then feed to a > > > > function (psycopg2 copy_from) that expects a file-like object (needs > > > > read and readline methods). > > > > > I have a class like so: > > > > > class GeneInfo(): > > > > ? ? def __init__(self): > > > > ? ? ? ? #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > > > > gene_info.gz',"/tmp/gene_info.gz") > > > > ? ? ? ? self.fh = gzip.open("/tmp/gene_info.gz") > > > > ? ? ? ? self.fh.readline() #deal with header line > > > > > ? ? def _read(self,n=1): > > > > ? ? ? ? for line in self.fh: > > > > ? ? ? ? ? ? if line=='': > > > > ? ? ? ? ? ? ? ? break > > > > ? ? ? ? ? ? line=line.strip() > > > > ? ? ? ? ? ? line=re.sub("\t-","\t",line) > > > > ? ? ? ? ? ? rowvals = line.split("\t") > > > > ? ? ? ? ? ? yield "\t".join([rowvals[i] for i in > > > > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > > > > ? ? def readline(self,n=1): > > > > ? ? ? ? return self._read().next() > > > > > ? ? def read(self,n=1): > > > > ? ? ? ? return self._read().next() > > > > Each time readline() and read() call self._read() they are creating a > > > new generator. They then get one value from the newly-created > > > generator and then discard that generator. What you should do is > > > create the generator in __init__ and then use it in readline() and > > > read(). > > > > > ? ? def close(self): > > > > ? ? ? ? self.fh.close() > > > > > and I use it like so: > > > > > a=GeneInfo() > > > > cur.copy_from(a,"gene_info") > > > > a.close() > > > > > It works well except that the end of file is not caught by copy_from. > > > > I get errors like: > > > > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > > > > during .read() call > > > > CONTEXT: ?COPY gene_info, line 1000: "" > > > > > for a 1000 line test file. ?Any ideas what is going on? > > > > I wonder whether it's expecting readline() and read() to return an > > > empty string at the end of the file instead of raising StopIteration. > > > Don't wonder; ReadTheFantasticManual: > > > read( [size]) > > > ... An empty string is returned when EOF is encountered > > immediately. ... > > > readline( [size]) > > > ?... An empty string is returned only when EOF is encountered > > immediately. > > Thanks. ?This was indeed my problem--not reading the manual closely > enough. > > And the points about the iterator being re-instantiated were also > right on point. ?Interestingly, in this case, the code was working > because read() and readline() were still returning the next line each > time since the file handle was being read one line at a time. > After further thought, do you actually need a generator? read() and readline() could just call _read(), which would read a line from the file and return the result or an empty string. Or the processing could be done in readline() and read() just could call readline(). From brtzsnr at gmail.com Fri Sep 5 05:46:56 2008 From: brtzsnr at gmail.com (Alexandru Mosoi) Date: Fri, 5 Sep 2008 02:46:56 -0700 (PDT) Subject: derived classes and __getattr__ References: <d5a86bf2-2b8c-487f-9097-51bc92ef478d@w24g2000prd.googlegroups.com> <g9qrmh$k62$02$1@news.t-online.com> Message-ID: <4aea3086-9310-403a-8ddf-9180b3385e76@r15g2000prh.googlegroups.com> On Sep 5, 11:47?am, Peter Otten <__pete... at web.de> wrote: > Alexandru Mo?oi wrote: > > i'm facing the following problem: > > > class Base(object): > > ? def __getattr__(self, attr): return lambda x: attr + '_' + x > > > def dec(callable): > > ? return lambda *args: 'dec_' + callable(*args) > > > class Derived(Base): > > ? ?what_so_ever = dec(Base.what_so_ever) # wrong, base doesn't have > > what_so_ever > > ? ?mumu = dec(Base.mumu) ? ? ? ? ? ? ? ? ? ? ? ? ?# wrong, base > > doesn't have mumu > > > any idea how to do this? > > __getattr__() is defined in the class to create instance attributes on the > fly. If you want class attributes you have to put the __getattr__() method > into the class of the class, or "metaclass": > > class Base(object): > ? ? class __metaclass__(type): > ? ? ? ? def __getattr__(self, attr): > ? ? ? ? ? ? return lambda self, x: attr + '_' + x > > def dec(callable): > ? ? return lambda *args: 'dec_' + callable(*args) > > class Derived(Base): > ? ?what_so_ever = dec(Base.what_so_ever) > > d = Derived() > print d.what_so_ever("42") > > I don't see how you can turn this into something useful... > > Peter 10x. it works. however I have another small problem. now, d.third('blah') doesn't work because instance d doesn't have 'third' attribute. I was expecting derived class to inherit the metaclass as well, but it didn't. From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 8 09:46:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Sep 2008 15:46:57 +0200 Subject: Dictionaries and loops In-Reply-To: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> References: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> Message-ID: <48c52c54$0$16982$426a74cc@news.free.fr> Mike P a ?crit : > Hi All > i have a CSV file that i'm reading in and each line has the look of > the below > > {None: ['User-ID', 'Count']} > {None: ['576460847178667334', '1']} > {None: ['576460847178632334', '8']} This doesn't look like a CSV file at all... Is that what you actually have in the file, or what you get from the csv.reader ??? > i want to make a dictionary of items in the form > {576460847178667334:1, 576460847178632334:8, ..... } for all rows in > the datafile > > my code so far is thus: > > dict1={} > j=1 > for row in reader1: > if j==1: > j+=1 > continue #thus allowing me to skip the first row > if j>1: Drop this, and call reader1.next() before entering the loop. > for element in row.values(): > for item in element: > if int(item)%2==0: > dict1[int(item)] = int(item)+1 You're repeating the same operation (building an int from a string) three time, where one would be enough: for item in element: item = int(item) if item %2 == 0: # or : if not item % 2: dict1[item] = item + 1 But this code is not going to yield the expected result... > # i know this is the problem line as it's not picking the second item > up just finding the first and increasing it, but i can't figure out > how to correct this? Mmm... What about learning Python instead of trying any random code ? Programming by accident won't take you very far, and you can't expect this neswgroup to do your own work. Ok, assuming your CSV file looks like this - and you never have duplicate values for the User-id column: # source.csv "User-ID", "Count" 576460847178667334, 1 576460847178632334, 8' Here's a possible solution: result = {} src = open("source.csv", "rb") try: reader = csv.reader(src) reader.next() for row in reader: user_id, count = int(row[0]), int(row[1]) result[user_id] = count finally: src.close() or more tersely: src = open("source.csv", "rb") try: reader = csv.reader(src) reader.next() result = dict(map(int, row) for row in reader) finally: src.close() From castironpi at gmail.com Wed Sep 17 19:45:40 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 17 Sep 2008 16:45:40 -0700 (PDT) Subject: decorator and API References: <mailman.1183.1221688957.3487.python-list@python.org> <160e332b-3b46-4a9f-957b-0eb8199ed3d7@8g2000hse.googlegroups.com> Message-ID: <e1b089e4-13f9-40cd-b5ff-98ffed5d036a@d45g2000hsc.googlegroups.com> On Sep 17, 6:09?pm, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 17, 4:56?pm, Lee Harr <miss... at hotmail.com> wrote: > > > > > I have a class with certain methods from which I want to select > > one at random, with weighting. (snip) > > > The problem I have now is that if I subclass A and want to > > change the weighting of one of the methods, I am not sure > > how to do that. > > > One idea I had was to override the method using the new > > weight in the decorator, and then call the original method: > > > class B(A): > > ? ? @weight(50) > > ? ? def action_1(self): > > ? ? ? ? A.action_1(self) > > > That works, but it feels messy. > > > Another idea was to store the weightings as a dictionary > > on each instance, but I could not see how to update that > > from a decorator. > > > I like the idea of having the weights in a dictionary, so I > > am looking for a better API, or a way to re-weight the > > methods using a decorator. > > > Any suggestions appreciated. > > class A: > ? ?weights= WeightOb() #just a dictionary, mostly > ? ?@weights( 10 ) ... > ? ?@weights( 20 ) ... > > class B( A ): > ? ?weights= WeightOb( A.weights ) #new, refs "super-member" > ? ?@weights( 50 ) ... Lee, Probably overkill. Here's a solution like above. class WeightOb( object ): def __init__( self, *supers ): self.weights= {} self.supers= supers def set( self, weight ): def __callset__( fun ): self.weights[ fun.func_name ]= weight return fun return __callset__ def reset( self, weight, fun ): self.weights[ fun.func_name ]= weight return fun #search parent 'weight' objects #return 'child-most' weight of 'name' def get_weight( self, name ): if name in self.weights: return self.weights[ name ] else: for x in self.supers: try: return x.get_weight( name ) except KeyError: #not found pass raise KeyError #returns a dictionary mapping bound instances to weights #(hence the second parameter) def contents( self, inst ): d= {} for x in reversed( self.supers ): d.update( x.contents( inst ) ) d.update( dict( [ ( getattr( inst, k ), v ) for k, v in self.weights.iteritems( ) ] ) ) return d class A( object ): weights= WeightOb( ) @weights.set( 10 ) def action_1( self ): print 'action_1' @weights.set( 20 ) def action_2( self ): print 'action_2' #WeightOb.contents needs to know which instance to bind #functions to. Get weights from an instance that has them. def getweights( self ): return self.weights.contents( self ) class B( A ): weights= WeightOb( A.weights ) action_2= weights.reset( 50, A.action_2 ) a= A() b= B() print a.weights.get_weight( 'action_1' ) print a.weights.get_weight( 'action_2' ) print b.weights.get_weight( 'action_1' ) print b.weights.get_weight( 'action_2' ) print a.getweights( ) print b.getweights( ) /Output: 10 20 10 50 {<bound method A.action_2 of <__main__.A object at 0x00A04070>>: 20, <bound meth od A.action_1 of <__main__.A object at 0x00A04070>>: 10} {<bound method B.action_2 of <__main__.B object at 0x00A04090>>: 50, <bound meth od B.action_1 of <__main__.B object at 0x00A04090>>: 10} From skip at pobox.com Tue Sep 9 09:23:11 2008 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 Sep 2008 08:23:11 -0500 Subject: creating an (inefficent) alternating regular expression from a list of options In-Reply-To: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> References: <5b90f11a-472d-408d-b416-63b87da6fbe6@z72g2000hsb.googlegroups.com> Message-ID: <18630.30911.707343.588287@montanaro-dyndns-org.local> >> I really dont care if the expression is optimal. So the goal is >> something like: >> vowel_regexp = oneOf("a aa i ii u uu".split()) # yielding r'(aa|a|uu| >> u|ii|i)' >> Is there a public module available for this purpose? Check Ka-Ping Yee's rxb module: http://lfw.org/python/ Needs translating from the old regex module to the current re module, but it shouldn't take a lot of effort. You can find regex docs in old distributions (probably through 2.1 or 2.2?). Also, check PyPI to see if someone has already updated rxb for use with re. Skip From simon.palmer at gmail.com Wed Sep 3 17:59:44 2008 From: simon.palmer at gmail.com (SimonPalmer) Date: Wed, 3 Sep 2008 14:59:44 -0700 (PDT) Subject: Python on the web - newby question References: <6822d749-cc00-48ce-a30a-ded96a938e79@b30g2000prf.googlegroups.com> <48bf0459$0$27459$426a74cc@news.free.fr> Message-ID: <f460a507-1ac6-4d30-966e-5347a768a640@s1g2000pra.googlegroups.com> On Sep 3, 8:41?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > SimonPalmer a ?crit : > > > Apologies in advance if this is either a) the wrong board or b) been > > answered a million times elsewhere, but... > > > I have been given an assignment to get a python module up and running > > behind an existing web site. ?At the moment the rest of the site is > > developed in PHP but the hosts have said they will provide python > > support for free, although they haven't given any more details than > > that, so I'm not sure exactly what that means. > > Depending on the hosts, this can range from having an antiquated python > version with only cgi enabled and no way to install anything to the very > last stable release and (almost) whatever third-part lib / frameworks > and correct configuration. > > > ?All reasonably > > encouraging though. > > > I'm a newbie to python but quite experienced with Java/J2EE/JBoss. > > Quite another world... > > > What I need to know is how I get python running on the server > > For which definition of 'server' ? The computer, or the web server process ? > > > and what > > tools/middleware I would need to have installed on the host's machines > > to be able to support my python modules. > > Depends on your modules dependencies !-) > > More seriously : Python is known has being the language with more web > frameworks than keywords. IOW, there's no simple straightforward answer > to your question. Fisrt choose which Python web development solution you > intend to use, then read the FineManual's "deployment" section of the > chosen solution. > > You'll find pointers to most web-related libs / frameworks here:http://wiki.python.org/moin/WebFrameworkshttp://wiki.python.org/moin/WebProgramming > > Given your situation (Python newcomer with a real job to do), and if > your job is anything more than a very Q&D deadsimple task, I'd > personnaly recommand Django (http://djangiproject.com). Don't let the > version number fools you (latest version is 1.0 release candidate), > Django is a mature, solid and proven solution that have years of > existance, and what they call 1.0rc would be labeled at least 3.5 for > some other software... It's also mostly documented, and there's a strong > community around the framework, so you should not have much problem > getting help. > > For any other Python question (I mean, non django-related), you're at > the right place. > > Oh, and yes, if I may suggest a reading:http://dirtsimple.org/2004/12/python-is-not-java.html > > HTH, and welcome on board... Hey, thanks very much this is really helpful. What I really need is pointers, I'm sure I can figure the rest out. I am indeed a guy with a real job to do. Doesn't help that the client and host are on the other side of the world. I quite like python. As a veteran coder who has tried a lot of languages this has been a pleasant experience so far. I *really* like numpy and scipy. My stock in trade is algorithms and they are quite a revelation. I wish I had known about them sooner and I think they will keep me coming back to python regularly. Thanks again. SP From nishalrs at yahoo.co.uk Mon Sep 29 09:00:19 2008 From: nishalrs at yahoo.co.uk (nishalrs) Date: Mon, 29 Sep 2008 13:00:19 -0000 Subject: writing dll in python? Message-ID: <gbqjh3+39e0@eGroups.com> Hello All, My main motivation is to build a collection of useful mathematical models (that I have developed over the years) to design ultrasonic sensors. This should be some sort of a library that should be able to be used for desktop/web application development, to run in variety of operating systems. I am more than convinced after looking at python.org website, it is the right tool for the job. I intend to learn python, but I am not really sure, where to begin. Should I write all the functions as simple python scripts? Or is there some facility for creating a .dll like library, that could be more suitable for what in intend to develop? Any help is much appreciated. Regards, Nishal From skip at pobox.com Fri Sep 26 19:27:11 2008 From: skip at pobox.com (skip at pobox.com) Date: Fri, 26 Sep 2008 18:27:11 -0500 Subject: Are spams on comp.lang.python a major nuisance? In-Reply-To: <4b195687-e4a5-4fdd-89b2-f3906e625770@j22g2000hsf.googlegroups.com> References: <mailman.1533.1222428711.3487.python-list@python.org> <4b195687-e4a5-4fdd-89b2-f3906e625770@j22g2000hsf.googlegroups.com> Message-ID: <18653.28623.732020.288418@montanaro-dyndns-org.local> Aaron> Is there such a thing as an open-source spam filter? That way Aaron> any time anyone had spare time and got annoyed, they could dump a Aaron> short snippet of code into the grinder. Yes: <http://spambayes.sf.net/> though I think your model of how it works probably needs a bit of refinement. <wink> You might want to read through the background reading page: <http://spambayes.sf.net/background.html>. It's what we're running on the python.org site. The initial impetus for it came from a desire to filter spam for python.org mailing lists. If you'd like to contribute we can always use developers. Skip From emile at fenx.com Fri Sep 12 13:43:08 2008 From: emile at fenx.com (Emile van Sebille) Date: Fri, 12 Sep 2008 10:43:08 -0700 Subject: manipulating files within 'for' In-Reply-To: <48CAA2AA.40809@umbc.edu> References: <48CAA2AA.40809@umbc.edu> Message-ID: <gae9jj$sks$1@ger.gmane.org> Ben Keshet wrote: > Hi Pythoneers, > > I have a question about a code I wrote with the help of someone. The > code below copy a few lines from different files into one file. It works > fine as it is given here and generates the new file 'pockets.out' > correctly, but says:"....py returned exit code 0". However, if I add > more values to 'receptor' (say, receptor = ['1AZM' '1ADS']) At risk of stating the obvious, you _did_ put this in properly as receptors = ['1AZM', '1ADS'] ...right? Emile it gives an > error: "Exception raised while running script". > > Can anyone please advice me? Why is it giving an error on multiple x but > runs well with one (I made sure that all files and folders exist, etc.). > What does exit code 0 mean? No error > what does "exception raised" mean? Error From ggpolo at gmail.com Sat Sep 20 16:37:06 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 20 Sep 2008 17:37:06 -0300 Subject: [Tkinter-discuss] (newbie) can't invoke button for twice In-Reply-To: <19588292.post@talk.nabble.com> References: <19588292.post@talk.nabble.com> Message-ID: <ac2200130809201337h3d9ac853y35b667e5b2b8c3dc@mail.gmail.com> On Sat, Sep 20, 2008 at 4:10 PM, dmitrey <dmitrey15 at ukr.net> wrote: > > hi all, > I have the problem: > a func has been binded to a Button: > > RunPause = Button(root, textvariable = t, command = lambda: > invokeRunPause(p)) > > def invokeRunPause(p): > if p.state == 'init': > p.state = 'running' > t.set(' Pause ') > p.GUI_root.update_idletasks() > p.tmp_result = p.solve(*p._args, **p._kwargs) > > elif p.state == 'running': > .... > So the problem is that I can't invoke the button RunPause till my > calculations (in p.solve()) will be finished. I can observe it even > graphically, the button doesn't respond when it is pressed. > Could anyone provide a solution? It is not only the button that doesn't respond, the entire application won't respond if you are blocking tcl from processing anything. This call to p.solve blocks, and, in turn the interpreter can't process events and the GUI remains frozen till p.solve returns. Ideally you should break this p.solve in steps, so you can schedule next steps and the GUI will remain responsible, but if you can't break it, and if it doesn't make sense to run it in another process then you use a thread to solve this. > > Thank you ion advance, Dmitrey. > -- > View this message in context: http://www.nabble.com/%28newbie%29-can%27t-invoke-button-for-twice-tp19588292p19588292.html > Sent from the Python - tkinter-discuss mailing list archive at Nabble.com. > > _______________________________________________ > Tkinter-discuss mailing list > Tkinter-discuss at python.org > http://mail.python.org/mailman/listinfo/tkinter-discuss > -- -- Guilherme H. Polo Goncalves From Lie.1296 at gmail.com Sun Sep 28 17:19:15 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 28 Sep 2008 14:19:15 -0700 (PDT) Subject: Why are "broken iterators" broken? References: <00e65e7b$0$20303$c3e8da3@news.astraweb.com> Message-ID: <039352a3-45ce-4784-8ff2-244ed6953cd4@p31g2000prf.googlegroups.com> On Sep 21, 10:13?pm, Steven D'Aprano <st... at REMOVE-THIS- cybersource.com.au> wrote: > According to the Python docs, once an iterator raises StopIteration, it > should continue to raise StopIteration forever. Iterators that fail to > behave in this fashion are deemed to be "broken": > > http://docs.python.org/lib/typeiter.html > > I don't understand the reasoning behind this. As I understand it, an > iterator is something like a stream. There's no constraint that once a > stream is empty it must remain empty forever. I think empty != StopIteration. StopIteration (IMHO) shouldn't be raised when the stream is empty, instead a sentinel value specifying that "there is no data yet, but if you wait there might be" should be returned (possibly None or empty string). When you raise StopIteration, it is a signal that I don't have any more data and there is no use in waiting. > Can somebody explain why "broken iterators" are broken? > > -- > Steven From tino at wildenhain.de Sat Sep 27 10:14:31 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Sat, 27 Sep 2008 16:14:31 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> <170543c70809261505j6914f0cdg1c880ab05704407f@mail.gmail.com> Message-ID: <48DE3FC7.4030307@wildenhain.de> Hi, Michael Mabin wrote: > so you wouldn't object then to something like > > '.... in (%)' % ','.join([str_edit_for_exploit(x) for x in aList]) > > if str_edit_for_exploit applied security edits? Whats an security edit btw? If it is something meant to turn possibly insecure data into 'secure' then, no I would still object. Why? Because its a bad example of "default permit". Its always better to have a whitelist - even more so when its so easy to do. Its just a habit you develope - if you never do it right, how would you know when and how to do it right when you need to? Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080927/1b1daf92/attachment-0001.bin> From timr at probo.com Thu Sep 25 02:39:24 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 25 Sep 2008 06:39:24 GMT Subject: curses.setsyx()? References: <f4bfa060-3053-4ca6-90c2-2a057bfedf79@34g2000hsh.googlegroups.com> <tqd6d4po3dmvba3a3v1a8c2b34qgfmc8d9@4ax.com> <550ab070-ab4a-401b-abe2-45f9f9ec772d@r66g2000hsg.googlegroups.com> <38efe340-e0e7-46e8-a022-ad494af66583@m73g2000hsh.googlegroups.com> <naogd45497jn4s8jegu15j4u1oo49cinqc@4ax.com> <713190fc-e3a9-4a72-8bee-4fd3affcb531@c58g2000hsc.googlegroups.com> <ea23fc87-feb5-4853-bf0f-58e69b890af7@t54g2000hsg.googlegroups.com> Message-ID: <5acmd4t7p44cbgi1fkmhaaasfplv0jaatr@4ax.com> linkmaster032000 at gmail.com wrote: >On Sep 23, 4:16?pm, brad.at.sch... at gmail.com wrote: >> On Sep 22, 11:24?pm, Tim Roberts <t... at probo.com> wrote: >> > linkmaster032... at gmail.com wrote: >> > >On Sep 19, 6:42?pm, linkmaster032... at gmail.com wrote: >> > >> On Sep 19, 1:24?am, Tim Roberts <t... at probo.com> wrote: >> >> > >> > linkmaster032... at gmail.com wrote: >> >> > >> > >I tried curses.setsyx(2,3) in my script and it doesn't move the curses >> > >> > >cursor. Any alternatives/solutions? >>... >> > >> I added it and it still doesn't work. This is what I'm doing when I >> > >> want to display the cursor and prepare it for input at 2,3: >> >> > >> curses.echo() >> > >> curses.curs_set(1) >> > >> curses.setsyx(2,3) >> > >> curses.doupdate() >> >> > >Any idea what's wrong? >> >> http://pastebin.com/m6413db1 >> >> Run that and press 'n' key. It is supposed to move the cursor to 2,3 >> and it doesn't. Of course it does. It moves the cursor, then does an update, then immediately calls draw.game, which redraws the screen and moves the cursor. If you want curses.setsyx (or the equivalent and more mnemonic scr.move) to leave the cursor somewhere, you can't draw more text afterward. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From digitig at gmail.com Mon Sep 22 09:45:20 2008 From: digitig at gmail.com (Tim Rowe) Date: Mon, 22 Sep 2008 14:45:20 +0100 Subject: What do you call a class not intended to be instantiated In-Reply-To: <48d78c3c$0$6998$426a74cc@news.free.fr> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> <48d7720d$0$12866$426a34cc@news.free.fr> <mailman.1358.1222081500.3487.python-list@python.org> <48d78c3c$0$6998$426a74cc@news.free.fr> Message-ID: <aee48b3c0809220645s6bf8ac24n373aa726358b211a@mail.gmail.com> 2008/9/22 Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid>: >> Sounds to me like a functor, aka a function object: >> http://en.wikipedia.org/wiki/Function_object >> > > Ok, then the simple solution is to implement a callable type (__call__ > method), possibly with appropriate support for the descriptor protocol if > it's meant to be usable as a method. Yes -- and instantiate the thing and keep the state in the instance, rather than keeping the state in the class, so that it's possible to safely have more than one of them if a later design change calls for it (probably what led people off onto the sidetrack of thinking a singleton was called for). That's the classic way of implementing a "class [to be] used as a function". -- Tim Rowe From castironpi at gmail.com Wed Sep 24 15:45:41 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 12:45:41 -0700 (PDT) Subject: PyRun_SimpleFile() crashes References: <d71e6607-31ca-48a6-b61f-040536a7cebf@g17g2000prg.googlegroups.com> <slrngdk68l.fu2.nick@irishsea.home.craig-wood.com> <26532f88-b70c-4b18-af4d-5176ec023f46@c65g2000hsa.googlegroups.com> Message-ID: <2facaea6-3a54-45e6-86e8-a0aee9a90522@m73g2000hsh.googlegroups.com> On Sep 24, 11:05?am, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 24, 6:30?am, Nick Craig-Wood <n... at craig-wood.com> wrote: > > > > > lixinyi... at gmail.com <lixinyi... at gmail.com> wrote: > > > ?my code: > > > ?main.cpp > > > ?#include <Python.h> > > > > ?int main(int argc, char **argv) > > > ?{ > > > ?Py_Initialize(); > > > > ?FILE *file_1 = fopen("a2l_reader.py","r+"); > > > ?PyRun_SimpleFile(file_1,"a2l_reader.py"); > > > > ?Py_Finalize(); > > > ?} > > > > ?compile under windows using MinGW: > > > ?g++ main.cpp libpython25.a -o a > > > > ?no error was found. But when I run a.exe the program just crashes. > > > > ?What should I do? > > > Run it under gdb (which should have come with MinGW). > > > Check that you actually opened the file, ie file_1 != 0. > > > This might be relevant > > > ?http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-o... > > > -- > > Nick Craig-Wood <n... at craig-wood.com> --http://www.craig-wood.com/nick > > There's a workaround. > > filename = "Entire path of the python file"; > PyObject* PyFileObject = PyFile_FromString(filename, "r"); > PyRun_SimpleFile(PyFile_AsFile(PyFileObject), filename); > // decref PyFileObject > > http://mail.python.org/pipermail/python-list/2007-March/431725.htmlhttp://python-forum.org/pythonforum/viewtopic.php?f=15&t=1554&p=6567 Just to follow up-- The links say that the crash comes from opening a file with two different versions of a library. Would it be possible to get an API entry point to the version the build uses? It does use the 'fopen' function by name, but not the same version. And creating the entire object just to get its f_fp field is really long. From pavlovevidence at gmail.com Wed Sep 24 05:53:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 24 Sep 2008 02:53:48 -0700 (PDT) Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> Message-ID: <84668bf4-a8d9-4140-b405-63d82d4f85ce@c65g2000hsa.googlegroups.com> On Sep 22, 4:02?am, Al Kabaila <akaba... at pcug.org.au> wrote: > 1. Is there any interest in matrix algebra "for the masses" (I mean interest > in a wrapper for a subset of functions of the packages with a unified > simple syntax)? I wouldn't since I do pretty advanced stuff and I'm happy to use numpy as-is, but I suspect a lot of people would find a convenient basic matrix library useful. > 2. What other matrix operations would be required for your area of interest? Your short list covers most of the important stuff. Graphics and simulation make use of rigid transformations a lot (composition of rotations and stuff). It's pretty straightforward and specialized so I'd give it low priority. I use linear least squares (psuedoinverse) occasionally for curve- fitting. > 3. What other matrix packages, if any, should one include in the wrapper? Oftentimes libraries like this have a dumb implementation, that uses only the basic machinery that ships with every system. You might consider such an implementation of your API that uses only Python lists or arrays. One matrix API that is pretty irritating is Blender's; in fact whenever I write Blender plugins I usually do all the dirty work with numpy. Carl Banks From pavlovevidence at gmail.com Sat Sep 13 01:08:14 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 12 Sep 2008 22:08:14 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? References: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> Message-ID: <12aaddbd-6589-409e-b6d3-b06eda7f4cab@a3g2000prm.googlegroups.com> On Sep 12, 9:08?pm, i... at illusorygoals.com wrote: > First off, I'm a python n00b, so feel free to comment on anything if > I'm doing it "the wrong way." I'm building a discrete event simulation > tool. I wanted to use coroutines. However, I want to know if there's > any way to hide a yield statement. > > I have a class that I'd like to look like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? result = self.ping("128.111.41.38") > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > But because I can't hide yield inside ping, and because I can't find a > convenient way to get a self reference to the coroutine (which is used > by the event queue to pass back results), my code looks like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? # I dislike this next line > ? ? ? ? self.this_pointer = (yield None) > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? # I want to get rid of the yield in the next line > ? ? ? ? ? ? result = (yield self.ping("128.111.41.38")) > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > I'd like to know, is there a way to get the syntax I want? I think you're stuck with using threads in a standard Python release. Generators can't serve as coroutines when you're yielding from a nested call (they only go one level deep). You can get coroutines with Stackless Python, a non-standard version of Python. But even with Stackless I got the impression that you'd be building coroutines atop something that was fairly thread-like. There is no coroutine syntax. Carl Banks From hjtoi-better-remove-when_replying at comcast.net Tue Sep 16 02:48:33 2008 From: hjtoi-better-remove-when_replying at comcast.net (Heikki Toivonen) Date: Mon, 15 Sep 2008 23:48:33 -0700 Subject: How to convert M2Crypto.RSA.RSA to string In-Reply-To: <mailman.1040.1221484013.3487.python-list@python.org> References: <a3158e8b0809142323t2a2d2c7dm8bb65482e25a1d1@mail.gmail.com> <mailman.1040.1221484013.3487.python-list@python.org> Message-ID: <48CF56C1.50208@comcast.net> > On Mon, Sep 15, 2008 at 8:23 AM, Usman Ajmal <uzmanajmal at gmail.com> wrote: >> I have a M2Crypto.RSA.RSA instance that contain my public-key. I want that >> key as string. Is there any way to convert the said instance into string? Take a look at as_pem() method. -- Heikki Toivonen From jepe_abrantes at hotmail.com Mon Sep 15 07:02:58 2008 From: jepe_abrantes at hotmail.com (=?iso-8859-1?Q?Jo=E3o_Abrantes?=) Date: Mon, 15 Sep 2008 11:02:58 +0000 Subject: how to protect the source Message-ID: <BLU115-W513E8E918A8A16CEB298E596520@phx.gbl> Hello Everyone. I am building a client in python that will connect himself to a mysql server with a certain username and password. I will compile this client and turn him into a .exe . The thing is that I know that is possible to get the source of the code back from an .exe and I don't want anyone to know which username and password are they using because I don't want them to access to the mysql server without my client. Do you have any ideas of what can i do? Thanks! _________________________________________________________________ Connect to the next generation of MSN Messenger? http://imagine-msn.com/messenger/launch80/default.aspx?locale=en-us&source=wlmailtagline -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/b44c0b51/attachment-0001.html> From m_palmer45 at yahoo.ca Wed Sep 3 15:29:53 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Wed, 3 Sep 2008 12:29:53 -0700 (PDT) Subject: Help needed to freeze a script. References: <7f364174-75c6-4120-b00e-6f41643ccbf5@z72g2000hsb.googlegroups.com> Message-ID: <614c7366-ba7e-4296-a4f0-a32accaa427a@b38g2000prf.googlegroups.com> On Sep 3, 1:30 pm, LB <berthe.l... at gmail.com> wrote: > Hi, > > I would like to freeze a numpy based script in order to have an > application which could run without having to install numpy and cie. > > Indeed, I'm not root on the targeted computer and I can't easily > make a complete install of numpy and scipy. > > So I decided to test the freeze.py tool shipped with python2.5. > To complicate matters, I must say that I only have a local > installation > of python2.5 and numpy. > > I used the following command line : > > > python2.5 ../Python-2.5.1/Tools/freeze/freeze.py ~/Python/numpy/test_freeze.py > > At first sight, it seems to be fine, as I saw numpy in the liste of > frozen dependancies : > [...] > freezing numpy ... > freezing numpy.__config__ ... > freezing numpy._import_tools ... > freezing numpy.add_newdocs ... > freezing numpy.core ... > freezing numpy.core._internal ... > freezing numpy.core.arrayprint ... > freezing numpy.core.defchararray ... > freezing numpy.core.defmatrix ... > freezing numpy.core.fromnumeric ... > freezing numpy.core.info ... > freezing numpy.core.memmap ... > freezing numpy.core.numeric ... > freezing numpy.core.numerictypes ... > freezing numpy.core.records ... > freezing numpy.ctypeslib ... > [...] > freezing numpy.version ... > > But at the end I saw this message : > Warning: unknown modules remain: _bisect _csv _ctypes _curses _hashlib > _heapq > [...] > numpy.core._dotblas numpy.core._sort numpy.core.multiarray > numpy.core.scalarmath numpy.core.umath numpy.fft.fftpack_lite > numpy.lib._compiled_base numpy.linalg.lapack_lite numpy.random.mtrand > operator parser pyexpat readline > [...] > Now run "make" to build the target: test_weibull > > I runned make without any problem but the final application didn't > work : > % ./test_freeze > Traceback (most recent call last): > File "/home/loic/Python/numpy/test_freeze.py", line 8, in <module> > import numpy as np > [...] > File "/home/loic/tmp/bluelagoon/lib/python2.5/site-packages/numpy/ > core/__init__.py", line 5, in <module> > import multiarray > ImportError: No module named multiarray > > Is there any known issue when freezing a numpy based script ? > I should add that I configured my PYTHONPATH to match my local > installation > > echo $PYTHONPATH > /home/loic/lib/python:/home/loic/tmp/bluelagoon/lib/python2.5:/home/ > loic/tmp/bluelagoon/lib/python2.5/site-packages/: > > and this local installation work fine : > > > python2.5 -c 'import numpy; print numpy.__version__; import numpy.core.multiarray; print "no pb"' > > 1.2.0b2 > no pb > > Have you got any recipe to freeze numpy based script ? > > Regards, > > -- > LB Did you try py2exe instead of freeze? On the page http://www.py2exe.org/index.cgi/WorkingWithVariousPackagesAndModules there is only one brief mention of numpy packaging troubles, suggesting that it might work better. I have used py2exe in the past without much trouble. From mhuening at zedat.fu-berlin.de Wed Sep 10 10:11:40 2008 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Wed, 10 Sep 2008 16:11:40 +0200 Subject: PHP's str_replace ? In-Reply-To: <6iq2jpFs113rU1@mid.uni-berlin.de> References: <mailman.788.1221054649.3487.python-list@python.org> <6iq2jpFs113rU1@mid.uni-berlin.de> Message-ID: <6iq2sbFs113rU2@mid.uni-berlin.de> Matthias Huening (10.09.2008 16:07): > Anjanesh Lekshminarayanan (10.09.2008 15:50): >> In PHP, if I do >> str_replace(array('a', 'e', 'i', 'o', 'u'), '-', $str) >> it'll replace all vowels with a hyphen in string $str. >> >> Is there some equivalent in Python ? > > What about something like this: > > import re > new_str = re.sub('([aeiou])-', r'\1', str) > Sorry - I misinterpreted your question. Try this instead: import re new_str = re.sub('[aeiou]', '-', str) matthias From agostino.russo at gmail.com Tue Sep 9 14:55:30 2008 From: agostino.russo at gmail.com (ago) Date: Tue, 9 Sep 2008 11:55:30 -0700 (PDT) Subject: PYTHONSITEDIR environment variable References: <eccd24ff-001b-4f4e-a9da-c7052d67383d@k30g2000hse.googlegroups.com> <mailman.744.1220982999.3487.python-list@python.org> <e3f06a84-5888-462c-87df-1dfba494362a@2g2000hsn.googlegroups.com> <mailman.747.1220985923.3487.python-list@python.org> Message-ID: <6e024b6a-c86c-4690-ad86-951c8118e3fd@m45g2000hsb.googlegroups.com> On Sep 9, 7:45?pm, Christian Heimes <li... at cheimes.de> wrote: > ago wrote: > > The only thing I would add is that in my experience I often use > > different working-envs for different projects, so I'd prefer to have a > > more generic solution as opposed to a single working-env per user. The > > latter could still be achieved by setting the appropriate environment > > variable in the user profile. Do you think it would be possible to > > accommodate for the above in your PEP? > > Isn't PYTHONUSERBASE sufficient for your needs? The env var alters the > base directory. > > I can neither change the PEP nor the implementation at this stage of the > development cycle. Python 2.6 and 3.0 are in beta and the API is set in > stone. > > Christian I had missed that, yes I think that PYTHONUSERBASE will do fine! It might be useful though to be able to skip other system site dirs altogether so that only local site packages are used, as in the second patch I sent (see PYTHONNOSYSSITES). Thanks a lot, Ago From pavlovevidence at gmail.com Mon Sep 22 17:48:11 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 22 Sep 2008 14:48:11 -0700 (PDT) Subject: A bit weird dictionary behavior References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> Message-ID: <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> On Sep 22, 3:43?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > bearophileH... at lycos.com a ?crit : > > > Pekka Laukkanen: > >> but it still doesn't feel exactly right. Would it be worth submitting a bug? > > > It feels wrong because it is. In a tidier language (Pascal, Java, etc) > > a boolean and an integer must be different types. > > Some would argue (and some did by the time Python grew a 'bool' type) > that what is wrong is to have a bool type in a language that already > have a wider definition of the truth value of an expression... And some would argue that it was wrong to have such a wide definition for the truth value of an expression in the first place... Carl Banks From aioe.org at technicalbloke.com Wed Sep 24 16:09:55 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 24 Sep 2008 16:09:55 -0400 Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <gbe6qk$b54$1@aioe.org> bearophileHUGS at lycos.com wrote: > sturlamolden: >> No, because Python already has list comprehensions and we don't need the XML buzzword.< > > LINQ is more than buzzwords. Python misses several of those features. > So maybe for once the Python crowd may recognize such C# feature as > much better than things present in Python. > Said that, I presume Python will go on as usual, and LINQ-like > capabilities will not be integrated in Python. In the meantime where I > live lot of people will keep using C# instead of Python and CLisp, > natural selection at work indeed. > > Bye, > bearophile LOL, I just read that and thought - Ok this sounds serious I'd better go find out what this LINQ business is all about so I googled.. and ended up on MSDN where there's impressive sounding talk about how we need a way to query databases and XML files with a unified syntax like we do for for standard datatypes like files and arrays. Well yes,that makes sense I think and proceed to look at their example code, curious as to what this new paradigm looks like: using System; using System.Linq; using System.Collections.Generic; class app { static void Main() { string[] names = { "Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David" }; IEnumerable<string> query = from s in names where s.Length == 5 orderby s select s.ToUpper(); foreach (string item in query) Console.WriteLine(item); } } ROTFLMAO! Wow, what progress they're making! Quick guys let's jump on before we get left behind - we dont want to miss out on this exciting and mysterious 'foreach' construct or this strange and exotic sounding 'IEnumerable query' thing. To think that python might someday reach such lofty heights where we'll be able to simply write... names = ["Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David"] result = [each.upper() for each in names if len(each) == 5] result.sort() for each in result: print each Yes clearly 'the Python crowd' must admit LINQ is 'much better', I'm sold, in fact off to download my "Free, but limited editions of Visual Studio 2005 for a single programming language supported by .NET" right away! OK so maybe I'm being naive here but it looks to me like this new paradigm's big idea is to use a python + SQL type syntax to access data in random objects. Big whoop. It's not that difficult to write a generators that wraps XML files and databases is it? What am I missing here? Roger Heathcote. From rafesacks at gmail.com Wed Sep 10 23:44:01 2008 From: rafesacks at gmail.com (Rafe) Date: Wed, 10 Sep 2008 20:44:01 -0700 (PDT) Subject: Clearing a session and reload() problem (with repro error) References: <8a1b2997-5e7d-4099-98a3-96afce2fcc32@v39g2000pro.googlegroups.com> <mailman.740.1220976221.3487.python-list@python.org> <067abd3f-0d02-46e8-8d26-d85f20fa2e3a@s9g2000prg.googlegroups.com> <mailman.765.1221031725.3487.python-list@python.org> Message-ID: <350aabd1-d08e-4010-85f7-aff34361d6ba@w39g2000prb.googlegroups.com> On Sep 10, 2:28?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Wed, 10 Sep 2008 00:56:43 -0300,Rafe<rafesa... at gmail.com> escribi?: > > > > > On Sep 9, 11:03 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > > wrote: > >> En Mon, 08 Sep 2008 05:37:24 -0300,Rafe<rafesa... at gmail.com> escribi?: > >> ... > >> This dependency between modules, applied to all modules in your project, > >> defines a "dependency graph". In some cases, one can define a partial > >> ordering of its nodes, such that no module depends on any other module > >> *after* it (it may depend only on modules *before* it). Look for > >> "topological sort". > > >> Doing that in the generic case is not easy. If you *know* your > >> dependencies, reload the modules in the right order by hand. > >> ... > > I was hoping there would be a way to just wipe out the module cache > > and let it get rebuilt by executing my code (since I'm not using > > reload as part of my program, but rather, to test it in an environment > > where I cannot restart the Python session). > > Ok, I think the following sequence *might* work: > > - replace the __import__ and reload builtins with a custom callable ? > object. This way you can hook into any import attempt. The object should ? > keep a list of already reloaded modules. When a module is imported: if it ? > is already in the list, just delegate to the original __import__; if it is ? > not in the list, locate the module in sys.modules and reload it. > > - iterate over sys.modules and reload the desired modules, as you did in ? > your previous attempt. > > - restore the original __import__ function. > > This way, you effectively transform any import statement into a recursive ? > reload (for the first time); subsequent imports of the same module behave ? > as usual. This may work for you, or perhaps not, or it may screw all your ? > running environment up, or even cause the next global thermonuclear war... ? > (I hope not!) > > Note: some modules don't work well with reload(). A common case: global ? > mutable values, like a list of objects which starts empty: > ? ? ? ? my_list = [] > To make it more "reload friendly", use this: > ? ? ? ? try: my_list > ? ? ? ? except NameError: my_list = [] > (this way the list will keep its previous values). > > The example below shows how to hook into the import mechanism - it just ? > prints the module being imported. Implementing the functionality outlined ? > above is left as an exercise to the reader :) > > py> class ImportHook(object): > ... ? ? _orig_import = None > ... # > ... ? ? def __call__(self, name, globals={}, locals={}, fromlist=[], ? > level=-1): > ... ? ? ? ? if fromlist: > ... ? ? ? ? ? ? print "-> from %s import %s" % (name, ','.join(fromlist)) > ... ? ? ? ? else: > ... ? ? ? ? ? ? print "-> import %s" % name > ... ? ? ? ? return self._orig_import(name, globals, locals, fromlist, ? > level) > ... # > ... ? ? def hook(self): > ... ? ? ? ? import __builtin__ > ... ? ? ? ? self._orig_import = __builtin__.__import__ > ... ? ? ? ? __builtin__.__import__ = self > ... # > ... ? ? def unhook(self): > ... ? ? ? ? assert self._orig_import is not None, "unhook called with no ? > previous hook" > ... ? ? ? ? import __builtin__ > ... ? ? ? ? __builtin__.__import__ = self._orig_import > ... ? ? ? ? del self._orig_import > ... # > ... ? ? # support the "with" statement > ... ? ? def __enter__(self): > ... ? ? ? ? self.hook() > ... ? ? ? ? return self > ... # > ... ? ? def __exit__(self, type, value, tb): > ... ? ? ? ? self.unhook() > ... > py> > py> ih = ImportHook() > py> ih.hook() > py> import htmllib > -> import htmllib > -> import sgmllib > -> import markupbase > -> import re > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import re > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> import sre_parse > -> from formatter import AS_IS > -> import sys > -> from htmlentitydefs import entitydefs > py> reload(htmllib) > -> import sgmllib > -> from formatter import AS_IS > -> from htmlentitydefs import entitydefs > <module 'htmllib' from 'C:\apps\Python25\lib\htmllib.pyc'> > py> ih.unhook() > -> import __builtin__ > py> import htmllib > py> > > > I have been keeping a diagram of my module inheritance to make sure it > > is as clean as possible, so I could just right a list of reloads as > > you suggest. However, one of the sub-packages is designed to allow > > users to add more modules. Because these get dynamically imported, a > > guess I could add an argument to the reload function to allow a user > > to give the 'add-on' module they are working on... so much work just > > to get a clean environment... > > > Separate of my program, I was really hoping to write a generic reload > > tool for anyone developing in the same application as I am. I just > > don't see a way to trace import dependencies in systems which include > > dynamic imports. Any ideas? > > You may adapt the example above. > Good luck! > > -- > Gabriel Genellina Thanks again Gabriel! I'll see if I can take another swing at this when I catch up to my milestones ;). I'll post anything useful. - Rafe From nick at craig-wood.com Wed Sep 24 07:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 24 Sep 2008 06:30:03 -0500 Subject: PyRun_SimpleFile() crashes References: <d71e6607-31ca-48a6-b61f-040536a7cebf@g17g2000prg.googlegroups.com> Message-ID: <slrngdk68l.fu2.nick@irishsea.home.craig-wood.com> lixinyi.23 at gmail.com <lixinyi.23 at gmail.com> wrote: > my code: > main.cpp > #include <Python.h> > > int main(int argc, char **argv) > { > Py_Initialize(); > > FILE *file_1 = fopen("a2l_reader.py","r+"); > PyRun_SimpleFile(file_1,"a2l_reader.py"); > > Py_Finalize(); > } > > compile under windows using MinGW: > g++ main.cpp libpython25.a -o a > > no error was found. But when I run a.exe the program just crashes. > > What should I do? Run it under gdb (which should have come with MinGW). Check that you actually opened the file, ie file_1 != 0. This might be relevant http://effbot.org/pyfaq/pyrun-simplefile-crashes-on-windows-but-not-on-unix-why.htm -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From rschroev_nospam_ml at fastmail.fm Mon Sep 1 03:45:10 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 01 Sep 2008 09:45:10 +0200 Subject: (in memory) database In-Reply-To: <I8Fuk.118921$oT7.63551@newsfe10.ams2> References: <mailman.299.1220210443.3487.python-list@python.org> <o9cro5-sul.ln1@lairds.us> <I8Fuk.118921$oT7.63551@newsfe10.ams2> Message-ID: <b4Nuk.78766$OR5.7547@newsfe20.ams2> Roel Schroeven schreef: > Cameron Laird schreef: > >> I now suspect that my 2.5 packaging has something to do with 64-bit builds; >> all my 32-bit Ubuntu servers have Python 2.5.2, while the 64-bit ones are at >> Python 2.5. > > Strange: my 64-bit Ubuntu 8.04 has Python 2.5.2, with working sqlite: (mine is a desktop, not a server; I don't know if that should make any difference). -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From fredrik at pythonware.com Wed Sep 10 12:34:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 Sep 2008 18:34:42 +0200 Subject: md5 differences In-Reply-To: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> References: <4C3A3A20-22BD-497C-97E6-37D917A867BD@rgbaz.eu> Message-ID: <ga8sv3$kl7$1@ger.gmane.org> Python wrote: > I'm trying to match the results of an md5 checksum done in a tcsh shell. > I keep getting different results and can't find anything on google... > > here's an example: > > Arno at Computer:~% echo "hello" | md5 > b1946ac92492d2347c6235b4d2611184 > > Arno at Computer:~% python > Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> import md5 > >>> md5.new("hello").hexdigest() > '5d41402abc4b2a76b9719d911017c592' >>> import md5 >>> md5.new("hello\n").hexdigest() 'b1946ac92492d2347c6235b4d2611184' </F> From bearophileHUGS at lycos.com Thu Sep 25 06:23:35 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 25 Sep 2008 03:23:35 -0700 (PDT) Subject: python sorting 2dim. array ? References: <9684e81b-df99-4d95-99f9-8345c125b69b@d77g2000hsb.googlegroups.com> Message-ID: <e30cc15e-f3ea-410f-8c0e-2ebfc48773e6@f63g2000hsf.googlegroups.com> fred... at fulladsl.be: > list[rowindex][colomindex] > I want to sort on the second colom as first (and as > second sortfield the first colom). A good way, in Python 2.5: >>> from operator import itemgetter >>> a = [[1, 2], [3, 1], [2, 5], [7, 1]] >>> a.sort(key=itemgetter(1, 0)) >>> a [[3, 1], [7, 1], [1, 2], [2, 5]] Bye, bearophile From jamesd at echeque.com Wed Sep 10 22:10:44 2008 From: jamesd at echeque.com (James A. Donald) Date: Thu, 11 Sep 2008 12:10:44 +1000 Subject: wxpython ms-dos black window popping up in background References: <01c7dbd2-d74f-492e-a041-cd2c3f660a31@w39g2000prb.googlegroups.com> <mailman.753.1220993363.3487.python-list@python.org> <f7384268-84fa-4626-bf35-61201dd21f23@v13g2000pro.googlegroups.com> <6u8fc4tc19kbs8vpvm8u86bj4jnr0ea266@4ax.com> <c36f0a82-3e6a-4930-8e5c-6e1b87369c8e@y21g2000hsf.googlegroups.com> <4pcgc495c6ml60a09fh3gc8e6t1akmlmin@4ax.com> <d4ad46ba-0862-404a-81a7-279a5a3d68e3@d77g2000hsb.googlegroups.com> Message-ID: <3rtgc4palueahldle35j1ma21bih1kcse5@4ax.com> James A. Donald > > > > Horrible installs are a chronic problem of GUI programs driven by > > > > interpreted languages ?Installing visual basic programs that worked on > > > > one Windows machine to work on a very slightly different windows > > > > machine was also a nightmare. > > > > > > > > I have not attempted to create installable wxPython windows, but > > > > generally, "run anywhere" will bite you. ?Still looking for a good > > > > solution to "run anywhere". Mike Driscoll > I used Inno Setup which creates an uninstaller, however I am not > seeing it in my Windows Add/Remove. Odd. However, you can uninstall it > from the Start menu entry and it works. Could anyone tell me their experiences with NSIS? Has anyone tried scripting msi (Windows Installer 3.0 Redistributable) with Orca and the Windows SDK Components for Windows Installer Developers. How did it go. I notice that Python 2.4 is distributed as an msi file. I suspect there is a reason for that. Was that constructed with Orca? -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From bearophileHUGS at lycos.com Fri Sep 5 11:18:52 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 08:18:52 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> Message-ID: <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> Helmut Jarausch: > I need to hash arrays of integers (from the hash module). One of the possible solutions is to hash the equivalent tuple, but it requires some memory (your sequence must not be tuples already): assert not isinstance(somelist, tuple) hash(tuple(somelist)) This is an alternative solution, it doesn't use much memory, but I am not sure it works correctly: from operator import xor hash(reduce(xor, somelist)) Bye, bearophile From dblubaugh at belcan.com Mon Sep 8 19:19:59 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 8 Sep 2008 19:19:59 -0400 Subject: F2PY ?? Has anyone worked with the F2PY generator? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F3802840447@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F3802840447@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F3804F0F018@AWMAIL04.belcan.com> Pauli, Yes, I am utilizing the windows environment. I cannot install f2py. I obtain the following error when I try to execute the setup.py file within the f2py folder located within the numpy master folder: Warning: Assuming default configuration (lib\parser/{setup_parser,setup}.py was not found) Appending f2py.lib.parser configuration to f2py.lib Ignoring attempt to set 'name' (from 'f2py.lib' to 'f2py.lib.parser') Warning: Assuming default configuration (lib\extgen/{setup_extgen,setup}.py was not found) Appending f2py.lib.extgen configuration to f2py.lib Ignoring attempt to set 'name' (from 'f2py.lib' to 'f2py.lib.extgen') Appending f2py.lib configuration to f2py Ignoring attempt to set 'name' (from 'f2py' to 'f2py.lib') F2PY Version 2_4423 Traceback (most recent call last): File "C:\Python25\Lib\site-packages\numpy\f2py\setup.py", line 130, in <module> **config) TypeError: setup() got multiple values for keyword argument 'version' >>> I do not know as to how to fix the multiple values for version?? PLEASE HELP!!! David Blubaugh -----Original Message----- From: Blubaugh, David A. Sent: Monday, September 08, 2008 6:04 PM To: 'python-list at python.org' Subject: F2PY ?? Has anyone worked with the F2PY generator? To All, Has anyone worked with the F2PY generator? This is something that is supposedly built within numpy and scipy for the Python environment. I was wondering if anyone has encountered any issues with this environment?? This is important to find the answers to these questions. Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From deets at nospam.web.de Wed Sep 10 11:55:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 17:55:45 +0200 Subject: Alternatives to traditional RDBMS References: <mailman.791.1221056566.3487.python-list@python.org> Message-ID: <6iq90jFdeiU1@mid.uni-berlin.de> James Mills wrote: > Hi all, > > Are there any known alternatives > to the traditional RDBMS (MySQL, > PostgreSQL, SQLite, Oracle, etc0 / > > I know of 3 written in Python: > * buzhug > * kirbybase > * PyDbLite ZODB. Without any problems usable without ZOPE, clusterable, ACID-conform and so forth. Diez From tony.clarke5 at googlemail.com Tue Sep 16 01:58:10 2008 From: tony.clarke5 at googlemail.com (tony.clarke5 at googlemail.com) Date: Mon, 15 Sep 2008 22:58:10 -0700 (PDT) Subject: append on lists References: <gamgom$tmm$1@ger.gmane.org> <mailman.1085.1221541489.3487.python-list@python.org> Message-ID: <4097db86-b9dc-4ed5-ac84-6747a9f2bb11@t54g2000hsg.googlegroups.com> On Sep 16, 6:03?am, Peter Anderson <peter.ander... at internode.on.net> wrote: > "/... I don't think you've thought this one through, really./" > snip > > We ought to try and be a little kinder to others on the list, don't you > think? :-) > > snip Well said! Tony From wuwei23 at gmail.com Tue Sep 2 02:08:10 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 1 Sep 2008 23:08:10 -0700 (PDT) Subject: Put the output from all my programs in one place References: <3110346f-ed2b-458d-bbf8-af7e594f6509@e53g2000hsa.googlegroups.com> Message-ID: <d93208db-2411-4180-8ed8-d1e8234812b3@k36g2000pri.googlegroups.com> On Sep 2, 6:30?am, Jesse Aldridge <JesseAldri... at gmail.com> wrote: > I want to put all the output from all of my python programs in one > place. Have you considered using the python logging module? http://docs.python.org/lib/module-logging.html http://www.onlamp.com/pub/a/python/2005/06/02/logging.html You can define handlers within a program or via a config file. Then you just need to specify that they all log to the same location, which you could define via an environment variable... From lixinyi.23 at gmail.com Tue Sep 23 20:27:45 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Tue, 23 Sep 2008 17:27:45 -0700 (PDT) Subject: How can I use a PyObject in C++? Message-ID: <eaccc109-2cd6-4330-a6a6-ee559487741c@g17g2000prg.googlegroups.com> for example: #include <Python.h> void exec_python_code(int arg, char** argv) { Py_Initialize(); Py_Main(argc,argv); Py_Finalize(); } What I would like to know is: after Py_Main(argc,argv); How do I get every variable in python space, say a=[1,2,3,'Hello World',[2,3]] b=['xx','xxx','ffff',0.1234] , and use them in C++? any sample code? Thanks in advance! From steve at holdenweb.com Mon Sep 29 09:49:06 2008 From: steve at holdenweb.com (Steve Holden) Date: Mon, 29 Sep 2008 09:49:06 -0400 Subject: Cannot install pysqlite on Cygwin In-Reply-To: <b3fe277b-d191-43ad-8de8-83d99dd890f1@w1g2000prk.googlegroups.com> References: <b3fe277b-d191-43ad-8de8-83d99dd890f1@w1g2000prk.googlegroups.com> Message-ID: <gbqmcj$cuq$1@ger.gmane.org> Tilman Kispersky wrote: > I am trying to install sqlite for use with python on cygwin. I have > installed the sqlite packages from cygwin (that is libsqlite3-devel > and libsqlite3_0). When attempting to easy_install pysqlite I get: > > $ easy_install pysqlite > Searching for pysqlite > Reading http://pypi.python.org/simple/pysqlite/ > Reading http://pysqlite.org/ > Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.3/ > Reading http://pysqlite.sourceforge.net/ > Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.4/ > Reading http://initd.org/tracker/pysqlite/wiki/PysqliteDownloads > Reading http://oss.itsystementwicklung.de/trac/pysqlite > Reading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/ > Reading http://initd.org/pub/software/pysqlite/releases/2.3/2.3.5/ > Reading http://oss.itsystementwicklung.de/download/pysqlite/2.4/2.4.1/ > Reading http://initd.org/pub/software/pysqlite/releases/2.4/2.4.0/ > Best match: pysqlite 2.5.0 > Downloading http://oss.itsystementwicklung.de/download/pysqlite/2.5/2.5.0/pysqlite-2.5.0.tar.gz > Processing pysqlite-2.5.0.tar.gz > Running pysqlite-2.5.0/setup.py -q bdist_egg --dist-dir /cygdrive/c/ > Users/Tilman/AppData/Local/Temp/easy_install-876nHz/pysqlite-2.5.0/egg- > dist-tmp-7mr3WS > warning: no files found matching 'doc/*.html' > warning: no files found matching 'doc/code/*.py' > src/statement.c: In function `pysqlite_statement_recompile': > src/statement.c:351: warning: `sqlite3_transfer_bindings' is > deprecated (declared at /usr/include/sqlite3.h:3985) > build/temp.cygwin-1.5.25-i686-2.5/src/connection.o: In function > `pysqlite_enable_load_extension': > /cygdrive/c/Users/Tilman/AppData/Local/Temp/easy_install-876nHz/ > pysqlite-2.5.0/src/connection.c:922: undefined reference to > `_sqlite3_enable_load_extension' > collect2: ld returned 1 exit status > error: Setup script exited with error: command 'gcc' failed with exit > status 1 > $ > > > It seems to me this is due to some missing library (undefined > reference...) but I have no idea what these missing files might be. > I've tried installing everything that made any reference to sqlite > form the cygwin interface. Does anyone know how I might get a working > install of sqlite for python on cygwin? I believe it's a glitch in the 2.5.1 distribution current on Cygwin - I had to install the _sqlite DLL separately to get it to work, but no recompilation was necessary AFAICR. Chui Tey detailed the necessary steps in his blog post "Cygwin Python and sqlite3", but sadly it got lost and he hasn't replenished it, so you will have to stab around to see if there's a cached copy anywhere. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ From grante at visi.com Thu Sep 11 10:57:58 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 11 Sep 2008 09:57:58 -0500 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> <87k5djb6e2.fsf@benfinney.id.au> <pan.2008.09.11.09.10.00@REMOVE.THIS.cybersource.com.au> Message-ID: <6sCdnZcLo6xrrFTVnZ2dnUVZ_vWdnZ2d@posted.visi> On 2008-09-11, Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote: > On Thu, 11 Sep 2008 15:25:57 +1000, Ben Finney wrote: > >>> > The bounce messages are sent to you because you sent the original. >>> >>> Wrong. I didn't send _any_ e-mail. Why should I get bounce messages? >> >> You asked for email to be sent, No, I didn't. >> by sending a Usenet post to comp.lang.python. That's what a >> news-to-mail gateway does. ROTFL. That's like saying: you asked to be mugged by walking down a street where there was a mugger. That's what a mugger does. > I wasn't aware that comp.lang.python was a news-to-mail > gateway. How can one tell the difference between news groups > that use a news-to-mail gateway, and news groups that don't? One can't tell. > Posting to a public newsgroup is obviously giving consent to > forward that news posting to news clients. Given the ability > to opt-out with the X-No- Archive header, there may even be an > implied consent to allow archiving. But I don't believe there > is any such implied consent to format-shift news messages to > email. I certainly don't care if the articles I post are sent to anybody via any transport. I just don't like it being made to appear that I'm the one who sent them. I supposed I could break down and stop using my real e-mail address in the From: field. Or I could add some procmail rules to try to filter out the results of being joe-jobbed by the gateway. > In practice, I couldn't care less what format my news postings > are converted to, so long as it is invisible and transparent > to me. That's the issue: it's not invisible to you if you're getting bounce messages, out-of-office-replies, and other e-mail traffic generated by the fact the somebody is grabbing articles off Usenet and mailing them out as if it were you that sent them. > If somebody wants to build a > news-to-carved-in-giant-stone-tablets gateway, I don't care, > so long as I don't get giant stone tablets aren't dumped in > my front yard. > > Nor do I believe that by posting a news message I've > automatically consented to receive email messages. To imply > that the one implies the other is equivalent to arguing that > because I've written a letter to the editor of a newspaper, I > therefore must accept private correspondence from any person > or corporation that has a subscription to that newspaper. > > (In practice, I don't mind human-generated email messages, but > not automatic messages. If you can turn my munged email > address into a real email address, I probably won't mind you > emailing me. Don't abuse the privilege.) I don't mind receiving private e-mails from people who recieved the posting (either via Usenet or the gatewayed mailing list). If I did, I wouldn't use my real e-mail address. But, I don't want to receive machined generated trash or to be cc'd by people following up to the article. > "The bounce/ooo-reply is sent to the message author, not to > any intermediate host(s). After all, on that end, it's normal > email failure response -- notify the author of the message. It > doesn't matter that the original message was posted on a > Usenet newsgroup if that group is automatically relayed to > members of a mailing list." > > But that's wrong: it *shouldn't* be an normal email failure > response, because the message author is in no position to do > anything about it except to cease posting. That's a problem > with all mailing lists (that I know of). I know of other mailing lists aren't configured that way: the original author doesn't get bounce messages -- the sender of the bounced e-mail gets the bounce message. -- Grant Edwards grante Yow! Clear the laundromat!! at This whirl-o-matic just had visi.com a nuclear meltdown!! From has.temp3 at virgin.net Thu Sep 25 07:39:54 2008 From: has.temp3 at virgin.net (has) Date: Thu, 25 Sep 2008 04:39:54 -0700 (PDT) Subject: Folder Actions on Mac OSX Leopard? References: <18ce0f7c-6dc3-4fd7-985a-7f0682915626@l42g2000hsc.googlegroups.com> <6ea2a222-90be-4079-b78f-ead1e8f6d241@q26g2000prq.googlegroups.com> Message-ID: <0c5bd076-8806-4f46-9380-b221588bffb0@79g2000hsk.googlegroups.com> On 25 Sep, 00:30, Sean DiZazzo <half.ital... at gmail.com> wrote: > I always wondered about Folder Actions... ?I just tested. ?You can > have applescript call python scripts via `do shell script`. ?But it > seemed a bit flakey. Should work in theory. For which values of flakey? e.g. Is it a technical problem with Folder Actions, AppleScript, 'do shell script, and/or Python, or just your AppleScript code that needs some work (e.g. there are some common gotchas with using 'do shell script' that often trip up AppleScript newcomers). FWIW, I would second the suggestion to look into FSEvents as a possible alternative to Folder Actions. There's also kqueue which is lower level but may have/have had Python bindings already written for it. Alternatively, if the OP really wants to use FAs, there are a couple of other options for that: 1. I've got a simple py2app-based application shell and an AppleScript that automatically forwards FA events to that application - just insert your Python code into the application shell and build it, attach the AppleScript to some folders, and you're good to go. Email me directly if you want a copy. 2. If you're brave, you could try using the PyOSA component on the appscript website, which allows you to write OSA scripts in Python. FAs will work with any kind of OSA script (.scpt files), not just AppleScript ones. PyOSA is officially discontinued due to some intractable limitations in its/CPython's design (specifically the inability of an in-process Python interpreter to sandbox unrelated scripts so that they can't interfere with each others' modules, file handles, etc). However, it's reasonably functional and should be usable for FAs with a little care. HTH has -- Control AppleScriptable applications from Python, Ruby and ObjC: http://appscript.sourceforge.net From fredrik at pythonware.com Sun Sep 7 18:01:01 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 00:01:01 +0200 Subject: formatting a string with thousands separators In-Reply-To: <e1a84d570809071449s3978b9c3w8d16c95091c966be@mail.gmail.com> References: <89e4b5fd-5b2e-4062-b442-d2be445f482e@k30g2000hse.googlegroups.com> <RTVwk.660$Dj1.566@trnddc02> <e1a84d570809071449s3978b9c3w8d16c95091c966be@mail.gmail.com> Message-ID: <ga1iuu$65e$1@ger.gmane.org> James Mills wrote: > There is a much easier more consistent way: > >>>> import locale >>>> locale.setlocale(locale.LC_ALL, "en_AU.UTF-8") > 'en_AU.UTF-8' doesn't work on all Python platforms, though: >>> locale.setlocale(locale.LC_ALL, "en_AU.UTF-8") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\python25\lib\locale.py", line 478, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting and is likely to give you somewhat unpredictable output if you use the machine's actual locale: >>> import os >>> locale.setlocale(locale.LC_ALL, os.environ["LANG"]) 'sv_SE.UTF-8' >>> locale.format("%0.2f", 5000000, True) '5000000,00' </F> From invalid at invalid Wed Sep 24 11:54:40 2008 From: invalid at invalid (Grant Edwards) Date: Wed, 24 Sep 2008 10:54:40 -0500 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <pan.2008.09.24.06.17.06@REMOVE.THIS.cybersource.com.au> <JcKdndouSNGG10fVnZ2dnUVZ_hCdnZ2d@posted.visi> <gbdmgh$nd0$1@rumours.uwaterloo.ca> Message-ID: <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> On 2008-09-24, Ross Ridge <rridge at csclub.uwaterloo.ca> wrote: > Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote: >> Presumably somebody has suggested that calling sys.exit() was a good >> option. I'm curious to what possible reason they could give for such a >> poor choice. > > Grant Edwards <invalid at invalid> wrote: >>Same here. It's like an automotive engine controls designer >>asking if a failed O2 sensor should turn on the check engine >>light or blow up the car. > > No, it's more like asking if the failed sensor should turn on > a strange and mysterious light on the dashboard You're right. I had forgotten that sys.exit() is actually raising the system exit exception, and that the application calling the library could handle that exception. > and then blow up the car if the driver doesn't immediately > stop and check the engine. The owners manual would only > vaguely hint at the fact that this could happen. -- Grant Edwards grante Yow! Why is it that when at you DIE, you can't take visi.com your HOME ENTERTAINMENT CENTER with you?? From ireborin at delete.this.gmail.com Mon Sep 29 21:56:03 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 30 Sep 2008 03:56:03 +0200 Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <affd6918-3444-4a8f-9816-faa56ee34512@k37g2000hsf.googlegroups.com> <q1r2e458kqe2t7phvj5iorgj0tbnbi7ikb@4ax.com> <6d265f36-352c-4866-bf91-c14d26101fc2@k37g2000hsf.googlegroups.com> Message-ID: <ku03e4pddv9fbshgkbpbfv2hrg3u1p1i6h@4ax.com> On Mon, 29 Sep 2008 17:59:40 -0700 (PDT), bearophileHUGS at lycos.com wrote: Hello bearophile, thank you for replying. >The Python genie grants you that wish. You were almost right: >>>> print (3 * '%12.3f') % (a, b, c) > 2.000 123456.789 1234.000 >>>> print 3 * '%12.3f' % (a, b, c) > 2.000 123456.789 1234.000 Works beautifully :-) Thank you! >>>> print 3 * '%12.3f' % a, b, c >Traceback (most recent call last): > File "<stdin>", line 1, in <module> >TypeError: not enough arguments for format string Just one more question - it's actually an extension to this one (forgive my curiosity, but I really need this info, and searching google always gives me the same stuff again and again) ... a = 2.000001 b = 123456.789 c = 1234.0001 d = 98765.4321 # same as above except for d print (3 * '%12.3f') % (a, b, c) #this works beautifully How to add d at the end but with a different format now, since I've "used" the "format part" ? Again, my weird wishful-thinking code: print (3*'%12.3f', '%5.3f') %(a,b,c),d >(Note the spaces and parentheses. Python programmers thank you if put >them improving readability a little). Yes, ok. I can agree with that - separating the format from the variable list part sounds reasonable. > >Bye, >bearophile -- Ivan From bruno.42.desthuilliers at websiteburo.invalid Tue Sep 23 03:01:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 23 Sep 2008 09:01:57 +0200 Subject: Docstrings for class attributes In-Reply-To: <mailman.1392.1222147427.3487.python-list@python.org> References: <mailman.1392.1222147427.3487.python-list@python.org> Message-ID: <48d8945f$0$27140$426a74cc@news.free.fr> Tom Harris a ?crit : > Greetings, > > I want to have a class as a container for a bunch of symbolic names > for integers, eg: > > class Constants: > FOO = 1 > BAR = 2 Do you have a reason to stuff them in a class ? Usually, putting them at the top level of a module is quite enough... > Except that I would like to attach a docstring text to the constants, > so that help(Constants.FOO) will print some arbitrary string. You can document them in the module or class docstring... From h.goebel at goebel-consult.de Tue Sep 16 13:29:31 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Tue, 16 Sep 2008 19:29:31 +0200 Subject: Python and Open Office In-Reply-To: <mailman.826.1221077307.3487.python-list@python.org> References: <a9f39a410809101304j592cb7actc1f95882f8fe632c@mail.gmail.com> <mailman.826.1221077307.3487.python-list@python.org> Message-ID: <48cfecfc$0$6660$9b4e6d93@newsspool2.arcor-online.net> Marco Bizzarri schrieb: > On Wed, Sep 10, 2008 at 10:04 PM, Greg Lindstrom <gslindstrom at gmail.com> wrote: >> Hello, >> >> I would like to create and manipulate Open Office documents using Python. I [...] >> Is there someone here who can help me out, or is there an appropriate >> mailing list for me to join? > > Ciao, Greg. > > you should check with the openoffice.org mailing list; I think what > you are looking for is the api mailing list for openoffice; you could > try to get the OpenOffice.org developers guide and the SDK, and check > it (but it is not a little work) If want to create documents, there is no nead to fight with OOo and UNO. As I thought everybody already knows, ODF is simply a Zip-File containing some XML files. So there is no need to use OOo for handling the files. So odfpy seams to be the best way to to this. You may also want to check OOopy <http://pypi.python.org/pypi/OOoPy/>. If you are going to interact with OOo, you may want to try out <http://openoffice-python.origo.ethz.ch/> -- Sch?nen Gru? - Regards Hartmut Goebel Dipl.-Informatiker (univ.), CISSP Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From dudeja.rajat at gmail.com Tue Sep 2 15:21:29 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 2 Sep 2008 20:21:29 +0100 Subject: What is module initialization? In-Reply-To: <g9jsoo$uf0$1@ger.gmane.org> References: <mailman.367.1220362362.3487.python-list@python.org> <48bd4799$0$17215$426a74cc@news.free.fr> <e0b6c39a0809020732i5f3f3a41kbdccf0c4bf7549ec@mail.gmail.com> <g9jsoo$uf0$1@ger.gmane.org> Message-ID: <e0b6c39a0809021221l89afa47ubc6867576135b220@mail.gmail.com> On Tue, Sep 2, 2008 at 6:22 PM, Fredrik Lundh <fredrik at pythonware.com> wrote: > dudeja.rajat at gmail.com wrote: > >>> # myglobals.py: >>> answer = 42 >>> >>> # question.py >>> import myglobals >>> myglobals.answer = "WTF ?" >>> >> >> But if I do :- >> #question.py >> from myglobals import * >> myglobals.answer = "WTF ?" >> >> will this work? > > with the above definition of myglobals, no. "from myglobals import" doesn't > add the module object to the importing module's namespace. > > have you read: > > http://effbot.org/zone/import-confusion.htm > > ? > > </F> > > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for your help guys that I got my problem resolved. Regards, Rajat From clp at rebertia.com Fri Sep 26 00:42:59 2008 From: clp at rebertia.com (Chris Rebert) Date: Thu, 25 Sep 2008 21:42:59 -0700 Subject: Fastest way to max() list In-Reply-To: <ea42fb160809252057o283216c1v35067189835f227c@mail.gmail.com> References: <ea42fb160809252057o283216c1v35067189835f227c@mail.gmail.com> Message-ID: <47c890dc0809252142i69bae4fdk9b135d43f73d3e@mail.gmail.com> On Thu, Sep 25, 2008 at 8:57 PM, David Di Biase <dave.dibiase at gmail.com> wrote: > I have a list with about 1000-1500 sub-lists which look like so: > list[-0.28817955213290786, 3.6693631467403929, 'H', 31.31225233035784]] > > The first and second values are Angstrom units specifying the location of a > particle. What I'd like to do is determine the distance between the smallest > and largest value in the arrays first position 0. I tried reading the manual > for this but I don't see how it applies key or any of those other commands > to the function. I could easily write a sort to do this and capture the > first and last spots, but why do that when I can use max and min (if I can > actually do that...). A. You should probably be using objects rather than arrays to represent your datapoints, so that they're more structured and it's more apparent what the values mean. B. Assuming by "distance" you meant "difference" and/or that the distance is only in 1 dimension: from operator import itemgetter firsts = map(itemgetter(0), main_list) distance = max(firsts) - min(firsts) > > So you wonderful Python gods, lay some knowledge on me. please? lol... > > while I'm at it, is there a way to modify an entire list without having to > produce a whole new one? For example now say I want to modify list[0] and > multiply it by some value. From what I understand previous version of Python > allowed lists to be multiplied like matrices...now apparently it just > replicates the list. :-/ shucks... You just have to apply the transform to each list element individually (also, you might consider using NumPy [http://numpy.scipy.org/] if you're doing a lot of matrix manipulation): for lst in main_list: lst[0] *= some_value Regards, Chris > > The first question would be useful to know, but the second question I do > quite a bit of and the "best practice" would be really great to know! > > Thanks in advanced! > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From david.huard at gmail.com Tue Sep 16 16:25:13 2008 From: david.huard at gmail.com (David Huard) Date: Tue, 16 Sep 2008 20:25:13 +0000 (UTC) Subject: Programmatically exit the REPL References: <288810.50426.qm@web7904.mail.in.yahoo.com> <48B35768.80304@nienna.org> <48B46BF1.20408@nienna.org> Message-ID: <gap4n9$gb3$1@ger.gmane.org> > [snip] > > Does anyone know how to make raw_input think it has gotten input? > > -Matt Hi Matt, So you really need raw_input ? Couldn't you use a mock-up ? sys.stdout.write('> ') sys.stdout.flush() And get the user input with something like: while self.continue: input = os.read(sys.stdin.fileno(), 80).strip() if input== '': time.sleep(.2) The background thread can stop the listening thread by setting self.continue to False. The subversion trunk of pymc (on google code) has something that I think is similar to your problem, you might want to look at it (look at revision 868). HTH, David Huard From marco.bizzarri at gmail.com Thu Sep 4 06:57:10 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Thu, 4 Sep 2008 12:57:10 +0200 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? Message-ID: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> Let's say I've a class a, where I can write: -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From michel at nospam.please Tue Sep 16 14:12:54 2008 From: michel at nospam.please (Michel Leunen) Date: Tue, 16 Sep 2008 20:12:54 +0200 Subject: Python Nautilus script In-Reply-To: <99dc3fb0-f4ea-4b3e-926c-ce3462cd9973@b1g2000hsg.googlegroups.com> References: <48ceb5ac$0$2847$ba620e4c@news.skynet.be> <6j7rjpF1rp5lU1@mid.uni-berlin.de> <48cebba7$0$2862$ba620e4c@news.skynet.be> <99dc3fb0-f4ea-4b3e-926c-ce3462cd9973@b1g2000hsg.googlegroups.com> Message-ID: <48cff726$0$2861$ba620e4c@news.skynet.be> kaer a ?crit : > #! /usr/bin/python > # -*- coding: utf8 -*- > > import os, sys > > #NAUTILUS_SCRIPT_SELECTED_FILE_PATHS : chemins des fichiers > s?lectionn?s s?par?s par des retours ? la ligne (newline) (uniquement > pour les fichiers locaux) > #NAUTILUS_SCRIPT_SELECTED_URIS : URIs des fichiers s?lectionn?s > s?par?s par des retours ? la ligne (newline) > #NAUTILUS_SCRIPT_CURRENT_URI : URI de l'emplacement actuel > #NAUTILUS_SCRIPT_WINDOW_GEOMETRY : position et taille de la fen?tre > actuelle > > > KEYS=("NAUTILUS_SCRIPT_SELECTED_FILE_PATHS", > "NAUTILUS_SCRIPT_SELECTED_URIS", "NAUTILUS_SCRIPT_CURRENT_URI", > "NAUTILUS_SCRIPT_WINDOW_GEOMETRY") > > ft=open("/home/kaer/stupid.txt", "w") > for key_value in [(key, os.environ.get(key, 'NOT FOUND')) for key in > KEYS]: > ft.write("env(%s): %s\n" % key_value) > file_names=sys.argv[1:] > for index, file_name in enumerate(file_names): > ft.write("%s: [%s]\n" % (index, file_name)) > if os.path.isfile(file_name): os.rename(file_name, '%03d-%s' % > (index+1, file_name)) > ft.close() Yes, indeed, it works with your code. Thanks for it. I just have to find out why it doesn't work with mine. The problem is that Nautilus scripts are hard to debug. Thanks for your help, Michel -- Michel Leunen http://linux.leunen.com From python at p0w.org Fri Sep 12 08:08:05 2008 From: python at p0w.org (Strato) Date: Fri, 12 Sep 2008 14:08:05 +0200 Subject: testing if another instance of a script is already running Message-ID: <48CA5BA5.8020709@p0w.org> Hi folks, I want to write some kind of test to check at startup if another instance of my script is already running. I don't want to handle writing of a PID file because it is too Unix/Linux specific way to do this, and I need to keep the code to be cross-platform. I think the better way to achieve this is to use some process control, but I'm a neebie and I don't see how to do this in a safe and clean way. Any idea ? Best regards, Strato From gherron at islandtraining.com Sun Sep 14 15:15:04 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 14 Sep 2008 12:15:04 -0700 Subject: Abstract class In-Reply-To: <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> References: <mailman.1008.1221408214.3487.python-list@python.org> <roy-9FFFBD.13564414092008@news.panix.com> <8f67b6f80809141155v6e6fc3dau7fbc47a80034dd53@mail.gmail.com> Message-ID: <48CD62B8.7070708@islandtraining.com> Mr.SpOOn wrote: > Gary Harron: > >> I believe you are mixing up class *inheritance* and *abstract* classes. >> > > >> Class inheritance (with Python has has for years) is how one class inherits >behavior/properties/attributes from another class. The class being inherited from is >called the base class. This is probably what you want. >> > > Well, I know the difference between an abstract class and an inherited > one. The idea was to create a main class Note, with abstract methods, > and implement these methods in the other classes. > > On Sun, Sep 14, 2008 at 7:56 PM, Roy Smith <roy at panix.com> wrote: > >> What properties or behaviors does SharpNote have which NaturalNote doesn't? >> Unless there is some new behavior, you don't need subclasses. >> > > Well, from a SharpNote I can obtain the relative NaturalNote. So if I > have a C# I can call > > natural('C#') and get 'C' > > While in the class NaturalNote I don't need such a method, but I need > two methods to get the sharped and flatted version > > >> Are you also going to have DoubleSharpNote and DoubleFlatNote? >> > > Yes, that's an option. > > >> Consider the following code: >> >> note1 = SharpNote("E4") >> note2 = NaturalNote("F4") >> if note1 == note2: >> print "the same note" >> else >> print "different notes" >> >> what should it print? >> > > Well, that's not so simple. The idea is that I use a notation (A, B, > C, D...) and an integer (a distance expressed in semitones) to > identify a note. > > Anyway, I think I need an abstract class. Or not? > No! Definitely not! You need inheritance of a class from a base class. Implement your base class with whatever shared methods you want. Implement your derived class with methods (new, inherited or reimplemented) as you like. (If you wish to consider the base class "abstract", just agree with yourself to not instantiate it.) Please forget about Abstract Base Classes. They have nothing to do with what you want, and are a *HUGE* overkill for your application. They are not (yet) even part of standard Python, and are used primarily for a class implementor to guarantee to a user of a class that it provides a specific interface. Gary Herron > -- > http://mail.python.org/mailman/listinfo/python-list > From anita.vishwas at gmail.com Mon Sep 22 08:03:08 2008 From: anita.vishwas at gmail.com (Shopping) Date: Mon, 22 Sep 2008 05:03:08 -0700 (PDT) Subject: Lenovo N3000 0769CVQ Notebook Message-ID: <2bcbd1f3-bc5c-4244-8333-e67496247188@z11g2000prl.googlegroups.com> Buy low price Lenovo N3000 0769CVQ Notebook - buy best Lenovo N3000 0769CVQ Notebook online at lowest price, homeshop18.com offers best deals to buy Lenovo N3000 0769CVQ Notebook online with discount in India. To know more visit : http://www.homeshop18.com/shop/u/y/p-Computers-Q-and-Q-Peripherals-S-Laptops-S-Lenovo-Q-N3000-Q-0769CVQ-Q-Notebook/Home_Online-pI_20249-clI_2-cI_920-pCI_909- From circularfunc at gmail.com Fri Sep 26 22:39:49 2008 From: circularfunc at gmail.com (process) Date: Fri, 26 Sep 2008 19:39:49 -0700 (PDT) Subject: what does ` ` do in ' '.join([`x * x` for x in range(1, 6)])? Message-ID: <97ed7142-d89f-42f5-9d23-6437aef18ea4@79g2000hsk.googlegroups.com> ' '.join([`x * x` for x in range(1, 6)]) exactly what does this symbol do and what does it stand for? From christopher.paul.taylor at gmail.com Wed Sep 17 09:27:47 2008 From: christopher.paul.taylor at gmail.com (christopher taylor) Date: Wed, 17 Sep 2008 09:27:47 -0400 Subject: python regex character group matches Message-ID: <f44caf830809170627m19b5f4e3qb9fe2fb69ee20afa@mail.gmail.com> hello python-list! the other day, i was trying to match unicode character sequences that looked like this: \\uAD0X... my issue, is that the pattern i used was returning: [ '\\uAD0X', '\\u1BF3', ... ] when i expected: [ '\\uAD0X\\u1BF3', ] the code looks something like this: pat = re.compile("(\\\u[0-9A-F]{4})+", re.UNICODE|re.LOCALE) #print pat.findall(txt_line) results = pat.finditer(txt_line) i ran the pattern through a couple of my colleagues and they were all in agreement that my pattern should have matched correctly. is this a simple case of a messed up regex or am i not using the regex api correctly? cheers, ct From gogtesuyash at gmail.com Wed Sep 17 08:28:05 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 05:28:05 -0700 (PDT) Subject: Problem occured while sending mail References: <b7481bed-df0f-4ef7-8fe7-09da5869492f@c22g2000prc.googlegroups.com> Message-ID: <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> On Sep 17, 5:04 pm, sui <gogtesuy... at gmail.com> wrote: > this is my code > > import sys, os, glob, datetime, time > import smtplib > ## Parameters for SMTP session > port=587 > SMTPserver= 'smtp.gmail.com' > SMTPuser= '... at gmail.com' > pw= 'fill in here' > SENDER= SMTPuser > > ## Message details > FROM= SENDER > TO= 'notgm... at a.com' > CC=FROM > ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC > RECEIVERS= (TO,) ## ignore the CC address > > subject= 'Test 1a' > message='*** Email test *** ' > > print 'Starting SMTP mail session on %s as %s ' % > (SMTPserver,SMTPuser) > session = smtplib.SMTP(SMTPserver,port) > session.set_debuglevel(0) # set debug level to 1 to see details > session.ehlo(SMTPuser) # say hello > session.starttls() # TLS needed > session.ehlo(SMTPuser) # say hello again, not sure why > session.login(SMTPuser, pw) > > ##Create HEADER + MESSAGE > HEADER= 'From: %s\r\n' % FROM > HEADER= HEADER + 'To: %s\r\n' % TO > HEADER= HEADER + 'Cc: %s\r\n' % CC > HEADER= HEADER + 'Subject: %s\r\n' % subject > BODY= HEADER + '\r\n' + message > print BODY > > SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email > > session.close() > > Now when i run this .py file...as python mail.py > i can see only statement > starting smtp mail......n details > then nothing on screen after few minutes or after pressing ctrl +c > Traceback (most recent call last): > File "mail4.py", line 21, in <module> > session = smtplib.SMTP(SMTPserver,port) > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > (code, msg) = self.connect(host, port) > File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > self.sock.connect(sa) > File "<string>", line 1, in connect > or may be conncetion time out > > wats the solution for this if i dont press cntrl + c then it shows Starting SMTP mail session on smtp.gmail.com as gogtesuyash at gmail.com Traceback (most recent call last): File "mail4.py", line 21, in <module> session = smtplib.SMTP(SMTPserver,port) File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect raise socket.error, msg socket.error: (110, 'Connection timed out') plz help me its urgent.....i want to complete it as early as possible From barry at python.org Fri Sep 12 21:28:55 2008 From: barry at python.org (Barry Warsaw) Date: Fri, 12 Sep 2008 21:28:55 -0400 Subject: RELEASED Python 2.6rc1 Message-ID: <49568982-472B-46BB-9001-12078706B238@python.org> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On behalf of the Python development team and the Python community, I am happy to announce the first release candidate for Python 2.6. This is a release candidate, so while it is not suitable for production environments, we strongly encourage you to download the release and test it on your software. We expect only critical bugs to be fixed between now and the final 2.6 release, still scheduled for October 1st, 2008. There is one more release candidate planned for September 17th. You might notice that unlike earlier releases, we are /not/ releasing Python 3.0rc1 at this time. It was decided that 3.0 still needs time to resolve open issues and that we would not hold up the 2.6 release for this. We feel that Python 2.6 is nearly ready for its final release. If you find things broken or incorrect, please submit bug reports at http://bugs.python.org For more information and downloadable distributions, see the Python 2.6 website: http://www.python.org/download/releases/2.6/ (Note that the Windows installers will be uploaded shortly.) See PEP 361 for release schedule details: http://www.python.org/dev/peps/pep-0361/ Enjoy, - -Barry Barry Warsaw barry at python.org Python 2.6/3.0 Release Manager (on behalf of the entire python-dev team) -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (Darwin) iQCVAwUBSMsXV3EjvBPtnXfVAQJFsgP9GxZYQocbDTd0Z/0yEjpHfZ/FTd8y83jV 5JouO07lB8XtLawnWB9hF8sUrCuBVog5He3mLVUPDmlyn30qvjYWMG2J6zW0yYMX yZdjUyUmta0IMCsXe7YXj369xebh4nWuwG4tDygly4donA7GYPXAlxI48MmyDJxw 1v07LM4Dttw= =Nd3s -----END PGP SIGNATURE----- From maric at aristote.info Tue Sep 16 09:26:55 2008 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 Sep 2008 15:26:55 +0200 Subject: Gateway to python-list is generating bounce messages. In-Reply-To: <200809151645.13078.maric@aristote.info> References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <97udndzTorVUPlXVnZ2dnUVZ_ojinZ2d@earthlink.com> <200809151645.13078.maric@aristote.info> Message-ID: <200809161526.56000.maric@aristote.info> Le Monday 15 September 2008 16:45:12 Maric Michaud, vous avez ?crit?: > Le Thursday 11 September 2008 06:51:19 Dennis Lee Bieber, vous avez ?crit?: > > On Wed, 10 Sep 2008 21:36:36 -0500, Grant Edwards <grante at visi.com> > > > > declaimed the following in comp.lang.python: > > > Wrong. I didn't send _any_ e-mail. Why should I get bounce > > > messages? > > > > One: Comp.lang.python is dual-routed with a mailing list; anything > > you post to either CLP or the mailing list gets cross-posted to the > > other -- the FROM header retains that of the original author (which > > could be you). > > > > Two: Somebody else is subscribed to the mailing list, and sets up an > > "out-of-office" reply or has other problems (like an overfilled mailbox, > > causing a bounce, or a discontinued account) when the forwarded post > > reaches their address. > > > > Three: The bounce/ooo-reply is sent to the message author, not to > > any intermediate host(s). After all, on that end, it's normal email > > failure response -- notify the author of the message. It doesn't matter > > that the original message was posted on a Usenet newsgroup if that group > > is automatically relayed to members of a mailing list. > > Given RFCs, the problem should not be, for DSN, the MTA should rewrite the > FROM envelope address to the one of the list maintainer : > > RFC 3464 : > > 3. Conformance and Usage Requirements > > > > ... > > > > By contrast, successful submission of a message to a mailing list > > exploder is considered final delivery of the message. Upon delivery > > of a message to a recipient address corresponding to a mailing list > > exploder, the Reporting MTA SHOULD issue an appropriate DSN exactly > > as if the recipient address were that of an ordinary mailbox. > > > > NOTE: This is actually intended to make DSNs usable by mailing > > lists themselves. Any message sent to a mailing list subscriber > > should have its envelope return address pointing to the list > > maintainer [see RFC 1123, section 5.3.7(E)]. Since DSNs are sent > > to the envelope return address, all DSNs resulting from delivery > > to the recipients of a mailing list will be sent to the list > > maintainer. The list maintainer may elect to mechanically > > process DSNs upon receipt, and thus automatically delete invalid > > addresses from the list. (See section 7 of this memo.) > > and > > > Appendix C - Guidelines for use of DSNs by mailing list exploders > > > > - Guidelines for use of DSNs by mailing list exploders > > > > > > This section pertains only to the use of DSNs by "mailing lists" as > > defined in [4], section 7.2.7. > > > > DSNs are designed to be used by mailing list exploders to allow them > > to detect and automatically delete recipients for whom mail delivery > > fails repeatedly. > > > > When forwarding a message to list subscribers, the mailing list > > exploder should always set the envelope return address (e.g., SMTP > > MAIL FROM address) to point to a special address which is set up to > > receive non-delivery reports. A "smart" mailing list exploder can > > therefore intercept such non-delivery reports, and if they are in the > > DSN format, automatically examine them to determine for which > > recipients a message delivery failed or was delayed. > > This is not sufficient for auto-responses, and given the following rfcs, it > would smart to both : > > - add an "Auto-Submitted: Python User Group" header, > - add or modify the Return-Path and/or Reply-To header for badly > implemented auto-responders to point to list maintainer. > Oh, no ! to the list itself of course. This could also avoid the common mistake mailing list users do in replying private mail accidentally when the adress of the list is only present in CC field. > RFC 3834: > > 4. Where to send automatic responses (and where not to send them) > > > > > > In general, automatic responses SHOULD be sent to the Return-Path > > field if generated after delivery. If the response is generated > > prior to delivery, the response SHOULD be sent to the reverse-path > > from the SMTP MAIL FROM command, or (in a non-SMTP system) to the > > envelope return address which serves as the destination for non- > > delivery reports. > > and > > > 5. The Auto-Submitted header field > > > > > > The purpose of the Auto-Submitted header field is to indicate that > > the message was originated by an automatic process, or an automatic > > responder, rather than by a human; and to facilitate automatic > > filtering of messages from signal paths for which automatically > > generated messages and automatic responses are not desirable. > > RFC 1123 : > > 5.3.7 Mail Gatewaying > > > > Gatewaying mail between different mail environments, i.e., > > different mail formats and protocols, is complex and does not > > easily yield to standardization. See for example [SMTP:5a], > > [SMTP:5b]. However, some general requirements may be given for > > a gateway between the Internet and another mail environment. > > > > (A) Header fields MAY be rewritten when necessary as messages > > are gatewayed across mail environment boundaries. > > > > DISCUSSION: > > This may involve interpreting the local-part of the > > destination address, as suggested in Section 5.2.16 > > I'm also frustrated by some (rare) of my mails which are actually blocked > for > > confirmation by a moderator with this message : > > Is being held until the list moderator can review it for approval. > > > > The reason it is being held: > > > > Message has a suspicious header > > I think it's probably my domain name which makes this, do the anti-spam > engine use whitelists ? How to resolve the problem if not ? I re-send this correction to my previous post because the first got held as spam, :' (, is there really a moderator, as the bounce says, and he decided to censor me ? -- _____________ Maric Michaud From a at nospam.org Tue Sep 16 07:10:37 2008 From: a at nospam.org (Armin) Date: Tue, 16 Sep 2008 13:10:37 +0200 Subject: append on lists In-Reply-To: <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> Message-ID: <gao3d0$7q1$1@online.de> Duncan Booth wrote: > "Chris Rebert" <clp at rebertia.com> wrote: >> On Tue, Sep 16, 2008 at 1:20 AM, Armin <a at nospam.org> wrote: >>> [1,2,3,4,7].append(c) -> Is this a valid expression? >> Literally, no, because you can't call methods on literals. > > Rubbish. There is no restriction about calling methods on literals. That > expression is perfectly valid but has no practical use that I can see. The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c (with c = [8,9]) is identical, but the first expression doesn't provide a value. Strange by design ... --Armin > > There is a syntax gotcha which you may have been thinking of: to call a > method on an integer literal (or indeed to access any attribute) you have > to use whitespace between the literal and the dot otherwise you have a > float literal and a syntax error. > >>>> 5 .__hex__() > '0x5' > > The only relatively common use I can think of where you might want to call > a method directly on a literal is to produce a list of strings while being > lazy about the typing: > > COLOURS = "red green blue pink yellow".split() > > versus > > COLOURS = ["red", "green", "blue", "pink", "yellow"] > > From grante at visi.com Fri Sep 26 21:34:56 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 26 Sep 2008 20:34:56 -0500 Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d@posted.visi> <gbjmdp$q1e$2@lust.ihug.co.nz> Message-ID: <dZOdnT0NKORdEEDVnZ2dnUVZ_rvinZ2d@posted.usinternet> On 2008-09-26, Lawrence D'Oliveiro <ldo at geek-central.gen.new_zealand> wrote: > In message <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d at posted.visi>, Grant Edwards > wrote: > >> Never assume somebody reading the article and attempting to >> help you can see the subject line. > > Why not? Because it might not be. It depends on the user's newsreader and editor settings. Assuming the reader can't see the subject line while reading the article has been one of the basic rules of Usenet posting for decades. At least that's what I've always been told: make sure the body of a posting contains sufficient information to answer the question. -- Grant From lanny at freshells.ch Sat Sep 6 17:43:31 2008 From: lanny at freshells.ch (Lanny) Date: Sat, 6 Sep 2008 14:43:31 -0700 Subject: indices question References: <g9sgda$e9h$1@adenine.netfront.net> <cc9bc4bf-412e-44e9-ba6d-76352ec08fd4@26g2000hsk.googlegroups.com> Message-ID: <g9sqtn$1n8f$1@adenine.netfront.net> > Lanny: >> ... >> varcc = raw_input >> grid[varc] = 'O' >> ... >> Why can't I put a varible thats an integer instead? > > 'varcc' and 'varc' are different names. > > 'raw_input' isn't a function call, you may want to turn that into a > function call. > > varc isn't an integer, you may have to convert it to integer first, > using int(), because Python lists aren't like Lua ones, they are > represented with a sequence of cells, and an integer number is used to > denote what cells you want. Note that the cell must already exists > before accessing its contents. > > Maybe you want to use an associative array instead, named 'dict' in > Python, that allows you freedom in the type of the keys and allows you > to create cells on the fly. > > Surely my answer isn't enough to solve your problems, but it may give > you a starting point. > > Bye, > bearophile Thanks, this was very usefull -- Posted on news://freenews.netfront.net - Complaints to news at netfront.net -- From skip at pobox.com Sun Sep 14 09:21:37 2008 From: skip at pobox.com (skip at pobox.com) Date: Sun, 14 Sep 2008 08:21:37 -0500 Subject: testing if another instance of a script is already running In-Reply-To: <ed010651-331a-4b81-bbce-086a5ffb6368@m3g2000hsc.googlegroups.com> References: <mailman.911.1221221070.3487.python-list@python.org> <43f5d8be-a8c4-4074-9cb9-c182d097239e@79g2000hsk.googlegroups.com> <mailman.986.1221345275.3487.python-list@python.org> <ed010651-331a-4b81-bbce-086a5ffb6368@m3g2000hsc.googlegroups.com> Message-ID: <18637.4065.376526.515813@montanaro-dyndns-org.local> Aaron> Would it suffice to call 'os.open' with flags= _O_CREAT| _O_EXCL Aaron> ? Would that be platform-independent? I suspect it would be platform-independent but not NFS-safe. (The other solutions in lockfile might have NFS problems as well. In any case, lockfile provides a bit more functionality as well, including timeouts and the ability to break locks. Skip From ruqiang826 at gmail.com Thu Sep 11 05:31:23 2008 From: ruqiang826 at gmail.com (ruqiang826) Date: Thu, 11 Sep 2008 02:31:23 -0700 (PDT) Subject: how dump a program which is running in memory Message-ID: <0592abb3-c2f6-4977-8338-3aa1956a353c@b38g2000prf.googlegroups.com> hi I have written a service running backgroud to do something in linux. unfortunately?I deleted the source code by mistake, and I can still see the process running background using "ps aux" : username 13820 0.0 0.0 60368 2964 ? S Aug20 0:33 python ./UpdateJobStatus.py I wonder if there is some way to dump the programme "UpdateJobStatus.py" and get the source code back? Thanks a lot. From gogtesuyash at gmail.com Wed Sep 17 08:23:53 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 05:23:53 -0700 (PDT) Subject: SMTP via GMAIL References: <17a187fd-79e3-428f-8317-eca7e461eb57@c65g2000hsa.googlegroups.com> <tvkf941kmehd7hcihihdiil6fjutbfkf6k@4ax.com> <93afa637-9292-4628-9028-ca6f8b299914@x35g2000hsb.googlegroups.com> Message-ID: <973f75d4-90f5-4930-9107-15fc8651196d@v16g2000prc.googlegroups.com> On Aug 7, 12:40 am, mmm <mdbol... at gmail.com> wrote: > On Aug 5, 12:18 am, Tim Roberts <t... at probo.com> wrote: > > > >But when using smtp.gmail.com as the server I learned that any > > >@gmail.com address in the Cc: text block would > > >receive mail even if I changed the code to have the RECEIVERS list to > > >ignore the CC addresses or not include the gmail address in the CC > > >list as below > > > Interesting. If true, that is incorrect behavior. > > I ran some more tests and now I am pretty sure > > session.sendmail(SENDER, RECEIVERS, BODY) > > is only sending to the RECEIVERS list, ignoring the Cc: field in the > body (as it should) > > What fooled me is that I was using my own gmail account (i.e., > m... at gmail.com) as a Cc: field and not putting it in the RECEIVERS > list. It seems Gmail creates two links (or copies?) to the message: > (1) as it is stored in the SENT box (as it should since the message > was sent by my gmail account) and (2) another in my INBOX because the > mail reading software reads the Cc: field. > > Other smtp servers such as comcast do not create the stored SENT mail > and hence behave different in terms of how they treat Cc: fields of > the same account (m... at comcast.net in this case). > > Most important, using another gmail account (not m... at gmail.com) as a > Cc: field does not create another sent message (outside of what is in > the RECEIVERS field). > > Sorry for confusion, and I do appreciate the tips as I now see how > almost anything To:, Cc:, Bcc: combination can be handled by a proper > RECEIVERS list. > > Below is python code that can be used by anyone that wants to test > what I did (just fill in the SMTPuser and password variables) and > then check you gmail inbox > > import sys, os, glob, datetime, time > import smtplib > ## Parameters for SMTP session > port=587 > SMTPserver= 'smtp.gmail.com' > SMTPuser= '... at gmail.com' > pw= 'fill in here' > SENDER= SMTPuser > > ## Message details > FROM= SENDER > TO= 'notgm... at a.com' > CC=FROM > ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC > RECEIVERS= (TO,) ## ignore the CC address > > subject= 'Test 1a' > message='*** Email test *** ' > > print 'Starting SMTP mail session on %s as %s ' % > (SMTPserver,SMTPuser) > session = smtplib.SMTP(SMTPserver,port) > session.set_debuglevel(0) # set debug level to 1 to see details > session.ehlo(SMTPuser) # say hello > session.starttls() # TLS needed > session.ehlo(SMTPuser) # say hello again, not sure why > session.login(SMTPuser, pw) > > ##Create HEADER + MESSAGE > HEADER= 'From: %s\r\n' % FROM > HEADER= HEADER + 'To: %s\r\n' % TO > HEADER= HEADER + 'Cc: %s\r\n' % CC > HEADER= HEADER + 'Subject: %s\r\n' % subject > BODY= HEADER + '\r\n' + message > print BODY > > SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email > > session.close() i tried to run this code...but it didnt work it shows that message like starting smtp session then it doesnt show anything after very long time it shows Traceback (most recent call last): File "mail5.py", line 21, in <module> session = smtplib.SMTP(SMTPserver,port) File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ (code, msg) = self.connect(host, port) File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect self.sock.connect(sa) File "<string>", line 1, in connect then conncetion time out..... can u tell me wats the prob ...plz tell me solun From tino at wildenhain.de Fri Sep 26 11:13:58 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Fri, 26 Sep 2008 17:13:58 +0200 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> Message-ID: <48DCFC36.3070708@wildenhain.de> Michael Mabin wrote: > I laugh in the face of danger. > > Give me a use case for an exploit. .... (see below) > > On Fri, Sep 26, 2008 at 8:05 AM, Tino Wildenhain <tino at wildenhain.de > <mailto:tino at wildenhain.de>> wrote: > > Michael Mabin wrote: > > cursor.execute(""" > SELECT titem.object_id, titem.tag_id > FROM tagging_taggeditem titem > WHERE titem.object_id IN (%s) > """ % ','.join([str(x) for x in [1,5,9]]) > > > Nope. That would be dangerous! -> google for SQL injection > > Tino You are not seeing it? Do you know where the OP actually gets his list data from in the first place? You might get away with str(int(x)) as an easy "sanetizer" Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/a3c27d4a/attachment-0001.bin> From a_jtim at bellsouth.net Wed Sep 24 21:27:24 2008 From: a_jtim at bellsouth.net (Tim Arnold) Date: Wed, 24 Sep 2008 18:27:24 -0700 (PDT) Subject: multiple processes, private working directories Message-ID: <57cdd3f1-cde8-45f5-b9d9-3eef32010bda@l43g2000hsh.googlegroups.com> I have a bunch of processes to run and each one needs its own working directory. I'd also like to know when all of the processes are finished. (1) First thought was threads, until I saw that os.chdir was process- global. (2) Next thought was fork, but I don't know how to signal when each child is finished. (3) Current thought is to break the process from a method into a external script; call the script in separate threads. This is the only way I can see to give each process a separate dir (external process fixes that), and I can find out when each process is finished (thread fixes that). Am I missing something? Is there a better way? I hate to rewrite this method as a script since I've got a lot of object metadata that I'll have to regenerate with each call of the script. thanks for any suggestions, --Tim Arnold From joefazee at gmail.com Sat Sep 27 17:43:02 2008 From: joefazee at gmail.com (A. Joseph) Date: Sat, 27 Sep 2008 14:43:02 -0700 Subject: check if file is MS Word or PDF file Message-ID: <ea09b3700809271443p14a5a550g8b4985746897b14c@mail.gmail.com> What should I look for in a file to determine whether or not it is a MS Word file or an Excel file or a PDF file, etc., etc.? including Zip files I don`t want to check for file extension. os.path.splitext('Filename.jpg') will produce a tuple of filename and extension, but some file don`t even have extension and can still be read by MS Word or NotePad. i want to be 100% sure of the file. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080927/3980f9c9/attachment-0001.html> From gopalm at infotechsw.com Thu Sep 4 05:28:13 2008 From: gopalm at infotechsw.com (gopal mishra) Date: Thu, 4 Sep 2008 14:58:13 +0530 Subject: cPickle Message-ID: <01f901c90e70$8e118a50$2fc513ac@pwit.com> I have 3 objects and want to save in one pickle file. I used cPickle to dump 3 objects in a pkl file i.e cPickle.dump(object1, fileobject, -1) cPickle.dump(object2, fileobject, -1) cPickle.dump(object3, fileobject, -1) I have changed the 3rd object and want to save the updated 3rd object in the pickle file. I have to dump all the 3 objects again. Is there any way to dump only the 3rd object in to the pkl file. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080904/c0f18b27/attachment-0001.html> From ldo at geek-central.gen.new_zealand Fri Sep 26 18:06:49 2008 From: ldo at geek-central.gen.new_zealand (Lawrence D'Oliveiro) Date: Sat, 27 Sep 2008 10:06:49 +1200 Subject: Time.sleep(0.0125) not available within Linux References: <mailman.1386.1222135814.3487.python-list@python.org> <__KdneWJPotDx0XVnZ2dnUVZ_gGdnZ2d@posted.usinternet> <gbd44t$vo9$2@lust.ihug.co.nz> <00eb2560$0$20666$c3e8da3@news.astraweb.com> <gbi402$s8a$2@lust.ihug.co.nz> <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d@posted.visi> Message-ID: <gbjmdp$q1e$2@lust.ihug.co.nz> In message <Qtmdndz1gYzQnkDVnZ2dnUVZ_szinZ2d at posted.visi>, Grant Edwards wrote: > Never assume somebody reading the article and attempting to > help you can see the subject line. Why not? From callen314 at gmail.com Mon Sep 22 21:34:46 2008 From: callen314 at gmail.com (Craig Allen) Date: Mon, 22 Sep 2008 18:34:46 -0700 (PDT) Subject: Not fully OO ? References: <48d4c11b$0$22877$426a74cc@news.free.fr> Message-ID: <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> It is clear to me that Python is a multiparadigmed object oriented language. It is clearly possible to write procedural code... that is, Python does not force object oriented syntax or concepts on you and insist you define everything in such a structure. Is the OO it allows full OO, I think so, and the only way to argue otherwise I think is to point out that the "main" function is just the module level itself, and is not part of an object... which is just the sort of pedantic things purists like to hang their hat on. personally I am very much the sort that believe in "trust the programmer" and likes languages that provide a freedom to use various complementary paradigms, in the style of C++. Compared to that, it's clear that Python is quite object oriented even in the sense of drawing you to build things in object oriented ways... just not strictly requiring it. Which is good, it allows some interesting patterns which play quite well with object oriented desirgn (i.e. module as singleton)... in fact, that plays so well as a singleton, some would say the module is just an object anyway, and indeed, the intepreter tends to agree. So python may turn out to be pure OO, where Objects SIMULATE procedural programming paradigms and allow that paradigm as a result, on top of OO. cheers. From python-pep at arcor.de Thu Sep 25 16:14:56 2008 From: python-pep at arcor.de (python-pep at arcor.de) Date: Thu, 25 Sep 2008 22:14:56 +0200 Subject: PEP Proposal References: <48dbe58a$0$6663$9b4e6d93@newsspool2.arcor-online.net> <mailman.1508.1222373098.3487.python-list@python.org> Message-ID: <48dbf140$0$6655$9b4e6d93@newsspool2.arcor-online.net> Gabriel Genellina wrote: > En Thu, 25 Sep 2008 16:24:58 -0300, <python-pep at arcor.de> escribi?: > >> sorry, I have these ideas for longer than 10 years, please have a look >> on it >> and comment on it. Thx. >> >> This is another proposal for introducing types into Python. > > You got the terminology wrong. Python had "types" from the very start. > You're talking about some kind of generic functions, or an alternative > dispatch method. Typed parameters. Method-Declaration-filtered-typed parameters. That's what I'm thinking of. I hear & I will answer. From gh at ghaering.de Fri Sep 5 19:30:18 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sat, 06 Sep 2008 01:30:18 +0200 Subject: sqlite3 import performance In-Reply-To: <df87099b-4957-4f01-b9f2-e452bef064e9@v16g2000prc.googlegroups.com> References: <df87099b-4957-4f01-b9f2-e452bef064e9@v16g2000prc.googlegroups.com> Message-ID: <6idtobFq1f6tU1@mid.uni-berlin.de> Ben Lee wrote: > hi folks -- > > a quick python and sqlite3 performance question. i find that > inserting a million rows of in-memory data into an in-memory database > via a single executemany() is about 30% slower than using the sqlite3 > CLI and the .import command (reading the same data from a disk file, > even.) i find this surprising, executemany() i assume is using a > prepared statement and this is exactly what the .import command does > (based on my quick perusal of the source.) > > is this discrepancy to be expected? where is the overhead coming > from? [...] Ok, I'll bite. Well, first, the a 30 % slowdown with a Python DB-API wrapper compared to the native commandline tool of the database is to be considered still quite reasonable, in my opinion. About a year ago I compared the performance of pysqlite vs. the other SQLite wrapper, APSW. At the time, APSW was a bit faster, not excessively, but measurable. In meaningless benchmarks like yours ;-) So I changed pysqlite here and there to get the same performance as APSW. Only minor tweaks, nothing spectacular. And a few hardcore tricks as well, like special-casing *not-subclassed* classes. The result was pysqlite 2.3.5: http://oss.itsystementwicklung.de/trac/pysqlite/wiki/2.3.5_Changelog These optmizations are not yet in Python 2.5.x, but they can be found in the sqlite3 module of the Python 2.6/3.0 betas. Well, here are my results of your benchmark :-) -- Gerhard # with Python 2.5.2's sqlite3 module gerhard at lara:~/tmp$ python t.py generating data... done! testing 1000000 inserts... [42.795290946960449, 44.337385892868042, 46.35642409324646] # with pysqlite 2.5.0, which I released earlier today gerhard at lara:~/tmp$ python t.py generating data... done! testing 1000000 inserts... [33.027599096298218, 32.73675012588501, 32.823790073394775] # SQLite commandline gerhard at lara:~/tmp$ time sqlite3 -init sqlcmds ':memory:' '.quit' real 0m32.514s gerhard at lara:~/tmp$ time sqlite3 -init sqlcmds ':memory:' '.quit' real 0m32.576s gerhard at lara:~/tmp$ time sqlite3 -init sqlcmds ':memory:' '.quit' real 0m32.604s From miki.tebeka at gmail.com Thu Sep 18 19:35:48 2008 From: miki.tebeka at gmail.com (Miki) Date: Thu, 18 Sep 2008 16:35:48 -0700 (PDT) Subject: Python newbie question re Strings and integers References: <c0287f45-1c5a-40b5-aff3-ab5639d26749@k13g2000hse.googlegroups.com> Message-ID: <7c66014b-bfcf-40ef-aca9-16f3f749c7ac@b2g2000prf.googlegroups.com> > ? ? currentSymbol=filename[int(filenameStart),int(extensionStart)] Should be currentSymbol=filename[int(filenameStart):int(extensionStart)] (change , to :) You don't need to convert to int all the time, rfind will return an integer. Also you can use os.path for this from os.path import basename, splitext currentSymbol = splitext(basename(filename))[0] HTH, -- Miki <miki.tebeka at gmail.com> http://pythonwise.blogspot.com From kqanh at yahoo.com Tue Sep 30 23:48:12 2008 From: kqanh at yahoo.com (Anh Khuong) Date: Tue, 30 Sep 2008 20:48:12 -0700 (PDT) Subject: Output of pexpect Message-ID: <285898.28621.qm@web50802.mail.re2.yahoo.com> Hi all, I am using pexpect and I want to send output of pexpet to both stdout and log file concurrently. Anybody know a solution for it please let me know. Thanks From castironpi at gmail.com Fri Sep 12 23:08:27 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 12 Sep 2008 20:08:27 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? References: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> Message-ID: <b2a326bf-8b80-4b1c-9896-d5056bb3237a@w7g2000hsa.googlegroups.com> On Sep 12, 8:08?pm, i... at illusorygoals.com wrote: > First off, I'm a python n00b, so feel free to comment on anything if > I'm doing it "the wrong way." I'm building a discrete event simulation > tool. I wanted to use coroutines. However, I want to know if there's > any way to hide a yield statement. > > I have a class that I'd like to look like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? result = self.ping("128.111.41.38") > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > But because I can't hide yield inside ping, and because I can't find a > convenient way to get a self reference to the coroutine (which is used > by the event queue to pass back results), my code looks like this: > > class Pinger(Actor): > ? ? def go(self): > ? ? ? ? # I dislike this next line > ? ? ? ? self.this_pointer = (yield None) > ? ? ? ? success = True > ? ? ? ? while success: > ? ? ? ? ? ? # I want to get rid of the yield in the next line > ? ? ? ? ? ? result = (yield self.ping("128.111.41.38")) > ? ? ? ? ? ? if result != "success": > ? ? ? ? ? ? ? ? success = False > ? ? ? ? print "Pinger done" > > I posted a more detailed version of this as a rant here:http://illusorygoals.com/post/49926627/ > > I'd like to know, is there a way to get the syntax I want? After > staying up late last night to get a proof-of-concept working with > coroutines, my boss expressed disappointment in the ugliness of the > Pinger code (we agreed on the desired syntax above). I spent almost 2 > hours today to migrate the system over to threads. That made my boss > happy, but I'm still curious if I can do something to salvage the > coroutine version. > > Regards, > IG I did not read you whole post though I did skim your link. I don't know your whole problem but it seems you are trying to inform a generator of its own identity. Here's a solution to that problem; perhaps it relates to yours. (The shorter retort is, "Just use closures.") def gen( ): def _gen( ): while 1: yield 1, 'i am %r'% ob yield 2, 'i am %r'% ob yield 3, 'i am %r'% ob ob= _gen( ) return ob gens= [ gen( ) for _ in range( 4 ) ] for i in range( 6 ): print i for g in gens: print g.next( ) /Output (lengthy): 0 (1, 'i am <generator object at 0x009FEC10>') (1, 'i am <generator object at 0x009FEC38>') (1, 'i am <generator object at 0x009FEC60>') (1, 'i am <generator object at 0x009FEC88>') 1 (2, 'i am <generator object at 0x009FEC10>') (2, 'i am <generator object at 0x009FEC38>') (2, 'i am <generator object at 0x009FEC60>') (2, 'i am <generator object at 0x009FEC88>') 2 (3, 'i am <generator object at 0x009FEC10>') (3, 'i am <generator object at 0x009FEC38>') (3, 'i am <generator object at 0x009FEC60>') (3, 'i am <generator object at 0x009FEC88>') 3 (1, 'i am <generator object at 0x009FEC10>') (1, 'i am <generator object at 0x009FEC38>') (1, 'i am <generator object at 0x009FEC60>') (1, 'i am <generator object at 0x009FEC88>') 4 (2, 'i am <generator object at 0x009FEC10>') (2, 'i am <generator object at 0x009FEC38>') (2, 'i am <generator object at 0x009FEC60>') (2, 'i am <generator object at 0x009FEC88>') 5 (3, 'i am <generator object at 0x009FEC10>') (3, 'i am <generator object at 0x009FEC38>') (3, 'i am <generator object at 0x009FEC60>') (3, 'i am <generator object at 0x009FEC88>') From support at mysfdomain.com Wed Sep 17 16:12:49 2008 From: support at mysfdomain.com (support at mysfdomain.com) Date: Wed, 17 Sep 2008 13:12:49 -0700 (PDT) Subject: ANN: Python GUI development using XULRunner References: <mailman.1150.1221614920.3487.python-list@python.org> <276894e1-2611-44b2-b804-ae61c3b16d33@59g2000hsb.googlegroups.com> <mailman.1179.1221675641.3487.python-list@python.org> Message-ID: <6fb3f093-23bc-4a3f-91ce-1c3c03480823@d45g2000hsc.googlegroups.com> On Sep 17, 1:21?pm, Todd Whiteman <to... at activestate.com> wrote: > Don Spaulding wrote: > > On Sep 16, 8:29 pm, Todd Whiteman <to... at activestate.com> wrote: > >> I've put together a tutorial that shows off how to build a GUI > >> application using XULRunner (same architectural components as Firefox > >> uses) that can be used in conjunction with the Python programming language. > > >> The tutorial covers how to build a Python/XULRunner GUI application:http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xul... > > > I get to the "Running" step and run into "Couldn't load XPCOM." > > > Does this work on x86_64? ?Or have I made a rookie mistake? > > Hi Don, > > A good question. Mozilla only provide 32-bit XulRunner applications by > default, you you'll need to install the necessary 32-bit compatability > libraries on your Linux machine, i.e. for Ubuntu it's something like: > sudo apt-get install ia32-libs ia32-libs-gtk > > Then you should be able to run the example. You can check the > dependencies using something the following commands, there should be no > missing dependencies: > $ cd pyxpcom_gui_app/xulrunner > $ LD_LIBRARY_PATH=. ldd ./xulrunner-bin > > It is possible to use a 64-bit version, but you'll need to compile this > yourself (or find somewhere that provides these x86_64 versions). Note > that the PythonExt project does not offer Python bindings for x86_64 > either (it's on my todo list), you can compile the PythonExt part > yourself as well if you need a 64-bit version. > > Cheers, > Todd Interesting, I'm running Ubuntu Intrepid here, and have both ia32-libs and ia32-libs-gtk installed. ldd shows that I'm missing the following libs, even though the proper packages are installed, and the files show up in /usr/lib. libxcb-render-util.so.0 => not found libxcb-render.so.0 => not found There's also /usr/lib/libxcb-render.so.0.0.0 and the same for render- util, so I wonder if that could be part of the problem? Don /me never knew how to get out of DLL hell on Windows either ;-) From rstarkov at gmail.com Sun Sep 14 02:50:28 2008 From: rstarkov at gmail.com (rs387) Date: Sat, 13 Sep 2008 23:50:28 -0700 (PDT) Subject: Stuck connection in Python 3.0b2 http.server Message-ID: <1a23cbe5-26f5-4332-8901-7aa06c69d68e@k7g2000hsd.googlegroups.com> Hi All I've encountered a weird issue when migrating a web server to Python 3 - the browser would wait forever without showing a page, displaying "Transferring data" in the status bar. I tracked it down to a reference cycle in my BaseHTTPRequestHandler descendant - one of the attributes stored a dict of methods. Removing the cycle made the problem go away. In Python 2.5.2 the code works fine either way. Here's a minimal example which runs in both 2.5 and 3.0 - to see stuck connections run as-is in 3.0 and navigate to http://localhost:8123; to fix this comment out "self.dummy = self" (alternatively reset self.dummy = None at the end of the __init__ method). Am I doing it wrong, or is this a bug? try: import http.server httpmodule = http.server except: import BaseHTTPServer httpmodule = BaseHTTPServer class BreakageRequest(httpmodule.BaseHTTPRequestHandler): def __init__(self, request, client_address, server): self.dummy = self # COMMENT THIS OUT to see the connection become unstuck httpmodule.BaseHTTPRequestHandler.__init__(self, request, client_address, server) def do_GET(self): self.send_response(200) self.send_header("Content-Type", "application/xml") self.end_headers() self.wfile.write("<is_it_stuck/>".encode('utf-8')) srv = httpmodule.HTTPServer(('', 8123), BreakageRequest) srv.serve_forever() From steve at REMOVE-THIS-cybersource.com.au Thu Sep 4 05:24:28 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 04 Sep 2008 09:24:28 GMT Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <mailman.375.1220375272.3487.python-list@python.org> Message-ID: <00cfa3b9$0$20302$c3e8da3@news.astraweb.com> On Tue, 02 Sep 2008 13:07:33 -0400, Joe Riopel wrote: > On Tue, Sep 2, 2008 at 12:55 PM, Steven D'Aprano > <steve at remove-this-cybersource.com.au> wrote: >> Is there a better way of doing this than the way I am going about it? > > Would the logging module help, and just print the output to the stdout > (or a file) instead? Thank you to everyone who answered. As I feared, it seems that there's no really simple way of dealing with arbitrary messages at arbitrary parts of my code. I'm currently playing around with a few ideas, one of which is a decorator to print information about function calls. However, what I'd like to avoid is having to explicitly call the decorator on every method. I guess that there's metaclass trickery I can play. Does anyone have any pointers on how I can apply a decorator to every method in a class automatically? -- Steven From m_palmer45 at yahoo.ca Mon Sep 22 09:44:39 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Mon, 22 Sep 2008 06:44:39 -0700 (PDT) Subject: matrix algebra References: <1222070567.979005@chilli.pcug.org.au> Message-ID: <78547919-be84-41ac-955b-78824d64b4b8@y21g2000hsf.googlegroups.com> On Sep 22, 4:02 am, Al Kabaila <akaba... at pcug.org.au> wrote: > This is a very active newsgroup that incudes such giants as Frederik Lundh He looks rather small to me in this picture: http://www.python.org/~guido/confpix/flundh-2.jpg From m_palmer45 at yahoo.ca Fri Sep 12 18:53:00 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 12 Sep 2008 15:53:00 -0700 (PDT) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <8a81f213-4ea2-4808-b92f-f001fac3fe0c@x41g2000hsb.googlegroups.com> On Sep 12, 11:08 am, Bojan Mihelac <bmihe... at gmail.com> wrote: > Hi all - when trying to set some dynamic attributes in class, for > example: > > class A: > for lang in ['1', '2']: > exec('title_%s = lang' % lang) #this work but is ugly > # setattr(A, "title_%s" % lang, lang) # this wont work > > setattr(A, "title_1", "x") # this work when outside class > > print A.title_1 > print A.title_2 > > I guess A class not yet exists in line 4. Is it possible to achive > adding dynamic attributes without using exec? > > thanks, > Bojan Is it really worth it? If the names of the attributes are only known at runtime, why not just use a dict - that's what they are for. If you want a dict plus some special behaviour, just write a class that inherits from dict, or use UserDict.DictMixin. From lists at cheimes.de Fri Sep 5 19:54:10 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 06 Sep 2008 01:54:10 +0200 Subject: indices question In-Reply-To: <g9sgda$e9h$1@adenine.netfront.net> References: <g9sgda$e9h$1@adenine.netfront.net> Message-ID: <g9sgr2$6fb$1@ger.gmane.org> Lanny wrote: > Please don't tell me that "list indices must be integers" because I know > that, Why can't I put a varible thats an integer instead? raw_input() always returns a string. You have to convert the string into an integer using int(). Christian From python at rgbaz.eu Sun Sep 7 11:13:12 2008 From: python at rgbaz.eu (Python) Date: Sun, 7 Sep 2008 17:13:12 +0200 Subject: modules path In-Reply-To: <op.ug30i0hqx6zn5v@a98gizw.cpe.telecentro.net.ar> References: <mailman.626.1220738606.3487.python-list@python.org> <a6c1143a-bb64-4b9c-953e-831c6a74d741@a3g2000prm.googlegroups.com> <ADE2F843-E0B0-4679-9113-6AEBAC95DC09@rgbaz.eu> <op.ug30i0hqx6zn5v@a98gizw.cpe.telecentro.net.ar> Message-ID: <2AC6A5D0-A7EC-43C9-9948-99A5BCF82AD7@rgbaz.eu> On 7 sep 2008, at 13:50, Gabriel Genellina wrote: > En Sat, 06 Sep 2008 20:26:24 -0300, Python <python at rgbaz.eu> escribi?: > >> now one question came up, how do I make those path permanent? >> i mean, sys.path.append(<path)> adds it for the current session, >> yet when i logout of IDLE and start it again it's gone... >> how do i keep it in there? > > You can add that path to the PYTHONPATH environment variable, or you > can put a .pth file in the current Lib directory, containing the > desired path. > See http://docs.python.org/inst/search-path.html and the > documentation for the site module (although it appears not to be > totally accurate). > > -- > Gabriel Genellina > i read that but was wondering why some modules installed by macports did show up in the path and some didn't the PYTHONPATH wasn't set anywhere in my shell I did add it and now it works! Thanks John & Gabriel! gr Arno From fredrik at pythonware.com Thu Sep 4 17:53:33 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 23:53:33 +0200 Subject: Is it possible to download only the <head> of a web page? In-Reply-To: <d10e6046-fef2-46b8-a6ed-876afa93aa17@v16g2000prc.googlegroups.com> References: <d10e6046-fef2-46b8-a6ed-876afa93aa17@v16g2000prc.googlegroups.com> Message-ID: <g9plcu$uma$1@ger.gmane.org> Rex wrote: > I am writing a script that executes a bunch of queries through a form > on a website and reads the results. I am only interested in the > <title> section in the <head> of each web page. Currently, each page > the server returns is about 100kb and contains a bunch of HTML and > Javascript, all of which I don't need; I don't want to waste bandwidth > or consume too much of the server's resources. I just need the <title> > string. you need to issue a GET request to get the HTML head section, which almost always means that the server will build the entire page before sending it to you (so it can set content-length etc). you can save on network traffic by parsing the data as it arrives, and stopping when you've gotten the TITLE element: http://effbot.org/librarybook/sgmllib.htm </F> From apardon at forel.vub.ac.be Mon Sep 22 03:52:54 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 22 Sep 2008 07:52:54 GMT Subject: flock trouble References: <1460c93c-af24-40a3-8be4-31d582d48cb1@y21g2000hsf.googlegroups.com> Message-ID: <slrngdejn4.b8q.apardon@rcpc42.vub.ac.be> On 2008-09-08, Seb <sebastianthegreatful at gmail.com> wrote: > I'm trying to implement a file server using the code below. However > the locking doesn't work. I can delete while put'ing a file. > > Anyone got an idea about why? > [code snipped] As far as I understand you are writing some kind of server. What isn't clear is whether the daemon is using threading or forking to handle multiple requests. If I remember correctly, flock doesn't work well with multiple threads. -- Antoon Pardon From dear.jay.logan at gmail.com Mon Sep 22 09:55:13 2008 From: dear.jay.logan at gmail.com (josh logan) Date: Mon, 22 Sep 2008 06:55:13 -0700 (PDT) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> <87myi0z4tq.fsf@mulj.homelinux.net> Message-ID: <dfe26463-49fa-4f79-8b55-ac098d6808fb@26g2000hsk.googlegroups.com> On Sep 22, 9:29?am, Hrvoje Niksic <hnik... at xemacs.org> wrote: > josh logan <dear.jay.lo... at gmail.com> writes: > > sorted(P) # throws TypeError: unorderable types Player() < Player() > > > The sorted function works when I define __lt__. > > I must be misreading the documentation, because I read for the > > documentation __cmp__ that it is called if none of the other rich > > comparison functions are defined. > > Is this a bug in Python 3.0rc1, or am I missing something? > > What documentation are you referring to, exactly? ?The whole __cmp__ > thing was supposed to be removed from Python 3, so mention of it > sounds like a documentation bug. > > > Secondly, say that we suddenly need another sorting order, where we > > want to sort by decreasing score and then by DECREASING last name > > (instead of increasing last name, defined above). Now that the > > comparison function argument is taken away from the sorted builtin, > > how do we accomplish this with the "key" parameter? > > By calling sort twice on the sequence: > > lst.sort(key=lambda x: x.score) > lst.sort(key=lambda x: x.last_name, reverse=True) > > As much as I like the key argument, I believe it was a mistake to > remove cmp, simply because it was the more general mechanism. > Emulating cmp with key is possible, but it requires creating a bunch > of objects for each sort. ?(I'm aware that list.sort caches the > calculated keys, but it still has to create as many of them as there > are list items.) It looks like __cmp__ is still in the documentation, and it seems to work somewhat in Python 3.0rc1. Here is the link to the documnetation http://docs.python.org/dev/3.0/reference/datamodel.html#object.__cmp__ From timothy.grant at gmail.com Thu Sep 4 13:15:02 2008 From: timothy.grant at gmail.com (Timothy Grant) Date: Thu, 4 Sep 2008 10:15:02 -0700 Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? In-Reply-To: <3f0d61c40809040409v3ee40da3h7eb0703009e78f06@mail.gmail.com> References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <3f0d61c40809040409v3ee40da3h7eb0703009e78f06@mail.gmail.com> Message-ID: <e775286d0809041015t5d3b7945h9956cf36632bd53@mail.gmail.com> On Thu, Sep 4, 2008 at 4:09 AM, Marco Bizzarri <marco.bizzarri at gmail.com> wrote: > Sorry... pressed enter but really didn't want to. > > As I said, let's say I have a class > > class A: > def __init__(self): > self.x = None > > > > Python makes the decision to allow the developers to directly access > the attribute "x", so that they can directly write: "a.x = 1", or > whatever; this has for me the unfortunate side effect that if I write, > for example "a.y = 1", when I really wanted to write "a.x = 1" no one > cares about it, and I'm unable to spot this error until later. > > Of course, I know that while I'm fresh, I've a good knowledge of the > code, and anything else, I will be able to avoid such stupid errors; > however, I'm afraid of the times when I'm tired, when I have to put my > hands on the code of someone else, and so on. > > Please, understand that I'm not stating that python is wrong... after > all, if it is wrong, I can move to a language like Java, which has a > different approach on it. I'm really very interested in reading past > discussion on it, if they are available. > > Regards > Marco I think the most obvious solution to the problem is effective unit tests. If you type "a.y =1" and have a test that asserts a.x == 1 then you would quite quickly discover that you made a typo. -- Stand Fast, tjg. [Timothy Grant] From mkbernard.dev at gmail.com Sun Sep 7 20:47:28 2008 From: mkbernard.dev at gmail.com (MK Bernard) Date: Sun, 7 Sep 2008 17:47:28 -0700 (PDT) Subject: Updating python dictionary References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> <f8c5f1de-d358-468b-81fd-aa8108d8f7e0@q26g2000prq.googlegroups.com> Message-ID: <dde588e9-84eb-4890-ac42-21dd2aec35c6@q26g2000prq.googlegroups.com> On Sep 7, 3:37?pm, John Machin <sjmac... at lexicon.net> wrote: > On Sep 8, 7:51?am, "andyh... at gmail.com" <andyh... at gmail.com> wrote: > > > > > Hello... > > > I have a dict of key/values and I want to change the keys in it, based > > on another mapping dictionary. An example follows: > > > MAPPING_DICT = { > > ? ? 'a': 'A', > > ? ? 'b': 'B', > > > } > > > my_dict = { > > ? ? 'a': '1', > > ? ? 'b': '2' > > > } > > > I want the finished my_dict to look like: > > > my_dict = { > > ? ? 'A': '1', > > ? ? 'B': '2' > > > } > > > Whereby the keys in the original my_dict have been swapped out for the > > keys mapped in MAPPING_DICT. > > > Is there a clever way to do this, or should I loop through both, > > essentially creating a brand new dict? > > Is this homework? > > There seems to be an implicit assumption in the answers so far that > your mapping is a 1:1 mapping of all possible input keys. > > If it doesn't include all possible input keys, answers will crash with > a KeyError. If there are any many:1 elements in the mapping (for > example, {'a': 'A', 'b': 'A'}), lossage happens. You may wish to code > in some checks for this. Thats exactly why I did an explicit check in my post, so as to make sure that such a collision could not occur. It would seem that something along what I posted would be safer, if less elegant, than the others. Cheers, MK From mail at nospam.glenstark.net Tue Sep 9 03:31:12 2008 From: mail at nospam.glenstark.net (glen stark) Date: 9 Sep 2008 09:31:12 +0200 Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <yfs63pcwyip.fsf@gmail.com> <mailman.716.1220913165.3487.python-list@python.org> Message-ID: <48c62640_1@news.bluewin.ch> On Tue, 09 Sep 2008 08:32:29 +1000, Tom Harris wrote: > I agree. So did Forth's early designers. That is why Forth's number > parser considers a word that starts with a number and has embedded > punctuation to be a 32 bit integer, and simply ignores the punctuation. > I haven't used Forth in years, but it seems a neat solution to the > problem of decoding a long string of numbers: let the user put in > whatever they want, the parser ignores it. I usually used a comma (with > no surrounding whitespace of course), but it was your choice. You could > also do this in whatever base you were working in, so you could > punctuate a 32 bit hex number to correspond to the bit fields inside it. > Of course not applicable to Python. That sounds like a great idea, except I'd specify non-period (.) punctuation, so it would go for floating points as well. Is there a language design guru who can say why inputs like 123,456.00 couldn't be handles as above? the only problem I can see is an abiguity in argument lists (e.g. mult(2,4) ) which could be handled by the inclusion of whitespace. From http Fri Sep 26 13:11:15 2008 From: http (Paul Rubin) Date: 26 Sep 2008 10:11:15 -0700 Subject: how to search multiple textfiles ? References: <mailman.1536.1222436146.3487.python-list@python.org> Message-ID: <7xd4iqj0i4.fsf@ruckus.brouhaha.com> Stef Mientki <s.mientki at ru.nl> writes: > Does anyone know of a search library that performs this task fast ? You mean you want a Python search engine (with inverted indexes and all that)? Try: nucular.sf.net From mail at timgolden.me.uk Wed Sep 24 15:20:17 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 24 Sep 2008 20:20:17 +0100 Subject: Linq to Python In-Reply-To: <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> Message-ID: <48DA92F1.1060501@timgolden.me.uk> bearophileHUGS at lycos.com wrote: > sturlamolden: >> No, because Python already has list comprehensions and we don't need the XML buzzword.< > > LINQ is more than buzzwords. Python misses several of those features. > So maybe for once the Python crowd may recognize such C# feature as > much better than things present in Python. > Said that, I presume Python will go on as usual, and LINQ-like > capabilities will not be integrated in Python. In the meantime where I > live lot of people will keep using C# instead of Python and CLisp, > natural selection at work indeed. Perhaps a quick summary of what LINQ offers which might "be integrated into Python" would help those of us who are ignorant? (This is a serious comment; I'd like to know). TJG From kyosohma at gmail.com Thu Sep 4 09:34:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 4 Sep 2008 06:34:59 -0700 (PDT) Subject: Access to Windows "Add/Remove Programs"? References: <cf08e654-d2d5-48fe-a2ac-919fd2479254@v13g2000pro.googlegroups.com> <mailman.454.1220494440.3487.python-list@python.org> <e31f2517-23a3-459c-9c6f-bcb7233d0f82@w24g2000prd.googlegroups.com> Message-ID: <d0947bac-67ab-4e56-85e6-06752c08eca4@p10g2000prf.googlegroups.com> On Sep 3, 9:41?pm, Sean DiZazzo <half.ital... at gmail.com> wrote: > On Sep 3, 7:13?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > > > > > En Wed, 03 Sep 2008 21:51:59 -0300, Sean DiZazzo <half.ital... at gmail.com> ? > > escribi : > > > > I'm trying to find a way to get a list of all the installed programs > > > on a Windows box via Python. ?I thought of a few hacks that might > > > partially work, and then thought about "Add/Remove Programs" ?Seems > > > like the right way to go. ?I looked over the pywin32 docs a bit, but > > > nothing slapped me in the face. > > > > Is there any reliable way to get at that info? > > > You may enumerate the entries under this registry key: > > HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall > > > -- > > Gabriel Genellina > > Thank both of you. ?Perfect! > > ~Sean I have used both of these methods, but it should be noted that not all programs register themselves in the registry. The usual suspects are spyware related. But there are still a few programs that you can just download and unzip that don't write anything to the registry. But this does work for probably 99% of programs on Windows. Mike From code at pizzashack.org Fri Sep 26 15:25:08 2008 From: code at pizzashack.org (Derek Martin) Date: Fri, 26 Sep 2008 15:25:08 -0400 Subject: Test if list contains another list In-Reply-To: <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> <48c6380b$0$17080$426a34cc@news.free.fr> <mailman.741.1220976622.3487.python-list@python.org> <ebf50672-1371-4703-9567-cebd778cf4ee@a3g2000prm.googlegroups.com> Message-ID: <20080926192508.GK26713@dragontoe.org> On Thu, Sep 18, 2008 at 03:24:16AM -0700, gauravatnet at gmail.com wrote: > I looked inside this thread for my query which brought me the > following google search result > "Test if list contains another list - comp.lang.python | Google > Groups" > > But then I was disappointed to see the question asked was not exactly > right. [...] > def findAllMatchingList(mainList, subList): > resultIndex = [] > globalIndex = 0 > for i in range(len(mainList)): > if i < globalIndex: > continue > globalIndex = i > increment = 0 > for j in range(len(subList)): > if mainList[globalIndex] == subList[j]: > globalIndex += 1 > increment += 1 > if j == (len(subList)-1): > resultIndex.append(globalIndex-increment) > else: > break > > return resultIndex I didn't time them to compare, but how about this instead: >>> def find_needle_in_haystack(needle, haystack): ... r = [] ... L = len(needle) ... for i in range(len(haystack)): ... if haystack[i:i+L] == needle: ... r.append(i) ... return r >>> # this fails because "3" is not 3... >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,"3","9"]) [] >>> find_needle_in_haystack([1,2,3], [1,2,3]) [0] >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,3,"9"]) [2] >>> find_needle_in_haystack([1,2,3], ["a","b",1,2,3,"9","q",1,2,3]) [2, 7] -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/48921ad9/attachment-0001.sig> From kay.schluehr at gmx.net Thu Sep 4 01:49:21 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 3 Sep 2008 22:49:21 -0700 (PDT) Subject: PyGUI as a standard GUI API for Python? References: <4fa54717-913c-4269-8d03-58d9a9b31043@73g2000hsx.googlegroups.com> Message-ID: <b367b494-66ba-4bd0-a724-9bc77fcea97a@b30g2000prf.googlegroups.com> On 3 Sep., 18:34, Michael Palmer <m_palme... at yahoo.ca> wrote: > As anyone knows, the state of Python GUI programming is a little > fractured at this time, with many toolkits, wrappers and meta-wrappers > dead and alive, with or without documentation. A few thoughts. 1) This topic is discussed here every few months. While some kind of AnyGUI is theoretically very elegant it hasn't worked out well in practice: GUI libs are huge and heterogeneous. It's much unlike building an API-layer on top of SQL. Moreover I'd like to ask whether the fragmentation turns out to be that much of a problem in practice? 2) Tcl/Tk might have a revival due to the new Tk-theme engine in version 8.5. http://www.tcl.tk/software/tcltk/8.5.tml http://wiki.tcl.tk/13636 Chances are Tkinter widgets will not look like early '90s legacy anymore. 3) Following the public rumor mill and the latest hype RIA i.e. the merge of web- and desktop applications with systems like Adobe AIR, JavaFX, Google Gears and MS Silverlight is the future of frontend development. With the exception of IronPython and Silverlight, Python hasn't even entered this game and no one knows if it ever will. Ciao, Kay From luigi at lambrate.inaf.it Wed Sep 3 08:31:02 2008 From: luigi at lambrate.inaf.it (Luigi Paioro) Date: Wed, 03 Sep 2008 14:31:02 +0200 Subject: Custom handler for logging Message-ID: <48BE8386.6010305@lambrate.inaf.it> Dear all, concerning the logging module, I have written a new Handler which stores the logging messages in an SQLite database. It works well, but when I try to use it exploiting a configuration file I have a problem since the "class" entry does not accept a class which is not within the logging name-space, while the class I implemented is coded in my personal module (thus another name-space). Is there a workaround to allow the usage of custom handlers? Thanks in advance. Luigi From bearophileHUGS at lycos.com Mon Sep 1 21:34:40 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Mon, 1 Sep 2008 18:34:40 -0700 (PDT) Subject: Numeric literal syntax (was: Py 2.6 changes) References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> Message-ID: <5796f7d3-08c3-43d9-96a2-5b5b3716a781@t54g2000hsg.googlegroups.com> Ben Finney: > I don't see any good reason (other than your familiarity with the D > language) to use underscores for this purpose, and much more reason > (readability, consistency, fewer arbitrary differences in syntax, > perhaps simpler implementation) to use whitespace just as with string > literals. It's not just my familiarity, Ada language too uses underscore for that purpose, I think, so there's a precedent, and Ada is a language designed to always minimize programming errors, simple code mistakes too. And another thing to consider is that they so far have given me zero problems... Consider: a = 125 125 125 a = 125, 125, 125 a = 125_125_125 For me the gestalt of the first line looks too much like the second one, that is three separated things (note that this is relative to the font you use, I am using a really good free font, Inconsolata, the very best I have found to program (better than Consolas) that separates things well). While in the third case the _ helps glue the parts, creating a single gestalt to my eyes. Note that it's not just a matter of font and familiarity, it's also a matter of brains. Your brain may be different from mine, so it may be possible that what's better for you isn't better for me. So in such situation a popular voting may be the only way to choose. But for me having spaces to split number literals in parts is _worse_ than not having any way at all to split them. So I'm strong opposed to your suggestion, so I may not even propose the PEP if lot of people agrees with your tastes. Bye, bearophile From pladow at gmail.com Mon Sep 15 11:58:10 2008 From: pladow at gmail.com (PlayDough) Date: Mon, 15 Sep 2008 08:58:10 -0700 (PDT) Subject: Segfault in vgetargskeywords Message-ID: <b65fcd21-deb5-49a9-ac95-0ddc6c8e329c@8g2000hse.googlegroups.com> I am using ActivePython 2.5.1 (python --version returns 'Python 2.5.1') and I am trying to embed/extend. It is segfaulting in vgetargkeywords during the call to Py_Initialize(). Now, we are using a non-standard configuration, and perhaps some explanation is in order. Here's our system config (via 'uname -a' with the hostname stripped): Linux xxx.xxx.com 2.6.9-67.0.4.ELsmp #1 SMP Fri Jan 18 05:00:58 EST 2008 i686 i686 i386 GNU/Linux Or from the syslog: Linux version 2.6.9-67.0.4.ELsmp (brewbuilder at hs20- bc2-4.build.redhat.com) (gcc version 3.4.6 20060404 (Red Hat 3.4.6-9)) #1 SMP Fri Jan 18 05:00:58 EST 2008 I've already run into the problem linking because of the __ctype_b issue, but I think I've worked around that with '-Wl,-wrap' (at least it links). Here's the compilation command line I am doing: gcc -ggdb -O0 `python-config --includes` -o main main.c `python- config --ldflags` -Wl,-wrap,__ctype_b -Wl,-wrap,__ctype_tolower -Wl,- wrap,__ctype_toupper Where GCC is: gcc (GCC) 3.4.6 20060404 (Red Hat 3.4.6-9) And the code is just a single call to Py_Initialize(). There is the additional code to handle the wrap of __ctype_b: #include #include int main(int argc, char *argv[]) { Py_Initialize(); return 0; } __const unsigned short int **__wrap___ctype_b(void) { return __ctype_b_loc(); } __const __int32_t **__wrap___ctype_tolower(void) { return __ctype_tolower_loc(); } __const __int32_t **__wrap___ctype_toupper(void) { return __ctype_toupper_loc(); } So, after compiling, when I run it it coredumps with a segfault. Looking at the stack trace with gdb yields: GNU gdb Red Hat Linux (6.3.0.0-1.153.el4_6.2rh) Copyright 2004 Free Software Foundation, Inc. GDB is free software, covered by the GNU General Public License, and you are welcome to change it and/or distribute copies of it under certain conditions. Type "show copying" to see the conditions. There is absolutely no warranty for GDB. Type "show warranty" for details. This GDB was configured as "i386-redhat-linux-gnu"...Using host libthread_db library "/lib/tls/libthread_db.so.1". warning: exec file is newer than core file. Core was generated by `./sharc2'. Program terminated with signal 11, Segmentation fault. Reading symbols from /lib/tls/libpthread.so.0...done. Loaded symbols for /lib/tls/libpthread.so.0 Reading symbols from /lib/libdl.so.2...done. Loaded symbols for /lib/libdl.so.2 Reading symbols from /lib/libutil.so.1...done. Loaded symbols for /lib/libutil.so.1 Reading symbols from /lib/tls/libm.so.6...done. Loaded symbols for /lib/tls/libm.so.6 Reading symbols from /lib/tls/libc.so.6...done. Loaded symbols for /lib/tls/libc.so.6 Reading symbols from /lib/ld-linux.so.2...done. Loaded symbols for /lib/ld-linux.so.2 #0 0x080efbe3 in vgetargskeywords (args=0x40032c5c, keywords=0x0, format=0x812bf04 "|OOOi:__import__", kwlist=0x814ff84, p_va=0xbffff1c4, flags=0) at Python/getargs.c:1382 1382 Python/getargs.c: No such file or directory. in Python/getargs.c (gdb) bt #0 0x080efbe3 in vgetargskeywords (args=0x40032c5c, keywords=0x0, format=0x812bf04 "|OOOi:__import__", kwlist=0x814ff84, p_va=0xbffff1c4, flags=0) at Python/getargs.c:1382 #1 0x080efab1 in PyArg_ParseTupleAndKeywords (args=0x40032c5c, keywords=0x0, format=0x812bf03 "s|OOOi:__import__", kwlist=0x814ff84) at Python/getargs.c:1251 #2 0x080d6551 in builtin___import__ (self=0x0, args=0x40032c5c, kwds=0x0) at Python/bltinmodule.c:44 #3 0x0808ca6b in PyCFunction_Call (func=0x40025e6c, arg=0x40032c5c, kw=0x0) at Objects/methodobject.c:77 #4 0x080634d9 in PyObject_CallFunctionObjArgs (callable=0x40025e6c) at Objects/abstract.c:1860 #5 0x080f46f7 in PyImport_Import (module_name=0x40032b38) at Python/import.c:2570 #6 0x080f5319 in PyImport_ImportModule (name=0x8122fcb "__builtin__") at Python/import.c:1966 #7 0x0806f879 in _PyExc_Init () at Objects/exceptions.c:2061 #8 0x0804d5c9 in Py_InitializeEx (install_sigs=1) at Python/ pythonrun.c:228 #9 0x0804f43d in Py_Initialize () at Python/pythonrun.c:321 #10 0x0804d2c9 in main (argc=1, argv=0xbffff474) at main.c:22 Any ideas what is causing this problem? It appears to be while importing the __builtin__ package, but beyond that I'm not sure. From steven at REMOVE.THIS.cybersource.com.au Tue Sep 9 03:41:41 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 09 Sep 2008 07:41:41 GMT Subject: Correcting for Drift between Two Dates References: <pgnxk.9513$cn7.668@flpi145.ffdc.sbc.com> Message-ID: <pan.2008.09.09.07.41.41@REMOVE.THIS.cybersource.com.au> On Mon, 08 Sep 2008 21:53:18 -0700, W. eWatson wrote: > I have two dates, ts1, ts2 as below in the sample program. I know the > clock drift in seconds per day. I would like to calculate the actual > date of ts2. See my question at the end of the program. When faced with a complicated task, break it down into simpler subtasks. Functions are your friends. Here you go: from __future__ import division from datetime import datetime as DT from datetime import timedelta SITE_DRIFT = 4.23 # drift in seconds per day # negative drift means the clock falls slow SEC_PER_DAY = 60*60*24 # number of seconds per day def calc_drift(when, base, drift=SITE_DRIFT): """Return the amount of drift at date when since date base.""" x = when - base days = x.days + x.seconds/SEC_PER_DAY return drift*days def fix_date(when, base, drift=SITE_DRIFT): """Return date when adjusted to the correct time.""" d = calc_drift(when, base, drift) delta = timedelta(seconds=-d) return when + delta And here it is in action: >>> fix_date(DT(2008,9,9), DT(2008,9,8)) datetime.datetime(2008, 9, 8, 23, 59, 55, 770000) I leave it to you to convert date/time strings into datetime objects. -- Steven From hniksic at xemacs.org Tue Sep 16 09:02:46 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 15:02:46 +0200 Subject: Is 'x' an instance of a new-style class? References: <f568f4d9-b179-4ef1-9688-fcd8cb5ef641@d1g2000hsg.googlegroups.com> <mailman.1102.1221557922.3487.python-list@python.org> <739d438d-3631-4d06-8855-65097a5623aa@z66g2000hsc.googlegroups.com> Message-ID: <87tzcg5jm1.fsf@mulj.homelinux.net> MatthewS <schaefer.mp at gmail.com> writes: > Thanks Gabriel, the second solution seems to work based on my tests. > So I have this now this test: > > static BOOL IsPythonInstance( PyObject * src ) > { > { > // old style classes or instances or new style classes or instances > if( ( PyInstance_Check( src ) ) || ( PyClass_Check( src ) ) || > PyObject_TypeCheck( src, &PyBaseObject_Type) ) > { > return TRUE; > } > > return FALSE; > } > } I think this will return TRUE on any Python object you pass it. From steven at REMOVE.THIS.cybersource.com.au Fri Sep 19 04:14:07 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 19 Sep 2008 08:14:07 GMT Subject: Python newbie References: <gavjfd$mvd$1@registered.motzarella.org> <mailman.1261.1221809756.3487.python-list@python.org> Message-ID: <pan.2008.09.19.08.14.07@REMOVE.THIS.cybersource.com.au> On Fri, 19 Sep 2008 03:34:50 -0400, Steve Holden wrote: > Please note the above statement is contentious, and will likely bring a > horde of screaming fanatics of various flavors down on my head for > terminological inexactitude. A pox on you and your descendants onto the tenth generation! *wink* -- Steven From marco.bizzarri at gmail.com Sun Sep 14 04:08:10 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Sun, 14 Sep 2008 10:08:10 +0200 Subject: recursion gotcha? In-Reply-To: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> References: <928f2c67-0f80-4e83-82b4-d9397247483d@x41g2000hsb.googlegroups.com> Message-ID: <3f0d61c40809140108n515006dci87f91dcd971f0169@mail.gmail.com> On Sun, Sep 14, 2008 at 10:01 AM, cnb <circularfunc at yahoo.se> wrote: > this recursive definition of sum thrumped me, is this some sort of > gotcha or am I just braindead today? > and yes i know this is easy a a for x in xs acc += x or just using the > builtin. > > def suma(xs, acc=0): > if len(xs) == 0: > acc > else: > suma(xs[1:], acc+xs[0]) You're just missing the "return" statements? def suma(xs, acc=0): if len(xs) == 0: return acc else: return suma(xs[1:], acc+xs[0]) Regards Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From samslists at gmail.com Fri Sep 19 23:45:59 2008 From: samslists at gmail.com (Sam) Date: Fri, 19 Sep 2008 20:45:59 -0700 (PDT) Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <mailman.766.1221033019.3487.python-list@python.org> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> <mailman.1247.1221772248.3487.python-list@python.org> <61439bf7-e0c2-48c8-8fb3-62ae350f8768@p10g2000prf.googlegroups.com> <mailman.1273.1221821307.3487.python-list@python.org> Message-ID: <13fd1a7d-1d18-49c4-bd28-f06df620e6c1@a8g2000prf.googlegroups.com> Gabriel... Awesome! Thank you so much for the solution. And yeah, I found exactly one website that strangely enough only does deflate, not gzip. I'd rather not say what website it is, since it's small and not mine. They may be few and in between, but they do exist. Thanks On Sep 19, 3:48?am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> wrote: > En Thu, 18 Sep 2008 23:29:30 -0300, Sam <samsli... at gmail.com> escribi?: > > > On Sep 18, 2:10?pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar> > > wrote: > >> En Tue, 16 Sep 2008 21:58:31 -0300, Sam <samsli... at gmail.com> escribi?: > >> The code is correct - try with another server. I tested it with a ? > >> LightHTTPd server and worked fine. > > > Gabriel... > > > I found a bunch of servers to test it on. ?It fails on every server I > > could find (sans one). > > I'll try to check later. Anyway, why are you so interested in deflate? ? > Both "deflate" and "gzip" coding use the same algorithm and generate ? > exactly the same compressed stream, the only difference being the header ? > and tail format. Have you found any server supporting deflate that doesn't ? > support gzip as well? > > -- > Gabriel Genellina From tino at wildenhain.de Wed Sep 10 07:52:40 2008 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 10 Sep 2008 13:52:40 +0200 Subject: Web shopping carts In-Reply-To: <C4EB6DE0.11187%luke.hamilton@rpm-solutions.com.au> References: <C4EB6DE0.11187%luke.hamilton@rpm-solutions.com.au> Message-ID: <48C7B508.6070006@wildenhain.de> Luke Hamilton wrote: > Hey People, > > I am wondering if there are any OS shopping cart application written in > python? > Yes there are. HTH Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/1383c78d/attachment-0001.bin> From ppearson at nowhere.invalid Thu Sep 18 10:49:22 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: 18 Sep 2008 14:49:22 GMT Subject: Problem occured while sending mail References: <b7481bed-df0f-4ef7-8fe7-09da5869492f@c22g2000prc.googlegroups.com> <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> <6jckjhF2llrvU1@mid.individual.net> <2e63873f-ba8f-4519-b30c-9b5da913c64f@w24g2000prd.googlegroups.com> Message-ID: <6jf83iF2vk8jU1@mid.individual.net> On Wed, 17 Sep 2008 23:53:36 -0700 (PDT), sui <gogtesuyash at gmail.com> wrote: > On Sep 17, 8:04 pm, Peter Pearson <ppear... at nowhere.invalid> wrote: >> On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <gogtesuy... at gmail.com> wrote: [snip] >> > socket.error: (110, 'Connection timed out') [snip] >> As a simple connectivity test, you might see whether you can connect >> using telnet: [snip] > even i couldnt connect using telnet.... > msg comes host is down Then your problem is a networking problem. I know even less about networking than I know about Python. Can you ping the destination? Perhaps tracepath or traceroute will help you find where your messages are being refused. Perhaps you are trying to work through an internet access provider (e.g., ISP) that doesn't allow direct connections to remote mail servers. If I might add a grouchy comment, you really should learn a little about netiquette. When you don't bother to trim the quoted context or even to punctuate your text, you broadcast a conspicuous implication that you value your own time much more than you value the time of the people whose help you're soliciting, which is incongruous and insulting. A more carefully presented request might have gotten a response from someone more knowledgeable -- and less grouchy -- than me. -- To email me, substitute nowhere->spamcop, invalid->net. From blabla at dungeon.de Tue Sep 2 13:36:50 2008 From: blabla at dungeon.de (hofer) Date: Tue, 2 Sep 2008 10:36:50 -0700 (PDT) Subject: converting a sed / grep / awk / . . . bash pipe line into python Message-ID: <27212884-34a7-45b8-aceb-4ab6ae3b5ec3@a1g2000hsb.googlegroups.com> Hi, Something I have to do very often is filtering / transforming line based file contents and storing the result in an array or a dictionary. Very often the functionallity exists already in form of a shell script with sed / awk / grep , . . . and I would like to have the same implementation in my script What's a compact, efficient (no intermediate arrays generated / regexps compiled only once) way in python for such kind of 'pipe line' Example 1 (in bash): (annotated with comment (thus not working) if copied / pasted #------------------------------------------------------------------------------------------- cat file \ ### read from file | sed 's/\.\..*//' \ ### remove '//' comments | sed 's/#.*//' \ ### remove '#' comments | grep -v '^\s*$' \ ### get rid of empty lines | awk '{ print $1 + $2 " " $2 }' \ ### knowing, that all remaining lines contain always at least \ ### two integers calculate sum and 'keep' second number | grep '^42 ' ### keep lines for which sum is 42 | awk '{ print $2 }' ### print number Same example in perl: # I guess (but didn't try), taht the perl example will create more intermediate # data structures than necessary. # Ideally the python implementation shouldn't do this, but just 'chain' iterators. #------------------------------------------------------------------------------------------- my $filename= "file"; open(my $fh,$filename) or die "failed opening file $filename"; # order of 'pipeline' is syntactically reversed (if compared to shell script) my @numbers = map { $_->[1] } # extract num 2 grep { $_->[0] == 42 } # keep lines with result 42 map { [ $_->[0]+$_->[1],$_->[1] ] } # calculate sum of first two nums and keep second num map { [ split(' ',$_,3) ] } # split by white space grep { ! ($_ =~ /^\s*$/) } # remove empty lines map { $_ =~ s/#.*// ; $_} # strip '#' comments map { $_ =~ s/\/\/.*// ; $_} # strip '//' comments <$fh>; print "Numbers are:\n",join("\n", at numbers),"\n"; thanks in advance for any suggestions of how to code this (keeping the comments) H From ggpolo at gmail.com Sun Sep 14 10:45:20 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sun, 14 Sep 2008 11:45:20 -0300 Subject: cjson 1.0.5 keyword argument In-Reply-To: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> References: <3e715968-aae6-4e26-9933-273c654a1bc7@b30g2000prf.googlegroups.com> Message-ID: <ac2200130809140745i5ce3a3d5xc932f5deb8346e36@mail.gmail.com> On Sun, Sep 14, 2008 at 10:33 AM, Clodoaldo <clodoaldo.pinto at gmail.com> wrote: > I have installed cjson 1.05 in Fedora 8 (python 2.5.1). > > The cjson home page shows a keyword argument "encoding". > http://python.cx.hu/python-cjson/ > The latest python-cjson on that page is 1.0.3, which accepts keywords for the encode function. python-cjson 1.0.5 no longer accepts. > When i use it i get an error: > >>>> cjson.encode('?', encoding='utf8') > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > TypeError: encode() takes no keyword arguments > > What am i missing? There is no mail list for cjson. Try doing cjson.encode('?'.decode('utf-8')) instead. > > Regards, Clodoaldo > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From dev001 at pas-world.com Tue Sep 23 13:37:59 2008 From: dev001 at pas-world.com (F.) Date: Tue, 23 Sep 2008 19:37:59 +0200 Subject: Problems compiling on CentOS Python 2.5 Message-ID: <1222191480.13007.5.camel@localhost.localdomain> Hello, I have problems making python on CentOS 5. Seems that can not find something. I can not find the problem. Where is the problem? > case $MAKEFLAGS in \ > *-s*) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python -E ./setup.py -q build;; \ > *) CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \ > esac > running build > running build_ext > db.h: found (4, 3) in /usr/include > db lib: using (4, 3) db-4.3 > INFO: Can't locate Tcl/Tk libs and/or headers > building '_ssl' extension > gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes -I. -I/home/unStable/progC/exLibs/Python-2.5.2/Python-2.5.2/./Include -I. -IInclude -I./Include -I/usr/local/include -I/directory/Python-2.5.2/Python-2.5.2/Include -I/directory/Python-2.5.2/Python-2.5.2 -c /directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.c -o build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o > gcc -pthread -shared -fno-strict-aliasing -DNDEBUG -fwrapv -march=i686 -mmmx -msse -msse2 -msse3 -O3 -pipe -fomit-frame-pointer -Wall -Wstrict-prototypes build/temp.linux-i686-2.5/directory/Python-2.5.2/Python-2.5.2/Modules/_ssl.o -L/usr/local/lib -lssl -lcrypto -o build/lib.linux-i686-2.5/_ssl.so > *** WARNING: renaming "_ssl" since importing it failed: build/lib.linux-i686-2.5/_ssl.so: undefined symbol: krb5_auth_con_getrcache > running build_scripts -- -- Publicidad http://www.pas-world.com From gagsl-py2 at yahoo.com.ar Wed Sep 3 22:13:43 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 23:13:43 -0300 Subject: Access to Windows "Add/Remove Programs"? References: <cf08e654-d2d5-48fe-a2ac-919fd2479254@v13g2000pro.googlegroups.com> Message-ID: <op.ugxps5mmx6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 03 Sep 2008 21:51:59 -0300, Sean DiZazzo <half.italian at gmail.com> escribi?: > I'm trying to find a way to get a list of all the installed programs > on a Windows box via Python. I thought of a few hacks that might > partially work, and then thought about "Add/Remove Programs" Seems > like the right way to go. I looked over the pywin32 docs a bit, but > nothing slapped me in the face. > > Is there any reliable way to get at that info? You may enumerate the entries under this registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Sep 4 03:47:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 04 Sep 2008 04:47:07 -0300 Subject: use str as variable name References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> Message-ID: <op.ugx48t1hx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 04 Sep 2008 04:25:37 -0300, Mathieu Prevot <mathieu.prevot at gmail.com> escribi?: > I have a program that take a word as argument, and I would like to > link this word to a class variable. > > eg. > class foo(): > width = 10 > height = 20 > > a=foo() > arg='height' > a.__argname__= new_value > > rather than : > > if arg == 'height': > a.height = new_value > elif arg == 'width'; > a.width = new_value You're looking for "setattr": setattr(a, arg, new_value) http://docs.python.org/lib/built-in-funcs.html#l2h-66 > > Can I do this with python ? How ? > > Thanks, > Mathieu > -- > http://mail.python.org/mailman/listinfo/python-list > -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Wed Sep 3 15:19:30 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 Sep 2008 21:19:30 +0200 Subject: Late initialization using __getattribute__ In-Reply-To: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> Message-ID: <48beff32$0$10287$426a74cc@news.free.fr> bukzor a ?crit : > I want to make a MixIn class that waits to initialize its super- > classes until an attribute of the object is accessed. Not generally > useful, but desirable in my case. I've written this, and it works, but > would like to take any suggestions you guys have. You shouldn't mess with __getattribute__ unless you really know what you're doing and are ok to suffer the constant performance hit you'll get. Remember that __getattribute__ actually *is* the implementation of attribute lookup rules, and is called on each and every attribute lookup. Your below snippet would be much better using __getattr__ (which is only called as a last resort). > I've commented out > the "delattr" call because it throws an AttributeError (although I > don't know why). __getattribute__ belongs to the class, not to the instance. delattr() only removes instance attributes. You'd have to remove __getattribute__ from the LateInitMixIn class object itself, but then it would break the whole thing. > > > class LateInitMixIn(object): > def __init__(self): > print "LateInit initialization" > self.inited = False > def __getattribute__(self, attr): > print "Doing __getattribute__" > getattr = lambda attr:object.__getattribute__(self, attr) > if not getattr("inited"): > super(LateInitMixIn, self).__init__() > setattr(self, "inited", True) > #delattr(self, "__getattribute__") > return getattr(attr) Here's another possible implementation (which doesn't solve all problems, cf below) using __getattr__: class LateInitMixin(object): def __init__(self): print "not yet" self.__initialized = False def __getattr__(self, name): if self.__initialized: raise AttributeError( "object %s has no attribute '%s'" % (type(self), name) ) super(LateInitMixin, self).__init__() self.__initialized = True return getattr(self, name) class Base(object): def __init__(self): print "yet" self.base = True class LateInit(LateInitMixin, Base): pass def main(): print "shouldn't init" S = LateInit() print "should init" print S.base if __name__=="__main__": main() Ok, now, the other problem : what if Base.__init__ expects args ? From larry.bates at vitalEsafe.com Wed Sep 24 22:23:28 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Wed, 24 Sep 2008 21:23:28 -0500 Subject: Making small executive file for distribution In-Reply-To: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> References: <35fkd4t0nhjqu5l0gbcacqu4o5q10puu05@4ax.com> Message-ID: <ZyCCk.37890$XT1.10310@bignews5.bellsouth.net> Marin Brkic wrote: > Not commercial distribution, but an academic kind of sorts - giving > the exe file to coleagues, so they can use it in their work. Giving > .py file is not an option, since due to centralized computer > maintenance, they don't (and cannot) have installed python (except the > ones that bring their own computer at work, but those are an > exception). > > As far as I know py2exe is the only option which can do such a thing > (make exe files from scripts). Is there a way to make those exe files > a little smaller (for a small script they easily go up to 5-10 mb). > > Has anyone had a situation like this ? All your inputs and suggestions > are more then welcomed. > > -- > Marin > Times have changed, 5-10Mb is REALLY small. Flash drives hold 4000-8000Mb for less than $20 and standard hard drives are now 500Gb. IMHO you are concerned about a problem that doesn't actually exist. -Larry From clp at rebertia.com Mon Sep 8 15:04:41 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 8 Sep 2008 12:04:41 -0700 Subject: lacking follow-through In-Reply-To: <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <ccf8d124-4609-48a6-b487-7cccc6d9c4b9@a3g2000prm.googlegroups.com> <92da89760809080903j53be5306pb3867aed6e77c39e@mail.gmail.com> Message-ID: <47c890dc0809081204o3511b9dck1adadd98f73ca2b7@mail.gmail.com> On Mon, Sep 8, 2008 at 9:03 AM, Eric Wertman <ewertman at gmail.com> wrote: >> Perhaps the wrong idea of what the group is. I would have thought >> that >> if one had a sufficiently developed idea and wanted to have it / >> formally/ >> rejected, rather than merely sniped at, then writting a PEP would be >> more >> apposite than posting to c.l.py. >> >> It's fine to post your not sufficiently developed ideas here merely >> to >> have them discussed. But I don't know what makes you feel that you, >> or >> your ideas, are /entitled/ to any response at all, much less >> "follow-through." > > > To expand on this a little bit, I've been subscribed to this group > for a couple of months, but there seems to be a bit more gray area > between what would go to a 'python-dev' group and a 'python-user' > group. Long debates about language features and abstract ideas would > appeal to the former, but not the latter. Certainly I fall into the > user category.. I'm pretty happy with python, and generally just > adjust to it's design and features, rather than spend lots of time on > whether they are 'right' or could be 'better'. /shrug Yeah, suggestions about changing the language are much better suited to the more-specific Python-ideas or Python-3000 mailinglists than the general-purpose c.l.p - Chris > -- > http://mail.python.org/mailman/listinfo/python-list > -- Follow the path of the Iguana... http://rebertia.com From gagsl-py2 at yahoo.com.ar Tue Sep 30 15:28:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 30 Sep 2008 16:28:11 -0300 Subject: Would this be called a bug in inspect ? References: <48E268A3.4050900@gmail.com> Message-ID: <op.uia609w8x6zn5v@gabriel2.softlabbsas.com.ar> En Tue, 30 Sep 2008 14:57:55 -0300, Stef Mientki <stef.mientki at gmail.com> escribi?: > I'm not familiar with inspect, > but I get an error (see below) in > getmembers ( wx ) > > Of course this is bug in wx . Yes. > But would you also call this a bug in inspect ? > (inspect crashes and doesn't continue with th rest of the code, nor it > returns the already gathered data) getmembers works fine; try m=getmembers(wx) and see. It fails when you attemp to print (or pprint) the returned list. -- Gabriel Genellina From bj_666 at gmx.net Tue Sep 2 09:57:26 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Sep 2008 13:57:26 GMT Subject: Inquiry regarding the name of subprocess.Popen class References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> Message-ID: <6i4v26Fol29aU4@mid.uni-berlin.de> On Tue, 02 Sep 2008 09:28:42 -0400, Derek Martin wrote: > On Tue, Sep 02, 2008 at 12:27:49PM +0000, Marc 'BlackJack' Rintsch > wrote: >> > The Python class is a generalization of the standard Posix function >> > of (almost) the same name: >> > http://opengroup.org/onlinepubs/007908775/xsh/popen.html >> >> So it's a name of a *function* and it's a little bit unsuitable for a >> *class*. As Jeremy wrote: the instances represent *processes* not >> "popen"s, whatever that may be. > > I would argue that they don't represent processes at all; the object is > a set of files which connect the standard I/O streams of a subprocess to > its parent, and methods to operate on those files. And the process' ID, an attribute with the process' return code, a method to wait until the process is finished and file objects to communicate with the process. > The C library's popen() function, on which this class is based, > provides a means to open a file and connect it to the standard steams > of a subprocess, making it more closely analogous to what the Popen > class does/provides. As such, "Popen" is a better name to describe > this object than "subprocess" would be. Is strongly disagree. The class provides an interface to start and communicate with a `Subprocess`. Instances stand for processes. With your reasoning the `file` type should be called `open`. Ciao, Marc 'BlackJack' Rintsch From george.sakkis at gmail.com Thu Sep 4 12:53:21 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 4 Sep 2008 09:53:21 -0700 (PDT) Subject: Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ? References: <3f0d61c40809040357l7d8f1b23l4c751dbf4cb0adaa@mail.gmail.com> <mailman.478.1220526604.3487.python-list@python.org> Message-ID: <1494118c-d183-48c4-b91f-af8c8480b189@a8g2000prf.googlegroups.com> On Sep 4, 7:09?am, "Marco Bizzarri" <marco.bizza... at gmail.com> wrote: > Sorry... pressed enter but really didn't want to. > > As I said, let's say I have a class > > class A: > ? ? def __init__(self): > ? ? ? ? ?self.x = None > > Python makes the decision to allow the developers to directly access > the attribute "x", ?so that they can directly write: "a.x = 1", or > whatever; this has for me the unfortunate side effect that if I write, > for example "a.y = 1", when I really wanted to write "a.x = 1" no one > cares about it, and I'm unable to spot this error until later. > > Of course, I know that while I'm fresh, I've a good knowledge of the > code, and anything else, I will be able to avoid such stupid errors; > however, I'm afraid of the times when I'm tired, when I have to put my > hands on the code of someone else, and so on. So what happens in Java (or any language for that matter) if there are indeed two attributes x and y with the same type and you mistype the one for the other ? Or if you meant to write x-y instead of y-x ? When coding tired or on someone's else code, stupid errors are the ones you should worry the least about. George From hniksic at xemacs.org Tue Sep 16 06:05:51 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 12:05:51 +0200 Subject: Is 'x' an instance of a new-style class? References: <f568f4d9-b179-4ef1-9688-fcd8cb5ef641@d1g2000hsg.googlegroups.com> <mailman.1102.1221557922.3487.python-list@python.org> Message-ID: <878wts76dc.fsf@mulj.homelinux.net> "Gabriel Genellina" <gagsl-py2 at yahoo.com.ar> writes: > En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS <schaefer.mp at gmail.com> > escribi?: > >> I've seen the question raised several times here, but apparently never >> answered. Since PyInstance_Check returns False for new-style class >> instances, is there a standard procedure for testing this using the C- >> Api? >> >> I would greatly appreciate some help with this. > > In Python you would write isinstance(x, object). It will return True for all Python objects (except perhaps those that fiddle with metaclasses), not only for instances of new-style classes. >>> isinstance([], object) True >>> isinstance((), object) True >>> isinstance(list, object) True >>> isinstance(type, object) True I don't think there is a good way to check if something is a new-style class instance. The whole point of new-style classes was removing the distinction between classes and types. The distinction is now so well removed that it's hard to find it when you need it. A better question for OP is *why* he needs to distinguish between instances of new-style classes and other objects. From xpahos at gmail.com Thu Sep 4 10:42:47 2008 From: xpahos at gmail.com (phasma) Date: Thu, 4 Sep 2008 07:42:47 -0700 (PDT) Subject: Python and Cyrillic characters in regular expression Message-ID: <0680a82c-2b69-4dc9-bd1a-27e5214dbc4c@z6g2000pre.googlegroups.com> Hi, I'm trying extract all alphabetic characters from string. reg = re.compile('(?u)([\w\s]+)', re.UNICODE) buf = re.match(string) But it's doesn't work. If string starts from Cyrillic character, all works fine. But if string starts from Latin character, match returns only Latin characters. Please, help. From dblubaugh at belcan.com Mon Sep 29 19:20:20 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Mon, 29 Sep 2008 19:20:20 -0400 Subject: Is Pyperl still active ?? In-Reply-To: <27CC3060AF71DA40A5DC85F7D5B70F380521CBB0@AWMAIL04.belcan.com> References: <27CC3060AF71DA40A5DC85F7D5B70F380521CBB0@AWMAIL04.belcan.com> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38053D9212@AWMAIL04.belcan.com> To All, I was wondering if Pyperl is still active?? It appears as though it may very well be no longer active at this time!!! Is this correct?? Thanks, David Blubaugh This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From sniipe at gmail.com Tue Sep 2 04:22:20 2008 From: sniipe at gmail.com (sniipe at gmail.com) Date: Tue, 2 Sep 2008 01:22:20 -0700 (PDT) Subject: How to print first(national) char from unicode string encoded inutf-8? References: <513c6011-c126-45cb-90cc-acc322c168c7@m44g2000hsc.googlegroups.com><mailman.330.1220274652.3487.python-list@python.org><7427d257-6cb1-471a-8201-8507590e67a9@25g2000hsx.googlegroups.com> <mailman.331.1220276398.3487.python-list@python.org> <iKednf5sStIbJiHVnZ2dnUVZ_sGdnZ2d@comcast.com> <aaf6e20b-efee-401d-8a94-85f1f2d2c79e@c65g2000hsa.googlegroups.com> Message-ID: <b72f7bcc-5791-4ed5-96d4-99b8a8b283ed@m36g2000hse.googlegroups.com> On 2 Wrz, 10:17, sni... at gmail.com wrote: > On 2 Wrz, 06:05, "Mark Tolonen" <M8R-yft... at mailinator.com> wrote: > > > > > "Marco Bizzarri" <marco.bizza... at gmail.com> wrote in message > > >news:mailman.331.1220276398.3487.python-list at python.org... > > > > On Mon, Sep 1, 2008 at 3:25 PM, <sni... at gmail.com> wrote: > > > >> When I do ${urllib.unquote(c.user.firstName)} without encoding to > > >> latin-1 I got different chars than I will get: no ?ukasz but ? ukasz > > >> -- > > >>http://mail.python.org/mailman/listinfo/python-list > > > > That's crazy. "string".encode('latin1') gives you a latin1 encoded > > > string; latin1 is a single byte encoding, therefore taking the first > > > byte should be no problem. > > > > Have you tried: > > > > urlib.unquote(c.user.firstName)[0].encode('latin1') or > > > > urlib.unquote(c.user.firstName)[0].encode('utf8') > > > > I'm assuming here that the urlib.unquote(c.user.firstName) returns an > > > encodable string (which I'm absolutely not sure), but if it does, this > > > should take the first 'character'. > > > The OP stated that the original string was "encoded in UTF-8 and > > urllib.quote()", so after urllib.unquote the string is in UTF-8 format. > > This must be decoded into a Unicode string before removing the first > > character: > > > urllib.unquote(c.user.firstName).decode('utf-8')[0] > > > The next problem is that the character in the OP's example string '?' is not > > present in the latin-1 encoding, but using utf-8 encoding demonstrates that > > the full two-byte UTF-8 encoded character is collected: > > > >>> import urllib > > >>> name = urllib.quote(u'?ukasz'.encode('utf-8')) > > >>> name > > '%C5%81ukasz' > > >>> urllib.unquote(name).decode('utf-8')[0].encode('utf-8') > > '\xc5\x81' > > > -Mark > > @Mark, when I tried urllib.unquote(c.user.firstName).decode('utf-8') > [0].encode('utf-8'), I received this message: > > >> return render('/reports/create_report_step2.mako') > > Module pylons.templating:344 in render > << **cache_args) > return pylons.buffet.render(template_name=template, > fragment=fragment, > format=format, namespace=kargs, > **cache_args) > > >> format=format, namespace=kargs, **cache_args) > Module pylons.templating:229 in render > << log.debug("Rendering template %s with engine %s", > full_path, engine_name) > return engine_config['engine'].render(namespace, > template=full_path, > **options)>> **options) > Module mako.ext.turbogears:49 in render > << info.update(self.extra_vars_func()) > > return template.render(**info) > >> return template.render(**info) > Module mako.template:114 in render > << declared by this template's internal rendering method are > also pulled from the given *args, **data > members. members.""" > return runtime._render(self, self.callable_, args, data) > > def render_unicode(self, *args, **data):>> return > runtime._render(self, self.callable_, args, data) > Module mako.runtime:287 in _render > << context = Context(buf, **data) > context._with_template = template > _render_context(template, callable_, context, *args, > **_kwargs_for_callable(callable_, data)) > return context.pop_buffer().getvalue()>> > _render_context(template, callable_, context, *args, > **_kwargs_for_callable(callable_, data)) > Module mako.runtime:304 in _render_context > << # if main render method, call from the base of the > inheritance stack > (inherit, lclcontext) = _populate_self_namespace(context, > tmpl) > _exec_template(inherit, lclcontext, args=args, > kwargs=kwargs) > else: > # otherwise, call the actual rendering method specified>> > _exec_template(inherit, lclcontext, args=args, kwargs=kwargs) > Module mako.runtime:337 in _exec_template > << error_template.render_context(context, > error=error) > else: > callable_(context, *args, **kwargs)>> callable_(context, > *args, **kwargs) > Module _reports_create_report_step2_mako:57 in render_body > << > context.write(filters.decode.utf8(urllib.unquote(str(c.period.end)))) > context.write(u' + ') > > context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8') > [0].encode('utf-8'))) > > context.write(filters.decode.utf8(urllib.unquote(str(c.user.secondName) > [0:1]))) > context.write(u'</h3>\r\n <input type="hidden" > name="works[]" value="')>> > context.write(filters.decode.utf8(urllib.unquote(c.user.firstName).decode('utf-8') > [0].encode('utf-8'))) > Module encodings.utf_8:16 in decode > << > def decode(input, errors='strict'): > return codecs.utf_8_decode(input, errors, True) > > class IncrementalEncoder(codecs.IncrementalEncoder):>> return > codecs.utf_8_decode(input, errors, True) > <type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode > characters in position 0-1: ordinal not in range(128) ok, I resolved this problem $ {urllib.unquote(str(c.user.firstName)).decode('utf-8')[0]} Could anyone explain me why this code works? From hrishys at yahoo.co.uk Thu Sep 25 07:21:44 2008 From: hrishys at yahoo.co.uk (hrishy) Date: Thu, 25 Sep 2008 11:21:44 +0000 (GMT) Subject: Linq to Python In-Reply-To: <579eb852-031c-4f50-ac64-88ad8d677b05@m73g2000hsh.googlegroups.com> Message-ID: <255010.14702.qm@web27403.mail.ukl.yahoo.com> Hi Thank you very much I appreciate taking the pain to explain this to me. regards Hrishy --- On Thu, 25/9/08, sturlamolden <sturlamolden at yahoo.no> wrote: > From: sturlamolden <sturlamolden at yahoo.no> > Subject: Re: Linq to Python > To: python-list at python.org > Date: Thursday, 25 September, 2008, 12:16 PM > On 25 Sep, 13:08, hrishy <hris... at yahoo.co.uk> wrote: > > > Pardon my ignorance again but id ont see any join in > python or did i miss something ? > > It's more Pythonic to use the syntax of dictionary > lookups. > -- > http://mail.python.org/mailman/listinfo/python-list From dmitrey.kroshko at scipy.org Tue Sep 23 16:34:51 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Tue, 23 Sep 2008 13:34:51 -0700 (PDT) Subject: how to keep a window above all other OS windows? References: <e03ba1b5-c120-45a3-bf27-640f86c35754@2g2000hsn.googlegroups.com> Message-ID: <62cc640e-3526-49f9-ba10-22ff31f094e1@e39g2000hsf.googlegroups.com> On Sep 23, 11:21?pm, dmitrey <dmitrey.kros... at scipy.org> wrote: > Hi all, > how to keep a Tkinter window above all other OS windows (i.e. > including those ones from other programs)? > > Thank you in advance, > Dmitrey I have put [Tkinter] into topic of my message but somehow it has been removed. D. From gogtesuyash at gmail.com Thu Sep 18 02:53:36 2008 From: gogtesuyash at gmail.com (sui) Date: Wed, 17 Sep 2008 23:53:36 -0700 (PDT) Subject: Problem occured while sending mail References: <b7481bed-df0f-4ef7-8fe7-09da5869492f@c22g2000prc.googlegroups.com> <4fe922e4-1623-491b-899c-e9134332fde4@25g2000prz.googlegroups.com> <6jckjhF2llrvU1@mid.individual.net> Message-ID: <2e63873f-ba8f-4519-b30c-9b5da913c64f@w24g2000prd.googlegroups.com> On Sep 17, 8:04 pm, Peter Pearson <ppear... at nowhere.invalid> wrote: > On Wed, 17 Sep 2008 05:28:05 -0700 (PDT), sui <gogtesuy... at gmail.com> wrote: > > On Sep 17, 5:04 pm, sui <gogtesuy... at gmail.com> wrote: > >> this is my code > > >> import sys, os, glob, datetime, time > >> import smtplib > >> ## Parameters for SMTP session > >> port=587 > >> SMTPserver= 'smtp.gmail.com' > >> SMTPuser= '... at gmail.com' > >> pw= 'fill in here' > >> SENDER= SMTPuser > > >> ## Message details > >> FROM= SENDER > >> TO= 'notgm... at a.com' > >> CC=FROM > >> ##RECEIVERS= (TO, CC) ##proper way to send to both TO and CC > >> RECEIVERS= (TO,) ## ignore the CC address > > >> subject= 'Test 1a' > >> message='*** Email test *** ' > > >> print 'Starting SMTPmailsession on %s as %s ' % > >> (SMTPserver,SMTPuser) > >> session = smtplib.SMTP(SMTPserver,port) > >> session.set_debuglevel(0) # set debug level to 1 to see details > >> session.ehlo(SMTPuser) # say hello > >> session.starttls() # TLS needed > >> session.ehlo(SMTPuser) # say hello again, not sure why > >> session.login(SMTPuser, pw) > > >> ##Create HEADER + MESSAGE > >> HEADER= 'From: %s\r\n' % FROM > >> HEADER= HEADER + 'To: %s\r\n' % TO > >> HEADER= HEADER + 'Cc: %s\r\n' % CC > >> HEADER= HEADER + 'Subject: %s\r\n' % subject > >> BODY= HEADER + '\r\n' + message > >> print BODY > > >> SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) ## send email > > >> session.close() > > >> Now when i run this .py file...as pythonmail.py > >> i can see only statement > >> starting smtpmail......n details > >> then nothing on screen after few minutes or after pressing ctrl +c > >> Traceback (most recent call last): > >> File "mail4.py", line 21, in <module> > >> session = smtplib.SMTP(SMTPserver,port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > >> (code, msg) = self.connect(host, port) > >> File "/usr/local/lib/python2.5/smtplib.py", line 301, in connect > >> self.sock.connect(sa) > >> File "<string>", line 1, in connect > >> or may be conncetion time out > > >> wats the solution for this > > > if i dont press cntrl + c then it shows > > Starting SMTPmailsession on smtp.gmail.com as gogtesuy... at gmail.com > > Traceback (most recent call last): > > File "mail4.py", line 21, in <module> > > session = smtplib.SMTP(SMTPserver,port) > > File "/usr/local/lib/python2.5/smtplib.py", line 244, in __init__ > > (code, msg) = self.connect(host, port) > > File "/usr/local/lib/python2.5/smtplib.py", line 310, in connect > > raise socket.error, msg > > socket.error: (110, 'Connection timed out') > > > plz help me its urgent.....i want to complete it as early as possible > > I pasted your code into a file named temp.py, > and (perhaps superstitiously) added a backslash to this line: > > >> print 'Starting SMTPmailsession on %s as %s ' % > > Here's what it does (long line wrapped manually): > > peter at eleodes:~$ python temp.py > Starting SMTPmailsession on smtp.gmail.com as .... at gmail.com > Traceback (most recent call last): > File "temp.py", line 27, in ? > session.login(SMTPuser, pw) > File "/usr/lib/python2.4/smtplib.py", line 591, in login > raise SMTPAuthenticationError(code, resp) > smtplib.SMTPAuthenticationError: (535, \ > '5.7.1 Username and Password not accepted. Learn more at\n' \ > '5.7.1http://mail.google.com/support/bin/answer.py?answer='\ > '14257 a8sm34686663poa.12') > peter at eleodes:~$ > > This indicates that it got much farther than when you ran it, since > your timeout message comes from the smtplib.SMTP call several lines > before the session.login call. > > As a simple connectivity test, you might see whether you can connect > using telnet: > > peter at eleodes:~$ telnet smtp.gmail.com 587 > Trying 72.14.253.109... > Connected to gmail-smtp.l.google.com. > Escape character is '^]'. > 220 mx.google.com ESMTP m27sm34789033pof.6 > ^]c > > telnet> c > Connection closed. > peter at eleodes:~$ > > -- > To email me, substitute nowhere->spamcop, invalid->net. even i couldnt connect using telnet.... msg comes host is down From uzmanajmal at gmail.com Wed Sep 17 05:55:54 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Wed, 17 Sep 2008 09:55:54 +0000 Subject: File Reading related query Message-ID: <a3158e8b0809170255y6527dc96ta0f7466fd575db8f@mail.gmail.com> Hi., Is there any function for reading a file while ignoring *\n* occuring in the file? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080917/b270a482/attachment-0001.html> From steve at REMOVE-THIS-cybersource.com.au Wed Sep 17 10:55:35 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Sep 2008 14:55:35 GMT Subject: python regex character group matches References: <f44caf830809170627m19b5f4e3qb9fe2fb69ee20afa@mail.gmail.com> <mailman.1170.1221659832.3487.python-list@python.org> Message-ID: <00e11472$0$20331$c3e8da3@news.astraweb.com> On Wed, 17 Sep 2008 15:56:31 +0200, Fredrik Lundh wrote: > Assuming that you want to find runs of \uXXXX escapes, simply use > non-capturing parentheses: > > pat = re.compile(u"(?:\\\u[0-9A-F]{4})") Doesn't work for me: >>> pat = re.compile(u"(?:\\\u[0-9A-F]{4})") UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 5-7: truncated \uXXXX escape Assuming that the OP is searching byte strings, I came up with this: >>> pat = re.compile('(\\\u[0-9A-F]{4})+') >>> pat.search('abcd\\u1234\\uAA99\\u0BC4efg').group(0) '\\u1234\\uAA99\\u0BC4' -- Steven From bignose+hates-spam at benfinney.id.au Tue Sep 30 19:06:08 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Oct 2008 09:06:08 +1000 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> <87zllqqa1i.fsf@benfinney.id.au> <pan.2008.09.30.10.04.18@REMOVE.THIS.cybersource.com.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> <mailman.1766.1222798706.3487.python-list@python.org> Message-ID: <87hc7xqlnj.fsf@benfinney.id.au> Terry Reedy <tjreedy at udel.edu> writes: > Steven D'Aprano wrote: > > We agree that the restriction is artificial, and I think > > irrational (although I'd be interested in hearing the gnuplot > > developers' reasoning before making a final judgment). > > I believe it is a matter of preserving clarity of authorship, just > as is the quoting mechanism we take for granted in posts like this. > If I removed the quote marks above and silently edited what Ben and > you wrote, I might upset someone and certainly could confuse > readers. That, if it were to be prosecuted under law, would be a matter already covered by laws other than copyright: fraud, libel, etc. Note that I consider a work free even if it fails to grant ?the right to distribute misrepresentations of the author's words?, because that act is an exercise of undue power over another person, and so falls outside the limit imposed by the freedoms of others. -- \ ?What is it that makes a complete stranger dive into an icy | `\ river to save a solid gold baby? Maybe we'll never know.? ?Jack | _o__) Handey | Ben Finney From sjmachin at lexicon.net Sun Sep 21 06:52:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 21 Sep 2008 03:52:55 -0700 (PDT) Subject: writeable buffer and struct.pack_into and struct.unpck_from References: <bd9c1d00-2c55-4a29-aa99-c4a2dcd48c29@79g2000hsk.googlegroups.com> <mailman.1311.1221954200.3487.python-list@python.org> <d7f5e34a-6283-4348-aa63-0f1e03437f45@s50g2000hsb.googlegroups.com> Message-ID: <214c1d71-883e-4af7-bd5b-267f0714d873@v39g2000pro.googlegroups.com> On Sep 21, 3:16?pm, Tzury Bar Yochay <Afro.Syst... at gmail.com> wrote: > Thanks Gabriel, > I was missing the information how to create a writable buffer. array.array objects also have the writable buffer nature: >>> import array >>> b = array.array('c', '\0' * 10) >>> b array('c', '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') >>> import struct >>> struct.pack_into('<hhhh', b, 0, 1, 2, -1, -32768) >>> b array('c', '\x01\x00\x02\x00\xff\xff\x00\x80\x00\x00') HTH, John From bignose+hates-spam at benfinney.id.au Tue Sep 9 08:07:24 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 09 Sep 2008 22:07:24 +1000 Subject: Python Installation and Running on Windows Vista References: <4f66ca7b-b495-4b12-bb4c-29b096eb53c9@j22g2000hsf.googlegroups.com> Message-ID: <87fxo9ed4z.fsf@benfinney.id.au> Mchizi_Crazy <silazima at gmail.com> writes: > Please help with issue... What is the issue? What have you tried, what is happening, and what behaviour were you expecting instead? > I heard of compatimbiltity issues and would like clarification. Same here. Can you please clarify what the issue is, as above. -- \ ?There's no excuse to be bored. Sad, yes. Angry, yes. | `\ Depressed, yes. Crazy, yes. But there's no excuse for boredom, | _o__) ever.? ?Viggo Mortensen | Ben Finney From goldnery at gmail.com Mon Sep 1 18:11:01 2008 From: goldnery at gmail.com (Gandalf) Date: Mon, 1 Sep 2008 15:11:01 -0700 (PDT) Subject: encoding References: <1243e22e-2204-426b-887f-94ab1894890b@t54g2000hsg.googlegroups.com> <6i36tkFogbfkU1@mid.uni-berlin.de> Message-ID: <54811a01-b8fe-408b-91cd-8671c5c42697@d77g2000hsb.googlegroups.com> On Sep 1, 11:59?pm, "Diez B. Roggisch" <de... at nospam.web.de> wrote: > Gandalf schrieb: > > > if i want to print utf-8 string i should writre: > > > print u"hello word" > > No, you don't. You write > > print u"hello world".encode("utf-8") > > Read this: > > http://www.reportlab.com/i18n/python_unicode_tutorial.html > > > but what happen if i want to print variable? > > Then you do > > print variable_containing_unicode_object.encode("utf-8") > > Diez thanks From circularfunc at yahoo.se Sat Sep 13 04:06:22 2008 From: circularfunc at yahoo.se (cnb) Date: Sat, 13 Sep 2008 01:06:22 -0700 (PDT) Subject: Profiling, sum-comprehension vs reduce Message-ID: <361dddf5-91c5-490e-ade4-149b88364183@e39g2000hsf.googlegroups.com> This must be because of implementation right? Shouldn't reduce be faster since it iterates once over the list? doesnt sum first construct the list then sum it? ----------------------- >>> ================================ RESTART ================================ >>> reduce with named function: 37.9864357062 reduce with nested, named function: 39.4710288598 reduce with lambda: 39.2463927678 sum comprehension: 25.9530121845 >>> ================================ RESTART ================================ >>> reduce with named function: 36.4529584067 reduce with nested, named function: 37.6278529813 reduce with lambda: 38.2629448715 sum comprehension: 26.0197561422 >>> from timeit import Timer def add(x,y): return x+y def rednamed(lst): return reduce(add, lst) def rednn(lst): def add2(x,y): return x+y return reduce(add2, lst) def redlambda(lst): return reduce(lambda x,y:x+y, lst) def com(lst): return sum(x for x in lst) s = xrange(101) t1 = Timer('rednamed(s)', 'from __main__ import rednamed, s') t2 = Timer('rednn(s)', 'from __main__ import rednn, s') t3 = Timer('redlambda(s)', 'from __main__ import redlambda, s') t4 = Timer('com(s)', 'from __main__ import com, s') print "reduce with named function: ", t1.timeit() print "reduce with nested, named function: ", t2.timeit() print "reduce with lambda: ", t3.timeit() print "sum comprehension: ", t4.timeit() --------------------------------------- also, using range instead of xrange doesnt seem to generate a performance-penalty: >>> reduce with named function: 36.7560729087 reduce with nested, named function: 38.5393266463 reduce with lambda: 38.3852953378 sum comprehension: 27.9001007111 >>> From tjreedy at udel.edu Tue Sep 30 04:21:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 Sep 2008 04:21:13 -0400 Subject: Comparing float and decimal In-Reply-To: <op.uh9wgumox6zn5v@gabriel2.softlabbsas.com.ar> References: <mailman.1400.1222168827.3487.python-list@python.org> <48d8e810$0$4541$9b622d9e@news.freenet.de> <51455e44-fa24-4f6a-a0e4-fd12898620c9@k13g2000hse.googlegroups.com> <op.uh9wgumox6zn5v@gabriel2.softlabbsas.com.ar> Message-ID: <gbsnhl$846$1@ger.gmane.org> Gabriel Genellina wrote: > En Thu, 25 Sep 2008 08:02:49 -0300, Mark Dickinson <dickinsm at gmail.com> > escribi?: >> On Sep 23, 1:58 pm, Robert Lehmann <stargam... at gmail.com> wrote: >>> I don't see why transitivity should apply to Python objects in general. >> >> Hmmm. Lack of transitivity does produce some, um, interesting >> results when playing with sets and dicts. Here are sets s and >> t such that the unions s | t and t | s have different sizes: >> >>>>> from decimal import Decimal >>>>> s = set([Decimal(2), 2.0]) >>>>> t = set([2]) >>>>> len(s | t) >> 2 >>>>> len(t | s) >> 1 > > Ouch! > >> This opens up some wonderful possibilities for hard-to-find bugs... > > And I was thinking all this thread was just a theoretical question > without practical consequences... To explain this anomaly more clearly, here is a recursive definition of set union. if b: a|b = a.add(x)|(b-x) where x is arbitrary member of b else: a|b = a Since Python only defines set-set and not set-ob, we would have to subtract {x} to directly implement the above. But b.pop() subtracts an arbitrary members and returns it so we can add it. So here is a Python implementation of the definition. def union(a,b): a = set(a) # copy to preserve original b = set(b) # ditto while b: a.add(b.pop()) return a from decimal import Decimal d1 = Decimal(1) fd = set((1.0, d1)) i = set((1,)) print(union(fd,i)) print(union(i,fd)) # prints {1.0, Decimal('1')} {1} This is a bug in relation to the manual: "union(other, ...) set | other | ... Return a new set with elements from both sets." Transitivity is basic to logical deduction: equations: a == b == c ... == z implies a == z implications: (a implies b) and (b implies c)implies (a implies c) The latter covers syllogism and other deduction rules. The induction part of an induction proof of set union commutivity is a typical equality chain: if b: a | b = a.add(x)| b-x for x in b # definition for non-empty b = b-x | a.add(x) # induction hypothesis = (b-x).add(x) | a.add(x)-x # definition for non-empty a = b | a.add(x)-x # definitions of - and .add if x not in a: = b | a # .add and - if x in a: = b | a-x # .add and - = b.add(x) | a-x # definition of .add for x in b = b | a # definition for non-empty a = b | a # in either case, by case analysis By transitivity of =, a | b = b | a ! So where does this go wrong for our example? This shows the problems. >>> fd - i set() This pretty much says that 2-1=0, or that 2=1. Not good. The fundamental idea of a set is that it only contains something once. This definition assumes that equality is defined sanely, with the usual properties. So, while fd having two members implies d1 != 1.0, the fact that f1 == 1 and 1.0 == 1 implies that they are really the same thing, so that d1 == 1.0, a contradiction. To put this another way: The rule of substitution is that if E, F, and G are expressions and E == F and E is a subexpression of G and we substitute F for E in G to get H, then G == H. Again, this rule, which is a premise of all formal expressional systems I know of, assumes the normal definition of =. When we apply this, fd == {f1, 1.0} == {1,1.0} == {1} == i But Python says >>> fd == i False Conclusion: fd is not a mathematical set. Yet another anomaly: >>> f = set((1.0,)) >>> i == f True >>> i.add(d1) >>> f.add(d1) >>> i == f False So much for "adding the same thing to equals yields equals", which is a special case of "doing the same thing to equals, where the thing done only depends on the properties that make the things equal, yields equals." And another >>> d1 in i True >>> 1.0 in i True >>> fd <= i False Manual: "set <= other Test whether every element in the set is in other" I bet Python first tests the sizes because the implementer *assumed* that every member of a larger set could not be in a smaller set. I presume the same assumption is used for equality testing. Or Manual: "symmetric_difference(other) set ^ other Return a new set with elements in either the set or other but not both." >>> d1 in fd True >>> d1 in i True >>> d1 Decimal('1') >>> fd ^ i {Decimal('1')} If no one beats me to it, I will probably file a bug report or two, but I am still thinking about what to say and to suggest. Terry Jan Reedy From george.sakkis at gmail.com Fri Sep 26 09:47:14 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 26 Sep 2008 06:47:14 -0700 (PDT) Subject: how to search multiple textfiles ? References: <mailman.1536.1222436146.3487.python-list@python.org> Message-ID: <bf1664da-1e2e-48c8-a108-66b0fb457e43@k30g2000hse.googlegroups.com> On Sep 26, 9:35 am, Stef Mientki <s.mien... at ru.nl> wrote: > hello, > > I want to search multiple textfiles (python source files) for a specific > word. > I can find all files, open them and do a search, > but I guess that will be rather slow. > > I couldn't find any relevant information through google. > > Does anyone know of a search library that performs this task fast ? > > If it indeed only concerns py-files, > is there another way of searching words ? > ( I could imagine that such a "py-only-search" would have benefits, > because you could set a flag to see the words in comment yes or no ) If you're on *nix platform, you can use: $ find -name "*py" | xargs egrep "\bword\b" HTH, George From benlindelof at gmail.com Mon Sep 8 20:02:14 2008 From: benlindelof at gmail.com (benlindelof at gmail.com) Date: Mon, 8 Sep 2008 17:02:14 -0700 (PDT) Subject: Coming from .NET and VB and C References: <d20e9c18-9607-4746-a34a-c37ef6c22aef@d45g2000hsc.googlegroups.com> <6vmdncQnBO4JkSLVnZ2dnUVZ_orinZ2d@earthlink.com> <mailman.471.1220523953.3487.python-list@python.org> <48bfc4e4$0$13232$426a74cc@news.free.fr> <mailman.479.1220528581.3487.python-list@python.org> Message-ID: <bfe480a0-2523-4a16-953c-ecbae4271c11@t54g2000hsg.googlegroups.com> BigTable looks great! There's a 3% performance hit for these types of databases. However it makes up for it in other ways. "Dive Into Python" seems to suggest there is less busy work, but I am still looking into the GUI components of Python. Say, a grid of 10x10 tiles of PNGs. _______________________________________________________________________________ > have no preference with MySQL or SQL, stored procedures or ad-hoc > queries. Please note: MySQL is specific relational database management system (RDBMs), which uses a dialect of structured query language (SQL). SQL by itself is just a semi-standardized query language -- and can technically be used to access non-relational DBMS (if any such are still in use), though the query processor would be a pain to program (map a relational join into a hierarchical DBMS schema? ugh). > SO, I'm interested in using my Google App space (free 500MB) to > develop a quick database application. Using Python. I found "Dive > Into Python" which I will be reading shortly. So one question: what RDBMs are supported in that space? -- Wulfraed Dennis Lee Bieber KD6MOG From python-url at phaseit.net Tue Sep 16 09:43:58 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Tue, 16 Sep 2008 13:43:58 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Sep 16) Message-ID: <gaod6u$tle$1@lairds.us> QOTW: "There is no point in creating new hardware without new software." - Niklaus Wirth http://www.modulaware.com/mdlt52.htm The first Release Candidate for Python 2.6 is out: http://groups.google.com/group/comp.lang.python/browse_thread/thread/bdf349528605e27f/ Abstract base classes, pros and cons: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/ Converting dictionary accesses from Perl to Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c70e09497db3c7f4/ Naming style: should a library wrapping foreign code keep the original names or follow PEP8? http://groups.google.com/group/comp.lang.python/browse_thread/thread/42f6a6c097fc74cb/ Profiles of sum() and reduce(): http://groups.google.com/group/comp.lang.python/browse_thread/thread/78a31fe094f79f2b/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From gioco at nekhem.com Tue Sep 2 12:04:18 2008 From: gioco at nekhem.com (Corrado Gioannini) Date: Tue, 2 Sep 2008 18:04:18 +0200 Subject: email.Message problem Message-ID: <20080902160417.GA20438@zephyr> Hi all, i know i'm probably going to ask a very silly question, but i can't figure out where i'm doing wrong just reading the docs. trying to build and send a mail message using the email.* modules (with python 2.5). a simplified version of my script that breaks is this: mailtest.py ---------------------------------------------------------------------- # coding: ISO-8859-15 import os, mimetypes, smtplib, base64, StringIO import email.message, email.header, email.generator messg = email.message.Message() messg.set_charset('ISO-8859-15') messg['To'] = 'email.x at mydomain' messg['From'] = 'email.y at mydomain' messg['Subject'] = email.header.Header("This is a test.", 'ISO-8859-15') messg["Message-ID"] = email.Utils.make_msgid() messg["Content-type"] = "Multipart/mixed" messg.preamble = "Mime test\n" pl = email.Message.Message() pl.add_header("Content-type", "text/plain; charset=ISO-8859-15") pl.add_header("Content-transfer-encoding", "8bit") pl.set_payload("Body text goes here.\n", 'ISO-8859-15') messg.attach(pl) messg.as_string() ---------------------------------------------------------------------- running it gives: Traceback (most recent call last): File "mailtest.py", line 22, in <module> messg.as_string() File "/usr/lib/python2.5/email/message.py", line 131, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/lib/python2.5/email/generator.py", line 84, in flatten self._write(msg) File "/usr/lib/python2.5/email/generator.py", line 109, in _write self._dispatch(msg) File "/usr/lib/python2.5/email/generator.py", line 135, in _dispatch meth(msg) File "/usr/lib/python2.5/email/generator.py", line 175, in _handle_text raise TypeError('string payload expected: %s' % type(payload)) TypeError: string payload expected: <type 'list'> the real case is just a little more complex: i have to attach some files and then send the message with smtplib to a list of recipients. no problems when attaching files etc., but when i try to get the message value 'flattened' to pass it to smtplib i always get an error as above. it seems to work only if i don't use .attach but just .set_payload in the main message, but in this case i cannot attach the extra files (or maybe i'm wrong in this?) any help (or pointers to docs/examples etc) are very appreciated :-) 10x, C. -- Quando l'infanzia muore i suoi cadaveri sono chiamati adulti. (B. Aldiss) From fredrik at pythonware.com Mon Sep 22 13:25:26 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 22 Sep 2008 19:25:26 +0200 Subject: Regex Help In-Reply-To: <E2E744D6A24F4889AE41F847706FF840@office.ipglobal.net> References: <mailman.11779.1222099792.3486.python-list@python.org> <E2E744D6A24F4889AE41F847706FF840@office.ipglobal.net> Message-ID: <gb8ke7$ick$1@ger.gmane.org> Support Desk wrote: > the code I am using is > > regex = r'<a href=["|\']([^"|\']+)["|\']>' that's way too fragile to work with real-life HTML (what if the link has a TITLE attribute, for example? or contains whitespace after the HREF?) you might want to consider using a real HTML parser for this task. > page_text = urllib.urlopen('http://somesite.com') > page_text = page_text.read() > > links = re.findall(regex, text, re.IGNORECASE) the RE looks fine for the subset of all valid A elements that it can handle, though. got any examples of pages where you see that behaviour? </F> From martindemello at gmail.com Thu Sep 4 16:08:38 2008 From: martindemello at gmail.com (Martin DeMello) Date: Thu, 4 Sep 2008 13:08:38 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() References: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> <mailman.498.1220557317.3487.python-list@python.org> <e97d94df-8da5-4ac4-8029-abf90529c500@z11g2000prl.googlegroups.com> <3a59a1d4-4478-49e5-8316-9d27c09f55b0@m3g2000hsc.googlegroups.com> Message-ID: <ce09b0fc-6a51-4bdd-85a4-2f55dd220747@w39g2000prb.googlegroups.com> On Sep 4, 1:04?pm, castironpi <castiro... at gmail.com> wrote: > > Random access isn't supported by the defined interface. ?You can make > it more convenient, though. Thanks. I wasn't looking for random access, just wondering what the cleanest way to implement items = Queue.get_all() was. Your code should work nicely for that. martin From andyhume at gmail.com Sun Sep 7 17:51:32 2008 From: andyhume at gmail.com (andyhume at gmail.com) Date: Sun, 7 Sep 2008 14:51:32 -0700 (PDT) Subject: Updating python dictionary Message-ID: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Hello... I have a dict of key/values and I want to change the keys in it, based on another mapping dictionary. An example follows: MAPPING_DICT = { 'a': 'A', 'b': 'B', } my_dict = { 'a': '1', 'b': '2' } I want the finished my_dict to look like: my_dict = { 'A': '1', 'B': '2' } Whereby the keys in the original my_dict have been swapped out for the keys mapped in MAPPING_DICT. Is there a clever way to do this, or should I loop through both, essentially creating a brand new dict? Cheers, Andy. From almar.klein at gmail.com Mon Sep 15 04:57:23 2008 From: almar.klein at gmail.com (Almar Klein) Date: Mon, 15 Sep 2008 10:57:23 +0200 Subject: Python IDEs with F5 or hotkey shell interaction In-Reply-To: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> References: <9b3b04f3-5377-49b4-9f34-2e25c371ef5e@l42g2000hsc.googlegroups.com> Message-ID: <cc38d75f0809150157i3cb9fb0foed89be6efb343b9b@mail.gmail.com> > ... <http://wiki.python.org/moin/PythonEditors> > but few if any alternatives seem to have all of the 'interactive' > power of IDLE?- not only a run program in a python shell hotkey but a > persistent, after-a-run memory state can be accessed for interactive > coding and exploration-- i.e. how IDLE works ! I felt the same. Coming from Matlab, I missed the interactive behaviour. I found IPython with a proper editor (I really liked PyPE) a nice solution. Still, I found it awkward having to use two programs and not having code completion in my editor (I mean the editor not knowing what names are present in my python session.) Therefore, I started creating an editor with an interactive shell in it in which you can run (parts of) your code and have a persisten session. It's not finished yet, but I'm quite happy with the result so far. It starts python in a subprocess in much the same way PyPE does. I actually "stole" code from PyPE as a base for multiple things (thanks Josiah :) ). Almar -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080915/23d18a36/attachment-0001.html> From martindemello at gmail.com Thu Sep 4 15:26:51 2008 From: martindemello at gmail.com (Martin DeMello) Date: Thu, 4 Sep 2008 12:26:51 -0700 (PDT) Subject: Not fully understanding the role of Queue.task_done() Message-ID: <2105e362-8420-41ca-871e-af7daefea03c@b30g2000prf.googlegroups.com> I'm writing a cluster monitor, that collects information from a set of machines and logs it to a database In the interests of not hammering the db unnecessarily, I'm considering the following 1. A series of independent "monitor" threads that collect information over TCP from the cluster of machines, and write it to a queue 2. A "logger" thread that empties the queue every second or so and inserts the collected information to the db via a single insert statement Reading up on python's built in Queue class, though, it seems oriented towards "job queues", with a two-step dequeue operation (get() and task_done()). I'm worried that this would make it too heavyweight for my application. Is ther documentation somewhere on what exactly task_done() does, and whether I can disable the tracking of a job once it's removed from the queue? The python docs for the Queue module were a bit light. martin From gagsl-py2 at yahoo.com.ar Wed Sep 3 05:58:16 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 03 Sep 2008 06:58:16 -0300 Subject: sys.stdin on windows References: <7e9916be-4755-493b-aba9-7e6666665a9b@s20g2000prd.googlegroups.com> Message-ID: <op.ugwgnenkx6zn5v@gabriel2.softlabbsas.com.ar> En Wed, 03 Sep 2008 06:16:03 -0300, zugnush at gmail.com <zugnush at gmail.com> escribi?: > I often grep particular patterns out of large logfiles and then > pipeline the output to sort and uniq -c > I thought today to knock up a script to do the counting in a python > dict. > > This seems work in linux > > $ cat count.py > #!/usr/bin/env python > import sys > from collections import defaultdict > accumulator=defaultdict(int) > for line in sys.stdin.readlines(): > accumulator[line.strip()]+=1 > print "contents,count" > for key in accumulator.keys(): > print key,",",accumulator[key] > > $ cat test | ./count.py > contents,count > , 1 > 23 , 1 > 1 , 1 > 3 , 2 > 2 , 2 > 5 , 3 > > When I try to run the same thing on windows I get > IOError: [Error 9] Bad file descriptor > > How can I make this more windows friendly? Explicitely invoking the interpreter worked for me. That is, these two commands worked fine: type test.txt | python count.py python count.py < test.txt But I cannot explain *why* it doesn't work the other way. -- Gabriel Genellina From bearophileHUGS at lycos.com Fri Sep 5 20:00:04 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 17:00:04 -0700 (PDT) Subject: indices question References: <g9sgda$e9h$1@adenine.netfront.net> Message-ID: <cc9bc4bf-412e-44e9-ba6d-76352ec08fd4@26g2000hsk.googlegroups.com> Lanny: > ... > varcc = raw_input > grid[varc] = 'O' > ... > Why can't I put a varible thats an integer instead? 'varcc' and 'varc' are different names. 'raw_input' isn't a function call, you may want to turn that into a function call. varc isn't an integer, you may have to convert it to integer first, using int(), because Python lists aren't like Lua ones, they are represented with a sequence of cells, and an integer number is used to denote what cells you want. Note that the cell must already exists before accessing its contents. Maybe you want to use an associative array instead, named 'dict' in Python, that allows you freedom in the type of the keys and allows you to create cells on the fly. Surely my answer isn't enough to solve your problems, but it may give you a starting point. Bye, bearophile From tjreedy at udel.edu Sat Sep 13 14:08:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 13 Sep 2008 14:08:29 -0400 Subject: Checking the boolean value of a collection In-Reply-To: <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> References: <mailman.921.1221227464.3487.python-list@python.org> <6ivbfvFnfucU1@mid.uni-berlin.de> <3f0d61c40809130656j70c1fc20s7b7369825e52ae3d@mail.gmail.com> Message-ID: <gagviq$i9v$1@ger.gmane.org> Marco Bizzarri wrote: > On Fri, Sep 12, 2008 at 4:09 PM, Diez B. Roggisch <deets at nospam.web.de> wrote: > >> You should also consider using PEP8 style naming. >> >> >> Diez > > > class FolderInUse: > > def __init__(self, core): > self.core = core > > def true_for(self, archivefolder): > return any([instance.forbid_to_close(archivefolder) for instance in > self.core.active_outgoing_registration_instances()]) > > Is this any better? Yes. Now I can read it to suggest shorter names (I agree with FL here). I would consider 'outgoing' for 'a_o_r_i' and perhaps 'no_close' or 'stay_open' or suggestions below for 'f_t_c' > The true_for name does not satisfy me a lot... > maybe because it is too similar to True. Does one of 'locked', 'forbidden', 'untouchable' express the essence of the condition being tested? I would consider using the same adjective to name the test on instances and the collection of instances, or maybe 'x' and 'any_x'. Anyway, I'm trying a good > naming so that code is readable, like: > > specification = FolderInUse(core) > > if specification.true_for(folder): > ... > > Any thought about this? tjr From bmihelac at gmail.com Fri Sep 12 11:30:18 2008 From: bmihelac at gmail.com (Bojan Mihelac) Date: Fri, 12 Sep 2008 08:30:18 -0700 (PDT) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> <mailman.930.1221232940.3487.python-list@python.org> Message-ID: <005ca418-9e1a-424b-b4d4-823427584424@x35g2000hsb.googlegroups.com> On Sep 12, 5:21?pm, Christian Heimes <li... at cheimes.de> wrote: > Bojan Mihelac wrote: > > I guess A class not yet exists in line 4. Is it possible to achive > > adding dynamic attributes without using exec? > > Correct, the class doesn't exist until the end of the class body. You > can either do it outside the class definition or you can use a metaclass. > > Christian thanks, can you give example on using a metaclass? From fredrik at pythonware.com Sat Sep 27 07:36:10 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 Sep 2008 13:36:10 +0200 Subject: Using the 'with' statement with cStringIO objects In-Reply-To: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> References: <5fa7a7b2-c77f-4c80-b7ca-af98c7a2f367@i20g2000prf.googlegroups.com> Message-ID: <gbl5rd$gjv$1@ger.gmane.org> peppergrower wrote: > teststring='this is a test' > > with cStringIO.StringIO(teststring) as testfile: > pass umm. what exactly do you expect that code to do? </F> From tjreedy at udel.edu Mon Sep 8 23:21:04 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 08 Sep 2008 23:21:04 -0400 Subject: universal unicode font for reportlab In-Reply-To: <ga4nq3$4kh$1@rumours.uwaterloo.ca> References: <mailman.674.1220863917.3487.python-list@python.org> <87ej3uk4e1.fsf@Kimiko.i-did-not-set--mail-host-address--so-tickle-me> <48C55E7B.9090807@shopzeus.com> <mailman.705.1220907160.3487.python-list@python.org> <ga4nq3$4kh$1@rumours.uwaterloo.ca> Message-ID: <ga4q30$5nu$1@ger.gmane.org> Ross Ridge wrote: > Terry Reedy <tjreedy at udel.edu> wrote: >> My OpenOffice on WinXP uses a unicode font, I believe Lucida Sans >> Unicode, that seems to cover the entire BMP. > > Lucida Sans Unicode only covers a small subset of Unicode. It may seem > to cover a wider range because Windows (and possibly OpenOffice) will > automatically substitute characters from other fonts, if necessary. Sorry, I posted the wrong name. Ariel Unicode MS is the one that seems pretty complete. >> I don't know whether it was already installed or installed by OO or >> how one would get to it to extract it. > > It's a standard Windows font. From the MS, I would guess that is a Windows font too ;-). From lists at cheimes.de Mon Sep 8 05:28:12 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 08 Sep 2008 11:28:12 +0200 Subject: Test if list contains another list In-Reply-To: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> Message-ID: <ga2r78$lj$1@ger.gmane.org> mathieu wrote: > Hi there, > > I am trying to write something very simple to test if a list > contains another one: > > a = [1,2,3] > > b = [3,2,1,4] > > but 'a in b' returns False. How do I check that a is indeed contained > in b ? Use sets: >>> a = [1,2,3] >>> b = [3,2,1,4] >>> set(a).issubset(set(b)) True Christian From tchendrix at gmail.com Wed Sep 24 16:17:38 2008 From: tchendrix at gmail.com (Bobby Roberts) Date: Wed, 24 Sep 2008 13:17:38 -0700 (PDT) Subject: empty csv file attachments Message-ID: <200563c8-a4d1-45db-aaa1-63f885851b76@s50g2000hsb.googlegroups.com> hi group. I'm new to python but a veteran at programming. This one has me stumped. I have a simple contact form which the user fills out. The email is sent to the site user as well and it is delivered with the content in the body of the email as well in nice order. I have modified my code to also send the content as a csv attachment. On the server, the file is perfectly generated with content. The attachment, however, is completely blank. Any ideas what that could be? My code snippet is shown below: if int(attachmenttype)==2 or int(attachmenttype)==3: for field in ctx.request.field_names(): if field=='last_name': myfilename=ctx.request.field_value(field)+'.txt' if myfilename=='': myfilename='tempfile.txt' mypath= mynewfilepath + '/' + myfilename f=open(mypath, 'w') mynewstring='' counter=0 for field in ctx.request.field_names(): if field != 'inquiry_required': mynewstring=mynewstring + field +',' if mynewstring[-1]==',': mynewstring=mynewstring[0:len(mynewstring)-1] f.write(mynewstring) f.write ('\n') mynewstring='' counter=1 for field in ctx.request.field_names(): fielddata=ctx.request.field_value(field) if counter==1: dummydata=0 else: mynewstring=mynewstring + '"' + fielddata.replace('"','') + '",' counter = counter + 1 if mynewstring[-1]==',': mynewstring=mynewstring[0:len(mynewstring)-1] f.write(mynewstring) f.write('\n') f.close attachments.append('/'.join((ctx.request.library, myfilename))) [snip... sends email just after this] any ideas? From circularfunc at gmail.com Wed Sep 10 06:52:24 2008 From: circularfunc at gmail.com (process) Date: Wed, 10 Sep 2008 03:52:24 -0700 (PDT) Subject: which of these 2 quicksorts is faster? References: <f585f9cd-723a-49d2-8af2-223a8ef625a8@c65g2000hsa.googlegroups.com> <mailman.767.1221042609.3487.python-list@python.org> Message-ID: <5fd41cf4-59c6-4d4d-bf4d-681e5bc88e6f@79g2000hsk.googlegroups.com> On Sep 10, 12:29?pm, Fredrik Lundh <fred... at pythonware.com> wrote: > process wrote: > > qsort can handle bigger lists it seems, making less recursive calls > > before finishing(quicksort blows the stack when sorting > > range(100,-1000,-1). > > qsort does more work though right? is there a way to speed up that? > > > is the built-in sort not defined recursively? > > what makes you think you can write a better sort than the built-in > algorithm by typing in some toy quick-sort implementations from a > "sorting for dummies" article? > > </F> Where did I write that I was trying to do that? I am merely trying to learn. Get some social skills dude. From execrable at gmail.com Wed Sep 10 12:31:35 2008 From: execrable at gmail.com (B) Date: Wed, 10 Sep 2008 09:31:35 -0700 Subject: dict slice in python (translating perl to python) In-Reply-To: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Message-ID: <HDSxk.1411$ZY5.32@newsfe02.iad> for a long list, you could try: result = [mydict[k] for k in mydict] or [mydict[k] for k in mydict.keys()] or [mydict[k] for k in mydict.iterkeys()] this won't give you the same order as your code though, if you want them sorted you can use the sorted function: [mydict[k] for k in sorted(x)] (or sorted(x.etc)) hofer wrote: > Hi, > > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; > > How do I translate the second line in a similiar compact way to > python? > > Below is what I tried. I'm just interested in something more compact. > > mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } > # first idea, but still a little too much to type > [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] > > # for long lists lazier typing,but more computational intensive > # as split will probably be performed at runtime and not compilation > time > [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] > > print "%s\n%s\n%s" %(v1,v2,v3) > > > > thanks for any ideas > From lists at cheimes.de Mon Sep 8 15:03:48 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 08 Sep 2008 21:03:48 +0200 Subject: exit() In-Reply-To: <20080908134608759530.9d832e42@mac.com> References: <20080908134608759530.9d832e42@mac.com> Message-ID: <ga3suk$tkv$1@ger.gmane.org> Gary Robinson wrote: > In Python 2.5.2, I notice that, in the interpreter or in a script, I can exit with: > > exit() The exit callable is defined in the site module. Check out site.py! It shouldn't be used in code. It was added to help newbies to 'escape' from an interactive Python shell. Christian From steve at REMOVE-THIS-cybersource.com.au Fri Sep 26 11:13:29 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Sep 2008 15:13:29 GMT Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> Message-ID: <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> On Fri, 26 Sep 2008 06:31:40 -0500, skip wrote: > I took over spam filter management for the python.org mailing lists a > couple months ago and made a few changes to the way the spam filter is > trained. Things seem to be at a reasonable level as far as I can tell (I > see a few spams leak through each day), though I wasn't actively reading > comp.lang.python/python-list at python.org before I took over the task, so > I have nothing to compare with. Does the level of spam leaking through > the filter now seem excessive? Is it more or less than in June and > July? I don't have any objective numbers, but subjectively it seems to me that the number of spams is significantly higher, but not so high as to be a major nuisance. -- Steven From bdesth.quelquechose at free.quelquepart.fr Wed Sep 24 13:31:44 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 Sep 2008 19:31:44 +0200 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <gbe0kd$qh9$1@rumours.uwaterloo.ca> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <JcKdndouSNGG10fVnZ2dnUVZ_hCdnZ2d@posted.visi> <gbdmgh$nd0$1@rumours.uwaterloo.ca> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <gbe0kd$qh9$1@rumours.uwaterloo.ca> Message-ID: <48da956c$0$1269$426a74cc@news.free.fr> Ross Ridge a ?crit : (snip) > Grant Edwards <invalid at invalid> wrote: >> Same here. It's like an automotive engine controls designer >> asking if a failed O2 sensor should turn on the check engine >> light or blow up the car. > > Ross Ridge <rridge at csclub.uwaterloo.ca> wrote: >> No, it's more like asking if the failed sensor should turn on >> a strange and mysterious light on the dashboard > > Grant Edwards <invalid at invalid> wrote: >> You're right. I had forgotten that sys.exit() is actually >> raising the system exit exception, and that the application >> calling the library could handle that exception. > > Well, my point was that exceptions in Python are a bit like a car's > check engine light. Few drivers know what this mysterious light means, > and aren't prepared to do anything about it when it goes on. You're kidding, aren't you ? From larry.bates at vitalEsafe.com Tue Sep 23 17:15:26 2008 From: larry.bates at vitalEsafe.com (Larry Bates) Date: Tue, 23 Sep 2008 16:15:26 -0500 Subject: Python style: exceptions vs. sys.exit() In-Reply-To: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <T_cCk.35701$rD2.7934@bignews4.bellsouth.net> Drake wrote: > I have a general question of Python style, or perhaps just good > programming practice. > > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), or should the exception propagate to the calling program which > handles the issue? > > Thanks in advance for anyone who can either answer my question or > point me to where this question has already been answered. > IMHO libraries should always just let the exception propagate up to the caller. That allows the caller the option of taking the appropriate action. -Larry From jake at vapourforge.com Fri Sep 19 10:30:53 2008 From: jake at vapourforge.com (Jake Anderson) Date: Sat, 20 Sep 2008 00:30:53 +1000 Subject: improving a huge double-for cycle In-Reply-To: <48d2bd22$0$4514$426a74cc@news.free.fr> References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> <48d2bd22$0$4514$426a74cc@news.free.fr> Message-ID: <48D3B79D.6080003@vapourforge.com> Bruno Desthuilliers wrote: > Alexzive a ?crit : >> Hello there :) , >> >> I am a python newbie and need to run following code for a task in an >> external simulation programm called "Abaqus" which makes use of python >> to access the mesh (ensamble of nodes with xy coordinates) of a >> certain geometrical model. >> >> [IN is the starting input containing the nodes to be check, there are >> some double nodes with the same x and y coordinates which need to be >> removed. SN is the output containing such double nodes] >> >> Code: Select all >> for i in range(len(IN)): #scan all elements of the list IN >> for j in range(len(IN)): >> if i <> j: >> if IN[i].coordinates[0] == IN[j].coordinates[0]: >> if IN[i].coordinates[1] == IN[j].coordinates[1]: >> SN.append(IN[i].label) >> >> >> >> Unfortunately my len(IN) is about 100.000 and the running time about >> 15h !!!! :( >> >> Any idea to improve it? > > A couple ones have been submitted. Harald gets a point about the > redundant tests (even if his solution seems to be broken, cf below) - > your inner loop should have looked like : > > for j in xrange(i+1, len(IN)) > > Now the obvious winner is pruebono - even unoptimized, using sets seems > to be *way* faster than even the most optimized corrected version of > your algorithm. > > Here's a quick bench - please everyone doublecheck it to make sure it's ok: > <snip code> > Results here (py2.5, gentoo linux, athlonxp1800, 512 ram): > > >>> test_results() > True > >>> test_times() > doubles0 : 1.55667901039 > doubles1 : 0.719144105911 > doubles2 : 0.703393936157 > doubles3 : 0.700654983521 > doubles4 : 0.706257104874 > doubles5 : 0.528184890747 > doubles6 : 0.461633205414 > doubles8 : 0.0134379863739 > doubles9 : 0.0108540058136 > >>> > > Not surprisingly, half less iterations makes for half less time. > Aliasing, as often, proves to be a good optimization too. But obviously, > using the correct data structure / algorithm combo is the key : simpler > code, and 115 times faster (143 times with aliasing). If pruebono > solution's is correct (and it as AFAICT), your 15 hours computation > should by now take less than 10 minutes... > > Ubuntu 8.04 core2 2.6(i think) without psycho doubles0 : 0.610555171967 doubles1 : 0.29314494133 doubles2 : 0.286273956299 doubles3 : 0.281984090805 doubles4 : 0.28240609169 doubles5 : 0.207377910614 doubles6 : 0.156388044357 doubles8 : 0.00533080101013 doubles9 : 0.00458884239197 with psycho doubles0 : 0.127684116364 doubles1 : 0.069571018219 doubles2 : 0.064826965332 doubles3 : 0.0702300071716 doubles4 : 0.0647261142731 doubles5 : 0.0522589683533 doubles6 : 0.0437579154968 doubles8 : 0.00190806388855 doubles9 : 0.00214099884033 On this small test its a variance between ~6x to 2X still its basically free so why not ;-> From mark at thomaszone.com Tue Sep 30 13:50:56 2008 From: mark at thomaszone.com (Mark Thomas) Date: Tue, 30 Sep 2008 10:50:56 -0700 (PDT) Subject: r"<path>" References: <5679444b-ca47-4e45-a20e-9433f24cb368@2g2000hsn.googlegroups.com> Message-ID: <459b50e2-1284-46d5-b788-f4438c6104a7@w7g2000hsa.googlegroups.com> On Sep 30, 1:17?pm, Kyle Hayes <mrkyleha... at gmail.com> wrote: > Is there a way to use the 'r' in front of a variable instead of > directly in front of a string? Or do I need to use a function to get > all of the slashes automatically fixed? Is this what you're talking about? str = "foo/bar" re = Regexp.new(str) => /foo\/bar/ -- Mark. From exarkun at divmod.com Fri Sep 26 15:14:05 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 26 Sep 2008 15:14:05 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Message-ID: <20080926191405.29191.1556457531.divmod.quotient.30634@ohm> On Fri, 26 Sep 2008 14:04:35 -0500, Michael Mabin <d3vvnull at gmail.com> wrote: >Doesn't it depend on where and why you intend to execute the code? >Obviously some SQL is more at risk for exploit when the input is from the >screen on a web page than if you were running parameterized code in a >controlled batch environment. Or if you were writing code generators (which >is what I happen to do) which won't be run by the general public. > No, not really. Particularly when it's not any harder to be secure than it is to be insecure, there's no reason to pick the insecure solution. It doesn't cost you anything to be secure. It *might* cost you something to be insecure, even if the environment is controlled. It's rarely the case that you actually control *every* aspect of an environment, and you can't reliably predict how a piece of code you write will be used in the future (either by you or by someone else, perhaps someone you've never even met at the time you write the code). Jean-Paul From fredrik at pythonware.com Thu Sep 11 12:59:08 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 11 Sep 2008 18:59:08 +0200 Subject: Python platform. In-Reply-To: <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <mailman.876.1221142791.3487.python-list@python.org> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> Message-ID: <gabiot$6vo$1@ger.gmane.org> carriere.jonathan at gmail.com wrote: > I want to build a desktop application. I am searching for some kind of > environment that would provide all the elements ready (Windows...). > Then I would have to code the business logic only. start here: http://wiki.python.org/moin/GuiProgramming The big ones are Tkinter, which is usually bundled with Python; wxPython, and PyQt. There's also a trend towards using the web browser as a presentation engine also for local applications; for libraries that help you with that, you can start here: http://wiki.python.org/moin/WebProgramming or jump directly to http://www.djangoproject.com/ </F> From sjmachin at lexicon.net Tue Sep 2 17:14:47 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 14:14:47 -0700 (PDT) Subject: How to write verbose scripts References: <00cd6a93$0$20302$c3e8da3@news.astraweb.com> <d5de89ff-ad8f-4a61-b6af-2c43f449acd0@m45g2000hsb.googlegroups.com> Message-ID: <5a3c1c2e-6613-41a9-b132-e979f978b14a@t1g2000pra.googlegroups.com> On Sep 3, 3:52 am, Mensanator <mensana... at aol.com> wrote: > On Sep 2, 11:55 am, Steven D'Aprano <st... at REMOVE-THIS- > > if (p & 1)==1: > print_evens = True > else: > print_evens = False > if (p & 2)==2: > print_odds = True > else: > print_odds = False > if (p & 4)==4: > print_debug = True > else: > print_debug = False No, no, no, you've taken "How to write verbose scripts" rather too literally; try this: print_evens = p & 1 print_odds = p & 2 print_debug = p & 4 From mensanator at aol.com Mon Sep 1 21:02:29 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 1 Sep 2008 18:02:29 -0700 (PDT) Subject: Py 2.6 changes References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <00cc7976$0$20302$c3e8da3@news.astraweb.com> <fb60e830-1267-48c9-9b99-3352a1db64cc@i76g2000hsf.googlegroups.com> Message-ID: <1bd15c2c-82e0-4742-a97f-ae16fb75ae26@m3g2000hsc.googlegroups.com> On Sep 1, 6:55?pm, bearophileH... at lycos.com wrote: > Steven D'Aprano: > > > productory() -- I don't know that function, and googling mostly comes up > > with retail product searches. Do you mean product(), > > Darn my English, you are right, sorry, I meant a product() of > course :-) But the name product() has already been taken by itertools to mean Cartesian Product. > > Bye, > bearophile From michael.pearmain at tangozebra.com Tue Sep 2 11:31:40 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Tue, 2 Sep 2008 08:31:40 -0700 (PDT) Subject: dict.update References: <0f959a45-252d-45e1-9a75-adf8c9c4e923@k37g2000hsf.googlegroups.com> <1b79577e-d74b-461f-ac0c-6841d3c22251@t1g2000pra.googlegroups.com> Message-ID: <223616eb-c9d6-4604-bc02-ec11815981b8@c58g2000hsc.googlegroups.com> Thanks Raymond, That's a neat trick, i'll look into learning more about this Mike From bearophileHUGS at lycos.com Wed Sep 3 11:37:07 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 08:37:07 -0700 (PDT) Subject: Numeric literal syntax References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <pan.2007.07.24.23.08.36.154246@REMOVE.THIS.cybersource.com.au> <87ej43pcy0.fsf@benfinney.id.au> <87hc8xor9g.fsf@benfinney.id.au> Message-ID: <63b8f474-00e7-4c48-99a5-5d70b60d2e3d@b1g2000hsg.googlegroups.com> Ben Finney: > ? for numbers with many digits the digits may be divided into > groups of three by a thin space, in order to facilitate reading. > Neither dots nor commas are inserted in the spaces between groups > of three. > <URL:http://www.bipm.org/en/si/si_brochure/chapter5/5-3-2.html#5-3-4> > This isn't binding upon Python, of course. However, it should be a > consideration in choosing what separator convention to follow. It confirms what I say :-) A thin space doesn't break the gestalt of the number, while a normal space, especially if you use a not proportional font with good readability (and characters well spaced) breaks the single gestalt of the number. Bye, bearophile From fredrik at pythonware.com Mon Sep 8 10:41:42 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 08 Sep 2008 16:41:42 +0200 Subject: firefox timestamp In-Reply-To: <9f9d35df0809072317h49ccec2ep72524f8d4900daa0@mail.gmail.com> References: <9f9d35df0809072317h49ccec2ep72524f8d4900daa0@mail.gmail.com> Message-ID: <ga3dj8$vfg$1@ger.gmane.org> abhilash pp wrote: > I don't know if this question will fit on this section, > any way my query is , i have used one script demork.py to extract > details from Firefox history.dat file > and now the problem is how to convert the TIMESTAMP given by that to > normal date and time. > example timestams are like this, > > 1202919771609375 > 1213874676203125 > 1215693263859375 > > i have used datetime module for this but it gave me error a quick googling indicates that the file contains microseconds, not seconds. dividing by 1e6 should do the trick: >>> t = 1202919771609375 >>> datetime.datetime.fromtimestamp(t / 1e6) datetime.datetime(2008, 2, 13, 17, 22, 51, 609375) </F> From castironpi at gmail.com Sat Sep 20 01:03:36 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Fri, 19 Sep 2008 22:03:36 -0700 (PDT) Subject: migrating processess to avoid the GIL References: <mailman.1288.1221867648.3487.python-list@python.org> Message-ID: <1d2982d9-9875-453b-9490-c33de612ebf6@m45g2000hsb.googlegroups.com> On Sep 19, 6:40?pm, "Patrick Stinson" <patrickstinson.li... at gmail.com> wrote: > I need to migrate calls to CPython to another process in my C++ app to > get around the GIL. Does anyone know of a good way to do this on > windows and Mac? All calls and callbacks can be blocking, I just need > to share some data structures. > > Cheers You should look into 'mmap' and 'struct'. mmap shares memory between processes, and is a random-access read-write file buffer. struct packs data from primitive types (integers, floats, & short strings) into a buffer. If you need advice on structuring your shared file, feel free to write back. From deets at nospam.web.de Mon Sep 1 07:21:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 Sep 2008 13:21:55 +0200 Subject: Using NLTK in Java References: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> <6i1hu9FnvcngU1@mid.uni-berlin.de> <d6558bd3-c077-4f09-b7cc-652ac3f17c7d@k13g2000hse.googlegroups.com> Message-ID: <6i21jaFomilbU1@mid.uni-berlin.de> hussainsaiger at gmail.com wrote: > On 1 Sep, 11:55, "Diez B. Roggisch" <de... at nospam.web.de> wrote: >> hussainsai... at gmail.com schrieb: >> >> > I am trying to convert a python module (that contains the use of >> > NLTK.Corpus) by jythonc. It is not able to include nltk dependencies >> > within the java class it creates. So when i use this class in java, it >> > fails to recognize nltk. Can anyone please let me know how should i >> > use nltk in python/jython modules so i can use in Java. >> >> If there are any binary dependencies, you are out of luck. It won't >> work. You would need to write a RPC-Server then, with technologies such >> as XMLRPC or CORBA. >> >> Diez > > So does that mean that Jython does not support nltk uptil now. I ask > this because when I try to import nltk in Jython (which is assumed to > replace Python), i get the same error. Its just nltk that I am not > able to use. The rest of the jython functions and libraries work fine > within Java. I don't know for sure - how about you post the error-message? Otherwise we can't assess the problem. Diez From asdfasdfasdfasdfasdf at arcor.de Sat Sep 6 17:04:14 2008 From: asdfasdfasdfasdfasdf at arcor.de (Andreas Hofmann) Date: Sat, 06 Sep 2008 23:04:14 +0200 Subject: String/Number Conversion Message-ID: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Hello Folks! I've got a little problem here, which which really creeps me out at the moment. I've got some strings, which only contain numbers plus eventually one character as si-postfix (k for kilo, m for mega, g for giga). I'm trying to convert those strings to integers, with this function: def eliminate_postfix(value): if type(value) is str: value.upper() if value.endswith('K'): mult = 1000 elif value.endswith('M'): mult = 1000000 elif value.endswith('G'): mult = 1000000000 else: mult = 1 if mult is 1: value = string.atoi(value) else: value = string.atoi(value[:-1]) * mult return value The problem is as follows: Everytime a string with a postfix should get converted, mult does not get set properly. It is always 1. Does anyone have an idea how to fix this? I just don't see it, maybe because I'm pretty new to python or because I'm just blind I would be really greatful. Kind regards, Andy From steve at REMOVE-THIS-cybersource.com.au Mon Sep 22 18:32:48 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Sep 2008 22:32:48 GMT Subject: What do you call a class not intended to be instantiated References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <76fd5acf0809211639u343893d4v94123620599320ba@mail.gmail.com> <mailman.1347.1222042368.3487.python-list@python.org> <pan.2008.09.22.09.07.43@REMOVE.THIS.cybersource.com.au> <mailman.1357.1222076517.3487.python-list@python.org> Message-ID: <00e816f4$0$20303$c3e8da3@news.astraweb.com> On Mon, 22 Sep 2008 19:41:46 +1000, James Mills wrote: > On 22 Sep 2008 09:07:43 GMT, Steven D'Aprano >> But that's precisely what I want to avoid: I don't want the objects to >> share *any* state, not even their class. I'm not trying for a Borg or >> Singleton: the user can call the factory as many times as they want, >> but the objects returned shouldn't share any state. I don't know if >> what I want has a name. Judging from people's reactions, I'd say >> probably not. > > Snce when are "users" ever involved > in programming problems or programming languages ? What an astounding question. Consider a class. There are the programmers who write the class, and there are the programmers (possibly the same people, but not necessarily) who use the class. The second set of people, the programmers who use the class, are *users* of the class. What else would they be? -- Steven From castironpi at gmail.com Wed Sep 24 21:57:55 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Wed, 24 Sep 2008 18:57:55 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <f5a4027b-4b9b-4d09-b76b-11d50b8070eb@p31g2000prf.googlegroups.com> <zllxzcpt.fsf@wgmail2.gatwick.eur.slb.com> <beeea088-c336-465e-a24c-160f5c56a2c4@p10g2000prf.googlegroups.com> Message-ID: <c4817afc-d588-4807-8e45-25d22988652c@59g2000hsb.googlegroups.com> On Sep 24, 8:40?pm, Asun Friere <afri... at yahoo.co.uk> wrote: > On Sep 25, 3:16 am, Pete Forman <pete.for... at westerngeco.com> wrote: > > > Asun Friere <afri... at yahoo.co.uk> writes: > > > ?> A canonical use of the conditional operator is in > > ?> pluralising words, (eg. '%s dollar' % n + 's' if n!=1 else ''). > > > That fails for n == 1. ?So what is best? > > Sorry missing parantheses. ?I should test, even for fragments written > out as part of a sentence. %-/ > > > for i in range(4): > > ? ? print '%d thing' % i + ('s' if i != 1 else '') > > That's the corrected version of what I meant, but actually I think > your last version ('%d thing%s' % (i, 's' if i != 1 else '')), holding > all variables for placeholders in the tuple, is better. It's certainly > more readible. It's a different answer if you have 'things is/are'. '%d thing%s %s'% ( ( i, )+ ( 's', 'are' ) if i!= 1 else ( '', 'is' ) ). Or excluding prepositional phrases and subordinate clauses, '%d thing%s'% ( i, 's are' if i!= 1 else ' is' ). From bearophileHUGS at lycos.com Wed Sep 3 19:00:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 3 Sep 2008 16:00:26 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> Message-ID: <8a5d982c-d5da-4b1d-bc29-228eca4202ae@v16g2000prc.googlegroups.com> Laszlo Nagy: > I believe that there have been excessive discussions about this > decision, and the current implementation is very good, if not the best. I see. But note that my post is mostly about the max()/min() functions :-) Bye, bearophile From ebgssth at gmail.com Thu Sep 25 17:02:45 2008 From: ebgssth at gmail.com (js) Date: Fri, 26 Sep 2008 06:02:45 +0900 Subject: How can I customize builtin module search path to prefix/lib to prefix/lib64? In-Reply-To: <c88dfce7-98bb-4827-a69d-3b3cb12820a0@y21g2000hsf.googlegroups.com> References: <c88dfce7-98bb-4827-a69d-3b3cb12820a0@y21g2000hsf.googlegroups.com> Message-ID: <a23effaf0809251402q50ba938bk3ef212f6c91d6b01@mail.gmail.com> For 64bit python, there's no need to look at lib/lib-dynload because libraries for 64bit should be in lib64/lib-dynload. Having module search path which point to libraries the python can not understand is, IMHO, wrong. On Fri, Sep 26, 2008 at 3:03 AM, Mike Driscoll <kyosohma at gmail.com> wrote: > On Sep 25, 10:41 am, js <ebgs... at gmail.com> wrote: >> Hi list, >> >> Is it possible to change module search path (PYTHONPATH) built-in to >> Python interpreter? >> I thought I can change it with configure --libdir but it didn't work for me. >> I also tried patching around python source tree replacing lib to lib64 >> but it didn't work either. >> >> Adjusting sys.path directly or using environ should do the trick but >> I'd rather want to make it the default path for my python >> >> Thanks, > > Why not just add a custom path file (*.pth)? EasyInstall, wx, PyWin32 > and others do it. Of course there's always sys.path.append as well. > > Mike > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Tue Sep 9 16:04:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 09 Sep 2008 17:04:04 -0300 Subject: Using NamedTemporaryDir instead of multiple NamedTemporaryFiles References: <ga6gfu$lgk$1@aioe.org> Message-ID: <op.ug8co2z9x6zn5v@a98gizw.cpe.telecentro.net.ar> En Tue, 09 Sep 2008 15:49:32 -0300, Michael Hoffman <4g4trz802 at sneakemail.com> escribi?: > I've written a NamedTemporaryDir class which is derived somewhat from > tempfile.NamedTemporaryFile in the standard library. Right now I am > using NamedTemporaryFile to create individual files, but since I am > putting them in a directory that will be deleted anyway, I'm wondering > if I can simplify things (and not have to keep track of all fo the > NamedTemporaryFile instances) by using tempfile.mkstemp() specifying my > temporary directory, and relying on the directory deletion when exiting > its with block. Looks fine... > def close(self): > if not self.close_called: > self.close_called = True > self.unlink(self.name) Windows won't let you remove a non-empty directory. > def __exit__(self, exc, value, tb): > result = self.file.__exit__(exc, value, tb) > self.close() > return result self.file? -- Gabriel Genellina From deets at nospam.web.de Fri Sep 5 07:12:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 13:12:16 +0200 Subject: newbie question: how to run a python file if it is in a package In-Reply-To: <cee5bd8f-3f02-4287-8fe2-176b4ca2d61b@q26g2000prq.googlegroups.com> References: <cee5bd8f-3f02-4287-8fe2-176b4ca2d61b@q26g2000prq.googlegroups.com> Message-ID: <6icighFpi4dpU1@mid.uni-berlin.de> neoedmund schrieb: > for example: > > X.py is in aaa.bbb and it has a line like "import aaa.bbb.Y" > how can I run X.py avoiding it saying such like "ImportError: No > module named aaa.bbb"? > > Is all runnable script must be in the default package? There is no such thing as a "default package" All imports are resolved over the "sys.path" list of directories (or eggs). There are various ways to modify this: - by hand. If you know X.py lives below aaa/bbb, you can get it's __file__-attribute, and walk the way down two levels. Then add the resulting path to sys.path. All this has to be done before any import of aaa.bbb occurs. - modify the environment variable PYTHONPATH to contain the root of aaa.bbb before starting the script. - write a custom .pth-file and place it into your pythno installation. The pth-file will contain the above mentioned root path. - use setuptools to create script entry-points, and install your whole application either fully, or as so-called egg-link. Possibly inside a virtualenv. This would be my personally preferred method. - simply copy your wohe aaa.bbb-stuff into site-packages. Make sure you do that whenever you change something in your code. Diez From http Wed Sep 10 17:50:07 2008 From: http (Paul Rubin) Date: 10 Sep 2008 14:50:07 -0700 Subject: handling uncaught exceptions with pdb? Message-ID: <7xmyifpt68.fsf@ruckus.brouhaha.com> I think I've asked about this before, but is there a way to set up Python to handle uncaught exceptions with pdb? I know about setting sys.except_hook to something that calls pdb, but this is normally done at the outer level of a program, and by the time that hook gets called, the exception has already unwound the stack to the outermost level. My situation is I run a multi-hour or multi-day computation that eventually crashes due to some unexpected input and I'd like to break to the debugger at the innermost level, right when the exception is encountered, so I can fix the error with pdb commands and resume processing. Of course this presumes a certain semantics for Python exceptions (i.e. handling one involves scanning the stack twice, once to look for a handler and again to actually unwind the stack) and I'm not sure if it's really done that way. I do know that Lisp has a requirement like that, though; so maybe there is hope. From __peter__ at web.de Thu Sep 18 05:32:47 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 18 Sep 2008 11:32:47 +0200 Subject: decorator and API References: <mailman.1183.1221688957.3487.python-list@python.org> <pan.2008.09.18.03.35.53@REMOVE.THIS.cybersource.com.au> Message-ID: <gat77u$33p$02$1@news.t-online.com> Steven D'Aprano wrote: I agree with you that the simple explicit approach is better. Now, to answer the question the OP didn't ask: > def choose_with_weighting(actions, weights=None): > ? ? if weights is None: > ? ? ? ? weights = [1]*len(actions) ?# equal weights > ? ? # Taken virtually unchanged from your code. > ? ? # I hope it does what you want it to do! It probably doesn't. > ? ? assert len(weights) == len(actions) > ? ? total = sum(weights) > ? ? choice = random.randrange(total) > ? ? while choice > weights[0]: > ? ? ? ? choice -= weights[0] > ? ? ? ? weights.pop(0) > ? ? ? ? actions.pop(0) > ? ? return actions[0] Assume two actions with equal weights [1, 1]. total becomes 2, and choice is either 0 or 1, but never > weights[0]. While this can be fixed by changing the while condition to while choice >= weights[0]: #... I prefer an approach that doesn't destroy the actions and weights lists, something like import bisect def choose_with_weighting(actions, weights=None, acc_weights=None): if acc_weights is None: if weights is None: return random.choice(actions) else: sigma = 0 acc_weights = [] for w in weights: sigma += w acc_weights.append(sigma) return actions[bisect.bisect(acc_weights, random.randrange(acc_weights[-1]))] especially if you prepare the acc_weights list once outside the function. Peter From robert.kern at gmail.com Sat Sep 27 19:07:36 2008 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 27 Sep 2008 18:07:36 -0500 Subject: EPD (Enthought Python Distribution) 4.0.300 Beta 3 available In-Reply-To: <975844EF-46F5-439E-8481-544A91EF7A98@dcs.shef.ac.uk> References: <48DDCDDA.50009@enthought.com> <975844EF-46F5-439E-8481-544A91EF7A98@dcs.shef.ac.uk> Message-ID: <gbmebp$s70$1@ger.gmane.org> Disclosure: I work for Enthought. Christopher Brewster wrote: > I have always thought this idea very good, but if I download it and > install it (on my MacBook pro) will any conflicts occur with existing > bits and pieces of Python and its libraries? For the Mac distribution, we have tried very carefully to keep EPD's Python separate from any previous installation. I believe the only thing that will get "overwritten" is that our bin/ directory inside our version of Python.framework will get prepended to your $PATH environment variable. This will be added to your ~/.bash_profile with a a descriptive comment. When you type $ python at your Terminal prompt, you will get EPD's Python. To uninstall EPD, you can remove those lines in your ~/.bash_profile, delete /Library/Frameworks/Python.framework/Versions/4.0.300/, and delete "/Applications/EPD <something or other>/". Then your previous Python installation should be usable again. To just use your previous Python installation without uninstalling EPD, just comment out our addition to ~/.bash_profile. If you have more questions about EPD, please join us on the enthought-dev mailing list: https://mail.enthought.com/mailman/listinfo/enthought-dev -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From steve at REMOVE-THIS-cybersource.com.au Sun Sep 21 18:39:47 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 21 Sep 2008 22:39:47 GMT Subject: What do you call a class not intended to be instantiated Message-ID: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> I have a class which is not intended to be instantiated. Instead of using the class to creating an instance and then operate on it, I use the class directly, with classmethods. Essentially, the class is used as a function that keeps state from one call to the next. The problem is that I don't know what to call such a thing! "Abstract class" isn't right, because that implies that you should subclass the class and then instantiate the subclasses. What do you call such a class? -- Steven From maric at aristote.info Thu Sep 4 07:54:56 2008 From: maric at aristote.info (Maric Michaud) Date: Thu, 4 Sep 2008 13:54:56 +0200 Subject: cPickle In-Reply-To: <g9ofjv$44p$1@ger.gmane.org> References: <01f901c90e70$8e118a50$2fc513ac@pwit.com> <g9ofjv$44p$1@ger.gmane.org> Message-ID: <200809041354.57003.maric@aristote.info> Le Thursday 04 September 2008 13:08:59 Gerhard H?ring, vous avez ?crit?: > gopal mishra wrote: > > I have 3 objects and want to save in one pickle file. > > > > I used cPickle to dump 3 objects in a pkl file > > > > i.e cPickle.dump(object1, fileobject, -1) > > > > cPickle.dump(object2, fileobject, -1) > > > > cPickle.dump(object3, fileobject, -1) > > > > > > > > I have changed the 3^rd object and want to save the updated 3^rd object > > in the pickle file. > > > > I have to dump all the 3 objects again. > > > > Is there any way to dump only the 3^rd object in to the pkl file. > > No, there isn't. You could, of course, save each object in its own > pickle file. Or use an object database like ZODB instead. > Shelve is another alternative, shipped with python and rather straightforward. Shelve as ZODB use pickles of objects but, unlike ZODB, won't need you change anything to your actual classes. >>>[8]: import shelve >>>[9]: s = shelve.open('db') >>>[10]: a, b, c = 5, 4., ("foo", "bar") >>>[11]: s['a'], s['b'], s['c'] = a, b, c >>>[12]: s.close() >>>[13]: maric at redflag1 13:46:42:~$ file db db: Berkeley DB (Hash, version 8, native byte-order) maric at redflag1 13:46:44:~$ ipython >>>[1]: import shelve >>>[2]: s = shelve.open('db') >>>[3]: for name, value in s.items() : print name, value ...: b 4.0 a 5 c ('foo', 'bar') >>>[5]: del s['b'] >>>[6]: s['c'] += ('baz',) >>>[7]: s.sync() >>>[8]: maric at redflag1 13:48:12:~$ ipython >>>[1]: import shelve >>>[2]: s = shelve.open('db') >>>[3]: for name, value in s.items() : print name, value ...: a 5 c ('foo', 'bar', 'baz') The sync method may not work on all platform, maybe you'll have to close and re-open the db file to write to disk. -- _____________ Maric Michaud From pataphor at gmail.com Sun Sep 14 09:25:28 2008 From: pataphor at gmail.com (pataphor) Date: Sun, 14 Sep 2008 15:25:28 +0200 Subject: How to emit Cyrillic and Chinese via unicode from console mode? References: <ieidnYDBwLZ3_1HVnZ2dnUVZ_tPinZ2d@comcast.com> <543bde0c-4d99-4d79-a4dd-b6f8d85e8c48@l64g2000hse.googlegroups.com> Message-ID: <20080914152528.51457e1f@hyperspace> On Sun, 14 Sep 2008 01:02:39 -0700 (PDT) rs387 <rstarkov at gmail.com> wrote: > On Sep 14, 2:03?am, "Siegfried Heintze" <siegfr... at heintze.com> wrote: > > Can someone point me to an example of a little program that emits > > non-ascii Unicode characters (Russian or Chinese perhaps)? > > The following doesn't quite work, but I'll post it anyway since it > actually ends up printing the characters. That's more like it! Just answer with whatever one has. Here's another gem: from Tkinter import * from collections import deque def byn(x,n =5 ): L = deque(x) R = [] while L: R.append(L.popleft()) if len(R) == n: yield ''.join(R) R = [] if R: yield ''.join(R) root = Tk() start = int('16A6',16) end = int('16F0',16) g = (unichr(i) for i in xrange(start, end+1)) L = byn(g,16) s = '\n'.join(L) w = Label(root, text=s,font = ("freemono","80")) w.pack() root.mainloop() P. From vaidehi.pawar at yahoo.co.in Wed Sep 10 17:49:50 2008 From: vaidehi.pawar at yahoo.co.in (Vaidehi Pawar) Date: Thu, 11 Sep 2008 03:19:50 +0530 (IST) Subject: PLEASE HELP ME WITH THIS ASSIGNMENT...PLEASE.... Message-ID: <276719.72706.qm@web95107.mail.in2.yahoo.com> I know I'm tooooo late to ask you for help....but please help me out..I am really new to unix and dont know how to finish this assignment on time.....proff. said he will be using MOSS to detect whether I downloaded the code..please help me.. email me : vaidehi.pawar at yahoo.co.in Assignment 1 Processes, Inter-Process Communication, and Concurrency Due September 13th midnight Summary In this assignment, you will create two versions of a simple multi-process game : one without and another with inter-process synchronization. You will also measure the relative performance of the two versions of your multi-process game. Objectives * Learn how to create and terminate processes. * Learn use of inter-process communication using shared memory, semaphores, signals, etc. * Learn the basic workings of CPU scheduling code in Linux. Part A: Multi-Process Game of Turns In this part, you are asked to write a simple program that takes two command-line arguments P and N. The main process creates P other child processes, waits for all of them to complete, and then exits. All the child processes form one logical ring among each other. (In rest of the description, the term "process" refers to a "child process".) For example, if the processes are numbered 1 to P, then * The next neighbor of process 1 is process 2, * The next neighbor of process i is process i+1 for all i < P , and * The next neighbor of process P is process 1, which completes a ring among the processes. Assume that a shared integer variable, called turn, identifies the number of the processes whose turn it is at any instant. A second process-local variable in each process, called me, identifies the identity of each process (i.e. each process stores its own identity in a per-process local variable me). A third per-process local variable, called next, identifies the next process in the ring. The processes sequentially pass the turns among each other in the logical ring. When each process gets its turn, it increments another shared variable called counter. The pseudo-code within each process for passing turns might look something as follows. (Note: Replace turn and counter below with appropriate ways of accessing data within shared memory regions). while(turn != me ) /* do nothing - just busy loop*/ ; /* got my turn - increment counter */ counter = counter + 1; /* give the turn to next process */ turn = next; The program terminates when the each process has received N turns. In the above description, several programming details have been omitted for you to figure out. This includes * Creating P child processes from main process. * Constructing the logical ring among child processes. o Initializing each child process's identity in the me variable. o Initializing each child process' next neighbor in the next variable. * Initializing the shared memory region and the shared data values. * Have the main process wait for child processes to complete N turns before exiting. Part B: More Efficient Game of Turns You might notice that the program you wrote in Part A is inefficient because each process busy loops till the CPU scheduler kicks it out (after its time-slice is over) and allows another process to execute and make progress. (Does the program in Part A have a race condition? Why or why not?) What we ideally want is that each process should be given control of the CPU only when it is that process' turn. Modify the program you wrote in Part A (using appropriate synchronization mechanisms) such that each process gets to run (i.e., gets control of the CPU) only when it is that process's turn, and at no other time. Again, you would need to work out the programming details of how and where to use inter-process synchronization. Part C: Profiling the Game of Turns In this part, you are asked to write user-level profiling code in order to measure the performance of the two versions of programs you wrote in Part A and Part B. Use a combination of gettimeofday() system call and inter-process synchronization to measure (1) the average hand-over time between two consecutive processes in the ring and (b) the total execution time to complete N turns. Plot the measured values as graphs when varying number of processes P and number of turns N. Explain the results you obtain. Submission Guidelines Thanking you, Ms. Vaidehi Pawar ________________________________ Check out the all-new face of Yahoo! India. Go to http://in.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080911/abc03a9e/attachment-0001.html> From metallourlante at gmail.com Sun Sep 21 09:17:36 2008 From: metallourlante at gmail.com (Alex) Date: Sun, 21 Sep 2008 06:17:36 -0700 (PDT) Subject: understanding list scope References: <58c416d6-9f17-4903-b415-a6d8d1067ac6@r66g2000hsg.googlegroups.com> <974c3434-d409-484d-8bc4-7a3294132bd0@73g2000hsx.googlegroups.com> Message-ID: <e9b3c8ed-c548-4807-8c3b-1fe7ccc0009b@m3g2000hsc.googlegroups.com> On 21 Set, 15:07, George Sakkis <george.sak... at gmail.com> wrote: > On Sep 21, 8:51 am, Alex <metallourla... at gmail.com> wrote: > > > > > Hi all! > > > I have a problem understanding the behaviour of this snippet: > > > data_set = ({"param":"a"},{"param":"b"},{"param":"c"}) > > > for i in range(len(data_set)): > > ds = data_set[:] > > data = ds[i] > > if i == 1: data['param'] = "y" > > if i == 2: data['param'] = "x" > > > print data_set > > > This script print out: > > ({'param': 'a'}, {'param': 'y'}, {'param': 'x'}) > > > Why? I'm coping data_set in ds so why data_set is changed? > > Because you're doing a shallow copy:http://docs.python.org/lib/module-copy.html > > George Thanks a lot. It was giving me and headache! From castironpi at gmail.com Sun Sep 28 19:11:06 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 28 Sep 2008 16:11:06 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> Message-ID: <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> On Sep 28, 4:47?pm, Terry Reedy <tjre... at udel.edu> wrote: > Aaron "Castironpi" Brady wrote: > > On Sep 28, 2:52 am, Steven D'Aprano <st... at REMOVE-THIS- > >> As for why the complicated version works, it may be clearer if you expand > >> it from a one-liner: > > >> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n ) > > >> inner = lambda: n > >> outer = lambda n: inner > >> f[n] = outer(n) > > >> outer(0) => inner with a local scope of n=0 > >> outer(1) => inner with a local scope of n=1 etc. > > For this to work, the 'expansion' has to be mental and not actual. > Which is to say, inner must be a text macro to be substituted back into > outer. > > >> Then, later, when you call inner() it grabs the local scope and returns > >> the number you expected. > > > I must have misunderstood. ?Here's my run of your code: > > I cannot speak to what Steven meant, but > > >>>> inner = lambda: n > > when inner is actually compiled outside of outer, it is no longer a > closure over outer's 'n' and 'n' will be looked for in globals instead. > > >>>> outer = lambda n: inner > >>>> outer(0) > > <function <lambda> at 0x00A01170> > >>>> a=outer(0) > >>>> b=outer(1) > >>>> a() > > Traceback (most recent call last): > > ? File "<stdin>", line 1, in <module> > > ? File "<stdin>", line 1, in <lambda> > > NameError: global name 'n' is not defined > > > Why doesn't 'inner' know it's been used in two different scopes, and > > look up 'n' based on the one it's in? > > That would be dynamic rather than lexical scoping. I couldn't find how those apply on the wikipedia website. It says: "dynamic scoping can be dangerous and almost no modern languages use it", but it sounded like that was what closures use. Or maybe it was what 'inner' in Steven's example would use. I'm confused. Actually, I'll pick this apart a little bit. See above when I suggested 'late' and 'early' functions which control (or simulate) different bindings. I get the idea that 'late' bound functions would use a dangerous "dynamic scope", but I could be wrong; that's just my impression. > >> inner = lambda: n > >> outer = lambda n: inner > >> f[n] = outer(n) > > >> outer(0) => inner with a local scope of n=0 > >> outer(1) => inner with a local scope of n=1 etc. If you defined these as: inner= late( lambda: n ) outer= lambda n: inner You could get the right results. It's not even clear you need quotes. Perhaps 'late' could carry the definition of 'n' with it when it's returned from 'outer'. In my proposal, it makes a copy of the "localest" namespace, at least all the variables used below it, then returns its argument in an original closure. From noelob at gmail.com Mon Sep 22 06:21:57 2008 From: noelob at gmail.com (noelob) Date: Mon, 22 Sep 2008 03:21:57 -0700 (PDT) Subject: BadStatusLine: Message-ID: <4e3d5d97-1b5f-4593-9c33-ad8b57d59b05@f36g2000hsa.googlegroups.com> Hi All, During performance testing of my web application, I occasionally get a BadStatusLine exception from httplib. Reading http://docs.python.org/lib/module-httplib.html#l2h-4021 tells me that it's "Raised if a server responds with a HTTP status code that we don't understand." Is there a way to find what the actual status code returned was? I.e. the value that caused the exception to be thrown? Under what circumstances is a BadStatusLine normally thrown? (e.g. data corruption?) I'm quite new to python, but not to programming. Apologies if this is a silly question ;) Thanks, Noel From pruebauno at latinmail.com Thu Sep 18 11:18:34 2008 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Thu, 18 Sep 2008 08:18:34 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <30fab72b-2d7f-497d-a687-1d697633db9c@z66g2000hsc.googlegroups.com> On Sep 18, 8:25 am, Alexzive <zasaconsult... at gmail.com> wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > for i in range(len(IN)): #scan all elements of the list IN > for j in range(len(IN)): > if i <> j: > if IN[i].coordinates[0] == IN[j].coordinates[0]: > if IN[i].coordinates[1] == IN[j].coordinates[1]: > SN.append(IN[i].label) > > Unfortunately my len(IN) is about 100.000 and the running time about > 15h !!!! :( > > Any idea to improve it? > > I have already tried to group the "if statements" in a single one: > > Code: Select all > if i <> j and if IN[i].coordinates[0] == IN[j].coordinates[0] and > if IN[i].coordinates[1] == IN[j].coordinates[1]: > > but no improvements. > > Many thanks, Alex dup=set() SN=[] for item in IN: c=item.coordinates[0], item.coordinates[1] if c in dup: SN.append(item.label) else: dup.add(c) From mailcindy at gmail.com Tue Sep 30 02:53:21 2008 From: mailcindy at gmail.com (cindy jones) Date: Tue, 30 Sep 2008 12:23:21 +0530 Subject: Python script for tracert Message-ID: <46da4e770809292353o2d72091aj6e717e35e62cfce6@mail.gmail.com> Hello.. I'm trying to do a scripting for tracert in windows using python... I'm using popen(), but it displays only after the tracert is completed. i want the results to be displayed for every route. can anyone help me in this.. Thank You -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/5efbb8d4/attachment-0001.html> From don.hamilton at btinternet.com Fri Sep 12 13:16:31 2008 From: don.hamilton at btinternet.com (Don) Date: Fri, 12 Sep 2008 18:16:31 +0100 Subject: Which version Message-ID: <3eqdnSlKTvJsPlfVnZ2dnUVZ8uOdnZ2d@bt.com> Hi, I'm a reasonably experienced in other languages and have just decided to get my feet wet with Python. But I'm using FC6 which has v2.4.4 installed, is this good enough to start out with or am I likely to encounter bugs that have been fixed in later versions. Don From M8R-yfto6h at mailinator.com Sun Sep 28 20:58:28 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 28 Sep 2008 17:58:28 -0700 Subject: Python 3.0 and repr References: <q6KdnXBZ9LioJkLVnZ2dnUVZ_u-dnZ2d@comcast.com> <48dffb54$0$1082$9b622d9e@news.freenet.de> Message-ID: <a9-dnTLNuJGztX3VnZ2dnUVZ_h6dnZ2d@comcast.com> ""Martin v. L?wis"" <martin at v.loewis.de> wrote in message news:48dffb54$0$1082$9b622d9e at news.freenet.de... >> What are others' opinions? Any insight to this design decision? > > The intention is that all printable characters in a string get displayed > in repr. This was in particular requested by Japanese users (but also by > other users of non-ASCII characters) which complained that repr() is > fairly useless if your strings actually contains *no* ASCII characters > (but all of them are printable). > > Notice that repr() of the string actually succeeds; try > >>>> x='\u5000' >>>> z=repr(x) > > It is the printing of the repr that fails. > >> Maybe repr() should always display the ASCII representation with >> escapes for all other characters > > You can use the ascii() builtin if you want that. > >> especially considering the "repr() should produce output suitable for >> eval() when possible" rule. > > But that is preserved under the new behavior, also! Just try > > py> x='\u5000' > py> eval(repr(x))==x > True > > Regards, > Martin Thanks Martin, it's clear now. I just read about the new ascii() function before seeing your reply. > P.S. How did you manage to get U+5000 into your data, on a system where > the terminal encoding is cp437? Google translates it as "Rash"; the > Unihan database also has "bewildered", "wildly". I just picked that example out of the air. I study Chinese and knew it was a character in that area of the Unicode map. My usual editors (PythonWin and PyAlaMode from wxPython) don't work with Python 3, which was why I was using the Windows cmd prompt. Thanks, Mark From invalid at invalid Thu Sep 18 13:47:41 2008 From: invalid at invalid (Grant Edwards) Date: Thu, 18 Sep 2008 12:47:41 -0500 Subject: PEP proposal optparse References: <ca58efdf-3f9c-4aea-9c20-69c69a578754@k30g2000hse.googlegroups.com> <baKdnTZYS-BM4U_VnZ2dnUVZ_jKdnZ2d@posted.visi> <6jffpaF2s539U1@mid.uni-berlin.de> Message-ID: <p8GdnS_ddZmgCU_VnZ2dnUVZ_sTinZ2d@posted.visi> On 2008-09-18, Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote: > On Thu, 18 Sep 2008 11:07:45 -0500, Grant Edwards wrote: > >> While we're making suggestions, I've always wished that the --help >> output displayed the default values for options in addition to the help >> text specified by the user. I end up having to enter the default values >> twice -- once as a keyword argument and again in the help text. > > '%default' in the help text will be replaced by the default value. See > the last option in the first example here: > > http://docs.python.org/lib/optparse-generating-help.html Great! I guess I should scan the doc pages for changes more often. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com From mathieu.prevot at gmail.com Sat Sep 6 11:14:33 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Sat, 6 Sep 2008 17:14:33 +0200 Subject: Canonical way to build Python 2.6/svn on MacIntel/MacOSX10.5 with icc 32bits 10.1.014 Message-ID: <3e473cc60809060814y4ff4eca6sf89b7af03c94b9f4@mail.gmail.com> Hi, I would like to build Python (svn) on Macosx 10.5 with icc in /opt/intel/cc (32 bit). Can you help me to determine the right way to do this ? I got a prototype with: export CC=icc export CXX=icpc export CFLAGS="-w" ./configure --with-framework-name=PythonIntel 1) It seems to be unsufficient. Does someone have links/mail archives/patches/scripts ? 2) Python needs gettext for _locale package, but I fail to compile it with icc. 3) How can I build an autonomous and sufficient distribution (a dmg file with everything in it) ? Thanks, Mathieu From raj.indian.08 at gmail.com Thu Sep 18 11:14:03 2008 From: raj.indian.08 at gmail.com (raj.indian.08 at gmail.com) Date: Thu, 18 Sep 2008 08:14:03 -0700 (PDT) Subject: Modifying the system menu References: <bfa45e21-fb5e-454d-a4c2-e7cc00919f38@p31g2000prf.googlegroups.com> <mailman.1154.1221639413.3487.python-list@python.org> <8c1df849-d6e0-409a-930d-0593eed85683@a29g2000pra.googlegroups.com> Message-ID: <1e409ef1-ffd1-4774-8b12-d62d9b79e130@a29g2000pra.googlegroups.com> On Sep 18, 6:39?am, raj.indian... at gmail.com wrote: > I tested it again and found that the behaviour is a little different > from what I mentioned previously in the mailchain. > The item is working perfectly the first time around. Now if I close > the application and run it again (which was what I did earlier), if > that application system menu is already modified, it is causing this > issue. > > Why would this happen? If it is that the file handle is not obtained, > it wouldnt have gone through the following check at all? > > > ? ? hw = win32gui.GetSystemMenu(hwnd, False) > > ? ? if hw != None: > > ? ? ? ? win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); > > Not only did it go through, it failed with an invalid menu handle > error. More worryingly, this happens randomly. Am I doing some mistake here? From bignose+hates-spam at benfinney.id.au Thu Sep 11 01:25:57 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 11 Sep 2008 15:25:57 +1000 Subject: Gateway to python-list is generating bounce messages. References: <8K6dnVaoxJS9lFXVnZ2dnUVZ_j6dnZ2d@posted.visi> <87d4jbd0v7.fsf@benfinney.id.au> <fpWdnbUMGNWpGVXVnZ2dnUVZ_sudnZ2d@posted.usinternet> Message-ID: <87k5djb6e2.fsf@benfinney.id.au> Grant Edwards <grante at visi.com> writes: > On 2008-09-10, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: > > Grant Edwards <grante at visi.com> writes: > > > >> Could whoever is responsible for the gateway that is grabbing > >> my postings off of Usenet and e-mailing them out please fix the > >> headers in the mail messages so that I don't get the bounce > >> messages? > > > > The bounce messages are sent to you because you sent the > > original. > > Wrong. I didn't send _any_ e-mail. Why should I get bounce > messages? You asked for email to be sent, by sending a Usenet post to comp.lang.python. That's what a news-to-mail gateway does. > Isn't sending e-mails pretending they're from somebody else > considered unethical (if not illegal)? No, since it's clearly the function of a news-to-mail gateway to make this forum operate as a single pool of communication, seamlessly passing the messages between two distinct media. That happens by preserving the messages as intact as feasible in both media. > > Indeed it is rude, and the person subscribed to the mailing list > > whose software is sending these bounce messages is the one > > responsible for making it stop. > > No, the one who's sending e-mail with forged headers is the one who > ought to make it stop. That e-mail was not from me. It was from > somebody who grabbed the article off a usenet server and mailed it > to a bunch of people. You seem to be arguing that the news-to-mail gateway of this forum should stop functioning. I don't know if you're claiming to be ignorant of the news-to-mail gateway before now; if so, I hope you'll agree that having a large body of mostly well-behaved contributors on this joint forum is worth effort to keep it operational. > I think the list administrator ought to stop putting other people's > e-mail addresses in the From: headers of e-mails he's sending. (Note that an email message has exactly one header, by definition; it consists of separate fields, of which the From field is one.) It's unfortunate that you don't like how the news-to-mail gateway functions, but I'm not convinced that one person's surprise at how it operates should be reason to break its primary function. I sympathise completely with your irritation at receiving bounce messages from poorly-configured software, but the solution is not to break the news-to-mail gateway. The correct solution is to unsubscribe the badly-behaving address from the mailing list, and refuse re-subscription from that address without assurance that the bad behaviour has ceased. -- \ ?A child of five could understand this. Fetch me a child of | `\ five.? ?Groucho Marx | _o__) | Ben Finney From maric at aristote.info Mon Sep 15 08:09:13 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 14:09:13 +0200 Subject: Abstract class In-Reply-To: <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> References: <mailman.1008.1221408214.3487.python-list@python.org> <mailman.1012.1221419718.3487.python-list@python.org> <00dd6d4d$0$20331$c3e8da3@news.astraweb.com> Message-ID: <200809151409.14149.maric@aristote.info> Le Sunday 14 September 2008 22:25:18 Steven D'Aprano, vous avez ?crit?: > On Sun, 14 Sep 2008 12:15:04 -0700, Gary Herron wrote: > > (If you wish to consider the base class "abstract", just agree with > > yourself to not instantiate it.) > > That's certainly the most lightweight option. > > > Please forget about Abstract Base Classes. They have nothing to do with > > what you want, and are a *HUGE* overkill for your application. They > > are not (yet) even part of standard Python, and are used primarily for a > > class implementor to guarantee to a user of a class that it provides a > > specific interface. > > You can implement a lightweight abstract base class in Python fairly > easily, by adding two lines to the __init__ method of your base class. > > > class Base(object): > def __init__(self): > if self.__class__ is Base: > raise NotImplementedError("Abstract base class") > def method(self, *args): > return len(args) # or something useful > > But this doesn't match what abstract classes are (in C++ for example), because __init__ can, and probably will, have logic reusable in concrete classes. The only way to do this is to call in the __int__ at least one of the methods raising NotImplementedError, probably creating a dummy one for this purpose, and still it doesn't satisfy with the constraint that *all* abstract methods must be implemented in concrete classes. > "The fact that many languages disallow instantiation of abstract types > (and force subtypes to implement all needed functionality) further > ensures program correctness." > > http://en.wikipedia.org/wiki/Abstract_base_class > > but I don't see how that follows (except possibly in very special cases). > Given that the set of instances of class B is empty, how does that help > you know that B.method is correct? I agree with you on this, and the simple scheme of defining some methods raising exceptions is obviously sufficiient where duck typing is. ABC, as I understood it, is for resolving another problem : unrelated (by inheritance) classes, which share the same signature, but need to be distinguished in their behavior. -- _____________ Maric Michaud From gagsl-py2 at yahoo.com.ar Sun Sep 7 15:50:09 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 07 Sep 2008 16:50:09 -0300 Subject: __builtins__ magic behavior References: <d09829f50809071000x5b1cfe89va6ebd07404d7af8f@mail.gmail.com> Message-ID: <op.ug4mpvsrx6zn5v@a98gizw.cpe.telecentro.net.ar> En Sun, 07 Sep 2008 14:00:48 -0300, Patrick Maupin <pmaupin at gmail.com> escribi?: > __builtins__ in 2.5.2 doesn't seem to behave like I remember it did > the last time I did some custom stuff with it, a very long time ago. > > This isn't surprising, because of ongoing optimization, but it's hard > to google for '__builtins__' so I didn't really find any documentation > on the current CPython behavior, which in some cases seems quite > strange to me. > > The documentation node at http://docs.python.org/ref/naming.html has a > "here be dragons" note on __builtins__, which is nice as far as it > goes, but doesn't provide any help for people wanting to abuse the > current CPython implementation. Additionally, the sentence > immediately above the note, "__builtins__ can be set to a user-created > dictionary to create a weak form of restricted execution" not only > contradicts the note, but in some cases appears not to be true. > > When the code below is run, either standalone or by importing it, the > builtins used are different depending on whether exec is used with > globals() or with a copy of globals(). Any explanations for this > behavior would be much appreciated. Python takes some shortcuts when dealing with builtins. I'll just describe what happens (I won't say whether it is "right" or "wrong"). The exec statement, when given a string source, compiles it and eventually calls PyEval_EvalCodeEx, which creates a new frame using PyFrame_New and finally executes it. A frame object contains a pointer to the previous frame, the code to be executed, a pointer to the current globals *and* a separate pointer to the current builtins. Inside PyFrame_New, there is a shortcut: if the new frame and the previous one share the same globals, then the previous builtins are copied into the new frame. Only if the globals differ the builtins are searched in globals. From frameobject.c: /* If we share the globals, we share the builtins. Save a lookup and a call. */ It is this assumption that fails in your code. If you want to execute some code with modified builtins, do not change __builtins__ in the *calling* code, but in the globals that you pass to the exec call. That appears to be the most logical approach, and the way the developers appear to have expected. -- Gabriel Genellina From gaius at gaius.org.uk Fri Sep 5 09:26:04 2008 From: gaius at gaius.org.uk (gaius hammond) Date: Fri, 05 Sep 2008 14:26:04 +0100 Subject: cx_oracle and commands Message-ID: <1220621164.48c1336c32f31@netmail.pipex.net> Hi all, I am having a very strange problem with cx_Oracle, has anyone seen this kind of behavior before: ActivePython 2.5.2.2 (ActiveState Software Inc.) based on Python 2.5.2 (r252:60911, Mar 27 2008, 18:53:24) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> from commands import getstatusoutput >>> (status, output) = getstatusoutput('ls') >>> status 0 >>> from cx_Oracle import connect, SYSDBA >>> db = connect(mode=SYSDBA) >>> (status, output) = getstatusoutput('ls') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/ASpy25/lib/python2.5/commands.py", line 55, in getstatusoutput sts = pipe.close() IOError: [Errno 10] No child processes Basically, once I have made a connection to Oracle I can no longer use getstatusoutput(). This is a real problem as I need to get a list of things to work on from Oracle then spawn commands to process them... Thanks, G -- gaius at gaius.org.uk http://www.gaius.org.uk/ "First things first, but not necessarily in that order" -- The Doctor, "Doctor Who" ------------------------------------------------- Visit Pipex Business: The homepage for UK Small Businesses Go to http://www.pipex.co.uk/business-services From adityashukla1983 at gmail.com Wed Sep 10 15:41:36 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Wed, 10 Sep 2008 14:41:36 -0500 Subject: tempfile module Message-ID: <73045cca0809101241u1d2ddbe8i7b7598bca785509e@mail.gmail.com> Hello folks, I am using Python-2.5.2 on fedora 9 sulphur -2.6.25-14.fc9.i686.I am creating a temporary file , in which data is written by another program and then i am using that temporary file to do my computations.I am new to linux and i am facing two issues homedir = os.path.expanduser('~') temp = tempfile.NamedTemporaryFile( suffix='_suffix',prefix='prefix_',dir= homedir) temp.close() tn = temp.name print tn Issue1 -> when i am logged in as root then everything works fine except that the file is created in the current working directory (/usr/Python-2.5.2) and not in the directory supplied as the dir='directory' parameter.i have tried dir='/tmp' as well.i don't know how to fix this issue and why the file is not getting created in the specified directory. Issue2 -> when i am logged in as user ie any other user than root then i get this error sh: prefix_u92XQJ_suffix: Permission denied also , i cannot find the find in either the current working directory nor in the dir='directory'.so i cant check the permission by using ls -l prefix_u92XQJ_suffix Please help me understand this issue and eventually fix it. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/4a5cf451/attachment-0001.html> From digitig at gmail.com Fri Sep 26 19:40:59 2008 From: digitig at gmail.com (Tim Rowe) Date: Sat, 27 Sep 2008 00:40:59 +0100 Subject: Not fully OO ? In-Reply-To: <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <24ac4a18-049f-4ae0-892a-d3fc84995c9d@a18g2000pra.googlegroups.com> <aee48b3c0809231001s4bbf9026u6c47b8d13a131fd7@mail.gmail.com> <48DCC786.2040407@wildenhain.de> <mailman.1551.1222447687.3487.python-list@python.org> <126c068b-ac41-4c4c-874a-1b379135ee2d@l64g2000hse.googlegroups.com> Message-ID: <aee48b3c0809261640v2d2850c1t5236894a56ba5779@mail.gmail.com> 2008/9/26 Aaron Castironpi Brady <castironpi at gmail.com>: > If you have wxFormBuilder and the win32 library, it's pretty fast. Speed has never been an issue for me with Python. For my masters degree I did a project that involved a lot of number crunching, and in my proposal I wrote that I'd use Python for most of the code and C for any parts that were unacceptably slow. In practice, not only did I never need to replace any parts with C, I never even needed to use numpy; it was quite fast enough as it was. > Python's philosophy is to make common things easy and everything > possible. But what's common for one person may be uncommon for another. And sometimes "possible" isn't enough, or we'd all be using INTERCAL! Another, quite different example to the one I was referring to earlier is the fact that I often work with safety critical systems. I don't think formal proof of program behaviour would be at all straightforward in Python (or C# for that matter, and although Spec# gets closer, it really needs a language like Spark Ada). -- Tim Rowe From mensanator at aol.com Sun Sep 7 20:36:58 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 7 Sep 2008 17:36:58 -0700 (PDT) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <dullrich-991CAD.11173704092008@text.giganews.com> <18c765e0-1dcb-4e40-93a9-32bb9d129b7e@n38g2000prl.googlegroups.com> <af011a56-c10b-45a6-82cf-ffd5d20f37ca@j22g2000hsf.googlegroups.com> <mailman.542.1220603336.3487.python-list@python.org> <85c5bf48-65c9-4d45-ac12-272805f3e120@d45g2000hsc.googlegroups.com> <mailman.595.1220667618.3487.python-list@python.org> <00d1f730$0$20302$c3e8da3@news.astraweb.com> <92be31b9-dea4-44e2-9780-6416efee551d@d77g2000hsb.googlegroups.com> <00d34d6c$0$30713$c3e8da3@news.astraweb.com> <58a96145-6c22-413c-ac62-2ddd7c0af8ce@k7g2000hsd.googlegroups.com> <e01ccc30-54e5-4966-b12c-c893fb2be972@z66g2000hsc.googlegroups.com> Message-ID: <6b2d4059-6c80-4440-ae6f-dd2c67531236@l43g2000hsh.googlegroups.com> On Sep 7, 1:17?pm, Patrick Maupin <pmau... at gmail.com> wrote: > On Sep 7, 12:30?pm, Mensanator <mensana... at aol.com> wrote: > > > On Sep 6, 11:05 pm, Steven D'Aprano <st... at REMOVE-THIS- > > > Sheesh. That's not a problem, because Python is not trying to be a > > > dialect of SQL. > > > And yet, they added a Sqlite3 module. > > Does that mean that, because there is an 'os' module, Python is trying > to compete with Linux and Windows? I wasn't thinking "compete", rather "complement". Python obviously wants to be a player in the SQL market, so you would think it would be in Python's interest to know how SQL behaves, just as it's in Python's interest for the os module to know how BOTH Linnux and Windows work. > > This is starting to feel like a troll, It wasn't intended to be. > but JUST IN CASE you are really > serious about wanting to get work done with Python, rather than > complaining about how it is not perfect, Things never change if no one ever speaks up. > I offer the following snippet > which will show you how you can test the results of a sum() to see if > there were any items in the list: Thanks. I'll drop this from this point on. > > >>> class MyZero(int): > > ... ? ? pass > ... > > > > >>> zero = MyZero() > >>> x=sum([], zero) > >>> isinstance(x,MyZero) > True > >>> x = sum([1,2,3], zero) > >>> isinstance(x,MyZero) > False- Hide quoted text - > > - Show quoted text - From dullrich at sprynet.com Thu Sep 4 12:13:12 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Thu, 04 Sep 2008 11:13:12 -0500 Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> Message-ID: <dullrich-D271BF.11131204092008@text.giganews.com> In article <719910b1-3776-4bf2-a0b6-236f3167e9e3 at 25g2000prz.googlegroups.com>, Mensanator <mensanator at aol.com> wrote: > On Sep 3, 2:18?pm, Laszlo Nagy <gand... at shopzeus.com> wrote: > > bearophileH... at lycos.com wrote: > > > Empty Python lists [] don't know the type of the items it will > > > contain, so this sounds strange: > > > > >>>> sum([]) > > > > > 0 > > > > > Because that [] may be an empty sequence of someobject: > > > > You are right in that sum could be used to sum arbitrary objects. > > However, in 99.99% of the cases, you will be summing numerical values. > > When adding real numbers, the neutral element is zero. ( X + 0 = X) It > > is very logical to return zero for empty sequences. > > No it isn't. Nothing is not 0, check with MS-Access, for instance: > > Null + 1 returns Null. Any arithmetic expression involving a > Null evaluates to Null. Adding something to an unknown returns > an unknown, as it should. > > It is a logical fallacy to equate unknown with 0. Which has nothing to do with the "right" value for an empty sum. If they hear about what you said here in sci.math they're gonna kick you out - what do you imagine the universally accepted value of \sum_{j=1}^0 is? > For example, the water table elevation in ft above Mean Sea Level > is WTE = TopOfCasing - DepthToWater. > > TopOfCasing is usually known and constant (until resurveyed). > But DepthToWater may or may not exist for a given event (well > may be covered with fire ants, for example). > > Now, if you equate Null with 0, then the WTE calculation says > the water table elevation is flush with the top of the well, > falsely implying that the site is underwater. > > And, since this particular site is on the Mississippi River, > it sometimes IS underwater, but this is NEVER determined by > water table elevations, which, due to the CORRECT treatment > of Nulls by Access, never returns FALSE calculations. > > >>> sum([]) > 0 > > is a bug, just as it's a bug in Excel to evaluate blank cells > as 0. It should return None or throw an exception like sum([None,1]) > does. > > > > > Same way, if we would have a prod() function, it should return one for > > empty sequences because X*1 = X. The neutral element for this operation > > is one. > > > > Of course this is not good for summing other types of objects. But how > > clumsy would it be to use > > > > sum( L +[0] ) > > > > or > > > > if L: > > value = sum(L) > > else: > > value = 0 > > > > instead of sum(L). > > > > Once again, this is what sum() is used for in most cases, so this > > behavior is the "expected" one. > > > > Another argument to convince you: the sum() function in SQL for empty > > row sets returns zero in most relational databases. > > > > But of course it could have been implemented in a different way... I > > believe that there have been excessive discussions about this decision, > > and the current implementation is very good, if not the best. > > > > Best, > > > > Laszlo -- David C. Ullrich From mensanator at aol.com Sun Sep 28 18:06:58 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 28 Sep 2008 15:06:58 -0700 (PDT) Subject: generate random digits with length of 5 References: <e1923ff8-8150-41b6-9444-19c14b4d2f6f@8g2000hse.googlegroups.com> <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> <mailman.1641.1222632690.3487.python-list@python.org> <a380bc46-cf5f-4ae9-b1f2-d8789ba4f838@d45g2000hsc.googlegroups.com> <07d14730-a585-4976-adda-540d32a2066d@y38g2000hsy.googlegroups.com> Message-ID: <1d078691-662d-40a5-8519-62bee01dad4e@u65g2000hsc.googlegroups.com> On Sep 28, 3:54?pm, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 28, 3:44?pm, Mensanator <mensana... at aol.com> wrote: > > > > > > > On Sep 28, 3:11 pm, "Gary M. Josack" <g... at byoteki.com> wrote: > > > > Chris Rebert wrote: > > > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <soti... at gmail.com> wrote: > > > > >> Wondering if there is a better way to generate string of numbers with > > > >> a length of 5 which also can have a 0 in the front of the number. > > > > >> <pre> > > > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 > > > >> elements > > > >> code = 'this is a string' + str(random_number[0]) + > > > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3]) > > > >> + str(random_number[4]) > > > > > code = ''.join(str(digit) for digit in random_number) > > > > > Regards, > > > > Chris > > > > >> </pre> > > > > >> -- > > > >>http://mail.python.org/mailman/listinfo/python-list > > > > will random.randint(10000,99999) work for you? > > > It doesn't meet the OP's requirement that the number > > can start with 0. Also, the method the OP asks about > > returns a list of unique numbers, so no number can > > be duplicated. He can get 02468 but not 13345. > > > Now, IF it's ok to have an arbitrary number of leading > > 0s, he can do this: > > > >>> str(random.randint(0,99999)).zfill(5) > > '00089' > > >>> str(random.randint(0,99999)).zfill(5) > > '63782' > > >>> str(random.randint(0,99999)).zfill(5) > > '63613' > > >>> str(random.randint(0,99999)).zfill(5) > > > '22315' > > Is a while loop until there are 5 distinct digits best otherwise? Of course not. > > while 1: > ? a= '%05i'% random.randint( 0, 99999 ) > ? if len( set( a ) )== 5: break How is this better than the OP's original code? From sturlamolden at yahoo.no Tue Sep 23 16:34:10 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 23 Sep 2008 13:34:10 -0700 (PDT) Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <eogid4d6s2a5l55pu20220sr2bdt5s6hob@4ax.com> Message-ID: <c3f6f232-4165-495b-b998-cc813eae57ea@f63g2000hsf.googlegroups.com> On Sep 23, 10:05?pm, Robert Singer <rsinger at ____.com> wrote: > May I ask what are your main objections to it ? 1. gfortran is not Absoft. 2. If I program the same in C99 and Fortran 95, and compile with gcc and gfortran, the C99 code runs a lot faster (I've only tested with wavelet transforms). 3. gfortran is not Absoft. From sjmachin at lexicon.net Tue Sep 2 21:54:29 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 2 Sep 2008 18:54:29 -0700 (PDT) Subject: Is try-except slow? References: <0b6189d9-cd4c-4886-af22-1b4978de1c85@34g2000hsh.googlegroups.com> <2f0eef56-3e4e-463c-9d27-8b7d96298820@a2g2000prm.googlegroups.com> <183da55d-b5b7-4503-80de-77c97dcbd123@m3g2000hsc.googlegroups.com> <8b3857ec-e629-44a3-98f2-8fe509df7b75@f36g2000hsa.googlegroups.com> Message-ID: <870e4b08-610f-4037-89be-407677c790aa@b30g2000prf.googlegroups.com> On Sep 3, 11:14 am, process <circularf... at gmail.com> wrote: > is this faster btw? Time it and see. > I guess big doesn't help, it's only retrieved once > anyway? Correct. > But is rows retrieved in every loop? Of course. Read your own code! The point is that retrieving the list referenced by "rows" is much faster than creating it needlessly each time. > the python interpreter > aint too smart? It's smarter than some. The trade-off for having a very dynamic language is that some compile-time optimisations are more difficult. If you are interested in work (being)? done in this area, look at psyco and PyPy. From nagle at animats.com Sun Sep 7 22:52:07 2008 From: nagle at animats.com (John Nagle) Date: Sun, 07 Sep 2008 19:52:07 -0700 Subject: Use BeautifulSoup to delete certain tag while keeping its content In-Reply-To: <mailman.637.1220738822.3487.python-list@python.org> References: <mailman.637.1220738822.3487.python-list@python.org> Message-ID: <48c48e4b$0$17163$742ec2ed@news.sonic.net> Jackie Wang wrote: > Dear all, > > I have the following html code: > > <td valign="top" headers="col1"> > <font size="2"> > Center Bank > <br /> > Los Angeles, CA > </font> > </td> > > <td valign="top" headers="col1"> > <font size="2"> > Salisbury > Bank and Trust Company > <font face="arial, helvetica" size="2" color="#0000000"> > <br /> > Lakeville, CT > </font> > </font> > </td> > > How should I delete the 'font' tags while keeping the content inside? See the BeautifulSoup documentation. Find the font tags with findAll, make a list, then go in and use "extract" and "replaceWith" appropriately. John Nagle From castironpi at gmail.com Tue Sep 23 22:24:00 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 19:24:00 -0700 (PDT) Subject: python syntax for conditional is unfortunate References: <mailman.1434.1222213968.3487.python-list@python.org> <ee44675b-04ad-48b3-8eed-629ebb10d616@z66g2000hsc.googlegroups.com> <mailman.1440.1222221042.3487.python-list@python.org> Message-ID: <ff83a928-f398-41f7-857c-4d8226a89335@j22g2000hsf.googlegroups.com> On Sep 23, 8:50?pm, Neal Becker <ndbeck... at gmail.com> wrote: > Aaron "Castironpi" Brady wrote: > > On Sep 23, 6:52 pm, Neal Becker <ndbeck... at gmail.com> wrote: > >> In hindsight, I am disappointed with the choice of conditional syntax. ?I > >> know it's too late to change. ?The problem is > > >> y = some thing or other if x else something_else > > >> When scanning this my eye tends to see the first phrase and only later > >> notice that it's conditioned on x (or maybe not notice at all!). > >> Particularly if 'some thing or other' is long or complicated. > > > You're talking strictly about readability, which among other things is > > in the eye of the beholder, of course. ?Temporary variables can clean > > up some code, even if choosing names can be a hassle and it's more > > things to keep track of. ?Long lines and extra variables form a trade- > > off. ?You are writing a line with a conditional expression the value > > of which depends on something. ?What does it depend on, what is its > > value if that's true, and what is it if it's false? ?'...if...else...' > > only takes 6 characters... maybe you want more! > > > If you're looking for a strictly syntactic construct, you can always > > "fire blanks", or tracers, if the analogy's more accurate. > > > z= conditionally( x ) if b else y > > > This could serve as a gentle reminder, even where 'conditionally' > > returns its argument, i.e. is the identity function. ?You can always > > roll your own ternary with extra parameters too: > > > z= condition( b, x, y ) > > > Just don't confuse it with threading.Condition. > > > Otherwise, you're stuck with old syntax markers, and unless you > > wanted: > > > z= if b then x else y > > > You're out of options. ?You have to express it somehow. ?Did you want > > the condition first? ?Was there an alternative proposal you > > preferred? ?IINM if I'm not mistaken, > > > z= b and x or y > > > works just the same so long as x evaluates to True, as it will be > > tested. > > > Feel free to write your own from scratch, and we'll see how close > > Python can come to resembling it. > > > I suppose you can compare it to someone who stops listening before the > > word 'if', and completely misunderstands your statement. ?"Feed the > > dog if he's standing near the food dish" != "Feed the dog", which can > > of course lead to errors of both omission and commission (doing too > > little -or- too much). ?There's no way to fix that in a guaranteed > > way, except to say, "listen to the whole statement". > > > And strictly sarcastically, what did you want to do with reading the > > program? ?Why were you reading it? ?<snicker, ducks> > > I find I'm often tripped up by: > > x = Y (lots of ?constructor arguments....) if something ... > > on first glance, I don't notice the if. > > Why am I reading this? ?Umm, because I wrote it. Put it somewhere you'll notice! From castironpi at gmail.com Tue Sep 16 21:39:01 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 16 Sep 2008 18:39:01 -0700 (PDT) Subject: ka-ping yee tokenizer.py References: <mailman.1139.1221594553.3487.python-list@python.org> Message-ID: <63a54182-9d0e-4a42-a8b9-da29029d0125@25g2000hsx.googlegroups.com> On Sep 16, 2:48?pm, "Karl Kobata" <karl.kob... at syncira.com> wrote: > Hi Fredrik, > > This is exactly what I need. ?Thank you. > I would like to do one additional function. ?I am not using the tokenizer to > parse python code. ?It happens to work very well for my application. > However, I would like either or both of the following variance: > 1) I would like to add 2 other characters as comment designation > 2) write a module that can readline, modify the line as required, and > finally, this module can be used as the argument for the tokenizer. > > Def modifyLine( fileHandle ): > ? # readline and modify this string if required > ... > > For token in tokenize.generate_tokens( modifyLine( myFileHandle ) ): > ? ? ? ? Print token > > Anxiously looking forward to your thoughts. > karl > > -----Original Message----- > From: python-list-bounces+kkobata=syncira.... at python.org > > [mailto:python-list-bounces+kkobata=syncira.... at python.org] On Behalf Of > Fredrik Lundh > Sent: Monday, September 15, 2008 2:04 PM > To: python-l... at python.org > Subject: Re: ka-ping yee tokenizer.py > > Karl Kobata wrote: > > > I have enjoyed using ka-ping yee's tokenizer.py. ?I would like to > > replace the readline parameter input with my own and pass a list of > > strings to the tokenizer. ?I understand it must be a callable object and > > iteratable but it is obvious with errors I am getting, that this is not > > the only functions required. > > not sure I can decipher your detailed requirements, but to use Python's > standard "tokenize" module (written by ping) on a list, you can simple > do as follows: > > ? ? ?import tokenize > > ? ? ?program = [ ... program given as list ... ] > > ? ? ?for token in tokenize.generate_tokens(iter(program).next): > ? ? ? ? ?print token > > another approach is to turn the list back into a string, and wrap that > in a StringIO object: > > ? ? ?import tokenize > ? ? ?import StringIO > > ? ? ?program = [ ... program given as list ... ] > > ? ? ?program_buffer = StringIO.StringIO("".join(program)) > > ? ? ?for token in tokenize.generate_tokens(program_buffer.readline): > ? ? ? ? ?print token > > </F> > > --http://mail.python.org/mailman/listinfo/python-list > > This is an interesting construction: >>> a= [ 'a', 'b', 'c' ] >>> def moditer( mod, nextfun ): ... while 1: ... yield mod( nextfun( ) ) ... >>> list( moditer( ord, iter( a ).next ) ) [97, 98, 99] Here's my point: >>> a= [ 'print a', 'print b', 'print c' ] >>> tokenize.generate_tokens( iter( a ).next ) <generator object at 0x009FF440> >>> tokenize.generate_tokens( moditer( lambda s: s+ '#', iter( a ).next ).next ) It adds a '#' to the end of every line, then tokenizes. From bearophileHUGS at lycos.com Thu Sep 11 12:31:31 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Sep 2008 09:31:31 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <mailman.876.1221142791.3487.python-list@python.org> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> Message-ID: <8716c7a6-e3f1-4e68-b533-705d31599a97@p25g2000hsf.googlegroups.com> carriere.jonat...: > I want to build a desktop application. I am searching for some kind of > environment that would provide all the elements ready (Windows...). > Then I would have to code the business logic only. I don't think there's such thing in Python, "all elements ready" sounds strange :-) Maybe you may appreciate Dabo: http://dabodev.com/ Or maybe Pythoncard? Bye, bearophile From hniksic at xemacs.org Tue Sep 16 05:03:59 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 16 Sep 2008 11:03:59 +0200 Subject: append on lists References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> Message-ID: <87d4j4798g.fsf@mulj.homelinux.net> Duncan Booth <duncan.booth at invalid.invalid> writes: > The only relatively common use I can think of where you might want to call > a method directly on a literal is to produce a list of strings while being > lazy about the typing: By far the most common is probably 'sep'.join(iterable). From adityashukla1983 at gmail.com Wed Sep 10 13:37:25 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Wed, 10 Sep 2008 12:37:25 -0500 Subject: File operations Message-ID: <73045cca0809101037i6cc1e945tcf8d2fb9761b52b4@mail.gmail.com> Hello folks, I am using Python-2.5.2 on fedora 9 sulphur -2.6.25-14.fc9.i686.I am creating a temporary file , in which data is written by another program and then i am using that temporary file to do my computations.I am new to linux and i am facing two issues homedir = os.path.expanduser('~') temp = tempfile.NamedTemporaryFile( suffix='_suffix',prefix='prefix_',dir= homedir) temp.close() tn = temp.name print tn Issue1 -> when i am logged in as root then everything works fine except that the file is created in the current working directory (/usr/Python-2.5.2) and not in the directory supplied as the dir='directory' parameter.i have tried dir='/tmp' as well.i don't know how to fix this issue and why the file is not getting created in the specified directory. Issue2 -> when i am logged in as user ie any other user than root then i get this error sh: prefix_u92XQJ_suffix: Permission denied also , i cannot find the find in either the current working directory nor in the dir='directory'.so i cant check the permission by using ls -l prefix_u92XQJ_suffix Please help me understand this issue and eventually fix it. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080910/c03f9802/attachment-0001.html> From invalid at nowhere.invalid.org Tue Sep 16 07:22:46 2008 From: invalid at nowhere.invalid.org (Alex Marandon) Date: Tue, 16 Sep 2008 12:22:46 +0100 Subject: append on lists In-Reply-To: <gao3d0$7q1$1@online.de> References: <gamffv$qms$1@online.de> <mailman.1064.1221510115.3487.python-list@python.org> <gamgn9$5r5$1@online.de> <9dc64c3a-6a28-4f9e-8bb2-2c23d24346db@z6g2000pre.googlegroups.com> <ganpdo$1gf$1@online.de> <mailman.1098.1221552919.3487.python-list@python.org> <Xns9B1B64E0F6C29duncanbooth@127.0.0.1> <gao3d0$7q1$1@online.de> Message-ID: <1221564169.16690.0@proxy00.news.clara.net> Armin wrote: > Duncan Booth wrote: > > The semantic of [1,2,3,4,7].append(c) and [1,2,3,4,7] + c > (with c = [8,9]) is identical, No it's not, + doesn't alter its operands. >>> a = 1 >>> b = 2 >>> a + b 3 >>> a 1 Were you expecting a == 3? From mauriceling at gmail.com Thu Sep 4 08:58:21 2008 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Thu, 4 Sep 2008 05:58:21 -0700 (PDT) Subject: [ANN] The Python Papers, Volume 3 Issue 2 Message-ID: <3eb3b85a-67cc-4260-a86f-acee9c8f6eb8@q5g2000prf.googlegroups.com> Hi everyone After a long wait of nearly 5 month, we are back in business to bring the latest edition of The Python Papers - Volume 3 Issue 2 (http:// ojs.pythonpapers.org/index.php/tpp/issue/current). >From this issue onwards, we will be having only 3 issues per year instead of 4. This is in compliance with our ISSN registration. What's new ========= 1. We have expanded our editorial team with 2 new Associate Editors, Sarah Mount (from UK) and Guy Kloss from (New Zealand). 2. TPP is now managed using Open Journal System and it can be assessed at http://ojs.pythonpapers.org/tpp 3. Backporting of previous issues of TPP from Volume 1 Issue 1 is complete 4. We had "soft-launched" TWO new periodicals - The Python Papers Monographs (for monograph-length submissions which may include dissertations, conference proceedings, case studies and advanced-level lectures) and The Python Papers Source Codes (modeled after ACM Collected Algorithms and provides a collection of software and source codes, usually associated with papers published in The Python Papers and The Python Papers Monograph). They shall be TPPM and TPPSC respectively. 5. Collectively, TPP, TPPM and TPPSC will be umbrella-ed as The Python Papers Anthology (TPPA) and managed under the same editorial committee. 6. Probably the most important development to TPP is that TPP is currently indexed by a number of services, including Google Scholar and OAIster, as a result of using Open Journal System. So, please enjoy our latest edition and we look towards all of your continued support and contributions. Thank you. Cheers Maurice Ling Co-Editor-in-Chief, The Python Papers Anthology From Ron.Barak at lsi.com Wed Sep 24 03:54:24 2008 From: Ron.Barak at lsi.com (Barak, Ron) Date: Wed, 24 Sep 2008 08:54:24 +0100 Subject: How to copy a GUI2exe project - to serve as basis for new project ? In-Reply-To: <mailman.12523.1222237400.3486.python-list@python.org> References: <mailman.12523.1222237400.3486.python-list@python.org> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF6022A71DF@enbmail01.lsi.com> Hi, In GUI2exe, I'd like to create a project that is different from an existing project only in a few details (e.g., the location of the 'dist' directory). Is there a way to copy a current project - so it would serve as a basis for a new project ? Bye, Ron. From sebastianthegreatful at gmail.com Mon Sep 8 09:15:17 2008 From: sebastianthegreatful at gmail.com (Seb) Date: Mon, 8 Sep 2008 06:15:17 -0700 (PDT) Subject: flock trouble Message-ID: <1460c93c-af24-40a3-8be4-31d582d48cb1@y21g2000hsf.googlegroups.com> I'm trying to implement a file server using the code below. However the locking doesn't work. I can delete while put'ing a file. Anyone got an idea about why? best regards, seb #! /usr/bin/env python import Pyro.core, Pyro.naming from Pyro.errors import PyroError, NamingError import sys import urllib import os import fcntl class fileServer(Pyro.core.ObjBase): basePath = "/home/snot/diku/dist/opg2/files_to_serve" def __init__(self): Pyro.core.ObjBase.__init__(self) self.basePath = self.basePath.strip("..") if not os.path.isdir(self.basePath) or os.path.islink(self.basePath): raise "invalid path" def get(self, uri): f = open(self.basePath + uri, 'r+') fcntl.flock(f, fcntl.LOCK_SH) data = f.read() fcntl.flock(f, fcntl.LOCK_UN) f.close() return data def put(self, uri, payload): f = open(self.basePath + urllib.unquote_plus(uri), 'w') fcntl.flock(f, fcntl.LOCK_EX) f.truncate() f.write(payload) fcntl.flock(f, fcntl.LOCK_UN) f.close() def delete(self, uri): f = open(self.basePath + urllib.unquote_plus(uri), 'w') fcntl.flock(f, fcntl.LOCK_EX) os.unlink(self.basePath + uri) fcntl.flock(f, fcntl.LOCK_UN) f.close() try: Pyro.core.initServer() daemon = Pyro.core.Daemon() locator = Pyro.naming.NameServerLocator() print 'Searching for Name Server...' try: ns = locator.getNS() except Pyro.errors.PyroError, message: print message sys.exit(1) daemon.useNameServer(ns) try: ns.unregister("fileServer") except NamingError: pass uri = daemon.connect(fileServer(), "fileServer") print "The daemon runs on port:", daemon.port print "The object's uri is:", uri daemon.requestLoop() except KeyboardInterrupt: ns.unregister("fileServer") print "ctrl + c pressed" From mathieu.prevot at gmail.com Thu Sep 4 09:01:49 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Thu, 4 Sep 2008 15:01:49 +0200 Subject: use str as variable name In-Reply-To: <g9o7a9$t11$1@ger.gmane.org> References: <3e473cc60809040025l41b272b0q9bce5c83b1e6d246@mail.gmail.com> <47c890dc0809040036s85280bdgc91a710c36992248@mail.gmail.com> <mailman.464.1220515161.3487.python-list@python.org> <48bf9d12$0$7552$426a74cc@news.free.fr> <g9o7a9$t11$1@ger.gmane.org> Message-ID: <3e473cc60809040601t7ef63a1cr1265330043fa1247@mail.gmail.com> 2008/9/4 Fredrik Lundh <fredrik at pythonware.com>: > Bruno Desthuilliers wrote: > >> You wouldn't write something like 2.__add__(3), would you ? > > Don't give the "it's only OO if I write obj.method(args)" crowd more bad > ideas, please ;-) > > (...as Bruno implies, setattr(), len() et al can be and should be viewed as > generic functions. A specific Python implementation may use custom code to > implement behaviour for a given object; behaviour that's more efficient than > a full Python-level method call. For example, in CPython, len(L) is about > twice as fast as L.__len__() for built-in sequences.) Got it. Thanks :) Mathieu From tjreedy at udel.edu Mon Sep 1 02:27:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 01 Sep 2008 02:27:54 -0400 Subject: Python 3.0b2 cannot map '\u12b' In-Reply-To: <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> References: <d0652dd2-24f6-4045-89a8-ba6deaf25b37@c65g2000hsa.googlegroups.com> <qarmb417t40ktm1etvhpamkh64hhe253dj@4ax.com> Message-ID: <g9g219$1ak$1@ger.gmane.org> Tim Roberts wrote: > josh logan <dear.jay.logan at gmail.com> wrote: >> I am using Python 3.0b2. >> I have an XML file that has the unicode character '\u012b' in it, >> which, when parsed, causes a UnicodeEncodeError: >> >> 'charmap' codec can't encode character '\u012b' in position 26: >> character maps to <undefined> >> >> This happens even when I assign this character to a reference in the >> interpreter: >> >> Python 3.0b2 (r30b2:65106, Jul 18 2008, 18:44:17) [MSC v.1500 32 bit >> (Intel)] on >> win32 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> s = '\u012b' >>>>> s >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> File "C:\Python30\lib\io.py", line 1428, in write >> b = encoder.encode(s) >> File "C:\Python30\lib\encodings\cp437.py", line 19, in encode >> return codecs.charmap_encode(input,self.errors,encoding_map)[0] >> UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in >> position >> 1: character maps to <undefined> >> >> Is this a known issue, or am I doing something wrong? > > Both. U+012B is the Latin lower-case i with macron (i with a bar instead > of a dot). That character does not exist in the 8-bit character set CP437, > which you are trying to use. > > If you choose an 8-bit character set that includes i-with-macron, then it > will work. UTF-8 would be a good choice. It's in ISO-8859-10. I doubt the OP 'chose' cp437. Why does Python using cp437 even when the default encoding is utf-8? On WinXP >>> sys.getdefaultencoding() 'utf-8' >>> s='\u012b' >>> s Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Program Files\Python30\lib\io.py", line 1428, in write b = encoder.encode(s) File "C:\Program Files\Python30\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u012b' in position 1: character maps to <undefined> To put it another way, how can one 'choose' utf-8 for display to screen? Using IDLE, display works fine. IDLE 3.0b2 >>> s='\u012b' >>> s '?' # i macron >>> import sys >>> sys.getdefaultencoding() 'utf-8' I ran across this is a different context and mentioned it on the bug tracker, but the Windows interpreter seems broken here. I will send this in UTF-8 so the i-macron will hopefully show up. tjr From invalid at invalid Tue Sep 23 17:18:11 2008 From: invalid at invalid (Grant Edwards) Date: Tue, 23 Sep 2008 16:18:11 -0500 Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> Message-ID: <4d6dnWXRMfiOwETVnZ2dnUVZ_jqdnZ2d@posted.visi> On 2008-09-23, Drake <cjdrake at gmail.com> wrote: > My group is developing a medium-sized library of general-purpose > Python functions, some of which do I/O. Therefore it is possible for > many of the library functions to raise IOError Exceptions. The > question is: should the library function be able to just dump to > sys.exit() with a message about the error (like "couldn't open this > file"), No. A library module should never call sys.exit(). > or should the exception propagate to the calling program which > handles the issue? Yes. Let the application handle the error if it wants to. If it's not handled, it'll end up causing the program to exit. -- Grant Edwards grante Yow! It's a hole all the at way to downtown Burbank! visi.com From gh at ghaering.de Thu Sep 4 07:08:59 2008 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Thu, 04 Sep 2008 13:08:59 +0200 Subject: cPickle In-Reply-To: <01f901c90e70$8e118a50$2fc513ac@pwit.com> References: <01f901c90e70$8e118a50$2fc513ac@pwit.com> Message-ID: <g9ofjv$44p$1@ger.gmane.org> gopal mishra wrote: > I have 3 objects and want to save in one pickle file. > > I used cPickle to dump 3 objects in a pkl file > > i.e cPickle.dump(object1, fileobject, -1) > > cPickle.dump(object2, fileobject, -1) > > cPickle.dump(object3, fileobject, -1) > > > > I have changed the 3^rd object and want to save the updated 3^rd object > in the pickle file. > > I have to dump all the 3 objects again. > > Is there any way to dump only the 3^rd object in to the pkl file. No, there isn't. You could, of course, save each object in its own pickle file. Or use an object database like ZODB instead. -- Gerhard From workitharder at gmail.com Wed Sep 3 17:46:00 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 3 Sep 2008 14:46:00 -0700 (PDT) Subject: Late initialization using __getattribute__ References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> Message-ID: <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> On Sep 3, 12:19?pm, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > bukzor a ?crit : > > > I want to make a MixIn class that waits to initialize its super- > > classes until an attribute of the object is accessed. Not generally > > useful, but desirable in my case. I've written this, and it works, but > > would like to take any suggestions you guys have. > > You shouldn't mess with __getattribute__ unless you really know what > you're doing and are ok to suffer the constant performance hit you'll > get. Remember that __getattribute__ actually *is* the implementation of > attribute lookup rules, and is called on each and every attribute > lookup. Your below snippet would be much better using __getattr__ (which > is only called as a last resort). > > > I've commented out > > the "delattr" call because it throws an AttributeError (although I > > don't know why). > > __getattribute__ belongs to the class, not to the instance. delattr() > only removes instance attributes. You'd have to remove __getattribute__ > from the LateInitMixIn class object itself, but then it would break the > whole thing. > > > > > class LateInitMixIn(object): > > ? ? def __init__(self): > > ? ? ? ? print "LateInit initialization" > > ? ? ? ? self.inited = False > > ? ? def __getattribute__(self, attr): > > ? ? ? ? print "Doing __getattribute__" > > ? ? ? ? getattr = lambda attr:object.__getattribute__(self, attr) > > ? ? ? ? if not getattr("inited"): > > ? ? ? ? ? ? super(LateInitMixIn, self).__init__() > > ? ? ? ? ? ? setattr(self, "inited", True) > > ? ? ? ? #delattr(self, "__getattribute__") > > ? ? ? ? return getattr(attr) > > Here's another possible implementation (which doesn't solve all > problems, cf below) using __getattr__: > > class LateInitMixin(object): > ? ? ?def __init__(self): > ? ? ? ? ?print "not yet" > ? ? ? ? ?self.__initialized = False > > ? ? ?def __getattr__(self, name): > ? ? ? ? ?if self.__initialized: > ? ? ? ? ? ? ?raise AttributeError( > ? ? ? ? ? ? ? ? ?"object %s has no attribute '%s'" % (type(self), name) > ? ? ? ? ? ? ? ? ?) > ? ? ? ? ?super(LateInitMixin, self).__init__() > ? ? ? ? ?self.__initialized = True > ? ? ? ? ?return getattr(self, name) > > class Base(object): > ? ? ?def __init__(self): > ? ? ? ? ?print "yet" > ? ? ? ? ?self.base = True > > class LateInit(LateInitMixin, Base): > ? ? ?pass > > def main(): > ? ? ?print "shouldn't init" > ? ? ?S = LateInit() > ? ? ?print "should init" > ? ? ?print S.base > > if __name__=="__main__": > ? ? ?main() > > Ok, now, the other problem : what if Base.__init__ expects args ? Thanks for the reply. Just to see it not work, I tried to remove __getattribute__ from LateInitMixIn, but couldn't get it to work. My Base class is a C class (_mysql.connection from MySQLdb) that sometimes segfaults if you try to use it before it's fully initialized, so unfortunately I think I need to use __getattribute__ to do this. I'm doing all this just to make the connection not actually connect until used. From paul at boddie.org.uk Mon Sep 29 10:14:49 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 29 Sep 2008 07:14:49 -0700 (PDT) Subject: closures and dynamic binding References: <2d88b068-0f87-4879-9680-51b554bf0cc3@l64g2000hse.googlegroups.com> <00ef3194$0$20666$c3e8da3@news.astraweb.com> <d363b399-3e4d-49c9-b1c8-c508b3c7e147@d1g2000hsg.googlegroups.com> <mailman.1648.1222638470.3487.python-list@python.org> <3c75ce4b-bb58-4da4-9b7a-87d7c5d5d2d0@m45g2000hsb.googlegroups.com> <mailman.1661.1222660566.3487.python-list@python.org> Message-ID: <3d4e4abd-89b6-411a-b812-e644793c18d4@59g2000hsb.googlegroups.com> On 29 Sep, 05:56, Terry Reedy <tjre... at udel.edu> wrote: > > As I understand it, partly from postings here years ago... > > Lexical: The namespace scope of 'n' in inner is determined by where > inner is located in the code -- where is is compiled. ?This is Python > (and nearly all modern languages). ?Even without closures, the global > scope of a function is the module it is defined in. This is how I understand it, too. The confusing part involves the definition of any inner function and how any "external" names are bound or defined. As we've seen... def f(x): def g(): return x x += 1 # added for illustration return g ...it might look at first glance like the function known as g (within f) should return the initial value of x (as known within f), since that was the value x had when g was defined. The following is an example execution trace based on that mental model: fn = f(1) -> def f(1): -> def g(): # g defined with x as 1 -> return x # would be 1 -> x += 1 # x becomes 2 -> return g fn() -> def g(): -> return x # would still be 1 However, as we know, this isn't the case in real Python since g isn't initialised with the value of x at the time of its definition - it instead maintains access to the namespace providing x. We must therefore revise the example: fn = f(1) -> def f(1): -> def g(): # g refers to x within f(1) -> return x # would be the current value of x within f(1) -> x += 1 # x becomes 2 -> return g fn() -> def g(): # g refers to x within f(1) -> return x # would be the current value of x within f(1), which is 2 This is the dynamic aspect of closures: values aren't used to initialise inner functions; names are looked up from their origin. > Dynamic: The namespace scope of 'n' in inner, how it is looked up, is > determined by where inner is called from. This is what you seemed to be > suggesting -- look up 'n' based on the scope it is *used* in. Indeed. Dynamic scoping is confusing in that one has to set up an appropriate "environment" for the closure to access so that references to names can be meaningfully satisfied; obviously, this creates all sorts of encapsulation problems. The confusing aspect of lexical scoping, however, especially if non-local names can be changed, is that the effects of closures are potentially distant - one doesn't always invoke inner functions in the place where they were defined, as we see above - and such effects may thus happen within "abandoned namespaces" - that is, namespaces which can no longer be revisited and used in their original context. So, in the above, once f has been invoked, the namespace for that invocation effectively lives on, but that namespace is not a general one for f - if we invoke f again, we get another namespace as one should reasonably expect. A somewhat separate issue is illustrated by the modification of x within f. Although for most statements, we would expect the value of x to evolve following from a top-to-bottom traversal of the code within a unit, function definition statements do not behave like, say, "for", "if" or "while" statements. Now although this should be obvious at the module global level, I feel that it can be easy to overlook within a function where one normally expects to find plain old control-flow constructs, expressions, assignments and so on. It is pertinent to note, with respect to the original inquiry, that lambda functions are subject to the same caveats, and I believe that lexical scoping was introduced precisely to make lambda functions less cumbersome to employ, eliminating the need to explicitly initialise them using the "identity" default parameters trick, but obviously introducing the consequences and potential misunderstandings described above. Paul From bhood37 at hotmail.com Thu Sep 4 17:33:50 2008 From: bhood37 at hotmail.com (Uberman) Date: Thu, 04 Sep 2008 15:33:50 -0600 Subject: Happy fun time with SWIG Message-ID: <5vYvk.75246$C65.45163@en-nntp-01.dc1.easynews.com> I have a bit of a odd arrangement here with SWIG, Python, Embedded Python and C++ classes exported into Python. Here's the plot: I have a class defined in a C++ DLL library. I am wrapping this class (we'll call it "Peter") with SWIG so some of its base functionality is available in Python. For the sake of this example, Peter has a method called get_type(), that takes no arguments and returns an integer. This all works, and within my Python environment I can create instances of Peter, copy them, query their values -- everything I need to do with them. I've tested all this from the Python interpreter with expected results. Peter exists functionally within Python's environment. However, I am also embedding Python into an application, an application that needs to execute the Python module that makes heavy use of Peter (A-ha! The plot thickens!). Peter's instance within the Python environment contains singular data, set within the Python environment, that I need to access from within the embedded Python code. I also use C++ instances of Peter within my C++ code. Here's an example of what I'm looking at: # this is the SWIG generated Python import module from Peter import * class BaseClass: def __init__(self): self.peters = [] class SubClass(BaseClass): def __init__(self): BaseClass.__init__(self) my_peter = Peter(0) self.peters.append(my_peter) Then, in my embedded code, after creating an instance of the Python SubClass: ... PyObject* key = PyString_FromString("peters"); PyObject* py_peters = PyObject_GetAttr(py_SubClass_inst,key); Py_XDECREF(key); if(!py_peters || !PyList_Check(py_peters)) // handle this error for(int j = 0;j < PyList_Size(py_peters);j++) { PyObject* py_peter = PyList_GetItem(py_peters,j); PyObject* py_peter_method = PyObject_GetAttrString(py_peter, "get_type"); if(!py_peter_method || !PyCallable_Check(py_peter_method)) continue; PyThreadState* old_thread_state = PyThreadState_Swap(my_interpreter); PyObject* pargs = Py_BuildValue("( )"); PyObject* py_peter_type = PyEval_CallObject(py_peter_method, pargs); ... So, right here in PyEval_CallObject(), we are invoking the SWIG-generated code to execute Peter's get_type() C++ method. However, this call is returning -1 (not a value coded into Peter's get_type() method). I debugged into the SWIG code, and I see that I'm getting a PyExc_TypeError error, with a the message that looks something like: in method 'Peter_get_type', argument 1 of type 'Peter const *' Checking the watch window, the PyObject->obj_type->tp_name of "py_peter" is "Peter" (not "instance", as I've seen it set to before with other Python attributes). This leads me to believe that what I'm dealing with is not actually an instance of Peter, but rather a class template of Peter. This confuses me, because I thought I initialized the peters[] arrays with instances. Anybody have any helpful insights on this? Why is SWIG barfing? Am I perhaps accessing the Peter instance incorrectly? Many thanks in advance. From bellman at lysator.liu.se Thu Sep 4 13:31:20 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 4 Sep 2008 17:31:20 +0000 (UTC) Subject: max(), sum(), next() References: <24061e7d-935a-442f-8d50-b8619d5581d3@34g2000hsh.googlegroups.com> <mailman.438.1220469507.3487.python-list@python.org> <719910b1-3776-4bf2-a0b6-236f3167e9e3@25g2000prz.googlegroups.com> <00cf3495$0$20302$c3e8da3@news.astraweb.com> <46931979-edaa-4c67-bd07-4cb6c0e5c0e1@1g2000pre.googlegroups.com> <00cf79ec$0$20302$c3e8da3@news.astraweb.com> <56cbb47a-efda-45bc-b595-db30d64e2ddf@w24g2000prd.googlegroups.com> <g9o1bf$dsf$1@news.lysator.liu.se> <55551dc6-2a3a-4126-b8eb-8289623b158c@25g2000prz.googlegroups.com> Message-ID: <g9p618$o0h$1@news.lysator.liu.se> Mensanator <mensanator at aol.com> wrote: > Ok, but I don't understand why an empty list is a valid sum > whereas a list containing None is not. You can't conclude the behaviour of the one from the behaviour of the other, because the two situations have nothing at all in common. >> As it happens, the SQL sum() function (at least in MySQL; I don't >> have any other database easily available, nor any SQL standard to >> read) does return NULL for a sum over the empty sequence, so you >> could argue that that would be the correct behaviour for the >> Python sum() function as well, but you can't argue that because a >> sum *involving* a NULL value returns NULL. > I'm not following that. Are you saying a query that returns no > records doesn't have a specific field containg a Null so there > are no Nulls to poison the sum? ...tap...tap...tap. Ok, I can see > that, Exactly. > but you don't get 0 either. That's because the SQL sum() has a special case for "no rows returned". A *different* special case than the one that taint's the sum when encountering a NULL. It does the equivalent of if len(rows_returned) == 0: # Special case for no rows returned return NULL total = 0 for row in rows_returned: value = row[column] if value is NULL: # Special case for encountering a NULL value return NULL total += value return total Two different special cases for the two different situations. If you were to remove the special case for no rows returned, you would get zero when the SELECT statement finds no rows, but the sum would still be tainted when a NULL value is encountered.. The definition of sum in mathematics *does* do away with that special case. The sum of zero terms is zero. And the Python sum() function follows the mathematics definition in this respect, not the SQL definition. You can argue that Python sum() should have special cased the empty sequence. It's not an illogical stance to take. It's just a totally different issue from encountering a non-numeric element in the sequence. In some cases it might actually make sense to treat the empty sequence as an error, but just ignore non-numeric elements (i.e, treat them as if they were zero). And in some cases both should be an error, and in some neither should be an error. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "You are in a twisty little passage of ! bellman @ lysator.liu.se standards, all conflicting." ! Make Love -- Nicht Wahr! From ireborin at delete.this.gmail.com Mon Sep 22 22:19:49 2008 From: ireborin at delete.this.gmail.com (Ivan Reborin) Date: Tue, 23 Sep 2008 04:19:49 +0200 Subject: gplt from scipy missing ? Message-ID: <lckgd4dsk4hqfsibr5ldv3tnc3dl6lfvum@4ax.com> I'm relatively new to python. I'm following a tutorial I found on the net, and it uses scipy's gplt for plotting. I installed scipy from their website (win32 installation), numpy also, but when I do from scipy import gplt it gives this error: Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from scipy import gplt ImportError: cannot import name gplt Please, can you help me solve this ? How do I get gplt to work ? All advice appreciated. Best regards Ivan From gagsl-py2 at yahoo.com.ar Fri Sep 19 22:03:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 23:03:33 -0300 Subject: Out of memory issue with dialog box References: <ea3cb13c-1793-46fb-86cc-2a4a6861b750@k30g2000hse.googlegroups.com> Message-ID: <op.uhrbz7uvx6zn5v@gabriel2.softlabbsas.com.ar> En Thu, 18 Sep 2008 13:32:32 -0300, <numan.salati at gmail.com> escribi?: > We have a mutilthreaded process in which one of the threads uses too > much memory causing the process to run out of memory. However when > this happens we see a dialog box pop up with the message "fatal error > in GC : too many heap sections." When you click "ok" only then does > the process die. That message comes from the Boehm garbage collection library; Python does not use it. Check any compiled extension in use. -- Gabriel Genellina From mail at johnlawrence.net Thu Sep 11 06:51:53 2008 From: mail at johnlawrence.net (John Lawrence) Date: Thu, 11 Sep 2008 11:51:53 +0100 Subject: Adding environment variables to bash. In-Reply-To: <gaaotj$305$1@ger.gmane.org> References: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> <gaan73$so4$1@ger.gmane.org> <18e8b60e0809110228s4920689eua391797220e87175@mail.gmail.com> <gaaotj$305$1@ger.gmane.org> Message-ID: <18e8b60e0809110351o35202c23ied4a1e8e3270d684@mail.gmail.com> > > doesn't exactly work for Python scripts, though: > True, but you can use it in the following (admittedly messy) way: jl> cat setenv.sh /usr/bin/env python $@ . ./settmp rm settmp jl> cat env.py #!/usr/bin/python command = "export TEST='hello'\n" open('settmp', 'w').write(command) jl> . setenv.sh env.py && env | grep TEST TEST=hello Note this won't set the environment variable until the end of the script, so if it's used in the script as well then it'll also need to be set with, for example, os.environ["TEST"] = "hello" John. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080911/b363be28/attachment-0001.html> From siegfried at heintze.com Sun Sep 14 02:51:39 2008 From: siegfried at heintze.com (Siegfried Heintze) Date: Sat, 13 Sep 2008 23:51:39 -0700 Subject: How does python call OS? Message-ID: <f9idnWTIta_gKVHVnZ2dnUVZ_gCdnZ2d@comcast.com> I just finished reading a chapter in "Python Programming on Win32" and tried out the pythonwin scribble application. I'm not sure if I got it right because I could not open a new document. I tried to download the source code as referenced in the chm file but it is corrupted. I cut and pasted from my softcopy of the book. I see the next sub-chapter on wxWindows for python and the previous sub-chapter on TK. This is looking a lot like other scripting languages (such as perl and groovy and even java). Can python call anything directly or does someone have to write a DLL in C/C++ that calls the function first? Thanks! Siegfried From blabla at dungeon.de Wed Sep 10 11:28:43 2008 From: blabla at dungeon.de (hofer) Date: Wed, 10 Sep 2008 08:28:43 -0700 (PDT) Subject: dict slice in python (translating perl to python) Message-ID: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Hi, Let's take following perl code snippet: %myhash=( one => 1 , two => 2 , three => 3 ); ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest print "$v1\n$v2\n$v2\n"; How do I translate the second line in a similiar compact way to python? Below is what I tried. I'm just interested in something more compact. mydict={ 'one' : 1 , 'two' : 2 , 'three' : 3 } # first idea, but still a little too much to type [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']] # for long lists lazier typing,but more computational intensive # as split will probably be performed at runtime and not compilation time [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()] print "%s\n%s\n%s" %(v1,v2,v3) thanks for any ideas From luke.hamilton at rpm-solutions.com.au Mon Sep 8 10:03:44 2008 From: luke.hamilton at rpm-solutions.com.au (Luke Hamilton) Date: Mon, 8 Sep 2008 09:03:44 -0500 Subject: Web shopping carts Message-ID: <C4EB6DE0.11187%luke.hamilton@rpm-solutions.com.au> Hey People, I am wondering if there are any OS shopping cart application written in python? Regards, Luke Hamilton Solutions Architect RPM Solutions Pty. Ltd. Mobile: 0430 223 558 luke.hamilton at rpm-solutions.com.au -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080908/4edc188d/attachment-0001.html> From python at bdurham.com Mon Sep 1 15:03:04 2008 From: python at bdurham.com (python at bdurham.com) Date: Mon, 01 Sep 2008 15:03:04 -0400 Subject: Benchmark differences between 32 and 64 bit Python? In-Reply-To: <48BC13CD.1010704@timgolden.me.uk> References: <6599d785-87b2-4bbc-97bc-799cac3640f5@b1g2000hsg.googlegroups.com> <48BC13CD.1010704@timgolden.me.uk> Message-ID: <1220295784.9450.1271593301@webmail.messagingengine.com> Anyone have any benchmarks on the difference in performance between 32 and 64 bit versions of Python for specific categories of operation, eg. math, file, string, etc. operations? My question is OS neutral so feel free to share your experience with either Windows or Linux OS's. Thank you, Malcolm From mailcindy at gmail.com Tue Sep 30 10:27:41 2008 From: mailcindy at gmail.com (cindy jones) Date: Tue, 30 Sep 2008 19:57:41 +0530 Subject: How to add CC and BCC while sending mails using python Message-ID: <46da4e770809300727j368a27b8qc570a8451a53e470@mail.gmail.com> Hello all, Can someone tel me how to add cc's and bcc's while sending mails using python Thank you all -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/3af4a690/attachment-0001.html> From circularfunc at yahoo.se Sat Sep 6 18:13:45 2008 From: circularfunc at yahoo.se (cnb) Date: Sat, 6 Sep 2008 15:13:45 -0700 (PDT) Subject: Cathing several potential errors? Message-ID: <c74c4be6-0019-4729-a79b-2af2d37a6969@m36g2000hse.googlegroups.com> if i do try: something except TypeError, IndexError: pass only the first error will get caught. I dont want to use Exception and catch all errors, but just 2. how can i do that? From diesch at spamfence.net Thu Sep 11 08:14:12 2008 From: diesch at spamfence.net (Florian Diesch) Date: Thu, 11 Sep 2008 14:14:12 +0200 Subject: formating a filesystem with python References: <mailman.828.1221080255.3487.python-list@python.org> Message-ID: <llenp5-th8.ln1@mid.florian-diesch.de> "Ricardo Tiago" <rtiago at gmail.com> wrote: > is there a package in python that allows to mount/umount and format > (to ext3) a filesystem? I know that this is possible by just calling > the os commands 'mount/umount and mkfs' but this would imply to have > to change sudoers to run the script as non-root. On Linux (I guess that"s the target OS as you mentioned ext3) mounting could be done as non-root using FUSE or HAL (maybe using a frontend like gio or kio) if the system supports that, or with an appropriate fstab entry. Maybe HAL can configured to do mkfs but that has to be done very carefully to avoid security problems. Maybe you could use something like AppArmor, too. Most likely you get better answers by first asking in a Linux group how to do this things without root privileges and then come back to ask how to do it with Python. Florian -- <http://www.florian-diesch.de/> ----------------------------------------------------------------------- ** Hi! I'm a signature virus! Copy me into your signature, please! ** ----------------------------------------------------------------------- From bearophileHUGS at lycos.com Thu Sep 11 08:54:15 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 11 Sep 2008 05:54:15 -0700 (PDT) Subject: removing text string References: <loom.20080910T144026-626@post.gmane.org><mailman.814.1221069201.3487.python-list@python.org> <xqWdnQ2Hm7s1vlXVnZ2dnUVZ_sLinZ2d@earthlink.com> <mailman.865.1221136393.3487.python-list@python.org> Message-ID: <514c0466-3142-43e7-abc6-f75fb139e25e@c65g2000hsa.googlegroups.com> Ahmed, Shakir: > Actually the number I am getting it is from slicing from a long text > line. I need to slice 10 characters from that line but no string only > numeric numbers. When I am slicing 10 characters those A, c, O is coming > at the end. It's better to avoid Regular expressions when they aren't necessary, but once in a while they are the simpler way to solve a problem, you may create one like this (mostly untested): \d+?-\d+ Using it like: >>> import re >>> patt = re.compile(r"\d+?-\d+") >>> patt.search("xxxxxx080829-7_A xxxx").group() '080829-7' >>> re.search(r"\d+?-\d+", "xxxxxx080829-7_A xxxx").group() '080829-7' Learning Regexps can be useful. Bye, bearophile From ggpolo at gmail.com Thu Sep 4 23:25:23 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Fri, 5 Sep 2008 00:25:23 -0300 Subject: Tkinter Radio button on the second window In-Reply-To: <e5da0605-0dc4-41fe-9a9f-fa75b9094e5a@b30g2000prf.googlegroups.com> References: <e5da0605-0dc4-41fe-9a9f-fa75b9094e5a@b30g2000prf.googlegroups.com> Message-ID: <ac2200130809042025qde8f760p1cfb25e8e63ce4b8@mail.gmail.com> On Thu, Sep 4, 2008 at 10:01 PM, Dream <god1124 at gmail.com> wrote: > The code create 2 windows. 2 radiobuttons are put on the second > window. A control variable "v" is binded to the 2 widgets. > But when I run the code, I found the control variable not binded > succsessfully: The second radiobutton was not selected by default; > Click ed each button always print 1. I don't know what is wrong. So I > need help.Thanks. > > from Tkinter import * > > def test(event_instance): > print v.get() > > window1=Tk() > window2=Tk() Now you have created two Tcl interpreters, and Tkinter stores the "default master" as the first one created, so window1 is the default master. > v=IntVar() Here is your variable with no master specified, meaning it will use the default master, "window1". > v.set(1) > radiobutton1=Radiobutton(window2,variable=v,value=0) > radiobutton2=Radiobutton(window2,variable=v,value=1) Now you set the master for your buttons as window2, and use a variable that has as master window1. This is the big problem, besides the use of two Tcl interpreters. Tkinter doesn't really try to make this situation work, so you better not continue with it. > radiobutton1.pack() > radiobutton2.pack() > radiobutton2.bind('<Button-1>',test) > radiobutton1.bind('<Button-1>',test) > window1.mainloop() > > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From sdouche at gmail.com Sun Sep 21 05:46:54 2008 From: sdouche at gmail.com (Sebastien Douche) Date: Sun, 21 Sep 2008 11:46:54 +0200 Subject: report a BUG of package setuptools-0.6c8. In-Reply-To: <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> References: <d2d5d61d0809192114p7b2a20b1tca588b5ed73acc26@mail.gmail.com> <mailman.1291.1221898300.3487.python-list@python.org> <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> Message-ID: <5e1183fa0809210246q46f864eic359964a0cb0d46e@mail.gmail.com> 2008/9/20 Carl Banks <pavlovevidence at gmail.com>: > On Sep 20, 1:11 am, Fredrik Lundh <fred... at pythonware.com> wrote: >> ???? wrote: >> > File "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", >> > line 98, in entries_finder >> > log.warn("unrecognized .svn/entries format in %s", dirname) >> > NameError: global name 'log' is not defined >> >> > global name 'log' is not defined to the line 98!!! >> >> please report bugs here: >> >> http://bugs.python.org/ > > Does bugs.python.org track bugs for setuptools? (Genuine question; > the PEAK site doesn't list an obvious way to report bugs so I wonder > if they're using bugs.python.org? Hope not....) > > If not, the OP should ask on the setuptools mailing list. http://bugs.python.org/setuptools/ BTW, this blocker bug (Setuptools and SVN 1.5.x) is known for 2 months *sigh*. -- Seb From dmitry at athabascau.ca Fri Sep 26 11:41:32 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Fri, 26 Sep 2008 15:41:32 GMT Subject: is decorator the right thing to use? References: <h3zCk.1766$T65.1068@edtnps82> <2203c7b1-abd4-43f0-9180-12d13103bc57@b38g2000prf.googlegroups.com> <KFDCk.1805$T65.1265@edtnps82> <FUDCk.1809$T65.1083@edtnps82> <6k0qc1F53ov8U1@mid.uni-berlin.de> <kiOCk.1755$Pv5.238@edtnps83> <b3c2c98a-12e0-4fd5-abde-24a050b027ce@m36g2000hse.googlegroups.com> Message-ID: <Mo7Dk.2064$T65.1885@edtnps82> Paul McGuire wrote: >> see, in your code you're assuming that there's only 1 property ( 'b' ) >> inside of A that needs proxying. In reality I have several. <snip/> > > No, really, Diez has posted the canonical Proxy form in Python, using > __getattr__ on the proxy, and then redirecting to the contained > delegate object. This code does *not* assume that only one property > ('b'? where did that come from?) is being redirected - __getattr__ > will intercept all attribute lookups and redirect them to the > delegate. > > If you need to get fancier and support this single-proxy-to-multiple- > delegates form, then yes, you will need some kind of map that says > which method should delegate to which object. Or, if it is just a > matter of precedence (try A, then try B, then...), then use hasattr to > see if the first delegate has the given attribute, and if not, move on > to the next. that is what I didn't like about it - I have to iterate over delegates when I can build direct mapping once and for all and tie it to class definition ;) > Your original question was "is decorator the right thing to use?" For > this application, the answer is "no". yeah. seems that way. in the other fork of this thread you'll find my conclusion which agrees with that :) > It sounds like you are trying > to force this particular to solution to your problem, but you are > probably better off giving __getattr__ intercepting another look. __getattr__ implies constant lookups and checks (for filtering purposes) - I want to do them once, attach generated methods as native methods and be done with it. That is why I do not like __getattr__ in this particular case. Otherwise - you're right. From luigi.paioro at gmail.com Fri Sep 12 03:21:51 2008 From: luigi.paioro at gmail.com (luigi.paioro at gmail.com) Date: Fri, 12 Sep 2008 00:21:51 -0700 (PDT) Subject: XML-RPC "filter" References: <283e7d17-387c-48f6-b334-ed6facd9482d@73g2000hsx.googlegroups.com> <6inkkiFrbptbU1@mid.uni-berlin.de> <10be4328-138c-4076-9a79-4a44b6a7a043@34g2000hsh.googlegroups.com> <6iqr3dF3msoU1@mid.uni-berlin.de> <e91c2424-7b31-4eb7-abe3-2b3e8c021264@r15g2000prd.googlegroups.com> Message-ID: <48914423-0410-4ee3-a2ad-c977c4917e84@34g2000hsh.googlegroups.com> On 11 Set, 18:45, Richard Levasseur <richard... at gmail.com> wrote: > Because he wants to insert parameters at the very start, he can > probably get away with modifying the xml directly. ?Just find the > position of the <params> (i think thats the tag) and insert the xml > you need after it. ?Its pretty dirty, but would work. ?The wire format > isn't that complicated. I think this is exactly what I do... isn't it? From mensanator at aol.com Sun Sep 28 16:44:00 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 28 Sep 2008 13:44:00 -0700 (PDT) Subject: generate random digits with length of 5 References: <e1923ff8-8150-41b6-9444-19c14b4d2f6f@8g2000hse.googlegroups.com> <47c890dc0809281302rf01afe5j65bc141057cb5f7@mail.gmail.com> <mailman.1641.1222632690.3487.python-list@python.org> Message-ID: <a380bc46-cf5f-4ae9-b1f2-d8789ba4f838@d45g2000hsc.googlegroups.com> On Sep 28, 3:11?pm, "Gary M. Josack" <g... at byoteki.com> wrote: > Chris Rebert wrote: > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <soti... at gmail.com> wrote: > > >> Wondering if there is a better way to generate string of numbers with > >> a length of 5 which also can have a 0 in the front of the number. > > >> <pre> > >> ?random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 > >> elements > >> ?code = 'this is a string' + str(random_number[0]) + > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3]) > >> + str(random_number[4]) > > > code = ''.join(str(digit) for digit in random_number) > > > Regards, > > Chris > > >> </pre> > > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > will random.randint(10000,99999) work for you? It doesn't meet the OP's requirement that the number can start with 0. Also, the method the OP asks about returns a list of unique numbers, so no number can be duplicated. He can get 02468 but not 13345. Now, IF it's ok to have an arbitrary number of leading 0s, he can do this: >>> str(random.randint(0,99999)).zfill(5) '00089' >>> str(random.randint(0,99999)).zfill(5) '63782' >>> str(random.randint(0,99999)).zfill(5) '63613' >>> str(random.randint(0,99999)).zfill(5) '22315' From vel.accel at gmail.com Tue Sep 2 00:56:45 2008 From: vel.accel at gmail.com (dieter h) Date: Tue, 2 Sep 2008 00:56:45 -0400 Subject: Process "Killed" In-Reply-To: <92da89760808300807p1af72cbcoec2b39f153fe073e@mail.gmail.com> References: <48a554c6-eeb3-4605-bdf2-a4b7de17bca3@b1g2000hsg.googlegroups.com> <92da89760808300807p1af72cbcoec2b39f153fe073e@mail.gmail.com> Message-ID: <1e52e0880809012156w581586dey34d6c42858bce514@mail.gmail.com> On Sat, Aug 30, 2008 at 11:07 AM, Eric Wertman <ewertman at gmail.com> wrote: >> I'm doing some simple file manipulation work and the process gets >> "Killed" everytime I run it. No traceback, no segfault... just the >> word "Killed" in the bash shell and the process ends. The first few >> batch runs would only succeed with one or two files being processed >> (out of 60) before the process was "Killed". Now it makes no >> successful progress at all. Just a little processing then "Killed". > > This is the behavior you'll see when your os has run out of some > memory resource. The kernel sends a 9 signal. I'm pretty sure that > if you exceed a soft limit your program will abort with out of memory > error. > > Eric > Eric, thank you very much for your response. From ig at illusorygoals.com Fri Sep 12 21:08:20 2008 From: ig at illusorygoals.com (ig at illusorygoals.com) Date: Fri, 12 Sep 2008 18:08:20 -0700 (PDT) Subject: n00b question: Better Syntax for Coroutines? Message-ID: <7f953bb2-b9f5-47d9-99f7-7c9194c0cc4a@q5g2000prf.googlegroups.com> First off, I'm a python n00b, so feel free to comment on anything if I'm doing it "the wrong way." I'm building a discrete event simulation tool. I wanted to use coroutines. However, I want to know if there's any way to hide a yield statement. I have a class that I'd like to look like this: class Pinger(Actor): def go(self): success = True while success: result = self.ping("128.111.41.38") if result != "success": success = False print "Pinger done" But because I can't hide yield inside ping, and because I can't find a convenient way to get a self reference to the coroutine (which is used by the event queue to pass back results), my code looks like this: class Pinger(Actor): def go(self): # I dislike this next line self.this_pointer = (yield None) success = True while success: # I want to get rid of the yield in the next line result = (yield self.ping("128.111.41.38")) if result != "success": success = False print "Pinger done" I posted a more detailed version of this as a rant here: http://illusorygoals.com/post/49926627/ I'd like to know, is there a way to get the syntax I want? After staying up late last night to get a proof-of-concept working with coroutines, my boss expressed disappointment in the ugliness of the Pinger code (we agreed on the desired syntax above). I spent almost 2 hours today to migrate the system over to threads. That made my boss happy, but I'm still curious if I can do something to salvage the coroutine version. Regards, IG From bearophileHUGS at lycos.com Wed Sep 24 15:11:07 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 24 Sep 2008 12:11:07 -0700 (PDT) Subject: Linq to Python References: <mailman.1412.1222181744.3487.python-list@python.org> <811bb792-d7ab-4df0-829d-e8183c75d66b@c58g2000hsc.googlegroups.com> Message-ID: <5a8e214d-0ab7-4023-a8b4-c139fb5a0899@r66g2000hsg.googlegroups.com> sturlamolden: >No, because Python already has list comprehensions and we don't need the XML buzzword.< LINQ is more than buzzwords. Python misses several of those features. So maybe for once the Python crowd may recognize such C# feature as much better than things present in Python. Said that, I presume Python will go on as usual, and LINQ-like capabilities will not be integrated in Python. In the meantime where I live lot of people will keep using C# instead of Python and CLisp, natural selection at work indeed. Bye, bearophile From aaron.hildebrandt at gmail.com Wed Sep 10 13:14:13 2008 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Wed, 10 Sep 2008 10:14:13 -0700 (PDT) Subject: Reading binary data Message-ID: <b3dc097d-e0df-4d0f-8998-d8940cef7c50@2g2000hsn.googlegroups.com> I've been trying to tackle this all morning, and so far I've been completely unsuccessful. I have a binary file that I have the structure to, and I'd like to read it into Python. It's not a particularly complicated file. For instance: signature char[3] "GDE" version uint32 2 attr_count uint32 { attr_id uint32 attr_val_len uint32 attr_val char[attr_val_len] } ... repeated attr_count times ... However, I can't find a way to bring it into Python. This is my code -- which I know is definitely wrong, but I had to start somewhere: import struct file = open("test.gde", "rb") output = file.read(3) print output version = struct.unpack("I", file.read(4))[0] print version attr_count = struct.unpack("I", file.read(4))[0] while attr_count: print "---" file.seek(4, 1) counter = int(struct.unpack("I", file.read(4))[0]) print file.read(counter) attr_count -= 1 file.close() Of course, this doesn't work at all. It produces: GDE 2 --- ? --- ??? I'm completely at a loss. If anyone could show me the correct way to do this (or at least point me in the right direction), I'd be extremely grateful. From google at mrabarnett.plus.com Thu Sep 11 19:46:26 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 11 Sep 2008 16:46:26 -0700 (PDT) Subject: dict slice in python (translating perl to python) References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> <b4470822-e893-4b5f-893e-28c39e71dddb@m73g2000hsh.googlegroups.com> <mailman.883.1221153104.3487.python-list@python.org> Message-ID: <9d3e52f4-e24f-47e9-a2b4-af214919c2ca@z72g2000hsb.googlegroups.com> On Sep 11, 6:11?pm, Fredrik Lundh <fred... at pythonware.com> wrote: [snip] > (the next step towards true Pythonicness would be to store your data in > class instances instead of dictionaries in the first place, but one step > at a time...) > Surely the word is "Pythonicity"? :-) From aioe.org at technicalbloke.com Tue Sep 30 04:15:14 2008 From: aioe.org at technicalbloke.com (r0g) Date: Tue, 30 Sep 2008 04:15:14 -0400 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> Message-ID: <gbsn6i$ut0$1@aioe.org> Lawrence D'Oliveiro wrote: > In message <gbr4ks$1vv$1 at aioe.org>, r0g wrote: > >> You can only distribute modifications to gnuplot itself as >> patches, but you can distribute it freely ... > > This must be some new definition of "freely" of which I'm unaware. As in beer. From celephicus at gmail.com Tue Sep 23 01:23:35 2008 From: celephicus at gmail.com (Tom Harris) Date: Tue, 23 Sep 2008 15:23:35 +1000 Subject: Docstrings for class attributes Message-ID: <aa19747c0809222223y2c9c3e88h8a31b070b6529f68@mail.gmail.com> Greetings, I want to have a class as a container for a bunch of symbolic names for integers, eg: class Constants: FOO = 1 BAR = 2 Except that I would like to attach a docstring text to the constants, so that help(Constants.FOO) will print some arbitrary string. Sort of a very limited implementation of PEP 224. The only solution that I can see is to subclass int.__new__(), since once I have an int all it's attributes are immutable. -- Tom Harris <celephicus(AT)gmail(DOT)com> From mccredie at gmail.com Mon Sep 8 12:24:20 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 8 Sep 2008 09:24:20 -0700 (PDT) Subject: Test if list contains another list References: <2f65fc47-a835-4eb9-8cfd-5b3d795f3f68@r66g2000hsg.googlegroups.com> <48c4f0e0$0$11223$426a34cc@news.free.fr> Message-ID: <bc3207c3-1121-4533-a8e9-0bb1464b27d3@n33g2000pri.googlegroups.com> On Sep 8, 12:32?am, Bruno Desthuilliers <bdesth.quelquech... at free.quelquepart.fr> wrote: > mathieu a ?crit : > > > Hi there, > > > ? I am trying to write something very simple to test if a list > > contains another one: > > > a = [1,2,3] > > > b = [3,2,1,4] > > > but 'a in b' returns False. > > Indeed. Lists are not sets, and the fact that all elements of list a > happens to also be part of list b doesn't make the list a itself an > element of list b. > > ?>>> a = [1, 2, 3] > ?>>> b = [3,2,1,4] > ?>>> c = [b, a] > ?>>> a in c > True > ?>>> b in c > True > ?>>> c > [[3, 2, 1, 4], [1, 2, 3]] > ?>>> > > > How do I check that a is indeed contained > > in b ? > > But that's what you did - you *did* checked if a was contained in b, and > this is not the case. What you want is to check if *all elements* of a > are contained in b, which is quite another problem. Now the answer to > your question : use sets. > > ?>>> set(a).issubset(set(b)) > True > ?>>> > > HTH Just to clarify, doing it using sets is not going to preserve order OR number of elements that are the same. That is: >>> a = [1,1,2,3,4] >>> b = [4,5,3,7,2,6,1] >>> set(a).issubset(set(b)) True This will return True if b contains at least on of each element found in a. If the OP wanted to check that list `a` appeared in order somewhere in list `b` then sets won't work. Matt From mail at johnohagan.com Tue Sep 30 08:53:19 2008 From: mail at johnohagan.com (John O'Hagan) Date: Tue, 30 Sep 2008 12:53:19 +0000 Subject: How best to pass arbitrary parameters from one function to another Message-ID: <200809301253.19296.mail@johnohagan.com> On Tue Sep 30 11:32:41 CEST 2008, Steven D'Aprano >On Tue, 30 Sep 2008 08:58:15 +0000, John O'Hagan wrote: > >> Hi Pythonistas, >> >> I'm looking for the best way to pass an arbitrary number and type of >> variables created by one function to another. They can't be global >> because they may have different values each time they are used in the >> second function. >> >> So far I'm trying to do something like this: >> >> >> def process_args( [list, of, command-line, arguments] ): > > >If you are trying to process commandline args, I suggest you don't re- >invent the wheel. Have a look at the two standard modules, optparse and >getopt. Of the two, getopt is probably simpler to get started with, but >optparse is more powerful. > Thanks, both to you and Bruno for pointing this out, I'll certainly be using it in future. >To answer your more general question, see below. > > >> do stuff >> return {dictionary : of, local : variables } >> >> def main_function( **kwargs ): >> >> do stuff >> return result >> >> kw1 = process_args( [some, list] ) >> kw2 = process_args( [a, different, list] ) >> >> for i in main_function( **kw1 ): >> >> kw2[ var1 ] = i >> kw2[ var2 ] = len( i ) >> >> for j in main_function(**kw2): >> >> print j >> >> This only seems to work if I specify a default value for every possible >> parameter of main_function and also for any others which may be passed >> to it, which is a bit tedious because there are very many of them but >> only a few are used in any given execution of the program. >> >Er, yes. Presumably main_function actually does something. So it expects >some arguments, and if the arguments aren't given, then it will fail. To >prevent it failing when arguments aren't given, they must have default >values. So define them, once, and be done with it: [...snip code example...] >Default values are a feature, not a problem to be solved. I take your point, but in this case all necessary parameters are present in the keyword dictionary, so I guess I was surprised that default values still need to specified. Also, the function body tests for the presence of each parameter and only acts on those that are there, so it does not fail because of a missing argument. However, I'm sure there's a good reason that it works this way. >As for your nested for-loops (see above), I'm guessing that you're trying >to copy items from one dictionary kw1 to another kw2, before processing >kw2. You should check out the update method on dictionaries. [...] That's also of great use, thank you. What I'm actually trying to do, though, is add some of the output of one call of main_function to the arguments of another call of the same function (with different arguments). It's a long story, but I have a number-crunching function which produces lists of numbers representing musical notes, either rhythmic or melodic, to be printed out as a score using Lilypond and/or played by samples or synthesizers using sox. The melodic and rhythmic parts work by themselves, but I'm trying to get the function to feed itself rhythms for its melodies, and vice-versa. I guess that's already too much information.... Thanks for your help. John From grante at visi.com Mon Sep 1 11:12:07 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 01 Sep 2008 10:12:07 -0500 Subject: How Compute # of Days between Two Dates? References: <JAIuk.19687$cW3.19527@nlpi064.nbdc.sbc.com> <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> <VpTuk.38934$ZE5.3067@nlpi061.nbdc.sbc.com> Message-ID: <l8OdnfiOPe7amyHVnZ2dnUVZ_qvinZ2d@posted.visi> On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: > Grant Edwards wrote: >> On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: >> >>> That's the question in Subject. For example, the difference between >>> 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and >>> 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in >>> years between, say, 1990 and 2050. In other words not some really strange >>> period of time well outside our current era of history. >> >> Does the standard library's datetime module not do what you want? >> >> http://docs.python.org/lib/module-datetime.html >> > Yes, it would seem so. This works fine. It would probably be worth your while to read through one of introductory Python books or just browse through the Python tutorial: http://docs.python.org/tut/ > I was pondering this in pyfdate, but perhaps missed it or it > was not obvious to me in the tutorial for some reason. Sorry, can't help you there -- I've never heard of pyfdate. The timedate module that comes with Python has always done what I needed to do with dates/times. -- Grant From sri_annauni at yahoo.co.in Thu Sep 11 05:55:17 2008 From: sri_annauni at yahoo.co.in (srinivasan srinivas) Date: Thu, 11 Sep 2008 15:25:17 +0530 (IST) Subject: Extracing data from webpage Message-ID: <315956.68571.qm@web7903.mail.in.yahoo.com> Hi, I am trying to download data from a webpage. I use mechanize python module. Could someone tell me how to set/pass an agent?like Mozilla or IE that we do in perl's WWW::Mechanize?? Thanks, Srini Be the first one to try the new Messenger 9 Beta! Go to http://in.messenger.yahoo.com/win/ From bcurtu at gmail.com Fri Sep 26 05:32:50 2008 From: bcurtu at gmail.com (bcurtu) Date: Fri, 26 Sep 2008 02:32:50 -0700 (PDT) Subject: how to replace and string in a "SELECT ... IN ()" Message-ID: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> Hi, I have a BIIIIIG problem with the next query: cursor.execute(""" SELECT titem.object_id, titem.tag_id FROM tagging_taggeditem titem WHERE titem.object_id IN (%s) """,( eid_list)) eid_list is suppossed to be a list of ids = [1,5,9] How can I make it work? Thanks From jaycx2.3.calrobert at spamgourmet.com.remove Mon Sep 1 15:04:05 2008 From: jaycx2.3.calrobert at spamgourmet.com.remove (Robert Maas,) Date: Mon, 01 Sep 2008 12:04:05 -0700 Subject: The Importance of Terminology's Quality References: <48a8df27$0$7362$607ed4bc@cv.net> <g8bflo$984$1@localhost.localdomain> <2OedndEZrPbzTTHVnZ2dnUVZ_qfinZ2d@speakeasy.net> <4fkpa4prudu3gkdt9095coho3srb52o82d@4ax.com> <s2lta4lorjk49dn3joo3gj3juc8rfqqinf@4ax.com> Message-ID: <rem-2008sep01-004@yahoo.com> > From: George Neuner <gneun... at comcast.net> > A friend of mine had an early 8080 micros that was programmed > through the front panel using knife switches When you say "knife switches", do you mean the kind that are shaped like flat paddles? I think that would be the IMSAI, which came after the ALTAIR. Those flat paddle-shaped switched would presumably be much more comfortable on the fingers than the standard metal toggle switches on the ALTAIR. I had an ALTAIR, which made front-panel programming rather painful on the fingers. > ... toggle in the binary address, latch it, toggle in the binary > data, latch it, repeat ad nauseam. For manually loading software in sequential locations, you have to enter the binary address only once. After that, you press the EXAMINE-NEXT toggle to increment the address by one. That reduced the effort by nearly a factor of 3. Instead of toggling a 16-bit address and EXAMINE and 8-bit datum and STORE each time, you toggle just EXAMINE-NEXT and 8-bit datum and STORE for each consecutive memory location after the first. Note the address and data toggles are bistable, stay in whatever position you left them in, whereas the three control toggles (EXAMIME EXAMINE-NEXT STORE) are spring loaded, making momentary contact when you force them then spring back to inactive when you release them. > It had no storage device initially ... to use it you had to input > your program by hand every time you turned it on. Almost but not quite true. With static RAM, most of the data can survive power-downs of hours or even days. I had 28k bytes of static RAM on my ALTAIR, so if I needed to start it up after it had been shut down I'd toggle in the starting address by hand, EXAMINE that, compare what shows with what's on my printed listing, and if it matches just EXAMINE-NEXT to compare the next. In the few cases I saw a bit or two flipped, I'd re-enter that one byte of data. I had to do that only for my BOOT1 loader, which was hand-loaded from front panel and took text input in 3n+1 form from Beehive 3A terminal connected to serial port, maybe also for BOOT2 loader which had been loaded in 3n+1 form and took input in hexadecimal form, and maybe also for BOOT3 loader which had been loaded in hexadecimail form from Beehive and automatically downloaded the next bootstrap loader from modem. If only a few bytes (of BOOT2 or BOOT3) had been damaged by days of power down, comparing binary against listing to verify it's 99% correct, and then manually patching just one or two bytes, would be faster and safer than manually entering 3n+1 or hexadecimal from keyboard. But once BOOT3 was loaded, I always downloaded all the rest of the software from the PDP-10 over the modem. > I did a little bit of programming on it, but I tired of it quickly. Did your friend's machine have two serial ports, one for local terminal and one for modem, and did you have access to a remote PDP-10 or other mainframe for running a cross-assembler? Or did you have some other computer locally available, where you could use that other computer both to store your library of code and to perform automated file transfer from archive on other computer to where it's needed on IMSAI? > As did my friend - once he got the tape storage working (a new > prom) Yeah, I never had the money to buy that, and with the PDP-10 available for both cross-assembling and archiving/downloading, I didn't need it. > Machine coding is not relevant anymore - it's completely > infeasible to input all but the smallest program. That's not totally true. For some educational purposes, like *really* understanding pointers (not the kind in C so much as the kind that are inherent in all pointer-linked data structures such as linked lists and binary search trees etc.), it helps to have some "hands-on" experience writing and executing machine-language code, in a sense actually "seeing" a register first point to the first byte of a CONS cell then by indexing with offset pointing *through* the *second* pointer of that CONS cell to whatever the CDR points to. Then "mission impossible" when your instructor tells you to see if there's a way to reverse that process, whereby you are given the register pointing to whatever the CDR points to, and you are supposed to find the address of the original CONS cell. Instant enlightenment, no lecture/sermon needed! From gminick at bzt.bzt Mon Sep 1 14:44:41 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Mon, 1 Sep 2008 18:44:41 +0000 (UTC) Subject: Getting an objetcs dict? References: <11465066-38f7-48df-97a2-6739d6407571@z66g2000hsc.googlegroups.com> Message-ID: <g9hd6n$iqp$1@inews.gazeta.pl> On Mon, 1 Sep 2008 11:31:42 -0700 (PDT), ssecorp wrote: > I did nce(I think). > > class X > > X.__dict__() and ngot a dict of its variables. > > Now i get errors doing this. what am i doing wrong? You're not asking smart questions: http://www.catb.org/~esr/faqs/smart-questions.html HINT: the attribute you're accessing is not a callable. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From tjreedy at udel.edu Wed Sep 24 13:35:00 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 24 Sep 2008 13:35:00 -0400 Subject: problem updating variable in a module In-Reply-To: <e0b6c39a0809240742k7ef2e8cfi33f88d8169b17170@mail.gmail.com> References: <e0b6c39a0809240742k7ef2e8cfi33f88d8169b17170@mail.gmail.com> Message-ID: <gbdtnq$jpb$1@ger.gmane.org> dudeja.rajat at gmail.com wrote: > Hi, > > I've a problem updating my variable in a module. > > In my main program, I call a function from mod1 to update a variable of mod1 > As soon as I update this varibale, I check it back in the mail program > but it the variable from mod1 does not get updated. > > main Program: > **************** > import mod1 > a = 20 > mod.update(a) > print mod.a <---- does not print anything As Tim noted, this cannot run. *** Always post the code you actually ran *** So we cannot answer why the code you did not post did not work. With the mod/mod1 mixup fixed, you do not need the update function. mod.a = 20 should do the same thing. > > mod1 > ******** > a = 10 > def update(someInt): > global a > a = someInt > print a <---- this does actually print a = 20 tjr From gminick at bzt.bzt Fri Sep 12 11:35:02 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Fri, 12 Sep 2008 15:35:02 +0000 (UTC) Subject: setattr in class References: <4378b918-82bd-43af-9b31-b714d3d9f1cf@s50g2000hsb.googlegroups.com> Message-ID: <gae275$s4c$1@inews.gazeta.pl> On Fri, 12 Sep 2008 08:08:18 -0700 (PDT), Bojan Mihelac wrote: > Hi all - when trying to set some dynamic attributes in class, for > example: > > class A: > for lang in ['1', '2']: > exec('title_%s = lang' % lang) #this work but is ugly > # setattr(A, "title_%s" % lang, lang) # this wont work > I guess A class not yet exists in line 4. Is it possible to achive > adding dynamic attributes without using exec? Yes, it is: ------------- class A: for i in (1, 2): locals()['xxx%d' % (i)] = i print A.xxx1 print A.xxx2 a = A() print a.xxx1 print a.xxx2 ------------- And the output is: ----- 1 2 1 2 ----- But I definitely don't consider this one as a good programming practice. -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From adykes at panix.com Sat Sep 13 10:09:39 2008 From: adykes at panix.com (Al Dykes) Date: 13 Sep 2008 10:09:39 -0400 Subject: Code example that will make a Skype connection? Message-ID: <gaghj3$4tf$1@panix5.panix.com> Can some post a Python code fragment that will to make a PC with Skpye installed to make a Skype call, given a valid phone # string. I'm not asking for code that handles the audio once the connection is made. -- Al Dykes News is something someone wants to suppress, everything else is advertising. - Lord Northcliffe, publisher of the Daily Mail From pavlovevidence at gmail.com Fri Sep 26 21:00:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 26 Sep 2008 18:00:36 -0700 (PDT) Subject: Large Data Sets: Use base variables or classes? And some binding questions References: <48e182e3-2e74-40af-aabf-f3cf0088f5ab@g17g2000prg.googlegroups.com> <00b839d9-fe35-4478-aba2-0435fbf285e8@m36g2000hse.googlegroups.com> <00ed6d83$0$20666$c3e8da3@news.astraweb.com> <4039a6ac-f418-471b-8e21-3863adbe0d36@f63g2000hsf.googlegroups.com> Message-ID: <00139f01-67b9-48c4-ae2d-2a710d40474e@e53g2000hsa.googlegroups.com> On Sep 26, 8:53?pm, Carl Banks <pavlovevide... at gmail.com> wrote: > It might still end up being slower (creating slot descriptors might > take more time for all I know) but it's more than just an effect of > less memory. Actually scratch that. Descriptors are only created when the type object is created. I can't think of anything that would need to be done in an instance only if no dict is present, so using slots probably almost certianly makes object creation faster. Still, the last word is the profiler. Carl Banks From M8R-yfto6h at mailinator.com Sun Sep 28 15:20:55 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Sun, 28 Sep 2008 12:20:55 -0700 Subject: Music knowledge representation References: <mailman.1624.1222612634.3487.python-list@python.org><e21d8f09-6285-472e-9bfe-4757862d2c1c@x41g2000hsb.googlegroups.com> <mailman.1633.1222628890.3487.python-list@python.org> Message-ID: <7PGdnekcC-CMRELVnZ2dnUVZ_qKdnZ2d@comcast.com> "Mr.SpOOn" <mr.spoon21 at gmail.com> wrote in message news:mailman.1633.1222628890.3487.python-list at python.org... > On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady > <castironpi at gmail.com> wrote: > >> Here is a link to someone else's design they asked about on the >> newsgroup a couple weeks ago. >> >> http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc > > :D > It's always me. > > I think my question is more specific. I need some sort of cycle. > > So if I have a list with A, B, C, D, when I iter over it I need to get > an A after the D. Check out itertools.cycle: >>> x=itertools.cycle('ABCDEFG') >>> x.next() 'A' >>> x.next() 'B' >>> x.next() 'C' >>> x.next() 'D' >>> x.next() 'E' >>> x.next() 'F' >>> x.next() 'G' >>> x.next() 'A' >>> x.next() 'B' -Mark From mnordhoff at mattnordhoff.com Tue Sep 9 03:37:20 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Tue, 09 Sep 2008 07:37:20 +0000 Subject: "AttributeError: 'module' object has no attribute 'getdefaultlocale'" on Python start In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF601ADBEE2@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF601ADBE4D@enbmail01.lsi.com> <7F0503CD69378F49BE0DC30661C6CCF601ADBEE2@enbmail01.lsi.com> Message-ID: <48C627B0.6060806@mattnordhoff.com> Barak, Ron wrote: > Hi Fellow Pythonians, > > I stated getting the following when starting Python (2.5.2 on Windows XP): > > C:\Documents and Settings\RBARAK>python -v > # installing zipimport hook > import zipimport # builtin > # installed zipimport hook > # D:\Python25\lib\site.pyc matches D:\Python25\lib\site.py > import site # precompiled from D:\Python25\lib\site.pyc > # D:\Python25\lib\os.pyc matches D:\Python25\lib\os.py > import os # precompiled from D:\Python25\lib\os.pyc > import errno # builtin > import nt # builtin > # D:\Python25\lib\ntpath.pyc matches D:\Python25\lib\ntpath.py > import ntpath # precompiled from D:\Python25\lib\ntpath.pyc > # D:\Python25\lib\stat.pyc matches D:\Python25\lib\stat.py > import stat # precompiled from D:\Python25\lib\stat.pyc > # D:\Python25\lib\UserDict.pyc matches D:\Python25\lib\UserDict.py > import UserDict # precompiled from D:\Python25\lib\UserDict.pyc > # D:\Python25\lib\copy_reg.pyc matches D:\Python25\lib\copy_reg.py > import copy_reg # precompiled from D:\Python25\lib\copy_reg.pyc > # D:\Python25\lib\types.pyc matches D:\Python25\lib\types.py > import types # precompiled from D:\Python25\lib\types.pyc > import _types # builtin > import locale # directory > D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale > import locale # precompiled from > D:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\locale\__init__.pyc For some reason, when you run "import locale", it's importing wx.locale instead of the "locale" module from the stdlib. However, I have no idea why that would be happening... Did you do something to add wx to your PYTHONPATH? Maybe do "import sys; print sys.path" or "import os; print os.environ['PYTHONPATH']" to verify this. (Hopefully someone more knowledgeable than me will come along soon.) > # D:\Python25\lib\codecs.pyc matches D:\Python25\lib\codecs.py > import codecs # precompiled from D:\Python25\lib\codecs.pyc > import _codecs # builtin > import encodings # directory D:\Python25\lib\encodings > # D:\Python25\lib\encodings\__init__.pyc matches > D:\Python25\lib\encodings\__init__.py > import encodings # precompiled from D:\Python25\lib\encodings\__init__.pyc > # D:\Python25\lib\encodings\aliases.pyc matches > D:\Python25\lib\encodings\aliases.py > import encodings.aliases # precompiled from > D:\Python25\lib\encodings\aliases.pyc > 'import site' failed; traceback: > Traceback (most recent call last): > File "d:\Python25\lib\site.py", line 415, in <module> > main() > File "d:\Python25\lib\site.py", line 406, in main > aliasmbcs() > File "d:\Python25\lib\site.py", line 357, in aliasmbcs > enc = locale.getdefaultlocale()[1] > AttributeError: 'module' object has no attribute 'getdefaultlocale' > # D:\Python25\lib\warnings.pyc matches D:\Python25\lib\warnings.py > import warnings # precompiled from D:\Python25\lib\warnings.pyc > # D:\Python25\lib\linecache.pyc matches D:\Python25\lib\linecache.py > import linecache # precompiled from D:\Python25\lib\linecache.pyc > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> > > Has anyone else gotten this error ? > Could anyone suggest a solution ? > > Thanks, > Ron. -- From mike.terrell at earthlink.net Sun Sep 21 22:26:27 2008 From: mike.terrell at earthlink.net (Michael A. Terrell) Date: Sun, 21 Sep 2008 22:26:27 -0400 Subject: Milenko Kindl rtegdgd References: <b3a8139e-656c-4451-bbe4-203d48cb3203@d77g2000hsb.googlegroups.com> <5118c027-e872-4447-9448-7dbb134b3389@k7g2000hsd.googlegroups.com> Message-ID: <HoGdnZmrGszOn0rVnZ2dnUVZ_t3inZ2d@earthlink.com> H Vlems wrote: > > On 21 sep, 19:48, yuma <yuma400... at yahoo.com> wrote: > > Milenko Kindl > > Banja Luka > > Banjaluka > > Bihac > > Well, that's not C isn't it, more like Snobol or RPG/2 Tidybowl -- http://improve-usenet.org/index.html aioe.org, Goggle Groups, and Web TV users must request to be white listed, or I will not see your messages. If you have broadband, your ISP may have a NNTP news server included in your account: http://www.usenettools.net/ISP.htm There are two kinds of people on this earth: The crazy, and the insane. The first sign of insanity is denying that you're crazy. From arnodel at googlemail.com Sun Sep 14 13:45:58 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 14 Sep 2008 10:45:58 -0700 (PDT) Subject: Is there any nice way to unpack a list of unknown size?? References: <238815.3778.qm@web7902.mail.in.yahoo.com> <mailman.1005.1221404903.3487.python-list@python.org> Message-ID: <6bbcb770-d9f7-4bfd-ae9a-491b2084a739@34g2000hsh.googlegroups.com> On Sep 14, 4:08?pm, Gary Herron <gher... at islandtraining.com> wrote: > srinivasan srinivas wrote: > > I want to do something like below: > > > 1. first, second, third, *rest = foo > > Python 3.0 has exactly this feature. ?No current Python 2.x version has it. > > Gary Herron > > > ?2. for (a,b,c,*rest) in list_of_lists: > > > Please suggest. > > > Thanks, > > Srini > > > ? ? ? Bring your gang together. Do your thing. Find your favourite Yahoo! group athttp://in.promos.yahoo.com/groups/ > > -- > >http://mail.python.org/mailman/listinfo/python-list In python >= 2.4, you can define a function like this: def truncate(iterable, n=1): iterator = iter(iterable) for i in iterator: if n == 0: yield iterator return yield i n -= 1 >>> a, b, c, tail = truncate([1,2,3,4,5,6], 3) >>> a 1 >>> b 2 >>> c 3 >>> tail <listiterator object at 0x78990> >>> list(tail) [5, 6] -- Arnaud From maebert at uos.de Tue Sep 16 11:41:33 2008 From: maebert at uos.de (Manuel Ebert) Date: Tue, 16 Sep 2008 15:41:33 -0000 (GMT) Subject: backup with python In-Reply-To: <11a3fca0-ded7-47c3-aeff-bb08acb1eb20@d1g2000hsg.googlegroups.com> References: <11a3fca0-ded7-47c3-aeff-bb08acb1eb20@d1g2000hsg.googlegroups.com> Message-ID: <59862.131.173.35.176.1221579693.squirrel@webmail.rz.uos.de> You may want to look into http://www.bigpaul.org/burn/ > Hi ! > I need some help to create backup with python. > I want to backup some bases on DVD - RW . > How i make this with python ? > I want to use python because the program is write on python . > > Thank you ! > -- > http://mail.python.org/mailman/listinfo/python-list > > -- www.redsdesk.de Goethering 10 49074 Osnabrueck Germany home +49.(0)541.3344529 mobile +49.(0)176.23970331 skype red.wraith icq 9905 7991 From aahz at pythoncraft.com Fri Sep 12 13:14:06 2008 From: aahz at pythoncraft.com (Aahz) Date: 12 Sep 2008 10:14:06 -0700 Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <336395c5-e7e9-43e6-95df-a45bf307ede3@8g2000hse.googlegroups.com> <gae588$dnq$1@ger.gmane.org <mailman.934.1221237380.3487.python-list@python.org> Message-ID: <gae80u$fgf$1@panix3.panix.com> In article <mailman.934.1221237380.3487.python-list at python.org>, Fredrik Lundh <fredrik at pythonware.com> wrote: >Steve Holden wrote: >> >> The defence rests. > >can you please stop quoting that guy, so we don't have to killfile you >as well... +1 -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From gnewsg at gmail.com Fri Sep 12 08:37:47 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 12 Sep 2008 05:37:47 -0700 (PDT) Subject: Please help me finding a way to implement os.path.issubpath(a, b) References: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> <34bc968e-735e-4ef0-99f3-3d71da6254d4@z72g2000hsb.googlegroups.com> Message-ID: <e08af2ae-7d39-4674-9a12-db49c9bf77cc@59g2000hsb.googlegroups.com> On Sep 11, 8:04?pm, Arnaud Delobelle <arno... at googlemail.com> wrote: > On Sep 11, 5:40?pm, "Giampaolo Rodola'" <gne... at gmail.com> wrote: > > > > > Hi, > > I'm trying to implement a function which returns whether a path is a > > subpath of another one (e.g. /a/b/c is a subpath of /a/b). > > I wrote this function which apparently seems to work fine: > > > import os > > > def issubpath(path1, path2): > > ? ? """Return True if path1 is a sub path of path2.""" > > ? ? if path1 == path2: > > ? ? ? ? return False > > ? ? x1 = path1.split(os.sep) > > ? ? x2 = path2.split(os.sep) > > ? ? return x1[:len(x2)] == x2 > > > ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False. > > A little help would be appreciated. > > > Thanks in advance. > > That's because: > > >>> 'C:\\dir'.split('\\') > ['C:', 'dir'] > >>> 'C:\\'.split('\\') > > ['C:', ''] > > So you could write instead something like > > ? ? x1 = path1.rstrip(os.sep).split(os.sep) > ? ? x2 = path2.rstrip(os.sep).split(os.sep) > > in your function > > HTH > > -- > Arnaud Thanks, it seems to work just fine. --- Giampaolo http://code.google.com/p/pyftpdlib/ From half.italian at gmail.com Wed Sep 3 20:51:59 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 3 Sep 2008 17:51:59 -0700 (PDT) Subject: Access to Windows "Add/Remove Programs"? Message-ID: <cf08e654-d2d5-48fe-a2ac-919fd2479254@v13g2000pro.googlegroups.com> Hi all, I'm trying to find a way to get a list of all the installed programs on a Windows box via Python. I thought of a few hacks that might partially work, and then thought about "Add/Remove Programs" Seems like the right way to go. I looked over the pywin32 docs a bit, but nothing slapped me in the face. Is there any reliable way to get at that info? Thanks in advance, ~Sean From bockman at virgilio.it Sun Sep 14 06:32:34 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: 14 Sep 2008 10:32:34 GMT Subject: Windows / Tkinter - problem with grid - not able to place widgets at desired places References: <e0b6c39a0808170725q2937194dl96049b16300aec@mail.gmail.com> <mailman.1760.1219058122.922.python-list@python.org> Message-ID: <48cce842$0$11367$5fc30a8@news.tiscali.it> Il Mon, 18 Aug 2008 12:15:10 +0100, dudeja.rajat ha scritto: >>Hi, >> >>I'm learning Python and Tkinter. I've started programming in Eclipse >>with PyDev. I'm intending to create a GUI. I'm not able to understand >>the Grid manager perhaps because there is quite a less documentation >>available for it on the net. >> >>My desired GUI is attached in the mail. Although I've tried writing a >>class module for this GUI but I'm not able to set all things right in >>the GUI. The Biggest problem seems to be with the Grid Manager in terms >>how it divides a window in Rows / columns. etc. I'm not able to place >>none of the widgets correctly in the GUI. >> >>For your convenience, I'm attaching this code also as myModule1.py . >>Please some one review it and help create me this GUI. >> Uhm, I don't think you should use the grid manager to obtain a window like that. The grid manager is for equally distributing widgets both horizontally and vertically. And I'm not sure that you can realize that window look with Tkinter. You could get close by horizontally packing each widget row in a frame and then vertically packing the frames in the window. But the look will be quite different than your target. If you are not satisfied with that I suggest you move to other toolkits which have more complex geometry managers than .pack and .grid. Ciao ----- FB From ewertman at gmail.com Tue Sep 2 23:51:02 2008 From: ewertman at gmail.com (Eric Wertman) Date: Tue, 2 Sep 2008 23:51:02 -0400 Subject: Library/project for making an invitation-only website? In-Reply-To: <7502-61941@sneakemail.com> References: <7502-61941@sneakemail.com> Message-ID: <92da89760809022051t6f8f5ecpe8b982dcd793beee@mail.gmail.com> I think Drupy is best library for these task. On Tue, Sep 2, 2008 at 12:27 PM, Dani <iphthfu02 at sneakemail.com> wrote: > Hi. > > I want to create a website where new users need to be invited by an existing user in order to open an account. Think of it the way Orkut became popular. > > I need a library, or code from some project, that sends the invitations, keeps track of which user invited who, etc. > > I'm sure there's already some code out there that performs these tasks. Drupy maybe? > > Could anybody recommend me some library/project for these tasks? > > Thank you in advance. > -- > http://mail.python.org/mailman/listinfo/python-list > From gstaniak at wp.pl Mon Sep 22 18:12:02 2008 From: gstaniak at wp.pl (Grzegorz Staniak) Date: Mon, 22 Sep 2008 22:12:02 +0000 (UTC) Subject: A bit weird dictionary behavior References: <mailman.1354.1222075570.3487.python-list@python.org> <7bc6eb30-7903-49f1-a528-0a49c67a757c@k37g2000hsf.googlegroups.com> <48d7f5b4$0$20534$426a74cc@news.free.fr> <919cd8a9-cdf4-43ef-b494-55d56db19b83@k7g2000hsd.googlegroups.com> Message-ID: <gb957i$ja0$1@news.lublin.pl> On 22.09.2008, Carl Banks <pavlovevidence at gmail.com> wroted: >> >> but it still doesn't feel exactly right. Would it be worth submitting a bug? >> >> > It feels wrong because it is. In a tidier language (Pascal, Java, etc) >> > a boolean and an integer must be different types. >> >> Some would argue (and some did by the time Python grew a 'bool' type) >> that what is wrong is to have a bool type in a language that already >> have a wider definition of the truth value of an expression... > > And some would argue that it was wrong to have such a wide definition > for the truth value of an expression in the first place... Just out of idle curiosity, what could be the alternatives? Not to evaluate e.g. strings to "true"? Aren't such conventions as "whatever is not empty, is 'true'" popular in dynamic langauges? GS -- Grzegorz Staniak <gstaniak _at_ wp [dot] pl> Nocturnal Infiltration and Accurate Killing From aioe.org at technicalbloke.com Sat Sep 27 02:26:25 2008 From: aioe.org at technicalbloke.com (r0g) Date: Sat, 27 Sep 2008 02:26:25 -0400 Subject: How to get the filename in the right case ? References: <6k1dukF5hk86U1@mid.uni-berlin.de> <mailman.1500.1222353834.3487.python-list@python.org> <Xns9B24589F2DBEOKB@199.45.49.11> <48DBB9C8.6090500@gmail.com> <gbh53f$dim$1@ger.gmane.org> <mailman.1518.1222386373.3487.python-list@python.org> <pan.2008.09.26.07.28.03@REMOVE.THIS.cybersource.com.au> Message-ID: <gbkjmh$l2q$2@aioe.org> Steven D'Aprano wrote: > On Fri, 26 Sep 2008 01:46:15 +0200, Stef Mientki wrote: > >> Secondly thoughtless copying of current behavior, doesn't bring any >> progress, >> and I think that's one of the reasons why we're still burdened by >> inventions done 20 years ago, >> e.g. "do you want to save your changes ?". > > I click No about 50% of the time, and Yes Of Course You Stupid Machine > the other 50% of the time. Until they have a computer capable of reading > my mind, I'm curious what alternative you'd suggest. > > Agreed, it's pretty handy, especially since every program and its dog decided to sprout tabs everywhere. Roger. From dudeja.rajat at gmail.com Tue Sep 16 08:50:37 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 16 Sep 2008 13:50:37 +0100 Subject: Problem parsing the input Message-ID: <e0b6c39a0809160550kfb6dd1flf09e94c80eb176f1@mail.gmail.com> Hi, I've a following input: ***** - Burst_Length not read from ini file ? - + BurstLength not read from ini file ***** - PilotTracking_Timing not read from ini file ? ^^^^^^^^^^^^^^ + NumTimings not read from ini file ***** - Analysis Time (Iterations = 1) = 0.519444s ? ^ --- + Analysis Time (Iterations = 1) = 0.562249s ***** - Burst Position = 89511samples ? ^ + Burst Position = 89510samples ***** - Rising Edge Time = 371682us ? ^ + Rising Edge Time = 371683us ***** How can I find the the colored items from the input. I though of using RE but don't know much about it. The colored item can be dot notation e.g. 0.05678 or a whole digit as 5678 Please help -- Regrads, Rajat -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080916/0476a65b/attachment-0001.html> From bdesth.quelquechose at free.quelquepart.fr Mon Sep 29 16:04:29 2008 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 29 Sep 2008 22:04:29 +0200 Subject: Converting a strng to an anonymous function In-Reply-To: <gbrh3l$m18$1@aioe.org> References: <gbrh3l$m18$1@aioe.org> Message-ID: <48e150b6$0$12658$426a74cc@news.free.fr> Nathan Seese a ?crit : > I'm writing a program to sort files with arbitrary python code. The > method I'm using for that is to pass sort an anonymous function taken > from the arguments. I'm wondering how to change a raw string into an > anonyous function. Care to give a couple more explanation about your use case ? There might be better solutions than eval/exec... From praveenapanch at gmail.com Mon Sep 8 05:26:20 2008 From: praveenapanch at gmail.com (Praveena P) Date: Mon, 8 Sep 2008 02:26:20 -0700 (PDT) Subject: String to hexadecimal conversion References: <0e555e09-358f-44b7-bef3-db2e689247f7@d77g2000hsb.googlegroups.com> Message-ID: <ba106c18-3e8e-4642-bbe0-0dac3d69411e@z66g2000hsc.googlegroups.com> On Sep 8, 2:05?pm, Praveena P <praveenapa... at gmail.com> wrote: > Hi folks, > > I am new to Python... so am not too sure about how the type conversion > works. > > I have to read a file that contains hexadecimal data and use the data > further to do some arithmetic calculations. > A sample of the input is : 00000000000020E0000032F800000000400022005E > The problem I am facing is this: > I am using f.read(2) to read a byte at a time, but the data that is > read is a string rather than a number. So it kind of hampers any > arithmetic operations I perform on this data... > > Could you please suggest some method I could use for this? > > Thanks guys! > Praveena I was thinking of using dictionary like this: hex_to_decimal = {"1":"1", "2":"2", "3":"3", "4":"4", "5":"5", "6":"6", "7":"7", "8":"8", "9":"9", "A":"10", "B":"11", "C":"12", "D":"13", "E":"14", "F":"15", "0":"0"} Extracting one character at a time and converting to decimal, and then using the decimal numbers generated for the further calculations.... Would there be a simpler way to do it? From clp at rebertia.com Mon Sep 29 13:19:55 2008 From: clp at rebertia.com (Chris Rebert) Date: Mon, 29 Sep 2008 10:19:55 -0700 Subject: Generate documentation for a Python developed software In-Reply-To: <1222706734.15761.403.camel@king.imim.es> References: <1222706734.15761.403.camel@king.imim.es> Message-ID: <47c890dc0809291019m5e31df2eq2c0340e2f2c01f84@mail.gmail.com> On Mon, Sep 29, 2008 at 9:45 AM, Alfons Nonell-Canals <alfons.nonell at upf.edu> wrote: > Dear all, > I have a complex program developed using Python. It contains lot of > files and classes. > > Now I have the lazy task to documentate it. I have some notes about is > class but I would like to know if there is something to auto-generate > the doucmentation with the program code. I know I will have to explain > each class and variable but, if an external software canprepare it, the > template, it will be great! Sphinx (http://sphinx.pocoo.org/) is pretty slick and was used to generate the spiffy new python docs (http://docs.python.org/dev/). There's also epydoc (http://epydoc.sourceforge.net/), the standard library module 'pydoc', and [to a lesser degree] Doxygen (http://www.stack.nl/~dimitri/doxygen/) Regards, Chris > > Thanks in advance! > > Regards, > > -- > ------------ > Alfons Nonell-Canals > Chemogenomics Lab > Research Group on Biomedical Informatics (GRIB) - IMIM/UPF > Parc de Recerca Biom?dica de Barcelona (PRBB) > C/ Doctor Aiguader, 88 - 08003 Barcelona > alfons.nonell at upf.edu - http://cgl.imim.es > > http://alfons.elmeuportal.cat > http://www.selenocisteina.info > > -- > http://mail.python.org/mailman/listinfo/python-list -- Follow the path of the Iguana... http://rebertia.com From aioe.org at technicalbloke.com Wed Sep 17 13:41:26 2008 From: aioe.org at technicalbloke.com (r0g) Date: Wed, 17 Sep 2008 13:41:26 -0400 Subject: File Reading related query References: <a3158e8b0809170255y6527dc96ta0f7466fd575db8f@mail.gmail.com> <mailman.1158.1221646738.3487.python-list@python.org> Message-ID: <garfg6$e17$1@aioe.org> Fredrik Lundh wrote: > Usman Ajmal wrote: > >> Is there any function for reading a file while ignoring *\n* occuring >> in the file? > > can you be a bit more precise? are we talking about text files or > binary files? how do you want to treat any newlines that actually > appear in the file? > > </F> > Hi Usan, I've always just done... for each in open('filename.txt', 'r'): each = each.rstrip() You could wrap this as a generator if you really want it to be a one liner, personally it's never seemed worth it to me. Regards, Roger Heathcote http://www.technicalbloke.com http://movingtoubuntu.technicalbloke.co.uk From deets at nospam.web.de Fri Sep 5 07:07:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 Sep 2008 13:07:28 +0200 Subject: atomic section in code In-Reply-To: <c0632676-51ab-4cf6-a6a7-f2f089196d57@m45g2000hsb.googlegroups.com> References: <a475a219-1577-4018-a541-5b05c87f6f71@i76g2000hsf.googlegroups.com> <mailman.544.1220605512.3487.python-list@python.org> <c0632676-51ab-4cf6-a6a7-f2f089196d57@m45g2000hsb.googlegroups.com> Message-ID: <6ici7gFo8e4nU1@mid.uni-berlin.de> Ahmad Humayun schrieb: > On Sep 5, 1:59 pm, Fredrik Lundh <fred... at pythonware.com> wrote: >> Ahmad Humayun wrote: >>> I need to create an atomic section in Python code i.e. there is no >>> context switch to any other thread during the running of that piece of >>> code. Would would do the trick? >> use a lock, and make sure that anyone that needs access to the shared >> state you're manipulating in that section uses the same lock. >> >> lock = threading.Lock() # or RLock() etc [1] >> >> with lock: >> section >> >> this only works if everyone honors the lock, of course; there's no way >> in Python to lock out non-cooperating external threads. >> >> </F> >> >> 1) seehttp://effbot.org/zone/thread-synchronization.htm > > Thats true, but this will ensure mutual exclusion; not atomicity AFAIC that kind of mutual exclusion is what atomicity is about. What else do you expect to happen? Diez From alamat_email_aku at yahoo.co.id Thu Sep 4 09:15:49 2008 From: alamat_email_aku at yahoo.co.id (Abdurrahman Wahid) Date: Thu, 4 Sep 2008 06:15:49 -0700 (PDT) Subject: Assalamu'alaikum wr. wb. Message-ID: <1a5daf31-d1de-4973-9a69-04d1bc8f27da@r15g2000prd.googlegroups.com> Assalamu'alaikum wr. wb., Faith Freedom Indonesia (http://www.indonesia.faithfreedom.org/forum/) The Amazing Racist: Moslem Mosque (http://13gb.com/videos/923/) Forum Murtadin Indonesia (http://mantanmuslim.blogspot.com/) Wassalam From goon12 at gmail.com Tue Sep 23 08:54:25 2008 From: goon12 at gmail.com (Joe Riopel) Date: Tue, 23 Sep 2008 08:54:25 -0400 Subject: finding domain name In-Reply-To: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> References: <a21ac927-672c-4283-b58f-5420083617d3@79g2000hsk.googlegroups.com> Message-ID: <6a2ccd190809230554w43ac4752k52c6d7f49447faca@mail.gmail.com> On Tue, Sep 23, 2008 at 8:37 AM, Bobby Roberts <tchendrix at gmail.com> wrote: > hi group. I'm new to python and need some help and hope you can > answer this question. I have a situation in my code where i need to > create a file on the server and write to it. That's not a problem if > i hard code the path. However, the domain name needs to be dynamic so > it is picked up automatically. The path to our websites is > > home/sites/xxxxx/ > > where xxxxx represents the domain name. > > How can I find the domain name of the current url being viewed. I would guess that a pretty simple regular expression might do it. From fredrik at pythonware.com Tue Sep 16 03:30:35 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 16 Sep 2008 09:30:35 +0200 Subject: Cross-platform socket.getsockopt and struct.unpack (or socket timeout)? In-Reply-To: <vs-dnbIKaOy4wlLVnZ2dnUVZ_vGdnZ2d@comcast.com> References: <vs-dnbIKaOy4wlLVnZ2dnUVZ_vGdnZ2d@comcast.com> Message-ID: <gannau$2r8$2@ger.gmane.org> Heikki Toivonen wrote: > Is there a cross-platform way of doing what the M2Crypto code is > attempting to do? calling the socket object's settimeout() method? </F> From patrick.chartier at aero.bombardier.com Sun Sep 7 05:55:32 2008 From: patrick.chartier at aero.bombardier.com (wildfireporn.com@googlegroups.com) Date: Sun, 7 Sep 2008 02:55:32 -0700 (PDT) Subject: Watch Free Adult Videos Online Message-ID: <bd51f8fe-bd9e-4ce8-8cc6-e56214447e00@8g2000hse.googlegroups.com> http://groups.google.com/group/hyd-masti?lnk= From febkimbleox at gmail.com Sat Sep 27 07:18:12 2008 From: febkimbleox at gmail.com (febkimbleox at gmail.com) Date: Sat, 27 Sep 2008 04:18:12 -0700 (PDT) Subject: amy fisher sex tape free amy fisher sex tape amy fisher - Free Message-ID: <7fb54300-b8e5-4781-b0fc-b807747bc814@e53g2000hsa.googlegroups.com> amy . . . *******CLICK HERE******** http://vids365.cn/amy ***************************** . . . . . . . . . . . . She then walks toward amy with a slow, seductive sway with amy large breasts bouncing slightly with each step. She then walks toward fisher with a slow, seductive sway with fisher large breasts bouncing slightly with each step. She then walks toward sex with a slow, seductive sway with sex large breasts bouncing slightly with each step. She then walks toward tape with a slow, seductive sway with tape large breasts bouncing slightly with each step. She then walks toward free with a slow, seductive sway with free large breasts bouncing slightly with each step. She then walks toward amy with a slow, seductive sway with amy large breasts bouncing slightly with each step. She then walks toward fisher with a slow, seductive sway with fisher large breasts bouncing slightly with each step. She then walks toward sex with a slow, seductive sway with sex large breasts bouncing slightly with each step. She then walks toward tape with a slow, seductive sway with tape large breasts bouncing slightly with each step. She then walks toward amy with a slow, seductive sway with amy large breasts bouncing slightly with each step. She then walks toward fisher with a slow, seductive sway with fisher large breasts bouncing slightly with each step. You are one gorgeous girl and sex won't hurt sex any, just keep doing what sex say. You are one gorgeous girl and tape won't hurt tape any, just keep doing what tape say. You are one gorgeous girl and free won't hurt free any, just keep doing what free say. You are one gorgeous girl and amy won't hurt amy any, just keep doing what amy say. You are one gorgeous girl and fisher won't hurt fisher any, just keep doing what fisher say. You are one gorgeous girl and sex won't hurt sex any, just keep doing what sex say. You are one gorgeous girl and tapes won't hurt tapes any, just keep doing what tapes say. You are one gorgeous girl and amy won't hurt amy any, just keep doing what amy say. You are one gorgeous girl and fisher won't hurt fisher any, just keep doing what fisher say. You are one gorgeous girl and sex won't hurt sex any, just keep doing what sex say. You are one gorgeous girl and tape won't hurt tape any, just keep doing what tape say. You are one gorgeous girl and download won't hurt download any, just keep doing what download say. ?She then says, ?Thanks, amy can come in, and place amy on the table next to the tub, if amy don?t mind. ?She then says, ?Thanks, fisher can come in, and place fisher on the table next to the tub, if fisher don?t mind. ?She then says, ?Thanks, sex can come in, and place sex on the table next to the tub, if sex don?t mind. ?She then says, ?Thanks, tape can come in, and place tape on the table next to the tub, if tape don?t mind. ?She then says, ?Thanks, clips can come in, and place clips on the table next to the tub, if clips don?t mind. ?She then says, ?Thanks, amy can come in, and place amy on the table next to the tub, if amy don?t mind. ?She then says, ?Thanks, fisher can come in, and place fisher on the table next to the tub, if fisher don?t mind. ?She then says, ?Thanks, free can come in, and place free on the table next to the tub, if free don?t mind. ?She then says, ?Thanks, sex can come in, and place sex on the table next to the tub, if sex don?t mind. ?She then says, ?Thanks, tape can come in, and place tape on the table next to the tub, if tape don?t mind. ?She then says, ?Thanks, a can come in, and place a on the table next to the tub, if a don?t mind. ?She then says, ?Thanks, sex can come in, and place sex on the table next to the tub, if sex don?t mind. As tape watched, tape sprung a full blown hard on, just looking at her. As of watched, of sprung a full blown hard on, just looking at her. As amy watched, amy sprung a full blown hard on, just looking at her. As fisher watched, fisher sprung a full blown hard on, just looking at her. As and watched, and sprung a full blown hard on, just looking at her. As her watched, her sprung a full blown hard on, just looking at her. As husband watched, husband sprung a full blown hard on, just looking at her. As amy watched, amy sprung a full blown hard on, just looking at her. As fisher watched, fisher sprung a full blown hard on, just looking at her. As sex watched, sex sprung a full blown hard on, just looking at her. As tape watched, tape sprung a full blown hard on, just looking at her. As sex watched, sex sprung a full blown hard on, just looking at her. ? Oh fuck, tape cock was getting hard again. ? Oh fuck, of cock was getting hard again. ? Oh fuck, amy cock was getting hard again. ? Oh fuck, fisher cock was getting hard again. ? Oh fuck, download cock was getting hard again. ? Oh fuck, amy cock was getting hard again. ? Oh fuck, fisher cock was getting hard again. ? Oh fuck, sex cock was getting hard again. ? Oh fuck, tape cock was getting hard again. ? Oh fuck, watch cock was getting hard again. ? Oh fuck, amy cock was getting hard again. ? Oh fuck, fisher cock was getting hard again. sex knew a second later when the needle passed through both of my labia. tape knew a second later when the needle passed through both of my labia. amy knew a second later when the needle passed through both of my labia. fisher knew a second later when the needle passed through both of my labia. sex knew a second later when the needle passed through both of my labia. tape knew a second later when the needle passed through both of my labia. uncensored knew a second later when the needle passed through both of my labia. amy knew a second later when the needle passed through both of my labia. fisher knew a second later when the needle passed through both of my labia. sex knew a second later when the needle passed through both of my labia. tape knew a second later when the needle passed through both of my labia. free knew a second later when the needle passed through both of my labia. Then lifts them to download mouth and licks the cunt juice from them. Then lifts them to amy mouth and licks the cunt juice from them. Then lifts them to fisher mouth and licks the cunt juice from them. Then lifts them to sex mouth and licks the cunt juice from them. Then lifts them to tape mouth and licks the cunt juice from them. Then lifts them to preview mouth and licks the cunt juice from them. Then lifts them to amy mouth and licks the cunt juice from them. Then lifts them to fisher mouth and licks the cunt juice from them. Then lifts them to sex mouth and licks the cunt juice from them. Then lifts them to tape mouth and licks the cunt juice from them. Then lifts them to review mouth and licks the cunt juice from them. Then lifts them to amy mouth and licks the cunt juice from them. fisher wasn't tied. sex wasn't tied. tape wasn't tied. uncut wasn't tied. amy wasn't tied. fisher wasn't tied. sex wasn't tied. tapes wasn't tied. gallery wasn't tied. amy wasn't tied. fisher wasn't tied. When sex comes near sex ass, sex sighs, then slaps sex butt gently and giggles, ?You have a nice ass baby, if sex don?t mind sex saying so. When tape comes near tape ass, tape sighs, then slaps tape butt gently and giggles, ?You have a nice ass baby, if tape don?t mind tape saying so. When amy comes near amy ass, amy sighs, then slaps amy butt gently and giggles, ?You have a nice ass baby, if amy don?t mind amy saying so. When fisher comes near fisher ass, fisher sighs, then slaps fisher butt gently and giggles, ?You have a nice ass baby, if fisher don?t mind fisher saying so. When sex comes near sex ass, sex sighs, then slaps sex butt gently and giggles, ?You have a nice ass baby, if sex don?t mind sex saying so. When tape comes near tape ass, tape sighs, then slaps tape butt gently and giggles, ?You have a nice ass baby, if tape don?t mind tape saying so. When sample comes near sample ass, sample sighs, then slaps sample butt gently and giggles, ?You have a nice ass baby, if sample don?t mind sample saying so. When release comes near release ass, release sighs, then slaps release butt gently and giggles, ?You have a nice ass baby, if release don?t mind release saying so. When date comes near date ass, date sighs, then slaps date butt gently and giggles, ?You have a nice ass baby, if date don?t mind date saying so. When amy comes near amy ass, amy sighs, then slaps amy butt gently and giggles, ?You have a nice ass baby, if amy don?t mind amy saying so. When fisher comes near fisher ass, fisher sighs, then slaps fisher butt gently and giggles, ?You have a nice ass baby, if fisher don?t mind fisher saying so. When sex comes near sex ass, sex sighs, then slaps sex butt gently and giggles, ?You have a nice ass baby, if sex don?t mind sex saying so. If tape could have screamed tape certainly would have. If sex could have screamed sex certainly would have. If tape could have screamed tape certainly would have. If amy could have screamed amy certainly would have. If fisher could have screamed fisher certainly would have. If the could have screamed the certainly would have. If amy could have screamed amy certainly would have. If fisher could have screamed fisher certainly would have. If sex could have screamed sex certainly would have. If tape could have screamed tape certainly would have. If amy could have screamed amy certainly would have. If fisher could have screamed fisher certainly would have. If promotes could have screamed promotes certainly would have. See sex in a few minutes. See tape in a few minutes. See amy in a few minutes. See fisher in a few minutes. See sex in a few minutes. See tape in a few minutes. See full in a few minutes. See download in a few minutes. See amy in a few minutes. See fisher in a few minutes. See sex in a few minutes. See tape in a few minutes. pictures couldn't speak! I'll clean pictures up, then you'll have some washing to do. amy couldn't speak! I'll clean amy up, then you'll have some washing to do. fisher couldn't speak! I'll clean fisher up, then you'll have some washing to do. sex couldn't speak! I'll clean sex up, then you'll have some washing to do. tape couldn't speak! I'll clean tape up, then you'll have some washing to do. rapidshare couldn't speak! I'll clean rapidshare up, then you'll have some washing to do. amy couldn't speak! I'll clean amy up, then you'll have some washing to do. sex couldn't speak! I'll clean sex up, then you'll have some washing to do. fisher couldn't speak! I'll clean fisher up, then you'll have some washing to do. tape couldn't speak! I'll clean tape up, then you'll have some washing to do. amy couldn't speak! I'll clean amy up, then you'll have some washing to do. fisher couldn't speak! I'll clean fisher up, then you'll have some washing to do. After all sex is quite handsome and sex prefers older men. After all tape is quite handsome and tape prefers older men. After all downloads is quite handsome and downloads prefers older men. After all amy is quite handsome and amy prefers older men. After all fisher is quite handsome and fisher prefers older men. After all sex is quite handsome and sex prefers older men. After all tape is quite handsome and tape prefers older men. After all links is quite handsome and links prefers older men. After all amy is quite handsome and amy prefers older men. After all fisher is quite handsome and fisher prefers older men. After all sex is quite handsome and sex prefers older men. After all tape is quite handsome and tape prefers older men. ?As screen glasses clicked screen told himself, ?The best is yet to come, my precious Valentine. ?As shot glasses clicked shot told himself, ?The best is yet to come, my precious Valentine. ?As amy glasses clicked amy told himself, ?The best is yet to come, my precious Valentine. ?As fisher glasses clicked fisher told himself, ?The best is yet to come, my precious Valentine. ?As sex glasses clicked sex told himself, ?The best is yet to come, my precious Valentine. ?As tape glasses clicked tape told himself, ?The best is yet to come, my precious Valentine. ?As torrent glasses clicked torrent told himself, ?The best is yet to come, my precious Valentine. ?As amy glasses clicked amy told himself, ?The best is yet to come, my precious Valentine. ?As fisher glasses clicked fisher told himself, ?The best is yet to come, my precious Valentine. ?As sex glasses clicked sex told himself, ?The best is yet to come, my precious Valentine. ?As tape glasses clicked tape told himself, ?The best is yet to come, my precious Valentine. ?As where glasses clicked where told himself, ?The best is yet to come, my precious Valentine. His hand would slip and caress can breast. His hand would slip and caress i breast. His hand would slip and caress find breast. His hand would slip and caress amy breast. His hand would slip and caress fisher breast. His hand would slip and caress xxx breast. His hand would slip and caress sex breast. His hand would slip and caress tape breast. His hand would slip and caress where breast. His hand would slip and caress can breast. His hand would slip and caress i breast. His hand would slip and caress find breast. Here was one of the girdles, a pair of the bloomers and several pairs of the knickers - not to mention stockings, bras and slips (petticoats, as the called them then). Here was one of amy girdles, a pair of amy bloomers and several pairs of amy knickers - not to mention stockings, bras and slips (petticoats, as amy called them then). Here was one of fisher girdles, a pair of fisher bloomers and several pairs of fisher knickers - not to mention stockings, bras and slips (petticoats, as fisher called them then). Here was one of sex girdles, a pair of sex bloomers and several pairs of sex knickers - not to mention stockings, bras and slips (petticoats, as sex called them then). Here was one of tape girdles, a pair of tape bloomers and several pairs of tape knickers - not to mention stockings, bras and slips (petticoats, as tape called them then). Here was one of for girdles, a pair of for bloomers and several pairs of for knickers - not to mention stockings, bras and slips (petticoats, as for called them then). Here was one of free girdles, a pair of free bloomers and several pairs of free knickers - not to mention stockings, bras and slips (petticoats, as free called them then). Here was one of amy girdles, a pair of amy bloomers and several pairs of amy knickers - not to mention stockings, bras and slips (petticoats, as amy called them then). Here was one of fisher girdles, a pair of fisher bloomers and several pairs of fisher knickers - not to mention stockings, bras and slips (petticoats, as fisher called them then). Here was one of nudity girdles, a pair of nudity bloomers and several pairs of nudity knickers - not to mention stockings, bras and slips (petticoats, as nudity called them then). Here was one of sex girdles, a pair of sex bloomers and several pairs of sex knickers - not to mention stockings, bras and slips (petticoats, as sex called them then). Here was one of tape girdles, a pair of tape bloomers and several pairs of tape knickers - not to mention stockings, bras and slips (petticoats, as tape called them then). Here was one of amy girdles, a pair of amy bloomers and several pairs of amy knickers - not to mention stockings, bras and slips (petticoats, as amy called them then). fisher leaned back, fisher eyes fixed on my cock as fisher pushed against fisher innocent teen slit, stretching fisher virgin love hole as my head penetrated fisher wetness. sex leaned back, sex eyes fixed on my cock as sex pushed against sex innocent teen slit, stretching sex virgin love hole as my head penetrated sex wetness. tape leaned back, tape eyes fixed on my cock as tape pushed against tape innocent teen slit, stretching tape virgin love hole as my head penetrated tape wetness. clip leaned back, clip eyes fixed on my cock as clip pushed against clip innocent teen slit, stretching clip virgin love hole as my head penetrated clip wetness. amy leaned back, amy eyes fixed on my cock as amy pushed against amy innocent teen slit, stretching amy virgin love hole as my head penetrated amy wetness. fisher leaned back, fisher eyes fixed on my cock as fisher pushed against fisher innocent teen slit, stretching fisher virgin love hole as my head penetrated fisher wetness. sex leaned back, sex eyes fixed on my cock as sex pushed against sex innocent teen slit, stretching sex virgin love hole as my head penetrated sex wetness. tape leaned back, tape eyes fixed on my cock as tape pushed against tape innocent teen slit, stretching tape virgin love hole as my head penetrated tape wetness. part leaned back, part eyes fixed on my cock as part pushed against part innocent teen slit, stretching part virgin love hole as my head penetrated part wetness. 2 leaned back, 2 eyes fixed on my cock as 2 pushed against 2 innocent teen slit, stretching 2 virgin love hole as my head penetrated 2 wetness. amy leaned back, amy eyes fixed on my cock as amy pushed against amy innocent teen slit, stretching amy virgin love hole as my head penetrated amy wetness. fisher leaned back, fisher eyes fixed on my cock as fisher pushed against fisher innocent teen slit, stretching fisher virgin love hole as my head penetrated fisher wetness. In sex mind, sex was saying, ?Rebecca, don?t worry sex pretty little head, sex intend to marry sex daughter. In tape mind, tape was saying, ?Rebecca, don?t worry tape pretty little head, tape intend to marry tape daughter. In warez mind, warez was saying, ?Rebecca, don?t worry warez pretty little head, warez intend to marry warez daughter. In amy mind, amy was saying, ?Rebecca, don?t worry amy pretty little head, amy intend to marry amy daughter. In fisher mind, fisher was saying, ?Rebecca, don?t worry fisher pretty little head, fisher intend to marry fisher daughter. In sex mind, sex was saying, ?Rebecca, don?t worry sex pretty little head, sex intend to marry sex daughter. In tape mind, tape was saying, ?Rebecca, don?t worry tape pretty little head, tape intend to marry tape daughter. In with mind, with was saying, ?Rebecca, don?t worry with pretty little head, with intend to marry with daughter. In husband mind, husband was saying, ?Rebecca, don?t worry husband pretty little head, husband intend to marry husband daughter. In amy mind, amy was saying, ?Rebecca, don?t worry amy pretty little head, amy intend to marry amy daughter. In fisher mind, fisher was saying, ?Rebecca, don?t worry fisher pretty little head, fisher intend to marry fisher daughter. I joined my parents and uncut walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and sex walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and tape walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and part3 walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and free walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and amy walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and fisher walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and sex walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and tape walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and movies walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and free walked into a large room decorated with flowers where the wedding service was being held. I joined my parents and amy walked into a large room decorated with flowers where the wedding service was being held. fisher was just thinking about this dress fisher saw in a magazine, and how good fisher would look on you. sex was just thinking about this dress sex saw in a magazine, and how good sex would look on you. tapes was just thinking about this dress tapes saw in a magazine, and how good tapes would look on you. leaked was just thinking about this dress leaked saw in a magazine, and how good leaked would look on you. amy was just thinking about this dress amy saw in a magazine, and how good amy would look on you. fisher was just thinking about this dress fisher saw in a magazine, and how good fisher would look on you. sex was just thinking about this dress sex saw in a magazine, and how good sex would look on you. tape was just thinking about this dress tape saw in a magazine, and how good tape would look on you. long was just thinking about this dress long saw in a magazine, and how good long would look on you. island was just thinking about this dress island saw in a magazine, and how good island would look on you. lolita was just thinking about this dress lolita saw in a magazine, and how good lolita would look on you. amy was just thinking about this dress amy saw in a magazine, and how good amy would look on you. fisher was just thinking about this dress fisher saw in a magazine, and how good fisher would look on you. At last sex all came to an end and sex trooped past Joe and Samantha as sex welcomed us to the reception. At last tape all came to an end and tape trooped past Joe and Samantha as tape welcomed us to the reception. At last watch all came to an end and watch trooped past Joe and Samantha as watch welcomed us to the reception. At last amy all came to an end and amy trooped past Joe and Samantha as amy welcomed us to the reception. At last fisher all came to an end and fisher trooped past Joe and Samantha as fisher welcomed us to the reception. At last sex all came to an end and sex trooped past Joe and Samantha as sex welcomed us to the reception. At last tape all came to an end and tape trooped past Joe and Samantha as tape welcomed us to the reception. At last for all came to an end and for trooped past Joe and Samantha as for welcomed us to the reception. At last free all came to an end and free trooped past Joe and Samantha as free welcomed us to the reception. At last watchable all came to an end and watchable trooped past Joe and Samantha as watchable welcomed us to the reception. At last amy all came to an end and amy trooped past Joe and Samantha as amy welcomed us to the reception. At last fisher all came to an end and fisher trooped past Joe and Samantha as fisher welcomed us to the reception. Okay, sex hear you. Okay, tape hear you. Okay, where hear you. Okay, can hear you. Okay, i hear you. Okay, find hear you. Okay, amy hear you. Okay, fisher hear you. Okay, sex hear you. Okay, tape hear you. Okay, for hear you. Okay, free hear you. From lists at cheimes.de Tue Sep 16 11:56:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 16 Sep 2008 17:56:19 +0200 Subject: How do I add permanently to Pythons sys.path? In-Reply-To: <A183D966-C2F9-453F-8A74-CB0ADEDEBDE2@rgbaz.eu> References: <b93a71a3-4496-4e18-af64-36e06e4ce646@x35g2000hsb.googlegroups.com> <A183D966-C2F9-453F-8A74-CB0ADEDEBDE2@rgbaz.eu> Message-ID: <gaokv2$922$1@ger.gmane.org> Python wrote: > a temp solution is to append it to that list: > > sys.path.append('C:/Python25/Progs/') > > a permanent solution is to add it to the environment variable > (no idea where to set this in windows) > $PYTHONPATH = "/C:/Python25/Progs/" Don't append a / or \!Use "C:/Python25/Progs" instead of "C:/Python25/Progs/". The trailing slash causes trouble on Windows. The reason for the trouble is design decision from Microsoft. The low level stat() syscall returns an error for "C:\\Python25\\Progs\\" but it returns success for "C:\\Python25\\Progs". Christian From steven at REMOVE.THIS.cybersource.com.au Tue Sep 30 05:32:41 2008 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 30 Sep 2008 09:32:41 GMT Subject: How best to pass arbitrary parameters from one function to another References: <mailman.1731.1222764932.3487.python-list@python.org> Message-ID: <pan.2008.09.30.09.32.41@REMOVE.THIS.cybersource.com.au> On Tue, 30 Sep 2008 08:58:15 +0000, John O'Hagan wrote: > Hi Pythonistas, > > I'm looking for the best way to pass an arbitrary number and type of > variables created by one function to another. They can't be global > because they may have different values each time they are used in the > second function. > > So far I'm trying to do something like this: > > > def process_args( [list, of, command-line, arguments] ): If you are trying to process commandline args, I suggest you don't re- invent the wheel. Have a look at the two standard modules, optparse and getopt. Of the two, getopt is probably simpler to get started with, but optparse is more powerful. To answer your more general question, see below. > do stuff > return {dictionary : of, local : variables } > > def main_function( **kwargs ): > > do stuff > return result > > kw1 = process_args( [some, list] ) > kw2 = process_args( [a, different, list] ) > > for i in main_function( **kw1 ): > > kw2[ var1 ] = i > kw2[ var2 ] = len( i ) > > for j in main_function(**kw2): > > print j > > This only seems to work if I specify a default value for every possible > parameter of main_function and also for any others which may be passed > to it, which is a bit tedious because there are very many of them but > only a few are used in any given execution of the program. Er, yes. Presumably main_function actually does something. So it expects some arguments, and if the arguments aren't given, then it will fail. To prevent it failing when arguments aren't given, they must have default values. So define them, once, and be done with it: def main_function(a=1, b=2, c=3, d=4): dostuff return result Now this will work fine: result = main_function( **{'a': 22, 'd': 33} ) and b and c will take their default values and everything works well. Default values are a feature, not a problem to be solved. As for your nested for-loops (see above), I'm guessing that you're trying to copy items from one dictionary kw1 to another kw2, before processing kw2. You should check out the update method on dictionaries. Either of: kw2.update(kw1) kw1.update(kw2) will probably do the right thing, depending on which values you want to take priority in the case of clashes. If you need something even more flexible, write a small function to merge the two dicts in whatever way you want. Here's one example: def merge(kw1, kw2): """Merge dict kw1 to kw2 and return a new dict.""" new = kw2.copy() for key, value in kw1.items(): if key in kw2: # clash, keep the biggest value new[key] = max(value, kw2[key]) else: new[key] = value return new -- Steven From ronald.chis at googlemail.com Tue Sep 16 13:31:21 2008 From: ronald.chis at googlemail.com (ronald.chis) Date: Tue, 16 Sep 2008 10:31:21 -0700 (PDT) Subject: Iwebs v1.2 - Open Source Web-Publishing Platform for Bloggers and website builders available Now Message-ID: <80ad040d-3e23-4456-a656-0832f0b2d132@k13g2000hse.googlegroups.com> Iwebs v1.2 - Open Source Web-Publishing Platform for Bloggers and website builders available Now- (Sept 16-2008) With more updations iwebs version 1.2 can be downloaded here - http://webs.investorline.co.in/. Features The following is a list of some of the features that come standard with iwebs, however there are literally hundreds of plugins (on WordPress Site that can also be used with iwebs) that extend what iwebs does, so the actual functionality is nearly limitless. You are also free to do whatever you like with the iwebs code, extend it or modify in any way or use it for commercial projects without any licensing fees. That is the beauty of free software, free meaning not only price but also the freedom to have complete control over it. Key Features * Full standards compliance ? We have gone to great lengths to make sure every bit of iwebs generated code is in full compliance with the standards of the W3C. This is important not only for interoperability with today?s browser but also for forward compatibility with the tools of the next generation. Your web site is a beautiful thing, and you should demand nothing less. * No rebuilding ? Changes you make to your templates or entries are reflected immediately on your site, with no need for regenerating static pages. * Iwebs Pages ? Pages allow you to manage non-blog content easily, so for example you could have a static ?About? page that you manage through iwebs. For an idea of how powerful this is, the entire http://investorline.co.in site could be run off iwebs alone. * Iwebs Links ? Links allows you to create, maintain, and update any number of blogrolls through your administration interface. This is much faster than calling an external blogroll manager. * Themes ? Iwebs comes with 20 great looking themes designed by several professional designers, which makes designing everything from the simplest blog to the most complicated webzine a piece of cake, and you can even have multiple themes with totally different looks that you switch with a single click. Have a new design every day. You can even install more designs at http://webs.investorline.co.in. * Cross-blog communication tools? Iwebs fully supports both the Trackback and Pingback standards, and we are committed to supporting future standards as they develop. * Comments ? Visitors to your site can leave comments on individual entries, and through Trackback or Pingback can comment on their own site. You can enable or disable comments on a per-post basis. * Spam protection ? Iwebs comes with very robust tools such as an integrated blacklist and open proxy checker to manage and eliminate comment spam on your blog, and there is also a rich array of plugins that can take this functionality a step further. * Full user registration ? Iwebs has a built-in user registration system that (if you choose) can allow people to register and maintain profiles and leave authenticated comments on your blog. You can optionally close comments for non-registered users. There are also plugins that hide posts from lower level users * Password Protected Posts ? You can give passwords to individual posts to hide them from the public. You can also have private posts which are viewable only by their author. * Easy installation and upgrades ? Installing iwebs and upgrading from previous versions and other software is a piece of cake. Try it and you?ll wonder why all web software isn?t this easy. * Easy Importing ? We currently have importers for Movable Type, Textpattern, Greymatter, Blogger, and b2. Work on importers for Nucleus and pMachine are under way. * XML-RPC interface ? Iwebs currently supports an extended version of the Blogger API, MetaWeblog API, and finally the MovableType API. You can even use clients designed for other platforms like Zempt. * Workflow ? You can have types of users that can only post drafts, not publish to the front page. * Typographical niceties ? Iwebs uses the Texturize engine to intelligently convert plain ASCII into typographically correct XHTML entities. This includes quotes, apostrophes, ellipses, em and en dashes, multiplication symbols, and ampersands. For information about the proper use of such entities see Peter Sheerin?s article The Trouble With Em ?n En. * Intelligent text formatting ? If you?ve dealt with systems that convert new lines to line breaks before you know why they have a bad name: if you have any sort of HTML they butcher it by putting tags after every new line indiscriminately, breaking your formatting and validation. Our function for this intelligently avoids places where you already have breaks and block-level HTML tags, so you can leave it on without worrying about it breaking your code. * Multiple authors ? Iwebs? highly advanced user system allows up to 10 levels of users, with different levels having different (and configurable) privileges with regard to publishing, editing, options, and other users. * Bookmarklets ? Cross-browser bookmarklets make it easy to publish to your blog or add links to your blogroll with a minimum of effort. * Ping away ? Iwebs supports pinging Ping-O-Matic, which means maximum exposure for your blog to search engines. * Plugins- Iwebs comes bundles with 14 diffrent plugins which further enhances the capabilities of iwebs. To know more about the plugins that comes with standard installation visit plugins section. There?s much more, but these are the highlights. If there?s something that you really want, submit a request on the support forums and there?s a good chance someone will whip it up for you. Download it here - http://webs.investorline.co.in/ From fredrik at pythonware.com Thu Sep 4 16:42:28 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 04 Sep 2008 22:42:28 +0200 Subject: why is self not passed to id()? In-Reply-To: <g9pg72$3vi$1@aioe.org> References: <g9pg72$3vi$1@aioe.org> Message-ID: <g9ph7l$ftb$1@ger.gmane.org> Ruediger wrote: > Executing following little program gives me an TypeError. > > What makes me wonder is that foo does get an argument passed while bar > doesn't. Can anyone explain why?????? >>> id <built-in function id> >>> lambda x: id(x) <function <lambda> at 0x00C07C30> any special reason why you're not using Python to write Python programs, btw? </F> From half.italian at gmail.com Thu Sep 11 14:43:21 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 11 Sep 2008 11:43:21 -0700 (PDT) Subject: Python platform. References: <1808172a-273f-4e24-936a-a1eb1589bab7@d45g2000hsc.googlegroups.com> <mailman.876.1221142791.3487.python-list@python.org> <8790688e-5aff-4948-8baa-db413b0caead@a1g2000hsb.googlegroups.com> <mailman.880.1221152366.3487.python-list@python.org> <734ce614-3e92-4515-9342-d2e4e88c9632@b30g2000prf.googlegroups.com> Message-ID: <152effa1-1678-4bb1-85a0-a5340749d6a3@p10g2000prf.googlegroups.com> On Sep 11, 11:39?am, Sean DiZazzo <half.ital... at gmail.com> wrote: > On Sep 11, 9:59?am, Fredrik Lundh <fred... at pythonware.com> wrote: > > > > > carriere.jonat... at gmail.com wrote: > > > I want to build a desktop application. I am searching for some kind of > > > environment that would provide all the elements ready (Windows...). > > > Then I would have to code the business logic only. > > > start here: > > > ? ?http://wiki.python.org/moin/GuiProgramming > > > The big ones are Tkinter, which is usually bundled with Python; > > wxPython, and PyQt. ?There's also a trend towards using the web browser > > as a presentation engine also for local applications; for libraries that > > help you with that, you can start here: > > > ? ?http://wiki.python.org/moin/WebProgramming > > > or jump directly to > > > ? ?http://www.djangoproject.com/ > > > </F> > > I saw a message in the last few days showing how to use Flash as a > front end for Python apps. ?It looked interested. > > Can anyone point me to it? > > ~Sean Ahh...i see. It was the xml-rpc method you mentioned. Looks interesting to me if it's fairly responsive for normal gui apps. http://www.artima.com/weblogs/viewpost.jsp?thread=208528 ~Sean From robert.kern at gmail.com Tue Sep 23 15:53:13 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 23 Sep 2008 14:53:13 -0500 Subject: Python is slow? In-Reply-To: <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <1c4b005f-2e17-4a2e-ad82-a7007c6e105b@b1g2000hsg.googlegroups.com> <0fe14118-402a-42fe-a9fc-63420f7feca0@w24g2000prd.googlegroups.com> Message-ID: <gbbhf9$b84$1@ger.gmane.org> J Peyret wrote: > On Sep 23, 8:31 am, bearophileH... at lycos.com wrote: > > Guys, this looks like a great data structure/algo for something I am > working on. > > But... where do I find some definitions of the original BK-tree idea? Uh, actually we're talking about kd-trees, not BK-trees. kd-trees are for searching through point sets in a k-dimensional space. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From marco.bizzarri at gmail.com Wed Sep 10 09:19:11 2008 From: marco.bizzarri at gmail.com (Marco Bizzarri) Date: Wed, 10 Sep 2008 15:19:11 +0200 Subject: Adding further report options to unittest.py Message-ID: <3f0d61c40809100619i2631fb64p846dea0fea3f2051@mail.gmail.com> Hi all. I would like to change the way test reports are generated, in a Zope environment. I'm playing with TextTestReport, TextTestRunner. Since things are getting to complicated, I'm afraid I'm following a non-pythonic way. Specifically, I would like to have an output like: package.subpackage.test_module.TestCase 0.1 where 0.1 is the time spent into doing the test. In a previous attempt, I made the tests print the number of the test executed, so that I would have the following output: 1 package.subpackage.test_module.TestCase however, to do this, I had to put things in the following way: class PAFlowTestRunner(TextTestRunner): def _makeResult(self): return PAFlowTextResult(self.stream, self.descriptions, self.verbosity) class PAFlowTextResult(_TextTestResult): def startTest(self, test): self.stream.write("%s " % self.testsRun) _TextTestResult.startTest(self, test) now, of course, this is ugly, because I'm using _TextTestResult, which I'm not supposed to know, and I'm changing behaviour by subclassing, which is not exactly what I would like to do. What is the pythonic way to accomplish this? Marco -- Marco Bizzarri http://notenotturne.blogspot.com/ http://iliveinpisa.blogspot.com/ From prologic at shortcircuit.net.au Sun Sep 7 18:06:18 2008 From: prologic at shortcircuit.net.au (James Mills) Date: Mon, 8 Sep 2008 08:06:18 +1000 Subject: Updating python dictionary In-Reply-To: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> References: <9ff21908-d95e-4469-935b-e4e31a62705e@m44g2000hsc.googlegroups.com> Message-ID: <e1a84d570809071506k22a48650q2c4e1af372311e4f@mail.gmail.com> Hi, There is "never" a "clever" way of doing anything, but: $ cat test.py MAPPING_DICT = {'a': 'A','b': 'B',} my_dict = {'a': '1','b': '2'} my_dict = dict((MAPPING_DICT[k], my_dict[k]) for k in my_dict) print my_dict $ python test.py {'A': '1', 'B': '2'} $ That should do the trick. cheers James On Mon, Sep 8, 2008 at 7:51 AM, andyhume at gmail.com <andyhume at gmail.com> wrote: > Hello... > > I have a dict of key/values and I want to change the keys in it, based > on another mapping dictionary. An example follows: > > MAPPING_DICT = { > 'a': 'A', > 'b': 'B', > } > > my_dict = { > 'a': '1', > 'b': '2' > } > > I want the finished my_dict to look like: > > my_dict = { > 'A': '1', > 'B': '2' > } > > Whereby the keys in the original my_dict have been swapped out for the > keys mapped in MAPPING_DICT. > > Is there a clever way to do this, or should I loop through both, > essentially creating a brand new dict? > > Cheers, > Andy. > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- -- "Problems are solved by method" From benjamin.kaplan at case.edu Fri Sep 26 15:28:39 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 26 Sep 2008 15:28:39 -0400 Subject: how to replace and string in a "SELECT ... IN ()" In-Reply-To: <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> References: <d2e0f916-5cff-4ba7-ac2f-d59b7a2878e2@j22g2000hsf.googlegroups.com> <48dcc0ce$0$25400$426a34cc@news.free.fr> <48DCC618.9040907@wildenhain.de> <170543c70809260510o47220748s30e9ce94bb20937d@mail.gmail.com> <48DCDE1F.6040709@wildenhain.de> <170543c70809260738s2f677835o568fdf7923a03cca@mail.gmail.com> <ec96e1390809260750p36220609me676294ebdda841e@mail.gmail.com> <170543c70809260900w4e9f0ac5rd312b03a7839433d@mail.gmail.com> <20080926123848.98c06cd5.darcy@druid.net> <170543c70809261204q5f84ee30g5bd31372a7cc7fe6@mail.gmail.com> Message-ID: <ec96e1390809261228h66888b16pfbbb280aa3cc358@mail.gmail.com> On Fri, Sep 26, 2008 at 3:04 PM, Michael Mabin <d3vvnull at gmail.com> wrote: > Doesn't it depend on where and why you intend to execute the code? > Obviously some SQL is more at risk for exploit when the input is from the > screen on a web page than if you were running parameterized code in a > controlled batch environment. Or if you were writing code generators (which > is what I happen to do) which won't be run by the general public. > > Incidentally, couldn't input field edits prevent such exploits prior to > interpolation? > There are ways to avoid SQL injection attacks, such as escaping all quotes in the text. We were simply pointing out that you have to be very careful when you add arbitrary strings into SQL statements. If you control everything going into the statement, you shouldn't have to worry about this. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080926/3908055f/attachment-0001.html> From castironpi at gmail.com Sun Sep 14 12:10:07 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Sun, 14 Sep 2008 09:10:07 -0700 (PDT) Subject: Function getting a reference to its own module References: <00dcd3b6$0$20302$c3e8da3@news.astraweb.com> <7b4b9efb-336c-4adf-9717-0cb22323e5b7@a70g2000hsh.googlegroups.com> Message-ID: <f38eddfe-ca5a-4595-b898-e7ca70119f83@d1g2000hsg.googlegroups.com> On Sep 14, 4:43?am, Arnaud Delobelle <arno... at googlemail.com> wrote: > On Sep 14, 10:29?am, Steven D'Aprano <st... at REMOVE-THIS- > > > > cybersource.com.au> wrote: > > I have a function that needs a reference to the module object it is > > defined in. (For the reason why, if you care, see the thread "doctest not > > seeing any of my doc tests" from a week ago.) I know of two ways to deal > > with this problem, both of which feel unsatisfactory to me. Assume the > > name of the module is "Mod", then I can do either of these: > > > def foo(): > > ? ? import Mod > > ? ? process(Mod) > > > Disadvantage: If I change the name of the module, I have to remember to > > change the name of the module reference in foo() twice. > > > def foo(): > > ? ? modname = foo.__module__ > > ? ? module = __import__(modname) > > ? ? process(module) > > > Disadvantage: if I change the name of the function, I have to remember to > > change the reference to itself, but at least both changes are right next > > to each other. > > > Assume that changing the function name or the module name are both > > equally likely/unlikely. > > > Which do other people prefer? Which seems "better" to you? Are there any > > other alternatives? > > What about something like: > > ? ? sys.modules[__name__] ? > > -- > Arnaud You're just worried about changing the module's name in the future. So use a global variable or function that you only have to change once. def Mod_mod( ): import Mod as Mod #<-- only one change needed return Mod def foo( ): process( Mod_mod( ) ) From maric at aristote.info Mon Sep 15 07:29:45 2008 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 Sep 2008 13:29:45 +0200 Subject: how to protect the source In-Reply-To: <BLU115-W513E8E918A8A16CEB298E596520@phx.gbl> References: <BLU115-W513E8E918A8A16CEB298E596520@phx.gbl> Message-ID: <200809151329.45811.maric@aristote.info> Le Monday 15 September 2008 13:02:58 Jo?o Abrantes, vous avez ?crit?: > Hello Everyone. > Hello, > > I am building a client in python that will connect himself to a mysql > server with a certain username and password. I will compile this client > and turn him into a .exe . The thing is that I know that is possible to > get the source of the code back from an .exe and I don't want anyone to > know which username and password are they using because I don't want > them to access to the mysql server without my client. Do you have any > ideas of what can i do? Thanks! You're going on the wrong path. It's far easier to sniff the network traffic to get the password than to decompile the program. Furthermore you can't achieve good security this way (games vendors try hard to do this but are always defeated). You can't hope to gain control on what your users do with the access you gave them. So, the right thing to do is to only allow on the database server the operations your client app needs given the account you created specifically for it. -- _____________ Maric Michaud From hussainsaiger at gmail.com Mon Sep 1 02:42:25 2008 From: hussainsaiger at gmail.com (hussainsaiger at gmail.com) Date: Sun, 31 Aug 2008 23:42:25 -0700 (PDT) Subject: Using NLTK in Java Message-ID: <2cdf2d5f-4b96-4da8-9d6c-4e9557232345@k7g2000hsd.googlegroups.com> I am trying to convert a python module (that contains the use of NLTK.Corpus) by jythonc. It is not able to include nltk dependencies within the java class it creates. So when i use this class in java, it fails to recognize nltk. Can anyone please let me know how should i use nltk in python/jython modules so i can use in Java. From adityashukla1983 at gmail.com Thu Sep 11 04:39:40 2008 From: adityashukla1983 at gmail.com (aditya shukla) Date: Thu, 11 Sep 2008 03:39:40 -0500 Subject: Adding environment variables to bash. Message-ID: <73045cca0809110139g6d1feb5p32ccacc1c91a010e@mail.gmail.com> Hello folks Can i add any environment variable to bash from my python script? so that when i use env command then i can see that environment variable. Thanks Aditya -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080911/6a2634a8/attachment-0001.html> From steve at REMOVE-THIS-cybersource.com.au Tue Sep 9 18:58:01 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 09 Sep 2008 22:58:01 GMT Subject: dynamic allocation file buffer References: <695ed75f-eee6-46bb-b950-ef9d792152b3@c58g2000hsc.googlegroups.com> Message-ID: <00d6f9bd$0$20306$c3e8da3@news.astraweb.com> On Tue, 09 Sep 2008 14:59:19 -0700, castironpi wrote: > I will try my idea again. I want to talk to people about a module I > want to write and I will take the time to explain it. I think it's a > "cool idea" that a lot of people, forgiving the slang, could benefit > from. What are its flaws? [snip long description with not-very-credible use-cases] You've created a solution to a problem which (probably) only affects a very small number of people, at least judging by your use-cases. Who has a 4GB XML file, and how much crack did they smoke? Castironpi, what do *you* use this proof-of-concept module for? Don't bother tell us what you think *we* should use it for. Tell us what you're using it for, or at least what somebody else is using it for. If this is just a module that you think will be cool, I don't like your chances of people caring. There is no shortage of "cool" software that isn't useful for anything, and unlike eye-candy, nobody is going to use your module just because they like the algorithm. If you don't have an existing application for the software, then explain what it does (not how) and give some idea of the performance ("it's alpha and written in Python and really slow, but I will re-write it in C and expect it to make a billion random accesses in a 10GB file per millisecond", or whatever). You might be lucky and have somebody say "Hey, that's just the tool I need to solve my problem!". -- Steven From tim_grove at sil.org Tue Sep 2 17:08:50 2008 From: tim_grove at sil.org (Tim Grove) Date: Tue, 02 Sep 2008 22:08:50 +0100 Subject: [cairo] Rendering SVG with libRSVG,Python ... CTYPES SUCCESS AT LAST!!! In-Reply-To: <91882ea90809021242y2c6e8606o621951cfd8f252e1@mail.gmail.com> References: <48BD76B0.8050205@sil.org> <91882ea90809021242y2c6e8606o621951cfd8f252e1@mail.gmail.com> Message-ID: <48BDAB62.20300@sil.org> Thanks for your advice Gerdus, but I have tried your suggestion with no success. It has at least been beneficial to discover a tool which I did not know about in 'Dependency Walker'; all dependencies appear okay. HOWEVER (!!!) I HAVE JUST HAD SUCCESS IN LOADING THE DLL !!! In searching through my 'C:WINDOWS\system32' directory I discovered a subdirectory named 'rsvg' containing a number of .dll's associated with that library, including the ones I was attempting to load. I'm not certain how it got there; I probably added it myself sometime in the last couple of weeks in a vain attempt to solve the problem. In any case, that directory seems to have been the root of my problems causing some path conflicts, since when I deleted it my code ran fine! At last, "l = CDLL('librsvg-2-2.dll')" works! Now to give the rest of your solution a try... Best regards, Tim Gerdus van Zyl wrote: > I created that ctypes recipe since there is no binary for win32. > The python binding for librsvg is part of gnome-python-desktop and as > such you need > a gtk build env which is pretty much impossible to get working. Plus > the build system uses codegen/magic/amuletyendor so I can't even hand > compile it. But if you have some linux development experience (I > don't) you might get it working that way. > > On the ctypes problem from the ctypes list: Try putting all the dll > files in the same directory as the script and then using Dependency > Walker to ensure it's finding the dll dependencies in that directory. > > ~Gerdus > > On Tue, Sep 2, 2008 at 7:24 PM, Tim Grove <tim_grove at sil.org> wrote: > >> In the recipe found at >> http://www.cairographics.org/cookbook/librsvgpython/, the intro reads: >> >> "Normally it's easier to use librsvg Python bindings from PyGTK, so you >> can import rsvg. When that's not an option, you may be able to bind just >> enough of it using the ctypes module to use it. Example for win32 follows." >> >> I've been having trouble getting the actual recipe for ctypes working >> (another story - visit the ctypes mailing list!!!), but I'm looking for >> advice on how to get my pc setup (Windows XP Pro) so that I can use >> "import rsvg" in my python program, as suggested by the intro. Can >> anyone help? >> >> Tim >> _______________________________________________ >> cairo mailing list >> cairo at cairographics.org >> http://lists.cairographics.org/mailman/listinfo/cairo >> >> > _______________________________________________ > cairo mailing list > cairo at cairographics.org > http://lists.cairographics.org/mailman/listinfo/cairo > > From bj_666 at gmx.net Tue Sep 30 01:54:03 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Sep 2008 05:54:03 GMT Subject: Python arrays and sting formatting options References: <75j2e458kk2m7suqsi1a30c6bflg6dki81@4ax.com> <affd6918-3444-4a8f-9816-faa56ee34512@k37g2000hsf.googlegroups.com> <q1r2e458kqe2t7phvj5iorgj0tbnbi7ikb@4ax.com> <6d265f36-352c-4866-bf91-c14d26101fc2@k37g2000hsf.googlegroups.com> <ku03e4pddv9fbshgkbpbfv2hrg3u1p1i6h@4ax.com> Message-ID: <6kdt7rF7dmkkU1@mid.uni-berlin.de> On Tue, 30 Sep 2008 03:56:03 +0200, Ivan Reborin wrote: > a = 2.000001 > b = 123456.789 > c = 1234.0001 > d = 98765.4321 > # same as above except for d > > print (3 * '%12.3f') % (a, b, c) > #this works beautifully > > How to add d at the end but with a different format now, since I've > "used" the "format part" ? > > Again, my weird wishful-thinking code: print (3*'%12.3f', '%5.3f') > %(a,b,c),d Maybe you should stop that wishful thinking and programming by accident and start actually thinking about what the code does, then it's easy to construct something working yourself. The ``%`` operator on strings expects a string on the left with format strings in it and a tuple with objects to replace the format strings with. So you want '%12.3f%12.3f%12.3f%5.3f' % (a, b, c, d) But without repeating the '%12.3f' literally. So you must construct that string dynamically by repeating the '%12.3f' and adding the '%5.3f': In [27]: 3 * '%12.3f' Out[27]: '%12.3f%12.3f%12.3f' In [28]: 3 * '%12.3f' + '%5.3f' Out[28]: '%12.3f%12.3f%12.3f%5.3f' Now you can use the ``%`` operator on that string: In [29]: (3 * '%12.3f' + '%5.3f') % (a, b, c, d) Out[29]: ' 2.000 123456.789 1234.00098765.432' (I guess there should be at least a space before the last format string.) This time you *have* to put parenthesis around the construction of the format string BTW because ``%`` has a higher priority than ``+``. So implicit parentheses look like this: 3 * '%12.3f' + '%5.3f' % (a, b, c, d) <=> 3 * '%12.3f' + ('%5.3f' % (a, b, c, d)) And there are of course not enough formatting place holders for four objects in '%5.3f'. It's also important to learn why your wrong codes fail. In your wishful thinking example you will get a `TypeError` saying "unsupported operand type(s) for %: 'tuple' and 'tuple'". That's because on the left side of the ``%`` operator you wrote a tuple: In [34]: (3 * '%12.3f', '%5.3f') Out[34]: ('%12.3f%12.3f%12.3f', '%5.3f') Ciao, Marc 'BlackJack' Rintsch From gminick at bzt.bzt Thu Sep 11 08:43:20 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Thu, 11 Sep 2008 12:43:20 +0000 (UTC) Subject: how dump a program which is running in memory References: <0592abb3-c2f6-4977-8338-3aa1956a353c@b38g2000prf.googlegroups.com> Message-ID: <gab3p7$snu$1@inews.gazeta.pl> On Thu, 11 Sep 2008 02:31:23 -0700 (PDT), ruqiang826 wrote: > I have written a service running backgroud to do something in linux. > unfortunately$B!$(BI deleted the source code by mistake, and I can still > see the process running background using "ps aux" : > > username 13820 0.0 0.0 60368 2964 ? S Aug20 0:33 > python ./UpdateJobStatus.py > > > I wonder if there is some way to dump the programme > "UpdateJobStatus.py" and get the source code back? The best way to do it would be to undelete the file, just as Gerhard suggested. If you remember any line (or piece) of code from the UpdateJobStatus.py file you can try to dump the /dev/mem to the hard disk, and then grep through it (remember that you need root priviledges to access /dev/mem). I tried it with this code: http://www.mail-archive.com/linuxbios at listman.lanl.gov/msg03696.html with a small modification of this line: nvram = (strtol(argv[1], 0, 0)) << 16; changed to: nvram = (strtol(argv[1], 0, 0)); After compilation I just did: ./a.out 0x0 0xffffffff > memdump to get the memory dump. I am not a memory expert, but 0xffffffff should be enough for <= 4GB of RAM. If you got more, increase it. And to make it clear: I do not recommend this way of sorting things out :) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From bedouglas at earthlink.net Mon Sep 1 23:36:59 2008 From: bedouglas at earthlink.net (bruce) Date: Mon, 1 Sep 2008 20:36:59 -0700 Subject: python mechanize/libxml2dom question Message-ID: <108c01c90cad$28dd5840$0301a8c0@tmesa.com> hi... i've got the following situation, with the following test url: "http://schedule.psu.edu/soc/fall/Alloz/a-c/acctg.html#". i can generate a list of the tables i want for the courses on the page. however, when i try to create the xpath query, and plug it into the xpath within python, i'm missing something. if i have a parent xpath query, that generates a list of results/nodes... how can i then use the individual parent node, and trigger off of it, to get further information. i tried using the following chunk of code with no luck. #s is the html from the course file d = libxml2dom.parseString(s, html=1) #at this point, we should have a vaild "d" representation print "sdddd=",s aa=libxml2dom.toString(d) print "hereeeeee \n\n\n" print "aa",aa #sys.exit() # **** course names cpath='//table[position()>0]/descendant::td[position()=2][@width="85%"]/../t d[1]/font/a[2]/text()' cpath_=[] cpath_=d.xpath(cpath) print "len=",len(cpath_) if len(cpath_)>0: for cpath in cpath_: #get the coursename info cname=cpath.toString() print "cpath=",cpath print "cname=",cname rr="./../../../../../../following-sibling::table//tr[position()>1]" rr=cpath.xpath() print "rrlen=",len(rr) print rr[0].toString() sys.exit() i'm assuming that there's a libxml2node method that will do what i need that i'm missing... pointers/comments would be helpful here... thanks! From tjreedy at udel.edu Sun Sep 28 15:17:19 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 15:17:19 -0400 Subject: What is not objects in Python? In-Reply-To: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <gbol7v$3ra$1@ger.gmane.org> process wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. Feel free to ignore it if you wish. > What is not an object in Python? Depends on what you mean by 'in'. Python is a language for defining and manipulating information objects. Code 'in' Python is not usually a maniputed object, though is can be (by eval, exec, and compile, for instance). Names in code that are only used to directly access objects typically are also, typically, not objects themselves. > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? Partly history and partly practicality. Len is implemented as .__len__ ;-). The len function is one, __len__ methods are many. If you want to pass an argument to a function, passing len is easier that passing operator.attrgetter('__len__'). Passing '__len__' (or 'len') would be easy, but using len is easier than using getattr(ob,'__len__'). tjr From gherlylukita at gmail.com Wed Sep 24 15:47:51 2008 From: gherlylukita at gmail.com (gherlylu) Date: Wed, 24 Sep 2008 12:47:51 -0700 (PDT) Subject: online pharmacy perscription.dt8v1 Message-ID: <ecf4b19b-2d74-46dc-b673-abe35f349c36@m45g2000hsb.googlegroups.com> Start saving, best online pharmacy here http://defgjkmahl.nufehrurald.net/?bciahlxwvrsydefgjkzchcmm From bearophileHUGS at lycos.com Thu Sep 18 13:04:37 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 18 Sep 2008 10:04:37 -0700 (PDT) Subject: Cython dynamic library problem References: <mailman.1216.1221749258.3487.python-list@python.org> <8763otl8ea.fsf@merkury.smsnet.pl> Message-ID: <f1b25309-9064-484d-9e29-bbdd3c8e2b68@8g2000hse.googlegroups.com> Rob Wolfe: > # setup.py > from distutils.core import setup > from distutils.extension import Extension > from Cython.Distutils import build_ext as build_pyx > > setup(name = 'pyx_test', > ext_modules=[Extension('pyx_test', ['test_cython.pyx'])], > cmdclass = { 'build_ext': build_pyx }) > > $ python2.5 setup.py build_ext -i > running build_ext > cythoning test_cython.pyx to test_cython.c > building 'pyx_test' extension > creating build/temp.linux-i686-2.5 > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.5 -c test_cython.c -o build/temp.linux-i686-2.5/test_cython.o > test_cython.c:86: warning: function declaration isn?t a prototype > test_cython.c:241: warning: function declaration isn?t a prototype > test_cython.c:59: warning: ?__pyx_skip_dispatch? defined but not used > gcc -pthread -shared -Wl,-O1 build/temp.linux-i686-2.5/test_cython.o -o pyx_test.so > $ python2.5 test_cython.py > 0 > 100 With some intelligence added to Cython, probably there are ways to reduce all this, and most of the times avoid any setup.py module too. Bye, bearophile From almar.klein at gmail.com Thu Sep 25 10:53:17 2008 From: almar.klein at gmail.com (Almar Klein) Date: Thu, 25 Sep 2008 16:53:17 +0200 Subject: matplotlib in interactive mode locks when run from subprocess In-Reply-To: <cc38d75f0809201312u6bfc5f0awfd18b307aa421ce@mail.gmail.com> References: <cc38d75f0809180713r5ae45167xc0c52c5557e63381@mail.gmail.com> <cc38d75f0809201312u6bfc5f0awfd18b307aa421ce@mail.gmail.com> Message-ID: <cc38d75f0809250753w7588cb96p424c1af487b632c5@mail.gmail.com> To who cares, I found out what my problem was. Testing interactivity with Tk in a normal Python console gave proper results, just like IPython. Also running "python -i" gives the interactive behaviour I wanted. But running "python -i" from a subprocess did not. I was startled, because it worked out of the box with Python! I read somewhere that Tkinter does not need a mainloop, which should be true in order to have the interactive behaviour in python without a second thread. Well, tk does indeed not need a mainloop, but you DO need to create a tk app and call update() on it from time to time. (Which makes sense now that I know it :) ) After examing code from IPython, I saw that it runs code to start a Tk app, and performs tk.update(). So I guess this means that the standard python shell creates such a "hidden tk app", but NOT when run from a subprocess. I have now solved my problem, and interactivity works! Almar 2008/9/20 Almar Klein <almar.klein at gmail.com> > I think my question was not very clear. I narrowed the problem down to > a reconstructable small example, consisting of a python script (a very > simple interpreter) and three lines to execute in it: > > ========== start simple interpreter file ====== > import os > import sys > import time > > def run(): > while True: > > # read a line of text, the thread is stuck here untill a \n is > # fed to the stream. > time.sleep(0.1) > line = "" > try: > line = sys.stdin.readline() > except Exception, why: > sys.stdout.wite(why.message+"\n") > > if line: > try: > code = compile(line,"<none>","exec") > exec(code) > except Exception, why: > sys.stderr.write(why.message) > sys.stderr.write(">>> ") > > if __name__ == "__main__": > run() > > ========== end of file ============== > > Now I run this file (by double clicking it) and I get a prompt. The three > lines I type in are: > import matplotlib.pylab as pl > pl.ion() #interactive mode on > pl.plot([1,2,3],[4,6,5]) > > This produces a tk window, but it's unresponsive. The process does have 5 > threads, so > matplotlib managed to create the threads, but it seems as if they're > blocked. > > When I run the three lines of code in a normal python shell, I get the > proper results: > a responsive figure (I can zoom and pan) and my shell is still responsive > too. > > I am in the dark why this does not work. Any thoughts anyone? I've been > busy all day > trying to get this right, with hardly any progress... :( > > Almar > > PS: I run windows xp, my matplotlibrc file has the backend: TkAgg, > interactive: True > > > 2008/9/18 Almar Klein <almar.klein at gmail.com> > > Hi, >> >> In wxpython, I made an interactive shell, which creates a remote python >> subprocess >> to do the interpreting. Communication is done via a pipe. The idea is that >> the python >> session is an actual process separate from the GUI, which has some >> advantages, >> like I can have multiple such shells in my application, and I can kill >> them without >> worrying that my wx app will crash. >> >> To do this I use the wx.Process class, which allows asynchronous >> communication with >> the remote process. >> >> This all works really, I will also launch wxpython apps. So I was quite >> happy, untill I tried >> doing some plotting with matplotlib (in TkAgg backend). The problem is >> that the process >> becomes unresponsive when I plot something (No prompt is written to the >> stdout/stderr). >> (more details below) >> >> I don't know much about creating subprocess and how they are different >> from a normal >> process. So can anyone offer some help as to what the problem might be? >> >> Thanks in advance, >> Almar >> >> To get to the details: >> - When I start a process with command "python -u -i" >> -- When interactive mode is off, the whole process becomes unresponsive >> when doing >> pylab.show() >> -- When interactive mode in on, on doing pylab.plot(), a figure appears, >> which I can >> zoom etc., but the process is now stuck, also after closing the figure >> >> - When I start a process with command >> "python -u -c 'import code;code.interact(readfunc=raw_input)'" (This is >> how Pype does it). >> -- When interactive mode is off, the figures show when doing >> pylab.show() and the process >> behaves as normal after closing the figure(s). >> -- When interactive mode in on, on doing pylab.plot(), a figure appears, >> but most of the time >> it is not drawn and emmediately unresponsive, just like the process >> itself. >> >> I have also tried an asynchronous Popen recipe by Joshiah Carlson I found >> on >> activestate. And I made my own process class using >> win32process.CreateProcess. >> Both alternatives to wx.Process resulted in the same sympoms. >> >> Oh, and I run windows. >> >> > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080925/59796bde/attachment-0001.html> From siona at chiark.greenend.org.uk Mon Sep 22 07:32:04 2008 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 22 Sep 2008 12:32:04 +0100 (BST) Subject: Question about sorted in Python 3.0rc1 References: <9088d3df-941e-4838-a3cc-d03448beb5eb@i76g2000hsf.googlegroups.com> Message-ID: <ugv*ncEns@news.chiark.greenend.org.uk> josh logan <dear.jay.logan at gmail.com> wrote: >sorted(P) # throws TypeError: unorderable types Player() < Player() > >The sorted function works when I define __lt__. >I must be misreading the documentation, because I read for the >documentation __cmp__ that it is called if none of the other rich >comparison functions are defined. You're either misreading or forgetting that __eq__ and __ne__, which you define, are rich comparison functions. __cmp__ will only be called for a comparison when *none* of the rich comparison functions are defined, not just the one in question. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From tjreedy at udel.edu Tue Sep 2 22:37:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 02 Sep 2008 22:37:25 -0400 Subject: Inquiry regarding the name of subprocess.Popen class In-Reply-To: <20080902235412.GT29228@dragontoe.org> References: <2008090103233816807-jeremy@jeremybanksca> <eeaa4abf-652f-42f2-9301-c56d2b8d7da0@79g2000hsk.googlegroups.com> <6i4pq5Fol29aU1@mid.uni-berlin.de> <mailman.366.1220362139.3487.python-list@python.org> <6i4v26Fol29aU4@mid.uni-berlin.de> <20080902153909.GQ29228@dragontoe.org> <op.ugvewdcqx6zn5v@a98gizw.cpe.telecentro.net.ar> <mailman.390.1220393719.3487.python-list@python.org> <6i5ujqFol29aU8@mid.uni-berlin.de> <20080902235412.GT29228@dragontoe.org> Message-ID: <g9kt94$12p$1@ger.gmane.org> Derek Martin wrote: > On Tue, Sep 02, 2008 at 10:55:54PM +0000, Marc 'BlackJack' Rintsch wrote: > >> It's a way more self explaining name, even for people who know the >> `popen()` function > > I, and apparently the maintainers (at least at the time they added > this thing) don't agree. In fact I think it's quite the opposite. If > I came across such a "process" object without knowing what it was, I > would expect that a process object described a running process, i.e. > gave information about things like executable path name, cpu and > memory utilization, perhaps a list of all open file descriptors (but > not just three specific ones), etc; or something similar. This object > provides none of that. It does not, in fact, describe a process at > all. It is quite distinct and different from the concept of a > process, indeed. > >> because there's a concept called "process" but none called "popen". > > Anything that exists can be conceptualized and therefore is a concept. > The popen concept exists, and is more than just a concept; it has a > concrete implementation in C AND Python and numerous other languages. > Verbs can be concepts too. In this case, at least, I think of the module name as part of the total class name. subprocess.Popen == open pipes to a subprocess -- and return a structure that lets me use the pipes and monitor the process. So as a practical matter, I am okay with the name even if I theoretically agree with the guideline as a guideline. tjr From lists at cheimes.de Wed Sep 10 20:53:01 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 11 Sep 2008 02:53:01 +0200 Subject: Working with environment variables. In-Reply-To: <73045cca0809101739m560d382bi8ba506022f600286@mail.gmail.com> References: <73045cca0809101739m560d382bi8ba506022f600286@mail.gmail.com> Message-ID: <ga9q5b$8on$1@ger.gmane.org> aditya shukla wrote: > now this dosen't change the value of the variable which was set earlier > .Please help me in fixing this issue. Are you trying to modify or add an environment var so the change is visible from the calling shell? That's not possible. You can't change the env var of a parent process. Christian From uzmanajmal at gmail.com Fri Sep 12 14:39:00 2008 From: uzmanajmal at gmail.com (Usman Ajmal) Date: Fri, 12 Sep 2008 23:39:00 +0500 Subject: Need help with the 'transport' for setting the header while calling a function at server side Message-ID: <a3158e8b0809121139v3d7137e1r908f8414fbb25b10@mail.gmail.com> I am getting an Internal Server Error 500 when i run my client code. I am trying to call a function at the server side which for now only returns a string. Meanwhile this calling i also set the header of HTTP request. Following are my client and server code. Am i doing something wrong? #-----------------------Server code----------------------------- import SimpleXMLRPCServer class AuthenticationFunctions: def system_auth(self): # No need to print here if you are going to print it at the client side. Return it instead. return "something..." server = SimpleXMLRPCServer.SimpleXMLRPCServer(("localhost", 8000)) server.register_instance(AuthenticationFunctions()) server.serve_forever() #-----------------------Client code----------------------------- import sha,random, os, time, sha, quopri, xmlrpclib class SecureTransport(xmlrpclib.Transport): def set_authorization(self, ustring, text_ucert): self.authorization = quopri.encodestring("%s:%s" % (ustring,text_ucert)) def send_request(self, connection, handler, request_body): connection.putrequest("POST", handler) connection.putheader("Authorization","Basic %s" % self.authorization) def caller(): #Opening file named newcert.pem in which certificate generated via openssl command is placed infile = open('newcert.pem', "r+") if infile: text_ucert = infile.read() infile.close() #Generating a random string random.seed(); ustring_raw="%s_%f_%f"%(os.getpid(),time.time(),random.random()) #For calculating the hash of some arbitrary message hashValue = sha.new() hashValue.update("(.2).ch^kjdw*()!hjsu7 at hsue @!jssljdu2837.kd'lsid4vhwoi3821@#1azzZ3234202J83&") #Updating the hash with the previously generated random string hashValue.update(ustring_raw) ustring = quopri.encodestring(hashValue.digest()) #Instantiating the transport t = SecureTransport() t.set_authorization(ustring, text_ucert) server = xmlrpclib.Server('http://localhost:8000',transport=t) #Calling some arbitrary function at server side print server.system_auth() caller() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080912/469a2dd6/attachment-0001.html> From dmitry at athabascau.ca Thu Sep 25 17:30:19 2008 From: dmitry at athabascau.ca (Dmitry S. Makovey) Date: Thu, 25 Sep 2008 21:30:19 GMT Subject: Eggs, VirtualEnv, and Apt - best practices? References: <mailman.1506.1222370612.3487.python-list@python.org> <QQRCk.1802$Pv5.235@edtnps83> <6k2aqqF5p185U1@mid.uni-berlin.de> <qNSCk.1824$Pv5.181@edtnps83> <6k2c5pF5oenoU1@mid.uni-berlin.de> Message-ID: <LpTCk.1833$Pv5.1470@edtnps83> Diez B. Roggisch wrote: > Well, you certainly want a desktop-orientied Linux for users, so you > chose ubuntu - but then on the server you go with a more stable debian > system. Even though the both have the same technical and even package > management-base, they are still incompatible wrt to package versions for > python. > > And other constraints such as Photoshop not being available for Linux > can complicate things further. actually I had in mind X11 sessions forwarded from server to desktop - all development tools and libraries are on server, and all unrelated packages (like Photoshop etc.) are on desktop. >> that definitely becomes tricky however not impossible to track. You do >> need a common snapshot for all developers to use anyway - so why not just >> package it up? > > I do, but based on Python eggs. They are platform independent (at > ultimo, you can use the source distribution, albeit that sux for windows > most of the time), and as I explained in my other post - things are > moving in the right direction. /I'll play devil's advocate here even though I see your point/ how do you deal with non-pythonic dependencies then? surely you don't package ImageMagic into an egg ;) > Don't get me wrong - I love .deb-based systems. But if using them for my > development means that I have to essentially create a full zoo of > various packages *nobody else* uses - I rather stick with what's working > for me. Looks like if you package and make those available you'll have quite a few people using them. I've seen people looking for pre-packaged python libs just to stick to OS package management tools. :) Eggs and debs are not silver-bullet for *any* scenario, so you'd have to weight what can you get out of either one against what are you going to sacrifice. In my case I know all our systems (servers) run same OS, however developers don't. So I provide them with environment on devel/testing servers that they can use as a primary development environment or develop on their own boxes (which means they are on their own hunting dependencies/packages/etc.) but testing before moving forward they still have to test it on "certified" server. And I don't suggest that everybody should run *this* type of environment - it just works better in our case. From tjreedy at udel.edu Mon Sep 22 14:36:03 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 Sep 2008 14:36:03 -0400 Subject: What do you call a class not intended to be instantiated In-Reply-To: <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> References: <00e6c71d$0$20303$c3e8da3@news.astraweb.com> <48d7534f$0$5096$426a74cc@news.free.fr> <pan.2008.09.22.09.32.39@REMOVE.THIS.cybersource.com.au> Message-ID: <gb8oi9$1iu$1@ger.gmane.org> Steven D'Aprano wrote: > > Consider a factory function: > > def factory(x): # a toy example > alist = [x] > def foo(): > return alist > return foo > > > Now suppose we "instantiate" the factory (for lack of a better term): > >>>> f1 = factory(0) >>>> f2 = factory(0) Your factory is returning closures. This is the functional equivalent of a class returning instances. class factory(object): def __init__(self, x): self.alist = [x] def __call__(self): return self.alist > Even though f1 and f2 have the same behaviour, they are obviously not the > same object. And although both return a list [0], it is not the same list: > >>>> f1() == f2() == [0] > True >>>> f1() is f2() > False same results > They have a (very little) amount of state, which is *not* shared: > >>>> L = f1() >>>> L.append(1) >>>> f1() > [0, 1] >>>> f2() > [0] same results > But there's only a limited amount of state that functions carry around. That is why Python has class statements. > And instances share at least some state, by virtue of having the same class. If the only class attributes are methods and you do mutate the class, then the fact that f1.__class__ is f2.__class__ is not really shared state. [from a later post] >But that's precisely what I want to avoid: I don't want the objects to share *any* state, not even their class. Unless you can show how sharing an immutable __class__ attribute is an actual impediment, this strike me as artificial pedantry and unnecessary self handcuffing. And you obviously can make that attribute effectively immutable by ignoring it and also not changing the class itself. It is just internal, implementation-defined bookkeeping. The identity of immutable objects is irrelevant. If part of your 'unshared state' for each instance were a string, and two instances happened to have the same string value, would you be upset because the interpreter happened to use the same string object instead of two string objects with the same value? Ditto for numbers, tuples, and so on. Terry Jan Reedy From ricaraoz at gmail.com Mon Sep 22 10:36:18 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 22 Sep 2008 11:36:18 -0300 Subject: Not fully OO ? In-Reply-To: <8d30318b-2c54-4d4e-b333-016a0806c1ad@y38g2000hsy.googlegroups.com> References: <48d4c11b$0$22877$426a74cc@news.free.fr> <48d541d8$0$32185$426a34cc@news.free.fr> <d2f627cb-c18f-4401-9797-6680f19db825@c58g2000hsc.googlegroups.com> <2c0a8279-e888-4ae5-90a2-f2f1bb137607@x41g2000hsb.googlegroups.com> <8d30318b-2c54-4d4e-b333-016a0806c1ad@y38g2000hsy.googlegroups.com> Message-ID: <48D7AD62.2090503@bigfoot.com> Kay Schluehr wrote: > On 20 Sep., 23:07, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> > wrote: >> On Sep 20, 3:22 pm, Kay Schluehr <kay.schlu... at gmx.net> wrote: >> >> >> >>> On 20 Sep., 18:33, Bruno Desthuilliers >>> <bdesth.quelquech... at free.quelquepart.fr> wrote: >>>> The following definitions are AFAIK the only commonly accepted >>>> definitions about OO: >>>> 1/ an object is defined by identity, state and behaviour >>>> 2/ objects interacts by sending messages each other >>>> 3/ an OO program is made of interacting objects >>>> I let you find out whether Python meets these 3 definitions - and if >>>> Java does (hint : in Python, everything you can bind to a name is an >>>> object - this is not true in Java or C++). >>> This is correct but it detracts from a more general problem of >>> language "paradigms". >>> Assume you type >>>>>> 2+2 >>> 4 >>> Now you are free to interpret this as a simple, primitive arithmetic >>> operation but you can also claim that 2 sends an __add__ message to 2. >>> Hereby the state of the 2 objects are not altered but a new 4 object >>> is created. OO babble is more impressive isn't it? >>> Actually it is simply wrong in the mentioned case and here is the >>> proof: >>> def foo(): >>> return 2+2 >>> import dis >>> dis.dis(foo) >>> 2 0 LOAD_CONST 2 (4) >>> 3 RETURN_VALUE >>> OO is a heuristic method used to understand the semantics of a >>> programming language. It can also inspire language design but as >>> you've rightly said: jugde yourself and see how far you get with it. >>> Applying OO on interpreter level is by no means a sign of a high >>> quality implementation whereas structuring programs in the large will >>> likely benefit from class based organization and encapsulation. Of >>> course one can also reverse the value hierarchy and find perverse joy >>> in having a pure OO language but apply monkey patching everywhere. I >>> suppose you know which language I'm talking about... >> It sounds like you think that you -can- write OO programs in Python, >> but you don't have to. I agree. > > The whole point of OO is providing high level ( system level ) not low > level ( interpreter level ) semantics. Partitioning a system into > isolated and communicating objects is a strong and important metaphor. > Recently there were some comments on the web that mentioned Erlang to > be pretty much OO in this respect although Erlang is functional and > has no base level notion of an "object". It's even well known that Joe > Armstrong holds low opinions about the entire object business. > > Notice that I believe that the popular meme that OO is "bolted on" > Python has little if nothing to do with OO itself but with API > consistency. When people have to type len(x) instead of x.len() this > breaks their expectations on how the language has to behave. x.__len__() From enleverlesX.XmcX at XmclaveauX.com Sat Sep 27 02:59:20 2008 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Sat, 27 Sep 2008 08:59:20 +0200 Subject: how to search multiple textfiles ? (Python is slow ?) In-Reply-To: <mailman.1566.1222464403.3487.python-list@python.org> References: <mailman.1536.1222436146.3487.python-list@python.org><17334ed4-d92c-4f48-abb9-4561823ae9a1@z6g2000pre.googlegroups.com> <mailman.1566.1222464403.3487.python-list@python.org> Message-ID: <48ddda41$0$920$ba4acef3@news.orange.fr> Hi ! Thanks for return. Some infos: from a long time, I found that it's often more fast to use windows's command, instead of develop in high level language (and also, low level...) FINDSTR is fast. OK. But internal commands are more fast. Example : DIR (with all his options) And it's faster to read the result via a Pipe. Thus, I use frequently this sort of function: import os def cmdone(repstart, commande, moderetour="LIST"): os.chdir(repstart) sret=''.join(os.popen(commande)) if moderetour.upper() == "STR": return sret else: return sret.split('\n') print cmdone('D:\\dev\\python','findstr /N /I ponx *.py','STR') print print cmdone('D:\\dev\\python','dir *.jpg /B') Sorry for my bad english, and have a good day... -- Michel Claveau From giltay at gmail.com Tue Sep 30 13:40:10 2008 From: giltay at gmail.com (giltay at gmail.com) Date: Tue, 30 Sep 2008 10:40:10 -0700 (PDT) Subject: OS.SYSTEM ERROR !!! References: <mailman.1759.1222795317.3487.python-list@python.org> Message-ID: <402462d4-e2a6-493b-9bc9-52aab68cad96@y71g2000hsa.googlegroups.com> On Sep 30, 1:21?pm, "Blubaugh, David A." <dbluba... at belcan.com> wrote: > I would usually execute this program (with the appropriate arguments) by > going to following directory within MS-DOS (Windows XP): > > C:\myprogramfolder\run> Myprogram.exe 1 1 acc 0 [snip] > import os > > os.system(r"C:\myprogramfolder\run\Myprogram.exe 1 1 acc 0") [snip] > ERROR opening inputs/io/control.dat [snip] I would add the following line right before your call to os.system: os.chdir(r'C:\myprogramfolder\run') If you have to change directories to run it properly in the Windows shell, then you need to do it in Python, too. HTH, Geoff G-T From deets at nospam.web.de Mon Sep 15 17:59:12 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 Sep 2008 23:59:12 +0200 Subject: conditional install/distribution In-Reply-To: <3f8893c3-fd23-4734-a2d4-07921be67202@z11g2000prl.googlegroups.com> References: <6763addc-e539-4c00-b94c-fa628d5ca83f@y21g2000hsf.googlegroups.com> <6it533Fe2h8U1@mid.uni-berlin.de> <3f8893c3-fd23-4734-a2d4-07921be67202@z11g2000prl.googlegroups.com> Message-ID: <6j845gF1tnd6U1@mid.uni-berlin.de> i3dmaster schrieb: > On Sep 11, 11:07 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote: >> i3dmasterschrieb: >> >>> Is there a feature in distutils or easy_install to specify what >>> version of python that the target package can be installed? For >>> example, if a package has a module that only needed if the python >>> version < 2.6, is there a way to specifiy that in setup.py or >>> easy_install cfg file so that when installing to python >= 2.6, this >>> module wouldn't be installed?? >> you can simply import sys and check sys.version in the setup-script, and >> abort with an error-message if the expectations aren't matched. >> >> Diez > I know I can precheck the version, but the real issue is how I can > prevent from installing a specific module? Actually, the rest of the > package should still be installed but just not a particular module > because the feature is built in after 2.6. How about simply not importing the module in question if the version is not proper? Or even a try: import a_module_requiring_2_6 except (SyntaxError, ImportError): pass Diez From tjreedy at udel.edu Mon Sep 15 14:29:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 Sep 2008 14:29:13 -0400 Subject: Converting between binary, decimal, hexadecimal, octal In-Reply-To: <ea09b3700809150154y65b90b4cuffbbec9485cab637@mail.gmail.com> References: <ea09b3700809150154y65b90b4cuffbbec9485cab637@mail.gmail.com> Message-ID: <gam9hk$ugr$1@ger.gmane.org> A. Joseph wrote: > Converting between binary, decimal, hexadecimal, octal > Where can I find good tutorial on numbering system? These are number representation systems that can be applied to or used with integral, rational (numberator,denominator), and 'point' numbers. Try Wikipedia or any search engine. > I really want to know the process of converting between all the numbers. > I may soon start HLA (assemply). There are standard algorithms for converting between representations. See above. Good programmer calculators have these built in. If you want to use the Python interactive interpreter, check the docs for the various integer literals and the hex, oct, and bin functions. Binary literals and bin are only available in 2.6 (I believe) and 3.0 (for sure). tjr From h.goebel at goebel-consult.de Tue Sep 16 13:32:14 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Tue, 16 Sep 2008 19:32:14 +0200 Subject: Python and Open Office In-Reply-To: <056cba0b-6c6e-4066-951c-3e97266d93d4@r15g2000prd.googlegroups.com> References: <a9f39a410809101304j592cb7actc1f95882f8fe632c@mail.gmail.com> <mailman.826.1221077307.3487.python-list@python.org> <ga9cps$mnt$1@theodyn.ncf.ca> <056cba0b-6c6e-4066-951c-3e97266d93d4@r15g2000prd.googlegroups.com> Message-ID: <48cfed9e$0$6660$9b4e6d93@newsspool2.arcor-online.net> Peter Georgeson schrieb: > I can confirm that unfortunately, the PyUNO interface presently > (OpenOffice 2.4) is built with Python 2.3... so to use the UNO > interface from Python you have to write a separate script to run in > the OpenOffice Python 2.3 environment. This may be true for Windows. On Linux - at least for Mandriva --, OOo is already integrated with Python 2.5. -- Sch?nen Gru? - Regards Hartmut Goebel Dipl.-Informatiker (univ.), CISSP Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From fredrik at pythonware.com Sat Sep 13 08:37:47 2008 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 13 Sep 2008 14:37:47 +0200 Subject: XML RPC Problem.... In-Reply-To: <a3158e8b0809130523g579ac36ci88caee7ac279f64d@mail.gmail.com> References: <a3158e8b0809110008t6e1b82f1w3fb2c6b09588896c@mail.gmail.com> <gaagp1$804$1@ger.gmane.org> <a3158e8b0809130032o3807f431y9caec7793f411039@mail.gmail.com> <gafuhg$sh1$1@ger.gmane.org> <a3158e8b0809130306m25dda070w73f0a3c25888e051@mail.gmail.com> <gag6dj$fd5$1@ger.gmane.org> <a3158e8b0809130523g579ac36ci88caee7ac279f64d@mail.gmail.com> Message-ID: <gagc6u$tj6$1@ger.gmane.org> Usman Ajmal wrote: > Problem is that when i start client (while the server is already > running), i get an error i.e. > Error 500 Internal Server Error that's a server error, not a client error. check the server logs (e.g. error.log or similar). </F> From steve at REMOVE-THIS-cybersource.com.au Wed Sep 24 22:15:46 2008 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Sep 2008 02:15:46 GMT Subject: Python style: exceptions vs. sys.exit() References: <369e4003-f9c1-44ea-9ad1-cddaa6b5e152@w39g2000prb.googlegroups.com> <4rWdndQrldhd_0fVnZ2dnUVZ_jCdnZ2d@posted.visi> <gbe0kd$qh9$1@rumours.uwaterloo.ca> <48da956c$0$1269$426a74cc@news.free.fr> <gbeae1$uin$1@rumours.uwaterloo.ca> Message-ID: <00eaee25$0$20666$c3e8da3@news.astraweb.com> On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote: > Plenty of people were quick to say that the exception should be passed > through to the caller. No one said this behaviour should be documented. > There may be little practical difference bewteen calling sys.exit() > after printing an error and progating an exception if no one using the > library knows that it could generate that exception in those > circumstances. That's true, I didn't explicitly say that the library should be documented. Nor did I say that it shouldn't be riddled with bugs. There's little practical difference between a buggy library and one that raises unexpected (i.e. undocumented) exceptions either. -- Steven From williamhpurcell at gmail.com Tue Sep 30 17:04:34 2008 From: williamhpurcell at gmail.com (William Purcell) Date: Tue, 30 Sep 2008 16:04:34 -0500 Subject: why? __builtins__ key added from eval Message-ID: <d9186c3b0809301404k5ea2c84cj13189061d60c8899@mail.gmail.com> I want to use eval to evaluate wx.TextCtrl inputs. How can I keep python from adding the __builtins__ key to mydict when I use it with eval? Other wise I have to __delitem__('__builtins__') everytime I use eval? >>> mydict = {'a':2,'b':3} >>> eval('a*b',mydict) 6 >>> mydict {'a': 2, '__builtins__': {'IndexError': <type 'exceptions.IndexError'>, ...(I'll spare you the rest)...}, 'b': 3} Also, how come eval has this behavior? Is it desirable? -Bill -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20080930/ae55e128/attachment-0001.html> From castironpi at gmail.com Mon Sep 15 14:59:54 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Mon, 15 Sep 2008 11:59:54 -0700 (PDT) Subject: how to go around non-picklable object types? References: <91xzk.28830$rD2.16046@bignews4.bellsouth.net> Message-ID: <e6b79944-35f7-4ef9-ad14-7493fec341d4@d77g2000hsb.googlegroups.com> On Sep 15, 12:36?pm, "inhahe" <inh... at gmail.com> wrote: > There are certain types of objects that can't be pickled, like file objects. > My question is how could I pickle a hierarchy while automatically skipping > all such objects instead of just aborting the pickle when it comes across > one. > > The only thing I can think of is to make my own classes that wrap file > objects and so forth and use __getstate__ to leave out the underlying file, > etc. objects, or to set __getstate__ for every class that holds an offending > object type and filter such objects out of dictionaries when I pickle those. > And I don't even have a list of common object types that would make it > break. > > Is there a better way? ?thx.. inhahe, Nice to hear from you again. This is one possibility. import pickle class TolerantPickler( pickle.Pickler ): def save(self, obj): try: pickle.Pickler.save( self, obj ) except TypeError: pickle.Pickler.save( self, None ) Then every time the native Pickler object tries to call 'save' it gets your protected call instead. If the call fails with TypeError, just pickle None. Here are 'dumps' and a test. from StringIO import StringIO def dumps(obj, protocol=None): file = StringIO() TolerantPickler(file, protocol).dump(obj) return file.getvalue() class A: pass a= A() a.a= open( 'temp.dat' ) a.b= 32 b= dumps( a ) c= pickle.loads( b ) print c print c.a, c.b /Output: <__main__.A instance at 0x00A7D1E8> None 32 It may accomplish some of what you want. If it works, a pat on the back to the writer of the Pickler class for using encapsulation. From bearophileHUGS at lycos.com Fri Sep 5 17:49:21 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 5 Sep 2008 14:49:21 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> <45c11b84-bbf9-4048-9743-c69c67f421bf@y21g2000hsf.googlegroups.com> <a34c6ffd-0353-43c9-8b22-36d0fc66ed22@v16g2000prc.googlegroups.com> Message-ID: <d9a713e1-3305-4d9c-8cac-02dc1c57aa86@m3g2000hsc.googlegroups.com> John Machin: > Consider this:>>> hash(123) == hash(123.0) == hash(123L) > True Right... Can you explain me why Python designers have chosen to build a hash() like that? > Try "uses all the information that is relevant to the task". My knowledge of hash data structures seems not enough to understand why. > Your alternative solution using reduce and xor may have suboptimal > characteristics ... Right, sorry. Bye, bearophile From grflanagan at gmail.com Thu Sep 18 15:09:59 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 18 Sep 2008 21:09:59 +0200 Subject: dict generator question In-Reply-To: <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> References: <23d7e1bb0809180754r2b0bd944qb5e6accea87f2a99@mail.gmail.com> <mailman.1220.1221752633.3487.python-list@python.org> <9a875773-3c2e-406c-80e9-383820cfbecf@8g2000hse.googlegroups.com> Message-ID: <gau926$f20$1@ger.gmane.org> George Sakkis wrote: > On Sep 18, 11:43 am, Gerard flanagan <grflana... at gmail.com> wrote: >> Simon Mullis wrote: >>> Hi, >>> Let's say I have an arbitrary list of minor software versions of an >>> imaginary software product: >>> l = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] >>> I'd like to create a dict with major_version : count. >>> (So, in this case: >>> dict_of_counts = { "1.1" : "1", >>> "1.2" : "2", >>> "1.3" : "2" } >> [...] >> data = [ "1.1.1.1", "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.3.4.5"] >> >> from itertools import groupby >> >> datadict = \ >> dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) >> print datadict > > Note that this works correctly only if the versions are already sorted > by major version. > Yes, I should have mentioned it. Here's a fuller example below. There's maybe better ways of sorting version numbers, but this is what I do. data = [ "1.2.2.2", "1.2.2.3", "1.3.1.2", "1.1.1.1", "1.3.14.5", "1.3.21.6" ] from itertools import groupby import re RXBUILDSORT = re.compile(r'\d+|[a-zA-Z]') def versionsort(s): key = [] for part in RXBUILDSORT.findall(s.lower()): try: key.append(int(part)) except ValueError: key.append(ord(part)) return tuple(key) data.sort(key=versionsort) print data datadict = \ dict((k, len(list(g))) for k,g in groupby(data, lambda s: s[:3])) print datadict From eric.e.janke at gmail.com Tue Sep 23 10:50:30 2008 From: eric.e.janke at gmail.com (Eric E) Date: Tue, 23 Sep 2008 07:50:30 -0700 (PDT) Subject: Attachment Size and SMTP EMail Message-ID: <a2747a10-ecd6-4254-922e-59e8a2784c3b@m3g2000hsc.googlegroups.com> Hello All - I am using python to send an email with a large zip file as an attachment. I successfully sent a 52M attachment. If I try to send a 63M attachment or larger, the message never gets through. I do not get any errors in my python code. I pasted my python code below. from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email import Encoders import smtplib,os mssg = MIMEMultipart() part = MIMEBase('application',"octet-stream") part.set_payload(open(zipFileName,"rb").read()) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(zipFileName)) mssg.attach(part) s = smtplib.SMTP('localhost') s.set_debuglevel(1) s.sendmail(fromAddr,toAddr,mssg.as_string()) s.quit() I am using a Fedora Core 6 system with python 2.4.4. Any suggestions on what could be limiting the attachment size or how I could troubleshoot this? Thanks! EricE From washakie at gmail.com Fri Sep 19 16:37:58 2008 From: washakie at gmail.com (John [H2O]) Date: Fri, 19 Sep 2008 13:37:58 -0700 (PDT) Subject: appending * to glob returns files with '*' !! Message-ID: <19579121.post@talk.nabble.com> I have a glob.glob search: searchstring = os.path.join('path'+'EN*') files = glob.glob(searchstring) for f in files: print f ___ This returns some files: EN082333 EN092334 EN* My routine cannot handle the '*' and it should'nt be returned anyway? :-/ A bug? -- View this message in context: http://www.nabble.com/appending-*-to-glob-returns-files-with-%27*%27-%21%21-tp19579121p19579121.html Sent from the Python - python-list mailing list archive at Nabble.com. From gagsl-py2 at yahoo.com.ar Sun Sep 21 13:56:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 21 Sep 2008 14:56:01 -0300 Subject: report a BUG of package setuptools-0.6c8. References: <d2d5d61d0809192114p7b2a20b1tca588b5ed73acc26@mail.gmail.com> <mailman.1291.1221898300.3487.python-list@python.org> <68d3023b-cc57-4db0-b2cd-309fdeb9c91e@p25g2000hsf.googlegroups.com> <5e1183fa0809210246q46f864eic359964a0cb0d46e@mail.gmail.com> Message-ID: <op.uhudtowzx6zn5v@a98gizw.noga> En Sun, 21 Sep 2008 06:46:54 -0300, Sebastien Douche <sdouche at gmail.com> escribi?: > 2008/9/20 Carl Banks <pavlovevidence at gmail.com>: >> On Sep 20, 1:11 am, Fredrik Lundh <fred... at pythonware.com> wrote: >>> ???? wrote: >>> > File >>> "/usr/lib/python2.5/site-packages/setuptools/command/sdist.py", >>> > line 98, in entries_finder >>> > log.warn("unrecognized .svn/entries format in %s", dirname) >>> > NameError: global name 'log' is not defined >>> >>> > global name 'log' is not defined to the line 98!!! >>> >>> please report bugs here: >>> >>> http://bugs.python.org/ >> >> Does bugs.python.org track bugs for setuptools? (Genuine question; >> the PEAK site doesn't list an obvious way to report bugs so I wonder >> if they're using bugs.python.org? Hope not....) > > http://bugs.python.org/setuptools/ And how do people manage to know that? -- Gabriel Genellina From cournape at gmail.com Thu Sep 25 23:45:14 2008 From: cournape at gmail.com (David Cournapeau) Date: Fri, 26 Sep 2008 12:45:14 +0900 Subject: Python is slow? In-Reply-To: <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <gqrhd4h2ub6u4nifu3hj1rsfcs346jpvfn@4ax.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> Message-ID: <5b8d13220809252045v6365658ct462cd30f09407743@mail.gmail.com> On Wed, Sep 24, 2008 at 3:07 AM, sturlamolden <sturlamolden at yahoo.no> wrote: > On Sep 23, 3:44 pm, Robert Singer <rsinger at ____.com> wrote: > >> Well, python is not a number crunching language. However much we would >> like it to be (we would ? :-). > >> No scripting language is. > > Not even Matlab, R, IDL, Octave, SciLab, S-PLUS or Mathematica? I am fairly experienced in matlab (have been using it extensively for 5 years in academical context), and now with numpy, and generally, they are comparable speed-wise. Matlab has some niceties which makes it faster in some simple cases (JIT for loops, function calls faster, sometimes COW semantics means it faster), but numpy (at its core at least) is much more powerful IMHO. Also, matlab is horrible when you want to interface some C to it (the C api is basically broken; in particular, there is no way to gurantee you won't leak memory when you Ctrl+C custom C extensions because the C api does not have facility to deal with signals). I totally gave up matlab for numpy 2 years ago, and never regretted it. I think speed is not the issue when comparing matlab, R and co. Availability of functionalities matter much more. R is quite hard to beat if you need to do advanced statistics, specially since it is the tool of choice for most academic statisticians. I hope numpy/scipy will be there sometime, but it is honestly still quite far in that domain. cheers, David From gminick at bzt.bzt Wed Sep 10 12:14:53 2008 From: gminick at bzt.bzt (Wojtek Walczak) Date: Wed, 10 Sep 2008 16:14:53 +0000 (UTC) Subject: dict slice in python (translating perl to python) References: <c4db95bd-9835-4bb4-b27e-7c8c46504dff@k37g2000hsf.googlegroups.com> Message-ID: <ga8rps$70e$1@inews.gazeta.pl> On Wed, 10 Sep 2008 08:28:43 -0700 (PDT), hofer wrote: > Hi, > > Let's take following perl code snippet: > > %myhash=( one => 1 , two => 2 , three => 3 ); > ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest > print "$v1\n$v2\n$v2\n"; What about: >>> myhash={'one':1, 'two':2, 'three':3} >>> map(myhash.get, ['one', 'two', 'two']) [1, 2, 2] >>> or, to make it more similar to perl's qw() thing: >>> map(myhash.get, 'one two two'.split()) [1, 2, 2] >>> ...but I think that using explicit list is more pythonic. Isn't it? ;) -- Regards, Wojtek Walczak, http://tosh.pl/gminick/ From clay at lakeserv.net Sun Sep 21 13:14:30 2008 From: clay at lakeserv.net (Clay Hobbs) Date: Sun, 21 Sep 2008 13:14:30 -0400 Subject: Some questions about PyOpenGL and wxPython Message-ID: <1222017270.7824.3.camel@generator> I am making a program with wxPython that renders objects in 3D using PyOpenGL, and I am having some problems. For one thing, I forgot how to make a double-buffered hardware surface. For another thing, glColor(1.0, 0.0, 0.0) just before the rendering doesn't make the object red. Please help, I'm a total noob to OpenGL. From michele.petrazzo at TOGLIunipex.it Thu Sep 4 08:31:23 2008 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Thu, 04 Sep 2008 14:31:23 +0200 Subject: overwrite set behavior In-Reply-To: <mailman.468.1220522726.3487.python-list@python.org> References: <g9oat3$veh$1@nnrp-beta.newsland.it> <mailman.468.1220522726.3487.python-list@python.org> Message-ID: <g9oker$66v$1@nnrp-beta.newsland.it> Marco Bizzarri wrote: > looking at the source, maybe you could create a subclass of Set > redefining the __contains__ method? > Made some tries, but __contains__ are never called >>> class foo(set): ... def __contains__(self, value): ... print value ... >>> a = foo((1,2)) >>> Thanks, Michele From gagsl-py2 at yahoo.com.ar Thu Sep 18 17:10:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 18 Sep 2008 18:10:34 -0300 Subject: Deflate with urllib2... References: <173ba4ae-3375-4e62-9c0d-0645e7ab27ff@z11g2000prl.googlegroups.com> <mailman.766.1221033019.3487.python-list@python.org> <2b7cc4b6-dc19-4592-a80c-75bcd3707203@v13g2000pro.googlegroups.com> Message-ID: <op.uho3rwojx6zn5v@a98gizw.noga> En Tue, 16 Sep 2008 21:58:31 -0300, Sam <samslists at gmail.com> escribi?: > Gabriel, et al. > > It's hard to find a web site that uses deflate these days. > > Luckily, slashdot to the rescue. > > I even wrote a test script. > > If someone can tell me what's wrong that would be great. > > Here's what I get when I run it: > Data is compressed using deflate. Length is: 107160 > Traceback (most recent call last): > File "my_deflate_test.py", line 19, in <module> > data = zlib.decompress(data) > zlib.error: Error -3 while decompressing data: incorrect header check And that's true. The slashdot server is sending bogus data: py> s = socket.socket() py> s.connect(('slashdot.org',80)) py> s.sendall("GET / HTTP/1.1\r\nHost: slashdot.org\r\nAccept-Encoding: deflate\ r\n\r\n") py> s.recv(500) 'HTTP/1.1 200 OK\r\nDate: Thu, 18 Sep 2008 20:48:34 GMT\r\nServer: Apache/1.3.41 (Unix) mod_perl/1.31-rc4\r\nSLASH_LOG_DATA: shtml\r\nX-Powered-By: Slash 2.0050 01220\r\nX-Bender: Alright! Closure!\r\nCache-Control: private\r\nPragma: privat e\r\nConnection: close\r\nContent-Type: text/html; charset=iso-8859-1\r\nVary: A ccept-Encoding, User-Agent\r\nContent-Encoding: deflate\r\nTransfer-Encoding: ch unked\r\n\r\n1c76\r\n\x02\x00\x00\x00\xff\xff\x00\xc1\x0f>\xf0<!DOCTYPE HTML PUB LIC "-//W3C//DTD HTML 4.01//EN"\n "http://www.w3.org/TR/html4/str...' Note those 11 bytes starting with "\x02\x00\x00\xff..." followed by the page contents in plain text. According to RFC 2616 (HTTP 1.1), the deflate content coding consists of the "zlib" format defined in RFC 1950 in combination with the "deflate" compression mechanism described in RFC 1951. RFC 1950 says that the lower 4 bits of the first byte in a zlib stream represent the compression method; the only compression method defined is "deflate" with value 8. The slashdot data contains a 2 instead, so it is not valid. > #!/usr/bin/env python > > import urllib2 > import zlib > > opener = urllib2.build_opener() > opener.addheaders = [('Accept-encoding', 'deflate')] > > stream = opener.open('http://www.slashdot.org') > data = stream.read() > encoded = stream.headers.get('Content-Encoding') > > if encoded == 'deflate': > print "Data is compressed using deflate. Length is: ", > str(len(data)) > data = zlib.decompress(data) > print "After uncompressing, length is: ", str(len(data)) > else: > print "Data is not deflated." The code is correct - try with another server. I tested it with a LightHTTPd server and worked fine. -- Gabriel Genellina From paul.hankin at gmail.com Thu Sep 18 16:14:50 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 18 Sep 2008 13:14:50 -0700 (PDT) Subject: improving a huge double-for cycle References: <099d9b31-0c04-4e82-91d1-b3ac9c02f037@m3g2000hsc.googlegroups.com> Message-ID: <b71efff9-2a9c-4f14-a15d-e11c454ebdd8@x16g2000prn.googlegroups.com> On Sep 18, 2:25?pm, Alexzive <zasaconsult... at gmail.com> wrote: > Hello there :) , > > I am a python newbie and need to run following code for a task in an > external simulation programm called "Abaqus" which makes use of python > to access the mesh (ensamble of nodes with xy coordinates) of a > certain geometrical model. > > [IN is the starting input containing the nodes to be check, there are > some double nodes with the same x and y coordinates which need to be > removed. SN is the output containing such double nodes] > > Code: Select all > ? ? for i in range(len(IN)): #scan all elements of the list IN > ? ? ? for j in range(len(IN)): > ? ? ? ? if i <> j: > ? ? ? ? ?if IN[i].coordinates[0] == IN[j].coordinates[0]: > ? ? ? ? ? ?if IN[i].coordinates[1] == IN[j].coordinates[1]: > ? ? ? ? ? ? ? SN.append(IN[i].label) Using only a little extra storage to compute IN (but O(N log N) time complexity): import itertools IN.sort() SN = [k for k, v in itertools.groupby(IN) if len(list(v)) > 1] -- Paul Hankin From matiassurdi at gmail.com Mon Sep 15 15:04:04 2008 From: matiassurdi at gmail.com (Matias Surdi) Date: Mon, 15 Sep 2008 21:04:04 +0200 Subject: Converting .py files to batch files. In-Reply-To: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> References: <73045cca0809151030i7637cc73s7fe432598ed53448@mail.gmail.com> Message-ID: <gambf9$5vt$1@ger.gmane.org> aditya shukla escribi?: > How can we convert .py files to batch files? is there any library for this? > > > Aditya > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list Maybe py2exe can help you. From lily200802 at gmail.com Fri Sep 12 22:41:59 2008 From: lily200802 at gmail.com (lily200802 at gmail.com) Date: Fri, 12 Sep 2008 19:41:59 -0700 (PDT) Subject: Insider information, fackbook labs open today, we the first to register! Message-ID: <211adcf3-fb68-498b-8dec-5722d8534571@q26g2000prq.googlegroups.com> Insider information, fackbook labs open today, we the first to register! www.fackbooklabs.com From tjreedy at udel.edu Thu Sep 4 19:54:56 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 04 Sep 2008 19:54:56 -0400 Subject: why is self not passed to id()? In-Reply-To: <g9piha$gs9$1@aioe.org> References: <g9pg72$3vi$1@aioe.org> <mailman.502.1220560976.3487.python-list@python.org> <g9piha$gs9$1@aioe.org> Message-ID: <g9psgf$ll4$2@ger.gmane.org> Ruediger wrote: > I am aware that id is a built in function why shouldn't i use it? I consider this a sensible thing to have tried, but I an not too surprised it does not work because I am aware that built-in functions do not have all the features of Python function. I have asked about this case on Py-dev. Subject: Can/should built-in functions get __get__? > Replaceing lambda with id was intended as an performance hack. Profiling > proofed that lambda itself takes more than twice as much cpu time than id > alone. (profile shortened) > > 3610503 function calls in 22.451 CPU seconds > > Ordered by: standard name > > ncalls tottime percall cumtime percall filename:lineno(function) > > 960096 4.593 0.000 6.702 0.000 test14.py:33(<lambda>) > 1 0.003 0.003 22.451 22.451 {execfile} > 960096 2.109 0.000 2.109 0.000 {id} > > However using lambda seemed useless to me since id already took an argument > and wrapping it in an python function simply has no real purpose. Ironically, such simple wrappings are usually considered bad form. There *is* a third alternative, which works in this case, and which should be closer in speed to id. I will leave you to do a speed test. >>> class bang(list): __hash__ = object.__hash__ >>> s=set() >>> s.add(bang()) >>> s {[]} __eq__ = object.__eq__ should also work instead of the Python implementation I gave in my response to another response. Terry Jan Reedy From bruno.42.desthuilliers at websiteburo.invalid Thu Sep 4 04:23:43 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 04 Sep 2008 10:23:43 +0200 Subject: Late initialization using __getattribute__ In-Reply-To: <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> References: <2deb98fd-e1ec-4e31-8299-4d5bfb51066d@1g2000pre.googlegroups.com> <48beff32$0$10287$426a74cc@news.free.fr> <fea1d67d-1c74-4966-a198-2d174e6f7b7a@v13g2000pro.googlegroups.com> <48bf092a$0$14321$426a74cc@news.free.fr> <538e8aba-f552-4675-aa63-e20df7a56733@k36g2000pri.googlegroups.com> Message-ID: <48bf9aab$0$4598$426a74cc@news.free.fr> bukzor a ?crit : > On Sep 3, 1:02 pm, Bruno Desthuilliers > <bdesth.quelquech... at free.quelquepart.fr> wrote: >> bukzor a ?crit : >> (snip) >> >>> Thanks for the reply. Just to see it not work, I tried to remove >>> __getattribute__ from LateInitMixIn, but couldn't get it to work. >> ??? Sorry, I don't get what you mean... > > Since you said __getattribute__ is an attribute of the class, I tried > to run (something to the effect of) delattr(self.__class__, > "__getattribute__"), Ah, ok. Definitively *not* a thing to do... > but it threw an AttributeError. You'd have to call it on the mixin class itself, not on a subclass. > >>> My Base class is a C class (_mysql.connection from MySQLdb) that >>> sometimes segfaults if you try to use it before it's fully >>> initialized, >> >> ... I have used MySQLdb for years on more than a dozen linux >> distribs, and never had such a problem. Is this a known bug ? Or is >> there something wrong with your setup ? > > I'm trying to optimize my number of connections Connection pooling anyone ? IIRC, this is something that already exists in quite a couple libs / frameworks. Is there a reason you try to roll your own ? > by not fully > initializing (read: not connecting) my connection until it's used in > some way. Of course the maintainer didn't envision this (mis)use, so > the object sometimes throws bad errors until it's fully initialized. Ok. > Of course the *correct* way to do this is to be more careful about > when I create connections, but I think I should be able to get this to > work, and it (would be) much easier to do it The Right Way once it > works. Please pardon me for repeating the same thing over and over, but messing with __getattribute__ is certainly not the way to go. >>> so unfortunately I think I need to use __getattribute__ >>> to do this. I'm doing all this just to make the connection not >>> actually connect until used. >> I may be dumb, but I don't get how this is supposed to solve your >> problem. But anyway : there's a known design pattern for what you're >> trying to do, that doesn't require mixins nor messing with >> __getattribute__ (which, I repeat, is more often than not something you >> *don't* want to do). The name of the design pattern is "proxy". I >> strongly suggest that you 1/ try to cure the real problem instead of >> hacking around and 2/ read about the proxy design pattern. >> >> My 2 cents... > > I like the idea of mix-ins, but can't figure out how to make a proxy > work that way. You mean, "how to use a proxy for lazy initialization" ? Heck, that's the exact use case in the GoF. > For a long time I had a proxy class that added five or > six features on top of the MySQLdb package, but it wasn't configurable > enough, and I'm working on splitting each feature into its own MixIn > class. > > > As an aside, this is working for me pretty well. The "reconnect" > method (inheritied from a "Reconnectable" mixin) uses several of the > object's attributes, so I need to set _inited beforehand so that I > don't get into an infinite __getattribute__ loop. What I'd *really* > like to do is remove __getattribute__ from the object at that point. You can't. Or, more exactly, all you can do is remove __getattribute__ from the mixin class - but then the mixin class won't work anymore. I don't mean to be condescendant, but it looks like you don't have a clear understanding of Python's object model here - else you wouldn't even consider doing such a thing. FWIW, I posted a solution based on the __getattr__ hook, which did work - at least for the "specs" implied by your code snippet. From Scott.Daniels at Acm.Org Sat Sep 6 18:41:09 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 06 Sep 2008 15:41:09 -0700 Subject: String/Number Conversion In-Reply-To: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> References: <48c2f04e$0$20939$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <GumdnTnIzfeEmV7VnZ2dnUVZ_r_inZ2d@pdx.net> Andreas Hofmann wrote: > I've got some strings, which only contain numbers plus eventually one > character as si-postfix (k for kilo, m for mega, g for giga). I'm trying > to convert those strings to integers, with this function: Why bother to always switch the case if you only use a few values? Also, the Python style is to do an operation and handle failures, rather than test first. Try something like: _units = dict(K=1000, M=1000000, G=1000000000, k=1000, m=1000000, g=1000000000) def eliminate_postfix(value): try: return _units[value[-1]] * int(value[: -1]) except (TypeError, KeyError): return int(value) If you normally do not have the suffixes, then switch it around: def eliminate_postfix(value): try: return int(value) except ValueError: return _units[value[-1]] * int(value[: -1]) If this is really SI units, you likely are doing real measurements, so I'd consider using "float" instead of "int" in the above. --Scott David Daniels Scott.Daniels at Acm.Org From dblubaugh at belcan.com Sun Sep 21 18:42:10 2008 From: dblubaugh at belcan.com (Blubaugh, David A.) Date: Sun, 21 Sep 2008 18:42:10 -0400 Subject: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py References: <27CC3060AF71DA40A5DC85F7D5B70F3802840466@AWMAIL04.belcan.com><27CC3060AF71DA40A5DC85F7D5B70F38051C09EC@AWMAIL04.belcan.com><27CC3060AF71DA40A5DC85F7D5B70F38051C09ED@AWMAIL04.belcan.com><gb3bvk$9a1$1@ger.gmane.org><27CC3060AF71DA40A5DC85F7D5B70F38051C09F2@AWMAIL04.belcan.com> <op.uhucuzo8x6zn5v@a98gizw.noga> Message-ID: <27CC3060AF71DA40A5DC85F7D5B70F38051C09F3@AWMAIL04.belcan.com> Sir, Thank you for your reply. This is as to how I developed my .pyd file. I entered the following commands within my MS-DOS prompt within Windows XP: C:\python25\Scripts> C:\python25\python f2py.py -c --fcompiler=gnu95 --compiler=mingw32 -m hello hello.f90 I am using the gfortran compiler, that was prescribed to use, as well as, the required commands on the following website: http://www.scipy.org/F2PY_Window <https://webmail.belcan.com/exchweb/bin/redir.asp?URL=http://www.scipy.org/F2PY_Window> I comes down to that yes, I am able to generate a .pyd file, which was generated by f2py. However, when I tried to import this file into my python script program I was given the following error: error 193?? I do not know as to what I am doing incorrectly, since I am generating a .pyd file by f2py? If I am doing anything that is incorrect, then why am I EVEN ABLE TO GENERATE A .PYD FILE IN THE FIRST PLACE??? Any Help will be greatly appreciated!!!!! Thanks, David Blubaugh ________________________________ From: Gabriel Genellina [mailto:gagsl-py2 at yahoo.com.ar] Sent: Sun 9/21/2008 1:55 PM To: python-list at python.org Subject: Re: NEW GENERATED DLL ERROR FOUND WITHIN f2PY.py En Sat, 20 Sep 2008 16:07:12 -0300, Blubaugh, David A. <dblubaugh at belcan.com> escribi?: > Let me state that do have extensive experience with developing binary > files. Please note that I have followed all of the instructions to the > letter as far as developing a DLL to be imported. However, it is not > working correctly. I believe it might be my system environment > variables?? It might be the sunspots (or the lack of them) as well. You could start telling us what's your platform, which instructions have you followed, which compiler have you used... -- Gabriel Genellina This e-mail transmission contains information that is confidential and may be privileged. It is intended only for the addressee(s) named above. If you receive this e-mail in error, please do not read, copy or disseminate it in any manner. If you are not the intended recipient, any disclosure, copying, distribution or use of the contents of this information is prohibited. Please reply to the message immediately by informing the sender that the message was misdirected. After replying, please erase it from your computer system. Your assistance in correcting this error is appreciated. From castironpi at gmail.com Wed Sep 24 00:15:36 2008 From: castironpi at gmail.com (Aaron "Castironpi" Brady) Date: Tue, 23 Sep 2008 21:15:36 -0700 (PDT) Subject: How do I use python object in C++ References: <11fc5cde-464b-422b-a896-5dd003d03fd2@z11g2000prl.googlegroups.com> <fde4ed92-77ed-438e-a163-d5e248a80ee9@d45g2000hsc.googlegroups.com> <31ff7c8a-28f3-4c62-8ac5-6d0f90106c5d@a8g2000prf.googlegroups.com> <e2537230-c4ad-474a-913c-d0829286e699@k13g2000hse.googlegroups.com> Message-ID: <0fd3fd66-a4f5-4322-8823-722de1dfa952@c58g2000hsc.googlegroups.com> On Sep 23, 11:06?pm, "Aaron \"Castironpi\" Brady" <castiro... at gmail.com> wrote: > On Sep 23, 9:30?pm, lixinyi... at gmail.com wrote: > > > > > If the PyObject is a PyList, and all list items are strings, > > say a=['aaa','bbb','ccc'] > > > How can I have a > > myArray[0] = "aaa" > > myArray[1] = "bbb" > > myArray[2] = "ccc" > > in C++? > > > Do I have to > > use PyModule_GetDict() to get the dict first? > > what about the next? > > > > What do you know about the contents of 'argc' and 'argv'? ?If it's > > > impossible with Py_Main, can you use one of the other entry points? > > > > If you've never manipulated PyObject* objects in C, they can be > > > hairy. ?Even if you know 'a' is a sequence, its contents are still all > > > PyObject*s, which you can access via PyList_... and PySequence_ > > > functions. > > This one writes '[aaa, bbb, ccc]' to the console in two different > ways. > > #include <Python.h> > > int main() { > ? ? PyObject *list, *listrepr; > ? ? Py_Initialize(); > > ? ? /* first */ > ? ? list= PyList_New( 3 ); > ? ? PyList_SetItem( list, 0, PyString_FromString( "aaa" ) ); > ? ? PyList_SetItem( list, 1, PyString_FromString( "bbb" ) ); > ? ? PyList_SetItem( list, 2, PyString_FromString( "ccc" ) ); > > ? ? listrepr= PyObject_Repr( list ); > ? ? printf( "%s\n", PyString_AsString( listrepr ) ); > > ? ? Py_DECREF( listrepr ); > ? ? Py_DECREF( list ); > > ? ? /* second */ > ? ? list= Py_BuildValue( "[sss]", "aaa", "bbb", "ccc" ); > ? ? listrepr= PyObject_Repr( list ); > ? ? printf( "%s\n", PyString_AsString( listrepr ) ); > > ? ? Py_DECREF( listrepr ); > ? ? Py_DECREF( list ); > > ? ? Py_Finalize(); > ? ? return 0; > > } > > Did you want to execute some Python code, and examine variables it > creates? Here's a third way: PyObject *list, *listrepr, *dict, *result, *name; /* third */ dict= PyDict_New( ); result= PyRun_String( "myarray= [ 'ggg', 'hhh', 'iii' ]", Py_file_input, dict, NULL ); name= PyString_FromString( "myarray" ); list= PyDict_GetItem( dict, name ); listrepr= PyObject_Repr( list ); printf( "%s\n", PyString_AsString( listrepr ) ); Py_DECREF( dict ); Py_DECREF( result ); Py_DECREF( name ); Py_DECREF( listrepr ); Py_DECREF( list ); PyRun_String runs a namespace, 'dict', which holds the variables. From __peter__ at web.de Fri Sep 5 10:57:12 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 Sep 2008 16:57:12 +0200 Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> Message-ID: <g9rhc4$81p$01$1@news.t-online.com> Helmut Jarausch wrote: > I need to hash arrays of integers (from the hash module). > > So, I have to derive from array and supply a __hash__ method. > But how to hash an array (of fixed length, say 25)? > What I need is a function which maps a tuple of 25 integers > into 1 integer with good hashing properties. > > Does anybody know such a thing? Have you tried this already? def __hash__(self): return hash(self.tostring()) Peter From mail at microcorp.co.za Sat Sep 6 17:24:24 2008 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 6 Sep 2008 23:24:24 +0200 Subject: atomic section in code Message-ID: <005901c91086$208021a0$0d00a8c0@hendrik> Fredrik Lundh <fredr...ware.com> wrote: >sounds like he wants/needs non-cooperative, mandatory locking. Could one get there using ctypes to disable interrupts? Cross Platform? I can think of lots of hassles, starting with permissions to use the privileged instructions. - Hendrik From gagsl-py2 at yahoo.com.ar Fri Sep 19 10:15:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 11:15:55 -0300 Subject: Intercepting printed strings References: <496954360809181524g6037e0b0x84e98834bbf8ad9c@mail.gmail.com> <op.uhp1mu0ux6zn5v@gabriel2.softlabbsas.com.ar> <496954360809190637n8c12c6cvc177327aeb032ae4@mail.gmail.com> Message-ID: <op.uhqe8tpkx6zn5v@a98gizw.noga> En Fri, 19 Sep 2008 10:37:00 -0300, Robert Dailey <rcdailey at gmail.com> escribi?: > On Fri, Sep 19, 2008 at 4:21 AM, Gabriel Genellina > <gagsl-py2 at yahoo.com.ar>wrote: > >> En Thu, 18 Sep 2008 19:24:26 -0300, Robert Dailey <rcdailey at gmail.com> >> escribi?: >> >> >> I'm currently using Python 3.0 b3 and I'm curious as to how I can go >> about >>> intercepting things send to print() for some intermediate processing >>> before >>> they're actually sent to sys.stdout. Right now I've thought of the >>> following: >>> >>> Replace sys.stdout with a class named PrintStream. PrintStream is >>> defined >>> as >>> follows: >>> >>> class PrintStream: >>> def write( self, message ): >>> sys.__stdout__.write( '\t{0}'.format( message ) ) >>> >>> Will this work? Basically I want to add a tab character in front of >>> every >>> message printed. Thanks. >>> >> >> Why don't you try it yourself? >> You may replace builtins.print with your own function too. It's not >> exactly >> the same thing, but given your request "intercepting things send to >> print() >> before they're sent to sys.stdout" it may be more adequate. > > > I did try the code I posted and it doesn't work. Works for me: p3> class PrintStream: ... def write( self, message ): ... sys.__stdout__.write( '\t{0}'.format( message ) ) ... p3> sys.stdout = PrintStream() p3> print("Hello world!") Hello world! p3> print(1, 2, 3) 1 2 3 (note the double spacing between elements) You may want to replace the print() function instead (this was not so easy in previous versions): p3> sys.stdout = sys.__stdout__ p3> def _print(*args): # simplified print() signature ... sys.stdout.write('\t' + ' '.join(str(arg) for arg in args) + '\n') ... p3> import builtins p3> builtins.print = _print p3> print("Hello world!") Hello world! p3> print(1, 2, 3) 1 2 3 p3> -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Tue Sep 30 20:52:40 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Oct 2008 10:52:40 +1000 Subject: Python is slow? References: <f905b3c6-c9da-4b7e-b698-f2a5d97e6dc6@c58g2000hsc.googlegroups.com> <705010f0-2501-4a04-b2c2-5d8d49a711f9@25g2000hsx.googlegroups.com> <02918eb6-c2fb-4908-923f-d878a1956ee2@x35g2000hsb.googlegroups.com> <53052009-e103-47e3-bf9a-34f5585c3af3@k37g2000hsf.googlegroups.com> <9537590f-bc86-4fb7-813a-dbd72ac21616@f36g2000hsa.googlegroups.com> <gbr4ks$1vv$1@aioe.org> <gbs0l2$l4d$3@lust.ihug.co.nz> <pan.2008.09.30.08.52.11@REMOVE.THIS.cybersource.com.au> <87zllqqa1i.fsf@benfinney.id.au> <pan.2008.09.30.10.04.18@REMOVE.THIS.cybersource.com.au> <87prmlrfki.fsf@benfinney.id.au> <00f226c8$0$20617$c3e8da3@news.astraweb.com> <mailman.1766.1222798706.3487.python-list@python.org> <87hc7xqlnj.fsf@benfinney.id.au> <00f2b5d2$0$20617$c3e8da3@news.astraweb.com> Message-ID: <87d4ilqgpz.fsf@benfinney.id.au> Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> writes: > On Wed, 01 Oct 2008 09:06:08 +1000, Ben Finney wrote: > > > Note that I consider a work free even if it fails to grant ?the > > right to distribute misrepresentations of the author's words?, > > because that act is an exercise of undue power over another > > person, and so falls outside the limit imposed by the freedoms of > > others. > > But distributing modified source code *does* misrepresent the > author's words, because you confuse authorship. That's a possibility. There are other ways to avoid it than to restrict the freedom to redistribute; for example, some licenses state that modified works must clearly state who, when, and what was modified. I would not consider that a non-free restriction, since the freedom of the original distributor *and* the freedom of the redistributor is preserved. > If that is why the gnuplot people do not allow you to distribute > such modified documents, then the only "freedom" they fail to grant > is exactly the one you don't consider necessary for a free licence: > "the right to distribute misrepresentations of the author's words". We're going around in circles. I've already pointed out another freedom they fail to grant: the freedom to redistribute a modified work *as modified*. It's not equivalent to the act of misrepresentation. -- \ ?War is God's way of teaching geography to Americans.? ?Ambrose | `\ Bierce | _o__) | Ben Finney From M8R-yfto6h at mailinator.com Mon Sep 29 11:03:55 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Mon, 29 Sep 2008 08:03:55 -0700 Subject: Using re to find unicode ranges References: <mailman.1674.1222694261.3487.python-list@python.org> Message-ID: <Q8udnU3y8J_Bc33VnZ2dnUVZ_oqdnZ2d@comcast.com> "Eric Abrahamsen" <eric at ericabrahamsen.net> wrote in message news:mailman.1674.1222694261.3487.python-list at python.org... > Is it possible to use the re module to find runs of characters within a > certain Unicode range? > > I'm writing a Markdown extension to go over text and wrap blocks of > consecutive Chinese characters in <span class="char"></span> tags for > nice styling in an HTML page. The available hooks appear to be a pre- > processor (which is a "for line in lines" situation) or an inline pattern > (which uses regular expressions). The regular expression solution would > be much simpler and faster, but something tells me there's no way to use > a regex to find character ranges... Chinese characters appear to fall > between 19968 and 40959 using ord(), and I suppose I can go that route if > necessary, but I think it would be ugly. # coding: utf-8 import re sample = u'My name is ??. I am ???.' for n in re.findall(ur'[\u4e00-\u9fff]+',sample): print n output: ?? ??? --Mark From namekuseijin at gmail.com Tue Sep 30 00:03:07 2008 From: namekuseijin at gmail.com (namekuseijin) Date: Mon, 29 Sep 2008 21:03:07 -0700 (PDT) Subject: What is not objects in Python? References: <7e72409d-a9aa-44b5-a8dc-0201504d7870@m45g2000hsb.googlegroups.com> Message-ID: <f2d2bf0b-9362-47f5-84eb-411e09ab38e1@8g2000hse.googlegroups.com> On 28 set, 15:29, process <circularf... at gmail.com> wrote: > I have heard some criticism about Python, that it is not fully object- > oriented. So what? > Why isn't len implemented as a str.len and list.len method instead of > a len(list) function? Because postfix notation sucks. The natural way of spelling is adjective+noun and verb+predicate. That's one of the reasons I like Lisp better than Python. From gagsl-py2 at yahoo.com.ar Tue Sep 2 03:26:36 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 02 Sep 2008 04:26:36 -0300 Subject: Enhanced property decorator References: <9e36cdd4-7d66-4eae-aa60-1782e500abfe@34g2000hsh.googlegroups.com> Message-ID: <op.ugueymrlx6zn5v@a98gizw.cpe.telecentro.net.ar> En Mon, 25 Aug 2008 22:45:36 -0300, Daniel <millerdev at gmail.com> escribi?: > I've often been frustrated by the inability of the built-in property > descriptor to handle anything other than a read-only property when > used as a decorator. Furthermore, read/write/delete properties take > their doc-string and property definition at a non-intuitive and > awkward place (after the getter/setter/delter functions). The > following are three possible solutions to this problem (inspired by > message http://groups.google.com/group/comp.lang.python/msg/9a56da7ca8ceb7c7). > I don't like the solution in that thread because it uses apply() which > will go away in Python 3. > > Solution 1: new built-in function/descriptor > > def prop(func): > funcs = dict(enumerate(func())) > return property(funcs[0], funcs[1], funcs.get(2), func.__doc__) > > class Test(object): > @prop > def test(): > """test doc string""" > def fget(self): > return self._test > def fset(self, value): > self._test = value > def fdel(self): > del self._test > return fget, fset, fdel > > Of course the name (prop) could be changed... I couldn't think of > anything more concise. > > Pros: > (1) encapsulation of property logic inside function namespace, > preventing clutter in class namespace. > (2) doc string appears in a more natural place, before getter/setter/ > delter logic, as in classes and functions. > > Cons: > (1) additional built-in name. > (2) duplication/boilerplate in return line (DRY violation). (Some days late, sorry...) I like the variant below, based on your code. It avoids issue (2) by using locals(). Works with Python 3.0 too - and don't use tricks like sys._getframe or sys.settrace: def defproperty(func): impls = func() return property(doc=func.__doc__, **impls) class Test(object): @defproperty def test(): """test doc string""" def fget(self): return self._test def fset(self, value): self._test = value def fdel(self): del self._test return locals() -- Gabriel Genellina From tjreedy at udel.edu Sun Sep 28 03:55:46 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 Sep 2008 03:55:46 -0400 Subject: str() should convert ANY object to a string without EXCEPTIONS ! In-Reply-To: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> References: <9890864a-09f9-40d6-b2cc-5028e7a0c8c3@q26g2000prq.googlegroups.com> Message-ID: <gbnda2$7cq$1@ger.gmane.org> est wrote: >>From python manual > > str( [object]) > > Return a string containing a nicely printable representation of an > object. For strings, this returns the string itself. The difference > with repr(object) is that str(object) does not always attempt to > return a string that is acceptable to eval(); its goal is to return a > printable string. If no argument is given, returns the empty string, > ''. > > > now we try this under windows: > >>>> str(u'\ue863') > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in > position 0 > : ordinal not in range(128) In 3.0 this is fixed: >>> str('\ue863') # u prefix is gone '\ue863' >>> str(b'123') # b prefix is added "b'123'" Problems like this at least partly motivated the change to unicode instead of bytes as the string type. tjr From google at mrabarnett.plus.com Sun Sep 7 20:34:00 2008 From: google at mrabarnett.plus.com (MRAB) Date: Sun, 7 Sep 2008 17:34:00 -0700 (PDT) Subject: lacking follow-through References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> <mailman.666.1220826503.3487.python-list@python.org> Message-ID: <086a0906-c6f1-489c-91ab-f6a4f9e1ae3f@59g2000hsb.googlegroups.com> On Sep 7, 11:28?pm, "Eric Wertman" <ewert... at gmail.com> wrote: > +1 Bot I think it's like duck typing: it doesn't matter whether he's actually a bot, only whether he behaves like one. From gagsl-py2 at yahoo.com.ar Fri Sep 19 12:07:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 19 Sep 2008 13:07:02 -0300 Subject: generator exceptions References: <826a734c-968c-4d68-9ed1-c2688340ebc5@a3g2000prm.googlegroups.com> Message-ID: <op.uhqkd0bex6zn5v@a98gizw.noga> En Fri, 19 Sep 2008 10:40:00 -0300, Alexandru Mosoi <brtzsnr at gmail.com> escribi?: > i have a generator that raises an exception when calling next(), > however if I try to catch the exception and print the traceback i get > only the line where next() was called > > > while True: > try: > iterator.next() > except StopIteration: > break > except Exception, e: > traceback.print_exc() > > how do I get the traceback starting from where exception was raised in > first place? I get a complete traceback: py> import traceback py> py> def a(x): ... raise ValueError ... py> def b(x): ... return a(x) ... py> def c(n): ... for i in range(n): ... yield b(i) ... py> it = c(5) py> while True: ... try: ... it.next() ... except StopIteration: ... break ... except Exception: ... print traceback.print_exc() ... Traceback (most recent call last): File "<stdin>", line 3, in <module> File "<stdin>", line 3, in c File "<stdin>", line 2, in b File "<stdin>", line 2, in a ValueError None py> Could you provide a more complete example that fails? -- Gabriel Genellina From mnordhoff at mattnordhoff.com Fri Sep 12 15:57:17 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 12 Sep 2008 19:57:17 +0000 Subject: manipulating files within 'for' In-Reply-To: <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> References: <48CAA2AA.40809@umbc.edu> <gae9jj$sks$1@ger.gmane.org> <mailman.940.1221242051.3487.python-list@python.org> <7860991c-e893-46c7-902f-d99aca71f0b5@t54g2000hsg.googlegroups.com> Message-ID: <48CAC99D.3060603@mattnordhoff.com> bearophileHUGS at lycos.com wrote: > Ben Keshet: >> ...wrong. I thought I should omit the comma and didn't put it. I guess >> that stating the obvious should be the first attempt with beginners like >> me. Thanks for thinking about it (it's running perfect now). > > In CLisp, Scheme etc, lists such commas aren't necessary, but in > Python if you don't separate strings with a comma they become merged > into a single string: > >>>> 'foo', 'bar' > ('foo', 'bar') >>>> 'foo' 'bar' > 'foobar' > > Your mistake is caused by Python not following one of its general > rules: > > Explicit is better than implicit. > > In such case the string concatenation (+) is done implicitly. It's a > little handy feature once in a while (but not for me so far), while it > may cause bugs, so I don't like this little feature of Python and I > may like to see it removed, because it may bite you in similar > situations, where you forgot a comma for mistake: > > parts = ["foo", "bar" "baz"] > > Bye, > bearophile It's useful when wrapping a line. For lack of better lorem ipsum: whatever = some_function("Your mistake is caused by Python not " "following one of its general rules:\n\n" "Explicit is better than implicit.") You can also use backslashes, and probably even + if you want to, but the implicit concatenation is prettier (IMO, at least ;-). But you do have a point. I have never thought about the problems it could cause. BTW, I could easily be wrong, but I think C behaves the same way as Python. -- From deets at nospam.web.de Wed Sep 10 17:52:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 Sep 2008 23:52:00 +0200 Subject: emulating read and readline methods In-Reply-To: <ee4202f1-ce8f-458e-9627-08215351694d@e53g2000hsa.googlegroups.com> References: <ee4202f1-ce8f-458e-9627-08215351694d@e53g2000hsa.googlegroups.com> Message-ID: <6iqts0F3v76U1@mid.uni-berlin.de> Sean Davis schrieb: > I have a large file that I would like to transform and then feed to a > function (psycopg2 copy_from) that expects a file-like object (needs > read and readline methods). > > I have a class like so: > > class GeneInfo(): > def __init__(self): > #urllib.urlretrieve('ftp://ftp.ncbi.nih.gov/gene/DATA/ > gene_info.gz',"/tmp/gene_info.gz") > self.fh = gzip.open("/tmp/gene_info.gz") > self.fh.readline() #deal with header line > > def _read(self,n=1): > for line in self.fh: > if line=='': > break > line=line.strip() > line=re.sub("\t-","\t",line) > rowvals = line.split("\t") > yield "\t".join([rowvals[i] for i in > [0,1,2,3,6,7,8,9,10,11,12,14]]) + "\n" > > def readline(self,n=1): > return self._read().next() > > def read(self,n=1): > return self._read().next() > > def close(self): > self.fh.close() > > and I use it like so: > > a=GeneInfo() > cur.copy_from(a,"gene_info") > a.close() > > It works well except that the end of file is not caught by copy_from. > I get errors like: > > psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error > during .read() call > CONTEXT: COPY gene_info, line 1000: "" > > for a 1000 line test file. Any ideas what is going on? I'm a bit lost why the above actually works - as _read() appears to be re-created instead of re-used for each invocation, and thus can't work IMHO. Anyway, I think the real problem is that you don't follow the readline-protocol. it returns "" if there is no more line to read, instead you raise a StopIteration Diez From clp at rebertia.com Tue Sep 2 23:01:36 2008 From: clp at rebertia.com (Chris Rebert) Date: Tue, 2 Sep 2008 20:01:36 -0700 Subject: Py 2.6 changes In-Reply-To: <1bd15c2c-82e0-4742-a97f-ae16fb75ae26@m3g2000hsc.googlegroups.com> References: <1e2a91b1-fba6-43a8-a228-8c4b40320ee4@34g2000hsh.googlegroups.com> <00cc7976$0$20302$c3e8da3@news.astraweb.com> <fb60e830-1267-48c9-9b99-3352a1db64cc@i76g2000hsf.googlegroups.com> <1bd15c2c-82e0-4742-a97f-ae16fb75ae26@m3g2000hsc.googlegroups.com> Message-ID: <47c890dc0809022001w2dcaa008s88fd01592fa24140@mail.gmail.com> On Mon, Sep 1, 2008 at 6:02 PM, Mensanator <mensanator at aol.com> wrote: > On Sep 1, 6:55?pm, bearophileH... at lycos.com wrote: >> Steven D'Aprano: >> >> > productory() -- I don't know that function, and googling mostly comes up >> > with retail product searches. Do you mean product(), >> >> Darn my English, you are right, sorry, I meant a product() of >> course :-) > > But the name product() has already been taken by itertools to > mean Cartesian Product. We have this thing called "namespacing" and it's one honking great idea that's perfect for these situations. - Chris > >> >> Bye, >> bearophile > > -- > http://mail.python.org/mailman/listinfo/python-list -- Follow the path of the Iguana... http://rebertia.com From m_palmer45 at yahoo.ca Fri Sep 5 11:49:28 2008 From: m_palmer45 at yahoo.ca (Michael Palmer) Date: Fri, 5 Sep 2008 08:49:28 -0700 (PDT) Subject: hashing an array - howto References: <48c14472$0$2864$ba620e4c@news.skynet.be> <2f7ae5c8-9d95-45a1-8a12-d2b503ad88d1@k30g2000hse.googlegroups.com> Message-ID: <9dc8fc1b-9429-4077-bc65-650f73854ef7@e53g2000hsa.googlegroups.com> On Sep 5, 11:18 am, bearophileH... at lycos.com wrote: > Helmut Jarausch: > > > I need to hash arrays of integers (from the hash module). > > One of the possible solutions is to hash the equivalent tuple, but it > requires some memory (your sequence must not be tuples already): why can't it be tuple already? Doesn't matter: >>> from numpy import arange >>> a=arange(5) >>> a array([0, 1, 2, 3, 4]) >>> hash(a) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unhashable type >>> b=tuple(a) >>> b (0, 1, 2, 3, 4) >>> c=tuple(b) >>> c (0, 1, 2, 3, 4) >>> hash(c) 1286958229 you can discard the tuple, so the memory requirement is transient. From tjreedy at udel.edu Mon Sep 29 13:55:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 29 Sep 2008 13:55:10 -0400 Subject: writing dll in python? In-Reply-To: <gbqjh3+39e0@eGroups.com> References: <gbqjh3+39e0@eGroups.com> Message-ID: <gbr4pt$2li$1@ger.gmane.org> nishalrs wrote: > Hello All, > > My main motivation is to build a collection of useful mathematical > models (that I have developed over the years) to design ultrasonic > sensors. This should be some sort of a library that should be able to > be used for desktop/web application development, to run in variety of > operating systems. Interesting new applications of Python are welcome. Googling "Python package (or module) ultrasonic sensor" did not turn up anything relevant that I saw. > I am more than convinced after looking at python.org website, it is > the right tool for the job. I intend to learn python, but I am not > really sure, where to begin. Start with the Python tutorial, perhaps parts of the reference manual, and definitely peruse the first chapters in the library manual on built-in functions and classes. You will almost certainly want to use numpy (numpy.org) for numerical calculation and possibly existing modules in scipy (scipy.org) or elsewhere. > Should I write all the functions as simple python scripts? Or is there > some facility for creating a .dll like library, that could be more > suitable for what in intend to develop? A module is a 'script' that is intended to be imported by other Python code. In your Python installation directory, /Libs has numerous *.py examples. A 'package' is a collection of modules in a directory that includes only called __init__.py (if I remember correctly). Don't worry about details yet. When you have something worth distributing, you can get help here or on other lists, such as the one for numpy/scipy. When you are ready, you can announce it here and elsewhere and register it at the Python Package Index (pypi.python.org/pypi). Terry Jan Reedy From kannu.valli3 at gmail.com Sat Sep 20 01:30:56 2008 From: kannu.valli3 at gmail.com (kannu.valli3 at gmail.com) Date: Fri, 19 Sep 2008 22:30:56 -0700 (PDT) Subject: Enjoy seeing Enjoy seeingEnjoy seeingEnjoy seeing Enjoy seeing Message-ID: <fad1a0bf-3a38-4c27-a18b-f24b310fe669@v16g2000prc.googlegroups.com> Enjoy seeing with new video pictures http://nagaaraja.blogspots.com\ From gnewsg at gmail.com Thu Sep 11 12:40:59 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 11 Sep 2008 09:40:59 -0700 (PDT) Subject: Please help me finding a way to implement os.path.issubpath(a, b) Message-ID: <36cdd191-1681-4f15-9ab0-93fb786d38e1@d45g2000hsc.googlegroups.com> Hi, I'm trying to implement a function which returns whether a path is a subpath of another one (e.g. /a/b/c is a subpath of /a/b). I wrote this function which apparently seems to work fine: import os def issubpath(path1, path2): """Return True if path1 is a sub path of path2.""" if path1 == path2: return False x1 = path1.split(os.sep) x2 = path2.split(os.sep) return x1[:len(x2)] == x2 ...but if I use "issubpath('C:\\dir', 'C:\\')" it returns False. A little help would be appreciated. Thanks in advance. --- Giampaolo http://code.google.com/p/pyftpdlib/ From dudeja.rajat at gmail.com Tue Sep 2 09:32:30 2008 From: dudeja.rajat at gmail.com (dudeja.rajat at gmail.com) Date: Tue, 2 Sep 2008 14:32:30 +0100 Subject: What is module initialization? Message-ID: <e0b6c39a0809020632g678cc1e4vbcec509da9bc19f4@mail.gmail.com> Hi, I found on the net that there is something called module initialization. Unfortunately, there is not much information for this. However, small the information I found module initialization can be of use to me in my project. I'm currently messing with a problem where I'm keeping my global variables ( or symbols) in a module and the other mdoules in the project acess these global variables. However, there is one case when a module updates one such global variable but the variable is not getting updated in the module containing global symbols ( variables). This happen only at the start of the program and at rest of the places in the program that global variable is not accessed. So, I thought of using this module initialization where I will intialize the module only once to update that variable. Ans in the rest of the program where ever this module is imported I shall be able to easily access the update value of the variable. Could some one provide me a sample code of module intialization? And how can I ensure that module initialization is done only once? Thanks and regards, Rajat From skip at pobox.com Wed Sep 17 05:54:21 2008 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 Sep 2008 04:54:21 -0500 Subject: Python for the iPhone? Message-ID: <18640.54221.603481.301379@montanaro-dyndns-org.local> Anybody tried this port of Python to the iPhone? http://www.modmyi.com/nativeapps/python-v251/ http://iphone.natetrue.com/ Hasn't been updated since July 2007. Maybe just a proof-of-concept? I'm guessing it involves jailbreaking the phone. Skip From notvalid2 at sbcglobal.net Mon Sep 1 10:57:59 2008 From: notvalid2 at sbcglobal.net (W. eWatson) Date: Mon, 01 Sep 2008 07:57:59 -0700 Subject: How Compute # of Days between Two Dates? In-Reply-To: <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> References: <JAIuk.19687$cW3.19527@nlpi064.nbdc.sbc.com> <Jbidnadw_ZTYaibVnZ2dnUVZ_qjinZ2d@posted.visi> Message-ID: <VpTuk.38934$ZE5.3067@nlpi061.nbdc.sbc.com> Grant Edwards wrote: > On 2008-09-01, W. eWatson <notvalid2 at sbcglobal.net> wrote: > >> That's the question in Subject. For example, the difference between >> 08/29/2008 and 09/03/2008 is +5. The difference between 02/28/2008 and >> 03/03/2008 is 4, leap year--extra day in Feb. I'm really only interested in >> years between, say, 1990 and 2050. In other words not some really strange >> period of time well outside our current era of history. > > Does the standard library's datetime module not do what you want? > > http://docs.python.org/lib/module-datetime.html > Yes, it would seem so. This works fine. date1 = datetime.date(2007, 2, 27) date2 = datetime.date(2007, 3, 3) print "date1: ", date1 print "date2: ", date2 diff = date2 - date1 print "diff: ", diff result: date1: 2007-02-27 date2: 2007-03-03 diff: 4 days, 0:00:00 I was pondering this in pyfdate, but perhaps missed it or it was not obvious to me in the tutorial for some reason. There are few places where it's not quite complete. pyfdate has some rules for dealing with length of month oddities that started me thinking it would have difficulty with situations like the above. However, it would seem any general implementation of time and date should be capable of making similar calculations without difficulty. -- W. eWatson (121.015 Deg. W, 39.262 Deg. N) GMT-8 hr std. time) Obz Site: 39? 15' 7" N, 121? 2' 32" W, 2700 feet Web Page: <www.speckledwithstars.net/> From user at domain.invalid Wed Sep 17 12:02:15 2008 From: user at domain.invalid (Canned) Date: Wed, 17 Sep 2008 18:02:15 +0200 Subject: translating ascii to binary Message-ID: <48d12a01$0$27230$9a622dc7@news.kpnplanet.nl> Hi, I'm trying to write a class that can convert ascii to binary and vice versa. I write my class based on this function I've found on internet > def ascii_to_bin(char): > ascii = ord(char) > bin = [] > > while (ascii > 0): > if (ascii & 1) == 1: > bin.append("1") > else: > bin.append("0") > ascii = ascii >> 1 > > bin.reverse() > binary = "".join(bin) > zerofix = (8 - len(binary)) * '0' > > return zerofix + binary > > > > some_string = 'Time to go now, Rummy?' > > binary = [] > for char in some_string: > binary.append(ascii_to_bin(char)) > > print binary > print " ".join(binary) That works perfectly, but when I try to implement it in my own class it gives me alot of headache, also because I'm totally new to the language. It work only with one character at a time, and if I give a string it just give some weird result. > if len(sys.argv) < 2: > print 'usage:', os.path.basename(sys.argv[0]), 'text' > sys.exit() > > class Converterab: > ''' > Ascii-binary converter. > ''' > def __init__(self, string): > self.string = string > > def ascii_to_bin(self): > bindump = [] > for char in self.string: > bin = ord(char) > while bin > 0: > if (bin & 1) == 1: > bindump.append("1") > else: > bindump.append("0") > bin = bin >> 1 > bindump.reverse() > print bindump # Debug tool, delete this > > ''' > Zero fix in bindump > ''' > bindump.insert(0, "0") > count = 0 > pos = 0 > for dg in bindump: > count += 1 > pos += 1 > if count == 8: > bindump.insert(pos, "0") > count = 0 > bindump.pop() > print bindump # Debug tool, delete this, the best result so far > > ''' > Reversing array per byte > ''' > final = [] > pos -= pos # Set pos to 0 again > while len(bindump) != 0: > print count # Debug tool, delete this, this is weird, start at 1, I expected 0 > count += 1 > if count > 8: > pos += 8 > count -= count > final.insert(pos, bindump.pop()) > print final # Debug tool, delete this > ''' > for ar in bindump: > count += 1 > if (count < 8): > final.insert(pos, bindump.pop()) > elif (count >= 8): > pos = count > final.insert(pos, bindump.pop()) > else: > final.insert(pos, bindump.pop()) > ''' > final.insert(0, final.pop()) > > binary = "".join(final) > return binary > > result = Converterab(sys.argv[1]) > > print "Char : ", result.ascii_to_bin() The problem start at "Reversing array per byte". That block should reversing the array from 'bindump' and copy it to 'final' per 8 items, e.g. a = ['0', '1', '0', '1', '0', '1', '0', '1', '2', '1', '2', '1', '2', '1', '2', '1', '3', '2', '3', '2', '3', '2', '3', '2'] b = ['3', '2', '3', '2', '3', '2', '3', '2', '2', '1', '2', '1', '2', '1', '2', '1', '0', '1', '0', '1', '0', '1', '0', '1'] Any advice about this matter would be very appreciated. Thanks in advance. C From zentraders at gmail.com Tue Sep 2 11:38:31 2008 From: zentraders at gmail.com (Zentrader) Date: Tue, 2 Sep 2008 08:38:31 -0700 (PDT) Subject: (in memory) database References: <d1104d4c-b894-46ed-9641-fcbcdc3661d0@26g2000hsk.googlegroups.com> <mailman.297.1220190030.3487.python-list@python.org> <5enqo5-9n9.ln1@lairds.us> <b68940e4-78cc-4fbb-94cd-69478d45f96c@26g2000hsk.googlegroups.com> <k33ro5-lqh.ln1@lairds.us> <507b2e9e-147b-4f99-aeca-21c136bebfe3@s1g2000pra.googlegroups.com> <3e419475-61a1-4579-a8b6-fc15f9fe0a9b@m73g2000hsh.googlegroups.com> Message-ID: <f1312026-9450-483d-87e0-be9903f7f9e0@z11g2000prl.googlegroups.com> > I don't understand why Cameron has a different version of Python which > doesn't seem to have sqlite support enabled. Agreed, but won't the package manager tell him if python-sqlite is installed? That would be the next step since it appears that SQLite intself is already installed. Since Ubuntu uses precompied binaries, Python should be configured for SQLite which again leaves no python- sqlite as the only possibility (yeah right). BTW Python is easy to install manually. From ceball at users.sourceforge.net Fri Sep 12 09:32:18 2008 From: ceball at users.sourceforge.net (Chris) Date: Fri, 12 Sep 2008 13:32:18 +0000 (UTC) Subject: Accessing =?utf-8?b?X19zbG90c19f?= from C References: <mailman.793.1221057913.3487.python-list@python.org> <87k5diex3m.fsf@mulj.homelinux.net> <mailman.895.1221164133.3487.python-list@python.org> <87ej3p7ira.fsf@mulj.homelinux.net> Message-ID: <loom.20080912T122528-968@post.gmane.org> Hrvoje Niksic <hniksic <at> xemacs.org> writes: ... > Chris <ceball <at> users.sourceforge.net> writes: > > >> PyObject_GetAttrString is convenient, but it creates a Python string > >> only so it can intern it (and in most cases throw away the freshly > >> created version). For maximum efficiency, pre-create the string > >> object using PyString_InternFromString, and use that with > >> PyObject_GetAttr. > > > > Yes, we'd thought of that too, but it doesn't seem to be an > > important factor compared to the actual attribute lookup. > > I'd like to see your test code. Thanks for your interest in this. My test code is a whole function that's part of a big simulator, unfortunately! I need to use the data structures created by the simulator as part of the testing. While the source is freely available*, that doesn't make it easy for others to run the tests... > In my experience, as long as you're > accessing simple slots, you should notice a difference. (I'm not sure what you mean by a 'simple slot'. The slot we're accessing is a numpy array.) Sorry I wasn't clear before - we do notice a difference, but not as big a difference as when we access the attributes (arrays) from a pre-built list. Below are timings from running the simulator (i.e. calling the function in question many times) using the three approaches (GetAttrString, GetAttr, and instead using a list and GetItem; times outside parentheses are from a stopwatch; times in parentheses are from Python's cProfile module): - GetAttrString: 55 seconds (58 seconds) inside the loop: PyObject *weights_obj = PyObject_GetAttrString(obj,"attr_one"); - GetAttr: 46 seconds (46 seconds) outside the loop: PyObject *name = PyString_FromString("attr_one"); inside the loop: PyObject *obj = PyObject_GetAttr(obj,name); - PyList_GetItem: 35 seconds (37 seconds) So, of course, you are right to say that we should notice a difference! But speed is critical for us here. Incidentally, what we have is a simulator written entirely in Python, but we also provide optimized C versions of some parts of it. These C parts must be entirely optional. > Here is a test program that shows a 4.6 time speedup simply by > switching from PyObject_GetAttrString to PyObject_GetAttr: Thanks for the illustration. While I didn't run your code myself, I did try to study it. Illustrations like that are very helpful. Chris * from http://topographica.org/ From bignose+hates-spam at benfinney.id.au Fri Sep 26 22:33:28 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 27 Sep 2008 12:33:28 +1000 Subject: Are spams on comp.lang.python a major nuisance? References: <mailman.1533.1222428711.3487.python-list@python.org> <00ecf5e2$0$20666$c3e8da3@news.astraweb.com> <mailman.1549.1222447407.3487.python-list@python.org> <1621ddff-33b8-451f-8847-ed5cb630b4ea@a1g2000hsb.googlegroups.com> <48dd4756$0$25116$426a74cc@news.free.fr> <dZOdnQINKORUEUDVnZ2dnUVZ_rvinZ2d@posted.usinternet> <6e0eba80-0c7e-41c6-9389-fb6c8a06848f@m3g2000hsc.googlegroups.com> Message-ID: <87ej36uxl3.fsf@benfinney.id.au> George Sakkis <george.sakkis at gmail.com> writes: > On Sep 26, 9:30?pm, Grant Edwards <gra... at visi.com> wrote: > > I read the group via NNTP, and I find that blocking all articles > > posted from google.groups gets rid of all of the spam. > > ... along with a far from trivial (I guess) percentage of non-spam, > such as this post. As a Google user, you have (presumably) more clout with them than those of us who are not. Please pressure your provider to reduce the spam they output so the above drastic measure is not so attractive. Such pressure may be more effective if you *also* use an alternate NNTP provider that isn't such a spam-haven. -- \ ?I put contact lenses in my dog's eyes. They had little | `\ pictures of cats on them. Then I took one out and he ran around | _o__) in circles.? ?Steven Wright | Ben Finney From mail at timgolden.me.uk Wed Sep 17 04:17:30 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 17 Sep 2008 09:17:30 +0100 Subject: Modifying the system menu In-Reply-To: <bfa45e21-fb5e-454d-a4c2-e7cc00919f38@p31g2000prf.googlegroups.com> References: <bfa45e21-fb5e-454d-a4c2-e7cc00919f38@p31g2000prf.googlegroups.com> Message-ID: <48D0BD1A.2080700@timgolden.me.uk> raj.indian.08 at gmail.com wrote: > For (2) I wrote the following code for basic testing: > hwnd = win32gui.GetForegroundWindow() > hw = win32gui.GetSystemMenu(hwnd, False) > if hw != None: > win32gui.AppendMenu(hw,win32con.MF_SEPARATOR,0,'-'); > > and it shows the following error: pywintypes.error: (1401, > 'AppendMenu', 'Invalid menu handle.') Works for me. The following adds a separator and the string "Hello" to my (Console) window's system menu <code> import win32con import win32gui hwnd = win32gui.GetForegroundWindow () hmenu = win32gui.GetSystemMenu (hwnd, False) win32gui.AppendMenu (hmenu, win32con.MF_SEPARATOR, 0, '') win32gui.AppendMenu (hmenu, win32con.MF_STRING, 100, 'Hello') </code> TJG From bruno.42.desthuilliers at websiteburo.invalid Mon Sep 8 11:57:57 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 08 Sep 2008 17:57:57 +0200 Subject: Dictionaries and loops In-Reply-To: <069dc97f-9a6f-4adf-9667-c02a352836b3@b1g2000hsg.googlegroups.com> References: <bfd964a3-0162-47f9-8a9b-4d098a331af1@59g2000hsb.googlegroups.com> <48c52c54$0$16982$426a74cc@news.free.fr> <7f9db2b5-b76c-4f0e-bf6f-4e946f39b918@79g2000hsk.googlegroups.com> <48c53322$0$3460$426a74cc@news.free.fr> <069dc97f-9a6f-4adf-9667-c02a352836b3@b1g2000hsg.googlegroups.com> Message-ID: <48c54b07$0$18786$426a74cc@news.free.fr> Mike P a ?crit : > Thanks for the solution above, > > The raw data looked like > User-ID,COUNTS > 576460840144207854,6 > 576460821700280307,2 > 576460783848259584,1 > 576460809027715074,3 > 576460825909089607,1 > 576460817407934470,1 > > and i used > > CSV_INPUT1 = "C:/Example work/Attr_model/Activity_test.csv" > fin1 = open(CSV_INPUT1, "rb") > reader1 = csv.DictReader((fin1), [], delimiter=",") This should have been: reader1 = csv.DictReader(fin1, delimiter=",") or even just csv.DictReader(fin1), since IIRC ',' is the default delimiter (I'll let you check this by yourself...). with which you would have: [ {'User-ID':'576460840144207854', 'count':'6'}, {'User-ID':'576460821700280307', 'count':'2'}, # etc... ] > with the following outcome. > {None: ['User-ID', 'COUNTS']} > {None: ['576460840144207854', '6']} > {None: ['576460821700280307', '2']} > {None: ['576460783848259584', '1']} > {None: ['576460809027715074', '3']} > {None: ['576460825909089607', '1']} And you didn't noticed anything strange ??? > So i can see csv.reader is what i should have been using With only 2 values, DictReader is probably a bit overkill, yes. > Thanks for the help You're welcome. But do yourself a favour: take time to *learn* Python - at least the very basic (no pun) stuff like iterating over a sequence. From ewertman at gmail.com Sun Sep 7 18:28:11 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sun, 7 Sep 2008 18:28:11 -0400 Subject: lacking follow-through In-Reply-To: <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> References: <d1cd06a3-73ef-429e-87d3-e1f3727feeac@d77g2000hsb.googlegroups.com> <mailman.657.1220823307.3487.python-list@python.org> <6ij1ecFqp39rU4@mid.uni-berlin.de> <284bba5e-5e87-45c1-8bc4-f2c96eee7181@c58g2000hsc.googlegroups.com> Message-ID: <92da89760809071528u7323d5d8g3dde98ddf0d042b7@mail.gmail.com> +1 Bot From robin at alldunn.com Mon Sep 29 18:46:08 2008 From: robin at alldunn.com (Robin Dunn) Date: Mon, 29 Sep 2008 15:46:08 -0700 Subject: [wxpython-users] ANN: wxPython 2.8.9.0 In-Reply-To: <1222647042.29889.1.camel@generator> References: <48DFD492.1090905@alldunn.com> <1222647042.29889.1.camel@generator> Message-ID: <48E15AB0.4050909@alldunn.com> Clay Hobbs wrote: >> > > I'm curious, why do you package wxPython for Fedora 6 and 7, but not 8 > and 9? It's only because I haven't taken the time to update and retest those build boxes. -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython!